diff --git a/.do/deploy.template.yaml b/.do/deploy.template.yaml new file mode 100644 index 0000000..311cd1e --- /dev/null +++ b/.do/deploy.template.yaml @@ -0,0 +1,43 @@ +spec: + name: budgetzen + envs: + - key: BASE_URL + scope: RUN_AND_BUILD_TIME + value: ${app.PUBLIC_URL} + services: + - name: app + dockerfile_path: Dockerfile + git: + branch: main + http_port: 8000 + instance_count: 1 + instance_size_slug: basic-xs + routes: + - path: / + health_check: + http_path: / + source_dir: / + envs: + - key: POSTGRESQL_HOST + scope: RUN_AND_BUILD_TIME + value: ${db.HOSTNAME} + - key: POSTGRESQL_USER + scope: RUN_AND_BUILD_TIME + value: ${db.USERNAME} + - key: POSTGRESQL_PASSWORD + scope: RUN_AND_BUILD_TIME + value: ${db.PASSWORD} + - key: POSTGRESQL_DBNAME + scope: RUN_AND_BUILD_TIME + value: ${db.DATABASE} + - key: POSTGRESQL_PORT + scope: RUN_AND_BUILD_TIME + value: ${db.PORT} + - key: POSTGRESQL_CAFILE + scope: RUN_AND_BUILD_TIME + value: "" + databases: + - name: db + engine: PG + production: false + version: "15" diff --git a/.dvmrc b/.dvmrc index 83cf0d9..b0f3390 100644 --- a/.dvmrc +++ b/.dvmrc @@ -1 +1 @@ -1.29.1 +1.30.3 diff --git a/.env.sample b/.env.sample index 8526897..55c5e57 100644 --- a/.env.sample +++ b/.env.sample @@ -1 +1,16 @@ -USERBASE_APP_ID=get-from-userbase.com +PORT=8000 +BASE_URL="http://localhost:8000" + +POSTGRESQL_HOST="localhost" +POSTGRESQL_USER="postgres" +POSTGRESQL_PASSWORD="fake" +POSTGRESQL_DBNAME="budgetzen" +POSTGRESQL_PORT=5432 +POSTGRESQL_CAFILE="" + +POSTMARK_SERVER_API_TOKEN="fake" + +STRIPE_API_KEY="fake" + +PAYPAL_CLIENT_ID="fake" +PAYPAL_CLIENT_SECRET="fake" diff --git a/.github/workflows/cron-check-subscriptions.yml b/.github/workflows/cron-check-subscriptions.yml new file mode 100644 index 0000000..8d5b0be --- /dev/null +++ b/.github/workflows/cron-check-subscriptions.yml @@ -0,0 +1,28 @@ +name: "Cron: Check subscriptions" + +on: + workflow_dispatch: + schedule: + # At 04:06 every day. + - cron: '6 4 * * *' + +jobs: + cron-cleanup: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: denoland/setup-deno@v1 + with: + deno-version: v1.30.3 + - env: + POSTGRESQL_HOST: ${{ secrets.POSTGRESQL_HOST }} + POSTGRESQL_USER: ${{ secrets.POSTGRESQL_USER }} + POSTGRESQL_PASSWORD: ${{ secrets.POSTGRESQL_PASSWORD }} + POSTGRESQL_DBNAME: ${{ secrets.POSTGRESQL_DBNAME }} + POSTGRESQL_PORT: ${{ secrets.POSTGRESQL_PORT }} + POSTGRESQL_CAFILE: ${{ secrets.POSTGRESQL_CAFILE }} + STRIPE_API_KEY: ${{ secrets.STRIPE_API_KEY }} + PAYPAL_CLIENT_ID: ${{ secrets.PAYPAL_CLIENT_ID }} + PAYPAL_CLIENT_SECRET: ${{ secrets.PAYPAL_CLIENT_SECRET }} + run: | + make crons/check-subscriptions diff --git a/.github/workflows/cron-cleanup.yml b/.github/workflows/cron-cleanup.yml new file mode 100644 index 0000000..08dfe14 --- /dev/null +++ b/.github/workflows/cron-cleanup.yml @@ -0,0 +1,25 @@ +name: "Cron: Cleanup" + +on: + workflow_dispatch: + schedule: + # At 03:05 every day. + - cron: '5 3 * * *' + +jobs: + cron-cleanup: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: denoland/setup-deno@v1 + with: + deno-version: v1.30.3 + - env: + POSTGRESQL_HOST: ${{ secrets.POSTGRESQL_HOST }} + POSTGRESQL_USER: ${{ secrets.POSTGRESQL_USER }} + POSTGRESQL_PASSWORD: ${{ secrets.POSTGRESQL_PASSWORD }} + POSTGRESQL_DBNAME: ${{ secrets.POSTGRESQL_DBNAME }} + POSTGRESQL_PORT: ${{ secrets.POSTGRESQL_PORT }} + POSTGRESQL_CAFILE: ${{ secrets.POSTGRESQL_CAFILE }} + run: | + make crons/cleanup diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 37ea88e..85b996a 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -9,6 +9,12 @@ jobs: - uses: actions/checkout@v3 - uses: denoland/setup-deno@v1 with: - deno-version: v1.29.1 + deno-version: v1.30.3 + - run: docker-compose pull + - uses: jpribyl/action-docker-layer-caching@v0.1.1 + continue-on-error: true - run: | + cp .env.sample .env + docker-compose up -d + make migrate-db make test diff --git a/Caddyfile b/Caddyfile new file mode 100644 index 0000000..e1827d5 --- /dev/null +++ b/Caddyfile @@ -0,0 +1,3 @@ +localhost + +reverse_proxy * localhost:8000 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..1ea7be4 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,16 @@ +FROM denoland/deno:1.30.3 + +EXPOSE 8000 + +WORKDIR /app + +# Prefer not to run as root. +USER deno + +# These steps will be re-run upon each file change in your working directory: +ADD . /app + +# Compile the main app so that it doesn't need to be compiled each startup/entry. +RUN deno cache --reload main.ts + +CMD ["make", "start"] diff --git a/Makefile b/Makefile index db70e4d..ac5b86a 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ .PHONY: start start: - deno run --watch --allow-net --allow-read=public,pages,.env,.env.defaults,.env.example --allow-env main.ts + deno run --watch --allow-net --allow-read --allow-env main.ts .PHONY: format format: @@ -10,4 +10,20 @@ format: test: deno fmt --check deno lint - deno test --allow-net --allow-read=public,pages,.env,.env.defaults,.env.example --allow-env --check=all + deno test --allow-net --allow-read --allow-env --check + +.PHONY: migrate-db +migrate-db: + deno run --allow-net --allow-read --allow-env migrate-db.ts + +.PHONY: crons/check-subscriptions +crons/check-subscriptions: + deno run --allow-net --allow-read --allow-env crons/check-subscriptions.ts + +.PHONY: crons/cleanup +crons/cleanup: + deno run --allow-net --allow-read --allow-env crons/cleanup.ts + +.PHONY: exec-db +exec-db: + docker exec -it -u postgres $(shell basename $(CURDIR))_postgresql_1 psql diff --git a/README.md b/README.md index 1be7442..6c43f40 100644 --- a/README.md +++ b/README.md @@ -4,31 +4,61 @@ This is the web app for the [Budget Zen app](https://budgetzen.net), built with [Deno](https://deno.land) and deployed to [Deno Deploy](https://deno.com/deploy). -This is v2, which is [end-to-end encrypted via userbase](https://userbase.com), and works via web on any device (it's a PWA - Progressive Web App). +This is v3, which is [end-to-end encrypted with open Web Standards](https://en.wikipedia.org/wiki/End-to-end_encryption), and works via web on any device (it's a PWA - Progressive Web App). -It's not compatible with Budget Zen v1 (not end-to-end encrypted), which you can still get locally from [this commit](https://github.com/BrunoBernardino/budgetzen-web/tree/397d625469b7dfd8d1968c847b32e607ee7c8ee9). You can still export and import the data as the JSON format is the same (unencrypted). +It's not compatible with Budget Zen v2 ([end-to-end encrypted via Userbase](https://userbase.com)) which you can still get locally from [this commit](https://github.com/BrunoBernardino/budgetzen-web/tree/7e88a602be437cd4d54268f87113b21e9cff5c60), nor v1 (not end-to-end encrypted), which you can still get locally from [this commit](https://github.com/BrunoBernardino/budgetzen-web/tree/397d625469b7dfd8d1968c847b32e607ee7c8ee9). You can still export and import the data as the JSON format is the same across all 3 versions (unencrypted). + +## Self-host it! + +[![Deploy to DigitalOcean](https://www.deploytodo.com/do-btn-blue.svg)](https://cloud.digitalocean.com/apps/new?repo=https://github.com/BrunoBernardino/budgetzen-web) + +[![Deploy to Render](https://render.com/images/deploy-to-render-button.svg)](https://render.com/deploy?repo=https://github.com/BrunoBernardino/budgetzen-web) + +Or check the [Development section below](#development). + +> **NOTE:** You don't need to have emails (Postmark) and subscriptions (Stripe/PayPal) setup to have the app work. Those are only used for allowing others to automatically manage their account. You can simply make any `user.status = 'active'` and `user.subscription.expires_at = new Date('2100-01-01')` to "never" expire, in the database, directly. + +## Framework-less + +This right here is vanilla TypeScript and JavaScript using Web Standards. It's very easy to update and maintain. + +It's meant to have no unnecessary dependencies, packagers, or bundlers. Just vanilla, simple stuff. ## Requirements -This was tested with `deno`'s version in the `.dvmrc` file, though it's possible other versions might work. +This was tested with [`Deno`](https://deno.land)'s version stated in the `.dvmrc` file, though other versions may work. -There are no other dependencies. **Deno**! +For the PostgreSQL dependency (used when running locally, self-hosted, or in CI), you should have `Docker` and `docker-compose` installed. + +If you want to run the app locally with SSL (Web Crypto standards require `https` except for Chrome), you can use [`Caddy`](https://caddyserver.com) (there's a `Caddyfile` that proxies `https://localhost` to the Deno app). + +Don't forget to set up your `.env` file based on `.env.sample`. ## Development ```sh -$ make start -$ make format -$ make test +$ docker-compose up # (optional) runs docker with postgres, locally +$ sudo caddy run # (optional) runs an https proxy for the deno app +$ make migrate-db # runs any missing database migrations +$ make start # runs the app +$ make format # formats the code +$ make test # runs tests ``` -## Structure +## Other less-used commands -This is vanilla JS, web standards, no frameworks. If you'd like to see/use [the Next.js version deployed to AWS via Serverless, check this commit](https://github.com/BrunoBernardino/budgetzen-web/tree/b1097c710ba89abf9aed044a7d7444e91d04a6a7). +```sh +$ make exec-db # runs psql inside the postgres container, useful for running direct development queries like `DROP DATABASE "budgetzen"; CREATE DATABASE "budgetzen";` +``` + +## Structure - Backend routes are defined at `routes.ts`. -- Static files are defined at `public/`. +- Publicly-available files are defined at `public/`. - Pages are defined at `pages/`. +- Cron jobs are defined at `crons/`. +- Reusable bits of code are defined at `lib/`. +- Database migrations are defined at `db-migrations/`. ## Deployment @@ -37,4 +67,3 @@ This is vanilla JS, web standards, no frameworks. If you'd like to see/use [the ## TODOs: - [ ] Enable true offline mode (securely cache data, allow read-only) - - https://github.com/smallbets/userbase/issues/255 has interesting ideas, while it's not natively supported diff --git a/components/footer.ts b/components/footer.ts index 56d3f77..ad68b56 100644 --- a/components/footer.ts +++ b/components/footer.ts @@ -1,4 +1,4 @@ -import { html } from '../lib/utils.ts'; +import { helpEmail, html } from '/lib/utils.ts'; export default function footer() { return html` @@ -9,7 +9,7 @@ export default function footer() {

What is Budget Zen?

- Simple and encrypted budget management. + Simple and encrypted expense management. Read more here.

@@ -47,8 +47,9 @@ export default function footer() { diff --git a/components/header.ts b/components/header.ts index f986c5b..35584fa 100644 --- a/components/header.ts +++ b/components/header.ts @@ -1,4 +1,4 @@ -import { html } from '../lib/utils.ts'; +import { html } from '/lib/utils.ts'; export default function header(currentPath: string) { return html` diff --git a/components/loading.ts b/components/loading.ts index 49b59f7..a3486a2 100644 --- a/components/loading.ts +++ b/components/loading.ts @@ -1,4 +1,4 @@ -import { html } from '../lib/utils.ts'; +import { html } from '/lib/utils.ts'; export default function loading() { return html` diff --git a/components/modals/verification-code.ts b/components/modals/verification-code.ts new file mode 100644 index 0000000..25e0b9a --- /dev/null +++ b/components/modals/verification-code.ts @@ -0,0 +1,31 @@ +import { html } from '/lib/utils.ts'; + +export default function verificationCodeModal() { + return html` + + `; +} diff --git a/crons/check-subscriptions.ts b/crons/check-subscriptions.ts new file mode 100644 index 0000000..e89110a --- /dev/null +++ b/crons/check-subscriptions.ts @@ -0,0 +1,88 @@ +import Database, { sql } from '/lib/interfaces/database.ts'; +import { getSubscriptions as getStripeSubscriptions } from '/lib/providers/stripe.ts'; +// import { getSubscriptions as getPaypalSubscriptions } from '/lib/providers/paypal.ts'; +import { updateUser } from '/lib/data-utils.ts'; +import { User } from '/lib/types.ts'; + +const db = new Database(); + +async function checkSubscriptions() { + try { + const users = await db.query( + sql`SELECT * FROM "budgetzen_users" WHERE "status" IN ('active', 'trial')`, + ); + + let updatedUsers = 0; + + const stripeSubscriptions = await getStripeSubscriptions(); + + for (const subscription of stripeSubscriptions) { + // Skip subscriptions that aren't related to Budget Zen + if (!subscription.items.data.some((item) => item.price.id.startsWith('budget-zen-'))) { + continue; + } + + const matchingUser = users.find((user) => user.email === subscription.customer.email); + + if (matchingUser) { + if (!matchingUser.subscription.external.stripe) { + matchingUser.subscription.external.stripe = { + user_id: subscription.customer.id, + subscription_id: subscription.id, + }; + } + + matchingUser.subscription.isMonthly = subscription.items.data.some((item) => item.price.id.includes('monthly')); + matchingUser.subscription.updated_at = new Date().toISOString(); + matchingUser.subscription.expires_at = new Date(subscription.current_period_end * 1000).toISOString(); + + if (['active', 'paused'].includes(subscription.status)) { + matchingUser.status = 'active'; + } else if (subscription.status === 'trialing') { + matchingUser.status = 'trial'; + } else { + matchingUser.status = 'inactive'; + } + + await updateUser(matchingUser); + + ++updatedUsers; + } + } + + // const paypalSubscriptions = await getPaypalSubscriptions(); + + // for (const subscription of paypalSubscriptions) { + // const matchingUser = users.find((user) => user.email === subscription.subscriber.email_address); + + // if (matchingUser) { + // if (!matchingUser.subscription.external.paypal) { + // matchingUser.subscription.external.paypal = { + // user_id: subscription.subscriber.payer_id, + // subscription_id: subscription.id, + // }; + // } + + // matchingUser.subscription.isMonthly = parseInt(subscription.billing_info.last_payment.amount.value, 10) < 10; + // matchingUser.subscription.updated_at = new Date().toISOString(); + // matchingUser.subscription.expires_at = new Date(subscription.billing_info.next_billing_time).toISOString(); + + // if (['ACTIVE', 'APPROVED'].includes(subscription.status)) { + // matchingUser.status = 'active'; + // } else { + // matchingUser.status = 'inactive'; + // } + + // await updateUser(matchingUser); + + // ++updatedUsers; + // } + // } + + console.log('Updated', updatedUsers, 'users'); + } catch (error) { + console.log(error); + } +} + +await checkSubscriptions(); diff --git a/crons/cleanup.ts b/crons/cleanup.ts new file mode 100644 index 0000000..1e07ad0 --- /dev/null +++ b/crons/cleanup.ts @@ -0,0 +1,82 @@ +import Database, { sql } from '/lib/interfaces/database.ts'; +import { User } from '/lib/types.ts'; + +const db = new Database(); + +async function cleanupSessions() { + const yesterday = new Date(new Date().setUTCDate(new Date().getUTCDate() - 1)); + + try { + const result = await db.query<{ count: number }>( + sql`WITH "deleted" AS ( + DELETE FROM "budgetzen_user_sessions" WHERE "expires_at" <= $1 RETURNING * + ) + SELECT COUNT(*) FROM "deleted"`, + [ + yesterday.toISOString().substring(0, 10), + ], + ); + + console.log('Deleted', result[0].count, 'user sessions'); + } catch (error) { + console.log(error); + } +} + +async function cleanupInactiveUsers() { + const thirtyDaysAgo = new Date(new Date().setUTCDate(new Date().getUTCDate() - 30)); + + try { + const result = await db.query>( + sql`SELECT "id" FROM "budgetzen_users" WHERE "status" = 'inactive' AND "subscription" ->> 'expires_at' <= $1`, + [ + thirtyDaysAgo.toISOString().substring(0, 10), + ], + ); + + const userIdsToDelete = result.map((user) => user.id); + + await db.query( + sql`DELETE FROM "budgetzen_user_sessions" WHERE "user_id" = ANY($1)`, + [ + userIdsToDelete, + ], + ); + + await db.query( + sql`DELETE FROM "budgetzen_verification_codes" WHERE "user_id" = ANY($1)`, + [ + userIdsToDelete, + ], + ); + + await db.query( + sql`DELETE FROM "budgetzen_budgets" WHERE "user_id" = ANY($1)`, + [ + userIdsToDelete, + ], + ); + + await db.query( + sql`DELETE FROM "budgetzen_expenses" WHERE "user_id" = ANY($1)`, + [ + userIdsToDelete, + ], + ); + + await db.query( + sql`DELETE FROM "budgetzen_users" WHERE "id" = ANY($1)`, + [ + userIdsToDelete, + ], + ); + + console.log('Deleted', userIdsToDelete.length, 'users'); + } catch (error) { + console.log(error); + } +} + +await cleanupInactiveUsers(); + +await cleanupSessions(); diff --git a/db-migrations/001-base.pgsql b/db-migrations/001-base.pgsql new file mode 100644 index 0000000..64852c9 --- /dev/null +++ b/db-migrations/001-base.pgsql @@ -0,0 +1,239 @@ +SET statement_timeout = 0; +SET lock_timeout = 0; +SET idle_in_transaction_session_timeout = 0; +SET client_encoding = 'UTF8'; +SET standard_conforming_strings = on; +SELECT pg_catalog.set_config('search_path', '', false); +SET check_function_bodies = false; +SET xmloption = content; +SET client_min_messages = warning; +SET row_security = off; + + +-- +-- Name: budgetzen_user_sessions; Type: TABLE; Schema: public; Owner: postgres +-- + +CREATE TABLE public.budgetzen_user_sessions ( + id uuid DEFAULT gen_random_uuid(), + user_id uuid DEFAULT gen_random_uuid(), + expires_at timestamp with time zone NOT NULL, + verified BOOLEAN NOT NULL, + last_seen_at timestamp with time zone DEFAULT now(), + created_at timestamp with time zone DEFAULT now() +); + + +ALTER TABLE public.budgetzen_user_sessions OWNER TO postgres; + + +-- +-- Name: budgetzen_verification_codes; Type: TABLE; Schema: public; Owner: postgres +-- + +CREATE TABLE public.budgetzen_verification_codes ( + id uuid DEFAULT gen_random_uuid(), + user_id uuid DEFAULT gen_random_uuid(), + code character varying NOT NULL, + verification jsonb NOT NULL, + expires_at timestamp with time zone NOT NULL, + created_at timestamp with time zone DEFAULT now() +); + + +ALTER TABLE public.budgetzen_verification_codes OWNER TO postgres; + + +-- +-- Name: budgetzen_budgets; Type: TABLE; Schema: public; Owner: postgres +-- + +CREATE TABLE public.budgetzen_budgets ( + id uuid DEFAULT gen_random_uuid(), + user_id uuid DEFAULT gen_random_uuid(), + name text NOT NULL, + month character varying NOT NULL, + value text NOT NULL, + extra jsonb NOT NULL +); + + +ALTER TABLE public.budgetzen_budgets OWNER TO postgres; + + +-- +-- Name: budgetzen_expenses; Type: TABLE; Schema: public; Owner: postgres +-- + +CREATE TABLE public.budgetzen_expenses ( + id uuid DEFAULT gen_random_uuid(), + user_id uuid DEFAULT gen_random_uuid(), + cost text NOT NULL, + description text NOT NULL, + budget text NOT NULL, + date character varying NOT NULL, + is_recurring BOOLEAN NOT NULL, + extra jsonb NOT NULL +); + + +ALTER TABLE public.budgetzen_expenses OWNER TO postgres; + + +-- +-- Name: budgetzen_users; Type: TABLE; Schema: public; Owner: postgres +-- + +CREATE TABLE public.budgetzen_users ( + id uuid DEFAULT gen_random_uuid(), + email character varying NOT NULL, + encrypted_key_pair text NOT NULL, + subscription jsonb NOT NULL, + status character varying NOT NULL, + extra jsonb NOT NULL, + created_at timestamp with time zone DEFAULT now() +); + + +ALTER TABLE public.budgetzen_users OWNER TO postgres; + + +-- +-- Name: budgetzen_migrations; Type: TABLE; Schema: public; Owner: postgres +-- + +CREATE TABLE public.budgetzen_migrations ( + id uuid DEFAULT gen_random_uuid(), + name character varying(100) NOT NULL, + executed_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP +); + +ALTER TABLE public.budgetzen_migrations OWNER TO postgres; + + +-- +-- Name: budgetzen_user_sessions budgetzen_user_sessions_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres +-- + +ALTER TABLE ONLY public.budgetzen_user_sessions + ADD CONSTRAINT budgetzen_user_sessions_pkey PRIMARY KEY (id); + + +-- +-- Name: budgetzen_verification_codes budgetzen_verification_codes_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres +-- + +ALTER TABLE ONLY public.budgetzen_verification_codes + ADD CONSTRAINT budgetzen_verification_codes_pkey PRIMARY KEY (id); + + +-- +-- Name: budgetzen_budgets budgetzen_budgets_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres +-- + +ALTER TABLE ONLY public.budgetzen_budgets + ADD CONSTRAINT budgetzen_budgets_pkey PRIMARY KEY (id); + + +-- +-- Name: budgetzen_expenses budgetzen_expenses_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres +-- + +ALTER TABLE ONLY public.budgetzen_expenses + ADD CONSTRAINT budgetzen_expenses_pkey PRIMARY KEY (id); + + +-- +-- Name: budgetzen_users budgetzen_users_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres +-- + +ALTER TABLE ONLY public.budgetzen_users + ADD CONSTRAINT budgetzen_users_pkey PRIMARY KEY (id); + + +-- +-- Name: budgetzen_user_sessions budgetzen_user_sessions_user_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres +-- + +ALTER TABLE ONLY public.budgetzen_user_sessions + ADD CONSTRAINT budgetzen_user_sessions_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.budgetzen_users(id); + + +-- +-- Name: budgetzen_verification_codes budgetzen_verification_codes_user_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres +-- + +ALTER TABLE ONLY public.budgetzen_verification_codes + ADD CONSTRAINT budgetzen_verification_codes_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.budgetzen_users(id); + + +-- +-- Name: budgetzen_budgets budgetzen_budgets_user_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres +-- + +ALTER TABLE ONLY public.budgetzen_budgets + ADD CONSTRAINT budgetzen_budgets_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.budgetzen_users(id); + + +-- +-- Name: budgetzen_expenses budgetzen_expenses_user_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres +-- + +ALTER TABLE ONLY public.budgetzen_expenses + ADD CONSTRAINT budgetzen_expenses_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.budgetzen_users(id); + + +-- +-- Name: TABLE budgetzen_user_sessions; Type: ACL; Schema: public; Owner: postgres +-- + +GRANT ALL ON TABLE public.budgetzen_user_sessions TO postgres; + + +-- +-- Name: TABLE budgetzen_verification_codes; Type: ACL; Schema: public; Owner: postgres +-- + +GRANT ALL ON TABLE public.budgetzen_verification_codes TO postgres; + + +-- +-- Name: TABLE budgetzen_budgets; Type: ACL; Schema: public; Owner: postgres +-- + +GRANT ALL ON TABLE public.budgetzen_budgets TO postgres; + + +-- +-- Name: TABLE budgetzen_expenses; Type: ACL; Schema: public; Owner: postgres +-- + +GRANT ALL ON TABLE public.budgetzen_expenses TO postgres; + + +-- +-- Name: TABLE budgetzen_users; Type: ACL; Schema: public; Owner: postgres +-- + +GRANT ALL ON TABLE public.budgetzen_users TO postgres; + + +-- +-- Name: DEFAULT PRIVILEGES FOR SEQUENCES; Type: DEFAULT ACL; Schema: public; Owner: postgres +-- + +ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO postgres; + + +-- +-- Name: DEFAULT PRIVILEGES FOR FUNCTIONS; Type: DEFAULT ACL; Schema: public; Owner: postgres +-- + +ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO postgres; + + +-- +-- Name: DEFAULT PRIVILEGES FOR TABLES; Type: DEFAULT ACL; Schema: public; Owner: postgres +-- + +ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO postgres; diff --git a/deno.json b/deno.json index 56a759d..a244982 100644 --- a/deno.json +++ b/deno.json @@ -9,10 +9,7 @@ }, "files": { "exclude": [ - "public/js/stripe.js", - "public/js/sweetalert.js", - "public/js/userbase.js", - "public/js/userbase.js.map" + "public/js/sweetalert.js" ] } }, @@ -25,13 +22,18 @@ }, "files": { "exclude": [ - "public/js/stripe.js", - "public/js/sweetalert.js", - "public/js/userbase.js", - "public/js/userbase.js.map" + "public/js/sweetalert.js" ] } }, + "compilerOptions": { + "lib": [ + "dom", + "dom.iterable", + "dom.asynciterable", + "deno.ns" + ] + }, "importMap": "./import_map.json", "lock": false } diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..38fd405 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,31 @@ +services: + postgresql: + image: postgres:15 + environment: + - POSTGRES_USER=postgres + - POSTGRES_PASSWORD=fake + - POSTGRES_DB=budgetzen + restart: on-failure + volumes: + - pgdata:/var/lib/postgresql/data + ports: + - 5432:5432 + ulimits: + memlock: + soft: -1 + hard: -1 + + # NOTE: This would be nice to develop with https:// locally, but it doesn't work, for whatever reason, so we need a system caddy instead + # caddy: + # image: caddy:2-alpine + # restart: unless-stopped + # command: caddy reverse-proxy --from https://localhost:443 --to http://localhost:8000 + # network_mode: "host" + # volumes: + # - caddy:/data + +volumes: + pgdata: + driver: local + # caddy: + # driver: local diff --git a/lib/data-utils.ts b/lib/data-utils.ts new file mode 100644 index 0000000..527d843 --- /dev/null +++ b/lib/data-utils.ts @@ -0,0 +1,478 @@ +import Database, { sql } from './interfaces/database.ts'; +import { Budget, Expense, User, UserSession, VerificationCode } from './types.ts'; +import { generateRandomCode, splitArrayInChunks } from './utils.ts'; + +const db = new Database(); + +export const monthRegExp = new RegExp(/^\d{4}\-\d{2}$/); + +export async function getUserByEmail(email: string) { + const lowercaseEmail = email.toLowerCase().trim(); + + const user = (await db.query(sql`SELECT * FROM "budgetzen_users" WHERE "email" = $1 LIMIT 1`, [ + lowercaseEmail, + ]))[0]; + + return user; +} + +export async function getUserById(id: string) { + const user = (await db.query(sql`SELECT * FROM "budgetzen_users" WHERE "id" = $1 LIMIT 1`, [ + id, + ]))[0]; + + return user; +} + +export async function createUser(email: User['email'], encryptedKeyPair: User['encrypted_key_pair']) { + const trialDays = 30; + const now = new Date(); + const trialEndDate = new Date(new Date().setUTCDate(new Date().getUTCDate() + trialDays)); + + const subscription: User['subscription'] = { + external: {}, + expires_at: trialEndDate.toISOString(), + updated_at: now.toISOString(), + }; + + const newUser = (await db.query( + sql`INSERT INTO "budgetzen_users" ( + "email", + "subscription", + "status", + "encrypted_key_pair", + "extra" + ) VALUES ($1, $2, $3, $4, $5) + RETURNING *`, + [ + email, + JSON.stringify(subscription), + 'trial', + encryptedKeyPair, + JSON.stringify({}), + ], + ))[0]; + + return newUser; +} + +export async function updateUser(user: User) { + await db.query( + sql`UPDATE "budgetzen_users" SET + "email" = $2, + "subscription" = $3, + "status" = $4, + "encrypted_key_pair" = $5, + "extra" = $6 + WHERE "id" = $1`, + [ + user.id, + user.email, + JSON.stringify(user.subscription), + user.status, + user.encrypted_key_pair, + JSON.stringify(user.extra), + ], + ); +} + +export async function deleteUser(userId: string) { + await db.query( + sql`DELETE FROM "budgetzen_user_sessions" WHERE "user_id" = $1`, + [ + userId, + ], + ); + + await db.query( + sql`DELETE FROM "budgetzen_verification_codes" WHERE "user_id" = $1`, + [ + userId, + ], + ); + + await db.query( + sql`DELETE FROM "budgetzen_budgets" WHERE "user_id" = $1`, + [ + userId, + ], + ); + + await db.query( + sql`DELETE FROM "budgetzen_expenses" WHERE "user_id" = $1`, + [ + userId, + ], + ); + + await db.query( + sql`DELETE FROM "budgetzen_users" WHERE "id" = $1`, + [ + userId, + ], + ); +} + +export async function getSessionById(id: string) { + const session = (await db.query( + sql`SELECT * FROM "budgetzen_user_sessions" WHERE "id" = $1 AND "expires_at" > now() LIMIT 1`, + [ + id, + ], + ))[0]; + + return session; +} + +export async function createSession(user: User, isNewUser = false) { + // Add new user session to the db + const oneMonthFromToday = new Date(new Date().setUTCMonth(new Date().getUTCMonth() + 1)); + + const newSession: Omit = { + user_id: user.id, + expires_at: oneMonthFromToday, + last_seen_at: new Date(), + verified: isNewUser, + }; + + const newUserSessionResult = (await db.query( + sql`INSERT INTO "budgetzen_user_sessions" ( + "user_id", + "expires_at", + "verified", + "last_seen_at" + ) VALUES ($1, $2, $3, $4) + RETURNING *`, + [ + newSession.user_id, + newSession.expires_at, + newSession.verified, + newSession.last_seen_at, + ], + ))[0]; + + return newUserSessionResult; +} + +export async function updateSession(session: UserSession) { + await db.query( + sql`UPDATE "budgetzen_user_sessions" SET + "expires_at" = $2, + "verified" = $3, + "last_seen_at" = $4 + WHERE "id" = $1`, + [ + session.id, + session.expires_at, + session.verified, + session.last_seen_at, + ], + ); +} + +export async function validateUserAndSession(userId: string, sessionId: string, acceptUnverifiedSession = false) { + const user = await getUserById(userId); + + if (!user) { + throw new Error('Not Found'); + } + + const session = await getSessionById(sessionId); + + if (!session || session.user_id !== user.id || (!session.verified && !acceptUnverifiedSession)) { + throw new Error('Not Found'); + } + + session.last_seen_at = new Date(); + + await updateSession(session); + + return { user, session }; +} + +export async function createVerificationCode( + user: User, + session: UserSession, + type: VerificationCode['verification']['type'], +) { + const inThirtyMinutes = new Date(new Date().setUTCMinutes(new Date().getUTCMinutes() + 30)); + + const code = generateRandomCode(); + + const newVerificationCode: Omit = { + user_id: user.id, + code, + expires_at: inThirtyMinutes, + verification: { + id: session.id, + type, + }, + }; + + await db.query( + sql`INSERT INTO "budgetzen_verification_codes" ( + "user_id", + "code", + "expires_at", + "verification" + ) VALUES ($1, $2, $3, $4) + RETURNING "id"`, + [ + newVerificationCode.user_id, + newVerificationCode.code, + newVerificationCode.expires_at, + JSON.stringify(newVerificationCode.verification), + ], + ); + + return code; +} + +export async function validateVerificationCode( + user: User, + session: UserSession, + code: string, + type: VerificationCode['verification']['type'], +) { + const verificationCode = (await db.query( + sql`SELECT * FROM "budgetzen_verification_codes" + WHERE "user_id" = $1 AND + "code" = $2 AND + "verification" ->> 'type' = $3 AND + "verification" ->> 'id' = $4 AND + "expires_at" > now() + LIMIT 1`, + [ + user.id, + code, + type, + session.id, + ], + ))[0]; + + if (verificationCode) { + await db.query( + sql`DELETE FROM "budgetzen_verification_codes" WHERE "id" = $1`, + [ + verificationCode.id, + ], + ); + } else { + throw new Error('Not Found'); + } +} + +export async function getAllBudgets(userId: string) { + const budgets = await db.query( + sql`SELECT * FROM "budgetzen_budgets" + WHERE "user_id" = $1 + ORDER BY "month" DESC`, + [ + userId, + ], + ); + + return budgets; +} + +export async function getBudgetsByMonth(userId: string, month: string) { + const budgets = await db.query( + sql`SELECT * FROM "budgetzen_budgets" + WHERE "user_id" = $1 AND + "month" = $2 + ORDER BY "month" DESC`, + [ + userId, + month, + ], + ); + + return budgets; +} + +export async function createBudget(budget: Omit) { + const newBudget = (await db.query( + sql`INSERT INTO "budgetzen_budgets" ( + "user_id", + "name", + "month", + "value", + "extra" + ) VALUES ($1, $2, $3, $4, $5) + RETURNING *`, + [ + budget.user_id, + budget.name, + budget.month, + budget.value, + JSON.stringify(budget.extra), + ], + ))[0]; + + return newBudget; +} + +// Don't allow updating a budget's month +export async function updateBudget(budget: Omit & { month?: Budget['month'] }) { + await db.query( + sql`UPDATE "budgetzen_budgets" SET + "name" = $2, + "value" = $3, + "extra" = $4 + WHERE "id" = $1`, + [ + budget.id, + budget.name, + budget.value, + JSON.stringify(budget.extra), + ], + ); +} + +export async function deleteBudget(budgetId: string) { + await db.query( + sql`DELETE FROM "budgetzen_budgets" WHERE "id" = $1`, + [ + budgetId, + ], + ); +} + +export async function deleteAllBudgets(userId: string) { + await db.query( + sql`DELETE FROM "budgetzen_budgets" WHERE "user_id" = $1`, + [ + userId, + ], + ); +} + +export async function getAllExpenses(userId: string) { + const expenses = await db.query( + sql`SELECT * FROM "budgetzen_expenses" + WHERE "user_id" = $1 + ORDER BY "date" DESC`, + [ + userId, + ], + ); + + return expenses; +} + +export async function getExpensesByMonth(userId: string, month: string) { + const expenses = await db.query( + sql`SELECT * FROM "budgetzen_expenses" + WHERE "user_id" = $1 AND + "date" >= '${month}-01' AND + "date" <= '${month}-31' + ORDER BY "date" DESC`, + [ + userId, + ], + ); + + return expenses; +} + +export async function createExpense(expense: Omit) { + const newExpense = (await db.query( + sql`INSERT INTO "budgetzen_expenses" ( + "user_id", + "cost", + "description", + "budget", + "date", + "is_recurring", + "extra" + ) VALUES ($1, $2, $3, $4, $5, $6, $7) + RETURNING *`, + [ + expense.user_id, + expense.cost, + expense.description, + expense.budget, + expense.date, + expense.is_recurring, + JSON.stringify(expense.extra), + ], + ))[0]; + + return newExpense; +} + +export async function updateExpense(expense: Expense) { + await db.query( + sql`UPDATE "budgetzen_expenses" SET + "cost" = $2, + "description" = $3, + "budget" = $4, + "date" = $5, + "is_recurring" = $6, + "extra" = $7 + WHERE "id" = $1`, + [ + expense.id, + expense.cost, + expense.description, + expense.budget, + expense.date, + expense.is_recurring, + JSON.stringify(expense.extra), + ], + ); +} + +export async function deleteExpense(expenseId: string) { + await db.query( + sql`DELETE FROM "budgetzen_expenses" WHERE "id" = $1`, + [ + expenseId, + ], + ); +} + +export async function deleteAllExpenses(userId: string) { + await db.query( + sql`DELETE FROM "budgetzen_expenses" WHERE "user_id" = $1`, + [ + userId, + ], + ); +} + +export async function importUserData( + userId: string, + budgets: Omit[], + expenses: Omit[], +) { + const addBudgetChunks = splitArrayInChunks( + budgets, + 100, // import in transactions of 100 events each + ); + + for (const budgetsToAdd of addBudgetChunks) { + await db.query(sql`BEGIN;`); + + for (const budget of budgetsToAdd) { + await createBudget({ ...budget, user_id: userId }); + } + + await db.query(sql`COMMIT;`); + } + + const addExpenseChunks = splitArrayInChunks( + expenses, + 100, // import in transactions of 100 events each + ); + + for (const expensesToAdd of addExpenseChunks) { + await db.query(sql`BEGIN;`); + + for (const expense of expensesToAdd) { + await createExpense({ ...expense, user_id: userId }); + } + + await db.query(sql`COMMIT;`); + } +} diff --git a/lib/interfaces/database.ts b/lib/interfaces/database.ts new file mode 100644 index 0000000..30d969e --- /dev/null +++ b/lib/interfaces/database.ts @@ -0,0 +1,76 @@ +import { Client } from 'https://deno.land/x/postgres@v0.17.0/mod.ts'; +import 'std/dotenv/load.ts'; + +const POSTGRESQL_HOST = Deno.env.get('POSTGRESQL_HOST') || ''; +const POSTGRESQL_USER = Deno.env.get('POSTGRESQL_USER') || ''; +const POSTGRESQL_PASSWORD = Deno.env.get('POSTGRESQL_PASSWORD') || ''; +const POSTGRESQL_DBNAME = Deno.env.get('POSTGRESQL_DBNAME') || ''; +const POSTGRESQL_PORT = Deno.env.get('POSTGRESQL_PORT') || ''; +const POSTGRESQL_CAFILE = Deno.env.get('POSTGRESQL_CAFILE') || ''; + +const tls = POSTGRESQL_CAFILE + ? { + enabled: true, + enforce: false, + caCertificates: [await Deno.readTextFile(POSTGRESQL_CAFILE)], + } + : { + enabled: true, + enforce: false, + }; + +export default class Database { + protected db?: Client; + + constructor(connectNow = false) { + if (connectNow) { + this.connectToPostgres(); + } + } + + protected async connectToPostgres() { + if (this.db) { + return this.db; + } + + const postgresClient = new Client({ + user: POSTGRESQL_USER, + password: POSTGRESQL_PASSWORD, + database: POSTGRESQL_DBNAME, + hostname: POSTGRESQL_HOST, + port: POSTGRESQL_PORT, + tls, + }); + + await postgresClient.connect(); + + this.db = postgresClient; + } + + protected async disconnectFromPostgres() { + if (!this.db) { + return; + } + + await this.db.end(); + + this.db = undefined; + } + + public close() { + this.disconnectFromPostgres(); + } + + public async query(sql: string, args?: any[]) { + if (!this.db) { + await this.connectToPostgres(); + } + + const result = await this.db!.queryObject(sql, args); + + return result.rows; + } +} + +// This allows us to have nice SQL syntax highlighting in template literals +export const sql = String.raw; diff --git a/lib/providers/paypal.ts b/lib/providers/paypal.ts new file mode 100644 index 0000000..153f88c --- /dev/null +++ b/lib/providers/paypal.ts @@ -0,0 +1,83 @@ +import 'std/dotenv/load.ts'; + +const PAYPAL_CLIENT_ID = Deno.env.get('PAYPAL_CLIENT_ID') || ''; +const PAYPAL_CLIENT_SECRET = Deno.env.get('PAYPAL_CLIENT_SECRET') || ''; + +interface PaypalSubscriber { + payer_id: string; + name: { + given_name: string; + surname: string; + }; + email_address: string; +} + +interface PaypalSubscription { + id: string; + plan_id: string; + start_time: string; + subscriber: PaypalSubscriber; + billing_info: { + next_billing_time: string; + last_payment: { + amount: { + value: string; + }; + time: string; + }; + }; + create_time: string; + status: 'ACTIVE' | 'APPROVED' | 'APPROVAL_PENDING' | 'SUSPENDED' | 'CANCELLED' | 'EXPIRED'; +} + +let stripeAccessToken = ''; + +async function getApiRequestHeaders() { + if (!stripeAccessToken) { + stripeAccessToken = await getAccessToken(); + } + + return { + 'Authorization': `Bearer ${stripeAccessToken}`, + 'Accept': 'application/json; charset=utf-8', + 'Content-Type': 'application/json; charset=utf-8', + }; +} + +async function getAccessToken() { + const body = { grant_type: 'client_credentials' }; + + const response = await fetch('https://api-m.paypal.com/v1/oauth2/token', { + method: 'POST', + headers: { + 'Authorization': `Basic ${btoa(`${PAYPAL_CLIENT_ID}:${PAYPAL_CLIENT_SECRET}`)}`, + 'Content-Type': 'application/x-www-form-urlencoded', + }, + body: new URLSearchParams(Object.entries(body)).toString(), + }); + + const result = (await response.json()) as { access_token: string }; + + return result.access_token; +} + +export async function getSubscriptions() { + const searchParams = new URLSearchParams(); + + searchParams.set('page_size', '20'); + + // NOTE: This doesn't exist yet + const response = await fetch(`https://api-m.paypal.com/v1/billing/subscriptions?${searchParams.toString()}`, { + method: 'GET', + headers: await getApiRequestHeaders(), + }); + + const result = (await response.json()) as PaypalSubscription[]; + + if (!result) { + console.log(JSON.stringify({ result }, null, 2)); + throw new Error(`Failed to make API request: "${result}"`); + } + + return result; +} diff --git a/lib/providers/postmark.ts b/lib/providers/postmark.ts new file mode 100644 index 0000000..01919d5 --- /dev/null +++ b/lib/providers/postmark.ts @@ -0,0 +1,153 @@ +import 'std/dotenv/load.ts'; + +import { helpEmail } from '/lib/utils.ts'; + +const POSTMARK_SERVER_API_TOKEN = Deno.env.get('POSTMARK_SERVER_API_TOKEN') || ''; + +interface PostmarkResponse { + To: string; + SubmittedAt: string; + MessageID: string; + ErrorCode: number; + Message: string; +} + +type TemplateAlias = 'verify-login' | 'verify-delete' | 'verify-update' | 'update-paddle-email'; + +function getApiRequestHeaders() { + return { + 'X-Postmark-Server-Token': POSTMARK_SERVER_API_TOKEN, + 'Accept': 'application/json; charset=utf-8', + 'Content-Type': 'application/json; charset=utf-8', + }; +} + +interface PostmarkEmailWithTemplateRequestBody { + TemplateId?: number; + TemplateAlias: TemplateAlias; + TemplateModel: { + [key: string]: any; + }; + InlineCss?: boolean; + From: string; + To: string; + Cc?: string; + Bcc?: string; + Tag?: string; + ReplyTo?: string; + Headers?: { Name: string; Value: string }[]; + TrackOpens?: boolean; + TrackLinks?: 'None' | 'HtmlAndText' | 'HtmlOnly' | 'TextOnly'; + Attachments?: { Name: string; Content: string; ContentType: string }[]; + Metadata?: { + [key: string]: string; + }; + MessageStream: 'outbound' | 'broadcast'; +} + +async function sendEmailWithTemplate( + to: string, + templateAlias: TemplateAlias, + data: PostmarkEmailWithTemplateRequestBody['TemplateModel'], + attachments: PostmarkEmailWithTemplateRequestBody['Attachments'] = [], + cc?: string, +) { + const email: PostmarkEmailWithTemplateRequestBody = { + From: helpEmail, + To: to, + TemplateAlias: templateAlias, + TemplateModel: data, + MessageStream: 'outbound', + }; + + if (attachments?.length) { + email.Attachments = attachments; + } + + if (cc) { + email.Cc = cc; + } + + const postmarkResponse = await fetch('https://api.postmarkapp.com/email/withTemplate', { + method: 'POST', + headers: getApiRequestHeaders(), + body: JSON.stringify(email), + }); + const postmarkResult = (await postmarkResponse.json()) as PostmarkResponse; + + if (postmarkResult.ErrorCode !== 0 || postmarkResult.Message !== 'OK') { + console.log(JSON.stringify({ postmarkResult }, null, 2)); + throw new Error(`Failed to send email "${templateAlias}"`); + } +} + +export async function sendVerifyLoginEmail( + email: string, + verificationCode: string, +) { + const data = { + verificationCode, + }; + + await sendEmailWithTemplate(email, 'verify-login', data); +} + +export async function sendVerifyDeleteDataEmail( + email: string, + verificationCode: string, +) { + const data = { + verificationCode, + deletionSubject: 'all your data', + }; + + await sendEmailWithTemplate(email, 'verify-delete', data); +} + +export async function sendVerifyDeleteAccountEmail( + email: string, + verificationCode: string, +) { + const data = { + verificationCode, + deletionSubject: 'your account', + }; + + await sendEmailWithTemplate(email, 'verify-delete', data); +} + +export async function sendVerifyUpdateEmailEmail( + email: string, + verificationCode: string, +) { + const data = { + verificationCode, + updateSubject: 'your email', + }; + + await sendEmailWithTemplate(email, 'verify-update', data); +} + +export async function sendVerifyUpdatePasswordEmail( + email: string, + verificationCode: string, +) { + const data = { + verificationCode, + updateSubject: 'your password', + }; + + await sendEmailWithTemplate(email, 'verify-update', data); +} + +export async function sendUpdateEmailInProviderEmail( + oldEmail: string, + newEmail: string, +) { + const data = { + oldEmail, + newEmail, + }; + + await sendEmailWithTemplate(helpEmail, 'update-paddle-email', data); +} diff --git a/lib/providers/stripe.ts b/lib/providers/stripe.ts new file mode 100644 index 0000000..15abf96 --- /dev/null +++ b/lib/providers/stripe.ts @@ -0,0 +1,92 @@ +import 'std/dotenv/load.ts'; + +const STRIPE_API_KEY = Deno.env.get('STRIPE_API_KEY') || ''; + +interface StripeCustomer { + id: string; + object: 'customer'; + balance: number; + created: number; + currency?: string | null; + deleted?: void; + delinquent?: boolean | null; + email: string | null; + name?: string | null; +} + +interface StripeSubscription { + id: string; + object: 'subscription'; + application: string | null; + cancel_at: number | null; + canceled_at: number | null; + created: number; + currency: string; + current_period_end: number; + current_period_start: number; + customer: StripeCustomer; + days_until_due: number | null; + ended_at: number | null; + items: { + object: 'list'; + data: StripeSubscriptionItem[]; + }; + start_date: number; + status: + | 'active' + | 'canceled' + | 'incomplete' + | 'incomplete_expired' + | 'past_due' + | 'paused' + | 'trialing' + | 'unpaid'; +} + +interface StripeSubscriptionItem { + id: string; + object: 'subscription_item'; + created: number; + deleted?: void; + price: { + id: string; + }; +} + +interface StripeResponse { + object: 'list'; + url: string; + has_more: boolean; + data: any[]; +} + +function getApiRequestHeaders() { + return { + 'Authorization': `Bearer ${STRIPE_API_KEY}`, + 'Accept': 'application/json; charset=utf-8', + 'Content-Type': 'application/json; charset=utf-8', + }; +} + +export async function getSubscriptions() { + const searchParams = new URLSearchParams(); + + searchParams.set('expand[]', 'data.customer'); + searchParams.set('limit', '100'); + + const response = await fetch(`https://api.stripe.com/v1/subscriptions?${searchParams.toString()}`, { + method: 'GET', + headers: getApiRequestHeaders(), + }); + + const result = (await response.json()) as StripeResponse; + + const subscriptions = result.data as StripeSubscription[]; + + if (!subscriptions) { + console.log(JSON.stringify({ result }, null, 2)); + throw new Error(`Failed to make API request: "${result}"`); + } + + return subscriptions; +} diff --git a/lib/types.ts b/lib/types.ts new file mode 100644 index 0000000..bd92189 --- /dev/null +++ b/lib/types.ts @@ -0,0 +1,75 @@ +import { SupportedCurrencySymbol } from '../public/ts/utils.ts'; + +export type EncryptedData = string; + +export interface KeyPair { + publicKeyJwk: JsonWebKey; + privateKeyJwk: JsonWebKey; +} + +export interface User { + id: string; + email: string; + encrypted_key_pair: EncryptedData; + subscription: { + external: { + paypal?: { + user_id: string; + subscription_id: string; + }; + stripe?: { + user_id: string; + subscription_id: string; + }; + }; + isMonthly?: boolean; + expires_at: string; + updated_at: string; + }; + status: 'trial' | 'active' | 'inactive'; + extra: { + currency?: SupportedCurrencySymbol; + }; + created_at: Date; +} + +export interface UserSession { + id: string; + user_id: string; + expires_at: Date; + verified: boolean; + last_seen_at: Date; + created_at: Date; +} + +export interface VerificationCode { + id: string; + user_id: string; + code: string; + verification: { + type: 'session' | 'user-update' | 'data-delete' | 'user-delete'; + id: string; + }; + expires_at: Date; + created_at: Date; +} + +export interface Budget { + id: string; + user_id: User['id']; + name: EncryptedData; + month: string; + value: EncryptedData; + extra: Record; // NOTE: Here for potential future fields +} + +export interface Expense { + id: string; + user_id: User['id']; + cost: EncryptedData; + description: EncryptedData; + budget: EncryptedData; + date: string; + is_recurring: boolean; + extra: Record; // NOTE: Here for potential future fields +} diff --git a/lib/utils.ts b/lib/utils.ts index 971ff95..2fb6e76 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -1,18 +1,33 @@ import 'std/dotenv/load.ts'; +import { emit } from 'https://deno.land/x/emit@0.15.0/mod.ts'; +import sass from 'https://deno.land/x/denosass@1.0.6/mod.ts'; +import { serveFile } from 'std/http/file_server.ts'; -import header from '../components/header.ts'; -import footer from '../components/footer.ts'; -import loading from '../components/loading.ts'; +import header from '/components/header.ts'; +import footer from '/components/footer.ts'; +import loading from '/components/loading.ts'; // This allows us to have nice html syntax highlighting in template literals export const html = String.raw; -const USERBASE_APP_ID = Deno.env.get('USERBASE_APP_ID') || ''; -const sessionLengthInHours = 90 * 24; // 3 months - -export const baseUrl = 'https://app.budgetzen.net'; +export const baseUrl = Deno.env.get('BASE_URL') || 'https://app.budgetzen.net'; export const defaultTitle = 'Budget Zen — Simple and end-to-end encrypted budget and expense manager'; export const defaultDescription = 'Simple and end-to-end encrypted budget and expense manager.'; +export const helpEmail = 'help@budgetzen.net'; + +export const PORT = Deno.env.get('PORT') || 8000; +export const STRIPE_MONTHLY_URL = 'https://buy.stripe.com/eVa01H57C3MB6CQ14s'; +export const STRIPE_YEARLY_URL = 'https://buy.stripe.com/28o5m1dE896V0es8wV'; +export const STRIPE_CUSTOMER_URL = 'https://billing.stripe.com/p/login/4gw15w3G9bDyfWU6oo'; +export const PAYPAL_MONTHLY_URL = + `https://www.paypal.com/webapps/billing/plans/subscribe?plan_id=P-41N48210MJ2770038MQDVBLI&return_url=${ + encodeURI(`${baseUrl}/pricing?paypalCheckoutId=true`) + }`; +export const PAYPAL_YEARLY_URL = + `https://www.paypal.com/webapps/billing/plans/subscribe?plan_id=P-20P504881F952811BMQDVA4Q&return_url=${ + encodeURI(`${baseUrl}/pricing?paypalCheckoutId=true`) + }`; +export const PAYPAL_CUSTOMER_URL = 'https://www.paypal.com'; export interface PageContentResult { htmlContent: string; @@ -45,6 +60,7 @@ function basicLayout(htmlContent: string, { currentPath, titlePrefix, descriptio + @@ -56,21 +72,22 @@ function basicLayout(htmlContent: string, { currentPath, titlePrefix, descriptio ${loading()} ${header(currentPath)} -
+
${htmlContent}
${footer()} - - `; @@ -81,88 +98,93 @@ export function basicLayoutResponse(htmlContent: string, options: BasicLayoutOpt headers: { 'content-type': 'text/html; charset=utf-8', 'content-security-policy': - 'default-src \'self\' https://*.userbase.com wss://*.userbase.com https://*.stripe.com https://stripe.com data: blob:; child-src \'self\' data: blob: https://*.stripe.com; img-src \'self\' data: blob: https://*.stripe.com; style-src \'self\' \'unsafe-inline\' https://*.stripe.com; script-src \'self\' \'unsafe-inline\' \'unsafe-eval\';', + 'default-src \'self\'; child-src \'self\'; img-src \'self\'; style-src \'self\' \'unsafe-inline\'; script-src \'self\' \'unsafe-inline\' \'unsafe-eval\';', 'x-frame-options': 'DENY', + 'x-content-type-options': 'nosniff', 'strict-transport-security': 'max-age=31536000; includeSubDomains; preload', }, }); } export function isRunningLocally(urlPatternResult: URLPatternResult) { - return urlPatternResult.hostname.input === 'localhost'; + return urlPatternResult.hostname.input.includes('localhost'); } -// NOTE: The functions below are used in the frontend, but this copy allows for easier testing and type-checking - export function escapeHtml(unsafe: string) { return unsafe.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"') .replaceAll('\'', '''); } -export function formatNumber(currency: string, number: number) { - return new Intl.NumberFormat('en-US', { - style: 'currency', - currency: currency || 'USD', - minimumFractionDigits: 0, - maximumFractionDigits: 2, - }).format(number); +async function transpileTs(content: string, specifier: URL) { + const urlStr = specifier.toString(); + const result = await emit(specifier, { + load(specifier: string) { + if (specifier !== urlStr) { + return Promise.resolve({ kind: 'module', specifier, content: '' }); + } + return Promise.resolve({ kind: 'module', specifier, content }); + }, + }); + return result[urlStr]; } -type SortableByDate = { date: string }; -export function sortByDate( - objectA: SortableByDate, - objectB: SortableByDate, -) { - if (objectA.date < objectB.date) { - return -1; - } - if (objectA.date > objectB.date) { - return 1; +export async function serveFileWithTs(request: Request, filePath: string, extraHeaders?: ResponseInit['headers']) { + const response = await serveFile(request, filePath); + + if (response.status !== 200) { + return response; } - return 0; + + const tsCode = await response.text(); + const jsCode = await transpileTs(tsCode, new URL('file:///src.ts')); + const { headers } = response; + headers.set('content-type', 'application/javascript; charset=utf-8'); + headers.delete('content-length'); + + return new Response(jsCode, { + status: response.status, + statusText: response.statusText, + headers, + ...(extraHeaders || {}), + }); } -type SortableByCount = { count: number }; -export function sortByCount( - objectA: SortableByCount, - objectB: SortableByCount, -) { - if (objectA.count < objectB.count) { - return 1; - } - if (objectA.count > objectB.count) { - return -1; - } - return 0; +function transpileSass(content: string) { + const compiler = sass(content); + + return compiler.to_string('compressed') as string; } -type SortableByName = { name: string }; -export function sortByName( - objectA: SortableByName, - objectB: SortableByName, -) { - const nameA = objectA.name.toUpperCase(); - const nameB = objectB.name.toUpperCase(); - if (nameA < nameB) { - return -1; - } - if (nameA > nameB) { - return 1; +export async function serveFileWithSass(request: Request, filePath: string, extraHeaders?: ResponseInit['headers']) { + const response = await serveFile(request, filePath); + + if (response.status !== 200) { + return response; } - return 0; + + const sassCode = await response.text(); + const cssCode = transpileSass(sassCode); + const { headers } = response; + headers.set('content-type', 'text/css; charset=utf-8'); + headers.delete('content-length'); + + return new Response(cssCode, { + status: response.status, + statusText: response.statusText, + headers, + ...(extraHeaders || {}), + }); } -type SortableByMissingBudget = { expensesCost: number; value: number }; -export function sortByMissingBudget( - objectA: SortableByMissingBudget, - objectB: SortableByMissingBudget, -) { - const valueA = objectA.value - objectA.expensesCost; - const valueB = objectB.value - objectB.expensesCost; - return valueB - valueA; +export function generateRandomCode(length = 6) { + const getRandomDigit = () => Math.floor(Math.random() * (10)); // 0-9 + + const codeDigits = Array.from({ length }).map(getRandomDigit); + + return codeDigits.join(''); } -export function splitArrayInChunks(array: any[], chunkLength: number) { +export function splitArrayInChunks(array: T[], chunkLength: number) { const chunks = []; let chunkIndex = 0; const arrayLength = array.length; @@ -173,22 +195,3 @@ export function splitArrayInChunks(array: any[], chunkLength: number) { return chunks; } - -export function uniqueBy( - array: any[], - predicate: string | ((item: any) => any), -) { - const filter = typeof predicate === 'function' ? predicate : (object: any) => object[predicate]; - - return [ - ...array - .reduce((map, item) => { - const key = item === null || item === undefined ? item : filter(item); - - map.has(key) || map.set(key, item); - - return map; - }, new Map()) - .values(), - ]; -} diff --git a/lib/utils_test.ts b/lib/utils_test.ts index 96613d7..fbac83c 100644 --- a/lib/utils_test.ts +++ b/lib/utils_test.ts @@ -1,5 +1,5 @@ import { assertEquals } from 'std/testing/asserts.ts'; -import { escapeHtml, formatNumber, splitArrayInChunks } from './utils.ts'; +import { escapeHtml, generateRandomCode, splitArrayInChunks } from './utils.ts'; Deno.test('that escapeHtml works', () => { const tests = [ @@ -19,22 +19,22 @@ Deno.test('that escapeHtml works', () => { } }); -Deno.test('that formatNumber works', () => { +Deno.test('that generateRandomCode works', () => { const tests = [ - { currency: 'USD', number: 10000, expected: '$10,000' }, - { currency: 'USD', number: 10000.5, expected: '$10,000.5' }, - { currency: 'EUR', number: 10000, expected: '€10,000' }, - { currency: 'EUR', number: 900.999, expected: '€901' }, - { currency: 'EUR', number: 900.991, expected: '€900.99' }, - { currency: 'USD', number: 50.11, expected: '$50.11' }, - { currency: 'GBP', number: 900.999, expected: '£901' }, - { currency: 'GBP', number: 900.991, expected: '£900.99' }, - { currency: 'GBP', number: 50.11, expected: '£50.11' }, + { + length: 6, + }, + { + length: 7, + }, + { + length: 8, + }, ]; for (const test of tests) { - const result = formatNumber(test.currency, test.number); - assertEquals(result, test.expected); + const output = generateRandomCode(test.length); + assertEquals(output.length, test.length); } }); diff --git a/migrate-db.ts b/migrate-db.ts new file mode 100644 index 0000000..99de0ea --- /dev/null +++ b/migrate-db.ts @@ -0,0 +1,90 @@ +import 'std/dotenv/load.ts'; + +import Database, { sql } from '/lib/interfaces/database.ts'; + +const migrationsDirectoryPath = `${Deno.cwd()}/db-migrations`; + +const migrationsDirectory = Deno.readDir(migrationsDirectoryPath); + +const db = new Database(); + +interface Migration { + id: string; + name: string; + executed_at: Date; +} + +async function getExecutedMigrations() { + const executedMigrations = new Set( + Array.from( + (await db.query(sql`SELECT * FROM "budgetzen_migrations" ORDER BY "name" ASC`)).map((migration) => + migration.name + ), + ), + ); + + return executedMigrations; +} + +async function getMissingMigrations() { + const existingMigrations: Set = new Set(); + + for await (const migrationFile of migrationsDirectory) { + // Skip non-files + if (!migrationFile.isFile) { + continue; + } + + // Skip files not in the "001-blah.pgsql" format + if (!migrationFile.name.match(/^\d+-.*(\.pgsql)$/)) { + continue; + } + + existingMigrations.add(migrationFile.name); + } + + // Add everything to run, by default + const migrationsToExecute = new Set([...existingMigrations]); + + try { + const executedMigrations = await getExecutedMigrations(); + + // Remove any existing migrations that were executed, from the list of migrations to execute + for (const executedMigration of executedMigrations) { + migrationsToExecute.delete(executedMigration); + } + } catch (_error) { + // The table likely doesn't exist, so run everything. + } + + return migrationsToExecute; +} + +async function runMigrations(missingMigrations: Set) { + for (const missingMigration of missingMigrations) { + console.log(`Running "${missingMigration}"...`); + + try { + const migrationSql = await Deno.readTextFile(`${migrationsDirectoryPath}/${missingMigration}`); + + await db.query(migrationSql); + + await db.query(sql`INSERT INTO "public"."budgetzen_migrations" ("name", "executed_at") VALUES ($1, NOW())`, [ + missingMigration, + ]); + + console.log('Success!'); + } catch (error) { + console.log('Failed!'); + console.error(error); + } + } +} + +const missingMigrations = await getMissingMigrations(); + +await runMigrations(missingMigrations); + +if (missingMigrations.size === 0) { + console.log('No migrations to run!'); +} diff --git a/pages/api/budgets.ts b/pages/api/budgets.ts new file mode 100644 index 0000000..8741b80 --- /dev/null +++ b/pages/api/budgets.ts @@ -0,0 +1,90 @@ +import { + createBudget, + deleteBudget, + getAllBudgets, + getBudgetsByMonth, + monthRegExp, + updateBudget, + validateUserAndSession, +} from '/lib/data-utils.ts'; +import { Budget } from '/lib/types.ts'; + +async function createOrUpdateBudget(request: Request) { + const { session_id, user_id, name, month, value, extra, id }: Omit & { + session_id: string; + id?: string; + } = await request.json(); + + if (!session_id || !user_id || !name || !month || !extra) { + return new Response('Bad Request', { status: 400 }); + } + + if ((request.method === 'PATCH' && !id) || (request.method === 'POST' && id)) { + return new Response('Bad Request', { status: 400 }); + } + + await validateUserAndSession(user_id, session_id); + + if (request.method === 'PATCH') { + await updateBudget({ id: id!, user_id, name, value, extra }); + + return new Response(JSON.stringify({ success: true }), { + headers: { 'Content-Type': 'application/json; charset=utf-8' }, + }); + } + + const newBudget = await createBudget({ + user_id, + name, + month, + value, + extra, + }); + + return new Response(JSON.stringify(newBudget), { headers: { 'Content-Type': 'application/json; charset=utf-8' } }); +} + +async function deleteBudgetAction(request: Request) { + const { user_id, session_id, id }: { user_id: string; session_id: string; id: string } = await request.json(); + + if (!user_id || !session_id || !id) { + return new Response('Bad Request', { status: 400 }); + } + + await validateUserAndSession(user_id, session_id); + + await deleteBudget(id); + + return new Response(JSON.stringify({ success: true }), { + headers: { 'Content-Type': 'application/json; charset=utf-8' }, + }); +} + +export function pageAction(request: Request) { + switch (request.method) { + case 'POST': + case 'PATCH': + return createOrUpdateBudget(request); + case 'DELETE': + return deleteBudgetAction(request); + } + + return new Response('Not Implemented', { status: 501 }); +} + +export async function pageContent(request: Request, _match: URLPatternResult) { + const urlSearchParams = new URL(request.url).searchParams; + const sessionId = urlSearchParams.get('session_id'); + const userId = urlSearchParams.get('user_id'); + const month = urlSearchParams.get('month'); + + if (!sessionId || !userId || !month || (!monthRegExp.test(month) && month !== 'all')) { + return new Response('Bad Request', { status: 400 }); + } + + const { user } = await validateUserAndSession(userId, sessionId); + + const events = await (month === 'all' ? getAllBudgets(user.id) : getBudgetsByMonth(user.id, month)); + + return new Response(JSON.stringify(events), { headers: { 'Content-Type': 'application/json; charset=utf-8' } }); +} diff --git a/pages/api/data.ts b/pages/api/data.ts new file mode 100644 index 0000000..a6c2de1 --- /dev/null +++ b/pages/api/data.ts @@ -0,0 +1,71 @@ +import { + createVerificationCode, + deleteAllBudgets, + deleteAllExpenses, + importUserData, + validateUserAndSession, + validateVerificationCode, +} from '/lib/data-utils.ts'; +import { sendVerifyDeleteDataEmail } from '/lib/providers/postmark.ts'; +import { Budget, Expense } from '/lib/types.ts'; + +async function importDataAction(request: Request) { + const { user_id, session_id, budgets, expenses }: { + user_id: string; + session_id: string; + budgets: Omit[]; + expenses: Omit[]; + } = await request.json(); + + if (!user_id || !session_id || !budgets || !expenses) { + return new Response('Bad Request', { status: 400 }); + } + + const { user } = await validateUserAndSession(user_id, session_id); + + await importUserData(user.id, budgets, expenses); + + return new Response(JSON.stringify({ success: true }), { + headers: { 'Content-Type': 'application/json; charset=utf-8' }, + }); +} + +async function deleteDataAction(request: Request) { + const { user_id, session_id, code }: { user_id: string; session_id: string; code?: string } = await request.json(); + + if (!user_id || !session_id) { + return new Response('Bad Request', { status: 400 }); + } + + const { user, session } = await validateUserAndSession(user_id, session_id); + + if (!code) { + const verificationCode = await createVerificationCode(user, session, 'data-delete'); + + await sendVerifyDeleteDataEmail(user.email, verificationCode); + } else { + await validateVerificationCode(user, session, code, 'data-delete'); + + await deleteAllBudgets(user.id); + await deleteAllExpenses(user.id); + } + + return new Response(JSON.stringify({ success: true }), { + headers: { 'Content-Type': 'application/json; charset=utf-8' }, + }); +} + +export function pageAction(request: Request) { + switch (request.method) { + case 'POST': + return importDataAction(request); + case 'DELETE': + return deleteDataAction(request); + } + + return new Response('Not Implemented', { status: 501 }); +} + +export function pageContent() { + return new Response('Not Implemented', { status: 501 }); +} diff --git a/pages/api/expenses.ts b/pages/api/expenses.ts new file mode 100644 index 0000000..de937d2 --- /dev/null +++ b/pages/api/expenses.ts @@ -0,0 +1,92 @@ +import { + createExpense, + deleteExpense, + getAllExpenses, + getExpensesByMonth, + monthRegExp, + updateExpense, + validateUserAndSession, +} from '/lib/data-utils.ts'; +import { Expense } from '/lib/types.ts'; + +async function createOrUpdateExpense(request: Request) { + const { session_id, user_id, description, date, cost, budget, is_recurring, extra, id }: Omit & { + session_id: string; + id?: string; + } = await request.json(); + + if (!session_id || !user_id || !description || !date || !cost || !budget || !extra) { + return new Response('Bad Request', { status: 400 }); + } + + if ((request.method === 'PATCH' && !id) || (request.method === 'POST' && id)) { + return new Response('Bad Request', { status: 400 }); + } + + await validateUserAndSession(user_id, session_id); + + if (request.method === 'PATCH') { + await updateExpense({ id: id!, user_id, description, date, cost, budget, is_recurring, extra }); + + return new Response(JSON.stringify({ success: true }), { + headers: { 'Content-Type': 'application/json; charset=utf-8' }, + }); + } + + const newExpense = await createExpense({ + user_id, + description, + date, + cost, + budget, + is_recurring, + extra, + }); + + return new Response(JSON.stringify(newExpense), { headers: { 'Content-Type': 'application/json; charset=utf-8' } }); +} + +async function deleteExpenseAction(request: Request) { + const { user_id, session_id, id }: { user_id: string; session_id: string; id: string } = await request.json(); + + if (!user_id || !session_id || !id) { + return new Response('Bad Request', { status: 400 }); + } + + await validateUserAndSession(user_id, session_id); + + await deleteExpense(id); + + return new Response(JSON.stringify({ success: true }), { + headers: { 'Content-Type': 'application/json; charset=utf-8' }, + }); +} + +export function pageAction(request: Request) { + switch (request.method) { + case 'POST': + case 'PATCH': + return createOrUpdateExpense(request); + case 'DELETE': + return deleteExpenseAction(request); + } + + return new Response('Not Implemented', { status: 501 }); +} + +export async function pageContent(request: Request, _match: URLPatternResult) { + const urlSearchParams = new URL(request.url).searchParams; + const sessionId = urlSearchParams.get('session_id'); + const userId = urlSearchParams.get('user_id'); + const month = urlSearchParams.get('month'); + + if (!sessionId || !userId || !month || (!monthRegExp.test(month) && month !== 'all')) { + return new Response('Bad Request', { status: 400 }); + } + + const { user } = await validateUserAndSession(userId, sessionId); + + const events = await (month === 'all' ? getAllExpenses(user.id) : getExpensesByMonth(user.id, month)); + + return new Response(JSON.stringify(events), { headers: { 'Content-Type': 'application/json; charset=utf-8' } }); +} diff --git a/pages/api/session.ts b/pages/api/session.ts new file mode 100644 index 0000000..7365878 --- /dev/null +++ b/pages/api/session.ts @@ -0,0 +1,94 @@ +import { + createSession, + createVerificationCode, + getUserByEmail, + updateSession, + validateUserAndSession, + validateVerificationCode, +} from '/lib/data-utils.ts'; +import { sendVerifyLoginEmail } from '/lib/providers/postmark.ts'; + +async function validateSession(request: Request) { + const { email }: { email: string } = await request.json(); + + if (!email) { + return new Response('Bad Request', { status: 400 }); + } + + const user = await getUserByEmail(email); + + if (!user) { + return new Response('Not Found', { status: 404 }); + } + + const session = await createSession(user); + + if (!session) { + return new Response('Bad Request', { status: 400 }); + } + + const verificationCode = await createVerificationCode(user, session, 'session'); + + await sendVerifyLoginEmail(user.email, verificationCode); + + return new Response(JSON.stringify({ user, session_id: session.id }), { + headers: { 'Content-Type': 'application/json; charset=utf-8' }, + }); +} + +async function verifySession(request: Request) { + const { user_id, session_id, code }: { user_id: string; session_id: string; code: string } = await request.json(); + + if (!user_id || !session_id || !code) { + return new Response('Bad Request', { status: 400 }); + } + + const { user, session } = await validateUserAndSession(user_id, session_id, true); + + await validateVerificationCode(user, session, code, 'session'); + + session.verified = true; + + await updateSession(session); + + return new Response(JSON.stringify({ success: true }), { + headers: { 'Content-Type': 'application/json; charset=utf-8' }, + }); +} + +async function deleteSession(request: Request) { + const { user_id, session_id }: { user_id: string; session_id: string } = await request.json(); + + if (!user_id || !session_id) { + return new Response('Bad Request', { status: 400 }); + } + + const { session } = await validateUserAndSession(user_id, session_id); + + const yesterday = new Date(new Date().setUTCDate(new Date().getUTCDate() - 1)); + + session.expires_at = yesterday; + + await updateSession(session); + + return new Response(JSON.stringify({ success: true }), { + headers: { 'Content-Type': 'application/json; charset=utf-8' }, + }); +} + +export function pageAction(request: Request) { + switch (request.method) { + case 'POST': + return validateSession(request); + case 'PATCH': + return verifySession(request); + case 'DELETE': + return deleteSession(request); + } + + return new Response('Not Implemented', { status: 501 }); +} + +export function pageContent() { + return new Response('Not Implemented', { status: 501 }); +} diff --git a/pages/api/subscription.ts b/pages/api/subscription.ts new file mode 100644 index 0000000..776c860 --- /dev/null +++ b/pages/api/subscription.ts @@ -0,0 +1,68 @@ +import { updateUser, validateUserAndSession } from '/lib/data-utils.ts'; +import { getSubscriptions as getStripeSubscriptions } from '/lib/providers/stripe.ts'; +// import { getSubscriptions as getPaypalSubscriptions } from '/lib/providers/paypal.ts'; +import { sendUpdateEmailInProviderEmail } from '/lib/providers/postmark.ts'; + +export async function pageAction(request: Request) { + if (request.method !== 'POST') { + return new Response('Not Implemented', { status: 501 }); + } + + const { session_id, user_id, provider }: { session_id: string; user_id: string; provider: 'paypal' | 'stripe' } = + await request.json(); + + if (!session_id || !user_id) { + return new Response('Bad Request', { status: 400 }); + } + + const { user } = await validateUserAndSession(user_id, session_id); + + if (provider === 'stripe') { + const subscriptions = await getStripeSubscriptions(); + + const subscription = subscriptions.find((subscription) => + subscription.customer.email === user.email && + subscription.items.data.some((item) => item.price.id.startsWith('budget-zen-')) + ); + + if (subscription) { + user.subscription.isMonthly = subscription.items.data.some((item) => item.price.id.includes('monthly')); + user.subscription.updated_at = new Date().toISOString(); + user.subscription.expires_at = new Date(subscription.current_period_end * 1000).toISOString(); + user.subscription.external.stripe = { + user_id: subscription.customer.id, + subscription_id: subscription.id, + }; + user.status = 'active'; + + await updateUser(user); + } + } else if (provider === 'paypal') { + // NOTE: "Hack" for manually updating/verifying until PayPal builds a subscriptions list API + await sendUpdateEmailInProviderEmail(user.email, user.email); + // const subscriptions = await getPaypalSubscriptions(); + + // const subscription = subscriptions.find((subscription) => subscription.subscriber.email_address === user.email); + + // if (subscription) { + // user.subscription.isMonthly = parseInt(subscription.billing_info.last_payment.amount.value, 10) < 10; + // user.subscription.updated_at = new Date().toISOString(); + // user.subscription.expires_at = new Date(subscription.billing_info.next_billing_time).toISOString(); + // user.subscription.external.stripe = { + // user_id: subscription.subscriber.payer_id, + // subscription_id: subscription.id, + // }; + user.status = 'active'; + + await updateUser(user); + // } + } + + return new Response(JSON.stringify({ success: true }), { + headers: { 'Content-Type': 'application/json; charset=utf-8' }, + }); +} + +export function pageContent() { + return new Response('Not Implemented', { status: 501 }); +} diff --git a/pages/api/user.ts b/pages/api/user.ts new file mode 100644 index 0000000..4b25e15 --- /dev/null +++ b/pages/api/user.ts @@ -0,0 +1,183 @@ +import { + createSession, + createUser, + createVerificationCode, + deleteUser, + getSessionById, + getUserByEmail, + getUserById, + updateSession, + updateUser, + validateUserAndSession, + validateVerificationCode, +} from '/lib/data-utils.ts'; +import { EncryptedData } from '/lib/types.ts'; +import { + sendUpdateEmailInProviderEmail, + sendVerifyDeleteAccountEmail, + sendVerifyUpdateEmailEmail, + sendVerifyUpdatePasswordEmail, +} from '/lib/providers/postmark.ts'; +import { SupportedCurrencySymbol } from '/public/ts/utils.ts'; + +async function createUserAction(request: Request) { + const { email, encrypted_key_pair }: { email: string; encrypted_key_pair: EncryptedData } = await request.json(); + + if (!email || !encrypted_key_pair) { + return new Response('Bad Request', { status: 400 }); + } + + const existingUserByEmail = await getUserByEmail(email); + + if (existingUserByEmail) { + return new Response('Bad Request', { status: 400 }); + } + + const user = await createUser(email, encrypted_key_pair); + + if (!user) { + return new Response('Bad Request', { status: 400 }); + } + + const session = await createSession(user, true); + + if (!session) { + return new Response('Bad Request', { status: 400 }); + } + + return new Response(JSON.stringify({ user, session_id: session.id }), { + headers: { 'Content-Type': 'application/json; charset=utf-8' }, + }); +} + +async function updateUserAction(request: Request) { + const { user_id, session_id, email, currency, encrypted_key_pair, code }: { + user_id: string; + session_id: string; + email?: string; + currency?: SupportedCurrencySymbol; + encrypted_key_pair?: EncryptedData; + code?: string; + } = await request.json(); + + if (!user_id || !session_id) { + return new Response('Bad Request', { status: 400 }); + } + + if (!email && !encrypted_key_pair && !currency) { + return new Response('Bad Request', { status: 400 }); + } + + const { user, session } = await validateUserAndSession(user_id, session_id); + + if (!code) { + if (currency) { + user.extra.currency = currency; + + await updateUser(user); + } else if (email) { + const existingUserByEmail = await getUserByEmail(email); + + if (existingUserByEmail) { + return new Response('Bad Request', { status: 400 }); + } + } + + const verificationCode = await createVerificationCode(user, session, 'user-update'); + + if (email) { + await sendVerifyUpdateEmailEmail(user.email, verificationCode); + } + if (encrypted_key_pair) { + await sendVerifyUpdatePasswordEmail(user.email, verificationCode); + } + } else { + await validateVerificationCode(user, session, code, 'user-update'); + + const oldEmail = user.email; + + if (email) { + user.email = email; + } + + if (encrypted_key_pair) { + user.encrypted_key_pair = encrypted_key_pair; + } + + await updateUser(user); + + if (email && (user.subscription.external.stripe || user.subscription.external.paypal) && email !== oldEmail) { + await sendUpdateEmailInProviderEmail(oldEmail, email); + } + } + + return new Response(JSON.stringify({ success: true }), { + headers: { 'Content-Type': 'application/json; charset=utf-8' }, + }); +} + +async function deleteUserAction(request: Request) { + const { user_id, session_id, code }: { user_id: string; session_id: string; code?: string } = await request.json(); + + if (!user_id || !session_id) { + return new Response('Bad Request', { status: 400 }); + } + + const { user, session } = await validateUserAndSession(user_id, session_id); + + if (!code) { + const verificationCode = await createVerificationCode(user, session, 'user-delete'); + + await sendVerifyDeleteAccountEmail(user.email, verificationCode); + } else { + await validateVerificationCode(user, session, code, 'user-delete'); + + await deleteUser(user.id); + } + + return new Response(JSON.stringify({ success: true }), { + headers: { 'Content-Type': 'application/json; charset=utf-8' }, + }); +} + +export function pageAction(request: Request) { + switch (request.method) { + case 'POST': + return createUserAction(request); + case 'PATCH': + return updateUserAction(request); + case 'DELETE': + return deleteUserAction(request); + } + + return new Response('Not Implemented', { status: 501 }); +} + +export async function pageContent(request: Request) { + const urlSearchParams = new URL(request.url).searchParams; + const sessionId = urlSearchParams.get('session_id'); + const userId = urlSearchParams.get('user_id'); + const email = urlSearchParams.get('email'); + + if (!sessionId || !userId || !email) { + return new Response('Bad Request', { status: 400 }); + } + + const user = await getUserById(userId); + + if (!user || user.email !== email) { + return new Response('Not Found', { status: 404 }); + } + + const session = await getSessionById(sessionId); + + if (!session) { + return new Response('Not Found', { status: 404 }); + } + + session.last_seen_at = new Date(); + + await updateSession(session); + + return new Response(JSON.stringify(user), { headers: { 'Content-Type': 'application/json; charset=utf-8' } }); +} diff --git a/pages/billing.ts b/pages/billing.ts index 15cd551..88b4864 100644 --- a/pages/billing.ts +++ b/pages/billing.ts @@ -1,4 +1,5 @@ -import { html, PageContentResult } from '../lib/utils.ts'; +import { html, PageContentResult } from '/lib/utils.ts'; +import verificationCodeModal from '/components/modals/verification-code.ts'; export function pageAction() { return new Response('Not Implemented', { status: 501 }); @@ -65,117 +66,10 @@ export function pageContent() {

You probably want to check out the pricing section instead.

- + + ${verificationCodeModal()} + + `; return { diff --git a/pages/index.ts b/pages/index.ts index 5bb09e8..a30b8b9 100644 --- a/pages/index.ts +++ b/pages/index.ts @@ -1,4 +1,5 @@ -import { html, PageContentResult } from '../lib/utils.ts'; +import { helpEmail, html, PageContentResult } from '/lib/utils.ts'; +import verificationCodeModal from '/components/modals/verification-code.ts'; export function pageAction() { return new Response('Not Implemented', { status: 501 }); @@ -8,10 +9,10 @@ export function pageContent() { const htmlContent = html`
-

Simple + Encrypted Budget Management

+

Simple + Encrypted Expense Management

- Budget Zen is a simple and encrypted budget management + Budget Zen is a simple and encrypted expense management app. You can learn more about it here, as this is the app.

@@ -32,7 +33,6 @@ export function pageContent() { type="email" placeholder="you@example.com" name="email" - data-automation="login-email" />
@@ -42,11 +42,10 @@ export function pageContent() { type="password" placeholder="something secret" name="password" - data-automation="login-password" />
- or @@ -56,15 +55,14 @@ export function pageContent() {

- When you signup, you're agreeing with the Terms of Service. -

-

- Note that logging in will take up a few seconds. This is intentional, in order to generate a safer assymetric encryption key. After logging in, the app should be blazing fast in any device. + Note that logging in will take up a few seconds. This is + intentional, in order to generate a safer assymetric encryption key. + After logging in, the app should be blazing fast in any device.

Need help?

- If you're having any issues or have any questions, please reach out. + If you're having any issues or have any questions, please reach out.

@@ -86,7 +84,6 @@ export function pageContent() {
-
@@ -98,7 +95,6 @@ export function pageContent() {
-
@@ -123,7 +119,7 @@ export function pageContent() { - + + ${verificationCodeModal()} + + `; return { diff --git a/pages/pricing.ts b/pages/pricing.ts index 5020211..c6a2cb2 100644 --- a/pages/pricing.ts +++ b/pages/pricing.ts @@ -1,4 +1,4 @@ -import { html, PageContentResult } from '../lib/utils.ts'; +import { html, PageContentResult } from '/lib/utils.ts'; export function pageAction() { return new Response('Not Implemented', { status: 501 }); @@ -43,84 +43,12 @@ export function pageContent() { - + `; return { htmlContent, titlePrefix: 'Pricing', - description: 'Simple pricing for Budget Zen.', + description: 'Simple pricing for Budget Zen', } as PageContentResult; } diff --git a/pages/settings.ts b/pages/settings.ts index 71df7ee..d67ed46 100644 --- a/pages/settings.ts +++ b/pages/settings.ts @@ -1,4 +1,5 @@ -import { html, PageContentResult } from '../lib/utils.ts'; +import { html, PageContentResult } from '/lib/utils.ts'; +import verificationCodeModal from '/components/modals/verification-code.ts'; export function pageAction() { return new Response('Not Implemented', { status: 501 }); @@ -37,7 +38,7 @@ export function pageContent() { - + + ${verificationCodeModal()} + + `; return { diff --git a/public/css/style.css b/public/css/style.css index e2ac3a2..034f214 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -268,32 +268,6 @@ footer .links span.by { margin-right: -0.4rem; } -#loading { - position: fixed; - top: 0; - left: 0; - display: flex; - align-items: center; - justify-content: center; - width: 100%; - height: 100%; - z-index: 10000; - background: rgba(0, 0, 0, 0.7); - transition: all 200ms ease-in-out; - visibility: visible; - opacity: 1; -} - -#loading svg path, -#loading svg rect { - fill: rgba(255, 255, 255, 0.8); -} - -#loading.hide { - opacity: 0; - visibility: hidden; -} - hr { border: 0; height: 1px; diff --git a/public/js/index.js b/public/js/index.js deleted file mode 100644 index ac378a9..0000000 --- a/public/js/index.js +++ /dev/null @@ -1,687 +0,0 @@ -(() => { - document.addEventListener('app-loaded', () => { - const loginForm = document.getElementById('login-form'); - const emailInput = document.getElementById('email'); - const passwordInput = document.getElementById('password'); - const loginButton = document.getElementById('login-button'); - const signupButton = document.getElementById('signup-button'); - const expensesFilterSearchInput = document.getElementById('expenses-filter-search'); - const budgetsFilterButton = document.getElementById('budgets-filter-button'); - const addBudgetButton = document.getElementById('add-budget-button'); - - const expensesList = document.getElementById('expenses'); - const budgetsList = document.getElementById('budgets'); - const addExpenseForm = document.getElementById('add-expense-form'); - const addExpenseButton = document.getElementById('add-expense-button'); - const expenseCostInput = document.getElementById('expense-cost'); - const expenseDescriptionInput = document.getElementById('expense-description'); - const expenseBudgetSelect = document.getElementById('expense-budget'); - const expenseDateInput = document.getElementById('expense-date'); - - const monthNavigationPreviousButton = document.getElementById('month-navigation-previous'); - const monthNavigationNextButton = document.getElementById('month-navigation-next'); - const monthNavigationLabel = document.getElementById('current-month'); - - let currentMonth = (new Date().toISOString()).substring(0, 7); - let currency = '$'; - const budgetFilters = new Set(); - - async function login(event) { - loginButton.textContent = 'Logging in...'; - await loginOrSignup(event, false); - loginButton.textContent = 'Login'; - } - - async function signup(event) { - signupButton.textContent = 'Signing up...'; - await loginOrSignup(event, true); - signupButton.textContent = 'Signup'; - } - - let isLoggingInOrSigningUp = false; - - async function loginOrSignup(event, isSigningUp) { - event.preventDefault(); - event.stopPropagation(); - - if (isLoggingInOrSigningUp) { - return; - } - - isLoggingInOrSigningUp = true; - window.app.showLoading(); - - const email = emailInput.value; - const password = passwordInput.value; - - const loginOrSignupMethod = isSigningUp ? window.app.dataUtils.createAccount : window.app.dataUtils.validateLogin; - - const { success, error } = await loginOrSignupMethod(email, password); - - if (success) { - window.app.showNotification('Logged in successfully.', 'success'); - - window.app.showValidSessionElements(); - loginForm.reset(); - await initializePage(); - } else { - if (error) { - window.app.showNotification(error, 'error'); - } - } - - window.app.hideLoading(); - isLoggingInOrSigningUp = false; - } - - function getExpenseItemHtmlElement(expense) { - const template = document.getElementById('expense-item'); - - const clonedElement = template.content.firstElementChild.cloneNode(true); - clonedElement.dataset.id = expense.id; - - const costElement = clonedElement.querySelector('article span.cost'); - costElement.textContent = window.app.utils.formatNumber(currency, expense.cost); - - const budgetElement = clonedElement.querySelector('article span.budget'); - budgetElement.textContent = expense.budget; - - const descriptionElement = clonedElement.querySelector('span.description'); - descriptionElement.textContent = expense.description; - - const dateElement = clonedElement.querySelector('time'); - dateElement.textContent = window.app.utils.showFormattedDate(expense.date); - - return clonedElement; - } - - function getBudgetItemHtmlElement(budget) { - const template = document.getElementById('budget-item'); - - const clonedElement = template.content.firstElementChild.cloneNode(true); - clonedElement.dataset.name = budget.name; - - const costElement = clonedElement.querySelector('article span.cost'); - costElement.textContent = `${window.app.utils.formatNumber(currency, budget.expensesCost)} of ${ - window.app.utils.formatNumber(currency, budget.value) - }`; - - const nameElement = clonedElement.querySelector('article span.name'); - nameElement.textContent = budget.name; - - const missingElement = clonedElement.querySelector('span.missing'); - missingElement.textContent = window.app.utils.formatNumber(currency, budget.value - budget.expensesCost); - - if (budget.id === 'total') { - clonedElement.classList.add('total'); - } - - return clonedElement; - } - - function getBudgetSelectOptionHtmlElement(budgetName) { - const template = document.getElementById('budget-select-option'); - - const clonedElement = template.content.firstElementChild.cloneNode(true); - clonedElement.textContent = budgetName; - - return clonedElement; - } - - function getBudgetsFilterModalBudgetItemHtmlElement(budget) { - const template = document.getElementById('budgets-filter-modal-budget-item'); - - const clonedElement = template.content.firstElementChild.cloneNode(true); - - const labelElement = clonedElement.querySelector('label'); - labelElement.attributes[0].value = `budget-filter-name-${budget.id}`; - - const nameElement = clonedElement.querySelector('label span'); - nameElement.textContent = budget.name; - - const inputElement = clonedElement.querySelector('input'); - inputElement.value = budget.name; - inputElement.id = `budget-filter-name-${budget.id}`; - - if (budgetFilters.has(budget.name)) { - inputElement.checked = true; - } - - return clonedElement; - } - - async function showData(isComingFromEmptyState = false) { - monthNavigationLabel.textContent = window.app.utils.showFormattedDate(currentMonth, { - showDay: false, - showYear: true, - longMonth: true, - longYear: true, - }); - - const allBudgets = await window.app.dataUtils.fetchBudgets(); - const budgets = await window.app.dataUtils.fetchBudgets(currentMonth); - const expenses = await window.app.dataUtils.fetchExpenses(currentMonth); - - const budgetOptions = new Set([{ name: 'Misc' }, ...allBudgets].map((budget) => budget.name)); - - let totalCost = 0; - let totalBudget = 0; - - const budgetsToShow = [...budgets] - .map((budget) => { - const budgetToShow = { - expensesCost: 0, - ...budget, - }; - - // Calculate expenses cost - expenses.forEach((expense) => { - if (expense.budget === budget.name) { - budgetToShow.expensesCost += expense.cost; - } - }); - - totalCost += budgetToShow.expensesCost; - totalBudget += budgetToShow.value; - - return budgetToShow; - }) - .sort(window.app.utils.sortByMissingBudget); - - // Add Total budget - if (budgetsToShow.length > 0) { - budgetsToShow.unshift({ - id: 'total', - name: 'Total', - value: totalBudget, - expensesCost: totalCost, - month: currentMonth, - }); - } - - // If this is for the current or next month and there are no budgets, create budgets based on the previous/current month. - if (budgets.length === 0 && !isComingFromEmptyState) { - const currentMonthDate = new Date(`${currentMonth}-15`); - currentMonthDate.setMonth(currentMonthDate.getMonth() + 1); - const actualCurrentMonth = currentMonthDate.toISOString().substring(0, 7); - - const nextMonthDate = new Date(); - nextMonthDate.setMonth(nextMonthDate.getMonth() + 1); - const nextMonth = nextMonthDate.toISOString().substring(0, 7); - - if (currentMonth === nextMonth || currentMonth === actualCurrentMonth) { - const previousMonthDate = new Date(`${currentMonth}-15`); - previousMonthDate.setMonth(previousMonthDate.getMonth() - 1); - const previousMonth = previousMonthDate.toISOString().substring(0, 7); - - await window.app.dataUtils.copyBudgets(previousMonth, currentMonth); - await showData(true); - return; - } - } - - let expensesToShow = expenses; - - if (expensesFilterSearchInput.value) { - expensesToShow = expensesToShow.filter((expense) => - expense.description - .toLowerCase() - .includes(expensesFilterSearchInput.value.toLowerCase()) - ); - } - - if (budgetFilters.size > 0) { - budgetsFilterButton.classList.add('active'); - expensesToShow = expensesToShow.filter((expense) => budgetFilters.has(expense.budget)); - } else { - budgetsFilterButton.classList.remove('active'); - } - - // Show month's budgets - budgetsList.replaceChildren(); - for (const budget of budgetsToShow) { - const element = getBudgetItemHtmlElement(budget); - - if (budget.id !== 'total') { - element.addEventListener('click', () => showEditBudgetModal(budget)); - } - - budgetsList.appendChild(element); - } - - if (budgetsToShow.length === 0) { - budgetsList.innerHTML = 'There are no budgets yet. Add some!'; - } - - // Show month's expenses - expensesList.replaceChildren(); - for (const expense of expensesToShow) { - const element = getExpenseItemHtmlElement(expense); - - element.addEventListener('click', () => showEditExpenseModal(expense)); - - expensesList.appendChild(element); - } - - if (expensesToShow.length === 0) { - expensesList.innerHTML = 'No expenses found for this month. Add some!'; - } - - // Show all budgets in expenseBudgetSelect - expenseBudgetSelect.replaceChildren(); - for (const budgetName of budgetOptions.values()) { - const element = getBudgetSelectOptionHtmlElement(budgetName); - - expenseBudgetSelect.appendChild(element); - } - } - - async function navigateToMonth(month) { - currentMonth = month; - budgetFilters.clear(); - await showData(); - } - - async function navigateToPreviousMonth() { - const previousMonthDate = new Date(`${currentMonth}-15`); - previousMonthDate.setMonth(previousMonthDate.getMonth() - 1); - const month = previousMonthDate.toISOString().substring(0, 7); - - await navigateToMonth(month); - } - - async function navigateToNextMonth() { - const currentMonthDate = new Date(`${currentMonth}-15`); - currentMonthDate.setMonth(currentMonthDate.getMonth() + 1); - const month = currentMonthDate.toISOString().substring(0, 7); - - const nextMonthDate = new Date(); - nextMonthDate.setMonth(nextMonthDate.getMonth() + 1); - const nextMonth = nextMonthDate.toISOString().substring(0, 7); - - if (month > nextMonth) { - window.app.showNotification('Cannot travel further into the future!', 'error'); - return; - } - - await navigateToMonth(month); - } - - async function initializePage() { - await window.app.dataUtils.initializeDb(); - - const userSession = await window.app.getUserSession(); - currency = userSession.profile?.currency || '$'; - - showData(); - } - - let isAddingExpense = false; - - async function addExpense(event) { - event.preventDefault(); - event.stopPropagation(); - - if (isAddingExpense) { - return; - } - - addExpenseButton.textContent = 'Adding...'; - isAddingExpense = true; - window.app.showLoading(); - - const cost = Number.parseFloat(expenseCostInput.value.replace(',', '.')); - const description = expenseDescriptionInput.value; - const budget = expenseBudgetSelect.value; - const date = expenseDateInput.value; - - const parsedExpense = { - id: 'newExpense', - cost, - description, - budget, - date, - }; - - const success = await window.app.dataUtils.saveExpense(parsedExpense); - - if (success) { - window.app.showNotification('Expense added successfully.'); - addExpenseForm.reset(); - } - - await showData(); - - window.app.hideLoading(); - isAddingExpense = false; - addExpenseButton.textContent = 'Add Expense'; - } - - async function showEditExpenseModal(expense) { - const { Swal } = window; - - let isUpdating = false; - - await Swal.fire({ - template: '#edit-expense-modal', - focusConfirm: false, - allowEscapeKey: true, - preConfirm: async () => { - const updatedExpense = { - id: expense.id, - cost: Number.parseFloat(document.getElementById('edit-expense-cost').value.replace(',', '.')), - description: document.getElementById('edit-expense-description').value, - budget: document.getElementById('edit-expense-budget').value, - date: document.getElementById('edit-expense-date').value, - isRecurring: document.getElementById('edit-expense-recurring').value === 'yes', - }; - - const saveExpenseButton = Swal.getConfirmButton(); - - if (isUpdating) { - return false; - } - - saveExpenseButton.textContent = 'Saving...'; - isUpdating = true; - window.app.showLoading(); - - const success = await window.app.dataUtils.saveExpense(updatedExpense); - - if (success) { - window.app.showNotification('Expense updated successfully.'); - } - - await showData(); - - window.app.hideLoading(); - isUpdating = false; - saveExpenseButton.textContent = 'Save'; - - return Boolean(success); - }, - preDeny: async () => { - const deleteExpenseButton = Swal.getDenyButton(); - - if (isUpdating) { - return false; - } - - const { isConfirmed } = await Swal.fire({ - title: 'Are you sure?', - text: 'You won\'t be able to recover this expense!', - icon: 'warning', - showCancelButton: true, - confirmButtonColor: 'red', - confirmButtonText: 'Yes, delete it!', - }); - - if (isConfirmed) { - deleteExpenseButton.textContent = 'Deleting...'; - isUpdating = true; - window.app.showLoading(); - - const success = await window.app.dataUtils.deleteExpense(expense.id); - - if (success) { - window.app.showNotification('Expense deleted successfully.'); - } - - await showData(); - - window.app.hideLoading(); - isUpdating = false; - deleteExpenseButton.textContent = 'Delete'; - - return Boolean(success); - } - - return false; - }, - willOpen: async () => { - // Show all budgets in expenseBudgetSelect - const allBudgets = await window.app.dataUtils.fetchBudgets(); - const budgetOptions = new Set([{ name: 'Misc' }, ...allBudgets].map((budget) => budget.name)); - const budgetSelect = document.getElementById('edit-expense-budget'); - budgetSelect.replaceChildren(); - for (const budgetName of budgetOptions.values()) { - const element = getBudgetSelectOptionHtmlElement(budgetName); - - budgetSelect.appendChild(element); - } - - document.getElementById('edit-expense-cost').value = expense.cost; - document.getElementById('edit-expense-description').value = expense.description; - document.getElementById('edit-expense-budget').value = expense.budget; - document.getElementById('edit-expense-date').value = expense.date; - document.getElementById('edit-expense-recurring').value = expense.isRecurring ? 'yes' : 'no'; - document.getElementById('edit-expense-recurring').selectedIndex = expense.isRecurring ? 1 : 0; - }, - }); - } - - async function showEditBudgetModal(budget) { - const { Swal } = window; - - let isUpdating = false; - - await Swal.fire({ - template: '#edit-budget-modal', - focusConfirm: false, - allowEscapeKey: true, - preConfirm: async () => { - const updatedBudget = { - id: budget.id, - name: document.getElementById('edit-budget-name').value, - value: Number.parseFloat(document.getElementById('edit-budget-value').value.replace(',', '.')), - month: document.getElementById('edit-budget-month').value.substring(0, 7), - }; - - const saveBudgetButton = Swal.getConfirmButton(); - - if (isUpdating) { - return false; - } - - saveBudgetButton.textContent = 'Saving...'; - isUpdating = true; - window.app.showLoading(); - - const success = await window.app.dataUtils.saveBudget(updatedBudget); - - if (success) { - window.app.showNotification('Budget updated successfully.'); - } - - await showData(); - - window.app.hideLoading(); - isUpdating = false; - saveBudgetButton.textContent = 'Save'; - - return Boolean(success); - }, - preDeny: async () => { - const deleteBudgetButton = Swal.getDenyButton(); - - if (isUpdating) { - return false; - } - - const { isConfirmed } = await Swal.fire({ - title: 'Are you sure?', - text: 'You won\'t be able to recover this budget!', - icon: 'warning', - showCancelButton: true, - confirmButtonColor: 'red', - confirmButtonText: 'Yes, delete it!', - }); - - if (isConfirmed) { - deleteBudgetButton.textContent = 'Deleting...'; - isUpdating = true; - window.app.showLoading(); - - const success = await window.app.dataUtils.deleteBudget(budget.id); - - if (success) { - window.app.showNotification('Budget deleted successfully.'); - } - - await showData(); - - window.app.hideLoading(); - isUpdating = false; - deleteBudgetButton.textContent = 'Delete'; - - return Boolean(success); - } - - return false; - }, - willOpen: () => { - document.getElementById('edit-budget-name').value = budget.name; - document.getElementById('edit-budget-value').value = budget.value; - document.getElementById('edit-budget-month').value = `${budget.month}-15`; - }, - }); - } - - async function showAddBudgetModal() { - const { Swal } = window; - - let isAdding = false; - - await Swal.fire({ - template: '#edit-budget-modal', - focusConfirm: false, - allowEscapeKey: true, - showDenyButton: false, - title: 'Add Budget', - preConfirm: async () => { - const newBudget = { - id: 'newBudget', - name: document.getElementById('edit-budget-name').value, - value: Number.parseFloat(document.getElementById('edit-budget-value').value.replace(',', '.')), - month: document.getElementById('edit-budget-month').value.substring(0, 7), - }; - - const saveBudgetButton = Swal.getConfirmButton(); - - if (isAdding) { - return false; - } - - saveBudgetButton.textContent = 'Adding...'; - isAdding = true; - window.app.showLoading(); - - const success = await window.app.dataUtils.saveBudget(newBudget); - - if (success) { - window.app.showNotification('Budget added successfully.'); - } - - await showData(); - - window.app.hideLoading(); - isAdding = false; - saveBudgetButton.textContent = 'Add'; - - return Boolean(success); - }, - willOpen: () => { - const saveBudgetButton = Swal.getConfirmButton(); - saveBudgetButton.textContent = 'Add'; - - document.getElementById('edit-budget-name').value = ''; - document.getElementById('edit-budget-value').value = 100; - document.getElementById('edit-budget-month').value = `${currentMonth}-15`; - }, - }); - } - - async function showBudgetsFilterModal() { - const { Swal } = window; - - await Swal.fire({ - template: '#budgets-filter-modal', - focusConfirm: false, - allowEscapeKey: true, - showConfirmButton: false, - didClose: () => { - budgetsFilterButton.blur(); - }, - willOpen: async () => { - // Show month's budgets in #budgets-filter-form - const monthBudgets = await window.app.dataUtils.fetchBudgets(currentMonth); - const budgetsFilterForm = document.getElementById('budgets-filter-form'); - budgetsFilterForm.replaceChildren(); - for (const budget of monthBudgets) { - const element = getBudgetsFilterModalBudgetItemHtmlElement(budget); - - const inputElement = element.querySelector('input'); - - inputElement.addEventListener('change', () => { - if (!inputElement.checked) { - budgetFilters.delete(budget.name); - } else { - budgetFilters.add(budget.name); - } - - showData(); - }); - - budgetsFilterForm.appendChild(element); - } - }, - }); - } - - async function chooseMonthModal() { - const { Swal } = window; - - const { value: newMonth } = await Swal.fire({ - template: '#choose-month-modal', - focusConfirm: false, - allowEscapeKey: true, - preConfirm: () => { - const monthInput = document.getElementById('choose-month-input').value; - const month = monthInput.substring(0, 7); - - const nextMonthDate = new Date(); - nextMonthDate.setMonth(nextMonthDate.getMonth() + 1); - const nextMonth = nextMonthDate.toISOString().substring(0, 7); - - if (month > nextMonth) { - window.app.showNotification('Cannot travel further into the future!', 'error'); - return false; - } - - return month; - }, - willOpen: () => { - document.getElementById('choose-month-input').value = `${currentMonth}-15`; - }, - }); - - if (newMonth) { - await navigateToMonth(newMonth); - } - } - - if (window.app.isLoggedIn) { - initializePage(); - } - - loginForm.addEventListener('submit', login); - signupButton.addEventListener('click', signup); - addExpenseForm.addEventListener('submit', addExpense); - addBudgetButton.addEventListener('click', showAddBudgetModal); - budgetsFilterButton.addEventListener('click', showBudgetsFilterModal); - expensesFilterSearchInput.addEventListener('keyup', window.app.utils.debounce(showData, 150)); - monthNavigationPreviousButton.addEventListener('click', navigateToPreviousMonth); - monthNavigationNextButton.addEventListener('click', navigateToNextMonth); - monthNavigationLabel.addEventListener('click', chooseMonthModal); - }); -})(); diff --git a/public/js/script.js b/public/js/script.js index 4a38078..e4c9cc4 100644 --- a/public/js/script.js +++ b/public/js/script.js @@ -1,78 +1,13 @@ (() => { - const cachedData = { - budgets: [], - expenses: [], - }; - - async function initializeApp() { + function initializeApp() { window.app = window.app || {}; initializeLoading(); + // TODO: Uncomment this when supporting offline mode // if (navigator && navigator.serviceWorker) { // navigator.serviceWorker.register('/public/js/sw.js'); // } - // Expose helper functions - window.app.isLoggedIn = false; - window.app.showNotification = showNotification; - window.app.doLogout = doLogout; - window.app.getUserSession = getUserSession; - window.app.showValidSessionElements = showValidSessionElements; - window.app.hideValidSessionElements = hideValidSessionElements; - window.app.dataUtils = { - validateLogin, - createAccount, - initializeDb, - fetchExpenses, - saveExpense, - deleteExpense, - fetchBudgets, - saveBudget, - deleteBudget, - copyBudgets, - deleteAllData, - exportAllData, - importData, - generateId, - }; - window.app.utils = { - formatNumber, - showFormattedDate, - sortByDate, - sortByCount, - sortByName, - sortByMissingBudget, - dateDiffInDays, - debounce, - }; - - const checkForValidSession = async () => { - const isUserLoggedIn = await isLoggedIn(); - - if (isUserLoggedIn) { - window.app.isLoggedIn = true; - showValidSessionElements(); - - const userSession = await getUserSession(); - - if (userSession.trialExpirationDate) { - const trialExpirationDate = new Date(userSession.trialExpirationDate); - const now = new Date(); - - if (userSession.subscriptionStatus !== 'active' && trialExpirationDate < now) { - showNotification('Your trial has expired!', 'error'); - - // Give people some time to logout or export - setTimeout(() => { - window.location.href = '/pricing'; - }, 10000); - } - } - } - }; - - await checkForValidSession(); - document.dispatchEvent(new Event('app-loaded')); window.app.hideLoading(); @@ -85,1014 +20,6 @@ window.app.hideLoading = () => loadingComponent.classList.add('hide'); } - function showValidSessionElements() { - const elementsToShow = document.querySelectorAll('[data-has-valid-session]'); - const elementsToHide = document.querySelectorAll('[data-has-invalid-session]'); - - elementsToShow.forEach((element) => element.classList.remove('hidden')); - elementsToHide.forEach((element) => element.classList.add('hidden')); - } - - function hideValidSessionElements() { - const elementsToShow = document.querySelectorAll('[data-has-invalid-session]'); - const elementsToHide = document.querySelectorAll('[data-has-valid-session]'); - - elementsToShow.forEach((element) => element.classList.remove('hidden')); - elementsToHide.forEach((element) => element.classList.add('hidden')); - } - - function showNotification(message, type = 'success') { - const { Swal } = window; - - const Toast = window.Swal.mixin({ - toast: true, - position: 'top-end', - showConfirmButton: false, - timer: type === 'success' ? 2500 : 0, - timerProgressBar: type === 'success', - didOpen: (toast) => { - toast.addEventListener('mouseenter', Swal.stopTimer); - toast.addEventListener('mouseleave', Swal.resumeTimer); - }, - }); - - Toast.fire({ - icon: type, - title: message, - }); - } - - async function doLogout() { - try { - const { userbase } = window; - await userbase.signOut(); - hideValidSessionElements(); - - Swal.fire('Alright!', 'No idea who you are right now.', 'success'); - return true; - } catch (error) { - const { Swal } = window; - - Swal.fire( - 'Something went wrong!', - `Uh oh! Something wrong happened: ${error && error.message}`, - 'error', - ); - } - - return false; - } - - async function isLoggedIn() { - try { - const { userbase } = window; - const { userbaseConfig } = window.app; - const session = await userbase.init(userbaseConfig); - if (session.user) { - return true; - } - } catch (_error) { - // Do nothing - } - - return false; - } - - async function getUserSession() { - try { - const { userbase } = window; - const { userbaseConfig } = window.app; - const session = await userbase.init(userbaseConfig); - return session.user; - } catch (_error) { - // Do nothing - } - - return null; - } - - async function validateLogin(email, password) { - try { - const { userbase } = window; - const { userbaseConfig } = window.app; - await userbase.signIn({ - username: email, - password, - sessionLength: userbaseConfig.sessionLength, - rememberMe: 'local', - }); - return { success: true }; - } catch (error) { - console.log(error); - return { success: false, error }; - } - } - - async function createAccount(email, password) { - try { - const { userbase } = window; - const { userbaseConfig } = window.app; - await userbase.signUp({ - username: email, - password, - sessionLength: userbaseConfig.sessionLength, - rememberMe: 'local', - email, - }); - return { success: true }; - } catch (error) { - console.log(error); - return { success: false, error }; - } - } - - function getExpenseFromItem(item) { - try { - return { - id: item.itemId, - cost: item.item.cost, - description: item.item.description, - budget: item.item.budget, - date: item.item.date, - isRecurring: item.item.isRecurring, - }; - } catch (_error) { - return null; - } - } - - function getBudgetFromItem(item) { - try { - return { - id: item.itemId, - name: item.item.name, - month: item.item.month, - value: item.item.value, - }; - } catch (_error) { - return null; - } - } - - async function loadItemsAsync() { - const { userbase } = window; - await userbase.openDatabase({ - databaseName: 'expenses', - changeHandler: (items) => { - const expenses = items - .map(getExpenseFromItem) - .filter((expense) => Boolean(expense)); - - hasFinishedLoading.expenses = true; - - cachedData.expenses = expenses; - }, - }); - - await userbase.openDatabase({ - databaseName: 'budgets', - changeHandler: (items) => { - const budgets = items - .map(getBudgetFromItem) - .filter((budget) => Boolean(budget)); - - hasFinishedLoading.budgets = true; - - cachedData.budgets = budgets; - }, - }); - } - - async function initializeDb() { - try { - const { userbase } = window; - const { userbaseConfig } = window.app; - await userbase.init(userbaseConfig); - - await loadItemsAsync(); - } catch (error) { - console.log(error); - showNotification(error, 'error'); - } - } - - const hasFinishedLoading = { - budgets: false, - expenses: false, - }; - - async function fetchBudgets(month) { - try { - // Very ugly, but... works. - while (!hasFinishedLoading.budgets) { - await new Promise((resolve) => { - setTimeout(resolve, 100); - }); - } - - const sortedBudgets = cachedData.budgets - .filter((budget) => { - if (!month) { - return true; - } - - if (budget.month === month) { - return true; - } - - return false; - }) - .sort(sortByName); - - return sortedBudgets; - } catch (error) { - const { Swal } = window; - - Swal.fire({ - title: 'Uh-oh', - text: 'Something went wrong fetching budgets.', - }); - - console.error(error); - } - - return []; - } - - async function fetchExpenses(month) { - try { - // Very ugly, but... works. - while (!hasFinishedLoading.expenses) { - await new Promise((resolve) => { - setTimeout(resolve, 100); - }); - } - - const sortedExpenses = cachedData.expenses - .filter((expense) => { - if (!month) { - return true; - } - - if (expense.date >= `${month}-01` && expense.date <= `${month}-31`) { - return true; - } - - return false; - }) - .sort(sortByDate) - .reverse(); - - return sortedExpenses; - } catch (error) { - const { Swal } = window; - - Swal.fire({ - title: 'Uh-oh', - text: 'Something went wrong fetching expenses.', - }); - - console.error(error); - } - - return []; - } - - async function saveBudget(budget) { - try { - if (budget.name === 'Total') { - showNotification('Cannot create budget named "Total".', 'error'); - return false; - } - - if (budget.name.trim().length === 0) { - showNotification('The budget needs a valid name.', 'error'); - return false; - } - - if (budget.value <= 0 || Number.isNaN(budget.value)) { - showNotification('The budget needs a valid value.', 'error'); - return false; - } - - if (!isValidDate(budget.month)) { - budget.month = new Date().toISOString().substring(0, 7); - } - - // Check if the name is unique for the given month - const existingBudgetsInMonth = await fetchBudgets(budget.month); - const duplicateBudget = existingBudgetsInMonth.find( - (existingBudget) => existingBudget.name === budget.name && existingBudget.id !== budget.id, - ); - - if (duplicateBudget) { - showNotification( - 'A budget with the same name for the same month already exists.', - 'error', - ); - return false; - } - - const { userbase } = window; - - if (budget.id === 'newBudget') { - budget.id = `${generateId()}`; - - await userbase.insertItem({ - databaseName: 'budgets', - item: { - name: budget.name, - value: budget.value, - month: budget.month, - }, - itemId: budget.id, - }); - } else { - const existingBudget = cachedData.budgets.find( - (_budget) => _budget.id === budget.id, - ); - const oldName = existingBudget.name; - const newName = budget.name; - - await userbase.updateItem({ - databaseName: 'budgets', - item: { - name: budget.name, - value: budget.value, - month: existingBudget.month, // Don't allow changing a budget's month - }, - itemId: budget.id, - }); - - // Update all expenses with the previous budget name to the new one, if it changed - if (oldName !== newName) { - const matchingExpenses = ( - await fetchExpenses(existingBudget.month) - ).filter((expense) => expense.budget === oldName); - - const updateChunks = splitArrayInChunks( - matchingExpenses, - 10, - ); - - for (const machingExpensesChunk of updateChunks) { - await userbase.putTransaction({ - databaseName: 'expenses', - operations: machingExpensesChunk.map((expense) => ({ - command: 'Update', - item: { - cost: expense.cost, - description: expense.description, - budget: newName, - date: expense.date, - isRecurring: expense.isRecurring, - }, - itemId: expense.id, - })), - }); - } - } - } - - return true; - } catch (error) { - const { Swal } = window; - - Swal.fire({ - title: 'Uh-oh', - text: 'Something went wrong saving that budget.', - }); - - console.error(error); - } - - return false; - } - - async function saveExpense(expense) { - try { - if (!expense.cost || typeof expense.cost !== 'number') { - showNotification('Cost missing or invalid', 'error'); - return false; - } - - if (expense.description.trim().length === 0) { - showNotification('The expense needs a valid description.', 'error'); - return false; - } - - if (!isValidDate(expense.date)) { - expense.date = new Date().toISOString().substring(0, 10); - } - - // Check if there's an existing expense with a better budget - if ( - (!expense.budget || expense.budget === 'Misc') && - expense.id === 'newExpense' - ) { - const matchingExpense = (await fetchExpenses()).find( - (_expense) => _expense.description === expense.description, - ); - - if (matchingExpense && matchingExpense.budget) { - expense.budget = matchingExpense.budget; - } - } - - if (!expense.budget || typeof expense.budget !== 'string') { - expense.budget = 'Misc'; - } - - if (!expense.isRecurring || typeof expense.isRecurring !== 'boolean') { - expense.isRecurring = false; - } - - // Check if the budget exists for the expense in that given month, otherwise create one - const existingBudget = ( - await fetchBudgets(expense.date.substring(0, 7)) - ).find((budget) => budget.name === expense.budget); - - const { userbase } = window; - - if (!existingBudget) { - const newBudgetId = `${generateId()}`; - - await userbase.insertItem({ - databaseName: 'budgets', - item: { - name: expense.budget, - month: expense.date.substring(0, 7), - value: 100, - }, - itemId: newBudgetId, - }); - } - - if (expense.id === 'newExpense') { - expense.id = `${generateId()}`; - - await userbase.insertItem({ - databaseName: 'expenses', - item: { - cost: expense.cost, - description: expense.description, - budget: expense.budget, - date: expense.date, - isRecurring: expense.isRecurring, - }, - itemId: expense.id, - }); - } else { - await userbase.updateItem({ - databaseName: 'expenses', - item: { - cost: expense.cost, - description: expense.description, - budget: expense.budget, - date: expense.date, - isRecurring: expense.isRecurring, - }, - itemId: expense.id, - }); - } - - return true; - } catch (error) { - const { Swal } = window; - - Swal.fire({ - title: 'Uh-oh', - text: 'Something went wrong saving that expense.', - }); - - console.error(error); - } - - return false; - } - - async function deleteBudget(budgetId) { - try { - const existingBudget = cachedData.budgets.find( - (budget) => budget.id === budgetId, - ); - - // Check if the budget has no expenses, if so, don't delete - const matchingExpenses = (await fetchExpenses(existingBudget.month)).filter( - (expense) => expense.budget === existingBudget.name, - ); - - if (matchingExpenses.length > 0) { - // Check if there are duplicate budgets (can happen on slow sync) - const matchingBudgets = (await fetchBudgets(existingBudget.month)).filter( - (budget) => budget.name === existingBudget.name, - ); - - if (matchingBudgets.length === 1) { - showNotification( - 'There are expenses using this budget. You can\'t delete a budget with expenses', - 'error', - ); - return false; - } - } - - const { userbase } = window; - - await userbase.deleteItem({ - databaseName: 'budgets', - itemId: budgetId, - }); - - const cachedItemIndex = cachedData.budgets.findIndex( - (budget) => budget.id === budgetId, - ); - if (cachedItemIndex !== -1) { - cachedData.budgets.splice(cachedItemIndex, 1); - } - - return true; - } catch (error) { - const { Swal } = window; - - Swal.fire({ - title: 'Uh-oh', - text: 'Something went wrong deleting that budget.', - }); - - console.error(error); - } - - return false; - } - - async function deleteExpense(expenseId) { - try { - const { userbase } = window; - - await userbase.deleteItem({ - databaseName: 'expenses', - itemId: expenseId, - }); - - const cachedItemIndex = cachedData.expenses.findIndex( - (expense) => expense.id === expenseId, - ); - if (cachedItemIndex !== -1) { - cachedData.expenses.splice(cachedItemIndex, 1); - } - - return true; - } catch (error) { - const { Swal } = window; - - Swal.fire({ - title: 'Uh-oh', - text: 'Something went wrong deleting that expense.', - }); - - console.error(error); - } - - return false; - } - - async function deleteAllData() { - const budgets = await fetchBudgets(); - const expenses = await fetchExpenses(); - - const deleteBudgetChunks = splitArrayInChunks(budgets, 10); - const deleteExpenseChunks = splitArrayInChunks(expenses, 10); - - const { userbase } = window; - - for (const budgetsToDelete of deleteBudgetChunks) { - await userbase.putTransaction({ - databaseName: 'budgets', - operations: budgetsToDelete.map((budget) => ({ - command: 'Delete', - itemId: budget.id, - })), - }); - - // Wait a second, to avoid hitting rate limits - await new Promise((resolve) => { - setTimeout(resolve, 1000); - }); - } - - for (const expensesToDelete of deleteExpenseChunks) { - await userbase.putTransaction({ - databaseName: 'expenses', - operations: expensesToDelete.map((expense) => ({ - command: 'Delete', - itemId: expense.id, - })), - }); - - // Wait a second, to avoid hitting rate limits - await new Promise((resolve) => { - setTimeout(resolve, 1000); - }); - } - - cachedData.budgets.length = 0; - cachedData.expenses.length = 0; - hasFinishedLoading.budgets = false; - hasFinishedLoading.expenses = false; - } - - async function exportAllData() { - // Don't export anything until we're done with the first full load - if (!hasFinishedLoading.budgets || !hasFinishedLoading.expenses) { - return {}; - } - - try { - const budgets = (await fetchBudgets()).sort(sortByName); - const expenses = (await fetchExpenses()).sort(sortByDate); - - return { budgets, expenses }; - } catch (error) { - const { Swal } = window; - - Swal.fire({ - title: 'Uh-oh', - text: 'Something went wrong exporting data.', - }); - - console.error(error); - } - - return {}; - } - - async function importData(replaceData, budgets, expenses) { - // Don't import anything until we're done with the first full load - if (!hasFinishedLoading.budgets || !hasFinishedLoading.expenses) { - return false; - } - - try { - if (replaceData) { - await deleteAllData(); - - await initializeDb(); - - // Very ugly, but... works. - while (!hasFinishedLoading.budgets || !hasFinishedLoading.expenses) { - await new Promise((resolve) => { - setTimeout(resolve, 100); - }); - } - } - - const finalBudgetsToAdd = []; - - for (const budget of budgets) { - const newBudgetId = `${generateId()}`; - const newBudget = { - id: newBudgetId, - name: budget.name, - value: budget.value, - month: budget.month, - }; - - finalBudgetsToAdd.push(newBudget); - } - - const addBudgetChunks = splitArrayInChunks( - finalBudgetsToAdd, - 10, - ); - - const { userbase } = window; - - for (const budgetsToAdd of addBudgetChunks) { - await userbase.putTransaction({ - databaseName: 'budgets', - operations: budgetsToAdd.map((budget) => ({ - command: 'Insert', - item: { - name: budget.name, - value: budget.value, - month: budget.month, - }, - itemId: budget.id, - })), - }); - - // Wait a second, to avoid hitting rate limits - await new Promise((resolve) => { - setTimeout(resolve, 1000); - }); - } - - const finalExpensesToAdd = []; - - for (const expense of expenses) { - const newExpenseId = `${generateId()}`; - const newExpense = { - id: newExpenseId, - cost: expense.cost, - budget: expense.budget, - description: expense.description, - date: expense.date, - isRecurring: expense.isRecurring, - }; - - finalExpensesToAdd.push(newExpense); - } - - const addExpenseChunks = splitArrayInChunks( - finalExpensesToAdd, - 10, - ); - - for (const expensesToAdd of addExpenseChunks) { - await userbase.putTransaction({ - databaseName: 'expenses', - operations: expensesToAdd.map((expense) => ({ - command: 'Insert', - item: { - cost: expense.cost, - budget: expense.budget, - description: expense.description, - date: expense.date, - isRecurring: expense.isRecurring, - }, - itemId: expense.id, - })), - }); - - // Wait a second, to avoid hitting rate limits - await new Promise((resolve) => { - setTimeout(resolve, 1000); - }); - } - - return true; - } catch (error) { - const { Swal } = window; - - Swal.fire({ - title: 'Uh-oh', - text: 'Something went wrong importing data.', - }); - - console.error(error); - } - - return false; - } - - async function copyBudgets(originalMonth, destinationMonth) { - // Don't copy anything until we're done with the first full load - if (!hasFinishedLoading.budgets || !hasFinishedLoading.expenses) { - return; - } - - const originalBudgets = await fetchBudgets(originalMonth); - const destinationBudgets = originalBudgets.map((budget) => { - const newBudget = { ...budget }; - newBudget.id = `${generateId()}`; - newBudget.month = destinationMonth; - return newBudget; - }); - - if (destinationBudgets.length > 0) { - try { - const finalBudgetsToAdd = []; - - for (const budget of destinationBudgets) { - const newBudget = { - id: budget.id, - name: budget.name, - value: budget.value, - month: budget.month, - }; - - finalBudgetsToAdd.push(newBudget); - } - - const addBudgetChunks = splitArrayInChunks( - finalBudgetsToAdd, - 10, - ); - - const { userbase } = window; - - for (const budgetsToAdd of addBudgetChunks) { - await userbase.putTransaction({ - databaseName: 'budgets', - operations: budgetsToAdd.map((budget) => ({ - command: 'Insert', - item: { - name: budget.name, - value: budget.value, - month: budget.month, - }, - itemId: budget.id, - })), - }); - } - } catch (error) { - Swal.fire({ - title: 'Uh-oh', - text: 'Something went wrong copying budgets.', - }); - - console.error(error); - } - } - - const originalRecurringExpenses = (await fetchExpenses(originalMonth)).filter((expense) => expense.isRecurring); - const destinationExpenses = originalRecurringExpenses.map((expense) => { - const expenseDay = new Date(expense.date).getDate(); - const newExpense = { ...expense }; - newExpense.id = `${generateId()}`; - newExpense.date = `${destinationMonth}-${(`0${expenseDay}`).slice(-2)}`; - return newExpense; - }); - - if (destinationExpenses.length > 0) { - try { - const finalExpensesToAdd = []; - - for (const expense of destinationExpenses) { - const newExpense = { - id: expense.id, - cost: expense.cost, - description: expense.description, - budget: expense.budget, - date: expense.date, - isRecurring: expense.isRecurring, - }; - - finalExpensesToAdd.push(newExpense); - } - - const addExpenseChunks = splitArrayInChunks( - finalExpensesToAdd, - 10, - ); - - const { userbase } = window; - - for (const expensesToAdd of addExpenseChunks) { - await userbase.putTransaction({ - databaseName: 'expenses', - operations: expensesToAdd.map((expense) => ({ - command: 'Insert', - item: { - cost: expense.cost, - description: expense.description, - budget: expense.budget, - date: expense.date, - isRecurring: expense.isRecurring, - }, - itemId: expense.id, - })), - }); - } - } catch (error) { - Swal.fire({ - title: 'Uh-oh', - text: 'Something went wrong copying expenses.', - }); - - console.error(error); - } - } - } - - function generateId() { - return `${Date.now().toString()}:${Math.random()}`; - } - - function splitArrayInChunks(array, chunkLength) { - const chunks = []; - let chunkIndex = 0; - const arrayLength = array.length; - - while (chunkIndex < arrayLength) { - chunks.push(array.slice(chunkIndex, chunkIndex += chunkLength)); - } - - return chunks; - } - - function sortByDate(objectA, objectB) { - if (objectA.date < objectB.date) { - return -1; - } - if (objectA.date > objectB.date) { - return 1; - } - return 0; - } - - function sortByCount(objectA, objectB) { - if (objectA.count < objectB.count) { - return 1; - } - if (objectA.count > objectB.count) { - return -1; - } - return 0; - } - - function sortByName(objectA, objectB) { - const nameA = objectA.name.toUpperCase(); - const nameB = objectB.name.toUpperCase(); - if (nameA < nameB) { - return -1; - } - if (nameA > nameB) { - return 1; - } - return 0; - } - - function sortByMissingBudget(objectA, objectB) { - const valueA = objectA.value - objectA.expensesCost; - const valueB = objectB.value - objectB.expensesCost; - return valueB - valueA; - } - - const currencyMap = new Map([ - ['$', 'USD'], - ['€', 'EUR'], - ['£', 'GBP'], - ['¥', 'JPY'], - ['₹', 'INR'], - ]); - - function formatNumber(currency, number) { - return new Intl.NumberFormat('en-US', { - style: 'currency', - currency: currencyMap.get(currency) || 'USD', - minimumFractionDigits: 0, - maximumFractionDigits: 2, - }).format(Number.parseFloat(`${number}`.replace(',', '.'))); - } - - const months = [ - 'January', - 'February', - 'March', - 'April', - 'May', - 'June', - 'July', - 'August', - 'September', - 'October', - 'November', - 'December', - ]; - - function showFormattedDate( - stringDate, - { showDay = true, showYear = false, longMonth = false, longYear = false } = {}, - ) { - const dateYear = parseInt(stringDate.substring(0, 4)); - const dateMonth = parseInt(stringDate.substring(5, 7), 10) - 1; - const dateDay = parseInt(stringDate.substring(8, 10), 10); - - const monthName = longMonth ? months[dateMonth] : months[dateMonth].substring(0, 3); - const yearName = longYear ? dateYear.toString() : `'${dateYear.toString().substring(2, 4)}`; - - if (showYear) { - if (showDay) { - return `${dateDay} ${monthName} ${yearName}`; - } - - return `${monthName} ${yearName}`; - } - - return `${dateDay} ${monthName}`; - } - - function dateDiffInDays(startDate, endDate) { - return Math.round((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24)); - } - - function isValidDate(dateObject) { - return new Date(dateObject).toString() !== 'Invalid Date'; - } - - function debounce(callback, waitInMs) { - let timeoutId = null; - return (...args) => { - window.clearTimeout(timeoutId); - - timeoutId = window.setTimeout(() => { - callback.apply(null, args); - }, waitInMs); - }; - } - document.addEventListener('DOMContentLoaded', () => { initializeApp(); }); diff --git a/public/js/settings.js b/public/js/settings.js deleted file mode 100644 index d0a942d..0000000 --- a/public/js/settings.js +++ /dev/null @@ -1,250 +0,0 @@ -(() => { - document.addEventListener('app-loaded', () => { - const changeCurrencyForm = document.getElementById('change-currency-form'); - const newCurrencySelect = document.getElementById('new-currency'); - const changeCurrencyButton = document.getElementById('change-currency-button'); - - const importDataButton = document.getElementById('import-button'); - const exportDataButton = document.getElementById('export-button'); - - const changeEmailForm = document.getElementById('change-email-form'); - const newEmailInput = document.getElementById('new-email'); - const changeEmailButton = document.getElementById('change-email-button'); - - const changePasswordForm = document.getElementById('change-password-form'); - const currentPasswordInput = document.getElementById('current-password'); - const newPasswordInput = document.getElementById('new-password'); - const changePasswordButton = document.getElementById('change-password-button'); - - let isUpdating = false; - - async function changeCurrency(event) { - event.preventDefault(); - event.stopPropagation(); - - if (isUpdating) { - return; - } - - isUpdating = true; - window.app.showLoading(); - changeCurrencyButton.textContent = 'Changing...'; - - const currency = newCurrencySelect.value; - - try { - await userbase.updateUser({ - profile: { - currency, - }, - }); - - window.app.showNotification('Currency changed successfully!'); - } catch (error) { - window.app.showNotification(error, 'error'); - } - - isUpdating = false; - window.app.hideLoading(); - changeCurrencyButton.textContent = 'Change currency'; - } - - async function importData() { - const { Swal } = window; - - if (isUpdating) { - return; - } - - const importFileDialogResult = await Swal.fire({ - icon: 'warning', - input: 'file', - title: 'Choose JSON File', - inputAttributes: { - accept: 'text/pain,application/json,.json', - 'aria-label': 'Import your budgets and expenses', - }, - }); - - if (!importFileDialogResult || !importFileDialogResult.value) { - return; - } - - const reader = new FileReader(); - reader.onload = async (fileRead) => { - const importFileContents = fileRead.target.result; - - let importedFileData = {}; - - try { - importedFileData = JSON.parse(importFileContents.toString()); - } catch (_error) { - importedFileData = {}; - } - - if ( - !Object.prototype.hasOwnProperty.call(importedFileData, 'budgets') && - !Object.prototype.hasOwnProperty.call(importedFileData, 'expenses') - ) { - window.app.showNotification( - 'Could not parse the file. Please confirm what you chose is correct.', - 'error', - ); - return; - } - - const budgets = importedFileData.budgets || []; - const expenses = importedFileData.expenses || []; - - const mergeOrReplaceDialogResult = await Swal.fire({ - icon: 'question', - title: 'Merge or Replace?', - text: 'Do you want to merge this with your existing data, or replace it?', - showCancelButton: true, - showDenyButton: true, - confirmButtonText: 'Merge', - denyButtonText: 'Replace', - cancelButtonText: 'Wait, cancel.', - }); - - if ( - mergeOrReplaceDialogResult.isConfirmed || - mergeOrReplaceDialogResult.isDenied - ) { - isUpdating = true; - window.app.showLoading(); - - const success = await window.app.dataUtils.importData( - mergeOrReplaceDialogResult.isDenied, - budgets, - expenses, - ); - - isUpdating = false; - window.app.hideLoading(); - - if (success) { - window.app.showNotification('Data imported successfully!'); - } - } - }; - - reader.readAsText(importFileDialogResult.value); - } - - async function exportData() { - if (isUpdating) { - return; - } - - isUpdating = true; - window.app.showLoading(); - - const fileName = [ - 'budget-zen-data-export-', - new Date().toISOString().substring(0, 19).replace(/:/g, '-'), - '.json', - ] - .join(''); - - const exportData = await window.app.dataUtils.exportAllData(); - - const exportContents = JSON.stringify(exportData, null, 2); - - // Add content-type - const jsonContent = ['data:application/json; charset=utf-8,', exportContents].join(''); - - // Download the file - const data = encodeURI(jsonContent); - const link = document.createElement('a'); - link.setAttribute('href', data); - link.setAttribute('download', fileName); - link.click(); - link.remove(); - - isUpdating = false; - window.app.hideLoading(); - - window.app.showNotification('Data exported successfully!'); - } - - async function changeEmail(event) { - event.preventDefault(); - event.stopPropagation(); - - if (isUpdating) { - return; - } - - isUpdating = true; - window.app.showLoading(); - changeEmailButton.textContent = 'Changing...'; - - const email = newEmailInput.value; - - try { - await userbase.updateUser({ - username: email, - email, - }); - - window.location.reload(); - } catch (error) { - isUpdating = false; - window.app.hideLoading(); - changeEmailButton.textContent = 'Change email'; - window.app.showNotification(error, 'error'); - } - } - - async function changePassword(event) { - event.preventDefault(); - event.stopPropagation(); - - if (isUpdating) { - return; - } - - isUpdating = true; - window.app.showLoading(); - changePasswordButton.textContent = 'Changing...'; - - const currentPassword = currentPasswordInput.value; - const newPassword = newPasswordInput.value; - - try { - await userbase.updateUser({ - currentPassword, - newPassword, - }); - - window.location.reload(); - } catch (error) { - isUpdating = false; - window.app.hideLoading(); - changePasswordButton.textContent = 'Change password / encryption key'; - window.app.showNotification(error, 'error'); - } - } - - async function initializePage() { - await window.app.dataUtils.initializeDb(); - - const userSession = await window.app.getUserSession(); - const currentCurrency = userSession.profile?.currency || '$'; - newCurrencySelect.value = currentCurrency; - } - - if (window.app.isLoggedIn) { - initializePage(); - } - - changeCurrencyForm.addEventListener('submit', changeCurrency); - - importDataButton.addEventListener('click', importData); - exportDataButton.addEventListener('click', exportData); - - changeEmailForm.addEventListener('submit', changeEmail); - changePasswordForm.addEventListener('submit', changePassword); - }); -})(); diff --git a/public/js/stripe.js b/public/js/stripe.js deleted file mode 100644 index 7798f2c..0000000 --- a/public/js/stripe.js +++ /dev/null @@ -1 +0,0 @@ -!function(e){function t(t){for(var n,a,o=t[0],i=t[1],c=0,u=[];c1&&void 0!==arguments[1]?arguments[1]:"absurd";throw new Error(t)},a=n(5),o=n(7),i=n(1),c=n(2),s=n(13),u=n(45),l={AE:"AE",AT:"AT",AU:"AU",BE:"BE",BG:"BG",BR:"BR",CA:"CA",CH:"CH",CI:"CI",CR:"CR",CY:"CY",CZ:"CZ",DE:"DE",DK:"DK",DO:"DO",EE:"EE",ES:"ES",FI:"FI",FR:"FR",GB:"GB",GI:"GI",GR:"GR",GT:"GT",HK:"HK",HR:"HR",HU:"HU",ID:"ID",IE:"IE",IN:"IN",IT:"IT",JP:"JP",LI:"LI",LT:"LT",LU:"LU",LV:"LV",MT:"MT",MX:"MX",MY:"MY",NL:"NL",NO:"NO",NZ:"NZ",PE:"PE",PH:"PH",PL:"PL",PT:"PT",RO:"RO",SE:"SE",SG:"SG",SI:"SI",SK:"SK",SN:"SN",TH:"TH",TT:"TT",US:"US",UY:"UY"},d=Object.keys(l),p=n(29),f=(n(15),function(e,t,n){var r=n.path.reduce((function(e,t,n){return 0===n?t:0===t.indexOf(".")?"".concat(e,'["').concat(t,'"]'):"".concat(e,".").concat(t)}),"");return"undefined"===t?"Missing value for ".concat(n.label,": ").concat(r||"value"," should be ").concat(e,"."):"Invalid value for ".concat(n.label,": ").concat(r||"value"," should be ").concat(e,". You specified: ").concat(t,".")}),m=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return{type:"valid",value:e,warnings:t}},h=function(e){return{error:e,errorType:"full",type:"error"}},_=function(e,t,n){var r=new c.b(f(e,t,n));return h(r)},b=function(e,t,n){return{expected:e,actual:String(t),options:n,errorType:"mismatch",type:"error"}},y=function(e,t){return Object(i.a)(Object(i.a)({},e),{},{path:[].concat(Object(o.a)(e.path),[t])})},v=function(e){return function(t,n){return void 0===t?m(t):e(t,n)}},O=function(e){return function(t,n){return null===t?m(t):e(t,n)}},g=function(e,t){return function(n,r){var a=function(e){var t=e.options.path.join(".")||"value";return{error:"".concat(t," should be ").concat(e.expected),actual:"".concat(t," as ").concat(e.actual)}},o=function(e,t,n){return h(new c.b("Invalid value for ".concat(e,": ").concat(t,". You specified ").concat(n,".")))},i=e(n,r),s=t(n,r);if("error"===i.type&&"error"===s.type){if("mismatch"===i.errorType&&"mismatch"===s.errorType){var u=a(i),l=u.error,d=u.actual,p=a(s),f=p.error,m=p.actual;return o(r.label,l===f?l:"".concat(l," or ").concat(f),d===m?d:"".concat(d," and ").concat(m))}if("mismatch"===i.errorType){var _=a(i),b=_.error,y=_.actual;return o(r.label,b,y)}if("mismatch"===s.errorType){var v=a(s),O=v.error,g=v.actual;return o(r.label,O,g)}return h(i.error)}return"valid"===i.type?i:s}},j=function(e,t){return function(n,r){return n instanceof e?m(n):b("a ".concat(t," instance"),n,r)}},w=function(e,t){return function(n,r){var a=Object(s.a)(e,(function(e){return e===n}));if(void 0===a){var o=t?"a recognized string.":"one of the following strings: ".concat(e.join(", "));return b(o,n,r)}return m(a)}},k=function(e){return function(t,n){return"string"==typeof t&&0===t.indexOf(e)?m(t):b("a string starting with ".concat(e),t,n)}},E=function(e,t){return function(n,r){return"string"==typeof n&&n.length>=e&&n.length<=t?m(n):b(e===t?"a string of ".concat(e," characters"):"a string with ".concat(e," to ").concat(t," characters"),n,r)}},S=function(){for(var e=arguments.length,t=new Array(e),n=0;ne?m(t):b("a number greater than ".concat(e),t,n)}},x=function(e){return function(t,n){return"number"==typeof t&&t===parseInt(t,10)&&(!e||t>=0)?m(t):b(e?"a positive amount in the currency's subunit":"an amount in the currency's subunit",t,n)}},B=function(e,t){return x(!1)(e,t)},L=function(e,t){return x(!0)(e,t)},D=function(e,t){return e&&"object"==typeof e?m(e):b("an object",e,t)},q=function(e){return function(t,n){return Array.isArray(t)?t.map((function(t,r){return e(t,y(n,String(r)))})).reduce((function(e,t){return"error"===e.type?e:"error"===t.type?t:m([].concat(Object(o.a)(e.value),[t.value]),[].concat(Object(o.a)(e.warnings),Object(o.a)(t.warnings)))}),m([])):b("array",t,n)}},F=function(e){return function(t){return function(n,r){if(Array.isArray(n)){var a=t(n,r);if("valid"===a.type)for(var o={},i=0;i-1})):e.indexOf(t)>-1},d=window.location.hash.substring(1).split("?")[0],p=Object(i.I)(Object(i.y)({betas:Object(i.J)(Object(i.b)(i.u.apply(void 0,Object(a.a)(u))),(function(){return[]}))}),Object(o.a)(d),"internal"),f=("valid"===p.type&&p.value.betas,function(e){var t=[],n=[];if(e&&e.forEach((function(e){u.indexOf(e)>-1?t.push(c[e]):n.push(e)})),n.length>0){var r="The following betas are unrecognized for Stripe() parameter:\n\n- ".concat(n.join("\n- "),"\n\n They are either invalid or expired betas, please remove these beta flags to prevent future integration issues.");return{validBetas:t,betaWarning:r}}return{validBetas:t}}),m=(r=[],function(e,t){return l(t,c.stripe_js_beta_locales)||-1===r.indexOf(e)?e:"auto"})},function(e,t,n){"use strict";n.d(t,"a",(function(){return i}));var r=n(31);var a=n(34),o=n(28);function i(e){return function(e){if(Array.isArray(e))return Object(r.a)(e)}(e)||Object(a.a)(e)||Object(o.a)(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(e,t,n){"use strict";n.d(t,"b",(function(){return o})),n.d(t,"c",(function(){return i.a})),n.d(t,"a",(function(){return c})),n.d(t,"d",(function(){return a.a})),n.d(t,"f",(function(){return d})),n.d(t,"e",(function(){return p})),n.d(t,"g",(function(){return f}));var r=n(25),a=n(16),o=function(e){var t={frameborder:"0",allowTransparency:"true",scrolling:"no"},n=!r.f;if(n&&(t.allow="payment *"),"STRIPE_3DS2_CHALLENGE"===e){var o="publickey-credentials-get ".concat(Object(a.a)());t.allow=n?"payment *; ".concat(o):o}if("PAYMENT_REQUEST_GOOGLE_PAY"===e){t.sandbox=["allow-scripts","allow-forms","allow-popups","allow-popups-to-escape-sandbox","allow-same-origin"].join(" "),t.referrerpolicy="origin"}return t},i=n(66),c={ADDRESS_AUTOCOMPLETE:"ADDRESS_AUTOCOMPLETE",CARD_ELEMENT:"CARD_ELEMENT",CONTROLLER:"CONTROLLER",METRICS_CONTROLLER:"METRICS_CONTROLLER",PAYMENT_REQUEST_ELEMENT:"PAYMENT_REQUEST_ELEMENT",PAYMENT_REQUEST_BROWSER:"PAYMENT_REQUEST_BROWSER",PAYMENT_REQUEST_GOOGLE_PAY:"PAYMENT_REQUEST_GOOGLE_PAY",IBAN_ELEMENT:"IBAN_ELEMENT",IDEAL_BANK_ELEMENT:"IDEAL_BANK_ELEMENT",P24_BANK_ELEMENT:"P24_BANK_ELEMENT",AUTHORIZE_WITH_URL:"AUTHORIZE_WITH_URL",STRIPE_3DS2_CHALLENGE:"STRIPE_3DS2_CHALLENGE",STRIPE_3DS2_FINGERPRINT:"STRIPE_3DS2_FINGERPRINT",AU_BANK_ACCOUNT_ELEMENT:"AU_BANK_ACCOUNT_ELEMENT",FPX_BANK_ELEMENT:"FPX_BANK_ELEMENT",LIGHTBOX_APP:"LIGHTBOX_APP",ISSUING_CARD_NUMBER_DISPLAY_ELEMENT:"ISSUING_CARD_NUMBER_DISPLAY_ELEMENT",ISSUING_CARD_COPY_BUTTON_ELEMENT:"ISSUING_CARD_COPY_BUTTON_ELEMENT",ISSUING_CARD_CVC_DISPLAY_ELEMENT:"ISSUING_CARD_CVC_DISPLAY_ELEMENT",ISSUING_CARD_EXPIRY_DISPLAY_ELEMENT:"ISSUING_CARD_EXPIRY_DISPLAY_ELEMENT",ISSUING_CARD_PIN_DISPLAY_ELEMENT:"ISSUING_CARD_PIN_DISPLAY_ELEMENT",EPS_BANK_ELEMENT:"EPS_BANK_ELEMENT",HCAPTCHA_APP:"HCAPTCHA_APP",LINK_LOGIN:"LINK_LOGIN",NETBANKING_BANK_ELEMENT:"NETBANKING_BANK_ELEMENT",AFFIRM_MESSAGE_ELEMENT:"AFFIRM_MESSAGE_ELEMENT",AFFIRM_MESSAGE_MODAL_ELEMENT:"AFFIRM_MESSAGE_MODAL_ELEMENT",AFTERPAY_MESSAGE_MODAL_ELEMENT:"AFTERPAY_MESSAGE_MODAL_ELEMENT",AUTOCOMPLETE_SUGGESTIONS_ELEMENT:"AUTOCOMPLETE_SUGGESTIONS_ELEMENT",ACH_BANK_SEARCH_RESULTS_ELEMENT:"ACH_BANK_SEARCH_RESULTS_ELEMENT",INSTANT_DEBITS_APP:"INSTANT_DEBITS_APP",LINK_AUTHENTICATION_ELEMENT:"LINK_AUTHENTICATION_ELEMENT",PAYMENT_ELEMENT:"PAYMENT_ELEMENT",LINKED_ACCOUNTS_INNER:"LINKED_ACCOUNTS_INNER",WECHAT_PAY_INNER:"WECHAT_PAY_INNER",PAYNOW_INNER:"PAYNOW_INNER",PIX_INNER:"PIX_INNER",PROMPTPAY_INNER:"PROMPTPAY_INNER",SHIPPING_ADDRESS_ELEMENT:"SHIPPING_ADDRESS_ELEMENT",LINK_AUTOFILL_MODAL:"LINK_AUTOFILL_MODAL",LINK_INFO_MODAL:"LINK_INFO_MODAL",GOOGLE_MAPS_APP:"GOOGLE_MAPS_APP",LOADER_UI_APP:"LOADER_UI_APP",CART_ELEMENT:"CART_ELEMENT",BACS_MANDATE_CONFIRMATION_APP:"BACS_MANDATE_CONFIRMATION_APP",BACS_CONFIRMATION_INNER:"BACS_CONFIRMATION_INNER"},s=(n(9),n(23),n(1)),u=(n(0),n(4)),l=n(12),d=function(e){var t,n=e.controllerId,r=e.frameId,a=e.targetOrigin,o=e.type,i=a;if("controller"===o?t=Object(l.m)(r):"group"===o?t=Object(l.m)(n):"outer"===o||"hosted"===o?t=window.frames[r]:"inner"===o&&(i=i||"*",t=window.parent),i=i||u.k,t&&"function"==typeof t.postMessage){var c=e.message.delegate?{targetOrigin:i,delegate:e.message.delegate}:i;t.postMessage(JSON.stringify(Object(s.a)(Object(s.a)({},e),{},{__stripeJsV3:!0})),c)}},p=function(e){try{var t="string"==typeof e?JSON.parse(e):e;return t.__stripeJsV3?t:null}catch(e){return null}},f=function(e){return e}},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";n.d(t,"b",(function(){return o})),n.d(t,"a",(function(){return i})),n.d(t,"g",(function(){return c})),n.d(t,"h",(function(){return s})),n.d(t,"d",(function(){return u})),n.d(t,"e",(function(){return l})),n.d(t,"f",(function(){return d})),n.d(t,"c",(function(){return p}));var r=n(1),a=n(0),o=(n(4),"webauthn"),i="spc",c=function(e,t){switch(e.type){case"object":return{paymentIntent:e.object};case"error":var n=t?{payment_intent:t}:{};return{error:Object(r.a)(Object(r.a)({},n),e.error)};default:return Object(a.a)(e)}},s=function(e,t){switch(e.type){case"error":return{error:Object(r.a)(Object(r.a)({},t?{setup_intent:t}:{}),e.error)};case"object":return{setupIntent:e.object};default:return Object(a.a)(e)}},u=function(e){var t=e.trim().match(/^((seti|pi)_[^_]+)_secret_[^-]+$/);return t?"pi"===t[2]?{id:t[1],clientSecret:t[0],type:"PAYMENT_INTENT"}:{id:t[1],clientSecret:t[0],type:"SETUP_INTENT"}:null},l=function(e){return"payment_intent"===e.object?{id:e.id,clientSecret:e.client_secret,type:"PAYMENT_INTENT"}:{id:e.id,clientSecret:e.client_secret,type:"SETUP_INTENT"}},d=function(e){return"requires_source_action"===e||"requires_action"===e},p=function(e){return"requires_source_action"===e.status||"requires_action"===e.status?e.next_action:null}},function(e,t,n){"use strict";n.d(t,"b",(function(){return i})),n.d(t,"a",(function(){return c})),n.d(t,"c",(function(){return s})),n.d(t,"d",(function(){return u}));var r,a=n(5),o=n(4),i={alipay:"alipay",affirm:"affirm",afterpay_clearpay:"afterpay_clearpay",au_becs_debit:"au_becs_debit",acss_debit:"acss_debit",bacs_debit:"bacs_debit",bancontact:"bancontact",blik:"blik",boleto:"boleto",card:"card",customer_balance:"customer_balance",eps:"eps",fpx:"fpx",giropay:"giropay",grabpay:"grabpay",ideal:"ideal",klarna:"klarna",konbini:"konbini",nz_bank_account:"nz_bank_account",oxxo:"oxxo",p24:"p24",pay_by_bank:"pay_by_bank",paypal:"paypal",sepa_debit:"sepa_debit",sofort:"sofort",three_d_secure:"three_d_secure",upi:"upi",us_bank_account:"us_bank_account",wechat_pay:"wechat_pay",paynow:"paynow",pix:"pix",promptpay:"promptpay",qris:"qris",netbanking:"netbanking",id_bank_transfer:"id_bank_transfer",link:"link",apple_pay:"apple_pay",google_pay:"google_pay"},c=(r={},Object(a.a)(r,o.e.auBankAccount,i.au_becs_debit),Object(a.a)(r,o.e.card,i.card),Object(a.a)(r,o.e.cardNumber,i.card),Object(a.a)(r,o.e.cardExpiry,i.card),Object(a.a)(r,o.e.cardCvc,i.card),Object(a.a)(r,o.e.postalCode,i.card),Object(a.a)(r,o.e.iban,i.sepa_debit),Object(a.a)(r,o.e.idealBank,i.ideal),Object(a.a)(r,o.e.fpxBank,i.fpx),Object(a.a)(r,o.e.p24Bank,i.p24),Object(a.a)(r,o.e.netbankingBank,i.netbanking),Object(a.a)(r,o.e.epsBank,i.eps),r),s=function(e){return-1===o.m.indexOf(e)},u=function(e,t){return null!=t?t:s(e)?null:c[e]||null}},function(e,t,n){"use strict";n.d(t,"a",(function(){return i})),n.d(t,"d",(function(){return d})),n.d(t,"j",(function(){return p})),n.d(t,"b",(function(){return f})),n.d(t,"e",(function(){return u})),n.d(t,"n",(function(){return _})),n.d(t,"l",(function(){return b})),n.d(t,"k",(function(){return v})),n.d(t,"m",(function(){return O})),n.d(t,"c",(function(){return g})),n.d(t,"q",(function(){return j})),n.d(t,"g",(function(){return E})),n.d(t,"h",(function(){return P})),n.d(t,"i",(function(){return A})),n.d(t,"f",(function(){return I})),n.d(t,"p",(function(){return T})),n.d(t,"o",(function(){return N}));var r="1.2em",a="14px",o=function(e){var t=e.split(" ").map((function(e){return parseInt(e.trim(),10)}));return 1===t.length||2===t.length?2*t[0]:3===t.length||4===t.length?t[0]+t[2]:0},i=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:r,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:a,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"0",i=o(n);if("string"==typeof e&&/^[0-9.]+px$/.test(e)){var c=parseFloat(e.toString().replace(/[^0-9.]/g,""));return"".concat(c+i,"px")}var s,u=parseFloat(e.toString().replace(/[^0-9.]/g,"")),l=parseFloat(a.replace(/[^0-9.]/g,"")),d=parseFloat(t.toString().replace(/[^0-9.]/g,""));if("string"==typeof t&&/^(\d+|\d*\.\d+)px$/.test(t))s=d;else if("string"==typeof t&&/^(\d+|\d*\.\d+)em$/.test(t))s=d*l;else if("string"==typeof t&&/^(\d+|\d*\.\d+)%$/.test(t))s=d/100*l;else{if("string"!=typeof t||!/^[\d.]+$/.test(t)&&!/^\d*\.(px|em|%)$/.test(t))return"100%";s=l}var p=u*s+i,f="".concat(p,"px");return/^[0-9.]+px$/.test(f)?f:"100%"},c=n(39),s=n(13),u=function(e,t){return e?window.getComputedStyle(e,t):null},l=function(){return Array.prototype.slice.call(document.querySelectorAll("a[href], area[href], input:not([disabled]),\n select:not([disabled]), textarea:not([disabled]), button:not([disabled]),\n object, embed, *[tabindex], *[contenteditable]")).filter((function(e){var t=e.getAttribute("tabindex"),n=!t||parseInt(t,10)>=0,r=e.getBoundingClientRect(),a=u(e),o=r.width>0&&r.height>0&&a&&"hidden"!==a.getPropertyValue("visibility");return n&&o}))},d=function(e,t){var n=l();return n[Object(s.b)(n,(function(t){return t===e||e.contains(t)}))+("previous"===t?-1:1)]},p=function(e,t){return e.then((function(){return Object(s.f)(t,(function(e){var t=e.element,n=e.tabIndex;""===n?t.removeAttribute("tabindex"):t.setAttribute("tabindex",n)}))}))},f=function(e){var t=[],n=Object(s.f)(document.querySelectorAll("*"),(function(n){var r=n.getAttribute("tabindex")||"";e!==n&&(n.tabIndex=-1),t.push({element:n,tabIndex:r})})),r=Object(c.d)((function(){p(n,t)}));return{lockedPromise:n,lockedElements:t,restoreFocus:r}},m=(n(15),n(20)),h=n(2),_=function(e,t){var n={},r={};e.className.split(/\s+/).forEach((function(e){e&&(n[e]=!0)})),t.forEach((function(e){var t=Object(m.a)(e,2),a=t[0],o=t[1];a.split(/\s+/).forEach((function(e){e&&(r[e]=r[e]||o,n[e]=r[e])}))})),e.className=Object.keys(n).filter((function(e){return n[e]})).join(" ")},b=function(e,t){e.style.cssText=Object.keys(t).map((function(e){return"".concat(e,": ").concat(t[e]," !important;")})).join(" ")},y={border:"none",margin:"0",padding:"0",width:"1px","min-width":"100%",overflow:"hidden",display:"block",visibility:"hidden",position:"fixed",height:"1px","pointer-events":"none","user-select":"none"},v=function(e){b(e,y)},O=function(e){try{return window.parent.frames[e]}catch(e){return null}},g=function(){if(!document.body)throw new h.b("Stripe.js requires that your page has a element.");return document.body},j=function(e){return setTimeout(e,16)},w=function(e,t){return!!e.documentElement&&e.documentElement.contains(t)},k="isConnected"in window.Node.prototype?function(e,t){return t.isConnected&&t.ownerDocument===e}:w,E=function(e,t){return!w(e,t)&&k(e,t)},S=["button","checkbox","file","hidden","image","submit","radio","reset"],P=function(e){var t=e.tagName;if(e.isContentEditable||"TEXTAREA"===t)return!0;if("INPUT"!==t)return!1;var n=e.getAttribute("type");return-1===S.indexOf(n)},A=function(){var e=g(),t=e.style.overflow;e.style.overflow="hidden";var n={passive:!1},r=function(e){return e.preventDefault()},a=function(){};return window.addEventListener("touchmove",a,n),e.addEventListener("touchstart",a,n),e.addEventListener("touchmove",r,n),Object(c.d)((function(){e.style.overflow=t||"",window.removeEventListener("touchmove",a,n),e.removeEventListener("touchstart",a,n),e.removeEventListener("touchmove",r,n)}))},I=function(){var e=document.querySelectorAll("meta[name=viewport][content]"),t=e[e.length-1];return t&&t instanceof HTMLMetaElement?t.content:""},C=function(e){return I().match(e)},T=function(e){C("width=device-width")||e('Elements requires "width=device-width" be set in your page\'s viewport meta tag.\n For more information: https://stripe.com/docs/js/appendix/viewport_meta_requirements')},N=function(e){C("minimum-scale=1")||e('The Financial Connections authentication flow requires "minimum-scale=1" to be set in your page\'s viewport meta tag.')}},function(e,t,n){"use strict";function r(){return(r=Object.assign||function(e){for(var t=1;t=0||(a[n]=e[n]);return a}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return a})),n.d(t,"j",(function(){return i})),n.d(t,"d",(function(){return s})),n.d(t,"c",(function(){return u})),n.d(t,"i",(function(){return l})),n.d(t,"b",(function(){return d})),n.d(t,"h",(function(){return p})),n.d(t,"e",(function(){return m})),n.d(t,"f",(function(){return h})),n.d(t,"g",(function(){return _}));var r=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},a=function(e){var t={};return e.replace(/\+/g," ").split("&").forEach((function(e,n){var a,o=e.split("="),i=decodeURIComponent(o[0]),c=t,s=0,u=i.split("]["),l=u.length-1;if(/\[/.test(u[0])&&/\]$/.test(u[l])?(u[l]=u[l].replace(/\]$/,""),l=(u=u.shift().split("[").concat(u)).length-1):l=0,!(u.indexOf("__proto__")>=0))if(2===o.length)if(a=decodeURIComponent(o[1]),l)for(;s<=l;s++){if(i=""===u[s]?c.length:u[s],!r(c,i)&&c[i])return;c[i]=se.length)&&(t=e.length);for(var n=0,r=new Array(t);n0){var n=500*Math.pow(2,3-s);i=setTimeout(p,n),s-=1}else o(e,l)}}))}(),function(){clearTimeout(i),c=!1}},f=function(e){var t=e.initialDelay,n=e.pollTimeGap,r=e.checkIntent,a=e.locale,u=e.controller,l=e.intent,d=e.expandParam,p=void 0===d?[]:d,f=e.shouldPoll,m=void 0===f?function(){return!0}:f,h="payment_intent"===l.object?{paymentIntent:l}:{setupIntent:l};return new o.a((function(e,o){setTimeout((function(){var t=setInterval((function(){if(!m())return e(h),void clearInterval(t);var n;(n={hosted:!1,intentSecret:Object(i.e)(l),locale:a,expandParam:p},"payment_intent"===l.object?u.action.retrievePaymentIntent(n):u.action.retrieveSetupIntent(n)).then((function(n){h=s(n),n.error?(u.action.localizeError(c.f).then((function(e){return{error:e}})).then(e),clearInterval(t)):r(n.object)&&(e(h),clearInterval(t))}))}),n)}),t-n)}))}},function(e,t,n){"use strict";function r(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";function r(e){if(Array.isArray(e))return e}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";function r(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";function r(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";n.d(t,"b",(function(){return s})),n.d(t,"d",(function(){return u})),n.d(t,"a",(function(){return d})),n.d(t,"c",(function(){return p}));var r,a,o,i=n(5),c=n(4),s=(r={},Object(i.a)(r,c.e.card,{unique:!0,conflict:[c.e.cardNumber,c.e.cardExpiry,c.e.cardCvc,c.e.postalCode],beta:!1,implementation:"legacy"}),Object(i.a)(r,c.e.cardNumber,{unique:!0,conflict:[c.e.card],beta:!1,implementation:"legacy"}),Object(i.a)(r,c.e.cardExpiry,{unique:!0,conflict:[c.e.card],beta:!1,implementation:"legacy"}),Object(i.a)(r,c.e.cardCvc,{unique:!0,conflict:[c.e.card],beta:!1,implementation:"legacy"}),Object(i.a)(r,c.e.postalCode,{unique:!0,conflict:[c.e.card],beta:!1,implementation:"legacy"}),Object(i.a)(r,c.e.paymentRequestButton,{unique:!0,conflict:[],beta:!1,implementation:"legacy"}),Object(i.a)(r,c.e.iban,{unique:!0,conflict:[],beta:!1,implementation:"legacy"}),Object(i.a)(r,c.e.idealBank,{unique:!0,conflict:[],beta:!1,implementation:"legacy"}),Object(i.a)(r,c.e.p24Bank,{unique:!0,conflict:[],beta:!1,implementation:"legacy"}),Object(i.a)(r,c.e.auBankAccount,{unique:!0,beta:!1,conflict:[],implementation:"legacy"}),Object(i.a)(r,c.e.fpxBank,{unique:!0,beta:!1,conflict:[],implementation:"legacy"}),Object(i.a)(r,c.e.netbankingBank,{unique:!0,beta:!0,conflict:[],implementation:"legacy"}),Object(i.a)(r,c.e.issuingCardCopyButton,{unique:!1,beta:!0,conflict:[],implementation:"legacy"}),Object(i.a)(r,c.e.issuingCardNumberDisplay,{unique:!1,beta:!0,conflict:[],implementation:"legacy"}),Object(i.a)(r,c.e.issuingCardCvcDisplay,{unique:!1,beta:!0,conflict:[],implementation:"legacy"}),Object(i.a)(r,c.e.issuingCardExpiryDisplay,{unique:!1,beta:!0,conflict:[],implementation:"legacy"}),Object(i.a)(r,c.e.issuingCardPinDisplay,{unique:!1,beta:!0,conflict:[],implementation:"legacy"}),Object(i.a)(r,c.e.epsBank,{unique:!0,conflict:[],beta:!0,implementation:"legacy"}),Object(i.a)(r,c.e.affirmMessage,{unique:!1,conflict:[],beta:!0,implementation:"affirm_message"}),Object(i.a)(r,c.e.afterpayClearpayMessage,{unique:!1,conflict:[],beta:!1,implementation:"afterpay_message"}),Object(i.a)(r,c.e.linkAuthentication,{unique:!0,conflict:[],beta:!0,implementation:"frame"}),Object(i.a)(r,c.e.payment,{unique:!0,conflict:[],beta:!0,implementation:"frame"}),Object(i.a)(r,c.e.shippingAddress,{unique:!0,conflict:[],beta:!0,implementation:"frame"}),Object(i.a)(r,c.e.cart,{unique:!0,conflict:[],beta:!0,implementation:"cart"}),r),u="__PrivateStripeElement",l=["brand"],d=(a={},Object(i.a)(a,c.e.card,l),Object(i.a)(a,c.e.cardNumber,l),Object(i.a)(a,c.e.iban,["country","bankName"]),Object(i.a)(a,c.e.auBankAccount,["bankName","branchName"]),a),p=(o={},Object(i.a)(o,c.e.idealBank,{secondary:c.e.idealBankSecondary}),Object(i.a)(o,c.e.p24Bank,{secondary:c.e.p24BankSecondary}),Object(i.a)(o,c.e.fpxBank,{secondary:c.e.fpxBankSecondary}),Object(i.a)(o,c.e.netbankingBank,{secondary:c.e.netbankingBankSecondary}),Object(i.a)(o,c.e.epsBank,{secondary:c.e.epsBankSecondary}),o)},function(e,t,n){"use strict";n.d(t,"b",(function(){return o})),n.d(t,"a",(function(){return i})),n.d(t,"d",(function(){return c})),n.d(t,"c",(function(){return s}));var r=n(2),a=n(3),o=function(e){var t={},n={};return function(r){var a="_".concat(r);if("string"==typeof r&&void 0!==t[a])return t[a];if("number"==typeof r&&void 0!==n[a])return n[a];var o=e(r);return"string"==typeof r&&(t[a]=o),"number"==typeof r&&(n[a]=o),o}},i=function(e,t){var n=!1;return function(){if(n)throw new r.b(t);n=!0;try{return e.apply(void 0,arguments).then((function(e){return n=!1,e}),(function(e){throw n=!1,e}))}catch(e){throw n=!1,e}}},c=function(e){var t=e;return function(){t&&(t.apply(void 0,arguments),t=null)}},s=function(e,t){return e.reduce((function(e,n){return e.then((function(e){return"SATISFIED"===e.type?e:n().then((function(e){return t(e)?{type:"SATISFIED",value:e}:{type:"UNSATISFIED"}}))}))}),a.a.resolve({type:"UNSATISFIED"}))}},,function(e,t,n){"use strict";function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";n.d(t,"a",(function(){return g})),n.d(t,"c",(function(){return w})),n.d(t,"b",(function(){return k}));var r=n(10),a=n(60),o=n(61),i=n(65),c=n(3),s=n(22),u=n(8),l=n(62),d=n(33),p=n(25),f=function(e){return"requires_action"!==e.status&&"requires_source_action"!==e.status},m=n(56),h=function(e){return"requires_action"!==e.status&&"requires_source_action"!==e.status},_=n(0),b=n(4),y=n(2),v=n(6),O=function(e){return["id_bank_account","id_bank_transfer"].indexOf(e.bankTransferType)>-1},g=function(e){switch(e.type){case"error":var t=e.error;if("payment_intent_unexpected_state"===t.code&&"object"==typeof t.payment_intent&&null!=t.payment_intent&&"string"==typeof t.payment_intent.status&&Object(r.f)(t.payment_intent.status)){var n=t.payment_intent;return{type:"object",locale:e.locale,object:n}}return e;case"object":return e;default:return Object(_.a)(e)}},j=function(e,t,_,g,j){var w=Object(a.a)(Object(r.c)(t)),k=Object(r.e)(t);if(!w)return c.a.resolve({paymentIntent:t});switch(w.type){case"cardimageverification-challenge":return n.e(7).then(n.bind(null,91)).then((function(n){return(0,n.performCardImageVerification)(w,t,e,_)}));case"captcha-challenge":return Object(l.a)(w,t,e,_);case"3ds1-modal":return Object(o.a)(w,k,b.g.PAYMENT_INTENT,e,_,j);case"3ds2-fingerprint":case"3ds2-challenge":return Object(i.a)(w,{intentSecret:k,intentType:b.g.PAYMENT_INTENT,controller:e,locale:_,hosted:g},j);case"redirect":return Object(m.a)(t,w.redirectUrl,e);case"blik_authorize":return function(e){var t=e.controller,n=e.intent,r=e.locale;return Object(d.d)({controller:t,initialDelay:8e3,pollTimeGap:5e3,intent:n,checkIntent:function(e){return"requires_action"!==e.status||"blik_authorize"!==e.next_action.type},locale:r})}({controller:e,intent:t,locale:_});case"boleto-display":if(void 0===w.hostedVoucherUrl)throw new y.b("Expect `next_action.boleto_display_details.hosted_voucher_url` of `PaymentIntent` to be not undefined. Please refer to \n\nhttps://stripe.com/docs/api/payment_intents/object#payment_intent_object-next_action-boleto_display_details-hosted_voucher_url");return function(e){var t=e.controller,n=e.url,r=e.intent,a=e.locale,o=Object(s.b)(t,{url:Object(u.g)(n),size:"600x700",locale:a,frameTitle:"boleto.voucher_frame_title",useLightboxHostedCloseButton:!1});return new c.a((function(e){o._on("request-close",(function(){Object(s.a)(o).then((function(){e({paymentIntent:r})}))}))}))}({controller:e,locale:_,url:w.hostedVoucherUrl,intent:t});case"konbini-display":if(void 0===w.hostedVoucherUrl)throw new y.b("Expected option `handleActions` to be `false`. The Konbini pilot does not handle the next actions for you automatically yet (e.g. displaying Konbini payment details). Please refer to the Stripe Konbini integration guide for more info: \n\nhttps://stripe.com/docs/payments/konbini");return function(e){var t=e.controller,n=e.url,r=e.intent,a=e.locale,o=Object(s.b)(t,{url:Object(u.g)(n),size:"600x900",locale:a,frameTitle:"konbini.voucher_frame_title",useLightboxHostedCloseButton:!1});return new c.a((function(e){o._on("request-close",(function(){Object(s.a)(o).then((function(){e({paymentIntent:r})}))}))}))}({controller:e,locale:_,url:w.hostedVoucherUrl,intent:t});case"oxxo-display":if(void 0===w.hostedVoucherUrl)throw new y.b("To handle the next actions automatically, set the API version to oxxo_beta=v2. Please refer to the Stripe OXXO integration guide for more info: \n\nhttps://stripe.com/docs/payments/oxxo");return function(e){var t=e.controller,n=e.url,r=e.intent,a=e.locale,o=Object(s.b)(t,{url:Object(u.g)(n),size:"600x700",locale:a,frameTitle:"oxxo.voucher_frame_title",useLightboxHostedCloseButton:!1});return new c.a((function(e){o._on("request-close",(function(){Object(s.a)(o).then((function(){e({paymentIntent:r})}))}))}))}({controller:e,locale:_,url:w.hostedVoucherUrl,intent:t});case"upi_await_notification":return function(e){var t=e.controller,n=e.intentSecret,r=e.intentType,a=e.locale;return new c.a((function(e){setTimeout((function o(){Object(d.e)(n,r,t,a).then((function(t){var n=Object(d.b)(t);if(null!==n)switch(n.status){case"requires_action":return void setTimeout(o,1e4);default:e(t)}}))}),5e3)}))}({controller:e,intentSecret:k,intentType:b.g.PAYMENT_INTENT,locale:_});case"wechat_pay_display_qr_code":return function(e){var t=e.controller,n=e.intent,a=e.locale,o=Object(r.c)(n);if(!o||"wechat_pay_display_qr_code"!==o.type)throw new Error("Expected next_action.wechat_pay_display_qr_code");var i=t.createLightboxFrame({type:u.a.WECHAT_PAY_INNER,options:{qrCodeData:o.wechat_pay_display_qr_code.data,qrCodeUrl:o.wechat_pay_display_qr_code.image_url_png,locale:a}}),l=!1;return new c.a((function(e,r){i._on("load",(function(){i.show(),i.fadeInBackdrop()})),i._once("request-close",(function(){Object(s.a)(i).then((function(){l=!0,e({paymentIntent:n})}))})),Object(d.d)({controller:t,initialDelay:5e3,pollTimeGap:2e3,intent:n,checkIntent:function(e){return"requires_action"!==e.status},shouldPoll:function(){return!l},locale:a}).then((function(t){t.error||i.destroy(!0).then((function(){e(t)}))}))}))}({controller:e,locale:_,intent:t});case"paynow_display_qr_code":return function(e){var t=e.controller,n=e.intent,a=e.intentType,o=e.intentSecret,i=e.locale,l=Object(r.c)(n);if(!l||"paynow_display_qr_code"!==l.type)throw new Error("Expected next_action.paynow_display_qr_code");var p=t.createLightboxFrame({type:u.a.PAYNOW_INNER,options:{qrCodeUrl:l.paynow_display_qr_code.image_url_png,qrCodeData:l.paynow_display_qr_code.data,locale:i}}),f=null;return new c.a((function(e,r){p._on("load",(function(){p.show(),p.fadeInBackdrop()})),p._once("request-close",(function(){Object(s.a)(p).then((function(){f&&clearTimeout(f),e({paymentIntent:n})}))})),p._on("complete",(function(t){Object(s.a)(p).then((function(){f&&clearTimeout(f),e(t)}))})),f=setTimeout((function n(){Object(d.e)(o,a,t,i).then((function(t){var r=Object(d.b)(t);if(null!==r)switch(r.status){case"requires_action":return void(f=setTimeout(n,2e3));default:p.destroy(!0).then((function(){"payment_intent"===r.object?e({paymentIntent:r}):e({setupIntent:r})}))}}))}),5e3)}))}({controller:e,locale:_,intent:t,intentSecret:k,intentType:b.g.PAYMENT_INTENT});case"pix_display_qr_code":if(void 0===w.hostedInstructionsUrl)throw new y.b("Expect `next_action.pix_display_qr_code.hosted_instructions_url` of `PaymentIntent` to be not undefined. Please refer to \n\nhttps://stripe.com/docs/api/payment_intents/object#payment_intent_object-next_action-pix_display_qr_code-hosted_instructions_url");return function(e){var t=e.controller,n=e.intent,r=e.intentSecret,a=e.intentType,o=e.locale,i=e.url,l=Object(s.b)(t,{url:Object(u.g)(i),size:"450x600",locale:o,frameTitle:"pix.instructions_frame_title",useLightboxHostedCloseButton:!1}),p=null;return new c.a((function(e,i){l._on("load",(function(){l.show(),l.fadeInBackdrop()})),l._once("request-close",(function(){Object(s.a)(l).then((function(){p&&clearTimeout(p),e({paymentIntent:n})}))})),l._on("complete",(function(t){Object(s.a)(l).then((function(){p&&clearTimeout(p),e(t)}))})),p=setTimeout((function n(){Object(d.e)(r,a,t,o).then((function(t){var r=Object(d.b)(t);if(r)switch(r.status){case"requires_action":return void(p=setTimeout(n,2e3));default:l.destroy(!0).then((function(){"payment_intent"===r.object?e({paymentIntent:r}):e({setupIntent:r})}))}}))}),5e3)}))}({controller:e,locale:_,url:w.hostedInstructionsUrl,intent:t,intentSecret:k,intentType:b.g.PAYMENT_INTENT});case"promptpay_display_qr_code":return function(e){var t,n=e.controller,r=e.intent,a=e.locale,o=e.url,i=Object(s.b)(n,{url:Object(u.g)(o),size:(t=p.h,t?"fullScreen":"400x600"),locale:a,frameTitle:"hosted_qr_code_instructions.promptpay.frame_title",useLightboxHostedCloseButton:!1}),l=!1;return new c.a((function(e){return i._on("load",(function(){i.show(),i.fadeInBackdrop()})),i._once("request-close",(function(){Object(s.a)(i).then((function(){l=!0,e({paymentIntent:r})}))})),i._on("complete",(function(t){Object(s.a)(i).then((function(){l=!0,e(t)}))})),Object(d.d)({controller:n,initialDelay:5e3,pollTimeGap:2e3,intent:r,checkIntent:f,shouldPoll:function(){return!l},locale:a}).then((function(t){t.error||l||i.destroy(!0).then((function(){e(t)}))}))}))}({controller:e,locale:_,intent:t,intentSecret:k,url:w.hostedInstructionsUrl,intentType:b.g.PAYMENT_INTENT});case"display_bank_transfer_instructions":return function(e,t){return!!O(e)&&(Object(v.d)(t||[],v.a.id_bank_transfer_beta_2)||Object(v.d)(t||[],v.a.customer_balance_beta_1))}(w,e._betas)?Object(m.a)(t,w.hostedInstructionsUrl,e):function(e){return!O(e)}(w)?function(e){var t=e.controller,n=e.url,r=e.intent,a=e.locale,o=Object(s.b)(t,{url:Object(u.g)(n),size:"600x700",locale:a,frameTitle:"display_bank_transfer_instructions.voucher_frame_title",useLightboxHostedCloseButton:!1});return new c.a((function(e){o._on("request-close",(function(){Object(s.a)(o).then((function(){e({paymentIntent:r})}))}))}))}({controller:e,url:w.hostedInstructionsUrl,intent:t,locale:_}):c.a.resolve({paymentIntent:t});case"qris_display_qr_code":return function(e){var t=e.controller,n=e.intent,r=e.locale,a=e.url,o=Object(s.b)(t,{url:Object(u.g)(a),size:p.h?"fullScreen":"400x600",locale:r,frameTitle:"hosted_qr_code_instructions.qris.frame_title",useLightboxHostedCloseButton:!1}),i=!1;return new c.a((function(e){return o._on("load",(function(){o.show(),o.fadeInBackdrop()})),o._once("request-close",(function(){Object(s.a)(o).then((function(){i=!0,e({paymentIntent:n})}))})),o._on("complete",(function(t){Object(s.a)(o).then((function(){i=!0,e(t)}))})),Object(d.d)({controller:t,initialDelay:5e3,pollTimeGap:2e3,intent:n,checkIntent:h,shouldPoll:function(){return!i},locale:r}).then((function(t){"error"in t&&t.error||i||o.destroy(!0).then((function(){e(t)}))}))}))}({controller:e,locale:_,intent:t,intentSecret:k,url:w.hostedInstructionsUrl,intentType:b.g.PAYMENT_INTENT});default:return c.a.resolve({paymentIntent:t})}},w=function e(t,n,r,a,o){var i=arguments.length>5&&void 0!==arguments[5]?arguments[5]:0;if(b.i1)for(var n=1;n0&&void 0!==arguments[0]?arguments[0]:{};if((null==r||null===(e=r.allowedCardBrands)||void 0===e?void 0:e.length)&&(null==r||null===(t=r.disallowedCardBrands)||void 0===t?void 0:t.length))throw new c.b("You cannot specify both disallowedCardBrands and allowedCardBrands. Please specify only one of those parameters.");if((null==r||null===(n=r.disallowedCardBrands)||void 0===n?void 0:n.length)===a.a.length)throw new c.b("You cannot block all available card brands.")}},function(e,t,n){"use strict";(function(t){function n(e){a.length||(r(),!0),a[a.length]=e}e.exports=n;var r,a=[],o=0;function i(){for(;o1024){for(var t=0,n=a.length-o;t=82||4430===t&&n>=11||t>=4431)}()||function(){var e=/iPad|iPhone/i.test(window.navigator.userAgent),t=/^((?!chrome|android).)*safari/i.test(window.navigator.userAgent)&&!/SamsungBrowser/.test(window.navigator.userAgent);if(!e||t)return!1;var n=window.navigator.userAgent.match(/OS (\d+)_(\d+)(_\d+)? like Mac OS X/)||[],r=parseInt(n[1],10),a=parseInt(n[2],10);return!isNaN(r)&&!isNaN(a)&&(15===r&&a>=4||r>15)}())return a.a.resolve(!1);var e=window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable(),t=new a.a((function(e){return setTimeout((function(){return e(!1)}),500)}));return a.a.race([e,t]).catch((function(){return!1}))},j=function(){if(void 0===window.PaymentRequest)return a.a.resolve(!1);if(!/Chrome\/(9[5-9]|[1-9]\d\d)/.test(window.navigator.userAgent))return a.a.resolve(!1);try{var e=[{supportedMethods:"secure-payment-confirmation",data:{action:"authenticate",credentialIds:[new Uint8Array(1)],challenge:new Uint8Array(1),fallbackUrl:window.location,rpId:"stripe.com",payeeOrigin:"https://stripe.com",instrument:{displayName:"Mock ····1234",icon:'data:image/svg+xml;utf8,'}}}];return new window.PaymentRequest(e,{total:{label:"Total",amount:{currency:"USD",value:"0"}}}).canMakePayment().catch((function(){return!1}))}catch(e){return a.a.resolve(!1)}},w="stripe-js-one-click-authn",k="W",E="S",S="SE/WA",P=function(e){return btoa(String.fromCharCode.apply(null,new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")},A=function(e){return atob(e.replace(/-/g,"+").replace(/_/g,"/"))},I=function(e){var t=A(e);return Uint8Array.from(t,(function(e){return e.charCodeAt(0)}))},C=(n(68),n(69),n(70),function(e){return"data:image/svg+xml,".concat(encodeURIComponent(e.replace(/\n/g,"").replace(/\s+/g," ")))}),T=function(e){switch(e){case"visa":return C('\n \n \n \n \n');case"amex":return C('\n \n \n \n \n \n \n \n \n \n');case"mastercard":return C('\n \n \n \n \n \n \n');case"unionpay":case"discover":case"jcb":case"diners":case"unknown":case"elo":return C('');default:return Object(o.a)(e)}},N=n(10),M=function(e,t,n){var r=e.threeDS2Source,o=e.oneClickAuthn,i=t.controller,s=n.deviceSupport,u=n.startTimestamp;if(!o)return a.a.resolve(null);var l=o.credentials.filter((function(e){return e.type===N.a}));if(0===l.length)return i.report("one_click_authn.request_spc_authn.empty_credentials_list",{client_id:w,source:r,device_support:s}),a.a.resolve(null);try{var d=o.merchant.origin;if(!d)return i.report("one_click_authn.request_spc_authn.empty_merchant_origin",{client_id:w,source:r,device_support:s}),a.a.resolve(null);var p=new window.PaymentRequest(function(e,t,n){var r=n.authenticationChallenge,a=n.instrument,o=a.cardBrand,i=a.cardName,c=a.cardLast4,s=n.merchant;return[{supportedMethods:"secure-payment-confirmation",data:{action:"authenticate",rpId:"stripe.com",credentialIds:e.map((function(e){return I(e.id)})),challenge:I(r),timeout:6e4,fallbackUrl:window.location.toString(),instrument:{displayName:"".concat(i," ····").concat(c),icon:T(o)},payeeOrigin:t,payeeName:s.name}}]}(l,d,o),{total:{label:"Total",amount:o.amount}});return i.report("one_click_authn.request_spc_authn.prompted",{client_id:w,source:r,timeToComplete:u.getElapsedTime(),device_support:s}),p.show().then((function(e){var t;return e.complete("success"),i.report("one_click_authn.request_spc_authn.completed",{client_id:w,source:r,timeToComplete:u.getElapsedTime(),device_support:s}),{type:N.a,assertion:(t=e.details,{type:"public-key",id:t.id,raw_id:t.id,response:{authenticator_data:P(t.response.authenticatorData),client_data_json:P(t.response.clientDataJSON),signature:P(t.response.signature)}}),payment_data:{merchant_data:{merchant_origin:d,total:o.amount},network_data:o.authenticationChallenge}}})).catch((function(e){var t={AbortError:"request_aborted",InvalidStateError:"payment_already_shown",NotSupportedError:"payment_method_not_supported",SecurityError:"security_error"}[e.name]||"unexpected_error";return i.report("one_click_authn.request_spc_authn.error",{reason:t,client_id:w,source:r,timeToError:u.getElapsedTime(),device_support:s,error:Object(c.a)({name:e.name,message:e.message},e)}),null}))}catch(e){i.report("one_click_authn.request_spc_authn.error",{client_id:w,reason:"unexpected_error",source:r,timeToError:u.getElapsedTime(),device_support:s,error:Object(c.a)({name:e.name,message:e.message},e)})}return a.a.resolve(null)},R=function(e,t,n){var r=t.controller,o=n.deviceSupport,i=n.challengeFrame,c=n.startTimestamp,s=e.oneClickAuthn;if(!s)return a.a.resolve(null);var l=function(e){var t=e.spcEligible,n=e.configurationType;return t&&(n===E||n===S)}(o)?N.a:N.b,d=s.credentials.filter((function(e){return e.type===l}));return 0===d.length?(r.report("one_click_authn.request_webauthn_authn.empty_credentials_list",{client_id:w,source:e.threeDS2Source,device_support:o}),a.a.resolve(null)):new a.a((function(t,n){i.then((function(r){var a=function(){return n(new Error("User canceled"))};r._once("cancel",a),r.isVisible||(r.show(),r.fadeInBackdrop());var i={amount:s.amount,instrument:s.instrument,merchant:s.merchant,authenticationChallenge:s.authenticationChallenge,layout:s.layout,allowCredentials:d};return r.action.performOneClickWebauthnAuthentication({threeDS2Source:e.threeDS2Source,cardBrand:e.cardBrand,appUrl:Object(u.d)("one-click-webauthn-authentication-112decb7ef95cfbe08e7924e5e140074.html"),deviceSupport:o,payload:i,startPosixTime:c.getAsPosixTime()}).then((function(e){r._off("cancel",a),t(e)}))}))}))},x=function(e,t){var n=e.threeDS2Source,r=e.oneClickAuthn,a=t.controller;if(!r)return null;var o=O.j?"safari":O.f?"firefox":O.c?O.a?"chrome_android":"chrome":O.e||O.d?"edge":null;if(!o)return a.report("one_click_authn.configuration.error",{client_id:w,reason:"browser_not_found",source:n}),null;try{switch(new URLSearchParams(A(r.configuration)).get(o)){case k:return k;case E:return E;case S:return S;default:return null}}catch(e){return a.report("one_click_authn.configuration.error",{client_id:w,reason:"unexpected_error",source:n,error:Object(c.a)({name:e.name,message:e.message},e)}),null}},B=function(){try{return 0==="https://js.stripe.com/v3/".indexOf(window.top.location.origin)}catch(e){return!1}},L=function(){var e=document.featurePolicy;if(!e)return!1;try{return-1!==e.allowedFeatures().indexOf("publickey-credentials-get")}catch(e){return!1}},D=function(e,t){return a.a.all([j(),g()]).then((function(n){var a=Object(r.a)(n,2),o=a[0],i=a[1];return{sameOriginFrame:B(),spcEligible:o,webauthnEligible:i,publickeyCredentialsGetAllowed:L(),configurationType:x(e,t)}}))},q=function(e,t,n){var r=n.challengeFrame,a=n.startTimestamp;return D(e,t).then((function(n){return i=(o=n).webauthnEligible,c=o.configurationType,!i||c!==k&&c!==S?function(e){var t=e.spcEligible,n=e.configurationType;return t&&n===E}(n)?M(e,t,{deviceSupport:n,startTimestamp:a}).then((function(e){return{deviceSupport:n,authenticationAPIParam:e}})):{deviceSupport:n,authenticationAPIParam:null}:R(e,t,{deviceSupport:n,challengeFrame:r,startTimestamp:a}).then((function(e){return{deviceSupport:n,authenticationAPIParam:e}}));var o,i,c}))},F=function(e,t,n){var c=new i.a,s=l(e,t);switch(e.type){case"3ds2-challenge":return D(e,t).then((function(r){return d(e,0,{oneClickAuthnDeviceSupport:r,challengeFrame:s}).then((function(){return b(t,{intent:h(0,t,n),challengeFrame:s,startTimestamp:c})}),(function(){return b(t,{intent:_(e,t),challengeFrame:s,startTimestamp:c})}))}));case"3ds2-fingerprint":return a.a.all([v(e,t),q(e,t,{challengeFrame:s,startTimestamp:c})]).then((function(n){var o=Object(r.a)(n,2),i=o[0],c=o[1];return function(e,t,n){var r=n.fingerprintResult,a=n.oneClickAuthn,o=t.controller,i=t.hosted,c=t.intentSecret;return o.report("3ds2.authenticate",{hosted:i,intentId:c.id}),o.action.authenticate3DS2({threeDS2Source:e.threeDS2Source,outerWindowWidth:window.innerWidth,hosted:i,fingerprintResult:r,oneClickAuthnDeviceSupportAPIParam:{hosted:i,same_origin_frame:a.deviceSupport.sameOriginFrame,spc_eligible:a.deviceSupport.spcEligible,webauthn_eligible:a.deviceSupport.webauthnEligible,publickey_credentials_get_allowed:a.deviceSupport.publickeyCredentialsGetAllowed},oneClickAuthnAuthenticationAPIParam:a.authenticationAPIParam,publishableKey:e.publishableKey}).then((function(e){return"error"===e.type?o.report("3ds2.authenticate.error",{error:e.error,hosted:i,intentId:c.id}):o.report("3ds2.authenticate.success",{hosted:i,intentId:c.id}),e}))}(e,t,{fingerprintResult:i,oneClickAuthn:c}).then((function(n){return function(e,t,n){var r=n.authenticateResponse,o=n.oneClickAuthnDeviceSupport,i=n.challengeFrame,c=t.controller,s=t.hosted,u=t.intentSecret;if("error"===r.type)return a.a.resolve();var l=r.object,p=l.state,f=l.ares,m=l.creq;return"delegated"===p||null===f?a.a.resolve():"C"!==f.transStatus||null==m?(c.report("3ds2.frictionless",{hosted:s,intentId:u.id}),a.a.resolve()):d({type:"3ds2-challenge",threeDS2Source:e.threeDS2Source,cardBrand:e.cardBrand,transactionId:e.transactionId,acsUrl:f.acsURL,acsTransactionId:f.acsTransID,optimizations:e.optimizations,oneClickAuthn:e.oneClickAuthn,creq:m,publishableKey:e.publishableKey},0,{oneClickAuthnDeviceSupport:o,challengeFrame:i})}(e,t,{authenticateResponse:n,oneClickAuthnDeviceSupport:c.deviceSupport,challengeFrame:s})}))})).then((function(){return b(t,{intent:h(0,t,n),challengeFrame:s,startTimestamp:c})}),(function(){return b(t,{intent:_(e,t),challengeFrame:s,startTimestamp:c})}));default:return Object(o.a)(e)}}},function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return o}));var r=n(0),a=n(16),o=function(t){switch(t){case"ADDRESS_AUTOCOMPLETE":return Object(a.a)("checkout-inner-address-autocomplete-bebe72253eeb9b8dffd8d048a7fc5eb8.html");case"CARD_ELEMENT":return Object(a.a)("elements-inner-card-b54aca11d9705c95df51bafbacac9139.html");case"CONTROLLER":return Object(a.a)("controller-0d71f6aea26d3bc048d4f2547af0cf23.html");case"METRICS_CONTROLLER":return Object(a.a)("m-outer-6262077c14f753400d607dc30e70f1af.html");case"PAYMENT_REQUEST_ELEMENT":return Object(a.a)("elements-inner-payment-request-bedc699b26f8949c2d098f7712a2b16f.html");case"PAYMENT_REQUEST_BROWSER":return Object(a.a)("payment-request-inner-browser-9b48e20e81239ad4a2323c4262a4cc9d.html");case"PAYMENT_REQUEST_GOOGLE_PAY":return Object(a.a)("payment-request-inner-google-pay-dc0bfcab75ba4e8c06d95765fcf29361.html");case"IBAN_ELEMENT":return Object(a.a)("elements-inner-iban-5db20e4bbf9834e974ee7a844535c31b.html");case"IDEAL_BANK_ELEMENT":return Object(a.a)("elements-inner-ideal-bank-5edcc0a4d48f6b51bc51e432a2de3192.html");case"P24_BANK_ELEMENT":return Object(a.a)("elements-inner-p24-bank-0faf4f1683d3b80060a8ddf116a54e23.html");case"AUTHORIZE_WITH_URL":return Object(a.a)("authorize-with-url-inner-e356f6f5a0ae1626de7ac0571c7f44b1.html");case"STRIPE_3DS2_CHALLENGE":return Object(a.a)("three-ds-2-challenge-26ba49a6542c78ba002e5f7c0c25647b.html");case"STRIPE_3DS2_FINGERPRINT":return Object(a.a)("three-ds-2-fingerprint-17d1291c86bacb9a59bf661cf94c7d3c.html");case"AU_BANK_ACCOUNT_ELEMENT":return Object(a.a)("elements-inner-au-bank-account-ccefe3871fbd3271c613c473a8a1fae3.html");case"FPX_BANK_ELEMENT":return Object(a.a)("elements-inner-fpx-bank-628c5a1199a61841b27ca95de45ec8bf.html");case"LIGHTBOX_APP":return Object(a.a)("lightbox-inner-d28485d0256a05386dbefca9f3634abf.html");case"ISSUING_CARD_NUMBER_DISPLAY_ELEMENT":return Object(a.a)("elements-inner-issuing-card-number-display-0b2f3a9b740c6dad18ea7b976ec9efa5.html");case"ISSUING_CARD_COPY_BUTTON_ELEMENT":return Object(a.a)("elements-inner-issuing-card-copy-button-70be48d6bfc4f6f71b777c76b0f9ceb1.html");case"ISSUING_CARD_CVC_DISPLAY_ELEMENT":return Object(a.a)("elements-inner-issuing-card-cvc-display-10a94e5ed04153df763a4365c95481d4.html");case"ISSUING_CARD_EXPIRY_DISPLAY_ELEMENT":return Object(a.a)("elements-inner-issuing-card-expiry-display-63e9ef233a798a95516ddf3149026051.html");case"ISSUING_CARD_PIN_DISPLAY_ELEMENT":return Object(a.a)("elements-inner-issuing-card-pin-display-8101e8d254b62bbdcb9f8f9fd1cbc9f6.html");case"EPS_BANK_ELEMENT":return Object(a.a)("elements-inner-eps-bank-e00f58994f40a34c021d28f946de891c.html");case"HCAPTCHA_APP":return Object(a.a)("hcaptcha-inner-ab097c8938601edcd00a6ccb0bc78c68.html");case"NETBANKING_BANK_ELEMENT":return Object(a.a)("elements-inner-netbanking-bank-593e5a5d16212176cf19e62d2862605e.html");case"AFFIRM_MESSAGE_ELEMENT":return Object(a.a)("elements-inner-affirm-message-75ec47ef2d77af26c63732e9c0499033.html");case"AFFIRM_MESSAGE_MODAL_ELEMENT":return Object(a.a)("elements-inner-affirm-message-modal-de0e69a427bacbda09eeb6ce6df18672.html");case"AFTERPAY_MESSAGE_MODAL_ELEMENT":return Object(a.a)("elements-inner-afterpay-message-modal-4ced4f904892477964979de90ad4ab60.html");case"INSTANT_DEBITS_APP":return Object(a.a)("instant-debits-app-4639be63fea30e0ee4cfb857506005da.html");case"LINK_AUTHENTICATION_ELEMENT":return Object(a.a)("elements-inner-authentication-ad661929290dc34e196308f0f05c7b1c.html");case"PAYMENT_ELEMENT":return Object(a.a)("elements-inner-payment-c61927b876fe950fd9bc18c7ec09c84a.html");case"LINKED_ACCOUNTS_INNER":return Object(a.a)("linked-accounts-inner-426f7ec862e2e4cad070ba813e1280b9.html");case"WECHAT_PAY_INNER":return Object(a.a)("wechat-pay-inner-c99528be9b946f045e464d98ebd01419.html");case"PAYNOW_INNER":return Object(a.a)("paynow-inner-58d147d490a8c2f94a072437fab3819a.html");case"PIX_INNER":return Object(a.a)(e.env.PIX_INNER_HTML_NAME);case"PROMPTPAY_INNER":return Object(a.a)(e.env.PROMPTPAY_INNER_HTML_NAME);case"SHIPPING_ADDRESS_ELEMENT":return Object(a.a)("elements-inner-shipping-address-f5115c9f7a580797ec225071ffd46e9b.html");case"LINK_AUTOFILL_MODAL":return Object(a.a)("link-autofill-modal-inner-0ff832b966ba80b7bf307cc7c0e1336a.html");case"GOOGLE_MAPS_APP":return Object(a.a)("google-maps-inner-961f0fc5abdc7099717a23884de273f6.html");case"AUTOCOMPLETE_SUGGESTIONS_ELEMENT":return Object(a.a)("elements-inner-autocomplete-suggestions-d9079ddf6611e7bea30800a66cf9d70f.html");case"ACH_BANK_SEARCH_RESULTS_ELEMENT":return Object(a.a)("elements-inner-ach-bank-search-results-5afd2b6fc97fe0373ad6a5bb1ff838bf.html");case"LINK_INFO_MODAL":return Object(a.a)("elements-inner-link-info-modal-1d956cd71290f3300cc952d8cf41f2c9.html");case"LOADER_UI_APP":return Object(a.a)("elements-inner-loader-ui-fffe4f738905b19a332ef79c95b528d7.html");case"CART_ELEMENT":return Object(a.a)("elements-inner-cart-bcb1da70255e5767f76b4d2a0f4b19bf.html");case"BACS_MANDATE_CONFIRMATION_APP":return Object(a.a)("bacs-mandate-confirmation-inner-cb7e6763e84b39bee786f69327492fa9.html");case"BACS_CONFIRMATION_INNER":return Object(a.a)(e.env.BACS_CONFIRMATION_INNER);case"LINK_LOGIN":return Object(a.a)("link-login-inner-f02c5eba95d563f4ab1cd31d7c0b389c.html");default:return Object(r.a)(t)}}}).call(this,n(49))},function(e,t){e.exports=function(e){var t=e.split("").map((function(e){return e.charCodeAt(0)})).reduce((function(e,t){return(e<<5)-e+t&(e<<5)-e+t}),0).toString();return"_".concat(t.replace(/[-.]/g,"_"))}},function(e,t,n){e.exports=n.p+"fingerprinted/img/visa-0daded1e4b9a21ae5304a6794bb9e46a.svg"},function(e,t,n){e.exports=n.p+"fingerprinted/img/amex-3440dd14f9308959e71dfef65267235f.svg"},function(e,t,n){e.exports=n.p+"fingerprinted/img/mastercard-4868931ddf88ab0fc551d18a1a859ff7.svg"},function(e,t,n){"use strict";(function(e){n.d(t,"a",(function(){return u}));var r=n(1),a=n(14),o=n(73),i=n(43),c=n(13),s=function(t,n){var r=n;return Boolean(e.env.STRIPE_JS_COMPILE_DEVAPP)&&window.__STRIPE_CHECKOUT_URL_OVERRIDE__&&(r=n.replace(/^https?:\/\/[^/]+\//,window.__STRIPE_CHECKOUT_URL_OVERRIDE__)),Object(i.a)(r).then((function(e){return Object(i.b)(t,"redirectToCheckout",e),{error:e.error}}))},u=function(e,t,n,i,u){var l=Object(o.a)(t,i,u,e.keyMode());if(e.report("redirect_to_checkout.options",{betas:t,options:Object(c.h)(l,["mode","sessionId"]),globalLocale:i}),"session"===l.tag){var d=l.sessionId;return e.action.createPaymentPageWithSession({betas:t,mids:n(),sessionId:d}).then((function(t){if("error"===t.type)return{error:t.error};var n=t.object.url;return s(e,n)}))}var p=l,f=(p.tag,p.items),m=p.lineItems,h=p.mode,_=p.successUrl,b=p.cancelUrl,y=p.clientReferenceId,v=p.customerEmail,O=p.billingAddressCollection,g=p.submitType,j=p.allowIncompleteSubscriptions,w=p.shippingAddressCollection,k=Object(a.a)(p,["tag","items","lineItems","mode","successUrl","cancelUrl","clientReferenceId","customerEmail","billingAddressCollection","submitType","allowIncompleteSubscriptions","shippingAddressCollection"]),E=[];if(m&&f)throw new Error("Only one of items, lineItems can be passed in.");if(m){if(!h)throw new Error("Expected `mode`");E=m.map((function(e){if(e.price)return{type:"price",id:e.price,quantity:e.quantity};throw new Error("Unexpected item shape.")}))}else{if(!f)throw new Error("An items field must be passed in.");E=f.map((function(e){if("sku"in e)return{type:"sku",id:e.sku,quantity:e.quantity};if(e.plan)return{type:"plan",id:e.plan,quantity:e.quantity};throw new Error("Unexpected item shape.")}))}return e.action.createPaymentPage(Object(r.a)({betas:t,mids:n(),items:E,mode:h,success_url:_,cancel_url:b,client_reference_id:y,customer_email:v,billing_address_collection:O,submit_type:g,allow_incomplete_subscriptions:j,shipping_address_collection:w&&{allowed_countries:w.allowedCountries}},k)).then((function(t){if("error"===t.type)return{error:t.error};var n=t.object.url;return s(e,n)}))}}).call(this,n(49))},,function(e,t,n){"use strict";var r=n(14),a=n(1),o=n(7),i={bg:"bg",cs:"cs",da:"da",de:"de",el:"el",en:"en","en-GB":"en-GB",es:"es","es-419":"es-419",et:"et",fi:"fi",fil:"fil",fr:"fr","fr-CA":"fr-CA",hr:"hr",hu:"hu",id:"id",it:"it",ja:"ja",ko:"ko",lt:"lt",lv:"lv",ms:"ms",mt:"mt",nb:"nb",nl:"nl",pl:"pl",pt:"pt","pt-BR":"pt-BR",ro:"ro",ru:"ru",sk:"sk",sl:"sl",sv:"sv",th:"th",tr:"tr",vi:"vi",zh:"zh","zh-HK":"zh-HK","zh-TW":"zh-TW"},c={"pt-PT":"pt-PT"},s=Object.keys(i),u=Object.keys(c),l=n(63),d=n(0),p=n(6),f=n(2),m=n(15),h=n(13),_={sku:Object(d.w)(d.B),plan:Object(d.w)(d.B),clientReferenceId:Object(d.w)(d.B),locale:Object(d.w)(d.u.apply(void 0,["auto"].concat(Object(o.a)(s)))),customerEmail:Object(d.w)(d.B),billingAddressCollection:Object(d.w)(Object(d.u)("required","auto")),submitType:Object(d.w)(Object(d.u)("auto","pay","book","donate")),allowIncompleteSubscriptions:Object(d.w)(d.e),shippingAddressCollection:Object(d.w)(Object(d.h)({allowedCountries:Object(d.b)(d.B)}))},b=/cs_(test|live)_.+/,y=function(e,t){var n=Object(d.h)(Object(a.a)(Object(a.a)({},_),{},{items:Object(d.w)(Object(d.x)(Object(d.b)(Object(d.h)({type:Object(d.u)("plan"),quantity:Object(d.s)(0),id:d.B})),Object(d.b)(Object(d.h)({type:Object(d.u)("sku"),quantity:Object(d.s)(0),id:d.B})))),successUrl:d.B,cancelUrl:d.B})),o=Object(d.H)(n,t,"stripe.redirectToCheckout").value,i=o.sku,c=o.plan,s=o.items,u=Object(r.a)(o,["sku","plan","items"]),l=function(e,t,n){if(e&&t||(e||t)&&n)throw new f.b("stripe.redirectToCheckout: Expected only one of sku, plan, or items.");if("string"==typeof e)return[{sku:e,quantity:1}];if("string"==typeof t)return[{plan:t,quantity:1}];if(n)return n.map((function(e){return"sku"===e.type?{sku:e.id,quantity:e.quantity}:{plan:e.id,quantity:e.quantity}}));throw new f.b("stripe.redirectToCheckout: You must provide either sku, plan, or items.")}(i,c,s);return Object(a.a)({tag:"no-session",items:l},u)},v=function(e,t,n){var i=Object(d.h)(Object(a.a)(Object(a.a)({},_),{},{sessionId:Object(d.w)(d.B),successUrl:Object(d.w)(d.B),cancelUrl:Object(d.w)(d.B),mode:Object(d.w)(Object(d.u)("subscription","payment")),items:Object(d.w)(Object(d.x)(Object(d.b)(Object(d.h)({quantity:Object(d.s)(0),plan:d.B})),Object(d.b)(Object(d.h)({quantity:Object(d.s)(0),sku:d.B})))),lineItems:Object(d.w)(Object(d.b)(Object(d.h)({quantity:Object(d.s)(0),price:d.B})))},-1!==e.indexOf("checkout_beta_locales")?{locale:Object(d.w)(d.u.apply(void 0,["auto"].concat(Object(o.a)(s),Object(o.a)(u))))}:{})),c=Object(d.H)(i,t,"stripe.redirectToCheckout").value;if(c.sessionId){var l=c.sessionId;if(Object.keys(c).length>1)throw new f.b("stripe.redirectToCheckout: Do not provide other parameters when providing sessionId. Specify all parameters on your server when creating the CheckoutSession.");if(!/^cs_/.test(l))throw new f.b("stripe.redirectToCheckout: Invalid value for sessionId. You specified '".concat(l,"'."));if("live"===n&&/^cs_test_/.test(l))throw new f.b("stripe.redirectToCheckout: the provided sessionId is for a test mode Checkout Session, whereas Stripe.js was initialized with a live mode publishable key.");if("test"===n&&/^cs_live_/.test(l))throw new f.b("stripe.redirectToCheckout: the provided sessionId is for a live mode Checkout Session, whereas Stripe.js was initialized with a test mode publishable key.");return{tag:"session",sessionId:l}}c.sessionId,c.sku,c.plan;var p=c.items,m=c.lineItems,h=c.successUrl,b=c.cancelUrl,y=c.mode,v=Object(r.a)(c,["sessionId","sku","plan","items","lineItems","successUrl","cancelUrl","mode"]);if(!m&&!p)throw new f.b("stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId.");if(!h||!b)throw new f.b("stripe.redirectToCheckout: You must provide successUrl and cancelUrl.");return Object(a.a)({tag:"no-session",items:p,lineItems:m,successUrl:h,cancelUrl:b,mode:y},v)},O=function(e,t,n){var r=v(e,t,n);if("no-session"===r.tag){var a=r.successUrl,o=r.cancelUrl;if(!Object(m.d)(a))throw new f.b("stripe.redirectToCheckout: successUrl must start with either http:// or https://.");if(!Object(m.d)(o))throw new f.b("stripe.redirectToCheckout: cancelUrl must start with either http:// or https://.");return r}return r},g=function(e,t){return"session"===t.tag||null==e||t.locale||-1===["auto"].concat(Object(o.a)(s)).indexOf(e)?t:Object(a.a)(Object(a.a)({},t),{},{locale:e})},j=function(e,t,n){var r=Object(h.a)(l.b,(function(t){return Object(p.d)(e,t)}));if(t&&t.lineItems&&r)throw new f.b("Prices cannot be used with ".concat(r));if("string"==typeof t&&b.test(t))throw new f.b("stripe.redirectToCheckout: Checkout Session IDs must be passed in as an object with a key of `sessionId` and the Session ID as the value.");switch(r){case"checkout_beta_2":return y(0,t);case"checkout_beta_3":return v(e,t,n);case"checkout_beta_4":default:return O(e,t,n)}};t.a=function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"unknown";return g(t,j(e,n,r))}},function(e,t,n){e.exports=n(87)},,,,,,,,,,,,,function(e,t,n){"use strict";n.r(t);var r,a,o,i,c,s=n(1),u=n(7),l=n(9),d=n(23),p=n(5),f=n(14),m=n(0),h="00".concat(Math.floor(1e3*Math.random())).slice(-3),_=0,b=function(e){return"".concat(e).concat(h).concat(_++)},y=function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return t?(parseInt(t,10)^16*Math.random()>>parseInt(t,10)/4).toString(16):"00000000-0000-4000-8000-000000000000".replace(/[08]/g,e)},v=n(12),O=n(25),g=n(15),j=n(6),w=n(13),k=n(2),E=n(3),S=function(e){var t=e.data,n=e.contentType,r=void 0===n?"application/x-www-form-urlencoded":n,a=e.method,o=e.url,i="";return t&&"application/x-www-form-urlencoded"===r?i=Object(g.j)(t):t&&"application/json"===r&&(i=JSON.stringify(t)),{requestUrl:"GET"===a&&i?"".concat(o,"?").concat(i):o,requestData:"GET"===a?"":i,contentType:r}},P=function(e){return new E.a((function(t,n){var r=e.method,a=e.headers,o=e.withCredentials,i=S(e),c=i.requestUrl,u=i.requestData,l=i.contentType,d=new XMLHttpRequest;o&&(d.withCredentials=o),d.open(r,c,!0),d.setRequestHeader("Accept","application/json"),d.setRequestHeader("Content-Type",l),d.json=function(){return new E.a((function(e,t){try{e(JSON.parse(d.responseText))}catch(e){t(new k.a(e,c))}}))},a&&Object.keys(a).forEach((function(e){var t=a[e];"string"==typeof t&&d.setRequestHeader(e,t)})),d.onreadystatechange=function(){4===d.readyState&&(d.onreadystatechange=function(){},0===d.status?o?n(new k.c(c)):I(Object(s.a)(Object(s.a)({},e),{},{withCredentials:!0})).then(t,n):t(d))};try{d.send(u)}catch(e){n(new k.a(e,c))}}))},A=function e(t){return new E.a((function(n,r){var a=t.method,o=t.headers,i=void 0===o?{}:o,c=t.keepalive,u=t.withCredentials,l=S(t),d=l.requestUrl,p=l.requestData,f={Accept:"application/json","Content-Type":l.contentType};i&&Object.keys(i).forEach((function(e){var t=i[e];"string"==typeof t&&(f[e]=t)})),window.fetch(d,{method:a,keepalive:c,headers:f,body:p||void 0,mode:"cors",credentials:u?"include":"omit"}).then((function(a){if(0===a.status){if(!u)return e(Object(s.a)(Object(s.a)({},t),{},{withCredentials:!0})).then(n,r);r(new k.c(d))}return a.text().then((function(e){n({responseURL:a.url,status:a.status,json:function(){return E.a.resolve(JSON.parse(e))},getResponseHeader:function(e){return a.headers.get(e)||""},responseText:e})}))})).catch((function(e){r(new k.a(e,d))}))}))},I=function(e){return"function"==typeof window.fetch?A(e):P(e)},C=n(4),T=function(e,t){var n=e.reduce((function(e,n){var r=function(e,t){var n=e.indexOf(":");if(-1===n)throw new k.b("Invalid css declaration in file from ".concat(t,': "').concat(e,'"'));var r=e.slice(0,n).trim(),a=C.c[r];if(!a)throw new k.b("Unsupported css property in file from ".concat(t,': "').concat(r,'"'));return{property:a,value:e.slice(n+1).trim()}}(n,t),a=r.property,o=r.value;return Object(s.a)(Object(s.a)({},e),{},Object(p.a)({},a,o))}),{});return["family","src"].forEach((function(e){if(!n[e])throw new k.b("Missing css property in file from ".concat(t,': "').concat(C.h[e],'"'))})),n},N=function(e){return I({url:e,method:"GET"}).then((function(e){return e.responseText})).then((function(t){return function(e,t){var n=e.match(/@font-face[ ]?{[^}]*}/g);if(!n)throw new k.b("No @font-face rules found in file from ".concat(t));return n}(t,e).map((function(t){var n,r=function(e,t){var n=e.replace(/\/\*.*\*\//g,"").trim(),r=(n.length&&/;$/.test(n)?n:"".concat(n,";")).match(/((([^;(]*\([^()]*\)[^;)]*)|[^;]+)+)(?=;)/g);if(!r)throw new k.b("Found @font-face rule containing no valid font-properties in file from ".concat(t));return r}((n=t.match(/@font-face[ ]?{([^}]*)}/))?n[1]:"",e);return T(r,e)}))}))},M=/https?:\/\/([^/]*)\/[^:]*/g,R=function(e,t,n,r){var a,o,i,c=e._isUserError||"IntegrationError"===e.name;throw t&&!c&&t.report("fatal.uncaught_error",{iframe:!1,name:e.name,element:"outer",message:e.message||e.description,fileName:e.fileName,lineNumber:e.lineNumber,columnNumber:e.columnNumber,stack:e.stack&&(a=e.stack,o=a.match(M),i=a,o&&o.forEach((function(e){-1===e.indexOf("https://js.stripe.com")&&(i=i.replace(e,""))})),i.substring(0,1e3)),inPromise:n,apiMethodName:r}),e},x=function(e,t,n){return function(r){try{return e.call(this,r)}catch(e){return R(e,t||this&&this._controller,!1,n)}}},B=function(e,t,n){return function(r,a){try{return e.call(this,r,a)}catch(e){return R(e,t||this&&this._controller,!1,n)}}},L=function(e,t,n){return function(){var r=this;try{return e.call(this).catch((function(e){return R(e,t||r&&r._controller,!0,n)}))}catch(e){return R(e,t||this&&this._controller,!1,n)}}},D=function(e,t,n){return function(r){var a=this;try{return e.call(this,r).catch((function(e){return R(e,t||a&&a._controller,!0,n)}))}catch(e){return R(e,t||this&&this._controller,!1,n)}}},q=function(e,t,n){return function(r,a){var o=this;try{return e.call(this,r,a).catch((function(e){return R(e,t||o&&o._controller,!0,n)}))}catch(e){return R(e,t||this&&this._controller,!1,n)}}},F=function(e,t,n){return function(r,a,o){var i=this;try{return e.call(this,r,a,o).catch((function(e){return R(e,t||i&&i._controller,!0,n)}))}catch(e){return R(e,t||this&&this._controller,!1,n)}}},U=n(38),H=function(e,t){var n,r="string"==typeof(n=e)&&Object(w.a)(Object.keys(U.b),(function(e){return e===n}))||null;if(!r||!function(e,t){var n=j.b[e];return!n||Object(j.d)(t,n)}(r,t)){var a="string"==typeof e?e:typeof e;throw new k.b("A valid Element name must be provided. Valid Elements are:\n ".concat(Object.keys(U.b).filter((function(e){return!U.b[e].beta})).join(", "),"; you passed: ").concat(a,"."))}},G=n(21),z=n(17),K=n(18),Y=function e(){var t=this;Object(l.a)(this,e),this._emit=function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),a=1;a0},this._off=function(e,n){if(n){for(var r,a=t._callbacks[e],o=0;o=0},X=Object.keys(V),$="40px",Q={success:"success",fail:"fail",invalid_shipping_address:"invalid_shipping_address"},Z={shipping:"shipping",delivery:"delivery",pickup:"pickup"},ee=Object(s.a)({success:"success"},{fail:"fail",invalid_payer_name:"invalid_payer_name",invalid_payer_email:"invalid_payer_email",invalid_payer_phone:"invalid_payer_phone",invalid_shipping_address:"invalid_shipping_address"}),te={merchantCapabilities:["supports3DS"],displayItems:[]},ne=Object(m.y)({amount:m.o,label:m.B,pending:Object(m.w)(m.e)}),re=Object(m.y)({amount:m.f,label:m.B,pending:Object(m.w)(m.e)}),ae=Object(m.y)({amount:m.f,label:m.B,pending:Object(m.w)(m.e),id:Object(m.J)(m.B,(function(){return b("shippingOption")})),detail:Object(m.J)(m.B,(function(){return""}))}),oe=Object(m.y)({major:m.r,minor:m.r}),ie=m.u.apply(void 0,Object(u.a)(Object.keys(Z))),ce=Object(m.y)({origin:m.B,name:m.B}),se=m.u.apply(void 0,Object(u.a)(X)),ue=Object(m.y)({displayItems:Object(m.w)(Object(m.b)(re)),shippingOptions:Object(m.w)(Object(m.F)("id")(Object(m.b)(ae))),wallets:Object(m.w)(Object(m.b)(se)),disableWallets:Object(m.w)(Object(m.b)(se)),blockedCardBrands:Object(m.w)(Object(m.b)(m.u.apply(void 0,Object(u.a)(C.b)))),total:ne,requestShipping:Object(m.w)(m.e),requestPayerName:Object(m.w)(m.e),requestPayerEmail:Object(m.w)(m.e),requestPayerPhone:Object(m.w)(m.e),shippingType:Object(m.w)(ie),currency:m.D,country:m.C,jcbEnabled:Object(m.w)(m.e),__billingDetailsEmailOverride:Object(m.w)(m.B),__minApplePayVersion:Object(m.w)(m.r),__minGooglePayVersion:Object(m.w)(oe),__merchantDetails:Object(m.w)(ce),__isCheckout:Object(m.w)(m.e),__betas:Object(m.w)(Object(m.b)(m.v.apply(void 0,Object(u.a)(j.c))))}),le=Object(m.h)({__merchantDetails:Object(m.w)(ce),country:Object(m.w)(m.C),currency:Object(m.w)(m.D),displayItems:Object(m.w)(Object(m.b)(re)),shippingOptions:Object(m.w)(Object(m.F)("id")(Object(m.b)(ae))),total:Object(m.w)(ne),blockedCardBrands:Object(m.w)(Object(m.b)(m.u.apply(void 0,Object(u.a)(C.b))))}),de=Object(m.y)({displayItems:Object(m.w)(Object(m.b)(re)),shippingOptions:Object(m.w)(Object(m.F)("id")(Object(m.b)(ae))),total:Object(m.w)(ne),status:function(e,t){return m.u.apply(void 0,Object(u.a)(Object.keys(Q)))(-1!==["invalid_payer_name","invalid_payer_email","invalid_payer_phone"].indexOf(e)?"fail":e,t)}}),pe=m.u.apply(void 0,Object(u.a)(Object.keys(ee))),fe=function(){return window.ApplePaySession?["APPLE_PAY"]:["GOOGLE_PAY","BROWSER"]},me=function(e){var t=[];return window.ApplePaySession?J(e,V.applePay)&&t.push("APPLE_PAY"):(J(e,V.googlePay)&&(t.push("GOOGLE_PAY"),O.a&&t.push("BROWSER")),J(e,V.browserCard)&&-1===t.indexOf("BROWSER")&&t.push("BROWSER")),t},he=function(){try{return window.location.origin===window.top.location.origin}catch(e){return!1}},_e=Object(W.b)((function(e){return window.ApplePaySession.canMakePaymentsWithActiveCard(e)})),be=function(){return E.a.resolve(window.ApplePaySession.canMakePayments())},ye=function(e){if(!window.ApplePaySession)return!1;try{return window.ApplePaySession.supportsVersion(e)}catch(e){return!1}},ve=(r={},Object(p.a)(r,C.a.VISA,"visa"),Object(p.a)(r,C.a.MASTERCARD,"masterCard"),Object(p.a)(r,C.a.AMEX,"amex"),Object(p.a)(r,C.a.DISCOVER,"discover"),Object(p.a)(r,C.a.JCB,"jcb"),Object(p.a)(r,C.a.UNIONPAY,"chinaUnionPay"),Object(p.a)(r,C.a.DINERS,null),Object(p.a)(r,"MAESTRO","maestro"),r),Oe=(a={},Object(p.a)(a,C.a.VISA,"VISA"),Object(p.a)(a,C.a.MASTERCARD,"MASTERCARD"),Object(p.a)(a,C.a.AMEX,"AMEX"),Object(p.a)(a,C.a.DISCOVER,"DISCOVER"),Object(p.a)(a,C.a.JCB,"JCB"),Object(p.a)(a,C.a.DINERS,null),["AT","AU","BE","CA","CH","DE","DK","EE","ES","FI","FR","GB","GR","HK","IE","IT","JP","LT","LU","LV","MX","NL","NO","NZ","PL","PT","SE","SG","US"]),ge=function(e,t,n){var r=[];return-1!==Oe.indexOf(e)&&r.push(C.a.AMEX),("US"===e||t)&&r.push.apply(r,[C.a.DISCOVER,C.a.DINERS,C.a.JCB]),r.push.apply(r,[C.a.MASTERCARD,C.a.VISA]),r.filter((function(e){return-1===n.indexOf(e)}))},je=n(45),we=function(e,t){return{amount:Object(je.b)(e.amount,t.currency),label:e.label,type:e.pending?"pending":"final"}},ke=function(e,t){return new window.ApplePayError(e,t)},Ee=function(e){return function(t){return t[e]&&"string"==typeof t[e]?t[e].toUpperCase():null}},Se=(o={},Object(p.a)(o,ee.success,0),Object(p.a)(o,ee.fail,1),Object(p.a)(o,ee.invalid_payer_name,2),Object(p.a)(o,ee.invalid_shipping_address,3),Object(p.a)(o,ee.invalid_payer_phone,4),Object(p.a)(o,ee.invalid_payer_email,4),o),Pe=(i={},Object(p.a)(i,ee.success,(function(){return null})),Object(p.a)(i,ee.fail,(function(){return null})),Object(p.a)(i,ee.invalid_payer_name,(function(){return ke("billingContactInvalid","name")})),Object(p.a)(i,ee.invalid_shipping_address,(function(){return ke("shippingContactInvalid","postalAddress")})),Object(p.a)(i,ee.invalid_payer_phone,(function(){return ke("shippingContactInvalid","phoneNumber")})),Object(p.a)(i,ee.invalid_payer_email,(function(){return ke("shippingContactInvalid","emailAddress")})),i),Ae=(c={},Object(p.a)(c,Z.pickup,"storePickup"),Object(p.a)(c,Z.shipping,"shipping"),Object(p.a)(c,Z.delivery,"delivery"),c),Ie={total:function(e){return we(e.total,e)},lineItems:function(e){return e.displayItems?e.displayItems.map((function(t){return we(t,e)})):[]},shippingMethods:function(e){return e.shippingOptions?e.shippingOptions.map((function(t){return function(e,t){return{amount:Object(je.b)(e.amount,t.currency),label:e.label,detail:e.detail,identifier:e.id}}(t,e)})):[]},applicationData:function(e){return e.applicationData||null}},Ce={shippingType:function(e){var t=e.shippingType;if(!t)return null;var n=Ae[t];if(void 0!==n)return n;throw new k.b("Invalid value for shippingType: ".concat(t))},requiredBillingContactFields:function(e){return e.requestPayerName?["postalAddress"]:null},requiredShippingContactFields:function(e){var t=[];return e.requestShipping&&t.push("postalAddress"),e.requestPayerEmail&&t.push("email"),e.requestPayerPhone&&t.push("phone"),t.length?t:null},countryCode:Ee("country"),currencyCode:Ee("currency"),merchantCapabilities:function(e){var t=e.merchantCapabilities||te.merchantCapabilities;return e.__betas&&Object(j.d)(e.__betas,"cup_apple_pay_beta_1")&&t.push("supportsEMV"),t},supportedNetworks:function(e){var t,n,r,a=(t=e.country,n=e.jcbEnabled||!1,r=e.blockedCardBrands||[],ge(t,n,r).reduce((function(e,t){var n=ve[t];return n&&e.push(n),e}),[]));return ye(4)&&-1===(e.blockedCardBrands||[]).indexOf("mastercard")&&a.push("maestro"),e.__betas&&Object(j.d)(e.__betas,"cup_apple_pay_beta_1")&&-1===(e.blockedCardBrands||[]).indexOf("unionpay")&&a.push("chinaUnionPay"),a}},Te={status:function(e){var t=Se[e.status];return ye(3)&&t>1?1:t},error:function(e){return ye(3)?Pe[e.status]():null}},Ne=Object(s.a)(Object(s.a)({},Ie),Ce),Me=Object(s.a)(Object(s.a)({},Ie),Te),Re=function(e){return Object.keys(Me).reduce((function(t,n){var r=(0,Me[n])(e);return null!==r?Object(s.a)(Object(s.a)({},t),{},Object(p.a)({},n,r)):t}),{})},xe=function(e){return"string"==typeof e?e:null},Be=function(e){return e?xe(e.phoneNumber):null},Le=function(e){return e?xe(e.emailAddress):null},De=function(e){return e?[e.givenName,e.familyName].filter((function(e){return e&&"string"==typeof e})).join(" "):null},qe=function(e){var t=e.addressLines,n=e.countryCode,r=e.postalCode,a=e.administrativeArea,o=e.locality,i=e.phoneNumber,c=xe(n);return{addressLine:Array.isArray(t)?t.reduce((function(e,t){return"string"==typeof t?[].concat(Object(u.a)(e),[t]):e}),[]):[],country:c?c.toUpperCase():"",postalCode:xe(r)||"",recipient:De(e)||"",region:xe(a)||"",city:xe(o)||"",phone:xe(i)||"",sortingCode:"",dependentLocality:"",organization:""}},Fe=function(e,t){var n=e.identifier,r=e.label;return t.filter((function(e){return e.id===n&&e.label===r}))[0]},Ue=function(e,t){var n=e.shippingContact,r=e.shippingMethod,a=e.billingContact;return{shippingOption:r&&t.shippingOptions&&t.shippingOptions.length?Fe(r,t.shippingOptions):null,shippingAddress:n?qe(n):null,payerEmail:Le(n),payerPhone:Be(n),payerName:De(a),walletName:"applePay",methodName:"apple-pay"}},He=n(29),Ge={austria:"AT",sterreich:"AT",csterreich:"AT",au:"AU",australia:"AU",belgium:"BE",br:"BR",brasil:"BR",brazil:"BR",ca:"CA",canada:"CA",ch:"CH",schweiz:"CH",switzerland:"CH",china:"CN",czechrepublic:"CZ",de:"DE",deutschland:"DE",germany:"DE",danmark:"DK",denmark:"DK",es:"ES",espaa:"ES",spain:"ES",finland:"FI",suomi:"FI",fr:"FR",hk:"HK",hongkong:"HK",england:"GB",gb:"GB",uk:"GB",unitedkingdom:"GB",scotland:"GB",wales:"GB",it:"IT",italy:"IT",italia:"IT",japan:"JP",lietuva:"LT",luxembourg:"LU",netherlands:"NL",nederland:"NL",norway:"NO",poland:"PL",polska:"PL",russia:"RU",saudiarabia:"SA",se:"SE",sweden:"SE",sverige:"SE",singapore:"SG",us:"US",usa:"US",unitedstatesofamerica:"US",unitedstates:"US",estadosunidos:"US"},ze=function(e,t){return e&&"object"==typeof e?t(e):null},Ke=function(){function e(t){var n=this;Object(l.a)(this,e),this._onEvent=function(){},this.setEventHandler=function(e){n._onEvent=e},this.canMakePayment=function(e){var t=e.skipEnrollmentChecks;return function(e,t,n,r){var a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:2,o=arguments.length>5?arguments[5]:void 0,i=Math.max(2,a);if(window.ApplePaySession){if(he()){if(window.ApplePaySession.supportsVersion(i)){var c="merchant.".concat((t?[e,t]:[e]).join("."),".stripe");return o?be():_e(c).then((function(a){if(r("pr.apple_pay.can_make_payment_native_response",{available:a}),n&&!a&&window.console){var o=t?"or stripeAccount parameter (".concat(t,") "):"";window.console.warn("Either you do not have a card saved to your Wallet or the current domain (".concat(e,") ").concat(o,"is not registered for Apple Pay. Visit https://dashboard.stripe.com/account/apple_pay to register this domain."))}return a}))}return n&&window.console&&window.console.warn("This version of Safari does not support ApplePay JS version ".concat(i,".")),E.a.resolve(!1)}return E.a.resolve(!1)}return E.a.resolve(!1)}(window.location.hostname,n._authentication.accountId,Object(He.c)(n._authentication.apiKey)===He.a.test,n._report,n._minimumVersion,t)},this.update=function(e){n._initialPaymentRequest=Object(w.e)(n._paymentRequestOptions,e),n._initializeSessionState()},this.show=function(){var e,t,r;n._initializeSessionState();try{e=new window.ApplePaySession(n._minimumVersion,(t=n._paymentRequestOptions,r=Object(s.a)(Object(s.a)({},te),t),Object.keys(Ne).reduce((function(e,t){var n=(0,Ne[t])(r);return null!==n?Object(s.a)(Object(s.a)({},e),{},Object(p.a)({},t,n)):e}),{})))}catch(e){throw"Must create a new ApplePaySession from a user gesture handler."===e.message?new k.b("show() must be called from a user gesture handler (such as a click handler, after the user clicks a button)."):e}n._privateSession=e,n._setupSession(e,n._usesButtonElement()),e.begin(),n._isShowing=!0},this.abort=function(){n._privateSession&&n._privateSession.abort()},this._warn=function(e){},this._report=function(e,t){n._controller.report(e,Object(s.a)(Object(s.a)({},t),{},{backingLibrary:"APPLE_PAY",usesButtonElement:n._usesButtonElement()}))},this._validateMerchant=function(e,t){return function(r){n._controller.action.createApplePaySession({data:{validation_url:r.validationURL,domain_name:window.location.hostname,display_name:n._paymentRequestOptions.total.label},usesButtonElement:t}).then((function(t){if(n._isShowing)switch(t.type){case"object":e.completeMerchantValidation(JSON.parse(t.object.session));break;case"error":n._handleValidationError(e)(t.error);break;default:Object(m.a)(t)}}),n._handleValidationError(e))}},this._handleValidationError=function(e){return function(t){n._report("error.pr.apple_pay.session_creation_failed",{error:t}),e.abort();var r=t.message;"string"==typeof r&&n._controller.warn(r)}},this._paymentAuthorized=function(e){return function(t){var r=t.payment,a=n._usesButtonElement()?C.e.paymentRequestButton:null;n._controller.action.tokenizeWithData({type:"apple_pay",elementName:a,tokenData:Object(s.a)(Object(s.a)({},r),{},{billingContact:ze(r.billingContact,n._normalizeContact)}),mids:n._mids}).then((function(t){if("error"===t.type)e.completePayment(window.ApplePaySession.STATUS_FAILURE),n._report("error.pr.create_token_failed",{error:t.error});else{var a=ze(r.shippingContact,n._normalizeContact),o=ze(r.billingContact,n._normalizeContact);a&&n._paymentRequestOptions.requestShipping&&!a.countryCode&&e.completePayment(window.ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS);var i=Ue({shippingContact:a,billingContact:o},n._paymentRequestOptions);n._onToken(e)(Object(s.a)(Object(s.a)({},i),{},{shippingOption:n._privateShippingOption,token:t.object}))}}))}},this._normalizeContact=function(e){if(e.country&&"string"==typeof e.country){var t,r=e.country.toLowerCase().replace(/[^a-z]+/g,"");return e.countryCode?"string"==typeof e.countryCode&&(t=e.countryCode.toUpperCase()):(t=Ge[r])||n._report("warn.pr.apple_pay.missing_country_code",{country:e.country}),Object(s.a)(Object(s.a)({},e),{},{countryCode:t})}return e},this._onToken=function(e){return function(t){n._onEvent({type:"paymentresponse",payload:Object(s.a)(Object(s.a)({},t),{},{complete:x(n._completePayment(e))})})}},this._completePayment=function(e){return function(t){n._paymentRequestOptions=Object(w.e)(n._paymentRequestOptions,{status:t});var r=Re(n._paymentRequestOptions),a=r.status,o=r.error;n._isShowing&&(o?e.completePayment({status:a,errors:[o]}):e.completePayment(a)),(0===a||1===a&&null==o)&&(n._isShowing=!1,n._onEvent&&n._onEvent({type:"close"}))}},this._shippingContactSelected=function(e){return function(t){n._onEvent({type:"shippingaddresschange",payload:{shippingAddress:qe(n._normalizeContact(t.shippingContact)),updateWith:x(n._completeShippingContactSelection(e))}})}},this._completeShippingContactSelection=function(e){return function(t){var r;n._paymentRequestOptions=Object(w.e)(n._paymentRequestOptions,t),(null===(r=n._paymentRequestOptions.shippingOptions)||void 0===r?void 0:r.length)&&(n._privateShippingOption=n._paymentRequestOptions.shippingOptions[0]);var a=Re(n._paymentRequestOptions),o=a.status,i=a.shippingMethods,c=a.total,s=a.lineItems;e.completeShippingContactSelection(o,i,c,s)}},this._shippingMethodSelected=function(e){return function(t){if(n._paymentRequestOptions.shippingOptions){var r=Fe(t.shippingMethod,n._paymentRequestOptions.shippingOptions);n._privateShippingOption=r,n._onEvent({type:"shippingoptionchange",payload:{shippingOption:r,updateWith:x(n._completeShippingMethodSelection(e))}})}}},this._completeShippingMethodSelection=function(e){return function(t){n._paymentRequestOptions=Object(w.e)(n._paymentRequestOptions,t);var r=Re(n._paymentRequestOptions),a=r.status,o=r.total,i=r.lineItems;e.completeShippingMethodSelection(a,o,i)}};var r=t.controller,a=t.authentication,o=t.mids,i=t.options,c=t.usesButtonElement,u=t.listenerRegistry;this._controller=r,this._authentication=a,this._mids=o,this._minimumVersion=i.__minApplePayVersion||2,this._usesButtonElement=c,this._listenerRegistry=u,this._initialPaymentRequest=i,this._isShowing=!1,this._initializeSessionState()}return Object(d.a)(e,[{key:"_initializeSessionState",value:function(){var e=btoa(this._authentication.accountId?"".concat(this._authentication.apiKey,":").concat(this._authentication.accountId):this._authentication.apiKey);this._paymentRequestOptions=Object(s.a)(Object(s.a)(Object(s.a)({},te),this._initialPaymentRequest),{},{status:ee.success,applicationData:e}),this._privateSession=null,this._privateShippingOption=null;var t=this._paymentRequestOptions.shippingOptions;(null==t?void 0:t.length)&&(this._privateShippingOption=t[0])}},{key:"_setupSession",value:function(e,t){var n=this;this._listenerRegistry.addEventListener(e,"validatemerchant",x(this._validateMerchant(e,t))),this._listenerRegistry.addEventListener(e,"paymentauthorized",x(this._paymentAuthorized(e))),this._listenerRegistry.addEventListener(e,"cancel",x((function(){n._isShowing=!1,n._onEvent({type:"cancel"}),n._onEvent({type:"close"})}))),this._listenerRegistry.addEventListener(e,"shippingcontactselected",x(this._shippingContactSelected(e))),this._listenerRegistry.addEventListener(e,"shippingmethodselected",x(this._shippingMethodSelected(e)))}}]),e}(),Ye=n(8),We={display:"block",position:"fixed","z-index":"2147483647",background:"rgba(40,40,40,0)",transition:"background 400ms ease","will-change":"background",top:"0",left:"0",right:"0",bottom:"0",margin:"0",padding:"0"},Ve=Object(s.a)(Object(s.a)({},We),{},{background:"rgba(40,40,40,0.75)"}),Je=function e(t){var n=this,r=t.lockScrolling,a=t.lockFocus,o=t.lockFocusOn,i=t.listenerRegistry;Object(l.a)(this,e),this.domElement=document.createElement("div"),this._runOnHide=[],this.mount=function(){var e=Object(v.c)();n.domElement.style.display="none",e.contains(n.domElement)||e.insertBefore(n.domElement,e.firstChild)},this.show=function(){if(Object(v.l)(n.domElement,We),n._lockScrolling){var e=Object(v.i)();n._runOnHide.push(e)}if(n._lockFocus){var t=Object(v.b)(n._lockFocusOn).restoreFocus;n._runOnHide.push(t)}},this.fadeIn=function(){setTimeout((function(){Object(v.l)(n.domElement,Ve)}))},this.fadeOut=function(){return new E.a((function(e){Object(v.l)(n.domElement,We),setTimeout(e,500),n._listenerRegistry.addEventListener(n.domElement,"transitionend",e)})).then((function(){for(n.domElement.style.display="none";n._runOnHide.length;)n._runOnHide.pop()()}))},this.unmount=function(){Object(v.c)().removeChild(n.domElement)},this._lockScrolling=!!r,this._lockFocus=!!a,this._lockFocusOn=o||null,this._listenerRegistry=i},Xe=null,$e=function(e){return null!==Xe?E.a.resolve(Xe):e().then((function(e){return Xe=e}))};var Qe,Ze=function(e){return!(!O.m&&!O.b)&&(!O.d&&(!(!e.isCheckout&&!window.PaymentRequest)&&!(!e.isCheckout&&O.a)))},et=function e(t){var n=this;Object(l.a)(this,e),this._mids=null,this._frame=null,this._initFrame=function(e){var t=n._controller.createHiddenFrame(Ye.a.PAYMENT_REQUEST_GOOGLE_PAY,{authentication:n._authentication,mids:n._mids,origin:n._origin});t.send({action:"stripe-pr-initialize",payload:{data:e}}),n._initFrameEventHandlers(t),n._frame=t},this._initFrameEventHandlers=function(e){e._on("pr-cancel",(function(){n._onEvent({type:"cancel"})})),e._on("pr-close",(function(){n._backdrop.fadeOut().then((function(){n._backdrop.unmount()})),n._onEvent({type:"close"})})),e._on("pr-error",(function(e){n._onEvent({type:"error",payload:{errorMessage:e.errorMessage,errorCode:e.errorCode}})})),e._on("pr-callback",(function(t){var r=t.event,a=t.options,o=t.nonce;switch(r){case"paymentresponse":n._handlePaymentResponse(e,a,o);break;case"shippingaddresschange":n._handleShippingAddressChange(e,a,o);break;case"shippingoptionchange":n._handleShippingOptionChange(e,a,o);break;default:throw new Error("Unexpected event name: ".concat(r))}}))},this._handlePaymentResponse=function(e,t,r){n._onEvent({type:"paymentresponse",payload:Object(s.a)(Object(s.a)({},t),{},{complete:function(t){e.send({action:"stripe-pr-callback-complete",payload:{nonce:r,data:{status:t}}})}})})},this._handleShippingAddressChange=function(e,t,r){n._onEvent({type:"shippingaddresschange",payload:Object(s.a)(Object(s.a)({},t),{},{updateWith:function(t){e.send({action:"stripe-pr-callback-complete",payload:{nonce:r,data:t}})}})})},this._handleShippingOptionChange=function(e,t,r){n._onEvent({type:"shippingoptionchange",payload:Object(s.a)(Object(s.a)({},t),{},{updateWith:function(t){e.send({action:"stripe-pr-callback-complete",payload:{nonce:r,data:t}})}})})},this.setEventHandler=function(e){n._onEvent=e},this.canMakePayment=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{skipEnrollmentChecks:!1},t=e.skipEnrollmentChecks;if(!Ze({isCheckout:n._isCheckout}))return E.a.resolve(!1);if(!n._frame)throw new Error("Frame not initialized.");var r=n._frame;return $e((function(){return r.action.checkCanMakePayment({skipEnrollmentChecks:t}).then((function(e){return!0===e.available}))}))},this.show=function(){n._frame&&(n._frame.send({delegate:"payment",action:"stripe-pr-show",payload:{data:{usesButtonElement:n._usesButtonElement()}}}),n._backdrop.mount(),n._backdrop.show(),n._backdrop.fadeIn())},this.update=function(e){n._frame&&n._frame.send({action:"stripe-pr-update",payload:{data:e}})},this.abort=function(){n._frame&&n._frame.send({action:"stripe-pr-abort",payload:{}})},this._controller=t.controller,this._authentication=t.authentication,this._mids=t.mids,this._origin=t.origin,this._usesButtonElement=t.usesButtonElement,this._backdrop=new Je({lockScrolling:!1,lockFocus:!0,lockFocusOn:null,listenerRegistry:t.listenerRegistry}),this._isCheckout=!!t.options.__isCheckout,Ze({isCheckout:this._isCheckout})&&this._controller&&(this._controller.action.fetchLocale({locale:"auto"}),this._initFrame(t.options))},tt=function(){if(!window.PaymentRequest)return null;if(/CriOS\/59/.test(navigator.userAgent))return null;if(/.*\(.*; wv\).*Chrome\/(?:53|54)\.\d.*/g.test(navigator.userAgent))return null;if(O.l)return null;var e=window.PaymentRequest;return e.prototype.canMakePayment||(e.prototype.canMakePayment=function(){return E.a.resolve(!1)}),e}(),nt=null,rt=function e(t){var n=this;Object(l.a)(this,e),this._onEvent=function(){},this.setEventHandler=function(e){n._onEvent=e},this.canMakePayment=function(e){var t=e.skipEnrollmentChecks;return function(e,t,n){return null!==nt?E.a.resolve(nt):tt&&e?e.action.checkCanMakePayment({skipEnrollmentChecks:n}).then((function(e){var t=e.available;return nt=!0===t})):E.a.resolve(!1)}(n._prFrame,(Object(He.c)(n._authentication.apiKey),He.a.test),t)},this.update=function(e){var t=n._prFrame;t&&t.send({action:"stripe-pr-update",payload:{data:e}})},this.show=function(){if(!n._prFrame)throw new k.b("Payment Request is not available in this browser.");n._prFrame.send({delegate:"payment",action:"stripe-pr-show",payload:{data:{usesButtonElement:n._usesButtonElement()}}})},this.abort=function(){n._prFrame&&n._prFrame.send({action:"stripe-pr-abort",payload:{}})},this._setupPrFrame=function(e,t){e.send({action:"stripe-pr-initialize",payload:{data:t}}),e._on("pr-cancel",(function(){n._onEvent({type:"cancel"})})),e._on("pr-close",(function(){n._onEvent({type:"close"})})),e._on("pr-error",(function(e){n._onEvent({type:"error",payload:{errorMessage:e.message||"",errorCode:e.code||""}})})),e._on("pr-callback",(function(t){var r=t.event,a=t.nonce,o=t.options;switch(r){case"token":n._onEvent({type:"paymentresponse",payload:Object(s.a)(Object(s.a)({},o),{},{complete:function(t){e.send({action:"stripe-pr-callback-complete",payload:{data:{status:t},nonce:a}})}})});break;case"shippingaddresschange":n._onEvent({type:"shippingaddresschange",payload:{shippingAddress:o.shippingAddress,updateWith:function(t){e.send({action:"stripe-pr-callback-complete",payload:{nonce:a,data:t}})}}});break;case"shippingoptionchange":n._onEvent({type:"shippingoptionchange",payload:{shippingOption:o.shippingOption,updateWith:function(t){e.send({action:"stripe-pr-callback-complete",payload:{nonce:a,data:t}})}}});break;default:throw new Error("Unexpected event from PaymentRequest inner: ".concat(r))}}))};var r=t.authentication,a=t.controller,o=t.mids,i=t.origin,c=t.usesButtonElement,u=t.options;if(this._authentication=r,this._controller=a,this._usesButtonElement=c,tt&&"https:"===window.location.protocol){this._controller.action.fetchLocale({locale:"auto"});var d=this._controller.createHiddenFrame(Ye.a.PAYMENT_REQUEST_BROWSER,{authentication:r,mids:o,origin:i});this._setupPrFrame(d,u),this._prFrame=d}else this._prFrame=null},at=n(27),ot=!1,it=function(e){Object(z.a)(n,e);var t=Object(K.a)(n);function n(e){var r;Object(l.a)(this,n),(r=t.call(this))._usedByButtonElement=null,r._showCalledByButtonElement=!1,r._isShowing=!1,r._backingLibraries={APPLE_PAY:null,GOOGLE_PAY:null,BROWSER:null},r._activeBackingLibraryName=null,r._buttonTypeName=null,r._activeBackingLibrary=null,r._canMakePaymentAvailability={APPLE_PAY:null,GOOGLE_PAY:null,BROWSER:null},r._canMakePaymentResolved=!1,r._validateUserOn=function(e,t){"string"==typeof e&&("source"===e&&r._hasRegisteredListener("paymentmethod")||"paymentmethod"===e&&r._hasRegisteredListener("source"))&&(r._report("pr.double_callback_registration"),r._controller.warn("Do not register event listeners for both `source` or `paymentmethod`. Only one of them will succeed."))},r._report=function(e,t){r._controller.report(e,Object(s.a)(Object(s.a)({},t),{},{activeBackingLibrary:r._activeBackingLibraryName,usesButtonElement:r._usedByButtonElement||!1}))},r._warn=function(e){r._controller.warn(e)},r._registerElement=function(){r._usedByButtonElement=!0},r._elementShow=function(){r._showCalledByButtonElement=!0,r.show()},r._initBackingLibraries=function(e){r._queryStrategy.forEach((function(t){var n={controller:r._controller,authentication:r._authentication,mids:r._mids,origin:window.location.origin,options:e,usesButtonElement:function(){return!0===r._usedByButtonElement},listenerRegistry:r._listenerRegistry};switch(t){case"APPLE_PAY":r._backingLibraries.APPLE_PAY=new Ke(n),r._backingLibraries.APPLE_PAY.setEventHandler(r._handleInternalEvent);break;case"GOOGLE_PAY":r._backingLibraries.GOOGLE_PAY=new et(n),r._backingLibraries.GOOGLE_PAY.setEventHandler(r._handleInternalEvent);break;case"BROWSER":r._backingLibraries.BROWSER=new rt(n),r._backingLibraries.BROWSER.setEventHandler(r._handleInternalEvent);break;default:Object(m.a)(t)}}))},r._handleInternalEvent=function(e){switch(e.type){case"paymentresponse":r._emitPaymentResponse(e.payload);break;case"error":r._report("error.pr.internal_error",{error:e.payload});break;case"close":r._isShowing=!1;break;default:r._emitExternalEvent(e)}},r._emitExternalEvent=function(e){switch(e.type){case"cancel":r._emit("cancel");break;case"shippingoptionchange":case"shippingaddresschange":var t=e.type,n=e.payload,a=null,o=!1,i=!1,c=function(c){if(i&&o)return r._report("pr.update_with_called_after_timeout",{event:t}),void r._controller.warn("Call to updateWith() was ignored because it has already timed out. Please ensure that updateWith is called within 30 seconds.");if(o)return r._report("pr.update_with_double_call",{event:t}),void r._controller.warn("Call to updateWith() was ignored because it has already been called. Do not call updateWith more than once.");a&&clearTimeout(a),o=!0,r._report("pr.update_with",{event:t});var s=Object(m.H)(de,c||{},"".concat(t," callback")),u=s.value;s.warnings.forEach((function(e){return r._controller.warn(e)}));var l=u,d=!1;if(r._initialOptions.__isCheckout&&"APPLE_PAY"===r._activeBackingLibraryName&&u.shippingOptions&&1===u.shippingOptions.length&&0===u.shippingOptions[0].amount){u.shippingOptions;l=Object(f.a)(u,["shippingOptions"]),d=!0}var p=u.shippingOptions||r._initialOptions.shippingOptions;if(!(d||"shippingaddresschange"!==e.type||u.status!==ee.success||p&&p.length))throw new k.b("When requesting shipping information, you must specify shippingOptions once a shipping address is selected.\nEither provide shippingOptions in stripe.paymentRequest(...) or listen for the shippingaddresschange event and provide shippingOptions to the updateWith callback there.");n.updateWith(l)};r._hasRegisteredListener(e.type)?(a=setTimeout((function(){i=!0,r._report("pr.update_with_timed_out",{event:t}),r._controller.warn('Timed out waiting for a call to updateWith(). If you listen to "'.concat(e.type,'" events, then you must call event.updateWith in the "').concat(e.type,'" handler within 30 seconds.')),c({status:"fail"})}),29900),r._emit(t,Object(s.a)(Object(s.a)({},n),{},{updateWith:c}))):c({status:"success"});break;case"token":case"source":case"paymentmethod":var u=e.type,l=e.payload,d=null,p=!1,h=!1,_=function(e){if(p&&h)return r._report("pr.complete_called_after_timeout"),void r._controller.warn("Call to complete() was ignored because it has already timed out. Please ensure that complete is called within 30 seconds.");if(h)return r._report("pr.complete_double_call"),void r._controller.warn("Call to complete() was ignored because it has already been called. Do not call complete more than once.");d&&clearTimeout(d),h=!0;var t=Object(m.H)(pe,e,"status for PaymentRequest completion"),n=t.value;t.warnings.forEach((function(e){return r._controller.warn(e)})),l.complete(n)};d=setTimeout((function(){p=!0,r._report("pr.complete_timed_out"),r._controller.warn('Timed out waiting for a call to complete(). Once you have processed the payment in the "'.concat(e.type,'" handler, you must call event.complete within 30 seconds.')),_("fail")}),29900),r._emit(u,Object(s.a)(Object(s.a)({},l),{},{complete:_}));break;default:Object(m.a)(e)}},r._maybeEmitPaymentResponse=function(e){r._isShowing&&r._emitExternalEvent(e)},r._emitPaymentResponse=function(e){r._report("pr.payment_authorized");var t=e.token,n=Object(f.a)(e,["token"]),a=n.payerEmail,o=n.payerPhone,i=n.complete,c=r._showCalledByButtonElement?C.e.paymentRequestButton:null;r._hasRegisteredListener("token")&&r._maybeEmitPaymentResponse({type:"token",payload:e}),r._hasRegisteredListener("paymentmethod")?r._controller.action.createPaymentMethodWithData({elementName:c,type:"card",paymentMethodData:{card:{token:t.id},billing_details:{email:r._initialOptions.__billingDetailsEmailOverride||a,phone:o}},mids:null}).then((function(e){"error"===e.type?e.error.code&&"email_invalid"===e.error.code?i("invalid_payer_email"):(r._report("fatal.pr.token_to_payment_method_failed",{error:e.error,token:t.id}),i("fail")):r._maybeEmitPaymentResponse({type:"paymentmethod",payload:Object(s.a)(Object(s.a)({},n),{},{paymentMethod:e.object})})})):r._hasRegisteredListener("source")&&r._controller.action.createSourceWithData({elementName:c,type:"card",sourceData:{token:t.id,owner:{email:r._initialOptions.__billingDetailsEmailOverride||a,phone:o}},mids:null}).then((function(e){"error"===e.type?e.error.code&&"email_invalid"===e.error.code?i("invalid_payer_email"):(r._report("fatal.pr.token_to_source_failed",{error:e.error,token:t.id}),i("fail")):r._maybeEmitPaymentResponse({type:"source",payload:Object(s.a)(Object(s.a)({},n),{},{source:e.object})})}))},r._canMakePaymentForBackingLibrary=function(e,t){var n=r._backingLibraries[e];if(!n)throw new Error("Unexpectedly calling canMakePayment on uninitialized backing library.");return E.a.race([new E.a((function(e){return setTimeout(e,1e4)})).then((function(){return!1})),n.canMakePayment({skipEnrollmentChecks:t}).then((function(e){return!!e}))]).then((function(t){return r._canMakePaymentAvailability=Object(s.a)(Object(s.a)({},r._canMakePaymentAvailability),{},Object(p.a)({},e,t)),{backingLibraryName:e,available:t}}))},r._isGooglePayOnAndroid=function(){var e=r._initialOptions.wallets,t=e&&-1===e.indexOf("googlePay");return O.a&&!t},r._constructCanMakePaymentResponse=function(){var e=r._isGooglePayOnAndroid()&&!!r._canMakePaymentAvailability.BROWSER;return{applePay:!!r._canMakePaymentAvailability.APPLE_PAY,googlePay:!!r._canMakePaymentAvailability.GOOGLE_PAY||e}},r.canMakePayment=x((function(e){var t=Boolean(null==e?void 0:e.skipEnrollmentChecks);if(r._report("pr.can_make_payment"),r._canMakePaymentResolved){var n=null!==r._activeBackingLibrary?r._constructCanMakePaymentResponse():null;return r._report("pr.can_make_payment_response",{response:n,cached:!0}),E.a.resolve(n)}if("https:"!==window.location.protocol)return ot||(r._controller.warn("If you are testing Apple Pay or Google Pay, you must serve this page over HTTPS as it will not work over HTTP. Please read https://stripe.com/docs/stripe-js/elements/payment-request-button#html-js-prerequisites for more details."),ot=!0),r._canMakePaymentResolved=!0,E.a.resolve(null);var a=r._queryStrategy.map((function(e){return function(){return r._canMakePaymentForBackingLibrary(e,!!r._initialOptions.__isCheckout&&t)}})),o=new at.a;return Object(W.c)(a,(function(e){var t=e.backingLibraryName,n=e.available;return n&&(r._activeBackingLibraryName=t,r._activeBackingLibrary=r._backingLibraries[t],r._buttonTypeName=r._activeBackingLibraryName,r._isGooglePayOnAndroid()&&(r._buttonTypeName="GOOGLE_PAY")),n})).then((function(e){var t=new at.a;r._canMakePaymentResolved=!0;var n=null;return"SATISFIED"===e.type&&(n=r._constructCanMakePaymentResponse()),r._report("pr.can_make_payment_response",{response:n,cached:!1,duration:o.getElapsedTime(t)}),n}))})),r.update=x((function(e){if(r._isShowing)throw r._report("pr.update_called_while_showing"),new k.b("You cannot update Payment Request options while the payment sheet is showing.");var t=Object(m.H)(le,e,"PaymentRequest update()"),n=t.value,a=t.warnings;r._report("pr.update"),a.forEach((function(e){return r._warn(e)})),Object(w.j)(r._backingLibraries).forEach((function(e){e&&e.update(n)}))})),r.show=x((function(){if(r._usedByButtonElement&&!r._showCalledByButtonElement&&(r._report("pr.show_called_with_button"),r._warn("Do not call show() yourself if you are using the paymentRequestButton Element. The Element handles showing the payment sheet.")),!r._canMakePaymentResolved)throw r._report("pr.show_called_before_can_make_payment"),new k.b("You must first check the Payment Request API's availability using paymentRequest.canMakePayment() before calling show().");if(!r._activeBackingLibrary)throw r._report("pr.show_called_with_can_make_payment_false"),new k.b("Payment Request is not available in this browser.");var e=r._activeBackingLibrary;r._report("pr.show",{listeners:Object.keys(r._callbacks).sort()}),r._isShowing=!0,e.show()})),r.abort=x((function(){if(r._activeBackingLibrary){var e=r._activeBackingLibrary;r._report("pr.abort"),e.abort()}})),r.isShowing=function(){return r._isShowing},r._controller=e.controller,r._authentication=e.authentication,r._mids=e.mids,r._listenerRegistry=e.listenerRegistry;var a=Object(m.H)(ue,e.rawOptions||{},"paymentRequest()"),o=a.value,i=a.warnings;if(r._report("pr.options",{options:Object(w.h)(o,["country","currency","jcbEnabled","requestPayerEmail","requestPayerName","requestPayerPhone","requestShipping","disableWallets","wallets","blockedCardBrands"])}),i.forEach((function(e){return r._warn(e)})),o.__billingDetailsEmailOverride&&o.requestPayerEmail)throw new k.b("When providing `__billingDetailsEmailOverride`, `requestPayerEmail` has to be `false` so that the customer is not prompted for their email in the payment sheet.");var c=o.disableWallets,u=c?X.filter((function(e){return-1===c.indexOf(e)})):o.wallets;return r._queryStrategy=u?me(u):e.queryStrategyOverride||fe(),r._report("pr.query_strategy",{queryStrategy:r._queryStrategy}),r._initialOptions=Object(s.a)(Object(s.a)({},o),{},{__betas:e.betas,wallets:u}),r._initBackingLibraries(r._initialOptions),r}return n}(Y),ct={base:Object(m.w)(m.t),complete:Object(m.w)(m.t),empty:Object(m.w)(m.t),invalid:Object(m.w)(m.t),paymentRequestButton:Object(m.w)(m.t)},st={classes:Object(m.w)(Object(m.y)({base:Object(m.w)(m.B),complete:Object(m.w)(m.B),empty:Object(m.w)(m.B),focus:Object(m.w)(m.B),invalid:Object(m.w)(m.B),webkitAutofill:Object(m.w)(m.B)})),hidePostalCode:Object(m.w)(m.e),hideIcon:Object(m.w)(m.e),showIcon:Object(m.w)(m.e),style:Object(m.w)(Object(m.y)(ct)),iconStyle:Object(m.w)(Object(m.u)("solid","default")),value:Object(m.w)(Object(m.x)(m.B,m.t)),__privateCvcOptional:Object(m.w)(m.e),__privateValue:Object(m.w)(Object(m.x)(m.B,m.t)),__privateEmitIbanValue:Object(m.w)(m.e),error:Object(m.w)(Object(m.y)({type:m.B,code:Object(m.w)(m.B),decline_code:Object(m.w)(m.B),param:Object(m.w)(m.B)})),locale:Object(m.n)("elements()"),fonts:Object(m.n)("elements()"),placeholder:Object(m.w)(m.B),disabled:Object(m.w)(m.e),placeholderCountry:Object(m.w)(m.B),paymentRequest:Object(m.w)(Object(m.l)(it,"stripe.paymentRequest(...)")),supportedCountries:Object(m.w)(Object(m.b)(m.B)),accountHolderType:Object(m.w)(Object(m.u)("individual","company")),issuingCard:Object(m.w)(m.B),toCopy:Object(m.w)(Object(m.u)("number","cvc","expiry","pin"))},ut=Object(m.y)(st),lt=(Qe={},Object(p.a)(Qe,C.e.card,Ye.a.CARD_ELEMENT),Object(p.a)(Qe,C.e.cardNumber,Ye.a.CARD_ELEMENT),Object(p.a)(Qe,C.e.cardExpiry,Ye.a.CARD_ELEMENT),Object(p.a)(Qe,C.e.cardCvc,Ye.a.CARD_ELEMENT),Object(p.a)(Qe,C.e.postalCode,Ye.a.CARD_ELEMENT),Object(p.a)(Qe,C.e.paymentRequestButton,Ye.a.PAYMENT_REQUEST_ELEMENT),Object(p.a)(Qe,C.e.iban,Ye.a.IBAN_ELEMENT),Object(p.a)(Qe,C.e.idealBank,Ye.a.IDEAL_BANK_ELEMENT),Object(p.a)(Qe,C.e.p24Bank,Ye.a.P24_BANK_ELEMENT),Object(p.a)(Qe,C.e.auBankAccount,Ye.a.AU_BANK_ACCOUNT_ELEMENT),Object(p.a)(Qe,C.e.fpxBank,Ye.a.FPX_BANK_ELEMENT),Object(p.a)(Qe,C.e.issuingCardNumberDisplay,Ye.a.ISSUING_CARD_NUMBER_DISPLAY_ELEMENT),Object(p.a)(Qe,C.e.issuingCardCopyButton,Ye.a.ISSUING_CARD_COPY_BUTTON_ELEMENT),Object(p.a)(Qe,C.e.issuingCardCvcDisplay,Ye.a.ISSUING_CARD_CVC_DISPLAY_ELEMENT),Object(p.a)(Qe,C.e.issuingCardExpiryDisplay,Ye.a.ISSUING_CARD_EXPIRY_DISPLAY_ELEMENT),Object(p.a)(Qe,C.e.issuingCardPinDisplay,Ye.a.ISSUING_CARD_PIN_DISPLAY_ELEMENT),Object(p.a)(Qe,C.e.epsBank,Ye.a.EPS_BANK_ELEMENT),Object(p.a)(Qe,C.e.netbankingBank,Ye.a.NETBANKING_BANK_ELEMENT),Object(p.a)(Qe,C.e.afterpayClearpayMessageModal,Ye.a.AFTERPAY_MESSAGE_MODAL_ELEMENT),Object(p.a)(Qe,C.e.autocompleteSuggestions,Ye.a.AUTOCOMPLETE_SUGGESTIONS_ELEMENT),Object(p.a)(Qe,C.e.achBankSearchResults,Ye.a.ACH_BANK_SEARCH_RESULTS_ELEMENT),Qe),dt=function(e){var t=Object(v.e)(e,null);return!!t&&"rtl"===t.getPropertyValue("direction")},pt=n(44),ft=n(57),mt=function(e){var t=document.createElement("input");return t.className=e,t.setAttribute("aria-hidden","true"),t.setAttribute("aria-label"," "),t.setAttribute("autocomplete","false"),t.maxLength=1,t.disabled=!0,Object(v.l)(t,ft.b),t},ht={margin:"0",padding:"0",border:"none",display:"block",background:"transparent",position:"relative",opacity:"1"},_t=function(e){var t=e.name,n=e.value,r=e.expiresIn,a=e.path,o=e.domain,i=e.protocol,c=e.sameSite,s=void 0===c?"Lax":c,u=new Date,l=r||31536e6;u.setTime(u.getTime()+l);var d=a||"/",p=(n||"").replace(/[^!#-+\--:<-[\]-~]/g,encodeURIComponent),f="".concat(encodeURIComponent(t),"=").concat(p,";expires=").concat(u.toGMTString(),";path=").concat(d,";SameSite=").concat(s);return o&&(f+=";domain=".concat(o)),"https:"===i&&(f+=";secure"),document.cookie=f,f},bt=function(e){var t=Object(w.a)(document.cookie.split("; "),(function(t){var n=t.indexOf("=");try{return decodeURIComponent(t.substr(0,n))===e}catch(e){return!1}}));if(!t)return null;var n=t.indexOf("=");try{return decodeURIComponent(t.substr(n+1))}catch(e){return null}},yt=n(67),vt=n.n(yt),Ot=C.n.replace(/\/$/,"");var gt="_1776170249",jt="__1104211103",wt=function(e){var t,n=(t={},Object(p.a)(t,gt,!0),Object(p.a)(t,jt,!1),t);try{var r=Object(g.a)(e.slice(e.indexOf("?")+1));Object.keys(r).forEach((function(e){var t=vt()(e),a=r[e];switch(t){case gt:"false"===a&&(n[t]=!1);break;case jt:"true"===a&&(n[t]=!0)}}))}catch(e){}return n}(function(e){try{if(e.currentScript)return e.currentScript.src;var t=e.querySelectorAll('script[src^="'.concat(Ot,'"]')),n=Object(w.a)(t,(function(e){var t=(e.getAttribute("src")||"").split("?")[0];return new RegExp("^".concat(Ot,"/?$")).test(t)}));return n&&n.getAttribute("src")||""}catch(e){return""}}(document)),kt=wt._1776170249,Et=wt.__1104211103,St=n(46),Pt=n(24);function At(e,t,n){return(At="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,n){var r=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=Object(Pt.a)(e)););return e}(e,t);if(r){var a=Object.getOwnPropertyDescriptor(r,t);return a.get?a.get.call(n):a.value}})(e,t,n||e)}var It,Ct=function(e){Object(z.a)(n,e);var t=Object(K.a)(n);function n(e){var r,a=e.type,o=e.controllerId,i=e.listenerRegistry,c=e.betas,s=e.appParams;return Object(l.a)(this,n),(r=t.call(this))._sendFAReq=function(e){var t=b(e.tag);return new E.a((function(n,a){r._requests[t]={resolve:n,reject:a},r._send({message:{action:"stripe-frame-action",payload:{nonce:t,faReq:e}},type:"outer",frameId:r.id,controllerId:r._controllerId})}))},r.action={perform3DS2Challenge:function(e){return r._sendFAReq({tag:"PERFORM_3DS2_CHALLENGE",value:e})},perform3DS2Fingerprint:function(e){return r._sendFAReq({tag:"PERFORM_3DS2_FINGERPRINT",value:e})},performOneClickWebauthnAuthentication:function(e){return r._sendFAReq({tag:"PERFORM_ONE_CLICK_WEBAUTHN_AUTHENTICATION",value:e})},show3DS2Spinner:function(e){return r._sendFAReq({tag:"SHOW_3DS2_SPINNER",value:e})},checkCanMakePayment:function(e){return r._sendFAReq({tag:"CHECK_CAN_MAKE_PAYMENT",value:e})},closeLightboxFrame:function(e){return r._sendFAReq({tag:"CLOSE_LIGHTBOX_FRAME",value:e})},openLightboxFrame:function(e){return r._sendFAReq({tag:"OPEN_LIGHTBOX_FRAME",value:e})},setFocusTarget:function(e){return r._sendFAReq({tag:"SET_FOCUS_TARGET",value:e})}},r.type=a,r.loaded=!1,r._controllerId=o,r._persistentMessages=[],r._queuedMessages=[],r._requests={},r._listenerRegistry=i,r.id=r._generateId(),r._iframe=r._createIFrame(a,c,s),r._on("load",(function(){r.loaded=!0,r._ensureMounted(),r.loaded&&(r._persistentMessages.forEach((function(e){return r._send(e)})),r._queuedMessages.forEach((function(e){return r._send(e)})),r._queuedMessages=[])})),r._on("title",(function(e){var t=e.title;r._iframe.setAttribute("title",t)})),r}return Object(d.a)(n,[{key:"_generateId",value:function(){return b("__privateStripeFrame")}},{key:"send",value:function(e){this._send({message:e,type:"outer",frameId:this.id,controllerId:this._controllerId})}},{key:"sendPersistent",value:function(e){this._ensureMounted();var t={message:e,type:"outer",frameId:this.id,controllerId:this._controllerId};this._persistentMessages=[].concat(Object(u.a)(this._persistentMessages),[t]),this.loaded&&Object(Ye.f)(t)}},{key:"resolve",value:function(e,t){this._requests[e]&&this._requests[e].resolve(t)}},{key:"reject",value:function(e,t){this._requests[e]&&this._requests[e].reject(t)}},{key:"_send",value:function(e){this._ensureMounted(),this.loaded?Object(Ye.f)(e):this._queuedMessages=[].concat(Object(u.a)(this._queuedMessages),[e])}},{key:"appendTo",value:function(e){this._emit("mount",{anchor:e}),e.appendChild(this._iframe)}},{key:"prependTo",value:function(e,t){this._emit("mount",{anchor:e,parent:t}),t.insertBefore(this._iframe,e)}},{key:"unmount",value:function(){this.loaded=!1,this._emit("unload")}},{key:"destroy",value:function(){this.unmount();var e=this._iframe.parentElement;e&&e.removeChild(this._iframe),this._emit("destroy")}},{key:"_ensureMounted",value:function(){this._isMounted()||this.unmount()}},{key:"_isMounted",value:function(){return!!document.body&&document.body.contains(this._iframe)}},{key:"_createIFrame",value:function(e,t,n){var r=window.location.href.toString(),a="string"==typeof n?n:Object(g.j)(Object(s.a)(Object(s.a)({},n||{}),{},{referrer:r,controllerId:this._controllerId})),o=document.createElement("iframe");o.setAttribute("name",this.id);var i=Object(Ye.b)(e);return Object.keys(i).forEach((function(e){o.setAttribute(e,i[e])})),(null==n?void 0:n.allowCamera)&&o.setAttribute("allow","camera"),o.src="".concat(Object(Ye.c)(e)).concat(a?"#":"").concat(a),o}}]),n}(Y),Tt=function(e){Object(z.a)(n,e);var t=Object(K.a)(n);function n(e){var r;if(Object(l.a)(this,n),(r=t.call(this,e)).autoload=e.autoload||!1,"complete"===document.readyState)r._ensureMounted();else{var a=r._ensureMounted.bind(Object(G.a)(r));r._listenerRegistry.addEventListener(document,"DOMContentLoaded",a),r._listenerRegistry.addEventListener(window,"load",a),setTimeout(a,5e3)}return r}return Object(d.a)(n,[{key:"_ensureMounted",value:function(){At(Object(Pt.a)(n.prototype),"_ensureMounted",this).call(this),this._isMounted()||this._autoMount()}},{key:"_autoMount",value:function(){var e=document.body;if(e){var t=document.querySelector("#stripe-hidden-frames-container")||e;this.appendTo(t)}else if("complete"===document.readyState||"interactive"===document.readyState)throw new k.b("Stripe.js requires that your page has a element.");this.autoload&&(this.loaded=!0)}},{key:"_createIFrame",value:function(e,t,r){var a=At(Object(Pt.a)(n.prototype),"_createIFrame",this).call(this,e,t,r);return a.setAttribute("aria-hidden","true"),a.setAttribute("tabIndex","-1"),Object(v.k)(a),a}}]),n}(Ct),Nt=function(e){Object(z.a)(n,e);var t=Object(K.a)(n);function n(){return Object(l.a)(this,n),t.apply(this,arguments)}return Object(d.a)(n,[{key:"_generateId",value:function(){return this._controllerId}}]),n}(Tt),Mt="__privateStripeMetricsController",Rt="merchant",xt="session",Bt="NA",Lt=function(e){return 42===e.length},Dt=function(e,t,n){return n?!e||!Lt(e)&&Lt(t)?t:e:y()},qt=function(){function e(){var t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(Object(l.a)(this,e),this._controllerFrame=null,this._latencies=[],this._handleMessage=function(e){return function(n){var r=n.data,a=n.origin;if(Object(g.g)(a)&&"string"==typeof r)try{var o=JSON.parse(r),i=o.originatingScript,c=o.payload;if("m2"===i){var s=c.guid,u=c.muid,l=c.sid;t._guid=s,t._muid=t._getID(Rt,u),t._sid=t._getID(xt,l),e()}}catch(e){}}},n.checkoutIds){var r=n.checkoutIds,a=r.muid,o=r.sid;this._guid=Bt,this._muid=a,this._sid=o,this._doNotPersist="NA"!==a&&"NA"!==o}else this._guid=Bt,this._muid=this._getID(Rt),this._sid=this._getID(xt),this._doNotPersist=!1;this._listenerRegistry=Object(St.a)(),this._idsPromise=new E.a((function(e){t._establishMessageChannel(e)})),this._id=b(Mt),kt&&(this._controllerFrame=new Nt({type:Ye.a.METRICS_CONTROLLER,controllerId:this._id,listenerRegistry:this._listenerRegistry,autoload:!0,appParams:this._buildFrameQueryString()}),this._startIntervalCheck(),setTimeout(this._testLatency.bind(this),2e3+500*Math.random()))}return Object(d.a)(e,[{key:"ids",value:function(){return{guid:this._guid,muid:this._muid,sid:this._sid}}},{key:"idsPromise",value:function(){var e=this;return this._idsPromise.then((function(){return e.ids()}))}},{key:"_establishMessageChannel",value:function(e){if(!kt)return this._guid=y(),void e();this._listenerRegistry.addEventListener(window,"message",this._handleMessage(e))}},{key:"_startIntervalCheck",value:function(){var e=this,t=window.location.href;setInterval((function(){var n=window.location.href;n!==t&&(e.send((function(e){return{action:"ping",payload:{sid:e.sid,muid:e.muid,title:document.title,referrer:document.referrer,url:document.location.href,version:6}}})),t=n)}),5e3)}},{key:"report",value:function(e,t){this.send((function(n){return{action:"track",payload:{sid:n.sid,muid:n.muid,url:document.location.href,source:e,data:t,version:6}}}))}},{key:"send",value:function(e){var t=this;this._idsPromise.then((function(){try{t._controllerFrame&&t._controllerFrame.send(e(t.ids()))}catch(e){}}))}},{key:"_testLatency",value:function(){var e=this,t=new Date;this._listenerRegistry.addEventListener(document,"mousemove",(function n(){try{var r=new Date;e._latencies.push(r-t),e._latencies.length>=10&&(e.report("mouse-timings-10",e._latencies),e._listenerRegistry.removeEventListener(document,"mousemove",n)),t=r}catch(e){}}))}},{key:"_extractMetaReferrerPolicy",value:function(){var e=document.querySelector("meta[name=referrer]");return null!=e&&e instanceof HTMLMetaElement?e.content.toLowerCase():null}},{key:"_extractUrl",value:function(e){var t=document.location.href;switch(e){case"origin":case"strict-origin":case"origin-when-cross-origin":case"strict-origin-when-cross-origin":return document.location.origin;case"unsafe-url":return t.split("#")[0];default:return t}}},{key:"_buildFrameQueryString",value:function(){var e=this._extractMetaReferrerPolicy(),t=this._extractUrl(e),n={url:t,title:document.title,referrer:document.referrer,muid:this._muid,sid:this._sid,version:6,preview:Object(g.g)(t)};return null!=e&&(n.metaReferrerPolicy=e),Object.keys(n).map((function(e){return null!=n[e]?"".concat(e,"=").concat(encodeURIComponent(n[e].toString())):null})).join("&")}},{key:"_getID",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Bt;switch(e){case Rt:if(this._doNotPersist)return Dt(this._muid,t,kt);try{var n="__stripe_mid",r=Dt(bt(n),t,kt);return Lt(r)&&_t({name:n,value:r,domain:".".concat(document.location.hostname),protocol:document.location.protocol,sameSite:"Strict"}),r}catch(e){return Bt}case xt:if(this._doNotPersist)return Dt(this._sid,t,kt);try{var a="__stripe_sid",o=Dt(bt(a),t,kt);return Lt(o)&&_t({name:a,value:o,domain:".".concat(document.location.hostname),protocol:document.location.protocol,sameSite:"Strict",expiresIn:18e5}),o}catch(e){return Bt}default:throw new Error("Invalid ID type specified: ".concat(e))}}}]),e}(),Ft=null,Ut=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Ft=new qt(e)},Ht=!1,Gt=function(){var e=Ft;e&&(Ht||(Ht=!0,e.send((function(e){return{action:"ping",payload:{v2:2,sid:e.sid,muid:e.muid,title:document.title,referrer:document.referrer,url:document.location.href,version:6}}})),e.send((function(t){return{action:"track",payload:{sid:t.sid,muid:t.muid,url:document.location.href,source:"mouse-timings-10-v2",data:e._latencies,version:6}}}))))},zt=["test_id"],Kt=function(e){switch(e.type){case"object":return zt.push(e.object.id),{issuingCard:e.object};case"error":return{error:e.error};default:return Object(m.a)(e)}},Yt=function(e){switch(e.type){case"object":return{nonce:e.object.public_nonce};case"error":return{error:e.error};default:return Object(m.a)(e)}},Wt={base:"StripeElement",focus:"StripeElement--focus",invalid:"StripeElement--invalid",complete:"StripeElement--complete",empty:"StripeElement--empty",webkitAutofill:"StripeElement--webkit-autofill"},Vt="#faffbd",Jt=function(e){return parseFloat(e.toFixed(1))},Xt=function(e){return/^\d+(\.\d*)?px$/.test(e)},$t=function(){function e(t){var n=this;Object(l.a)(this,e),this.focus=function(){if(n._isIssuingDisplayElement())throw new k.b("Cannot call focus() on an ".concat(n._componentName," Element."));document.activeElement&&document.activeElement.blur&&document.activeElement.blur(),n._fakeInput.focus()},this._formSubmit=function(){for(var e=n._component.parentElement;e&&"FORM"!==e.nodeName;)e=e.parentElement;if(e){var t=document.createEvent("Event");t.initEvent("submit",!0,!0),e.dispatchEvent(t)}};var r=t.options,a=t.component,o=t.listenerRegistry,i=t.elementTimings,c=t.emitEvent,s=t.getParent,u=t.hasRegisteredListener,d=Object(w.g)(r,["loader"]),p=d.controller,f=d.componentName,h=d.publicOptions;this._componentName=f,this._component=a,this._controller=p,this._listenerRegistry=o,this._emitEvent=c,this._getParent=s,this._hasRegisteredListener=u;var _=Object(m.H)(ut,h||{},"create()"),b=_.value;_.warnings.forEach((function(e){return n._controller.warn(e)}));var y,v=b.paymentRequest,O=b.classes,g=b.issuingCard,j="paymentRequestButton"===this._componentName;if(j){if(!v)throw new k.b("You must pass in a stripe.paymentRequest object in order to use this Element.");this._paymentRequest=v,this._paymentRequest._registerElement()}if(this._isIssuingDisplayElement()){if(!g)throw new Error("You must pass in an ID to the issuingCard option in order to use this Element.");if(y=g,-1===zt.indexOf(y))throw new Error("Issuing card ".concat(g," has not been retrieved."))}this._createElement(d,b,i),this._classes=Wt,this._computeCustomClasses(O||{}),this._lastBackgroundColor="",this._focused=!1,this._empty=!j,this._invalid=!1,this._complete=!1,this._autofilled=!1,this._lastSubmittedAt=null}return Object(d.a)(e,[{key:"update",value:function(e){var t=this,n=Object(m.H)(ut,e||{},"element.update()"),r=n.value;if(n.warnings.forEach((function(e){return t._controller.warn(e)})),r){var a=r.classes,o=Object(f.a)(r,["classes"]);a&&(this._removeClasses(),this._computeCustomClasses(a),this._updateClasses()),this._updateFrameHeight(r),Object.keys(o).length&&(this._frame.update(o),this._secondaryFrame&&this._secondaryFrame.update(o))}}},{key:"blur",value:function(){if(this._isIssuingDisplayElement())throw new k.b("Cannot call blur() on an ".concat(this._componentName," Element."));this._frame.blur(),this._fakeInput.blur()}},{key:"clear",value:function(){this._frame.clear()}},{key:"unmount",value:function(){var e=this._getParent(),t=this._label;e&&(this._listenerRegistry.removeEventListener(e,"click",this.focus),this._removeClasses()),t&&(this._listenerRegistry.removeEventListener(t,"click",this.focus),this._label=null),this._secondaryFrame&&(this._secondaryFrame.unmount(),this._listenerRegistry.removeEventListener(window,"click",this._handleOutsideClick)),this._fakeInput.disabled=!0,this._frame.unmount()}},{key:"mount",value:function(){if(Object(v.g)(document,this._component)){this._controller.report("user_error.shadow_dom_mount",{element:this._componentName});var e=function(){throw new k.b("Elements cannot be mounted in a ShadowRoot. Please mount in the Light DOM.")};"test"===this._controller.keyMode()?e():setTimeout(e,0)}if(this._paymentRequest){if(!this._paymentRequest._canMakePaymentResolved)throw new k.b("For the paymentRequestButton Element, you must first check availability using paymentRequest.canMakePayment() before mounting the Element.");if(!this._paymentRequest._activeBackingLibraryName)throw new k.b("The paymentRequestButton Element is not available in the current environment.")}this._mountTimestamp=new at.a,this._findPossibleLabel(),this._updateClasses()}},{key:"_isIssuingDisplayElement",value:function(){return"issuingCardNumberDisplay"===this._componentName||"issuingCardCvcDisplay"===this._componentName||"issuingCardExpiryDisplay"===this._componentName||"issuingCardPinDisplay"===this._componentName}},{key:"_updateClasses",value:function(){var e=this._getParent();e&&Object(v.n)(e,[[this._classes.base,!0],[this._classes.empty,this._empty],[this._classes.focus,this._focused],[this._classes.invalid,this._invalid],[this._classes.complete,this._complete],[this._classes.webkitAutofill,this._autofilled]])}},{key:"_removeClasses",value:function(){var e=this._getParent();e&&Object(v.n)(e,[[this._classes.base,!1],[this._classes.empty,!1],[this._classes.focus,!1],[this._classes.invalid,!1],[this._classes.complete,!1],[this._classes.webkitAutofill,!1]])}},{key:"_findPossibleLabel",value:function(){var e=this._getParent();if(e){var t,n=e.getAttribute("id");if(n&&(t=document.querySelector("label[for='".concat(n,"']"))),t)this._listenerRegistry.addEventListener(e,"click",this.focus);else for(t=t||e.parentElement;t&&"LABEL"!==t.nodeName;)t=t.parentElement;t?(this._label=t,this._listenerRegistry.addEventListener(t,"click",this.focus)):this._listenerRegistry.addEventListener(e,"click",this.focus)}}},{key:"_computeCustomClasses",value:function(e){var t={};return Object.keys(e).forEach((function(n){if(!Wt[n])throw new k.b("".concat(n," is not a customizable class name.\nYou can customize: ").concat(Object.keys(Wt).join(", ")));var r=e[n]||Wt[n];t[n]=r.replace(/\./g," ")})),this._classes=Object(s.a)(Object(s.a)({},this._classes),t),this}},{key:"_setupEvents",value:function(e,t,n){var r=this,a=e.stripeJsLoadTimestamp,o=(e.stripeCreateTimestamp,e.groupCreateTimestamp),i=e.createTimestamp,c=0,s=0,l={stripeJsLoad:a.getAsPosixTime(),stripeCreate:i.getAsPosixTime(),groupCreate:o.getAsPosixTime(),create:i.getAsPosixTime()};if(this._frame._on("load",(function(e){var t=e.source;c++;var n=r._getParent(),a=dt(n),o=r._paymentRequest?r._paymentRequest._buttonTypeName:null;r._mountTimestamp&&(l.mount=r._mountTimestamp.getAsPosixTime()),r._frame.send({action:"stripe-user-mount",payload:{timestamps:l,loadCount:c,matchFrame:t===r._frame._iframe.contentWindow,rtl:a,paymentRequestButtonType:o}})})),this._secondaryFrame){var d=this._secondaryFrame;d._on("load",(function(e){var t=e.source;s++,r._mountTimestamp&&(l.mount=r._mountTimestamp.getAsPosixTime()),d.send({action:"stripe-user-mount",payload:{timestamps:l,loadCount:s,matchFrame:t===d._iframe.contentWindow,rtl:!1,paymentRequestButtonType:null}})}))}this._frame._on("redirectfocus",(function(e){var t=e.focusDirection,n=Object(v.d)(r._component,t);n&&n.focus()})),this._frame._on("focus",(function(){r._focused=!0,r._updateClasses()})),this._frame._on("blur",(function(){r._focused=!1,r._updateClasses(),r._lastSubmittedAt&&"paymentRequestButton"===r._componentName&&(r._controller.report("payment_request_button.sheet_visible",{latency:r._lastSubmittedAt.getElapsedTime()}),r._lastSubmittedAt=null)})),this._frame._on("submit",(function(){if("paymentRequestButton"===r._componentName){r._lastSubmittedAt=new at.a;var e=!1,t=!1;Gt(),r._emitEvent("click",{preventDefault:function(){r._controller.report("payment_request_button.default_prevented"),e&&r._controller.warn("event.preventDefault() was called after the payment sheet was shown. Make sure to call it synchronously when handling the `click` event."),t=!0}}),!t&&r._paymentRequest&&(r._paymentRequest._elementShow(),e=!0)}else r._emitEvent("submit"),r._formSubmit()})),["ready","focus","blur","escape","click"].forEach((function(e){r._frame._on(e,(function(){r._emitEvent(e)}))})),this._frame._on("change",(function(e){Gt();var t={},n=U.a[r._componentName]||[];["error","value","empty","complete"].concat(Object(u.a)(n)).forEach((function(n){return t[n]=e[n]})),r._emitEvent("change",t),r._empty=t.empty,r._invalid=!!t.error,r._complete=t.complete,r._updateClasses()})),this._frame._on("__privateIntegrationError",(function(e){var t=e.message;r._emitEvent("__privateIntegrationError",{message:t})})),this._frame._on("networkschange-start",(function(){Object(j.d)(t,j.a.networks_change_1)&&r._hasRegisteredListener("networkschange")&&r._controller.action.isCardMetadataRequired({groupId:n.groupId}).then((function(e){return e&&r._emitNetworksChangeEvent(null,!0),r._controller.action.retrieveCardNetworks({groupId:n.groupId})})).then((function(e){e&&r._emitNetworksChangeEvent(e,!1)}))})),this._frame._on("dimensions",(function(e){var t=r._getParent();if(t){var n=Object(v.e)(t,null);if(n){var a=parseFloat(n.getPropertyValue("height")),o=e.height;if("border-box"===n.getPropertyValue("box-sizing")){var i=parseFloat(n.getPropertyValue("padding-top")),c=parseFloat(n.getPropertyValue("padding-bottom"));a=a-parseFloat(n.getPropertyValue("border-top"))-parseFloat(n.getPropertyValue("border-bottom"))-i-c}var s=Jt(a),u=Jt(o);0!==a&&s1&&void 0!==arguments[1]&&arguments[1],n=e.style;if("paymentRequestButton"===this._componentName){var r=n&&n.paymentRequestButton||{},a=r.height,o="string"==typeof a?a:void 0;(t||o)&&(this._frame.updateStyle({height:o||this._lastHeight||$,minHeight:"auto"}),this._lastHeight=o||this._lastHeight)}else{var i=n&&n.base||{},c=i.lineHeight,s=i.fontSize,u=i.padding,l="string"!=typeof c||isNaN(parseFloat(c))?void 0:c,d="string"==typeof s?s:void 0,p="string"==typeof u?u:void 0;if(d&&!Xt(d)&&this._controller.warn("The fontSize style you specified (".concat(d,") is not in px. We do not recommend using relative css units, as they will be calculated relative to our iframe's styles rather than your site's.")),t||l||d){var f=-1===C.l.indexOf(this._componentName)?void 0:p||this._lastPadding,m=Object(v.a)(l||this._lastHeight,d||this._lastFontSize,f);this._frame.updateStyle({height:m}),this._lastFontSize=d||this._lastFontSize,this._lastHeight=l||this._lastHeight,this._lastPadding=f}}}},{key:"_createElement",value:function(e,t,n){var r=this,a=(e.controller,e.publicOptions,e.componentName),o=e.groupId,i=Object(f.a)(e,["controller","publicOptions","componentName","groupId"]),c=(t.classes,t.paymentRequest,Object(f.a)(t,["classes","paymentRequest"])),u=this._component,l=mt(pt.c);Object(v.l)(u,ht);var d=dt(document.body),p=lt[a],m=Object(s.a)(Object(s.a)(Object(s.a)({},i),c),{},{rtl:d}),h=this._controller.createElementFrame(p,a,o,m);if(h._on("load",(function(){l.disabled=!1})),this._listenerRegistry.addEventListener(l,"focus",(function(){h.focus()})),h.appendTo(u),U.c[a]){var _=U.c[a].secondary,b=this._controller.createSecondaryElementFrame(p,_,a,o,m);b&&b.on&&b.on("height-change",(function(e){b.updateStyle({height:"".concat(e.height,"px")})})),this._secondaryFrame=b,b.appendTo(u),this._listenerRegistry.addEventListener(window,"click",(function(){return r._handleOutsideClick()}))}if(u.appendChild(l),O.i&&a!==C.e.paymentRequestButton){var y=function(){var e=mt(pt.d);return e.setAttribute("tabindex","-1"),e}();u.appendChild(y)}this._frame=h,this._fakeInput=l,this._setupEvents(n,e.betas,e),this._updateFrameHeight(t,!0)}}]),e}(),Qt=n(20),Zt={amount:m.r,currency:Object(m.u)("USD"),logoColor:Object(m.w)(Object(m.u)("primary","black","white")),fontColor:Object(m.w)(m.B),fontSize:Object(m.w)(m.B),textAlign:Object(m.w)(m.B),stripeMerchantId:Object(m.w)(m.B)},en=Object(m.y)(Zt),tn=function(e){var t=!1;window.Promise||(t=!0,window.Promise=E.a);var n=e();return t&&window.Promise===E.a&&delete window.Promise,n},nn=function(){return tn((function(){return n.e(3).then(n.bind(null,95))}))},rn=function(e){var t,r=e.options,a=Object(f.a)(e,["options"]),o=e.emitEvent,i=e.listenerRegistry,c=r.controller,l=r.componentName,d=r.publicOptions,p=r.groupId,h=new at.a,_=function(e){var t=Object(m.H)(en,e||{},"create()"),n=t.value,r=t.warnings;if(!Math.floor(n.amount)===n.amount)throw new k.b("'Amount' must be a whole integer number that represents the lowest denomination (cents).");return r.forEach((function(e){return c.warn(e)})),n},b=_(d),y=function(e,n){return e.apply(void 0,[t].concat(Object(u.a)(n)))},v=[],O=function(e){return function(){for(var n=arguments.length,r=new Array(n),a=0;a-1,d="payment"===t.componentName&&(u.value.parsedIntentSecret||null);if(l&&!t.clientSecret&&!d)throw new k.b("In order to create a ".concat(t.componentName,' element, you must pass a valid PaymentIntent or SetupIntent client secret when creating the Elements group.\n\n e.g. stripe.elements({clientSecret: "{{CLIENT_SECRET}}"})'));var p=Kn(Object(s.a)(Object(s.a)({},n),{},{options:Object(s.a)(Object(s.a)({},i),{},{controller:r,componentName:c,publicOptions:u.value})})),m=p.update,h=Object(f.a)(p,["update"]);return Object(s.a)({update:function(e){var n=jn(c,e||{},"".concat(c,".update()"),!0,t.betas);n.warnings.forEach((function(e){return r.warn(e)})),m(n.value)}},h)},Wn=Object.freeze({header:Object(m.w)(Object(m.y)({text:Object(m.w)(m.B)})),showOnAdd:Object(m.w)(Object(m.u)("auto","never"))}),Vn=Object.freeze(Object(s.a)({clientSecret:dn.c,descriptor:Object(m.w)(Object(m.u)("cart","bag","basket"))},Wn)),Jn=(Object.freeze(Object(s.a)({},Object(w.g)(Vn,["clientSecret"]))),Object.freeze({price:Object(m.w)(m.B),product:Object(m.w)(m.B),quantity:Object(m.w)(m.r)})),Xn=(Object.freeze(Object(s.a)(Object(s.a)({},Jn),{},{quantity:m.r,outerRequestId:m.r})),["ready","change","checkout"]),$n="StripeElement",Qn={margin:"0",padding:"0",border:"none",display:"block",background:"transparent",position:"relative",opacity:"1"},Zn={visibility:"hidden",position:"fixed",top:"0px",left:"100%",width:"100%",height:"100%","pointer-events":"none","max-width":"none","max-height":"none","min-width":"none","min-height":"none"},er={visibility:"visible",position:"fixed",top:"0px",left:"0px","z-index":"99999",width:"100%",height:"100%","pointer-events":"all","max-width":"none","max-height":"none","min-width":"none","min-height":"none"},tr=function(e){var t=e.component,n=e.getParent,r=e.emitEvent,a=e.options,o=e.selfDestruct,i={mounted:!1,frameReady:!1,visible:!1,showStarted:!1,releasePageScroll:null,restoreFocus:null,runOnUnmount:[],addRequestIdCounter:0};Object(v.l)(t,Qn);var c=function(e){var t=e.controller,n=e.componentName,r=e.groupId,a={fonts:e.fonts,wait:e.wait,rtl:!1,publicOptions:e.publicOptions,controllingElement:e.controllingElement};return t.createElementFrame(Ye.a.CART_ELEMENT,n,r,a)}(a);c.updateStyle(Zn),c.appendTo(t);var u=function(e){return function(t){i.mounted&&i.frameReady&&e(t)}},l=u((function(){i.visible||(i.visible=!0,c.updateStyle(er),c.show(),i.releasePageScroll=Object(v.i)(),(i.restoreFocus?i.restoreFocus():E.a.resolve()).then((function(){var e=Object(v.b)(c._iframe),t=e.lockedPromise,n=e.lockedElements;i.restoreFocus=function(){return Object(v.j)(t,n)}})))})),d=u((function(){i.visible&&(c.hide(),i.showStarted||(b(),y()))})),p=u((function(e){c.cancelCheckout(e)})),f=function(e){return function(){throw new k.b(e)}},m=f("focus() is not supported by the cart Element."),h=f("blur() is not supported by the cart Element."),_=f("clear() is not supported by the cart Element.");c._on("load-error",(function(e){null==r||r("loaderror",{error:e}),null==o||o()})),c._on("ready",(function(){i.frameReady=!0})),Xn.forEach((function(e){c._on(e,(function(t){return null==r?void 0:r(e,t)}))})),c._on("lineitemclick",(function(e){var t=e.url,n=!1;r("lineitemclick",{preventDefault:function(){n=!0},url:t}),n||(window.location.href=t)})),c._on("show-start",(function(){i.visible&&(i.showStarted=!0)}));var b=function(){var e,t;null===(e=i.releasePageScroll)||void 0===e||e.call(i),i.releasePageScroll=null,null===(t=i.restoreFocus)||void 0===t||t.call(i).then((function(){i.restoreFocus=null})),i.showStarted=!1,i.visible=!1},y=function(){i.visible||c.updateStyle(Zn)};return c._on("hide-start",b),c._on("hide-complete",y),c._on("show",l),{update:function(e){c.update(e)},focus:m,blur:h,clear:_,mount:function(){i.mounted=!0;var e=n();e&&(Object(v.n)(e,[[$n,!0]]),i.runOnUnmount.push((function(){Object(v.n)(e,[[$n,!1]])})));var t=function(){p()};window.addEventListener("beforeunload",t),i.runOnUnmount.push((function(){return window.removeEventListener("beforeunload",t)}));var r=function(e){"Escape"===e.code&&d()};window.addEventListener("keydown",r),i.runOnUnmount.push((function(){return window.removeEventListener("keydown",r)}))},unmount:function(){for(var e,t;i.runOnUnmount.length;){var n;null===(n=i.runOnUnmount.pop())||void 0===n||n()}null===(e=i.releasePageScroll)||void 0===e||e.call(i),null===(t=i.restoreFocus)||void 0===t||t.call(i),i.mounted=!1,i.releasePageScroll=null,i.restoreFocus=null,c.unmount()},show:l,hide:d,addLineItem:function(e){if(!i.frameReady||!i.mounted)return E.a.resolve({clientError:"initializing"});var t=++i.addRequestIdCounter;return c.addLineItem(Object(s.a)(Object(s.a)({},e),{},{quantity:e.quantity||1,outerRequestId:t})),new E.a((function(e){c._on("add-line-item-response",(function n(r){var a=r.outerRequestId,o=r.error;a===t&&(c._off("add-line-item-response",n),e(o?{error:o}:{}))}))}))},cancelCheckout:p,_frame:c}},nr=function(e){var t=e.options,n=Object(f.a)(e,["options"]),r=t.controller,a=t.publicOptions,o=(t.componentName,Object(f.a)(t,["controller","publicOptions","componentName"]));if(r.keyMode()===He.a.unknown)throw new k.b("It looks like you're using an older Stripe key. The Cart Element is only available for use with a modern API key, which is prefixed with 'pk_live_' or 'pk_test_'.\n You can roll your publishable key here: https://dashboard.stripe.com/account/apikeys");var i,c,u,l=(i=a||{},c="elements.create('cart', options)",Object(m.H)(Object(m.y)(Vn),i,c,u?{authenticatedOrigin:u}:null)),d=l.value,p=d.clientSecret,h=Object(f.a)(d,["clientSecret"]);l.warnings.forEach((function(e){return r.warn(e)}));var _={},b=function(e,t){return e.forEach((function(e){return r.warn(e)})),E.a.resolve({clientError:t})},y=tr(Object(s.a)(Object(s.a)({},n),{},{options:Object(s.a)(Object(s.a)({},o),{},{componentName:"cart",controller:r,publicOptions:h})})),v=y.update,O=y.cancelCheckout,g=y.addLineItem,j=Object(f.a)(y,["update","cancelCheckout","addLineItem"]);return r.action.fetchCartSession({clientSecret:p,groupId:t.groupId}).catch((function(t){e.emitEvent("loaderror",{error:t}),e.selfDestruct()})),Object(s.a)(Object(s.a)({},j),{},{update:function(e){var t=function(e,t,n){return Object(m.H)(Object(m.y)(Wn),e,t,n?{authenticatedOrigin:n}:null)}(e||{},"cart.update()"),n=t.value;t.warnings.forEach((function(e){return r.warn(e)})),v(n)},addLineItem:function(e){var t=function(e,t){var n=Object(m.H)(Object(m.y)(Jn),e,"cart.addLineItem()",t?{authenticatedOrigin:t}:null);return{value:n.value,warnings:n.warnings}}(e||{}),n=t.value,r=t.warnings,a=n.product||n.price;if(a){if(function(e){var t=Date.now(),n=_[e],r=void 0!==n&&t-n<200;return r||(_[e]=t),r}(a))return r.push("addLineItem() cannot be consecutively called within ".concat(200," milliseconds for the same price or product.")),b(r,"throttled")}else r.push("addLineItem() must be provided either a product or price.");return r.length?b(r,"integration"):g(n)},cancelCheckout:function(e){var t="string"==typeof e,n=t?e:"";t||r.warn("Expected a string passed to cancelCheckout(), but received ".concat(typeof e,".")),O(n)}})},rr=function(e,t){var n=function(e){if(!U.b[e])throw new Error("Unexpected Element type: ".concat(e,"."));return U.b[e].implementation}(e);switch(n){case"legacy":return new $t(t);case"affirm_message":return rn(t);case"afterpay_message":return sn(t);case"frame":return Yn(t);case"cart":return nr(t);default:return Object(m.a)(n,"Unexpected implementation type: ".concat(n,"."))}},ar=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Object(w.h)(e,["business","fields","paymentMethodOrder","readOnly","terms","wallets","allowedCardBrands","disallowedCardBrands","accountHolderType","disabled","hideIcon","hidePostalCode","iconStyle","placeholderCountry","rtl","showIcon","supportedCountries","betas","componentName","groupId","locale","loader"])},or=function(e){Object(z.a)(n,e);var t=Object(K.a)(n);function n(e,r,a){var o;Object(l.a)(this,n),(o=t.call(this)).mount=x((function(e){var t;if(o._checkDestroyed(),!e)throw new k.b("Missing argument. Make sure to call mount() with a valid DOM element or selector.");if("string"==typeof e){var n=document.querySelectorAll(e);if(n.length>1&&o._controller.warn("The selector you specified (".concat(e,") applies to ").concat(n.length," DOM elements that are currently on the page.\nThe Stripe Element will be mounted to the first one.")),!n.length)throw new k.b("The selector you specified (".concat(e,") applies to no DOM elements that are currently on the page.\nMake sure the element exists on the page before calling mount()."));t=n[0]}else{if(!e.appendChild)throw new k.b("Invalid DOM element. Make sure to call mount() with a valid DOM element or selector.");t=e}if("INPUT"===t.nodeName)throw new k.b("Stripe Elements must be mounted in a DOM element that\ncan contain child nodes. `input` elements are not permitted to have child\nnodes. Try using a `div` element instead.");t.children.length&&t!==document.body&&o._controller.warn("This Element will be mounted to a DOM element that contains child nodes."),o._mountToParent(t)})),o.update=x((function(e){return o._controller.report("update",{options:ar(e),element:o._componentName}),o._checkDestroyed(),o._implementation.update(e),Object(G.a)(o)})),o.focus=x((function(e){return o._checkDestroyed(),e&&e.preventDefault(),o._implementation.focus(),Object(G.a)(o)})),o.blur=x((function(){return o._checkDestroyed(),o._implementation.blur(),Object(G.a)(o)})),o.clear=x((function(){return o._checkDestroyed(),o._implementation.clear(),Object(G.a)(o)})),o.collapse=x((function(){if(o._checkDestroyed(),!o._implementation.collapse)throw new k.b("Collapse is not supported by the ".concat(o._componentName," Element."));return o._implementation.collapse(),Object(G.a)(o)})),o.show=x((function(){if(o._checkDestroyed(),!o._implementation.show)throw new k.b("show() is not supported by the ".concat(o._componentName," Element."));return o._implementation.show(),Object(G.a)(o)})),o.hide=x((function(){if(o._checkDestroyed(),!o._implementation.hide)throw new k.b("hide() is not supported by the ".concat(o._componentName," Element."));return o._implementation.hide(),Object(G.a)(o)})),o.addLineItem=x((function(e){if(o._checkDestroyed(),o._implementation.addLineItem)return o._implementation.addLineItem(e);throw new k.b("addLineItem() is not supported by the ".concat(o._componentName," Element."))})),o.cancelCheckout=x((function(e){if(o._checkDestroyed(),!o._implementation.cancelCheckout)throw new k.b("cancelCheckout() is not supported by the ".concat(o._componentName," Element."));return o._implementation.cancelCheckout(e),Object(G.a)(o)})),o.unmount=x((function(){return o._checkDestroyed(),o._unmount(),Object(G.a)(o)})),o.destroy=x((function(){return o._checkDestroyed(),o.unmount(),o._destroyed=!0,o._emitEvent("destroy"),Object(G.a)(o)})),o._getParent=function(){return o._parent},o._emitEvent=function(e,t){return"loaderror"!==e||o._hasRegisteredListener("loaderror")||o._controller.keyMode()!==He.a.test||console.error("Unhandled ".concat(o._componentName," Element loaderror"),t),o._emit(e,Object(s.a)({elementType:o._componentName},t))};var i=e.controller,c=e.componentName,u=e.groupId,d=e.locale,p=e.betas,f=e.mids;o._controller=i,o._componentName=c,o._destroyed=!1,o._mids=f;var m=document.createElement("div");return m.className=U.d,o._component=m,i.report("create",{options:ar(Object(s.a)({componentName:c,groupId:u,locale:d,betas:p},e.publicOptions)),element:c}),o._implementation=rr(o._componentName,{options:e,component:m,listenerRegistry:r,elementTimings:a,emitEvent:o._emitEvent,getParent:o._getParent,hasRegisteredListener:o._hasRegisteredListener,selfDestruct:function(){o.destroy()}}),o}return Object(d.a)(n,[{key:"_checkDestroyed",value:function(){if(this._destroyed)throw new k.b("This Element has already been destroyed. Please create a new one.")}},{key:"_isMounted",value:function(){return!!document.body&&document.body.contains(this._component)}},{key:"_unmount",value:function(){var e=this._component.parentElement;e&&e.removeChild(this._component),this._implementation.unmount(),this._parent=null}},{key:"_mountToParent",value:function(e){var t=this._component.parentElement,n=this._isMounted();if(e===t){if(n)return;this.unmount(),this._mountTo(e)}else if(t){if(n)throw new k.b("This Element is already mounted. Use `unmount()` to unmount the Element before re-mounting.");this.unmount(),this._mountTo(e)}else this._mountTo(e)}},{key:"_mountTo",value:function(e){for(this._parent=e;e.firstChild&&e!==document.body;)e.removeChild(e.firstChild);e.appendChild(this._component),this._controller.report("mount",{element:this._componentName}),this._implementation.mount()}}]),n}(Y),ir=function(e,t){e._controller.report("legacy_private_property_used",{prop:t,componentName:e._componentName})};["_autofilled","_classes","_complete","_empty","_fakeInput","_focused","_frame","_invalid","_lastBackgroundColor","_lastFontSize","_lastHeight","_lastPadding","_lastSubmittedAt","_listenerRegistry","_paymentRequest"].forEach((function(e){Object.defineProperty(or.prototype,e,{enumerable:!1,get:function(){return ir(this,e),this._implementation[e]}})}));["_formSubmit","_isIssuingDisplayElement"].forEach((function(e){Object.defineProperty(or.prototype,e,{enumerable:!1,writable:!1,value:function(){return ir(this,e),this._implementation[e]()}})}));var cr=or,sr=Object(m.y)({locale:Object(m.w)(m.B),appearance:Object(m.w)(m.t)}),ur=function e(t,n,r,a,o,i){var c=this;Object(l.a)(this,e),this.getElement=x((function(e){var t,n=(null!=(t=e)&&t.__elementType&&"string"==typeof t.__elementType&&"function"==typeof t?t.__elementType:null)||e;return H(n,c._betas),Object(w.a)(c._elements,(function(e){return e._componentName===n}))||null})),this.update=x((function(e){var t=Object(m.H)(sr,e||{},"elements.update()"),n=t.value;t.warnings.forEach((function(e){return c._controller.warn(e)}));var r=n.locale,a=n.appearance,o=void 0===a?void 0:a,i=Object(j.f)(r,c._betas);i&&c._controller.action.fetchLocale({locale:i}),(o||i)&&c._controller.action.updateElementsOptions({locale:i,appearance:o,groupId:c._id})})),this.create=B((function(e,t){var n=new at.a;!function(e,t,n){if(H(e,n),U.b[e].unique&&-1!==t.indexOf(e))throw new k.b("Can only create one Element of type ".concat(e,"."));var r=U.b[e].conflict,a=Object(w.i)(t,r);if(a.length){var o=a[0];throw new k.b("Cannot create an Element of type ".concat(e," after an Element of type ").concat(o," has already been created."))}}(e,c._elements.map((function(e){return e._componentName})),c._betas);var r=Object(s.a)(Object(s.a)(Object(s.a)({},t),c._commonOptions),{},{componentName:e,groupId:c._id}),a=(r.paymentRequest,Object(f.a)(r,["paymentRequest"])),o=(O.e||O.g)&&Object(g.j)(a).length>2e3,i=!!c._pendingFonts||o,l=new cr(Object(s.a)(Object(s.a)({publicOptions:t},c._commonOptions),{},{componentName:e,groupId:c._id,fonts:o?null:c._commonOptions.fonts,controller:c._controller,wait:i,mids:c._mids}),c._listenerRegistry,Object(s.a)(Object(s.a)({},c._timings),{},{createTimestamp:n}));return c._elements=[].concat(Object(u.a)(c._elements),[l]),l._on("destroy",(function(){c._elements=c._elements.filter((function(t){return t._componentName!==e}))})),o&&l._implementation.update({fonts:c._commonOptions.fonts}),l})),this.fetchUpdates=L((function(){if(c._commonOptions.clientSecret)return c._controller.action.fetchUpdates({clientSecret:c._commonOptions.clientSecret,customerOptions:c._customerOptions,locale:c._commonOptions.locale,groupId:c._id}).then((function(e){if("error"===(null==e?void 0:e.type)){var t=e.error,n=t.message,r=t.extra_fields;return(null==r?void 0:r.status)?{error:{message:n,status:r.status}}:{error:{message:n}}}return{}}));throw new k.b('In order to call fetchUpdates, you must pass a valid PaymentIntent or SetupIntent client secret when creating the Elements group.\n\n e.g. stripe.elements({clientSecret: "{{CLIENT_SECRET}}"})')}));var d=new at.a,p=Object(m.H)(function(e){var t={locale:Object(m.w)(m.B),fonts:Object(m.w)(Object(m.b)(m.t)),appearance:Object(m.w)(m.t),clientSecret:Object(m.w)(dn.d),loader:Object(m.w)(Object(m.u)("auto","always","never"))};return Object(j.d)(e,j.a.elements_customers_beta_1)?Object(m.y)(Object(s.a)(Object(s.a)({},t),{},{customerOptions:Object(m.w)(Object(m.y)({customer:m.B,ephemeralKey:m.B}))})):Object(m.y)(t)}(a),i||{},"elements()"),h=p.value;p.warnings.forEach((function(e){return t.warn(e)})),Object(v.p)(t.warn),t.report("elements",{options:h}),h.loader||(Object(j.d)(a,j.a.link_beta_3)?h.loader="auto":h.loader="never");var _=h.fonts,y=void 0===_?[]:_,E=h.locale,S=h.customerOptions,P=void 0===S?null:S,A=Object(f.a)(h,["fonts","locale","customerOptions"]);this._customerOptions=P;var I=h.appearance?h.appearance:{};this._elements=[],this._id=b("elements"),this._timings=Object(s.a)(Object(s.a)({},r),{},{groupCreateTimestamp:d}),this._controller=t,this._betas=a,this._listenerRegistry=n,this._mids=o;var C=Object(j.f)(E,a);this._controller.action.fetchLocale({locale:C||"auto"});var T=y.filter((function(e){return!e.cssSrc||"string"!=typeof e.cssSrc})).map((function(e){return Object(s.a)(Object(s.a)({},e),{},{__resolveFontRelativeTo:window.location.href})})),M=y.map((function(e){return e.cssSrc})).reduce((function(e,t){return"string"==typeof t?[].concat(Object(u.a)(e),[t]):e}),[]).map((function(e){return Object(g.d)(e)?e:Object(g.h)(window.location.href,e)}));(this._pendingFonts=M.length,Object(j.d)(a,j.a.payment_element_beta_1)&&!A.clientSecret||t.action.setupStoreForElementsGroup({clientSecret:A.clientSecret,customerOptions:P,locale:E,appearance:I,groupId:this._id}),this._commonOptions=Object(s.a)(Object(s.a)({},A),{},{betas:a,appearance:I,locale:C,fonts:T}),M.forEach((function(e){if("string"==typeof e){var t=new at.a;N(e).then((function(n){c._controller.report("font.loaded",{load_time:t.getElapsedTime(),font_count:n.length,css_src:e});var r=n.map((function(t){return Object(s.a)(Object(s.a)({},t),{},{__resolveFontRelativeTo:e})}));c._controller.action.updateCSSFonts({fonts:r,groupId:c._id}),c._commonOptions=Object(s.a)(Object(s.a)({},c._commonOptions),{},{fonts:[].concat(Object(u.a)(c._commonOptions.fonts?c._commonOptions.fonts:[]),Object(u.a)(r))})})).catch((function(n){c._controller.report("error.font.not_loaded",{load_time:t.getElapsedTime(),message:n&&n.message&&n.message,css_src:e}),c._controller.warn("Failed to load CSS file at ".concat(e,"."))}))}})),"never"!==h.loader)&&function(e){return It||((It=e.createHiddenFrame(Ye.a.LOADER_UI_APP,{}))._on("generate-loader-ui",(function(e){It.send({action:"generate-loader-ui",payload:{data:e}})})),It._on("get-element-loader-ui",(function(e){It.send({action:"get-element-loader-ui",payload:{}})})),It)}(t)._emit("generate-loader-ui",{rawAppearanceConfig:I});return this},lr=function(e,t,n,r,a,o,i){return new it({controller:e,authentication:t,mids:n,rawOptions:r,betas:a,queryStrategyOverride:o,listenerRegistry:i})},dr=Object(m.y)({name:Object(m.u)("react-stripe-js","stripe-js","react-stripe-elements"),version:Object(m.q)(m.B),startTime:Object(m.w)(m.r)}),pr=Object(m.h)({name:Object(m.z)(1,30),partner_id:Object(m.w)(Object(m.A)("pp_partner_")),version:Object(m.w)(Object(m.z)(5,15)),url:Object(m.w)(Object(m.z)(4,60))}),fr=n(11),mr={border:"none",margin:"0",padding:"0",width:"1px","min-width":"100%",overflow:"hidden",display:"block","user-select":"none",transform:"translate(0)","color-scheme":"only light"},hr=function(e){Object(z.a)(n,e);var t=Object(K.a)(n);function n(e){var r;return Object(l.a)(this,n),r=t.call(this,e),O.j&&r._listenerRegistry.addEventListener(document,"transitionstart",(function(e){switch(e.propertyName){case"opacity":case"transform":case"visibility":var t=e.target;r._isMounted()&&t.contains(r._iframe)&&r._forceRepaint()}}),{passive:!0}),r}return Object(d.a)(n,[{key:"update",value:function(e){this.send({action:"stripe-user-update",payload:e})}},{key:"updateStyle",value:function(e){var t=this;Object.keys(e).forEach((function(n){t._iframe.style[n]=e[n]}))}},{key:"focus",value:function(){this.loaded&&(O.j?this._iframe.focus():this.send({action:"stripe-user-focus",payload:{}}))}},{key:"blur",value:function(){this.loaded&&(this._iframe.contentWindow.blur(),this._iframe.blur(),document.activeElement===this._iframe&&(window.focus(),document.activeElement&&"function"==typeof document.activeElement.blur&&document.activeElement.blur()))}},{key:"clear",value:function(){this.send({action:"stripe-user-clear",payload:{}})}},{key:"collapse",value:function(){this.send({action:"stripe-user-collapse",payload:{}})}},{key:"show",value:function(){this.send({action:"stripe-user-show",payload:{}})}},{key:"hide",value:function(){this.send({action:"stripe-user-hide",payload:{}})}},{key:"addLineItem",value:function(e){this.send({action:"stripe-user-add-line-item",payload:e})}},{key:"cancelCheckout",value:function(e){this.send({action:"stripe-user-cancel-checkout",payload:{errorMessage:e}})}},{key:"_createIFrame",value:function(e,t,r){var a=At(Object(Pt.a)(n.prototype),"_createIFrame",this).call(this,e,t,r);return a.setAttribute("title","Secure payment input frame"),Object(v.l)(a,mr),a}},{key:"_forceRepaint",value:function(){var e=this._iframe,t=e.style.display;e.style.display="none";var n=e.offsetHeight;return e.style.display=t,n}}]),n}(Ct),_r={position:"absolute",left:"0",top:"0",height:"100%",width:"100%"},br=function(e){Object(z.a)(n,e);var t=Object(K.a)(n);function n(e){var r,a,o,i=e.type,c=e.controllerId,s=e.listenerRegistry,u=e.options;return Object(l.a)(this,n),(o=t.call(this,{type:i,controllerId:c,listenerRegistry:s,appParams:u}))._autoMount=function(){o.appendTo(o._backdrop.domElement),o._backdrop.mount()},o.show=function(){o._backdrop.show(),Object(v.l)(o._iframe,_r),o.isVisible=!0},o.fadeInBackdrop=function(){o._backdrop.fadeIn()},o._backdropFadeoutPromise=null,o.fadeOutBackdrop=function(){return o._backdropFadeoutPromise||(o._backdropFadeoutPromise=o._backdrop.fadeOut()),o._backdropFadeoutPromise.then((function(){o._backdropFadeoutPromise=null}))},o.destroy=function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=o.fadeOutBackdrop().then((function(){o._backdrop.unmount(),e||At((r=Object(G.a)(o),Object(Pt.a)(n.prototype)),"destroy",r).call(r)}));return e&&At((a=Object(G.a)(o),Object(Pt.a)(n.prototype)),"destroy",a).call(a),o.isVisible=!1,t},o._backdrop=new Je({lockScrolling:!0,lockFocus:!0,lockFocusOn:o._iframe,listenerRegistry:s}),o._autoMount(),o.isVisible=!1,o}return n}(Ct),yr={display:"block",position:"absolute","z-index":"1000",width:"1px","min-width":"100%",margin:"2px 0 0 0",padding:"0",border:"none",overflow:"hidden"},vr=function(e){Object(z.a)(n,e);var t=Object(K.a)(n);function n(){return Object(l.a)(this,n),t.apply(this,arguments)}return Object(d.a)(n,[{key:"updateStyle",value:function(e){var t=this;Object.keys(e).forEach((function(n){t._iframe.style[n]=e[n]}))}},{key:"update",value:function(e){this.send({action:"stripe-user-update",payload:e})}},{key:"_createIFrame",value:function(e,t,r){var a=At(Object(Pt.a)(n.prototype),"_createIFrame",this).call(this,e,t,r&&"object"==typeof r?Object(s.a)(Object(s.a)({},r),{},{isSecondaryFrame:!0}):r);return Object(v.l)(a,yr),a.style.height="0",a}}]),n}(Ct),Or=!1,gr=function(e){Or||"null"===(null!=e?e:window.origin)&&(Or=!0,console.error("Stripe.js requires 'allow-same-origin' if sandboxed."))},jr=n(22),wr={attachLinkAccountSessionForPayment:null,attachLinkAccountSessionForSetup:null,authenticate3DS2:null,cancelCardImageVerificationChallenge:null,cancelPaymentIntentSource:null,cancelSetupIntentSource:null,completeLinkAccountSessionElements:null,completeWalletConfirm:null,confirmPaymentIntent:null,confirmReturnIntent:null,confirmSetupIntent:null,createAcssDebitSession:null,createApplePaySession:null,createBankPaymentDetails:null,createConsumerPaymentDetails:null,createEphemeralKeyNonce:null,createPaymentMethodWithData:null,createPaymentMethodWithElement:null,createPaymentPage:null,createPaymentPageWithSession:null,createRadarSession:null,createSourceWithData:null,createSourceWithElement:null,fetchingWallets:null,fetchLocale:null,fetchUpdates:null,localizeError:null,loginWithConsumerInfo:null,lookupLocale:null,refreshPaymentIntent:null,refreshSetupIntent:null,retrieveIssuingCard:null,retrieveIssuingCardWithoutNonce:null,retrieveOrder:null,retrievePaymentIntent:null,retrieveSetupIntent:null,retrieveSource:null,fetchCartSession:null,setupStoreForElementsGroup:null,submitOrder:null,tokenizeCvcUpdate:null,tokenizeWithData:null,tokenizeWithElement:null,updateCSSFonts:null,updateElementsOptions:null,updateOrder:null,updatePaymentIntent:null,verifyCardImageVerificationChallenge:null,verifyMicrodepositsForPayment:null,verifyMicrodepositsForSetup:null,retrieveCardNetworks:null,isCardMetadataRequired:null},kr=function(){function e(){var t=this;Object(l.a)(this,e),this._state="pending",this._state="pending",this.promise=new E.a((function(e,n){t._resolve=e,t._reject=n})),this.promise.then((function(){t._state="resolved"}),(function(){t._state="rejected"}))}return Object(d.a)(e,[{key:"resolve",value:function(e){this._resolve(e)}},{key:"reject",value:function(e){this._reject(e)}},{key:"isResolved",value:function(){return"resolved"===this._state}},{key:"isRejected",value:function(){return"rejected"===this._state}},{key:"isPending",value:function(){return"pending"===this._state}}]),e}(),Er=!1,Sr={},Pr=function(e,t){return document.activeElement===e._iframe||e._iframe.parentElement&&document.activeElement===t},Ar=function(e){return"object"==typeof e&&null!==e&&"IntegrationError"===e.name?new k.b("string"==typeof e.message?e.message:""):e},Ir=function(){function e(t){var n=this;Object(l.a)(this,e),this._sendCaReq=function(e,t){var r=b(e),a=new kr;return n._requests[r]=a,n._controllerFrame.send({action:"stripe-controller-action-request",payload:{nonce:r,actionName:e,request:t}}),a.promise},this.keyMode=function(){return Object(He.c)(n._apiKey)},this.action=Object.keys(wr).reduce((function(e,t){return Object(s.a)(Object(s.a)({},e),{},Object(p.a)({},t,(function(e){return n._sendCaReq(t,e)})))}),{}),this.createElementFrame=function(e,t,r,a){var o=n._betas,i=new hr({type:e,betas:o,controllerId:n._id,listenerRegistry:n._listenerRegistry,appParams:Object(s.a)(Object(s.a)({},a),{},{componentName:t,keyMode:Object(He.c)(n._apiKey),apiKey:n._apiKey})});return n._setupFrame(i,e,r)},this.createSecondaryElementFrame=function(e,t,r,a,o){var i=n._betas,c=new vr({type:e,betas:i,controllerId:n._id,listenerRegistry:n._listenerRegistry,appParams:Object(s.a)(Object(s.a)({},o),{},{componentName:t,primaryElementType:r,keyMode:Object(He.c)(n._apiKey)})});return n._setupFrame(c,e,a)},this.createHiddenFrame=function(e,t){var r=new Tt({type:e,betas:n._betas,controllerId:n._id,listenerRegistry:n._listenerRegistry,appParams:t});return n._setupFrame(r,e)},this.getCredentials=function(){return{publishableKey:n._apiKey,stripeAccount:n._stripeAccount,apiVersion:n._apiVersion}},this.createLightboxFrame=function(e){var t=e.type,r=e.options,a=new br({type:t,controllerId:n._id,listenerRegistry:n._listenerRegistry,options:Object(s.a)(Object(s.a)({},r),{},{betas:n._betas})}),o="LINK_AUTOFILL_MODAL"===e.type?e.groupId:null;return n._setupFrame(a,t,o)},this._setupFrame=function(e,t,r){return n._frames[e.id]=e,n._controllerFrame.sendPersistent({action:"stripe-user-createframe",payload:{newFrameId:e.id,frameType:t,groupId:r}}),e._on("unload",(function(){n._controllerFrame.sendPersistent({action:"stripe-frame-unload",payload:{unloadedFrameId:e.id}})})),e._on("destroy",(function(){delete n._frames[e.id],n._controllerFrame.sendPersistent({action:"stripe-frame-destroy",payload:{destroyedFrameId:e.id}})})),e._on("load",(function(){n._controllerFrame.sendPersistent({action:"stripe-frame-load",payload:{loadedFrameId:e.id}}),n._controllerFrame.loaded&&e.send({action:"stripe-controller-load",payload:{}})})),e},this.report=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};n._controllerFrame.send({action:"stripe-controller-report",payload:{event:e,data:t}})},this.warn=function(){for(var e=arguments.length,t=new Array(e),r=0;r5&&void 0!==arguments[5]?arguments[5]:0;if(C.i { - const cache = await caches.open(cacheVersion); + const cache = await caches.open(CACHE_VERSION); await cache.addAll(resources); }; const putInCache = async (request, response) => { - const cache = await caches.open(cacheVersion); + const cache = await caches.open(CACHE_VERSION); await cache.put(request, response); }; @@ -56,11 +56,10 @@ self.addEventListener('install', (event) => { event.waitUntil( addResourcesToCache([ '/', + '/public/js/script.js', + '/public/js/index.js', '/public/css/style.css', '/public/manifest.json', - '/public/js/script.js', - '/public/js/userbase.js', - '/public/js/stripe.js', '/public/js/sweetalert.js', ]), ); diff --git a/public/js/userbase.js b/public/js/userbase.js deleted file mode 100644 index a30e422..0000000 --- a/public/js/userbase.js +++ /dev/null @@ -1,26 +0,0 @@ -var userbase=function(e){var t={};function s(a){if(t[a])return t[a].exports;var r=t[a]={i:a,l:!1,exports:{}};return e[a].call(r.exports,r,r.exports,s),r.l=!0,r.exports}return s.m=e,s.c=t,s.d=function(e,t,a){s.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.t=function(e,t){if(1&t&&(e=s(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(s.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)s.d(a,r,function(t){return e[t]}.bind(null,r));return a},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,"a",t),t},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="",s(s.s=27)}([function(e,t){!function(){"use strict";for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=new Uint8Array(256),a=0;a>2],n+=e[(3&a[s])<<4|a[s+1]>>4],n+=e[(15&a[s+1])<<2|a[s+2]>>6],n+=e[63&a[s+2]];return r%3==2?n=n.substring(0,n.length-1)+"=":r%3==1&&(n=n.substring(0,n.length-2)+"=="),n},t.decode=function(e){var t,a,r,n,i,o=.75*e.length,c=e.length,u=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);var d=new ArrayBuffer(o),h=new Uint8Array(d);for(t=0;t>4,h[u++]=(15&r)<<4|n>>2,h[u++]=(3&n)<<6|63&i;return d}}()},function(e,t){e.exports=function(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}},function(e,t,s){var a=s(13),r=s(14);e.exports=function(e,t,s){var n=t&&s||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var i=(e=e||{}).random||(e.rng||a)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t)for(var o=0;o<16;++o)t[n+o]=i[o];return t||r(i)}},function(e,t){var s;s=function(){return this}();try{s=s||new Function("return this")()}catch(e){"object"==typeof window&&(s=window)}e.exports=s},function(e,t,s){"use strict";(function(e){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -var a=s(15),r=s(16),n=s(17);function i(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(i()=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|e}function m(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var s=e.length;if(0===s)return 0;for(var a=!1;;)switch(t){case"ascii":case"latin1":case"binary":return s;case"utf8":case"utf-8":case void 0:return L(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*s;case"hex":return s>>>1;case"base64":return j(e).length;default:if(a)return L(e).length;t=(""+t).toLowerCase(),a=!0}}function p(e,t,s){var a=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===s||s>this.length)&&(s=this.length),s<=0)return"";if((s>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return A(this,t,s);case"utf8":case"utf-8":return B(this,t,s);case"ascii":return N(this,t,s);case"latin1":case"binary":return U(this,t,s);case"base64":return E(this,t,s);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,t,s);default:if(a)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),a=!0}}function w(e,t,s){var a=e[t];e[t]=e[s],e[s]=a}function g(e,t,s,a,r){if(0===e.length)return-1;if("string"==typeof s?(a=s,s=0):s>2147483647?s=2147483647:s<-2147483648&&(s=-2147483648),s=+s,isNaN(s)&&(s=r?0:e.length-1),s<0&&(s=e.length+s),s>=e.length){if(r)return-1;s=e.length-1}else if(s<0){if(!r)return-1;s=0}if("string"==typeof t&&(t=c.from(t,a)),c.isBuffer(t))return 0===t.length?-1:y(e,t,s,a,r);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,s):Uint8Array.prototype.lastIndexOf.call(e,t,s):y(e,[t],s,a,r);throw new TypeError("val must be string, number or Buffer")}function y(e,t,s,a,r){var n,i=1,o=e.length,c=t.length;if(void 0!==a&&("ucs2"===(a=String(a).toLowerCase())||"ucs-2"===a||"utf16le"===a||"utf-16le"===a)){if(e.length<2||t.length<2)return-1;i=2,o/=2,c/=2,s/=2}function u(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(r){var d=-1;for(n=s;no&&(s=o-c),n=s;n>=0;n--){for(var h=!0,l=0;lr&&(a=r):a=r;var n=t.length;if(n%2!=0)throw new TypeError("Invalid hex string");a>n/2&&(a=n/2);for(var i=0;i>8,r=s%256,n.push(r),n.push(a);return n}(t,e.length-s),e,s,a)}function E(e,t,s){return 0===t&&s===e.length?a.fromByteArray(e):a.fromByteArray(e.slice(t,s))}function B(e,t,s){s=Math.min(e.length,s);for(var a=[],r=t;r239?4:u>223?3:u>191?2:1;if(r+h<=s)switch(h){case 1:u<128&&(d=u);break;case 2:128==(192&(n=e[r+1]))&&(c=(31&u)<<6|63&n)>127&&(d=c);break;case 3:n=e[r+1],i=e[r+2],128==(192&n)&&128==(192&i)&&(c=(15&u)<<12|(63&n)<<6|63&i)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:n=e[r+1],i=e[r+2],o=e[r+3],128==(192&n)&&128==(192&i)&&128==(192&o)&&(c=(15&u)<<18|(63&n)<<12|(63&i)<<6|63&o)>65535&&c<1114112&&(d=c)}null===d?(d=65533,h=1):d>65535&&(d-=65536,a.push(d>>>10&1023|55296),d=56320|1023&d),a.push(d),r+=h}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var s="",a=0;for(;a0&&(e=this.toString("hex",0,s).match(/.{2}/g).join(" "),this.length>s&&(e+=" ... ")),""},c.prototype.compare=function(e,t,s,a,r){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===s&&(s=e?e.length:0),void 0===a&&(a=0),void 0===r&&(r=this.length),t<0||s>e.length||a<0||r>this.length)throw new RangeError("out of range index");if(a>=r&&t>=s)return 0;if(a>=r)return-1;if(t>=s)return 1;if(this===e)return 0;for(var n=(r>>>=0)-(a>>>=0),i=(s>>>=0)-(t>>>=0),o=Math.min(n,i),u=this.slice(a,r),d=e.slice(t,s),h=0;hr)&&(s=r),e.length>0&&(s<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");a||(a="utf8");for(var n=!1;;)switch(a){case"hex":return b(this,e,t,s);case"utf8":case"utf-8":return v(this,e,t,s);case"ascii":return M(this,e,t,s);case"latin1":case"binary":return S(this,e,t,s);case"base64":return I(this,e,t,s);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,e,t,s);default:if(n)throw new TypeError("Unknown encoding: "+a);a=(""+a).toLowerCase(),n=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function N(e,t,s){var a="";s=Math.min(e.length,s);for(var r=t;ra)&&(s=a);for(var r="",n=t;ns)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,s,a,r,n){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||te.length)throw new RangeError("Index out of range")}function K(e,t,s,a){t<0&&(t=65535+t+1);for(var r=0,n=Math.min(e.length-s,2);r>>8*(a?r:1-r)}function x(e,t,s,a){t<0&&(t=4294967295+t+1);for(var r=0,n=Math.min(e.length-s,4);r>>8*(a?r:3-r)&255}function R(e,t,s,a,r,n){if(s+a>e.length)throw new RangeError("Index out of range");if(s<0)throw new RangeError("Index out of range")}function O(e,t,s,a,n){return n||R(e,0,s,4),r.write(e,t,s,a,23,4),s+4}function C(e,t,s,a,n){return n||R(e,0,s,8),r.write(e,t,s,a,52,8),s+8}c.prototype.slice=function(e,t){var s,a=this.length;if((e=~~e)<0?(e+=a)<0&&(e=0):e>a&&(e=a),(t=void 0===t?a:~~t)<0?(t+=a)<0&&(t=0):t>a&&(t=a),t0&&(r*=256);)a+=this[e+--t]*r;return a},c.prototype.readUInt8=function(e,t){return t||k(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||k(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||k(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||k(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||k(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,s){e|=0,t|=0,s||k(e,t,this.length);for(var a=this[e],r=1,n=0;++n=(r*=128)&&(a-=Math.pow(2,8*t)),a},c.prototype.readIntBE=function(e,t,s){e|=0,t|=0,s||k(e,t,this.length);for(var a=t,r=1,n=this[e+--a];a>0&&(r*=256);)n+=this[e+--a]*r;return n>=(r*=128)&&(n-=Math.pow(2,8*t)),n},c.prototype.readInt8=function(e,t){return t||k(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||k(e,2,this.length);var s=this[e]|this[e+1]<<8;return 32768&s?4294901760|s:s},c.prototype.readInt16BE=function(e,t){t||k(e,2,this.length);var s=this[e+1]|this[e]<<8;return 32768&s?4294901760|s:s},c.prototype.readInt32LE=function(e,t){return t||k(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||k(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||k(e,4,this.length),r.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||k(e,4,this.length),r.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||k(e,8,this.length),r.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||k(e,8,this.length),r.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,s,a){(e=+e,t|=0,s|=0,a)||D(this,e,t,s,Math.pow(2,8*s)-1,0);var r=1,n=0;for(this[t]=255&e;++n=0&&(n*=256);)this[t+r]=e/n&255;return t+s},c.prototype.writeUInt8=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):K(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):K(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):x(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):x(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,s,a){if(e=+e,t|=0,!a){var r=Math.pow(2,8*s-1);D(this,e,t,s,r-1,-r)}var n=0,i=1,o=0;for(this[t]=255&e;++n>0)-o&255;return t+s},c.prototype.writeIntBE=function(e,t,s,a){if(e=+e,t|=0,!a){var r=Math.pow(2,8*s-1);D(this,e,t,s,r-1,-r)}var n=s-1,i=1,o=0;for(this[t+n]=255&e;--n>=0&&(i*=256);)e<0&&0===o&&0!==this[t+n+1]&&(o=1),this[t+n]=(e/i>>0)-o&255;return t+s},c.prototype.writeInt8=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):K(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):K(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):x(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):x(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,s){return O(this,e,t,!0,s)},c.prototype.writeFloatBE=function(e,t,s){return O(this,e,t,!1,s)},c.prototype.writeDoubleLE=function(e,t,s){return C(this,e,t,!0,s)},c.prototype.writeDoubleBE=function(e,t,s){return C(this,e,t,!1,s)},c.prototype.copy=function(e,t,s,a){if(s||(s=0),a||0===a||(a=this.length),t>=e.length&&(t=e.length),t||(t=0),a>0&&a=this.length)throw new RangeError("sourceStart out of bounds");if(a<0)throw new RangeError("sourceEnd out of bounds");a>this.length&&(a=this.length),e.length-t=0;--r)e[r+t]=this[r+s];else if(n<1e3||!c.TYPED_ARRAY_SUPPORT)for(r=0;r>>=0,s=void 0===s?this.length:s>>>0,e||(e=0),"number"==typeof e)for(n=t;n55295&&s<57344){if(!r){if(s>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(i+1===a){(t-=3)>-1&&n.push(239,191,189);continue}r=s;continue}if(s<56320){(t-=3)>-1&&n.push(239,191,189),r=s;continue}s=65536+(r-55296<<10|s-56320)}else r&&(t-=3)>-1&&n.push(239,191,189);if(r=null,s<128){if((t-=1)<0)break;n.push(s)}else if(s<2048){if((t-=2)<0)break;n.push(s>>6|192,63&s|128)}else if(s<65536){if((t-=3)<0)break;n.push(s>>12|224,s>>6&63|128,63&s|128)}else{if(!(s<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(s>>18|240,s>>12&63|128,s>>6&63|128,63&s|128)}}return n}function j(e){return a.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(_,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function q(e,t,s,a){for(var r=0;r=t.length||r>=e.length);++r)t[r+s]=e[r];return r}}).call(this,s(3))},function(e,t,s){(function(e){!function(e,t){"use strict";function a(e,t){if(!e)throw new Error(t||"Assertion failed")}function r(e,t){e.super_=t;var s=function(){};s.prototype=t.prototype,e.prototype=new s,e.prototype.constructor=e}function n(e,t,s){if(n.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(s=t,t=10),this._init(e||0,t||10,s||"be"))}var i;"object"==typeof e?e.exports=n:t.BN=n,n.BN=n,n.wordSize=26;try{i=s(20).Buffer}catch(e){}function o(e,t,s){for(var a=0,r=Math.min(e.length,s),n=t;n=49&&i<=54?i-49+10:i>=17&&i<=22?i-17+10:15&i}return a}function c(e,t,s,a){for(var r=0,n=Math.min(e.length,s),i=t;i=49?o-49+10:o>=17?o-17+10:o}return r}n.isBN=function(e){return e instanceof n||null!==e&&"object"==typeof e&&e.constructor.wordSize===n.wordSize&&Array.isArray(e.words)},n.max=function(e,t){return e.cmp(t)>0?e:t},n.min=function(e,t){return e.cmp(t)<0?e:t},n.prototype._init=function(e,t,s){if("number"==typeof e)return this._initNumber(e,t,s);if("object"==typeof e)return this._initArray(e,t,s);"hex"===t&&(t=16),a(t===(0|t)&&t>=2&&t<=36);var r=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&r++,16===t?this._parseHex(e,r):this._parseBase(e,t,r),"-"===e[0]&&(this.negative=1),this.strip(),"le"===s&&this._initArray(this.toArray(),t,s)},n.prototype._initNumber=function(e,t,s){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(a(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===s&&this._initArray(this.toArray(),t,s)},n.prototype._initArray=function(e,t,s){if(a("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var r=0;r=0;r-=3)i=e[r]|e[r-1]<<8|e[r-2]<<16,this.words[n]|=i<>>26-o&67108863,(o+=24)>=26&&(o-=26,n++);else if("le"===s)for(r=0,n=0;r>>26-o&67108863,(o+=24)>=26&&(o-=26,n++);return this.strip()},n.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var s=0;s=t;s-=6)r=o(e,s,s+6),this.words[a]|=r<>>26-n&4194303,(n+=24)>=26&&(n-=26,a++);s+6!==t&&(r=o(e,t,s+6),this.words[a]|=r<>>26-n&4194303),this.strip()},n.prototype._parseBase=function(e,t,s){this.words=[0],this.length=1;for(var a=0,r=1;r<=67108863;r*=t)a++;a--,r=r/t|0;for(var n=e.length-s,i=n%a,o=Math.min(n,n-i)+s,u=0,d=s;d1&&0===this.words[this.length-1];)this.length--;return this._normSign()},n.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},n.prototype.inspect=function(){return(this.red?""};var u=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],d=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(e,t,s){s.negative=t.negative^e.negative;var a=e.length+t.length|0;s.length=a,a=a-1|0;var r=0|e.words[0],n=0|t.words[0],i=r*n,o=67108863&i,c=i/67108864|0;s.words[0]=o;for(var u=1;u>>26,h=67108863&c,l=Math.min(u,t.length-1),f=Math.max(0,u-e.length+1);f<=l;f++){var m=u-f|0;d+=(i=(r=0|e.words[m])*(n=0|t.words[f])+h)/67108864|0,h=67108863&i}s.words[u]=0|h,c=0|d}return 0!==c?s.words[u]=0|c:s.length--,s.strip()}n.prototype.toString=function(e,t){var s;if(t=0|t||1,16===(e=e||10)||"hex"===e){s="";for(var r=0,n=0,i=0;i>>24-r&16777215)||i!==this.length-1?u[6-c.length]+c+s:c+s,(r+=2)>=26&&(r-=26,i--)}for(0!==n&&(s=n.toString(16)+s);s.length%t!=0;)s="0"+s;return 0!==this.negative&&(s="-"+s),s}if(e===(0|e)&&e>=2&&e<=36){var l=d[e],f=h[e];s="";var m=this.clone();for(m.negative=0;!m.isZero();){var p=m.modn(f).toString(e);s=(m=m.idivn(f)).isZero()?p+s:u[l-p.length]+p+s}for(this.isZero()&&(s="0"+s);s.length%t!=0;)s="0"+s;return 0!==this.negative&&(s="-"+s),s}a(!1,"Base should be between 2 and 36")},n.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&a(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},n.prototype.toJSON=function(){return this.toString(16)},n.prototype.toBuffer=function(e,t){return a(void 0!==i),this.toArrayLike(i,e,t)},n.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},n.prototype.toArrayLike=function(e,t,s){var r=this.byteLength(),n=s||Math.max(1,r);a(r<=n,"byte array longer than desired length"),a(n>0,"Requested array length <= 0"),this.strip();var i,o,c="le"===t,u=new e(n),d=this.clone();if(c){for(o=0;!d.isZero();o++)i=d.andln(255),d.iushrn(8),u[o]=i;for(;o=4096&&(s+=13,t>>>=13),t>=64&&(s+=7,t>>>=7),t>=8&&(s+=4,t>>>=4),t>=2&&(s+=2,t>>>=2),s+t},n.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,s=0;return 0==(8191&t)&&(s+=13,t>>>=13),0==(127&t)&&(s+=7,t>>>=7),0==(15&t)&&(s+=4,t>>>=4),0==(3&t)&&(s+=2,t>>>=2),0==(1&t)&&s++,s},n.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},n.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},n.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},n.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var s=0;se.length?this.clone().iand(e):e.clone().iand(this)},n.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},n.prototype.iuxor=function(e){var t,s;this.length>e.length?(t=this,s=e):(t=e,s=this);for(var a=0;ae.length?this.clone().ixor(e):e.clone().ixor(this)},n.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},n.prototype.inotn=function(e){a("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),s=e%26;this._expand(t),s>0&&t--;for(var r=0;r0&&(this.words[r]=~this.words[r]&67108863>>26-s),this.strip()},n.prototype.notn=function(e){return this.clone().inotn(e)},n.prototype.setn=function(e,t){a("number"==typeof e&&e>=0);var s=e/26|0,r=e%26;return this._expand(s+1),this.words[s]=t?this.words[s]|1<e.length?(s=this,a=e):(s=e,a=this);for(var r=0,n=0;n>>26;for(;0!==r&&n>>26;if(this.length=s.length,0!==r)this.words[this.length]=r,this.length++;else if(s!==this)for(;ne.length?this.clone().iadd(e):e.clone().iadd(this)},n.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var s,a,r=this.cmp(e);if(0===r)return this.negative=0,this.length=1,this.words[0]=0,this;r>0?(s=this,a=e):(s=e,a=this);for(var n=0,i=0;i>26,this.words[i]=67108863&t;for(;0!==n&&i>26,this.words[i]=67108863&t;if(0===n&&i>>13,f=0|i[1],m=8191&f,p=f>>>13,w=0|i[2],g=8191&w,y=w>>>13,b=0|i[3],v=8191&b,M=b>>>13,S=0|i[4],I=8191&S,P=S>>>13,E=0|i[5],B=8191&E,N=E>>>13,U=0|i[6],A=8191&U,T=U>>>13,k=0|i[7],D=8191&k,K=k>>>13,x=0|i[8],R=8191&x,O=x>>>13,C=0|i[9],_=8191&C,F=C>>>13,L=0|o[0],j=8191&L,q=L>>>13,V=0|o[1],H=8191&V,G=V>>>13,J=0|o[2],W=8191&J,Y=J>>>13,z=0|o[3],Z=8191&z,X=z>>>13,Q=0|o[4],$=8191&Q,ee=Q>>>13,te=0|o[5],se=8191&te,ae=te>>>13,re=0|o[6],ne=8191&re,ie=re>>>13,oe=0|o[7],ce=8191&oe,ue=oe>>>13,de=0|o[8],he=8191&de,le=de>>>13,fe=0|o[9],me=8191&fe,pe=fe>>>13;s.negative=e.negative^t.negative,s.length=19;var we=(u+(a=Math.imul(h,j))|0)+((8191&(r=(r=Math.imul(h,q))+Math.imul(l,j)|0))<<13)|0;u=((n=Math.imul(l,q))+(r>>>13)|0)+(we>>>26)|0,we&=67108863,a=Math.imul(m,j),r=(r=Math.imul(m,q))+Math.imul(p,j)|0,n=Math.imul(p,q);var ge=(u+(a=a+Math.imul(h,H)|0)|0)+((8191&(r=(r=r+Math.imul(h,G)|0)+Math.imul(l,H)|0))<<13)|0;u=((n=n+Math.imul(l,G)|0)+(r>>>13)|0)+(ge>>>26)|0,ge&=67108863,a=Math.imul(g,j),r=(r=Math.imul(g,q))+Math.imul(y,j)|0,n=Math.imul(y,q),a=a+Math.imul(m,H)|0,r=(r=r+Math.imul(m,G)|0)+Math.imul(p,H)|0,n=n+Math.imul(p,G)|0;var ye=(u+(a=a+Math.imul(h,W)|0)|0)+((8191&(r=(r=r+Math.imul(h,Y)|0)+Math.imul(l,W)|0))<<13)|0;u=((n=n+Math.imul(l,Y)|0)+(r>>>13)|0)+(ye>>>26)|0,ye&=67108863,a=Math.imul(v,j),r=(r=Math.imul(v,q))+Math.imul(M,j)|0,n=Math.imul(M,q),a=a+Math.imul(g,H)|0,r=(r=r+Math.imul(g,G)|0)+Math.imul(y,H)|0,n=n+Math.imul(y,G)|0,a=a+Math.imul(m,W)|0,r=(r=r+Math.imul(m,Y)|0)+Math.imul(p,W)|0,n=n+Math.imul(p,Y)|0;var be=(u+(a=a+Math.imul(h,Z)|0)|0)+((8191&(r=(r=r+Math.imul(h,X)|0)+Math.imul(l,Z)|0))<<13)|0;u=((n=n+Math.imul(l,X)|0)+(r>>>13)|0)+(be>>>26)|0,be&=67108863,a=Math.imul(I,j),r=(r=Math.imul(I,q))+Math.imul(P,j)|0,n=Math.imul(P,q),a=a+Math.imul(v,H)|0,r=(r=r+Math.imul(v,G)|0)+Math.imul(M,H)|0,n=n+Math.imul(M,G)|0,a=a+Math.imul(g,W)|0,r=(r=r+Math.imul(g,Y)|0)+Math.imul(y,W)|0,n=n+Math.imul(y,Y)|0,a=a+Math.imul(m,Z)|0,r=(r=r+Math.imul(m,X)|0)+Math.imul(p,Z)|0,n=n+Math.imul(p,X)|0;var ve=(u+(a=a+Math.imul(h,$)|0)|0)+((8191&(r=(r=r+Math.imul(h,ee)|0)+Math.imul(l,$)|0))<<13)|0;u=((n=n+Math.imul(l,ee)|0)+(r>>>13)|0)+(ve>>>26)|0,ve&=67108863,a=Math.imul(B,j),r=(r=Math.imul(B,q))+Math.imul(N,j)|0,n=Math.imul(N,q),a=a+Math.imul(I,H)|0,r=(r=r+Math.imul(I,G)|0)+Math.imul(P,H)|0,n=n+Math.imul(P,G)|0,a=a+Math.imul(v,W)|0,r=(r=r+Math.imul(v,Y)|0)+Math.imul(M,W)|0,n=n+Math.imul(M,Y)|0,a=a+Math.imul(g,Z)|0,r=(r=r+Math.imul(g,X)|0)+Math.imul(y,Z)|0,n=n+Math.imul(y,X)|0,a=a+Math.imul(m,$)|0,r=(r=r+Math.imul(m,ee)|0)+Math.imul(p,$)|0,n=n+Math.imul(p,ee)|0;var Me=(u+(a=a+Math.imul(h,se)|0)|0)+((8191&(r=(r=r+Math.imul(h,ae)|0)+Math.imul(l,se)|0))<<13)|0;u=((n=n+Math.imul(l,ae)|0)+(r>>>13)|0)+(Me>>>26)|0,Me&=67108863,a=Math.imul(A,j),r=(r=Math.imul(A,q))+Math.imul(T,j)|0,n=Math.imul(T,q),a=a+Math.imul(B,H)|0,r=(r=r+Math.imul(B,G)|0)+Math.imul(N,H)|0,n=n+Math.imul(N,G)|0,a=a+Math.imul(I,W)|0,r=(r=r+Math.imul(I,Y)|0)+Math.imul(P,W)|0,n=n+Math.imul(P,Y)|0,a=a+Math.imul(v,Z)|0,r=(r=r+Math.imul(v,X)|0)+Math.imul(M,Z)|0,n=n+Math.imul(M,X)|0,a=a+Math.imul(g,$)|0,r=(r=r+Math.imul(g,ee)|0)+Math.imul(y,$)|0,n=n+Math.imul(y,ee)|0,a=a+Math.imul(m,se)|0,r=(r=r+Math.imul(m,ae)|0)+Math.imul(p,se)|0,n=n+Math.imul(p,ae)|0;var Se=(u+(a=a+Math.imul(h,ne)|0)|0)+((8191&(r=(r=r+Math.imul(h,ie)|0)+Math.imul(l,ne)|0))<<13)|0;u=((n=n+Math.imul(l,ie)|0)+(r>>>13)|0)+(Se>>>26)|0,Se&=67108863,a=Math.imul(D,j),r=(r=Math.imul(D,q))+Math.imul(K,j)|0,n=Math.imul(K,q),a=a+Math.imul(A,H)|0,r=(r=r+Math.imul(A,G)|0)+Math.imul(T,H)|0,n=n+Math.imul(T,G)|0,a=a+Math.imul(B,W)|0,r=(r=r+Math.imul(B,Y)|0)+Math.imul(N,W)|0,n=n+Math.imul(N,Y)|0,a=a+Math.imul(I,Z)|0,r=(r=r+Math.imul(I,X)|0)+Math.imul(P,Z)|0,n=n+Math.imul(P,X)|0,a=a+Math.imul(v,$)|0,r=(r=r+Math.imul(v,ee)|0)+Math.imul(M,$)|0,n=n+Math.imul(M,ee)|0,a=a+Math.imul(g,se)|0,r=(r=r+Math.imul(g,ae)|0)+Math.imul(y,se)|0,n=n+Math.imul(y,ae)|0,a=a+Math.imul(m,ne)|0,r=(r=r+Math.imul(m,ie)|0)+Math.imul(p,ne)|0,n=n+Math.imul(p,ie)|0;var Ie=(u+(a=a+Math.imul(h,ce)|0)|0)+((8191&(r=(r=r+Math.imul(h,ue)|0)+Math.imul(l,ce)|0))<<13)|0;u=((n=n+Math.imul(l,ue)|0)+(r>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,a=Math.imul(R,j),r=(r=Math.imul(R,q))+Math.imul(O,j)|0,n=Math.imul(O,q),a=a+Math.imul(D,H)|0,r=(r=r+Math.imul(D,G)|0)+Math.imul(K,H)|0,n=n+Math.imul(K,G)|0,a=a+Math.imul(A,W)|0,r=(r=r+Math.imul(A,Y)|0)+Math.imul(T,W)|0,n=n+Math.imul(T,Y)|0,a=a+Math.imul(B,Z)|0,r=(r=r+Math.imul(B,X)|0)+Math.imul(N,Z)|0,n=n+Math.imul(N,X)|0,a=a+Math.imul(I,$)|0,r=(r=r+Math.imul(I,ee)|0)+Math.imul(P,$)|0,n=n+Math.imul(P,ee)|0,a=a+Math.imul(v,se)|0,r=(r=r+Math.imul(v,ae)|0)+Math.imul(M,se)|0,n=n+Math.imul(M,ae)|0,a=a+Math.imul(g,ne)|0,r=(r=r+Math.imul(g,ie)|0)+Math.imul(y,ne)|0,n=n+Math.imul(y,ie)|0,a=a+Math.imul(m,ce)|0,r=(r=r+Math.imul(m,ue)|0)+Math.imul(p,ce)|0,n=n+Math.imul(p,ue)|0;var Pe=(u+(a=a+Math.imul(h,he)|0)|0)+((8191&(r=(r=r+Math.imul(h,le)|0)+Math.imul(l,he)|0))<<13)|0;u=((n=n+Math.imul(l,le)|0)+(r>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,a=Math.imul(_,j),r=(r=Math.imul(_,q))+Math.imul(F,j)|0,n=Math.imul(F,q),a=a+Math.imul(R,H)|0,r=(r=r+Math.imul(R,G)|0)+Math.imul(O,H)|0,n=n+Math.imul(O,G)|0,a=a+Math.imul(D,W)|0,r=(r=r+Math.imul(D,Y)|0)+Math.imul(K,W)|0,n=n+Math.imul(K,Y)|0,a=a+Math.imul(A,Z)|0,r=(r=r+Math.imul(A,X)|0)+Math.imul(T,Z)|0,n=n+Math.imul(T,X)|0,a=a+Math.imul(B,$)|0,r=(r=r+Math.imul(B,ee)|0)+Math.imul(N,$)|0,n=n+Math.imul(N,ee)|0,a=a+Math.imul(I,se)|0,r=(r=r+Math.imul(I,ae)|0)+Math.imul(P,se)|0,n=n+Math.imul(P,ae)|0,a=a+Math.imul(v,ne)|0,r=(r=r+Math.imul(v,ie)|0)+Math.imul(M,ne)|0,n=n+Math.imul(M,ie)|0,a=a+Math.imul(g,ce)|0,r=(r=r+Math.imul(g,ue)|0)+Math.imul(y,ce)|0,n=n+Math.imul(y,ue)|0,a=a+Math.imul(m,he)|0,r=(r=r+Math.imul(m,le)|0)+Math.imul(p,he)|0,n=n+Math.imul(p,le)|0;var Ee=(u+(a=a+Math.imul(h,me)|0)|0)+((8191&(r=(r=r+Math.imul(h,pe)|0)+Math.imul(l,me)|0))<<13)|0;u=((n=n+Math.imul(l,pe)|0)+(r>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,a=Math.imul(_,H),r=(r=Math.imul(_,G))+Math.imul(F,H)|0,n=Math.imul(F,G),a=a+Math.imul(R,W)|0,r=(r=r+Math.imul(R,Y)|0)+Math.imul(O,W)|0,n=n+Math.imul(O,Y)|0,a=a+Math.imul(D,Z)|0,r=(r=r+Math.imul(D,X)|0)+Math.imul(K,Z)|0,n=n+Math.imul(K,X)|0,a=a+Math.imul(A,$)|0,r=(r=r+Math.imul(A,ee)|0)+Math.imul(T,$)|0,n=n+Math.imul(T,ee)|0,a=a+Math.imul(B,se)|0,r=(r=r+Math.imul(B,ae)|0)+Math.imul(N,se)|0,n=n+Math.imul(N,ae)|0,a=a+Math.imul(I,ne)|0,r=(r=r+Math.imul(I,ie)|0)+Math.imul(P,ne)|0,n=n+Math.imul(P,ie)|0,a=a+Math.imul(v,ce)|0,r=(r=r+Math.imul(v,ue)|0)+Math.imul(M,ce)|0,n=n+Math.imul(M,ue)|0,a=a+Math.imul(g,he)|0,r=(r=r+Math.imul(g,le)|0)+Math.imul(y,he)|0,n=n+Math.imul(y,le)|0;var Be=(u+(a=a+Math.imul(m,me)|0)|0)+((8191&(r=(r=r+Math.imul(m,pe)|0)+Math.imul(p,me)|0))<<13)|0;u=((n=n+Math.imul(p,pe)|0)+(r>>>13)|0)+(Be>>>26)|0,Be&=67108863,a=Math.imul(_,W),r=(r=Math.imul(_,Y))+Math.imul(F,W)|0,n=Math.imul(F,Y),a=a+Math.imul(R,Z)|0,r=(r=r+Math.imul(R,X)|0)+Math.imul(O,Z)|0,n=n+Math.imul(O,X)|0,a=a+Math.imul(D,$)|0,r=(r=r+Math.imul(D,ee)|0)+Math.imul(K,$)|0,n=n+Math.imul(K,ee)|0,a=a+Math.imul(A,se)|0,r=(r=r+Math.imul(A,ae)|0)+Math.imul(T,se)|0,n=n+Math.imul(T,ae)|0,a=a+Math.imul(B,ne)|0,r=(r=r+Math.imul(B,ie)|0)+Math.imul(N,ne)|0,n=n+Math.imul(N,ie)|0,a=a+Math.imul(I,ce)|0,r=(r=r+Math.imul(I,ue)|0)+Math.imul(P,ce)|0,n=n+Math.imul(P,ue)|0,a=a+Math.imul(v,he)|0,r=(r=r+Math.imul(v,le)|0)+Math.imul(M,he)|0,n=n+Math.imul(M,le)|0;var Ne=(u+(a=a+Math.imul(g,me)|0)|0)+((8191&(r=(r=r+Math.imul(g,pe)|0)+Math.imul(y,me)|0))<<13)|0;u=((n=n+Math.imul(y,pe)|0)+(r>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,a=Math.imul(_,Z),r=(r=Math.imul(_,X))+Math.imul(F,Z)|0,n=Math.imul(F,X),a=a+Math.imul(R,$)|0,r=(r=r+Math.imul(R,ee)|0)+Math.imul(O,$)|0,n=n+Math.imul(O,ee)|0,a=a+Math.imul(D,se)|0,r=(r=r+Math.imul(D,ae)|0)+Math.imul(K,se)|0,n=n+Math.imul(K,ae)|0,a=a+Math.imul(A,ne)|0,r=(r=r+Math.imul(A,ie)|0)+Math.imul(T,ne)|0,n=n+Math.imul(T,ie)|0,a=a+Math.imul(B,ce)|0,r=(r=r+Math.imul(B,ue)|0)+Math.imul(N,ce)|0,n=n+Math.imul(N,ue)|0,a=a+Math.imul(I,he)|0,r=(r=r+Math.imul(I,le)|0)+Math.imul(P,he)|0,n=n+Math.imul(P,le)|0;var Ue=(u+(a=a+Math.imul(v,me)|0)|0)+((8191&(r=(r=r+Math.imul(v,pe)|0)+Math.imul(M,me)|0))<<13)|0;u=((n=n+Math.imul(M,pe)|0)+(r>>>13)|0)+(Ue>>>26)|0,Ue&=67108863,a=Math.imul(_,$),r=(r=Math.imul(_,ee))+Math.imul(F,$)|0,n=Math.imul(F,ee),a=a+Math.imul(R,se)|0,r=(r=r+Math.imul(R,ae)|0)+Math.imul(O,se)|0,n=n+Math.imul(O,ae)|0,a=a+Math.imul(D,ne)|0,r=(r=r+Math.imul(D,ie)|0)+Math.imul(K,ne)|0,n=n+Math.imul(K,ie)|0,a=a+Math.imul(A,ce)|0,r=(r=r+Math.imul(A,ue)|0)+Math.imul(T,ce)|0,n=n+Math.imul(T,ue)|0,a=a+Math.imul(B,he)|0,r=(r=r+Math.imul(B,le)|0)+Math.imul(N,he)|0,n=n+Math.imul(N,le)|0;var Ae=(u+(a=a+Math.imul(I,me)|0)|0)+((8191&(r=(r=r+Math.imul(I,pe)|0)+Math.imul(P,me)|0))<<13)|0;u=((n=n+Math.imul(P,pe)|0)+(r>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,a=Math.imul(_,se),r=(r=Math.imul(_,ae))+Math.imul(F,se)|0,n=Math.imul(F,ae),a=a+Math.imul(R,ne)|0,r=(r=r+Math.imul(R,ie)|0)+Math.imul(O,ne)|0,n=n+Math.imul(O,ie)|0,a=a+Math.imul(D,ce)|0,r=(r=r+Math.imul(D,ue)|0)+Math.imul(K,ce)|0,n=n+Math.imul(K,ue)|0,a=a+Math.imul(A,he)|0,r=(r=r+Math.imul(A,le)|0)+Math.imul(T,he)|0,n=n+Math.imul(T,le)|0;var Te=(u+(a=a+Math.imul(B,me)|0)|0)+((8191&(r=(r=r+Math.imul(B,pe)|0)+Math.imul(N,me)|0))<<13)|0;u=((n=n+Math.imul(N,pe)|0)+(r>>>13)|0)+(Te>>>26)|0,Te&=67108863,a=Math.imul(_,ne),r=(r=Math.imul(_,ie))+Math.imul(F,ne)|0,n=Math.imul(F,ie),a=a+Math.imul(R,ce)|0,r=(r=r+Math.imul(R,ue)|0)+Math.imul(O,ce)|0,n=n+Math.imul(O,ue)|0,a=a+Math.imul(D,he)|0,r=(r=r+Math.imul(D,le)|0)+Math.imul(K,he)|0,n=n+Math.imul(K,le)|0;var ke=(u+(a=a+Math.imul(A,me)|0)|0)+((8191&(r=(r=r+Math.imul(A,pe)|0)+Math.imul(T,me)|0))<<13)|0;u=((n=n+Math.imul(T,pe)|0)+(r>>>13)|0)+(ke>>>26)|0,ke&=67108863,a=Math.imul(_,ce),r=(r=Math.imul(_,ue))+Math.imul(F,ce)|0,n=Math.imul(F,ue),a=a+Math.imul(R,he)|0,r=(r=r+Math.imul(R,le)|0)+Math.imul(O,he)|0,n=n+Math.imul(O,le)|0;var De=(u+(a=a+Math.imul(D,me)|0)|0)+((8191&(r=(r=r+Math.imul(D,pe)|0)+Math.imul(K,me)|0))<<13)|0;u=((n=n+Math.imul(K,pe)|0)+(r>>>13)|0)+(De>>>26)|0,De&=67108863,a=Math.imul(_,he),r=(r=Math.imul(_,le))+Math.imul(F,he)|0,n=Math.imul(F,le);var Ke=(u+(a=a+Math.imul(R,me)|0)|0)+((8191&(r=(r=r+Math.imul(R,pe)|0)+Math.imul(O,me)|0))<<13)|0;u=((n=n+Math.imul(O,pe)|0)+(r>>>13)|0)+(Ke>>>26)|0,Ke&=67108863;var xe=(u+(a=Math.imul(_,me))|0)+((8191&(r=(r=Math.imul(_,pe))+Math.imul(F,me)|0))<<13)|0;return u=((n=Math.imul(F,pe))+(r>>>13)|0)+(xe>>>26)|0,xe&=67108863,c[0]=we,c[1]=ge,c[2]=ye,c[3]=be,c[4]=ve,c[5]=Me,c[6]=Se,c[7]=Ie,c[8]=Pe,c[9]=Ee,c[10]=Be,c[11]=Ne,c[12]=Ue,c[13]=Ae,c[14]=Te,c[15]=ke,c[16]=De,c[17]=Ke,c[18]=xe,0!==u&&(c[19]=u,s.length++),s};function m(e,t,s){return(new p).mulp(e,t,s)}function p(e,t){this.x=e,this.y=t}Math.imul||(f=l),n.prototype.mulTo=function(e,t){var s=this.length+e.length;return 10===this.length&&10===e.length?f(this,e,t):s<63?l(this,e,t):s<1024?function(e,t,s){s.negative=t.negative^e.negative,s.length=e.length+t.length;for(var a=0,r=0,n=0;n>>26)|0)>>>26,i&=67108863}s.words[n]=o,a=i,i=r}return 0!==a?s.words[n]=a:s.length--,s.strip()}(this,e,t):m(this,e,t)},p.prototype.makeRBT=function(e){for(var t=new Array(e),s=n.prototype._countBits(e)-1,a=0;a>=1;return a},p.prototype.permute=function(e,t,s,a,r,n){for(var i=0;i>>=1)r++;return 1<>>=13,s[2*i+1]=8191&n,n>>>=13;for(i=2*t;i>=26,t+=r/67108864|0,t+=n>>>26,this.words[s]=67108863&n}return 0!==t&&(this.words[s]=t,this.length++),this},n.prototype.muln=function(e){return this.clone().imuln(e)},n.prototype.sqr=function(){return this.mul(this)},n.prototype.isqr=function(){return this.imul(this.clone())},n.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),s=0;s>>r}return t}(e);if(0===t.length)return new n(1);for(var s=this,a=0;a=0);var t,s=e%26,r=(e-s)/26,n=67108863>>>26-s<<26-s;if(0!==s){var i=0;for(t=0;t>>26-s}i&&(this.words[t]=i,this.length++)}if(0!==r){for(t=this.length-1;t>=0;t--)this.words[t+r]=this.words[t];for(t=0;t=0),r=t?(t-t%26)/26:0;var n=e%26,i=Math.min((e-n)/26,this.length),o=67108863^67108863>>>n<i)for(this.length-=i,u=0;u=0&&(0!==d||u>=r);u--){var h=0|this.words[u];this.words[u]=d<<26-n|h>>>n,d=h&o}return c&&0!==d&&(c.words[c.length++]=d),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},n.prototype.ishrn=function(e,t,s){return a(0===this.negative),this.iushrn(e,t,s)},n.prototype.shln=function(e){return this.clone().ishln(e)},n.prototype.ushln=function(e){return this.clone().iushln(e)},n.prototype.shrn=function(e){return this.clone().ishrn(e)},n.prototype.ushrn=function(e){return this.clone().iushrn(e)},n.prototype.testn=function(e){a("number"==typeof e&&e>=0);var t=e%26,s=(e-t)/26,r=1<=0);var t=e%26,s=(e-t)/26;if(a(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!==t&&s++,this.length=Math.min(s,this.length),0!==t){var r=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},n.prototype.isubn=function(e){if(a("number"==typeof e),a(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(c/67108864|0),this.words[r+s]=67108863&n}for(;r>26,this.words[r+s]=67108863&n;if(0===o)return this.strip();for(a(-1===o),o=0,r=0;r>26,this.words[r]=67108863&n;return this.negative=1,this.strip()},n.prototype._wordDiv=function(e,t){var s=(this.length,e.length),a=this.clone(),r=e,i=0|r.words[r.length-1];0!==(s=26-this._countBits(i))&&(r=r.ushln(s),a.iushln(s),i=0|r.words[r.length-1]);var o,c=a.length-r.length;if("mod"!==t){(o=new n(null)).length=c+1,o.words=new Array(o.length);for(var u=0;u=0;h--){var l=67108864*(0|a.words[r.length+h])+(0|a.words[r.length+h-1]);for(l=Math.min(l/i|0,67108863),a._ishlnsubmul(r,l,h);0!==a.negative;)l--,a.negative=0,a._ishlnsubmul(r,1,h),a.isZero()||(a.negative^=1);o&&(o.words[h]=l)}return o&&o.strip(),a.strip(),"div"!==t&&0!==s&&a.iushrn(s),{div:o||null,mod:a}},n.prototype.divmod=function(e,t,s){return a(!e.isZero()),this.isZero()?{div:new n(0),mod:new n(0)}:0!==this.negative&&0===e.negative?(o=this.neg().divmod(e,t),"mod"!==t&&(r=o.div.neg()),"div"!==t&&(i=o.mod.neg(),s&&0!==i.negative&&i.iadd(e)),{div:r,mod:i}):0===this.negative&&0!==e.negative?(o=this.divmod(e.neg(),t),"mod"!==t&&(r=o.div.neg()),{div:r,mod:o.mod}):0!=(this.negative&e.negative)?(o=this.neg().divmod(e.neg(),t),"div"!==t&&(i=o.mod.neg(),s&&0!==i.negative&&i.isub(e)),{div:o.div,mod:i}):e.length>this.length||this.cmp(e)<0?{div:new n(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new n(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new n(this.modn(e.words[0]))}:this._wordDiv(e,t);var r,i,o},n.prototype.div=function(e){return this.divmod(e,"div",!1).div},n.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},n.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},n.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var s=0!==t.div.negative?t.mod.isub(e):t.mod,a=e.ushrn(1),r=e.andln(1),n=s.cmp(a);return n<0||1===r&&0===n?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},n.prototype.modn=function(e){a(e<=67108863);for(var t=(1<<26)%e,s=0,r=this.length-1;r>=0;r--)s=(t*s+(0|this.words[r]))%e;return s},n.prototype.idivn=function(e){a(e<=67108863);for(var t=0,s=this.length-1;s>=0;s--){var r=(0|this.words[s])+67108864*t;this.words[s]=r/e|0,t=r%e}return this.strip()},n.prototype.divn=function(e){return this.clone().idivn(e)},n.prototype.egcd=function(e){a(0===e.negative),a(!e.isZero());var t=this,s=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r=new n(1),i=new n(0),o=new n(0),c=new n(1),u=0;t.isEven()&&s.isEven();)t.iushrn(1),s.iushrn(1),++u;for(var d=s.clone(),h=t.clone();!t.isZero();){for(var l=0,f=1;0==(t.words[0]&f)&&l<26;++l,f<<=1);if(l>0)for(t.iushrn(l);l-- >0;)(r.isOdd()||i.isOdd())&&(r.iadd(d),i.isub(h)),r.iushrn(1),i.iushrn(1);for(var m=0,p=1;0==(s.words[0]&p)&&m<26;++m,p<<=1);if(m>0)for(s.iushrn(m);m-- >0;)(o.isOdd()||c.isOdd())&&(o.iadd(d),c.isub(h)),o.iushrn(1),c.iushrn(1);t.cmp(s)>=0?(t.isub(s),r.isub(o),i.isub(c)):(s.isub(t),o.isub(r),c.isub(i))}return{a:o,b:c,gcd:s.iushln(u)}},n.prototype._invmp=function(e){a(0===e.negative),a(!e.isZero());var t=this,s=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r,i=new n(1),o=new n(0),c=s.clone();t.cmpn(1)>0&&s.cmpn(1)>0;){for(var u=0,d=1;0==(t.words[0]&d)&&u<26;++u,d<<=1);if(u>0)for(t.iushrn(u);u-- >0;)i.isOdd()&&i.iadd(c),i.iushrn(1);for(var h=0,l=1;0==(s.words[0]&l)&&h<26;++h,l<<=1);if(h>0)for(s.iushrn(h);h-- >0;)o.isOdd()&&o.iadd(c),o.iushrn(1);t.cmp(s)>=0?(t.isub(s),i.isub(o)):(s.isub(t),o.isub(i))}return(r=0===t.cmpn(1)?i:o).cmpn(0)<0&&r.iadd(e),r},n.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),s=e.clone();t.negative=0,s.negative=0;for(var a=0;t.isEven()&&s.isEven();a++)t.iushrn(1),s.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;s.isEven();)s.iushrn(1);var r=t.cmp(s);if(r<0){var n=t;t=s,s=n}else if(0===r||0===s.cmpn(1))break;t.isub(s)}return s.iushln(a)},n.prototype.invm=function(e){return this.egcd(e).a.umod(e)},n.prototype.isEven=function(){return 0==(1&this.words[0])},n.prototype.isOdd=function(){return 1==(1&this.words[0])},n.prototype.andln=function(e){return this.words[0]&e},n.prototype.bincn=function(e){a("number"==typeof e);var t=e%26,s=(e-t)/26,r=1<>>26,o&=67108863,this.words[i]=o}return 0!==n&&(this.words[i]=n,this.length++),this},n.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},n.prototype.cmpn=function(e){var t,s=e<0;if(0!==this.negative&&!s)return-1;if(0===this.negative&&s)return 1;if(this.strip(),this.length>1)t=1;else{s&&(e=-e),a(e<=67108863,"Number is too big");var r=0|this.words[0];t=r===e?0:re.length)return 1;if(this.length=0;s--){var a=0|this.words[s],r=0|e.words[s];if(a!==r){ar&&(t=1);break}}return t},n.prototype.gtn=function(e){return 1===this.cmpn(e)},n.prototype.gt=function(e){return 1===this.cmp(e)},n.prototype.gten=function(e){return this.cmpn(e)>=0},n.prototype.gte=function(e){return this.cmp(e)>=0},n.prototype.ltn=function(e){return-1===this.cmpn(e)},n.prototype.lt=function(e){return-1===this.cmp(e)},n.prototype.lten=function(e){return this.cmpn(e)<=0},n.prototype.lte=function(e){return this.cmp(e)<=0},n.prototype.eqn=function(e){return 0===this.cmpn(e)},n.prototype.eq=function(e){return 0===this.cmp(e)},n.red=function(e){return new S(e)},n.prototype.toRed=function(e){return a(!this.red,"Already a number in reduction context"),a(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},n.prototype.fromRed=function(){return a(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},n.prototype._forceRed=function(e){return this.red=e,this},n.prototype.forceRed=function(e){return a(!this.red,"Already a number in reduction context"),this._forceRed(e)},n.prototype.redAdd=function(e){return a(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},n.prototype.redIAdd=function(e){return a(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},n.prototype.redSub=function(e){return a(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},n.prototype.redISub=function(e){return a(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},n.prototype.redShl=function(e){return a(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},n.prototype.redMul=function(e){return a(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},n.prototype.redIMul=function(e){return a(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},n.prototype.redSqr=function(){return a(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},n.prototype.redISqr=function(){return a(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},n.prototype.redSqrt=function(){return a(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},n.prototype.redInvm=function(){return a(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},n.prototype.redNeg=function(){return a(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},n.prototype.redPow=function(e){return a(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var w={k256:null,p224:null,p192:null,p25519:null};function g(e,t){this.name=e,this.p=new n(t,16),this.n=this.p.bitLength(),this.k=new n(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function y(){g.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function b(){g.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function v(){g.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function M(){g.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function S(e){if("string"==typeof e){var t=n._prime(e);this.m=t.p,this.prime=t}else a(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function I(e){S.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new n(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}g.prototype._tmp=function(){var e=new n(null);return e.words=new Array(Math.ceil(this.n/13)),e},g.prototype.ireduce=function(e){var t,s=e;do{this.split(s,this.tmp),t=(s=(s=this.imulK(s)).iadd(this.tmp)).bitLength()}while(t>this.n);var a=t0?s.isub(this.p):void 0!==s.strip?s.strip():s._strip(),s},g.prototype.split=function(e,t){e.iushrn(this.n,0,t)},g.prototype.imulK=function(e){return e.imul(this.k)},r(y,g),y.prototype.split=function(e,t){for(var s=Math.min(e.length,9),a=0;a>>22,r=n}r>>>=22,e.words[a-10]=r,0===r&&e.length>10?e.length-=10:e.length-=9},y.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,s=0;s>>=26,e.words[s]=r,t=a}return 0!==t&&(e.words[e.length++]=t),e},n._prime=function(e){if(w[e])return w[e];var t;if("k256"===e)t=new y;else if("p224"===e)t=new b;else if("p192"===e)t=new v;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new M}return w[e]=t,t},S.prototype._verify1=function(e){a(0===e.negative,"red works only with positives"),a(e.red,"red works only with red numbers")},S.prototype._verify2=function(e,t){a(0==(e.negative|t.negative),"red works only with positives"),a(e.red&&e.red===t.red,"red works only with red numbers")},S.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},S.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},S.prototype.add=function(e,t){this._verify2(e,t);var s=e.add(t);return s.cmp(this.m)>=0&&s.isub(this.m),s._forceRed(this)},S.prototype.iadd=function(e,t){this._verify2(e,t);var s=e.iadd(t);return s.cmp(this.m)>=0&&s.isub(this.m),s},S.prototype.sub=function(e,t){this._verify2(e,t);var s=e.sub(t);return s.cmpn(0)<0&&s.iadd(this.m),s._forceRed(this)},S.prototype.isub=function(e,t){this._verify2(e,t);var s=e.isub(t);return s.cmpn(0)<0&&s.iadd(this.m),s},S.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},S.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},S.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},S.prototype.isqr=function(e){return this.imul(e,e.clone())},S.prototype.sqr=function(e){return this.mul(e,e)},S.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(a(t%2==1),3===t){var s=this.m.add(new n(1)).iushrn(2);return this.pow(e,s)}for(var r=this.m.subn(1),i=0;!r.isZero()&&0===r.andln(1);)i++,r.iushrn(1);a(!r.isZero());var o=new n(1).toRed(this),c=o.redNeg(),u=this.m.subn(1).iushrn(1),d=this.m.bitLength();for(d=new n(2*d*d).toRed(this);0!==this.pow(d,u).cmp(c);)d.redIAdd(c);for(var h=this.pow(d,r),l=this.pow(e,r.addn(1).iushrn(1)),f=this.pow(e,r),m=i;0!==f.cmp(o);){for(var p=f,w=0;0!==p.cmp(o);w++)p=p.redSqr();a(w=0;a--){for(var u=t.words[a],d=c-1;d>=0;d--){var h=u>>d&1;r!==s[0]&&(r=this.sqr(r)),0!==h||0!==i?(i<<=1,i|=h,(4===++o||0===a&&0===d)&&(r=this.mul(r,s[i]),o=0,i=0)):o=0}c=26}return r},S.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},S.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},n.mont=function(e){return new I(e)},r(I,S),I.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},I.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},I.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var s=e.imul(t),a=s.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=s.isub(a).iushrn(this.shift),n=r;return r.cmp(this.m)>=0?n=r.isub(this.m):r.cmpn(0)<0&&(n=r.iadd(this.m)),n._forceRed(this)},I.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new n(0)._forceRed(this);var s=e.mul(t),a=s.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=s.isub(a).iushrn(this.shift),i=r;return r.cmp(this.m)>=0?i=r.isub(this.m):r.cmpn(0)<0&&(i=r.iadd(this.m)),i._forceRed(this)},I.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e,this)}).call(this,s(19)(e))},function(e,t,s){var a=s(7);e.exports=y,y.simpleSieve=w,y.fermatTest=g;var r=s(5),n=new r(24),i=new(s(9)),o=new r(1),c=new r(2),u=new r(5),d=(new r(16),new r(8),new r(10)),h=new r(3),l=(new r(7),new r(11)),f=new r(4),m=(new r(12),null);function p(){if(null!==m)return m;var e=[];e[0]=2;for(var t=1,s=3;s<1048576;s+=2){for(var a=Math.ceil(Math.sqrt(s)),r=0;re;)s.ishrn(1);if(s.isEven()&&s.iadd(o),s.testn(1)||s.iadd(c),t.cmp(c)){if(!t.cmp(u))for(;s.mod(d).cmp(h);)s.iadd(f)}else for(;s.mod(n).cmp(l);)s.iadd(f);if(w(m=s.shrn(1))&&w(s)&&g(m)&&g(s)&&i.test(m)&&i.test(s))return s}}},function(e,t,s){"use strict";(function(t,a){var r=s(18).Buffer,n=t.crypto||t.msCrypto;n&&n.getRandomValues?e.exports=function(e,t){if(e>4294967295)throw new RangeError("requested too many random bytes");var s=r.allocUnsafe(e);if(e>0)if(e>65536)for(var i=0;i1)for(var s=1;s=0);return r},n.prototype._randrange=function(e,t){var s=t.sub(e);return e.add(this._randbelow(s))},n.prototype.test=function(e,t,s){var r=e.bitLength(),n=a.mont(e),i=new a(1).toRed(n);t||(t=Math.max(1,r/48|0));for(var o=e.subn(1),c=0;!o.testn(c);c++);for(var u=e.shrn(c),d=o.toRed(n);t>0;t--){var h=this._randrange(new a(2),o);s&&s(h);var l=h.toRed(n).redPow(u);if(0!==l.cmp(i)&&0!==l.cmp(d)){for(var f=1;f0;t--){var d=this._randrange(new a(2),i),h=e.gcd(d);if(0!==h.cmpn(1))return h;var l=d.toRed(r).redPow(c);if(0!==l.cmp(n)&&0!==l.cmp(u)){for(var f=1;f=64;){let f,m,p,w,g,y=s,b=a,v=r,M=n,S=i,I=o,P=c,E=u;for(m=0;m<16;m++)p=h+4*m,d[m]=(255&e[p])<<24|(255&e[p+1])<<16|(255&e[p+2])<<8|255&e[p+3];for(m=16;m<64;m++)f=d[m-2],w=(f>>>17|f<<15)^(f>>>19|f<<13)^f>>>10,f=d[m-15],g=(f>>>7|f<<25)^(f>>>18|f<<14)^f>>>3,d[m]=(w+d[m-7]|0)+(g+d[m-16]|0)|0;for(m=0;m<64;m++)w=(((S>>>6|S<<26)^(S>>>11|S<<21)^(S>>>25|S<<7))+(S&I^~S&P)|0)+(E+(t[m]+d[m]|0)|0)|0,g=((y>>>2|y<<30)^(y>>>13|y<<19)^(y>>>22|y<<10))+(y&b^y&v^b&v)|0,E=P,P=I,I=S,S=M+w|0,M=v,v=b,b=y,y=w+g|0;s=s+y|0,a=a+b|0,r=r+v|0,n=n+M|0,i=i+S|0,o=o+I|0,c=c+P|0,u=u+E|0,h+=64,l-=64}}h(e);let l,f=e.length%64,m=e.length/536870912|0,p=e.length<<3,w=f<56?56:120,g=e.slice(e.length-f,e.length);for(g.push(128),l=f+1;l>>24&255),g.push(m>>>16&255),g.push(m>>>8&255),g.push(m>>>0&255),g.push(p>>>24&255),g.push(p>>>16&255),g.push(p>>>8&255),g.push(p>>>0&255),h(g),[s>>>24&255,s>>>16&255,s>>>8&255,s>>>0&255,a>>>24&255,a>>>16&255,a>>>8&255,a>>>0&255,r>>>24&255,r>>>16&255,r>>>8&255,r>>>0&255,n>>>24&255,n>>>16&255,n>>>8&255,n>>>0&255,i>>>24&255,i>>>16&255,i>>>8&255,i>>>0&255,o>>>24&255,o>>>16&255,o>>>8&255,o>>>0&255,c>>>24&255,c>>>16&255,c>>>8&255,c>>>0&255,u>>>24&255,u>>>16&255,u>>>8&255,u>>>0&255]}function r(e,t,s){e=e.length<=64?e:a(e);const r=64+t.length+4,n=new Array(r),i=new Array(64);let o,c=[];for(o=0;o<64;o++)n[o]=54;for(o=0;o=r-4;e--){if(n[e]++,n[e]<=255)return;n[e]=0}}for(;s>=32;)u(),c=c.concat(a(i.concat(a(n)))),s-=32;return s>0&&(u(),c=c.concat(a(i.concat(a(n))).slice(0,s))),c}function n(e,t,s,a,r){let n;for(u(e,16*(2*s-1),r,0,16),n=0;n<2*s;n++)c(e,16*n,r,16),o(r,a),u(r,0,e,t+16*n,16);for(n=0;n>>32-t}function o(e,t){u(e,0,t,0,16);for(let e=8;e>0;e-=2)t[4]^=i(t[0]+t[12],7),t[8]^=i(t[4]+t[0],9),t[12]^=i(t[8]+t[4],13),t[0]^=i(t[12]+t[8],18),t[9]^=i(t[5]+t[1],7),t[13]^=i(t[9]+t[5],9),t[1]^=i(t[13]+t[9],13),t[5]^=i(t[1]+t[13],18),t[14]^=i(t[10]+t[6],7),t[2]^=i(t[14]+t[10],9),t[6]^=i(t[2]+t[14],13),t[10]^=i(t[6]+t[2],18),t[3]^=i(t[15]+t[11],7),t[7]^=i(t[3]+t[15],9),t[11]^=i(t[7]+t[3],13),t[15]^=i(t[11]+t[7],18),t[1]^=i(t[0]+t[3],7),t[2]^=i(t[1]+t[0],9),t[3]^=i(t[2]+t[1],13),t[0]^=i(t[3]+t[2],18),t[6]^=i(t[5]+t[4],7),t[7]^=i(t[6]+t[5],9),t[4]^=i(t[7]+t[6],13),t[5]^=i(t[4]+t[7],18),t[11]^=i(t[10]+t[9],7),t[8]^=i(t[11]+t[10],9),t[9]^=i(t[8]+t[11],13),t[10]^=i(t[9]+t[8],18),t[12]^=i(t[15]+t[14],7),t[13]^=i(t[12]+t[15],9),t[14]^=i(t[13]+t[12],13),t[15]^=i(t[14]+t[13],18);for(let s=0;s<16;++s)e[s]+=t[s]}function c(e,t,s,a){for(let r=0;r=256)return!1}return!0}function h(e,t){if("number"!=typeof e||e%1)throw new Error("invalid "+t);return e}function l(e,s,a,i,o,l,f){if(a=h(a,"N"),i=h(i,"r"),o=h(o,"p"),l=h(l,"dkLen"),0===a||0!=(a&a-1))throw new Error("N must be power of 2");if(a>2147483647/128/i)throw new Error("N too large");if(i>2147483647/128/o)throw new Error("r too large");if(!d(e))throw new Error("password must be an array or buffer");if(e=Array.prototype.slice.call(e),!d(s))throw new Error("salt must be an array or buffer");s=Array.prototype.slice.call(s);let m=r(e,s,128*o*i);const p=new Uint32Array(32*o*i);for(let e=0;eA&&(t=A);for(let e=0;eA&&(t=A);for(let e=0;e>0&255),m.push(p[e]>>8&255),m.push(p[e]>>16&255),m.push(p[e]>>24&255);const s=r(e,m,l);return f&&f(null,1,s),s}f&&T(k)};if(!f)for(;;){const e=k();if(null!=e)return e}k()}const f={scrypt:function(e,t,s,a,r,n,i){return new Promise((function(o,c){let u=0;i&&i(0),l(e,t,s,a,r,n,(function(e,t,s){if(e)c(e);else if(s)i&&1!==u&&i(1),o(new Uint8Array(s));else if(i&&t!==u)return u=t,i(t)}))}))},syncScrypt:function(e,t,s,a,r,n){return new Uint8Array(l(e,t,s,a,r,n))}};e.exports=f}()}).call(this,s(25).setImmediate)},function(e,t,s){var a,r=function(){var e,t,s=((t=(e={constructor:function(e,t){this.array=[],this.compare=t||a;for(var s=e.length,r=0;r=i;)if((s=r(a[t=(n+i)/2>>>0],e))<0)i=t+1;else{if(!(s>0)){o=t;break}n=t-1}for(-1===o&&(o=n),o++,n=a.length-1;oo;)a[t]=a[--t];return a[o]=e,this},search:function(e){for(var t,s,a=this.array,r=this.compare,n=a.length-1,i=0;n>=i;)if((s=r(a[t=(n+i)/2>>>0],e))<0)i=t+1;else{if(!(s>0))return t;n=t-1}return-1},remove:function(e){var t=this.search(e);return t>=0&&this.array.splice(t,1),this}}).constructor).prototype=e,t);return s.comparing=function(e,t){return new s(t,(function(t,s){return a(t[e],s[e])}))},s;function a(e,t){return et?1:0}}();e.exports=r,void 0===(a=function(){return r}.call(t,s,t,e))||(e.exports=a)},function(e,t){var s="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(s){var a=new Uint8Array(16);e.exports=function(){return s(a),a}}else{var r=new Array(16);e.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),r[t]=e>>>((3&t)<<3)&255;return r}}},function(e,t){for(var s=[],a=0;a<256;++a)s[a]=(a+256).toString(16).substr(1);e.exports=function(e,t){var a=t||0,r=s;return[r[e[a++]],r[e[a++]],r[e[a++]],r[e[a++]],"-",r[e[a++]],r[e[a++]],"-",r[e[a++]],r[e[a++]],"-",r[e[a++]],r[e[a++]],"-",r[e[a++]],r[e[a++]],r[e[a++]],r[e[a++]],r[e[a++]],r[e[a++]]].join("")}},function(e,t,s){"use strict";t.byteLength=function(e){var t=u(e),s=t[0],a=t[1];return 3*(s+a)/4-a},t.toByteArray=function(e){var t,s,a=u(e),i=a[0],o=a[1],c=new n(function(e,t,s){return 3*(t+s)/4-s}(0,i,o)),d=0,h=o>0?i-4:i;for(s=0;s>16&255,c[d++]=t>>8&255,c[d++]=255&t;2===o&&(t=r[e.charCodeAt(s)]<<2|r[e.charCodeAt(s+1)]>>4,c[d++]=255&t);1===o&&(t=r[e.charCodeAt(s)]<<10|r[e.charCodeAt(s+1)]<<4|r[e.charCodeAt(s+2)]>>2,c[d++]=t>>8&255,c[d++]=255&t);return c},t.fromByteArray=function(e){for(var t,s=e.length,r=s%3,n=[],i=0,o=s-r;io?o:i+16383));1===r?(t=e[s-1],n.push(a[t>>2]+a[t<<4&63]+"==")):2===r&&(t=(e[s-2]<<8)+e[s-1],n.push(a[t>>10]+a[t>>4&63]+a[t<<2&63]+"="));return n.join("")};for(var a=[],r=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,c=i.length;o0)throw new Error("Invalid string. Length must be a multiple of 4");var s=e.indexOf("=");return-1===s&&(s=t),[s,s===t?0:4-s%4]}function d(e,t,s){for(var r,n,i=[],o=t;o>18&63]+a[n>>12&63]+a[n>>6&63]+a[63&n]);return i.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},function(e,t){ -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -t.read=function(e,t,s,a,r){var n,i,o=8*r-a-1,c=(1<>1,d=-7,h=s?r-1:0,l=s?-1:1,f=e[t+h];for(h+=l,n=f&(1<<-d)-1,f>>=-d,d+=o;d>0;n=256*n+e[t+h],h+=l,d-=8);for(i=n&(1<<-d)-1,n>>=-d,d+=a;d>0;i=256*i+e[t+h],h+=l,d-=8);if(0===n)n=1-u;else{if(n===c)return i?NaN:1/0*(f?-1:1);i+=Math.pow(2,a),n-=u}return(f?-1:1)*i*Math.pow(2,n-a)},t.write=function(e,t,s,a,r,n){var i,o,c,u=8*n-r-1,d=(1<>1,l=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,f=a?0:n-1,m=a?1:-1,p=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,i=d):(i=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-i))<1&&(i--,c*=2),(t+=i+h>=1?l/c:l*Math.pow(2,1-h))*c>=2&&(i++,c/=2),i+h>=d?(o=0,i=d):i+h>=1?(o=(t*c-1)*Math.pow(2,r),i+=h):(o=t*Math.pow(2,h-1)*Math.pow(2,r),i=0));r>=8;e[s+f]=255&o,f+=m,o/=256,r-=8);for(i=i<0;e[s+f]=255&i,f+=m,i/=256,u-=8);e[s+f-m]|=128*p}},function(e,t){var s={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==s.call(e)}},function(e,t,s){ -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -var a=s(4),r=a.Buffer;function n(e,t){for(var s in e)t[s]=e[s]}function i(e,t,s){return r(e,t,s)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=a:(n(a,t),t.Buffer=i),i.prototype=Object.create(r.prototype),n(r,i),i.from=function(e,t,s){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,s)},i.alloc=function(e,t,s){if("number"!=typeof e)throw new TypeError("Argument must be a number");var a=r(e);return void 0!==t?"string"==typeof s?a.fill(t,s):a.fill(t):a.fill(0),a},i.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return a.SlowBuffer(e)}},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t){},function(e,t,s){var a;function r(e){this.rand=e}if(e.exports=function(e){return a||(a=new r(null)),a.generate(e)},e.exports.Rand=r,r.prototype.generate=function(e){return this._rand(e)},r.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),s=0;s=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},s(26),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(this,s(3))},function(e,t,s){(function(e,t){!function(e,s){"use strict";if(!e.setImmediate){var a,r,n,i,o,c=1,u={},d=!1,h=e.document,l=Object.getPrototypeOf&&Object.getPrototypeOf(e);l=l&&l.setTimeout?l:e,"[object process]"==={}.toString.call(e.process)?a=function(e){t.nextTick((function(){m(e)}))}:!function(){if(e.postMessage&&!e.importScripts){var t=!0,s=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=s,t}}()?e.MessageChannel?((n=new MessageChannel).port1.onmessage=function(e){m(e.data)},a=function(e){n.port2.postMessage(e)}):h&&"onreadystatechange"in h.createElement("script")?(r=h.documentElement,a=function(e){var t=h.createElement("script");t.onreadystatechange=function(){m(e),t.onreadystatechange=null,r.removeChild(t),t=null},r.appendChild(t)}):a=function(e){setTimeout(m,0,e)}:(i="setImmediate$"+Math.random()+"$",o=function(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(i)&&m(+t.data.slice(i.length))},e.addEventListener?e.addEventListener("message",o,!1):e.attachEvent("onmessage",o),a=function(t){e.postMessage(i+t,"*")}),l.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),s=0;s{if(!ls)throw new hs.AppIdNotSet;return ls},gs=()=>fs,ys=()=>window._userbaseEndpoint||"https://v1.userbase.com/v1",bs=({appId:e,updateUserHandler:t,allowServerSideEncryption:s})=>{if(ls&&ls!==e)throw new hs.AppIdAlreadySet(ls);ls=e,fs=t,ms=s},vs=e=>e?window._USERBASE_STRIPE_PRODUCTION_PUBLISHABLE_KEY||"pk_live_jI6lbsAIQlu2u4uTkDXFrSEW":window._USERBASE_STRIPE_TEST_PUBLISHABLE_KEY||"pk_test_rYANrLdNfdJXJ2d808wW4pqY",Ms=()=>ms;class Ss extends Error{constructor(e,t,s,...a){super(e,t,s,...a),this.response={data:e,status:t,statusText:s},this.message="Request failed with status code "+t}}class Is extends Error{constructor(e,...t){super(e,...t),this.message="timeout of ".concat(e,"ms exceeded")}}const Ps=(e,t,s,a=1e4)=>{e.timeout=a,e.onload=()=>((e,t,s)=>{let a;try{a=JSON.parse(e.response)}catch(t){a=e.response}e.status>=200&&e.status<300?t(a):s(new Ss(a,e.status,e.statusText))})(e,t,s),e.onerror=()=>s(new hs.ServiceUnavailable),e.ontimeout=()=>s(new Is(a))};var Es=(e,t,s,a,r,n,i,o,c)=>new Promise((u,d)=>{const h=new XMLHttpRequest,l="".concat(ys(),"/api/auth/sign-up?appId=").concat(ws(),"&userbaseJsVersion=").concat(ps),f=JSON.stringify({username:e,passwordToken:t,ecKeyData:s,passwordSalts:a,keySalts:r,email:n,profile:i,passwordBasedBackup:o,sessionLength:c});h.open("POST",l),h.setRequestHeader("Content-Type","application/json"),h.send(f),Ps(h,u,d)}),Bs=e=>new Promise((t,s)=>{const a=new XMLHttpRequest,r="".concat(ys(),"/api/auth/get-password-salts?appId=").concat(ws(),"&username=").concat(encodeURIComponent(e),"&userbaseJsVersion=").concat(ps);a.open("GET",r),a.send(),Ps(a,t,s)}),Ns=async(e,t,s)=>new Promise((a,r)=>{const n=new XMLHttpRequest,i="".concat(ys(),"/api/auth/sign-in?appId=").concat(ws(),"&userbaseJsVersion=").concat(ps),o=JSON.stringify({username:e,passwordToken:t,sessionLength:s});n.open("POST",i),n.setRequestHeader("Content-Type","application/json"),n.send(o),Ps(n,a,r)}),Us=(e,t)=>new Promise((s,a)=>{const r=new XMLHttpRequest,n="".concat(ys(),"/api/auth/sign-in-with-session?appId=").concat(ws(),"&sessionId=").concat(e,"&userbaseJsVersion=").concat(ps),i=JSON.stringify({sessionLength:t});r.open("POST",n),r.setRequestHeader("Content-Type","application/json"),r.send(i),Ps(r,s,a)}),As=async()=>new Promise((e,t)=>{const s=new XMLHttpRequest,a="".concat(ys(),"/api/auth/server-public-key?&userbaseJsVersion=").concat(ps);s.open("GET",a),s.responseType="arraybuffer",s.send(),Ps(s,e,t)}),Ts=e=>new Promise((t,s)=>{const a=new XMLHttpRequest,r="".concat(ys(),"/api/public-key?appId=").concat(ws(),"&username=").concat(encodeURIComponent(e),"&userbaseJsVersion=").concat(ps);a.open("GET",r),a.send(),Ps(a,t,s)}),ks=s(2),Ds=s.n(ks);function Ks(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,a)}return s}function xs(e){for(var t=1;t(...t)=>{try{return e(...t)}catch(e){console.warn("Error accessing browser storage. Defaulting to memory.\n\n",e)}},Os=(e,t)=>"userbaseSeed.".concat(e,".").concat(t),Cs=Rs((e,t,s,a,r,n)=>{const i={username:t,signedIn:s,sessionId:a,creationDate:r,expirationDate:n},o=JSON.stringify(i);"local"===e?localStorage.setItem("userbaseCurrentSession",o):"session"===e&&sessionStorage.setItem("userbaseCurrentSession",o)});var _s={signInSession:(e,t,s,a,r)=>{Cs(e,t,!0,s,a,r)},signOutSession:(e,t)=>{Cs(e,t,!1)},getCurrentSession:Rs(()=>{const e=sessionStorage.getItem("userbaseCurrentSession");if(e){if(!JSON.parse(e).signedIn){const e=localStorage.getItem("userbaseCurrentSession");if(e){const t=JSON.parse(e);if(t.signedIn)return xs(xs({},t),{},{rememberMe:"local"})}}return xs(xs({},JSON.parse(e)),{},{rememberMe:"session"})}const t=localStorage.getItem("userbaseCurrentSession");return t&&xs(xs({},JSON.parse(t)),{},{rememberMe:"local"})}),saveSeedString:Rs((e,t,s,a)=>{"local"===e?localStorage.setItem(Os(t,s),a):"session"===e&&sessionStorage.setItem(Os(t,s),a)}),removeSeedString:Rs((e,t)=>{const s=Os(e,t);sessionStorage.removeItem(s),localStorage.removeItem(s)}),getSeedString:Rs((e,t)=>{const s=Os(e,t);return sessionStorage.getItem(s)||localStorage.getItem(s)}),removeCurrentSession:Rs(()=>{sessionStorage.removeItem("userbaseCurrentSession"),localStorage.removeItem("userbaseCurrentSession")})};const Fs=(e,t)=>{const s=t?new Uint8Array(e):new Uint16Array(e),a=s.length;let r="",n=10240;for(var i=0;ia&&(n=a-i);const e=s.subarray(i,i+n);r+=String.fromCharCode.apply(null,e)}return r},Ls=(e,t=!1)=>{let s=new ArrayBuffer(e.length*(t?1:2)),a=t?new Uint8Array(s):new Uint16Array(s);for(let t=0,s=e.length;t{const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer},qs=async e=>await window.crypto.subtle.digest({name:"SHA-256"},e);var Vs={BYTE_SIZE:32,HASH_ALGORITHM_NAME:"SHA-256",hash:qs,hashBase64String:async e=>{const t=i.a.decode(e),s=await qs(t);return i.a.encode(s)},hashString:async e=>{const t=Ls(e),s=await qs(t);return i.a.encode(s)}};const Hs=["deriveKey","deriveBits"],Gs=async e=>await window.crypto.subtle.importKey("raw",e,{name:"HKDF"},!1,Hs),Js=Vs.BYTE_SIZE,Ws=(e,t)=>({name:"HKDF",info:Ls(e),hash:Vs.HASH_ALGORITHM_NAME,salt:t});var Ys={importHkdfKeyFromString:async e=>{const t=Ls(e);return await Gs(t)},importHkdfKey:Gs,generateSalt:()=>window.crypto.getRandomValues(new Uint8Array(Js)),getParams:Ws,getPasswordToken:async(e,t)=>{const s=await window.crypto.subtle.deriveBits(Ws("password-token",t),e,256);return i.a.encode(s)}};const zs=["encrypt","decrypt"],Zs=()=>"undefined"!=typeof window?window:self,Xs=()=>({name:"AES-GCM",length:256}),Qs=e=>({name:"AES-GCM",tagLength:128,iv:e}),$s=()=>window.crypto.getRandomValues(new Uint8Array(12)),ea=e=>{const t=e.byteLength-12;return{ciphertextArrayBuffer:e.slice(0,t),iv:e.slice(t)}},ta=async()=>await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,zs),sa=async e=>await Zs().crypto.subtle.importKey("raw",e,{name:"AES-GCM"},!0,zs),aa=async e=>await Zs().crypto.subtle.exportKey("raw",e),ra=async(e,t)=>{const s=$s(),a=await Zs().crypto.subtle.encrypt(Qs(s),e,t);return js(a,s)},na=async(e,t)=>{const s=Ls(t),a=await ra(e,s);return i.a.encode(a)},ia=async(e,t)=>{const{ciphertextArrayBuffer:s,iv:a}=ea(t);return await Zs().crypto.subtle.decrypt(Qs(a),e,s)},oa=async(e,t)=>{const s=i.a.decode(t),a=await ia(e,s);return Fs(a)};var ca={getEncryptionKeyParams:Xs,getCiphertextParams:Qs,generateIv:$s,sliceEncryptedArrayBuffer:ea,importKeyFromMaster:async(e,t,s="encryption")=>await window.crypto.subtle.deriveKey(Ys.getParams(s,t),e,{name:"AES-GCM",length:256},!0,zs),generateKey:ta,getKeyStringFromKey:async e=>{const t=await window.crypto.subtle.exportKey("raw",e);return i.a.encode(t)},getKeyFromKeyString:async e=>{const t=i.a.decode(e);return await sa(t)},getRawKeyFromKey:aa,getKeyFromRawKey:sa,encrypt:ra,encryptJson:async(e,t)=>{const s=JSON.stringify(t);return await na(e,s)},encryptString:na,decrypt:ia,decryptJson:async(e,t)=>{const s=await oa(e,t);return JSON.parse(s)},decryptString:oa,getPasswordBasedEncryptionKey:async(e,t)=>await window.crypto.subtle.deriveKey(Ys.getParams("password-based-encryption",t),e,{name:"AES-GCM",length:256},!1,zs),generateAndEncryptKeyEncryptionKey:async e=>{const t=await ta(),s=await aa(t);return[t,await ra(e,s)]},RAW_KEY_TYPE:"raw",KEY_WILL_BE_USED_TO:zs},ua=s(10),da=s.n(ua);const ha=["encrypt"],la=(e=>{if(e.length%2!=0)throw new Error("Hex string must be even length");const t=e.length/2,s=[];for(let a=0;a((e,t)=>(e.setPrivateKey(t),e.generateKeys(),e))(da.a.createDiffieHellman(la,fa),e),wa=async(e,t)=>{const s=pa(e).computeSecret(t),a=await Vs.hash(s);return await ca.getKeyFromRawKey(a)};var ga={getPublicKey:e=>pa(e).getPublicKey(),getSharedKey:wa,getSharedKeyWithServer:async e=>await wa(e,new Uint8Array(await(async()=>ma||(ma=await As(),ma))())),importKeyFromMaster:async(e,t)=>{const s=await window.crypto.subtle.deriveKey(Ys.getParams("diffie-hellman",t),e,ca.getEncryptionKeyParams(),!0,ha);return await ca.getRawKeyFromKey(s)}};const ya=["sign","verify"],ba=["sign"],va=["verify"],Ma={name:"ECDSA",namedCurve:"P-256"},Sa={name:"ECDSA",hash:{name:Vs.HASH_ALGORITHM_NAME}},Ia=async e=>await window.crypto.subtle.exportKey("spki",e),Pa=async e=>{const t=await Ia(e);return i.a.encode(t)},Ea=async(e,t)=>await ca.importKeyFromMaster(e,t,"ecdsa-key-encryption-key"),Ba=async(e,t)=>await window.crypto.subtle.sign(Sa,e,t),Na=async(e,t,s)=>await window.crypto.subtle.verify(Sa,e,t,s);var Ua={generateEcdsaKeyData:async e=>{const t=await(async()=>await window.crypto.subtle.generateKey(Ma,!0,ya))(),s=Ys.generateSalt(),a=await Ea(e,s),r=await(async e=>{const t=await window.crypto.subtle.exportKey("jwk",e);return Ls(JSON.stringify(t))})(t.privateKey),n=await ca.encrypt(a,r);return{ecdsaPrivateKey:t.privateKey,ecdsaPublicKey:await Pa(t.publicKey),encryptedEcdsaPrivateKey:i.a.encode(n),ecdsaKeyEncryptionKeySalt:i.a.encode(s)}},importEcdsaKeyEncryptionKeyFromMaster:Ea,getPrivateKeyFromRawPrivateKey:async e=>{const t=JSON.parse(Fs(e));return await window.crypto.subtle.importKey("jwk",t,Ma,!0,ba)},getPublicKeyFromRawPublicKey:async e=>await window.crypto.subtle.importKey("spki",e,Ma,!0,va),getRawPublicKeyFromPublicKey:Ia,getPublicKeyStringFromPublicKey:Pa,getPublicKeyFromPrivateKey:async e=>{const t=await window.crypto.subtle.exportKey("jwk",e);delete t.d,t.key_ops=va;return await window.crypto.subtle.importKey("jwk",t,Ma,!0,va)},sign:Ba,signString:async(e,t)=>{const s=Ls(t),a=await Ba(e,s);return i.a.encode(a)},verify:Na,verifyString:async(e,t,s)=>{const a=Ls(s),r=i.a.decode(t);return await Na(e,r,a)}};const Aa=["deriveKey","deriveBits"],Ta={name:"ECDH",namedCurve:"P-256"},ka=async()=>await window.crypto.subtle.generateKey(Ta,!0,Aa),Da=async e=>await window.crypto.subtle.exportKey("spki",e),Ka=async(e,t)=>await ca.importKeyFromMaster(e,t,"ecdh-key-encryption-key");var xa={generateKeyPair:ka,generateEcdhKeyData:async(e,t)=>{const s=await ka(),a=Ys.generateSalt(),r=await Ka(e,a),n=await(async e=>{const t=await window.crypto.subtle.exportKey("jwk",e);return Ls(JSON.stringify(t))})(s.privateKey),o=await ca.encrypt(r,n),c=await Da(s.publicKey),u=await Ua.sign(t,c);return{ecdhPrivateKey:s.privateKey,ecdhPublicKey:i.a.encode(c),encryptedEcdhPrivateKey:i.a.encode(o),signedEcdhPublicKey:i.a.encode(u),ecdhKeyEncryptionKeySalt:i.a.encode(a)}},importEcdhKeyEncryptionKeyFromMaster:Ka,getPrivateKeyFromRawPrivateKey:async e=>{const t=JSON.parse(Fs(e));return await window.crypto.subtle.importKey("jwk",t,Ta,!0,Aa)},getRawPublicKeyFromPublicKey:Da,getPublicKeyFromRawPublicKey:async e=>await window.crypto.subtle.importKey("spki",e,Ta,!0,[]),computeSharedKeyEncryptionKey:async(e,t)=>await window.crypto.subtle.deriveKey({name:"ECDH",namedCurve:"P-256",public:e},t,ca.getEncryptionKeyParams(),!1,ca.KEY_WILL_BE_USED_TO)};const Ra=["sign"],Oa=["sign","verify"],Ca=async(e,t)=>await window.crypto.subtle.sign({name:"HMAC"},e,t);var _a={importKeyFromMaster:async(e,t)=>await window.crypto.subtle.deriveKey(Ys.getParams("authentication",t),e,{name:"HMAC",hash:{name:Vs.HASH_ALGORITHM_NAME},length:512},!1,Ra),importKeyFromRawBits:async e=>await window.crypto.subtle.importKey("raw",e,{name:"HMAC",hash:{name:Vs.HASH_ALGORITHM_NAME},length:256},!1,Oa),sign:Ca,signString:async(e,t)=>{const s=await Ca(e,Ls(t));return i.a.encode(s)}},Fa=s(11),La=s.n(Fa);var ja={generateSeed:()=>window.crypto.getRandomValues(new Uint8Array(32)),aesGcm:ca,diffieHellman:ga,ecdsa:Ua,ecdh:xa,sha256:Vs,hmac:_a,hkdf:Ys,scrypt:{generateSalt:()=>window.crypto.getRandomValues(new Uint8Array(16)),hash:async(e,t,s=La.a.scrypt)=>{const a=new Uint8Array(Ls(e)),r=await s(a,t,16384,8,1,32);return i.a.encode(r)}}};const qa=e=>e.split(":")[0],Va=e=>{const t=(e=>"http://"===e.substring(0,"http://".length)?e.substring("http://".length):"https://"===e.substring(0,"https://".length)?e.substring("https://".length):e)(e);return("https"===qa(e)?"wss://":"ws://")+t},Ha=e=>2*e.length,Ga=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function Ja(){let e=[],t=0;this.getLength=()=>e.length-t,this.isEmpty=()=>0===e.length,this.enqueue=t=>(e.push(t),this.getLength()),this.dequeue=()=>{const s=e[t];return t+=1,2*t>e.length&&(e=e.slice(t),t=0),s},this.peek=()=>e[t]}const Wa=()=>{const e=URL.createObjectURL(new Blob(["(",function(){self.onmessage=function(e){const{compress:t,decompress:s,data:a}=e.data,r=function(){function e(e,t){if(!r[e]){r[e]={};for(var s=0;sa;a++){var i=t.charCodeAt(a);s[2*a]=i>>>8,s[2*a+1]=i%256}return s},decompressFromUint8Array:function(e){if(null==e)return n.decompress(e);for(var s=new Array(e.length/2),a=0,r=s.length;r>a;a++)s[a]=256*e[2*a]+e[2*a+1];var i=[];return s.forEach((function(e){i.push(t(e))})),n.decompress(i.join(""))},compressToEncodedURIComponent:function(e){return null==e?"":n._compress(e,6,(function(e){return a.charAt(e)}))},decompressFromEncodedURIComponent:function(t){return null==t?"":""==t?null:(t=t.replace(/ /g,"+"),n._decompress(t.length,32,(function(s){return e(a,t.charAt(s))})))},compress:function(e){return n._compress(e,16,(function(e){return t(e)}))},_compress:function(e,t,s){if(null==e)return"";var a,r,n,i={},o={},c="",u="",d="",h=2,l=3,f=2,m=[],p=0,w=0;for(n=0;na;a++)p<<=1,w==t-1?(w=0,m.push(s(p)),p=0):w++;for(r=d.charCodeAt(0),a=0;8>a;a++)p=p<<1|1&r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r>>=1}else{for(r=1,a=0;f>a;a++)p=p<<1|r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r=0;for(r=d.charCodeAt(0),a=0;16>a;a++)p=p<<1|1&r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r>>=1}0==--h&&(h=Math.pow(2,f),f++),delete o[d]}else for(r=i[d],a=0;f>a;a++)p=p<<1|1&r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r>>=1;0==--h&&(h=Math.pow(2,f),f++),i[u]=l++,d=String(c)}if(""!==d){if(Object.prototype.hasOwnProperty.call(o,d)){if(d.charCodeAt(0)<256){for(a=0;f>a;a++)p<<=1,w==t-1?(w=0,m.push(s(p)),p=0):w++;for(r=d.charCodeAt(0),a=0;8>a;a++)p=p<<1|1&r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r>>=1}else{for(r=1,a=0;f>a;a++)p=p<<1|r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r=0;for(r=d.charCodeAt(0),a=0;16>a;a++)p=p<<1|1&r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r>>=1}0==--h&&(h=Math.pow(2,f),f++),delete o[d]}else for(r=i[d],a=0;f>a;a++)p=p<<1|1&r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r>>=1;0==--h&&(h=Math.pow(2,f),f++)}for(r=2,a=0;f>a;a++)p=p<<1|1&r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r>>=1;for(;;){if(p<<=1,w==t-1){m.push(s(p));break}w++}return m.join("")},decompress:function(e){return null==e?"":""==e?null:n._decompress(e.length,32768,(function(t){return e.charCodeAt(t)}))},_decompress:function(e,s,a){var r,n,i,o,c,u,d,h=[],l=4,f=4,m=3,p="",w=[],g={val:a(0),position:s,index:1};for(r=0;3>r;r+=1)h[r]=r;for(i=0,c=Math.pow(2,2),u=1;u!=c;)o=g.val&g.position,g.position>>=1,0==g.position&&(g.position=s,g.val=a(g.index++)),i|=(o>0?1:0)*u,u<<=1;switch(i){case 0:for(i=0,c=Math.pow(2,8),u=1;u!=c;)o=g.val&g.position,g.position>>=1,0==g.position&&(g.position=s,g.val=a(g.index++)),i|=(o>0?1:0)*u,u<<=1;d=t(i);break;case 1:for(i=0,c=Math.pow(2,16),u=1;u!=c;)o=g.val&g.position,g.position>>=1,0==g.position&&(g.position=s,g.val=a(g.index++)),i|=(o>0?1:0)*u,u<<=1;d=t(i);break;case 2:return""}for(h[3]=d,n=d,w.push(d);;){if(g.index>e)return"";for(i=0,c=Math.pow(2,m),u=1;u!=c;)o=g.val&g.position,g.position>>=1,0==g.position&&(g.position=s,g.val=a(g.index++)),i|=(o>0?1:0)*u,u<<=1;switch(d=i){case 0:for(i=0,c=Math.pow(2,8),u=1;u!=c;)o=g.val&g.position,g.position>>=1,0==g.position&&(g.position=s,g.val=a(g.index++)),i|=(o>0?1:0)*u,u<<=1;h[f++]=t(i),d=f-1,l--;break;case 1:for(i=0,c=Math.pow(2,16),u=1;u!=c;)o=g.val&g.position,g.position>>=1,0==g.position&&(g.position=s,g.val=a(g.index++)),i|=(o>0?1:0)*u,u<<=1;h[f++]=t(i),d=f-1,l--;break;case 2:return w.join("")}if(0==l&&(l=Math.pow(2,m),m++),h[d])p=h[d];else{if(d!==f)return null;p=n+n.charAt(0)}w.push(p),h[f++]=n+p.charAt(0),n=p,0==--l&&(l=Math.pow(2,m),m++)}}};return n}();t?postMessage(r.compress(a)):s&&postMessage(r.decompress(a))}}.toString(),")()"],{type:"application/javascript"})),t=new Worker(e);return URL.revokeObjectURL(e),t},Ya=async e=>{const t=Wa();return new Promise(s=>{t.onmessage=e=>{s(e.data),t.terminate()},t.postMessage({compress:!0,data:e})})},za=async e=>{const t=Wa();return new Promise(s=>{t.onmessage=e=>{s(e.data),t.terminate()},t.postMessage({decompress:!0,data:e})})},Za=async(e,t,s,a,r,n)=>new Promise((i,o)=>{const c=new XMLHttpRequest,u="".concat(ys(),"/api/bundle-chunk?userbaseJsVersion=").concat(ps,"&")+"userId=".concat(e,"&")+"databaseId=".concat(t,"&")+"seqNo=".concat(s,"&")+"bundleId=".concat(a,"&")+"chunkNumber=".concat(r);c.open("POST",u),c.send(new Uint8Array(n)),Ps(c,i,o,3e4)});function Xa(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,a)}return s}function Qa(e){for(var t=1;t{let u=!1;const d=setTimeout(()=>{this.connected||this.reconnecting||(u=!0,c(new tr("timeout")))},1e4),h="".concat(Va(ys()),"/api?appId=").concat(ws(),"&sessionId=").concat(e.sessionId,"&clientId=").concat($a,"&userbaseJsVersion=").concat(ps),l=new WebSocket(h);l.onopen=async()=>{u||clearTimeout(d)},l.onmessage=async r=>{if(!u)try{const u=JSON.parse(r.data);switch(u.route){case"Ping":{this.heartbeat();const e="Pong";this.ws.send(JSON.stringify({action:e}));break}case"Connection":{const{encryptionMode:o}=u;if(this.init(i,c,e,t,s,a,n,o),this.ws=l,this.heartbeat(),this.connected=!0,t){const{keySalts:e,validationMessage:t,ecKeyData:s,encryptedValidationMessage:a}=u;this.keys.salts=e,this.validationMessage=t,this.ecKeyData=s,a&&(this.encryptedValidationMessage=new Uint8Array(a.data));try{await this.setKeys(this.seedString);const e=await this.validateKey();this.userData=e}catch(r){throw r&&"OperationError"===r.name||r instanceof DOMException?new Error("Invalid seed"):r}this.keys.init=!0}this.resolveConnection(),this.connectionResolved=!0;break}case"ApplyTransactions":{const e=u.dbId,t=u.dbNameHash,s=u.isOwner?this.state.databases[t]:this.state.databasesByDbId[e];if(!s)throw new Error("Missing database");s.applyTransactionsQueue.isEmpty()?s.applyTransactionsQueue.enqueue(null):await new Promise(e=>{const t=e;s.applyTransactionsQueue.enqueue(t)});if((u.dbNameHash&&(u.dbKey||u.plaintextDbKey)||u.shareTokenEncryptedDbKey)&&(!s.dbKeyString||!s.dbKey)){const e=u.plaintextDbKey||(u.dbKey?await ja.aesGcm.decryptString(this.keys.encryptionKey,u.dbKey):await s.decryptShareTokenEncryptedDbKey(u.shareTokenEncryptedDbKey,u.shareTokenEncryptionKeySalt));s.dbKeyString=e,s.dbKey=await ja.aesGcm.getKeyFromKeyString(e)}if(!s.dbKey)throw new Error("Missing db key");if(u.writers){s.attributionEnabled=!0;for(const{userId:e,username:t}of u.writers)s.usernamesByUserId.set(e,t)}if(u.waitForFullBundle){s.finishedWaitingForBundle||await new Promise(e=>s.finishedWaitingForBundle=e);try{const e=await this.rebuildBundle(s,u.bundleSeqNo,u.encryptedBundleEncryptionKey);await s.applyBundle(e,u.bundleSeqNo)}catch(r){throw window.alert("Oops! Something went wrong. Please contact the site administrator with this issue (".concat(e,").\n\n")+r),r}}const a=u.transactionLog;if(await s.applyTransactions(a,u.ownerId,e,t),u.buildBundle&&this.buildBundle(s),s.applyTransactionsQueue.dequeue(),!s.applyTransactionsQueue.isEmpty()){s.applyTransactionsQueue.peek()()}break}case"DownloadBundleChunk":{const{dbId:e,dbNameHash:t,isOwner:s,bundleSeqNo:a,isFirstChunk:r,isLastChunk:n,chunk:i}=u,o=s?this.state.databases[t]:this.state.databasesByDbId[e];if(!o)throw new Error("Missing database");r&&(o.bundleChunks[a]=[]),o.bundleChunks[a].push(i),n&&(o.finishedWaitingForBundle?o.finishedWaitingForBundle():o.finishedWaitingForBundle=!0);break}case"UpdatedUser":this.handleUpdateUser(u.updatedUser);break;case"SignOut":case"UpdateUser":case"DeleteUser":case"CreateDatabase":case"OpenDatabase":case"OpenDatabaseByDatabaseId":case"GetDatabases":case"GetDatabaseUsers":case"Insert":case"Update":case"Delete":case"BatchTransaction":case"InitBundleUpload":case"CompleteBundleUpload":case"GenerateFileId":case"UploadFileChunk":case"CompleteFileUpload":case"GetChunk":case"ValidateKey":case"GetPasswordSalts":case"PurchaseSubscription":case"CancelSubscription":case"ResumeSubscription":case"UpdatePaymentMethod":case"ShareDatabase":case"ShareDatabaseToken":case"AuthenticateShareToken":case"SaveDatabase":case"ModifyDatabasePermissions":case"VerifyUser":{const e=u.requestId;if(!e)return console.warn("Missing request id");const t=this.requests[e];if(!t)return console.warn("Request ".concat(e," no longer exists!"));if(!t.promiseResolve||!t.promiseReject)return;const s=u.response;return s&&s.status===o?t.promiseResolve(s):t.promiseReject(s)}default:console.log("Received unknown message from backend:"+JSON.stringify(u))}}catch(r){this.connectionResolved?console.warn("Error handling message: ",r):(this.close(),c(new tr(r.message,e.username,r)))}},l.onclose=async o=>{if(u)return;const d=o.code===y,h=o.code===b;if(d||h||!o.wasClean){const o=d&&!r?0:r?r+1e3:1e3;this.reconnecting=!0,await this.reconnect(i,c,e,this.seedString||t,s,a,o,!this.reconnected&&n)}else o.code===v?c(new tr("Web Socket already connected",e.username,o)):this.init()},l.onerror=()=>{}})}async reconnect(e,t,s,a,r,n,i,o){try{const t=Math.min(i,3e4);console.log("Connection to server lost. Attempting to reconnect in ".concat(t/1e3," second").concat(1e3!==t?"s":"","..."));const c=[],u=[];e(await new Promise((e,d)=>setTimeout(async()=>{try{const t=o||{dbNameToHash:Qa({},this.state.dbNameToHash),databases:Qa({},this.state.databases),databasesByDbId:Qa({},this.state.databasesByDbId),shareTokenIdToDbId:Qa({},this.state.shareTokenIdToDbId)};for(const e in t.databases)t.databases[e].init=!1,t.databases[e].finishedWaitingForBundle=!1,c.push(e);for(const e in t.databasesByDbId)t.databasesByDbId[e].init=!1,t.databasesByDbId[e].finishedWaitingForBundle=!1,u.push(e);this.init(),this.reconnecting=!0;const d=await this.connect(s,a,r,n,i,t);this.reconnected=!0,o||(await this.reopenDatabases(c,u,1e3),console.log("Reconnected!")),e(d)}catch(e){d(e)}},t)))}catch(e){t(e)}}async reopenDatabases(e,t,s){try{const s=[];for(const t of e){const e=this.state.databases[t];if(!e.init){const a="OpenDatabase",r={dbNameHash:t,reopenAtSeqNo:e.lastSeqNo};s.push(this.request(a,r))}}for(const e of t){const t=this.state.databasesByDbId[e];if(!t.init){const a=t.shareTokenHkdfKey,r=a?await this.authenticateShareToken(t.shareTokenId,a):{},n="OpenDatabaseByDatabaseId",i=Qa({databaseId:e,reopenAtSeqNo:t.lastSeqNo},r);s.push(this.request(n,i))}}await Promise.all(s)}catch(a){await new Promise(a=>setTimeout(async()=>{await this.reopenDatabases(e,t,s+1e3),a()},Math.min(s,3e4)))}}heartbeat(){clearTimeout(this.pingTimeout);this.pingTimeout=setTimeout(()=>{this.ws&&this.ws.close(b)},33e3)}close(e){this.ws?this.ws.close(e):this.init()}async signOut(){const e=this.session.username,t=this.connectionResolved,s=this.rejectConnection;try{_s.signOutSession(this.rememberMe,e);const a=this.session.sessionId;if(this.reconnecting)throw new hs.Reconnecting;const r="SignOut",n={sessionId:a};await this.request(r,n),this.close(),!t&&s&&s(new tr("Canceled",e))}catch(a){throw!t&&s&&s(new tr("Canceled",e)),a}}async setKeys(e){if(this.keys.init)return;if(!e)throw new tr("Missing seed",this.session.username);if(!this.keys.salts)throw new tr("Missing salts",this.session.username);this.seedString||(this.seedString=e);const t=i.a.decode(e),s=await ja.hkdf.importHkdfKey(t),a=this.keys.salts;if(this.keys.encryptionKey=await ja.aesGcm.importKeyFromMaster(s,i.a.decode(a.encryptionKeySalt)),this.keys.hmacKey=await ja.hmac.importKeyFromMaster(s,i.a.decode(a.hmacKeySalt)),a.ecdsaKeyEncryptionKeySalt){const e=await ja.ecdsa.importEcdsaKeyEncryptionKeyFromMaster(s,i.a.decode(a.ecdsaKeyEncryptionKeySalt)),t=i.a.decode(this.ecKeyData.encryptedEcdsaPrivateKey),r=await ja.aesGcm.decrypt(e,t);this.keys.ecdsaPrivateKey=await ja.ecdsa.getPrivateKeyFromRawPrivateKey(r);const n=await ja.ecdh.importEcdhKeyEncryptionKeyFromMaster(s,i.a.decode(a.ecdhKeyEncryptionKeySalt)),o=i.a.decode(this.ecKeyData.encryptedEcdhPrivateKey),c=await ja.aesGcm.decrypt(n,o);this.keys.ecdhPrivateKey=await ja.ecdh.getPrivateKeyFromRawPrivateKey(c)}else a.dhKeySalt&&(this.keys.dhPrivateKey=await ja.diffieHellman.importKeyFromMaster(s,i.a.decode(a.dhKeySalt)));if(a.dhKeySalt||a.ecdsaKeyWrapperSalt){const e=await ja.ecdsa.generateEcdsaKeyData(s),t=await ja.ecdh.generateEcdhKeyData(s,e.ecdsaPrivateKey);this.keys.ecdsaPrivateKey=e.ecdsaPrivateKey,this.keys.ecdhPrivateKey=t.ecdhPrivateKey,delete e.ecdsaPrivateKey,delete t.ecdhPrivateKey,this.newEcKeyData={ecdsaKeyData:e,ecdhKeyData:t}}}async validateKey(){let e;if(this.keys.ecdsaPrivateKey&&!this.keys.dhPrivateKey)e=await ja.ecdsa.sign(this.keys.ecdsaPrivateKey,i.a.decode(this.validationMessage));else if(this.keys.dhPrivateKey){const t=await ja.diffieHellman.getSharedKeyWithServer(this.keys.dhPrivateKey);e=await ja.aesGcm.decrypt(t,this.encryptedValidationMessage),delete this.keys.dhPrivateKey}const t={validationMessage:i.a.encode(e),ecKeyData:this.newEcKeyData};return(await this.request("ValidateKey",t)).data}async request(e,t){const s=Ds()();this.requests[s]={};const a=this.watch(s);this.ws.send(JSON.stringify({requestId:s,action:e,params:t}));try{return await a}catch(t){throw t.status===m?new hs.TooManyRequests(t.data.retryDelay):new er(e,t)}}async watch(e){const t=await new Promise((t,s)=>{this.requests[e].promiseResolve=t,this.requests[e].promiseReject=s,setTimeout(()=>{s(new Error("timeout"))},3e4)});return delete this.requests[e],t}async rebuildBundle(e,t,s){const a=[];for(let s=0;s{const t=e.map(e=>e.byteLength),s=t.reduce((e,t)=>e+t),a=new Uint8Array(s);let r=0;for(let s=0;s=s)return;e.bundledAtSeqNo=s;const n=this.prepareBundle(e),i=e.attributionEnabled?[...e.usernamesByUserId.keys()].join(","):void 0,{bundleId:o,bundleEncryptionKey:c,encryptedBundleEncryptionKey:u}=await this.initBundleUpload(t,s,a);if(!o)return;const[d,h]=await Promise.all([Ya(n.encrypted),Ya(n.plaintextMetadata)]),l=Ls(d),f=await ja.aesGcm.encrypt(c,l);n.encrypted=Fs(f),n.plaintextMetadata=h;const m=Ls(JSON.stringify(n)),p=await this.uploadBundle(r,t,s,o,m);if(!p)return;const w={dbId:t,seqNo:s,bundleId:o,writers:i,numChunks:p,encryptedBundleEncryptionKey:u};try{await this.request("CompleteBundleUpload",w)}catch(e){return}}buildUserResult({username:e,userId:t,authToken:s,email:a,profile:r,protectedProfile:n,usedTempPassword:i,changePassword:o,passwordChanged:c,userData:u}){const d={username:e,userId:t,authToken:s};if(a&&(d.email=a),r&&(d.profile=r),n&&(d.protectedProfile=n),i&&(d.usedTempPassword=i),o&&(d.changePassword=o),c&&(d.passwordChanged=c),u){const{creationDate:e,stripeData:t}=u;if(e&&(d.creationDate=e),t){const{paymentsMode:e,subscriptionStatus:s,cancelSubscriptionAt:a,subscriptionPlanId:r,trialExpirationDate:n}=t;e&&(d.paymentsMode=e),s&&(d.subscriptionStatus=s),a&&(d.cancelSubscriptionAt=a),r&&(d.subscriptionPlanId=r),n&&(d.trialExpirationDate=n)}}return d}handleUpdateUser(e){if(this.session&&this.session.userId===e.userId){this.session.username=e.username,this.userData=e.userData;const t=gs();t&&t({user:this.buildUserResult(Qa({authToken:this.session.authToken},e))})}}async rotateKeys(e,t){const{keySalts:s,ecKeyData:a}=t,{ecdsaKeyData:r,ecdhKeyData:n}=a;s.ecdsaKeyEncryptionKeySalt=r.ecdsaKeyEncryptionKeySalt,s.ecdhKeyEncryptionKeySalt=n.ecdhKeyEncryptionKeySalt,this.keys.salts=s,this.ecKeyData=Qa(Qa({},r),n),await this.setKeys(e),this.keys.init=!0}async authenticateShareToken(e,t){const s={shareTokenId:e};let a;try{a=await this.request("AuthenticateShareToken",s)}catch(e){if(e.response&&"ShareTokenNotFound"===e.response.data)throw new hs.ShareTokenNotFound;throw e}const{databaseId:r,shareTokenAuthKeyData:n,validationMessage:o}=a.data;let c;try{const e=i.a.decode(n.shareTokenEcdsaKeyEncryptionKeySalt),s=await ja.ecdsa.importEcdsaKeyEncryptionKeyFromMaster(t,e),a=i.a.decode(n.shareTokenEncryptedEcdsaPrivateKey),r=await ja.aesGcm.decrypt(s,a);c=await ja.ecdsa.getPrivateKeyFromRawPrivateKey(r)}catch(e){throw new hs.ShareTokenInvalid}const u=await ja.ecdsa.sign(c,i.a.decode(o));return{databaseId:r,validationMessage:o,signedValidationMessage:i.a.encode(u)}}};function ar(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,a)}return s}function rr(e){for(var t=1;t{if(e.response){if("Domain not whitelisted"===e.response.data)throw new hs.DomainNotWhitelisted(window.location.origin);if("App ID not valid"===e.response.data)throw new hs.AppIdNotValid;if("UserNotFound"===e.response.data)throw new hs.UserNotFound;if(e.response.status===p)throw new hs.InternalServerError;if(e.response.status===g)throw new hs.Timeout}else if(e.message&&-1!==e.message.indexOf("timeout"))throw new hs.Timeout},ur=async(e,t,s,a)=>{try{await sr.connect(e,t,s,a)}catch(e){if(cr(e),"Web Socket already connected"===e.message)throw new hs.UserAlreadySignedIn(e.username);throw e}},dr=e=>{if(e.response&&"UsernameTooLong"===e.response.data.error)throw new hs.UsernameTooLong(e.response.data.maxLen);if(e.response&&"PasswordAttemptLimitExceeded"===e.response.data.error)throw new hs.PasswordAttemptLimitExceeded(e.response.data.delay)},hr=e=>{if(e.response&&e.response.data){const t=e.response.data;switch(t.error){case"SessionLengthTooShort":throw new hs.SessionLengthTooShort(t.minLen);case"SessionLengthTooLong":throw new hs.SessionLengthTooLong(t.maxLen)}}},lr=(e,t)=>{if(cr(e),dr(e),e.response){const s=e.response.data;switch(s){case"UsernameAlreadyExists":throw new hs.UsernameAlreadyExists(t);case"TrialExceededLimit":throw new hs.TrialExceededLimit;case"CurrentPasswordIncorrect":throw new hs.CurrentPasswordIncorrect}switch(s.error){case"EmailNotValid":throw new hs.EmailNotValid;case"ProfileMustBeObject":throw new hs.ProfileMustBeObject;case"ProfileKeyTooLong":throw new hs.ProfileKeyTooLong(s.maxLen,s.key);case"ProfileValueMustBeString":throw new hs.ProfileValueMustBeString(s.key,s.value);case"ProfileValueCannotBeBlank":throw new hs.ProfileValueCannotBeBlank(s.key);case"ProfileValueTooLong":throw new hs.ProfileValueTooLong(s.maxLen,s.key,s.value);case"ProfileHasTooManyKeys":throw new hs.ProfileHasTooManyKeys(s.maxKeys);case"ProfileCannotBeEmpty":throw new hs.ProfileCannotBeEmpty}}throw e},fr=e=>e&&60*e*60*1e3,mr=e=>{if("string"!=typeof e)throw new hs.UsernameMustBeString;if(0===e.length)throw new hs.UsernameCannotBeBlank},pr=e=>{if("string"!=typeof e)throw new hs.PasswordMustBeString;if(0===e.length)throw new hs.PasswordCannotBeBlank;if(e.length<6)throw new hs.PasswordTooShort(6);if(e.length>1e3)throw new hs.PasswordTooLong(1e3)},wr=e=>{if("object"!=typeof e)throw new hs.ParamsMustBeObject;if(!Ga(e,"username"))throw new hs.UsernameMissing;if(!Ga(e,"password"))throw new hs.PasswordMissing;if(mr(e.username),pr(e.password),Ga(e,"rememberMe")&&!nr[e.rememberMe])throw new hs.RememberMeValueNotValid(nr);if(Ga(e,"sessionLength")&&"number"!=typeof e.sessionLength)throw new hs.SessionLengthMustBeNumber},gr=async(e,t,s)=>{const a=ja.scrypt.generateSalt(),r=await ja.scrypt.hash(e,a,s),n=await ja.hkdf.importHkdfKeyFromString(r),o=ja.hkdf.generateSalt(),c=await ja.hkdf.getPasswordToken(n,o),u=ja.hkdf.generateSalt(),d=await ja.aesGcm.getPasswordBasedEncryptionKey(n,u),h=await ja.aesGcm.encrypt(d,t);return{passwordToken:c,passwordSalts:{passwordSalt:i.a.encode(a),passwordTokenSalt:i.a.encode(o)},passwordBasedBackup:{passwordBasedEncryptionKeySalt:i.a.encode(u),passwordEncryptedSeed:i.a.encode(h)}}},yr=async e=>{const t=await ja.hkdf.importHkdfKey(e),s=ja.hkdf.generateSalt(),a=ja.hkdf.generateSalt(),r={encryptionKeySalt:i.a.encode(s),hmacKeySalt:i.a.encode(a)},n=await ja.ecdsa.generateEcdsaKeyData(t),o=await ja.ecdh.generateEcdhKeyData(t,n.ecdsaPrivateKey);delete n.ecdsaPrivateKey,delete o.ecdhPrivateKey;return{ecKeyData:{ecdsaKeyData:n,ecdhKeyData:o},keySalts:r}},br=e=>{if("object"!=typeof e)throw new hs.ProfileMustBeObject;let t=!1;for(const s in e){t=!0;const a=e[s];if("string"!=typeof a)throw new hs.ProfileValueMustBeString(s,a);if(!a)throw new hs.ProfileValueCannotBeBlank(s)}if(!t)throw new hs.ProfileCannotBeEmpty},vr=async()=>{try{const e="GetPasswordSalts";return(await sr.request(e)).data}catch(e){throw cr(e),e}},Mr=async(e,t,s)=>{const{passwordSalt:a,passwordTokenSalt:r}=t,n=await ja.scrypt.hash(e,new Uint8Array(i.a.decode(a)),s),o=await ja.hkdf.importHkdfKeyFromString(n);return{passwordHkdfKey:o,passwordToken:await ja.hkdf.getPasswordToken(o,i.a.decode(r))}},Sr=async(e,t)=>{let s;try{const a=_s.getCurrentSession();if(!a)return{};const{signedIn:r,sessionId:n,creationDate:i,expirationDate:o,rememberMe:c}=a;s=a.username;const u=_s.getSeedString(e,s);if(!r||!u||new Date>new Date(o))return{lastUsedUsername:s};let d;try{d=await Us(n,t)}catch(e){if(cr(e),hr(e),e.response&&"Session invalid"===e.response.data)return{lastUsedUsername:s};throw e}const{userId:h,authToken:l,username:f,email:m,profile:p,protectedProfile:w}=d;if(f!==s&&(_s.saveSeedString(c,e,f,u),_s.removeSeedString(e,s)),_s.signInSession(c,f,n,i,d.expirationDate),sr.connectionResolved){if(sr.session.sessionId===n)return{user:sr.buildUserResult({username:f,userId:h,authToken:sr.session.authToken,email:m,profile:p,protectedProfile:w,userData:sr.userData})};throw new hs.UserAlreadySignedIn(sr.session.username)}const g=rr(rr({},a),{},{username:f,userId:h,authToken:l});return await ur(g,u,c),{user:sr.buildUserResult({username:f,userId:h,authToken:l,email:m,profile:p,protectedProfile:w,userData:sr.userData})}}catch(e){if("Invalid seed"===e.message)return{lastUsedUsername:s};throw cr(e),e}},Ir=async(e,t)=>{const s=_s.getSeedString(e,t);if(!s)throw new hs.KeyNotFound(or);const a=i.a.decode(s);return await ja.hkdf.importHkdfKey(a)};var Pr={signUp:async e=>{try{(e=>{if(wr(e),e.profile&&br(e.profile),e.email&&"string"!=typeof e.email)throw new hs.EmailNotValid})(e);const{password:t,profile:s,passwordHashAlgo:a,rememberMe:r="session"}=e,n=e.username.toLowerCase(),o=e.email&&e.email.toLowerCase(),c=ws(),u=await ja.generateSeed(),d=fr(e.sessionLength),{sessionId:h,creationDate:l,expirationDate:f,userId:m,authToken:p}=await(async(e,t,s,a,r,n,i)=>{const{passwordToken:o,passwordSalts:c,passwordBasedBackup:u}=await gr(t,s,a),{ecKeyData:d,keySalts:h}=await yr(s);try{return await Es(e,o,d,c,h,r,n,u,i)}catch(t){hr(t),lr(t,e)}})(n,t,u,a,o,s,d),w={username:n,userId:m,sessionId:h,creationDate:l,expirationDate:f,authToken:p},g=i.a.encode(u);return _s.saveSeedString(r,c,n,g),_s.signInSession(r,n,h,l,f),await ur(w,g,r),sr.buildUserResult({username:n,userId:m,authToken:p,email:o,profile:s,userData:sr.userData})}catch(e){switch(e.name){case"ParamsMustBeObject":case"UsernameMissing":case"UsernameAlreadyExists":case"UsernameCannotBeBlank":case"UsernameMustBeString":case"UsernameTooLong":case"PasswordMissing":case"PasswordCannotBeBlank":case"PasswordTooShort":case"PasswordTooLong":case"PasswordMustBeString":case"EmailNotValid":case"ProfileMustBeObject":case"ProfileCannotBeEmpty":case"ProfileHasTooManyKeys":case"ProfileKeyTooLong":case"ProfileValueMustBeString":case"ProfileValueCannotBeBlank":case"ProfileValueTooLong":case"RememberMeValueNotValid":case"SessionLengthMustBeNumber":case"SessionLengthTooShort":case"SessionLengthTooLong":case"TrialExceededLimit":case"AppIdNotSet":case"AppIdNotValid":case"DomainNotWhitelisted":case"UserAlreadySignedIn":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},signOut:async()=>{try{if(!sr.session.username)throw new hs.UserNotSignedIn;try{await sr.signOut()}catch(e){throw cr(e),e}}catch(e){switch(e.name){case"UserNotSignedIn":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},signIn:async e=>{try{wr(e);const t=e.username.toLowerCase(),{password:s,passwordHashAlgo:a,rememberMe:r="session"}=e,n=ws(),o=await(async e=>{try{return await Bs(e)}catch(e){if(cr(e),dr(e),e.response&&"User not found"===e.response.data)throw new hs.UsernameOrPasswordMismatch;throw e}})(t),{passwordHkdfKey:c,passwordToken:u}=await Mr(s,o,a),d=fr(e.sessionLength),h=await(async(e,t,s)=>{try{return await Ns(e,t,s)}catch(e){if(cr(e),dr(e),hr(e),e.response&&"Invalid password"===e.response.data)throw new hs.UsernameOrPasswordMismatch;if(e.response&&"User pending deletion"===e.response.data)throw new hs.UserPendingDeletion;throw e}})(t,u,d),{userId:l,email:f,profile:m,passwordBasedBackup:p,protectedProfile:w,usedTempPassword:g,changePassword:y}=h,b=rr(rr({},h.session),{},{username:t,userId:l});let v;if(!y){const e=_s.getSeedString(n,t);let s;if(!e&&g)throw new hs.KeyNotFound(ir);g||(s=await(async(e,t)=>{const{passwordBasedEncryptionKeySalt:s,passwordEncryptedSeed:a}=t,r=await ja.aesGcm.getPasswordBasedEncryptionKey(e,i.a.decode(s)),n=await ja.aesGcm.decrypt(r,i.a.decode(a));return i.a.encode(n)})(c,p),_s.saveSeedString(r,n,t,s)),v=s||e}_s.signInSession(r,t,b.sessionId,b.creationDate,b.expirationDate);try{await ur(b,v,r,y)}catch(e){if(g&&"Invalid seed"===e.message)throw new hs.KeyNotFound(ir);throw e}return sr.buildUserResult({username:t,userId:l,authToken:b.authToken,email:f,profile:m,protectedProfile:w,usedTempPassword:g,changePassword:y,userData:sr.userData})}catch(e){switch(e.name){case"ParamsMustBeObject":case"UsernameMissing":case"UsernameOrPasswordMismatch":case"UserPendingDeletion":case"UsernameCannotBeBlank":case"UsernameTooLong":case"UsernameMustBeString":case"PasswordMissing":case"PasswordCannotBeBlank":case"PasswordTooShort":case"PasswordTooLong":case"PasswordMustBeString":case"PasswordAttemptLimitExceeded":case"RememberMeValueNotValid":case"SessionLengthMustBeNumber":case"SessionLengthTooShort":case"SessionLengthTooLong":case"KeyNotFound":case"AppIdNotSet":case"AppIdNotValid":case"DomainNotWhitelisted":case"UserAlreadySignedIn":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},init:async e=>{try{if(!window.crypto.subtle)throw new hs.WebCryptoUnavailable;if("object"!=typeof e)throw new hs.ParamsMustBeObject;if(!Ga(e,"appId"))throw new hs.AppIdMissing;if("string"!=typeof e.appId)throw new hs.AppIdMustBeString;if(0===e.appId.length)throw new hs.AppIdCannotBeBlank;if(Ga(e,"updateUserHandler")&&"function"!=typeof e.updateUserHandler)throw new hs.UpdateUserHandlerMustBeFunction;if(Ga(e,"sessionLength")&&"number"!=typeof e.sessionLength)throw new hs.SessionLengthMustBeNumber;if(Ga(e,"allowServerSideEncryption")&&"boolean"!=typeof e.allowServerSideEncryption)throw new hs.AllowServerSideEncryptionMustBeBoolean;bs(e);return await Sr(e.appId,fr(e.sessionLength))}catch(e){switch(e.name){case"WebCryptoUnavailable":case"ParamsMustBeObject":case"AppIdMissing":case"AppIdAlreadySet":case"AppIdMustBeString":case"AppIdCannotBeBlank":case"AppIdNotValid":case"DomainNotWhitelisted":case"UpdateUserHandlerMustBeFunction":case"SessionLengthMustBeNumber":case"SessionLengthTooShort":case"SessionLengthTooLong":case"AllowServerSideEncryptionMustBeBoolean":case"UserAlreadySignedIn":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},updateUser:async e=>{try{if("object"!=typeof e)throw new hs.ParamsMustBeObject;if((e=>{if(!(Ga(e,"username")||Ga(e,"newPassword")||Ga(e,"email")||Ga(e,"profile")))throw new hs.ParamsMissing;const{username:t,currentPassword:s,newPassword:a,email:r,profile:n}=e;if(Ga(e,"username")&&mr(t),Ga(e,"newPassword")){if(!Ga(e,"currentPassword"))throw new hs.CurrentPasswordMissing;pr(s),pr(a)}if(r&&"string"!=typeof r)throw new hs.EmailNotValid;n&&br(n)})(e),sr.reconnecting)throw new hs.Reconnecting;if(!sr.connectionResolved)throw new hs.UserNotSignedIn;const t=sr.session.userId,s=e.newPassword&&!sr.keys.init&&sr.changePassword&&await ja.generateSeed(),a="UpdateUser",r=await(async(e,t)=>{if(e.username&&(e.username=e.username.toLowerCase()),e.newPassword){const[s,a,r]=await Promise.all([vr(),gr(e.newPassword,t||i.a.decode(sr.seedString)),t&&yr(t)]),{passwordToken:n}=await Mr(e.currentPassword,s,e.passwordHashAlgo);e.currentPasswordToken=n,delete e.currentPassword,e.passwordToken=a.passwordToken,e.passwordSalts=a.passwordSalts,e.passwordBasedBackup=a.passwordBasedBackup,delete e.newPassword,r&&(e.newKeyData=r)}return e.email?e.email=e.email.toLowerCase():Ga(e,"email")&&(e.email=!1),!e.profile&&Ga(e,"profile")&&(e.profile=!1),e})(rr({},e),s);if(sr.reconnecting)throw new hs.Reconnecting;if(!sr.connectionResolved)throw new hs.UserNotSignedIn;if(!sr.session||t!==sr.session.userId)throw new hs.ServiceUnavailable;try{r.username&&_s.saveSeedString(sr.rememberMe,ws(),r.username,sr.seedString);const e=(await sr.request(a,r)).data.updatedUser;if(sr.handleUpdateUser(e),s&&sr.session&&t===sr.session.userId){const t=i.a.encode(s);await sr.rotateKeys(t,r.newKeyData),_s.saveSeedString(sr.rememberMe,ws(),e.username,t);const{sessionId:a,creationDate:n,expirationDate:o}=sr.session;_s.signInSession(sr.rememberMe,e.username,a,n,o)}}catch(e){lr(e,r.username)}}catch(e){switch(e.name){case"ParamsMustBeObject":case"ParamsMissing":case"UsernameAlreadyExists":case"UsernameMustBeString":case"UsernameCannotBeBlank":case"UsernameTooLong":case"CurrentPasswordMissing":case"CurrentPasswordIncorrect":case"PasswordAttemptLimitExceeded":case"PasswordMustBeString":case"PasswordCannotBeBlank":case"PasswordTooShort":case"PasswordTooLong":case"EmailNotValid":case"ProfileMustBeObject":case"ProfileCannotBeEmpty":case"ProfileHasTooManyKeys":case"ProfileKeyTooLong":case"ProfileValueMustBeString":case"ProfileValueCannotBeBlank":case"ProfileValueTooLong":case"AppIdNotSet":case"AppIdNotValid":case"UserNotFound":case"UserNotSignedIn":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},deleteUser:async()=>{try{(()=>{if(sr.reconnecting)throw new hs.Reconnecting;if(!sr.keys.init&&sr.changePassword)throw new hs.UserMustChangePassword;if(!sr.keys.init)throw new hs.UserNotSignedIn})();const e=sr.session.username;_s.removeSeedString(ws(),e),_s.removeCurrentSession();try{const e="DeleteUser";await sr.request(e)}catch(e){throw cr(e),e}sr.close()}catch(e){switch(e.name){case"UserMustChangePassword":case"UserNotSignedIn":case"UserNotFound":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},forgotPassword:async e=>{try{if("object"!=typeof e)throw new hs.ParamsMustBeObject;if(Ga(e,"deleteEndToEndEncryptedData")&&"boolean"!=typeof e.deleteEndToEndEncryptedData)throw new hs.DeleteEndToEndEncryptedDataMustBeBoolean;if(!Ga(e,"username"))throw new hs.UsernameMissing;mr(e.username);const t=e.username.toLowerCase(),s=ws(),a="".concat(Va(ys()),"/api/auth/forgot-password?appId=").concat(s,"&username=").concat(encodeURIComponent(t),"&userbaseJsVersion=").concat(ps),r=new WebSocket(a+(Ga(e,"deleteEndToEndEncryptedData")?"&deleteEndToEndEncryptedData=".concat(e.deleteEndToEndEncryptedData):""));await new Promise((e,a)=>{setTimeout(()=>a(new hs.Timeout),15e3),r.onerror=()=>a(new hs.ServiceUnavailable),r.onmessage=async n=>{try{const o=JSON.parse(n.data);switch(o.route){case"ReceiveEncryptedToken":{const e=await Ir(s,t),a=new Uint8Array(o.encryptedForgotPasswordToken.data),n=await ja.diffieHellman.importKeyFromMaster(e,i.a.decode(o.dhKeySalt)),c=await ja.diffieHellman.getSharedKeyWithServer(n);let u;try{u=i.a.encode(await ja.aesGcm.decrypt(c,a))}catch(e){throw new hs.KeyNotFound(or)}r.send(JSON.stringify({action:"ForgotPassword",params:{forgotPasswordToken:u}}));break}case"ReceiveToken":{const e=await Ir(s,t),{ecdsaKeyEncryptionKeySalt:a,encryptedEcdsaPrivateKey:n,forgotPasswordToken:c}=o,u=await ja.ecdsa.importEcdsaKeyEncryptionKeyFromMaster(e,i.a.decode(a));let d;try{const e=await ja.aesGcm.decrypt(u,i.a.decode(n));d=await ja.ecdsa.getPrivateKeyFromRawPrivateKey(e)}catch(e){throw new hs.KeyNotFound(or)}const h=i.a.encode(await ja.ecdsa.sign(d,i.a.decode(c)));r.send(JSON.stringify({action:"ForgotPassword",params:{signedForgotPasswordToken:h}}));break}case"SuccessfullyForgotPassword":e();break;case"Error":{const e=o.data;switch(e.name){case"UsernameTooLong":throw new hs.UsernameTooLong(e.maxLen);case"AppIdNotValid":throw new hs.AppIdNotValid;case"UserNotFound":throw new hs.UserNotFound;case"UserEmailNotFound":throw new hs.UserEmailNotFound;default:throw o.status===p?new hs.ServiceUnavailable:new hs.UnknownServiceUnavailable(e)}}case"Ping":break;default:a(new Error("Received unknown message from userbase-server: ".concat(n.data)))}}catch(n){a(n)}}}),r.close()}catch(e){switch(e.name){case"ParamsMustBeObject":case"UsernameMissing":case"UsernameMustBeString":case"UsernameCannotBeBlank":case"UsernameTooLong":case"AppIdNotSet":case"AppIdNotValid":case"KeyNotFound":case"UserNotFound":case"UserEmailNotFound":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}}},Er=s(12),Br=s.n(Er);function Nr(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,a)}return s}function Ur(e){for(var t=1;t{if(sr.reconnecting)throw new hs.Reconnecting;if(!sr.keys.init&&sr.changePassword)throw new hs.UserMustChangePassword;if(!sr.keys.init||!Ar[sr.encryptionMode])throw new hs.UserNotSignedIn},kr=e=>{if(e.response){if("UserNotFound"===e.response.data)throw new hs.UserNotFound;if(e.response.status===p)throw new hs.InternalServerError;if(e.response.status===g)throw new hs.Timeout}else if(e.message&&-1!==e.message.indexOf("timeout"))throw new hs.Timeout};class Dr{constructor(e){this.startSeqNo=e,this.txSeqNo=null,this.transactions={},this.promiseResolve=null,this.promiseReject=null,this.index=null}getStartSeqNo(){return this.startSeqNo}getIndex(){return this.index}setIndex(e){this.index=e}async getResult(e){this.txSeqNo=e;const t=new Promise((e,t)=>{this.promiseResolve=e,this.promiseReject=t,setTimeout(()=>{t(new Error("timeout"))},3e4)});return this.verifyPromise(),t}verifyPromise(){(this.txSeqNo||0==this.txSeqNo)&&this.promiseResolve&&this.promiseReject&&this.transactions[this.txSeqNo]&&("Success"==this.transactions[this.txSeqNo]?this.promiseResolve():this.promiseReject(this.transactions[this.txSeqNo]))}addTransaction(e,t){this.transactions[e.seqNo]||(this.transactions[e.seqNo]=t,this.verifyPromise())}}class Kr{constructor(e,t,s,a){this.onChange=xr(e),this.items={},this.itemsPlaintextMetadata={},this.fileIds={};this.itemsIndex=new Br.a([],(e,t)=>e.seqNot.seqNo||e.seqNo===t.seqNo&&e.operationIndex>t.operationIndex?1:0),this.unverifiedTransactions=[],this.lastSeqNo=0,this.init=!1,this.dbKey=null,this.receivedMessage=t,this.usernamesByUserId=new Map,this.attributionEnabled=!1,this.shareTokenId=s,this.shareTokenHkdfKey=a,this.applyTransactionsQueue=new Ja,this.bundleChunks={}}async applyTransactions(e,t,s,a){for(let s=0;st=>{try{e(t)}catch(e){console.error("There was an error in your changeHandler.\n\n",e)}},Rr=(e,t,s)=>{e.onChange=xr(t);const a=e.receivedMessage;return e.receivedMessage=()=>{a(),s()},!!e.init&&(e.onChange(e.getItems()),e.receivedMessage(),!0)},Or=e=>{const t=e.slice(0,36),s=Fs(t,!0);if(!s||36!==s.length)throw new hs.ShareTokenInvalid;return s},Cr=async(e,t,s)=>{let a,r;try{a=(e=>{const t=i.a.decode(e);return{shareTokenId:Or(t),shareTokenSeed:t.slice(36)}})(e),r=await ja.hkdf.importHkdfKey(a.shareTokenSeed)}catch(e){throw new hs.ShareTokenInvalid}const{shareTokenId:n}=a,{databaseId:o,validationMessage:c,signedValidationMessage:u}=await sr.authenticateShareToken(n,r);sr.state.shareTokenIdToDbId[n]=o,await _r(o,t,s,n,r,c,u)},_r=async(e,t,s,a,r,n,i)=>{const o=sr.state.databasesByDbId[e];if(o){if(Rr(o,t,s))return}else sr.state.databasesByDbId[e]=new Kr(t,s,a,r);const c={databaseId:e,validationMessage:n,signedValidationMessage:i};await sr.request("OpenDatabaseByDatabaseId",c)},Fr=async(e,t)=>{try{let s,a;const r=new Promise((e,t)=>{s=e,a=setTimeout(()=>t(new Error("timeout")),3e4)}),{dbNameHash:n,newDatabaseParams:i,databaseId:o,shareToken:c}=t;try{n?await(async(e,t,s,a)=>{const r=sr.state.databases[e];if(r){if(Rr(r,s,a))return}else sr.state.databases[e]=new Kr(s,a);const n={dbNameHash:e,newDatabaseParams:t};await sr.request("OpenDatabase",n)})(n,i,e,s):o?await _r(o,e,s):c&&await Cr(c,e,s),await r}catch(e){if(clearTimeout(a),e.response&&e.response.data){const t=e.response.data;if("Database already creating"===t)throw new hs.DatabaseAlreadyOpening;if("Database is owned by user"===t){if(o)throw new hs.DatabaseIdNotAllowedForOwnDatabase;if(c)throw new hs.ShareTokenNotAllowedForOwnDatabase}else if("Database key not found"===t||"Database not found"===t)throw new hs.DatabaseNotFound;switch(t.name){case"SubscriptionNotFound":throw new hs.SubscriptionNotFound;case"SubscriptionInactive":throw new hs.SubscriptionInactive(t.subscriptionStatus);case"TrialExpired":throw new hs.TrialExpired}}throw e}}catch(e){throw kr(e),e}},Lr=e=>{if("server-side"===e&&!Ms())throw new hs.ServerSideEncryptionNotEnabledInClient},jr=e=>{if("object"!=typeof e)throw new hs.ParamsMustBeObject;if(Ga(e,"databaseName")){if((e=>{if("string"!=typeof e)throw new hs.DatabaseNameMustBeString;if(0===e.length)throw new hs.DatabaseNameCannotBeBlank;if(e.length>100)throw new hs.DatabaseNameTooLong(100)})(e.databaseName),Ga(e,"databaseId"))throw new hs.DatabaseIdNotAllowed;if(Ga(e,"shareToken"))throw new hs.ShareTokenNotAllowed;if(!e.allowVerifiedUsersDatabase&&"__userbase_verified_users"===e.databaseName)throw new hs.DatabaseNameRestricted("__userbase_verified_users")}else if(Ga(e,"databaseId")){if((e=>{if("string"!=typeof e)throw new hs.DatabaseIdMustBeString;if(0===e.length)throw new hs.DatabaseIdCannotBeBlank;if(36!==e.length)throw new hs.DatabaseIdInvalidLength(36)})(e.databaseId),Ga(e,"shareToken"))throw new hs.ShareTokenNotAllowed}else{if(!Ga(e,"shareToken"))throw new hs.DatabaseNameMissing;if("string"!=typeof e.shareToken)throw new hs.ShareTokenInvalid}if(Ga(e,"encryptionMode")&&!Ar[e.encryptionMode])throw new hs.EncryptionModeNotValid(Ar);Tr()},qr=async e=>{try{if(jr(e),!Ga(e,"changeHandler"))throw new hs.ChangeHandlerMissing;const{databaseName:t,databaseId:s,shareToken:a,changeHandler:r,encryptionMode:n=sr.encryptionMode}=e;if("function"!=typeof r)throw new hs.ChangeHandlerMustBeFunction;if(Lr(n),t){const e="server-side"===n?t:sr.state.dbNameToHash[t]||await ja.hmac.signString(sr.keys.hmacKey,t);"end-to-end"===n&&(sr.state.dbNameToHash[t]=e);const s={dbNameHash:e,newDatabaseParams:await(async(e,t)=>{const s=Ds()(),a=await ja.aesGcm.generateKey(),r=await ja.aesGcm.getKeyStringFromKey(a),[n,i]=await Promise.all([ja.aesGcm.encryptString(sr.keys.encryptionKey,r),ja.aesGcm.encryptString(a,e)]),o={dbId:s,encryptedDbKey:n,encryptedDbName:i,attribution:!0};return"server-side"===t&&(o.plaintextDbKey=r),o.fingerprint=await ln(),o})(t,n)};await Fr(r,s)}else if(s){const e={databaseId:s};await Fr(r,e)}else{const e={shareToken:a};await Fr(r,e)}}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseAlreadyOpening":case"DatabaseNameMustBeString":case"DatabaseNameMissing":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"DatabaseIdNotAllowedForOwnDatabase":case"ShareTokenNotAllowed":case"ShareTokenInvalid":case"ShareTokenNotFound":case"ShareTokenNotAllowedForOwnDatabase":case"DatabaseNotFound":case"ChangeHandlerMissing":case"ChangeHandlerMustBeFunction":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"UserMustChangePassword":case"UserNotSignedIn":case"UserNotFound":case"SubscriptionNotFound":case"SubscriptionInactive":case"TrialExpired":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},Vr=(e,t,s,a="end-to-end")=>{Lr(a);const r=s&&Or(i.a.decode(s)),n="server-side"===a?e:sr.state.dbNameToHash[e],o=e?sr.state.databases[n]:sr.state.databasesByDbId[t||sr.state.shareTokenIdToDbId[r]];if(!o||!o.init)throw new hs.DatabaseNotOpen;return o},Hr=async e=>{try{jr(e);const t=Vr(e.databaseName,e.databaseId,e.shareToken,e.encryptionMode||sr.encryptionMode),s="Insert",a=await Gr(t,e);await zr(t,s,a)}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseNotOpen":case"DatabaseNameMissing":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"ShareTokenInvalid":case"DatabaseIsReadOnly":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"ItemIdMustBeString":case"ItemIdCannotBeBlank":case"ItemIdTooLong":case"ItemMissing":case"ItemInvalid":case"ItemTooLarge":case"ItemAlreadyExists":case"UserMustChangePassword":case"UserNotSignedIn":case"UserNotFound":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},Gr=async(e,t)=>{if(!Ga(t,"item"))throw new hs.ItemMissing;const{item:s,itemId:a,writeAccess:r}=t;if(Ga(t,"itemId")){if("string"!=typeof a)throw new hs.ItemIdMustBeString;if(0===a.length)throw new hs.ItemIdCannotBeBlank;if(a.length>100)throw new hs.ItemIdTooLong(100)}const n=JSON.stringify(s);if(!n)throw new hs.ItemInvalid;if(Ha(n)>10240)throw new hs.ItemTooLarge(10);const i=a||Ds()(),o={id:i,item:s};return{itemKey:await ja.hmac.signString(sr.keys.hmacKey,i),encryptedItem:await ja.aesGcm.encryptJson(e.dbKey,o),writeAccess:r}},Jr=async e=>{try{jr(e);const t=Vr(e.databaseName,e.databaseId,e.shareToken,e.encryptionMode||sr.encryptionMode),s="Update",a=await Wr(t,e);await zr(t,s,a)}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseNotOpen":case"DatabaseNameMissing":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"ShareTokenInvalid":case"DatabaseIsReadOnly":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"ItemIdMissing":case"ItemIdMustBeString":case"ItemIdCannotBeBlank":case"ItemIdTooLong":case"ItemMissing":case"ItemInvalid":case"ItemTooLarge":case"ItemDoesNotExist":case"ItemUpdateConflict":case"WriteAccessParamNotAllowed":case"TransactionUnauthorized":case"UserMustChangePassword":case"UserNotSignedIn":case"UserNotFound":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},Wr=async(e,t)=>{if(!Ga(t,"item"))throw new hs.ItemMissing;if(!Ga(t,"itemId"))throw new hs.ItemIdMissing;!t.writeAccess&&Ga(t,"writeAccess")&&(t.writeAccess=!1);const{item:s,itemId:a,writeAccess:r}=t;if("string"!=typeof a)throw new hs.ItemIdMustBeString;if(0===a.length)throw new hs.ItemIdCannotBeBlank;if(a.length>100)throw new hs.ItemIdTooLong(100);if(!e.itemExists(a))throw new hs.ItemDoesNotExist;const n=JSON.stringify(s);if(!n)throw new hs.ItemInvalid;if(Ha(n)>10240)throw new hs.ItemTooLarge(10);const i={id:a,item:s,__v:e.getItemVersionNumber(a)+1};return{itemKey:await ja.hmac.signString(sr.keys.hmacKey,a),encryptedItem:await ja.aesGcm.encryptJson(e.dbKey,i),writeAccess:r}},Yr=async(e,t)=>{if(!Ga(t,"itemId"))throw new hs.ItemIdMissing;const{itemId:s}=t;if("string"!=typeof s)throw new hs.ItemIdMustBeString;if(0===s.length)throw new hs.ItemIdCannotBeBlank;if(s.length>100)throw new hs.ItemIdTooLong(100);if(!e.itemExists(s))throw new hs.ItemDoesNotExist;const a={id:s,__v:e.getItemVersionNumber(s)+1};return{itemKey:await ja.hmac.signString(sr.keys.hmacKey,s),encryptedItem:await ja.aesGcm.encryptJson(e.dbKey,a)}},zr=async(e,t,s)=>{try{const a=e.registerUnverifiedTransaction(),r=Ur(Ur({},s),{},{dbId:e.dbId,dbNameHash:e.dbNameHash}),n=(await sr.request(t,r)).data.sequenceNo;return await a.getResult(n),e.unregisterUnverifiedTransaction(a),n}catch(e){if(kr(e),e.response){if("DatabaseIsReadOnly"===e.response.data.name)throw new hs.DatabaseIsReadOnly;if("UserNotFound"===e.response.data.message)throw new hs.UserNotFound(e.response.data.username)}throw e}},Zr=async(e,t,s,a,r,n,i,o)=>{const c=await(async e=>{const t=new FileReader;return new Promise((s,a)=>{t.onload=e=>{e.target.error?a(e.target.error):s(e.target.result)},t.readAsArrayBuffer(e)})})(t),[u,d]=await ja.aesGcm.generateAndEncryptKeyEncryptionKey(r),h=await ja.aesGcm.encrypt(u,c),l={dbId:s,chunkNumber:n,fileId:a,chunk:Fs(new Uint8Array(h)),chunkEncryptionKey:Fs(new Uint8Array(d))},f=(async(e,t,s,a)=>{await e,t.bytesTransferred+=a,s&&s(Ur({},t))})(sr.request("UploadFileChunk",l),i,o,t.size);e.push(f),10===e.length&&(await Promise.all(e),e.length=0)},Xr=async(e,t,s,a)=>{try{const r="GetChunk",n={dbId:e,fileId:t,chunkNumber:s},i=(await sr.request(r,n)).data,o=new Uint8Array(new Uint16Array(Ls(i.chunk))).buffer,c=new Uint8Array(new Uint16Array(Ls(i.chunkEncryptionKey))).buffer,u=await ja.aesGcm.decrypt(a,c),d=await ja.aesGcm.getKeyFromRawKey(u);return await ja.aesGcm.decrypt(d,o)}catch(e){throw kr(e),e}},Qr=async(e,t,s)=>{const{username:a,senderUsername:r,verificationValues:n}=s,{sentSignature:o,receivedSignature:c,senderEcdsaPublicKey:u}=n,d=t[a]&&t[a].record.fingerprint,h=i.a.decode(u),l=t[r]&&t[r].record.fingerprint||await hn(h),f=await ja.ecdsa.getPublicKeyFromRawPublicKey(h),m=await rn(e,d),p=await ja.ecdsa.verifyString(f,o,m),w=await ja.ecdsa.getPublicKeyFromRawPublicKey(i.a.decode(n.recipientEcdsaPublicKey)),g=await rn(e,l),y=await ja.ecdsa.verifyString(w,c,g);return p&&y},$r=async(e,t,s,a,r)=>{const{mySentSignature:n,myReceivedSignature:o}=r,c=await rn(e,t),u=await ja.ecdsa.verifyString(a,o,c);if(!u)return u;const d=await rn(e,s),h=await ja.ecdsa.getPublicKeyFromRawPublicKey(i.a.decode(r.mySenderEcdsaPublicKey));return await ja.ecdsa.verifyString(h,n,d)&&u},en=async(e,t,s,a,r)=>{const{sentSignature:n,receivedSignature:o}=r,c=await rn(e,t),u=await ja.ecdsa.verifyString(a,n,c);if(!u)return u;const d=await rn(e,s),h=await ja.ecdsa.getPublicKeyFromRawPublicKey(i.a.decode(r.recipientEcdsaPublicKey)),l=await ja.ecdsa.verifyString(h,o,d);return u&&l},tn=async(e,t,s,a,r)=>{const n=await ja.ecdsa.getPublicKeyFromPrivateKey(sr.keys.ecdsaPrivateKey),i=await ln();for(let o=0;o{const{databaseId:n,databaseNameHash:o,isOwner:c,readOnly:u,resharingAllowed:d,senderUsername:h}=e;let l,f;if(e.encryptedDbKey||e.plaintextDbKey){const s=e.plaintextDbKey||await ja.aesGcm.decryptString(t,e.encryptedDbKey);if(l=await ja.aesGcm.getKeyFromKeyString(s),f=await ja.aesGcm.decryptString(l,e.databaseName),c&&"__userbase_verified_users"===f)return null}else{if(e.wrappedDbKey)return null;{let a;try{const{ephemeralPublicKey:t,signedEphemeralPublicKey:r,sharedEncryptedDbKey:n}=e;a=i.a.decode(e.senderEcdsaPublicKey);const o=await ja.ecdsa.getPublicKeyFromRawPublicKey(a);if(!await ja.ecdsa.verify(o,i.a.decode(r),i.a.decode(t)))throw new hs.ServiceUnavailable;const c=await ja.ecdh.getPublicKeyFromRawPublicKey(i.a.decode(t)),u=await ja.ecdh.computeSharedKeyEncryptionKey(c,s),d=await ja.aesGcm.decryptString(u,n);l=await ja.aesGcm.getKeyFromKeyString(d),f=await ja.aesGcm.decryptString(l,e.databaseName)}catch(e){return null}const r=await hn(a),n=await nn(l,r),c=await ja.aesGcm.getKeyStringFromKey(l),u="SaveDatabase",d={databaseNameHash:o,encryptedDbKey:await ja.aesGcm.encryptString(t,c),receivedSignature:n};sr.request(u,d)}}const m={databaseName:f,databaseId:n,isOwner:c,readOnly:u,resharingAllowed:d,encryptionMode:e.plaintextDbKey?"server-side":"end-to-end"},p=await(async(e,t,s,a,r,n)=>{const i=[],o={databaseId:e,databaseNameHash:t};let c=await sr.request("GetDatabaseUsers",o);for(i.push(...await tn(s,c.data.users,a,r,n));c.data.nextPageTokenLessThanUserId||c.data.nextPageTokenMoreThanUserId;)o.nextPageTokenLessThanUserId=c.data.nextPageTokenLessThanUserId,o.nextPageTokenMoreThanUserId=c.data.nextPageTokenMoreThanUserId,c=await sr.request("GetDatabaseUsers",o),i.push(...await tn(s,c.data.users,a,r,n));return i})(n,o,l,a,r,h);return c||(e=>{for(let t=0;t{let a;Lr(s);try{a=Vr(e,t,null,s)}catch(r){const n="GetDatabases",i=e?{dbNameHash:"server-side"===s?e:await ja.hmac.signString(sr.keys.hmacKey,e)}:{databaseId:t},o=(await sr.request(n,i)).data.databases;if(!o||!o.length)throw new hs.DatabaseNotFound;a=o[0],a.dbNameHash=a.databaseNameHash,a.dbId=a.databaseId}return a},rn=async(e,t)=>{const s=await ja.aesGcm.getRawKeyFromKey(e),a=await ja.sha256.hash(s),r=await ja.hmac.importKeyFromRawBits(a);return await ja.hmac.signString(r,t)},nn=async(e,t)=>{const s=await rn(e,t);return await ja.ecdsa.signString(sr.keys.ecdsaPrivateKey,s)},on=async e=>{let t;return e.dbKey?t=await ja.aesGcm.getKeyStringFromKey(e.dbKey):(t=e.plaintextDbKey||await ja.aesGcm.decryptString(sr.keys.encryptionKey,e.encryptedDbKey),e.dbKey=await ja.aesGcm.getKeyFromKeyString(t)),t},cn=async(e,t,s,a,r)=>{const{databaseName:n,databaseId:o}=e,c=e.username.toLowerCase();try{const[e,u,d]=await Promise.all([Ts(c),a&&fn(),an(n,o,r)]);if(!e.ecdhPublicKey||!e.ecdsaPublicKey)throw new hs.UserUnableToReceiveDatabase;const h=i.a.decode(e.ecdsaPublicKey),l=await hn(h);a&&await(async(e,t,s)=>{let a,r;const n=Object.keys(s);for(let i=0;i{if("string"!=typeof e)throw new hs.UsernameMustBeString;if(0===e.length)throw new hs.UsernameCannotBeBlank},dn=e=>{if(Ga(e,"shareToken"))throw new hs.ShareTokenNotAllowed;if(Ga(e,"username")&&un(e.username),Ga(e,"readOnly")&&"boolean"!=typeof e.readOnly)throw new hs.ReadOnlyMustBeBoolean;if(Ga(e,"resharingAllowed")&&"boolean"!=typeof e.resharingAllowed)throw new hs.ResharingAllowedMustBeBoolean;if(Ga(e,"requireVerified")&&"boolean"!=typeof e.requireVerified)throw new hs.RequireVerifiedMustBeBoolean},hn=async e=>{const t=await ja.sha256.hash(e);return i.a.encode(t)},ln=async()=>{const e=await ja.ecdsa.getPublicKeyFromPrivateKey(sr.keys.ecdsaPrivateKey),t=await ja.ecdsa.getRawPublicKeyFromPublicKey(e);return await hn(t)},fn=async()=>{await qr({databaseName:"__userbase_verified_users",changeHandler:()=>{},allowVerifiedUsersDatabase:!0,encryptionMode:"end-to-end"});const e=sr.state.dbNameToHash.__userbase_verified_users;return sr.state.databases[e].items};var mn={openDatabase:qr,getDatabases:async e=>{try{void 0!==e&&jr(e),Tr();const{encryptionKey:t,ecdhPrivateKey:s}=sr.keys,a=sr.session.username;if(e&&Ga(e,"shareToken"))throw new hs.ShareTokenNotAllowed;const r=e&&e.encryptionMode||sr.encryptionMode;Lr(r);try{const n=[],i="GetDatabases",o=e&&{databaseId:e.databaseId,dbNameHash:"server-side"===r?e.databaseName:e.databaseName&&await ja.hmac.signString(sr.keys.hmacKey,e.databaseName)};let[c,u]=await Promise.all([sr.request(i,o),fn()]),d=await Promise.all(c.data.databases.map(e=>sn(e,t,s,u,a)));for(n.push(...d);c.data.nextPageToken;){const e={nextPageToken:c.data.nextPageToken};c=await sr.request(i,e),d=await Promise.all(c.data.databases.map(e=>sn(e,t,s,u,a))),n.push(...d)}return{databases:n.filter(e=>null!==e)}}catch(e){throw kr(e),e}}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"UserMustChangePassword":case"UserNotSignedIn":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},insertItem:Hr,updateItem:Jr,deleteItem:async e=>{try{jr(e);const t=Vr(e.databaseName,e.databaseId,e.shareToken,e.encryptionMode||sr.encryptionMode),s="Delete",a=await Yr(t,e);await zr(t,s,a)}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseNotOpen":case"DatabaseNameMissing":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"ShareTokenInvalid":case"DatabaseIsReadOnly":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"ItemIdMissing":case"ItemIdMustBeString":case"ItemIdCannotBeBlank":case"ItemIdTooLong":case"ItemDoesNotExist":case"ItemUpdateConflict":case"TransactionUnauthorized":case"UserMustChangePassword":case"UserNotSignedIn":case"UserNotFound":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},putTransaction:async e=>{try{if(jr(e),!Ga(e,"operations"))throw new hs.OperationsMissing;const{databaseName:t,databaseId:s,shareToken:a,operations:r,encryptionMode:n=sr.encryptionMode}=e;if(!Array.isArray(r))throw new hs.OperationsMustBeArray;const i=Vr(t,s,a,n),o="BatchTransaction",c=await Promise.all(r.map(e=>{const t=e.command;switch(t){case"Insert":return Gr(i,e);case"Update":return Wr(i,e);case"Delete":return Yr(i,e);default:throw new hs.CommandNotRecognized(t)}})),u=await Promise.all(c),d={operations:r.map((e,t)=>Ur({command:e.command},u[t]))};try{await zr(i,o,d)}catch(e){if(e.response&&"OperationsExceedLimit"===e.response.data.error)throw new hs.OperationsExceedLimit(e.response.data.limit);throw e}}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseNotOpen":case"DatabaseNameMissing":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"ShareTokenInvalid":case"DatabaseIsReadOnly":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"OperationsMissing":case"OperationsMustBeArray":case"OperationsConflict":case"OperationsExceedLimit":case"CommandNotRecognized":case"ItemIdMissing":case"ItemIdMustBeString":case"ItemIdCannotBeBlank":case"ItemIdTooLong":case"ItemMissing":case"ItemInvalid":case"ItemTooLarge":case"ItemAlreadyExists":case"ItemDoesNotExist":case"ItemUpdateConflict":case"WriteAccessParamNotAllowed":case"TransactionUnauthorized":case"UserMustChangePassword":case"UserNotSignedIn":case"UserNotFound":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},uploadFile:async e=>{try{(e=>{if(jr(e),Ga(e,"progressHandler")&&"function"!=typeof e.progressHandler)throw new hs.ProgressHandlerMustBeFunction})(e);const t=Vr(e.databaseName,e.databaseId,e.shareToken,e.encryptionMode||sr.encryptionMode),{dbId:s}=t;try{const{itemKey:a,fileMetadata:r}=await(async(e,t)=>{if(!Ga(e,"itemId"))throw new hs.ItemIdMissing;if(!Ga(e,"file"))throw new hs.FileMissing;const{itemId:s,file:a}=e;if("string"!=typeof s)throw new hs.ItemIdMustBeString;if(0===s.length)throw new hs.ItemIdCannotBeBlank;if(s.length>100)throw new hs.ItemIdTooLong(100);if(!t.itemExists(s))throw new hs.ItemDoesNotExist;if(!(a instanceof File))throw new hs.FileMustBeFile;if(0===a.size)throw new hs.FileCannotBeEmpty;const r=await ja.hmac.signString(sr.keys.hmacKey,s),n=t.getFileVersionNumber(s);return{itemKey:r,fileMetadata:{itemId:s,__v:void 0===n?0:n+1,fileName:a.name,fileSize:a.size,fileType:a.type}}})(e,t),[n,o]=await ja.aesGcm.generateAndEncryptKeyEncryptionKey(t.dbKey),c=await ja.aesGcm.encryptJson(n,r),{data:{fileId:u}}=await sr.request("GenerateFileId",{dbId:t.dbId}),d=e.file;let h=0,l=0,f=[];const m={bytesTransferred:0};for(;h{const n={dbId:e.dbId,fileId:t,itemKey:s,fileMetadata:a,fileEncryptionKey:i.a.encode(r)};await zr(e,"CompleteFileUpload",n)})(t,u,a,c,o)}catch(e){if(kr(e),e.response&&"DatabaseIsReadOnly"===e.response.data)throw new hs.DatabaseIsReadOnly;throw e}}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseNotOpen":case"DatabaseNameMissing":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"ShareTokenInvalid":case"DatabaseIsReadOnly":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"ItemIdMissing":case"ItemIdMustBeString":case"ItemIdCannotBeBlank":case"ItemIdTooLong":case"ItemDoesNotExist":case"TransactionUnauthorized":case"FileMustBeFile":case"FileCannotBeEmpty":case"FileMissing":case"FileUploadConflict":case"ProgressHandlerMustBeFunction":case"UserMustChangePassword":case"UserNotSignedIn":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},getFile:async e=>{try{(e=>{if(jr(e),!Ga(e,"fileId"))throw new hs.FileIdMissing;const{fileId:t,range:s}=e;if("string"!=typeof t)throw new hs.FileIdMustBeString;if(0===t.length)throw new hs.FileIdCannotBeBlank;if(t.length>100)throw new hs.FileIdTooLong(100);if(Ga(e,"range")){if("object"!=typeof s)throw new hs.RangeMustBeObject;if(!Ga(s,"start"))throw new hs.RangeMissingStart;if(!Ga(s,"end"))throw new hs.RangeMissingEnd;const{start:e,end:t}=s;if("number"!=typeof e)throw new hs.RangeStartMustBeNumber;if("number"!=typeof t)throw new hs.RangeEndMustBeNumber;if(e<0)throw new hs.RangeStartMustBeGreaterThanZero;if(t<=e)throw new hs.RangeEndMustBeGreaterThanRangeStart}})(e);const t=Vr(e.databaseName,e.databaseId,e.shareToken,e.encryptionMode||sr.encryptionMode),{dbId:s}=t,{fileId:a,range:r}=e,n=t.fileIds[a],i=t.items[n];if(!i||!i.file)throw new hs.FileNotFound;const{file:{fileName:o,fileSize:c,fileType:u,fileEncryptionKey:d}}=i;if(r&&r.end>c)throw new hs.RangeEndMustBeLessThanFileSize;const h=r?await(async(e,t,s,a)=>{const{start:r,end:n}=a,i=[],o=Math.floor(r/524288),c=Math.floor(n/524288)-(n%524288==0?1:0);let u=o;for(;u<=c;){let a=await Xr(e,t,u,s);u===o&&u===c&&n%524288?a=a.slice(r%524288,n%524288):u===o?a=a.slice(r%524288):u===c&&n%524288&&(a=a.slice(0,n%524288)),i.push(a),u+=1}return i})(s,a,d,r):await(async(e,t,s,a)=>{const r=[];let n=0;const i=a<524288?0:Math.floor(a/524288)-(a%524288==0?1:0);for(;n<=i;){const a=await Xr(e,t,n,s);r.push(a),n+=1}return r})(s,a,d,c);return{file:new File(h,o,{type:u})}}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseNotOpen":case"DatabaseNameMissing":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"ShareTokenInvalid":case"DatabaseIsReadOnly":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"FileIdMissing":case"FileIdMustBeString":case"FileIdCannotBeBlank":case"FileIdTooLong":case"FileNotFound":case"RangeMustBeObject":case"RangeMissingStart":case"RangeMissingEnd":case"RangeStartMustBeNumber":case"RangeEndMustBeNumber":case"RangeStartMustBeGreaterThanZero":case"RangeEndMustBeGreaterThanRangeStart":case"RangeEndMustBeLessThanFileSize":case"UserMustChangePassword":case"UserNotSignedIn":case"UserNotFound":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},shareDatabase:async e=>{try{jr(e),dn(e);const t=!Ga(e,"readOnly")||e.readOnly,s=!!Ga(e,"resharingAllowed")&&e.resharingAllowed,a=!Ga(e,"requireVerified")||e.requireVerified,r=e.encryptionMode||sr.encryptionMode;Lr(r);let n={};return Ga(e,"username")?await cn(e,t,s,a,r):n.shareToken=await(async(e,t,s)=>{try{const{databaseName:a,databaseId:r}=e;if(Ga(e,"requireVerified"))throw new hs.RequireVerifiedParamNotNecessary;if(Ga(e,"resharingAllowed"))throw new hs.ResharingAllowedParamNotAllowed("when retrieving a share token");const n=ja.generateSeed(),o=await ja.hkdf.importHkdfKey(n),c=ja.hkdf.generateSalt(),u=await ja.aesGcm.importKeyFromMaster(o,c),d=await an(a,r,s),h=await on(d),l=await ja.aesGcm.encryptString(u,h),{ecdsaPublicKey:f,encryptedEcdsaPrivateKey:m,ecdsaKeyEncryptionKeySalt:p}=await ja.ecdsa.generateEcdsaKeyData(o),w="ShareDatabaseToken",g={databaseId:d.dbId,databaseNameHash:d.dbNameHash,readOnly:t,keyData:{shareTokenEncryptedDbKey:l,shareTokenEncryptionKeySalt:i.a.encode(c),shareTokenPublicKey:f,shareTokenEncryptedEcdsaPrivateKey:m,shareTokenEcdsaKeyEncryptionKeySalt:p}},y=await sr.request(w,g),{shareTokenId:b}=y.data,v=Ls(b,!0);return i.a.encode(js(v,n))}catch(e){if(kr(e),e.response&&e.response.data)switch(e.response.data.message){case"DatabaseNotFound":throw new hs.DatabaseNotFound;case"ResharingNotAllowed":throw new hs.ResharingNotAllowed("Only the owner can generate a share token")}throw e}})(e,t,r),n}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseNameMissing":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"DatabaseNotFound":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"UsernameCannotBeBlank":case"UsernameMustBeString":case"ReadOnlyMustBeBoolean":case"ResharingAllowedMustBeBoolean":case"ResharingNotAllowed":case"ResharingWithWriteAccessNotAllowed":case"ResharingAllowedParamNotAllowed":case"RequireVerifiedMustBeBoolean":case"RequireVerifiedParamNotNecessary":case"SharingWithSelfNotAllowed":case"UserMustChangePassword":case"UserNotSignedIn":case"UserUnableToReceiveDatabase":case"UserNotFound":case"UserNotVerified":case"UserMustBeReverified":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},modifyDatabasePermissions:async e=>{try{if(jr(e),dn(e),!Ga(e,"username"))throw new hs.UsernameMissing;if(Ga(e,"revoke")){if("boolean"!=typeof e.revoke)throw new hs.RevokeMustBeBoolean;if(e.revoke){if(Ga(e,"readOnly"))throw new hs.ReadOnlyParamNotAllowed;if(Ga(e,"resharingAllowed"))throw new hs.ResharingAllowedParamNotAllowed("when revoking access to a database")}}else if(!Ga(e,"readOnly")&&!Ga(e,"resharingAllowed"))throw new hs.ParamsMissing;const{databaseName:t,databaseId:s,readOnly:a,resharingAllowed:r,revoke:n,encryptionMode:i=sr.encryptionMode}=e,o=e.username.toLowerCase();try{const e=await an(t,s,i),c="ModifyDatabasePermissions",u={databaseId:e.dbId,databaseNameHash:e.dbNameHash,username:o,readOnly:a,resharingAllowed:r,revoke:n};await sr.request(c,u)}catch(e){if(kr(e),e.response&&e.response.data)switch(e.response.data.message){case"SharingWithSelfNotAllowed":throw new hs.ModifyingOwnPermissionsNotAllowed;case"ModifyingOwnerPermissionsNotAllowed":throw new hs.ModifyingOwnerPermissionsNotAllowed;case"ResharingNotAllowed":throw new hs.ModifyingPermissionsNotAllowed;case"ResharingWithWriteAccessNotAllowed":throw new hs.GrantingWriteAccessNotAllowed;case"DatabaseNotFound":throw new hs.DatabaseNotFound;case"UserNotFound":throw new hs.UserNotFound}throw e}}catch(e){switch(e.name){case"ParamsMustBeObject":case"ParamsMissing":case"DatabaseNameMissing":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"DatabaseNotFound":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"UsernameMissing":case"UsernameCannotBeBlank":case"UsernameMustBeString":case"ReadOnlyMustBeBoolean":case"ReadOnlyParamNotAllowed":case"ResharingAllowedMustBeBoolean":case"ResharingAllowedParamNotAllowed":case"RevokeMustBeBoolean":case"ModifyingOwnPermissionsNotAllowed":case"ModifyingOwnerPermissionsNotAllowed":case"ModifyingPermissionsNotAllowed":case"GrantingWriteAccessNotAllowed":case"UserMustChangePassword":case"UserNotSignedIn":case"UserNotFound":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},getVerificationMessage:async()=>{try{Tr();const e=sr.session.username,t=await ln();return{verificationMessage:((e,t)=>btoa(JSON.stringify({username:e,fingerprint:t})))(e,t)}}catch(e){switch(e.name){case"UserMustChangePassword":case"UserNotSignedIn":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},verifyUser:async e=>{try{if("object"!=typeof e)throw new hs.ParamsMustBeObject;if(Tr(),!Ga(e,"verificationMessage"))throw new hs.VerificationMessageMissing;const{verificationMessage:t}=e;if("string"!=typeof t)throw new hs.VerificationMessageMustBeString;if(0===t.length)throw new hs.VerificationMessageCannotBeBlank;const{username:s,fingerprint:a}=(e=>{try{const{username:t,fingerprint:s}=JSON.parse(atob(e));if(un(t),!s)throw new hs.VerificationMessageInvalid;return{username:t,fingerprint:s}}catch(e){throw new hs.VerificationMessageInvalid}})(t);if(s===sr.session.username||a===await ln())throw new hs.VerifyingSelfNotAllowed;await fn();const r="__userbase_verified_users",n=!0,i=s,o={fingerprint:a};try{await Hr({databaseName:r,itemId:i,item:o,allowVerifiedUsersDatabase:n})}catch(e){if("ItemAlreadyExists"!==e.name)throw e;await Jr({databaseName:r,itemId:i,item:o,allowVerifiedUsersDatabase:n})}}catch(e){switch(e.name){case"ParamsMustBeObject":case"VerificationMessageMissing":case"VerificationMessageMustBeString":case"VerificationMessageCannotBeBlank":case"VerificationMessageInvalid":case"VerifyingSelfNotAllowed":case"UserMustChangePassword":case"UserNotSignedIn":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}}};const pn=()=>{if(sr.reconnecting)throw new hs.Reconnecting;if(!sr.keys.init&&sr.changePassword)throw new hs.UserMustChangePassword;if(!sr.keys.init)throw new hs.UserNotSignedIn},wn=e=>{if(e.response){if(e.response.status===p)throw new hs.InternalServerError;if(e.response.status===g)throw new hs.Timeout}else if(e.message&&-1!==e.message.indexOf("timeout"))throw new hs.Timeout},gn=e=>{pn();const t=sr.userData.stripeData;if(!t.stripeAccountId)throw new hs.StripeAccountNotConnected;if("disabled"===t.paymentsMode)throw new hs.PaymentsDisabled;if(!Ga(window,"Stripe"))throw new hs.StripeJsLibraryMissing;if("object"!=typeof e)throw new hs.ParamsMustBeObject;if(!Ga(e,"successUrl"))throw new hs.SuccessUrlMissing;if("string"!=typeof e.successUrl)throw new hs.SuccessUrlMustBeString;const s=qa(e.successUrl);if("http"!==s&&"https"!==s){const e=!0;throw new hs.SuccessUrlInvalid(e)}if(!Ga(e,"cancelUrl"))throw new hs.CancelUrlMissing;if("string"!=typeof e.cancelUrl)throw new hs.CancelUrlMustBeString;const a=qa(e.cancelUrl);if("http"!==a&&"https"!==a){const e=!0;throw new hs.CancelUrlInvalid(e)}},yn=()=>{pn();const e=sr.userData.stripeData;if(!e.stripeAccountId)throw new hs.StripeAccountNotConnected;if("disabled"===e.paymentsMode)throw new hs.PaymentsDisabled;if("canceled"===e.subscriptionStatus)throw new hs.SubscriptionAlreadyCanceled};var bn={purchaseSubscription:async e=>{try{const t=sr.userData.stripeData;if(!t.cancelSubscriptionAt&&t.subscriptionStatus&&"canceled"!==t.subscriptionStatus)throw new hs.SubscriptionPlanAlreadyPurchased;gn(e);try{const s="PurchaseSubscription",a=(await sr.request(s,e)).data,r=vs("prod"===t.paymentsMode),n=await window.Stripe(r,{stripeAccount:t.stripeAccountId}).redirectToCheckout({sessionId:a});if(n.error)throw n.error}catch(e){if(wn(e),e.response)switch(e.response.data){case"PriceIdOrPlanIdAllowed":throw new hs.PriceIdOrPlanIdAllowed;case"PriceIdOrPlanIdMissing":throw new hs.PriceIdOrPlanIdMissing;case"SubscriptionPlanAlreadyPurchased":throw new hs.SubscriptionPlanAlreadyPurchased;case"SuccessUrlInvalid":throw new hs.SuccessUrlInvalid;case"CancelUrlInvalid":throw new hs.CancelUrlInvalid;default:if(e.response.data&&"StripeError"===e.response.data.name)throw new hs.StripeError(e.response.data)}throw e}}catch(e){switch(e.name){case"ParamsMustBeObject":case"SuccessUrlMissing":case"SuccessUrlMustBeString":case"SuccessUrlInvalid":case"CancelUrlMissing":case"CancelUrlMustBeString":case"CancelUrlInvalid":case"StripeError":case"StripeJsLibraryMissing":case"PriceIdOrPlanIdAllowed":case"PriceIdOrPlanIdMissing":case"SubscriptionPlanAlreadyPurchased":case"StripeAccountNotConnected":case"PaymentsDisabled":case"UserMustChangePassword":case"UserNotSignedIn":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},cancelSubscription:async()=>{try{yn();try{const e="CancelSubscription",t=(await sr.request(e)).data;return sr.userData.stripeData.cancelSubscriptionAt=t,{cancelSubscriptionAt:t}}catch(e){if(wn(e),e.response&&"SubscriptionNotFound"===e.response.data)throw new hs.SubscriptionNotFound;throw e}}catch(e){switch(e.name){case"SubscriptionNotFound":case"StripeAccountNotConnected":case"PaymentsDisabled":case"SubscriptionAlreadyCanceled":case"UserMustChangePassword":case"UserNotSignedIn":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},resumeSubscription:async()=>{try{yn();try{const e="ResumeSubscription";await sr.request(e),delete sr.userData.stripeData.cancelSubscriptionAt}catch(e){if(wn(e),e.response&&"SubscriptionNotFound"===e.response.data)throw new hs.SubscriptionNotFound;throw e}}catch(e){switch(e.name){case"SubscriptionNotFound":case"StripeAccountNotConnected":case"PaymentsDisabled":case"SubscriptionAlreadyCanceled":case"UserMustChangePassword":case"UserNotSignedIn":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},updatePaymentMethod:async e=>{try{gn(e);const t=sr.userData.stripeData;if(!t.subscriptionStatus)throw new hs.SubscriptionNotPurchased;try{const s="UpdatePaymentMethod",a=(await sr.request(s,e)).data,r=vs("prod"===t.paymentsMode),n=await window.Stripe(r,{stripeAccount:t.stripeAccountId}).redirectToCheckout({sessionId:a});if(n.error)throw n.error}catch(e){if(wn(e),e.response){if("SuccessUrlInvalid"===e.response.data)throw new hs.SuccessUrlInvalid;if("CancelUrlInvalid"===e.response.data)throw new hs.CancelUrlInvalid}throw e}}catch(e){switch(e.name){case"ParamsMustBeObject":case"SuccessUrlMissing":case"SuccessUrlMustBeString":case"SuccessUrlInvalid":case"CancelUrlMissing":case"CancelUrlMustBeString":case"CancelUrlInvalid":case"StripeJsLibraryMissing":case"SubscriptionNotPurchased":case"StripeAccountNotConnected":case"PaymentsDisabled":case"UserMustChangePassword":case"UserNotSignedIn":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}}};t.default={init:Pr.init,signUp:Pr.signUp,signIn:Pr.signIn,signOut:Pr.signOut,updateUser:Pr.updateUser,deleteUser:Pr.deleteUser,forgotPassword:Pr.forgotPassword,openDatabase:mn.openDatabase,insertItem:mn.insertItem,updateItem:mn.updateItem,deleteItem:mn.deleteItem,putTransaction:mn.putTransaction,uploadFile:mn.uploadFile,getFile:mn.getFile,getDatabases:mn.getDatabases,shareDatabase:mn.shareDatabase,modifyDatabasePermissions:mn.modifyDatabasePermissions,getVerificationMessage:mn.getVerificationMessage,verifyUser:mn.verifyUser,purchaseSubscription:bn.purchaseSubscription,cancelSubscription:bn.cancelSubscription,resumeSubscription:bn.resumeSubscription,updatePaymentMethod:bn.updatePaymentMethod}}]).default; -//# sourceMappingURL=userbase.js.map -var userbase=function(e){var t={};function s(a){if(t[a])return t[a].exports;var r=t[a]={i:a,l:!1,exports:{}};return e[a].call(r.exports,r,r.exports,s),r.l=!0,r.exports}return s.m=e,s.c=t,s.d=function(e,t,a){s.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:a})},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.t=function(e,t){if(1&t&&(e=s(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var a=Object.create(null);if(s.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)s.d(a,r,function(t){return e[t]}.bind(null,r));return a},s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,"a",t),t},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.p="",s(s.s=27)}([function(e,t){!function(){"use strict";for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=new Uint8Array(256),a=0;a>2],n+=e[(3&a[s])<<4|a[s+1]>>4],n+=e[(15&a[s+1])<<2|a[s+2]>>6],n+=e[63&a[s+2]];return r%3==2?n=n.substring(0,n.length-1)+"=":r%3==1&&(n=n.substring(0,n.length-2)+"=="),n},t.decode=function(e){var t,a,r,n,i,o=.75*e.length,c=e.length,u=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);var d=new ArrayBuffer(o),h=new Uint8Array(d);for(t=0;t>4,h[u++]=(15&r)<<4|n>>2,h[u++]=(3&n)<<6|63&i;return d}}()},function(e,t){e.exports=function(e,t,s){return t in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}},function(e,t,s){var a=s(13),r=s(14);e.exports=function(e,t,s){var n=t&&s||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var i=(e=e||{}).random||(e.rng||a)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t)for(var o=0;o<16;++o)t[n+o]=i[o];return t||r(i)}},function(e,t){var s;s=function(){return this}();try{s=s||new Function("return this")()}catch(e){"object"==typeof window&&(s=window)}e.exports=s},function(e,t,s){"use strict";(function(e){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -var a=s(15),r=s(16),n=s(17);function i(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(i()=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|e}function m(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var s=e.length;if(0===s)return 0;for(var a=!1;;)switch(t){case"ascii":case"latin1":case"binary":return s;case"utf8":case"utf-8":case void 0:return L(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*s;case"hex":return s>>>1;case"base64":return j(e).length;default:if(a)return L(e).length;t=(""+t).toLowerCase(),a=!0}}function p(e,t,s){var a=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===s||s>this.length)&&(s=this.length),s<=0)return"";if((s>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return A(this,t,s);case"utf8":case"utf-8":return B(this,t,s);case"ascii":return N(this,t,s);case"latin1":case"binary":return U(this,t,s);case"base64":return E(this,t,s);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,t,s);default:if(a)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),a=!0}}function w(e,t,s){var a=e[t];e[t]=e[s],e[s]=a}function g(e,t,s,a,r){if(0===e.length)return-1;if("string"==typeof s?(a=s,s=0):s>2147483647?s=2147483647:s<-2147483648&&(s=-2147483648),s=+s,isNaN(s)&&(s=r?0:e.length-1),s<0&&(s=e.length+s),s>=e.length){if(r)return-1;s=e.length-1}else if(s<0){if(!r)return-1;s=0}if("string"==typeof t&&(t=c.from(t,a)),c.isBuffer(t))return 0===t.length?-1:y(e,t,s,a,r);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,s):Uint8Array.prototype.lastIndexOf.call(e,t,s):y(e,[t],s,a,r);throw new TypeError("val must be string, number or Buffer")}function y(e,t,s,a,r){var n,i=1,o=e.length,c=t.length;if(void 0!==a&&("ucs2"===(a=String(a).toLowerCase())||"ucs-2"===a||"utf16le"===a||"utf-16le"===a)){if(e.length<2||t.length<2)return-1;i=2,o/=2,c/=2,s/=2}function u(e,t){return 1===i?e[t]:e.readUInt16BE(t*i)}if(r){var d=-1;for(n=s;no&&(s=o-c),n=s;n>=0;n--){for(var h=!0,l=0;lr&&(a=r):a=r;var n=t.length;if(n%2!=0)throw new TypeError("Invalid hex string");a>n/2&&(a=n/2);for(var i=0;i>8,r=s%256,n.push(r),n.push(a);return n}(t,e.length-s),e,s,a)}function E(e,t,s){return 0===t&&s===e.length?a.fromByteArray(e):a.fromByteArray(e.slice(t,s))}function B(e,t,s){s=Math.min(e.length,s);for(var a=[],r=t;r239?4:u>223?3:u>191?2:1;if(r+h<=s)switch(h){case 1:u<128&&(d=u);break;case 2:128==(192&(n=e[r+1]))&&(c=(31&u)<<6|63&n)>127&&(d=c);break;case 3:n=e[r+1],i=e[r+2],128==(192&n)&&128==(192&i)&&(c=(15&u)<<12|(63&n)<<6|63&i)>2047&&(c<55296||c>57343)&&(d=c);break;case 4:n=e[r+1],i=e[r+2],o=e[r+3],128==(192&n)&&128==(192&i)&&128==(192&o)&&(c=(15&u)<<18|(63&n)<<12|(63&i)<<6|63&o)>65535&&c<1114112&&(d=c)}null===d?(d=65533,h=1):d>65535&&(d-=65536,a.push(d>>>10&1023|55296),d=56320|1023&d),a.push(d),r+=h}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var s="",a=0;for(;a0&&(e=this.toString("hex",0,s).match(/.{2}/g).join(" "),this.length>s&&(e+=" ... ")),""},c.prototype.compare=function(e,t,s,a,r){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===s&&(s=e?e.length:0),void 0===a&&(a=0),void 0===r&&(r=this.length),t<0||s>e.length||a<0||r>this.length)throw new RangeError("out of range index");if(a>=r&&t>=s)return 0;if(a>=r)return-1;if(t>=s)return 1;if(this===e)return 0;for(var n=(r>>>=0)-(a>>>=0),i=(s>>>=0)-(t>>>=0),o=Math.min(n,i),u=this.slice(a,r),d=e.slice(t,s),h=0;hr)&&(s=r),e.length>0&&(s<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");a||(a="utf8");for(var n=!1;;)switch(a){case"hex":return b(this,e,t,s);case"utf8":case"utf-8":return v(this,e,t,s);case"ascii":return M(this,e,t,s);case"latin1":case"binary":return S(this,e,t,s);case"base64":return I(this,e,t,s);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(this,e,t,s);default:if(n)throw new TypeError("Unknown encoding: "+a);a=(""+a).toLowerCase(),n=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function N(e,t,s){var a="";s=Math.min(e.length,s);for(var r=t;ra)&&(s=a);for(var r="",n=t;ns)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,s,a,r,n){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||te.length)throw new RangeError("Index out of range")}function K(e,t,s,a){t<0&&(t=65535+t+1);for(var r=0,n=Math.min(e.length-s,2);r>>8*(a?r:1-r)}function x(e,t,s,a){t<0&&(t=4294967295+t+1);for(var r=0,n=Math.min(e.length-s,4);r>>8*(a?r:3-r)&255}function R(e,t,s,a,r,n){if(s+a>e.length)throw new RangeError("Index out of range");if(s<0)throw new RangeError("Index out of range")}function O(e,t,s,a,n){return n||R(e,0,s,4),r.write(e,t,s,a,23,4),s+4}function C(e,t,s,a,n){return n||R(e,0,s,8),r.write(e,t,s,a,52,8),s+8}c.prototype.slice=function(e,t){var s,a=this.length;if((e=~~e)<0?(e+=a)<0&&(e=0):e>a&&(e=a),(t=void 0===t?a:~~t)<0?(t+=a)<0&&(t=0):t>a&&(t=a),t0&&(r*=256);)a+=this[e+--t]*r;return a},c.prototype.readUInt8=function(e,t){return t||k(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||k(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||k(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||k(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||k(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,s){e|=0,t|=0,s||k(e,t,this.length);for(var a=this[e],r=1,n=0;++n=(r*=128)&&(a-=Math.pow(2,8*t)),a},c.prototype.readIntBE=function(e,t,s){e|=0,t|=0,s||k(e,t,this.length);for(var a=t,r=1,n=this[e+--a];a>0&&(r*=256);)n+=this[e+--a]*r;return n>=(r*=128)&&(n-=Math.pow(2,8*t)),n},c.prototype.readInt8=function(e,t){return t||k(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||k(e,2,this.length);var s=this[e]|this[e+1]<<8;return 32768&s?4294901760|s:s},c.prototype.readInt16BE=function(e,t){t||k(e,2,this.length);var s=this[e+1]|this[e]<<8;return 32768&s?4294901760|s:s},c.prototype.readInt32LE=function(e,t){return t||k(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||k(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||k(e,4,this.length),r.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||k(e,4,this.length),r.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||k(e,8,this.length),r.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||k(e,8,this.length),r.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,s,a){(e=+e,t|=0,s|=0,a)||D(this,e,t,s,Math.pow(2,8*s)-1,0);var r=1,n=0;for(this[t]=255&e;++n=0&&(n*=256);)this[t+r]=e/n&255;return t+s},c.prototype.writeUInt8=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):K(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):K(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):x(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):x(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,s,a){if(e=+e,t|=0,!a){var r=Math.pow(2,8*s-1);D(this,e,t,s,r-1,-r)}var n=0,i=1,o=0;for(this[t]=255&e;++n>0)-o&255;return t+s},c.prototype.writeIntBE=function(e,t,s,a){if(e=+e,t|=0,!a){var r=Math.pow(2,8*s-1);D(this,e,t,s,r-1,-r)}var n=s-1,i=1,o=0;for(this[t+n]=255&e;--n>=0&&(i*=256);)e<0&&0===o&&0!==this[t+n+1]&&(o=1),this[t+n]=(e/i>>0)-o&255;return t+s},c.prototype.writeInt8=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):K(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):K(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):x(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,s){return e=+e,t|=0,s||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):x(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,s){return O(this,e,t,!0,s)},c.prototype.writeFloatBE=function(e,t,s){return O(this,e,t,!1,s)},c.prototype.writeDoubleLE=function(e,t,s){return C(this,e,t,!0,s)},c.prototype.writeDoubleBE=function(e,t,s){return C(this,e,t,!1,s)},c.prototype.copy=function(e,t,s,a){if(s||(s=0),a||0===a||(a=this.length),t>=e.length&&(t=e.length),t||(t=0),a>0&&a=this.length)throw new RangeError("sourceStart out of bounds");if(a<0)throw new RangeError("sourceEnd out of bounds");a>this.length&&(a=this.length),e.length-t=0;--r)e[r+t]=this[r+s];else if(n<1e3||!c.TYPED_ARRAY_SUPPORT)for(r=0;r>>=0,s=void 0===s?this.length:s>>>0,e||(e=0),"number"==typeof e)for(n=t;n55295&&s<57344){if(!r){if(s>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(i+1===a){(t-=3)>-1&&n.push(239,191,189);continue}r=s;continue}if(s<56320){(t-=3)>-1&&n.push(239,191,189),r=s;continue}s=65536+(r-55296<<10|s-56320)}else r&&(t-=3)>-1&&n.push(239,191,189);if(r=null,s<128){if((t-=1)<0)break;n.push(s)}else if(s<2048){if((t-=2)<0)break;n.push(s>>6|192,63&s|128)}else if(s<65536){if((t-=3)<0)break;n.push(s>>12|224,s>>6&63|128,63&s|128)}else{if(!(s<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;n.push(s>>18|240,s>>12&63|128,s>>6&63|128,63&s|128)}}return n}function j(e){return a.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(_,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function q(e,t,s,a){for(var r=0;r=t.length||r>=e.length);++r)t[r+s]=e[r];return r}}).call(this,s(3))},function(e,t,s){(function(e){!function(e,t){"use strict";function a(e,t){if(!e)throw new Error(t||"Assertion failed")}function r(e,t){e.super_=t;var s=function(){};s.prototype=t.prototype,e.prototype=new s,e.prototype.constructor=e}function n(e,t,s){if(n.isBN(e))return e;this.negative=0,this.words=null,this.length=0,this.red=null,null!==e&&("le"!==t&&"be"!==t||(s=t,t=10),this._init(e||0,t||10,s||"be"))}var i;"object"==typeof e?e.exports=n:t.BN=n,n.BN=n,n.wordSize=26;try{i=s(20).Buffer}catch(e){}function o(e,t,s){for(var a=0,r=Math.min(e.length,s),n=t;n=49&&i<=54?i-49+10:i>=17&&i<=22?i-17+10:15&i}return a}function c(e,t,s,a){for(var r=0,n=Math.min(e.length,s),i=t;i=49?o-49+10:o>=17?o-17+10:o}return r}n.isBN=function(e){return e instanceof n||null!==e&&"object"==typeof e&&e.constructor.wordSize===n.wordSize&&Array.isArray(e.words)},n.max=function(e,t){return e.cmp(t)>0?e:t},n.min=function(e,t){return e.cmp(t)<0?e:t},n.prototype._init=function(e,t,s){if("number"==typeof e)return this._initNumber(e,t,s);if("object"==typeof e)return this._initArray(e,t,s);"hex"===t&&(t=16),a(t===(0|t)&&t>=2&&t<=36);var r=0;"-"===(e=e.toString().replace(/\s+/g,""))[0]&&r++,16===t?this._parseHex(e,r):this._parseBase(e,t,r),"-"===e[0]&&(this.negative=1),this.strip(),"le"===s&&this._initArray(this.toArray(),t,s)},n.prototype._initNumber=function(e,t,s){e<0&&(this.negative=1,e=-e),e<67108864?(this.words=[67108863&e],this.length=1):e<4503599627370496?(this.words=[67108863&e,e/67108864&67108863],this.length=2):(a(e<9007199254740992),this.words=[67108863&e,e/67108864&67108863,1],this.length=3),"le"===s&&this._initArray(this.toArray(),t,s)},n.prototype._initArray=function(e,t,s){if(a("number"==typeof e.length),e.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(e.length/3),this.words=new Array(this.length);for(var r=0;r=0;r-=3)i=e[r]|e[r-1]<<8|e[r-2]<<16,this.words[n]|=i<>>26-o&67108863,(o+=24)>=26&&(o-=26,n++);else if("le"===s)for(r=0,n=0;r>>26-o&67108863,(o+=24)>=26&&(o-=26,n++);return this.strip()},n.prototype._parseHex=function(e,t){this.length=Math.ceil((e.length-t)/6),this.words=new Array(this.length);for(var s=0;s=t;s-=6)r=o(e,s,s+6),this.words[a]|=r<>>26-n&4194303,(n+=24)>=26&&(n-=26,a++);s+6!==t&&(r=o(e,t,s+6),this.words[a]|=r<>>26-n&4194303),this.strip()},n.prototype._parseBase=function(e,t,s){this.words=[0],this.length=1;for(var a=0,r=1;r<=67108863;r*=t)a++;a--,r=r/t|0;for(var n=e.length-s,i=n%a,o=Math.min(n,n-i)+s,u=0,d=s;d1&&0===this.words[this.length-1];)this.length--;return this._normSign()},n.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.negative=0),this},n.prototype.inspect=function(){return(this.red?""};var u=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],d=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],h=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];function l(e,t,s){s.negative=t.negative^e.negative;var a=e.length+t.length|0;s.length=a,a=a-1|0;var r=0|e.words[0],n=0|t.words[0],i=r*n,o=67108863&i,c=i/67108864|0;s.words[0]=o;for(var u=1;u>>26,h=67108863&c,l=Math.min(u,t.length-1),f=Math.max(0,u-e.length+1);f<=l;f++){var m=u-f|0;d+=(i=(r=0|e.words[m])*(n=0|t.words[f])+h)/67108864|0,h=67108863&i}s.words[u]=0|h,c=0|d}return 0!==c?s.words[u]=0|c:s.length--,s.strip()}n.prototype.toString=function(e,t){var s;if(t=0|t||1,16===(e=e||10)||"hex"===e){s="";for(var r=0,n=0,i=0;i>>24-r&16777215)||i!==this.length-1?u[6-c.length]+c+s:c+s,(r+=2)>=26&&(r-=26,i--)}for(0!==n&&(s=n.toString(16)+s);s.length%t!=0;)s="0"+s;return 0!==this.negative&&(s="-"+s),s}if(e===(0|e)&&e>=2&&e<=36){var l=d[e],f=h[e];s="";var m=this.clone();for(m.negative=0;!m.isZero();){var p=m.modn(f).toString(e);s=(m=m.idivn(f)).isZero()?p+s:u[l-p.length]+p+s}for(this.isZero()&&(s="0"+s);s.length%t!=0;)s="0"+s;return 0!==this.negative&&(s="-"+s),s}a(!1,"Base should be between 2 and 36")},n.prototype.toNumber=function(){var e=this.words[0];return 2===this.length?e+=67108864*this.words[1]:3===this.length&&1===this.words[2]?e+=4503599627370496+67108864*this.words[1]:this.length>2&&a(!1,"Number can only safely store up to 53 bits"),0!==this.negative?-e:e},n.prototype.toJSON=function(){return this.toString(16)},n.prototype.toBuffer=function(e,t){return a(void 0!==i),this.toArrayLike(i,e,t)},n.prototype.toArray=function(e,t){return this.toArrayLike(Array,e,t)},n.prototype.toArrayLike=function(e,t,s){var r=this.byteLength(),n=s||Math.max(1,r);a(r<=n,"byte array longer than desired length"),a(n>0,"Requested array length <= 0"),this.strip();var i,o,c="le"===t,u=new e(n),d=this.clone();if(c){for(o=0;!d.isZero();o++)i=d.andln(255),d.iushrn(8),u[o]=i;for(;o=4096&&(s+=13,t>>>=13),t>=64&&(s+=7,t>>>=7),t>=8&&(s+=4,t>>>=4),t>=2&&(s+=2,t>>>=2),s+t},n.prototype._zeroBits=function(e){if(0===e)return 26;var t=e,s=0;return 0==(8191&t)&&(s+=13,t>>>=13),0==(127&t)&&(s+=7,t>>>=7),0==(15&t)&&(s+=4,t>>>=4),0==(3&t)&&(s+=2,t>>>=2),0==(1&t)&&s++,s},n.prototype.bitLength=function(){var e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},n.prototype.zeroBits=function(){if(this.isZero())return 0;for(var e=0,t=0;te.length?this.clone().ior(e):e.clone().ior(this)},n.prototype.uor=function(e){return this.length>e.length?this.clone().iuor(e):e.clone().iuor(this)},n.prototype.iuand=function(e){var t;t=this.length>e.length?e:this;for(var s=0;se.length?this.clone().iand(e):e.clone().iand(this)},n.prototype.uand=function(e){return this.length>e.length?this.clone().iuand(e):e.clone().iuand(this)},n.prototype.iuxor=function(e){var t,s;this.length>e.length?(t=this,s=e):(t=e,s=this);for(var a=0;ae.length?this.clone().ixor(e):e.clone().ixor(this)},n.prototype.uxor=function(e){return this.length>e.length?this.clone().iuxor(e):e.clone().iuxor(this)},n.prototype.inotn=function(e){a("number"==typeof e&&e>=0);var t=0|Math.ceil(e/26),s=e%26;this._expand(t),s>0&&t--;for(var r=0;r0&&(this.words[r]=~this.words[r]&67108863>>26-s),this.strip()},n.prototype.notn=function(e){return this.clone().inotn(e)},n.prototype.setn=function(e,t){a("number"==typeof e&&e>=0);var s=e/26|0,r=e%26;return this._expand(s+1),this.words[s]=t?this.words[s]|1<e.length?(s=this,a=e):(s=e,a=this);for(var r=0,n=0;n>>26;for(;0!==r&&n>>26;if(this.length=s.length,0!==r)this.words[this.length]=r,this.length++;else if(s!==this)for(;ne.length?this.clone().iadd(e):e.clone().iadd(this)},n.prototype.isub=function(e){if(0!==e.negative){e.negative=0;var t=this.iadd(e);return e.negative=1,t._normSign()}if(0!==this.negative)return this.negative=0,this.iadd(e),this.negative=1,this._normSign();var s,a,r=this.cmp(e);if(0===r)return this.negative=0,this.length=1,this.words[0]=0,this;r>0?(s=this,a=e):(s=e,a=this);for(var n=0,i=0;i>26,this.words[i]=67108863&t;for(;0!==n&&i>26,this.words[i]=67108863&t;if(0===n&&i>>13,f=0|i[1],m=8191&f,p=f>>>13,w=0|i[2],g=8191&w,y=w>>>13,b=0|i[3],v=8191&b,M=b>>>13,S=0|i[4],I=8191&S,P=S>>>13,E=0|i[5],B=8191&E,N=E>>>13,U=0|i[6],A=8191&U,T=U>>>13,k=0|i[7],D=8191&k,K=k>>>13,x=0|i[8],R=8191&x,O=x>>>13,C=0|i[9],_=8191&C,F=C>>>13,L=0|o[0],j=8191&L,q=L>>>13,V=0|o[1],H=8191&V,G=V>>>13,J=0|o[2],W=8191&J,Y=J>>>13,z=0|o[3],Z=8191&z,X=z>>>13,Q=0|o[4],$=8191&Q,ee=Q>>>13,te=0|o[5],se=8191&te,ae=te>>>13,re=0|o[6],ne=8191&re,ie=re>>>13,oe=0|o[7],ce=8191&oe,ue=oe>>>13,de=0|o[8],he=8191&de,le=de>>>13,fe=0|o[9],me=8191&fe,pe=fe>>>13;s.negative=e.negative^t.negative,s.length=19;var we=(u+(a=Math.imul(h,j))|0)+((8191&(r=(r=Math.imul(h,q))+Math.imul(l,j)|0))<<13)|0;u=((n=Math.imul(l,q))+(r>>>13)|0)+(we>>>26)|0,we&=67108863,a=Math.imul(m,j),r=(r=Math.imul(m,q))+Math.imul(p,j)|0,n=Math.imul(p,q);var ge=(u+(a=a+Math.imul(h,H)|0)|0)+((8191&(r=(r=r+Math.imul(h,G)|0)+Math.imul(l,H)|0))<<13)|0;u=((n=n+Math.imul(l,G)|0)+(r>>>13)|0)+(ge>>>26)|0,ge&=67108863,a=Math.imul(g,j),r=(r=Math.imul(g,q))+Math.imul(y,j)|0,n=Math.imul(y,q),a=a+Math.imul(m,H)|0,r=(r=r+Math.imul(m,G)|0)+Math.imul(p,H)|0,n=n+Math.imul(p,G)|0;var ye=(u+(a=a+Math.imul(h,W)|0)|0)+((8191&(r=(r=r+Math.imul(h,Y)|0)+Math.imul(l,W)|0))<<13)|0;u=((n=n+Math.imul(l,Y)|0)+(r>>>13)|0)+(ye>>>26)|0,ye&=67108863,a=Math.imul(v,j),r=(r=Math.imul(v,q))+Math.imul(M,j)|0,n=Math.imul(M,q),a=a+Math.imul(g,H)|0,r=(r=r+Math.imul(g,G)|0)+Math.imul(y,H)|0,n=n+Math.imul(y,G)|0,a=a+Math.imul(m,W)|0,r=(r=r+Math.imul(m,Y)|0)+Math.imul(p,W)|0,n=n+Math.imul(p,Y)|0;var be=(u+(a=a+Math.imul(h,Z)|0)|0)+((8191&(r=(r=r+Math.imul(h,X)|0)+Math.imul(l,Z)|0))<<13)|0;u=((n=n+Math.imul(l,X)|0)+(r>>>13)|0)+(be>>>26)|0,be&=67108863,a=Math.imul(I,j),r=(r=Math.imul(I,q))+Math.imul(P,j)|0,n=Math.imul(P,q),a=a+Math.imul(v,H)|0,r=(r=r+Math.imul(v,G)|0)+Math.imul(M,H)|0,n=n+Math.imul(M,G)|0,a=a+Math.imul(g,W)|0,r=(r=r+Math.imul(g,Y)|0)+Math.imul(y,W)|0,n=n+Math.imul(y,Y)|0,a=a+Math.imul(m,Z)|0,r=(r=r+Math.imul(m,X)|0)+Math.imul(p,Z)|0,n=n+Math.imul(p,X)|0;var ve=(u+(a=a+Math.imul(h,$)|0)|0)+((8191&(r=(r=r+Math.imul(h,ee)|0)+Math.imul(l,$)|0))<<13)|0;u=((n=n+Math.imul(l,ee)|0)+(r>>>13)|0)+(ve>>>26)|0,ve&=67108863,a=Math.imul(B,j),r=(r=Math.imul(B,q))+Math.imul(N,j)|0,n=Math.imul(N,q),a=a+Math.imul(I,H)|0,r=(r=r+Math.imul(I,G)|0)+Math.imul(P,H)|0,n=n+Math.imul(P,G)|0,a=a+Math.imul(v,W)|0,r=(r=r+Math.imul(v,Y)|0)+Math.imul(M,W)|0,n=n+Math.imul(M,Y)|0,a=a+Math.imul(g,Z)|0,r=(r=r+Math.imul(g,X)|0)+Math.imul(y,Z)|0,n=n+Math.imul(y,X)|0,a=a+Math.imul(m,$)|0,r=(r=r+Math.imul(m,ee)|0)+Math.imul(p,$)|0,n=n+Math.imul(p,ee)|0;var Me=(u+(a=a+Math.imul(h,se)|0)|0)+((8191&(r=(r=r+Math.imul(h,ae)|0)+Math.imul(l,se)|0))<<13)|0;u=((n=n+Math.imul(l,ae)|0)+(r>>>13)|0)+(Me>>>26)|0,Me&=67108863,a=Math.imul(A,j),r=(r=Math.imul(A,q))+Math.imul(T,j)|0,n=Math.imul(T,q),a=a+Math.imul(B,H)|0,r=(r=r+Math.imul(B,G)|0)+Math.imul(N,H)|0,n=n+Math.imul(N,G)|0,a=a+Math.imul(I,W)|0,r=(r=r+Math.imul(I,Y)|0)+Math.imul(P,W)|0,n=n+Math.imul(P,Y)|0,a=a+Math.imul(v,Z)|0,r=(r=r+Math.imul(v,X)|0)+Math.imul(M,Z)|0,n=n+Math.imul(M,X)|0,a=a+Math.imul(g,$)|0,r=(r=r+Math.imul(g,ee)|0)+Math.imul(y,$)|0,n=n+Math.imul(y,ee)|0,a=a+Math.imul(m,se)|0,r=(r=r+Math.imul(m,ae)|0)+Math.imul(p,se)|0,n=n+Math.imul(p,ae)|0;var Se=(u+(a=a+Math.imul(h,ne)|0)|0)+((8191&(r=(r=r+Math.imul(h,ie)|0)+Math.imul(l,ne)|0))<<13)|0;u=((n=n+Math.imul(l,ie)|0)+(r>>>13)|0)+(Se>>>26)|0,Se&=67108863,a=Math.imul(D,j),r=(r=Math.imul(D,q))+Math.imul(K,j)|0,n=Math.imul(K,q),a=a+Math.imul(A,H)|0,r=(r=r+Math.imul(A,G)|0)+Math.imul(T,H)|0,n=n+Math.imul(T,G)|0,a=a+Math.imul(B,W)|0,r=(r=r+Math.imul(B,Y)|0)+Math.imul(N,W)|0,n=n+Math.imul(N,Y)|0,a=a+Math.imul(I,Z)|0,r=(r=r+Math.imul(I,X)|0)+Math.imul(P,Z)|0,n=n+Math.imul(P,X)|0,a=a+Math.imul(v,$)|0,r=(r=r+Math.imul(v,ee)|0)+Math.imul(M,$)|0,n=n+Math.imul(M,ee)|0,a=a+Math.imul(g,se)|0,r=(r=r+Math.imul(g,ae)|0)+Math.imul(y,se)|0,n=n+Math.imul(y,ae)|0,a=a+Math.imul(m,ne)|0,r=(r=r+Math.imul(m,ie)|0)+Math.imul(p,ne)|0,n=n+Math.imul(p,ie)|0;var Ie=(u+(a=a+Math.imul(h,ce)|0)|0)+((8191&(r=(r=r+Math.imul(h,ue)|0)+Math.imul(l,ce)|0))<<13)|0;u=((n=n+Math.imul(l,ue)|0)+(r>>>13)|0)+(Ie>>>26)|0,Ie&=67108863,a=Math.imul(R,j),r=(r=Math.imul(R,q))+Math.imul(O,j)|0,n=Math.imul(O,q),a=a+Math.imul(D,H)|0,r=(r=r+Math.imul(D,G)|0)+Math.imul(K,H)|0,n=n+Math.imul(K,G)|0,a=a+Math.imul(A,W)|0,r=(r=r+Math.imul(A,Y)|0)+Math.imul(T,W)|0,n=n+Math.imul(T,Y)|0,a=a+Math.imul(B,Z)|0,r=(r=r+Math.imul(B,X)|0)+Math.imul(N,Z)|0,n=n+Math.imul(N,X)|0,a=a+Math.imul(I,$)|0,r=(r=r+Math.imul(I,ee)|0)+Math.imul(P,$)|0,n=n+Math.imul(P,ee)|0,a=a+Math.imul(v,se)|0,r=(r=r+Math.imul(v,ae)|0)+Math.imul(M,se)|0,n=n+Math.imul(M,ae)|0,a=a+Math.imul(g,ne)|0,r=(r=r+Math.imul(g,ie)|0)+Math.imul(y,ne)|0,n=n+Math.imul(y,ie)|0,a=a+Math.imul(m,ce)|0,r=(r=r+Math.imul(m,ue)|0)+Math.imul(p,ce)|0,n=n+Math.imul(p,ue)|0;var Pe=(u+(a=a+Math.imul(h,he)|0)|0)+((8191&(r=(r=r+Math.imul(h,le)|0)+Math.imul(l,he)|0))<<13)|0;u=((n=n+Math.imul(l,le)|0)+(r>>>13)|0)+(Pe>>>26)|0,Pe&=67108863,a=Math.imul(_,j),r=(r=Math.imul(_,q))+Math.imul(F,j)|0,n=Math.imul(F,q),a=a+Math.imul(R,H)|0,r=(r=r+Math.imul(R,G)|0)+Math.imul(O,H)|0,n=n+Math.imul(O,G)|0,a=a+Math.imul(D,W)|0,r=(r=r+Math.imul(D,Y)|0)+Math.imul(K,W)|0,n=n+Math.imul(K,Y)|0,a=a+Math.imul(A,Z)|0,r=(r=r+Math.imul(A,X)|0)+Math.imul(T,Z)|0,n=n+Math.imul(T,X)|0,a=a+Math.imul(B,$)|0,r=(r=r+Math.imul(B,ee)|0)+Math.imul(N,$)|0,n=n+Math.imul(N,ee)|0,a=a+Math.imul(I,se)|0,r=(r=r+Math.imul(I,ae)|0)+Math.imul(P,se)|0,n=n+Math.imul(P,ae)|0,a=a+Math.imul(v,ne)|0,r=(r=r+Math.imul(v,ie)|0)+Math.imul(M,ne)|0,n=n+Math.imul(M,ie)|0,a=a+Math.imul(g,ce)|0,r=(r=r+Math.imul(g,ue)|0)+Math.imul(y,ce)|0,n=n+Math.imul(y,ue)|0,a=a+Math.imul(m,he)|0,r=(r=r+Math.imul(m,le)|0)+Math.imul(p,he)|0,n=n+Math.imul(p,le)|0;var Ee=(u+(a=a+Math.imul(h,me)|0)|0)+((8191&(r=(r=r+Math.imul(h,pe)|0)+Math.imul(l,me)|0))<<13)|0;u=((n=n+Math.imul(l,pe)|0)+(r>>>13)|0)+(Ee>>>26)|0,Ee&=67108863,a=Math.imul(_,H),r=(r=Math.imul(_,G))+Math.imul(F,H)|0,n=Math.imul(F,G),a=a+Math.imul(R,W)|0,r=(r=r+Math.imul(R,Y)|0)+Math.imul(O,W)|0,n=n+Math.imul(O,Y)|0,a=a+Math.imul(D,Z)|0,r=(r=r+Math.imul(D,X)|0)+Math.imul(K,Z)|0,n=n+Math.imul(K,X)|0,a=a+Math.imul(A,$)|0,r=(r=r+Math.imul(A,ee)|0)+Math.imul(T,$)|0,n=n+Math.imul(T,ee)|0,a=a+Math.imul(B,se)|0,r=(r=r+Math.imul(B,ae)|0)+Math.imul(N,se)|0,n=n+Math.imul(N,ae)|0,a=a+Math.imul(I,ne)|0,r=(r=r+Math.imul(I,ie)|0)+Math.imul(P,ne)|0,n=n+Math.imul(P,ie)|0,a=a+Math.imul(v,ce)|0,r=(r=r+Math.imul(v,ue)|0)+Math.imul(M,ce)|0,n=n+Math.imul(M,ue)|0,a=a+Math.imul(g,he)|0,r=(r=r+Math.imul(g,le)|0)+Math.imul(y,he)|0,n=n+Math.imul(y,le)|0;var Be=(u+(a=a+Math.imul(m,me)|0)|0)+((8191&(r=(r=r+Math.imul(m,pe)|0)+Math.imul(p,me)|0))<<13)|0;u=((n=n+Math.imul(p,pe)|0)+(r>>>13)|0)+(Be>>>26)|0,Be&=67108863,a=Math.imul(_,W),r=(r=Math.imul(_,Y))+Math.imul(F,W)|0,n=Math.imul(F,Y),a=a+Math.imul(R,Z)|0,r=(r=r+Math.imul(R,X)|0)+Math.imul(O,Z)|0,n=n+Math.imul(O,X)|0,a=a+Math.imul(D,$)|0,r=(r=r+Math.imul(D,ee)|0)+Math.imul(K,$)|0,n=n+Math.imul(K,ee)|0,a=a+Math.imul(A,se)|0,r=(r=r+Math.imul(A,ae)|0)+Math.imul(T,se)|0,n=n+Math.imul(T,ae)|0,a=a+Math.imul(B,ne)|0,r=(r=r+Math.imul(B,ie)|0)+Math.imul(N,ne)|0,n=n+Math.imul(N,ie)|0,a=a+Math.imul(I,ce)|0,r=(r=r+Math.imul(I,ue)|0)+Math.imul(P,ce)|0,n=n+Math.imul(P,ue)|0,a=a+Math.imul(v,he)|0,r=(r=r+Math.imul(v,le)|0)+Math.imul(M,he)|0,n=n+Math.imul(M,le)|0;var Ne=(u+(a=a+Math.imul(g,me)|0)|0)+((8191&(r=(r=r+Math.imul(g,pe)|0)+Math.imul(y,me)|0))<<13)|0;u=((n=n+Math.imul(y,pe)|0)+(r>>>13)|0)+(Ne>>>26)|0,Ne&=67108863,a=Math.imul(_,Z),r=(r=Math.imul(_,X))+Math.imul(F,Z)|0,n=Math.imul(F,X),a=a+Math.imul(R,$)|0,r=(r=r+Math.imul(R,ee)|0)+Math.imul(O,$)|0,n=n+Math.imul(O,ee)|0,a=a+Math.imul(D,se)|0,r=(r=r+Math.imul(D,ae)|0)+Math.imul(K,se)|0,n=n+Math.imul(K,ae)|0,a=a+Math.imul(A,ne)|0,r=(r=r+Math.imul(A,ie)|0)+Math.imul(T,ne)|0,n=n+Math.imul(T,ie)|0,a=a+Math.imul(B,ce)|0,r=(r=r+Math.imul(B,ue)|0)+Math.imul(N,ce)|0,n=n+Math.imul(N,ue)|0,a=a+Math.imul(I,he)|0,r=(r=r+Math.imul(I,le)|0)+Math.imul(P,he)|0,n=n+Math.imul(P,le)|0;var Ue=(u+(a=a+Math.imul(v,me)|0)|0)+((8191&(r=(r=r+Math.imul(v,pe)|0)+Math.imul(M,me)|0))<<13)|0;u=((n=n+Math.imul(M,pe)|0)+(r>>>13)|0)+(Ue>>>26)|0,Ue&=67108863,a=Math.imul(_,$),r=(r=Math.imul(_,ee))+Math.imul(F,$)|0,n=Math.imul(F,ee),a=a+Math.imul(R,se)|0,r=(r=r+Math.imul(R,ae)|0)+Math.imul(O,se)|0,n=n+Math.imul(O,ae)|0,a=a+Math.imul(D,ne)|0,r=(r=r+Math.imul(D,ie)|0)+Math.imul(K,ne)|0,n=n+Math.imul(K,ie)|0,a=a+Math.imul(A,ce)|0,r=(r=r+Math.imul(A,ue)|0)+Math.imul(T,ce)|0,n=n+Math.imul(T,ue)|0,a=a+Math.imul(B,he)|0,r=(r=r+Math.imul(B,le)|0)+Math.imul(N,he)|0,n=n+Math.imul(N,le)|0;var Ae=(u+(a=a+Math.imul(I,me)|0)|0)+((8191&(r=(r=r+Math.imul(I,pe)|0)+Math.imul(P,me)|0))<<13)|0;u=((n=n+Math.imul(P,pe)|0)+(r>>>13)|0)+(Ae>>>26)|0,Ae&=67108863,a=Math.imul(_,se),r=(r=Math.imul(_,ae))+Math.imul(F,se)|0,n=Math.imul(F,ae),a=a+Math.imul(R,ne)|0,r=(r=r+Math.imul(R,ie)|0)+Math.imul(O,ne)|0,n=n+Math.imul(O,ie)|0,a=a+Math.imul(D,ce)|0,r=(r=r+Math.imul(D,ue)|0)+Math.imul(K,ce)|0,n=n+Math.imul(K,ue)|0,a=a+Math.imul(A,he)|0,r=(r=r+Math.imul(A,le)|0)+Math.imul(T,he)|0,n=n+Math.imul(T,le)|0;var Te=(u+(a=a+Math.imul(B,me)|0)|0)+((8191&(r=(r=r+Math.imul(B,pe)|0)+Math.imul(N,me)|0))<<13)|0;u=((n=n+Math.imul(N,pe)|0)+(r>>>13)|0)+(Te>>>26)|0,Te&=67108863,a=Math.imul(_,ne),r=(r=Math.imul(_,ie))+Math.imul(F,ne)|0,n=Math.imul(F,ie),a=a+Math.imul(R,ce)|0,r=(r=r+Math.imul(R,ue)|0)+Math.imul(O,ce)|0,n=n+Math.imul(O,ue)|0,a=a+Math.imul(D,he)|0,r=(r=r+Math.imul(D,le)|0)+Math.imul(K,he)|0,n=n+Math.imul(K,le)|0;var ke=(u+(a=a+Math.imul(A,me)|0)|0)+((8191&(r=(r=r+Math.imul(A,pe)|0)+Math.imul(T,me)|0))<<13)|0;u=((n=n+Math.imul(T,pe)|0)+(r>>>13)|0)+(ke>>>26)|0,ke&=67108863,a=Math.imul(_,ce),r=(r=Math.imul(_,ue))+Math.imul(F,ce)|0,n=Math.imul(F,ue),a=a+Math.imul(R,he)|0,r=(r=r+Math.imul(R,le)|0)+Math.imul(O,he)|0,n=n+Math.imul(O,le)|0;var De=(u+(a=a+Math.imul(D,me)|0)|0)+((8191&(r=(r=r+Math.imul(D,pe)|0)+Math.imul(K,me)|0))<<13)|0;u=((n=n+Math.imul(K,pe)|0)+(r>>>13)|0)+(De>>>26)|0,De&=67108863,a=Math.imul(_,he),r=(r=Math.imul(_,le))+Math.imul(F,he)|0,n=Math.imul(F,le);var Ke=(u+(a=a+Math.imul(R,me)|0)|0)+((8191&(r=(r=r+Math.imul(R,pe)|0)+Math.imul(O,me)|0))<<13)|0;u=((n=n+Math.imul(O,pe)|0)+(r>>>13)|0)+(Ke>>>26)|0,Ke&=67108863;var xe=(u+(a=Math.imul(_,me))|0)+((8191&(r=(r=Math.imul(_,pe))+Math.imul(F,me)|0))<<13)|0;return u=((n=Math.imul(F,pe))+(r>>>13)|0)+(xe>>>26)|0,xe&=67108863,c[0]=we,c[1]=ge,c[2]=ye,c[3]=be,c[4]=ve,c[5]=Me,c[6]=Se,c[7]=Ie,c[8]=Pe,c[9]=Ee,c[10]=Be,c[11]=Ne,c[12]=Ue,c[13]=Ae,c[14]=Te,c[15]=ke,c[16]=De,c[17]=Ke,c[18]=xe,0!==u&&(c[19]=u,s.length++),s};function m(e,t,s){return(new p).mulp(e,t,s)}function p(e,t){this.x=e,this.y=t}Math.imul||(f=l),n.prototype.mulTo=function(e,t){var s=this.length+e.length;return 10===this.length&&10===e.length?f(this,e,t):s<63?l(this,e,t):s<1024?function(e,t,s){s.negative=t.negative^e.negative,s.length=e.length+t.length;for(var a=0,r=0,n=0;n>>26)|0)>>>26,i&=67108863}s.words[n]=o,a=i,i=r}return 0!==a?s.words[n]=a:s.length--,s.strip()}(this,e,t):m(this,e,t)},p.prototype.makeRBT=function(e){for(var t=new Array(e),s=n.prototype._countBits(e)-1,a=0;a>=1;return a},p.prototype.permute=function(e,t,s,a,r,n){for(var i=0;i>>=1)r++;return 1<>>=13,s[2*i+1]=8191&n,n>>>=13;for(i=2*t;i>=26,t+=r/67108864|0,t+=n>>>26,this.words[s]=67108863&n}return 0!==t&&(this.words[s]=t,this.length++),this},n.prototype.muln=function(e){return this.clone().imuln(e)},n.prototype.sqr=function(){return this.mul(this)},n.prototype.isqr=function(){return this.imul(this.clone())},n.prototype.pow=function(e){var t=function(e){for(var t=new Array(e.bitLength()),s=0;s>>r}return t}(e);if(0===t.length)return new n(1);for(var s=this,a=0;a=0);var t,s=e%26,r=(e-s)/26,n=67108863>>>26-s<<26-s;if(0!==s){var i=0;for(t=0;t>>26-s}i&&(this.words[t]=i,this.length++)}if(0!==r){for(t=this.length-1;t>=0;t--)this.words[t+r]=this.words[t];for(t=0;t=0),r=t?(t-t%26)/26:0;var n=e%26,i=Math.min((e-n)/26,this.length),o=67108863^67108863>>>n<i)for(this.length-=i,u=0;u=0&&(0!==d||u>=r);u--){var h=0|this.words[u];this.words[u]=d<<26-n|h>>>n,d=h&o}return c&&0!==d&&(c.words[c.length++]=d),0===this.length&&(this.words[0]=0,this.length=1),this.strip()},n.prototype.ishrn=function(e,t,s){return a(0===this.negative),this.iushrn(e,t,s)},n.prototype.shln=function(e){return this.clone().ishln(e)},n.prototype.ushln=function(e){return this.clone().iushln(e)},n.prototype.shrn=function(e){return this.clone().ishrn(e)},n.prototype.ushrn=function(e){return this.clone().iushrn(e)},n.prototype.testn=function(e){a("number"==typeof e&&e>=0);var t=e%26,s=(e-t)/26,r=1<=0);var t=e%26,s=(e-t)/26;if(a(0===this.negative,"imaskn works only with positive numbers"),this.length<=s)return this;if(0!==t&&s++,this.length=Math.min(s,this.length),0!==t){var r=67108863^67108863>>>t<=67108864;t++)this.words[t]-=67108864,t===this.length-1?this.words[t+1]=1:this.words[t+1]++;return this.length=Math.max(this.length,t+1),this},n.prototype.isubn=function(e){if(a("number"==typeof e),a(e<67108864),e<0)return this.iaddn(-e);if(0!==this.negative)return this.negative=0,this.iaddn(e),this.negative=1,this;if(this.words[0]-=e,1===this.length&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var t=0;t>26)-(c/67108864|0),this.words[r+s]=67108863&n}for(;r>26,this.words[r+s]=67108863&n;if(0===o)return this.strip();for(a(-1===o),o=0,r=0;r>26,this.words[r]=67108863&n;return this.negative=1,this.strip()},n.prototype._wordDiv=function(e,t){var s=(this.length,e.length),a=this.clone(),r=e,i=0|r.words[r.length-1];0!==(s=26-this._countBits(i))&&(r=r.ushln(s),a.iushln(s),i=0|r.words[r.length-1]);var o,c=a.length-r.length;if("mod"!==t){(o=new n(null)).length=c+1,o.words=new Array(o.length);for(var u=0;u=0;h--){var l=67108864*(0|a.words[r.length+h])+(0|a.words[r.length+h-1]);for(l=Math.min(l/i|0,67108863),a._ishlnsubmul(r,l,h);0!==a.negative;)l--,a.negative=0,a._ishlnsubmul(r,1,h),a.isZero()||(a.negative^=1);o&&(o.words[h]=l)}return o&&o.strip(),a.strip(),"div"!==t&&0!==s&&a.iushrn(s),{div:o||null,mod:a}},n.prototype.divmod=function(e,t,s){return a(!e.isZero()),this.isZero()?{div:new n(0),mod:new n(0)}:0!==this.negative&&0===e.negative?(o=this.neg().divmod(e,t),"mod"!==t&&(r=o.div.neg()),"div"!==t&&(i=o.mod.neg(),s&&0!==i.negative&&i.iadd(e)),{div:r,mod:i}):0===this.negative&&0!==e.negative?(o=this.divmod(e.neg(),t),"mod"!==t&&(r=o.div.neg()),{div:r,mod:o.mod}):0!=(this.negative&e.negative)?(o=this.neg().divmod(e.neg(),t),"div"!==t&&(i=o.mod.neg(),s&&0!==i.negative&&i.isub(e)),{div:o.div,mod:i}):e.length>this.length||this.cmp(e)<0?{div:new n(0),mod:this}:1===e.length?"div"===t?{div:this.divn(e.words[0]),mod:null}:"mod"===t?{div:null,mod:new n(this.modn(e.words[0]))}:{div:this.divn(e.words[0]),mod:new n(this.modn(e.words[0]))}:this._wordDiv(e,t);var r,i,o},n.prototype.div=function(e){return this.divmod(e,"div",!1).div},n.prototype.mod=function(e){return this.divmod(e,"mod",!1).mod},n.prototype.umod=function(e){return this.divmod(e,"mod",!0).mod},n.prototype.divRound=function(e){var t=this.divmod(e);if(t.mod.isZero())return t.div;var s=0!==t.div.negative?t.mod.isub(e):t.mod,a=e.ushrn(1),r=e.andln(1),n=s.cmp(a);return n<0||1===r&&0===n?t.div:0!==t.div.negative?t.div.isubn(1):t.div.iaddn(1)},n.prototype.modn=function(e){a(e<=67108863);for(var t=(1<<26)%e,s=0,r=this.length-1;r>=0;r--)s=(t*s+(0|this.words[r]))%e;return s},n.prototype.idivn=function(e){a(e<=67108863);for(var t=0,s=this.length-1;s>=0;s--){var r=(0|this.words[s])+67108864*t;this.words[s]=r/e|0,t=r%e}return this.strip()},n.prototype.divn=function(e){return this.clone().idivn(e)},n.prototype.egcd=function(e){a(0===e.negative),a(!e.isZero());var t=this,s=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r=new n(1),i=new n(0),o=new n(0),c=new n(1),u=0;t.isEven()&&s.isEven();)t.iushrn(1),s.iushrn(1),++u;for(var d=s.clone(),h=t.clone();!t.isZero();){for(var l=0,f=1;0==(t.words[0]&f)&&l<26;++l,f<<=1);if(l>0)for(t.iushrn(l);l-- >0;)(r.isOdd()||i.isOdd())&&(r.iadd(d),i.isub(h)),r.iushrn(1),i.iushrn(1);for(var m=0,p=1;0==(s.words[0]&p)&&m<26;++m,p<<=1);if(m>0)for(s.iushrn(m);m-- >0;)(o.isOdd()||c.isOdd())&&(o.iadd(d),c.isub(h)),o.iushrn(1),c.iushrn(1);t.cmp(s)>=0?(t.isub(s),r.isub(o),i.isub(c)):(s.isub(t),o.isub(r),c.isub(i))}return{a:o,b:c,gcd:s.iushln(u)}},n.prototype._invmp=function(e){a(0===e.negative),a(!e.isZero());var t=this,s=e.clone();t=0!==t.negative?t.umod(e):t.clone();for(var r,i=new n(1),o=new n(0),c=s.clone();t.cmpn(1)>0&&s.cmpn(1)>0;){for(var u=0,d=1;0==(t.words[0]&d)&&u<26;++u,d<<=1);if(u>0)for(t.iushrn(u);u-- >0;)i.isOdd()&&i.iadd(c),i.iushrn(1);for(var h=0,l=1;0==(s.words[0]&l)&&h<26;++h,l<<=1);if(h>0)for(s.iushrn(h);h-- >0;)o.isOdd()&&o.iadd(c),o.iushrn(1);t.cmp(s)>=0?(t.isub(s),i.isub(o)):(s.isub(t),o.isub(i))}return(r=0===t.cmpn(1)?i:o).cmpn(0)<0&&r.iadd(e),r},n.prototype.gcd=function(e){if(this.isZero())return e.abs();if(e.isZero())return this.abs();var t=this.clone(),s=e.clone();t.negative=0,s.negative=0;for(var a=0;t.isEven()&&s.isEven();a++)t.iushrn(1),s.iushrn(1);for(;;){for(;t.isEven();)t.iushrn(1);for(;s.isEven();)s.iushrn(1);var r=t.cmp(s);if(r<0){var n=t;t=s,s=n}else if(0===r||0===s.cmpn(1))break;t.isub(s)}return s.iushln(a)},n.prototype.invm=function(e){return this.egcd(e).a.umod(e)},n.prototype.isEven=function(){return 0==(1&this.words[0])},n.prototype.isOdd=function(){return 1==(1&this.words[0])},n.prototype.andln=function(e){return this.words[0]&e},n.prototype.bincn=function(e){a("number"==typeof e);var t=e%26,s=(e-t)/26,r=1<>>26,o&=67108863,this.words[i]=o}return 0!==n&&(this.words[i]=n,this.length++),this},n.prototype.isZero=function(){return 1===this.length&&0===this.words[0]},n.prototype.cmpn=function(e){var t,s=e<0;if(0!==this.negative&&!s)return-1;if(0===this.negative&&s)return 1;if(this.strip(),this.length>1)t=1;else{s&&(e=-e),a(e<=67108863,"Number is too big");var r=0|this.words[0];t=r===e?0:re.length)return 1;if(this.length=0;s--){var a=0|this.words[s],r=0|e.words[s];if(a!==r){ar&&(t=1);break}}return t},n.prototype.gtn=function(e){return 1===this.cmpn(e)},n.prototype.gt=function(e){return 1===this.cmp(e)},n.prototype.gten=function(e){return this.cmpn(e)>=0},n.prototype.gte=function(e){return this.cmp(e)>=0},n.prototype.ltn=function(e){return-1===this.cmpn(e)},n.prototype.lt=function(e){return-1===this.cmp(e)},n.prototype.lten=function(e){return this.cmpn(e)<=0},n.prototype.lte=function(e){return this.cmp(e)<=0},n.prototype.eqn=function(e){return 0===this.cmpn(e)},n.prototype.eq=function(e){return 0===this.cmp(e)},n.red=function(e){return new S(e)},n.prototype.toRed=function(e){return a(!this.red,"Already a number in reduction context"),a(0===this.negative,"red works only with positives"),e.convertTo(this)._forceRed(e)},n.prototype.fromRed=function(){return a(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},n.prototype._forceRed=function(e){return this.red=e,this},n.prototype.forceRed=function(e){return a(!this.red,"Already a number in reduction context"),this._forceRed(e)},n.prototype.redAdd=function(e){return a(this.red,"redAdd works only with red numbers"),this.red.add(this,e)},n.prototype.redIAdd=function(e){return a(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,e)},n.prototype.redSub=function(e){return a(this.red,"redSub works only with red numbers"),this.red.sub(this,e)},n.prototype.redISub=function(e){return a(this.red,"redISub works only with red numbers"),this.red.isub(this,e)},n.prototype.redShl=function(e){return a(this.red,"redShl works only with red numbers"),this.red.shl(this,e)},n.prototype.redMul=function(e){return a(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.mul(this,e)},n.prototype.redIMul=function(e){return a(this.red,"redMul works only with red numbers"),this.red._verify2(this,e),this.red.imul(this,e)},n.prototype.redSqr=function(){return a(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},n.prototype.redISqr=function(){return a(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},n.prototype.redSqrt=function(){return a(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},n.prototype.redInvm=function(){return a(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},n.prototype.redNeg=function(){return a(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},n.prototype.redPow=function(e){return a(this.red&&!e.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,e)};var w={k256:null,p224:null,p192:null,p25519:null};function g(e,t){this.name=e,this.p=new n(t,16),this.n=this.p.bitLength(),this.k=new n(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}function y(){g.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function b(){g.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function v(){g.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function M(){g.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function S(e){if("string"==typeof e){var t=n._prime(e);this.m=t.p,this.prime=t}else a(e.gtn(1),"modulus must be greater than 1"),this.m=e,this.prime=null}function I(e){S.call(this,e),this.shift=this.m.bitLength(),this.shift%26!=0&&(this.shift+=26-this.shift%26),this.r=new n(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}g.prototype._tmp=function(){var e=new n(null);return e.words=new Array(Math.ceil(this.n/13)),e},g.prototype.ireduce=function(e){var t,s=e;do{this.split(s,this.tmp),t=(s=(s=this.imulK(s)).iadd(this.tmp)).bitLength()}while(t>this.n);var a=t0?s.isub(this.p):void 0!==s.strip?s.strip():s._strip(),s},g.prototype.split=function(e,t){e.iushrn(this.n,0,t)},g.prototype.imulK=function(e){return e.imul(this.k)},r(y,g),y.prototype.split=function(e,t){for(var s=Math.min(e.length,9),a=0;a>>22,r=n}r>>>=22,e.words[a-10]=r,0===r&&e.length>10?e.length-=10:e.length-=9},y.prototype.imulK=function(e){e.words[e.length]=0,e.words[e.length+1]=0,e.length+=2;for(var t=0,s=0;s>>=26,e.words[s]=r,t=a}return 0!==t&&(e.words[e.length++]=t),e},n._prime=function(e){if(w[e])return w[e];var t;if("k256"===e)t=new y;else if("p224"===e)t=new b;else if("p192"===e)t=new v;else{if("p25519"!==e)throw new Error("Unknown prime "+e);t=new M}return w[e]=t,t},S.prototype._verify1=function(e){a(0===e.negative,"red works only with positives"),a(e.red,"red works only with red numbers")},S.prototype._verify2=function(e,t){a(0==(e.negative|t.negative),"red works only with positives"),a(e.red&&e.red===t.red,"red works only with red numbers")},S.prototype.imod=function(e){return this.prime?this.prime.ireduce(e)._forceRed(this):e.umod(this.m)._forceRed(this)},S.prototype.neg=function(e){return e.isZero()?e.clone():this.m.sub(e)._forceRed(this)},S.prototype.add=function(e,t){this._verify2(e,t);var s=e.add(t);return s.cmp(this.m)>=0&&s.isub(this.m),s._forceRed(this)},S.prototype.iadd=function(e,t){this._verify2(e,t);var s=e.iadd(t);return s.cmp(this.m)>=0&&s.isub(this.m),s},S.prototype.sub=function(e,t){this._verify2(e,t);var s=e.sub(t);return s.cmpn(0)<0&&s.iadd(this.m),s._forceRed(this)},S.prototype.isub=function(e,t){this._verify2(e,t);var s=e.isub(t);return s.cmpn(0)<0&&s.iadd(this.m),s},S.prototype.shl=function(e,t){return this._verify1(e),this.imod(e.ushln(t))},S.prototype.imul=function(e,t){return this._verify2(e,t),this.imod(e.imul(t))},S.prototype.mul=function(e,t){return this._verify2(e,t),this.imod(e.mul(t))},S.prototype.isqr=function(e){return this.imul(e,e.clone())},S.prototype.sqr=function(e){return this.mul(e,e)},S.prototype.sqrt=function(e){if(e.isZero())return e.clone();var t=this.m.andln(3);if(a(t%2==1),3===t){var s=this.m.add(new n(1)).iushrn(2);return this.pow(e,s)}for(var r=this.m.subn(1),i=0;!r.isZero()&&0===r.andln(1);)i++,r.iushrn(1);a(!r.isZero());var o=new n(1).toRed(this),c=o.redNeg(),u=this.m.subn(1).iushrn(1),d=this.m.bitLength();for(d=new n(2*d*d).toRed(this);0!==this.pow(d,u).cmp(c);)d.redIAdd(c);for(var h=this.pow(d,r),l=this.pow(e,r.addn(1).iushrn(1)),f=this.pow(e,r),m=i;0!==f.cmp(o);){for(var p=f,w=0;0!==p.cmp(o);w++)p=p.redSqr();a(w=0;a--){for(var u=t.words[a],d=c-1;d>=0;d--){var h=u>>d&1;r!==s[0]&&(r=this.sqr(r)),0!==h||0!==i?(i<<=1,i|=h,(4===++o||0===a&&0===d)&&(r=this.mul(r,s[i]),o=0,i=0)):o=0}c=26}return r},S.prototype.convertTo=function(e){var t=e.umod(this.m);return t===e?t.clone():t},S.prototype.convertFrom=function(e){var t=e.clone();return t.red=null,t},n.mont=function(e){return new I(e)},r(I,S),I.prototype.convertTo=function(e){return this.imod(e.ushln(this.shift))},I.prototype.convertFrom=function(e){var t=this.imod(e.mul(this.rinv));return t.red=null,t},I.prototype.imul=function(e,t){if(e.isZero()||t.isZero())return e.words[0]=0,e.length=1,e;var s=e.imul(t),a=s.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=s.isub(a).iushrn(this.shift),n=r;return r.cmp(this.m)>=0?n=r.isub(this.m):r.cmpn(0)<0&&(n=r.iadd(this.m)),n._forceRed(this)},I.prototype.mul=function(e,t){if(e.isZero()||t.isZero())return new n(0)._forceRed(this);var s=e.mul(t),a=s.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),r=s.isub(a).iushrn(this.shift),i=r;return r.cmp(this.m)>=0?i=r.isub(this.m):r.cmpn(0)<0&&(i=r.iadd(this.m)),i._forceRed(this)},I.prototype.invm=function(e){return this.imod(e._invmp(this.m).mul(this.r2))._forceRed(this)}}(e,this)}).call(this,s(19)(e))},function(e,t,s){var a=s(7);e.exports=y,y.simpleSieve=w,y.fermatTest=g;var r=s(5),n=new r(24),i=new(s(9)),o=new r(1),c=new r(2),u=new r(5),d=(new r(16),new r(8),new r(10)),h=new r(3),l=(new r(7),new r(11)),f=new r(4),m=(new r(12),null);function p(){if(null!==m)return m;var e=[];e[0]=2;for(var t=1,s=3;s<1048576;s+=2){for(var a=Math.ceil(Math.sqrt(s)),r=0;re;)s.ishrn(1);if(s.isEven()&&s.iadd(o),s.testn(1)||s.iadd(c),t.cmp(c)){if(!t.cmp(u))for(;s.mod(d).cmp(h);)s.iadd(f)}else for(;s.mod(n).cmp(l);)s.iadd(f);if(w(m=s.shrn(1))&&w(s)&&g(m)&&g(s)&&i.test(m)&&i.test(s))return s}}},function(e,t,s){"use strict";(function(t,a){var r=s(18).Buffer,n=t.crypto||t.msCrypto;n&&n.getRandomValues?e.exports=function(e,t){if(e>4294967295)throw new RangeError("requested too many random bytes");var s=r.allocUnsafe(e);if(e>0)if(e>65536)for(var i=0;i1)for(var s=1;s=0);return r},n.prototype._randrange=function(e,t){var s=t.sub(e);return e.add(this._randbelow(s))},n.prototype.test=function(e,t,s){var r=e.bitLength(),n=a.mont(e),i=new a(1).toRed(n);t||(t=Math.max(1,r/48|0));for(var o=e.subn(1),c=0;!o.testn(c);c++);for(var u=e.shrn(c),d=o.toRed(n);t>0;t--){var h=this._randrange(new a(2),o);s&&s(h);var l=h.toRed(n).redPow(u);if(0!==l.cmp(i)&&0!==l.cmp(d)){for(var f=1;f0;t--){var d=this._randrange(new a(2),i),h=e.gcd(d);if(0!==h.cmpn(1))return h;var l=d.toRed(r).redPow(c);if(0!==l.cmp(n)&&0!==l.cmp(u)){for(var f=1;f=64;){let f,m,p,w,g,y=s,b=a,v=r,M=n,S=i,I=o,P=c,E=u;for(m=0;m<16;m++)p=h+4*m,d[m]=(255&e[p])<<24|(255&e[p+1])<<16|(255&e[p+2])<<8|255&e[p+3];for(m=16;m<64;m++)f=d[m-2],w=(f>>>17|f<<15)^(f>>>19|f<<13)^f>>>10,f=d[m-15],g=(f>>>7|f<<25)^(f>>>18|f<<14)^f>>>3,d[m]=(w+d[m-7]|0)+(g+d[m-16]|0)|0;for(m=0;m<64;m++)w=(((S>>>6|S<<26)^(S>>>11|S<<21)^(S>>>25|S<<7))+(S&I^~S&P)|0)+(E+(t[m]+d[m]|0)|0)|0,g=((y>>>2|y<<30)^(y>>>13|y<<19)^(y>>>22|y<<10))+(y&b^y&v^b&v)|0,E=P,P=I,I=S,S=M+w|0,M=v,v=b,b=y,y=w+g|0;s=s+y|0,a=a+b|0,r=r+v|0,n=n+M|0,i=i+S|0,o=o+I|0,c=c+P|0,u=u+E|0,h+=64,l-=64}}h(e);let l,f=e.length%64,m=e.length/536870912|0,p=e.length<<3,w=f<56?56:120,g=e.slice(e.length-f,e.length);for(g.push(128),l=f+1;l>>24&255),g.push(m>>>16&255),g.push(m>>>8&255),g.push(m>>>0&255),g.push(p>>>24&255),g.push(p>>>16&255),g.push(p>>>8&255),g.push(p>>>0&255),h(g),[s>>>24&255,s>>>16&255,s>>>8&255,s>>>0&255,a>>>24&255,a>>>16&255,a>>>8&255,a>>>0&255,r>>>24&255,r>>>16&255,r>>>8&255,r>>>0&255,n>>>24&255,n>>>16&255,n>>>8&255,n>>>0&255,i>>>24&255,i>>>16&255,i>>>8&255,i>>>0&255,o>>>24&255,o>>>16&255,o>>>8&255,o>>>0&255,c>>>24&255,c>>>16&255,c>>>8&255,c>>>0&255,u>>>24&255,u>>>16&255,u>>>8&255,u>>>0&255]}function r(e,t,s){e=e.length<=64?e:a(e);const r=64+t.length+4,n=new Array(r),i=new Array(64);let o,c=[];for(o=0;o<64;o++)n[o]=54;for(o=0;o=r-4;e--){if(n[e]++,n[e]<=255)return;n[e]=0}}for(;s>=32;)u(),c=c.concat(a(i.concat(a(n)))),s-=32;return s>0&&(u(),c=c.concat(a(i.concat(a(n))).slice(0,s))),c}function n(e,t,s,a,r){let n;for(u(e,16*(2*s-1),r,0,16),n=0;n<2*s;n++)c(e,16*n,r,16),o(r,a),u(r,0,e,t+16*n,16);for(n=0;n>>32-t}function o(e,t){u(e,0,t,0,16);for(let e=8;e>0;e-=2)t[4]^=i(t[0]+t[12],7),t[8]^=i(t[4]+t[0],9),t[12]^=i(t[8]+t[4],13),t[0]^=i(t[12]+t[8],18),t[9]^=i(t[5]+t[1],7),t[13]^=i(t[9]+t[5],9),t[1]^=i(t[13]+t[9],13),t[5]^=i(t[1]+t[13],18),t[14]^=i(t[10]+t[6],7),t[2]^=i(t[14]+t[10],9),t[6]^=i(t[2]+t[14],13),t[10]^=i(t[6]+t[2],18),t[3]^=i(t[15]+t[11],7),t[7]^=i(t[3]+t[15],9),t[11]^=i(t[7]+t[3],13),t[15]^=i(t[11]+t[7],18),t[1]^=i(t[0]+t[3],7),t[2]^=i(t[1]+t[0],9),t[3]^=i(t[2]+t[1],13),t[0]^=i(t[3]+t[2],18),t[6]^=i(t[5]+t[4],7),t[7]^=i(t[6]+t[5],9),t[4]^=i(t[7]+t[6],13),t[5]^=i(t[4]+t[7],18),t[11]^=i(t[10]+t[9],7),t[8]^=i(t[11]+t[10],9),t[9]^=i(t[8]+t[11],13),t[10]^=i(t[9]+t[8],18),t[12]^=i(t[15]+t[14],7),t[13]^=i(t[12]+t[15],9),t[14]^=i(t[13]+t[12],13),t[15]^=i(t[14]+t[13],18);for(let s=0;s<16;++s)e[s]+=t[s]}function c(e,t,s,a){for(let r=0;r=256)return!1}return!0}function h(e,t){if("number"!=typeof e||e%1)throw new Error("invalid "+t);return e}function l(e,s,a,i,o,l,f){if(a=h(a,"N"),i=h(i,"r"),o=h(o,"p"),l=h(l,"dkLen"),0===a||0!=(a&a-1))throw new Error("N must be power of 2");if(a>2147483647/128/i)throw new Error("N too large");if(i>2147483647/128/o)throw new Error("r too large");if(!d(e))throw new Error("password must be an array or buffer");if(e=Array.prototype.slice.call(e),!d(s))throw new Error("salt must be an array or buffer");s=Array.prototype.slice.call(s);let m=r(e,s,128*o*i);const p=new Uint32Array(32*o*i);for(let e=0;eA&&(t=A);for(let e=0;eA&&(t=A);for(let e=0;e>0&255),m.push(p[e]>>8&255),m.push(p[e]>>16&255),m.push(p[e]>>24&255);const s=r(e,m,l);return f&&f(null,1,s),s}f&&T(k)};if(!f)for(;;){const e=k();if(null!=e)return e}k()}const f={scrypt:function(e,t,s,a,r,n,i){return new Promise((function(o,c){let u=0;i&&i(0),l(e,t,s,a,r,n,(function(e,t,s){if(e)c(e);else if(s)i&&1!==u&&i(1),o(new Uint8Array(s));else if(i&&t!==u)return u=t,i(t)}))}))},syncScrypt:function(e,t,s,a,r,n){return new Uint8Array(l(e,t,s,a,r,n))}};e.exports=f}()}).call(this,s(25).setImmediate)},function(e,t,s){var a,r=function(){var e,t,s=((t=(e={constructor:function(e,t){this.array=[],this.compare=t||a;for(var s=e.length,r=0;r=i;)if((s=r(a[t=(n+i)/2>>>0],e))<0)i=t+1;else{if(!(s>0)){o=t;break}n=t-1}for(-1===o&&(o=n),o++,n=a.length-1;oo;)a[t]=a[--t];return a[o]=e,this},search:function(e){for(var t,s,a=this.array,r=this.compare,n=a.length-1,i=0;n>=i;)if((s=r(a[t=(n+i)/2>>>0],e))<0)i=t+1;else{if(!(s>0))return t;n=t-1}return-1},remove:function(e){var t=this.search(e);return t>=0&&this.array.splice(t,1),this}}).constructor).prototype=e,t);return s.comparing=function(e,t){return new s(t,(function(t,s){return a(t[e],s[e])}))},s;function a(e,t){return et?1:0}}();e.exports=r,void 0===(a=function(){return r}.call(t,s,t,e))||(e.exports=a)},function(e,t){var s="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(s){var a=new Uint8Array(16);e.exports=function(){return s(a),a}}else{var r=new Array(16);e.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),r[t]=e>>>((3&t)<<3)&255;return r}}},function(e,t){for(var s=[],a=0;a<256;++a)s[a]=(a+256).toString(16).substr(1);e.exports=function(e,t){var a=t||0,r=s;return[r[e[a++]],r[e[a++]],r[e[a++]],r[e[a++]],"-",r[e[a++]],r[e[a++]],"-",r[e[a++]],r[e[a++]],"-",r[e[a++]],r[e[a++]],"-",r[e[a++]],r[e[a++]],r[e[a++]],r[e[a++]],r[e[a++]],r[e[a++]]].join("")}},function(e,t,s){"use strict";t.byteLength=function(e){var t=u(e),s=t[0],a=t[1];return 3*(s+a)/4-a},t.toByteArray=function(e){var t,s,a=u(e),i=a[0],o=a[1],c=new n(function(e,t,s){return 3*(t+s)/4-s}(0,i,o)),d=0,h=o>0?i-4:i;for(s=0;s>16&255,c[d++]=t>>8&255,c[d++]=255&t;2===o&&(t=r[e.charCodeAt(s)]<<2|r[e.charCodeAt(s+1)]>>4,c[d++]=255&t);1===o&&(t=r[e.charCodeAt(s)]<<10|r[e.charCodeAt(s+1)]<<4|r[e.charCodeAt(s+2)]>>2,c[d++]=t>>8&255,c[d++]=255&t);return c},t.fromByteArray=function(e){for(var t,s=e.length,r=s%3,n=[],i=0,o=s-r;io?o:i+16383));1===r?(t=e[s-1],n.push(a[t>>2]+a[t<<4&63]+"==")):2===r&&(t=(e[s-2]<<8)+e[s-1],n.push(a[t>>10]+a[t>>4&63]+a[t<<2&63]+"="));return n.join("")};for(var a=[],r=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,c=i.length;o0)throw new Error("Invalid string. Length must be a multiple of 4");var s=e.indexOf("=");return-1===s&&(s=t),[s,s===t?0:4-s%4]}function d(e,t,s){for(var r,n,i=[],o=t;o>18&63]+a[n>>12&63]+a[n>>6&63]+a[63&n]);return i.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},function(e,t){ -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -t.read=function(e,t,s,a,r){var n,i,o=8*r-a-1,c=(1<>1,d=-7,h=s?r-1:0,l=s?-1:1,f=e[t+h];for(h+=l,n=f&(1<<-d)-1,f>>=-d,d+=o;d>0;n=256*n+e[t+h],h+=l,d-=8);for(i=n&(1<<-d)-1,n>>=-d,d+=a;d>0;i=256*i+e[t+h],h+=l,d-=8);if(0===n)n=1-u;else{if(n===c)return i?NaN:1/0*(f?-1:1);i+=Math.pow(2,a),n-=u}return(f?-1:1)*i*Math.pow(2,n-a)},t.write=function(e,t,s,a,r,n){var i,o,c,u=8*n-r-1,d=(1<>1,l=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,f=a?0:n-1,m=a?1:-1,p=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,i=d):(i=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-i))<1&&(i--,c*=2),(t+=i+h>=1?l/c:l*Math.pow(2,1-h))*c>=2&&(i++,c/=2),i+h>=d?(o=0,i=d):i+h>=1?(o=(t*c-1)*Math.pow(2,r),i+=h):(o=t*Math.pow(2,h-1)*Math.pow(2,r),i=0));r>=8;e[s+f]=255&o,f+=m,o/=256,r-=8);for(i=i<0;e[s+f]=255&i,f+=m,i/=256,u-=8);e[s+f-m]|=128*p}},function(e,t){var s={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==s.call(e)}},function(e,t,s){ -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -var a=s(4),r=a.Buffer;function n(e,t){for(var s in e)t[s]=e[s]}function i(e,t,s){return r(e,t,s)}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=a:(n(a,t),t.Buffer=i),i.prototype=Object.create(r.prototype),n(r,i),i.from=function(e,t,s){if("number"==typeof e)throw new TypeError("Argument must not be a number");return r(e,t,s)},i.alloc=function(e,t,s){if("number"!=typeof e)throw new TypeError("Argument must be a number");var a=r(e);return void 0!==t?"string"==typeof s?a.fill(t,s):a.fill(t):a.fill(0),a},i.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return a.SlowBuffer(e)}},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t){},function(e,t,s){var a;function r(e){this.rand=e}if(e.exports=function(e){return a||(a=new r(null)),a.generate(e)},e.exports.Rand=r,r.prototype.generate=function(e){return this._rand(e)},r.prototype._rand=function(e){if(this.rand.getBytes)return this.rand.getBytes(e);for(var t=new Uint8Array(e),s=0;s=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},s(26),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(this,s(3))},function(e,t,s){(function(e,t){!function(e,s){"use strict";if(!e.setImmediate){var a,r,n,i,o,c=1,u={},d=!1,h=e.document,l=Object.getPrototypeOf&&Object.getPrototypeOf(e);l=l&&l.setTimeout?l:e,"[object process]"==={}.toString.call(e.process)?a=function(e){t.nextTick((function(){m(e)}))}:!function(){if(e.postMessage&&!e.importScripts){var t=!0,s=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=s,t}}()?e.MessageChannel?((n=new MessageChannel).port1.onmessage=function(e){m(e.data)},a=function(e){n.port2.postMessage(e)}):h&&"onreadystatechange"in h.createElement("script")?(r=h.documentElement,a=function(e){var t=h.createElement("script");t.onreadystatechange=function(){m(e),t.onreadystatechange=null,r.removeChild(t),t=null},r.appendChild(t)}):a=function(e){setTimeout(m,0,e)}:(i="setImmediate$"+Math.random()+"$",o=function(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(i)&&m(+t.data.slice(i.length))},e.addEventListener?e.addEventListener("message",o,!1):e.attachEvent("onmessage",o),a=function(t){e.postMessage(i+t,"*")}),l.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),s=0;s{if(!ls)throw new hs.AppIdNotSet;return ls},gs=()=>fs,ys=()=>window._userbaseEndpoint||"https://v1.userbase.com/v1",bs=({appId:e,updateUserHandler:t,allowServerSideEncryption:s})=>{if(ls&&ls!==e)throw new hs.AppIdAlreadySet(ls);ls=e,fs=t,ms=s},vs=e=>e?window._USERBASE_STRIPE_PRODUCTION_PUBLISHABLE_KEY||"pk_live_jI6lbsAIQlu2u4uTkDXFrSEW":window._USERBASE_STRIPE_TEST_PUBLISHABLE_KEY||"pk_test_rYANrLdNfdJXJ2d808wW4pqY",Ms=()=>ms;class Ss extends Error{constructor(e,t,s,...a){super(e,t,s,...a),this.response={data:e,status:t,statusText:s},this.message="Request failed with status code "+t}}class Is extends Error{constructor(e,...t){super(e,...t),this.message="timeout of ".concat(e,"ms exceeded")}}const Ps=(e,t,s,a=1e4)=>{e.timeout=a,e.onload=()=>((e,t,s)=>{let a;try{a=JSON.parse(e.response)}catch(t){a=e.response}e.status>=200&&e.status<300?t(a):s(new Ss(a,e.status,e.statusText))})(e,t,s),e.onerror=()=>s(new hs.ServiceUnavailable),e.ontimeout=()=>s(new Is(a))};var Es=(e,t,s,a,r,n,i,o,c)=>new Promise((u,d)=>{const h=new XMLHttpRequest,l="".concat(ys(),"/api/auth/sign-up?appId=").concat(ws(),"&userbaseJsVersion=").concat(ps),f=JSON.stringify({username:e,passwordToken:t,ecKeyData:s,passwordSalts:a,keySalts:r,email:n,profile:i,passwordBasedBackup:o,sessionLength:c});h.open("POST",l),h.setRequestHeader("Content-Type","application/json"),h.send(f),Ps(h,u,d)}),Bs=e=>new Promise((t,s)=>{const a=new XMLHttpRequest,r="".concat(ys(),"/api/auth/get-password-salts?appId=").concat(ws(),"&username=").concat(encodeURIComponent(e),"&userbaseJsVersion=").concat(ps);a.open("GET",r),a.send(),Ps(a,t,s)}),Ns=async(e,t,s)=>new Promise((a,r)=>{const n=new XMLHttpRequest,i="".concat(ys(),"/api/auth/sign-in?appId=").concat(ws(),"&userbaseJsVersion=").concat(ps),o=JSON.stringify({username:e,passwordToken:t,sessionLength:s});n.open("POST",i),n.setRequestHeader("Content-Type","application/json"),n.send(o),Ps(n,a,r)}),Us=(e,t)=>new Promise((s,a)=>{const r=new XMLHttpRequest,n="".concat(ys(),"/api/auth/sign-in-with-session?appId=").concat(ws(),"&sessionId=").concat(e,"&userbaseJsVersion=").concat(ps),i=JSON.stringify({sessionLength:t});r.open("POST",n),r.setRequestHeader("Content-Type","application/json"),r.send(i),Ps(r,s,a)}),As=async()=>new Promise((e,t)=>{const s=new XMLHttpRequest,a="".concat(ys(),"/api/auth/server-public-key?&userbaseJsVersion=").concat(ps);s.open("GET",a),s.responseType="arraybuffer",s.send(),Ps(s,e,t)}),Ts=e=>new Promise((t,s)=>{const a=new XMLHttpRequest,r="".concat(ys(),"/api/public-key?appId=").concat(ws(),"&username=").concat(encodeURIComponent(e),"&userbaseJsVersion=").concat(ps);a.open("GET",r),a.send(),Ps(a,t,s)}),ks=s(2),Ds=s.n(ks);function Ks(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,a)}return s}function xs(e){for(var t=1;t(...t)=>{try{return e(...t)}catch(e){console.warn("Error accessing browser storage. Defaulting to memory.\n\n",e)}},Os=(e,t)=>"userbaseSeed.".concat(e,".").concat(t),Cs=Rs((e,t,s,a,r,n)=>{const i={username:t,signedIn:s,sessionId:a,creationDate:r,expirationDate:n},o=JSON.stringify(i);"local"===e?localStorage.setItem("userbaseCurrentSession",o):"session"===e&&sessionStorage.setItem("userbaseCurrentSession",o)});var _s={signInSession:(e,t,s,a,r)=>{Cs(e,t,!0,s,a,r)},signOutSession:(e,t)=>{Cs(e,t,!1)},getCurrentSession:Rs(()=>{const e=sessionStorage.getItem("userbaseCurrentSession");if(e){if(!JSON.parse(e).signedIn){const e=localStorage.getItem("userbaseCurrentSession");if(e){const t=JSON.parse(e);if(t.signedIn)return xs(xs({},t),{},{rememberMe:"local"})}}return xs(xs({},JSON.parse(e)),{},{rememberMe:"session"})}const t=localStorage.getItem("userbaseCurrentSession");return t&&xs(xs({},JSON.parse(t)),{},{rememberMe:"local"})}),saveSeedString:Rs((e,t,s,a)=>{"local"===e?localStorage.setItem(Os(t,s),a):"session"===e&&sessionStorage.setItem(Os(t,s),a)}),removeSeedString:Rs((e,t)=>{const s=Os(e,t);sessionStorage.removeItem(s),localStorage.removeItem(s)}),getSeedString:Rs((e,t)=>{const s=Os(e,t);return sessionStorage.getItem(s)||localStorage.getItem(s)}),removeCurrentSession:Rs(()=>{sessionStorage.removeItem("userbaseCurrentSession"),localStorage.removeItem("userbaseCurrentSession")})};const Fs=(e,t)=>{const s=t?new Uint8Array(e):new Uint16Array(e),a=s.length;let r="",n=10240;for(var i=0;ia&&(n=a-i);const e=s.subarray(i,i+n);r+=String.fromCharCode.apply(null,e)}return r},Ls=(e,t=!1)=>{let s=new ArrayBuffer(e.length*(t?1:2)),a=t?new Uint8Array(s):new Uint16Array(s);for(let t=0,s=e.length;t{const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer},qs=async e=>await window.crypto.subtle.digest({name:"SHA-256"},e);var Vs={BYTE_SIZE:32,HASH_ALGORITHM_NAME:"SHA-256",hash:qs,hashBase64String:async e=>{const t=i.a.decode(e),s=await qs(t);return i.a.encode(s)},hashString:async e=>{const t=Ls(e),s=await qs(t);return i.a.encode(s)}};const Hs=["deriveKey","deriveBits"],Gs=async e=>await window.crypto.subtle.importKey("raw",e,{name:"HKDF"},!1,Hs),Js=Vs.BYTE_SIZE,Ws=(e,t)=>({name:"HKDF",info:Ls(e),hash:Vs.HASH_ALGORITHM_NAME,salt:t});var Ys={importHkdfKeyFromString:async e=>{const t=Ls(e);return await Gs(t)},importHkdfKey:Gs,generateSalt:()=>window.crypto.getRandomValues(new Uint8Array(Js)),getParams:Ws,getPasswordToken:async(e,t)=>{const s=await window.crypto.subtle.deriveBits(Ws("password-token",t),e,256);return i.a.encode(s)}};const zs=["encrypt","decrypt"],Zs=()=>"undefined"!=typeof window?window:self,Xs=()=>({name:"AES-GCM",length:256}),Qs=e=>({name:"AES-GCM",tagLength:128,iv:e}),$s=()=>window.crypto.getRandomValues(new Uint8Array(12)),ea=e=>{const t=e.byteLength-12;return{ciphertextArrayBuffer:e.slice(0,t),iv:e.slice(t)}},ta=async()=>await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,zs),sa=async e=>await Zs().crypto.subtle.importKey("raw",e,{name:"AES-GCM"},!0,zs),aa=async e=>await Zs().crypto.subtle.exportKey("raw",e),ra=async(e,t)=>{const s=$s(),a=await Zs().crypto.subtle.encrypt(Qs(s),e,t);return js(a,s)},na=async(e,t)=>{const s=Ls(t),a=await ra(e,s);return i.a.encode(a)},ia=async(e,t)=>{const{ciphertextArrayBuffer:s,iv:a}=ea(t);return await Zs().crypto.subtle.decrypt(Qs(a),e,s)},oa=async(e,t)=>{const s=i.a.decode(t),a=await ia(e,s);return Fs(a)};var ca={getEncryptionKeyParams:Xs,getCiphertextParams:Qs,generateIv:$s,sliceEncryptedArrayBuffer:ea,importKeyFromMaster:async(e,t,s="encryption")=>await window.crypto.subtle.deriveKey(Ys.getParams(s,t),e,{name:"AES-GCM",length:256},!0,zs),generateKey:ta,getKeyStringFromKey:async e=>{const t=await window.crypto.subtle.exportKey("raw",e);return i.a.encode(t)},getKeyFromKeyString:async e=>{const t=i.a.decode(e);return await sa(t)},getRawKeyFromKey:aa,getKeyFromRawKey:sa,encrypt:ra,encryptJson:async(e,t)=>{const s=JSON.stringify(t);return await na(e,s)},encryptString:na,decrypt:ia,decryptJson:async(e,t)=>{const s=await oa(e,t);return JSON.parse(s)},decryptString:oa,getPasswordBasedEncryptionKey:async(e,t)=>await window.crypto.subtle.deriveKey(Ys.getParams("password-based-encryption",t),e,{name:"AES-GCM",length:256},!1,zs),generateAndEncryptKeyEncryptionKey:async e=>{const t=await ta(),s=await aa(t);return[t,await ra(e,s)]},RAW_KEY_TYPE:"raw",KEY_WILL_BE_USED_TO:zs},ua=s(10),da=s.n(ua);const ha=["encrypt"],la=(e=>{if(e.length%2!=0)throw new Error("Hex string must be even length");const t=e.length/2,s=[];for(let a=0;a((e,t)=>(e.setPrivateKey(t),e.generateKeys(),e))(da.a.createDiffieHellman(la,fa),e),wa=async(e,t)=>{const s=pa(e).computeSecret(t),a=await Vs.hash(s);return await ca.getKeyFromRawKey(a)};var ga={getPublicKey:e=>pa(e).getPublicKey(),getSharedKey:wa,getSharedKeyWithServer:async e=>await wa(e,new Uint8Array(await(async()=>ma||(ma=await As(),ma))())),importKeyFromMaster:async(e,t)=>{const s=await window.crypto.subtle.deriveKey(Ys.getParams("diffie-hellman",t),e,ca.getEncryptionKeyParams(),!0,ha);return await ca.getRawKeyFromKey(s)}};const ya=["sign","verify"],ba=["sign"],va=["verify"],Ma={name:"ECDSA",namedCurve:"P-256"},Sa={name:"ECDSA",hash:{name:Vs.HASH_ALGORITHM_NAME}},Ia=async e=>await window.crypto.subtle.exportKey("spki",e),Pa=async e=>{const t=await Ia(e);return i.a.encode(t)},Ea=async(e,t)=>await ca.importKeyFromMaster(e,t,"ecdsa-key-encryption-key"),Ba=async(e,t)=>await window.crypto.subtle.sign(Sa,e,t),Na=async(e,t,s)=>await window.crypto.subtle.verify(Sa,e,t,s);var Ua={generateEcdsaKeyData:async e=>{const t=await(async()=>await window.crypto.subtle.generateKey(Ma,!0,ya))(),s=Ys.generateSalt(),a=await Ea(e,s),r=await(async e=>{const t=await window.crypto.subtle.exportKey("jwk",e);return Ls(JSON.stringify(t))})(t.privateKey),n=await ca.encrypt(a,r);return{ecdsaPrivateKey:t.privateKey,ecdsaPublicKey:await Pa(t.publicKey),encryptedEcdsaPrivateKey:i.a.encode(n),ecdsaKeyEncryptionKeySalt:i.a.encode(s)}},importEcdsaKeyEncryptionKeyFromMaster:Ea,getPrivateKeyFromRawPrivateKey:async e=>{const t=JSON.parse(Fs(e));return await window.crypto.subtle.importKey("jwk",t,Ma,!0,ba)},getPublicKeyFromRawPublicKey:async e=>await window.crypto.subtle.importKey("spki",e,Ma,!0,va),getRawPublicKeyFromPublicKey:Ia,getPublicKeyStringFromPublicKey:Pa,getPublicKeyFromPrivateKey:async e=>{const t=await window.crypto.subtle.exportKey("jwk",e);delete t.d,t.key_ops=va;return await window.crypto.subtle.importKey("jwk",t,Ma,!0,va)},sign:Ba,signString:async(e,t)=>{const s=Ls(t),a=await Ba(e,s);return i.a.encode(a)},verify:Na,verifyString:async(e,t,s)=>{const a=Ls(s),r=i.a.decode(t);return await Na(e,r,a)}};const Aa=["deriveKey","deriveBits"],Ta={name:"ECDH",namedCurve:"P-256"},ka=async()=>await window.crypto.subtle.generateKey(Ta,!0,Aa),Da=async e=>await window.crypto.subtle.exportKey("spki",e),Ka=async(e,t)=>await ca.importKeyFromMaster(e,t,"ecdh-key-encryption-key");var xa={generateKeyPair:ka,generateEcdhKeyData:async(e,t)=>{const s=await ka(),a=Ys.generateSalt(),r=await Ka(e,a),n=await(async e=>{const t=await window.crypto.subtle.exportKey("jwk",e);return Ls(JSON.stringify(t))})(s.privateKey),o=await ca.encrypt(r,n),c=await Da(s.publicKey),u=await Ua.sign(t,c);return{ecdhPrivateKey:s.privateKey,ecdhPublicKey:i.a.encode(c),encryptedEcdhPrivateKey:i.a.encode(o),signedEcdhPublicKey:i.a.encode(u),ecdhKeyEncryptionKeySalt:i.a.encode(a)}},importEcdhKeyEncryptionKeyFromMaster:Ka,getPrivateKeyFromRawPrivateKey:async e=>{const t=JSON.parse(Fs(e));return await window.crypto.subtle.importKey("jwk",t,Ta,!0,Aa)},getRawPublicKeyFromPublicKey:Da,getPublicKeyFromRawPublicKey:async e=>await window.crypto.subtle.importKey("spki",e,Ta,!0,[]),computeSharedKeyEncryptionKey:async(e,t)=>await window.crypto.subtle.deriveKey({name:"ECDH",namedCurve:"P-256",public:e},t,ca.getEncryptionKeyParams(),!1,ca.KEY_WILL_BE_USED_TO)};const Ra=["sign"],Oa=["sign","verify"],Ca=async(e,t)=>await window.crypto.subtle.sign({name:"HMAC"},e,t);var _a={importKeyFromMaster:async(e,t)=>await window.crypto.subtle.deriveKey(Ys.getParams("authentication",t),e,{name:"HMAC",hash:{name:Vs.HASH_ALGORITHM_NAME},length:512},!1,Ra),importKeyFromRawBits:async e=>await window.crypto.subtle.importKey("raw",e,{name:"HMAC",hash:{name:Vs.HASH_ALGORITHM_NAME},length:256},!1,Oa),sign:Ca,signString:async(e,t)=>{const s=await Ca(e,Ls(t));return i.a.encode(s)}},Fa=s(11),La=s.n(Fa);var ja={generateSeed:()=>window.crypto.getRandomValues(new Uint8Array(32)),aesGcm:ca,diffieHellman:ga,ecdsa:Ua,ecdh:xa,sha256:Vs,hmac:_a,hkdf:Ys,scrypt:{generateSalt:()=>window.crypto.getRandomValues(new Uint8Array(16)),hash:async(e,t,s=La.a.scrypt)=>{const a=new Uint8Array(Ls(e)),r=await s(a,t,16384,8,1,32);return i.a.encode(r)}}};const qa=e=>e.split(":")[0],Va=e=>{const t=(e=>"http://"===e.substring(0,"http://".length)?e.substring("http://".length):"https://"===e.substring(0,"https://".length)?e.substring("https://".length):e)(e);return("https"===qa(e)?"wss://":"ws://")+t},Ha=e=>2*e.length,Ga=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function Ja(){let e=[],t=0;this.getLength=()=>e.length-t,this.isEmpty=()=>0===e.length,this.enqueue=t=>(e.push(t),this.getLength()),this.dequeue=()=>{const s=e[t];return t+=1,2*t>e.length&&(e=e.slice(t),t=0),s},this.peek=()=>e[t]}const Wa=()=>{const e=URL.createObjectURL(new Blob(["(",function(){self.onmessage=function(e){const{compress:t,decompress:s,data:a}=e.data,r=function(){function e(e,t){if(!r[e]){r[e]={};for(var s=0;sa;a++){var i=t.charCodeAt(a);s[2*a]=i>>>8,s[2*a+1]=i%256}return s},decompressFromUint8Array:function(e){if(null==e)return n.decompress(e);for(var s=new Array(e.length/2),a=0,r=s.length;r>a;a++)s[a]=256*e[2*a]+e[2*a+1];var i=[];return s.forEach((function(e){i.push(t(e))})),n.decompress(i.join(""))},compressToEncodedURIComponent:function(e){return null==e?"":n._compress(e,6,(function(e){return a.charAt(e)}))},decompressFromEncodedURIComponent:function(t){return null==t?"":""==t?null:(t=t.replace(/ /g,"+"),n._decompress(t.length,32,(function(s){return e(a,t.charAt(s))})))},compress:function(e){return n._compress(e,16,(function(e){return t(e)}))},_compress:function(e,t,s){if(null==e)return"";var a,r,n,i={},o={},c="",u="",d="",h=2,l=3,f=2,m=[],p=0,w=0;for(n=0;na;a++)p<<=1,w==t-1?(w=0,m.push(s(p)),p=0):w++;for(r=d.charCodeAt(0),a=0;8>a;a++)p=p<<1|1&r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r>>=1}else{for(r=1,a=0;f>a;a++)p=p<<1|r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r=0;for(r=d.charCodeAt(0),a=0;16>a;a++)p=p<<1|1&r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r>>=1}0==--h&&(h=Math.pow(2,f),f++),delete o[d]}else for(r=i[d],a=0;f>a;a++)p=p<<1|1&r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r>>=1;0==--h&&(h=Math.pow(2,f),f++),i[u]=l++,d=String(c)}if(""!==d){if(Object.prototype.hasOwnProperty.call(o,d)){if(d.charCodeAt(0)<256){for(a=0;f>a;a++)p<<=1,w==t-1?(w=0,m.push(s(p)),p=0):w++;for(r=d.charCodeAt(0),a=0;8>a;a++)p=p<<1|1&r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r>>=1}else{for(r=1,a=0;f>a;a++)p=p<<1|r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r=0;for(r=d.charCodeAt(0),a=0;16>a;a++)p=p<<1|1&r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r>>=1}0==--h&&(h=Math.pow(2,f),f++),delete o[d]}else for(r=i[d],a=0;f>a;a++)p=p<<1|1&r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r>>=1;0==--h&&(h=Math.pow(2,f),f++)}for(r=2,a=0;f>a;a++)p=p<<1|1&r,w==t-1?(w=0,m.push(s(p)),p=0):w++,r>>=1;for(;;){if(p<<=1,w==t-1){m.push(s(p));break}w++}return m.join("")},decompress:function(e){return null==e?"":""==e?null:n._decompress(e.length,32768,(function(t){return e.charCodeAt(t)}))},_decompress:function(e,s,a){var r,n,i,o,c,u,d,h=[],l=4,f=4,m=3,p="",w=[],g={val:a(0),position:s,index:1};for(r=0;3>r;r+=1)h[r]=r;for(i=0,c=Math.pow(2,2),u=1;u!=c;)o=g.val&g.position,g.position>>=1,0==g.position&&(g.position=s,g.val=a(g.index++)),i|=(o>0?1:0)*u,u<<=1;switch(i){case 0:for(i=0,c=Math.pow(2,8),u=1;u!=c;)o=g.val&g.position,g.position>>=1,0==g.position&&(g.position=s,g.val=a(g.index++)),i|=(o>0?1:0)*u,u<<=1;d=t(i);break;case 1:for(i=0,c=Math.pow(2,16),u=1;u!=c;)o=g.val&g.position,g.position>>=1,0==g.position&&(g.position=s,g.val=a(g.index++)),i|=(o>0?1:0)*u,u<<=1;d=t(i);break;case 2:return""}for(h[3]=d,n=d,w.push(d);;){if(g.index>e)return"";for(i=0,c=Math.pow(2,m),u=1;u!=c;)o=g.val&g.position,g.position>>=1,0==g.position&&(g.position=s,g.val=a(g.index++)),i|=(o>0?1:0)*u,u<<=1;switch(d=i){case 0:for(i=0,c=Math.pow(2,8),u=1;u!=c;)o=g.val&g.position,g.position>>=1,0==g.position&&(g.position=s,g.val=a(g.index++)),i|=(o>0?1:0)*u,u<<=1;h[f++]=t(i),d=f-1,l--;break;case 1:for(i=0,c=Math.pow(2,16),u=1;u!=c;)o=g.val&g.position,g.position>>=1,0==g.position&&(g.position=s,g.val=a(g.index++)),i|=(o>0?1:0)*u,u<<=1;h[f++]=t(i),d=f-1,l--;break;case 2:return w.join("")}if(0==l&&(l=Math.pow(2,m),m++),h[d])p=h[d];else{if(d!==f)return null;p=n+n.charAt(0)}w.push(p),h[f++]=n+p.charAt(0),n=p,0==--l&&(l=Math.pow(2,m),m++)}}};return n}();t?postMessage(r.compress(a)):s&&postMessage(r.decompress(a))}}.toString(),")()"],{type:"application/javascript"})),t=new Worker(e);return URL.revokeObjectURL(e),t},Ya=async e=>{const t=Wa();return new Promise(s=>{t.onmessage=e=>{s(e.data),t.terminate()},t.postMessage({compress:!0,data:e})})},za=async e=>{const t=Wa();return new Promise(s=>{t.onmessage=e=>{s(e.data),t.terminate()},t.postMessage({decompress:!0,data:e})})},Za=async(e,t,s,a,r,n)=>new Promise((i,o)=>{const c=new XMLHttpRequest,u="".concat(ys(),"/api/bundle-chunk?userbaseJsVersion=").concat(ps,"&")+"userId=".concat(e,"&")+"databaseId=".concat(t,"&")+"seqNo=".concat(s,"&")+"bundleId=".concat(a,"&")+"chunkNumber=".concat(r);c.open("POST",u),c.send(new Uint8Array(n)),Ps(c,i,o,3e4)});function Xa(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,a)}return s}function Qa(e){for(var t=1;t{let u=!1;const d=setTimeout(()=>{this.connected||this.reconnecting||(u=!0,c(new tr("timeout")))},1e4),h="".concat(Va(ys()),"/api?appId=").concat(ws(),"&sessionId=").concat(e.sessionId,"&clientId=").concat($a,"&userbaseJsVersion=").concat(ps),l=new WebSocket(h);l.onopen=async()=>{u||clearTimeout(d)},l.onmessage=async r=>{if(!u)try{const u=JSON.parse(r.data);switch(u.route){case"Ping":{this.heartbeat();const e="Pong";this.ws.send(JSON.stringify({action:e}));break}case"Connection":{const{encryptionMode:o}=u;if(this.init(i,c,e,t,s,a,n,o),this.ws=l,this.heartbeat(),this.connected=!0,t){const{keySalts:e,validationMessage:t,ecKeyData:s,encryptedValidationMessage:a}=u;this.keys.salts=e,this.validationMessage=t,this.ecKeyData=s,a&&(this.encryptedValidationMessage=new Uint8Array(a.data));try{await this.setKeys(this.seedString);const e=await this.validateKey();this.userData=e}catch(r){throw r&&"OperationError"===r.name||r instanceof DOMException?new Error("Invalid seed"):r}this.keys.init=!0}this.resolveConnection(),this.connectionResolved=!0;break}case"ApplyTransactions":{const e=u.dbId,t=u.dbNameHash,s=u.isOwner?this.state.databases[t]:this.state.databasesByDbId[e];if(!s)throw new Error("Missing database");s.applyTransactionsQueue.isEmpty()?s.applyTransactionsQueue.enqueue(null):await new Promise(e=>{const t=e;s.applyTransactionsQueue.enqueue(t)});if((u.dbNameHash&&(u.dbKey||u.plaintextDbKey)||u.shareTokenEncryptedDbKey)&&(!s.dbKeyString||!s.dbKey)){const e=u.plaintextDbKey||(u.dbKey?await ja.aesGcm.decryptString(this.keys.encryptionKey,u.dbKey):await s.decryptShareTokenEncryptedDbKey(u.shareTokenEncryptedDbKey,u.shareTokenEncryptionKeySalt));s.dbKeyString=e,s.dbKey=await ja.aesGcm.getKeyFromKeyString(e)}if(!s.dbKey)throw new Error("Missing db key");if(u.writers){s.attributionEnabled=!0;for(const{userId:e,username:t}of u.writers)s.usernamesByUserId.set(e,t)}if(u.waitForFullBundle){s.finishedWaitingForBundle||await new Promise(e=>s.finishedWaitingForBundle=e);try{const e=await this.rebuildBundle(s,u.bundleSeqNo,u.encryptedBundleEncryptionKey);await s.applyBundle(e,u.bundleSeqNo)}catch(r){throw window.alert("Oops! Something went wrong. Please contact the site administrator with this issue (".concat(e,").\n\n")+r),r}}const a=u.transactionLog;if(await s.applyTransactions(a,u.ownerId,e,t),u.buildBundle&&this.buildBundle(s),s.applyTransactionsQueue.dequeue(),!s.applyTransactionsQueue.isEmpty()){s.applyTransactionsQueue.peek()()}break}case"DownloadBundleChunk":{const{dbId:e,dbNameHash:t,isOwner:s,bundleSeqNo:a,isFirstChunk:r,isLastChunk:n,chunk:i}=u,o=s?this.state.databases[t]:this.state.databasesByDbId[e];if(!o)throw new Error("Missing database");r&&(o.bundleChunks[a]=[]),o.bundleChunks[a].push(i),n&&(o.finishedWaitingForBundle?o.finishedWaitingForBundle():o.finishedWaitingForBundle=!0);break}case"UpdatedUser":this.handleUpdateUser(u.updatedUser);break;case"SignOut":case"UpdateUser":case"DeleteUser":case"CreateDatabase":case"OpenDatabase":case"OpenDatabaseByDatabaseId":case"GetDatabases":case"GetDatabaseUsers":case"Insert":case"Update":case"Delete":case"BatchTransaction":case"InitBundleUpload":case"CompleteBundleUpload":case"GenerateFileId":case"UploadFileChunk":case"CompleteFileUpload":case"GetChunk":case"ValidateKey":case"GetPasswordSalts":case"PurchaseSubscription":case"CancelSubscription":case"ResumeSubscription":case"UpdatePaymentMethod":case"ShareDatabase":case"ShareDatabaseToken":case"AuthenticateShareToken":case"SaveDatabase":case"ModifyDatabasePermissions":case"VerifyUser":{const e=u.requestId;if(!e)return console.warn("Missing request id");const t=this.requests[e];if(!t)return console.warn("Request ".concat(e," no longer exists!"));if(!t.promiseResolve||!t.promiseReject)return;const s=u.response;return s&&s.status===o?t.promiseResolve(s):t.promiseReject(s)}default:console.log("Received unknown message from backend:"+JSON.stringify(u))}}catch(r){this.connectionResolved?console.warn("Error handling message: ",r):(this.close(),c(new tr(r.message,e.username,r)))}},l.onclose=async o=>{if(u)return;const d=o.code===y,h=o.code===b;if(d||h||!o.wasClean){const o=d&&!r?0:r?r+1e3:1e3;this.reconnecting=!0,await this.reconnect(i,c,e,this.seedString||t,s,a,o,!this.reconnected&&n)}else o.code===v?c(new tr("Web Socket already connected",e.username,o)):this.init()},l.onerror=()=>{}})}async reconnect(e,t,s,a,r,n,i,o){try{const t=Math.min(i,3e4);console.log("Connection to server lost. Attempting to reconnect in ".concat(t/1e3," second").concat(1e3!==t?"s":"","..."));const c=[],u=[];e(await new Promise((e,d)=>setTimeout(async()=>{try{const t=o||{dbNameToHash:Qa({},this.state.dbNameToHash),databases:Qa({},this.state.databases),databasesByDbId:Qa({},this.state.databasesByDbId),shareTokenIdToDbId:Qa({},this.state.shareTokenIdToDbId)};for(const e in t.databases)t.databases[e].init=!1,t.databases[e].finishedWaitingForBundle=!1,c.push(e);for(const e in t.databasesByDbId)t.databasesByDbId[e].init=!1,t.databasesByDbId[e].finishedWaitingForBundle=!1,u.push(e);this.init(),this.reconnecting=!0;const d=await this.connect(s,a,r,n,i,t);this.reconnected=!0,o||(await this.reopenDatabases(c,u,1e3),console.log("Reconnected!")),e(d)}catch(e){d(e)}},t)))}catch(e){t(e)}}async reopenDatabases(e,t,s){try{const s=[];for(const t of e){const e=this.state.databases[t];if(!e.init){const a="OpenDatabase",r={dbNameHash:t,reopenAtSeqNo:e.lastSeqNo};s.push(this.request(a,r))}}for(const e of t){const t=this.state.databasesByDbId[e];if(!t.init){const a=t.shareTokenHkdfKey,r=a?await this.authenticateShareToken(t.shareTokenId,a):{},n="OpenDatabaseByDatabaseId",i=Qa({databaseId:e,reopenAtSeqNo:t.lastSeqNo},r);s.push(this.request(n,i))}}await Promise.all(s)}catch(a){await new Promise(a=>setTimeout(async()=>{await this.reopenDatabases(e,t,s+1e3),a()},Math.min(s,3e4)))}}heartbeat(){clearTimeout(this.pingTimeout);this.pingTimeout=setTimeout(()=>{this.ws&&this.ws.close(b)},33e3)}close(e){this.ws?this.ws.close(e):this.init()}async signOut(){const e=this.session.username,t=this.connectionResolved,s=this.rejectConnection;try{_s.signOutSession(this.rememberMe,e);const a=this.session.sessionId;if(this.reconnecting)throw new hs.Reconnecting;const r="SignOut",n={sessionId:a};await this.request(r,n),this.close(),!t&&s&&s(new tr("Canceled",e))}catch(a){throw!t&&s&&s(new tr("Canceled",e)),a}}async setKeys(e){if(this.keys.init)return;if(!e)throw new tr("Missing seed",this.session.username);if(!this.keys.salts)throw new tr("Missing salts",this.session.username);this.seedString||(this.seedString=e);const t=i.a.decode(e),s=await ja.hkdf.importHkdfKey(t),a=this.keys.salts;if(this.keys.encryptionKey=await ja.aesGcm.importKeyFromMaster(s,i.a.decode(a.encryptionKeySalt)),this.keys.hmacKey=await ja.hmac.importKeyFromMaster(s,i.a.decode(a.hmacKeySalt)),a.ecdsaKeyEncryptionKeySalt){const e=await ja.ecdsa.importEcdsaKeyEncryptionKeyFromMaster(s,i.a.decode(a.ecdsaKeyEncryptionKeySalt)),t=i.a.decode(this.ecKeyData.encryptedEcdsaPrivateKey),r=await ja.aesGcm.decrypt(e,t);this.keys.ecdsaPrivateKey=await ja.ecdsa.getPrivateKeyFromRawPrivateKey(r);const n=await ja.ecdh.importEcdhKeyEncryptionKeyFromMaster(s,i.a.decode(a.ecdhKeyEncryptionKeySalt)),o=i.a.decode(this.ecKeyData.encryptedEcdhPrivateKey),c=await ja.aesGcm.decrypt(n,o);this.keys.ecdhPrivateKey=await ja.ecdh.getPrivateKeyFromRawPrivateKey(c)}else a.dhKeySalt&&(this.keys.dhPrivateKey=await ja.diffieHellman.importKeyFromMaster(s,i.a.decode(a.dhKeySalt)));if(a.dhKeySalt||a.ecdsaKeyWrapperSalt){const e=await ja.ecdsa.generateEcdsaKeyData(s),t=await ja.ecdh.generateEcdhKeyData(s,e.ecdsaPrivateKey);this.keys.ecdsaPrivateKey=e.ecdsaPrivateKey,this.keys.ecdhPrivateKey=t.ecdhPrivateKey,delete e.ecdsaPrivateKey,delete t.ecdhPrivateKey,this.newEcKeyData={ecdsaKeyData:e,ecdhKeyData:t}}}async validateKey(){let e;if(this.keys.ecdsaPrivateKey&&!this.keys.dhPrivateKey)e=await ja.ecdsa.sign(this.keys.ecdsaPrivateKey,i.a.decode(this.validationMessage));else if(this.keys.dhPrivateKey){const t=await ja.diffieHellman.getSharedKeyWithServer(this.keys.dhPrivateKey);e=await ja.aesGcm.decrypt(t,this.encryptedValidationMessage),delete this.keys.dhPrivateKey}const t={validationMessage:i.a.encode(e),ecKeyData:this.newEcKeyData};return(await this.request("ValidateKey",t)).data}async request(e,t){const s=Ds()();this.requests[s]={};const a=this.watch(s);this.ws.send(JSON.stringify({requestId:s,action:e,params:t}));try{return await a}catch(t){throw t.status===m?new hs.TooManyRequests(t.data.retryDelay):new er(e,t)}}async watch(e){const t=await new Promise((t,s)=>{this.requests[e].promiseResolve=t,this.requests[e].promiseReject=s,setTimeout(()=>{s(new Error("timeout"))},3e4)});return delete this.requests[e],t}async rebuildBundle(e,t,s){const a=[];for(let s=0;s{const t=e.map(e=>e.byteLength),s=t.reduce((e,t)=>e+t),a=new Uint8Array(s);let r=0;for(let s=0;s=s)return;e.bundledAtSeqNo=s;const n=this.prepareBundle(e),i=e.attributionEnabled?[...e.usernamesByUserId.keys()].join(","):void 0,{bundleId:o,bundleEncryptionKey:c,encryptedBundleEncryptionKey:u}=await this.initBundleUpload(t,s,a);if(!o)return;const[d,h]=await Promise.all([Ya(n.encrypted),Ya(n.plaintextMetadata)]),l=Ls(d),f=await ja.aesGcm.encrypt(c,l);n.encrypted=Fs(f),n.plaintextMetadata=h;const m=Ls(JSON.stringify(n)),p=await this.uploadBundle(r,t,s,o,m);if(!p)return;const w={dbId:t,seqNo:s,bundleId:o,writers:i,numChunks:p,encryptedBundleEncryptionKey:u};try{await this.request("CompleteBundleUpload",w)}catch(e){return}}buildUserResult({username:e,userId:t,authToken:s,email:a,profile:r,protectedProfile:n,usedTempPassword:i,changePassword:o,passwordChanged:c,userData:u}){const d={username:e,userId:t,authToken:s};if(a&&(d.email=a),r&&(d.profile=r),n&&(d.protectedProfile=n),i&&(d.usedTempPassword=i),o&&(d.changePassword=o),c&&(d.passwordChanged=c),u){const{creationDate:e,stripeData:t}=u;if(e&&(d.creationDate=e),t){const{paymentsMode:e,subscriptionStatus:s,cancelSubscriptionAt:a,subscriptionPlanId:r,trialExpirationDate:n}=t;e&&(d.paymentsMode=e),s&&(d.subscriptionStatus=s),a&&(d.cancelSubscriptionAt=a),r&&(d.subscriptionPlanId=r),n&&(d.trialExpirationDate=n)}}return d}handleUpdateUser(e){if(this.session&&this.session.userId===e.userId){this.session.username=e.username,this.userData=e.userData;const t=gs();t&&t({user:this.buildUserResult(Qa({authToken:this.session.authToken},e))})}}async rotateKeys(e,t){const{keySalts:s,ecKeyData:a}=t,{ecdsaKeyData:r,ecdhKeyData:n}=a;s.ecdsaKeyEncryptionKeySalt=r.ecdsaKeyEncryptionKeySalt,s.ecdhKeyEncryptionKeySalt=n.ecdhKeyEncryptionKeySalt,this.keys.salts=s,this.ecKeyData=Qa(Qa({},r),n),await this.setKeys(e),this.keys.init=!0}async authenticateShareToken(e,t){const s={shareTokenId:e};let a;try{a=await this.request("AuthenticateShareToken",s)}catch(e){if(e.response&&"ShareTokenNotFound"===e.response.data)throw new hs.ShareTokenNotFound;throw e}const{databaseId:r,shareTokenAuthKeyData:n,validationMessage:o}=a.data;let c;try{const e=i.a.decode(n.shareTokenEcdsaKeyEncryptionKeySalt),s=await ja.ecdsa.importEcdsaKeyEncryptionKeyFromMaster(t,e),a=i.a.decode(n.shareTokenEncryptedEcdsaPrivateKey),r=await ja.aesGcm.decrypt(s,a);c=await ja.ecdsa.getPrivateKeyFromRawPrivateKey(r)}catch(e){throw new hs.ShareTokenInvalid}const u=await ja.ecdsa.sign(c,i.a.decode(o));return{databaseId:r,validationMessage:o,signedValidationMessage:i.a.encode(u)}}};function ar(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,a)}return s}function rr(e){for(var t=1;t{if(e.response){if("Domain not whitelisted"===e.response.data)throw new hs.DomainNotWhitelisted(window.location.origin);if("App ID not valid"===e.response.data)throw new hs.AppIdNotValid;if("UserNotFound"===e.response.data)throw new hs.UserNotFound;if(e.response.status===p)throw new hs.InternalServerError;if(e.response.status===g)throw new hs.Timeout}else if(e.message&&-1!==e.message.indexOf("timeout"))throw new hs.Timeout},ur=async(e,t,s,a)=>{try{await sr.connect(e,t,s,a)}catch(e){if(cr(e),"Web Socket already connected"===e.message)throw new hs.UserAlreadySignedIn(e.username);throw e}},dr=e=>{if(e.response&&"UsernameTooLong"===e.response.data.error)throw new hs.UsernameTooLong(e.response.data.maxLen);if(e.response&&"PasswordAttemptLimitExceeded"===e.response.data.error)throw new hs.PasswordAttemptLimitExceeded(e.response.data.delay)},hr=e=>{if(e.response&&e.response.data){const t=e.response.data;switch(t.error){case"SessionLengthTooShort":throw new hs.SessionLengthTooShort(t.minLen);case"SessionLengthTooLong":throw new hs.SessionLengthTooLong(t.maxLen)}}},lr=(e,t)=>{if(cr(e),dr(e),e.response){const s=e.response.data;switch(s){case"UsernameAlreadyExists":throw new hs.UsernameAlreadyExists(t);case"TrialExceededLimit":throw new hs.TrialExceededLimit;case"CurrentPasswordIncorrect":throw new hs.CurrentPasswordIncorrect}switch(s.error){case"EmailNotValid":throw new hs.EmailNotValid;case"ProfileMustBeObject":throw new hs.ProfileMustBeObject;case"ProfileKeyTooLong":throw new hs.ProfileKeyTooLong(s.maxLen,s.key);case"ProfileValueMustBeString":throw new hs.ProfileValueMustBeString(s.key,s.value);case"ProfileValueCannotBeBlank":throw new hs.ProfileValueCannotBeBlank(s.key);case"ProfileValueTooLong":throw new hs.ProfileValueTooLong(s.maxLen,s.key,s.value);case"ProfileHasTooManyKeys":throw new hs.ProfileHasTooManyKeys(s.maxKeys);case"ProfileCannotBeEmpty":throw new hs.ProfileCannotBeEmpty}}throw e},fr=e=>e&&60*e*60*1e3,mr=e=>{if("string"!=typeof e)throw new hs.UsernameMustBeString;if(0===e.length)throw new hs.UsernameCannotBeBlank},pr=e=>{if("string"!=typeof e)throw new hs.PasswordMustBeString;if(0===e.length)throw new hs.PasswordCannotBeBlank;if(e.length<6)throw new hs.PasswordTooShort(6);if(e.length>1e3)throw new hs.PasswordTooLong(1e3)},wr=e=>{if("object"!=typeof e)throw new hs.ParamsMustBeObject;if(!Ga(e,"username"))throw new hs.UsernameMissing;if(!Ga(e,"password"))throw new hs.PasswordMissing;if(mr(e.username),pr(e.password),Ga(e,"rememberMe")&&!nr[e.rememberMe])throw new hs.RememberMeValueNotValid(nr);if(Ga(e,"sessionLength")&&"number"!=typeof e.sessionLength)throw new hs.SessionLengthMustBeNumber},gr=async(e,t,s)=>{const a=ja.scrypt.generateSalt(),r=await ja.scrypt.hash(e,a,s),n=await ja.hkdf.importHkdfKeyFromString(r),o=ja.hkdf.generateSalt(),c=await ja.hkdf.getPasswordToken(n,o),u=ja.hkdf.generateSalt(),d=await ja.aesGcm.getPasswordBasedEncryptionKey(n,u),h=await ja.aesGcm.encrypt(d,t);return{passwordToken:c,passwordSalts:{passwordSalt:i.a.encode(a),passwordTokenSalt:i.a.encode(o)},passwordBasedBackup:{passwordBasedEncryptionKeySalt:i.a.encode(u),passwordEncryptedSeed:i.a.encode(h)}}},yr=async e=>{const t=await ja.hkdf.importHkdfKey(e),s=ja.hkdf.generateSalt(),a=ja.hkdf.generateSalt(),r={encryptionKeySalt:i.a.encode(s),hmacKeySalt:i.a.encode(a)},n=await ja.ecdsa.generateEcdsaKeyData(t),o=await ja.ecdh.generateEcdhKeyData(t,n.ecdsaPrivateKey);delete n.ecdsaPrivateKey,delete o.ecdhPrivateKey;return{ecKeyData:{ecdsaKeyData:n,ecdhKeyData:o},keySalts:r}},br=e=>{if("object"!=typeof e)throw new hs.ProfileMustBeObject;let t=!1;for(const s in e){t=!0;const a=e[s];if("string"!=typeof a)throw new hs.ProfileValueMustBeString(s,a);if(!a)throw new hs.ProfileValueCannotBeBlank(s)}if(!t)throw new hs.ProfileCannotBeEmpty},vr=async()=>{try{const e="GetPasswordSalts";return(await sr.request(e)).data}catch(e){throw cr(e),e}},Mr=async(e,t,s)=>{const{passwordSalt:a,passwordTokenSalt:r}=t,n=await ja.scrypt.hash(e,new Uint8Array(i.a.decode(a)),s),o=await ja.hkdf.importHkdfKeyFromString(n);return{passwordHkdfKey:o,passwordToken:await ja.hkdf.getPasswordToken(o,i.a.decode(r))}},Sr=async(e,t)=>{let s;try{const a=_s.getCurrentSession();if(!a)return{};const{signedIn:r,sessionId:n,creationDate:i,expirationDate:o,rememberMe:c}=a;s=a.username;const u=_s.getSeedString(e,s);if(!r||!u||new Date>new Date(o))return{lastUsedUsername:s};let d;try{d=await Us(n,t)}catch(e){if(cr(e),hr(e),e.response&&"Session invalid"===e.response.data)return{lastUsedUsername:s};throw e}const{userId:h,authToken:l,username:f,email:m,profile:p,protectedProfile:w}=d;if(f!==s&&(_s.saveSeedString(c,e,f,u),_s.removeSeedString(e,s)),_s.signInSession(c,f,n,i,d.expirationDate),sr.connectionResolved){if(sr.session.sessionId===n)return{user:sr.buildUserResult({username:f,userId:h,authToken:sr.session.authToken,email:m,profile:p,protectedProfile:w,userData:sr.userData})};throw new hs.UserAlreadySignedIn(sr.session.username)}const g=rr(rr({},a),{},{username:f,userId:h,authToken:l});return await ur(g,u,c),{user:sr.buildUserResult({username:f,userId:h,authToken:l,email:m,profile:p,protectedProfile:w,userData:sr.userData})}}catch(e){if("Invalid seed"===e.message)return{lastUsedUsername:s};throw cr(e),e}},Ir=async(e,t)=>{const s=_s.getSeedString(e,t);if(!s)throw new hs.KeyNotFound(or);const a=i.a.decode(s);return await ja.hkdf.importHkdfKey(a)};var Pr={signUp:async e=>{try{(e=>{if(wr(e),e.profile&&br(e.profile),e.email&&"string"!=typeof e.email)throw new hs.EmailNotValid})(e);const{password:t,profile:s,passwordHashAlgo:a,rememberMe:r="session"}=e,n=e.username.toLowerCase(),o=e.email&&e.email.toLowerCase(),c=ws(),u=await ja.generateSeed(),d=fr(e.sessionLength),{sessionId:h,creationDate:l,expirationDate:f,userId:m,authToken:p}=await(async(e,t,s,a,r,n,i)=>{const{passwordToken:o,passwordSalts:c,passwordBasedBackup:u}=await gr(t,s,a),{ecKeyData:d,keySalts:h}=await yr(s);try{return await Es(e,o,d,c,h,r,n,u,i)}catch(t){hr(t),lr(t,e)}})(n,t,u,a,o,s,d),w={username:n,userId:m,sessionId:h,creationDate:l,expirationDate:f,authToken:p},g=i.a.encode(u);return _s.saveSeedString(r,c,n,g),_s.signInSession(r,n,h,l,f),await ur(w,g,r),sr.buildUserResult({username:n,userId:m,authToken:p,email:o,profile:s,userData:sr.userData})}catch(e){switch(e.name){case"ParamsMustBeObject":case"UsernameMissing":case"UsernameAlreadyExists":case"UsernameCannotBeBlank":case"UsernameMustBeString":case"UsernameTooLong":case"PasswordMissing":case"PasswordCannotBeBlank":case"PasswordTooShort":case"PasswordTooLong":case"PasswordMustBeString":case"EmailNotValid":case"ProfileMustBeObject":case"ProfileCannotBeEmpty":case"ProfileHasTooManyKeys":case"ProfileKeyTooLong":case"ProfileValueMustBeString":case"ProfileValueCannotBeBlank":case"ProfileValueTooLong":case"RememberMeValueNotValid":case"SessionLengthMustBeNumber":case"SessionLengthTooShort":case"SessionLengthTooLong":case"TrialExceededLimit":case"AppIdNotSet":case"AppIdNotValid":case"DomainNotWhitelisted":case"UserAlreadySignedIn":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},signOut:async()=>{try{if(!sr.session.username)throw new hs.UserNotSignedIn;try{await sr.signOut()}catch(e){throw cr(e),e}}catch(e){switch(e.name){case"UserNotSignedIn":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},signIn:async e=>{try{wr(e);const t=e.username.toLowerCase(),{password:s,passwordHashAlgo:a,rememberMe:r="session"}=e,n=ws(),o=await(async e=>{try{return await Bs(e)}catch(e){if(cr(e),dr(e),e.response&&"User not found"===e.response.data)throw new hs.UsernameOrPasswordMismatch;throw e}})(t),{passwordHkdfKey:c,passwordToken:u}=await Mr(s,o,a),d=fr(e.sessionLength),h=await(async(e,t,s)=>{try{return await Ns(e,t,s)}catch(e){if(cr(e),dr(e),hr(e),e.response&&"Invalid password"===e.response.data)throw new hs.UsernameOrPasswordMismatch;if(e.response&&"User pending deletion"===e.response.data)throw new hs.UserPendingDeletion;throw e}})(t,u,d),{userId:l,email:f,profile:m,passwordBasedBackup:p,protectedProfile:w,usedTempPassword:g,changePassword:y}=h,b=rr(rr({},h.session),{},{username:t,userId:l});let v;if(!y){const e=_s.getSeedString(n,t);let s;if(!e&&g)throw new hs.KeyNotFound(ir);g||(s=await(async(e,t)=>{const{passwordBasedEncryptionKeySalt:s,passwordEncryptedSeed:a}=t,r=await ja.aesGcm.getPasswordBasedEncryptionKey(e,i.a.decode(s)),n=await ja.aesGcm.decrypt(r,i.a.decode(a));return i.a.encode(n)})(c,p),_s.saveSeedString(r,n,t,s)),v=s||e}_s.signInSession(r,t,b.sessionId,b.creationDate,b.expirationDate);try{await ur(b,v,r,y)}catch(e){if(g&&"Invalid seed"===e.message)throw new hs.KeyNotFound(ir);throw e}return sr.buildUserResult({username:t,userId:l,authToken:b.authToken,email:f,profile:m,protectedProfile:w,usedTempPassword:g,changePassword:y,userData:sr.userData})}catch(e){switch(e.name){case"ParamsMustBeObject":case"UsernameMissing":case"UsernameOrPasswordMismatch":case"UserPendingDeletion":case"UsernameCannotBeBlank":case"UsernameTooLong":case"UsernameMustBeString":case"PasswordMissing":case"PasswordCannotBeBlank":case"PasswordTooShort":case"PasswordTooLong":case"PasswordMustBeString":case"PasswordAttemptLimitExceeded":case"RememberMeValueNotValid":case"SessionLengthMustBeNumber":case"SessionLengthTooShort":case"SessionLengthTooLong":case"KeyNotFound":case"AppIdNotSet":case"AppIdNotValid":case"DomainNotWhitelisted":case"UserAlreadySignedIn":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},init:async e=>{try{if(!window.crypto.subtle)throw new hs.WebCryptoUnavailable;if("object"!=typeof e)throw new hs.ParamsMustBeObject;if(!Ga(e,"appId"))throw new hs.AppIdMissing;if("string"!=typeof e.appId)throw new hs.AppIdMustBeString;if(0===e.appId.length)throw new hs.AppIdCannotBeBlank;if(Ga(e,"updateUserHandler")&&"function"!=typeof e.updateUserHandler)throw new hs.UpdateUserHandlerMustBeFunction;if(Ga(e,"sessionLength")&&"number"!=typeof e.sessionLength)throw new hs.SessionLengthMustBeNumber;if(Ga(e,"allowServerSideEncryption")&&"boolean"!=typeof e.allowServerSideEncryption)throw new hs.AllowServerSideEncryptionMustBeBoolean;bs(e);return await Sr(e.appId,fr(e.sessionLength))}catch(e){switch(e.name){case"WebCryptoUnavailable":case"ParamsMustBeObject":case"AppIdMissing":case"AppIdAlreadySet":case"AppIdMustBeString":case"AppIdCannotBeBlank":case"AppIdNotValid":case"DomainNotWhitelisted":case"UpdateUserHandlerMustBeFunction":case"SessionLengthMustBeNumber":case"SessionLengthTooShort":case"SessionLengthTooLong":case"AllowServerSideEncryptionMustBeBoolean":case"UserAlreadySignedIn":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},updateUser:async e=>{try{if("object"!=typeof e)throw new hs.ParamsMustBeObject;if((e=>{if(!(Ga(e,"username")||Ga(e,"newPassword")||Ga(e,"email")||Ga(e,"profile")))throw new hs.ParamsMissing;const{username:t,currentPassword:s,newPassword:a,email:r,profile:n}=e;if(Ga(e,"username")&&mr(t),Ga(e,"newPassword")){if(!Ga(e,"currentPassword"))throw new hs.CurrentPasswordMissing;pr(s),pr(a)}if(r&&"string"!=typeof r)throw new hs.EmailNotValid;n&&br(n)})(e),sr.reconnecting)throw new hs.Reconnecting;if(!sr.connectionResolved)throw new hs.UserNotSignedIn;const t=sr.session.userId,s=e.newPassword&&!sr.keys.init&&sr.changePassword&&await ja.generateSeed(),a="UpdateUser",r=await(async(e,t)=>{if(e.username&&(e.username=e.username.toLowerCase()),e.newPassword){const[s,a,r]=await Promise.all([vr(),gr(e.newPassword,t||i.a.decode(sr.seedString)),t&&yr(t)]),{passwordToken:n}=await Mr(e.currentPassword,s,e.passwordHashAlgo);e.currentPasswordToken=n,delete e.currentPassword,e.passwordToken=a.passwordToken,e.passwordSalts=a.passwordSalts,e.passwordBasedBackup=a.passwordBasedBackup,delete e.newPassword,r&&(e.newKeyData=r)}return e.email?e.email=e.email.toLowerCase():Ga(e,"email")&&(e.email=!1),!e.profile&&Ga(e,"profile")&&(e.profile=!1),e})(rr({},e),s);if(sr.reconnecting)throw new hs.Reconnecting;if(!sr.connectionResolved)throw new hs.UserNotSignedIn;if(!sr.session||t!==sr.session.userId)throw new hs.ServiceUnavailable;try{r.username&&_s.saveSeedString(sr.rememberMe,ws(),r.username,sr.seedString);const e=(await sr.request(a,r)).data.updatedUser;if(sr.handleUpdateUser(e),s&&sr.session&&t===sr.session.userId){const t=i.a.encode(s);await sr.rotateKeys(t,r.newKeyData),_s.saveSeedString(sr.rememberMe,ws(),e.username,t);const{sessionId:a,creationDate:n,expirationDate:o}=sr.session;_s.signInSession(sr.rememberMe,e.username,a,n,o)}}catch(e){lr(e,r.username)}}catch(e){switch(e.name){case"ParamsMustBeObject":case"ParamsMissing":case"UsernameAlreadyExists":case"UsernameMustBeString":case"UsernameCannotBeBlank":case"UsernameTooLong":case"CurrentPasswordMissing":case"CurrentPasswordIncorrect":case"PasswordAttemptLimitExceeded":case"PasswordMustBeString":case"PasswordCannotBeBlank":case"PasswordTooShort":case"PasswordTooLong":case"EmailNotValid":case"ProfileMustBeObject":case"ProfileCannotBeEmpty":case"ProfileHasTooManyKeys":case"ProfileKeyTooLong":case"ProfileValueMustBeString":case"ProfileValueCannotBeBlank":case"ProfileValueTooLong":case"AppIdNotSet":case"AppIdNotValid":case"UserNotFound":case"UserNotSignedIn":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},deleteUser:async()=>{try{(()=>{if(sr.reconnecting)throw new hs.Reconnecting;if(!sr.keys.init&&sr.changePassword)throw new hs.UserMustChangePassword;if(!sr.keys.init)throw new hs.UserNotSignedIn})();const e=sr.session.username;_s.removeSeedString(ws(),e),_s.removeCurrentSession();try{const e="DeleteUser";await sr.request(e)}catch(e){throw cr(e),e}sr.close()}catch(e){switch(e.name){case"UserMustChangePassword":case"UserNotSignedIn":case"UserNotFound":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},forgotPassword:async e=>{try{if("object"!=typeof e)throw new hs.ParamsMustBeObject;if(Ga(e,"deleteEndToEndEncryptedData")&&"boolean"!=typeof e.deleteEndToEndEncryptedData)throw new hs.DeleteEndToEndEncryptedDataMustBeBoolean;if(!Ga(e,"username"))throw new hs.UsernameMissing;mr(e.username);const t=e.username.toLowerCase(),s=ws(),a="".concat(Va(ys()),"/api/auth/forgot-password?appId=").concat(s,"&username=").concat(encodeURIComponent(t),"&userbaseJsVersion=").concat(ps),r=new WebSocket(a+(Ga(e,"deleteEndToEndEncryptedData")?"&deleteEndToEndEncryptedData=".concat(e.deleteEndToEndEncryptedData):""));await new Promise((e,a)=>{setTimeout(()=>a(new hs.Timeout),15e3),r.onerror=()=>a(new hs.ServiceUnavailable),r.onmessage=async n=>{try{const o=JSON.parse(n.data);switch(o.route){case"ReceiveEncryptedToken":{const e=await Ir(s,t),a=new Uint8Array(o.encryptedForgotPasswordToken.data),n=await ja.diffieHellman.importKeyFromMaster(e,i.a.decode(o.dhKeySalt)),c=await ja.diffieHellman.getSharedKeyWithServer(n);let u;try{u=i.a.encode(await ja.aesGcm.decrypt(c,a))}catch(e){throw new hs.KeyNotFound(or)}r.send(JSON.stringify({action:"ForgotPassword",params:{forgotPasswordToken:u}}));break}case"ReceiveToken":{const e=await Ir(s,t),{ecdsaKeyEncryptionKeySalt:a,encryptedEcdsaPrivateKey:n,forgotPasswordToken:c}=o,u=await ja.ecdsa.importEcdsaKeyEncryptionKeyFromMaster(e,i.a.decode(a));let d;try{const e=await ja.aesGcm.decrypt(u,i.a.decode(n));d=await ja.ecdsa.getPrivateKeyFromRawPrivateKey(e)}catch(e){throw new hs.KeyNotFound(or)}const h=i.a.encode(await ja.ecdsa.sign(d,i.a.decode(c)));r.send(JSON.stringify({action:"ForgotPassword",params:{signedForgotPasswordToken:h}}));break}case"SuccessfullyForgotPassword":e();break;case"Error":{const e=o.data;switch(e.name){case"UsernameTooLong":throw new hs.UsernameTooLong(e.maxLen);case"AppIdNotValid":throw new hs.AppIdNotValid;case"UserNotFound":throw new hs.UserNotFound;case"UserEmailNotFound":throw new hs.UserEmailNotFound;default:throw o.status===p?new hs.ServiceUnavailable:new hs.UnknownServiceUnavailable(e)}}case"Ping":break;default:a(new Error("Received unknown message from userbase-server: ".concat(n.data)))}}catch(n){a(n)}}}),r.close()}catch(e){switch(e.name){case"ParamsMustBeObject":case"UsernameMissing":case"UsernameMustBeString":case"UsernameCannotBeBlank":case"UsernameTooLong":case"AppIdNotSet":case"AppIdNotValid":case"KeyNotFound":case"UserNotFound":case"UserEmailNotFound":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}}},Er=s(12),Br=s.n(Er);function Nr(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,a)}return s}function Ur(e){for(var t=1;t{if(sr.reconnecting)throw new hs.Reconnecting;if(!sr.keys.init&&sr.changePassword)throw new hs.UserMustChangePassword;if(!sr.keys.init||!Ar[sr.encryptionMode])throw new hs.UserNotSignedIn},kr=e=>{if(e.response){if("UserNotFound"===e.response.data)throw new hs.UserNotFound;if(e.response.status===p)throw new hs.InternalServerError;if(e.response.status===g)throw new hs.Timeout}else if(e.message&&-1!==e.message.indexOf("timeout"))throw new hs.Timeout};class Dr{constructor(e){this.startSeqNo=e,this.txSeqNo=null,this.transactions={},this.promiseResolve=null,this.promiseReject=null,this.index=null}getStartSeqNo(){return this.startSeqNo}getIndex(){return this.index}setIndex(e){this.index=e}async getResult(e){this.txSeqNo=e;const t=new Promise((e,t)=>{this.promiseResolve=e,this.promiseReject=t,setTimeout(()=>{t(new Error("timeout"))},3e4)});return this.verifyPromise(),t}verifyPromise(){(this.txSeqNo||0==this.txSeqNo)&&this.promiseResolve&&this.promiseReject&&this.transactions[this.txSeqNo]&&("Success"==this.transactions[this.txSeqNo]?this.promiseResolve():this.promiseReject(this.transactions[this.txSeqNo]))}addTransaction(e,t){this.transactions[e.seqNo]||(this.transactions[e.seqNo]=t,this.verifyPromise())}}class Kr{constructor(e,t,s,a){this.onChange=xr(e),this.items={},this.itemsPlaintextMetadata={},this.fileIds={};this.itemsIndex=new Br.a([],(e,t)=>e.seqNot.seqNo||e.seqNo===t.seqNo&&e.operationIndex>t.operationIndex?1:0),this.unverifiedTransactions=[],this.lastSeqNo=0,this.init=!1,this.dbKey=null,this.receivedMessage=t,this.usernamesByUserId=new Map,this.attributionEnabled=!1,this.shareTokenId=s,this.shareTokenHkdfKey=a,this.applyTransactionsQueue=new Ja,this.bundleChunks={}}async applyTransactions(e,t,s,a){for(let s=0;st=>{try{e(t)}catch(e){console.error("There was an error in your changeHandler.\n\n",e)}},Rr=(e,t,s)=>{e.onChange=xr(t);const a=e.receivedMessage;return e.receivedMessage=()=>{a(),s()},!!e.init&&(e.onChange(e.getItems()),e.receivedMessage(),!0)},Or=e=>{const t=e.slice(0,36),s=Fs(t,!0);if(!s||36!==s.length)throw new hs.ShareTokenInvalid;return s},Cr=async(e,t,s)=>{let a,r;try{a=(e=>{const t=i.a.decode(e);return{shareTokenId:Or(t),shareTokenSeed:t.slice(36)}})(e),r=await ja.hkdf.importHkdfKey(a.shareTokenSeed)}catch(e){throw new hs.ShareTokenInvalid}const{shareTokenId:n}=a,{databaseId:o,validationMessage:c,signedValidationMessage:u}=await sr.authenticateShareToken(n,r);sr.state.shareTokenIdToDbId[n]=o,await _r(o,t,s,n,r,c,u)},_r=async(e,t,s,a,r,n,i)=>{const o=sr.state.databasesByDbId[e];if(o){if(Rr(o,t,s))return}else sr.state.databasesByDbId[e]=new Kr(t,s,a,r);const c={databaseId:e,validationMessage:n,signedValidationMessage:i};await sr.request("OpenDatabaseByDatabaseId",c)},Fr=async(e,t)=>{try{let s,a;const r=new Promise((e,t)=>{s=e,a=setTimeout(()=>t(new Error("timeout")),3e4)}),{dbNameHash:n,newDatabaseParams:i,databaseId:o,shareToken:c}=t;try{n?await(async(e,t,s,a)=>{const r=sr.state.databases[e];if(r){if(Rr(r,s,a))return}else sr.state.databases[e]=new Kr(s,a);const n={dbNameHash:e,newDatabaseParams:t};await sr.request("OpenDatabase",n)})(n,i,e,s):o?await _r(o,e,s):c&&await Cr(c,e,s),await r}catch(e){if(clearTimeout(a),e.response&&e.response.data){const t=e.response.data;if("Database already creating"===t)throw new hs.DatabaseAlreadyOpening;if("Database is owned by user"===t){if(o)throw new hs.DatabaseIdNotAllowedForOwnDatabase;if(c)throw new hs.ShareTokenNotAllowedForOwnDatabase}else if("Database key not found"===t||"Database not found"===t)throw new hs.DatabaseNotFound;switch(t.name){case"SubscriptionNotFound":throw new hs.SubscriptionNotFound;case"SubscriptionInactive":throw new hs.SubscriptionInactive(t.subscriptionStatus);case"TrialExpired":throw new hs.TrialExpired}}throw e}}catch(e){throw kr(e),e}},Lr=e=>{if("server-side"===e&&!Ms())throw new hs.ServerSideEncryptionNotEnabledInClient},jr=e=>{if("object"!=typeof e)throw new hs.ParamsMustBeObject;if(Ga(e,"databaseName")){if((e=>{if("string"!=typeof e)throw new hs.DatabaseNameMustBeString;if(0===e.length)throw new hs.DatabaseNameCannotBeBlank;if(e.length>100)throw new hs.DatabaseNameTooLong(100)})(e.databaseName),Ga(e,"databaseId"))throw new hs.DatabaseIdNotAllowed;if(Ga(e,"shareToken"))throw new hs.ShareTokenNotAllowed;if(!e.allowVerifiedUsersDatabase&&"__userbase_verified_users"===e.databaseName)throw new hs.DatabaseNameRestricted("__userbase_verified_users")}else if(Ga(e,"databaseId")){if((e=>{if("string"!=typeof e)throw new hs.DatabaseIdMustBeString;if(0===e.length)throw new hs.DatabaseIdCannotBeBlank;if(36!==e.length)throw new hs.DatabaseIdInvalidLength(36)})(e.databaseId),Ga(e,"shareToken"))throw new hs.ShareTokenNotAllowed}else{if(!Ga(e,"shareToken"))throw new hs.DatabaseNameMissing;if("string"!=typeof e.shareToken)throw new hs.ShareTokenInvalid}if(Ga(e,"encryptionMode")&&!Ar[e.encryptionMode])throw new hs.EncryptionModeNotValid(Ar);Tr()},qr=async e=>{try{if(jr(e),!Ga(e,"changeHandler"))throw new hs.ChangeHandlerMissing;const{databaseName:t,databaseId:s,shareToken:a,changeHandler:r,encryptionMode:n=sr.encryptionMode}=e;if("function"!=typeof r)throw new hs.ChangeHandlerMustBeFunction;if(Lr(n),t){const e="server-side"===n?t:sr.state.dbNameToHash[t]||await ja.hmac.signString(sr.keys.hmacKey,t);"end-to-end"===n&&(sr.state.dbNameToHash[t]=e);const s={dbNameHash:e,newDatabaseParams:await(async(e,t)=>{const s=Ds()(),a=await ja.aesGcm.generateKey(),r=await ja.aesGcm.getKeyStringFromKey(a),[n,i]=await Promise.all([ja.aesGcm.encryptString(sr.keys.encryptionKey,r),ja.aesGcm.encryptString(a,e)]),o={dbId:s,encryptedDbKey:n,encryptedDbName:i,attribution:!0};return"server-side"===t&&(o.plaintextDbKey=r),o.fingerprint=await ln(),o})(t,n)};await Fr(r,s)}else if(s){const e={databaseId:s};await Fr(r,e)}else{const e={shareToken:a};await Fr(r,e)}}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseAlreadyOpening":case"DatabaseNameMustBeString":case"DatabaseNameMissing":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"DatabaseIdNotAllowedForOwnDatabase":case"ShareTokenNotAllowed":case"ShareTokenInvalid":case"ShareTokenNotFound":case"ShareTokenNotAllowedForOwnDatabase":case"DatabaseNotFound":case"ChangeHandlerMissing":case"ChangeHandlerMustBeFunction":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"UserMustChangePassword":case"UserNotSignedIn":case"UserNotFound":case"SubscriptionNotFound":case"SubscriptionInactive":case"TrialExpired":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},Vr=(e,t,s,a="end-to-end")=>{Lr(a);const r=s&&Or(i.a.decode(s)),n="server-side"===a?e:sr.state.dbNameToHash[e],o=e?sr.state.databases[n]:sr.state.databasesByDbId[t||sr.state.shareTokenIdToDbId[r]];if(!o||!o.init)throw new hs.DatabaseNotOpen;return o},Hr=async e=>{try{jr(e);const t=Vr(e.databaseName,e.databaseId,e.shareToken,e.encryptionMode||sr.encryptionMode),s="Insert",a=await Gr(t,e);await zr(t,s,a)}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseNotOpen":case"DatabaseNameMissing":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"ShareTokenInvalid":case"DatabaseIsReadOnly":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"ItemIdMustBeString":case"ItemIdCannotBeBlank":case"ItemIdTooLong":case"ItemMissing":case"ItemInvalid":case"ItemTooLarge":case"ItemAlreadyExists":case"UserMustChangePassword":case"UserNotSignedIn":case"UserNotFound":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},Gr=async(e,t)=>{if(!Ga(t,"item"))throw new hs.ItemMissing;const{item:s,itemId:a,writeAccess:r}=t;if(Ga(t,"itemId")){if("string"!=typeof a)throw new hs.ItemIdMustBeString;if(0===a.length)throw new hs.ItemIdCannotBeBlank;if(a.length>100)throw new hs.ItemIdTooLong(100)}const n=JSON.stringify(s);if(!n)throw new hs.ItemInvalid;if(Ha(n)>10240)throw new hs.ItemTooLarge(10);const i=a||Ds()(),o={id:i,item:s};return{itemKey:await ja.hmac.signString(sr.keys.hmacKey,i),encryptedItem:await ja.aesGcm.encryptJson(e.dbKey,o),writeAccess:r}},Jr=async e=>{try{jr(e);const t=Vr(e.databaseName,e.databaseId,e.shareToken,e.encryptionMode||sr.encryptionMode),s="Update",a=await Wr(t,e);await zr(t,s,a)}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseNotOpen":case"DatabaseNameMissing":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"ShareTokenInvalid":case"DatabaseIsReadOnly":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"ItemIdMissing":case"ItemIdMustBeString":case"ItemIdCannotBeBlank":case"ItemIdTooLong":case"ItemMissing":case"ItemInvalid":case"ItemTooLarge":case"ItemDoesNotExist":case"ItemUpdateConflict":case"WriteAccessParamNotAllowed":case"TransactionUnauthorized":case"UserMustChangePassword":case"UserNotSignedIn":case"UserNotFound":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},Wr=async(e,t)=>{if(!Ga(t,"item"))throw new hs.ItemMissing;if(!Ga(t,"itemId"))throw new hs.ItemIdMissing;!t.writeAccess&&Ga(t,"writeAccess")&&(t.writeAccess=!1);const{item:s,itemId:a,writeAccess:r}=t;if("string"!=typeof a)throw new hs.ItemIdMustBeString;if(0===a.length)throw new hs.ItemIdCannotBeBlank;if(a.length>100)throw new hs.ItemIdTooLong(100);if(!e.itemExists(a))throw new hs.ItemDoesNotExist;const n=JSON.stringify(s);if(!n)throw new hs.ItemInvalid;if(Ha(n)>10240)throw new hs.ItemTooLarge(10);const i={id:a,item:s,__v:e.getItemVersionNumber(a)+1};return{itemKey:await ja.hmac.signString(sr.keys.hmacKey,a),encryptedItem:await ja.aesGcm.encryptJson(e.dbKey,i),writeAccess:r}},Yr=async(e,t)=>{if(!Ga(t,"itemId"))throw new hs.ItemIdMissing;const{itemId:s}=t;if("string"!=typeof s)throw new hs.ItemIdMustBeString;if(0===s.length)throw new hs.ItemIdCannotBeBlank;if(s.length>100)throw new hs.ItemIdTooLong(100);if(!e.itemExists(s))throw new hs.ItemDoesNotExist;const a={id:s,__v:e.getItemVersionNumber(s)+1};return{itemKey:await ja.hmac.signString(sr.keys.hmacKey,s),encryptedItem:await ja.aesGcm.encryptJson(e.dbKey,a)}},zr=async(e,t,s)=>{try{const a=e.registerUnverifiedTransaction(),r=Ur(Ur({},s),{},{dbId:e.dbId,dbNameHash:e.dbNameHash}),n=(await sr.request(t,r)).data.sequenceNo;return await a.getResult(n),e.unregisterUnverifiedTransaction(a),n}catch(e){if(kr(e),e.response){if("DatabaseIsReadOnly"===e.response.data.name)throw new hs.DatabaseIsReadOnly;if("UserNotFound"===e.response.data.message)throw new hs.UserNotFound(e.response.data.username)}throw e}},Zr=async(e,t,s,a,r,n,i,o)=>{const c=await(async e=>{const t=new FileReader;return new Promise((s,a)=>{t.onload=e=>{e.target.error?a(e.target.error):s(e.target.result)},t.readAsArrayBuffer(e)})})(t),[u,d]=await ja.aesGcm.generateAndEncryptKeyEncryptionKey(r),h=await ja.aesGcm.encrypt(u,c),l={dbId:s,chunkNumber:n,fileId:a,chunk:Fs(new Uint8Array(h)),chunkEncryptionKey:Fs(new Uint8Array(d))},f=(async(e,t,s,a)=>{await e,t.bytesTransferred+=a,s&&s(Ur({},t))})(sr.request("UploadFileChunk",l),i,o,t.size);e.push(f),10===e.length&&(await Promise.all(e),e.length=0)},Xr=async(e,t,s,a)=>{try{const r="GetChunk",n={dbId:e,fileId:t,chunkNumber:s},i=(await sr.request(r,n)).data,o=new Uint8Array(new Uint16Array(Ls(i.chunk))).buffer,c=new Uint8Array(new Uint16Array(Ls(i.chunkEncryptionKey))).buffer,u=await ja.aesGcm.decrypt(a,c),d=await ja.aesGcm.getKeyFromRawKey(u);return await ja.aesGcm.decrypt(d,o)}catch(e){throw kr(e),e}},Qr=async(e,t,s)=>{const{username:a,senderUsername:r,verificationValues:n}=s,{sentSignature:o,receivedSignature:c,senderEcdsaPublicKey:u}=n,d=t[a]&&t[a].record.fingerprint,h=i.a.decode(u),l=t[r]&&t[r].record.fingerprint||await hn(h),f=await ja.ecdsa.getPublicKeyFromRawPublicKey(h),m=await rn(e,d),p=await ja.ecdsa.verifyString(f,o,m),w=await ja.ecdsa.getPublicKeyFromRawPublicKey(i.a.decode(n.recipientEcdsaPublicKey)),g=await rn(e,l),y=await ja.ecdsa.verifyString(w,c,g);return p&&y},$r=async(e,t,s,a,r)=>{const{mySentSignature:n,myReceivedSignature:o}=r,c=await rn(e,t),u=await ja.ecdsa.verifyString(a,o,c);if(!u)return u;const d=await rn(e,s),h=await ja.ecdsa.getPublicKeyFromRawPublicKey(i.a.decode(r.mySenderEcdsaPublicKey));return await ja.ecdsa.verifyString(h,n,d)&&u},en=async(e,t,s,a,r)=>{const{sentSignature:n,receivedSignature:o}=r,c=await rn(e,t),u=await ja.ecdsa.verifyString(a,n,c);if(!u)return u;const d=await rn(e,s),h=await ja.ecdsa.getPublicKeyFromRawPublicKey(i.a.decode(r.recipientEcdsaPublicKey)),l=await ja.ecdsa.verifyString(h,o,d);return u&&l},tn=async(e,t,s,a,r)=>{const n=await ja.ecdsa.getPublicKeyFromPrivateKey(sr.keys.ecdsaPrivateKey),i=await ln();for(let o=0;o{const{databaseId:n,databaseNameHash:o,isOwner:c,readOnly:u,resharingAllowed:d,senderUsername:h}=e;let l,f;if(e.encryptedDbKey||e.plaintextDbKey){const s=e.plaintextDbKey||await ja.aesGcm.decryptString(t,e.encryptedDbKey);if(l=await ja.aesGcm.getKeyFromKeyString(s),f=await ja.aesGcm.decryptString(l,e.databaseName),c&&"__userbase_verified_users"===f)return null}else{if(e.wrappedDbKey)return null;{let a;try{const{ephemeralPublicKey:t,signedEphemeralPublicKey:r,sharedEncryptedDbKey:n}=e;a=i.a.decode(e.senderEcdsaPublicKey);const o=await ja.ecdsa.getPublicKeyFromRawPublicKey(a);if(!await ja.ecdsa.verify(o,i.a.decode(r),i.a.decode(t)))throw new hs.ServiceUnavailable;const c=await ja.ecdh.getPublicKeyFromRawPublicKey(i.a.decode(t)),u=await ja.ecdh.computeSharedKeyEncryptionKey(c,s),d=await ja.aesGcm.decryptString(u,n);l=await ja.aesGcm.getKeyFromKeyString(d),f=await ja.aesGcm.decryptString(l,e.databaseName)}catch(e){return null}const r=await hn(a),n=await nn(l,r),c=await ja.aesGcm.getKeyStringFromKey(l),u="SaveDatabase",d={databaseNameHash:o,encryptedDbKey:await ja.aesGcm.encryptString(t,c),receivedSignature:n};sr.request(u,d)}}const m={databaseName:f,databaseId:n,isOwner:c,readOnly:u,resharingAllowed:d,encryptionMode:e.plaintextDbKey?"server-side":"end-to-end"},p=await(async(e,t,s,a,r,n)=>{const i=[],o={databaseId:e,databaseNameHash:t};let c=await sr.request("GetDatabaseUsers",o);for(i.push(...await tn(s,c.data.users,a,r,n));c.data.nextPageTokenLessThanUserId||c.data.nextPageTokenMoreThanUserId;)o.nextPageTokenLessThanUserId=c.data.nextPageTokenLessThanUserId,o.nextPageTokenMoreThanUserId=c.data.nextPageTokenMoreThanUserId,c=await sr.request("GetDatabaseUsers",o),i.push(...await tn(s,c.data.users,a,r,n));return i})(n,o,l,a,r,h);return c||(e=>{for(let t=0;t{let a;Lr(s);try{a=Vr(e,t,null,s)}catch(r){const n="GetDatabases",i=e?{dbNameHash:"server-side"===s?e:await ja.hmac.signString(sr.keys.hmacKey,e)}:{databaseId:t},o=(await sr.request(n,i)).data.databases;if(!o||!o.length)throw new hs.DatabaseNotFound;a=o[0],a.dbNameHash=a.databaseNameHash,a.dbId=a.databaseId}return a},rn=async(e,t)=>{const s=await ja.aesGcm.getRawKeyFromKey(e),a=await ja.sha256.hash(s),r=await ja.hmac.importKeyFromRawBits(a);return await ja.hmac.signString(r,t)},nn=async(e,t)=>{const s=await rn(e,t);return await ja.ecdsa.signString(sr.keys.ecdsaPrivateKey,s)},on=async e=>{let t;return e.dbKey?t=await ja.aesGcm.getKeyStringFromKey(e.dbKey):(t=e.plaintextDbKey||await ja.aesGcm.decryptString(sr.keys.encryptionKey,e.encryptedDbKey),e.dbKey=await ja.aesGcm.getKeyFromKeyString(t)),t},cn=async(e,t,s,a,r)=>{const{databaseName:n,databaseId:o}=e,c=e.username.toLowerCase();try{const[e,u,d]=await Promise.all([Ts(c),a&&fn(),an(n,o,r)]);if(!e.ecdhPublicKey||!e.ecdsaPublicKey)throw new hs.UserUnableToReceiveDatabase;const h=i.a.decode(e.ecdsaPublicKey),l=await hn(h);a&&await(async(e,t,s)=>{let a,r;const n=Object.keys(s);for(let i=0;i{if("string"!=typeof e)throw new hs.UsernameMustBeString;if(0===e.length)throw new hs.UsernameCannotBeBlank},dn=e=>{if(Ga(e,"shareToken"))throw new hs.ShareTokenNotAllowed;if(Ga(e,"username")&&un(e.username),Ga(e,"readOnly")&&"boolean"!=typeof e.readOnly)throw new hs.ReadOnlyMustBeBoolean;if(Ga(e,"resharingAllowed")&&"boolean"!=typeof e.resharingAllowed)throw new hs.ResharingAllowedMustBeBoolean;if(Ga(e,"requireVerified")&&"boolean"!=typeof e.requireVerified)throw new hs.RequireVerifiedMustBeBoolean},hn=async e=>{const t=await ja.sha256.hash(e);return i.a.encode(t)},ln=async()=>{const e=await ja.ecdsa.getPublicKeyFromPrivateKey(sr.keys.ecdsaPrivateKey),t=await ja.ecdsa.getRawPublicKeyFromPublicKey(e);return await hn(t)},fn=async()=>{await qr({databaseName:"__userbase_verified_users",changeHandler:()=>{},allowVerifiedUsersDatabase:!0,encryptionMode:"end-to-end"});const e=sr.state.dbNameToHash.__userbase_verified_users;return sr.state.databases[e].items};var mn={openDatabase:qr,getDatabases:async e=>{try{void 0!==e&&jr(e),Tr();const{encryptionKey:t,ecdhPrivateKey:s}=sr.keys,a=sr.session.username;if(e&&Ga(e,"shareToken"))throw new hs.ShareTokenNotAllowed;const r=e&&e.encryptionMode||sr.encryptionMode;Lr(r);try{const n=[],i="GetDatabases",o=e&&{databaseId:e.databaseId,dbNameHash:"server-side"===r?e.databaseName:e.databaseName&&await ja.hmac.signString(sr.keys.hmacKey,e.databaseName)};let[c,u]=await Promise.all([sr.request(i,o),fn()]),d=await Promise.all(c.data.databases.map(e=>sn(e,t,s,u,a)));for(n.push(...d);c.data.nextPageToken;){const e={nextPageToken:c.data.nextPageToken};c=await sr.request(i,e),d=await Promise.all(c.data.databases.map(e=>sn(e,t,s,u,a))),n.push(...d)}return{databases:n.filter(e=>null!==e)}}catch(e){throw kr(e),e}}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"UserMustChangePassword":case"UserNotSignedIn":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},insertItem:Hr,updateItem:Jr,deleteItem:async e=>{try{jr(e);const t=Vr(e.databaseName,e.databaseId,e.shareToken,e.encryptionMode||sr.encryptionMode),s="Delete",a=await Yr(t,e);await zr(t,s,a)}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseNotOpen":case"DatabaseNameMissing":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"ShareTokenInvalid":case"DatabaseIsReadOnly":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"ItemIdMissing":case"ItemIdMustBeString":case"ItemIdCannotBeBlank":case"ItemIdTooLong":case"ItemDoesNotExist":case"ItemUpdateConflict":case"TransactionUnauthorized":case"UserMustChangePassword":case"UserNotSignedIn":case"UserNotFound":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},putTransaction:async e=>{try{if(jr(e),!Ga(e,"operations"))throw new hs.OperationsMissing;const{databaseName:t,databaseId:s,shareToken:a,operations:r,encryptionMode:n=sr.encryptionMode}=e;if(!Array.isArray(r))throw new hs.OperationsMustBeArray;const i=Vr(t,s,a,n),o="BatchTransaction",c=await Promise.all(r.map(e=>{const t=e.command;switch(t){case"Insert":return Gr(i,e);case"Update":return Wr(i,e);case"Delete":return Yr(i,e);default:throw new hs.CommandNotRecognized(t)}})),u=await Promise.all(c),d={operations:r.map((e,t)=>Ur({command:e.command},u[t]))};try{await zr(i,o,d)}catch(e){if(e.response&&"OperationsExceedLimit"===e.response.data.error)throw new hs.OperationsExceedLimit(e.response.data.limit);throw e}}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseNotOpen":case"DatabaseNameMissing":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"ShareTokenInvalid":case"DatabaseIsReadOnly":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"OperationsMissing":case"OperationsMustBeArray":case"OperationsConflict":case"OperationsExceedLimit":case"CommandNotRecognized":case"ItemIdMissing":case"ItemIdMustBeString":case"ItemIdCannotBeBlank":case"ItemIdTooLong":case"ItemMissing":case"ItemInvalid":case"ItemTooLarge":case"ItemAlreadyExists":case"ItemDoesNotExist":case"ItemUpdateConflict":case"WriteAccessParamNotAllowed":case"TransactionUnauthorized":case"UserMustChangePassword":case"UserNotSignedIn":case"UserNotFound":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},uploadFile:async e=>{try{(e=>{if(jr(e),Ga(e,"progressHandler")&&"function"!=typeof e.progressHandler)throw new hs.ProgressHandlerMustBeFunction})(e);const t=Vr(e.databaseName,e.databaseId,e.shareToken,e.encryptionMode||sr.encryptionMode),{dbId:s}=t;try{const{itemKey:a,fileMetadata:r}=await(async(e,t)=>{if(!Ga(e,"itemId"))throw new hs.ItemIdMissing;if(!Ga(e,"file"))throw new hs.FileMissing;const{itemId:s,file:a}=e;if("string"!=typeof s)throw new hs.ItemIdMustBeString;if(0===s.length)throw new hs.ItemIdCannotBeBlank;if(s.length>100)throw new hs.ItemIdTooLong(100);if(!t.itemExists(s))throw new hs.ItemDoesNotExist;if(!(a instanceof File))throw new hs.FileMustBeFile;if(0===a.size)throw new hs.FileCannotBeEmpty;const r=await ja.hmac.signString(sr.keys.hmacKey,s),n=t.getFileVersionNumber(s);return{itemKey:r,fileMetadata:{itemId:s,__v:void 0===n?0:n+1,fileName:a.name,fileSize:a.size,fileType:a.type}}})(e,t),[n,o]=await ja.aesGcm.generateAndEncryptKeyEncryptionKey(t.dbKey),c=await ja.aesGcm.encryptJson(n,r),{data:{fileId:u}}=await sr.request("GenerateFileId",{dbId:t.dbId}),d=e.file;let h=0,l=0,f=[];const m={bytesTransferred:0};for(;h{const n={dbId:e.dbId,fileId:t,itemKey:s,fileMetadata:a,fileEncryptionKey:i.a.encode(r)};await zr(e,"CompleteFileUpload",n)})(t,u,a,c,o)}catch(e){if(kr(e),e.response&&"DatabaseIsReadOnly"===e.response.data)throw new hs.DatabaseIsReadOnly;throw e}}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseNotOpen":case"DatabaseNameMissing":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"ShareTokenInvalid":case"DatabaseIsReadOnly":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"ItemIdMissing":case"ItemIdMustBeString":case"ItemIdCannotBeBlank":case"ItemIdTooLong":case"ItemDoesNotExist":case"TransactionUnauthorized":case"FileMustBeFile":case"FileCannotBeEmpty":case"FileMissing":case"FileUploadConflict":case"ProgressHandlerMustBeFunction":case"UserMustChangePassword":case"UserNotSignedIn":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},getFile:async e=>{try{(e=>{if(jr(e),!Ga(e,"fileId"))throw new hs.FileIdMissing;const{fileId:t,range:s}=e;if("string"!=typeof t)throw new hs.FileIdMustBeString;if(0===t.length)throw new hs.FileIdCannotBeBlank;if(t.length>100)throw new hs.FileIdTooLong(100);if(Ga(e,"range")){if("object"!=typeof s)throw new hs.RangeMustBeObject;if(!Ga(s,"start"))throw new hs.RangeMissingStart;if(!Ga(s,"end"))throw new hs.RangeMissingEnd;const{start:e,end:t}=s;if("number"!=typeof e)throw new hs.RangeStartMustBeNumber;if("number"!=typeof t)throw new hs.RangeEndMustBeNumber;if(e<0)throw new hs.RangeStartMustBeGreaterThanZero;if(t<=e)throw new hs.RangeEndMustBeGreaterThanRangeStart}})(e);const t=Vr(e.databaseName,e.databaseId,e.shareToken,e.encryptionMode||sr.encryptionMode),{dbId:s}=t,{fileId:a,range:r}=e,n=t.fileIds[a],i=t.items[n];if(!i||!i.file)throw new hs.FileNotFound;const{file:{fileName:o,fileSize:c,fileType:u,fileEncryptionKey:d}}=i;if(r&&r.end>c)throw new hs.RangeEndMustBeLessThanFileSize;const h=r?await(async(e,t,s,a)=>{const{start:r,end:n}=a,i=[],o=Math.floor(r/524288),c=Math.floor(n/524288)-(n%524288==0?1:0);let u=o;for(;u<=c;){let a=await Xr(e,t,u,s);u===o&&u===c&&n%524288?a=a.slice(r%524288,n%524288):u===o?a=a.slice(r%524288):u===c&&n%524288&&(a=a.slice(0,n%524288)),i.push(a),u+=1}return i})(s,a,d,r):await(async(e,t,s,a)=>{const r=[];let n=0;const i=a<524288?0:Math.floor(a/524288)-(a%524288==0?1:0);for(;n<=i;){const a=await Xr(e,t,n,s);r.push(a),n+=1}return r})(s,a,d,c);return{file:new File(h,o,{type:u})}}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseNotOpen":case"DatabaseNameMissing":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"ShareTokenInvalid":case"DatabaseIsReadOnly":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"FileIdMissing":case"FileIdMustBeString":case"FileIdCannotBeBlank":case"FileIdTooLong":case"FileNotFound":case"RangeMustBeObject":case"RangeMissingStart":case"RangeMissingEnd":case"RangeStartMustBeNumber":case"RangeEndMustBeNumber":case"RangeStartMustBeGreaterThanZero":case"RangeEndMustBeGreaterThanRangeStart":case"RangeEndMustBeLessThanFileSize":case"UserMustChangePassword":case"UserNotSignedIn":case"UserNotFound":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},shareDatabase:async e=>{try{jr(e),dn(e);const t=!Ga(e,"readOnly")||e.readOnly,s=!!Ga(e,"resharingAllowed")&&e.resharingAllowed,a=!Ga(e,"requireVerified")||e.requireVerified,r=e.encryptionMode||sr.encryptionMode;Lr(r);let n={};return Ga(e,"username")?await cn(e,t,s,a,r):n.shareToken=await(async(e,t,s)=>{try{const{databaseName:a,databaseId:r}=e;if(Ga(e,"requireVerified"))throw new hs.RequireVerifiedParamNotNecessary;if(Ga(e,"resharingAllowed"))throw new hs.ResharingAllowedParamNotAllowed("when retrieving a share token");const n=ja.generateSeed(),o=await ja.hkdf.importHkdfKey(n),c=ja.hkdf.generateSalt(),u=await ja.aesGcm.importKeyFromMaster(o,c),d=await an(a,r,s),h=await on(d),l=await ja.aesGcm.encryptString(u,h),{ecdsaPublicKey:f,encryptedEcdsaPrivateKey:m,ecdsaKeyEncryptionKeySalt:p}=await ja.ecdsa.generateEcdsaKeyData(o),w="ShareDatabaseToken",g={databaseId:d.dbId,databaseNameHash:d.dbNameHash,readOnly:t,keyData:{shareTokenEncryptedDbKey:l,shareTokenEncryptionKeySalt:i.a.encode(c),shareTokenPublicKey:f,shareTokenEncryptedEcdsaPrivateKey:m,shareTokenEcdsaKeyEncryptionKeySalt:p}},y=await sr.request(w,g),{shareTokenId:b}=y.data,v=Ls(b,!0);return i.a.encode(js(v,n))}catch(e){if(kr(e),e.response&&e.response.data)switch(e.response.data.message){case"DatabaseNotFound":throw new hs.DatabaseNotFound;case"ResharingNotAllowed":throw new hs.ResharingNotAllowed("Only the owner can generate a share token")}throw e}})(e,t,r),n}catch(e){switch(e.name){case"ParamsMustBeObject":case"DatabaseNameMissing":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"DatabaseNotFound":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"UsernameCannotBeBlank":case"UsernameMustBeString":case"ReadOnlyMustBeBoolean":case"ResharingAllowedMustBeBoolean":case"ResharingNotAllowed":case"ResharingWithWriteAccessNotAllowed":case"ResharingAllowedParamNotAllowed":case"RequireVerifiedMustBeBoolean":case"RequireVerifiedParamNotNecessary":case"SharingWithSelfNotAllowed":case"UserMustChangePassword":case"UserNotSignedIn":case"UserUnableToReceiveDatabase":case"UserNotFound":case"UserNotVerified":case"UserMustBeReverified":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},modifyDatabasePermissions:async e=>{try{if(jr(e),dn(e),!Ga(e,"username"))throw new hs.UsernameMissing;if(Ga(e,"revoke")){if("boolean"!=typeof e.revoke)throw new hs.RevokeMustBeBoolean;if(e.revoke){if(Ga(e,"readOnly"))throw new hs.ReadOnlyParamNotAllowed;if(Ga(e,"resharingAllowed"))throw new hs.ResharingAllowedParamNotAllowed("when revoking access to a database")}}else if(!Ga(e,"readOnly")&&!Ga(e,"resharingAllowed"))throw new hs.ParamsMissing;const{databaseName:t,databaseId:s,readOnly:a,resharingAllowed:r,revoke:n,encryptionMode:i=sr.encryptionMode}=e,o=e.username.toLowerCase();try{const e=await an(t,s,i),c="ModifyDatabasePermissions",u={databaseId:e.dbId,databaseNameHash:e.dbNameHash,username:o,readOnly:a,resharingAllowed:r,revoke:n};await sr.request(c,u)}catch(e){if(kr(e),e.response&&e.response.data)switch(e.response.data.message){case"SharingWithSelfNotAllowed":throw new hs.ModifyingOwnPermissionsNotAllowed;case"ModifyingOwnerPermissionsNotAllowed":throw new hs.ModifyingOwnerPermissionsNotAllowed;case"ResharingNotAllowed":throw new hs.ModifyingPermissionsNotAllowed;case"ResharingWithWriteAccessNotAllowed":throw new hs.GrantingWriteAccessNotAllowed;case"DatabaseNotFound":throw new hs.DatabaseNotFound;case"UserNotFound":throw new hs.UserNotFound}throw e}}catch(e){switch(e.name){case"ParamsMustBeObject":case"ParamsMissing":case"DatabaseNameMissing":case"DatabaseNameMustBeString":case"DatabaseNameCannotBeBlank":case"DatabaseNameTooLong":case"DatabaseNameRestricted":case"DatabaseIdMustBeString":case"DatabaseIdCannotBeBlank":case"DatabaseIdInvalidLength":case"DatabaseIdNotAllowed":case"ShareTokenNotAllowed":case"DatabaseNotFound":case"EncryptionModeNotValid":case"ServerSideEncryptionNotEnabledInClient":case"UsernameMissing":case"UsernameCannotBeBlank":case"UsernameMustBeString":case"ReadOnlyMustBeBoolean":case"ReadOnlyParamNotAllowed":case"ResharingAllowedMustBeBoolean":case"ResharingAllowedParamNotAllowed":case"RevokeMustBeBoolean":case"ModifyingOwnPermissionsNotAllowed":case"ModifyingOwnerPermissionsNotAllowed":case"ModifyingPermissionsNotAllowed":case"GrantingWriteAccessNotAllowed":case"UserMustChangePassword":case"UserNotSignedIn":case"UserNotFound":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},getVerificationMessage:async()=>{try{Tr();const e=sr.session.username,t=await ln();return{verificationMessage:((e,t)=>btoa(JSON.stringify({username:e,fingerprint:t})))(e,t)}}catch(e){switch(e.name){case"UserMustChangePassword":case"UserNotSignedIn":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},verifyUser:async e=>{try{if("object"!=typeof e)throw new hs.ParamsMustBeObject;if(Tr(),!Ga(e,"verificationMessage"))throw new hs.VerificationMessageMissing;const{verificationMessage:t}=e;if("string"!=typeof t)throw new hs.VerificationMessageMustBeString;if(0===t.length)throw new hs.VerificationMessageCannotBeBlank;const{username:s,fingerprint:a}=(e=>{try{const{username:t,fingerprint:s}=JSON.parse(atob(e));if(un(t),!s)throw new hs.VerificationMessageInvalid;return{username:t,fingerprint:s}}catch(e){throw new hs.VerificationMessageInvalid}})(t);if(s===sr.session.username||a===await ln())throw new hs.VerifyingSelfNotAllowed;await fn();const r="__userbase_verified_users",n=!0,i=s,o={fingerprint:a};try{await Hr({databaseName:r,itemId:i,item:o,allowVerifiedUsersDatabase:n})}catch(e){if("ItemAlreadyExists"!==e.name)throw e;await Jr({databaseName:r,itemId:i,item:o,allowVerifiedUsersDatabase:n})}}catch(e){switch(e.name){case"ParamsMustBeObject":case"VerificationMessageMissing":case"VerificationMessageMustBeString":case"VerificationMessageCannotBeBlank":case"VerificationMessageInvalid":case"VerifyingSelfNotAllowed":case"UserMustChangePassword":case"UserNotSignedIn":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}}};const pn=()=>{if(sr.reconnecting)throw new hs.Reconnecting;if(!sr.keys.init&&sr.changePassword)throw new hs.UserMustChangePassword;if(!sr.keys.init)throw new hs.UserNotSignedIn},wn=e=>{if(e.response){if(e.response.status===p)throw new hs.InternalServerError;if(e.response.status===g)throw new hs.Timeout}else if(e.message&&-1!==e.message.indexOf("timeout"))throw new hs.Timeout},gn=e=>{pn();const t=sr.userData.stripeData;if(!t.stripeAccountId)throw new hs.StripeAccountNotConnected;if("disabled"===t.paymentsMode)throw new hs.PaymentsDisabled;if(!Ga(window,"Stripe"))throw new hs.StripeJsLibraryMissing;if("object"!=typeof e)throw new hs.ParamsMustBeObject;if(!Ga(e,"successUrl"))throw new hs.SuccessUrlMissing;if("string"!=typeof e.successUrl)throw new hs.SuccessUrlMustBeString;const s=qa(e.successUrl);if("http"!==s&&"https"!==s){const e=!0;throw new hs.SuccessUrlInvalid(e)}if(!Ga(e,"cancelUrl"))throw new hs.CancelUrlMissing;if("string"!=typeof e.cancelUrl)throw new hs.CancelUrlMustBeString;const a=qa(e.cancelUrl);if("http"!==a&&"https"!==a){const e=!0;throw new hs.CancelUrlInvalid(e)}},yn=()=>{pn();const e=sr.userData.stripeData;if(!e.stripeAccountId)throw new hs.StripeAccountNotConnected;if("disabled"===e.paymentsMode)throw new hs.PaymentsDisabled;if("canceled"===e.subscriptionStatus)throw new hs.SubscriptionAlreadyCanceled};var bn={purchaseSubscription:async e=>{try{const t=sr.userData.stripeData;if(!t.cancelSubscriptionAt&&t.subscriptionStatus&&"canceled"!==t.subscriptionStatus)throw new hs.SubscriptionPlanAlreadyPurchased;gn(e);try{const s="PurchaseSubscription",a=(await sr.request(s,e)).data,r=vs("prod"===t.paymentsMode),n=await window.Stripe(r,{stripeAccount:t.stripeAccountId}).redirectToCheckout({sessionId:a});if(n.error)throw n.error}catch(e){if(wn(e),e.response)switch(e.response.data){case"PriceIdOrPlanIdAllowed":throw new hs.PriceIdOrPlanIdAllowed;case"PriceIdOrPlanIdMissing":throw new hs.PriceIdOrPlanIdMissing;case"SubscriptionPlanAlreadyPurchased":throw new hs.SubscriptionPlanAlreadyPurchased;case"SuccessUrlInvalid":throw new hs.SuccessUrlInvalid;case"CancelUrlInvalid":throw new hs.CancelUrlInvalid;default:if(e.response.data&&"StripeError"===e.response.data.name)throw new hs.StripeError(e.response.data)}throw e}}catch(e){switch(e.name){case"ParamsMustBeObject":case"SuccessUrlMissing":case"SuccessUrlMustBeString":case"SuccessUrlInvalid":case"CancelUrlMissing":case"CancelUrlMustBeString":case"CancelUrlInvalid":case"StripeError":case"StripeJsLibraryMissing":case"PriceIdOrPlanIdAllowed":case"PriceIdOrPlanIdMissing":case"SubscriptionPlanAlreadyPurchased":case"StripeAccountNotConnected":case"PaymentsDisabled":case"UserMustChangePassword":case"UserNotSignedIn":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},cancelSubscription:async()=>{try{yn();try{const e="CancelSubscription",t=(await sr.request(e)).data;return sr.userData.stripeData.cancelSubscriptionAt=t,{cancelSubscriptionAt:t}}catch(e){if(wn(e),e.response&&"SubscriptionNotFound"===e.response.data)throw new hs.SubscriptionNotFound;throw e}}catch(e){switch(e.name){case"SubscriptionNotFound":case"StripeAccountNotConnected":case"PaymentsDisabled":case"SubscriptionAlreadyCanceled":case"UserMustChangePassword":case"UserNotSignedIn":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},resumeSubscription:async()=>{try{yn();try{const e="ResumeSubscription";await sr.request(e),delete sr.userData.stripeData.cancelSubscriptionAt}catch(e){if(wn(e),e.response&&"SubscriptionNotFound"===e.response.data)throw new hs.SubscriptionNotFound;throw e}}catch(e){switch(e.name){case"SubscriptionNotFound":case"StripeAccountNotConnected":case"PaymentsDisabled":case"SubscriptionAlreadyCanceled":case"UserMustChangePassword":case"UserNotSignedIn":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}},updatePaymentMethod:async e=>{try{gn(e);const t=sr.userData.stripeData;if(!t.subscriptionStatus)throw new hs.SubscriptionNotPurchased;try{const s="UpdatePaymentMethod",a=(await sr.request(s,e)).data,r=vs("prod"===t.paymentsMode),n=await window.Stripe(r,{stripeAccount:t.stripeAccountId}).redirectToCheckout({sessionId:a});if(n.error)throw n.error}catch(e){if(wn(e),e.response){if("SuccessUrlInvalid"===e.response.data)throw new hs.SuccessUrlInvalid;if("CancelUrlInvalid"===e.response.data)throw new hs.CancelUrlInvalid}throw e}}catch(e){switch(e.name){case"ParamsMustBeObject":case"SuccessUrlMissing":case"SuccessUrlMustBeString":case"SuccessUrlInvalid":case"CancelUrlMissing":case"CancelUrlMustBeString":case"CancelUrlInvalid":case"StripeJsLibraryMissing":case"SubscriptionNotPurchased":case"StripeAccountNotConnected":case"PaymentsDisabled":case"UserMustChangePassword":case"UserNotSignedIn":case"TooManyRequests":case"ServiceUnavailable":throw e;default:throw new hs.UnknownServiceUnavailable(e)}}}};t.default={init:Pr.init,signUp:Pr.signUp,signIn:Pr.signIn,signOut:Pr.signOut,updateUser:Pr.updateUser,deleteUser:Pr.deleteUser,forgotPassword:Pr.forgotPassword,openDatabase:mn.openDatabase,insertItem:mn.insertItem,updateItem:mn.updateItem,deleteItem:mn.deleteItem,putTransaction:mn.putTransaction,uploadFile:mn.uploadFile,getFile:mn.getFile,getDatabases:mn.getDatabases,shareDatabase:mn.shareDatabase,modifyDatabasePermissions:mn.modifyDatabasePermissions,getVerificationMessage:mn.getVerificationMessage,verifyUser:mn.verifyUser,purchaseSubscription:bn.purchaseSubscription,cancelSubscription:bn.cancelSubscription,resumeSubscription:bn.resumeSubscription,updatePaymentMethod:bn.updatePaymentMethod}}]).default; -//# sourceMappingURL=userbase.js.map diff --git a/public/js/userbase.js.map b/public/js/userbase.js.map deleted file mode 100644 index 84fe57a..0000000 --- a/public/js/userbase.js.map +++ /dev/null @@ -1,2022 +0,0 @@ -{ - "version": 3, - "sources": [ - "webpack://userbase/webpack/bootstrap", - "webpack://userbase/./node_modules/base64-arraybuffer/lib/base64-arraybuffer.js", - "webpack://userbase/./node_modules/@babel/runtime/helpers/defineProperty.js", - "webpack://userbase/./node_modules/uuid/v4.js", - "webpack://userbase/(webpack)/buildin/global.js", - "webpack://userbase/./node_modules/node-libs-browser/node_modules/buffer/index.js", - "webpack://userbase/./node_modules/bn.js/lib/bn.js", - "webpack://userbase/./node_modules/diffie-hellman/lib/generatePrime.js", - "webpack://userbase/./node_modules/randombytes/browser.js", - "webpack://userbase/./node_modules/process/browser.js", - "webpack://userbase/./node_modules/miller-rabin/lib/mr.js", - "webpack://userbase/./node_modules/diffie-hellman/browser.js", - "webpack://userbase/./node_modules/scrypt-js/scrypt.js", - "webpack://userbase/./node_modules/sorted-array/sorted-array.js", - "webpack://userbase/./node_modules/uuid/lib/rng-browser.js", - "webpack://userbase/./node_modules/uuid/lib/bytesToUuid.js", - "webpack://userbase/./node_modules/base64-js/index.js", - "webpack://userbase/./node_modules/ieee754/index.js", - "webpack://userbase/./node_modules/isarray/index.js", - "webpack://userbase/./node_modules/safe-buffer/index.js", - "webpack://userbase/(webpack)/buildin/module.js", - "webpack://userbase/./node_modules/brorand/index.js", - "webpack://userbase/./node_modules/diffie-hellman/lib/dh.js", - "webpack://userbase/./node_modules/timers-browserify/main.js", - "webpack://userbase/./node_modules/setimmediate/setImmediate.js", - "webpack://userbase/./src/statusCodes.js", - "webpack://userbase/./src/errors/auth.js", - "webpack://userbase/./src/errors/db.js", - "webpack://userbase/./src/errors/config.js", - "webpack://userbase/./src/errors/payments.js", - "webpack://userbase/./src/errors/index.js", - "webpack://userbase/./src/config.js", - "webpack://userbase/./src/api/utils.js", - "webpack://userbase/./src/api/auth.js", - "webpack://userbase/./src/localData.js", - "webpack://userbase/./src/Crypto/utils.js", - "webpack://userbase/./src/Crypto/sha-256.js", - "webpack://userbase/./src/Crypto/hkdf.js", - "webpack://userbase/./src/Crypto/aes-gcm.js", - "webpack://userbase/./src/Crypto/diffie-hellman.js", - "webpack://userbase/./src/Crypto/ecdsa.js", - "webpack://userbase/./src/Crypto/ecdh.js", - "webpack://userbase/./src/Crypto/hmac.js", - "webpack://userbase/./src/Crypto/index.js", - "webpack://userbase/./src/Crypto/scrypt.js", - "webpack://userbase/./src/utils.js", - "webpack://userbase/./src/worker.js", - "webpack://userbase/./src/api/db.js", - "webpack://userbase/./src/ws.js", - "webpack://userbase/./src/auth.js", - "webpack://userbase/./src/db.js", - "webpack://userbase/./src/payments.js", - "webpack://userbase/./src/index.js" - ], - "names": [ - "installedModules", - "__webpack_require__", - "moduleId", - "exports", - "module", - "i", - "l", - "modules", - "call", - "m", - "c", - "d", - "name", - "getter", - "o", - "Object", - "defineProperty", - "enumerable", - "get", - "r", - "Symbol", - "toStringTag", - "value", - "t", - "mode", - "__esModule", - "ns", - "create", - "key", - "bind", - "n", - "object", - "property", - "prototype", - "hasOwnProperty", - "p", - "s", - "chars", - "lookup", - "Uint8Array", - "length", - "charCodeAt", - "encode", - "arraybuffer", - "bytes", - "len", - "base64", - "substring", - "decode", - "encoded1", - "encoded2", - "encoded3", - "encoded4", - "bufferLength", - "ArrayBuffer", - "obj", - "configurable", - "writable", - "rng", - "bytesToUuid", - "options", - "buf", - "offset", - "Array", - "rnds", - "random", - "ii", - "g", - "this", - "Function", - "e", - "window", - "ieee754", - "isArray", - "kMaxLength", - "Buffer", - "TYPED_ARRAY_SUPPORT", - "createBuffer", - "that", - "RangeError", - "__proto__", - "arg", - "encodingOrOffset", - "Error", - "allocUnsafe", - "from", - "TypeError", - "array", - "byteOffset", - "byteLength", - "undefined", - "fromArrayLike", - "fromArrayBuffer", - "string", - "encoding", - "isEncoding", - "actual", - "write", - "slice", - "fromString", - "isBuffer", - "checked", - "copy", - "buffer", - "val", - "type", - "data", - "fromObject", - "assertSize", - "size", - "toString", - "isView", - "loweredCase", - "utf8ToBytes", - "base64ToBytes", - "toLowerCase", - "slowToString", - "start", - "end", - "hexSlice", - "utf8Slice", - "asciiSlice", - "latin1Slice", - "base64Slice", - "utf16leSlice", - "swap", - "b", - "bidirectionalIndexOf", - "dir", - "isNaN", - "arrayIndexOf", - "indexOf", - "lastIndexOf", - "arr", - "indexSize", - "arrLength", - "valLength", - "String", - "read", - "readUInt16BE", - "foundIndex", - "found", - "j", - "hexWrite", - "Number", - "remaining", - "strLen", - "parsed", - "parseInt", - "substr", - "utf8Write", - "blitBuffer", - "asciiWrite", - "str", - "byteArray", - "push", - "asciiToBytes", - "latin1Write", - "base64Write", - "ucs2Write", - "units", - "hi", - "lo", - "utf16leToBytes", - "fromByteArray", - "Math", - "min", - "res", - "secondByte", - "thirdByte", - "fourthByte", - "tempCodePoint", - "firstByte", - "codePoint", - "bytesPerSequence", - "codePoints", - "fromCharCode", - "apply", - "decodeCodePointsArray", - "SlowBuffer", - "alloc", - "INSPECT_MAX_BYTES", - "global", - "foo", - "subarray", - "typedArraySupport", - "poolSize", - "_augment", - "species", - "fill", - "allocUnsafeSlow", - "_isBuffer", - "compare", - "a", - "x", - "y", - "concat", - "list", - "pos", - "swap16", - "swap32", - "swap64", - "arguments", - "equals", - "inspect", - "max", - "match", - "join", - "target", - "thisStart", - "thisEnd", - "thisCopy", - "targetCopy", - "includes", - "isFinite", - "toJSON", - "_arr", - "ret", - "out", - "toHex", - "checkOffset", - "ext", - "checkInt", - "objectWriteUInt16", - "littleEndian", - "objectWriteUInt32", - "checkIEEE754", - "writeFloat", - "noAssert", - "writeDouble", - "newBuf", - "sliceLen", - "readUIntLE", - "mul", - "readUIntBE", - "readUInt8", - "readUInt16LE", - "readUInt32LE", - "readUInt32BE", - "readIntLE", - "pow", - "readIntBE", - "readInt8", - "readInt16LE", - "readInt16BE", - "readInt32LE", - "readInt32BE", - "readFloatLE", - "readFloatBE", - "readDoubleLE", - "readDoubleBE", - "writeUIntLE", - "writeUIntBE", - "writeUInt8", - "floor", - "writeUInt16LE", - "writeUInt16BE", - "writeUInt32LE", - "writeUInt32BE", - "writeIntLE", - "limit", - "sub", - "writeIntBE", - "writeInt8", - "writeInt16LE", - "writeInt16BE", - "writeInt32LE", - "writeInt32BE", - "writeFloatLE", - "writeFloatBE", - "writeDoubleLE", - "writeDoubleBE", - "targetStart", - "set", - "code", - "INVALID_BASE64_RE", - "Infinity", - "leadSurrogate", - "toByteArray", - "trim", - "replace", - "stringtrim", - "base64clean", - "src", - "dst", - "assert", - "msg", - "inherits", - "ctor", - "superCtor", - "super_", - "TempCtor", - "constructor", - "BN", - "number", - "base", - "endian", - "isBN", - "negative", - "words", - "red", - "_init", - "wordSize", - "parseHex", - "parseBase", - "num", - "left", - "right", - "cmp", - "_initNumber", - "_initArray", - "_parseHex", - "_parseBase", - "strip", - "toArray", - "ceil", - "w", - "off", - "limbLen", - "limbPow", - "total", - "mod", - "word", - "imuln", - "_iaddn", - "dest", - "clone", - "_expand", - "_normSign", - "zeros", - "groupSizes", - "groupBases", - "smallMulTo", - "self", - "carry", - "k", - "ncarry", - "rword", - "maxJ", - "padding", - "groupSize", - "groupBase", - "isZero", - "modn", - "idivn", - "toNumber", - "toBuffer", - "toArrayLike", - "ArrayType", - "reqLength", - "q", - "andln", - "iushrn", - "clz32", - "_countBits", - "_zeroBits", - "bitLength", - "zeroBits", - "toTwos", - "width", - "abs", - "inotn", - "iaddn", - "fromTwos", - "testn", - "notn", - "ineg", - "isNeg", - "neg", - "iuor", - "ior", - "or", - "uor", - "iuand", - "iand", - "and", - "uand", - "iuxor", - "ixor", - "xor", - "uxor", - "bytesNeeded", - "bitsLeft", - "setn", - "bit", - "wbit", - "iadd", - "isub", - "add", - "comb10MulTo", - "mid", - "a0", - "al0", - "ah0", - "a1", - "al1", - "ah1", - "a2", - "al2", - "ah2", - "a3", - "al3", - "ah3", - "a4", - "al4", - "ah4", - "a5", - "al5", - "ah5", - "a6", - "al6", - "ah6", - "a7", - "al7", - "ah7", - "a8", - "al8", - "ah8", - "a9", - "al9", - "ah9", - "b0", - "bl0", - "bh0", - "b1", - "bl1", - "bh1", - "b2", - "bl2", - "bh2", - "b3", - "bl3", - "bh3", - "b4", - "bl4", - "bh4", - "b5", - "bl5", - "bh5", - "b6", - "bl6", - "bh6", - "b7", - "bl7", - "bh7", - "b8", - "bl8", - "bh8", - "b9", - "bl9", - "bh9", - "w0", - "imul", - "w1", - "w2", - "w3", - "w4", - "w5", - "w6", - "w7", - "w8", - "w9", - "w10", - "w11", - "w12", - "w13", - "w14", - "w15", - "w16", - "w17", - "w18", - "jumboMulTo", - "FFTM", - "mulp", - "mulTo", - "hncarry", - "bigMulTo", - "makeRBT", - "N", - "revBin", - "rb", - "permute", - "rbt", - "rws", - "iws", - "rtws", - "itws", - "transform", - "rtwdf", - "cos", - "PI", - "itwdf", - "sin", - "rtwdf_", - "itwdf_", - "re", - "ie", - "ro", - "io", - "rx", - "guessLen13b", - "odd", - "conjugate", - "normalize13b", - "ws", - "round", - "convert13b", - "stub", - "ph", - "_", - "rwst", - "iwst", - "nrws", - "nrwst", - "niwst", - "rmws", - "mulf", - "muln", - "sqr", - "isqr", - "toBitArray", - "iushln", - "bits", - "carryMask", - "newCarry", - "ishln", - "hint", - "extended", - "h", - "mask", - "maskedWords", - "ishrn", - "shln", - "ushln", - "shrn", - "ushrn", - "imaskn", - "maskn", - "isubn", - "addn", - "subn", - "iabs", - "_ishlnsubmul", - "shift", - "_wordDiv", - "bhi", - "diff", - "qj", - "div", - "divmod", - "positive", - "divn", - "umod", - "divRound", - "dm", - "half", - "r2", - "acc", - "egcd", - "A", - "B", - "C", - "D", - "isEven", - "yp", - "xp", - "im", - "isOdd", - "jm", - "gcd", - "_invmp", - "x1", - "x2", - "delta", - "cmpn", - "invm", - "bincn", - "ucmp", - "gtn", - "gt", - "gten", - "gte", - "ltn", - "lt", - "lten", - "lte", - "eqn", - "eq", - "Red", - "toRed", - "ctx", - "convertTo", - "_forceRed", - "fromRed", - "convertFrom", - "forceRed", - "redAdd", - "redIAdd", - "redSub", - "redISub", - "redShl", - "shl", - "redMul", - "_verify2", - "redIMul", - "redSqr", - "_verify1", - "redISqr", - "redSqrt", - "sqrt", - "redInvm", - "redNeg", - "redPow", - "primes", - "k256", - "p224", - "p192", - "p25519", - "MPrime", - "tmp", - "_tmp", - "K256", - "P224", - "P192", - "P25519", - "prime", - "_prime", - "Mont", - "imod", - "rinv", - "minv", - "ireduce", - "rlen", - "split", - "imulK", - "_strip", - "input", - "output", - "outLen", - "prev", - "next", - "mod3", - "one", - "nOne", - "lpow", - "z", - "inv", - "wnd", - "current", - "currentLen", - "mont", - "u", - "randomBytes", - "findPrime", - "simpleSieve", - "fermatTest", - "TWENTYFOUR", - "millerRabin", - "ONE", - "TWO", - "FIVE", - "TEN", - "THREE", - "ELEVEN", - "FOUR", - "_getPrimes", - "gen", - "n2", - "test", - "crypto", - "msCrypto", - "getRandomValues", - "cb", - "generated", - "process", - "nextTick", - "cachedSetTimeout", - "cachedClearTimeout", - "defaultSetTimout", - "defaultClearTimeout", - "runTimeout", - "fun", - "setTimeout", - "clearTimeout", - "currentQueue", - "queue", - "draining", - "queueIndex", - "cleanUpNextTick", - "drainQueue", - "timeout", - "run", - "marker", - "runClearTimeout", - "Item", - "noop", - "args", - "title", - "browser", - "env", - "argv", - "version", - "versions", - "on", - "addListener", - "once", - "removeListener", - "removeAllListeners", - "emit", - "prependListener", - "prependOnceListener", - "listeners", - "binding", - "cwd", - "chdir", - "umask", - "bn", - "brorand", - "MillerRabin", - "rand", - "Rand", - "_randbelow", - "min_bytes", - "generate", - "_randrange", - "stop", - "rone", - "n1", - "rn1", - "getDivisor", - "DH", - "ENCODINGS", - "DiffieHellmanGroup", - "createDiffieHellmanGroup", - "getDiffieHellman", - "createDiffieHellman", - "DiffieHellman", - "enc", - "generator", - "genc", - "generatePrime", - "root", - "SHA256", - "K", - "Uint32Array", - "h0", - "h1", - "h2", - "h3", - "h4", - "h5", - "h6", - "h7", - "blocks", - "t1", - "t2", - "f", - "bytesLeft", - "bitLenHi", - "bitLenLo", - "numZeros", - "PBKDF2_HMAC_SHA256_OneIter", - "password", - "salt", - "dkLen", - "innerLen", - "inner", - "outerKey", - "dk", - "incrementCounter", - "blockmix_salsa8", - "BY", - "Yi", - "_X", - "arraycopy", - "blockxor", - "salsa20_8", - "R", - "S", - "Si", - "srcPos", - "destPos", - "checkBufferish", - "v", - "ensureInteger", - "_scrypt", - "callback", - "XY", - "V", - "totalOps", - "i1", - "Bi", - "currentOp", - "lastPercent10", - "state", - "i0", - "setImmediate", - "incrementalSMix", - "steps", - "percent10", - "derivedKey", - "lib", - "scrypt", - "progressCallback", - "Promise", - "resolve", - "reject", - "lastProgress", - "error", - "progress", - "syncScrypt", - "SortedArray", - "compareDefault", - "index", - "insert", - "element", - "ordering", - "high", - "low", - "search", - "remove", - "splice", - "comparing", - "rnds8", - "byteToHex", - "bth", - "b64", - "lens", - "getLens", - "validLen", - "placeHoldersLen", - "Arr", - "_byteLength", - "curByte", - "revLookup", - "uint8", - "extraBytes", - "parts", - "len2", - "encodeChunk", - "isLE", - "mLen", - "nBytes", - "eLen", - "eMax", - "eBias", - "nBits", - "NaN", - "rt", - "log", - "LN2", - "copyProps", - "SafeBuffer", - "webpackPolyfill", - "deprecate", - "paths", - "children", - "_rand", - "getBytes", - "getByte", - "SEVEN", - "setPublicKey", - "pub", - "_pub", - "setPrivateKey", - "priv", - "_priv", - "primeCache", - "malleable", - "setGenerator", - "__prime", - "_primeLen", - "_primeCode", - "formatReturnValue", - "hex", - "rem", - "checkPrime", - "__gen", - "generateKeys", - "_gen", - "getPublicKey", - "computeSecret", - "other", - "secret", - "getPrime", - "front", - "getPrivateKey", - "getGenerator", - "Timeout", - "id", - "clearFn", - "_id", - "_clearFn", - "scope", - "setInterval", - "clearInterval", - "close", - "unref", - "ref", - "enroll", - "item", - "msecs", - "_idleTimeoutId", - "_idleTimeout", - "unenroll", - "_unrefActive", - "active", - "_onTimeout", - "clearImmediate", - "registerImmediate", - "html", - "channel", - "messagePrefix", - "onGlobalMessage", - "nextHandle", - "tasksByHandle", - "currentlyRunningATask", - "doc", - "document", - "attachTo", - "getPrototypeOf", - "handle", - "runIfPresent", - "postMessage", - "importScripts", - "postMessageIsAsynchronous", - "oldOnMessage", - "onmessage", - "canUsePostMessage", - "MessageChannel", - "port1", - "event", - "port2", - "createElement", - "documentElement", - "script", - "onreadystatechange", - "removeChild", - "appendChild", - "source", - "addEventListener", - "attachEvent", - "task", - "UsernameAlreadyExists", - "params", - "super", - "message", - "status", - "statusCodes", - "UsernameMissing", - "UsernameCannotBeBlank", - "UsernameTooLong", - "maxLen", - "UsernameMustBeString", - "PasswordMissing", - "PasswordCannotBeBlank", - "PasswordTooShort", - "minLen", - "PasswordTooLong", - "PasswordMustBeString", - "PasswordAttemptLimitExceeded", - "delay", - "UsernameOrPasswordMismatch", - "SessionLengthMustBeNumber", - "SessionLengthTooShort", - "SessionLengthTooLong", - "AllowServerSideEncryptionMustBeBoolean", - "UserAlreadySignedIn", - "username", - "UserPendingDeletion", - "AppIdNotValid", - "DomainNotWhitelisted", - "domain", - "UserNotSignedIn", - "UserNotFound", - "UserEmailNotFound", - "UserMustChangePassword", - "EmailNotValid", - "ProfileMustBeObject", - "ProfileCannotBeEmpty", - "ProfileHasTooManyKeys", - "maxKeys", - "ProfileKeyTooLong", - "ProfileValueMustBeString", - "ProfileValueCannotBeBlank", - "ProfileValueTooLong", - "RememberMeValueNotValid", - "JSON", - "stringify", - "keys", - "ParamsMissing", - "TrialExceededLimit", - "CurrentPasswordMissing", - "CurrentPasswordIncorrect", - "KeyNotFound", - "DeleteEndToEndEncryptedDataMustBeBoolean", - "DatabaseNameMissing", - "DatabaseNameCannotBeBlank", - "DatabaseNameMustBeString", - "DatabaseNameTooLong", - "maxLength", - "DatabaseNameRestricted", - "databaseName", - "DatabaseAlreadyOpening", - "ChangeHandlerMissing", - "ChangeHandlerMustBeFunction", - "EncryptionModeNotValid", - "ServerSideEncryptionNotEnabledInClient", - "DatabaseNotOpen", - "DatabaseNotFound", - "DatabaseIsReadOnly", - "DatabaseIdMustBeString", - "DatabaseIdCannotBeBlank", - "DatabaseIdNotAllowed", - "DatabaseIdNotAllowedForOwnDatabase", - "DatabaseIdInvalidLength", - "ShareTokenInvalid", - "ShareTokenNotFound", - "ShareTokenNotAllowed", - "reason", - "ShareTokenNotAllowedForOwnDatabase", - "ReadOnlyMustBeBoolean", - "ReadOnlyParamNotAllowed", - "ResharingAllowedParamNotAllowed", - "ResharingAllowedMustBeBoolean", - "ResharingNotAllowed", - "ResharingWithWriteAccessNotAllowed", - "SharingWithSelfNotAllowed", - "ModifyingOwnPermissionsNotAllowed", - "ModifyingOwnerPermissionsNotAllowed", - "ModifyingPermissionsNotAllowed", - "GrantingWriteAccessNotAllowed", - "RequireVerifiedMustBeBoolean", - "RequireVerifiedParamNotNecessary", - "RevokeMustBeBoolean", - "ItemMissing", - "ItemInvalid", - "ItemTooLarge", - "maxKb", - "ItemIdMustBeString", - "ItemIdTooLong", - "ItemIdMissing", - "ItemIdCannotBeBlank", - "ItemAlreadyExists", - "ItemDoesNotExist", - "ItemUpdateConflict", - "FileMissing", - "FileMustBeFile", - "FileCannotBeEmpty", - "FileUploadConflict", - "FileNotFound", - "FileIdMissing", - "FileIdMustBeString", - "FileIdCannotBeBlank", - "FileIdTooLong", - "RangeMustBeObject", - "RangeMissingStart", - "RangeMissingEnd", - "RangeStartMustBeNumber", - "RangeEndMustBeNumber", - "RangeStartMustBeGreaterThanZero", - "RangeEndMustBeGreaterThanRangeStart", - "RangeEndMustBeLessThanFileSize", - "OperationsMissing", - "OperationsMustBeArray", - "CommandNotRecognized", - "command", - "OperationsConflict", - "OperationsExceedLimit", - "UserNotVerified", - "UserMustBeReverified", - "UserUnableToReceiveDatabase", - "VerificationMessageMissing", - "VerificationMessageCannotBeBlank", - "VerificationMessageMustBeString", - "VerificationMessageInvalid", - "VerifyingSelfNotAllowed", - "ProgressHandlerMustBeFunction", - "TransactionUnauthorized", - "WriteAccessParamNotAllowed", - "AppIdAlreadySet", - "appId", - "AppIdMustBeString", - "AppIdMissing", - "AppIdCannotBeBlank", - "WebCryptoUnavailable", - "UpdateUserHandlerMustBeFunction", - "SuccessUrlMissing", - "SuccessUrlMustBeString", - "SuccessUrlInvalid", - "invalidProtocol", - "CancelUrlMissing", - "CancelUrlMustBeString", - "CancelUrlInvalid", - "StripeJsLibraryMissing", - "PaymentsDisabled", - "PriceIdOrPlanIdAllowed", - "PriceIdOrPlanIdMissing", - "SubscriptionPlanAlreadyPurchased", - "StripeAccountNotConnected", - "SubscriptionNotFound", - "SubscriptionInactive", - "subscriptionStatus", - "SubscriptionNotPurchased", - "SubscriptionAlreadyCanceled", - "TrialExpired", - "StripeError", - "AppIdNotSet", - "ServiceUnavailable", - "ParamsMustBeObject", - "TooManyRequests", - "retryDelay", - "retryDelaySeconds", - "auth", - "db", - "config", - "payments", - "InternalServerError", - "Reconnecting", - "UnknownServiceUnavailable", - "console", - "userbaseAppId", - "userbaseUpdateUserHandler", - "userbaseAllowServerSideEncryptionMode", - "errors", - "_userbaseEndpoint", - "updateUserHandler", - "allowServerSideEncryption", - "isProduction", - "_USERBASE_STRIPE_PRODUCTION_PUBLISHABLE_KEY", - "_USERBASE_STRIPE_TEST_PUBLISHABLE_KEY", - "RequestError", - "statusText", - "response", - "TimeoutError", - "processXhr", - "xhr", - "onload", - "parse", - "handleResponse", - "onerror", - "ontimeout", - "passwordToken", - "ecKeyData", - "passwordSalts", - "keySalts", - "email", - "profile", - "passwordBasedBackup", - "sessionLength", - "XMLHttpRequest", - "url", - "open", - "setRequestHeader", - "send", - "encodeURIComponent", - "async", - "sessionId", - "responseType", - "tryCatchWrapper", - "func", - "warn", - "_getSeedName", - "setCurrentSession", - "rememberMe", - "signedIn", - "creationDate", - "expirationDate", - "session", - "sessionString", - "localStorage", - "setItem", - "sessionStorage", - "signInSession", - "signOutSession", - "getCurrentSession", - "sessionStorageCurrentSessionString", - "getItem", - "localCurrentSessionString", - "localCurrentSession", - "localSessionString", - "saveSeedString", - "seedString", - "removeSeedString", - "seedName", - "removeItem", - "getSeedString", - "removeCurrentSession", - "arrayBufferToString", - "minified", - "bufView", - "Uint16Array", - "result", - "chunkSize", - "chunk", - "stringToArrayBuffer", - "appendBuffer", - "buffer1", - "buffer2", - "hash", - "subtle", - "digest", - "BYTE_SIZE", - "HASH_ALGORITHM_NAME", - "hashBase64String", - "dataString", - "hashString", - "KEY_WILL_BE_USED_TO", - "importHkdfKey", - "importKey", - "seed", - "SALT_BYTE_SIZE", - "sha256", - "getParams", - "keyName", - "info", - "importHkdfKeyFromString", - "generateSalt", - "getPasswordToken", - "hkdfKey", - "passwordTokenBits", - "deriveBits", - "windowOrSelfObject", - "getEncryptionKeyParams", - "getCiphertextParams", - "iv", - "tagLength", - "generateIv", - "sliceEncryptedArrayBuffer", - "encryptedArrayBuffer", - "ivStartIndex", - "ciphertextArrayBuffer", - "generateKey", - "getKeyFromRawKey", - "rawKey", - "getRawKeyFromKey", - "exportKey", - "encrypt", - "plaintext", - "encryptString", - "plaintextString", - "plaintextArrayBuffer", - "encrypted", - "decrypt", - "decryptString", - "encryptedString", - "importKeyFromMaster", - "masterKey", - "encryptionKeyName", - "deriveKey", - "hkdf", - "getKeyStringFromKey", - "getKeyFromKeyString", - "keyString", - "encryptJson", - "plaintextJson", - "decryptJson", - "encryptedJsonString", - "getPasswordBasedEncryptionKey", - "generateAndEncryptKeyEncryptionKey", - "keyEncryptionKey", - "keyEncryptionKeyRaw", - "RAW_KEY_TYPE", - "PRIME", - "hexString", - "halfHexStringLen", - "byteStartIndex", - "byte", - "byteAsInt", - "hexStringToArrayBuffer", - "GENERATOR", - "serverPublicKey", - "privateKey", - "diffieHellman", - "setPrivateKeyAndGenerateKeys", - "getSharedKey", - "otherPublicKey", - "sharedSecret", - "sharedRawKey", - "aesGcm", - "getSharedKeyWithServer", - "authApi", - "getServerPublicKey", - "KEY_PAIR_WILL_BE_USED_TO", - "PRIVATE_KEY_WILL_BE_USED_TO", - "PUBLIC_KEY_WILL_BE_USED_TO", - "ECDSA_PARAMS", - "namedCurve", - "ECDSA_SIGNING_PARAMS", - "getRawPublicKeyFromPublicKey", - "publicKey", - "getPublicKeyStringFromPublicKey", - "rawPublicKey", - "importEcdsaKeyEncryptionKeyFromMaster", - "sign", - "verify", - "signature", - "generateEcdsaKeyData", - "ecdsaKeyPair", - "generateKeyPair", - "ecdsaKeyEncryptionKeySalt", - "ecdsaKeyEncryptionKey", - "ecdsaRawPrivateKey", - "jwkPrivateKey", - "getRawPrivateKeyFromPrivateKey", - "encryptedEcdsaPrivateKey", - "ecdsaPrivateKey", - "ecdsaPublicKey", - "getPrivateKeyFromRawPrivateKey", - "rawPrivateKey", - "getPublicKeyFromRawPublicKey", - "getPublicKeyFromPrivateKey", - "key_ops", - "signString", - "verifyString", - "signatureString", - "ECDH_PARAMS", - "importEcdhKeyEncryptionKeyFromMaster", - "generateEcdhKeyData", - "ecdhKeyPair", - "ecdhKeyEncryptionKeySalt", - "ecdhKeyEncryptionKey", - "ecdhRawPrivateKey", - "encryptedEcdhPrivateKey", - "ecdhPublicKey", - "signedEcdhPublicKey", - "ecdsa", - "ecdhPrivateKey", - "computeSharedKeyEncryptionKey", - "otherEcdhPublicKey", - "public", - "KEY_WILL_BE_USED_TO_SIGN", - "KEY_WILL_BE_USED_TO_SIGN_AND_VERIFY", - "importKeyFromRawBits", - "rawBits", - "generateSeed", - "ecdh", - "hmac", - "passwordString", - "passwordHashAlgo", - "scryptJs", - "passwordArrayBuffer", - "passwordHash", - "getProtocolFromEndpoint", - "endpoint", - "getWsUrl", - "host", - "removeProtocolFromEndpoint", - "byteSizeOfString", - "objectHasOwnProperty", - "Queue", - "getLength", - "isEmpty", - "enqueue", - "dequeue", - "peek", - "newWorker", - "blobURL", - "URL", - "createObjectURL", - "Blob", - "compress", - "decompress", - "LZString", - "charAt", - "compressToBase64", - "_compress", - "decompressFromBase64", - "_decompress", - "compressToUTF16", - "decompressFromUTF16", - "compressToUint8Array", - "decompressFromUint8Array", - "forEach", - "compressToEncodedURIComponent", - "decompressFromEncodedURIComponent", - "position", - "worker", - "Worker", - "revokeObjectURL", - "terminate", - "uploadBundleChunk", - "userId", - "databaseId", - "seqNo", - "bundleId", - "chunkNo", - "clientId", - "uuidv4", - "RequestFailed", - "action", - "WebSocketError", - "init", - "resolveConnection", - "rejectConnection", - "changePassword", - "encryptionMode", - "pingTimeout", - "connected", - "connectionResolved", - "authToken", - "salts", - "userData", - "stripeData", - "requests", - "dbNameToHash", - "databases", - "databasesByDbId", - "shareTokenIdToDbId", - "connect", - "reconnectDelay", - "timeoutToOpenWebSocket", - "reconnecting", - "WebSocket", - "onopen", - "route", - "heartbeat", - "validationMessage", - "encryptedValidationMessage", - "setKeys", - "validateKey", - "DOMException", - "dbId", - "dbNameHash", - "database", - "isOwner", - "applyTransactionsQueue", - "startApplyingThisBatchOfTransactions", - "dbKey", - "plaintextDbKey", - "shareTokenEncryptedDbKey", - "dbKeyString", - "encryptionKey", - "decryptShareTokenEncryptedDbKey", - "shareTokenEncryptionKeySalt", - "writers", - "attributionEnabled", - "usernamesByUserId", - "waitForFullBundle", - "finishedWaitingForBundle", - "bundle", - "rebuildBundle", - "bundleSeqNo", - "encryptedBundleEncryptionKey", - "applyBundle", - "alert", - "newTransactions", - "transactionLog", - "applyTransactions", - "ownerId", - "buildBundle", - "startApplyingNextBatchInQueue", - "isFirstChunk", - "isLastChunk", - "bundleChunks", - "handleUpdateUser", - "updatedUser", - "requestId", - "request", - "promiseResolve", - "promiseReject", - "onclose", - "serviceRestart", - "clientDisconnected", - "wasClean", - "reconnect", - "reconnected", - "currentState", - "dbsToReopen", - "dbsToReopenById", - "reopenDatabases", - "openDatabasePromises", - "reopenAtSeqNo", - "lastSeqNo", - "shareTokenHkdfKey", - "shareTokenAuthData", - "authenticateShareToken", - "shareTokenId", - "all", - "localData", - "encryptionKeySalt", - "hmacKey", - "hmacKeySalt", - "rawEcdsaPrivateKey", - "rawEcdhPrivateKey", - "dhKeySalt", - "dhPrivateKey", - "ecdsaKeyWrapperSalt", - "ecdsaKeyData", - "ecdhKeyData", - "newEcKeyData", - "sharedKey", - "responseWatcher", - "watch", - "chunkArrayBuffer", - "bundleArrayBuffer", - "buffers", - "bufferByteLengths", - "map", - "totalByteLength", - "reduce", - "byteLengthSum", - "bufferByteLength", - "currentByteLength", - "byteLengths", - "appendBuffers", - "plaintextMetadata", - "bundleEncryptionKeyRaw", - "bundleEncryptionKey", - "decrypted", - "decryptedString", - "decompressedEncrypted", - "decompressedPlaintextMetdata", - "chunkNumber", - "batch", - "initResponse", - "orderedItems", - "items", - "itemsIndex", - "orderedItemsArray", - "itemId", - "prepareBundle", - "itemsPlaintextMetadata", - "bundledAtSeqNo", - "initBundleUpload", - "compressedBeforeEncryption", - "compressedPlaintextMetadataString", - "compressedArrayBufferBeforeEncryption", - "encryptedItems", - "numChunks", - "uploadBundle", - "buildUserResult", - "protectedProfile", - "usedTempPassword", - "passwordChanged", - "paymentsMode", - "cancelSubscriptionAt", - "subscriptionPlanId", - "trialExpirationDate", - "user", - "newSeedString", - "newKeyData", - "shareTokenAuthKeyData", - "shareTokenEcdsaPrivateKey", - "shareTokenEcdsaKeyEncryptionKeySalt", - "shareTokenEcdsaKeyEncryptionKey", - "shareTokenEncryptedEcdsaPrivateKey", - "shareTokenEcdsaPrivateKeyRaw", - "signedValidationMessage", - "REMEMBER_ME_OPTIONS", - "local", - "none", - "KEY_NOT_FOUND_ON_SIGN_IN", - "KEY_NOT_FOUND_ON_FORGOT_PASSWORD", - "_parseGenericErrors", - "location", - "origin", - "_connectWebSocket", - "_parseGenericUsernamePasswordError", - "_parseSessionLengthError", - "_parseUserResponseError", - "_calculateSessionLengthMs", - "_validateUsername", - "_validatePassword", - "_validateSignUpOrSignInInput", - "_generatePasswordToken", - "passwordSalt", - "passwordHkdfKey", - "passwordTokenSalt", - "passwordBasedEncryptionKeySalt", - "passwordBasedEncryptionKey", - "passwordEncryptedSeed", - "_generateKeys", - "_validateProfile", - "keyExists", - "_getPasswordSaltsOverWebSocket", - "_rebuildPasswordToken", - "signInWithSession", - "lastUsedUsername", - "currentSession", - "savedSeedString", - "Date", - "apiSignInWithSessionResult", - "_getMasterKeyAndKeyNotFoundMessage", - "signUp", - "_validateSignUpInput", - "_generateKeysAndSignUp", - "signOut", - "signIn", - "_getPasswordSaltsOverRestEndpoint", - "apiSignInResult", - "_signInWrapper", - "seedStringFromBackup", - "seedFromBackup", - "_getSeedStringFromPasswordBasedBackup", - "updateUser", - "currentPassword", - "newPassword", - "_validateUpdatedUserInput", - "startingUserId", - "newSeed", - "finalParams", - "currentPasswordSalts", - "newPasswordPromise", - "currentPasswordToken", - "_buildUpdateUserParams", - "rotateKeys", - "deleteUser", - "_checkSignedInState", - "forgotPassword", - "deleteEndToEndEncryptedData", - "forgotPasswordWs", - "encryptedForgotPasswordToken", - "forgotPasswordToken", - "signedForgotPasswordToken", - "ENCRYPTION_MODE_OPTIONS", - "UnverifiedTransaction", - "startSeqNo", - "txSeqNo", - "transactions", - "getStartSeqNo", - "getIndex", - "setIndex", - "promise", - "verifyPromise", - "addTransaction", - "transaction", - "Database", - "changeHandler", - "receivedMessage", - "onChange", - "_setChangeHandler", - "fileIds", - "operationIndex", - "unverifiedTransactions", - "Map", - "transactionCode", - "applyTransaction", - "getItems", - "itemIndex", - "file", - "fileEncryptionKeyString", - "fileEncryptionKey", - "fileId", - "record", - "createdBy", - "attributionFromTransaction", - "writeAccess", - "validateInsert", - "applyInsert", - "updatedBy", - "__v", - "validateUpdate", - "applyUpdate", - "deletedBy", - "validateUpdateOrDelete", - "applyDelete", - "operations", - "attribution", - "recordPromises", - "operation", - "records", - "validateBatchTransaction", - "applyBatchTransaction", - "fileEncryptionKeyRaw", - "fileMetadata", - "fileVersion", - "fileName", - "fileSize", - "fileType", - "fileUploadedBy", - "validateUploadFile", - "applyUploadFile", - "timestamp", - "createdByUserId", - "updatedByUserId", - "getItemVersionNumber", - "validateAccessPermissions", - "getFileVersionNumber", - "modifiedByUserId", - "userIsAuthorized", - "onlyCreator", - "users", - "itemExists", - "existingFile", - "uniqueItemIds", - "registerUnverifiedTransaction", - "unverifiedTransaction", - "unregisterUnverifiedTransaction", - "pendingTransaction", - "prop", - "userDeleted", - "shareTokenEncryptionKey", - "_idempotentOpenDatabase", - "currentReceivedMessage", - "_getShareTokenIdFromShareToken", - "shareTokenArrayBuffer", - "shareTokenIdArrayBuffer", - "_openDatabaseByShareToken", - "shareToken", - "shareTokenIdAndShareTokenSeed", - "shareTokenResult", - "shareTokenSeed", - "_getShareTokenIdAndShareTokenSeed", - "_openDatabaseByDatabaseId", - "_openDatabase", - "firstMessageFromWebSocket", - "newDatabaseParams", - "_openDatabaseByNameHash", - "_validateEncryptionMode", - "_validateDbInput", - "dbName", - "_validateDbName", - "allowVerifiedUsersDatabase", - "_validateDbId", - "openDatabase", - "openByDbNameHashParams", - "encryptedDbKey", - "encryptedDbName", - "fingerprint", - "_getMyFingerprint", - "_createDatabase", - "openByDbIdParams", - "openByShareToken", - "getOpenDb", - "insertItem", - "insertParams", - "_buildInsertParams", - "postTransaction", - "itemString", - "MAX_ITEM_KB", - "itemRecord", - "itemKey", - "encryptedItem", - "updateItem", - "updateParams", - "_buildUpdateParams", - "_buildDeleteParams", - "pendingTx", - "paramsWithDbData", - "sequenceNo", - "getResult", - "_uploadChunk", - "bytesTransferredObject", - "progressHandler", - "plaintextChunk", - "reader", - "FileReader", - "readAsArrayBuffer", - "blob", - "_readBlob", - "chunkEncryptionKey", - "encryptedChunkEncryptionKey", - "encryptedChunk", - "uploadChunkParams", - "uploadChunkRequest", - "bytesTransferred", - "_uploadChunkRequest", - "_getChunk", - "chunkRawBuffer", - "chunkEncryptionKeyRawBuffer", - "chunkEncryptionKeyRaw", - "_verifyUsersParent", - "verifiedUsers", - "databaseUser", - "senderUsername", - "verificationValues", - "sentSignature", - "receivedSignature", - "senderEcdsaPublicKey", - "verifiedFingerprint", - "parentRawEcdsaPublicKey", - "parentFingerprint", - "_getFingerprint", - "parentEcdsaPublicKey", - "expectedSentSignature", - "_signFingerprintWithDbKey", - "verifiedParentSent", - "recipientEcdsaPublicKey", - "expectedReceivedSignature", - "verifiedReceivedFromParent", - "_verifyReceivedDatabaseFromUser", - "myFingerprint", - "myEcdsaPublicKey", - "mySentSignature", - "myReceivedSignature", - "verifiedReceived", - "mySenderEcdsaPublicKey", - "_verifySentDatabaseToUser", - "verifiedSent", - "_buildDatabaseUserResult", - "databaseUsers", - "myUsername", - "mySenderUsername", - "sentDatabaseToUser", - "isChild", - "receivedDatabaseFromUser", - "verified", - "verifiedReceivedDatabaseFromUser", - "verifiedGrandparent", - "verifiedUsersParent", - "receivedFromUsername", - "_buildDatabaseResult", - "databaseNameHash", - "readOnly", - "resharingAllowed", - "wrappedDbKey", - "senderRawEcdsaPublicKey", - "ephemeralPublicKey", - "signedEphemeralPublicKey", - "sharedEncryptedDbKey", - "senderEphemeralEcdhPublicKey", - "sharedKeyEncryptionKey", - "senderFingerprint", - "_signDbKeyAndFingerprint", - "databaseUsersResponse", - "nextPageTokenLessThanUserId", - "nextPageTokenMoreThanUserId", - "_getDatabaseUsers", - "_databaseHasOwner", - "_getDatabase", - "requestParams", - "rawDbKey", - "dbKeyHash", - "signedFingerprint", - "_getDatabaseEncryptionKey", - "_shareDatabaseWithUsername", - "requireVerified", - "recipientPublicKey", - "_openVerifiedUsersDatabase", - "recipientRawEcdsaPublicKey", - "recipientFingerprint", - "verifiedRecipientFingerprint", - "foundOldFingerprint", - "verifiedUsersArray", - "verifiedUsername", - "_verifyDatabaseRecipientFingerprint", - "recipientEcdhPublicKey", - "ephemeralEcdhKeyPair", - "rawEphemeralEcdhPublicKey", - "signedEphemeralEcdhPublicKey", - "sharedEncryptedDbKeyString", - "_validateDbSharingInput", - "ecdsaPublicKeyHash", - "ecdsaRawPublicKey", - "getDatabases", - "databasesResponse", - "databaseResults", - "nextPageToken", - "filter", - "deleteItem", - "deleteParams", - "putTransaction", - "operationParamsPromises", - "operationParamsPromiseResults", - "operationParams", - "uploadFile", - "_validateUploadFile", - "File", - "currentVersion", - "_buildFileMetadata", - "encryptedFileEncryptionKey", - "encryptedFileMetadata", - "_completeFileUpload", - "getFile", - "range", - "_validateGetFileParams", - "chunks", - "startChunkNumber", - "endChunkNumber", - "_getByteRange", - "finalChunkNumber", - "_getFile", - "shareDatabase", - "shareTokenEncryptedDbKeyString", - "keyData", - "shareTokenPublicKey", - "shareTokenResponse", - "_getShareToken", - "modifyDatabasePermissions", - "revoke", - "getVerificationMessage", - "verificationMessage", - "btoa", - "_packVerificationMessage", - "verifyUser", - "atob", - "_unpackVerificationMessage", - "_validatePurchaseOrUpdate", - "stripeAccountId", - "successUrl", - "successUrlProtocol", - "cancelUrl", - "cancelUrlProtocol", - "_validateModifySubscriptionConditions", - "purchaseSubscription", - "stripeSessionId", - "stripePk", - "Stripe", - "stripeAccount", - "redirectToCheckout", - "cancelSubscription", - "resumeSubscription", - "updatePaymentMethod" - ], - "mappings": "yBACE,IAAIA,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUC,QAGnC,IAAIC,EAASJ,EAAiBE,GAAY,CACzCG,EAAGH,EACHI,GAAG,EACHH,QAAS,IAUV,OANAI,EAAQL,GAAUM,KAAKJ,EAAOD,QAASC,EAAQA,EAAOD,QAASF,GAG/DG,EAAOE,GAAI,EAGJF,EAAOD,QA0Df,OArDAF,EAAoBQ,EAAIF,EAGxBN,EAAoBS,EAAIV,EAGxBC,EAAoBU,EAAI,SAASR,EAASS,EAAMC,GAC3CZ,EAAoBa,EAAEX,EAASS,IAClCG,OAAOC,eAAeb,EAASS,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEZ,EAAoBkB,EAAI,SAAShB,GACX,oBAA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,GAAwB,qBAApB3/B,EAAEuiC,SAASngC,KACpB,MAAM,IAAI0/B,GAAO/B,iBAIrB,MAAM//B,GAGR,MAAOA,GAEP,OAAQA,EAAE1D,MACR,IAAK,qBACL,IAAK,oBACL,IAAK,yBACL,IAAK,oBACL,IAAK,mBACL,IAAK,wBACL,IAAK,mBACL,IAAK,yBACL,IAAK,2BACL,IAAK,4BACL,IAAK,mBACL,IAAK,yBACL,IAAK,kBACL,IAAK,kBACL,IAAK,qBACH,MAAM0D,EAER,QACE,MAAM,IAAI8hC,GAAOL,0BAA0BzhC,OCtQpC,WACb0yC,KAAMvR,GAAKuR,KAEXgM,OAAQvd,GAAKud,OACbI,OAAQ3d,GAAK2d,OACbD,QAAS1d,GAAK0d,QACdQ,WAAYle,GAAKke,WACjBY,WAAY9e,GAAK8e,WACjBE,eAAgBhf,GAAKgf,eAErB0G,aAAczlB,GAAGylB,aAEjBU,WAAYnmB,GAAGmmB,WACfS,WAAY5mB,GAAG4mB,WACfoH,WAAYhuB,GAAGguB,WACfE,eAAgBluB,GAAGkuB,eAEnBI,WAAYtuB,GAAGsuB,WACfQ,QAAS9uB,GAAG8uB,QAEZnB,aAAc3tB,GAAG2tB,aACjB4B,cAAevvB,GAAGuvB,cAClBM,0BAA2B7vB,GAAG6vB,0BAC9BE,uBAAwB/vB,GAAG+vB,uBAC3BI,WAAYnwB,GAAGmwB,WAEfU,qBAAsB3wB,GAAS2wB,qBAC/BM,mBAAoBjxB,GAASixB,mBAC7BC,mBAAoBlxB,GAASkxB,mBAC7BC,oBAAqBnxB,GAASmxB,wB", - "file": "userbase.js", - "sourcesContent": [ - " \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 27);\n", - "/*\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\n(function(){\n \"use strict\";\n\n var chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n // Use a lookup table to find the index.\n var lookup = new Uint8Array(256);\n for (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n }\n\n exports.encode = function(arraybuffer) {\n var bytes = new Uint8Array(arraybuffer),\n i, len = bytes.length, base64 = \"\";\n\n for (i = 0; i < len; i+=3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n\n if ((len % 3) === 2) {\n base64 = base64.substring(0, base64.length - 1) + \"=\";\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + \"==\";\n }\n\n return base64;\n };\n\n exports.decode = function(base64) {\n var bufferLength = base64.length * 0.75,\n len = base64.length, i, p = 0,\n encoded1, encoded2, encoded3, encoded4;\n\n if (base64[base64.length - 1] === \"=\") {\n bufferLength--;\n if (base64[base64.length - 2] === \"=\") {\n bufferLength--;\n }\n }\n\n var arraybuffer = new ArrayBuffer(bufferLength),\n bytes = new Uint8Array(arraybuffer);\n\n for (i = 0; i < len; i+=4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i+1)];\n encoded3 = lookup[base64.charCodeAt(i+2)];\n encoded4 = lookup[base64.charCodeAt(i+3)];\n\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n\n return arraybuffer;\n };\n})();\n", - "function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}\n\nmodule.exports = _defineProperty;", - "var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\nfunction v4(options, buf, offset) {\n var i = buf && offset || 0;\n\n if (typeof(options) == 'string') {\n buf = options === 'binary' ? new Array(16) : null;\n options = null;\n }\n options = options || {};\n\n var rnds = options.random || (options.rng || rng)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n for (var ii = 0; ii < 16; ++ii) {\n buf[i + ii] = rnds[ii];\n }\n }\n\n return buf || bytesToUuid(rnds);\n}\n\nmodule.exports = v4;\n", - "var g;\n\n// This works in non-strict mode\ng = (function() {\n\treturn this;\n})();\n\ntry {\n\t// This works if eval is allowed (see CSP)\n\tg = g || new Function(\"return this\")();\n} catch (e) {\n\t// This works if the window reference is available\n\tif (typeof window === \"object\") g = window;\n}\n\n// g can still be undefined, but nothing to do about it...\n// We return undefined, instead of nothing here, so it's\n// easier to handle this case. if(!global) { ...}\n\nmodule.exports = g;\n", - "/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar isArray = require('isarray')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : typedArraySupport()\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nexports.kMaxLength = kMaxLength()\n\nfunction typedArraySupport () {\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}\n return arr.foo() === 42 && // typed array instances can be augmented\n typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n } catch (e) {\n return false\n }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true\n })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!Buffer.isBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n", - "(function (module, exports) {\n 'use strict';\n\n // Utils\n function assert (val, msg) {\n if (!val) throw new Error(msg || 'Assertion failed');\n }\n\n // Could use `inherits` module, but don't want to move from single file\n // architecture yet.\n function inherits (ctor, superCtor) {\n ctor.super_ = superCtor;\n var TempCtor = function () {};\n TempCtor.prototype = superCtor.prototype;\n ctor.prototype = new TempCtor();\n ctor.prototype.constructor = ctor;\n }\n\n // BN\n\n function BN (number, base, endian) {\n if (BN.isBN(number)) {\n return number;\n }\n\n this.negative = 0;\n this.words = null;\n this.length = 0;\n\n // Reduction context\n this.red = null;\n\n if (number !== null) {\n if (base === 'le' || base === 'be') {\n endian = base;\n base = 10;\n }\n\n this._init(number || 0, base || 10, endian || 'be');\n }\n }\n if (typeof module === 'object') {\n module.exports = BN;\n } else {\n exports.BN = BN;\n }\n\n BN.BN = BN;\n BN.wordSize = 26;\n\n var Buffer;\n try {\n Buffer = require('buffer').Buffer;\n } catch (e) {\n }\n\n BN.isBN = function isBN (num) {\n if (num instanceof BN) {\n return true;\n }\n\n return num !== null && typeof num === 'object' &&\n num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);\n };\n\n BN.max = function max (left, right) {\n if (left.cmp(right) > 0) return left;\n return right;\n };\n\n BN.min = function min (left, right) {\n if (left.cmp(right) < 0) return left;\n return right;\n };\n\n BN.prototype._init = function init (number, base, endian) {\n if (typeof number === 'number') {\n return this._initNumber(number, base, endian);\n }\n\n if (typeof number === 'object') {\n return this._initArray(number, base, endian);\n }\n\n if (base === 'hex') {\n base = 16;\n }\n assert(base === (base | 0) && base >= 2 && base <= 36);\n\n number = number.toString().replace(/\\s+/g, '');\n var start = 0;\n if (number[0] === '-') {\n start++;\n }\n\n if (base === 16) {\n this._parseHex(number, start);\n } else {\n this._parseBase(number, base, start);\n }\n\n if (number[0] === '-') {\n this.negative = 1;\n }\n\n this.strip();\n\n if (endian !== 'le') return;\n\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initNumber = function _initNumber (number, base, endian) {\n if (number < 0) {\n this.negative = 1;\n number = -number;\n }\n if (number < 0x4000000) {\n this.words = [ number & 0x3ffffff ];\n this.length = 1;\n } else if (number < 0x10000000000000) {\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff\n ];\n this.length = 2;\n } else {\n assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)\n this.words = [\n number & 0x3ffffff,\n (number / 0x4000000) & 0x3ffffff,\n 1\n ];\n this.length = 3;\n }\n\n if (endian !== 'le') return;\n\n // Reverse the bytes\n this._initArray(this.toArray(), base, endian);\n };\n\n BN.prototype._initArray = function _initArray (number, base, endian) {\n // Perhaps a Uint8Array\n assert(typeof number.length === 'number');\n if (number.length <= 0) {\n this.words = [ 0 ];\n this.length = 1;\n return this;\n }\n\n this.length = Math.ceil(number.length / 3);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n var off = 0;\n if (endian === 'be') {\n for (i = number.length - 1, j = 0; i >= 0; i -= 3) {\n w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n } else if (endian === 'le') {\n for (i = 0, j = 0; i < number.length; i += 3) {\n w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n }\n return this.strip();\n };\n\n function parseHex (str, start, end) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r <<= 4;\n\n // 'a' - 'f'\n if (c >= 49 && c <= 54) {\n r |= c - 49 + 0xa;\n\n // 'A' - 'F'\n } else if (c >= 17 && c <= 22) {\n r |= c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r |= c & 0xf;\n }\n }\n return r;\n }\n\n BN.prototype._parseHex = function _parseHex (number, start) {\n // Create possibly bigger array to ensure that it fits the number\n this.length = Math.ceil((number.length - start) / 6);\n this.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n this.words[i] = 0;\n }\n\n var j, w;\n // Scan 24-bit chunks and add them to the number\n var off = 0;\n for (i = number.length - 6, j = 0; i >= start; i -= 6) {\n w = parseHex(number, i, i + 6);\n this.words[j] |= (w << off) & 0x3ffffff;\n // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb\n this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;\n off += 24;\n if (off >= 26) {\n off -= 26;\n j++;\n }\n }\n if (i + 6 !== start) {\n w = parseHex(number, start, i + 6);\n this.words[j] |= (w << off) & 0x3ffffff;\n this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;\n }\n this.strip();\n };\n\n function parseBase (str, start, end, mul) {\n var r = 0;\n var len = Math.min(str.length, end);\n for (var i = start; i < len; i++) {\n var c = str.charCodeAt(i) - 48;\n\n r *= mul;\n\n // 'a'\n if (c >= 49) {\n r += c - 49 + 0xa;\n\n // 'A'\n } else if (c >= 17) {\n r += c - 17 + 0xa;\n\n // '0' - '9'\n } else {\n r += c;\n }\n }\n return r;\n }\n\n BN.prototype._parseBase = function _parseBase (number, base, start) {\n // Initialize as zero\n this.words = [ 0 ];\n this.length = 1;\n\n // Find length of limb in base\n for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {\n limbLen++;\n }\n limbLen--;\n limbPow = (limbPow / base) | 0;\n\n var total = number.length - start;\n var mod = total % limbLen;\n var end = Math.min(total, total - mod) + start;\n\n var word = 0;\n for (var i = start; i < end; i += limbLen) {\n word = parseBase(number, i, i + limbLen, base);\n\n this.imuln(limbPow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n\n if (mod !== 0) {\n var pow = 1;\n word = parseBase(number, i, number.length, base);\n\n for (i = 0; i < mod; i++) {\n pow *= base;\n }\n\n this.imuln(pow);\n if (this.words[0] + word < 0x4000000) {\n this.words[0] += word;\n } else {\n this._iaddn(word);\n }\n }\n };\n\n BN.prototype.copy = function copy (dest) {\n dest.words = new Array(this.length);\n for (var i = 0; i < this.length; i++) {\n dest.words[i] = this.words[i];\n }\n dest.length = this.length;\n dest.negative = this.negative;\n dest.red = this.red;\n };\n\n BN.prototype.clone = function clone () {\n var r = new BN(null);\n this.copy(r);\n return r;\n };\n\n BN.prototype._expand = function _expand (size) {\n while (this.length < size) {\n this.words[this.length++] = 0;\n }\n return this;\n };\n\n // Remove leading `0` from `this`\n BN.prototype.strip = function strip () {\n while (this.length > 1 && this.words[this.length - 1] === 0) {\n this.length--;\n }\n return this._normSign();\n };\n\n BN.prototype._normSign = function _normSign () {\n // -0 = 0\n if (this.length === 1 && this.words[0] === 0) {\n this.negative = 0;\n }\n return this;\n };\n\n BN.prototype.inspect = function inspect () {\n return (this.red ? '';\n };\n\n /*\n\n var zeros = [];\n var groupSizes = [];\n var groupBases = [];\n\n var s = '';\n var i = -1;\n while (++i < BN.wordSize) {\n zeros[i] = s;\n s += '0';\n }\n groupSizes[0] = 0;\n groupSizes[1] = 0;\n groupBases[0] = 0;\n groupBases[1] = 0;\n var base = 2 - 1;\n while (++base < 36 + 1) {\n var groupSize = 0;\n var groupBase = 1;\n while (groupBase < (1 << BN.wordSize) / base) {\n groupBase *= base;\n groupSize += 1;\n }\n groupSizes[base] = groupSize;\n groupBases[base] = groupBase;\n }\n\n */\n\n var zeros = [\n '',\n '0',\n '00',\n '000',\n '0000',\n '00000',\n '000000',\n '0000000',\n '00000000',\n '000000000',\n '0000000000',\n '00000000000',\n '000000000000',\n '0000000000000',\n '00000000000000',\n '000000000000000',\n '0000000000000000',\n '00000000000000000',\n '000000000000000000',\n '0000000000000000000',\n '00000000000000000000',\n '000000000000000000000',\n '0000000000000000000000',\n '00000000000000000000000',\n '000000000000000000000000',\n '0000000000000000000000000'\n ];\n\n var groupSizes = [\n 0, 0,\n 25, 16, 12, 11, 10, 9, 8,\n 8, 7, 7, 7, 7, 6, 6,\n 6, 6, 6, 6, 6, 5, 5,\n 5, 5, 5, 5, 5, 5, 5,\n 5, 5, 5, 5, 5, 5, 5\n ];\n\n var groupBases = [\n 0, 0,\n 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,\n 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,\n 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,\n 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,\n 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176\n ];\n\n BN.prototype.toString = function toString (base, padding) {\n base = base || 10;\n padding = padding | 0 || 1;\n\n var out;\n if (base === 16 || base === 'hex') {\n out = '';\n var off = 0;\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = this.words[i];\n var word = (((w << off) | carry) & 0xffffff).toString(16);\n carry = (w >>> (24 - off)) & 0xffffff;\n if (carry !== 0 || i !== this.length - 1) {\n out = zeros[6 - word.length] + word + out;\n } else {\n out = word + out;\n }\n off += 2;\n if (off >= 26) {\n off -= 26;\n i--;\n }\n }\n if (carry !== 0) {\n out = carry.toString(16) + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n if (base === (base | 0) && base >= 2 && base <= 36) {\n // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));\n var groupSize = groupSizes[base];\n // var groupBase = Math.pow(base, groupSize);\n var groupBase = groupBases[base];\n out = '';\n var c = this.clone();\n c.negative = 0;\n while (!c.isZero()) {\n var r = c.modn(groupBase).toString(base);\n c = c.idivn(groupBase);\n\n if (!c.isZero()) {\n out = zeros[groupSize - r.length] + r + out;\n } else {\n out = r + out;\n }\n }\n if (this.isZero()) {\n out = '0' + out;\n }\n while (out.length % padding !== 0) {\n out = '0' + out;\n }\n if (this.negative !== 0) {\n out = '-' + out;\n }\n return out;\n }\n\n assert(false, 'Base should be between 2 and 36');\n };\n\n BN.prototype.toNumber = function toNumber () {\n var ret = this.words[0];\n if (this.length === 2) {\n ret += this.words[1] * 0x4000000;\n } else if (this.length === 3 && this.words[2] === 0x01) {\n // NOTE: at this stage it is known that the top bit is set\n ret += 0x10000000000000 + (this.words[1] * 0x4000000);\n } else if (this.length > 2) {\n assert(false, 'Number can only safely store up to 53 bits');\n }\n return (this.negative !== 0) ? -ret : ret;\n };\n\n BN.prototype.toJSON = function toJSON () {\n return this.toString(16);\n };\n\n BN.prototype.toBuffer = function toBuffer (endian, length) {\n assert(typeof Buffer !== 'undefined');\n return this.toArrayLike(Buffer, endian, length);\n };\n\n BN.prototype.toArray = function toArray (endian, length) {\n return this.toArrayLike(Array, endian, length);\n };\n\n BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {\n var byteLength = this.byteLength();\n var reqLength = length || Math.max(1, byteLength);\n assert(byteLength <= reqLength, 'byte array longer than desired length');\n assert(reqLength > 0, 'Requested array length <= 0');\n\n this.strip();\n var littleEndian = endian === 'le';\n var res = new ArrayType(reqLength);\n\n var b, i;\n var q = this.clone();\n if (!littleEndian) {\n // Assume big-endian\n for (i = 0; i < reqLength - byteLength; i++) {\n res[i] = 0;\n }\n\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[reqLength - i - 1] = b;\n }\n } else {\n for (i = 0; !q.isZero(); i++) {\n b = q.andln(0xff);\n q.iushrn(8);\n\n res[i] = b;\n }\n\n for (; i < reqLength; i++) {\n res[i] = 0;\n }\n }\n\n return res;\n };\n\n if (Math.clz32) {\n BN.prototype._countBits = function _countBits (w) {\n return 32 - Math.clz32(w);\n };\n } else {\n BN.prototype._countBits = function _countBits (w) {\n var t = w;\n var r = 0;\n if (t >= 0x1000) {\n r += 13;\n t >>>= 13;\n }\n if (t >= 0x40) {\n r += 7;\n t >>>= 7;\n }\n if (t >= 0x8) {\n r += 4;\n t >>>= 4;\n }\n if (t >= 0x02) {\n r += 2;\n t >>>= 2;\n }\n return r + t;\n };\n }\n\n BN.prototype._zeroBits = function _zeroBits (w) {\n // Short-cut\n if (w === 0) return 26;\n\n var t = w;\n var r = 0;\n if ((t & 0x1fff) === 0) {\n r += 13;\n t >>>= 13;\n }\n if ((t & 0x7f) === 0) {\n r += 7;\n t >>>= 7;\n }\n if ((t & 0xf) === 0) {\n r += 4;\n t >>>= 4;\n }\n if ((t & 0x3) === 0) {\n r += 2;\n t >>>= 2;\n }\n if ((t & 0x1) === 0) {\n r++;\n }\n return r;\n };\n\n // Return number of used bits in a BN\n BN.prototype.bitLength = function bitLength () {\n var w = this.words[this.length - 1];\n var hi = this._countBits(w);\n return (this.length - 1) * 26 + hi;\n };\n\n function toBitArray (num) {\n var w = new Array(num.bitLength());\n\n for (var bit = 0; bit < w.length; bit++) {\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;\n }\n\n return w;\n }\n\n // Number of trailing zero bits\n BN.prototype.zeroBits = function zeroBits () {\n if (this.isZero()) return 0;\n\n var r = 0;\n for (var i = 0; i < this.length; i++) {\n var b = this._zeroBits(this.words[i]);\n r += b;\n if (b !== 26) break;\n }\n return r;\n };\n\n BN.prototype.byteLength = function byteLength () {\n return Math.ceil(this.bitLength() / 8);\n };\n\n BN.prototype.toTwos = function toTwos (width) {\n if (this.negative !== 0) {\n return this.abs().inotn(width).iaddn(1);\n }\n return this.clone();\n };\n\n BN.prototype.fromTwos = function fromTwos (width) {\n if (this.testn(width - 1)) {\n return this.notn(width).iaddn(1).ineg();\n }\n return this.clone();\n };\n\n BN.prototype.isNeg = function isNeg () {\n return this.negative !== 0;\n };\n\n // Return negative clone of `this`\n BN.prototype.neg = function neg () {\n return this.clone().ineg();\n };\n\n BN.prototype.ineg = function ineg () {\n if (!this.isZero()) {\n this.negative ^= 1;\n }\n\n return this;\n };\n\n // Or `num` with `this` in-place\n BN.prototype.iuor = function iuor (num) {\n while (this.length < num.length) {\n this.words[this.length++] = 0;\n }\n\n for (var i = 0; i < num.length; i++) {\n this.words[i] = this.words[i] | num.words[i];\n }\n\n return this.strip();\n };\n\n BN.prototype.ior = function ior (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuor(num);\n };\n\n // Or `num` with `this`\n BN.prototype.or = function or (num) {\n if (this.length > num.length) return this.clone().ior(num);\n return num.clone().ior(this);\n };\n\n BN.prototype.uor = function uor (num) {\n if (this.length > num.length) return this.clone().iuor(num);\n return num.clone().iuor(this);\n };\n\n // And `num` with `this` in-place\n BN.prototype.iuand = function iuand (num) {\n // b = min-length(num, this)\n var b;\n if (this.length > num.length) {\n b = num;\n } else {\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = this.words[i] & num.words[i];\n }\n\n this.length = b.length;\n\n return this.strip();\n };\n\n BN.prototype.iand = function iand (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuand(num);\n };\n\n // And `num` with `this`\n BN.prototype.and = function and (num) {\n if (this.length > num.length) return this.clone().iand(num);\n return num.clone().iand(this);\n };\n\n BN.prototype.uand = function uand (num) {\n if (this.length > num.length) return this.clone().iuand(num);\n return num.clone().iuand(this);\n };\n\n // Xor `num` with `this` in-place\n BN.prototype.iuxor = function iuxor (num) {\n // a.length > b.length\n var a;\n var b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n for (var i = 0; i < b.length; i++) {\n this.words[i] = a.words[i] ^ b.words[i];\n }\n\n if (this !== a) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = a.length;\n\n return this.strip();\n };\n\n BN.prototype.ixor = function ixor (num) {\n assert((this.negative | num.negative) === 0);\n return this.iuxor(num);\n };\n\n // Xor `num` with `this`\n BN.prototype.xor = function xor (num) {\n if (this.length > num.length) return this.clone().ixor(num);\n return num.clone().ixor(this);\n };\n\n BN.prototype.uxor = function uxor (num) {\n if (this.length > num.length) return this.clone().iuxor(num);\n return num.clone().iuxor(this);\n };\n\n // Not ``this`` with ``width`` bitwidth\n BN.prototype.inotn = function inotn (width) {\n assert(typeof width === 'number' && width >= 0);\n\n var bytesNeeded = Math.ceil(width / 26) | 0;\n var bitsLeft = width % 26;\n\n // Extend the buffer with leading zeroes\n this._expand(bytesNeeded);\n\n if (bitsLeft > 0) {\n bytesNeeded--;\n }\n\n // Handle complete words\n for (var i = 0; i < bytesNeeded; i++) {\n this.words[i] = ~this.words[i] & 0x3ffffff;\n }\n\n // Handle the residue\n if (bitsLeft > 0) {\n this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));\n }\n\n // And remove leading zeroes\n return this.strip();\n };\n\n BN.prototype.notn = function notn (width) {\n return this.clone().inotn(width);\n };\n\n // Set `bit` of `this`\n BN.prototype.setn = function setn (bit, val) {\n assert(typeof bit === 'number' && bit >= 0);\n\n var off = (bit / 26) | 0;\n var wbit = bit % 26;\n\n this._expand(off + 1);\n\n if (val) {\n this.words[off] = this.words[off] | (1 << wbit);\n } else {\n this.words[off] = this.words[off] & ~(1 << wbit);\n }\n\n return this.strip();\n };\n\n // Add `num` to `this` in-place\n BN.prototype.iadd = function iadd (num) {\n var r;\n\n // negative + positive\n if (this.negative !== 0 && num.negative === 0) {\n this.negative = 0;\n r = this.isub(num);\n this.negative ^= 1;\n return this._normSign();\n\n // positive + negative\n } else if (this.negative === 0 && num.negative !== 0) {\n num.negative = 0;\n r = this.isub(num);\n num.negative = 1;\n return r._normSign();\n }\n\n // a.length > b.length\n var a, b;\n if (this.length > num.length) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) + (b.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n this.words[i] = r & 0x3ffffff;\n carry = r >>> 26;\n }\n\n this.length = a.length;\n if (carry !== 0) {\n this.words[this.length] = carry;\n this.length++;\n // Copy the rest of the words\n } else if (a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n return this;\n };\n\n // Add `num` to `this`\n BN.prototype.add = function add (num) {\n var res;\n if (num.negative !== 0 && this.negative === 0) {\n num.negative = 0;\n res = this.sub(num);\n num.negative ^= 1;\n return res;\n } else if (num.negative === 0 && this.negative !== 0) {\n this.negative = 0;\n res = num.sub(this);\n this.negative = 1;\n return res;\n }\n\n if (this.length > num.length) return this.clone().iadd(num);\n\n return num.clone().iadd(this);\n };\n\n // Subtract `num` from `this` in-place\n BN.prototype.isub = function isub (num) {\n // this - (-num) = this + num\n if (num.negative !== 0) {\n num.negative = 0;\n var r = this.iadd(num);\n num.negative = 1;\n return r._normSign();\n\n // -this - num = -(this + num)\n } else if (this.negative !== 0) {\n this.negative = 0;\n this.iadd(num);\n this.negative = 1;\n return this._normSign();\n }\n\n // At this point both numbers are positive\n var cmp = this.cmp(num);\n\n // Optimization - zeroify\n if (cmp === 0) {\n this.negative = 0;\n this.length = 1;\n this.words[0] = 0;\n return this;\n }\n\n // a > b\n var a, b;\n if (cmp > 0) {\n a = this;\n b = num;\n } else {\n a = num;\n b = this;\n }\n\n var carry = 0;\n for (var i = 0; i < b.length; i++) {\n r = (a.words[i] | 0) - (b.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n for (; carry !== 0 && i < a.length; i++) {\n r = (a.words[i] | 0) + carry;\n carry = r >> 26;\n this.words[i] = r & 0x3ffffff;\n }\n\n // Copy rest of the words\n if (carry === 0 && i < a.length && a !== this) {\n for (; i < a.length; i++) {\n this.words[i] = a.words[i];\n }\n }\n\n this.length = Math.max(this.length, i);\n\n if (a !== this) {\n this.negative = 1;\n }\n\n return this.strip();\n };\n\n // Subtract `num` from `this`\n BN.prototype.sub = function sub (num) {\n return this.clone().isub(num);\n };\n\n function smallMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n var len = (self.length + num.length) | 0;\n out.length = len;\n len = (len - 1) | 0;\n\n // Peel one iteration (compiler can't do it, because of code complexity)\n var a = self.words[0] | 0;\n var b = num.words[0] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n var carry = (r / 0x4000000) | 0;\n out.words[0] = lo;\n\n for (var k = 1; k < len; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = carry >>> 26;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = (k - j) | 0;\n a = self.words[i] | 0;\n b = num.words[j] | 0;\n r = a * b + rword;\n ncarry += (r / 0x4000000) | 0;\n rword = r & 0x3ffffff;\n }\n out.words[k] = rword | 0;\n carry = ncarry | 0;\n }\n if (carry !== 0) {\n out.words[k] = carry | 0;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n // TODO(indutny): it may be reasonable to omit it for users who don't need\n // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit\n // multiplication (like elliptic secp256k1).\n var comb10MulTo = function comb10MulTo (self, num, out) {\n var a = self.words;\n var b = num.words;\n var o = out.words;\n var c = 0;\n var lo;\n var mid;\n var hi;\n var a0 = a[0] | 0;\n var al0 = a0 & 0x1fff;\n var ah0 = a0 >>> 13;\n var a1 = a[1] | 0;\n var al1 = a1 & 0x1fff;\n var ah1 = a1 >>> 13;\n var a2 = a[2] | 0;\n var al2 = a2 & 0x1fff;\n var ah2 = a2 >>> 13;\n var a3 = a[3] | 0;\n var al3 = a3 & 0x1fff;\n var ah3 = a3 >>> 13;\n var a4 = a[4] | 0;\n var al4 = a4 & 0x1fff;\n var ah4 = a4 >>> 13;\n var a5 = a[5] | 0;\n var al5 = a5 & 0x1fff;\n var ah5 = a5 >>> 13;\n var a6 = a[6] | 0;\n var al6 = a6 & 0x1fff;\n var ah6 = a6 >>> 13;\n var a7 = a[7] | 0;\n var al7 = a7 & 0x1fff;\n var ah7 = a7 >>> 13;\n var a8 = a[8] | 0;\n var al8 = a8 & 0x1fff;\n var ah8 = a8 >>> 13;\n var a9 = a[9] | 0;\n var al9 = a9 & 0x1fff;\n var ah9 = a9 >>> 13;\n var b0 = b[0] | 0;\n var bl0 = b0 & 0x1fff;\n var bh0 = b0 >>> 13;\n var b1 = b[1] | 0;\n var bl1 = b1 & 0x1fff;\n var bh1 = b1 >>> 13;\n var b2 = b[2] | 0;\n var bl2 = b2 & 0x1fff;\n var bh2 = b2 >>> 13;\n var b3 = b[3] | 0;\n var bl3 = b3 & 0x1fff;\n var bh3 = b3 >>> 13;\n var b4 = b[4] | 0;\n var bl4 = b4 & 0x1fff;\n var bh4 = b4 >>> 13;\n var b5 = b[5] | 0;\n var bl5 = b5 & 0x1fff;\n var bh5 = b5 >>> 13;\n var b6 = b[6] | 0;\n var bl6 = b6 & 0x1fff;\n var bh6 = b6 >>> 13;\n var b7 = b[7] | 0;\n var bl7 = b7 & 0x1fff;\n var bh7 = b7 >>> 13;\n var b8 = b[8] | 0;\n var bl8 = b8 & 0x1fff;\n var bh8 = b8 >>> 13;\n var b9 = b[9] | 0;\n var bl9 = b9 & 0x1fff;\n var bh9 = b9 >>> 13;\n\n out.negative = self.negative ^ num.negative;\n out.length = 19;\n /* k = 0 */\n lo = Math.imul(al0, bl0);\n mid = Math.imul(al0, bh0);\n mid = (mid + Math.imul(ah0, bl0)) | 0;\n hi = Math.imul(ah0, bh0);\n var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;\n w0 &= 0x3ffffff;\n /* k = 1 */\n lo = Math.imul(al1, bl0);\n mid = Math.imul(al1, bh0);\n mid = (mid + Math.imul(ah1, bl0)) | 0;\n hi = Math.imul(ah1, bh0);\n lo = (lo + Math.imul(al0, bl1)) | 0;\n mid = (mid + Math.imul(al0, bh1)) | 0;\n mid = (mid + Math.imul(ah0, bl1)) | 0;\n hi = (hi + Math.imul(ah0, bh1)) | 0;\n var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;\n w1 &= 0x3ffffff;\n /* k = 2 */\n lo = Math.imul(al2, bl0);\n mid = Math.imul(al2, bh0);\n mid = (mid + Math.imul(ah2, bl0)) | 0;\n hi = Math.imul(ah2, bh0);\n lo = (lo + Math.imul(al1, bl1)) | 0;\n mid = (mid + Math.imul(al1, bh1)) | 0;\n mid = (mid + Math.imul(ah1, bl1)) | 0;\n hi = (hi + Math.imul(ah1, bh1)) | 0;\n lo = (lo + Math.imul(al0, bl2)) | 0;\n mid = (mid + Math.imul(al0, bh2)) | 0;\n mid = (mid + Math.imul(ah0, bl2)) | 0;\n hi = (hi + Math.imul(ah0, bh2)) | 0;\n var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;\n w2 &= 0x3ffffff;\n /* k = 3 */\n lo = Math.imul(al3, bl0);\n mid = Math.imul(al3, bh0);\n mid = (mid + Math.imul(ah3, bl0)) | 0;\n hi = Math.imul(ah3, bh0);\n lo = (lo + Math.imul(al2, bl1)) | 0;\n mid = (mid + Math.imul(al2, bh1)) | 0;\n mid = (mid + Math.imul(ah2, bl1)) | 0;\n hi = (hi + Math.imul(ah2, bh1)) | 0;\n lo = (lo + Math.imul(al1, bl2)) | 0;\n mid = (mid + Math.imul(al1, bh2)) | 0;\n mid = (mid + Math.imul(ah1, bl2)) | 0;\n hi = (hi + Math.imul(ah1, bh2)) | 0;\n lo = (lo + Math.imul(al0, bl3)) | 0;\n mid = (mid + Math.imul(al0, bh3)) | 0;\n mid = (mid + Math.imul(ah0, bl3)) | 0;\n hi = (hi + Math.imul(ah0, bh3)) | 0;\n var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;\n w3 &= 0x3ffffff;\n /* k = 4 */\n lo = Math.imul(al4, bl0);\n mid = Math.imul(al4, bh0);\n mid = (mid + Math.imul(ah4, bl0)) | 0;\n hi = Math.imul(ah4, bh0);\n lo = (lo + Math.imul(al3, bl1)) | 0;\n mid = (mid + Math.imul(al3, bh1)) | 0;\n mid = (mid + Math.imul(ah3, bl1)) | 0;\n hi = (hi + Math.imul(ah3, bh1)) | 0;\n lo = (lo + Math.imul(al2, bl2)) | 0;\n mid = (mid + Math.imul(al2, bh2)) | 0;\n mid = (mid + Math.imul(ah2, bl2)) | 0;\n hi = (hi + Math.imul(ah2, bh2)) | 0;\n lo = (lo + Math.imul(al1, bl3)) | 0;\n mid = (mid + Math.imul(al1, bh3)) | 0;\n mid = (mid + Math.imul(ah1, bl3)) | 0;\n hi = (hi + Math.imul(ah1, bh3)) | 0;\n lo = (lo + Math.imul(al0, bl4)) | 0;\n mid = (mid + Math.imul(al0, bh4)) | 0;\n mid = (mid + Math.imul(ah0, bl4)) | 0;\n hi = (hi + Math.imul(ah0, bh4)) | 0;\n var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;\n w4 &= 0x3ffffff;\n /* k = 5 */\n lo = Math.imul(al5, bl0);\n mid = Math.imul(al5, bh0);\n mid = (mid + Math.imul(ah5, bl0)) | 0;\n hi = Math.imul(ah5, bh0);\n lo = (lo + Math.imul(al4, bl1)) | 0;\n mid = (mid + Math.imul(al4, bh1)) | 0;\n mid = (mid + Math.imul(ah4, bl1)) | 0;\n hi = (hi + Math.imul(ah4, bh1)) | 0;\n lo = (lo + Math.imul(al3, bl2)) | 0;\n mid = (mid + Math.imul(al3, bh2)) | 0;\n mid = (mid + Math.imul(ah3, bl2)) | 0;\n hi = (hi + Math.imul(ah3, bh2)) | 0;\n lo = (lo + Math.imul(al2, bl3)) | 0;\n mid = (mid + Math.imul(al2, bh3)) | 0;\n mid = (mid + Math.imul(ah2, bl3)) | 0;\n hi = (hi + Math.imul(ah2, bh3)) | 0;\n lo = (lo + Math.imul(al1, bl4)) | 0;\n mid = (mid + Math.imul(al1, bh4)) | 0;\n mid = (mid + Math.imul(ah1, bl4)) | 0;\n hi = (hi + Math.imul(ah1, bh4)) | 0;\n lo = (lo + Math.imul(al0, bl5)) | 0;\n mid = (mid + Math.imul(al0, bh5)) | 0;\n mid = (mid + Math.imul(ah0, bl5)) | 0;\n hi = (hi + Math.imul(ah0, bh5)) | 0;\n var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;\n w5 &= 0x3ffffff;\n /* k = 6 */\n lo = Math.imul(al6, bl0);\n mid = Math.imul(al6, bh0);\n mid = (mid + Math.imul(ah6, bl0)) | 0;\n hi = Math.imul(ah6, bh0);\n lo = (lo + Math.imul(al5, bl1)) | 0;\n mid = (mid + Math.imul(al5, bh1)) | 0;\n mid = (mid + Math.imul(ah5, bl1)) | 0;\n hi = (hi + Math.imul(ah5, bh1)) | 0;\n lo = (lo + Math.imul(al4, bl2)) | 0;\n mid = (mid + Math.imul(al4, bh2)) | 0;\n mid = (mid + Math.imul(ah4, bl2)) | 0;\n hi = (hi + Math.imul(ah4, bh2)) | 0;\n lo = (lo + Math.imul(al3, bl3)) | 0;\n mid = (mid + Math.imul(al3, bh3)) | 0;\n mid = (mid + Math.imul(ah3, bl3)) | 0;\n hi = (hi + Math.imul(ah3, bh3)) | 0;\n lo = (lo + Math.imul(al2, bl4)) | 0;\n mid = (mid + Math.imul(al2, bh4)) | 0;\n mid = (mid + Math.imul(ah2, bl4)) | 0;\n hi = (hi + Math.imul(ah2, bh4)) | 0;\n lo = (lo + Math.imul(al1, bl5)) | 0;\n mid = (mid + Math.imul(al1, bh5)) | 0;\n mid = (mid + Math.imul(ah1, bl5)) | 0;\n hi = (hi + Math.imul(ah1, bh5)) | 0;\n lo = (lo + Math.imul(al0, bl6)) | 0;\n mid = (mid + Math.imul(al0, bh6)) | 0;\n mid = (mid + Math.imul(ah0, bl6)) | 0;\n hi = (hi + Math.imul(ah0, bh6)) | 0;\n var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;\n w6 &= 0x3ffffff;\n /* k = 7 */\n lo = Math.imul(al7, bl0);\n mid = Math.imul(al7, bh0);\n mid = (mid + Math.imul(ah7, bl0)) | 0;\n hi = Math.imul(ah7, bh0);\n lo = (lo + Math.imul(al6, bl1)) | 0;\n mid = (mid + Math.imul(al6, bh1)) | 0;\n mid = (mid + Math.imul(ah6, bl1)) | 0;\n hi = (hi + Math.imul(ah6, bh1)) | 0;\n lo = (lo + Math.imul(al5, bl2)) | 0;\n mid = (mid + Math.imul(al5, bh2)) | 0;\n mid = (mid + Math.imul(ah5, bl2)) | 0;\n hi = (hi + Math.imul(ah5, bh2)) | 0;\n lo = (lo + Math.imul(al4, bl3)) | 0;\n mid = (mid + Math.imul(al4, bh3)) | 0;\n mid = (mid + Math.imul(ah4, bl3)) | 0;\n hi = (hi + Math.imul(ah4, bh3)) | 0;\n lo = (lo + Math.imul(al3, bl4)) | 0;\n mid = (mid + Math.imul(al3, bh4)) | 0;\n mid = (mid + Math.imul(ah3, bl4)) | 0;\n hi = (hi + Math.imul(ah3, bh4)) | 0;\n lo = (lo + Math.imul(al2, bl5)) | 0;\n mid = (mid + Math.imul(al2, bh5)) | 0;\n mid = (mid + Math.imul(ah2, bl5)) | 0;\n hi = (hi + Math.imul(ah2, bh5)) | 0;\n lo = (lo + Math.imul(al1, bl6)) | 0;\n mid = (mid + Math.imul(al1, bh6)) | 0;\n mid = (mid + Math.imul(ah1, bl6)) | 0;\n hi = (hi + Math.imul(ah1, bh6)) | 0;\n lo = (lo + Math.imul(al0, bl7)) | 0;\n mid = (mid + Math.imul(al0, bh7)) | 0;\n mid = (mid + Math.imul(ah0, bl7)) | 0;\n hi = (hi + Math.imul(ah0, bh7)) | 0;\n var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;\n w7 &= 0x3ffffff;\n /* k = 8 */\n lo = Math.imul(al8, bl0);\n mid = Math.imul(al8, bh0);\n mid = (mid + Math.imul(ah8, bl0)) | 0;\n hi = Math.imul(ah8, bh0);\n lo = (lo + Math.imul(al7, bl1)) | 0;\n mid = (mid + Math.imul(al7, bh1)) | 0;\n mid = (mid + Math.imul(ah7, bl1)) | 0;\n hi = (hi + Math.imul(ah7, bh1)) | 0;\n lo = (lo + Math.imul(al6, bl2)) | 0;\n mid = (mid + Math.imul(al6, bh2)) | 0;\n mid = (mid + Math.imul(ah6, bl2)) | 0;\n hi = (hi + Math.imul(ah6, bh2)) | 0;\n lo = (lo + Math.imul(al5, bl3)) | 0;\n mid = (mid + Math.imul(al5, bh3)) | 0;\n mid = (mid + Math.imul(ah5, bl3)) | 0;\n hi = (hi + Math.imul(ah5, bh3)) | 0;\n lo = (lo + Math.imul(al4, bl4)) | 0;\n mid = (mid + Math.imul(al4, bh4)) | 0;\n mid = (mid + Math.imul(ah4, bl4)) | 0;\n hi = (hi + Math.imul(ah4, bh4)) | 0;\n lo = (lo + Math.imul(al3, bl5)) | 0;\n mid = (mid + Math.imul(al3, bh5)) | 0;\n mid = (mid + Math.imul(ah3, bl5)) | 0;\n hi = (hi + Math.imul(ah3, bh5)) | 0;\n lo = (lo + Math.imul(al2, bl6)) | 0;\n mid = (mid + Math.imul(al2, bh6)) | 0;\n mid = (mid + Math.imul(ah2, bl6)) | 0;\n hi = (hi + Math.imul(ah2, bh6)) | 0;\n lo = (lo + Math.imul(al1, bl7)) | 0;\n mid = (mid + Math.imul(al1, bh7)) | 0;\n mid = (mid + Math.imul(ah1, bl7)) | 0;\n hi = (hi + Math.imul(ah1, bh7)) | 0;\n lo = (lo + Math.imul(al0, bl8)) | 0;\n mid = (mid + Math.imul(al0, bh8)) | 0;\n mid = (mid + Math.imul(ah0, bl8)) | 0;\n hi = (hi + Math.imul(ah0, bh8)) | 0;\n var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;\n w8 &= 0x3ffffff;\n /* k = 9 */\n lo = Math.imul(al9, bl0);\n mid = Math.imul(al9, bh0);\n mid = (mid + Math.imul(ah9, bl0)) | 0;\n hi = Math.imul(ah9, bh0);\n lo = (lo + Math.imul(al8, bl1)) | 0;\n mid = (mid + Math.imul(al8, bh1)) | 0;\n mid = (mid + Math.imul(ah8, bl1)) | 0;\n hi = (hi + Math.imul(ah8, bh1)) | 0;\n lo = (lo + Math.imul(al7, bl2)) | 0;\n mid = (mid + Math.imul(al7, bh2)) | 0;\n mid = (mid + Math.imul(ah7, bl2)) | 0;\n hi = (hi + Math.imul(ah7, bh2)) | 0;\n lo = (lo + Math.imul(al6, bl3)) | 0;\n mid = (mid + Math.imul(al6, bh3)) | 0;\n mid = (mid + Math.imul(ah6, bl3)) | 0;\n hi = (hi + Math.imul(ah6, bh3)) | 0;\n lo = (lo + Math.imul(al5, bl4)) | 0;\n mid = (mid + Math.imul(al5, bh4)) | 0;\n mid = (mid + Math.imul(ah5, bl4)) | 0;\n hi = (hi + Math.imul(ah5, bh4)) | 0;\n lo = (lo + Math.imul(al4, bl5)) | 0;\n mid = (mid + Math.imul(al4, bh5)) | 0;\n mid = (mid + Math.imul(ah4, bl5)) | 0;\n hi = (hi + Math.imul(ah4, bh5)) | 0;\n lo = (lo + Math.imul(al3, bl6)) | 0;\n mid = (mid + Math.imul(al3, bh6)) | 0;\n mid = (mid + Math.imul(ah3, bl6)) | 0;\n hi = (hi + Math.imul(ah3, bh6)) | 0;\n lo = (lo + Math.imul(al2, bl7)) | 0;\n mid = (mid + Math.imul(al2, bh7)) | 0;\n mid = (mid + Math.imul(ah2, bl7)) | 0;\n hi = (hi + Math.imul(ah2, bh7)) | 0;\n lo = (lo + Math.imul(al1, bl8)) | 0;\n mid = (mid + Math.imul(al1, bh8)) | 0;\n mid = (mid + Math.imul(ah1, bl8)) | 0;\n hi = (hi + Math.imul(ah1, bh8)) | 0;\n lo = (lo + Math.imul(al0, bl9)) | 0;\n mid = (mid + Math.imul(al0, bh9)) | 0;\n mid = (mid + Math.imul(ah0, bl9)) | 0;\n hi = (hi + Math.imul(ah0, bh9)) | 0;\n var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;\n w9 &= 0x3ffffff;\n /* k = 10 */\n lo = Math.imul(al9, bl1);\n mid = Math.imul(al9, bh1);\n mid = (mid + Math.imul(ah9, bl1)) | 0;\n hi = Math.imul(ah9, bh1);\n lo = (lo + Math.imul(al8, bl2)) | 0;\n mid = (mid + Math.imul(al8, bh2)) | 0;\n mid = (mid + Math.imul(ah8, bl2)) | 0;\n hi = (hi + Math.imul(ah8, bh2)) | 0;\n lo = (lo + Math.imul(al7, bl3)) | 0;\n mid = (mid + Math.imul(al7, bh3)) | 0;\n mid = (mid + Math.imul(ah7, bl3)) | 0;\n hi = (hi + Math.imul(ah7, bh3)) | 0;\n lo = (lo + Math.imul(al6, bl4)) | 0;\n mid = (mid + Math.imul(al6, bh4)) | 0;\n mid = (mid + Math.imul(ah6, bl4)) | 0;\n hi = (hi + Math.imul(ah6, bh4)) | 0;\n lo = (lo + Math.imul(al5, bl5)) | 0;\n mid = (mid + Math.imul(al5, bh5)) | 0;\n mid = (mid + Math.imul(ah5, bl5)) | 0;\n hi = (hi + Math.imul(ah5, bh5)) | 0;\n lo = (lo + Math.imul(al4, bl6)) | 0;\n mid = (mid + Math.imul(al4, bh6)) | 0;\n mid = (mid + Math.imul(ah4, bl6)) | 0;\n hi = (hi + Math.imul(ah4, bh6)) | 0;\n lo = (lo + Math.imul(al3, bl7)) | 0;\n mid = (mid + Math.imul(al3, bh7)) | 0;\n mid = (mid + Math.imul(ah3, bl7)) | 0;\n hi = (hi + Math.imul(ah3, bh7)) | 0;\n lo = (lo + Math.imul(al2, bl8)) | 0;\n mid = (mid + Math.imul(al2, bh8)) | 0;\n mid = (mid + Math.imul(ah2, bl8)) | 0;\n hi = (hi + Math.imul(ah2, bh8)) | 0;\n lo = (lo + Math.imul(al1, bl9)) | 0;\n mid = (mid + Math.imul(al1, bh9)) | 0;\n mid = (mid + Math.imul(ah1, bl9)) | 0;\n hi = (hi + Math.imul(ah1, bh9)) | 0;\n var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;\n w10 &= 0x3ffffff;\n /* k = 11 */\n lo = Math.imul(al9, bl2);\n mid = Math.imul(al9, bh2);\n mid = (mid + Math.imul(ah9, bl2)) | 0;\n hi = Math.imul(ah9, bh2);\n lo = (lo + Math.imul(al8, bl3)) | 0;\n mid = (mid + Math.imul(al8, bh3)) | 0;\n mid = (mid + Math.imul(ah8, bl3)) | 0;\n hi = (hi + Math.imul(ah8, bh3)) | 0;\n lo = (lo + Math.imul(al7, bl4)) | 0;\n mid = (mid + Math.imul(al7, bh4)) | 0;\n mid = (mid + Math.imul(ah7, bl4)) | 0;\n hi = (hi + Math.imul(ah7, bh4)) | 0;\n lo = (lo + Math.imul(al6, bl5)) | 0;\n mid = (mid + Math.imul(al6, bh5)) | 0;\n mid = (mid + Math.imul(ah6, bl5)) | 0;\n hi = (hi + Math.imul(ah6, bh5)) | 0;\n lo = (lo + Math.imul(al5, bl6)) | 0;\n mid = (mid + Math.imul(al5, bh6)) | 0;\n mid = (mid + Math.imul(ah5, bl6)) | 0;\n hi = (hi + Math.imul(ah5, bh6)) | 0;\n lo = (lo + Math.imul(al4, bl7)) | 0;\n mid = (mid + Math.imul(al4, bh7)) | 0;\n mid = (mid + Math.imul(ah4, bl7)) | 0;\n hi = (hi + Math.imul(ah4, bh7)) | 0;\n lo = (lo + Math.imul(al3, bl8)) | 0;\n mid = (mid + Math.imul(al3, bh8)) | 0;\n mid = (mid + Math.imul(ah3, bl8)) | 0;\n hi = (hi + Math.imul(ah3, bh8)) | 0;\n lo = (lo + Math.imul(al2, bl9)) | 0;\n mid = (mid + Math.imul(al2, bh9)) | 0;\n mid = (mid + Math.imul(ah2, bl9)) | 0;\n hi = (hi + Math.imul(ah2, bh9)) | 0;\n var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;\n w11 &= 0x3ffffff;\n /* k = 12 */\n lo = Math.imul(al9, bl3);\n mid = Math.imul(al9, bh3);\n mid = (mid + Math.imul(ah9, bl3)) | 0;\n hi = Math.imul(ah9, bh3);\n lo = (lo + Math.imul(al8, bl4)) | 0;\n mid = (mid + Math.imul(al8, bh4)) | 0;\n mid = (mid + Math.imul(ah8, bl4)) | 0;\n hi = (hi + Math.imul(ah8, bh4)) | 0;\n lo = (lo + Math.imul(al7, bl5)) | 0;\n mid = (mid + Math.imul(al7, bh5)) | 0;\n mid = (mid + Math.imul(ah7, bl5)) | 0;\n hi = (hi + Math.imul(ah7, bh5)) | 0;\n lo = (lo + Math.imul(al6, bl6)) | 0;\n mid = (mid + Math.imul(al6, bh6)) | 0;\n mid = (mid + Math.imul(ah6, bl6)) | 0;\n hi = (hi + Math.imul(ah6, bh6)) | 0;\n lo = (lo + Math.imul(al5, bl7)) | 0;\n mid = (mid + Math.imul(al5, bh7)) | 0;\n mid = (mid + Math.imul(ah5, bl7)) | 0;\n hi = (hi + Math.imul(ah5, bh7)) | 0;\n lo = (lo + Math.imul(al4, bl8)) | 0;\n mid = (mid + Math.imul(al4, bh8)) | 0;\n mid = (mid + Math.imul(ah4, bl8)) | 0;\n hi = (hi + Math.imul(ah4, bh8)) | 0;\n lo = (lo + Math.imul(al3, bl9)) | 0;\n mid = (mid + Math.imul(al3, bh9)) | 0;\n mid = (mid + Math.imul(ah3, bl9)) | 0;\n hi = (hi + Math.imul(ah3, bh9)) | 0;\n var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;\n w12 &= 0x3ffffff;\n /* k = 13 */\n lo = Math.imul(al9, bl4);\n mid = Math.imul(al9, bh4);\n mid = (mid + Math.imul(ah9, bl4)) | 0;\n hi = Math.imul(ah9, bh4);\n lo = (lo + Math.imul(al8, bl5)) | 0;\n mid = (mid + Math.imul(al8, bh5)) | 0;\n mid = (mid + Math.imul(ah8, bl5)) | 0;\n hi = (hi + Math.imul(ah8, bh5)) | 0;\n lo = (lo + Math.imul(al7, bl6)) | 0;\n mid = (mid + Math.imul(al7, bh6)) | 0;\n mid = (mid + Math.imul(ah7, bl6)) | 0;\n hi = (hi + Math.imul(ah7, bh6)) | 0;\n lo = (lo + Math.imul(al6, bl7)) | 0;\n mid = (mid + Math.imul(al6, bh7)) | 0;\n mid = (mid + Math.imul(ah6, bl7)) | 0;\n hi = (hi + Math.imul(ah6, bh7)) | 0;\n lo = (lo + Math.imul(al5, bl8)) | 0;\n mid = (mid + Math.imul(al5, bh8)) | 0;\n mid = (mid + Math.imul(ah5, bl8)) | 0;\n hi = (hi + Math.imul(ah5, bh8)) | 0;\n lo = (lo + Math.imul(al4, bl9)) | 0;\n mid = (mid + Math.imul(al4, bh9)) | 0;\n mid = (mid + Math.imul(ah4, bl9)) | 0;\n hi = (hi + Math.imul(ah4, bh9)) | 0;\n var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;\n w13 &= 0x3ffffff;\n /* k = 14 */\n lo = Math.imul(al9, bl5);\n mid = Math.imul(al9, bh5);\n mid = (mid + Math.imul(ah9, bl5)) | 0;\n hi = Math.imul(ah9, bh5);\n lo = (lo + Math.imul(al8, bl6)) | 0;\n mid = (mid + Math.imul(al8, bh6)) | 0;\n mid = (mid + Math.imul(ah8, bl6)) | 0;\n hi = (hi + Math.imul(ah8, bh6)) | 0;\n lo = (lo + Math.imul(al7, bl7)) | 0;\n mid = (mid + Math.imul(al7, bh7)) | 0;\n mid = (mid + Math.imul(ah7, bl7)) | 0;\n hi = (hi + Math.imul(ah7, bh7)) | 0;\n lo = (lo + Math.imul(al6, bl8)) | 0;\n mid = (mid + Math.imul(al6, bh8)) | 0;\n mid = (mid + Math.imul(ah6, bl8)) | 0;\n hi = (hi + Math.imul(ah6, bh8)) | 0;\n lo = (lo + Math.imul(al5, bl9)) | 0;\n mid = (mid + Math.imul(al5, bh9)) | 0;\n mid = (mid + Math.imul(ah5, bl9)) | 0;\n hi = (hi + Math.imul(ah5, bh9)) | 0;\n var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;\n w14 &= 0x3ffffff;\n /* k = 15 */\n lo = Math.imul(al9, bl6);\n mid = Math.imul(al9, bh6);\n mid = (mid + Math.imul(ah9, bl6)) | 0;\n hi = Math.imul(ah9, bh6);\n lo = (lo + Math.imul(al8, bl7)) | 0;\n mid = (mid + Math.imul(al8, bh7)) | 0;\n mid = (mid + Math.imul(ah8, bl7)) | 0;\n hi = (hi + Math.imul(ah8, bh7)) | 0;\n lo = (lo + Math.imul(al7, bl8)) | 0;\n mid = (mid + Math.imul(al7, bh8)) | 0;\n mid = (mid + Math.imul(ah7, bl8)) | 0;\n hi = (hi + Math.imul(ah7, bh8)) | 0;\n lo = (lo + Math.imul(al6, bl9)) | 0;\n mid = (mid + Math.imul(al6, bh9)) | 0;\n mid = (mid + Math.imul(ah6, bl9)) | 0;\n hi = (hi + Math.imul(ah6, bh9)) | 0;\n var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;\n w15 &= 0x3ffffff;\n /* k = 16 */\n lo = Math.imul(al9, bl7);\n mid = Math.imul(al9, bh7);\n mid = (mid + Math.imul(ah9, bl7)) | 0;\n hi = Math.imul(ah9, bh7);\n lo = (lo + Math.imul(al8, bl8)) | 0;\n mid = (mid + Math.imul(al8, bh8)) | 0;\n mid = (mid + Math.imul(ah8, bl8)) | 0;\n hi = (hi + Math.imul(ah8, bh8)) | 0;\n lo = (lo + Math.imul(al7, bl9)) | 0;\n mid = (mid + Math.imul(al7, bh9)) | 0;\n mid = (mid + Math.imul(ah7, bl9)) | 0;\n hi = (hi + Math.imul(ah7, bh9)) | 0;\n var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;\n w16 &= 0x3ffffff;\n /* k = 17 */\n lo = Math.imul(al9, bl8);\n mid = Math.imul(al9, bh8);\n mid = (mid + Math.imul(ah9, bl8)) | 0;\n hi = Math.imul(ah9, bh8);\n lo = (lo + Math.imul(al8, bl9)) | 0;\n mid = (mid + Math.imul(al8, bh9)) | 0;\n mid = (mid + Math.imul(ah8, bl9)) | 0;\n hi = (hi + Math.imul(ah8, bh9)) | 0;\n var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;\n w17 &= 0x3ffffff;\n /* k = 18 */\n lo = Math.imul(al9, bl9);\n mid = Math.imul(al9, bh9);\n mid = (mid + Math.imul(ah9, bl9)) | 0;\n hi = Math.imul(ah9, bh9);\n var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;\n c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;\n w18 &= 0x3ffffff;\n o[0] = w0;\n o[1] = w1;\n o[2] = w2;\n o[3] = w3;\n o[4] = w4;\n o[5] = w5;\n o[6] = w6;\n o[7] = w7;\n o[8] = w8;\n o[9] = w9;\n o[10] = w10;\n o[11] = w11;\n o[12] = w12;\n o[13] = w13;\n o[14] = w14;\n o[15] = w15;\n o[16] = w16;\n o[17] = w17;\n o[18] = w18;\n if (c !== 0) {\n o[19] = c;\n out.length++;\n }\n return out;\n };\n\n // Polyfill comb\n if (!Math.imul) {\n comb10MulTo = smallMulTo;\n }\n\n function bigMulTo (self, num, out) {\n out.negative = num.negative ^ self.negative;\n out.length = self.length + num.length;\n\n var carry = 0;\n var hncarry = 0;\n for (var k = 0; k < out.length - 1; k++) {\n // Sum all words with the same `i + j = k` and accumulate `ncarry`,\n // note that ncarry could be >= 0x3ffffff\n var ncarry = hncarry;\n hncarry = 0;\n var rword = carry & 0x3ffffff;\n var maxJ = Math.min(k, num.length - 1);\n for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {\n var i = k - j;\n var a = self.words[i] | 0;\n var b = num.words[j] | 0;\n var r = a * b;\n\n var lo = r & 0x3ffffff;\n ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;\n lo = (lo + rword) | 0;\n rword = lo & 0x3ffffff;\n ncarry = (ncarry + (lo >>> 26)) | 0;\n\n hncarry += ncarry >>> 26;\n ncarry &= 0x3ffffff;\n }\n out.words[k] = rword;\n carry = ncarry;\n ncarry = hncarry;\n }\n if (carry !== 0) {\n out.words[k] = carry;\n } else {\n out.length--;\n }\n\n return out.strip();\n }\n\n function jumboMulTo (self, num, out) {\n var fftm = new FFTM();\n return fftm.mulp(self, num, out);\n }\n\n BN.prototype.mulTo = function mulTo (num, out) {\n var res;\n var len = this.length + num.length;\n if (this.length === 10 && num.length === 10) {\n res = comb10MulTo(this, num, out);\n } else if (len < 63) {\n res = smallMulTo(this, num, out);\n } else if (len < 1024) {\n res = bigMulTo(this, num, out);\n } else {\n res = jumboMulTo(this, num, out);\n }\n\n return res;\n };\n\n // Cooley-Tukey algorithm for FFT\n // slightly revisited to rely on looping instead of recursion\n\n function FFTM (x, y) {\n this.x = x;\n this.y = y;\n }\n\n FFTM.prototype.makeRBT = function makeRBT (N) {\n var t = new Array(N);\n var l = BN.prototype._countBits(N) - 1;\n for (var i = 0; i < N; i++) {\n t[i] = this.revBin(i, l, N);\n }\n\n return t;\n };\n\n // Returns binary-reversed representation of `x`\n FFTM.prototype.revBin = function revBin (x, l, N) {\n if (x === 0 || x === N - 1) return x;\n\n var rb = 0;\n for (var i = 0; i < l; i++) {\n rb |= (x & 1) << (l - i - 1);\n x >>= 1;\n }\n\n return rb;\n };\n\n // Performs \"tweedling\" phase, therefore 'emulating'\n // behaviour of the recursive algorithm\n FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {\n for (var i = 0; i < N; i++) {\n rtws[i] = rws[rbt[i]];\n itws[i] = iws[rbt[i]];\n }\n };\n\n FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {\n this.permute(rbt, rws, iws, rtws, itws, N);\n\n for (var s = 1; s < N; s <<= 1) {\n var l = s << 1;\n\n var rtwdf = Math.cos(2 * Math.PI / l);\n var itwdf = Math.sin(2 * Math.PI / l);\n\n for (var p = 0; p < N; p += l) {\n var rtwdf_ = rtwdf;\n var itwdf_ = itwdf;\n\n for (var j = 0; j < s; j++) {\n var re = rtws[p + j];\n var ie = itws[p + j];\n\n var ro = rtws[p + j + s];\n var io = itws[p + j + s];\n\n var rx = rtwdf_ * ro - itwdf_ * io;\n\n io = rtwdf_ * io + itwdf_ * ro;\n ro = rx;\n\n rtws[p + j] = re + ro;\n itws[p + j] = ie + io;\n\n rtws[p + j + s] = re - ro;\n itws[p + j + s] = ie - io;\n\n /* jshint maxdepth : false */\n if (j !== l) {\n rx = rtwdf * rtwdf_ - itwdf * itwdf_;\n\n itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;\n rtwdf_ = rx;\n }\n }\n }\n }\n };\n\n FFTM.prototype.guessLen13b = function guessLen13b (n, m) {\n var N = Math.max(m, n) | 1;\n var odd = N & 1;\n var i = 0;\n for (N = N / 2 | 0; N; N = N >>> 1) {\n i++;\n }\n\n return 1 << i + 1 + odd;\n };\n\n FFTM.prototype.conjugate = function conjugate (rws, iws, N) {\n if (N <= 1) return;\n\n for (var i = 0; i < N / 2; i++) {\n var t = rws[i];\n\n rws[i] = rws[N - i - 1];\n rws[N - i - 1] = t;\n\n t = iws[i];\n\n iws[i] = -iws[N - i - 1];\n iws[N - i - 1] = -t;\n }\n };\n\n FFTM.prototype.normalize13b = function normalize13b (ws, N) {\n var carry = 0;\n for (var i = 0; i < N / 2; i++) {\n var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +\n Math.round(ws[2 * i] / N) +\n carry;\n\n ws[i] = w & 0x3ffffff;\n\n if (w < 0x4000000) {\n carry = 0;\n } else {\n carry = w / 0x4000000 | 0;\n }\n }\n\n return ws;\n };\n\n FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {\n var carry = 0;\n for (var i = 0; i < len; i++) {\n carry = carry + (ws[i] | 0);\n\n rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;\n rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;\n }\n\n // Pad with zeroes\n for (i = 2 * len; i < N; ++i) {\n rws[i] = 0;\n }\n\n assert(carry === 0);\n assert((carry & ~0x1fff) === 0);\n };\n\n FFTM.prototype.stub = function stub (N) {\n var ph = new Array(N);\n for (var i = 0; i < N; i++) {\n ph[i] = 0;\n }\n\n return ph;\n };\n\n FFTM.prototype.mulp = function mulp (x, y, out) {\n var N = 2 * this.guessLen13b(x.length, y.length);\n\n var rbt = this.makeRBT(N);\n\n var _ = this.stub(N);\n\n var rws = new Array(N);\n var rwst = new Array(N);\n var iwst = new Array(N);\n\n var nrws = new Array(N);\n var nrwst = new Array(N);\n var niwst = new Array(N);\n\n var rmws = out.words;\n rmws.length = N;\n\n this.convert13b(x.words, x.length, rws, N);\n this.convert13b(y.words, y.length, nrws, N);\n\n this.transform(rws, _, rwst, iwst, N, rbt);\n this.transform(nrws, _, nrwst, niwst, N, rbt);\n\n for (var i = 0; i < N; i++) {\n var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];\n iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];\n rwst[i] = rx;\n }\n\n this.conjugate(rwst, iwst, N);\n this.transform(rwst, iwst, rmws, _, N, rbt);\n this.conjugate(rmws, _, N);\n this.normalize13b(rmws, N);\n\n out.negative = x.negative ^ y.negative;\n out.length = x.length + y.length;\n return out.strip();\n };\n\n // Multiply `this` by `num`\n BN.prototype.mul = function mul (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return this.mulTo(num, out);\n };\n\n // Multiply employing FFT\n BN.prototype.mulf = function mulf (num) {\n var out = new BN(null);\n out.words = new Array(this.length + num.length);\n return jumboMulTo(this, num, out);\n };\n\n // In-place Multiplication\n BN.prototype.imul = function imul (num) {\n return this.clone().mulTo(num, this);\n };\n\n BN.prototype.imuln = function imuln (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n\n // Carry\n var carry = 0;\n for (var i = 0; i < this.length; i++) {\n var w = (this.words[i] | 0) * num;\n var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);\n carry >>= 26;\n carry += (w / 0x4000000) | 0;\n // NOTE: lo is 27bit maximum\n carry += lo >>> 26;\n this.words[i] = lo & 0x3ffffff;\n }\n\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n\n return this;\n };\n\n BN.prototype.muln = function muln (num) {\n return this.clone().imuln(num);\n };\n\n // `this` * `this`\n BN.prototype.sqr = function sqr () {\n return this.mul(this);\n };\n\n // `this` * `this` in-place\n BN.prototype.isqr = function isqr () {\n return this.imul(this.clone());\n };\n\n // Math.pow(`this`, `num`)\n BN.prototype.pow = function pow (num) {\n var w = toBitArray(num);\n if (w.length === 0) return new BN(1);\n\n // Skip leading zeroes\n var res = this;\n for (var i = 0; i < w.length; i++, res = res.sqr()) {\n if (w[i] !== 0) break;\n }\n\n if (++i < w.length) {\n for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {\n if (w[i] === 0) continue;\n\n res = res.mul(q);\n }\n }\n\n return res;\n };\n\n // Shift-left in-place\n BN.prototype.iushln = function iushln (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);\n var i;\n\n if (r !== 0) {\n var carry = 0;\n\n for (i = 0; i < this.length; i++) {\n var newCarry = this.words[i] & carryMask;\n var c = ((this.words[i] | 0) - newCarry) << r;\n this.words[i] = c | carry;\n carry = newCarry >>> (26 - r);\n }\n\n if (carry) {\n this.words[i] = carry;\n this.length++;\n }\n }\n\n if (s !== 0) {\n for (i = this.length - 1; i >= 0; i--) {\n this.words[i + s] = this.words[i];\n }\n\n for (i = 0; i < s; i++) {\n this.words[i] = 0;\n }\n\n this.length += s;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishln = function ishln (bits) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushln(bits);\n };\n\n // Shift-right in-place\n // NOTE: `hint` is a lowest bit before trailing zeroes\n // NOTE: if `extended` is present - it will be filled with destroyed bits\n BN.prototype.iushrn = function iushrn (bits, hint, extended) {\n assert(typeof bits === 'number' && bits >= 0);\n var h;\n if (hint) {\n h = (hint - (hint % 26)) / 26;\n } else {\n h = 0;\n }\n\n var r = bits % 26;\n var s = Math.min((bits - r) / 26, this.length);\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n var maskedWords = extended;\n\n h -= s;\n h = Math.max(0, h);\n\n // Extended mode, copy masked part\n if (maskedWords) {\n for (var i = 0; i < s; i++) {\n maskedWords.words[i] = this.words[i];\n }\n maskedWords.length = s;\n }\n\n if (s === 0) {\n // No-op, we should not move anything at all\n } else if (this.length > s) {\n this.length -= s;\n for (i = 0; i < this.length; i++) {\n this.words[i] = this.words[i + s];\n }\n } else {\n this.words[0] = 0;\n this.length = 1;\n }\n\n var carry = 0;\n for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {\n var word = this.words[i] | 0;\n this.words[i] = (carry << (26 - r)) | (word >>> r);\n carry = word & mask;\n }\n\n // Push carried bits as a mask\n if (maskedWords && carry !== 0) {\n maskedWords.words[maskedWords.length++] = carry;\n }\n\n if (this.length === 0) {\n this.words[0] = 0;\n this.length = 1;\n }\n\n return this.strip();\n };\n\n BN.prototype.ishrn = function ishrn (bits, hint, extended) {\n // TODO(indutny): implement me\n assert(this.negative === 0);\n return this.iushrn(bits, hint, extended);\n };\n\n // Shift-left\n BN.prototype.shln = function shln (bits) {\n return this.clone().ishln(bits);\n };\n\n BN.prototype.ushln = function ushln (bits) {\n return this.clone().iushln(bits);\n };\n\n // Shift-right\n BN.prototype.shrn = function shrn (bits) {\n return this.clone().ishrn(bits);\n };\n\n BN.prototype.ushrn = function ushrn (bits) {\n return this.clone().iushrn(bits);\n };\n\n // Test if n bit is set\n BN.prototype.testn = function testn (bit) {\n assert(typeof bit === 'number' && bit >= 0);\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) return false;\n\n // Check bit and return\n var w = this.words[s];\n\n return !!(w & q);\n };\n\n // Return only lowers bits of number (in-place)\n BN.prototype.imaskn = function imaskn (bits) {\n assert(typeof bits === 'number' && bits >= 0);\n var r = bits % 26;\n var s = (bits - r) / 26;\n\n assert(this.negative === 0, 'imaskn works only with positive numbers');\n\n if (this.length <= s) {\n return this;\n }\n\n if (r !== 0) {\n s++;\n }\n this.length = Math.min(s, this.length);\n\n if (r !== 0) {\n var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);\n this.words[this.length - 1] &= mask;\n }\n\n return this.strip();\n };\n\n // Return only lowers bits of number\n BN.prototype.maskn = function maskn (bits) {\n return this.clone().imaskn(bits);\n };\n\n // Add plain number `num` to `this`\n BN.prototype.iaddn = function iaddn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.isubn(-num);\n\n // Possible sign change\n if (this.negative !== 0) {\n if (this.length === 1 && (this.words[0] | 0) < num) {\n this.words[0] = num - (this.words[0] | 0);\n this.negative = 0;\n return this;\n }\n\n this.negative = 0;\n this.isubn(num);\n this.negative = 1;\n return this;\n }\n\n // Add without checks\n return this._iaddn(num);\n };\n\n BN.prototype._iaddn = function _iaddn (num) {\n this.words[0] += num;\n\n // Carry\n for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {\n this.words[i] -= 0x4000000;\n if (i === this.length - 1) {\n this.words[i + 1] = 1;\n } else {\n this.words[i + 1]++;\n }\n }\n this.length = Math.max(this.length, i + 1);\n\n return this;\n };\n\n // Subtract plain number `num` from `this`\n BN.prototype.isubn = function isubn (num) {\n assert(typeof num === 'number');\n assert(num < 0x4000000);\n if (num < 0) return this.iaddn(-num);\n\n if (this.negative !== 0) {\n this.negative = 0;\n this.iaddn(num);\n this.negative = 1;\n return this;\n }\n\n this.words[0] -= num;\n\n if (this.length === 1 && this.words[0] < 0) {\n this.words[0] = -this.words[0];\n this.negative = 1;\n } else {\n // Carry\n for (var i = 0; i < this.length && this.words[i] < 0; i++) {\n this.words[i] += 0x4000000;\n this.words[i + 1] -= 1;\n }\n }\n\n return this.strip();\n };\n\n BN.prototype.addn = function addn (num) {\n return this.clone().iaddn(num);\n };\n\n BN.prototype.subn = function subn (num) {\n return this.clone().isubn(num);\n };\n\n BN.prototype.iabs = function iabs () {\n this.negative = 0;\n\n return this;\n };\n\n BN.prototype.abs = function abs () {\n return this.clone().iabs();\n };\n\n BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {\n var len = num.length + shift;\n var i;\n\n this._expand(len);\n\n var w;\n var carry = 0;\n for (i = 0; i < num.length; i++) {\n w = (this.words[i + shift] | 0) + carry;\n var right = (num.words[i] | 0) * mul;\n w -= right & 0x3ffffff;\n carry = (w >> 26) - ((right / 0x4000000) | 0);\n this.words[i + shift] = w & 0x3ffffff;\n }\n for (; i < this.length - shift; i++) {\n w = (this.words[i + shift] | 0) + carry;\n carry = w >> 26;\n this.words[i + shift] = w & 0x3ffffff;\n }\n\n if (carry === 0) return this.strip();\n\n // Subtraction overflow\n assert(carry === -1);\n carry = 0;\n for (i = 0; i < this.length; i++) {\n w = -(this.words[i] | 0) + carry;\n carry = w >> 26;\n this.words[i] = w & 0x3ffffff;\n }\n this.negative = 1;\n\n return this.strip();\n };\n\n BN.prototype._wordDiv = function _wordDiv (num, mode) {\n var shift = this.length - num.length;\n\n var a = this.clone();\n var b = num;\n\n // Normalize\n var bhi = b.words[b.length - 1] | 0;\n var bhiBits = this._countBits(bhi);\n shift = 26 - bhiBits;\n if (shift !== 0) {\n b = b.ushln(shift);\n a.iushln(shift);\n bhi = b.words[b.length - 1] | 0;\n }\n\n // Initialize quotient\n var m = a.length - b.length;\n var q;\n\n if (mode !== 'mod') {\n q = new BN(null);\n q.length = m + 1;\n q.words = new Array(q.length);\n for (var i = 0; i < q.length; i++) {\n q.words[i] = 0;\n }\n }\n\n var diff = a.clone()._ishlnsubmul(b, 1, m);\n if (diff.negative === 0) {\n a = diff;\n if (q) {\n q.words[m] = 1;\n }\n }\n\n for (var j = m - 1; j >= 0; j--) {\n var qj = (a.words[b.length + j] | 0) * 0x4000000 +\n (a.words[b.length + j - 1] | 0);\n\n // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max\n // (0x7ffffff)\n qj = Math.min((qj / bhi) | 0, 0x3ffffff);\n\n a._ishlnsubmul(b, qj, j);\n while (a.negative !== 0) {\n qj--;\n a.negative = 0;\n a._ishlnsubmul(b, 1, j);\n if (!a.isZero()) {\n a.negative ^= 1;\n }\n }\n if (q) {\n q.words[j] = qj;\n }\n }\n if (q) {\n q.strip();\n }\n a.strip();\n\n // Denormalize\n if (mode !== 'div' && shift !== 0) {\n a.iushrn(shift);\n }\n\n return {\n div: q || null,\n mod: a\n };\n };\n\n // NOTE: 1) `mode` can be set to `mod` to request mod only,\n // to `div` to request div only, or be absent to\n // request both div & mod\n // 2) `positive` is true if unsigned mod is requested\n BN.prototype.divmod = function divmod (num, mode, positive) {\n assert(!num.isZero());\n\n if (this.isZero()) {\n return {\n div: new BN(0),\n mod: new BN(0)\n };\n }\n\n var div, mod, res;\n if (this.negative !== 0 && num.negative === 0) {\n res = this.neg().divmod(num, mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.iadd(num);\n }\n }\n\n return {\n div: div,\n mod: mod\n };\n }\n\n if (this.negative === 0 && num.negative !== 0) {\n res = this.divmod(num.neg(), mode);\n\n if (mode !== 'mod') {\n div = res.div.neg();\n }\n\n return {\n div: div,\n mod: res.mod\n };\n }\n\n if ((this.negative & num.negative) !== 0) {\n res = this.neg().divmod(num.neg(), mode);\n\n if (mode !== 'div') {\n mod = res.mod.neg();\n if (positive && mod.negative !== 0) {\n mod.isub(num);\n }\n }\n\n return {\n div: res.div,\n mod: mod\n };\n }\n\n // Both numbers are positive at this point\n\n // Strip both numbers to approximate shift value\n if (num.length > this.length || this.cmp(num) < 0) {\n return {\n div: new BN(0),\n mod: this\n };\n }\n\n // Very short reduction\n if (num.length === 1) {\n if (mode === 'div') {\n return {\n div: this.divn(num.words[0]),\n mod: null\n };\n }\n\n if (mode === 'mod') {\n return {\n div: null,\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return {\n div: this.divn(num.words[0]),\n mod: new BN(this.modn(num.words[0]))\n };\n }\n\n return this._wordDiv(num, mode);\n };\n\n // Find `this` / `num`\n BN.prototype.div = function div (num) {\n return this.divmod(num, 'div', false).div;\n };\n\n // Find `this` % `num`\n BN.prototype.mod = function mod (num) {\n return this.divmod(num, 'mod', false).mod;\n };\n\n BN.prototype.umod = function umod (num) {\n return this.divmod(num, 'mod', true).mod;\n };\n\n // Find Round(`this` / `num`)\n BN.prototype.divRound = function divRound (num) {\n var dm = this.divmod(num);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;\n\n var half = num.ushrn(1);\n var r2 = num.andln(1);\n var cmp = mod.cmp(half);\n\n // Round down\n if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;\n\n // Round up\n return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);\n };\n\n BN.prototype.modn = function modn (num) {\n assert(num <= 0x3ffffff);\n var p = (1 << 26) % num;\n\n var acc = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n acc = (p * acc + (this.words[i] | 0)) % num;\n }\n\n return acc;\n };\n\n // In-place division by number\n BN.prototype.idivn = function idivn (num) {\n assert(num <= 0x3ffffff);\n\n var carry = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var w = (this.words[i] | 0) + carry * 0x4000000;\n this.words[i] = (w / num) | 0;\n carry = w % num;\n }\n\n return this.strip();\n };\n\n BN.prototype.divn = function divn (num) {\n return this.clone().idivn(num);\n };\n\n BN.prototype.egcd = function egcd (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var x = this;\n var y = p.clone();\n\n if (x.negative !== 0) {\n x = x.umod(p);\n } else {\n x = x.clone();\n }\n\n // A * x + B * y = x\n var A = new BN(1);\n var B = new BN(0);\n\n // C * x + D * y = y\n var C = new BN(0);\n var D = new BN(1);\n\n var g = 0;\n\n while (x.isEven() && y.isEven()) {\n x.iushrn(1);\n y.iushrn(1);\n ++g;\n }\n\n var yp = y.clone();\n var xp = x.clone();\n\n while (!x.isZero()) {\n for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n x.iushrn(i);\n while (i-- > 0) {\n if (A.isOdd() || B.isOdd()) {\n A.iadd(yp);\n B.isub(xp);\n }\n\n A.iushrn(1);\n B.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n y.iushrn(j);\n while (j-- > 0) {\n if (C.isOdd() || D.isOdd()) {\n C.iadd(yp);\n D.isub(xp);\n }\n\n C.iushrn(1);\n D.iushrn(1);\n }\n }\n\n if (x.cmp(y) >= 0) {\n x.isub(y);\n A.isub(C);\n B.isub(D);\n } else {\n y.isub(x);\n C.isub(A);\n D.isub(B);\n }\n }\n\n return {\n a: C,\n b: D,\n gcd: y.iushln(g)\n };\n };\n\n // This is reduced incarnation of the binary EEA\n // above, designated to invert members of the\n // _prime_ fields F(p) at a maximal speed\n BN.prototype._invmp = function _invmp (p) {\n assert(p.negative === 0);\n assert(!p.isZero());\n\n var a = this;\n var b = p.clone();\n\n if (a.negative !== 0) {\n a = a.umod(p);\n } else {\n a = a.clone();\n }\n\n var x1 = new BN(1);\n var x2 = new BN(0);\n\n var delta = b.clone();\n\n while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {\n for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);\n if (i > 0) {\n a.iushrn(i);\n while (i-- > 0) {\n if (x1.isOdd()) {\n x1.iadd(delta);\n }\n\n x1.iushrn(1);\n }\n }\n\n for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);\n if (j > 0) {\n b.iushrn(j);\n while (j-- > 0) {\n if (x2.isOdd()) {\n x2.iadd(delta);\n }\n\n x2.iushrn(1);\n }\n }\n\n if (a.cmp(b) >= 0) {\n a.isub(b);\n x1.isub(x2);\n } else {\n b.isub(a);\n x2.isub(x1);\n }\n }\n\n var res;\n if (a.cmpn(1) === 0) {\n res = x1;\n } else {\n res = x2;\n }\n\n if (res.cmpn(0) < 0) {\n res.iadd(p);\n }\n\n return res;\n };\n\n BN.prototype.gcd = function gcd (num) {\n if (this.isZero()) return num.abs();\n if (num.isZero()) return this.abs();\n\n var a = this.clone();\n var b = num.clone();\n a.negative = 0;\n b.negative = 0;\n\n // Remove common factor of two\n for (var shift = 0; a.isEven() && b.isEven(); shift++) {\n a.iushrn(1);\n b.iushrn(1);\n }\n\n do {\n while (a.isEven()) {\n a.iushrn(1);\n }\n while (b.isEven()) {\n b.iushrn(1);\n }\n\n var r = a.cmp(b);\n if (r < 0) {\n // Swap `a` and `b` to make `a` always bigger than `b`\n var t = a;\n a = b;\n b = t;\n } else if (r === 0 || b.cmpn(1) === 0) {\n break;\n }\n\n a.isub(b);\n } while (true);\n\n return b.iushln(shift);\n };\n\n // Invert number in the field F(num)\n BN.prototype.invm = function invm (num) {\n return this.egcd(num).a.umod(num);\n };\n\n BN.prototype.isEven = function isEven () {\n return (this.words[0] & 1) === 0;\n };\n\n BN.prototype.isOdd = function isOdd () {\n return (this.words[0] & 1) === 1;\n };\n\n // And first word and num\n BN.prototype.andln = function andln (num) {\n return this.words[0] & num;\n };\n\n // Increment at the bit position in-line\n BN.prototype.bincn = function bincn (bit) {\n assert(typeof bit === 'number');\n var r = bit % 26;\n var s = (bit - r) / 26;\n var q = 1 << r;\n\n // Fast case: bit is much higher than all existing words\n if (this.length <= s) {\n this._expand(s + 1);\n this.words[s] |= q;\n return this;\n }\n\n // Add bit and propagate, if needed\n var carry = q;\n for (var i = s; carry !== 0 && i < this.length; i++) {\n var w = this.words[i] | 0;\n w += carry;\n carry = w >>> 26;\n w &= 0x3ffffff;\n this.words[i] = w;\n }\n if (carry !== 0) {\n this.words[i] = carry;\n this.length++;\n }\n return this;\n };\n\n BN.prototype.isZero = function isZero () {\n return this.length === 1 && this.words[0] === 0;\n };\n\n BN.prototype.cmpn = function cmpn (num) {\n var negative = num < 0;\n\n if (this.negative !== 0 && !negative) return -1;\n if (this.negative === 0 && negative) return 1;\n\n this.strip();\n\n var res;\n if (this.length > 1) {\n res = 1;\n } else {\n if (negative) {\n num = -num;\n }\n\n assert(num <= 0x3ffffff, 'Number is too big');\n\n var w = this.words[0] | 0;\n res = w === num ? 0 : w < num ? -1 : 1;\n }\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Compare two numbers and return:\n // 1 - if `this` > `num`\n // 0 - if `this` == `num`\n // -1 - if `this` < `num`\n BN.prototype.cmp = function cmp (num) {\n if (this.negative !== 0 && num.negative === 0) return -1;\n if (this.negative === 0 && num.negative !== 0) return 1;\n\n var res = this.ucmp(num);\n if (this.negative !== 0) return -res | 0;\n return res;\n };\n\n // Unsigned comparison\n BN.prototype.ucmp = function ucmp (num) {\n // At this point both numbers have the same sign\n if (this.length > num.length) return 1;\n if (this.length < num.length) return -1;\n\n var res = 0;\n for (var i = this.length - 1; i >= 0; i--) {\n var a = this.words[i] | 0;\n var b = num.words[i] | 0;\n\n if (a === b) continue;\n if (a < b) {\n res = -1;\n } else if (a > b) {\n res = 1;\n }\n break;\n }\n return res;\n };\n\n BN.prototype.gtn = function gtn (num) {\n return this.cmpn(num) === 1;\n };\n\n BN.prototype.gt = function gt (num) {\n return this.cmp(num) === 1;\n };\n\n BN.prototype.gten = function gten (num) {\n return this.cmpn(num) >= 0;\n };\n\n BN.prototype.gte = function gte (num) {\n return this.cmp(num) >= 0;\n };\n\n BN.prototype.ltn = function ltn (num) {\n return this.cmpn(num) === -1;\n };\n\n BN.prototype.lt = function lt (num) {\n return this.cmp(num) === -1;\n };\n\n BN.prototype.lten = function lten (num) {\n return this.cmpn(num) <= 0;\n };\n\n BN.prototype.lte = function lte (num) {\n return this.cmp(num) <= 0;\n };\n\n BN.prototype.eqn = function eqn (num) {\n return this.cmpn(num) === 0;\n };\n\n BN.prototype.eq = function eq (num) {\n return this.cmp(num) === 0;\n };\n\n //\n // A reduce context, could be using montgomery or something better, depending\n // on the `m` itself.\n //\n BN.red = function red (num) {\n return new Red(num);\n };\n\n BN.prototype.toRed = function toRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n assert(this.negative === 0, 'red works only with positives');\n return ctx.convertTo(this)._forceRed(ctx);\n };\n\n BN.prototype.fromRed = function fromRed () {\n assert(this.red, 'fromRed works only with numbers in reduction context');\n return this.red.convertFrom(this);\n };\n\n BN.prototype._forceRed = function _forceRed (ctx) {\n this.red = ctx;\n return this;\n };\n\n BN.prototype.forceRed = function forceRed (ctx) {\n assert(!this.red, 'Already a number in reduction context');\n return this._forceRed(ctx);\n };\n\n BN.prototype.redAdd = function redAdd (num) {\n assert(this.red, 'redAdd works only with red numbers');\n return this.red.add(this, num);\n };\n\n BN.prototype.redIAdd = function redIAdd (num) {\n assert(this.red, 'redIAdd works only with red numbers');\n return this.red.iadd(this, num);\n };\n\n BN.prototype.redSub = function redSub (num) {\n assert(this.red, 'redSub works only with red numbers');\n return this.red.sub(this, num);\n };\n\n BN.prototype.redISub = function redISub (num) {\n assert(this.red, 'redISub works only with red numbers');\n return this.red.isub(this, num);\n };\n\n BN.prototype.redShl = function redShl (num) {\n assert(this.red, 'redShl works only with red numbers');\n return this.red.shl(this, num);\n };\n\n BN.prototype.redMul = function redMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.mul(this, num);\n };\n\n BN.prototype.redIMul = function redIMul (num) {\n assert(this.red, 'redMul works only with red numbers');\n this.red._verify2(this, num);\n return this.red.imul(this, num);\n };\n\n BN.prototype.redSqr = function redSqr () {\n assert(this.red, 'redSqr works only with red numbers');\n this.red._verify1(this);\n return this.red.sqr(this);\n };\n\n BN.prototype.redISqr = function redISqr () {\n assert(this.red, 'redISqr works only with red numbers');\n this.red._verify1(this);\n return this.red.isqr(this);\n };\n\n // Square root over p\n BN.prototype.redSqrt = function redSqrt () {\n assert(this.red, 'redSqrt works only with red numbers');\n this.red._verify1(this);\n return this.red.sqrt(this);\n };\n\n BN.prototype.redInvm = function redInvm () {\n assert(this.red, 'redInvm works only with red numbers');\n this.red._verify1(this);\n return this.red.invm(this);\n };\n\n // Return negative clone of `this` % `red modulo`\n BN.prototype.redNeg = function redNeg () {\n assert(this.red, 'redNeg works only with red numbers');\n this.red._verify1(this);\n return this.red.neg(this);\n };\n\n BN.prototype.redPow = function redPow (num) {\n assert(this.red && !num.red, 'redPow(normalNum)');\n this.red._verify1(this);\n return this.red.pow(this, num);\n };\n\n // Prime numbers with efficient reduction\n var primes = {\n k256: null,\n p224: null,\n p192: null,\n p25519: null\n };\n\n // Pseudo-Mersenne prime\n function MPrime (name, p) {\n // P = 2 ^ N - K\n this.name = name;\n this.p = new BN(p, 16);\n this.n = this.p.bitLength();\n this.k = new BN(1).iushln(this.n).isub(this.p);\n\n this.tmp = this._tmp();\n }\n\n MPrime.prototype._tmp = function _tmp () {\n var tmp = new BN(null);\n tmp.words = new Array(Math.ceil(this.n / 13));\n return tmp;\n };\n\n MPrime.prototype.ireduce = function ireduce (num) {\n // Assumes that `num` is less than `P^2`\n // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)\n var r = num;\n var rlen;\n\n do {\n this.split(r, this.tmp);\n r = this.imulK(r);\n r = r.iadd(this.tmp);\n rlen = r.bitLength();\n } while (rlen > this.n);\n\n var cmp = rlen < this.n ? -1 : r.ucmp(this.p);\n if (cmp === 0) {\n r.words[0] = 0;\n r.length = 1;\n } else if (cmp > 0) {\n r.isub(this.p);\n } else {\n if (r.strip !== undefined) {\n // r is BN v4 instance\n r.strip();\n } else {\n // r is BN v5 instance\n r._strip();\n }\n }\n\n return r;\n };\n\n MPrime.prototype.split = function split (input, out) {\n input.iushrn(this.n, 0, out);\n };\n\n MPrime.prototype.imulK = function imulK (num) {\n return num.imul(this.k);\n };\n\n function K256 () {\n MPrime.call(\n this,\n 'k256',\n 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');\n }\n inherits(K256, MPrime);\n\n K256.prototype.split = function split (input, output) {\n // 256 = 9 * 26 + 22\n var mask = 0x3fffff;\n\n var outLen = Math.min(input.length, 9);\n for (var i = 0; i < outLen; i++) {\n output.words[i] = input.words[i];\n }\n output.length = outLen;\n\n if (input.length <= 9) {\n input.words[0] = 0;\n input.length = 1;\n return;\n }\n\n // Shift by 9 limbs\n var prev = input.words[9];\n output.words[output.length++] = prev & mask;\n\n for (i = 10; i < input.length; i++) {\n var next = input.words[i] | 0;\n input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);\n prev = next;\n }\n prev >>>= 22;\n input.words[i - 10] = prev;\n if (prev === 0 && input.length > 10) {\n input.length -= 10;\n } else {\n input.length -= 9;\n }\n };\n\n K256.prototype.imulK = function imulK (num) {\n // K = 0x1000003d1 = [ 0x40, 0x3d1 ]\n num.words[num.length] = 0;\n num.words[num.length + 1] = 0;\n num.length += 2;\n\n // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390\n var lo = 0;\n for (var i = 0; i < num.length; i++) {\n var w = num.words[i] | 0;\n lo += w * 0x3d1;\n num.words[i] = lo & 0x3ffffff;\n lo = w * 0x40 + ((lo / 0x4000000) | 0);\n }\n\n // Fast length reduction\n if (num.words[num.length - 1] === 0) {\n num.length--;\n if (num.words[num.length - 1] === 0) {\n num.length--;\n }\n }\n return num;\n };\n\n function P224 () {\n MPrime.call(\n this,\n 'p224',\n 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');\n }\n inherits(P224, MPrime);\n\n function P192 () {\n MPrime.call(\n this,\n 'p192',\n 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');\n }\n inherits(P192, MPrime);\n\n function P25519 () {\n // 2 ^ 255 - 19\n MPrime.call(\n this,\n '25519',\n '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');\n }\n inherits(P25519, MPrime);\n\n P25519.prototype.imulK = function imulK (num) {\n // K = 0x13\n var carry = 0;\n for (var i = 0; i < num.length; i++) {\n var hi = (num.words[i] | 0) * 0x13 + carry;\n var lo = hi & 0x3ffffff;\n hi >>>= 26;\n\n num.words[i] = lo;\n carry = hi;\n }\n if (carry !== 0) {\n num.words[num.length++] = carry;\n }\n return num;\n };\n\n // Exported mostly for testing purposes, use plain name instead\n BN._prime = function prime (name) {\n // Cached version of prime\n if (primes[name]) return primes[name];\n\n var prime;\n if (name === 'k256') {\n prime = new K256();\n } else if (name === 'p224') {\n prime = new P224();\n } else if (name === 'p192') {\n prime = new P192();\n } else if (name === 'p25519') {\n prime = new P25519();\n } else {\n throw new Error('Unknown prime ' + name);\n }\n primes[name] = prime;\n\n return prime;\n };\n\n //\n // Base reduction engine\n //\n function Red (m) {\n if (typeof m === 'string') {\n var prime = BN._prime(m);\n this.m = prime.p;\n this.prime = prime;\n } else {\n assert(m.gtn(1), 'modulus must be greater than 1');\n this.m = m;\n this.prime = null;\n }\n }\n\n Red.prototype._verify1 = function _verify1 (a) {\n assert(a.negative === 0, 'red works only with positives');\n assert(a.red, 'red works only with red numbers');\n };\n\n Red.prototype._verify2 = function _verify2 (a, b) {\n assert((a.negative | b.negative) === 0, 'red works only with positives');\n assert(a.red && a.red === b.red,\n 'red works only with red numbers');\n };\n\n Red.prototype.imod = function imod (a) {\n if (this.prime) return this.prime.ireduce(a)._forceRed(this);\n return a.umod(this.m)._forceRed(this);\n };\n\n Red.prototype.neg = function neg (a) {\n if (a.isZero()) {\n return a.clone();\n }\n\n return this.m.sub(a)._forceRed(this);\n };\n\n Red.prototype.add = function add (a, b) {\n this._verify2(a, b);\n\n var res = a.add(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.iadd = function iadd (a, b) {\n this._verify2(a, b);\n\n var res = a.iadd(b);\n if (res.cmp(this.m) >= 0) {\n res.isub(this.m);\n }\n return res;\n };\n\n Red.prototype.sub = function sub (a, b) {\n this._verify2(a, b);\n\n var res = a.sub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res._forceRed(this);\n };\n\n Red.prototype.isub = function isub (a, b) {\n this._verify2(a, b);\n\n var res = a.isub(b);\n if (res.cmpn(0) < 0) {\n res.iadd(this.m);\n }\n return res;\n };\n\n Red.prototype.shl = function shl (a, num) {\n this._verify1(a);\n return this.imod(a.ushln(num));\n };\n\n Red.prototype.imul = function imul (a, b) {\n this._verify2(a, b);\n return this.imod(a.imul(b));\n };\n\n Red.prototype.mul = function mul (a, b) {\n this._verify2(a, b);\n return this.imod(a.mul(b));\n };\n\n Red.prototype.isqr = function isqr (a) {\n return this.imul(a, a.clone());\n };\n\n Red.prototype.sqr = function sqr (a) {\n return this.mul(a, a);\n };\n\n Red.prototype.sqrt = function sqrt (a) {\n if (a.isZero()) return a.clone();\n\n var mod3 = this.m.andln(3);\n assert(mod3 % 2 === 1);\n\n // Fast case\n if (mod3 === 3) {\n var pow = this.m.add(new BN(1)).iushrn(2);\n return this.pow(a, pow);\n }\n\n // Tonelli-Shanks algorithm (Totally unoptimized and slow)\n //\n // Find Q and S, that Q * 2 ^ S = (P - 1)\n var q = this.m.subn(1);\n var s = 0;\n while (!q.isZero() && q.andln(1) === 0) {\n s++;\n q.iushrn(1);\n }\n assert(!q.isZero());\n\n var one = new BN(1).toRed(this);\n var nOne = one.redNeg();\n\n // Find quadratic non-residue\n // NOTE: Max is such because of generalized Riemann hypothesis.\n var lpow = this.m.subn(1).iushrn(1);\n var z = this.m.bitLength();\n z = new BN(2 * z * z).toRed(this);\n\n while (this.pow(z, lpow).cmp(nOne) !== 0) {\n z.redIAdd(nOne);\n }\n\n var c = this.pow(z, q);\n var r = this.pow(a, q.addn(1).iushrn(1));\n var t = this.pow(a, q);\n var m = s;\n while (t.cmp(one) !== 0) {\n var tmp = t;\n for (var i = 0; tmp.cmp(one) !== 0; i++) {\n tmp = tmp.redSqr();\n }\n assert(i < m);\n var b = this.pow(c, new BN(1).iushln(m - i - 1));\n\n r = r.redMul(b);\n c = b.redSqr();\n t = t.redMul(c);\n m = i;\n }\n\n return r;\n };\n\n Red.prototype.invm = function invm (a) {\n var inv = a._invmp(this.m);\n if (inv.negative !== 0) {\n inv.negative = 0;\n return this.imod(inv).redNeg();\n } else {\n return this.imod(inv);\n }\n };\n\n Red.prototype.pow = function pow (a, num) {\n if (num.isZero()) return new BN(1).toRed(this);\n if (num.cmpn(1) === 0) return a.clone();\n\n var windowSize = 4;\n var wnd = new Array(1 << windowSize);\n wnd[0] = new BN(1).toRed(this);\n wnd[1] = a;\n for (var i = 2; i < wnd.length; i++) {\n wnd[i] = this.mul(wnd[i - 1], a);\n }\n\n var res = wnd[0];\n var current = 0;\n var currentLen = 0;\n var start = num.bitLength() % 26;\n if (start === 0) {\n start = 26;\n }\n\n for (i = num.length - 1; i >= 0; i--) {\n var word = num.words[i];\n for (var j = start - 1; j >= 0; j--) {\n var bit = (word >> j) & 1;\n if (res !== wnd[0]) {\n res = this.sqr(res);\n }\n\n if (bit === 0 && current === 0) {\n currentLen = 0;\n continue;\n }\n\n current <<= 1;\n current |= bit;\n currentLen++;\n if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;\n\n res = this.mul(res, wnd[current]);\n currentLen = 0;\n current = 0;\n }\n start = 26;\n }\n\n return res;\n };\n\n Red.prototype.convertTo = function convertTo (num) {\n var r = num.umod(this.m);\n\n return r === num ? r.clone() : r;\n };\n\n Red.prototype.convertFrom = function convertFrom (num) {\n var res = num.clone();\n res.red = null;\n return res;\n };\n\n //\n // Montgomery method engine\n //\n\n BN.mont = function mont (num) {\n return new Mont(num);\n };\n\n function Mont (m) {\n Red.call(this, m);\n\n this.shift = this.m.bitLength();\n if (this.shift % 26 !== 0) {\n this.shift += 26 - (this.shift % 26);\n }\n\n this.r = new BN(1).iushln(this.shift);\n this.r2 = this.imod(this.r.sqr());\n this.rinv = this.r._invmp(this.m);\n\n this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);\n this.minv = this.minv.umod(this.r);\n this.minv = this.r.sub(this.minv);\n }\n inherits(Mont, Red);\n\n Mont.prototype.convertTo = function convertTo (num) {\n return this.imod(num.ushln(this.shift));\n };\n\n Mont.prototype.convertFrom = function convertFrom (num) {\n var r = this.imod(num.mul(this.rinv));\n r.red = null;\n return r;\n };\n\n Mont.prototype.imul = function imul (a, b) {\n if (a.isZero() || b.isZero()) {\n a.words[0] = 0;\n a.length = 1;\n return a;\n }\n\n var t = a.imul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.mul = function mul (a, b) {\n if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);\n\n var t = a.mul(b);\n var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);\n var u = t.isub(c).iushrn(this.shift);\n var res = u;\n if (u.cmp(this.m) >= 0) {\n res = u.isub(this.m);\n } else if (u.cmpn(0) < 0) {\n res = u.iadd(this.m);\n }\n\n return res._forceRed(this);\n };\n\n Mont.prototype.invm = function invm (a) {\n // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R\n var res = this.imod(a._invmp(this.m).mul(this.r2));\n return res._forceRed(this);\n };\n})(typeof module === 'undefined' || module, this);\n", - "var randomBytes = require('randombytes');\nmodule.exports = findPrime;\nfindPrime.simpleSieve = simpleSieve;\nfindPrime.fermatTest = fermatTest;\nvar BN = require('bn.js');\nvar TWENTYFOUR = new BN(24);\nvar MillerRabin = require('miller-rabin');\nvar millerRabin = new MillerRabin();\nvar ONE = new BN(1);\nvar TWO = new BN(2);\nvar FIVE = new BN(5);\nvar SIXTEEN = new BN(16);\nvar EIGHT = new BN(8);\nvar TEN = new BN(10);\nvar THREE = new BN(3);\nvar SEVEN = new BN(7);\nvar ELEVEN = new BN(11);\nvar FOUR = new BN(4);\nvar TWELVE = new BN(12);\nvar primes = null;\n\nfunction _getPrimes() {\n if (primes !== null)\n return primes;\n\n var limit = 0x100000;\n var res = [];\n res[0] = 2;\n for (var i = 1, k = 3; k < limit; k += 2) {\n var sqrt = Math.ceil(Math.sqrt(k));\n for (var j = 0; j < i && res[j] <= sqrt; j++)\n if (k % res[j] === 0)\n break;\n\n if (i !== j && res[j] <= sqrt)\n continue;\n\n res[i++] = k;\n }\n primes = res;\n return res;\n}\n\nfunction simpleSieve(p) {\n var primes = _getPrimes();\n\n for (var i = 0; i < primes.length; i++)\n if (p.modn(primes[i]) === 0) {\n if (p.cmpn(primes[i]) === 0) {\n return true;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\nfunction fermatTest(p) {\n var red = BN.mont(p);\n return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0;\n}\n\nfunction findPrime(bits, gen) {\n if (bits < 16) {\n // this is what openssl does\n if (gen === 2 || gen === 5) {\n return new BN([0x8c, 0x7b]);\n } else {\n return new BN([0x8c, 0x27]);\n }\n }\n gen = new BN(gen);\n\n var num, n2;\n\n while (true) {\n num = new BN(randomBytes(Math.ceil(bits / 8)));\n while (num.bitLength() > bits) {\n num.ishrn(1);\n }\n if (num.isEven()) {\n num.iadd(ONE);\n }\n if (!num.testn(1)) {\n num.iadd(TWO);\n }\n if (!gen.cmp(TWO)) {\n while (num.mod(TWENTYFOUR).cmp(ELEVEN)) {\n num.iadd(FOUR);\n }\n } else if (!gen.cmp(FIVE)) {\n while (num.mod(TEN).cmp(THREE)) {\n num.iadd(FOUR);\n }\n }\n n2 = num.shrn(1);\n if (simpleSieve(n2) && simpleSieve(num) &&\n fermatTest(n2) && fermatTest(num) &&\n millerRabin.test(n2) && millerRabin.test(num)) {\n return num;\n }\n }\n\n}\n", - "'use strict'\n\n// limit of Crypto.getRandomValues()\n// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues\nvar MAX_BYTES = 65536\n\n// Node supports requesting up to this number of bytes\n// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48\nvar MAX_UINT32 = 4294967295\n\nfunction oldBrowser () {\n throw new Error('Secure random number generation is not supported by this browser.\\nUse Chrome, Firefox or Internet Explorer 11')\n}\n\nvar Buffer = require('safe-buffer').Buffer\nvar crypto = global.crypto || global.msCrypto\n\nif (crypto && crypto.getRandomValues) {\n module.exports = randomBytes\n} else {\n module.exports = oldBrowser\n}\n\nfunction randomBytes (size, cb) {\n // phantomjs needs to throw\n if (size > MAX_UINT32) throw new RangeError('requested too many random bytes')\n\n var bytes = Buffer.allocUnsafe(size)\n\n if (size > 0) { // getRandomValues fails on IE if size == 0\n if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues\n // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues\n for (var generated = 0; generated < size; generated += MAX_BYTES) {\n // buffer.slice automatically checks if the end is past the end of\n // the buffer so we don't have to here\n crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES))\n }\n } else {\n crypto.getRandomValues(bytes)\n }\n }\n\n if (typeof cb === 'function') {\n return process.nextTick(function () {\n cb(null, bytes)\n })\n }\n\n return bytes\n}\n", - "// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n", - "var bn = require('bn.js');\nvar brorand = require('brorand');\n\nfunction MillerRabin(rand) {\n this.rand = rand || new brorand.Rand();\n}\nmodule.exports = MillerRabin;\n\nMillerRabin.create = function create(rand) {\n return new MillerRabin(rand);\n};\n\nMillerRabin.prototype._randbelow = function _randbelow(n) {\n var len = n.bitLength();\n var min_bytes = Math.ceil(len / 8);\n\n // Generage random bytes until a number less than n is found.\n // This ensures that 0..n-1 have an equal probability of being selected.\n do\n var a = new bn(this.rand.generate(min_bytes));\n while (a.cmp(n) >= 0);\n\n return a;\n};\n\nMillerRabin.prototype._randrange = function _randrange(start, stop) {\n // Generate a random number greater than or equal to start and less than stop.\n var size = stop.sub(start);\n return start.add(this._randbelow(size));\n};\n\nMillerRabin.prototype.test = function test(n, k, cb) {\n var len = n.bitLength();\n var red = bn.mont(n);\n var rone = new bn(1).toRed(red);\n\n if (!k)\n k = Math.max(1, (len / 48) | 0);\n\n // Find d and s, (n - 1) = (2 ^ s) * d;\n var n1 = n.subn(1);\n for (var s = 0; !n1.testn(s); s++) {}\n var d = n.shrn(s);\n\n var rn1 = n1.toRed(red);\n\n var prime = true;\n for (; k > 0; k--) {\n var a = this._randrange(new bn(2), n1);\n if (cb)\n cb(a);\n\n var x = a.toRed(red).redPow(d);\n if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)\n continue;\n\n for (var i = 1; i < s; i++) {\n x = x.redSqr();\n\n if (x.cmp(rone) === 0)\n return false;\n if (x.cmp(rn1) === 0)\n break;\n }\n\n if (i === s)\n return false;\n }\n\n return prime;\n};\n\nMillerRabin.prototype.getDivisor = function getDivisor(n, k) {\n var len = n.bitLength();\n var red = bn.mont(n);\n var rone = new bn(1).toRed(red);\n\n if (!k)\n k = Math.max(1, (len / 48) | 0);\n\n // Find d and s, (n - 1) = (2 ^ s) * d;\n var n1 = n.subn(1);\n for (var s = 0; !n1.testn(s); s++) {}\n var d = n.shrn(s);\n\n var rn1 = n1.toRed(red);\n\n for (; k > 0; k--) {\n var a = this._randrange(new bn(2), n1);\n\n var g = n.gcd(a);\n if (g.cmpn(1) !== 0)\n return g;\n\n var x = a.toRed(red).redPow(d);\n if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)\n continue;\n\n for (var i = 1; i < s; i++) {\n x = x.redSqr();\n\n if (x.cmp(rone) === 0)\n return x.fromRed().subn(1).gcd(n);\n if (x.cmp(rn1) === 0)\n break;\n }\n\n if (i === s) {\n x = x.redSqr();\n return x.fromRed().subn(1).gcd(n);\n }\n }\n\n return false;\n};\n", - "var generatePrime = require('./lib/generatePrime')\nvar primes = require('./lib/primes.json')\n\nvar DH = require('./lib/dh')\n\nfunction getDiffieHellman (mod) {\n var prime = new Buffer(primes[mod].prime, 'hex')\n var gen = new Buffer(primes[mod].gen, 'hex')\n\n return new DH(prime, gen)\n}\n\nvar ENCODINGS = {\n 'binary': true, 'hex': true, 'base64': true\n}\n\nfunction createDiffieHellman (prime, enc, generator, genc) {\n if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) {\n return createDiffieHellman(prime, 'binary', enc, generator)\n }\n\n enc = enc || 'binary'\n genc = genc || 'binary'\n generator = generator || new Buffer([2])\n\n if (!Buffer.isBuffer(generator)) {\n generator = new Buffer(generator, genc)\n }\n\n if (typeof prime === 'number') {\n return new DH(generatePrime(prime, generator), generator, true)\n }\n\n if (!Buffer.isBuffer(prime)) {\n prime = new Buffer(prime, enc)\n }\n\n return new DH(prime, generator, true)\n}\n\nexports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman\nexports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman\n", - "\"use strict\";\n\n(function(root) {\n const MAX_VALUE = 0x7fffffff;\n\n // The SHA256 and PBKDF2 implementation are from scrypt-async-js:\n // See: https://github.com/dchest/scrypt-async-js\n function SHA256(m) {\n const K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,\n 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,\n 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,\n 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,\n 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,\n 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,\n 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,\n 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,\n 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n ]);\n\n let h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a;\n let h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19;\n const w = new Uint32Array(64);\n\n function blocks(p) {\n let off = 0, len = p.length;\n while (len >= 64) {\n let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7, u, i, j, t1, t2;\n\n for (i = 0; i < 16; i++) {\n j = off + i*4;\n w[i] = ((p[j] & 0xff)<<24) | ((p[j+1] & 0xff)<<16) |\n ((p[j+2] & 0xff)<<8) | (p[j+3] & 0xff);\n }\n\n for (i = 16; i < 64; i++) {\n u = w[i-2];\n t1 = ((u>>>17) | (u<<(32-17))) ^ ((u>>>19) | (u<<(32-19))) ^ (u>>>10);\n\n u = w[i-15];\n t2 = ((u>>>7) | (u<<(32-7))) ^ ((u>>>18) | (u<<(32-18))) ^ (u>>>3);\n\n w[i] = (((t1 + w[i-7]) | 0) + ((t2 + w[i-16]) | 0)) | 0;\n }\n\n for (i = 0; i < 64; i++) {\n t1 = ((((((e>>>6) | (e<<(32-6))) ^ ((e>>>11) | (e<<(32-11))) ^\n ((e>>>25) | (e<<(32-25)))) + ((e & f) ^ (~e & g))) | 0) +\n ((h + ((K[i] + w[i]) | 0)) | 0)) | 0;\n\n t2 = ((((a>>>2) | (a<<(32-2))) ^ ((a>>>13) | (a<<(32-13))) ^\n ((a>>>22) | (a<<(32-22)))) + ((a & b) ^ (a & c) ^ (b & c))) | 0;\n\n h = g;\n g = f;\n f = e;\n e = (d + t1) | 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) | 0;\n }\n\n h0 = (h0 + a) | 0;\n h1 = (h1 + b) | 0;\n h2 = (h2 + c) | 0;\n h3 = (h3 + d) | 0;\n h4 = (h4 + e) | 0;\n h5 = (h5 + f) | 0;\n h6 = (h6 + g) | 0;\n h7 = (h7 + h) | 0;\n\n off += 64;\n len -= 64;\n }\n }\n\n blocks(m);\n\n let i, bytesLeft = m.length % 64,\n bitLenHi = (m.length / 0x20000000) | 0,\n bitLenLo = m.length << 3,\n numZeros = (bytesLeft < 56) ? 56 : 120,\n p = m.slice(m.length - bytesLeft, m.length);\n\n p.push(0x80);\n for (i = bytesLeft + 1; i < numZeros; i++) { p.push(0); }\n p.push((bitLenHi >>> 24) & 0xff);\n p.push((bitLenHi >>> 16) & 0xff);\n p.push((bitLenHi >>> 8) & 0xff);\n p.push((bitLenHi >>> 0) & 0xff);\n p.push((bitLenLo >>> 24) & 0xff);\n p.push((bitLenLo >>> 16) & 0xff);\n p.push((bitLenLo >>> 8) & 0xff);\n p.push((bitLenLo >>> 0) & 0xff);\n\n blocks(p);\n\n return [\n (h0 >>> 24) & 0xff, (h0 >>> 16) & 0xff, (h0 >>> 8) & 0xff, (h0 >>> 0) & 0xff,\n (h1 >>> 24) & 0xff, (h1 >>> 16) & 0xff, (h1 >>> 8) & 0xff, (h1 >>> 0) & 0xff,\n (h2 >>> 24) & 0xff, (h2 >>> 16) & 0xff, (h2 >>> 8) & 0xff, (h2 >>> 0) & 0xff,\n (h3 >>> 24) & 0xff, (h3 >>> 16) & 0xff, (h3 >>> 8) & 0xff, (h3 >>> 0) & 0xff,\n (h4 >>> 24) & 0xff, (h4 >>> 16) & 0xff, (h4 >>> 8) & 0xff, (h4 >>> 0) & 0xff,\n (h5 >>> 24) & 0xff, (h5 >>> 16) & 0xff, (h5 >>> 8) & 0xff, (h5 >>> 0) & 0xff,\n (h6 >>> 24) & 0xff, (h6 >>> 16) & 0xff, (h6 >>> 8) & 0xff, (h6 >>> 0) & 0xff,\n (h7 >>> 24) & 0xff, (h7 >>> 16) & 0xff, (h7 >>> 8) & 0xff, (h7 >>> 0) & 0xff\n ];\n }\n\n function PBKDF2_HMAC_SHA256_OneIter(password, salt, dkLen) {\n // compress password if it's longer than hash block length\n password = (password.length <= 64) ? password : SHA256(password);\n\n const innerLen = 64 + salt.length + 4;\n const inner = new Array(innerLen);\n const outerKey = new Array(64);\n\n let i;\n let dk = [];\n\n // inner = (password ^ ipad) || salt || counter\n for (i = 0; i < 64; i++) { inner[i] = 0x36; }\n for (i = 0; i < password.length; i++) { inner[i] ^= password[i]; }\n for (i = 0; i < salt.length; i++) { inner[64 + i] = salt[i]; }\n for (i = innerLen - 4; i < innerLen; i++) { inner[i] = 0; }\n\n // outerKey = password ^ opad\n for (i = 0; i < 64; i++) outerKey[i] = 0x5c;\n for (i = 0; i < password.length; i++) outerKey[i] ^= password[i];\n\n // increments counter inside inner\n function incrementCounter() {\n for (let i = innerLen - 1; i >= innerLen - 4; i--) {\n inner[i]++;\n if (inner[i] <= 0xff) return;\n inner[i] = 0;\n }\n }\n\n // output blocks = SHA256(outerKey || SHA256(inner)) ...\n while (dkLen >= 32) {\n incrementCounter();\n dk = dk.concat(SHA256(outerKey.concat(SHA256(inner))));\n dkLen -= 32;\n }\n if (dkLen > 0) {\n incrementCounter();\n dk = dk.concat(SHA256(outerKey.concat(SHA256(inner))).slice(0, dkLen));\n }\n\n return dk;\n }\n\n // The following is an adaptation of scryptsy\n // See: https://www.npmjs.com/package/scryptsy\n function blockmix_salsa8(BY, Yi, r, x, _X) {\n let i;\n\n arraycopy(BY, (2 * r - 1) * 16, _X, 0, 16);\n for (i = 0; i < 2 * r; i++) {\n blockxor(BY, i * 16, _X, 16);\n salsa20_8(_X, x);\n arraycopy(_X, 0, BY, Yi + (i * 16), 16);\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2) * 16, BY, (i * 16), 16);\n }\n\n for (i = 0; i < r; i++) {\n arraycopy(BY, Yi + (i * 2 + 1) * 16, BY, (i + r) * 16, 16);\n }\n }\n\n function R(a, b) {\n return (a << b) | (a >>> (32 - b));\n }\n\n function salsa20_8(B, x) {\n arraycopy(B, 0, x, 0, 16);\n\n for (let i = 8; i > 0; i -= 2) {\n x[ 4] ^= R(x[ 0] + x[12], 7);\n x[ 8] ^= R(x[ 4] + x[ 0], 9);\n x[12] ^= R(x[ 8] + x[ 4], 13);\n x[ 0] ^= R(x[12] + x[ 8], 18);\n x[ 9] ^= R(x[ 5] + x[ 1], 7);\n x[13] ^= R(x[ 9] + x[ 5], 9);\n x[ 1] ^= R(x[13] + x[ 9], 13);\n x[ 5] ^= R(x[ 1] + x[13], 18);\n x[14] ^= R(x[10] + x[ 6], 7);\n x[ 2] ^= R(x[14] + x[10], 9);\n x[ 6] ^= R(x[ 2] + x[14], 13);\n x[10] ^= R(x[ 6] + x[ 2], 18);\n x[ 3] ^= R(x[15] + x[11], 7);\n x[ 7] ^= R(x[ 3] + x[15], 9);\n x[11] ^= R(x[ 7] + x[ 3], 13);\n x[15] ^= R(x[11] + x[ 7], 18);\n x[ 1] ^= R(x[ 0] + x[ 3], 7);\n x[ 2] ^= R(x[ 1] + x[ 0], 9);\n x[ 3] ^= R(x[ 2] + x[ 1], 13);\n x[ 0] ^= R(x[ 3] + x[ 2], 18);\n x[ 6] ^= R(x[ 5] + x[ 4], 7);\n x[ 7] ^= R(x[ 6] + x[ 5], 9);\n x[ 4] ^= R(x[ 7] + x[ 6], 13);\n x[ 5] ^= R(x[ 4] + x[ 7], 18);\n x[11] ^= R(x[10] + x[ 9], 7);\n x[ 8] ^= R(x[11] + x[10], 9);\n x[ 9] ^= R(x[ 8] + x[11], 13);\n x[10] ^= R(x[ 9] + x[ 8], 18);\n x[12] ^= R(x[15] + x[14], 7);\n x[13] ^= R(x[12] + x[15], 9);\n x[14] ^= R(x[13] + x[12], 13);\n x[15] ^= R(x[14] + x[13], 18);\n }\n\n for (let i = 0; i < 16; ++i) {\n B[i] += x[i];\n }\n }\n\n // naive approach... going back to loop unrolling may yield additional performance\n function blockxor(S, Si, D, len) {\n for (let i = 0; i < len; i++) {\n D[i] ^= S[Si + i]\n }\n }\n\n function arraycopy(src, srcPos, dest, destPos, length) {\n while (length--) {\n dest[destPos++] = src[srcPos++];\n }\n }\n\n function checkBufferish(o) {\n if (!o || typeof(o.length) !== 'number') { return false; }\n\n for (let i = 0; i < o.length; i++) {\n const v = o[i];\n if (typeof(v) !== 'number' || v % 1 || v < 0 || v >= 256) {\n return false;\n }\n }\n\n return true;\n }\n\n function ensureInteger(value, name) {\n if (typeof(value) !== \"number\" || (value % 1)) { throw new Error('invalid ' + name); }\n return value;\n }\n\n // N = Cpu cost, r = Memory cost, p = parallelization cost\n // callback(error, progress, key)\n function _scrypt(password, salt, N, r, p, dkLen, callback) {\n\n N = ensureInteger(N, 'N');\n r = ensureInteger(r, 'r');\n p = ensureInteger(p, 'p');\n\n dkLen = ensureInteger(dkLen, 'dkLen');\n\n if (N === 0 || (N & (N - 1)) !== 0) { throw new Error('N must be power of 2'); }\n\n if (N > MAX_VALUE / 128 / r) { throw new Error('N too large'); }\n if (r > MAX_VALUE / 128 / p) { throw new Error('r too large'); }\n\n if (!checkBufferish(password)) {\n throw new Error('password must be an array or buffer');\n }\n password = Array.prototype.slice.call(password);\n\n if (!checkBufferish(salt)) {\n throw new Error('salt must be an array or buffer');\n }\n salt = Array.prototype.slice.call(salt);\n\n let b = PBKDF2_HMAC_SHA256_OneIter(password, salt, p * 128 * r);\n const B = new Uint32Array(p * 32 * r)\n for (let i = 0; i < B.length; i++) {\n const j = i * 4;\n B[i] = ((b[j + 3] & 0xff) << 24) |\n ((b[j + 2] & 0xff) << 16) |\n ((b[j + 1] & 0xff) << 8) |\n ((b[j + 0] & 0xff) << 0);\n }\n\n const XY = new Uint32Array(64 * r);\n const V = new Uint32Array(32 * r * N);\n\n const Yi = 32 * r;\n\n // scratch space\n const x = new Uint32Array(16); // salsa20_8\n const _X = new Uint32Array(16); // blockmix_salsa8\n\n const totalOps = p * N * 2;\n let currentOp = 0;\n let lastPercent10 = null;\n\n // Set this to true to abandon the scrypt on the next step\n let stop = false;\n\n // State information\n let state = 0;\n let i0 = 0, i1;\n let Bi;\n\n // How many blockmix_salsa8 can we do per step?\n const limit = callback ? parseInt(1000 / r): 0xffffffff;\n\n // Trick from scrypt-async; if there is a setImmediate shim in place, use it\n const nextTick = (typeof(setImmediate) !== 'undefined') ? setImmediate : setTimeout;\n\n // This is really all I changed; making scryptsy a state machine so we occasionally\n // stop and give other evnts on the evnt loop a chance to run. ~RicMoo\n const incrementalSMix = function() {\n if (stop) {\n return callback(new Error('cancelled'), currentOp / totalOps);\n }\n\n let steps;\n\n switch (state) {\n case 0:\n // for (var i = 0; i < p; i++)...\n Bi = i0 * 32 * r;\n\n arraycopy(B, Bi, XY, 0, Yi); // ROMix - 1\n\n state = 1; // Move to ROMix 2\n i1 = 0;\n\n // Fall through\n\n case 1:\n\n // Run up to 1000 steps of the first inner smix loop\n steps = N - i1;\n if (steps > limit) { steps = limit; }\n for (let i = 0; i < steps; i++) { // ROMix - 2\n arraycopy(XY, 0, V, (i1 + i) * Yi, Yi) // ROMix - 3\n blockmix_salsa8(XY, Yi, r, x, _X); // ROMix - 4\n }\n\n // for (var i = 0; i < N; i++)\n i1 += steps;\n currentOp += steps;\n\n if (callback) {\n // Call the callback with the progress (optionally stopping us)\n const percent10 = parseInt(1000 * currentOp / totalOps);\n if (percent10 !== lastPercent10) {\n stop = callback(null, currentOp / totalOps);\n if (stop) { break; }\n lastPercent10 = percent10;\n }\n }\n\n if (i1 < N) { break; }\n\n i1 = 0; // Move to ROMix 6\n state = 2;\n\n // Fall through\n\n case 2:\n\n // Run up to 1000 steps of the second inner smix loop\n steps = N - i1;\n if (steps > limit) { steps = limit; }\n for (let i = 0; i < steps; i++) { // ROMix - 6\n const offset = (2 * r - 1) * 16; // ROMix - 7\n const j = XY[offset] & (N - 1);\n blockxor(V, j * Yi, XY, Yi); // ROMix - 8 (inner)\n blockmix_salsa8(XY, Yi, r, x, _X); // ROMix - 9 (outer)\n }\n\n // for (var i = 0; i < N; i++)...\n i1 += steps;\n currentOp += steps;\n\n // Call the callback with the progress (optionally stopping us)\n if (callback) {\n const percent10 = parseInt(1000 * currentOp / totalOps);\n if (percent10 !== lastPercent10) {\n stop = callback(null, currentOp / totalOps);\n if (stop) { break; }\n lastPercent10 = percent10;\n }\n }\n\n if (i1 < N) { break; }\n\n arraycopy(XY, 0, B, Bi, Yi); // ROMix - 10\n\n // for (var i = 0; i < p; i++)...\n i0++;\n if (i0 < p) {\n state = 0;\n break;\n }\n\n b = [];\n for (let i = 0; i < B.length; i++) {\n b.push((B[i] >> 0) & 0xff);\n b.push((B[i] >> 8) & 0xff);\n b.push((B[i] >> 16) & 0xff);\n b.push((B[i] >> 24) & 0xff);\n }\n\n const derivedKey = PBKDF2_HMAC_SHA256_OneIter(password, b, dkLen);\n\n // Send the result to the callback\n if (callback) { callback(null, 1.0, derivedKey); }\n\n // Done; don't break (which would reschedule)\n return derivedKey;\n }\n\n // Schedule the next steps\n if (callback) { nextTick(incrementalSMix); }\n }\n\n // Run the smix state machine until completion\n if (!callback) {\n while (true) {\n const derivedKey = incrementalSMix();\n if (derivedKey != undefined) { return derivedKey; }\n }\n }\n\n // Bootstrap the async incremental smix\n incrementalSMix();\n }\n\n const lib = {\n scrypt: function(password, salt, N, r, p, dkLen, progressCallback) {\n return new Promise(function(resolve, reject) {\n let lastProgress = 0;\n if (progressCallback) { progressCallback(0); }\n _scrypt(password, salt, N, r, p, dkLen, function(error, progress, key) {\n if (error) {\n reject(error);\n } else if (key) {\n if (progressCallback && lastProgress !== 1) {\n progressCallback(1);\n }\n resolve(new Uint8Array(key));\n } else if (progressCallback && progress !== lastProgress) {\n lastProgress = progress;\n return progressCallback(progress);\n }\n });\n });\n },\n syncScrypt: function(password, salt, N, r, p, dkLen) {\n return new Uint8Array(_scrypt(password, salt, N, r, p, dkLen));\n }\n };\n\n // node.js\n if (typeof(exports) !== 'undefined') {\n module.exports = lib;\n\n // RequireJS/AMD\n // http://www.requirejs.org/docs/api.html\n // https://github.com/amdjs/amdjs-api/wiki/AMD\n } else if (typeof(define) === 'function' && define.amd) {\n define(lib);\n\n // Web Browsers\n } else if (root) {\n\n // If there was an existing library \"scrypt\", make sure it is still available\n if (root.scrypt) {\n root._scrypt = root.scrypt;\n }\n\n root.scrypt = lib;\n }\n\n})(this);\n", - "var SortedArray = (function () {\n var SortedArray = defclass({\n\n constructor: function (array, compare) {\n this.array = [];\n this.compare = compare || compareDefault;\n var length = array.length,\n index = 0;\n while (index < length) this.insert(array[index++]);\n },\n insert: function (element) {\n var array = this.array,\n compare = this.compare,\n high = array.length-1,\n low = 0,\n pos = -1,\n index,\n ordering;\n\n // The array is sorted. You must find the position of new element in O(log(n)), not O(n).\n while (high >= low) {\n index = (high + low) / 2 >>> 0;\n ordering = compare(array[index], element); \n if (ordering < 0) low = index + 1;\n else if (ordering > 0) high = index - 1;\n else {\n pos = index;\n break;\n };\n }\n\n if (pos === -1) {\n // if element was not found, high < low.\n pos = high;\n }\n // This assures that equal elements inserted after will be in a higher position in array.\n // They can be equal for comparison purposes, but different objects with different data.\n // Respecting the chronological order can be important for many applications.\n pos++;\n high = array.length-1;\n while ((pos < high) && (compare(element, array[pos]) === 0)){\n pos++;\n }\n index = array.length;\n // Just to increase array size.\n array.push(element); \n // Much faster. No need to elements swap.\n while (index > pos) {\n array[index] = array[--index];\n }\n // Set the new element on its correct position.\n array[pos] = element;\n\n return this;\n },\n search: function (element) {\n var array = this.array,\n compare = this.compare,\n high = array.length-1,\n low = 0,\n // In most languages, inner variable declaration makes the code slower.\n index,\n ordering;\n\n while (high >= low) {\n index = (high + low) / 2 >>> 0;\n ordering = compare(array[index], element);\n\n if (ordering < 0) low = index + 1;\n else if (ordering > 0) high = index - 1;\n else return index;\n }\n\n return -1;\n },\n remove: function (element) {\n var index = this.search(element);\n if (index >= 0) this.array.splice(index, 1);\n return this;\n }\n });\n\n SortedArray.comparing = function (property, array) {\n return new SortedArray(array, function (a, b) {\n // This should be faster than calling functions.\n // Besides, this way it is not needed to create useless function to return property value.\n return compareDefault(a[property], b[property]);\n });\n };\n\n return SortedArray;\n\n function defclass(prototype) {\n var constructor = prototype.constructor;\n constructor.prototype = prototype;\n return constructor;\n }\n\n function compareDefault(a, b) {\n // Equality has a very low chance to happen. It should be the last option.\n if (a < b)\n return -1;\n else if (a > b)\n return 1;\n else\n return 0;\n }\n}());\n\nif (typeof module === \"object\") module.exports = SortedArray;\nif (typeof define === \"function\" && define.amd)\n define(function () { return SortedArray; });\n", - "// Unique ID creation requires a high quality random # generator. In the\n// browser this is a little complicated due to unknown quality of Math.random()\n// and inconsistent support for the `crypto` API. We do the best we can via\n// feature-detection\n\n// getRandomValues needs to be invoked in a context where \"this\" is a Crypto\n// implementation. Also, find the complete implementation of crypto on IE11.\nvar getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||\n (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));\n\nif (getRandomValues) {\n // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto\n var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef\n\n module.exports = function whatwgRNG() {\n getRandomValues(rnds8);\n return rnds8;\n };\n} else {\n // Math.random()-based (RNG)\n //\n // If all else fails, use Math.random(). It's fast, but is of unspecified\n // quality.\n var rnds = new Array(16);\n\n module.exports = function mathRNG() {\n for (var i = 0, r; i < 16; i++) {\n if ((i & 0x03) === 0) r = Math.random() * 0x100000000;\n rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n }\n\n return rnds;\n };\n}\n", - "/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nvar byteToHex = [];\nfor (var i = 0; i < 256; ++i) {\n byteToHex[i] = (i + 0x100).toString(16).substr(1);\n}\n\nfunction bytesToUuid(buf, offset) {\n var i = offset || 0;\n var bth = byteToHex;\n // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4\n return ([\n bth[buf[i++]], bth[buf[i++]],\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]],\n bth[buf[i++]], bth[buf[i++]],\n bth[buf[i++]], bth[buf[i++]]\n ]).join('');\n}\n\nmodule.exports = bytesToUuid;\n", - "'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n", - "/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n", - "var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n", - "/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n", - "module.exports = function(module) {\n\tif (!module.webpackPolyfill) {\n\t\tmodule.deprecate = function() {};\n\t\tmodule.paths = [];\n\t\t// module.parent = undefined by default\n\t\tif (!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\n", - "var r;\n\nmodule.exports = function rand(len) {\n if (!r)\n r = new Rand(null);\n\n return r.generate(len);\n};\n\nfunction Rand(rand) {\n this.rand = rand;\n}\nmodule.exports.Rand = Rand;\n\nRand.prototype.generate = function generate(len) {\n return this._rand(len);\n};\n\n// Emulate crypto API using randy\nRand.prototype._rand = function _rand(n) {\n if (this.rand.getBytes)\n return this.rand.getBytes(n);\n\n var res = new Uint8Array(n);\n for (var i = 0; i < res.length; i++)\n res[i] = this.rand.getByte();\n return res;\n};\n\nif (typeof self === 'object') {\n if (self.crypto && self.crypto.getRandomValues) {\n // Modern browsers\n Rand.prototype._rand = function _rand(n) {\n var arr = new Uint8Array(n);\n self.crypto.getRandomValues(arr);\n return arr;\n };\n } else if (self.msCrypto && self.msCrypto.getRandomValues) {\n // IE\n Rand.prototype._rand = function _rand(n) {\n var arr = new Uint8Array(n);\n self.msCrypto.getRandomValues(arr);\n return arr;\n };\n\n // Safari's WebWorkers do not have `crypto`\n } else if (typeof window === 'object') {\n // Old junk\n Rand.prototype._rand = function() {\n throw new Error('Not implemented yet');\n };\n }\n} else {\n // Node.js or Web worker with no crypto support\n try {\n var crypto = require('crypto');\n if (typeof crypto.randomBytes !== 'function')\n throw new Error('Not supported');\n\n Rand.prototype._rand = function _rand(n) {\n return crypto.randomBytes(n);\n };\n } catch (e) {\n }\n}\n", - "var BN = require('bn.js');\nvar MillerRabin = require('miller-rabin');\nvar millerRabin = new MillerRabin();\nvar TWENTYFOUR = new BN(24);\nvar ELEVEN = new BN(11);\nvar TEN = new BN(10);\nvar THREE = new BN(3);\nvar SEVEN = new BN(7);\nvar primes = require('./generatePrime');\nvar randomBytes = require('randombytes');\nmodule.exports = DH;\n\nfunction setPublicKey(pub, enc) {\n enc = enc || 'utf8';\n if (!Buffer.isBuffer(pub)) {\n pub = new Buffer(pub, enc);\n }\n this._pub = new BN(pub);\n return this;\n}\n\nfunction setPrivateKey(priv, enc) {\n enc = enc || 'utf8';\n if (!Buffer.isBuffer(priv)) {\n priv = new Buffer(priv, enc);\n }\n this._priv = new BN(priv);\n return this;\n}\n\nvar primeCache = {};\nfunction checkPrime(prime, generator) {\n var gen = generator.toString('hex');\n var hex = [gen, prime.toString(16)].join('_');\n if (hex in primeCache) {\n return primeCache[hex];\n }\n var error = 0;\n\n if (prime.isEven() ||\n !primes.simpleSieve ||\n !primes.fermatTest(prime) ||\n !millerRabin.test(prime)) {\n //not a prime so +1\n error += 1;\n\n if (gen === '02' || gen === '05') {\n // we'd be able to check the generator\n // it would fail so +8\n error += 8;\n } else {\n //we wouldn't be able to test the generator\n // so +4\n error += 4;\n }\n primeCache[hex] = error;\n return error;\n }\n if (!millerRabin.test(prime.shrn(1))) {\n //not a safe prime\n error += 2;\n }\n var rem;\n switch (gen) {\n case '02':\n if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {\n // unsuidable generator\n error += 8;\n }\n break;\n case '05':\n rem = prime.mod(TEN);\n if (rem.cmp(THREE) && rem.cmp(SEVEN)) {\n // prime mod 10 needs to equal 3 or 7\n error += 8;\n }\n break;\n default:\n error += 4;\n }\n primeCache[hex] = error;\n return error;\n}\n\nfunction DH(prime, generator, malleable) {\n this.setGenerator(generator);\n this.__prime = new BN(prime);\n this._prime = BN.mont(this.__prime);\n this._primeLen = prime.length;\n this._pub = undefined;\n this._priv = undefined;\n this._primeCode = undefined;\n if (malleable) {\n this.setPublicKey = setPublicKey;\n this.setPrivateKey = setPrivateKey;\n } else {\n this._primeCode = 8;\n }\n}\nObject.defineProperty(DH.prototype, 'verifyError', {\n enumerable: true,\n get: function () {\n if (typeof this._primeCode !== 'number') {\n this._primeCode = checkPrime(this.__prime, this.__gen);\n }\n return this._primeCode;\n }\n});\nDH.prototype.generateKeys = function () {\n if (!this._priv) {\n this._priv = new BN(randomBytes(this._primeLen));\n }\n this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();\n return this.getPublicKey();\n};\n\nDH.prototype.computeSecret = function (other) {\n other = new BN(other);\n other = other.toRed(this._prime);\n var secret = other.redPow(this._priv).fromRed();\n var out = new Buffer(secret.toArray());\n var prime = this.getPrime();\n if (out.length < prime.length) {\n var front = new Buffer(prime.length - out.length);\n front.fill(0);\n out = Buffer.concat([front, out]);\n }\n return out;\n};\n\nDH.prototype.getPublicKey = function getPublicKey(enc) {\n return formatReturnValue(this._pub, enc);\n};\n\nDH.prototype.getPrivateKey = function getPrivateKey(enc) {\n return formatReturnValue(this._priv, enc);\n};\n\nDH.prototype.getPrime = function (enc) {\n return formatReturnValue(this.__prime, enc);\n};\n\nDH.prototype.getGenerator = function (enc) {\n return formatReturnValue(this._gen, enc);\n};\n\nDH.prototype.setGenerator = function (gen, enc) {\n enc = enc || 'utf8';\n if (!Buffer.isBuffer(gen)) {\n gen = new Buffer(gen, enc);\n }\n this.__gen = gen;\n this._gen = new BN(gen);\n return this;\n};\n\nfunction formatReturnValue(bn, enc) {\n var buf = new Buffer(bn.toArray());\n if (!enc) {\n return buf;\n } else {\n return buf.toString(enc);\n }\n}\n", - "var scope = (typeof global !== \"undefined\" && global) ||\n (typeof self !== \"undefined\" && self) ||\n window;\nvar apply = Function.prototype.apply;\n\n// DOM APIs, for completeness\n\nexports.setTimeout = function() {\n return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);\n};\nexports.setInterval = function() {\n return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);\n};\nexports.clearTimeout =\nexports.clearInterval = function(timeout) {\n if (timeout) {\n timeout.close();\n }\n};\n\nfunction Timeout(id, clearFn) {\n this._id = id;\n this._clearFn = clearFn;\n}\nTimeout.prototype.unref = Timeout.prototype.ref = function() {};\nTimeout.prototype.close = function() {\n this._clearFn.call(scope, this._id);\n};\n\n// Does not start the time, just sets up the members needed.\nexports.enroll = function(item, msecs) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = msecs;\n};\n\nexports.unenroll = function(item) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = -1;\n};\n\nexports._unrefActive = exports.active = function(item) {\n clearTimeout(item._idleTimeoutId);\n\n var msecs = item._idleTimeout;\n if (msecs >= 0) {\n item._idleTimeoutId = setTimeout(function onTimeout() {\n if (item._onTimeout)\n item._onTimeout();\n }, msecs);\n }\n};\n\n// setimmediate attaches itself to the global object\nrequire(\"setimmediate\");\n// On some exotic environments, it's not clear which object `setimmediate` was\n// able to install onto. Search each possibility in the same order as the\n// `setimmediate` library.\nexports.setImmediate = (typeof self !== \"undefined\" && self.setImmediate) ||\n (typeof global !== \"undefined\" && global.setImmediate) ||\n (this && this.setImmediate);\nexports.clearImmediate = (typeof self !== \"undefined\" && self.clearImmediate) ||\n (typeof global !== \"undefined\" && global.clearImmediate) ||\n (this && this.clearImmediate);\n", - "(function (global, undefined) {\n \"use strict\";\n\n if (global.setImmediate) {\n return;\n }\n\n var nextHandle = 1; // Spec says greater than zero\n var tasksByHandle = {};\n var currentlyRunningATask = false;\n var doc = global.document;\n var registerImmediate;\n\n function setImmediate(callback) {\n // Callback can either be a function or a string\n if (typeof callback !== \"function\") {\n callback = new Function(\"\" + callback);\n }\n // Copy function arguments\n var args = new Array(arguments.length - 1);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i + 1];\n }\n // Store and register the task\n var task = { callback: callback, args: args };\n tasksByHandle[nextHandle] = task;\n registerImmediate(nextHandle);\n return nextHandle++;\n }\n\n function clearImmediate(handle) {\n delete tasksByHandle[handle];\n }\n\n function run(task) {\n var callback = task.callback;\n var args = task.args;\n switch (args.length) {\n case 0:\n callback();\n break;\n case 1:\n callback(args[0]);\n break;\n case 2:\n callback(args[0], args[1]);\n break;\n case 3:\n callback(args[0], args[1], args[2]);\n break;\n default:\n callback.apply(undefined, args);\n break;\n }\n }\n\n function runIfPresent(handle) {\n // From the spec: \"Wait until any invocations of this algorithm started before this one have completed.\"\n // So if we're currently running a task, we'll need to delay this invocation.\n if (currentlyRunningATask) {\n // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a\n // \"too much recursion\" error.\n setTimeout(runIfPresent, 0, handle);\n } else {\n var task = tasksByHandle[handle];\n if (task) {\n currentlyRunningATask = true;\n try {\n run(task);\n } finally {\n clearImmediate(handle);\n currentlyRunningATask = false;\n }\n }\n }\n }\n\n function installNextTickImplementation() {\n registerImmediate = function(handle) {\n process.nextTick(function () { runIfPresent(handle); });\n };\n }\n\n function canUsePostMessage() {\n // The test against `importScripts` prevents this implementation from being installed inside a web worker,\n // where `global.postMessage` means something completely different and can't be used for this purpose.\n if (global.postMessage && !global.importScripts) {\n var postMessageIsAsynchronous = true;\n var oldOnMessage = global.onmessage;\n global.onmessage = function() {\n postMessageIsAsynchronous = false;\n };\n global.postMessage(\"\", \"*\");\n global.onmessage = oldOnMessage;\n return postMessageIsAsynchronous;\n }\n }\n\n function installPostMessageImplementation() {\n // Installs an event handler on `global` for the `message` event: see\n // * https://developer.mozilla.org/en/DOM/window.postMessage\n // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages\n\n var messagePrefix = \"setImmediate$\" + Math.random() + \"$\";\n var onGlobalMessage = function(event) {\n if (event.source === global &&\n typeof event.data === \"string\" &&\n event.data.indexOf(messagePrefix) === 0) {\n runIfPresent(+event.data.slice(messagePrefix.length));\n }\n };\n\n if (global.addEventListener) {\n global.addEventListener(\"message\", onGlobalMessage, false);\n } else {\n global.attachEvent(\"onmessage\", onGlobalMessage);\n }\n\n registerImmediate = function(handle) {\n global.postMessage(messagePrefix + handle, \"*\");\n };\n }\n\n function installMessageChannelImplementation() {\n var channel = new MessageChannel();\n channel.port1.onmessage = function(event) {\n var handle = event.data;\n runIfPresent(handle);\n };\n\n registerImmediate = function(handle) {\n channel.port2.postMessage(handle);\n };\n }\n\n function installReadyStateChangeImplementation() {\n var html = doc.documentElement;\n registerImmediate = function(handle) {\n // Create a