From 4fdcb4a406a6828c3e8fc1cee10fda58e9d9c454 Mon Sep 17 00:00:00 2001 From: Shanks0465 Date: Thu, 29 Aug 2024 02:34:24 +0530 Subject: [PATCH 1/3] Added Recorder Package --- node_modules/.bin/loose-envify | 1 + node_modules/.package-lock.json | 164 + .../@ffmpeg/ffmpeg/.gitpod.Dockerfile | 2 + node_modules/@ffmpeg/ffmpeg/.gitpod.yml | 7 + node_modules/@ffmpeg/ffmpeg/.yarnrc.yml | 4 + .../@ffmpeg/ffmpeg/CODE_OF_CONDUCT.md | 76 + node_modules/@ffmpeg/ffmpeg/CONTRIBUTING.md | 1 + node_modules/@ffmpeg/ffmpeg/LICENSE | 21 + node_modules/@ffmpeg/ffmpeg/README.md | 202 + node_modules/@ffmpeg/ffmpeg/_config.yml | 1 + .../ffmpeg/dist/046d0074eee1d99a674a.js | 1 + .../@ffmpeg/ffmpeg/dist/ffmpeg.min.js | 2 + .../@ffmpeg/ffmpeg/dist/ffmpeg.min.js.map | 1 + node_modules/@ffmpeg/ffmpeg/package.json | 73 + node_modules/@ffmpeg/ffmpeg/scripts/server.js | 25 + .../@ffmpeg/ffmpeg/scripts/test-helper.js | 9 + .../ffmpeg/scripts/webpack.config.common.js | 23 + .../ffmpeg/scripts/webpack.config.dev.js | 27 + .../ffmpeg/scripts/webpack.config.prod.js | 26 + .../scripts/webpack.config.worker.dev.js | 29 + .../scripts/webpack.config.worker.prod.js | 27 + .../@ffmpeg/ffmpeg/scripts/worker-server.js | 25 + .../ffmpeg/src/browser/defaultOptions.js | 10 + .../@ffmpeg/ffmpeg/src/browser/fetchFile.js | 38 + .../ffmpeg/src/browser/getCreateFFmpegCore.js | 114 + .../@ffmpeg/ffmpeg/src/browser/index.js | 5 + node_modules/@ffmpeg/ffmpeg/src/config.js | 50 + .../@ffmpeg/ffmpeg/src/createFFmpeg.js | 279 + node_modules/@ffmpeg/ffmpeg/src/index.d.ts | 120 + node_modules/@ffmpeg/ffmpeg/src/index.js | 36 + .../@ffmpeg/ffmpeg/src/node/defaultOptions.js | 6 + .../@ffmpeg/ffmpeg/src/node/fetchFile.js | 33 + .../ffmpeg/src/node/getCreateFFmpegCore.js | 7 + node_modules/@ffmpeg/ffmpeg/src/node/index.js | 9 + .../@ffmpeg/ffmpeg/src/utils/errors.js | 11 + node_modules/@ffmpeg/ffmpeg/src/utils/log.js | 24 + .../@ffmpeg/ffmpeg/src/utils/parseArgs.js | 10 + node_modules/is-url/.travis.yml | 3 + node_modules/is-url/History.md | 25 + node_modules/is-url/LICENSE-MIT | 19 + node_modules/is-url/Readme.md | 19 + node_modules/is-url/index.js | 47 + node_modules/is-url/package.json | 13 + node_modules/is-url/test/index.js | 149 + node_modules/js-tokens/CHANGELOG.md | 151 + node_modules/js-tokens/LICENSE | 21 + node_modules/js-tokens/README.md | 240 + node_modules/js-tokens/index.js | 23 + node_modules/js-tokens/package.json | 30 + node_modules/loose-envify/LICENSE | 21 + node_modules/loose-envify/README.md | 45 + node_modules/loose-envify/cli.js | 16 + node_modules/loose-envify/custom.js | 4 + node_modules/loose-envify/index.js | 3 + node_modules/loose-envify/loose-envify.js | 36 + node_modules/loose-envify/package.json | 36 + node_modules/loose-envify/replace.js | 65 + node_modules/node-fetch/LICENSE.md | 22 + node_modules/node-fetch/README.md | 634 + node_modules/node-fetch/browser.js | 25 + node_modules/node-fetch/lib/index.es.js | 1777 + node_modules/node-fetch/lib/index.js | 1787 + node_modules/node-fetch/lib/index.mjs | 1775 + node_modules/node-fetch/package.json | 89 + node_modules/react-audio-visualize/LICENSE | 21 + node_modules/react-audio-visualize/README.md | 101 + .../dist/AudioVisualizer/AudioVisualizer.d.ts | 50 + .../dist/AudioVisualizer/index.d.ts | 1 + .../dist/AudioVisualizer/types.d.ts | 4 + .../dist/AudioVisualizer/utils.d.ts | 3 + .../LiveAudioVisualizer.d.ts | 60 + .../dist/LiveAudioVisualizer/index.d.ts | 1 + .../dist/LiveAudioVisualizer/utils.d.ts | 2 + .../react-audio-visualize/dist/index.d.ts | 2 + .../dist/react-audio-visualize.es.js | 828 + .../dist/react-audio-visualize.umd.js | 27 + .../react-audio-visualize/package.json | 72 + .../react-audio-voice-recorder/README.md | 152 + .../components/AudioRecordingComponent.d.ts | 18 + .../dist/components/interfaces.d.ts | 80 + .../dist/hooks/useAudioRecorder.d.ts | 28 + .../dist/index-1c988149.js | 802 + .../dist/index.d.ts | 2 + .../dist/react-audio-visualize.es-69216c73.js | 828 + .../dist/react-audio-voice-recorder.es.js | 817 + .../dist/vite-env.d.ts | 1 + .../react-audio-voice-recorder/package.json | 102 + node_modules/react-dom/LICENSE | 21 + node_modules/react-dom/README.md | 60 + ...t-dom-server-legacy.browser.development.js | 7029 ++++ ...om-server-legacy.browser.production.min.js | 93 + ...eact-dom-server-legacy.node.development.js | 7093 ++++ ...t-dom-server-legacy.node.production.min.js | 101 + .../react-dom-server.browser.development.js | 7014 ++++ ...react-dom-server.browser.production.min.js | 96 + .../cjs/react-dom-server.node.development.js | 7070 ++++ .../react-dom-server.node.production.min.js | 102 + .../cjs/react-dom-test-utils.development.js | 1763 + .../react-dom-test-utils.production.min.js | 40 + .../react-dom/cjs/react-dom.development.js | 29923 +++++++++++++++ .../react-dom/cjs/react-dom.production.min.js | 322 + .../react-dom/cjs/react-dom.profiling.min.js | 366 + node_modules/react-dom/client.js | 25 + node_modules/react-dom/index.js | 38 + node_modules/react-dom/package.json | 62 + node_modules/react-dom/profiling.js | 38 + node_modules/react-dom/server.browser.js | 17 + node_modules/react-dom/server.js | 3 + node_modules/react-dom/server.node.js | 17 + node_modules/react-dom/test-utils.js | 7 + ...t-dom-server-legacy.browser.development.js | 7026 ++++ ...om-server-legacy.browser.production.min.js | 75 + .../react-dom-server.browser.development.js | 7011 ++++ ...react-dom-server.browser.production.min.js | 76 + .../umd/react-dom-test-utils.development.js | 1759 + .../react-dom-test-utils.production.min.js | 33 + .../react-dom/umd/react-dom.development.js | 29924 ++++++++++++++++ .../react-dom/umd/react-dom.production.min.js | 267 + .../react-dom/umd/react-dom.profiling.min.js | 285 + node_modules/react/LICENSE | 21 + node_modules/react/README.md | 37 + .../cjs/react-jsx-dev-runtime.development.js | 1315 + .../react-jsx-dev-runtime.production.min.js | 10 + .../react-jsx-dev-runtime.profiling.min.js | 10 + .../cjs/react-jsx-runtime.development.js | 1333 + .../cjs/react-jsx-runtime.production.min.js | 11 + .../cjs/react-jsx-runtime.profiling.min.js | 11 + node_modules/react/cjs/react.development.js | 2740 ++ .../react/cjs/react.production.min.js | 26 + .../cjs/react.shared-subset.development.js | 20 + .../cjs/react.shared-subset.production.min.js | 10 + node_modules/react/index.js | 7 + node_modules/react/jsx-dev-runtime.js | 7 + node_modules/react/jsx-runtime.js | 7 + node_modules/react/package.json | 47 + node_modules/react/react.shared-subset.js | 7 + node_modules/react/umd/react.development.js | 3343 ++ .../react/umd/react.production.min.js | 31 + node_modules/react/umd/react.profiling.min.js | 31 + node_modules/regenerator-runtime/LICENSE | 21 + node_modules/regenerator-runtime/README.md | 31 + node_modules/regenerator-runtime/package.json | 19 + node_modules/regenerator-runtime/path.js | 11 + node_modules/regenerator-runtime/runtime.js | 761 + node_modules/resolve-url/.jshintrc | 44 + node_modules/resolve-url/LICENSE | 21 + node_modules/resolve-url/bower.json | 15 + node_modules/resolve-url/changelog.md | 15 + node_modules/resolve-url/component.json | 15 + node_modules/resolve-url/package.json | 34 + node_modules/resolve-url/readme.md | 83 + node_modules/resolve-url/resolve-url.js | 47 + node_modules/resolve-url/test/resolve-url.js | 70 + node_modules/scheduler/LICENSE | 21 + node_modules/scheduler/README.md | 9 + .../scheduler-unstable_mock.development.js | 700 + .../scheduler-unstable_mock.production.min.js | 20 + ...cheduler-unstable_post_task.development.js | 207 + ...duler-unstable_post_task.production.min.js | 14 + .../scheduler/cjs/scheduler.development.js | 634 + .../scheduler/cjs/scheduler.production.min.js | 19 + node_modules/scheduler/index.js | 7 + node_modules/scheduler/package.json | 36 + .../scheduler-unstable_mock.development.js | 699 + .../scheduler-unstable_mock.production.min.js | 19 + .../scheduler/umd/scheduler.development.js | 152 + .../scheduler/umd/scheduler.production.min.js | 146 + .../scheduler/umd/scheduler.profiling.min.js | 146 + node_modules/scheduler/unstable_mock.js | 7 + node_modules/scheduler/unstable_post_task.js | 7 + node_modules/tr46/.npmignore | 4 + node_modules/tr46/index.js | 193 + node_modules/tr46/lib/.gitkeep | 0 node_modules/tr46/lib/mappingTable.json | 1 + node_modules/tr46/package.json | 31 + node_modules/webidl-conversions/LICENSE.md | 12 + node_modules/webidl-conversions/README.md | 53 + node_modules/webidl-conversions/lib/index.js | 189 + node_modules/webidl-conversions/package.json | 23 + node_modules/whatwg-url/LICENSE.txt | 21 + node_modules/whatwg-url/README.md | 67 + node_modules/whatwg-url/lib/URL-impl.js | 200 + node_modules/whatwg-url/lib/URL.js | 196 + node_modules/whatwg-url/lib/public-api.js | 11 + .../whatwg-url/lib/url-state-machine.js | 1297 + node_modules/whatwg-url/lib/utils.js | 20 + node_modules/whatwg-url/package.json | 32 + package-lock.json | 169 + package.json | 5 + 189 files changed, 135910 insertions(+) create mode 120000 node_modules/.bin/loose-envify create mode 100644 node_modules/.package-lock.json create mode 100644 node_modules/@ffmpeg/ffmpeg/.gitpod.Dockerfile create mode 100644 node_modules/@ffmpeg/ffmpeg/.gitpod.yml create mode 100644 node_modules/@ffmpeg/ffmpeg/.yarnrc.yml create mode 100644 node_modules/@ffmpeg/ffmpeg/CODE_OF_CONDUCT.md create mode 100644 node_modules/@ffmpeg/ffmpeg/CONTRIBUTING.md create mode 100644 node_modules/@ffmpeg/ffmpeg/LICENSE create mode 100644 node_modules/@ffmpeg/ffmpeg/README.md create mode 100644 node_modules/@ffmpeg/ffmpeg/_config.yml create mode 100644 node_modules/@ffmpeg/ffmpeg/dist/046d0074eee1d99a674a.js create mode 100644 node_modules/@ffmpeg/ffmpeg/dist/ffmpeg.min.js create mode 100644 node_modules/@ffmpeg/ffmpeg/dist/ffmpeg.min.js.map create mode 100644 node_modules/@ffmpeg/ffmpeg/package.json create mode 100644 node_modules/@ffmpeg/ffmpeg/scripts/server.js create mode 100644 node_modules/@ffmpeg/ffmpeg/scripts/test-helper.js create mode 100644 node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.common.js create mode 100644 node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.dev.js create mode 100644 node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.prod.js create mode 100644 node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.worker.dev.js create mode 100644 node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.worker.prod.js create mode 100644 node_modules/@ffmpeg/ffmpeg/scripts/worker-server.js create mode 100644 node_modules/@ffmpeg/ffmpeg/src/browser/defaultOptions.js create mode 100644 node_modules/@ffmpeg/ffmpeg/src/browser/fetchFile.js create mode 100644 node_modules/@ffmpeg/ffmpeg/src/browser/getCreateFFmpegCore.js create mode 100644 node_modules/@ffmpeg/ffmpeg/src/browser/index.js create mode 100644 node_modules/@ffmpeg/ffmpeg/src/config.js create mode 100644 node_modules/@ffmpeg/ffmpeg/src/createFFmpeg.js create mode 100644 node_modules/@ffmpeg/ffmpeg/src/index.d.ts create mode 100644 node_modules/@ffmpeg/ffmpeg/src/index.js create mode 100644 node_modules/@ffmpeg/ffmpeg/src/node/defaultOptions.js create mode 100644 node_modules/@ffmpeg/ffmpeg/src/node/fetchFile.js create mode 100644 node_modules/@ffmpeg/ffmpeg/src/node/getCreateFFmpegCore.js create mode 100644 node_modules/@ffmpeg/ffmpeg/src/node/index.js create mode 100644 node_modules/@ffmpeg/ffmpeg/src/utils/errors.js create mode 100644 node_modules/@ffmpeg/ffmpeg/src/utils/log.js create mode 100644 node_modules/@ffmpeg/ffmpeg/src/utils/parseArgs.js create mode 100644 node_modules/is-url/.travis.yml create mode 100644 node_modules/is-url/History.md create mode 100644 node_modules/is-url/LICENSE-MIT create mode 100644 node_modules/is-url/Readme.md create mode 100644 node_modules/is-url/index.js create mode 100644 node_modules/is-url/package.json create mode 100644 node_modules/is-url/test/index.js create mode 100644 node_modules/js-tokens/CHANGELOG.md create mode 100644 node_modules/js-tokens/LICENSE create mode 100644 node_modules/js-tokens/README.md create mode 100644 node_modules/js-tokens/index.js create mode 100644 node_modules/js-tokens/package.json create mode 100644 node_modules/loose-envify/LICENSE create mode 100644 node_modules/loose-envify/README.md create mode 100755 node_modules/loose-envify/cli.js create mode 100644 node_modules/loose-envify/custom.js create mode 100644 node_modules/loose-envify/index.js create mode 100644 node_modules/loose-envify/loose-envify.js create mode 100644 node_modules/loose-envify/package.json create mode 100644 node_modules/loose-envify/replace.js 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/browser.js create mode 100644 node_modules/node-fetch/lib/index.es.js create mode 100644 node_modules/node-fetch/lib/index.js create mode 100644 node_modules/node-fetch/lib/index.mjs create mode 100644 node_modules/node-fetch/package.json create mode 100644 node_modules/react-audio-visualize/LICENSE create mode 100644 node_modules/react-audio-visualize/README.md create mode 100644 node_modules/react-audio-visualize/dist/AudioVisualizer/AudioVisualizer.d.ts create mode 100644 node_modules/react-audio-visualize/dist/AudioVisualizer/index.d.ts create mode 100644 node_modules/react-audio-visualize/dist/AudioVisualizer/types.d.ts create mode 100644 node_modules/react-audio-visualize/dist/AudioVisualizer/utils.d.ts create mode 100644 node_modules/react-audio-visualize/dist/LiveAudioVisualizer/LiveAudioVisualizer.d.ts create mode 100644 node_modules/react-audio-visualize/dist/LiveAudioVisualizer/index.d.ts create mode 100644 node_modules/react-audio-visualize/dist/LiveAudioVisualizer/utils.d.ts create mode 100644 node_modules/react-audio-visualize/dist/index.d.ts create mode 100644 node_modules/react-audio-visualize/dist/react-audio-visualize.es.js create mode 100644 node_modules/react-audio-visualize/dist/react-audio-visualize.umd.js create mode 100644 node_modules/react-audio-visualize/package.json create mode 100644 node_modules/react-audio-voice-recorder/README.md create mode 100644 node_modules/react-audio-voice-recorder/dist/components/AudioRecordingComponent.d.ts create mode 100644 node_modules/react-audio-voice-recorder/dist/components/interfaces.d.ts create mode 100644 node_modules/react-audio-voice-recorder/dist/hooks/useAudioRecorder.d.ts create mode 100644 node_modules/react-audio-voice-recorder/dist/index-1c988149.js create mode 100644 node_modules/react-audio-voice-recorder/dist/index.d.ts create mode 100644 node_modules/react-audio-voice-recorder/dist/react-audio-visualize.es-69216c73.js create mode 100644 node_modules/react-audio-voice-recorder/dist/react-audio-voice-recorder.es.js create mode 100644 node_modules/react-audio-voice-recorder/dist/vite-env.d.ts create mode 100644 node_modules/react-audio-voice-recorder/package.json create mode 100644 node_modules/react-dom/LICENSE create mode 100644 node_modules/react-dom/README.md create mode 100644 node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js create mode 100644 node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js create mode 100644 node_modules/react-dom/cjs/react-dom-server-legacy.node.development.js create mode 100644 node_modules/react-dom/cjs/react-dom-server-legacy.node.production.min.js create mode 100644 node_modules/react-dom/cjs/react-dom-server.browser.development.js create mode 100644 node_modules/react-dom/cjs/react-dom-server.browser.production.min.js create mode 100644 node_modules/react-dom/cjs/react-dom-server.node.development.js create mode 100644 node_modules/react-dom/cjs/react-dom-server.node.production.min.js create mode 100644 node_modules/react-dom/cjs/react-dom-test-utils.development.js create mode 100644 node_modules/react-dom/cjs/react-dom-test-utils.production.min.js create mode 100644 node_modules/react-dom/cjs/react-dom.development.js create mode 100644 node_modules/react-dom/cjs/react-dom.production.min.js create mode 100644 node_modules/react-dom/cjs/react-dom.profiling.min.js create mode 100644 node_modules/react-dom/client.js create mode 100644 node_modules/react-dom/index.js create mode 100644 node_modules/react-dom/package.json create mode 100644 node_modules/react-dom/profiling.js create mode 100644 node_modules/react-dom/server.browser.js create mode 100644 node_modules/react-dom/server.js create mode 100644 node_modules/react-dom/server.node.js create mode 100644 node_modules/react-dom/test-utils.js create mode 100644 node_modules/react-dom/umd/react-dom-server-legacy.browser.development.js create mode 100644 node_modules/react-dom/umd/react-dom-server-legacy.browser.production.min.js create mode 100644 node_modules/react-dom/umd/react-dom-server.browser.development.js create mode 100644 node_modules/react-dom/umd/react-dom-server.browser.production.min.js create mode 100644 node_modules/react-dom/umd/react-dom-test-utils.development.js create mode 100644 node_modules/react-dom/umd/react-dom-test-utils.production.min.js create mode 100644 node_modules/react-dom/umd/react-dom.development.js create mode 100644 node_modules/react-dom/umd/react-dom.production.min.js create mode 100644 node_modules/react-dom/umd/react-dom.profiling.min.js create mode 100644 node_modules/react/LICENSE create mode 100644 node_modules/react/README.md create mode 100644 node_modules/react/cjs/react-jsx-dev-runtime.development.js create mode 100644 node_modules/react/cjs/react-jsx-dev-runtime.production.min.js create mode 100644 node_modules/react/cjs/react-jsx-dev-runtime.profiling.min.js create mode 100644 node_modules/react/cjs/react-jsx-runtime.development.js create mode 100644 node_modules/react/cjs/react-jsx-runtime.production.min.js create mode 100644 node_modules/react/cjs/react-jsx-runtime.profiling.min.js create mode 100644 node_modules/react/cjs/react.development.js create mode 100644 node_modules/react/cjs/react.production.min.js create mode 100644 node_modules/react/cjs/react.shared-subset.development.js create mode 100644 node_modules/react/cjs/react.shared-subset.production.min.js create mode 100644 node_modules/react/index.js create mode 100644 node_modules/react/jsx-dev-runtime.js create mode 100644 node_modules/react/jsx-runtime.js create mode 100644 node_modules/react/package.json create mode 100644 node_modules/react/react.shared-subset.js create mode 100644 node_modules/react/umd/react.development.js create mode 100644 node_modules/react/umd/react.production.min.js create mode 100644 node_modules/react/umd/react.profiling.min.js create mode 100644 node_modules/regenerator-runtime/LICENSE create mode 100644 node_modules/regenerator-runtime/README.md create mode 100644 node_modules/regenerator-runtime/package.json create mode 100644 node_modules/regenerator-runtime/path.js create mode 100644 node_modules/regenerator-runtime/runtime.js create mode 100644 node_modules/resolve-url/.jshintrc create mode 100644 node_modules/resolve-url/LICENSE create mode 100644 node_modules/resolve-url/bower.json create mode 100644 node_modules/resolve-url/changelog.md create mode 100644 node_modules/resolve-url/component.json create mode 100644 node_modules/resolve-url/package.json create mode 100644 node_modules/resolve-url/readme.md create mode 100644 node_modules/resolve-url/resolve-url.js create mode 100644 node_modules/resolve-url/test/resolve-url.js create mode 100644 node_modules/scheduler/LICENSE create mode 100644 node_modules/scheduler/README.md create mode 100644 node_modules/scheduler/cjs/scheduler-unstable_mock.development.js create mode 100644 node_modules/scheduler/cjs/scheduler-unstable_mock.production.min.js create mode 100644 node_modules/scheduler/cjs/scheduler-unstable_post_task.development.js create mode 100644 node_modules/scheduler/cjs/scheduler-unstable_post_task.production.min.js create mode 100644 node_modules/scheduler/cjs/scheduler.development.js create mode 100644 node_modules/scheduler/cjs/scheduler.production.min.js create mode 100644 node_modules/scheduler/index.js create mode 100644 node_modules/scheduler/package.json create mode 100644 node_modules/scheduler/umd/scheduler-unstable_mock.development.js create mode 100644 node_modules/scheduler/umd/scheduler-unstable_mock.production.min.js create mode 100644 node_modules/scheduler/umd/scheduler.development.js create mode 100644 node_modules/scheduler/umd/scheduler.production.min.js create mode 100644 node_modules/scheduler/umd/scheduler.profiling.min.js create mode 100644 node_modules/scheduler/unstable_mock.js create mode 100644 node_modules/scheduler/unstable_post_task.js create mode 100644 node_modules/tr46/.npmignore create mode 100644 node_modules/tr46/index.js create mode 100644 node_modules/tr46/lib/.gitkeep create mode 100644 node_modules/tr46/lib/mappingTable.json create mode 100644 node_modules/tr46/package.json create mode 100644 node_modules/webidl-conversions/LICENSE.md create mode 100644 node_modules/webidl-conversions/README.md create mode 100644 node_modules/webidl-conversions/lib/index.js create mode 100644 node_modules/webidl-conversions/package.json create mode 100644 node_modules/whatwg-url/LICENSE.txt create mode 100644 node_modules/whatwg-url/README.md create mode 100644 node_modules/whatwg-url/lib/URL-impl.js create mode 100644 node_modules/whatwg-url/lib/URL.js create mode 100644 node_modules/whatwg-url/lib/public-api.js create mode 100644 node_modules/whatwg-url/lib/url-state-machine.js create mode 100644 node_modules/whatwg-url/lib/utils.js create mode 100644 node_modules/whatwg-url/package.json create mode 100644 package-lock.json create mode 100644 package.json diff --git a/node_modules/.bin/loose-envify b/node_modules/.bin/loose-envify new file mode 120000 index 0000000..ed9009c --- /dev/null +++ b/node_modules/.bin/loose-envify @@ -0,0 +1 @@ +../loose-envify/cli.js \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..5fb6b5a --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,164 @@ +{ + "name": "ai4b-website", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@ffmpeg/ffmpeg": { + "version": "0.11.6", + "resolved": "https://registry.npmjs.org/@ffmpeg/ffmpeg/-/ffmpeg-0.11.6.tgz", + "integrity": "sha512-uN8J8KDjADEavPhNva6tYO9Fj0lWs9z82swF3YXnTxWMBoFLGq3LZ6FLlIldRKEzhOBKnkVfA8UnFJuvGvNxcA==", + "license": "MIT", + "dependencies": { + "is-url": "^1.2.4", + "node-fetch": "^2.6.1", + "regenerator-runtime": "^0.13.7", + "resolve-url": "^0.2.1" + }, + "engines": { + "node": ">=12.16.1" + } + }, + "node_modules/is-url": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/is-url/-/is-url-1.2.4.tgz", + "integrity": "sha512-ITvGim8FhRiYe4IQ5uHSkj7pVaPDrCTkNd3yq3cV7iZAcJdHTUMPMEHcqSOy9xZ9qFenQCvi+2wjH9a1nXqHww==", + "license": "MIT" + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT", + "peer": true + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "peer": true, + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/react": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-audio-visualize": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/react-audio-visualize/-/react-audio-visualize-1.1.3.tgz", + "integrity": "sha512-gvKcmyfJP6XQrzCJeEK4z/lBL/qijqWD6JArZBfaaf5ZxEQPMfQhTipG0LJIUcBYxzVO1rvIhj4ex+/5MRYTFA==", + "license": "MIT", + "peerDependencies": { + "react": ">=16.2.0", + "react-dom": ">=16.2.0" + } + }, + "node_modules/react-audio-voice-recorder": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/react-audio-voice-recorder/-/react-audio-voice-recorder-2.2.0.tgz", + "integrity": "sha512-Hq+143Zs99vJojT/uFvtpxUuiIKoLbMhxhA7qgxe5v8hNXrh5/qTnvYP92hFaE5V+GyoCXlESONa0ufk7t5kHQ==", + "license": "MIT", + "dependencies": { + "@ffmpeg/ffmpeg": "^0.11.6", + "react-audio-visualize": "^1.1.3" + }, + "peerDependencies": { + "react": ">=16.2.0", + "react-dom": ">=16.2.0" + } + }, + "node_modules/react-dom": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", + "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", + "license": "MIT", + "peer": true, + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.13.11", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz", + "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==", + "license": "MIT" + }, + "node_modules/resolve-url": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", + "integrity": "sha512-ZuF55hVUQaaczgOIwqWzkEcEidmlD/xl44x1UZnhOXcYuFN2S6+rcxpG+C1N3So0wvNI3DmJICUFfu2SxhBmvg==", + "deprecated": "https://github.com/lydell/resolve-url#deprecated", + "license": "MIT" + }, + "node_modules/scheduler": { + "version": "0.23.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", + "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "loose-envify": "^1.1.0" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT" + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + } + } +} diff --git a/node_modules/@ffmpeg/ffmpeg/.gitpod.Dockerfile b/node_modules/@ffmpeg/ffmpeg/.gitpod.Dockerfile new file mode 100644 index 0000000..dc5632c --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/.gitpod.Dockerfile @@ -0,0 +1,2 @@ +FROM gitpod/workspace-full +RUN sudo apt-get update && sudo apt-get install -y libgtk-3-0 libx11-xcb1 libnss3 libxss1 libasound2 diff --git a/node_modules/@ffmpeg/ffmpeg/.gitpod.yml b/node_modules/@ffmpeg/ffmpeg/.gitpod.yml new file mode 100644 index 0000000..371e1c9 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/.gitpod.yml @@ -0,0 +1,7 @@ +image: + file: .gitpod.Dockerfile +tasks: +- init: > + wget https://github.com/jeromewu/docker-workspace/raw/master/vim.zip -O /tmp/vim.zip &> /dev/null && + unzip /tmp/vim.zip -d /home/gitpod &> /dev/null && + npm install diff --git a/node_modules/@ffmpeg/ffmpeg/.yarnrc.yml b/node_modules/@ffmpeg/ffmpeg/.yarnrc.yml new file mode 100644 index 0000000..e5a331c --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/.yarnrc.yml @@ -0,0 +1,4 @@ +packageExtensions: + "@ffmpeg/ffmpeg@*": + peerDependencies: + "@ffmpeg/core": "*" diff --git a/node_modules/@ffmpeg/ffmpeg/CODE_OF_CONDUCT.md b/node_modules/@ffmpeg/ffmpeg/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..e8b22d6 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at jeromewus@gmail.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/node_modules/@ffmpeg/ffmpeg/CONTRIBUTING.md b/node_modules/@ffmpeg/ffmpeg/CONTRIBUTING.md new file mode 100644 index 0000000..00d7bdd --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/CONTRIBUTING.md @@ -0,0 +1 @@ +WIP diff --git a/node_modules/@ffmpeg/ffmpeg/LICENSE b/node_modules/@ffmpeg/ffmpeg/LICENSE new file mode 100644 index 0000000..3032c67 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jerome Wu + +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/@ffmpeg/ffmpeg/README.md b/node_modules/@ffmpeg/ffmpeg/README.md new file mode 100644 index 0000000..a2b8205 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/README.md @@ -0,0 +1,202 @@ +

+ + ffmpeg.wasm + +

+ +# ffmpeg.wasm + +[![stability-experimental](https://img.shields.io/badge/stability-experimental-orange.svg)](https://github.com/emersion/stability-badges#experimental) +[![Node Version](https://img.shields.io/node/v/@ffmpeg/ffmpeg.svg)](https://img.shields.io/node/v/@ffmpeg/ffmpeg.svg) +[![Actions Status](https://github.com/ffmpegwasm/ffmpeg.wasm/workflows/CI/badge.svg)](https://github.com/ffmpegwasm/ffmpeg.wasm/actions) +![CodeQL](https://github.com/ffmpegwasm/ffmpeg.wasm/workflows/CodeQL/badge.svg) +![npm (tag)](https://img.shields.io/npm/v/@ffmpeg/ffmpeg/latest) +[![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://github.com/ffmpegwasm/ffmpeg.wasm/graphs/commit-activity) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) +[![Code Style](https://badgen.net/badge/code%20style/airbnb/ff5a5f?icon=airbnb)](https://github.com/airbnb/javascript) +[![Downloads Total](https://img.shields.io/npm/dt/@ffmpeg/ffmpeg.svg)](https://www.npmjs.com/package/@ffmpeg/ffmpeg) +[![Downloads Month](https://img.shields.io/npm/dm/@ffmpeg/ffmpeg.svg)](https://www.npmjs.com/package/@ffmpeg/ffmpeg) + +Join us on Discord! + +[![Discord](https://dcbadge.vercel.app/api/server/NjGMaqqfm5)](https://discord.gg/NjGMaqqfm5) + +ffmpeg.wasm is a pure Webassembly / Javascript port of FFmpeg. It enables video & audio record, convert and stream right inside browsers. + +**AVI to MP4 Demo** +

+ + transcode-demo + +

+ +Try it: [https://ffmpegwasm.netlify.app](https://ffmpegwasm.netlify.app#demo) + +Check next steps of ffmpeg.wasm [HERE](https://github.com/ffmpegwasm/ffmpeg.wasm/discussions/415) + +## Installation + +**Node** + +``` +$ npm install @ffmpeg/ffmpeg @ffmpeg/core +``` + +> As we are using experimental features, you need to add flags to run in Node.js + +``` +$ node --experimental-wasm-threads transcode.js +``` + +**Browser** + +Or, using a script tag in the browser (only works in some browsers, see list below): + +> SharedArrayBuffer is only available to pages that are [cross-origin isolated](https://developer.chrome.com/blog/enabling-shared-array-buffer/#cross-origin-isolation). So you need to host [your own server](https://github.com/ffmpegwasm/ffmpegwasm.github.io/blob/main/server/server.js) with `Cross-Origin-Embedder-Policy: require-corp` and `Cross-Origin-Opener-Policy: same-origin` headers to use ffmpeg.wasm. + +```html + + +``` + +> Only browsers with SharedArrayBuffer support can use ffmpeg.wasm, you can check [HERE](https://caniuse.com/sharedarraybuffer) for the complete list. + +## Usage + +ffmpeg.wasm provides simple to use APIs, to transcode a video you only need few lines of code: + +```javascript +import { writeFile } from 'fs/promises'; +import { createFFmpeg, fetchFile } from '@ffmpeg/ffmpeg'; + +const ffmpeg = createFFmpeg({ log: true }); + +(async () => { + await ffmpeg.load(); + ffmpeg.FS('writeFile', 'test.avi', await fetchFile('./test.avi')); + await ffmpeg.run('-i', 'test.avi', 'test.mp4'); + await fs.promises.writeFile('./test.mp4', ffmpeg.FS('readFile', 'test.mp4')); + process.exit(0); +})(); +``` + +### Use other version of ffmpeg.wasm-core / @ffmpeg/core + +For each version of ffmpeg.wasm, there is a default version of @ffmpeg/core (you can find it in **devDependencies** section of [package.json](https://github.com/ffmpegwasm/ffmpeg.wasm/blob/master/package.json)), but sometimes you may need to use newer version of @ffmpeg/core to use the latest/experimental features. + +**Node** + +Just install the specific version you need: + +```bash +$ npm install @ffmpeg/core@latest +``` + +Or use your own version with customized path + +```javascript +const ffmpeg = createFFmpeg({ + corePath: '../../../src/ffmpeg-core.js', +}); +``` + +**Browser** + +```javascript +const ffmpeg = createFFmpeg({ + corePath: 'static/js/ffmpeg-core.js', +}); +``` + +Keep in mind that for compatibility with webworkers and nodejs this will default to a local path, so it will attempt to look for `'static/js/ffmpeg.core.js'` locally, often resulting in a local resource error. If you wish to use a core version hosted on your own domain, you might reference it relatively like this: + +```javascript +const ffmpeg = createFFmpeg({ + corePath: new URL('static/js/ffmpeg-core.js', document.location).href, +}); +``` + +For the list available versions and their changelog, please check: https://github.com/ffmpegwasm/ffmpeg.wasm-core/releases + +### Use single thread version + +```javascript +const ffmpeg = createFFmpeg({ + mainName: 'main', + corePath: 'https://unpkg.com/@ffmpeg/core-st@0.11.1/dist/ffmpeg-core.js', +}); +``` + +## Multi-threading + +Multi-threading need to be configured per external libraries, only following libraries supports it now: + +### x264 + +Run it multi-threading mode by default, no need to pass any arguments. + +### libvpx / webm + +Need to pass `-row-mt 1`, but can only use one thread to help, can speed up around 30% + +## Documentation + +- [API](https://github.com/ffmpegwasm/ffmpeg.wasm/blob/master/docs/api.md) +- [Supported External Libraries](https://github.com/ffmpegwasm/ffmpeg.wasm-core#configuration) + +## FAQ + +### What is the license of ffmpeg.wasm? + +There are two components inside ffmpeg.wasm: + +- @ffmpeg/ffmpeg (https://github.com/ffmpegwasm/ffmpeg.wasm) +- @ffmpeg/core (https://github.com/ffmpegwasm/ffmpeg.wasm-core) + +@ffmpeg/core contains WebAssembly code which is transpiled from original FFmpeg C code with minor modifications, but overall it still following the same licenses as FFmpeg and its external libraries (as each external libraries might have its own license). + +@ffmpeg/ffmpeg contains kind of a wrapper to handle the complexity of loading core and calling low-level APIs. It is a small code base and under MIT license. + +### Can I use ffmpeg.wasm in Firefox? + +Yes, but only for Firefox 79+ with proper header in both client and server, visit https://ffmpegwasm.netlify.app to try whether your Firefox works. + +![](https://user-images.githubusercontent.com/5723124/98955802-4cb20c80-253a-11eb-8f16-ce0298720a2a.png) + +For more details: https://github.com/ffmpegwasm/ffmpeg.wasm/issues/106 + +### What is the maximum size of input file? + +2 GB, which is a hard limit in WebAssembly. Might become 4 GB in the future. + +### How can I build my own ffmpeg.wasm? + +In fact, it is ffmpeg.wasm-core most people would like to build. + +To build on your own, you can check build.sh inside https://github.com/ffmpegwasm/ffmpeg.wasm-core repository. + +Also you can check this series of posts to learn more fundamental concepts: + +- https://jeromewu.github.io/build-ffmpeg-webassembly-version-part-1-preparation/ +- https://jeromewu.github.io/build-ffmpeg-webassembly-version-part-2-compile-with-emscripten/ +- https://jeromewu.github.io/build-ffmpeg-webassembly-version-part-3-v0.1/ +- https://jeromewu.github.io/build-ffmpeg-webassembly-version-part-4-v0.2/ + +### Why it doesn't work in my local environment? + +When calling `ffmpeg.load()`, by default it looks for `http://localhost:3000/node_modules/@ffmpeg/core/dist/` to download essential files (ffmpeg-core.js, ffmpeg-core.wasm, ffmpeg-core.worker.js). It is necessary to make sure you have those files served there. + +If you have those files serving in other location, you can rewrite the default behavior when calling `createFFmpeg()`: + +```javascript +const { createFFmpeg } = FFmpeg; +const ffmpeg = createFFmpeg({ + corePath: "http://localhost:3000/public/ffmpeg-core.js", + // Use public address if you don't want to host your own. + // corePath: 'https://unpkg.com/@ffmpeg/core@0.10.0/dist/ffmpeg-core.js' + log: true, +}); +``` diff --git a/node_modules/@ffmpeg/ffmpeg/_config.yml b/node_modules/@ffmpeg/ffmpeg/_config.yml new file mode 100644 index 0000000..c419263 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/_config.yml @@ -0,0 +1 @@ +theme: jekyll-theme-cayman \ No newline at end of file diff --git a/node_modules/@ffmpeg/ffmpeg/dist/046d0074eee1d99a674a.js b/node_modules/@ffmpeg/ffmpeg/dist/046d0074eee1d99a674a.js new file mode 100644 index 0000000..91c5502 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/dist/046d0074eee1d99a674a.js @@ -0,0 +1 @@ +var createFFmpegCore=function(){var e="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0;return"undefined"!=typeof __filename&&(e=e||__filename),function(t){var n,r,i;t=t||{},n||(n=void 0!==t?t:{}),n.ready=new Promise((function(e,t){r=e,i=t})),n.quit=function(e){throw n.onExit&&n.onExit(e),new Qr(e)},n.exit=$r,k=A=function(){};var a,f={};for(a in n)n.hasOwnProperty(a)&&(f[a]=n[a]);var o=[],u="./this.program";function c(e,t){throw t}var s=!1,l=!1,d=!1,h=!1;s="object"==typeof window,l="function"==typeof importScripts,d="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,h=!s&&!d&&!l;var p=n.ENVIRONMENT_IS_PTHREAD||!1;p&&(q=n.buffer);var m,g,w,y,v="";function b(e){return n.locateFile?n.locateFile(e,v):v+e}if(d){var _;v=l?require("path").dirname(v)+"/":__dirname+"/",m=function(e,t){return w||(w=require("fs")),y||(y=require("path")),e=y.normalize(e),w.readFileSync(e,t?null:"utf8")},g=function(e){return(e=m(e,!0)).buffer||(e=new Uint8Array(e)),O(e.buffer),e},1=n);){var i=e[t++];if(!i)break;if(128&i){var a=63&e[t++];if(192==(224&i))r+=String.fromCharCode((31&i)<<6|a);else{var f=63&e[t++];65536>(i=224==(240&i)?(15&i)<<12|a<<6|f:(7&i)<<18|a<<12|f<<6|63&e[t++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r}function R(e,t){return e?L(Y,e,t):""}function N(e,t,n,r){if(!(0=f&&(f=65536+((1023&f)<<10)|1023&e.charCodeAt(++a)),127>=f){if(n>=r)break;t[n++]=f}else{if(2047>=f){if(n+1>=r)break;t[n++]=192|f>>6}else{if(65535>=f){if(n+2>=r)break;t[n++]=224|f>>12}else{if(n+3>=r)break;t[n++]=240|f>>18,t[n++]=128|f>>12&63}t[n++]=128|f>>6&63}t[n++]=128|63&f}}return t[n]=0,n-i}function B(e,t,n){return N(e,Y,t,n)}function U(e){for(var t=0,n=0;n=r&&(r=65536+((1023&r)<<10)|1023&e.charCodeAt(++n)),127>=r?++t:t=2047>=r?t+2:65535>=r?t+3:t+4}return t}function z(e){var t=U(e)+1,n=ir(t);return n&&N(e,H,n,t),n}function G(e){var t=U(e)+1,n=yr(t);return N(e,H,n,t),n}function W(e,t,n){for(var r=0;r>0]=e.charCodeAt(r);n||(H[t>>0]=0)}var q,H,Y,X,V,Q,J,$,Z,K=n.INITIAL_MEMORY||1073741824;if(p)M=n.wasmMemory,q=n.buffer;else if(n.wasmMemory)M=n.wasmMemory;else if(!((M=new WebAssembly.Memory({initial:K/65536,maximum:K/65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw A("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),d&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");M&&(q=M.buffer),K=q.byteLength;var ee=q;q=ee,n.HEAP8=H=new Int8Array(ee),n.HEAP16=X=new Int16Array(ee),n.HEAP32=Q=new Int32Array(ee),n.HEAPU8=Y=new Uint8Array(ee),n.HEAPU16=V=new Uint16Array(ee),n.HEAPU32=J=new Uint32Array(ee),n.HEAPF32=$=new Float32Array(ee),n.HEAPF64=Z=new Float64Array(ee);var te,ne=[],re=[],ie=[],ae=[],fe=[];function oe(){var e=n.preRun.shift();ne.unshift(e)}var ue=0,ce=null,se=null;function le(){O(!p,"addRunDependency cannot be used in a pthread worker"),ue++,n.monitorRunDependencies&&n.monitorRunDependencies(ue)}function de(){if(ue--,n.monitorRunDependencies&&n.monitorRunDependencies(ue),0==ue&&(null!==ce&&(clearInterval(ce),ce=null),se)){var e=se;se=null,e()}}function he(e){throw n.onAbort&&n.onAbort(e),p&&console.error("Pthread aborting at "+Error().stack),A(e),F=!0,e=new WebAssembly.RuntimeError("abort("+e+"). Build with -s ASSERTIONS=1 for more info."),i(e),e}function pe(e){var t=ge;return String.prototype.startsWith?t.startsWith(e):0===t.indexOf(e)}function me(){return pe("data:application/octet-stream;base64,")}n.preloadedImages={},n.preloadedAudios={};var ge="ffmpeg-core.wasm";function we(){try{if(E)return new Uint8Array(E);if(g)return g(ge);throw"both async and sync fetching of the wasm failed"}catch(e){he(e)}}function ye(){return E||!s&&!l||"function"!=typeof fetch||pe("file://")?Promise.resolve().then(we):fetch(ge,{credentials:"same-origin"}).then((function(e){if(!e.ok)throw"failed to load wasm binary file at '"+ge+"'";return e.arrayBuffer()})).catch((function(){return we()}))}me()||(ge=b(ge));var ve,be,_e={5449136:function(){throw"Canceled!"},5449356:function(e,t){setTimeout((function(){Ar(e,t)}),0)},5449458:function(){return 5242880}};function ke(e){for(;0=e||e>H.length||1&e||0>t)return-28;if(0==t)return 0;2147483647<=t&&(t=1/0);var n=Atomics.load(Q,Fe.Vf>>2),r=0;if(n==e&&Atomics.compareExchange(Q,Fe.Vf>>2,n,0)==n&&(r=1,0>=--t))return 1;if(0<=(e=Atomics.notify(Q,e>>2,t)))return e+r;throw"Atomics.notify returned an unexpected value "+e}function Te(e){if(p)throw"Internal Error! cancelThread() can only ever be called from main application thread!";if(!e)throw"Internal Error! Null pthread_ptr in cancelThread!";Fe.Ef[e].worker.postMessage({cmd:"cancel"})}function De(e){if(p)throw"Internal Error! cleanupThread() can only ever be called from main application thread!";if(!e)throw"Internal Error! Null pthread_ptr in cleanupThread!";Q[e+12>>2]=0,(e=Fe.Ef[e])&&Fe.Ag(e.worker)}n.registerPthreadPtr=Se,n._emscripten_futex_wake=Me;var Ce,Fe={Ph:1,nj:{Ih:0,Jh:0},Gf:[],Kf:[],lj:function(){},pi:function(){Fe.xf=ir(232);for(var e=0;58>e;++e)J[Fe.xf/4+e]=0;Q[Fe.xf+12>>2]=Fe.xf,e=Fe.xf+156,Q[e>>2]=e;var t=ir(512);for(e=0;128>e;++e)J[t/4+e]=0;Atomics.store(J,Fe.xf+104>>2,t),Atomics.store(J,Fe.xf+40>>2,Fe.xf),Atomics.store(J,Fe.xf+44>>2,42),Fe.Ch(),Se(Fe.xf,!l,1),kr(Fe.xf)},ri:function(){Fe.Ch(),r(n),Fe.receiveObjectTransfer=Fe.Ii,Fe.setThreadStatus=Fe.Li,Fe.threadCancel=Fe.Pi,Fe.threadExit=Fe.Qi},Ch:function(){Fe.Vf=Cr},Ef:{},Dg:[],Li:function(){},eh:function(){for(;0>2,e),Atomics.store(J,t+0>>2,1),Atomics.store(J,t+60>>2,1),Atomics.store(J,t+64>>2,0),Fe.eh(),Me(t+0,2147483647),Se(0,0,0),D=0,p&&postMessage({cmd:"exit"}))},Pi:function(){Fe.eh(),Atomics.store(J,D+4>>2,-1),Atomics.store(J,D+0>>2,1),Me(D+0,2147483647),D=C=0,Se(0,0,0),postMessage({cmd:"cancelDone"})},Oi:function(){for(var e in Fe.Ef){var t=Fe.Ef[e];t&&t.worker&&Fe.Ag(t.worker)}for(Fe.Ef={},e=0;e>2];Q[e.threadInfoStruct+104>>2]=0,rr(t),rr(e.threadInfoStruct)}e.threadInfoStruct=0,e.Kg&&e.Rf&&rr(e.Rf),e.Rf=0,e.worker&&(e.worker.yf=null)}},Ag:function(e){delete Fe.Ef[e.yf.Lh],Fe.Gf.push(e),Fe.Kf.splice(Fe.Kf.indexOf(e),1),Fe.Pg(e.yf),e.yf=void 0},Ii:function(){},vi:function(t,r){t.onmessage=function(e){var n=e.data,i=n.cmd;if(t.yf&&(Fe.Mg=t.yf.threadInfoStruct),n.targetThread&&n.targetThread!=(0|xe)){var a=Fe.Ef[n.xj];a?a.worker.postMessage(e.data,n.transferList):console.error('Internal error! Worker sent a message "'+i+'" to target pthread '+n.targetThread+", but that thread no longer exists!")}else if("processQueuedMainThreadWork"===i)_r();else if("spawnThread"===i)Nn(e.data);else if("cleanupThread"===i)De(n.thread);else if("killThread"===i){if(e=n.thread,p)throw"Internal Error! killThread() can only ever be called from main application thread!";if(!e)throw"Internal Error! Null pthread_ptr in killThread!";Q[e+12>>2]=0,(e=Fe.Ef[e]).worker.terminate(),Fe.Pg(e),Fe.Kf.splice(Fe.Kf.indexOf(e.worker),1),e.worker.yf=void 0}else if("cancelThread"===i)Te(n.thread);else if("loaded"===i)t.loaded=!0,r&&r(t),t.og&&(t.og(),delete t.og);else if("print"===i)k("Thread "+n.threadId+": "+n.text);else if("printErr"===i)A("Thread "+n.threadId+": "+n.text);else if("alert"===i)alert("Thread "+n.threadId+": "+n.text);else if("exit"===i)t.yf&&Atomics.load(J,t.yf.Lh+68>>2)&&Fe.Ag(t);else if("exitProcess"===i){j=!1;try{$r(n.returnCode)}catch(e){if(e instanceof Qr)return;throw e}}else"cancelDone"===i?Fe.Ag(t):"objectTransfer"!==i&&("setimmediate"===e.data.target?t.postMessage(e.data):A("worker sent an unknown command "+i));Fe.Mg=void 0},t.onerror=function(e){A("pthread sent an error! "+e.filename+":"+e.lineno+": "+e.message)},d&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("exit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:n.mainScriptUrlOrBlob||e,wasmMemory:M,wasmModule:T})},Vh:function(){var e=b("ffmpeg-core.worker.js");Fe.Gf.push(new Worker(e))},li:function(){return 0==Fe.Gf.length&&(Fe.Vh(),Fe.vi(Fe.Gf[0])),0>2]=e}function Ie(e,t){if(0===e)e=Date.now();else{if(1!==e&&4!==e)return Oe(28),-1;e=Ce()}return Q[t>>2]=e/1e3|0,Q[t+4>>2]=e%1e3*1e6|0,0}function Pe(e,t){if(p)return vn(1,1,e,t);ae.unshift({vh:e,Tf:t})}function Le(e,t){return e=new Date(1e3*Q[e>>2]),Q[t>>2]=e.getUTCSeconds(),Q[t+4>>2]=e.getUTCMinutes(),Q[t+8>>2]=e.getUTCHours(),Q[t+12>>2]=e.getUTCDate(),Q[t+16>>2]=e.getUTCMonth(),Q[t+20>>2]=e.getUTCFullYear()-1900,Q[t+24>>2]=e.getUTCDay(),Q[t+36>>2]=0,Q[t+32>>2]=0,Q[t+28>>2]=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,Le.ih||(Le.ih=z("GMT")),Q[t+40>>2]=Le.ih,t}function Re(){function e(e){return(e=e.toTimeString().match(/\(([A-Za-z ]+)\)$/))?e[1]:"GMT"}if(p)return vn(2,1);if(!Re.Yh){Re.Yh=!0;var t=(new Date).getFullYear(),n=new Date(t,0,1),r=new Date(t,6,1);t=n.getTimezoneOffset();var i=r.getTimezoneOffset(),a=Math.max(t,i);Q[mr()>>2]=60*a,Q[pr()>>2]=Number(t!=i),n=e(n),r=e(r),n=z(n),r=z(r),i>2]=n,Q[hr()+4>>2]=r):(Q[hr()>>2]=r,Q[hr()+4>>2]=n)}}function Ne(e,t){Re(),e=new Date(1e3*Q[e>>2]),Q[t>>2]=e.getSeconds(),Q[t+4>>2]=e.getMinutes(),Q[t+8>>2]=e.getHours(),Q[t+12>>2]=e.getDate(),Q[t+16>>2]=e.getMonth(),Q[t+20>>2]=e.getFullYear()-1900,Q[t+24>>2]=e.getDay();var n=new Date(e.getFullYear(),0,1);Q[t+28>>2]=(e.getTime()-n.getTime())/864e5|0,Q[t+36>>2]=-60*e.getTimezoneOffset();var r=new Date(e.getFullYear(),6,1).getTimezoneOffset();return e=0|(r!=(n=n.getTimezoneOffset())&&e.getTimezoneOffset()==Math.min(n,r)),Q[t+32>>2]=e,e=Q[hr()+(e?4:0)>>2],Q[t+40>>2]=e,t}function Be(e,t){for(var n=0,r=e.length-1;0<=r;r--){var i=e[r];"."===i?e.splice(r,1):".."===i?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n;n--)e.unshift("..");return e}function Ue(e){var t="/"===e.charAt(0),n="/"===e.substr(-1);return(e=Be(e.split("/").filter((function(e){return!!e})),!t).join("/"))||t||(e="."),e&&n&&(e+="/"),(t?"/":"")+e}function ze(e){var t=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1);return e=t[0],t=t[1],e||t?(t&&(t=t.substr(0,t.length-1)),e+t):"."}function Ge(e){if("/"===e)return"/";var t=(e=(e=Ue(e)).replace(/\/$/,"")).lastIndexOf("/");return-1===t?e:e.substr(t+1)}function We(e,t){return Ue(e+"/"+t)}function qe(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var e=new Uint8Array(1);return function(){return crypto.getRandomValues(e),e[0]}}if(d)try{var t=require("crypto");return function(){return t.randomBytes(1)[0]}}catch(e){}return function(){he("randomDevice")}}function He(){for(var e="",t=!1,n=arguments.length-1;-1<=n&&!t;n--){if("string"!=typeof(t=0<=n?arguments[n]:Ke.cwd()))throw new TypeError("Arguments to path.resolve must be strings");if(!t)return"";e=t+"/"+e,t="/"===t.charAt(0)}return(t?"/":"")+(e=Be(e.split("/").filter((function(e){return!!e})),!t).join("/"))||"."}function Ye(e,t){function n(e){for(var t=0;tn?[]:e.slice(t,n-t+1)}e=He(e).substr(1),t=He(t).substr(1),e=n(e.split("/")),t=n(t.split("/"));for(var r=Math.min(e.length,t.length),i=r,a=0;a=t||(t=Math.max(t,n*(1048576>n?2:1.125)>>>0),0!=n&&(t=Math.max(t,256)),n=e.bf,e.bf=new Uint8Array(t),0t)e.bf.length=t;else for(;e.bf.length=e.node.gf)return 0;if(8<(e=Math.min(e.node.gf-i,r))&&a.subarray)t.set(a.subarray(i,i+e),n);else for(r=0;rt)throw new Ke.af(28);return t},fg:function(e,t,n){Ze.sh(e.node,t+n),e.node.gf=Math.max(e.node.gf,t+n)},Wf:function(e,t,n,r,i,a){if(O(0===t),!Ke.isFile(e.node.mode))throw new Ke.af(43);if(e=e.node.bf,2&a||e.buffer!==q){for((0>>0)%Ke.Cf.length},zh:function(e){var t=Ke.Sg(e.parent.id,e.name);e.Pf=Ke.Cf[t],Ke.Cf[t]=e},Ah:function(e){var t=Ke.Sg(e.parent.id,e.name);if(Ke.Cf[t]===e)Ke.Cf[t]=e.Pf;else for(t=Ke.Cf[t];t;){if(t.Pf===e){t.Pf=e.Pf;break}t=t.Pf}},Bf:function(e,t){var n=Ke.yi(e);if(n)throw new Ke.af(n,e);for(n=Ke.Cf[Ke.Sg(e.id,t)];n;n=n.Pf){var r=n.name;if(n.parent.id===e.id&&r===t)return n}return Ke.lookup(e,t)},createNode:function(e,t,n,r){return e=new Ke.Oh(e,t,n,r),Ke.zh(e),e},Ng:function(e){Ke.Ah(e)},wg:function(e){return e===e.parent},Nf:function(e){return!!e.lg},isFile:function(e){return 32768==(61440&e)},kf:function(e){return 16384==(61440&e)},Mf:function(e){return 40960==(61440&e)},hg:function(e){return 8192==(61440&e)},si:function(e){return 24576==(61440&e)},isFIFO:function(e){return 4096==(61440&e)},isSocket:function(e){return 49152==(49152&e)},ji:{r:0,rs:1052672,"r+":2,w:577,wx:705,xw:705,"w+":578,"wx+":706,"xw+":706,a:1089,ax:1217,xa:1217,"a+":1090,"ax+":1218,"xa+":1218},Dh:function(e){var t=Ke.ji[e];if(void 0===t)throw Error("Unknown file open mode: "+e);return t},th:function(e){var t=["r","w","rw"][3&e];return 512&e&&(t+="w"),t},Jf:function(e,t){return Ke.Bh||(-1===t.indexOf("r")||292&e.mode)&&(-1===t.indexOf("w")||146&e.mode)&&(-1===t.indexOf("x")||73&e.mode)?0:2},yi:function(e){return Ke.Jf(e,"x")||(e.cf.lookup?0:2)},Yg:function(e,t){try{return Ke.Bf(e,t),20}catch(e){}return Ke.Jf(e,"wx")},xg:function(e,t,n){try{var r=Ke.Bf(e,t)}catch(e){return e.ef}if(e=Ke.Jf(e,"wx"))return e;if(n){if(!Ke.kf(r.mode))return 54;if(Ke.wg(r)||Ke.If(r)===Ke.cwd())return 10}else if(Ke.kf(r.mode))return 31;return 0},zi:function(e,t){return e?Ke.Mf(e.mode)?32:Ke.kf(e.mode)&&("r"!==Ke.th(t)||512&t)?31:Ke.Jf(e,Ke.th(t)):44},Qh:4096,Bi:function(e,t){for(t=t||Ke.Qh,e=e||0;e<=t;e++)if(!Ke.streams[e])return e;throw new Ke.af(33)},zf:function(e){return Ke.streams[e]},nh:function(e,t,n){Ke.Hg||(Ke.Hg=function(){},Ke.Hg.prototype={object:{get:function(){return this.node},set:function(e){this.node=e}}});var r,i=new Ke.Hg;for(r in e)i[r]=e[r];return e=i,t=Ke.Bi(t,n),e.fd=t,Ke.streams[t]=e},ai:function(e){Ke.streams[e]=null},$h:{open:function(e){e.df=Ke.ki(e.node.rdev).df,e.df.open&&e.df.open(e)},tf:function(){throw new Ke.af(70)}},Wg:function(e){return e>>8},oj:function(e){return 255&e},Of:function(e,t){return e<<8|t},dh:function(e,t){Ke.ph[e]={df:t}},ki:function(e){return Ke.ph[e]},wh:function(e){var t=[];for(e=[e];e.length;){var n=e.pop();t.push(n),e.push.apply(e,n.mg)}return t},Kh:function(e,t){function n(e){return Ke.Cg--,t(e)}function r(e){if(e){if(!r.gi)return r.gi=!0,n(e)}else++a>=i.length&&n(null)}"function"==typeof e&&(t=e,e=!1),Ke.Cg++,1t)throw new Ke.af(28);var n;if(!(n="string"==typeof e?Ke.ff(e,{wf:!0}).node:e).cf.nf)throw new Ke.af(63);if(Ke.kf(n.mode))throw new Ke.af(31);if(!Ke.isFile(n.mode))throw new Ke.af(28);if(e=Ke.Jf(n,"w"))throw new Ke.af(e);n.cf.nf(n,{size:t,timestamp:Date.now()})},fj:function(e,t){if(!(e=Ke.zf(e)))throw new Ke.af(8);if(0==(2097155&e.flags))throw new Ke.af(28);Ke.truncate(e.node,t)},Aj:function(e,t,n){(e=Ke.ff(e,{wf:!0}).node).cf.nf(e,{timestamp:Math.max(t,n)})},open:function(e,t,r,i,a){if(""===e)throw new Ke.af(44);if(r=64&(t="string"==typeof t?Ke.Dh(t):t)?4095&(void 0===r?438:r)|32768:0,"object"==typeof e)var f=e;else{e=Ue(e);try{f=Ke.ff(e,{wf:!(131072&t)}).node}catch(e){}}var o=!1;if(64&t)if(f){if(128&t)throw new Ke.af(20)}else f=Ke.Ff(e,r,0),o=!0;if(!f)throw new Ke.af(44);if(Ke.hg(f.mode)&&(t&=-513),65536&t&&!Ke.kf(f.mode))throw new Ke.af(54);if(!o&&(r=Ke.zi(f,t)))throw new Ke.af(r);512&t&&Ke.truncate(f,0),t&=-131713,(i=Ke.nh({node:f,path:Ke.If(f),flags:t,seekable:!0,position:0,df:f.df,Wi:[],error:!1},i,a)).df.open&&i.df.open(i),!n.logReadFiles||1&t||(Ke.$g||(Ke.$g={}),e in Ke.$g||(Ke.$g[e]=1,A("FS.trackingDelegate error on read file: "+e)));try{Ke.mf.onOpenFile&&(a=0,1!=(2097155&t)&&(a|=Ke.Mh.Gh.Rh),0!=(2097155&t)&&(a|=Ke.Mh.Gh.Sh),Ke.mf.onOpenFile(e,a))}catch(t){A("FS.trackingDelegate['onOpenFile']('"+e+"', flags) threw an exception: "+t.message)}return i},close:function(e){if(Ke.ig(e))throw new Ke.af(8);e.Lf&&(e.Lf=null);try{e.df.close&&e.df.close(e)}catch(e){throw e}finally{Ke.ai(e.fd)}e.fd=null},ig:function(e){return null===e.fd},tf:function(e,t,n){if(Ke.ig(e))throw new Ke.af(8);if(!e.seekable||!e.df.tf)throw new Ke.af(70);if(0!=n&&1!=n&&2!=n)throw new Ke.af(28);return e.position=e.df.tf(e,t,n),e.Wi=[],e.position},read:function(e,t,n,r,i){if(0>r||0>i)throw new Ke.af(28);if(Ke.ig(e))throw new Ke.af(8);if(1==(2097155&e.flags))throw new Ke.af(8);if(Ke.kf(e.node.mode))throw new Ke.af(31);if(!e.df.read)throw new Ke.af(28);var a=void 0!==i;if(a){if(!e.seekable)throw new Ke.af(70)}else i=e.position;return t=e.df.read(e,t,n,r,i),a||(e.position+=t),t},write:function(e,t,n,r,i,a){if(0>r||0>i)throw new Ke.af(28);if(Ke.ig(e))throw new Ke.af(8);if(0==(2097155&e.flags))throw new Ke.af(8);if(Ke.kf(e.node.mode))throw new Ke.af(31);if(!e.df.write)throw new Ke.af(28);e.seekable&&1024&e.flags&&Ke.tf(e,0,2);var f=void 0!==i;if(f){if(!e.seekable)throw new Ke.af(70)}else i=e.position;t=e.df.write(e,t,n,r,i,a),f||(e.position+=t);try{e.path&&Ke.mf.onWriteToFile&&Ke.mf.onWriteToFile(e.path)}catch(t){A("FS.trackingDelegate['onWriteToFile']('"+e.path+"') threw an exception: "+t.message)}return t},fg:function(e,t,n){if(Ke.ig(e))throw new Ke.af(8);if(0>t||0>=n)throw new Ke.af(28);if(0==(2097155&e.flags))throw new Ke.af(8);if(!Ke.isFile(e.node.mode)&&!Ke.kf(e.node.mode))throw new Ke.af(43);if(!e.df.fg)throw new Ke.af(138);e.df.fg(e,t,n)},Wf:function(e,t,n,r,i,a){if(0!=(2&i)&&0==(2&a)&&2!=(2097155&e.flags))throw new Ke.af(2);if(1==(2097155&e.flags))throw new Ke.af(2);if(!e.df.Wf)throw new Ke.af(43);return e.df.Wf(e,t,n,r,i,a)},Xf:function(e,t,n,r,i){return e&&e.df.Xf?e.df.Xf(e,t,n,r,i):0},sj:function(){return 0},Uf:function(e,t,n){if(!e.df.Uf)throw new Ke.af(59);return e.df.Uf(e,t,n)},readFile:function(e,t){if((t=t||{}).flags=t.flags||"r",t.encoding=t.encoding||"binary","utf8"!==t.encoding&&"binary"!==t.encoding)throw Error('Invalid encoding type "'+t.encoding+'"');var n,r=Ke.open(e,t.flags);e=Ke.stat(e).size;var i=new Uint8Array(e);return Ke.read(r,i,0,e,0),"utf8"===t.encoding?n=L(i,0):"binary"===t.encoding&&(n=i),Ke.close(r),n},writeFile:function(e,t,n){if((n=n||{}).flags=n.flags||"w",e=Ke.open(e,n.flags,n.mode),"string"==typeof t){var r=new Uint8Array(U(t)+1);t=N(t,r,0,r.length),Ke.write(e,r,0,t,void 0,n.Zh)}else{if(!ArrayBuffer.isView(t))throw Error("Unsupported data type");Ke.write(e,t,0,t.byteLength,void 0,n.Zh)}Ke.close(e)},cwd:function(){return Ke.oh},chdir:function(e){if(null===(e=Ke.ff(e,{wf:!0})).node)throw new Ke.af(44);if(!Ke.kf(e.node.mode))throw new Ke.af(54);var t=Ke.Jf(e.node,"x");if(t)throw new Ke.af(t);Ke.oh=e.path},ci:function(){Ke.mkdir("/tmp"),Ke.mkdir("/home"),Ke.mkdir("/home/web_user")},bi:function(){Ke.mkdir("/dev"),Ke.dh(Ke.Of(1,3),{read:function(){return 0},write:function(e,t,n,r){return r}}),Ke.yg("/dev/null",Ke.Of(1,3)),Ve(Ke.Of(5,0),Je),Ve(Ke.Of(6,0),$e),Ke.yg("/dev/tty",Ke.Of(5,0)),Ke.yg("/dev/tty1",Ke.Of(6,0));var e=qe();Ke.Hf("/dev","random",e),Ke.Hf("/dev","urandom",e),Ke.mkdir("/dev/shm"),Ke.mkdir("/dev/shm/tmp")},ei:function(){Ke.mkdir("/proc"),Ke.mkdir("/proc/self"),Ke.mkdir("/proc/self/fd"),Ke.jf({jf:function(){var e=Ke.createNode("/proc/self","fd",16895,73);return e.cf={lookup:function(e,t){var n=Ke.zf(+t);if(!n)throw new Ke.af(8);return(e={parent:null,jf:{Eh:"fake"},cf:{readlink:function(){return n.path}}}).parent=e}},e}},{},"/proc/self/fd")},fi:function(){n.stdin?Ke.Hf("/dev","stdin",n.stdin):Ke.symlink("/dev/tty","/dev/stdin"),n.stdout?Ke.Hf("/dev","stdout",null,n.stdout):Ke.symlink("/dev/tty","/dev/stdout"),n.stderr?Ke.Hf("/dev","stderr",null,n.stderr):Ke.symlink("/dev/tty1","/dev/stderr"),Ke.open("/dev/stdin","r"),Ke.open("/dev/stdout","w"),Ke.open("/dev/stderr","w")},rh:function(){Ke.af||(Ke.af=function(e,t){this.node=t,this.Ki=function(e){this.ef=e},this.Ki(e),this.message="FS error"},Ke.af.prototype=Error(),Ke.af.prototype.constructor=Ke.af,[44].forEach((function(e){Ke.Qg[e]=new Ke.af(e),Ke.Qg[e].stack=""})))},Ni:function(){Ke.rh(),Ke.Cf=Array(4096),Ke.jf(Ze,{},"/"),Ke.ci(),Ke.bi(),Ke.ei(),Ke.ii={MEMFS:Ze}},gg:function(e,t,r){Ke.gg.Tg=!0,Ke.rh(),n.stdin=e||n.stdin,n.stdout=t||n.stdout,n.stderr=r||n.stderr,Ke.fi()},quit:function(){Ke.gg.Tg=!1;var e=n._fflush;for(e&&e(0),e=0;ethis.length-1||0>e)){var t=e%this.chunkSize;return this.yh(e/this.chunkSize|0)[t]}},a.prototype.Wh=function(e){this.yh=e},a.prototype.kh=function(){var e=new XMLHttpRequest;if(e.open("HEAD",n,!1),e.send(null),!(200<=e.status&&300>e.status||304===e.status))throw Error("Couldn't load "+n+". Status: "+e.status);var t,r=Number(e.getResponseHeader("Content-length")),i=(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t;e=(t=e.getResponseHeader("Content-Encoding"))&&"gzip"===t;var a=1048576;i||(a=r);var f=this;f.Wh((function(e){var t=e*a,i=(e+1)*a-1;if(i=Math.min(i,r-1),void 0===f.Sf[e]){var o=f.Sf;if(t>i)throw Error("invalid range ("+t+", "+i+") or no bytes requested!");if(i>r-1)throw Error("only "+r+" bytes available! programmer error!");var u=new XMLHttpRequest;if(u.open("GET",n,!1),r!==a&&u.setRequestHeader("Range","bytes="+t+"-"+i),"undefined"!=typeof Uint8Array&&(u.responseType="arraybuffer"),u.overrideMimeType&&u.overrideMimeType("text/plain; charset=x-user-defined"),u.send(null),!(200<=u.status&&300>u.status||304===u.status))throw Error("Couldn't load "+n+". Status: "+u.status);t=void 0!==u.response?new Uint8Array(u.response||[]):er(u.responseText||"",!0),o[e]=t}if(void 0===f.Sf[e])throw Error("doXHR failed!");return f.Sf[e]})),!e&&r||(a=r=1,a=r=this.yh(0).length,k("LazyFiles on gzip forces download of the whole file when length is accessed")),this.Uh=r,this.Th=a,this.Vg=!0},"undefined"!=typeof XMLHttpRequest){if(!l)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var f=new a;Object.defineProperties(f,{length:{get:function(){return this.Vg||this.kh(),this.Uh}},chunkSize:{get:function(){return this.Vg||this.kh(),this.Th}}}),f={Ug:!1,bf:f}}else f={Ug:!1,url:n};var o=Ke.di(e,t,f,r,i);f.bf?o.bf=f.bf:f.url&&(o.bf=null,o.url=f.url),Object.defineProperties(o,{gf:{get:function(){return this.bf.length}}});var u={};return Object.keys(o.df).forEach((function(e){var t=o.df[e];u[e]=function(){if(!Ke.uh(o))throw new Ke.af(29);return t.apply(null,arguments)}})),u.read=function(e,t,n,r,i){if(!Ke.uh(o))throw new Ke.af(29);if(i>=(e=e.node.bf).length)return 0;if(r=Math.min(e.length-i,r),e.slice)for(var a=0;a>2]=r.dev,Q[n+4>>2]=0,Q[n+8>>2]=r.ino,Q[n+12>>2]=r.mode,Q[n+16>>2]=r.nlink,Q[n+20>>2]=r.uid,Q[n+24>>2]=r.gid,Q[n+28>>2]=r.rdev,Q[n+32>>2]=0,be=[r.size>>>0,(ve=r.size,1<=+Math.abs(ve)?0>>0:~~+Math.ceil((ve-+(~~ve>>>0))/4294967296)>>>0:0)],Q[n+40>>2]=be[0],Q[n+44>>2]=be[1],Q[n+48>>2]=4096,Q[n+52>>2]=r.blocks,Q[n+56>>2]=r.atime.getTime()/1e3|0,Q[n+60>>2]=0,Q[n+64>>2]=r.mtime.getTime()/1e3|0,Q[n+68>>2]=0,Q[n+72>>2]=r.ctime.getTime()/1e3|0,Q[n+76>>2]=0,be=[r.ino>>>0,(ve=r.ino,1<=+Math.abs(ve)?0>>0:~~+Math.ceil((ve-+(~~ve>>>0))/4294967296)>>>0:0)],Q[n+80>>2]=be[0],Q[n+84>>2]=be[1],0}var nt=void 0;function rt(){return Q[(nt+=4)-4>>2]}function it(e){if(!(e=Ke.zf(e)))throw new Ke.af(8);return e}function at(e,t,n,r,i){if(p)return vn(3,1,e,t,n,r,i);try{i=0;for(var a=t?Q[t>>2]:0,f=t?Q[t+4>>2]:0,o=n?Q[n>>2]:0,u=n?Q[n+4>>2]:0,c=r?Q[r>>2]:0,s=r?Q[r+4>>2]:0,l=0,d=0,h=0,m=0,g=0,w=0,y=(t?Q[t>>2]:0)|(n?Q[n>>2]:0)|(r?Q[r>>2]:0),v=(t?Q[t+4>>2]:0)|(n?Q[n+4>>2]:0)|(r?Q[r+4>>2]:0),b=0;bb?y&_:v&_){var k=Ke.zf(b);if(!k)throw new Ke.af(8);var A=5;k.df.Zf&&(A=k.df.Zf(k)),1&A&&(32>b?a&_:f&_)&&(32>b?l|=_:d|=_,i++),4&A&&(32>b?o&_:u&_)&&(32>b?h|=_:m|=_,i++),2&A&&(32>b?c&_:s&_)&&(32>b?g|=_:w|=_,i++)}}return t&&(Q[t>>2]=l,Q[t+4>>2]=d),n&&(Q[n>>2]=h,Q[n+4>>2]=m),r&&(Q[r>>2]=g,Q[r+4>>2]=w),i}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function ft(e,t){if(p)return vn(4,1,e,t);try{var n;if(e=R(e),-8&t)var r=-28;else(n=Ke.ff(e,{wf:!0}).node)?(e="",4&t&&(e+="r"),2&t&&(e+="w"),1&t&&(e+="x"),r=e&&Ke.Jf(n,e)?-2:0):r=-44;return r}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function ot(e,t,n){if(p)return vn(5,1,e,t,n);nt=n;try{var r=it(e);switch(t){case 0:var i=rt();return 0>i?-28:Ke.open(r.path,r.flags,0,i).fd;case 1:case 2:case 13:case 14:return 0;case 3:return r.flags;case 4:return i=rt(),r.flags|=i,0;case 12:return i=rt(),X[i+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return Oe(28),-1}}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function ut(e,t){if(p)return vn(6,1,e,t);try{var n=it(e);return tt(Ke.stat,n.path,t)}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function ct(e,t,n){if(p)return vn(7,1,e,t,n);try{var r=it(e);r.Lf||(r.Lf=Ke.readdir(r.path)),e=0;for(var i=Ke.tf(r,0,1),a=Math.floor(i/280);a>>0,(ve=o,1<=+Math.abs(ve)?0>>0:~~+Math.ceil((ve-+(~~ve>>>0))/4294967296)>>>0:0)],Q[t+e>>2]=be[0],Q[t+e+4>>2]=be[1],be=[280*(a+1)>>>0,(ve=280*(a+1),1<=+Math.abs(ve)?0>>0:~~+Math.ceil((ve-+(~~ve>>>0))/4294967296)>>>0:0)],Q[t+e+8>>2]=be[0],Q[t+e+12>>2]=be[1],X[t+e+16>>1]=280,H[t+e+18>>0]=u,B(f,t+e+19,256),e+=280,a+=1}return Ke.tf(r,280*a,0),e}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function st(e,t){if(p)return vn(8,1,e,t);try{return dr(t,0,136),Q[t>>2]=1,Q[t+4>>2]=2,Q[t+8>>2]=3,Q[t+12>>2]=4,0}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function lt(e,t,n){if(p)return vn(9,1,e,t,n);nt=n;try{var r=it(e);switch(t){case 21509:case 21505:case 21510:case 21511:case 21512:case 21506:case 21507:case 21508:case 21523:case 21524:return r.tty?0:-59;case 21519:if(!r.tty)return-59;var i=rt();return Q[i>>2]=0;case 21520:return r.tty?-28:-59;case 21531:return i=rt(),Ke.Uf(r,t,i);default:he("bad ioctl syscall "+t)}}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function dt(e,t){if(p)return vn(10,1,e,t);try{return e=R(e),tt(Ke.lstat,e,t)}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function ht(e,t){if(p)return vn(11,1,e,t);try{return"/"===(e=Ue(e=R(e)))[e.length-1]&&(e=e.substr(0,e.length-1)),Ke.mkdir(e,t,0),0}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function pt(e,t,n,r,i,a){if(p)return vn(12,1,e,t,n,r,i,a);try{e:{a<<=12;var f=!1;if(0!=(16&r)&&0!=e%16384)var o=-28;else{if(0!=(32&r)){var u=fr(16384,t);if(!u){o=-48;break e}dr(u,0,t),f=!0}else{var c=Ke.zf(i);if(!c){o=-8;break e}var s=Ke.Wf(c,e,t,a,n,r);u=s.Hi,f=s.Jg}et[u]={xi:u,ui:t,Jg:f,fd:i,Gi:n,flags:r,offset:a},o=u}}return o}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function mt(e,t){if(p)return vn(13,1,e,t);try{if(-1==(0|e)||0===t)var n=-28;else{var r=et[e];if(r&&t===r.ui){var i=Ke.zf(r.fd);if(2&r.Gi){var a=r.flags,f=r.offset,o=Y.slice(e,e+t);Ke.Xf(i,o,f,t,a)}et[e]=null,r.Jg&&rr(r.xi)}n=0}return n}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function gt(e,t,n){if(p)return vn(14,1,e,t,n);nt=n;try{var r=R(e),i=rt();return Ke.open(r,t,i).fd}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function wt(e,t,n){if(p)return vn(15,1,e,t,n);try{for(var r=n=0;r>1],f=32,o=Ke.zf(Q[i>>2]);o&&(f=5,o.df.Zf&&(f=o.df.Zf(o))),(f&=24|a)&&n++,X[i+6>>1]=f}return n}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function yt(e,t,n,r){if(p)return vn(16,1,e,t,n,r);try{return r&&(Q[r>>2]=-1,Q[r+4>>2]=-1,Q[r+8>>2]=-1,Q[r+12>>2]=-1),0}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function vt(e,t,n){if(p)return vn(17,1,e,t,n);try{var r=it(e);return Ke.read(r,H,t,n)}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function bt(e,t){if(p)return vn(18,1,e,t);try{return e=R(e),t=R(t),Ke.rename(e,t),0}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function _t(e){if(p)return vn(19,1,e);try{return e=R(e),Ke.rmdir(e),0}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}var kt={jf:function(){return n.websocket=n.websocket&&"object"==typeof n.websocket?n.websocket:{},n.websocket.Ig={},n.websocket.on=function(e,t){return"function"==typeof t&&(this.Ig[e]=t),this},n.websocket.emit=function(e,t){"function"==typeof this.Ig[e]&&this.Ig[e].call(this,t)},Ke.createNode(null,"/",16895,0)},createSocket:function(e,t,n){return t&=-526337,n&&O(1==t==(6==n)),e={family:e,type:t,protocol:n,lf:null,error:null,ng:{},pending:[],ag:[],pf:kt.qf},t=kt.zg(),(n=Ke.createNode(kt.root,t,49152,0)).bg=e,t=Ke.nh({path:t,node:n,flags:Ke.Dh("r+"),seekable:!1,df:kt.df}),e.stream=t,e},mi:function(e){return(e=Ke.zf(e))&&Ke.isSocket(e.node.mode)?e.node.bg:null},df:{Zf:function(e){return(e=e.node.bg).pf.Zf(e)},Uf:function(e,t,n){return(e=e.node.bg).pf.Uf(e,t,n)},read:function(e,t,n,r){return(r=(e=e.node.bg).pf.bh(e,r))?(t.set(r.buffer,n),r.buffer.length):0},write:function(e,t,n,r){return(e=e.node.bg).pf.fh(e,t,n,r)},close:function(e){(e=e.node.bg).pf.close(e)}},zg:function(){return kt.zg.current||(kt.zg.current=0),"socket["+kt.zg.current+++"]"},qf:{tg:function(e,t,r){if("object"==typeof t){var i=t;r=t=null}if(i)if(i._socket)t=i._socket.remoteAddress,r=i._socket.remotePort;else{if(!(r=/ws[s]?:\/\/([^:]+):(\d+)/.exec(i.url)))throw Error("WebSocket URL must be in the format ws(s)://address:port");t=r[1],r=parseInt(r[2],10)}else try{var a=n.websocket&&"object"==typeof n.websocket,f="ws:#".replace("#","//");if(a&&"string"==typeof n.websocket.url&&(f=n.websocket.url),"ws://"===f||"wss://"===f){var o=t.split("/");f=f+o[0]+":"+r+"/"+o.slice(1).join("/")}o="binary",a&&"string"==typeof n.websocket.subprotocol&&(o=n.websocket.subprotocol);var u=void 0;"null"!==o&&(o=o.replace(/^ +| +$/g,"").split(/ *, */),u=d?{protocol:o.toString()}:o),a&&null===n.websocket.subprotocol&&(u=void 0),(i=new(d?require("ws"):WebSocket)(f,u)).binaryType="arraybuffer"}catch(e){throw new Ke.af(23)}return t={hf:t,port:r,socket:i,ug:[]},kt.qf.jh(e,t),kt.qf.ni(e,t),2===e.type&&void 0!==e.Qf&&t.ug.push(new Uint8Array([255,255,255,255,112,111,114,116,(65280&e.Qf)>>8,255&e.Qf])),t},vg:function(e,t,n){return e.ng[t+":"+n]},jh:function(e,t){e.ng[t.hf+":"+t.port]=t},Hh:function(e,t){delete e.ng[t.hf+":"+t.port]},ni:function(e,t){function r(){n.websocket.emit("open",e.stream.fd);try{for(var r=t.ug.shift();r;)t.socket.send(r),r=t.ug.shift()}catch(e){t.socket.close()}}function i(r){if("string"==typeof r)r=(new TextEncoder).encode(r);else{if(O(void 0!==r.byteLength),0==r.byteLength)return;r=new Uint8Array(r)}var i=a;a=!1,i&&10===r.length&&255===r[0]&&255===r[1]&&255===r[2]&&255===r[3]&&112===r[4]&&111===r[5]&&114===r[6]&&116===r[7]?(r=r[8]<<8|r[9],kt.qf.Hh(e,t),t.port=r,kt.qf.jh(e,t)):(e.ag.push({hf:t.hf,port:t.port,data:r}),n.websocket.emit("message",e.stream.fd))}var a=!0;d?(t.socket.on("open",r),t.socket.on("message",(function(e,t){t.Yi&&i(new Uint8Array(e).buffer)})),t.socket.on("close",(function(){n.websocket.emit("close",e.stream.fd)})),t.socket.on("error",(function(){e.error=14,n.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])}))):(t.socket.onopen=r,t.socket.onclose=function(){n.websocket.emit("close",e.stream.fd)},t.socket.onmessage=function(e){i(e.data)},t.socket.onerror=function(){e.error=14,n.websocket.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})},Zf:function(e){if(1===e.type&&e.lf)return e.pending.length?65:0;var t=0,n=1===e.type?kt.qf.vg(e,e.sf,e.vf):null;return(e.ag.length||!n||n&&n.socket.readyState===n.socket.CLOSING||n&&n.socket.readyState===n.socket.CLOSED)&&(t|=65),(!n||n&&n.socket.readyState===n.socket.OPEN)&&(t|=4),(n&&n.socket.readyState===n.socket.CLOSING||n&&n.socket.readyState===n.socket.CLOSED)&&(t|=16),t},Uf:function(e,t,n){return 21531===t?(t=0,e.ag.length&&(t=e.ag[0].data.length),Q[n>>2]=t,0):28},close:function(e){if(e.lf){try{e.lf.close()}catch(e){}e.lf=null}for(var t=Object.keys(e.ng),n=0;nt;t++){var n=Number(e[t]);if(isNaN(n))return null;e[t]=n}return(e[0]|e[1]<<8|e[2]<<16|e[3]<<24)>>>0}function xt(e){var t,n,r=[];if(!/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i.test(e))return null;if("::"===e)return[0,0,0,0,0,0,0,0];for(0<(e=0===e.indexOf("::")?e.replace("::","Z:"):e.replace("::",":Z:")).indexOf(".")?((e=(e=e.replace(/[.]/g,":")).split(":"))[e.length-4]=parseInt(e[e.length-4])+256*parseInt(e[e.length-3]),e[e.length-3]=parseInt(e[e.length-2])+256*parseInt(e[e.length-1]),e=e.slice(0,e.length-2)):e=e.split(":"),t=n=0;t(t=Et++),"exceeded max address mappings of 65535"),St[t="172.29."+(255&t)+"."+(65280&t)]=e,jt[e]=t),t)}function Tt(e){return St[e]?St[e]:null}function Dt(e){return(255&e)+"."+(e>>8&255)+"."+(e>>16&255)+"."+(e>>24&255)}function Ct(e){var t,n="",r=0,i=0,a=0,f=0;e=[65535&e[0],e[0]>>16,65535&e[1],e[1]>>16,65535&e[2],e[2]>>16,65535&e[3],e[3]>>16];var o=!0;for(t=0;5>t;t++)if(0!==e[t]){o=!1;break}if(o){if(t=Dt(e[6]|e[7]<<16),-1===e[5])return"::ffff:"+t;if(0===e[5])return"0.0.0.0"===t&&(t=""),"0.0.0.1"===t&&(t="1"),"::"+t}for(t=0;8>t;t++)0===e[t]&&(1r&&(a=t-(r=f)+1);for(t=0;8>t;t++)1=a&&tt?":":"");return n}function Ft(e,t){var n=X[e>>1],r=or(V[e+2>>1]);switch(n){case 2:if(16!==t)return{ef:28};e=Dt(e=Q[e+4>>2]);break;case 10:if(28!==t)return{ef:28};e=Ct(e=[Q[e+8>>2],Q[e+12>>2],Q[e+16>>2],Q[e+20>>2]]);break;default:return{ef:5}}return{family:n,hf:e,port:r}}function Ot(e,t,n,r){switch(t){case 2:n=At(n),X[e>>1]=t,Q[e+4>>2]=n,X[e+2>>1]=ur(r);break;case 10:n=xt(n),Q[e>>2]=t,Q[e+8>>2]=n[0],Q[e+12>>2]=n[1],Q[e+16>>2]=n[2],Q[e+20>>2]=n[3],X[e+2>>1]=ur(r),Q[e+4>>2]=0,Q[e+24>>2]=0;break;default:return{ef:5}}return{}}function It(e,t){if(p)return vn(20,1,e,t);try{nt=t,t=function(){var e=kt.mi(rt());if(!e)throw new Ke.af(8);return e};var n=function(e){var t=rt(),n=rt();if(e&&0===t)return null;if((e=Ft(t,n)).ef)throw new Ke.af(e.ef);return e.hf=Tt(e.hf)||e.hf,e};switch(e){case 1:var r=rt(),i=rt(),a=rt(),f=kt.createSocket(r,i,a);return f.stream.fd;case 2:f=t();var o=n();return f.pf.bind(f,o.hf,o.port),0;case 3:return f=t(),o=n(),f.pf.connect(f,o.hf,o.port),0;case 4:f=t();var u=rt();return f.pf.listen(f,u),0;case 5:f=t();var c=rt();rt();var s=f.pf.accept(f);return c&&Ot(c,s.family,Mt(s.sf),s.vf),s.stream.fd;case 6:return f=t(),c=rt(),rt(),Ot(c,f.family,Mt(f.Bg||"0.0.0.0"),f.Qf),0;case 7:return f=t(),c=rt(),rt(),f.sf?(Ot(c,f.family,Mt(f.sf),f.vf),0):-53;case 11:f=t();var l=rt(),d=rt();rt();var h=n(!0);return h?f.pf.fh(f,H,l,d,h.hf,h.port):Ke.write(f.stream,H,l,d);case 12:f=t();var m=rt(),g=rt();rt(),c=rt(),rt();var w=f.pf.bh(f,g);return w?(c&&Ot(c,f.family,Mt(w.hf),w.port),Y.set(w.buffer,m),w.buffer.byteLength):0;case 14:return-50;case 15:f=t();var y=rt(),v=rt(),b=rt(),_=rt();return 1===y&&4===v?(Q[b>>2]=f.error,Q[_>>2]=4,f.error=null,0):-50;case 16:f=t(),l=rt(),rt();var k=Q[l+8>>2],A=Q[l+12>>2],x=Q[l>>2],E=Q[l+4>>2];if(x){if((o=Ft(x,E)).ef)return-o.ef;var j=o.port;c=Tt(o.hf)||o.hf}for(var S=0,M=0;M>2];var T=new Uint8Array(S);for(M=d=0;M>2],C=Q[k+(8*M+4)>>2];for(m=0;m>0]}return f.pf.fh(f,T,0,S,c,j);case 17:for(f=t(),l=rt(),rt(),k=Q[l+8>>2],A=Q[l+12>>2],M=S=0;M>2];if(!(w=f.pf.bh(f,S)))return 0;(x=Q[l>>2])&&Ot(x,f.family,Mt(w.hf),w.port),f=0;var F=w.buffer.byteLength;for(M=0;0>2],(C=Q[k+(8*M+4)>>2])&&(d=Math.min(C,F),m=w.buffer.subarray(f,f+d),Y.set(m,D+f),f+=d,F-=d);return f;default:return-52}}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function Pt(e,t){if(p)return vn(21,1,e,t);try{return e=R(e),tt(Ke.stat,e,t)}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function Lt(e){if(p)return vn(22,1,e);try{return e=R(e),Ke.unlink(e),0}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}}function Rt(){return void 0===Rt.start&&(Rt.start=Date.now()),1e3*(Date.now()-Rt.start)|0}function Nt(){d||l||(x||(x={}),x["Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread"]||(x["Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread"]=1,A("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")))}function Bt(e,t,n){if(0>=e||e>H.length||1&e)return-28;if(s){if(Atomics.load(Q,e>>2)!=t)return-6;var r=performance.now();for(n=r+n,Atomics.exchange(Q,Fe.Vf>>2,e);;){if((r=performance.now())>n)return Atomics.exchange(Q,Fe.Vf>>2,0),-73;if(0==(r=Atomics.exchange(Q,Fe.Vf>>2,0)))break;if(_r(),Atomics.load(Q,e>>2)!=t)return-6;Atomics.exchange(Q,Fe.Vf>>2,e)}return 0}if("timed-out"===(e=Atomics.wait(Q,e>>2,t,n)))return-73;if("not-equal"===e)return-6;if("ok"===e)return 0;throw"Atomics.wait returned an unexpected value "+e}function Ut(e){var t=e.getExtension("ANGLE_instanced_arrays");t&&(e.vertexAttribDivisor=function(e,n){t.vertexAttribDivisorANGLE(e,n)},e.drawArraysInstanced=function(e,n,r,i){t.drawArraysInstancedANGLE(e,n,r,i)},e.drawElementsInstanced=function(e,n,r,i,a){t.drawElementsInstancedANGLE(e,n,r,i,a)})}function zt(e){var t=e.getExtension("OES_vertex_array_object");t&&(e.createVertexArray=function(){return t.createVertexArrayOES()},e.deleteVertexArray=function(e){t.deleteVertexArrayOES(e)},e.bindVertexArray=function(e){t.bindVertexArrayOES(e)},e.isVertexArray=function(e){return t.isVertexArrayOES(e)})}function Gt(e){var t=e.getExtension("WEBGL_draw_buffers");t&&(e.drawBuffers=function(e,n){t.drawBuffersWEBGL(e,n)})}var Wt=1,qt=[],Ht=[],Yt=[],Xt=[],Vt=[],Qt=[],Jt=[],$t=[],Zt=[],Kt={},en={},tn=4;function nn(e){fn||(fn=e)}function rn(e){for(var t=Wt++,n=e.length;n>2]=f}}function sn(e,t,n,r,i,a,f,o){t=Ht[t],(e=Qn[e](t,n))&&(r=o&&B(e.name,o,r),i&&(Q[i>>2]=r),a&&(Q[a>>2]=e.size),f&&(Q[f>>2]=e.type))}function ln(e,t){J[e>>2]=t,J[e+4>>2]=(t-J[e>>2])/4294967296}function dn(e,t,n){if(t){var r=void 0;switch(e){case 36346:r=1;break;case 36344:return void(0!=n&&1!=n&&nn(1280));case 36345:r=0;break;case 34466:var i=Qn.getParameter(34467);r=i?i.length:0}if(void 0===r)switch(i=Qn.getParameter(e),typeof i){case"number":r=i;break;case"boolean":r=i?1:0;break;case"string":return void nn(1280);case"object":if(null===i)switch(e){case 34964:case 35725:case 34965:case 36006:case 36007:case 32873:case 34229:case 34068:r=0;break;default:return void nn(1280)}else{if(i instanceof Float32Array||i instanceof Uint32Array||i instanceof Int32Array||i instanceof Array){for(e=0;e>2]=i[e];break;case 2:$[t+4*e>>2]=i[e];break;case 4:H[t+e>>0]=i[e]?1:0}return}try{r=0|i.name}catch(t){return nn(1280),void A("GL_INVALID_ENUM in glGet"+n+"v: Unknown object returned from WebGL getParameter("+e+")! (error: "+t+")")}}break;default:return nn(1280),void A("GL_INVALID_ENUM in glGet"+n+"v: Native code calling glGet"+n+"v("+e+") and it returns "+i+" of type "+typeof i+"!")}switch(n){case 1:ln(t,r);break;case 0:Q[t>>2]=r;break;case 2:$[t>>2]=r;break;case 4:H[t>>0]=r?1:0}}else nn(1281)}function hn(e){var t=U(e)+1,n=ir(t);return B(e,n,t),n}function pn(e,t,n,r){if(n)if("number"==typeof(e=Qn.getUniform(Ht[e],Qt[t]))||"boolean"==typeof e)switch(r){case 0:Q[n>>2]=e;break;case 2:$[n>>2]=e}else for(t=0;t>2]=e[t];break;case 2:$[n+4*t>>2]=e[t]}else nn(1281)}function mn(e,t,n,r){if(n)if(e=Qn.getVertexAttrib(e,t),34975==t)Q[n>>2]=e&&e.name;else if("number"==typeof e||"boolean"==typeof e)switch(r){case 0:Q[n>>2]=e;break;case 2:$[n>>2]=e;break;case 5:Q[n>>2]=Math.fround(e)}else for(t=0;t>2]=e[t];break;case 2:$[n+4*t>>2]=e[t];break;case 5:Q[n+4*t>>2]=Math.fround(e[t])}else nn(1281)}function gn(e,t,n,r,i){e=1==(e-=5120)?Y:4==e?Q:6==e?$:5==e||28922==e?J:V;var a=31-Math.clz32(e.BYTES_PER_ELEMENT),f=tn;return e.subarray(i>>a,i+r*(n*({5:3,6:4,8:2,29502:3,29504:4}[t-6402]||1)*(1<>a)}var wn=[],yn=[];function vn(e,t){for(var n=arguments.length-2,r=gr(),i=yr(8*n),a=i>>3,f=0;f>2]=t,Q[r.sg+4>>2]=n),!r.Fh&&r.aj){if(r.sg){e=e?R(e):"",r=Q[r.sg+8>>2];var i=gr(),a=yr(12),f=0;return e&&(f=hn(e)),Q[a>>2]=f,Q[a+4>>2]=t,Q[a+8>>2]=n,jr(0,r,657457152,0,f,a),wr(i),1}return-4}return r.Fh&&(r=r.Fh),e=!1,r.rg&&r.rg.qg&&(e=0===(e=r.rg.qg.getParameter(2978))[0]&&0===e[1]&&e[2]===r.width&&e[3]===r.height),r.width=t,r.height=n,e&&r.rg.qg.viewport(0,0,t,n),0}function En(e,t,n){return p?vn(23,1,e,t,n):xn(e,t,n)}var jn,Sn=["default","low-power","high-performance"],Mn={};function Tn(){if(!jn){var e,t={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:u||"./this.program"};for(e in Mn)t[e]=Mn[e];var n=[];for(e in t)n.push(e+"="+t[e]);jn=n}return jn}function Dn(e){if(p)return vn(24,1,e);try{var t=it(e);return Ke.close(t),0}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),e.ef}}function Cn(e,t){if(p)return vn(25,1,e,t);try{var n=it(e);return H[t>>0]=n.tty?2:Ke.kf(n.mode)?3:Ke.Mf(n.mode)?7:4,0}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),e.ef}}function Fn(e,t,n,r){if(p)return vn(26,1,e,t,n,r);try{e:{for(var i=it(e),a=e=0;a>2],o=Ke.read(i,H,Q[t+8*a>>2],f,void 0);if(0>o){var u=-1;break e}if(e+=o,o>2]=u,0}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),e.ef}}function On(e,t,n,r,i){if(p)return vn(27,1,e,t,n,r,i);try{var a=it(e);return-9007199254740992>=(e=4294967296*n+(t>>>0))||9007199254740992<=e?-61:(Ke.tf(a,e,r),be=[a.position>>>0,(ve=a.position,1<=+Math.abs(ve)?0>>0:~~+Math.ceil((ve-+(~~ve>>>0))/4294967296)>>>0:0)],Q[i>>2]=be[0],Q[i+4>>2]=be[1],a.Lf&&0===e&&0===r&&(a.Lf=null),0)}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),e.ef}}function In(e,t,n,r){if(p)return vn(28,1,e,t,n,r);try{e:{for(var i=it(e),a=e=0;a>2],Q[t+(8*a+4)>>2],void 0);if(0>f){var o=-1;break e}e+=f}o=e}return Q[r>>2]=o,0}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),e.ef}}var Pn={};function Ln(e){Ln.buffer||(Ln.buffer=ir(256),Pn[0]="Success",Pn[-1]="Invalid value for 'ai_flags' field",Pn[-2]="NAME or SERVICE is unknown",Pn[-3]="Temporary failure in name resolution",Pn[-4]="Non-recoverable failure in name res",Pn[-6]="'ai_family' not supported",Pn[-7]="'ai_socktype' not supported",Pn[-8]="SERVICE not supported for 'ai_socktype'",Pn[-10]="Memory allocation failure",Pn[-11]="System error returned in 'errno'",Pn[-12]="Argument buffer overflow");var t="Unknown error";return e in Pn&&(t=255>2]=e,Q[i+8>>2]=t,Q[i+12>>2]=n,Q[i+24>>2]=r,Q[i+20>>2]=f,Q[i+16>>2]=10===e?28:16,Q[i+28>>2]=0,i}if(p)return vn(29,1,e,t,n,r);var a=0,f=0,o=0,u=0,c=0,s=0;if(n&&(o=Q[n>>2],u=Q[n+4>>2],c=Q[n+8>>2],s=Q[n+12>>2]),c&&!s&&(s=2===c?17:6),!c&&s&&(c=17===s?2:1),0===s&&(s=6),0===c&&(c=1),!e&&!t)return-2;if(-1088&o||0!==n&&2&Q[n>>2]&&!e)return-1;if(32&o)return-2;if(0!==c&&1!==c&&2!==c)return-7;if(0!==u&&2!==u&&10!==u)return-6;if(t&&(t=R(t),f=parseInt(t,10),isNaN(f)))return 1024&o?-2:-8;if(!e)return 0===u&&(u=2),0==(1&o)&&(a=2===u?lr(2130706433):[0,0,0,1]),e=i(u,c,s,null,a,f),Q[r>>2]=e,0;if(null!==(a=At(e=R(e))))if(0===u||2===u)u=2;else{if(!(10===u&&8&o))return-2;a=[0,0,lr(65535),a],u=10}else if(null!==(a=xt(e))){if(0!==u&&10!==u)return-2;u=10}return null!=a?(e=i(u,c,s,e,a,f),Q[r>>2]=e,0):4&o?-2:(a=At(e=Mt(e)),0===u?u=2:10===u&&(a=[0,0,lr(65535),a]),e=i(u,c,s,null,a,f),Q[r>>2]=e,0)}function Nn(e){if(p)throw"Internal Error! spawnThread() can only ever be called from main application thread!";var t=Fe.li();if(void 0!==t.yf)throw"Internal error!";if(!e.$f)throw"Internal error, no pthread ptr!";Fe.Kf.push(t);for(var n=ir(512),r=0;128>r;++r)Q[n+4*r>>2]=0;var i=e.Rf+e.cg,a=(r=Fe.Ef[e.$f]={worker:t,Rf:e.Rf,cg:e.cg,Kg:e.Kg,Lh:e.$f,threadInfoStruct:e.$f}).threadInfoStruct>>2;Atomics.store(J,a,0),Atomics.store(J,a+1,0),Atomics.store(J,a+2,0),Atomics.store(J,a+17,e.detached),Atomics.store(J,a+26,n),Atomics.store(J,a+12,0),Atomics.store(J,a+10,r.threadInfoStruct),Atomics.store(J,a+11,42),Atomics.store(J,a+27,e.cg),Atomics.store(J,a+21,e.cg),Atomics.store(J,a+20,i),Atomics.store(J,a+29,i),Atomics.store(J,a+30,e.detached),Atomics.store(J,a+32,e.Ih),Atomics.store(J,a+33,e.Jh),n=sr()+40,Atomics.store(J,a+44,n),t.yf=r;var f={cmd:"run",start_routine:e.Mi,arg:e.Tf,threadInfoStruct:e.$f,selfThreadId:e.$f,parentThreadId:e.Fi,stackBase:e.Rf,stackSize:e.cg};t.og=function(){f.time=performance.now(),t.postMessage(f,e.Vi)},t.loaded&&(t.og(),delete t.og)}function Bn(){return 0|xe}function Un(e,t){if(!e)return A("pthread_join attempted on a null thread pointer!"),71;if(p&&C==e)return A("PThread "+e+" is attempting to join to itself!"),16;if(!p&&Fe.xf==e)return A("Main thread "+e+" is attempting to join to itself!"),16;if(Q[e+12>>2]!==e)return A("pthread_join attempted on thread "+e+", which does not point to a valid thread, or does not exist anymore!"),71;if(Atomics.load(J,e+68>>2))return A("Attempted to join thread "+e+", which was already detached!"),28;for(Nt();;){var n=Atomics.load(J,e>>2);if(1==n)return n=Atomics.load(J,e+4>>2),t&&(Q[t>>2]=n),Atomics.store(J,e+68>>2,1),p?postMessage({cmd:"cleanupThread",thread:e}):De(e),0;if(p&&D&&!Atomics.load(J,D+60>>2)&&2==Atomics.load(J,D+0>>2))throw"Canceled!";p||_r(),Bt(e,n,p?100:1)}}function zn(e){return 0==e%4&&(0!=e%100||0==e%400)}function Gn(e,t){for(var n=0,r=0;r<=t;n+=e[r++]);return n}n._pthread_self=Bn;var Wn=[31,29,31,30,31,30,31,31,30,31,30,31],qn=[31,28,31,30,31,30,31,31,30,31,30,31];function Hn(e,t){for(e=new Date(e.getTime());0r-e.getDate())){e.setDate(e.getDate()+t);break}t-=r-e.getDate()+1,e.setDate(1),11>n?e.setMonth(n+1):(e.setMonth(0),e.setFullYear(e.getFullYear()+1))}return e}function Yn(e){if(p)return vn(30,1,e);switch(e){case 30:case 75:return 16384;case 85:return Y.length/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 80:case 81:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:case 79:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return"object"==typeof navigator&&navigator.hardwareConcurrency||1}return Oe(28),-1}function Xn(e,t,n,r){e||(e=this),this.parent=e,this.jf=e.jf,this.lg=null,this.id=Ke.Ai++,this.name=t,this.mode=n,this.cf={},this.df={},this.rdev=r}Object.defineProperties(Xn.prototype,{read:{get:function(){return 365==(365&this.mode)},set:function(e){e?this.mode|=365:this.mode&=-366}},write:{get:function(){return 146==(146&this.mode)},set:function(e){e?this.mode|=146:this.mode&=-147}},ti:{get:function(){return Ke.kf(this.mode)}},Ug:{get:function(){return Ke.hg(this.mode)}}}),Ke.Oh=Xn,Ke.Ni();for(var Vn,Qn,Jn=0;32>Jn;++Jn)un.push(Array(Jn));var $n=new Float32Array(288);for(Jn=0;288>Jn;++Jn)wn[Jn]=$n.subarray(0,Jn+1);var Zn=new Int32Array(288);for(Jn=0;288>Jn;++Jn)yn[Jn]=Zn.subarray(0,Jn+1);var Kn=[null,Pe,Re,at,ft,ot,ut,ct,st,lt,dt,ht,pt,mt,gt,wt,yt,vt,bt,_t,It,Pt,Lt,En,Dn,Cn,Fn,On,In,Rn,Yn];function er(e,t){var n=Array(U(e)+1);return e=N(e,n,0,n.length),t&&(n.length=e),n}p||re.push({vh:function(){nr()}});var tr={c:function(e,t,n,r){he("Assertion failed: "+R(e)+", at: "+[t?R(t):"unknown filename",n,r?R(r):"unknown function"])},K:function(e,t){if(e=cr(e,t),!j)return postMessage({cmd:"exitProcess",returnCode:e}),e},W:function(e,t){return Ie(e,t)},aa:function(e,t){return Pe(e,t)},va:function(e,t){return Le(e,t)},ua:function(e,t){return Ne(e,t)},Ma:at,Ea:ft,u:ot,Na:ut,Ka:ct,Ha:st,V:lt,Oa:dt,Pa:ht,ya:pt,Aa:function(){return 0},za:mt,Da:function(){return-63},Y:gt,La:wt,Ja:yt,Ca:vt,wa:bt,Ga:_t,Ia:function(){return 0},t:It,X:Pt,Fa:function(e){try{if(!e)return-21;var t={__size__:390,sysname:0,nodename:65,release:130,version:195,machine:260,domainname:325};return W("Emscripten",e+t.sysname),W("emscripten",e+t.nodename),W("1.0",e+t.release),W("#1",e+t.version),W("x86-JS",e+t.machine),0}catch(e){return void 0!==Ke&&e instanceof Ke.af||he(e),-e.ef}},Ba:Lt,pa:function(e,t){if(e==t)postMessage({cmd:"processQueuedMainThreadWork"});else if(p)postMessage({targetThread:e,cmd:"processThreadQueue"});else{if(!(e=(e=Fe.Ef[e])&&e.worker))return;e.postMessage({cmd:"processThreadQueue"})}return 1},b:function(){he()},Qa:Rt,Ta:Ie,$:function(){he("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ua:function(){he("To use dlopen, you need to use Emscripten's linking support, see https://github.com/emscripten-core/emscripten/wiki/Linking")},F:function(e,t,n){var r;for(_n.length=0,n>>=2;r=Y[t++];)(r=105>r)&&1&n&&n++,_n.push(r?Z[n++>>1]:Q[n]),++n;return _e[e].apply(null,_n)},qa:Nt,I:function(){},A:Bt,p:Me,z:Ce,Ed:function(e){Qn.activeTexture(e)},Dd:function(e,t){Qn.attachShader(Ht[e],Jt[t])},ea:function(e,t){Qn.uf.beginQueryEXT(e,Zt[t])},Cd:function(e,t,n){Qn.bindAttribLocation(Ht[e],t,R(n))},Bd:function(e,t){Qn.bindBuffer(e,qt[t])},Ad:function(e,t){Qn.bindFramebuffer(e,Yt[t])},zd:function(e,t){Qn.bindRenderbuffer(e,Xt[t])},yd:function(e,t){Qn.bindTexture(e,Vt[t])},Md:function(e){Qn.bindVertexArray($t[e])},xd:function(e,t,n,r){Qn.blendColor(e,t,n,r)},wd:function(e){Qn.blendEquation(e)},vd:function(e,t){Qn.blendEquationSeparate(e,t)},ud:function(e,t){Qn.blendFunc(e,t)},td:function(e,t,n,r){Qn.blendFuncSeparate(e,t,n,r)},sd:function(e,t,n,r){Qn.bufferData(e,n?Y.subarray(n,n+t):t,r)},rd:function(e,t,n,r){Qn.bufferSubData(e,t,Y.subarray(r,r+n))},qd:function(e){return Qn.checkFramebufferStatus(e)},pd:function(e){Qn.clear(e)},od:function(e,t,n,r){Qn.clearColor(e,t,n,r)},nd:function(e){Qn.clearDepth(e)},md:function(e){Qn.clearStencil(e)},ld:function(e,t,n,r){Qn.colorMask(!!e,!!t,!!n,!!r)},kd:function(e){Qn.compileShader(Jt[e])},jd:function(e,t,n,r,i,a,f,o){Qn.compressedTexImage2D(e,t,n,r,i,a,o?Y.subarray(o,o+f):null)},id:function(e,t,n,r,i,a,f,o,u){Qn.compressedTexSubImage2D(e,t,n,r,i,a,f,u?Y.subarray(u,u+o):null)},hd:function(e,t,n,r,i,a,f,o){Qn.copyTexImage2D(e,t,n,r,i,a,f,o)},gd:function(e,t,n,r,i,a,f,o){Qn.copyTexSubImage2D(e,t,n,r,i,a,f,o)},fd:function(){var e=rn(Ht),t=Qn.createProgram();return t.name=e,Ht[e]=t,e},ed:function(e){var t=rn(Jt);return Jt[t]=Qn.createShader(e),t},dd:function(e){Qn.cullFace(e)},cd:function(e,t){for(var n=0;n>2],i=qt[r];i&&(Qn.deleteBuffer(i),i.name=0,qt[r]=null)}},bd:function(e,t){for(var n=0;n>2],i=Yt[r];i&&(Qn.deleteFramebuffer(i),i.name=0,Yt[r]=null)}},ad:function(e){if(e){var t=Ht[e];t?(Qn.deleteProgram(t),t.name=0,Ht[e]=null,Kt[e]=null):nn(1281)}},ga:function(e,t){for(var n=0;n>2],i=Zt[r];i&&(Qn.uf.deleteQueryEXT(i),Zt[r]=null)}},$c:function(e,t){for(var n=0;n>2],i=Xt[r];i&&(Qn.deleteRenderbuffer(i),i.name=0,Xt[r]=null)}},_c:function(e){if(e){var t=Jt[e];t?(Qn.deleteShader(t),Jt[e]=null):nn(1281)}},Zc:function(e,t){for(var n=0;n>2],i=Vt[r];i&&(Qn.deleteTexture(i),i.name=0,Vt[r]=null)}},Ld:function(e,t){for(var n=0;n>2];Qn.deleteVertexArray($t[r]),$t[r]=null}},Yc:function(e){Qn.depthFunc(e)},Xc:function(e){Qn.depthMask(!!e)},Wc:function(e,t){Qn.depthRange(e,t)},Vc:function(e,t){Qn.detachShader(Ht[e],Jt[t])},Uc:function(e){Qn.disable(e)},Tc:function(e){Qn.disableVertexAttribArray(e)},Sc:function(e,t,n){Qn.drawArrays(e,t,n)},Hd:function(e,t,n,r){Qn.drawArraysInstanced(e,t,n,r)},Id:function(e,t){for(var n=un[e],r=0;r>2];Qn.drawBuffers(n)},Rc:function(e,t,n,r){Qn.drawElements(e,t,n,r)},Gd:function(e,t,n,r,i){Qn.drawElementsInstanced(e,t,n,r,i)},Qc:function(e){Qn.enable(e)},Pc:function(e){Qn.enableVertexAttribArray(e)},da:function(e){Qn.uf.endQueryEXT(e)},Oc:function(){Qn.finish()},Nc:function(){Qn.flush()},Mc:function(e,t,n,r){Qn.framebufferRenderbuffer(e,t,n,Xt[r])},Lc:function(e,t,n,r,i){Qn.framebufferTexture2D(e,t,n,Vt[r],i)},Kc:function(e){Qn.frontFace(e)},Jc:function(e,t){cn(e,t,"createBuffer",qt)},Hc:function(e,t){cn(e,t,"createFramebuffer",Yt)},ha:function(e,t){for(var n=0;n>2]=0;break}var i=rn(Zt);r.name=i,Zt[i]=r,Q[t+4*n>>2]=i}},Gc:function(e,t){cn(e,t,"createRenderbuffer",Xt)},Fc:function(e,t){cn(e,t,"createTexture",Vt)},Kd:function(e,t){cn(e,t,"createVertexArray",$t)},Ic:function(e){Qn.generateMipmap(e)},Ec:function(e,t,n,r,i,a,f){sn("getActiveAttrib",e,t,n,r,i,a,f)},Dc:function(e,t,n,r,i,a,f){sn("getActiveUniform",e,t,n,r,i,a,f)},Cc:function(e,t,n,r){var i=(e=Qn.getAttachedShaders(Ht[e])).length;for(i>t&&(i=t),Q[n>>2]=i,t=0;t>2]=Jt.indexOf(e[t])},Bc:function(e,t){return Qn.getAttribLocation(Ht[e],R(t))},Ac:function(e,t){dn(e,t,4)},zc:function(e,t,n){n?Q[n>>2]=Qn.getBufferParameter(e,t):nn(1281)},yc:function(){var e=Qn.getError()||fn;return fn=0,e},xc:function(e,t){dn(e,t,2)},wc:function(e,t,n,r){((e=Qn.getFramebufferAttachmentParameter(e,t,n))instanceof WebGLRenderbuffer||e instanceof WebGLTexture)&&(e=0|e.name),Q[r>>2]=e},vc:function(e,t){dn(e,t,0)},tc:function(e,t,n,r){null===(e=Qn.getProgramInfoLog(Ht[e]))&&(e="(unknown error)"),t=0>2]=t)},uc:function(e,t,n){if(n)if(e>=Wt)nn(1281);else{var r=Kt[e];if(r)if(35716==t)null===(e=Qn.getProgramInfoLog(Ht[e]))&&(e="(unknown error)"),Q[n>>2]=e.length+1;else if(35719==t)Q[n>>2]=r.Xg;else if(35722==t){if(-1==r.jg){e=Ht[e];var i=Qn.getProgramParameter(e,35721);for(t=r.jg=0;t>2]=r.jg}else if(35381==t){if(-1==r.kg)for(e=Ht[e],i=Qn.getProgramParameter(e,35382),t=r.kg=0;t>2]=r.kg}else Q[n>>2]=Qn.getProgramParameter(Ht[e],t);else nn(1282)}else nn(1281)},Od:function(e,t,n){n?ln(n,"boolean"==typeof(e=Qn.uf.getQueryObjectEXT(Zt[e],t))?e?1:0:e):nn(1281)},Qd:function(e,t,n){var r;n?(r="boolean"==typeof(e=Qn.uf.getQueryObjectEXT(Zt[e],t))?e?1:0:e,Q[n>>2]=r):nn(1281)},Nd:function(e,t,n){n?ln(n,"boolean"==typeof(e=Qn.uf.getQueryObjectEXT(Zt[e],t))?e?1:0:e):nn(1281)},Pd:function(e,t,n){var r;n?(r="boolean"==typeof(e=Qn.uf.getQueryObjectEXT(Zt[e],t))?e?1:0:e,Q[n>>2]=r):nn(1281)},Rd:function(e,t,n){n?Q[n>>2]=Qn.uf.getQueryEXT(e,t):nn(1281)},sc:function(e,t,n){n?Q[n>>2]=Qn.getRenderbufferParameter(e,t):nn(1281)},qc:function(e,t,n,r){null===(e=Qn.getShaderInfoLog(Jt[e]))&&(e="(unknown error)"),t=0>2]=t)},pc:function(e,t,n,r){e=Qn.getShaderPrecisionFormat(e,t),Q[n>>2]=e.rangeMin,Q[n+4>>2]=e.rangeMax,Q[r>>2]=e.precision},oc:function(e,t,n,r){(e=Qn.getShaderSource(Jt[e]))&&(t=0>2]=t))},rc:function(e,t,n){n?35716==t?(null===(e=Qn.getShaderInfoLog(Jt[e]))&&(e="(unknown error)"),Q[n>>2]=e?e.length+1:0):35720==t?(e=Qn.getShaderSource(Jt[e]),Q[n>>2]=e?e.length+1:0):Q[n>>2]=Qn.getShaderParameter(Jt[e],t):nn(1281)},nc:function(e){if(en[e])return en[e];switch(e){case 7939:var t=Qn.getSupportedExtensions()||[];t=hn((t=t.concat(t.map((function(e){return"GL_"+e})))).join(" "));break;case 7936:case 7937:case 37445:case 37446:(t=Qn.getParameter(e))||nn(1280),t=hn(t);break;case 7938:t=hn("OpenGL ES 2.0 ("+Qn.getParameter(7938)+")");break;case 35724:var n=(t=Qn.getParameter(35724)).match(/^WebGL GLSL ES ([0-9]\.[0-9][0-9]?)(?:$| .*)/);null!==n&&(3==n[1].length&&(n[1]+="0"),t="OpenGL ES GLSL ES "+n[1]+" ("+t+")"),t=hn(t);break;default:return nn(1280),0}return en[e]=t},mc:function(e,t,n){n?$[n>>2]=Qn.getTexParameter(e,t):nn(1281)},lc:function(e,t,n){n?Q[n>>2]=Qn.getTexParameter(e,t):nn(1281)},ic:function(e,t){var n=0;if("]"==(t=R(t))[t.length-1]){var r=t.lastIndexOf("[");n="]"!=t[r+1]?parseInt(t.slice(r+1)):0,t=t.slice(0,r)}return(e=Kt[e]&&Kt[e].Nh[t])&&0<=n&&n>2]=Qn.getVertexAttribOffset(e,t):nn(1281)},hc:function(e,t,n){mn(e,t,n,2)},gc:function(e,t,n){mn(e,t,n,5)},ec:function(e,t){Qn.hint(e,t)},dc:function(e){return(e=qt[e])?Qn.isBuffer(e):0},cc:function(e){return Qn.isEnabled(e)},bc:function(e){return(e=Yt[e])?Qn.isFramebuffer(e):0},ac:function(e){return(e=Ht[e])?Qn.isProgram(e):0},fa:function(e){return(e=Zt[e])?Qn.uf.isQueryEXT(e):0},$b:function(e){return(e=Xt[e])?Qn.isRenderbuffer(e):0},_b:function(e){return(e=Jt[e])?Qn.isShader(e):0},Zb:function(e){return(e=Vt[e])?Qn.isTexture(e):0},Jd:function(e){return(e=$t[e])?Qn.isVertexArray(e):0},Yb:function(e){Qn.lineWidth(e)},Xb:function(e){Qn.linkProgram(Ht[e]);for(var t=Ht[e],n=(e=Kt[e]={Nh:{},Xg:0,jg:-1,kg:-1}).Nh,r=Qn.getProgramParameter(t,35718),i=0;i>2]:-1;i+=R(Q[n+4*a>>2],0>f?void 0:f)}Qn.shaderSource(Jt[e],i)},Nb:function(e,t,n){Qn.stencilFunc(e,t,n)},Mb:function(e,t,n,r){Qn.stencilFuncSeparate(e,t,n,r)},Lb:function(e){Qn.stencilMask(e)},Kb:function(e,t){Qn.stencilMaskSeparate(e,t)},Jb:function(e,t,n){Qn.stencilOp(e,t,n)},Ib:function(e,t,n,r){Qn.stencilOpSeparate(e,t,n,r)},Hb:function(e,t,n,r,i,a,f,o,u){Qn.texImage2D(e,t,n,r,i,a,f,o,u?gn(o,f,r,i,u):null)},Gb:function(e,t,n){Qn.texParameterf(e,t,n)},Fb:function(e,t,n){Qn.texParameterf(e,t,$[n>>2])},Eb:function(e,t,n){Qn.texParameteri(e,t,n)},Db:function(e,t,n){Qn.texParameteri(e,t,Q[n>>2])},Cb:function(e,t,n,r,i,a,f,o,u){var c=null;u&&(c=gn(o,f,i,a,u)),Qn.texSubImage2D(e,t,n,r,i,a,f,o,c)},Bb:function(e,t){Qn.uniform1f(Qt[e],t)},Ab:function(e,t,n){if(288>=t)for(var r=wn[t-1],i=0;i>2];else r=$.subarray(n>>2,n+4*t>>2);Qn.uniform1fv(Qt[e],r)},zb:function(e,t){Qn.uniform1i(Qt[e],t)},yb:function(e,t,n){if(288>=t)for(var r=yn[t-1],i=0;i>2];else r=Q.subarray(n>>2,n+4*t>>2);Qn.uniform1iv(Qt[e],r)},xb:function(e,t,n){Qn.uniform2f(Qt[e],t,n)},wb:function(e,t,n){if(144>=t)for(var r=wn[2*t-1],i=0;i<2*t;i+=2)r[i]=$[n+4*i>>2],r[i+1]=$[n+(4*i+4)>>2];else r=$.subarray(n>>2,n+8*t>>2);Qn.uniform2fv(Qt[e],r)},vb:function(e,t,n){Qn.uniform2i(Qt[e],t,n)},ub:function(e,t,n){if(144>=t)for(var r=yn[2*t-1],i=0;i<2*t;i+=2)r[i]=Q[n+4*i>>2],r[i+1]=Q[n+(4*i+4)>>2];else r=Q.subarray(n>>2,n+8*t>>2);Qn.uniform2iv(Qt[e],r)},tb:function(e,t,n,r){Qn.uniform3f(Qt[e],t,n,r)},sb:function(e,t,n){if(96>=t)for(var r=wn[3*t-1],i=0;i<3*t;i+=3)r[i]=$[n+4*i>>2],r[i+1]=$[n+(4*i+4)>>2],r[i+2]=$[n+(4*i+8)>>2];else r=$.subarray(n>>2,n+12*t>>2);Qn.uniform3fv(Qt[e],r)},rb:function(e,t,n,r){Qn.uniform3i(Qt[e],t,n,r)},qb:function(e,t,n){if(96>=t)for(var r=yn[3*t-1],i=0;i<3*t;i+=3)r[i]=Q[n+4*i>>2],r[i+1]=Q[n+(4*i+4)>>2],r[i+2]=Q[n+(4*i+8)>>2];else r=Q.subarray(n>>2,n+12*t>>2);Qn.uniform3iv(Qt[e],r)},pb:function(e,t,n,r,i){Qn.uniform4f(Qt[e],t,n,r,i)},ob:function(e,t,n){if(72>=t){var r=wn[4*t-1];n>>=2;for(var i=0;i<4*t;i+=4){var a=n+i;r[i]=$[a],r[i+1]=$[a+1],r[i+2]=$[a+2],r[i+3]=$[a+3]}}else r=$.subarray(n>>2,n+16*t>>2);Qn.uniform4fv(Qt[e],r)},nb:function(e,t,n,r,i){Qn.uniform4i(Qt[e],t,n,r,i)},mb:function(e,t,n){if(72>=t)for(var r=yn[4*t-1],i=0;i<4*t;i+=4)r[i]=Q[n+4*i>>2],r[i+1]=Q[n+(4*i+4)>>2],r[i+2]=Q[n+(4*i+8)>>2],r[i+3]=Q[n+(4*i+12)>>2];else r=Q.subarray(n>>2,n+16*t>>2);Qn.uniform4iv(Qt[e],r)},lb:function(e,t,n,r){if(72>=t)for(var i=wn[4*t-1],a=0;a<4*t;a+=4)i[a]=$[r+4*a>>2],i[a+1]=$[r+(4*a+4)>>2],i[a+2]=$[r+(4*a+8)>>2],i[a+3]=$[r+(4*a+12)>>2];else i=$.subarray(r>>2,r+16*t>>2);Qn.uniformMatrix2fv(Qt[e],!!n,i)},kb:function(e,t,n,r){if(32>=t)for(var i=wn[9*t-1],a=0;a<9*t;a+=9)i[a]=$[r+4*a>>2],i[a+1]=$[r+(4*a+4)>>2],i[a+2]=$[r+(4*a+8)>>2],i[a+3]=$[r+(4*a+12)>>2],i[a+4]=$[r+(4*a+16)>>2],i[a+5]=$[r+(4*a+20)>>2],i[a+6]=$[r+(4*a+24)>>2],i[a+7]=$[r+(4*a+28)>>2],i[a+8]=$[r+(4*a+32)>>2];else i=$.subarray(r>>2,r+36*t>>2);Qn.uniformMatrix3fv(Qt[e],!!n,i)},jb:function(e,t,n,r){if(18>=t){var i=wn[16*t-1];r>>=2;for(var a=0;a<16*t;a+=16){var f=r+a;i[a]=$[f],i[a+1]=$[f+1],i[a+2]=$[f+2],i[a+3]=$[f+3],i[a+4]=$[f+4],i[a+5]=$[f+5],i[a+6]=$[f+6],i[a+7]=$[f+7],i[a+8]=$[f+8],i[a+9]=$[f+9],i[a+10]=$[f+10],i[a+11]=$[f+11],i[a+12]=$[f+12],i[a+13]=$[f+13],i[a+14]=$[f+14],i[a+15]=$[f+15]}}else i=$.subarray(r>>2,r+64*t>>2);Qn.uniformMatrix4fv(Qt[e],!!n,i)},ib:function(e){Qn.useProgram(Ht[e])},hb:function(e){Qn.validateProgram(Ht[e])},gb:function(e,t){Qn.vertexAttrib1f(e,t)},fb:function(e,t){Qn.vertexAttrib1f(e,$[t>>2])},eb:function(e,t,n){Qn.vertexAttrib2f(e,t,n)},db:function(e,t){Qn.vertexAttrib2f(e,$[t>>2],$[t+4>>2])},cb:function(e,t,n,r){Qn.vertexAttrib3f(e,t,n,r)},bb:function(e,t){Qn.vertexAttrib3f(e,$[t>>2],$[t+4>>2],$[t+8>>2])},ab:function(e,t,n,r,i){Qn.vertexAttrib4f(e,t,n,r,i)},$a:function(e,t){Qn.vertexAttrib4f(e,$[t>>2],$[t+4>>2],$[t+8>>2],$[t+12>>2])},Fd:function(e,t){Qn.vertexAttribDivisor(e,t)},_a:function(e,t,n,r,i,a){Qn.vertexAttribPointer(e,t,n,!!r,i,a)},Za:function(e,t,n,r){Qn.viewport(e,t,n,r)},ka:function(){return"undefined"!=typeof SharedArrayBuffer},G:function(){return 0|je},R:function(){return 0|Ee},f:function(e,t){throw vr(e,t||1),"longjmp"},ja:function(e,t,n){Y.copyWithin(e,t,t+n)},ma:function(e,t,n){bn.length=t,n>>=3;for(var r=0;re?_e[-e-1]:Kn[e]).apply(null,bn)},ra:function(){he("OOM")},na:function(e,t,n){return An(e)?xn(e,t,n):En(e,t,n)},Q:function(){},la:function(){},oa:function(e,t){var n={};if(t>>=2,n.alpha=!!Q[t],n.depth=!!Q[t+1],n.stencil=!!Q[t+2],n.antialias=!!Q[t+3],n.premultipliedAlpha=!!Q[t+4],n.preserveDrawingBuffer=!!Q[t+5],n.powerPreference=Sn[Q[t+6]],n.failIfMajorPerformanceCaveat=!!Q[t+7],n.wi=Q[t+8],n.pj=Q[t+9],n.qh=Q[t+10],n.hi=Q[t+11],n.uj=Q[t+12],n.vj=Q[t+13],!(e=An(e))||n.hi)n=0;else if(e=e.getContext("webgl",n)){t=ir(8),Q[t+4>>2]=0|xe;var r={jj:t,attributes:n,version:n.wi,qg:e};e.canvas&&(e.canvas.rg=r),(void 0===n.qh||n.qh)&&an(r),n=t}else n=0;return n},sa:function(e,t){var n=0;return Tn().forEach((function(r,i){var a=t+n;Q[e+4*i>>2]=a,W(r,a),n+=r.length+1})),0},ta:function(e,t){var n=Tn();Q[e>>2]=n.length;var r=0;return n.forEach((function(e){r+=e.length+1})),Q[t>>2]=r,0},D:function(e){$r(e)},H:Dn,U:Cn,xa:Fn,Va:On,M:In,B:Ln,d:function(){return 0|S},y:Rn,v:function(e,t,n,r,i,a,f){if((t=Ft(e,t)).ef)return-6;e=t.port;var o=t.hf;if(t=!1,n&&r){var u;if(1&f||!(u=Tt(o))){if(8&f)return-2}else o=u;(n=B(o,n,r))+1>=r&&(t=!0)}return i&&a&&(n=B(""+e,i,a))+1>=a&&(t=!0),t?-12:0},l:function(e){var t=Date.now();return Q[e>>2]=t/1e3|0,Q[e+4>>2]=t%1e3*1e3|0,0},r:Le,ia:function(){Fe.pi()},ba:Ur,j:Lr,h:Fr,C:Gr,P:Rr,_:Wr,O:Nr,Xa:Xr,Wa:Vr,k:Or,w:Pr,J:Br,g:Ir,N:zr,Sa:Hr,Z:qr,Ya:Yr,q:Ne,a:M||n.wasmMemory,T:function(e){Re();var t=new Date(Q[e+20>>2]+1900,Q[e+16>>2],Q[e+12>>2],Q[e+8>>2],Q[e+4>>2],Q[e>>2],0),n=Q[e+32>>2],r=t.getTimezoneOffset(),i=new Date(t.getFullYear(),0,1),a=new Date(t.getFullYear(),6,1).getTimezoneOffset(),f=i.getTimezoneOffset(),o=Math.min(f,a);return 0>n?Q[e+32>>2]=Number(a!=f&&o==r):0>2]=t.getDay(),Q[e+28>>2]=(t.getTime()-i.getTime())/864e5|0,t.getTime()/1e3|0},Ra:function(e){return e===Fe.Ph?(A("Main thread (id="+e+") cannot be canceled!"),71):e?Q[e+12>>2]!==e?(A("pthread_cancel attempted on thread "+e+", which does not point to a valid thread, or does not exist anymore!"),71):(Atomics.compareExchange(J,e>>2,0,2),p?postMessage({cmd:"cancelThread",thread:e}):Te(e),0):(A("pthread_cancel attempted on a null thread pointer!"),71)},S:function(e){var t=Fe.Dg.pop();e&&t()},L:function(e,t){Fe.Dg.push((function(){te.get(e)(t)}))},n:function(e,t,n,r){if("undefined"==typeof SharedArrayBuffer)return A("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!e)return A("pthread_create called with a null thread pointer!"),28;var i=[];if(p&&0===i.length)return xr(687865856,e,t,n,r);var a=0,f=0,o=0,u=0;if(t){var c=Q[t>>2];if(c+=81920,a=Q[t+8>>2],f=0!==Q[t+12>>2],0===Q[t+16>>2]){var s=Q[t+20>>2],l=Q[t+24>>2];o=t+20,u=t+24;var d=Fe.Mg?Fe.Mg:0|xe;if(o||u)if(d)if(Q[d+12>>2]!==d)A("pthread_getschedparam attempted on thread "+d+", which does not point to a valid thread, or does not exist anymore!");else{var h=Atomics.load(J,d+128>>2);d=Atomics.load(J,d+132>>2),o&&(Q[o>>2]=h),u&&(Q[u>>2]=d)}else A("pthread_getschedparam called with a null thread pointer!");o=Q[t+20>>2],u=Q[t+24>>2],Q[t+20>>2]=s,Q[t+24>>2]=l}else o=Q[t+20>>2],u=Q[t+24>>2]}else c=2097152;for((t=0==a)?a=fr(16,c):O(0<(a-=c)),s=ir(232),l=0;58>l;++l)J[(s>>2)+l]=0;return Q[e>>2]=s,Q[s+12>>2]=s,Q[(e=s+156)>>2]=e,n={Rf:a,cg:c,Kg:t,Ih:o,Jh:u,detached:f,Mi:n,$f:s,Fi:0|xe,Tf:r,Vi:i},p?(n.$i="spawnThread",postMessage(n,i)):Nn(n),0},o:function(e,t){return Un(e,t)},i:Bn,e:function(e){S=0|e},E:function(){return 0},m:function(e,t,n,r){function i(e,t,n){for(e="number"==typeof e?e.toString():e||"";e.lengthe?-1:0=f(n,e)?0>=f(t,e)?e.getFullYear()+1:e.getFullYear():e.getFullYear()-1}var c=Q[r+40>>2];for(var s in r={Ti:Q[r>>2],Si:Q[r+4>>2],Eg:Q[r+8>>2],pg:Q[r+12>>2],dg:Q[r+16>>2],rf:Q[r+20>>2],Fg:Q[r+24>>2],Gg:Q[r+28>>2],yj:Q[r+32>>2],Ri:Q[r+36>>2],Ui:c?R(c):""},n=R(n),c={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(s,"g"),c[s]);var l="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(s in c={"%a":function(e){return l[e.Fg].substring(0,3)},"%A":function(e){return l[e.Fg]},"%b":function(e){return d[e.dg].substring(0,3)},"%B":function(e){return d[e.dg]},"%C":function(e){return a((e.rf+1900)/100|0,2)},"%d":function(e){return a(e.pg,2)},"%e":function(e){return i(e.pg,2," ")},"%g":function(e){return u(e).toString().substring(2)},"%G":function(e){return u(e)},"%H":function(e){return a(e.Eg,2)},"%I":function(e){return 0==(e=e.Eg)?e=12:12e.Eg?"AM":"PM"},"%S":function(e){return a(e.Ti,2)},"%t":function(){return"\t"},"%u":function(e){return e.Fg||7},"%U":function(e){var t=new Date(e.rf+1900,0,1),n=0===t.getDay()?t:Hn(t,7-t.getDay());return 0>f(n,e=new Date(e.rf+1900,e.dg,e.pg))?a(Math.ceil((31-n.getDate()+(Gn(zn(e.getFullYear())?Wn:qn,e.getMonth()-1)-31)+e.getDate())/7),2):0===f(n,t)?"01":"00"},"%V":function(e){var t=new Date(e.rf+1901,0,4),n=o(new Date(e.rf+1900,0,4));t=o(t);var r=Hn(new Date(e.rf+1900,0,1),e.Gg);return 0>f(r,n)?"53":0>=f(t,r)?"01":a(Math.ceil((n.getFullYear()f(n,e=new Date(e.rf+1900,e.dg,e.pg))?a(Math.ceil((31-n.getDate()+(Gn(zn(e.getFullYear())?Wn:qn,e.getMonth()-1)-31)+e.getDate())/7),2):0===f(n,t)?"01":"00"},"%y":function(e){return(e.rf+1900).toString().substring(2)},"%Y":function(e){return e.rf+1900},"%z":function(e){var t=0<=(e=e.Ri);return e=Math.abs(e)/60,(t?"+":"-")+String("0000"+(e/60*100+e%60)).slice(-4)},"%Z":function(e){return e.Ui},"%%":function(){return"%"}})0<=n.indexOf(s)&&(n=n.replace(new RegExp(s,"g"),c[s](r)));return(s=er(n,!1)).length>t?0:(H.set(s,e),s.length-1)},x:Yn,s:function(e){var t=Date.now()/1e3|0;return e&&(Q[e>>2]=t),t}};!function(){function e(e,t){n.asm=e.exports,te=n.asm.Sd,T=t,p||de()}function t(t){e(t.instance,t.module)}function r(e){return ye().then((function(e){return WebAssembly.instantiate(e,a)})).then(e,(function(e){A("failed to asynchronously prepare wasm: "+e),he(e)}))}var a={a:tr};if(p||le(),n.instantiateWasm)try{return n.instantiateWasm(a,e)}catch(e){return A("Module.instantiateWasm callback failed with error: "+e),!1}(E||"function"!=typeof WebAssembly.instantiateStreaming||me()||pe("file://")||"function"!=typeof fetch?r(t):fetch(ge,{credentials:"same-origin"}).then((function(e){return WebAssembly.instantiateStreaming(e,a).then(t,(function(e){return A("wasm streaming compile failed: "+e),A("falling back to ArrayBuffer instantiation"),r(t)}))}))).catch(i)}();var nr=n.___wasm_call_ctors=function(){return(nr=n.___wasm_call_ctors=n.asm.Td).apply(null,arguments)},rr=n._free=function(){return(rr=n._free=n.asm.Ud).apply(null,arguments)},ir=n._malloc=function(){return(ir=n._malloc=n.asm.Vd).apply(null,arguments)},ar=n.___errno_location=function(){return(ar=n.___errno_location=n.asm.Wd).apply(null,arguments)};n._fflush=function(){return(n._fflush=n.asm.Xd).apply(null,arguments)};var fr=n._memalign=function(){return(fr=n._memalign=n.asm.Yd).apply(null,arguments)},or=n._ntohs=function(){return(or=n._ntohs=n.asm.Zd).apply(null,arguments)},ur=n._htons=function(){return(ur=n._htons=n.asm._d).apply(null,arguments)},cr=n._main=function(){return(cr=n._main=n.asm.$d).apply(null,arguments)},sr=n._emscripten_get_global_libc=function(){return(sr=n._emscripten_get_global_libc=n.asm.ae).apply(null,arguments)};n.___em_js__initPthreadsJS=function(){return(n.___em_js__initPthreadsJS=n.asm.be).apply(null,arguments)};var lr=n._htonl=function(){return(lr=n._htonl=n.asm.ce).apply(null,arguments)},dr=n._memset=function(){return(dr=n._memset=n.asm.de).apply(null,arguments)},hr=n.__get_tzname=function(){return(hr=n.__get_tzname=n.asm.ee).apply(null,arguments)},pr=n.__get_daylight=function(){return(pr=n.__get_daylight=n.asm.fe).apply(null,arguments)},mr=n.__get_timezone=function(){return(mr=n.__get_timezone=n.asm.ge).apply(null,arguments)},gr=n.stackSave=function(){return(gr=n.stackSave=n.asm.he).apply(null,arguments)},wr=n.stackRestore=function(){return(wr=n.stackRestore=n.asm.ie).apply(null,arguments)},yr=n.stackAlloc=function(){return(yr=n.stackAlloc=n.asm.je).apply(null,arguments)},vr=n._setThrew=function(){return(vr=n._setThrew=n.asm.ke).apply(null,arguments)};n._emscripten_main_browser_thread_id=function(){return(n._emscripten_main_browser_thread_id=n.asm.le).apply(null,arguments)};var br=n.___pthread_tsd_run_dtors=function(){return(br=n.___pthread_tsd_run_dtors=n.asm.me).apply(null,arguments)},_r=n._emscripten_main_thread_process_queued_calls=function(){return(_r=n._emscripten_main_thread_process_queued_calls=n.asm.ne).apply(null,arguments)};n._emscripten_current_thread_process_queued_calls=function(){return(n._emscripten_current_thread_process_queued_calls=n.asm.oe).apply(null,arguments)};var kr=n._emscripten_register_main_browser_thread_id=function(){return(kr=n._emscripten_register_main_browser_thread_id=n.asm.pe).apply(null,arguments)},Ar=n._do_emscripten_dispatch_to_thread=function(){return(Ar=n._do_emscripten_dispatch_to_thread=n.asm.qe).apply(null,arguments)};n._emscripten_async_run_in_main_thread=function(){return(n._emscripten_async_run_in_main_thread=n.asm.re).apply(null,arguments)},n._emscripten_sync_run_in_main_thread=function(){return(n._emscripten_sync_run_in_main_thread=n.asm.se).apply(null,arguments)},n._emscripten_sync_run_in_main_thread_0=function(){return(n._emscripten_sync_run_in_main_thread_0=n.asm.te).apply(null,arguments)},n._emscripten_sync_run_in_main_thread_1=function(){return(n._emscripten_sync_run_in_main_thread_1=n.asm.ue).apply(null,arguments)},n._emscripten_sync_run_in_main_thread_2=function(){return(n._emscripten_sync_run_in_main_thread_2=n.asm.ve).apply(null,arguments)},n._emscripten_sync_run_in_main_thread_xprintf_varargs=function(){return(n._emscripten_sync_run_in_main_thread_xprintf_varargs=n.asm.we).apply(null,arguments)},n._emscripten_sync_run_in_main_thread_3=function(){return(n._emscripten_sync_run_in_main_thread_3=n.asm.xe).apply(null,arguments)};var xr=n._emscripten_sync_run_in_main_thread_4=function(){return(xr=n._emscripten_sync_run_in_main_thread_4=n.asm.ye).apply(null,arguments)};n._emscripten_sync_run_in_main_thread_5=function(){return(n._emscripten_sync_run_in_main_thread_5=n.asm.ze).apply(null,arguments)},n._emscripten_sync_run_in_main_thread_6=function(){return(n._emscripten_sync_run_in_main_thread_6=n.asm.Ae).apply(null,arguments)},n._emscripten_sync_run_in_main_thread_7=function(){return(n._emscripten_sync_run_in_main_thread_7=n.asm.Be).apply(null,arguments)};var Er=n._emscripten_run_in_main_runtime_thread_js=function(){return(Er=n._emscripten_run_in_main_runtime_thread_js=n.asm.Ce).apply(null,arguments)},jr=n.__emscripten_call_on_thread=function(){return(jr=n.__emscripten_call_on_thread=n.asm.De).apply(null,arguments)};n._proxy_main=function(){return(n._proxy_main=n.asm.Ee).apply(null,arguments)},n._emscripten_tls_init=function(){return(n._emscripten_tls_init=n.asm.Fe).apply(null,arguments)},n.dynCall_ijiii=function(){return(n.dynCall_ijiii=n.asm.Ge).apply(null,arguments)};var Sr=n.dynCall_vijjjid=function(){return(Sr=n.dynCall_vijjjid=n.asm.He).apply(null,arguments)},Mr=n.dynCall_iiiijj=function(){return(Mr=n.dynCall_iiiijj=n.asm.Ie).apply(null,arguments)};n.dynCall_iiijiii=function(){return(n.dynCall_iiijiii=n.asm.Je).apply(null,arguments)},n.dynCall_jiiii=function(){return(n.dynCall_jiiii=n.asm.Ke).apply(null,arguments)},n.dynCall_jii=function(){return(n.dynCall_jii=n.asm.Le).apply(null,arguments)};var Tr=n.dynCall_iij=function(){return(Tr=n.dynCall_iij=n.asm.Me).apply(null,arguments)};n.dynCall_viiijj=function(){return(n.dynCall_viiijj=n.asm.Ne).apply(null,arguments)},n.dynCall_jij=function(){return(n.dynCall_jij=n.asm.Oe).apply(null,arguments)},n.dynCall_jiji=function(){return(n.dynCall_jiji=n.asm.Pe).apply(null,arguments)},n.dynCall_iiiji=function(){return(n.dynCall_iiiji=n.asm.Qe).apply(null,arguments)},n.dynCall_iiiiij=function(){return(n.dynCall_iiiiij=n.asm.Re).apply(null,arguments)},n.dynCall_jiiij=function(){return(n.dynCall_jiiij=n.asm.Se).apply(null,arguments)},n.dynCall_iiijjji=function(){return(n.dynCall_iiijjji=n.asm.Te).apply(null,arguments)},n.dynCall_iiiiiij=function(){return(n.dynCall_iiiiiij=n.asm.Ue).apply(null,arguments)},n.dynCall_jiiji=function(){return(n.dynCall_jiiji=n.asm.Ve).apply(null,arguments)},n.dynCall_viiiiijji=function(){return(n.dynCall_viiiiijji=n.asm.We).apply(null,arguments)},n.dynCall_viiiji=function(){return(n.dynCall_viiiji=n.asm.Xe).apply(null,arguments)},n.dynCall_viiiiji=function(){return(n.dynCall_viiiiji=n.asm.Ye).apply(null,arguments)},n.dynCall_jiiiii=function(){return(n.dynCall_jiiiii=n.asm.Ze).apply(null,arguments)},n.dynCall_jiii=function(){return(n.dynCall_jiii=n.asm._e).apply(null,arguments)},n.dynCall_jiiiiii=function(){return(n.dynCall_jiiiiii=n.asm.$e).apply(null,arguments)},n._ff_h264_cabac_tables=2116006;var Dr,Cr=n._main_thread_futex=17189696;function Fr(e,t,n){var r=gr();try{return te.get(e)(t,n)}catch(e){if(wr(r),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function Or(e,t){var n=gr();try{te.get(e)(t)}catch(e){if(wr(n),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function Ir(e,t,n,r,i){var a=gr();try{te.get(e)(t,n,r,i)}catch(e){if(wr(a),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function Pr(e,t,n){var r=gr();try{te.get(e)(t,n)}catch(e){if(wr(r),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function Lr(e,t){var n=gr();try{return te.get(e)(t)}catch(e){if(wr(n),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function Rr(e,t,n,r,i){var a=gr();try{return te.get(e)(t,n,r,i)}catch(e){if(wr(a),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function Nr(e,t,n,r,i,a,f,o,u){var c=gr();try{return te.get(e)(t,n,r,i,a,f,o,u)}catch(e){if(wr(c),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function Br(e,t,n,r){var i=gr();try{te.get(e)(t,n,r)}catch(e){if(wr(i),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function Ur(e){var t=gr();try{return te.get(e)()}catch(e){if(wr(t),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function zr(e,t,n,r,i,a){var f=gr();try{te.get(e)(t,n,r,i,a)}catch(e){if(wr(f),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function Gr(e,t,n,r){var i=gr();try{return te.get(e)(t,n,r)}catch(e){if(wr(i),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function Wr(e,t,n,r,i,a){var f=gr();try{return te.get(e)(t,n,r,i,a)}catch(e){if(wr(f),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function qr(e,t,n,r,i,a,f,o,u){var c=gr();try{te.get(e)(t,n,r,i,a,f,o,u)}catch(e){if(wr(c),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function Hr(e,t,n,r,i,a,f){var o=gr();try{te.get(e)(t,n,r,i,a,f)}catch(e){if(wr(o),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function Yr(e,t,n,r,i,a,f,o,u,c){var s=gr();try{Sr(e,t,n,r,i,a,f,o,u,c)}catch(e){if(wr(s),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function Xr(e,t,n,r,i,a,f,o){var u=gr();try{return Mr(e,t,n,r,i,a,f,o)}catch(e){if(wr(u),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function Vr(e,t,n,r){var i=gr();try{return Tr(e,t,n,r)}catch(e){if(wr(i),e!==e+0&&"longjmp"!==e)throw e;vr(1,0)}}function Qr(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}function Jr(e){function t(){if(!Dr&&(Dr=!0,n.calledRun=!0,!F)){if(n.noFSInit||Ke.gg.Tg||Ke.gg(),kt.root=Ke.jf(kt,{},null),ke(re),p||(Ke.Bh=!1,ke(ie)),r(n),n.onRuntimeInitialized&&n.onRuntimeInitialized(),Zr){var t=e,i=(t=t||[]).length+1,a=yr(4*(i+1));Q[a>>2]=G(u);for(var f=1;f>2)+f]=G(t[f-1]);Q[(a>>2)+i]=0,n._proxy_main(i,a)}if(!p){if(n.postRun)for("function"==typeof n.postRun&&(n.postRun=[n.postRun]);n.postRun.length;)t=n.postRun.shift(),fe.unshift(t);ke(fe)}}}if(e=e||o,!(0>0]=t;break;case"i16":X[e>>1]=t;break;case"i32":Q[e>>2]=t;break;case"i64":be=[t>>>0,(ve=t,1<=+Math.abs(ve)?0>>0:~~+Math.ceil((ve-+(~~ve>>>0))/4294967296)>>>0:0)],Q[e>>2]=be[0],Q[e+4>>2]=be[1];break;case"float":$[e>>2]=t;break;case"double":Z[e>>3]=t;break;default:he("invalid type for setValue: "+n)}},n.UTF8ToString=R,n.stringToUTF8=B,n.lengthBytesUTF8=U,n.writeAsciiToMemory=W,n.FS=Ke,n.PThread=Fe,n.PThread=Fe,n._pthread_self=Bn,n.wasmMemory=M,n.ExitStatus=Qr,se=function e(){Dr||Jr(),Dr||(se=e)},n.run=Jr,n.preInit)for("function"==typeof n.preInit&&(n.preInit=[n.preInit]);0{var e={725:(e,t,r)=>{"use strict";e.exports=r.p+"046d0074eee1d99a674a.js"},839:(e,t,r)=>{"use strict";r.r(t),r.d(t,{defaultOptions:()=>o,fetchFile:()=>m,getCreateFFmpegCore:()=>u});var n=r(306);const o={corePath:"https://unpkg.com/@ffmpeg/core@".concat(n.devDependencies["@ffmpeg/core"].substring(1),"/dist/ffmpeg-core.js")};var a=r(185),i=r(835);function c(e,t,r,n,o,a,i){try{var c=e[a](i),s=c.value}catch(e){return void r(e)}c.done?t(s):Promise.resolve(s).then(n,o)}function s(e){return function(){var t=this,r=arguments;return new Promise((function(n,o){var a=e.apply(t,r);function i(e){c(a,n,o,i,s,"next",e)}function s(e){c(a,n,o,i,s,"throw",e)}i(void 0)}))}}var f=function(){var e=s(regeneratorRuntime.mark((function e(t,r){var n,o,i;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return(0,a.log)("info","fetch ".concat(t)),e.next=3,fetch(t);case 3:return e.next=5,e.sent.arrayBuffer();case 5:return n=e.sent,(0,a.log)("info","".concat(t," file size = ").concat(n.byteLength," bytes")),o=new Blob([n],{type:r}),i=URL.createObjectURL(o),(0,a.log)("info","".concat(t," blob URL = ").concat(i)),e.abrupt("return",i);case 11:case"end":return e.stop()}}),e)})));return function(t,r){return e.apply(this,arguments)}}(),u=function(){var e=s(regeneratorRuntime.mark((function e(t){var r,n,o,c,s,u,l,p,m,h,g;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=t.corePath,n=t.workerPath,o=t.wasmPath,!("undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope)){e.next=18;break}if("string"==typeof r){e.next=4;break}throw Error("corePath should be a string!");case 4:return c=new URL(r,"file:///home/jeromewu/repos/ffmpeg.wasm/src/browser/getCreateFFmpegCore.js").href,e.next=7,f(c,"application/javascript");case 7:return s=e.sent,e.next=10,f(void 0!==o?o:c.replace("ffmpeg-core.js","ffmpeg-core.wasm"),"application/wasm");case 10:return u=e.sent,e.next=13,f(void 0!==n?n:c.replace("ffmpeg-core.js","ffmpeg-core.worker.js"),"application/javascript");case 13:if(l=e.sent,"undefined"!=typeof createFFmpegCore){e.next=16;break}return e.abrupt("return",new Promise((function(e){if(globalThis.importScripts(s),"undefined"==typeof createFFmpegCore)throw Error((0,i.CREATE_FFMPEG_CORE_IS_NOT_DEFINED)(c));(0,a.log)("info","ffmpeg-core.js script loaded"),e({createFFmpegCore,corePath:s,wasmPath:u,workerPath:l})})));case 16:return(0,a.log)("info","ffmpeg-core.js script is loaded already"),e.abrupt("return",Promise.resolve({createFFmpegCore,corePath:s,wasmPath:u,workerPath:l}));case 18:if("string"==typeof r){e.next=20;break}throw Error("corePath should be a string!");case 20:return p=new URL(r,"file:///home/jeromewu/repos/ffmpeg.wasm/src/browser/getCreateFFmpegCore.js").href,e.next=23,f(p,"application/javascript");case 23:return m=e.sent,e.next=26,f(void 0!==o?o:p.replace("ffmpeg-core.js","ffmpeg-core.wasm"),"application/wasm");case 26:return h=e.sent,e.next=29,f(void 0!==n?n:p.replace("ffmpeg-core.js","ffmpeg-core.worker.js"),"application/javascript");case 29:if(g=e.sent,"undefined"!=typeof createFFmpegCore){e.next=32;break}return e.abrupt("return",new Promise((function(e){var t=document.createElement("script");t.src=m,t.type="text/javascript",t.addEventListener("load",(function r(){if(t.removeEventListener("load",r),"undefined"==typeof createFFmpegCore)throw Error((0,i.CREATE_FFMPEG_CORE_IS_NOT_DEFINED)(p));(0,a.log)("info","ffmpeg-core.js script loaded"),e({createFFmpegCore,corePath:m,wasmPath:h,workerPath:g})})),document.getElementsByTagName("head")[0].appendChild(t)})));case 32:return(0,a.log)("info","ffmpeg-core.js script is loaded already"),e.abrupt("return",Promise.resolve({createFFmpegCore,corePath:m,wasmPath:h,workerPath:g}));case 34:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}();function l(e,t,r,n,o,a,i){try{var c=e[a](i),s=c.value}catch(e){return void r(e)}c.done?t(s):Promise.resolve(s).then(n,o)}var p=function(e){return new Promise((function(t,r){var n=new FileReader;n.onload=function(){t(n.result)},n.onerror=function(e){var t=e.target.error.code;r(Error("File could not be read! Code=".concat(t)))},n.readAsArrayBuffer(e)}))},m=function(){var e,t=(e=regeneratorRuntime.mark((function e(t){var r,n;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=t,void 0!==t){e.next=3;break}return e.abrupt("return",new Uint8Array);case 3:if("string"!=typeof t){e.next=16;break}if(!/data:_data\/([a-zA-Z]*);base64,([^"]*)/.test(t)){e.next=8;break}r=atob(t.split(",")[1]).split("").map((function(e){return e.charCodeAt(0)})),e.next=14;break;case 8:return e.next=10,fetch(new URL(t,"file:///home/jeromewu/repos/ffmpeg.wasm/src/browser/fetchFile.js").href);case 10:return n=e.sent,e.next=13,n.arrayBuffer();case 13:r=e.sent;case 14:e.next=20;break;case 16:if(!(t instanceof File||t instanceof Blob)){e.next=20;break}return e.next=19,p(t);case 19:r=e.sent;case 20:return e.abrupt("return",new Uint8Array(r));case 21:case"end":return e.stop()}}),e)})),function(){var t=this,r=arguments;return new Promise((function(n,o){var a=e.apply(t,r);function i(e){l(a,n,o,i,c,"next",e)}function c(e){l(a,n,o,i,c,"throw",e)}i(void 0)}))});return function(e){return t.apply(this,arguments)}}()},500:e=>{e.exports={defaultArgs:["./ffmpeg","-nostdin","-y"],baseOptions:{log:!1,logger:function(){},progress:function(){},corePath:""}}},906:(e,t,r)=>{function n(e){return function(e){if(Array.isArray(e))return s(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||c(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function o(e,t,r,n,o,a,i){try{var c=e[a](i),s=c.value}catch(e){return void r(e)}c.done?t(s):Promise.resolve(s).then(n,o)}function a(e){return function(){var t=this,r=arguments;return new Promise((function(n,a){var i=e.apply(t,r);function c(e){o(i,n,a,c,s,"next",e)}function s(e){o(i,n,a,c,s,"throw",e)}c(void 0)}))}}function i(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e)){var r=[],n=!0,o=!1,a=void 0;try{for(var i,c=e[Symbol.iterator]();!(n=(i=c.next()).done)&&(r.push(i.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{n||null==c.return||c.return()}finally{if(o)throw a}}return r}}(e,t)||c(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function c(e,t){if(e){if("string"==typeof e)return s(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?s(e,t):void 0}}function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r=0||(o[r]=e[r]);return o}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}var m=r(500),h=m.defaultArgs,g=m.baseOptions,d=r(319),y=r(839),v=y.defaultOptions,w=y.getCreateFFmpegCore,b=r(306).version,x=Error("ffmpeg.wasm is not ready, make sure you have completed load().");e.exports=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=u(u(u({},g),v),e),r=t.log,o=(t.logger,t.progress),c=p(t,["log","logger","progress"]),s=null,f=null,l=null,m=null,y=!1,F=function(){},j=r,E=o,P=0,O=0,k=!1,L=0,S=function(e){"FFMPEG_END"===e&&null!==l&&(l(),l=null,m=null,y=!1)},_=function(e,t){F({type:e,message:t}),j&&console.log("[".concat(e,"] ").concat(t))},C=function(e){var t=i(e.split(":"),3),r=t[0],n=t[1],o=t[2];return 60*parseFloat(r)*60+60*parseFloat(n)+parseFloat(o)},A=function(e,t){if("string"==typeof e)if(e.startsWith(" Duration")){var r=e.split(", ")[0].split(": ")[1],n=C(r);t({duration:n,ratio:L}),(0===P||P>n)&&(P=n,k=!0)}else if(k&&e.startsWith(" Stream")){var o=e.match(/([\d.]+) fps/);if(o){var a=parseFloat(o[1]);O=P*a}else O=0;k=!1}else if(e.startsWith("frame")||e.startsWith("size")){var i=e.split("time=")[1].split(" ")[0],c=C(i),s=e.match(/frame=\s*(\d+)/);if(O&&s){var f=parseFloat(s[1]);L=Math.min(f/O,1)}else L=c/P;t({ratio:L,time:c})}else e.startsWith("video:")&&(t({ratio:1}),P=0)},T=function(e){var t=e.type,r=e.message;_(t,r),A(r,E),S(r)},R=function(){var e=a(regeneratorRuntime.mark((function e(){var t,r,n,o,a;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(_("info","load ffmpeg-core"),null!==s){e.next=17;break}return _("info","loading ffmpeg-core"),e.next=5,w(c);case 5:return t=e.sent,r=t.createFFmpegCore,n=t.corePath,o=t.workerPath,a=t.wasmPath,e.next=12,r({mainScriptUrlOrBlob:n,printErr:function(e){return T({type:"fferr",message:e})},print:function(e){return T({type:"ffout",message:e})},locateFile:function(e,t){if("undefined"!=typeof window||"undefined"!=typeof WorkerGlobalScope){if(void 0!==a&&e.endsWith("ffmpeg-core.wasm"))return a;if(void 0!==o&&e.endsWith("ffmpeg-core.worker.js"))return o}return t+e}});case 12:s=e.sent,f=s.cwrap(c.mainName||"proxy_main","number",["number","number"]),_("info","ffmpeg-core loaded"),e.next=18;break;case 17:throw Error("ffmpeg.wasm was loaded, you should not load it again, use ffmpeg.isLoaded() to check next time.");case 18:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}(),N=function(){return null!==s},I=function(){for(var e=arguments.length,t=new Array(e),r=0;r1?t-1:0),n=1;n")})).join(" "))),null===s)throw x;var o=null;try{var a;o=(a=s.FS)[e].apply(a,r)}catch(t){throw"readdir"===e?Error("ffmpeg.FS('readdir', '".concat(r[0],"') error. Check if the path exists, ex: ffmpeg.FS('readdir', '/')")):"readFile"===e?Error("ffmpeg.FS('readFile', '".concat(r[0],"') error. Check if the path exists")):Error("Oops, something went wrong in FS operation.")}return o},G=function(){if(null===s)throw x;m&&m("ffmpeg has exited"),y=!1;try{s.exit(1)}catch(e){_(e.message),m&&m(e)}finally{s=null,f=null,l=null,m=null}},D=function(e){E=e},W=function(e){F=e},B=function(e){j=e};return _("info","use ffmpeg.wasm v".concat(b)),{setProgress:D,setLogger:W,setLogging:B,load:R,isLoaded:N,run:I,exit:G,FS:U}}},352:(e,t,r)=>{r(666);var n=r(906),o=r(839).fetchFile;e.exports={createFFmpeg:n,fetchFile:o}},835:e=>{e.exports={CREATE_FFMPEG_CORE_IS_NOT_DEFINED:function(e){return"\ncreateFFmpegCore is not defined. ffmpeg.wasm is unable to find createFFmpegCore after loading ffmpeg-core.js from ".concat(e,". Use another URL when calling createFFmpeg():\n\nconst ffmpeg = createFFmpeg({\n corePath: 'http://localhost:3000/ffmpeg-core.js',\n});\n")}}},185:e=>{var t=!1,r=function(){};e.exports={logging:t,setLogging:function(e){t=e},setCustomLogger:function(e){r=e},log:function(e,n){r({type:e,message:n}),t&&console.log("[".concat(e,"] ").concat(n))}}},319:e=>{e.exports=function(e,t){var r=e._malloc(t.length*Uint32Array.BYTES_PER_ELEMENT);return t.forEach((function(t,n){var o=e.lengthBytesUTF8(t)+1,a=e._malloc(o);e.stringToUTF8(t,a,o),e.setValue(r+Uint32Array.BYTES_PER_ELEMENT*n,a,"i32")})),[t.length,r]}},666:e=>{var t=function(e){"use strict";var t,r=Object.prototype,n=r.hasOwnProperty,o="function"==typeof Symbol?Symbol:{},a=o.iterator||"@@iterator",i=o.asyncIterator||"@@asyncIterator",c=o.toStringTag||"@@toStringTag";function s(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{s({},"")}catch(e){s=function(e,t,r){return e[t]=r}}function f(e,t,r,n){var o=t&&t.prototype instanceof d?t:d,a=Object.create(o.prototype),i=new L(n||[]);return a._invoke=function(e,t,r){var n=l;return function(o,a){if(n===m)throw new Error("Generator is already running");if(n===h){if("throw"===o)throw a;return _()}for(r.method=o,r.arg=a;;){var i=r.delegate;if(i){var c=P(i,r);if(c){if(c===g)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if(n===l)throw n=h,r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n=m;var s=u(e,t,r);if("normal"===s.type){if(n=r.done?h:p,s.arg===g)continue;return{value:s.arg,done:r.done}}"throw"===s.type&&(n=h,r.method="throw",r.arg=s.arg)}}}(e,r,i),a}function u(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}e.wrap=f;var l="suspendedStart",p="suspendedYield",m="executing",h="completed",g={};function d(){}function y(){}function v(){}var w={};w[a]=function(){return this};var b=Object.getPrototypeOf,x=b&&b(b(S([])));x&&x!==r&&n.call(x,a)&&(w=x);var F=v.prototype=d.prototype=Object.create(w);function j(e){["next","throw","return"].forEach((function(t){s(e,t,(function(e){return this._invoke(t,e)}))}))}function E(e,t){function r(o,a,i,c){var s=u(e[o],e,a);if("throw"!==s.type){var f=s.arg,l=f.value;return l&&"object"==typeof l&&n.call(l,"__await")?t.resolve(l.__await).then((function(e){r("next",e,i,c)}),(function(e){r("throw",e,i,c)})):t.resolve(l).then((function(e){f.value=e,i(f)}),(function(e){return r("throw",e,i,c)}))}c(s.arg)}var o;this._invoke=function(e,n){function a(){return new t((function(t,o){r(e,n,t,o)}))}return o=o?o.then(a,a):a()}}function P(e,r){var n=e.iterator[r.method];if(n===t){if(r.delegate=null,"throw"===r.method){if(e.iterator.return&&(r.method="return",r.arg=t,P(e,r),"throw"===r.method))return g;r.method="throw",r.arg=new TypeError("The iterator does not provide a 'throw' method")}return g}var o=u(n,e.iterator,r.arg);if("throw"===o.type)return r.method="throw",r.arg=o.arg,r.delegate=null,g;var a=o.arg;return a?a.done?(r[e.resultName]=a.value,r.next=e.nextLoc,"return"!==r.method&&(r.method="next",r.arg=t),r.delegate=null,g):a:(r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,g)}function O(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function k(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function L(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(O,this),this.reset(!0)}function S(e){if(e){var r=e[a];if(r)return r.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var o=-1,i=function r(){for(;++o=0;--a){var i=this.tryEntries[a],c=i.completion;if("root"===i.tryLoc)return o("end");if(i.tryLoc<=this.prev){var s=n.call(i,"catchLoc"),f=n.call(i,"finallyLoc");if(s&&f){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),k(r),g}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if("throw"===n.type){var o=n.arg;k(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:S(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),g}},e}(e.exports);try{regeneratorRuntime=t}catch(e){Function("r","regeneratorRuntime = r")(t)}},306:e=>{"use strict";e.exports=JSON.parse('{"name":"@ffmpeg/ffmpeg","version":"0.11.6","description":"FFmpeg WebAssembly version","main":"src/index.js","types":"src/index.d.ts","directories":{"example":"examples"},"scripts":{"start":"node scripts/server.js","start:worker":"node scripts/worker-server.js","build":"rimraf dist && webpack --config scripts/webpack.config.prod.js","build:worker":"rimraf dist && webpack --config scripts/webpack.config.worker.prod.js","prepublishOnly":"npm run build","lint":"eslint src","wait":"rimraf dist && wait-on http://localhost:3000/dist/ffmpeg.dev.js","test":"npm-run-all -p -r start test:all","test:all":"npm-run-all wait test:browser:ffmpeg test:node:all","test:node":"node node_modules/mocha/bin/_mocha --exit --bail --require ./scripts/test-helper.js","test:node:all":"npm run test:node -- ./tests/*.test.js","test:browser":"mocha-headless-chrome -a allow-file-access-from-files -a incognito -a no-sandbox -a disable-setuid-sandbox -a disable-logging -t 300000","test:browser:ffmpeg":"npm run test:browser -- -f ./tests/ffmpeg.test.html"},"browser":{"./src/node/index.js":"./src/browser/index.js"},"repository":{"type":"git","url":"git+https://github.com/ffmpegwasm/ffmpeg.wasm.git"},"keywords":["ffmpeg","WebAssembly","video"],"author":"Jerome Wu ","license":"MIT","bugs":{"url":"https://github.com/ffmpegwasm/ffmpeg.wasm/issues"},"engines":{"node":">=12.16.1"},"homepage":"https://github.com/ffmpegwasm/ffmpeg.wasm#readme","dependencies":{"is-url":"^1.2.4","node-fetch":"^2.6.1","regenerator-runtime":"^0.13.7","resolve-url":"^0.2.1"},"devDependencies":{"@babel/core":"^7.12.3","@babel/preset-env":"^7.12.1","@ffmpeg/core":"^0.11.0","@types/emscripten":"^1.39.4","babel-eslint":"^10.1.0","babel-loader":"^8.1.0","chai":"^4.2.0","cors":"^2.8.5","eslint":"^7.12.1","eslint-config-airbnb-base":"^14.1.0","eslint-plugin-import":"^2.22.1","express":"^4.17.1","mocha":"^8.2.1","mocha-headless-chrome":"^2.0.3","npm-run-all":"^4.1.5","wait-on":"^5.3.0","webpack":"^5.3.2","webpack-cli":"^4.1.0","webpack-dev-middleware":"^4.0.0"}}')}},t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={exports:{}};return e[n](o,o.exports,r),o.exports}return r.m=e,r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;r.g.importScripts&&(e=r.g.location+"");var t=r.g.document;if(!e&&t&&(t.currentScript&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");n.length&&(e=n[n.length-1].src)}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),r.p=e})(),r.b=document.baseURI||self.location.href,r(352)})()})); +//# sourceMappingURL=ffmpeg.min.js.map \ No newline at end of file diff --git a/node_modules/@ffmpeg/ffmpeg/dist/ffmpeg.min.js.map b/node_modules/@ffmpeg/ffmpeg/dist/ffmpeg.min.js.map new file mode 100644 index 0000000..3fefb9e --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/dist/ffmpeg.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["webpack://FFmpeg/webpack/universalModuleDefinition","webpack://FFmpeg/./src/browser/defaultOptions.js","webpack://FFmpeg/./src/browser/getCreateFFmpegCore.js","webpack://FFmpeg/./src/browser/fetchFile.js","webpack://FFmpeg/./src/config.js","webpack://FFmpeg/./src/createFFmpeg.js","webpack://FFmpeg/./src/index.js","webpack://FFmpeg/./src/utils/errors.js","webpack://FFmpeg/./src/utils/log.js","webpack://FFmpeg/./src/utils/parseArgs.js","webpack://FFmpeg/./node_modules/regenerator-runtime/runtime.js","webpack://FFmpeg/webpack/bootstrap","webpack://FFmpeg/webpack/startup","webpack://FFmpeg/webpack/runtime/define property getters","webpack://FFmpeg/webpack/runtime/global","webpack://FFmpeg/webpack/runtime/hasOwnProperty shorthand","webpack://FFmpeg/webpack/runtime/make namespace object","webpack://FFmpeg/webpack/runtime/publicPath","webpack://FFmpeg/webpack/runtime/jsonp chunk loading"],"names":["root","factory","exports","module","define","amd","self","corePath","pkg","toBlobURL","url","mimeType","log","fetch","arrayBuffer","buf","byteLength","blob","Blob","type","blobURL","URL","createObjectURL","getCreateFFmpegCore","_corePath","_workerPath","workerPath","_wasmPath","wasmPath","WorkerGlobalScope","Error","coreRemotePath","import","href","undefined","replace","createFFmpegCore","Promise","resolve","globalThis","importScripts","CREATE_FFMPEG_CORE_IS_NOT_DEFINED","script","document","createElement","src","addEventListener","eventHandler","removeEventListener","getElementsByTagName","appendChild","readFromBlobOrFile","reject","fileReader","FileReader","onload","result","onerror","code","target","error","readAsArrayBuffer","fetchFile","_data","data","Uint8Array","test","atob","split","map","c","charCodeAt","res","File","defaultArgs","baseOptions","logger","progress","require","parseArgs","defaultOptions","version","NO_LOAD","_options","optLog","optProgress","options","Core","ffmpeg","runResolve","runReject","running","customLogger","logging","duration","frames","readFrames","ratio","detectCompletion","message","console","ts2sec","ts","h","m","s","parseFloat","parseProgress","prog","startsWith","d","match","fps","t","f","Math","min","time","parseMessage","load","mainScriptUrlOrBlob","printErr","print","locateFile","path","prefix","window","endsWith","cwrap","mainName","isLoaded","run","_args","join","args","filter","length","FS","method","arg","ret","e","exit","err","setProgress","_progress","setLogger","_logger","setLogging","_logging","createFFmpeg","setCustomLogger","argsPtr","_malloc","Uint32Array","BYTES_PER_ELEMENT","forEach","idx","sz","lengthBytesUTF8","stringToUTF8","setValue","runtime","Op","Object","prototype","hasOwn","hasOwnProperty","$Symbol","Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","obj","key","value","defineProperty","enumerable","configurable","writable","wrap","innerFn","outerFn","tryLocsList","protoGenerator","Generator","generator","create","context","Context","_invoke","state","GenStateSuspendedStart","GenStateExecuting","GenStateCompleted","doneResult","delegate","delegateResult","maybeInvokeDelegate","ContinueSentinel","sent","_sent","dispatchException","abrupt","record","tryCatch","done","GenStateSuspendedYield","makeInvokeMethod","fn","call","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","this","getProto","getPrototypeOf","NativeIteratorPrototype","values","Gp","defineIteratorMethods","AsyncIterator","PromiseImpl","invoke","__await","then","unwrapped","previousPromise","callInvokeWithMethodAndArg","TypeError","info","resultName","next","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","iterable","iteratorMethod","isNaN","i","constructor","displayName","isGeneratorFunction","genFun","ctor","name","mark","setPrototypeOf","__proto__","awrap","async","iter","toString","keys","object","reverse","pop","skipTempReset","prev","charAt","slice","stop","rootRecord","rval","exception","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","thrown","delegateYield","regeneratorRuntime","accidentalStrictMode","Function","__webpack_module_cache__","__webpack_require__","moduleId","__webpack_modules__","definition","o","get","g","prop","r","scriptUrl","location","currentScript","scripts","p","b","baseURI"],"mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAgB,OAAID,IAEpBD,EAAa,OAAIC,GAClB,CATD,CASGK,MAAM,WACT,M,wMCDA,SAAiBC,SAJA,yCAEqBC,4CAA8C,GAFnE,yB,kVCKjB,IAAMC,EAAS,4CAAG,WAAOC,EAAKC,GAAZ,iGAChBC,SAAI,OAAD,gBAAkBF,IADL,SAESG,MAAMH,GAFf,8BAEqBI,cAFrB,cAEVC,EAFU,QAGhBH,SAAI,OAAD,UAAYF,EAAZ,wBAA+BK,EAAIC,WAAnC,WACGC,EAAO,IAAIC,KAAK,CAACH,GAAM,CAAEI,KAAMR,IAC/BS,EAAUC,IAAIC,gBAAgBL,IACpCL,SAAI,OAAD,UAAYF,EAAZ,uBAA8BU,IANjB,kBAOTA,GAPS,4CAAH,wDAWFG,EAAmB,4CAAG,2HACvBC,EADuB,EACjCjB,SACYkB,EAFqB,EAEjCC,WACUC,EAHuB,EAGjCC,WAIiC,oBAAtBC,mBAAqCvB,gBAAgBuB,mBAP/B,oBAQN,iBAAdL,EARoB,sBASvBM,MAAM,gCATiB,cAWzBC,EAAiB,IAAIV,IAAIG,EAAWQ,8EAAiBC,KAX5B,SAYRxB,EACrBsB,EACA,0BAd6B,cAYzBxB,EAZyB,iBAgBRE,OACPyB,IAAdP,EAA0BA,EAAYI,EAAeI,QAAQ,iBAAkB,oBAC/E,oBAlB6B,eAgBzBP,EAhByB,iBAoBNnB,OACPyB,IAAhBT,EAA4BA,EAAcM,EAAeI,QAAQ,iBAAkB,yBACnF,0BAtB6B,WAoBzBT,EApByB,OAwBC,oBAArBU,iBAxBoB,0CAyBtB,IAAIC,SAAQ,SAACC,GAElB,GADAC,WAAWC,cAAcjC,GACO,oBAArB6B,iBACT,MAAMN,OAAMW,uCAAkCV,KAEhDnB,SAAI,OAAQ,gCACZ0B,EAAQ,CACNF,iBACA7B,WACAqB,WACAF,cAEH,KArC4B,eAuC/Bd,SAAI,OAAQ,2CAvCmB,kBAwCxByB,QAAQC,QAAQ,CACrBF,iBACA7B,WACAqB,WACAF,gBA5C6B,WA+CR,iBAAdF,EA/CsB,uBAgDzBM,MAAM,gCAhDmB,eAkD3BC,EAAiB,IAAIV,IAAIG,EAAWQ,8EAAiBC,KAlD1B,UAmDVxB,EACrBsB,EACA,0BArD+B,eAmD3BxB,EAnD2B,iBAuDVE,OACPyB,IAAdP,EAA0BA,EAAYI,EAAeI,QAAQ,iBAAkB,oBAC/E,oBAzD+B,eAuD3BP,EAvD2B,iBA2DRnB,OACPyB,IAAhBT,EAA4BA,EAAcM,EAAeI,QAAQ,iBAAkB,yBACnF,0BA7D+B,WA2D3BT,EA3D2B,OA+DD,oBAArBU,iBA/DsB,0CAgExB,IAAIC,SAAQ,SAACC,GAClB,IAAMI,EAASC,SAASC,cAAc,UActCF,EAAOG,IAAMtC,EACbmC,EAAOvB,KAAO,kBACduB,EAAOI,iBAAiB,QAfH,SAAfC,IAEJ,GADAL,EAAOM,oBAAoB,OAAQD,GACH,oBAArBX,iBACT,MAAMN,OAAMW,uCAAkCV,KAEhDnB,SAAI,OAAQ,gCACZ0B,EAAQ,CACNF,iBACA7B,WACAqB,WACAF,cAEH,IAIDiB,SAASM,qBAAqB,QAAQ,GAAGC,YAAYR,EACtD,KAnF8B,eAqFjC9B,SAAI,OAAQ,2CArFqB,kBAsF1ByB,QAAQC,QAAQ,CACrBF,iBACA7B,WACAqB,WACAF,gBA1F+B,4CAAH,sD,yHCrBhC,IAAMyB,EAAqB,SAAClC,GAAD,OACzB,IAAIoB,SAAQ,SAACC,EAASc,GACpB,IAAMC,EAAa,IAAIC,WACvBD,EAAWE,OAAS,WAClBjB,EAAQe,EAAWG,OACpB,EACDH,EAAWI,QAAU,YAAqC,IAAfC,EAAe,EAAlCC,OAAUC,MAASF,KACzCN,EAAOtB,MAAM,gCAAD,OAAiC4B,IAC9C,EACDL,EAAWQ,kBAAkB5C,EAC9B,GAVwB,EAcd6C,EAAS,e,EAAA,G,EAAA,yBAAG,WAAOC,GAAP,2FACnBC,EAAOD,OACU,IAAVA,EAFY,yCAGd,IAAIE,YAHU,UAMF,iBAAVF,EANY,qBAQjB,yCAAyCG,KAAKH,GAR7B,gBASnBC,EAAOG,KAAKJ,EAAMK,MAAM,KAAK,IAC1BA,MAAM,IACNC,KAAI,SAACC,GAAD,OAAOA,EAAEC,WAAW,EAApB,IAXY,wCAcD1D,MAAM,IAAIQ,IAAI0C,EAAO/B,oEAAiBC,MAdrC,eAcbuC,EAda,iBAeNA,EAAI1D,cAfE,QAenBkD,EAfmB,4CAkBZD,aAAiBU,MAAQV,aAAiB7C,MAlB9B,kCAmBRiC,EAAmBY,GAnBX,QAmBrBC,EAnBqB,wCAsBhB,IAAIC,WAAWD,IAtBC,2C,+KAAH,qD,UCdtB7D,EAAOD,QAAU,CACfwE,YAAa,CAEX,WAEA,WAEA,MAEFC,YAAa,CAEX/D,KAAK,EAiBLgE,OAAQ,WAAQ,EAahBC,SAAU,WAAQ,EAMlBtE,SAAU,I,0oFC/CuBuE,EAAQ,KAArCJ,E,EAAAA,YAAaC,E,EAAAA,YACfI,EAAYD,EAAQ,K,EACsBA,EAAQ,KAAhDE,E,EAAAA,eAAgBzD,E,EAAAA,oBAChB0D,EAAYH,EAAQ,KAApBG,QAEFC,EAAUpD,MAAM,kEAEtB3B,EAAOD,QAAU,WAAmB,IAAlBiF,EAAkB,uDAAP,CAAC,EAAM,WAO7BR,GACAK,GACAG,GAPEC,EAF2B,EAEhCxE,IAEUyE,GAJsB,EAGhCT,OAHgC,EAIhCC,UACGS,EAL6B,iCAW9BC,EAAO,KACPC,EAAS,KACTC,EAAa,KACbC,EAAY,KACZC,GAAU,EACVC,EAAe,WAAQ,EACvBC,EAAUT,EACVP,EAAWQ,EACXS,EAAW,EACXC,EAAS,EACTC,GAAa,EACbC,EAAQ,EAENC,EAAmB,SAACC,GACR,eAAZA,GAA2C,OAAfV,IAC9BA,IACAA,EAAa,KACbC,EAAY,KACZC,GAAU,EAEb,EACK/E,EAAM,SAACO,EAAMgF,GACjBP,EAAa,CAAEzE,OAAMgF,YACjBN,GACFO,QAAQxF,IAAR,WAAgBO,EAAhB,aAAyBgF,GAE5B,EACKE,EAAS,SAACC,GAAO,QACHA,EAAGlC,MAAM,KADN,GACdmC,EADc,KACXC,EADW,KACRC,EADQ,KAErB,OAAwB,GAAhBC,WAAWH,GAAU,GAAuB,GAAhBG,WAAWF,GAAWE,WAAWD,EACtE,EACKE,EAAgB,SAACR,EAASS,GAC9B,GAAuB,iBAAZT,EACT,GAAIA,EAAQU,WAAW,cAAe,CACpC,IAAMP,EAAKH,EAAQ/B,MAAM,MAAM,GAAGA,MAAM,MAAM,GACxC0C,EAAIT,EAAOC,GACjBM,EAAK,CAAEd,SAAUgB,EAAGb,WACH,IAAbH,GAAkBA,EAAWgB,KAC/BhB,EAAWgB,EACXd,GAAa,EAEhB,MAAM,GAAIA,GAAcG,EAAQU,WAAW,cAAe,CACzD,IAAME,EAAQZ,EAAQY,MAAM,gBAC5B,GAAIA,EAAO,CACT,IAAMC,EAAMN,WAAWK,EAAM,IAC7BhB,EAASD,EAAWkB,CACrB,MACCjB,EAAS,EAEXC,GAAa,CACd,MAAM,GAAIG,EAAQU,WAAW,UAAYV,EAAQU,WAAW,QAAS,CACpE,IAAMP,EAAKH,EAAQ/B,MAAM,SAAS,GAAGA,MAAM,KAAK,GAC1C6C,EAAIZ,EAAOC,GACXS,EAAQZ,EAAQY,MAAM,kBAC5B,GAAIhB,GAAUgB,EAAO,CACnB,IAAMG,EAAIR,WAAWK,EAAM,IAC3Bd,EAAQkB,KAAKC,IAAIF,EAAInB,EAAQ,EAC9B,MACCE,EAAQgB,EAAInB,EAEdc,EAAK,CAAEX,QAAOoB,KAAMJ,GACrB,MAAUd,EAAQU,WAAW,YAC5BD,EAAK,CAAEX,MAAO,IACdH,EAAW,EAGhB,EACKwB,EAAe,SAAC,GAAsB,IAApBnG,EAAoB,EAApBA,KAAMgF,EAAc,EAAdA,QAC5BvF,EAAIO,EAAMgF,GACVQ,EAAcR,EAAStB,GACvBqB,EAAiBC,EAClB,EAaKoB,EAAI,4CAAG,8GACX3G,EAAI,OAAQ,oBACC,OAAT2E,EAFO,wBAGT3E,EAAI,OAAQ,uBAHH,SAaCW,EAAoB+D,GAbrB,uBASPlD,EATO,EASPA,iBACA7B,EAVO,EAUPA,SACAmB,EAXO,EAWPA,WACAE,EAZO,EAYPA,SAZO,UAcIQ,EAAiB,CAK5BoF,oBAAqBjH,EACrBkH,SAAU,SAACtB,GAAD,OAAamB,EAAa,CAAEnG,KAAM,QAASgF,WAA3C,EACVuB,MAAO,SAACvB,GAAD,OAAamB,EAAa,CAAEnG,KAAM,QAASgF,WAA3C,EAMPwB,WAAY,SAACC,EAAMC,GACjB,GAAsB,oBAAXC,QAAuD,oBAAtBjG,kBAAmC,CAC7E,QAAwB,IAAbD,GACNgG,EAAKG,SAAS,oBACjB,OAAOnG,EAET,QAA0B,IAAfF,GACNkG,EAAKG,SAAS,yBACjB,OAAOrG,CAEV,CACD,OAAOmG,EAASD,CACjB,IAvCM,QAcTrC,EAdS,OAyCTC,EAASD,EAAKyC,MAAM1C,EAAQ2C,UAAY,aAAc,SAAU,CAAC,SAAU,WAC3ErH,EAAI,OAAQ,sBA1CH,8BA4CHkB,MAAM,mGA5CH,4CAAH,qDAmDJoG,EAAW,kBAAe,OAAT3C,CAAN,EAoBX4C,EAAM,WAAc,2BAAVC,EAAU,yBAAVA,EAAU,gBAExB,GADAxH,EAAI,OAAD,8BAAgCwH,EAAMC,KAAK,OACjC,OAAT9C,EACF,MAAML,EACD,GAAIS,EACT,MAAM7D,MAAM,kDAGZ,OADA6D,GAAU,EACH,IAAItD,SAAQ,SAACC,EAASc,GAC3B,IAAMkF,EAAO,YAAI5D,GAAgB0D,GAAOG,QAAO,SAAC9B,GAAD,OAAoB,IAAbA,EAAE+B,MAAT,IAC/C/C,EAAanD,EACboD,EAAYtC,EACZoC,EAAM,WAAN,IAAUT,EAAUQ,EAAM+C,IAC3B,GAEJ,EAiBKG,EAAK,SAACC,GAAoB,2BAATJ,EAAS,iCAATA,EAAS,kBAE9B,GADA1H,EAAI,OAAD,iBAAmB8H,EAAnB,YAA6BJ,EAAKjE,KAAI,SAACsE,GAAD,MAAyB,iBAARA,EAAmBA,EAA1B,WAAoCA,EAAIH,OAAxC,sBAAV,IAAgFH,KAAK,OACjH,OAAT9C,EACF,MAAML,EAEN,IAAI0D,EAAM,KACV,IAAI,MACFA,GAAM,EAAArD,EAAKkD,IAAGC,GAAR,QAAmBJ,EAS1B,CARC,MAAOO,GACP,KAAe,YAAXH,EACI5G,MAAM,yBAAD,OAA0BwG,EAAK,GAA/B,sEACS,aAAXI,EACH5G,MAAM,0BAAD,OAA2BwG,EAAK,GAAhC,uCAELxG,MAAM,8CAEf,CACD,OAAO8G,CAEV,EAKKE,EAAO,WACX,GAAa,OAATvD,EACF,MAAML,EAGFQ,GACFA,EAAU,qBAEZC,GAAU,EACV,IACEJ,EAAKuD,KAAK,EAWX,CAVC,MAAOC,GACPnI,EAAImI,EAAI5C,SACJT,GACFA,EAAUqD,EAEb,CAPD,QAQExD,EAAO,KACPC,EAAS,KACTC,EAAa,KACbC,EAAY,IACb,CAEJ,EAEKsD,EAAc,SAACC,GACnBpE,EAAWoE,CACZ,EAEKC,EAAY,SAACC,GACjBvD,EAAeuD,CAChB,EAEKC,EAAa,SAACC,GAClBxD,EAAUwD,CACX,EAID,OAFAzI,EAAI,OAAD,2BAA6BqE,IAEzB,CACL+D,cACAE,YACAE,aACA7B,OACAW,WACAC,MACAW,OACAL,KAEH,C,gBCtRD3D,EAAQ,KACR,IAAMwE,EAAexE,EAAQ,KACrBhB,EAAcgB,EAAQ,KAAtBhB,UAER3D,EAAOD,QAAU,CAoBfoJ,eAUAxF,Y,UC1BF3D,EAAOD,QAAU,CACfuC,kCATwC,SAAClC,GAAD,oIAC0EA,EAD1E,gJ,UCA1C,IAAIsF,GAAU,EACVD,EAAe,WAAQ,EAiB3BzF,EAAOD,QAAU,CACf2F,UACAuD,WAjBiB,SAACC,GAClBxD,EAAUwD,CACX,EAgBCE,gBAdsB,SAAC3E,GACvBgB,EAAehB,CAChB,EAaChE,IAXU,SAACO,EAAMgF,GACjBP,EAAa,CAAEzE,OAAMgF,YACjBN,GACFO,QAAQxF,IAAR,WAAgBO,EAAhB,aAAyBgF,GAE5B,E,UChBDhG,EAAOD,QAAU,SAACqF,EAAM+C,GACtB,IAAMkB,EAAUjE,EAAKkE,QAAQnB,EAAKE,OAASkB,YAAYC,mBAOvD,OANArB,EAAKsB,SAAQ,SAACnD,EAAGoD,GACf,IAAMC,EAAKvE,EAAKwE,gBAAgBtD,GAAK,EAC/B1F,EAAMwE,EAAKkE,QAAQK,GACzBvE,EAAKyE,aAAavD,EAAG1F,EAAK+I,GAC1BvE,EAAK0E,SAAST,EAAWE,YAAYC,kBAAoBE,EAAM9I,EAAK,MACrE,IACM,CAACuH,EAAKE,OAAQgB,EACtB,C,UCFD,IAAIU,EAAW,SAAUhK,GACvB,aAEA,IAEIgC,EAFAiI,EAAKC,OAAOC,UACZC,EAASH,EAAGI,eAEZC,EAA4B,mBAAXC,OAAwBA,OAAS,CAAC,EACnDC,EAAiBF,EAAQG,UAAY,aACrCC,EAAsBJ,EAAQK,eAAiB,kBAC/CC,EAAoBN,EAAQO,aAAe,gBAE/C,SAAS3K,EAAO4K,EAAKC,EAAKC,GAOxB,OANAd,OAAOe,eAAeH,EAAKC,EAAK,CAC9BC,MAAOA,EACPE,YAAY,EACZC,cAAc,EACdC,UAAU,IAELN,EAAIC,EACb,CACA,IAEE7K,EAAO,CAAC,EAAG,GAKb,CAJE,MAAO2I,GACP3I,EAAS,SAAS4K,EAAKC,EAAKC,GAC1B,OAAOF,EAAIC,GAAOC,CACpB,CACF,CAEA,SAASK,EAAKC,EAASC,EAASnL,EAAMoL,GAEpC,IAAIC,EAAiBF,GAAWA,EAAQpB,qBAAqBuB,EAAYH,EAAUG,EAC/EC,EAAYzB,OAAO0B,OAAOH,EAAetB,WACzC0B,EAAU,IAAIC,EAAQN,GAAe,IAMzC,OAFAG,EAAUI,QAsMZ,SAA0BT,EAASlL,EAAMyL,GACvC,IAAIG,EAAQC,EAEZ,OAAO,SAAgBzD,EAAQC,GAC7B,GAAIuD,IAAUE,EACZ,MAAM,IAAItK,MAAM,gCAGlB,GAAIoK,IAAUG,EAAmB,CAC/B,GAAe,UAAX3D,EACF,MAAMC,EAKR,OAAO2D,GACT,CAKA,IAHAP,EAAQrD,OAASA,EACjBqD,EAAQpD,IAAMA,IAED,CACX,IAAI4D,EAAWR,EAAQQ,SACvB,GAAIA,EAAU,CACZ,IAAIC,EAAiBC,EAAoBF,EAAUR,GACnD,GAAIS,EAAgB,CAClB,GAAIA,IAAmBE,EAAkB,SACzC,OAAOF,CACT,CACF,CAEA,GAAuB,SAAnBT,EAAQrD,OAGVqD,EAAQY,KAAOZ,EAAQa,MAAQb,EAAQpD,SAElC,GAAuB,UAAnBoD,EAAQrD,OAAoB,CACrC,GAAIwD,IAAUC,EAEZ,MADAD,EAAQG,EACFN,EAAQpD,IAGhBoD,EAAQc,kBAAkBd,EAAQpD,IAEpC,KAA8B,WAAnBoD,EAAQrD,QACjBqD,EAAQe,OAAO,SAAUf,EAAQpD,KAGnCuD,EAAQE,EAER,IAAIW,EAASC,EAASxB,EAASlL,EAAMyL,GACrC,GAAoB,WAAhBgB,EAAO5L,KAAmB,CAO5B,GAJA+K,EAAQH,EAAQkB,KACZZ,EACAa,EAEAH,EAAOpE,MAAQ+D,EACjB,SAGF,MAAO,CACLxB,MAAO6B,EAAOpE,IACdsE,KAAMlB,EAAQkB,KAGlB,CAA2B,UAAhBF,EAAO5L,OAChB+K,EAAQG,EAGRN,EAAQrD,OAAS,QACjBqD,EAAQpD,IAAMoE,EAAOpE,IAEzB,CACF,CACF,CAlRsBwE,CAAiB3B,EAASlL,EAAMyL,GAE7CF,CACT,CAaA,SAASmB,EAASI,EAAIpC,EAAKrC,GACzB,IACE,MAAO,CAAExH,KAAM,SAAUwH,IAAKyE,EAAGC,KAAKrC,EAAKrC,GAG7C,CAFE,MAAOI,GACP,MAAO,CAAE5H,KAAM,QAASwH,IAAKI,EAC/B,CACF,CAlBA7I,EAAQqL,KAAOA,EAoBf,IAAIY,EAAyB,iBACzBe,EAAyB,iBACzBd,EAAoB,YACpBC,EAAoB,YAIpBK,EAAmB,CAAC,EAMxB,SAASd,IAAa,CACtB,SAAS0B,IAAqB,CAC9B,SAASC,IAA8B,CAIvC,IAAIC,EAAoB,CAAC,EACzBA,EAAkB9C,GAAkB,WAClC,OAAO+C,IACT,EAEA,IAAIC,EAAWtD,OAAOuD,eAClBC,EAA0BF,GAAYA,EAASA,EAASG,EAAO,MAC/DD,GACAA,IAA4BzD,GAC5BG,EAAO+C,KAAKO,EAAyBlD,KAGvC8C,EAAoBI,GAGtB,IAAIE,EAAKP,EAA2BlD,UAClCuB,EAAUvB,UAAYD,OAAO0B,OAAO0B,GAWtC,SAASO,EAAsB1D,GAC7B,CAAC,OAAQ,QAAS,UAAUT,SAAQ,SAASlB,GAC3CtI,EAAOiK,EAAW3B,GAAQ,SAASC,GACjC,OAAO8E,KAAKxB,QAAQvD,EAAQC,EAC9B,GACF,GACF,CA+BA,SAASqF,EAAcnC,EAAWoC,GAChC,SAASC,EAAOxF,EAAQC,EAAKrG,EAASc,GACpC,IAAI2J,EAASC,EAASnB,EAAUnD,GAASmD,EAAWlD,GACpD,GAAoB,UAAhBoE,EAAO5L,KAEJ,CACL,IAAIqC,EAASuJ,EAAOpE,IAChBuC,EAAQ1H,EAAO0H,MACnB,OAAIA,GACiB,iBAAVA,GACPZ,EAAO+C,KAAKnC,EAAO,WACd+C,EAAY3L,QAAQ4I,EAAMiD,SAASC,MAAK,SAASlD,GACtDgD,EAAO,OAAQhD,EAAO5I,EAASc,EACjC,IAAG,SAAS2F,GACVmF,EAAO,QAASnF,EAAKzG,EAASc,EAChC,IAGK6K,EAAY3L,QAAQ4I,GAAOkD,MAAK,SAASC,GAI9C7K,EAAO0H,MAAQmD,EACf/L,EAAQkB,EACV,IAAG,SAASI,GAGV,OAAOsK,EAAO,QAAStK,EAAOtB,EAASc,EACzC,GACF,CAzBEA,EAAO2J,EAAOpE,IA0BlB,CAEA,IAAI2F,EAgCJb,KAAKxB,QA9BL,SAAiBvD,EAAQC,GACvB,SAAS4F,IACP,OAAO,IAAIN,GAAY,SAAS3L,EAASc,GACvC8K,EAAOxF,EAAQC,EAAKrG,EAASc,EAC/B,GACF,CAEA,OAAOkL,EAaLA,EAAkBA,EAAgBF,KAChCG,EAGAA,GACEA,GACR,CAKF,CA4GA,SAAS9B,EAAoBF,EAAUR,GACrC,IAAIrD,EAAS6D,EAAS5B,SAASoB,EAAQrD,QACvC,GAAIA,IAAWxG,EAAW,CAKxB,GAFA6J,EAAQQ,SAAW,KAEI,UAAnBR,EAAQrD,OAAoB,CAE9B,GAAI6D,EAAS5B,SAAiB,SAG5BoB,EAAQrD,OAAS,SACjBqD,EAAQpD,IAAMzG,EACduK,EAAoBF,EAAUR,GAEP,UAAnBA,EAAQrD,QAGV,OAAOgE,EAIXX,EAAQrD,OAAS,QACjBqD,EAAQpD,IAAM,IAAI6F,UAChB,iDACJ,CAEA,OAAO9B,CACT,CAEA,IAAIK,EAASC,EAAStE,EAAQ6D,EAAS5B,SAAUoB,EAAQpD,KAEzD,GAAoB,UAAhBoE,EAAO5L,KAIT,OAHA4K,EAAQrD,OAAS,QACjBqD,EAAQpD,IAAMoE,EAAOpE,IACrBoD,EAAQQ,SAAW,KACZG,EAGT,IAAI+B,EAAO1B,EAAOpE,IAElB,OAAM8F,EAOFA,EAAKxB,MAGPlB,EAAQQ,EAASmC,YAAcD,EAAKvD,MAGpCa,EAAQ4C,KAAOpC,EAASqC,QAQD,WAAnB7C,EAAQrD,SACVqD,EAAQrD,OAAS,OACjBqD,EAAQpD,IAAMzG,GAUlB6J,EAAQQ,SAAW,KACZG,GANE+B,GA3BP1C,EAAQrD,OAAS,QACjBqD,EAAQpD,IAAM,IAAI6F,UAAU,oCAC5BzC,EAAQQ,SAAW,KACZG,EA+BX,CAqBA,SAASmC,EAAaC,GACpB,IAAIC,EAAQ,CAAEC,OAAQF,EAAK,IAEvB,KAAKA,IACPC,EAAME,SAAWH,EAAK,IAGpB,KAAKA,IACPC,EAAMG,WAAaJ,EAAK,GACxBC,EAAMI,SAAWL,EAAK,IAGxBrB,KAAK2B,WAAWC,KAAKN,EACvB,CAEA,SAASO,EAAcP,GACrB,IAAIhC,EAASgC,EAAMQ,YAAc,CAAC,EAClCxC,EAAO5L,KAAO,gBACP4L,EAAOpE,IACdoG,EAAMQ,WAAaxC,CACrB,CAEA,SAASf,EAAQN,GAIf+B,KAAK2B,WAAa,CAAC,CAAEJ,OAAQ,SAC7BtD,EAAY9B,QAAQiF,EAAcpB,MAClCA,KAAK+B,OAAM,EACb,CA6BA,SAAS3B,EAAO4B,GACd,GAAIA,EAAU,CACZ,IAAIC,EAAiBD,EAAS/E,GAC9B,GAAIgF,EACF,OAAOA,EAAerC,KAAKoC,GAG7B,GAA6B,mBAAlBA,EAASd,KAClB,OAAOc,EAGT,IAAKE,MAAMF,EAASjH,QAAS,CAC3B,IAAIoH,GAAK,EAAGjB,EAAO,SAASA,IAC1B,OAASiB,EAAIH,EAASjH,QACpB,GAAI8B,EAAO+C,KAAKoC,EAAUG,GAGxB,OAFAjB,EAAKzD,MAAQuE,EAASG,GACtBjB,EAAK1B,MAAO,EACL0B,EAOX,OAHAA,EAAKzD,MAAQhJ,EACbyM,EAAK1B,MAAO,EAEL0B,CACT,EAEA,OAAOA,EAAKA,KAAOA,CACrB,CACF,CAGA,MAAO,CAAEA,KAAMrC,EACjB,CAGA,SAASA,IACP,MAAO,CAAEpB,MAAOhJ,EAAW+K,MAAM,EACnC,CA8MA,OA5mBAK,EAAkBjD,UAAYyD,EAAG+B,YAActC,EAC/CA,EAA2BsC,YAAcvC,EACzCA,EAAkBwC,YAAc1P,EAC9BmN,EACAzC,EACA,qBAaF5K,EAAQ6P,oBAAsB,SAASC,GACrC,IAAIC,EAAyB,mBAAXD,GAAyBA,EAAOH,YAClD,QAAOI,IACHA,IAAS3C,GAG2B,uBAAnC2C,EAAKH,aAAeG,EAAKC,MAEhC,EAEAhQ,EAAQiQ,KAAO,SAASH,GAQtB,OAPI5F,OAAOgG,eACThG,OAAOgG,eAAeJ,EAAQzC,IAE9ByC,EAAOK,UAAY9C,EACnBnN,EAAO4P,EAAQlF,EAAmB,sBAEpCkF,EAAO3F,UAAYD,OAAO0B,OAAOgC,GAC1BkC,CACT,EAMA9P,EAAQoQ,MAAQ,SAAS3H,GACvB,MAAO,CAAEwF,QAASxF,EACpB,EAqEAoF,EAAsBC,EAAc3D,WACpC2D,EAAc3D,UAAUO,GAAuB,WAC7C,OAAO6C,IACT,EACAvN,EAAQ8N,cAAgBA,EAKxB9N,EAAQqQ,MAAQ,SAAS/E,EAASC,EAASnL,EAAMoL,EAAauC,QACxC,IAAhBA,IAAwBA,EAAc5L,SAE1C,IAAImO,EAAO,IAAIxC,EACbzC,EAAKC,EAASC,EAASnL,EAAMoL,GAC7BuC,GAGF,OAAO/N,EAAQ6P,oBAAoBtE,GAC/B+E,EACAA,EAAK7B,OAAOP,MAAK,SAAS5K,GACxB,OAAOA,EAAOyJ,KAAOzJ,EAAO0H,MAAQsF,EAAK7B,MAC3C,GACN,EAqKAZ,EAAsBD,GAEtB1N,EAAO0N,EAAIhD,EAAmB,aAO9BgD,EAAGpD,GAAkB,WACnB,OAAO+C,IACT,EAEAK,EAAG2C,SAAW,WACZ,MAAO,oBACT,EAiCAvQ,EAAQwQ,KAAO,SAASC,GACtB,IAAID,EAAO,GACX,IAAK,IAAIzF,KAAO0F,EACdD,EAAKrB,KAAKpE,GAMZ,OAJAyF,EAAKE,UAIE,SAASjC,IACd,KAAO+B,EAAKlI,QAAQ,CAClB,IAAIyC,EAAMyF,EAAKG,MACf,GAAI5F,KAAO0F,EAGT,OAFAhC,EAAKzD,MAAQD,EACb0D,EAAK1B,MAAO,EACL0B,CAEX,CAMA,OADAA,EAAK1B,MAAO,EACL0B,CACT,CACF,EAoCAzO,EAAQ2N,OAASA,EAMjB7B,EAAQ3B,UAAY,CAClBwF,YAAa7D,EAEbwD,MAAO,SAASsB,GAcd,GAbArD,KAAKsD,KAAO,EACZtD,KAAKkB,KAAO,EAGZlB,KAAKd,KAAOc,KAAKb,MAAQ1K,EACzBuL,KAAKR,MAAO,EACZQ,KAAKlB,SAAW,KAEhBkB,KAAK/E,OAAS,OACd+E,KAAK9E,IAAMzG,EAEXuL,KAAK2B,WAAWxF,QAAQ0F,IAEnBwB,EACH,IAAK,IAAIZ,KAAQzC,KAEQ,MAAnByC,EAAKc,OAAO,IACZ1G,EAAO+C,KAAKI,KAAMyC,KACjBP,OAAOO,EAAKe,MAAM,MACrBxD,KAAKyC,GAAQhO,EAIrB,EAEAgP,KAAM,WACJzD,KAAKR,MAAO,EAEZ,IACIkE,EADY1D,KAAK2B,WAAW,GACLG,WAC3B,GAAwB,UAApB4B,EAAWhQ,KACb,MAAMgQ,EAAWxI,IAGnB,OAAO8E,KAAK2D,IACd,EAEAvE,kBAAmB,SAASwE,GAC1B,GAAI5D,KAAKR,KACP,MAAMoE,EAGR,IAAItF,EAAU0B,KACd,SAAS6D,EAAOC,EAAKC,GAYnB,OAXAzE,EAAO5L,KAAO,QACd4L,EAAOpE,IAAM0I,EACbtF,EAAQ4C,KAAO4C,EAEXC,IAGFzF,EAAQrD,OAAS,OACjBqD,EAAQpD,IAAMzG,KAGNsP,CACZ,CAEA,IAAK,IAAI5B,EAAInC,KAAK2B,WAAW5G,OAAS,EAAGoH,GAAK,IAAKA,EAAG,CACpD,IAAIb,EAAQtB,KAAK2B,WAAWQ,GACxB7C,EAASgC,EAAMQ,WAEnB,GAAqB,SAAjBR,EAAMC,OAIR,OAAOsC,EAAO,OAGhB,GAAIvC,EAAMC,QAAUvB,KAAKsD,KAAM,CAC7B,IAAIU,EAAWnH,EAAO+C,KAAK0B,EAAO,YAC9B2C,EAAapH,EAAO+C,KAAK0B,EAAO,cAEpC,GAAI0C,GAAYC,EAAY,CAC1B,GAAIjE,KAAKsD,KAAOhC,EAAME,SACpB,OAAOqC,EAAOvC,EAAME,UAAU,GACzB,GAAIxB,KAAKsD,KAAOhC,EAAMG,WAC3B,OAAOoC,EAAOvC,EAAMG,WAGxB,MAAO,GAAIuC,GACT,GAAIhE,KAAKsD,KAAOhC,EAAME,SACpB,OAAOqC,EAAOvC,EAAME,UAAU,OAG3B,KAAIyC,EAMT,MAAM,IAAI5P,MAAM,0CALhB,GAAI2L,KAAKsD,KAAOhC,EAAMG,WACpB,OAAOoC,EAAOvC,EAAMG,WAKxB,CACF,CACF,CACF,EAEApC,OAAQ,SAAS3L,EAAMwH,GACrB,IAAK,IAAIiH,EAAInC,KAAK2B,WAAW5G,OAAS,EAAGoH,GAAK,IAAKA,EAAG,CACpD,IAAIb,EAAQtB,KAAK2B,WAAWQ,GAC5B,GAAIb,EAAMC,QAAUvB,KAAKsD,MACrBzG,EAAO+C,KAAK0B,EAAO,eACnBtB,KAAKsD,KAAOhC,EAAMG,WAAY,CAChC,IAAIyC,EAAe5C,EACnB,KACF,CACF,CAEI4C,IACU,UAATxQ,GACS,aAATA,IACDwQ,EAAa3C,QAAUrG,GACvBA,GAAOgJ,EAAazC,aAGtByC,EAAe,MAGjB,IAAI5E,EAAS4E,EAAeA,EAAapC,WAAa,CAAC,EAIvD,OAHAxC,EAAO5L,KAAOA,EACd4L,EAAOpE,IAAMA,EAETgJ,GACFlE,KAAK/E,OAAS,OACd+E,KAAKkB,KAAOgD,EAAazC,WAClBxC,GAGFe,KAAKmE,SAAS7E,EACvB,EAEA6E,SAAU,SAAS7E,EAAQoC,GACzB,GAAoB,UAAhBpC,EAAO5L,KACT,MAAM4L,EAAOpE,IAcf,MAXoB,UAAhBoE,EAAO5L,MACS,aAAhB4L,EAAO5L,KACTsM,KAAKkB,KAAO5B,EAAOpE,IACM,WAAhBoE,EAAO5L,MAChBsM,KAAK2D,KAAO3D,KAAK9E,IAAMoE,EAAOpE,IAC9B8E,KAAK/E,OAAS,SACd+E,KAAKkB,KAAO,OACa,WAAhB5B,EAAO5L,MAAqBgO,IACrC1B,KAAKkB,KAAOQ,GAGPzC,CACT,EAEAmF,OAAQ,SAAS3C,GACf,IAAK,IAAIU,EAAInC,KAAK2B,WAAW5G,OAAS,EAAGoH,GAAK,IAAKA,EAAG,CACpD,IAAIb,EAAQtB,KAAK2B,WAAWQ,GAC5B,GAAIb,EAAMG,aAAeA,EAGvB,OAFAzB,KAAKmE,SAAS7C,EAAMQ,WAAYR,EAAMI,UACtCG,EAAcP,GACPrC,CAEX,CACF,EAEA,MAAS,SAASsC,GAChB,IAAK,IAAIY,EAAInC,KAAK2B,WAAW5G,OAAS,EAAGoH,GAAK,IAAKA,EAAG,CACpD,IAAIb,EAAQtB,KAAK2B,WAAWQ,GAC5B,GAAIb,EAAMC,SAAWA,EAAQ,CAC3B,IAAIjC,EAASgC,EAAMQ,WACnB,GAAoB,UAAhBxC,EAAO5L,KAAkB,CAC3B,IAAI2Q,EAAS/E,EAAOpE,IACpB2G,EAAcP,EAChB,CACA,OAAO+C,CACT,CACF,CAIA,MAAM,IAAIhQ,MAAM,wBAClB,EAEAiQ,cAAe,SAAStC,EAAUf,EAAYE,GAa5C,OAZAnB,KAAKlB,SAAW,CACd5B,SAAUkD,EAAO4B,GACjBf,WAAYA,EACZE,QAASA,GAGS,SAAhBnB,KAAK/E,SAGP+E,KAAK9E,IAAMzG,GAGNwK,CACT,GAOKxM,CAET,CA/sBc,CAotBiBC,EAAOD,SAGtC,IACE8R,mBAAqB9H,CAYvB,CAXE,MAAO+H,GAUPC,SAAS,IAAK,yBAAdA,CAAwChI,EAC1C,C,gjEC1uBIiI,EAA2B,CAAC,EAGhC,SAASC,EAAoBC,GAE5B,GAAGF,EAAyBE,GAC3B,OAAOF,EAAyBE,GAAUnS,QAG3C,IAAIC,EAASgS,EAAyBE,GAAY,CAGjDnS,QAAS,CAAC,GAOX,OAHAoS,EAAoBD,GAAUlS,EAAQA,EAAOD,QAASkS,GAG/CjS,EAAOD,OACf,CClBA,ODqBAkS,EAAoB5L,EAAI8L,EEvBxBF,EAAoBtL,EAAI,CAAC5G,EAASqS,KACjC,IAAI,IAAItH,KAAOsH,EACXH,EAAoBI,EAAED,EAAYtH,KAASmH,EAAoBI,EAAEtS,EAAS+K,IAC5Eb,OAAOe,eAAejL,EAAS+K,EAAK,CAAEG,YAAY,EAAMqH,IAAKF,EAAWtH,IAE1E,ECNDmH,EAAoBM,EAAI,WACvB,GAA0B,iBAAfnQ,WAAyB,OAAOA,WAC3C,IACC,OAAOkL,MAAQ,IAAIyE,SAAS,cAAb,EAGhB,CAFE,MAAOrJ,GACR,GAAsB,iBAAXf,OAAqB,OAAOA,MACxC,CACA,CAPuB,GCAxBsK,EAAoBI,EAAI,CAACxH,EAAK2H,IAASvI,OAAOC,UAAUE,eAAe8C,KAAKrC,EAAK2H,GCCjFP,EAAoBQ,EAAK1S,IACH,oBAAXuK,QAA0BA,OAAOM,aAC1CX,OAAOe,eAAejL,EAASuK,OAAOM,YAAa,CAAEG,MAAO,WAE7Dd,OAAOe,eAAejL,EAAS,aAAc,CAAEgL,OAAO,GAAO,E,MCL9D,IAAI2H,EACAT,EAAoBM,EAAElQ,gBAAeqQ,EAAYT,EAAoBM,EAAEI,SAAW,IACtF,IAAInQ,EAAWyP,EAAoBM,EAAE/P,SACrC,IAAKkQ,GAAalQ,IACbA,EAASoQ,gBACZF,EAAYlQ,EAASoQ,cAAclQ,MAC/BgQ,GAAW,CACf,IAAIG,EAAUrQ,EAASM,qBAAqB,UACzC+P,EAAQxK,SAAQqK,EAAYG,EAAQA,EAAQxK,OAAS,GAAG3F,IAC5D,CAID,IAAKgQ,EAAW,MAAM,IAAI/Q,MAAM,yDAChC+Q,EAAYA,EAAU1Q,QAAQ,OAAQ,IAAIA,QAAQ,QAAS,IAAIA,QAAQ,YAAa,KACpFiQ,EAAoBa,EAAIJ,C,KCfxBT,EAAoBc,EAAIvQ,SAASwQ,SAAW7S,KAAKwS,SAAS7Q,KNGnDmQ,EAAoB,I","file":"ffmpeg.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"FFmpeg\"] = factory();\n\telse\n\t\troot[\"FFmpeg\"] = factory();\n})(self, function() {\nreturn ","import pkg from '../../package.json';\n\n/*\n * Default options for browser environment\n */\nconst corePath = typeof process !== 'undefined' && process.env.NODE_ENV === 'development'\n ? new URL('/node_modules/@ffmpeg/core/dist/ffmpeg-core.js', import.meta.url).href\n : `https://unpkg.com/@ffmpeg/core@${pkg.devDependencies['@ffmpeg/core'].substring(1)}/dist/ffmpeg-core.js`;\n\nexport default { corePath };\n","/* eslint-disable no-undef */\nimport { log } from '../utils/log';\nimport {\n CREATE_FFMPEG_CORE_IS_NOT_DEFINED,\n} from '../utils/errors';\n\n/*\n * Fetch data from remote URL and convert to blob URL\n * to avoid CORS issue\n */\nconst toBlobURL = async (url, mimeType) => {\n log('info', `fetch ${url}`);\n const buf = await (await fetch(url)).arrayBuffer();\n log('info', `${url} file size = ${buf.byteLength} bytes`);\n const blob = new Blob([buf], { type: mimeType });\n const blobURL = URL.createObjectURL(blob);\n log('info', `${url} blob URL = ${blobURL}`);\n return blobURL;\n};\n\n// eslint-disable-next-line\nexport const getCreateFFmpegCore = async ({\n corePath: _corePath,\n workerPath: _workerPath,\n wasmPath: _wasmPath,\n}) => {\n // in Web Worker context\n // eslint-disable-next-line\n if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {\n if (typeof _corePath !== 'string') {\n throw Error('corePath should be a string!');\n }\n const coreRemotePath = new URL(_corePath, import.meta.url).href;\n const corePath = await toBlobURL(\n coreRemotePath,\n 'application/javascript',\n );\n const wasmPath = await toBlobURL(\n _wasmPath !== undefined ? _wasmPath : coreRemotePath.replace('ffmpeg-core.js', 'ffmpeg-core.wasm'),\n 'application/wasm',\n );\n const workerPath = await toBlobURL(\n _workerPath !== undefined ? _workerPath : coreRemotePath.replace('ffmpeg-core.js', 'ffmpeg-core.worker.js'),\n 'application/javascript',\n );\n if (typeof createFFmpegCore === 'undefined') {\n return new Promise((resolve) => {\n globalThis.importScripts(corePath);\n if (typeof createFFmpegCore === 'undefined') {\n throw Error(CREATE_FFMPEG_CORE_IS_NOT_DEFINED(coreRemotePath));\n }\n log('info', 'ffmpeg-core.js script loaded');\n resolve({\n createFFmpegCore,\n corePath,\n wasmPath,\n workerPath,\n });\n });\n }\n log('info', 'ffmpeg-core.js script is loaded already');\n return Promise.resolve({\n createFFmpegCore,\n corePath,\n wasmPath,\n workerPath,\n });\n }\n if (typeof _corePath !== 'string') {\n throw Error('corePath should be a string!');\n }\n const coreRemotePath = new URL(_corePath, import.meta.url).href;\n const corePath = await toBlobURL(\n coreRemotePath,\n 'application/javascript',\n );\n const wasmPath = await toBlobURL(\n _wasmPath !== undefined ? _wasmPath : coreRemotePath.replace('ffmpeg-core.js', 'ffmpeg-core.wasm'),\n 'application/wasm',\n );\n const workerPath = await toBlobURL(\n _workerPath !== undefined ? _workerPath : coreRemotePath.replace('ffmpeg-core.js', 'ffmpeg-core.worker.js'),\n 'application/javascript',\n );\n if (typeof createFFmpegCore === 'undefined') {\n return new Promise((resolve) => {\n const script = document.createElement('script');\n const eventHandler = () => {\n script.removeEventListener('load', eventHandler);\n if (typeof createFFmpegCore === 'undefined') {\n throw Error(CREATE_FFMPEG_CORE_IS_NOT_DEFINED(coreRemotePath));\n }\n log('info', 'ffmpeg-core.js script loaded');\n resolve({\n createFFmpegCore,\n corePath,\n wasmPath,\n workerPath,\n });\n };\n script.src = corePath;\n script.type = 'text/javascript';\n script.addEventListener('load', eventHandler);\n document.getElementsByTagName('head')[0].appendChild(script);\n });\n }\n log('info', 'ffmpeg-core.js script is loaded already');\n return Promise.resolve({\n createFFmpegCore,\n corePath,\n wasmPath,\n workerPath,\n });\n};\n","const readFromBlobOrFile = (blob) => (\n new Promise((resolve, reject) => {\n const fileReader = new FileReader();\n fileReader.onload = () => {\n resolve(fileReader.result);\n };\n fileReader.onerror = ({ target: { error: { code } } }) => {\n reject(Error(`File could not be read! Code=${code}`));\n };\n fileReader.readAsArrayBuffer(blob);\n })\n);\n\n// eslint-disable-next-line\nexport const fetchFile = async (_data) => {\n let data = _data;\n if (typeof _data === 'undefined') {\n return new Uint8Array();\n }\n\n if (typeof _data === 'string') {\n /* From base64 format */\n if (/data:_data\\/([a-zA-Z]*);base64,([^\"]*)/.test(_data)) {\n data = atob(_data.split(',')[1])\n .split('')\n .map((c) => c.charCodeAt(0));\n /* From remote server/URL */\n } else {\n const res = await fetch(new URL(_data, import.meta.url).href);\n data = await res.arrayBuffer();\n }\n /* From Blob or File */\n } else if (_data instanceof File || _data instanceof Blob) {\n data = await readFromBlobOrFile(_data);\n }\n\n return new Uint8Array(data);\n};\n","module.exports = {\n defaultArgs: [\n /* args[0] is always the binary path */\n './ffmpeg',\n /* Disable interaction mode */\n '-nostdin',\n /* Force to override output file */\n '-y',\n ],\n baseOptions: {\n /* Flag to turn on/off log messages in console */\n log: false,\n /*\n * Custom logger to get ffmpeg.wasm output messages.\n * a sample logger looks like this:\n *\n * ```\n * logger = ({ type, message }) => {\n * console.log(type, message);\n * }\n * ```\n *\n * type can be one of following:\n *\n * info: internal workflow debug messages\n * fferr: ffmpeg native stderr output\n * ffout: ffmpeg native stdout output\n */\n logger: () => {},\n /*\n * Progress handler to get current progress of ffmpeg command.\n * a sample progress handler looks like this:\n *\n * ```\n * progress = ({ ratio }) => {\n * console.log(ratio);\n * }\n * ```\n *\n * ratio is a float number between 0 to 1.\n */\n progress: () => {},\n /*\n * Path to find/download ffmpeg.wasm-core,\n * this value should be overwriten by `defaultOptions` in\n * each environment.\n */\n corePath: '',\n },\n};\n","const { defaultArgs, baseOptions } = require('./config');\nconst parseArgs = require('./utils/parseArgs');\nconst { defaultOptions, getCreateFFmpegCore } = require('./node');\nconst { version } = require('../package.json');\n\nconst NO_LOAD = Error('ffmpeg.wasm is not ready, make sure you have completed load().');\n\nmodule.exports = (_options = {}) => {\n const {\n log: optLog,\n logger,\n progress: optProgress,\n ...options\n } = {\n ...baseOptions,\n ...defaultOptions,\n ..._options,\n };\n let Core = null;\n let ffmpeg = null;\n let runResolve = null;\n let runReject = null;\n let running = false;\n let customLogger = () => {};\n let logging = optLog;\n let progress = optProgress;\n let duration = 0;\n let frames = 0;\n let readFrames = false;\n let ratio = 0;\n\n const detectCompletion = (message) => {\n if (message === 'FFMPEG_END' && runResolve !== null) {\n runResolve();\n runResolve = null;\n runReject = null;\n running = false;\n }\n };\n const log = (type, message) => {\n customLogger({ type, message });\n if (logging) {\n console.log(`[${type}] ${message}`);\n }\n };\n const ts2sec = (ts) => {\n const [h, m, s] = ts.split(':');\n return (parseFloat(h) * 60 * 60) + (parseFloat(m) * 60) + parseFloat(s);\n };\n const parseProgress = (message, prog) => {\n if (typeof message === 'string') {\n if (message.startsWith(' Duration')) {\n const ts = message.split(', ')[0].split(': ')[1];\n const d = ts2sec(ts);\n prog({ duration: d, ratio });\n if (duration === 0 || duration > d) {\n duration = d;\n readFrames = true;\n }\n } else if (readFrames && message.startsWith(' Stream')) {\n const match = message.match(/([\\d.]+) fps/);\n if (match) {\n const fps = parseFloat(match[1]);\n frames = duration * fps;\n } else {\n frames = 0;\n }\n readFrames = false;\n } else if (message.startsWith('frame') || message.startsWith('size')) {\n const ts = message.split('time=')[1].split(' ')[0];\n const t = ts2sec(ts);\n const match = message.match(/frame=\\s*(\\d+)/);\n if (frames && match) {\n const f = parseFloat(match[1]);\n ratio = Math.min(f / frames, 1);\n } else {\n ratio = t / duration;\n }\n prog({ ratio, time: t });\n } else if (message.startsWith('video:')) {\n prog({ ratio: 1 });\n duration = 0;\n }\n }\n };\n const parseMessage = ({ type, message }) => {\n log(type, message);\n parseProgress(message, progress);\n detectCompletion(message);\n };\n\n /*\n * Load ffmpeg.wasm-core script.\n * In browser environment, the ffmpeg.wasm-core script is fetch from\n * CDN and can be assign to a local path by assigning `corePath`.\n * In node environment, we use dynamic require and the default `corePath`\n * is `$ffmpeg/core`.\n *\n * Typically the load() func might take few seconds to minutes to complete,\n * better to do it as early as possible.\n *\n */\n const load = async () => {\n log('info', 'load ffmpeg-core');\n if (Core === null) {\n log('info', 'loading ffmpeg-core');\n /*\n * In node environment, all paths are undefined as there\n * is no need to set them.\n */\n const {\n createFFmpegCore,\n corePath,\n workerPath,\n wasmPath,\n } = await getCreateFFmpegCore(options);\n Core = await createFFmpegCore({\n /*\n * Assign mainScriptUrlOrBlob fixes chrome extension web worker issue\n * as there is no document.currentScript in the context of content_scripts\n */\n mainScriptUrlOrBlob: corePath,\n printErr: (message) => parseMessage({ type: 'fferr', message }),\n print: (message) => parseMessage({ type: 'ffout', message }),\n /*\n * locateFile overrides paths of files that is loaded by main script (ffmpeg-core.js).\n * It is critical for browser environment and we override both wasm and worker paths\n * as we are using blob URL instead of original URL to avoid cross origin issues.\n */\n locateFile: (path, prefix) => {\n if (typeof window !== 'undefined' || typeof WorkerGlobalScope !== 'undefined') {\n if (typeof wasmPath !== 'undefined'\n && path.endsWith('ffmpeg-core.wasm')) {\n return wasmPath;\n }\n if (typeof workerPath !== 'undefined'\n && path.endsWith('ffmpeg-core.worker.js')) {\n return workerPath;\n }\n }\n return prefix + path;\n },\n });\n ffmpeg = Core.cwrap(options.mainName || 'proxy_main', 'number', ['number', 'number']);\n log('info', 'ffmpeg-core loaded');\n } else {\n throw Error('ffmpeg.wasm was loaded, you should not load it again, use ffmpeg.isLoaded() to check next time.');\n }\n };\n\n /*\n * Determine whether the Core is loaded.\n */\n const isLoaded = () => Core !== null;\n\n /*\n * Run ffmpeg command.\n * This is the major function in ffmpeg.wasm, you can just imagine it\n * as ffmpeg native cli and what you need to pass is the same.\n *\n * For example, you can convert native command below:\n *\n * ```\n * $ ffmpeg -i video.avi -c:v libx264 video.mp4\n * ```\n *\n * To\n *\n * ```\n * await ffmpeg.run('-i', 'video.avi', '-c:v', 'libx264', 'video.mp4');\n * ```\n *\n */\n const run = (..._args) => {\n log('info', `run ffmpeg command: ${_args.join(' ')}`);\n if (Core === null) {\n throw NO_LOAD;\n } else if (running) {\n throw Error('ffmpeg.wasm can only run one command at a time');\n } else {\n running = true;\n return new Promise((resolve, reject) => {\n const args = [...defaultArgs, ..._args].filter((s) => s.length !== 0);\n runResolve = resolve;\n runReject = reject;\n ffmpeg(...parseArgs(Core, args));\n });\n }\n };\n\n /*\n * Run FS operations.\n * For input/output file of ffmpeg.wasm, it is required to save them to MEMFS\n * first so that ffmpeg.wasm is able to consume them. Here we rely on the FS\n * methods provided by Emscripten.\n *\n * Common methods to use are:\n * ffmpeg.FS('writeFile', 'video.avi', new Uint8Array(...)): writeFile writes\n * data to MEMFS. You need to use Uint8Array for binary data.\n * ffmpeg.FS('readFile', 'video.mp4'): readFile from MEMFS.\n * ffmpeg.FS('unlink', 'video.map'): delete file from MEMFS.\n *\n * For more info, check https://emscripten.org/docs/api_reference/Filesystem-API.html\n *\n */\n const FS = (method, ...args) => {\n log('info', `run FS.${method} ${args.map((arg) => (typeof arg === 'string' ? arg : `<${arg.length} bytes binary file>`)).join(' ')}`);\n if (Core === null) {\n throw NO_LOAD;\n } else {\n let ret = null;\n try {\n ret = Core.FS[method](...args);\n } catch (e) {\n if (method === 'readdir') {\n throw Error(`ffmpeg.FS('readdir', '${args[0]}') error. Check if the path exists, ex: ffmpeg.FS('readdir', '/')`);\n } else if (method === 'readFile') {\n throw Error(`ffmpeg.FS('readFile', '${args[0]}') error. Check if the path exists`);\n } else {\n throw Error('Oops, something went wrong in FS operation.');\n }\n }\n return ret;\n }\n };\n\n /**\n * forcibly terminate the ffmpeg program.\n */\n const exit = () => {\n if (Core === null) {\n throw NO_LOAD;\n } else {\n // if there's any pending runs, reject them\n if (runReject) {\n runReject('ffmpeg has exited');\n }\n running = false;\n try {\n Core.exit(1);\n } catch (err) {\n log(err.message);\n if (runReject) {\n runReject(err);\n }\n } finally {\n Core = null;\n ffmpeg = null;\n runResolve = null;\n runReject = null;\n }\n }\n };\n\n const setProgress = (_progress) => {\n progress = _progress;\n };\n\n const setLogger = (_logger) => {\n customLogger = _logger;\n };\n\n const setLogging = (_logging) => {\n logging = _logging;\n };\n\n log('info', `use ffmpeg.wasm v${version}`);\n\n return {\n setProgress,\n setLogger,\n setLogging,\n load,\n isLoaded,\n run,\n exit,\n FS,\n };\n};\n","require('regenerator-runtime/runtime');\nconst createFFmpeg = require('./createFFmpeg');\nconst { fetchFile } = require('./node');\n\nmodule.exports = {\n /*\n * Create ffmpeg instance.\n * Each ffmpeg instance owns an isolated MEMFS and works\n * independently.\n *\n * For example:\n *\n * ```\n * const ffmpeg = createFFmpeg({\n * log: true,\n * logger: () => {},\n * progress: () => {},\n * corePath: '',\n * })\n * ```\n *\n * For the usage of these four arguments, check config.js\n *\n */\n createFFmpeg,\n /*\n * Helper function for fetching files from various resource.\n * Sometimes the video/audio file you want to process may located\n * in a remote URL and somewhere in your local file system.\n *\n * This helper function helps you to fetch to file and return an\n * Uint8Array variable for ffmpeg.wasm to consume.\n *\n */\n fetchFile,\n};\n","const CREATE_FFMPEG_CORE_IS_NOT_DEFINED = (corePath) => (`\ncreateFFmpegCore is not defined. ffmpeg.wasm is unable to find createFFmpegCore after loading ffmpeg-core.js from ${corePath}. Use another URL when calling createFFmpeg():\n\nconst ffmpeg = createFFmpeg({\n corePath: 'http://localhost:3000/ffmpeg-core.js',\n});\n`);\n\nmodule.exports = {\n CREATE_FFMPEG_CORE_IS_NOT_DEFINED,\n};\n","let logging = false;\nlet customLogger = () => {};\n\nconst setLogging = (_logging) => {\n logging = _logging;\n};\n\nconst setCustomLogger = (logger) => {\n customLogger = logger;\n};\n\nconst log = (type, message) => {\n customLogger({ type, message });\n if (logging) {\n console.log(`[${type}] ${message}`);\n }\n};\n\nmodule.exports = {\n logging,\n setLogging,\n setCustomLogger,\n log,\n};\n","module.exports = (Core, args) => {\n const argsPtr = Core._malloc(args.length * Uint32Array.BYTES_PER_ELEMENT);\n args.forEach((s, idx) => {\n const sz = Core.lengthBytesUTF8(s) + 1;\n const buf = Core._malloc(sz);\n Core.stringToUTF8(s, buf, sz);\n Core.setValue(argsPtr + (Uint32Array.BYTES_PER_ELEMENT * idx), buf, 'i32');\n });\n return [args.length, argsPtr];\n};\n","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n IteratorPrototype[iteratorSymbol] = function () {\n return this;\n };\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n return this;\n };\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n Gp[iteratorSymbol] = function() {\n return this;\n };\n\n Gp.toString = function() {\n return \"[object Generator]\";\n };\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n}\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tif(__webpack_module_cache__[moduleId]) {\n\t\treturn __webpack_module_cache__[moduleId].exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// module exports must be returned from runtime so entry inlining is disabled\n// startup\n// Load entry module and return exports\nreturn __webpack_require__(352);\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop)","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","var scriptUrl;\nif (__webpack_require__.g.importScripts) scriptUrl = __webpack_require__.g.location + \"\";\nvar document = __webpack_require__.g.document;\nif (!scriptUrl && document) {\n\tif (document.currentScript)\n\t\tscriptUrl = document.currentScript.src\n\tif (!scriptUrl) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tif(scripts.length) scriptUrl = scripts[scripts.length - 1].src\n\t}\n}\n// When supporting browsers where an automatic publicPath is not supported you must specify an output.publicPath manually via configuration\n// or pass an empty string (\"\") and set the __webpack_public_path__ variable from your code to use your own logic.\nif (!scriptUrl) throw new Error(\"Automatic publicPath is not supported in this browser\");\nscriptUrl = scriptUrl.replace(/#.*$/, \"\").replace(/\\?.*$/, \"\").replace(/\\/[^\\/]+$/, \"/\");\n__webpack_require__.p = scriptUrl;","__webpack_require__.b = document.baseURI || self.location.href;\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// Promise = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t179: 0\n};\n\n\n// no chunk on demand loading\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n// no deferred startup\n\n// no jsonp function"],"sourceRoot":""} \ No newline at end of file diff --git a/node_modules/@ffmpeg/ffmpeg/package.json b/node_modules/@ffmpeg/ffmpeg/package.json new file mode 100644 index 0000000..f99cf8d --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/package.json @@ -0,0 +1,73 @@ +{ + "name": "@ffmpeg/ffmpeg", + "version": "0.11.6", + "description": "FFmpeg WebAssembly version", + "main": "src/index.js", + "types": "src/index.d.ts", + "directories": { + "example": "examples" + }, + "scripts": { + "start": "node scripts/server.js", + "start:worker": "node scripts/worker-server.js", + "build": "rimraf dist && webpack --config scripts/webpack.config.prod.js", + "build:worker": "rimraf dist && webpack --config scripts/webpack.config.worker.prod.js", + "prepublishOnly": "npm run build", + "lint": "eslint src", + "wait": "rimraf dist && wait-on http://localhost:3000/dist/ffmpeg.dev.js", + "test": "npm-run-all -p -r start test:all", + "test:all": "npm-run-all wait test:browser:ffmpeg test:node:all", + "test:node": "node node_modules/mocha/bin/_mocha --exit --bail --require ./scripts/test-helper.js", + "test:node:all": "npm run test:node -- ./tests/*.test.js", + "test:browser": "mocha-headless-chrome -a allow-file-access-from-files -a incognito -a no-sandbox -a disable-setuid-sandbox -a disable-logging -t 300000", + "test:browser:ffmpeg": "npm run test:browser -- -f ./tests/ffmpeg.test.html" + }, + "browser": { + "./src/node/index.js": "./src/browser/index.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ffmpegwasm/ffmpeg.wasm.git" + }, + "keywords": [ + "ffmpeg", + "WebAssembly", + "video" + ], + "author": "Jerome Wu ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ffmpegwasm/ffmpeg.wasm/issues" + }, + "engines": { + "node": ">=12.16.1" + }, + "homepage": "https://github.com/ffmpegwasm/ffmpeg.wasm#readme", + "dependencies": { + "is-url": "^1.2.4", + "node-fetch": "^2.6.1", + "regenerator-runtime": "^0.13.7", + "resolve-url": "^0.2.1" + }, + "devDependencies": { + "@babel/core": "^7.12.3", + "@babel/preset-env": "^7.12.1", + "@ffmpeg/core": "^0.11.0", + "@types/emscripten": "^1.39.4", + "babel-eslint": "^10.1.0", + "babel-loader": "^8.1.0", + "chai": "^4.2.0", + "cors": "^2.8.5", + "eslint": "^7.12.1", + "eslint-config-airbnb-base": "^14.1.0", + "eslint-plugin-import": "^2.22.1", + "express": "^4.17.1", + "mocha": "^8.2.1", + "mocha-headless-chrome": "^2.0.3", + "npm-run-all": "^4.1.5", + "wait-on": "^5.3.0", + "webpack": "^5.3.2", + "webpack-cli": "^4.1.0", + "webpack-dev-middleware": "^4.0.0" + } +} diff --git a/node_modules/@ffmpeg/ffmpeg/scripts/server.js b/node_modules/@ffmpeg/ffmpeg/scripts/server.js new file mode 100644 index 0000000..bf135a8 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/scripts/server.js @@ -0,0 +1,25 @@ +const webpack = require('webpack'); +const middleware = require('webpack-dev-middleware'); +const express = require('express'); +const path = require('path'); +const cors = require('cors'); +const webpackConfig = require('./webpack.config.dev'); + +const compiler = webpack(webpackConfig); +const app = express(); + +function coi(req, res, next) { + res.setHeader("Cross-Origin-Opener-Policy", "same-origin"); + res.setHeader("Cross-Origin-Embedder-Policy", "require-corp"); + next(); +} + +app.use(cors()); +app.use(coi); + +app.use('/', express.static(path.resolve(__dirname, '..'))); +app.use(middleware(compiler, { publicPath: '/dist', writeToDisk: true })); + +module.exports = app.listen(3000, () => { + console.log('Server is running on port 3000'); +}); diff --git a/node_modules/@ffmpeg/ffmpeg/scripts/test-helper.js b/node_modules/@ffmpeg/ffmpeg/scripts/test-helper.js new file mode 100644 index 0000000..c1d900a --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/scripts/test-helper.js @@ -0,0 +1,9 @@ +const chai = require('chai'); +const constants = require('../tests/constants'); + +global.expect = chai.expect; +global.FFmpeg = require('../src'); + +Object.keys(constants).forEach((key) => { + global[key] = constants[key]; +}); diff --git a/node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.common.js b/node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.common.js new file mode 100644 index 0000000..7d9133d --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.common.js @@ -0,0 +1,23 @@ +module.exports = { + module: { + rules: [ + { + test: /\.m?js$/, + exclude: /(node_modules|bower_components)/, + use: { + loader: 'babel-loader', + options: { + presets: [ + [ + '@babel/preset-env', + { + targets: 'last 2 versions', + }, + ], + ], + }, + }, + }, + ], + }, +}; diff --git a/node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.dev.js b/node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.dev.js new file mode 100644 index 0000000..2bfd2d0 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.dev.js @@ -0,0 +1,27 @@ +const path = require('path'); +const common = require('./webpack.config.common'); + +const genConfig = ({ + entry, filename, library, libraryTarget, +}) => ({ + ...common, + mode: 'development', + entry, + output: { + filename, + library, + libraryTarget, + }, + devServer: { + allowedHosts: ['localhost', '.gitpod.io'], + }, +}); + +module.exports = [ + genConfig({ + entry: path.resolve(__dirname, '..', 'src', 'index.js'), + filename: 'ffmpeg.dev.js', + library: 'FFmpeg', + libraryTarget: 'umd', + }), +]; diff --git a/node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.prod.js b/node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.prod.js new file mode 100644 index 0000000..8f1bac3 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.prod.js @@ -0,0 +1,26 @@ +const path = require('path'); +const common = require('./webpack.config.common'); + +const genConfig = ({ + entry, filename, library, libraryTarget, +}) => ({ + ...common, + mode: 'production', + devtool: 'source-map', + entry, + output: { + path: path.resolve(__dirname, '..', 'dist'), + filename, + library, + libraryTarget, + }, +}); + +module.exports = [ + genConfig({ + entry: path.resolve(__dirname, '..', 'src', 'index.js'), + filename: 'ffmpeg.min.js', + library: 'FFmpeg', + libraryTarget: 'umd', + }), +]; diff --git a/node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.worker.dev.js b/node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.worker.dev.js new file mode 100644 index 0000000..5683212 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.worker.dev.js @@ -0,0 +1,29 @@ +const path = require('path'); +const webpack = require('webpack'); +const common = require('./webpack.config.common'); + +const genConfig = ({ + entry, filename, library, libraryTarget, +}) => ({ + ...common, + mode: 'development', + target: 'webworker', + entry, + output: { + filename, + library, + libraryTarget, + }, + devServer: { + allowedHosts: ['localhost', '.gitpod.io'], + }, +}); + +module.exports = [ + genConfig({ + entry: path.resolve(__dirname, '..', 'src', 'index.js'), + filename: 'ffmpeg.dev.js', + library: 'FFmpeg', + libraryTarget: 'umd', + }), +]; diff --git a/node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.worker.prod.js b/node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.worker.prod.js new file mode 100644 index 0000000..ee51cd7 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/scripts/webpack.config.worker.prod.js @@ -0,0 +1,27 @@ +const path = require('path'); +const common = require('./webpack.config.common'); + +const genConfig = ({ + entry, filename, library, libraryTarget, +}) => ({ + ...common, + mode: 'production', + devtool: 'source-map', + target: 'webworker', + entry, + output: { + path: path.resolve(__dirname, '..', 'dist'), + filename, + library, + libraryTarget, + }, +}); + +module.exports = [ + genConfig({ + entry: path.resolve(__dirname, '..', 'src', 'index.js'), + filename: 'ffmpeg.min.js', + library: 'FFmpeg', + libraryTarget: 'umd', + }), +]; diff --git a/node_modules/@ffmpeg/ffmpeg/scripts/worker-server.js b/node_modules/@ffmpeg/ffmpeg/scripts/worker-server.js new file mode 100644 index 0000000..ffd9a34 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/scripts/worker-server.js @@ -0,0 +1,25 @@ +const webpack = require('webpack'); +const middleware = require('webpack-dev-middleware'); +const express = require('express'); +const path = require('path'); +const cors = require('cors'); +const webpackConfig = require('./webpack.config.worker.dev'); + +const compiler = webpack(webpackConfig); +const app = express(); + +function coi(req, res, next) { + res.setHeader("Cross-Origin-Opener-Policy", "same-origin"); + res.setHeader("Cross-Origin-Embedder-Policy", "require-corp"); + next(); +} + +app.use(cors()); +app.use(coi); + +app.use('/', express.static(path.resolve(__dirname, '..'))); +app.use(middleware(compiler, { publicPath: '/dist', writeToDisk: true })); + +module.exports = app.listen(3000, () => { + console.log('Server is running on port 3000'); +}); diff --git a/node_modules/@ffmpeg/ffmpeg/src/browser/defaultOptions.js b/node_modules/@ffmpeg/ffmpeg/src/browser/defaultOptions.js new file mode 100644 index 0000000..ac32af3 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/src/browser/defaultOptions.js @@ -0,0 +1,10 @@ +import pkg from '../../package.json'; + +/* + * Default options for browser environment + */ +const corePath = typeof process !== 'undefined' && process.env.NODE_ENV === 'development' + ? new URL('/node_modules/@ffmpeg/core/dist/ffmpeg-core.js', import.meta.url).href + : `https://unpkg.com/@ffmpeg/core@${pkg.devDependencies['@ffmpeg/core'].substring(1)}/dist/ffmpeg-core.js`; + +export default { corePath }; diff --git a/node_modules/@ffmpeg/ffmpeg/src/browser/fetchFile.js b/node_modules/@ffmpeg/ffmpeg/src/browser/fetchFile.js new file mode 100644 index 0000000..c241a02 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/src/browser/fetchFile.js @@ -0,0 +1,38 @@ +const readFromBlobOrFile = (blob) => ( + new Promise((resolve, reject) => { + const fileReader = new FileReader(); + fileReader.onload = () => { + resolve(fileReader.result); + }; + fileReader.onerror = ({ target: { error: { code } } }) => { + reject(Error(`File could not be read! Code=${code}`)); + }; + fileReader.readAsArrayBuffer(blob); + }) +); + +// eslint-disable-next-line +export const fetchFile = async (_data) => { + let data = _data; + if (typeof _data === 'undefined') { + return new Uint8Array(); + } + + if (typeof _data === 'string') { + /* From base64 format */ + if (/data:_data\/([a-zA-Z]*);base64,([^"]*)/.test(_data)) { + data = atob(_data.split(',')[1]) + .split('') + .map((c) => c.charCodeAt(0)); + /* From remote server/URL */ + } else { + const res = await fetch(new URL(_data, import.meta.url).href); + data = await res.arrayBuffer(); + } + /* From Blob or File */ + } else if (_data instanceof File || _data instanceof Blob) { + data = await readFromBlobOrFile(_data); + } + + return new Uint8Array(data); +}; diff --git a/node_modules/@ffmpeg/ffmpeg/src/browser/getCreateFFmpegCore.js b/node_modules/@ffmpeg/ffmpeg/src/browser/getCreateFFmpegCore.js new file mode 100644 index 0000000..ba77d33 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/src/browser/getCreateFFmpegCore.js @@ -0,0 +1,114 @@ +/* eslint-disable no-undef */ +import { log } from '../utils/log'; +import { + CREATE_FFMPEG_CORE_IS_NOT_DEFINED, +} from '../utils/errors'; + +/* + * Fetch data from remote URL and convert to blob URL + * to avoid CORS issue + */ +const toBlobURL = async (url, mimeType) => { + log('info', `fetch ${url}`); + const buf = await (await fetch(url)).arrayBuffer(); + log('info', `${url} file size = ${buf.byteLength} bytes`); + const blob = new Blob([buf], { type: mimeType }); + const blobURL = URL.createObjectURL(blob); + log('info', `${url} blob URL = ${blobURL}`); + return blobURL; +}; + +// eslint-disable-next-line +export const getCreateFFmpegCore = async ({ + corePath: _corePath, + workerPath: _workerPath, + wasmPath: _wasmPath, +}) => { + // in Web Worker context + // eslint-disable-next-line + if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) { + if (typeof _corePath !== 'string') { + throw Error('corePath should be a string!'); + } + const coreRemotePath = new URL(_corePath, import.meta.url).href; + const corePath = await toBlobURL( + coreRemotePath, + 'application/javascript', + ); + const wasmPath = await toBlobURL( + _wasmPath !== undefined ? _wasmPath : coreRemotePath.replace('ffmpeg-core.js', 'ffmpeg-core.wasm'), + 'application/wasm', + ); + const workerPath = await toBlobURL( + _workerPath !== undefined ? _workerPath : coreRemotePath.replace('ffmpeg-core.js', 'ffmpeg-core.worker.js'), + 'application/javascript', + ); + if (typeof createFFmpegCore === 'undefined') { + return new Promise((resolve) => { + globalThis.importScripts(corePath); + if (typeof createFFmpegCore === 'undefined') { + throw Error(CREATE_FFMPEG_CORE_IS_NOT_DEFINED(coreRemotePath)); + } + log('info', 'ffmpeg-core.js script loaded'); + resolve({ + createFFmpegCore, + corePath, + wasmPath, + workerPath, + }); + }); + } + log('info', 'ffmpeg-core.js script is loaded already'); + return Promise.resolve({ + createFFmpegCore, + corePath, + wasmPath, + workerPath, + }); + } + if (typeof _corePath !== 'string') { + throw Error('corePath should be a string!'); + } + const coreRemotePath = new URL(_corePath, import.meta.url).href; + const corePath = await toBlobURL( + coreRemotePath, + 'application/javascript', + ); + const wasmPath = await toBlobURL( + _wasmPath !== undefined ? _wasmPath : coreRemotePath.replace('ffmpeg-core.js', 'ffmpeg-core.wasm'), + 'application/wasm', + ); + const workerPath = await toBlobURL( + _workerPath !== undefined ? _workerPath : coreRemotePath.replace('ffmpeg-core.js', 'ffmpeg-core.worker.js'), + 'application/javascript', + ); + if (typeof createFFmpegCore === 'undefined') { + return new Promise((resolve) => { + const script = document.createElement('script'); + const eventHandler = () => { + script.removeEventListener('load', eventHandler); + if (typeof createFFmpegCore === 'undefined') { + throw Error(CREATE_FFMPEG_CORE_IS_NOT_DEFINED(coreRemotePath)); + } + log('info', 'ffmpeg-core.js script loaded'); + resolve({ + createFFmpegCore, + corePath, + wasmPath, + workerPath, + }); + }; + script.src = corePath; + script.type = 'text/javascript'; + script.addEventListener('load', eventHandler); + document.getElementsByTagName('head')[0].appendChild(script); + }); + } + log('info', 'ffmpeg-core.js script is loaded already'); + return Promise.resolve({ + createFFmpegCore, + corePath, + wasmPath, + workerPath, + }); +}; diff --git a/node_modules/@ffmpeg/ffmpeg/src/browser/index.js b/node_modules/@ffmpeg/ffmpeg/src/browser/index.js new file mode 100644 index 0000000..19b7ff3 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/src/browser/index.js @@ -0,0 +1,5 @@ +import defaultOptions from './defaultOptions'; +import { getCreateFFmpegCore } from './getCreateFFmpegCore'; +import { fetchFile } from './fetchFile'; + +export { defaultOptions, getCreateFFmpegCore, fetchFile }; diff --git a/node_modules/@ffmpeg/ffmpeg/src/config.js b/node_modules/@ffmpeg/ffmpeg/src/config.js new file mode 100644 index 0000000..9baf464 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/src/config.js @@ -0,0 +1,50 @@ +module.exports = { + defaultArgs: [ + /* args[0] is always the binary path */ + './ffmpeg', + /* Disable interaction mode */ + '-nostdin', + /* Force to override output file */ + '-y', + ], + baseOptions: { + /* Flag to turn on/off log messages in console */ + log: false, + /* + * Custom logger to get ffmpeg.wasm output messages. + * a sample logger looks like this: + * + * ``` + * logger = ({ type, message }) => { + * console.log(type, message); + * } + * ``` + * + * type can be one of following: + * + * info: internal workflow debug messages + * fferr: ffmpeg native stderr output + * ffout: ffmpeg native stdout output + */ + logger: () => {}, + /* + * Progress handler to get current progress of ffmpeg command. + * a sample progress handler looks like this: + * + * ``` + * progress = ({ ratio }) => { + * console.log(ratio); + * } + * ``` + * + * ratio is a float number between 0 to 1. + */ + progress: () => {}, + /* + * Path to find/download ffmpeg.wasm-core, + * this value should be overwriten by `defaultOptions` in + * each environment. + */ + corePath: '', + }, +}; diff --git a/node_modules/@ffmpeg/ffmpeg/src/createFFmpeg.js b/node_modules/@ffmpeg/ffmpeg/src/createFFmpeg.js new file mode 100644 index 0000000..032f527 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/src/createFFmpeg.js @@ -0,0 +1,279 @@ +const { defaultArgs, baseOptions } = require('./config'); +const parseArgs = require('./utils/parseArgs'); +const { defaultOptions, getCreateFFmpegCore } = require('./node'); +const { version } = require('../package.json'); + +const NO_LOAD = Error('ffmpeg.wasm is not ready, make sure you have completed load().'); + +module.exports = (_options = {}) => { + const { + log: optLog, + logger, + progress: optProgress, + ...options + } = { + ...baseOptions, + ...defaultOptions, + ..._options, + }; + let Core = null; + let ffmpeg = null; + let runResolve = null; + let runReject = null; + let running = false; + let customLogger = () => {}; + let logging = optLog; + let progress = optProgress; + let duration = 0; + let frames = 0; + let readFrames = false; + let ratio = 0; + + const detectCompletion = (message) => { + if (message === 'FFMPEG_END' && runResolve !== null) { + runResolve(); + runResolve = null; + runReject = null; + running = false; + } + }; + const log = (type, message) => { + customLogger({ type, message }); + if (logging) { + console.log(`[${type}] ${message}`); + } + }; + const ts2sec = (ts) => { + const [h, m, s] = ts.split(':'); + return (parseFloat(h) * 60 * 60) + (parseFloat(m) * 60) + parseFloat(s); + }; + const parseProgress = (message, prog) => { + if (typeof message === 'string') { + if (message.startsWith(' Duration')) { + const ts = message.split(', ')[0].split(': ')[1]; + const d = ts2sec(ts); + prog({ duration: d, ratio }); + if (duration === 0 || duration > d) { + duration = d; + readFrames = true; + } + } else if (readFrames && message.startsWith(' Stream')) { + const match = message.match(/([\d.]+) fps/); + if (match) { + const fps = parseFloat(match[1]); + frames = duration * fps; + } else { + frames = 0; + } + readFrames = false; + } else if (message.startsWith('frame') || message.startsWith('size')) { + const ts = message.split('time=')[1].split(' ')[0]; + const t = ts2sec(ts); + const match = message.match(/frame=\s*(\d+)/); + if (frames && match) { + const f = parseFloat(match[1]); + ratio = Math.min(f / frames, 1); + } else { + ratio = t / duration; + } + prog({ ratio, time: t }); + } else if (message.startsWith('video:')) { + prog({ ratio: 1 }); + duration = 0; + } + } + }; + const parseMessage = ({ type, message }) => { + log(type, message); + parseProgress(message, progress); + detectCompletion(message); + }; + + /* + * Load ffmpeg.wasm-core script. + * In browser environment, the ffmpeg.wasm-core script is fetch from + * CDN and can be assign to a local path by assigning `corePath`. + * In node environment, we use dynamic require and the default `corePath` + * is `$ffmpeg/core`. + * + * Typically the load() func might take few seconds to minutes to complete, + * better to do it as early as possible. + * + */ + const load = async () => { + log('info', 'load ffmpeg-core'); + if (Core === null) { + log('info', 'loading ffmpeg-core'); + /* + * In node environment, all paths are undefined as there + * is no need to set them. + */ + const { + createFFmpegCore, + corePath, + workerPath, + wasmPath, + } = await getCreateFFmpegCore(options); + Core = await createFFmpegCore({ + /* + * Assign mainScriptUrlOrBlob fixes chrome extension web worker issue + * as there is no document.currentScript in the context of content_scripts + */ + mainScriptUrlOrBlob: corePath, + printErr: (message) => parseMessage({ type: 'fferr', message }), + print: (message) => parseMessage({ type: 'ffout', message }), + /* + * locateFile overrides paths of files that is loaded by main script (ffmpeg-core.js). + * It is critical for browser environment and we override both wasm and worker paths + * as we are using blob URL instead of original URL to avoid cross origin issues. + */ + locateFile: (path, prefix) => { + if (typeof window !== 'undefined' || typeof WorkerGlobalScope !== 'undefined') { + if (typeof wasmPath !== 'undefined' + && path.endsWith('ffmpeg-core.wasm')) { + return wasmPath; + } + if (typeof workerPath !== 'undefined' + && path.endsWith('ffmpeg-core.worker.js')) { + return workerPath; + } + } + return prefix + path; + }, + }); + ffmpeg = Core.cwrap(options.mainName || 'proxy_main', 'number', ['number', 'number']); + log('info', 'ffmpeg-core loaded'); + } else { + throw Error('ffmpeg.wasm was loaded, you should not load it again, use ffmpeg.isLoaded() to check next time.'); + } + }; + + /* + * Determine whether the Core is loaded. + */ + const isLoaded = () => Core !== null; + + /* + * Run ffmpeg command. + * This is the major function in ffmpeg.wasm, you can just imagine it + * as ffmpeg native cli and what you need to pass is the same. + * + * For example, you can convert native command below: + * + * ``` + * $ ffmpeg -i video.avi -c:v libx264 video.mp4 + * ``` + * + * To + * + * ``` + * await ffmpeg.run('-i', 'video.avi', '-c:v', 'libx264', 'video.mp4'); + * ``` + * + */ + const run = (..._args) => { + log('info', `run ffmpeg command: ${_args.join(' ')}`); + if (Core === null) { + throw NO_LOAD; + } else if (running) { + throw Error('ffmpeg.wasm can only run one command at a time'); + } else { + running = true; + return new Promise((resolve, reject) => { + const args = [...defaultArgs, ..._args].filter((s) => s.length !== 0); + runResolve = resolve; + runReject = reject; + ffmpeg(...parseArgs(Core, args)); + }); + } + }; + + /* + * Run FS operations. + * For input/output file of ffmpeg.wasm, it is required to save them to MEMFS + * first so that ffmpeg.wasm is able to consume them. Here we rely on the FS + * methods provided by Emscripten. + * + * Common methods to use are: + * ffmpeg.FS('writeFile', 'video.avi', new Uint8Array(...)): writeFile writes + * data to MEMFS. You need to use Uint8Array for binary data. + * ffmpeg.FS('readFile', 'video.mp4'): readFile from MEMFS. + * ffmpeg.FS('unlink', 'video.map'): delete file from MEMFS. + * + * For more info, check https://emscripten.org/docs/api_reference/Filesystem-API.html + * + */ + const FS = (method, ...args) => { + log('info', `run FS.${method} ${args.map((arg) => (typeof arg === 'string' ? arg : `<${arg.length} bytes binary file>`)).join(' ')}`); + if (Core === null) { + throw NO_LOAD; + } else { + let ret = null; + try { + ret = Core.FS[method](...args); + } catch (e) { + if (method === 'readdir') { + throw Error(`ffmpeg.FS('readdir', '${args[0]}') error. Check if the path exists, ex: ffmpeg.FS('readdir', '/')`); + } else if (method === 'readFile') { + throw Error(`ffmpeg.FS('readFile', '${args[0]}') error. Check if the path exists`); + } else { + throw Error('Oops, something went wrong in FS operation.'); + } + } + return ret; + } + }; + + /** + * forcibly terminate the ffmpeg program. + */ + const exit = () => { + if (Core === null) { + throw NO_LOAD; + } else { + // if there's any pending runs, reject them + if (runReject) { + runReject('ffmpeg has exited'); + } + running = false; + try { + Core.exit(1); + } catch (err) { + log(err.message); + if (runReject) { + runReject(err); + } + } finally { + Core = null; + ffmpeg = null; + runResolve = null; + runReject = null; + } + } + }; + + const setProgress = (_progress) => { + progress = _progress; + }; + + const setLogger = (_logger) => { + customLogger = _logger; + }; + + const setLogging = (_logging) => { + logging = _logging; + }; + + log('info', `use ffmpeg.wasm v${version}`); + + return { + setProgress, + setLogger, + setLogging, + load, + isLoaded, + run, + exit, + FS, + }; +}; diff --git a/node_modules/@ffmpeg/ffmpeg/src/index.d.ts b/node_modules/@ffmpeg/ffmpeg/src/index.d.ts new file mode 100644 index 0000000..338c35e --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/src/index.d.ts @@ -0,0 +1,120 @@ +export const FS: { + writeFile: (fileName: string, binaryData: Uint8Array | string) => void, + readFile: (fileName: string) => Uint8Array, + readdir: (pathName: string) => string[], + unlink: (fileName: string) => void, + mkdir: (fileName: string) => void, +} + +type FSMethodNames = { [K in keyof typeof FS]: (typeof FS)[K] extends (...args: any[]) => any ? K : never }[keyof typeof FS]; +type FSMethodArgs = { [K in FSMethodNames]: Parameters<(typeof FS)[K]> }; +type FSMethodReturn = { [K in FSMethodNames]: ReturnType<(typeof FS)[K]> }; + +type LogCallback = (logParams: { type: string; message: string }) => any; +type ProgressCallback = (progressParams: { ratio: number }) => any; + +export interface CreateFFmpegOptions { + /** path for ffmpeg-core.js script */ + corePath?: string; + /** path for ffmpeg-worker.js script */ + workerPath?: string; + /** path for ffmpeg-core.wasm script */ + wasmPath?: string; + /** a boolean to turn on all logs, default is false */ + log?: boolean; + /** a function to get log messages, a quick example is ({ message }) => console.log(message) */ + logger?: LogCallback; + /** a function to trace the progress, a quick example is p => console.log(p) */ + progress?: ProgressCallback; + /** name of the main function of the ffmpeg-core.js script */ + mainName?: string; +} + +export interface FFmpeg { + /* + * Load ffmpeg.wasm-core script. + * In browser environment, the ffmpeg.wasm-core script is fetch from + * CDN and can be assign to a local path by assigning `corePath`. + * In node environment, we use dynamic require and the default `corePath` + * is `$ffmpeg/core`. + * + * Typically the load() func might take few seconds to minutes to complete, + * better to do it as early as possible. + * + */ + load(): Promise; + /* + * Determine whether the Core is loaded. + */ + isLoaded(): boolean; + /* + * Run ffmpeg command. + * This is the major function in ffmpeg.wasm, you can just imagine it + * as ffmpeg native cli and what you need to pass is the same. + * + * For example, you can convert native command below: + * + * ``` + * $ ffmpeg -i video.avi -c:v libx264 video.mp4 + * ``` + * + * To + * + * ``` + * await ffmpeg.run('-i', 'video.avi', '-c:v', 'libx264', 'video.mp4'); + * ``` + * + */ + run(...args: string[]): Promise; + /* + * Run FS operations. + * For input/output file of ffmpeg.wasm, it is required to save them to MEMFS + * first so that ffmpeg.wasm is able to consume them. Here we rely on the FS + * methods provided by Emscripten. + * + * Common methods to use are: + * ffmpeg.FS('writeFile', 'video.avi', new Uint8Array(...)): writeFile writes + * data to MEMFS. You need to use Uint8Array for binary data. + * ffmpeg.FS('readFile', 'video.mp4'): readFile from MEMFS. + * ffmpeg.FS('unlink', 'video.map'): delete file from MEMFS. + * + * For more info, check https://emscripten.org/docs/api_reference/Filesystem-API.html + * + */ + FS(method: Method, ...args: FSMethodArgs[Method]): FSMethodReturn[Method]; + setProgress(progress: ProgressCallback): void; + setLogger(log: LogCallback): void; + setLogging(logging: boolean): void; + exit(): void; +} + +/* + * Create ffmpeg instance. + * Each ffmpeg instance owns an isolated MEMFS and works + * independently. + * + * For example: + * + * ``` + * const ffmpeg = createFFmpeg({ + * log: true, + * logger: () => {}, + * progress: () => {}, + * corePath: '', + * }) + * ``` + * + * For the usage of these four arguments, check config.js + * + */ +export function createFFmpeg(options?: CreateFFmpegOptions): FFmpeg; +/* + * Helper function for fetching files from various resource. + * Sometimes the video/audio file you want to process may located + * in a remote URL and somewhere in your local file system. + * + * This helper function helps you to fetch to file and return an + * Uint8Array variable for ffmpeg.wasm to consume. + * + */ +export function fetchFile(data: string | Buffer | Blob | File): Promise; diff --git a/node_modules/@ffmpeg/ffmpeg/src/index.js b/node_modules/@ffmpeg/ffmpeg/src/index.js new file mode 100644 index 0000000..8c69a5b --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/src/index.js @@ -0,0 +1,36 @@ +require('regenerator-runtime/runtime'); +const createFFmpeg = require('./createFFmpeg'); +const { fetchFile } = require('./node'); + +module.exports = { + /* + * Create ffmpeg instance. + * Each ffmpeg instance owns an isolated MEMFS and works + * independently. + * + * For example: + * + * ``` + * const ffmpeg = createFFmpeg({ + * log: true, + * logger: () => {}, + * progress: () => {}, + * corePath: '', + * }) + * ``` + * + * For the usage of these four arguments, check config.js + * + */ + createFFmpeg, + /* + * Helper function for fetching files from various resource. + * Sometimes the video/audio file you want to process may located + * in a remote URL and somewhere in your local file system. + * + * This helper function helps you to fetch to file and return an + * Uint8Array variable for ffmpeg.wasm to consume. + * + */ + fetchFile, +}; diff --git a/node_modules/@ffmpeg/ffmpeg/src/node/defaultOptions.js b/node_modules/@ffmpeg/ffmpeg/src/node/defaultOptions.js new file mode 100644 index 0000000..5b22e73 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/src/node/defaultOptions.js @@ -0,0 +1,6 @@ +/* + * Default options for node environment + */ +module.exports = { + corePath: '@ffmpeg/core', +}; diff --git a/node_modules/@ffmpeg/ffmpeg/src/node/fetchFile.js b/node_modules/@ffmpeg/ffmpeg/src/node/fetchFile.js new file mode 100644 index 0000000..9c181bf --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/src/node/fetchFile.js @@ -0,0 +1,33 @@ +const util = require('util'); +const fs = require('fs'); +const fetch = require('node-fetch'); +const isURL = require('is-url'); + +module.exports = async (_data) => { + let data = _data; + if (typeof _data === 'undefined') { + return new Uint8Array(); + } + + if (typeof _data === 'string') { + /* From remote URL/server */ + if (isURL(_data) + || _data.startsWith('moz-extension://') + || _data.startsWith('chrome-extension://') + || _data.startsWith('file://')) { + const res = await fetch(_data); + data = await res.arrayBuffer(); + /* From base64 format */ + } else if (/data:_data\/([a-zA-Z]*);base64,([^"]*)/.test(_data)) { + data = Buffer.from(_data.split(',')[1], 'base64'); + /* From local file path */ + } else { + data = await util.promisify(fs.readFile)(_data); + } + /* From Buffer */ + } else if (Buffer.isBuffer(_data)) { + data = _data; + } + + return new Uint8Array(data); +}; diff --git a/node_modules/@ffmpeg/ffmpeg/src/node/getCreateFFmpegCore.js b/node_modules/@ffmpeg/ffmpeg/src/node/getCreateFFmpegCore.js new file mode 100644 index 0000000..29314c9 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/src/node/getCreateFFmpegCore.js @@ -0,0 +1,7 @@ +const { log } = require('../utils/log'); + +module.exports = ({ corePath }) => new Promise((resolve) => { + log('info', `fetch ffmpeg.wasm-core script from ${corePath}`); + // eslint-disable-next-line import/no-dynamic-require + resolve({ createFFmpegCore: require(corePath) }); +}); diff --git a/node_modules/@ffmpeg/ffmpeg/src/node/index.js b/node_modules/@ffmpeg/ffmpeg/src/node/index.js new file mode 100644 index 0000000..e73bfaa --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/src/node/index.js @@ -0,0 +1,9 @@ +const defaultOptions = require('./defaultOptions'); +const getCreateFFmpegCore = require('./getCreateFFmpegCore'); +const fetchFile = require('./fetchFile'); + +module.exports = { + defaultOptions, + getCreateFFmpegCore, + fetchFile, +}; diff --git a/node_modules/@ffmpeg/ffmpeg/src/utils/errors.js b/node_modules/@ffmpeg/ffmpeg/src/utils/errors.js new file mode 100644 index 0000000..58a0c77 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/src/utils/errors.js @@ -0,0 +1,11 @@ +const CREATE_FFMPEG_CORE_IS_NOT_DEFINED = (corePath) => (` +createFFmpegCore is not defined. ffmpeg.wasm is unable to find createFFmpegCore after loading ffmpeg-core.js from ${corePath}. Use another URL when calling createFFmpeg(): + +const ffmpeg = createFFmpeg({ + corePath: 'http://localhost:3000/ffmpeg-core.js', +}); +`); + +module.exports = { + CREATE_FFMPEG_CORE_IS_NOT_DEFINED, +}; diff --git a/node_modules/@ffmpeg/ffmpeg/src/utils/log.js b/node_modules/@ffmpeg/ffmpeg/src/utils/log.js new file mode 100644 index 0000000..bb2f0fb --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/src/utils/log.js @@ -0,0 +1,24 @@ +let logging = false; +let customLogger = () => {}; + +const setLogging = (_logging) => { + logging = _logging; +}; + +const setCustomLogger = (logger) => { + customLogger = logger; +}; + +const log = (type, message) => { + customLogger({ type, message }); + if (logging) { + console.log(`[${type}] ${message}`); + } +}; + +module.exports = { + logging, + setLogging, + setCustomLogger, + log, +}; diff --git a/node_modules/@ffmpeg/ffmpeg/src/utils/parseArgs.js b/node_modules/@ffmpeg/ffmpeg/src/utils/parseArgs.js new file mode 100644 index 0000000..90c18c5 --- /dev/null +++ b/node_modules/@ffmpeg/ffmpeg/src/utils/parseArgs.js @@ -0,0 +1,10 @@ +module.exports = (Core, args) => { + const argsPtr = Core._malloc(args.length * Uint32Array.BYTES_PER_ELEMENT); + args.forEach((s, idx) => { + const sz = Core.lengthBytesUTF8(s) + 1; + const buf = Core._malloc(sz); + Core.stringToUTF8(s, buf, sz); + Core.setValue(argsPtr + (Uint32Array.BYTES_PER_ELEMENT * idx), buf, 'i32'); + }); + return [args.length, argsPtr]; +}; diff --git a/node_modules/is-url/.travis.yml b/node_modules/is-url/.travis.yml new file mode 100644 index 0000000..1a8f06b --- /dev/null +++ b/node_modules/is-url/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - 8 \ No newline at end of file diff --git a/node_modules/is-url/History.md b/node_modules/is-url/History.md new file mode 100644 index 0000000..8b24e02 --- /dev/null +++ b/node_modules/is-url/History.md @@ -0,0 +1,25 @@ + +1.2.0 - November 25, 2014 +------------------------- +* add support for protocol relative urls + +1.1.0 - February 8, 2013 +------------------------ +* support any protocol +* support paths on localhost + +1.0.0 - January 17, 2013 +------------------------ +* allow localhost to have a port + +0.1.0 - September 8, 2013 +------------------------- +* make regexp match more valid url types + +0.0.2 - August 2, 2013 +---------------------- +* remove loose matching + +0.0.1 - August 2, 2013 +---------------------- +:sparkles: \ No newline at end of file diff --git a/node_modules/is-url/LICENSE-MIT b/node_modules/is-url/LICENSE-MIT new file mode 100644 index 0000000..fe5bb30 --- /dev/null +++ b/node_modules/is-url/LICENSE-MIT @@ -0,0 +1,19 @@ +MIT LICENSE + +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/is-url/Readme.md b/node_modules/is-url/Readme.md new file mode 100644 index 0000000..20ed181 --- /dev/null +++ b/node_modules/is-url/Readme.md @@ -0,0 +1,19 @@ +# is-url + +Check whether a string is a URL. + +## Installation + +```sh +npm install is-url +``` + +## API + +### `isUrl(string)` + +Returns a Boolean indicating whether `string` is a URL. + +## License + +MIT diff --git a/node_modules/is-url/index.js b/node_modules/is-url/index.js new file mode 100644 index 0000000..3ea3d20 --- /dev/null +++ b/node_modules/is-url/index.js @@ -0,0 +1,47 @@ + +/** + * Expose `isUrl`. + */ + +module.exports = isUrl; + +/** + * RegExps. + * A URL must match #1 and then at least one of #2/#3. + * Use two levels of REs to avoid REDOS. + */ + +var protocolAndDomainRE = /^(?:\w+:)?\/\/(\S+)$/; + +var localhostDomainRE = /^localhost[\:?\d]*(?:[^\:?\d]\S*)?$/ +var nonLocalhostDomainRE = /^[^\s\.]+\.\S{2,}$/; + +/** + * Loosely validate a URL `string`. + * + * @param {String} string + * @return {Boolean} + */ + +function isUrl(string){ + if (typeof string !== 'string') { + return false; + } + + var match = string.match(protocolAndDomainRE); + if (!match) { + return false; + } + + var everythingAfterProtocol = match[1]; + if (!everythingAfterProtocol) { + return false; + } + + if (localhostDomainRE.test(everythingAfterProtocol) || + nonLocalhostDomainRE.test(everythingAfterProtocol)) { + return true; + } + + return false; +} diff --git a/node_modules/is-url/package.json b/node_modules/is-url/package.json new file mode 100644 index 0000000..34b3ac1 --- /dev/null +++ b/node_modules/is-url/package.json @@ -0,0 +1,13 @@ +{ + "name": "is-url", + "description": "Check whether a string is a URL.", + "repository": "https://github.com/segmentio/is-url", + "version": "1.2.4", + "scripts": { + "test": "mocha --reporter spec" + }, + "license": "MIT", + "devDependencies": { + "mocha": "*" + } +} diff --git a/node_modules/is-url/test/index.js b/node_modules/is-url/test/index.js new file mode 100644 index 0000000..404e1b6 --- /dev/null +++ b/node_modules/is-url/test/index.js @@ -0,0 +1,149 @@ + +try { + var url = require('is-url'); +} catch (e) { + var url = require('..'); +} + +var assert = require('assert'); + +describe('is-url', function () { + describe('valid', function () { + it('http://google.com', function () { + assert(url('http://google.com')); + }); + + it('https://google.com', function () { + assert(url('https://google.com')); + }); + + it('ftp://google.com', function () { + assert(url('ftp://google.com')); + }); + + it('http://www.google.com', function () { + assert(url('http://www.google.com')); + }); + + it('http://google.com/something', function () { + assert(url('http://google.com/something')); + }); + + it('http://google.com?q=query', function () { + assert(url('http://google.com?q=query')); + }); + + it('http://google.com#hash', function () { + assert(url('http://google.com#hash')); + }); + + it('http://google.com/something?q=query#hash', function () { + assert(url('http://google.com/something?q=query#hash')); + }); + + it('http://google.co.uk', function () { + assert(url('http://google.co.uk')); + }); + + it('http://www.google.co.uk', function () { + assert(url('http://www.google.co.uk')); + }); + + it('http://google.cat', function () { + assert(url('http://google.cat')); + }); + + it('https://d1f4470da51b49289906b3d6cbd65074@app.getsentry.com/13176', function () { + assert(url('https://d1f4470da51b49289906b3d6cbd65074@app.getsentry.com/13176')); + }); + + it('http://0.0.0.0', function () { + assert(url('http://0.0.0.0')); + }); + + it('http://localhost', function () { + assert(url('http://localhost')); + }); + + it('postgres://u:p@example.com:5702/db', function () { + assert(url('postgres://u:p@example.com:5702/db')); + }); + + it('redis://:123@174.129.42.52:13271', function () { + assert(url('redis://:123@174.129.42.52:13271')); + }); + + it('mongodb://u:p@example.com:10064/db', function () { + assert(url('mongodb://u:p@example.com:10064/db')); + }); + + it('ws://chat.example.com/games', function () { + assert(url('ws://chat.example.com/games')); + }); + + it('wss://secure.example.com/biz', function () { + assert(url('wss://secure.example.com/biz')); + }); + + it('http://localhost:4000', function () { + assert(url('http://localhost:4000')); + }); + + it('http://localhost:342/a/path', function () { + assert(url('http://localhost:342/a/path')); + }); + + it('//google.com', function () { + assert(url('//google.com')); + }); + }); + + describe('invalid', function () { + it('http://', function () { + assert(!url('http://')); + }); + + it('http://google', function () { + assert(!url('http://google')); + }); + + it('http://google.', function () { + assert(!url('http://google.')); + }); + + it('google', function () { + assert(!url('google')); + }); + + it('google.com', function () { + assert(!url('google.com')); + }); + + it('empty', function () { + assert(!url('')); + }); + + it('undef', function () { + assert(!url(undefined)); + }); + + it('object', function () { + assert(!url({})); + }); + + it('re', function () { + assert(!url(/abc/)); + }); + }); + + describe('redos', function () { + it('redos exploit', function () { + // Invalid. This should be discovered in under 1 second. + var attackString = 'a://localhost' + '9'.repeat(100000) + '\t'; + var before = process.hrtime(); + assert(!url(attackString), 'attackString was valid'); + var elapsed = process.hrtime(before); + assert(elapsed[0] < 1, 'attackString took ' + elapsed[0] + ' > 1 seconds'); + }); + }); +}); diff --git a/node_modules/js-tokens/CHANGELOG.md b/node_modules/js-tokens/CHANGELOG.md new file mode 100644 index 0000000..755e6f6 --- /dev/null +++ b/node_modules/js-tokens/CHANGELOG.md @@ -0,0 +1,151 @@ +### Version 4.0.0 (2018-01-28) ### + +- Added: Support for ES2018. The only change needed was recognizing the `s` + regex flag. +- Changed: _All_ tokens returned by the `matchToToken` function now have a + `closed` property. It is set to `undefined` for the tokens where “closed” + doesn’t make sense. This means that all tokens objects have the same shape, + which might improve performance. + +These are the breaking changes: + +- `'/a/s'.match(jsTokens)` no longer returns `['/', 'a', '/', 's']`, but + `['/a/s']`. (There are of course other variations of this.) +- Code that rely on some token objects not having the `closed` property could + now behave differently. + + +### Version 3.0.2 (2017-06-28) ### + +- No code changes. Just updates to the readme. + + +### Version 3.0.1 (2017-01-30) ### + +- Fixed: ES2015 unicode escapes with more than 6 hex digits are now matched + correctly. + + +### Version 3.0.0 (2017-01-11) ### + +This release contains one breaking change, that should [improve performance in +V8][v8-perf]: + +> So how can you, as a JavaScript developer, ensure that your RegExps are fast? +> If you are not interested in hooking into RegExp internals, make sure that +> neither the RegExp instance, nor its prototype is modified in order to get the +> best performance: +> +> ```js +> var re = /./g; +> re.exec(''); // Fast path. +> re.new_property = 'slow'; +> ``` + +This module used to export a single regex, with `.matchToToken` bolted +on, just like in the above example. This release changes the exports of +the module to avoid this issue. + +Before: + +```js +import jsTokens from "js-tokens" +// or: +var jsTokens = require("js-tokens") +var matchToToken = jsTokens.matchToToken +``` + +After: + +```js +import jsTokens, {matchToToken} from "js-tokens" +// or: +var jsTokens = require("js-tokens").default +var matchToToken = require("js-tokens").matchToToken +``` + +[v8-perf]: http://v8project.blogspot.se/2017/01/speeding-up-v8-regular-expressions.html + + +### Version 2.0.0 (2016-06-19) ### + +- Added: Support for ES2016. In other words, support for the `**` exponentiation + operator. + +These are the breaking changes: + +- `'**'.match(jsTokens)` no longer returns `['*', '*']`, but `['**']`. +- `'**='.match(jsTokens)` no longer returns `['*', '*=']`, but `['**=']`. + + +### Version 1.0.3 (2016-03-27) ### + +- Improved: Made the regex ever so slightly smaller. +- Updated: The readme. + + +### Version 1.0.2 (2015-10-18) ### + +- Improved: Limited npm package contents for a smaller download. Thanks to + @zertosh! + + +### Version 1.0.1 (2015-06-20) ### + +- Fixed: Declared an undeclared variable. + + +### Version 1.0.0 (2015-02-26) ### + +- Changed: Merged the 'operator' and 'punctuation' types into 'punctuator'. That + type is now equivalent to the Punctuator token in the ECMAScript + specification. (Backwards-incompatible change.) +- Fixed: A `-` followed by a number is now correctly matched as a punctuator + followed by a number. It used to be matched as just a number, but there is no + such thing as negative number literals. (Possibly backwards-incompatible + change.) + + +### Version 0.4.1 (2015-02-21) ### + +- Added: Support for the regex `u` flag. + + +### Version 0.4.0 (2015-02-21) ### + +- Improved: `jsTokens.matchToToken` performance. +- Added: Support for octal and binary number literals. +- Added: Support for template strings. + + +### Version 0.3.1 (2015-01-06) ### + +- Fixed: Support for unicode spaces. They used to be allowed in names (which is + very confusing), and some unicode newlines were wrongly allowed in strings and + regexes. + + +### Version 0.3.0 (2014-12-19) ### + +- Changed: The `jsTokens.names` array has been replaced with the + `jsTokens.matchToToken` function. The capturing groups of `jsTokens` are no + longer part of the public API; instead use said function. See this [gist] for + an example. (Backwards-incompatible change.) +- Changed: The empty string is now considered an “invalid” token, instead an + “empty” token (its own group). (Backwards-incompatible change.) +- Removed: component support. (Backwards-incompatible change.) + +[gist]: https://gist.github.com/lydell/be49dbf80c382c473004 + + +### Version 0.2.0 (2014-06-19) ### + +- Changed: Match ES6 function arrows (`=>`) as an operator, instead of its own + category (“functionArrow”), for simplicity. (Backwards-incompatible change.) +- Added: ES6 splats (`...`) are now matched as an operator (instead of three + punctuations). (Backwards-incompatible change.) + + +### Version 0.1.0 (2014-03-08) ### + +- Initial release. diff --git a/node_modules/js-tokens/LICENSE b/node_modules/js-tokens/LICENSE new file mode 100644 index 0000000..54aef52 --- /dev/null +++ b/node_modules/js-tokens/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014, 2015, 2016, 2017, 2018 Simon Lydell + +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/js-tokens/README.md b/node_modules/js-tokens/README.md new file mode 100644 index 0000000..00cdf16 --- /dev/null +++ b/node_modules/js-tokens/README.md @@ -0,0 +1,240 @@ +Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens) +======== + +A regex that tokenizes JavaScript. + +```js +var jsTokens = require("js-tokens").default + +var jsString = "var foo=opts.foo;\n..." + +jsString.match(jsTokens) +// ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...] +``` + + +Installation +============ + +`npm install js-tokens` + +```js +import jsTokens from "js-tokens" +// or: +var jsTokens = require("js-tokens").default +``` + + +Usage +===== + +### `jsTokens` ### + +A regex with the `g` flag that matches JavaScript tokens. + +The regex _always_ matches, even invalid JavaScript and the empty string. + +The next match is always directly after the previous. + +### `var token = matchToToken(match)` ### + +```js +import {matchToToken} from "js-tokens" +// or: +var matchToToken = require("js-tokens").matchToToken +``` + +Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type: +String, value: String}` object. The following types are available: + +- string +- comment +- regex +- number +- name +- punctuator +- whitespace +- invalid + +Multi-line comments and strings also have a `closed` property indicating if the +token was closed or not (see below). + +Comments and strings both come in several flavors. To distinguish them, check if +the token starts with `//`, `/*`, `'`, `"` or `` ` ``. + +Names are ECMAScript IdentifierNames, that is, including both identifiers and +keywords. You may use [is-keyword-js] to tell them apart. + +Whitespace includes both line terminators and other whitespace. + +[is-keyword-js]: https://github.com/crissdev/is-keyword-js + + +ECMAScript support +================== + +The intention is to always support the latest ECMAScript version whose feature +set has been finalized. + +If adding support for a newer version requires changes, a new version with a +major verion bump will be released. + +Currently, ECMAScript 2018 is supported. + + +Invalid code handling +===================== + +Unterminated strings are still matched as strings. JavaScript strings cannot +contain (unescaped) newlines, so unterminated strings simply end at the end of +the line. Unterminated template strings can contain unescaped newlines, though, +so they go on to the end of input. + +Unterminated multi-line comments are also still matched as comments. They +simply go on to the end of the input. + +Unterminated regex literals are likely matched as division and whatever is +inside the regex. + +Invalid ASCII characters have their own capturing group. + +Invalid non-ASCII characters are treated as names, to simplify the matching of +names (except unicode spaces which are treated as whitespace). Note: See also +the [ES2018](#es2018) section. + +Regex literals may contain invalid regex syntax. They are still matched as +regex literals. They may also contain repeated regex flags, to keep the regex +simple. + +Strings may contain invalid escape sequences. + + +Limitations +=========== + +Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be +perfect. But that’s not the point either. + +You may compare jsTokens with [esprima] by using `esprima-compare.js`. +See `npm run esprima-compare`! + +[esprima]: http://esprima.org/ + +### Template string interpolation ### + +Template strings are matched as single tokens, from the starting `` ` `` to the +ending `` ` ``, including interpolations (whose tokens are not matched +individually). + +Matching template string interpolations requires recursive balancing of `{` and +`}`—something that JavaScript regexes cannot do. Only one level of nesting is +supported. + +### Division and regex literals collision ### + +Consider this example: + +```js +var g = 9.82 +var number = bar / 2/g + +var regex = / 2/g +``` + +A human can easily understand that in the `number` line we’re dealing with +division, and in the `regex` line we’re dealing with a regex literal. How come? +Because humans can look at the whole code to put the `/` characters in context. +A JavaScript regex cannot. It only sees forwards. (Well, ES2018 regexes can also +look backwards. See the [ES2018](#es2018) section). + +When the `jsTokens` regex scans throught the above, it will see the following +at the end of both the `number` and `regex` rows: + +```js +/ 2/g +``` + +It is then impossible to know if that is a regex literal, or part of an +expression dealing with division. + +Here is a similar case: + +```js +foo /= 2/g +foo(/= 2/g) +``` + +The first line divides the `foo` variable with `2/g`. The second line calls the +`foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only +sees forwards, it cannot tell the two cases apart. + +There are some cases where we _can_ tell division and regex literals apart, +though. + +First off, we have the simple cases where there’s only one slash in the line: + +```js +var foo = 2/g +foo /= 2 +``` + +Regex literals cannot contain newlines, so the above cases are correctly +identified as division. Things are only problematic when there are more than +one non-comment slash in a single line. + +Secondly, not every character is a valid regex flag. + +```js +var number = bar / 2/e +``` + +The above example is also correctly identified as division, because `e` is not a +valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*` +(any letter) as flags, but it is not worth it since it increases the amount of +ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are +allowed. This means that the above example will be identified as division as +long as you don’t rename the `e` variable to some permutation of `gmiyus` 1 to 6 +characters long. + +Lastly, we can look _forward_ for information. + +- If the token following what looks like a regex literal is not valid after a + regex literal, but is valid in a division expression, then the regex literal + is treated as division instead. For example, a flagless regex cannot be + followed by a string, number or name, but all of those three can be the + denominator of a division. +- Generally, if what looks like a regex literal is followed by an operator, the + regex literal is treated as division instead. This is because regexes are + seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division + could likely be part of such an expression. + +Please consult the regex source and the test cases for precise information on +when regex or division is matched (should you need to know). In short, you +could sum it up as: + +If the end of a statement looks like a regex literal (even if it isn’t), it +will be treated as one. Otherwise it should work as expected (if you write sane +code). + +### ES2018 ### + +ES2018 added some nice regex improvements to the language. + +- [Unicode property escapes] should allow telling names and invalid non-ASCII + characters apart without blowing up the regex size. +- [Lookbehind assertions] should allow matching telling division and regex + literals apart in more cases. +- [Named capture groups] might simplify some things. + +These things would be nice to do, but are not critical. They probably have to +wait until the oldest maintained Node.js LTS release supports those features. + +[Unicode property escapes]: http://2ality.com/2017/07/regexp-unicode-property-escapes.html +[Lookbehind assertions]: http://2ality.com/2017/05/regexp-lookbehind-assertions.html +[Named capture groups]: http://2ality.com/2017/05/regexp-named-capture-groups.html + + +License +======= + +[MIT](LICENSE). diff --git a/node_modules/js-tokens/index.js b/node_modules/js-tokens/index.js new file mode 100644 index 0000000..b23a4a0 --- /dev/null +++ b/node_modules/js-tokens/index.js @@ -0,0 +1,23 @@ +// Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell +// License: MIT. (See LICENSE.) + +Object.defineProperty(exports, "__esModule", { + value: true +}) + +// This regex comes from regex.coffee, and is inserted here by generate-index.js +// (run `npm run build`). +exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g + +exports.matchToToken = function(match) { + var token = {type: "invalid", value: match[0], closed: undefined} + if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4]) + else if (match[ 5]) token.type = "comment" + else if (match[ 6]) token.type = "comment", token.closed = !!match[7] + else if (match[ 8]) token.type = "regex" + else if (match[ 9]) token.type = "number" + else if (match[10]) token.type = "name" + else if (match[11]) token.type = "punctuator" + else if (match[12]) token.type = "whitespace" + return token +} diff --git a/node_modules/js-tokens/package.json b/node_modules/js-tokens/package.json new file mode 100644 index 0000000..66752fa --- /dev/null +++ b/node_modules/js-tokens/package.json @@ -0,0 +1,30 @@ +{ + "name": "js-tokens", + "version": "4.0.0", + "author": "Simon Lydell", + "license": "MIT", + "description": "A regex that tokenizes JavaScript.", + "keywords": [ + "JavaScript", + "js", + "token", + "tokenize", + "regex" + ], + "files": [ + "index.js" + ], + "repository": "lydell/js-tokens", + "scripts": { + "test": "mocha --ui tdd", + "esprima-compare": "node esprima-compare ./index.js everything.js/es5.js", + "build": "node generate-index.js", + "dev": "npm run build && npm test" + }, + "devDependencies": { + "coffeescript": "2.1.1", + "esprima": "4.0.0", + "everything.js": "1.0.3", + "mocha": "5.0.0" + } +} diff --git a/node_modules/loose-envify/LICENSE b/node_modules/loose-envify/LICENSE new file mode 100644 index 0000000..fbafb48 --- /dev/null +++ b/node_modules/loose-envify/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Andres Suarez + +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/loose-envify/README.md b/node_modules/loose-envify/README.md new file mode 100644 index 0000000..7f4e07b --- /dev/null +++ b/node_modules/loose-envify/README.md @@ -0,0 +1,45 @@ +# loose-envify + +[![Build Status](https://travis-ci.org/zertosh/loose-envify.svg?branch=master)](https://travis-ci.org/zertosh/loose-envify) + +Fast (and loose) selective `process.env` replacer using [js-tokens](https://github.com/lydell/js-tokens) instead of an AST. Works just like [envify](https://github.com/hughsk/envify) but much faster. + +## Gotchas + +* Doesn't handle broken syntax. +* Doesn't look inside embedded expressions in template strings. + - **this won't work:** + ```js + console.log(`the current env is ${process.env.NODE_ENV}`); + ``` +* Doesn't replace oddly-spaced or oddly-commented expressions. + - **this won't work:** + ```js + console.log(process./*won't*/env./*work*/NODE_ENV); + ``` + +## Usage/Options + +loose-envify has the exact same interface as [envify](https://github.com/hughsk/envify), including the CLI. + +## Benchmark + +``` +envify: + + $ for i in {1..5}; do node bench/bench.js 'envify'; done + 708ms + 727ms + 791ms + 719ms + 720ms + +loose-envify: + + $ for i in {1..5}; do node bench/bench.js '../'; done + 51ms + 52ms + 52ms + 52ms + 52ms +``` diff --git a/node_modules/loose-envify/cli.js b/node_modules/loose-envify/cli.js new file mode 100755 index 0000000..c0b63cb --- /dev/null +++ b/node_modules/loose-envify/cli.js @@ -0,0 +1,16 @@ +#!/usr/bin/env node +'use strict'; + +var looseEnvify = require('./'); +var fs = require('fs'); + +if (process.argv[2]) { + fs.createReadStream(process.argv[2], {encoding: 'utf8'}) + .pipe(looseEnvify(process.argv[2])) + .pipe(process.stdout); +} else { + process.stdin.resume() + process.stdin + .pipe(looseEnvify(__filename)) + .pipe(process.stdout); +} diff --git a/node_modules/loose-envify/custom.js b/node_modules/loose-envify/custom.js new file mode 100644 index 0000000..6389bfa --- /dev/null +++ b/node_modules/loose-envify/custom.js @@ -0,0 +1,4 @@ +// envify compatibility +'use strict'; + +module.exports = require('./loose-envify'); diff --git a/node_modules/loose-envify/index.js b/node_modules/loose-envify/index.js new file mode 100644 index 0000000..8cd8305 --- /dev/null +++ b/node_modules/loose-envify/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./loose-envify')(process.env); diff --git a/node_modules/loose-envify/loose-envify.js b/node_modules/loose-envify/loose-envify.js new file mode 100644 index 0000000..b5a5be2 --- /dev/null +++ b/node_modules/loose-envify/loose-envify.js @@ -0,0 +1,36 @@ +'use strict'; + +var stream = require('stream'); +var util = require('util'); +var replace = require('./replace'); + +var jsonExtRe = /\.json$/; + +module.exports = function(rootEnv) { + rootEnv = rootEnv || process.env; + return function (file, trOpts) { + if (jsonExtRe.test(file)) { + return stream.PassThrough(); + } + var envs = trOpts ? [rootEnv, trOpts] : [rootEnv]; + return new LooseEnvify(envs); + }; +}; + +function LooseEnvify(envs) { + stream.Transform.call(this); + this._data = ''; + this._envs = envs; +} +util.inherits(LooseEnvify, stream.Transform); + +LooseEnvify.prototype._transform = function(buf, enc, cb) { + this._data += buf; + cb(); +}; + +LooseEnvify.prototype._flush = function(cb) { + var replaced = replace(this._data, this._envs); + this.push(replaced); + cb(); +}; diff --git a/node_modules/loose-envify/package.json b/node_modules/loose-envify/package.json new file mode 100644 index 0000000..5e3d0e2 --- /dev/null +++ b/node_modules/loose-envify/package.json @@ -0,0 +1,36 @@ +{ + "name": "loose-envify", + "version": "1.4.0", + "description": "Fast (and loose) selective `process.env` replacer using js-tokens instead of an AST", + "keywords": [ + "environment", + "variables", + "browserify", + "browserify-transform", + "transform", + "source", + "configuration" + ], + "homepage": "https://github.com/zertosh/loose-envify", + "license": "MIT", + "author": "Andres Suarez ", + "main": "index.js", + "bin": { + "loose-envify": "cli.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/zertosh/loose-envify.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "devDependencies": { + "browserify": "^13.1.1", + "envify": "^3.4.0", + "tap": "^8.0.0" + } +} diff --git a/node_modules/loose-envify/replace.js b/node_modules/loose-envify/replace.js new file mode 100644 index 0000000..ec15e81 --- /dev/null +++ b/node_modules/loose-envify/replace.js @@ -0,0 +1,65 @@ +'use strict'; + +var jsTokens = require('js-tokens').default; + +var processEnvRe = /\bprocess\.env\.[_$a-zA-Z][$\w]+\b/; +var spaceOrCommentRe = /^(?:\s|\/[/*])/; + +function replace(src, envs) { + if (!processEnvRe.test(src)) { + return src; + } + + var out = []; + var purge = envs.some(function(env) { + return env._ && env._.indexOf('purge') !== -1; + }); + + jsTokens.lastIndex = 0 + var parts = src.match(jsTokens); + + for (var i = 0; i < parts.length; i++) { + if (parts[i ] === 'process' && + parts[i + 1] === '.' && + parts[i + 2] === 'env' && + parts[i + 3] === '.') { + var prevCodeToken = getAdjacentCodeToken(-1, parts, i); + var nextCodeToken = getAdjacentCodeToken(1, parts, i + 4); + var replacement = getReplacementString(envs, parts[i + 4], purge); + if (prevCodeToken !== '.' && + nextCodeToken !== '.' && + nextCodeToken !== '=' && + typeof replacement === 'string') { + out.push(replacement); + i += 4; + continue; + } + } + out.push(parts[i]); + } + + return out.join(''); +} + +function getAdjacentCodeToken(dir, parts, i) { + while (true) { + var part = parts[i += dir]; + if (!spaceOrCommentRe.test(part)) { + return part; + } + } +} + +function getReplacementString(envs, name, purge) { + for (var j = 0; j < envs.length; j++) { + var env = envs[j]; + if (typeof env[name] !== 'undefined') { + return JSON.stringify(env[name]); + } + } + if (purge) { + return 'undefined'; + } +} + +module.exports = replace; diff --git a/node_modules/node-fetch/LICENSE.md b/node_modules/node-fetch/LICENSE.md new file mode 100644 index 0000000..660ffec --- /dev/null +++ b/node_modules/node-fetch/LICENSE.md @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 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/node-fetch/README.md b/node_modules/node-fetch/README.md new file mode 100644 index 0000000..55f09b7 --- /dev/null +++ b/node_modules/node-fetch/README.md @@ -0,0 +1,634 @@ +node-fetch +========== + +[![npm version][npm-image]][npm-url] +[![build status][travis-image]][travis-url] +[![coverage status][codecov-image]][codecov-url] +[![install size][install-size-image]][install-size-url] +[![Discord][discord-image]][discord-url] + +A light-weight module that brings `window.fetch` to Node.js + +(We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567)) + +[![Backers][opencollective-image]][opencollective-url] + + + +- [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) +- [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) +- [Advanced Usage](#advanced-usage) + - [Streams](#streams) + - [Buffer](#buffer) + - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data) + - [Extract Set-Cookie Header](#extract-set-cookie-header) + - [Post data using a file stream](#post-data-using-a-file-stream) + - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart) + - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal) +- [API](#api) + - [fetch(url[, options])](#fetchurl-options) + - [Options](#options) + - [Class: Request](#class-request) + - [Class: Response](#class-response) + - [Class: Headers](#class-headers) + - [Interface: Body](#interface-body) + - [Class: FetchError](#class-fetcherror) +- [License](#license) +- [Acknowledgement](#acknowledgement) + + + +## 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 Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) 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 but allow substituting it with [insert your favorite promise library]. +- Use native Node streams for body on both request and response. +- Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically. +- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting. + +## Difference from client-side fetch + +- See [Known Differences](LIMITS.md) for details. +- 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 (`2.x`) + +```sh +$ npm install node-fetch +``` + +## Loading and configuring the module +We suggest you load the module via `require` until the stabilization of ES modules in node: +```js +const fetch = require('node-fetch'); +``` + +If you are using a Promise library other than native, set it through `fetch.Promise`: +```js +const Bluebird = require('bluebird'); + +fetch.Promise = Bluebird; +``` + +## Common Usage + +NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences. + +#### Plain text or HTML +```js +fetch('https://github.com/') + .then(res => res.text()) + .then(body => console.log(body)); +``` + +#### JSON + +```js + +fetch('https://api.github.com/users/github') + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Simple Post +```js +fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' }) + .then(res => res.json()) // expecting a json response + .then(json => console.log(json)); +``` + +#### Post with JSON + +```js +const body = { a: 1 }; + +fetch('https://httpbin.org/post', { + method: 'post', + body: JSON.stringify(body), + headers: { 'Content-Type': 'application/json' }, + }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Post with form parameters +`URLSearchParams` is available in Node.js as of v7.5.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 +const { URLSearchParams } = require('url'); + +const params = new URLSearchParams(); +params.append('a', 1); + +fetch('https://httpbin.org/post', { method: 'POST', body: params }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Handling exceptions +NOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information. + +Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details. + +```js +fetch('https://domain.invalid/') + .catch(err => console.error(err)); +``` + +#### 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 +function checkStatus(res) { + if (res.ok) { // res.status >= 200 && res.status < 300 + return res; + } else { + throw MyCustomError(res.statusText); + } +} + +fetch('https://httpbin.org/status/400') + .then(checkStatus) + .then(res => console.log('will not get here...')) +``` + +## Advanced Usage + +#### Streams +The "Node.js way" is to use streams when possible: + +```js +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') + .then(res => { + const dest = fs.createWriteStream('./octocat.png'); + res.body.pipe(dest); + }); +``` + +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 +const fetch = require('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 +const fetch = require('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); +} +``` + +#### Buffer +If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API) + +```js +const fileType = require('file-type'); + +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') + .then(res => res.buffer()) + .then(buffer => fileType(buffer)) + .then(type => { /* ... */ }); +``` + +#### Accessing Headers and other Meta data +```js +fetch('https://github.com/') + .then(res => { + console.log(res.ok); + console.log(res.status); + console.log(res.statusText); + console.log(res.headers.raw()); + console.log(res.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 +fetch(url).then(res => { + // returns an array of values, instead of a string of comma-separated values + console.log(res.headers.raw()['set-cookie']); +}); +``` + +#### Post data using a file stream + +```js +const { createReadStream } = require('fs'); + +const stream = createReadStream('input.txt'); + +fetch('https://httpbin.org/post', { method: 'POST', body: stream }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Post with form-data (detect multipart) + +```js +const FormData = require('form-data'); + +const form = new FormData(); +form.append('a', 1); + +fetch('https://httpbin.org/post', { method: 'POST', body: form }) + .then(res => res.json()) + .then(json => console.log(json)); + +// OR, using custom headers +// NOTE: getHeaders() is non-standard API + +const form = new FormData(); +form.append('a', 1); + +const options = { + method: 'POST', + body: form, + headers: form.getHeaders() +} + +fetch('https://httpbin.org/post', options) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Request cancellation with AbortSignal + +> NOTE: You may cancel streamed requests only on Node >= v8.0.0 + +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 AbortController from 'abort-controller'; + +const controller = new AbortController(); +const timeout = setTimeout( + () => { controller.abort(); }, + 150, +); + +fetch(url, { signal: controller.signal }) + .then(res => res.json()) + .then( + data => { + useData(data) + }, + err => { + if (err.name === 'AbortError') { + // request was aborted + } + }, + ) + .finally(() => { + clearTimeout(timeout); + }); +``` + +See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) 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, a string, a Buffer, a Blob, 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 + timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead. + 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) +} +``` + +##### Default Headers + +If no values are set, the following request headers will be sent automatically: + +Header | Value +------------------- | -------------------------------------------------------- +`Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ +`Accept` | `*/*` +`Content-Length` | _(automatically calculated, if possible)_ +`Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ +`User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/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. + +If no agent is specified, the default agent provided by Node.js is used. Note that [this changed in Node.js 19](https://github.com/nodejs/node/blob/4267b92604ad78584244488e7f7508a690cb80d0/lib/_http_agent.js#L564) to have `keepalive` true by default. If you wish to enable `keepalive` in an earlier version of Node.js, you can override the agent as per the following code sample. + +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 +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; + } + } +} +``` + + +### 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` +- `referrer` +- `referrerPolicy` +- `mode` +- `credentials` +- `cache` +- `integrity` +- `keepalive` + +The following node-fetch extension properties are provided: + +- `follow` +- `compress` +- `counter` +- `agent` + +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: + +- `Response.error()` +- `Response.redirect()` +- `type` +- `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. + + +### 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 + +const meta = { + 'Content-Type': 'text/xml', + 'Breaking-Bad': '<3' +}; +const headers = new Headers(meta); + +// The above is equivalent to +const meta = [ + [ 'Content-Type', 'text/xml' ], + [ 'Breaking-Bad', '<3' ] +]; +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'); +meta.set('Breaking-Bad', '<3'); +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. + +The following methods are not yet implemented in node-fetch at this moment: + +- `formData()` + +#### 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.blob() +#### body.json() +#### body.text() + +*(spec-compliant)* + +* Returns: Promise + +Consume the body and return a promise that will resolve to one of these formats. + +#### body.buffer() + +*(node-fetch extension)* + +* Returns: Promise<Buffer> + +Consume the body and return a promise that will resolve to a Buffer. + +#### body.textConverted() + +*(node-fetch extension)* + +* Returns: Promise<String> + +Identical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible. + +(This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.) + + +### 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. + +## Acknowledgement + +Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference. + +`node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr). + +## License + +MIT + +[npm-image]: https://flat.badgen.net/npm/v/node-fetch +[npm-url]: https://www.npmjs.com/package/node-fetch +[travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch +[travis-url]: https://travis-ci.org/bitinn/node-fetch +[codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master +[codecov-url]: https://codecov.io/gh/bitinn/node-fetch +[install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch +[install-size-url]: https://packagephobia.now.sh/result?p=node-fetch +[discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square +[discord-url]: https://discord.gg/Zxbndcm +[opencollective-image]: https://opencollective.com/node-fetch/backers.svg +[opencollective-url]: https://opencollective.com/node-fetch +[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 +[LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md +[ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md +[UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md diff --git a/node_modules/node-fetch/browser.js b/node_modules/node-fetch/browser.js new file mode 100644 index 0000000..ee86265 --- /dev/null +++ b/node_modules/node-fetch/browser.js @@ -0,0 +1,25 @@ +"use strict"; + +// ref: https://github.com/tc39/proposal-global +var getGlobal = function () { + // the only reliable means to get the global object is + // `Function('return this')()` + // However, this causes CSP violations in Chrome apps. + if (typeof self !== 'undefined') { return self; } + if (typeof window !== 'undefined') { return window; } + if (typeof global !== 'undefined') { return global; } + throw new Error('unable to locate global object'); +} + +var globalObject = getGlobal(); + +module.exports = exports = globalObject.fetch; + +// Needed for TypeScript and Webpack. +if (globalObject.fetch) { + exports.default = globalObject.fetch.bind(globalObject); +} + +exports.Headers = globalObject.Headers; +exports.Request = globalObject.Request; +exports.Response = globalObject.Response; diff --git a/node_modules/node-fetch/lib/index.es.js b/node_modules/node-fetch/lib/index.es.js new file mode 100644 index 0000000..aae9799 --- /dev/null +++ b/node_modules/node-fetch/lib/index.es.js @@ -0,0 +1,1777 @@ +process.emitWarning("The .es.js file is deprecated. Use .mjs instead."); + +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // 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) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// 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 } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + 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 + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + 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); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // 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); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && 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 + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // 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. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.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$1(location, request.url).toString(); + } catch (err) { + // 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': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + 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 requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // 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 || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + 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 = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + 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 = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/node_modules/node-fetch/lib/index.js b/node_modules/node-fetch/lib/index.js new file mode 100644 index 0000000..567ff5d --- /dev/null +++ b/node_modules/node-fetch/lib/index.js @@ -0,0 +1,1787 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var Stream = _interopDefault(require('stream')); +var http = _interopDefault(require('http')); +var Url = _interopDefault(require('url')); +var whatwgUrl = _interopDefault(require('whatwg-url')); +var https = _interopDefault(require('https')); +var zlib = _interopDefault(require('zlib')); + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // 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) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// 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 } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + 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 + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + 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); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // 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); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && 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 + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // 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. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.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$1(location, request.url).toString(); + } catch (err) { + // 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': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + 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 requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // 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 || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + 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 = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + 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 = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; +exports.AbortError = AbortError; diff --git a/node_modules/node-fetch/lib/index.mjs b/node_modules/node-fetch/lib/index.mjs new file mode 100644 index 0000000..2863dd9 --- /dev/null +++ b/node_modules/node-fetch/lib/index.mjs @@ -0,0 +1,1775 @@ +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // 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) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// 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 } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + 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 + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + 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); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // 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); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && 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 + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // 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. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.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$1(location, request.url).toString(); + } catch (err) { + // 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': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + 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 requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // 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 || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + 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 = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + 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 = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/node_modules/node-fetch/package.json b/node_modules/node-fetch/package.json new file mode 100644 index 0000000..e0be176 --- /dev/null +++ b/node_modules/node-fetch/package.json @@ -0,0 +1,89 @@ +{ + "name": "node-fetch", + "version": "2.7.0", + "description": "A light-weight module that brings window.fetch to node.js", + "main": "lib/index.js", + "browser": "./browser.js", + "module": "lib/index.mjs", + "files": [ + "lib/index.js", + "lib/index.mjs", + "lib/index.es.js", + "browser.js" + ], + "engines": { + "node": "4.x || >=6.0.0" + }, + "scripts": { + "build": "cross-env BABEL_ENV=rollup rollup -c", + "prepare": "npm run build", + "test": "cross-env BABEL_ENV=test mocha --require babel-register --throw-deprecation test/test.js", + "report": "cross-env BABEL_ENV=coverage nyc --reporter lcov --reporter text mocha -R spec test/test.js", + "coverage": "cross-env BABEL_ENV=coverage nyc --reporter json --reporter text mocha -R spec test/test.js && codecov -f coverage/coverage-final.json" + }, + "repository": { + "type": "git", + "url": "https://github.com/bitinn/node-fetch.git" + }, + "keywords": [ + "fetch", + "http", + "promise" + ], + "author": "David Frank", + "license": "MIT", + "bugs": { + "url": "https://github.com/bitinn/node-fetch/issues" + }, + "homepage": "https://github.com/bitinn/node-fetch", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + }, + "devDependencies": { + "@ungap/url-search-params": "^0.1.2", + "abort-controller": "^1.1.0", + "abortcontroller-polyfill": "^1.3.0", + "babel-core": "^6.26.3", + "babel-plugin-istanbul": "^4.1.6", + "babel-plugin-transform-async-generator-functions": "^6.24.1", + "babel-polyfill": "^6.26.0", + "babel-preset-env": "1.4.0", + "babel-register": "^6.16.3", + "chai": "^3.5.0", + "chai-as-promised": "^7.1.1", + "chai-iterator": "^1.1.1", + "chai-string": "~1.3.0", + "codecov": "3.3.0", + "cross-env": "^5.2.0", + "form-data": "^2.3.3", + "is-builtin-module": "^1.0.0", + "mocha": "^5.0.0", + "nyc": "11.9.0", + "parted": "^0.1.1", + "promise": "^8.0.3", + "resumer": "0.0.0", + "rollup": "^0.63.4", + "rollup-plugin-babel": "^3.0.7", + "string-to-arraybuffer": "^1.0.2", + "teeny-request": "3.7.0" + }, + "release": { + "branches": [ + "+([0-9]).x", + "main", + "next", + { + "name": "beta", + "prerelease": true + } + ] + } +} diff --git a/node_modules/react-audio-visualize/LICENSE b/node_modules/react-audio-visualize/LICENSE new file mode 100644 index 0000000..2d4fd23 --- /dev/null +++ b/node_modules/react-audio-visualize/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Samhir Tarif + +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/react-audio-visualize/README.md b/node_modules/react-audio-visualize/README.md new file mode 100644 index 0000000..28c34ff --- /dev/null +++ b/node_modules/react-audio-visualize/README.md @@ -0,0 +1,101 @@ +# **react-audio-visualize** +An audio visualizer for React. Provides separate components to visualize both live audio and audio blobs. + +## Installation +```sh +npm install react-audio-visualize +``` + +## **AudioVisualizer** Component ([Example](https://stackblitz.com/edit/stackblitz-starters-kjpu5q?file=src%2FApp.tsx)) + +![screenshot](./assets/AudioVisualizer.png) + +```js +import React, { useState } from 'react'; +import { AudioVisualizer } from 'react-audio-visualize'; + +const Visualizer = () => { + const [blob, setBlob] = useState(); + const visualizerRef = useRef(null) + + // set blob somewhere in code + + return ( +
+ {blob && ( + + )} +
+ ) +} + +``` + +| Props | Description | Default | Optional | +| :------------ |:--------------- |:--------------- | :--------------- | +| **`blob`** | Audio blob to visualize | N/A | No | +| **`width`** | Width of the visualizer | N/A | No | +| **`height`** | Height of the visualizer | N/A | No | +| **`barWidth`** | Width of each individual bar in the visualization | `2` | Yes | +| **`gap`** | Gap between each bar in the visualization | `1` | Yes | +| **`backgroundColor`** | BackgroundColor for the visualization | `transparent` | Yes | +| **`barColor`** | Color for the bars that have not yet been played | `"rgb(184, 184, 184)""` | Yes | +| **`barPlayedColor`** | Color for the bars that have been played | `"rgb(160, 198, 255)""` | Yes | +| **`currentTime`** | Current time stamp till which the audio blob has been played. Visualized bars that fall before the current time will have `barPlayerColor`, while that ones that fall after will have `barColor` | N/A | Yes | +| **`style`** | Custom styles that can be passed to the visualization canvas | N/A | Yes | +| **`ref`** | A `ForwardedRef` for the `HTMLCanvasElement` | N/A | Yes | + +--- + +## **LiveAudioVisualizer** Component ([Example](https://stackblitz.com/edit/stackblitz-starters-kjpu5q?file=src%2FApp.tsx)) + +![livevisualizergif](./assets/LiveAudioVisualizer.gif) + +```js +import React, { useState } from 'react'; +import { LiveAudioVisualizer } from 'react-audio-visualize'; + +const Visualizer = () => { + const [mediaRecorder, setMediaRecorder] = useState(); + + // set media recorder somewhere in code + + return ( +
+ {mediaRecorder && ( + + )} +
+ ) +} + +``` + +| Props | Description | Default | Optional | +| :------------ |:--------------- |:--------------- | :--------------- | +| **`mediaRecorder`** | Media recorder who's stream needs to visualized | N/A | No | +| **`width`** | Width of the visualizer | `100%` | Yes | +| **`height`** | Height of the visualizer | `100%` | Yes | +| **`barWidth`** | Width of each individual bar in the visualization | `2` | Yes | +| **`gap`** | Gap between each bar in the visualization | `1` | Yes | +| **`backgroundColor`** | BackgroundColor for the visualization | `transparent` | Yes | +| **`barColor`** | Color for the bars that have not yet been played | `"rgb(160, 198, 255)"` | Yes | +| **`fftSize`** | An unsigned integer, representing the window size of the FFT, given in number of samples. For more [details](https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/fftSize) | `1024` | Yes | +| **`maxDecibels`** | A double, representing the maximum decibel value for scaling the FFT analysis data. For more [details](https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/maxDecibels) | `-10` | Yes | +| **`minDecibels`** | A double, representing the minimum decibel value for scaling the FFT analysis data, where 0 dB is the loudest possible sound. For more [details](https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/minDecibels) | `-90` | Yes | +| **`smoothingTimeConstant`** | A double within the range 0 to 1 (0 meaning no time averaging). For more [details](https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/smoothingTimeConstant) | `0.4` | Yes | + + + diff --git a/node_modules/react-audio-visualize/dist/AudioVisualizer/AudioVisualizer.d.ts b/node_modules/react-audio-visualize/dist/AudioVisualizer/AudioVisualizer.d.ts new file mode 100644 index 0000000..b42a252 --- /dev/null +++ b/node_modules/react-audio-visualize/dist/AudioVisualizer/AudioVisualizer.d.ts @@ -0,0 +1,50 @@ +import { type ForwardRefExoticComponent, type RefAttributes } from "react"; +interface Props { + /** + * Audio blob to visualize + */ + blob: Blob; + /** + * Width of the visualizer + */ + width: number; + /** + * Height of the visualizer + */ + height: number; + /** + * Width of each individual bar in the visualization. Default: `2` + */ + barWidth?: number; + /** + * Gap between each bar in the visualization. Default: `1` + */ + gap?: number; + /** + * BackgroundColor for the visualization: Default: `"transparent"` + */ + backgroundColor?: string; + /** + * Color for the bars that have not yet been played: Default: `"rgb(184, 184, 184)""` + */ + barColor?: string; + /** + * Color for the bars that have been played: Default: `"rgb(160, 198, 255)""` + */ + barPlayedColor?: string; + /** + * Current time stamp till which the audio blob has been played. + * Visualized bars that fall before the current time will have `barPlayerColor`, while that ones that fall after will have `barColor` + */ + currentTime?: number; + /** + * Custome styles that can be passed to the visualization canvas + */ + style?: React.CSSProperties; + /** + * A `ForwardedRef` for the `HTMLCanvasElement` + */ + ref?: React.ForwardedRef; +} +declare const AudioVisualizer: ForwardRefExoticComponent>; +export { AudioVisualizer }; diff --git a/node_modules/react-audio-visualize/dist/AudioVisualizer/index.d.ts b/node_modules/react-audio-visualize/dist/AudioVisualizer/index.d.ts new file mode 100644 index 0000000..51ae41d --- /dev/null +++ b/node_modules/react-audio-visualize/dist/AudioVisualizer/index.d.ts @@ -0,0 +1 @@ +export { AudioVisualizer } from "./AudioVisualizer"; diff --git a/node_modules/react-audio-visualize/dist/AudioVisualizer/types.d.ts b/node_modules/react-audio-visualize/dist/AudioVisualizer/types.d.ts new file mode 100644 index 0000000..593c74d --- /dev/null +++ b/node_modules/react-audio-visualize/dist/AudioVisualizer/types.d.ts @@ -0,0 +1,4 @@ +export interface dataPoint { + max: number; + min: number; +} diff --git a/node_modules/react-audio-visualize/dist/AudioVisualizer/utils.d.ts b/node_modules/react-audio-visualize/dist/AudioVisualizer/utils.d.ts new file mode 100644 index 0000000..f357a65 --- /dev/null +++ b/node_modules/react-audio-visualize/dist/AudioVisualizer/utils.d.ts @@ -0,0 +1,3 @@ +import { type dataPoint } from "./types"; +export declare const calculateBarData: (buffer: AudioBuffer, height: number, width: number, barWidth: number, gap: number) => dataPoint[]; +export declare const draw: (data: dataPoint[], canvas: HTMLCanvasElement, barWidth: number, gap: number, backgroundColor: string, barColor: string, barPlayedColor?: string, currentTime?: number, duration?: number) => void; diff --git a/node_modules/react-audio-visualize/dist/LiveAudioVisualizer/LiveAudioVisualizer.d.ts b/node_modules/react-audio-visualize/dist/LiveAudioVisualizer/LiveAudioVisualizer.d.ts new file mode 100644 index 0000000..c09bd7b --- /dev/null +++ b/node_modules/react-audio-visualize/dist/LiveAudioVisualizer/LiveAudioVisualizer.d.ts @@ -0,0 +1,60 @@ +import { type ReactElement } from "react"; +export interface Props { + /** + * Media recorder who's stream needs to visualized + */ + mediaRecorder: MediaRecorder; + /** + * Width of the visualization. Default" "100%" + */ + width?: number | string; + /** + * Height of the visualization. Default" "100%" + */ + height?: number | string; + /** + * Width of each individual bar in the visualization. Default: `2` + */ + barWidth?: number; + /** + * Gap between each bar in the visualization. Default `1` + */ + gap?: number; + /** + * BackgroundColor for the visualization: Default `transparent` + */ + backgroundColor?: string; + /** + * Color of the bars drawn in the visualization. Default: `"rgb(160, 198, 255)"` + */ + barColor?: string; + /** + * An unsigned integer, representing the window size of the FFT, given in number of samples. + * A higher value will result in more details in the frequency domain but fewer details in the amplitude domain. + * For more details {@link https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/fftSize MDN AnalyserNode: fftSize property} + * Default: `1024` + */ + fftSize?: 32 | 64 | 128 | 256 | 512 | 1024 | 2048 | 4096 | 8192 | 16384 | 32768; + /** + * A double, representing the maximum decibel value for scaling the FFT analysis data + * For more details {@link https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/maxDecibels MDN AnalyserNode: maxDecibels property} + * Default: `-10` + */ + maxDecibels?: number; + /** + * A double, representing the minimum decibel value for scaling the FFT analysis data, where 0 dB is the loudest possible sound + * For more details {@link https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/minDecibels MDN AnalyserNode: minDecibels property} + * Default: `-90` + */ + minDecibels?: number; + /** + * A double within the range 0 to 1 (0 meaning no time averaging). The default value is 0.8. + * If 0 is set, there is no averaging done, whereas a value of 1 means "overlap the previous and current buffer quite a lot while computing the value", + * which essentially smooths the changes across + * For more details {@link https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/smoothingTimeConstant MDN AnalyserNode: smoothingTimeConstant property} + * Default: `0.4` + */ + smoothingTimeConstant?: number; +} +declare const LiveAudioVisualizer: (props: Props) => ReactElement; +export { LiveAudioVisualizer }; diff --git a/node_modules/react-audio-visualize/dist/LiveAudioVisualizer/index.d.ts b/node_modules/react-audio-visualize/dist/LiveAudioVisualizer/index.d.ts new file mode 100644 index 0000000..c55c835 --- /dev/null +++ b/node_modules/react-audio-visualize/dist/LiveAudioVisualizer/index.d.ts @@ -0,0 +1 @@ +export { LiveAudioVisualizer } from "./LiveAudioVisualizer"; diff --git a/node_modules/react-audio-visualize/dist/LiveAudioVisualizer/utils.d.ts b/node_modules/react-audio-visualize/dist/LiveAudioVisualizer/utils.d.ts new file mode 100644 index 0000000..9939994 --- /dev/null +++ b/node_modules/react-audio-visualize/dist/LiveAudioVisualizer/utils.d.ts @@ -0,0 +1,2 @@ +export declare const calculateBarData: (frequencyData: Uint8Array, width: number, barWidth: number, gap: number) => number[]; +export declare const draw: (data: number[], canvas: HTMLCanvasElement, barWidth: number, gap: number, backgroundColor: string, barColor: string) => void; diff --git a/node_modules/react-audio-visualize/dist/index.d.ts b/node_modules/react-audio-visualize/dist/index.d.ts new file mode 100644 index 0000000..20d5506 --- /dev/null +++ b/node_modules/react-audio-visualize/dist/index.d.ts @@ -0,0 +1,2 @@ +export { LiveAudioVisualizer } from "./LiveAudioVisualizer"; +export { AudioVisualizer } from "./AudioVisualizer"; diff --git a/node_modules/react-audio-visualize/dist/react-audio-visualize.es.js b/node_modules/react-audio-visualize/dist/react-audio-visualize.es.js new file mode 100644 index 0000000..507c601 --- /dev/null +++ b/node_modules/react-audio-visualize/dist/react-audio-visualize.es.js @@ -0,0 +1,828 @@ +import Ae, { useState as J, useRef as De, useEffect as G, useCallback as fr, forwardRef as dr, useImperativeHandle as vr } from "react"; +var ae = { exports: {} }, V = {}; +/** + * @license React + * react-jsx-runtime.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var Pe; +function pr() { + if (Pe) + return V; + Pe = 1; + var d = Ae, v = Symbol.for("react.element"), w = Symbol.for("react.fragment"), R = Object.prototype.hasOwnProperty, y = d.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, E = { key: !0, ref: !0, __self: !0, __source: !0 }; + function b(u, c, m) { + var a, i = {}, l = null, S = null; + m !== void 0 && (l = "" + m), c.key !== void 0 && (l = "" + c.key), c.ref !== void 0 && (S = c.ref); + for (a in c) + R.call(c, a) && !E.hasOwnProperty(a) && (i[a] = c[a]); + if (u && u.defaultProps) + for (a in c = u.defaultProps, c) + i[a] === void 0 && (i[a] = c[a]); + return { $$typeof: v, type: u, key: l, ref: S, props: i, _owner: y.current }; + } + return V.Fragment = w, V.jsx = b, V.jsxs = b, V; +} +var L = {}; +/** + * @license React + * react-jsx-runtime.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var je; +function mr() { + return je || (je = 1, process.env.NODE_ENV !== "production" && function() { + var d = Ae, v = Symbol.for("react.element"), w = Symbol.for("react.portal"), R = Symbol.for("react.fragment"), y = Symbol.for("react.strict_mode"), E = Symbol.for("react.profiler"), b = Symbol.for("react.provider"), u = Symbol.for("react.context"), c = Symbol.for("react.forward_ref"), m = Symbol.for("react.suspense"), a = Symbol.for("react.suspense_list"), i = Symbol.for("react.memo"), l = Symbol.for("react.lazy"), S = Symbol.for("react.offscreen"), C = Symbol.iterator, A = "@@iterator"; + function D(e) { + if (e === null || typeof e != "object") + return null; + var r = C && e[C] || e[A]; + return typeof r == "function" ? r : null; + } + var g = d.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + function p(e) { + { + for (var r = arguments.length, t = new Array(r > 1 ? r - 1 : 0), n = 1; n < r; n++) + t[n - 1] = arguments[n]; + T("error", e, t); + } + } + function T(e, r, t) { + { + var n = g.ReactDebugCurrentFrame, f = n.getStackAddendum(); + f !== "" && (r += "%s", t = t.concat([f])); + var h = t.map(function(s) { + return String(s); + }); + h.unshift("Warning: " + r), Function.prototype.apply.call(console[e], console, h); + } + } + var P = !1, Fe = !1, Ie = !1, $e = !1, Ye = !1, ie; + ie = Symbol.for("react.module.reference"); + function Me(e) { + return !!(typeof e == "string" || typeof e == "function" || e === R || e === E || Ye || e === y || e === m || e === a || $e || e === S || P || Fe || Ie || typeof e == "object" && e !== null && (e.$$typeof === l || e.$$typeof === i || e.$$typeof === b || e.$$typeof === u || e.$$typeof === c || // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + e.$$typeof === ie || e.getModuleId !== void 0)); + } + function Ne(e, r, t) { + var n = e.displayName; + if (n) + return n; + var f = r.displayName || r.name || ""; + return f !== "" ? t + "(" + f + ")" : t; + } + function oe(e) { + return e.displayName || "Context"; + } + function k(e) { + if (e == null) + return null; + if (typeof e.tag == "number" && p("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."), typeof e == "function") + return e.displayName || e.name || null; + if (typeof e == "string") + return e; + switch (e) { + case R: + return "Fragment"; + case w: + return "Portal"; + case E: + return "Profiler"; + case y: + return "StrictMode"; + case m: + return "Suspense"; + case a: + return "SuspenseList"; + } + if (typeof e == "object") + switch (e.$$typeof) { + case u: + var r = e; + return oe(r) + ".Consumer"; + case b: + var t = e; + return oe(t._context) + ".Provider"; + case c: + return Ne(e, e.render, "ForwardRef"); + case i: + var n = e.displayName || null; + return n !== null ? n : k(e.type) || "Memo"; + case l: { + var f = e, h = f._payload, s = f._init; + try { + return k(s(h)); + } catch { + return null; + } + } + } + return null; + } + var I = Object.assign, M = 0, ue, se, ce, le, fe, de, ve; + function pe() { + } + pe.__reactDisabledLog = !0; + function Ve() { + { + if (M === 0) { + ue = console.log, se = console.info, ce = console.warn, le = console.error, fe = console.group, de = console.groupCollapsed, ve = console.groupEnd; + var e = { + configurable: !0, + enumerable: !0, + value: pe, + writable: !0 + }; + Object.defineProperties(console, { + info: e, + log: e, + warn: e, + error: e, + group: e, + groupCollapsed: e, + groupEnd: e + }); + } + M++; + } + } + function Le() { + { + if (M--, M === 0) { + var e = { + configurable: !0, + enumerable: !0, + writable: !0 + }; + Object.defineProperties(console, { + log: I({}, e, { + value: ue + }), + info: I({}, e, { + value: se + }), + warn: I({}, e, { + value: ce + }), + error: I({}, e, { + value: le + }), + group: I({}, e, { + value: fe + }), + groupCollapsed: I({}, e, { + value: de + }), + groupEnd: I({}, e, { + value: ve + }) + }); + } + M < 0 && p("disabledDepth fell below zero. This is a bug in React. Please file an issue."); + } + } + var H = g.ReactCurrentDispatcher, K; + function W(e, r, t) { + { + if (K === void 0) + try { + throw Error(); + } catch (f) { + var n = f.stack.trim().match(/\n( *(at )?)/); + K = n && n[1] || ""; + } + return ` +` + K + e; + } + } + var X = !1, B; + { + var We = typeof WeakMap == "function" ? WeakMap : Map; + B = new We(); + } + function me(e, r) { + if (!e || X) + return ""; + { + var t = B.get(e); + if (t !== void 0) + return t; + } + var n; + X = !0; + var f = Error.prepareStackTrace; + Error.prepareStackTrace = void 0; + var h; + h = H.current, H.current = null, Ve(); + try { + if (r) { + var s = function() { + throw Error(); + }; + if (Object.defineProperty(s.prototype, "props", { + set: function() { + throw Error(); + } + }), typeof Reflect == "object" && Reflect.construct) { + try { + Reflect.construct(s, []); + } catch (F) { + n = F; + } + Reflect.construct(e, [], s); + } else { + try { + s.call(); + } catch (F) { + n = F; + } + e.call(s.prototype); + } + } else { + try { + throw Error(); + } catch (F) { + n = F; + } + e(); + } + } catch (F) { + if (F && n && typeof F.stack == "string") { + for (var o = F.stack.split(` +`), O = n.stack.split(` +`), _ = o.length - 1, x = O.length - 1; _ >= 1 && x >= 0 && o[_] !== O[x]; ) + x--; + for (; _ >= 1 && x >= 0; _--, x--) + if (o[_] !== O[x]) { + if (_ !== 1 || x !== 1) + do + if (_--, x--, x < 0 || o[_] !== O[x]) { + var j = ` +` + o[_].replace(" at new ", " at "); + return e.displayName && j.includes("") && (j = j.replace("", e.displayName)), typeof e == "function" && B.set(e, j), j; + } + while (_ >= 1 && x >= 0); + break; + } + } + } finally { + X = !1, H.current = h, Le(), Error.prepareStackTrace = f; + } + var Y = e ? e.displayName || e.name : "", Oe = Y ? W(Y) : ""; + return typeof e == "function" && B.set(e, Oe), Oe; + } + function Be(e, r, t) { + return me(e, !1); + } + function Ue(e) { + var r = e.prototype; + return !!(r && r.isReactComponent); + } + function U(e, r, t) { + if (e == null) + return ""; + if (typeof e == "function") + return me(e, Ue(e)); + if (typeof e == "string") + return W(e); + switch (e) { + case m: + return W("Suspense"); + case a: + return W("SuspenseList"); + } + if (typeof e == "object") + switch (e.$$typeof) { + case c: + return Be(e.render); + case i: + return U(e.type, r, t); + case l: { + var n = e, f = n._payload, h = n._init; + try { + return U(h(f), r, t); + } catch { + } + } + } + return ""; + } + var z = Object.prototype.hasOwnProperty, he = {}, ge = g.ReactDebugCurrentFrame; + function q(e) { + if (e) { + var r = e._owner, t = U(e.type, e._source, r ? r.type : null); + ge.setExtraStackFrame(t); + } else + ge.setExtraStackFrame(null); + } + function ze(e, r, t, n, f) { + { + var h = Function.call.bind(z); + for (var s in e) + if (h(e, s)) { + var o = void 0; + try { + if (typeof e[s] != "function") { + var O = Error((n || "React class") + ": " + t + " type `" + s + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof e[s] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); + throw O.name = "Invariant Violation", O; + } + o = e[s](r, s, n, t, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); + } catch (_) { + o = _; + } + o && !(o instanceof Error) && (q(f), p("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", n || "React class", t, s, typeof o), q(null)), o instanceof Error && !(o.message in he) && (he[o.message] = !0, q(f), p("Failed %s type: %s", t, o.message), q(null)); + } + } + } + var qe = Array.isArray; + function Z(e) { + return qe(e); + } + function Je(e) { + { + var r = typeof Symbol == "function" && Symbol.toStringTag, t = r && e[Symbol.toStringTag] || e.constructor.name || "Object"; + return t; + } + } + function Ge(e) { + try { + return ye(e), !1; + } catch { + return !0; + } + } + function ye(e) { + return "" + e; + } + function Re(e) { + if (Ge(e)) + return p("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", Je(e)), ye(e); + } + var N = g.ReactCurrentOwner, He = { + key: !0, + ref: !0, + __self: !0, + __source: !0 + }, Ee, _e, Q; + Q = {}; + function Ke(e) { + if (z.call(e, "ref")) { + var r = Object.getOwnPropertyDescriptor(e, "ref").get; + if (r && r.isReactWarning) + return !1; + } + return e.ref !== void 0; + } + function Xe(e) { + if (z.call(e, "key")) { + var r = Object.getOwnPropertyDescriptor(e, "key").get; + if (r && r.isReactWarning) + return !1; + } + return e.key !== void 0; + } + function Ze(e, r) { + if (typeof e.ref == "string" && N.current && r && N.current.stateNode !== r) { + var t = k(N.current.type); + Q[t] || (p('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', k(N.current.type), e.ref), Q[t] = !0); + } + } + function Qe(e, r) { + { + var t = function() { + Ee || (Ee = !0, p("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", r)); + }; + t.isReactWarning = !0, Object.defineProperty(e, "key", { + get: t, + configurable: !0 + }); + } + } + function er(e, r) { + { + var t = function() { + _e || (_e = !0, p("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", r)); + }; + t.isReactWarning = !0, Object.defineProperty(e, "ref", { + get: t, + configurable: !0 + }); + } + } + var rr = function(e, r, t, n, f, h, s) { + var o = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: v, + // Built-in properties that belong on the element + type: e, + key: r, + ref: t, + props: s, + // Record the component responsible for creating this element. + _owner: h + }; + return o._store = {}, Object.defineProperty(o._store, "validated", { + configurable: !1, + enumerable: !1, + writable: !0, + value: !1 + }), Object.defineProperty(o, "_self", { + configurable: !1, + enumerable: !1, + writable: !1, + value: n + }), Object.defineProperty(o, "_source", { + configurable: !1, + enumerable: !1, + writable: !1, + value: f + }), Object.freeze && (Object.freeze(o.props), Object.freeze(o)), o; + }; + function tr(e, r, t, n, f) { + { + var h, s = {}, o = null, O = null; + t !== void 0 && (Re(t), o = "" + t), Xe(r) && (Re(r.key), o = "" + r.key), Ke(r) && (O = r.ref, Ze(r, f)); + for (h in r) + z.call(r, h) && !He.hasOwnProperty(h) && (s[h] = r[h]); + if (e && e.defaultProps) { + var _ = e.defaultProps; + for (h in _) + s[h] === void 0 && (s[h] = _[h]); + } + if (o || O) { + var x = typeof e == "function" ? e.displayName || e.name || "Unknown" : e; + o && Qe(s, x), O && er(s, x); + } + return rr(e, o, O, f, n, N.current, s); + } + } + var ee = g.ReactCurrentOwner, be = g.ReactDebugCurrentFrame; + function $(e) { + if (e) { + var r = e._owner, t = U(e.type, e._source, r ? r.type : null); + be.setExtraStackFrame(t); + } else + be.setExtraStackFrame(null); + } + var re; + re = !1; + function te(e) { + return typeof e == "object" && e !== null && e.$$typeof === v; + } + function xe() { + { + if (ee.current) { + var e = k(ee.current.type); + if (e) + return ` + +Check the render method of \`` + e + "`."; + } + return ""; + } + } + function nr(e) { + { + if (e !== void 0) { + var r = e.fileName.replace(/^.*[\\\/]/, ""), t = e.lineNumber; + return ` + +Check your code at ` + r + ":" + t + "."; + } + return ""; + } + } + var we = {}; + function ar(e) { + { + var r = xe(); + if (!r) { + var t = typeof e == "string" ? e : e.displayName || e.name; + t && (r = ` + +Check the top-level render call using <` + t + ">."); + } + return r; + } + } + function Te(e, r) { + { + if (!e._store || e._store.validated || e.key != null) + return; + e._store.validated = !0; + var t = ar(r); + if (we[t]) + return; + we[t] = !0; + var n = ""; + e && e._owner && e._owner !== ee.current && (n = " It was passed a child from " + k(e._owner.type) + "."), $(e), p('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', t, n), $(null); + } + } + function Se(e, r) { + { + if (typeof e != "object") + return; + if (Z(e)) + for (var t = 0; t < e.length; t++) { + var n = e[t]; + te(n) && Te(n, r); + } + else if (te(e)) + e._store && (e._store.validated = !0); + else if (e) { + var f = D(e); + if (typeof f == "function" && f !== e.entries) + for (var h = f.call(e), s; !(s = h.next()).done; ) + te(s.value) && Te(s.value, r); + } + } + } + function ir(e) { + { + var r = e.type; + if (r == null || typeof r == "string") + return; + var t; + if (typeof r == "function") + t = r.propTypes; + else if (typeof r == "object" && (r.$$typeof === c || // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + r.$$typeof === i)) + t = r.propTypes; + else + return; + if (t) { + var n = k(r); + ze(t, e.props, "prop", n, e); + } else if (r.PropTypes !== void 0 && !re) { + re = !0; + var f = k(r); + p("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", f || "Unknown"); + } + typeof r.getDefaultProps == "function" && !r.getDefaultProps.isReactClassApproved && p("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); + } + } + function or(e) { + { + for (var r = Object.keys(e.props), t = 0; t < r.length; t++) { + var n = r[t]; + if (n !== "children" && n !== "key") { + $(e), p("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", n), $(null); + break; + } + } + e.ref !== null && ($(e), p("Invalid attribute `ref` supplied to `React.Fragment`."), $(null)); + } + } + function Ce(e, r, t, n, f, h) { + { + var s = Me(e); + if (!s) { + var o = ""; + (e === void 0 || typeof e == "object" && e !== null && Object.keys(e).length === 0) && (o += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."); + var O = nr(f); + O ? o += O : o += xe(); + var _; + e === null ? _ = "null" : Z(e) ? _ = "array" : e !== void 0 && e.$$typeof === v ? (_ = "<" + (k(e.type) || "Unknown") + " />", o = " Did you accidentally export a JSX literal instead of a component?") : _ = typeof e, p("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", _, o); + } + var x = tr(e, r, t, f, h); + if (x == null) + return x; + if (s) { + var j = r.children; + if (j !== void 0) + if (n) + if (Z(j)) { + for (var Y = 0; Y < j.length; Y++) + Se(j[Y], e); + Object.freeze && Object.freeze(j); + } else + p("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."); + else + Se(j, e); + } + return e === R ? or(x) : ir(x), x; + } + } + function ur(e, r, t) { + return Ce(e, r, t, !0); + } + function sr(e, r, t) { + return Ce(e, r, t, !1); + } + var cr = sr, lr = ur; + L.Fragment = R, L.jsx = cr, L.jsxs = lr; + }()), L; +} +process.env.NODE_ENV === "production" ? ae.exports = pr() : ae.exports = mr(); +var ke = ae.exports; +const hr = (d, v, w, R) => { + let y = v / (w + R), E = Math.floor(d.length / y); + y > d.length && (y = d.length, E = 1); + const b = []; + for (let u = 0; u < y; u++) { + let c = 0; + for (let m = 0; m < E && u * E + m < d.length; m++) + c += d[u * E + m]; + b.push(c / E); + } + return b; +}, gr = (d, v, w, R, y, E) => { + const b = v.height / 2, u = v.getContext("2d"); + u && (u.clearRect(0, 0, v.width, v.height), y !== "transparent" && (u.fillStyle = y, u.fillRect(0, 0, v.width, v.height)), d.forEach((c, m) => { + u.fillStyle = E; + const a = m * (w + R), i = b - c / 2, l = w, S = c || 1; + u.beginPath(), u.roundRect ? (u.roundRect(a, i, l, S, 50), u.fill()) : u.fillRect(a, i, l, S); + })); +}, _r = ({ + mediaRecorder: d, + width: v = "100%", + height: w = "100%", + barWidth: R = 2, + gap: y = 1, + backgroundColor: E = "transparent", + barColor: b = "rgb(160, 198, 255)", + fftSize: u = 1024, + maxDecibels: c = -10, + minDecibels: m = -90, + smoothingTimeConstant: a = 0.4 +}) => { + const [i] = J(() => new AudioContext()), [l, S] = J(), C = De(null); + G(() => { + if (!d.stream) + return; + const g = i.createAnalyser(); + S(g), g.fftSize = u, g.minDecibels = m, g.maxDecibels = c, g.smoothingTimeConstant = a, i.createMediaStreamSource(d.stream).connect(g); + }, [d.stream]), G(() => { + l && d.state === "recording" && A(); + }, [l, d.state]); + const A = fr(() => { + if (!l) + return; + const g = new Uint8Array(l == null ? void 0 : l.frequencyBinCount); + d.state === "recording" ? (l == null || l.getByteFrequencyData(g), D(g), requestAnimationFrame(A)) : d.state === "paused" ? D(g) : d.state === "inactive" && i.state !== "closed" && i.close(); + }, [l, i.state]), D = (g) => { + if (!C.current) + return; + const p = hr( + g, + C.current.width, + R, + y + ); + gr( + p, + C.current, + R, + y, + E, + b + ); + }; + return /* @__PURE__ */ ke.jsx( + "canvas", + { + ref: C, + width: v, + height: w, + style: { + aspectRatio: "unset" + } + } + ); +}, yr = (d, v, w, R, y) => { + const E = d.getChannelData(0), b = w / (R + y), u = Math.floor(E.length / b), c = v / 2; + let m = [], a = 0; + for (let i = 0; i < b; i++) { + const l = []; + let S = 0; + const C = []; + let A = 0; + for (let T = 0; T < u && i * u + T < d.length; T++) { + const P = E[i * u + T]; + P <= 0 && (l.push(P), S++), P > 0 && (C.push(P), A++); + } + const D = l.reduce((T, P) => T + P, 0) / S, p = { max: C.reduce((T, P) => T + P, 0) / A, min: D }; + p.max > a && (a = p.max), Math.abs(p.min) > a && (a = Math.abs(p.min)), m.push(p); + } + if (c * 0.8 > a * c) { + const i = c * 0.8 / a; + m = m.map((l) => ({ + max: l.max * i, + min: l.min * i + })); + } + return m; +}, ne = (d, v, w, R, y, E, b, u = 0, c = 1) => { + const m = v.height / 2, a = v.getContext("2d"); + if (!a) + return; + a.clearRect(0, 0, v.width, v.height), y !== "transparent" && (a.fillStyle = y, a.fillRect(0, 0, v.width, v.height)); + const i = (u || 0) / c; + d.forEach((l, S) => { + const C = S / d.length, A = i > C; + a.fillStyle = A && b ? b : E; + const D = S * (w + R), g = m + l.min, p = w, T = m + l.max - g; + a.beginPath(), a.roundRect ? (a.roundRect(D, g, p, T, 50), a.fill()) : a.fillRect(D, g, p, T); + }); +}, Rr = dr( + ({ + blob: d, + width: v, + height: w, + barWidth: R = 2, + gap: y = 1, + currentTime: E, + style: b, + backgroundColor: u = "transparent", + barColor: c = "rgb(184, 184, 184)", + barPlayedColor: m = "rgb(160, 198, 255)" + }, a) => { + const i = De(null), [l, S] = J([]), [C, A] = J(0); + return vr( + a, + () => i.current, + [] + ), G(() => { + (async () => { + if (!i.current) + return; + if (!d) { + const T = Array.from({ length: 100 }, () => ({ + max: 0, + min: 0 + })); + ne( + T, + i.current, + R, + y, + u, + c, + m + ); + return; + } + const g = await d.arrayBuffer(); + await new AudioContext().decodeAudioData(g, (T) => { + if (!i.current) + return; + A(T.duration); + const P = yr( + T, + w, + v, + R, + y + ); + S(P), ne( + P, + i.current, + R, + y, + u, + c, + m + ); + }); + })(); + }, [d, i.current]), G(() => { + i.current && ne( + l, + i.current, + R, + y, + u, + c, + m, + E, + C + ); + }, [E, C]), /* @__PURE__ */ ke.jsx( + "canvas", + { + ref: i, + width: v, + height: w, + style: { + ...b + } + } + ); + } +); +Rr.displayName = "AudioVisualizer"; +export { + Rr as AudioVisualizer, + _r as LiveAudioVisualizer +}; diff --git a/node_modules/react-audio-visualize/dist/react-audio-visualize.umd.js b/node_modules/react-audio-visualize/dist/react-audio-visualize.umd.js new file mode 100644 index 0000000..725b0e5 --- /dev/null +++ b/node_modules/react-audio-visualize/dist/react-audio-visualize.umd.js @@ -0,0 +1,27 @@ +(function(V,T){typeof exports=="object"&&typeof module<"u"?T(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],T):(V=typeof globalThis<"u"?globalThis:V||self,T(V.AudioVisualize={},V.React))})(this,function(V,T){"use strict";var X={exports:{}},N={};/** + * @license React + * react-jsx-runtime.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var ie;function ke(){if(ie)return N;ie=1;var d=T,v=Symbol.for("react.element"),w=Symbol.for("react.fragment"),E=Object.prototype.hasOwnProperty,y=d.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,R={key:!0,ref:!0,__self:!0,__source:!0};function b(s,c,h){var a,i={},f=null,O=null;h!==void 0&&(f=""+h),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(O=c.ref);for(a in c)E.call(c,a)&&!R.hasOwnProperty(a)&&(i[a]=c[a]);if(s&&s.defaultProps)for(a in c=s.defaultProps,c)i[a]===void 0&&(i[a]=c[a]);return{$$typeof:v,type:s,key:f,ref:O,props:i,_owner:y.current}}return N.Fragment=w,N.jsx=b,N.jsxs=b,N}var W={};/** + * @license React + * react-jsx-runtime.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var oe;function Fe(){return oe||(oe=1,process.env.NODE_ENV!=="production"&&function(){var d=T,v=Symbol.for("react.element"),w=Symbol.for("react.portal"),E=Symbol.for("react.fragment"),y=Symbol.for("react.strict_mode"),R=Symbol.for("react.profiler"),b=Symbol.for("react.provider"),s=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),a=Symbol.for("react.suspense_list"),i=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),O=Symbol.for("react.offscreen"),P=Symbol.iterator,D="@@iterator";function k(e){if(e===null||typeof e!="object")return null;var r=P&&e[P]||e[D];return typeof r=="function"?r:null}var g=d.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function p(e){{for(var r=arguments.length,t=new Array(r>1?r-1:0),n=1;n=1&&x>=0&&o[_]!==C[x];)x--;for(;_>=1&&x>=0;_--,x--)if(o[_]!==C[x]){if(_!==1||x!==1)do if(_--,x--,x<0||o[_]!==C[x]){var A=` +`+o[_].replace(" at new "," at ");return e.displayName&&A.includes("")&&(A=A.replace("",e.displayName)),typeof e=="function"&&J.set(e,A),A}while(_>=1&&x>=0);break}}}finally{q=!1,Q.current=m,Ge(),Error.prepareStackTrace=l}var L=e?e.displayName||e.name:"",De=L?z(L):"";return typeof e=="function"&&J.set(e,De),De}function Ke(e,r,t){return Ee(e,!1)}function Xe(e){var r=e.prototype;return!!(r&&r.isReactComponent)}function G(e,r,t){if(e==null)return"";if(typeof e=="function")return Ee(e,Xe(e));if(typeof e=="string")return z(e);switch(e){case h:return z("Suspense");case a:return z("SuspenseList")}if(typeof e=="object")switch(e.$$typeof){case c:return Ke(e.render);case i:return G(e.type,r,t);case f:{var n=e,l=n._payload,m=n._init;try{return G(m(l),r,t)}catch{}}}return""}var H=Object.prototype.hasOwnProperty,Re={},_e=g.ReactDebugCurrentFrame;function K(e){if(e){var r=e._owner,t=G(e.type,e._source,r?r.type:null);_e.setExtraStackFrame(t)}else _e.setExtraStackFrame(null)}function Ze(e,r,t,n,l){{var m=Function.call.bind(H);for(var u in e)if(m(e,u)){var o=void 0;try{if(typeof e[u]!="function"){var C=Error((n||"React class")+": "+t+" type `"+u+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[u]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw C.name="Invariant Violation",C}o=e[u](r,u,n,t,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(_){o=_}o&&!(o instanceof Error)&&(K(l),p("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",n||"React class",t,u,typeof o),K(null)),o instanceof Error&&!(o.message in Re)&&(Re[o.message]=!0,K(l),p("Failed %s type: %s",t,o.message),K(null))}}}var Qe=Array.isArray;function ee(e){return Qe(e)}function $e(e){{var r=typeof Symbol=="function"&&Symbol.toStringTag,t=r&&e[Symbol.toStringTag]||e.constructor.name||"Object";return t}}function qe(e){try{return be(e),!1}catch{return!0}}function be(e){return""+e}function xe(e){if(qe(e))return p("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",$e(e)),be(e)}var U=g.ReactCurrentOwner,er={key:!0,ref:!0,__self:!0,__source:!0},Te,we,re;re={};function rr(e){if(H.call(e,"ref")){var r=Object.getOwnPropertyDescriptor(e,"ref").get;if(r&&r.isReactWarning)return!1}return e.ref!==void 0}function tr(e){if(H.call(e,"key")){var r=Object.getOwnPropertyDescriptor(e,"key").get;if(r&&r.isReactWarning)return!1}return e.key!==void 0}function nr(e,r){if(typeof e.ref=="string"&&U.current&&r&&U.current.stateNode!==r){var t=F(U.current.type);re[t]||(p('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref',F(U.current.type),e.ref),re[t]=!0)}}function ar(e,r){{var t=function(){Te||(Te=!0,p("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",r))};t.isReactWarning=!0,Object.defineProperty(e,"key",{get:t,configurable:!0})}}function ir(e,r){{var t=function(){we||(we=!0,p("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",r))};t.isReactWarning=!0,Object.defineProperty(e,"ref",{get:t,configurable:!0})}}var or=function(e,r,t,n,l,m,u){var o={$$typeof:v,type:e,key:r,ref:t,props:u,_owner:m};return o._store={},Object.defineProperty(o._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(o,"_self",{configurable:!1,enumerable:!1,writable:!1,value:n}),Object.defineProperty(o,"_source",{configurable:!1,enumerable:!1,writable:!1,value:l}),Object.freeze&&(Object.freeze(o.props),Object.freeze(o)),o};function sr(e,r,t,n,l){{var m,u={},o=null,C=null;t!==void 0&&(xe(t),o=""+t),tr(r)&&(xe(r.key),o=""+r.key),rr(r)&&(C=r.ref,nr(r,l));for(m in r)H.call(r,m)&&!er.hasOwnProperty(m)&&(u[m]=r[m]);if(e&&e.defaultProps){var _=e.defaultProps;for(m in _)u[m]===void 0&&(u[m]=_[m])}if(o||C){var x=typeof e=="function"?e.displayName||e.name||"Unknown":e;o&&ar(u,x),C&&ir(u,x)}return or(e,o,C,l,n,U.current,u)}}var te=g.ReactCurrentOwner,Se=g.ReactDebugCurrentFrame;function M(e){if(e){var r=e._owner,t=G(e.type,e._source,r?r.type:null);Se.setExtraStackFrame(t)}else Se.setExtraStackFrame(null)}var ne;ne=!1;function ae(e){return typeof e=="object"&&e!==null&&e.$$typeof===v}function Oe(){{if(te.current){var e=F(te.current.type);if(e)return` + +Check the render method of \``+e+"`."}return""}}function ur(e){{if(e!==void 0){var r=e.fileName.replace(/^.*[\\\/]/,""),t=e.lineNumber;return` + +Check your code at `+r+":"+t+"."}return""}}var Pe={};function cr(e){{var r=Oe();if(!r){var t=typeof e=="string"?e:e.displayName||e.name;t&&(r=` + +Check the top-level render call using <`+t+">.")}return r}}function Ce(e,r){{if(!e._store||e._store.validated||e.key!=null)return;e._store.validated=!0;var t=cr(r);if(Pe[t])return;Pe[t]=!0;var n="";e&&e._owner&&e._owner!==te.current&&(n=" It was passed a child from "+F(e._owner.type)+"."),M(e),p('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',t,n),M(null)}}function je(e,r){{if(typeof e!="object")return;if(ee(e))for(var t=0;t",o=" Did you accidentally export a JSX literal instead of a component?"):_=typeof e,p("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",_,o)}var x=sr(e,r,t,l,m);if(x==null)return x;if(u){var A=r.children;if(A!==void 0)if(n)if(ee(A)){for(var L=0;L{let y=v/(w+E),R=Math.floor(d.length/y);y>d.length&&(y=d.length,R=1);const b=[];for(let s=0;s{const b=v.height/2,s=v.getContext("2d");s&&(s.clearRect(0,0,v.width,v.height),y!=="transparent"&&(s.fillStyle=y,s.fillRect(0,0,v.width,v.height)),d.forEach((c,h)=>{s.fillStyle=R;const a=h*(w+E),i=b-c/2,f=w,O=c||1;s.beginPath(),s.roundRect?(s.roundRect(a,i,f,O,50),s.fill()):s.fillRect(a,i,f,O)}))},Ye=({mediaRecorder:d,width:v="100%",height:w="100%",barWidth:E=2,gap:y=1,backgroundColor:R="transparent",barColor:b="rgb(160, 198, 255)",fftSize:s=1024,maxDecibels:c=-10,minDecibels:h=-90,smoothingTimeConstant:a=.4})=>{const[i]=T.useState(()=>new AudioContext),[f,O]=T.useState(),P=T.useRef(null);T.useEffect(()=>{if(!d.stream)return;const g=i.createAnalyser();O(g),g.fftSize=s,g.minDecibels=h,g.maxDecibels=c,g.smoothingTimeConstant=a,i.createMediaStreamSource(d.stream).connect(g)},[d.stream]),T.useEffect(()=>{f&&d.state==="recording"&&D()},[f,d.state]);const D=T.useCallback(()=>{if(!f)return;const g=new Uint8Array(f==null?void 0:f.frequencyBinCount);d.state==="recording"?(f==null||f.getByteFrequencyData(g),k(g),requestAnimationFrame(D)):d.state==="paused"?k(g):d.state==="inactive"&&i.state!=="closed"&&i.close()},[f,i.state]),k=g=>{if(!P.current)return;const p=Ie(g,P.current.width,E,y);Ve(p,P.current,E,y,R,b)};return se.jsx("canvas",{ref:P,width:v,height:w,style:{aspectRatio:"unset"}})},Me=(d,v,w,E,y)=>{const R=d.getChannelData(0),b=w/(E+y),s=Math.floor(R.length/b),c=v/2;let h=[],a=0;for(let i=0;i0&&(P.push(j),D++)}const k=f.reduce((S,j)=>S+j,0)/O,p={max:P.reduce((S,j)=>S+j,0)/D,min:k};p.max>a&&(a=p.max),Math.abs(p.min)>a&&(a=Math.abs(p.min)),h.push(p)}if(c*.8>a*c){const i=c*.8/a;h=h.map(f=>({max:f.max*i,min:f.min*i}))}return h},Z=(d,v,w,E,y,R,b,s=0,c=1)=>{const h=v.height/2,a=v.getContext("2d");if(!a)return;a.clearRect(0,0,v.width,v.height),y!=="transparent"&&(a.fillStyle=y,a.fillRect(0,0,v.width,v.height));const i=(s||0)/c;d.forEach((f,O)=>{const P=O/d.length,D=i>P;a.fillStyle=D&&b?b:R;const k=O*(w+E),g=h+f.min,p=w,S=h+f.max-g;a.beginPath(),a.roundRect?(a.roundRect(k,g,p,S,50),a.fill()):a.fillRect(k,g,p,S)})},ue=T.forwardRef(({blob:d,width:v,height:w,barWidth:E=2,gap:y=1,currentTime:R,style:b,backgroundColor:s="transparent",barColor:c="rgb(184, 184, 184)",barPlayedColor:h="rgb(160, 198, 255)"},a)=>{const i=T.useRef(null),[f,O]=T.useState([]),[P,D]=T.useState(0);return T.useImperativeHandle(a,()=>i.current,[]),T.useEffect(()=>{(async()=>{if(!i.current)return;if(!d){const S=Array.from({length:100},()=>({max:0,min:0}));Z(S,i.current,E,y,s,c,h);return}const g=await d.arrayBuffer();await new AudioContext().decodeAudioData(g,S=>{if(!i.current)return;D(S.duration);const j=Me(S,w,v,E,y);O(j),Z(j,i.current,E,y,s,c,h)})})()},[d,i.current]),T.useEffect(()=>{i.current&&Z(f,i.current,E,y,s,c,h,R,P)},[R,P]),se.jsx("canvas",{ref:i,width:v,height:w,style:{...b}})});ue.displayName="AudioVisualizer",V.AudioVisualizer=ue,V.LiveAudioVisualizer=Ye,Object.defineProperty(V,Symbol.toStringTag,{value:"Module"})}); diff --git a/node_modules/react-audio-visualize/package.json b/node_modules/react-audio-visualize/package.json new file mode 100644 index 0000000..73d831f --- /dev/null +++ b/node_modules/react-audio-visualize/package.json @@ -0,0 +1,72 @@ +{ + "name": "react-audio-visualize", + "private": false, + "version": "1.1.3", + "license": "MIT", + "author": "", + "repository": { + "type": "git", + "url": "https://github.com/samhirtarif/react-audio-visualize.git" + }, + "keywords": [ + "audio", + "visualize", + "visualise", + "visualizer", + "visualiser", + "audio visualiser", + "audio visualizer", + "audio visualize", + "audio visualise", + "audio waveform", + "waveform", + "audio visualization", + "visualization", + "live visualize" + ], + "files": [ + "dist" + ], + "main": "./dist/react-audio-visualize.umd.js", + "module": "./dist/react-audio-visualize.es.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "import": "./dist/react-audio-visualize.es.js", + "require": "./dist/react-audio-visualize.umd.js" + } + }, + "scripts": { + "dev": "vite", + "build": "tsc && vite build", + "preview": "vite preview", + "lint": "eslint src/**/*.ts{,x}", + "lint:fix": "npm run lint -- --fix" + }, + "devDependencies": { + "@types/node": "^20.2.1", + "@types/react": "^18.0.28", + "@types/react-dom": "^18.0.11", + "@typescript-eslint/eslint-plugin": "^5.57.1", + "@typescript-eslint/parser": "^5.57.1", + "@vitejs/plugin-react": "^4.0.0", + "eslint": "^8.38.0", + "eslint-config-prettier": "^8.8.0", + "eslint-config-standard-with-typescript": "^34.0.1", + "eslint-plugin-prettier": "^4.2.1", + "eslint-plugin-react": "^7.32.2", + "eslint-plugin-react-hooks": "^4.6.0", + "eslint-plugin-react-refresh": "^0.3.4", + "path": "^0.12.7", + "prettier": "^2.8.8", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "typescript": "^5.0.2", + "vite": "^4.3.9", + "vite-plugin-dts": "^2.3.0" + }, + "peerDependencies": { + "react": ">=16.2.0", + "react-dom": ">=16.2.0" + } +} diff --git a/node_modules/react-audio-voice-recorder/README.md b/node_modules/react-audio-voice-recorder/README.md new file mode 100644 index 0000000..95d69d2 --- /dev/null +++ b/node_modules/react-audio-voice-recorder/README.md @@ -0,0 +1,152 @@ + +# **react-audio-voice-recorder** +An audio recording helper for React. Provides a component and a hook to help with audio recording. + +[![NPM downloads][npm-download-img]][npm-download-url] +[![Run ESlint][eslint-img]][eslint-url] +[![Run Unit tests][test-img]][test-url] + +[npm-download-img]: https://img.shields.io/npm/dm/react-audio-voice-recorder.svg?style=round-square +[npm-download-url]: https://www.npmjs.com/package/react-audio-voice-recorder +[eslint-img]: https://github.com/samhirtarif/react-audio-recorder/actions/workflows/lint.yml/badge.svg +[eslint-url]: https://github.com/samhirtarif/react-audio-recorder/actions/workflows/lint.yml +[test-img]: https://github.com/samhirtarif/react-audio-recorder/actions/workflows/test.yml/badge.svg +[test-url]: https://github.com/samhirtarif/react-audio-recorder/actions/workflows/test.yml + +## Installation +```sh +npm install react-audio-voice-recorder +``` + +```sh +yarn add react-audio-voice-recorder +``` + +## Migrating from v1 → v2 +### Breaking changes +- In v2 the `AudioRecorder` prop `downloadFileExtension` no longer supports `mp3` and `wav` without the website using this package being [cross-origin isolated](https://web.dev/cross-origin-isolation-guide/). This change was made in order to fix [issue #54](https://github.com/samhirtarif/react-audio-recorder/issues/54) in v1.2.1 + +## Usage + +### **AudioRecorder** Component ([See it in action](https://stackblitz.com/edit/react-ts-cc5l47?file=App.tsx)) + +You can use an out-of-the-box component that takes `onRecordingComplete` method as a prop and calls it when you save the recording + +```js +import React from "react"; +import ReactDOM from "react-dom/client"; +import { AudioRecorder } from 'react-audio-voice-recorder'; + +const addAudioElement = (blob) => { + const url = URL.createObjectURL(blob); + const audio = document.createElement("audio"); + audio.src = url; + audio.controls = true; + document.body.appendChild(audio); +}; + +ReactDOM.createRoot(document.getElementById("root")).render( + + + +); +``` + +| Props | Description | Default | Optional | +| :------------ |:--------------- |:--------------- | :--------------- | +| **`onRecordingComplete`** | A method that gets called when "Save recording" option is pressed | N/A | Yes | +| **`audioTrackConstraints`** | Takes a [subset](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackSettings#instance_properties_of_audio_tracks) of `MediaTrackConstraints` that apply to the audio track | N/A | Yes +| **`onNotAllowedOrFound`** | This gets called when the `getUserMedia` promise is rejected. It takes the resultant `DOMException` as its parameter | N/A | Yes +| **`downloadOnSavePress`** | A `boolean` value that determines if the recording should be downloaded when "Save recording" option is pressed | `false` | Yes | +| **`downloadFileExtension`** | The file extension to be used for the downloaded file. Allowed values are `webm`, `mp3` and `wav`. In order to use `mp3` or `wav` please ensure that your website is [cross-origin isolated](https://web.dev/cross-origin-isolation-guide/). [Further reading](https://web.dev/coop-coep/) | `webm` | Yes | +| **`showVisualizer`** | Displays a waveform visualization for the audio when set to `true` | `false` | Yes | +| **`classes`** | This allows class names to be passed to modify the styles for the entire component or specific portions of it | N/A | Yes | + +**NOTE: In order for `mp3` and `wav` downloading to work properly, your website needs to be [cross-origin isolated](https://web.dev/cross-origin-isolation-guide/). This is necessary because this package uses [FFmpeg](https://www.npmjs.com/package/@ffmpeg/ffmpeg) which internally uses `SharedArrayBuffer` that requires cross-origin isolation** + +--- +### **useAudioRecorder** hook + +If you prefer to build up your own UI but take advantage of the implementation provided by this package, you can use this hook instead of the component + +| Params | Description | Optional | +| :------------ |:---------------|:---------------| +| **`audioTrackConstraints`** | Takes a [subset](https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackSettings#instance_properties_of_audio_tracks) of `MediaTrackConstraints` that apply to the audio track | Yes | +| **`onNotAllowedOrFound`** | This gets called when the `getUserMedia` promise is rejected. It takes the resultant `DOMException` as its parameter | Yes | + +The hook returns the following: + +| Identifiers | Description | +| :------------ |:---------------| +| **`startRecording`** | Invoking this method starts the recording. Sets `isRecording` to `true` | +| **`stopRecording`** | Invoking this method stops the recording in progress and the resulting audio is made available in `recordingBlob`. Sets `isRecording` to `false` | +| **`togglePauseResume`** | Invoking this method would pause the recording if it is currently running or resume if it is paused. Toggles the value `isPaused` | +| **`recordingBlob`** | This is the recording blob that is created after `stopRecording` has been called | +| **`isRecording`** | A boolean value that represents whether a recording is currently in progress | +| **`isPaused`** | A boolean value that represents whether a recording in progress is paused | +| **`recordingTime`** | Number of seconds that the recording has gone on. This is updated every second | +| **`mediaRecorder`** | The current mediaRecorder in use. Can be undefined in case recording is not in progress | + +### Sample usage of hook + +```js + import { useAudioRecorder } from 'react-audio-voice-recorder'; + // ... + // ... + const { + startRecording, + stopRecording, + togglePauseResume, + recordingBlob, + isRecording, + isPaused, + recordingTime, + mediaRecorder + } = useAudioRecorder(); + + useEffect(() => { + if (!recordingBlob) return; + + // recordingBlob will be present at this point after 'stopRecording' has been called + }, [recordingBlob]) +``` +--- +### Combine the **`useAudioRecorder`** hook and the **`AudioRecorder`** component +This is for scenarios where you would wish to control the `AudioRecorder` component from outside the component. You can call the `useAudioRecorder` and pass the object it returns to the **`recorderControls`** of the `AudioRecorder`. This would enable you to control the `AudioRecorder` component from outside the component as well + +#### Sample usage ([See it in action](https://stackblitz.com/edit/react-ts-ryj6jz?file=App.tsx)) + +```js +import { AudioRecorder, useAudioRecorder } from 'react-audio-voice-recorder'; + +const ExampleComponent = () => { + const recorderControls = useAudioRecorder() + const addAudioElement = (blob) => { + const url = URL.createObjectURL(blob); + const audio = document.createElement("audio"); + audio.src = url; + audio.controls = true; + document.body.appendChild(audio); + }; + + return ( +
+ addAudioElement(blob)} + recorderControls={recorderControls} + /> + +
+ ) +} +``` + +**NOTE: When using both `AudioRecorder` and `useAudioRecorder` in combination, the `audioTrackConstraints` and `onNotAllowedOrFound` should be provided in the `useAudioRecorder` hook** diff --git a/node_modules/react-audio-voice-recorder/dist/components/AudioRecordingComponent.d.ts b/node_modules/react-audio-voice-recorder/dist/components/AudioRecordingComponent.d.ts new file mode 100644 index 0000000..c563e51 --- /dev/null +++ b/node_modules/react-audio-voice-recorder/dist/components/AudioRecordingComponent.d.ts @@ -0,0 +1,18 @@ +import { ReactElement } from "react"; +import { Props } from "./interfaces"; +/** + * Usage: https://github.com/samhirtarif/react-audio-recorder#audiorecorder-component + * + * + * @prop `onRecordingComplete` Method that gets called when save recording option is clicked + * @prop `recorderControls` Externally initilize hook and pass the returned object to this param, this gives your control over the component from outside the component. + * https://github.com/samhirtarif/react-audio-recorder#combine-the-useaudiorecorder-hook-and-the-audiorecorder-component + * @prop `audioTrackConstraints`: Takes a {@link https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackSettings#instance_properties_of_audio_tracks subset} of `MediaTrackConstraints` that apply to the audio track + * @prop `onNotAllowedOrFound`: A method that gets called when the getUserMedia promise is rejected. It receives the DOMException as its input. + * @prop `downloadOnSavePress` If set to `true` the file gets downloaded when save recording is pressed. Defaults to `false` + * @prop `downloadFileExtension` File extension for the audio filed that gets downloaded. Defaults to `mp3`. Allowed values are `mp3`, `wav` and `webm` + * @prop `showVisualizer` Displays a waveform visualization for the audio when set to `true`. Defaults to `false` + * @prop `classes` Is an object with attributes representing classes for different parts of the component + */ +declare const AudioRecorder: (props: Props) => ReactElement; +export default AudioRecorder; diff --git a/node_modules/react-audio-voice-recorder/dist/components/interfaces.d.ts b/node_modules/react-audio-voice-recorder/dist/components/interfaces.d.ts new file mode 100644 index 0000000..100e52c --- /dev/null +++ b/node_modules/react-audio-voice-recorder/dist/components/interfaces.d.ts @@ -0,0 +1,80 @@ +import { MediaAudioTrackConstraints, recorderControls } from "../hooks/useAudioRecorder"; +interface StyleProps { + /** + * Applies passed classes to audio recorder container + **/ + AudioRecorderClass?: string; + /** + * Applies passed classes to audio recorder start/save option + **/ + AudioRecorderStartSaveClass?: string; + /** + * Applies passed classes to audio recorder timer + **/ + AudioRecorderTimerClass?: string; + /** + * Applies passed classes to audio recorder status option + **/ + AudioRecorderStatusClass?: string; + /** + * Applies passed classes to audio recorder pause/resume option + **/ + AudioRecorderPauseResumeClass?: string; + /** + * Applies passed classes to audio recorder discard option + **/ + AudioRecorderDiscardClass?: string; +} +export interface Props { + /** + * This gets called when the save button is clicked. + * In case the recording is cancelled, the blob is discarded. + **/ + onRecordingComplete?: (blob: Blob) => void; + /** + * This gets called when the getUserMedia Promise is rejected. + * It takes the resultant DOMException as its parameter. + **/ + onNotAllowedOrFound?: (exception: DOMException) => any; + /** + * Allows calling of hook outside this component. The controls returned by the hook can then be passed to the component using this prop. + * This allows for use of hook methods and state outside this component + * @sample_usage https://github.com/samhirtarif/react-audio-recorder#combine-the-useaudiorecorder-hook-and-the-audiorecorder-component + **/ + recorderControls?: recorderControls; + /** + * Takes a {@link https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackSettings#instance_properties_of_audio_tracks subset} of + * `MediaTrackConstraints` that apply to the audio track + * + * @Property `deviceId` + * @Property `groupId` + * @Property `autoGainControl` + * @Property `channelCount` + * @Property `echoCancellation` + * @Property `noiseSuppression` + * @Property `sampleRate` + * @Property `sampleSize` + */ + audioTrackConstraints?: MediaAudioTrackConstraints; + /** + * If set to `true` the file gets downloaded when save recording is pressed + **/ + downloadOnSavePress?: boolean; + /** + * File extension for the audio filed that gets downloaded + **/ + downloadFileExtension?: "mp3" | "wav" | "webm"; + /** + * Displays a waveform visualization for the audio when set to `true`. Defaults to `false` + **/ + showVisualizer?: boolean; + /** + * The options passed to the HTML MediaRecorder API. + **/ + mediaRecorderOptions?: MediaRecorderOptions; + /** + * Custom classes to changes styles. + **/ + classes?: StyleProps; +} +export {}; diff --git a/node_modules/react-audio-voice-recorder/dist/hooks/useAudioRecorder.d.ts b/node_modules/react-audio-voice-recorder/dist/hooks/useAudioRecorder.d.ts new file mode 100644 index 0000000..326cdd6 --- /dev/null +++ b/node_modules/react-audio-voice-recorder/dist/hooks/useAudioRecorder.d.ts @@ -0,0 +1,28 @@ +export interface recorderControls { + startRecording: () => void; + stopRecording: () => void; + togglePauseResume: () => void; + recordingBlob?: Blob; + isRecording: boolean; + isPaused: boolean; + recordingTime: number; + mediaRecorder?: MediaRecorder; +} +export declare type MediaAudioTrackConstraints = Pick; +/** + * @returns Controls for the recording. Details of returned controls are given below + * + * @param `audioTrackConstraints`: Takes a {@link https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackSettings#instance_properties_of_audio_tracks subset} of `MediaTrackConstraints` that apply to the audio track + * @param `onNotAllowedOrFound`: A method that gets called when the getUserMedia promise is rejected. It receives the DOMException as its input. + * + * @details `startRecording`: Calling this method would result in the recording to start. Sets `isRecording` to true + * @details `stopRecording`: This results in a recording in progress being stopped and the resulting audio being present in `recordingBlob`. Sets `isRecording` to false + * @details `togglePauseResume`: Calling this method would pause the recording if it is currently running or resume if it is paused. Toggles the value `isPaused` + * @details `recordingBlob`: This is the recording blob that is created after `stopRecording` has been called + * @details `isRecording`: A boolean value that represents whether a recording is currently in progress + * @details `isPaused`: A boolean value that represents whether a recording in progress is paused + * @details `recordingTime`: Number of seconds that the recording has gone on. This is updated every second + * @details `mediaRecorder`: The current mediaRecorder in use + */ +declare const useAudioRecorder: (audioTrackConstraints?: MediaAudioTrackConstraints, onNotAllowedOrFound?: (exception: DOMException) => any, mediaRecorderOptions?: MediaRecorderOptions) => recorderControls; +export default useAudioRecorder; diff --git a/node_modules/react-audio-voice-recorder/dist/index-1c988149.js b/node_modules/react-audio-voice-recorder/dist/index-1c988149.js new file mode 100644 index 0000000..933d1ec --- /dev/null +++ b/node_modules/react-audio-voice-recorder/dist/index-1c988149.js @@ -0,0 +1,802 @@ +function re(o, f) { + for (var s = 0; s < f.length; s++) { + const p = f[s]; + if (typeof p != "string" && !Array.isArray(p)) { + for (const c in p) + if (c !== "default" && !(c in o)) { + const l = Object.getOwnPropertyDescriptor(p, c); + l && Object.defineProperty(o, c, l.get ? l : { + enumerable: !0, + get: () => p[c] + }); + } + } + } + return Object.freeze(Object.defineProperty(o, Symbol.toStringTag, { value: "Module" })); +} +function oe(o) { + return o && o.__esModule && Object.prototype.hasOwnProperty.call(o, "default") ? o.default : o; +} +function ne(o) { + if (o.__esModule) + return o; + var f = o.default; + if (typeof f == "function") { + var s = function p() { + if (this instanceof p) { + var c = [null]; + c.push.apply(c, arguments); + var l = Function.bind.apply(f, c); + return new l(); + } + return f.apply(this, arguments); + }; + s.prototype = f.prototype; + } else + s = {}; + return Object.defineProperty(s, "__esModule", { value: !0 }), Object.keys(o).forEach(function(p) { + var c = Object.getOwnPropertyDescriptor(o, p); + Object.defineProperty(s, p, c.get ? c : { + enumerable: !0, + get: function() { + return o[p]; + } + }); + }), s; +} +var ie = { exports: {} }; +(function(o) { + var f = function(s) { + var p = Object.prototype, c = p.hasOwnProperty, l, j = typeof Symbol == "function" ? Symbol : {}, y = j.iterator || "@@iterator", m = j.asyncIterator || "@@asyncIterator", v = j.toStringTag || "@@toStringTag"; + function w(t, e, r) { + return Object.defineProperty(t, e, { + value: r, + enumerable: !0, + configurable: !0, + writable: !0 + }), t[e]; + } + try { + w({}, ""); + } catch { + w = function(e, r, i) { + return e[r] = i; + }; + } + function C(t, e, r, i) { + var n = e && e.prototype instanceof O ? e : O, d = Object.create(n.prototype), b = new u(i || []); + return d._invoke = V(t, r, b), d; + } + s.wrap = C; + function N(t, e, r) { + try { + return { type: "normal", arg: t.call(e, r) }; + } catch (i) { + return { type: "throw", arg: i }; + } + } + var _ = "suspendedStart", G = "suspendedYield", U = "executing", P = "completed", L = {}; + function O() { + } + function T() { + } + function k() { + } + var D = {}; + w(D, y, function() { + return this; + }); + var B = Object.getPrototypeOf, M = B && B(B(h([]))); + M && M !== p && c.call(M, y) && (D = M); + var $ = k.prototype = O.prototype = Object.create(D); + T.prototype = k, w($, "constructor", k), w(k, "constructor", T), T.displayName = w( + k, + v, + "GeneratorFunction" + ); + function Y(t) { + ["next", "throw", "return"].forEach(function(e) { + w(t, e, function(r) { + return this._invoke(e, r); + }); + }); + } + s.isGeneratorFunction = function(t) { + var e = typeof t == "function" && t.constructor; + return e ? e === T || // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (e.displayName || e.name) === "GeneratorFunction" : !1; + }, s.mark = function(t) { + return Object.setPrototypeOf ? Object.setPrototypeOf(t, k) : (t.__proto__ = k, w(t, v, "GeneratorFunction")), t.prototype = Object.create($), t; + }, s.awrap = function(t) { + return { __await: t }; + }; + function I(t, e) { + function r(d, b, F, S) { + var E = N(t[d], t, b); + if (E.type === "throw") + S(E.arg); + else { + var H = E.arg, z = H.value; + return z && typeof z == "object" && c.call(z, "__await") ? e.resolve(z.__await).then(function(R) { + r("next", R, F, S); + }, function(R) { + r("throw", R, F, S); + }) : e.resolve(z).then(function(R) { + H.value = R, F(H); + }, function(R) { + return r("throw", R, F, S); + }); + } + } + var i; + function n(d, b) { + function F() { + return new e(function(S, E) { + r(d, b, S, E); + }); + } + return i = // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + i ? i.then( + F, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + F + ) : F(); + } + this._invoke = n; + } + Y(I.prototype), w(I.prototype, m, function() { + return this; + }), s.AsyncIterator = I, s.async = function(t, e, r, i, n) { + n === void 0 && (n = Promise); + var d = new I( + C(t, e, r, i), + n + ); + return s.isGeneratorFunction(e) ? d : d.next().then(function(b) { + return b.done ? b.value : d.next(); + }); + }; + function V(t, e, r) { + var i = _; + return function(d, b) { + if (i === U) + throw new Error("Generator is already running"); + if (i === P) { + if (d === "throw") + throw b; + return g(); + } + for (r.method = d, r.arg = b; ; ) { + var F = r.delegate; + if (F) { + var S = q(F, r); + if (S) { + if (S === L) + continue; + return S; + } + } + if (r.method === "next") + r.sent = r._sent = r.arg; + else if (r.method === "throw") { + if (i === _) + throw i = P, r.arg; + r.dispatchException(r.arg); + } else + r.method === "return" && r.abrupt("return", r.arg); + i = U; + var E = N(t, e, r); + if (E.type === "normal") { + if (i = r.done ? P : G, E.arg === L) + continue; + return { + value: E.arg, + done: r.done + }; + } else + E.type === "throw" && (i = P, r.method = "throw", r.arg = E.arg); + } + }; + } + function q(t, e) { + var r = t.iterator[e.method]; + if (r === l) { + if (e.delegate = null, e.method === "throw") { + if (t.iterator.return && (e.method = "return", e.arg = l, q(t, e), e.method === "throw")) + return L; + e.method = "throw", e.arg = new TypeError( + "The iterator does not provide a 'throw' method" + ); + } + return L; + } + var i = N(r, t.iterator, e.arg); + if (i.type === "throw") + return e.method = "throw", e.arg = i.arg, e.delegate = null, L; + var n = i.arg; + if (!n) + return e.method = "throw", e.arg = new TypeError("iterator result is not an object"), e.delegate = null, L; + if (n.done) + e[t.resultName] = n.value, e.next = t.nextLoc, e.method !== "return" && (e.method = "next", e.arg = l); + else + return n; + return e.delegate = null, L; + } + Y($), w($, v, "Generator"), w($, y, function() { + return this; + }), w($, "toString", function() { + return "[object Generator]"; + }); + function x(t) { + var e = { tryLoc: t[0] }; + 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); + } + function a(t) { + var e = t.completion || {}; + e.type = "normal", delete e.arg, t.completion = e; + } + function u(t) { + this.tryEntries = [{ tryLoc: "root" }], t.forEach(x, this), this.reset(!0); + } + s.keys = function(t) { + var e = []; + for (var r in t) + e.push(r); + return e.reverse(), function i() { + for (; e.length; ) { + var n = e.pop(); + if (n in t) + return i.value = n, i.done = !1, i; + } + return i.done = !0, i; + }; + }; + function h(t) { + if (t) { + var e = t[y]; + if (e) + return e.call(t); + if (typeof t.next == "function") + return t; + if (!isNaN(t.length)) { + var r = -1, i = function n() { + for (; ++r < t.length; ) + if (c.call(t, r)) + return n.value = t[r], n.done = !1, n; + return n.value = l, n.done = !0, n; + }; + return i.next = i; + } + } + return { next: g }; + } + s.values = h; + function g() { + return { value: l, done: !0 }; + } + return u.prototype = { + constructor: u, + reset: function(t) { + if (this.prev = 0, this.next = 0, this.sent = this._sent = l, this.done = !1, this.delegate = null, this.method = "next", this.arg = l, this.tryEntries.forEach(a), !t) + for (var e in this) + e.charAt(0) === "t" && c.call(this, e) && !isNaN(+e.slice(1)) && (this[e] = l); + }, + stop: function() { + this.done = !0; + var t = this.tryEntries[0], e = t.completion; + if (e.type === "throw") + throw e.arg; + return this.rval; + }, + dispatchException: function(t) { + if (this.done) + throw t; + var e = this; + function r(S, E) { + return d.type = "throw", d.arg = t, e.next = S, E && (e.method = "next", e.arg = l), !!E; + } + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var n = this.tryEntries[i], d = n.completion; + if (n.tryLoc === "root") + return r("end"); + if (n.tryLoc <= this.prev) { + var b = c.call(n, "catchLoc"), F = c.call(n, "finallyLoc"); + if (b && F) { + if (this.prev < n.catchLoc) + return r(n.catchLoc, !0); + if (this.prev < n.finallyLoc) + return r(n.finallyLoc); + } else if (b) { + if (this.prev < n.catchLoc) + return r(n.catchLoc, !0); + } else if (F) { + if (this.prev < n.finallyLoc) + return r(n.finallyLoc); + } else + throw new Error("try statement without catch or finally"); + } + } + }, + abrupt: function(t, e) { + for (var r = this.tryEntries.length - 1; r >= 0; --r) { + var i = this.tryEntries[r]; + if (i.tryLoc <= this.prev && c.call(i, "finallyLoc") && this.prev < i.finallyLoc) { + var n = i; + break; + } + } + n && (t === "break" || t === "continue") && n.tryLoc <= e && e <= n.finallyLoc && (n = null); + var d = n ? n.completion : {}; + return d.type = t, d.arg = e, n ? (this.method = "next", this.next = n.finallyLoc, L) : this.complete(d); + }, + complete: function(t, e) { + if (t.type === "throw") + throw t.arg; + return t.type === "break" || t.type === "continue" ? this.next = t.arg : t.type === "return" ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : t.type === "normal" && e && (this.next = e), L; + }, + finish: function(t) { + for (var e = this.tryEntries.length - 1; e >= 0; --e) { + var r = this.tryEntries[e]; + if (r.finallyLoc === t) + return this.complete(r.completion, r.afterLoc), a(r), L; + } + }, + catch: function(t) { + for (var e = this.tryEntries.length - 1; e >= 0; --e) { + var r = this.tryEntries[e]; + if (r.tryLoc === t) { + var i = r.completion; + if (i.type === "throw") { + var n = i.arg; + a(r); + } + return n; + } + } + throw new Error("illegal catch attempt"); + }, + delegateYield: function(t, e, r) { + return this.delegate = { + iterator: h(t), + resultName: e, + nextLoc: r + }, this.method === "next" && (this.arg = l), L; + } + }, s; + }( + // If this script is executing as a CommonJS module, use module.exports + // as the regeneratorRuntime namespace. Otherwise create a new empty + // object. Either way, the resulting object will be used to initialize + // the regeneratorRuntime variable at the top of this file. + o.exports + ); + try { + regeneratorRuntime = f; + } catch { + typeof globalThis == "object" ? globalThis.regeneratorRuntime = f : Function("r", "regeneratorRuntime = r")(f); + } +})(ie); +var ae = { + defaultArgs: [ + /* args[0] is always the binary path */ + "./ffmpeg", + /* Disable interaction mode */ + "-nostdin", + /* Force to override output file */ + "-y" + ], + baseOptions: { + /* Flag to turn on/off log messages in console */ + log: !1, + /* + * Custom logger to get ffmpeg.wasm output messages. + * a sample logger looks like this: + * + * ``` + * logger = ({ type, message }) => { + * console.log(type, message); + * } + * ``` + * + * type can be one of following: + * + * info: internal workflow debug messages + * fferr: ffmpeg native stderr output + * ffout: ffmpeg native stdout output + */ + logger: () => { + }, + /* + * Progress handler to get current progress of ffmpeg command. + * a sample progress handler looks like this: + * + * ``` + * progress = ({ ratio }) => { + * console.log(ratio); + * } + * ``` + * + * ratio is a float number between 0 to 1. + */ + progress: () => { + }, + /* + * Path to find/download ffmpeg.wasm-core, + * this value should be overwriten by `defaultOptions` in + * each environment. + */ + corePath: "" + } +}, se = (o, f) => { + const s = o._malloc(f.length * Uint32Array.BYTES_PER_ELEMENT); + return f.forEach((p, c) => { + const l = o.lengthBytesUTF8(p) + 1, j = o._malloc(l); + o.stringToUTF8(p, j, l), o.setValue(s + Uint32Array.BYTES_PER_ELEMENT * c, j, "i32"); + }), [f.length, s]; +}; +const fe = "@ffmpeg/ffmpeg", ce = "0.11.6", le = "FFmpeg WebAssembly version", pe = "src/index.js", ue = "src/index.d.ts", he = { + example: "examples" +}, de = { + start: "node scripts/server.js", + "start:worker": "node scripts/worker-server.js", + build: "rimraf dist && webpack --config scripts/webpack.config.prod.js", + "build:worker": "rimraf dist && webpack --config scripts/webpack.config.worker.prod.js", + prepublishOnly: "npm run build", + lint: "eslint src", + wait: "rimraf dist && wait-on http://localhost:3000/dist/ffmpeg.dev.js", + test: "npm-run-all -p -r start test:all", + "test:all": "npm-run-all wait test:browser:ffmpeg test:node:all", + "test:node": "node node_modules/mocha/bin/_mocha --exit --bail --require ./scripts/test-helper.js", + "test:node:all": "npm run test:node -- ./tests/*.test.js", + "test:browser": "mocha-headless-chrome -a allow-file-access-from-files -a incognito -a no-sandbox -a disable-setuid-sandbox -a disable-logging -t 300000", + "test:browser:ffmpeg": "npm run test:browser -- -f ./tests/ffmpeg.test.html" +}, me = { + "./src/node/index.js": "./src/browser/index.js" +}, ge = { + type: "git", + url: "git+https://github.com/ffmpegwasm/ffmpeg.wasm.git" +}, we = [ + "ffmpeg", + "WebAssembly", + "video" +], ye = "Jerome Wu ", ve = "MIT", be = { + url: "https://github.com/ffmpegwasm/ffmpeg.wasm/issues" +}, Fe = { + node: ">=12.16.1" +}, Ee = "https://github.com/ffmpegwasm/ffmpeg.wasm#readme", je = { + "is-url": "^1.2.4", + "node-fetch": "^2.6.1", + "regenerator-runtime": "^0.13.7", + "resolve-url": "^0.2.1" +}, Le = { + "@babel/core": "^7.12.3", + "@babel/preset-env": "^7.12.1", + "@ffmpeg/core": "^0.11.0", + "@types/emscripten": "^1.39.4", + "babel-eslint": "^10.1.0", + "babel-loader": "^8.1.0", + chai: "^4.2.0", + cors: "^2.8.5", + eslint: "^7.12.1", + "eslint-config-airbnb-base": "^14.1.0", + "eslint-plugin-import": "^2.22.1", + express: "^4.17.1", + mocha: "^8.2.1", + "mocha-headless-chrome": "^2.0.3", + "npm-run-all": "^4.1.5", + "wait-on": "^5.3.0", + webpack: "^5.3.2", + "webpack-cli": "^4.1.0", + "webpack-dev-middleware": "^4.0.0" +}, Q = { + name: fe, + version: ce, + description: le, + main: pe, + types: ue, + directories: he, + scripts: de, + browser: me, + repository: ge, + keywords: we, + author: ye, + license: ve, + bugs: be, + engines: Fe, + homepage: Ee, + dependencies: je, + devDependencies: Le +}, Oe = typeof process < "u" && process.env.NODE_ENV === "development" ? new URL("/node_modules/@ffmpeg/core/dist/ffmpeg-core.js", self.location).href : `https://unpkg.com/@ffmpeg/core@${Q.devDependencies["@ffmpeg/core"].substring(1)}/dist/ffmpeg-core.js`, Se = { corePath: Oe }; +let Z = !1, X = () => { +}; +const _e = (o) => { + Z = o; +}, Pe = (o) => { + X = o; +}, ke = (o, f) => { + X({ type: o, message: f }), Z && console.log(`[${o}] ${f}`); +}; +var A = { + logging: Z, + setLogging: _e, + setCustomLogger: Pe, + log: ke +}; +const $e = (o) => ` +createFFmpegCore is not defined. ffmpeg.wasm is unable to find createFFmpegCore after loading ffmpeg-core.js from ${o}. Use another URL when calling createFFmpeg(): + +const ffmpeg = createFFmpeg({ + corePath: 'http://localhost:3000/ffmpeg-core.js', +}); +`; +var K = { + CREATE_FFMPEG_CORE_IS_NOT_DEFINED: $e +}; +const W = async (o, f) => { + A.log("info", `fetch ${o}`); + const s = await (await fetch(o)).arrayBuffer(); + A.log("info", `${o} file size = ${s.byteLength} bytes`); + const p = new Blob([s], { type: f }), c = URL.createObjectURL(p); + return A.log("info", `${o} blob URL = ${c}`), c; +}, Ce = async ({ + corePath: o, + workerPath: f, + wasmPath: s +}) => { + if (typeof WorkerGlobalScope < "u" && self instanceof WorkerGlobalScope) { + if (typeof o != "string") + throw Error("corePath should be a string!"); + const y = new URL(o, import.meta.url).href, m = await W( + y, + "application/javascript" + ), v = await W( + s !== void 0 ? s : y.replace("ffmpeg-core.js", "ffmpeg-core.wasm"), + "application/wasm" + ), w = await W( + f !== void 0 ? f : y.replace("ffmpeg-core.js", "ffmpeg-core.worker.js"), + "application/javascript" + ); + return typeof createFFmpegCore > "u" ? new Promise((C) => { + if (globalThis.importScripts(m), typeof createFFmpegCore > "u") + throw Error(K.CREATE_FFMPEG_CORE_IS_NOT_DEFINED(y)); + A.log("info", "ffmpeg-core.js script loaded"), C({ + createFFmpegCore, + corePath: m, + wasmPath: v, + workerPath: w + }); + }) : (A.log("info", "ffmpeg-core.js script is loaded already"), Promise.resolve({ + createFFmpegCore, + corePath: m, + wasmPath: v, + workerPath: w + })); + } + if (typeof o != "string") + throw Error("corePath should be a string!"); + const p = new URL(o, import.meta.url).href, c = await W( + p, + "application/javascript" + ), l = await W( + s !== void 0 ? s : p.replace("ffmpeg-core.js", "ffmpeg-core.wasm"), + "application/wasm" + ), j = await W( + f !== void 0 ? f : p.replace("ffmpeg-core.js", "ffmpeg-core.worker.js"), + "application/javascript" + ); + return typeof createFFmpegCore > "u" ? new Promise((y) => { + const m = document.createElement("script"), v = () => { + if (m.removeEventListener("load", v), typeof createFFmpegCore > "u") + throw Error(K.CREATE_FFMPEG_CORE_IS_NOT_DEFINED(p)); + A.log("info", "ffmpeg-core.js script loaded"), y({ + createFFmpegCore, + corePath: c, + wasmPath: l, + workerPath: j + }); + }; + m.src = c, m.type = "text/javascript", m.addEventListener("load", v), document.getElementsByTagName("head")[0].appendChild(m); + }) : (A.log("info", "ffmpeg-core.js script is loaded already"), Promise.resolve({ + createFFmpegCore, + corePath: c, + wasmPath: l, + workerPath: j + })); +}, Te = (o) => new Promise((f, s) => { + const p = new FileReader(); + p.onload = () => { + f(p.result); + }, p.onerror = ({ target: { error: { code: c } } }) => { + s(Error(`File could not be read! Code=${c}`)); + }, p.readAsArrayBuffer(o); +}), Re = async (o) => { + let f = o; + return typeof o > "u" ? new Uint8Array() : (typeof o == "string" ? /data:_data\/([a-zA-Z]*);base64,([^"]*)/.test(o) ? f = atob(o.split(",")[1]).split("").map((s) => s.charCodeAt(0)) : f = await (await fetch(new URL(o, import.meta.url).href)).arrayBuffer() : (o instanceof File || o instanceof Blob) && (f = await Te(o)), new Uint8Array(f)); +}, Ae = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + defaultOptions: Se, + fetchFile: Re, + getCreateFFmpegCore: Ce +}, Symbol.toStringTag, { value: "Module" })), ee = /* @__PURE__ */ ne(Ae), { defaultArgs: Ne, baseOptions: Ge } = ae, Ue = se, { defaultOptions: De, getCreateFFmpegCore: Me } = ee, { version: Ie } = Q, J = Error("ffmpeg.wasm is not ready, make sure you have completed load()."); +var We = (o = {}) => { + const { + log: f, + logger: s, + progress: p, + ...c + } = { + ...Ge, + ...De, + ...o + }; + let l = null, j = null, y = null, m = null, v = !1, w = () => { + }, C = f, N = p, _ = 0, G = 0, U = !1, P = 0; + const L = (a) => { + a === "FFMPEG_END" && y !== null && (y(), y = null, m = null, v = !1); + }, O = (a, u) => { + w({ type: a, message: u }), C && console.log(`[${a}] ${u}`); + }, T = (a) => { + const [u, h, g] = a.split(":"); + return parseFloat(u) * 60 * 60 + parseFloat(h) * 60 + parseFloat(g); + }, k = (a, u) => { + if (typeof a == "string") + if (a.startsWith(" Duration")) { + const h = a.split(", ")[0].split(": ")[1], g = T(h); + u({ duration: g, ratio: P }), (_ === 0 || _ > g) && (_ = g, U = !0); + } else if (U && a.startsWith(" Stream")) { + const h = a.match(/([\d.]+) fps/); + if (h) { + const g = parseFloat(h[1]); + G = _ * g; + } else + G = 0; + U = !1; + } else if (a.startsWith("frame") || a.startsWith("size")) { + const h = a.split("time=")[1].split(" ")[0], g = T(h), t = a.match(/frame=\s*(\d+)/); + if (G && t) { + const e = parseFloat(t[1]); + P = Math.min(e / G, 1); + } else + P = g / _; + u({ ratio: P, time: g }); + } else + a.startsWith("video:") && (u({ ratio: 1 }), _ = 0); + }, D = ({ type: a, message: u }) => { + O(a, u), k(u, N), L(u); + }, B = async () => { + if (O("info", "load ffmpeg-core"), l === null) { + O("info", "loading ffmpeg-core"); + const { + createFFmpegCore: a, + corePath: u, + workerPath: h, + wasmPath: g + } = await Me(c); + l = await a({ + /* + * Assign mainScriptUrlOrBlob fixes chrome extension web worker issue + * as there is no document.currentScript in the context of content_scripts + */ + mainScriptUrlOrBlob: u, + printErr: (t) => D({ type: "fferr", message: t }), + print: (t) => D({ type: "ffout", message: t }), + /* + * locateFile overrides paths of files that is loaded by main script (ffmpeg-core.js). + * It is critical for browser environment and we override both wasm and worker paths + * as we are using blob URL instead of original URL to avoid cross origin issues. + */ + locateFile: (t, e) => { + if (typeof window < "u" || typeof WorkerGlobalScope < "u") { + if (typeof g < "u" && t.endsWith("ffmpeg-core.wasm")) + return g; + if (typeof h < "u" && t.endsWith("ffmpeg-core.worker.js")) + return h; + } + return e + t; + } + }), j = l.cwrap(c.mainName || "proxy_main", "number", ["number", "number"]), O("info", "ffmpeg-core loaded"); + } else + throw Error("ffmpeg.wasm was loaded, you should not load it again, use ffmpeg.isLoaded() to check next time."); + }, M = () => l !== null, $ = (...a) => { + if (O("info", `run ffmpeg command: ${a.join(" ")}`), l === null) + throw J; + if (v) + throw Error("ffmpeg.wasm can only run one command at a time"); + return v = !0, new Promise((u, h) => { + const g = [...Ne, ...a].filter((t) => t.length !== 0); + y = u, m = h, j(...Ue(l, g)); + }); + }, Y = (a, ...u) => { + if (O("info", `run FS.${a} ${u.map((h) => typeof h == "string" ? h : `<${h.length} bytes binary file>`).join(" ")}`), l === null) + throw J; + { + let h = null; + try { + h = l.FS[a](...u); + } catch { + throw Error(a === "readdir" ? `ffmpeg.FS('readdir', '${u[0]}') error. Check if the path exists, ex: ffmpeg.FS('readdir', '/')` : a === "readFile" ? `ffmpeg.FS('readFile', '${u[0]}') error. Check if the path exists` : "Oops, something went wrong in FS operation."); + } + return h; + } + }, I = () => { + if (l === null) + throw J; + m && m("ffmpeg has exited"), v = !1; + try { + l.exit(1); + } catch (a) { + O(a.message), m && m(a); + } finally { + l = null, j = null, y = null, m = null; + } + }, V = (a) => { + N = a; + }, q = (a) => { + w = a; + }, x = (a) => { + C = a; + }; + return O("info", `use ffmpeg.wasm v${Ie}`), { + setProgress: V, + setLogger: q, + setLogging: x, + load: B, + isLoaded: M, + run: $, + exit: I, + FS: Y + }; +}; +const Be = We, { fetchFile: ze } = ee; +var te = { + /* + * Create ffmpeg instance. + * Each ffmpeg instance owns an isolated MEMFS and works + * independently. + * + * For example: + * + * ``` + * const ffmpeg = createFFmpeg({ + * log: true, + * logger: () => {}, + * progress: () => {}, + * corePath: '', + * }) + * ``` + * + * For the usage of these four arguments, check config.js + * + */ + createFFmpeg: Be, + /* + * Helper function for fetching files from various resource. + * Sometimes the video/audio file you want to process may located + * in a remote URL and somewhere in your local file system. + * + * This helper function helps you to fetch to file and return an + * Uint8Array variable for ffmpeg.wasm to consume. + * + */ + fetchFile: ze +}; +const Ye = /* @__PURE__ */ oe(te), qe = /* @__PURE__ */ re({ + __proto__: null, + default: Ye +}, [te]); +export { + qe as i +}; diff --git a/node_modules/react-audio-voice-recorder/dist/index.d.ts b/node_modules/react-audio-voice-recorder/dist/index.d.ts new file mode 100644 index 0000000..5cdf8ef --- /dev/null +++ b/node_modules/react-audio-voice-recorder/dist/index.d.ts @@ -0,0 +1,2 @@ +export { default as AudioRecorder } from "./components/AudioRecordingComponent"; +export { default as useAudioRecorder } from "./hooks/useAudioRecorder"; diff --git a/node_modules/react-audio-voice-recorder/dist/react-audio-visualize.es-69216c73.js b/node_modules/react-audio-voice-recorder/dist/react-audio-visualize.es-69216c73.js new file mode 100644 index 0000000..56ca9cb --- /dev/null +++ b/node_modules/react-audio-voice-recorder/dist/react-audio-visualize.es-69216c73.js @@ -0,0 +1,828 @@ +import Te, { useState as Y, useRef as De, useEffect as H, useCallback as fr, forwardRef as pr, useImperativeHandle as yr } from "react"; +var ne = { exports: {} }, z = {}; +/** + * @license React + * react-jsx-runtime.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var je; +function dr() { + if (je) + return z; + je = 1; + var y = Te, m = Symbol.for("react.element"), _ = Symbol.for("react.fragment"), b = Object.prototype.hasOwnProperty, h = y.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, w = { key: !0, ref: !0, __self: !0, __source: !0 }; + function k(i, s, g) { + var o, a = {}, d = null, E = null; + g !== void 0 && (d = "" + g), s.key !== void 0 && (d = "" + s.key), s.ref !== void 0 && (E = s.ref); + for (o in s) + b.call(s, o) && !w.hasOwnProperty(o) && (a[o] = s[o]); + if (i && i.defaultProps) + for (o in s = i.defaultProps, s) + a[o] === void 0 && (a[o] = s[o]); + return { $$typeof: m, type: i, key: d, ref: E, props: a, _owner: h.current }; + } + return z.Fragment = _, z.jsx = k, z.jsxs = k, z; +} +var q = {}; +/** + * @license React + * react-jsx-runtime.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var Pe; +function mr() { + return Pe || (Pe = 1, process.env.NODE_ENV !== "production" && function() { + var y = Te, m = Symbol.for("react.element"), _ = Symbol.for("react.portal"), b = Symbol.for("react.fragment"), h = Symbol.for("react.strict_mode"), w = Symbol.for("react.profiler"), k = Symbol.for("react.provider"), i = Symbol.for("react.context"), s = Symbol.for("react.forward_ref"), g = Symbol.for("react.suspense"), o = Symbol.for("react.suspense_list"), a = Symbol.for("react.memo"), d = Symbol.for("react.lazy"), E = Symbol.for("react.offscreen"), C = Symbol.iterator, T = "@@iterator"; + function D(e) { + if (e === null || typeof e != "object") + return null; + var r = C && e[C] || e[T]; + return typeof r == "function" ? r : null; + } + var l = y.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + function f(e) { + { + for (var r = arguments.length, t = new Array(r > 1 ? r - 1 : 0), n = 1; n < r; n++) + t[n - 1] = arguments[n]; + j("error", e, t); + } + } + function j(e, r, t) { + { + var n = l.ReactDebugCurrentFrame, p = n.getStackAddendum(); + p !== "" && (r += "%s", t = t.concat([p])); + var v = t.map(function(u) { + return String(u); + }); + v.unshift("Warning: " + r), Function.prototype.apply.call(console[e], console, v); + } + } + var xe = !1, Fe = !1, Ne = !1, Ae = !1, Ie = !1, oe; + oe = Symbol.for("react.module.reference"); + function Le(e) { + return !!(typeof e == "string" || typeof e == "function" || e === b || e === w || Ie || e === h || e === g || e === o || Ae || e === E || xe || Fe || Ne || typeof e == "object" && e !== null && (e.$$typeof === d || e.$$typeof === a || e.$$typeof === k || e.$$typeof === i || e.$$typeof === s || // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + e.$$typeof === oe || e.getModuleId !== void 0)); + } + function ze(e, r, t) { + var n = e.displayName; + if (n) + return n; + var p = r.displayName || r.name || ""; + return p !== "" ? t + "(" + p + ")" : t; + } + function ae(e) { + return e.displayName || "Context"; + } + function $(e) { + if (e == null) + return null; + if (typeof e.tag == "number" && f("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."), typeof e == "function") + return e.displayName || e.name || null; + if (typeof e == "string") + return e; + switch (e) { + case b: + return "Fragment"; + case _: + return "Portal"; + case w: + return "Profiler"; + case h: + return "StrictMode"; + case g: + return "Suspense"; + case o: + return "SuspenseList"; + } + if (typeof e == "object") + switch (e.$$typeof) { + case i: + var r = e; + return ae(r) + ".Consumer"; + case k: + var t = e; + return ae(t._context) + ".Provider"; + case s: + return ze(e, e.render, "ForwardRef"); + case a: + var n = e.displayName || null; + return n !== null ? n : $(e.type) || "Memo"; + case d: { + var p = e, v = p._payload, u = p._init; + try { + return $(u(v)); + } catch { + return null; + } + } + } + return null; + } + var F = Object.assign, I = 0, ie, ce, le, se, ue, fe, pe; + function ye() { + } + ye.__reactDisabledLog = !0; + function We() { + { + if (I === 0) { + ie = console.log, ce = console.info, le = console.warn, se = console.error, ue = console.group, fe = console.groupCollapsed, pe = console.groupEnd; + var e = { + configurable: !0, + enumerable: !0, + value: ye, + writable: !0 + }; + Object.defineProperties(console, { + info: e, + log: e, + warn: e, + error: e, + group: e, + groupCollapsed: e, + groupEnd: e + }); + } + I++; + } + } + function Me() { + { + if (I--, I === 0) { + var e = { + configurable: !0, + enumerable: !0, + writable: !0 + }; + Object.defineProperties(console, { + log: F({}, e, { + value: ie + }), + info: F({}, e, { + value: ce + }), + warn: F({}, e, { + value: le + }), + error: F({}, e, { + value: se + }), + group: F({}, e, { + value: ue + }), + groupCollapsed: F({}, e, { + value: fe + }), + groupEnd: F({}, e, { + value: pe + }) + }); + } + I < 0 && f("disabledDepth fell below zero. This is a bug in React. Please file an issue."); + } + } + var X = l.ReactCurrentDispatcher, J; + function W(e, r, t) { + { + if (J === void 0) + try { + throw Error(); + } catch (p) { + var n = p.stack.trim().match(/\n( *(at )?)/); + J = n && n[1] || ""; + } + return ` +` + J + e; + } + } + var K = !1, M; + { + var Ue = typeof WeakMap == "function" ? WeakMap : Map; + M = new Ue(); + } + function de(e, r) { + if (!e || K) + return ""; + { + var t = M.get(e); + if (t !== void 0) + return t; + } + var n; + K = !0; + var p = Error.prepareStackTrace; + Error.prepareStackTrace = void 0; + var v; + v = X.current, X.current = null, We(); + try { + if (r) { + var u = function() { + throw Error(); + }; + if (Object.defineProperty(u.prototype, "props", { + set: function() { + throw Error(); + } + }), typeof Reflect == "object" && Reflect.construct) { + try { + Reflect.construct(u, []); + } catch (x) { + n = x; + } + Reflect.construct(e, [], u); + } else { + try { + u.call(); + } catch (x) { + n = x; + } + e.call(u.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + n = x; + } + e(); + } + } catch (x) { + if (x && n && typeof x.stack == "string") { + for (var c = x.stack.split(` +`), O = n.stack.split(` +`), S = c.length - 1, R = O.length - 1; S >= 1 && R >= 0 && c[S] !== O[R]; ) + R--; + for (; S >= 1 && R >= 0; S--, R--) + if (c[S] !== O[R]) { + if (S !== 1 || R !== 1) + do + if (S--, R--, R < 0 || c[S] !== O[R]) { + var P = ` +` + c[S].replace(" at new ", " at "); + return e.displayName && P.includes("") && (P = P.replace("", e.displayName)), typeof e == "function" && M.set(e, P), P; + } + while (S >= 1 && R >= 0); + break; + } + } + } finally { + K = !1, X.current = v, Me(), Error.prepareStackTrace = p; + } + var A = e ? e.displayName || e.name : "", Oe = A ? W(A) : ""; + return typeof e == "function" && M.set(e, Oe), Oe; + } + function Be(e, r, t) { + return de(e, !1); + } + function Ve(e) { + var r = e.prototype; + return !!(r && r.isReactComponent); + } + function U(e, r, t) { + if (e == null) + return ""; + if (typeof e == "function") + return de(e, Ve(e)); + if (typeof e == "string") + return W(e); + switch (e) { + case g: + return W("Suspense"); + case o: + return W("SuspenseList"); + } + if (typeof e == "object") + switch (e.$$typeof) { + case s: + return Be(e.render); + case a: + return U(e.type, r, t); + case d: { + var n = e, p = n._payload, v = n._init; + try { + return U(v(p), r, t); + } catch { + } + } + } + return ""; + } + var B = Object.prototype.hasOwnProperty, me = {}, ge = l.ReactDebugCurrentFrame; + function V(e) { + if (e) { + var r = e._owner, t = U(e.type, e._source, r ? r.type : null); + ge.setExtraStackFrame(t); + } else + ge.setExtraStackFrame(null); + } + function qe(e, r, t, n, p) { + { + var v = Function.call.bind(B); + for (var u in e) + if (v(e, u)) { + var c = void 0; + try { + if (typeof e[u] != "function") { + var O = Error((n || "React class") + ": " + t + " type `" + u + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof e[u] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); + throw O.name = "Invariant Violation", O; + } + c = e[u](r, u, n, t, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); + } catch (S) { + c = S; + } + c && !(c instanceof Error) && (V(p), f("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", n || "React class", t, u, typeof c), V(null)), c instanceof Error && !(c.message in me) && (me[c.message] = !0, V(p), f("Failed %s type: %s", t, c.message), V(null)); + } + } + } + var Ye = Array.isArray; + function Q(e) { + return Ye(e); + } + function He(e) { + { + var r = typeof Symbol == "function" && Symbol.toStringTag, t = r && e[Symbol.toStringTag] || e.constructor.name || "Object"; + return t; + } + } + function Xe(e) { + try { + return ve(e), !1; + } catch { + return !0; + } + } + function ve(e) { + return "" + e; + } + function he(e) { + if (Xe(e)) + return f("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", He(e)), ve(e); + } + var L = l.ReactCurrentOwner, Je = { + key: !0, + ref: !0, + __self: !0, + __source: !0 + }, be, we, Z; + Z = {}; + function Ke(e) { + if (B.call(e, "ref")) { + var r = Object.getOwnPropertyDescriptor(e, "ref").get; + if (r && r.isReactWarning) + return !1; + } + return e.ref !== void 0; + } + function Qe(e) { + if (B.call(e, "key")) { + var r = Object.getOwnPropertyDescriptor(e, "key").get; + if (r && r.isReactWarning) + return !1; + } + return e.key !== void 0; + } + function Ze(e, r) { + if (typeof e.ref == "string" && L.current && r && L.current.stateNode !== r) { + var t = $(L.current.type); + Z[t] || (f('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', $(L.current.type), e.ref), Z[t] = !0); + } + } + function Ge(e, r) { + { + var t = function() { + be || (be = !0, f("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", r)); + }; + t.isReactWarning = !0, Object.defineProperty(e, "key", { + get: t, + configurable: !0 + }); + } + } + function er(e, r) { + { + var t = function() { + we || (we = !0, f("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", r)); + }; + t.isReactWarning = !0, Object.defineProperty(e, "ref", { + get: t, + configurable: !0 + }); + } + } + var rr = function(e, r, t, n, p, v, u) { + var c = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: m, + // Built-in properties that belong on the element + type: e, + key: r, + ref: t, + props: u, + // Record the component responsible for creating this element. + _owner: v + }; + return c._store = {}, Object.defineProperty(c._store, "validated", { + configurable: !1, + enumerable: !1, + writable: !0, + value: !1 + }), Object.defineProperty(c, "_self", { + configurable: !1, + enumerable: !1, + writable: !1, + value: n + }), Object.defineProperty(c, "_source", { + configurable: !1, + enumerable: !1, + writable: !1, + value: p + }), Object.freeze && (Object.freeze(c.props), Object.freeze(c)), c; + }; + function tr(e, r, t, n, p) { + { + var v, u = {}, c = null, O = null; + t !== void 0 && (he(t), c = "" + t), Qe(r) && (he(r.key), c = "" + r.key), Ke(r) && (O = r.ref, Ze(r, p)); + for (v in r) + B.call(r, v) && !Je.hasOwnProperty(v) && (u[v] = r[v]); + if (e && e.defaultProps) { + var S = e.defaultProps; + for (v in S) + u[v] === void 0 && (u[v] = S[v]); + } + if (c || O) { + var R = typeof e == "function" ? e.displayName || e.name || "Unknown" : e; + c && Ge(u, R), O && er(u, R); + } + return rr(e, c, O, p, n, L.current, u); + } + } + var G = l.ReactCurrentOwner, Se = l.ReactDebugCurrentFrame; + function N(e) { + if (e) { + var r = e._owner, t = U(e.type, e._source, r ? r.type : null); + Se.setExtraStackFrame(t); + } else + Se.setExtraStackFrame(null); + } + var ee; + ee = !1; + function re(e) { + return typeof e == "object" && e !== null && e.$$typeof === m; + } + function ke() { + { + if (G.current) { + var e = $(G.current.type); + if (e) + return ` + +Check the render method of \`` + e + "`."; + } + return ""; + } + } + function nr(e) { + { + if (e !== void 0) { + var r = e.fileName.replace(/^.*[\\\/]/, ""), t = e.lineNumber; + return ` + +Check your code at ` + r + ":" + t + "."; + } + return ""; + } + } + var Re = {}; + function or(e) { + { + var r = ke(); + if (!r) { + var t = typeof e == "string" ? e : e.displayName || e.name; + t && (r = ` + +Check the top-level render call using <` + t + ">."); + } + return r; + } + } + function _e(e, r) { + { + if (!e._store || e._store.validated || e.key != null) + return; + e._store.validated = !0; + var t = or(r); + if (Re[t]) + return; + Re[t] = !0; + var n = ""; + e && e._owner && e._owner !== G.current && (n = " It was passed a child from " + $(e._owner.type) + "."), N(e), f('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', t, n), N(null); + } + } + function Ee(e, r) { + { + if (typeof e != "object") + return; + if (Q(e)) + for (var t = 0; t < e.length; t++) { + var n = e[t]; + re(n) && _e(n, r); + } + else if (re(e)) + e._store && (e._store.validated = !0); + else if (e) { + var p = D(e); + if (typeof p == "function" && p !== e.entries) + for (var v = p.call(e), u; !(u = v.next()).done; ) + re(u.value) && _e(u.value, r); + } + } + } + function ar(e) { + { + var r = e.type; + if (r == null || typeof r == "string") + return; + var t; + if (typeof r == "function") + t = r.propTypes; + else if (typeof r == "object" && (r.$$typeof === s || // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + r.$$typeof === a)) + t = r.propTypes; + else + return; + if (t) { + var n = $(r); + qe(t, e.props, "prop", n, e); + } else if (r.PropTypes !== void 0 && !ee) { + ee = !0; + var p = $(r); + f("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", p || "Unknown"); + } + typeof r.getDefaultProps == "function" && !r.getDefaultProps.isReactClassApproved && f("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); + } + } + function ir(e) { + { + for (var r = Object.keys(e.props), t = 0; t < r.length; t++) { + var n = r[t]; + if (n !== "children" && n !== "key") { + N(e), f("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", n), N(null); + break; + } + } + e.ref !== null && (N(e), f("Invalid attribute `ref` supplied to `React.Fragment`."), N(null)); + } + } + function Ce(e, r, t, n, p, v) { + { + var u = Le(e); + if (!u) { + var c = ""; + (e === void 0 || typeof e == "object" && e !== null && Object.keys(e).length === 0) && (c += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."); + var O = nr(p); + O ? c += O : c += ke(); + var S; + e === null ? S = "null" : Q(e) ? S = "array" : e !== void 0 && e.$$typeof === m ? (S = "<" + ($(e.type) || "Unknown") + " />", c = " Did you accidentally export a JSX literal instead of a component?") : S = typeof e, f("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", S, c); + } + var R = tr(e, r, t, p, v); + if (R == null) + return R; + if (u) { + var P = r.children; + if (P !== void 0) + if (n) + if (Q(P)) { + for (var A = 0; A < P.length; A++) + Ee(P[A], e); + Object.freeze && Object.freeze(P); + } else + f("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."); + else + Ee(P, e); + } + return e === b ? ir(R) : ar(R), R; + } + } + function cr(e, r, t) { + return Ce(e, r, t, !0); + } + function lr(e, r, t) { + return Ce(e, r, t, !1); + } + var sr = lr, ur = cr; + q.Fragment = b, q.jsx = sr, q.jsxs = ur; + }()), q; +} +process.env.NODE_ENV === "production" ? ne.exports = dr() : ne.exports = mr(); +var $e = ne.exports; +const gr = (y, m, _, b) => { + let h = m / (_ + b), w = Math.floor(y.length / h); + h > y.length && (h = y.length, w = 1); + const k = []; + for (let i = 0; i < h; i++) { + let s = 0; + for (let g = 0; g < w && i * w + g < y.length; g++) + s += y[i * w + g]; + k.push(s / w); + } + return k; +}, vr = (y, m, _, b, h, w) => { + const k = m.height / 2, i = m.getContext("2d"); + i && (i.clearRect(0, 0, m.width, m.height), h !== "transparent" && (i.fillStyle = h, i.fillRect(0, 0, m.width, m.height)), y.forEach((s, g) => { + i.fillStyle = w; + const o = g * (_ + b), a = k - s / 2, d = _, E = s || 1; + i.beginPath(), i.roundRect ? (i.roundRect(o, a, d, E, 50), i.fill()) : i.fillRect(o, a, d, E); + })); +}, Sr = ({ + mediaRecorder: y, + width: m = "100%", + height: _ = "100%", + barWidth: b = 2, + gap: h = 1, + backgroundColor: w = "transparent", + barColor: k = "rgb(160, 198, 255)", + fftSize: i = 1024, + maxDecibels: s = -10, + minDecibels: g = -90, + smoothingTimeConstant: o = 0.4 +}) => { + const [a] = Y(() => new AudioContext()), [d, E] = Y(), C = De(null); + H(() => { + if (!y.stream) + return; + const l = a.createAnalyser(); + E(l), l.fftSize = i, l.minDecibels = g, l.maxDecibels = s, l.smoothingTimeConstant = o, a.createMediaStreamSource(y.stream).connect(l); + }, [y.stream]), H(() => { + d && y.state === "recording" && T(); + }, [d, y.state]); + const T = fr(() => { + if (!d) + return; + const l = new Uint8Array(d == null ? void 0 : d.frequencyBinCount); + y.state === "recording" ? (d == null || d.getByteFrequencyData(l), D(l), requestAnimationFrame(T)) : y.state === "paused" ? D(l) : y.state === "inactive" && a.state !== "closed" && a.close(); + }, [d, a.state]), D = (l) => { + if (!C.current) + return; + const f = gr( + l, + C.current.width, + b, + h + ); + vr( + f, + C.current, + b, + h, + w, + k + ); + }; + return /* @__PURE__ */ $e.jsx( + "canvas", + { + ref: C, + width: m, + height: _, + style: { + aspectRatio: "unset" + } + } + ); +}, hr = (y, m, _, b, h) => { + const w = y.getChannelData(0), k = _ / (b + h), i = Math.floor(w.length / k), s = m / 2; + let g = [], o = 0; + for (let a = 0; a < k; a++) { + const d = []; + let E = 0; + const C = []; + let T = 0; + for (let f = 0; f < i && a * i + f < y.length; f++) { + const j = w[a * i + f]; + j <= 0 && (d.push(j), E++), j > 0 && (C.push(j), T++); + } + const D = d.reduce((f, j) => f + j, 0) / E, l = { max: C.reduce((f, j) => f + j, 0) / T, min: D }; + l.max > o && (o = l.max), Math.abs(l.min) > o && (o = Math.abs(l.min)), g.push(l); + } + if (s * 0.8 > o * s) { + const a = s * 0.8 / o; + g = g.map((d) => ({ + max: d.max * a, + min: d.min * a + })); + } + return g; +}, te = (y, m, _, b, h, w, k, i = 0, s = 1) => { + const g = m.height / 2, o = m.getContext("2d"); + if (!o) + return; + o.clearRect(0, 0, m.width, m.height), h !== "transparent" && (o.fillStyle = h, o.fillRect(0, 0, m.width, m.height)); + const a = (i || 0) / s; + y.forEach((d, E) => { + const C = E / y.length, T = a > C; + o.fillStyle = T && k ? k : w; + const D = E * (_ + b), l = g + d.min, f = _, j = g + d.max - l; + o.beginPath(), o.roundRect ? (o.roundRect(D, l, f, j, 50), o.fill()) : o.fillRect(D, l, f, j); + }); +}, br = pr( + ({ + blob: y, + width: m, + height: _, + barWidth: b = 2, + gap: h = 1, + currentTime: w, + style: k, + backgroundColor: i = "transparent", + barColor: s = "rgb(184, 184, 184)", + barPlayedColor: g = "rgb(160, 198, 255)" + }, o) => { + const a = De(null), [d, E] = Y([]), [C, T] = Y(0); + return yr( + o, + () => a.current, + [] + ), H(() => { + (async () => { + if (!a.current) + return; + if (!y) { + const l = Array.from({ length: 100 }, () => ({ + max: 0, + min: 0 + })); + te( + l, + a.current, + b, + h, + i, + s, + g + ); + return; + } + const D = await y.arrayBuffer(); + await new AudioContext().decodeAudioData(D, (l) => { + if (!a.current) + return; + T(l.duration); + const f = hr( + l, + _, + m, + b, + h + ); + E(f), te( + f, + a.current, + b, + h, + i, + s, + g + ); + }); + })(); + }, [y, a.current]), H(() => { + a.current && te( + d, + a.current, + b, + h, + i, + s, + g, + w, + C + ); + }, [w, C]), /* @__PURE__ */ $e.jsx( + "canvas", + { + ref: a, + width: m, + height: _, + style: { + ...k + } + } + ); + } +); +br.displayName = "AudioVisualizer"; +export { + br as AudioVisualizer, + Sr as LiveAudioVisualizer +}; diff --git a/node_modules/react-audio-voice-recorder/dist/react-audio-voice-recorder.es.js b/node_modules/react-audio-voice-recorder/dist/react-audio-voice-recorder.es.js new file mode 100644 index 0000000..70d2528 --- /dev/null +++ b/node_modules/react-audio-voice-recorder/dist/react-audio-voice-recorder.es.js @@ -0,0 +1,817 @@ +(function(){"use strict";(r=>{try{if(typeof window>"u")return;var e=document.createElement("style");e.appendChild(document.createTextNode(r)),document.head.appendChild(e)}catch(i){console.error("vite-plugin-css-injected-by-js",i)}})(".audio-recorder{background-color:#ebebeb;box-shadow:0 2px 5px #bebebe;border-radius:20px;box-sizing:border-box;color:#000;width:40px;display:flex;align-items:center;transition:all .2s ease-in;-webkit-tap-highlight-color:transparent}.audio-recorder-mic{box-sizing:content-box;cursor:pointer;height:16px;color:#000;padding:12px}.audio-recorder .audio-recorder-mic{border-radius:20px}.audio-recorder.recording .audio-recorder-mic{border-radius:0}.audio-recorder-timer,.audio-recorder-status{color:#000;margin-left:10px;font-family:Segoe UI,Tahoma,Geneva,Verdana,sans-serif;font-size:14px;font-weight:400;line-height:1}.audio-recorder-status{margin-left:15px;display:flex;align-items:baseline;flex-grow:1;animation-name:fading-ar-status;animation-duration:2s;animation-iteration-count:infinite}.audio-recorder-status-dot{background-color:#d00;border-radius:50%;height:10px;width:9px;margin-right:5px}.audio-recorder-options{box-sizing:content-box;height:16px;cursor:pointer;padding:12px 6px 12px 12px}.audio-recorder-options~.audio-recorder-options{padding:12px 12px 12px 6px;border-radius:0 5px 5px 0}.recording{border-radius:12px;width:300px;transition:all .2s ease-out}.display-none{display:none}.audio-recorder-visualizer{margin-left:15px;flex-grow:1;align-self:center;display:flex;align-items:center}@keyframes fading-ar-status{0%{opacity:1}50%{opacity:0}to{opacity:1}}")})(); +import ge, { useState as B, useCallback as J, useEffect as cr, Suspense as lr } from "react"; +var de = { exports: {} }, H = {}; +/** + * @license React + * react-jsx-runtime.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var ke; +function fr() { + if (ke) + return H; + ke = 1; + var D = ge, j = Symbol.for("react.element"), z = Symbol.for("react.fragment"), E = Object.prototype.hasOwnProperty, I = D.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, C = { key: !0, ref: !0, __self: !0, __source: !0 }; + function y(T, i, c) { + var d, v = {}, M = null, m = null; + c !== void 0 && (M = "" + c), i.key !== void 0 && (M = "" + i.key), i.ref !== void 0 && (m = i.ref); + for (d in i) + E.call(i, d) && !C.hasOwnProperty(d) && (v[d] = i[d]); + if (T && T.defaultProps) + for (d in i = T.defaultProps, i) + v[d] === void 0 && (v[d] = i[d]); + return { $$typeof: j, type: T, key: M, ref: m, props: v, _owner: I.current }; + } + return H.Fragment = z, H.jsx = y, H.jsxs = y, H; +} +var $ = {}; +/** + * @license React + * react-jsx-runtime.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var _e; +function dr() { + return _e || (_e = 1, process.env.NODE_ENV !== "production" && function() { + var D = ge, j = Symbol.for("react.element"), z = Symbol.for("react.portal"), E = Symbol.for("react.fragment"), I = Symbol.for("react.strict_mode"), C = Symbol.for("react.profiler"), y = Symbol.for("react.provider"), T = Symbol.for("react.context"), i = Symbol.for("react.forward_ref"), c = Symbol.for("react.suspense"), d = Symbol.for("react.suspense_list"), v = Symbol.for("react.memo"), M = Symbol.for("react.lazy"), m = Symbol.for("react.offscreen"), _ = Symbol.iterator, A = "@@iterator"; + function O(e) { + if (e === null || typeof e != "object") + return null; + var r = _ && e[_] || e[A]; + return typeof r == "function" ? r : null; + } + var h = D.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + function g(e) { + { + for (var r = arguments.length, t = new Array(r > 1 ? r - 1 : 0), a = 1; a < r; a++) + t[a - 1] = arguments[a]; + V("error", e, t); + } + } + function V(e, r, t) { + { + var a = h.ReactDebugCurrentFrame, u = a.getStackAddendum(); + u !== "" && (r += "%s", t = t.concat([u])); + var s = t.map(function(o) { + return String(o); + }); + s.unshift("Warning: " + r), Function.prototype.apply.call(console[e], console, s); + } + } + var p = !1, R = !1, x = !1, Q = !1, P = !1, Y; + Y = Symbol.for("react.module.reference"); + function L(e) { + return !!(typeof e == "string" || typeof e == "function" || e === E || e === C || P || e === I || e === c || e === d || Q || e === m || p || R || x || typeof e == "object" && e !== null && (e.$$typeof === M || e.$$typeof === v || e.$$typeof === y || e.$$typeof === T || e.$$typeof === i || // This needs to include all possible module reference object + // types supported by any Flight configuration anywhere since + // we don't know which Flight build this will end up being used + // with. + e.$$typeof === Y || e.getModuleId !== void 0)); + } + function te(e, r, t) { + var a = e.displayName; + if (a) + return a; + var u = r.displayName || r.name || ""; + return u !== "" ? t + "(" + u + ")" : t; + } + function ae(e) { + return e.displayName || "Context"; + } + function S(e) { + if (e == null) + return null; + if (typeof e.tag == "number" && g("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."), typeof e == "function") + return e.displayName || e.name || null; + if (typeof e == "string") + return e; + switch (e) { + case E: + return "Fragment"; + case z: + return "Portal"; + case C: + return "Profiler"; + case I: + return "StrictMode"; + case c: + return "Suspense"; + case d: + return "SuspenseList"; + } + if (typeof e == "object") + switch (e.$$typeof) { + case T: + var r = e; + return ae(r) + ".Consumer"; + case y: + var t = e; + return ae(t._context) + ".Provider"; + case i: + return te(e, e.render, "ForwardRef"); + case v: + var a = e.displayName || null; + return a !== null ? a : S(e.type) || "Memo"; + case M: { + var u = e, s = u._payload, o = u._init; + try { + return S(o(s)); + } catch { + return null; + } + } + } + return null; + } + var W = Object.assign, U = 0, ve, Me, me, we, ye, je, Ce; + function pe() { + } + pe.__reactDisabledLog = !0; + function Pe() { + { + if (U === 0) { + ve = console.log, Me = console.info, me = console.warn, we = console.error, ye = console.group, je = console.groupCollapsed, Ce = console.groupEnd; + var e = { + configurable: !0, + enumerable: !0, + value: pe, + writable: !0 + }; + Object.defineProperties(console, { + info: e, + log: e, + warn: e, + error: e, + group: e, + groupCollapsed: e, + groupEnd: e + }); + } + U++; + } + } + function Ye() { + { + if (U--, U === 0) { + var e = { + configurable: !0, + enumerable: !0, + writable: !0 + }; + Object.defineProperties(console, { + log: W({}, e, { + value: ve + }), + info: W({}, e, { + value: Me + }), + warn: W({}, e, { + value: me + }), + error: W({}, e, { + value: we + }), + group: W({}, e, { + value: ye + }), + groupCollapsed: W({}, e, { + value: je + }), + groupEnd: W({}, e, { + value: Ce + }) + }); + } + U < 0 && g("disabledDepth fell below zero. This is a bug in React. Please file an issue."); + } + } + var ie = h.ReactCurrentDispatcher, ne; + function X(e, r, t) { + { + if (ne === void 0) + try { + throw Error(); + } catch (u) { + var a = u.stack.trim().match(/\n( *(at )?)/); + ne = a && a[1] || ""; + } + return ` +` + ne + e; + } + } + var oe = !1, K; + { + var We = typeof WeakMap == "function" ? WeakMap : Map; + K = new We(); + } + function be(e, r) { + if (!e || oe) + return ""; + { + var t = K.get(e); + if (t !== void 0) + return t; + } + var a; + oe = !0; + var u = Error.prepareStackTrace; + Error.prepareStackTrace = void 0; + var s; + s = ie.current, ie.current = null, Pe(); + try { + if (r) { + var o = function() { + throw Error(); + }; + if (Object.defineProperty(o.prototype, "props", { + set: function() { + throw Error(); + } + }), typeof Reflect == "object" && Reflect.construct) { + try { + Reflect.construct(o, []); + } catch (k) { + a = k; + } + Reflect.construct(e, [], o); + } else { + try { + o.call(); + } catch (k) { + a = k; + } + e.call(o.prototype); + } + } else { + try { + throw Error(); + } catch (k) { + a = k; + } + e(); + } + } catch (k) { + if (k && a && typeof k.stack == "string") { + for (var n = k.stack.split(` +`), w = a.stack.split(` +`), l = n.length - 1, f = w.length - 1; l >= 1 && f >= 0 && n[l] !== w[f]; ) + f--; + for (; l >= 1 && f >= 0; l--, f--) + if (n[l] !== w[f]) { + if (l !== 1 || f !== 1) + do + if (l--, f--, f < 0 || n[l] !== w[f]) { + var b = ` +` + n[l].replace(" at new ", " at "); + return e.displayName && b.includes("") && (b = b.replace("", e.displayName)), typeof e == "function" && K.set(e, b), b; + } + while (l >= 1 && f >= 0); + break; + } + } + } finally { + oe = !1, ie.current = s, Ye(), Error.prepareStackTrace = u; + } + var F = e ? e.displayName || e.name : "", Oe = F ? X(F) : ""; + return typeof e == "function" && K.set(e, Oe), Oe; + } + function Be(e, r, t) { + return be(e, !1); + } + function Ve(e) { + var r = e.prototype; + return !!(r && r.isReactComponent); + } + function q(e, r, t) { + if (e == null) + return ""; + if (typeof e == "function") + return be(e, Ve(e)); + if (typeof e == "string") + return X(e); + switch (e) { + case c: + return X("Suspense"); + case d: + return X("SuspenseList"); + } + if (typeof e == "object") + switch (e.$$typeof) { + case i: + return Be(e.render); + case v: + return q(e.type, r, t); + case M: { + var a = e, u = a._payload, s = a._init; + try { + return q(s(u), r, t); + } catch { + } + } + } + return ""; + } + var ee = Object.prototype.hasOwnProperty, Ne = {}, Ie = h.ReactDebugCurrentFrame; + function re(e) { + if (e) { + var r = e._owner, t = q(e.type, e._source, r ? r.type : null); + Ie.setExtraStackFrame(t); + } else + Ie.setExtraStackFrame(null); + } + function Qe(e, r, t, a, u) { + { + var s = Function.call.bind(ee); + for (var o in e) + if (s(e, o)) { + var n = void 0; + try { + if (typeof e[o] != "function") { + var w = Error((a || "React class") + ": " + t + " type `" + o + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof e[o] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); + throw w.name = "Invariant Violation", w; + } + n = e[o](r, o, a, t, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); + } catch (l) { + n = l; + } + n && !(n instanceof Error) && (re(u), g("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", a || "React class", t, o, typeof n), re(null)), n instanceof Error && !(n.message in Ne) && (Ne[n.message] = !0, re(u), g("Failed %s type: %s", t, n.message), re(null)); + } + } + } + var Ze = Array.isArray; + function ue(e) { + return Ze(e); + } + function Fe(e) { + { + var r = typeof Symbol == "function" && Symbol.toStringTag, t = r && e[Symbol.toStringTag] || e.constructor.name || "Object"; + return t; + } + } + function Ue(e) { + try { + return Te(e), !1; + } catch { + return !0; + } + } + function Te(e) { + return "" + e; + } + function Le(e) { + if (Ue(e)) + return g("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", Fe(e)), Te(e); + } + var G = h.ReactCurrentOwner, Ge = { + key: !0, + ref: !0, + __self: !0, + __source: !0 + }, Se, De, se; + se = {}; + function Je(e) { + if (ee.call(e, "ref")) { + var r = Object.getOwnPropertyDescriptor(e, "ref").get; + if (r && r.isReactWarning) + return !1; + } + return e.ref !== void 0; + } + function He(e) { + if (ee.call(e, "key")) { + var r = Object.getOwnPropertyDescriptor(e, "key").get; + if (r && r.isReactWarning) + return !1; + } + return e.key !== void 0; + } + function $e(e, r) { + if (typeof e.ref == "string" && G.current && r && G.current.stateNode !== r) { + var t = S(G.current.type); + se[t] || (g('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', S(G.current.type), e.ref), se[t] = !0); + } + } + function Xe(e, r) { + { + var t = function() { + Se || (Se = !0, g("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", r)); + }; + t.isReactWarning = !0, Object.defineProperty(e, "key", { + get: t, + configurable: !0 + }); + } + } + function Ke(e, r) { + { + var t = function() { + De || (De = !0, g("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", r)); + }; + t.isReactWarning = !0, Object.defineProperty(e, "ref", { + get: t, + configurable: !0 + }); + } + } + var qe = function(e, r, t, a, u, s, o) { + var n = { + // This tag allows us to uniquely identify this as a React Element + $$typeof: j, + // Built-in properties that belong on the element + type: e, + key: r, + ref: t, + props: o, + // Record the component responsible for creating this element. + _owner: s + }; + return n._store = {}, Object.defineProperty(n._store, "validated", { + configurable: !1, + enumerable: !1, + writable: !0, + value: !1 + }), Object.defineProperty(n, "_self", { + configurable: !1, + enumerable: !1, + writable: !1, + value: a + }), Object.defineProperty(n, "_source", { + configurable: !1, + enumerable: !1, + writable: !1, + value: u + }), Object.freeze && (Object.freeze(n.props), Object.freeze(n)), n; + }; + function er(e, r, t, a, u) { + { + var s, o = {}, n = null, w = null; + t !== void 0 && (Le(t), n = "" + t), He(r) && (Le(r.key), n = "" + r.key), Je(r) && (w = r.ref, $e(r, u)); + for (s in r) + ee.call(r, s) && !Ge.hasOwnProperty(s) && (o[s] = r[s]); + if (e && e.defaultProps) { + var l = e.defaultProps; + for (s in l) + o[s] === void 0 && (o[s] = l[s]); + } + if (n || w) { + var f = typeof e == "function" ? e.displayName || e.name || "Unknown" : e; + n && Xe(o, f), w && Ke(o, f); + } + return qe(e, n, w, u, a, G.current, o); + } + } + var ce = h.ReactCurrentOwner, Ee = h.ReactDebugCurrentFrame; + function Z(e) { + if (e) { + var r = e._owner, t = q(e.type, e._source, r ? r.type : null); + Ee.setExtraStackFrame(t); + } else + Ee.setExtraStackFrame(null); + } + var le; + le = !1; + function fe(e) { + return typeof e == "object" && e !== null && e.$$typeof === j; + } + function he() { + { + if (ce.current) { + var e = S(ce.current.type); + if (e) + return ` + +Check the render method of \`` + e + "`."; + } + return ""; + } + } + function rr(e) { + { + if (e !== void 0) { + var r = e.fileName.replace(/^.*[\\\/]/, ""), t = e.lineNumber; + return ` + +Check your code at ` + r + ":" + t + "."; + } + return ""; + } + } + var Re = {}; + function tr(e) { + { + var r = he(); + if (!r) { + var t = typeof e == "string" ? e : e.displayName || e.name; + t && (r = ` + +Check the top-level render call using <` + t + ">."); + } + return r; + } + } + function xe(e, r) { + { + if (!e._store || e._store.validated || e.key != null) + return; + e._store.validated = !0; + var t = tr(r); + if (Re[t]) + return; + Re[t] = !0; + var a = ""; + e && e._owner && e._owner !== ce.current && (a = " It was passed a child from " + S(e._owner.type) + "."), Z(e), g('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', t, a), Z(null); + } + } + function ze(e, r) { + { + if (typeof e != "object") + return; + if (ue(e)) + for (var t = 0; t < e.length; t++) { + var a = e[t]; + fe(a) && xe(a, r); + } + else if (fe(e)) + e._store && (e._store.validated = !0); + else if (e) { + var u = O(e); + if (typeof u == "function" && u !== e.entries) + for (var s = u.call(e), o; !(o = s.next()).done; ) + fe(o.value) && xe(o.value, r); + } + } + } + function ar(e) { + { + var r = e.type; + if (r == null || typeof r == "string") + return; + var t; + if (typeof r == "function") + t = r.propTypes; + else if (typeof r == "object" && (r.$$typeof === i || // Note: Memo only checks outer props here. + // Inner props are checked in the reconciler. + r.$$typeof === v)) + t = r.propTypes; + else + return; + if (t) { + var a = S(r); + Qe(t, e.props, "prop", a, e); + } else if (r.PropTypes !== void 0 && !le) { + le = !0; + var u = S(r); + g("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", u || "Unknown"); + } + typeof r.getDefaultProps == "function" && !r.getDefaultProps.isReactClassApproved && g("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); + } + } + function ir(e) { + { + for (var r = Object.keys(e.props), t = 0; t < r.length; t++) { + var a = r[t]; + if (a !== "children" && a !== "key") { + Z(e), g("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", a), Z(null); + break; + } + } + e.ref !== null && (Z(e), g("Invalid attribute `ref` supplied to `React.Fragment`."), Z(null)); + } + } + function Ae(e, r, t, a, u, s) { + { + var o = L(e); + if (!o) { + var n = ""; + (e === void 0 || typeof e == "object" && e !== null && Object.keys(e).length === 0) && (n += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."); + var w = rr(u); + w ? n += w : n += he(); + var l; + e === null ? l = "null" : ue(e) ? l = "array" : e !== void 0 && e.$$typeof === j ? (l = "<" + (S(e.type) || "Unknown") + " />", n = " Did you accidentally export a JSX literal instead of a component?") : l = typeof e, g("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", l, n); + } + var f = er(e, r, t, u, s); + if (f == null) + return f; + if (o) { + var b = r.children; + if (b !== void 0) + if (a) + if (ue(b)) { + for (var F = 0; F < b.length; F++) + ze(b[F], e); + Object.freeze && Object.freeze(b); + } else + g("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."); + else + ze(b, e); + } + return e === E ? ir(f) : ar(f), f; + } + } + function nr(e, r, t) { + return Ae(e, r, t, !0); + } + function or(e, r, t) { + return Ae(e, r, t, !1); + } + var ur = or, sr = nr; + $.Fragment = E, $.jsx = ur, $.jsxs = sr; + }()), $; +} +process.env.NODE_ENV === "production" ? de.exports = fr() : de.exports = dr(); +var N = de.exports; +const gr = (D, j, z) => { + const [E, I] = B(!1), [C, y] = B(!1), [T, i] = B(0), [c, d] = B(), [v, M] = B(), [m, _] = B(), A = J(() => { + const p = setInterval(() => { + i((R) => R + 1); + }, 1e3); + M(p); + }, [i, M]), O = J(() => { + v != null && clearInterval(v), M(void 0); + }, [v, M]), h = J(() => { + v == null && navigator.mediaDevices.getUserMedia({ audio: D ?? !0 }).then((p) => { + I(!0); + const R = new MediaRecorder( + p, + z + ); + d(R), R.start(), A(), R.addEventListener("dataavailable", (x) => { + _(x.data), R.stream.getTracks().forEach((Q) => Q.stop()), d(void 0); + }); + }).catch((p) => { + console.log(p.name, p.message, p.cause), j == null || j(p); + }); + }, [ + v, + I, + d, + A, + _, + j, + z + ]), g = J(() => { + c == null || c.stop(), O(), i(0), I(!1), y(!1); + }, [ + c, + i, + I, + y, + O + ]), V = J(() => { + C ? (y(!1), c == null || c.resume(), A()) : (y(!0), O(), c == null || c.pause()); + }, [c, y, A, O]); + return { + startRecording: h, + stopRecording: g, + togglePauseResume: V, + recordingBlob: m, + isRecording: E, + isPaused: C, + recordingTime: T, + mediaRecorder: c + }; +}, vr = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTkuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgdmlld0JveD0iMCAwIDQ3MCA0NzAiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDQ3MCA0NzA7IiB4bWw6c3BhY2U9InByZXNlcnZlIj4KCTxnPgoJCTxwYXRoIGQ9Ik0yMzUsMzAyLjI5NmM0Ny4xNzcsMCw4NS40MjMtMzguMjQ1LDg1LjQyMy04NS40MjNWODUuNDIzQzMyMC40MjMsMzguMjQ1LDI4Mi4xNzcsMCwyMzUsMHMtODUuNDIzLDM4LjI0NS04NS40MjMsODUuNDIzCgkJCXYxMzEuNDUxQzE0OS41NzcsMjY0LjA1MSwxODcuODIzLDMwMi4yOTYsMjM1LDMwMi4yOTZ6Ii8+CgkJPHBhdGggZD0iTTM1MC40MjMsMTM2LjE0OHYzMGgxNXY1MC43MjZjMCw3MS45MTUtNTguNTA4LDEzMC40MjMtMTMwLjQyMywxMzAuNDIzcy0xMzAuNDIzLTU4LjUwNy0xMzAuNDIzLTEzMC40MjN2LTUwLjcyNmgxNXYtMzAKCQkJaC00NXY4MC43MjZDNzQuNTc3LDMwMC4yNzMsMTM4LjU1MSwzNjksMjIwLDM3Ni41ODlWNDQwaC05MC40NDR2MzBoMjEwLjg4OXYtMzBIMjUwdi02My40MTEKCQkJYzgxLjQ0OS03LjU4OSwxNDUuNDIzLTc2LjMxNywxNDUuNDIzLTE1OS43MTZ2LTgwLjcyNkgzNTAuNDIzeiIvPgoJPC9nPgo8L3N2Zz4K", Mr = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTkuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCIKCSB2aWV3Qm94PSIwIDAgNDcuNjA3IDQ3LjYwNyIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNDcuNjA3IDQ3LjYwNzsiIHhtbDpzcGFjZT0icHJlc2VydmUiPgoJPGc+CgkJPHBhdGggZD0iTTE3Ljk5MSw0MC45NzZjMCwzLjY2Mi0yLjk2OSw2LjYzMS02LjYzMSw2LjYzMWwwLDBjLTMuNjYyLDAtNi42MzEtMi45NjktNi42MzEtNi42MzFWNi42MzFDNC43MjksMi45NjksNy42OTgsMCwxMS4zNiwwCgkJCWwwLDBjMy42NjIsMCw2LjYzMSwyLjk2OSw2LjYzMSw2LjYzMVY0MC45NzZ6Ii8+CgkJPHBhdGggZD0iTTQyLjg3Nyw0MC45NzZjMCwzLjY2Mi0yLjk2OSw2LjYzMS02LjYzMSw2LjYzMWwwLDBjLTMuNjYyLDAtNi42MzEtMi45NjktNi42MzEtNi42MzFWNi42MzEKCQkJQzI5LjYxNiwyLjk2OSwzMi41ODUsMCwzNi4yNDYsMGwwLDBjMy42NjIsMCw2LjYzMSwyLjk2OSw2LjYzMSw2LjYzMVY0MC45NzZ6Ii8+Cgk8L2c+Cjwvc3ZnPgo=", mr = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTkuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiCgkgdmlld0JveD0iMCAwIDQ5NC4xNDggNDk0LjE0OCIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNDk0LjE0OCA0OTQuMTQ4OyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+Cgk8Zz4KCQk8Zz4KCQkJPHBhdGggZD0iTTQwNS4yODQsMjAxLjE4OEwxMzAuODA0LDEzLjI4QzExOC4xMjgsNC41OTYsMTA1LjM1NiwwLDk0Ljc0LDBDNzQuMjE2LDAsNjEuNTIsMTYuNDcyLDYxLjUyLDQ0LjA0NHY0MDYuMTI0CgkJCQljMCwyNy41NCwxMi42OCw0My45OCwzMy4xNTYsNDMuOThjMTAuNjMyLDAsMjMuMi00LjYsMzUuOTA0LTEzLjMwOGwyNzQuNjA4LTE4Ny45MDRjMTcuNjYtMTIuMTA0LDI3LjQ0LTI4LjM5MiwyNy40NC00NS44ODQKCQkJCUM0MzIuNjMyLDIyOS41NzIsNDIyLjk2NCwyMTMuMjg4LDQwNS4yODQsMjAxLjE4OHoiLz4KCQk8L2c+Cgk8L2c+Cjwvc3ZnPgo=", wr = "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMThweCIgaGVpZ2h0PSIxOHB4IiB2aWV3Qm94PSIwIDAgMTggMTgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgPHBhdGggZmlsbD0iIzAwMDAwMCIgZD0iTTE3Ljg1IDMuMTVsLTIuOTktM0EuNTA4LjUwOCAwIDAgMCAxNC41IDBIMS40QTEuNDE3IDEuNDE3IDAgMCAwIDAgMS40M3YxNS4xNEExLjQxNyAxLjQxNyAwIDAgMCAxLjQgMThoMTUuMmExLjQxNyAxLjQxNyAwIDAgMCAxLjQtMS40M1YzLjVhLjQ3LjQ3IDAgMCAwLS4xNS0uMzV6TTIgNVYzYTEgMSAwIDAgMSAxLTFoOGExIDEgMCAwIDEgMSAxdjJhMSAxIDAgMCAxLTEgMUgzYTEgMSAwIDAgMS0xLTF6bTcgMTFhNCA0IDAgMSAxIDQtNCA0IDQgMCAwIDEtNCA0eiIvPgo8L3N2Zz4K", yr = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pgo8IS0tIEdlbmVyYXRvcjogQWRvYmUgSWxsdXN0cmF0b3IgMTkuMC4wLCBTVkcgRXhwb3J0IFBsdWctSW4gLiBTVkcgVmVyc2lvbjogNi4wMCBCdWlsZCAwKSAgLS0+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iQ2FwYV8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCIKCSB2aWV3Qm94PSIwIDAgNDYuNzM0IDQ2LjczNCIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNDYuNzM0IDQ2LjczNDsiIHhtbDpzcGFjZT0icHJlc2VydmUiPgo8Zz4KCTxwYXRoIGQ9Ik00MS4zNDYsMEg1LjM4OEMyLjQxNywwLDAsMi40MTcsMCw1LjM4OHYzNS45NThjMCwyLjk3MSwyLjQxNyw1LjM4OCw1LjM4OCw1LjM4OGgzNS45NThjMi45NzEsMCw1LjM4OC0yLjQxNyw1LjM4OC01LjM4OAoJCVY1LjM4OEM0Ni43MzMsMi40MTcsNDQuMzE2LDAsNDEuMzQ2LDB6Ii8+CjwvZz4KPC9zdmc+Cg=="; +const jr = ge.lazy(async () => { + const { LiveAudioVisualizer: D } = await import("./react-audio-visualize.es-69216c73.js"); + return { default: D }; +}), pr = ({ + onRecordingComplete: D, + onNotAllowedOrFound: j, + recorderControls: z, + audioTrackConstraints: E, + downloadOnSavePress: I = !1, + downloadFileExtension: C = "webm", + showVisualizer: y = !1, + mediaRecorderOptions: T, + classes: i +}) => { + const { + startRecording: c, + stopRecording: d, + togglePauseResume: v, + recordingBlob: M, + isRecording: m, + isPaused: _, + recordingTime: A, + mediaRecorder: O + } = z ?? // eslint-disable-next-line react-hooks/rules-of-hooks + gr( + E, + j, + T + ), [h, g] = B(!1), V = (x = !0) => { + g(x), d(); + }, p = async (x) => { + const P = (await import("./index-1c988149.js").then((S) => S.i)).createFFmpeg({ log: !1 }); + await P.load(); + const Y = "input.webm", L = `output.${C}`; + P.FS( + "writeFile", + Y, + new Uint8Array(await x.arrayBuffer()) + ), await P.run("-i", Y, L); + const te = P.FS("readFile", L); + return new Blob([te.buffer], { + type: `audio/${C}` + }); + }, R = async (x) => { + !crossOriginIsolated && C !== "webm" && console.warn( + 'This website is not "cross-origin isolated". Audio will be downloaded in webm format, since mp3/wav encoding requires cross origin isolation. Please visit https://web.dev/cross-origin-isolation-guide/ and https://web.dev/coop-coep/ for information on how to make your website "cross-origin isolated"' + ); + const Q = crossOriginIsolated ? await p(x) : x, P = crossOriginIsolated ? C : "webm", Y = URL.createObjectURL(Q), L = document.createElement("a"); + L.style.display = "none", L.href = Y, L.download = `audio.${P}`, document.body.appendChild(L), L.click(), L.remove(); + }; + return cr(() => { + (h || z) && M != null && D != null && (D(M), I && R(M)); + }, [M]), /* @__PURE__ */ N.jsxs( + "div", + { + className: `audio-recorder ${m ? "recording" : ""} ${(i == null ? void 0 : i.AudioRecorderClass) ?? ""}`, + "data-testid": "audio_recorder", + children: [ + /* @__PURE__ */ N.jsx( + "img", + { + src: m ? wr : vr, + className: `audio-recorder-mic ${(i == null ? void 0 : i.AudioRecorderStartSaveClass) ?? ""}`, + onClick: m ? () => V() : c, + "data-testid": "ar_mic", + title: m ? "Save recording" : "Start recording" + } + ), + /* @__PURE__ */ N.jsxs( + "span", + { + className: `audio-recorder-timer ${m ? "" : "display-none"} ${(i == null ? void 0 : i.AudioRecorderTimerClass) ?? ""}`, + "data-testid": "ar_timer", + children: [ + Math.floor(A / 60), + ":", + String(A % 60).padStart(2, "0") + ] + } + ), + y ? /* @__PURE__ */ N.jsx( + "span", + { + className: `audio-recorder-visualizer ${m ? "" : "display-none"}`, + children: O && /* @__PURE__ */ N.jsx(lr, { fallback: /* @__PURE__ */ N.jsx(N.Fragment, {}), children: /* @__PURE__ */ N.jsx( + jr, + { + mediaRecorder: O, + barWidth: 2, + gap: 2, + width: 140, + height: 30, + fftSize: 512, + maxDecibels: -10, + minDecibels: -80, + smoothingTimeConstant: 0.4 + } + ) }) + } + ) : /* @__PURE__ */ N.jsxs( + "span", + { + className: `audio-recorder-status ${m ? "" : "display-none"} ${(i == null ? void 0 : i.AudioRecorderStatusClass) ?? ""}`, + children: [ + /* @__PURE__ */ N.jsx("span", { className: "audio-recorder-status-dot" }), + "Recording" + ] + } + ), + /* @__PURE__ */ N.jsx( + "img", + { + src: _ ? mr : Mr, + className: `audio-recorder-options ${m ? "" : "display-none"} ${(i == null ? void 0 : i.AudioRecorderPauseResumeClass) ?? ""}`, + onClick: v, + title: _ ? "Resume recording" : "Pause recording", + "data-testid": "ar_pause" + } + ), + /* @__PURE__ */ N.jsx( + "img", + { + src: yr, + className: `audio-recorder-options ${m ? "" : "display-none"} ${(i == null ? void 0 : i.AudioRecorderDiscardClass) ?? ""}`, + onClick: () => V(!1), + title: "Discard Recording", + "data-testid": "ar_cancel" + } + ) + ] + } + ); +}; +export { + pr as AudioRecorder, + gr as useAudioRecorder +}; diff --git a/node_modules/react-audio-voice-recorder/dist/vite-env.d.ts b/node_modules/react-audio-voice-recorder/dist/vite-env.d.ts new file mode 100644 index 0000000..11f02fe --- /dev/null +++ b/node_modules/react-audio-voice-recorder/dist/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/node_modules/react-audio-voice-recorder/package.json b/node_modules/react-audio-voice-recorder/package.json new file mode 100644 index 0000000..9d7ae24 --- /dev/null +++ b/node_modules/react-audio-voice-recorder/package.json @@ -0,0 +1,102 @@ +{ + "name": "react-audio-voice-recorder", + "private": false, + "version": "2.2.0", + "type": "module", + "license": "MIT", + "author": "Samhir Tarif", + "repository": { + "type": "git", + "url": "https://github.com/samhirtarif/react-audio-recorder.git" + }, + "keywords": [ + "react", + "reactjs", + "nextjs", + "audio", + "voice", + "audio recording", + "audio recorder", + "voice recording", + "voice recorder", + "recorder", + "recording", + "getUserMedia", + "mediaDevices", + "ffmpeg", + "download audio", + "download", + "mp3", + "webm", + "wav", + "mpeg" + ], + "files": [ + "dist" + ], + "module": "./dist/react-audio-voice-recorder.es.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/react-audio-voice-recorder.es.js" + } + }, + "scripts": { + "dev": "vite", + "build": "tsc && vite build", + "preview": "vite preview", + "lint": "eslint src/**/*.ts{,x}", + "lint:fix": "npm run lint -- --fix", + "test": "vitest", + "storybook": "start-storybook -p 6006 --no-manager-cache", + "build-storybook": "build-storybook" + }, + "peerDependencies": { + "react": ">=16.2.0", + "react-dom": ">=16.2.0" + }, + "devDependencies": { + "@babel/core": "^7.18.13", + "@fortawesome/fontawesome-svg-core": "^6.2.0", + "@storybook/addon-actions": "^6.5.10", + "@storybook/addon-essentials": "^6.5.10", + "@storybook/addon-interactions": "^6.5.10", + "@storybook/addon-links": "^6.5.10", + "@storybook/builder-vite": "^0.2.2", + "@storybook/react": "^6.5.10", + "@storybook/testing-library": "^0.0.13", + "@testing-library/jest-dom": "^5.16.5", + "@testing-library/react": "^13.3.0", + "@testing-library/user-event": "^14.4.3", + "@types/jest": "^29.0.0", + "@types/react": "^18.0.17", + "@types/react-dom": "^18.0.6", + "@typescript-eslint/eslint-plugin": "^5.35.1", + "@vitejs/plugin-react": "^2.0.1", + "babel-loader": "^8.2.5", + "eslint": "^8.23.0", + "eslint-config-prettier": "^8.5.0", + "eslint-config-standard-with-typescript": "^22.0.0", + "eslint-plugin-import": "^2.26.0", + "eslint-plugin-n": "^15.2.5", + "eslint-plugin-prettier": "^4.2.1", + "eslint-plugin-promise": "^6.0.1", + "eslint-plugin-react": "^7.31.1", + "eslint-plugin-react-hooks": "^4.6.0", + "eslint-plugin-storybook": "^0.6.4", + "jsdom": "^20.0.0", + "prettier": "^2.7.1", + "react": "^18.2.0", + "react-dom": "^18.2.0", + "typescript": "^4.8.2", + "vite": "^4.4.2", + "vite-plugin-css-injected-by-js": "^3.1.0", + "vite-plugin-dts": "^1.4.1", + "vitest": "^0.33.0" + }, + "dependencies": { + "@ffmpeg/ffmpeg": "^0.11.6", + "react-audio-visualize": "^1.1.3" + } +} diff --git a/node_modules/react-dom/LICENSE b/node_modules/react-dom/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/react-dom/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +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/react-dom/README.md b/node_modules/react-dom/README.md new file mode 100644 index 0000000..ecba5cf --- /dev/null +++ b/node_modules/react-dom/README.md @@ -0,0 +1,60 @@ +# `react-dom` + +This package serves as the entry point to the DOM and server renderers for React. It is intended to be paired with the generic React package, which is shipped as `react` to npm. + +## Installation + +```sh +npm install react react-dom +``` + +## Usage + +### In the browser + +```js +import { createRoot } from 'react-dom/client'; + +function App() { + return
Hello World
; +} + +const root = createRoot(document.getElementById('root')); +root.render(); +``` + +### On the server + +```js +import { renderToPipeableStream } from 'react-dom/server'; + +function App() { + return
Hello World
; +} + +function handleRequest(res) { + // ... in your server handler ... + const stream = renderToPipeableStream(, { + onShellReady() { + res.statusCode = 200; + res.setHeader('Content-type', 'text/html'); + stream.pipe(res); + }, + // ... + }); +} +``` + +## API + +### `react-dom` + +See https://reactjs.org/docs/react-dom.html + +### `react-dom/client` + +See https://reactjs.org/docs/react-dom-client.html + +### `react-dom/server` + +See https://reactjs.org/docs/react-dom-server.html diff --git a/node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js b/node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js new file mode 100644 index 0000000..102e3ef --- /dev/null +++ b/node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js @@ -0,0 +1,7029 @@ +/** + * @license React + * react-dom-server-legacy.browser.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +if (process.env.NODE_ENV !== "production") { + (function() { +'use strict'; + +var React = require('react'); + +var ReactVersion = '18.3.1'; + +var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; + +// by calls to these methods by a Babel plugin. +// +// In PROD (or in packages without access to React internals), +// they are left as they are instead. + +function warn(format) { + { + { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + printWarning('warn', format, args); + } + } +} +function error(format) { + { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } // eslint-disable-next-line react-internal/safe-string-coercion + + + var argsWithFormat = args.map(function (item) { + return String(item); + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + } +} + +function scheduleWork(callback) { + callback(); +} +function beginWriting(destination) {} +function writeChunk(destination, chunk) { + writeChunkAndReturn(destination, chunk); +} +function writeChunkAndReturn(destination, chunk) { + return destination.push(chunk); +} +function completeWriting(destination) {} +function close(destination) { + destination.push(null); +} +function stringToChunk(content) { + return content; +} +function stringToPrecomputedChunk(content) { + return content; +} +function closeWithError(destination, error) { + // $FlowFixMe: This is an Error object or the destination accepts other types. + destination.destroy(error); +} + +/* + * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol + * and Temporal.* types. See https://github.com/facebook/react/pull/22064. + * + * The functions in this module will throw an easier-to-understand, + * easier-to-debug exception with a clear errors message message explaining the + * problem. (Instead of a confusing exception thrown inside the implementation + * of the `value` object). + */ +// $FlowFixMe only called in DEV, so void return is not possible. +function typeName(value) { + { + // toStringTag is needed for namespaced types like Temporal.Instant + var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag; + var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object'; + return type; + } +} // $FlowFixMe only called in DEV, so void return is not possible. + + +function willCoercionThrow(value) { + { + try { + testStringCoercion(value); + return false; + } catch (e) { + return true; + } + } +} + +function testStringCoercion(value) { + // If you ended up here by following an exception call stack, here's what's + // happened: you supplied an object or symbol value to React (as a prop, key, + // DOM attribute, CSS property, string ref, etc.) and when React tried to + // coerce it to a string using `'' + value`, an exception was thrown. + // + // The most common types that will cause this exception are `Symbol` instances + // and Temporal objects like `Temporal.Instant`. But any object that has a + // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this + // exception. (Library authors do this to prevent users from using built-in + // numeric operators like `+` or comparison operators like `>=` because custom + // methods are needed to perform accurate arithmetic or comparison.) + // + // To fix the problem, coerce this object or symbol value to a string before + // passing it to React. The most reliable way is usually `String(value)`. + // + // To find which value is throwing, check the browser or debugger console. + // Before this exception was thrown, there should be `console.error` output + // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the + // problem and how that type was used: key, atrribute, input value prop, etc. + // In most cases, this console output also shows the component and its + // ancestor components where the exception happened. + // + // eslint-disable-next-line react-internal/safe-string-coercion + return '' + value; +} + +function checkAttributeStringCoercion(value, attributeName) { + { + if (willCoercionThrow(value)) { + error('The provided `%s` attribute is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', attributeName, typeName(value)); + + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } +} +function checkCSSPropertyStringCoercion(value, propName) { + { + if (willCoercionThrow(value)) { + error('The provided `%s` CSS property is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', propName, typeName(value)); + + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } +} +function checkHtmlStringCoercion(value) { + { + if (willCoercionThrow(value)) { + error('The provided HTML markup uses a value of unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value)); + + return testStringCoercion(value); // throw (to help callers find troubleshooting comments) + } + } +} + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +// A reserved attribute. +// It is handled by React separately and shouldn't be written to the DOM. +var RESERVED = 0; // A simple string attribute. +// Attributes that aren't in the filter are presumed to have this type. + +var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called +// "enumerated" attributes with "true" and "false" as possible values. +// When true, it should be set to a "true" string. +// When false, it should be set to a "false" string. + +var BOOLEANISH_STRING = 2; // A real boolean attribute. +// When true, it should be present (set either to an empty string or its name). +// When false, it should be omitted. + +var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value. +// When true, it should be present (set either to an empty string or its name). +// When false, it should be omitted. +// For any other value, should be present with that value. + +var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric. +// When falsy, it should be removed. + +var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric. +// When falsy, it should be removed. + +var POSITIVE_NUMERIC = 6; + +/* eslint-disable max-len */ +var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; +/* eslint-enable max-len */ + +var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; +var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$'); +var illegalAttributeNameCache = {}; +var validatedAttributeNameCache = {}; +function isAttributeNameSafe(attributeName) { + if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) { + return true; + } + + if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) { + return false; + } + + if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { + validatedAttributeNameCache[attributeName] = true; + return true; + } + + illegalAttributeNameCache[attributeName] = true; + + { + error('Invalid attribute name: `%s`', attributeName); + } + + return false; +} +function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { + if (propertyInfo !== null && propertyInfo.type === RESERVED) { + return false; + } + + switch (typeof value) { + case 'function': // $FlowIssue symbol is perfectly valid here + + case 'symbol': + // eslint-disable-line + return true; + + case 'boolean': + { + if (isCustomComponentTag) { + return false; + } + + if (propertyInfo !== null) { + return !propertyInfo.acceptsBooleans; + } else { + var prefix = name.toLowerCase().slice(0, 5); + return prefix !== 'data-' && prefix !== 'aria-'; + } + } + + default: + return false; + } +} +function getPropertyInfo(name) { + return properties.hasOwnProperty(name) ? properties[name] : null; +} + +function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) { + this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; + this.attributeName = attributeName; + this.attributeNamespace = attributeNamespace; + this.mustUseProperty = mustUseProperty; + this.propertyName = name; + this.type = type; + this.sanitizeURL = sanitizeURL; + this.removeEmptyString = removeEmptyString; +} // When adding attributes to this list, be sure to also add them to +// the `possibleStandardNames` module to ensure casing and incorrect +// name warnings. + + +var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM. + +var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular +// elements (not just inputs). Now that ReactDOMInput assigns to the +// defaultValue property -- do we need this? +'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style']; + +reservedProps.forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // A few React string attributes have a different name. +// This is a mapping from React prop names to the attribute names. + +[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) { + var name = _ref[0], + attributeName = _ref[1]; + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are "enumerated" HTML attributes that accept "true" and "false". +// In React, we let users pass `true` and `false` even though technically +// these aren't boolean attributes (they are coerced to strings). + +['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are "enumerated" SVG attributes that accept "true" and "false". +// In React, we let users pass `true` and `false` even though technically +// these aren't boolean attributes (they are coerced to strings). +// Since these are SVG attributes, their attribute names are case-sensitive. + +['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are HTML boolean attributes. + +['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM +// on the client side because the browsers are inconsistent. Instead we call focus(). +'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'disableRemotePlayback', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata +'itemScope'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are the few React props that we set as DOM properties +// rather than attributes. These are all booleans. + +['checked', // Note: `option.selected` is not updated if `select.multiple` is +// disabled with `removeAttribute`. We have special logic for handling this. +'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are HTML attributes that are "overloaded booleans": they behave like +// booleans, but can also accept a string value. + +['capture', 'download' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are HTML attributes that must be positive numbers. + +['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These are HTML attributes that must be numbers. + +['rowSpan', 'start'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); +var CAMELIZE = /[\-\:]([a-z])/g; + +var capitalize = function (token) { + return token[1].toUpperCase(); +}; // This is a list of all SVG attributes that need special casing, namespacing, +// or boolean value assignment. Regular attributes that just accept strings +// and have the same names are omitted, just like in the HTML attribute filter. +// Some of these attributes can be hard to find. This list was created by +// scraping the MDN documentation. + + +['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, null, // attributeNamespace + false, // sanitizeURL + false); +}); // String SVG attributes with the xlink namespace. + +['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, 'http://www.w3.org/1999/xlink', false, // sanitizeURL + false); +}); // String SVG attributes with the xml namespace. + +['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, 'http://www.w3.org/XML/1998/namespace', false, // sanitizeURL + false); +}); // These attribute exists both in HTML and SVG. +// The attribute name is case-sensitive in SVG so we can't just use +// the React name like we do for attributes that exist only in HTML. + +['tabIndex', 'crossOrigin'].forEach(function (attributeName) { + properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty + attributeName.toLowerCase(), // attributeName + null, // attributeNamespace + false, // sanitizeURL + false); +}); // These attributes accept URLs. These must not allow javascript: URLS. +// These will also need to accept Trusted Types object in the future. + +var xlinkHref = 'xlinkHref'; +properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty +'xlink:href', 'http://www.w3.org/1999/xlink', true, // sanitizeURL +false); +['src', 'href', 'action', 'formAction'].forEach(function (attributeName) { + properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty + attributeName.toLowerCase(), // attributeName + null, // attributeNamespace + true, // sanitizeURL + true); +}); + +/** + * CSS properties which accept numbers but are not in units of "px". + */ +var isUnitlessNumber = { + animationIterationCount: true, + aspectRatio: true, + borderImageOutset: true, + borderImageSlice: true, + borderImageWidth: true, + boxFlex: true, + boxFlexGroup: true, + boxOrdinalGroup: true, + columnCount: true, + columns: true, + flex: true, + flexGrow: true, + flexPositive: true, + flexShrink: true, + flexNegative: true, + flexOrder: true, + gridArea: true, + gridRow: true, + gridRowEnd: true, + gridRowSpan: true, + gridRowStart: true, + gridColumn: true, + gridColumnEnd: true, + gridColumnSpan: true, + gridColumnStart: true, + fontWeight: true, + lineClamp: true, + lineHeight: true, + opacity: true, + order: true, + orphans: true, + tabSize: true, + widows: true, + zIndex: true, + zoom: true, + // SVG-related properties + fillOpacity: true, + floodOpacity: true, + stopOpacity: true, + strokeDasharray: true, + strokeDashoffset: true, + strokeMiterlimit: true, + strokeOpacity: true, + strokeWidth: true +}; +/** + * @param {string} prefix vendor-specific prefix, eg: Webkit + * @param {string} key style name, eg: transitionDuration + * @return {string} style name prefixed with `prefix`, properly camelCased, eg: + * WebkitTransitionDuration + */ + +function prefixKey(prefix, key) { + return prefix + key.charAt(0).toUpperCase() + key.substring(1); +} +/** + * Support style names that may come passed in prefixed by adding permutations + * of vendor prefixes. + */ + + +var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an +// infinite loop, because it iterates over the newly added props too. + +Object.keys(isUnitlessNumber).forEach(function (prop) { + prefixes.forEach(function (prefix) { + isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; + }); +}); + +var hasReadOnlyValue = { + button: true, + checkbox: true, + image: true, + hidden: true, + radio: true, + reset: true, + submit: true +}; +function checkControlledValueProps(tagName, props) { + { + if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { + error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + } + + if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { + error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + } + } +} + +function isCustomComponent(tagName, props) { + if (tagName.indexOf('-') === -1) { + return typeof props.is === 'string'; + } + + switch (tagName) { + // These are reserved SVG and MathML elements. + // We don't mind this list too much because we expect it to never grow. + // The alternative is to track the namespace in a few places which is convoluted. + // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts + case 'annotation-xml': + case 'color-profile': + case 'font-face': + case 'font-face-src': + case 'font-face-uri': + case 'font-face-format': + case 'font-face-name': + case 'missing-glyph': + return false; + + default: + return true; + } +} + +var ariaProperties = { + 'aria-current': 0, + // state + 'aria-description': 0, + 'aria-details': 0, + 'aria-disabled': 0, + // state + 'aria-hidden': 0, + // state + 'aria-invalid': 0, + // state + 'aria-keyshortcuts': 0, + 'aria-label': 0, + 'aria-roledescription': 0, + // Widget Attributes + 'aria-autocomplete': 0, + 'aria-checked': 0, + 'aria-expanded': 0, + 'aria-haspopup': 0, + 'aria-level': 0, + 'aria-modal': 0, + 'aria-multiline': 0, + 'aria-multiselectable': 0, + 'aria-orientation': 0, + 'aria-placeholder': 0, + 'aria-pressed': 0, + 'aria-readonly': 0, + 'aria-required': 0, + 'aria-selected': 0, + 'aria-sort': 0, + 'aria-valuemax': 0, + 'aria-valuemin': 0, + 'aria-valuenow': 0, + 'aria-valuetext': 0, + // Live Region Attributes + 'aria-atomic': 0, + 'aria-busy': 0, + 'aria-live': 0, + 'aria-relevant': 0, + // Drag-and-Drop Attributes + 'aria-dropeffect': 0, + 'aria-grabbed': 0, + // Relationship Attributes + 'aria-activedescendant': 0, + 'aria-colcount': 0, + 'aria-colindex': 0, + 'aria-colspan': 0, + 'aria-controls': 0, + 'aria-describedby': 0, + 'aria-errormessage': 0, + 'aria-flowto': 0, + 'aria-labelledby': 0, + 'aria-owns': 0, + 'aria-posinset': 0, + 'aria-rowcount': 0, + 'aria-rowindex': 0, + 'aria-rowspan': 0, + 'aria-setsize': 0 +}; + +var warnedProperties = {}; +var rARIA = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'); +var rARIACamel = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$'); + +function validateProperty(tagName, name) { + { + if (hasOwnProperty.call(warnedProperties, name) && warnedProperties[name]) { + return true; + } + + if (rARIACamel.test(name)) { + var ariaName = 'aria-' + name.slice(4).toLowerCase(); + var correctName = ariaProperties.hasOwnProperty(ariaName) ? ariaName : null; // If this is an aria-* attribute, but is not listed in the known DOM + // DOM properties, then it is an invalid aria-* attribute. + + if (correctName == null) { + error('Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.', name); + + warnedProperties[name] = true; + return true; + } // aria-* attributes should be lowercase; suggest the lowercase version. + + + if (name !== correctName) { + error('Invalid ARIA attribute `%s`. Did you mean `%s`?', name, correctName); + + warnedProperties[name] = true; + return true; + } + } + + if (rARIA.test(name)) { + var lowerCasedName = name.toLowerCase(); + var standardName = ariaProperties.hasOwnProperty(lowerCasedName) ? lowerCasedName : null; // If this is an aria-* attribute, but is not listed in the known DOM + // DOM properties, then it is an invalid aria-* attribute. + + if (standardName == null) { + warnedProperties[name] = true; + return false; + } // aria-* attributes should be lowercase; suggest the lowercase version. + + + if (name !== standardName) { + error('Unknown ARIA attribute `%s`. Did you mean `%s`?', name, standardName); + + warnedProperties[name] = true; + return true; + } + } + } + + return true; +} + +function warnInvalidARIAProps(type, props) { + { + var invalidProps = []; + + for (var key in props) { + var isValid = validateProperty(type, key); + + if (!isValid) { + invalidProps.push(key); + } + } + + var unknownPropString = invalidProps.map(function (prop) { + return '`' + prop + '`'; + }).join(', '); + + if (invalidProps.length === 1) { + error('Invalid aria prop %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type); + } else if (invalidProps.length > 1) { + error('Invalid aria props %s on <%s> tag. ' + 'For details, see https://reactjs.org/link/invalid-aria-props', unknownPropString, type); + } + } +} + +function validateProperties(type, props) { + if (isCustomComponent(type, props)) { + return; + } + + warnInvalidARIAProps(type, props); +} + +var didWarnValueNull = false; +function validateProperties$1(type, props) { + { + if (type !== 'input' && type !== 'textarea' && type !== 'select') { + return; + } + + if (props != null && props.value === null && !didWarnValueNull) { + didWarnValueNull = true; + + if (type === 'select' && props.multiple) { + error('`value` prop on `%s` should not be null. ' + 'Consider using an empty array when `multiple` is set to `true` ' + 'to clear the component or `undefined` for uncontrolled components.', type); + } else { + error('`value` prop on `%s` should not be null. ' + 'Consider using an empty string to clear the component or `undefined` ' + 'for uncontrolled components.', type); + } + } + } +} + +// When adding attributes to the HTML or SVG allowed attribute list, be sure to +// also add them to this module to ensure casing and incorrect name +// warnings. +var possibleStandardNames = { + // HTML + accept: 'accept', + acceptcharset: 'acceptCharset', + 'accept-charset': 'acceptCharset', + accesskey: 'accessKey', + action: 'action', + allowfullscreen: 'allowFullScreen', + alt: 'alt', + as: 'as', + async: 'async', + autocapitalize: 'autoCapitalize', + autocomplete: 'autoComplete', + autocorrect: 'autoCorrect', + autofocus: 'autoFocus', + autoplay: 'autoPlay', + autosave: 'autoSave', + capture: 'capture', + cellpadding: 'cellPadding', + cellspacing: 'cellSpacing', + challenge: 'challenge', + charset: 'charSet', + checked: 'checked', + children: 'children', + cite: 'cite', + class: 'className', + classid: 'classID', + classname: 'className', + cols: 'cols', + colspan: 'colSpan', + content: 'content', + contenteditable: 'contentEditable', + contextmenu: 'contextMenu', + controls: 'controls', + controlslist: 'controlsList', + coords: 'coords', + crossorigin: 'crossOrigin', + dangerouslysetinnerhtml: 'dangerouslySetInnerHTML', + data: 'data', + datetime: 'dateTime', + default: 'default', + defaultchecked: 'defaultChecked', + defaultvalue: 'defaultValue', + defer: 'defer', + dir: 'dir', + disabled: 'disabled', + disablepictureinpicture: 'disablePictureInPicture', + disableremoteplayback: 'disableRemotePlayback', + download: 'download', + draggable: 'draggable', + enctype: 'encType', + enterkeyhint: 'enterKeyHint', + for: 'htmlFor', + form: 'form', + formmethod: 'formMethod', + formaction: 'formAction', + formenctype: 'formEncType', + formnovalidate: 'formNoValidate', + formtarget: 'formTarget', + frameborder: 'frameBorder', + headers: 'headers', + height: 'height', + hidden: 'hidden', + high: 'high', + href: 'href', + hreflang: 'hrefLang', + htmlfor: 'htmlFor', + httpequiv: 'httpEquiv', + 'http-equiv': 'httpEquiv', + icon: 'icon', + id: 'id', + imagesizes: 'imageSizes', + imagesrcset: 'imageSrcSet', + innerhtml: 'innerHTML', + inputmode: 'inputMode', + integrity: 'integrity', + is: 'is', + itemid: 'itemID', + itemprop: 'itemProp', + itemref: 'itemRef', + itemscope: 'itemScope', + itemtype: 'itemType', + keyparams: 'keyParams', + keytype: 'keyType', + kind: 'kind', + label: 'label', + lang: 'lang', + list: 'list', + loop: 'loop', + low: 'low', + manifest: 'manifest', + marginwidth: 'marginWidth', + marginheight: 'marginHeight', + max: 'max', + maxlength: 'maxLength', + media: 'media', + mediagroup: 'mediaGroup', + method: 'method', + min: 'min', + minlength: 'minLength', + multiple: 'multiple', + muted: 'muted', + name: 'name', + nomodule: 'noModule', + nonce: 'nonce', + novalidate: 'noValidate', + open: 'open', + optimum: 'optimum', + pattern: 'pattern', + placeholder: 'placeholder', + playsinline: 'playsInline', + poster: 'poster', + preload: 'preload', + profile: 'profile', + radiogroup: 'radioGroup', + readonly: 'readOnly', + referrerpolicy: 'referrerPolicy', + rel: 'rel', + required: 'required', + reversed: 'reversed', + role: 'role', + rows: 'rows', + rowspan: 'rowSpan', + sandbox: 'sandbox', + scope: 'scope', + scoped: 'scoped', + scrolling: 'scrolling', + seamless: 'seamless', + selected: 'selected', + shape: 'shape', + size: 'size', + sizes: 'sizes', + span: 'span', + spellcheck: 'spellCheck', + src: 'src', + srcdoc: 'srcDoc', + srclang: 'srcLang', + srcset: 'srcSet', + start: 'start', + step: 'step', + style: 'style', + summary: 'summary', + tabindex: 'tabIndex', + target: 'target', + title: 'title', + type: 'type', + usemap: 'useMap', + value: 'value', + width: 'width', + wmode: 'wmode', + wrap: 'wrap', + // SVG + about: 'about', + accentheight: 'accentHeight', + 'accent-height': 'accentHeight', + accumulate: 'accumulate', + additive: 'additive', + alignmentbaseline: 'alignmentBaseline', + 'alignment-baseline': 'alignmentBaseline', + allowreorder: 'allowReorder', + alphabetic: 'alphabetic', + amplitude: 'amplitude', + arabicform: 'arabicForm', + 'arabic-form': 'arabicForm', + ascent: 'ascent', + attributename: 'attributeName', + attributetype: 'attributeType', + autoreverse: 'autoReverse', + azimuth: 'azimuth', + basefrequency: 'baseFrequency', + baselineshift: 'baselineShift', + 'baseline-shift': 'baselineShift', + baseprofile: 'baseProfile', + bbox: 'bbox', + begin: 'begin', + bias: 'bias', + by: 'by', + calcmode: 'calcMode', + capheight: 'capHeight', + 'cap-height': 'capHeight', + clip: 'clip', + clippath: 'clipPath', + 'clip-path': 'clipPath', + clippathunits: 'clipPathUnits', + cliprule: 'clipRule', + 'clip-rule': 'clipRule', + color: 'color', + colorinterpolation: 'colorInterpolation', + 'color-interpolation': 'colorInterpolation', + colorinterpolationfilters: 'colorInterpolationFilters', + 'color-interpolation-filters': 'colorInterpolationFilters', + colorprofile: 'colorProfile', + 'color-profile': 'colorProfile', + colorrendering: 'colorRendering', + 'color-rendering': 'colorRendering', + contentscripttype: 'contentScriptType', + contentstyletype: 'contentStyleType', + cursor: 'cursor', + cx: 'cx', + cy: 'cy', + d: 'd', + datatype: 'datatype', + decelerate: 'decelerate', + descent: 'descent', + diffuseconstant: 'diffuseConstant', + direction: 'direction', + display: 'display', + divisor: 'divisor', + dominantbaseline: 'dominantBaseline', + 'dominant-baseline': 'dominantBaseline', + dur: 'dur', + dx: 'dx', + dy: 'dy', + edgemode: 'edgeMode', + elevation: 'elevation', + enablebackground: 'enableBackground', + 'enable-background': 'enableBackground', + end: 'end', + exponent: 'exponent', + externalresourcesrequired: 'externalResourcesRequired', + fill: 'fill', + fillopacity: 'fillOpacity', + 'fill-opacity': 'fillOpacity', + fillrule: 'fillRule', + 'fill-rule': 'fillRule', + filter: 'filter', + filterres: 'filterRes', + filterunits: 'filterUnits', + floodopacity: 'floodOpacity', + 'flood-opacity': 'floodOpacity', + floodcolor: 'floodColor', + 'flood-color': 'floodColor', + focusable: 'focusable', + fontfamily: 'fontFamily', + 'font-family': 'fontFamily', + fontsize: 'fontSize', + 'font-size': 'fontSize', + fontsizeadjust: 'fontSizeAdjust', + 'font-size-adjust': 'fontSizeAdjust', + fontstretch: 'fontStretch', + 'font-stretch': 'fontStretch', + fontstyle: 'fontStyle', + 'font-style': 'fontStyle', + fontvariant: 'fontVariant', + 'font-variant': 'fontVariant', + fontweight: 'fontWeight', + 'font-weight': 'fontWeight', + format: 'format', + from: 'from', + fx: 'fx', + fy: 'fy', + g1: 'g1', + g2: 'g2', + glyphname: 'glyphName', + 'glyph-name': 'glyphName', + glyphorientationhorizontal: 'glyphOrientationHorizontal', + 'glyph-orientation-horizontal': 'glyphOrientationHorizontal', + glyphorientationvertical: 'glyphOrientationVertical', + 'glyph-orientation-vertical': 'glyphOrientationVertical', + glyphref: 'glyphRef', + gradienttransform: 'gradientTransform', + gradientunits: 'gradientUnits', + hanging: 'hanging', + horizadvx: 'horizAdvX', + 'horiz-adv-x': 'horizAdvX', + horizoriginx: 'horizOriginX', + 'horiz-origin-x': 'horizOriginX', + ideographic: 'ideographic', + imagerendering: 'imageRendering', + 'image-rendering': 'imageRendering', + in2: 'in2', + in: 'in', + inlist: 'inlist', + intercept: 'intercept', + k1: 'k1', + k2: 'k2', + k3: 'k3', + k4: 'k4', + k: 'k', + kernelmatrix: 'kernelMatrix', + kernelunitlength: 'kernelUnitLength', + kerning: 'kerning', + keypoints: 'keyPoints', + keysplines: 'keySplines', + keytimes: 'keyTimes', + lengthadjust: 'lengthAdjust', + letterspacing: 'letterSpacing', + 'letter-spacing': 'letterSpacing', + lightingcolor: 'lightingColor', + 'lighting-color': 'lightingColor', + limitingconeangle: 'limitingConeAngle', + local: 'local', + markerend: 'markerEnd', + 'marker-end': 'markerEnd', + markerheight: 'markerHeight', + markermid: 'markerMid', + 'marker-mid': 'markerMid', + markerstart: 'markerStart', + 'marker-start': 'markerStart', + markerunits: 'markerUnits', + markerwidth: 'markerWidth', + mask: 'mask', + maskcontentunits: 'maskContentUnits', + maskunits: 'maskUnits', + mathematical: 'mathematical', + mode: 'mode', + numoctaves: 'numOctaves', + offset: 'offset', + opacity: 'opacity', + operator: 'operator', + order: 'order', + orient: 'orient', + orientation: 'orientation', + origin: 'origin', + overflow: 'overflow', + overlineposition: 'overlinePosition', + 'overline-position': 'overlinePosition', + overlinethickness: 'overlineThickness', + 'overline-thickness': 'overlineThickness', + paintorder: 'paintOrder', + 'paint-order': 'paintOrder', + panose1: 'panose1', + 'panose-1': 'panose1', + pathlength: 'pathLength', + patterncontentunits: 'patternContentUnits', + patterntransform: 'patternTransform', + patternunits: 'patternUnits', + pointerevents: 'pointerEvents', + 'pointer-events': 'pointerEvents', + points: 'points', + pointsatx: 'pointsAtX', + pointsaty: 'pointsAtY', + pointsatz: 'pointsAtZ', + prefix: 'prefix', + preservealpha: 'preserveAlpha', + preserveaspectratio: 'preserveAspectRatio', + primitiveunits: 'primitiveUnits', + property: 'property', + r: 'r', + radius: 'radius', + refx: 'refX', + refy: 'refY', + renderingintent: 'renderingIntent', + 'rendering-intent': 'renderingIntent', + repeatcount: 'repeatCount', + repeatdur: 'repeatDur', + requiredextensions: 'requiredExtensions', + requiredfeatures: 'requiredFeatures', + resource: 'resource', + restart: 'restart', + result: 'result', + results: 'results', + rotate: 'rotate', + rx: 'rx', + ry: 'ry', + scale: 'scale', + security: 'security', + seed: 'seed', + shaperendering: 'shapeRendering', + 'shape-rendering': 'shapeRendering', + slope: 'slope', + spacing: 'spacing', + specularconstant: 'specularConstant', + specularexponent: 'specularExponent', + speed: 'speed', + spreadmethod: 'spreadMethod', + startoffset: 'startOffset', + stddeviation: 'stdDeviation', + stemh: 'stemh', + stemv: 'stemv', + stitchtiles: 'stitchTiles', + stopcolor: 'stopColor', + 'stop-color': 'stopColor', + stopopacity: 'stopOpacity', + 'stop-opacity': 'stopOpacity', + strikethroughposition: 'strikethroughPosition', + 'strikethrough-position': 'strikethroughPosition', + strikethroughthickness: 'strikethroughThickness', + 'strikethrough-thickness': 'strikethroughThickness', + string: 'string', + stroke: 'stroke', + strokedasharray: 'strokeDasharray', + 'stroke-dasharray': 'strokeDasharray', + strokedashoffset: 'strokeDashoffset', + 'stroke-dashoffset': 'strokeDashoffset', + strokelinecap: 'strokeLinecap', + 'stroke-linecap': 'strokeLinecap', + strokelinejoin: 'strokeLinejoin', + 'stroke-linejoin': 'strokeLinejoin', + strokemiterlimit: 'strokeMiterlimit', + 'stroke-miterlimit': 'strokeMiterlimit', + strokewidth: 'strokeWidth', + 'stroke-width': 'strokeWidth', + strokeopacity: 'strokeOpacity', + 'stroke-opacity': 'strokeOpacity', + suppresscontenteditablewarning: 'suppressContentEditableWarning', + suppresshydrationwarning: 'suppressHydrationWarning', + surfacescale: 'surfaceScale', + systemlanguage: 'systemLanguage', + tablevalues: 'tableValues', + targetx: 'targetX', + targety: 'targetY', + textanchor: 'textAnchor', + 'text-anchor': 'textAnchor', + textdecoration: 'textDecoration', + 'text-decoration': 'textDecoration', + textlength: 'textLength', + textrendering: 'textRendering', + 'text-rendering': 'textRendering', + to: 'to', + transform: 'transform', + typeof: 'typeof', + u1: 'u1', + u2: 'u2', + underlineposition: 'underlinePosition', + 'underline-position': 'underlinePosition', + underlinethickness: 'underlineThickness', + 'underline-thickness': 'underlineThickness', + unicode: 'unicode', + unicodebidi: 'unicodeBidi', + 'unicode-bidi': 'unicodeBidi', + unicoderange: 'unicodeRange', + 'unicode-range': 'unicodeRange', + unitsperem: 'unitsPerEm', + 'units-per-em': 'unitsPerEm', + unselectable: 'unselectable', + valphabetic: 'vAlphabetic', + 'v-alphabetic': 'vAlphabetic', + values: 'values', + vectoreffect: 'vectorEffect', + 'vector-effect': 'vectorEffect', + version: 'version', + vertadvy: 'vertAdvY', + 'vert-adv-y': 'vertAdvY', + vertoriginx: 'vertOriginX', + 'vert-origin-x': 'vertOriginX', + vertoriginy: 'vertOriginY', + 'vert-origin-y': 'vertOriginY', + vhanging: 'vHanging', + 'v-hanging': 'vHanging', + videographic: 'vIdeographic', + 'v-ideographic': 'vIdeographic', + viewbox: 'viewBox', + viewtarget: 'viewTarget', + visibility: 'visibility', + vmathematical: 'vMathematical', + 'v-mathematical': 'vMathematical', + vocab: 'vocab', + widths: 'widths', + wordspacing: 'wordSpacing', + 'word-spacing': 'wordSpacing', + writingmode: 'writingMode', + 'writing-mode': 'writingMode', + x1: 'x1', + x2: 'x2', + x: 'x', + xchannelselector: 'xChannelSelector', + xheight: 'xHeight', + 'x-height': 'xHeight', + xlinkactuate: 'xlinkActuate', + 'xlink:actuate': 'xlinkActuate', + xlinkarcrole: 'xlinkArcrole', + 'xlink:arcrole': 'xlinkArcrole', + xlinkhref: 'xlinkHref', + 'xlink:href': 'xlinkHref', + xlinkrole: 'xlinkRole', + 'xlink:role': 'xlinkRole', + xlinkshow: 'xlinkShow', + 'xlink:show': 'xlinkShow', + xlinktitle: 'xlinkTitle', + 'xlink:title': 'xlinkTitle', + xlinktype: 'xlinkType', + 'xlink:type': 'xlinkType', + xmlbase: 'xmlBase', + 'xml:base': 'xmlBase', + xmllang: 'xmlLang', + 'xml:lang': 'xmlLang', + xmlns: 'xmlns', + 'xml:space': 'xmlSpace', + xmlnsxlink: 'xmlnsXlink', + 'xmlns:xlink': 'xmlnsXlink', + xmlspace: 'xmlSpace', + y1: 'y1', + y2: 'y2', + y: 'y', + ychannelselector: 'yChannelSelector', + z: 'z', + zoomandpan: 'zoomAndPan' +}; + +var validateProperty$1 = function () {}; + +{ + var warnedProperties$1 = {}; + var EVENT_NAME_REGEX = /^on./; + var INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/; + var rARIA$1 = new RegExp('^(aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$'); + var rARIACamel$1 = new RegExp('^(aria)[A-Z][' + ATTRIBUTE_NAME_CHAR + ']*$'); + + validateProperty$1 = function (tagName, name, value, eventRegistry) { + if (hasOwnProperty.call(warnedProperties$1, name) && warnedProperties$1[name]) { + return true; + } + + var lowerCasedName = name.toLowerCase(); + + if (lowerCasedName === 'onfocusin' || lowerCasedName === 'onfocusout') { + error('React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.'); + + warnedProperties$1[name] = true; + return true; + } // We can't rely on the event system being injected on the server. + + + if (eventRegistry != null) { + var registrationNameDependencies = eventRegistry.registrationNameDependencies, + possibleRegistrationNames = eventRegistry.possibleRegistrationNames; + + if (registrationNameDependencies.hasOwnProperty(name)) { + return true; + } + + var registrationName = possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? possibleRegistrationNames[lowerCasedName] : null; + + if (registrationName != null) { + error('Invalid event handler property `%s`. Did you mean `%s`?', name, registrationName); + + warnedProperties$1[name] = true; + return true; + } + + if (EVENT_NAME_REGEX.test(name)) { + error('Unknown event handler property `%s`. It will be ignored.', name); + + warnedProperties$1[name] = true; + return true; + } + } else if (EVENT_NAME_REGEX.test(name)) { + // If no event plugins have been injected, we are in a server environment. + // So we can't tell if the event name is correct for sure, but we can filter + // out known bad ones like `onclick`. We can't suggest a specific replacement though. + if (INVALID_EVENT_NAME_REGEX.test(name)) { + error('Invalid event handler property `%s`. ' + 'React events use the camelCase naming convention, for example `onClick`.', name); + } + + warnedProperties$1[name] = true; + return true; + } // Let the ARIA attribute hook validate ARIA attributes + + + if (rARIA$1.test(name) || rARIACamel$1.test(name)) { + return true; + } + + if (lowerCasedName === 'innerhtml') { + error('Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.'); + + warnedProperties$1[name] = true; + return true; + } + + if (lowerCasedName === 'aria') { + error('The `aria` attribute is reserved for future use in React. ' + 'Pass individual `aria-` attributes instead.'); + + warnedProperties$1[name] = true; + return true; + } + + if (lowerCasedName === 'is' && value !== null && value !== undefined && typeof value !== 'string') { + error('Received a `%s` for a string attribute `is`. If this is expected, cast ' + 'the value to a string.', typeof value); + + warnedProperties$1[name] = true; + return true; + } + + if (typeof value === 'number' && isNaN(value)) { + error('Received NaN for the `%s` attribute. If this is expected, cast ' + 'the value to a string.', name); + + warnedProperties$1[name] = true; + return true; + } + + var propertyInfo = getPropertyInfo(name); + var isReserved = propertyInfo !== null && propertyInfo.type === RESERVED; // Known attributes should match the casing specified in the property config. + + if (possibleStandardNames.hasOwnProperty(lowerCasedName)) { + var standardName = possibleStandardNames[lowerCasedName]; + + if (standardName !== name) { + error('Invalid DOM property `%s`. Did you mean `%s`?', name, standardName); + + warnedProperties$1[name] = true; + return true; + } + } else if (!isReserved && name !== lowerCasedName) { + // Unknown attributes should have lowercase casing since that's how they + // will be cased anyway with server rendering. + error('React does not recognize the `%s` prop on a DOM element. If you ' + 'intentionally want it to appear in the DOM as a custom ' + 'attribute, spell it as lowercase `%s` instead. ' + 'If you accidentally passed it from a parent component, remove ' + 'it from the DOM element.', name, lowerCasedName); + + warnedProperties$1[name] = true; + return true; + } + + if (typeof value === 'boolean' && shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { + if (value) { + error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.', value, name, name, value, name); + } else { + error('Received `%s` for a non-boolean attribute `%s`.\n\n' + 'If you want to write it to the DOM, pass a string instead: ' + '%s="%s" or %s={value.toString()}.\n\n' + 'If you used to conditionally omit it with %s={condition && value}, ' + 'pass %s={condition ? value : undefined} instead.', value, name, name, value, name, name, name); + } + + warnedProperties$1[name] = true; + return true; + } // Now that we've validated casing, do not validate + // data types for reserved props + + + if (isReserved) { + return true; + } // Warn when a known attribute is a bad type + + + if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, false)) { + warnedProperties$1[name] = true; + return false; + } // Warn when passing the strings 'false' or 'true' into a boolean prop + + + if ((value === 'false' || value === 'true') && propertyInfo !== null && propertyInfo.type === BOOLEAN) { + error('Received the string `%s` for the boolean attribute `%s`. ' + '%s ' + 'Did you mean %s={%s}?', value, name, value === 'false' ? 'The browser will interpret it as a truthy value.' : 'Although this works, it will not work as expected if you pass the string "false".', name, value); + + warnedProperties$1[name] = true; + return true; + } + + return true; + }; +} + +var warnUnknownProperties = function (type, props, eventRegistry) { + { + var unknownProps = []; + + for (var key in props) { + var isValid = validateProperty$1(type, key, props[key], eventRegistry); + + if (!isValid) { + unknownProps.push(key); + } + } + + var unknownPropString = unknownProps.map(function (prop) { + return '`' + prop + '`'; + }).join(', '); + + if (unknownProps.length === 1) { + error('Invalid value for prop %s on <%s> tag. Either remove it from the element, ' + 'or pass a string or number value to keep it in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type); + } else if (unknownProps.length > 1) { + error('Invalid values for props %s on <%s> tag. Either remove them from the element, ' + 'or pass a string or number value to keep them in the DOM. ' + 'For details, see https://reactjs.org/link/attribute-behavior ', unknownPropString, type); + } + } +}; + +function validateProperties$2(type, props, eventRegistry) { + if (isCustomComponent(type, props)) { + return; + } + + warnUnknownProperties(type, props, eventRegistry); +} + +var warnValidStyle = function () {}; + +{ + // 'msTransform' is correct, but the other prefixes should be capitalized + var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; + var msPattern = /^-ms-/; + var hyphenPattern = /-(.)/g; // style values shouldn't contain a semicolon + + var badStyleValueWithSemicolonPattern = /;\s*$/; + var warnedStyleNames = {}; + var warnedStyleValues = {}; + var warnedForNaNValue = false; + var warnedForInfinityValue = false; + + var camelize = function (string) { + return string.replace(hyphenPattern, function (_, character) { + return character.toUpperCase(); + }); + }; + + var warnHyphenatedStyleName = function (name) { + if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { + return; + } + + warnedStyleNames[name] = true; + + error('Unsupported style property %s. Did you mean %s?', name, // As Andi Smith suggests + // (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix + // is converted to lowercase `ms`. + camelize(name.replace(msPattern, 'ms-'))); + }; + + var warnBadVendoredStyleName = function (name) { + if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { + return; + } + + warnedStyleNames[name] = true; + + error('Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)); + }; + + var warnStyleValueWithSemicolon = function (name, value) { + if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { + return; + } + + warnedStyleValues[value] = true; + + error("Style property values shouldn't contain a semicolon. " + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')); + }; + + var warnStyleValueIsNaN = function (name, value) { + if (warnedForNaNValue) { + return; + } + + warnedForNaNValue = true; + + error('`NaN` is an invalid value for the `%s` css style property.', name); + }; + + var warnStyleValueIsInfinity = function (name, value) { + if (warnedForInfinityValue) { + return; + } + + warnedForInfinityValue = true; + + error('`Infinity` is an invalid value for the `%s` css style property.', name); + }; + + warnValidStyle = function (name, value) { + if (name.indexOf('-') > -1) { + warnHyphenatedStyleName(name); + } else if (badVendoredStyleNamePattern.test(name)) { + warnBadVendoredStyleName(name); + } else if (badStyleValueWithSemicolonPattern.test(value)) { + warnStyleValueWithSemicolon(name, value); + } + + if (typeof value === 'number') { + if (isNaN(value)) { + warnStyleValueIsNaN(name, value); + } else if (!isFinite(value)) { + warnStyleValueIsInfinity(name, value); + } + } + }; +} + +var warnValidStyle$1 = warnValidStyle; + +// code copied and modified from escape-html +var matchHtmlRegExp = /["'&<>]/; +/** + * Escapes special characters and HTML entities in a given html string. + * + * @param {string} string HTML string to escape for later insertion + * @return {string} + * @public + */ + +function escapeHtml(string) { + { + checkHtmlStringCoercion(string); + } + + var str = '' + string; + var match = matchHtmlRegExp.exec(str); + + if (!match) { + return str; + } + + var escape; + var html = ''; + var index; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: + // " + escape = '"'; + break; + + case 38: + // & + escape = '&'; + break; + + case 39: + // ' + escape = '''; // modified from escape-html; used to be ''' + + break; + + case 60: + // < + escape = '<'; + break; + + case 62: + // > + escape = '>'; + break; + + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + + return lastIndex !== index ? html + str.substring(lastIndex, index) : html; +} // end code copied and modified from escape-html + +/** + * Escapes text to prevent scripting attacks. + * + * @param {*} text Text value to escape. + * @return {string} An escaped string. + */ + + +function escapeTextForBrowser(text) { + if (typeof text === 'boolean' || typeof text === 'number') { + // this shortcircuit helps perf for types that we know will never have + // special characters, especially given that this function is used often + // for numeric dom ids. + return '' + text; + } + + return escapeHtml(text); +} + +var uppercasePattern = /([A-Z])/g; +var msPattern$1 = /^ms-/; +/** + * Hyphenates a camelcased CSS property name, for example: + * + * > hyphenateStyleName('backgroundColor') + * < "background-color" + * > hyphenateStyleName('MozTransition') + * < "-moz-transition" + * > hyphenateStyleName('msTransition') + * < "-ms-transition" + * + * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix + * is converted to `-ms-`. + */ + +function hyphenateStyleName(name) { + return name.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern$1, '-ms-'); +} + +// and any newline or tab are filtered out as if they're not part of the URL. +// https://url.spec.whatwg.org/#url-parsing +// Tab or newline are defined as \r\n\t: +// https://infra.spec.whatwg.org/#ascii-tab-or-newline +// A C0 control is a code point in the range \u0000 NULL to \u001F +// INFORMATION SEPARATOR ONE, inclusive: +// https://infra.spec.whatwg.org/#c0-control-or-space + +/* eslint-disable max-len */ + +var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; +var didWarn = false; + +function sanitizeURL(url) { + { + if (!didWarn && isJavaScriptProtocol.test(url)) { + didWarn = true; + + error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url)); + } + } +} + +var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare + +function isArray(a) { + return isArrayImpl(a); +} + +var startInlineScript = stringToPrecomputedChunk(''); +var startScriptSrc = stringToPrecomputedChunk(''); +/** + * This escaping function is designed to work with bootstrapScriptContent only. + * because we know we are escaping the entire script. We can avoid for instance + * escaping html comment string sequences that are valid javascript as well because + * if there are no sebsequent '); +function writeCompletedSegmentInstruction(destination, responseState, contentSegmentID) { + writeChunk(destination, responseState.startInlineScript); + + if (!responseState.sentCompleteSegmentFunction) { + // The first time we write this, we'll need to include the full implementation. + responseState.sentCompleteSegmentFunction = true; + writeChunk(destination, completeSegmentScript1Full); + } else { + // Future calls can just reuse the same function. + writeChunk(destination, completeSegmentScript1Partial); + } + + writeChunk(destination, responseState.segmentPrefix); + var formattedID = stringToChunk(contentSegmentID.toString(16)); + writeChunk(destination, formattedID); + writeChunk(destination, completeSegmentScript2); + writeChunk(destination, responseState.placeholderPrefix); + writeChunk(destination, formattedID); + return writeChunkAndReturn(destination, completeSegmentScript3); +} +var completeBoundaryScript1Full = stringToPrecomputedChunk(completeBoundaryFunction + ';$RC("'); +var completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC("'); +var completeBoundaryScript2 = stringToPrecomputedChunk('","'); +var completeBoundaryScript3 = stringToPrecomputedChunk('")'); +function writeCompletedBoundaryInstruction(destination, responseState, boundaryID, contentSegmentID) { + writeChunk(destination, responseState.startInlineScript); + + if (!responseState.sentCompleteBoundaryFunction) { + // The first time we write this, we'll need to include the full implementation. + responseState.sentCompleteBoundaryFunction = true; + writeChunk(destination, completeBoundaryScript1Full); + } else { + // Future calls can just reuse the same function. + writeChunk(destination, completeBoundaryScript1Partial); + } + + if (boundaryID === null) { + throw new Error('An ID must have been assigned before we can complete the boundary.'); + } + + var formattedContentID = stringToChunk(contentSegmentID.toString(16)); + writeChunk(destination, boundaryID); + writeChunk(destination, completeBoundaryScript2); + writeChunk(destination, responseState.segmentPrefix); + writeChunk(destination, formattedContentID); + return writeChunkAndReturn(destination, completeBoundaryScript3); +} +var clientRenderScript1Full = stringToPrecomputedChunk(clientRenderFunction + ';$RX("'); +var clientRenderScript1Partial = stringToPrecomputedChunk('$RX("'); +var clientRenderScript1A = stringToPrecomputedChunk('"'); +var clientRenderScript2 = stringToPrecomputedChunk(')'); +var clientRenderErrorScriptArgInterstitial = stringToPrecomputedChunk(','); +function writeClientRenderBoundaryInstruction(destination, responseState, boundaryID, errorDigest, errorMessage, errorComponentStack) { + writeChunk(destination, responseState.startInlineScript); + + if (!responseState.sentClientRenderFunction) { + // The first time we write this, we'll need to include the full implementation. + responseState.sentClientRenderFunction = true; + writeChunk(destination, clientRenderScript1Full); + } else { + // Future calls can just reuse the same function. + writeChunk(destination, clientRenderScript1Partial); + } + + if (boundaryID === null) { + throw new Error('An ID must have been assigned before we can complete the boundary.'); + } + + writeChunk(destination, boundaryID); + writeChunk(destination, clientRenderScript1A); + + if (errorDigest || errorMessage || errorComponentStack) { + writeChunk(destination, clientRenderErrorScriptArgInterstitial); + writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorDigest || ''))); + } + + if (errorMessage || errorComponentStack) { + writeChunk(destination, clientRenderErrorScriptArgInterstitial); + writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorMessage || ''))); + } + + if (errorComponentStack) { + writeChunk(destination, clientRenderErrorScriptArgInterstitial); + writeChunk(destination, stringToChunk(escapeJSStringsForInstructionScripts(errorComponentStack))); + } + + return writeChunkAndReturn(destination, clientRenderScript2); +} +var regexForJSStringsInScripts = /[<\u2028\u2029]/g; + +function escapeJSStringsForInstructionScripts(input) { + var escaped = JSON.stringify(input); + return escaped.replace(regexForJSStringsInScripts, function (match) { + switch (match) { + // santizing breaking out of strings and script tags + case '<': + return "\\u003c"; + + case "\u2028": + return "\\u2028"; + + case "\u2029": + return "\\u2029"; + + default: + { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error('escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React'); + } + } + }); +} + +function createResponseState$1(generateStaticMarkup, identifierPrefix) { + var responseState = createResponseState(identifierPrefix, undefined); + return { + // Keep this in sync with ReactDOMServerFormatConfig + bootstrapChunks: responseState.bootstrapChunks, + startInlineScript: responseState.startInlineScript, + placeholderPrefix: responseState.placeholderPrefix, + segmentPrefix: responseState.segmentPrefix, + boundaryPrefix: responseState.boundaryPrefix, + idPrefix: responseState.idPrefix, + nextSuspenseID: responseState.nextSuspenseID, + sentCompleteSegmentFunction: responseState.sentCompleteSegmentFunction, + sentCompleteBoundaryFunction: responseState.sentCompleteBoundaryFunction, + sentClientRenderFunction: responseState.sentClientRenderFunction, + // This is an extra field for the legacy renderer + generateStaticMarkup: generateStaticMarkup + }; +} +function createRootFormatContext() { + return { + insertionMode: HTML_MODE, + // We skip the root mode because we don't want to emit the DOCTYPE in legacy mode. + selectedValue: null + }; +} +function pushTextInstance$1(target, text, responseState, textEmbedded) { + if (responseState.generateStaticMarkup) { + target.push(stringToChunk(escapeTextForBrowser(text))); + return false; + } else { + return pushTextInstance(target, text, responseState, textEmbedded); + } +} +function pushSegmentFinale$1(target, responseState, lastPushedText, textEmbedded) { + if (responseState.generateStaticMarkup) { + return; + } else { + return pushSegmentFinale(target, responseState, lastPushedText, textEmbedded); + } +} +function writeStartCompletedSuspenseBoundary$1(destination, responseState) { + if (responseState.generateStaticMarkup) { + // A completed boundary is done and doesn't need a representation in the HTML + // if we're not going to be hydrating it. + return true; + } + + return writeStartCompletedSuspenseBoundary(destination); +} +function writeStartClientRenderedSuspenseBoundary$1(destination, responseState, // flushing these error arguments are not currently supported in this legacy streaming format. +errorDigest, errorMessage, errorComponentStack) { + if (responseState.generateStaticMarkup) { + // A client rendered boundary is done and doesn't need a representation in the HTML + // since we'll never hydrate it. This is arguably an error in static generation. + return true; + } + + return writeStartClientRenderedSuspenseBoundary(destination, responseState, errorDigest, errorMessage, errorComponentStack); +} +function writeEndCompletedSuspenseBoundary$1(destination, responseState) { + if (responseState.generateStaticMarkup) { + return true; + } + + return writeEndCompletedSuspenseBoundary(destination); +} +function writeEndClientRenderedSuspenseBoundary$1(destination, responseState) { + if (responseState.generateStaticMarkup) { + return true; + } + + return writeEndClientRenderedSuspenseBoundary(destination); +} + +var assign = Object.assign; + +// ATTENTION +// When adding new symbols to this file, +// Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' +// The Symbol used to tag the ReactElement-like types. +var REACT_ELEMENT_TYPE = Symbol.for('react.element'); +var REACT_PORTAL_TYPE = Symbol.for('react.portal'); +var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'); +var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'); +var REACT_PROFILER_TYPE = Symbol.for('react.profiler'); +var REACT_PROVIDER_TYPE = Symbol.for('react.provider'); +var REACT_CONTEXT_TYPE = Symbol.for('react.context'); +var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'); +var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'); +var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'); +var REACT_MEMO_TYPE = Symbol.for('react.memo'); +var REACT_LAZY_TYPE = Symbol.for('react.lazy'); +var REACT_SCOPE_TYPE = Symbol.for('react.scope'); +var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for('react.debug_trace_mode'); +var REACT_LEGACY_HIDDEN_TYPE = Symbol.for('react.legacy_hidden'); +var REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED = Symbol.for('react.default_value'); +var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +function getWrappedName(outerType, innerType, wrapperName) { + var displayName = outerType.displayName; + + if (displayName) { + return displayName; + } + + var functionName = innerType.displayName || innerType.name || ''; + return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName; +} // Keep in sync with react-reconciler/getComponentNameFromFiber + + +function getContextName(type) { + return type.displayName || 'Context'; +} // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead. + + +function getComponentNameFromType(type) { + if (type == null) { + // Host root, text node or just invalid type. + return null; + } + + { + if (typeof type.tag === 'number') { + error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.'); + } + } + + if (typeof type === 'function') { + return type.displayName || type.name || null; + } + + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_FRAGMENT_TYPE: + return 'Fragment'; + + case REACT_PORTAL_TYPE: + return 'Portal'; + + case REACT_PROFILER_TYPE: + return 'Profiler'; + + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; + + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + var context = type; + return getContextName(context) + '.Consumer'; + + case REACT_PROVIDER_TYPE: + var provider = type; + return getContextName(provider._context) + '.Provider'; + + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); + + case REACT_MEMO_TYPE: + var outerName = type.displayName || null; + + if (outerName !== null) { + return outerName; + } + + return getComponentNameFromType(type.type) || 'Memo'; + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + return getComponentNameFromType(init(payload)); + } catch (x) { + return null; + } + } + + // eslint-disable-next-line no-fallthrough + } + } + + return null; +} + +// Helpers to patch console.logs to avoid logging during side-effect free +// replaying on render function. This currently only patches the object +// lazily which won't cover if the log function was extracted eagerly. +// We could also eagerly patch the method. +var disabledDepth = 0; +var prevLog; +var prevInfo; +var prevWarn; +var prevError; +var prevGroup; +var prevGroupCollapsed; +var prevGroupEnd; + +function disabledLog() {} + +disabledLog.__reactDisabledLog = true; +function disableLogs() { + { + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + prevLog = console.log; + prevInfo = console.info; + prevWarn = console.warn; + prevError = console.error; + prevGroup = console.group; + prevGroupCollapsed = console.groupCollapsed; + prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099 + + var props = { + configurable: true, + enumerable: true, + value: disabledLog, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + info: props, + log: props, + warn: props, + error: props, + group: props, + groupCollapsed: props, + groupEnd: props + }); + /* eslint-enable react-internal/no-production-logging */ + } + + disabledDepth++; + } +} +function reenableLogs() { + { + disabledDepth--; + + if (disabledDepth === 0) { + /* eslint-disable react-internal/no-production-logging */ + var props = { + configurable: true, + enumerable: true, + writable: true + }; // $FlowFixMe Flow thinks console is immutable. + + Object.defineProperties(console, { + log: assign({}, props, { + value: prevLog + }), + info: assign({}, props, { + value: prevInfo + }), + warn: assign({}, props, { + value: prevWarn + }), + error: assign({}, props, { + value: prevError + }), + group: assign({}, props, { + value: prevGroup + }), + groupCollapsed: assign({}, props, { + value: prevGroupCollapsed + }), + groupEnd: assign({}, props, { + value: prevGroupEnd + }) + }); + /* eslint-enable react-internal/no-production-logging */ + } + + if (disabledDepth < 0) { + error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.'); + } + } +} + +var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; +var prefix; +function describeBuiltInComponentFrame(name, source, ownerFn) { + { + if (prefix === undefined) { + // Extract the VM specific prefix used by each line. + try { + throw Error(); + } catch (x) { + var match = x.stack.trim().match(/\n( *(at )?)/); + prefix = match && match[1] || ''; + } + } // We use the prefix to ensure our stacks line up with native stack frames. + + + return '\n' + prefix + name; + } +} +var reentry = false; +var componentFrameCache; + +{ + var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; + componentFrameCache = new PossiblyWeakMap(); +} + +function describeNativeComponentFrame(fn, construct) { + // If something asked for a stack inside a fake render, it should get ignored. + if ( !fn || reentry) { + return ''; + } + + { + var frame = componentFrameCache.get(fn); + + if (frame !== undefined) { + return frame; + } + } + + var control; + reentry = true; + var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined. + + Error.prepareStackTrace = undefined; + var previousDispatcher; + + { + previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function + // for warnings. + + ReactCurrentDispatcher.current = null; + disableLogs(); + } + + try { + // This should throw. + if (construct) { + // Something should be setting the props in the constructor. + var Fake = function () { + throw Error(); + }; // $FlowFixMe + + + Object.defineProperty(Fake.prototype, 'props', { + set: function () { + // We use a throwing setter instead of frozen or non-writable props + // because that won't throw in a non-strict mode function. + throw Error(); + } + }); + + if (typeof Reflect === 'object' && Reflect.construct) { + // We construct a different control for this case to include any extra + // frames added by the construct call. + try { + Reflect.construct(Fake, []); + } catch (x) { + control = x; + } + + Reflect.construct(fn, [], Fake); + } else { + try { + Fake.call(); + } catch (x) { + control = x; + } + + fn.call(Fake.prototype); + } + } else { + try { + throw Error(); + } catch (x) { + control = x; + } + + fn(); + } + } catch (sample) { + // This is inlined manually because closure doesn't do it for us. + if (sample && control && typeof sample.stack === 'string') { + // This extracts the first frame from the sample that isn't also in the control. + // Skipping one frame that we assume is the frame that calls the two. + var sampleLines = sample.stack.split('\n'); + var controlLines = control.stack.split('\n'); + var s = sampleLines.length - 1; + var c = controlLines.length - 1; + + while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { + // We expect at least one stack frame to be shared. + // Typically this will be the root most one. However, stack frames may be + // cut off due to maximum stack limits. In this case, one maybe cut off + // earlier than the other. We assume that the sample is longer or the same + // and there for cut off earlier. So we should find the root most frame in + // the sample somewhere in the control. + c--; + } + + for (; s >= 1 && c >= 0; s--, c--) { + // Next we find the first one that isn't the same which should be the + // frame that called our sample function and the control. + if (sampleLines[s] !== controlLines[c]) { + // In V8, the first line is describing the message but other VMs don't. + // If we're about to return the first line, and the control is also on the same + // line, that's a pretty good indicator that our sample threw at same line as + // the control. I.e. before we entered the sample frame. So we ignore this result. + // This can happen if you passed a class to function component, or non-function. + if (s !== 1 || c !== 1) { + do { + s--; + c--; // We may still have similar intermediate frames from the construct call. + // The next one that isn't the same should be our match though. + + if (c < 0 || sampleLines[s] !== controlLines[c]) { + // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier. + var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "" + // but we have a user-provided "displayName" + // splice it in to make the stack more readable. + + + if (fn.displayName && _frame.includes('')) { + _frame = _frame.replace('', fn.displayName); + } + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, _frame); + } + } // Return the line we found. + + + return _frame; + } + } while (s >= 1 && c >= 0); + } + + break; + } + } + } + } finally { + reentry = false; + + { + ReactCurrentDispatcher.current = previousDispatcher; + reenableLogs(); + } + + Error.prepareStackTrace = previousPrepareStackTrace; + } // Fallback to just using the name if we couldn't make it throw. + + + var name = fn ? fn.displayName || fn.name : ''; + var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ''; + + { + if (typeof fn === 'function') { + componentFrameCache.set(fn, syntheticFrame); + } + } + + return syntheticFrame; +} + +function describeClassComponentFrame(ctor, source, ownerFn) { + { + return describeNativeComponentFrame(ctor, true); + } +} +function describeFunctionComponentFrame(fn, source, ownerFn) { + { + return describeNativeComponentFrame(fn, false); + } +} + +function shouldConstruct(Component) { + var prototype = Component.prototype; + return !!(prototype && prototype.isReactComponent); +} + +function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { + + if (type == null) { + return ''; + } + + if (typeof type === 'function') { + { + return describeNativeComponentFrame(type, shouldConstruct(type)); + } + } + + if (typeof type === 'string') { + return describeBuiltInComponentFrame(type); + } + + switch (type) { + case REACT_SUSPENSE_TYPE: + return describeBuiltInComponentFrame('Suspense'); + + case REACT_SUSPENSE_LIST_TYPE: + return describeBuiltInComponentFrame('SuspenseList'); + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + return describeFunctionComponentFrame(type.render); + + case REACT_MEMO_TYPE: + // Memo may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); + + case REACT_LAZY_TYPE: + { + var lazyComponent = type; + var payload = lazyComponent._payload; + var init = lazyComponent._init; + + try { + // Lazy may contain any component type so we recursively resolve it. + return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); + } catch (x) {} + } + } + } + + return ''; +} + +var loggedTypeFailures = {}; +var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + +function setCurrentlyValidatingElement(element) { + { + if (element) { + var owner = element._owner; + var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); + ReactDebugCurrentFrame.setExtraStackFrame(stack); + } else { + ReactDebugCurrentFrame.setExtraStackFrame(null); + } + } +} + +function checkPropTypes(typeSpecs, values, location, componentName, element) { + { + // $FlowFixMe This is okay but Flow doesn't know it. + var has = Function.call.bind(hasOwnProperty); + + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + // eslint-disable-next-line react-internal/prod-error-codes + var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'); + err.name = 'Invariant Violation'; + throw err; + } + + error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'); + } catch (ex) { + error$1 = ex; + } + + if (error$1 && !(error$1 instanceof Error)) { + setCurrentlyValidatingElement(element); + + error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1); + + setCurrentlyValidatingElement(null); + } + + if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error$1.message] = true; + setCurrentlyValidatingElement(element); + + error('Failed %s type: %s', location, error$1.message); + + setCurrentlyValidatingElement(null); + } + } + } + } +} + +var warnedAboutMissingGetChildContext; + +{ + warnedAboutMissingGetChildContext = {}; +} + +var emptyContextObject = {}; + +{ + Object.freeze(emptyContextObject); +} + +function getMaskedContext(type, unmaskedContext) { + { + var contextTypes = type.contextTypes; + + if (!contextTypes) { + return emptyContextObject; + } + + var context = {}; + + for (var key in contextTypes) { + context[key] = unmaskedContext[key]; + } + + { + var name = getComponentNameFromType(type) || 'Unknown'; + checkPropTypes(contextTypes, context, 'context', name); + } + + return context; + } +} +function processChildContext(instance, type, parentContext, childContextTypes) { + { + // TODO (bvaughn) Replace this behavior with an invariant() in the future. + // It has only been added in Fiber to match the (unintentional) behavior in Stack. + if (typeof instance.getChildContext !== 'function') { + { + var componentName = getComponentNameFromType(type) || 'Unknown'; + + if (!warnedAboutMissingGetChildContext[componentName]) { + warnedAboutMissingGetChildContext[componentName] = true; + + error('%s.childContextTypes is specified but there is no getChildContext() method ' + 'on the instance. You can either define getChildContext() on %s or remove ' + 'childContextTypes from it.', componentName, componentName); + } + } + + return parentContext; + } + + var childContext = instance.getChildContext(); + + for (var contextKey in childContext) { + if (!(contextKey in childContextTypes)) { + throw new Error((getComponentNameFromType(type) || 'Unknown') + ".getChildContext(): key \"" + contextKey + "\" is not defined in childContextTypes."); + } + } + + { + var name = getComponentNameFromType(type) || 'Unknown'; + checkPropTypes(childContextTypes, childContext, 'child context', name); + } + + return assign({}, parentContext, childContext); + } +} + +var rendererSigil; + +{ + // Use this to detect multiple renderers using the same context + rendererSigil = {}; +} // Used to store the parent path of all context overrides in a shared linked list. +// Forming a reverse tree. + + +var rootContextSnapshot = null; // We assume that this runtime owns the "current" field on all ReactContext instances. +// This global (actually thread local) state represents what state all those "current", +// fields are currently in. + +var currentActiveSnapshot = null; + +function popNode(prev) { + { + prev.context._currentValue2 = prev.parentValue; + } +} + +function pushNode(next) { + { + next.context._currentValue2 = next.value; + } +} + +function popToNearestCommonAncestor(prev, next) { + if (prev === next) ; else { + popNode(prev); + var parentPrev = prev.parent; + var parentNext = next.parent; + + if (parentPrev === null) { + if (parentNext !== null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + } else { + if (parentNext === null) { + throw new Error('The stacks must reach the root at the same time. This is a bug in React.'); + } + + popToNearestCommonAncestor(parentPrev, parentNext); + } // On the way back, we push the new ones that weren't common. + + + pushNode(next); + } +} + +function popAllPrevious(prev) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev !== null) { + popAllPrevious(parentPrev); + } +} + +function pushAllNext(next) { + var parentNext = next.parent; + + if (parentNext !== null) { + pushAllNext(parentNext); + } + + pushNode(next); +} + +function popPreviousToCommonLevel(prev, next) { + popNode(prev); + var parentPrev = prev.parent; + + if (parentPrev === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (parentPrev.depth === next.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(parentPrev, next); + } else { + // We must still be deeper. + popPreviousToCommonLevel(parentPrev, next); + } +} + +function popNextToCommonLevel(prev, next) { + var parentNext = next.parent; + + if (parentNext === null) { + throw new Error('The depth must equal at least at zero before reaching the root. This is a bug in React.'); + } + + if (prev.depth === parentNext.depth) { + // We found the same level. Now we just need to find a shared ancestor. + popToNearestCommonAncestor(prev, parentNext); + } else { + // We must still be deeper. + popNextToCommonLevel(prev, parentNext); + } + + pushNode(next); +} // Perform context switching to the new snapshot. +// To make it cheap to read many contexts, while not suspending, we make the switch eagerly by +// updating all the context's current values. That way reads, always just read the current value. +// At the cost of updating contexts even if they're never read by this subtree. + + +function switchContext(newSnapshot) { + // The basic algorithm we need to do is to pop back any contexts that are no longer on the stack. + // We also need to update any new contexts that are now on the stack with the deepest value. + // The easiest way to update new contexts is to just reapply them in reverse order from the + // perspective of the backpointers. To avoid allocating a lot when switching, we use the stack + // for that. Therefore this algorithm is recursive. + // 1) First we pop which ever snapshot tree was deepest. Popping old contexts as we go. + // 2) Then we find the nearest common ancestor from there. Popping old contexts as we go. + // 3) Then we reapply new contexts on the way back up the stack. + var prev = currentActiveSnapshot; + var next = newSnapshot; + + if (prev !== next) { + if (prev === null) { + // $FlowFixMe: This has to be non-null since it's not equal to prev. + pushAllNext(next); + } else if (next === null) { + popAllPrevious(prev); + } else if (prev.depth === next.depth) { + popToNearestCommonAncestor(prev, next); + } else if (prev.depth > next.depth) { + popPreviousToCommonLevel(prev, next); + } else { + popNextToCommonLevel(prev, next); + } + + currentActiveSnapshot = next; + } +} +function pushProvider(context, nextValue) { + var prevValue; + + { + prevValue = context._currentValue2; + context._currentValue2 = nextValue; + + { + if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } + + context._currentRenderer2 = rendererSigil; + } + } + + var prevNode = currentActiveSnapshot; + var newNode = { + parent: prevNode, + depth: prevNode === null ? 0 : prevNode.depth + 1, + context: context, + parentValue: prevValue, + value: nextValue + }; + currentActiveSnapshot = newNode; + return newNode; +} +function popProvider(context) { + var prevSnapshot = currentActiveSnapshot; + + if (prevSnapshot === null) { + throw new Error('Tried to pop a Context at the root of the app. This is a bug in React.'); + } + + { + if (prevSnapshot.context !== context) { + error('The parent context is not the expected context. This is probably a bug in React.'); + } + } + + { + var _value = prevSnapshot.parentValue; + + if (_value === REACT_SERVER_CONTEXT_DEFAULT_VALUE_NOT_LOADED) { + prevSnapshot.context._currentValue2 = prevSnapshot.context._defaultValue; + } else { + prevSnapshot.context._currentValue2 = _value; + } + + { + if (context._currentRenderer2 !== undefined && context._currentRenderer2 !== null && context._currentRenderer2 !== rendererSigil) { + error('Detected multiple renderers concurrently rendering the ' + 'same context provider. This is currently unsupported.'); + } + + context._currentRenderer2 = rendererSigil; + } + } + + return currentActiveSnapshot = prevSnapshot.parent; +} +function getActiveContext() { + return currentActiveSnapshot; +} +function readContext(context) { + var value = context._currentValue2; + return value; +} + +/** + * `ReactInstanceMap` maintains a mapping from a public facing stateful + * instance (key) and the internal representation (value). This allows public + * methods to accept the user facing instance as an argument and map them back + * to internal methods. + * + * Note that this module is currently shared and assumed to be stateless. + * If this becomes an actual Map, that will break. + */ +function get(key) { + return key._reactInternals; +} +function set(key, value) { + key._reactInternals = value; +} + +var didWarnAboutNoopUpdateForComponent = {}; +var didWarnAboutDeprecatedWillMount = {}; +var didWarnAboutUninitializedState; +var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate; +var didWarnAboutLegacyLifecyclesAndDerivedState; +var didWarnAboutUndefinedDerivedState; +var warnOnUndefinedDerivedState; +var warnOnInvalidCallback; +var didWarnAboutDirectlyAssigningPropsToState; +var didWarnAboutContextTypeAndContextTypes; +var didWarnAboutInvalidateContextType; + +{ + didWarnAboutUninitializedState = new Set(); + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set(); + didWarnAboutLegacyLifecyclesAndDerivedState = new Set(); + didWarnAboutDirectlyAssigningPropsToState = new Set(); + didWarnAboutUndefinedDerivedState = new Set(); + didWarnAboutContextTypeAndContextTypes = new Set(); + didWarnAboutInvalidateContextType = new Set(); + var didWarnOnInvalidCallback = new Set(); + + warnOnInvalidCallback = function (callback, callerName) { + if (callback === null || typeof callback === 'function') { + return; + } + + var key = callerName + '_' + callback; + + if (!didWarnOnInvalidCallback.has(key)) { + didWarnOnInvalidCallback.add(key); + + error('%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, callback); + } + }; + + warnOnUndefinedDerivedState = function (type, partialState) { + if (partialState === undefined) { + var componentName = getComponentNameFromType(type) || 'Component'; + + if (!didWarnAboutUndefinedDerivedState.has(componentName)) { + didWarnAboutUndefinedDerivedState.add(componentName); + + error('%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' + 'You have returned undefined.', componentName); + } + } + }; +} + +function warnNoop(publicInstance, callerName) { + { + var _constructor = publicInstance.constructor; + var componentName = _constructor && getComponentNameFromType(_constructor) || 'ReactClass'; + var warningKey = componentName + '.' + callerName; + + if (didWarnAboutNoopUpdateForComponent[warningKey]) { + return; + } + + error('%s(...): Can only update a mounting component. ' + 'This usually means you called %s() outside componentWillMount() on the server. ' + 'This is a no-op.\n\nPlease check the code for the %s component.', callerName, callerName, componentName); + + didWarnAboutNoopUpdateForComponent[warningKey] = true; + } +} + +var classComponentUpdater = { + isMounted: function (inst) { + return false; + }, + enqueueSetState: function (inst, payload, callback) { + var internals = get(inst); + + if (internals.queue === null) { + warnNoop(inst, 'setState'); + } else { + internals.queue.push(payload); + + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, 'setState'); + } + } + } + }, + enqueueReplaceState: function (inst, payload, callback) { + var internals = get(inst); + internals.replace = true; + internals.queue = [payload]; + + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, 'setState'); + } + } + }, + enqueueForceUpdate: function (inst, callback) { + var internals = get(inst); + + if (internals.queue === null) { + warnNoop(inst, 'forceUpdate'); + } else { + { + if (callback !== undefined && callback !== null) { + warnOnInvalidCallback(callback, 'setState'); + } + } + } + } +}; + +function applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, prevState, nextProps) { + var partialState = getDerivedStateFromProps(nextProps, prevState); + + { + warnOnUndefinedDerivedState(ctor, partialState); + } // Merge the partial state and the previous state. + + + var newState = partialState === null || partialState === undefined ? prevState : assign({}, prevState, partialState); + return newState; +} + +function constructClassInstance(ctor, props, maskedLegacyContext) { + var context = emptyContextObject; + var contextType = ctor.contextType; + + { + if ('contextType' in ctor) { + var isValid = // Allow null for conditional declaration + contextType === null || contextType !== undefined && contextType.$$typeof === REACT_CONTEXT_TYPE && contextType._context === undefined; // Not a + + if (!isValid && !didWarnAboutInvalidateContextType.has(ctor)) { + didWarnAboutInvalidateContextType.add(ctor); + var addendum = ''; + + if (contextType === undefined) { + addendum = ' However, it is set to undefined. ' + 'This can be caused by a typo or by mixing up named and default imports. ' + 'This can also happen due to a circular dependency, so ' + 'try moving the createContext() call to a separate file.'; + } else if (typeof contextType !== 'object') { + addendum = ' However, it is set to a ' + typeof contextType + '.'; + } else if (contextType.$$typeof === REACT_PROVIDER_TYPE) { + addendum = ' Did you accidentally pass the Context.Provider instead?'; + } else if (contextType._context !== undefined) { + // + addendum = ' Did you accidentally pass the Context.Consumer instead?'; + } else { + addendum = ' However, it is set to an object with keys {' + Object.keys(contextType).join(', ') + '}.'; + } + + error('%s defines an invalid contextType. ' + 'contextType should point to the Context object returned by React.createContext().%s', getComponentNameFromType(ctor) || 'Component', addendum); + } + } + } + + if (typeof contextType === 'object' && contextType !== null) { + context = readContext(contextType); + } else { + context = maskedLegacyContext; + } + + var instance = new ctor(props, context); + + { + if (typeof ctor.getDerivedStateFromProps === 'function' && (instance.state === null || instance.state === undefined)) { + var componentName = getComponentNameFromType(ctor) || 'Component'; + + if (!didWarnAboutUninitializedState.has(componentName)) { + didWarnAboutUninitializedState.add(componentName); + + error('`%s` uses `getDerivedStateFromProps` but its initial state is ' + '%s. This is not recommended. Instead, define the initial state by ' + 'assigning an object to `this.state` in the constructor of `%s`. ' + 'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.', componentName, instance.state === null ? 'null' : 'undefined', componentName); + } + } // If new component APIs are defined, "unsafe" lifecycles won't be called. + // Warn about these lifecycles if they are present. + // Don't warn about react-lifecycles-compat polyfilled methods though. + + + if (typeof ctor.getDerivedStateFromProps === 'function' || typeof instance.getSnapshotBeforeUpdate === 'function') { + var foundWillMountName = null; + var foundWillReceivePropsName = null; + var foundWillUpdateName = null; + + if (typeof instance.componentWillMount === 'function' && instance.componentWillMount.__suppressDeprecationWarning !== true) { + foundWillMountName = 'componentWillMount'; + } else if (typeof instance.UNSAFE_componentWillMount === 'function') { + foundWillMountName = 'UNSAFE_componentWillMount'; + } + + if (typeof instance.componentWillReceiveProps === 'function' && instance.componentWillReceiveProps.__suppressDeprecationWarning !== true) { + foundWillReceivePropsName = 'componentWillReceiveProps'; + } else if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') { + foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; + } + + if (typeof instance.componentWillUpdate === 'function' && instance.componentWillUpdate.__suppressDeprecationWarning !== true) { + foundWillUpdateName = 'componentWillUpdate'; + } else if (typeof instance.UNSAFE_componentWillUpdate === 'function') { + foundWillUpdateName = 'UNSAFE_componentWillUpdate'; + } + + if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) { + var _componentName = getComponentNameFromType(ctor) || 'Component'; + + var newApiName = typeof ctor.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()'; + + if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName)) { + didWarnAboutLegacyLifecyclesAndDerivedState.add(_componentName); + + error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + '%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' + 'The above lifecycles should be removed. Learn more about this warning here:\n' + 'https://reactjs.org/link/unsafe-component-lifecycles', _componentName, newApiName, foundWillMountName !== null ? "\n " + foundWillMountName : '', foundWillReceivePropsName !== null ? "\n " + foundWillReceivePropsName : '', foundWillUpdateName !== null ? "\n " + foundWillUpdateName : ''); + } + } + } + } + + return instance; +} + +function checkClassInstance(instance, ctor, newProps) { + { + var name = getComponentNameFromType(ctor) || 'Component'; + var renderPresent = instance.render; + + if (!renderPresent) { + if (ctor.prototype && typeof ctor.prototype.render === 'function') { + error('%s(...): No `render` method found on the returned component ' + 'instance: did you accidentally return an object from the constructor?', name); + } else { + error('%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', name); + } + } + + if (instance.getInitialState && !instance.getInitialState.isReactClassApproved && !instance.state) { + error('getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', name); + } + + if (instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved) { + error('getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', name); + } + + if (instance.propTypes) { + error('propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', name); + } + + if (instance.contextType) { + error('contextType was defined as an instance property on %s. Use a static ' + 'property to define contextType instead.', name); + } + + { + if (instance.contextTypes) { + error('contextTypes was defined as an instance property on %s. Use a static ' + 'property to define contextTypes instead.', name); + } + + if (ctor.contextType && ctor.contextTypes && !didWarnAboutContextTypeAndContextTypes.has(ctor)) { + didWarnAboutContextTypeAndContextTypes.add(ctor); + + error('%s declares both contextTypes and contextType static properties. ' + 'The legacy contextTypes property will be ignored.', name); + } + } + + if (typeof instance.componentShouldUpdate === 'function') { + error('%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', name); + } + + if (ctor.prototype && ctor.prototype.isPureReactComponent && typeof instance.shouldComponentUpdate !== 'undefined') { + error('%s has a method called shouldComponentUpdate(). ' + 'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 'Please extend React.Component if shouldComponentUpdate is used.', getComponentNameFromType(ctor) || 'A pure component'); + } + + if (typeof instance.componentDidUnmount === 'function') { + error('%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', name); + } + + if (typeof instance.componentDidReceiveProps === 'function') { + error('%s has a method called ' + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + 'If you meant to update the state in response to changing props, ' + 'use componentWillReceiveProps(). If you meant to fetch data or ' + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', name); + } + + if (typeof instance.componentWillRecieveProps === 'function') { + error('%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', name); + } + + if (typeof instance.UNSAFE_componentWillRecieveProps === 'function') { + error('%s has a method called ' + 'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?', name); + } + + var hasMutatedProps = instance.props !== newProps; + + if (instance.props !== undefined && hasMutatedProps) { + error('%s(...): When calling super() in `%s`, make sure to pass ' + "up the same props that your component's constructor was passed.", name, name); + } + + if (instance.defaultProps) { + error('Setting defaultProps as an instance property on %s is not supported and will be ignored.' + ' Instead, define defaultProps as a static property on %s.', name, name); + } + + if (typeof instance.getSnapshotBeforeUpdate === 'function' && typeof instance.componentDidUpdate !== 'function' && !didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)) { + didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor); + + error('%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' + 'This component defines getSnapshotBeforeUpdate() only.', getComponentNameFromType(ctor)); + } + + if (typeof instance.getDerivedStateFromProps === 'function') { + error('%s: getDerivedStateFromProps() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); + } + + if (typeof instance.getDerivedStateFromError === 'function') { + error('%s: getDerivedStateFromError() is defined as an instance method ' + 'and will be ignored. Instead, declare it as a static method.', name); + } + + if (typeof ctor.getSnapshotBeforeUpdate === 'function') { + error('%s: getSnapshotBeforeUpdate() is defined as a static method ' + 'and will be ignored. Instead, declare it as an instance method.', name); + } + + var _state = instance.state; + + if (_state && (typeof _state !== 'object' || isArray(_state))) { + error('%s.state: must be set to an object or null', name); + } + + if (typeof instance.getChildContext === 'function' && typeof ctor.childContextTypes !== 'object') { + error('%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', name); + } + } +} + +function callComponentWillMount(type, instance) { + var oldState = instance.state; + + if (typeof instance.componentWillMount === 'function') { + { + if ( instance.componentWillMount.__suppressDeprecationWarning !== true) { + var componentName = getComponentNameFromType(type) || 'Unknown'; + + if (!didWarnAboutDeprecatedWillMount[componentName]) { + warn( // keep this warning in sync with ReactStrictModeWarning.js + 'componentWillMount has been renamed, and is not recommended for use. ' + 'See https://reactjs.org/link/unsafe-component-lifecycles for details.\n\n' + '* Move code from componentWillMount to componentDidMount (preferred in most cases) ' + 'or the constructor.\n' + '\nPlease update the following components: %s', componentName); + + didWarnAboutDeprecatedWillMount[componentName] = true; + } + } + } + + instance.componentWillMount(); + } + + if (typeof instance.UNSAFE_componentWillMount === 'function') { + instance.UNSAFE_componentWillMount(); + } + + if (oldState !== instance.state) { + { + error('%s.componentWillMount(): Assigning directly to this.state is ' + "deprecated (except inside a component's " + 'constructor). Use setState instead.', getComponentNameFromType(type) || 'Component'); + } + + classComponentUpdater.enqueueReplaceState(instance, instance.state, null); + } +} + +function processUpdateQueue(internalInstance, inst, props, maskedLegacyContext) { + if (internalInstance.queue !== null && internalInstance.queue.length > 0) { + var oldQueue = internalInstance.queue; + var oldReplace = internalInstance.replace; + internalInstance.queue = null; + internalInstance.replace = false; + + if (oldReplace && oldQueue.length === 1) { + inst.state = oldQueue[0]; + } else { + var nextState = oldReplace ? oldQueue[0] : inst.state; + var dontMutate = true; + + for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) { + var partial = oldQueue[i]; + var partialState = typeof partial === 'function' ? partial.call(inst, nextState, props, maskedLegacyContext) : partial; + + if (partialState != null) { + if (dontMutate) { + dontMutate = false; + nextState = assign({}, nextState, partialState); + } else { + assign(nextState, partialState); + } + } + } + + inst.state = nextState; + } + } else { + internalInstance.queue = null; + } +} // Invokes the mount life-cycles on a previously never rendered instance. + + +function mountClassInstance(instance, ctor, newProps, maskedLegacyContext) { + { + checkClassInstance(instance, ctor, newProps); + } + + var initialState = instance.state !== undefined ? instance.state : null; + instance.updater = classComponentUpdater; + instance.props = newProps; + instance.state = initialState; // We don't bother initializing the refs object on the server, since we're not going to resolve them anyway. + // The internal instance will be used to manage updates that happen during this mount. + + var internalInstance = { + queue: [], + replace: false + }; + set(instance, internalInstance); + var contextType = ctor.contextType; + + if (typeof contextType === 'object' && contextType !== null) { + instance.context = readContext(contextType); + } else { + instance.context = maskedLegacyContext; + } + + { + if (instance.state === newProps) { + var componentName = getComponentNameFromType(ctor) || 'Component'; + + if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) { + didWarnAboutDirectlyAssigningPropsToState.add(componentName); + + error('%s: It is not recommended to assign props directly to state ' + "because updates to props won't be reflected in state. " + 'In most cases, it is better to use props directly.', componentName); + } + } + } + + var getDerivedStateFromProps = ctor.getDerivedStateFromProps; + + if (typeof getDerivedStateFromProps === 'function') { + instance.state = applyDerivedStateFromProps(instance, ctor, getDerivedStateFromProps, initialState, newProps); + } // In order to support react-lifecycles-compat polyfilled components, + // Unsafe lifecycles should not be invoked for components using the new APIs. + + + if (typeof ctor.getDerivedStateFromProps !== 'function' && typeof instance.getSnapshotBeforeUpdate !== 'function' && (typeof instance.UNSAFE_componentWillMount === 'function' || typeof instance.componentWillMount === 'function')) { + callComponentWillMount(ctor, instance); // If we had additional state updates during this life-cycle, let's + // process them now. + + processUpdateQueue(internalInstance, instance, newProps, maskedLegacyContext); + } +} + +// Ids are base 32 strings whose binary representation corresponds to the +// position of a node in a tree. +// Every time the tree forks into multiple children, we add additional bits to +// the left of the sequence that represent the position of the child within the +// current level of children. +// +// 00101 00010001011010101 +// ╰─┬─╯ ╰───────┬───────╯ +// Fork 5 of 20 Parent id +// +// The leading 0s are important. In the above example, you only need 3 bits to +// represent slot 5. However, you need 5 bits to represent all the forks at +// the current level, so we must account for the empty bits at the end. +// +// For this same reason, slots are 1-indexed instead of 0-indexed. Otherwise, +// the zeroth id at a level would be indistinguishable from its parent. +// +// If a node has only one child, and does not materialize an id (i.e. does not +// contain a useId hook), then we don't need to allocate any space in the +// sequence. It's treated as a transparent indirection. For example, these two +// trees produce the same ids: +// +// <> <> +// +// +// +// +// +// +// However, we cannot skip any node that materializes an id. Otherwise, a parent +// id that does not fork would be indistinguishable from its child id. For +// example, this tree does not fork, but the parent and child must have +// different ids. +// +// +// +// +// +// To handle this scenario, every time we materialize an id, we allocate a +// new level with a single slot. You can think of this as a fork with only one +// prong, or an array of children with length 1. +// +// It's possible for the size of the sequence to exceed 32 bits, the max +// size for bitwise operations. When this happens, we make more room by +// converting the right part of the id to a string and storing it in an overflow +// variable. We use a base 32 string representation, because 32 is the largest +// power of 2 that is supported by toString(). We want the base to be large so +// that the resulting ids are compact, and we want the base to be a power of 2 +// because every log2(base) bits corresponds to a single character, i.e. every +// log2(32) = 5 bits. That means we can lop bits off the end 5 at a time without +// affecting the final result. +var emptyTreeContext = { + id: 1, + overflow: '' +}; +function getTreeId(context) { + var overflow = context.overflow; + var idWithLeadingBit = context.id; + var id = idWithLeadingBit & ~getLeadingBit(idWithLeadingBit); + return id.toString(32) + overflow; +} +function pushTreeContext(baseContext, totalChildren, index) { + var baseIdWithLeadingBit = baseContext.id; + var baseOverflow = baseContext.overflow; // The leftmost 1 marks the end of the sequence, non-inclusive. It's not part + // of the id; we use it to account for leading 0s. + + var baseLength = getBitLength(baseIdWithLeadingBit) - 1; + var baseId = baseIdWithLeadingBit & ~(1 << baseLength); + var slot = index + 1; + var length = getBitLength(totalChildren) + baseLength; // 30 is the max length we can store without overflowing, taking into + // consideration the leading 1 we use to mark the end of the sequence. + + if (length > 30) { + // We overflowed the bitwise-safe range. Fall back to slower algorithm. + // This branch assumes the length of the base id is greater than 5; it won't + // work for smaller ids, because you need 5 bits per character. + // + // We encode the id in multiple steps: first the base id, then the + // remaining digits. + // + // Each 5 bit sequence corresponds to a single base 32 character. So for + // example, if the current id is 23 bits long, we can convert 20 of those + // bits into a string of 4 characters, with 3 bits left over. + // + // First calculate how many bits in the base id represent a complete + // sequence of characters. + var numberOfOverflowBits = baseLength - baseLength % 5; // Then create a bitmask that selects only those bits. + + var newOverflowBits = (1 << numberOfOverflowBits) - 1; // Select the bits, and convert them to a base 32 string. + + var newOverflow = (baseId & newOverflowBits).toString(32); // Now we can remove those bits from the base id. + + var restOfBaseId = baseId >> numberOfOverflowBits; + var restOfBaseLength = baseLength - numberOfOverflowBits; // Finally, encode the rest of the bits using the normal algorithm. Because + // we made more room, this time it won't overflow. + + var restOfLength = getBitLength(totalChildren) + restOfBaseLength; + var restOfNewBits = slot << restOfBaseLength; + var id = restOfNewBits | restOfBaseId; + var overflow = newOverflow + baseOverflow; + return { + id: 1 << restOfLength | id, + overflow: overflow + }; + } else { + // Normal path + var newBits = slot << baseLength; + + var _id = newBits | baseId; + + var _overflow = baseOverflow; + return { + id: 1 << length | _id, + overflow: _overflow + }; + } +} + +function getBitLength(number) { + return 32 - clz32(number); +} + +function getLeadingBit(id) { + return 1 << getBitLength(id) - 1; +} // TODO: Math.clz32 is supported in Node 12+. Maybe we can drop the fallback. + + +var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. +// Based on: +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 + +var log = Math.log; +var LN2 = Math.LN2; + +function clz32Fallback(x) { + var asUint = x >>> 0; + + if (asUint === 0) { + return 32; + } + + return 31 - (log(asUint) / LN2 | 0) | 0; +} + +/** + * inlined Object.is polyfill to avoid requiring consumers ship their own + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + */ +function is(x, y) { + return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare + ; +} + +var objectIs = typeof Object.is === 'function' ? Object.is : is; + +var currentlyRenderingComponent = null; +var currentlyRenderingTask = null; +var firstWorkInProgressHook = null; +var workInProgressHook = null; // Whether the work-in-progress hook is a re-rendered hook + +var isReRender = false; // Whether an update was scheduled during the currently executing render pass. + +var didScheduleRenderPhaseUpdate = false; // Counts the number of useId hooks in this component + +var localIdCounter = 0; // Lazily created map of render-phase updates + +var renderPhaseUpdates = null; // Counter to prevent infinite loops. + +var numberOfReRenders = 0; +var RE_RENDER_LIMIT = 25; +var isInHookUserCodeInDev = false; // In DEV, this is the name of the currently executing primitive hook + +var currentHookNameInDev; + +function resolveCurrentlyRenderingComponent() { + if (currentlyRenderingComponent === null) { + throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for' + ' one of the following reasons:\n' + '1. You might have mismatching versions of React and the renderer (such as React DOM)\n' + '2. You might be breaking the Rules of Hooks\n' + '3. You might have more than one copy of React in the same app\n' + 'See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.'); + } + + { + if (isInHookUserCodeInDev) { + error('Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. ' + 'You can only call Hooks at the top level of your React function. ' + 'For more information, see ' + 'https://reactjs.org/link/rules-of-hooks'); + } + } + + return currentlyRenderingComponent; +} + +function areHookInputsEqual(nextDeps, prevDeps) { + if (prevDeps === null) { + { + error('%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev); + } + + return false; + } + + { + // Don't bother comparing lengths in prod because these arrays should be + // passed inline. + if (nextDeps.length !== prevDeps.length) { + error('The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, "[" + nextDeps.join(', ') + "]", "[" + prevDeps.join(', ') + "]"); + } + } + + for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) { + if (objectIs(nextDeps[i], prevDeps[i])) { + continue; + } + + return false; + } + + return true; +} + +function createHook() { + if (numberOfReRenders > 0) { + throw new Error('Rendered more hooks than during the previous render'); + } + + return { + memoizedState: null, + queue: null, + next: null + }; +} + +function createWorkInProgressHook() { + if (workInProgressHook === null) { + // This is the first hook in the list + if (firstWorkInProgressHook === null) { + isReRender = false; + firstWorkInProgressHook = workInProgressHook = createHook(); + } else { + // There's already a work-in-progress. Reuse it. + isReRender = true; + workInProgressHook = firstWorkInProgressHook; + } + } else { + if (workInProgressHook.next === null) { + isReRender = false; // Append to the end of the list + + workInProgressHook = workInProgressHook.next = createHook(); + } else { + // There's already a work-in-progress. Reuse it. + isReRender = true; + workInProgressHook = workInProgressHook.next; + } + } + + return workInProgressHook; +} + +function prepareToUseHooks(task, componentIdentity) { + currentlyRenderingComponent = componentIdentity; + currentlyRenderingTask = task; + + { + isInHookUserCodeInDev = false; + } // The following should have already been reset + // didScheduleRenderPhaseUpdate = false; + // localIdCounter = 0; + // firstWorkInProgressHook = null; + // numberOfReRenders = 0; + // renderPhaseUpdates = null; + // workInProgressHook = null; + + + localIdCounter = 0; +} +function finishHooks(Component, props, children, refOrContext) { + // This must be called after every function component to prevent hooks from + // being used in classes. + while (didScheduleRenderPhaseUpdate) { + // Updates were scheduled during the render phase. They are stored in + // the `renderPhaseUpdates` map. Call the component again, reusing the + // work-in-progress hooks and applying the additional updates on top. Keep + // restarting until no more updates are scheduled. + didScheduleRenderPhaseUpdate = false; + localIdCounter = 0; + numberOfReRenders += 1; // Start over from the beginning of the list + + workInProgressHook = null; + children = Component(props, refOrContext); + } + + resetHooksState(); + return children; +} +function checkDidRenderIdHook() { + // This should be called immediately after every finishHooks call. + // Conceptually, it's part of the return value of finishHooks; it's only a + // separate function to avoid using an array tuple. + var didRenderIdHook = localIdCounter !== 0; + return didRenderIdHook; +} // Reset the internal hooks state if an error occurs while rendering a component + +function resetHooksState() { + { + isInHookUserCodeInDev = false; + } + + currentlyRenderingComponent = null; + currentlyRenderingTask = null; + didScheduleRenderPhaseUpdate = false; + firstWorkInProgressHook = null; + numberOfReRenders = 0; + renderPhaseUpdates = null; + workInProgressHook = null; +} + +function readContext$1(context) { + { + if (isInHookUserCodeInDev) { + error('Context can only be read while React is rendering. ' + 'In classes, you can read it in the render method or getDerivedStateFromProps. ' + 'In function components, you can read it directly in the function body, but not ' + 'inside Hooks like useReducer() or useMemo().'); + } + } + + return readContext(context); +} + +function useContext(context) { + { + currentHookNameInDev = 'useContext'; + } + + resolveCurrentlyRenderingComponent(); + return readContext(context); +} + +function basicStateReducer(state, action) { + // $FlowFixMe: Flow doesn't like mixed types + return typeof action === 'function' ? action(state) : action; +} + +function useState(initialState) { + { + currentHookNameInDev = 'useState'; + } + + return useReducer(basicStateReducer, // useReducer has a special case to support lazy useState initializers + initialState); +} +function useReducer(reducer, initialArg, init) { + { + if (reducer !== basicStateReducer) { + currentHookNameInDev = 'useReducer'; + } + } + + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); + + if (isReRender) { + // This is a re-render. Apply the new render phase updates to the previous + // current hook. + var queue = workInProgressHook.queue; + var dispatch = queue.dispatch; + + if (renderPhaseUpdates !== null) { + // Render phase updates are stored in a map of queue -> linked list + var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + + if (firstRenderPhaseUpdate !== undefined) { + renderPhaseUpdates.delete(queue); + var newState = workInProgressHook.memoizedState; + var update = firstRenderPhaseUpdate; + + do { + // Process this render phase update. We don't have to check the + // priority because it will always be the same as the current + // render's. + var action = update.action; + + { + isInHookUserCodeInDev = true; + } + + newState = reducer(newState, action); + + { + isInHookUserCodeInDev = false; + } + + update = update.next; + } while (update !== null); + + workInProgressHook.memoizedState = newState; + return [newState, dispatch]; + } + } + + return [workInProgressHook.memoizedState, dispatch]; + } else { + { + isInHookUserCodeInDev = true; + } + + var initialState; + + if (reducer === basicStateReducer) { + // Special case for `useState`. + initialState = typeof initialArg === 'function' ? initialArg() : initialArg; + } else { + initialState = init !== undefined ? init(initialArg) : initialArg; + } + + { + isInHookUserCodeInDev = false; + } + + workInProgressHook.memoizedState = initialState; + + var _queue = workInProgressHook.queue = { + last: null, + dispatch: null + }; + + var _dispatch = _queue.dispatch = dispatchAction.bind(null, currentlyRenderingComponent, _queue); + + return [workInProgressHook.memoizedState, _dispatch]; + } +} + +function useMemo(nextCreate, deps) { + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); + var nextDeps = deps === undefined ? null : deps; + + if (workInProgressHook !== null) { + var prevState = workInProgressHook.memoizedState; + + if (prevState !== null) { + if (nextDeps !== null) { + var prevDeps = prevState[1]; + + if (areHookInputsEqual(nextDeps, prevDeps)) { + return prevState[0]; + } + } + } + } + + { + isInHookUserCodeInDev = true; + } + + var nextValue = nextCreate(); + + { + isInHookUserCodeInDev = false; + } + + workInProgressHook.memoizedState = [nextValue, nextDeps]; + return nextValue; +} + +function useRef(initialValue) { + currentlyRenderingComponent = resolveCurrentlyRenderingComponent(); + workInProgressHook = createWorkInProgressHook(); + var previousRef = workInProgressHook.memoizedState; + + if (previousRef === null) { + var ref = { + current: initialValue + }; + + { + Object.seal(ref); + } + + workInProgressHook.memoizedState = ref; + return ref; + } else { + return previousRef; + } +} + +function useLayoutEffect(create, inputs) { + { + currentHookNameInDev = 'useLayoutEffect'; + + error('useLayoutEffect does nothing on the server, because its effect cannot ' + "be encoded into the server renderer's output format. This will lead " + 'to a mismatch between the initial, non-hydrated UI and the intended ' + 'UI. To avoid this, useLayoutEffect should only be used in ' + 'components that render exclusively on the client. ' + 'See https://reactjs.org/link/uselayouteffect-ssr for common fixes.'); + } +} + +function dispatchAction(componentIdentity, queue, action) { + if (numberOfReRenders >= RE_RENDER_LIMIT) { + throw new Error('Too many re-renders. React limits the number of renders to prevent ' + 'an infinite loop.'); + } + + if (componentIdentity === currentlyRenderingComponent) { + // This is a render phase update. Stash it in a lazily-created map of + // queue -> linked list of updates. After this render pass, we'll restart + // and apply the stashed updates on top of the work-in-progress hook. + didScheduleRenderPhaseUpdate = true; + var update = { + action: action, + next: null + }; + + if (renderPhaseUpdates === null) { + renderPhaseUpdates = new Map(); + } + + var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue); + + if (firstRenderPhaseUpdate === undefined) { + renderPhaseUpdates.set(queue, update); + } else { + // Append the update to the end of the list. + var lastRenderPhaseUpdate = firstRenderPhaseUpdate; + + while (lastRenderPhaseUpdate.next !== null) { + lastRenderPhaseUpdate = lastRenderPhaseUpdate.next; + } + + lastRenderPhaseUpdate.next = update; + } + } +} + +function useCallback(callback, deps) { + return useMemo(function () { + return callback; + }, deps); +} // TODO Decide on how to implement this hook for server rendering. +// If a mutation occurs during render, consider triggering a Suspense boundary +// and falling back to client rendering. + +function useMutableSource(source, getSnapshot, subscribe) { + resolveCurrentlyRenderingComponent(); + return getSnapshot(source._source); +} + +function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { + if (getServerSnapshot === undefined) { + throw new Error('Missing getServerSnapshot, which is required for ' + 'server-rendered content. Will revert to client rendering.'); + } + + return getServerSnapshot(); +} + +function useDeferredValue(value) { + resolveCurrentlyRenderingComponent(); + return value; +} + +function unsupportedStartTransition() { + throw new Error('startTransition cannot be called during server rendering.'); +} + +function useTransition() { + resolveCurrentlyRenderingComponent(); + return [false, unsupportedStartTransition]; +} + +function useId() { + var task = currentlyRenderingTask; + var treeId = getTreeId(task.treeContext); + var responseState = currentResponseState; + + if (responseState === null) { + throw new Error('Invalid hook call. Hooks can only be called inside of the body of a function component.'); + } + + var localId = localIdCounter++; + return makeId(responseState, treeId, localId); +} + +function noop() {} + +var Dispatcher = { + readContext: readContext$1, + useContext: useContext, + useMemo: useMemo, + useReducer: useReducer, + useRef: useRef, + useState: useState, + useInsertionEffect: noop, + useLayoutEffect: useLayoutEffect, + useCallback: useCallback, + // useImperativeHandle is not run in the server environment + useImperativeHandle: noop, + // Effects are not run in the server environment. + useEffect: noop, + // Debugging effect + useDebugValue: noop, + useDeferredValue: useDeferredValue, + useTransition: useTransition, + useId: useId, + // Subscriptions are not setup in a server environment. + useMutableSource: useMutableSource, + useSyncExternalStore: useSyncExternalStore +}; + +var currentResponseState = null; +function setCurrentResponseState(responseState) { + currentResponseState = responseState; +} + +function getStackByComponentStackNode(componentStack) { + try { + var info = ''; + var node = componentStack; + + do { + switch (node.tag) { + case 0: + info += describeBuiltInComponentFrame(node.type, null, null); + break; + + case 1: + info += describeFunctionComponentFrame(node.type, null, null); + break; + + case 2: + info += describeClassComponentFrame(node.type, null, null); + break; + } + + node = node.parent; + } while (node); + + return info; + } catch (x) { + return '\nError generating stack: ' + x.message + '\n' + x.stack; + } +} + +var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; +var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; +var PENDING = 0; +var COMPLETED = 1; +var FLUSHED = 2; +var ABORTED = 3; +var ERRORED = 4; +var OPEN = 0; +var CLOSING = 1; +var CLOSED = 2; +// This is a default heuristic for how to split up the HTML content into progressive +// loading. Our goal is to be able to display additional new content about every 500ms. +// Faster than that is unnecessary and should be throttled on the client. It also +// adds unnecessary overhead to do more splits. We don't know if it's a higher or lower +// end device but higher end suffer less from the overhead than lower end does from +// not getting small enough pieces. We error on the side of low end. +// We base this on low end 3G speeds which is about 500kbits per second. We assume +// that there can be a reasonable drop off from max bandwidth which leaves you with +// as little as 80%. We can receive half of that each 500ms - at best. In practice, +// a little bandwidth is lost to processing and contention - e.g. CSS and images that +// are downloaded along with the main content. So we estimate about half of that to be +// the lower end throughput. In other words, we expect that you can at least show +// about 12.5kb of content per 500ms. Not counting starting latency for the first +// paint. +// 500 * 1024 / 8 * .8 * 0.5 / 2 +var DEFAULT_PROGRESSIVE_CHUNK_SIZE = 12800; + +function defaultErrorHandler(error) { + console['error'](error); // Don't transform to our wrapper + + return null; +} + +function noop$1() {} + +function createRequest(children, responseState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError) { + var pingedTasks = []; + var abortSet = new Set(); + var request = { + destination: null, + responseState: responseState, + progressiveChunkSize: progressiveChunkSize === undefined ? DEFAULT_PROGRESSIVE_CHUNK_SIZE : progressiveChunkSize, + status: OPEN, + fatalError: null, + nextSegmentId: 0, + allPendingTasks: 0, + pendingRootTasks: 0, + completedRootSegment: null, + abortableTasks: abortSet, + pingedTasks: pingedTasks, + clientRenderedBoundaries: [], + completedBoundaries: [], + partialBoundaries: [], + onError: onError === undefined ? defaultErrorHandler : onError, + onAllReady: onAllReady === undefined ? noop$1 : onAllReady, + onShellReady: onShellReady === undefined ? noop$1 : onShellReady, + onShellError: onShellError === undefined ? noop$1 : onShellError, + onFatalError: onFatalError === undefined ? noop$1 : onFatalError + }; // This segment represents the root fallback. + + var rootSegment = createPendingSegment(request, 0, null, rootFormatContext, // Root segments are never embedded in Text on either edge + false, false); // There is no parent so conceptually, we're unblocked to flush this segment. + + rootSegment.parentFlushed = true; + var rootTask = createTask(request, children, null, rootSegment, abortSet, emptyContextObject, rootContextSnapshot, emptyTreeContext); + pingedTasks.push(rootTask); + return request; +} + +function pingTask(request, task) { + var pingedTasks = request.pingedTasks; + pingedTasks.push(task); + + if (pingedTasks.length === 1) { + scheduleWork(function () { + return performWork(request); + }); + } +} + +function createSuspenseBoundary(request, fallbackAbortableTasks) { + return { + id: UNINITIALIZED_SUSPENSE_BOUNDARY_ID, + rootSegmentID: -1, + parentFlushed: false, + pendingTasks: 0, + forceClientRender: false, + completedSegments: [], + byteSize: 0, + fallbackAbortableTasks: fallbackAbortableTasks, + errorDigest: null + }; +} + +function createTask(request, node, blockedBoundary, blockedSegment, abortSet, legacyContext, context, treeContext) { + request.allPendingTasks++; + + if (blockedBoundary === null) { + request.pendingRootTasks++; + } else { + blockedBoundary.pendingTasks++; + } + + var task = { + node: node, + ping: function () { + return pingTask(request, task); + }, + blockedBoundary: blockedBoundary, + blockedSegment: blockedSegment, + abortSet: abortSet, + legacyContext: legacyContext, + context: context, + treeContext: treeContext + }; + + { + task.componentStack = null; + } + + abortSet.add(task); + return task; +} + +function createPendingSegment(request, index, boundary, formatContext, lastPushedText, textEmbedded) { + return { + status: PENDING, + id: -1, + // lazily assigned later + index: index, + parentFlushed: false, + chunks: [], + children: [], + formatContext: formatContext, + boundary: boundary, + lastPushedText: lastPushedText, + textEmbedded: textEmbedded + }; +} // DEV-only global reference to the currently executing task + + +var currentTaskInDEV = null; + +function getCurrentStackInDEV() { + { + if (currentTaskInDEV === null || currentTaskInDEV.componentStack === null) { + return ''; + } + + return getStackByComponentStackNode(currentTaskInDEV.componentStack); + } +} + +function pushBuiltInComponentStackInDEV(task, type) { + { + task.componentStack = { + tag: 0, + parent: task.componentStack, + type: type + }; + } +} + +function pushFunctionComponentStackInDEV(task, type) { + { + task.componentStack = { + tag: 1, + parent: task.componentStack, + type: type + }; + } +} + +function pushClassComponentStackInDEV(task, type) { + { + task.componentStack = { + tag: 2, + parent: task.componentStack, + type: type + }; + } +} + +function popComponentStackInDEV(task) { + { + if (task.componentStack === null) { + error('Unexpectedly popped too many stack frames. This is a bug in React.'); + } else { + task.componentStack = task.componentStack.parent; + } + } +} // stash the component stack of an unwinding error until it is processed + + +var lastBoundaryErrorComponentStackDev = null; + +function captureBoundaryErrorDetailsDev(boundary, error) { + { + var errorMessage; + + if (typeof error === 'string') { + errorMessage = error; + } else if (error && typeof error.message === 'string') { + errorMessage = error.message; + } else { + // eslint-disable-next-line react-internal/safe-string-coercion + errorMessage = String(error); + } + + var errorComponentStack = lastBoundaryErrorComponentStackDev || getCurrentStackInDEV(); + lastBoundaryErrorComponentStackDev = null; + boundary.errorMessage = errorMessage; + boundary.errorComponentStack = errorComponentStack; + } +} + +function logRecoverableError(request, error) { + // If this callback errors, we intentionally let that error bubble up to become a fatal error + // so that someone fixes the error reporting instead of hiding it. + var errorDigest = request.onError(error); + + if (errorDigest != null && typeof errorDigest !== 'string') { + // eslint-disable-next-line react-internal/prod-error-codes + throw new Error("onError returned something with a type other than \"string\". onError should return a string and may return null or undefined but must not return anything else. It received something of type \"" + typeof errorDigest + "\" instead"); + } + + return errorDigest; +} + +function fatalError(request, error) { + // This is called outside error handling code such as if the root errors outside + // a suspense boundary or if the root suspense boundary's fallback errors. + // It's also called if React itself or its host configs errors. + var onShellError = request.onShellError; + onShellError(error); + var onFatalError = request.onFatalError; + onFatalError(error); + + if (request.destination !== null) { + request.status = CLOSED; + closeWithError(request.destination, error); + } else { + request.status = CLOSING; + request.fatalError = error; + } +} + +function renderSuspenseBoundary(request, task, props) { + pushBuiltInComponentStackInDEV(task, 'Suspense'); + var parentBoundary = task.blockedBoundary; + var parentSegment = task.blockedSegment; // Each time we enter a suspense boundary, we split out into a new segment for + // the fallback so that we can later replace that segment with the content. + // This also lets us split out the main content even if it doesn't suspend, + // in case it ends up generating a large subtree of content. + + var fallback = props.fallback; + var content = props.children; + var fallbackAbortSet = new Set(); + var newBoundary = createSuspenseBoundary(request, fallbackAbortSet); + var insertionIndex = parentSegment.chunks.length; // The children of the boundary segment is actually the fallback. + + var boundarySegment = createPendingSegment(request, insertionIndex, newBoundary, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them + false, false); + parentSegment.children.push(boundarySegment); // The parentSegment has a child Segment at this index so we reset the lastPushedText marker on the parent + + parentSegment.lastPushedText = false; // This segment is the actual child content. We can start rendering that immediately. + + var contentRootSegment = createPendingSegment(request, 0, null, parentSegment.formatContext, // boundaries never require text embedding at their edges because comment nodes bound them + false, false); // We mark the root segment as having its parent flushed. It's not really flushed but there is + // no parent segment so there's nothing to wait on. + + contentRootSegment.parentFlushed = true; // Currently this is running synchronously. We could instead schedule this to pingedTasks. + // I suspect that there might be some efficiency benefits from not creating the suspended task + // and instead just using the stack if possible. + // TODO: Call this directly instead of messing with saving and restoring contexts. + // We can reuse the current context and task to render the content immediately without + // context switching. We just need to temporarily switch which boundary and which segment + // we're writing to. If something suspends, it'll spawn new suspended task with that context. + + task.blockedBoundary = newBoundary; + task.blockedSegment = contentRootSegment; + + try { + // We use the safe form because we don't handle suspending here. Only error handling. + renderNode(request, task, content); + pushSegmentFinale$1(contentRootSegment.chunks, request.responseState, contentRootSegment.lastPushedText, contentRootSegment.textEmbedded); + contentRootSegment.status = COMPLETED; + queueCompletedSegment(newBoundary, contentRootSegment); + + if (newBoundary.pendingTasks === 0) { + // This must have been the last segment we were waiting on. This boundary is now complete. + // Therefore we won't need the fallback. We early return so that we don't have to create + // the fallback. + popComponentStackInDEV(task); + return; + } + } catch (error) { + contentRootSegment.status = ERRORED; + newBoundary.forceClientRender = true; + newBoundary.errorDigest = logRecoverableError(request, error); + + { + captureBoundaryErrorDetailsDev(newBoundary, error); + } // We don't need to decrement any task numbers because we didn't spawn any new task. + // We don't need to schedule any task because we know the parent has written yet. + // We do need to fallthrough to create the fallback though. + + } finally { + task.blockedBoundary = parentBoundary; + task.blockedSegment = parentSegment; + } // We create suspended task for the fallback because we don't want to actually work + // on it yet in case we finish the main content, so we queue for later. + + + var suspendedFallbackTask = createTask(request, fallback, parentBoundary, boundarySegment, fallbackAbortSet, task.legacyContext, task.context, task.treeContext); + + { + suspendedFallbackTask.componentStack = task.componentStack; + } // TODO: This should be queued at a separate lower priority queue so that we only work + // on preparing fallbacks if we don't have any more main content to task on. + + + request.pingedTasks.push(suspendedFallbackTask); + popComponentStackInDEV(task); +} + +function renderHostElement(request, task, type, props) { + pushBuiltInComponentStackInDEV(task, type); + var segment = task.blockedSegment; + var children = pushStartInstance(segment.chunks, type, props, request.responseState, segment.formatContext); + segment.lastPushedText = false; + var prevContext = segment.formatContext; + segment.formatContext = getChildFormatContext(prevContext, type, props); // We use the non-destructive form because if something suspends, we still + // need to pop back up and finish this subtree of HTML. + + renderNode(request, task, children); // We expect that errors will fatal the whole task and that we don't need + // the correct context. Therefore this is not in a finally. + + segment.formatContext = prevContext; + pushEndInstance(segment.chunks, type); + segment.lastPushedText = false; + popComponentStackInDEV(task); +} + +function shouldConstruct$1(Component) { + return Component.prototype && Component.prototype.isReactComponent; +} + +function renderWithHooks(request, task, Component, props, secondArg) { + var componentIdentity = {}; + prepareToUseHooks(task, componentIdentity); + var result = Component(props, secondArg); + return finishHooks(Component, props, result, secondArg); +} + +function finishClassComponent(request, task, instance, Component, props) { + var nextChildren = instance.render(); + + { + if (instance.props !== props) { + if (!didWarnAboutReassigningProps) { + error('It looks like %s is reassigning its own `this.props` while rendering. ' + 'This is not supported and can lead to confusing bugs.', getComponentNameFromType(Component) || 'a component'); + } + + didWarnAboutReassigningProps = true; + } + } + + { + var childContextTypes = Component.childContextTypes; + + if (childContextTypes !== null && childContextTypes !== undefined) { + var previousContext = task.legacyContext; + var mergedContext = processChildContext(instance, Component, previousContext, childContextTypes); + task.legacyContext = mergedContext; + renderNodeDestructive(request, task, nextChildren); + task.legacyContext = previousContext; + return; + } + } + + renderNodeDestructive(request, task, nextChildren); +} + +function renderClassComponent(request, task, Component, props) { + pushClassComponentStackInDEV(task, Component); + var maskedContext = getMaskedContext(Component, task.legacyContext) ; + var instance = constructClassInstance(Component, props, maskedContext); + mountClassInstance(instance, Component, props, maskedContext); + finishClassComponent(request, task, instance, Component, props); + popComponentStackInDEV(task); +} + +var didWarnAboutBadClass = {}; +var didWarnAboutModulePatternComponent = {}; +var didWarnAboutContextTypeOnFunctionComponent = {}; +var didWarnAboutGetDerivedStateOnFunctionComponent = {}; +var didWarnAboutReassigningProps = false; +var didWarnAboutDefaultPropsOnFunctionComponent = {}; +var didWarnAboutGenerators = false; +var didWarnAboutMaps = false; +var hasWarnedAboutUsingContextAsConsumer = false; // This would typically be a function component but we still support module pattern +// components for some reason. + +function renderIndeterminateComponent(request, task, Component, props) { + var legacyContext; + + { + legacyContext = getMaskedContext(Component, task.legacyContext); + } + + pushFunctionComponentStackInDEV(task, Component); + + { + if (Component.prototype && typeof Component.prototype.render === 'function') { + var componentName = getComponentNameFromType(Component) || 'Unknown'; + + if (!didWarnAboutBadClass[componentName]) { + error("The <%s /> component appears to have a render method, but doesn't extend React.Component. " + 'This is likely to cause errors. Change %s to extend React.Component instead.', componentName, componentName); + + didWarnAboutBadClass[componentName] = true; + } + } + } + + var value = renderWithHooks(request, task, Component, props, legacyContext); + var hasId = checkDidRenderIdHook(); + + { + // Support for module components is deprecated and is removed behind a flag. + // Whether or not it would crash later, we want to show a good message in DEV first. + if (typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { + var _componentName = getComponentNameFromType(Component) || 'Unknown'; + + if (!didWarnAboutModulePatternComponent[_componentName]) { + error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName, _componentName, _componentName); + + didWarnAboutModulePatternComponent[_componentName] = true; + } + } + } + + if ( // Run these checks in production only if the flag is off. + // Eventually we'll delete this branch altogether. + typeof value === 'object' && value !== null && typeof value.render === 'function' && value.$$typeof === undefined) { + { + var _componentName2 = getComponentNameFromType(Component) || 'Unknown'; + + if (!didWarnAboutModulePatternComponent[_componentName2]) { + error('The <%s /> component appears to be a function component that returns a class instance. ' + 'Change %s to a class that extends React.Component instead. ' + "If you can't use a class try assigning the prototype on the function as a workaround. " + "`%s.prototype = React.Component.prototype`. Don't use an arrow function since it " + 'cannot be called with `new` by React.', _componentName2, _componentName2, _componentName2); + + didWarnAboutModulePatternComponent[_componentName2] = true; + } + } + + mountClassInstance(value, Component, props, legacyContext); + finishClassComponent(request, task, value, Component, props); + } else { + + { + validateFunctionComponentInDev(Component); + } // We're now successfully past this task, and we don't have to pop back to + // the previous task every again, so we can use the destructive recursive form. + + + if (hasId) { + // This component materialized an id. We treat this as its own level, with + // a single "child" slot. + var prevTreeContext = task.treeContext; + var totalChildren = 1; + var index = 0; + task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index); + + try { + renderNodeDestructive(request, task, value); + } finally { + task.treeContext = prevTreeContext; + } + } else { + renderNodeDestructive(request, task, value); + } + } + + popComponentStackInDEV(task); +} + +function validateFunctionComponentInDev(Component) { + { + if (Component) { + if (Component.childContextTypes) { + error('%s(...): childContextTypes cannot be defined on a function component.', Component.displayName || Component.name || 'Component'); + } + } + + if ( Component.defaultProps !== undefined) { + var componentName = getComponentNameFromType(Component) || 'Unknown'; + + if (!didWarnAboutDefaultPropsOnFunctionComponent[componentName]) { + error('%s: Support for defaultProps will be removed from function components ' + 'in a future major release. Use JavaScript default parameters instead.', componentName); + + didWarnAboutDefaultPropsOnFunctionComponent[componentName] = true; + } + } + + if (typeof Component.getDerivedStateFromProps === 'function') { + var _componentName3 = getComponentNameFromType(Component) || 'Unknown'; + + if (!didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3]) { + error('%s: Function components do not support getDerivedStateFromProps.', _componentName3); + + didWarnAboutGetDerivedStateOnFunctionComponent[_componentName3] = true; + } + } + + if (typeof Component.contextType === 'object' && Component.contextType !== null) { + var _componentName4 = getComponentNameFromType(Component) || 'Unknown'; + + if (!didWarnAboutContextTypeOnFunctionComponent[_componentName4]) { + error('%s: Function components do not support contextType.', _componentName4); + + didWarnAboutContextTypeOnFunctionComponent[_componentName4] = true; + } + } + } +} + +function resolveDefaultProps(Component, baseProps) { + if (Component && Component.defaultProps) { + // Resolve default props. Taken from ReactElement + var props = assign({}, baseProps); + var defaultProps = Component.defaultProps; + + for (var propName in defaultProps) { + if (props[propName] === undefined) { + props[propName] = defaultProps[propName]; + } + } + + return props; + } + + return baseProps; +} + +function renderForwardRef(request, task, type, props, ref) { + pushFunctionComponentStackInDEV(task, type.render); + var children = renderWithHooks(request, task, type.render, props, ref); + var hasId = checkDidRenderIdHook(); + + if (hasId) { + // This component materialized an id. We treat this as its own level, with + // a single "child" slot. + var prevTreeContext = task.treeContext; + var totalChildren = 1; + var index = 0; + task.treeContext = pushTreeContext(prevTreeContext, totalChildren, index); + + try { + renderNodeDestructive(request, task, children); + } finally { + task.treeContext = prevTreeContext; + } + } else { + renderNodeDestructive(request, task, children); + } + + popComponentStackInDEV(task); +} + +function renderMemo(request, task, type, props, ref) { + var innerType = type.type; + var resolvedProps = resolveDefaultProps(innerType, props); + renderElement(request, task, innerType, resolvedProps, ref); +} + +function renderContextConsumer(request, task, context, props) { + // The logic below for Context differs depending on PROD or DEV mode. In + // DEV mode, we create a separate object for Context.Consumer that acts + // like a proxy to Context. This proxy object adds unnecessary code in PROD + // so we use the old behaviour (Context.Consumer references Context) to + // reduce size and overhead. The separate object references context via + // a property called "_context", which also gives us the ability to check + // in DEV mode if this property exists or not and warn if it does not. + { + if (context._context === undefined) { + // This may be because it's a Context (rather than a Consumer). + // Or it may be because it's older React where they're the same thing. + // We only want to warn if we're sure it's a new React. + if (context !== context.Consumer) { + if (!hasWarnedAboutUsingContextAsConsumer) { + hasWarnedAboutUsingContextAsConsumer = true; + + error('Rendering directly is not supported and will be removed in ' + 'a future major release. Did you mean to render instead?'); + } + } + } else { + context = context._context; + } + } + + var render = props.children; + + { + if (typeof render !== 'function') { + error('A context consumer was rendered with multiple children, or a child ' + "that isn't a function. A context consumer expects a single child " + 'that is a function. If you did pass a function, make sure there ' + 'is no trailing or leading whitespace around it.'); + } + } + + var newValue = readContext(context); + var newChildren = render(newValue); + renderNodeDestructive(request, task, newChildren); +} + +function renderContextProvider(request, task, type, props) { + var context = type._context; + var value = props.value; + var children = props.children; + var prevSnapshot; + + { + prevSnapshot = task.context; + } + + task.context = pushProvider(context, value); + renderNodeDestructive(request, task, children); + task.context = popProvider(context); + + { + if (prevSnapshot !== task.context) { + error('Popping the context provider did not return back to the original snapshot. This is a bug in React.'); + } + } +} + +function renderLazyComponent(request, task, lazyComponent, props, ref) { + pushBuiltInComponentStackInDEV(task, 'Lazy'); + var payload = lazyComponent._payload; + var init = lazyComponent._init; + var Component = init(payload); + var resolvedProps = resolveDefaultProps(Component, props); + renderElement(request, task, Component, resolvedProps, ref); + popComponentStackInDEV(task); +} + +function renderElement(request, task, type, props, ref) { + if (typeof type === 'function') { + if (shouldConstruct$1(type)) { + renderClassComponent(request, task, type, props); + return; + } else { + renderIndeterminateComponent(request, task, type, props); + return; + } + } + + if (typeof type === 'string') { + renderHostElement(request, task, type, props); + return; + } + + switch (type) { + // TODO: LegacyHidden acts the same as a fragment. This only works + // because we currently assume that every instance of LegacyHidden is + // accompanied by a host component wrapper. In the hidden mode, the host + // component is given a `hidden` attribute, which ensures that the + // initial HTML is not visible. To support the use of LegacyHidden as a + // true fragment, without an extra DOM node, we would have to hide the + // initial HTML in some other way. + // TODO: Add REACT_OFFSCREEN_TYPE here too with the same capability. + case REACT_LEGACY_HIDDEN_TYPE: + case REACT_DEBUG_TRACING_MODE_TYPE: + case REACT_STRICT_MODE_TYPE: + case REACT_PROFILER_TYPE: + case REACT_FRAGMENT_TYPE: + { + renderNodeDestructive(request, task, props.children); + return; + } + + case REACT_SUSPENSE_LIST_TYPE: + { + pushBuiltInComponentStackInDEV(task, 'SuspenseList'); // TODO: SuspenseList should control the boundaries. + + renderNodeDestructive(request, task, props.children); + popComponentStackInDEV(task); + return; + } + + case REACT_SCOPE_TYPE: + { + + throw new Error('ReactDOMServer does not yet support scope components.'); + } + // eslint-disable-next-line-no-fallthrough + + case REACT_SUSPENSE_TYPE: + { + { + renderSuspenseBoundary(request, task, props); + } + + return; + } + } + + if (typeof type === 'object' && type !== null) { + switch (type.$$typeof) { + case REACT_FORWARD_REF_TYPE: + { + renderForwardRef(request, task, type, props, ref); + return; + } + + case REACT_MEMO_TYPE: + { + renderMemo(request, task, type, props, ref); + return; + } + + case REACT_PROVIDER_TYPE: + { + renderContextProvider(request, task, type, props); + return; + } + + case REACT_CONTEXT_TYPE: + { + renderContextConsumer(request, task, type, props); + return; + } + + case REACT_LAZY_TYPE: + { + renderLazyComponent(request, task, type, props); + return; + } + } + } + + var info = ''; + + { + if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { + info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and " + 'named imports.'; + } + } + + throw new Error('Element type is invalid: expected a string (for built-in ' + 'components) or a class/function (for composite components) ' + ("but got: " + (type == null ? type : typeof type) + "." + info)); +} + +function validateIterable(iterable, iteratorFn) { + { + // We don't support rendering Generators because it's a mutation. + // See https://github.com/facebook/react/issues/12995 + if (typeof Symbol === 'function' && // $FlowFixMe Flow doesn't know about toStringTag + iterable[Symbol.toStringTag] === 'Generator') { + if (!didWarnAboutGenerators) { + error('Using Generators as children is unsupported and will likely yield ' + 'unexpected results because enumerating a generator mutates it. ' + 'You may convert it to an array with `Array.from()` or the ' + '`[...spread]` operator before rendering. Keep in mind ' + 'you might need to polyfill these features for older browsers.'); + } + + didWarnAboutGenerators = true; + } // Warn about using Maps as children + + + if (iterable.entries === iteratorFn) { + if (!didWarnAboutMaps) { + error('Using Maps as children is not supported. ' + 'Use an array of keyed ReactElements instead.'); + } + + didWarnAboutMaps = true; + } + } +} + +function renderNodeDestructive(request, task, node) { + { + // In Dev we wrap renderNodeDestructiveImpl in a try / catch so we can capture + // a component stack at the right place in the tree. We don't do this in renderNode + // becuase it is not called at every layer of the tree and we may lose frames + try { + return renderNodeDestructiveImpl(request, task, node); + } catch (x) { + if (typeof x === 'object' && x !== null && typeof x.then === 'function') ; else { + // This is an error, stash the component stack if it is null. + lastBoundaryErrorComponentStackDev = lastBoundaryErrorComponentStackDev !== null ? lastBoundaryErrorComponentStackDev : getCurrentStackInDEV(); + } // rethrow so normal suspense logic can handle thrown value accordingly + + + throw x; + } + } +} // This function by it self renders a node and consumes the task by mutating it +// to update the current execution state. + + +function renderNodeDestructiveImpl(request, task, node) { + // Stash the node we're working on. We'll pick up from this task in case + // something suspends. + task.node = node; // Handle object types + + if (typeof node === 'object' && node !== null) { + switch (node.$$typeof) { + case REACT_ELEMENT_TYPE: + { + var element = node; + var type = element.type; + var props = element.props; + var ref = element.ref; + renderElement(request, task, type, props, ref); + return; + } + + case REACT_PORTAL_TYPE: + throw new Error('Portals are not currently supported by the server renderer. ' + 'Render them conditionally so that they only appear on the client render.'); + // eslint-disable-next-line-no-fallthrough + + case REACT_LAZY_TYPE: + { + var lazyNode = node; + var payload = lazyNode._payload; + var init = lazyNode._init; + var resolvedNode; + + { + try { + resolvedNode = init(payload); + } catch (x) { + if (typeof x === 'object' && x !== null && typeof x.then === 'function') { + // this Lazy initializer is suspending. push a temporary frame onto the stack so it can be + // popped off in spawnNewSuspendedTask. This aligns stack behavior between Lazy in element position + // vs Component position. We do not want the frame for Errors so we exclusively do this in + // the wakeable branch + pushBuiltInComponentStackInDEV(task, 'Lazy'); + } + + throw x; + } + } + + renderNodeDestructive(request, task, resolvedNode); + return; + } + } + + if (isArray(node)) { + renderChildrenArray(request, task, node); + return; + } + + var iteratorFn = getIteratorFn(node); + + if (iteratorFn) { + { + validateIterable(node, iteratorFn); + } + + var iterator = iteratorFn.call(node); + + if (iterator) { + // We need to know how many total children are in this set, so that we + // can allocate enough id slots to acommodate them. So we must exhaust + // the iterator before we start recursively rendering the children. + // TODO: This is not great but I think it's inherent to the id + // generation algorithm. + var step = iterator.next(); // If there are not entries, we need to push an empty so we start by checking that. + + if (!step.done) { + var children = []; + + do { + children.push(step.value); + step = iterator.next(); + } while (!step.done); + + renderChildrenArray(request, task, children); + return; + } + + return; + } + } + + var childString = Object.prototype.toString.call(node); + throw new Error("Objects are not valid as a React child (found: " + (childString === '[object Object]' ? 'object with keys {' + Object.keys(node).join(', ') + '}' : childString) + "). " + 'If you meant to render a collection of children, use an array ' + 'instead.'); + } + + if (typeof node === 'string') { + var segment = task.blockedSegment; + segment.lastPushedText = pushTextInstance$1(task.blockedSegment.chunks, node, request.responseState, segment.lastPushedText); + return; + } + + if (typeof node === 'number') { + var _segment = task.blockedSegment; + _segment.lastPushedText = pushTextInstance$1(task.blockedSegment.chunks, '' + node, request.responseState, _segment.lastPushedText); + return; + } + + { + if (typeof node === 'function') { + error('Functions are not valid as a React child. This may happen if ' + 'you return a Component instead of from render. ' + 'Or maybe you meant to call this function rather than return it.'); + } + } +} + +function renderChildrenArray(request, task, children) { + var totalChildren = children.length; + + for (var i = 0; i < totalChildren; i++) { + var prevTreeContext = task.treeContext; + task.treeContext = pushTreeContext(prevTreeContext, totalChildren, i); + + try { + // We need to use the non-destructive form so that we can safely pop back + // up and render the sibling if something suspends. + renderNode(request, task, children[i]); + } finally { + task.treeContext = prevTreeContext; + } + } +} + +function spawnNewSuspendedTask(request, task, x) { + // Something suspended, we'll need to create a new segment and resolve it later. + var segment = task.blockedSegment; + var insertionIndex = segment.chunks.length; + var newSegment = createPendingSegment(request, insertionIndex, null, segment.formatContext, // Adopt the parent segment's leading text embed + segment.lastPushedText, // Assume we are text embedded at the trailing edge + true); + segment.children.push(newSegment); // Reset lastPushedText for current Segment since the new Segment "consumed" it + + segment.lastPushedText = false; + var newTask = createTask(request, task.node, task.blockedBoundary, newSegment, task.abortSet, task.legacyContext, task.context, task.treeContext); + + { + if (task.componentStack !== null) { + // We pop one task off the stack because the node that suspended will be tried again, + // which will add it back onto the stack. + newTask.componentStack = task.componentStack.parent; + } + } + + var ping = newTask.ping; + x.then(ping, ping); +} // This is a non-destructive form of rendering a node. If it suspends it spawns +// a new task and restores the context of this task to what it was before. + + +function renderNode(request, task, node) { + // TODO: Store segment.children.length here and reset it in case something + // suspended partially through writing something. + // Snapshot the current context in case something throws to interrupt the + // process. + var previousFormatContext = task.blockedSegment.formatContext; + var previousLegacyContext = task.legacyContext; + var previousContext = task.context; + var previousComponentStack = null; + + { + previousComponentStack = task.componentStack; + } + + try { + return renderNodeDestructive(request, task, node); + } catch (x) { + resetHooksState(); + + if (typeof x === 'object' && x !== null && typeof x.then === 'function') { + spawnNewSuspendedTask(request, task, x); // Restore the context. We assume that this will be restored by the inner + // functions in case nothing throws so we don't use "finally" here. + + task.blockedSegment.formatContext = previousFormatContext; + task.legacyContext = previousLegacyContext; + task.context = previousContext; // Restore all active ReactContexts to what they were before. + + switchContext(previousContext); + + { + task.componentStack = previousComponentStack; + } + + return; + } else { + // Restore the context. We assume that this will be restored by the inner + // functions in case nothing throws so we don't use "finally" here. + task.blockedSegment.formatContext = previousFormatContext; + task.legacyContext = previousLegacyContext; + task.context = previousContext; // Restore all active ReactContexts to what they were before. + + switchContext(previousContext); + + { + task.componentStack = previousComponentStack; + } // We assume that we don't need the correct context. + // Let's terminate the rest of the tree and don't render any siblings. + + + throw x; + } + } +} + +function erroredTask(request, boundary, segment, error) { + // Report the error to a global handler. + var errorDigest = logRecoverableError(request, error); + + if (boundary === null) { + fatalError(request, error); + } else { + boundary.pendingTasks--; + + if (!boundary.forceClientRender) { + boundary.forceClientRender = true; + boundary.errorDigest = errorDigest; + + { + captureBoundaryErrorDetailsDev(boundary, error); + } // Regardless of what happens next, this boundary won't be displayed, + // so we can flush it, if the parent already flushed. + + + if (boundary.parentFlushed) { + // We don't have a preference where in the queue this goes since it's likely + // to error on the client anyway. However, intentionally client-rendered + // boundaries should be flushed earlier so that they can start on the client. + // We reuse the same queue for errors. + request.clientRenderedBoundaries.push(boundary); + } + } + } + + request.allPendingTasks--; + + if (request.allPendingTasks === 0) { + var onAllReady = request.onAllReady; + onAllReady(); + } +} + +function abortTaskSoft(task) { + // This aborts task without aborting the parent boundary that it blocks. + // It's used for when we didn't need this task to complete the tree. + // If task was needed, then it should use abortTask instead. + var request = this; + var boundary = task.blockedBoundary; + var segment = task.blockedSegment; + segment.status = ABORTED; + finishedTask(request, boundary, segment); +} + +function abortTask(task, request, reason) { + // This aborts the task and aborts the parent that it blocks, putting it into + // client rendered mode. + var boundary = task.blockedBoundary; + var segment = task.blockedSegment; + segment.status = ABORTED; + + if (boundary === null) { + request.allPendingTasks--; // We didn't complete the root so we have nothing to show. We can close + // the request; + + if (request.status !== CLOSED) { + request.status = CLOSED; + + if (request.destination !== null) { + close(request.destination); + } + } + } else { + boundary.pendingTasks--; + + if (!boundary.forceClientRender) { + boundary.forceClientRender = true; + + var _error = reason === undefined ? new Error('The render was aborted by the server without a reason.') : reason; + + boundary.errorDigest = request.onError(_error); + + { + var errorPrefix = 'The server did not finish this Suspense boundary: '; + + if (_error && typeof _error.message === 'string') { + _error = errorPrefix + _error.message; + } else { + // eslint-disable-next-line react-internal/safe-string-coercion + _error = errorPrefix + String(_error); + } + + var previousTaskInDev = currentTaskInDEV; + currentTaskInDEV = task; + + try { + captureBoundaryErrorDetailsDev(boundary, _error); + } finally { + currentTaskInDEV = previousTaskInDev; + } + } + + if (boundary.parentFlushed) { + request.clientRenderedBoundaries.push(boundary); + } + } // If this boundary was still pending then we haven't already cancelled its fallbacks. + // We'll need to abort the fallbacks, which will also error that parent boundary. + + + boundary.fallbackAbortableTasks.forEach(function (fallbackTask) { + return abortTask(fallbackTask, request, reason); + }); + boundary.fallbackAbortableTasks.clear(); + request.allPendingTasks--; + + if (request.allPendingTasks === 0) { + var onAllReady = request.onAllReady; + onAllReady(); + } + } +} + +function queueCompletedSegment(boundary, segment) { + if (segment.chunks.length === 0 && segment.children.length === 1 && segment.children[0].boundary === null) { + // This is an empty segment. There's nothing to write, so we can instead transfer the ID + // to the child. That way any existing references point to the child. + var childSegment = segment.children[0]; + childSegment.id = segment.id; + childSegment.parentFlushed = true; + + if (childSegment.status === COMPLETED) { + queueCompletedSegment(boundary, childSegment); + } + } else { + var completedSegments = boundary.completedSegments; + completedSegments.push(segment); + } +} + +function finishedTask(request, boundary, segment) { + if (boundary === null) { + if (segment.parentFlushed) { + if (request.completedRootSegment !== null) { + throw new Error('There can only be one root segment. This is a bug in React.'); + } + + request.completedRootSegment = segment; + } + + request.pendingRootTasks--; + + if (request.pendingRootTasks === 0) { + // We have completed the shell so the shell can't error anymore. + request.onShellError = noop$1; + var onShellReady = request.onShellReady; + onShellReady(); + } + } else { + boundary.pendingTasks--; + + if (boundary.forceClientRender) ; else if (boundary.pendingTasks === 0) { + // This must have been the last segment we were waiting on. This boundary is now complete. + if (segment.parentFlushed) { + // Our parent segment already flushed, so we need to schedule this segment to be emitted. + // If it is a segment that was aborted, we'll write other content instead so we don't need + // to emit it. + if (segment.status === COMPLETED) { + queueCompletedSegment(boundary, segment); + } + } + + if (boundary.parentFlushed) { + // The segment might be part of a segment that didn't flush yet, but if the boundary's + // parent flushed, we need to schedule the boundary to be emitted. + request.completedBoundaries.push(boundary); + } // We can now cancel any pending task on the fallback since we won't need to show it anymore. + // This needs to happen after we read the parentFlushed flags because aborting can finish + // work which can trigger user code, which can start flushing, which can change those flags. + + + boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request); + boundary.fallbackAbortableTasks.clear(); + } else { + if (segment.parentFlushed) { + // Our parent already flushed, so we need to schedule this segment to be emitted. + // If it is a segment that was aborted, we'll write other content instead so we don't need + // to emit it. + if (segment.status === COMPLETED) { + queueCompletedSegment(boundary, segment); + var completedSegments = boundary.completedSegments; + + if (completedSegments.length === 1) { + // This is the first time since we last flushed that we completed anything. + // We can schedule this boundary to emit its partially completed segments early + // in case the parent has already been flushed. + if (boundary.parentFlushed) { + request.partialBoundaries.push(boundary); + } + } + } + } + } + } + + request.allPendingTasks--; + + if (request.allPendingTasks === 0) { + // This needs to be called at the very end so that we can synchronously write the result + // in the callback if needed. + var onAllReady = request.onAllReady; + onAllReady(); + } +} + +function retryTask(request, task) { + var segment = task.blockedSegment; + + if (segment.status !== PENDING) { + // We completed this by other means before we had a chance to retry it. + return; + } // We restore the context to what it was when we suspended. + // We don't restore it after we leave because it's likely that we'll end up + // needing a very similar context soon again. + + + switchContext(task.context); + var prevTaskInDEV = null; + + { + prevTaskInDEV = currentTaskInDEV; + currentTaskInDEV = task; + } + + try { + // We call the destructive form that mutates this task. That way if something + // suspends again, we can reuse the same task instead of spawning a new one. + renderNodeDestructive(request, task, task.node); + pushSegmentFinale$1(segment.chunks, request.responseState, segment.lastPushedText, segment.textEmbedded); + task.abortSet.delete(task); + segment.status = COMPLETED; + finishedTask(request, task.blockedBoundary, segment); + } catch (x) { + resetHooksState(); + + if (typeof x === 'object' && x !== null && typeof x.then === 'function') { + // Something suspended again, let's pick it back up later. + var ping = task.ping; + x.then(ping, ping); + } else { + task.abortSet.delete(task); + segment.status = ERRORED; + erroredTask(request, task.blockedBoundary, segment, x); + } + } finally { + { + currentTaskInDEV = prevTaskInDEV; + } + } +} + +function performWork(request) { + if (request.status === CLOSED) { + return; + } + + var prevContext = getActiveContext(); + var prevDispatcher = ReactCurrentDispatcher$1.current; + ReactCurrentDispatcher$1.current = Dispatcher; + var prevGetCurrentStackImpl; + + { + prevGetCurrentStackImpl = ReactDebugCurrentFrame$1.getCurrentStack; + ReactDebugCurrentFrame$1.getCurrentStack = getCurrentStackInDEV; + } + + var prevResponseState = currentResponseState; + setCurrentResponseState(request.responseState); + + try { + var pingedTasks = request.pingedTasks; + var i; + + for (i = 0; i < pingedTasks.length; i++) { + var task = pingedTasks[i]; + retryTask(request, task); + } + + pingedTasks.splice(0, i); + + if (request.destination !== null) { + flushCompletedQueues(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } finally { + setCurrentResponseState(prevResponseState); + ReactCurrentDispatcher$1.current = prevDispatcher; + + { + ReactDebugCurrentFrame$1.getCurrentStack = prevGetCurrentStackImpl; + } + + if (prevDispatcher === Dispatcher) { + // This means that we were in a reentrant work loop. This could happen + // in a renderer that supports synchronous work like renderToString, + // when it's called from within another renderer. + // Normally we don't bother switching the contexts to their root/default + // values when leaving because we'll likely need the same or similar + // context again. However, when we're inside a synchronous loop like this + // we'll to restore the context to what it was before returning. + switchContext(prevContext); + } + } +} + +function flushSubtree(request, destination, segment) { + segment.parentFlushed = true; + + switch (segment.status) { + case PENDING: + { + // We're emitting a placeholder for this segment to be filled in later. + // Therefore we'll need to assign it an ID - to refer to it by. + var segmentID = segment.id = request.nextSegmentId++; // When this segment finally completes it won't be embedded in text since it will flush separately + + segment.lastPushedText = false; + segment.textEmbedded = false; + return writePlaceholder(destination, request.responseState, segmentID); + } + + case COMPLETED: + { + segment.status = FLUSHED; + var r = true; + var chunks = segment.chunks; + var chunkIdx = 0; + var children = segment.children; + + for (var childIdx = 0; childIdx < children.length; childIdx++) { + var nextChild = children[childIdx]; // Write all the chunks up until the next child. + + for (; chunkIdx < nextChild.index; chunkIdx++) { + writeChunk(destination, chunks[chunkIdx]); + } + + r = flushSegment(request, destination, nextChild); + } // Finally just write all the remaining chunks + + + for (; chunkIdx < chunks.length - 1; chunkIdx++) { + writeChunk(destination, chunks[chunkIdx]); + } + + if (chunkIdx < chunks.length) { + r = writeChunkAndReturn(destination, chunks[chunkIdx]); + } + + return r; + } + + default: + { + throw new Error('Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.'); + } + } +} + +function flushSegment(request, destination, segment) { + var boundary = segment.boundary; + + if (boundary === null) { + // Not a suspense boundary. + return flushSubtree(request, destination, segment); + } + + boundary.parentFlushed = true; // This segment is a Suspense boundary. We need to decide whether to + // emit the content or the fallback now. + + if (boundary.forceClientRender) { + // Emit a client rendered suspense boundary wrapper. + // We never queue the inner boundary so we'll never emit its content or partial segments. + writeStartClientRenderedSuspenseBoundary$1(destination, request.responseState, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack); // Flush the fallback. + + flushSubtree(request, destination, segment); + return writeEndClientRenderedSuspenseBoundary$1(destination, request.responseState); + } else if (boundary.pendingTasks > 0) { + // This boundary is still loading. Emit a pending suspense boundary wrapper. + // Assign an ID to refer to the future content by. + boundary.rootSegmentID = request.nextSegmentId++; + + if (boundary.completedSegments.length > 0) { + // If this is at least partially complete, we can queue it to be partially emitted early. + request.partialBoundaries.push(boundary); + } /// This is the first time we should have referenced this ID. + + + var id = boundary.id = assignSuspenseBoundaryID(request.responseState); + writeStartPendingSuspenseBoundary(destination, request.responseState, id); // Flush the fallback. + + flushSubtree(request, destination, segment); + return writeEndPendingSuspenseBoundary(destination, request.responseState); + } else if (boundary.byteSize > request.progressiveChunkSize) { + // This boundary is large and will be emitted separately so that we can progressively show + // other content. We add it to the queue during the flush because we have to ensure that + // the parent flushes first so that there's something to inject it into. + // We also have to make sure that it's emitted into the queue in a deterministic slot. + // I.e. we can't insert it here when it completes. + // Assign an ID to refer to the future content by. + boundary.rootSegmentID = request.nextSegmentId++; + request.completedBoundaries.push(boundary); // Emit a pending rendered suspense boundary wrapper. + + writeStartPendingSuspenseBoundary(destination, request.responseState, boundary.id); // Flush the fallback. + + flushSubtree(request, destination, segment); + return writeEndPendingSuspenseBoundary(destination, request.responseState); + } else { + // We can inline this boundary's content as a complete boundary. + writeStartCompletedSuspenseBoundary$1(destination, request.responseState); + var completedSegments = boundary.completedSegments; + + if (completedSegments.length !== 1) { + throw new Error('A previously unvisited boundary must have exactly one root segment. This is a bug in React.'); + } + + var contentSegment = completedSegments[0]; + flushSegment(request, destination, contentSegment); + return writeEndCompletedSuspenseBoundary$1(destination, request.responseState); + } +} + +function flushClientRenderedBoundary(request, destination, boundary) { + return writeClientRenderBoundaryInstruction(destination, request.responseState, boundary.id, boundary.errorDigest, boundary.errorMessage, boundary.errorComponentStack); +} + +function flushSegmentContainer(request, destination, segment) { + writeStartSegment(destination, request.responseState, segment.formatContext, segment.id); + flushSegment(request, destination, segment); + return writeEndSegment(destination, segment.formatContext); +} + +function flushCompletedBoundary(request, destination, boundary) { + var completedSegments = boundary.completedSegments; + var i = 0; + + for (; i < completedSegments.length; i++) { + var segment = completedSegments[i]; + flushPartiallyCompletedSegment(request, destination, boundary, segment); + } + + completedSegments.length = 0; + return writeCompletedBoundaryInstruction(destination, request.responseState, boundary.id, boundary.rootSegmentID); +} + +function flushPartialBoundary(request, destination, boundary) { + var completedSegments = boundary.completedSegments; + var i = 0; + + for (; i < completedSegments.length; i++) { + var segment = completedSegments[i]; + + if (!flushPartiallyCompletedSegment(request, destination, boundary, segment)) { + i++; + completedSegments.splice(0, i); // Only write as much as the buffer wants. Something higher priority + // might want to write later. + + return false; + } + } + + completedSegments.splice(0, i); + return true; +} + +function flushPartiallyCompletedSegment(request, destination, boundary, segment) { + if (segment.status === FLUSHED) { + // We've already flushed this inline. + return true; + } + + var segmentID = segment.id; + + if (segmentID === -1) { + // This segment wasn't previously referred to. This happens at the root of + // a boundary. We make kind of a leap here and assume this is the root. + var rootSegmentID = segment.id = boundary.rootSegmentID; + + if (rootSegmentID === -1) { + throw new Error('A root segment ID must have been assigned by now. This is a bug in React.'); + } + + return flushSegmentContainer(request, destination, segment); + } else { + flushSegmentContainer(request, destination, segment); + return writeCompletedSegmentInstruction(destination, request.responseState, segmentID); + } +} + +function flushCompletedQueues(request, destination) { + + try { + // The structure of this is to go through each queue one by one and write + // until the sink tells us to stop. When we should stop, we still finish writing + // that item fully and then yield. At that point we remove the already completed + // items up until the point we completed them. + // TODO: Emit preloading. + // TODO: It's kind of unfortunate to keep checking this array after we've already + // emitted the root. + var completedRootSegment = request.completedRootSegment; + + if (completedRootSegment !== null && request.pendingRootTasks === 0) { + flushSegment(request, destination, completedRootSegment); + request.completedRootSegment = null; + writeCompletedRoot(destination, request.responseState); + } // We emit client rendering instructions for already emitted boundaries first. + // This is so that we can signal to the client to start client rendering them as + // soon as possible. + + + var clientRenderedBoundaries = request.clientRenderedBoundaries; + var i; + + for (i = 0; i < clientRenderedBoundaries.length; i++) { + var boundary = clientRenderedBoundaries[i]; + + if (!flushClientRenderedBoundary(request, destination, boundary)) { + request.destination = null; + i++; + clientRenderedBoundaries.splice(0, i); + return; + } + } + + clientRenderedBoundaries.splice(0, i); // Next we emit any complete boundaries. It's better to favor boundaries + // that are completely done since we can actually show them, than it is to emit + // any individual segments from a partially complete boundary. + + var completedBoundaries = request.completedBoundaries; + + for (i = 0; i < completedBoundaries.length; i++) { + var _boundary = completedBoundaries[i]; + + if (!flushCompletedBoundary(request, destination, _boundary)) { + request.destination = null; + i++; + completedBoundaries.splice(0, i); + return; + } + } + + completedBoundaries.splice(0, i); // Allow anything written so far to flush to the underlying sink before + // we continue with lower priorities. + + completeWriting(destination); + beginWriting(destination); // TODO: Here we'll emit data used by hydration. + // Next we emit any segments of any boundaries that are partially complete + // but not deeply complete. + + var partialBoundaries = request.partialBoundaries; + + for (i = 0; i < partialBoundaries.length; i++) { + var _boundary2 = partialBoundaries[i]; + + if (!flushPartialBoundary(request, destination, _boundary2)) { + request.destination = null; + i++; + partialBoundaries.splice(0, i); + return; + } + } + + partialBoundaries.splice(0, i); // Next we check the completed boundaries again. This may have had + // boundaries added to it in case they were too larged to be inlined. + // New ones might be added in this loop. + + var largeBoundaries = request.completedBoundaries; + + for (i = 0; i < largeBoundaries.length; i++) { + var _boundary3 = largeBoundaries[i]; + + if (!flushCompletedBoundary(request, destination, _boundary3)) { + request.destination = null; + i++; + largeBoundaries.splice(0, i); + return; + } + } + + largeBoundaries.splice(0, i); + } finally { + + if (request.allPendingTasks === 0 && request.pingedTasks.length === 0 && request.clientRenderedBoundaries.length === 0 && request.completedBoundaries.length === 0 // We don't need to check any partially completed segments because + // either they have pending task or they're complete. + ) { + { + if (request.abortableTasks.size !== 0) { + error('There was still abortable task at the root when we closed. This is a bug in React.'); + } + } // We're done. + + + close(destination); + } + } +} + +function startWork(request) { + scheduleWork(function () { + return performWork(request); + }); +} +function startFlowing(request, destination) { + if (request.status === CLOSING) { + request.status = CLOSED; + closeWithError(destination, request.fatalError); + return; + } + + if (request.status === CLOSED) { + return; + } + + if (request.destination !== null) { + // We're already flowing. + return; + } + + request.destination = destination; + + try { + flushCompletedQueues(request, destination); + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} // This is called to early terminate a request. It puts all pending boundaries in client rendered state. + +function abort(request, reason) { + try { + var abortableTasks = request.abortableTasks; + abortableTasks.forEach(function (task) { + return abortTask(task, request, reason); + }); + abortableTasks.clear(); + + if (request.destination !== null) { + flushCompletedQueues(request, request.destination); + } + } catch (error) { + logRecoverableError(request, error); + fatalError(request, error); + } +} + +function onError() {// Non-fatal errors are ignored. +} + +function renderToStringImpl(children, options, generateStaticMarkup, abortReason) { + var didFatal = false; + var fatalError = null; + var result = ''; + var destination = { + push: function (chunk) { + if (chunk !== null) { + result += chunk; + } + + return true; + }, + destroy: function (error) { + didFatal = true; + fatalError = error; + } + }; + var readyToStream = false; + + function onShellReady() { + readyToStream = true; + } + + var request = createRequest(children, createResponseState$1(generateStaticMarkup, options ? options.identifierPrefix : undefined), createRootFormatContext(), Infinity, onError, undefined, onShellReady, undefined, undefined); + startWork(request); // If anything suspended and is still pending, we'll abort it before writing. + // That way we write only client-rendered boundaries from the start. + + abort(request, abortReason); + startFlowing(request, destination); + + if (didFatal) { + throw fatalError; + } + + if (!readyToStream) { + // Note: This error message is the one we use on the client. It doesn't + // really make sense here. But this is the legacy server renderer, anyway. + // We're going to delete it soon. + throw new Error('A component suspended while responding to synchronous input. This ' + 'will cause the UI to be replaced with a loading indicator. To fix, ' + 'updates that suspend should be wrapped with startTransition.'); + } + + return result; +} + +function renderToString(children, options) { + return renderToStringImpl(children, options, false, 'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server'); +} + +function renderToStaticMarkup(children, options) { + return renderToStringImpl(children, options, true, 'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server'); +} + +function renderToNodeStream() { + throw new Error('ReactDOMServer.renderToNodeStream(): The streaming API is not available ' + 'in the browser. Use ReactDOMServer.renderToString() instead.'); +} + +function renderToStaticNodeStream() { + throw new Error('ReactDOMServer.renderToStaticNodeStream(): The streaming API is not available ' + 'in the browser. Use ReactDOMServer.renderToStaticMarkup() instead.'); +} + +exports.renderToNodeStream = renderToNodeStream; +exports.renderToStaticMarkup = renderToStaticMarkup; +exports.renderToStaticNodeStream = renderToStaticNodeStream; +exports.renderToString = renderToString; +exports.version = ReactVersion; + })(); +} diff --git a/node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js b/node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js new file mode 100644 index 0000000..1568365 --- /dev/null +++ b/node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js @@ -0,0 +1,93 @@ +/** + * @license React + * react-dom-server-legacy.browser.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +'use strict';var aa=require("react");function l(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c