diff --git a/.gitignore b/.gitignore index 78212683a..b00bdfb56 100644 --- a/.gitignore +++ b/.gitignore @@ -272,3 +272,4 @@ $RECYCLE.BIN/ # Windows shortcuts *.lnk +/.idea/ diff --git a/lib/commands/block.js b/lib/commands/block.js index 450eb4a86..1afb7dab9 100644 --- a/lib/commands/block.js +++ b/lib/commands/block.js @@ -4,6 +4,8 @@ const Block = module.exports; const Nacl = require("tweetnacl/nacl-fast"); +const ml_kem = require("@noble/post-quantum/ml-kem"); +const ml_dsa = require("@noble/post-quantum/ml-dsa"); const nThen = require("nthen"); const Util = require("../common-util"); const BlockStore = require("../storage/block"); @@ -36,7 +38,7 @@ Block.isValidBlockId = id => { author of the block, since we assume that the block will have been encrypted with xsalsa20-poly1305 which is authenticated. */ -Block.validateLoginBlock = function (Env, publicKey, signature, block, _cb) { +Block.validateLoginBlock = function (Env, publicKey, signature, block, pqPublicKey, _cb) { var cb = Util.once(Util.mkAsync(_cb)); // convert the public key to a Uint8Array and validate it @@ -68,10 +70,87 @@ Block.validateLoginBlock = function (Env, publicKey, signature, block, _cb) { // take its hash var hash = Nacl.hash(u8_block); - // validate the signature against the hash of the content - var verified = Nacl.sign.detached.verify(hash, u8_signature, u8_public_key); + // Check signature type - first byte indicates the format + var sigType = u8_signature[0]; + var verified = false; - // existing authentication ensures that users cannot replay old blocks + if (sigType === 1 && u8_signature.length > 65) { + // Hybrid signature - check the classical part first + const classicalSig = u8_signature.subarray(1, 1 + 64); // Ed25519 signature is 64 bytes + const classicalVerified = Nacl.sign.detached.verify(hash, classicalSig, u8_public_key); + + if (!classicalVerified) { + Env.Log.error('BLOCK_CLASSICAL_VERIFICATION_FAILED', { + blockId: publicKey + }); + return void cb('E_COULD_NOT_VERIFY_CLASSICAL'); + } + + // Now check PQ signature - this is required for hybrid signatures + let pqVerified = false; + + if (!ml_kem || !ml_dsa) { + Env.Log.error('BLOCK_PQ_VERIFICATION_ERROR', { + error: 'PQ libraries not available', + blockId: publicKey + }); + return void cb('E_PQ_LIBRARIES_MISSING'); + } + + try { + // Get PQ signature length from the 4 bytes after classical signature + const pqSigLenView = new DataView(u8_signature.buffer, u8_signature.byteOffset + 65); + const pqSigLen = pqSigLenView.getUint32(0, false); // big-endian + + // Extract PQ signature + const pqSig = u8_signature.subarray(1 + 64 + 4, 1 + 64 + 4 + pqSigLen); + + // If PQ public key is provided, verify the PQ signature + let publicKeyToUse = pqPublicKey; + if (!publicKeyToUse && Env.blockInfo && Env.blockInfo[publicKey] && Env.blockInfo[publicKey].pqPublicKey) { + publicKeyToUse = Env.blockInfo[publicKey].pqPublicKey; + } + + if (!publicKeyToUse) { + Env.Log.error('BLOCK_PQ_VERIFICATION_ERROR', { + error: 'PQ public key not available', + blockId: publicKey + }); + return void cb('E_MISSING_PQ_PUBLIC_KEY'); + } + + const pqPublicKeyDecoded = Util.decodeBase64(publicKeyToUse); + + pqVerified = ml_dsa.ml_dsa44.internal.verify( + pqPublicKeyDecoded, + hash, + pqSig + ); + + Env.Log.info('BLOCK_PQ_VERIFICATION_RESULT', { + blockId: publicKey, + result: pqVerified + }); + + if (!pqVerified) { + return void cb('E_COULD_NOT_VERIFY_PQ'); + } + } catch (err) { + Env.Log.error('BLOCK_PQ_VERIFICATION_ERROR', { + error: err.message, + blockId: publicKey + }); + return void cb('E_PQ_VERIFICATION_ERROR'); + } + + // Both classical and PQ signatures verified + verified = classicalVerified && pqVerified; + } else { + // Classical signature or unrecognized format - use normal verification + // For type 0 we need to skip the first byte + const classicalSig = sigType === 0 ? u8_signature.subarray(1) : u8_signature; + verified = Nacl.sign.detached.verify(hash, classicalSig, u8_public_key); + } // call back with (err) if unsuccessful if (!verified) { return void cb("E_COULD_NOT_VERIFY"); } @@ -81,16 +160,106 @@ Block.validateLoginBlock = function (Env, publicKey, signature, block, _cb) { Block.validateAncestorProof = function (Env, proof, _cb) { var cb = Util.once(Util.mkAsync(_cb)); -/* prove that you own an existing block by signing for its publicKey */ + /* prove that you own an existing block by signing for its publicKey */ try { var parsed = JSON.parse(proof); var pub = parsed[0]; var u8_pub = Util.decodeBase64(pub); var sig = parsed[1]; var u8_sig = Util.decodeBase64(sig); + // Extract PQ public key from the proof if it exists (3rd element) + var ancestorPqPublicKey = parsed.length > 2 ? parsed[2] : undefined; var valid = false; + nThen(function (w) { - valid = Nacl.sign.detached.verify(u8_pub, u8_sig, u8_pub); + // Check signature type - first byte indicates the format + var sigType = u8_sig[0]; + + if (sigType === 1 && u8_sig.length > 65) { + // Hybrid signature - check the classical part first + const classicalSig = u8_sig.subarray(1, 1 + 64); // Ed25519 signature is 64 bytes + const classicalVerified = Nacl.sign.detached.verify(u8_pub, classicalSig, u8_pub); + + if (!classicalVerified) { + Env.Log.error('ANCESTOR_CLASSICAL_VERIFICATION_FAILED', { + blockId: pub + }); + w.abort(); + return void cb('E_INVALID_ANCESTOR_PROOF_CLASSICAL'); + } + + // Now check PQ signature - this is required for hybrid signatures + let pqVerified = false; + + if (!ml_kem || !ml_dsa) { + Env.Log.error('ANCESTOR_PQ_VERIFICATION_ERROR', { + error: 'PQ libraries not available', + blockId: pub + }); + w.abort(); + return void cb('E_PQ_LIBRARIES_MISSING'); + } + + try { + // Get PQ signature length from the 4 bytes after classical signature + const pqSigLenView = new DataView(u8_sig.buffer, u8_sig.byteOffset + 65); + const pqSigLen = pqSigLenView.getUint32(0, false); // big-endian + + // Extract PQ signature + const pqSig = u8_sig.subarray(1 + 64 + 4, 1 + 64 + 4 + pqSigLen); + + // If PQ public key is provided, verify the PQ signature + let pqPublicKey; + if (Env.blockInfo && Env.blockInfo[pub] && Env.blockInfo[pub].pqPublicKey) { + pqPublicKey = Env.blockInfo[pub].pqPublicKey; + } else if (ancestorPqPublicKey) { + pqPublicKey = ancestorPqPublicKey; + } + + if (!pqPublicKey) { + Env.Log.error('ANCESTOR_PQ_VERIFICATION_ERROR', { + error: 'PQ public key not available', + blockId: pub + }); + w.abort(); + return void cb('E_MISSING_PQ_PUBLIC_KEY'); + } + + const pqPublicKeyDecoded = Util.decodeBase64(pqPublicKey); + + pqVerified = ml_dsa.ml_dsa44.internal.verify( + pqPublicKeyDecoded, + u8_pub, + pqSig + ); + + Env.Log.info('ANCESTOR_PQ_VERIFICATION_RESULT', { + blockId: pub, + result: pqVerified + }); + + if (!pqVerified) { + w.abort(); + return void cb('E_INVALID_ANCESTOR_PROOF_PQ'); + } + } catch (err) { + Env.Log.error('ANCESTOR_PQ_VERIFICATION_ERROR', { + error: err.message, + blockId: pub + }); + w.abort(); + return void cb('E_PQ_VERIFICATION_ERROR'); + } + + // Both classical and PQ signatures verified + valid = classicalVerified && pqVerified; + } else { + // Classical signature or unrecognized format - use normal verification + // For type 0 we need to skip the first byte + const classicalSig = sigType === 0 ? u8_sig.subarray(1) : u8_sig; + valid = Nacl.sign.detached.verify(u8_pub, classicalSig, u8_pub); + } + if (!valid) { w.abort(); return void cb('E_INVALID_ANCESTOR_PROOF'); @@ -109,7 +278,7 @@ Block.validateAncestorProof = function (Env, proof, _cb) { Block.writeLoginBlock = function (Env, msg, _cb) { var cb = Util.once(Util.mkAsync(_cb)); - const { publicKey, signature, ciphertext, registrationProof, userData, inviteToken, isSSO } = msg; + const { publicKey, signature, ciphertext, registrationProof, userData, inviteToken, isSSO, pqPublicKey } = msg; var previousKey; var validatedBlock, path; @@ -144,7 +313,7 @@ Block.writeLoginBlock = function (Env, msg, _cb) { previousKey = provenKey; })); }).nThen(function (w) { - Block.validateLoginBlock(Env, publicKey, signature, ciphertext, w(function (e, _validatedBlock) { + Block.validateLoginBlock(Env, publicKey, signature, ciphertext, pqPublicKey, w(function (e, _validatedBlock) { if (e) { w.abort(); return void cb(e); @@ -170,6 +339,20 @@ Block.writeLoginBlock = function (Env, msg, _cb) { previousKey: previousKey, path: path, }); + + // Store PQ public key in blockInfo if provided + if (!err && pqPublicKey && typeof pqPublicKey === 'string') { + // Initialize blockInfo if it doesn't exist + if (!Env.blockInfo) { Env.blockInfo = {}; } + if (!Env.blockInfo[publicKey]) { Env.blockInfo[publicKey] = {}; } + + // Store PQ public key for later verification + Env.blockInfo[publicKey].pqPublicKey = pqPublicKey; + Env.Log.info('BLOCK_PQ_KEY_STORED', { + blockId: publicKey + }); + } + cb(err); if (!err && registrationProof) { Users.checkUpdate(Env, userData, publicKey, (err) => { @@ -255,4 +438,3 @@ Block.removeLoginBlock = function (Env, publicKey, reason, edPublic, _cb) { SSOUtils.deleteBlock(Env, publicKey, () => {}); } }; - diff --git a/lib/commands/core.js b/lib/commands/core.js index 6c92af74f..afd5233e3 100644 --- a/lib/commands/core.js +++ b/lib/commands/core.js @@ -19,6 +19,10 @@ Core.isValidPublicKey = function (owner) { return typeof(owner) === 'string' && owner.length === 44; }; +Core.isValidKemPublicKey = function (kemPublic) { + return typeof(kemPublic) === 'string' && kemPublic.length === 800; +}; + var makeToken = Core.makeToken = function () { return Number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)) .toString(16); diff --git a/lib/decrees.js b/lib/decrees.js index ba5f57a95..a3a503e72 100644 --- a/lib/decrees.js +++ b/lib/decrees.js @@ -264,14 +264,16 @@ commands.DISABLE_APPS = function (Env, args) { commands.SET_SUPPORT_KEYS = function (Env, args) { const curvePublic = args[0]; // Support mailbox key const edPublic = args[1]; // Support pin log + const kemPublic = args[2]; // Support KEM key let validated = typeof(curvePublic) === "string" && (Core.isValidPublicKey(curvePublic) || !curvePublic) && typeof(edPublic) === "string" && (Core.isValidPublicKey(edPublic) || !edPublic); if (!validated) { throw new Error('INVALID_ARGS'); } - if (Env.supportMailboxKey === curvePublic && Env.supportPinKey === edPublic) { return false; } + if (Env.supportMailboxKey === curvePublic && Env.supportPinKey === edPublic && Env.supportMailboxKemKey === kemPublic) { return false; } Env.supportMailboxKey = curvePublic; Env.supportPinKey = edPublic; + Env.supportMailboxKemKey = kemPublic; return true; }; diff --git a/lib/env.js b/lib/env.js index 2c7f18c1a..50ed5b013 100644 --- a/lib/env.js +++ b/lib/env.js @@ -98,7 +98,7 @@ module.exports.create = function (config) { protocol: new URL(httpUnsafeOrigin).protocol, - fileHost: config.fileHost || undefined, + fileHost: config.fileHost? new URL(config.fileHost).origin : undefined, NO_SANDBOX: NO_SANDBOX, httpSafePort: httpSafePort, websocketPort: config.websocketPort, @@ -156,6 +156,7 @@ module.exports.create = function (config) { adminEmail: config.adminEmail, supportMailbox: config.supportMailboxPublicKey, supportMailboxKey: undefined, + supportMailboxKemKey: undefined, metadata_cache: {}, channel_cache: {}, diff --git a/lib/hk-util.js b/lib/hk-util.js index 4be22239e..8d54fa3b3 100644 --- a/lib/hk-util.js +++ b/lib/hk-util.js @@ -107,6 +107,10 @@ HK.authenticateNetfluxSession = function (Env, netfluxId, unsafeKey) { var user = Env.netfluxUsers[netfluxId] = Env.netfluxUsers[netfluxId] || {}; user[unsafeKey] = +new Date(); }; +HK.unauthenticateNetfluxSession = function (Env, netfluxId, unsafeKey) { + var user = Env.netfluxUsers[netfluxId] = Env.netfluxUsers[netfluxId] || {}; + delete user[unsafeKey]; +}; HK.closeNetfluxSession = function (Env, netfluxId) { delete Env.netfluxUsers[netfluxId]; @@ -1032,7 +1036,7 @@ HK.onChannelMessage = function (Env, Server, channel, msgStruct, cb) { })); }).nThen(function (w) { // if there's no validateKey present skip to the next block - if (!(metadata && metadata.validateKey)) { return; } + if (!(metadata && metadata.validateKey && metadata.dsaPublic)) { return; } // trim the checkpoint indicator off the message if it's present let signedMsg = (isCp) ? msgStruct[4].replace(CHECKPOINT_PATTERN, '') : msgStruct[4]; @@ -1045,7 +1049,7 @@ HK.onChannelMessage = function (Env, Server, channel, msgStruct, cb) { */ var proceed = w(); Env.queueValidation(channel.id, function (next) { - Env.validateMessage(signedMsg, metadata.validateKey, function (err) { + Env.validateMessage(signedMsg, metadata.validateKey, metadata.dsaPublic, function (err) { // always go on to the next item in the queue regardless of the outcome next(); @@ -1056,7 +1060,8 @@ HK.onChannelMessage = function (Env, Server, channel, msgStruct, cb) { // we log this case, but not others for some reason Log.info("HK_SIGNED_MESSAGE_REJECTED", { channel: channel.id, - validateKey: metadata.validayKey, + validateKey: metadata.validateKey, + dsaPublic: metadata.dsaPublic, message: signedMsg, }); } diff --git a/lib/http-worker.js b/lib/http-worker.js index eb5a0dd74..640a2a8ef 100644 --- a/lib/http-worker.js +++ b/lib/http-worker.js @@ -623,6 +623,7 @@ var serveConfig = makeRouteCache(function () { inactiveTime: Env.inactiveTime, supportMailbox: Env.supportMailbox, supportMailboxKey: Env.supportMailboxKey, + supportMailboxKemKey: Env.supportMailboxKemKey, defaultStorageLimit: Env.defaultStorageLimit, maxUploadSize: Env.maxUploadSize, premiumUploadSize: Env.premiumUploadSize, diff --git a/lib/rpc.js b/lib/rpc.js index 806950db5..d9c122461 100644 --- a/lib/rpc.js +++ b/lib/rpc.js @@ -72,6 +72,7 @@ const AUTHENTICATED_USER_SCOPED = { REMOVE_PINS: Pinning.removePins, TRIM_PINS: Pinning.trimPins, COOKIE: Core.haveACookie, + DESTROY: () => {} }; var isAuthenticatedCall = function (call) { @@ -190,6 +191,11 @@ var rpc = function (Env, Server, userId, data, respond) { if (command === 'COOKIE' && !hadSession && Env.logIP) { Env.Log.info('NEW_RPC_SESSION', {userId: userId, publicKey: publicKey}); } + if (command === "DESTROY") { + HK.unauthenticateNetfluxSession(Env, userId, publicKey); + return; // No need to respond, user will close the session + } + HK.authenticateNetfluxSession(Env, userId, publicKey); return void handleAuthenticatedMessage(Env, publicKey, msg, respond, Server); }); diff --git a/lib/stats.js b/lib/stats.js index 4a4fab916..3b5c334f4 100644 --- a/lib/stats.js +++ b/lib/stats.js @@ -45,6 +45,7 @@ Stats.instanceData = function (Env) { // we expect that you enable your support mailbox data.supportMailbox = Boolean(Env.supportMailbox); data.supportMailboxKey = Boolean(Env.supportMailboxKey); + data.supportMailboxKemKey = Boolean(Env.supportMailboxKemKey); // do you allow registration? data.restrictRegistration = Boolean(Env.restrictRegistration); diff --git a/lib/workers/db-worker.js b/lib/workers/db-worker.js index e9aa15e20..3712c5c1b 100644 --- a/lib/workers/db-worker.js +++ b/lib/workers/db-worker.js @@ -18,6 +18,7 @@ const Nacl = require('tweetnacl/nacl-fast'); const Eviction = require("../eviction"); const CPCrypto = require('../crypto'); const plugins = require("../plugin-manager"); +const ml_dsa = require('@noble/post-quantum/ml-dsa'); const Env = { Log: {}, @@ -783,8 +784,52 @@ COMMANDS.INLINE = function (data, cb) { } catch (e) { return void cb("E_BADKEY"); } - // validate the message - //const validated = Nacl.sign.open(signedMsg, validateKey); + + // Hybrid signature detection: [classical sig (64 bytes)] + [PQC sig length (4 bytes)] + [PQC sig] + [message] + if (signedMsg.length > 64 + 4) { + try { + // Parse hybrid signature + const classicalSig = signedMsg.slice(0, 64); + const pqSigLen = new DataView(signedMsg.buffer, signedMsg.byteOffset + 64, 4).getUint32(0, false); + const pqSig = signedMsg.slice(64 + 4, 64 + 4 + pqSigLen); + const message = signedMsg.slice(64 + 4 + pqSigLen); + + // Classical verification + const classicalVerified = Nacl.sign.detached.verify(message, classicalSig, validateKey); + + // PQC verification: get PQC public key from metadata if available + let pqcVerified = false; + let pqcPublicKey; + if (data.dsaPublic) { + try { + pqcPublicKey = Util.decodeBase64(data.dsaPublic); + } catch (e) { + return void cb("E_BAD_PQ_KEY"); + } + } else { + // If not provided, fail (could be extended to fetch from metadata) + return void cb("E_NO_PQ_KEY"); + } + try { + pqcVerified = ml_dsa.ml_dsa44.internal.verify( + pqcPublicKey, + message, + pqSig + ); + } catch (e) { + pqcVerified = false; + } + + if (!classicalVerified || !pqcVerified) { + return void cb("FAILED"); + } + return cb(); + } catch (e) { + return void cb("E_HYBRID_SIG_PARSE"); + } + } + + // Fallback: classical only const validated = Env.crypto.open(signedMsg, validateKey); if (!validated) { return void cb("FAILED"); diff --git a/lib/workers/index.js b/lib/workers/index.js index 81fba424f..1acdc665c 100644 --- a/lib/workers/index.js +++ b/lib/workers/index.js @@ -555,12 +555,14 @@ Workers.initialize = function (Env, config, _cb) { }; // Synchronous crypto functions - Env.validateMessage = function (signedMsg, key, cb) { - sendCommand({ - msg: signedMsg, - key: key, + Env.validateMessage = function (opts, cb) { + const cmd = { + msg: opts.msg, + key: opts.key, command: 'INLINE', - }, cb); + }; + if (opts.dsaPublic) cmd.dsaPublic = opts.dsaPublic; + sendCommand(cmd, cb); }; Env.checkSignature = function (signedMsg, signature, publicKey, cb) { diff --git a/package-lock.json b/package-lock.json index 7e5ef0f44..96a1747d8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "license": "AGPL-3.0+", "dependencies": { "@mcrowe/minibloom": "^0.2.0", + "@noble/post-quantum": "^0.4.1", "@node-saml/node-saml": "^4.0.5", "alertify.js": "1.0.11", "body-parser": "^1.20.2", @@ -517,6 +518,30 @@ "dev": true, "license": "CC0-1.0" }, + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/post-quantum": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@noble/post-quantum/-/post-quantum-0.4.1.tgz", + "integrity": "sha512-TRXjvnY9jAFNWbxOx+pKt21BNsCEWKFjMbIKwdx9CQXBudDanpY20EfOcooV7DIsRS/+Mf8D8utpUPjfGrQ8fA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@node-saml/node-saml": { "version": "4.0.5", "resolved": "https://registry.npmjs.org/@node-saml/node-saml/-/node-saml-4.0.5.tgz", diff --git a/package.json b/package.json index 4eb46a165..17d540e5c 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ }, "dependencies": { "@mcrowe/minibloom": "^0.2.0", + "@noble/post-quantum": "^0.4.1", "@node-saml/node-saml": "^4.0.5", "alertify.js": "1.0.11", "body-parser": "^1.20.2", @@ -89,7 +90,7 @@ "jquery": "3.6.0" }, "scripts": { - "install:components": "node scripts/copy-components.js", + "install:components": "node scripts/copy-components.js && node scripts/pqc-browser-convert.js", "start": "node server.js", "dev": "DEV=1 node server.js", "windev": "set DEV=1& node server.js", diff --git a/scripts/check-account-deletion.js b/scripts/check-account-deletion.js index 806c9d138..6ef62fa1c 100644 --- a/scripts/check-account-deletion.js +++ b/scripts/check-account-deletion.js @@ -4,7 +4,7 @@ const Fs = require('fs'); const nThen = require('nthen'); -const Nacl = require('tweetnacl/nacl-fast'); +const Crypto = require('chainpad-crypto/crypto'); const Path = require('path'); const Pins = require('../lib/pins'); const Util = require('../lib/common-util'); @@ -28,7 +28,7 @@ if (dataIdx === -1) { const ed = Util.decodeBase64(deleteData.toSign.edPublic); const signed = Util.decodeUTF8(JSON.stringify(deleteData.toSign)); const proof = Util.decodeBase64(deleteData.proof); - if (!Nacl.sign.detached.verify(signed, proof, ed)) { return void console.error("Invalid signature"); } + if (!Crypto.CryptoAgility.verifyDetached(signed, proof, ed)) { return void console.error("Invalid signature"); } edPublic = escapeKeyCharacters(deleteData.toSign.edPublic); } diff --git a/scripts/copy-components.js b/scripts/copy-components.js index 7d728156d..0e4ab39ac 100644 --- a/scripts/copy-components.js +++ b/scripts/copy-components.js @@ -47,7 +47,8 @@ Fse.rmSync(oldComponentsPath, { recursive: true, force: true }); "netflux-websocket", "drawio", "pako", - "x2js" + "x2js", + "@noble" ].forEach(l => { let s = l; if (s === 'tweetnacl') { diff --git a/scripts/generate-admin-keys.js b/scripts/generate-admin-keys.js index c33b2d41f..8e09affdb 100644 --- a/scripts/generate-admin-keys.js +++ b/scripts/generate-admin-keys.js @@ -2,10 +2,10 @@ // // SPDX-License-Identifier: AGPL-3.0-or-later -const Nacl = require('tweetnacl/nacl-fast'); +const Crypto = require('chainpad-crypto/crypto'); const Util = require('../lib/common-util'); -const keyPair = Nacl.box.keyPair(); +const keyPair = Crypto.CryptoAgility.curveKeyPair(); console.log("You've just generated a new key pair for your support mailbox."); console.log("The public key should first be added to your config.js file ('supportMailboxPublicKey'), then save and restart the server."); diff --git a/scripts/pqc-browser-convert.js b/scripts/pqc-browser-convert.js new file mode 100644 index 000000000..18a0a1139 --- /dev/null +++ b/scripts/pqc-browser-convert.js @@ -0,0 +1,76 @@ +// SPDX-FileCopyrightText: 2023 XWiki CryptPad Team and contributors +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +const { execSync } = require('child_process'); +const fs = require('fs/promises'); +const path = require('path'); + +// This content will be used for a temporary entry file for the bundle. +// It re-exports the necessary modules from the @noble/post-quantum package. +const entryPointContent = ` +export * as ml_kem from '@noble/post-quantum/ml-kem'; +export * as ml_dsa from '@noble/post-quantum/ml-dsa'; +export * as utils from '@noble/post-quantum/utils'; +`; + +async function main() { + try { + console.log('Temporarily installing esbuild...'); + execSync('npm install esbuild', { stdio: 'inherit' }); + + const esbuild = require('esbuild'); + + const outputDir = path.join('www', 'components', '@noble', 'post-quantum'); + const entryPointPath = path.join(outputDir, '_pqc_entry.js'); + const outfile = path.resolve(outputDir, 'index.js'); + + try { + await fs.mkdir(outputDir, { recursive: true }); + await fs.writeFile(entryPointPath, entryPointContent.trim()); + console.log('Bundling for browser with esbuild...'); + + await esbuild.build({ + entryPoints: [entryPointPath], + bundle: true, + outfile, + format: 'iife', + globalName: 'PostQuantum', + platform: 'browser', + minify: false, + sourcemap: true, + }); + + const amdLoader = `\nif (typeof define === 'function' && define.amd) { define([], function() { return window.PostQuantum; }); }`; + await fs.appendFile(outfile, amdLoader); + + console.log(`Bundle created successfully: ${outfile}`); + } finally { + // Clean up the temporary entry file + await fs.unlink(entryPointPath).catch(err => { + if (err.code !== 'ENOENT') { + console.error('Failed to remove temporary entry file:', err); + } + }); + } + } catch (e) { + console.error('An error occurred during the process:'); + console.error(e); + process.exit(1); + } finally { + console.log('Removing temporary esbuild dependency...'); + try { + execSync('npm uninstall esbuild', { stdio: 'inherit' }); + } catch (uninstallErr) { + console.error('Failed to uninstall esbuild. You may need to remove it manually.', uninstallErr); + } + } +} + +console.log('Starting PQ crypto browser conversion...'); + +main().then(() => { + console.log('PQ crypto browser conversion complete!'); +}).catch(() => { + process.exit(1); +}); diff --git a/scripts/testcrypto.js b/scripts/testcrypto.js index 0be5f6551..6aee16120 100644 --- a/scripts/testcrypto.js +++ b/scripts/testcrypto.js @@ -3,17 +3,17 @@ // SPDX-License-Identifier: AGPL-3.0-or-later let SodiumNative = require('sodium-native'); -let Nacl = require('tweetnacl/nacl-fast'); +let Crypto = require('chainpad-crypto/crypto'); let LibSodium = require('libsodium-wrappers'); let Util = require('../lib/common-util'); let msgStr = "This is a test"; -let keys = Nacl.sign.keyPair(); +let keys = Crypto.CryptoAgility.signKeyPair(); let pub = keys.publicKey; let msg = Util.decodeUTF8(msgStr); -let signedMsg = Nacl.sign(msg, keys.secretKey); +let signedMsg = Crypto.CryptoAgility.sign(msg, keys.secretKey); let sig = signedMsg.subarray(0, 64); LibSodium.ready.then(() => { @@ -57,8 +57,8 @@ console.log(LibSodium.crypto_sign_verify_detached(sig, msg, pub)); console.log('start tweetnacl'); a = +new Date(); for (let i = 0; i < n; i++) { - Nacl.sign.open(signedMsg, pub); - Nacl.sign.detached.verify(msg, sig, pub); + Crypto.CryptoAgility.signOpen(signedMsg, pub); + Crypto.CryptoAgility.verifyDetached(msg, sig, pub); } console.log('end tweetnacl ', (+new Date() - a), ' ms'); diff --git a/scripts/tests/test-lkh.js b/scripts/tests/test-lkh.js index 7edfecdcb..442641722 100644 --- a/scripts/tests/test-lkh.js +++ b/scripts/tests/test-lkh.js @@ -3,13 +3,13 @@ // SPDX-License-Identifier: AGPL-3.0-or-later var Client = require("../../lib/client"); -var Nacl = require("tweetnacl/nacl-fast"); var nThen = require("nthen"); var CPNetflux = require("../../www/components/chainpad-netflux/chainpad-netflux"); var Hash = require("../../www/common/common-hash"); var Util = require("../../lib/common-util"); var Rpc = require("../../www/common/rpc"); var HK = require("../../lib/hk-util"); +var Crypto = require("../../www/components/chainpad-crypto"); var identity = function (x) { @@ -70,7 +70,7 @@ nThen(function (w) { //console.log(i); if (i-- <= 0) { return void done(); } - var ciphertext = Util.encodeBase64(Nacl.randomBytes(256)); + var ciphertext = Util.encodeBase64(Crypto.CryptoAgility.bytes(256)); client.anonRpc.send('WRITE_PRIVATE_MESSAGE', [ client.channel, diff --git a/scripts/tests/test-rpc.js b/scripts/tests/test-rpc.js index e960f6c10..ed7f1953a 100644 --- a/scripts/tests/test-rpc.js +++ b/scripts/tests/test-rpc.js @@ -5,7 +5,6 @@ var Client = require("../../lib/client/"); var Crypto = require("../../www/components/chainpad-crypto"); var Mailbox = Crypto.Mailbox; -var Nacl = require("tweetnacl/nacl-fast"); var nThen = require("nthen"); var Pinpad = require("../../www/common/pinpad"); var Rpc = require("../../www/common/rpc"); @@ -41,7 +40,7 @@ process.on('unhandledRejection', function (err) { }); var makeCurveKeys = function () { - var pair = Nacl.box.keyPair(); + var pair = Crypto.CryptoAgility.curveKeyPair(); return { curvePrivate: Util.encodeBase64(pair.secretKey), curvePublic: Util.encodeBase64(pair.publicKey), @@ -49,7 +48,7 @@ var makeCurveKeys = function () { }; var makeEdKeys = function () { - var keys = Nacl.sign.keyPair.fromSeed(Nacl.randomBytes(Nacl.sign.seedLength)); + var keys = Crypto.CryptoAgility.signKeyPairFromSeed(Crypto.CryptoAgility.bytes(Crypto.CryptoAgility.signSeedLength())); return { edPrivate: Util.encodeBase64(keys.secretKey), edPublic: Util.encodeBase64(keys.publicKey), diff --git a/src/common/common-hash.js b/src/common/common-hash.js index 0eb4faa37..560e503fb 100644 --- a/src/common/common-hash.js +++ b/src/common/common-hash.js @@ -3,7 +3,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later (function (window) { -var factory = function (Util, Crypto, Keys, Nacl) { +var factory = function (Util, Crypto, Keys) { var Hash = window.CryptPad_Hash = {}; var uint8ArrayToHex = Util.uint8ArrayToHex; @@ -15,33 +15,52 @@ var factory = function (Util, Crypto, Keys, Nacl) { // This implementation must match that on the server // it's used for a checksum Hash.hashChannelList = function (list) { - return Util.encodeBase64(Nacl.hash(Util + return Util.encodeBase64(Crypto.CryptoAgility.createHash(Util .decodeUTF8(JSON.stringify(list)))); }; Hash.generateSignPair = function () { - var ed = Nacl.sign.keyPair(); + // Generate classical Ed25519 keypair + var ed = Crypto.CryptoAgility.signKeyPair(); var makeSafe = function (key) { return Crypto.b64RemoveSlashes(key).replace(/=+$/g, ''); }; - return { + + var result = { validateKey: Hash.encodeBase64(ed.publicKey), signKey: Hash.encodeBase64(ed.secretKey), safeValidateKey: makeSafe(Hash.encodeBase64(ed.publicKey)), safeSignKey: makeSafe(Hash.encodeBase64(ed.secretKey)), }; + + // Add post-quantum DSA keypair if available + if (Crypto.PQC && Crypto.PQC.ml_dsa && Crypto.PQC.ml_dsa.ml_dsa44) { + try { + // Derive a deterministic seed from the Ed25519 secret key + var dsaSeed = Crypto.Nacl.hash(ed.secretKey).subarray(0, 32); + var dsaPair = Crypto.CryptoAgility.generateDsaKeypair(dsaSeed); + result.dsaPublic = Hash.encodeBase64(dsaPair.publicKey); + result.dsaPrivate = Hash.encodeBase64(dsaPair.secretKey); + result.safeDsaPublic = makeSafe(Hash.encodeBase64(dsaPair.publicKey)); + result.safeDsaPrivate = makeSafe(Hash.encodeBase64(dsaPair.secretKey)); + } catch (err) { + console.error("Failed to generate post-quantum DSA keys:", err); + } + } + + return result; }; Hash.getSignPublicFromPrivate = function (edPrivateSafeStr) { var edPrivateStr = Crypto.b64AddSlashes(edPrivateSafeStr); var privateKey = Util.decodeBase64(edPrivateStr); - var keyPair = Nacl.sign.keyPair.fromSecretKey(privateKey); + var keyPair = Crypto.CryptoAgility.signKeyPairFromSecretKey(privateKey); return Util.encodeBase64(keyPair.publicKey); }; Hash.getCurvePublicFromPrivate = function (curvePrivateSafeStr) { var curvePrivateStr = Crypto.b64AddSlashes(curvePrivateSafeStr); var privateKey = Util.decodeBase64(curvePrivateStr); - var keyPair = Nacl.box.keyPair.fromSecretKey(privateKey); + var keyPair = Crypto.CryptoAgility.boxKeyPairFromSecretKey(privateKey); return Util.encodeBase64(keyPair.publicKey); }; @@ -117,7 +136,7 @@ var factory = function (Util, Crypto, Keys, Nacl) { Hash.ephemeralChannelLength = 34; Hash.createChannelId = function (ephemeral) { - var id = uint8ArrayToHex(Crypto.Nacl.randomBytes(ephemeral? 17: 16)); + var id = uint8ArrayToHex(Crypto.CryptoAgility.bytes(ephemeral? 17: 16)); if ([32, 34].indexOf(id.length) === -1 || /[^a-f0-9]/.test(id)) { throw new Error('channel ids must consist of 32 hex characters'); } @@ -138,7 +157,7 @@ var factory = function (Util, Crypto, Keys, Nacl) { Hash.getBoxPublicFromSecret = function (priv) { if (!priv) { return; } var u8_priv = Hash.decodeBase64(priv); - var pair = Nacl.box.keyPair.fromSecretKey(u8_priv); + var pair = Crypto.CryptoAgility.boxKeyPairFromSecretKey(u8_priv); return Hash.encodeBase64(pair.publicKey); }; @@ -148,7 +167,7 @@ var factory = function (Util, Crypto, Keys, Nacl) { Hash.checkBoxKeyPair = function (priv, pub) { if (!pub || !priv) { return false; } var u8_priv = Hash.decodeBase64(priv); - var pair = Nacl.box.keyPair.fromSecretKey(u8_priv); + var pair = Crypto.CryptoAgility.boxKeyPairFromSecretKey(u8_priv); return pub === Hash.encodeBase64(pair.publicKey); }; @@ -653,7 +672,7 @@ Version 4: Data URL when not a realtime link yet (new pad or "static" app) var keys = secret && secret.keys; var secondary = keys && keys.secondaryKey; if (!secondary) { return; } - var curvePair = Nacl.box.keyPair.fromSecretKey(Util.decodeUTF8(secondary).slice(0,32)); + var curvePair = Crypto.CryptoAgility.boxKeyPairFromSecretKey(Util.decodeUTF8(secondary).slice(0,32)); var ret = {}; ret.form_public = Util.encodeBase64(curvePair.publicKey); var privateKey = ret.form_private = Util.encodeBase64(curvePair.secretKey); diff --git a/src/common/common-util.js b/src/common/common-util.js index c48bf809f..23b9eaa93 100644 --- a/src/common/common-util.js +++ b/src/common/common-util.js @@ -3,21 +3,18 @@ // SPDX-License-Identifier: AGPL-3.0-or-later (function (window) { -const factory = (NaclUtil) => { +const factory = (Crypto) => { var Util = window.CryptPad_Util = {}; // polyfill for atob in case you're using this from node... window.atob = window.atob || function (str) { return Buffer.from(str, 'base64').toString('binary'); }; window.btoa = window.btoa || function (str) { return Buffer.from(str, 'binary').toString('base64'); }; - Util.encodeBase64 = NaclUtil.encodeBase64; - Util.decodeBase64 = str => { - let i = str.length % 4; - if (i) { str += '='.repeat(4-i); } - return NaclUtil.decodeBase64(str); - }; - Util.encodeUTF8 = NaclUtil.encodeUTF8; - Util.decodeUTF8 = NaclUtil.decodeUTF8; + Util.encodeBase64 = Crypto.CryptoAgility.encodeBase64; + Util.decodeBase64 = Crypto.CryptoAgility.decodeBase64; + + Util.encodeUTF8 = Crypto.CryptoAgility.encodeUTF8; + Util.decodeUTF8 = Crypto.CryptoAgility.decodeUTF8; Util.slice = function (A, start, end) { return Array.prototype.slice.call(A, start, end); @@ -871,10 +868,10 @@ const factory = (NaclUtil) => { }; if (typeof(module) !== 'undefined' && module.exports) { - module.exports = factory(require('tweetnacl-util')); + module.exports = factory(require('chainpad-crypto/crypto')); } else if ((typeof(define) !== 'undefined' && define !== null) && (define.amd !== null)) { - define(['/components/tweetnacl-util/nacl-util.min.js'], function () { - return factory(globalThis?.nacl?.util); + define(['/components/chainpad-crypto/crypto.js'], function (Crypto) { + return factory(Crypto); }); } else { // Unsupported initialization diff --git a/src/common/outer/http-command.js b/src/common/outer/http-command.js index 19839469d..bf2ceefaf 100644 --- a/src/common/outer/http-command.js +++ b/src/common/outer/http-command.js @@ -3,7 +3,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later (() => { -const factory = (nThen, Util, ApiConfig = {}, Nacl) => { +const factory = (nThen, Util, ApiConfig = {}, Nacl, Crypto) => { const getApiOrigin = function () { if (!Object.keys(ApiConfig).length) { return; } @@ -26,7 +26,7 @@ const factory = (nThen, Util, ApiConfig = {}, Nacl) => { }; var clone = o => JSON.parse(JSON.stringify(o)); - var randomToken = () => Util.encodeBase64(Nacl.randomBytes(24)); + var randomToken = () => Util.encodeBase64(Crypto.CryptoAgility.bytes(24)); var postData = function (url, data, cb) { var CB = Util.once(Util.mkAsync(cb)); fetch(url, { @@ -83,7 +83,7 @@ const factory = (nThen, Util, ApiConfig = {}, Nacl) => { copy.txid = txid; copy.date = date; var toSign = Util.decodeUTF8(JSON.stringify(copy)); - var sig = Nacl.sign.detached(toSign, keypair.secretKey); + var sig = Crypto.CryptoAgility.signDetached(toSign, keypair.secretKey); var encoded = Util.encodeBase64(sig); var obj2 = { sig: encoded, @@ -112,7 +112,8 @@ if (typeof(module) !== 'undefined' && module.exports) { require('nthen'), require('../common-util'), undefined, - require('tweetnacl/nacl-fast') + require('tweetnacl/nacl-fast'), + require('chainpad-crypto/crypto') ); } else if ((typeof(define) !== 'undefined' && define !== null) && (define.amd !== null)) { define([ @@ -120,8 +121,9 @@ if (typeof(module) !== 'undefined' && module.exports) { '/common/common-util.js', '/api/config', '/components/tweetnacl/nacl-fast.min.js', - ], (nThen, Util, ApiConfig) => { - return factory(nThen, Util, ApiConfig, window.nacl); + '/components/chainpad-crypto/crypto.js', + ], (nThen, Util, ApiConfig, Nacl, Crypto) => { + return factory(nThen, Util, ApiConfig, window.nacl, Crypto); }); } else { // unsupported initialization diff --git a/src/common/outer/login-block.js b/src/common/outer/login-block.js index 312e8b7e2..7201a83fc 100644 --- a/src/common/outer/login-block.js +++ b/src/common/outer/login-block.js @@ -3,7 +3,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later (() => { -const factory = (Util, ApiConfig = {}, ServerCommand, Nacl) => { +const factory = (Util, ApiConfig = {}, ServerCommand, Nacl, Crypto) => { var Block = {}; @@ -23,7 +23,7 @@ const factory = (Util, ApiConfig = {}, ServerCommand, Nacl) => { // [b64_public, b64_sig, b64_block [version, nonce, content]] Block.seed = function () { - return Nacl.hash(Util.decodeUTF8('pewpewpew')); + return Crypto.CryptoAgility.createHash(Util.decodeUTF8('pewpewpew')); }; // should be deterministic from a seed... @@ -35,23 +35,54 @@ const factory = (Util, ApiConfig = {}, ServerCommand, Nacl) => { throw new Error('INVALID_SEED_LENGTH'); } - var signSeed = seed.subarray(0, Nacl.sign.seedLength); - var symmetric = seed.subarray(Nacl.sign.seedLength, - Nacl.sign.seedLength + Nacl.secretbox.keyLength); + var signSeed = seed.subarray(0, Crypto.CryptoAgility.signSeedLength()); + var symmetric = seed.subarray(Crypto.CryptoAgility.signSeedLength(), + Crypto.CryptoAgility.signSeedLength() + Crypto.CryptoAgility.secretboxKeyLength()); + + // Generate standard keys using the existing method + var sign = Crypto.CryptoAgility.signKeyPairFromSeed(signSeed); + + // Store the post-quantum keys separately for future use (no server validation issues) + var pqSignPair = null; + var hybridCapable = !!Crypto.PQC && !!Crypto.PQC.ml_dsa; + + if (hybridCapable) { + try { + // Use separate seed for PQ keys derived from original seed + // ML-DSA requires a 32-byte seed, so we hash the seed to get a consistent 32-byte value + var pqSeed = Nacl.hash(seed).subarray(0, 32); + + // Generate post-quantum keypair using the 32-byte hash + pqSignPair = Crypto.CryptoAgility.generateDsaKeypair(pqSeed); + } catch (err) { + console.error("Failed to generate post-quantum keys:", err); + pqSignPair = null; + } + } return { - sign: Nacl.sign.keyPair.fromSeed(signSeed), // 32 bytes - symmetric: symmetric, // 32 bytes ... + sign: sign, + pqSignPair: pqSignPair, + symmetric: symmetric, + // Store whether we have post-quantum capability + hasPQ: pqSignPair !== null }; }; Block.keysToRPCFormat = function (keys) { try { var sign = keys.sign; - return { + var pqSignPair = keys.pqSignPair; + + // Basic format with classical and pqc keys + var result = { edPrivate: Util.encodeBase64(sign.secretKey), edPublic: Util.encodeBase64(sign.publicKey), + dsaPrivate: Util.encodeBase64(pqSignPair.secretKey), + dsaPublic: Util.encodeBase64(pqSignPair.publicKey), }; + + return result; } catch (err) { console.error(err); return; @@ -61,21 +92,23 @@ const factory = (Util, ApiConfig = {}, ServerCommand, Nacl) => { // (UTF8 content, keys object) => Uint8Array block Block.encrypt = function (version, content, keys) { var u8 = Util.decodeUTF8(content); - var nonce = Nacl.randomBytes(Nacl.secretbox.nonceLength); + var nonce = Crypto.CryptoAgility.bytes(Crypto.CryptoAgility.secretboxNonceLength()); return Block.join([ [0], nonce, - Nacl.secretbox(u8, nonce, keys.symmetric) + Crypto.CryptoAgility.secretbox(u8, nonce, keys.symmetric) ]); }; // (uint8Array block) => payload object + // src/common/outer/login-block.js Block.decrypt = function (u8_content, keys) { // version is currently ignored since there is only one - var nonce = u8_content.subarray(1, 1 + Nacl.secretbox.nonceLength); - var box = u8_content.subarray(1 + Nacl.secretbox.nonceLength); + var nonceLength = Crypto.CryptoAgility.secretboxNonceLength(); + var nonce = u8_content.subarray(1, 1 + nonceLength); + var box = u8_content.subarray(1 + nonceLength); - var plaintext = Nacl.secretbox.open(box, nonce, keys.symmetric); + var plaintext = Crypto.CryptoAgility.secretboxOpen(box, nonce, keys.symmetric); try { return JSON.parse(Util.encodeUTF8(plaintext)); } catch (e) { @@ -86,7 +119,43 @@ const factory = (Util, ApiConfig = {}, ServerCommand, Nacl) => { // (Uint8Array block) => signature Block.sign = function (ciphertext, keys) { - return Nacl.sign.detached(Nacl.hash(ciphertext), keys.sign.secretKey); + var hash = Crypto.CryptoAgility.createHash(ciphertext); + + // Generate hybrid signature if post-quantum capabilities are available + if (keys.hasPQ && keys.pqSignPair) { + try { + // Generate classical signature (always required for server compatibility) + var classicalSig = Crypto.CryptoAgility.signDetached(hash, keys.sign.secretKey); + + // Generate post-quantum signature + var pqSig = Crypto.PQC.ml_dsa.ml_dsa44.internal.sign(keys.pqSignPair.secretKey, hash); + + console.log("Hybrid signature created successfully:"); + // Create a hybrid signature with format: + // [1-byte type][64-byte classical sig][4-byte PQ sig length][PQ sig bytes] + var hybridSig = new Uint8Array(1 + classicalSig.length + 4 + pqSig.length); + hybridSig[0] = 1; // Type 1 indicates hybrid signature + hybridSig.set(classicalSig, 1); + + // Set PQ signature length as 4-byte integer (big endian) + var view = new DataView(hybridSig.buffer); + view.setUint32(1 + classicalSig.length, pqSig.length, false); + + // Add the PQ signature + hybridSig.set(pqSig, 1 + classicalSig.length + 4); + + return hybridSig; + } catch (e) { + console.error("PQ signing failed, falling back to classical:", e); + } + } + + // Classical signature with a type marker + classicalSig = Crypto.CryptoAgility.signDetached(hash, keys.sign.secretKey); + var taggedSig = new Uint8Array(classicalSig.length + 1); + taggedSig[0] = 0; // Type 0 indicates classical only + taggedSig.set(classicalSig, 1); + return taggedSig; }; Block.serialize = function (content, keys) { @@ -97,21 +166,29 @@ const factory = (Util, ApiConfig = {}, ServerCommand, Nacl) => { var sig = Block.sign(ciphertext, keys); // serialize {publickey, sig, ciphertext} - return { + var result = { publicKey: Util.encodeBase64(keys.sign.publicKey), + pqPublicKey: Util.encodeBase64(keys.pqSignPair.publicKey), signature: Util.encodeBase64(sig), ciphertext: Util.encodeBase64(ciphertext), }; + + return result; }; Block.proveAncestor = function (O /* oldBlockKeys, N, newBlockKeys */) { var u8_pub = Util.find(O, ['sign', 'publicKey']); - var u8_secret = Util.find(O, ['sign', 'secretKey']); try { - // sign your old publicKey with your old privateKey - var u8_sig = Nacl.sign.detached(u8_pub, u8_secret); - // return an array with the sig and the pubkey - return JSON.stringify([u8_pub, u8_sig].map(Util.encodeBase64)); + // Use Block.sign to create a hybrid signature if available + var hybridSig = Block.sign(u8_pub, O); + let result = [u8_pub, hybridSig].map(Util.encodeBase64); + + if (O.pqSignPair && O.pqSignPair.publicKey) { + result.push(Util.encodeBase64(O.pqSignPair.publicKey)); + } + + // Return an array with the signature and the pubkey + return JSON.stringify(result); } catch (err) { return void console.error(err); } @@ -122,6 +199,7 @@ const factory = (Util, ApiConfig = {}, ServerCommand, Nacl) => { }; Block.getBlockUrl = function (keys) { + // Use classical keys for backward compatibility with URL structure var publicKey = urlSafeB64(keys.sign.publicKey); // 'block/' here is hardcoded because it's hardcoded on the server // if we want to make CryptPad work in server subfolders, we'll need @@ -172,9 +250,10 @@ const factory = (Util, ApiConfig = {}, ServerCommand, Nacl) => { ServerCommand(blockKeys.sign, { command: command, - auth: auth && auth.data + auth: auth && auth.data, }, cb); }; + Block.writeLoginBlock = function (data, cb) { const { content, blockKeys, oldBlockKeys, auth, pw, session, token, userData } = data; @@ -191,9 +270,10 @@ const factory = (Util, ApiConfig = {}, ServerCommand, Nacl) => { ServerCommand(blockKeys.sign, { command: command, content: block, - session: session // sso session + session: session, // sso session }, cb); }; + Block.removeLoginBlock = function (data, cb) { const { reason, blockKeys, auth, edPublic } = data; @@ -204,7 +284,7 @@ const factory = (Util, ApiConfig = {}, ServerCommand, Nacl) => { command: command, auth: auth && auth.data, edPublic: edPublic, - reason: reason + reason: reason, }, cb); }; @@ -214,7 +294,7 @@ const factory = (Util, ApiConfig = {}, ServerCommand, Nacl) => { ServerCommand(blockKeys.sign, { command: 'SSO_UPDATE_BLOCK', - ancestorProof: oldProof + ancestorProof: oldProof, }, cb); }; @@ -227,7 +307,8 @@ if (typeof(module) !== 'undefined' && module.exports) { require('../common-util'), undefined, require('./http-command'), - require('tweetnacl/nacl-fast') + require('tweetnacl/nacl-fast'), + require('chainpad-crypto/crypto') ); } else if ((typeof(define) !== 'undefined' && define !== null) && (define.amd !== null)) { define([ @@ -235,8 +316,9 @@ if (typeof(module) !== 'undefined' && module.exports) { '/api/config', '/common/outer/http-command.js', '/components/tweetnacl/nacl-fast.min.js', - ], (Util, ApiConfig, ServerCommand) => { - return factory(Util, ApiConfig, ServerCommand, window.nacl); + '/components/chainpad-crypto/crypto.js', + ], (Util, ApiConfig, ServerCommand, Nacl, Crypto) => { + return factory(Util, ApiConfig, ServerCommand, window.nacl, Crypto); }); } else { // unsupported initialization diff --git a/src/common/rpc.js b/src/common/rpc.js index d95949bf2..e3a2a746c 100644 --- a/src/common/rpc.js +++ b/src/common/rpc.js @@ -3,7 +3,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later (function () { -var factory = function (Util, Nacl) { +var factory = function (Util, Nacl, Crypto) { // we will send messages with a unique id for each RPC // that id is returned with each response, indicating which call it was in response to var uid = Util.uid; @@ -15,7 +15,7 @@ var factory = function (Util, Nacl) { // this handles that in a generic way var signMsg = function (data, signKey) { var buffer = Util.decodeUTF8(JSON.stringify(data)); - return Util.encodeBase64(Nacl.sign.detached(buffer, signKey)); + return Util.encodeBase64(Crypto.CryptoAgility.signDetached(buffer, signKey)); }; // sendMsg takes a pre-formed message, does a little validation @@ -264,6 +264,8 @@ var factory = function (Util, Nacl) { clearTimeout(to); }); + ctx.send('DESTROY', "", function () {}); + // remove the ctx from the network's stack var idx = networkContext.authenticated.indexOf(ctx); if (idx === -1) { return; } @@ -408,13 +410,14 @@ var factory = function (Util, Nacl) { }; if (typeof(module) !== 'undefined' && module.exports) { - module.exports = factory(require("./common-util"), require("tweetnacl/nacl-fast")); + module.exports = factory(require("./common-util"), require("tweetnacl/nacl-fast"), require("chainpad-crypto/crypto")); } else if ((typeof(define) !== 'undefined' && define !== null) && (define.amd !== null)) { define([ '/common/common-util.js', '/components/tweetnacl/nacl-fast.min.js', - ], function (Util) { - return factory(Util, window.nacl); + '/components/chainpad-crypto/crypto.js' + ], function (Util, Nacl, Crypto) { + return factory(Util, window.nacl, Crypto); }); } else { // I'm not gonna bother supporting any other kind of instanciation diff --git a/src/worker/async-store.js b/src/worker/async-store.js index f1e388ab1..32c9d2589 100644 --- a/src/worker/async-store.js +++ b/src/worker/async-store.js @@ -25,6 +25,7 @@ const factory = (Sortify, UserObject, ProxyManager, const Saferphore = Util.Saferphore; var onReadyEvt = Util.mkEvent(true); var onCacheReadyEvt = Util.mkEvent(true); + var onDriveReadyEvt = Util.mkEvent(true); var onPadRejectedEvt = Util.mkEvent(true); const setCustomize = data => { @@ -422,8 +423,8 @@ const factory = (Sortify, UserObject, ProxyManager, var initTempRpc = (clientId, cb) => { if (store.rpc) { return void cb(store.rpc); } - var kp = Crypto.Nacl.sign.keyPair(); - var keys = store.tempKeys = { + var kp = Crypto.CryptoAgility.signKeyPair(); + var keys = { edPublic: Util.encodeBase64(kp.publicKey), edPrivate: Util.encodeBase64(kp.secretKey) }; @@ -586,7 +587,9 @@ const factory = (Sortify, UserObject, ProxyManager, color: Store.getUserColor(), notifications: Util.find(proxy, ['mailboxes', 'notifications', 'channel']), curvePublic: proxy.curvePublic, + kemPublic: proxy.kemPublic, edPublic: proxy.edPublic, + dsaPublic: proxy.dsaPublic, netfluxId: store?.network?.webChannels?.[0]?.myID, badge: Util.find(proxy, ['profile', 'badge']) }, @@ -595,6 +598,8 @@ const factory = (Sortify, UserObject, ProxyManager, clientId: clientId, edPublic: proxy.edPublic, edPrivate: proxy.edPrivate, + dsaPublic: proxy.dsaPublic, + dsaPrivate: proxy.dsaPrivate, friends: proxy.friends || {}, settings: proxy.settings || NEW_USER_SETTINGS, thumbnails: disableThumbnails === false, @@ -881,7 +886,7 @@ const factory = (Sortify, UserObject, ProxyManager, toSign.drive = store.driveChannel; toSign.edPublic = edPublic; var signKey = Util.decodeBase64(store.proxy.edPrivate); - var proof = Crypto.Nacl.sign.detached(Util.decodeUTF8(Sortify(toSign)), signKey); + var proof = Crypto.CryptoAgility.signDetached(Util.decodeUTF8(Sortify(toSign)), signKey); var check = Crypto.Nacl.sign.detached.verify(Util.decodeUTF8(Sortify(toSign)), proof, @@ -1608,7 +1613,7 @@ const factory = (Sortify, UserObject, ProxyManager, if (!Array.isArray(allowed)) { return void cb('ERESTRICTED'); } onPadRejectedEvt.fire(); - onReadyEvt.reg(() => { + onDriveReadyEvt.reg(() => { // There is an allow list: check if we can authenticate if (!store.loggedIn || !store.proxy.edPublic) { return void cb('ERESTRICTED'); } @@ -1782,7 +1787,7 @@ const factory = (Sortify, UserObject, ProxyManager, if (!channel || !ownerKey) { return void console.error("Can't delete BAR pad"); } try { var signKey = Hash.decodeBase64(ownerKey); - var pair = Crypto.Nacl.sign.keyPair.fromSecretKey(signKey); + var pair = Crypto.CryptoAgility.signKeyPairFromSecretKey(signKey); Pinpad.create(store.network, { edPublic: Hash.encodeBase64(pair.publicKey), edPrivate: Hash.encodeBase64(pair.secretKey) @@ -2570,6 +2575,7 @@ const factory = (Sortify, UserObject, ProxyManager, cacheCb(store.cacheReturned || store.returned); }); onDriveReady(() => { + onDriveReadyEvt.fire(); cb(store.returned); }); diff --git a/src/worker/components/invitation.js b/src/worker/components/invitation.js index 0424809e5..da671542b 100644 --- a/src/worker/components/invitation.js +++ b/src/worker/components/invitation.js @@ -10,21 +10,30 @@ var factory = function (Util, Cred, Nacl, Crypto) { // ed and curve keys can be random... Invite.generateKeys = function () { - var ed = Nacl.sign.keyPair(); - var curve = Nacl.box.keyPair(); + var ed = Crypto.CryptoAgility.signKeyPair(); + var curve = Crypto.CryptoAgility.curveKeyPair(); + var kem = Crypto.CryptoAgility.generateKemKeypair(); + var dsa = Crypto.CryptoAgility.generateDsaKeypair(); return { edPublic: encode64(ed.publicKey), edPrivate: encode64(ed.secretKey), curvePublic: encode64(curve.publicKey), curvePrivate: encode64(curve.secretKey), + kemPublic: encode64(kem.publicKey), + kemPrivate: encode64(kem.secretKey), + dsaPublic: encode64(dsa.publicKey), + dsaPrivate: encode64(dsa.secretKey), }; }; Invite.generateSignPair = function () { - var ed = Nacl.sign.keyPair(); + var ed = Crypto.CryptoAgility.signKeyPair(); + var dsa = Crypto.CryptoAgility.generateKemKeypair(); return { validateKey: encode64(ed.publicKey), signKey: encode64(ed.secretKey), + dsaPublic: encode64(dsa.publicKey), + dsaPrivate: encode64(dsa.secretKey), }; }; @@ -32,7 +41,7 @@ var factory = function (Util, Cred, Nacl, Crypto) { var dispense = Cred.dispenser(decode64(b64)); return { channel: Util.uint8ArrayToHex(dispense(16)), - cryptKey: dispense(Nacl.secretbox.keyLength), + cryptKey: dispense(Crypto.CryptoAgility.secretboxKeyLength()), }; }; @@ -58,13 +67,13 @@ var factory = function (Util, Cred, Nacl, Crypto) { var decodeUTF8 = Util.decodeUTF8; Invite.encryptHash = function (data, seedStr) { var array = decodeUTF8(seedStr); - var bytes = Nacl.hash(array); + var bytes = Crypto.CryptoAgility.createHash(array); var cryptKey = bytes.subarray(0, 32); return Crypto.encrypt(data, cryptKey); }; Invite.decryptHash = function (encryptedStr, seedStr) { var array = decodeUTF8(seedStr); - var bytes = Nacl.hash(array); + var bytes = Crypto.CryptoAgility.createHash(array); var cryptKey = bytes.subarray(0, 32); return Crypto.decrypt(encryptedStr, cryptKey); }; diff --git a/src/worker/components/messaging.js b/src/worker/components/messaging.js index b286bfe1a..7a14378e4 100644 --- a/src/worker/components/messaging.js +++ b/src/worker/components/messaging.js @@ -5,13 +5,35 @@ const factory = (Crypto, Hash, Util, Constants, Realtime) => { var Msg = {}; + /* + * CRYPTOGRAPHIC IDENTITY NOTE: + * + * Throughout this module and the entire CryptPad application, we continue to use + * curve25519 public keys (curvePublic) as the primary identifier for users despite + * having post-quantum cryptography (PQC) keys (kemPublic) available. + * + * 1. Legacy compatibility: A complete migration to PQC for identification would require + * changing all existing user relationships and channels + * + * 2. System integration: The curvePublic key is deeply integrated into friend relationships, + * channel management, history keeper, and other core components + * + * 3. Risk management: Partially migrating identity systems can lead to inconsistencies + * across the application, potentially creating security vulnerabilities + * + * A future coordinated migration will be necessary to fully replace curve25519 with PQC, + * which will require careful planning to ensure all components are updated simultaneously. + */ + var createData = Msg.createData = function (proxy, hash) { var data = { channel: hash || Hash.createChannelId(), displayName: proxy['cryptpad.username'], profile: proxy.profile && proxy.profile.view, edPublic: proxy.edPublic, - curvePublic: proxy.curvePublic, + curvePublic: proxy.curvePublic, // Still used as primary ID throughout the system + dsaPublic: proxy.dsaPublic, + kemPublic: proxy.kemPublic, // PQC key available but not used as primary ID yet notifications: Util.find(proxy, ['mailboxes', 'notifications', 'channel']), avatar: proxy.profile && proxy.profile.avatar, badge: proxy.profile && proxy.profile.badge, @@ -21,6 +43,8 @@ const factory = (Crypto, Hash, Util, Constants, Realtime) => { return data; }; + // Friend lookup still uses curvePublic as the key - changing this would require + // migrating all existing friendship relationships and updating all related code var getFriend = Msg.getFriend = function (proxy, pubkey) { if (!pubkey) { return; } if (pubkey === proxy.curvePublic) { diff --git a/src/worker/components/migrate-user-object.js b/src/worker/components/migrate-user-object.js index a6d71cbe2..e627563ed 100644 --- a/src/worker/components/migrate-user-object.js +++ b/src/worker/components/migrate-user-object.js @@ -297,7 +297,7 @@ const factory = (Feedback, Hash, Util, * 3.b. No ==> post our mailbox data to the messenger channel */ network.join(friend.channel).then(function (wc) { - var keys = Crypto.Curve.deriveKeys(friend.curvePublic, userObject.curvePrivate); + var keys = Crypto.Curve.deriveKeys(friend.curvePublic, userObject.curvePrivate, friend.kemPublic, userObject.kemPublic); var encryptor = Crypto.Curve.createEncryptor(keys); channels[friend.channel] = { wc: wc, diff --git a/src/worker/components/roster.js b/src/worker/components/roster.js index 198b37f3c..85c3f226e 100644 --- a/src/worker/components/roster.js +++ b/src/worker/components/roster.js @@ -730,10 +730,6 @@ var factory = function (Util, Hash, CPNetflux, Sortify, nThen, Crypto) { var ciphertext = crypto.encrypt(Sortify(msg)); var id = getMessageId(ciphertext); - - //console.log("Sending with id [%s]", id, msg); - //console.log(); - response.expect(id, function (err, state) { if (err) { return void cb(err); } cb(void 0, state, id); @@ -879,8 +875,19 @@ var factory = function (Util, Hash, CPNetflux, Sortify, nThen, Crypto) { w.abort(); return void cb("NO_VALIDATE_KEY"); } + if (!config.keys.teamKemPublic && metadata.kemPublic) { + config.keys.teamKemPublic = metadata.kemPublic; + } + if (!config.keys.teamDsaPublic && metadata.dsaPublic) { + config.keys.teamDsaPublic = metadata.dsaPublic; + } + if (!config.keys.teamKemPublic && !config.keys.teamDsaPublic) { + w.abort(); + return void cb("NO_PQC_KEYS"); + } try { + // Crypto.Team.createEncryptor now supports PQC keys crypto = Crypto.Team.createEncryptor(config.keys); } catch (err) { w.abort(); @@ -903,6 +910,7 @@ var factory = function (Util, Hash, CPNetflux, Sortify, nThen, Crypto) { crypto: crypto, validateKey: config.keys.teamEdPublic, + dsaValidateKey: config.keys.teamDsaPublic, // PQC validation key for ML-DSA owners: config.owners, diff --git a/src/worker/modules/integration.js b/src/worker/modules/integration.js index ac733cfcd..e691dc8d4 100644 --- a/src/worker/modules/integration.js +++ b/src/worker/modules/integration.js @@ -24,7 +24,16 @@ const factory = (Crypto) => { msg: data.msg, uid: data.uid, }; - chan.sendMsg(JSON.stringify(obj), cb); + if (obj.msg === 'ISAVE') { + ctx.pending[data.uid] = true; + } + chan.sendMsg(JSON.stringify(obj), obj => { + if (!ctx.pending[data.uid]) { + return void setTimeout(cb, 1000); + } + delete ctx.pending[data.uid]; + cb(obj); + }); ctx.emit('MESSAGE', obj, chan.clients.filter(function (cl) { return cl !== client; })); @@ -90,6 +99,9 @@ const factory = (Crypto) => { var parsed; try { parsed = JSON.parse(msg); + if (parsed.msg === "ISAVE") { + delete ctx.pending[parsed.uid]; + } ctx.emit('MESSAGE', parsed, chan.clients); } catch (e) { console.error(e); } }); @@ -176,6 +188,7 @@ const factory = (Crypto) => { store: cfg.store, emit: emit, channels: {}, + pending: {}, // prevent ISAVE race condition clients: {} }; diff --git a/src/worker/modules/mailbox.js b/src/worker/modules/mailbox.js index 1c0a5e10b..817753ba0 100644 --- a/src/worker/modules/mailbox.js +++ b/src/worker/modules/mailbox.js @@ -78,10 +78,12 @@ proxy.mailboxes = { var getMyKeys = function (ctx) { var proxy = ctx.store && ctx.store.proxy; - if (!proxy.curvePrivate || !proxy.curvePublic) { return; } + if (!proxy.curvePrivate || !proxy.curvePublic || !proxy.kemPublic || !proxy.kemPrivate) { return; } return { curvePrivate: proxy.curvePrivate, - curvePublic: proxy.curvePublic + curvePublic: proxy.curvePublic, + kemPrivate: proxy.kemPrivate, + kemPublic: proxy.kemPublic }; }; @@ -130,7 +132,10 @@ proxy.mailboxes = { } var text = JSON.stringify(obj); - var ciphertext = crypto.encrypt(text, user.curvePublic); + var ciphertext = crypto.encrypt(text, user.curvePublic, user.kemPublic); + + // const bytes = Crypto.CryptoAgility.decodeBase64(ciphertext); + // if (bytes[0] !== 1) throw new Error("PQC not used for encryption"); // If we've sent this message to one of our teams' mailbox, we may want to "dismiss" it // automatically @@ -158,17 +163,42 @@ proxy.mailboxes = { }); }; Mailbox.sendToAnon = function (anonRpc, type, msg, user, cb) { - var Nacl = Crypto.Nacl; - var curveSeed = Nacl.randomBytes(32); - var curvePair = Nacl.box.keyPair.fromSecretKey(new Uint8Array(curveSeed)); + var curveSeed = Crypto.CryptoAgility.bytes(32); + var curvePair = Crypto.CryptoAgility.boxKeyPairFromSecretKey(new Uint8Array(curveSeed)); var curvePrivate = Util.encodeBase64(curvePair.secretKey); var curvePublic = Util.encodeBase64(curvePair.publicKey); + + // Generate ephemeral PQC keys if PQC is available + var kemPrivate, kemPublic; + if (Crypto.PQC && Crypto.PQC.ml_kem && Crypto.PQC.ml_kem.ml_kem512) { + try { + var kemSeed = Crypto.CryptoAgility.bytes(64); + var kemPair = Crypto.PQC.ml_kem.ml_kem512.keygen(new Uint8Array(kemSeed)); + kemPrivate = Util.encodeBase64(kemPair.secretKey); + kemPublic = Util.encodeBase64(kemPair.publicKey); + } catch (e) { + console.warn('Failed to generate ephemeral PQC keys:', e); + } + } + + var proxyData = { + curvePrivate: curvePrivate, + curvePublic: curvePublic + }; + + if (kemPrivate && kemPublic) { + proxyData.kemPrivate = kemPrivate; + proxyData.kemPublic = kemPublic; + } + sendTo({ store: { anon_rpc: anonRpc, proxy: { curvePrivate: curvePrivate, - curvePublic: curvePublic + curvePublic: curvePublic, + kemPrivate: kemPrivate, + kemPublic: kemPublic, } } }, type, msg, user, cb); diff --git a/src/worker/modules/messenger.js b/src/worker/modules/messenger.js index ad55143a7..fe8b6bca2 100644 --- a/src/worker/modules/messenger.js +++ b/src/worker/modules/messenger.js @@ -13,6 +13,26 @@ const factory = (Crypto, Hash, Util, Realtime, Messaging, Messages = data.Messages; }; + /* + * CRYPTOGRAPHIC IDENTITY NOTE: + * + * Throughout this module and the entire CryptPad application, we continue to use + * curve25519 public keys (curvePublic) as the primary identifier for users despite + * having post-quantum cryptography (PQC) keys (kemPublic) available. + * + * 1. Legacy compatibility: A complete migration to PQC for identification would require + * changing all existing user relationships and channels + * + * 2. System integration: The curvePublic key is deeply integrated into friend relationships, + * channel management, history keeper, and other core components + * + * 3. Risk management: Partially migrating identity systems can lead to inconsistencies + * across the application, potentially creating security vulnerabilities + * + * A future coordinated migration will be necessary to fully replace curve25519 with PQC, + * which will require careful planning to ensure all components are updated simultaneously. + */ + var Types = { message: 'MSG', unfriend: 'UNFRIEND', @@ -701,7 +721,7 @@ const factory = (Crypto, Hash, Util, Realtime, Messaging, } var proxy = ctx.store.proxy; - var keys = Curve.deriveKeys(friend.curvePublic, proxy.curvePrivate); + var keys = Curve.deriveKeys(friend.curvePublic, proxy.curvePrivate, friend.kemPublic, proxy.kemPublic); var data = { keys: keys, channel: friend.channel, diff --git a/src/worker/modules/support.js b/src/worker/modules/support.js index 262cb37f7..d36b22af6 100644 --- a/src/worker/modules/support.js +++ b/src/worker/modules/support.js @@ -11,7 +11,6 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, ApiConfig = data.ApiConfig; }; - var Nacl = Crypto.Nacl; // UTILS @@ -40,13 +39,18 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, return void cb('EFORBIDDEN'); } + var supportKemKey = NewConfig.supportMailboxKemKey; + if (isAdmin) { return ctx.adminRdyEvt.reg(() => { cb(null, { supportKey: supportKey, + supportKemKey: supportKemKey, myCurve: data.adminCurvePrivate || Util.find(ctx.store.proxy, [ 'mailboxes', 'supportteam', 'keys', 'curvePrivate']), theirPublic: data.curvePublic, + myKem: ctx.store.proxy.kemPrivate, + theirKem: data.kemPublic, notifKey: data.curvePublic }); }); @@ -54,8 +58,11 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, cb(null, { supportKey: supportKey, + supportKemKey: supportKemKey, myCurve: ctx.store.proxy.curvePrivate, theirPublic: data.curvePublic || supportKey, // old tickets may use deprecated key + myKem: ctx.store.proxy.kemPrivate, + theirKem: data.kemPublic || supportKemKey, // Needed for PQC, currently making messages unreadable notifKey: supportKey }); }); @@ -64,7 +71,7 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, // Get the content of a ticket mailbox and close it var getContent = function (ctx, data, isAdmin, _cb) { var cb = Util.once(Util.mkAsync(_cb)); - var theirPublic, myCurve; + var theirPublic, myCurve, theirKem, myKem; nThen((waitFor) => { getKeys(ctx, isAdmin, data, waitFor((err, obj) => { if (err) { @@ -73,9 +80,11 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, } theirPublic = obj.theirPublic; myCurve = obj.myCurve; + theirKem = obj.theirKem; + myKem = obj.myKem; })); }).nThen(() => { - var keys = Crypto.Curve.deriveKeys(theirPublic, myCurve); + var keys = Crypto.Curve.deriveKeys(theirPublic, myCurve, theirKem, myKem); var crypto = Crypto.Curve.createEncryptor(keys); var cfg = { network: ctx.store.network, @@ -122,7 +131,7 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, var channel = data.channel; var title = data.title; var ticket = data.ticket; - var supportKey, theirPublic, myCurve; + var supportKey, theirPublic, myCurve, theirKem, myKem; var time = +new Date(); nThen((waitFor) => { // Send ticket to the admins and call back @@ -133,13 +142,15 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, } supportKey = obj.supportKey; theirPublic = obj.theirPublic; + theirKem = obj.theirKem; + myKem = obj.myKem; myCurve = obj.myCurve; // No need for notifKey here: users can only create tickets for the // currently used key })); }).nThen((waitFor) => { // Create ticket mailbox - var keys = Crypto.Curve.deriveKeys(theirPublic, myCurve); + var keys = Crypto.Curve.deriveKeys(theirPublic, myCurve, theirKem, myKem); var crypto = Crypto.Curve.createEncryptor(keys); var text = JSON.stringify(ticket); var ciphertext = crypto.encrypt(text); @@ -228,7 +239,7 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, if (!mailbox) { return void cb('E_NOT_READY'); } if (!anonRpc) { return void cb("anonymous rpc session not ready"); } if (!data?.ticket) { return void cb('E_NO_DATA'); } - var theirPublic, myCurve, notifKey; + var theirPublic, myCurve, notifKey, myKem, theirKem; var time; nThen((waitFor) => { // Get correct keys @@ -239,11 +250,13 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, } theirPublic = obj.theirPublic; myCurve = obj.myCurve; + theirKem = obj.theirKem; + myKem = obj.myKem; notifKey = obj.notifKey; })); }).nThen((waitFor) => { // Send message - var keys = Crypto.Curve.deriveKeys(theirPublic, myCurve); + var keys = Crypto.Curve.deriveKeys(theirPublic, myCurve, theirKem, myKem); var crypto = Crypto.Curve.createEncryptor(keys); var text = JSON.stringify(data.ticket); var ciphertext = crypto.encrypt(text); @@ -302,7 +315,7 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, if (!curvePrivate) { return void cb('EFORBIDDEN'); } let edPrivate, edPublic; try { - let pair = Nacl.sign.keyPair.fromSeed(Util.decodeBase64(curvePrivate)); + let pair = Crypto.CryptoAgility.signKeyPairFromSeed(Util.decodeBase64(curvePrivate)); edPrivate = Util.encodeBase64(pair.secretKey); edPublic = Util.encodeBase64(pair.publicKey); } catch (e) { @@ -418,7 +431,8 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, var t = Util.clone(ctx.supportData[ticket]); getContent(ctx, { channel: ticket, - curvePublic: t.curvePublic + curvePublic: t.curvePublic, + kemPublic: t.kemPublic }, false, waitFor((err, messages) => { if (err) { if (err.type === 'EDELETED') { @@ -830,6 +844,7 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, name: Util.find(first, ['sender', 'name']), notifications: Util.find(first, ['sender', 'notifications']), curvePublic: Util.find(first, ['sender', 'curvePublic']), + kemPublic: Util.find(first, ['sender', 'kemPublic']), channel: Hash.createChannelId(), title: first.title, time: last.time, @@ -996,17 +1011,17 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, // ADMIN COMMANDS - let updateServerKey = (ctx, curvePublic, curvePrivate, cb) => { + let updateServerKey = (ctx, curvePublic, curvePrivate, kemPublic, cb) => { let edPublic; try { - let pair = Nacl.sign.keyPair.fromSeed(Util.decodeBase64(curvePrivate)); + let pair = Crypto.CryptoAgility.signKeyPairFromSeed(Util.decodeBase64(curvePrivate)); edPublic = Util.encodeBase64(pair.publicKey); } catch (e) { return void cb(e); } ctx.Store.adminRpc(null, { cmd: 'ADMIN_DECREE', - data: ['SET_SUPPORT_KEYS', [curvePublic, edPublic]] + data: ['SET_SUPPORT_KEYS', [curvePublic, edPublic, kemPublic]] }, cb); }; let getModerators = (ctx, data, cId, cb) => { @@ -1021,12 +1036,15 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, let proxy = ctx.store.proxy; let edPublic = proxy.edPublic; - const keyPair = Nacl.box.keyPair(); + const keyPair = Crypto.CryptoAgility.curveKeyPair(); + const kemPair = Crypto.CryptoAgility.generateKemKeypair(); const newKeyPub = Util.encodeBase64(keyPair.publicKey); const newKey = Util.encodeBase64(keyPair.secretKey); + const newKemPublic = Util.encodeBase64(kemPair.publicKey); const oldKey = Util.find(proxy, ['mailboxes', 'supportteam', 'keys', 'curvePrivate']); const oldKeyPub = Util.find(proxy, ['mailboxes', 'supportteam', 'keys', 'curvePublic']); + const oldKemPublic = Util.find(proxy, ['mailboxes', 'supportteam', 'keys', 'kemPublic']); if (!newKey || !newKeyPub) { return void cb({ error: 'INVALID_KEY' }); } let oldAdminChan; @@ -1092,7 +1110,7 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, }); }).nThen((waitFor) => { // Send new key to server - updateServerKey(ctx, newKeyPub, newKey, waitFor((obj) => { + updateServerKey(ctx, newKeyPub, newKey, newKemPublic, waitFor((obj) => { if (obj && obj.error) { waitFor.abort(); return void cb(obj); @@ -1123,7 +1141,7 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, waitFor.abort(); if (oldSupportKey) { // If we weren't able to store the new key, abort and restore old keys - return updateServerKey(ctx, oldKeyPub, oldKey, () => { + return updateServerKey(ctx, oldKeyPub, oldKey, oldKemPublic,() => { return void cb(obj); }); } @@ -1205,7 +1223,7 @@ const factory = (Util, Hash, Realtime, Pinpad, Crypt, }).nThen((waitFor) => { ctx.Store.adminRpc(null, { cmd: 'ADMIN_DECREE', - data: ['SET_SUPPORT_KEYS', ['', '']] + data: ['SET_SUPPORT_KEYS', ['', '', '']] }, waitFor(function (obj) { if (obj && obj.error) { waitFor.abort(); diff --git a/src/worker/modules/team.js b/src/worker/modules/team.js index 9e7ba7a77..746b7ac71 100644 --- a/src/worker/modules/team.js +++ b/src/worker/modules/team.js @@ -5,10 +5,9 @@ const factory = (Util, Hash, Constants, Realtime, ProxyManager, UserObject, SF, Roster, Messaging, Feedback, Invite, Crypt, Cache, Pinpad, Listmap, Crypto, - CpNetflux, ChainPad, nThen, Nacl) => { + CpNetflux, ChainPad, nThen) => { const Team = {}; - Nacl = Nacl || (typeof(window) !== "undefined" && window.nacl); var onStoreReady = Util.mkEvent(true); var openCachedTeamChat = function () {}; // Placeholder @@ -107,6 +106,7 @@ const factory = (Util, Hash, Constants, Realtime, ProxyManager, try { team.roster.stop(); } catch (e) {} team.proxy = {}; team.stopped = true; + team?.rpc?.destroy(); delete ctx.teams[teamId]; delete ctx.cache[teamId]; delete ctx.store.proxy.teams[teamId]; @@ -449,7 +449,9 @@ const factory = (Util, Hash, Constants, Realtime, ProxyManager, // Roster keys var myKeys = { curvePublic: ctx.store.proxy.curvePublic, - curvePrivate: ctx.store.proxy.curvePrivate + curvePrivate: ctx.store.proxy.curvePrivate, + kemPublic: ctx.store.proxy.kemPublic, + kemPrivate: ctx.store.proxy.kemPrivate, }; var rosterData = keys.roster || {}; var rosterKeys = rosterData.edit ? Crypto.Team.deriveMemberKeys(rosterData.edit, myKeys) @@ -471,6 +473,11 @@ const factory = (Util, Hash, Constants, Realtime, ProxyManager, if (k && !rosterKeys.teamEdPublic) { rosterKeys.teamEdPublic = k; } + // Also get DSA public key from cache if available + var dsaPublic = obj && obj.dsaPublic; + if (dsaPublic && !rosterKeys.teamDsaPublic) { + rosterKeys.teamDsaPublic = dsaPublic; + } if (!c) { waitFor.abort(); cb({error: 'NOCACHE'}); @@ -654,14 +661,18 @@ const factory = (Util, Hash, Constants, Realtime, ProxyManager, var hash = Hash.createRandomHash('team', password); var secret = Hash.getSecrets('team', hash, password); var roHash = Hash.getViewHashFromKeys(secret); - var keyPair = Nacl.sign.keyPair(); // keyPair.secretKey , keyPair.publicKey + var keyPair = Crypto.CryptoAgility.signKeyPair(); // ed25519 + var curvePair = Crypto.CryptoAgility.curveKeyPair(); // Curve25519 - var curvePair = Nacl.box.keyPair(); + var kemPair = Crypto.CryptoAgility.generateKemKeypair(); + var dsaPair = Crypto.CryptoAgility.generateKemKeypair(); var rosterSeed = Crypto.Team.createSeed(); var rosterKeys = Crypto.Team.deriveMemberKeys(rosterSeed, { curvePublic: ctx.store.proxy.curvePublic, - curvePrivate: ctx.store.proxy.curvePrivate + curvePrivate: ctx.store.proxy.curvePrivate, + kemPublic: ctx.store.proxy.kemPublic, + kemPrivate: ctx.store.proxy.kemPrivate, }); var roster; @@ -681,7 +692,6 @@ const factory = (Util, Hash, Constants, Realtime, ProxyManager, owners: [ctx.store.proxy.edPublic] }; nThen(function (waitFor) { - // Initialize the roster Roster.create({ network: ctx.store.network || ctx.store.networkPromise, channel: rosterKeys.channel, //sharedConfig.rosterChannel, @@ -694,7 +704,6 @@ const factory = (Util, Hash, Constants, Realtime, ProxyManager, }, waitFor(function (err, _roster) { if (err) { waitFor.abort(); - console.error(err); return void cb({error: 'ROSTER_ERROR'}); } roster = _roster; @@ -708,7 +717,6 @@ const factory = (Util, Hash, Constants, Realtime, ProxyManager, })); })); - // Add yourself as owner of the chat channel var crypto = Crypto.createEncryptor(chatSecret.keys); var chatCfg = { network: ctx.store.network, @@ -751,19 +759,22 @@ const factory = (Util, Hash, Constants, Realtime, ProxyManager, var proxy = lm.proxy; proxy.version = 2; // No migration needed proxy.on('ready', function () { - // Store keys in our drive var keys = { mailbox: { channel: Hash.createChannelId(), viewed: [], keys: { curvePrivate: Util.encodeBase64(curvePair.secretKey), - curvePublic: Util.encodeBase64(curvePair.publicKey) + curvePublic: Util.encodeBase64(curvePair.publicKey), + kemPrivate: Util.encodeBase64(kemPair.secretKey), + kemPublic: Util.encodeBase64(kemPair.publicKey), } }, drive: { edPrivate: Util.encodeBase64(keyPair.secretKey), - edPublic: Util.encodeBase64(keyPair.publicKey) + edPublic: Util.encodeBase64(keyPair.publicKey), + dsaPrivate: Util.encodeBase64(dsaPair.secretKey), + dsaPublic: Util.encodeBase64(dsaPair.publicKey), }, chat: { edit: chatHashes.editHash, @@ -784,7 +795,6 @@ const factory = (Util, Hash, Constants, Realtime, ProxyManager, roHash: roHash, password: password, keys: keys, - //members: membersHashes.editHash, metadata: { name: data.name } @@ -803,13 +813,11 @@ const factory = (Util, Hash, Constants, Realtime, ProxyManager, cb(); }); }).on('error', function (info) { - if (info && typeof (info.loaded) !== "undefined" && !info.loaded) { + if (info && typeof (info.loaded) !== "undefined" && !info.loaded) { cb({error:'ECONNECT'}); } - if (info && info.error) { - if (info.error === "EDELETED") { - closeTeam(ctx, id); - } + if (info && info.error === "EDELETED") { + closeTeam(ctx, id); } }); }); @@ -1674,6 +1682,10 @@ const factory = (Util, Hash, Constants, Realtime, ProxyManager, edPrivate: ephemeralKeys.edPrivate, curvePublic: ephemeralKeys.curvePublic, curvePrivate: ephemeralKeys.curvePrivate, + kemPublic: ephemeralKeys.kemPublic, + kemPrivate: ephemeralKeys.kemPrivate, + dsaPublic: ephemeralKeys.dsaPublic, + dsaPrivate: ephemeralKeys.dsaPrivate, }, }; @@ -1867,10 +1879,10 @@ const factory = (Util, Hash, Constants, Realtime, ProxyManager, if (team.keys && team.keys.mailbox) { return team.keys.mailbox; } var strSeed = Util.find(team, ['keys', 'roster', 'edit']); if (!strSeed) { return; } - var hash = Nacl.hash(Util.decodeUTF8(strSeed)); + var hash = Crypto.CryptoAgility.createHash(Util.decodeUTF8(strSeed)); var seed = hash.slice(0,32); var mailboxChannel = Util.uint8ArrayToHex(hash.slice(32,48)); - var curvePair = Nacl.box.keyPair.fromSecretKey(seed); + var curvePair = Crypto.CryptoAgility.boxKeyPairFromSecretKey(seed); return { channel: mailboxChannel, viewed: [], @@ -1919,7 +1931,7 @@ const factory = (Util, Hash, Constants, Realtime, ProxyManager, if (!edPrivate || !edPublic) { return true; } try { var secretKey = Util.decodeBase64(edPrivate); - var pair = Nacl.sign.keyPair.fromSecretKey(secretKey); + var pair = Crypto.CryptoAgility.signKeyPairFromSecretKey(secretKey); return Util.encodeBase64(pair.publicKey) === edPublic; } catch (e) { return false; diff --git a/www/admin/inner.js b/www/admin/inner.js index 4978e4218..2e99b5514 100644 --- a/www/admin/inner.js +++ b/www/admin/inner.js @@ -22,6 +22,7 @@ define([ '/api/instance', '/lib/datepicker/flatpickr.js', '/install/onboardscreen.js', + '/components/chainpad-crypto/crypto.js', 'css!/lib/datepicker/flatpickr.min.css', 'css!/components/bootstrap/dist/css/bootstrap.min.css', @@ -47,11 +48,12 @@ define([ Instance, Flatpickr, Onboarding, + Crypto ) { var APP = window.APP = {}; - var Nacl = window.nacl; + //var Nacl = window.nacl; var common; var sFrameChan; @@ -2798,7 +2800,7 @@ define([ var msg = Util.decodeUTF8(Sortify(clone)); var sig = Util.decodeBase64(json.proof); var pub = Util.decodeBase64(json.blockId); - return Nacl.sign.detached.verify(msg, sig, pub); + return Crypto.CryptoAgility.verifyDetached(msg, sig, pub); }; // Msg.admin_totpRecoveryHint.admin_totpRecoveryTitle diff --git a/www/assert/main.js b/www/assert/main.js index d2f59cff0..b581653e7 100644 --- a/www/assert/main.js +++ b/www/assert/main.js @@ -21,11 +21,12 @@ define([ '/customize/messages.js', '/components/tweetnacl/nacl-fast.min.js', + '/components/chainpad-crypto/crypto.js', 'less!/customize/src/less2/pages/page-assert.less', -], function ($, Hyperjson, Sortify, Drive, /*Test,*/ Hash, Util, Thumb, Wire, Flat, MediaTag, Block, ApiConfig, Assertions, h, Messages) { +], function ($, Hyperjson, Sortify, Drive, /*Test,*/ Hash, Util, Thumb, Wire, Flat, MediaTag, Block, ApiConfig, Assertions, h, Messages, Crypto) { window.Hyperjson = Hyperjson; window.Sortify = Sortify; - var Nacl = window.nacl; + //var Nacl = window.nacl; var assert = Assertions(); @@ -314,7 +315,7 @@ define([ }, "test that protocol relative URLs are rejected"); assert(function (cb) { - var keys = Block.genkeys(Nacl.randomBytes(64)); + var keys = Block.genkeys(Crypto.CryptoAgility.bytes(64)); var hash = Block.getBlockHash(keys); var parsed = Block.parseBlockHash(hash); diff --git a/www/auth/main.js b/www/auth/main.js index bcae41bb3..0b66eb659 100644 --- a/www/auth/main.js +++ b/www/auth/main.js @@ -15,11 +15,12 @@ define([ '/lib/qrcode.min.js', '/components/tweetnacl/nacl-fast.min.js', + 'componenst/chainpad-cypto/crypto.js', 'less!/auth/app-auth.less', -], function ($, Util, h, UI, ServerCommand, Base32, Login, Block, LocalStore) { +], function ($, Util, h, UI, ServerCommand, Base32, Login, Block, LocalStore, Crypto) { var QRCode = window.QRCode; - var Nacl = window.nacl; + //var Nacl = window.nacl; var main = h('div.centered', [ @@ -220,7 +221,7 @@ Note: This must currently be reversed manually (by deleting the mfa config file) var $b32Secret = $('#base32-secret'); var randomSecret = () => { - var U8 = Nacl.randomBytes(20); + var U8 = Crypto.CryptoAgility.bytes(20); return Base32.encode(U8); }; diff --git a/www/common/common-login.js b/www/common/common-login.js index 37cd08aa0..1e37264e2 100644 --- a/www/common/common-login.js +++ b/www/common/common-login.js @@ -24,10 +24,11 @@ define([ '/components/scrypt-async/scrypt-async.min.js', // better load speed ], function (Listmap, Crypto, Util, NetConfig, Cred, ChainPad, Realtime, Constants, UI, Feedback, LocalStore, Messages, nThen, Block, Hash, ServerCommand) { - var Nacl = window.nacl; + //var Nacl = window.nacl; var Exports = { - requiredBytes: 192, + // Increased required bytes to accommodate post-quantum keys + requiredBytes: 288, // Increased from original to accommodate post-quantum keys }; var allocateBytes = Exports.allocateBytes = function (bytes) { @@ -42,23 +43,43 @@ define([ // 32 bytes for a curve key var curveSeed = dispense(32); - var curvePair = Nacl.box.keyPair.fromSecretKey(new Uint8Array(curveSeed)); + // KEM keys (post-quantum) + var kemSeed = dispense(64); // 64 bytes for post-quantum KEM keys + if (Crypto.PQC && Crypto.PQC.ml_kem && Crypto.PQC.ml_kem.ml_kem512) { + var pqKemPair = Crypto.CryptoAgility.generateKemKeypair(new Uint8Array(kemSeed)); + opt.kemPrivate = Util.encodeBase64(pqKemPair.secretKey); + opt.kemPublic = Util.encodeBase64(pqKemPair.publicKey); + } else { + opt.kemPrivate = undefined; + opt.kemPublic = undefined; + } + + var curvePair = Crypto.CryptoAgility.boxKeyPairFromSecretKey(new Uint8Array(curveSeed)); opt.curvePrivate = Util.encodeBase64(curvePair.secretKey); opt.curvePublic = Util.encodeBase64(curvePair.publicKey); // 32 more for a signing key var edSeed = opt.edSeed = dispense(32); - // 64 more bytes to seed an additional signing key - var blockKeys = opt.blockKeys = Block.genkeys(new Uint8Array(dispense(64))); + // Allocate more bytes for block keys seed to accommodate PQ keys + var blockKeysSeed = dispense(96); // Increased from original to fit PQ keys + + // Generate block keys + var blockKeys = opt.blockKeys = Block.genkeys(new Uint8Array(blockKeysSeed)); opt.blockHash = Block.getBlockHash(blockKeys); // derive a private key from the ed seed - var signingKeypair = Nacl.sign.keyPair.fromSeed(new Uint8Array(edSeed)); + var signingKeypair = Crypto.CryptoAgility.signKeyPairFromSeed(new Uint8Array(edSeed)); opt.edPrivate = Util.encodeBase64(signingKeypair.secretKey); opt.edPublic = Util.encodeBase64(signingKeypair.publicKey); + // Store post-quantum keys if they're available + if (blockKeys.hasPQ && blockKeys.pqSignPair) { + opt.dsaPrivate = Util.encodeBase64(blockKeys.pqSignPair.secretKey); + opt.dsaPublic = Util.encodeBase64(blockKeys.pqSignPair.publicKey); + } + var keys = opt.keys = Crypto.createEditCryptor(null, encryptionSeed); // 24 bytes of base64 @@ -86,6 +107,9 @@ define([ opt.channelHex = parsed.channel; opt.keys = parsed.keys; opt.edPublic = blockInfo.edPublic; + opt.dsaPublic = blockInfo.dsaPublic; + + return opt; }; @@ -171,10 +195,17 @@ define([ res.edPrivate = opt.edPrivate; res.edPublic = opt.edPublic; + //export their post-quantum keys if available + res.dsaPrivate = opt.dsaPrivate; + res.dsaPublic = opt.dsaPublic; + // export their encryption key res.curvePrivate = opt.curvePrivate; res.curvePublic = opt.curvePublic; + res.kemPrivate = opt.kemPrivate; + res.kemPublic = opt.kemPublic; + // don't proceed past this async block. // We have to call whenRealtimeSyncs asynchronously here because in the current @@ -201,7 +232,7 @@ define([ opt.userHash = blockInfo.User_hash; } else { console.log("allocating random bytes for a new user object"); - opt = allocateBytes(Nacl.randomBytes(Exports.requiredBytes)); + opt = allocateBytes(Crypto.CryptoAgility.bytes(Exports.requiredBytes)); // create a random v2 hash, since we don't need backwards compatibility opt.userHash = Hash.createRandomHash('drive'); var secret = Hash.getSecrets('drive', opt.userHash); @@ -223,7 +254,7 @@ define([ var RT = rt; var proxy = rt.proxy; - if (isRegister && !isProxyEmpty(proxy) && (!proxy.edPublic || !proxy.edPrivate)) { + if (isRegister && !isProxyEmpty(proxy) && (!proxy.edPublic || !proxy.edPrivate || !proxy.dsaPublic || !proxy.dsaPrivate)){ console.error("INVALID KEYS"); console.log(JSON.stringify(proxy)); return void cb(void 0, void 0, RT); @@ -245,7 +276,7 @@ define([ return void cb('NO_SUCH_USER'); } - if (!isProxyEmpty(rt.proxy) && res.auth_token && res.auth_token.bearer) { + if (!isRegister && !isProxyEmpty(rt.proxy) && res.auth_token && res.auth_token.bearer) { LocalStore.setSessionToken(res.auth_token.bearer); } @@ -268,8 +299,12 @@ define([ if (isRegister && isProxyEmpty(rt.proxy)) { proxy.edPublic = opt.edPublic; proxy.edPrivate = opt.edPrivate; + proxy.dsaPublic = opt.dsaPublic; + proxy.dsaPrivate = opt.dsaPrivate; proxy.curvePublic = opt.curvePublic; proxy.curvePrivate = opt.curvePrivate; + proxy.kemPublic = opt.kemPublic; + proxy.kemPrivate = opt.kemPrivate; proxy.login_name = res.uname; proxy[Constants.displayNameKey] = res.uname; proxy.version = 11; diff --git a/www/common/cryptpad-common.js b/www/common/cryptpad-common.js index af9b61f07..e041908e4 100644 --- a/www/common/cryptpad-common.js +++ b/www/common/cryptpad-common.js @@ -23,10 +23,11 @@ define([ '/customize/application_config.js', '/components/nthen/index.js', - '/components/tweetnacl/nacl-fast.min.js' + '/components/tweetnacl/nacl-fast.min.js', + '/components/chainpad-crypto/crypto.js' ], function (Config, Broadcast, Messages, Util, Hash, Cache, Constants, Feedback, Visible, UserObject, LocalStore, Channel, Block, - Cred, Login, Store, Types, AppConfig, nThen) { + Cred, Login, Store, Types, AppConfig, nThen, Crypto) { /* This file exposes functionality which is specific to Cryptpad, but not to any particular pad type. This includes functions for committing metadata @@ -251,8 +252,8 @@ define([ // Make proof var curve = answer.curvePrivate; var mySecret = Util.decodeBase64(curve); - var nonce = nacl.randomBytes(24); - var proofBytes = nacl.box(h, nonce, theirs, mySecret); + var nonce = Crypto.CryptoAgility.bytes(24); + var proofBytes = Crypto.CryptoAgility.box(h, nonce, theirs, mySecret); var proof = Util.encodeBase64(nonce) +'|'+ Util.encodeBase64(proofBytes); var lineData = { channel: data.channel, diff --git a/www/common/inner/invitation.js b/www/common/inner/invitation.js index 3396c0e6b..f7850580d 100644 --- a/www/common/inner/invitation.js +++ b/www/common/inner/invitation.js @@ -3,18 +3,18 @@ // SPDX-License-Identifier: AGPL-3.0-or-later (function () { -var factory = function (Util, Nacl, Scrypt) { +var factory = function (Util, Nacl, Scrypt, Crypto) { var Invite = {}; Invite.deriveSeeds = function (safeSeed) { // take the hash of the provided seed var seed = safeSeed.replace(/\-/g, '/'); - var u8_seed = Nacl.hash(Util.decodeBase64(seed)); + var u8_seed = Crypto.CryptoAgility.createHash(Util.decodeBase64(seed)); // hash the first half again for scrypt's input - var subseed1 = Nacl.hash(u8_seed.subarray(0, 32)); + var subseed1 = Crypto.CryptoAgility.createHash(u8_seed.subarray(0, 32)); // hash the remainder for the invite content - var subseed2 = Nacl.hash(u8_seed.subarray(32)); + var subseed2 = Crypto.CryptoAgility.createHash(u8_seed.subarray(32)); return { scrypt: Util.encodeBase64(subseed1), @@ -44,15 +44,17 @@ var factory = function (Util, Nacl, Scrypt) { module.exports = factory( require("../common-util"), require("tweetnacl/nacl-fast"), - require("scrypt-async") + require("scrypt-async"), + require("chainpad-crypto/crypto") ); } else if ((typeof(define) !== 'undefined' && define !== null) && (define.amd !== null)) { define([ '/common/common-util.js', '/components/tweetnacl/nacl-fast.min.js', '/components/scrypt-async/scrypt-async.min.js', - ], function (Util) { - return factory(Util, window.nacl, window.scrypt); + '/components/chainpad-crypto/crypto.js' + ], function (Util, nacl, Scrypt, Crypto) { + return factory(Util, window.nacl, window.scrypt, Crypto); }); } }()); diff --git a/www/common/inner/mfa.js b/www/common/inner/mfa.js index 94516f0b9..2df040939 100644 --- a/www/common/inner/mfa.js +++ b/www/common/inner/mfa.js @@ -10,8 +10,9 @@ define([ '/components/nthen/index.js', '/customize.dist/login.js', '/common/common-util.js', + '/components/chainpad-crypto/crypto.js' -], function ($, Messages, h, UI, nThen, Login, Util) { +], function ($, Messages, h, UI, nThen, Login, Util, Crypto) { const MFA = {}; MFA.totpSetup = function (common, config, content, enabled, cb) { @@ -161,7 +162,7 @@ define([ $(pwInput).prop('disabled', 'disabled'); $mfaSetupBtn.prop('disabled', 'disabled'); - var Base32, QRCode, Nacl; + var Base32, QRCode; var blockKeys; var recoverySecret; var ssoSeed; @@ -173,7 +174,6 @@ define([ ], waitFor(function (_Base32) { Base32 = _Base32; QRCode = window.QRCode; - Nacl = window.nacl; })); }).nThen(function (waitFor) { sframeChan.query("Q_SETTINGS_GET_SSO_SEED", { @@ -212,7 +212,7 @@ define([ }).nThen(function (waitFor) { $content.empty(); var next = waitFor(); - recoverySecret = Util.encodeBase64(Nacl.randomBytes(24)); + recoverySecret = Util.encodeBase64(Crypto.CryptoAgility.bytes(24)); var button = h('button.btn.btn-primary', [ h('i.fa.fa-check'), h('span', Messages.done) @@ -241,7 +241,7 @@ define([ }); }).nThen(function () { var randomSecret = function () { - var U8 = Nacl.randomBytes(20); + var U8 = Crypto.CryptoAgility.bytes(20); return Base32.encode(U8); }; $content.empty(); diff --git a/www/common/media-tag.js b/www/common/media-tag.js index f019df47d..8c59e3950 100644 --- a/www/common/media-tag.js +++ b/www/common/media-tag.js @@ -3,7 +3,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later (function (window) { -var factory = function (Util) { +var factory = function (Util, Crypto) { var Promise = window.Promise; var cache; var cypherChunkLength = 131088; @@ -456,7 +456,7 @@ var factory = function (Util) { var metadataLength = Decrypt.decodePrefix(prefix); var metaBox = new Uint8Array(u8.subarray(2, 2 + metadataLength)); - var metaChunk = window.nacl.secretbox.open(metaBox, Decrypt.createNonce(), key); + var metaChunk = Crypto.CryptoAgility.secretboxOpen(metaBox, Decrypt.createNonce(), key); try { return JSON.parse(Util.encodeUTF8(metaChunk)); @@ -478,7 +478,7 @@ var factory = function (Util) { // Decrypts a Uint8Array with the given key. var decrypt = function (u8, strKey, done, progressCb) { - var Nacl = window.nacl; + //var Nacl = window.nacl; var progress = function (offset) { progressCb((offset / u8.length) * 100); @@ -494,7 +494,7 @@ var factory = function (Util) { // Get metadata var metaBox = new Uint8Array(u8.subarray(2, 2 + metadataLength)); - var metaChunk = Nacl.secretbox.open(metaBox, nonce, key); + var metaChunk = Crypto.CryptoAgility.secretboxOpen(metaBox, nonce, key); Decrypt.increment(nonce); @@ -513,7 +513,7 @@ var factory = function (Util) { var box = new Uint8Array(u8.subarray(start, end)); // Decrypt the chunk - var plaintext = Nacl.secretbox.open(box, nonce, key); + var plaintext = Crypto.CryptoAgility.secretboxOpen(box, nonce, key); Decrypt.increment(nonce); if (!plaintext) { return void cb('DECRYPTION_FAILURE'); } @@ -833,8 +833,8 @@ var factory = function (Util) { if (typeof(module) !== 'undefined' && module.exports) { module.exports = factory(); } else if ((typeof(define) !== 'undefined' && define !== null) && (define.amd !== null)) { - define(['/common/common-util.js'], function (Util) { - return factory(Util); + define(['/common/common-util.js', '/components/chainpad-crypto/crypto.js'], function (Util, Crypto) { + return factory(Util, Crypto); }); } else { // unsupported initialization diff --git a/www/common/onlyoffice/inner.js b/www/common/onlyoffice/inner.js index d91394fc4..3ba1ce06b 100644 --- a/www/common/onlyoffice/inner.js +++ b/www/common/onlyoffice/inner.js @@ -28,6 +28,8 @@ define([ '/common/onlyoffice/broken-formats.js', '/components/file-saver/FileSaver.min.js', + '/components/chainpad-crypto/crypto.js', + 'css!/components/bootstrap/dist/css/bootstrap.min.css', 'less!/components/components-font-awesome/css/font-awesome.min.css', 'less!/common/onlyoffice/app-oo.less', @@ -40,6 +42,7 @@ define([ UI, Hash, Util, + Crypto, UIElements, Feedback, h, @@ -56,7 +59,7 @@ define([ BrokenFormats) { var saveAs = window.saveAs; - var Nacl = window.nacl; + //var Nacl = window.nacl; var APP = window.APP = { $: $, urlArgs: Util.find(ApiConfig, ['requireConf', 'urlArgs']) @@ -2495,7 +2498,7 @@ Uncaught TypeError: Cannot read property 'calculatedType' of null } try { debug("Decrypt with key " + data.key); - FileCrypto.decrypt(u8, Nacl.util.decodeBase64(data.key), function (err, res) { + FileCrypto.decrypt(u8, Crypto.CryptoAgility.decodeBase64(data.key), function (err, res) { APP.loadingImage--; if (err || !res.content) { debug("Decrypting failed"); diff --git a/www/common/sframe-common-integration.js b/www/common/sframe-common-integration.js index 8b1ab5374..5fdb6da02 100644 --- a/www/common/sframe-common-integration.js +++ b/www/common/sframe-common-integration.js @@ -92,7 +92,7 @@ define([ if (state.me) { return; } // I have the lock: abort if (state.other && state.other !== data.uid) { return; } // someone else has the lock // If state.other === data.uid ==> save failed and someone else tries again - if (!state.changed) { return; } + if (!state.changed && state.other !== data.uid) { return; } // If !state.other: nobody has the lock, give them state.other = data.uid; state.lastTmp = +new Date(); @@ -103,6 +103,7 @@ define([ setStateChanged(false); saveTo = setTimeout(function () { // They weren't able to save in time, try ourselves + setStateChanged(true); var id = state.other; state.other = false; save(id); @@ -151,7 +152,7 @@ define([ // is already saving requestSave = function (id, cb) { if (state.other || state.me) { return void cb(false); } // save in progress - debug('Integration send ISAVE'); + debug('Integration send ISAVE', id); alreadySaved = false; // someone may have saved while we were waiting for our callback execCommand('SEND', { msg: 'ISAVE', diff --git a/www/common/worker.bundle.min.js b/www/common/worker.bundle.min.js index 467cae904..3287bb422 100644 --- a/www/common/worker.bundle.min.js +++ b/www/common/worker.bundle.min.js @@ -1 +1 @@ -!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self)["cryptpad-worker-min"]={})}(this,function(e){"use strict";function n(e,n){return n.forEach(function(n){n&&"string"!=typeof n&&!Array.isArray(n)&&Object.keys(n).forEach(function(t){if("default"!==t&&!(t in e)){var r=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:function(){return n[t]}})}})}),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function r(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function o(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var n=e.default;if("function"==typeof n){var t=function e(){var t=!1;try{t=this instanceof e}catch{}return t?Reflect.construct(n,arguments,this.constructor):n.apply(this,arguments)};t.prototype=n.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}),t}var a,i={exports:{}},s={exports:{}},c={exports:{}};function u(){return a||(a=1,function(e){var n;n=function(){var e=function(){},n=function(){return(new Date).getTime()},t=function(e,n,t){e.timeouts.push(setTimeout(n,t))},r=function(n,r){n.ws&&(n.ws.onmessage=e,n.ws.onopen=e,n.ws.close(),r?n.ws.onclose({reason:"offline"}):t(n,function(){n.ws&&n.ws.onclose({reason:"forced closed because websocket failed to close"})},1e4))},o=function(e,n){return!!e.ws&&(e.ws.send(JSON.stringify(n)),!0)},a=function(e,n){return function(e,t){var r=n[e];if(!r)throw new Error("no such event "+e);r.push(t)}},i=function(e,n,t,r){var o=r[n];if(!o)throw new Error("no such event "+n);var a=o.indexOf(t);-1!==a&&o.splice(a,1)},s=function(e,t,r){if(e.channels[t])return new Promise(function(n){n(e.channels[t])});var s=e.queues.p2;1===r?s=e.queues.p1:3===r&&(s=e.queues.p3);var c={queue:s,onMessage:[],onJoin:[],onLeave:[],members:[],jSeq:e.seq++},u={message:c.onMessage,join:c.onJoin,leave:c.onLeave},f={_:c,time:n(),id:t,members:c.members,bcast:function(t){return function(e,t,r){var a=e.channels[t],i=e.seq++,s=[i,"MSG",t,r];if(!a)return new Promise(function(e,n){n({type:"NO_SUCH_CHANNEL",message:JSON.stringify(s)})});var c=o(e,s);return new Promise(function(t,r){c?e.requests[i]={reject:r,resolve:t,time:n()}:r({type:"DISCONNECTED",message:JSON.stringify(s)})})}(e,f.id,t)},leave:function(t){return function(e,t,r){if(e.channels[t]){if(delete e.channels[t],e.ws&&1===e.ws.readyState){var a=e.seq++;o(e,[a,"LEAVE",t,r]);var i=function(){};e.requests[a]={reject:i,resolve:i,time:n()}}}else console.debug("no such channel",t)}(e,f.id,t)},on:a(0,u),off:function(e,n){i(0,e,n,u)}};e.requests[c.jSeq]=f;var l=[c.jSeq,"JOIN",t],d=o(e,l);return new Promise(function(e,n){d?(f._.resolve=e,f._.reject=n):n({type:"DISCONNECTED",message:JSON.stringify(l)})})},c=function(t){var r={message:t.onMessage,disconnect:t.onDisconnect,reconnect:t.onReconnect},c={webChannels:t.channels,getLag:function(){return function(e){return e.ws?e.pingOutstanding?Math.max(n()-e.timeOfLastPingSent,e.lastObservedLag):e.lastObservedLag:null}(t)},sendto:function(e,r){return function(e,t,r){var a=e.seq++,i=[a,"MSG",t,r],s=o(e,i);return new Promise(function(t,r){s?e.requests[a]={reject:r,resolve:t,time:n()}:r({type:"DISCONNECTED",message:JSON.stringify(i)})})}(t,e,r)},join:function(e,n){return s(t,e,n)},disconnect:function(){return function(n){if(n.ws){var t=n.ws.onclose;n.ws.onclose=e,n.ws.close(),t({reason:"network.disconnect() called"})}n.timeouts.forEach(clearTimeout),n.timeouts=[]}(t)},on:a(0,r),off:function(e,n){i(0,e,n,r)}};return c.__defineGetter__("webChannels",function(){return Object.keys(t.channels).map(function(e){return t.channels[e]})}),c},u=function(e,t){var a=void 0;try{a=JSON.parse(t.data)}catch(e){return void console.log(e.stack)}if(e.timeOfLastMsgReceived=n(),0===a[0]){if("IDENT"===a[2])return e.uid=a[3],e.ws._onident(),void(e.pingInterval=setInterval(function(){if(!(n()-e.timeOfLastPingReceived<15e3||(n()-e.timeOfLastMsgReceived>6e4&&r(e),e.pingOutstanding))){var t=e.seq++,a=n();e.timeOfLastPingSent=a,e.pingOutstanding++,e.requests[t]={time:a,ping:a},o(e,[t,"PING"])}},5e3));if(e.uid){if("PING"===a[2])return a[2]="PONG",void o(e,a);if("MSG"===a[2]){var i=void 0,s=e.queues.p2;if(a[3]===e.uid)i=e.onMessage,"number"==typeof a[5]&&(1===a[5]&&(s=e.queues.p1),3===a[5]&&(s=e.queues.p3));else{var c=e.channels[a[3]];if(!c)return void console.log("message to non-existent chan "+JSON.stringify(a));i=c._.onMessage,c._.queue&&(s=c._.queue)}s.push({msg:a,h:i}),function(e){if(!e.queues.busy){var n=function(){var t=e.queues.p1.shift()||e.queues.p2.shift()||e.queues.p3.shift();if(t){e.queues.busy=!0;var r=t.h,o=t.msg;r.forEach(function(e){setTimeout(function(){try{e(o[4],o[1])}catch(e){console.error(e)}})}),setTimeout(function(){n()})}else e.queues.busy=!1};n()}}(e)}if("LEAVE"===a[2]){var u=e.channels[a[3]];if(!u)return void(a[1]!==e.uid&&console.log("leaving non-existent chan "+JSON.stringify(a)));var f=u._.members.indexOf(a[1]);-1!==f&&u._.members.splice(f,1),u._.onLeave.forEach(function(e){try{e(a[1],a[4])}catch(e){console.log(e.stack)}})}if("JOIN"===a[2]){var l=e.channels[a[3]];if(!l)return void console.log("ERROR: join to non-existent chan "+JSON.stringify(a));if(-1!==l._.members.indexOf(a[1]))return;var d=-1!==l._.members.indexOf(e.uid);l._.members.push(a[1]),d||a[1]!==e.uid||(l.myID=e.uid,l._.resolve(l)),d&&l._.onJoin.forEach(function(e){try{e(a[1])}catch(e){console.log(e.stack)}})}}}else{var h=e.requests[a[0]];if(!h)return void console.log("error: "+JSON.stringify(a));if(delete e.requests[a[0]],"ACK"===a[1]){if(h.ping)return e.lastObservedLag=n()-Number(h.ping),e.timeOfLastPingReceived=n(),void e.pingOutstanding--;h.resolve()}else if("JACK"===a[1]){if(h._){if(!a[2])throw new Error("wrong type of ACK for channel join");return h.id=a[2],void(e.channels[h.id]=h)}h.resolve()}else if("ERROR"===a[1])if("function"==typeof h.reject)h.reject({type:a[2],message:a[3]});else if(h._&&"function"==typeof h._.reject){if("EJOINED"===a[2]&&!e.channels[a[3]])return h.id=a[3],void(e.channels[h.id]=h);h._.reject({type:a[2],message:a[3]})}else console.error(a);else h.reject({type:"UNKNOWN",message:JSON.stringify(a)})}};return{connect:function(o,a){a=a||function(e){return new globalThis.WebSocket(e)};var i={ws:null,seq:1,uid:null,network:null,channels:{},onMessage:[],onDisconnect:[],onReconnect:[],timeouts:[],requests:{},pingInterval:null,queues:{p1:[],p2:[],p3:[]},timeOfLastPingSent:-1,timeOfLastPingReceived:-1,timeOfLastMsgReceived:-1,lastObservedLag:0,pingOutstanding:0};i.network=c(i);var s=e,f=e;"undefined"!=typeof window&&window.addEventListener("offline",function(){-1===["localhost","127.0.0.1",""].indexOf(window.location.hostname)&&r(i,!0)});var l=function(){var c=i.ws=a(o);i.timeOfLastPingSent=i.timeOfLastPingReceived=n(),i.timeOfLastMsgReceived=n(),c.onmessage=function(e){return u(i,e)},c.onclose=function(n){c.onclose=e,clearInterval(i.pingInterval),i.timeouts.forEach(clearTimeout),i.ws=null,i.uid&&(i.uid=null,i.onDisconnect.forEach(function(e){try{e(n.reason)}catch(e){console.log(e.stack)}})),t(i,l,i.uid?0:7e3)},c.onopen=function(){t(i,function(){i.uid||(f({type:"TIMEOUT",message:"waited 30000ms"}),s=f=e,r(i))},3e4)},i.ws._onident=function(){i.timeOfLastPingReceived=n(),i.timeOfLastMsgReceived=n(),i.lastObservedLag=n()-i.timeOfLastPingSent,s!==e?(s(i.network),s=f=e):(i.channels={},i.requests={},i.pingOutstanding=0,i.onReconnect.forEach(function(e){try{e(i.uid)}catch(e){console.log(e.stack)}}))}};return new Promise(function(e,n){s=e,f=n,l()})}}},e.exports?e.exports=n():window.netflux_websocket=n()}(c)),c.exports}function f(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var l,d={exports:{}};function h(){return l||(l=1,function(e){!function(e){var n=function(e){var n,t=new Float64Array(16);if(e)for(n=0;n>24&255,e[n+1]=t>>16&255,e[n+2]=t>>8&255,e[n+3]=255&t,e[n+4]=r>>24&255,e[n+5]=r>>16&255,e[n+6]=r>>8&255,e[n+7]=255&r}function v(e,n,t,r,o){var a,i=0;for(a=0;a>>8)-1}function y(e,n,t,r){return v(e,n,t,r,16)}function m(e,n,t,r){return v(e,n,t,r,32)}function g(e,n,t,r){!function(e,n,t,r){for(var o,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,i=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,s=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,c=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,u=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,f=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,l=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,d=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,h=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,p=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,v=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,y=255&t[16]|(255&t[17])<<8|(255&t[18])<<16|(255&t[19])<<24,m=255&t[20]|(255&t[21])<<8|(255&t[22])<<16|(255&t[23])<<24,g=255&t[24]|(255&t[25])<<8|(255&t[26])<<16|(255&t[27])<<24,E=255&t[28]|(255&t[29])<<8|(255&t[30])<<16|(255&t[31])<<24,b=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,O=a,A=i,w=s,D=c,_=u,T=f,S=l,N=d,I=h,x=p,C=v,R=y,P=m,k=g,M=E,F=b,L=0;L<20;L+=2)O^=(o=(P^=(o=(I^=(o=(_^=(o=O+P|0)<<7|o>>>25)+O|0)<<9|o>>>23)+_|0)<<13|o>>>19)+I|0)<<18|o>>>14,T^=(o=(A^=(o=(k^=(o=(x^=(o=T+A|0)<<7|o>>>25)+T|0)<<9|o>>>23)+x|0)<<13|o>>>19)+k|0)<<18|o>>>14,C^=(o=(S^=(o=(w^=(o=(M^=(o=C+S|0)<<7|o>>>25)+C|0)<<9|o>>>23)+M|0)<<13|o>>>19)+w|0)<<18|o>>>14,F^=(o=(R^=(o=(N^=(o=(D^=(o=F+R|0)<<7|o>>>25)+F|0)<<9|o>>>23)+D|0)<<13|o>>>19)+N|0)<<18|o>>>14,O^=(o=(D^=(o=(w^=(o=(A^=(o=O+D|0)<<7|o>>>25)+O|0)<<9|o>>>23)+A|0)<<13|o>>>19)+w|0)<<18|o>>>14,T^=(o=(_^=(o=(N^=(o=(S^=(o=T+_|0)<<7|o>>>25)+T|0)<<9|o>>>23)+S|0)<<13|o>>>19)+N|0)<<18|o>>>14,C^=(o=(x^=(o=(I^=(o=(R^=(o=C+x|0)<<7|o>>>25)+C|0)<<9|o>>>23)+R|0)<<13|o>>>19)+I|0)<<18|o>>>14,F^=(o=(M^=(o=(k^=(o=(P^=(o=F+M|0)<<7|o>>>25)+F|0)<<9|o>>>23)+P|0)<<13|o>>>19)+k|0)<<18|o>>>14;O=O+a|0,A=A+i|0,w=w+s|0,D=D+c|0,_=_+u|0,T=T+f|0,S=S+l|0,N=N+d|0,I=I+h|0,x=x+p|0,C=C+v|0,R=R+y|0,P=P+m|0,k=k+g|0,M=M+E|0,F=F+b|0,e[0]=O>>>0&255,e[1]=O>>>8&255,e[2]=O>>>16&255,e[3]=O>>>24&255,e[4]=A>>>0&255,e[5]=A>>>8&255,e[6]=A>>>16&255,e[7]=A>>>24&255,e[8]=w>>>0&255,e[9]=w>>>8&255,e[10]=w>>>16&255,e[11]=w>>>24&255,e[12]=D>>>0&255,e[13]=D>>>8&255,e[14]=D>>>16&255,e[15]=D>>>24&255,e[16]=_>>>0&255,e[17]=_>>>8&255,e[18]=_>>>16&255,e[19]=_>>>24&255,e[20]=T>>>0&255,e[21]=T>>>8&255,e[22]=T>>>16&255,e[23]=T>>>24&255,e[24]=S>>>0&255,e[25]=S>>>8&255,e[26]=S>>>16&255,e[27]=S>>>24&255,e[28]=N>>>0&255,e[29]=N>>>8&255,e[30]=N>>>16&255,e[31]=N>>>24&255,e[32]=I>>>0&255,e[33]=I>>>8&255,e[34]=I>>>16&255,e[35]=I>>>24&255,e[36]=x>>>0&255,e[37]=x>>>8&255,e[38]=x>>>16&255,e[39]=x>>>24&255,e[40]=C>>>0&255,e[41]=C>>>8&255,e[42]=C>>>16&255,e[43]=C>>>24&255,e[44]=R>>>0&255,e[45]=R>>>8&255,e[46]=R>>>16&255,e[47]=R>>>24&255,e[48]=P>>>0&255,e[49]=P>>>8&255,e[50]=P>>>16&255,e[51]=P>>>24&255,e[52]=k>>>0&255,e[53]=k>>>8&255,e[54]=k>>>16&255,e[55]=k>>>24&255,e[56]=M>>>0&255,e[57]=M>>>8&255,e[58]=M>>>16&255,e[59]=M>>>24&255,e[60]=F>>>0&255,e[61]=F>>>8&255,e[62]=F>>>16&255,e[63]=F>>>24&255}(e,n,t,r)}function E(e,n,t,r){!function(e,n,t,r){for(var o,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,i=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,s=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,c=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,u=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,f=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,l=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,d=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,h=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,p=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,v=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,y=255&t[16]|(255&t[17])<<8|(255&t[18])<<16|(255&t[19])<<24,m=255&t[20]|(255&t[21])<<8|(255&t[22])<<16|(255&t[23])<<24,g=255&t[24]|(255&t[25])<<8|(255&t[26])<<16|(255&t[27])<<24,E=255&t[28]|(255&t[29])<<8|(255&t[30])<<16|(255&t[31])<<24,b=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,O=0;O<20;O+=2)a^=(o=(m^=(o=(h^=(o=(u^=(o=a+m|0)<<7|o>>>25)+a|0)<<9|o>>>23)+u|0)<<13|o>>>19)+h|0)<<18|o>>>14,f^=(o=(i^=(o=(g^=(o=(p^=(o=f+i|0)<<7|o>>>25)+f|0)<<9|o>>>23)+p|0)<<13|o>>>19)+g|0)<<18|o>>>14,v^=(o=(l^=(o=(s^=(o=(E^=(o=v+l|0)<<7|o>>>25)+v|0)<<9|o>>>23)+E|0)<<13|o>>>19)+s|0)<<18|o>>>14,b^=(o=(y^=(o=(d^=(o=(c^=(o=b+y|0)<<7|o>>>25)+b|0)<<9|o>>>23)+c|0)<<13|o>>>19)+d|0)<<18|o>>>14,a^=(o=(c^=(o=(s^=(o=(i^=(o=a+c|0)<<7|o>>>25)+a|0)<<9|o>>>23)+i|0)<<13|o>>>19)+s|0)<<18|o>>>14,f^=(o=(u^=(o=(d^=(o=(l^=(o=f+u|0)<<7|o>>>25)+f|0)<<9|o>>>23)+l|0)<<13|o>>>19)+d|0)<<18|o>>>14,v^=(o=(p^=(o=(h^=(o=(y^=(o=v+p|0)<<7|o>>>25)+v|0)<<9|o>>>23)+y|0)<<13|o>>>19)+h|0)<<18|o>>>14,b^=(o=(E^=(o=(g^=(o=(m^=(o=b+E|0)<<7|o>>>25)+b|0)<<9|o>>>23)+m|0)<<13|o>>>19)+g|0)<<18|o>>>14;e[0]=a>>>0&255,e[1]=a>>>8&255,e[2]=a>>>16&255,e[3]=a>>>24&255,e[4]=f>>>0&255,e[5]=f>>>8&255,e[6]=f>>>16&255,e[7]=f>>>24&255,e[8]=v>>>0&255,e[9]=v>>>8&255,e[10]=v>>>16&255,e[11]=v>>>24&255,e[12]=b>>>0&255,e[13]=b>>>8&255,e[14]=b>>>16&255,e[15]=b>>>24&255,e[16]=l>>>0&255,e[17]=l>>>8&255,e[18]=l>>>16&255,e[19]=l>>>24&255,e[20]=d>>>0&255,e[21]=d>>>8&255,e[22]=d>>>16&255,e[23]=d>>>24&255,e[24]=h>>>0&255,e[25]=h>>>8&255,e[26]=h>>>16&255,e[27]=h>>>24&255,e[28]=p>>>0&255,e[29]=p>>>8&255,e[30]=p>>>16&255,e[31]=p>>>24&255}(e,n,t,r)}var b=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function O(e,n,t,r,o,a,i){var s,c,u=new Uint8Array(16),f=new Uint8Array(64);for(c=0;c<16;c++)u[c]=0;for(c=0;c<8;c++)u[c]=a[c];for(;o>=64;){for(g(f,u,i,b),c=0;c<64;c++)e[n+c]=t[r+c]^f[c];for(s=1,c=8;c<16;c++)s=s+(255&u[c])|0,u[c]=255&s,s>>>=8;o-=64,n+=64,r+=64}if(o>0)for(g(f,u,i,b),c=0;c=64;){for(g(c,s,o,b),i=0;i<64;i++)e[n+i]=c[i];for(a=1,i=8;i<16;i++)a=a+(255&s[i])|0,s[i]=255&a,a>>>=8;t-=64,n+=64}if(t>0)for(g(c,s,o,b),i=0;i>>13|t<<3),r=255&e[4]|(255&e[5])<<8,this.r[2]=7939&(t>>>10|r<<6),o=255&e[6]|(255&e[7])<<8,this.r[3]=8191&(r>>>7|o<<9),a=255&e[8]|(255&e[9])<<8,this.r[4]=255&(o>>>4|a<<12),this.r[5]=a>>>1&8190,i=255&e[10]|(255&e[11])<<8,this.r[6]=8191&(a>>>14|i<<2),s=255&e[12]|(255&e[13])<<8,this.r[7]=8065&(i>>>11|s<<5),c=255&e[14]|(255&e[15])<<8,this.r[8]=8191&(s>>>8|c<<8),this.r[9]=c>>>5&127,this.pad[0]=255&e[16]|(255&e[17])<<8,this.pad[1]=255&e[18]|(255&e[19])<<8,this.pad[2]=255&e[20]|(255&e[21])<<8,this.pad[3]=255&e[22]|(255&e[23])<<8,this.pad[4]=255&e[24]|(255&e[25])<<8,this.pad[5]=255&e[26]|(255&e[27])<<8,this.pad[6]=255&e[28]|(255&e[29])<<8,this.pad[7]=255&e[30]|(255&e[31])<<8};function T(e,n,t,r,o,a){var i=new _(a);return i.update(t,r,o),i.finish(e,n),0}function S(e,n,t,r,o,a){var i=new Uint8Array(16);return T(i,0,t,r,o,a),y(e,n,i,0)}function N(e,n,t,r,o){var a;if(t<32)return-1;for(D(e,0,n,0,t,r,o),T(e,16,e,32,t-32,e),a=0;a<16;a++)e[a]=0;return 0}function I(e,n,t,r,o){var a,i=new Uint8Array(32);if(t<32)return-1;if(w(i,0,32,r,o),0!==S(n,16,n,32,t-32,i))return-1;for(D(e,0,n,0,t,r,o),a=0;a<32;a++)e[a]=0;return 0}function x(e,n){var t;for(t=0;t<16;t++)e[t]=0|n[t]}function C(e){var n,t,r=1;for(n=0;n<16;n++)t=e[n]+r+65535,r=Math.floor(t/65536),e[n]=t-65536*r;e[0]+=r-1+37*(r-1)}function R(e,n,t){for(var r,o=~(t-1),a=0;a<16;a++)r=o&(e[a]^n[a]),e[a]^=r,n[a]^=r}function P(e,t){var r,o,a,i=n(),s=n();for(r=0;r<16;r++)s[r]=t[r];for(C(s),C(s),C(s),o=0;o<2;o++){for(i[0]=s[0]-65517,r=1;r<15;r++)i[r]=s[r]-65535-(i[r-1]>>16&1),i[r-1]&=65535;i[15]=s[15]-32767-(i[14]>>16&1),a=i[15]>>16&1,i[14]&=65535,R(s,i,1-a)}for(r=0;r<16;r++)e[2*r]=255&s[r],e[2*r+1]=s[r]>>8}function k(e,n){var t=new Uint8Array(32),r=new Uint8Array(32);return P(t,e),P(r,n),m(t,0,r,0)}function M(e){var n=new Uint8Array(32);return P(n,e),1&n[0]}function F(e,n){var t;for(t=0;t<16;t++)e[t]=n[2*t]+(n[2*t+1]<<8);e[15]&=32767}function L(e,n,t){for(var r=0;r<16;r++)e[r]=n[r]+t[r]}function H(e,n,t){for(var r=0;r<16;r++)e[r]=n[r]-t[r]}function j(e,n,t){var r,o,a=0,i=0,s=0,c=0,u=0,f=0,l=0,d=0,h=0,p=0,v=0,y=0,m=0,g=0,E=0,b=0,O=0,A=0,w=0,D=0,_=0,T=0,S=0,N=0,I=0,x=0,C=0,R=0,P=0,k=0,M=0,F=t[0],L=t[1],H=t[2],j=t[3],K=t[4],U=t[5],B=t[6],V=t[7],Y=t[8],G=t[9],J=t[10],q=t[11],W=t[12],z=t[13],Q=t[14],Z=t[15];a+=(r=n[0])*F,i+=r*L,s+=r*H,c+=r*j,u+=r*K,f+=r*U,l+=r*B,d+=r*V,h+=r*Y,p+=r*G,v+=r*J,y+=r*q,m+=r*W,g+=r*z,E+=r*Q,b+=r*Z,i+=(r=n[1])*F,s+=r*L,c+=r*H,u+=r*j,f+=r*K,l+=r*U,d+=r*B,h+=r*V,p+=r*Y,v+=r*G,y+=r*J,m+=r*q,g+=r*W,E+=r*z,b+=r*Q,O+=r*Z,s+=(r=n[2])*F,c+=r*L,u+=r*H,f+=r*j,l+=r*K,d+=r*U,h+=r*B,p+=r*V,v+=r*Y,y+=r*G,m+=r*J,g+=r*q,E+=r*W,b+=r*z,O+=r*Q,A+=r*Z,c+=(r=n[3])*F,u+=r*L,f+=r*H,l+=r*j,d+=r*K,h+=r*U,p+=r*B,v+=r*V,y+=r*Y,m+=r*G,g+=r*J,E+=r*q,b+=r*W,O+=r*z,A+=r*Q,w+=r*Z,u+=(r=n[4])*F,f+=r*L,l+=r*H,d+=r*j,h+=r*K,p+=r*U,v+=r*B,y+=r*V,m+=r*Y,g+=r*G,E+=r*J,b+=r*q,O+=r*W,A+=r*z,w+=r*Q,D+=r*Z,f+=(r=n[5])*F,l+=r*L,d+=r*H,h+=r*j,p+=r*K,v+=r*U,y+=r*B,m+=r*V,g+=r*Y,E+=r*G,b+=r*J,O+=r*q,A+=r*W,w+=r*z,D+=r*Q,_+=r*Z,l+=(r=n[6])*F,d+=r*L,h+=r*H,p+=r*j,v+=r*K,y+=r*U,m+=r*B,g+=r*V,E+=r*Y,b+=r*G,O+=r*J,A+=r*q,w+=r*W,D+=r*z,_+=r*Q,T+=r*Z,d+=(r=n[7])*F,h+=r*L,p+=r*H,v+=r*j,y+=r*K,m+=r*U,g+=r*B,E+=r*V,b+=r*Y,O+=r*G,A+=r*J,w+=r*q,D+=r*W,_+=r*z,T+=r*Q,S+=r*Z,h+=(r=n[8])*F,p+=r*L,v+=r*H,y+=r*j,m+=r*K,g+=r*U,E+=r*B,b+=r*V,O+=r*Y,A+=r*G,w+=r*J,D+=r*q,_+=r*W,T+=r*z,S+=r*Q,N+=r*Z,p+=(r=n[9])*F,v+=r*L,y+=r*H,m+=r*j,g+=r*K,E+=r*U,b+=r*B,O+=r*V,A+=r*Y,w+=r*G,D+=r*J,_+=r*q,T+=r*W,S+=r*z,N+=r*Q,I+=r*Z,v+=(r=n[10])*F,y+=r*L,m+=r*H,g+=r*j,E+=r*K,b+=r*U,O+=r*B,A+=r*V,w+=r*Y,D+=r*G,_+=r*J,T+=r*q,S+=r*W,N+=r*z,I+=r*Q,x+=r*Z,y+=(r=n[11])*F,m+=r*L,g+=r*H,E+=r*j,b+=r*K,O+=r*U,A+=r*B,w+=r*V,D+=r*Y,_+=r*G,T+=r*J,S+=r*q,N+=r*W,I+=r*z,x+=r*Q,C+=r*Z,m+=(r=n[12])*F,g+=r*L,E+=r*H,b+=r*j,O+=r*K,A+=r*U,w+=r*B,D+=r*V,_+=r*Y,T+=r*G,S+=r*J,N+=r*q,I+=r*W,x+=r*z,C+=r*Q,R+=r*Z,g+=(r=n[13])*F,E+=r*L,b+=r*H,O+=r*j,A+=r*K,w+=r*U,D+=r*B,_+=r*V,T+=r*Y,S+=r*G,N+=r*J,I+=r*q,x+=r*W,C+=r*z,R+=r*Q,P+=r*Z,E+=(r=n[14])*F,b+=r*L,O+=r*H,A+=r*j,w+=r*K,D+=r*U,_+=r*B,T+=r*V,S+=r*Y,N+=r*G,I+=r*J,x+=r*q,C+=r*W,R+=r*z,P+=r*Q,k+=r*Z,b+=(r=n[15])*F,i+=38*(A+=r*H),s+=38*(w+=r*j),c+=38*(D+=r*K),u+=38*(_+=r*U),f+=38*(T+=r*B),l+=38*(S+=r*V),d+=38*(N+=r*Y),h+=38*(I+=r*G),p+=38*(x+=r*J),v+=38*(C+=r*q),y+=38*(R+=r*W),m+=38*(P+=r*z),g+=38*(k+=r*Q),E+=38*(M+=r*Z),a=(r=(a+=38*(O+=r*L))+(o=1)+65535)-65536*(o=Math.floor(r/65536)),i=(r=i+o+65535)-65536*(o=Math.floor(r/65536)),s=(r=s+o+65535)-65536*(o=Math.floor(r/65536)),c=(r=c+o+65535)-65536*(o=Math.floor(r/65536)),u=(r=u+o+65535)-65536*(o=Math.floor(r/65536)),f=(r=f+o+65535)-65536*(o=Math.floor(r/65536)),l=(r=l+o+65535)-65536*(o=Math.floor(r/65536)),d=(r=d+o+65535)-65536*(o=Math.floor(r/65536)),h=(r=h+o+65535)-65536*(o=Math.floor(r/65536)),p=(r=p+o+65535)-65536*(o=Math.floor(r/65536)),v=(r=v+o+65535)-65536*(o=Math.floor(r/65536)),y=(r=y+o+65535)-65536*(o=Math.floor(r/65536)),m=(r=m+o+65535)-65536*(o=Math.floor(r/65536)),g=(r=g+o+65535)-65536*(o=Math.floor(r/65536)),E=(r=E+o+65535)-65536*(o=Math.floor(r/65536)),b=(r=b+o+65535)-65536*(o=Math.floor(r/65536)),a=(r=(a+=o-1+37*(o-1))+(o=1)+65535)-65536*(o=Math.floor(r/65536)),i=(r=i+o+65535)-65536*(o=Math.floor(r/65536)),s=(r=s+o+65535)-65536*(o=Math.floor(r/65536)),c=(r=c+o+65535)-65536*(o=Math.floor(r/65536)),u=(r=u+o+65535)-65536*(o=Math.floor(r/65536)),f=(r=f+o+65535)-65536*(o=Math.floor(r/65536)),l=(r=l+o+65535)-65536*(o=Math.floor(r/65536)),d=(r=d+o+65535)-65536*(o=Math.floor(r/65536)),h=(r=h+o+65535)-65536*(o=Math.floor(r/65536)),p=(r=p+o+65535)-65536*(o=Math.floor(r/65536)),v=(r=v+o+65535)-65536*(o=Math.floor(r/65536)),y=(r=y+o+65535)-65536*(o=Math.floor(r/65536)),m=(r=m+o+65535)-65536*(o=Math.floor(r/65536)),g=(r=g+o+65535)-65536*(o=Math.floor(r/65536)),E=(r=E+o+65535)-65536*(o=Math.floor(r/65536)),b=(r=b+o+65535)-65536*(o=Math.floor(r/65536)),a+=o-1+37*(o-1),e[0]=a,e[1]=i,e[2]=s,e[3]=c,e[4]=u,e[5]=f,e[6]=l,e[7]=d,e[8]=h,e[9]=p,e[10]=v,e[11]=y,e[12]=m,e[13]=g,e[14]=E,e[15]=b}function K(e,n){j(e,n,n)}function U(e,t){var r,o=n();for(r=0;r<16;r++)o[r]=t[r];for(r=253;r>=0;r--)K(o,o),2!==r&&4!==r&&j(o,o,t);for(r=0;r<16;r++)e[r]=o[r]}function B(e,t){var r,o=n();for(r=0;r<16;r++)o[r]=t[r];for(r=250;r>=0;r--)K(o,o),1!==r&&j(o,o,t);for(r=0;r<16;r++)e[r]=o[r]}function V(e,t,r){var o,a,i=new Uint8Array(32),c=new Float64Array(80),u=n(),f=n(),l=n(),d=n(),h=n(),p=n();for(a=0;a<31;a++)i[a]=t[a];for(i[31]=127&t[31]|64,i[0]&=248,F(c,r),a=0;a<16;a++)f[a]=c[a],d[a]=u[a]=l[a]=0;for(u[0]=d[0]=1,a=254;a>=0;--a)R(u,f,o=i[a>>>3]>>>(7&a)&1),R(l,d,o),L(h,u,l),H(u,u,l),L(l,f,d),H(f,f,d),K(d,h),K(p,u),j(u,l,u),j(l,f,h),L(h,u,l),H(u,u,l),K(f,u),H(l,d,p),j(u,l,s),L(u,u,d),j(l,l,u),j(u,d,p),j(d,f,c),K(f,h),R(u,f,o),R(l,d,o);for(a=0;a<16;a++)c[a+16]=u[a],c[a+32]=l[a],c[a+48]=f[a],c[a+64]=d[a];var v=c.subarray(32),y=c.subarray(16);return U(v,v),j(y,y,v),P(e,y),0}function Y(e,n){return V(e,n,o)}function G(e,n){return t(n,32),Y(e,n)}function J(e,n,t){var o=new Uint8Array(32);return V(o,t,n),E(e,r,o,b)}_.prototype.blocks=function(e,n,t){for(var r,o,a,i,s,c,u,f,l,d,h,p,v,y,m,g,E,b,O,A=this.fin?0:2048,w=this.h[0],D=this.h[1],_=this.h[2],T=this.h[3],S=this.h[4],N=this.h[5],I=this.h[6],x=this.h[7],C=this.h[8],R=this.h[9],P=this.r[0],k=this.r[1],M=this.r[2],F=this.r[3],L=this.r[4],H=this.r[5],j=this.r[6],K=this.r[7],U=this.r[8],B=this.r[9];t>=16;)d=l=0,d+=(w+=8191&(r=255&e[n+0]|(255&e[n+1])<<8))*P,d+=(D+=8191&(r>>>13|(o=255&e[n+2]|(255&e[n+3])<<8)<<3))*(5*B),d+=(_+=8191&(o>>>10|(a=255&e[n+4]|(255&e[n+5])<<8)<<6))*(5*U),d+=(T+=8191&(a>>>7|(i=255&e[n+6]|(255&e[n+7])<<8)<<9))*(5*K),l=(d+=(S+=8191&(i>>>4|(s=255&e[n+8]|(255&e[n+9])<<8)<<12))*(5*j))>>>13,d&=8191,d+=(N+=s>>>1&8191)*(5*H),d+=(I+=8191&(s>>>14|(c=255&e[n+10]|(255&e[n+11])<<8)<<2))*(5*L),d+=(x+=8191&(c>>>11|(u=255&e[n+12]|(255&e[n+13])<<8)<<5))*(5*F),d+=(C+=8191&(u>>>8|(f=255&e[n+14]|(255&e[n+15])<<8)<<8))*(5*M),h=l+=(d+=(R+=f>>>5|A)*(5*k))>>>13,h+=w*k,h+=D*P,h+=_*(5*B),h+=T*(5*U),l=(h+=S*(5*K))>>>13,h&=8191,h+=N*(5*j),h+=I*(5*H),h+=x*(5*L),h+=C*(5*F),l+=(h+=R*(5*M))>>>13,h&=8191,p=l,p+=w*M,p+=D*k,p+=_*P,p+=T*(5*B),l=(p+=S*(5*U))>>>13,p&=8191,p+=N*(5*K),p+=I*(5*j),p+=x*(5*H),p+=C*(5*L),v=l+=(p+=R*(5*F))>>>13,v+=w*F,v+=D*M,v+=_*k,v+=T*P,l=(v+=S*(5*B))>>>13,v&=8191,v+=N*(5*U),v+=I*(5*K),v+=x*(5*j),v+=C*(5*H),y=l+=(v+=R*(5*L))>>>13,y+=w*L,y+=D*F,y+=_*M,y+=T*k,l=(y+=S*P)>>>13,y&=8191,y+=N*(5*B),y+=I*(5*U),y+=x*(5*K),y+=C*(5*j),m=l+=(y+=R*(5*H))>>>13,m+=w*H,m+=D*L,m+=_*F,m+=T*M,l=(m+=S*k)>>>13,m&=8191,m+=N*P,m+=I*(5*B),m+=x*(5*U),m+=C*(5*K),g=l+=(m+=R*(5*j))>>>13,g+=w*j,g+=D*H,g+=_*L,g+=T*F,l=(g+=S*M)>>>13,g&=8191,g+=N*k,g+=I*P,g+=x*(5*B),g+=C*(5*U),E=l+=(g+=R*(5*K))>>>13,E+=w*K,E+=D*j,E+=_*H,E+=T*L,l=(E+=S*F)>>>13,E&=8191,E+=N*M,E+=I*k,E+=x*P,E+=C*(5*B),b=l+=(E+=R*(5*U))>>>13,b+=w*U,b+=D*K,b+=_*j,b+=T*H,l=(b+=S*L)>>>13,b&=8191,b+=N*F,b+=I*M,b+=x*k,b+=C*P,O=l+=(b+=R*(5*B))>>>13,O+=w*B,O+=D*U,O+=_*K,O+=T*j,l=(O+=S*H)>>>13,O&=8191,O+=N*L,O+=I*F,O+=x*M,O+=C*k,w=d=8191&(l=(l=((l+=(O+=R*P)>>>13)<<2)+l|0)+(d&=8191)|0),D=h+=l>>>=13,_=p&=8191,T=v&=8191,S=y&=8191,N=m&=8191,I=g&=8191,x=E&=8191,C=b&=8191,R=O&=8191,n+=16,t-=16;this.h[0]=w,this.h[1]=D,this.h[2]=_,this.h[3]=T,this.h[4]=S,this.h[5]=N,this.h[6]=I,this.h[7]=x,this.h[8]=C,this.h[9]=R},_.prototype.finish=function(e,n){var t,r,o,a,i=new Uint16Array(10);if(this.leftover){for(a=this.leftover,this.buffer[a++]=1;a<16;a++)this.buffer[a]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(t=this.h[1]>>>13,this.h[1]&=8191,a=2;a<10;a++)this.h[a]+=t,t=this.h[a]>>>13,this.h[a]&=8191;for(this.h[0]+=5*t,t=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=t,t=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=t,i[0]=this.h[0]+5,t=i[0]>>>13,i[0]&=8191,a=1;a<10;a++)i[a]=this.h[a]+t,t=i[a]>>>13,i[a]&=8191;for(i[9]-=8192,r=(1^t)-1,a=0;a<10;a++)i[a]&=r;for(r=~r,a=0;a<10;a++)this.h[a]=this.h[a]&r|i[a];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),o=this.h[0]+this.pad[0],this.h[0]=65535&o,a=1;a<8;a++)o=(this.h[a]+this.pad[a]|0)+(o>>>16)|0,this.h[a]=65535&o;e[n+0]=this.h[0]>>>0&255,e[n+1]=this.h[0]>>>8&255,e[n+2]=this.h[1]>>>0&255,e[n+3]=this.h[1]>>>8&255,e[n+4]=this.h[2]>>>0&255,e[n+5]=this.h[2]>>>8&255,e[n+6]=this.h[3]>>>0&255,e[n+7]=this.h[3]>>>8&255,e[n+8]=this.h[4]>>>0&255,e[n+9]=this.h[4]>>>8&255,e[n+10]=this.h[5]>>>0&255,e[n+11]=this.h[5]>>>8&255,e[n+12]=this.h[6]>>>0&255,e[n+13]=this.h[6]>>>8&255,e[n+14]=this.h[7]>>>0&255,e[n+15]=this.h[7]>>>8&255},_.prototype.update=function(e,n,t){var r,o;if(this.leftover){for((o=16-this.leftover)>t&&(o=t),r=0;r=16&&(o=t-t%16,this.blocks(e,n,o),n+=o,t-=o),t){for(r=0;r=128;){for(A=0;A<16;A++)w=8*A+W,x[A]=t[w+0]<<24|t[w+1]<<16|t[w+2]<<8|t[w+3],C[A]=t[w+4]<<24|t[w+5]<<16|t[w+6]<<8|t[w+7];for(A=0;A<80;A++)if(o=R,a=P,i=k,s=M,c=F,u=L,f=H,j,d=K,h=U,p=B,v=V,y=Y,m=G,g=J,q,T=65535&(_=q),S=_>>>16,N=65535&(D=j),I=D>>>16,T+=65535&(_=(Y>>>14|F<<18)^(Y>>>18|F<<14)^(F>>>9|Y<<23)),S+=_>>>16,N+=65535&(D=(F>>>14|Y<<18)^(F>>>18|Y<<14)^(Y>>>9|F<<23)),I+=D>>>16,T+=65535&(_=Y&G^~Y&J),S+=_>>>16,N+=65535&(D=F&L^~F&H),I+=D>>>16,T+=65535&(_=z[2*A+1]),S+=_>>>16,N+=65535&(D=z[2*A]),I+=D>>>16,D=x[A%16],S+=(_=C[A%16])>>>16,N+=65535&D,I+=D>>>16,N+=(S+=(T+=65535&_)>>>16)>>>16,T=65535&(_=O=65535&T|S<<16),S=_>>>16,N=65535&(D=b=65535&N|(I+=N>>>16)<<16),I=D>>>16,T+=65535&(_=(K>>>28|R<<4)^(R>>>2|K<<30)^(R>>>7|K<<25)),S+=_>>>16,N+=65535&(D=(R>>>28|K<<4)^(K>>>2|R<<30)^(K>>>7|R<<25)),I+=D>>>16,S+=(_=K&U^K&B^U&B)>>>16,N+=65535&(D=R&P^R&k^P&k),I+=D>>>16,l=65535&(N+=(S+=(T+=65535&_)>>>16)>>>16)|(I+=N>>>16)<<16,E=65535&T|S<<16,T=65535&(_=v),S=_>>>16,N=65535&(D=s),I=D>>>16,S+=(_=O)>>>16,N+=65535&(D=b),I+=D>>>16,P=o,k=a,M=i,F=s=65535&(N+=(S+=(T+=65535&_)>>>16)>>>16)|(I+=N>>>16)<<16,L=c,H=u,j=f,R=l,U=d,B=h,V=p,Y=v=65535&T|S<<16,G=y,J=m,q=g,K=E,A%16==15)for(w=0;w<16;w++)D=x[w],T=65535&(_=C[w]),S=_>>>16,N=65535&D,I=D>>>16,D=x[(w+9)%16],T+=65535&(_=C[(w+9)%16]),S+=_>>>16,N+=65535&D,I+=D>>>16,b=x[(w+1)%16],T+=65535&(_=((O=C[(w+1)%16])>>>1|b<<31)^(O>>>8|b<<24)^(O>>>7|b<<25)),S+=_>>>16,N+=65535&(D=(b>>>1|O<<31)^(b>>>8|O<<24)^b>>>7),I+=D>>>16,b=x[(w+14)%16],S+=(_=((O=C[(w+14)%16])>>>19|b<<13)^(b>>>29|O<<3)^(O>>>6|b<<26))>>>16,N+=65535&(D=(b>>>19|O<<13)^(O>>>29|b<<3)^b>>>6),I+=D>>>16,I+=(N+=(S+=(T+=65535&_)>>>16)>>>16)>>>16,x[w]=65535&N|I<<16,C[w]=65535&T|S<<16;T=65535&(_=K),S=_>>>16,N=65535&(D=R),I=D>>>16,D=e[0],S+=(_=n[0])>>>16,N+=65535&D,I+=D>>>16,I+=(N+=(S+=(T+=65535&_)>>>16)>>>16)>>>16,e[0]=R=65535&N|I<<16,n[0]=K=65535&T|S<<16,T=65535&(_=U),S=_>>>16,N=65535&(D=P),I=D>>>16,D=e[1],S+=(_=n[1])>>>16,N+=65535&D,I+=D>>>16,I+=(N+=(S+=(T+=65535&_)>>>16)>>>16)>>>16,e[1]=P=65535&N|I<<16,n[1]=U=65535&T|S<<16,T=65535&(_=B),S=_>>>16,N=65535&(D=k),I=D>>>16,D=e[2],S+=(_=n[2])>>>16,N+=65535&D,I+=D>>>16,I+=(N+=(S+=(T+=65535&_)>>>16)>>>16)>>>16,e[2]=k=65535&N|I<<16,n[2]=B=65535&T|S<<16,T=65535&(_=V),S=_>>>16,N=65535&(D=M),I=D>>>16,D=e[3],S+=(_=n[3])>>>16,N+=65535&D,I+=D>>>16,I+=(N+=(S+=(T+=65535&_)>>>16)>>>16)>>>16,e[3]=M=65535&N|I<<16,n[3]=V=65535&T|S<<16,T=65535&(_=Y),S=_>>>16,N=65535&(D=F),I=D>>>16,D=e[4],S+=(_=n[4])>>>16,N+=65535&D,I+=D>>>16,I+=(N+=(S+=(T+=65535&_)>>>16)>>>16)>>>16,e[4]=F=65535&N|I<<16,n[4]=Y=65535&T|S<<16,T=65535&(_=G),S=_>>>16,N=65535&(D=L),I=D>>>16,D=e[5],S+=(_=n[5])>>>16,N+=65535&D,I+=D>>>16,I+=(N+=(S+=(T+=65535&_)>>>16)>>>16)>>>16,e[5]=L=65535&N|I<<16,n[5]=G=65535&T|S<<16,T=65535&(_=J),S=_>>>16,N=65535&(D=H),I=D>>>16,D=e[6],S+=(_=n[6])>>>16,N+=65535&D,I+=D>>>16,I+=(N+=(S+=(T+=65535&_)>>>16)>>>16)>>>16,e[6]=H=65535&N|I<<16,n[6]=J=65535&T|S<<16,T=65535&(_=q),S=_>>>16,N=65535&(D=j),I=D>>>16,D=e[7],S+=(_=n[7])>>>16,N+=65535&D,I+=D>>>16,I+=(N+=(S+=(T+=65535&_)>>>16)>>>16)>>>16,e[7]=j=65535&N|I<<16,n[7]=q=65535&T|S<<16,W+=128,r-=128}return r}function Z(e,n,t){var r,o=new Int32Array(8),a=new Int32Array(8),i=new Uint8Array(256),s=t;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,a[0]=4089235720,a[1]=2227873595,a[2]=4271175723,a[3]=1595750129,a[4]=2917565137,a[5]=725511199,a[6]=4215389547,a[7]=327033209,Q(o,a,n,t),t%=128,r=0;r=0;--o)$(e,n,r=t[o/8|0]>>(7&o)&1),X(n,e),X(e,e),$(e,n,r)}function te(e,t){var r=[n(),n(),n(),n()];x(r[0],l),x(r[1],d),x(r[2],i),j(r[3],l,d),ne(e,r,t)}function re(e,r,o){var a,i=new Uint8Array(64),s=[n(),n(),n(),n()];for(o||t(r,32),Z(i,r,32),i[0]&=248,i[31]&=127,i[31]|=64,te(s,i),ee(e,s),a=0;a<32;a++)r[a+32]=e[a];return 0}var oe=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function ae(e,n){var t,r,o,a;for(r=63;r>=32;--r){for(t=0,o=r-32,a=r-12;o>4)*oe[o],t=n[o]>>8,n[o]&=255;for(o=0;o<32;o++)n[o]-=t*oe[o];for(r=0;r<32;r++)n[r+1]+=n[r]>>8,e[r]=255&n[r]}function ie(e){var n,t=new Float64Array(64);for(n=0;n<64;n++)t[n]=e[n];for(n=0;n<64;n++)e[n]=0;ae(e,t)}function se(e,t,r,o){var a,i,s=new Uint8Array(64),c=new Uint8Array(64),u=new Uint8Array(64),f=new Float64Array(64),l=[n(),n(),n(),n()];Z(s,o,32),s[0]&=248,s[31]&=127,s[31]|=64;var d=r+64;for(a=0;a>7&&H(e[0],a,e[0]),j(e[3],e[0],e[1]),0)}(d,o))return-1;for(s=0;s=0},e.sign.keyPair=function(){var e=new Uint8Array(le),n=new Uint8Array(de);return re(e,n),{publicKey:e,secretKey:n}},e.sign.keyPair.fromSecretKey=function(e){if(pe(e),e.length!==de)throw new Error("bad secret key size");for(var n=new Uint8Array(le),t=0;t{if(Array.isArray(n))return n.map(e);if(n instanceof Object){let t=[],r=[];return Object.keys(n).forEach(e=>{/^(0|[1-9][0-9]*)$/.test(e)?t.push(+e):r.push(e)}),t.sort(function(e,n){return e-n}).concat(r.sort()).reduce((t,r)=>(t[r]=e(n[r]),t),{})}return n},n=JSON.stringify.bind(JSON);return y=(t,r,o)=>{let a=n(t,r,0);if(!a||"{"!==a[0]&&"["!==a[0])return a;let i=JSON.parse(a);return n(e(i),null,o)}}())}function T(){return b||(b=1,function(e){e.exports&&(e.exports=function(e,n){const t=globalThis;var r,o={},a=void 0===t.Proxy,i=o.DeepProxy=function(){var e={},r=e.isArray=Array.isArray||function(e){return"[object Array]"===Object.toString(e)},o=e.type=function(e){return null===e?"null":r(e)?"array":typeof e},i=e.isProxyable=function(e,n){return(void 0!==n||!a)&&-1!==["object","array"].indexOf(o(e))},s=e.set=function(n){return function(t,r,o){if("on"===r)throw new Error("'on' is a reserved attribute name for realtime lists and maps");return i(o)?t[r]=e.create(o,n):t[r]=o,n(),t[r]||!0}},c=e.pathMatches=function(e,n){return!n.some(function(n,t){return n!==e[t]})},u=function(e,n){return n.pattern.length-e.pattern.length},f=function(e){return function(n,t,r){switch(n){case"change":t="array"===o(t)?t:[t],e.change.push({cb:function(e,n,o,a){if(c(o,t))return r(e,n,o,a)},pattern:t}),e.change.sort(u);break;case"remove":t="array"===o(t)?t:[t],e.remove.push({cb:function(e,n,o){if(c(n,t))return r(e,n,o)},pattern:t}),e.remove.sort(u);break;case"ready":e.ready.push({cb:function(e){t(e)}});break;case"cacheready":e.cacheready.push({cb:function(e){t(e)}});break;case"disconnect":e.disconnect.push({cb:function(e){t(e)}});break;case"reconnect":e.reconnect.push({cb:function(e){t(e)}});break;case"create":e.create.push({cb:function(e){t(e)}});break;case"error":e.error.push({cb:function(e){t(e)}})}return this}},l=e.get=function(){var e={cacheready:[],disconnect:[],reconnect:[],change:[],ready:[],remove:[],create:[],error:[]};return function(n,t){return"on"===t?f(e):"_isProxy"===t||("_events"===t?e:n[t])}},d=e.delete=function(e){return function(n,t){return void 0===n[t]||(delete n[t],e()),!0}},h=e.handlers=function(e,n){return n?{set:s(e),get:l(e),deleteProperty:d(e)}:{set:s(e),get:function(e,n){return"_isProxy"===n||e[n]},deleteProperty:d(e)}},p=e.remoteChangeFlag=!1,v=e.stringifyFakeProxy=function(e){var t=JSON.parse(n(e));return delete t._events,delete t._isProxy,n(t)};e.checkLocalChange=function(n,r){if(a&&!e.interval){var o=v(n);e.interval=t.setInterval(function(){var e=v(n);e!==o&&(o=e,p?p=!1:r())},300)}};var y=e.create=function(e,n,r){var s="function"===o(n)?h(n,r):n;switch(o(e)){case"object":Object.keys(e).forEach(function(t){i(e[t])&&!e[t]._isProxy&&(e[t]=y(e[t],n))});break;case"array":e.forEach(function(t,r){i(t)&&!t._isProxy&&(e[r]=y(e[r],n))});break;default:throw new Error("attempted to make a proxy of an unproxyable object")}if(!a)return e._isProxy?e:new t.Proxy(e,s);var c=JSON.parse(JSON.stringify(e));if(r){var u={cacheready:[],disconnect:[],reconnect:[],change:[],ready:[],remove:[],create:[],error:[]};c.on=f(u),c._events=u}return c},m=function(e,n,t,r,o){var a=e.slice(0);a.push(n),t._events.change.some(function(e){return!1===e.cb(r,o,a,t)})},g=e.find=function(e,n){for(var t=n.length,r=0;rs)for(var c,u=s;u<=s;u++)c=e[u],E(r,u,a,c,!0);e.length=s}};return e.update=function(e,n,t){var r=o(e),a=o(n);if(r!==a)throw new Error("Proxy updates can't result in type changes");switch(a){case"array":O.call(e,e,n,function(e){return y(e,t)},[],e);break;case"object":b.call(e,e,n,function(e){return y(e,t)},[],e);break;default:throw new Error("unsupported realtime datatype:"+a)}},e}();return o.create=function(o){if(!i.isProxyable(o.data,!0))throw new Error("unsupported datatype: "+i.type(o.data));if("function"!=typeof(r=o.ChainPad||t.ChainPad).SmartJSONTransformer)throw new Error("Please update ChainPad");o.classic&&!o.crypto&&(console.error("[chainpad-listmap] no crypto module provided. messages will not be encrypted"),o.crypto={encrypt:function(e){return e},decrypt:function(e){return e}});var s=o.readOnly,c={initialState:n(o.data),patchTransformer:r.SmartJSONTransformer,validateContent:o.validateContent||function(e){try{return JSON.parse(e),!0}catch(n){return console.log(e),console.error("Failed to parse, rejecting patch"),!1}},readOnly:o.readOnly,userName:o.userName||"listmap",Cache:o.Cache,logLevel:void 0===o.logLevel?0:o.logLevel};o.classic&&(c.channel=o.channel,c.crypto=o.crypto,c.network=o.network,c.websocketURL=o.websocketURL,c.metadata=o.metadata||{validateKey:o.validateKey,owners:o.owners,expire:o.expire},c.onRejected=o.onRejected);var u,f,l,d={metadata:{}},h=!0,p=!1,v=a?i.stringifyFakeProxy:n,y=function(){var e=v(f);try{u.contentUpdate(e)}catch(e){f._events.error.forEach(function(n){n.cb({type:"CHAINPAD",error:e.message})})}o.onLocal&&o.onLocal()},m=c.onLocal=function(e){h||s||(clearTimeout(l),e?y():l=setTimeout(y))},g=function(){i.remoteChangeFlag||m()};f=i.create(o.data,g,!0),c.onInit=function(e){f._events.create.forEach(function(n){n.cb(e)})},c.onCacheReady=function(e){u&&u===e.realtime||(u=d.realtime=e.realtime);var n=u.getUserDoc(),t=JSON.parse(n);i.update(f,t,g),i.checkLocalChange(f,m),p||f._events.cacheready.forEach(function(n){n.cb(e)})};var E=0;c.onReady=function(e){if(E=-1,p)return h=!1,c.onRemote(),void f._events.reconnect.forEach(function(n){n.cb(e)});u&&u===e.realtime||(u=d.realtime=e.realtime),d.metadata=e.metadata;var n=u.getUserDoc(),t=JSON.parse(n);i.update(f,t,g),i.checkLocalChange(f,m),h=!1,p=!0,f._events.ready.forEach(function(n){n.cb(e)})},c.onRemote=function(){if(!h){var e=u.getUserDoc(),n=JSON.parse(e);i.remoteChangeFlag=!0,i.update(f,n,g),i.remoteChangeFlag=!1}},c.onMessage=function(){-1!==E&&o.updateProgress&&o.updateProgress({progress:E++})},c.onAbort=function(e){f._events.disconnect.forEach(function(n){n.cb(e)})},c.onConnectionChange=function(e){e.state?h=!0:f._events.disconnect.forEach(function(n){n.cb(e)})},c.onMetadataUpdate=function(e){d.metadata=e,"function"==typeof o.onMetadataUpdate&&o.onMetadataUpdate(e)},c.onError=function(e){f._events.error.forEach(function(n){n.cb(e)})},c.onChannelError=function(e){f._events.error.forEach(function(n){n.cb(e)})},o.common&&"function"==typeof o.common.startRealtime?u=d.cpCnInner=o.common.startRealtime(c):d=e.start(c),d.proxy=f,d.realtime=u;var b=d.setReadOnly;return d.setReadOnly=function(e,n){s=e,b&&b(e,n)},d},o}(D(),_()))}(i)),i.exports}var S,N=T(),I={exports:{}};function x(){return S||(S=1,function(e){var n,r,o,a;a=function(){var e=f,n=function(t,r,o){r||(r=0);var a=n.resolve(t,r),i=n.m[r][a];if(!i&&e){if(i=e(a))return i}else if(i&&i.c&&(r=i.c,a=i.m,!(i=n.m[r][i.m])))throw new Error('failed to require "'+a+'" from '+r);if(!i)throw new Error('failed to require "'+t+'" from '+o);return i.exports||(i.exports={},i.call(i.exports,i,i.exports,n.relative(a,r))),i.exports};return n.resolve=function(e,t){var r=e,o=e+".js",a=e+"/index.js";return n.m[t][o]&&o?o:n.m[t][a]&&a?a:r},n.relative=function(e,t){return function(r){if("."!=r.charAt(0))return n(r,t,e);var o=e.split("/"),a=r.split("/");o.pop();for(var i=0;i=0;t--)o.check(e.operations[t],n),t>0&&r.assert(!o.shouldMerge(e.operations[t],e.operations[t-1])),"number"==typeof n&&(n+=o.lengthChange(e.operations[t]));return e.isCheckpoint&&(r.assert(1===e.operations.length),r.assert(0===e.operations[0].offset),"number"==typeof n&&r.assert(!n||e.operations[0].toRemove===n)),e};i.toObj=function(e){r.PARANOIA&&c(e);var n,t=new Array(e.operations.length+1);for(n=0;n0);var t,i=s(a.check(e[e.length-1]),n);for(t=0;t=0;t--)f(e,n.operations[t]);return e},i.apply=function(e,n){r.PARANOIA&&(c(e),r.assert("string"==typeof n),r.assert(a.hex_sha256(n)===e.parentHash));for(var t=n,i=e.operations.length-1;i>=0;i--)t=o.apply(e.operations[i],t);return t},i.lengthChange=function(e){r.PARANOIA&&c(e);for(var n=0,t=0;t=0;u--)i[u]=o.invert(e.operations[u],t),t=o.apply(e.operations[u],t);var f=new Array(e.operations.length);!function(){for(var e=i.length-1;e>=0;e--){f[e]=i[e].offset;for(var n=e-1;n>=0;n--)f[e]+=i[n].toRemove-i[n].toInsert.length}}();var l=s(a.hex_sha256(t),e.isCheckpoint);l.operations.splice(0,l.operations.length);for(var d=0;d=0;d--){var h=t(e.operations[d],u,o.simplify);h&&(u=o.apply(h,u),f[l++]=h)}return Array.prototype.push.apply(i.operations,f.reverse()),i.operations[0]||i.operations.shift(),r.PARANOIA&&c(i),i},i.equals=function(e,n){if(e.operations.length!==n.operations.length)return!1;for(var t=0;t0;){var u=o.random(i);i+=o.lengthChange(u),f(t,u)}return c(t),t},Object.freeze(e.exports)},"SHA256.js":function(e,n,t){!function(){function n(e,n){var t=(65535&e)+(65535&n);return(e>>16)+(n>>16)+(t>>16)<<16|65535&t}function t(e,n){return e>>>n|e<<32-n}function r(e,n){return e>>>n}function o(e,n,t){return e&n^~e&t}function a(e,n,t){return e&n^e&t^n&t}function i(e){return t(e,2)^t(e,13)^t(e,22)}function s(e){return t(e,6)^t(e,11)^t(e,25)}function c(e){return t(e,7)^t(e,18)^r(e,3)}function u(e){return t(e,17)^t(e,19)^r(e,10)}e.exports.hex_sha256=function(e){return function(e){for(var n="0123456789abcdef",t="",r=0;r<4*e.length;r++)t+=n.charAt(e[r>>2]>>8*(3-r%4)+4&15)+n.charAt(e[r>>2]>>8*(3-r%4)&15);return t}(function(e,t){var r,f,l,d,h,p,v,y,m,g,E=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],b=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],O=function(e){for(var n=[];e>0;e--)n.push(void 0);return n}(64);e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var A=0;A>5]|=(255&e.charCodeAt(t/8))<<24-t%32;return n}(e),8*e.length))}}()},"Common.js":function(e,n,r){e.exports.global=function(){if("undefined"!=typeof self)return self;if(void 0!==t)return t;if("undefined"!=typeof window)return window;throw new Error("no self, nor global, nor window")}();var o=function(n){return"undefined"!=typeof localStorage&&localStorage[n]?localStorage[n]:e.exports.global[n]},a=e.exports.PARANOIA=o("ChainPad_PARANOIA");e.exports.VALIDATE_ENTIRE_CHAIN_EACH_MSG=o("ChainPad_VALIDATE_ENTIRE_CHAIN_EACH_MSG"),e.exports.TESTING=o("ChainPad_TESTING"),e.exports.assert=function(e){if(!e)throw new Error("Failed assertion")},e.exports.isUint=function(e){return"number"==typeof e&&Math.floor(e)===e&&e>=0},e.exports.randomASCII=function(e){for(var n=[],t=0;tn?1:-1},Object.freeze(e.exports)},"sha256.js":function(e,n,t){var r=t("./sha256/exports.js"),o=t("./SHA256.js"),a=t("./Common");e.exports.check=function(e){if("string"!=typeof e)throw new Error;if(!/[a-f0-9]{64}/.test(e))throw new Error;return e},e.exports.hex_sha256=function(e){e+="";var n=r.hex(function(e){for(var n=new Uint8Array(e.length),t=0;t1&&console.log("["+e.userName+"] "+n)},d=function(e,n){e.logLevel>0&&console.error("["+e.userName+"] "+n)},h=function(e,n,t){if(!e.aborted){t||(t=Math.floor(2*Math.random()*e.config.avgSyncMilliseconds));var r=setTimeout(function(){e.schedules.splice(e.schedules.indexOf(r),1),n()},t);return e.schedules.push(r),r}},p=function(e,n){var t=e.schedules.indexOf(n);t>-1&&e.schedules.splice(t,1),clearTimeout(n)},v=function(e,n,t,o){var a=i.toStr(n);if(function(e,n,t){e.messageHandlers.length||t("no onMessage() handler registered");try{e.messageHandlers.forEach(function(e){e(n,function(){t.apply(null,arguments),t=function(){}})})}catch(e){t(e.stack)}}(e,a,function(t){if(t)l(e,"Posting to server failed ["+t+"]"),e.pending=null,e.syncSchedule=h(e,function(){g(e)});else{var o=e.pending;if(e.pending=null,!o)throw new Error;r.assert(o.hash===n.hashOf),R(e,a,!0)?(e.timeOfLastSuccess=+new Date,e.lag=+new Date-o.timeSent):l(e,"Our message ["+n.hashOf+"] failed validation"),o.callback()}}),e.pending)throw new Error("there is already a pending message");-1===e.timeOfLastSuccess&&(e.timeOfLastSuccess=+new Date),e.pending={hash:n.hashOf,timeSent:+new Date,callback:function(){e.syncSchedule=h(e,function(){g(e)},0),t()}},r.PARANOIA&&A(e)},y=function(e){var n=e.onSettle;e.onSettle=[],n.forEach(function(n){try{n()}catch(n){d(e,"Error in onSettle handler ["+n.stack+"]")}})},m=function(e){if(!e.mut.inverseOf)throw new Error;return e.mut.inverseOf},g=function(e,n){if(r.PARANOIA&&A(e),e.syncSchedule&&!e.pending){if(p(e,e.syncSchedule),e.syncSchedule=null,e.uncommitted=a.simplify(e.uncommitted,e.authDoc,e.config.operationSimplify),0===e.uncommitted.operations.length)return y(e),e.timeOfLastSuccess=+new Date,void(e.syncSchedule=h(e,function(){g(e)}));var t=_(e,e.best)+1;if(t%e.config.checkpointInterval!==0){var o;o=e.setContentPatch?e.setContentPatch:i.create(i.PATCH,e.uncommitted,e.best.hashOf),v(e,o,function(){e.setContentPatch&&(l(e,"initial Ack received ["+o.hashOf+"]"),e.setContentPatch=null)})}else{var s=e.best;if(l(e,"Sending checkpoint (interval ["+e.config.checkpointInterval+"]) patch no ["+t+"]"),l(e,_(e,e.best)),!s||!s.content||!m(s.content))throw new Error;var c=a.createCheckpoint(e.authDoc,e.authDoc,m(s.content).parentHash),u=i.create(i.CHECKPOINT,c,s.hashOf);v(e,u,function(){l(e,"Checkpoint sent and accepted")})}}},E=function(e,n){r.assert(n.lastMsgHash),r.assert(n.hashOf),e.messages[n.hashOf]=n,(e.messagesByParent[n.lastMsgHash]=e.messagesByParent[n.lastMsgHash]||[]).push(n)},b=function(e,n){r.assert(n.lastMsgHash),r.assert(n.hashOf),delete e.messages[n.hashOf];var t=e.messagesByParent[n.lastMsgHash];r.assert(t.indexOf(n)>-1),t.splice(t.indexOf(n),1),0===t.length&&delete e.messagesByParent[n.lastMsgHash];var o=e.messagesByParent[n.hashOf];if(o)for(var a=0;a_(e,t)&&(t=o)}),t},N=function(e,n){n.operations.length&&(e.patchHandlers.forEach(function(e){e(n)}),e.changeHandlers.forEach(function(e){n.operations.forEach(function(n){e(n.offset,n.toRemove,n.toInsert)})}))},I=function(e,n){try{return e.config.validateContent(n())}catch(n){d(e,"Error in content validator ["+n.stack+"]")}return!1},x=function(e,n,t){for(var r=O(e,n);r;r=O(e,r))if(!1===t(r))return},C=function(e,n){e.mut.inverseOf||((e.mut.inverseOf=a.invert(e,n)).mut.inverseOf=e)},R=function(e,n,t){r.PARANOIA&&A(e);var c=i.fromString(n);if(l(e,JSON.stringify([c.hashOf,c.content.operations])),e.messages[c.hashOf]){if(e.setContentPatch&&e.setContentPatch.hashOf===c.hashOf)e.setContentPatch=null;else{if(c.content.isCheckpoint)return l(e,"["+(t?"our":"their")+"] Checkpoint ["+c.hashOf+"] is already known"),!0;l(e,"Patch ["+c.hashOf+"] is already known")}r.PARANOIA&&A(e)}else if(!c.content.isCheckpoint||I(e,function(){return c.content.operations[0].toInsert})){if(E(e,c),!D(e,e.rootMessage,c)){if(c.content.isCheckpoint&&e.best.mut.isInitialMessage){l(e,"applying checkpoint ["+c.hashOf+"]");var u=a.apply(e.uncommitted,e.authDoc);r.assert(!r.PARANOIA||e.userInterfaceContent===u);var f=a.invert(e.uncommitted,e.authDoc);return a.addOperation(f,o.create(0,e.authDoc.length,c.content.operations[0].toInsert)),f=a.simplify(f,u,e.config.operationSimplify),c.mut.parentCount=0,e.rootMessage=e.best=c,e.authDoc=c.content.operations[0].toInsert,e.uncommitted=a.create(s.hex_sha256(e.authDoc)),N(e,f),r.PARANOIA&&(e.userInterfaceContent=e.authDoc),!0}return l(e,"Patch ["+c.hashOf+"] not connected to root (parent: ["+c.lastMsgHash+"])"),void(r.PARANOIA&&A(e))}(c=S(e,c)).mut.isFromMe=t;var d=c.content,h=[],p=e.best;if(!D(e,e.best,c)){var v=_(e,e.best),g=_(e,c);if(!(v0))return l(e,"Patch ["+c.hashOf+"] chain is ["+g+"] best chain is ["+v+"]"),r.PARANOIA&&A(e),!0;for(;p&&!D(e,p,c);)h.push(p),p=O(e,p);r.assert(p),l(e,"Patch ["+c.hashOf+"] better than best chain, switching")}var R=[],P=c;do{R.unshift(P),P=O(e,P),r.assert(P)}while(P!==p);var k=e.authDoc;h.forEach(function(e){k=a.apply(m(e.content),k)}),R.forEach(function(e,n){n!==R.length-1&&(C(e.content,k),k=a.apply(e.content,k))});var M=e.best;if(R.length>1?(M=R[R.length-2],r.assert(M)):h.length&&(M=O(e,h[h.length-1]),r.assert(M)),r.assert(m(M.content).parentHash),r.assert(!r.PARANOIA||m(M.content).parentHash===s.hex_sha256(k)),m(M.content).parentHash===d.parentHash){if(d.isCheckpoint&&e.config.noPrune);else if(d.isCheckpoint){var F;if(x(e,c,function(e){if(e.content.isCheckpoint){if(F)return F=e,!1;F=e}}),F&&F!==e.rootMessage){var L=_(e,F);if(e.config.strictCheckpointValidation&&L%e.config.checkpointInterval!==0){if(l(e,"checkpoint ["+c.hashOf+"] at invalid point ["+L+"]"),r.PARANOIA&&A(e),r.TESTING)throw new Error;return void b(e,c)}l(e,"checkpoint ["+c.hashOf+"]"),x(e,F,function(n){l(e,"pruning ["+n.hashOf+"]"),b(e,n)}),e.rootMessage=F}}else{var H=a.simplify(d,k,e.config.operationSimplify);if(!a.equals(H,d)){if(l(e,"patch ["+c.hashOf+"] can be simplified"),r.PARANOIA&&A(e),r.TESTING)throw new Error;return void b(e,c)}if(!I(e,function(){return a.apply(d,k)}))return void l(e,"Patch ["+c.hashOf+"] failed content validation")}C(d,k),e.uncommitted=a.simplify(e.uncommitted,e.authDoc,e.config.operationSimplify);var j=a.apply(e.uncommitted,e.authDoc);r.PARANOIA&&r.assert(j===e.userInterfaceContent);var K=a.invert(e.uncommitted,e.authDoc);if(h.forEach(function(n){l(e,"reverting ["+n.hashOf+"]"),n.mut.isFromMe&&l(e,"reverting patch 'from me' ["+JSON.stringify(n.content.operations)+"]"),K=a.merge(K,m(n.content)),function(e,n,t){T(e,n,m(t))}(e,n.mut.isFromMe,n.content)}),R.forEach(function(n){l(e,"applying ["+n.hashOf+"]"),K=a.merge(K,n.content),T(e,n.mut.isFromMe,n.content)}),K=a.merge(K,e.uncommitted),K=a.simplify(K,j,e.config.operationSimplify),e.best=c,r.PARANOIA){var U=a.apply(K,j);r.assert(e.userInterfaceContent.length===w(e)),r.assert(U===e.userInterfaceContent)}return N(e,K),e.uncommitted.operations.length||y(e),r.PARANOIA&&A(e),!0}if(l(e,"patch ["+c.hashOf+"] parentHash is not valid"),r.PARANOIA&&A(e),r.TESTING)throw new Error;b(e,c)}else l(e,"Checkpoint ["+c.hashOf+"] failed content validation")},P=function(e,n){return Object.freeze({type:"Block",hashOf:n.hashOf,lastMsgHash:n.lastMsgHash,isCheckpoint:!!n.content.isCheckpoint,isFromMe:n.mut&&n.mut.isFromMe,author:n.mut&&n.mut.author,serverHash:n.mut&&n.mut.serverHash,time:n.mut&&n.mut.time,getParent:function(){var t=O(e,n);if(t)return P(e,t)},getContent:function(){return function(e,n){for(var t=[n];t[0]!==e.rootMessage;){var o=O(e,t[0]);if(!o)return{error:"not connected to root",doc:void 0};t.unshift(o)}var i="";e.rootMessage.content.operations.length&&(r.assert(1===e.rootMessage.content.operations.length),i=e.rootMessage.content.operations[0].toInsert);for(var s=1;s=0;t--)n=s(e[t],n);return n};var c=o.invert=function(e,n){return r.PARANOIA&&(a(e),r.assert("string"==typeof n),r.assert(e.offset+e.toRemove<=n.length)),i(e.offset,e.toInsert.length,(" "+n.substring(e.offset,e.offset+e.toRemove)).slice(1))},u=/[\uD800-\uDBFF]|[\uDC00-\uDFFF]/,f=o.hasSurrogate=function(e){return u.test(e)};o.simplify=function(e,n){r.PARANOIA&&(a(e),r.assert("string"==typeof n),r.assert(e.offset+e.toRemove<=n.length));for(var t=c(e,n),o=Math.min(e.toInsert.length,t.toInsert.length),s=0;s=0&&h[s]===d[s];s--);d=d.substring(0,s+1),l=s+1}return 0===l&&0===d.length?null:i(u,l,d)},o.equals=function(e,n){return e.toRemove===n.toRemove&&e.toInsert===n.toInsert&&e.offset===n.offset},o.lengthChange=function(e){return r.PARANOIA&&a(e),e.toInsert.length-e.toRemove},o.merge=function(e,n){r.PARANOIA&&(a(n),a(e));var t=e.offset,o=e.toRemove,s=e.toInsert,c=n.offset,u=n.toRemove,f=n.toInsert,l=c-t;if(u>0){var d=s;s=s.substring(0,l)+s.substring(l+u),(u-=d.length-s.length)<0&&(u=0),o+=u,u=0}if(l<0)t+=l,s=f+s;else if(s.length===l)s+=f;else{if(!(s.length>l))throw new Error("should never happen\n"+JSON.stringify([e,n],null," "));s=s.substring(0,l)+f+s.substring(l)}return""===s&&0===o?null:i(t,o,s)},o.shouldMerge=function(e,n){return r.PARANOIA&&(a(e),a(n)),n.offset0;)a+=c=r._heap_write(t,o+a,e,i,s),i+=c,s-=c,o+=c=n.process(o,a),(a-=c)||(o=0);return this.pos=o,this.len=a,this},e.exports.hash_finish=function(){if(null!==this.result)throw new IllegalStateError("state must be reset before processing new data");return this.asm.finish(this.pos,this.len,0),this.result=new Uint8Array(this.HASH_SIZE),this.result.set(this.heap.subarray(0,this.HASH_SIZE)),this.pos=0,this.len=0,this}},"sha256/utils.js":function(e,n,t){var r=e.exports.string_to_bytes=function(e,n){n=!!n;for(var t=e.length,r=new Uint8Array(n?4*t:t),o=0,a=0;o=t)throw new Error("Malformed string, low surrogate expected at position "+o);i=(55296^i)<<10|65536|56320^e.charCodeAt(o)}else if(!n&&i>>>8)throw new Error("Wide characters are not allowed.");!n||i<=127?r[a++]=i:i<=2047?(r[a++]=192|i>>6,r[a++]=128|63&i):i<=65535?(r[a++]=224|i>>12,r[a++]=128|i>>6&63,r[a++]=128|63&i):(r[a++]=240|i>>18,r[a++]=128|i>>12&63,r[a++]=128|i>>6&63,r[a++]=128|63&i)}return r.subarray(0,a)};e.exports.hex_to_bytes=function(e){var n=e.length;1&n&&(e="0"+e,n++);for(var t=new Uint8Array(n>>1),r=0;r>1]=parseInt(e.substr(r,2),16);return t},e.exports.base64_to_bytes=function(e){return r(atob(e))};var o=e.exports.bytes_to_string=function(e,n){n=!!n;for(var t=e.length,r=new Array(t),o=0,a=0;o=192&&i<224&&o+1=224&&i<240&&o+2=240&&i<248&&o+3>10,r[a++]=56320|1023&s)}}for(var c="",u=16384,f=0;f>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e+=1},e.exports.is_number=function(e){return"number"==typeof e},e.exports.is_string=function(e){return"string"==typeof e},e.exports.is_buffer=function(e){return e instanceof ArrayBuffer},e.exports.is_bytes=function(e){return e instanceof Uint8Array},e.exports.is_typed_array=function(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array},e.exports._heap_init=function(e,n){var t=n.heap,r=t?t.byteLength:n.heapSize||65536;if(4095&r||r<=0)throw new Error("heap size must be a positive integer and a multiple of 4096");return t=t||new e(new ArrayBuffer(r))},e.exports._heap_write=function(e,n,t,r,o){var a=e.length-n,i=a>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x428a2f98|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;R=n+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x71374491|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;R=t+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xb5c0fbcf|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;R=l+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xe9b5dba5|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;R=d+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x3956c25b|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;R=h+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x59f111f1|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;R=p+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x923f82a4|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;R=v+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xab1c5ed5|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;R=y+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xd807aa98|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;R=m+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x12835b01|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;R=g+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x243185be|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;R=E+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x550c7dc3|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;R=b+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x72be5d74|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;R=O+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x80deb1fe|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;R=A+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x9bdc06a7|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;R=w+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xc19bf174|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;e=R=(n>>>7^n>>>18^n>>>3^n<<25^n<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+e+m|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xe49b69c1|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;n=R=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+n+g|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xefbe4786|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;t=R=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+t+E|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x0fc19dc6|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;l=R=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(n>>>17^n>>>19^n>>>10^n<<15^n<<13)+l+b|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x240ca1cc|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;d=R=(h>>>7^h>>>18^h>>>3^h<<25^h<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+O|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x2de92c6f|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;h=R=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+h+A|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x4a7484aa|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;p=R=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+p+w|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x5cb0a9dc|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;v=R=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(h>>>17^h>>>19^h>>>10^h<<15^h<<13)+v+e|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x76f988da|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;y=R=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+y+n|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x983e5152|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;m=R=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+m+t|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xa831c66d|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;g=R=(E>>>7^E>>>18^E>>>3^E<<25^E<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+g+l|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xb00327c8|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;E=R=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+E+d|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xbf597fc7|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;b=R=(O>>>7^O>>>18^O>>>3^O<<25^O<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+b+h|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xc6e00bf3|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;O=R=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(E>>>17^E>>>19^E>>>10^E<<15^E<<13)+O+p|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xd5a79147|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;A=R=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+A+v|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x06ca6351|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;w=R=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(O>>>17^O>>>19^O>>>10^O<<15^O<<13)+w+y|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x14292967|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;e=R=(n>>>7^n>>>18^n>>>3^n<<25^n<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+e+m|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x27b70a85|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;n=R=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+n+g|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x2e1b2138|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;t=R=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+t+E|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x4d2c6dfc|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;l=R=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(n>>>17^n>>>19^n>>>10^n<<15^n<<13)+l+b|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x53380d13|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;d=R=(h>>>7^h>>>18^h>>>3^h<<25^h<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+O|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x650a7354|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;h=R=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+h+A|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x766a0abb|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;p=R=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+p+w|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x81c2c92e|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;v=R=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(h>>>17^h>>>19^h>>>10^h<<15^h<<13)+v+e|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x92722c85|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;y=R=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+y+n|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xa2bfe8a1|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;m=R=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+m+t|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xa81a664b|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;g=R=(E>>>7^E>>>18^E>>>3^E<<25^E<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+g+l|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xc24b8b70|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;E=R=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+E+d|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xc76c51a3|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;b=R=(O>>>7^O>>>18^O>>>3^O<<25^O<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+b+h|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xd192e819|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;O=R=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(E>>>17^E>>>19^E>>>10^E<<15^E<<13)+O+p|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xd6990624|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;A=R=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+A+v|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xf40e3585|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;w=R=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(O>>>17^O>>>19^O>>>10^O<<15^O<<13)+w+y|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x106aa070|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;e=R=(n>>>7^n>>>18^n>>>3^n<<25^n<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+e+m|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x19a4c116|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;n=R=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+n+g|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x1e376c08|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;t=R=(l>>>7^l>>>18^l>>>3^l<<25^l<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+t+E|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x2748774c|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;l=R=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(n>>>17^n>>>19^n>>>10^n<<15^n<<13)+l+b|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x34b0bcb5|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;d=R=(h>>>7^h>>>18^h>>>3^h<<25^h<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+d+O|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x391c0cb3|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;h=R=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(l>>>17^l>>>19^l>>>10^l<<15^l<<13)+h+A|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x4ed8aa4a|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;p=R=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+p+w|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x5b9cca4f|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;v=R=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(h>>>17^h>>>19^h>>>10^h<<15^h<<13)+v+e|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x682e6ff3|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;y=R=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+y+n|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x748f82ee|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;m=R=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+m+t|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x78a5636f|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;g=R=(E>>>7^E>>>18^E>>>3^E<<25^E<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+g+l|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x84c87814|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;E=R=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+E+d|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x8cc70208|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;b=R=(O>>>7^O>>>18^O>>>3^O<<25^O<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+b+h|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0x90befffa|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;O=R=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(E>>>17^E>>>19^E>>>10^E<<15^E<<13)+O+p|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xa4506ceb|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;A=R=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+A+v|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xbef9a3f7|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;w=R=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(O>>>17^O>>>19^O>>>10^O<<15^O<<13)+w+y|0;R=R+C+(N>>>6^N>>>11^N>>>25^N<<26^N<<21^N<<7)+(x^N&(I^x))+0xc67178f2|0;C=x;x=I;I=N;N=S+R|0;S=T;T=_;_=D;D=R+(_&T^S&(_^T))+(_>>>2^_>>>13^_>>>22^_<<30^_<<19^_<<10)|0;r=r+D|0;o=o+_|0;a=a+T|0;i=i+S|0;s=s+N|0;c=c+I|0;u=u+x|0;f=f+C|0}function C(e){e=e|0;x(I[e|0]<<24|I[e|1]<<16|I[e|2]<<8|I[e|3],I[e|4]<<24|I[e|5]<<16|I[e|6]<<8|I[e|7],I[e|8]<<24|I[e|9]<<16|I[e|10]<<8|I[e|11],I[e|12]<<24|I[e|13]<<16|I[e|14]<<8|I[e|15],I[e|16]<<24|I[e|17]<<16|I[e|18]<<8|I[e|19],I[e|20]<<24|I[e|21]<<16|I[e|22]<<8|I[e|23],I[e|24]<<24|I[e|25]<<16|I[e|26]<<8|I[e|27],I[e|28]<<24|I[e|29]<<16|I[e|30]<<8|I[e|31],I[e|32]<<24|I[e|33]<<16|I[e|34]<<8|I[e|35],I[e|36]<<24|I[e|37]<<16|I[e|38]<<8|I[e|39],I[e|40]<<24|I[e|41]<<16|I[e|42]<<8|I[e|43],I[e|44]<<24|I[e|45]<<16|I[e|46]<<8|I[e|47],I[e|48]<<24|I[e|49]<<16|I[e|50]<<8|I[e|51],I[e|52]<<24|I[e|53]<<16|I[e|54]<<8|I[e|55],I[e|56]<<24|I[e|57]<<16|I[e|58]<<8|I[e|59],I[e|60]<<24|I[e|61]<<16|I[e|62]<<8|I[e|63])}function R(e){e=e|0;I[e|0]=r>>>24;I[e|1]=r>>>16&255;I[e|2]=r>>>8&255;I[e|3]=r&255;I[e|4]=o>>>24;I[e|5]=o>>>16&255;I[e|6]=o>>>8&255;I[e|7]=o&255;I[e|8]=a>>>24;I[e|9]=a>>>16&255;I[e|10]=a>>>8&255;I[e|11]=a&255;I[e|12]=i>>>24;I[e|13]=i>>>16&255;I[e|14]=i>>>8&255;I[e|15]=i&255;I[e|16]=s>>>24;I[e|17]=s>>>16&255;I[e|18]=s>>>8&255;I[e|19]=s&255;I[e|20]=c>>>24;I[e|21]=c>>>16&255;I[e|22]=c>>>8&255;I[e|23]=c&255;I[e|24]=u>>>24;I[e|25]=u>>>16&255;I[e|26]=u>>>8&255;I[e|27]=u&255;I[e|28]=f>>>24;I[e|29]=f>>>16&255;I[e|30]=f>>>8&255;I[e|31]=f&255}function P(){r=0x6a09e667;o=0xbb67ae85;a=0x3c6ef372;i=0xa54ff53a;s=0x510e527f;c=0x9b05688c;u=0x1f83d9ab;f=0x5be0cd19;l=d=0}function k(e,n,t,h,p,v,y,m,g,E){e=e|0;n=n|0;t=t|0;h=h|0;p=p|0;v=v|0;y=y|0;m=m|0;g=g|0;E=E|0;r=e;o=n;a=t;i=h;s=p;c=v;u=y;f=m;l=g;d=E}function M(e,n){e=e|0;n=n|0;var t=0;if(e&63)return-1;while((n|0)>=64){C(e);e=e+64|0;n=n-64|0;t=t+64|0}l=l+t|0;if(l>>>0>>0)d=d+1|0;return t|0}function F(e,n,t){e=e|0;n=n|0;t=t|0;var r=0,o=0;if(e&63)return-1;if(~t)if(t&31)return-1;if((n|0)>=64){r=M(e,n)|0;if((r|0)==-1)return-1;e=e+r|0;n=n-r|0}r=r+n|0;l=l+n|0;if(l>>>0>>0)d=d+1|0;I[e|n]=0x80;if((n|0)>=56){for(o=n+1|0;(o|0)<64;o=o+1|0)I[e|o]=0x00;C(e);n=0;I[e|0]=0}for(o=n+1|0;(o|0)<59;o=o+1|0)I[e|o]=0;I[e|56]=d>>>21&255;I[e|57]=d>>>13&255;I[e|58]=d>>>5&255;I[e|59]=d<<3&255|l>>>29;I[e|60]=l>>>21&255;I[e|61]=l>>>13&255;I[e|62]=l>>>5&255;I[e|63]=l<<3&255;C(e);if(~t)R(t);return r|0}function L(){r=h;o=p;a=v;i=y;s=m;c=g;u=E;f=b;l=64;d=0}function H(){r=O;o=A;a=w;i=D;s=_;c=T;u=S;f=N;l=64;d=0}function j(e,n,t,I,C,R,k,M,F,L,H,j,K,U,B,V){e=e|0;n=n|0;t=t|0;I=I|0;C=C|0;R=R|0;k=k|0;M=M|0;F=F|0;L=L|0;H=H|0;j=j|0;K=K|0;U=U|0;B=B|0;V=V|0;P();x(e^0x5c5c5c5c,n^0x5c5c5c5c,t^0x5c5c5c5c,I^0x5c5c5c5c,C^0x5c5c5c5c,R^0x5c5c5c5c,k^0x5c5c5c5c,M^0x5c5c5c5c,F^0x5c5c5c5c,L^0x5c5c5c5c,H^0x5c5c5c5c,j^0x5c5c5c5c,K^0x5c5c5c5c,U^0x5c5c5c5c,B^0x5c5c5c5c,V^0x5c5c5c5c);O=r;A=o;w=a;D=i;_=s;T=c;S=u;N=f;P();x(e^0x36363636,n^0x36363636,t^0x36363636,I^0x36363636,C^0x36363636,R^0x36363636,k^0x36363636,M^0x36363636,F^0x36363636,L^0x36363636,H^0x36363636,j^0x36363636,K^0x36363636,U^0x36363636,B^0x36363636,V^0x36363636);h=r;p=o;v=a;y=i;m=s;g=c;E=u;b=f;l=64;d=0}function K(e,n,t){e=e|0;n=n|0;t=t|0;var l=0,d=0,h=0,p=0,v=0,y=0,m=0,g=0,E=0;if(e&63)return-1;if(~t)if(t&31)return-1;E=F(e,n,-1)|0;l=r,d=o,h=a,p=i,v=s,y=c,m=u,g=f;H();x(l,d,h,p,v,y,m,g,0x80000000,0,0,0,0,0,0,768);if(~t)R(t);return E|0}function U(e,n,t,l,d){e=e|0;n=n|0;t=t|0;l=l|0;d=d|0;var h=0,p=0,v=0,y=0,m=0,g=0,E=0,b=0,O=0,A=0,w=0,D=0,_=0,T=0,S=0,N=0;if(e&63)return-1;if(~d)if(d&31)return-1;I[e+n|0]=t>>>24;I[e+n+1|0]=t>>>16&255;I[e+n+2|0]=t>>>8&255;I[e+n+3|0]=t&255;K(e,n+4|0,-1)|0;h=O=r,p=A=o,v=w=a,y=D=i,m=_=s,g=T=c,E=S=u,b=N=f;l=l-1|0;while((l|0)>0){L();x(O,A,w,D,_,T,S,N,0x80000000,0,0,0,0,0,0,768);O=r,A=o,w=a,D=i,_=s,T=c,S=u,N=f;H();x(O,A,w,D,_,T,S,N,0x80000000,0,0,0,0,0,0,768);O=r,A=o,w=a,D=i,_=s,T=c,S=u,N=f;h=h^r;p=p^o;v=v^a;y=y^i;m=m^s;g=g^c;E=E^u;b=b^f;l=l-1|0}r=h;o=p;a=v;i=y;s=m;c=g;u=E;f=b;if(~d)R(d);return 0}return{reset:P,init:k,process:M,finish:F,hmac_reset:L,hmac_init:j,hmac_finish:K,pbkdf2_generate_block:U}}},"transform/TextTransformer.js":function(e,n,t){var r=t("../Operation"),o=t("../Common"),a=function(e,n){o.PARANOIA&&(r.check(e),r.check(n));var t=function(e,n){if(e.offset>n.offset){if(e.offset>n.offset+n.toRemove)return r.create(e.offset-n.toRemove+n.toInsert.length,e.toRemove,e.toInsert);var t=e.toRemove-(n.offset+n.toRemove-e.offset);return t<0&&(t=0),0===t&&0===e.toInsert.length?null:r.create(n.offset+n.toInsert.length,t,e.toInsert)}if(e.offset+e.toRemove=0;i--)s=r.apply(n[i],s);var c=[];for(i=e.length-1;i>=0;i--){for(var u=e[i],f=n.length-1;f>=0;f--){try{u=a(u,n[f])}catch(e){return console.error("The pluggable transform function threw an error, failing operational transformation"),console.error(e.stack),[]}if(!u)break}u&&(o.PARANOIA&&r.check(u,s.length),c.unshift(u))}return c}},"transform/NaiveJSONTransformer.js":function(e,n,t){var r=t("./TextTransformer"),o=t("../Operation"),a=t("../Common");e.exports=function(e,n,t){var i,s,c,u=a.global.REALTIME_DEBUG=a.global.REALTIME_DEBUG||{};try{i=r(e,n,t),s=o.applyMulti(n,t),c=o.applyMulti(i,s);try{return JSON.parse(c),i}catch(r){console.error(r),u.ot_parseError={type:"resultParseError",resultOps:i,toTransform:e,transformBy:n,text1:t,text2:s,text3:c,error:r},console.log("Debugging info available at `window.REALTIME_DEBUG.ot_parseError`")}}catch(r){console.error(r),u.ot_applyError={type:"resultParseError",resultOps:i,toTransform:e,transformBy:n,text1:t,text2:s,text3:c,error:r},console.log("Debugging info available at `window.REALTIME_DEBUG.ot_applyError`")}return[]}},"transform/SmartJSONTransformer.js":function(e,n,t){var r,o,a,i=t("json.sortify"),s=t("../Diff"),c=t("../Operation"),u=t("./TextTransformer"),f=function(e){return null===e?"null":(n=e,"[object Array]"===Object.prototype.toString.call(n)?"array":typeof e);var n},l=function(e,n){for(var t=n.length,r=0;r1)return!0})&&("splice"!==n.type||!e.some(function(e){if("splice"===e.type&&y(e.path,n.path)&&e.path.length-n.path.length<0){if(!e.removals)return;for(var t=e.offset,r=e.offset+e.removals;te.offset+n.removals)return void(n.offset+=e.value.length-e.removals);if(n.offseti)){var d=n.slice(0,l);if((y=n.slice(l))===u){var p=Math.min(s,l);if((g=c.slice(0,p))===(b=d.slice(0,p)))return h(g,c.slice(p),d.slice(p),u)}}if(null===f||f===s){var v=s,y=(d=n.slice(0,v),n.slice(v));if(d===c){var m=Math.min(a-v,i-v);if((E=u.slice(u.length-m))===(O=y.slice(y.length-m)))return h(c,u.slice(0,u.length-m),y.slice(0,y.length-m),E)}}}if(r.length>0&&o&&0===o.length){var g=e.slice(0,r.index),E=e.slice(r.index+r.length);if(!(i<(p=g.length)+(m=E.length))){var b=n.slice(0,p),O=n.slice(i-m);if(g===b&&E===O)return h(g,e.slice(p,a-m),n.slice(p,i-m),E)}}return null}(e,n,t);if(f)return f}var l=i(e,n),d=e.substring(0,l);l=s(e=e.substring(l),n=n.substring(l));var p=e.substring(e.length-l),v=function(e,n){var t;if(!e)return[[1,n]];if(!n)return[[r,e]];var c=e.length>n.length?e:n,u=e.length>n.length?n:e,f=c.indexOf(u);if(-1!==f)return t=[[1,c.substring(0,f)],[0,u],[1,c.substring(f+u.length)]],e.length>n.length&&(t[0][0]=t[2][0]=r),t;if(1===u.length)return[[r,e],[1,n]];var l=function(e,n){var t=e.length>n.length?e:n,r=e.length>n.length?n:e;if(t.length<4||2*r.length=e.length?[r,o,a,c,l]:null}var a,c,u,f,l,d=o(t,r,Math.ceil(t.length/4)),h=o(t,r,Math.ceil(t.length/2));if(!d&&!h)return null;a=h?d&&d[4].length>h[4].length?d:h:d,e.length>n.length?(c=a[0],u=a[1],f=a[2],l=a[3]):(f=a[0],l=a[1],c=a[2],u=a[3]);var p=a[4];return[c,u,f,l,p]}(e,n);if(l){var d=l[0],h=l[1],p=l[2],v=l[3],y=l[4],m=o(d,p),g=o(h,v);return m.concat([[0,y]],g)}return function(e,n){for(var t=e.length,o=n.length,i=Math.ceil((t+o)/2),s=i,c=2*i,u=new Array(c),f=new Array(c),l=0;lt)v+=2;else if(O>o)p+=2;else if(h&&(D=s+d-E)>=0&&D=(w=t-f[D]))return a(e,n,T,O)}for(var A=-g+y;A<=g-m;A+=2){for(var w,D=s+A,_=(w=A===-g||A!==g&&f[D-1]t)m+=2;else if(_>o)y+=2;else if(!h){var T;if((b=s+d-A)>=0&&b=(w=t-w))return a(e,n,T,O)}}}return[[r,e],[1,n]]}(e,n)}(e=e.substring(0,e.length-l),n=n.substring(0,n.length-l));return d&&v.unshift([0,d]),p&&v.push([0,p]),c(v,u),v}function a(e,n,t,r){var a=e.substring(0,t),i=n.substring(0,r),s=e.substring(t),c=n.substring(r),u=o(a,i),f=o(s,c);return u.concat(f)}function i(e,n){if(!e||!n||e.charAt(0)!==n.charAt(0))return 0;for(var t=0,r=Math.min(e.length,n.length),o=r,a=0;t=0&&d(e[p][1])){var v=e[p][1].slice(-1);if(e[p][1]=e[p][1].slice(0,-1),f=v+f,h=v+h,!e[p][1]){e.splice(p,1),o--;var y=p-1;e[y]&&1===e[y][0]&&(u++,h=e[y][1]+h,y--),e[y]&&e[y][0]===r&&(a++,f=e[y][1]+f,y--),p=y}}l(e[o][1])&&(v=e[o][1].charAt(0),e[o][1]=e[o][1].slice(1),f+=v,h+=v)}if(o0||h.length>0){f.length>0&&h.length>0&&(0!==(t=i(h,f))&&(p>=0?e[p][1]+=h.substring(0,t):(e.splice(0,0,[0,h.substring(0,t)]),o++),h=h.substring(t),f=f.substring(t)),0!==(t=s(h,f))&&(e[o][1]=h.substring(h.length-t)+e[o][1],h=h.substring(0,h.length-t),f=f.substring(0,f.length-t)));var m=u+a;0===f.length&&0===h.length?(e.splice(o-m,m),o-=m):0===f.length?(e.splice(o-m,m,[1,h]),o=o-m+1):0===h.length?(e.splice(o-m,m,[r,f]),o=o-m+1):(e.splice(o-m,m,[r,f],[1,h]),o=o-m+2)}0!==o&&0===e[o-1][0]?(e[o-1][1]+=e[o][1],e.splice(o,1)):o++,u=0,a=0,f="",h=""}""===e[e.length-1][1]&&e.pop();var g=!1;for(o=1;o=55296&&e<=56319}function f(e){return e>=56320&&e<=57343}function l(e){return f(e.charCodeAt(0))}function d(e){return u(e.charCodeAt(e.length-1))}function h(e,n,t,o){return d(e)||l(o)?null:function(e){for(var n=[],t=0;t0&&n.push(e[t]);return n}([[0,e],[r,n],[1,t],[0,o]])}function p(e,n,t){return o(e,n,t,!0)}p.INSERT=1,p.DELETE=r,p.EQUAL=0,e.exports=p}},n=a("ChainPad.js"),r="ChainPad",e.exports=n,"undefined"!=typeof window?o=window:void 0!==t?o=t:"undefined"!=typeof self&&(o=self),o[r]=n}(I)),I.exports}var C,R=x(),P=n({__proto__:null,default:r(R)},[R]),k={exports:{}};function M(){return C||(C=1,function(e){var n;n=function(e,n){var t={Nacl:e},r=n.encodeBase64,o=e=>{let t;return(t=e.length%4)&&(e+="=".repeat(4-t)),n.decodeBase64(e)},a=n.decodeUTF8,i=n.encodeUTF8,s=function(e){for(var n="",t=0;t{var n={setCustomize:n=>{e=n.ApiConfig},getWebsocketURL:function(n){var t=e.websocketPath||"/cryptpad_websocket";if(/^ws{1,2}:\/\//.test(t))return t;var r=new URL(n||globalThis?.location?.href||e.httpUnsafeOrigin);return n&&(r.href=n),r.protocol.replace(/http/,"ws")+"//"+r.host+t}};return n})())}(H)),H.exports}var K,U=j(),B=n({__proto__:null,default:r(U)},[U]),V={exports:{}};function Y(){return K||(K=1,function(e){e.exports&&(e.exports=function(e={}){return{setCustomize:n=>{e=n.AppConfig},userHashKey:"User_hash",userNameKey:"User_name",blockHashKey:"Block_hash",fileHashKey:"FS_hash",sessionJWT:"Session_JWT",ssoSeed:"SSO_seed",displayNameKey:"cryptpad.username",oldStorageKey:"CryptPad_RECENTPADS",storageKey:"filesData",tokenKey:"loginToken",prefersDriveRedirectKey:"prefersDriveRedirect",isPremiumKey:"isPremiumUser",displayPadCreationScreen:"displayPadCreationScreen",deprecatedKey:"deprecated",MAX_TEAMS_SLOTS:e.maxTeamsSlots||5,MAX_TEAMS_OWNED:e.maxOwnedTeams||5,MAX_PREMIUM_TEAMS_SLOTS:Math.max(e.maxTeamsSlots||0,e.maxPremiumTeamsSlots||0)||5,MAX_PREMIUM_TEAMS_OWNED:Math.max(e.maxOwnedTeams||0,e.maxPremiumTeamsOwned||0)||5,criticalApps:["profile","settings","debug","admin","support","notifications","calendar","moderation","oldadmin"],earlyAccessApps:[]}}(void 0))}(V)),V.exports}var G,J=Y(),q=n({__proto__:null,default:r(J)},[J]),W={exports:{}},z={exports:{}},Q=z.exports;function Z(){return G||(G=1,function(e){!function(n){const t=e=>{var t=n.CryptPad_Util={};n.atob=n.atob||function(e){return Buffer.from(e,"base64").toString("binary")},n.btoa=n.btoa||function(e){return Buffer.from(e,"binary").toString("base64")},t.encodeBase64=e.encodeBase64,t.decodeBase64=n=>{let t=n.length%4;return t&&(n+="=".repeat(4-t)),e.decodeBase64(n)},t.encodeUTF8=e.encodeUTF8,t.decodeUTF8=e.decodeUTF8,t.slice=function(e,n,t){return Array.prototype.slice.call(e,n,t)},t.u8ToBase64=(e,n)=>{const t=new FileReader;t.onload=()=>{let e=t.result,r=e.slice(e.indexOf(",")+1);n(r)},t.readAsDataURL(new Blob([e]))},t.shuffleArray=function(e){for(var n=e.length-1;n>0;n--){var t=Math.floor(Math.random()*(n+1)),r=e[n];e[n]=e[t],e[t]=r}},t.bake=function(e,n){return void 0===n&&(n=[]),Array.isArray(n)||(n=[n]),function(){return e.apply(null,n)}},t.both=function(e,n){if("function"!=typeof e)throw new Error("INVALID_USAGE");return"function"!=typeof n&&(n=function(e){return e}),function(){return e.apply(null,arguments),n.apply(null,arguments)}},t.clone=function(e){return null==e?e:JSON.parse(JSON.stringify(e))},t.serializeError=function(e){if(!(e instanceof Error))return e;var n={};return Object.getOwnPropertyNames(e).forEach(function(t){n[t]=e[t]}),n},t.tryParse=function(e){try{return JSON.parse(e)}catch(e){return}},t.mkAsync=function(e,n){if("function"!=typeof e)throw new Error("EXPECTED_FUNCTION");return function(){var t=Array.prototype.slice.call(arguments);setTimeout(function(){e.apply(null,t)},n)}},t.mkEvent=function(e){var n=[],t=!1;let r;return{reg:function(r){e&&t?setTimeout(r):n.push(r)},unreg:function(e){-1!==n.indexOf(e)?n.splice(n.indexOf(e),1):console.log("event handler was already unregistered")},fire:function(){if(!e||!t){var o=Array.prototype.slice.call(arguments);t||r.apply(null,o),t=!0,n.forEach(function(e){e.apply(null,o)})}},promise:new Promise(e=>{r=e})}},t.mkTimeout=function(e,n){n=n||0;var r=t.once(e),o=setTimeout(function(){r("TIMEOUT")},n);return t.both(r,function(){clearTimeout(o)})},t.onClickEnter=function(e,n,t){e.on("click keydown",function(e){var r="click"===e.type,o="keydown"===e.type&&13===e.which,a="keydown"===e.type&&32===e.which&&t&&t.space;(r||o||a)&&("keydown"===e.type&&e.preventDefault(),n(e))})},t.response=function(e){var n={},t={};"function"!=typeof e&&(e=function(e){throw new Error(e)});var r=function(e){clearTimeout(t[e]),delete t[e],delete n[e]};return{clear:r,expected:function(e){return Boolean(n[e])},expectation:function(e){return n[e]},expect:function(o,a,i){"string"!=typeof o&&e("EXPECTED_STRING"),"function"!=typeof a&&e("EXPECTED_CALLBACK"),n[o]=a,"number"==typeof i&&i&&(t[o]=setTimeout(function(){"function"==typeof n[o]&&n[o]("TIMEOUT"),r(o)},i))},handle:function(t,o){var a=n[t];if("function"==typeof a){try{a.apply(null,Array.isArray(o)?o:[o])}catch(n){e("HANDLER_ERROR",{error:n,id:t,args:o})}r(t)}else e("MISSING_CALLBACK",{id:t,args:o})},_pending:n}},t.inc=function(e,n,t){e[n]=(e[n]||0)+("number"==typeof t?t:1)},t.values=function(e){return Object.keys(e).map(function(n){return e[n]})},t.find=function(e,n){for(var t=n.length,r=0;r&"']/g,function(e){return{"<":"<",">":">","&":"&",'"':""","'":"'"}[e]}):""},t.hexToBase64=function(e){var t=e.replace(/\r|\n/g,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" "),r=String.fromCharCode.apply(null,t);return n.btoa(r).replace(/\//g,"-").replace(/=+$/,"")},t.base64ToHex=function(e){var t=[];return n.atob(e.replace(/-/g,"/")).split("").forEach(function(e){var n=e.charCodeAt(0).toString(16);1===n.length&&(n="0"+n),t.push(n)}),t.join("")},t.uint8ArrayToHex=function(e){for(var n="",t=0;t=o?"GB":e>=r?"MB":"KB"};t.getBlock=function(e,n,r){var o=t.once(t.mkAsync(r)),a={};"string"==typeof n.bearer&&n.bearer&&(a.authorization=`Bearer ${n.bearer}`),fetch(e,{method:"GET",credentials:"include",headers:a}).then(e=>{e.ok?o(void 0,e):401!==e.status&&404!==e.status?o(e.status,e):e.json().then(n=>{o(e.status,n)}).catch(()=>{o(e.status)})}).catch(e=>{o(e)})},t.fetchApi=function(e,n,t,r){const o=new URL(e);o.pathname=`api/${n}`;let a=o.href+(t?"?"+ +new Date:"");if("undefined"!=typeof self&&self.crypto)fetch(a).then(e=>{if(!e.ok)throw new Error(`Fetch error: ${e.status}`);return e.text()}).then(e=>{r(JSON.parse(e.slice(27,-5)))}).catch(e=>{console.error(e.message),r({})});else if(void 0!==f){("http:"===o.protocol?require("node:http"):require("node:https")).get(o.href,e=>{let n="";e.on("data",e=>{n+=e}),e.on("end",()=>{try{r(JSON.parse(n.slice(27,-5)))}catch(e){console.error(e),r({})}})})}},t.fetch=function(e,n,r,o){var a,i=t.once(t.mkAsync(n)),s=function(e){var n=e.replace(/(\/)*$/,""),t=n.lastIndexOf("/"),r=n.slice(t+1);return/^[a-f0-9]{48}$/.test(r)||(r=void 0),r}(e),c=function(){(a=new XMLHttpRequest).open("GET",e,!0),r&&a.addEventListener("progress",function(e){if(e.lengthComputable){var n=e.loaded/e.total;r(n)}},!1),a.responseType="arraybuffer",a.onerror=function(e){i(e)},a.onload=function(){if(/^4/.test(""+this.status))return i("XHR_ERROR");var e=a.response;if(e){var n=new Uint8Array(e);return s?void function(e,n,t){o&&"function"==typeof o.setBlobCache?o.setBlobCache(e,n,t):t("EINVAL")}(s,n,function(){i(null,n)}):void i(void 0,n)}i("ENOENT")},a.send(null)};if(s)return function(e,n){o&&"function"==typeof o.getBlobCache?o.getBlobCache(e,n):n("EINVAL")}(s,function(e,n){!e&&n?i(void 0,n):c()}),{cancel:function(){a&&a.abort&&a.abort()}};c()},t.dataURIToBlob=function(e){for(var n=atob(e.split(",")[1]),t=e.split(",")[0].split(":")[1].split(";")[0],r=new ArrayBuffer(n.length),o=new Uint8Array(r),a=0;aparseInt(e,10).toString(16).padStart(2,"0")).join("")}`},t.isSmallScreen=function(){return n.innerHeight<800||n.innerWidth<800},t.stripTags=function(e){var n=document.createElement("div");return n.innerHTML=e,n.innerText},t.parseFilename=function(e){if(!e||!e.trim())return{};var n=/^(\.?.+?)(\.[^.]+)?$/.exec(e)||[];return{name:n[1],ext:n[2]}},t.isPlainTextFile=function(e,n){if(e&&0===e.indexOf("text/"))return!0;var r=t.parseFilename(n);return!(e||!n||r.ext)||("application/x-javascript"===e||"application/xml"===e)},t.isSpreadsheet=function(e,n){return e&&("application/vnd.oasis.opendocument.spreadsheet"===e||"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"===e)||n&&(n.endsWith(".xlsx")||n.endsWith(".ods"))},t.isOfficeDoc=function(e,n){return e&&("application/vnd.oasis.opendocument.text"===e||"application/vnd.openxmlformats-officedocument.wordprocessingml.document"===e)||n&&(n.endsWith(".docx")||n.endsWith(".odt"))},t.isPresentation=function(e,n){return e&&("application/vnd.oasis.opendocument.presentation"===e||"application/vnd.openxmlformats-officedocument.presentationml.presentation"===e)||n&&(n.endsWith(".pptx")||n.endsWith(".odp"))},t.isValidURL=function(e){return!!new RegExp("^(https?:\\/\\/)((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*(\\?[;&a-z\\d%_.~+=-]*)?").test(e)};var a=/([\uD800-\uDBFF][\uDC00-\uDFFF])/;t.getFirstCharacter=function(e){if(!e||!e.trim())return"?";var n=function(e){for(var n=e.split(a),t=[],r=0;r{let n=/ver=([0-9.]+)(-[0-9]*)?/.exec(e);return Array.isArray(n)&&n[1]||void 0},t.Saferphore={create:e=>{var n,t=[];return n=function(){if(e<0)throw new Error("(resourceCount < 0) should never happen");var r;0!==e&&0!==t.length&&(e--,t.shift()((r=0,function(t){if(r++)throw new Error("returnAfter() called multiple times");var o=0;return function(){if(o++)throw new Error("returnAfter wrapped callback called multiple times");t&&t.apply(null,arguments),e++,n()}})))},{take:function(e){t.push(e),n()}}}},t};e.exports&&(e.exports=t(w()))}("undefined"!=typeof self?self:Q)}(z)),z.exports}var X,$,ee={exports:{}};function ne(){return X||(X=1,function(e){e.exports&&(e.exports=function(){var e={},n=function(e){return e.replace(/-/g,"/")};return e.parseUser=function(e){var t,r,o,a=function(e){if(/^\[.*?@.*\]$/.test(e)){var t,r=e.slice(1,-1);if(r=r.replace(/\/([a-zA-Z0-9+-]{43}=)$/,function(e,r){return t=n(r),""}),t){var o=r.lastIndexOf("@");if(!(o<1))return{domain:r.slice(o+1),user:r.slice(0,o),pubkey:t}}}}(e);if(function(e){if(e&&e.domain&&e.user&&e.pubkey)return!0}(a))return a;if(e.replace(/^https*:\/\/([^\/]+)\/user\/#\/1\/([^\/]+)\/([a-zA-Z0-9+-]{43}=)$/,function(e,a,i,s){return t=a,r=i,o=n(s),""}),!t)throw new Error("Could not parse user id ["+e+"]");return{domain:t,user:r,pubkey:o}},e.serialize=function(e,n,t){return"["+n+"@"+e.replace(/https*:\/\//,"")+"/"+t.replace(/\//g,"-")+"]"},e.canonicalize=function(t){if("string"==typeof t){if(44===t.length)return n(t);try{return e.parseUser(t).pubkey}catch(e){return}}},e}())}(ee)),ee.exports}function te(){return $||($=1,function(e){!function(n){e.exports&&(e.exports=function(e,t,r,o){var a=n.CryptPad_Hash={},i=e.uint8ArrayToHex,s=e.hexToBase64,c=e.base64ToHex;a.encodeBase64=e.encodeBase64,a.decodeBase64=e.decodeBase64,a.hashChannelList=function(n){return e.encodeBase64(o.hash(e.decodeUTF8(JSON.stringify(n))))},a.generateSignPair=function(){var e=o.sign.keyPair(),n=function(e){return t.b64RemoveSlashes(e).replace(/=+$/g,"")};return{validateKey:a.encodeBase64(e.publicKey),signKey:a.encodeBase64(e.secretKey),safeValidateKey:n(a.encodeBase64(e.publicKey)),safeSignKey:n(a.encodeBase64(e.secretKey))}},a.getSignPublicFromPrivate=function(n){var r=t.b64AddSlashes(n),a=e.decodeBase64(r),i=o.sign.keyPair.fromSecretKey(a);return e.encodeBase64(i.publicKey)},a.getCurvePublicFromPrivate=function(n){var r=t.b64AddSlashes(n),a=e.decodeBase64(r),i=o.box.keyPair.fromSecretKey(a);return e.encodeBase64(i.publicKey)};var u=a.getEditHashFromKeys=function(e){var n=e.version,r=e.keys;if(0===n)return e.channel+e.key;if(1===n){if(!r.editKeyStr)return;return"/1/edit/"+s(e.channel)+"/"+t.b64RemoveSlashes(r.editKeyStr)+"/"}if(2===n){if(!r.editKeyStr)return;var o=e.password?"p/":"";return"/2/"+e.type+"/edit/"+t.b64RemoveSlashes(r.editKeyStr)+"/"+o}},f=a.getViewHashFromKeys=function(e){var n=e.version,r=e.keys;if(0!==n){if(1===n){if(!r.viewKeyStr)return;return"/1/view/"+s(e.channel)+"/"+t.b64RemoveSlashes(r.viewKeyStr)+"/"}if(2===n){if(!r.viewKeyStr)return;var o=e.password?"p/":"";return"/2/"+e.type+"/view/"+t.b64RemoveSlashes(r.viewKeyStr)+"/"+o}}};a.getHiddenHashFromKeys=function(e,n,t){t=t||{};var r=n.keys&&n.keys.editKeyStr||n.key,o=!t.view&&r?"edit/":"view/",i=n.password?"p/":"";n.keys&&n.keys.fileKeyStr&&(o="");var s="/3/"+e+"/"+o+n.channel+"/"+i,c=a.parseTypeHash(e,s);return c&&c.getHash?c.getHash(t||{}):s};var l=a.getFileHashFromKeys=function(e){var n=e.version,r=e.keys;if(0!==n){if(1===n)return"/1/"+s(e.channel)+"/"+t.b64RemoveSlashes(r.fileKeyStr)+"/";if(2===n){if(!r.fileKeyStr)return;var o=e.password?"p/":"";return"/2/"+e.type+"/"+t.b64RemoveSlashes(r.fileKeyStr)+"/"+o}}};a.getPublicSigningKeyString=r.serialize,a.ephemeralChannelLength=34,a.createChannelId=function(e){var n=i(t.Nacl.randomBytes(e?17:16));if(-1===[32,34].indexOf(n.length)||/[^a-f0-9]/.test(n))throw new Error("channel ids must consist of 32 hex characters");return n},a.getChannelIdFromKey=function(e){if(e)return i(a.decodeBase64(e).subarray(0,16))},a.getBoxPublicFromSecret=function(e){if(e){var n=a.decodeBase64(e),t=o.box.keyPair.fromSecretKey(n);return a.encodeBase64(t.publicKey)}},a.checkBoxKeyPair=function(e,n){if(!n||!e)return!1;var t=a.decodeBase64(e),r=o.box.keyPair.fromSecretKey(t);return n===a.encodeBase64(r.publicKey)},a.createRandomHash=function(e,n){var r;return"file"===e?(r=t.createFileCryptor2(void 0,n),l({password:Boolean(n),version:2,type:e,keys:r})):(r=t.createEditCryptor2(void 0,void 0,n),u({password:Boolean(n),version:2,type:e,keys:r}))};var d=a.parseTypeHash=function(e,n){if(n){var r,o=[],a={},i=(r=n,r.replace(/\/+/g,"/")).split("/"),s=function(){a.password=-1!==o.indexOf("p"),a.present=-1!==o.indexOf("present"),a.embed=-1!==o.indexOf("embed"),a.versionHash=function(e){var n;return e.some(function(e){if(/^hash=/.test(e))return n=e.slice(5),!0}),n?t.b64AddSlashes(n):""}(o),a.auditorKey=function(e){var n;return e.some(function(e){if(/^auditor=/.test(e))return n=e.slice(8),!0}),n?t.b64AddSlashes(n):""}(o),a.newPadOpts=function(e){var n;return e.some(function(e){if(/^newpad=/.test(e))return n=e.slice(7),!0}),n||""}(o),a.loginOpts=function(e){var n;return e.some(function(e){if(/^login=/.test(e))return n=e.slice(6),!0}),n||""}(o),a.ownerKey=function(e){var n;return e.some(function(e){if(86===e.length)return n=e,!0}),n}(o)};return i[1]&&"4"===i[1]?(a.getHash=function(n){if(!n||!Object.keys(n).length)return"";var t="/4/"+e+"/";return n.newPadOpts&&(t+="newpad="+n.newPadOpts+"/"),n.loginOpts&&(t+="login="+n.loginOpts+"/"),t},a.getOptions=function(){var e={};return a.newPadOpts&&(e.newPadOpts=a.newPadOpts),a.loginOpts&&(e.loginOpts=a.loginOpts),e},a.version=4,a.app=i[2],o=i.slice(3),s(),a):-1===["media","file","user","invite"].indexOf(e)?(a.type="pad",a.getHash=function(){return n},a.getOptions=function(){return{embed:a.embed,present:a.present,ownerKey:a.ownerKey,versionHash:a.versionHash,auditorKey:a.auditorKey,newPadOpts:a.newPadOpts,loginOpts:a.loginOpts,password:a.password}},"/"!==n.slice(0,1)&&n.length>=56?(a.channel=n.slice(0,32),a.key=n.slice(32,56),a.version=0,a):(a.getHash=function(e){var n=i.slice(0,5).join("/")+"/",r=void 0!==e.ownerKey?e.ownerKey:a.ownerKey;r&&(n+=r+"/"),(a.password||e.password)&&(n+="p/"),e.embed&&(n+="embed/"),e.present&&(n+="present/");var o=void 0!==e.versionHash?e.versionHash:a.versionHash;o&&(n+="hash="+t.b64RemoveSlashes(o)+"/");var s=void 0!==e.auditorKey?e.auditorKey:a.auditorKey;return s&&(n+="auditor="+t.b64RemoveSlashes(s)+"/"),e.newPadOpts&&(n+="newpad="+e.newPadOpts+"/"),e.loginOpts&&(n+="login="+e.loginOpts+"/"),n},i[1]&&"1"===i[1]?(a.version=1,a.mode=i[2],a.channel=i[3],a.key=t.b64AddSlashes(i[4]),o=i.slice(5),s(),a):i[1]&&"2"===i[1]?(a.version=2,a.app=i[2],a.mode=i[3],a.key=i[4],o=i.slice(5),s(),a):i[1]&&"3"===i[1]?(a.version=3,a.app=i[2],a.mode=i[3],a.channel=i[4],o=i.slice(5),s(),a):a)):(a.getHash=function(){return i.join("/")},-1!==["media","file"].indexOf(e)?(a.type="file",a.getOptions=function(){return{embed:a.embed,present:a.present,ownerKey:a.ownerKey,newPadOpts:a.newPadOpts,loginOpts:a.loginOpts,password:a.password}},a.getHash=function(e){var n=i.slice(0,4).join("/")+"/",t=void 0!==e.ownerKey?e.ownerKey:a.ownerKey;return t&&(n+=t+"/"),(a.password||e.password)&&(n+="p/"),e.embed&&(n+="embed/"),e.present&&(n+="present/"),e.newPadOpts&&(n+="newpad="+e.newPadOpts+"/"),e.loginOpts&&(n+="login="+e.loginOpts+"/"),n},i[1]&&"1"===i[1]?(a.version=1,a.channel=i[2].replace(/-/g,"/"),a.key=i[3].replace(/-/g,"/"),o=i.slice(4),s(),a):i[1]&&"2"===i[1]?(a.version=2,a.app=i[2],a.key=i[3],o=i.slice(4),s(),a):i[1]&&"3"===i[1]?(a.version=3,a.app=i[2],a.channel=i[3],o=i.slice(4),s(),a):a):-1!==["user"].indexOf(e)?(a.type="user",i[1]&&"1"===i[1]?(a.version=1,a.user=i[2],a.pubkey=i[3].replace(/-/g,"/"),a):a):-1!==["invite"].indexOf(e)?(a.type="invite",i[1]&&"2"===i[1]?(a.version=2,a.app=i[2],a.mode=i[3],a.key=i[4],o=i.slice(5),a.password=-1!==o.indexOf("p"),a):a):void 0)}},h=a.parsePadUrl=function(e){var n,t={};return e?("/"!==e.slice(-1)&&"#"!==e.slice(-1)&&(e+="/"),e=e.replace(/\/\?[^#]+#/,"/#"),t.getUrl=function(e){e=e||{};var n="/";return t.type?(n+=t.type+"/",!t.hashData&&e&&Object.keys(e).length?n+"#"+function(e){if(!e||!Object.keys(e).length)return"";var n="/4/"+t.type+"/";return e.newPadOpts&&(n+="newpad="+e.newPadOpts+"/"),e.loginOpts&&(n+="login="+e.loginOpts+"/"),n}(e):t.hashData?n+="#"+t.hashData.getHash(e):n):n},t.getOptions=function(){return t.hashData&&t.hashData.getOptions?t.hashData.getOptions():{}},/^https*:\/\//.test(e)?(e.replace(/^https*:\/\/([^\/]*)\/(.*?)\//i,function(e,n,r){return t.domain=n,t.type=r,""}),-1===(n=e.indexOf("/#"))||(t.hash=e.slice(n+2),t.hashData=d(t.type,t.hash)),t):/^\/($|[^\/])/.test(e)?(n=e.indexOf("/#"),t.type=e.slice(1,n),-1===n||(t.hash=e.slice(n+2),t.hashData=d(t.type,t.hash)),t):t):t};return a.hashToHref=function(e,n){return"/"+n+"/#"+e},a.hrefToHash=function(e){return a.parsePadUrl(e).hash},a.getRelativeHref=function(e){if(e&&-1!==e.indexOf("#")){var n=h(e);return"/"+n.type+"/#"+n.hash}},a.getSecrets=function(n,r,o){var a,i,s={},u=function(){s.keys=t.createEditCryptor2(void 0,void 0,o),s.channel=c(s.keys.chanId),s.version=2,s.type=n};if(!r)return u(),s;if(r){if(!n)throw new Error("getSecrets with a hash requires a type parameter");a=d(n,r),i=r}if(0===i.length)return u(),s;if(0===a.version)s.channel=a.channel,s.key=a.key,s.version=0;else if(1===a.version){if(s.version=1,"pad"===a.type){if(s.channel=c(a.channel),"edit"===a.mode){if(s.keys=t.createEditCryptor(a.key),s.key=s.keys.editKeyStr,32!==s.channel.length||24!==s.key.length)throw new Error("The channel key and/or the encryption key is invalid")}else if("view"===a.mode&&(s.keys=t.createViewCryptor(a.key),32!==s.channel.length))throw new Error("The channel key is invalid")}else if("file"===a.type)s.channel=c(a.channel),s.keys={fileKeyStr:a.key,cryptKey:e.decodeBase64(a.key)};else if("user"===a.type)throw new Error("User hashes can't be opened (yet)")}else if(2===a.version)if(s.version=2,s.type=n,s.password=o,"pad"===a.type){if("edit"===a.mode){if(s.keys=t.createEditCryptor2(a.key,void 0,o),s.channel=c(s.keys.chanId),s.key=s.keys.editKeyStr,32!==s.channel.length||24!==s.key.length)throw new Error("The channel key and/or the encryption key is invalid")}else if("view"===a.mode&&(s.keys=t.createViewCryptor2(a.key,o),s.channel=c(s.keys.chanId),32!==s.channel.length))throw new Error("The channel key is invalid")}else if("file"===a.type){if(s.keys=t.createFileCryptor2(a.key,o),s.channel=c(s.keys.chanId),s.key=s.keys.fileKeyStr,48!==s.channel.length||24!==s.key.length)throw new Error("The channel key and/or the encryption key is invalid")}else if("user"===a.type)throw new Error("User hashes can't be opened (yet)");return s},a.getHashes=function(e){var n={};return(e=JSON.parse(JSON.stringify(e))).keys||e.key?(e.keys||(e.keys={}),(e.keys.editKeyStr||0===e.version&&e.key)&&(n.editHash=u(e)),e.keys.viewKeyStr&&(n.viewHash=f(e)),e.keys.fileKeyStr&&(n.fileHash=l(e)),n):n},a.getFormData=function(n,t,r){var i=(n=n||a.getSecrets("form",t,r))&&n.keys,s=i&&i.secondaryKey;if(s){var c=o.box.keyPair.fromSecretKey(e.decodeUTF8(s).slice(0,32)),u={};u.form_public=e.encodeBase64(c.publicKey);var f=u.form_private=e.encodeBase64(c.secretKey),l=a.getViewHashFromKeys({version:1,channel:n.channel,keys:{viewKeyStr:e.encodeBase64(i.cryptKey)}}),d=a.parseTypeHash("pad",l);return u.form_auditorHash=d.getHash({auditorKey:f}),u}},a.hrefToHexChannelId=function(e,n){var t=a.parsePadUrl(e);if(t&&t.hash)return a.getSecrets(t.type,t.hash,n).channel},a.getBlobPathFromHex=function(e){return"/blob/"+e.slice(0,2)+"/"+e},a.serializeHash=function(e){return e&&"/"!==e.slice(-1)&&(e+="/"),e},a.createInviteUrl=function(e,t){return t=t||a.createChannelId(),n.location.origin+"/invite/#/1/"+t+"/"+e.replace(/\//g,"-")+"/"},a.isValidChannel=function(e){return/^[a-zA-Z0-9]{32,48}$/.test(e)},a.isValidHref=function(e){if(e){var n=a.parsePadUrl(e);if(n&&n.type){if(n.hash){if(!n.hashData)return;if(void 0===n.hashData.version)return;if("pad"===n.hashData.type||"file"===n.hashData.type){if(!n.hashData.key&&!n.hashData.channel)return;if(n.hashData.key&&!/^[a-zA-Z0-9+-/=]+$/.test(n.hashData.key))return}}return n}}},a.decodeDataOptions=function(n){var t=decodeURIComponent(n),r=e.encodeUTF8(e.decodeBase64(t));return e.tryParse(r)||{}},a.encodeDataOptions=function(n){var t=JSON.stringify(n),r=e.encodeBase64(e.decodeUTF8(t));return encodeURIComponent(r)},a.getNewPadURL=function(e,n){var t=a.parsePadUrl(e),r=t.getOptions();return r.newPadOpts=a.encodeDataOptions(n),t.getUrl(r)},a.getLoginURL=function(e,n){var t=a.parsePadUrl(e),r=t.getOptions();return r.loginOpts=a.encodeDataOptions(n),t.getUrl(r)},a}(Z(),M(),ne(),h()))}("undefined"!=typeof window?window:{})}(W)),W.exports}var re,oe,ae=te(),ie=Z(),se={exports:{}},ce={exports:{}};function ue(){return re||(re=1,function(e){e.exports=function e(n,t,r){function o(i,s){if(!t[i]){if(!n[i]){if(!s&&f)return f(i);if(a)return a(i,!0);var c=new Error("Cannot find module '"+i+"'");throw c.code="MODULE_NOT_FOUND",c}var u=t[i]={exports:{}};n[i][0].call(u.exports,function(e){var t=n[i][1][e];return o(t||e)},u,u.exports,e,n,t,r)}return t[i].exports}for(var a=f,i=0;i=43)}}).catch(function(){return!1})}function A(e){return"boolean"==typeof v?u.resolve(v):O(e).then(function(e){return v=e})}function w(e){var n=y[e.name],t={};t.promise=new u(function(e,n){t.resolve=e,t.reject=n}),n.deferredOperations.push(t),n.dbReady?n.dbReady=n.dbReady.then(function(){return t.promise}):n.dbReady=t.promise}function D(e){var n=y[e.name].deferredOperations.pop();if(n)return n.resolve(),n.promise}function _(e,n){var t=y[e.name].deferredOperations.pop();if(t)return t.reject(n),t.promise}function T(e,n){return new u(function(t,r){if(y[e.name]=y[e.name]||F(),e.db){if(!n)return t(e.db);w(e),e.db.close()}var o=[e.name];n&&o.push(e.version);var a=i.open.apply(i,o);n&&(a.onupgradeneeded=function(n){var t=a.result;try{t.createObjectStore(e.storeName),n.oldVersion<=1&&t.createObjectStore(p)}catch(t){if("ConstraintError"!==t.name)throw t;console.warn('The database "'+e.name+'" has been upgraded from version '+n.oldVersion+" to version "+n.newVersion+', but the storage "'+e.storeName+'" already exists.')}}),a.onerror=function(e){e.preventDefault(),r(a.error)},a.onsuccess=function(){var n=a.result;n.onversionchange=function(e){e.target.close()},t(n),D(e)}})}function S(e){return T(e,!1)}function N(e){return T(e,!0)}function I(e,n){if(!e.db)return!0;var t=!e.db.objectStoreNames.contains(e.storeName),r=e.versione.db.version;if(r&&(e.version!==n&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),o||t){if(t){var a=e.db.version+1;a>e.version&&(e.version=a)}return!0}return!1}function x(e){return new u(function(n,t){var r=new FileReader;r.onerror=t,r.onloadend=function(t){var r=btoa(t.target.result||"");n({__local_forage_encoded_blob:!0,data:r,type:e.type})},r.readAsBinaryString(e)})}function C(e){return c([b(atob(e.data))],{type:e.type})}function R(e){return e&&e.__local_forage_encoded_blob}function P(e){var n=this,t=n._initReady().then(function(){var e=y[n._dbInfo.name];if(e&&e.dbReady)return e.dbReady});return l(t,e,e),t}function k(e){w(e);for(var n=y[e.name],t=n.forages,r=0;r0&&(!e.db||"InvalidStateError"===o.name||"NotFoundError"===o.name))return u.resolve().then(function(){if(!e.db||"NotFoundError"===o.name&&!e.db.objectStoreNames.contains(e.storeName)&&e.version<=e.db.version)return e.db&&(e.version=e.db.version+1),N(e)}).then(function(){return k(e).then(function(){M(e,n,t,r-1)})}).catch(t);t(o)}}function F(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function L(e){var n=this,t={db:null};if(e)for(var r in e)t[r]=e[r];var o=y[t.name];o||(o=F(),y[t.name]=o),o.forages.push(n),n._initReady||(n._initReady=n.ready,n.ready=P);var a=[];function i(){return u.resolve()}for(var s=0;s>4,f[c++]=(15&r)<<4|o>>2,f[c++]=(3&o)<<6|63&a;return u}function pe(e){var n,t=new Uint8Array(e),r="";for(n=0;n>2],r+=z[(3&t[n])<<4|t[n+1]>>4],r+=z[(15&t[n+1])<<2|t[n+2]>>6],r+=z[63&t[n+2]];return t.length%3==2?r=r.substring(0,r.length-1)+"=":t.length%3==1&&(r=r.substring(0,r.length-2)+"=="),r}function ve(e,n){var t="";if(e&&(t=de.call(e)),e&&("[object ArrayBuffer]"===t||e.buffer&&"[object ArrayBuffer]"===de.call(e.buffer))){var r,o=X;e instanceof ArrayBuffer?(r=e,o+=ee):(r=e.buffer,"[object Int8Array]"===t?o+=te:"[object Uint8Array]"===t?o+=re:"[object Uint8ClampedArray]"===t?o+=oe:"[object Int16Array]"===t?o+=ae:"[object Uint16Array]"===t?o+=se:"[object Int32Array]"===t?o+=ie:"[object Uint32Array]"===t?o+=ce:"[object Float32Array]"===t?o+=ue:"[object Float64Array]"===t?o+=fe:n(new Error("Failed to get type for BinaryArray"))),n(o+pe(r))}else if("[object Blob]"===t){var a=new FileReader;a.onload=function(){var t=Q+e.type+"~"+pe(this.result);n(X+ne+t)},a.readAsArrayBuffer(e)}else try{n(JSON.stringify(e))}catch(t){console.error("Couldn't convert value into a JSON string: ",e),n(null,t)}}function ye(e){if(e.substring(0,$)!==X)return JSON.parse(e);var n,t=e.substring(le),r=e.substring($,le);if(r===ne&&Z.test(t)){var o=t.match(Z);n=o[1],t=t.substring(o[0].length)}var a=he(t);switch(r){case ee:return a;case ne:return c([a],{type:n});case te:return new Int8Array(a);case re:return new Uint8Array(a);case oe:return new Uint8ClampedArray(a);case ae:return new Int16Array(a);case se:return new Uint16Array(a);case ie:return new Int32Array(a);case ce:return new Uint32Array(a);case ue:return new Float32Array(a);case fe:return new Float64Array(a);default:throw new Error("Unkown type: "+r)}}var me={serialize:ve,deserialize:ye,stringToBuffer:he,bufferToString:pe};function ge(e,n,t,r){e.executeSql("CREATE TABLE IF NOT EXISTS "+n.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],t,r)}function Ee(e){var n=this,t={db:null};if(e)for(var r in e)t[r]="string"!=typeof e[r]?e[r].toString():e[r];var o=new u(function(e,r){try{t.db=openDatabase(t.name,String(t.version),t.description,t.size)}catch(e){return r(e)}t.db.transaction(function(o){ge(o,t,function(){n._dbInfo=t,e()},function(e,n){r(n)})},r)});return t.serializer=me,o}function be(e,n,t,r,o,a){e.executeSql(t,r,o,function(e,i){i.code===i.SYNTAX_ERR?e.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[n.storeName],function(e,s){s.rows.length?a(e,i):ge(e,n,function(){e.executeSql(t,r,o,a)},a)},a):a(e,i)},a)}function Oe(e,n){var t=this;e=d(e);var r=new u(function(n,r){t.ready().then(function(){var o=t._dbInfo;o.db.transaction(function(t){be(t,o,"SELECT * FROM "+o.storeName+" WHERE key = ? LIMIT 1",[e],function(e,t){var r=t.rows.length?t.rows.item(0).value:null;r&&(r=o.serializer.deserialize(r)),n(r)},function(e,n){r(n)})})}).catch(r)});return f(r,n),r}function Ae(e,n){var t=this,r=new u(function(n,r){t.ready().then(function(){var o=t._dbInfo;o.db.transaction(function(t){be(t,o,"SELECT * FROM "+o.storeName,[],function(t,r){for(var a=r.rows,i=a.length,s=0;s0)return void a(we.apply(o,[e,s,t,r-1]));i(n)}})})}).catch(i)});return f(a,t),a}function De(e,n,t){return we.apply(this,[e,n,t,1])}function _e(e,n){var t=this;e=d(e);var r=new u(function(n,r){t.ready().then(function(){var o=t._dbInfo;o.db.transaction(function(t){be(t,o,"DELETE FROM "+o.storeName+" WHERE key = ?",[e],function(){n()},function(e,n){r(n)})})}).catch(r)});return f(r,n),r}function Te(e){var n=this,t=new u(function(e,t){n.ready().then(function(){var r=n._dbInfo;r.db.transaction(function(n){be(n,r,"DELETE FROM "+r.storeName,[],function(){e()},function(e,n){t(n)})})}).catch(t)});return f(t,e),t}function Se(e){var n=this,t=new u(function(e,t){n.ready().then(function(){var r=n._dbInfo;r.db.transaction(function(n){be(n,r,"SELECT COUNT(key) as c FROM "+r.storeName,[],function(n,t){var r=t.rows.item(0).c;e(r)},function(e,n){t(n)})})}).catch(t)});return f(t,e),t}function Ne(e,n){var t=this,r=new u(function(n,r){t.ready().then(function(){var o=t._dbInfo;o.db.transaction(function(t){be(t,o,"SELECT key FROM "+o.storeName+" WHERE id = ? LIMIT 1",[e+1],function(e,t){var r=t.rows.length?t.rows.item(0).key:null;n(r)},function(e,n){r(n)})})}).catch(r)});return f(r,n),r}function Ie(e){var n=this,t=new u(function(e,t){n.ready().then(function(){var r=n._dbInfo;r.db.transaction(function(n){be(n,r,"SELECT key FROM "+r.storeName,[],function(n,t){for(var r=[],o=0;o '__WebKitDatabaseInfoTable__'",[],function(t,r){for(var o=[],a=0;a0}function Le(e){var n=this,t={};if(e)for(var r in e)t[r]=e[r];return t.keyPrefix=ke(e,n._defaultConfig),Fe()?(n._dbInfo=t,t.serializer=me,u.resolve()):u.reject()}function He(e){var n=this,t=n.ready().then(function(){for(var e=n._dbInfo.keyPrefix,t=localStorage.length-1;t>=0;t--){var r=localStorage.key(t);0===r.indexOf(e)&&localStorage.removeItem(r)}});return f(t,e),t}function je(e,n){var t=this;e=d(e);var r=t.ready().then(function(){var n=t._dbInfo,r=localStorage.getItem(n.keyPrefix+e);return r&&(r=n.serializer.deserialize(r)),r});return f(r,n),r}function Ke(e,n){var t=this,r=t.ready().then(function(){for(var n=t._dbInfo,r=n.keyPrefix,o=r.length,a=localStorage.length,i=1,s=0;s=0;n--){var t=localStorage.key(n);0===t.indexOf(e)&&localStorage.removeItem(t)}}):u.reject("Invalid arguments"),f(r,n),r}var qe={_driver:"localStorageWrapper",_initStorage:Le,_support:Pe(),iterate:Ke,getItem:je,setItem:Ge,removeItem:Ye,clear:He,length:Ve,key:Ue,keys:Be,dropInstance:Je},We=function(e,n){return e===n||"number"==typeof e&&"number"==typeof n&&isNaN(e)&&isNaN(n)},ze=function(e,n){for(var t=e.length,r=0;r{const n=(e,n)=>{let t=globalThis,r=globalThis;var o=t.CryptPad_Cache={},a=e.mkEvent(!0),i=!1,s=!1,c=!1;try{var u=t.indexedDB.open("test_db",1);u.onsuccess=function(){i=(c=!0)&&!s,a.fire()},u.onerror=function(){a.fire()}}catch(e){a.fire()}o.enable=function(){s=!1,i=c&&!s},o.disable=function(){s=!0,i=c&&!s},o.isEnabled=()=>i;var f=n.createInstance({driver:n.INDEXEDDB,name:"cp_cache"});o.getBlobCache=function(n,t){t=e.once(e.mkAsync(t||function(){})),a.reg(function(){i?f.getItem(n,function(r,o){!r&&o&&o.c?(t(null,o.c),o.t=+new Date,f.setItem(n,o,function(e){e&&console.error(e)})):t(e.serializeError(r||"EINVAL"))}):t("NOCACHE")})},o.setBlobCache=function(n,t,r){r=e.once(e.mkAsync(r||function(){})),a.reg(function(){i?t?f.setItem(n,{c:t,t:+new Date},function(n){r(e.serializeError(n))}):r("EINVAL"):r("NOCACHE")})},o.getChannelCache=function(n,t){t=e.once(e.mkAsync(t||function(){})),a.reg(function(){i?f.getItem(n,function(r,o){!r&&o&&Array.isArray(o.c)?(t(null,o),o.t=+new Date,f.setItem(n,o,function(e){e&&console.error(e)})):t(e.serializeError(r||"EINVAL"))}):t("NOCACHE")})};var l={};return o.storeCache=function(n,t,r,o){o=e.once(e.mkAsync(o||function(){})),a.reg(function(){l[n]=l[n]||e.throttle(function(t,r,o){var a,s;i?Array.isArray(r)&&t?(a=r,Array.isArray(a)&&(a.length>100&&a.splice(0,a.length-100),a.some(function(e,n){if(e.isCheckpoint)return s=n,!0}),a.splice(0,s)),f.setItem(n,{k:t,c:r,t:+new Date},function(n){n&&o(e.serializeError(n))})):o("EINVAL"):o("NOCACHE")},50),l[n](t,r,o)})},o.leaveChannel=function(e){delete l[e]},o.clearChannel=function(n,t){t=e.once(e.mkAsync(t||function(){})),a.reg(function(){i?f.removeItem(n,function(){t()}):t("NOCACHE")})},o.clear=function(n){n=e.once(e.mkAsync(n||function(){})),a.reg(function(){i?f.clear(n):n("NOCACHE")})},o.getKeys=function(n){n=e.once(e.mkAsync(n||function(){})),a.reg(function(){i?f.keys().then(function(e){n(null,e)}).catch(function(e){n(e)}):n("NOCACHE")})},o.getTime=function(n,t){t=e.once(e.mkAsync(t||function(){})),a.reg(function(){i?f.getItem(n,function(n,r){!n&&r&&r.c?t(null,r.t):t(e.serializeError(n||"EINVAL"))}):t("NOCACHE")})},r.CryptPad_clearIndexedDB=o.clear,o};e.exports&&(e.exports=n(Z(),ue()))})()}(se)),se.exports}var le=fe(),de=n({__proto__:null,default:r(le)},[le]);const he=ie.mkEvent(!0),pe=ie.mkEvent(!0),ve=ie.mkEvent(),ye=ie.mkEvent();let me={};const ge={setCustomize:e=>{me=e.ApiConfig},init:e=>{var n,t,r;const{broadcast:o,userHash:a,anonHash:i}=e,s=a||i||ae.createRandomHash("drive"),c=e.store,u=ae.getSecrets("drive",s),f=(null===(n=e.store)||void 0===n?void 0:n.network)||(null===(t=e.store)||void 0===t?void 0:t.networkPromise),l={data:{},websocketURL:U.getWebsocketURL(),network:f,channel:u.channel,readOnly:!1,validateKey:(null===(r=u.keys)||void 0===r?void 0:r.validateKey)||void 0,crypto:L.createEncryptor(u.keys),Cache:de,userName:"fs",logLevel:1,ChainPad:P,updateProgress:function(e){e.type="drive",o([],"LOADING_DRIVE",e)},classic:!0},d=globalThis.CP_account_rt=N.create(l);c.driveSecret=u,c.proxy=d.proxy,c.onRpcReadyEvt=ie.mkEvent(!0),c.loggedIn=void 0!==e.userHash;const h={loggedIn:c.loggedIn};return d.proxy.on("create",function(e){c.realtime=e.realtime,c.network=e.network,c.loggedIn||(h.anonHash=ae.getEditHashFromKeys(u))}).on("cacheready",function(n){c.realtime=n.realtime,c.offline=!0;const t=!!c.networkPromise;if(c.networkPromise||(c.networkPromise=n.networkPromise),c.cacheReturned=h,c.networkPromise&&c.networkPromise.then&&!t){const e=setTimeout(function(){c.networkTimeout=!0,o([],"LOADING_DRIVE",{type:"offline"})},5e3);c.networkPromise.then(function(n){c.network||(c.network=n),clearTimeout(e)},function(n){console.error(n),clearTimeout(e)})}e.cache&&(h.edPublic=d.proxy.edPublic,he.fire(h))}).on("ready",function(n){delete c.networkTimeout,c.ready||(c.driveMetadata=n.metadata,d.proxy.drive||(d.proxy.drive={}),!d.proxy[J.displayNameKey]&&c.noDriveName&&(d.proxy[J.displayNameKey]=c.noDriveName),!d.proxy.uid&&c.noDriveUid&&(d.proxy.uid=c.noDriveUid),!d.proxy.form_seed&&e.form_seed&&(d.proxy.form_seed=e.form_seed),d.proxy.edPublic&&Array.isArray(me.adminKeys)&&-1!==me.adminKeys.indexOf(d.proxy.edPublic)&&(c.isAdmin=!0),h.edPublic=d.proxy.edPublic,pe.fire(h))}).on("error",function(e){"EDELETED"===e.error&&(c.ownDeletion||(c.isDeleted=!0,o([],"DRIVE_DELETED",e.message)))}).on("disconnect",function(){c.offline=!0,ve.fire(),o([],"UPDATE_METADATA")}).on("reconnect",function(){c.offline=!1,ye.fire(),o([],"UPDATE_METADATA")}),{channel:u.channel,onAccountCacheReady:he.reg,onAccountReady:pe.reg,onDisconnect:ve.reg,onReconnect:ye.reg}}};var Ee,be=Object.freeze({__proto__:null,Account:ge}),Oe={exports:{}};function Ae(){return Ee||(Ee=1,function(e){(()=>{const n=(e={},n={})=>{var t={setCustomize:t=>{n=t.Messages,e=t.AppConfig},init:function(e){t.state=e}};return t.send=function(n,r,o){("function"!=typeof o&&(o=function(){}),e.disableFeedback)?o():n&&(!0===r||t.state)?function(e,n){var t=new XMLHttpRequest;t.open("HEAD",e),t.onreadystatechange=function(){this.readyState===this.DONE&&n&&n()},t.send()}("/common/feedback.html?"+n+"="+Math.random().toString(16).replace(/0./,""),o):o()},t.reportAppUsage=function(){var e=window.location.pathname.split("/").filter(function(e){return e}).join(".");/^#\/1\/view\//.test(window.location.hash)?t.send(e+"_VIEW"):t.send(e)},t.reportScreenDimensions=function(){var e=window.innerHeight,n=window.innerWidth;t.send("DIMENSIONS:"+e+"x"+n)},t.reportLanguage=function(){n&&t.send("LANG_"+n._languageUsed)},t};e.exports&&(e.exports=n(void 0,void 0))})()}(Oe)),Oe.exports}var we,De,_e=Ae(),Te=n({__proto__:null,default:r(_e)},[_e]),Se={exports:{}},Ne={exports:{}};function Ie(){return De||(De=1,function(e){e.exports&&(e.exports=function(e={},n){var t={setCustomize:n=>{e=n.AppConfig}};t.MINIMUM_PASSWORD_LENGTH="number"==typeof e.minimumPasswordLength?e.minimumPasswordLength:8,t.MINIMUM_NAME_LENGTH=1,t.MAXIMUM_NAME_LENGTH=64,t.isEmail=function(e){return/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(e).toLowerCase())},t.isLongEnoughPassword=function(e){return e.length>=t.MINIMUM_PASSWORD_LENGTH};var r=t.isString=function(e){return"string"==typeof e};return t.isValidUsername=function(e){return!!(r(e)&&e.length>=t.MINIMUM_NAME_LENGTH)},t.isValidPassword=function(e){return!(!e||!r(e))},t.passwordsMatch=function(e,n){return r(e)&&r(n)&&e===n},t.customSalt=function(){return"string"==typeof e.loginSalt?e.loginSalt:""},t.deriveFromPassphrase=function(e,r,o,a){n(r,e+t.customSalt(),8,1024,o||128,200,a,void 0)},t.dispenser=function(e){var n={used:0};return function(t){if(n.used+t>e.length)throw new Error("exceeded available entropy");if("number"!=typeof t)throw new Error("expected a number");if(t<=0)throw new Error("expected to consume a positive number of bytes");var r;return r=e.slice?e.slice(n.used,n.used+t):e.subarray(n.used,n.used+t),n.used+=t,r}},t}(void 0,(we||(we=1,function(e){e.exports=function(e,n,t,r,o,a,i,s){function c(e){var n=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],t=1779033703,r=3144134277,o=1013904242,a=2773480762,i=1359893119,s=2600822924,c=528734635,u=1541459225,f=new Array(64);function l(e){for(var l=0,d=e.length;d>=64;){var h,p,v,y,m,g=t,E=r,b=o,O=a,A=i,w=s,D=c,_=u;for(p=0;p<16;p++)v=l+4*p,f[p]=(255&e[v])<<24|(255&e[v+1])<<16|(255&e[v+2])<<8|255&e[v+3];for(p=16;p<64;p++)y=((h=f[p-2])>>>17|h<<15)^(h>>>19|h<<13)^h>>>10,m=((h=f[p-15])>>>7|h<<25)^(h>>>18|h<<14)^h>>>3,f[p]=(y+f[p-7]|0)+(m+f[p-16]|0)|0;for(p=0;p<64;p++)y=(((A>>>6|A<<26)^(A>>>11|A<<21)^(A>>>25|A<<7))+(A&w^~A&D)|0)+(_+(n[p]+f[p]|0)|0)|0,m=((g>>>2|g<<30)^(g>>>13|g<<19)^(g>>>22|g<<10))+(g&E^g&b^E&b)|0,_=D,D=w,w=A,A=O+y|0,O=b,b=E,E=g,g=y+m|0;t=t+g|0,r=r+E|0,o=o+b|0,a=a+O|0,i=i+A|0,s=s+w|0,c=c+D|0,u=u+_|0,l+=64,d-=64}}l(e);var d,h=e.length%64,p=e.length/536870912|0,v=e.length<<3,y=h<56?56:120,m=e.slice(e.length-h,e.length);for(m.push(128),d=h+1;d>>24&255),m.push(p>>>16&255),m.push(p>>>8&255),m.push(p>>>0&255),m.push(v>>>24&255),m.push(v>>>16&255),m.push(v>>>8&255),m.push(v>>>0&255),l(m),[t>>>24&255,t>>>16&255,t>>>8&255,t>>>0&255,r>>>24&255,r>>>16&255,r>>>8&255,r>>>0&255,o>>>24&255,o>>>16&255,o>>>8&255,o>>>0&255,a>>>24&255,a>>>16&255,a>>>8&255,a>>>0&255,i>>>24&255,i>>>16&255,i>>>8&255,i>>>0&255,s>>>24&255,s>>>16&255,s>>>8&255,s>>>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 u(e,n,t){e=e.length<=64?e:c(e);var r,o=64+n.length+4,a=new Array(o),i=new Array(64),s=[];for(r=0;r<64;r++)a[r]=54;for(r=0;r=o-4;e--){if(a[e]++,a[e]<=255)return;a[e]=0}}for(;t>=32;)u(),s=s.concat(c(i.concat(c(a)))),t-=32;return t>0&&(u(),s=s.concat(c(i.concat(c(a))).slice(0,t))),s}function f(e,n,t,r){var o,a,i=e[0]^n[t++],s=e[1]^n[t++],c=e[2]^n[t++],u=e[3]^n[t++],f=e[4]^n[t++],l=e[5]^n[t++],d=e[6]^n[t++],h=e[7]^n[t++],p=e[8]^n[t++],v=e[9]^n[t++],y=e[10]^n[t++],m=e[11]^n[t++],g=e[12]^n[t++],E=e[13]^n[t++],b=e[14]^n[t++],O=e[15]^n[t++],A=i,w=s,D=c,_=u,T=f,S=l,N=d,I=h,x=p,C=v,R=y,P=m,k=g,M=E,F=b,L=O;for(a=0;a<8;a+=2)A^=(o=(k^=(o=(x^=(o=(T^=(o=A+k)<<7|o>>>25)+A)<<9|o>>>23)+T)<<13|o>>>19)+x)<<18|o>>>14,S^=(o=(w^=(o=(M^=(o=(C^=(o=S+w)<<7|o>>>25)+S)<<9|o>>>23)+C)<<13|o>>>19)+M)<<18|o>>>14,R^=(o=(N^=(o=(D^=(o=(F^=(o=R+N)<<7|o>>>25)+R)<<9|o>>>23)+F)<<13|o>>>19)+D)<<18|o>>>14,L^=(o=(P^=(o=(I^=(o=(_^=(o=L+P)<<7|o>>>25)+L)<<9|o>>>23)+_)<<13|o>>>19)+I)<<18|o>>>14,A^=(o=(_^=(o=(D^=(o=(w^=(o=A+_)<<7|o>>>25)+A)<<9|o>>>23)+w)<<13|o>>>19)+D)<<18|o>>>14,S^=(o=(T^=(o=(I^=(o=(N^=(o=S+T)<<7|o>>>25)+S)<<9|o>>>23)+N)<<13|o>>>19)+I)<<18|o>>>14,R^=(o=(C^=(o=(x^=(o=(P^=(o=R+C)<<7|o>>>25)+R)<<9|o>>>23)+P)<<13|o>>>19)+x)<<18|o>>>14,L^=(o=(F^=(o=(M^=(o=(k^=(o=L+F)<<7|o>>>25)+L)<<9|o>>>23)+k)<<13|o>>>19)+M)<<18|o>>>14;n[r++]=e[0]=A+i|0,n[r++]=e[1]=w+s|0,n[r++]=e[2]=D+c|0,n[r++]=e[3]=_+u|0,n[r++]=e[4]=T+f|0,n[r++]=e[5]=S+l|0,n[r++]=e[6]=N+d|0,n[r++]=e[7]=I+h|0,n[r++]=e[8]=x+p|0,n[r++]=e[9]=C+v|0,n[r++]=e[10]=R+y|0,n[r++]=e[11]=P+m|0,n[r++]=e[12]=k+g|0,n[r++]=e[13]=M+E|0,n[r++]=e[14]=F+b|0,n[r++]=e[15]=L+O|0}function l(e,n,t,r,o){for(;o--;)e[n++]=t[r++]}function d(e,n,t,r,o){for(;o--;)e[n++]^=t[r++]}function h(e,n,t,r,o){l(e,0,n,t+16*(2*o-1),16);for(var a=0;a<2*o;a+=2)f(e,n,t+16*a,r+8*a),f(e,n,t+16*a+16,r+8*a+16*o)}function p(e,n,t){return e[n+16*(2*t-1)]}function v(e){for(var n=[],t=0;t127&&r<2048?(n.push(r>>6|192),n.push(63&r|128)):(n.push(r>>12|224),n.push(r>>6&63|128),n.push(63&r|128))}return n}if(t<1||t>31)throw new Error("scrypt: logN not be between 1 and 31");var y,m,g,E,b=1<>>0;if(1*r>=1<<30||r>16777216||r>8388608||b>16777216/r)throw new Error("scrypt: parameters are too large");"string"==typeof e&&(e=v(e)),"string"==typeof n&&(n=v(n)),"undefined"!=typeof Int32Array?(y=new Int32Array(64*r),m=new Int32Array(32*b*r),E=new Int32Array(16)):(y=[],m=[],E=new Array(16)),g=u(e,n,128*r);var O=32*r;function A(){for(var e=0;e<32*r;e++){var n=4*e;y[0+e]=(255&g[n+3])<<24|(255&g[n+2])<<16|(255&g[n+1])<<8|255&g[n+0]}}function w(e,n){for(var t=e;t>>0&255,g[4*e+1]=n>>>8&255,g[4*e+2]=n>>>16&255,g[4*e+3]=n>>>24&255}}var T="undefined"!=typeof setImmediate?setImmediate:setTimeout;function S(e,n,t,r,o){!function a(){T(function(){r(e,e+t>>18&63]),o.push(t[n>>>12&63]),o.push(t[n>>>6&63]),o.push(t[n>>>0&63]);return r%3>0&&(o[o.length-1]="=",r%3==1&&(o[o.length-2]="=")),o.join("")}(t):"hex"===n?function(e){for(var n="0123456789abcdef".split(""),t=e.length,r=[],o=0;o>>4&15]),r.push(n[e[o]>>>0&15]);return r.join("")}(t):t}"function"==typeof a&&(s=i,i=a,a=1e3),a<=0?(A(),w(0,b),D(0,b),_(),i(N(s))):(A(),S(0,b,2*a,w,function(){S(0,b,2*a,D,function(){_(),i(N(s))})}))}}(Ne)),Ne.exports)))}(Se)),Se.exports}var xe,Ce,Re,Pe=Ie(),ke=n({__proto__:null,default:r(Pe)},[Pe]),Me={exports:{}},Fe={exports:{}},Le={exports:{}},He={exports:{}};function je(){return xe||(xe=1,function(e){e.exports&&(e.exports={whenRealtimeSyncs:function(e,n){"function"==typeof e.getAuthDoc?setTimeout(function(){e.getAuthDoc()!==e.getUserDoc()?e.onSettle(n):n()},0):console.error("improper use of this function")}})}(He)),He.exports}function Ke(){return Ce||(Ce=1,function(e){(()=>{const n=(e,n,t)=>{let r=globalThis;var o={setCustomize:()=>{}},a=function(e){try{return JSON.parse(JSON.stringify(e))}catch(e){return}};return o.init=function(o,i,s){var c=o.loggedIn,u=o.sharedFolder,f=o.readOnly,l=o.Messages||{},d=i.ROOT,h=i.FILES_DATA,p=i.STATIC_DATA,v=i.OLD_FILES_DATA,y=i.UNSORTED,m=i.TRASH,g=i.TEMPLATE,E=i.SHARED_FOLDERS,b=i.SHARED_FOLDERS_TEMP,O=i.debug;i._setReadOnly=function(e){(f=e)||i.fixFiles()},i.setHref=function(e,t,r){(t||e)&&(f||(t?[t]:i.findChannels([e])).forEach(function(e){var t=i.getFileData(e,!0);if(i.getHref(t)===r)return;t.href=i.cryptor.encrypt(r);const o=n.parsePadUrl(r);if("form"!==o.type)return;const a=n.getSecrets(o.type,o.hash,t.password);t.roHref="/"+o.type+"/#"+n.getViewHashFromKeys(a)}))},i.setPadAttribute=function(e,n,t,r){if(r=r||function(){},f)r("EFORBIDDEN");else{var o=i.getIdFromHref(e);if(o)if(n&&n.trim()){var s=i.getFileData(o,!0);"href"===n?i.setHref(null,o,t):s[n]=a(t),r(null)}else r("E_INVAL_ATTR");else r("E_INVAL_HREF")}},i.getPadAttribute=function(e,n,t){t=t||function(){};var r=i.getIdFromHref(e);if(r){var o=i.getFileData(r);t(null,a(o[n]))}else t(null,void 0)},i.pushData=function(n,t){if("function"!=typeof t&&(t=function(){}),f)t("EFORBIDDEN");else{var r=e.createRandomInteger(),o=a(n);o.href&&-1!==o.href.indexOf("#")&&(o.href=i.cryptor.encrypt(o.href)),s[h][r]=o,t(null,r)}},i.pushLink=function(n,t){if("function"!=typeof t&&(t=function(){}),f)t("EFORBIDDEN");else{var r=e.createRandomInteger(),o=a(n);s[p][r]=o,t(null,r)}},i.pushSharedFolder=function(n,t){if("function"!=typeof t&&(t=function(){}),f)t("EFORBIDDEN");else{var r,u=a(n);if(Object.keys(s[E]).some(function(e){if(s[E][e].channel===u.channel)return u.href&&!s[E][e].href&&(s[E][e].href=u.href),r=e,!0}))t("EEXISTS",r);else if(c&&!o.testMode){var l=e.createRandomInteger();u.href&&-1!==u.href.indexOf("#")&&(u.href=i.cryptor.encrypt(u.href)),s[E][l]=u,t(null,l)}else t("EAUTH")}},i.deprecateSharedFolder=function(e,n){if(!f){var t=s[E][e];if(t){if(!(!t.href||-1===i.cryptor.decrypt(t.href).indexOf("#")))(s[b][e]=JSON.parse(JSON.stringify(t))).legacy="PASSWORD_CHANGE"!==n;var r=i.findFile(Number(e));i.delete(r,null,!0),delete s[E][e]}}};var A=function(e){f||delete s[h][e]};i.checkDeletedFiles=function(e){if(c||o.testMode)if(f)e("EFORBIDDEN");else{var t=i.getFiles([d,"hrefArray",m]),r=[];i.getFiles([h,E,p]).forEach(function(e){if(-1===t.indexOf(e)){var a=i.isSharedFolder(e)?s[E][e]:i.getFileData(e),c=a.channel;a.lastVersion&&r.push(n.hrefToHexChannelId(a.lastVersion)),a.rtChannel&&r.push(a.rtChannel),c&&r.push(c),i.isSharedFolder(e)?(delete s[E][e],o.removeProxy&&o.removeProxy(e)):s[p][e]?delete s[p][e]:A(e)}}),r.length?e(null,r):e()}else e()};i.deleteMultiplePermanently=function(e,n,t){if(f)t("EFORBIDDEN");else{var r=e.filter(function(e){return i.isPathIn(e,[h])});if(!c&&!o.testMode)return r.forEach(function(e){var n=e[1];n&&A(n)}),void t();var a=e.filter(function(e){return i.isPathIn(e,["hrefArray"])}),u=e.filter(function(e){return i.isPathIn(e,[d])}),l=e.filter(function(e){return i.isPathIn(e,[m])}),p=[];a.forEach(function(e){var n=i.find(e);p.push({root:e[0],id:n})}),function(e){f||e.forEach(function(e){var n=s[e.root].indexOf(e.id);s[e.root].splice(n,1)})}(p),u.forEach(function(e){var n=e.slice(),t=n.pop();delete i.find(n)[t]});var v,y=[];l.forEach(function(e){var n=e.slice(),t=n.pop(),r=i.find(n);4!==e.length?delete r[t]:y.push({name:e[1],el:r})}),v=y,f||v.forEach(function(e){var n=s[m][e.name].indexOf(e.el);s[m][e.name].splice(n,1)}),n?t():i.checkDeletedFiles(t)}},i.copyFromOtherDrive=function(e,t,r,o){if(!f){var a=[];if(Object.keys(r).forEach(function(e){e=Number(e);var n=r[e];if(n.static)return delete n.static,void(s[p][e]=n);n.href&&(n.href=i.cryptor.encrypt(n.href));var t=!1;for(var o in s[h])if(s[h][o].channel===n.channel){s[h][o].href||(s[h][o].href=n.href),t=!0;break}t?a.push(e):s[h][e]=n}),i.isFile(t)&&-1!==a.indexOf(t))i.log(l.sharedFolders_duplicate);else{if(i.isFolder(t)){var c=function(e){for(var n in e)i.isFile(e[n])?-1!==a.indexOf(e[n])&&(i.log(l.sharedFolders_duplicate),delete e[n]):i.isFolder(e[n])&&c(e[n])};c(t)}var u=i.find(e),d=i.isFile(t)?n.createChannelId():o,v=i.getAvailableName(u,d);Array.isArray(u)?u.push(t):u[v]=t}}};i.copyElement=function(e,t){if(!f&&!i.comparePath(e,t)){var r=i.find(e),o=i.find(t);if(i.isPathIn(t,[m])){if(!e||e.length<2||e[0]===m)return void O("Can't move an element from the trash to the trash: ",e);var a=e[e.length-1],c=i.isPathIn(e,["hrefArray"])?i.getTitle(r):a,u=e.slice();return u.pop(),function(e,n,t){if(!f){var r=s[m];void 0===r[e]&&(r[e]=[]);var o={element:n,path:t};r[e].push(o)}}(c,r,u),!0}if(i.isPathIn(t,["hrefArray"])){if(i.isFolder(r))return void i.log(l.fo_moveUnsortedError);if(e[0]===t[0])return;var d=t[0];return-1===s[d].indexOf(r)&&s[d].push(r),!0}var h=i.isFile(r)?i.getAvailableName(o,n.createChannelId()):i.isInTrashRoot(e)?e[1]:e.pop();if(void 0===o[h])return o[h]=r,!0;i.log(l.fo_unavailableName)}},i.forget=function(e){if(!f){var n=i.getIdFromHref(e);if(n){if(!c&&!o.testMode)return A(n),!0;var t=i.findFile(n);return i.move(t,[m]),!0}}},i.restoreHref=function(e){if(!f){var n=i.getIdFromHref(e);if(n&&i.isFile(n)){var t=i.findFile(n),r=!0;t.forEach(function(e){e[0]!==m?r=!1:i.delete(e,null,!0)}),r&&i.add(n)}}},i.add=function(e,t){if(!f&&(c||o.testMode)){e=Number(e);var r=s[h][e]||s[p][e]||s[E][e];if(r&&"object"==typeof r){var a,u=t;if(t&&!Array.isArray(t)&&(u=decodeURIComponent(t).split(",")),t&&i.isPathIn(u,["hrefArray"]))(a=i.find(u)).push(e);else if(-1!==i.getFiles([d,m,"hrefArray"]).indexOf(e)||u||(u=[d]),t&&i.isPathIn(u,[d])){if(a=i.find(u)){var l=i.getAvailableName(a,n.createChannelId());return void(a[l]=e)}a=i.find([d]),u.slice(1).forEach(function(e){a=a[e]=a[e]||{}}),a[n.createChannelId()]=e}}}},i.setFolderData=function(e,t,r,o){if(!f){var a=i.find(e);if(i.isFolder(a)&&!i.isSharedFolder(a)){if(!i.hasFolderData(a))a["000"+n.createChannelId().slice(0,-3)]={metadata:!0};i.getFolderData(a)[t]=r,o()}}};var w=function(e){i.rt?(i.rt.sync(),t.whenRealtimeSyncs(i.rt,e)):r.setTimeout(e,1e3)};return i.migrateReadOnly=function(e){if(!f&&o.editKey)if(s.version>=2)e();else{s.migrateRo=1;w(function(){var n=JSON.parse(JSON.stringify(s));i.reencrypt(o.editKey,o.editKey,n),setTimeout(function(){s.version>=2?e():(Object.keys(n).forEach(function(e){s[e]=n[e]}),s.version=2,delete s.migrateRo,w(e))},1e3)})}else e({error:"EFORBIDDEN"})},i.migrate=function(t){if(f)t();else{!function(){if(s[y]&&s[v]){O("UNSORTED still exists in the object, removing it...");var e=s[y];0!==e.length?(e.forEach(function(e){"string"==typeof e&&(0===s[v].filter(function(n){return n.href===e}).length&&s[v].push({href:e}))}),delete s[y]):delete s[y]}}(),function(t){if(s[v])try{O("Migrating file system..."),s.migrate=1;w(function(){var r=s[v].slice();s[h]||(s[h]={});var o=s[h];r.forEach(function(t){if(t&&t.href){var r=t.href,a=e.createRandomInteger(),s=i.findFile(r),c=t,u=n.createChannelId();o[a]=c||{href:r},s.forEach(function(e){var n=e.slice(),t=n.pop(),r=i.find(n);if(i.isInTrashRoot(e))return r.element=a,void(o[a].filename=e[1]);i.isPathIn(e,["hrefArray"])?r[t]=a:(r[u]=a,o[a].filename=t,delete r[t])})}}),delete s[v],delete s.migrate,t()})}catch(e){console.error(e),t()}else t()}(t)}},i.fixFiles=function(t){if(!f){t&&(O=function(){});var r=+new Date;O("Cleaning file system...");var a=JSON.stringify(s),l=function(t){"object"!=typeof s[d]&&(O("ROOT was not an object"),s[d]={});var r=t||s[d];if(!r)return console.error("Invalid element in root");var o,a=0,c=s[p],u=s[h];for(var f in r)if(null!==(o=r[f]))if(i.isFolderData(o))0!==a&&(O("Multiple metadata files in folder"),delete r[f]),a++;else if(i.isFile(o,!0)||i.isFolder(o))if(i.isFolder(o))l(o);else{if("string"==typeof o){var v=e.createRandomInteger(),y=n.createChannelId();u[v]={href:i.cryptor.encrypt(o),filename:f},r[y]=v,delete r[f]}if("number"==typeof o)u[o]||c[o]||(O("An element in ROOT doesn't have associated data",o,f),delete r[f])}else O("An element in ROOT was not a folder nor a file. ",o),delete r[f];else console.error("element[%s] is null",f),delete r[f]};e.isObject(s[p])||(O("STATIC_DATA was not an object"),s[p]={}),l(),function(){if(!u){"object"!=typeof s[m]&&(O("TRASH was not an object"),s[m]={});var n,t=s[m],r=function(t,r,o){if("object"==typeof t){if(!i.isSharedFolder(t.element))if(i.isFile(t.element,!0)||i.isFolder(t.element))if(Array.isArray(t.path)){if("string"==typeof t.element){var a=e.createRandomInteger();s[h][a]={href:i.cryptor.encrypt(t.element),filename:o},t.element=a}if(i.isFolder(t.element)&&l(t.element),"number"==typeof t.element)s[h][t.element]||s[p][t.element]||(O("An element in TRASH doesn't have associated data",t.element,o),n.push(r))}else n.push(r);else n.push(r)}else n.push(r)};for(var o in t)if(Array.isArray(t[o]))if(0===t[o].length)O("Empty array in TRASH root. ",t[o]),delete t[o];else{n=[];for(var a=0;a=0;c--)t[o].splice(n[c],1)}else O("An element in TRASH root is not an array. ",t[o]),delete t[o]}}(),function(){if(!u){Array.isArray(s[g])||(O("TEMPLATE was not an array"),s[g]=[]);var n=e.deduplicateString(s[g]);n.length!==s[g].length&&(s[g]=n);var t=s[g],r=i.getFiles([d]),o=[];t.forEach(function(n,a){if(i.isFile(n,!0)&&-1===r.indexOf(n)){if("string"==typeof n){var c=e.createRandomInteger();return s[h][c]={href:i.cryptor.encrypt(n)},void(t[a]=c)}if("number"==typeof n)s[h][n]||(O("An element in TEMPLATE doesn't have associated data",n),o.push(n))}else o.push(n)}),o.forEach(function(e){var n=t.indexOf(e);-1!==n&&t.splice(n,1)})}}(),function(){"object"!=typeof s[h]&&(O("FILES_DATA was not an object"),s[h]={});var e=s[h],t=i.getFiles([d,m,"hrefArray"]),r=i.find([d]),a=[];for(var u in e)if(String(u)===String(Number(u))){var l=e[u=Number(u)];if(l&&"object"==typeof l)if(l.href||l.roHref){var v;try{v=l.href&&(-1!==l.href.indexOf("#")?l.href:i.cryptor.decrypt(l.href))}catch(e){}if(!v||-1!==v.indexOf("#")){var y,g=n.parsePadUrl(v||l.roHref);if(g.hash)if(g.type){if(v&&"pad"===g.hashData.type&&g.hashData.version)if("view"===g.hashData.mode)l.roHref=v,delete l.href;else if(l.roHref){var E=n.parsePadUrl(l.roHref);E.hash&&E.type||(y=n.getSecrets(g.type,g.hash,l.password),l.roHref="/"+g.type+"/#"+n.getViewHashFromKeys(y))}else y=n.getSecrets(g.type,g.hash,l.password),l.roHref="/"+g.type+"/#"+n.getViewHashFromKeys(y);if(0===g.hashData.version&&delete l.roHref,v&&"/"!==v.slice(0,1)&&(l.href=i.cryptor.encrypt(n.getRelativeHref(v))),l.ctime||(l.ctime=l.atime),l.title||(l.title=i.getDefaultName(g)),!l.channel)try{y||(y=n.getSecrets(g.type,g.hash,l.password)),l.channel=y.channel,console.log(l),O("Adding missing channel in filesData ",l.channel)}catch(e){console.error(e)}if(n.isValidChannel(l.channel)||console.error("Remove invalid channel",l.channel,l),!c&&!o.testMode||-1!==t.indexOf(u));else O("An element in filesData was not in ROOT, TEMPLATE or TRASH.",u,l),r[n.createChannelId()]=u}else O("Removing an element in filesData with a invalid type.",l),a.push(u);else O("Removing an element in filesData with a invalid href.",l),a.push(u)}}else O("Removing an element in filesData with a missing href.",l),a.push(u);else O("An element in filesData was not an object.",l),a.push(u)}else O("Invalid file ID in filesData.",u),a.push(u);a.forEach(function(e){A(e)});var b=s[p],w=[];for(var D in b){var _=b[D=Number(D)];_&&"object"==typeof _&&_.href?!c&&!o.testMode||-1!==t.indexOf(D)||w.push(D):w.push(D)}w.forEach(function(e){f||delete s[p][e]})}(),Object.keys(s).forEach(function(e){"/"===e.slice(0,1)&&delete s[e]}),function(){if(!u){"object"!=typeof s[E]&&(O("SHARED_FOLDER was not an object"),s[E]={});var e,t,r=s[E],o=i.getFiles([d,m]),a=i.find([d]);for(var c in r){var f;t=r[c],c=Number(c);try{f=t.href&&(-1!==t.href.indexOf("#")?t.href:i.cryptor.decrypt(t.href))}catch(e){}if((e=n.parsePadUrl(f||t.roHref))&&e.hash&&"undefined"!==e.hash){if(-1===o.indexOf(c))console.log("missing"+c),a[n.createChannelId()]=c}else delete r[c]}}}(),function(){if(!u){"object"!=typeof s[b]&&(O("SHARED_FOLDER_TEMP was not an object"),s[b]={});var e=s[b],n=s[E];for(var t in e)n[t]&&delete e[t]}}();var v=+new Date-r+"ms";JSON.stringify(s)===a?O("File system was clean.",v):O("Your file system was corrupted. It has been cleaned so that the pads you visit can be stored safely.",v)}},i},o};e.exports&&(e.exports=n(Z(),te(),je()))})()}(Le)),Le.exports}function Ue(){return Re||(Re=1,function(e){(()=>{const n=(e,n,t,r,o,a={})=>{let i=globalThis;var s={setCustomize:e=>{a=e.Messages,r.setCustomize(e)}},c=s.ROOT="root",u=s.UNSORTED="unsorted",f=s.TRASH="trash",l=s.TEMPLATE="template",d=s.SHARED_FOLDERS="sharedFolders",h=s.SHARED_FOLDERS_TEMP="sharedFoldersTemp",p=s.FILES_DATA=t.storageKey,v=s.OLD_FILES_DATA=t.oldStorageKey,y=s.STATIC_DATA="static";s.getDefaultName=function(e){var n=e.type;return a.type[n]+" - "+function(){if(i.Intl&&i.Intl.DateTimeFormat)return new i.Intl.DateTimeFormat(void 0,{weekday:"short",year:"numeric",month:"long",day:"numeric"}).format(new Date);return(new Date).toString().split(" ").slice(0,4).join(" ")}()};var m=s.createCryptor=function(e){var n={};if(!e)return n.encrypt=function(e){return e},n.decrypt=function(e){return e},n;try{var t=o.createEncryptor(e);n.encrypt=function(e){try{return"/file/#"===e.slice(0,7)?e:t.encrypt(e)}catch(e){return}},n.decrypt=function(e){try{return t.decrypt(e)}catch(e){return}}}catch(e){console.error(e)}return n};return s.getHref=function(e,n){if(e.href&&-1!==e.href.indexOf("#"))return e.href;if(e.href&&n){var t=n.decrypt(e.href);if(t&&-1!==t.indexOf("#"))return t}return e.roHref},s.reencrypt=function(e,n,t){if(t){var r=m(e),o=m(n);Object.keys(t[p]).forEach(function(e){var n=t[p][e]||{};if(n.href&&n.roHref&&!n.fileType){var a=n.href&&-1===n.href.indexOf("#")?r.decrypt(n.href):n.href;if(!a)return;n.href=o.encrypt(a)}}),Object.keys(t[d]||{}).forEach(function(e){var n=t[d][e]||{};if(n.href){var a=n.href&&-1===n.href.indexOf("#")?r.decrypt(n.href):n.href;if(!a)return;n.href=o.encrypt(a)}}),Object.keys(t[h]||{}).forEach(function(e){var n=t[h][e]||{};if(n.href){var a=n.href&&-1===n.href.indexOf("#")?r.decrypt(n.href):n.href;if(!a)return;n.href=o.encrypt(a)}})}else console.error("Nothing to reencrypt")},s.init=function(t,o){var i={};i.cryptor=m(o.editKey),i.setReadOnly=function(e,n){o.editKey=n,i.cryptor=m(n),i.cryptor.k=Math.random(),i.readOnly=e,i._setReadOnly&&i._setReadOnly(e)},i.readOnly=o.readOnly,i.reencrypt=s.reencrypt,i.getDefaultName=s.getDefaultName;var g=o.sframeChan,E=a.fm_newFolder||"New folder",b=a.fm_newFile||"New file";i.ROOT=c,i.STATIC_DATA=y,i.UNSORTED=u,i.TRASH=f,i.TEMPLATE=l,i.SHARED_FOLDERS=d,i.SHARED_FOLDERS_TEMP=h,i.FILES_DATA=p,i.OLD_FILES_DATA=v;var O=i.sharedFolder=o.sharedFolder;i.id=o.id;var A=function(){console.debug.apply(console,arguments)},w=i.log=o.log||A,D=o.logError||A,_=i.debug=o.debug||A;i.fixFiles=function(){};var T=i.error=function(){g?g.query("Q_DRIVE_USEROBJECT",{cmd:"fixFiles",data:{}},function(){}):("function"==typeof i.fixFiles&&i.fixFiles(),console.error.apply(console,arguments),i.fixFiles())};o.outer&&r.init(o,i,t),i.getStructure=function(){var e={};return e[c]={},e[f]={},e[p]={},e[l]=[],e[d]={},e};var S=i.getHref=function(e){return s.getHref(e,i.cryptor)},N=function(e){return null===e?"null":Array.isArray(e)?"array":typeof e};i.isValidDrive=function(e){var n=i.getStructure();return"object"==typeof e&&Object.keys(n).every(function(t){return e[t]&&N(n[t])===N(e[t])})};var I=function(){return[l]},x=function(e,n){return e===n},C=i.isSharedFolder=function(e){return!O&&Boolean(t[d]&&t[d][e])},R=i.isFile=function(e,n){return!C(e)&&("number"==typeof e||(void 0!==t[v]||n)&&"string"==typeof e)},P=i.isFolderData=function(e){return"object"==typeof e&&!0===e.metadata};i.isReadOnlyFile=function(e){if(!R(e))return!1;var n=i.getFileData(e);return n.roHref?Boolean(n.roHref&&!n.href):void 0},i.isStaticFile=function(e){return Boolean(t[y]&&t[y][e])};var k=i.isFolder=function(e){return!P(e)&&("object"==typeof e&&!e.channel||C(e))};i.isFolderEmpty=function(e){return!!k(e)&&(0===Object.keys(e).length||!(1!==Object.keys(e).length||!P(e[Object.keys(e)[0]])))},i.hasSubfolder=function(e,n){if(!k(e))return!1;var t=0,r=function(e){t+=k(e.element)?1:0};for(var o in e)n?Array.isArray(e[o])&&e[o].forEach(r):t+=k(e[o])?1:0;return t},i.hasFile=function(e,n){if(!k(e))return!1;var t=0,r=function(e){t+=R(e.element)?1:0};for(var o in e)n?Array.isArray(e[o])&&e[o].forEach(r):t+=R(e[o])?1:0;return t},i.hasFolderData=function(e){for(var n in e)if(P(e[n]))return!0};var M=i.hasSubSharedFolder=function(e){for(var n in e){if(C(e[n]))return!0;if(k(e[n])&&M(e[n]))return!0}return!1},F=i.getFileData=function(n,r){if(n){var a,s;try{a=(t[y]||{})[n]}catch(e){console.error(e)}if(a){var c=r?a:e.clone(a);return r||(c.static=!0),c}try{s=t[p][n]||{}}catch(e){console.error(e),s={}}if(!r&&(s=JSON.parse(JSON.stringify(s))).href&&-1===s.href.indexOf("#"))if(o.editKey)try{s.href=i.cryptor.decrypt(s.href)}catch(e){delete s.href}else delete s.href;return s}};i.getFolderData=function(e){for(var n in e)if(P(e[n]))return e[n];return{}};var L=i.getTitle=function(e,n){if(C(e))return"??";var t=F(e);if(t){if(t.static)return t.name;if(e&&(t.href||t.roHref))return"title"===n?t.title:"name"===n?t.filename:t.filename||t.title||b;T("getTitle called with a non-existing file id: ",e,t)}else T("unable to retrieve data about the requested file: ",e,t)},H=i.comparePath=function(e,n){if(!(e&&n&&Array.isArray(e)&&Array.isArray(n)))return!1;if(e.length!==n.length)return!1;for(var t=!0,r=e.length-1;t&&r>=0;)t=e[r]===n[r],r--;return t},j=i.isSubpath=function(e,n){var t=n.slice(),r=e.slice(0,t.length);return H(t,r)},K=i.isPathIn=function(e,n){if(n){var t=n.indexOf("hrefArray");return-1!==t&&(n.splice(t,1),n=n.concat(I())),n.some(function(n){return Array.isArray(e)&&e[0]===n})}},U=i.isInTrashRoot=function(e){return e[0]===f&&4===e.length},B=function(e,n){if(n){if(0===n.length)return e;var t=n.slice(),r=t.shift();if(void 0!==e[r])return B(e[r],t);_("Unable to find the key '"+r+"' in the root object provided:",e)}else T("Invalid path:\n",n,"\nin root\n",e)},V=i.find=function(e){return B(t,e)},Y=i.getFilesRecursively=function(e,n){for(var t in n=n||[],e)R(e[t])||C(e[t])?-1===n.indexOf(e[t])&&n.push(e[t]):P(e[t])||Y(e[t],n);return n},G={array:function(e){return t[e]||(t[e]=[]),t[e].slice()}};I().forEach(function(e){G[e]=function(){return G.array(e)}}),G.hrefArray=function(){var n=[];return O?n:(I().forEach(function(e){n=n.concat(G[e]())}),e.deduplicateString(n))},G[c]=function(){var e=[];return Y(t[c],e),e},G[f]=function(){var e=t[f],n=[],r=function(e){R(e.element)||C(e.element)?-1===n.indexOf(e.element)&&n.push(e.element):Y(e.element,n)};for(var o in e){if(!Array.isArray(e[o]))return void T("Trash contains a non-array element");e[o].forEach(r)}return n},G[v]=function(){var e=[];return t[v]?(t[v].forEach(function(n){n.href&&-1===e.indexOf(n.href)&&e.push(n.href)}),e):e},G[y]=function(){return t[y]?Object.keys(t[y]).map(Number).filter(Boolean):[]},G[p]=function(){return t[p]?Object.keys(t[p]).map(Number).filter(Boolean):[]},G[d]=function(){return t[d]?Object.keys(t[d]).map(Number).filter(Boolean):[]};var J=i.getFiles=function(n){var t=[];return n&&n.length||(n=[c,"hrefArray",f,v,p,d]),n.forEach(function(e){"function"==typeof G[e]&&(t=t.concat(G[e]()))}),e.deduplicateString(t)},q=i.getIdFromHref=function(e){var r,o=function(e){if(e)return n.parsePadUrl(e).getUrl().replace(/\/p\/?/,"/")},a=o(e);return J([p]).some(function(e){if(o(S(t[p][e]))===a||o(t[p][e].roHref)===a)return r=e,!0}),r};i.getSFIdFromHref=function(e){var r,o=function(e){if(e)return n.parsePadUrl(e).getUrl().replace(/\/p\/?/,"/")},a=o(e);return J([d]).some(function(e){if(o(S(t[d][e]))===a||o(t[d][e].roHref)===a)return r=e,!0}),r};var W=function(e,n){if(!K(e,[c,f]))return[];n=Array.isArray(n)?n:[n];var t={},r=V(e),o=function(e){Object.keys(e).forEach(n=>{t[n]||=[],Array.prototype.push.apply(t[n],e[n])})};if(R(r)||C(r))return n.some(n=>{x(n,r)&&(t[n]||=[],t[n].push(e))}),t;if(k(r))for(var a in r){let t=e.slice();t.push(a),o(W(t,n))}return t},z=function(e,n){if(O)return{};if(!t[e])return{};var r=t[e].slice(),o={},a=-1;return n.forEach(n=>{for(;-1!==(a=r.indexOf(n,a+1));)o[n]||=[],o[n].push([e,a])}),o},Q=function(e,n){if(O)return[];var t=V(e),r={},o=function(e){Object.keys(e).forEach(n=>{r[n]||=[],Array.prototype.push.apply(r[n],e[n])})};if(1===e.length&&"object"==typeof t&&Object.keys(t).forEach(function(r){var a=t[r];if(Array.isArray(a)){var i=e.slice();i.push(r),o(Q(i,n))}}),2===e.length){if(!Array.isArray(t))return[];t.forEach(function(t,a){var i=e.slice();i.push(a),i.push("element"),R(t.element)?n.some(e=>{x(e,t.element)&&(r[e]||=[],r[e].push(i))}):o(Q(i,n))})}return e.length>=4&&o(W(e,n)),r},Z=i.findFiles=function(e){var n=W([c],e),t=z(l,e),r=Q([f],e);let o={};return e.forEach(e=>{o[e]=[]}),[n,t,r].forEach(e=>{Object.keys(e).forEach(n=>{o[n]||=[],Array.prototype.push.apply(o[n],e[n])})}),o},X=i.findFile=function(e){return Z([e])[e]||[]};i.findChannels=function(e,n){var r=t[p],o=t[d],a=[p];return n&&a.push(d),J(a).filter(function(n){var t=r[n]||o[n]||{};return-1!==e.indexOf(t.channel)})},i.search=function(r){if("string"!=typeof r)return[];r=r.trim();var o,a=[],s=t[p],u=t[d],f=r.toLowerCase();/^#/.test(f)&&(o=[f.slice(1).trim()]);J([p,d]).forEach(function(e){var n=s[e]||u[e];if(n)if(Array.isArray(n.tags)&&(t=n.tags,o&&t.length&&(t=t.map(function(e){return e.toLowerCase()}),o.some(function(e){return t.some(function(n){return n===e})}))))a.push(e);else{var t,r=n.title||n.lastTitle;(r&&-1!==r.toLowerCase().indexOf(f)||n.filename&&-1!==n.filename.toLowerCase().indexOf(f))&&a.push(e)}});var l=n.getRelativeHref(r);if(l){var h=q(l);h&&a.push(h)}a=e.deduplicateString(a);var v=[];a.forEach(function(e){v.push({id:e,paths:X(e),data:i.getFileData(e)})});var y=[],m=function(e,n){for(var t in e)k(e[t])&&!C(e[t])&&(-1!==t.toLowerCase().indexOf(f)&&y.push({id:null,paths:[n.concat(t)],data:{title:t}}),m(e[t],n.concat(t)))};return m(t[c],[c]),y=y.sort(function(e,n){return e.data.title.toLowerCase()>n.data.title.toLowerCase()}),v=y.concat(v)},i.getRecentPads=function(){var e=t[p];return Object.keys(e).filter(function(n){return e[n]}).sort(function(n,t){return e[t].atime-e[n].atime}).map(function(e){return Number(e)})},i.getOwnedPads=function(e){var n=t[p];return Object.keys(n).filter(function(t){return n[t].owners&&-1!==n[t].owners.indexOf(e)}).map(function(e){return Number(e)})};var $=i.getAvailableName=function(e,n){if(void 0===e[n])return n;for(var t=n,r=1;void 0!==e[t];)t=n+"_"+r,r++;return t},ee=i.move=function(e,n,t){if(g)g.query("Q_DRIVE_USEROBJECT",{cmd:"move",data:{paths:e,newPath:n}},t);else{var r=[];e.forEach(function(e){var t=e.slice();t.pop(),H(t,n)||(j(n,e)?w(a.fo_moveFolderToChildError):i.copyElement(e.slice(),n)&&r.push(e))}),i.delete(r,t)}};return i.restore=function(e,n){if(g)g.query("Q_DRIVE_USEROBJECT",{cmd:"restore",data:{path:e}},n);else if(U(e)){var t=e.slice();t.pop();var r=V(t).path;ee([e],r,n)}},i.addFolder=function(e,n,t){if(g)g.query("Q_DRIVE_USEROBJECT",{cmd:"addFolder",data:{path:e,name:n}},t);else{var r=V(e),o=$(r,n||E);r[o]={};var a=e.slice();a.push(o),t({newPath:a})}},i.delete=function(e,n,t){g?g.query("Q_DRIVE_USEROBJECT",{cmd:"delete",data:{paths:e,nocheck:t}},n):(n=n||function(){},i.deleteMultiplePermanently(e,t,n))},i.emptyTrash=function(e){e=e||function(){},g?g.query("Q_DRIVE_USEROBJECT",{cmd:"emptyTrash"},e):(t[f]={},i.checkDeletedFiles(e))},i.ownedInTrash=function(e){return J([f]).map(function(n){var r=C(n)?t[d][n]:i.getFileData(n);if(r)return e(r.owners)?r.channel:void 0}).filter(Boolean)},i.rename=function(e,n,r){if(r=r||function(){},g)g.query("Q_DRIVE_USEROBJECT",{cmd:"rename",data:{path:e,newName:n}},r);else if(e.length<=1)D("Renaming `root` is forbidden");else{var o,i=V(e);if(k(i)&&!C(i)){var s=e.slice(),c=s.pop();if(!n||!n.trim()||c===n)return;var u=V(s);return void 0!==u[n]?void w(a.fo_existingNameError):(u[n]=i,delete u[c],void("function"==typeof r&&r()))}if(o=C(i)?t[d][i]:t[p][i]||t[y][i])return t[y][i]?n&&n.trim()?(o.name=n,void r()):void r():n&&""!==n.trim()?void(L(i,"name")!==n&&(o.filename=n,"function"==typeof r&&r())):(delete o.filename,void("function"==typeof r&&r()))}},i.getTagsList=function(){var e,n={},r=function(e){n[e]=n[e]?++n[e]:1};for(var o in t[p])(e=t[p][o]).tags&&Array.isArray(e.tags)&&e.tags.forEach(r);return n},i},s};e.exports&&(e.exports=n(Z(),te(),Y(),Ke(),M(),void 0))})()}(Fe)),Fe.exports}var Be,Ve,Ye,Ge,Je={exports:{}};function qe(){return Be||(Be=1,function(e){e.exports=function(e){var n,t=[],r=[],o=0,a=function(e){return o++,function(){for(e&&e.apply(null,arguments),o=(o||1)-1;!o&&t.length&&!n;)t.shift()(a)}};a.abort=function(){r.forEach(clearTimeout),n=1};var i={nThen:function(e){return n||(o?t.push(e):e(a)),i},orTimeout:function(e,s){if(n)return i;if(!s)throw Error("Must specify milliseconds to orTimeout()");var c,u=setTimeout(function(){for(;t.shift()!==c;);for(e(a),o=(o||1)-1;!o&&t.length;)t.shift()(a)},s);return t.push(c=function(){var e=r.indexOf(u);if(e>-1)return r.splice(e,1),void clearTimeout(u);throw new Error("timeout not listed in array")}),r.push(u),i}};return i.nThen(e)}}(Je)),Je.exports}function We(){if(Ye)return Ve;Ye=1;return Ve=((e,n,t,r,o,a,i,s)=>{var c={},u={};return c.checkMigration=function(e,t,r,o){var a=n.once(n.mkAsync(o));if(t)if(e)if(t.version>=2)a();else if(t.migrateRo){var i,s=!1,c=setInterval(function(){if(t.version>=2)return s=!0,clearTimeout(i),clearInterval(c),void a()},100);i=setTimeout(function(){clearInterval(c),r.migrateReadOnly(function(){s=!0,a()})},2e4);t.on("change",["version"],function(){s||t.version>=2&&(s=!0,clearTimeout(i),clearInterval(c),a())})}else r.migrateReadOnly(a);else a();else a()},c.migrate=function(e){var t=u[e];if(t){var r=t.teams;if(Array.isArray(r)&&r.length){var o=r[0];if(o.secondaryKey){var a=n.find(o,["store","manager","folders",o.id]);a&&a.proxy&&!a.proxy.version&&a.userObject.migrateReadOnly(function(){r.forEach(function(e){n.find(e,["store","manager","folders",e.id,"userObject"]).setReadOnly(!1,e.secondarykey)})})}}}},c.load=function(t,f,l,d){var h=n.once(n.mkAsync(d)),p=t.network,v=t.store,y=t.isNew,m=t.isNewChannel,g=v.id,E=v.handleSharedFolder,b=v.manager.user.userObject.getHref(l),O=e.parsePadUrl(b),A=e.getSecrets("drive",O.hash,l.password);if(!A.keys)return v.manager.deprecateProxy(f),void h(null);var w=A.keys.secondaryKey;o(function(e){t.cache&&r.getChannelCache(A.channel,e(function(n){if("EINVAL"===n)return e.abort(),v.manager.restrictedProxy(f,A.channel),void h(null)}))}).nThen(function(e){m(null,{channel:A.channel},e(function(n){if(n.isNew&&!y)return v.manager.deprecateProxy(f,A.channel,n.reason),e.abort(),void h(null)}))}).nThen(function(){var e=u[A.channel];if(e&&e.readOnly&&w&&c.upgrade(A.channel,A),e&&e.ready&&e.rt)return setTimeout(function(){v.manager.addProxy(f,e.rt,function(){c.leave(A.channel,g)},w),h(e.rt)}),e.teams.push({cb:h,store:v,id:f}),void(E&&E(f,e.rt));if(e&&!e.ready&&e.rt)return e.teams.push({cb:h,store:v,secondaryKey:w,id:f}),void(E&&E(f,e.rt));e=u[A.channel]={teams:[{cb:h,store:v,secondaryKey:w,id:f}],readOnly:!Boolean(w)};var n=l.owners,o={data:{},channel:A.channel,readOnly:!Boolean(w),crypto:a.createEncryptor(A.keys),userName:"sharedFolder",logLevel:1,ChainPad:s,classic:!0,network:p,Cache:r,metadata:{validateKey:A.keys.validateKey||void 0,owners:n},onRejected:t.Store&&t.Store.onRejected},d=e.rt=i.create(o);d.proxy.on("cacheready",function(){e.teams&&(e.teams.forEach(function(n){d.cache=!0,n.store.manager.addProxy(n.id,d,function(){c.leave(A.channel,n.store.id)},n.secondaryKey,t.updatePassword),t.updatePassword=!1,n.cb(e.rt)}),e.ready=!0)}),d.proxy.on("ready",function(){y&&!Object.keys(d.proxy).length&&(d.proxy.version=2),e.teams&&(e.teams.forEach(function(n){d.cache=!1,n.store.manager.addProxy(n.id,d,function(){c.leave(A.channel,n.store.id)},n.secondaryKey,t.updatePassword),n.cb(e.rt)}),e.ready=!0)}),d.proxy.on("error",function(n){if(n&&n.error){if("EDELETED"===n.error){try{e.teams.forEach(function(e){e.store.manager.deprecateProxy(e.id,A.channel,n.message),e.store.handleSharedFolder&&e.store.handleSharedFolder(e.id,null),e.cb()})}catch(e){}return delete u[A.channel],void h()}if("ERESTRICTED"===n.error)return e.teams.forEach(function(e){e.store.manager.restrictedProxy(e.id,A.channel),e.cb()}),delete u[A.channel],void h()}}),E&&E(f,d)})},c.upgrade=function(e,n){var t=u[e];if(t&&t.readOnly&&t.rt.setReadOnly&&n.keys&&n.keys.editKeyStr){var r=a.createEncryptor(n.keys);t.readOnly=!1,t.rt.setReadOnly(!1,r)}},c.leave=function(e,n){var t=u[e];if(t){var r,o=t.teams;if(Array.isArray(o))o.some(function(e,t){if(e.store.id===n)return e.store.handleSharedFolder&&e.store.handleSharedFolder(e.id,null),r=t,!0}),void 0!==r&&(o.splice(r,1),o.length||t.rt&&t.rt.stop&&t.rt.stop())}},c.updatePassword=function(r,a,i,s){var f=a.oldChannel,l=a.href,d=a.password,h=e.parsePadUrl(l),p=e.getSecrets(h.type,h.hash,d),v=u[f];if(v){if(v.rt&&v.rt.stop)try{v.rt.stop()}catch(e){}var y=o;v.teams.forEach(function(e){y=y(function(o){var a=e.store,s=e.id,u=n.find(a.proxy,["drive",t.SHARED_FOLDERS])||{};if(s&&u[s]){var l=JSON.parse(JSON.stringify(u[s]));l.password=d,c.load({network:i,store:a,updatePassword:!0,Store:r,isNewChannel:r.isNewChannel},s,l,o()),a.rpc&&(a.rpc.unpin([f],o()),a.rpc.pin([p.channel],o()))}}).nThen}),y(function(){s()})}else s({error:"ENOTFOUND"})},c.loadSharedFolders=function(e,n,r,a,i,s,u,f){var l=a[t.SHARED_FOLDERS]||{},d=Object.keys(l).length,h=1,p=s();u=u||function(){},o(function(t){Object.keys(l).forEach(function(o){var a=l[o];c.load({network:n,store:r,Store:e,cache:f,isNewChannel:e.isNewChannel},o,a,t(function(){u({progress:h,max:d}),h++}))})}).nThen(function(){setTimeout(p)})},c.isSharedFolderChannel=function(e){return Object.keys(u).includes(e)},c})(te(),Z(),Ue(),fe(),qe(),M(),T(),x()),Ve}function ze(){return Ge||(Ge=1,function(e){(()=>{const n=(e,n,t,r={},o,a,i={})=>{var s=function(n,t,r,o,a,i){if(!n.folders[t]||i||n.folders[t].restricted){var s=function(e){var n={};for(var t in e.cfg)n[t]=e.cfg[t];return n}(n);s.sharedFolder=!0,s.id=t,s.editKey=a,s.rt=r.realtime,s.readOnly=Boolean(!a);var c=e.init(r.proxy,s);c.fixFiles&&c.fixFiles();var u=r.proxy;if(u.metadata&&u.metadata.title){var f=n.user.proxy[e.SHARED_FOLDERS][t];f&&(f.lastTitle=u.metadata.title)}return n.folders[t]={proxy:r.proxy,userObject:c,leave:o,restricted:u.restricted,offline:Boolean(r.cache)},u.on&&(u.on("disconnect",function(){n.folders[t].offline=!0}),u.on("reconnect",function(){n.folders[t].offline=!1})),c}n.folders[t].offline&&!r.cache&&n.Store&&(n.folders[t].offline=!1,n.folders[t].userObject.fixFiles&&n.folders[t].userObject.fixFiles(),n.Store.refreshDriveUI())},c=function(e,n){var t=e.folders[n];t&&(t.leave(),delete e.folders[n])},u=function(t,r,o,a){if(!t.folders[r]||!t.folders[r].deleting){if(t.user.userObject.readOnly){return c(t,r),s(t,r,{proxy:{deprecated:!0}},function(){}),void t.Store.refreshDriveUI()}if(o&&t.unpinPads([o],function(){}),a&&"PASSWORD_CHANGE"!==a){let o=n.find(t,["user","proxy",e.SHARED_FOLDERS]),a=o[r]&&o[r].lastTitle;return a&&((e,n,t)=>{var r=e.store.mailbox;if(r){var o,a=e.cfg.teamId;o=a?e.store.modules.team.getTeamsData()[a]:e.Store.getMetadata(null,null,()=>{}).user,r.sendTo("SF_DELETED",{sfId:n,team:a,title:t},{curvePublic:o.curvePublic,channel:o.notifications},e=>{console.error(e)})}})(t,r,a),delete o[r],void(t.Store&&t.Store.refreshDriveUI&&t.Store.refreshDriveUI())}t.user.userObject.deprecateSharedFolder(r,a),c(t,r),t.Store&&t.Store.refreshDriveUI&&t.Store.refreshDriveUI()}},f=function(e,n){c(e,n),s(e,n,{proxy:{restricted:!0,root:{},filesData:{}}},function(){}),e.Store.refreshDriveUI()},l=function(e,n){return Array.isArray(n)&&-1!==n.indexOf(e.edPublic)},d=function(e){var n=[e.user.userObject],t=Object.keys(e.folders).map(function(n){return e.folders[n].userObject});return Array.prototype.push.apply(n,t),n},h=function(e,n){var t=d(e),r=e.user.userObject;return t.some(function(e){if(Object.keys(e.getFileData(n)).length)return r=e,!0}),r},p=function(e,n){var t=Number(n.id);if(t)return e.user.userObject.findFile(t)[0]},v=function(n,t,r){var o=[];return n.user.userObject.findChannels([t],!0).forEach(function(t){var a=n.user.proxy[e.SHARED_FOLDERS][t];a&&!r&&(a=JSON.parse(JSON.stringify(a))),a||(a=n.user.userObject.getFileData(t,r)),o.push({id:t,data:a,userObject:n.user.userObject})}),Object.keys(n.folders).forEach(function(e){n.folders[e].userObject.findChannels([t]).forEach(function(t){o.push({id:t,fId:e,data:n.folders[e].userObject.getFileData(t,r),userObject:n.folders[e].userObject})})}),o},y=function(e,n){var t=[],r=e.user.userObject.getIdFromHref(n);return r&&t.push({data:e.user.userObject.getFileData(r),userObject:e.user.userObject}),Object.keys(e.folders).forEach(function(r){var o=e.folders[r].userObject.getIdFromHref(n);o&&t.push({fId:r,data:e.folders[r].userObject.getFileData(o),userObject:e.folders[r].userObject})}),t},m=function(e,n){var t=[],r=d(e);let o={};return r.forEach(function(e){var a=Number(e.id);let i;if(a){i=e.findFile(n);let t=(o[a]||[])[0];if(!t)return;i.forEach(function(e){Array.prototype.unshift.apply(e,t)})}else{let t=[n],a=r.map(e=>+e.id).filter(Boolean);Array.prototype.push.apply(t,a),o=e.findFiles(t),i=o[n]}Array.prototype.push.apply(t,i)}),t},g=function(e,n){var t={},r=d(e);let o={};return r.forEach(function(e){var a=Number(e.id);if(!e.id){let e=r.map(e=>+e.id).filter(Boolean);Array.prototype.push.apply(n,e)}var i=e.findFiles(n);if(e.id||(o=i),a){let e=(o[a]||[])[0];if(!e)return;Object.keys(i).forEach(n=>{i[n].forEach(n=>{Array.prototype.unshift.apply(n,e)})})}Object.keys(i).forEach(e=>{t[e]||=[],Array.prototype.push.apply(t[e],i[e])})}),t},E=function(e,t,r){if(r)return e.user.userObject.findChannels(t);var o=[];return d(e).forEach(function(e){var n=e.findChannels(t);Array.prototype.push.apply(o,n)}),o=n.deduplicateString(o)},b=function(e,n,t){var r=d(e),o={};return r.some(function(e){if((o=e.getFileData(n,t))&&Object.keys(o).length)return!0}),o},O=function(t,r){var o;if(t.isHistoryMode&&!t.folders[r])o=!0;else if(!t.folders[r])return{};var a=o?{}:t.folders[r].proxy;Object.keys(a.metadata||{}).length>1&&(a.metadata={title:a.metadata.title});var i=n.clone(a.metadata||{});for(var s in t.user.proxy[e.SHARED_FOLDERS][r]||{})if(void 0!==t.user.proxy[e.SHARED_FOLDERS][r][s]){var c=n.clone(t.user.proxy[e.SHARED_FOLDERS][r][s]);if("href"===s&&-1===c.indexOf("#"))try{c=t.user.userObject.cryptor.decrypt(c)}catch(e){}"href"===s&&-1===c.indexOf("#")&&(c=void 0),i[s]=c}return i},A=function(e,n){var t,r={id:null,userObject:e.user.userObject,path:n};if(!Array.isArray(n)||n.length<=1)return r;for(var o=e.user.userObject,a=2;a{r=n.Messages,e.setCustomize(n)},create:function(n,t,r){var o={pinPads:t.pin,unpinPads:t.unpin,onSync:t.onSync,Store:t.Store,store:t.store,removeOwnedChannel:t.removeOwnedChannel,loadSharedFolder:t.loadSharedFolder,cfg:r,edPublic:t.edPublic,settings:t.settings,user:{proxy:n},folders:{}};r.removeProxy=function(e){c(o,e)},o.user.userObject=e.init(n,r);var a=function(e){return function(){return[].unshift.call(arguments,o),e.apply(null,arguments)}};return{addProxy:a(s),removeProxy:a(c),deprecateProxy:a(u),restrictedProxy:a(f),addSharedFolder:a(I),addPin:function(e,n){o.pinPads=e,o.unpinPads=n},removePin:function(){delete o.pinPads,delete o.unpinPads},command:a(P),getPadAttribute:a(M),setPadAttribute:a(k),getTagsList:a(F),getSecureFilesList:a(L),getSharedFolderData:a(O),getChannelsList:a(j),addPad:a(K),delete:a(x),deleteOwned:a(C),findChannel:a(v),findHref:a(y),findFile:a(m),getEditHash:a(S),user:o.user,folders:o.folders}},createInner:function(n,t,r,o){var a={cfg:o,sframeChan:t,edPublic:r,user:{proxy:n,userObject:e.init(n,o)},folders:{}},i=function(e){return function(){return[].unshift.call(arguments,a),e.apply(null,arguments)}};return{addProxy:i(s),removeProxy:i(c),setHistoryMode:i(le),rename:i(U),move:i(B),emptyTrash:i(V),addFolder:i(Y),addSharedFolder:i(G),addLink:i(J),restoreSharedFolder:i(q),convertFolderToSharedFolder:i(W),delete:i(z),deleteOwned:i(Q),restore:i(Z),setFolderData:i(X),updateStaticAccess:i($),getFileData:i(ne),find:i(re),getTitle:i(oe),isReadOnlyFile:i(ie),isStaticFile:i(ae),getFiles:i(se),search:i(ce),getRecentPads:i(ue),getOwnedPads:i(fe),getTagsList:i(F),findFile:i(m),findFiles:i(g),findChannels:i(ee),getSharedFolderData:i(O),getFolderData:i(de),isInSharedFolder:i(he),getUserObjectPath:i(te),isDuplicateOwned:i(Se),ownedInTrash:i(Te),isValidDrive:i(pe),isFile:i(ve),isFolder:i(ye),isSharedFolder:i(me),isFolderEmpty:i(ge),isPathIn:i(Ee),isSubpath:i(be),isInTrashRoot:i(Oe),comparePath:i(Ae),hasSubfolder:i(we),hasSubSharedFolder:i(De),hasFile:i(_e),user:a.user,folders:a.folders}}}};e.exports&&(e.exports=n(Ue(),Z(),te(),void 0,Ae(),qe(),We()))})()}(Me)),Me.exports}var Qe,Ze,Xe=ze(),$e=n({__proto__:null,default:r(Xe)},[Xe]),en=Ue(),nn=n({__proto__:null,default:r(en)},[en]),tn={exports:{}},rn={exports:{}};function on(){return Ze||(Ze=1,function(e){e.exports&&(e.exports=((e={},n={},t)=>{let r=[];const o=["sheet","doc","presentation"],a=a=>{e=a.AppConfig;const i=(n=a.ApiConfig).onlyOffice&&n.onlyOffice.availableVersions.includes(t.currentVersion);r=e.availablePadTypes.filter(e=>i||!o.includes(e))};Object.keys(e).length&&a({AppConfig:e,ApiConfig:n});const i={OO_APPS:o,setCustomize:a};return i.__defineGetter__("availableTypes",function(){return n.appsToDisable?r.filter(e=>!n.appsToDisable.includes(e)):r}),i.__defineGetter__("appsToSelect",function(){return r.filter(e=>!["drive","teams","file","contacts","convert"].includes(e))}),i.isAvailable=e=>Array.isArray(i.availableTypes)&&i.availableTypes.includes(e),i})(void 0,void 0,(Qe||(Qe=1,function(e){e.exports&&(e.exports={currentVersionNumber:8,currentVersion:"v8"})}(rn)),rn.exports)))}(tn)),tn.exports}var an,sn,cn=on(),un=n({__proto__:null,default:r(cn)},[cn]),fn={exports:{}},ln={exports:{}};function dn(){return an||(an=1,function(e){(()=>{const n=(e,n,t={},r)=>{const o=function(){if(Object.keys(t).length){var e,n=new URL(t.httpUnsafeOrigin);try{return(e=new URL(t.websocketPath,t.httpUnsafeOrigin)).protocol=n.protocol,e.origin}catch(e){return console.error(e),t.httpUnsafeOrigin}}};var a=o();var i=e=>JSON.parse(JSON.stringify(e)),s=function(e,t,r){var o=n.once(n.mkAsync(r));fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}).then(e=>{e.ok?e.text().then(e=>{o(void 0,n.tryParse(e))}):e.json().then().then(n=>{o(e.status,n)})}).catch(e=>{o(e)})},c=function(t,o,c){var u=i(o);u.publicKey=n.encodeBase64(t.publicKey),u.nonce=n.encodeBase64(r.randomBytes(24));var f,l,d=new URL("/api/auth/",a);e(function(e){s(d,u,e((n,t)=>n?(e.abort(),console.error(n),t&&console.error(t),void c(n)):t.date&&t.txid?(f=t.txid,void(l=t.date)):(e.abort(),void c("REQUEST_REJECTED"))))}).nThen(function(e){var o=i(u);o.txid=f,o.date=l;var a=n.decodeUTF8(JSON.stringify(o)),h=r.sign.detached(a,t.secretKey),p=n.encodeBase64(h);s(d,{sig:p,txid:f},e((n,t)=>{if(n)return e.abort(),console.error(n),t&&console.error(t),void c("RESPONSE_REJECTED",t);c(void 0,t)}))})};return c.setCustomize=e=>{t=e.ApiConfig,a=o()},c};e.exports&&(e.exports=n(qe(),Z(),void 0,h()))})()}(ln)),ln.exports}function hn(){return sn||(sn=1,function(e){e.exports&&(e.exports=((e,n={},t,r)=>{var o={setCustomize:e=>{n=e.ApiConfig,t.setCustomize(e)}};o.join=e.uint8ArrayJoin,o.seed=function(){return r.hash(e.decodeUTF8("pewpewpew"))},o.genkeys=function(e){if(!(e instanceof Uint8Array))throw new Error("INVALID_SEED_FORMAT");if(!e||"number"!=typeof e.length||e.length<64)throw new Error("INVALID_SEED_LENGTH");var n=e.subarray(0,r.sign.seedLength),t=e.subarray(r.sign.seedLength,r.sign.seedLength+r.secretbox.keyLength);return{sign:r.sign.keyPair.fromSeed(n),symmetric:t}},o.keysToRPCFormat=function(n){try{var t=n.sign;return{edPrivate:e.encodeBase64(t.secretKey),edPublic:e.encodeBase64(t.publicKey)}}catch(e){return void console.error(e)}},o.encrypt=function(n,t,a){var i=e.decodeUTF8(t),s=r.randomBytes(r.secretbox.nonceLength);return o.join([[0],s,r.secretbox(i,s,a.symmetric)])},o.decrypt=function(n,t){var o=n.subarray(1,1+r.secretbox.nonceLength),a=n.subarray(1+r.secretbox.nonceLength),i=r.secretbox.open(a,o,t.symmetric);try{return JSON.parse(e.encodeUTF8(i))}catch(e){return void console.error(e)}},o.sign=function(e,n){return r.sign.detached(r.hash(e),n.sign.secretKey)},o.serialize=function(n,t){var r=o.encrypt(0,n,t),a=o.sign(r,t);return{publicKey:e.encodeBase64(t.sign.publicKey),signature:e.encodeBase64(a),ciphertext:e.encodeBase64(r)}},o.proveAncestor=function(n){var t=e.find(n,["sign","publicKey"]),o=e.find(n,["sign","secretKey"]);try{var a=r.sign.detached(t,o);return JSON.stringify([t,a].map(e.encodeBase64))}catch(e){return void console.error(e)}};var a=function(n){return e.encodeBase64(n).replace(/\//g,"-")};o.getBlockUrl=function(e){var t=a(e.sign.publicKey);return(n.fileHost||n.httpUnsafeOrigin||window.location.origin)+"/block/"+t.slice(0,2)+"/"+t},o.getBlockHash=function(e){return o.getBlockUrl(e)+"#"+a(e.symmetric)};var i=function(n){try{return e.decodeBase64(n.replace(/\-/g,"/"))}catch(e){return void console.error(e)}};return o.parseBlockHash=function(e){if("string"==typeof e){var n=e.split("#");if(2===n.length)try{return{href:n[0],keys:{symmetric:i(n[1])}}}catch(e){return void console.error(e)}}},o.checkRights=function(n,r){const o=e.mkAsync(r),{blockKeys:a,auth:i}=n;var s="MFA_CHECK";i&&i.type&&(s=`${i.type.toUpperCase()}_`+s),t(a.sign,{command:s,auth:i&&i.data},o)},o.writeLoginBlock=function(e,n){const{content:r,blockKeys:a,oldBlockKeys:i,auth:s,pw:c,session:u,token:f,userData:l}=e;var d="WRITE_BLOCK";s&&s.type&&(d=`${s.type.toUpperCase()}_`+d);var h=o.serialize(JSON.stringify(r),a);h.auth=s&&s.data,h.hasPassword=c,h.registrationProof=i&&o.proveAncestor(i),f&&(h.inviteToken=f),l&&(h.userData=l),t(a.sign,{command:d,content:h,session:u},n)},o.removeLoginBlock=function(e,n){const{reason:r,blockKeys:o,auth:a,edPublic:i}=e;var s="REMOVE_BLOCK";a&&a.type&&(s=`${a.type.toUpperCase()}_`+s),t(o.sign,{command:s,auth:a&&a.data,edPublic:i,reason:r},n)},o.updateSSOBlock=function(e,n){const{blockKeys:r,oldBlockKeys:a}=e;var i=a&&o.proveAncestor(a);t(r.sign,{command:"SSO_UPDATE_BLOCK",ancestorProof:i},n)},o})(Z(),void 0,dn(),h()))}(fn)),fn.exports}var pn,vn,yn,mn=hn(),gn=n({__proto__:null,default:r(mn)},[mn]),En={exports:{}};function bn(){return pn||(pn=1,function(e){var n;n=function(){var e=function(n){if(Array.isArray(n))return n.map(e);if(n instanceof Object){var t=[],r=[];return Object.keys(n).forEach(function(e){/^(0|[1-9][0-9]*)$/.test(e)?t.push(+e):r.push(e)}),t.sort(function(e,n){return e-n}).concat(r.sort()).reduce(function(t,r){return t[r]=e(n[r]),t},{})}return n},n=JSON.stringify.bind(JSON);return function(t,r,o){var a=n(t,r,0);if(!a||"{"!==a[0]&&"["!==a[0])return a;var i=JSON.parse(a);return n(e(i),null,o)}},e.exports?e.exports=n():JSON.sortify=n()}(En)),En.exports}function On(){if(yn)return vn;yn=1;var e,n,t,r,o,a,i,s;return M(),e=te(),n=Z(),Y(),t=je(),o=(r={}).createData=function(t,r){var o={channel:r||e.createChannelId(),displayName:t["cryptpad.username"],profile:t.profile&&t.profile.view,edPublic:t.edPublic,curvePublic:t.curvePublic,notifications:n.find(t,["mailboxes","notifications","channel"]),avatar:t.profile&&t.profile.avatar,badge:t.profile&&t.profile.badge,uid:t.uid};return!1===r&&delete o.channel,o},a=r.getFriend=function(e,n){if(n){if(n===e.curvePublic){var t=o(e);return delete t.channel,t}return e.friends?e.friends[n]:void 0}},i=r.getFriendList=function(e){return e.friends||(e.friends={}),e.friends},s=function(e,n){Object.keys(e).forEach(function(t){"me"!==t&&n(e[t],t,e)})},r.getFriendChannelsList=function(e){var n=[];return s(e.friends,function(e){n.push(e.channel)}),n},r.declineFriendRequest=function(e,n,t){e.mailbox.sendTo("DECLINE_FRIEND_REQUEST",{},{channel:n.notifications,curvePublic:n.curvePublic},function(e){t(e)})},r.acceptFriendRequest=function(e,n,t){var r=a(e.proxy,n.curvePublic)||{},i=o(e.proxy,r.channel||n.channel);e.mailbox.sendTo("ACCEPT_FRIEND_REQUEST",{user:i},{channel:n.notifications,curvePublic:n.curvePublic},function(e){t(e)})},r.addToFriendList=function(e,n,r){var o=e.proxy,a=i(o),s=n.curvePublic;s!==o.curvePublic?(a[s]=n,t.whenRealtimeSyncs(e.realtime,function(){r(),e.pinPads([n.channel],function(e){e.error&&console.error(e.error)})})):r("E_MYKEY")},r.updateMyData=function(e,t){var r=o(e.proxy,!1);e.proxy.friends&&(e.proxy.friends.me=n.clone(r),delete e.proxy.friends.me.channel),e.modules.team&&e.modules.team.updateMyData(r);var i=function(n){n&&n.notifications&&(delete n.user,r.channel=n.channel,e.mailbox.sendTo("UPDATE_DATA",r,{channel:n.notifications,curvePublic:n.curvePublic},function(e){e&&e.error&&console.error(e)}))};t?i(a(e.proxy,t)):s(e.proxy.friends||{},i)},r.removeFriend=function(e,n,r){var o=e.proxy,a=o.friends[n];a?a.notifications?e.mailbox.sendTo("UNFRIEND",{curvePublic:o.curvePublic},{channel:a.notifications,curvePublic:a.curvePublic},function(i){i&&i.error?r(i):(e.messenger.onFriendRemoved(n,a.channel),delete o.friends[n],t.whenRealtimeSyncs(e.realtime,function(){r(i)}))}):r({error:"EINVAL"}):r({error:"ENOENT"})},vn=r}var An,wn,Dn,_n={exports:{}},Tn={exports:{}},Sn={exports:{}};function Nn(){return An||(An=1,function(e){var n,t,r,o,a,i,s,c,u,f,l,d;e.exports&&(e.exports=(n=Z(),t=h(),r=n.uid,o=n.tryParse,a=function(e,r){var o=n.decodeUTF8(JSON.stringify(e));return n.encodeBase64(t.sign.detached(o,r))},i=function(e,n,t){if("function"!=typeof t)throw new Error("expected callback");var o=e.network,a=o.historyKeeper;if("string"==typeof a){var i=r(),s=e.pending[i]=function(e,n){t(e,n)};return s.data=n,s.called=0,o.sendto(a,JSON.stringify([i,n]))}t("NO_HISTORY_KEEPER")},s=[],c=[],u=function(e){var n={network:e,connected:!0,anon:void 0,authenticated:[]};return s.push(e),c.push(n),e.on("message",function(t,r){r===e.historyKeeper&&function(e,n){"string"!=typeof n&&console.error("received non-string message [%s]",n);var t=o(n);if(t){if(Array.isArray(t)&&!/(FULL_HISTORY|HISTORY_RANGE)/.test(t[0])){var r=t[0];"string"==typeof r&&(function(e,n){return!!e.anon&&"function"==typeof e.anon.pending[n]}(e,r)?function(e,n,t){var r=e.pending[n];"ERROR"===t[0]?r(t[1]):r(void 0,t.slice(1)),delete e.pending[n]}(e.anon,r,t.slice(1)):e.authenticated.some(function(e){var n=e.pending[r];return"function"==typeof n&&("ERROR"!==t[1]?(/\|/.test(t[1])&&e.cookie!==t[1]&&(e.cookie=t[1]),n(void 0,t.slice(2)),delete e.pending[r],!0):"NO_COOKIE"===t[2]?(e.send("COOKIE","",function(t){if(t)return console.error(t),void n(t);e.resend(r)&&delete e.pending[r]}),!0):(n(t[2]),delete e.pending[r],!0))})||console.error("UNHANDLED RPC MESSAGE",n))}}else console.error(new Error("could not parse message: %s",n))}(n,t)}),e.on("disconnect",function(){n.connected=!1,n.anon&&(n.anon.connected=!1),n.authenticated.forEach(function(e){e.connected=!1})}),e.on("reconnect",function(){n.anon&&(n.anon.connected=!0),n.authenticated.forEach(function(e){e.connected=!0})}),n},f=function(e){var n;return s.some(function(t,r){return e===t&&(n=r,!0)}),c[n]?c[n]:u(e)},l=function(e,t){if(!e)throw new Error("expected network context");var o,s=t.publicKeyString;return e.authenticated.some(function(e,n){return e.publicKey===s&&(o=n,!0)}),e.authenticated[o]?e.authenticated[o]:function(e,t){var o={network:e.network,publicKey:t.publicKeyString,timeouts:{},pending:{},cookie:null,connected:!0},s=o.send=function(e,r,s){var c=n.mkAsync(s);if(o.connected||"COOKIE"===e){var u=[e,r];o.cookie&&o.cookie.join?u.unshift(o.cookie.join("|")):u.unshift(o.cookie);var f=a(u,t.signKey);return u.unshift(t.publicKeyString),u.unshift(f),i(o,u,c)}c("DISCONNECTED")};return o.resend=function(e){var n=o.pending[e];if(n.called)return console.error("[%s] called too many times",e),!0;n.called++,n.data[2]=o.cookie,n.data[0]=a(n.data.slice(2),t.signKey);var i=r();o.pending[i]=n,delete o.pending[e];try{return o.network.sendto(o.network.historyKeeper,JSON.stringify([i,n.data]))}catch(e){console.log("failed to resend"),console.error(e)}},s.unauthenticated=function(e,r,a){var s=n.mkAsync(a);if(o.connected){var c=[null,t.publicKeyString,null,e,r];return o.cookie&&o.cookie.join?c[2]=o.cookie.join("|"):c[2]=o.cookie,i(o,c,s)}s("DISCONNECTED")},o.destroy=function(){Object.keys(o.timeouts).forEach(function(e){clearTimeout(e)});var n=e.authenticated.indexOf(o);-1!==n&&e.authenticated.splice(n,1)},e.authenticated.push(o),o}(e,t)},d=function(e){return e.anon||function(e){var t={network:e.network,timeouts:{},pending:{},connected:!0};return e.anon=t,t.send=function(e,r,o){var a=n.mkAsync(o);if(t.connected)return i(t,[e,r],a);a("DISCONNECTED")},t.resend=function(e){var n=t.pending[e];if(n.called)return console.error("[%s] called too many times",e),!0;n.called++;try{return t.network.sendto(t.network.historyKeeper,JSON.stringify([e,n.data]))}catch(e){console.log("failed to resend"),console.error(e)}},t.destroy=function(){Object.keys(t.timeouts).forEach(function(e){clearTimeout(e)}),e.anon=void 0},t}(e)},{create:function(e,t,r,o){if("function"!=typeof o)throw new Error("expected callback");var a,i=n.mkAsync(o);try{if(64!==(a=n.decodeBase64(t)).length)throw new Error("private key did not match expected length of 64")}catch(e){return void i(e)}try{if(32!==n.decodeBase64(r).length)return void i("expected public key to be 32 uint")}catch(e){return void i(e)}if(e){var s=f(e),c=l(s,{publicKeyString:r,signKey:a});c.send("COOKIE","",function(e){e?i(e):i(void 0,{send:c.send,destroy:c.destroy})})}else i("NO_NETWORK")},createAnonymous:function(e,t){var r=n.mkAsync(t);if("function"!=typeof r)throw new Error("expected callback");if(e){var o=d(f(e));r(void 0,{send:o.send,destroy:o.destroy})}else r("NO_NETWORK")}}))}(Sn)),Sn.exports}function In(){return wn||(wn=1,function(e){var n,t;e.exports&&(e.exports=(n=Z(),t=Nn(),{create:function(e,r,o,a){if("function"!=typeof o)throw new Error("Expected callback");var i=n.once(n.mkAsync(o));if(e)if(r){var s=r.edPrivate,c=r.edPublic;s&&c?t.create(e,s,c,function(e,t){if(e)i(e);else{var r={};r.destroy=t.destroy,r.publicKey=c,r.send=t.send,r.pin=function(e,r){var o=n.once(n.mkAsync(r));Array.isArray(e)?t.send("PIN",e,o):o("[TypeError] pin expects an array")},r.unpin=function(e,r){var o=n.once(n.mkAsync(r));Array.isArray(e)?t.send("UNPIN",e,o):o("[TypeError] pin expects an array")},r.adminRpc=function(e,n){if(e.cmd){var r=[e.cmd,e.data];t.send("ADMIN",r,n)}else setTimeout(function(){n("[TypeError] admin rpc expects a command")})},r.getServerHash=function(e){t.send("GET_HASH",c,function(n,t){t&&t[0]?e(n,Array.isArray(t)&&t[0]||void 0):e("NO_HASH_RETURNED")})},r.reset=function(e,r){var o=n.once(n.mkAsync(r));Array.isArray(e)?t.send("RESET",e,o):o("[TypeError] pin expects an array")},r.getFileListSize=function(e){t.send("GET_TOTAL_SIZE",void 0,function(n,t){n?e(n):t&&t.length&&"number"==typeof t[0]?e(void 0,t[0]):e("INVALID_RESPONSE")})},r.updatePinLimits=function(e){t.send("UPDATE_LIMITS",void 0,function(n,t){n?e(n):t&&t.length&&"number"==typeof t[0]?e(void 0,t[0],t[1],t[2]):e("INVALID_RESPONSE")})},r.getLimit=function(e){t.send("GET_LIMIT",void 0,function(n,t){n?e(n):t&&t.length&&"number"==typeof t[0]?e(void 0,t[0],t[1],t[2]):e("INVALID_RESPONSE")})},r.trimHistory=function(e,r){var o=n.once(n.mkAsync(r));"object"==typeof e&&e.channel&&e.hash?t.send("TRIM_HISTORY",e,function(e){if(e)return o(e);o()}):o("INVALID_ARGUMENTS")},r.clearOwnedChannel=function(e,n){"string"==typeof e&&32===e.length?t.send("CLEAR_OWNED_CHANNEL",e,function(e){if(e)return n(e);n()}):n("INVALID_ARGUMENTS")},r.removeOwnedChannel=function(e,n,r){if("string"!=typeof e||-1===[32,48].indexOf(e.length))return console.error("invalid channel to remove",e),void n("INVALID_ARGUMENTS");t.send("REMOVE_OWNED_CHANNEL",{channel:e,reason:r},function(t,r){t?n(t):r&&r.length&&"OK"===r[0]?(n(),a&&a.clearChannel&&a.clearChannel(e)):n("INVALID_RESPONSE")})},r.removePins=function(e){t.send("REMOVE_PINS",void 0,function(n,t){n?e(n):t&&t.length&&"OK"===t[0]?e():e("INVALID_RESPONSE")})},r.uploadComplete=function(e,n){t.send("UPLOAD_COMPLETE",e,function(e,t){if(e)n(e);else{var r=t[0];"string"==typeof r?n(void 0,r):n("INVALID_ID")}})},r.ownedUploadComplete=function(e,n){t.send("OWNED_UPLOAD_COMPLETE",e,function(e,t){if(e)n(e);else{var r=t[0];"string"==typeof r?n(void 0,r):n("INVALID_ID")}})},r.uploadStatus=function(e,n){"number"==typeof e?t.send("UPLOAD_STATUS",e,function(e,t){if(e)n(e);else{var r=t[0];"boolean"==typeof r?n(void 0,r):n("INVALID_RESPONSE")}}):setTimeout(function(){n("INVALID_SIZE")})},r.uploadCancel=function(e,n){t.send("UPLOAD_CANCEL",e,function(e){e?n(e):n()})},r.setMetadata=function(e,n){t.send("SET_METADATA",{channel:e.channel,command:e.command,value:e.value},n)},i(e,r)}}):i("INVALID_KEYS")}else i("INVALID_PROXY");else i("INVALID_NETWORK")}}))}(Tn)),Tn.exports}function xn(){return Dn||(Dn=1,function(e){(()=>{const n=(e,n,t,r,o,a,i,s,c,u)=>{var f=function(e,n,t){if(!e.done){if(e.cb(n&&n.error,t,n),e.done=!0,!e.hasNetwork){var o=r.find(e,["network","disconnect"]);"function"==typeof o&&o()}if(e.realtime&&e.realtime.stop)try{e.realtime.stop()}catch(e){console.error(e)}var a=r.find(e,["session","realtime","abort"]);"function"==typeof a&&(e.session.realtime.sync(),a())}},l=function(e,r){u(function(n){var o,a;e.hasNetwork||(o=n(function(e,n){e||(r.network=n)}),a=i.getWebsocketURL(),t.connect(a).then(function(e){o(null,e)},function(e){o(e)}))}).nThen(function(){e.realtime=n.start(r)})},d=function(e,n,t,r){Array.isArray(t)&&t.length&&16===t[0].length&&Array.isArray(n.accessKeys)?(e.network.historyKeeper=t[0],u(function(t){n.accessKeys.forEach(function(n){c.create(e.network,n,t(function(e){console.log("done",n),e&&console.error(e)}))})}).nThen(function(){r()})):r(!0)},h=function(n,t){var r;return"string"==typeof n?r=o.getSecrets("pad",n,t.password):"object"==typeof n&&(r=n),r.keys||(r.keys=r.key),{websocketURL:i.getWebsocketURL(t.origin),channel:r.channel,validateKey:r.keys.validateKey||void 0,crypto:e.createEncryptor(r.keys),logLevel:0,initialState:t.initialState,Cache:s}},p=function(e){return"object"==typeof e},v=function(e,n){p(e)&&p(n)&&Object.keys(n).forEach(function(t){e[t]=n[t]})};return{get:function(e,n,t,r){if("function"!=typeof n)throw new Error("Cryptget expects a callback");r=r||function(){};var o=h(e,t=t||{}),a={cb:n,accessKeys:t.accessKeys,hasNetwork:Boolean(t.network)};o.onRejected=function(e,n){d(o,a,e,n)},o.onReady=function(e){var n=a.session=e.realtime;a.network=e.network,r(1),f(a,void 0,n.getUserDoc())},o.onError=function(e){console.warn(e),f(a,e)},o.onChannelError=function(e){console.error(e),f(a,e)},o.onCacheReady=t.onCacheReady;var i=0;o.onMessage=function(){i++,r(Math.min(.99,i/100))},v(o,t),l(a,o)},put:function(e,n,t,r){if("function"!=typeof t)throw new Error("Cryptput expects a callback");var o=h(e,r=r||{}),i={cb:t,accessKeys:r.accessKeys,hasNetwork:Boolean(r.network)};o.onRejected=function(e,n){d(o,i,e,n)},o.onReady=function(e){var r=i.session=e.realtime;i.network=e.network,r.contentUpdate(n);var o=setTimeout(function(){t(new Error("Timeout"))},15e3);a.whenRealtimeSyncs(r,function(){clearTimeout(o);var e=r.getAuthDoc();r.abort(),f(i,void 0,e)})},o.onChannelError=function(e){f(i,e)},v(o,r),l(i,o)}}};e.exports&&(e.exports=n(M(),D(),u(),Z(),te(),je(),j(),fe(),In(),qe(),x()))})()}(_n)),_n.exports}var Cn,Rn,Pn,kn,Mn,Fn,Ln,Hn={exports:{}};function jn(){if(Mn)return kn;Mn=1;return kn=((e,n,t,r,o,a,i,s)=>{const c={};let u={};c.setCustomize=e=>{u=e.Broadcast};var f=["notifications","supportteam","broadcast"],l=[],d="000000000000000000000000000000000",h=function(e,n,t,r,o){e.emit("MESSAGE",{type:n,content:t},r?[r]:e.clients,o)},p=function(e,n,t,r){e.emit("VIEWED",{type:n,hash:t},r||e.clients)},v=function(e){var n=e.store&&e.store.proxy;if(n.curvePrivate&&n.curvePublic)return{curvePrivate:n.curvePrivate,curvePublic:n.curvePublic}},y=c.sendTo=function(n,t,o,a,i){a=a||{};var c=i||function(e){e&&e.error&&console.error(e.error)};if(s.Mailbox){var u=e.find(n,["store","anon_rpc"]);if(u){var f={encrypt:function(e){return e}},l=d,h={uid:e.uid(),type:t,content:o};if(!/^BROADCAST/.test(t)){var p=v(n);if(!p)return void c({error:"missing asymmetric encryption keys"});if(!a||!a.channel||!a.curvePublic)return void c({error:"no notification channel"});if(l=a.channel,f=s.Mailbox.createEncryptor(p),"object"==typeof o&&!o.user){var y=r.createData(n.store.proxy,!1);o.user=y}h={type:t,content:o}}var m=JSON.stringify(h),g=f.encrypt(m,a.curvePublic);if(a.viewed){var E=e.find(n,["store","proxy","teams",a.viewed]);if(E){var b=g.slice(0,64),O=e.find(E,["keys","mailbox","viewed"]);Array.isArray(O)&&O.push(b)}}u.send("WRITE_PRIVATE_MESSAGE",[l,g],function(e){c(e?{error:e}:{hash:g.slice(0,64)})})}else c({error:"anonymous rpc session not ready"})}else c({error:"chainpad-crypto is outdated and doesn't support mailboxes."})};c.sendToAnon=function(n,t,r,o,a){var i=s.Nacl,c=i.randomBytes(32),u=i.box.keyPair.fromSecretKey(new Uint8Array(c)),f=e.encodeBase64(u.secretKey),l=e.encodeBase64(u.publicKey);y({store:{anon_rpc:n,proxy:{curvePrivate:f,curvePublic:l}}},t,r,o,a)};var m=function(n,r,o,i){var s=r.type,c=r.hash;if(/^REMINDER\|/.test(c)){i(),delete n.boxes.reminders.content[c],p(n,s,c,n.clients.filter(function(e){return e!==o}));var u=c.slice(9).split("-")[0],f=e.find(n,["store","proxy","hideReminders",u]);if(!f){var l=n.store.proxy.hideReminders=n.store.proxy.hideReminders||{};f=l[u]=l[u]||[]}var d=c.split("-")[1];d&&!f.includes(d)&&f.push(Number(d))}else{var h=n.boxes[s];if(h){var v,y,m=h.data||{},g=h.history.indexOf(c);-1!==g&&(0===g?(m.lastKnownHash=c,h.history.shift()):-1===m.viewed.indexOf(c)&&m.viewed.push(c));var E=[];h.history.some(function(e,n){if(-1===m.viewed.indexOf(e))return!0;v=n+1,E.push(e),y=e}),m.viewed=m.viewed.filter(function(e){return-1===E.indexOf(e)}),v&&(h.history=h.history.slice(v),m.lastKnownHash=y),Object.keys(h.content).forEach(function(e){-1!==h.history.indexOf(e)&&-1===m.viewed.indexOf(e)||(a.remove(n,h,h.content[e],e),delete h.content[e])}),t.whenRealtimeSyncs(n.store.realtime,function(){i(),p(n,s,c,n.clients.filter(function(e){return e!==o}))})}else i({error:"NOT_LOADED"})}},g=function(e,n,t,c,u){u=u||{};var f=e.boxes[n]={channel:t.channel,type:n,queue:[],history:[],content:{},sendMessage:function(n){if("object"==typeof n&&!n.user){var t=r.createData(e.store.proxy,!1);n.user=t}try{n=JSON.stringify(n)}catch(e){console.error(e)}f.queue.push(n)},data:t};if(s.Mailbox){var l=t.keys||v(e);if(l||t.decrypted){var d=t.decrypted?{encrypt:function(e){return e},decrypt:function(e){return e}}:s.Mailbox.createEncryptor(l);f.encryptor=d;var y,g={network:e.store.network,channel:t.channel,noChainPad:!0,crypto:d,owners:"broadcast"===n?[]:u.owners||[e.store.proxy.edPublic],lastKnownHash:t.lastKnownHash};g.onConnectionChange=function(){},g.onConnect=function(t,r){f.sendMessage=function(t,o){var a;o=o||function(){};try{a=JSON.stringify(t)}catch(e){console.error(e)}r(a,function(r,a){r?console.error(r):(f.history.push(a),t.ctime=+new Date,f.content[a]=t,h(e,n,{msg:t,hash:a}),o(a))},l.curvePublic)},f.queue.forEach(function(e){f.sendMessage(e)}),f.queue=[]},f.onMessage=g.onMessage=function(r,i,s,c,l,d,p){if(l!==t.lastKnownHash&&l!==y){var v=p&&p.time;y=l;try{r=JSON.parse(r)}catch(e){console.error(e)}if(d&&(r.author=d),f.history.push(l),function(e,n){return-1===(n.viewed||[]).indexOf(e)&&e!==n.lastKnownHash}(l,t)){var g={msg:r,hash:l,time:v},E=f.ready;a.add(e,f,g,function(t,a,i){a&&m(e,a,"",function(){console.log("Notification handled automatically")}),i||t?m(e,{type:n,hash:l},"",function(){console.log("Notification handled automatically")}):(r.ctime=v||0,f.content[l]=r,u.dump||h(e,n,g,null,function(e){e&&e.msg&&E&&o.system(void 0,e.msg)}))})}else if(0===Object.keys(f.content).length){t.lastKnownHash=l,f.history=[];var b=t.viewed.indexOf(l);-1!==b&&t.viewed.splice(b,1)}}},g.onReady=function(){var r=[];t.viewed.forEach(function(e,n){-1===f.history.indexOf(e)&&r.push(n)});for(var o=r.length-1;o>=0;o--)t.viewed.splice(r[o],1);var i=function(t){a.remove(e,f,f.content[t],t),delete f.content[t],p(e,n,t)};e.store.proxy.on("change",["mailboxes",n],function(e,n,t){var r;"lastKnownHash"===t[2]&&(f.history.some(function(e,t){if(r=t+1,i(e),e===n)return!0}),f.history=f.history.slice(r));"viewed"===t[2]&&i(n)}),f.ready=!0,c(f.content)},f.cpNf=i.start(g)}else console.error("missing asymmetric encryption keys")}else console.error("chainpad-crypto is outdated and doesn't support mailboxes.")};return c.init=function(t,r,i){var s={},c=t.store,v=c.proxy.mailboxes=c.proxy.mailboxes||{},E={Store:t.Store,store:c,pinPads:t.pinPads,updateMetadata:t.updateMetadata,updateDrive:t.updateDrive,mailboxes:v,emit:i,clients:[],boxes:{},req:{},loggedIn:c.loggedIn&&c.proxy.edPublic};return function(e,t){!t.notifications&&e.loggedIn&&(t.notifications={channel:n.createChannelId(),lastKnownHash:"",viewed:[]},e.pinPads([t.notifications.channel],function(e){e.error&&console.error(e)})),t.support&&delete t.support,t.broadcast||(t.broadcast={channel:d,lastKnownHash:u.lastBroadcastHash,decrypted:!0,viewed:[]})}(E,v),E.loggedIn&&function(n){var t=n.store.network;t.on("message",function(r,o){if(o===t.historyKeeper){var a=JSON.parse(r);if(/HISTORY_RANGE/.test(a[0])){var i=a[1],s=n.req[i];if(s){var c=a[0],u=a[2],f=s.box;if("HISTORY_RANGE"===c){if(!Array.isArray(u))return;var l;if("broadcast"===s.box.type)l=e.tryParse(u[4]);else try{var d=f.encryptor.decrypt(u[4]);(l=JSON.parse(d.content)).author=d.author}catch(e){console.log(e)}var h=u[4].slice(0,64);n.emit("HISTORY",{txid:i,time:u[5],message:l,hash:h},[s.cId])}else"HISTORY_RANGE_END"===c&&(n.emit("HISTORY",{txid:i,complete:!0},[s.cId]),delete n.req[i])}}}})}(E),E.boxes.reminders={content:{}},Object.keys(v).forEach(function(e){if(-1!==f.indexOf(e)){var n=v[e];-1===l.indexOf(e)?g(E,e,n,function(){}):g(E,e,n,r(function(){}))}}),E.loggedIn&&Object.keys(c.proxy.teams||{}).forEach(function(n){var t=c.proxy.teams[n];if(t){var r=t.keys.mailbox||{};if(r.channel){var o={owners:[e.find(t,["keys","drive","edPublic"])]};g(E,"team-"+n,r,function(){},o)}}}),s.post=function(e,n,t){var r=E.boxes[e];r&&r.sendMessage({type:n,content:t,sender:c.proxy.curvePublic})},s.hideMessage=function(e,n){p(E,e,n.hash,E.clients)},s.showMessage=function(e,n,t,r){"reminders"===e&&n&&(E.boxes.reminders.content[n.hash]=n.msg,E.clients.length||(E.boxes.reminders.content[n.hash].requiresNotif=!0),p(E,e,n.hash,E.clients)),h(E,e,n,t,function(e){o.system(void 0,e.msg),r&&r()})},s.open=function(e,n,t,r,o){(-1!==f.indexOf(e)||r)&&g(E,e,n,t,o)},s.close=function(e,n){!function(e,n,t){t=t||function(){};var r=e.boxes[n];r?r.cpNf&&"function"==typeof r.cpNf.stop?(r.cpNf.stop(),Object.keys(r.content).forEach(function(t){a.remove(e,r,r.content[t],t),p(e,n,t,e.clients)}),delete e.boxes[n]):t("EINVAL"):t()}(E,e,n)},s.dismiss=function(e,n){m(E,e,"",n)},s.sendTo=function(e,n,t,r){E.loggedIn?y(E,e,n,t,r):r({error:"NOT_LOGGED_IN"})},s.removeClient=function(e){!function(e,n){var t=e.clients.indexOf(n);e.clients.splice(t,1)}(E,e)},s.execCommand=function(e,n,t){var r=n.cmd,a=n.data;"SUBSCRIBE"!==r?"DISMISS"!==r?"SENDTO"!==r?"LOAD_HISTORY"!==r||function(e,n,t,r){var o=e.boxes[t.type];if(o){var a=["GET_HISTORY_RANGE",o.channel,{from:t.lastKnownHash,count:t.count,txid:t.txid}];"broadcast"===t.type&&(a=["GET_HISTORY_RANGE",o.channel,{to:t.lastKnownHash,txid:t.txid}]),e.req[t.txid]={cId:n,box:o};var i=e.store.network;i.sendto(i.historyKeeper,JSON.stringify(a)).then(function(){},function(e){console.error(e)})}else r({error:"ENOENT"})}(E,e,a,t):y(E,a.type,a.msg,a.user,t):m(E,a,e,t):function(e,n,t,r){Object.keys(e.boxes).forEach(function(n){Object.keys(e.boxes[n].content).forEach(function(r){var a={msg:e.boxes[n].content[r],hash:r};h(e,n,a,t,function(e){e.error||a.msg&&a.msg.requiresNotif&&(o.system(void 0,e.msg),delete a.msg.requiresNotif)})})}),-1===e.clients.indexOf(t)&&e.clients.push(t),r()}(E,0,e,t)},s},c})(Z(),te(),je(),On(),(Cn||(Cn=1,function(e){(()=>{const n=(e={})=>{let n=globalThis;var t={};e.requireConf=e.requireConf||{},t.setCustomize=n=>{e=n.ApiConfig};var r=n.location&&n.location.pathname.slice(1,-1),o=-1!==["code","slide","pad","kanban","whiteboard","diagram","sheet","poll","teams","form","doc","presentation"].indexOf(r)?"-"+r:"",a="/customize/favicon/main-favicon"+o+".png?"+e.requireConf.urlArgs,i="/customize/favicon/alt-favicon"+o+".png?"+e.requireConf.urlArgs,s="/customize/favicon/main-favicon"+o+".ico?"+e.requireConf.urlArgs,c="/customize/favicon/alt-favicon"+o+".ico?"+e.requireConf.urlArgs,u=n.document,f=t.isSupported=function(){return"function"==typeof n.Notification&&n.isSecureContext},l=t.hasPermission=function(){return"granted"===Notification.permission},d=t.getPermission=function(e){e=e||function(){},Notification&&"function"==typeof Notification.requestPermission?Notification.requestPermission(function(n){e("granted"===n)}):e(!1)},h=t.create=function(e,t,r){u&&!r?r=u.getElementById("favicon").getAttribute("data-main-favicon")||i:r||(r=i);var o=new Notification(t,{icon:r,body:e});return o.onclick=function(){if(u)try{parent.focus(),n.focus(),this.close()}catch(e){}},o};return t.system=function(e,n,t){if(f())return l()?h(e,n,t):void("denied"!==Notification.permission&&d(function(r){r&&h(e,n,t)}))},u&&!u.getElementById("favicon")&&function(){if(u){console.debug("creating favicon");var e={id:"favicon",type:"image/png",rel:"icon","data-main-favicon":a,"data-alt-favicon":i,href:a};if(!u.getElementById("favicon")){var n=u.createElement("link");Object.keys(e).forEach(function(t){n.setAttribute(t,e[t])}),u.head.appendChild(n)}if(!u.getElementById("favicon-ico")){var t=u.createElement("link");e.href=e.href.replace(/\.png/g,".ico"),e.id="favicon-ico",e.type="image/x-icon",Object.keys(e).forEach(function(n){t.setAttribute(n,e[n])}),u.head.appendChild(t)}}else console.error("document is not available in this context")}(),t.tab=function(e,r){if(u){var o="_pendingTabNotification",f=u.getElementById("favicon"),l=u.getElementById("favicon-ico"),d=a,h=i,p=s,v=c;f&&(d=f.getAttribute("data-main-favicon")||a,h=f.getAttribute("data-alt-favicon")||i,f.setAttribute("href",d)),l&&(p=l.getAttribute("data-main-favicon")||s,v=l.getAttribute("data-alt-favicon")||c,l.setAttribute("href",p));var y=function(e){return!!t[o]&&(n.clearInterval(t[o]),f&&f.setAttribute("href",e?h:d),l&&l.setAttribute("href",e?v:p),!0)};y();var m=function(){f&&f.setAttribute("href",f.getAttribute("href")===d?h:d),l&&l.setAttribute("href",l.getAttribute("href")===p?v:p),--r};return t[o]=n.setInterval(function(){if(r>0)return m();y(!0)},e),m(),{cancel:y}}console.error("document is not available in this context")},t};e.exports&&(e.exports=n(void 0))})()}(Hn)),Hn.exports),(Pn||(Pn=1,Rn=((e,n,t,r,o)=>{var a=function(e){var n=e.store.realtime.getLag().lag||0;return 20*(Math.max(0,n)+300)*(.5+Math.random())},i={},s={},c=function(e,n){var r=e.store.proxy.mutedUsers||{},o=t.find(n,["msg","author"]);return!!o&&Boolean(r[o])},u={};i.FRIEND_REQUEST=function(n,t,r,o){var a=r.msg.content.user||r.msg.content;if(c(n,r))o(!0);else if(u[r.msg.author])o(!0);else{if(u[r.msg.author]={type:t.type,hash:r.hash},e.getFriend(n.store.proxy,r.msg.author)||n.store.proxy.friends_pending[r.msg.author])return delete n.store.proxy.friends_pending[r.msg.author],void e.acceptFriendRequest(n.store,a,function(t){t&&t.error?o():e.addToFriendList({proxy:n.store.proxy,realtime:n.store.realtime,pinPads:n.pinPads},a,function(e){if(e)return console.error(e),void o(!0);n.store.messenger&&n.store.messenger.onFriendAdded(a),n.updateMetadata(),o(!0)})});o()}},s.FRIEND_REQUEST=function(e,n,t){var r=t.content.user||t.content;u[r.curvePublic]&&delete u[r.curvePublic]};var f={},l={};i.DECLINE_FRIEND_REQUEST=function(e,n,t,r){var o=t.msg.content.user||t.msg.content;o.curvePublic||(o.curvePublic=t.msg.author),setTimeout(function(){r(!0),e.store.proxy.friends_pending[t.msg.author]&&(delete e.store.proxy.friends_pending[t.msg.author],e.updateMetadata(),f[t.msg.author]||n.sendMessage({type:"FRIEND_REQUEST_DECLINED",content:{user:o}},function(e){f[t.msg.author]={type:n.type,hash:e}}))},a(e))},i.FRIEND_REQUEST_DECLINED=function(e,n,t,r){e.updateMetadata();var o=t.msg.content.user.curvePublic||t.msg.content.user,a=l[o];delete l[o],f[o]?r(!0,a):(f[o]={type:n.type,hash:t.hash},r(!1,a))},s.FRIEND_REQUEST_DECLINED=function(e,n,t){var r=t.content.user.curvePublic||t.content.user;f[r]&&delete f[r]},i.ACCEPT_FRIEND_REQUEST=function(n,t,r,o){var i=r.msg.content.user||r.msg.content;setTimeout(function(){o(!0),n.store.proxy.friends_pending[r.msg.author]&&(delete n.store.proxy.friends_pending[r.msg.author],e.addToFriendList({proxy:n.store.proxy,realtime:n.store.realtime,pinPads:n.pinPads},i,function(e){e?console.error(e):(n.store.messenger&&n.store.messenger.onFriendAdded(i),n.updateMetadata(),n.store.modules.profile&&n.store.modules.profile.update(),l[r.msg.author]||t.sendMessage({type:"FRIEND_REQUEST_ACCEPTED",content:{user:i}},function(e){l[r.msg.author]={type:t.type,hash:e}}))}))},a(n))},i.FRIEND_REQUEST_ACCEPTED=function(e,n,t,r){e.updateMetadata();var o=t.msg.content.user.curvePublic||t.msg.content.user,a=f[o];delete f[o],l[o]?r(!0,a):(l[o]={type:n.type,hash:t.hash},r(!1,a))},s.FRIEND_REQUEST_ACCEPTED=function(e,n,t){var r=t.content.user.curvePublic||t.content.user;l[r]&&delete l[r]},i.CANCEL_FRIEND_REQUEST=function(e,n,t,r){var o=u[t.msg.author];o?r(!0,o):r(!0)},i.UNFRIEND=function(n,t,r,o){var a=r.msg.author,i=e.getFriend(n.store.proxy,a);i?(delete n.store.proxy.friends[a],delete n.store.proxy.friends_pending[a],n.store.messenger&&n.store.messenger.onFriendRemoved(a,i.channel),n.updateMetadata(),o(!0)):o(!0)},i.UPDATE_DATA=function(e,n,t,r){var o=t.msg,a=o.author,i=e.store.proxy.friends&&e.store.proxy.friends[a];if(!i||"object"!=typeof o.content)return void r(!0);const s=o.content.edPublic,c=()=>{Object.keys(o.content).forEach(function(e){i[e]=o.content[e]}),e.store.messenger&&e.store.messenger.onFriendUpdate(a),e.updateMetadata(),r(!0)};if(o.content.badge&&e.store.modules.badge)return e.store.modules.badge.listBadges({edPublic:s},e=>{e.includes(o.content.badge)||delete o.content.badge,c()});c()};var d=function(e,n){let t=e.store.data.blockHash,a=o.parseBlockHash(t).keys.symmetric;return r.encrypt(n,a)},h={};i.SHARE_PAD=function(e,t,r,o){var a=r.msg,i=r.hash,s=a.content;if(c(e,r))o(!0);else{var u,f=s.isStatic?s.href:n.hrefToHexChannelId(s.href,s.password),l=n.parsePadUrl(s.href),p=l.hashData&&l.hashData.mode||"n/a",v=h[f];if(v){if("edit"===v.mode&&"view"===p)return void o(!0);u=v.data}s.password&&(s.password=d(e,s.password)),h[f]={mode:p,data:{type:t.type,hash:i}},o(!1,u)}},s.SHARE_PAD=function(e,t,r,o){var a=r.content,i=n.hrefToHexChannelId(a.href,a.password),s=h[i];s&&s.data&&s.data.hash===o&&delete h[i]};var p=!1;i.SUPPORT_MESSAGE=function(e,n,t,r){p?r(!0):(p=!0,r())},s.SUPPORT_MESSAGE=function(){p=!1},i.REQUEST_PAD_ACCESS=function(e,n,t,r){var o=t.msg.content;if(c(e,t))r(!0);else{var a=o.channel,i=e.store.manager.findChannel(a);if(i.length){var s,u,f=e.store.proxy.edPublic;i.some(function(e){if(e.data&&Array.isArray(e.data.owners)&&-1!==e.data.owners.indexOf(f)&&e.data.href)return u=e.data.href,s=e.data.filename||e.data.title,!0})?(o.title=s,o.href=u,r(!1)):r(!0)}else r(!0)}},i.GIVE_PAD_ACCESS=function(e,n,t,r){var o,a=t.msg.content,i=a.channel;e.store.manager.findChannel(i,!0).forEach(function(e){e.data&&!e.data.href&&(o||(o=e.data.filename||e.data.title),e.userObject.setHref(i,null,a.href))}),a.title=o||a.title,r(!1)},i.ADD_TO_ACCESS_LIST=function(e,n,t,r){var o=t.msg.content.channel;e.Store.getAllStores().forEach(function(n){var t=n.manager.findChannel(o);if(t.length){var r=t[0].data,a=t[0].id,i=n.id;e.Store.loadSharedFolder(i,a,r,function(){},!1)}}),r(!0)};var v={};i.ADD_OWNER=function(e,n,t,r){var o=t.msg.content;if(c(e,t))r(!0);else{if(!(o.teamChannel||o.href&&o.title&&o.channel))return console.log("Remove invalid notification"),void r(!0);var a=o.channel||o.teamChannel;o.password&&(o.pw=o.password,o.password=d(e,o.password)),v[a]?r(!0):(v[a]={type:n.type,hash:t.hash},r(!1))}},s.ADD_OWNER=function(e,n,t){var r=t.content.channel||t.content.teamChannel;v[r]&&delete v[r]},i.RM_OWNER=function(e,n,t,r){var o=t.msg.content;if(!o.channel&&!o.teamChannel)return console.log("Remove invalid notification"),void r(!0);var a=o.channel||o.teamChannel;if(o.teamChannel){var i=e.store.proxy.teams||{};Object.keys(i).some(function(e){if(i[e].channel===a)return i[e].owner=!1,!0})}v[a]&&o.pending?r(!1,v[a]):r(!1)};var y={};i.INVITE_TO_TEAM=function(e,n,r,o){var a=r.msg.content;if(c(e,r))o(!0);else{if(!a.team)return console.log("Remove invalid notification"),void o(!0);var i=y[a.team.channel];if(i)return console.log("removing old invitation"),o(!1,i),void(y[a.team.channel]={type:n.type,hash:r.hash});var s=t.find(e,["store","proxy","teams"])||{};Object.keys(s).some(function(e){return s[e].channel===a.team.channel})?o(!0):(y[a.team.channel]={type:n.type,hash:r.hash},o(!1))}},s.INVITE_TO_TEAM=function(e,n,r){var o=t.find(r,["content","team","channel"]);delete y[o]},i.KICKED_FROM_TEAM=function(e,n,t,r){var o=t.msg.content;if(!o.teamChannel)return console.log("Remove invalid notification"),void r(!0);y[o.teamChannel]&&o.pending?r(!0,y[o.teamChannel]):r(!1)},i.INVITE_TO_TEAM_ANSWER=function(e,n,r,o){var a=r.msg,i=a.content;if(!i.teamChannel)return console.log("Remove invalid notification"),void o(!0);var s,c,u=t.find(e,["store","proxy","teams"])||{};if(Object.keys(u).some(function(e){var n=u[e];if(n.channel===i.teamChannel)return s=e,c=n,!0}),s){if(i.team=c,!i.answer)try{e.store.modules.team.removeFromTeam(s,a.author,!0)}catch(e){console.error(e)}var f=i.user||i;n.sendMessage({type:"INVITE_TO_TEAM_ANSWERED",content:{user:f,team:c,answer:i.answer}},function(){}),o(!0)}else o(!0)},i.TEAM_EDIT_RIGHTS=function(e,n,r,o){var a=r.msg.content;if(!a.teamData)return console.log("Remove invalid notification"),void o(!0);var i,s=t.find(e,["store","proxy","teams"])||{};if(Object.keys(s).some(function(e){if(s[e].channel===a.teamData.channel)return i=e,!0}),i)try{e.store.modules.team.changeMyRights(i,a.state,a.teamData,function(e){e||console.error("Can't update team rights"),o(!0)})}catch(e){console.error(e)}else o(!0)},i.OWNED_PAD_REMOVED=function(e,n,t,r){var o=t.msg.content;if(!o.channel)return console.log("Remove invalid notification"),void r(!0);var a=o.channel;e.store.manager.findChannel(a).forEach(function(n){var t=e.store.manager.findFile(n.id);e.store.manager.delete({paths:t},function(){e.updateDrive()})}),r(!0)},i.MOVE_TODO=function(e,n,t,r){var o=e.store.proxy.curvePublic;t.msg.author===o?r():r(!0)},i.SAFE_LINKS_DEFAULT=function(e,n,t,r){var o=e.store.proxy.curvePublic;t.msg.author===o?r():r(!0)};var m={};i.FORM_RESPONSE=function(e,n,t,r){var o,a,i=t.msg,s=t.hash,c=i.content,u=c.channel;if(u)if(function(e,n){return(e.store.proxy.mutedChannels||[]).includes(n)}(e,u))r(!0);else if(e.Store.getAllStores().some(function(e){return e.manager.findChannel(u).some(function(e){if(e.data&&(!a||e.data.href))return a=e.data.href||e.data.roHref,o=e.data.filename||e.data.title,!!e.data.href||void 0})}),a){c.href=a,c.title=o;var f=m[u],l=f?f.data:void 0;m[u]={data:{type:n.type,hash:s}},r(!1,l)}else r(!0);else r(!0)},s.FORM_RESPONSE=function(e,n,t,r){var o=t.content.channel,a=m[o];a&&a.data&&a.data.hash===r&&delete m[o]};var g={};i.COMMENT_REPLY=function(e,n,r,o){var a=r.msg,i=r.hash,s=a.content;if(t.find(e.store.proxy,["settings","pad","disableNotif"]))o(!0);else{var c,u,f=s.channel;if(f)if(e.Store.getAllStores().some(function(e){return e.manager.findChannel(f).some(function(e){if(e.data&&(!u||e.data.href))return u=e.data.href||e.data.roHref,c=e.data.filename||e.data.title,!!e.data.href||void 0})}),u){s.href=u,s.title=c;var l=g[f],d=l?l.data:void 0;g[f]={data:{type:n.type,hash:i}},o(!1,d)}else o(!0);else o(!0)}},s.COMMENT_REPLY=function(e,n,t,r){var o=t.content.channel,a=g[o];a&&a.data&&a.data.hash===r&&delete g[o]};var E,b,O={};i.MENTION=function(e,n,t,r){var o=t.msg,a=t.hash,i=o.content;if(c(e,t))r(!0);else{var s=i.channel;if(s){var u,f;e.Store.getAllStores().some(function(e){return e.manager.findChannel(s).some(function(e){if(e.data&&(!f||e.data.href))return f=e.data.href||e.data.roHref,u=e.data.filename||e.data.title,!!e.data.href||void 0})}),i.href=f,i.title=u;var l=O[s],d=l?l.data:void 0;O[s]={data:{type:n.type,hash:a}},r(!1,d)}else r(!0)}},s.MENTION=function(e,n,t,r){var o=t.content.channel,a=O[o];a&&a.data&&a.data.hash===r&&delete O[o]},i.BROADCAST_MAINTENANCE=function(e,n,t,r){var o=t.msg.uid;e.Store.onMaintenanceUpdate(o),r(!0)},i.BROADCAST_SURVEY=function(e,n,t,r){var o=t.msg,a=o.content,i=o.uid,s=E;E={type:n.type,hash:t.hash},e.Store.onSurveyUpdate(i),r(!a.url,s)},i.BROADCAST_CUSTOM=function(e,n,t,r){var o=t.msg.uid,a=b;b={uid:o,type:n.type,hash:t.hash},r(!1,a)},i.BROADCAST_DELETE=function(e,n,t,r){var o=t.msg.content.uid;if(b&&b.uid===o)return r(!0,b),void(b=void 0);r(!0)};var A,w,D={};return i.SF_DELETED=function(e,n,t,r){var o=t.msg.content,a=o.team,i=o.sfId;if(D[i])r(!0);else if(D[i]=1,a){var s=e.store.proxy.teams[a];o.teamName=s.metadata&&s.metadata.name,r(!1)}else r(!1)},s.SF_DELETED=function(e,n,t){var r=t.content.sfId;delete D[r]},i.NEW_TICKET=function(e,n,r,o){var a=r.msg.content;a.time||(a.time=r.time);var i=t.find(e,["store","modules","support"]);a.isAdmin&&i.addUserTicket(a,o),i.addAdminTicket(a,o)},i.NOTIF_TICKET=function(e,n,r,o){var a=r.msg.content;a.time||(a.time=r.time);var i=t.find(e,["store","modules","support"]);if(a.isAdmin)return t.find(e,["store","proxy","support",a.channel])?(i.updateUserTicket(a),A?void o(!1,A):(A={channel:a.channel,type:n.type,hash:r.hash},void o(!1))):void o(!0);i.checkAdminTicket(a,s=>{s?(i.updateAdminTicket(a),t.find(e.store.proxy,["settings","general","disableSupportNotif"])?o(!0):w?o(!1,w):(w={channel:a.channel,type:n.type,hash:r.hash},o(!1))):o(!0)})},s.NOTIF_TICKET=function(e,n,t){var r=t.content.channel;A&&A.channel===r&&(A=void 0),w&&w.channel===r&&(w=void 0)},i.ADD_MODERATOR=function(e,n,r,o){var a=r.msg.content;t.find(e,["store","modules","support"]).updateAdminKey(a,o)},i.MODERATOR_NEW_KEY=function(e,n,r,o){var a=r.msg.content;t.find(e,["store","modules","support"]).updateAdminKey(a,function(){o(!0)})},{add:function(e,n,r,o){if(r.msg){var a=t.find(e,["store","proxy","curvePublic"]),s=t.find(r,["msg","content","user","curvePublic"])||t.find(r,["msg","content","curvePublic"]);if(s&&r.msg.author!==s&&r.msg.author!==a)return console.error("blocked"),void o(null,null,!0);var c=r.msg.type;if(i[c])try{i[c](e,n,r,o)}catch(e){console.error(e),o()}else o()}else o(null,null,!0)},remove:function(e,n,t,r){if(t){var o=t.type;if(s[o])try{s[o](e,n,t,r)}catch(e){console.error(e)}}}}})(On(),te(),Z(),M(),hn())),Rn),D(),M()),kn}function Kn(){if(Ln)return Fn;Ln=1;return Fn=((e,n,t,r,o,a,i,s,c)=>{let u={};let f=function(f,l,d,h){var p=f.version||0;s(function(){}).nThen(function(){var n,t,r,o,a;p<2&&(n="cryptpad.userlist-drawer",t="cryptpad.hide_poll_text",r="cryptpad.indentUnit",o="cryptpad.indentWithTabs",a=f.settings=f.settings||{},void 0!==f[r]&&(a.codemirror=a.codemirror||{},a.codemirror.indentUnit=f[r],delete f[r]),void 0!==f[o]&&(a.codemirror=a.codemirror||{},a.codemirror.indentWithTabs=f[o],delete f[o]),void 0!==f[n]&&(a.toolbar=a.toolbar||{},a.toolbar["userlist-drawer"]=f[n],delete f[n]),void 0!==f[t]&&(a.poll=a.poll||{},a.poll["hide-text"]=f[t],delete f[t]),e.send("Migrate-2",!0),f.version=p=2)}).nThen(function(){p<3&&(!function(){if(localStorage.CRYPTPAD_LANG){var e=localStorage.CRYPTPAD_LANG;f.settings.language=e}}(),e.send("Migrate-3",!0),f.version=p=3)}).nThen(function(){var n;p<4&&(n=f.settings=f.settings||{},void 0!==f.allowUserFeedback&&(n.general=n.general||{},n.general.allowUserFeedback=f.allowUserFeedback,delete f.allowUserFeedback),e.send("Migrate-4",!0),f.version=p=4)}).nThen(function(){p<5&&(!function(){var e=f.drive&&f.drive.filesData;if(e)for(var n in e)"number"!=typeof e[n].ctime&&(e[n].ctime=+new Date(e[n].ctime)),"number"!=typeof e[n].atime&&(e[n].atime=+new Date(e[n].atime))}(),e.send("Migrate-5",!0),f.version=p=5)}).nThen(function(t){var r,o,a,i,c;p<6&&(a=f.drive.filesData||{},i=s(function(){}),c=Object.keys(a).length,Object.keys(a).forEach(function(e,t){i=i.nThen(function(i){setTimeout(i(function(){if(r=a[e],o=n.parsePadUrl(r.href),r.href&&!r.channel){var i=n.getSecrets(o.type,o.hash,r.password);r.channel=i.channel,d(6,Math.round(100*t/c)),console.log("Adding missing channel in filesData ",r.channel)}}))})}),i.nThen(t(function(){e.send("Migrate-6",!0),f.version=p=6})))}).nThen(function(t){var r,o,a,i,c;p<7&&(a=f.drive.filesData,i=s(function(){}),c=Object.keys(a).length,Object.keys(a).forEach(function(e,t){i=i.nThen(function(i){setTimeout(i(function(){if((r=a[e]).href)if(-1!==r.href.indexOf("#"))if("pad"===(o=n.parsePadUrl(r.href)).hashData.type){if("view"===o.hashData.mode)r.roHref=r.href,delete r.href,console.log("Move href to roHref in filesData ",r.roHref);else{var i=n.getSecrets(o.type,o.hash,r.password),s=n.getViewHashFromKeys(i);s&&(r.roHref="/"+o.type+"/#"+s,console.log("Adding missing roHref in filesData ",r.href))}d(6,Math.round(100*t/c))}else d(7,Math.round(100*t/c));else d(7,Math.round(100*t/c));else d(7,Math.round(100*t/c))}))})}),i.nThen(t(function(){e.send("Migrate-7",!0),f.version=p=7})))}).nThen(function(){p<8&&(f.FS_hashes=t.deduplicateString(f.FS_hashes||[]),e.send("Migrate-8",!0),f.version=p=8)}).nThen(function(){p<9&&(!function(){var e=h.network,n={},t={store:h},o=r.createData(f),i=function(e){var t=n[e];if(t){try{t.wc.leave()}catch(e){}delete n[e]}};e.on("message",function(r,s){try{!function(r,s){if(s===e.historyKeeper){var c=JSON.parse(r);if(!c.validateKey&&!c.owners||!c.channel){if(c.channel&&n[c.channel]){if(c.error&&"EINVAL"===c.error){var u=["GET_HISTORY",c.channel,{}];return void e.sendto(e.historyKeeper,JSON.stringify(u)).then(function(){},function(){})}if(c.state&&1===c.state){o.channel=c.channel;var f=["UPDATE",o.curvePublic,+new Date,o],l=n[c.channel].encrypt(JSON.stringify(f));return n[c.channel].wc.bcast(l).then(function(){},function(e){console.error("Can't migrate this friend",n[c.channel].friend,e)}),void i(c.channel)}}else if(c.channel)return;var d=c[3];if(d&&n[d]){var h=n[d],p=h.decrypt(c[4]),v=JSON.parse(p);if("UPDATE"===v[0]){if(v[1]===o.curvePublic)return;var y=v[3];if(!y.notifications)return;h.friend.notifications=y.notifications,o.channel=d,a.sendTo(t,"UPDATE_DATA",o,{channel:y.notifications,curvePublic:y.curvePublic},function(e){e&&e.error?console.error(e):console.log("friend migrated",h.friend)}),i(d)}}}}}(r,s)}catch(e){console.error(e)}});var s=f.friends||{};Object.keys(s).forEach(function(t){if(44===t.length){var r=s[t];r.notifications||e.join(r.channel).then(function(t){var o=c.Curve.deriveKeys(r.curvePublic,f.curvePrivate),a=c.Curve.createEncryptor(o);n[r.channel]={wc:t,friend:r,decrypt:a.decrypt,encrypt:a.encrypt};var i={lastKnownHash:r.lastKnownHash},s=["GET_HISTORY",r.channel,i];e.sendto(e.historyKeeper,JSON.stringify(s)).then(function(){},function(e){console.error("Can't migrate this friend",r,e)})},function(e){console.error("Can't migrate this friend",r,e)})}})}(),e.send("Migrate-9",!0),f.version=p=9)}).nThen(function(t){p<10&&function(){var i=h.proxy.todo;if(i){var c,l=t(function(){e.send("Migrate-10",!0),f.version=p=10}),d={network:h.network,initialState:"{}",metadata:{owners:h.proxy.edPublic?[h.proxy.edPublic]:[]}};s(function(e){o.get(i,e(function(n,t){if(n||!t)return e.abort(),void l();try{c=JSON.parse(t)}catch(e){}}),d)}).nThen(function(e){if(!c||"object"!=typeof c)return e.abort(),void l();var t={content:{data:{1:{id:"1",color:"color6",item:[],title:u.kanban_todo},2:{id:"2",color:"color3",item:[],title:u.kanban_working},3:{id:"3",color:"color5",item:[],title:u.kanban_done}},items:{},list:[1,2,3]},metadata:{title:u.type.todo,defaultTitle:u.type.todo,type:"kanban"}},s=4,p=!1;if((c.order||[]).forEach(function(e){var n=c.data[e];if(n&&n.task){p=!0;var r=n.state?"3":"1";t.content.data[r].item.push(s),t.content.items[s]={id:s,title:n.task},s++}}),!p)return e.abort(),void l();var v=n.createRandomHash("kanban"),y=n.getSecrets("kanban",v),m=n.getSecrets("todo",i);o.put(v,JSON.stringify(t),e(function(t){if(t)return e.abort(),void l();h.rpc&&(h.rpc.pin([y.channel],function(){}),h.rpc.unpin([m.channel],function(){}));var o=n.hashToHref(v,"kanban");h.manager.addPad(["root"],{title:u.type.todo,owners:d.metadata.owners,channel:y.channel,href:o,roHref:n.hashToHref(n.getViewHashFromKeys(y),"kanban"),atime:+new Date,ctime:+new Date},e(function(e){if(e)console.error(e);else{delete h.proxy.todo;var n=r.createData(f),t={store:h};a.sendTo(t,"MOVE_TODO",{user:n,href:o},{channel:n.notifications,curvePublic:n.curvePublic},function(e){e&&e.error&&console.error(e)})}}))}),d)}).nThen(function(){l()})}}()}).nThen(function(n){if(!(p>=11)){var o=function(){e.send("Migrate-11",!0),f.version=p=11};if(void 0===t.find(f,["settings","security","unsafeLinks"])){var i={store:h},s=r.createData(f);s.curvePublic?a.sendTo(i,"SAFE_LINKS_DEFAULT",{user:s},{channel:s.notifications,curvePublic:s.curvePublic},n(function(e){e&&e.error?console.error(e):o()})):o()}else o()}}).nThen(function(){i.whenRealtimeSyncs(h.realtime,t.mkAsync(t.bake(l)))})};return f.setCustomize=e=>{u=e.Messages},f})(Ae(),te(),Z(),On(),xn(),jn(),je(),qe(),M()),Fn}var Un,Bn,Vn=o(be);var Yn,Gn,Jn,qn,Wn=Bn?Un:(Bn=1,Yn=xn(),Gn=Ue(),te(),Jn=je(),qn={anonDriveIntoUser:function(e,n,t){n&&e.loggedIn||"function"!=typeof t?Yn.get(n,function(r,o){var a;if(r)console.error("Cannot migrate recent pads",r);else if(o){try{a=JSON.parse(o)}catch(e){return"function"==typeof t&&t(),void console.error("Cannot parsed recent pads",e)}if(a){var i=e.proxy,s=Gn.init(a.drive,{readOnly:!1,loggedIn:!0,outer:!0}),c=function(){s.fixFiles(!0);var r=e.manager;s.getFiles([s.FILES_DATA]).forEach(function(e){var n=s.getFileData(e),t=n.channel,o=r.findChannel(t);if(0===o.length)n&&r.addPad(null,n,function(e){e&&console.error("Cannot import file:",n,e)});else{if(!n.href)return;o.forEach(function(e){e.data&&!e.data.href&&e.userObject.setHref(t,null,n.href)})}}),i.FS_hashes&&Array.isArray(i.FS_hashes)||(i.FS_hashes=[]),-1===i.FS_hashes.indexOf(n)&&i.FS_hashes.push(n),"function"==typeof t&&Jn.whenRealtimeSyncs(e.realtime,t)};s&&"function"==typeof s.migrate?s.migrate(c):(console.log("oldFo.migrate is not a function"),c())}else"function"==typeof t&&t()}else"function"==typeof t&&t()}):t()}},Un=qn);const zn=ie.mkEvent(!0),Qn=ie.mkEvent(!0),Zn=ie.mkEvent(),Xn=ie.mkEvent(),$n=(e,n)=>{var t,r;const o=e.store,a=e.Store;let i;if(n){const e=a.getStore(n);i=null===(r=null==e?void 0:e.proxy)||void 0===r?void 0:r.drive}else i=null===(t=o.drive)||void 0===t?void 0:t.proxy;return i},et={init:e=>{var n;const{broadcast:t,store:r,Store:o,account:a}=e,i=r.drive||(r.drive={});let s=null===(n=r.proxy)||void 0===n?void 0:n.drive;if((null==s?void 0:s.hash)||ae.createRandomHash("drive"),!s.hash)return i.proxy=s,a.onAccountCacheReady(()=>{zn.fire()}),a.onAccountReady(()=>{Qn.fire()}),{channel:"",onDriveCacheReady:zn.reg,onDriveReady:Qn.reg,onDisconnect:Zn.reg,onReconnect:Xn.reg};throw new Error("NOT IMPLEMENTED")},initAPI:e=>{const{broadcast:n,store:t,Store:r,account:o}=e,a={store:t,Store:r};return{exists:(e,n,r)=>{r({state:Boolean(t.proxy)})},get:(e,n,t)=>{let r=$n(a,n.teamId);t(r?{drive:r}:{error:"ENOTFOUND"})},set:(e,n,t)=>{let o=$n(a,n.teamId);var i,s;o?(i=o,s=n.value,Object.keys(i).forEach(e=>{delete i[e]}),Object.keys(s).forEach(e=>{i[e]=ie.clone(s[e])}),r.onSync(n.teamId,t)):t({error:"ENOTFOUND"})},migrateAnon:(e,n,r)=>{Wn.anonDriveIntoUser(t,n.anonHash,r)}}}};var nt=o(Object.freeze({__proto__:null,Drive:et})),tt=D(),rt=r(qe()),ot=r(bn()),at=We();const it=ie.mkEvent(!0),st=ie.mkEvent(!0),ct=(e,n,t,r)=>{const o=ie.once(ie.mkAsync(r)),{store:a,Store:i}=e;!a.offline&&a.anon_rpc?t.channel?32===t.channel.length&&ae.isValidChannel(t.channel)?a.anon_rpc.send("GET_METADATA",t.channel,(e,n)=>{if(e)return void o({error:e});const r=n&&n[0]||{};o(r),r.rejected||i.getAllStores().forEach(e=>{const n=e.manager.findChannel(t.channel,!0);let o=!1;(n.forEach(e=>{ot(e.data.owners)!==ot(r.owners)&&(o=!0),e.data.owners=r.owners,e.data.atime=+new Date,r.expire&&(e.data.expire=+r.expire)}),o)&&(e.sendEvent||a.sendDriveEvent)("DRIVE_CHANGE",{path:["drive",en.FILES_DATA]})})}):o({error:"EINVAL"}):o({error:"ENOTFOUND"}):o({error:"OFFLINE"})},ut=(e,n,t)=>{if(t.versionHash)return((e,n,t)=>{let r;const{Store:o,store:a,postMessage:i}=e,s=t.channel,c=t.versionHash,u=ae.createChannelId();rt(t=>{ct(e,0,{channel:s},t(e=>{if(e&&e.rejected)return i(n,"PAD_ERROR",{type:"ERESTRICTED"}),void t.abort();r=e.validateKey}))}).nThen(()=>{o.getHistoryRange(n,{cpCount:1,channel:s,lastKnownHash:c},e=>{var t,o;if(e&&e.error)return i(n,"PAD_ERROR",e.error);const f=e.messages||[];if((null===(t=f[f.length-1])||void 0===t?void 0:t.serverHash)!==c)return i(n,"PAD_ERROR",{type:"HASH_NOT_FOUND"});i(n,"PAD_CONNECT",{myID:u,id:s,members:[u]}),(e.messages||[]).forEach(e=>{i(n,"PAD_MESSAGE",{msg:e.msg,time:e.time,user:u.slice(0,16)})}),r&&(null===(o=null==a?void 0:a.messenger)||void 0===o||o.storeValidateKey(s,r)),i(n,"PAD_READY")})})})(e,n,t);const{channels:r,store:o,Store:a,myDeletions:i,postMessage:s}=e,c=t.channel;if(!ae.isValidChannel(c))return s(n,"PAD_ERROR","INVALID_CHAN");const u=void 0===r[c],f=r[c]||(r[c]={queue:[],data:{},clients:[],bcast:(e,n,t)=>{f.clients.forEach(function(r){r!==t&&s(r,e,n)})},history:[],pushHistory:(e,n)=>{if(n){let n;for(f.history.push("cp|"+e),n=f.history.length-101;n>0&&!/^cp\|/.test(f.history[n]);n--);return void(f.history=f.history.slice(n))}f.history.push(e)}});if(-1===f.clients.indexOf(n)&&f.clients.push(n),!u&&f.wc)return s(n,"PAD_CONNECT",{myID:f.wc.myID,id:f.wc.id,members:f.wc.members}),f.wc.members.forEach(e=>{s(n,"PAD_JOIN",e)}),f.history.forEach(e=>{s(n,"PAD_MESSAGE",{msg:tt.removeCp(e),user:f.wc.myID,validateKey:f.data.validateKey})}),void s(n,"PAD_READY");const l=n=>{const r=null==n?void 0:n.type;"EDELETED"===r&&i[c]&&(delete i[c],n.ownDeletion=!0),f.bcast("PAD_ERROR",n),"EDELETED"===r&&(null==de?void 0:le.clearChannel)&&le.clearChannel(c),["EDELETED","EEXPIRED","ERESTRICTED"].includes(r)&&e.leavePad(null,t,function(){})},d={Cache:o.neverCache?void 0:de,priority:1,onCacheStart:()=>{s(n,"PAD_CACHE")},onCacheReady:()=>{s(n,"PAD_CACHE_READY"),st.fire()},onReady:e=>{const t=e.metadata||{};f.data=t,(null==t?void 0:t.validateKey)&&o.messenger&&o.messenger.storeValidateKey(c,t.validateKey),s(n,"PAD_READY",e.noCache)},onMessage:function(e,n,t,r,o){f.lastHash=o,f.pushHistory(e,r),f.bcast("PAD_MESSAGE",{user:n,msg:e,validateKey:t})},onJoin:function(e){f.bcast("PAD_JOIN",e)},onLeave:function(e){f.bcast("PAD_LEAVE",e)},onError:l,onChannelError:l,onRejected:a.onRejected,onConnectionChange:e=>{e.state||f.bcast("PAD_DISCONNECT")},onMetadataUpdate:e=>{f.data=e||{},a.getAllStores().forEach(n=>{n.manager.findChannel(c,!0).forEach(n=>{n.data.owners=e.owners,n.data.atime=+new Date,e.expire&&(n.data.expire=+e.expire)});(n.sendEvent||o.sendDriveEvent)("DRIVE_CHANGE",{path:["drive",en.FILES_DATA]})}),f.bcast("PAD_METADATA",e)},crypto:{encrypt:function(e){return e},decrypt:function(e){return e}},noChainPad:!0,channel:c,metadata:t.metadata,network:o.network||o.networkPromise,websocketURL:U.getWebsocketURL(),onInit:function(){it.fire()},onConnect:(e,t)=>{f.sendMessage=(n,r,o)=>{t(n,t=>{t?o({error:t}):(f.lastHash=n.slice(0,64),f.pushHistory(tt.removeCp(n),/^cp\|/.test(n)),f.bcast("PAD_MESSAGE",{user:e.myID,msg:tt.removeCp(n),validateKey:f.data.validateKey},r),o())})},f.wc=e,f.queue.forEach(function(e){f.sendMessage(e.message,n)}),f.queue=[],f.bcast("PAD_CONNECT",{myID:e.myID,id:e.id,members:e.members})}};f.cpNf=tt.start(d)},ft=(e,n)=>{var t,r,o,a,i,s;const c=e.store;if(null===(r=null===(t=c.messenger)||void 0===t?void 0:t.leavePad)||void 0===r||r.call(t,n),null===(a=null===(o=c.onlyoffice)||void 0===o?void 0:o.leavePad)||void 0===a||a.call(o,n),Object.keys(c.modules).forEach(e=>{var t,r;null===(r=null===(t=c.modules[e])||void 0===t?void 0:t.leavePad)||void 0===r||r.call(t,n)}),!((e,n)=>{const{store:t}=e;if(!t)return!1;if(t.driveChannel===n)return!0;if(at.isSharedFolderChannel(n))return!0;if(ie.find(t,["proxy","teams"])){var r=ie.find(t,["proxy","teams"])||{};return Object.keys(r).some(e=>r[e].channel===n)}if(ie.find(t,["proxy","profile","href"])){let e=ie.find(t,["proxy","profile","href"]);return ae.hrefToHexChannelId(e)===n}})(e,n)){try{le.leaveChannel(n)}catch(e){console.error(e)}null===(s=null===(i=e.channels[n])||void 0===i?void 0:i.cpNf)||void 0===s||s.stop()}delete e.channels[n]},lt={init:e=>{const{broadcast:n,postMessage:t,store:r,Store:o}=e,a={channels:[],postMessage:t,store:r,Store:o,myDeletions:[],leavePad:(e,n,t)=>{}},i=(e,n,t)=>{const r=a.channels[n.channel];(null==r?void 0:r.cpNf)?(ft(a,n.channel),t()):t({error:"EINVAL"})};a.leavePad=i;return{join:(e,n,t)=>{ut(a,e,n)},destroy:(e,n,t)=>{((e,n,t,r)=>{const{store:o,Store:a,channels:i,myDeletions:s}=e;let c,u,f=t,l=!1;if(t&&"object"==typeof t&&({channel:f,force:l,teamId:c,reason:u}=t),f===o.driveChannel&&!l)return void r({error:"User drive removal blocked!"});const d=a.getStore(c);d?d.rpc?(i[f]&&(s[f]=!0),d.rpc.removeOwnedChannel(f,e=>{e&&delete s[f],r({error:e})},u)):r({error:"RPC_NOT_READY"}):r({error:"ENOTFOUND"})})(a,0,n,t)},clear:(e,n,t)=>{((e,n,t,r)=>{const{Store:o}=e,a=o.getStore(t&&t.teamId);a.rpc?a.rpc.clearOwnedChannel(t.channel,e=>{r({error:e})}):r({error:"RPC_NOT_READY"})})(a,0,n,t)},setMetadata:(e,n,t)=>{((e,n,t,r)=>{if(!t.channel)return void r({error:"ENOTFOUND"});if(!t.command)return void r({error:"EINVAL"});const{Store:o}=e,a=o.getStore(t.teamId);if(!a)return void r({error:"ENOTFOUND"});const i=t.channels;delete t.channels,a.rpc.setMetadata(t,(e,n)=>{e?r({error:e}):Array.isArray(n)&&n.length?r(n[0]):r({})}),Array.isArray(i)&&i.forEach(e=>{var r=ie.clone(t);r.channel=e,o.setPadMetadata(n,r,()=>{})})})(a,e,n,t)},getMetadata:(e,n,t)=>{ct(a,0,n,t)},sendMessage:(e,n,t)=>{((e,n,t,r)=>{var o=t.msg,a=e.channels[t.channel];if(a)a.wc?a.sendMessage(o,n,r):(a.queue.push(o),r())})(a,e,n,t)},onCorruptedCache:(e,n,t)=>{((e,n,t)=>{var r=e.channels[t];r&&r.cpNf&&(le.clearChannel(t),r.cpNf.resetCache&&r.cpNf.resetCache())})(a,0,n)},getLastHash:(e,n,t)=>{((e,n,t,r)=>{var o=e.channels[t.channel];o?o.lastHash?r({hash:o.lastHash}):r({error:"EINVAL"}):r({error:"ENOCHAN"})})(a,0,n,t)},leave:i,removeClient:e=>{Object.keys(a.channels).forEach(n=>{let t=a.channels[n].clients.indexOf(e);-1!==t&&a.channels[n].clients.splice(t,1),0===a.channels[n].clients.length&&ft(a,n)})},onJoined:it.reg,onCacheReady:st.reg,getChannels:()=>a.channels}}};var dt,ht,pt,vt,yt,mt,gt,Et,bt,Ot,At,wt,Dt,_t,Tt,St,Nt,It,xt,Ct,Rt=o(Object.freeze({__proto__:null,Pad:lt}));function Pt(){if(ht)return dt;ht=1;return dt=((e,n,t)=>{const r={};let o={},a={};r.setCustomize=e=>{o=e.Messages,a=e.AppConfig};var i=function(e,n){n.degraded||n.clients.forEach(function(t){var r=e.clients[t];if(r){var o={id:r.id,cursor:r.cursor};n.sendMsg(JSON.stringify(o))}})},s=function(e,n,t){var r=n.members,o=a.degradedLimit||8;t.degraded=r.length-1>=o,e.emit("DEGRADED",{degraded:t.degraded},t.clients)},c=function(e,n,r,o){var a=n.channel,c=n.secret;c.keys.cryptKey&&(c.keys.cryptKey=function(e){for(var n=Object.keys(e).length,t=new Uint8Array(n),r=0;r{const f={};let l={};f.setCustomize=e=>{l=e.ApiConfig};var d=i.Nacl,h=function(e,n,t,r){let o=Object.keys(e.clients).filter(t=>Boolean(e.clients[t].admin)===n);o.length&&e.emit(t,{channel:r},[o])},p=function(n,t,r,o){var a=e.mkAsync(o);if(t&&!n.adminRdyEvt)return void a("EFORBIDDEN");let i=l.httpUnsafeOrigin;e.fetchApi(i,"config",!0,o=>{n.moderatorKeys=o.moderatorKeys,n.adminKeys=o.adminKeys;var i=o.supportMailboxKey;if(i){if(!t||e.find(n.store.proxy,["mailboxes","supportteam","keys","curvePublic"])===i)return t?n.adminRdyEvt.reg(()=>{a(null,{supportKey:i,myCurve:r.adminCurvePrivate||e.find(n.store.proxy,["mailboxes","supportteam","keys","curvePrivate"]),theirPublic:r.curvePublic,notifKey:r.curvePublic})}):void a(null,{supportKey:i,myCurve:n.store.proxy.curvePrivate,theirPublic:r.curvePublic||i,notifKey:i});a("EFORBIDDEN")}else a("E_NOT_INIT")})},v=function(n,t,r,o){var s,c,f=e.once(e.mkAsync(o));a(e=>{p(n,r,t,e((n,t)=>{if(n)return e.abort(),void f({error:n});s=t.theirPublic,c=t.myCurve}))}).nThen(()=>{var r,o=i.Curve.deriveKeys(s,c),a=i.Curve.createEncryptor(o),l={network:n.store.network,channel:t.channel,noChainPad:!0,crypto:a,owners:[]},d=[];f=e.both(function(){r&&"function"==typeof r.stop&&r.stop()},f),l.onMessage=function(e,n,t,r,o,a,i){var s=i&&i.time;try{e=JSON.parse(e)}catch(e){return void console.error(e)}e.time=s,a&&(e.author=a),d.push(e)},l.onError=f,l.onChannelError=f,l.onReady=function(){f(null,d)},r=u.start(l)})},y=function(t,r,o,s){var c=e.find(t,["store","mailbox"]),u=e.find(t,["store","anon_rpc"]);if(c)if(u){var f,l,d,h=r.channel,v=r.title,y=r.ticket,m=+new Date;a(e=>{p(t,o,r,e((n,t)=>{if(n)return e.abort(),void s({error:n});f=t.supportKey,l=t.theirPublic,d=t.myCurve}))}).nThen(e=>{var n=i.Curve.deriveKeys(l,d),t=i.Curve.createEncryptor(n),r=JSON.stringify(y),o=t.encrypt(r);u.send("WRITE_PRIVATE_MESSAGE",[h,o],e((n,t)=>{if(n)return e.abort(),void s({error:n});m=t&&t[0]}))}).nThen(e=>{if(o){var n=t.adminDoc.proxy.tickets.active;if(n[h])return e.abort(),void s({error:"EEXISTS"});n[h]={title:y.title,restored:y.legacy,premium:!1,time:m,author:r.name,supportKey:f,lastAdmin:!0,authorKey:r.curvePublic,notifications:r.notifications}}}).nThen(e=>{o||(t.supportData[h]={time:+new Date,title:v,curvePublic:f},t.Store.onSync(null,e()))}).nThen(()=>{var a=o?r.notifications:n.getChannelIdFromKey(f);c.sendTo("NEW_TICKET",{title:v,channel:h,time:m,isAdmin:o,supportKey:f,premium:o?"":e.find(t,["store","account","plan"]),user:e.find(r.ticket,["sender","curvePublic"])?void 0:{supportTeam:!0}},{channel:a,curvePublic:l},e=>{console.error(e),e&&e.error&&delete t.supportData[h],s(e)}),c.sendTo("NOTIF_TICKET",{title:v,channel:h,time:m,isAdmin:o,isNewTicket:!0,user:e.find(r.ticket,["sender","curvePublic"])?void 0:{supportTeam:!0}},{channel:a,curvePublic:l},()=>{})})}else s({error:"anonymous rpc session not ready"});else s({error:"E_NOT_READY"})},m=function(t,r,o,s){var c,u,f,l,d=e.find(t,["store","mailbox"]),h=e.find(t,["store","anon_rpc"]);d?h?r?.ticket?a(e=>{p(t,o,r,e((n,t)=>{if(n)return e.abort(),void s(n);c=t.theirPublic,u=t.myCurve,f=t.notifKey}))}).nThen(e=>{var n=i.Curve.deriveKeys(c,u),t=i.Curve.createEncryptor(n),o=JSON.stringify(r.ticket),a=t.encrypt(o);h.send("WRITE_PRIVATE_MESSAGE",[r.channel,a],e((n,t)=>{if(n)return e.abort(),void s(n);l=t&&t[0],s(void 0,l)}))}).nThen(()=>{var t=o?r.notifChannel:n.getChannelIdFromKey(f);t&&d.sendTo("NOTIF_TICKET",{isAdmin:o,title:r.ticket.title,isClose:r.ticket.close,channel:r.channel,time:l,user:e.find(r.ticket,["sender","curvePublic"])?void 0:{supportTeam:!0}},{channel:t,curvePublic:f},()=>{})}):s("E_NO_DATA"):s("anonymous rpc session not ready"):s("E_NOT_READY")},g=function(t,r,o){var a=n.getSecrets("support",r),u={data:{},channel:a.channel,crypto:i.createEncryptor(a.keys),userName:"support",ChainPad:c,classic:!0,network:t.store.network,metadata:{validateKey:a.keys.validateKey||void 0}},f=t.adminDoc=s.create(u);f.proxy.on("ready",function(){var r=f.proxy;if(r.tickets=r.tickets||{},r.tickets.active=r.tickets.active||{},r.tickets.closed=r.tickets.closed||{},r.tickets.pending=r.tickets.pending||{},t.adminRdyEvt.fire(),o(),!t.supportRpc)return;let a=function(n){if(!n.adminDoc||!n.supportRpc)return;let t=n.adminDoc.metadata&&n.adminDoc.metadata.channel,r=n.adminDoc.proxy.tickets,o=[t,...Object.keys(r.active),...Object.keys(r.pending),...Object.keys(r.closed)];return e.deduplicateString(o).sort()}(t),i=n.hashChannelList(a);t.supportRpc.getServerHash(function(e,n){e?console.warn(e):n!==i&&t.supportRpc.reset(a,function(e){e&&console.warn(e)})})}),f.proxy.on("change",["recorded"],function(){h(t,!0,"RECORDED_CHANGE","")}),f.proxy.on("remove",["recorded"],function(){h(t,!0,"RECORDED_CHANGE","")})},E=function(t,o,i){let s=i(),c=t.store.proxy,u=e.find(c,["mailboxes","supportteam","keys","curvePublic"]),f=e.find(c,["mailboxes","supportteam","keys","curvePrivate"]);o||(t.adminRdyEvt=e.mkEvent(!0)),a(e=>{p(t,!1,{},e((n,r)=>{if(setTimeout(s),n)e.abort();else if(r.theirPublic!==u){try{delete c.mailboxes.supportteam,t.store.mailbox.close("supportteam")}catch(e){}return delete t.adminRdyEvt,void e.abort()}}))}).nThen(n=>{!function(n,t){let o,a,i=e.mkAsync(t),s=n.store.proxy,c=e.find(s,["mailboxes","supportteam","keys","curvePrivate"]);if(c){try{let n=d.sign.keyPair.fromSeed(e.decodeBase64(c));o=e.encodeBase64(n.secretKey),a=e.encodeBase64(n.publicKey)}catch(e){return void i(e)}r.create(n.store.network,{edPublic:a,edPrivate:o},(e,t)=>{e?i(e):(console.log("Support RPC ready, public key is ",a),n.supportRpc=t,i())})}else i("EFORBIDDEN")}(t,n(e=>{e&&console.error("Support RPC not ready",e)}))}).nThen(e=>{let r=f.slice(0,24),o=n.getEditHashFromKeys({version:2,type:"support",keys:{editKeyStr:r}});g(t,o,e())}).nThen(()=>{console.log("Support admin loaded")})};var b=function(n,t,r,o){let a=n.store.proxy,i=e.find(a,["mailboxes","supportadmin"]);i?n.store.mailbox.open("supportadmin",i,function(t){n.store.mailbox.close("supportadmin",function(){});let r=e.clone(t||{}),a=[];Object.keys(r).forEach(e=>{let t=r[e];if("CLOSE"===t.type)return void(a.includes(t.content.id)||a.push(t.content.id));let o=t.author,i=t.content&&t.content.title;((e,n,t)=>{let r=e.adminDoc.proxy;return["active","pending","closed"].some(e=>{let o=r.tickets[e];return Object.keys(o).some(e=>{let r=o[e];return r.authorKey===n&&r.title===t&&r.restored})})})(n,o,i)&&(a.includes(t.content.id)||a.push(t.content.id))}),Object.keys(r).forEach(e=>{let n=r[e];n.content&&a.includes(n.content.id)&&delete r[e]}),o(r)},!0,{dump:!0}):o({error:"ENOENT"})};let O=(n,t,r,o)=>{let a;try{let n=d.sign.keyPair.fromSeed(e.decodeBase64(r));a=e.encodeBase64(n.publicKey)}catch(e){return void o(e)}n.Store.adminRpc(null,{cmd:"ADMIN_DECREE",data:["SET_SUPPORT_KEYS",[t,a]]},o)},A=(e,n,t,r)=>{e.Store.adminRpc(null,{cmd:"GET_MODERATORS",data:{}},r)};return f.init=function(r,i,s){var c={};if(r.store&&r.store.modules&&r.store.modules.support)return r.store.modules.support;var u=r.store,f=u.proxy.support=u.proxy.support||{},g={moderatorKeys:l.moderatorKeys,adminKeys:l.adminKeys,supportData:f,store:r.store,Store:r.Store,emit:s,clients:{}};return e.find(u,["proxy","mailboxes","supportteam"])&&E(g,!1,i),c.ctx=g,c.removeClient=function(e){delete g.clients[e]},c.leavePad=function(){},c.addAdminTicket=function(e,n){!function(e,n,r){e.adminRdyEvt?e.adminRdyEvt.reg(()=>{let o;a(t=>{p(e,!0,n,t((e,n)=>{if(e)return t.abort(),void r(!0);o=n.supportKey}))}).nThen(()=>{var a=Math.floor(2e3*Math.random());setTimeout(()=>{var a=e.adminDoc.proxy;a.tickets.active[n.channel]||a.tickets.closed[n.channel]||a.tickets.pending[n.channel]?r(!0):(a.tickets.active[n.channel]={title:n.title,premium:n.premium,time:n.time,author:n.user&&n.user.displayName,supportKey:n.supportKey||o,authorKey:n.user&&n.user.curvePublic},t.whenRealtimeSyncs(e.adminDoc.realtime,function(){r(!0)}),h(e,!0,"NEW_TICKET",n.channel),e.supportRpc&&e.supportRpc.pin([n.channel],()=>{}))},a)})}):r(!0)}(g,e,n)},c.updateAdminTicket=function(e){!function(e,n){e.adminRdyEvt&&e.adminRdyEvt.reg(()=>{var t=Math.floor(2e3*Math.random());setTimeout(()=>{var t=e.adminDoc.proxy;let r=t.tickets.active[n.channel]||t.tickets.pending[n.channel];r&&(n.time<=r.time||(n.isClose&&(t.tickets.closed[n.channel]=r,delete t.tickets.active[n.channel],delete t.tickets.pending[n.channel]),r.time=n.time,r.lastAdmin=!1,h(e,!0,"UPDATE_TICKET",n.channel)))},t)})}(g,e)},c.updateAdminKey=function(t,r){((t,r,o)=>{let i=r.supportKey,s=n.getBoxPublicFromSecret(i),c=t.store.proxy;const u=e.find(c,["mailboxes","supportteam","keys","curvePrivate"]),f=e.find(c,["mailboxes","supportteam","keys","curvePublic"]);p(t,!1,{},(n,r)=>{if(n)return void o(!0);if(s!==r.theirPublic)return void o(!0);if(u===i||f===s)return void o(!0);let c=e.find(t,["store","mailbox"]);try{t.adminDoc&&t.adminDoc.stop(),c&&c.close("supportteam"),t.supportRpc&&t.supportRpc.destroy(),t.adminRdyEvt=e.mkEvent(!0)}catch(e){console.error(e)}t.Store.addAdminMailbox(null,{version:2,priv:i},e=>{e&&e.error?o(!0):a(e=>{E(t,!0,e),t.adminRdyEvt.reg(()=>{h(t,!0,"UPDATE_RIGHTS"),o(!1)})})})})})(g,t,r)},c.checkAdminTicket=function(e,n){!function(e,n,t){e.adminRdyEvt?e.adminRdyEvt.reg(()=>{let r=e.adminDoc.proxy,o=r.tickets.active[n.channel]||r.tickets.pending[n.channel];t(o)}):t(!0)}(g,e,n)},c.addUserTicket=function(e,n){!function(e,n,t){if(!e.supportData)return void t(!0);let r=n.channel;e.supportData[r]={time:n.time,title:n.title,curvePublic:n.supportKey},e.Store.onSync(null,function(){t(!0)})}(g,e,n)},c.updateUserTicket=function(e){!function(e,n){if(h(e,!1,"UPDATE_TICKET",n.channel),n.isClose){let t=e.supportData[n.channel];if(!t)return;t.closed=!0}}(g,e)},c.execCommand=function(r,i,s){var c=i.cmd,u=i.data;"MAKE_TICKET"!==c?"GET_MY_TICKETS"!==c?"REPLY_TICKET"!==c?"CLOSE_TICKET"!==c?"DELETE_TICKET"!==c?"MAKE_TICKET_ADMIN"!==c?"LIST_TICKETS_ADMIN"!==c?"LOAD_TICKET_ADMIN"!==c?"REPLY_TICKET_ADMIN"!==c?"CLOSE_TICKET_ADMIN"!==c?"MOVE_TICKET_ADMIN"!==c?"GET_RECORDED"!==c?"SET_RECORDED"!==c?"USE_RECORDED"!==c?"SEARCH_ADMIN"!==c?"FILTER_TAGS_ADMIN"!==c?"SET_TAGS_ADMIN"!==c?"GET_LEGACY"!==c?"DUMP_LEGACY"!==c?"CLEAR_LEGACY"!==c?"RESTORE_LEGACY"!==c?"GET_PRIVATE_KEY"!==c?"DISABLE_SUPPORT"!==c?"ROTATE_KEYS"!==c?"ADD_MODERATOR"!==c?s({error:"NOT_SUPPORTED"}):function(n,t,r,o){let a=n.store.proxy;var i=e.find(n,["store","mailbox"]);let s=e.find(a,["mailboxes","supportteam","keys","curvePublic"]),c=e.find(a,["mailboxes","supportteam","keys","curvePrivate"]),u=e.find(a,["mailboxes","supportteam","lastKnownHash"]),f=a.edPublic;p(n,!1,{},(e,r)=>{e?o({error:e}):r.theirPublic===s&&n.moderatorKeys.includes(f)?i.sendTo("ADD_MODERATOR",{supportKey:c,lastKnownHash:u},{channel:t.mailbox,curvePublic:t.curvePublic},()=>{o()}):o({error:"EFORBIDDEN"})})}(g,u,0,s):function(t,r,i,s){let c,u=e.once(e.mkAsync(s)),f=t.store.proxy,l=f.edPublic;const h=d.box.keyPair(),v=e.encodeBase64(h.publicKey),y=e.encodeBase64(h.secretKey),m=e.find(f,["mailboxes","supportteam","keys","curvePrivate"]),g=e.find(f,["mailboxes","supportteam","keys","curvePublic"]);if(!y||!v)return void u({error:"INVALID_KEY"});let b;a(e=>{p(t,!1,{},e((n,t)=>{if("E_NOT_INIT"!==n)return n?(u({error:n}),void e.abort()):void(c=t.theirPublic)}))}).nThen(e=>{if(!t.adminKeys.includes(l))return e.abort(),void u({error:"EFORBIDDEN"})}).nThen(e=>{if(c)return t.moderatorKeys.includes(l)?g!==c?(e.abort(),void u({error:"EFORBIDDEN"})):void 0:(e.abort(),void u({error:"EINVAL"}))}).nThen(e=>{c&&t.adminRdyEvt.reg(()=>{let r=t.adminDoc.proxy;b=t.adminDoc.metadata&&t.adminDoc.metadata.channel;let a=y.slice(0,24),i=n.getEditHashFromKeys({version:2,type:"support",keys:{editKeyStr:a}}),s={network:t.store.network,initialState:"{}"};(r.oldKeys=r.oldKeys||{})[g]={curvePrivate:m,rotatedOn:+new Date,rotatedBy:l},o.put(i,JSON.stringify(r),e(n=>{if(n)return e.abort(),void u({error:n})}),s)})}).nThen(e=>{O(t,v,y,e(n=>{if(n&&n.error)return e.abort(),void u(n)}))}).nThen(()=>{if(!c)return;t.adminDoc&&t.adminDoc.stop();let n=e.find(t,["store","mailbox"]);n&&n.close("supportteam"),t.supportRpc&&t.supportRpc.destroy(),t.adminRdyEvt=e.mkEvent(!0)}).nThen(e=>{t.Store.addAdminMailbox(null,{version:2,priv:y},e(n=>{if(n&&n.error)return e.abort(),c?O(t,g,m,()=>{u(n)}):void u(n)}))}).nThen(n=>{if(!c)return;let r=e.find(t,["store","mailbox"]);A(t,0,0,n(e=>{if(e&&e.error)return void u({success:!0,noNotify:!0});let n=e&&e[0];Object.keys(n||{}).forEach(e=>{let t=n[e];r.sendTo("MODERATOR_NEW_KEY",{supportKey:y},{channel:t.mailbox,curvePublic:t.curvePublic},()=>{})})}))}).nThen(e=>{E(t,!0,e)}).nThen(e=>{b&&t.Store.adminRpc(null,{cmd:"ARCHIVE_DOCUMENT",data:{id:b,reason:"Deprecated support pad"}},e())}).nThen(()=>{u({success:!0})})}(g,0,0,s):function(n,t,r,o){let i,s=e.once(e.mkAsync(o)),c=n.store.proxy.edPublic;a(e=>{p(n,!1,{},e(n=>{if(n)return s({error:n}),void e.abort()}))}).nThen(e=>{if(!n.adminKeys.includes(c))return e.abort(),void s({error:"EFORBIDDEN"})}).nThen(e=>{n.Store.adminRpc(null,{cmd:"ARCHIVE_SUPPORT",data:{}},e(n=>{if(n&&n.error)return e.abort(),void s(n)}))}).nThen(e=>{n.Store.adminRpc(null,{cmd:"ADMIN_DECREE",data:["SET_SUPPORT_KEYS",["",""]]},e(function(n){if(n&&n.error)return e.abort(),void s(n)}))}).nThen(e=>{A(n,0,0,e(n=>{if(!n||n.error)return e.abort(),void s();i=n[0]||{}}))}).nThen(()=>{let e=a;Object.keys(i).forEach(t=>{e=e(e=>{n.Store.adminRpc(null,{cmd:"REMOVE_MODERATOR",data:t},e(e=>{e&&e.error&&console.error("Error removing moderator data",t,e.error)}))}).nThen}),e(()=>{s()})})}(g,0,0,s):function(n,t,r,o){let a=n.store.proxy,i=e.find(a,["mailboxes","supportteam","keys","curvePublic"]),s=e.find(a,["mailboxes","supportteam","keys","curvePrivate"]);p(n,!1,{},(e,n)=>{e?o({error:e}):(i&&n.theirPublic!==i&&(s=void 0),o({curvePrivate:s,curvePublic:n.theirPublic}))})}(g,0,0,s):function(t,r,o,a){let i=t.store.proxy,s=e.find(i,["mailboxes","supportadmin"]);if(!s)return void a({error:"ENOENT"});if(!t.adminRdyEvt)return void a({error:"EFORBIDDEN"});let c=r.messages,u=r.hashes,f=c[0],l=c[c.length-1];f?t.adminRdyEvt.reg(()=>{let r={name:e.find(f,["sender","name"]),notifications:e.find(f,["sender","notifications"]),curvePublic:e.find(f,["sender","curvePublic"]),channel:n.createChannelId(),title:f.title,time:l.time,ticket:{legacy:!0,title:f.title,sender:f.sender,messages:c}};y(t,r,!0,e=>{e&&e.error?a(e):(u.forEach(e=>{s.viewed.push(e)}),t.Store.onSync(null,function(){a({done:!0})}))})}):a({error:"EINVAL"})}(g,u,0,s):function(e,n,t,r){let o=e.store.proxy;e.store.mailbox.close("supportadmin",function(){delete o.mailboxes.supportadmin,e.Store.onSync(null,function(){r({done:!0})})})}(g,0,0,s):function(n,t,r,o){let a=n.store.proxy,i=e.find(a,["mailboxes","supportadmin"]);if(!i)return void o({error:"ENOENT"});let s=e.clone(i);s.lastKnownHash=void 0,s.viewed=[],n.store.mailbox.open("supportadmin",s,function(e){n.store.mailbox.close("supportadmin",function(){}),o(e)},!0,{dump:!0})}(g,0,0,s):b(g,0,0,s):((e,n,r,o)=>{e.adminRdyEvt?e.adminRdyEvt.reg(()=>{let r=e.adminDoc.proxy.tickets,a=n.channel;(r.active[a]||r.pending[a]||r.closed[a]).tags=n.tags||[],t.whenRealtimeSyncs(e.adminDoc.realtime,function(){let e=[];["active","pending","closed"].forEach(n=>{let t=r[n];Object.keys(t).forEach(n=>{(t[n].tags||[]).forEach(n=>{e.includes(n)||e.push(n)})})}),o({done:!0,allTags:e})})}):o({error:"EFORBIDDEN"})})(g,u,0,s):((e,n,t,r)=>{if(!e.adminRdyEvt)return void r({error:"EFORBIDDEN"});let o=n.tags||[];e.adminRdyEvt.reg(()=>{let n=e.adminDoc.proxy.tickets;if(!o.length)return void r({all:!0});let t=[];["active","pending","closed"].forEach(e=>{let r=n[e];Object.keys(r).forEach(e=>{(r[e].tags||[]).some(e=>o.includes(e))||t.push(e)})}),r({tickets:t})})})(g,u,0,s):((n,t,r,o)=>{if(!n.adminRdyEvt)return void o({error:"EFORBIDDEN"});let a=t.tags||[],i=(t.text||"").toLowerCase();n.adminRdyEvt.reg(()=>{let t=n.adminDoc.proxy.tickets,r={},s=(n,t,o)=>{let a=e.clone(t);a.category=o,r[n]=a};["active","pending","closed"].some(n=>{let o=t[n];return Object.keys(o).some(t=>{let c=o[t];if(a.length&&!(c.tags||[]).some(e=>a.includes(e)))return;let u=e.hexToBase64(t).slice(0,10);if(i===u)return r={},s(t,c,n),!0;(!i||c.title.toLowerCase().includes(i))&&s(t,c,n)})}),o({tickets:r})})})(g,u,0,s):function(e,n,t,r){if(!e.adminRdyEvt)return void r({error:"EFORBIDDEN"});let o=n.id;e.adminRdyEvt.reg(()=>{let n=e.adminDoc.proxy,t=(n.recorded=n.recorded||{})[o];t&&(t.count=(t.count||0)+1),r()})}(g,u,0,s):function(e,n,r,o){if(!e.adminRdyEvt)return void o({error:"EFORBIDDEN"});let a=n.id,i=n.content,s=Boolean(n.remove);e.adminRdyEvt.reg(()=>{let n=e.adminDoc.proxy,r=n.recorded=n.recorded||{};s?delete r[a]:r[a]={content:i,count:0},t.whenRealtimeSyncs(e.adminDoc.realtime,function(){o({done:!0})})})}(g,u,0,s):function(n,t,r,o){n.adminRdyEvt?n.adminRdyEvt.reg(()=>{let t=n.adminDoc.proxy,r=t.recorded=t.recorded||{};o({messages:e.clone(r)})}):o({error:"EFORBIDDEN"})}(g,0,0,s):function(e,n,r,o){if(!e.adminRdyEvt)return void o({error:"EFORBIDDEN"});let a=n.channel,i=n.from,s=n.to;e.adminRdyEvt.reg(()=>{let n=e.adminDoc.proxy,r=n.tickets[i],c=n.tickets[s];if(!i||!s)return void o({error:"EINVAL"});let u=r[a];u&&!c[a]?(c[a]=u,delete r[a],t.whenRealtimeSyncs(e.adminDoc.realtime,function(){o({moved:!0})})):o({error:"CANT_MOVE"})})}(g,u,0,s):function(e,n,r,o){if(!e.adminRdyEvt)return void o({error:"EFORBIDDEN"});let a=n.supportKey;e.adminRdyEvt.reg(()=>{let r=e.adminDoc.proxy;r.oldKeys&&r.oldKeys[a]&&(n.adminCurvePrivate=r.oldKeys[a].curvePrivate),m(e,n,!0,r=>{if(r)o({error:r});else{var a=e.adminDoc.proxy,i=a.tickets.active[n.channel]||a.tickets.pending[n.channel];i.time=+new Date,i.lastAdmin=!0,a.tickets.closed[n.channel]=i,delete a.tickets.active[n.channel],delete a.tickets.pending[n.channel],t.whenRealtimeSyncs(e.adminDoc.realtime,function(){o({closed:!0})})}})})}(g,u,0,s):function(e,n,t,r){if(!e.adminRdyEvt)return void r({error:"EFORBIDDEN"});let o=n.supportKey;e.adminRdyEvt.reg(()=>{let t=e.adminDoc.proxy;t.oldKeys&&t.oldKeys[o]&&(n.adminCurvePrivate=t.oldKeys[o].curvePrivate),m(e,n,!0,(t,o)=>{if(t)r({error:t});else{var a=e.adminDoc.proxy,i=a.tickets.active[n.channel]||a.tickets.pending[n.channel];i.time=o,i.lastAdmin=!0,r({sent:!0})}})})}(g,u,0,s):function(n,t,r,o){let a=t.supportKey;n.adminRdyEvt.reg(()=>{let r=n.adminDoc.proxy;r.oldKeys&&r.oldKeys[a]&&(t.adminCurvePrivate=r.oldKeys[a].curvePrivate),v(n,t,!0,function(r,a){if(r)return void o({error:r});var i=n.adminDoc.proxy;if(!Array.isArray(a)||!a.length)return void o(a);a.sort((e,n)=>e.time-n.time);let s=a[a.length-1],c=a.some(n=>{let r=e.find(n,["sender","curvePublic"]);if(t.curvePublic===r)return e.find(n,["sender","quota","plan"])});var u=i.tickets.active[t.channel];u&&(s.legacy&&(s=Array.isArray(s.messages)&&s.messages[s.messages.length-1]),u.time=s.time,u.premium=c,s.sender&&(u.lastAdmin=!s.sender.blockLocation),s.close&&(i.tickets.closed[t.channel]=u,delete i.tickets.active[t.channel],h(n,!0,"UPDATE_TICKET",t.channel))),o(a)})})}(g,u,0,s):function(n,t,r,o){n.adminRdyEvt?(n.clients[r]||(n.clients[r]={admin:!0}),n.adminRdyEvt.reg(()=>{var r=n.adminDoc.proxy;return"pending"===t.type?o(e.clone(r.tickets.pending)):"closed"===t.type?o(e.clone(r.tickets.closed)):void o(e.clone(r.tickets.active))})):o({error:"EFORBIDDEN"})}(g,u,r,s):function(e,n,t,r){e.adminRdyEvt?e.adminRdyEvt.reg(()=>{y(e,n,!0,r)}):r({error:"EFORBIDDEN"})}(g,u,0,s):function(e,n,t,r){let o=e.supportData,a=n.channel;o[a]&&o[a].closed?(delete o[a],r({deleted:!0})):r({error:"ENOTCLOSED"})}(g,u,0,s):function(e,n,t,r){m(e,n,!1,e=>{r(e?{error:e}:{closed:!0})})}(g,u,0,s):function(e,n,t,r){m(e,n,!1,e=>{r(e?{error:e}:{sent:!0})})}(g,u,0,s):function(n,t,r,o){var i=[],s=a;n.clients[r]||(n.clients[r]={admin:!1}),Object.keys(n.supportData).forEach(function(t){s=s(r=>{var o=e.clone(n.supportData[t]);v(n,{channel:t,curvePublic:o.curvePublic},!1,r((e,r)=>{if(e){if("EDELETED"===e.type)return void delete n.supportData[t];o.error=e}else o.messages=r,r.length&&r[r.length-1].close&&(n.supportData[t].closed=!0,o.closed=!0);o.id=t,i.push(o)}))}).nThen}),s(()=>{i.sort((e,n)=>e.closed&&n.closed?e.time-n.time:e.closed?1:n.closed?-1:e.time-n.time),o({tickets:i})})}(g,0,r,s):function(e,n,t,r){y(e,n,!1,r)}(g,u,0,s)},c},f})(Z(),te(),je(),In(),xn(),qe(),M(),T(),x(),D()),pt}function Mt(){if(mt)return yt;mt=1;var e,n,t;return e=M(),t=function(n,t,r,o){var a=t.channel,i=t.secret;i.keys.cryptKey&&(i.keys.cryptKey=function(e){for(var n=Object.keys(e).length,t=new Uint8Array(n),r=0;r{var c={};const u=e.mkEvent(!0);return c.init=function(c,f,l){var d={},h=c.store;if(h.loggedIn&&h.proxy.edPublic){var p={Store:c.Store,store:h,pinPads:c.pinPads,updateMetadata:c.updateMetadata,emit:l,onReadyHandlers:[],clients:[]};return p.profile=h.proxy.profile=h.proxy.profile||{},function(e,t){var r=e.profile;if(r.edit&&r.view)setTimeout(t);else{var o=n.createRandomHash("profile"),a=n.getSecrets("profile",o);e.pinPads([a.channel],function(e){e.error?t(e.error):(r.edit=n.getEditHashFromKeys(a),r.view=n.getViewHashFromKeys(a),setTimeout(t))})}}(p,f(function(r){r||function(r){var o=r.profile,c=n.getSecrets("profile",o.edit),f=i.createEncryptor(c.keys),l={data:{},network:r.store.network,channel:c.channel,crypto:f,owners:[r.store.proxy.edPublic],ChainPad:s,validateKey:c.keys.validateKey||void 0,userName:"profile",classic:!0},d=a.create(l);d.proxy.on("create",function(){}).on("ready",function(){if(d.proxy.name=r.store.proxy[t.displayNameKey]||"",r.listmap=d,d.proxy.curvePublic||(d.proxy.curvePublic=r.store.proxy.curvePublic),d.proxy.notifications||(d.proxy.notifications=e.find(r.store.proxy,["mailboxes","notifications","channel"])),d.proxy.edPublic||(d.proxy.edPublic=r.store.proxy.edPublic),!d.proxy.proof){let n=c.channel,t=e.decodeUTF8(n),o=e.decodeBase64(r.store.proxy.edPrivate),a=i.Nacl.sign(t,o),s=e.encodeBase64(a);d.proxy.proof=s}r.onReadyHandlers.length&&(r.onReadyHandlers.forEach(function(e){try{e(d.proxy)}catch(e){console.error(e)}}),r.onReadyHandlers=[]),u.fire()}).on("change",[],function(){r.emit("UPDATE",d.proxy,r.clients)})}(p)})),d.setName=function(e){!function(e,n){e.listmap.proxy.name=n,r.whenRealtimeSyncs(e.listmap.realtime,function(){e.listmap&&e.emit("UPDATE",e.listmap.proxy,e.clients)})}(p,e)},d.removeClient=function(e){!function(e,n){var t=e.clients.indexOf(n);-1!==t&&e.clients.splice(t,1)}(p,e)},d.update=function(){p.listmap&&p.emit("UPDATE",p.listmap.proxy,p.clients)},d.execCommand=function(e,n,t){console.log(n);var a=n.cmd,i=n.data;"SUBSCRIBE"!==a?"SET"!==a||function(e,n,t,a){u.reg(()=>{var i=n.key,s=n.value;i&&(e.listmap.proxy[i]=s,r.whenRealtimeSyncs(e.listmap.realtime,function(){e.emit("UPDATE",e.listmap.proxy,e.clients.filter(function(e){return e!==t})),"badge"===i&&e.Store.set(null,{key:["profile","badge"],value:s||void 0},()=>{o.updateMyData(e.store),e.updateMetadata()}),a(e.listmap.proxy)}))})}(p,i,e,t):function(e,n,t,r){-1===e.clients.indexOf(t)&&e.clients.push(t),e.listmap?r(e.listmap.proxy):e.onReadyHandlers.push(function(e){r(e)})}(p,0,e,t)},d}},c})(Z(),te(),Y(),je(),On(),T(),M(),x()),bt}function Ht(){if(wt)return At;wt=1;return At=function(e,n,t,r,o,a){var i={},s=function(e){return Boolean(e&&"object"==typeof e&&!Array.isArray(e))},c=function(e){return e.slice(0,64)},u=function(n,t){var r=e.find(t,[n,"role"]);return-1!==["OWNER","ADMIN"].indexOf(r)},f=function(n,t,r){var o=e.find(r,[n,"role"]);return!!o&&(!!function(e){return-1!==["OWNER","ADMIN","MEMBER","VIEWER"].indexOf(e)}(t)&&("OWNER"===o||"ADMIN"===o&&-1!==["ADMIN","MEMBER","VIEWER"].indexOf(t)))},l=function(e){return"string"==typeof e&&44===e.length},d=i.commands={};d.ADD=function(e,n,t){if(!s(e))throw new Error("INVALID ARGS");if(!t.internal.initialized)throw new Error("UNITIALIZED");if(void 0===t.state.members)throw new Error("CANNOT_ADD_TO_UNITIALIZED_ROSTER");var r=t.state.members;Object.keys(e).forEach(function(t){if(!l(t))throw console.log(t,t.length),new Error("INVALID_CURVE_KEY");if(!s(e[t]))throw new Error("INVALID_CONTENT");if(r[t])throw new Error("ALREADY_PRESENT");var o=e[t];if("string"!=typeof o.role&&(o.role="MEMBER"),!f(n,o.role,r))throw new Error("INSUFFICIENT_PERMISSIONS");if("string"!=typeof o.displayName)throw new Error("DISPLAYNAME_REQUIRED");if("string"!=typeof o.notifications)throw new Error("NOTIFICATIONS_REQUIRED")});var o=!1;return Object.keys(e).forEach(function(n){o=!0,r[n]=e[n]}),o},d.RM=function(n,t,r){if(!Array.isArray(n))throw new Error("INVALID_ARGS");if(void 0===r.state.members)throw new Error("CANNOT_RM_FROM_UNITIALIZED_ROSTER");var o=r.state.members;n.forEach(function(n){if(!l(n))throw new Error("INVALID_CURVE_KEY");if(n!==t){var r=o[n].role;if(!function(n,t,r){var o=e.find(r,[n,"role"]);return!!o&&("OWNER"===o||"ADMIN"===o&&-1!==["ADMIN","MEMBER","VIEWER"].indexOf(t))}(t,r,o))throw new Error("INSUFFICIENT_PERMISSIONS")}});var a=!1;return n.forEach(function(e){o[e]&&(a=!0,delete o[e])}),a},d.DESCRIBE=function(n,t,o){if(!n||"object"!=typeof n||Array.isArray(n))throw new Error("INVALID_ARGUMENTS");if(void 0===o.state.members)throw new Error("NOT_READY");var a=o.state.members;Object.keys(n).forEach(function(r){if(!l(r))throw new Error("INVALID_ID");if(!a[r])throw new Error("NOT_PRESENT");if(!function(n,t,r){if(!r[t])return!1;if(n===t&&r[t])return!0;var o=e.find(r,[n,"role"]),a=e.find(r,[t,"role"]);return!!o&&("OWNER"===o||"ADMIN"===o&&"OWNER"!==a)}(t,r,a))throw new Error("INSUFFICIENT_PERMISSIONS");var o=n[r];if(!s(o))throw new Error("INVALID_ARGUMENTS");var i=e.clone(a[r]);if("string"==typeof o.role&&!function(n,t,r,o){return!(n!==t||!o[t])&&("MEMBER"===e.find(o,[n,"role"])?"VIEWER"===r:void 0)}(t,r,o.role,a)&&!f(t,o.role,a))throw new Error("INSUFFICIENT_PERMISSIONS");if("string"!=typeof i.displayName&&"string"!=typeof o.displayName)throw new Error("DISPLAYNAME_REQUIRED");if(-1===["undefined","string"].indexOf(typeof o.displayName))throw new Error("INVALID_DISPLAYNAME");if("string"!=typeof i.notifications&&"string"!=typeof o.notifications)throw new Error("NOTIFICATIONS_REQUIRED");if(-1===["undefined","string"].indexOf(typeof o.notifications))throw new Error("INVALID_NOTIFICATIONS")});var i=!1;return Object.keys(n).forEach(function(t){var o=e.clone(a[t]),s=n[t];Object.keys(s).forEach(function(e){void 0===o[e]||null!==s[e]?o[e]=s[e]:delete o[e]}),r(o)!==r(a[t])&&(i=!0,a[t]=o)}),i},d.CHECKPOINT=function(e,n,t){if(!s(e))throw new Error("INVALID_CHECKPOINT_STATE");if(!t.internal.initialized){t.state=e;var o=t.state.metadata=t.state.metadata||{};return o.topic=o.topic||"",o.name=o.name||"",o.avatar=o.avatar||"",t.internal.initialized=!0,!0}if(r(e)!==r(t.state))throw new Error("CHECKPOINT_DOES_NOT_MATCH_PREVIOUS_STATE");if(!u(n,t.state.members))throw new Error("INSUFFICIENT_PERMISSIONS");return t.state=e,!0};var h=["avatar","name","topic"];d.METADATA=function(n,t,r){if(!s(n))throw new Error("INVALID_ARGS");if(!function(n,t){var r=e.find(t,[n,"role"]);return Boolean(r&&-1!==["OWNER","ADMIN"].indexOf(r))}(t,r.state.members))throw new Error("INSUFFICIENT_PERMISSIONS");Object.keys(n).forEach(function(e){if(null===n[e]){if(-1===h.indexOf(e))return;throw new Error("CANNOT_REMOVE_MANDATORY_METADATA")}if("string"!=typeof n[e])throw new Error("INVALID_ARGUMENTS")});var o=!1;return Object.keys(n).forEach(function(e){void 0!==r.state.metadata[e]&&null===n[e]&&(o=!0,delete r.state.metadata[e]),n[e]!==r.state.metadata[e]&&(o=!0,r.state.metadata[e]=n[e])}),o},d.INVITE=function(e,n,t){if(!s(e))throw new Error("INVALID_ARGS");if(!t.internal.initialized)throw new Error("UNINITIALIED");if(void 0===t.state.members)throw new Error("CANNOT+INVITE_TO_UNINITIALIED_ROSTER");var r=t.state.members;Object.keys(e).forEach(function(t){if(!l(t))throw console.log(t,t.length),new Error("INVALID_CURVE_KEY");if(!s(e[t]))throw new Error("INVALID_CONTENT");if(r[t])throw new Error("ARLEADY_PRESENT");var o=e[t];if("string"!=typeof o.role&&(o.role="VIEWER"),void 0===o.pending&&(o.pending=!0),!f(n,o.role,r))throw new Error("INSUFFICIENT_PERMISSIONS");if("string"!=typeof o.displayName||!o.displayName)throw new Error("DISPLAYNAME_REQUIRED")});var o=!1;return Object.keys(e).forEach(function(n){o=!0,r[n]=e[n]}),o},d.ACCEPT=function(n,t,r){if(!r.internal.initialized)throw new Error("UNINITIALIED");if(void 0===r.state.members)throw new Error("CANNOT_ADD_TO_UNINITIALIED_ROSTER");var o=r.state.members;if(!s(o[t]))throw new Error("INSUFFICIENT_PERMISSIONS");if(!o[t].pending)throw new Error("ALREADY_PRESENT");if("string"!=typeof n)throw new Error("INVALID_ARGS");if(!l(n))throw new Error("INVALID_CURVE_KEY");var a=n;if(void 0!==o[a])throw new Error("MEMBER_ALREADY_PRESENT");var i=e.clone(o[t]);delete i.remaining,delete i.totalUses,delete i.inviteChannel,delete i.previewChannel,o[a]=i;var c=o[t].remaining||1;return-1===c||(c>1?o[t].remaining=c-1:delete o[t]),!0};var p=function(e,n,t){if(!Array.isArray(e)||"string"!=typeof n)throw new Error("INVALID ARGUMENTS");var r=e[0];if("function"!=typeof d[r])throw new Error("INVALID_COMMAND");return d[r](e[1],n,t)},v=function(n,t,r){return p(n,t,e.clone(r))};return i.create=function(n,i){if("function"!=typeof i)throw new Error("EXPECTED_CALLBACK");var f=e.once(e.mkAsync(i));if(n.network)if(n.channel&&"string"==typeof n.channel&&32===n.channel.length)if(n.keys&&"object"==typeof n.keys)if(n.store){var d=e.response(function(e,n){console.error("ROSTER_RESPONSE__"+e,n)}),h=n.store,y=n.keys,m=y.myCurvePublic,g=n.channel,E=n.lastKnownHash||-1;n.newTeam&&(E=void 0);var b={state:{members:{},metadata:{}},internal:{initialized:!1,sinceLastCheckpoint:0,lastCheckpointHash:E}},O={},A={change:e.mkEvent(),checkpoint:e.mkEvent()};O.on=function(e,n){if("object"!=typeof A[e])throw new Error("unsupported event");return A[e].reg(n),O},O.off=function(e,n){if("object"!=typeof A[e])throw new Error("unsupported event");return A[e].unreg(n),O},O.once=function(e,n){if("object"!=typeof A[e])throw new Error("unsupported event");var t=function(){n.apply(null,Array.prototype.slice.call(arguments)),A[e].unreg(t)};return A[e].reg(t),O},O.getState=function(){return e.clone(b.state)},O.getLastCheckpointHash=function(){return b.internal.lastCheckpointHash||-1};var w=function(){b.internal.pendingCheckpointId&&(d.clear(b.internal.pendingCheckpointId),delete b.internal.pendingCheckpointId),clearTimeout(b.internal.checkpointTimeout),delete b.internal.checkpointTimeout};O.stop=function(){b.internal.cpNetflux&&"function"==typeof b.internal.cpNetflux.stop?(b.internal.cpNetflux.stop(),w()):console.log("FAILED TO LEAVE")};var D,_,T,S=!1,N=function(){if(n.onCacheReady){var e=b.state;if(Object.keys(e.members||{}).length)n.onCacheReady(O);else{try{b.internal.cpNetflux.resetCache()}catch(e){console.error(e)}n.onCacheReady({error:"CORRUPTED"})}}},I=function(){S=!0,f(void 0,O)},x=function(e){e&&"EUNKNOWN"===e.type||(S?console.error("CHANNEL_ERROR",e):f(e))},C=function(e){e.state||(S=!1)},R=function(){console.log("ROSTER CONNECTED")},P=function(){return Boolean(S&&m)},k=function(n,t,r,o,a,i){D!==a&&b.internal.sinceLastCheckpoint++,D=a;var s=e.tryParse(n);if(s){var f,l;try{f=p(s,i,b)}catch(e){l=e.message}var h=c(a);if(d.expected(h)){if(l)return void d.handle(h,[l]);try{f?d.handle(h,[void 0,O.getState()]):(d.handle(h,["NO_CHANGE"]),console.log(n))}catch(e){console.log("CAUGHT",e)}}if("CHECKPOINT"===s[0]&&f?(P()&&A.checkpoint.fire(a),b.internal.sinceLastCheckpoint=0,b.internal.lastCheckpointHash=a):f&&P()&&A.change.fire(),w(),P()&&function(e,n){if(!u(e,n.state.members))return!1;var t=n.internal.sinceLastCheckpoint;return!(!t||"number"!=typeof t||t<25)}(m,b)){var v=1e3*Math.floor(20*Math.random())+5e3;b.internal.checkpointTimeout=setTimeout(function(){b.internal.pendingCheckpointId=O.checkpoint(function(e){e&&console.error(e)})},v)}}else console.error("could not parse")},M=function(n,t){var r=e.tryParse(n);return"CHECKPOINT"===r[0]&&v(r,t,b)},F=function(e,n){if(P()){var t=h.anon_rpc;if(t){var o=!1;try{o=v(e,y.myCurvePublic,b)}catch(e){return void n(e.message)}if(o){var a=T.encrypt(r(e)),i=c(a);return d.expect(i,function(e,t){e?n(e):n(void 0,t,i)},3e4),t.send("WRITE_PRIVATE_MESSAGE",[g,a],function(e){if(e)return d.handle(i,[e.message||e])}),i}n("NO_CHANGE")}else n("ANON_RPC_NOT_READY")}else n("NOT_READY")};O.init=function(n,t){var r=e.once(e.mkAsync(t));if(b.internal.initialized)r("ALREADY_INITIALIZED");else if(s(n)){var o=e.clone(n);o.role="OWNER";var a={};a[m]=o,F(["CHECKPOINT",{members:a}],r)}else r("INVALID_ARGUMENTS")},O.checkpoint=function(n){var t=e.once(e.mkAsync(n));F(["CHECKPOINT",e.clone(b.state)],t)},O.add=function(n,t){var r=e.once(e.mkAsync(t));if(!b.internal.initialized)return r("UNINITIALIZED");if(s(n)){var o=e.clone(n);Object.keys(o).forEach(function(e){if(!l(e)||s(b.state.members[e]))return delete o[e]}),F(["ADD",o],r)}else r("INVALID_ARGUMENTS")},O.remove=function(n,t){var r=e.once(e.mkAsync(t)),o=b.state;if(!o)return r("UNINITIALIZED");if(Array.isArray(n)){var a=e.clone(n),i=[],s=Object.keys(o.members);a.forEach(function(e){-1!==s.indexOf(e)&&i.push(e)}),F(["RM",i],r)}else r("INVALID_ARGUMENTS")},O.describe=function(n,t){var r=e.once(e.mkAsync(t)),o=b.state;if(!o)return r("UNINITIALIZED");if(s(n)){var a=e.clone(n);Object.keys(a).some(function(e){var n=a[e];if(s(n)||delete a[e],!s(o.members[e]))return!0;Object.keys(n).forEach(function(t){n[t]===o.members[e][t]&&delete n[t]})})?r("INVALID_ARGUMENTS"):F(["DESCRIBE",a],r)}else r("INVALID_ARGUMENTS")},O.metadata=function(n,t){var r=e.once(e.mkAsync(t)),o=b.state.metadata;if(s(n)){var a=e.clone(n);Object.keys(a).forEach(function(e){a[e]===o[e]&&delete a[e]}),F(["METADATA",a],r)}else r("INVALID_ARGUMENTS")},O.invite=function(n,t){var r=e.once(e.mkAsync(t));if(!b.state)return r("UNINITIALIZED");if(!b.internal.initialized)return r("UNINITIALIZED");if(s(n)){var o=e.clone(n);Object.keys(o).forEach(function(e){if(!l(e)||s(b.state.members[e]))return delete o[e]}),F(["INVITE",o],r)}else r("INVALID_ARGUMENTS")},O.accept=function(n,t){var r=e.once(e.mkAsync(t));"string"==typeof n&&l(n)?F(["ACCEPT",n],r):r("INVALID_ARGUMENTS")},o(function(e){h.anon_rpc&&h.anon_rpc.send("GET_METADATA",g,function(n,t){if(n)return e.abort(),void console.error(n);_=b.internal.metadata=t&&t[0]||void 0})}).nThen(function(e){if(!n.keys.teamEdPublic&&_&&_.validateKey&&(n.keys.teamEdPublic=_.validateKey),!n.keys.teamEdPublic)return e.abort(),void f("NO_VALIDATE_KEY");try{T=a.Team.createEncryptor(n.keys)}catch(n){return e.abort(),void f(n)}}).nThen(function(){"string"==typeof E&&console.log("Synchronizing from checkpoint"),b.internal.cpNetflux=t.start({lastKnownHash:E,network:n.network,channel:n.channel,crypto:T,validateKey:n.keys.teamEdPublic,owners:n.owners,Cache:n.Cache,isCacheCheckpoint:M,onCacheReady:N,onChannelError:x,onReady:I,onConnect:R,onConnectionChange:C,onMessage:k,noChainPad:!0})})}else f("EXPECTED_STORE");else f("EXPECTED_CRYPTO_KEYS");else f("EXPECTED_CHANNEL");else f("EXPECTED_NETWORK")},i}(Z(),te(),D(),bn(),qe(),M()),At}function jt(){if(St)return Tt;St=1;return Tt=((e,n,t,r,o,a,i,s,c,u,f,l,d,h,p,v,y,m,g,E)=>{const b={};E=E||"undefined"!=typeof window&&window.nacl;var O=e.mkEvent(!0),A=function(){},w=function(e,t,r,o){t&&(o||(r.on("change",["drive",a.SHARED_FOLDERS],function(o,s,c){if(c.length>3&&"password"===c[3]){var u=c[2],f=r.drive[a.SHARED_FOLDERS][u],l=t.manager.user.userObject.getHref?t.manager.user.userObject.getHref(f):f.href,d=n.parsePadUrl(l),h=n.getSecrets(d.type,d.hash,o);return setTimeout(function(){i.updatePassword(e.Store,{oldChannel:h.channel,password:s,href:l},e.store.network,function(){console.log("Shared folder password changed")})}),!1}}),r.on("disconnect",function(){t.offline=!0,t.sendEvent("NETWORK_DISCONNECT",t.id)}),r.on("reconnect",function(){t.offline=!1,t.sendEvent("NETWORK_RECONNECT",t.id)})),r.on("change",[],function(n,r,i){if(o){if(i[0]===a.FILES_DATA&&"object"==typeof r&&r.channel&&!r.owners){var s=[r.channel];r.rtChannel&&s.push(r.rtChannel),r.lastVersion&&s.push(r.lastVersion),t.pin(s,function(e){e&&e.error&&console.error(e.error)})}if(i[0]===a.FILES_DATA&&"object"==typeof n&&n.channel&&!r){var c=[n.channel];t.manager.findChannel(n.channel).some(function(e){return e.fId!==o})||(n.rtChannel&&c.push(n.rtChannel),n.lastVersion&&c.push(n.lastVersion),t.unpin(c,function(e){e&&e.error&&console.error(e)}))}}n&&!r&&Array.isArray(i)&&(i[0]===a.FILES_DATA||"drive"===i[0]&&i[1]===a.FILES_DATA)&&setTimeout(function(){e.Store.checkDeletedPad(n&&n.channel)}),t.sendEvent("DRIVE_CHANGE",{id:o,old:n,new:r,path:i})}),r.on("remove",[],function(e,n){t.sendEvent("DRIVE_REMOVE",{id:o,old:e,path:n})}))},D=function(e,n){var t=e.teams[n];if(t){try{t.listmap.stop()}catch(e){}try{t.roster.stop()}catch(e){}t.proxy={},t.stopped=!0,delete e.teams[n],delete e.cache[n],delete e.store.proxy.teams[n],e.emit("LEAVE_TEAM",n,t.clients),e.updateMetadata(),e.store.calendar&&e.store.calendar.closeTeam(n),e.store.mailbox&&e.store.mailbox.close("team-"+n,function(){})}},_=function(e,n,t,r){n.rpc?r():t.edPrivate&&t.edPublic?h.create(e.store.network,t,function(e,t){e?r(e):(n.rpc=t,n&&n.onRpcReadyEvt&&n.onRpcReadyEvt.fire(),r())},d):r("EFORBIDDEN")},T=function(t,r,a,s,c,u,f){var l=e.once(e.mkAsync(f));if(t.cache[r])l();else{var d=a.proxy,h={id:r,proxy:d,listmap:a,clients:[],realtime:a.realtime,handleSharedFolder:function(e,n){!function(e,n,t,r){var o=e.teams[n];o&&(r?(o.sharedFolders[t]=r,w(e,o,r.proxy,t)):delete o.sharedFolders[t])}(t,r,e,n)},sharedFolders:{},roster:s,onRpcReadyEvt:e.mkEvent(!0),offline:!0};t.cache[r]=h,u&&h.clients.push(u),s.on("change",function(){var n=s.getState(),o=e.find(t,["store","proxy","curvePublic"]);if(n.members&&Object.keys(n.members).length)if(n.members[o]){var a=e.find(t,["store","proxy","teams",r]);a&&(a.metadata=n.metadata),t.updateMetadata(),t.emit("ROSTER_CHANGE",r,h.clients)}else D(t,r);else console.error(JSON.stringify(n))}),s.on("checkpoint",function(n){e.find(t,["store","proxy","teams",r,"keys","roster"]).lastKnownHash=n}),h.sendEvent=function(e,n,r){t.emit(e,n,h.clients.filter(function(e){return e!==r}))},h.getChatData=function(){var e=c.chat||{},t=e.edit||e.view;if(!t)return{};var o=n.getSecrets("chat",t);return{teamId:r,channel:o.channel,secret:o,validateKey:e.validateKey}},h.pin=function(e,n){c.drive.edPrivate?h.rpc?("function"!=typeof n&&console.error("expected a callback"),h.rpc.pin(e,function(e,t){n(e?{error:e}:{hash:t})})):n({error:"TEAM_RPC_NOT_READY"}):n({error:"EFORBIDDEN"})},h.unpin=function(e,n){c.drive.edPrivate?h.rpc?("function"!=typeof n&&console.error("expected a callback"),h.rpc.unpin(e,function(e,t){n(e?{error:e}:{hash:t})})):n({error:"TEAM_RPC_NOT_READY"}):n({error:"EFORBIDDEN"})};var p=t.store.proxy.teams[h.id],v=p.hash||p.roHash,y=n.getSecrets("team",v,p.password),m=h.manager=o.create(d.drive,{onSync:function(e){t.Store.onSync(r,e)},edPublic:c.drive.edPublic,pin:h.pin,unpin:h.unpin,loadSharedFolder:function(e,n,r,o){i.load({isNew:o,network:t.store.network||t.store.networkPromise,store:h,isNewChannel:t.Store.isNewChannel,Store:t.Store},e,n,r)},settings:{drive:e.find(t.store,["proxy","settings","drive"])},removeOwnedChannel:function(e,n){var o;"object"==typeof e?(e.teamId=r,o=e):o={channel:e,teamId:r},t.Store.pad.destroy("",o,n)},Store:t.Store,store:t.store},{teamId:h.id,outer:!0,edPublic:c.drive.edPublic,loggedIn:!0,log:function(e){h.sendEvent("DRIVE_LOG",e)},rt:h.realtime,editKey:y.keys.secondaryKey,readOnly:Boolean(!y.keys.secondaryKey)});h.secondaryKey=y&&y.keys.secondaryKey,h.userObject=m.user.userObject,g(function(e){t.teams[r]=h,w(t,h,d);var n=t.store.network||t.store.networkPromise;i.loadSharedFolders(t.Store,n,h,h.proxy.drive,h.userObject,e,function(e){t.progress+=70/(t.numberOfTeams*e.max),t.updateProgress({progress:t.progress})},!0)}).nThen(function(){t.store.modules.calendar&&t.store.modules.calendar.openTeam(r),l()})}},S=function(t,r,o,a,s,c,u){var f,l=a.getState(),d=e.find(t,["store","proxy","teams",r]);d&&(d.metadata=l.metadata),delete t.nocache[r],t.store.proxy.teams[r]&&g(function(e){T(t,r,o,a,s,c,e()),f=t.teams[r]||t.cache[r],s.drive.edPrivate&&_(t,f,s.drive,e(function(){}))}).nThen(function(e){f.userObject.fixFiles(),i.checkMigration(f.secondaryKey,f.proxy?.drive,f.userObject,e()),i.loadSharedFolders(t.Store,t.store.network,f,f.proxy?.drive,f.userObject,e,function(e){t.progress+=70/(t.numberOfTeams*e.max),t.updateProgress({progress:t.progress})})}).nThen(function(){if(f.rpc){var o=function(n,t){var r=n.teams[t];if(!r)return null;var o=r.manager.getChannelsList("pin"),a=n.store.proxy.teams[t];o.push(`${a.channel}#drive`);var i=e.find(a,["keys","chat","channel"]),s=e.find(a,["keys","roster","channel"]),c=e.find(a,["keys","mailbox","channel"]);if(i&&o.push(i),s&&o.push(s),c&&o.push(c),r.proxy.calendars){var u=Object.keys(r.proxy.calendars).map(function(e){return r.proxy.calendars[e].channel});o=o.concat(u)}var f=r.roster.getState();return f.members&&Object.keys(f.members).forEach(function(e){var n=f.members[e];n.inviteChannel&&n.pending&&o.push(n.inviteChannel),n.previewChannel&&n.pending&&o.push(n.previewChannel)}),o.sort(),o}(t,r),a=n.hashChannelList(o);f.rpc.getServerHash(function(e,n){e?console.warn(e):n!==a&&f.rpc.reset(o,function(e){e&&console.warn(e)})})}}).nThen(function(){f.offline=!1,t.onReadyHandlers[r]&&t.onReadyHandlers[r].forEach(function(e){("function"==typeof e.cb&&e.cb(),e.cId)&&(-1===f.clients.indexOf(e.cId)&&f.clients.push(e.cId))}),delete t.onReadyHandlers[r],t.store.modules.calendar&&t.store.modules.calendar.openTeam(r),u()})},N=function(e,n,t,r,o,a){var i=function(){(e.cache[n]||e.teams[n])&&D(e,n),delete e.store.proxy.teams[n],delete e.onReadyHandlers[n],o.abort(),a({error:"ENOENT"})};t&&e.store.anon_rpc.send("IS_NEW_CHANNEL",t,o(function(e,n){n&&n.length&&"object"==typeof n[0]&&n[0].isNew&&i()})),r&&e.store.anon_rpc.send("IS_NEW_CHANNEL",r,o(function(e,n){n&&n.length&&"object"==typeof n[0]&&n[0].isNew&&i()}))},I=function(t,r,o,a,i){var f=e.once(e.mkAsync(a)),l=r.hash||r.roHash,h=n.getSecrets("team",l,r.password),y=v.createEncryptor(h.keys);r.roHash||(r.roHash=n.getViewHashFromKeys(h));var E,b,A=r.keys;if(!A.chat.validateKey&&A.chat.edit){var w=n.getSecrets("chat",A.chat.edit);A.chat.validateKey=w.keys.validateKey}var _={curvePublic:t.store.proxy.curvePublic,curvePrivate:t.store.proxy.curvePrivate},I=A.roster||{},x=I.edit?v.Team.deriveMemberKeys(I.edit,_):v.Team.deriveGuestKeys(I.view||"");g(function(e){if(i)return d.getChannelCache(h.channel,e(function(n,t){t&&t.c||(e.abort(),f({error:"NOCACHE"}))})),void d.getChannelCache(x.channel,e(function(n,t){var r=t&&t.c,o=t&&t.k;o&&!x.teamEdPublic&&(x.teamEdPublic=o),r||(e.abort(),f({error:"NOCACHE"}))}));t.Store.onReadyEvt.reg(()=>{N(t,o,h.channel,x.channel,e,f)})}).nThen(function(n){var a={lm:!1,roster:!1,check:function(){this.lm&&this.roster&&i&&(t.progress+=30/t.numberOfTeams,t.updateProgress({progress:t.progress}),T(t,o,b,E,A,null,n(f)),this.check=function(){})}},u={data:{},readOnly:!Boolean(h.keys.signKey),network:t.store.network||t.store.networkPromise,channel:h.channel,crypto:y,ChainPad:m,Cache:d,metadata:{validateKey:h.keys.validateKey||void 0},userName:"team",classic:!0,onMetadataUpdate:function(){var e=t.teams[o];e&&t.emit("ROSTER_CHANGE",o,e.clients)}};(b=p.create(u)).proxy.on("cacheready",function(){a.lm=!0,a.check()}),b.proxy.on("ready",n()),b.proxy.on("error",function(e){e&&void 0!==e.loaded&&!e.loaded&&f({error:"ECONNECT"}),e&&e.error&&"EDELETED"===e.error&&D(t,o)}),s.create({network:t.store.network||t.store.networkPromise,channel:x.channel,keys:x,store:t.store,lastKnownHash:I.lastKnownHash,onCacheReady:function(e){if(i){if(e&&"CORRUPTED"===e.error)return console.error("Corrupted roster cache, cant load this team offline",r),b&&"function"==typeof b.stop&&b.stop(),n.abort(),void f({error:"CACHE_CORRUPTED_ROSTER"});E=e,a.roster=!0,a.check()}},Cache:d},n(function(r,o){if(r)return n.abort(),console.error(r),void f({error:"ROSTER_ERROR"});E=o,I.lastKnownHash=E.getLastCheckpointHash();var a=E.getState(),i=e.find(t,["store","proxy","curvePublic"]);a.members[i]&&O.reg(function(){if(I.edit){var e={},n=c.createData(t.store.proxy,!1);n.pending=!1,e[t.store.proxy.curvePublic]=n,E.describe(e,function(e){e&&"NO_CHANGE"!==e&&console.error(e)})}})}))}).nThen(function(n){var a=E.getState(),i=e.find(t,["store","proxy","curvePublic"]);if(!a.members||!Object.keys(a.members).length)return b.stop(),E.stop(),b.proxy={},f({error:"EINVAL"}),n.abort(),console.error(JSON.stringify(a)),void u.send("ROSTER_CORRUPTED");if(!a.members[i])return b.stop(),E.stop(),b.proxy={},delete t.store.proxy.teams[o],t.updateMetadata(),f({error:"EFORBIDDEN"}),void n.abort();var s=a.members[i],c=e.find(r,["keys","drive","edPrivate"]);if(r.hash&&c||-1===["ADMIN","MEMBER"].indexOf(s.role))r.hash&&c||"OWNER"!==s.role||u.send("TEAM_RIGHTS_OWNER");else{console.warn("Missing edit rights: demote to viewer");var l={};l[t.store.proxy.curvePublic]={role:"VIEWER"},E.describe(l,function(e){u.send("TEAM_RIGHTS_FIXED"),delete r.hash,delete r.keys.drive.edPrivate,delete r.keys.chat.edit,e&&"NO_CHANGE"!==e&&console.error(e)})}}).nThen(function(){i||(t.progress+=30/t.numberOfTeams,t.updateProgress({progress:t.progress})),S(t,o,b,E,A,null,f)})},x=function(n,t,r,o){var a=t.team;if(!((a.hash||a.roHash)&&a.channel&&a.password&&a.keys&&a.metadata))return void o({error:"EINVAL"});let i=n.store.proxy.teams;if(Object.values(i).some(e=>e.channel===a.channel))o({error:"EEXISTS"});else{var s=e.createRandomInteger();n.store.proxy.teams[s]=a,n.onReadyHandlers[s]=[],I(n,a,s,function(e){e&&e.error||console.debug("Team joined:"+s);var t=n.store.proxy.teams[s];n.store.mailbox.open("team-"+s,t.keys.mailbox,function(){},!0,{owners:t.keys.drive.edPublic}),n.updateMetadata(),o(e)})}},C=function(n,t,r){var o=e.find(n,["store","proxy","teams",t]);if(!o)return{};var a=e.clone(o);return r||(delete a.hash,delete a.keys.drive.edPrivate,delete a.keys.chat.edit),delete a.owner,a},R=function(t,r,o){if(!r)return!0;var a=e.find(t,["store","proxy","teams",r]);if(!a)return!0;var s=t.teams[r];if(!s)return!0;var c=n.getSecrets("team",o||a.roHash,a.password);if(i.upgrade(a.channel,c),s.userObject&&s.userObject.setReadOnly(!c.keys.secondaryKey,c.keys.secondaryKey),c.keys.secondaryKey)try{t.store.modules.calendar.upgradeTeam(r)}catch(e){console.error(e)}!c.keys.secondaryKey&&s.rpc&&s.rpc.destroy();var u=e.find(s,["proxy","drive","sharedFolders"]);Object.keys(u||{}).forEach(function(t){var r=s.manager.getSharedFolderData(t),o=n.parsePadUrl(r.href||r.roHref),a=n.getSecrets(o.type,o.hash,r.password);i.upgrade(a.channel,a);var c=e.find(s,["manager","folders",t,"userObject"]);c&&c.setReadOnly(!a.keys.secondaryKey,a.keys.secondaryKey)}),t.updateMetadata(),t.emit("ROSTER_CHANGE_RIGHTS",r,s.clients)},P=function(t,r,o,a,i){if(r){var s=e.find(t,["store","proxy","teams",r]);if(s){var c=t.onReadyHandlers[r],u=t.teams[r];if(s.channel===a.channel&&s.password===a.password)if(o?(s.hash=a.hash,s.keys.drive.edPrivate=a.keys.drive.edPrivate,s.keys.chat.edit=a.keys.chat.edit):(delete s.hash,delete s.keys.drive.edPrivate,delete s.keys.chat.edit),u||!Array.isArray(c))if(u){if(o){_(t,u,s.keys.drive,function(){u.manager.addPin(u.pin,u.unpin)});var f=n.getSecrets("team",a.hash,s.password);u.secondaryKey=f&&f.keys.secondaryKey;var l=v.createEncryptor(f.keys);u.listmap.setReadOnly(!1,l)}else delete u.secondaryKey,u.rpc&&u.rpc.destroy&&u.rpc.destroy(),u.manager.removePin(),u.listmap.setReadOnly(!0);R(t,r,a.hash),i(!0)}else i(!1);else c.push({cb:function(){P(t,r,o,a,i)}});else i(!1)}else i(!1)}else i(!1)},k=function(n,t,r,o,a){t?e.find(n,["store","proxy","teams",t])&&n.teams[t]?n.store.mailbox.sendTo("TEAM_EDIT_RIGHTS",{state:o,teamData:C(n,t,o)},{channel:r.notifications,curvePublic:r.curvePublic},a):a({error:"ENOENT"}):a({error:"EINVAL"})},M=function(n,t,r,o){var a=t.teamId;if(a){var i=e.find(n,["store","proxy","teams",a]),s=n.teams[a];if(i&&s)if(s.roster)if(t.curvePublic&&t.data){var c,u=s.roster.getState().members[t.curvePublic];g(function(e){n.Store.pad.getMetadata(null,{channel:i.channel},e(function(e){c=e&&e.error?s.listmap.metadata||{}:e}))}).nThen(function(){if(u.pendingOwner=Array.isArray(c.pending_owners)&&-1!==c.pending_owners.indexOf(u.edPublic),"OWNER"!==u.role||"OWNER"===t.data.role){"VIEWER"===u.role&&"VIEWER"!==t.data.role&&k(n,a,u,!0,function(e){o(e)}),"VIEWER"!==u.role&&"VIEWER"===t.data.role&&k(n,a,u,!1,function(e){o(e)});var r={};r[t.curvePublic]=t.data,s.roster.describe(r,function(e){e?o({error:e}):o()})}else!function(n,t,r,o){var a=e.once(o);if(t){var i=e.find(n,["store","proxy","teams",t]);if(i){var s=n.teams[t];if(s){var c=r.pendingOwner;g(function(t){var o=c?"RM_PENDING_OWNERS":"RM_OWNERS",s=function(e){var n=e&&e.error;if(n)return console.error(n),t.abort(),void a(n)},u=function(e){n.Store.pad.setMetadata(null,{channel:e,command:o,value:[r.edPublic]},t(s))};u(i.channel),u(e.find(i,["keys","roster","channel"])),u(e.find(i,["keys","chat","channel"]))}).nThen(function(e){var n={};n[r.curvePublic]={role:"ADMIN",pendingOwner:!1},s.roster.describe(n,e(function(e){e&&console.error(e)}))}).nThen(function(e){n.store.mailbox.sendTo("RM_OWNER",{teamChannel:i.channel,title:i.metadata.name,pending:c},{channel:r.notifications,curvePublic:r.curvePublic},e())}).nThen(function(){a()})}else a({error:"ENOENT"})}else a({error:"ENOENT"})}else a({error:"EINVAL"})}(n,a,u,function(e){e?(console.error(e),o({error:e})):o()})})}else o({error:"MISSING_DATA"});else o({error:"NO_ROSTER"});else o({error:"ENOENT"})}else o({error:"EINVAL"})},F=function(e,n){Object.keys(e.onReadyHandlers).forEach(function(t){var r=-1;e.onReadyHandlers[t].some(function(e,t){if(e.cId===n)return r=t,!0}),-1!==r&&e.onReadyHandlers[t].splice(r,1)}),Object.keys(e.teams).forEach(function(t){var r=e.teams[t].clients,o=r.indexOf(n);-1!==o&&r.splice(o,1)})},L=function(n,t,r,o){var a,i=t.seeds;try{a=f.derivePreviewKeys(i.preview)}catch(e){return void o({error:"INVALID_SEEDS"})}l.get({channel:a.channel,type:"pad",version:2,keys:{cryptKey:a.cryptKey}},function(n,t){if(n)o({error:n});else if(t){var r=e.tryParse(t);o(r||{error:"parseError"})}else o({error:"DELETED"})},{network:n.store.network,initialState:"{}"})},H=function(n,t,r,o){var a,i;g(function(r){!function(n,t,r,o){var a,i=t.bytes64;try{a=f.deriveInviteKeys(i)}catch(e){return void o({error:"INVALID_SEEDS"})}l.get({channel:a.channel,type:"pad",version:2,keys:{cryptKey:a.cryptKey}},function(n,t){if(n)o({error:n});else if(t){var r=e.tryParse(t);o(r||{error:"parseError"})}else o({error:"DELETED"})},{network:n.store.network,initialState:"{}"})}(n,t,0,r(function(e){if(e&&e.error)return r.abort(),void o(e);a=e}))}).nThen(function(t){var r=e.find(a,["teamData","channel"]),u=n.store.proxy.teams||{};if(Object.keys(u).some(function(e){return u[e].channel===r}))return t.abort(),void o({error:"ALREADY_MEMBER"});var f=e.find(a,["teamData","keys","roster"]),l=a.ephemeral;if(!f||!l)return t.abort(),void o({error:"INVALID_INVITE_CONTENT"});var h=v.Team.deriveMemberKeys(f.edit,l);s.create({network:n.store.network||n.store.networkPromise,channel:f.channel,keys:h,store:n.store,Cache:d},t(function(e,r){if(e)return t.abort(),console.error(e),void o({error:"ROSTER_ERROR"});var a=c.createData(n.store.proxy,!1),s=r.getState();i=s.members[l.curvePublic],r.accept(a.curvePublic,t(function(e){if(r.stop(),e)return t.abort(),console.error(e),void o({error:"ACCEPT_ERROR"})}))}))}).nThen(function(){var e={};i.remaining&&1!==i.remaining||_(n,e,a.ephemeral,function(n){if(!n){var t=e.rpc;i.inviteChannel&&t.removeOwnedChannel(i.inviteChannel,function(e){e&&console.error(e)}),i.previewChannel&&t.removeOwnedChannel(i.previewChannel,function(e){e&&console.error(e)})}}),x(n,{team:a.teamData},0,o)})},j=function(n){if(n){if(n.keys&&n.keys.mailbox)return n.keys.mailbox;var t=e.find(n,["keys","roster","edit"]);if(t){var r=E.hash(e.decodeUTF8(t)),o=r.slice(0,32),a=e.uint8ArrayToHex(r.slice(32,48)),i=E.box.keyPair.fromSecretKey(o);return{channel:a,viewed:[],keys:{curvePrivate:e.encodeBase64(i.secretKey),curvePublic:e.encodeBase64(i.publicKey)}}}}};return b.init=function(t,r,o){var a={},i=t.store;if(i.loggedIn&&i.proxy.edPublic&&!i.modules?.team){var h={store:i,Store:t.Store,pinPads:t.pinPads,emit:o,onReadyHandlers:{},teams:{},cache:{},nocache:{},updateMetadata:t.updateMetadata,updateProgress:t.updateLoadingProgress,progress:0};i.proxy.teams||(i.proxy.teams={});var b=i.proxy.teams;h.numberOfTeams=Object.keys(b).length,h.store.proxy.on("change",["teams"],function(e,n,t){"hash"===t[2]&&R(h,t[1],n)}),h.store.proxy.on("remove",["teams"],function(e,n){"hash"===n[2]&&R(h,n[1])});var w=function(n,t){if(!n||!t)return!0;try{var r=e.decodeBase64(n),o=E.sign.keyPair.fromSecretKey(r);return e.encodeBase64(o.publicKey)===t}catch(e){return!1}};Object.keys(b).forEach(function(n){h.onReadyHandlers[n]=[],e.find(b,[n,"keys","mailbox"])||(b[n].keys.mailbox=j(b[n])),I(h,b[n],n,r(function(e){if(e){delete h.onReadyHandlers[n],delete h.cache[n],"NOCACHE"===e?.error&&(h.nocache[n]=!0);var t="string"==typeof e?e:e.type||e.message;return u.send("TEAM_LOADING_ERROR="+t),void console.error(e)}console.debug("Team "+n+" cache ready")}),d.isEnabled())}),a.onReady=function(t){var r;r={},Object.keys(b).forEach(function(t){try{var o=b[t],a=r[o.channel],i=e.find(o,["keys","drive","edPrivate"]),s=e.find(o,["keys","drive","edPublic"]);if(s?i&&s&&!w(i,s)&&(u.send("TEAM_CORRUPTED_EDPRIVATE"),delete b[t].keys.drive.edPrivate,i=void 0):u.send("TEAM_CORRUPTED_EDPUBLIC"),o.hash&&2===n.parseTypeHash("drive",o.hash).version&&40!==o.hash.length&&u.send("TEAM_CORRUPTED_HASH"),!a)return void(r[o.channel]=t);var c=b[a],f=e.find(c,["keys","drive","edPrivate"]),l=e.find(c,["keys","chat","edit"]),d=e.find(o,["keys","chat","edit"]);!c.hash&&o.hash&&(c.hash=o.hash),!f&&i&&(c.keys.drive.edPrivate=i),!l&&d&&(c.keys.chat.edit=d),h.store.proxy.duplicateTeams=h.store.proxy.duplicateTeams||{},h.store.proxy.duplicateTeams[t]=b[t],delete b[t]}catch(e){console.error(e)}});var o=function(e){return!b[e]&&(D(h,e),delete h.onReadyHandlers[e],!0)};Object.keys(h.teams).forEach(o),Object.keys(h.onReadyHandlers).forEach(function(n){if(!o(n)){var r=h.store.proxy.teams[n],a=e.find(r,["keys","roster","channel"]),i=e.once(e.mkAsync(t()));g(function(e){N(h,n,r.channel,a,e,i)}),h.onReadyHandlers[n].push({cb:i})}}),Object.keys(b).forEach(function(n){h.onReadyHandlers[n]||h.teams[n]||(h.onReadyHandlers[n]=[],e.find(b,[n,"keys","mailbox"])||(b[n].keys.mailbox=j(b[n])),I(h,b[n],n,t(function(e){if(e){var t="string"==typeof e?e:e.type||e.message;return u.send("TEAM_LOADING_ERROR="+t),void console.error(e)}console.debug("Team "+n+" ready")})))}),A(),O.fire()},a.getTeam=function(e){return h.teams[e]},a.getTeamsData=function(n){var t={},r=!1;return-1!==["drive","teams","settings"].indexOf(n)&&(r=!0),Object.keys(b).forEach(function(n){if(h.teams[n]){var o=h.teams[n].proxy||{},a=o.drive&&Object.keys(o.drive.filesData||{}).length,i=o.drive&&Object.keys(o.drive.sharedFolders||{}).length;t[n]={owner:b[n].owner,name:b[n].metadata.name,channel:b[n].channel,numberPads:a,numberSf:i,roster:e.find(b[n],["keys","roster","channel"]),edPublic:e.find(b[n],["keys","drive","edPublic"]),avatar:e.find(b[n],["metadata","avatar"]),viewer:!e.find(b[n],["keys","drive","edPrivate"]),notifications:e.find(b[n],["keys","mailbox","channel"]),curvePublic:e.find(b[n],["keys","mailbox","keys","curvePublic"]),validKeys:w(e.find(b[n],["keys","drive","edPrivate"]),e.find(b[n],["keys","drive","edPublic"]))},r&&h.teams[n]&&(t[n].secondaryKey=h.teams[n].secondaryKey),h.teams[n]&&(t[n].hasSecondaryKey=Boolean(h.teams[n].secondaryKey))}}),t},a.getTeams=function(){return Object.keys(h.teams)};a.removeFromTeam=function(e,n,t){if(b[e]&&(!t||function(e,n){var t=h.teams[e];if(t){var r=t.roster&&t.roster.getState();if(r.members)return(r.members[n]||{}).pending}}(e,n)))if(h.onReadyHandlers[e])h.onReadyHandlers[e].push({cb:function(){h.teams[e].roster.remove([n],function(e){e&&"NO_CHANGE"!==e&&console.error(e)})}});else{var r=h.teams[e];r?r.roster.remove([n],function(e){e&&"NO_CHANGE"!==e&&console.error(e)}):console.error("TEAM MODULE ERROR")}},a.changeMyRights=function(e,n,t,r){P(h,e,n,t,r)},a.updateMyData=function(e){Object.keys(h.teams).forEach(function(n){var t=h.teams[n];if(t.roster){var r={};r[e.curvePublic]=e,t.roster.describe(r,function(e){e&&console.error(e)})}})},a.removeClient=function(e){F(h,e)};return a.execCommand=function(t,r,o){var a=r.cmd,i=r.data;if("SUBSCRIBE"!==a)if("LIST_TEAMS"!==a)if("OPEN_TEAM_CHAT"!==a)if("GET_TEAM_ROSTER"!==a)if("GET_TEAM_METADATA"!==a)if("SET_TEAM_METADATA"!==a){if("OFFER_OWNERSHIP"===a)return h.store.offline?void o({error:"OFFLINE"}):void function(n,t,r,o){var a=e.once(o),i=t.teamId;if(i){var s=e.find(n,["store","proxy","teams",i]);if(s){var c=n.teams[i];if(c)if(c.roster)if(t.curvePublic){var u=c.roster.getState().members[t.curvePublic];g(function(t){var r=function(e){var n=e&&e.error;if(n)return console.error(n),t.abort(),void a({error:n})},o=function(e){n.Store.pad.setMetadata(null,{channel:e,command:"ADD_PENDING_OWNERS",value:[u.edPublic]},t(r))};o(s.channel),o(e.find(s,["keys","roster","channel"])),o(e.find(s,["keys","chat","channel"]))}).nThen(function(e){var n={};n[u.curvePublic]={role:"OWNER"},c.roster.describe(n,e(function(e){e&&console.error(e)}))}).nThen(function(t){n.store.mailbox.sendTo("ADD_OWNER",{teamChannel:s.channel,chatChannel:e.find(s,["keys","chat","channel"]),rosterChannel:e.find(s,["keys","roster","channel"]),title:s.metadata.name},{channel:u.notifications,curvePublic:u.curvePublic},t())}).nThen(function(){a()})}else a({error:"MISSING_DATA"});else a({error:"NO_ROSTER"});else a({error:"ENOENT"})}else a({error:"ENOENT"})}else a({error:"EINVAL"})}(h,i,0,o);if("ANSWER_OWNERSHIP"===a)return h.store.offline?void o({error:"OFFLINE"}):void function(n,t,r,o){var a,i=n.store.proxy.teams;if(Object.keys(i).forEach(function(e){if(i[e].channel===t.teamChannel)return a=e,!0}),a){var s=e.find(n,["store","proxy","teams",a]);if(s){var c=n.teams[a];if(c)if(c.roster){var u={};t.answer?s.owner=!0:(u[n.store.proxy.curvePublic]={role:"ADMIN"},c.roster.describe(u,function(e){e?o({error:e}):o()}))}else o({error:"NO_ROSTER"});else o({error:"ENOENT"})}else o({error:"ENOENT"})}else o({error:"EINVAL"})}(h,i,0,o);if("DESCRIBE_USER"!==a){if("INVITE_TO_TEAM"===a)return h.store.offline?void o({error:"OFFLINE"}):void function(e,n,t,r){var o=n.teamId;if(o){var a=e.teams[o];if(a)if(a.roster){var i=n.user;if(i&&i.curvePublic&&i.notifications){delete i.channel,delete i.lastKnownHash,i.pending=!0;var s={};s[i.curvePublic]=i,s[i.curvePublic].role="VIEWER",a.roster.add(s,function(n){n&&"NO_CHANGE"!==n?r({error:n}):e.store.mailbox.sendTo("INVITE_TO_TEAM",{team:C(e,o)},{channel:i.notifications,curvePublic:i.curvePublic},function(e){r(e)})})}else r({error:"MISSING_DATA"})}else r({error:"NO_ROSTER"});else r({error:"ENOENT"})}else r({error:"EINVAL"})}(h,i,0,o);if("LEAVE_TEAM"!==a){if("JOIN_TEAM"===a)return h.store.offline?void o({error:"OFFLINE"}):void x(h,i,0,o);if("REMOVE_USER"!==a){if("DELETE_TEAM"===a)return h.store.offline?void o({error:"OFFLINE"}):void function(n,t,r,o){var a=t.teamId;if(a){var i=n.teams[a],s=e.find(n,["store","proxy","teams",a]);if(i&&s){var c=i.roster.getState(),f=e.find(n,["store","proxy","curvePublic"]),l=c.members[f];if(!l||"OWNER"!==l.role)return o({error:"EFORBIDDEN"});var d=e.find(n,["store","proxy","edPublic"]),h=e.find(s,["keys","drive","edPublic"]);g(function(e){n.Store.anonRpcMsg(null,{msg:"GET_METADATA",data:s.channel},e(function(n){if(n&&n.error)return e.abort(),o({error:n.error});var t=n[0];t&&Array.isArray(t.owners)&&-1!==t.owners.indexOf(d)||(e.abort(),o({error:"EFORBIDDEN"}))}))}).nThen(function(t){i.proxy.delete=!0;var r=i.manager.getChannelsList("owned"),o=e.Saferphore.create(10);r.forEach(function(e){var r=t();o.take(function(t){var o=!1;g(function(r){32===e.length&&n.Store.anonRpcMsg(null,{msg:"GET_METADATA",data:e},r(function(e){if(e&&e.error)return t(),void r.abort();var n=e[0];if(!n||!Array.isArray(n.owners)||-1===n.owners.indexOf(h))return t(),void r.abort();o=n.owners.some(function(e){return e!==h})}))}).nThen(function(t){o?n.Store.pad.setMetadata(null,{channel:e,command:"RM_OWNERS",value:[h]},t()):i.rpc.removeOwnedChannel(e,t(function(e){e&&console.error(e)}))}).nThen(function(){t(),r()})})})}).nThen(function(t){i.rpc.removePins(t(function(e){e&&console.error(e)}));var r=e.find(s,["keys","mailbox","channel"]);i.rpc.removeOwnedChannel(r,t(function(e){e&&console.error(e)}));var o=e.find(s,["keys","roster","channel"]);n.store.rpc.removeOwnedChannel(o,t(function(e){e&&console.error(e)}));var a=e.find(s,["keys","chat","channel"]);n.store.rpc.removeOwnedChannel(a,t(function(e){e&&console.error(e)})),n.store.rpc.removeOwnedChannel(s.channel,t(function(e){e&&console.error(e)}))}).nThen(function(){u.send("TEAM_DELETION"),D(n,a),o()})}else o({error:"ENOENT"})}else o({error:"EINVAL"})}(h,i,0,o);if("CREATE_TEAM"===a)return h.store.offline?void o({error:"OFFLINE"}):void function(t,r,o,a){var i,f=e.once(a),l=n.createChannelId(),h=n.createRandomHash("team",l),b=n.getSecrets("team",h,l),O=n.getViewHashFromKeys(b),A=E.sign.keyPair(),w=E.box.keyPair(),_=v.Team.createSeed(),T=v.Team.deriveMemberKeys(_,{curvePublic:t.store.proxy.curvePublic,curvePrivate:t.store.proxy.curvePrivate}),N=n.getSecrets("chat"),I=n.getHashes(N),x={network:t.store.network,channel:b.channel,data:{},validateKey:b.keys.validateKey,crypto:v.createEncryptor(b.keys),logLevel:1,classic:!0,ChainPad:m,Cache:d,owners:[t.store.proxy.edPublic]};g(function(e){s.create({network:t.store.network||t.store.networkPromise,channel:T.channel,owners:[t.store.proxy.edPublic],keys:T,store:t.store,lastKnownHash:void 0,newTeam:!0,Cache:d},e(function(n,r){if(n)return e.abort(),console.error(n),void f({error:"ROSTER_ERROR"});i=r;var o=c.createData(t.store.proxy);delete o.channel,i.init(o,e(function(n){if(n)return e.abort(),void f({error:"ROSTER_INIT_ERROR"})}))}));var n,r=v.createEncryptor(N.keys),o={network:t.store.network,channel:N.channel,noChainPad:!0,crypto:r,metadata:{validateKey:N.keys.validateKey,owners:[t.store.proxy.edPublic]}},a=e();o.onReady=function(){n&&n.stop(),a()},o.onError=function(){e.abort(),f({error:"CHAT_INIT_ERROR"})},n=y.start(o)}).nThen(function(e){i.metadata({name:r.name},e(function(n){if(n)return e.abort(),void f({error:"ROSTER_INIT_ERROR"})}))}).nThen(function(){var a=e.createRandomInteger();x.onMetadataUpdate=function(){var e=t.teams[a];e&&t.emit("ROSTER_CHANGE",a,e.clients)};var s=p.create(x),c=s.proxy;c.version=2,c.on("ready",function(){var d={mailbox:{channel:n.createChannelId(),viewed:[],keys:{curvePrivate:e.encodeBase64(w.secretKey),curvePublic:e.encodeBase64(w.publicKey)}},drive:{edPrivate:e.encodeBase64(A.secretKey),edPublic:e.encodeBase64(A.publicKey)},chat:{edit:I.editHash,view:I.viewHash,validateKey:N.keys.validateKey,channel:N.channel},roster:{channel:T.channel,edit:_,view:T.viewKeyStr}},p=t.store.proxy.teams[a]={owner:!0,channel:b.channel,hash:h,roHash:O,password:l,keys:d,metadata:{name:r.name}};c.drive={},S(t,a,s,i,d,o,function(){u.send("TEAM_CREATION"),t.store.mailbox.open("team-"+a,p.keys.mailbox,function(){},!0,{owners:p.keys.drive.edPublic}),t.updateMetadata(),f()})}).on("error",function(e){e&&void 0!==e.loaded&&!e.loaded&&f({error:"ECONNECT"}),e&&e.error&&"EDELETED"===e.error&&D(t,a)})})}(h,i,t,o);if("GET_EDITABLE_FOLDERS"!==a)if("CREATE_INVITE_LINK"!==a){if("GET_PREVIEW_CONTENT"!==a)return"ACCEPT_LINK_INVITATION"===a?h.store.offline?void o({error:"OFFLINE"}):void H(h,i,0,o):void 0;L(h,i,0,o)}else!function(n,t,r,o){var a=e.mkAsync(e.once(o)),i=t.teamId,s=n.teams[t.teamId],u=t.seeds,d=t.bytes64;if(i&&s){var h,p=s.roster;try{h=p.getState().metadata.name}catch(e){return void a({error:"TEAM_NAME_ERR"})}var v=t.message,y=t.name,m=t.hash,E=e.find(n,["store","proxy","teams",i]);try{var b=f.encryptHash(m,E.hash)}catch(e){console.error(e)}var O=f.derivePreviewKeys(u.preview),A=f.deriveInviteKeys(d),w=f.generateKeys(),D=t.role||"VIEWER",_=t.uses||1;g(function(e){!function(){var t=f.generateSignPair(),r={initialState:"{}",network:n.store.network,metadata:{owners:[n.store.proxy.edPublic,w.edPublic]}};r.metadata.validateKey=t.validateKey;var o={teamName:h,message:v,author:c.createData(n.store.proxy,!1),displayName:y},i={channel:O.channel,type:"pad",version:2,keys:{cryptKey:O.cryptKey,validateKey:t.validateKey,signKey:t.signKey}};l.put(i,JSON.stringify(o),e(function(n){if(n)return console.error("CRYPTPUT_ERR",n),e.abort(),void a({error:"SET_PREVIEW_CONTENT"})}),r)}(),function(){var t=f.generateSignPair(),r={initialState:"{}",network:n.store.network,metadata:{owners:[n.store.proxy.edPublic,w.edPublic]}};r.metadata.validateKey=t.validateKey;var o={teamData:C(n,i,"MEMBER"===D),ephemeral:{edPublic:w.edPublic,edPrivate:w.edPrivate,curvePublic:w.curvePublic,curvePrivate:w.curvePrivate}},s={channel:A.channel,type:"pad",version:2,keys:{cryptKey:A.cryptKey,validateKey:t.validateKey,signKey:t.signKey}};l.put(s,JSON.stringify(o),e(function(n){if(n)return console.error("CRYPTPUT_ERR",n),e.abort(),void a({error:"SET_PREVIEW_CONTENT"})}),r)}()}).nThen(function(e){s.pin([A.channel,O.channel],function(e){e&&e.error&&console.error(e.error)}),f.createRosterEntry(s.roster,{curvePublic:w.curvePublic,content:{curvePublic:w.curvePublic,displayName:t.name,pending:!0,remaining:_,totalUses:_,role:D,hash:b,inviteChannel:A.channel,previewChannel:O.channel}},e(function(n){n&&(e.abort(),a(n))}))}).nThen(function(){a()})}else a({error:"EINVAL"})}(h,i,0,o);else!function(n,t,r,o){var a=t.teamId;if(a){var i=n.teams[a];if(i){var s=i.manager.folders||{};o(Object.keys(s).filter(function(e){return!s[e].proxy.version}).map(function(n){var t=e.find(i,["user","userObject"]);return{name:e.find(s,[n,"proxy","metadata","title"]),path:t?t.findFile(n)[0]:[]}}))}else o({error:"ENOENT"})}else o({error:"EINVAL"})}(h,i,0,o)}else!function(e,n,t,r){var o=n.teamId;if(o){var a=e.teams[o];if(a)if(a.roster)if(n.curvePublic){var i=a.roster.getState().members[n.curvePublic];a.roster.remove([n.curvePublic],function(t){if(!t)return i&&i.notifications?void e.store.mailbox.sendTo("KICKED_FROM_TEAM",{pending:n.pending,teamChannel:C(e,o).channel,teamName:C(e,o).metadata.name},{channel:i.notifications,curvePublic:i.curvePublic},function(e){r(e)}):r();r({error:t})})}else r({error:"MISSING_DATA"});else r({error:"NO_ROSTER"});else r({error:"ENOENT"})}else r({error:"EINVAL"})}(h,i,0,o)}else!function(e,n,t,r){var o=n.teamId;if(o){var a=e.teams[o];if(a)if(a.roster){var i=e.store.proxy.curvePublic;a.roster.remove([i],function(n){n?r({error:n}):(D(e,o),r())})}else r({error:"NO_ROSTER"});else r({error:"ENOENT"})}else r({error:"EINVAL"})}(h,i,0,o)}else M(h,i,0,o)}else!function(e,n,t,r){var o=n.teamId;if(o){var a=e.teams[o];a?a.offline?r({error:"OFFLINE"}):a.roster?(n.metadata&&delete n.metadata.offline,a.roster.metadata(n.metadata,function(t){if(t)r({error:t});else{var a=e.store.proxy.teams[o];a&&(a.metadata=n.metadata),r()}})):r({error:"NO_ROSTER"}):r({error:"ENOENT"})}else r({error:"EINVAL"})}(h,i,0,o);else!function(e,n,t,r){var o=n.teamId;if(o){var a=e.teams[o];if(a)if(a.roster){var i=(a.roster.getState()||{}).metadata||{};i.offline=a.offline,r(i)}else r({error:"NO_ROSTER"});else r({error:"ENOENT"})}else r({error:"EINVAL"})}(h,i,0,o);else!function(n,t,r,o){var a=t.teamId;if(a){var i=e.find(n,["store","proxy","teams",a]);if(i){var s=n.teams[a];if(s)if(s.roster){var c,u=(s.roster.getState()||{}).members||{};g(function(e){n.Store.pad.getMetadata(null,{channel:i.channel},e(function(e){c=e&&e.error?s.listmap.metadata||{}:e}))}).nThen(function(){if(n.pending_owners=c.pending_owners,Array.isArray(c.pending_owners)&&c.pending_owners.forEach(function(t){var r;if(Object.keys(u).some(function(e){if(u[e].edPublic===t)return r=u[e],!0}),!r&&i.owner){var o=function(e){n.Store.pad.setMetadata(null,{channel:e,command:"RM_PENDING_OWNERS",value:[t]},function(){})};return o(i.channel),o(e.find(i,["keys","roster","channel"])),void o(e.find(i,["keys","chat","channel"]))}r.pendingOwner=!0}),n.store.messenger){var t=s.getChatData();(n.store.messenger.getOnlineList(t.channel)||[]).forEach(function(e){u[e]&&(u[e].online=!0)})}Object.keys(u).forEach(function(e){var n=u[e];if(n.inviteChannel&&n.hash)if(i.hash)try{n.hash=f.decryptHash(n.hash,i.hash)}catch(e){console.error(e)}else delete n.hash}),o(u)})}else o({error:"NO_ROSTER"});else o({error:"ENOENT"})}else o({error:"ENOENT"})}else o({error:"EINVAL"})}(h,i,0,o);else!function(e,n,t,r){var o=e.teams[n.teamId];if(o){var a=function(){e.emit("ROSTER_CHANGE",n.teamId,o.clients)};e.store.messenger?e.store.messenger.openTeamChat(o.getChatData(),a,t,r):A=function(){e.store.messenger.openTeamChat(o.getChatData(),a,t,r)}}else r({error:"ENOENT"})}(h,i,t,o);else!function(n){var t=e.clone(b);Object.keys(t).forEach(function(e){h.teams[e]?t[e].offline=h.teams[e].offline:(t[e].error=!0,h.nocache[e]&&(t[e].offline=!0))}),n(t)}(o);else!function(e,n,t,r){F(e,t);try{e.store.messenger.removeClient(t)}catch(e){}if(A=function(){},n)if(!e.onReadyHandlers[n]||e.teams[n])if(e.teams[n]){var o=e.teams[n].clients;-1===o.indexOf(t)&&o.push(t),r()}else r({error:"EINVAL"});else-1===e.onReadyHandlers[n].indexOf(t)&&e.onReadyHandlers[n].push({cId:t,cb:r});else r()}(h,i,t,o)},a}},b.anonGetPreviewContent=function(e,n,t){L(e,n,0,t)},b})(Z(),te(),Y(),je(),ze(),Ue(),We(),Ht(),On(),Ae(),(_t||(_t=1,Dt=function(e,n,t,r){var o={},a=e.encodeBase64,i=e.decodeBase64;o.generateKeys=function(){var e=t.sign.keyPair(),n=t.box.keyPair();return{edPublic:a(e.publicKey),edPrivate:a(e.secretKey),curvePublic:a(n.publicKey),curvePrivate:a(n.secretKey)}},o.generateSignPair=function(){var e=t.sign.keyPair();return{validateKey:a(e.publicKey),signKey:a(e.secretKey)}};var s=function(r){var o=n.dispenser(i(r));return{channel:e.uint8ArrayToHex(o(16)),cryptKey:o(t.secretbox.keyLength)}};o.deriveInviteKeys=s,o.derivePreviewKeys=s,o.createRosterEntry=function(e,n,t){var r={};r[n.curvePublic]=n.content,e.invite(r,t)};var c=e.decodeUTF8;return o.encryptHash=function(e,n){var o=c(n),a=t.hash(o).subarray(0,32);return r.encrypt(e,a)},o.decryptHash=function(e,n){var o=c(n),a=t.hash(o).subarray(0,32);return r.decrypt(e,a)},o}(Z(),Ie(),h(),M())),Dt),xn(),fe(),In(),T(),M(),D(),x(),qe(),h()),Tt}function Kt(){if(It)return Nt;It=1;return Nt=((e,n,t,r,o,a,i,s)=>{var c=e.Curve;const u={};let f={};u.setCustomize=e=>{f=e.Messages};var l="MSG",d="UNFRIEND",h="MAP_ID",p="MAP_ID_ACK",v=function(e){return JSON.parse(JSON.stringify(e))},y=function(e){for(var n=Object.keys(e).length,t=new Uint8Array(n),r=0;r{const n=p.store.network||e;n.on("message",function(e,n){I(p,e,n)}),n.on("disconnect",function(){p.emit("DISCONNECT",null,C(p))}),n.on("reconnect",function(){p.emit("RECONNECT",null,C(p))})});return h.networkPromise?.then(b),p.store.network&&b(),u.onFriendUpdate=function(e){var n=g(h.proxy,e);if(n&&n.channel){var t=p.channels[n.channel];t&&p.emit("UPDATE_DATA",{info:v(n),channel:n.channel},t.clients)}},u.onFriendAdded=function(e){if(p.friendsClients.length){var n=g(p.store.proxy,e.curvePublic);if("object"==typeof n)if(n.channel){var t=n.channel;p.channels[t]||P(p,null,n,function(){c("FRIEND",{curvePublic:n.curvePublic},p.friendsClients)})}}},u.onFriendRemoved=function(e,n){x(p,e,n)},u.getOnlineList=function(e){return function(e,n){var t=e.channels[n];if(t){var r=[],o=m(e.store.proxy,!1);return r.push(o.curvePublic),t.wc.members.forEach(function(n){if(n!==e.store.network.historyKeeper){var o=t.mapId[n]||{};o.curvePublic&&-1===r.indexOf(o.curvePublic)&&r.push(o.curvePublic)}}),r}}(p,e)},u.storeValidateKey=function(e,n){p.validateKeys[e]=n},u.leavePad=function(e){delete p.validateKeys[e],Object.keys(p.channels).some(function(n){var t=p.channels[n];if(t.padChan===e){t.wc&&t.wc.leave();var r=p.store.network;return t.onReconnect&&r.off("reconnect",t.onReconnect),t.stopped=!0,delete p.channels[n],!0}})},u.openTeamChat=function(n,r,o,a){!function(n,r,o,a,i){var s=o,c=s.channel,u=s.secret;if(c&&u){var f=t.once(t.mkAsync(function(){n.emit("TEAMCHAT_READY",c,[r]),i({readOnly:"object"==typeof u.keys&&!u.keys.validateKey,channel:c})})),l=n.channels[c];if(l)l.onReady.reg(function(){-1===l.clients.indexOf(r)&&l.clients.push(r),f()});else{u.keys.cryptKey&&(u.keys.cryptKey=y(u.keys.cryptKey));var d=e.createEncryptor(u.keys),h=u.keys&&u.keys.validateKey||s.validateKey,p={teamId:o.teamId,readOnly:"object"==typeof u.keys&&!u.keys.validateKey,encryptor:d,channel:c,isTeamChat:!0,decrypt:function(e){return d.decrypt(e,h)},clients:[r],onUserlistUpdate:a,onReady:f};R(n,p)}}else i({error:"EINVAL"})}(p,o,n,r,a)},u.removeClient=function(e){!function(e,n){var t=e.friendsClients.indexOf(n);-1!==t&&e.friendsClients.splice(t,1),Object.keys(e.channels).forEach(function(t){var r=e.channels[t],o=r.clients,a=o.indexOf(n);if(-1!==a&&o.splice(a,1),0===o.length){r.wc&&r.wc.leave();var i=e.store.network;return r.onReconnect&&i.off("reconnect",r.onReconnect),r.stopped=!0,delete e.channels[t],!0}})}(p,e)},u.execCommand=function(n,r,i){var c=r.cmd,u=r.data;"INIT_FRIENDS"!==c?"GET_ROOMS"!==c?"GET_MUTED_USERS"!==c?"GET_USERLIST"!==c?"OPEN_PAD_CHAT"!==c?"GET_MY_INFO"!==c?"REMOVE_FRIEND"!==c?"CANCEL_FRIEND"!==c?"MUTE_USER"!==c?"UNMUTE_USER"!==c?"GET_STATUS"!==c?"GET_MORE_HISTORY"!==c?"SEND_MESSAGE"!==c?"SET_CHANNEL_HEAD"!==c?"CLEAR_OWNED_CHANNEL"!==c||function(e,n,t){var r=e.channels[n];r?e.store.rpc?e.store.rpc.clearOwnedChannel(n,function(o){t({error:o}),o||(r.messages=[],e.emit("CLEAR_CHANNEL",n,r.clients))}):t({error:"RPC_NOT_READY"}):t({error:"NO_CHANNEL"})}(p,u,i):_(p,u.id,u.sig,i):function(e,n,t,r){var o=e.channels[n];if(o)if(o.readOnly)r({error:"FORBIDDEN"});else if(e.store.network.webChannels.some(function(e){if(e.id===o.wc.id)return!0})){var i=e.store.proxy||{},s=[l,i.curvePublic,+new Date,t];if(!o.isFriendChat){var c=i[a.displayNameKey]||f.anonymous+"#"+(i.uid||e.store.noDriveUid).slice(0,5);s.push(c)}var u=JSON.stringify(s),d=o.encrypt(u);o.wc.bcast(d).then(function(){N(e,o,d),r()},function(e){r({error:e})})}else r({error:"NO_SUCH_CHANNEL"});else r({error:"NO_CHANNEL"})}(p,u.id,u.content,i):function(e,n,r,o,a){if("function"==typeof a)if("string"==typeof r){var i=e.channels[n];if(void 0!==i){var s=t.uid();A(e,s,n,a);var c=["GET_HISTORY_RANGE",i.id,{from:r,count:o,txid:s}],u=e.store.network;u.sendto(u.historyKeeper,JSON.stringify(c)).then(function(){},function(e){console.error(e)})}else console.error("chan is undefined. we're going to have a problem here")}else a([])}(p,u.id,u.sig,u.count,i):function(e,n,t){var r=e.channels[n];if(r){r.onUserlistUpdate&&r.onUserlistUpdate();var o=e.store.proxy||{};t(r.wc.members.some(function(n){if(n!==e.store.network.historyKeeper){var t=r.mapId[n]||void 0;return!!t&&t.curvePublic!==o.curvePublic}}))}else t("NO_SUCH_CHANNEL")}(p,u,i):function(e,n,r){var o=t.once(t.mkAsync(r)),a=e.store.proxy,i=a.mutedUsers=a.mutedUsers||{};delete i[n],e.emit("UPDATE_MUTED",null,C(e)),o(Object.keys(i).length)}(p,u,i):function(e,n,r){var o=t.once(t.mkAsync(r)),a=e.store.proxy,i=a.mutedUsers=a.mutedUsers||{};i[n.curvePublic]||(i[n.curvePublic]=n,e.emit("UPDATE_MUTED",null,C(e))),o()}(p,u,i):function(e,n,r){var o=t.once(r);"function"==typeof o?e.Store.cancelFriendRequest(n,o):console.error("NO_CALLBACK")}(p,u,i):function(e,n,r){var a=t.once(r);if("function"==typeof a){var i=e.store.proxy,s=g(i,n);if(!s)return console.error("friend is not valid"),void a({error:"INVALID_FRIEND"});var c=e.channels[s.channel];if(e.store.mailbox&&s.curvePublic&&s.notifications)o.removeFriend(e.store,n,function(n){n&&n.error?a({error:n.error}):(e.updateMetadata(),a(n))});else if(c)try{var u=[d,i.curvePublic,+new Date],f=JSON.stringify(u),l=c.encrypt(f);c.wc.bcast(l).then(function(){x(e,n,s.channel),S(e,n,function(){a()})},function(t){t?a({error:t}):(x(e,n,s.channel),S(e,n,function(){a()}))})}catch(e){a({error:e})}else a({error:"NO_SUCH_CHANNEL"})}else console.error("NO_CALLBACK")}(p,u,i):function(e,n){var t=e.store.proxy||{};n({curvePublic:t.curvePublic,displayName:t[a.displayNameKey]})}(p,i):function(n,r,o,a){var i=o.channel,s=t.once(t.mkAsync(function(){n.emit("PADCHAT_READY",i,[r]),a()})),c=n.channels[i];if(c)c.onReady.reg(function(){-1===c.clients.indexOf(r)&&c.clients.push(r),s()});else{var u=o.secret;u.keys.cryptKey&&(u.keys.cryptKey=y(u.keys.cryptKey));var f=e.createEncryptor(u.keys),l=u.keys&&u.keys.validateKey||n.validateKeys[u.channel],d={padChan:o.secret&&o.secret.channel,readOnly:"object"==typeof u.keys&&!u.keys.validateKey,encryptor:f,channel:o.channel,isPadChat:!0,decrypt:function(e){return f.decrypt(e,l)},clients:[r],onReady:s};R(n,d)}}(p,n,u,i):function(e,n,t){var r=e.channels[n.id];if(r)if(r.isFriendChat){var o=O(e,n.id);if(!o)return void t({error:"NO_SUCH_FRIEND"});t([o])}else t([]);else t({error:"NO_SUCH_CHANNEL"})}(p,u,i):function(e,n){var t=e.store.proxy;if(!n)return t.mutedUsers||{};n(t.mutedUsers||{})}(p,i):function(e,n,t){var r=e.store.proxy;if(n&&n.curvePublic){var o=n.curvePublic,a=g(r,o);if(!a)return void t({error:"NO_SUCH_FRIEND"});var i=e.channels[a.channel];return i?void t([{id:i.id,isFriendChat:!0,name:a.displayName,lastKnownHash:a.lastKnownHash,curvePublic:a.curvePublic,messages:i.messages}]):void t({error:"NO_SUCH_CHANNEL"})}if(n&&n.padChat){var s=e.channels[n.padChat];return s?void t([{id:s.id,isPadChat:!0,messages:s.messages}]):void t({error:"NO_SUCH_CHANNEL"})}if(n&&n.teamChat){var c=e.channels[n.teamChat];return c?void t([{id:c.id,isTeamChat:!0,messages:c.messages}]):void t({error:"NO_SUCH_CHANNEL"})}var u=Object.keys(e.channels).map(function(n){var t,r,o,a=e.channels[n];if(a.isFriendChat){var i=O(e,n);if(!i)return null;t=i.displayName,r=i.lastKnownHash,o=i.curvePublic}else{if(a.isPadChat)return;if(a.isTeamChat)return}return{id:a.id,isFriendChat:a.isFriendChat,name:t,lastKnownHash:r,curvePublic:o,messages:a.messages}}).filter(function(e){return e});t(u)}(p,u,i):function(e,n,t){var r=E(e.store.proxy);s(function(t){Object.keys(r).forEach(function(o){if("me"!==o){var a=v(r[o]);"object"==typeof a&&a.channel&&P(e,n,a,t())}else delete r.me.channel})}).nThen(function(){-1===e.friendsClients.indexOf(n)&&e.friendsClients.push(n),t()})}(p,n,i)},u},u})(M(),te(),Z(),je(),On(),Y(),on(),qe()),Nt}function Ut(){if(Ct)return xt;Ct=1;return xt=((e,n,t,r)=>{const o={},a={};var i=function(n,t,o,a,i){var s,c=e.once(e.mkAsync(i)),u=function(n,t){if(!t)return e.find(n.store,["proxy","edPublic"]);var r=e.find(n,["store","proxy","teams",t]);return e.find(r,["keys","drive","edPublic"])}(n,a),f=n.Store,l=0,d=0,h=0;r(function(e){f.getFileSize(null,{channel:t},e(function(n){return n&&n.error?(e.abort(),void c(n)):void 0===n.size?(e.abort(),void c({error:"ENOENT"})):void(l=n.size)})),f.getHistory(null,{channel:t,lastKnownHash:o},e(function(n){if(n&&n.error)return e.abort(),void c(n);if(!Array.isArray(n))return e.abort(),void c({error:"EINVAL"});if(n.length){s=n[0].hash;var t=n.map(function(e){return e.msg});d=t.join("\n").length}}),!0),f.pad.getMetadata(null,{channel:t},e(function(n){if((!n||!n.error)&&n&&"object"==typeof n)return h=JSON.stringify(n).length,n&&Array.isArray(n.owners)&&-1!==n.owners.indexOf(u)?void 0:(e.abort(),void c({error:"INSUFFICIENT_PERMISSIONS"}))}))}).nThen(function(){c({size:l-h-d,hash:s})})};return a.GET_HISTORY_SIZE=function(o,a,s,c){if(o.store.loggedIn&&o.store.rpc){var u=a.channels;if(Array.isArray(u)){var f=[];a.account?u=function(r){var o=[],a=e.find(r.store,["proxy","edPublic"]);-1!==(e.find(r.store,["driveMetadata","owners"])||[]).indexOf(a)&&o.push(r.store.driveChannel);var i=r.store.proxy.profile;if(i){var s=i.edit?n.hrefToHexChannelId("/profile/#"+i.edit,null):null;s&&o.push(s)}r.store.proxy.todo&&o.push(n.hrefToHexChannelId("/todo/#"+r.store.proxy.todo,null));var c=r.store.proxy.mailboxes;if(c){var u=Object.keys(c).map(function(e){return{lastKnownHash:c[e].lastKnownHash,channel:c[e].channel}});Array.prototype.push.apply(o,u)}var f=r.store.proxy[t.SHARED_FOLDERS];if(f){var l=Object.keys(f).map(function(e){var n=f[e];if(n&&n.owners&&Array.isArray(n.owners)&&-1!==n.owners.indexOf(a))return n.channel}).filter(Boolean);Array.prototype.push.apply(o,l)}return o}(o):a.team&&(u=function(n,t){let r=e.find(n.store,["proxy","teams",t]);if(!r)return[];let o=[r.channel],a=r.keys.roster;return o.push({channel:a.channel,lastKnownHash:a.lastKnownHash}),o}(o,a.team));var l=0,d=[];r(function(e){u.forEach(function(n){var t,r=n;"object"==typeof n&&n.channel&&(r=n.channel,t=n.lastKnownHash),i(o,r,t,a.teamId,e(function(e){e&&e.error?f.push(e.error):(l+=e.size,e.hash&&d.push({channel:r,hash:e.hash}))}))})}).nThen(function(){c({warning:f.length?f:void 0,channels:d,size:l})})}else c({error:"EINVAL"})}else c({error:"INSUFFICIENT_PERMISSIONS"})},a.TRIM_HISTORY=function(e,n,t,o){if(e.store.loggedIn&&e.store.rpc){var a=n.channels;if(Array.isArray(a)){var i=function(e,n){if(!n)return e.store.rpc;var t=e.store.modules.team;if(t){var r=t.getTeam(n);if(r)return r.rpc}}(e,n.teamId);if(i){var s=[];r(function(e){a.forEach(function(n){i.trimHistory(n,e(function(e){e&&s.push(e)}))})}).nThen(function(){1===a.length&&s.length?o({error:s[0]}):o({warning:s.length?s:void 0})})}else o({error:"ENORPC"})}else o({error:"EINVAL"})}else o({error:"INSUFFICIENT_PERMISSIONS"})},o.init=function(e,n,t){var r={};if(e.store){var o={store:e.store,Store:e.Store,pinPads:e.pinPads,updateMetadata:e.updateMetadata,emit:t};return r.execCommand=function(e,n,t){var r=n.cmd,i=n.data;try{a[r](o,i,e,t)}catch(e){console.error(e)}},r}},o})(Z(),te(),Ue(),qe()),xt}var Bt,Vt={exports:{}};function Yt(){return Bt||(Bt=1,function(e){(()=>{const n=e=>{var n={};const t=globalThis;var r=function(){},o=n.getWeekNo=function(e,n){"number"!=typeof n&&(n=1);var t=new Date(e.getFullYear(),0,1),r=t.getDay()-n;r=r>=0?r:r+7;var o,a=Math.floor((e.getTime()-t.getTime())/864e5)+1;if(r<4){if((o=Math.floor((a+r-1)/7)+1)>52){var i=new Date(e.getFullYear()+1,0,1).getDay()-n;o=(i=i>=0?i:i+7)<4?1:53}}else o=Math.floor((a+r-1)/7);return o},a=function(e){var n=new Date(e.getFullYear(),0,0),t=e-n+60*(n.getTimezoneOffset()-e.getTimezoneOffset())*1e3;return Math.floor(t/864e5)},i=n.DAYORDER=["SU","MO","TU","WE","TH","FR","SA"],s=function(e){var n=Number(e.slice(0,-2)),t=i.indexOf(e.slice(-2));return n?[n,t]:t},c=function(e,n){var t=e.getDay();t>=(n="number"==typeof n?n:1)?e.setDate(e.getDate()-(t-n)):e.setDate(e.getDate()-(7+t-n))},u=function(e){return e.getFullYear()+"-"+(e.getMonth()+1)+"-"+e.getDate()},f={daily:function(e,n){e.setDate(e.getDate()+n)},weekly:function(e,n){e.setDate(e.getDate()+7*n)},monthly:function(e,n){e.setMonth(e.getMonth()+n)},yearly:function(e,n){e.setFullYear(e.getFullYear()+n)}},l={month:function(e,n,t){var r=new Date(n.start),o=(t-(e.getMonth()+1)+12)%12,a=e.getMonth()+o;if(e.setMonth(a),e.setDate(r.getDate()),e.getMonth()===a)return!0},weekno:function(e,n,t,r){var a=r&&r.wkst;"number"!=typeof a&&(a=1);var i=new Date(n.start),s=new Date(e.getFullYear(),11,31),u=o(s,a),f=1===u;1===u&&(u=52);var l=o(e,a);if(!t||t>u)return!1;t<0&&(t=u+t+1);var d=t-l,h=new Date(+e);h.setDate(h.getDate()+7*d),c(h,a);var p="aaaaaaa".split("").map(function(n,t){var r=new Date(+h);if(r.setDate(r.getDate()+t),r.getFullYear()===e.getFullYear())return r.toLocaleDateString()!==i.toLocaleDateString()&&r}).filter(Boolean);return 1===t&&f&&(c(s,a),"aaaaaaa".split("").some(function(n,t){var r=new Date(+s);if(r.setDate(r.getDate()+t),r.toLocaleDateString()!==i.toLocaleDateString())return r.getFullYear()>e.getFullYear()||void p.push(r)})),p.length?p:void 0}};l.yearday=function(e,n,t){var r=e.getFullYear();if(function(e,n){if(!("number"!=typeof n||Math.abs(n)<1||Math.abs(n)>366))return n<0&&(n=a(new Date(e.getFullYear(),11,31))+n+1),e.setMonth(0),e.setDate(n),!0}(e,t)&&e.getFullYear()===r)return!0},l.monthday=function(e,n,t,r){if("number"!=typeof t||Math.abs(t)<1||Math.abs(t)>31)return!1;var o=function(e,n){var t=e.getMonth();n<0&&(n=new Date(e.getFullYear(),e.getMonth()+1,0).getDate()+n+1);return e.setDate(n),e.getMonth()===t};if("monthly"===r.freq)return o(e,t);var a="aaaaaaaaaaaa".split("").map(function(n,r){var a=new Date(e.getFullYear(),r,1);return o(a,t)?a:void 0}).filter(Boolean);return a.length?a:void 0},l.day=function(e,n,t,r){var o,a=s(t);Array.isArray(a)&&(o=a[0],a=a[1]);var i=[];if(![0,1,2,3,4,5,6].includes(a))return!1;var c,u=function(e){if(o){var n=[];"aaaaaaaaaaaa".split("").some(function(t,r){if(void 0===e||r===e){var a,s=i.filter(function(e){return e.getMonth()===r});return a=o<0?s.length+o:o-1,n.push(s[a]),void 0!==e&&r===e}}),i=n.filter(Boolean)}};if("yearly"===r.freq){c=new Date(+e);for(var f=e.getFullYear();c.getDay()!==a;)c.setDate(c.getDate()+1);for(;c.getFullYear()===f;)i.push(new Date(+c)),c.setDate(c.getDate()+7);return u(),i}if("monthly"===r.freq){c=new Date(+e);for(var l=e.getMonth();c.getDay()!==a;)c.setDate(c.getDate()+1);for(;c.getMonth()===l;)i.push(new Date(+c)),c.setDate(c.getDate()+7);return u(l),i}if("weekly"===r.freq)for(;e.getDay()!==a;)e.setDate(e.getDate()+1);return!0};var d={month:function(e,n){return e.filter(function(e){return n.includes(e.getMonth()+1)})},weekno:function(e,n,t){return e.filter(function(e){var r=t&&t.wkst;"number"!=typeof r&&(r=1);var a=new Date(e.getFullYear(),11,31),i=o(a,r);1===i&&(i=52);var s=o(e,r);return n.some(function(e){return e>0?e===s:s===i+e+1})})},yearday:function(e,n){return e.filter(function(e){var t=a(e),r=a(new Date(e.getFullYear(),11,31));return n.some(function(e){return e>0?e===t:t===r+e+1})})},monthday:function(n,t){return n.filter(function(n){var r=e.clone(t);return(r=r.map(function(e){e<0&&(e=new Date(n.getFullYear(),n.getMonth()+1,0).getDate()+e+1);return e})).includes(n.getDate())})},day:function(e,n,t){return e.filter(function(e){var r=e.toLocaleDateString(),o="yearly";return("monthly"===t.freq||"yearly"===t.freq&&t.by&&t.by.month)&&(o="monthly"),n.some(function(n){var t,a=s(n);if(Array.isArray(a)&&(t=a[0],a=a[1]),!t)return e.getDay()===a;var i=new Date(e.getFullYear(),e.getMonth(),1);return"yearly"===o&&i.setMonth(0),l.day(i,{},n,{freq:o}).some(function(e){return e.toLocaleDateString()===r})})})},setpos:function(n,t){var r=n.slice(),o=e.deduplicateString(t.slice().map(function(e){return e>0?e-1:0!==e?r.length+e:void 0}));return n.filter(function(e){var n=r.indexOf(e);return o.includes(n)})}},h=["month","weekno","yearday","monthday","day"],p=["month","monthday","day"];n.getMonthId=function(e){return e.getFullYear()+"-"+e.getMonth()};var v=t.CP_calendar_cache={},y={};n.resetCache=function(){v=t.CP_calendar_cache={},y={}};var m=function(n){if(!n.recUpdate)return[];var t={},r=n.recUpdate.from;return Object.keys(r||{}).forEach(function(e){var n=r[e];n.recurrenceRule&&(t[e]=n.recurrenceRule)}),Object.keys(t).sort(function(e,n){return Number(e)-Number(n)}).map(function(n){var r=e.clone(t[n]);if(f[r.freq]&&!(r.interval&&r.interval<1))return r._start=Number(n),r}).filter(Boolean)};n.getRecurring=function(o,i){t.CP_DEV_MODE&&(r=console.warn);var s=[];return o.forEach(function(t){var o=t.split("-"),g=new Date(o[0],o[1]),E=new Date(+g);E.setMonth(E.getMonth()+1),E.setMilliseconds(-1),r("Compute month",g.toLocaleDateString()),(i||[]).forEach(function(t){var o=new Date(t.start),i=new Date(t.end),b=t,O=t.recurrenceRule;if(O){var A=m(t),w=A.shift();if(!(o>=E)){for(var D=O.until,_=A.slice(),T=w;T&&T._start&&T._startn)){var t;if(n.getFullYear()===e.getFullYear())t=a(n)-a(e);else{var r=new Date(e.getFullYear(),11,31);for(t=a(r)-a(e)+a(n);r.getFullYear()+1=N)){r("Start iteration",i.toLocaleDateString());var m=function(n,t,o){var a=e.clone(t),i=new Date(a.start),s=a.id.split("|")[0],u=o.toLocaleDateString();v[s]=v[s]||{};var y=n.interval||1,m=n.freq,g=[],E=function(e,t){g=d[e](g,t,n)},b=function(e){return function(t){var r=new Date(+o);"yearly"===n.freq?(r.setMonth(0),r.setDate(1)):"monthly"===n.freq?r.setDate(1):"weekly"===n.freq?c(r,n.wkst):n.freq;var s=l[e](r,a,t,n);if(s)if(Array.isArray(s))s=s.filter(function(e){return e.toLocaleDateString()!==i.toLocaleDateString()}),Array.prototype.push.apply(g,s);else{if(r.toLocaleDateString()===i.toLocaleDateString())return;g.push(r)}}},O=e.once(function(){f[m](o,y)}),A=function(){"monthly"===m?o.setDate(15):"yearly"===m&&1===i.getMonth()&&29===i.getDate()&&o.setDate(28),O();var e=new Date(+o);if("monthly"===m||"yearly"===m){if(e.setDate(i.getDate()),e.getDate()!==i.getDate())return;if("yearly"===m&&e.getMonth()!==i.getMonth())return}g.push(e)};if(Array.isArray(v[s][u]))return r("Get cache",s,u),"monthly"===m?o.setDate(15):"yearly"===m&&1===i.getMonth()&&29===i.getDate()&&o.setDate(28),O(),v[s][u];if(n.by&&"yearly"===m){var w=h.slice(),D=!1;(n.by.weekno||n.by.yearday||n.by.monthday||n.by.day)&&(w.shift(),D=!0);var _=!0;w.forEach(function(e){var t=n.by[e];t&&(_?(t.forEach(b(e)),_=!1):"day"===e?n.by.yearday||n.by.monthday||n.by.weekno?E("day",n.by.day):n.by.day.forEach(b("day")):E(e,t))}),n.by.month&&D&&E("month",n.by.month)}n.by&&"monthly"===m&&(n.by.monthday||n.by.day?n.by.monthday?n.by.monthday.forEach(b("monthday")):n.by.day&&n.by.day.forEach(b("day")):A(),n.by.month&&E("month",n.by.month),n.by.day&&n.by.monthday&&E("day",n.by.day)),n.by&&"weekly"===m&&(n.by.day?n.by.day.forEach(b("day")):A(),n.by.month&&E("month",n.by.month)),n.by&&"daily"===m&&(A(),p.forEach(function(e){var t=n.by[e];t&&E(e,t)})),g.sort(function(e,n){return e-n}),n.by&&n.by.setpos&&E("setpos",n.by.setpos),n.by&&Object.keys(n.by).length?O():A();var T=[];return g=g.filter(function(e){var n=new Date(+e).toLocaleDateString();return!T.includes(n)&&(T.push(n),!0)}),r("Set cache",s,u),v[s][u]=g,g}(O,t,i);if(r("Iteration results",JSON.stringify(m.map(function(e){return new Date(e).toLocaleDateString()}))),!m.length)return i.getFullYear()=N)return r(h.toLocaleDateString(),"count"),D=!0,!0;if(h>=E)return r(h.toLocaleDateString(),"endMonth"),D=!0,!0;if(O.until&&h>O.until)return r(h.toLocaleDateString(),"until"),D=!0,!0;if(!(h=E||h=g){if(y[c.id]&&y[c.id].includes(c.start))return;y[c.id]=y[c.id]||[],y[c.id].push(c.start)}if(b.timeZone&&!c.isAllDay){var m=function(e,n,t){var r=function(e,n){let t=e.toLocaleString("en-CA",{timeZone:n,hour12:!1}).replace(", ","T");return t+="."+e.getMilliseconds().toString().padStart(3,"0"),-(new Date(t+"Z")-e)},o=Intl.DateTimeFormat().resolvedOptions().timeZone,a=r(n,e)-r(t,e);return r(n,o)-r(t,o)-a}(b.timeZone,o,h);c.start+=m,c.end+=m}return s.push(c),_?(v(),!0):void 0}r(h.toLocaleDateString(),"start")}),D||x(i)}};x(o),r("Added this month (all events)",s.map(function(e){return new Date(e.start).toLocaleDateString()}))}}}}})}),s},n.getAllOccurrences=function(e){if(!e.recurrenceRule)return[e.start];var t=e.recurrenceRule;if(!t.until&&!t.count)return!1;var r=[e.start],o=new Date(e.start);o.setDate(15);for(var a=[],i=0,s=function(){return t.count?r.length=1e4;)t.setDate(t.getDate()-a),o++;return{d:o*=a,h:(t=new Date(n)).getHours()-r.getHours(),m:t.getMinutes()-r.getMinutes()}};return n.applyUpdates=function(e){return e.forEach(function(e){if(e.raw={start:e.start,end:e.end},e.recUpdate){var n,t=e.recUpdate.from||{},r=e.recUpdate.one||{},o=e.start,a=m(e).filter(function(e){return e._start>o}).shift(),i=function(n,t){var r=n[t],o=new Date(e.raw[t]);o.setDate(o.getDate()+r.d),o.setHours(o.getHours()+r.h),o.setMinutes(o.getMinutes()+r.m),e[t]=+o};(n=t,Object.keys(n).sort(function(e,n){return Number(e)-Number(n)})).forEach(function(n){o",noCalendar:!1,now:new Date,onChange:[],onClose:[],onDayCreate:[],onDestroy:[],onKeyDown:[],onMonthChange:[],onOpen:[],onParseConfig:[],onReady:[],onValueUpdate:[],onYearChange:[],onPreCalendarPosition:[],plugins:[],position:"auto",positionElement:void 0,prevArrow:"",shorthandCurrentMonth:!1,showMonths:1,static:!1,time_24hr:!1,weekNumbers:!1,wrap:!1},o={weekdays:{shorthand:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],longhand:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},months:{shorthand:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],longhand:["January","February","March","April","May","June","July","August","September","October","November","December"]},daysInMonth:[31,28,31,30,31,30,31,31,30,31,30,31],firstDayOfWeek:0,ordinal:function(e){var n=e%100;if(n>3&&n<21)return"th";switch(n%10){case 1:return"st";case 2:return"nd";case 3:return"rd";default:return"th"}},rangeSeparator:" to ",weekAbbreviation:"Wk",scrollTitle:"Scroll to increment",toggleTitle:"Click to toggle",amPM:["AM","PM"],yearAriaLabel:"Year",monthAriaLabel:"Month",hourAriaLabel:"Hour",minuteAriaLabel:"Minute",time_24hr:!1},a=function(e,n){return void 0===n&&(n=2),("000"+e).slice(-1*n)},i=function(e){return!0===e?1:0};function s(e,n){var t;return function(){var r=this;clearTimeout(t),t=setTimeout(function(){return e.apply(r,arguments)},n)}}var c=function(e){return e instanceof Array?e:[e]};function u(e,n,t){if(!0===t)return e.classList.add(n);e.classList.remove(n)}function f(e,n,t){var r=window.document.createElement(e);return n=n||"",t=t||"",r.className=n,void 0!==t&&(r.textContent=t),r}function l(e){for(;e.firstChild;)e.removeChild(e.firstChild)}function d(e,n){return n(e)?e:e.parentNode?d(e.parentNode,n):void 0}function h(e,n){var t=f("div","numInputWrapper"),r=f("input","numInput "+e),o=f("span","arrowUp"),a=f("span","arrowDown");if(-1===navigator.userAgent.indexOf("MSIE 9.0")?r.type="number":(r.type="text",r.pattern="\\d*"),void 0!==n)for(var i in n)r.setAttribute(i,n[i]);return t.appendChild(r),t.appendChild(o),t.appendChild(a),t}function p(e){try{return"function"==typeof e.composedPath?e.composedPath()[0]:e.target}catch(n){return e.target}}var v=function(){},y=function(e,n,t){return t.months[n?"shorthand":"longhand"][e]},m={D:v,F:function(e,n,t){e.setMonth(t.months.longhand.indexOf(n))},G:function(e,n){e.setHours(parseFloat(n))},H:function(e,n){e.setHours(parseFloat(n))},J:function(e,n){e.setDate(parseFloat(n))},K:function(e,n,t){e.setHours(e.getHours()%12+12*i(new RegExp(t.amPM[1],"i").test(n)))},M:function(e,n,t){e.setMonth(t.months.shorthand.indexOf(n))},S:function(e,n){e.setSeconds(parseFloat(n))},U:function(e,n){return new Date(1e3*parseFloat(n))},W:function(e,n,t){var r=parseInt(n),o=new Date(e.getFullYear(),0,2+7*(r-1),0,0,0,0);return o.setDate(o.getDate()-o.getDay()+t.firstDayOfWeek),o},Y:function(e,n){e.setFullYear(parseFloat(n))},Z:function(e,n){return new Date(n)},d:function(e,n){e.setDate(parseFloat(n))},h:function(e,n){e.setHours(parseFloat(n))},i:function(e,n){e.setMinutes(parseFloat(n))},j:function(e,n){e.setDate(parseFloat(n))},l:v,m:function(e,n){e.setMonth(parseFloat(n)-1)},n:function(e,n){e.setMonth(parseFloat(n)-1)},s:function(e,n){e.setSeconds(parseFloat(n))},u:function(e,n){return new Date(parseFloat(n))},w:v,y:function(e,n){e.setFullYear(2e3+parseFloat(n))}},g={D:"(\\w+)",F:"(\\w+)",G:"(\\d\\d|\\d)",H:"(\\d\\d|\\d)",J:"(\\d\\d|\\d)\\w+",K:"",M:"(\\w+)",S:"(\\d\\d|\\d)",U:"(.+)",W:"(\\d\\d|\\d)",Y:"(\\d{4})",Z:"(.+)",d:"(\\d\\d|\\d)",h:"(\\d\\d|\\d)",i:"(\\d\\d|\\d)",j:"(\\d\\d|\\d)",l:"(\\w+)",m:"(\\d\\d|\\d)",n:"(\\d\\d|\\d)",s:"(\\d\\d|\\d)",u:"(.+)",w:"(\\d\\d|\\d)",y:"(\\d{2})"},E={Z:function(e){return e.toISOString()},D:function(e,n,t){return n.weekdays.shorthand[E.w(e,n,t)]},F:function(e,n,t){return y(E.n(e,n,t)-1,!1,n)},G:function(e,n,t){return a(E.h(e,n,t))},H:function(e){return a(e.getHours())},J:function(e,n){return void 0!==n.ordinal?e.getDate()+n.ordinal(e.getDate()):e.getDate()},K:function(e,n){return n.amPM[i(e.getHours()>11)]},M:function(e,n){return y(e.getMonth(),!0,n)},S:function(e){return a(e.getSeconds())},U:function(e){return e.getTime()/1e3},W:function(e,n,t){return t.getWeek(e)},Y:function(e){return a(e.getFullYear(),4)},d:function(e){return a(e.getDate())},h:function(e){return e.getHours()%12?e.getHours()%12:12},i:function(e){return a(e.getMinutes())},j:function(e){return e.getDate()},l:function(e,n){return n.weekdays.longhand[e.getDay()]},m:function(e){return a(e.getMonth()+1)},n:function(e){return e.getMonth()+1},s:function(e){return e.getSeconds()},u:function(e){return e.getTime()},w:function(e){return e.getDay()},y:function(e){return String(e.getFullYear()).substring(2)}},b=function(e){var n=e.config,t=void 0===n?r:n,a=e.l10n,i=void 0===a?o:a,s=e.isMobile,c=void 0!==s&&s;return function(e,n,r){var o=r||i;return void 0===t.formatDate||c?n.split("").map(function(n,r,a){return E[n]&&"\\"!==a[r-1]?E[n](e,o,t):"\\"!==n?n:""}).join(""):t.formatDate(e,n,o)}},O=function(e){var n=e.config,t=void 0===n?r:n,a=e.l10n,i=void 0===a?o:a;return function(e,n,o,a){if(0===e||e){var s,c=a||i,u=e;if(e instanceof Date)s=new Date(e.getTime());else if("string"!=typeof e&&void 0!==e.toFixed)s=new Date(e);else if("string"==typeof e){var f=n||(t||r).dateFormat,l=String(e).trim();if("today"===l)s=new Date,o=!0;else if(/Z$/.test(l)||/GMT$/.test(l))s=new Date(e);else if(t&&t.parseDate)s=t.parseDate(e,f);else{s=t&&t.noCalendar?new Date((new Date).setHours(0,0,0,0)):new Date((new Date).getFullYear(),0,1,0,0,0,0);for(var d=void 0,h=[],p=0,v=0,y="";p=0?new Date:new Date(E.config.minDate.getTime()),t=D(E.config);n.setHours(t.hours,t.minutes,t.seconds,n.getMilliseconds()),E.selectedDates=[n],E.latestSelectedDateObj=n}void 0!==e&&"blur"!==e.type&&function(e){e.preventDefault();var n="keydown"===e.type,t=p(e),r=t;void 0!==E.amPM&&t===E.amPM&&(E.amPM.textContent=E.l10n.amPM[i(E.amPM.textContent===E.l10n.amPM[0])]);var o=parseFloat(r.getAttribute("min")),s=parseFloat(r.getAttribute("max")),c=parseFloat(r.getAttribute("step")),u=parseInt(r.value,10),f=u+c*(e.delta||(n?38===e.which?1:-1:0));if(void 0!==r.value&&2===r.value.length){var l=r===E.hourElement,d=r===E.minuteElement;fs&&(f=r===E.hourElement?f-s-i(!E.amPM):o,d&&L(void 0,1,E.hourElement)),E.amPM&&l&&(1===c?f+u===23:Math.abs(f-u)>c)&&(E.amPM.textContent=E.l10n.amPM[i(E.amPM.textContent===E.l10n.amPM[0])]),r.value=a(f)}}(e);var r=E._input.value;I(),be(),E._input.value!==r&&E._debouncedChange()}function I(){if(void 0!==E.hourElement&&void 0!==E.minuteElement){var e,n,t=(parseInt(E.hourElement.value.slice(-2),10)||0)%24,r=(parseInt(E.minuteElement.value,10)||0)%60,o=void 0!==E.secondElement?(parseInt(E.secondElement.value,10)||0)%60:0;void 0!==E.amPM&&(e=t,n=E.amPM.textContent,t=e%12+12*i(n===E.l10n.amPM[1]));var a=void 0!==E.config.minTime||E.config.minDate&&E.minDateHasTime&&E.latestSelectedDateObj&&0===A(E.latestSelectedDateObj,E.config.minDate,!0);if(void 0!==E.config.maxTime||E.config.maxDate&&E.maxDateHasTime&&E.latestSelectedDateObj&&0===A(E.latestSelectedDateObj,E.config.maxDate,!0)){var s=void 0!==E.config.maxTime?E.config.maxTime:E.config.maxDate;(t=Math.min(t,s.getHours()))===s.getHours()&&(r=Math.min(r,s.getMinutes())),r===s.getMinutes()&&(o=Math.min(o,s.getSeconds()))}if(a){var c=void 0!==E.config.minTime?E.config.minTime:E.config.minDate;(t=Math.max(t,c.getHours()))===c.getHours()&&r=12)]),void 0!==E.secondElement&&(E.secondElement.value=a(t)))}function R(e){var n=p(e),t=parseInt(n.value)+(e.delta||0);(t/1e3>1||"Enter"===e.key&&!/[^\d]/.test(t.toString()))&&X(t)}function P(e,n,t,r){return n instanceof Array?n.forEach(function(n){return P(e,n,t,r)}):e instanceof Array?e.forEach(function(e){return P(e,n,t,r)}):(e.addEventListener(n,t,r),void E._handlers.push({remove:function(){return e.removeEventListener(n,t)}}))}function k(){ve("onChange")}function M(e,n){var t=void 0!==e?E.parseDate(e):E.latestSelectedDateObj||(E.config.minDate&&E.config.minDate>E.now?E.config.minDate:E.config.maxDate&&E.config.maxDate=0&&A(e,E.selectedDates[1])<=0}(n)&&!me(n)&&a.classList.add("inRange"),E.weekNumbers&&1===E.config.showMonths&&"prevMonthDay"!==e&&t%7==1&&E.weekNumbers.insertAdjacentHTML("beforeend",""+E.config.getWeek(n)+""),ve("onDayCreate",a),a}function j(e){e.focus(),"range"===E.config.mode&&re(e)}function K(e){for(var n=e>0?0:E.config.showMonths-1,t=e>0?E.config.showMonths:-1,r=n;r!=t;r+=e)for(var o=E.daysContainer.children[r],a=e>0?0:o.children.length-1,i=e>0?o.children.length:-1,s=a;s!=i;s+=e){var c=o.children[s];if(-1===c.className.indexOf("hidden")&&$(c.dateObj))return c}}function U(e,n){var t=ee(document.activeElement||document.body),r=void 0!==e?e:t?document.activeElement:void 0!==E.selectedDateElem&&ee(E.selectedDateElem)?E.selectedDateElem:void 0!==E.todayDateElem&&ee(E.todayDateElem)?E.todayDateElem:K(n>0?1:-1);void 0===r?E._input.focus():t?function(e,n){for(var t=-1===e.className.indexOf("Month")?e.dateObj.getMonth():E.currentMonth,r=n>0?E.config.showMonths:-1,o=n>0?1:-1,a=t-E.currentMonth;a!=r;a+=o)for(var i=E.daysContainer.children[a],s=t-E.currentMonth===a?e.$i+n:n<0?i.children.length-1:0,c=i.children.length,u=s;u>=0&&u0?c:-1);u+=o){var f=i.children[u];if(-1===f.className.indexOf("hidden")&&$(f.dateObj)&&Math.abs(e.$i-u)>=Math.abs(n))return j(f)}E.changeMonth(o),U(K(o),0)}(r,n):j(r)}function B(e,n){for(var t=(new Date(e,n,1).getDay()-E.l10n.firstDayOfWeek+7)%7,r=E.utils.getDaysInMonth((n-1+12)%12,e),o=E.utils.getDaysInMonth(n,e),a=window.document.createDocumentFragment(),i=E.config.showMonths>1,s=i?"prevMonthDay hidden":"prevMonthDay",c=i?"nextMonthDay hidden":"nextMonthDay",u=r+1-t,l=0;u<=r;u++,l++)a.appendChild(H(s,new Date(e,n-1,u),u,l));for(u=1;u<=o;u++,l++)a.appendChild(H("",new Date(e,n,u),u,l));for(var d=o+1;d<=42-t&&(1===E.config.showMonths||l%7!=0);d++,l++)a.appendChild(H(c,new Date(e,n+1,d%o),d,l));var h=f("div","dayContainer");return h.appendChild(a),h}function V(){if(void 0!==E.daysContainer){l(E.daysContainer),E.weekNumbers&&l(E.weekNumbers);for(var e=document.createDocumentFragment(),n=0;n1||"dropdown"!==E.config.monthSelectorType)){var e=function(e){return!(void 0!==E.config.minDate&&E.currentYear===E.config.minDate.getFullYear()&&eE.config.maxDate.getMonth())};E.monthsDropdownContainer.tabIndex=-1,E.monthsDropdownContainer.innerHTML="";for(var n=0;n<12;n++)if(e(n)){var t=f("option","flatpickr-monthDropdown-month");t.value=new Date(E.currentYear,n).getMonth().toString(),t.textContent=y(n,E.config.shorthandCurrentMonth,E.l10n),t.tabIndex=-1,E.currentMonth===n&&(t.selected=!0),E.monthsDropdownContainer.appendChild(t)}}}function G(){var e,n=f("div","flatpickr-month"),t=window.document.createDocumentFragment();E.config.showMonths>1||"static"===E.config.monthSelectorType?e=f("span","cur-month"):(E.monthsDropdownContainer=f("select","flatpickr-monthDropdown-months"),E.monthsDropdownContainer.setAttribute("aria-label",E.l10n.monthAriaLabel),P(E.monthsDropdownContainer,"change",function(e){var n=p(e),t=parseInt(n.value,10);E.changeMonth(t-E.currentMonth),ve("onMonthChange")}),Y(),e=E.monthsDropdownContainer);var r=h("cur-year",{tabindex:"-1"}),o=r.getElementsByTagName("input")[0];o.setAttribute("aria-label",E.l10n.yearAriaLabel),E.config.minDate&&o.setAttribute("min",E.config.minDate.getFullYear().toString()),E.config.maxDate&&(o.setAttribute("max",E.config.maxDate.getFullYear().toString()),o.disabled=!!E.config.minDate&&E.config.minDate.getFullYear()===E.config.maxDate.getFullYear());var a=f("div","flatpickr-current-month");return a.appendChild(e),a.appendChild(r),t.appendChild(a),n.appendChild(t),{container:n,yearElement:o,monthElement:e}}function J(){l(E.monthNav),E.monthNav.appendChild(E.prevMonthNav),E.config.showMonths&&(E.yearElements=[],E.monthElements=[]);for(var e=E.config.showMonths;e--;){var n=G();E.yearElements.push(n.yearElement),E.monthElements.push(n.monthElement),E.monthNav.appendChild(n.container)}E.monthNav.appendChild(E.nextMonthNav)}function q(){E.weekdayContainer?l(E.weekdayContainer):E.weekdayContainer=f("div","flatpickr-weekdays");for(var e=E.config.showMonths;e--;){var n=f("div","flatpickr-weekdaycontainer");E.weekdayContainer.appendChild(n)}return W(),E.weekdayContainer}function W(){if(E.weekdayContainer){var e=E.l10n.firstDayOfWeek,t=n(E.l10n.weekdays.shorthand);e>0&&e\n "+t.join("")+"\n \n "}}function z(e,n){void 0===n&&(n=!0);var t=n?e:e-E.currentMonth;t<0&&!0===E._hidePrevMonthArrow||t>0&&!0===E._hideNextMonthArrow||(E.currentMonth+=t,(E.currentMonth<0||E.currentMonth>11)&&(E.currentYear+=E.currentMonth>11?1:-1,E.currentMonth=(E.currentMonth+12)%12,ve("onYearChange"),Y()),V(),ve("onMonthChange"),ge())}function Q(e){return!(!E.config.appendTo||!E.config.appendTo.contains(e))||E.calendarContainer.contains(e)}function Z(e){if(E.isOpen&&!E.config.inline){var n=p(e),t=Q(n),r=n===E.input||n===E.altInput||E.element.contains(n)||e.path&&e.path.indexOf&&(~e.path.indexOf(E.input)||~e.path.indexOf(E.altInput)),o="blur"===e.type?r&&e.relatedTarget&&!Q(e.relatedTarget):!r&&!t&&!Q(e.relatedTarget),a=!E.config.ignoredFocusElements.some(function(e){return e.contains(n)});o&&a&&(void 0!==E.timeContainer&&void 0!==E.minuteElement&&void 0!==E.hourElement&&""!==E.input.value&&void 0!==E.input.value&&N(),E.close(),E.config&&"range"===E.config.mode&&1===E.selectedDates.length&&(E.clear(!1),E.redraw()))}}function X(e){if(!(!e||E.config.minDate&&eE.config.maxDate.getFullYear())){var n=e,t=E.currentYear!==n;E.currentYear=n||E.currentYear,E.config.maxDate&&E.currentYear===E.config.maxDate.getFullYear()?E.currentMonth=Math.min(E.config.maxDate.getMonth(),E.currentMonth):E.config.minDate&&E.currentYear===E.config.minDate.getFullYear()&&(E.currentMonth=Math.max(E.config.minDate.getMonth(),E.currentMonth)),t&&(E.redraw(),ve("onYearChange"),Y())}}function $(e,n){var t;void 0===n&&(n=!0);var r=E.parseDate(e,void 0,n);if(E.config.minDate&&r&&A(r,E.config.minDate,void 0!==n?n:!E.minDateHasTime)<0||E.config.maxDate&&r&&A(r,E.config.maxDate,void 0!==n?n:!E.maxDateHasTime)>0)return!1;if(!E.config.enable&&0===E.config.disable.length)return!0;if(void 0===r)return!1;for(var o=!!E.config.enable,a=null!==(t=E.config.enable)&&void 0!==t?t:E.config.disable,i=0,s=void 0;i=s.from.getTime()&&r.getTime()<=s.to.getTime())return o}return!o}function ee(e){return void 0!==E.daysContainer&&-1===e.className.indexOf("hidden")&&-1===e.className.indexOf("flatpickr-disabled")&&E.daysContainer.contains(e)}function ne(e){e.target!==E._input||!(E.selectedDates.length>0||E._input.value.length>0)||e.relatedTarget&&Q(e.relatedTarget)||E.setDate(E._input.value,!0,e.target===E.altInput?E.config.altFormat:E.config.dateFormat)}function te(e){var n=p(e),t=E.config.wrap?v.contains(n):n===E._input,r=E.config.allowInput,o=E.isOpen&&(!r||!t),a=E.config.inline&&t&&!r;if(13===e.keyCode&&t){if(r)return E.setDate(E._input.value,!0,n===E.altInput?E.config.altFormat:E.config.dateFormat),n.blur();E.open()}else if(Q(n)||o||a){var i=!!E.timeContainer&&E.timeContainer.contains(n);switch(e.keyCode){case 13:i?(e.preventDefault(),N(),fe()):le(e);break;case 27:e.preventDefault(),fe();break;case 8:case 46:t&&!E.config.allowInput&&(e.preventDefault(),E.clear());break;case 37:case 39:if(i||t)E.hourElement&&E.hourElement.focus();else if(e.preventDefault(),void 0!==E.daysContainer&&(!1===r||document.activeElement&&ee(document.activeElement))){var s=39===e.keyCode?1:-1;e.ctrlKey?(e.stopPropagation(),z(s),U(K(1),0)):U(void 0,s)}break;case 38:case 40:e.preventDefault();var c=40===e.keyCode?1:-1;E.daysContainer&&void 0!==n.$i||n===E.input||n===E.altInput?e.ctrlKey?(e.stopPropagation(),X(E.currentYear-c),U(K(1),0)):i||U(void 0,7*c):n===E.currentYearElement?X(E.currentYear-c):E.config.enableTime&&(!i&&E.hourElement&&E.hourElement.focus(),N(e),E._debouncedChange());break;case 9:if(i){var u=[E.hourElement,E.minuteElement,E.secondElement,E.amPM].concat(E.pluginElements).filter(function(e){return e}),f=u.indexOf(n);if(-1!==f){var l=u[f+(e.shiftKey?-1:1)];e.preventDefault(),(l||E._input).focus()}}else!E.config.noCalendar&&E.daysContainer&&E.daysContainer.contains(n)&&e.shiftKey&&(e.preventDefault(),E._input.focus())}}if(void 0!==E.amPM&&n===E.amPM)switch(e.key){case E.l10n.amPM[0].charAt(0):case E.l10n.amPM[0].charAt(0).toLowerCase():E.amPM.textContent=E.l10n.amPM[0],I(),be();break;case E.l10n.amPM[1].charAt(0):case E.l10n.amPM[1].charAt(0).toLowerCase():E.amPM.textContent=E.l10n.amPM[1],I(),be()}(t||Q(n))&&ve("onKeyDown",e)}function re(e){if(1===E.selectedDates.length&&(!e||e.classList.contains("flatpickr-day")&&!e.classList.contains("flatpickr-disabled"))){for(var n=e?e.dateObj.getTime():E.days.firstElementChild.dateObj.getTime(),t=E.parseDate(E.selectedDates[0],void 0,!0).getTime(),r=Math.min(n,E.selectedDates[0].getTime()),o=Math.max(n,E.selectedDates[0].getTime()),a=!1,i=0,s=0,c=r;cr&&ci)?i=c:c>t&&(!s||c0&&h0&&h>s;return p?(d.classList.add("notAllowed"),["inRange","startRange","endRange"].forEach(function(e){d.classList.remove(e)}),"continue"):a&&!p?"continue":(["startRange","inRange","endRange","notAllowed"].forEach(function(e){d.classList.remove(e)}),void(void 0!==e&&(e.classList.add(n<=E.selectedDates[0].getTime()?"startRange":"endRange"),tn&&h===t&&d.classList.add("endRange"),h>=i&&(0===s||h<=s)&&(u=t,l=n,(c=h)>Math.min(u,l)&&c0||t.getMinutes()>0||t.getSeconds()>0),E.selectedDates&&(E.selectedDates=E.selectedDates.filter(function(e){return $(e)}),E.selectedDates.length||"min"!==e||x(t),be()),E.daysContainer&&(ue(),void 0!==t?E.currentYearElement[e]=t.getFullYear().toString():E.currentYearElement.removeAttribute(e),E.currentYearElement.disabled=!!r&&void 0!==t&&r.getFullYear()===t.getFullYear())}}function ie(){return E.config.wrap?v.querySelector("[data-input]"):v}function se(){"object"!=typeof E.config.locale&&void 0===S.l10ns[E.config.locale]&&E.config.errorHandler(new Error("flatpickr: invalid locale "+E.config.locale)),E.l10n=e(e({},S.l10ns.default),"object"==typeof E.config.locale?E.config.locale:"default"!==E.config.locale?S.l10ns[E.config.locale]:void 0),g.K="("+E.l10n.amPM[0]+"|"+E.l10n.amPM[1]+"|"+E.l10n.amPM[0].toLowerCase()+"|"+E.l10n.amPM[1].toLowerCase()+")",void 0===e(e({},m),JSON.parse(JSON.stringify(v.dataset||{}))).time_24hr&&void 0===S.defaultConfig.time_24hr&&(E.config.time_24hr=E.l10n.time_24hr),E.formatDate=b(E),E.parseDate=O({config:E.config,l10n:E.l10n})}function ce(e){if("function"!=typeof E.config.position){if(void 0!==E.calendarContainer){ve("onPreCalendarPosition");var n=e||E._positionElement,t=Array.prototype.reduce.call(E.calendarContainer.children,function(e,n){return e+n.offsetHeight},0),r=E.calendarContainer.offsetWidth,o=E.config.position.split(" "),a=o[0],i=o.length>1?o[1]:null,s=n.getBoundingClientRect(),c=window.innerHeight-s.bottom,f="above"===a||"below"!==a&&ct,l=window.pageYOffset+s.top+(f?-t-2:n.offsetHeight+2);if(u(E.calendarContainer,"arrowTop",!f),u(E.calendarContainer,"arrowBottom",f),!E.config.inline){var d=window.pageXOffset+s.left,h=!1,p=!1;"center"===i?(d-=(r-s.width)/2,h=!0):"right"===i&&(d-=r-s.width,p=!0),u(E.calendarContainer,"arrowLeft",!h&&!p),u(E.calendarContainer,"arrowCenter",h),u(E.calendarContainer,"arrowRight",p);var v=window.document.body.offsetWidth-(window.pageXOffset+s.right),y=d+r>window.document.body.offsetWidth,m=v+r>window.document.body.offsetWidth;if(u(E.calendarContainer,"rightMost",y),!E.config.static)if(E.calendarContainer.style.top=l+"px",y)if(m){var g=function(){for(var e=null,n=0;nE.currentMonth+E.config.showMonths-1)&&"range"!==E.config.mode;if(E.selectedDateElem=t,"single"===E.config.mode)E.selectedDates=[r];else if("multiple"===E.config.mode){var a=me(r);a?E.selectedDates.splice(parseInt(a),1):E.selectedDates.push(r)}else"range"===E.config.mode&&(2===E.selectedDates.length&&E.clear(!1,!1),E.latestSelectedDateObj=r,E.selectedDates.push(r),0!==A(r,E.selectedDates[0],!0)&&E.selectedDates.sort(function(e,n){return e.getTime()-n.getTime()}));if(I(),o){var i=E.currentYear!==r.getFullYear();E.currentYear=r.getFullYear(),E.currentMonth=r.getMonth(),i&&(ve("onYearChange"),Y()),ve("onMonthChange")}if(ge(),V(),be(),o||"range"===E.config.mode||1!==E.config.showMonths?void 0!==E.selectedDateElem&&void 0===E.hourElement&&E.selectedDateElem&&E.selectedDateElem.focus():j(t),void 0!==E.hourElement&&void 0!==E.hourElement&&E.hourElement.focus(),E.config.closeOnSelect){var s="single"===E.config.mode&&!E.config.enableTime,c="range"===E.config.mode&&2===E.selectedDates.length&&!E.config.enableTime;(s||c)&&fe()}k()}}E.parseDate=O({config:E.config,l10n:E.l10n}),E._handlers=[],E.pluginElements=[],E.loadedPlugins=[],E._bind=P,E._setHoursFromDate=x,E._positionCalendar=ce,E.changeMonth=z,E.changeYear=X,E.clear=function(e,n){if(void 0===e&&(e=!0),void 0===n&&(n=!0),E.input.value="",void 0!==E.altInput&&(E.altInput.value=""),void 0!==E.mobileInput&&(E.mobileInput.value=""),E.selectedDates=[],E.latestSelectedDateObj=void 0,!0===n&&(E.currentYear=E._initialDate.getFullYear(),E.currentMonth=E._initialDate.getMonth()),!0===E.config.enableTime){var t=D(E.config);C(t.hours,t.minutes,t.seconds)}E.redraw(),e&&ve("onChange")},E.close=function(){E.isOpen=!1,E.isMobile||(void 0!==E.calendarContainer&&E.calendarContainer.classList.remove("open"),void 0!==E._input&&E._input.classList.remove("active")),ve("onClose")},E._createElement=f,E.destroy=function(){void 0!==E.config&&ve("onDestroy");for(var e=E._handlers.length;e--;)E._handlers[e].remove();if(E._handlers=[],E.mobileInput)E.mobileInput.parentNode&&E.mobileInput.parentNode.removeChild(E.mobileInput),E.mobileInput=void 0;else if(E.calendarContainer&&E.calendarContainer.parentNode)if(E.config.static&&E.calendarContainer.parentNode){var n=E.calendarContainer.parentNode;if(n.lastChild&&n.removeChild(n.lastChild),n.parentNode){for(;n.firstChild;)n.parentNode.insertBefore(n.firstChild,n);n.parentNode.removeChild(n)}}else E.calendarContainer.parentNode.removeChild(E.calendarContainer);E.altInput&&(E.input.type="text",E.altInput.parentNode&&E.altInput.parentNode.removeChild(E.altInput),delete E.altInput),E.input&&(E.input.type=E.input._type,E.input.classList.remove("flatpickr-input"),E.input.removeAttribute("readonly")),["_showTimeInput","latestSelectedDateObj","_hideNextMonthArrow","_hidePrevMonthArrow","__hideNextMonthArrow","__hidePrevMonthArrow","isMobile","isOpen","selectedDateElem","minDateHasTime","maxDateHasTime","days","daysContainer","_input","_positionElement","innerContainer","rContainer","monthNav","todayDateElem","calendarContainer","weekdayContainer","prevMonthNav","nextMonthNav","monthsDropdownContainer","currentMonthElement","currentYearElement","navigationCurrentMonth","selectedDateElem","config"].forEach(function(e){try{delete E[e]}catch(e){}})},E.isEnabled=$,E.jumpToDate=M,E.open=function(e,n){if(void 0===n&&(n=E._positionElement),!0===E.isMobile){if(e){e.preventDefault();var t=p(e);t&&t.blur()}return void 0!==E.mobileInput&&(E.mobileInput.focus(),E.mobileInput.click()),void ve("onOpen")}if(!E._input.disabled&&!E.config.inline){var r=E.isOpen;E.isOpen=!0,r||(E.calendarContainer.classList.add("open"),E._input.classList.add("active"),ve("onOpen"),ce(n)),!0===E.config.enableTime&&!0===E.config.noCalendar&&(!1!==E.config.allowInput||void 0!==e&&E.timeContainer.contains(e.relatedTarget)||setTimeout(function(){return E.hourElement.select()},50))}},E.redraw=ue,E.set=function(e,n){if(null!==e&&"object"==typeof e)for(var r in Object.assign(E.config,e),e)void 0!==de[r]&&de[r].forEach(function(e){return e()});else E.config[e]=n,void 0!==de[e]?de[e].forEach(function(e){return e()}):t.indexOf(e)>-1&&(E.config[e]=c(n));E.redraw(),be(!0)},E.setDate=function(e,n,t){if(void 0===n&&(n=!1),void 0===t&&(t=E.config.dateFormat),0!==e&&!e||e instanceof Array&&0===e.length)return E.clear(n);he(e,t),E.latestSelectedDateObj=E.selectedDates[E.selectedDates.length-1],E.redraw(),M(void 0,n),x(),0===E.selectedDates.length&&E.clear(!1),be(n),n&&ve("onChange")},E.toggle=function(e){if(!0===E.isOpen)return E.close();E.open(e)};var de={locale:[se,W],showMonths:[J,T,q],minDate:[M],maxDate:[M],clickOpens:[function(){!0===E.config.clickOpens?(P(E._input,"focus",E.open),P(E._input,"click",E.open)):(E._input.removeEventListener("focus",E.open),E._input.removeEventListener("click",E.open))}]};function he(e,n){var t=[];if(e instanceof Array)t=e.map(function(e){return E.parseDate(e,n)});else if(e instanceof Date||"number"==typeof e)t=[E.parseDate(e,n)];else if("string"==typeof e)switch(E.config.mode){case"single":case"time":t=[E.parseDate(e,n)];break;case"multiple":t=e.split(E.config.conjunction).map(function(e){return E.parseDate(e,n)});break;case"range":t=e.split(E.l10n.rangeSeparator).map(function(e){return E.parseDate(e,n)})}else E.config.errorHandler(new Error("Invalid date supplied: "+JSON.stringify(e)));E.selectedDates=E.config.allowInvalidPreload?t:t.filter(function(e){return e instanceof Date&&$(e,!1)}),"range"===E.config.mode&&E.selectedDates.sort(function(e,n){return e.getTime()-n.getTime()})}function pe(e){return e.slice().map(function(e){return"string"==typeof e||"number"==typeof e||e instanceof Date?E.parseDate(e,void 0,!0):e&&"object"==typeof e&&e.from&&e.to?{from:E.parseDate(e.from,void 0),to:E.parseDate(e.to,void 0)}:e}).filter(function(e){return e})}function ve(e,n){if(void 0!==E.config){var t=E.config[e];if(void 0!==t&&t.length>0)for(var r=0;t[r]&&r1||"static"===E.config.monthSelectorType?E.monthElements[n].textContent=y(t.getMonth(),E.config.shorthandCurrentMonth,E.l10n)+" ":E.monthsDropdownContainer.value=t.getMonth().toString(),e.value=t.getFullYear().toString()}),E._hidePrevMonthArrow=void 0!==E.config.minDate&&(E.currentYear===E.config.minDate.getFullYear()?E.currentMonth<=E.config.minDate.getMonth():E.currentYearE.config.maxDate.getMonth():E.currentYear>E.config.maxDate.getFullYear()))}function Ee(e){return E.selectedDates.map(function(n){return E.formatDate(n,e)}).filter(function(e,n,t){return"range"!==E.config.mode||E.config.enableTime||t.indexOf(e)===n}).join("range"!==E.config.mode?E.config.conjunction:E.l10n.rangeSeparator)}function be(e){void 0===e&&(e=!0),void 0!==E.mobileInput&&E.mobileFormatStr&&(E.mobileInput.value=void 0!==E.latestSelectedDateObj?E.formatDate(E.latestSelectedDateObj,E.mobileFormatStr):""),E.input.value=Ee(E.config.dateFormat),void 0!==E.altInput&&(E.altInput.value=Ee(E.config.altFormat)),!1!==e&&ve("onValueUpdate")}function Oe(e){var n=p(e),t=E.prevMonthNav.contains(n),r=E.nextMonthNav.contains(n);t||r?z(t?-1:1):E.yearElements.indexOf(n)>=0?n.select():n.classList.contains("arrowUp")?E.changeYear(E.currentYear+1):n.classList.contains("arrowDown")&&E.changeYear(E.currentYear-1)}return function(){E.element=E.input=v,E.isOpen=!1,function(){var n=["wrap","weekNumbers","allowInput","allowInvalidPreload","clickOpens","time_24hr","enableTime","noCalendar","altInput","shorthandCurrentMonth","inline","static","enableSeconds","disableMobile"],o=e(e({},JSON.parse(JSON.stringify(v.dataset||{}))),m),a={};E.config.parseDate=o.parseDate,E.config.formatDate=o.formatDate,Object.defineProperty(E.config,"enable",{get:function(){return E.config._enable},set:function(e){E.config._enable=pe(e)}}),Object.defineProperty(E.config,"disable",{get:function(){return E.config._disable},set:function(e){E.config._disable=pe(e)}});var i="time"===o.mode;if(!o.dateFormat&&(o.enableTime||i)){var s=S.defaultConfig.dateFormat||r.dateFormat;a.dateFormat=o.noCalendar||i?"H:i"+(o.enableSeconds?":S":""):s+" H:i"+(o.enableSeconds?":S":"")}if(o.altInput&&(o.enableTime||i)&&!o.altFormat){var u=S.defaultConfig.altFormat||r.altFormat;a.altFormat=o.noCalendar||i?"h:i"+(o.enableSeconds?":S K":" K"):u+" h:i"+(o.enableSeconds?":S":"")+" K"}Object.defineProperty(E.config,"minDate",{get:function(){return E.config._minDate},set:ae("min")}),Object.defineProperty(E.config,"maxDate",{get:function(){return E.config._maxDate},set:ae("max")});var f=function(e){return function(n){E.config["min"===e?"_minTime":"_maxTime"]=E.parseDate(n,"H:i:S")}};Object.defineProperty(E.config,"minTime",{get:function(){return E.config._minTime},set:f("min")}),Object.defineProperty(E.config,"maxTime",{get:function(){return E.config._maxTime},set:f("max")}),"time"===o.mode&&(E.config.noCalendar=!0,E.config.enableTime=!0),Object.assign(E.config,a,o);for(var l=0;l-1?E.config[h]=c(d[h]).map(_).concat(E.config[h]):void 0===o[h]&&(E.config[h]=d[h])}o.altInputClass||(E.config.altInputClass=ie().className+" "+E.config.altInputClass),ve("onParseConfig")}(),se(),E.input=ie(),E.input?(E.input._type=E.input.type,E.input.type="text",E.input.classList.add("flatpickr-input"),E._input=E.input,E.config.altInput&&(E.altInput=f(E.input.nodeName,E.config.altInputClass),E._input=E.altInput,E.altInput.placeholder=E.input.placeholder,E.altInput.disabled=E.input.disabled,E.altInput.required=E.input.required,E.altInput.tabIndex=E.input.tabIndex,E.altInput.type="text",E.input.setAttribute("type","hidden"),!E.config.static&&E.input.parentNode&&E.input.parentNode.insertBefore(E.altInput,E.input.nextSibling)),E.config.allowInput||E._input.setAttribute("readonly","readonly"),E._positionElement=E.config.positionElement||E._input):E.config.errorHandler(new Error("Invalid input element specified")),function(){E.selectedDates=[],E.now=E.parseDate(E.config.now)||new Date;var e=E.config.defaultDate||("INPUT"!==E.input.nodeName&&"TEXTAREA"!==E.input.nodeName||!E.input.placeholder||E.input.value!==E.input.placeholder?E.input.value:null);e&&he(e,E.config.dateFormat),E._initialDate=E.selectedDates.length>0?E.selectedDates[0]:E.config.minDate&&E.config.minDate.getTime()>E.now.getTime()?E.config.minDate:E.config.maxDate&&E.config.maxDate.getTime()0&&(E.latestSelectedDateObj=E.selectedDates[0]),void 0!==E.config.minTime&&(E.config.minTime=E.parseDate(E.config.minTime,"H:i")),void 0!==E.config.maxTime&&(E.config.maxTime=E.parseDate(E.config.maxTime,"H:i")),E.minDateHasTime=!!E.config.minDate&&(E.config.minDate.getHours()>0||E.config.minDate.getMinutes()>0||E.config.minDate.getSeconds()>0),E.maxDateHasTime=!!E.config.maxDate&&(E.config.maxDate.getHours()>0||E.config.maxDate.getMinutes()>0||E.config.maxDate.getSeconds()>0)}(),E.utils={getDaysInMonth:function(e,n){return void 0===e&&(e=E.currentMonth),void 0===n&&(n=E.currentYear),1===e&&(n%4==0&&n%100!=0||n%400==0)?29:E.l10n.daysInMonth[e]}},E.isMobile||function(){var e=window.document.createDocumentFragment();if(E.calendarContainer=f("div","flatpickr-calendar"),E.calendarContainer.tabIndex=-1,!E.config.noCalendar){if(e.appendChild((E.monthNav=f("div","flatpickr-months"),E.yearElements=[],E.monthElements=[],E.prevMonthNav=f("span","flatpickr-prev-month"),E.prevMonthNav.innerHTML=E.config.prevArrow,E.nextMonthNav=f("span","flatpickr-next-month"),E.nextMonthNav.innerHTML=E.config.nextArrow,J(),Object.defineProperty(E,"_hidePrevMonthArrow",{get:function(){return E.__hidePrevMonthArrow},set:function(e){E.__hidePrevMonthArrow!==e&&(u(E.prevMonthNav,"flatpickr-disabled",e),E.__hidePrevMonthArrow=e)}}),Object.defineProperty(E,"_hideNextMonthArrow",{get:function(){return E.__hideNextMonthArrow},set:function(e){E.__hideNextMonthArrow!==e&&(u(E.nextMonthNav,"flatpickr-disabled",e),E.__hideNextMonthArrow=e)}}),E.currentYearElement=E.yearElements[0],ge(),E.monthNav)),E.innerContainer=f("div","flatpickr-innerContainer"),E.config.weekNumbers){var n=function(){E.calendarContainer.classList.add("hasWeeks");var e=f("div","flatpickr-weekwrapper");e.appendChild(f("span","flatpickr-weekday",E.l10n.weekAbbreviation));var n=f("div","flatpickr-weeks");return e.appendChild(n),{weekWrapper:e,weekNumbers:n}}(),t=n.weekWrapper,r=n.weekNumbers;E.innerContainer.appendChild(t),E.weekNumbers=r,E.weekWrapper=t}E.rContainer=f("div","flatpickr-rContainer"),E.rContainer.appendChild(q()),E.daysContainer||(E.daysContainer=f("div","flatpickr-days"),E.daysContainer.tabIndex=-1),V(),E.rContainer.appendChild(E.daysContainer),E.innerContainer.appendChild(E.rContainer),e.appendChild(E.innerContainer)}E.config.enableTime&&e.appendChild(function(){E.calendarContainer.classList.add("hasTime"),E.config.noCalendar&&E.calendarContainer.classList.add("noCalendar");var e=D(E.config);E.timeContainer=f("div","flatpickr-time"),E.timeContainer.tabIndex=-1;var n=f("span","flatpickr-time-separator",":"),t=h("flatpickr-hour",{"aria-label":E.l10n.hourAriaLabel});E.hourElement=t.getElementsByTagName("input")[0];var r=h("flatpickr-minute",{"aria-label":E.l10n.minuteAriaLabel});if(E.minuteElement=r.getElementsByTagName("input")[0],E.hourElement.tabIndex=E.minuteElement.tabIndex=-1,E.hourElement.value=a(E.latestSelectedDateObj?E.latestSelectedDateObj.getHours():E.config.time_24hr?e.hours:function(e){switch(e%24){case 0:case 12:return 12;default:return e%12}}(e.hours)),E.minuteElement.value=a(E.latestSelectedDateObj?E.latestSelectedDateObj.getMinutes():e.minutes),E.hourElement.setAttribute("step",E.config.hourIncrement.toString()),E.minuteElement.setAttribute("step",E.config.minuteIncrement.toString()),E.hourElement.setAttribute("min",E.config.time_24hr?"0":"1"),E.hourElement.setAttribute("max",E.config.time_24hr?"23":"12"),E.hourElement.setAttribute("maxlength","2"),E.minuteElement.setAttribute("min","0"),E.minuteElement.setAttribute("max","59"),E.minuteElement.setAttribute("maxlength","2"),E.timeContainer.appendChild(t),E.timeContainer.appendChild(n),E.timeContainer.appendChild(r),E.config.time_24hr&&E.timeContainer.classList.add("time24hr"),E.config.enableSeconds){E.timeContainer.classList.add("hasSeconds");var o=h("flatpickr-second");E.secondElement=o.getElementsByTagName("input")[0],E.secondElement.value=a(E.latestSelectedDateObj?E.latestSelectedDateObj.getSeconds():e.seconds),E.secondElement.setAttribute("step",E.minuteElement.getAttribute("step")),E.secondElement.setAttribute("min","0"),E.secondElement.setAttribute("max","59"),E.secondElement.setAttribute("maxlength","2"),E.timeContainer.appendChild(f("span","flatpickr-time-separator",":")),E.timeContainer.appendChild(o)}return E.config.time_24hr||(E.amPM=f("span","flatpickr-am-pm",E.l10n.amPM[i((E.latestSelectedDateObj?E.hourElement.value:E.config.defaultHour)>11)]),E.amPM.title=E.l10n.toggleTitle,E.amPM.tabIndex=-1,E.timeContainer.appendChild(E.amPM)),E.timeContainer}()),u(E.calendarContainer,"rangeMode","range"===E.config.mode),u(E.calendarContainer,"animate",!0===E.config.animate),u(E.calendarContainer,"multiMonth",E.config.showMonths>1),E.calendarContainer.appendChild(e);var o=void 0!==E.config.appendTo&&void 0!==E.config.appendTo.nodeType;if((E.config.inline||E.config.static)&&(E.calendarContainer.classList.add(E.config.inline?"inline":"static"),E.config.inline&&(!o&&E.element.parentNode?E.element.parentNode.insertBefore(E.calendarContainer,E._input.nextSibling):void 0!==E.config.appendTo&&E.config.appendTo.appendChild(E.calendarContainer)),E.config.static)){var s=f("div","flatpickr-wrapper");E.element.parentNode&&E.element.parentNode.insertBefore(s,E.element),s.appendChild(E.element),E.altInput&&s.appendChild(E.altInput),s.appendChild(E.calendarContainer)}E.config.static||E.config.inline||(void 0!==E.config.appendTo?E.config.appendTo:window.document.body).appendChild(E.calendarContainer)}(),function(){if(E.config.wrap&&["open","close","toggle","clear"].forEach(function(e){Array.prototype.forEach.call(E.element.querySelectorAll("[data-"+e+"]"),function(n){return P(n,"click",E[e])})}),E.isMobile)!function(){var e=E.config.enableTime?E.config.noCalendar?"time":"datetime-local":"date";E.mobileInput=f("input",E.input.className+" flatpickr-mobile"),E.mobileInput.tabIndex=1,E.mobileInput.type=e,E.mobileInput.disabled=E.input.disabled,E.mobileInput.required=E.input.required,E.mobileInput.placeholder=E.input.placeholder,E.mobileFormatStr="datetime-local"===e?"Y-m-d\\TH:i:S":"date"===e?"Y-m-d":"H:i:S",E.selectedDates.length>0&&(E.mobileInput.defaultValue=E.mobileInput.value=E.formatDate(E.selectedDates[0],E.mobileFormatStr)),E.config.minDate&&(E.mobileInput.min=E.formatDate(E.config.minDate,"Y-m-d")),E.config.maxDate&&(E.mobileInput.max=E.formatDate(E.config.maxDate,"Y-m-d")),E.input.getAttribute("step")&&(E.mobileInput.step=String(E.input.getAttribute("step"))),E.input.type="hidden",void 0!==E.altInput&&(E.altInput.type="hidden");try{E.input.parentNode&&E.input.parentNode.insertBefore(E.mobileInput,E.input.nextSibling)}catch(e){}P(E.mobileInput,"change",function(e){E.setDate(p(e).value,!1,E.mobileFormatStr),ve("onChange"),ve("onClose")})}();else{var e=s(oe,50);if(E._debouncedChange=s(k,300),E.daysContainer&&!/iPhone|iPad|iPod/i.test(navigator.userAgent)&&P(E.daysContainer,"mouseover",function(e){"range"===E.config.mode&&re(p(e))}),P(window.document.body,"keydown",te),E.config.inline||E.config.static||P(window,"resize",e),void 0!==window.ontouchstart?P(window.document,"touchstart",Z):P(window.document,"mousedown",Z),P(window.document,"focus",Z,{capture:!0}),!0===E.config.clickOpens&&(P(E._input,"focus",E.open),P(E._input,"click",E.open)),void 0!==E.daysContainer&&(P(E.monthNav,"click",Oe),P(E.monthNav,["keyup","increment"],R),P(E.daysContainer,"click",le)),void 0!==E.timeContainer&&void 0!==E.minuteElement&&void 0!==E.hourElement){var n=function(e){return p(e).select()};P(E.timeContainer,["increment"],N),P(E.timeContainer,"blur",N,{capture:!0}),P(E.timeContainer,"click",F),P([E.hourElement,E.minuteElement],["focus","click"],n),void 0!==E.secondElement&&P(E.secondElement,"focus",function(){return E.secondElement&&E.secondElement.select()}),void 0!==E.amPM&&P(E.amPM,"click",function(e){N(e),k()})}E.config.allowInput&&P(E._input,"blur",ne)}}(),(E.selectedDates.length||E.config.noCalendar)&&(E.config.enableTime&&x(E.config.noCalendar?E.latestSelectedDateObj:void 0),be(!1)),T();var n=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);!E.isMobile&&n&&ce(),ve("onReady")}(),E}function T(e,n){for(var t=Array.prototype.slice.call(e).filter(function(e){return e instanceof HTMLElement}),r=[],o=0;o{var l={setCustomize:()=>{}},d=function(e,n){if(!n||1===n)return e.store;var t=e.store.modules&&e.store.modules.team;return t?t.getTeam(n):void 0},h=function(n,t){n.emit("UPDATE",{teams:t.stores,roTeams:t.roStores,id:t.channel,loading:!t.ready&&!t.cacheready,readOnly:t.readOnly||!t.ready&&t.cacheready||t.offline,offline:t.offline,deleted:!t.stores.length,restricted:t.restricted,owned:n.Store.isOwned(t.owners),content:e.clone(t.proxy),hashes:t.hashes},n.clients)},p=function(e,n){var t=e.calendars[n];t&&t.reminders&&Object.keys(t.reminders).forEach(function(e){Array.isArray(t.reminders[e])&&t.reminders[e].forEach(function(e){clearTimeout(e)})})},v=function(e,n){var t=e.calendars[n];t&&(t.stores.length||(t.lm.stop(),p(e,n),delete e.calendars[n]))},y=function(e,n,t){n.stores.forEach(function(r){var o=d(e,r);if(o&&o.proxy&&o.rpc&&o.proxy.calendars){var a=o.proxy.calendars[n.channel];a&&(a.color!==t.color&&(a.color=t.color),a.title!==t.title&&(a.title=t.title))}})},m=function(n,t,r,o){var a=+new Date,i=e.clone(r),s=i.id;if(Array.isArray(t[s])&&t[s].forEach(function(e){clearTimeout(e)}),t[s]=[],!r.deleted){var u=e.find(n,["store","proxy","hideReminders",s])||[],f=n.store.data.lastVisit;if(i.isAllDay&&(i.startDay&&(i.start=+c.parseDate(i.startDay)),i.endDay)){var l=c.parseDate(i.endDay);l.setHours(23),l.setMinutes(59),l.setSeconds(59),i.end=+l}var d=a-6048e5,h=o&&i.start>f&&i.end<=a&&i.end>d;if(i.end<=a&&!h)return delete t[s],void function(n,t){var r=e.find(n,["store","proxy","hideReminders"])||{};Object.keys(r).filter(function(e){return e===t}).forEach(function(e){delete r[e]})}(n,s);var p=!1,v=function(t){p=!0,n.Store.onReadyEvt.reg(function(){!function(t){if(!e.find(n,["store","proxy","settings","general","calendar","hideNotif"])){var r=i.start<=a?i.start:+new Date;n.store.mailbox.showMessage("reminders",{msg:{ctime:r,type:"REMINDER",missed:Boolean(h),content:i},hash:"REMINDER|"+s+"-"+t},null,function(){})}}(t)})},y=i.reminders||[];y.sort(function(e,n){return e-n}),y.some(function(e){var n=a+6e4*e;if(!u.some(function(n){return e>=n}))return i.start-n>=2147483647||(i.start<=n?(v(e),!0):void t[s].push(setTimeout(function(){v(e)},i.start-n)))}),p||n.Store.onReadyEvt.reg(function(){n.store.mailbox.hideMessage("reminders",{hash:"REMINDER|"+s},null,function(){})})}},g=function(n,t,r,o){var i=function(e){var n=new Date,t=new Date(n.getFullYear(),n.getMonth()-1,15),r=new Date(n.getFullYear(),n.getMonth()+1,15),o=a.getMonthId(t),i=a.getMonthId(n),s=a.getMonthId(r),c=a.getRecurring([o,i,s],[e]),u=[e];return Array.prototype.push.apply(u,c),u}(e.clone(r));i.forEach(function(e){m(n,t,e,o)})},E=function(e,n,t){var r=e.calendars[n];t&&r&&r.reminders&&(1===r.stores.length&&0===r.stores[0]||g(e,r.reminders,t))},b=function(n,t,r){var o=n.calendars[t];if(o&&o.reminders&&!Object.keys(o.reminders).length&&(1!==o.stores.length||0!==o.stores[0])){var a=e.find(o,["proxy","content"]);a&&Object.keys(a).forEach(function(e){g(n,o.reminders,a[e],r)})}},O=function(t,r,a){var c=e.once(e.mkAsync(a||function(){})),l=r.storeId,v=r.data,m=v.channel;if(m){var g=t.calendars[m],O=function(){h(t,g)};if(g){if(g.readOnly&&v.href){var A=n.parsePadUrl(v.href),w=n.getSecrets("calendar",A.hash,v.password),D=u.createEncryptor(w.keys);g.hashes.editHash=n.getEditHashFromKeys(w),g.lm.setReadOnly(!1,D),g.readOnly=!1}else if(0===l)return 1===g.stores.length&&0===g.stores[0]&&g.tempId.length&&r.cId&&g.tempId.push(r.cId),void c();return-1!==g.roStores.indexOf(l)&&v.href&&(g.roStores.splice(g.roStores.indexOf(l),1),-1!==g.stores.indexOf(0)&&g.stores.splice(g.stores.indexOf(0),1),O()),g.stores&&-1!==g.stores.indexOf(l)?void c():(-1!==g.stores.indexOf(0)&&(g.stores.splice(g.stores.indexOf(0),1),g.tempId=[]),g.stores.push(l),v.href||g.roStores.push(l),O(),void c())}g=t.calendars[m]={ready:!1,channel:m,readOnly:!v.href,tempId:[],stores:[l],roStores:v.href?[]:[l],reminders:{},hashes:{}},0===l&&g.tempId.push(r.cId);var _=n.parsePadUrl(v.href||v.roHref),T=n.getSecrets("calendar",_.hash,v.password),S=u.createEncryptor(T.keys);g.hashes.viewHash=n.getViewHashFromKeys(T),v.href&&(g.hashes.editHash=n.getEditHashFromKeys(T)),g.proxy={metadata:{color:v.color,title:v.title}},O();var N=function(){g.stores.forEach(function(e){var n=d(t,e);n&&n.rpc&&n.proxy.calendars&&(delete n.proxy.calendars[m],(n.unpin||t.unpinPads)([m],function(e){e&&e.error&&console.error(e.error)}))}),g.lm&&g.lm.stop(),g.stores=[],h(t,g),p(t,m),delete t.calendars[m]};i(function(e){t.store.network&&!r.isNew&&t.Store.isNewChannel(null,m,e(function(n){if(!n||!n.error)return n&&"boolean"==typeof n.isNew&&n.isNew?(N(),c({error:"EDELETED"}),void e.abort()):void 0}))}).nThen(function(){var e;if(1!==l&&l){var n=t.store.modules.team&&t.store.modules.team.getTeamsData(),a=n&&n[l];e=a?a.edPublic:void 0}else e=t.store.proxy.edPublic;var i={data:{},network:t.store.network||t.store.networkPromise,channel:T.channel,crypto:S,owners:[e],ChainPad:f,validateKey:T.keys.validateKey||void 0,userName:"calendar",Cache:o,classic:!0,onRejected:t.Store&&t.Store.onRejected},u=s.create(i);g.lm=u;var d=g.proxy=u.proxy,h=!1,p=function(){h||(h=!0,setTimeout(function(){h=!1,O()}))};u.proxy.on("cacheready",function(){d.metadata&&(g.cacheready=!0,p(),c&&c(null,u.proxy),b(t,m,r.lastVisitNotif))}).on("ready",function(e){var n=e.metadata;if(g.owners=n.owners||[],g.ready=!0,!d.metadata){if(!r.isNew)return void N();d.metadata={color:v.color,title:v.title}}p(),c&&c(null,u.proxy),b(t,m,r.lastVisitNotif)}).on("change",[],function(){g.ready&&p()}).on("change",["content"],function(e,n,r){2!==r.length||!n||e?2!==r.length||n||!e?(r.length>=3&&["start","reminders","isAllDay"].includes(r[2])||r.length>=6&&["start","reminders","isAllDay"].includes(r[5]))&&setTimeout(function(){E(t,m,d.content[r[1]])}):E(t,m,{id:r[1],start:0}):E(t,m,n)}).on("remove",["content"],function(e,n){p(),(n.length>=3&&"reminders"===n[2]||n.length>=6&&"reminders"===n[5])&&setTimeout(function(){E(t,m,d.content[n[1]])})}).on("change",["metadata"],function(){var e=d.metadata;e&&e.title&&e.color&&y(t,g,e)}).on("disconnect",function(){g.offline=!0,p()}).on("reconnect",function(){g.offline=!1,p()}).on("error",function(e){e&&e.error&&("EDELETED"!==e.error?("ERESTRICTED"===e.error&&(g.restricted=!0,p()),c(e)):N())})})}},A=function(e,n){if(n.href&&-1===n.href.indexOf("#"))if(e.secondaryKey)try{n.href=e.userObject.cryptor.decrypt(n.href)}catch(e){console.error(e),delete n.href}else delete n.href},w=function(n,t){var r=t.proxy.calendars,o=t.id||1;t.proxy.on("change",["calendars"],function(r,a,i){i.length<2||(r&&!a&&function(){var e=i[1],t=n.calendars[e];if(t){var r=t.stores.indexOf(o);if(-1!==r){t.stores.splice(r,1);var a=t.roStores.indexOf(o);-1!==a&&t.roStores.splice(a,1),v(n,e),h(n,t)}}}(),!r&&a&&function(){var r=i[1],a=t.proxy.calendars[r];if(a){var s=e.clone(a);A(t,s),O(n,{storeId:o,data:s})}}())}),Object.keys(r||{}).forEach(function(a){var i=e.clone(r[a]);A(t,i),O(n,{storeId:o,lastVisitNotif:!0,data:i})})},D=function(e,t,o,a){var i=d(e,t.teamId);if(i)if(i.rpc){var s,c,u,f=i.proxy.calendars=i.proxy.calendars||{},l=(s=n.createRandomHash("calendar"),c=n.getSecrets("calendar",s),u=n.getViewHashFromKeys(c),{href:n.hashToHref(s,"calendar"),roHref:n.hashToHref(u,"calendar"),channel:c.channel});l.color=t.color,l.title=t.title,O(e,{storeId:i.id||1,data:l,isNew:!0},function(n){if(n)return console.error(n),void a({error:n.error});var t=e.calendars[l.channel];r.whenRealtimeSyncs(t.lm.realtime,function(){f[l.channel]=l,(i.pin||e.pinPads)([l.channel],function(e){e&&e.error&&console.error(e.error)}),e.Store.onSync(i.id,a)})})}else a({error:"EFORBIDDEN"});else a({error:"NO_STORE"})};return l.init=function(t,o,a){var s={},c=t.store,u={loggedIn:c.loggedIn&&c.proxy.edPublic,store:c,Store:t.Store,pinPads:t.pinPads,unpinPads:t.unpinPads,updateMetadata:t.updateMetadata,emit:a,onReady:e.mkEvent(!0),calendars:{},clients:[]};return function(e,n){var t=e.store.proxy;t.calendars=t.calendars||{},setTimeout(n)}(u,o(function(e){e||function(e){w(e,e.store);var n=e.store.modules.team&&e.store.modules.team.getTeamsData();n&&Object.keys(n).forEach(function(n){var t=d(e,n);w(e,t)})}(u)})),u.store.proxy.on("change",["hideReminders"],function(e,n,t){var r=t[1].split("|")[0];Object.keys(u.calendars).some(function(e){var n=u.calendars[e];if(n&&n.proxy&&n.proxy.content)return n.proxy.content[r]?(setTimeout(function(){E(u,e,n.proxy.content[r])}),!0):void 0})}),s.closeTeam=function(e){Object.keys(u.calendars).forEach(function(n){var t=u.calendars[n],r=t.stores.indexOf(e);if(-1!==r){t.stores.splice(r,1);var o=t.roStores.indexOf(e);-1!==o&&t.roStores.splice(o,1),v(u,n),h(u,t)}})},s.openTeam=function(e){var n=d(u,e);n&&w(u,n)},s.upgradeTeam=function(n){if(n){var t=d(u,n);t&&Object.keys(u.calendars).forEach(function(r){var o=u.calendars[r];if(-1!==o.stores.indexOf(n)){var a=t.proxy.calendars[r],i=e.clone(a);A(t,i),O(u,{storeId:n,data:i}),h(u,o)}})}},s.removeClient=function(e){!function(e,n){var t=e.clients.indexOf(n);-1!==t&&e.clients.splice(t,1),Object.keys(e.calendars).forEach(function(t){var r=e.calendars[t];if(1===r.stores.length&&0===r.stores[0]&&r.tempId.length){var o=r.tempId.indexOf(n);-1!==o&&r.tempId.splice(o,1),r.tempId.length||(r.stores=[],v(e,t))}})}(u,e)},s.execCommand=function(t,o,a){var s=o.cmd,c=o.data;if("SUBSCRIBE"!==s){if("OPEN"!==s)return"IMPORT"===s?u.store.offline?void a({error:"OFFLINE"}):u.loggedIn?void function(t,r,o,a){var i=r.id,s=t.calendars[i];if(s)if(Array.isArray(s.stores)&&-1!==s.stores.indexOf(r.teamId)){var c=t.store,u=c.proxy.calendars=c.proxy.calendars||{},f=s.hashes.editHash,l=s.hashes.viewHash;u[i]={href:f&&n.hashToHref(f,"calendar"),roHref:l&&n.hashToHref(l,"calendar"),channel:i,color:e.find(s,["proxy","metadata","color"])||e.getRandomColor(),title:e.find(s,["proxy","metadata","title"])||"..."},t.Store.onSync(null,a),O(t,{storeId:1,data:{href:u[i].href,toHref:u[i].roHref,channel:i}})}else a({error:"EINVAL"});else a({error:"ENOENT"})}(u,c,0,a):void a({error:"NOT_LOGGED_IN"}):"IMPORT_ICS"===s?u.store.offline?void a({error:"OFFLINE"}):void function(e,n,t,o){var a=n.id,i=e.calendars[a];if(i&&i.proxy){var s=n.json;i.proxy.content=i.proxy.content||{},Object.keys(s).forEach(function(n){i.proxy.content[n]=s[n],E(e,a,s[n])}),r.whenRealtimeSyncs(i.lm.realtime,function(){h(e,i),o()})}else o({error:"ENOENT"})}(u,c,0,a):"ADD"===s?u.store.offline?void a({error:"OFFLINE"}):u.loggedIn?void function(t,r,o,a){var i=d(t,r.teamId);if(i)if(i.rpc){var s=i.proxy.calendars=i.proxy.calendars||{},c=n.parsePadUrl(r.href),u=n.getSecrets(c.type,c.hash,r.password);if(u.channel===r.channel){var f=n.getEditHashFromKeys(u),l=n.getViewHashFromKeys(u),h=f&&n.hashToHref(f,"calendar"),p={href:h,roHref:l&&n.hashToHref(l,"calendar"),color:r.color,title:r.title,channel:r.channel};!s[r.channel]||!s[r.channel].href&&p.href?(p.color=r.color,p.title=r.title,O(t,{storeId:i.id||1,data:e.clone(p)},function(e){if(e)return console.error(e),void a({error:e.error});if(h&&i.id&&i.secondaryKey)try{p.href=i.userObject.cryptor.encrypt(h)}catch(e){console.error(e)}s[p.channel]=p,(i.pin||t.pinPads)([p.channel],function(e){e&&e.error&&console.error(e.error)}),t.Store.onSync(i.id,a)})):a()}else a({error:"EINVAL"})}else a({error:"EFORBIDDEN"});else a({error:"NO_STORE"})}(u,c,0,a):void a({error:"NOT_LOGGED_IN"}):"CREATE"===s?u.loggedIn?c.initialCalendar?void u.Store.onReadyEvt.reg(function(){D(u,c,0,a)}):u.store.offline?void a({error:"OFFLINE"}):void D(u,c,0,a):void a({error:"NOT_LOGGED_IN"}):"UPDATE"===s?u.store.offline?void a({error:"OFFLINE"}):void function(n,t,o,a){var i=t.id,s=n.calendars[i];if(s){var c=e.find(s,["proxy","metadata"]);c?(c.title=t.title,c.color=t.color,r.whenRealtimeSyncs(s.lm.realtime,a),h(n,s),y(n,s,t)):a({error:"EINVAL"})}else a({error:"ENOENT"})}(u,c,0,a):"DELETE"===s?u.store.offline?void a({error:"OFFLINE"}):u.loggedIn?void function(e,n,t,r){var o=d(e,n.teamId);if(o)if(o.rpc){if(o.proxy.calendars){var a=n.id;if(o.proxy.calendars[a]){delete o.proxy.calendars[a],(o.unpin||e.unpinPads)([a],function(e){e&&e.error&&console.error(e.error)});var i=e.calendars[a],s=i.stores.indexOf(o.id||1);i.stores.splice(s,1),v(e,a),e.Store.onSync(o.id,function(){h(e,i),r()})}else r()}}else r({error:"EFORBIDDEN"});else r({error:"NO_STORE"})}(u,c,0,a):void a({error:"NOT_LOGGED_IN"}):"CREATE_EVENT"===s?u.store.offline?void a({error:"OFFLINE"}):void function(e,n,t,o){var a=n.calendarId,i=e.calendars[a];if(i){var s=new Date(n.start),c=new Date(n.end);n.isAllDay?(n.startDay=s.getFullYear()+"-"+(s.getMonth()+1)+"-"+s.getDate(),n.endDay=c.getFullYear()+"-"+(c.getMonth()+1)+"-"+c.getDate()):(delete n.startDay,delete n.endDay),i.proxy.content=i.proxy.content||{},i.proxy.content[n.id]=n,r.whenRealtimeSyncs(i.lm.realtime,function(){E(e,a,n),h(e,i),o()})}else o({error:"ENOENT"})}(u,c,0,a):"UPDATE_EVENT"===s?u.store.offline?void a({error:"OFFLINE"}):void function(n,t,o,a){if(t&&t.ev){var s=t.ev.calendarId,c=n.calendars[s];if(c&&c.proxy&&c.proxy.content){var u=c.proxy.content[t.ev.id];if(u){t.rawData=t.rawData||{};var f,l=t.changes||{},d=t.type||{};if(l.calendarId){if(!(f=n.calendars[l.calendarId])||!f.proxy)return void a({error:"ENOENT"});f.proxy.content=f.proxy.content||{}}var p={one:{},from:{}};["one","from","all"].includes(d.which)&&(u.recUpdate=u.recUpdate||p,u.recUpdate.one||(u.recUpdate.one={}),u.recUpdate.from||(u.recUpdate.from={}));var v=u.recUpdate,y=["calendarId"],m=Object.keys(l).filter(function(e){return!y.includes(e)}),g=function(e){[v.from,v.one].forEach(function(n){Object.keys(n).forEach(function(t){Number(t){const r=[],o=null==Xt?void 0:Xt.httpUnsafeOrigin;ie.fetchApi(o,"config",!0,e=>{var o,a;(null===(o=null==e?void 0:e.adminKeys)||void 0===o?void 0:o.includes(n))&&r.push("admin");(null===(a=null==e?void 0:e.moderatorKeys)||void 0===a?void 0:a.includes(n))&&r.push("moderator"),t(r)})},er=(e,n,t)=>{e.Store.anonRpcMsg("",{msg:"IS_PREMIUM",data:n},e=>{let n=Array.isArray(e)&&e[0];t(n?["premium"]:[])})},nr=(e,n,t,r)=>{var o,a;const i=[];null==Xt||Xt.httpUnsafeOrigin;const s=n.edPublic||(null===(a=null===(o=e.store)||void 0===o?void 0:o.proxy)||void 0===a?void 0:a.edPublic);rt(e=>{$t(0,s,e(e=>{Array.prototype.push.apply(i,e)}))}).nThen(n=>{er(e,s,n(e=>{Array.prototype.push.apply(i,e)}))}).nThen(()=>{r(i)})},tr={admin:$t,moderator:$t,premium:er},rr={init:(e,n,t)=>{const r={store:e.store,Store:e.Store,updateMetadata:e.updateMetadata},o=r.Store;return o.onReadyEvt.reg(()=>{var e;const n=o.getMetadata(void 0,"drive",()=>{}),t=(null===(e=null==n?void 0:n.user)||void 0===e?void 0:e.badge)||"";t&&nr(r,{},0,e=>{var n,o;if(!e.includes(t)){const e=null===(o=null===(n=null==r?void 0:r.store)||void 0===n?void 0:n.modules)||void 0===o?void 0:o.profile;null==e||e.execCommand(void 0,{cmd:"SET",data:{key:"badge",value:""}},()=>{})}})}),{listBadges:(e,n)=>{nr(r,e,0,n)},removeClient:()=>{},execCommand:(e,n,t)=>{const o=n.cmd,a=n.data;"LIST_BADGES"!==o?"CHECK_BADGE"!==o?t():((e,n,t,r)=>{const{badge:o,ed:a,sig:i,nid:s}=n,c=ie.decodeBase64(a),u=ie.decodeBase64(i),f=Zt.sign.open(u,c);if(!f)return void r({verified:!1});if(ie.encodeUTF8(f)!==s)return void r({verified:!1});let l=tr[o];l?l(e,a,e=>{r({verified:e.includes(o),badge:o})}):r({verified:!1,error:"EINVAL"})})(r,a,0,t):nr(r,a,0,t)}}},setCustomize:e=>{Xt=null==e?void 0:e.ApiConfig}};var or,ar,ir=o(Object.freeze({__proto__:null,Badge:rr}));function sr(){if(ar)return or;ar=1;return or=((e,n,t,r,o,a,i,s,c,u,f,l,d,h,p,v,y,m,g,E,b,O,A,w,D,_,T,S,N,I,x,C,R,P,k,M)=>{const F=p.Account,L=v.Drive,H=y.Pad,j=S.Badge,K=globalThis;globalThis.nacl=globalThis.nacl||x.Nacl;let U={},B={};const V=a.Saferphore;var Y=a.mkEvent(!0),G=a.mkEvent(!0),J=a.mkEvent(!0);var q={drive:{hideDuplicate:!0},pad:{width:!0,spellcheck:!0},security:{unsafeLinks:!1},general:{allowUserFeedback:!0}};return{setCustomize:e=>{U=e.ApiConfig,B=e.AppConfig},create:function(p){var v=K.Cryptpad_Store={};let y=p.query||function(){},S=p.broadcast||function(){};var C=K.CryptPad_AsyncStore={modules:{}};v.onReadyEvt=Y,v.pad=H.init({Store:v,store:C,postMessage:y,broadcast:S}),v.drive=L.initAPI({Store:v,store:C,postMessage:y,broadcast:S});var R=[],P=C.sendDriveEvent=function(e,n,t){R.forEach(function(r){r!==t&&y(r,e,n)})},W=v.getStore=function(e){if(!e)return C;try{var n=C.modules.team.getTeam(e);return n||void console.error("Team not found",e)}catch(n){return console.error(n),void console.error("Team not found",e)}},z=v.onSync=function(e,n){var t=W(e);t?M(function(e){if(t.realtime&&c.whenRealtimeSyncs(t.realtime,e()),!t.id&&t.drive?.realtime&&c.whenRealtimeSyncs(t.drive.realtime,e()),t.sharedFolders&&"object"==typeof t.sharedFolders)for(var n in t.sharedFolders)t.sharedFolders[n].realtime&&c.whenRealtimeSyncs(t.sharedFolders[n].realtime,e())}).nThen(function(){n()}):n({error:"ENOTFOUND"})};v.get=function(e,n,t){var r=W(n.teamId);r?r.proxy?t(a.find(r.proxy,n.key)):t({error:"ENODRIVE"}):t({error:"ENOTFOUND"})},v.set=function(e,n,t){var r=W(n.teamId);if(r)if(r.proxy){var o=n.key.slice(),i=o.pop(),s=a.find(r.proxy,o);s&&"object"==typeof s?(void 0===n.value?delete s[i]:s[i]=n.value,n.teamId||(S([e],"UPDATE_METADATA"),Array.isArray(o)&&"profile"===o[0]&&C.messenger&&u.updateMyData(C)),z(n.teamId,t)):t({error:"INVALID_PATH"})}else t({error:"ENODRIVE"});else t({error:"ENOTFOUND"})},v.getSharedFolder=function(e,t,r){var o,i=W(t.teamId),s=t.id;if(i&&i.manager){if(i.manager.folders[s])return(o=a.clone(i.manager.folders[s].proxy)).offline=Boolean(i.manager.folders[s].offline),void r(o);var c=a.find(i.proxy,["drive",n.SHARED_FOLDERS])||{};c[s]?v.loadSharedFolder(t.teamId,s,c[s],function(){r(i.manager.folders[s].proxy)}):r({})}else r({error:"ENOTFOUND"})},v.restoreSharedFolder=function(e,n,t){if(n.sfId&&n.drive){var r=W(n.teamId);r.sharedFolders[n.sfId]&&(Object.keys(n.drive).forEach(function(e){r.sharedFolders[n.sfId].proxy[e]=n.drive[e]}),Object.keys(r.sharedFolders[n.sfId].proxy).forEach(function(e){n.drive[e]||delete r.sharedFolders[n.sfId].proxy[e]})),z(n.teamId,t)}else t({error:"EINVAL"})},v.hasSigningKeys=function(){if(C.proxy)return"string"==typeof C.proxy.edPrivate&&"string"==typeof C.proxy.edPublic},v.hasCurveKeys=function(){if(C.proxy)return"string"==typeof C.proxy.curvePrivate&&"string"==typeof C.proxy.curvePublic},v.isOwned=function(e){var n=C.proxy.edPublic;if(!n)return!1;if(!Array.isArray(e)||!e.length)return!1;if(-1!==e.indexOf(n))return!0;var t=C.proxy.teams;return!!t&&Object.keys(t).some(function(n){var r=a.find(t[n],["keys","drive","edPublic"]);return r&&-1!==e.indexOf(r)})};var Q=function(e){var n=e?C.manager.getChannelsList("expirable"):function(){var e=`${C.driveChannel}#drive`;if(!e)return null;var n=C.manager.getChannelsList("pin"),t=C.proxy.profile;if(t){var r=t.edit?o.hrefToHexChannelId("/profile/#"+t.edit,null):null;r&&n.push(r);var a=t.avatar?o.hrefToHexChannelId(t.avatar,null):null;a&&n.push(a)}if(C.proxy.todo&&n.push(o.hrefToHexChannelId("/todo/#"+C.proxy.todo,null)),C.proxy.friends){var i=u.getFriendChannelsList(C.proxy);n=n.concat(i)}if(C.proxy.mailboxes){var s=Object.keys(C.proxy.mailboxes).map(function(e){if("broadcast"!==e||C.isAdmin)return C.proxy.mailboxes[e].channel}).filter(Boolean);n=n.concat(s)}if(C.proxy.calendars){var c=Object.keys(C.proxy.calendars).map(function(e){return C.proxy.calendars[e].channel});n=n.concat(c)}return n.push(e),C.data&&C.data.blockId&&n.push(`${C.data.blockId}#block`),n.sort(),n}();return a.deduplicateString(n).sort()};v.pinPads=function(e,n,t){if(n){var r=W(n&&n.teamId);if(r.rpc){"function"!=typeof t&&(console.error("expected a callback"),t=function(){});var o=n.pads||n;r.rpc.pin(o,function(e){t(e?{error:e}:{})})}else t({error:"RPC_NOT_READY"})}else t({error:"EINVAL"})},v.unpinPads=function(e,n,t){if(n){var r=W(n&&n.teamId);if(r.rpc){var o=n.pads||n;r.rpc.unpin(o,function(e){t(e?{error:e}:{})})}else t({error:"RPC_NOT_READY"})}else t({error:"EINVAL"})};var Z=C.account={};v.getPinnedUsage=function(e,n,t){var r=W(n&&n.teamId);r&&r.rpc?r.rpc.getFileListSize(function(e,n){r.id||"number"!=typeof n||(Z.usage=n),t({bytes:n})}):t({error:"RPC_NOT_READY"})},v.getPinLimit=function(e,n,t){var r=W(n&&n.teamId);r.rpc?r.rpc.getLimit(function(e,n,o,a){if(e)t({error:e});else{var i=r.id?{}:Z;i.limit=n,i.plan=o,i.note=a,t(i)}}):t({error:"RPC_NOT_READY"})};v.uploadComplete=function(e,n,t){var r=W(n.teamId);r?r.rpc?n.owned?r.rpc.ownedUploadComplete(n.id,function(e,n){t(e?{error:e}:n)}):r.rpc.uploadComplete(n.id,function(e,n){t(e?{error:e}:n)}):t({error:"RPC_NOT_READY"}):t({error:"ENOTFOUND"})},v.uploadStatus=function(e,n,t){var r=W(n.teamId);r?r.rpc?r.rpc.uploadStatus(n.size,function(e,n){t(e?{error:e}:n)}):t({error:"RPC_NOT_READY"}):t({error:"ENOTFOUND"})},v.uploadCancel=function(e,n,t){var r=W(n.teamId);r?r.rpc?r.rpc.uploadCancel(n.size,function(e,n){t(e?{error:e}:n)}):t({error:"RPC_NOT_READY"}):t({error:"ENOTFOUND"})},v.uploadChunk=function(e,n,t){var r=W(n.teamId);r?r.rpc?r.rpc.send.unauthenticated("UPLOAD",n.chunk,function(e,n){t({error:e,msg:n})}):t({error:"RPC_NOT_READY"}):t({error:"ENOTFOUND"})};v.anonRpcMsg=function(e,n,t){C.anon_rpc?C.anon_rpc.send(n.msg,n.data,function(e,n){t(e?{error:e}:n)}):t({error:"ANON_RPC_NOT_READY"})},v.getFileSize=function(e,n,t){var r=a.once(a.mkAsync(t));if(C.anon_rpc){var i=n.channel||o.hrefToHexChannelId(n.href,n.password);C.anon_rpc.send("GET_FILE_SIZE",i,function(e,n){if(!e)return n&&n.length&&"number"==typeof n[0]?(0===n[0]&&d.clearChannel(i),void r({size:n[0]})):void r({error:"INVALID_RESPONSE"});r({error:e})})}else r({error:"ANON_RPC_NOT_READY"})},v.isNewChannel=function(e,n,t){if(C.anon_rpc){var r=n.channel||o.hrefToHexChannelId(n.href,n.password);C.anon_rpc.send("IS_NEW_CHANNEL",r,function(e,n){if(!e)return n&&n.length&&"object"==typeof n[0]?(n[0].isNew&&d.clearChannel(r),void t(n[0])):void t({error:"INVALID_RESPONSE"});t({error:e})})}else t({error:"ANON_RPC_NOT_READY"})},v.getMultipleFileSize=function(e,n,t){C.anon_rpc?Array.isArray(n.files)?C.anon_rpc.send("GET_MULTIPLE_FILE_SIZE",n.files,function(e,n){e?t({error:e}):n&&n.length&&"object"==typeof n[0]?t({size:n[0]}):t({error:"UNEXPECTED_RESPONSE"})}):t({error:"INVALID_FILE_LIST"}):t({error:"ANON_RPC_NOT_READY"})},v.getDeletedPads=function(e,n,t){if(C.anon_rpc){var r=n&&n.list||Q(!0);Array.isArray(r)?C.anon_rpc.send("GET_DELETED_PADS",r,function(e,n){e?t({error:e}):n&&n.length&&Array.isArray(n[0])?t(n[0]):t({error:"UNEXPECTED_RESPONSE"})}):t({error:"INVALID_FILE_LIST"})}else t({error:"ANON_RPC_NOT_READY"})};var X=function(e,n,t){C.anon_rpc?t():l.createAnonymous(C.network,function(e,n){e?t({error:e}):(C.anon_rpc=n,t())})},$=v.getAllStores=function(){if(!C.proxy||!C.manager)return[];var e=[C],n=C.modules.team;if(n){var t=n.getTeams().map(function(e){return n.getTeam(e)});Array.prototype.push.apply(e,t)}return e};v.getUserColor=function(){var e=a.find(C,["proxy","settings","general","cursor","color"]);return e||(e=a.getRandomColor(!0),v.setAttribute(null,{attr:["general","cursor","color"],value:e},function(){})),e},v.getMetadata=function(e,n,t){var r=C.proxy||{},s=a.find(r,["settings","general","disableThumbnails"]),c=C.modules.team&&C.modules.team.getTeamsData(n)||{};r.uid||(C.noDriveUid=C.noDriveUid||o.createChannelId());var u={user:{name:r[i.displayNameKey]||C.noDriveName||"",uid:r.uid||C.noDriveUid,avatar:a.find(r,["profile","avatar"]),profile:a.find(r,["profile","view"]),color:v.getUserColor(),notifications:a.find(r,["mailboxes","notifications","channel"]),curvePublic:r.curvePublic,edPublic:r.edPublic,netfluxId:C?.network?.webChannels?.[0]?.myID,badge:a.find(r,["profile","badge"])},priv:{clientId:e,edPublic:r.edPublic,edPrivate:r.edPrivate,friends:r.friends||{},settings:r.settings||q,thumbnails:!1===s,isDriveOwned:Boolean(a.find(C,["driveMetadata","owners"])),driveChannel:C.driveChannel,pendingFriends:r.friends_pending||{},supportPrivateKey:a.find(r,["mailboxes","supportadmin","keys","curvePrivate"]),accountName:r.login_name||"",offline:C.proxy&&C.offline,teams:c,plan:C.ready?Z.plan||"":void 0,mutedChannels:r.mutedChannels}};return t(JSON.parse(JSON.stringify(u))),u},v.onMaintenanceUpdate=function(){let e=U.httpUnsafeOrigin;a.fetchApi(e,"broadcast",!0,e=>{e&&S([],"UNIVERSAL_EVENT",{type:"broadcast",data:{ev:"MAINTENANCE",data:e.maintenance}})})},v.onSurveyUpdate=function(){let e=U.httpUnsafeOrigin;a.fetchApi(e,"broadcast",!0,e=>{S([],"UNIVERSAL_EVENT",{type:"broadcast",data:{ev:"SURVEY",data:e.surveyURL}})})};v.addPad=function(e,t,r){if(t.href||t.roHref){var a;if(!t.roHref){var i=o.parsePadUrl(t.href);"pad"===i.hashData.type&&(a=o.getSecrets(i.type,i.hash,t.password),t.roHref="/"+i.type+"/#"+o.getViewHashFromKeys(a))}var s,c,u,f,l=(s=t.href,c=t.roHref,u=t.title,f=+new Date,{href:s,roHref:c,atime:f,ctime:f,title:u||n.getDefaultName(o.parsePadUrl(s))});t.owners&&(l.owners=t.owners),t.expire&&(l.expire=t.expire),t.password&&(l.password=t.password),(t.channel||a)&&(l.channel=t.channel||a.channel),t.readme&&(l.readme=1),Object.keys(t.attributes||{}).forEach(e=>{t.attributes[e]&&(l[e]=t.attributes[e])}),-1===t.teamId&&(t.teamId=void 0);var d=W(t.teamId);d&&d.manager?d.manager.addPad(t.path,l,function(o){o?r({error:o}):($().forEach(function(t){(t.id?t.sendEvent:P)("DRIVE_CHANGE",{path:["drive",n.FILES_DATA]},e)}),z(t.teamId,r))}):r({error:"ENOTFOUND"})}else r({error:"NO_HREF"})};var ee=function(e,n){var t=a.find(C,["proxy","edPublic"]),r=function(e){var n=[];return e?(C.proxy.todo&&n.push(o.hrefToHexChannelId("/todo/#"+C.proxy.todo,null)),C.proxy.profile&&C.proxy.profile.edit&&n.push(o.hrefToHexChannelId("/profile/#"+C.proxy.profile.edit,null)),C.proxy.mailboxes&&Object.keys(C.proxy.mailboxes||{}).forEach(function(e){if("supportadmin"!==e){var t=C.proxy.mailboxes[e];n.push(t.channel)}})):n=C.manager.getChannelsList("owned"),n.filter(function(e){if("string"==typeof e)return-1!==[32,48].indexOf(e.length)})}(e),i=V.create(10),s=function(n){e||C.manager.findChannel(n).forEach(function(e){var n=C.manager.findFile(e.id);C.manager.delete({paths:n})})};r.forEach(function(e){var r=n();i.take(function(n){var o=!1;M(function(a){32===e.length&&v.anonRpcMsg(null,{msg:"GET_METADATA",data:e},a(function(i){if(i&&i.error)return n(),r(),void a.abort();var c=i[0];return Object.keys(c||{}).length?c&&Array.isArray(c.owners)&&-1!==c.owners.indexOf(t)?void(o=c.owners.some(function(e){return e!==t})):(n(),r(),void a.abort()):(s(e),n(),r(),void a.abort())}))}).nThen(function(n){o?v.pad.setMetadata(null,{channel:e,command:"RM_OWNERS",value:[t]},n()):C.rpc.removeOwnedChannel(e,n(function(n){n?console.error(n):s(e)}))}).nThen(function(){n(),r()})})})};v.removeOwnedPads=function(e,n,t){C.proxy.edPublic?M(function(e){ee(!1,e)}).nThen(t):t({error:"NOT_LOGGED_IN"})},v.deleteAccount=function(n,t,r){var o=C.proxy.edPublic,s=t&&t.keys,c=t&&t.auth;v.anonRpcMsg(n,{msg:"GET_METADATA",data:C.driveChannel},function(t){var u=t[0];if(u&&u.owners&&1===u.owners.length&&-1!==u.owners.indexOf(o))M(function(e){N.checkRights({auth:c,blockKeys:s},e(function(n){if(n)return e.abort(),console.error(n),void r({error:"INVALID_CODE"})}))}).nThen(function(e){globalThis.accountDeletion=n,C.proxy[i.tokenKey]="DELETED",z(null,e())}).nThen(function(e){C.rpc.removePins(e(function(e){e&&console.error(e)}))}).nThen(function(e){C.ownDeletion=!0,v.pad.destroy(n,{channel:C.driveChannel,force:!0},e())}).nThen(function(e){s&&N.removeLoginBlock({reason:"ARCHIVE_OWNED",auth:c,edPublic:o,blockKeys:s},e(function(e){e&&console.error(e)}))}).nThen(function(e){ee(!0,e)}).nThen(function(){S([n],"DRIVE_DELETED","ARCHIVE_OWNED"),y(n,"DELETE_ACCOUNT","DELETED",function(){}),C.network.disconnect(),r({state:!0})});else{var f={intent:"Please delete my account."};f.drive=C.driveChannel,f.edPublic=o;var l=a.decodeBase64(C.proxy.edPrivate),d=x.Nacl.sign.detached(a.decodeUTF8(e(f)),l);x.Nacl.sign.detached.verify(a.decodeUTF8(e(f)),d,a.decodeBase64(o))||console.error("signed message failed verification");var h=a.encodeBase64(d);r({proof:h,toSign:JSON.parse(e(f))})}})},v.setDisplayName=function(e,n,t){if(!C.proxy)return C.noDriveName=n,S([e],"UPDATE_METADATA"),void t();C.modules.profile&&C.modules.profile.setName(n),C.proxy[i.displayNameKey]=n,S([e],"UPDATE_METADATA"),u.updateMyData(C),z(null,t)},v.resetDrive=function(e,n,t){M(function(e){ee(e)}).nThen(function(){C.proxy.drive=C.userObject.getStructure(),P("DRIVE_CHANGE",{path:["drive","filesData"]},e),z(null,t)})},v.setPadAttribute=function(e,t,r){M(function(r){$().forEach(function(o){o.manager.setPadAttribute(t,r(function(){(o.id?o.sendEvent:P)("DRIVE_CHANGE",{path:["drive",n.FILES_DATA]},e),z(o.id,r())}))})}).nThen(r)},v.getPadAttribute=function(e,n,t){var r={};M(function(e){$().forEach(function(t){t.manager.getPadAttribute(n,e(function(e,n){e||(n&&"object"==typeof n?(!r.value||r.atime{if(C.loggedIn&&C.proxy.edPublic){var n,r=C.modules.team,o=r&&r.getTeams()||[];-1!==e.indexOf(C.proxy.edPublic)?n=C:o.some(function(t){var o=a.find(C,["proxy","teams",t,"keys","drive","edPublic"]),i=a.find(C,["proxy","teams",t,"keys","drive","edPrivate"]);if(-1===e.indexOf(o))return!1;if(!i)return!1;var s=r.getTeam(t);return n=s,!0});var i=function(){if(n){var e=n.rpc;e?e.send("COOKIE","",function(e){t(e)}):t("ERESTRICTED")}else t("ERESTRICTED")};n&&n.onRpcReadyEvt?n.onRpcReadyEvt.reg(function(){i()}):i()}else t("ERESTRICTED")})):t("ERESTRICTED")},v.changePadPasswordPin=function(e,n,t){var r=n.oldChannel,o=n.channel;M(function(e){$().forEach(function(n){n.manager.findChannel(o).length&&(n.rpc.unpin([r],e()),n.rpc.pin([o],e()))})}).nThen(t)},v.contactPadOwner=function(e,n,t){var r=n.owners;if(!Array.isArray(r)||!r.length)return t({state:!1});n.send?M(function(e){r.forEach(function(t){!function(e,t,r,o){if(C.mailbox&&!n.anon)return C.mailbox.sendTo(e,t,r,o);O.sendToAnon(C.anon_rpc,e,t,r,o)}(n.query,{channel:n.channel,data:n.msgData},{channel:t.notifications,curvePublic:t.curvePublic},e())})}).nThen(function(){t({state:!0})}):t({state:!0})},v.givePadAccess=function(e,n,t){var r,o,a=C.proxy.edPublic,i=n.channel,s=C.manager.findChannel(i);n.user&&n.user.notifications&&n.user.curvePublic?s.some(function(e){if(e.data&&Array.isArray(e.data.owners)&&-1!==e.data.owners.indexOf(a)&&e.data.href)return r=e.data.href,o=e.data.title,!0})?(C.mailbox.sendTo("GIVE_PAD_ACCESS",{channel:i,href:r,title:o},{channel:n.user.notifications,curvePublic:n.user.curvePublic}),t()):t({error:"ENOTFOUND"}):t({error:"EINVAL"})};v.burnPad=function(e,n){var t=n.channel,r=x.b64AddSlashes(n.ownerKey||"");if(t&&r)try{var a=o.decodeBase64(r),i=x.Nacl.sign.keyPair.fromSecretKey(a);f.create(C.network,{edPublic:o.encodeBase64(i.publicKey),edPrivate:o.encodeBase64(i.secretKey)},function(e,r){e?console.error(e):v.pad.getMetadata(null,{channel:t},function(e){r.removeOwnedChannel(t,function(t){t?console.error(t):function(e,n){var t=e.channel,r=e.href,a=o.parsePadUrl(r),i=o.getSecrets(a.type,a.hash,e.password);if((!n||!n.error)&&n.mailbox){var s,c=x.createEncryptor(i.keys),u=[];try{"string"==typeof n.mailbox?u.push(c.decrypt(n.mailbox,!0,!0)):Object.keys(n.mailbox).forEach(function(e){u.push(c.decrypt(n.mailbox[e],!0,!0))})}catch(e){console.error(e)}try{s=C.proxy.curvePublic}catch(e){return void console.error(e)}u.forEach(function(e){var n=JSON.parse(e);n.curvePublic!==s&&C.mailbox.sendTo("OWNED_PAD_REMOVED",{channel:t},{channel:n.notifications,curvePublic:n.curvePublic},function(){})})}}(n,e)})})})}catch(e){console.error(e)}else console.error("Can't delete BAR pad")},v.deleteMailboxMessage=function(e,n,t){C.anon_rpc?C.anon_rpc.send("DELETE_MAILBOX_MESSAGE",n,function(e){t({error:e})}):t({error:"RPC_NOT_READY"})},v.getFullHistory=function(e,n,t){var r=C.network,o=r.historyKeeper,a=[],i=!1,s=function(e){if(!i){var o=function(e){try{return JSON.parse(e)}catch(e){return null}}(e);if(o)return"FULL_HISTORY_END"===o[0]?(t(a),r.off("message",s),void(i=!0)):void("FULL_HISTORY"===o[0]&&(o[1]&&o[1].validateKey||o[1][3]===n.channel&&(e=o[1][4])&&(e=e.replace(/cp\|(([A-Za-z0-9+\/=]+)\|)?/,""),n.debug?a.push({serverHash:e.slice(0,64),msg:e,author:o[1][1],time:o[1][5]}):a.push(e))))}};r.on("message",s),r.sendto(o,JSON.stringify(["GET_FULL_HISTORY",n.channel,n.validateKey]))},v.getHistory=function(e,n,t,r){var o=a.once(a.mkAsync(t)),i=C.network,s=i.historyKeeper,c=Math.floor(1e6*Math.random()),u=[],f=!1,l=function(e,t){if(!f&&t===s){var a=function(e){try{return JSON.parse(e)}catch(e){return null}}(e);if(a&&!(a.txid&&a.txid!==c||a.validateKey&&a.channel))if(a.error&&a.channel)a.channel===n.channel&&(i.off("message",l),f=!0,o({error:a.error}));else{if(1===a.state&&a.channel){if(a.channel!==n.channel)return;return o(u),i.off("message",l),void(f=!0)}Array.isArray(a)&&a[0]&&a[0]!==c||a[3]===n.channel&&(a[4]&&r?u.push({msg:e,hash:a[4].slice(0,64)}):(e=a[4])&&(e=e.replace(/cp\|(([A-Za-z0-9+\/=]+)\|)?/,""),u.push(e)))}}};i.on("message",l);var d={txid:c,lastKnownHash:n.lastKnownHash},h=["GET_HISTORY",n.channel,d];i.sendto(s,JSON.stringify(h))},v.getHistoryRange=function(e,n,t){var r,o=C.network,i=o.historyKeeper,s=[],c=!0,u=!1,f=!1,l=a.uid();o.on("message",function(e){if(!f){var o=function(e){try{return JSON.parse(e)}catch(e){return null}}(e);if(o[1]===l){if("HISTORY_RANGE_ERROR"===o[0]){let e=o[2];return"ENOENT"===e?.code?(f=!0,void t({messages:s,isFull:!0})):void t({error:o[2]})}if("HISTORY_RANGE_END"===o[0])return t({messages:s,isFull:u,lastKnownHash:r}),void(f=!0);"HISTORY_RANGE"===o[0]&&(o[2]&&o[1].validateKey||o[2][3]===n.channel&&(e=o[2][4])&&(c&&(/^cp\|/.test(e)||n.toHash||(u=!0),r=e.slice(0,64),c=!1),e=e.replace(/cp\|(([A-Za-z0-9+\/=]+)\|)?/,""),s.push({serverHash:e.slice(0,64),msg:e,author:o[2][1],time:o[2][5]})))}else console.log("bad txid")}}),o.sendto(i,JSON.stringify(["GET_HISTORY_RANGE",n.channel,{from:n.lastKnownHash,to:n.toHash,cpCount:n.cpCount||2,txid:l}]))};var re=function(e,t){e&&(e.deprecated||e.restricted||(t||e.on("change",["drive",n.SHARED_FOLDERS],function(t,r,a){if(a.length>3&&"password"===a[3]){var i=a[2],s=e.drive[n.SHARED_FOLDERS][i],c=C.manager.user.userObject.getHref?C.manager.user.userObject.getHref(s):s.href,u=o.parsePadUrl(c),f=o.getSecrets(u.type,u.hash,t);return h.updatePassword(v,{oldChannel:f.channel,password:r,href:c},C.network,function(){console.log("Shared folder password changed")}),!1}}),e.on("change",[],function(e,r,o){if(t){if(o[0]===n.FILES_DATA&&"object"==typeof r&&r.channel&&!r.owners){var a=[r.channel];r.rtChannel&&a.push(r.rtChannel),r.lastVersion&&a.push(r.lastVersion),v.pinPads(null,a,function(e){console.error(e)})}if(o[0]===n.FILES_DATA&&"object"==typeof e&&e.channel&&!r){var i=[e.channel];C.manager.findChannel(e.channel).some(function(e){return e.fId!==t})||(e.rtChannel&&i.push(e.rtChannel),e.lastVersion&&i.push(e.lastVersion),v.unpinPads(null,i,function(e){console.error(e)}))}}e&&!r&&Array.isArray(o)&&(o[0]===n.FILES_DATA||"drive"===o[0]&&o[1]===n.FILES_DATA)&&setTimeout(function(){v.checkDeletedPad(e&&e.channel)}),P("DRIVE_CHANGE",{id:t,old:e,new:r,path:o})}),e.on("remove",[],function(e,n){P("DRIVE_REMOVE",{id:t,old:e,path:n})})))};v.loadSharedFolder=function(e,n,t,r,a){var i=W(e);if(i){var s=o.parsePadUrl(t.href||t.roHref);s||s.hashData?h.load({isNew:a,network:C.network||C.networkPromise,store:i,Store:v,isNewChannel:v.isNewChannel},n,t,r):r({error:"EINVAL"})}else r({error:"ENOTFOUND"})};var oe=function(e,n,t,r){v.loadSharedFolder(null,e,n,t,r)};v.loadSharedFolderAnon=function(e,n,t){v.loadSharedFolder(null,n.id,n.data,function(e){t({error:e?void 0:"EDELETED"})})},v.addSharedFolder=function(e,t,r){Y.reg(function(){var o=W(t.teamId);o.manager.addSharedFolder(t,function(a){a&&"object"==typeof a&&a.error?r(a):((t.teamId?o.sendEvent:P)("DRIVE_CHANGE",{path:["drive",n.FILES_DATA]},e),r(a))})})},v.updateSharedFolderPassword=function(e,n,t){h.updatePassword(v,n,C.network,t)},v.userObjectCommand=function(e,t,r){if(t&&t.cmd){var o=W(t.teamId);if(o.offline)return(o.id?o.sendEvent:P)("NETWORK_DISCONNECT"),void r({error:"OFFLINE"});o.manager.command(t,function(o){$().forEach(function(t){(t.id?t.sendEvent:P)("DRIVE_CHANGE",{path:["drive",n.FILES_DATA]},e)}),z(t.teamId,function(){r(o)})})}},v._removeClient=function(e){var n=R.indexOf(e);-1!==n&&R.splice(n,1),C.onlyoffice?.removeClient?.(e),C.mailbox?.removeClient?.(e),Object.keys(C.modules).forEach(function(n){C.modules[n]?.removeClient?.(e)}),v.pad?.removeClient?.(e)};v.refreshDriveUI=function(){$().forEach(function(e){(e.id?e.sendEvent:P)("DRIVE_CHANGE",{path:["drive",n.FILES_DATA]})})};var ae=function(e,n){const r=a.mkAsync(n);var o=C.proxy,i=C.drive;if(C.manager)r();else{var s=C.manager=t.create(i.proxy,{onSync:function(e){z(null,e)},edPublic:o.edPublic,pin:function(e,n){C.loggedIn?v.pinPads(null,e,n):n()},unpin:function(e,n){C.loggedIn?v.unpinPads(null,e,n):n()},loadSharedFolder:oe,settings:o.settings,removeOwnedChannel:function(e,n){v.pad.destroy("",e,n)},store:C,Store:v},{outer:!0,edPublic:C.proxy.edPublic,loggedIn:C.loggedIn,log:function(e){P("DRIVE_LOG",e)},rt:i.realtime}),c=C.userObject=s.user.userObject;M(function(e){C.sharedFolders={},C.handleSharedFolder=function(e,n){n?(C.sharedFolders[e]=n,C.driveEvents&&re(n.proxy,e)):delete C.sharedFolders[e]},c.migrate(e())}).nThen(function(n){var t=C.network||C.networkPromise;h.loadSharedFolders(v,t,C,i.proxy,c,n,n=>{var t={type:"sf",progress:100*n.progress/n.max};y(e,"LOADING_DRIVE",t)},!0)}).nThen(function(n){te(w,"team",n,e)}).nThen(function(e){te(T,"calendar",e)}).nThen(function(){r()})}};const ie=(e=function(){})=>{te(m,"cursor",e),te(E,"integration",e),te(D,"messenger",e),te(_,"history",e),te(j,"badge",e),C.onlyoffice||(C.onlyoffice=b.init(C,function(e,n,t){t.forEach(function(t){y(t,"OO_EVENT",{ev:e,data:n})})})),C&&(C.messenger=C.modules.messenger)},se=(e,n,t)=>{const r=a.mkAsync(t);ae(e,function(){G.fire(),r(n)})};var ce=function(e,n,t){C.ready=!0;var c=C.proxy,u=C.manager,l=C.userObject;M(function(t){c.settings||(c.settings=q),c.forms||(c.forms={}),c.friends_pending||(c.friends_pending={}),c.form_seed||(c.form_seed=o.createChannelId()),u||(se(e,n,t()),u=C.manager,l=C.userObject),X(0,0,t()),function(e,n,t){if(!C.loggedIn)return t();C.rpc?t(Z):f.create(C.network,C.proxy,function(e,n){e?t({error:e}):(C.rpc=n,C.onRpcReadyEvt.fire(),v.getPinLimit(null,null,function(e){e.error&&console.error(e.error),Z.limit=e.limit,Z.plan=e.plan,Z.note=e.note,t(e)}))},d)}(0,0,t()),y(e,"LOADING_DRIVE",{type:"migrate",progress:0})}).nThen(function(n){void 0===c.version&&(c.version=11),r(c,n(),function(n,t){y(e,"LOADING_DRIVE",{type:"migrate",progress:t})},C)}).nThen(function(n){y(e,"LOADING_DRIVE",{type:"sf",progress:0}),l.fixFiles(),h.loadSharedFolders(v,C.network,C,C.drive.proxy,l,n,n=>{var t={type:"sf",progress:100*n.progress/n.max};y(e,"LOADING_DRIVE",t)}),ie(n),te(A,"profile",n),te(T,"calendar",n),te(g,"support",n),M(e=>{C.modules.team&&C.modules.team.onReady(e)})}).nThen(function(){var e,r=function(){S([],"REQUEST_LOGIN")};C.loggedIn&&(function(e){if(C.rpc){var n=Q(!1),t=o.hashChannelList(n);C.rpc.getServerHash(function(n,r){n?e(n):e(null,r===t)})}else e({error:"RPC_NOT_READY"})}(function(e,n){n||function(e){if(C.rpc){var n=Q(!1);C.rpc.reset(n,function(n){e(n||null)})}else e({error:"RPC_NOT_READY"})}(function(e){if(e)return console.error(e);console.log("RESET DONE")})}),"number"!=typeof c.loginToken&&(c[i.tokenKey]=C.data.localToken||Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)),n[i.tokenKey]=c[i.tokenKey],C.data.localToken&&C.data.localToken!==c[i.tokenKey])?r():(n.feedback=a.find(c,["settings","general","allowUserFeedback"]),s.init(n.feedback),C.returned=n,"function"==typeof t&&t(n),C.offline=!1,P("NETWORK_RECONNECT"),S([],"UPDATE_METADATA"),S([],"STORE_READY",n),"string"==typeof c.uid&&32===c.uid.length||(console.log("generating a persistent identifier"),c.uid=o.createChannelId()),!C.loggedIn||v.hasSigningKeys()&&v.hasCurveKeys()?(c.on("change",[i.displayNameKey],function(e,n){"string"==typeof n&&S([],"UPDATE_METADATA")}),c.on("change",["profile"],function(){S([],"UPDATE_METADATA")}),c.on("change",["friends"],function(e,n,t){if(S([],"UPDATE_METADATA"),C.messenger&&void 0===e){var r=t.slice(-1)[0],o=c.friends&&c.friends[r];C.messenger.onFriendAdded(o)}}),c.on("remove",["friends"],function(e,n){if(S([],"UPDATE_METADATA"),C.messenger){var t=n[1];t&&"channel"===n[2]&&C.messenger.onFriendRemoved(t,e)}}),c.on("change",["friends_pending"],function(){S([],"UPDATE_METADATA")}),c.on("remove",["friends_pending"],function(){S([],"UPDATE_METADATA")}),c.on("change",["settings"],function(){S([],"UPDATE_METADATA")}),c.on("change",[i.tokenKey],function(){C.isDeleted||"DELETED"===c[i.tokenKey]||S([],"UPDATE_TOKEN",{token:c[i.tokenKey]})}),C.mailbox=O.init({Store:v,store:C,updateMetadata:function(){S([],"UPDATE_METADATA")},updateDrive:function(){P("DRIVE_CHANGE",{path:["drive","filesData"]})},pinPads:function(e,n){v.pinPads(null,e,n)}},e,function(e,n,t,r){var o=a.once(r||function(){});t.forEach(function(t){y(t,"MAILBOX_EVENT",{ev:e,data:n},o)})}),Y.fire()):r())})};const ue=(e,n,t,r)=>{if(C.accountModule)return C.accountModule;const o=F.init({userHash:n.userHash,anonHash:n.anonHash,cache:n.cache,form_seed:n.form_seed,store:C,broadcast:S,postMessage:y});C.accountModule=o;const{channel:i,onAccountReady:s,onAccountCacheReady:c,onDisconnect:u,onReconnect:f}=o;C.driveChannel=i,c(e=>{C.cacheReturned||=e,t(e)}),s(e=>{C.returned||=e,r(e)}),u(()=>{P("NETWORK_DISCONNECT")}),f(()=>{P("NETWORK_RECONNECT")});return setInterval(function(){var e=[];const n=v.pad.getChannels();Object.keys(n).forEach(function(t){var r=n[t].clients;Array.prototype.push.apply(e,r)}),(e=a.deduplicateString(e)).forEach(function(e){var n=0,t=function(){if(n>=2)return v._removeClient(e),y(e,"TIMEOUT"),void console.error("TIMEOUT",e);n++;var r=setTimeout(t,3e4);y(e,"PING",null,function(e){e&&console.error(e),clearTimeout(r)})};t()})},12e4),o},fe=(e,n,t,r)=>{const o=a.once(e=>{const n=L.init({account:e,store:C,broadcast:S,postMessage:y}),{onDriveReady:o,onDriveCacheReady:a,onDisconnect:i,onReconnect:s}=n;a(()=>{t(C.cacheReturned||C.returned)}),o(()=>{r(C.returned)}),i(()=>{}),s(()=>{})}),i=()=>{},s=ue(0,n,i,i);s.onAccountCacheReady(()=>{o(s)}),s.onAccountReady(()=>{o(s)})};v.disableCache=function(e,n,t){n?d.disable():d.enable(),t()};var le=!1;const de=e=>{if(C?.network?.historyKeeper)return setTimeout(e);const n=n=>{C.network||=n;n.join("0000000000000000000000000000000000").then(function(t){let r;t.members.forEach(e=>{16===e.length&&(r=e)}),n.historyKeeper=r,t.leave(),e()},function(n){console.error(n),e({error:"GET_HK"})})};if(C.network)return n(C.network);C.networkPromise?.then(n)};var he=function(e,n,t){const r=a.once(n);var o=function(){ie();let e=()=>{X(0,0,function(){s.send("NO_DRIVE",!0),r({})})};de(n=>{if(!n)return t?((e,n)=>{if(C.rpc)n(C.rpc);else{var t=x.Nacl.sign.keyPair(),r=C.tempKeys={edPublic:a.encodeBase64(t.publicKey),edPrivate:a.encodeBase64(t.secretKey)};f.create(C.network,r,function(e,t){e?n({error:e}):(C.rpc=t,n(t))})}})(0,e):void e()}),C.network||t||r({})};if(!C.network){var i=I.getWebsocketURL();return C.networkPromise=k.connect(i),o(),C.networkPromise.then(e=>{C.network!==e&&(C.network?(e.disconnect(),e=C.network):C.network=e)},function(e){console.error(e),r({error:"OFFLINE"})})}o()};const pe=(e,n,t)=>{C.manager?G.reg(function(){de(r=>{C.network||=r,ce(e,n,()=>{t(n)})})}):ce(e,n,()=>{t(n)})};return v.init=function(e,n,t){var r=a.once(function(r){n.driveEvents&&function(e){G.reg(()=>{-1===R.indexOf(e)&&R.push(e),C.driveEvents||(C.driveEvents=!0,re(C.proxy),Object.keys(C.manager.folders).forEach(function(e){var n=C.manager.folders[e].proxy;re(n,e)}))})}(e),t(r)});if(le&&!C.returned&&n.cache)G.reg(function(){r({state:"ALREADY_INIT",returned:C.cacheReturned})});else{if(le)return C.networkTimeout&&y(e,"LOADING_DRIVE",{type:"offline"}),void Y.reg(function(){r({state:"ALREADY_INIT",returned:C.returned})});n.disableCache&&d.disable(),n.noDrive&&!n.requires&&(n.requires="pad"),((e,n,t)=>{if(n.neverDrive||n.noDrive&&!n.userHash&&!n.anonHash)return n.neverDrive&&(C.neverCache=!0),void he(0,e=>{e?.error&&s.send("NO_DRIVE_ERROR",!0),n.neverDrive&&(e.tempKeys=C?.tempKeys),t(e)},!!n.neverDrive);const r=n.requires,o=!n.noDrive;le=!0,C.data=n;let c=e=>{1===Object.keys(C.proxy).length&&s.send("FIRST_APP_USE",!0),e&&e.error&&(le=!1)};if("pad"===r&&!o)return void he(0,function(r){if(r&&r.error)return;t(r);let o=a.once(()=>{fe(0,n,n=>{se(e,n,c)},n=>{pe(e,n,c)})});v.pad.onCacheReady(()=>{C.network||o()}),v.pad.onJoined(o),J.reg(o)});if("file"===r&&!o)return void he(0,function(r){r&&r.error||(t(r),fe(0,n,n=>{se(e,n,c)},n=>{pe(e,n,c)}))});if("team"===r){let r=!1;const o=o=>a=>{r||(r=!0,M(e=>{o||X(0,0,e())}).nThen(n=>{te(w,"team",n,e)}).nThen(e=>{!o&&C.modules.team&&C.modules.team.onReady(e)}).nThen(()=>{t(a),fe(0,n,n=>{se(e,n,c)},n=>{pe(e,n,c)})}))};return void ue(0,n,o(!0),o(!1))}if("drive"===r)return void fe(0,n,n=>{t(n),se(e,n,c)},n=>{t(n),pe(e,n,c)});let u=e=>{c(e);const n=i.prefersDriveRedirectKey,r=a.find(C,["proxy","settings","general",n]);e[n]=r,t(e)};fe(0,n,n=>{se(e,n,u)},n=>{pe(e,n,u)})})(e,n,a.once(e=>{"GET_HK"!==e.error?r(e):r({error:"ERROR"})}))}},Y.reg(function(){var e=+new Date-7776e6;d.getKeys(function(n,t){if(n)console.error(n);else{var r=function(){if(t.length){var n=t.pop();d.getTime(n,function(t,o){t?r():!o||o{const n=(e,n={})=>({create:function(t,r,o){var a,i=[],s=e.mkEvent(!0);t.reg(function(e){if(!a){var n=e.data;if("_READY"===n)return r("_READY"),a=!0,s.fire(),void i.forEach(function(e){t.fire(e)});i.push(n)}});var c={},u={},f={},l=[],d={},h={};h.query=function(e,n,t,o){var a,i=Math.random().toString(16).replace("0.","")+Math.random().toString(16).replace("0.",""),c=(o=o||{}).timeout||3e4;c>0&&(a=setTimeout(function(){delete u[i],t("TIMEOUT")},c)),f[i]=function(e){clearTimeout(a),delete f[i],e&&(delete u[i],t("UNHANDLED"))},u[i]=function(e,n){delete u[i],t(void 0,e.content,n)},s.reg(function(){var t={txid:i,content:n,q:e,raw:o.raw};r(o.raw?t:JSON.stringify(t))})};var p=h.event=function(e,n,t){t=t||{},s.reg(function(){var o={content:n,q:e,raw:t.raw};r(t.raw?o:JSON.stringify(o))})};h.on=function(e,n,t){var o=function(e,t,o){n(e.content,function(n){var t={txid:e.txid,content:n};r(o?t:JSON.stringify(t))},t)};return(c[e]=c[e]||[]).push(o),t||p("EV_REGISTER_HANDLER",e),{stop:function(){var n=c[e].indexOf(o);-1!==n&&c[e].splice(n,1)}}},h.whenReg=function(e,n,t){var r=t;l.indexOf(e)>-1?n():r=!0,r&&(d[e]=d[e]||[]).push(n)},h.onReg=function(e,n){h.whenReg(e,n,!0)},h.on("EV_REGISTER_HANDLER",function(e){d[e]&&(d[e].forEach(function(e){e()}),delete d[e]),l.push(e)});var v=!1;h.onReady=function(e){v?e():"function"==typeof e&&h.on("EV_RPC_READY",function(){v=!0,e()})},h.ready=function(){h.whenReg("EV_RPC_READY",function(){h.event("EV_RPC_READY")})};var y=[""];n.httpUnsafeOrigin?(y.push(n.httpUnsafeOrigin),y.push(n.httpSafeOrigin)):globalThis.location&&y.push(globalThis.location.origin),t.reg(function(e){if(a&&e.data&&"_READY"!==e.data&&y.includes(e.origin)){var n;try{n="object"==typeof e.data?e.data:JSON.parse(e.data)}catch(e){return void console.warn(e)}void 0!==n.ack?f[n.txid]&&f[n.txid](!n.ack):"string"==typeof n.q?c[n.q]?(n.txid&&r(JSON.stringify({txid:n.txid,ack:!0})),c[n.q].forEach(function(t){t(n||JSON.parse(e.data),e,n&&n.raw),n=void 0})):n.txid&&r(JSON.stringify({txid:n.txid,ack:!1})):void 0===n.q&&u[n.txid]&&u[n.txid](n,e)}}),r("_READY"),o(h)}});e.exports&&(e.exports=n(Z()))})()}(mr)),mr.exports}function Er(){if(pr)return hr;pr=1;var e;return hr=((e,n,t)=>{const r={};let o,a,i={},s=()=>{};return r.init=n=>{if(a)return;a=e.create({query:(e,n,t,r)=>{r=r||function(){},i[e].chan.query(n,t,function(e,n){r(e?{error:e}:n)})},broadcast:(e,n,t,r)=>{r=r||function(){},Object.keys(i).forEach(o=>{-1===e.indexOf(+o)&&i[o].chan.query(n,t,(e,n)=>{r(e?{error:e}:n)})})}}),s=n},r.initClient=(e,r)=>{if(!a)return console.error("Not initialized"),void r("NOT_INIT");const{postMsg:c}=e,u=t.mkEvent(),f=Number(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)),l=()=>{a._removeClient(f)};n.create(u,c,function(e){let n=i[f]={chan:e};console.debug("SharedW Channel created"),Object.keys(a.queries).forEach(function(t){"CONNECT"!==t&&"JOIN_PAD"!==t&&"SEND_PAD_MSG"!==t&&"STOPWORKER"!==t&&e.on(t,function(e,r){try{a.queries[t](f,e,r)}catch(n){console.error("Error in webworker when executing query "+t),console.error(n),console.log(e)}"DISCONNECT"===t&&(l(),globalThis.accountDeletion&&globalThis.accountDeletion===n.id&&(a=void 0,o=void 0))})}),e.on("STOPWORKER",function(e,n){s(),a.queries.DISCONNECT(f,e,n)}),e.on("CONNECT",function(e,n){console.debug("Connecting to store..."),a.queries.CONNECT(f,e,function(e){if(e&&"ALREADY_INIT"===e.state)return console.debug("Store already exists!"),o=o||e.returned,void n(e);o=e,n(e)})}),e.on("JOIN_PAD",function(e,t){n.channelId=e.channel;try{a.queries.JOIN_PAD(f,e,t)}catch(n){console.error("Error in webworker when executing query JOIN_PAD"),console.error(n),console.log(e)}}),e.on("SEND_PAD_MSG",function(e,t){var r={msg:e,channel:n.channelId};try{a.queries.SEND_PAD_MSG(f,r,t)}catch(e){console.error("Error in webworker when executing query SEND_PAD_MSG"),console.error(e),console.log(r)}}),r(u,l)},!0)},r})((ur||(ur=1,e=sr(),cr={create:function(n){var t=e.create(n),r={},o=r.queries={CONNECT:t.init,DISCONNECT:t.disconnect,PING:function(e,n,t){t()},CACHE_DISABLE:t.disableCache,GET_PIN_LIMIT:t.getPinLimit,PIN_PADS:t.pinPads,UNPIN_PADS:t.unpinPads,GET_PINNED_USAGE:t.getPinnedUsage,GET_DELETED_PADS:t.getDeletedPads,UPLOAD_CHUNK:t.uploadChunk,UPLOAD_COMPLETE:t.uploadComplete,UPLOAD_STATUS:t.uploadStatus,UPLOAD_CANCEL:t.uploadCancel,ANON_RPC_MESSAGE:t.anonRpcMsg,GET_FILE_SIZE:t.getFileSize,GET_MULTIPLE_FILE_SIZE:t.getMultipleFileSize,GET:t.get,SET:t.set,ADD_PAD:t.addPad,SET_PAD_TITLE:t.setPadTitle,MOVE_TO_TRASH:t.moveToTrash,RESET_DRIVE:t.resetDrive,GET_METADATA:t.getMetadata,IS_ONLY_IN_SHARED_FOLDER:t.isOnlyInSharedFolder,SET_DISPLAY_NAME:t.setDisplayName,SET_PAD_ATTRIBUTE:t.setPadAttribute,GET_PAD_ATTRIBUTE:t.getPadAttribute,SET_ATTRIBUTE:t.setAttribute,GET_ATTRIBUTE:t.getAttribute,LIST_ALL_TAGS:t.listAllTags,GET_TEMPLATES:t.getTemplates,GET_SECURE_FILES_LIST:t.getSecureFilesList,GET_PAD_DATA:t.getPadData,GET_PAD_DATA_FROM_CHANNEL:t.getPadDataFromChannel,GET_STRONGER_HASH:t.getStrongerHash,INCREMENT_TEMPLATE_USE:t.incrementTemplateUse,GET_SHARED_FOLDER:t.getSharedFolder,ADD_SHARED_FOLDER:t.addSharedFolder,LOAD_SHARED_FOLDER:t.loadSharedFolderAnon,RESTORE_SHARED_FOLDER:t.restoreSharedFolder,UPDATE_SHARED_FOLDER_PASSWORD:t.updateSharedFolderPassword,ANSWER_FRIEND_REQUEST:t.answerFriendRequest,SEND_FRIEND_REQUEST:t.sendFriendRequest,ANON_GET_PREVIEW_CONTENT:t.anonGetPreviewContent,OO_COMMAND:t.onlyoffice.execCommand,MAILBOX_COMMAND:t.mailbox.execCommand,UNIVERSAL_COMMAND:t.universal.execCommand,SEND_PAD_MSG:t.pad.sendMessage,JOIN_PAD:t.pad.join,LEAVE_PAD:t.pad.leave,REMOVE_OWNED_CHANNEL:t.pad.destroy,CLEAR_OWNED_CHANNEL:t.pad.clear,CORRUPTED_CACHE:t.pad.onCorruptedCache,GET_LAST_HASH:t.pad.getLastHash,GET_FULL_HISTORY:t.getFullHistory,GET_HISTORY:t.getHistory,GET_HISTORY_RANGE:t.getHistoryRange,IS_NEW_CHANNEL:t.isNewChannel,CONTACT_PAD_OWNER:t.contactPadOwner,GIVE_PAD_ACCESS:t.givePadAccess,BURN_PAD:t.burnPad,GET_PAD_METADATA:t.pad?.getMetadata,SET_PAD_METADATA:t.pad?.setMetadata,CHANGE_PAD_PASSWORD_PIN:t.changePadPasswordPin,GET_SNAPSHOT:t.getSnapshot,DELETE_MAILBOX_MESSAGE:t.deleteMailboxMessage,DRIVE_USEROBJECT:t.userObjectCommand,GET_DRIVE:t.drive.get,SET_DRIVE:t.drive.set,MIGRATE_ANON_DRIVE:t.drive.migrateAnon,HAS_DRIVE:t.drive.exists,DELETE_ACCOUNT:t.deleteAccount,REMOVE_OWNED_PADS:t.removeOwnedPads,ADMIN_RPC:t.adminRpc,ADMIN_ADD_MAILBOX:t.addAdminMailbox};return r.query=function(e,n,t){o[e]?o[e]("0",n,t):console.error("UNHANDLED_STORE_RPC")},r._removeClient=t._removeClient,r}}),cr),gr(),Z()),hr}var br,Or,Ar=function(){if(yr)return vr;yr=1;const e=Er();return vr={start:n=>{let t=!1,r=()=>{globalThis.close()};globalThis.window=globalThis,addEventListener("connect",o=>{console.debug("New SharedWorker client");const a=o.ports[0],i=e=>{a.postMessage(e)};let s,c=!1,u=()=>{};a.onmessage=function(o){if("INIT"===o.data?.type){if((o=>{t||(n(o),e.init(r),t=!0)})(o.data.cfg),c)return;c=!0,e.initClient({postMsg:i},function(e,n){s=e,u=n,i("SW_READY")})}else"CLOSE"===o.data?(console.debug("leave"),u()):s&&s.fire(o)}})}}}();var wr,Dr,_r=function(){if(Or)return br;Or=1;const e=Er();return br={start:n=>{let t,r=!1;const o=()=>{globalThis.close()},a=e=>{postMessage(e)};globalThis.window=globalThis,onmessage=function(i){if("INIT"===i.data?.type){let s=i.data.cfg;if(r)return;return n(s),e.init(o),r=!0,void e.initClient({postMsg:a},function(e){t=e,a("WW_READY")})}t&&t.fire(i)}}}}();var Tr=function(){if(Dr)return wr;Dr=1;const e=Er(),n=Z();return wr={start:t=>{let r,o=!1,a=!1;const i=n.mkEvent(),s=()=>{a=!0},c=e=>{a||i.fire(e)};return{init:n=>{o||(t(n),e.init(s),o=!0,e.initClient({postMsg:c},function(e){r=e,c("STORE_READY")}))},onMessage:e=>{i.reg(n=>{setTimeout(()=>{e(n)})})},query:e=>{r&&!a&&r.fire({data:e,origin:""})}}}}}(),Sr=Kn(),Nr=n({__proto__:null,default:r(Sr)},[Sr]),Ir=jn(),xr=n({__proto__:null,default:r(Ir)},[Ir]),Cr=Pt(),Rr=n({__proto__:null,default:r(Cr)},[Cr]),Pr=kt(),kr=n({__proto__:null,default:r(Pr)},[Pr]),Mr=Kt(),Fr=n({__proto__:null,default:r(Mr)},[Mr]),Lr=Qt(),Hr=n({__proto__:null,default:r(Lr)},[Lr]);let jr=e=>{[Te,nn,q,$e,B,Nr,gn,un,ke,Rr,kr,Hr,lr,ge,xr,Fr,rr].forEach(n=>{"function"==typeof n.setCustomize&&n.setCustomize(e)})},Kr="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,Ur="undefined"!=typeof SharedWorkerGlobalScope&&self instanceof SharedWorkerGlobalScope;e.store={},Ur?Ar.start(jr):Kr?_r.start(jr):("undefined"!=typeof module&&module.exports,e.store=Tr.start(jr)),e.start=jr}); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["cryptpad-worker-min"]={})}(this,(function(e){"use strict";function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}}))})),Object.freeze(e)}var n="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function r(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function o(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var n=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})})),n}var a,i={exports:{}},s={exports:{}},c={exports:{}};function u(){return a||(a=1,function(e){var t;t=function(){var e=function(){},t=function(){return(new Date).getTime()},n=function(e,t,n){e.timeouts.push(setTimeout(t,n))},r=function(t,r){t.ws&&(t.ws.onmessage=e,t.ws.onopen=e,t.ws.close(),r?t.ws.onclose({reason:"offline"}):n(t,(function(){t.ws&&t.ws.onclose({reason:"forced closed because websocket failed to close"})}),1e4))},o=function(e,t){return!!e.ws&&(e.ws.send(JSON.stringify(t)),!0)},a=function(e,t){return function(e,n){var r=t[e];if(!r)throw new Error("no such event "+e);r.push(n)}},i=function(e,t,n,r){var o=r[t];if(!o)throw new Error("no such event "+t);var a=o.indexOf(n);-1!==a&&o.splice(a,1)},s=function(e,n,r){if(e.channels[n])return new Promise((function(t){t(e.channels[n])}));var s=e.queues.p2;1===r?s=e.queues.p1:3===r&&(s=e.queues.p3);var c={queue:s,onMessage:[],onJoin:[],onLeave:[],members:[],jSeq:e.seq++},u={message:c.onMessage,join:c.onJoin,leave:c.onLeave},l={_:c,time:t(),id:n,members:c.members,bcast:function(n){return function(e,n,r){var a=e.channels[n],i=e.seq++,s=[i,"MSG",n,r];if(!a)return new Promise((function(e,t){t({type:"NO_SUCH_CHANNEL",message:JSON.stringify(s)})}));var c=o(e,s);return new Promise((function(n,r){c?e.requests[i]={reject:r,resolve:n,time:t()}:r({type:"DISCONNECTED",message:JSON.stringify(s)})}))}(e,l.id,n)},leave:function(n){return function(e,n,r){if(e.channels[n]){if(delete e.channels[n],e.ws&&1===e.ws.readyState){var a=e.seq++;o(e,[a,"LEAVE",n,r]);var i=function(){};e.requests[a]={reject:i,resolve:i,time:t()}}}else console.debug("no such channel",n)}(e,l.id,n)},on:a(0,u),off:function(e,t){i(0,e,t,u)}};e.requests[c.jSeq]=l;var f=[c.jSeq,"JOIN",n],d=o(e,f);return new Promise((function(e,t){d?(l._.resolve=e,l._.reject=t):t({type:"DISCONNECTED",message:JSON.stringify(f)})}))},c=function(n){var r={message:n.onMessage,disconnect:n.onDisconnect,reconnect:n.onReconnect},c={webChannels:n.channels,getLag:function(){return function(e){return e.ws?e.pingOutstanding?Math.max(t()-e.timeOfLastPingSent,e.lastObservedLag):e.lastObservedLag:null}(n)},sendto:function(e,r){return function(e,n,r){var a=e.seq++,i=[a,"MSG",n,r],s=o(e,i);return new Promise((function(n,r){s?e.requests[a]={reject:r,resolve:n,time:t()}:r({type:"DISCONNECTED",message:JSON.stringify(i)})}))}(n,e,r)},join:function(e,t){return s(n,e,t)},disconnect:function(){return function(t){if(t.ws){var n=t.ws.onclose;t.ws.onclose=e,t.ws.close(),n({reason:"network.disconnect() called"})}t.timeouts.forEach(clearTimeout),t.timeouts=[]}(n)},on:a(0,r),off:function(e,t){i(0,e,t,r)}};return c.__defineGetter__("webChannels",(function(){return Object.keys(n.channels).map((function(e){return n.channels[e]}))})),c},u=function(e,n){var a=void 0;try{a=JSON.parse(n.data)}catch(e){return void console.log(e.stack)}if(e.timeOfLastMsgReceived=t(),0===a[0]){if("IDENT"===a[2])return e.uid=a[3],e.ws._onident(),void(e.pingInterval=setInterval((function(){if(!(t()-e.timeOfLastPingReceived<15e3||(t()-e.timeOfLastMsgReceived>6e4&&r(e),e.pingOutstanding))){var n=e.seq++,a=t();e.timeOfLastPingSent=a,e.pingOutstanding++,e.requests[n]={time:a,ping:a},o(e,[n,"PING"])}}),5e3));if(e.uid){if("PING"===a[2])return a[2]="PONG",void o(e,a);if("MSG"===a[2]){var i=void 0,s=e.queues.p2;if(a[3]===e.uid)i=e.onMessage,"number"==typeof a[5]&&(1===a[5]&&(s=e.queues.p1),3===a[5]&&(s=e.queues.p3));else{var c=e.channels[a[3]];if(!c)return void console.log("message to non-existent chan "+JSON.stringify(a));i=c._.onMessage,c._.queue&&(s=c._.queue)}s.push({msg:a,h:i}),function(e){if(!e.queues.busy){var t=function(){var n=e.queues.p1.shift()||e.queues.p2.shift()||e.queues.p3.shift();if(n){e.queues.busy=!0;var r=n.h,o=n.msg;r.forEach((function(e){setTimeout((function(){try{e(o[4],o[1])}catch(e){console.error(e)}}))})),setTimeout((function(){t()}))}else e.queues.busy=!1};t()}}(e)}if("LEAVE"===a[2]){var u=e.channels[a[3]];if(!u)return void(a[1]!==e.uid&&console.log("leaving non-existent chan "+JSON.stringify(a)));var l=u._.members.indexOf(a[1]);-1!==l&&u._.members.splice(l,1),u._.onLeave.forEach((function(e){try{e(a[1],a[4])}catch(e){console.log(e.stack)}}))}if("JOIN"===a[2]){var f=e.channels[a[3]];if(!f)return void console.log("ERROR: join to non-existent chan "+JSON.stringify(a));if(-1!==f._.members.indexOf(a[1]))return;var d=-1!==f._.members.indexOf(e.uid);f._.members.push(a[1]),d||a[1]!==e.uid||(f.myID=e.uid,f._.resolve(f)),d&&f._.onJoin.forEach((function(e){try{e(a[1])}catch(e){console.log(e.stack)}}))}}}else{var h=e.requests[a[0]];if(!h)return void console.log("error: "+JSON.stringify(a));if(delete e.requests[a[0]],"ACK"===a[1]){if(h.ping)return e.lastObservedLag=t()-Number(h.ping),e.timeOfLastPingReceived=t(),void e.pingOutstanding--;h.resolve()}else if("JACK"===a[1]){if(h._){if(!a[2])throw new Error("wrong type of ACK for channel join");return h.id=a[2],void(e.channels[h.id]=h)}h.resolve()}else if("ERROR"===a[1])if("function"==typeof h.reject)h.reject({type:a[2],message:a[3]});else if(h._&&"function"==typeof h._.reject){if("EJOINED"===a[2]&&!e.channels[a[3]])return h.id=a[3],void(e.channels[h.id]=h);h._.reject({type:a[2],message:a[3]})}else console.error(a);else h.reject({type:"UNKNOWN",message:JSON.stringify(a)})}};return{connect:function(o,a){a=a||function(e){return new globalThis.WebSocket(e)};var i={ws:null,seq:1,uid:null,network:null,channels:{},onMessage:[],onDisconnect:[],onReconnect:[],timeouts:[],requests:{},pingInterval:null,queues:{p1:[],p2:[],p3:[]},timeOfLastPingSent:-1,timeOfLastPingReceived:-1,timeOfLastMsgReceived:-1,lastObservedLag:0,pingOutstanding:0};i.network=c(i);var s=e,l=e;"undefined"!=typeof window&&window.addEventListener("offline",(function(){-1===["localhost","127.0.0.1",""].indexOf(window.location.hostname)&&r(i,!0)}));var f=function(){var c=i.ws=a(o);i.timeOfLastPingSent=i.timeOfLastPingReceived=t(),i.timeOfLastMsgReceived=t(),c.onmessage=function(e){return u(i,e)},c.onclose=function(t){c.onclose=e,clearInterval(i.pingInterval),i.timeouts.forEach(clearTimeout),i.ws=null,i.uid&&(i.uid=null,i.onDisconnect.forEach((function(e){try{e(t.reason)}catch(e){console.log(e.stack)}}))),n(i,f,i.uid?0:7e3)},c.onopen=function(){n(i,(function(){i.uid||(l({type:"TIMEOUT",message:"waited 30000ms"}),s=l=e,r(i))}),3e4)},i.ws._onident=function(){i.timeOfLastPingReceived=t(),i.timeOfLastMsgReceived=t(),i.lastObservedLag=t()-i.timeOfLastPingSent,s!==e?(s(i.network),s=l=e):(i.channels={},i.requests={},i.pingOutstanding=0,i.onReconnect.forEach((function(e){try{e(i.uid)}catch(e){console.log(e.stack)}})))}};return new Promise((function(e,t){s=e,l=t,f()}))}}},e.exports?e.exports=t():window.netflux_websocket=t()}(c)),c.exports}function l(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var f,d={exports:{}};function h(){return f||(f=1,function(e){!function(e){var t=function(e){var t,n=new Float64Array(16);if(e)for(t=0;t>24&255,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=255&n,e[t+4]=r>>24&255,e[t+5]=r>>16&255,e[t+6]=r>>8&255,e[t+7]=255&r}function y(e,t,n,r,o){var a,i=0;for(a=0;a>>8)-1}function v(e,t,n,r){return y(e,t,n,r,16)}function m(e,t,n,r){return y(e,t,n,r,32)}function g(e,t,n,r){!function(e,t,n,r){for(var o,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,i=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,s=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,c=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,u=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,l=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,f=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,d=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,h=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,p=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,y=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,v=255&n[16]|(255&n[17])<<8|(255&n[18])<<16|(255&n[19])<<24,m=255&n[20]|(255&n[21])<<8|(255&n[22])<<16|(255&n[23])<<24,g=255&n[24]|(255&n[25])<<8|(255&n[26])<<16|(255&n[27])<<24,E=255&n[28]|(255&n[29])<<8|(255&n[30])<<16|(255&n[31])<<24,b=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,A=a,_=i,w=s,O=c,D=u,S=l,T=f,C=d,x=h,I=p,N=y,P=v,k=m,R=g,M=E,F=b,L=0;L<20;L+=2)A^=(o=(k^=(o=(x^=(o=(D^=(o=A+k|0)<<7|o>>>25)+A|0)<<9|o>>>23)+D|0)<<13|o>>>19)+x|0)<<18|o>>>14,S^=(o=(_^=(o=(R^=(o=(I^=(o=S+_|0)<<7|o>>>25)+S|0)<<9|o>>>23)+I|0)<<13|o>>>19)+R|0)<<18|o>>>14,N^=(o=(T^=(o=(w^=(o=(M^=(o=N+T|0)<<7|o>>>25)+N|0)<<9|o>>>23)+M|0)<<13|o>>>19)+w|0)<<18|o>>>14,F^=(o=(P^=(o=(C^=(o=(O^=(o=F+P|0)<<7|o>>>25)+F|0)<<9|o>>>23)+O|0)<<13|o>>>19)+C|0)<<18|o>>>14,A^=(o=(O^=(o=(w^=(o=(_^=(o=A+O|0)<<7|o>>>25)+A|0)<<9|o>>>23)+_|0)<<13|o>>>19)+w|0)<<18|o>>>14,S^=(o=(D^=(o=(C^=(o=(T^=(o=S+D|0)<<7|o>>>25)+S|0)<<9|o>>>23)+T|0)<<13|o>>>19)+C|0)<<18|o>>>14,N^=(o=(I^=(o=(x^=(o=(P^=(o=N+I|0)<<7|o>>>25)+N|0)<<9|o>>>23)+P|0)<<13|o>>>19)+x|0)<<18|o>>>14,F^=(o=(M^=(o=(R^=(o=(k^=(o=F+M|0)<<7|o>>>25)+F|0)<<9|o>>>23)+k|0)<<13|o>>>19)+R|0)<<18|o>>>14;A=A+a|0,_=_+i|0,w=w+s|0,O=O+c|0,D=D+u|0,S=S+l|0,T=T+f|0,C=C+d|0,x=x+h|0,I=I+p|0,N=N+y|0,P=P+v|0,k=k+m|0,R=R+g|0,M=M+E|0,F=F+b|0,e[0]=A>>>0&255,e[1]=A>>>8&255,e[2]=A>>>16&255,e[3]=A>>>24&255,e[4]=_>>>0&255,e[5]=_>>>8&255,e[6]=_>>>16&255,e[7]=_>>>24&255,e[8]=w>>>0&255,e[9]=w>>>8&255,e[10]=w>>>16&255,e[11]=w>>>24&255,e[12]=O>>>0&255,e[13]=O>>>8&255,e[14]=O>>>16&255,e[15]=O>>>24&255,e[16]=D>>>0&255,e[17]=D>>>8&255,e[18]=D>>>16&255,e[19]=D>>>24&255,e[20]=S>>>0&255,e[21]=S>>>8&255,e[22]=S>>>16&255,e[23]=S>>>24&255,e[24]=T>>>0&255,e[25]=T>>>8&255,e[26]=T>>>16&255,e[27]=T>>>24&255,e[28]=C>>>0&255,e[29]=C>>>8&255,e[30]=C>>>16&255,e[31]=C>>>24&255,e[32]=x>>>0&255,e[33]=x>>>8&255,e[34]=x>>>16&255,e[35]=x>>>24&255,e[36]=I>>>0&255,e[37]=I>>>8&255,e[38]=I>>>16&255,e[39]=I>>>24&255,e[40]=N>>>0&255,e[41]=N>>>8&255,e[42]=N>>>16&255,e[43]=N>>>24&255,e[44]=P>>>0&255,e[45]=P>>>8&255,e[46]=P>>>16&255,e[47]=P>>>24&255,e[48]=k>>>0&255,e[49]=k>>>8&255,e[50]=k>>>16&255,e[51]=k>>>24&255,e[52]=R>>>0&255,e[53]=R>>>8&255,e[54]=R>>>16&255,e[55]=R>>>24&255,e[56]=M>>>0&255,e[57]=M>>>8&255,e[58]=M>>>16&255,e[59]=M>>>24&255,e[60]=F>>>0&255,e[61]=F>>>8&255,e[62]=F>>>16&255,e[63]=F>>>24&255}(e,t,n,r)}function E(e,t,n,r){!function(e,t,n,r){for(var o,a=255&r[0]|(255&r[1])<<8|(255&r[2])<<16|(255&r[3])<<24,i=255&n[0]|(255&n[1])<<8|(255&n[2])<<16|(255&n[3])<<24,s=255&n[4]|(255&n[5])<<8|(255&n[6])<<16|(255&n[7])<<24,c=255&n[8]|(255&n[9])<<8|(255&n[10])<<16|(255&n[11])<<24,u=255&n[12]|(255&n[13])<<8|(255&n[14])<<16|(255&n[15])<<24,l=255&r[4]|(255&r[5])<<8|(255&r[6])<<16|(255&r[7])<<24,f=255&t[0]|(255&t[1])<<8|(255&t[2])<<16|(255&t[3])<<24,d=255&t[4]|(255&t[5])<<8|(255&t[6])<<16|(255&t[7])<<24,h=255&t[8]|(255&t[9])<<8|(255&t[10])<<16|(255&t[11])<<24,p=255&t[12]|(255&t[13])<<8|(255&t[14])<<16|(255&t[15])<<24,y=255&r[8]|(255&r[9])<<8|(255&r[10])<<16|(255&r[11])<<24,v=255&n[16]|(255&n[17])<<8|(255&n[18])<<16|(255&n[19])<<24,m=255&n[20]|(255&n[21])<<8|(255&n[22])<<16|(255&n[23])<<24,g=255&n[24]|(255&n[25])<<8|(255&n[26])<<16|(255&n[27])<<24,E=255&n[28]|(255&n[29])<<8|(255&n[30])<<16|(255&n[31])<<24,b=255&r[12]|(255&r[13])<<8|(255&r[14])<<16|(255&r[15])<<24,A=0;A<20;A+=2)a^=(o=(m^=(o=(h^=(o=(u^=(o=a+m|0)<<7|o>>>25)+a|0)<<9|o>>>23)+u|0)<<13|o>>>19)+h|0)<<18|o>>>14,l^=(o=(i^=(o=(g^=(o=(p^=(o=l+i|0)<<7|o>>>25)+l|0)<<9|o>>>23)+p|0)<<13|o>>>19)+g|0)<<18|o>>>14,y^=(o=(f^=(o=(s^=(o=(E^=(o=y+f|0)<<7|o>>>25)+y|0)<<9|o>>>23)+E|0)<<13|o>>>19)+s|0)<<18|o>>>14,b^=(o=(v^=(o=(d^=(o=(c^=(o=b+v|0)<<7|o>>>25)+b|0)<<9|o>>>23)+c|0)<<13|o>>>19)+d|0)<<18|o>>>14,a^=(o=(c^=(o=(s^=(o=(i^=(o=a+c|0)<<7|o>>>25)+a|0)<<9|o>>>23)+i|0)<<13|o>>>19)+s|0)<<18|o>>>14,l^=(o=(u^=(o=(d^=(o=(f^=(o=l+u|0)<<7|o>>>25)+l|0)<<9|o>>>23)+f|0)<<13|o>>>19)+d|0)<<18|o>>>14,y^=(o=(p^=(o=(h^=(o=(v^=(o=y+p|0)<<7|o>>>25)+y|0)<<9|o>>>23)+v|0)<<13|o>>>19)+h|0)<<18|o>>>14,b^=(o=(E^=(o=(g^=(o=(m^=(o=b+E|0)<<7|o>>>25)+b|0)<<9|o>>>23)+m|0)<<13|o>>>19)+g|0)<<18|o>>>14;e[0]=a>>>0&255,e[1]=a>>>8&255,e[2]=a>>>16&255,e[3]=a>>>24&255,e[4]=l>>>0&255,e[5]=l>>>8&255,e[6]=l>>>16&255,e[7]=l>>>24&255,e[8]=y>>>0&255,e[9]=y>>>8&255,e[10]=y>>>16&255,e[11]=y>>>24&255,e[12]=b>>>0&255,e[13]=b>>>8&255,e[14]=b>>>16&255,e[15]=b>>>24&255,e[16]=f>>>0&255,e[17]=f>>>8&255,e[18]=f>>>16&255,e[19]=f>>>24&255,e[20]=d>>>0&255,e[21]=d>>>8&255,e[22]=d>>>16&255,e[23]=d>>>24&255,e[24]=h>>>0&255,e[25]=h>>>8&255,e[26]=h>>>16&255,e[27]=h>>>24&255,e[28]=p>>>0&255,e[29]=p>>>8&255,e[30]=p>>>16&255,e[31]=p>>>24&255}(e,t,n,r)}var b=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function A(e,t,n,r,o,a,i){var s,c,u=new Uint8Array(16),l=new Uint8Array(64);for(c=0;c<16;c++)u[c]=0;for(c=0;c<8;c++)u[c]=a[c];for(;o>=64;){for(g(l,u,i,b),c=0;c<64;c++)e[t+c]=n[r+c]^l[c];for(s=1,c=8;c<16;c++)s=s+(255&u[c])|0,u[c]=255&s,s>>>=8;o-=64,t+=64,r+=64}if(o>0)for(g(l,u,i,b),c=0;c=64;){for(g(c,s,o,b),i=0;i<64;i++)e[t+i]=c[i];for(a=1,i=8;i<16;i++)a=a+(255&s[i])|0,s[i]=255&a,a>>>=8;n-=64,t+=64}if(n>0)for(g(c,s,o,b),i=0;i>>13|n<<3),r=255&e[4]|(255&e[5])<<8,this.r[2]=7939&(n>>>10|r<<6),o=255&e[6]|(255&e[7])<<8,this.r[3]=8191&(r>>>7|o<<9),a=255&e[8]|(255&e[9])<<8,this.r[4]=255&(o>>>4|a<<12),this.r[5]=a>>>1&8190,i=255&e[10]|(255&e[11])<<8,this.r[6]=8191&(a>>>14|i<<2),s=255&e[12]|(255&e[13])<<8,this.r[7]=8065&(i>>>11|s<<5),c=255&e[14]|(255&e[15])<<8,this.r[8]=8191&(s>>>8|c<<8),this.r[9]=c>>>5&127,this.pad[0]=255&e[16]|(255&e[17])<<8,this.pad[1]=255&e[18]|(255&e[19])<<8,this.pad[2]=255&e[20]|(255&e[21])<<8,this.pad[3]=255&e[22]|(255&e[23])<<8,this.pad[4]=255&e[24]|(255&e[25])<<8,this.pad[5]=255&e[26]|(255&e[27])<<8,this.pad[6]=255&e[28]|(255&e[29])<<8,this.pad[7]=255&e[30]|(255&e[31])<<8};function S(e,t,n,r,o,a){var i=new D(a);return i.update(n,r,o),i.finish(e,t),0}function T(e,t,n,r,o,a){var i=new Uint8Array(16);return S(i,0,n,r,o,a),v(e,t,i,0)}function C(e,t,n,r,o){var a;if(n<32)return-1;for(O(e,0,t,0,n,r,o),S(e,16,e,32,n-32,e),a=0;a<16;a++)e[a]=0;return 0}function x(e,t,n,r,o){var a,i=new Uint8Array(32);if(n<32)return-1;if(w(i,0,32,r,o),0!==T(t,16,t,32,n-32,i))return-1;for(O(e,0,t,0,n,r,o),a=0;a<32;a++)e[a]=0;return 0}function I(e,t){var n;for(n=0;n<16;n++)e[n]=0|t[n]}function N(e){var t,n,r=1;for(t=0;t<16;t++)n=e[t]+r+65535,r=Math.floor(n/65536),e[t]=n-65536*r;e[0]+=r-1+37*(r-1)}function P(e,t,n){for(var r,o=~(n-1),a=0;a<16;a++)r=o&(e[a]^t[a]),e[a]^=r,t[a]^=r}function k(e,n){var r,o,a,i=t(),s=t();for(r=0;r<16;r++)s[r]=n[r];for(N(s),N(s),N(s),o=0;o<2;o++){for(i[0]=s[0]-65517,r=1;r<15;r++)i[r]=s[r]-65535-(i[r-1]>>16&1),i[r-1]&=65535;i[15]=s[15]-32767-(i[14]>>16&1),a=i[15]>>16&1,i[14]&=65535,P(s,i,1-a)}for(r=0;r<16;r++)e[2*r]=255&s[r],e[2*r+1]=s[r]>>8}function R(e,t){var n=new Uint8Array(32),r=new Uint8Array(32);return k(n,e),k(r,t),m(n,0,r,0)}function M(e){var t=new Uint8Array(32);return k(t,e),1&t[0]}function F(e,t){var n;for(n=0;n<16;n++)e[n]=t[2*n]+(t[2*n+1]<<8);e[15]&=32767}function L(e,t,n){for(var r=0;r<16;r++)e[r]=t[r]+n[r]}function H(e,t,n){for(var r=0;r<16;r++)e[r]=t[r]-n[r]}function K(e,t,n){var r,o,a=0,i=0,s=0,c=0,u=0,l=0,f=0,d=0,h=0,p=0,y=0,v=0,m=0,g=0,E=0,b=0,A=0,_=0,w=0,O=0,D=0,S=0,T=0,C=0,x=0,I=0,N=0,P=0,k=0,R=0,M=0,F=n[0],L=n[1],H=n[2],K=n[3],j=n[4],U=n[5],B=n[6],V=n[7],G=n[8],Y=n[9],J=n[10],q=n[11],W=n[12],Q=n[13],z=n[14],X=n[15];a+=(r=t[0])*F,i+=r*L,s+=r*H,c+=r*K,u+=r*j,l+=r*U,f+=r*B,d+=r*V,h+=r*G,p+=r*Y,y+=r*J,v+=r*q,m+=r*W,g+=r*Q,E+=r*z,b+=r*X,i+=(r=t[1])*F,s+=r*L,c+=r*H,u+=r*K,l+=r*j,f+=r*U,d+=r*B,h+=r*V,p+=r*G,y+=r*Y,v+=r*J,m+=r*q,g+=r*W,E+=r*Q,b+=r*z,A+=r*X,s+=(r=t[2])*F,c+=r*L,u+=r*H,l+=r*K,f+=r*j,d+=r*U,h+=r*B,p+=r*V,y+=r*G,v+=r*Y,m+=r*J,g+=r*q,E+=r*W,b+=r*Q,A+=r*z,_+=r*X,c+=(r=t[3])*F,u+=r*L,l+=r*H,f+=r*K,d+=r*j,h+=r*U,p+=r*B,y+=r*V,v+=r*G,m+=r*Y,g+=r*J,E+=r*q,b+=r*W,A+=r*Q,_+=r*z,w+=r*X,u+=(r=t[4])*F,l+=r*L,f+=r*H,d+=r*K,h+=r*j,p+=r*U,y+=r*B,v+=r*V,m+=r*G,g+=r*Y,E+=r*J,b+=r*q,A+=r*W,_+=r*Q,w+=r*z,O+=r*X,l+=(r=t[5])*F,f+=r*L,d+=r*H,h+=r*K,p+=r*j,y+=r*U,v+=r*B,m+=r*V,g+=r*G,E+=r*Y,b+=r*J,A+=r*q,_+=r*W,w+=r*Q,O+=r*z,D+=r*X,f+=(r=t[6])*F,d+=r*L,h+=r*H,p+=r*K,y+=r*j,v+=r*U,m+=r*B,g+=r*V,E+=r*G,b+=r*Y,A+=r*J,_+=r*q,w+=r*W,O+=r*Q,D+=r*z,S+=r*X,d+=(r=t[7])*F,h+=r*L,p+=r*H,y+=r*K,v+=r*j,m+=r*U,g+=r*B,E+=r*V,b+=r*G,A+=r*Y,_+=r*J,w+=r*q,O+=r*W,D+=r*Q,S+=r*z,T+=r*X,h+=(r=t[8])*F,p+=r*L,y+=r*H,v+=r*K,m+=r*j,g+=r*U,E+=r*B,b+=r*V,A+=r*G,_+=r*Y,w+=r*J,O+=r*q,D+=r*W,S+=r*Q,T+=r*z,C+=r*X,p+=(r=t[9])*F,y+=r*L,v+=r*H,m+=r*K,g+=r*j,E+=r*U,b+=r*B,A+=r*V,_+=r*G,w+=r*Y,O+=r*J,D+=r*q,S+=r*W,T+=r*Q,C+=r*z,x+=r*X,y+=(r=t[10])*F,v+=r*L,m+=r*H,g+=r*K,E+=r*j,b+=r*U,A+=r*B,_+=r*V,w+=r*G,O+=r*Y,D+=r*J,S+=r*q,T+=r*W,C+=r*Q,x+=r*z,I+=r*X,v+=(r=t[11])*F,m+=r*L,g+=r*H,E+=r*K,b+=r*j,A+=r*U,_+=r*B,w+=r*V,O+=r*G,D+=r*Y,S+=r*J,T+=r*q,C+=r*W,x+=r*Q,I+=r*z,N+=r*X,m+=(r=t[12])*F,g+=r*L,E+=r*H,b+=r*K,A+=r*j,_+=r*U,w+=r*B,O+=r*V,D+=r*G,S+=r*Y,T+=r*J,C+=r*q,x+=r*W,I+=r*Q,N+=r*z,P+=r*X,g+=(r=t[13])*F,E+=r*L,b+=r*H,A+=r*K,_+=r*j,w+=r*U,O+=r*B,D+=r*V,S+=r*G,T+=r*Y,C+=r*J,x+=r*q,I+=r*W,N+=r*Q,P+=r*z,k+=r*X,E+=(r=t[14])*F,b+=r*L,A+=r*H,_+=r*K,w+=r*j,O+=r*U,D+=r*B,S+=r*V,T+=r*G,C+=r*Y,x+=r*J,I+=r*q,N+=r*W,P+=r*Q,k+=r*z,R+=r*X,b+=(r=t[15])*F,i+=38*(_+=r*H),s+=38*(w+=r*K),c+=38*(O+=r*j),u+=38*(D+=r*U),l+=38*(S+=r*B),f+=38*(T+=r*V),d+=38*(C+=r*G),h+=38*(x+=r*Y),p+=38*(I+=r*J),y+=38*(N+=r*q),v+=38*(P+=r*W),m+=38*(k+=r*Q),g+=38*(R+=r*z),E+=38*(M+=r*X),a=(r=(a+=38*(A+=r*L))+(o=1)+65535)-65536*(o=Math.floor(r/65536)),i=(r=i+o+65535)-65536*(o=Math.floor(r/65536)),s=(r=s+o+65535)-65536*(o=Math.floor(r/65536)),c=(r=c+o+65535)-65536*(o=Math.floor(r/65536)),u=(r=u+o+65535)-65536*(o=Math.floor(r/65536)),l=(r=l+o+65535)-65536*(o=Math.floor(r/65536)),f=(r=f+o+65535)-65536*(o=Math.floor(r/65536)),d=(r=d+o+65535)-65536*(o=Math.floor(r/65536)),h=(r=h+o+65535)-65536*(o=Math.floor(r/65536)),p=(r=p+o+65535)-65536*(o=Math.floor(r/65536)),y=(r=y+o+65535)-65536*(o=Math.floor(r/65536)),v=(r=v+o+65535)-65536*(o=Math.floor(r/65536)),m=(r=m+o+65535)-65536*(o=Math.floor(r/65536)),g=(r=g+o+65535)-65536*(o=Math.floor(r/65536)),E=(r=E+o+65535)-65536*(o=Math.floor(r/65536)),b=(r=b+o+65535)-65536*(o=Math.floor(r/65536)),a=(r=(a+=o-1+37*(o-1))+(o=1)+65535)-65536*(o=Math.floor(r/65536)),i=(r=i+o+65535)-65536*(o=Math.floor(r/65536)),s=(r=s+o+65535)-65536*(o=Math.floor(r/65536)),c=(r=c+o+65535)-65536*(o=Math.floor(r/65536)),u=(r=u+o+65535)-65536*(o=Math.floor(r/65536)),l=(r=l+o+65535)-65536*(o=Math.floor(r/65536)),f=(r=f+o+65535)-65536*(o=Math.floor(r/65536)),d=(r=d+o+65535)-65536*(o=Math.floor(r/65536)),h=(r=h+o+65535)-65536*(o=Math.floor(r/65536)),p=(r=p+o+65535)-65536*(o=Math.floor(r/65536)),y=(r=y+o+65535)-65536*(o=Math.floor(r/65536)),v=(r=v+o+65535)-65536*(o=Math.floor(r/65536)),m=(r=m+o+65535)-65536*(o=Math.floor(r/65536)),g=(r=g+o+65535)-65536*(o=Math.floor(r/65536)),E=(r=E+o+65535)-65536*(o=Math.floor(r/65536)),b=(r=b+o+65535)-65536*(o=Math.floor(r/65536)),a+=o-1+37*(o-1),e[0]=a,e[1]=i,e[2]=s,e[3]=c,e[4]=u,e[5]=l,e[6]=f,e[7]=d,e[8]=h,e[9]=p,e[10]=y,e[11]=v,e[12]=m,e[13]=g,e[14]=E,e[15]=b}function j(e,t){K(e,t,t)}function U(e,n){var r,o=t();for(r=0;r<16;r++)o[r]=n[r];for(r=253;r>=0;r--)j(o,o),2!==r&&4!==r&&K(o,o,n);for(r=0;r<16;r++)e[r]=o[r]}function B(e,n){var r,o=t();for(r=0;r<16;r++)o[r]=n[r];for(r=250;r>=0;r--)j(o,o),1!==r&&K(o,o,n);for(r=0;r<16;r++)e[r]=o[r]}function V(e,n,r){var o,a,i=new Uint8Array(32),c=new Float64Array(80),u=t(),l=t(),f=t(),d=t(),h=t(),p=t();for(a=0;a<31;a++)i[a]=n[a];for(i[31]=127&n[31]|64,i[0]&=248,F(c,r),a=0;a<16;a++)l[a]=c[a],d[a]=u[a]=f[a]=0;for(u[0]=d[0]=1,a=254;a>=0;--a)P(u,l,o=i[a>>>3]>>>(7&a)&1),P(f,d,o),L(h,u,f),H(u,u,f),L(f,l,d),H(l,l,d),j(d,h),j(p,u),K(u,f,u),K(f,l,h),L(h,u,f),H(u,u,f),j(l,u),H(f,d,p),K(u,f,s),L(u,u,d),K(f,f,u),K(u,d,p),K(d,l,c),j(l,h),P(u,l,o),P(f,d,o);for(a=0;a<16;a++)c[a+16]=u[a],c[a+32]=f[a],c[a+48]=l[a],c[a+64]=d[a];var y=c.subarray(32),v=c.subarray(16);return U(y,y),K(v,v,y),k(e,v),0}function G(e,t){return V(e,t,o)}function Y(e,t){return n(t,32),G(e,t)}function J(e,t,n){var o=new Uint8Array(32);return V(o,n,t),E(e,r,o,b)}D.prototype.blocks=function(e,t,n){for(var r,o,a,i,s,c,u,l,f,d,h,p,y,v,m,g,E,b,A,_=this.fin?0:2048,w=this.h[0],O=this.h[1],D=this.h[2],S=this.h[3],T=this.h[4],C=this.h[5],x=this.h[6],I=this.h[7],N=this.h[8],P=this.h[9],k=this.r[0],R=this.r[1],M=this.r[2],F=this.r[3],L=this.r[4],H=this.r[5],K=this.r[6],j=this.r[7],U=this.r[8],B=this.r[9];n>=16;)d=f=0,d+=(w+=8191&(r=255&e[t+0]|(255&e[t+1])<<8))*k,d+=(O+=8191&(r>>>13|(o=255&e[t+2]|(255&e[t+3])<<8)<<3))*(5*B),d+=(D+=8191&(o>>>10|(a=255&e[t+4]|(255&e[t+5])<<8)<<6))*(5*U),d+=(S+=8191&(a>>>7|(i=255&e[t+6]|(255&e[t+7])<<8)<<9))*(5*j),f=(d+=(T+=8191&(i>>>4|(s=255&e[t+8]|(255&e[t+9])<<8)<<12))*(5*K))>>>13,d&=8191,d+=(C+=s>>>1&8191)*(5*H),d+=(x+=8191&(s>>>14|(c=255&e[t+10]|(255&e[t+11])<<8)<<2))*(5*L),d+=(I+=8191&(c>>>11|(u=255&e[t+12]|(255&e[t+13])<<8)<<5))*(5*F),d+=(N+=8191&(u>>>8|(l=255&e[t+14]|(255&e[t+15])<<8)<<8))*(5*M),h=f+=(d+=(P+=l>>>5|_)*(5*R))>>>13,h+=w*R,h+=O*k,h+=D*(5*B),h+=S*(5*U),f=(h+=T*(5*j))>>>13,h&=8191,h+=C*(5*K),h+=x*(5*H),h+=I*(5*L),h+=N*(5*F),f+=(h+=P*(5*M))>>>13,h&=8191,p=f,p+=w*M,p+=O*R,p+=D*k,p+=S*(5*B),f=(p+=T*(5*U))>>>13,p&=8191,p+=C*(5*j),p+=x*(5*K),p+=I*(5*H),p+=N*(5*L),y=f+=(p+=P*(5*F))>>>13,y+=w*F,y+=O*M,y+=D*R,y+=S*k,f=(y+=T*(5*B))>>>13,y&=8191,y+=C*(5*U),y+=x*(5*j),y+=I*(5*K),y+=N*(5*H),v=f+=(y+=P*(5*L))>>>13,v+=w*L,v+=O*F,v+=D*M,v+=S*R,f=(v+=T*k)>>>13,v&=8191,v+=C*(5*B),v+=x*(5*U),v+=I*(5*j),v+=N*(5*K),m=f+=(v+=P*(5*H))>>>13,m+=w*H,m+=O*L,m+=D*F,m+=S*M,f=(m+=T*R)>>>13,m&=8191,m+=C*k,m+=x*(5*B),m+=I*(5*U),m+=N*(5*j),g=f+=(m+=P*(5*K))>>>13,g+=w*K,g+=O*H,g+=D*L,g+=S*F,f=(g+=T*M)>>>13,g&=8191,g+=C*R,g+=x*k,g+=I*(5*B),g+=N*(5*U),E=f+=(g+=P*(5*j))>>>13,E+=w*j,E+=O*K,E+=D*H,E+=S*L,f=(E+=T*F)>>>13,E&=8191,E+=C*M,E+=x*R,E+=I*k,E+=N*(5*B),b=f+=(E+=P*(5*U))>>>13,b+=w*U,b+=O*j,b+=D*K,b+=S*H,f=(b+=T*L)>>>13,b&=8191,b+=C*F,b+=x*M,b+=I*R,b+=N*k,A=f+=(b+=P*(5*B))>>>13,A+=w*B,A+=O*U,A+=D*j,A+=S*K,f=(A+=T*H)>>>13,A&=8191,A+=C*L,A+=x*F,A+=I*M,A+=N*R,w=d=8191&(f=(f=((f+=(A+=P*k)>>>13)<<2)+f|0)+(d&=8191)|0),O=h+=f>>>=13,D=p&=8191,S=y&=8191,T=v&=8191,C=m&=8191,x=g&=8191,I=E&=8191,N=b&=8191,P=A&=8191,t+=16,n-=16;this.h[0]=w,this.h[1]=O,this.h[2]=D,this.h[3]=S,this.h[4]=T,this.h[5]=C,this.h[6]=x,this.h[7]=I,this.h[8]=N,this.h[9]=P},D.prototype.finish=function(e,t){var n,r,o,a,i=new Uint16Array(10);if(this.leftover){for(a=this.leftover,this.buffer[a++]=1;a<16;a++)this.buffer[a]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(n=this.h[1]>>>13,this.h[1]&=8191,a=2;a<10;a++)this.h[a]+=n,n=this.h[a]>>>13,this.h[a]&=8191;for(this.h[0]+=5*n,n=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=n,n=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=n,i[0]=this.h[0]+5,n=i[0]>>>13,i[0]&=8191,a=1;a<10;a++)i[a]=this.h[a]+n,n=i[a]>>>13,i[a]&=8191;for(i[9]-=8192,r=(1^n)-1,a=0;a<10;a++)i[a]&=r;for(r=~r,a=0;a<10;a++)this.h[a]=this.h[a]&r|i[a];for(this.h[0]=65535&(this.h[0]|this.h[1]<<13),this.h[1]=65535&(this.h[1]>>>3|this.h[2]<<10),this.h[2]=65535&(this.h[2]>>>6|this.h[3]<<7),this.h[3]=65535&(this.h[3]>>>9|this.h[4]<<4),this.h[4]=65535&(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14),this.h[5]=65535&(this.h[6]>>>2|this.h[7]<<11),this.h[6]=65535&(this.h[7]>>>5|this.h[8]<<8),this.h[7]=65535&(this.h[8]>>>8|this.h[9]<<5),o=this.h[0]+this.pad[0],this.h[0]=65535&o,a=1;a<8;a++)o=(this.h[a]+this.pad[a]|0)+(o>>>16)|0,this.h[a]=65535&o;e[t+0]=this.h[0]>>>0&255,e[t+1]=this.h[0]>>>8&255,e[t+2]=this.h[1]>>>0&255,e[t+3]=this.h[1]>>>8&255,e[t+4]=this.h[2]>>>0&255,e[t+5]=this.h[2]>>>8&255,e[t+6]=this.h[3]>>>0&255,e[t+7]=this.h[3]>>>8&255,e[t+8]=this.h[4]>>>0&255,e[t+9]=this.h[4]>>>8&255,e[t+10]=this.h[5]>>>0&255,e[t+11]=this.h[5]>>>8&255,e[t+12]=this.h[6]>>>0&255,e[t+13]=this.h[6]>>>8&255,e[t+14]=this.h[7]>>>0&255,e[t+15]=this.h[7]>>>8&255},D.prototype.update=function(e,t,n){var r,o;if(this.leftover){for((o=16-this.leftover)>n&&(o=n),r=0;r=16&&(o=n-n%16,this.blocks(e,t,o),t+=o,n-=o),n){for(r=0;r=128;){for(_=0;_<16;_++)w=8*_+W,I[_]=n[w+0]<<24|n[w+1]<<16|n[w+2]<<8|n[w+3],N[_]=n[w+4]<<24|n[w+5]<<16|n[w+6]<<8|n[w+7];for(_=0;_<80;_++)if(o=P,a=k,i=R,s=M,c=F,u=L,l=H,K,d=j,h=U,p=B,y=V,v=G,m=Y,g=J,q,S=65535&(D=q),T=D>>>16,C=65535&(O=K),x=O>>>16,S+=65535&(D=(G>>>14|F<<18)^(G>>>18|F<<14)^(F>>>9|G<<23)),T+=D>>>16,C+=65535&(O=(F>>>14|G<<18)^(F>>>18|G<<14)^(G>>>9|F<<23)),x+=O>>>16,S+=65535&(D=G&Y^~G&J),T+=D>>>16,C+=65535&(O=F&L^~F&H),x+=O>>>16,S+=65535&(D=Q[2*_+1]),T+=D>>>16,C+=65535&(O=Q[2*_]),x+=O>>>16,O=I[_%16],T+=(D=N[_%16])>>>16,C+=65535&O,x+=O>>>16,C+=(T+=(S+=65535&D)>>>16)>>>16,S=65535&(D=A=65535&S|T<<16),T=D>>>16,C=65535&(O=b=65535&C|(x+=C>>>16)<<16),x=O>>>16,S+=65535&(D=(j>>>28|P<<4)^(P>>>2|j<<30)^(P>>>7|j<<25)),T+=D>>>16,C+=65535&(O=(P>>>28|j<<4)^(j>>>2|P<<30)^(j>>>7|P<<25)),x+=O>>>16,T+=(D=j&U^j&B^U&B)>>>16,C+=65535&(O=P&k^P&R^k&R),x+=O>>>16,f=65535&(C+=(T+=(S+=65535&D)>>>16)>>>16)|(x+=C>>>16)<<16,E=65535&S|T<<16,S=65535&(D=y),T=D>>>16,C=65535&(O=s),x=O>>>16,T+=(D=A)>>>16,C+=65535&(O=b),x+=O>>>16,k=o,R=a,M=i,F=s=65535&(C+=(T+=(S+=65535&D)>>>16)>>>16)|(x+=C>>>16)<<16,L=c,H=u,K=l,P=f,U=d,B=h,V=p,G=y=65535&S|T<<16,Y=v,J=m,q=g,j=E,_%16==15)for(w=0;w<16;w++)O=I[w],S=65535&(D=N[w]),T=D>>>16,C=65535&O,x=O>>>16,O=I[(w+9)%16],S+=65535&(D=N[(w+9)%16]),T+=D>>>16,C+=65535&O,x+=O>>>16,b=I[(w+1)%16],S+=65535&(D=((A=N[(w+1)%16])>>>1|b<<31)^(A>>>8|b<<24)^(A>>>7|b<<25)),T+=D>>>16,C+=65535&(O=(b>>>1|A<<31)^(b>>>8|A<<24)^b>>>7),x+=O>>>16,b=I[(w+14)%16],T+=(D=((A=N[(w+14)%16])>>>19|b<<13)^(b>>>29|A<<3)^(A>>>6|b<<26))>>>16,C+=65535&(O=(b>>>19|A<<13)^(A>>>29|b<<3)^b>>>6),x+=O>>>16,x+=(C+=(T+=(S+=65535&D)>>>16)>>>16)>>>16,I[w]=65535&C|x<<16,N[w]=65535&S|T<<16;S=65535&(D=j),T=D>>>16,C=65535&(O=P),x=O>>>16,O=e[0],T+=(D=t[0])>>>16,C+=65535&O,x+=O>>>16,x+=(C+=(T+=(S+=65535&D)>>>16)>>>16)>>>16,e[0]=P=65535&C|x<<16,t[0]=j=65535&S|T<<16,S=65535&(D=U),T=D>>>16,C=65535&(O=k),x=O>>>16,O=e[1],T+=(D=t[1])>>>16,C+=65535&O,x+=O>>>16,x+=(C+=(T+=(S+=65535&D)>>>16)>>>16)>>>16,e[1]=k=65535&C|x<<16,t[1]=U=65535&S|T<<16,S=65535&(D=B),T=D>>>16,C=65535&(O=R),x=O>>>16,O=e[2],T+=(D=t[2])>>>16,C+=65535&O,x+=O>>>16,x+=(C+=(T+=(S+=65535&D)>>>16)>>>16)>>>16,e[2]=R=65535&C|x<<16,t[2]=B=65535&S|T<<16,S=65535&(D=V),T=D>>>16,C=65535&(O=M),x=O>>>16,O=e[3],T+=(D=t[3])>>>16,C+=65535&O,x+=O>>>16,x+=(C+=(T+=(S+=65535&D)>>>16)>>>16)>>>16,e[3]=M=65535&C|x<<16,t[3]=V=65535&S|T<<16,S=65535&(D=G),T=D>>>16,C=65535&(O=F),x=O>>>16,O=e[4],T+=(D=t[4])>>>16,C+=65535&O,x+=O>>>16,x+=(C+=(T+=(S+=65535&D)>>>16)>>>16)>>>16,e[4]=F=65535&C|x<<16,t[4]=G=65535&S|T<<16,S=65535&(D=Y),T=D>>>16,C=65535&(O=L),x=O>>>16,O=e[5],T+=(D=t[5])>>>16,C+=65535&O,x+=O>>>16,x+=(C+=(T+=(S+=65535&D)>>>16)>>>16)>>>16,e[5]=L=65535&C|x<<16,t[5]=Y=65535&S|T<<16,S=65535&(D=J),T=D>>>16,C=65535&(O=H),x=O>>>16,O=e[6],T+=(D=t[6])>>>16,C+=65535&O,x+=O>>>16,x+=(C+=(T+=(S+=65535&D)>>>16)>>>16)>>>16,e[6]=H=65535&C|x<<16,t[6]=J=65535&S|T<<16,S=65535&(D=q),T=D>>>16,C=65535&(O=K),x=O>>>16,O=e[7],T+=(D=t[7])>>>16,C+=65535&O,x+=O>>>16,x+=(C+=(T+=(S+=65535&D)>>>16)>>>16)>>>16,e[7]=K=65535&C|x<<16,t[7]=q=65535&S|T<<16,W+=128,r-=128}return r}function X(e,t,n){var r,o=new Int32Array(8),a=new Int32Array(8),i=new Uint8Array(256),s=n;for(o[0]=1779033703,o[1]=3144134277,o[2]=1013904242,o[3]=2773480762,o[4]=1359893119,o[5]=2600822924,o[6]=528734635,o[7]=1541459225,a[0]=4089235720,a[1]=2227873595,a[2]=4271175723,a[3]=1595750129,a[4]=2917565137,a[5]=725511199,a[6]=4215389547,a[7]=327033209,z(o,a,t,n),n%=128,r=0;r=0;--o)$(e,t,r=n[o/8|0]>>(7&o)&1),Z(t,e),Z(e,e),$(e,t,r)}function ne(e,n){var r=[t(),t(),t(),t()];I(r[0],f),I(r[1],d),I(r[2],i),K(r[3],f,d),te(e,r,n)}function re(e,r,o){var a,i=new Uint8Array(64),s=[t(),t(),t(),t()];for(o||n(r,32),X(i,r,32),i[0]&=248,i[31]&=127,i[31]|=64,ne(s,i),ee(e,s),a=0;a<32;a++)r[a+32]=e[a];return 0}var oe=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function ae(e,t){var n,r,o,a;for(r=63;r>=32;--r){for(n=0,o=r-32,a=r-12;o>4)*oe[o],n=t[o]>>8,t[o]&=255;for(o=0;o<32;o++)t[o]-=n*oe[o];for(r=0;r<32;r++)t[r+1]+=t[r]>>8,e[r]=255&t[r]}function ie(e){var t,n=new Float64Array(64);for(t=0;t<64;t++)n[t]=e[t];for(t=0;t<64;t++)e[t]=0;ae(e,n)}function se(e,n,r,o){var a,i,s=new Uint8Array(64),c=new Uint8Array(64),u=new Uint8Array(64),l=new Float64Array(64),f=[t(),t(),t(),t()];X(s,o,32),s[0]&=248,s[31]&=127,s[31]|=64;var d=r+64;for(a=0;a>7&&H(e[0],a,e[0]),K(e[3],e[0],e[1]),0)}(d,o))return-1;for(s=0;s=0},e.sign.keyPair=function(){var e=new Uint8Array(fe),t=new Uint8Array(de);return re(e,t),{publicKey:e,secretKey:t}},e.sign.keyPair.fromSecretKey=function(e){if(pe(e),e.length!==de)throw new Error("bad secret key size");for(var t=new Uint8Array(fe),n=0;n{if(Array.isArray(t))return t.map(e);if(t instanceof Object){let n=[],r=[];return Object.keys(t).forEach((e=>{/^(0|[1-9][0-9]*)$/.test(e)?n.push(+e):r.push(e)})),n.sort((function(e,t){return e-t})).concat(r.sort()).reduce(((n,r)=>(n[r]=e(t[r]),n)),{})}return t},t=JSON.stringify.bind(JSON);return v=(n,r,o)=>{let a=t(n,r,0);if(!a||"{"!==a[0]&&"["!==a[0])return a;let i=JSON.parse(a);return t(e(i),null,o)}}())}function S(){return b||(b=1,function(e){e.exports&&(e.exports=function(e,t){const n=globalThis;var r,o={},a=void 0===n.Proxy,i=o.DeepProxy=function(){var e={},r=e.isArray=Array.isArray||function(e){return"[object Array]"===Object.toString(e)},o=e.type=function(e){return null===e?"null":r(e)?"array":typeof e},i=e.isProxyable=function(e,t){return(void 0!==t||!a)&&-1!==["object","array"].indexOf(o(e))},s=e.set=function(t){return function(n,r,o){if("on"===r)throw new Error("'on' is a reserved attribute name for realtime lists and maps");return i(o)?n[r]=e.create(o,t):n[r]=o,t(),n[r]||!0}},c=e.pathMatches=function(e,t){return!t.some((function(t,n){return t!==e[n]}))},u=function(e,t){return t.pattern.length-e.pattern.length},l=function(e){return function(t,n,r){switch(t){case"change":n="array"===o(n)?n:[n],e.change.push({cb:function(e,t,o,a){if(c(o,n))return r(e,t,o,a)},pattern:n}),e.change.sort(u);break;case"remove":n="array"===o(n)?n:[n],e.remove.push({cb:function(e,t,o){if(c(t,n))return r(e,t,o)},pattern:n}),e.remove.sort(u);break;case"ready":e.ready.push({cb:function(e){n(e)}});break;case"cacheready":e.cacheready.push({cb:function(e){n(e)}});break;case"disconnect":e.disconnect.push({cb:function(e){n(e)}});break;case"reconnect":e.reconnect.push({cb:function(e){n(e)}});break;case"create":e.create.push({cb:function(e){n(e)}});break;case"error":e.error.push({cb:function(e){n(e)}})}return this}},f=e.get=function(){var e={cacheready:[],disconnect:[],reconnect:[],change:[],ready:[],remove:[],create:[],error:[]};return function(t,n){return"on"===n?l(e):"_isProxy"===n||("_events"===n?e:t[n])}},d=e.delete=function(e){return function(t,n){return void 0===t[n]||(delete t[n],e()),!0}},h=e.handlers=function(e,t){return t?{set:s(e),get:f(e),deleteProperty:d(e)}:{set:s(e),get:function(e,t){return"_isProxy"===t||e[t]},deleteProperty:d(e)}},p=e.remoteChangeFlag=!1,y=e.stringifyFakeProxy=function(e){var n=JSON.parse(t(e));return delete n._events,delete n._isProxy,t(n)};e.checkLocalChange=function(t,r){if(a&&!e.interval){var o=y(t);e.interval=n.setInterval((function(){var e=y(t);e!==o&&(o=e,p?p=!1:r())}),300)}};var v=e.create=function(e,t,r){var s="function"===o(t)?h(t,r):t;switch(o(e)){case"object":Object.keys(e).forEach((function(n){i(e[n])&&!e[n]._isProxy&&(e[n]=v(e[n],t))}));break;case"array":e.forEach((function(n,r){i(n)&&!n._isProxy&&(e[r]=v(e[r],t))}));break;default:throw new Error("attempted to make a proxy of an unproxyable object")}if(!a)return e._isProxy?e:new n.Proxy(e,s);var c=JSON.parse(JSON.stringify(e));if(r){var u={cacheready:[],disconnect:[],reconnect:[],change:[],ready:[],remove:[],create:[],error:[]};c.on=l(u),c._events=u}return c},m=function(e,t,n,r,o){var a=e.slice(0);a.push(t),n._events.change.some((function(e){return!1===e.cb(r,o,a,n)}))},g=e.find=function(e,t){for(var n=t.length,r=0;rs)for(var c,u=s;u<=s;u++)c=e[u],E(r,u,a,c,!0);e.length=s}};return e.update=function(e,t,n){var r=o(e),a=o(t);if(r!==a)throw new Error("Proxy updates can't result in type changes");switch(a){case"array":A.call(e,e,t,(function(e){return v(e,n)}),[],e);break;case"object":b.call(e,e,t,(function(e){return v(e,n)}),[],e);break;default:throw new Error("unsupported realtime datatype:"+a)}},e}();return o.create=function(o){if(!i.isProxyable(o.data,!0))throw new Error("unsupported datatype: "+i.type(o.data));if("function"!=typeof(r=o.ChainPad||n.ChainPad).SmartJSONTransformer)throw new Error("Please update ChainPad");o.classic&&!o.crypto&&(console.error("[chainpad-listmap] no crypto module provided. messages will not be encrypted"),o.crypto={encrypt:function(e){return e},decrypt:function(e){return e}});var s=o.readOnly,c={initialState:t(o.data),patchTransformer:r.SmartJSONTransformer,validateContent:o.validateContent||function(e){try{return JSON.parse(e),!0}catch(t){return console.log(e),console.error("Failed to parse, rejecting patch"),!1}},readOnly:o.readOnly,userName:o.userName||"listmap",Cache:o.Cache,logLevel:void 0===o.logLevel?0:o.logLevel};o.classic&&(c.channel=o.channel,c.crypto=o.crypto,c.network=o.network,c.websocketURL=o.websocketURL,c.metadata=o.metadata||{validateKey:o.validateKey,owners:o.owners,expire:o.expire},c.onRejected=o.onRejected);var u,l,f,d={metadata:{}},h=!0,p=!1,y=a?i.stringifyFakeProxy:t,v=function(){var e=y(l);try{u.contentUpdate(e)}catch(e){l._events.error.forEach((function(t){t.cb({type:"CHAINPAD",error:e.message})}))}o.onLocal&&o.onLocal()},m=c.onLocal=function(e){h||s||(clearTimeout(f),e?v():f=setTimeout(v))},g=function(){i.remoteChangeFlag||m()};l=i.create(o.data,g,!0),c.onInit=function(e){l._events.create.forEach((function(t){t.cb(e)}))},c.onCacheReady=function(e){u&&u===e.realtime||(u=d.realtime=e.realtime);var t=u.getUserDoc(),n=JSON.parse(t);i.update(l,n,g),i.checkLocalChange(l,m),p||l._events.cacheready.forEach((function(t){t.cb(e)}))};var E=0;c.onReady=function(e){if(E=-1,p)return h=!1,c.onRemote(),void l._events.reconnect.forEach((function(t){t.cb(e)}));u&&u===e.realtime||(u=d.realtime=e.realtime),d.metadata=e.metadata;var t=u.getUserDoc(),n=JSON.parse(t);i.update(l,n,g),i.checkLocalChange(l,m),h=!1,p=!0,l._events.ready.forEach((function(t){t.cb(e)}))},c.onRemote=function(){if(!h){var e=u.getUserDoc(),t=JSON.parse(e);i.remoteChangeFlag=!0,i.update(l,t,g),i.remoteChangeFlag=!1}},c.onMessage=function(){-1!==E&&o.updateProgress&&o.updateProgress({progress:E++})},c.onAbort=function(e){l._events.disconnect.forEach((function(t){t.cb(e)}))},c.onConnectionChange=function(e){e.state?h=!0:l._events.disconnect.forEach((function(t){t.cb(e)}))},c.onMetadataUpdate=function(e){d.metadata=e,"function"==typeof o.onMetadataUpdate&&o.onMetadataUpdate(e)},c.onError=function(e){l._events.error.forEach((function(t){t.cb(e)}))},c.onChannelError=function(e){l._events.error.forEach((function(t){t.cb(e)}))},o.common&&"function"==typeof o.common.startRealtime?u=d.cpCnInner=o.common.startRealtime(c):d=e.start(c),d.proxy=l,d.realtime=u;var b=d.setReadOnly;return d.setReadOnly=function(e,t){s=e,b&&b(e,t)},d},o}(O(),D()))}(i)),i.exports}var T,C=S(),x={exports:{}};function I(){return T||(T=1,function(e){var t,r,o,a;a=function(){var e=l,t=function(n,r,o){r||(r=0);var a=t.resolve(n,r),i=t.m[r][a];if(!i&&e){if(i=e(a))return i}else if(i&&i.c&&(r=i.c,a=i.m,!(i=t.m[r][i.m])))throw new Error('failed to require "'+a+'" from '+r);if(!i)throw new Error('failed to require "'+n+'" from '+o);return i.exports||(i.exports={},i.call(i.exports,i,i.exports,t.relative(a,r))),i.exports};return t.resolve=function(e,n){var r=e,o=e+".js",a=e+"/index.js";return t.m[n][o]&&o?o:t.m[n][a]&&a?a:r},t.relative=function(e,n){return function(r){if("."!=r.charAt(0))return t(r,n,e);var o=e.split("/"),a=r.split("/");o.pop();for(var i=0;i=0;n--)o.check(e.operations[n],t),n>0&&r.assert(!o.shouldMerge(e.operations[n],e.operations[n-1])),"number"==typeof t&&(t+=o.lengthChange(e.operations[n]));return e.isCheckpoint&&(r.assert(1===e.operations.length),r.assert(0===e.operations[0].offset),"number"==typeof t&&r.assert(!t||e.operations[0].toRemove===t)),e};i.toObj=function(e){r.PARANOIA&&c(e);var t,n=new Array(e.operations.length+1);for(t=0;t0);var n,i=s(a.check(e[e.length-1]),t);for(n=0;n=0;n--)l(e,t.operations[n]);return e},i.apply=function(e,t){r.PARANOIA&&(c(e),r.assert("string"==typeof t),r.assert(a.hex_sha256(t)===e.parentHash));for(var n=t,i=e.operations.length-1;i>=0;i--)n=o.apply(e.operations[i],n);return n},i.lengthChange=function(e){r.PARANOIA&&c(e);for(var t=0,n=0;n=0;u--)i[u]=o.invert(e.operations[u],n),n=o.apply(e.operations[u],n);var l=new Array(e.operations.length);!function(){for(var e=i.length-1;e>=0;e--){l[e]=i[e].offset;for(var t=e-1;t>=0;t--)l[e]+=i[t].toRemove-i[t].toInsert.length}}();var f=s(a.hex_sha256(n),e.isCheckpoint);f.operations.splice(0,f.operations.length);for(var d=0;d=0;d--){var h=n(e.operations[d],u,o.simplify);h&&(u=o.apply(h,u),l[f++]=h)}return Array.prototype.push.apply(i.operations,l.reverse()),i.operations[0]||i.operations.shift(),r.PARANOIA&&c(i),i},i.equals=function(e,t){if(e.operations.length!==t.operations.length)return!1;for(var n=0;n0;){var u=o.random(i);i+=o.lengthChange(u),l(n,u)}return c(n),n},Object.freeze(e.exports)},"SHA256.js":function(e,t,n){!function(){function t(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function n(e,t){return e>>>t|e<<32-t}function r(e,t){return e>>>t}function o(e,t,n){return e&t^~e&n}function a(e,t,n){return e&t^e&n^t&n}function i(e){return n(e,2)^n(e,13)^n(e,22)}function s(e){return n(e,6)^n(e,11)^n(e,25)}function c(e){return n(e,7)^n(e,18)^r(e,3)}e.exports.hex_sha256=function(e){return function(e){for(var t="0123456789abcdef",n="",r=0;r<4*e.length;r++)n+=t.charAt(e[r>>2]>>8*(3-r%4)+4&15)+t.charAt(e[r>>2]>>8*(3-r%4)&15);return n}(function(e,u){var l,f,d,h,p,y,v,m,g,E,b,A=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],_=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],w=function(e){for(var t=[];e>0;e--)t.push(void 0);return t}(64);e[u>>5]|=128<<24-u%32,e[15+(u+64>>9<<4)]=u;for(var O=0;O>5]|=(255&e.charCodeAt(n/8))<<24-n%32;return t}(e),8*e.length))}}()},"Common.js":function(e,t,r){e.exports.global=function(){if("undefined"!=typeof self)return self;if(void 0!==n)return n;if("undefined"!=typeof window)return window;throw new Error("no self, nor global, nor window")}();var o=function(t){return"undefined"!=typeof localStorage&&localStorage[t]?localStorage[t]:e.exports.global[t]},a=e.exports.PARANOIA=o("ChainPad_PARANOIA");e.exports.VALIDATE_ENTIRE_CHAIN_EACH_MSG=o("ChainPad_VALIDATE_ENTIRE_CHAIN_EACH_MSG"),e.exports.TESTING=o("ChainPad_TESTING"),e.exports.assert=function(e){if(!e)throw new Error("Failed assertion")},e.exports.isUint=function(e){return"number"==typeof e&&Math.floor(e)===e&&e>=0},e.exports.randomASCII=function(e){for(var t=[],n=0;nt?1:-1},Object.freeze(e.exports)},"sha256.js":function(e,t,n){var r=n("./sha256/exports.js"),o=n("./SHA256.js"),a=n("./Common");e.exports.check=function(e){if("string"!=typeof e)throw new Error;if(!/[a-f0-9]{64}/.test(e))throw new Error;return e},e.exports.hex_sha256=function(e){e+="";var t=r.hex(function(e){for(var t=new Uint8Array(e.length),n=0;n1&&console.log("["+e.userName+"] "+t)},d=function(e,t){e.logLevel>0&&console.error("["+e.userName+"] "+t)},h=function(e,t,n){if(!e.aborted){n||(n=Math.floor(2*Math.random()*e.config.avgSyncMilliseconds));var r=setTimeout((function(){e.schedules.splice(e.schedules.indexOf(r),1),t()}),n);return e.schedules.push(r),r}},p=function(e,t){var n=e.schedules.indexOf(t);n>-1&&e.schedules.splice(n,1),clearTimeout(t)},y=function(e,t,n,o){var a=i.toStr(t);if(function(e,t,n){e.messageHandlers.length||n("no onMessage() handler registered");try{e.messageHandlers.forEach((function(e){e(t,(function(){n.apply(null,arguments),n=function(){}}))}))}catch(e){n(e.stack)}}(e,a,(function(n){if(n)f(e,"Posting to server failed ["+n+"]"),e.pending=null,e.syncSchedule=h(e,(function(){g(e)}));else{var o=e.pending;if(e.pending=null,!o)throw new Error;r.assert(o.hash===t.hashOf),P(e,a,!0)?(e.timeOfLastSuccess=+new Date,e.lag=+new Date-o.timeSent):f(e,"Our message ["+t.hashOf+"] failed validation"),o.callback()}})),e.pending)throw new Error("there is already a pending message");-1===e.timeOfLastSuccess&&(e.timeOfLastSuccess=+new Date),e.pending={hash:t.hashOf,timeSent:+new Date,callback:function(){e.syncSchedule=h(e,(function(){g(e)}),0),n()}},r.PARANOIA&&_(e)},v=function(e){var t=e.onSettle;e.onSettle=[],t.forEach((function(t){try{t()}catch(t){d(e,"Error in onSettle handler ["+t.stack+"]")}}))},m=function(e){if(!e.mut.inverseOf)throw new Error;return e.mut.inverseOf},g=function(e,t){if(r.PARANOIA&&_(e),e.syncSchedule&&!e.pending){if(p(e,e.syncSchedule),e.syncSchedule=null,e.uncommitted=a.simplify(e.uncommitted,e.authDoc,e.config.operationSimplify),0===e.uncommitted.operations.length)return v(e),e.timeOfLastSuccess=+new Date,void(e.syncSchedule=h(e,(function(){g(e)})));var n=D(e,e.best)+1;if(n%e.config.checkpointInterval!=0){var o;o=e.setContentPatch?e.setContentPatch:i.create(i.PATCH,e.uncommitted,e.best.hashOf),y(e,o,(function(){e.setContentPatch&&(f(e,"initial Ack received ["+o.hashOf+"]"),e.setContentPatch=null)}))}else{var s=e.best;if(f(e,"Sending checkpoint (interval ["+e.config.checkpointInterval+"]) patch no ["+n+"]"),f(e,D(e,e.best)),!s||!s.content||!m(s.content))throw new Error;var c=a.createCheckpoint(e.authDoc,e.authDoc,m(s.content).parentHash),u=i.create(i.CHECKPOINT,c,s.hashOf);y(e,u,(function(){f(e,"Checkpoint sent and accepted")}))}}},E=function(e,t){r.assert(t.lastMsgHash),r.assert(t.hashOf),e.messages[t.hashOf]=t,(e.messagesByParent[t.lastMsgHash]=e.messagesByParent[t.lastMsgHash]||[]).push(t)},b=function(e,t){r.assert(t.lastMsgHash),r.assert(t.hashOf),delete e.messages[t.hashOf];var n=e.messagesByParent[t.lastMsgHash];r.assert(n.indexOf(t)>-1),n.splice(n.indexOf(t),1),0===n.length&&delete e.messagesByParent[t.lastMsgHash];var o=e.messagesByParent[t.hashOf];if(o)for(var a=0;aD(e,n)&&(n=o)})),n},C=function(e,t){t.operations.length&&(e.patchHandlers.forEach((function(e){e(t)})),e.changeHandlers.forEach((function(e){t.operations.forEach((function(t){e(t.offset,t.toRemove,t.toInsert)}))})))},x=function(e,t){try{return e.config.validateContent(t())}catch(t){d(e,"Error in content validator ["+t.stack+"]")}return!1},I=function(e,t,n){for(var r=A(e,t);r;r=A(e,r))if(!1===n(r))return},N=function(e,t){e.mut.inverseOf||((e.mut.inverseOf=a.invert(e,t)).mut.inverseOf=e)},P=function(e,t,n){r.PARANOIA&&_(e);var c=i.fromString(t);if(f(e,JSON.stringify([c.hashOf,c.content.operations])),e.messages[c.hashOf]){if(e.setContentPatch&&e.setContentPatch.hashOf===c.hashOf)e.setContentPatch=null;else{if(c.content.isCheckpoint)return f(e,"["+(n?"our":"their")+"] Checkpoint ["+c.hashOf+"] is already known"),!0;f(e,"Patch ["+c.hashOf+"] is already known")}r.PARANOIA&&_(e)}else if(!c.content.isCheckpoint||x(e,(function(){return c.content.operations[0].toInsert}))){if(E(e,c),!O(e,e.rootMessage,c)){if(c.content.isCheckpoint&&e.best.mut.isInitialMessage){f(e,"applying checkpoint ["+c.hashOf+"]");var u=a.apply(e.uncommitted,e.authDoc);r.assert(!r.PARANOIA||e.userInterfaceContent===u);var l=a.invert(e.uncommitted,e.authDoc);return a.addOperation(l,o.create(0,e.authDoc.length,c.content.operations[0].toInsert)),l=a.simplify(l,u,e.config.operationSimplify),c.mut.parentCount=0,e.rootMessage=e.best=c,e.authDoc=c.content.operations[0].toInsert,e.uncommitted=a.create(s.hex_sha256(e.authDoc)),C(e,l),r.PARANOIA&&(e.userInterfaceContent=e.authDoc),!0}return f(e,"Patch ["+c.hashOf+"] not connected to root (parent: ["+c.lastMsgHash+"])"),void(r.PARANOIA&&_(e))}(c=T(e,c)).mut.isFromMe=n;var d=c.content,h=[],p=e.best;if(!O(e,e.best,c)){var y=D(e,e.best),g=D(e,c);if(!(y0))return f(e,"Patch ["+c.hashOf+"] chain is ["+g+"] best chain is ["+y+"]"),r.PARANOIA&&_(e),!0;for(;p&&!O(e,p,c);)h.push(p),p=A(e,p);r.assert(p),f(e,"Patch ["+c.hashOf+"] better than best chain, switching")}var P=[],k=c;do{P.unshift(k),k=A(e,k),r.assert(k)}while(k!==p);var R=e.authDoc;h.forEach((function(e){R=a.apply(m(e.content),R)})),P.forEach((function(e,t){t!==P.length-1&&(N(e.content,R),R=a.apply(e.content,R))}));var M=e.best;if(P.length>1?(M=P[P.length-2],r.assert(M)):h.length&&(M=A(e,h[h.length-1]),r.assert(M)),r.assert(m(M.content).parentHash),r.assert(!r.PARANOIA||m(M.content).parentHash===s.hex_sha256(R)),m(M.content).parentHash===d.parentHash){if(d.isCheckpoint&&e.config.noPrune);else if(d.isCheckpoint){var F;if(I(e,c,(function(e){if(e.content.isCheckpoint){if(F)return F=e,!1;F=e}})),F&&F!==e.rootMessage){var L=D(e,F);if(e.config.strictCheckpointValidation&&L%e.config.checkpointInterval!=0){if(f(e,"checkpoint ["+c.hashOf+"] at invalid point ["+L+"]"),r.PARANOIA&&_(e),r.TESTING)throw new Error;return void b(e,c)}f(e,"checkpoint ["+c.hashOf+"]"),I(e,F,(function(t){f(e,"pruning ["+t.hashOf+"]"),b(e,t)})),e.rootMessage=F}}else{var H=a.simplify(d,R,e.config.operationSimplify);if(!a.equals(H,d)){if(f(e,"patch ["+c.hashOf+"] can be simplified"),r.PARANOIA&&_(e),r.TESTING)throw new Error;return void b(e,c)}if(!x(e,(function(){return a.apply(d,R)})))return void f(e,"Patch ["+c.hashOf+"] failed content validation")}N(d,R),e.uncommitted=a.simplify(e.uncommitted,e.authDoc,e.config.operationSimplify);var K=a.apply(e.uncommitted,e.authDoc);r.PARANOIA&&r.assert(K===e.userInterfaceContent);var j=a.invert(e.uncommitted,e.authDoc);if(h.forEach((function(t){f(e,"reverting ["+t.hashOf+"]"),t.mut.isFromMe&&f(e,"reverting patch 'from me' ["+JSON.stringify(t.content.operations)+"]"),j=a.merge(j,m(t.content)),function(e,t,n){S(e,t,m(n))}(e,t.mut.isFromMe,t.content)})),P.forEach((function(t){f(e,"applying ["+t.hashOf+"]"),j=a.merge(j,t.content),S(e,t.mut.isFromMe,t.content)})),j=a.merge(j,e.uncommitted),j=a.simplify(j,K,e.config.operationSimplify),e.best=c,r.PARANOIA){var U=a.apply(j,K);r.assert(e.userInterfaceContent.length===w(e)),r.assert(U===e.userInterfaceContent)}return C(e,j),e.uncommitted.operations.length||v(e),r.PARANOIA&&_(e),!0}if(f(e,"patch ["+c.hashOf+"] parentHash is not valid"),r.PARANOIA&&_(e),r.TESTING)throw new Error;b(e,c)}else f(e,"Checkpoint ["+c.hashOf+"] failed content validation")},k=function(e,t){return Object.freeze({type:"Block",hashOf:t.hashOf,lastMsgHash:t.lastMsgHash,isCheckpoint:!!t.content.isCheckpoint,isFromMe:t.mut&&t.mut.isFromMe,author:t.mut&&t.mut.author,serverHash:t.mut&&t.mut.serverHash,time:t.mut&&t.mut.time,getParent:function(){var n=A(e,t);if(n)return k(e,n)},getContent:function(){return function(e,t){for(var n=[t];n[0]!==e.rootMessage;){var o=A(e,n[0]);if(!o)return{error:"not connected to root",doc:void 0};n.unshift(o)}var i="";e.rootMessage.content.operations.length&&(r.assert(1===e.rootMessage.content.operations.length),i=e.rootMessage.content.operations[0].toInsert);for(var s=1;s=0;n--)t=s(e[n],t);return t};var c=o.invert=function(e,t){return r.PARANOIA&&(a(e),r.assert("string"==typeof t),r.assert(e.offset+e.toRemove<=t.length)),i(e.offset,e.toInsert.length,(" "+t.substring(e.offset,e.offset+e.toRemove)).slice(1))},u=/[\uD800-\uDBFF]|[\uDC00-\uDFFF]/,l=o.hasSurrogate=function(e){return u.test(e)};o.simplify=function(e,t){r.PARANOIA&&(a(e),r.assert("string"==typeof t),r.assert(e.offset+e.toRemove<=t.length));for(var n=c(e,t),o=Math.min(e.toInsert.length,n.toInsert.length),s=0;s=0&&h[s]===d[s];s--);d=d.substring(0,s+1),f=s+1}return 0===f&&0===d.length?null:i(u,f,d)},o.equals=function(e,t){return e.toRemove===t.toRemove&&e.toInsert===t.toInsert&&e.offset===t.offset},o.lengthChange=function(e){return r.PARANOIA&&a(e),e.toInsert.length-e.toRemove},o.merge=function(e,t){r.PARANOIA&&(a(t),a(e));var n=e.offset,o=e.toRemove,s=e.toInsert,c=t.offset,u=t.toRemove,l=t.toInsert,f=c-n;if(u>0){var d=s;s=s.substring(0,f)+s.substring(f+u),(u-=d.length-s.length)<0&&(u=0),o+=u,u=0}if(f<0)n+=f,s=l+s;else if(s.length===f)s+=l;else{if(!(s.length>f))throw new Error("should never happen\n"+JSON.stringify([e,t],null," "));s=s.substring(0,f)+l+s.substring(f)}return""===s&&0===o?null:i(n,o,s)},o.shouldMerge=function(e,t){return r.PARANOIA&&(a(e),a(t)),t.offset0;)a+=c=r._heap_write(n,o+a,e,i,s),i+=c,s-=c,o+=c=t.process(o,a),(a-=c)||(o=0);return this.pos=o,this.len=a,this},e.exports.hash_finish=function(){if(null!==this.result)throw new IllegalStateError("state must be reset before processing new data");return this.asm.finish(this.pos,this.len,0),this.result=new Uint8Array(this.HASH_SIZE),this.result.set(this.heap.subarray(0,this.HASH_SIZE)),this.pos=0,this.len=0,this}},"sha256/utils.js":function(e,t,n){var r=e.exports.string_to_bytes=function(e,t){t=!!t;for(var n=e.length,r=new Uint8Array(t?4*n:n),o=0,a=0;o=n)throw new Error("Malformed string, low surrogate expected at position "+o);i=(55296^i)<<10|65536|56320^e.charCodeAt(o)}else if(!t&&i>>>8)throw new Error("Wide characters are not allowed.");!t||i<=127?r[a++]=i:i<=2047?(r[a++]=192|i>>6,r[a++]=128|63&i):i<=65535?(r[a++]=224|i>>12,r[a++]=128|i>>6&63,r[a++]=128|63&i):(r[a++]=240|i>>18,r[a++]=128|i>>12&63,r[a++]=128|i>>6&63,r[a++]=128|63&i)}return r.subarray(0,a)};e.exports.hex_to_bytes=function(e){var t=e.length;1&t&&(e="0"+e,t++);for(var n=new Uint8Array(t>>1),r=0;r>1]=parseInt(e.substr(r,2),16);return n},e.exports.base64_to_bytes=function(e){return r(atob(e))};var o=e.exports.bytes_to_string=function(e,t){t=!!t;for(var n=e.length,r=new Array(n),o=0,a=0;o=192&&i<224&&o+1=224&&i<240&&o+2=240&&i<248&&o+3>10,r[a++]=56320|1023&s)}}for(var c="",u=16384,l=0;l>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e+=1},e.exports.is_number=function(e){return"number"==typeof e},e.exports.is_string=function(e){return"string"==typeof e},e.exports.is_buffer=function(e){return e instanceof ArrayBuffer},e.exports.is_bytes=function(e){return e instanceof Uint8Array},e.exports.is_typed_array=function(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array||e instanceof Float64Array},e.exports._heap_init=function(e,t){var n=t.heap,r=n?n.byteLength:t.heapSize||65536;if(4095&r||r<=0)throw new Error("heap size must be a positive integer and a multiple of 4096");return n=n||new e(new ArrayBuffer(r))},e.exports._heap_write=function(e,t,n,r,o){var a=e.length-t,i=a>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x428a2f98|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=t+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x71374491|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=n+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xb5c0fbcf|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=f+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xe9b5dba5|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=d+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x3956c25b|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=h+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x59f111f1|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=p+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x923f82a4|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=y+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xab1c5ed5|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=v+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xd807aa98|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=m+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x12835b01|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=g+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x243185be|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=E+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x550c7dc3|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=b+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x72be5d74|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=A+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x80deb1fe|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=_+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x9bdc06a7|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;P=w+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xc19bf174|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;e=P=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+e+m|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xe49b69c1|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;t=P=(n>>>7^n>>>18^n>>>3^n<<25^n<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+t+g|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xefbe4786|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;n=P=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+n+E|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x0fc19dc6|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;f=P=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+f+b|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x240ca1cc|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;d=P=(h>>>7^h>>>18^h>>>3^h<<25^h<<14)+(n>>>17^n>>>19^n>>>10^n<<15^n<<13)+d+A|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x2de92c6f|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;h=P=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+h+_|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x4a7484aa|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;p=P=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+p+w|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x5cb0a9dc|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;y=P=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(h>>>17^h>>>19^h>>>10^h<<15^h<<13)+y+e|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x76f988da|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;v=P=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+v+t|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x983e5152|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;m=P=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+m+n|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xa831c66d|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;g=P=(E>>>7^E>>>18^E>>>3^E<<25^E<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+g+f|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xb00327c8|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;E=P=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+E+d|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xbf597fc7|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;b=P=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+b+h|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xc6e00bf3|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;A=P=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(E>>>17^E>>>19^E>>>10^E<<15^E<<13)+A+p|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xd5a79147|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;_=P=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+_+y|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x06ca6351|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;w=P=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+w+v|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x14292967|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;e=P=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+e+m|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x27b70a85|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;t=P=(n>>>7^n>>>18^n>>>3^n<<25^n<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+t+g|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x2e1b2138|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;n=P=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+n+E|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x4d2c6dfc|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;f=P=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+f+b|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x53380d13|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;d=P=(h>>>7^h>>>18^h>>>3^h<<25^h<<14)+(n>>>17^n>>>19^n>>>10^n<<15^n<<13)+d+A|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x650a7354|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;h=P=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+h+_|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x766a0abb|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;p=P=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+p+w|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x81c2c92e|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;y=P=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(h>>>17^h>>>19^h>>>10^h<<15^h<<13)+y+e|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x92722c85|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;v=P=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+v+t|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xa2bfe8a1|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;m=P=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+m+n|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xa81a664b|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;g=P=(E>>>7^E>>>18^E>>>3^E<<25^E<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+g+f|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xc24b8b70|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;E=P=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+E+d|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xc76c51a3|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;b=P=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+b+h|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xd192e819|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;A=P=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(E>>>17^E>>>19^E>>>10^E<<15^E<<13)+A+p|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xd6990624|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;_=P=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+_+y|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xf40e3585|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;w=P=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+w+v|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x106aa070|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;e=P=(t>>>7^t>>>18^t>>>3^t<<25^t<<14)+(_>>>17^_>>>19^_>>>10^_<<15^_<<13)+e+m|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x19a4c116|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;t=P=(n>>>7^n>>>18^n>>>3^n<<25^n<<14)+(w>>>17^w>>>19^w>>>10^w<<15^w<<13)+t+g|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x1e376c08|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;n=P=(f>>>7^f>>>18^f>>>3^f<<25^f<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+n+E|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x2748774c|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;f=P=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(t>>>17^t>>>19^t>>>10^t<<15^t<<13)+f+b|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x34b0bcb5|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;d=P=(h>>>7^h>>>18^h>>>3^h<<25^h<<14)+(n>>>17^n>>>19^n>>>10^n<<15^n<<13)+d+A|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x391c0cb3|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;h=P=(p>>>7^p>>>18^p>>>3^p<<25^p<<14)+(f>>>17^f>>>19^f>>>10^f<<15^f<<13)+h+_|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x4ed8aa4a|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;p=P=(y>>>7^y>>>18^y>>>3^y<<25^y<<14)+(d>>>17^d>>>19^d>>>10^d<<15^d<<13)+p+w|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x5b9cca4f|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;y=P=(v>>>7^v>>>18^v>>>3^v<<25^v<<14)+(h>>>17^h>>>19^h>>>10^h<<15^h<<13)+y+e|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x682e6ff3|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;v=P=(m>>>7^m>>>18^m>>>3^m<<25^m<<14)+(p>>>17^p>>>19^p>>>10^p<<15^p<<13)+v+t|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x748f82ee|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;m=P=(g>>>7^g>>>18^g>>>3^g<<25^g<<14)+(y>>>17^y>>>19^y>>>10^y<<15^y<<13)+m+n|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x78a5636f|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;g=P=(E>>>7^E>>>18^E>>>3^E<<25^E<<14)+(v>>>17^v>>>19^v>>>10^v<<15^v<<13)+g+f|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x84c87814|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;E=P=(b>>>7^b>>>18^b>>>3^b<<25^b<<14)+(m>>>17^m>>>19^m>>>10^m<<15^m<<13)+E+d|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x8cc70208|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;b=P=(A>>>7^A>>>18^A>>>3^A<<25^A<<14)+(g>>>17^g>>>19^g>>>10^g<<15^g<<13)+b+h|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0x90befffa|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;A=P=(_>>>7^_>>>18^_>>>3^_<<25^_<<14)+(E>>>17^E>>>19^E>>>10^E<<15^E<<13)+A+p|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xa4506ceb|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;_=P=(w>>>7^w>>>18^w>>>3^w<<25^w<<14)+(b>>>17^b>>>19^b>>>10^b<<15^b<<13)+_+y|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xbef9a3f7|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;w=P=(e>>>7^e>>>18^e>>>3^e<<25^e<<14)+(A>>>17^A>>>19^A>>>10^A<<15^A<<13)+w+v|0;P=P+N+(C>>>6^C>>>11^C>>>25^C<<26^C<<21^C<<7)+(I^C&(x^I))+0xc67178f2|0;N=I;I=x;x=C;C=T+P|0;T=S;S=D;D=O;O=P+(D&S^T&(D^S))+(D>>>2^D>>>13^D>>>22^D<<30^D<<19^D<<10)|0;r=r+O|0;o=o+D|0;a=a+S|0;i=i+T|0;s=s+C|0;c=c+x|0;u=u+I|0;l=l+N|0}function N(e){e=e|0;I(x[e|0]<<24|x[e|1]<<16|x[e|2]<<8|x[e|3],x[e|4]<<24|x[e|5]<<16|x[e|6]<<8|x[e|7],x[e|8]<<24|x[e|9]<<16|x[e|10]<<8|x[e|11],x[e|12]<<24|x[e|13]<<16|x[e|14]<<8|x[e|15],x[e|16]<<24|x[e|17]<<16|x[e|18]<<8|x[e|19],x[e|20]<<24|x[e|21]<<16|x[e|22]<<8|x[e|23],x[e|24]<<24|x[e|25]<<16|x[e|26]<<8|x[e|27],x[e|28]<<24|x[e|29]<<16|x[e|30]<<8|x[e|31],x[e|32]<<24|x[e|33]<<16|x[e|34]<<8|x[e|35],x[e|36]<<24|x[e|37]<<16|x[e|38]<<8|x[e|39],x[e|40]<<24|x[e|41]<<16|x[e|42]<<8|x[e|43],x[e|44]<<24|x[e|45]<<16|x[e|46]<<8|x[e|47],x[e|48]<<24|x[e|49]<<16|x[e|50]<<8|x[e|51],x[e|52]<<24|x[e|53]<<16|x[e|54]<<8|x[e|55],x[e|56]<<24|x[e|57]<<16|x[e|58]<<8|x[e|59],x[e|60]<<24|x[e|61]<<16|x[e|62]<<8|x[e|63])}function P(e){e=e|0;x[e|0]=r>>>24;x[e|1]=r>>>16&255;x[e|2]=r>>>8&255;x[e|3]=r&255;x[e|4]=o>>>24;x[e|5]=o>>>16&255;x[e|6]=o>>>8&255;x[e|7]=o&255;x[e|8]=a>>>24;x[e|9]=a>>>16&255;x[e|10]=a>>>8&255;x[e|11]=a&255;x[e|12]=i>>>24;x[e|13]=i>>>16&255;x[e|14]=i>>>8&255;x[e|15]=i&255;x[e|16]=s>>>24;x[e|17]=s>>>16&255;x[e|18]=s>>>8&255;x[e|19]=s&255;x[e|20]=c>>>24;x[e|21]=c>>>16&255;x[e|22]=c>>>8&255;x[e|23]=c&255;x[e|24]=u>>>24;x[e|25]=u>>>16&255;x[e|26]=u>>>8&255;x[e|27]=u&255;x[e|28]=l>>>24;x[e|29]=l>>>16&255;x[e|30]=l>>>8&255;x[e|31]=l&255}function k(){r=0x6a09e667;o=0xbb67ae85;a=0x3c6ef372;i=0xa54ff53a;s=0x510e527f;c=0x9b05688c;u=0x1f83d9ab;l=0x5be0cd19;f=d=0}function R(e,t,n,h,p,y,v,m,g,E){e=e|0;t=t|0;n=n|0;h=h|0;p=p|0;y=y|0;v=v|0;m=m|0;g=g|0;E=E|0;r=e;o=t;a=n;i=h;s=p;c=y;u=v;l=m;f=g;d=E}function M(e,t){e=e|0;t=t|0;var n=0;if(e&63)return-1;while((t|0)>=64){N(e);e=e+64|0;t=t-64|0;n=n+64|0}f=f+n|0;if(f>>>0>>0)d=d+1|0;return n|0}function F(e,t,n){e=e|0;t=t|0;n=n|0;var r=0,o=0;if(e&63)return-1;if(~n)if(n&31)return-1;if((t|0)>=64){r=M(e,t)|0;if((r|0)==-1)return-1;e=e+r|0;t=t-r|0}r=r+t|0;f=f+t|0;if(f>>>0>>0)d=d+1|0;x[e|t]=0x80;if((t|0)>=56){for(o=t+1|0;(o|0)<64;o=o+1|0)x[e|o]=0x00;N(e);t=0;x[e|0]=0}for(o=t+1|0;(o|0)<59;o=o+1|0)x[e|o]=0;x[e|56]=d>>>21&255;x[e|57]=d>>>13&255;x[e|58]=d>>>5&255;x[e|59]=d<<3&255|f>>>29;x[e|60]=f>>>21&255;x[e|61]=f>>>13&255;x[e|62]=f>>>5&255;x[e|63]=f<<3&255;N(e);if(~n)P(n);return r|0}function L(){r=h;o=p;a=y;i=v;s=m;c=g;u=E;l=b;f=64;d=0}function H(){r=A;o=_;a=w;i=O;s=D;c=S;u=T;l=C;f=64;d=0}function K(e,t,n,x,N,P,R,M,F,L,H,K,j,U,B,V){e=e|0;t=t|0;n=n|0;x=x|0;N=N|0;P=P|0;R=R|0;M=M|0;F=F|0;L=L|0;H=H|0;K=K|0;j=j|0;U=U|0;B=B|0;V=V|0;k();I(e^0x5c5c5c5c,t^0x5c5c5c5c,n^0x5c5c5c5c,x^0x5c5c5c5c,N^0x5c5c5c5c,P^0x5c5c5c5c,R^0x5c5c5c5c,M^0x5c5c5c5c,F^0x5c5c5c5c,L^0x5c5c5c5c,H^0x5c5c5c5c,K^0x5c5c5c5c,j^0x5c5c5c5c,U^0x5c5c5c5c,B^0x5c5c5c5c,V^0x5c5c5c5c);A=r;_=o;w=a;O=i;D=s;S=c;T=u;C=l;k();I(e^0x36363636,t^0x36363636,n^0x36363636,x^0x36363636,N^0x36363636,P^0x36363636,R^0x36363636,M^0x36363636,F^0x36363636,L^0x36363636,H^0x36363636,K^0x36363636,j^0x36363636,U^0x36363636,B^0x36363636,V^0x36363636);h=r;p=o;y=a;v=i;m=s;g=c;E=u;b=l;f=64;d=0}function j(e,t,n){e=e|0;t=t|0;n=n|0;var f=0,d=0,h=0,p=0,y=0,v=0,m=0,g=0,E=0;if(e&63)return-1;if(~n)if(n&31)return-1;E=F(e,t,-1)|0;f=r,d=o,h=a,p=i,y=s,v=c,m=u,g=l;H();I(f,d,h,p,y,v,m,g,0x80000000,0,0,0,0,0,0,768);if(~n)P(n);return E|0}function U(e,t,n,f,d){e=e|0;t=t|0;n=n|0;f=f|0;d=d|0;var h=0,p=0,y=0,v=0,m=0,g=0,E=0,b=0,A=0,_=0,w=0,O=0,D=0,S=0,T=0,C=0;if(e&63)return-1;if(~d)if(d&31)return-1;x[e+t|0]=n>>>24;x[e+t+1|0]=n>>>16&255;x[e+t+2|0]=n>>>8&255;x[e+t+3|0]=n&255;j(e,t+4|0,-1)|0;h=A=r,p=_=o,y=w=a,v=O=i,m=D=s,g=S=c,E=T=u,b=C=l;f=f-1|0;while((f|0)>0){L();I(A,_,w,O,D,S,T,C,0x80000000,0,0,0,0,0,0,768);A=r,_=o,w=a,O=i,D=s,S=c,T=u,C=l;H();I(A,_,w,O,D,S,T,C,0x80000000,0,0,0,0,0,0,768);A=r,_=o,w=a,O=i,D=s,S=c,T=u,C=l;h=h^r;p=p^o;y=y^a;v=v^i;m=m^s;g=g^c;E=E^u;b=b^l;f=f-1|0}r=h;o=p;a=y;i=v;s=m;c=g;u=E;l=b;if(~d)P(d);return 0}return{reset:k,init:R,process:M,finish:F,hmac_reset:L,hmac_init:K,hmac_finish:j,pbkdf2_generate_block:U}}},"transform/TextTransformer.js":function(e,t,n){var r=n("../Operation"),o=n("../Common"),a=function(e,t){o.PARANOIA&&(r.check(e),r.check(t));var n=function(e,t){if(e.offset>t.offset){if(e.offset>t.offset+t.toRemove)return r.create(e.offset-t.toRemove+t.toInsert.length,e.toRemove,e.toInsert);var n=e.toRemove-(t.offset+t.toRemove-e.offset);return n<0&&(n=0),0===n&&0===e.toInsert.length?null:r.create(t.offset+t.toInsert.length,n,e.toInsert)}if(e.offset+e.toRemove=0;i--)s=r.apply(t[i],s);var c=[];for(i=e.length-1;i>=0;i--){for(var u=e[i],l=t.length-1;l>=0;l--){try{u=a(u,t[l])}catch(e){return console.error("The pluggable transform function threw an error, failing operational transformation"),console.error(e.stack),[]}if(!u)break}u&&(o.PARANOIA&&r.check(u,s.length),c.unshift(u))}return c}},"transform/NaiveJSONTransformer.js":function(e,t,n){var r=n("./TextTransformer"),o=n("../Operation"),a=n("../Common");e.exports=function(e,t,n){var i,s,c,u=a.global.REALTIME_DEBUG=a.global.REALTIME_DEBUG||{};try{i=r(e,t,n),s=o.applyMulti(t,n),c=o.applyMulti(i,s);try{return JSON.parse(c),i}catch(r){console.error(r),u.ot_parseError={type:"resultParseError",resultOps:i,toTransform:e,transformBy:t,text1:n,text2:s,text3:c,error:r},console.log("Debugging info available at `window.REALTIME_DEBUG.ot_parseError`")}}catch(r){console.error(r),u.ot_applyError={type:"resultParseError",resultOps:i,toTransform:e,transformBy:t,text1:n,text2:s,text3:c,error:r},console.log("Debugging info available at `window.REALTIME_DEBUG.ot_applyError`")}return[]}},"transform/SmartJSONTransformer.js":function(e,t,n){var r,o,a,i=n("json.sortify"),s=n("../Diff"),c=n("../Operation"),u=n("./TextTransformer"),l=function(e){return null===e?"null":(t=e,"[object Array]"===Object.prototype.toString.call(t)?"array":typeof e);var t},f=function(e,t){for(var n=t.length,r=0;r1)return!0}))&&("splice"!==t.type||!e.some((function(e){if("splice"===e.type&&v(e.path,t.path)&&e.path.length-t.path.length<0){if(!e.removals)return;for(var n=e.offset,r=e.offset+e.removals;ne.offset+t.removals)return void(t.offset+=e.value.length-e.removals);if(t.offseti)){var d=t.slice(0,f);if((v=t.slice(f))===u){var p=Math.min(s,f);if((g=c.slice(0,p))===(b=d.slice(0,p)))return h(g,c.slice(p),d.slice(p),u)}}if(null===l||l===s){var y=s,v=(d=t.slice(0,y),t.slice(y));if(d===c){var m=Math.min(a-y,i-y);if((E=u.slice(u.length-m))===(A=v.slice(v.length-m)))return h(c,u.slice(0,u.length-m),v.slice(0,v.length-m),E)}}}if(r.length>0&&o&&0===o.length){var g=e.slice(0,r.index),E=e.slice(r.index+r.length);if(!(i<(p=g.length)+(m=E.length))){var b=t.slice(0,p),A=t.slice(i-m);if(g===b&&E===A)return h(g,e.slice(p,a-m),t.slice(p,i-m),E)}}return null}(e,t,n);if(l)return l}var f=i(e,t),d=e.substring(0,f);f=s(e=e.substring(f),t=t.substring(f));var p=e.substring(e.length-f),y=function(e,t){var n;if(!e)return[[1,t]];if(!t)return[[r,e]];var c=e.length>t.length?e:t,u=e.length>t.length?t:e,l=c.indexOf(u);if(-1!==l)return n=[[1,c.substring(0,l)],[0,u],[1,c.substring(l+u.length)]],e.length>t.length&&(n[0][0]=n[2][0]=r),n;if(1===u.length)return[[r,e],[1,t]];var f=function(e,t){var n=e.length>t.length?e:t,r=e.length>t.length?t:e;if(n.length<4||2*r.length=e.length?[r,o,a,c,f]:null}var a,c,u,l,f,d=o(n,r,Math.ceil(n.length/4)),h=o(n,r,Math.ceil(n.length/2));if(!d&&!h)return null;a=h?d&&d[4].length>h[4].length?d:h:d,e.length>t.length?(c=a[0],u=a[1],l=a[2],f=a[3]):(l=a[0],f=a[1],c=a[2],u=a[3]);var p=a[4];return[c,u,l,f,p]}(e,t);if(f){var d=f[0],h=f[1],p=f[2],y=f[3],v=f[4],m=o(d,p),g=o(h,y);return m.concat([[0,v]],g)}return function(e,t){for(var n=e.length,o=t.length,i=Math.ceil((n+o)/2),s=i,c=2*i,u=new Array(c),l=new Array(c),f=0;fn)y+=2;else if(A>o)p+=2;else if(h&&(O=s+d-E)>=0&&O=(w=n-l[O]))return a(e,t,S,A)}for(var _=-g+v;_<=g-m;_+=2){for(var w,O=s+_,D=(w=_===-g||_!==g&&l[O-1]n)m+=2;else if(D>o)v+=2;else if(!h){var S;if((b=s+d-_)>=0&&b=(w=n-w))return a(e,t,S,A)}}}return[[r,e],[1,t]]}(e,t)}(e=e.substring(0,e.length-f),t=t.substring(0,t.length-f));return d&&y.unshift([0,d]),p&&y.push([0,p]),c(y,u),y}function a(e,t,n,r){var a=e.substring(0,n),i=t.substring(0,r),s=e.substring(n),c=t.substring(r),u=o(a,i),l=o(s,c);return u.concat(l)}function i(e,t){if(!e||!t||e.charAt(0)!==t.charAt(0))return 0;for(var n=0,r=Math.min(e.length,t.length),o=r,a=0;n=0&&d(e[p][1])){var y=e[p][1].slice(-1);if(e[p][1]=e[p][1].slice(0,-1),l=y+l,h=y+h,!e[p][1]){e.splice(p,1),o--;var v=p-1;e[v]&&1===e[v][0]&&(u++,h=e[v][1]+h,v--),e[v]&&e[v][0]===r&&(a++,l=e[v][1]+l,v--),p=v}}f(e[o][1])&&(y=e[o][1].charAt(0),e[o][1]=e[o][1].slice(1),l+=y,h+=y)}if(o0||h.length>0){l.length>0&&h.length>0&&(0!==(n=i(h,l))&&(p>=0?e[p][1]+=h.substring(0,n):(e.splice(0,0,[0,h.substring(0,n)]),o++),h=h.substring(n),l=l.substring(n)),0!==(n=s(h,l))&&(e[o][1]=h.substring(h.length-n)+e[o][1],h=h.substring(0,h.length-n),l=l.substring(0,l.length-n)));var m=u+a;0===l.length&&0===h.length?(e.splice(o-m,m),o-=m):0===l.length?(e.splice(o-m,m,[1,h]),o=o-m+1):0===h.length?(e.splice(o-m,m,[r,l]),o=o-m+1):(e.splice(o-m,m,[r,l],[1,h]),o=o-m+2)}0!==o&&0===e[o-1][0]?(e[o-1][1]+=e[o][1],e.splice(o,1)):o++,u=0,a=0,l="",h=""}""===e[e.length-1][1]&&e.pop();var g=!1;for(o=1;o=55296&&e<=56319}function l(e){return e>=56320&&e<=57343}function f(e){return l(e.charCodeAt(0))}function d(e){return u(e.charCodeAt(e.length-1))}function h(e,t,n,o){return d(e)||f(o)?null:function(e){for(var t=[],n=0;n0&&t.push(e[n]);return t}([[0,e],[r,t],[1,n],[0,o]])}function p(e,t,n){return o(e,t,n,!0)}p.INSERT=1,p.DELETE=r,p.EQUAL=0,e.exports=p}},t=a("ChainPad.js"),r="ChainPad",e.exports=t,"undefined"!=typeof window?o=window:void 0!==n?o=n:"undefined"!=typeof self&&(o=self),o[r]=t}(x)),x.exports}var N,P=I(),k=t({__proto__:null,default:r(P)},[P]),R={exports:{}},M={},F={},L={};function H(){if(N)return L;N=1,Object.defineProperty(L,"__esModule",{value:!0}),L.toBig=L.shrSL=L.shrSH=L.rotrSL=L.rotrSH=L.rotrBL=L.rotrBH=L.rotr32L=L.rotr32H=L.rotlSL=L.rotlSH=L.rotlBL=L.rotlBH=L.add5L=L.add5H=L.add4L=L.add4H=L.add3L=L.add3H=void 0,L.add=m,L.fromBig=n,L.split=r;const e=BigInt(2**32-1),t=BigInt(32);function n(n,r=!1){return r?{h:Number(n&e),l:Number(n>>t&e)}:{h:0|Number(n>>t&e),l:0|Number(n&e)}}function r(e,t=!1){const r=e.length;let o=new Uint32Array(r),a=new Uint32Array(r);for(let i=0;iBigInt(e>>>0)<>>0);L.toBig=o;const a=(e,t,n)=>e>>>n;L.shrSH=a;const i=(e,t,n)=>e<<32-n|t>>>n;L.shrSL=i;const s=(e,t,n)=>e>>>n|t<<32-n;L.rotrSH=s;const c=(e,t,n)=>e<<32-n|t>>>n;L.rotrSL=c;const u=(e,t,n)=>e<<64-n|t>>>n-32;L.rotrBH=u;const l=(e,t,n)=>e>>>n-32|t<<64-n;L.rotrBL=l;const f=(e,t)=>t;L.rotr32H=f;const d=(e,t)=>e;L.rotr32L=d;const h=(e,t,n)=>e<>>32-n;L.rotlSH=h;const p=(e,t,n)=>t<>>32-n;L.rotlSL=p;const y=(e,t,n)=>t<>>64-n;L.rotlBH=y;const v=(e,t,n)=>e<>>64-n;function m(e,t,n,r){const o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:0|o}}L.rotlBL=v;const g=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0);L.add3L=g;const E=(e,t,n,r)=>t+n+r+(e/2**32|0)|0;L.add3H=E;const b=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0);L.add4L=b;const A=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0;L.add4H=A;const _=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0);L.add5L=_;const w=(e,t,n,r,o,a)=>t+n+r+o+a+(e/2**32|0)|0;L.add5H=w;const O={fromBig:n,split:r,toBig:o,shrSH:a,shrSL:i,rotrSH:s,rotrSL:c,rotrBH:u,rotrBL:l,rotr32H:f,rotr32L:d,rotlSH:h,rotlSL:p,rotlBH:y,rotlBL:v,add:m,add3L:g,add3H:E,add4L:b,add4H:A,add5H:w,add5L:_};return L.default=O,L}var K,j,U,B={},V={};function G(){return j||(j=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.wrapXOFConstructorWithOpts=e.wrapConstructorWithOpts=e.wrapConstructor=e.Hash=e.nextTick=e.swap32IfBE=e.byteSwapIfBE=e.swap8IfBE=e.isLE=void 0,e.isBytes=n,e.anumber=r,e.abytes=o,e.ahash=function(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");r(e.outputLen),r(e.blockLen)},e.aexists=function(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")},e.aoutput=function(e,t){o(e);const n=t.outputLen;if(e.length>>t},e.rotl=function(e,t){return e<>>32-t>>>0},e.byteSwap=a,e.byteSwap32=i,e.bytesToHex=function(e){if(o(e),s)return e.toHex();let t="";for(let n=0;n=0&&t0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function a(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function i(e){for(let t=0;te:e=>a(e),e.byteSwapIfBE=e.swap8IfBE,e.swap32IfBE=e.isLE?e=>e:i;const s=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),c=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));const u={_0:48,_9:57,A:65,F:70,a:97,f:102};function l(e){return e>=u._0&&e<=u._9?e-u._0:e>=u.A&&e<=u.F?e-(u.A-10):e>=u.a&&e<=u.f?e-(u.a-10):void 0}function f(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function d(e){return"string"==typeof e&&(e=f(e)),o(e),e}e.nextTick=async()=>{};function h(e){const t=t=>e().update(d(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function p(e){const t=(t,n)=>e(n).update(d(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t}function y(e){const t=(t,n)=>e(n).update(d(t)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=t=>e(t),t}e.Hash=class{},e.wrapConstructor=h,e.wrapConstructorWithOpts=p,e.wrapXOFConstructorWithOpts=y}(B)),B}function Y(){if(U)return F;U=1,Object.defineProperty(F,"__esModule",{value:!0}),F.shake256=F.shake128=F.keccak_512=F.keccak_384=F.keccak_256=F.keccak_224=F.sha3_512=F.sha3_384=F.sha3_256=F.sha3_224=F.Keccak=void 0,F.keccakP=v;const e=H(),t=G(),n=BigInt(0),r=BigInt(1),o=BigInt(2),a=BigInt(7),i=BigInt(256),s=BigInt(113),c=[],u=[],l=[];for(let e=0,t=r,f=1,d=0;e<24;e++){[f,d]=[d,(2*f+3*d)%5],c.push(2*(5*d+f)),u.push((e+1)*(e+2)/2%64);let h=n;for(let e=0;e<7;e++)t=(t<>a)*s)%i,t&o&&(h^=r<<(r<r>32?(0,e.rotlBH)(t,n,r):(0,e.rotlSH)(t,n,r),y=(t,n,r)=>r>32?(0,e.rotlBL)(t,n,r):(0,e.rotlSL)(t,n,r);function v(e,n=24){const r=new Uint32Array(10);for(let t=24-n;t<24;t++){for(let t=0;t<10;t++)r[t]=e[t]^e[t+10]^e[t+20]^e[t+30]^e[t+40];for(let t=0;t<10;t+=2){const n=(t+8)%10,o=(t+2)%10,a=r[o],i=r[o+1],s=p(a,i,1)^r[n],c=y(a,i,1)^r[n+1];for(let n=0;n<50;n+=10)e[t+n]^=s,e[t+n+1]^=c}let n=e[2],o=e[3];for(let t=0;t<24;t++){const r=u[t],a=p(n,o,r),i=y(n,o,r),s=c[t];n=e[s],o=e[s+1],e[s]=a,e[s+1]=i}for(let t=0;t<50;t+=10){for(let n=0;n<10;n++)r[n]=e[t+n];for(let n=0;n<10;n++)e[t+n]^=~r[(n+2)%10]&r[(n+4)%10]}e[0]^=d[t],e[1]^=h[t]}(0,t.clean)(r)}class m extends t.Hash{constructor(e,n,r,o=!1,a=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=o,this.rounds=a,(0,t.anumber)(r),!(0=r&&this.keccak();const a=Math.min(r-this.posOut,o-t);e.set(n.subarray(this.posOut,this.posOut+a),t),this.posOut+=a,t+=a}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,t.anumber)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,t.aoutput)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,(0,t.clean)(this.state)}_cloneInto(e){const{blockLen:t,suffix:n,outputLen:r,rounds:o,enableXOF:a}=this;return e||(e=new m(t,n,r,a,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=n,e.outputLen=r,e.enableXOF=a,e.destroyed=this.destroyed,e}}F.Keccak=m;const g=(e,n,r)=>(0,t.createHasher)((()=>new m(n,e,r)));F.sha3_224=g(6,144,28),F.sha3_256=g(6,136,32),F.sha3_384=g(6,104,48),F.sha3_512=g(6,72,64),F.keccak_224=g(1,144,28),F.keccak_256=g(1,136,32),F.keccak_384=g(1,104,48),F.keccak_512=g(1,72,64);const E=(e,n,r)=>(0,t.createXOFer)(((t={})=>new m(n,e,void 0===t.dkLen?r:t.dkLen,!0)));return F.shake128=E(31,168,16),F.shake256=E(31,136,32),F}var J,q,W,Q,z,X={},Z={},$={},ee={};function te(){if(J)return ee;J=1,Object.defineProperty(ee,"__esModule",{value:!0}),ee.SHA512_IV=ee.SHA384_IV=ee.SHA224_IV=ee.SHA256_IV=ee.HashMD=void 0,ee.setBigUint64=t,ee.Chi=function(e,t,n){return e&t^~e&n},ee.Maj=function(e,t,n){return e&t^e&n^t&n};const e=G();function t(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const o=BigInt(32),a=BigInt(4294967295),i=Number(n>>o&a),s=Number(n&a),c=r?4:0,u=r?0:4;e.setUint32(t+c,i,r),e.setUint32(t+u,s,r)}class n extends e.Hash{constructor(t,n,r,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=o,this.buffer=new Uint8Array(t),this.view=(0,e.createView)(this.buffer)}update(t){(0,e.aexists)(this),t=(0,e.toBytes)(t),(0,e.abytes)(t);const{view:n,buffer:r,blockLen:o}=this,a=t.length;for(let i=0;ia-s&&(this.process(o,0),s=0);for(let e=s;ef.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e>>3,i=(0,n.rotr)(r,17)^(0,n.rotr)(r,19)^r>>>10;o[e]=i+o[e-7]+a+o[e-16]|0}let{A:i,B:s,C:c,D:u,E:l,F:f,G:d,H:h}=this;for(let t=0;t<64;t++){const a=h+((0,n.rotr)(l,6)^(0,n.rotr)(l,11)^(0,n.rotr)(l,25))+(0,e.Chi)(l,f,d)+r[t]+o[t]|0,p=((0,n.rotr)(i,2)^(0,n.rotr)(i,13)^(0,n.rotr)(i,22))+(0,e.Maj)(i,s,c)|0;h=d,d=f,f=l,l=u+a|0,u=c,c=s,s=i,i=a+p|0}i=i+this.A|0,s=s+this.B|0,c=c+this.C|0,u=u+this.D|0,l=l+this.E|0,f=f+this.F|0,d=d+this.G|0,h=h+this.H|0,this.set(i,s,c,u,l,f,d,h)}roundClean(){(0,n.clean)(o)}destroy(){this.set(0,0,0,0,0,0,0,0),(0,n.clean)(this.buffer)}}$.SHA256=a;class i extends a{constructor(){super(28),this.A=0|e.SHA224_IV[0],this.B=0|e.SHA224_IV[1],this.C=0|e.SHA224_IV[2],this.D=0|e.SHA224_IV[3],this.E=0|e.SHA224_IV[4],this.F=0|e.SHA224_IV[5],this.G=0|e.SHA224_IV[6],this.H=0|e.SHA224_IV[7]}}$.SHA224=i;const s=(()=>t.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))))(),c=(()=>s[0])(),u=(()=>s[1])(),l=new Uint32Array(80),f=new Uint32Array(80);class d extends e.HashMD{constructor(t=64){super(128,t,16,!1),this.Ah=0|e.SHA512_IV[0],this.Al=0|e.SHA512_IV[1],this.Bh=0|e.SHA512_IV[2],this.Bl=0|e.SHA512_IV[3],this.Ch=0|e.SHA512_IV[4],this.Cl=0|e.SHA512_IV[5],this.Dh=0|e.SHA512_IV[6],this.Dl=0|e.SHA512_IV[7],this.Eh=0|e.SHA512_IV[8],this.El=0|e.SHA512_IV[9],this.Fh=0|e.SHA512_IV[10],this.Fl=0|e.SHA512_IV[11],this.Gh=0|e.SHA512_IV[12],this.Gl=0|e.SHA512_IV[13],this.Hh=0|e.SHA512_IV[14],this.Hl=0|e.SHA512_IV[15]}get(){const{Ah:e,Al:t,Bh:n,Bl:r,Ch:o,Cl:a,Dh:i,Dl:s,Eh:c,El:u,Fh:l,Fl:f,Gh:d,Gl:h,Hh:p,Hl:y}=this;return[e,t,n,r,o,a,i,s,c,u,l,f,d,h,p,y]}set(e,t,n,r,o,a,i,s,c,u,l,f,d,h,p,y){this.Ah=0|e,this.Al=0|t,this.Bh=0|n,this.Bl=0|r,this.Ch=0|o,this.Cl=0|a,this.Dh=0|i,this.Dl=0|s,this.Eh=0|c,this.El=0|u,this.Fh=0|l,this.Fl=0|f,this.Gh=0|d,this.Gl=0|h,this.Hh=0|p,this.Hl=0|y}process(e,n){for(let t=0;t<16;t++,n+=4)l[t]=e.getUint32(n),f[t]=e.getUint32(n+=4);for(let e=16;e<80;e++){const n=0|l[e-15],r=0|f[e-15],o=t.rotrSH(n,r,1)^t.rotrSH(n,r,8)^t.shrSH(n,r,7),a=t.rotrSL(n,r,1)^t.rotrSL(n,r,8)^t.shrSL(n,r,7),i=0|l[e-2],s=0|f[e-2],c=t.rotrSH(i,s,19)^t.rotrBH(i,s,61)^t.shrSH(i,s,6),u=t.rotrSL(i,s,19)^t.rotrBL(i,s,61)^t.shrSL(i,s,6),d=t.add4L(a,u,f[e-7],f[e-16]),h=t.add4H(d,o,c,l[e-7],l[e-16]);l[e]=0|h,f[e]=0|d}let{Ah:r,Al:o,Bh:a,Bl:i,Ch:s,Cl:d,Dh:h,Dl:p,Eh:y,El:v,Fh:m,Fl:g,Gh:E,Gl:b,Hh:A,Hl:_}=this;for(let e=0;e<80;e++){const n=t.rotrSH(y,v,14)^t.rotrSH(y,v,18)^t.rotrBH(y,v,41),w=t.rotrSL(y,v,14)^t.rotrSL(y,v,18)^t.rotrBL(y,v,41),O=y&m^~y&E,D=v&g^~v&b,S=t.add5L(_,w,D,u[e],f[e]),T=t.add5H(S,A,n,O,c[e],l[e]),C=0|S,x=t.rotrSH(r,o,28)^t.rotrBH(r,o,34)^t.rotrBH(r,o,39),I=t.rotrSL(r,o,28)^t.rotrBL(r,o,34)^t.rotrBL(r,o,39),N=r&a^r&s^a&s,P=o&i^o&d^i&d;A=0|E,_=0|b,E=0|m,b=0|g,m=0|y,g=0|v,({h:y,l:v}=t.add(0|h,0|p,0|T,0|C)),h=0|s,p=0|d,s=0|a,d=0|i,a=0|r,i=0|o;const k=t.add3L(C,I,P);r=t.add3H(k,T,x,N),o=0|k}({h:r,l:o}=t.add(0|this.Ah,0|this.Al,0|r,0|o)),({h:a,l:i}=t.add(0|this.Bh,0|this.Bl,0|a,0|i)),({h:s,l:d}=t.add(0|this.Ch,0|this.Cl,0|s,0|d)),({h,l:p}=t.add(0|this.Dh,0|this.Dl,0|h,0|p)),({h:y,l:v}=t.add(0|this.Eh,0|this.El,0|y,0|v)),({h:m,l:g}=t.add(0|this.Fh,0|this.Fl,0|m,0|g)),({h:E,l:b}=t.add(0|this.Gh,0|this.Gl,0|E,0|b)),({h:A,l:_}=t.add(0|this.Hh,0|this.Hl,0|A,0|_)),this.set(r,o,a,i,s,d,h,p,y,v,m,g,E,b,A,_)}roundClean(){(0,n.clean)(l,f)}destroy(){(0,n.clean)(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}$.SHA512=d;class h extends d{constructor(){super(48),this.Ah=0|e.SHA384_IV[0],this.Al=0|e.SHA384_IV[1],this.Bh=0|e.SHA384_IV[2],this.Bl=0|e.SHA384_IV[3],this.Ch=0|e.SHA384_IV[4],this.Cl=0|e.SHA384_IV[5],this.Dh=0|e.SHA384_IV[6],this.Dl=0|e.SHA384_IV[7],this.Eh=0|e.SHA384_IV[8],this.El=0|e.SHA384_IV[9],this.Fh=0|e.SHA384_IV[10],this.Fl=0|e.SHA384_IV[11],this.Gh=0|e.SHA384_IV[12],this.Gl=0|e.SHA384_IV[13],this.Hh=0|e.SHA384_IV[14],this.Hl=0|e.SHA384_IV[15]}}$.SHA384=h;const p=Uint32Array.from([2352822216,424955298,1944164710,2312950998,502970286,855612546,1738396948,1479516111,258812777,2077511080,2011393907,79989058,1067287976,1780299464,286451373,2446758561]),y=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class v extends d{constructor(){super(28),this.Ah=0|p[0],this.Al=0|p[1],this.Bh=0|p[2],this.Bl=0|p[3],this.Ch=0|p[4],this.Cl=0|p[5],this.Dh=0|p[6],this.Dl=0|p[7],this.Eh=0|p[8],this.El=0|p[9],this.Fh=0|p[10],this.Fl=0|p[11],this.Gh=0|p[12],this.Gl=0|p[13],this.Hh=0|p[14],this.Hl=0|p[15]}}$.SHA512_224=v;class m extends d{constructor(){super(32),this.Ah=0|y[0],this.Al=0|y[1],this.Bh=0|y[2],this.Bl=0|y[3],this.Ch=0|y[4],this.Cl=0|y[5],this.Dh=0|y[6],this.Dl=0|y[7],this.Eh=0|y[8],this.El=0|y[9],this.Fh=0|y[10],this.Fl=0|y[11],this.Gh=0|y[12],this.Gl=0|y[13],this.Hh=0|y[14],this.Hl=0|y[15]}}return $.SHA512_256=m,$.sha256=(0,n.createHasher)((()=>new a)),$.sha224=(0,n.createHasher)((()=>new i)),$.sha512=(0,n.createHasher)((()=>new d)),$.sha384=(0,n.createHasher)((()=>new h)),$.sha512_256=(0,n.createHasher)((()=>new m)),$.sha512_224=(0,n.createHasher)((()=>new v)),$}function re(){return W||(W=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.EMPTY=e.utf8ToBytes=e.concatBytes=e.randomBytes=e.ensureBytes=void 0,e.equalBytes=function(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r"number"==typeof e?e:e.bytesLen,r=t.reduce(((e,t)=>e+n(t)),0);return{bytesLen:r,encode:o=>{const a=new Uint8Array(r);for(let r=0,i=0;r{(0,e.ensureBytes)(o,r);const a=[];for(const e of t){const t=n(e),r=o.subarray(0,t);a.push("number"==typeof e?r:e.decode(r)),o=o.subarray(t)}return a}}},e.vecCoder=function(t,n){const r=n*t.bytesLen;return{bytesLen:r,encode:e=>{if(e.length!==n)throw new Error(`vecCoder.encode: wrong length=${e.length}. Expected: ${n}`);const o=new Uint8Array(r);for(let n=0,r=0;n{(0,e.ensureBytes)(n,r);const o=[];for(let e=0;e255)throw new Error("context should be less than 255 bytes");return(0,r.concatBytes)(new Uint8Array([0,n.length]),n,t)},e.getMessagePrehash=function(t,n,a=e.EMPTY){if((0,e.ensureBytes)(n),(0,e.ensureBytes)(a),a.length>255)throw new Error("context should be less than 255 bytes");if(!o[t])throw new Error("unknown hash: "+t);const{oid:i,hash:s}=o[t],c=s(n);return(0,r.concatBytes)(new Uint8Array([1,a.length]),a,i,c)};const t=ne(),n=Y(),r=G();Object.defineProperty(e,"concatBytes",{enumerable:!0,get:function(){return r.concatBytes}}),Object.defineProperty(e,"utf8ToBytes",{enumerable:!0,get:function(){return r.utf8ToBytes}}),e.ensureBytes=r.abytes,e.randomBytes=r.randomBytes,e.EMPTY=new Uint8Array(0);const o={"SHA2-256":{oid:(0,r.hexToBytes)("0609608648016503040201"),hash:t.sha256},"SHA2-384":{oid:(0,r.hexToBytes)("0609608648016503040202"),hash:t.sha384},"SHA2-512":{oid:(0,r.hexToBytes)("0609608648016503040203"),hash:t.sha512},"SHA2-224":{oid:(0,r.hexToBytes)("0609608648016503040204"),hash:t.sha224},"SHA2-512/224":{oid:(0,r.hexToBytes)("0609608648016503040205"),hash:t.sha512_224},"SHA2-512/256":{oid:(0,r.hexToBytes)("0609608648016503040206"),hash:t.sha512_256},"SHA3-224":{oid:(0,r.hexToBytes)("0609608648016503040207"),hash:n.sha3_224},"SHA3-256":{oid:(0,r.hexToBytes)("0609608648016503040208"),hash:n.sha3_256},"SHA3-384":{oid:(0,r.hexToBytes)("0609608648016503040209"),hash:n.sha3_384},"SHA3-512":{oid:(0,r.hexToBytes)("060960864801650304020A"),hash:n.sha3_512},"SHAKE-128":{oid:(0,r.hexToBytes)("060960864801650304020B"),hash:e=>(0,n.shake128)(e,{dkLen:32})},"SHAKE-256":{oid:(0,r.hexToBytes)("060960864801650304020C"),hash:e=>(0,n.shake256)(e,{dkLen:64})}}}(Z)),Z}function oe(){if(Q)return X;Q=1,Object.defineProperty(X,"__esModule",{value:!0}),X.XOF256=X.XOF128=X.genCrystals=void 0;const e=Y(),t=re();function n(e,t=8){const n=e.toString(2).padStart(8,"0").slice(-t).padStart(7,"0").split("").reverse().join("");return Number.parseInt(n,2)}X.genCrystals=e=>{const{newPoly:r,N:o,Q:a,F:i,ROOT_OF_UNITY:s,brvBits:c,isKyber:u}=e,l=(e,t=a)=>{const n=e%t|0;return 0|(n>=0?n:t+n)};const f=function(){const e=r(o);for(let t=0;t{for(let t=1,n=128;n>h;n>>=1)for(let r=0;r{for(let t=d-1,n=1+h;n{const n=0|l(e,t);return 0|(n>t>>1?n-t:n)},nttZetas:f,NTT:p,bitsCoder:(e,n)=>{const a=(0,t.getMask)(e),i=e*(o/8);return{bytesLen:i,encode:r=>{const o=new Uint8Array(i);for(let i=0,s=0,c=0,u=0;i=8;c-=8,s>>=8)o[u++]=s&(0,t.getMask)(c);return o},decode:t=>{const i=r(o);for(let r=0,o=0,s=0,c=0;r=e;s-=e,o>>=e)i[c++]=n.decode(o&a);return i}}}}};const r=e=>(t,n)=>{n||(n=e.blockLen);const r=new Uint8Array(t.length+2);r.set(t);const o=t.length,a=new Uint8Array(n);let i=e.create({}),s=0,c=0;return{stats:()=>({calls:s,xofs:c}),get:(t,n)=>(r[o+0]=t,r[o+1]=n,i.destroy(),i=e.create({}).update(r),s++,()=>(c++,i.xofInto(a))),clean:()=>{i.destroy(),a.fill(0),r.fill(0)}}};return X.XOF128=r(e.shake128),X.XOF256=r(e.shake256),X}function ae(){return z||(z=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ml_kem1024=e.ml_kem768=e.ml_kem512=e.PARAMS=void 0;const t=Y(),n=G(),r=oe(),o=re(),a=256,i=3329,{mod:s,nttZetas:c,NTT:u,bitsCoder:l}=(0,r.genCrystals)({N:a,Q:i,F:3303,ROOT_OF_UNITY:17,newPoly:e=>new Uint16Array(e),brvBits:7,isKyber:!0});e.PARAMS={512:{N:a,Q:i,K:2,ETA1:3,ETA2:2,du:10,dv:4,RBGstrength:128},768:{N:a,Q:i,K:3,ETA1:2,ETA2:2,du:10,dv:4,RBGstrength:192},1024:{N:a,Q:i,K:4,ETA1:2,ETA2:2,du:11,dv:5,RBGstrength:256}};const f=e=>l(e,(e=>{if(e>=12)return{encode:e=>e,decode:e=>e};const t=2**(e-1);return{encode:t=>((t<n*i+t>>>e}})(e));function d(e,t){for(let n=0;n>1)];1&i&&(u=-u);const{c0:l,c1:f}=(n=e[2*i+0],r=e[2*i+1],o=t[2*i+0],a=t[2*i+1],{c0:s(r*a*u+n*o),c1:s(n*a+r*o)});e[2*i+0]=l,e[2*i+1]=f}var n,r,o,a;return e}function p(e){const t=new Uint16Array(a);for(let n=0;n>4|r[e+2]<<4);o>=1,l+=1,l===o?(r=n,n=0):l===2*o&&(c[t++]=s(r-n),n=0,l=0)}if(l)throw new Error(`sampleCBD: leftover bits: ${l}`);return c}const v=e=>{const{K:t,PRF:n,XOF:r,HASH512:i,ETA1:c,ETA2:l,du:v,dv:m}=e,g=f(1),E=f(m),b=f(v),A=(0,o.splitCoder)((0,o.vecCoder)(f(12),t),32),_=(0,o.vecCoder)(f(12),t),w=(0,o.splitCoder)((0,o.vecCoder)(b,t),E),O=(0,o.splitCoder)(32,32);return{secretCoder:_,secretKeyLen:_.bytesLen,publicKeyLen:A.bytesLen,cipherTextLen:w.bytesLen,keygen:e=>{(0,o.ensureBytes)(e,32);const a=new Uint8Array(33);a.set(e),a[32]=t;const s=i(a),[l,f]=O.decode(s),v=[],m=[];for(let e=0;e{const[f,v]=A.decode(e),m=[];for(let e=0;e{const[r,i]=w.decode(e),c=_.decode(n),l=new Uint16Array(a);for(let e=0;e{(0,o.ensureBytes)(e,64);const{publicKey:r,secretKey:a}=t.keygen(e.subarray(0,32)),i=n(r),s=u.encode([a,r,i,e.subarray(32)]);return(0,o.cleanBytes)(a,i),{publicKey:r,secretKey:s}},encapsulate:(a,s=(0,o.randomBytes)(32))=>{(0,o.ensureBytes)(a,c),(0,o.ensureBytes)(s,32);const u=a.subarray(0,384*e.K),l=i.encode(i.decode(u.slice()));if(!(0,o.equalBytes)(l,u))throw(0,o.cleanBytes)(l),new Error("ML-KEM.encapsulate: wrong publicKey modulus");(0,o.cleanBytes)(l);const f=r.create().update(s).update(n(a)).digest(),d=t.encrypt(a,s,f.subarray(32,64));return f.subarray(32).fill(0),{cipherText:d,sharedSecret:f.subarray(0,32)}},decapsulate:(e,n)=>{(0,o.ensureBytes)(n,l),(0,o.ensureBytes)(e,s);const[i,c,f,d]=u.decode(n),h=t.decrypt(e,i),p=r.create().update(h).update(f).digest(),y=p.subarray(0,32),v=t.encrypt(c,h,p.subarray(32,64)),m=(0,o.equalBytes)(e,v),g=a.create({dkLen:32}).update(d).update(e).digest();return(0,o.cleanBytes)(h,v,m?g:y),m?y:g}}}const g={HASH256:t.sha3_256,HASH512:t.sha3_512,KDF:t.shake256,XOF:r.XOF128,PRF:function(e,n,r){return t.shake256.create({dkLen:e}).update(n).update(new Uint8Array([r])).digest()}};e.ml_kem512=m({...g,...e.PARAMS[512]}),e.ml_kem768=m({...g,...e.PARAMS[768]}),e.ml_kem1024=m({...g,...e.PARAMS[1024]})}(M)),M}var ie,se,ce,ue={};function le(){return ie||(ie=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ml_dsa87=e.ml_dsa65=e.ml_dsa44=e.PARAMS=void 0;const t=Y(),n=oe(),r=re(),o=256,a=8380417,i=13,s=0|Math.floor(95232),c=0|Math.floor(261888);e.PARAMS={2:{K:4,L:4,D:i,GAMMA1:2**17,GAMMA2:s,TAU:39,ETA:2,OMEGA:80},3:{K:6,L:5,D:i,GAMMA1:2**19,GAMMA2:c,TAU:49,ETA:4,OMEGA:55},5:{K:8,L:7,D:i,GAMMA1:2**19,GAMMA2:c,TAU:60,ETA:2,OMEGA:75}};const u=e=>new Int32Array(e),{mod:l,smod:f,NTT:d,bitsCoder:h}=(0,n.genCrystals)({N:o,Q:a,F:8347681,ROOT_OF_UNITY:1753,newPoly:u,isKyber:!1,brvBits:8}),p=e=>e,y=(e,t=p,n=p)=>h(e,{encode:e=>t(n(e)),decode:e=>n(t(e))}),v=(e,t)=>{for(let n=0;n{for(let n=0;n{for(let t=0;t{for(let n=0;n=t)return!0;return!1},b=(e,t)=>{const n=u(o);for(let r=0;r{const t=l(e),n=0|f(t,2*p);if(t-n==a-1)return{r1:0,r0:n-1|0};return{r1:0|Math.floor((t-n)/(2*p)),r0:n}},P=e=>N(e).r1,k=e=>N(e).r0,R=(e,t)=>{const n=Math.floor((a-1)/(2*p)),{r1:r,r0:o}=N(t);return 1===e?o>0?0|l(r+1,n):0|l(r-1,n):0|r},M=e=>{const t=l(e),n=0|f(t,8192);return{r1:0|Math.floor((t-n)/8192),r0:n}},F={bytesLen:O+n,encode:e=>{if(!1===e)throw new Error("hint.encode: hint is false");const t=new Uint8Array(O+n);for(let r=0,a=0;r{const t=[];let r=0;for(let a=0;aO)return!1;for(let t=r;tr&&e[t]<=e[t-1])return!1;n[e[t]]=1}r=e[O+a],t.push(n)}for(let t=r;tw-e),(e=>{if(!(-w<=e&&e<=w))throw new Error(`malformed key s1/s3 ${e} outside of ETA range [${-w}, ${w}]`);return e})),H=y(13,(e=>4096-e)),K=y(10),j=y(h===1<<17?18:20,(e=>f(h-e))),U=y(p===s?6:4),B=(0,r.vecCoder)(U,n),V=(0,r.splitCoder)(32,(0,r.vecCoder)(K,n)),G=(0,r.splitCoder)(32,32,S,(0,r.vecCoder)(L,i),(0,r.vecCoder)(L,n),(0,r.vecCoder)(H,n)),Y=(0,r.splitCoder)(T,(0,r.vecCoder)(j,i),F),J=2===w?e=>e<15&&2-e%5:e=>e<9&&4-e;function q(e){const t=u(o);for(let n=0;n>4&15);!1!==a&&(t[n++]=a),n{const n=u(o),r=t.shake256.create({}).update(e),a=new Uint8Array(t.shake256.blockLen);r.xofInto(a);const i=a.slice(0,8);for(let e=o-_,s=8,c=0,u=0;ee;)o=a[s++],s>u++&1)<<1),u>=8&&(c++,u=0)}return n},Q=e=>{const t=u(o),n=u(o);for(let r=0;r{for(let n=0;n{const n=u(o);let r=0;for(let c=0;ca-p||i===a-p&&0===s?0:1);n[c]=o,r+=o}var i,s;return{v:n,cnt:r}},Z=(0,r.splitCoder)(32,64,32),$={signRandBytes:32,keygen:e=>{const a=new Uint8Array(34),s=void 0===e;s&&(e=(0,r.randomBytes)(32)),(0,r.ensureBytes)(e,32),a.set(e),s&&e.fill(0),a[32]=n,a[33]=i;const[c,l,f]=Z.decode((0,t.shake256)(a,{dkLen:Z.bytesLen})),h=x(l),p=[];for(let e=0;e>8&255)));const y=[];for(let e=i;e>8&255)));const m=p.map((e=>d.encode(e.slice()))),g=[],E=[],_=C(c),w=u(o);for(let e=0;e{const[l,f,y,g,_,w]=G.decode(e),S=[],N=C(l);for(let e=0;e>8)()));const s=a.map((e=>d.encode(e.slice()))),c=[];for(let e=0;ee.map(P))),f=t.shake256.create({dkLen:T}).update(R).update(B.encode(l)).digest(),y=d.encode(W(f)),A=g.map((e=>b(e,y)));for(let e=0;eO)continue;L.clean();const x=Y.encode([f,A,C]);return(0,r.cleanBytes)(f,A,C,y,l,c,s,a,F,R,g,_,w,...S),x}throw new Error("Unreachable code path reached, report this error")},verify:(e,a,s,c=!1)=>{const[l,f]=V.decode(e),p=(0,t.shake256)(e,{dkLen:S});if(s.length!==Y.bytesLen)return!1;const[y,_,w]=Y.decode(s);if(!1===w)return!1;for(let e=0;ee.slice()));for(let e=0;ee+t),0)<=O))return!1}for(const e of _)if(E(e,h-I))return!1;return(0,r.equalBytes)(y,M)}};return{internal:$,keygen:$.keygen,signRandBytes:$.signRandBytes,sign:(e,t,n=r.EMPTY,o)=>{const a=(0,r.getMessage)(t,n),i=$.sign(e,a,o);return a.fill(0),i},verify:(e,t,n,o=r.EMPTY)=>$.verify(e,(0,r.getMessage)(t,o),n),prehash:e=>({sign:(t,n,o=r.EMPTY,a)=>{const i=(0,r.getMessagePrehash)(e,n,o),s=$.sign(t,i,a);return i.fill(0),s},verify:(t,n,o,a=r.EMPTY)=>$.verify(t,(0,r.getMessagePrehash)(e,n,a),o)})}}e.ml_dsa44=_({...e.PARAMS[2],CRH_BYTES:64,TR_BYTES:64,C_TILDE_BYTES:32,XOF128:n.XOF128,XOF256:n.XOF256}),e.ml_dsa65=_({...e.PARAMS[3],CRH_BYTES:64,TR_BYTES:64,C_TILDE_BYTES:48,XOF128:n.XOF128,XOF256:n.XOF256}),e.ml_dsa87=_({...e.PARAMS[5],CRH_BYTES:64,TR_BYTES:64,C_TILDE_BYTES:64,XOF128:n.XOF128,XOF256:n.XOF256})}(ue)),ue}var fe,de,he={exports:{}};function pe(){return fe||(fe=1,function(e){e.exports=function(e,t,n,r,o,a,i,s){function c(e){var t=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],n=1779033703,r=3144134277,o=1013904242,a=2773480762,i=1359893119,s=2600822924,c=528734635,u=1541459225,l=new Array(64);function f(e){for(var f=0,d=e.length;d>=64;){var h,p,y,v,m,g=n,E=r,b=o,A=a,_=i,w=s,O=c,D=u;for(p=0;p<16;p++)y=f+4*p,l[p]=(255&e[y])<<24|(255&e[y+1])<<16|(255&e[y+2])<<8|255&e[y+3];for(p=16;p<64;p++)v=((h=l[p-2])>>>17|h<<15)^(h>>>19|h<<13)^h>>>10,m=((h=l[p-15])>>>7|h<<25)^(h>>>18|h<<14)^h>>>3,l[p]=(v+l[p-7]|0)+(m+l[p-16]|0)|0;for(p=0;p<64;p++)v=(((_>>>6|_<<26)^(_>>>11|_<<21)^(_>>>25|_<<7))+(_&w^~_&O)|0)+(D+(t[p]+l[p]|0)|0)|0,m=((g>>>2|g<<30)^(g>>>13|g<<19)^(g>>>22|g<<10))+(g&E^g&b^E&b)|0,D=O,O=w,w=_,_=A+v|0,A=b,b=E,E=g,g=v+m|0;n=n+g|0,r=r+E|0,o=o+b|0,a=a+A|0,i=i+_|0,s=s+w|0,c=c+O|0,u=u+D|0,f+=64,d-=64}}f(e);var d,h=e.length%64,p=e.length/536870912|0,y=e.length<<3,v=h<56?56:120,m=e.slice(e.length-h,e.length);for(m.push(128),d=h+1;d>>24&255),m.push(p>>>16&255),m.push(p>>>8&255),m.push(p>>>0&255),m.push(y>>>24&255),m.push(y>>>16&255),m.push(y>>>8&255),m.push(y>>>0&255),f(m),[n>>>24&255,n>>>16&255,n>>>8&255,n>>>0&255,r>>>24&255,r>>>16&255,r>>>8&255,r>>>0&255,o>>>24&255,o>>>16&255,o>>>8&255,o>>>0&255,a>>>24&255,a>>>16&255,a>>>8&255,a>>>0&255,i>>>24&255,i>>>16&255,i>>>8&255,i>>>0&255,s>>>24&255,s>>>16&255,s>>>8&255,s>>>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 u(e,t,n){e=e.length<=64?e:c(e);var r,o=64+t.length+4,a=new Array(o),i=new Array(64),s=[];for(r=0;r<64;r++)a[r]=54;for(r=0;r=o-4;e--){if(a[e]++,a[e]<=255)return;a[e]=0}}for(;n>=32;)u(),s=s.concat(c(i.concat(c(a)))),n-=32;return n>0&&(u(),s=s.concat(c(i.concat(c(a))).slice(0,n))),s}function l(e,t,n,r){var o,a,i=e[0]^t[n++],s=e[1]^t[n++],c=e[2]^t[n++],u=e[3]^t[n++],l=e[4]^t[n++],f=e[5]^t[n++],d=e[6]^t[n++],h=e[7]^t[n++],p=e[8]^t[n++],y=e[9]^t[n++],v=e[10]^t[n++],m=e[11]^t[n++],g=e[12]^t[n++],E=e[13]^t[n++],b=e[14]^t[n++],A=e[15]^t[n++],_=i,w=s,O=c,D=u,S=l,T=f,C=d,x=h,I=p,N=y,P=v,k=m,R=g,M=E,F=b,L=A;for(a=0;a<8;a+=2)_^=(o=(R^=(o=(I^=(o=(S^=(o=_+R)<<7|o>>>25)+_)<<9|o>>>23)+S)<<13|o>>>19)+I)<<18|o>>>14,T^=(o=(w^=(o=(M^=(o=(N^=(o=T+w)<<7|o>>>25)+T)<<9|o>>>23)+N)<<13|o>>>19)+M)<<18|o>>>14,P^=(o=(C^=(o=(O^=(o=(F^=(o=P+C)<<7|o>>>25)+P)<<9|o>>>23)+F)<<13|o>>>19)+O)<<18|o>>>14,L^=(o=(k^=(o=(x^=(o=(D^=(o=L+k)<<7|o>>>25)+L)<<9|o>>>23)+D)<<13|o>>>19)+x)<<18|o>>>14,_^=(o=(D^=(o=(O^=(o=(w^=(o=_+D)<<7|o>>>25)+_)<<9|o>>>23)+w)<<13|o>>>19)+O)<<18|o>>>14,T^=(o=(S^=(o=(x^=(o=(C^=(o=T+S)<<7|o>>>25)+T)<<9|o>>>23)+C)<<13|o>>>19)+x)<<18|o>>>14,P^=(o=(N^=(o=(I^=(o=(k^=(o=P+N)<<7|o>>>25)+P)<<9|o>>>23)+k)<<13|o>>>19)+I)<<18|o>>>14,L^=(o=(F^=(o=(M^=(o=(R^=(o=L+F)<<7|o>>>25)+L)<<9|o>>>23)+R)<<13|o>>>19)+M)<<18|o>>>14;t[r++]=e[0]=_+i|0,t[r++]=e[1]=w+s|0,t[r++]=e[2]=O+c|0,t[r++]=e[3]=D+u|0,t[r++]=e[4]=S+l|0,t[r++]=e[5]=T+f|0,t[r++]=e[6]=C+d|0,t[r++]=e[7]=x+h|0,t[r++]=e[8]=I+p|0,t[r++]=e[9]=N+y|0,t[r++]=e[10]=P+v|0,t[r++]=e[11]=k+m|0,t[r++]=e[12]=R+g|0,t[r++]=e[13]=M+E|0,t[r++]=e[14]=F+b|0,t[r++]=e[15]=L+A|0}function f(e,t,n,r,o){for(;o--;)e[t++]=n[r++]}function d(e,t,n,r,o){for(;o--;)e[t++]^=n[r++]}function h(e,t,n,r,o){f(e,0,t,n+16*(2*o-1),16);for(var a=0;a<2*o;a+=2)l(e,t,n+16*a,r+8*a),l(e,t,n+16*a+16,r+8*a+16*o)}function p(e,t,n){return e[t+16*(2*n-1)]}function y(e){for(var t=[],n=0;n127&&r<2048?(t.push(r>>6|192),t.push(63&r|128)):(t.push(r>>12|224),t.push(r>>6&63|128),t.push(63&r|128))}return t}if(n<1||n>31)throw new Error("scrypt: logN not be between 1 and 31");var v,m,g,E,b=1<>>0;if(1*r>=1<<30||r>16777216||r>8388608||b>16777216/r)throw new Error("scrypt: parameters are too large");"string"==typeof e&&(e=y(e)),"string"==typeof t&&(t=y(t)),"undefined"!=typeof Int32Array?(v=new Int32Array(64*r),m=new Int32Array(32*b*r),E=new Int32Array(16)):(v=[],m=[],E=new Array(16)),g=u(e,t,128*r);var A=32*r;function _(){for(var e=0;e<32*r;e++){var t=4*e;v[0+e]=(255&g[t+3])<<24|(255&g[t+2])<<16|(255&g[t+1])<<8|255&g[t+0]}}function w(e,t){for(var n=e;n>>0&255,g[4*e+1]=t>>>8&255,g[4*e+2]=t>>>16&255,g[4*e+3]=t>>>24&255}}var S="undefined"!=typeof setImmediate?setImmediate:setTimeout;function T(e,t,n,r,o){!function a(){S((function(){r(e,e+n>>18&63]),o.push(n[t>>>12&63]),o.push(n[t>>>6&63]),o.push(n[t>>>0&63]);return r%3>0&&(o[o.length-1]="=",r%3==1&&(o[o.length-2]="=")),o.join("")}(n):"hex"===t?function(e){for(var t="0123456789abcdef".split(""),n=e.length,r=[],o=0;o>>4&15]),r.push(t[e[o]>>>0&15]);return r.join("")}(n):n}"function"==typeof a&&(s=i,i=a,a=1e3),a<=0?(_(),w(0,b),O(0,b),D(),i(C(s))):(_(),T(0,b,2*a,w,(function(){T(0,b,2*a,O,(function(){D(),i(C(s))}))})))}}(he)),he.exports}function ye(){return de||(de=1,function(e){var t;t=function(e,t,n,r){var o={Nacl:e,PQC:n},a=t.encodeBase64,i=e=>{let n;return(n=e.length%4)&&(e+="=".repeat(4-n)),t.decodeBase64(e)},s=t.decodeUTF8,c=t.encodeUTF8,u=function(e){for(var t="",n=0;n=p&&d&&h;if(a||"string"!=typeof r)s=u.subarray(l?p:64);else if(l)try{var y=u.subarray(0,64),v=u.subarray(64,p),m=u.subarray(p);if(!o.CryptoAgility.dsaVerify(d,m,v))return null;s=e.sign.open(f([y,m]),i(r))}catch(e){return null}else s=e.sign.open(u,i(r));return s?S(c(s),n):null},r}return n=T(t).cryptKey,{encrypt:function(e){return D(e,n)},decrypt:function(e){return S(e,n)}}},o.createEditCryptor=function(t,n){try{if(!t){if(n&&18!==n.length)throw new Error("expected supplied seed to have length of 18");n||(n=e.randomBytes(18)),t=a(n)}var r=e.hash(i(t)),o=e.sign.keyPair.fromSeed(r.subarray(0,32)),s=r.subarray(32,64),c={editKeyStr:t,signKey:a(o.secretKey),validateKey:a(o.publicKey),cryptKey:s,viewKeyStr:x(s)},u=h(r,"createEditCryptor");c=y(c,u);var l=p(o.secretKey,"createEditCryptor");return c=v(c,l)}catch(e){throw console.error("[chainpad-crypto.createEditCryptor] invalid string supplied"),e}},o.createViewCryptor=function(e){try{if(!e)throw new Error("Cannot open a new pad in read-only mode!");var t=i(e),n={cryptKey:t,viewKeyStr:e},r=h(t,"createViewCryptor");return n=y(n,r)}catch(e){throw console.error("[chainpad-crypto.createViewCryptor] invalid string supplied"),e}};var N=o.createViewCryptor2=function(t,n){try{if(!t)throw new Error("Cannot open a new pad in read-only mode!");var r=I(t),o=r;if(n){var i=s(n);(o=new Uint8Array(r.length+i.length)).set(i),o.set(r,i.length)}var c=e.hash(o),u=c.subarray(0,16),l=c.subarray(16,48),d=e.sign.keyPair.fromSeed(c.subarray(32,64)),m={viewKeyStr:t,cryptKey:l,chanId:x(u),secondarySignKey:a(d.secretKey),secondaryValidateKey:a(d.publicKey)},g=h(f([c,o]),"createViewCryptor2");m=y(m,g);var E=p(f([c.subarray(32,64),o]),"createViewCryptor2");return m=v(m,E)}catch(e){throw console.error("[chainpad-crypto.createViewCryptor2] invalid string supplied"),e}};o.createEditCryptor2=function(t,n,r){try{if(!t){if(n&&18!==n.length)throw new Error("expected supplied seed to have length of 18");n||(n=e.randomBytes(18)),t=x(n)}n||(n=I(t));var o=n;if(r){var i=s(r);(o=new Uint8Array(n.length+i.length)).set(i),o.set(n,i.length)}var c=e.hash(o),u=e.sign.keyPair.fromSeed(c.subarray(0,32)),l=e.hash(u.secretKey).subarray(0,e.secretbox.keyLength),f=c.subarray(32,64),d=x(f),h=N(d,r),y={editKeyStr:t,viewKeyStr:d,signKey:a(u.secretKey),validateKey:a(u.publicKey),cryptKey:h.cryptKey,secondaryKey:a(l),chanId:h.chanId,secondarySignKey:h.secondarySignKey,secondaryValidateKey:h.secondaryValidateKey};h.kemPublic&&(y.kemPublic=h.kemPublic,y.kemPrivate=h.kemPrivate),h.secondaryDsaKey&&(y.secondaryDsaKey=h.secondaryDsaKey,y.secondaryDsaValidateKey=h.secondaryDsaValidateKey);var m=p(c.subarray(0,32),"createEditCryptor2");return y=v(y,m)}catch(e){throw console.error("[chainpad-crypto.createEditCryptor2] invalid string supplied"),e}},o.createFileCryptor2=function(t,n){try{var r;t||(r=e.randomBytes(18),t=x(r)),r||(r=I(t));var o=r;if(n){var a=s(n);(o=new Uint8Array(r.length+a.length)).set(a),o.set(r,a.length)}var i=e.hash(o),c=i.subarray(0,24),u={fileKeyStr:t,cryptKey:i.subarray(24,56),chanId:x(c)},l=h(f([i,o]),"createFileCryptor2");u=y(u,l);var d=p(f([i.subarray(56,64),o]),"createFileCryptor2");return u=v(u,d)}catch(e){throw console.error("[chainpad-crypto.createFileCryptor2] invalid string supplied"),e}};var P=o.Curve={};P.encrypt=function(t,n){var r=s(t),o=e.randomBytes(24),i=e.box.after(r,o,n);return a(o)+"|"+a(i)},P.decrypt=function(t,n){var r=t.split("|"),o=i(r[0]),a=i(r[1]),s=e.box.open.after(a,o,n);return s?c(s):null},P.signAndEncrypt=function(t,n,r,i){var c=P.encrypt(t,n),u=s(c);if(i&&o.PQC&&o.PQC.ml_dsa&&o.PQC.ml_dsa.ml_dsa44)try{var l=e.sign(u,r),d=E(i,u),h=f([l,d]);return a(h)}catch(e){console.warn("ML-DSA signing failed, using only NaCl:",e)}return a(e.sign(u,r))},P.openSigned=function(t,n,r,a){var s=i(t),u=2420;if(s.length>=2484&&a&&o.PQC&&o.PQC.ml_dsa&&o.PQC.ml_dsa.ml_dsa44)try{var l=d(s,0,64+s.length-64-u),f=d(s,s.length-u),h=d(s,64,s.length-u);return e.sign.open(l,r)&&b(a,h,f)?P.decrypt(c(h),n):null}catch(e){return console.error("PQC signature verification failed:",e),null}var p=s.subarray(64);return P.decrypt(c(p),n)},P.deriveKeys=function(t,n,r,c){try{const u=i(t),l=i(n),d=e.box.before(u,l);let h=d;if(r&&c&&o.PQC?.ml_kem?.ml_kem512)try{const t=i(r),n=i(c),o=e.hash(f([d,u,l.subarray(0,32),t,n.subarray(0,32)])),a=e.hash(o).subarray(0,32);h=f([d,a])}catch(e){console.warn("PQC key exchange failed, using classical-only:",e)}const y=s("CryptPad.signingKeyGenerationSalt"),v=e.hash(f([y,h])),m=e.sign.keyPair.fromSeed(v.subarray(0,32)),g=v.subarray(32,64),E={cryptKey:a(g),signKey:a(m.secretKey),validateKey:a(m.publicKey)};if(o.PQC?.ml_dsa?.ml_dsa44)try{const t=s("CryptPad.curve.pqcSalt"),n=e.hash(f([h,t])).subarray(0,32),r=p(n,"deriveKeys");r&&(E.dsaPrivate=a(r.secretKey),E.dsaPublic=a(r.publicKey))}catch(e){console.error("Failed to generate PQC signature keys:",e)}return E}catch(e){return console.error("Failed to derive keys:",e),null}},P.createEncryptor=function(e){if(!e||"object"!=typeof e)return console.error("invalid input for createEncryptor"),{encrypt:function(){throw new Error("Invalid encryptor: keys missing or malformed")},decrypt:function(){throw new Error("Invalid encryptor: keys missing or malformed")}};var t,n,r,o,a;try{t=i(e.cryptKey),n=i(e.signKey),r=i(e.validateKey),o=e.dsaPrivate?i(e.dsaPrivate):void 0,a=e.dsaPublic?i(e.dsaPublic):void 0}catch(e){return console.error("Failed to decode keys for createEncryptor:",e),{encrypt:function(){throw new Error("Invalid encryptor: failed to decode keys")},decrypt:function(){throw new Error("Invalid encryptor: failed to decode keys")}}}return{encrypt:function(e){return P.signAndEncrypt(e,t,n,o)},decrypt:function(e){return P.openSigned(e,t,r,a)}}};var k=o.Mailbox={},R=function(t,n){var r=e.randomBytes(e.box.nonceLength),a=e.box(t,r,n.their_public,n.my_private),i=f([r,n.my_public,a]);if(n.their_kem_public&&o.PQC&&o.PQC.ml_kem&&o.PQC.ml_kem.ml_kem512)try{const t=m(n.their_kem_public,"pqc_asymmetric_encrypt");if(!t||!t.sharedSecret||!t.cipherText)throw new Error("[PQC] Encapsulate failed: result is undefined or incomplete");var s=t.sharedSecret,c=t.cipherText;if(!s||32!==s.length)throw new Error("[PQC] Internal encapsulate failed to return sharedSecret");var u=e.box.before(n.their_public,n.my_private),d=l(u,s),h=e.randomBytes(e.secretbox.nonceLength),p=e.secretbox(i,h,d);i=f([new Uint8Array([1]),c,h,p])}catch(e){console.warn("[PQC] Encryption failed, falling back to traditional:",e),i=f([new Uint8Array([0]),i])}else i=f([new Uint8Array([0]),i]);var y=new Uint8Array(i);return y.content=y,y.author=n.my_public,y.author_kem=n.my_kem_public,y},M=function(t,n){var r=t[0],a=d(t,1);if(1===r&&n.my_kem_private&&o.PQC&&o.PQC.ml_kem&&o.PQC.ml_kem.ml_kem512)try{var i=d(a,0,768),s=d(a,768,768+e.secretbox.nonceLength),c=d(a,768+e.secretbox.nonceLength),u=g(i,n.my_kem_private,"pqc_asymmetric_decrypt"),f=e.box.before(n.their_public,n.my_private),h=l(f,u),p=e.secretbox.open(c,s,h);if(!p)throw new Error("Failed to decrypt PQC layer");a=p}catch(e){throw new Error("E_PQC_DECRYPTION_FAILURE")}var y=d(a,0,e.box.nonceLength),v=d(a,e.box.nonceLength,e.box.nonceLength+e.box.publicKeyLength),m=d(a,e.box.nonceLength+e.box.publicKeyLength),E=e.box.open(m,y,v,n.my_private);if(!E)throw new Error("E_DECRYPTION_FAILURE");var b=new Uint8Array(E);return b.content=b,b.author=v,b.author_kem=n.my_kem_public,b},F=function(t,n){var r=2420;if(t.length>=2484&&n.dsaPublic&&o.PQC&&o.PQC.ml_dsa&&o.PQC.ml_dsa.ml_dsa44)try{var a=d(t,0,64+t.length-64-r),i=d(t,t.length-r),s=d(t,64,t.length-r);return e.sign.open(a,n.validateKey)&&b(n.dsaPublic,s,i,"pqc_verify_signature")?s:null}catch(e){return console.error("PQC signature verification failed:",e),null}return e.sign.open(t,n.validateKey)},L=k.sealSecretLetter=function(t,n){var r=s(t),i=R(r,{their_public:n.their_public,their_kem_public:n.their_kem_public,my_private:n.my_private,my_public:n.my_public,my_kem_private:n.my_kem_private,my_kem_public:n.my_kem_public}),c=n.ephemeral_keypair||e.box.keyPair(),u=n.ephemeral_kem_keypair||h(),l=R(i,{their_public:n.their_public,their_kem_public:n.their_kem_public,my_private:c.secretKey,my_public:c.publicKey,my_kem_private:u.secretKey,my_kem_public:u.publicKey});return n.signingKey&&(l=function(t,n){var r=e.sign(t,n.signingKey);if(n.dsaPrivate&&o.PQC&&o.PQC.ml_dsa&&o.PQC.ml_dsa.ml_dsa44)try{var a=E(n.dsaPrivate,t,"pqc_sign_message");if(a)return f([r,a])}catch(e){console.warn("ML-DSA signing failed, using only NaCl:",e)}return r}(l,{signingKey:n.signingKey,dsaPrivate:n.dsaPrivate})),a(l)};k.openOwnSecretLetter=function(e,t){var n=i(e);if(t.validateKey&&!(n=F(n,{validateKey:t.validateKey,dsaPublic:t.dsaPublic})))throw new Error("E_SIGNATURE_VERIFICATION_FAILED");var r=M(n,{my_private:t.ephemeral_private,my_kem_private:t.ephemeral_kem_private,their_public:t.their_public}),o=M(r.content,{my_private:t.my_private,my_kem_private:t.my_kem_private,their_public:t.their_public});return{content:c(o.content),author:a(o.author)}};var H=k.openSecretLetter=function(e,t){var n=i(e);if(t.validateKey&&!(n=F(n,{validateKey:t.validateKey,dsaPublic:t.dsaPublic})))throw new Error("E_SIGNATURE_VERIFICATION_FAILED");var r=M(n,{my_private:t.my_private,my_kem_private:t.my_kem_private,their_public:t.their_public}),o=M(r.content,{my_private:t.my_private,my_kem_private:t.my_kem_private,their_public:t.their_public});return{content:c(o.content),author:a(o.author)}};k.createEncryptor=function(e){if(e&&"object"==typeof e){["curvePublic","curvePrivate"].forEach((function(t){if("string"!=typeof e[t])throw console.log(t),new Error("Expected key was not present")}));var t=i(e.curvePrivate),n=i(e.curvePublic),r=e.kemPrivate?i(e.kemPrivate):void 0,o=e.kemPublic?i(e.kemPublic):void 0,a=e.signingKey?i(e.signingKey):void 0,s=e.validateKey?i(e.validateKey):void 0,c=e.dsaPrivate?i(e.dsaPrivate):void 0,u=e.dsaPublic?i(e.dsaPublic):void 0;return{encrypt:function(s,u,l){var f=i(u),d=l?i(l):void 0;try{return L(s,{signingKey:a,dsaPrivate:c,ephemeral_keypair:e.ephemeral_keypair,ephemeral_kem_keypair:e.ephemeral_kem_keypair,their_public:f,their_kem_public:d,my_private:t,my_kem_private:r,my_public:n,my_kem_public:o})}catch(e){return console.error(e),null}},decrypt:function(e){try{return H(e,{validateKey:s,dsaPublic:u,my_private:t,my_kem_private:r})}catch(e){return console.error(e),null}}}}console.error("invalid Mailbox.createEncryptor keys")};var K=o.Team={},j=function(t,n){var r=s(t),i=R(r,{their_public:n.team_curve_public,their_kem_public:n.team_kem_public,my_private:n.my_curve_private,my_public:n.my_curve_public,my_kem_private:n.my_kem_private,my_kem_public:n.my_kem_public}),c=e.box.keyPair(),u=null;if(o.PQC&&o.PQC.ml_kem&&o.PQC.ml_kem.ml_kem512)try{u=h()}catch(e){console.error("[PQC] Failed to generate ephemeral KEM keypair:",e)}var l,d=R(i,{their_public:n.team_curve_public,their_kem_public:n.team_kem_public,my_private:c.secretKey,my_public:c.publicKey,my_kem_private:u?.secretKey,my_kem_public:u?.publicKey});if(u?.publicKey&&"object"==typeof d&&d.author instanceof Uint8Array&&(d={content:d.content,author:d.author,author_kem:u.publicKey}),n.team_dsa_private&&o.PQC&&o.PQC.ml_dsa&&o.PQC.ml_dsa.ml_dsa44)try{const t=(l=d)instanceof Uint8Array?l:l.u8_bundle||l.content||new Uint8Array(l),r=e.sign(t,n.team_ed_private),o=E(n.team_dsa_private,t);return a(f([r,o]))}catch(t){return console.error("[PQC] Failed to create hybrid team signature, falling back to classical:",t),a(e.sign(d,n.team_ed_private))}return a(e.sign(d,n.team_ed_private))},U={teamCurvePublic:"team_curve_public",teamCurvePrivate:"team_curve_private",teamKemPrivate:"team_kem_private",teamKemPublic:"team_kem_public",myCurvePublic:"my_curve_public",myCurvePrivate:"my_curve_private",myKemPublic:"my_kem_public",myKemPrivate:"my_kem_private",teamEdPublic:"team_ed_public",teamEdPrivate:"team_ed_private",teamDsaPublic:"team_dsa_public",teamDsaPrivate:"team_dsa_private"},B=function(t){var n=e.hash(t);return[d(n,0,32),d(n,32)]},V=function(t){var n=B(t),r=e.box.keyPair.fromSecretKey(n[0]),i=d(n[1],0,16),s=null;if(o.PQC&&o.PQC.ml_kem&&o.PQC.ml_kem.ml_kem512)try{var c=e.hash(f([n[0],t]));s=h(c)}catch(e){console.error("Failed to generate post-quantum KEM keys for team:",e),s=null}var l={channel:u(i),teamCurvePublic:a(r.publicKey),teamCurvePrivate:a(r.secretKey),viewKeyStr:o.b64RemoveSlashes(a(t))};return s&&(l.teamKemPublic=a(s.publicKey),l.teamKemPrivate=a(s.secretKey)),l};K.deriveGuestKeys=function(e){var t=performance?.now?.()||Date.now(),n=V(i(o.b64AddSlashes(e)));return J(t,"Team.deriveGuestKeys"),n},K.createSeed=function(){var t=performance?.now?.()||Date.now(),n=o.b64AddSlashes(a(e.randomBytes(18)));return J(t,"Team.createSeed"),n},K.deriveMemberKeys=function(t,n){var r,s,c=performance?.now?.()||Date.now();try{if((r=i(o.b64AddSlashes(t))).length<18)throw new Error("INVALID_SEED")}catch(e){throw e}if(s=n,!Boolean(s.curvePublic&&i(s.curvePublic).length===e.box.publicKeyLength&&s.curvePrivate&&i(s.curvePrivate).length===e.box.secretKeyLength&&(!s.kemPublic||800===i(s.kemPublic).length)&&(!s.kemPrivate||1632===i(s.kemPrivate).length)))throw new Error("INVALID_OWN_KEYS");var u=B(r),l=e.sign.keyPair.fromSeed(u[0]),d=null;if(o.PQC&&o.PQC.ml_dsa&&o.PQC.ml_dsa.ml_dsa44)try{var h=e.hash(f([u[0],r])).subarray(0,32);d=p(h)}catch(e){console.error("Failed to generate post-quantum DSA keys for team:",e),d=null}var y,v,m,g=V(u[1]),E=(y={myCurvePublic:n.curvePublic,myCurvePrivate:n.curvePrivate,teamEdPrivate:a(l.secretKey),teamEdPublic:a(l.publicKey),myKemPublic:n.kemPublic,myKemPrivate:n.kemPrivate,teamDsaPrivate:a(d?.secretKey),teamDsaPublic:a(d?.publicKey)},v=g,m=JSON.parse(JSON.stringify(y)),Object.keys(v).forEach((function(e){m[e]=v[e]})),m);return J(c,"Team.deriveMemberKeys"),E},K.createEncryptor=function(t){var n=performance?.now?.()||Date.now(),r={};Object.keys(U).forEach((function(e){if(t[e])try{r[U[e]]=i(t[e])}catch(t){throw console.log(e),new Error("INVALID_KEY_SUPPLIED")}}));var s,u={};if(s=r,Boolean(s.my_curve_private&&s.my_curve_private.length===e.box.secretKeyLength&&s.my_curve_public&&s.my_curve_public.length===e.box.publicKeyLength&&s.team_curve_public&&s.team_curve_public.length===e.box.publicKeyLength&&(!o.PQC||!o.PQC.ml_kem||!o.PQC.ml_kem.ml_kem512||s.my_kem_private&&1632===s.my_kem_private.length&&s.my_kem_public&&800===s.my_kem_public.length&&s.team_kem_public&&800===s.team_kem_public.length)&&s.team_ed_private&&s.team_ed_private.length===e.sign.secretKeyLength&&(!o.PQC||!o.PQC.ml_dsa||!o.PQC.ml_dsa.ml_dsa44||s.team_dsa_private&&2560===s.team_dsa_private.length))&&(u.encrypt=function(e){var t=performance?.now?.()||Date.now();try{var n=j(e,r);return J(t,"Team.createEncryptor.encrypt"),n}catch(e){return console.error(e),J(t,"Team.createEncryptor.encrypt"),null}}),function(t){return Boolean(t.team_curve_private&&t.team_curve_private.length===e.box.secretKeyLength&&(!o.PQC||!o.PQC.ml_kem||!o.PQC.ml_kem.ml_kem512||t.team_kem_private&&1632===t.team_kem_private.length)&&t.team_ed_public&&t.team_ed_public.length===e.sign.publicKeyLength)}(r)&&(u.decrypt=function(t,n){var s=performance?.now?.()||Date.now();try{var u=function(t,n,r){var s,u=i(t),l=2420,f=u.length>2484&&n.team_dsa_public&&o.PQC&&o.PQC.ml_dsa&&o.PQC.ml_dsa.ml_dsa44;if(!0===r)s=d(u,64);else if(f)try{var h=d(u,0,u.length-l);if(!(s=e.sign.open(h,n.team_ed_public)))throw new Error("Classical signature verification failed");var p=d(u,u.length-l);if(!b(n.team_dsa_public,s,p))throw new Error("Post-quantum signature verification failed")}catch(t){if(console.error("Hybrid signature verification failed:",t),null===(s=e.sign.open(u,n.team_ed_public)))throw new Error("E_VALIDATION_FAILURE")}else if(null===(s=e.sign.open(u,n.team_ed_public)))throw new Error("E_VALIDATION_FAILURE");var y=M(s,{my_private:n.team_curve_private,my_kem_private:n.team_kem_private,their_public:n.team_curve_public,sender_public:n.team_kem_public}),v=M(y.content,{my_private:n.team_curve_private,my_kem_private:n.team_kem_private,their_public:y.author,sender_public:y.author_kem});return{content:c(v.content),author:a(v.author)}}(t,r,n);return J(s,"Team.createEncryptor.decrypt"),u}catch(e){return console.error(e),J(s,"Team.createEncryptor.decrypt"),null}}),0===Object.keys(u).length)throw new Error("INVALID_TEAM_CONFIGURATION");return J(n,"Team.createEncryptor"),u};var G=[],Y=0;function J(e,t){const n=(performance?.now?.()||Date.now())-e;Y+=n,G.push({fnName:t,deltaMs:n});const r=(n/1e3).toFixed(4),o=(Y/1e3).toFixed(4);console.log(`[Team timing] ${t}: +${r}s, cumulative: ${o}s`),console.log("[Team timing] Operation times:",G)}return o},e.exports?e.exports=t(h(),w(),ce?se:(ce=1,se={ml_kem:ae(),ml_dsa:le(),utils:re()}),pe()):window.chainpad_crypto=t(window.nacl,window.PostQuantum,window.scrypt)}(R)),R.exports}var ve,me=ye(),ge={exports:{}};function Ee(){return ve||(ve=1,function(e){e.exports&&(e.exports=((e={})=>{var t={setCustomize:t=>{e=t.ApiConfig},getWebsocketURL:function(t){var n=e.websocketPath||"/cryptpad_websocket";if(/^ws{1,2}:\/\//.test(n))return n;var r=new URL(t||globalThis?.location?.href||e.httpUnsafeOrigin);return t&&(r.href=t),r.protocol.replace(/http/,"ws")+"//"+r.host+n}};return t})())}(ge)),ge.exports}var be,Ae=Ee(),_e=t({__proto__:null,default:r(Ae)},[Ae]),we={exports:{}};function Oe(){return be||(be=1,function(e){e.exports&&(e.exports=function(e={}){return{setCustomize:t=>{e=t.AppConfig},userHashKey:"User_hash",userNameKey:"User_name",blockHashKey:"Block_hash",fileHashKey:"FS_hash",sessionJWT:"Session_JWT",ssoSeed:"SSO_seed",displayNameKey:"cryptpad.username",oldStorageKey:"CryptPad_RECENTPADS",storageKey:"filesData",tokenKey:"loginToken",prefersDriveRedirectKey:"prefersDriveRedirect",isPremiumKey:"isPremiumUser",displayPadCreationScreen:"displayPadCreationScreen",deprecatedKey:"deprecated",MAX_TEAMS_SLOTS:e.maxTeamsSlots||5,MAX_TEAMS_OWNED:e.maxOwnedTeams||5,MAX_PREMIUM_TEAMS_SLOTS:Math.max(e.maxTeamsSlots||0,e.maxPremiumTeamsSlots||0)||5,MAX_PREMIUM_TEAMS_OWNED:Math.max(e.maxOwnedTeams||0,e.maxPremiumTeamsOwned||0)||5,criticalApps:["profile","settings","debug","admin","support","notifications","calendar","moderation","oldadmin"],earlyAccessApps:[]}}(void 0))}(we)),we.exports}var De,Se=Oe(),Te=t({__proto__:null,default:r(Se)},[Se]),Ce={exports:{}},xe={exports:{}},Ie=xe.exports;function Ne(){return De||(De=1,function(e){!function(t){const n=e=>{var n=t.CryptPad_Util={};t.atob=t.atob||function(e){return Buffer.from(e,"base64").toString("binary")},t.btoa=t.btoa||function(e){return Buffer.from(e,"binary").toString("base64")},n.encodeBase64=e.CryptoAgility.encodeBase64,n.decodeBase64=e.CryptoAgility.decodeBase64,n.encodeUTF8=e.CryptoAgility.encodeUTF8,n.decodeUTF8=e.CryptoAgility.decodeUTF8,n.slice=function(e,t,n){return Array.prototype.slice.call(e,t,n)},n.u8ToBase64=(e,t)=>{const n=new FileReader;n.onload=()=>{let e=n.result,r=e.slice(e.indexOf(",")+1);t(r)},n.readAsDataURL(new Blob([e]))},n.shuffleArray=function(e){for(var t=e.length-1;t>0;t--){var n=Math.floor(Math.random()*(t+1)),r=e[t];e[t]=e[n],e[n]=r}},n.bake=function(e,t){return void 0===t&&(t=[]),Array.isArray(t)||(t=[t]),function(){return e.apply(null,t)}},n.both=function(e,t){if("function"!=typeof e)throw new Error("INVALID_USAGE");return"function"!=typeof t&&(t=function(e){return e}),function(){return e.apply(null,arguments),t.apply(null,arguments)}},n.clone=function(e){return null==e?e:JSON.parse(JSON.stringify(e))},n.serializeError=function(e){if(!(e instanceof Error))return e;var t={};return Object.getOwnPropertyNames(e).forEach((function(n){t[n]=e[n]})),t},n.tryParse=function(e){try{return JSON.parse(e)}catch(e){return}},n.mkAsync=function(e,t){if("function"!=typeof e)throw new Error("EXPECTED_FUNCTION");return function(){var n=Array.prototype.slice.call(arguments);setTimeout((function(){e.apply(null,n)}),t)}},n.mkEvent=function(e){var t=[],n=!1;let r;return{reg:function(r){e&&n?setTimeout(r):t.push(r)},unreg:function(e){-1!==t.indexOf(e)?t.splice(t.indexOf(e),1):console.log("event handler was already unregistered")},fire:function(){if(!e||!n){var o=Array.prototype.slice.call(arguments);n||r.apply(null,o),n=!0,t.forEach((function(e){e.apply(null,o)}))}},promise:new Promise((e=>{r=e}))}},n.mkTimeout=function(e,t){t=t||0;var r=n.once(e),o=setTimeout((function(){r("TIMEOUT")}),t);return n.both(r,(function(){clearTimeout(o)}))},n.onClickEnter=function(e,t,n){e.on("click keydown",(function(e){var r="click"===e.type,o="keydown"===e.type&&13===e.which,a="keydown"===e.type&&32===e.which&&n&&n.space;(r||o||a)&&("keydown"===e.type&&e.preventDefault(),t(e))}))},n.response=function(e){var t={},n={};"function"!=typeof e&&(e=function(e){throw new Error(e)});var r=function(e){clearTimeout(n[e]),delete n[e],delete t[e]};return{clear:r,expected:function(e){return Boolean(t[e])},expectation:function(e){return t[e]},expect:function(o,a,i){"string"!=typeof o&&e("EXPECTED_STRING"),"function"!=typeof a&&e("EXPECTED_CALLBACK"),t[o]=a,"number"==typeof i&&i&&(n[o]=setTimeout((function(){"function"==typeof t[o]&&t[o]("TIMEOUT"),r(o)}),i))},handle:function(n,o){var a=t[n];if("function"==typeof a){try{a.apply(null,Array.isArray(o)?o:[o])}catch(t){e("HANDLER_ERROR",{error:t,id:n,args:o})}r(n)}else e("MISSING_CALLBACK",{id:n,args:o})},_pending:t}},n.inc=function(e,t,n){e[t]=(e[t]||0)+("number"==typeof n?n:1)},n.values=function(e){return Object.keys(e).map((function(t){return e[t]}))},n.find=function(e,t){for(var n=t.length,r=0;r&"']/g,(function(e){return{"<":"<",">":">","&":"&",'"':""","'":"'"}[e]})):""},n.hexToBase64=function(e){var n=e.replace(/\r|\n/g,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" "),r=String.fromCharCode.apply(null,n);return t.btoa(r).replace(/\//g,"-").replace(/=+$/,"")},n.base64ToHex=function(e){var n=[];return t.atob(e.replace(/-/g,"/")).split("").forEach((function(e){var t=e.charCodeAt(0).toString(16);1===t.length&&(t="0"+t),n.push(t)})),n.join("")},n.uint8ArrayToHex=function(e){for(var t="",n=0;n=o?"GB":e>=r?"MB":"KB"};n.getBlock=function(e,t,r){var o=n.once(n.mkAsync(r)),a={};"string"==typeof t.bearer&&t.bearer&&(a.authorization=`Bearer ${t.bearer}`),fetch(e,{method:"GET",credentials:"include",headers:a}).then((e=>{e.ok?o(void 0,e):401!==e.status&&404!==e.status?o(e.status,e):e.json().then((t=>{o(e.status,t)})).catch((()=>{o(e.status)}))})).catch((e=>{o(e)}))},n.fetchApi=function(e,t,n,r){const o=new URL(e);o.pathname=`api/${t}`;let a=o.href+(n?"?"+ +new Date:"");if("undefined"!=typeof self&&self.crypto)fetch(a).then((e=>{if(!e.ok)throw new Error(`Fetch error: ${e.status}`);return e.text()})).then((e=>{r(JSON.parse(e.slice(27,-5)))})).catch((e=>{console.error(e.message),r({})}));else if(void 0!==l){("http:"===o.protocol?require("node:http"):require("node:https")).get(o.href,(e=>{let t="";e.on("data",(e=>{t+=e})),e.on("end",(()=>{try{r(JSON.parse(t.slice(27,-5)))}catch(e){console.error(e),r({})}}))}))}},n.fetch=function(e,t,r,o){var a,i=n.once(n.mkAsync(t)),s=function(e){var t=e.replace(/(\/)*$/,""),n=t.lastIndexOf("/"),r=t.slice(n+1);return/^[a-f0-9]{48}$/.test(r)||(r=void 0),r}(e),c=function(){(a=new XMLHttpRequest).open("GET",e,!0),r&&a.addEventListener("progress",(function(e){if(e.lengthComputable){var t=e.loaded/e.total;r(t)}}),!1),a.responseType="arraybuffer",a.onerror=function(e){i(e)},a.onload=function(){if(/^4/.test(""+this.status))return i("XHR_ERROR");var e=a.response;if(e){var t=new Uint8Array(e);return s?void function(e,t,n){o&&"function"==typeof o.setBlobCache?o.setBlobCache(e,t,n):n("EINVAL")}(s,t,(function(){i(null,t)})):void i(void 0,t)}i("ENOENT")},a.send(null)};if(s)return function(e,t){o&&"function"==typeof o.getBlobCache?o.getBlobCache(e,t):t("EINVAL")}(s,(function(e,t){!e&&t?i(void 0,t):c()})),{cancel:function(){a&&a.abort&&a.abort()}};c()},n.dataURIToBlob=function(e){for(var t=atob(e.split(",")[1]),n=e.split(",")[0].split(":")[1].split(";")[0],r=new ArrayBuffer(t.length),o=new Uint8Array(r),a=0;aparseInt(e,10).toString(16).padStart(2,"0"))).join("")}`},n.isSmallScreen=function(){return t.innerHeight<800||t.innerWidth<800},n.stripTags=function(e){var t=document.createElement("div");return t.innerHTML=e,t.innerText},n.parseFilename=function(e){if(!e||!e.trim())return{};var t=/^(\.?.+?)(\.[^.]+)?$/.exec(e)||[];return{name:t[1],ext:t[2]}},n.isPlainTextFile=function(e,t){if(e&&0===e.indexOf("text/"))return!0;var r=n.parseFilename(t);return!(e||!t||r.ext)||("application/x-javascript"===e||"application/xml"===e)},n.isSpreadsheet=function(e,t){return e&&("application/vnd.oasis.opendocument.spreadsheet"===e||"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"===e)||t&&(t.endsWith(".xlsx")||t.endsWith(".ods"))},n.isOfficeDoc=function(e,t){return e&&("application/vnd.oasis.opendocument.text"===e||"application/vnd.openxmlformats-officedocument.wordprocessingml.document"===e)||t&&(t.endsWith(".docx")||t.endsWith(".odt"))},n.isPresentation=function(e,t){return e&&("application/vnd.oasis.opendocument.presentation"===e||"application/vnd.openxmlformats-officedocument.presentationml.presentation"===e)||t&&(t.endsWith(".pptx")||t.endsWith(".odp"))},n.isValidURL=function(e){return!!new RegExp("^(https?:\\/\\/)((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*(\\?[;&a-z\\d%_.~+=-]*)?").test(e)};var a=/([\uD800-\uDBFF][\uDC00-\uDFFF])/;n.getFirstCharacter=function(e){if(!e||!e.trim())return"?";var t=function(e){for(var t=e.split(a),n=[],r=0;r{let t=/ver=([0-9.]+)(-[0-9]*)?/.exec(e);return Array.isArray(t)&&t[1]||void 0},n.Saferphore={create:e=>{var t,n=[];return t=function(){if(e<0)throw new Error("(resourceCount < 0) should never happen");var r;0!==e&&0!==n.length&&(e--,n.shift()((r=0,function(n){if(r++)throw new Error("returnAfter() called multiple times");var o=0;return function(){if(o++)throw new Error("returnAfter wrapped callback called multiple times");n&&n.apply(null,arguments),e++,t()}})))},{take:function(e){n.push(e),t()}}}},n};e.exports&&(e.exports=n(ye()))}("undefined"!=typeof self?self:Ie)}(xe)),xe.exports}var Pe,ke,Re={exports:{}};function Me(){return Pe||(Pe=1,function(e){e.exports&&(e.exports=function(){var e={},t=function(e){return e.replace(/-/g,"/")};return e.parseUser=function(e){var n,r,o,a=function(e){if(/^\[.*?@.*\]$/.test(e)){var n,r=e.slice(1,-1);if(r=r.replace(/\/([a-zA-Z0-9+-]{43}=)$/,(function(e,r){return n=t(r),""})),n){var o=r.lastIndexOf("@");if(!(o<1))return{domain:r.slice(o+1),user:r.slice(0,o),pubkey:n}}}}(e);if(function(e){if(e&&e.domain&&e.user&&e.pubkey)return!0}(a))return a;if(e.replace(/^https*:\/\/([^\/]+)\/user\/#\/1\/([^\/]+)\/([a-zA-Z0-9+-]{43}=)$/,(function(e,a,i,s){return n=a,r=i,o=t(s),""})),!n)throw new Error("Could not parse user id ["+e+"]");return{domain:n,user:r,pubkey:o}},e.serialize=function(e,t,n){return"["+t+"@"+e.replace(/https*:\/\//,"")+"/"+n.replace(/\//g,"-")+"]"},e.canonicalize=function(n){if("string"==typeof n){if(44===n.length)return t(n);try{return e.parseUser(n).pubkey}catch(e){return}}},e}())}(Re)),Re.exports}function Fe(){return ke||(ke=1,function(e){!function(t){e.exports&&(e.exports=function(e,n,r){var o=t.CryptPad_Hash={},a=e.uint8ArrayToHex,i=e.hexToBase64,s=e.base64ToHex;o.encodeBase64=e.encodeBase64,o.decodeBase64=e.decodeBase64,o.hashChannelList=function(t){return e.encodeBase64(n.CryptoAgility.createHash(e.decodeUTF8(JSON.stringify(t))))},o.generateSignPair=function(){var e=n.CryptoAgility.signKeyPair(),t=function(e){return n.b64RemoveSlashes(e).replace(/=+$/g,"")},r={validateKey:o.encodeBase64(e.publicKey),signKey:o.encodeBase64(e.secretKey),safeValidateKey:t(o.encodeBase64(e.publicKey)),safeSignKey:t(o.encodeBase64(e.secretKey))};if(n.PQC&&n.PQC.ml_dsa&&n.PQC.ml_dsa.ml_dsa44)try{var a=n.Nacl.hash(e.secretKey).subarray(0,32),i=n.CryptoAgility.generateDsaKeypair(a);r.dsaPublic=o.encodeBase64(i.publicKey),r.dsaPrivate=o.encodeBase64(i.secretKey),r.safeDsaPublic=t(o.encodeBase64(i.publicKey)),r.safeDsaPrivate=t(o.encodeBase64(i.secretKey))}catch(e){console.error("Failed to generate post-quantum DSA keys:",e)}return r},o.getSignPublicFromPrivate=function(t){var r=n.b64AddSlashes(t),o=e.decodeBase64(r),a=n.CryptoAgility.signKeyPairFromSecretKey(o);return e.encodeBase64(a.publicKey)},o.getCurvePublicFromPrivate=function(t){var r=n.b64AddSlashes(t),o=e.decodeBase64(r),a=n.CryptoAgility.boxKeyPairFromSecretKey(o);return e.encodeBase64(a.publicKey)};var c=o.getEditHashFromKeys=function(e){var t=e.version,r=e.keys;if(0===t)return e.channel+e.key;if(1===t){if(!r.editKeyStr)return;return"/1/edit/"+i(e.channel)+"/"+n.b64RemoveSlashes(r.editKeyStr)+"/"}if(2===t){if(!r.editKeyStr)return;var o=e.password?"p/":"";return"/2/"+e.type+"/edit/"+n.b64RemoveSlashes(r.editKeyStr)+"/"+o}},u=o.getViewHashFromKeys=function(e){var t=e.version,r=e.keys;if(0!==t){if(1===t){if(!r.viewKeyStr)return;return"/1/view/"+i(e.channel)+"/"+n.b64RemoveSlashes(r.viewKeyStr)+"/"}if(2===t){if(!r.viewKeyStr)return;var o=e.password?"p/":"";return"/2/"+e.type+"/view/"+n.b64RemoveSlashes(r.viewKeyStr)+"/"+o}}};o.getHiddenHashFromKeys=function(e,t,n){n=n||{};var r=t.keys&&t.keys.editKeyStr||t.key,a=!n.view&&r?"edit/":"view/",i=t.password?"p/":"";t.keys&&t.keys.fileKeyStr&&(a="");var s="/3/"+e+"/"+a+t.channel+"/"+i,c=o.parseTypeHash(e,s);return c&&c.getHash?c.getHash(n||{}):s};var l=o.getFileHashFromKeys=function(e){var t=e.version,r=e.keys;if(0!==t){if(1===t)return"/1/"+i(e.channel)+"/"+n.b64RemoveSlashes(r.fileKeyStr)+"/";if(2===t){if(!r.fileKeyStr)return;var o=e.password?"p/":"";return"/2/"+e.type+"/"+n.b64RemoveSlashes(r.fileKeyStr)+"/"+o}}};o.getPublicSigningKeyString=r.serialize,o.ephemeralChannelLength=34,o.createChannelId=function(e){var t=a(n.CryptoAgility.bytes(e?17:16));if(-1===[32,34].indexOf(t.length)||/[^a-f0-9]/.test(t))throw new Error("channel ids must consist of 32 hex characters");return t},o.getChannelIdFromKey=function(e){if(e)return a(o.decodeBase64(e).subarray(0,16))},o.getBoxPublicFromSecret=function(e){if(e){var t=o.decodeBase64(e),r=n.CryptoAgility.boxKeyPairFromSecretKey(t);return o.encodeBase64(r.publicKey)}},o.checkBoxKeyPair=function(e,t){if(!t||!e)return!1;var r=o.decodeBase64(e),a=n.CryptoAgility.boxKeyPairFromSecretKey(r);return t===o.encodeBase64(a.publicKey)},o.createRandomHash=function(e,t){var r;return"file"===e?(r=n.createFileCryptor2(void 0,t),l({password:Boolean(t),version:2,type:e,keys:r})):(r=n.createEditCryptor2(void 0,void 0,t),c({password:Boolean(t),version:2,type:e,keys:r}))};var f=o.parseTypeHash=function(e,t){if(t){var r,o=[],a={},i=(r=t,r.replace(/\/+/g,"/")).split("/"),s=function(){a.password=-1!==o.indexOf("p"),a.present=-1!==o.indexOf("present"),a.embed=-1!==o.indexOf("embed"),a.versionHash=function(e){var t;return e.some((function(e){if(/^hash=/.test(e))return t=e.slice(5),!0})),t?n.b64AddSlashes(t):""}(o),a.auditorKey=function(e){var t;return e.some((function(e){if(/^auditor=/.test(e))return t=e.slice(8),!0})),t?n.b64AddSlashes(t):""}(o),a.newPadOpts=function(e){var t;return e.some((function(e){if(/^newpad=/.test(e))return t=e.slice(7),!0})),t||""}(o),a.loginOpts=function(e){var t;return e.some((function(e){if(/^login=/.test(e))return t=e.slice(6),!0})),t||""}(o),a.ownerKey=function(e){var t;return e.some((function(e){if(86===e.length)return t=e,!0})),t}(o)};return i[1]&&"4"===i[1]?(a.getHash=function(t){if(!t||!Object.keys(t).length)return"";var n="/4/"+e+"/";return t.newPadOpts&&(n+="newpad="+t.newPadOpts+"/"),t.loginOpts&&(n+="login="+t.loginOpts+"/"),n},a.getOptions=function(){var e={};return a.newPadOpts&&(e.newPadOpts=a.newPadOpts),a.loginOpts&&(e.loginOpts=a.loginOpts),e},a.version=4,a.app=i[2],o=i.slice(3),s(),a):-1===["media","file","user","invite"].indexOf(e)?(a.type="pad",a.getHash=function(){return t},a.getOptions=function(){return{embed:a.embed,present:a.present,ownerKey:a.ownerKey,versionHash:a.versionHash,auditorKey:a.auditorKey,newPadOpts:a.newPadOpts,loginOpts:a.loginOpts,password:a.password}},"/"!==t.slice(0,1)&&t.length>=56?(a.channel=t.slice(0,32),a.key=t.slice(32,56),a.version=0,a):(a.getHash=function(e){var t=i.slice(0,5).join("/")+"/",r=void 0!==e.ownerKey?e.ownerKey:a.ownerKey;r&&(t+=r+"/"),(a.password||e.password)&&(t+="p/"),e.embed&&(t+="embed/"),e.present&&(t+="present/");var o=void 0!==e.versionHash?e.versionHash:a.versionHash;o&&(t+="hash="+n.b64RemoveSlashes(o)+"/");var s=void 0!==e.auditorKey?e.auditorKey:a.auditorKey;return s&&(t+="auditor="+n.b64RemoveSlashes(s)+"/"),e.newPadOpts&&(t+="newpad="+e.newPadOpts+"/"),e.loginOpts&&(t+="login="+e.loginOpts+"/"),t},i[1]&&"1"===i[1]?(a.version=1,a.mode=i[2],a.channel=i[3],a.key=n.b64AddSlashes(i[4]),o=i.slice(5),s(),a):i[1]&&"2"===i[1]?(a.version=2,a.app=i[2],a.mode=i[3],a.key=i[4],o=i.slice(5),s(),a):i[1]&&"3"===i[1]?(a.version=3,a.app=i[2],a.mode=i[3],a.channel=i[4],o=i.slice(5),s(),a):a)):(a.getHash=function(){return i.join("/")},-1!==["media","file"].indexOf(e)?(a.type="file",a.getOptions=function(){return{embed:a.embed,present:a.present,ownerKey:a.ownerKey,newPadOpts:a.newPadOpts,loginOpts:a.loginOpts,password:a.password}},a.getHash=function(e){var t=i.slice(0,4).join("/")+"/",n=void 0!==e.ownerKey?e.ownerKey:a.ownerKey;return n&&(t+=n+"/"),(a.password||e.password)&&(t+="p/"),e.embed&&(t+="embed/"),e.present&&(t+="present/"),e.newPadOpts&&(t+="newpad="+e.newPadOpts+"/"),e.loginOpts&&(t+="login="+e.loginOpts+"/"),t},i[1]&&"1"===i[1]?(a.version=1,a.channel=i[2].replace(/-/g,"/"),a.key=i[3].replace(/-/g,"/"),o=i.slice(4),s(),a):i[1]&&"2"===i[1]?(a.version=2,a.app=i[2],a.key=i[3],o=i.slice(4),s(),a):i[1]&&"3"===i[1]?(a.version=3,a.app=i[2],a.channel=i[3],o=i.slice(4),s(),a):a):-1!==["user"].indexOf(e)?(a.type="user",i[1]&&"1"===i[1]?(a.version=1,a.user=i[2],a.pubkey=i[3].replace(/-/g,"/"),a):a):-1!==["invite"].indexOf(e)?(a.type="invite",i[1]&&"2"===i[1]?(a.version=2,a.app=i[2],a.mode=i[3],a.key=i[4],o=i.slice(5),a.password=-1!==o.indexOf("p"),a):a):void 0)}},d=o.parsePadUrl=function(e){var t,n={};return e?("/"!==e.slice(-1)&&"#"!==e.slice(-1)&&(e+="/"),e=e.replace(/\/\?[^#]+#/,"/#"),n.getUrl=function(e){e=e||{};var t="/";return n.type?(t+=n.type+"/",!n.hashData&&e&&Object.keys(e).length?t+"#"+function(e){if(!e||!Object.keys(e).length)return"";var t="/4/"+n.type+"/";return e.newPadOpts&&(t+="newpad="+e.newPadOpts+"/"),e.loginOpts&&(t+="login="+e.loginOpts+"/"),t}(e):n.hashData?t+="#"+n.hashData.getHash(e):t):t},n.getOptions=function(){return n.hashData&&n.hashData.getOptions?n.hashData.getOptions():{}},/^https*:\/\//.test(e)?(e.replace(/^https*:\/\/([^\/]*)\/(.*?)\//i,(function(e,t,r){return n.domain=t,n.type=r,""})),-1===(t=e.indexOf("/#"))||(n.hash=e.slice(t+2),n.hashData=f(n.type,n.hash)),n):/^\/($|[^\/])/.test(e)?(t=e.indexOf("/#"),n.type=e.slice(1,t),-1===t||(n.hash=e.slice(t+2),n.hashData=f(n.type,n.hash)),n):n):n};return o.hashToHref=function(e,t){return"/"+t+"/#"+e},o.hrefToHash=function(e){return o.parsePadUrl(e).hash},o.getRelativeHref=function(e){if(e&&-1!==e.indexOf("#")){var t=d(e);return"/"+t.type+"/#"+t.hash}},o.getSecrets=function(t,r,o){var a,i,c={},u=function(){c.keys=n.createEditCryptor2(void 0,void 0,o),c.channel=s(c.keys.chanId),c.version=2,c.type=t};if(!r)return u(),c;if(r){if(!t)throw new Error("getSecrets with a hash requires a type parameter");a=f(t,r),i=r}if(0===i.length)return u(),c;if(0===a.version)c.channel=a.channel,c.key=a.key,c.version=0;else if(1===a.version){if(c.version=1,"pad"===a.type){if(c.channel=s(a.channel),"edit"===a.mode){if(c.keys=n.createEditCryptor(a.key),c.key=c.keys.editKeyStr,32!==c.channel.length||24!==c.key.length)throw new Error("The channel key and/or the encryption key is invalid")}else if("view"===a.mode&&(c.keys=n.createViewCryptor(a.key),32!==c.channel.length))throw new Error("The channel key is invalid")}else if("file"===a.type)c.channel=s(a.channel),c.keys={fileKeyStr:a.key,cryptKey:e.decodeBase64(a.key)};else if("user"===a.type)throw new Error("User hashes can't be opened (yet)")}else if(2===a.version)if(c.version=2,c.type=t,c.password=o,"pad"===a.type){if("edit"===a.mode){if(c.keys=n.createEditCryptor2(a.key,void 0,o),c.channel=s(c.keys.chanId),c.key=c.keys.editKeyStr,32!==c.channel.length||24!==c.key.length)throw new Error("The channel key and/or the encryption key is invalid")}else if("view"===a.mode&&(c.keys=n.createViewCryptor2(a.key,o),c.channel=s(c.keys.chanId),32!==c.channel.length))throw new Error("The channel key is invalid")}else if("file"===a.type){if(c.keys=n.createFileCryptor2(a.key,o),c.channel=s(c.keys.chanId),c.key=c.keys.fileKeyStr,48!==c.channel.length||24!==c.key.length)throw new Error("The channel key and/or the encryption key is invalid")}else if("user"===a.type)throw new Error("User hashes can't be opened (yet)");return c},o.getHashes=function(e){var t={};return(e=JSON.parse(JSON.stringify(e))).keys||e.key?(e.keys||(e.keys={}),(e.keys.editKeyStr||0===e.version&&e.key)&&(t.editHash=c(e)),e.keys.viewKeyStr&&(t.viewHash=u(e)),e.keys.fileKeyStr&&(t.fileHash=l(e)),t):t},o.getFormData=function(t,r,a){var i=(t=t||o.getSecrets("form",r,a))&&t.keys,s=i&&i.secondaryKey;if(s){var c=n.CryptoAgility.boxKeyPairFromSecretKey(e.decodeUTF8(s).slice(0,32)),u={};u.form_public=e.encodeBase64(c.publicKey);var l=u.form_private=e.encodeBase64(c.secretKey),f=o.getViewHashFromKeys({version:1,channel:t.channel,keys:{viewKeyStr:e.encodeBase64(i.cryptKey)}}),d=o.parseTypeHash("pad",f);return u.form_auditorHash=d.getHash({auditorKey:l}),u}},o.hrefToHexChannelId=function(e,t){var n=o.parsePadUrl(e);if(n&&n.hash)return o.getSecrets(n.type,n.hash,t).channel},o.getBlobPathFromHex=function(e){return"/blob/"+e.slice(0,2)+"/"+e},o.serializeHash=function(e){return e&&"/"!==e.slice(-1)&&(e+="/"),e},o.createInviteUrl=function(e,n){return n=n||o.createChannelId(),t.location.origin+"/invite/#/1/"+n+"/"+e.replace(/\//g,"-")+"/"},o.isValidChannel=function(e){return/^[a-zA-Z0-9]{32,48}$/.test(e)},o.isValidHref=function(e){if(e){var t=o.parsePadUrl(e);if(t&&t.type){if(t.hash){if(!t.hashData)return;if(void 0===t.hashData.version)return;if("pad"===t.hashData.type||"file"===t.hashData.type){if(!t.hashData.key&&!t.hashData.channel)return;if(t.hashData.key&&!/^[a-zA-Z0-9+-/=]+$/.test(t.hashData.key))return}}return t}}},o.decodeDataOptions=function(t){var n=decodeURIComponent(t),r=e.encodeUTF8(e.decodeBase64(n));return e.tryParse(r)||{}},o.encodeDataOptions=function(t){var n=JSON.stringify(t),r=e.encodeBase64(e.decodeUTF8(n));return encodeURIComponent(r)},o.getNewPadURL=function(e,t){var n=o.parsePadUrl(e),r=n.getOptions();return r.newPadOpts=o.encodeDataOptions(t),n.getUrl(r)},o.getLoginURL=function(e,t){var n=o.parsePadUrl(e),r=n.getOptions();return r.loginOpts=o.encodeDataOptions(t),n.getUrl(r)},o}(Ne(),ye(),Me(),h()))}("undefined"!=typeof window?window:{})}(Ce)),Ce.exports}var Le,He,Ke=Fe(),je=Ne(),Ue={exports:{}},Be={exports:{}};function Ve(){return Le||(Le=1,function(e){e.exports=function e(t,n,r){function o(i,s){if(!n[i]){if(!t[i]){if(!s&&l)return l(i);if(a)return a(i,!0);var c=new Error("Cannot find module '"+i+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[i]={exports:{}};t[i][0].call(u.exports,(function(e){var n=t[i][1][e];return o(n||e)}),u,u.exports,e,t,n,r)}return n[i].exports}for(var a=l,i=0;i=43)}})).catch((function(){return!1}))}function _(e){return"boolean"==typeof y?u.resolve(y):A(e).then((function(e){return y=e}))}function w(e){var t=v[e.name],n={};n.promise=new u((function(e,t){n.resolve=e,n.reject=t})),t.deferredOperations.push(n),t.dbReady?t.dbReady=t.dbReady.then((function(){return n.promise})):t.dbReady=n.promise}function O(e){var t=v[e.name].deferredOperations.pop();if(t)return t.resolve(),t.promise}function D(e,t){var n=v[e.name].deferredOperations.pop();if(n)return n.reject(t),n.promise}function S(e,t){return new u((function(n,r){if(v[e.name]=v[e.name]||F(),e.db){if(!t)return n(e.db);w(e),e.db.close()}var o=[e.name];t&&o.push(e.version);var a=i.open.apply(i,o);t&&(a.onupgradeneeded=function(t){var n=a.result;try{n.createObjectStore(e.storeName),t.oldVersion<=1&&n.createObjectStore(p)}catch(n){if("ConstraintError"!==n.name)throw n;console.warn('The database "'+e.name+'" has been upgraded from version '+t.oldVersion+" to version "+t.newVersion+', but the storage "'+e.storeName+'" already exists.')}}),a.onerror=function(e){e.preventDefault(),r(a.error)},a.onsuccess=function(){var t=a.result;t.onversionchange=function(e){e.target.close()},n(t),O(e)}}))}function T(e){return S(e,!1)}function C(e){return S(e,!0)}function x(e,t){if(!e.db)return!0;var n=!e.db.objectStoreNames.contains(e.storeName),r=e.versione.db.version;if(r&&(e.version!==t&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),o||n){if(n){var a=e.db.version+1;a>e.version&&(e.version=a)}return!0}return!1}function I(e){return new u((function(t,n){var r=new FileReader;r.onerror=n,r.onloadend=function(n){var r=btoa(n.target.result||"");t({__local_forage_encoded_blob:!0,data:r,type:e.type})},r.readAsBinaryString(e)}))}function N(e){return c([b(atob(e.data))],{type:e.type})}function P(e){return e&&e.__local_forage_encoded_blob}function k(e){var t=this,n=t._initReady().then((function(){var e=v[t._dbInfo.name];if(e&&e.dbReady)return e.dbReady}));return f(n,e,e),n}function R(e){w(e);for(var t=v[e.name],n=t.forages,r=0;r0&&(!e.db||"InvalidStateError"===o.name||"NotFoundError"===o.name))return u.resolve().then((function(){if(!e.db||"NotFoundError"===o.name&&!e.db.objectStoreNames.contains(e.storeName)&&e.version<=e.db.version)return e.db&&(e.version=e.db.version+1),C(e)})).then((function(){return R(e).then((function(){M(e,t,n,r-1)}))})).catch(n);n(o)}}function F(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function L(e){var t=this,n={db:null};if(e)for(var r in e)n[r]=e[r];var o=v[n.name];o||(o=F(),v[n.name]=o),o.forages.push(t),t._initReady||(t._initReady=t.ready,t.ready=k);var a=[];function i(){return u.resolve()}for(var s=0;s>4,l[c++]=(15&r)<<4|o>>2,l[c++]=(3&o)<<6|63&a;return u}function pe(e){var t,n=new Uint8Array(e),r="";for(t=0;t>2],r+=Q[(3&n[t])<<4|n[t+1]>>4],r+=Q[(15&n[t+1])<<2|n[t+2]>>6],r+=Q[63&n[t+2]];return n.length%3==2?r=r.substring(0,r.length-1)+"=":n.length%3==1&&(r=r.substring(0,r.length-2)+"=="),r}function ye(e,t){var n="";if(e&&(n=de.call(e)),e&&("[object ArrayBuffer]"===n||e.buffer&&"[object ArrayBuffer]"===de.call(e.buffer))){var r,o=Z;e instanceof ArrayBuffer?(r=e,o+=ee):(r=e.buffer,"[object Int8Array]"===n?o+=ne:"[object Uint8Array]"===n?o+=re:"[object Uint8ClampedArray]"===n?o+=oe:"[object Int16Array]"===n?o+=ae:"[object Uint16Array]"===n?o+=se:"[object Int32Array]"===n?o+=ie:"[object Uint32Array]"===n?o+=ce:"[object Float32Array]"===n?o+=ue:"[object Float64Array]"===n?o+=le:t(new Error("Failed to get type for BinaryArray"))),t(o+pe(r))}else if("[object Blob]"===n){var a=new FileReader;a.onload=function(){var n=z+e.type+"~"+pe(this.result);t(Z+te+n)},a.readAsArrayBuffer(e)}else try{t(JSON.stringify(e))}catch(n){console.error("Couldn't convert value into a JSON string: ",e),t(null,n)}}function ve(e){if(e.substring(0,$)!==Z)return JSON.parse(e);var t,n=e.substring(fe),r=e.substring($,fe);if(r===te&&X.test(n)){var o=n.match(X);t=o[1],n=n.substring(o[0].length)}var a=he(n);switch(r){case ee:return a;case te:return c([a],{type:t});case ne:return new Int8Array(a);case re:return new Uint8Array(a);case oe:return new Uint8ClampedArray(a);case ae:return new Int16Array(a);case se:return new Uint16Array(a);case ie:return new Int32Array(a);case ce:return new Uint32Array(a);case ue:return new Float32Array(a);case le:return new Float64Array(a);default:throw new Error("Unkown type: "+r)}}var me={serialize:ye,deserialize:ve,stringToBuffer:he,bufferToString:pe};function ge(e,t,n,r){e.executeSql("CREATE TABLE IF NOT EXISTS "+t.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],n,r)}function Ee(e){var t=this,n={db:null};if(e)for(var r in e)n[r]="string"!=typeof e[r]?e[r].toString():e[r];var o=new u((function(e,r){try{n.db=openDatabase(n.name,String(n.version),n.description,n.size)}catch(e){return r(e)}n.db.transaction((function(o){ge(o,n,(function(){t._dbInfo=n,e()}),(function(e,t){r(t)}))}),r)}));return n.serializer=me,o}function be(e,t,n,r,o,a){e.executeSql(n,r,o,(function(e,i){i.code===i.SYNTAX_ERR?e.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[t.storeName],(function(e,s){s.rows.length?a(e,i):ge(e,t,(function(){e.executeSql(n,r,o,a)}),a)}),a):a(e,i)}),a)}function Ae(e,t){var n=this;e=d(e);var r=new u((function(t,r){n.ready().then((function(){var o=n._dbInfo;o.db.transaction((function(n){be(n,o,"SELECT * FROM "+o.storeName+" WHERE key = ? LIMIT 1",[e],(function(e,n){var r=n.rows.length?n.rows.item(0).value:null;r&&(r=o.serializer.deserialize(r)),t(r)}),(function(e,t){r(t)}))}))})).catch(r)}));return l(r,t),r}function _e(e,t){var n=this,r=new u((function(t,r){n.ready().then((function(){var o=n._dbInfo;o.db.transaction((function(n){be(n,o,"SELECT * FROM "+o.storeName,[],(function(n,r){for(var a=r.rows,i=a.length,s=0;s0)return void a(we.apply(o,[e,s,n,r-1]));i(t)}}))}))})).catch(i)}));return l(a,n),a}function Oe(e,t,n){return we.apply(this,[e,t,n,1])}function De(e,t){var n=this;e=d(e);var r=new u((function(t,r){n.ready().then((function(){var o=n._dbInfo;o.db.transaction((function(n){be(n,o,"DELETE FROM "+o.storeName+" WHERE key = ?",[e],(function(){t()}),(function(e,t){r(t)}))}))})).catch(r)}));return l(r,t),r}function Se(e){var t=this,n=new u((function(e,n){t.ready().then((function(){var r=t._dbInfo;r.db.transaction((function(t){be(t,r,"DELETE FROM "+r.storeName,[],(function(){e()}),(function(e,t){n(t)}))}))})).catch(n)}));return l(n,e),n}function Te(e){var t=this,n=new u((function(e,n){t.ready().then((function(){var r=t._dbInfo;r.db.transaction((function(t){be(t,r,"SELECT COUNT(key) as c FROM "+r.storeName,[],(function(t,n){var r=n.rows.item(0).c;e(r)}),(function(e,t){n(t)}))}))})).catch(n)}));return l(n,e),n}function Ce(e,t){var n=this,r=new u((function(t,r){n.ready().then((function(){var o=n._dbInfo;o.db.transaction((function(n){be(n,o,"SELECT key FROM "+o.storeName+" WHERE id = ? LIMIT 1",[e+1],(function(e,n){var r=n.rows.length?n.rows.item(0).key:null;t(r)}),(function(e,t){r(t)}))}))})).catch(r)}));return l(r,t),r}function xe(e){var t=this,n=new u((function(e,n){t.ready().then((function(){var r=t._dbInfo;r.db.transaction((function(t){be(t,r,"SELECT key FROM "+r.storeName,[],(function(t,n){for(var r=[],o=0;o '__WebKitDatabaseInfoTable__'",[],(function(n,r){for(var o=[],a=0;a0}function Le(e){var t=this,n={};if(e)for(var r in e)n[r]=e[r];return n.keyPrefix=Re(e,t._defaultConfig),Fe()?(t._dbInfo=n,n.serializer=me,u.resolve()):u.reject()}function He(e){var t=this,n=t.ready().then((function(){for(var e=t._dbInfo.keyPrefix,n=localStorage.length-1;n>=0;n--){var r=localStorage.key(n);0===r.indexOf(e)&&localStorage.removeItem(r)}}));return l(n,e),n}function Ke(e,t){var n=this;e=d(e);var r=n.ready().then((function(){var t=n._dbInfo,r=localStorage.getItem(t.keyPrefix+e);return r&&(r=t.serializer.deserialize(r)),r}));return l(r,t),r}function je(e,t){var n=this,r=n.ready().then((function(){for(var t=n._dbInfo,r=t.keyPrefix,o=r.length,a=localStorage.length,i=1,s=0;s=0;t--){var n=localStorage.key(t);0===n.indexOf(e)&&localStorage.removeItem(n)}})):u.reject("Invalid arguments"),l(r,t),r}var qe={_driver:"localStorageWrapper",_initStorage:Le,_support:ke(),iterate:je,getItem:Ke,setItem:Ye,removeItem:Ge,clear:He,length:Ve,key:Ue,keys:Be,dropInstance:Je},We=function(e,t){return e===t||"number"==typeof e&&"number"==typeof t&&isNaN(e)&&isNaN(t)},Qe=function(e,t){for(var n=e.length,r=0;r{const t=(e,t)=>{let n=globalThis,r=globalThis;var o=n.CryptPad_Cache={},a=e.mkEvent(!0),i=!1,s=!1,c=!1;try{var u=n.indexedDB.open("test_db",1);u.onsuccess=function(){i=(c=!0)&&!s,a.fire()},u.onerror=function(){a.fire()}}catch(e){a.fire()}o.enable=function(){s=!1,i=c&&!s},o.disable=function(){s=!0,i=c&&!s},o.isEnabled=()=>i;var l=t.createInstance({driver:t.INDEXEDDB,name:"cp_cache"});o.getBlobCache=function(t,n){n=e.once(e.mkAsync(n||function(){})),a.reg((function(){i?l.getItem(t,(function(r,o){!r&&o&&o.c?(n(null,o.c),o.t=+new Date,l.setItem(t,o,(function(e){e&&console.error(e)}))):n(e.serializeError(r||"EINVAL"))})):n("NOCACHE")}))},o.setBlobCache=function(t,n,r){r=e.once(e.mkAsync(r||function(){})),a.reg((function(){i?n?l.setItem(t,{c:n,t:+new Date},(function(t){r(e.serializeError(t))})):r("EINVAL"):r("NOCACHE")}))},o.getChannelCache=function(t,n){n=e.once(e.mkAsync(n||function(){})),a.reg((function(){i?l.getItem(t,(function(r,o){!r&&o&&Array.isArray(o.c)?(n(null,o),o.t=+new Date,l.setItem(t,o,(function(e){e&&console.error(e)}))):n(e.serializeError(r||"EINVAL"))})):n("NOCACHE")}))};var f={};return o.storeCache=function(t,n,r,o){o=e.once(e.mkAsync(o||function(){})),a.reg((function(){f[t]=f[t]||e.throttle((function(n,r,o){var a,s;i?Array.isArray(r)&&n?(a=r,Array.isArray(a)&&(a.length>100&&a.splice(0,a.length-100),a.some((function(e,t){if(e.isCheckpoint)return s=t,!0})),a.splice(0,s)),l.setItem(t,{k:n,c:r,t:+new Date},(function(t){t&&o(e.serializeError(t))}))):o("EINVAL"):o("NOCACHE")}),50),f[t](n,r,o)}))},o.leaveChannel=function(e){delete f[e]},o.clearChannel=function(t,n){n=e.once(e.mkAsync(n||function(){})),a.reg((function(){i?l.removeItem(t,(function(){n()})):n("NOCACHE")}))},o.clear=function(t){t=e.once(e.mkAsync(t||function(){})),a.reg((function(){i?l.clear(t):t("NOCACHE")}))},o.getKeys=function(t){t=e.once(e.mkAsync(t||function(){})),a.reg((function(){i?l.keys().then((function(e){t(null,e)})).catch((function(e){t(e)})):t("NOCACHE")}))},o.getTime=function(t,n){n=e.once(e.mkAsync(n||function(){})),a.reg((function(){i?l.getItem(t,(function(t,r){!t&&r&&r.c?n(null,r.t):n(e.serializeError(t||"EINVAL"))})):n("NOCACHE")}))},r.CryptPad_clearIndexedDB=o.clear,o};e.exports&&(e.exports=t(Ne(),Ve()))})()}(Ue)),Ue.exports}var Ye=Ge(),Je=t({__proto__:null,default:r(Ye)},[Ye]);const qe=je.mkEvent(!0),We=je.mkEvent(!0),Qe=je.mkEvent(),ze=je.mkEvent();let Xe={};const Ze={setCustomize:e=>{Xe=e.ApiConfig},init:e=>{var t,n,r;const{broadcast:o,userHash:a,anonHash:i}=e,s=a||i||Ke.createRandomHash("drive"),c=e.store,u=Ke.getSecrets("drive",s),l=(null===(t=e.store)||void 0===t?void 0:t.network)||(null===(n=e.store)||void 0===n?void 0:n.networkPromise),f={data:{},websocketURL:Ae.getWebsocketURL(),network:l,channel:u.channel,readOnly:!1,validateKey:(null===(r=u.keys)||void 0===r?void 0:r.validateKey)||void 0,crypto:me.createEncryptor(u.keys),Cache:Je,userName:"fs",logLevel:1,ChainPad:k,updateProgress:function(e){e.type="drive",o([],"LOADING_DRIVE",e)},classic:!0},d=globalThis.CP_account_rt=C.create(f);c.driveSecret=u,c.proxy=d.proxy,c.onRpcReadyEvt=je.mkEvent(!0),c.loggedIn=void 0!==e.userHash;const h={loggedIn:c.loggedIn};return d.proxy.on("create",(function(e){c.realtime=e.realtime,c.network=e.network,c.loggedIn||(h.anonHash=Ke.getEditHashFromKeys(u))})).on("cacheready",(function(t){c.realtime=t.realtime,c.offline=!0;const n=!!c.networkPromise;if(c.networkPromise||(c.networkPromise=t.networkPromise),c.cacheReturned=h,c.networkPromise&&c.networkPromise.then&&!n){const e=setTimeout((function(){c.networkTimeout=!0,o([],"LOADING_DRIVE",{type:"offline"})}),5e3);c.networkPromise.then((function(t){c.network||(c.network=t),clearTimeout(e)}),(function(t){console.error(t),clearTimeout(e)}))}e.cache&&(h.edPublic=d.proxy.edPublic,qe.fire(h))})).on("ready",(function(t){delete c.networkTimeout,c.ready||(c.driveMetadata=t.metadata,d.proxy.drive||(d.proxy.drive={}),!d.proxy[Se.displayNameKey]&&c.noDriveName&&(d.proxy[Se.displayNameKey]=c.noDriveName),!d.proxy.uid&&c.noDriveUid&&(d.proxy.uid=c.noDriveUid),!d.proxy.form_seed&&e.form_seed&&(d.proxy.form_seed=e.form_seed),d.proxy.edPublic&&Array.isArray(Xe.adminKeys)&&-1!==Xe.adminKeys.indexOf(d.proxy.edPublic)&&(c.isAdmin=!0),h.edPublic=d.proxy.edPublic,We.fire(h))})).on("error",(function(e){"EDELETED"===e.error&&(c.ownDeletion||(c.isDeleted=!0,o([],"DRIVE_DELETED",e.message)))})).on("disconnect",(function(){c.offline=!0,Qe.fire(),o([],"UPDATE_METADATA")})).on("reconnect",(function(){c.offline=!1,ze.fire(),o([],"UPDATE_METADATA")})),{channel:u.channel,onAccountCacheReady:qe.reg,onAccountReady:We.reg,onDisconnect:Qe.reg,onReconnect:ze.reg}}};var $e,et=Object.freeze({__proto__:null,Account:Ze}),tt={exports:{}};function nt(){return $e||($e=1,function(e){(()=>{const t=(e={},t={})=>{var n={setCustomize:n=>{t=n.Messages,e=n.AppConfig},init:function(e){n.state=e}};return n.send=function(t,r,o){("function"!=typeof o&&(o=function(){}),e.disableFeedback)?o():t&&(!0===r||n.state)?function(e,t){var n=new XMLHttpRequest;n.open("HEAD",e),n.onreadystatechange=function(){this.readyState===this.DONE&&t&&t()},n.send()}("/common/feedback.html?"+t+"="+Math.random().toString(16).replace(/0./,""),o):o()},n.reportAppUsage=function(){var e=window.location.pathname.split("/").filter((function(e){return e})).join(".");/^#\/1\/view\//.test(window.location.hash)?n.send(e+"_VIEW"):n.send(e)},n.reportScreenDimensions=function(){var e=window.innerHeight,t=window.innerWidth;n.send("DIMENSIONS:"+e+"x"+t)},n.reportLanguage=function(){t&&n.send("LANG_"+t._languageUsed)},n};e.exports&&(e.exports=t(void 0,void 0))})()}(tt)),tt.exports}var rt,ot=nt(),at=t({__proto__:null,default:r(ot)},[ot]),it={exports:{}};function st(){return rt||(rt=1,function(e){e.exports&&(e.exports=function(e={},t){var n={setCustomize:t=>{e=t.AppConfig}};n.MINIMUM_PASSWORD_LENGTH="number"==typeof e.minimumPasswordLength?e.minimumPasswordLength:8,n.MINIMUM_NAME_LENGTH=1,n.MAXIMUM_NAME_LENGTH=64,n.isEmail=function(e){return/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(e).toLowerCase())},n.isLongEnoughPassword=function(e){return e.length>=n.MINIMUM_PASSWORD_LENGTH};var r=n.isString=function(e){return"string"==typeof e};return n.isValidUsername=function(e){return!!(r(e)&&e.length>=n.MINIMUM_NAME_LENGTH)},n.isValidPassword=function(e){return!(!e||!r(e))},n.passwordsMatch=function(e,t){return r(e)&&r(t)&&e===t},n.customSalt=function(){return"string"==typeof e.loginSalt?e.loginSalt:""},n.deriveFromPassphrase=function(e,r,o,a){t(r,e+n.customSalt(),8,1024,o||128,200,a,void 0)},n.dispenser=function(e){var t={used:0};return function(n){if(t.used+n>e.length)throw new Error("exceeded available entropy");if("number"!=typeof n)throw new Error("expected a number");if(n<=0)throw new Error("expected to consume a positive number of bytes");var r;return r=e.slice?e.slice(t.used,t.used+n):e.subarray(t.used,t.used+n),t.used+=n,r}},n}(void 0,pe()))}(it)),it.exports}var ct,ut,lt,ft=st(),dt=t({__proto__:null,default:r(ft)},[ft]),ht={exports:{}},pt={exports:{}},yt={exports:{}},vt={exports:{}};function mt(){return ct||(ct=1,function(e){e.exports&&(e.exports={whenRealtimeSyncs:function(e,t){"function"==typeof e.getAuthDoc?setTimeout((function(){e.getAuthDoc()!==e.getUserDoc()?e.onSettle(t):t()}),0):console.error("improper use of this function")}})}(vt)),vt.exports}function gt(){return ut||(ut=1,function(e){(()=>{const t=(e,t,n)=>{let r=globalThis;var o={setCustomize:()=>{}},a=function(e){try{return JSON.parse(JSON.stringify(e))}catch(e){return}};return o.init=function(o,i,s){var c=o.loggedIn,u=o.sharedFolder,l=o.readOnly,f=o.Messages||{},d=i.ROOT,h=i.FILES_DATA,p=i.STATIC_DATA,y=i.OLD_FILES_DATA,v=i.UNSORTED,m=i.TRASH,g=i.TEMPLATE,E=i.SHARED_FOLDERS,b=i.SHARED_FOLDERS_TEMP,A=i.debug;i._setReadOnly=function(e){(l=e)||i.fixFiles()},i.setHref=function(e,n,r){(n||e)&&(l||(n?[n]:i.findChannels([e])).forEach((function(e){var n=i.getFileData(e,!0);if(i.getHref(n)===r)return;n.href=i.cryptor.encrypt(r);const o=t.parsePadUrl(r);if("form"!==o.type)return;const a=t.getSecrets(o.type,o.hash,n.password);n.roHref="/"+o.type+"/#"+t.getViewHashFromKeys(a)})))},i.setPadAttribute=function(e,t,n,r){if(r=r||function(){},l)r("EFORBIDDEN");else{var o=i.getIdFromHref(e);if(o)if(t&&t.trim()){var s=i.getFileData(o,!0);"href"===t?i.setHref(null,o,n):s[t]=a(n),r(null)}else r("E_INVAL_ATTR");else r("E_INVAL_HREF")}},i.getPadAttribute=function(e,t,n){n=n||function(){};var r=i.getIdFromHref(e);if(r){var o=i.getFileData(r);n(null,a(o[t]))}else n(null,void 0)},i.pushData=function(t,n){if("function"!=typeof n&&(n=function(){}),l)n("EFORBIDDEN");else{var r=e.createRandomInteger(),o=a(t);o.href&&-1!==o.href.indexOf("#")&&(o.href=i.cryptor.encrypt(o.href)),s[h][r]=o,n(null,r)}},i.pushLink=function(t,n){if("function"!=typeof n&&(n=function(){}),l)n("EFORBIDDEN");else{var r=e.createRandomInteger(),o=a(t);s[p][r]=o,n(null,r)}},i.pushSharedFolder=function(t,n){if("function"!=typeof n&&(n=function(){}),l)n("EFORBIDDEN");else{var r,u=a(t);if(Object.keys(s[E]).some((function(e){if(s[E][e].channel===u.channel)return u.href&&!s[E][e].href&&(s[E][e].href=u.href),r=e,!0})))n("EEXISTS",r);else if(c&&!o.testMode){var f=e.createRandomInteger();u.href&&-1!==u.href.indexOf("#")&&(u.href=i.cryptor.encrypt(u.href)),s[E][f]=u,n(null,f)}else n("EAUTH")}},i.deprecateSharedFolder=function(e,t){if(!l){var n=s[E][e];if(n){if(!(!n.href||-1===i.cryptor.decrypt(n.href).indexOf("#")))(s[b][e]=JSON.parse(JSON.stringify(n))).legacy="PASSWORD_CHANGE"!==t;var r=i.findFile(Number(e));i.delete(r,null,!0),delete s[E][e]}}};var _=function(e){l||delete s[h][e]};i.checkDeletedFiles=function(e){if(c||o.testMode)if(l)e("EFORBIDDEN");else{var n=i.getFiles([d,"hrefArray",m]),r=[];i.getFiles([h,E,p]).forEach((function(e){if(-1===n.indexOf(e)){var a=i.isSharedFolder(e)?s[E][e]:i.getFileData(e),c=a.channel;a.lastVersion&&r.push(t.hrefToHexChannelId(a.lastVersion)),a.rtChannel&&r.push(a.rtChannel),c&&r.push(c),i.isSharedFolder(e)?(delete s[E][e],o.removeProxy&&o.removeProxy(e)):s[p][e]?delete s[p][e]:_(e)}})),r.length?e(null,r):e()}else e()};i.deleteMultiplePermanently=function(e,t,n){if(l)n("EFORBIDDEN");else{var r=e.filter((function(e){return i.isPathIn(e,[h])}));if(!c&&!o.testMode)return r.forEach((function(e){var t=e[1];t&&_(t)})),void n();var a=e.filter((function(e){return i.isPathIn(e,["hrefArray"])})),u=e.filter((function(e){return i.isPathIn(e,[d])})),f=e.filter((function(e){return i.isPathIn(e,[m])})),p=[];a.forEach((function(e){var t=i.find(e);p.push({root:e[0],id:t})})),function(e){l||e.forEach((function(e){var t=s[e.root].indexOf(e.id);s[e.root].splice(t,1)}))}(p),u.forEach((function(e){var t=e.slice(),n=t.pop();delete i.find(t)[n]}));var y,v=[];f.forEach((function(e){var t=e.slice(),n=t.pop(),r=i.find(t);4!==e.length?delete r[n]:v.push({name:e[1],el:r})})),y=v,l||y.forEach((function(e){var t=s[m][e.name].indexOf(e.el);s[m][e.name].splice(t,1)})),t?n():i.checkDeletedFiles(n)}},i.copyFromOtherDrive=function(e,n,r,o){if(!l){var a=[];if(Object.keys(r).forEach((function(e){e=Number(e);var t=r[e];if(t.static)return delete t.static,void(s[p][e]=t);t.href&&(t.href=i.cryptor.encrypt(t.href));var n=!1;for(var o in s[h])if(s[h][o].channel===t.channel){s[h][o].href||(s[h][o].href=t.href),n=!0;break}n?a.push(e):s[h][e]=t})),i.isFile(n)&&-1!==a.indexOf(n))i.log(f.sharedFolders_duplicate);else{if(i.isFolder(n)){var c=function(e){for(var t in e)i.isFile(e[t])?-1!==a.indexOf(e[t])&&(i.log(f.sharedFolders_duplicate),delete e[t]):i.isFolder(e[t])&&c(e[t])};c(n)}var u=i.find(e),d=i.isFile(n)?t.createChannelId():o,y=i.getAvailableName(u,d);Array.isArray(u)?u.push(n):u[y]=n}}};i.copyElement=function(e,n){if(!l&&!i.comparePath(e,n)){var r=i.find(e),o=i.find(n);if(i.isPathIn(n,[m])){if(!e||e.length<2||e[0]===m)return void A("Can't move an element from the trash to the trash: ",e);var a=e[e.length-1],c=i.isPathIn(e,["hrefArray"])?i.getTitle(r):a,u=e.slice();return u.pop(),function(e,t,n){if(!l){var r=s[m];void 0===r[e]&&(r[e]=[]);var o={element:t,path:n};r[e].push(o)}}(c,r,u),!0}if(i.isPathIn(n,["hrefArray"])){if(i.isFolder(r))return void i.log(f.fo_moveUnsortedError);if(e[0]===n[0])return;var d=n[0];return-1===s[d].indexOf(r)&&s[d].push(r),!0}var h=i.isFile(r)?i.getAvailableName(o,t.createChannelId()):i.isInTrashRoot(e)?e[1]:e.pop();if(void 0===o[h])return o[h]=r,!0;i.log(f.fo_unavailableName)}},i.forget=function(e){if(!l){var t=i.getIdFromHref(e);if(t){if(!c&&!o.testMode)return _(t),!0;var n=i.findFile(t);return i.move(n,[m]),!0}}},i.restoreHref=function(e){if(!l){var t=i.getIdFromHref(e);if(t&&i.isFile(t)){var n=i.findFile(t),r=!0;n.forEach((function(e){e[0]!==m?r=!1:i.delete(e,null,!0)})),r&&i.add(t)}}},i.add=function(e,n){if(!l&&(c||o.testMode)){e=Number(e);var r=s[h][e]||s[p][e]||s[E][e];if(r&&"object"==typeof r){var a,u=n;if(n&&!Array.isArray(n)&&(u=decodeURIComponent(n).split(",")),n&&i.isPathIn(u,["hrefArray"]))(a=i.find(u)).push(e);else if(-1!==i.getFiles([d,m,"hrefArray"]).indexOf(e)||u||(u=[d]),n&&i.isPathIn(u,[d])){if(a=i.find(u)){var f=i.getAvailableName(a,t.createChannelId());return void(a[f]=e)}a=i.find([d]),u.slice(1).forEach((function(e){a=a[e]=a[e]||{}})),a[t.createChannelId()]=e}}}},i.setFolderData=function(e,n,r,o){if(!l){var a=i.find(e);if(i.isFolder(a)&&!i.isSharedFolder(a)){if(!i.hasFolderData(a))a["000"+t.createChannelId().slice(0,-3)]={metadata:!0};i.getFolderData(a)[n]=r,o()}}};var w=function(e){i.rt?(i.rt.sync(),n.whenRealtimeSyncs(i.rt,e)):r.setTimeout(e,1e3)};return i.migrateReadOnly=function(e){if(!l&&o.editKey)if(s.version>=2)e();else{s.migrateRo=1;w((function(){var t=JSON.parse(JSON.stringify(s));i.reencrypt(o.editKey,o.editKey,t),setTimeout((function(){s.version>=2?e():(Object.keys(t).forEach((function(e){s[e]=t[e]})),s.version=2,delete s.migrateRo,w(e))}),1e3)}))}else e({error:"EFORBIDDEN"})},i.migrate=function(n){if(l)n();else{!function(){if(s[v]&&s[y]){A("UNSORTED still exists in the object, removing it...");var e=s[v];0!==e.length?(e.forEach((function(e){"string"==typeof e&&(0===s[y].filter((function(t){return t.href===e})).length&&s[y].push({href:e}))})),delete s[v]):delete s[v]}}(),function(n){if(s[y])try{A("Migrating file system..."),s.migrate=1;w((function(){var r=s[y].slice();s[h]||(s[h]={});var o=s[h];r.forEach((function(n){if(n&&n.href){var r=n.href,a=e.createRandomInteger(),s=i.findFile(r),c=n,u=t.createChannelId();o[a]=c||{href:r},s.forEach((function(e){var t=e.slice(),n=t.pop(),r=i.find(t);if(i.isInTrashRoot(e))return r.element=a,void(o[a].filename=e[1]);i.isPathIn(e,["hrefArray"])?r[n]=a:(r[u]=a,o[a].filename=n,delete r[n])}))}})),delete s[y],delete s.migrate,n()}))}catch(e){console.error(e),n()}else n()}(n)}},i.fixFiles=function(n){if(!l){n&&(A=function(){});var r=+new Date;A("Cleaning file system...");var a=JSON.stringify(s),f=function(n){"object"!=typeof s[d]&&(A("ROOT was not an object"),s[d]={});var r=n||s[d];if(!r)return console.error("Invalid element in root");var o,a=0,c=s[p],u=s[h];for(var l in r)if(null!==(o=r[l]))if(i.isFolderData(o))0!==a&&(A("Multiple metadata files in folder"),delete r[l]),a++;else if(i.isFile(o,!0)||i.isFolder(o))if(i.isFolder(o))f(o);else{if("string"==typeof o){var y=e.createRandomInteger(),v=t.createChannelId();u[y]={href:i.cryptor.encrypt(o),filename:l},r[v]=y,delete r[l]}if("number"==typeof o)u[o]||c[o]||(A("An element in ROOT doesn't have associated data",o,l),delete r[l])}else A("An element in ROOT was not a folder nor a file. ",o),delete r[l];else console.error("element[%s] is null",l),delete r[l]};e.isObject(s[p])||(A("STATIC_DATA was not an object"),s[p]={}),f(),function(){if(!u){"object"!=typeof s[m]&&(A("TRASH was not an object"),s[m]={});var t,n=s[m],r=function(n,r,o){if("object"==typeof n){if(!i.isSharedFolder(n.element))if(i.isFile(n.element,!0)||i.isFolder(n.element))if(Array.isArray(n.path)){if("string"==typeof n.element){var a=e.createRandomInteger();s[h][a]={href:i.cryptor.encrypt(n.element),filename:o},n.element=a}if(i.isFolder(n.element)&&f(n.element),"number"==typeof n.element)s[h][n.element]||s[p][n.element]||(A("An element in TRASH doesn't have associated data",n.element,o),t.push(r))}else t.push(r);else t.push(r)}else t.push(r)};for(var o in n)if(Array.isArray(n[o]))if(0===n[o].length)A("Empty array in TRASH root. ",n[o]),delete n[o];else{t=[];for(var a=0;a=0;c--)n[o].splice(t[c],1)}else A("An element in TRASH root is not an array. ",n[o]),delete n[o]}}(),function(){if(!u){Array.isArray(s[g])||(A("TEMPLATE was not an array"),s[g]=[]);var t=e.deduplicateString(s[g]);t.length!==s[g].length&&(s[g]=t);var n=s[g],r=i.getFiles([d]),o=[];n.forEach((function(t,a){if(i.isFile(t,!0)&&-1===r.indexOf(t)){if("string"==typeof t){var c=e.createRandomInteger();return s[h][c]={href:i.cryptor.encrypt(t)},void(n[a]=c)}if("number"==typeof t)s[h][t]||(A("An element in TEMPLATE doesn't have associated data",t),o.push(t))}else o.push(t)})),o.forEach((function(e){var t=n.indexOf(e);-1!==t&&n.splice(t,1)}))}}(),function(){"object"!=typeof s[h]&&(A("FILES_DATA was not an object"),s[h]={});var e=s[h],n=i.getFiles([d,m,"hrefArray"]),r=i.find([d]),a=[];for(var u in e)if(String(u)===String(Number(u))){var f=e[u=Number(u)];if(f&&"object"==typeof f)if(f.href||f.roHref){var y;try{y=f.href&&(-1!==f.href.indexOf("#")?f.href:i.cryptor.decrypt(f.href))}catch(e){}if(!y||-1!==y.indexOf("#")){var v,g=t.parsePadUrl(y||f.roHref);if(g.hash)if(g.type){if(y&&"pad"===g.hashData.type&&g.hashData.version)if("view"===g.hashData.mode)f.roHref=y,delete f.href;else if(f.roHref){var E=t.parsePadUrl(f.roHref);E.hash&&E.type||(v=t.getSecrets(g.type,g.hash,f.password),f.roHref="/"+g.type+"/#"+t.getViewHashFromKeys(v))}else v=t.getSecrets(g.type,g.hash,f.password),f.roHref="/"+g.type+"/#"+t.getViewHashFromKeys(v);if(0===g.hashData.version&&delete f.roHref,y&&"/"!==y.slice(0,1)&&(f.href=i.cryptor.encrypt(t.getRelativeHref(y))),f.ctime||(f.ctime=f.atime),f.title||(f.title=i.getDefaultName(g)),!f.channel)try{v||(v=t.getSecrets(g.type,g.hash,f.password)),f.channel=v.channel,console.log(f),A("Adding missing channel in filesData ",f.channel)}catch(e){console.error(e)}if(t.isValidChannel(f.channel)||console.error("Remove invalid channel",f.channel,f),!c&&!o.testMode||-1!==n.indexOf(u));else A("An element in filesData was not in ROOT, TEMPLATE or TRASH.",u,f),r[t.createChannelId()]=u}else A("Removing an element in filesData with a invalid type.",f),a.push(u);else A("Removing an element in filesData with a invalid href.",f),a.push(u)}}else A("Removing an element in filesData with a missing href.",f),a.push(u);else A("An element in filesData was not an object.",f),a.push(u)}else A("Invalid file ID in filesData.",u),a.push(u);a.forEach((function(e){_(e)}));var b=s[p],w=[];for(var O in b){var D=b[O=Number(O)];D&&"object"==typeof D&&D.href?!c&&!o.testMode||-1!==n.indexOf(O)||w.push(O):w.push(O)}w.forEach((function(e){l||delete s[p][e]}))}(),Object.keys(s).forEach((function(e){"/"===e.slice(0,1)&&delete s[e]})),function(){if(!u){"object"!=typeof s[E]&&(A("SHARED_FOLDER was not an object"),s[E]={});var e,n,r=s[E],o=i.getFiles([d,m]),a=i.find([d]);for(var c in r){var l;n=r[c],c=Number(c);try{l=n.href&&(-1!==n.href.indexOf("#")?n.href:i.cryptor.decrypt(n.href))}catch(e){}if((e=t.parsePadUrl(l||n.roHref))&&e.hash&&"undefined"!==e.hash){if(-1===o.indexOf(c))console.log("missing"+c),a[t.createChannelId()]=c}else delete r[c]}}}(),function(){if(!u){"object"!=typeof s[b]&&(A("SHARED_FOLDER_TEMP was not an object"),s[b]={});var e=s[b],t=s[E];for(var n in e)t[n]&&delete e[n]}}();var y=+new Date-r+"ms";JSON.stringify(s)===a?A("File system was clean.",y):A("Your file system was corrupted. It has been cleaned so that the pads you visit can be stored safely.",y)}},i},o};e.exports&&(e.exports=t(Ne(),Fe(),mt()))})()}(yt)),yt.exports}function Et(){return lt||(lt=1,function(e){(()=>{const t=(e,t,n,r,o,a={})=>{let i=globalThis;var s={setCustomize:e=>{a=e.Messages,r.setCustomize(e)}},c=s.ROOT="root",u=s.UNSORTED="unsorted",l=s.TRASH="trash",f=s.TEMPLATE="template",d=s.SHARED_FOLDERS="sharedFolders",h=s.SHARED_FOLDERS_TEMP="sharedFoldersTemp",p=s.FILES_DATA=n.storageKey,y=s.OLD_FILES_DATA=n.oldStorageKey,v=s.STATIC_DATA="static";s.getDefaultName=function(e){var t=e.type;return a.type[t]+" - "+function(){if(i.Intl&&i.Intl.DateTimeFormat)return new i.Intl.DateTimeFormat(void 0,{weekday:"short",year:"numeric",month:"long",day:"numeric"}).format(new Date);return(new Date).toString().split(" ").slice(0,4).join(" ")}()};var m=s.createCryptor=function(e){var t={};if(!e)return t.encrypt=function(e){return e},t.decrypt=function(e){return e},t;try{var n=o.createEncryptor(e);t.encrypt=function(e){try{return"/file/#"===e.slice(0,7)?e:n.encrypt(e)}catch(e){return}},t.decrypt=function(e){try{return n.decrypt(e)}catch(e){return}}}catch(e){console.error(e)}return t};return s.getHref=function(e,t){if(e.href&&-1!==e.href.indexOf("#"))return e.href;if(e.href&&t){var n=t.decrypt(e.href);if(n&&-1!==n.indexOf("#"))return n}return e.roHref},s.reencrypt=function(e,t,n){if(n){var r=m(e),o=m(t);Object.keys(n[p]).forEach((function(e){var t=n[p][e]||{};if(t.href&&t.roHref&&!t.fileType){var a=t.href&&-1===t.href.indexOf("#")?r.decrypt(t.href):t.href;if(!a)return;t.href=o.encrypt(a)}})),Object.keys(n[d]||{}).forEach((function(e){var t=n[d][e]||{};if(t.href){var a=t.href&&-1===t.href.indexOf("#")?r.decrypt(t.href):t.href;if(!a)return;t.href=o.encrypt(a)}})),Object.keys(n[h]||{}).forEach((function(e){var t=n[h][e]||{};if(t.href){var a=t.href&&-1===t.href.indexOf("#")?r.decrypt(t.href):t.href;if(!a)return;t.href=o.encrypt(a)}}))}else console.error("Nothing to reencrypt")},s.init=function(n,o){var i={};i.cryptor=m(o.editKey),i.setReadOnly=function(e,t){o.editKey=t,i.cryptor=m(t),i.cryptor.k=Math.random(),i.readOnly=e,i._setReadOnly&&i._setReadOnly(e)},i.readOnly=o.readOnly,i.reencrypt=s.reencrypt,i.getDefaultName=s.getDefaultName;var g=o.sframeChan,E=a.fm_newFolder||"New folder",b=a.fm_newFile||"New file";i.ROOT=c,i.STATIC_DATA=v,i.UNSORTED=u,i.TRASH=l,i.TEMPLATE=f,i.SHARED_FOLDERS=d,i.SHARED_FOLDERS_TEMP=h,i.FILES_DATA=p,i.OLD_FILES_DATA=y;var A=i.sharedFolder=o.sharedFolder;i.id=o.id;var _=function(){console.debug.apply(console,arguments)},w=i.log=o.log||_,O=o.logError||_,D=i.debug=o.debug||_;i.fixFiles=function(){};var S=i.error=function(){g?g.query("Q_DRIVE_USEROBJECT",{cmd:"fixFiles",data:{}},(function(){})):("function"==typeof i.fixFiles&&i.fixFiles(),console.error.apply(console,arguments),i.fixFiles())};o.outer&&r.init(o,i,n),i.getStructure=function(){var e={};return e[c]={},e[l]={},e[p]={},e[f]=[],e[d]={},e};var T=i.getHref=function(e){return s.getHref(e,i.cryptor)},C=function(e){return null===e?"null":Array.isArray(e)?"array":typeof e};i.isValidDrive=function(e){var t=i.getStructure();return"object"==typeof e&&Object.keys(t).every((function(n){return e[n]&&C(t[n])===C(e[n])}))};var x=function(){return[f]},I=function(e,t){return e===t},N=i.isSharedFolder=function(e){return!A&&Boolean(n[d]&&n[d][e])},P=i.isFile=function(e,t){return!N(e)&&("number"==typeof e||(void 0!==n[y]||t)&&"string"==typeof e)},k=i.isFolderData=function(e){return"object"==typeof e&&!0===e.metadata};i.isReadOnlyFile=function(e){if(!P(e))return!1;var t=i.getFileData(e);return t.roHref?Boolean(t.roHref&&!t.href):void 0},i.isStaticFile=function(e){return Boolean(n[v]&&n[v][e])};var R=i.isFolder=function(e){return!k(e)&&("object"==typeof e&&!e.channel||N(e))};i.isFolderEmpty=function(e){return!!R(e)&&(0===Object.keys(e).length||!(1!==Object.keys(e).length||!k(e[Object.keys(e)[0]])))},i.hasSubfolder=function(e,t){if(!R(e))return!1;var n=0,r=function(e){n+=R(e.element)?1:0};for(var o in e)t?Array.isArray(e[o])&&e[o].forEach(r):n+=R(e[o])?1:0;return n},i.hasFile=function(e,t){if(!R(e))return!1;var n=0,r=function(e){n+=P(e.element)?1:0};for(var o in e)t?Array.isArray(e[o])&&e[o].forEach(r):n+=P(e[o])?1:0;return n},i.hasFolderData=function(e){for(var t in e)if(k(e[t]))return!0};var M=i.hasSubSharedFolder=function(e){for(var t in e){if(N(e[t]))return!0;if(R(e[t])&&M(e[t]))return!0}return!1},F=i.getFileData=function(t,r){if(t){var a,s;try{a=(n[v]||{})[t]}catch(e){console.error(e)}if(a){var c=r?a:e.clone(a);return r||(c.static=!0),c}try{s=n[p][t]||{}}catch(e){console.error(e),s={}}if(!r&&(s=JSON.parse(JSON.stringify(s))).href&&-1===s.href.indexOf("#"))if(o.editKey)try{s.href=i.cryptor.decrypt(s.href)}catch(e){delete s.href}else delete s.href;return s}};i.getFolderData=function(e){for(var t in e)if(k(e[t]))return e[t];return{}};var L=i.getTitle=function(e,t){if(N(e))return"??";var n=F(e);if(n){if(n.static)return n.name;if(e&&(n.href||n.roHref))return"title"===t?n.title:"name"===t?n.filename:n.filename||n.title||b;S("getTitle called with a non-existing file id: ",e,n)}else S("unable to retrieve data about the requested file: ",e,n)},H=i.comparePath=function(e,t){if(!(e&&t&&Array.isArray(e)&&Array.isArray(t)))return!1;if(e.length!==t.length)return!1;for(var n=!0,r=e.length-1;n&&r>=0;)n=e[r]===t[r],r--;return n},K=i.isSubpath=function(e,t){var n=t.slice(),r=e.slice(0,n.length);return H(n,r)},j=i.isPathIn=function(e,t){if(t){var n=t.indexOf("hrefArray");return-1!==n&&(t.splice(n,1),t=t.concat(x())),t.some((function(t){return Array.isArray(e)&&e[0]===t}))}},U=i.isInTrashRoot=function(e){return e[0]===l&&4===e.length},B=function(e,t){if(t){if(0===t.length)return e;var n=t.slice(),r=n.shift();if(void 0!==e[r])return B(e[r],n);D("Unable to find the key '"+r+"' in the root object provided:",e)}else S("Invalid path:\n",t,"\nin root\n",e)},V=i.find=function(e){return B(n,e)},G=i.getFilesRecursively=function(e,t){for(var n in t=t||[],e)P(e[n])||N(e[n])?-1===t.indexOf(e[n])&&t.push(e[n]):k(e[n])||G(e[n],t);return t},Y={array:function(e){return n[e]||(n[e]=[]),n[e].slice()}};x().forEach((function(e){Y[e]=function(){return Y.array(e)}})),Y.hrefArray=function(){var t=[];return A?t:(x().forEach((function(e){t=t.concat(Y[e]())})),e.deduplicateString(t))},Y[c]=function(){var e=[];return G(n[c],e),e},Y[l]=function(){var e=n[l],t=[],r=function(e){P(e.element)||N(e.element)?-1===t.indexOf(e.element)&&t.push(e.element):G(e.element,t)};for(var o in e){if(!Array.isArray(e[o]))return void S("Trash contains a non-array element");e[o].forEach(r)}return t},Y[y]=function(){var e=[];return n[y]?(n[y].forEach((function(t){t.href&&-1===e.indexOf(t.href)&&e.push(t.href)})),e):e},Y[v]=function(){return n[v]?Object.keys(n[v]).map(Number).filter(Boolean):[]},Y[p]=function(){return n[p]?Object.keys(n[p]).map(Number).filter(Boolean):[]},Y[d]=function(){return n[d]?Object.keys(n[d]).map(Number).filter(Boolean):[]};var J=i.getFiles=function(t){var n=[];return t&&t.length||(t=[c,"hrefArray",l,y,p,d]),t.forEach((function(e){"function"==typeof Y[e]&&(n=n.concat(Y[e]()))})),e.deduplicateString(n)},q=i.getIdFromHref=function(e){var r,o=function(e){if(e)return t.parsePadUrl(e).getUrl().replace(/\/p\/?/,"/")},a=o(e);return J([p]).some((function(e){if(o(T(n[p][e]))===a||o(n[p][e].roHref)===a)return r=e,!0})),r};i.getSFIdFromHref=function(e){var r,o=function(e){if(e)return t.parsePadUrl(e).getUrl().replace(/\/p\/?/,"/")},a=o(e);return J([d]).some((function(e){if(o(T(n[d][e]))===a||o(n[d][e].roHref)===a)return r=e,!0})),r};var W=function(e,t){if(!j(e,[c,l]))return[];t=Array.isArray(t)?t:[t];var n={},r=V(e),o=function(e){Object.keys(e).forEach((t=>{n[t]||=[],Array.prototype.push.apply(n[t],e[t])}))};if(P(r)||N(r))return t.some((t=>{I(t,r)&&(n[t]||=[],n[t].push(e))})),n;if(R(r))for(var a in r){let n=e.slice();n.push(a),o(W(n,t))}return n},Q=function(e,t){if(A)return{};if(!n[e])return{};var r=n[e].slice(),o={},a=-1;return t.forEach((t=>{for(;-1!==(a=r.indexOf(t,a+1));)o[t]||=[],o[t].push([e,a])})),o},z=function(e,t){if(A)return[];var n=V(e),r={},o=function(e){Object.keys(e).forEach((t=>{r[t]||=[],Array.prototype.push.apply(r[t],e[t])}))};if(1===e.length&&"object"==typeof n&&Object.keys(n).forEach((function(r){var a=n[r];if(Array.isArray(a)){var i=e.slice();i.push(r),o(z(i,t))}})),2===e.length){if(!Array.isArray(n))return[];n.forEach((function(n,a){var i=e.slice();i.push(a),i.push("element"),P(n.element)?t.some((e=>{I(e,n.element)&&(r[e]||=[],r[e].push(i))})):o(z(i,t))}))}return e.length>=4&&o(W(e,t)),r},X=i.findFiles=function(e){var t=W([c],e),n=Q(f,e),r=z([l],e);let o={};return e.forEach((e=>{o[e]=[]})),[t,n,r].forEach((e=>{Object.keys(e).forEach((t=>{o[t]||=[],Array.prototype.push.apply(o[t],e[t])}))})),o},Z=i.findFile=function(e){return X([e])[e]||[]};i.findChannels=function(e,t){var r=n[p],o=n[d],a=[p];return t&&a.push(d),J(a).filter((function(t){var n=r[t]||o[t]||{};return-1!==e.indexOf(n.channel)}))},i.search=function(r){if("string"!=typeof r)return[];r=r.trim();var o,a=[],s=n[p],u=n[d],l=r.toLowerCase();/^#/.test(l)&&(o=[l.slice(1).trim()]);J([p,d]).forEach((function(e){var t=s[e]||u[e];if(t)if(Array.isArray(t.tags)&&(n=t.tags,o&&n.length&&(n=n.map((function(e){return e.toLowerCase()})),o.some((function(e){return n.some((function(t){return t===e}))})))))a.push(e);else{var n,r=t.title||t.lastTitle;(r&&-1!==r.toLowerCase().indexOf(l)||t.filename&&-1!==t.filename.toLowerCase().indexOf(l))&&a.push(e)}}));var f=t.getRelativeHref(r);if(f){var h=q(f);h&&a.push(h)}a=e.deduplicateString(a);var y=[];a.forEach((function(e){y.push({id:e,paths:Z(e),data:i.getFileData(e)})}));var v=[],m=function(e,t){for(var n in e)R(e[n])&&!N(e[n])&&(-1!==n.toLowerCase().indexOf(l)&&v.push({id:null,paths:[t.concat(n)],data:{title:n}}),m(e[n],t.concat(n)))};return m(n[c],[c]),v=v.sort((function(e,t){return e.data.title.toLowerCase()>t.data.title.toLowerCase()})),y=v.concat(y)},i.getRecentPads=function(){var e=n[p];return Object.keys(e).filter((function(t){return e[t]})).sort((function(t,n){return e[n].atime-e[t].atime})).map((function(e){return Number(e)}))},i.getOwnedPads=function(e){var t=n[p];return Object.keys(t).filter((function(n){return t[n].owners&&-1!==t[n].owners.indexOf(e)})).map((function(e){return Number(e)}))};var $=i.getAvailableName=function(e,t){if(void 0===e[t])return t;for(var n=t,r=1;void 0!==e[n];)n=t+"_"+r,r++;return n},ee=i.move=function(e,t,n){if(g)g.query("Q_DRIVE_USEROBJECT",{cmd:"move",data:{paths:e,newPath:t}},n);else{var r=[];e.forEach((function(e){var n=e.slice();n.pop(),H(n,t)||(K(t,e)?w(a.fo_moveFolderToChildError):i.copyElement(e.slice(),t)&&r.push(e))})),i.delete(r,n)}};return i.restore=function(e,t){if(g)g.query("Q_DRIVE_USEROBJECT",{cmd:"restore",data:{path:e}},t);else if(U(e)){var n=e.slice();n.pop();var r=V(n).path;ee([e],r,t)}},i.addFolder=function(e,t,n){if(g)g.query("Q_DRIVE_USEROBJECT",{cmd:"addFolder",data:{path:e,name:t}},n);else{var r=V(e),o=$(r,t||E);r[o]={};var a=e.slice();a.push(o),n({newPath:a})}},i.delete=function(e,t,n){g?g.query("Q_DRIVE_USEROBJECT",{cmd:"delete",data:{paths:e,nocheck:n}},t):(t=t||function(){},i.deleteMultiplePermanently(e,n,t))},i.emptyTrash=function(e){e=e||function(){},g?g.query("Q_DRIVE_USEROBJECT",{cmd:"emptyTrash"},e):(n[l]={},i.checkDeletedFiles(e))},i.ownedInTrash=function(e){return J([l]).map((function(t){var r=N(t)?n[d][t]:i.getFileData(t);if(r)return e(r.owners)?r.channel:void 0})).filter(Boolean)},i.rename=function(e,t,r){if(r=r||function(){},g)g.query("Q_DRIVE_USEROBJECT",{cmd:"rename",data:{path:e,newName:t}},r);else if(e.length<=1)O("Renaming `root` is forbidden");else{var o,i=V(e);if(R(i)&&!N(i)){var s=e.slice(),c=s.pop();if(!t||!t.trim()||c===t)return;var u=V(s);return void 0!==u[t]?void w(a.fo_existingNameError):(u[t]=i,delete u[c],void("function"==typeof r&&r()))}if(o=N(i)?n[d][i]:n[p][i]||n[v][i])return n[v][i]?t&&t.trim()?(o.name=t,void r()):void r():t&&""!==t.trim()?void(L(i,"name")!==t&&(o.filename=t,"function"==typeof r&&r())):(delete o.filename,void("function"==typeof r&&r()))}},i.getTagsList=function(){var e,t={},r=function(e){t[e]=t[e]?++t[e]:1};for(var o in n[p])(e=n[p][o]).tags&&Array.isArray(e.tags)&&e.tags.forEach(r);return t},i},s};e.exports&&(e.exports=t(Ne(),Fe(),Oe(),gt(),ye(),void 0))})()}(pt)),pt.exports}var bt,At,_t,wt,Ot={exports:{}};function Dt(){return bt||(bt=1,function(e){e.exports=function(e){var t,n=[],r=[],o=0,a=function(e){return o++,function(){for(e&&e.apply(null,arguments),o=(o||1)-1;!o&&n.length&&!t;)n.shift()(a)}};a.abort=function(){r.forEach(clearTimeout),t=1};var i={nThen:function(e){return t||(o?n.push(e):e(a)),i},orTimeout:function(e,s){if(t)return i;if(!s)throw Error("Must specify milliseconds to orTimeout()");var c,u=setTimeout((function(){for(;n.shift()!==c;);for(e(a),o=(o||1)-1;!o&&n.length;)n.shift()(a)}),s);return n.push(c=function(){var e=r.indexOf(u);if(e>-1)return r.splice(e,1),void clearTimeout(u);throw new Error("timeout not listed in array")}),r.push(u),i}};return i.nThen(e)}}(Ot)),Ot.exports}function St(){if(_t)return At;_t=1;return At=((e,t,n,r,o,a,i,s)=>{var c={},u={};return c.checkMigration=function(e,n,r,o){var a=t.once(t.mkAsync(o));if(n)if(e)if(n.version>=2)a();else if(n.migrateRo){var i,s=!1,c=setInterval((function(){if(n.version>=2)return s=!0,clearTimeout(i),clearInterval(c),void a()}),100);i=setTimeout((function(){clearInterval(c),r.migrateReadOnly((function(){s=!0,a()}))}),2e4);n.on("change",["version"],(function(){s||n.version>=2&&(s=!0,clearTimeout(i),clearInterval(c),a())}))}else r.migrateReadOnly(a);else a();else a()},c.migrate=function(e){var n=u[e];if(n){var r=n.teams;if(Array.isArray(r)&&r.length){var o=r[0];if(o.secondaryKey){var a=t.find(o,["store","manager","folders",o.id]);a&&a.proxy&&!a.proxy.version&&a.userObject.migrateReadOnly((function(){r.forEach((function(e){t.find(e,["store","manager","folders",e.id,"userObject"]).setReadOnly(!1,e.secondarykey)}))}))}}}},c.load=function(n,l,f,d){var h=t.once(t.mkAsync(d)),p=n.network,y=n.store,v=n.isNew,m=n.isNewChannel,g=y.id,E=y.handleSharedFolder,b=y.manager.user.userObject.getHref(f),A=e.parsePadUrl(b),_=e.getSecrets("drive",A.hash,f.password);if(!_.keys)return y.manager.deprecateProxy(l),void h(null);var w=_.keys.secondaryKey;o((function(e){n.cache&&r.getChannelCache(_.channel,e((function(t){if("EINVAL"===t)return e.abort(),y.manager.restrictedProxy(l,_.channel),void h(null)})))})).nThen((function(e){m(null,{channel:_.channel},e((function(t){if(t.isNew&&!v)return y.manager.deprecateProxy(l,_.channel,t.reason),e.abort(),void h(null)})))})).nThen((function(){var e=u[_.channel];if(e&&e.readOnly&&w&&c.upgrade(_.channel,_),e&&e.ready&&e.rt)return setTimeout((function(){y.manager.addProxy(l,e.rt,(function(){c.leave(_.channel,g)}),w),h(e.rt)})),e.teams.push({cb:h,store:y,id:l}),void(E&&E(l,e.rt));if(e&&!e.ready&&e.rt)return e.teams.push({cb:h,store:y,secondaryKey:w,id:l}),void(E&&E(l,e.rt));e=u[_.channel]={teams:[{cb:h,store:y,secondaryKey:w,id:l}],readOnly:!Boolean(w)};var t=f.owners,o={data:{},channel:_.channel,readOnly:!Boolean(w),crypto:a.createEncryptor(_.keys),userName:"sharedFolder",logLevel:1,ChainPad:s,classic:!0,network:p,Cache:r,metadata:{validateKey:_.keys.validateKey||void 0,owners:t},onRejected:n.Store&&n.Store.onRejected},d=e.rt=i.create(o);d.proxy.on("cacheready",(function(){e.teams&&(e.teams.forEach((function(t){d.cache=!0,t.store.manager.addProxy(t.id,d,(function(){c.leave(_.channel,t.store.id)}),t.secondaryKey,n.updatePassword),n.updatePassword=!1,t.cb(e.rt)})),e.ready=!0)})),d.proxy.on("ready",(function(){v&&!Object.keys(d.proxy).length&&(d.proxy.version=2),e.teams&&(e.teams.forEach((function(t){d.cache=!1,t.store.manager.addProxy(t.id,d,(function(){c.leave(_.channel,t.store.id)}),t.secondaryKey,n.updatePassword),t.cb(e.rt)})),e.ready=!0)})),d.proxy.on("error",(function(t){if(t&&t.error){if("EDELETED"===t.error){try{e.teams.forEach((function(e){e.store.manager.deprecateProxy(e.id,_.channel,t.message),e.store.handleSharedFolder&&e.store.handleSharedFolder(e.id,null),e.cb()}))}catch(e){}return delete u[_.channel],void h()}if("ERESTRICTED"===t.error)return e.teams.forEach((function(e){e.store.manager.restrictedProxy(e.id,_.channel),e.cb()})),delete u[_.channel],void h()}})),E&&E(l,d)}))},c.upgrade=function(e,t){var n=u[e];if(n&&n.readOnly&&n.rt.setReadOnly&&t.keys&&t.keys.editKeyStr){var r=a.createEncryptor(t.keys);n.readOnly=!1,n.rt.setReadOnly(!1,r)}},c.leave=function(e,t){var n=u[e];if(n){var r,o=n.teams;if(Array.isArray(o))o.some((function(e,n){if(e.store.id===t)return e.store.handleSharedFolder&&e.store.handleSharedFolder(e.id,null),r=n,!0})),void 0!==r&&(o.splice(r,1),o.length||n.rt&&n.rt.stop&&n.rt.stop())}},c.updatePassword=function(r,a,i,s){var l=a.oldChannel,f=a.href,d=a.password,h=e.parsePadUrl(f),p=e.getSecrets(h.type,h.hash,d),y=u[l];if(y){if(y.rt&&y.rt.stop)try{y.rt.stop()}catch(e){}var v=o;y.teams.forEach((function(e){v=v((function(o){var a=e.store,s=e.id,u=t.find(a.proxy,["drive",n.SHARED_FOLDERS])||{};if(s&&u[s]){var f=JSON.parse(JSON.stringify(u[s]));f.password=d,c.load({network:i,store:a,updatePassword:!0,Store:r,isNewChannel:r.isNewChannel},s,f,o()),a.rpc&&(a.rpc.unpin([l],o()),a.rpc.pin([p.channel],o()))}})).nThen})),v((function(){s()}))}else s({error:"ENOTFOUND"})},c.loadSharedFolders=function(e,t,r,a,i,s,u,l){var f=a[n.SHARED_FOLDERS]||{},d=Object.keys(f).length,h=1,p=s();u=u||function(){},o((function(n){Object.keys(f).forEach((function(o){var a=f[o];c.load({network:t,store:r,Store:e,cache:l,isNewChannel:e.isNewChannel},o,a,n((function(){u({progress:h,max:d}),h++})))}))})).nThen((function(){setTimeout(p)}))},c.isSharedFolderChannel=function(e){return Object.keys(u).includes(e)},c})(Fe(),Ne(),Et(),Ge(),Dt(),ye(),S(),I()),At}function Tt(){return wt||(wt=1,function(e){(()=>{const t=(e,t,n,r={},o,a,i={})=>{var s=function(t,n,r,o,a,i){if(!t.folders[n]||i||t.folders[n].restricted){var s=function(e){var t={};for(var n in e.cfg)t[n]=e.cfg[n];return t}(t);s.sharedFolder=!0,s.id=n,s.editKey=a,s.rt=r.realtime,s.readOnly=Boolean(!a);var c=e.init(r.proxy,s);c.fixFiles&&c.fixFiles();var u=r.proxy;if(u.metadata&&u.metadata.title){var l=t.user.proxy[e.SHARED_FOLDERS][n];l&&(l.lastTitle=u.metadata.title)}return t.folders[n]={proxy:r.proxy,userObject:c,leave:o,restricted:u.restricted,offline:Boolean(r.cache)},u.on&&(u.on("disconnect",(function(){t.folders[n].offline=!0})),u.on("reconnect",(function(){t.folders[n].offline=!1}))),c}t.folders[n].offline&&!r.cache&&t.Store&&(t.folders[n].offline=!1,t.folders[n].userObject.fixFiles&&t.folders[n].userObject.fixFiles(),t.Store.refreshDriveUI())},c=function(e,t){var n=e.folders[t];n&&(n.leave(),delete e.folders[t])},u=function(n,r,o,a){if(!n.folders[r]||!n.folders[r].deleting){if(n.user.userObject.readOnly){return c(n,r),s(n,r,{proxy:{deprecated:!0}},(function(){})),void n.Store.refreshDriveUI()}if(o&&n.unpinPads([o],(function(){})),a&&"PASSWORD_CHANGE"!==a){let o=t.find(n,["user","proxy",e.SHARED_FOLDERS]),a=o[r]&&o[r].lastTitle;return a&&((e,t,n)=>{var r=e.store.mailbox;if(r){var o,a=e.cfg.teamId;o=a?e.store.modules.team.getTeamsData()[a]:e.Store.getMetadata(null,null,(()=>{})).user,r.sendTo("SF_DELETED",{sfId:t,team:a,title:n},{curvePublic:o.curvePublic,channel:o.notifications},(e=>{console.error(e)}))}})(n,r,a),delete o[r],void(n.Store&&n.Store.refreshDriveUI&&n.Store.refreshDriveUI())}n.user.userObject.deprecateSharedFolder(r,a),c(n,r),n.Store&&n.Store.refreshDriveUI&&n.Store.refreshDriveUI()}},l=function(e,t){c(e,t),s(e,t,{proxy:{restricted:!0,root:{},filesData:{}}},(function(){})),e.Store.refreshDriveUI()},f=function(e,t){return Array.isArray(t)&&-1!==t.indexOf(e.edPublic)},d=function(e){var t=[e.user.userObject],n=Object.keys(e.folders).map((function(t){return e.folders[t].userObject}));return Array.prototype.push.apply(t,n),t},h=function(e,t){var n=d(e),r=e.user.userObject;return n.some((function(e){if(Object.keys(e.getFileData(t)).length)return r=e,!0})),r},p=function(e,t){var n=Number(t.id);if(n)return e.user.userObject.findFile(n)[0]},y=function(t,n,r){var o=[];return t.user.userObject.findChannels([n],!0).forEach((function(n){var a=t.user.proxy[e.SHARED_FOLDERS][n];a&&!r&&(a=JSON.parse(JSON.stringify(a))),a||(a=t.user.userObject.getFileData(n,r)),o.push({id:n,data:a,userObject:t.user.userObject})})),Object.keys(t.folders).forEach((function(e){t.folders[e].userObject.findChannels([n]).forEach((function(n){o.push({id:n,fId:e,data:t.folders[e].userObject.getFileData(n,r),userObject:t.folders[e].userObject})}))})),o},v=function(e,t){var n=[],r=e.user.userObject.getIdFromHref(t);return r&&n.push({data:e.user.userObject.getFileData(r),userObject:e.user.userObject}),Object.keys(e.folders).forEach((function(r){var o=e.folders[r].userObject.getIdFromHref(t);o&&n.push({fId:r,data:e.folders[r].userObject.getFileData(o),userObject:e.folders[r].userObject})})),n},m=function(e,t){var n=[],r=d(e);let o={};return r.forEach((function(e){var a=Number(e.id);let i;if(a){i=e.findFile(t);let n=(o[a]||[])[0];if(!n)return;i.forEach((function(e){Array.prototype.unshift.apply(e,n)}))}else{let n=[t],a=r.map((e=>+e.id)).filter(Boolean);Array.prototype.push.apply(n,a),o=e.findFiles(n),i=o[t]}Array.prototype.push.apply(n,i)})),n},g=function(e,t){var n={},r=d(e);let o={};return r.forEach((function(e){var a=Number(e.id);if(!e.id){let e=r.map((e=>+e.id)).filter(Boolean);Array.prototype.push.apply(t,e)}var i=e.findFiles(t);if(e.id||(o=i),a){let e=(o[a]||[])[0];if(!e)return;Object.keys(i).forEach((t=>{i[t].forEach((t=>{Array.prototype.unshift.apply(t,e)}))}))}Object.keys(i).forEach((e=>{n[e]||=[],Array.prototype.push.apply(n[e],i[e])}))})),n},E=function(e,n,r){if(r)return e.user.userObject.findChannels(n);var o=[];return d(e).forEach((function(e){var t=e.findChannels(n);Array.prototype.push.apply(o,t)})),o=t.deduplicateString(o)},b=function(e,t,n){var r=d(e),o={};return r.some((function(e){if((o=e.getFileData(t,n))&&Object.keys(o).length)return!0})),o},A=function(n,r){var o;if(n.isHistoryMode&&!n.folders[r])o=!0;else if(!n.folders[r])return{};var a=o?{}:n.folders[r].proxy;Object.keys(a.metadata||{}).length>1&&(a.metadata={title:a.metadata.title});var i=t.clone(a.metadata||{});for(var s in n.user.proxy[e.SHARED_FOLDERS][r]||{})if(void 0!==n.user.proxy[e.SHARED_FOLDERS][r][s]){var c=t.clone(n.user.proxy[e.SHARED_FOLDERS][r][s]);if("href"===s&&-1===c.indexOf("#"))try{c=n.user.userObject.cryptor.decrypt(c)}catch(e){}"href"===s&&-1===c.indexOf("#")&&(c=void 0),i[s]=c}return i},_=function(e,t){var n,r={id:null,userObject:e.user.userObject,path:t};if(!Array.isArray(t)||t.length<=1)return r;for(var o=e.user.userObject,a=2;a{r=t.Messages,e.setCustomize(t)},create:function(t,n,r){var o={pinPads:n.pin,unpinPads:n.unpin,onSync:n.onSync,Store:n.Store,store:n.store,removeOwnedChannel:n.removeOwnedChannel,loadSharedFolder:n.loadSharedFolder,cfg:r,edPublic:n.edPublic,settings:n.settings,user:{proxy:t},folders:{}};r.removeProxy=function(e){c(o,e)},o.user.userObject=e.init(t,r);var a=function(e){return function(){return[].unshift.call(arguments,o),e.apply(null,arguments)}};return{addProxy:a(s),removeProxy:a(c),deprecateProxy:a(u),restrictedProxy:a(l),addSharedFolder:a(x),addPin:function(e,t){o.pinPads=e,o.unpinPads=t},removePin:function(){delete o.pinPads,delete o.unpinPads},command:a(k),getPadAttribute:a(M),setPadAttribute:a(R),getTagsList:a(F),getSecureFilesList:a(L),getSharedFolderData:a(A),getChannelsList:a(K),addPad:a(j),delete:a(I),deleteOwned:a(N),findChannel:a(y),findHref:a(v),findFile:a(m),getEditHash:a(T),user:o.user,folders:o.folders}},createInner:function(t,n,r,o){var a={cfg:o,sframeChan:n,edPublic:r,user:{proxy:t,userObject:e.init(t,o)},folders:{}},i=function(e){return function(){return[].unshift.call(arguments,a),e.apply(null,arguments)}};return{addProxy:i(s),removeProxy:i(c),setHistoryMode:i(fe),rename:i(U),move:i(B),emptyTrash:i(V),addFolder:i(G),addSharedFolder:i(Y),addLink:i(J),restoreSharedFolder:i(q),convertFolderToSharedFolder:i(W),delete:i(Q),deleteOwned:i(z),restore:i(X),setFolderData:i(Z),updateStaticAccess:i($),getFileData:i(te),find:i(re),getTitle:i(oe),isReadOnlyFile:i(ie),isStaticFile:i(ae),getFiles:i(se),search:i(ce),getRecentPads:i(ue),getOwnedPads:i(le),getTagsList:i(F),findFile:i(m),findFiles:i(g),findChannels:i(ee),getSharedFolderData:i(A),getFolderData:i(de),isInSharedFolder:i(he),getUserObjectPath:i(ne),isDuplicateOwned:i(Te),ownedInTrash:i(Se),isValidDrive:i(pe),isFile:i(ye),isFolder:i(ve),isSharedFolder:i(me),isFolderEmpty:i(ge),isPathIn:i(Ee),isSubpath:i(be),isInTrashRoot:i(Ae),comparePath:i(_e),hasSubfolder:i(we),hasSubSharedFolder:i(Oe),hasFile:i(De),user:a.user,folders:a.folders}}}};e.exports&&(e.exports=t(Et(),Ne(),Fe(),void 0,nt(),Dt(),St()))})()}(ht)),ht.exports}var Ct,xt,It=Tt(),Nt=t({__proto__:null,default:r(It)},[It]),Pt=Et(),kt=t({__proto__:null,default:r(Pt)},[Pt]),Rt={exports:{}},Mt={exports:{}};function Ft(){return xt||(xt=1,function(e){e.exports&&(e.exports=((e={},t={},n)=>{let r=[];const o=["sheet","doc","presentation"],a=a=>{e=a.AppConfig;const i=(t=a.ApiConfig).onlyOffice&&t.onlyOffice.availableVersions.includes(n.currentVersion);r=e.availablePadTypes.filter((e=>i||!o.includes(e)))};Object.keys(e).length&&a({AppConfig:e,ApiConfig:t});const i={OO_APPS:o,setCustomize:a};return i.__defineGetter__("availableTypes",(function(){return t.appsToDisable?r.filter((e=>!t.appsToDisable.includes(e))):r})),i.__defineGetter__("appsToSelect",(function(){return r.filter((e=>!["drive","teams","file","contacts","convert"].includes(e)))})),i.isAvailable=e=>Array.isArray(i.availableTypes)&&i.availableTypes.includes(e),i})(void 0,void 0,(Ct||(Ct=1,function(e){e.exports&&(e.exports={currentVersionNumber:8,currentVersion:"v8"})}(Mt)),Mt.exports)))}(Rt)),Rt.exports}var Lt,Ht,Kt=Ft(),jt=t({__proto__:null,default:r(Kt)},[Kt]),Ut={exports:{}},Bt={exports:{}};function Vt(){return Lt||(Lt=1,function(e){(()=>{const t=(e,t,n={},r,o)=>{const a=function(){if(Object.keys(n).length){var e,t=new URL(n.httpUnsafeOrigin);try{return(e=new URL(n.websocketPath,n.httpUnsafeOrigin)).protocol=t.protocol,e.origin}catch(e){return console.error(e),n.httpUnsafeOrigin}}};var i=a();var s=e=>JSON.parse(JSON.stringify(e)),c=function(e,n,r){var o=t.once(t.mkAsync(r));fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}).then((e=>{e.ok?e.text().then((e=>{o(void 0,t.tryParse(e))})):e.json().then().then((t=>{o(e.status,t)}))})).catch((e=>{o(e)}))},u=function(n,r,a){var u=s(r);u.publicKey=t.encodeBase64(n.publicKey),u.nonce=t.encodeBase64(o.CryptoAgility.bytes(24));var l,f,d=new URL("/api/auth/",i);e((function(e){c(d,u,e(((t,n)=>t?(e.abort(),console.error(t),n&&console.error(n),void a(t)):n.date&&n.txid?(l=n.txid,void(f=n.date)):(e.abort(),void a("REQUEST_REJECTED")))))})).nThen((function(e){var r=s(u);r.txid=l,r.date=f;var i=t.decodeUTF8(JSON.stringify(r)),h=o.CryptoAgility.signDetached(i,n.secretKey),p=t.encodeBase64(h);c(d,{sig:p,txid:l},e(((t,n)=>{if(t)return e.abort(),console.error(t),n&&console.error(n),void a("RESPONSE_REJECTED",n);a(void 0,n)})))}))};return u.setCustomize=e=>{n=e.ApiConfig,i=a()},u};e.exports&&(e.exports=t(Dt(),Ne(),void 0,h(),ye()))})()}(Bt)),Bt.exports}function Gt(){return Ht||(Ht=1,function(e){e.exports&&(e.exports=((e,t={},n,r,o)=>{var a={setCustomize:e=>{t=e.ApiConfig,n.setCustomize(e)}};a.join=e.uint8ArrayJoin,a.seed=function(){return o.CryptoAgility.createHash(e.decodeUTF8("pewpewpew"))},a.genkeys=function(e){if(!(e instanceof Uint8Array))throw new Error("INVALID_SEED_FORMAT");if(!e||"number"!=typeof e.length||e.length<64)throw new Error("INVALID_SEED_LENGTH");var t=e.subarray(0,o.CryptoAgility.signSeedLength()),n=e.subarray(o.CryptoAgility.signSeedLength(),o.CryptoAgility.signSeedLength()+o.CryptoAgility.secretboxKeyLength()),a=o.CryptoAgility.signKeyPairFromSeed(t),i=null;if(o.PQC&&o.PQC.ml_dsa)try{var s=r.hash(e).subarray(0,32);i=o.CryptoAgility.generateDsaKeypair(s)}catch(e){console.error("Failed to generate post-quantum keys:",e),i=null}return{sign:a,pqSignPair:i,symmetric:n,hasPQ:null!==i}},a.keysToRPCFormat=function(t){try{var n=t.sign,r=t.pqSignPair;return{edPrivate:e.encodeBase64(n.secretKey),edPublic:e.encodeBase64(n.publicKey),dsaPrivate:e.encodeBase64(r.secretKey),dsaPublic:e.encodeBase64(r.publicKey)}}catch(e){return void console.error(e)}},a.encrypt=function(t,n,r){var i=e.decodeUTF8(n),s=o.CryptoAgility.bytes(o.CryptoAgility.secretboxNonceLength());return a.join([[0],s,o.CryptoAgility.secretbox(i,s,r.symmetric)])},a.decrypt=function(t,n){var r=o.CryptoAgility.secretboxNonceLength(),a=t.subarray(1,1+r),i=t.subarray(1+r),s=o.CryptoAgility.secretboxOpen(i,a,n.symmetric);try{return JSON.parse(e.encodeUTF8(s))}catch(e){return void console.error(e)}},a.sign=function(e,t){var n=o.CryptoAgility.createHash(e);if(t.hasPQ&&t.pqSignPair)try{var r=o.CryptoAgility.signDetached(n,t.sign.secretKey),a=o.PQC.ml_dsa.ml_dsa44.internal.sign(t.pqSignPair.secretKey,n);console.log("Hybrid signature created successfully:");var i=new Uint8Array(1+r.length+4+a.length);return i[0]=1,i.set(r,1),new DataView(i.buffer).setUint32(1+r.length,a.length,!1),i.set(a,1+r.length+4),i}catch(e){console.error("PQ signing failed, falling back to classical:",e)}r=o.CryptoAgility.signDetached(n,t.sign.secretKey);var s=new Uint8Array(r.length+1);return s[0]=0,s.set(r,1),s},a.serialize=function(t,n){var r=a.encrypt(0,t,n),o=a.sign(r,n);return{publicKey:e.encodeBase64(n.sign.publicKey),pqPublicKey:e.encodeBase64(n.pqSignPair.publicKey),signature:e.encodeBase64(o),ciphertext:e.encodeBase64(r)}},a.proveAncestor=function(t){var n=e.find(t,["sign","publicKey"]);try{let r=[n,a.sign(n,t)].map(e.encodeBase64);return t.pqSignPair&&t.pqSignPair.publicKey&&r.push(e.encodeBase64(t.pqSignPair.publicKey)),JSON.stringify(r)}catch(e){return void console.error(e)}};var i=function(t){return e.encodeBase64(t).replace(/\//g,"-")};a.getBlockUrl=function(e){var n=i(e.sign.publicKey);return(t.fileHost||t.httpUnsafeOrigin||window.location.origin)+"/block/"+n.slice(0,2)+"/"+n},a.getBlockHash=function(e){return a.getBlockUrl(e)+"#"+i(e.symmetric)};var s=function(t){try{return e.decodeBase64(t.replace(/\-/g,"/"))}catch(e){return void console.error(e)}};return a.parseBlockHash=function(e){if("string"==typeof e){var t=e.split("#");if(2===t.length)try{return{href:t[0],keys:{symmetric:s(t[1])}}}catch(e){return void console.error(e)}}},a.checkRights=function(t,r){const o=e.mkAsync(r),{blockKeys:a,auth:i}=t;var s="MFA_CHECK";i&&i.type&&(s=`${i.type.toUpperCase()}_`+s),n(a.sign,{command:s,auth:i&&i.data},o)},a.writeLoginBlock=function(e,t){const{content:r,blockKeys:o,oldBlockKeys:i,auth:s,pw:c,session:u,token:l,userData:f}=e;var d="WRITE_BLOCK";s&&s.type&&(d=`${s.type.toUpperCase()}_`+d);var h=a.serialize(JSON.stringify(r),o);h.auth=s&&s.data,h.hasPassword=c,h.registrationProof=i&&a.proveAncestor(i),l&&(h.inviteToken=l),f&&(h.userData=f),n(o.sign,{command:d,content:h,session:u},t)},a.removeLoginBlock=function(e,t){const{reason:r,blockKeys:o,auth:a,edPublic:i}=e;var s="REMOVE_BLOCK";a&&a.type&&(s=`${a.type.toUpperCase()}_`+s),n(o.sign,{command:s,auth:a&&a.data,edPublic:i,reason:r},t)},a.updateSSOBlock=function(e,t){const{blockKeys:r,oldBlockKeys:o}=e;var i=o&&a.proveAncestor(o);n(r.sign,{command:"SSO_UPDATE_BLOCK",ancestorProof:i},t)},a})(Ne(),void 0,Vt(),h(),ye()))}(Ut)),Ut.exports}var Yt,Jt,qt,Wt=Gt(),Qt=t({__proto__:null,default:r(Wt)},[Wt]),zt={exports:{}};function Xt(){return Yt||(Yt=1,function(e){var t;t=function(){var e=function(t){if(Array.isArray(t))return t.map(e);if(t instanceof Object){var n=[],r=[];return Object.keys(t).forEach((function(e){/^(0|[1-9][0-9]*)$/.test(e)?n.push(+e):r.push(e)})),n.sort((function(e,t){return e-t})).concat(r.sort()).reduce((function(n,r){return n[r]=e(t[r]),n}),{})}return t},t=JSON.stringify.bind(JSON);return function(n,r,o){var a=t(n,r,0);if(!a||"{"!==a[0]&&"["!==a[0])return a;var i=JSON.parse(a);return t(e(i),null,o)}},e.exports?e.exports=t():JSON.sortify=t()}(zt)),zt.exports}function Zt(){if(qt)return Jt;qt=1;var e,t,n,r,o,a,i,s;return ye(),e=Fe(),t=Ne(),Oe(),n=mt(),o=(r={}).createData=function(n,r){var o={channel:r||e.createChannelId(),displayName:n["cryptpad.username"],profile:n.profile&&n.profile.view,edPublic:n.edPublic,curvePublic:n.curvePublic,dsaPublic:n.dsaPublic,kemPublic:n.kemPublic,notifications:t.find(n,["mailboxes","notifications","channel"]),avatar:n.profile&&n.profile.avatar,badge:n.profile&&n.profile.badge,uid:n.uid};return!1===r&&delete o.channel,o},a=r.getFriend=function(e,t){if(t){if(t===e.curvePublic){var n=o(e);return delete n.channel,n}return e.friends?e.friends[t]:void 0}},i=r.getFriendList=function(e){return e.friends||(e.friends={}),e.friends},s=function(e,t){Object.keys(e).forEach((function(n){"me"!==n&&t(e[n],n,e)}))},r.getFriendChannelsList=function(e){var t=[];return s(e.friends,(function(e){t.push(e.channel)})),t},r.declineFriendRequest=function(e,t,n){e.mailbox.sendTo("DECLINE_FRIEND_REQUEST",{},{channel:t.notifications,curvePublic:t.curvePublic},(function(e){n(e)}))},r.acceptFriendRequest=function(e,t,n){var r=a(e.proxy,t.curvePublic)||{},i=o(e.proxy,r.channel||t.channel);e.mailbox.sendTo("ACCEPT_FRIEND_REQUEST",{user:i},{channel:t.notifications,curvePublic:t.curvePublic},(function(e){n(e)}))},r.addToFriendList=function(e,t,r){var o=e.proxy,a=i(o),s=t.curvePublic;s!==o.curvePublic?(a[s]=t,n.whenRealtimeSyncs(e.realtime,(function(){r(),e.pinPads([t.channel],(function(e){e.error&&console.error(e.error)}))}))):r("E_MYKEY")},r.updateMyData=function(e,n){var r=o(e.proxy,!1);e.proxy.friends&&(e.proxy.friends.me=t.clone(r),delete e.proxy.friends.me.channel),e.modules.team&&e.modules.team.updateMyData(r);var i=function(t){t&&t.notifications&&(delete t.user,r.channel=t.channel,e.mailbox.sendTo("UPDATE_DATA",r,{channel:t.notifications,curvePublic:t.curvePublic},(function(e){e&&e.error&&console.error(e)})))};n?i(a(e.proxy,n)):s(e.proxy.friends||{},i)},r.removeFriend=function(e,t,r){var o=e.proxy,a=o.friends[t];a?a.notifications?e.mailbox.sendTo("UNFRIEND",{curvePublic:o.curvePublic},{channel:a.notifications,curvePublic:a.curvePublic},(function(i){i&&i.error?r(i):(e.messenger.onFriendRemoved(t,a.channel),delete o.friends[t],n.whenRealtimeSyncs(e.realtime,(function(){r(i)})))})):r({error:"EINVAL"}):r({error:"ENOENT"})},Jt=r}var $t,en,tn,nn={exports:{}},rn={exports:{}},on={exports:{}};function an(){return $t||($t=1,function(e){var t,n,r,o,a,i,s,c,u,l,f,d;e.exports&&(e.exports=(t=Ne(),h(),n=ye(),r=t.uid,o=t.tryParse,a=function(e,r){var o=t.decodeUTF8(JSON.stringify(e));return t.encodeBase64(n.CryptoAgility.signDetached(o,r))},i=function(e,t,n){if("function"!=typeof n)throw new Error("expected callback");var o=e.network,a=o.historyKeeper;if("string"==typeof a){var i=r(),s=e.pending[i]=function(e,t){n(e,t)};return s.data=t,s.called=0,o.sendto(a,JSON.stringify([i,t]))}n("NO_HISTORY_KEEPER")},s=[],c=[],u=function(e){var t={network:e,connected:!0,anon:void 0,authenticated:[]};return s.push(e),c.push(t),e.on("message",(function(n,r){r===e.historyKeeper&&function(e,t){"string"!=typeof t&&console.error("received non-string message [%s]",t);var n=o(t);if(n){if(Array.isArray(n)&&!/(FULL_HISTORY|HISTORY_RANGE)/.test(n[0])){var r=n[0];"string"==typeof r&&(function(e,t){return!!e.anon&&"function"==typeof e.anon.pending[t]}(e,r)?function(e,t,n){var r=e.pending[t];"ERROR"===n[0]?r(n[1]):r(void 0,n.slice(1)),delete e.pending[t]}(e.anon,r,n.slice(1)):e.authenticated.some((function(e){var t=e.pending[r];return"function"==typeof t&&("ERROR"!==n[1]?(/\|/.test(n[1])&&e.cookie!==n[1]&&(e.cookie=n[1]),t(void 0,n.slice(2)),delete e.pending[r],!0):"NO_COOKIE"===n[2]?(e.send("COOKIE","",(function(n){if(n)return console.error(n),void t(n);e.resend(r)&&delete e.pending[r]})),!0):(t(n[2]),delete e.pending[r],!0))}))||console.error("UNHANDLED RPC MESSAGE",t))}}else console.error(new Error("could not parse message: %s",t))}(t,n)})),e.on("disconnect",(function(){t.connected=!1,t.anon&&(t.anon.connected=!1),t.authenticated.forEach((function(e){e.connected=!1}))})),e.on("reconnect",(function(){t.anon&&(t.anon.connected=!0),t.authenticated.forEach((function(e){e.connected=!0}))})),t},l=function(e){var t;return s.some((function(n,r){return e===n&&(t=r,!0)})),c[t]?c[t]:u(e)},f=function(e,n){if(!e)throw new Error("expected network context");var o,s=n.publicKeyString;return e.authenticated.some((function(e,t){return e.publicKey===s&&(o=t,!0)})),e.authenticated[o]?e.authenticated[o]:function(e,n){var o={network:e.network,publicKey:n.publicKeyString,timeouts:{},pending:{},cookie:null,connected:!0},s=o.send=function(e,r,s){var c=t.mkAsync(s);if(o.connected||"COOKIE"===e){var u=[e,r];o.cookie&&o.cookie.join?u.unshift(o.cookie.join("|")):u.unshift(o.cookie);var l=a(u,n.signKey);return u.unshift(n.publicKeyString),u.unshift(l),i(o,u,c)}c("DISCONNECTED")};return o.resend=function(e){var t=o.pending[e];if(t.called)return console.error("[%s] called too many times",e),!0;t.called++,t.data[2]=o.cookie,t.data[0]=a(t.data.slice(2),n.signKey);var i=r();o.pending[i]=t,delete o.pending[e];try{return o.network.sendto(o.network.historyKeeper,JSON.stringify([i,t.data]))}catch(e){console.log("failed to resend"),console.error(e)}},s.unauthenticated=function(e,r,a){var s=t.mkAsync(a);if(o.connected){var c=[null,n.publicKeyString,null,e,r];return o.cookie&&o.cookie.join?c[2]=o.cookie.join("|"):c[2]=o.cookie,i(o,c,s)}s("DISCONNECTED")},o.destroy=function(){Object.keys(o.timeouts).forEach((function(e){clearTimeout(e)})),o.send("DESTROY","",(function(){}));var t=e.authenticated.indexOf(o);-1!==t&&e.authenticated.splice(t,1)},e.authenticated.push(o),o}(e,n)},d=function(e){return e.anon||function(e){var n={network:e.network,timeouts:{},pending:{},connected:!0};return e.anon=n,n.send=function(e,r,o){var a=t.mkAsync(o);if(n.connected)return i(n,[e,r],a);a("DISCONNECTED")},n.resend=function(e){var t=n.pending[e];if(t.called)return console.error("[%s] called too many times",e),!0;t.called++;try{return n.network.sendto(n.network.historyKeeper,JSON.stringify([e,t.data]))}catch(e){console.log("failed to resend"),console.error(e)}},n.destroy=function(){Object.keys(n.timeouts).forEach((function(e){clearTimeout(e)})),e.anon=void 0},n}(e)},{create:function(e,n,r,o){if("function"!=typeof o)throw new Error("expected callback");var a,i=t.mkAsync(o);try{if(64!==(a=t.decodeBase64(n)).length)throw new Error("private key did not match expected length of 64")}catch(e){return void i(e)}try{if(32!==t.decodeBase64(r).length)return void i("expected public key to be 32 uint")}catch(e){return void i(e)}if(e){var s=l(e),c=f(s,{publicKeyString:r,signKey:a});c.send("COOKIE","",(function(e){e?i(e):i(void 0,{send:c.send,destroy:c.destroy})}))}else i("NO_NETWORK")},createAnonymous:function(e,n){var r=t.mkAsync(n);if("function"!=typeof r)throw new Error("expected callback");if(e){var o=d(l(e));r(void 0,{send:o.send,destroy:o.destroy})}else r("NO_NETWORK")}}))}(on)),on.exports}function sn(){return en||(en=1,function(e){var t,n;e.exports&&(e.exports=(t=Ne(),n=an(),{create:function(e,r,o,a){if("function"!=typeof o)throw new Error("Expected callback");var i=t.once(t.mkAsync(o));if(e)if(r){var s=r.edPrivate,c=r.edPublic;s&&c?n.create(e,s,c,(function(e,n){if(e)i(e);else{var r={};r.destroy=n.destroy,r.publicKey=c,r.send=n.send,r.pin=function(e,r){var o=t.once(t.mkAsync(r));Array.isArray(e)?n.send("PIN",e,o):o("[TypeError] pin expects an array")},r.unpin=function(e,r){var o=t.once(t.mkAsync(r));Array.isArray(e)?n.send("UNPIN",e,o):o("[TypeError] pin expects an array")},r.adminRpc=function(e,t){if(e.cmd){var r=[e.cmd,e.data];n.send("ADMIN",r,t)}else setTimeout((function(){t("[TypeError] admin rpc expects a command")}))},r.getServerHash=function(e){n.send("GET_HASH",c,(function(t,n){n&&n[0]?e(t,Array.isArray(n)&&n[0]||void 0):e("NO_HASH_RETURNED")}))},r.reset=function(e,r){var o=t.once(t.mkAsync(r));Array.isArray(e)?n.send("RESET",e,o):o("[TypeError] pin expects an array")},r.getFileListSize=function(e){n.send("GET_TOTAL_SIZE",void 0,(function(t,n){t?e(t):n&&n.length&&"number"==typeof n[0]?e(void 0,n[0]):e("INVALID_RESPONSE")}))},r.updatePinLimits=function(e){n.send("UPDATE_LIMITS",void 0,(function(t,n){t?e(t):n&&n.length&&"number"==typeof n[0]?e(void 0,n[0],n[1],n[2]):e("INVALID_RESPONSE")}))},r.getLimit=function(e){n.send("GET_LIMIT",void 0,(function(t,n){t?e(t):n&&n.length&&"number"==typeof n[0]?e(void 0,n[0],n[1],n[2]):e("INVALID_RESPONSE")}))},r.trimHistory=function(e,r){var o=t.once(t.mkAsync(r));"object"==typeof e&&e.channel&&e.hash?n.send("TRIM_HISTORY",e,(function(e){if(e)return o(e);o()})):o("INVALID_ARGUMENTS")},r.clearOwnedChannel=function(e,t){"string"==typeof e&&32===e.length?n.send("CLEAR_OWNED_CHANNEL",e,(function(e){if(e)return t(e);t()})):t("INVALID_ARGUMENTS")},r.removeOwnedChannel=function(e,t,r){if("string"!=typeof e||-1===[32,48].indexOf(e.length))return console.error("invalid channel to remove",e),void t("INVALID_ARGUMENTS");n.send("REMOVE_OWNED_CHANNEL",{channel:e,reason:r},(function(n,r){n?t(n):r&&r.length&&"OK"===r[0]?(t(),a&&a.clearChannel&&a.clearChannel(e)):t("INVALID_RESPONSE")}))},r.removePins=function(e){n.send("REMOVE_PINS",void 0,(function(t,n){t?e(t):n&&n.length&&"OK"===n[0]?e():e("INVALID_RESPONSE")}))},r.uploadComplete=function(e,t){n.send("UPLOAD_COMPLETE",e,(function(e,n){if(e)t(e);else{var r=n[0];"string"==typeof r?t(void 0,r):t("INVALID_ID")}}))},r.ownedUploadComplete=function(e,t){n.send("OWNED_UPLOAD_COMPLETE",e,(function(e,n){if(e)t(e);else{var r=n[0];"string"==typeof r?t(void 0,r):t("INVALID_ID")}}))},r.uploadStatus=function(e,t){"number"==typeof e?n.send("UPLOAD_STATUS",e,(function(e,n){if(e)t(e);else{var r=n[0];"boolean"==typeof r?t(void 0,r):t("INVALID_RESPONSE")}})):setTimeout((function(){t("INVALID_SIZE")}))},r.uploadCancel=function(e,t){n.send("UPLOAD_CANCEL",e,(function(e){e?t(e):t()}))},r.setMetadata=function(e,t){n.send("SET_METADATA",{channel:e.channel,command:e.command,value:e.value},t)},i(e,r)}})):i("INVALID_KEYS")}else i("INVALID_PROXY");else i("INVALID_NETWORK")}}))}(rn)),rn.exports}function cn(){return tn||(tn=1,function(e){(()=>{const t=(e,t,n,r,o,a,i,s,c,u)=>{var l=function(e,t,n){if(!e.done){if(e.cb(t&&t.error,n,t),e.done=!0,!e.hasNetwork){var o=r.find(e,["network","disconnect"]);"function"==typeof o&&o()}if(e.realtime&&e.realtime.stop)try{e.realtime.stop()}catch(e){console.error(e)}var a=r.find(e,["session","realtime","abort"]);"function"==typeof a&&(e.session.realtime.sync(),a())}},f=function(e,r){u((function(t){var o,a;e.hasNetwork||(o=t((function(e,t){e||(r.network=t)})),a=i.getWebsocketURL(),n.connect(a).then((function(e){o(null,e)}),(function(e){o(e)})))})).nThen((function(){e.realtime=t.start(r)}))},d=function(e,t,n,r){Array.isArray(n)&&n.length&&16===n[0].length&&Array.isArray(t.accessKeys)?(e.network.historyKeeper=n[0],u((function(n){t.accessKeys.forEach((function(t){c.create(e.network,t,n((function(e){console.log("done",t),e&&console.error(e)})))}))})).nThen((function(){r()}))):r(!0)},h=function(t,n){var r;return"string"==typeof t?r=o.getSecrets("pad",t,n.password):"object"==typeof t&&(r=t),r.keys||(r.keys=r.key),{websocketURL:i.getWebsocketURL(n.origin),channel:r.channel,validateKey:r.keys.validateKey||void 0,crypto:e.createEncryptor(r.keys),logLevel:0,initialState:n.initialState,Cache:s}},p=function(e){return"object"==typeof e},y=function(e,t){p(e)&&p(t)&&Object.keys(t).forEach((function(n){e[n]=t[n]}))};return{get:function(e,t,n,r){if("function"!=typeof t)throw new Error("Cryptget expects a callback");r=r||function(){};var o=h(e,n=n||{}),a={cb:t,accessKeys:n.accessKeys,hasNetwork:Boolean(n.network)};o.onRejected=function(e,t){d(o,a,e,t)},o.onReady=function(e){var t=a.session=e.realtime;a.network=e.network,r(1),l(a,void 0,t.getUserDoc())},o.onError=function(e){console.warn(e),l(a,e)},o.onChannelError=function(e){console.error(e),l(a,e)},o.onCacheReady=n.onCacheReady;var i=0;o.onMessage=function(){i++,r(Math.min(.99,i/100))},y(o,n),f(a,o)},put:function(e,t,n,r){if("function"!=typeof n)throw new Error("Cryptput expects a callback");var o=h(e,r=r||{}),i={cb:n,accessKeys:r.accessKeys,hasNetwork:Boolean(r.network)};o.onRejected=function(e,t){d(o,i,e,t)},o.onReady=function(e){var r=i.session=e.realtime;i.network=e.network,r.contentUpdate(t);var o=setTimeout((function(){n(new Error("Timeout"))}),15e3);a.whenRealtimeSyncs(r,(function(){clearTimeout(o);var e=r.getAuthDoc();r.abort(),l(i,void 0,e)}))},o.onChannelError=function(e){l(i,e)},y(o,r),f(i,o)}}};e.exports&&(e.exports=t(ye(),O(),u(),Ne(),Fe(),mt(),Ee(),Ge(),sn(),Dt(),I()))})()}(nn)),nn.exports}var un,ln,fn,dn,hn,pn,yn,vn={exports:{}};function mn(){if(hn)return dn;hn=1;return dn=((e,t,n,r,o,a,i,s)=>{const c={};let u={};c.setCustomize=e=>{u=e.Broadcast};var l=["notifications","supportteam","broadcast"],f=[],d="000000000000000000000000000000000",h=function(e,t,n,r,o){e.emit("MESSAGE",{type:t,content:n},r?[r]:e.clients,o)},p=function(e,t,n,r){e.emit("VIEWED",{type:t,hash:n},r||e.clients)},y=function(e){var t=e.store&&e.store.proxy;if(t.curvePrivate&&t.curvePublic&&t.kemPublic&&t.kemPrivate)return{curvePrivate:t.curvePrivate,curvePublic:t.curvePublic,kemPrivate:t.kemPrivate,kemPublic:t.kemPublic}},v=c.sendTo=function(t,n,o,a,i){a=a||{};var c=i||function(e){e&&e.error&&console.error(e.error)};if(s.Mailbox){var u=e.find(t,["store","anon_rpc"]);if(u){var l={encrypt:function(e){return e}},f=d,h={uid:e.uid(),type:n,content:o};if(!/^BROADCAST/.test(n)){var p=y(t);if(!p)return void c({error:"missing asymmetric encryption keys"});if(!a||!a.channel||!a.curvePublic)return void c({error:"no notification channel"});if(f=a.channel,l=s.Mailbox.createEncryptor(p),"object"==typeof o&&!o.user){var v=r.createData(t.store.proxy,!1);o.user=v}h={type:n,content:o}}var m=JSON.stringify(h),g=l.encrypt(m,a.curvePublic,a.kemPublic);if(a.viewed){var E=e.find(t,["store","proxy","teams",a.viewed]);if(E){var b=g.slice(0,64),A=e.find(E,["keys","mailbox","viewed"]);Array.isArray(A)&&A.push(b)}}u.send("WRITE_PRIVATE_MESSAGE",[f,g],(function(e){c(e?{error:e}:{hash:g.slice(0,64)})}))}else c({error:"anonymous rpc session not ready"})}else c({error:"chainpad-crypto is outdated and doesn't support mailboxes."})};c.sendToAnon=function(t,n,r,o,a){var i,c,u=s.CryptoAgility.bytes(32),l=s.CryptoAgility.boxKeyPairFromSecretKey(new Uint8Array(u)),f=e.encodeBase64(l.secretKey),d=e.encodeBase64(l.publicKey);if(s.PQC&&s.PQC.ml_kem&&s.PQC.ml_kem.ml_kem512)try{var h=s.CryptoAgility.bytes(64),p=s.PQC.ml_kem.ml_kem512.keygen(new Uint8Array(h));i=e.encodeBase64(p.secretKey),c=e.encodeBase64(p.publicKey)}catch(e){console.warn("Failed to generate ephemeral PQC keys:",e)}v({store:{anon_rpc:t,proxy:{curvePrivate:f,curvePublic:d,kemPrivate:i,kemPublic:c}}},n,r,o,a)};var m=function(t,r,o,i){var s=r.type,c=r.hash;if(/^REMINDER\|/.test(c)){i(),delete t.boxes.reminders.content[c],p(t,s,c,t.clients.filter((function(e){return e!==o})));var u=c.slice(9).split("-")[0],l=e.find(t,["store","proxy","hideReminders",u]);if(!l){var f=t.store.proxy.hideReminders=t.store.proxy.hideReminders||{};l=f[u]=f[u]||[]}var d=c.split("-")[1];d&&!l.includes(d)&&l.push(Number(d))}else{var h=t.boxes[s];if(h){var y,v,m=h.data||{},g=h.history.indexOf(c);-1!==g&&(0===g?(m.lastKnownHash=c,h.history.shift()):-1===m.viewed.indexOf(c)&&m.viewed.push(c));var E=[];h.history.some((function(e,t){if(-1===m.viewed.indexOf(e))return!0;y=t+1,E.push(e),v=e})),m.viewed=m.viewed.filter((function(e){return-1===E.indexOf(e)})),y&&(h.history=h.history.slice(y),m.lastKnownHash=v),Object.keys(h.content).forEach((function(e){-1!==h.history.indexOf(e)&&-1===m.viewed.indexOf(e)||(a.remove(t,h,h.content[e],e),delete h.content[e])})),n.whenRealtimeSyncs(t.store.realtime,(function(){i(),p(t,s,c,t.clients.filter((function(e){return e!==o})))}))}else i({error:"NOT_LOADED"})}},g=function(e,t,n,c,u){u=u||{};var l=e.boxes[t]={channel:n.channel,type:t,queue:[],history:[],content:{},sendMessage:function(t){if("object"==typeof t&&!t.user){var n=r.createData(e.store.proxy,!1);t.user=n}try{t=JSON.stringify(t)}catch(e){console.error(e)}l.queue.push(t)},data:n};if(s.Mailbox){var f=n.keys||y(e);if(f||n.decrypted){var d=n.decrypted?{encrypt:function(e){return e},decrypt:function(e){return e}}:s.Mailbox.createEncryptor(f);l.encryptor=d;var v,g={network:e.store.network,channel:n.channel,noChainPad:!0,crypto:d,owners:"broadcast"===t?[]:u.owners||[e.store.proxy.edPublic],lastKnownHash:n.lastKnownHash};g.onConnectionChange=function(){},g.onConnect=function(n,r){l.sendMessage=function(n,o){var a;o=o||function(){};try{a=JSON.stringify(n)}catch(e){console.error(e)}r(a,(function(r,a){r?console.error(r):(l.history.push(a),n.ctime=+new Date,l.content[a]=n,h(e,t,{msg:n,hash:a}),o(a))}),f.curvePublic)},l.queue.forEach((function(e){l.sendMessage(e)})),l.queue=[]},l.onMessage=g.onMessage=function(r,i,s,c,f,d,p){if(f!==n.lastKnownHash&&f!==v){var y=p&&p.time;v=f;try{r=JSON.parse(r)}catch(e){console.error(e)}if(d&&(r.author=d),l.history.push(f),function(e,t){return-1===(t.viewed||[]).indexOf(e)&&e!==t.lastKnownHash}(f,n)){var g={msg:r,hash:f,time:y},E=l.ready;a.add(e,l,g,(function(n,a,i){a&&m(e,a,"",(function(){console.log("Notification handled automatically")})),i||n?m(e,{type:t,hash:f},"",(function(){console.log("Notification handled automatically")})):(r.ctime=y||0,l.content[f]=r,u.dump||h(e,t,g,null,(function(e){e&&e.msg&&E&&o.system(void 0,e.msg)})))}))}else if(0===Object.keys(l.content).length){n.lastKnownHash=f,l.history=[];var b=n.viewed.indexOf(f);-1!==b&&n.viewed.splice(b,1)}}},g.onReady=function(){var r=[];n.viewed.forEach((function(e,t){-1===l.history.indexOf(e)&&r.push(t)}));for(var o=r.length-1;o>=0;o--)n.viewed.splice(r[o],1);var i=function(n){a.remove(e,l,l.content[n],n),delete l.content[n],p(e,t,n)};e.store.proxy.on("change",["mailboxes",t],(function(e,t,n){var r;"lastKnownHash"===n[2]&&(l.history.some((function(e,n){if(r=n+1,i(e),e===t)return!0})),l.history=l.history.slice(r));"viewed"===n[2]&&i(t)})),l.ready=!0,c(l.content)},l.cpNf=i.start(g)}else console.error("missing asymmetric encryption keys")}else console.error("chainpad-crypto is outdated and doesn't support mailboxes.")};return c.init=function(n,r,i){var s={},c=n.store,y=c.proxy.mailboxes=c.proxy.mailboxes||{},E={Store:n.Store,store:c,pinPads:n.pinPads,updateMetadata:n.updateMetadata,updateDrive:n.updateDrive,mailboxes:y,emit:i,clients:[],boxes:{},req:{},loggedIn:c.loggedIn&&c.proxy.edPublic};return function(e,n){!n.notifications&&e.loggedIn&&(n.notifications={channel:t.createChannelId(),lastKnownHash:"",viewed:[]},e.pinPads([n.notifications.channel],(function(e){e.error&&console.error(e)}))),n.support&&delete n.support,n.broadcast||(n.broadcast={channel:d,lastKnownHash:u.lastBroadcastHash,decrypted:!0,viewed:[]})}(E,y),E.loggedIn&&function(t){var n=t.store.network;n.on("message",(function(r,o){if(o===n.historyKeeper){var a=JSON.parse(r);if(/HISTORY_RANGE/.test(a[0])){var i=a[1],s=t.req[i];if(s){var c=a[0],u=a[2],l=s.box;if("HISTORY_RANGE"===c){if(!Array.isArray(u))return;var f;if("broadcast"===s.box.type)f=e.tryParse(u[4]);else try{var d=l.encryptor.decrypt(u[4]);(f=JSON.parse(d.content)).author=d.author}catch(e){console.log(e)}var h=u[4].slice(0,64);t.emit("HISTORY",{txid:i,time:u[5],message:f,hash:h},[s.cId])}else"HISTORY_RANGE_END"===c&&(t.emit("HISTORY",{txid:i,complete:!0},[s.cId]),delete t.req[i])}}}}))}(E),E.boxes.reminders={content:{}},Object.keys(y).forEach((function(e){if(-1!==l.indexOf(e)){var t=y[e];-1===f.indexOf(e)?g(E,e,t,(function(){})):g(E,e,t,r((function(){})))}})),E.loggedIn&&Object.keys(c.proxy.teams||{}).forEach((function(t){var n=c.proxy.teams[t];if(n){var r=n.keys.mailbox||{};if(r.channel){var o={owners:[e.find(n,["keys","drive","edPublic"])]};g(E,"team-"+t,r,(function(){}),o)}}})),s.post=function(e,t,n){var r=E.boxes[e];r&&r.sendMessage({type:t,content:n,sender:c.proxy.curvePublic})},s.hideMessage=function(e,t){p(E,e,t.hash,E.clients)},s.showMessage=function(e,t,n,r){"reminders"===e&&t&&(E.boxes.reminders.content[t.hash]=t.msg,E.clients.length||(E.boxes.reminders.content[t.hash].requiresNotif=!0),p(E,e,t.hash,E.clients)),h(E,e,t,n,(function(e){o.system(void 0,e.msg),r&&r()}))},s.open=function(e,t,n,r,o){(-1!==l.indexOf(e)||r)&&g(E,e,t,n,o)},s.close=function(e,t){!function(e,t,n){n=n||function(){};var r=e.boxes[t];r?r.cpNf&&"function"==typeof r.cpNf.stop?(r.cpNf.stop(),Object.keys(r.content).forEach((function(n){a.remove(e,r,r.content[n],n),p(e,t,n,e.clients)})),delete e.boxes[t]):n("EINVAL"):n()}(E,e,t)},s.dismiss=function(e,t){m(E,e,"",t)},s.sendTo=function(e,t,n,r){E.loggedIn?v(E,e,t,n,r):r({error:"NOT_LOGGED_IN"})},s.removeClient=function(e){!function(e,t){var n=e.clients.indexOf(t);e.clients.splice(n,1)}(E,e)},s.execCommand=function(e,t,n){var r=t.cmd,a=t.data;"SUBSCRIBE"!==r?"DISMISS"!==r?"SENDTO"!==r?"LOAD_HISTORY"!==r||function(e,t,n,r){var o=e.boxes[n.type];if(o){var a=["GET_HISTORY_RANGE",o.channel,{from:n.lastKnownHash,count:n.count,txid:n.txid}];"broadcast"===n.type&&(a=["GET_HISTORY_RANGE",o.channel,{to:n.lastKnownHash,txid:n.txid}]),e.req[n.txid]={cId:t,box:o};var i=e.store.network;i.sendto(i.historyKeeper,JSON.stringify(a)).then((function(){}),(function(e){console.error(e)}))}else r({error:"ENOENT"})}(E,e,a,n):v(E,a.type,a.msg,a.user,n):m(E,a,e,n):function(e,t,n,r){Object.keys(e.boxes).forEach((function(t){Object.keys(e.boxes[t].content).forEach((function(r){var a={msg:e.boxes[t].content[r],hash:r};h(e,t,a,n,(function(e){e.error||a.msg&&a.msg.requiresNotif&&(o.system(void 0,e.msg),delete a.msg.requiresNotif)}))}))})),-1===e.clients.indexOf(n)&&e.clients.push(n),r()}(E,0,e,n)},s},c})(Ne(),Fe(),mt(),Zt(),(un||(un=1,function(e){(()=>{const t=(e={})=>{let t=globalThis;var n={};e.requireConf=e.requireConf||{},n.setCustomize=t=>{e=t.ApiConfig};var r=t.location&&t.location.pathname.slice(1,-1),o=-1!==["code","slide","pad","kanban","whiteboard","diagram","sheet","poll","teams","form","doc","presentation"].indexOf(r)?"-"+r:"",a="/customize/favicon/main-favicon"+o+".png?"+e.requireConf.urlArgs,i="/customize/favicon/alt-favicon"+o+".png?"+e.requireConf.urlArgs,s="/customize/favicon/main-favicon"+o+".ico?"+e.requireConf.urlArgs,c="/customize/favicon/alt-favicon"+o+".ico?"+e.requireConf.urlArgs,u=t.document,l=n.isSupported=function(){return"function"==typeof t.Notification&&t.isSecureContext},f=n.hasPermission=function(){return"granted"===Notification.permission},d=n.getPermission=function(e){e=e||function(){},Notification&&"function"==typeof Notification.requestPermission?Notification.requestPermission((function(t){e("granted"===t)})):e(!1)},h=n.create=function(e,n,r){u&&!r?r=u.getElementById("favicon").getAttribute("data-main-favicon")||i:r||(r=i);var o=new Notification(n,{icon:r,body:e});return o.onclick=function(){if(u)try{parent.focus(),t.focus(),this.close()}catch(e){}},o};return n.system=function(e,t,n){if(l())return f()?h(e,t,n):void("denied"!==Notification.permission&&d((function(r){r&&h(e,t,n)})))},u&&!u.getElementById("favicon")&&function(){if(u){console.debug("creating favicon");var e={id:"favicon",type:"image/png",rel:"icon","data-main-favicon":a,"data-alt-favicon":i,href:a};if(!u.getElementById("favicon")){var t=u.createElement("link");Object.keys(e).forEach((function(n){t.setAttribute(n,e[n])})),u.head.appendChild(t)}if(!u.getElementById("favicon-ico")){var n=u.createElement("link");e.href=e.href.replace(/\.png/g,".ico"),e.id="favicon-ico",e.type="image/x-icon",Object.keys(e).forEach((function(t){n.setAttribute(t,e[t])})),u.head.appendChild(n)}}else console.error("document is not available in this context")}(),n.tab=function(e,r){if(u){var o="_pendingTabNotification",l=u.getElementById("favicon"),f=u.getElementById("favicon-ico"),d=a,h=i,p=s,y=c;l&&(d=l.getAttribute("data-main-favicon")||a,h=l.getAttribute("data-alt-favicon")||i,l.setAttribute("href",d)),f&&(p=f.getAttribute("data-main-favicon")||s,y=f.getAttribute("data-alt-favicon")||c,f.setAttribute("href",p));var v=function(e){return!!n[o]&&(t.clearInterval(n[o]),l&&l.setAttribute("href",e?h:d),f&&f.setAttribute("href",e?y:p),!0)};v();var m=function(){l&&l.setAttribute("href",l.getAttribute("href")===d?h:d),f&&f.setAttribute("href",f.getAttribute("href")===p?y:p),--r};return n[o]=t.setInterval((function(){if(r>0)return m();v(!0)}),e),m(),{cancel:v}}console.error("document is not available in this context")},n};e.exports&&(e.exports=t(void 0))})()}(vn)),vn.exports),(fn||(fn=1,ln=((e,t,n,r,o)=>{var a=function(e){var t=e.store.realtime.getLag().lag||0;return 20*(Math.max(0,t)+300)*(.5+Math.random())},i={},s={},c=function(e,t){var r=e.store.proxy.mutedUsers||{},o=n.find(t,["msg","author"]);return!!o&&Boolean(r[o])},u={};i.FRIEND_REQUEST=function(t,n,r,o){var a=r.msg.content.user||r.msg.content;if(c(t,r))o(!0);else if(u[r.msg.author])o(!0);else{if(u[r.msg.author]={type:n.type,hash:r.hash},e.getFriend(t.store.proxy,r.msg.author)||t.store.proxy.friends_pending[r.msg.author])return delete t.store.proxy.friends_pending[r.msg.author],void e.acceptFriendRequest(t.store,a,(function(n){n&&n.error?o():e.addToFriendList({proxy:t.store.proxy,realtime:t.store.realtime,pinPads:t.pinPads},a,(function(e){if(e)return console.error(e),void o(!0);t.store.messenger&&t.store.messenger.onFriendAdded(a),t.updateMetadata(),o(!0)}))}));o()}},s.FRIEND_REQUEST=function(e,t,n){var r=n.content.user||n.content;u[r.curvePublic]&&delete u[r.curvePublic]};var l={},f={};i.DECLINE_FRIEND_REQUEST=function(e,t,n,r){var o=n.msg.content.user||n.msg.content;o.curvePublic||(o.curvePublic=n.msg.author),setTimeout((function(){r(!0),e.store.proxy.friends_pending[n.msg.author]&&(delete e.store.proxy.friends_pending[n.msg.author],e.updateMetadata(),l[n.msg.author]||t.sendMessage({type:"FRIEND_REQUEST_DECLINED",content:{user:o}},(function(e){l[n.msg.author]={type:t.type,hash:e}})))}),a(e))},i.FRIEND_REQUEST_DECLINED=function(e,t,n,r){e.updateMetadata();var o=n.msg.content.user.curvePublic||n.msg.content.user,a=f[o];delete f[o],l[o]?r(!0,a):(l[o]={type:t.type,hash:n.hash},r(!1,a))},s.FRIEND_REQUEST_DECLINED=function(e,t,n){var r=n.content.user.curvePublic||n.content.user;l[r]&&delete l[r]},i.ACCEPT_FRIEND_REQUEST=function(t,n,r,o){var i=r.msg.content.user||r.msg.content;setTimeout((function(){o(!0),t.store.proxy.friends_pending[r.msg.author]&&(delete t.store.proxy.friends_pending[r.msg.author],e.addToFriendList({proxy:t.store.proxy,realtime:t.store.realtime,pinPads:t.pinPads},i,(function(e){e?console.error(e):(t.store.messenger&&t.store.messenger.onFriendAdded(i),t.updateMetadata(),t.store.modules.profile&&t.store.modules.profile.update(),f[r.msg.author]||n.sendMessage({type:"FRIEND_REQUEST_ACCEPTED",content:{user:i}},(function(e){f[r.msg.author]={type:n.type,hash:e}})))})))}),a(t))},i.FRIEND_REQUEST_ACCEPTED=function(e,t,n,r){e.updateMetadata();var o=n.msg.content.user.curvePublic||n.msg.content.user,a=l[o];delete l[o],f[o]?r(!0,a):(f[o]={type:t.type,hash:n.hash},r(!1,a))},s.FRIEND_REQUEST_ACCEPTED=function(e,t,n){var r=n.content.user.curvePublic||n.content.user;f[r]&&delete f[r]},i.CANCEL_FRIEND_REQUEST=function(e,t,n,r){var o=u[n.msg.author];o?r(!0,o):r(!0)},i.UNFRIEND=function(t,n,r,o){var a=r.msg.author,i=e.getFriend(t.store.proxy,a);i?(delete t.store.proxy.friends[a],delete t.store.proxy.friends_pending[a],t.store.messenger&&t.store.messenger.onFriendRemoved(a,i.channel),t.updateMetadata(),o(!0)):o(!0)},i.UPDATE_DATA=function(e,t,n,r){var o=n.msg,a=o.author,i=e.store.proxy.friends&&e.store.proxy.friends[a];if(!i||"object"!=typeof o.content)return void r(!0);const s=o.content.edPublic,c=()=>{Object.keys(o.content).forEach((function(e){i[e]=o.content[e]})),e.store.messenger&&e.store.messenger.onFriendUpdate(a),e.updateMetadata(),r(!0)};if(o.content.badge&&e.store.modules.badge)return e.store.modules.badge.listBadges({edPublic:s},(e=>{e.includes(o.content.badge)||delete o.content.badge,c()}));c()};var d=function(e,t){let n=e.store.data.blockHash,a=o.parseBlockHash(n).keys.symmetric;return r.encrypt(t,a)},h={};i.SHARE_PAD=function(e,n,r,o){var a=r.msg,i=r.hash,s=a.content;if(c(e,r))o(!0);else{var u,l=s.isStatic?s.href:t.hrefToHexChannelId(s.href,s.password),f=t.parsePadUrl(s.href),p=f.hashData&&f.hashData.mode||"n/a",y=h[l];if(y){if("edit"===y.mode&&"view"===p)return void o(!0);u=y.data}s.password&&(s.password=d(e,s.password)),h[l]={mode:p,data:{type:n.type,hash:i}},o(!1,u)}},s.SHARE_PAD=function(e,n,r,o){var a=r.content,i=t.hrefToHexChannelId(a.href,a.password),s=h[i];s&&s.data&&s.data.hash===o&&delete h[i]};var p=!1;i.SUPPORT_MESSAGE=function(e,t,n,r){p?r(!0):(p=!0,r())},s.SUPPORT_MESSAGE=function(){p=!1},i.REQUEST_PAD_ACCESS=function(e,t,n,r){var o=n.msg.content;if(c(e,n))r(!0);else{var a=o.channel,i=e.store.manager.findChannel(a);if(i.length){var s,u,l=e.store.proxy.edPublic;i.some((function(e){if(e.data&&Array.isArray(e.data.owners)&&-1!==e.data.owners.indexOf(l)&&e.data.href)return u=e.data.href,s=e.data.filename||e.data.title,!0}))?(o.title=s,o.href=u,r(!1)):r(!0)}else r(!0)}},i.GIVE_PAD_ACCESS=function(e,t,n,r){var o,a=n.msg.content,i=a.channel;e.store.manager.findChannel(i,!0).forEach((function(e){e.data&&!e.data.href&&(o||(o=e.data.filename||e.data.title),e.userObject.setHref(i,null,a.href))})),a.title=o||a.title,r(!1)},i.ADD_TO_ACCESS_LIST=function(e,t,n,r){var o=n.msg.content.channel;e.Store.getAllStores().forEach((function(t){var n=t.manager.findChannel(o);if(n.length){var r=n[0].data,a=n[0].id,i=t.id;e.Store.loadSharedFolder(i,a,r,(function(){}),!1)}})),r(!0)};var y={};i.ADD_OWNER=function(e,t,n,r){var o=n.msg.content;if(c(e,n))r(!0);else{if(!(o.teamChannel||o.href&&o.title&&o.channel))return console.log("Remove invalid notification"),void r(!0);var a=o.channel||o.teamChannel;o.password&&(o.pw=o.password,o.password=d(e,o.password)),y[a]?r(!0):(y[a]={type:t.type,hash:n.hash},r(!1))}},s.ADD_OWNER=function(e,t,n){var r=n.content.channel||n.content.teamChannel;y[r]&&delete y[r]},i.RM_OWNER=function(e,t,n,r){var o=n.msg.content;if(!o.channel&&!o.teamChannel)return console.log("Remove invalid notification"),void r(!0);var a=o.channel||o.teamChannel;if(o.teamChannel){var i=e.store.proxy.teams||{};Object.keys(i).some((function(e){if(i[e].channel===a)return i[e].owner=!1,!0}))}y[a]&&o.pending?r(!1,y[a]):r(!1)};var v={};i.INVITE_TO_TEAM=function(e,t,r,o){var a=r.msg.content;if(c(e,r))o(!0);else{if(!a.team)return console.log("Remove invalid notification"),void o(!0);var i=v[a.team.channel];if(i)return console.log("removing old invitation"),o(!1,i),void(v[a.team.channel]={type:t.type,hash:r.hash});var s=n.find(e,["store","proxy","teams"])||{};Object.keys(s).some((function(e){return s[e].channel===a.team.channel}))?o(!0):(v[a.team.channel]={type:t.type,hash:r.hash},o(!1))}},s.INVITE_TO_TEAM=function(e,t,r){var o=n.find(r,["content","team","channel"]);delete v[o]},i.KICKED_FROM_TEAM=function(e,t,n,r){var o=n.msg.content;if(!o.teamChannel)return console.log("Remove invalid notification"),void r(!0);v[o.teamChannel]&&o.pending?r(!0,v[o.teamChannel]):r(!1)},i.INVITE_TO_TEAM_ANSWER=function(e,t,r,o){var a=r.msg,i=a.content;if(!i.teamChannel)return console.log("Remove invalid notification"),void o(!0);var s,c,u=n.find(e,["store","proxy","teams"])||{};if(Object.keys(u).some((function(e){var t=u[e];if(t.channel===i.teamChannel)return s=e,c=t,!0})),s){if(i.team=c,!i.answer)try{e.store.modules.team.removeFromTeam(s,a.author,!0)}catch(e){console.error(e)}var l=i.user||i;t.sendMessage({type:"INVITE_TO_TEAM_ANSWERED",content:{user:l,team:c,answer:i.answer}},(function(){})),o(!0)}else o(!0)},i.TEAM_EDIT_RIGHTS=function(e,t,r,o){var a=r.msg.content;if(!a.teamData)return console.log("Remove invalid notification"),void o(!0);var i,s=n.find(e,["store","proxy","teams"])||{};if(Object.keys(s).some((function(e){if(s[e].channel===a.teamData.channel)return i=e,!0})),i)try{e.store.modules.team.changeMyRights(i,a.state,a.teamData,(function(e){e||console.error("Can't update team rights"),o(!0)}))}catch(e){console.error(e)}else o(!0)},i.OWNED_PAD_REMOVED=function(e,t,n,r){var o=n.msg.content;if(!o.channel)return console.log("Remove invalid notification"),void r(!0);var a=o.channel;e.store.manager.findChannel(a).forEach((function(t){var n=e.store.manager.findFile(t.id);e.store.manager.delete({paths:n},(function(){e.updateDrive()}))})),r(!0)},i.MOVE_TODO=function(e,t,n,r){var o=e.store.proxy.curvePublic;n.msg.author===o?r():r(!0)},i.SAFE_LINKS_DEFAULT=function(e,t,n,r){var o=e.store.proxy.curvePublic;n.msg.author===o?r():r(!0)};var m={};i.FORM_RESPONSE=function(e,t,n,r){var o,a,i=n.msg,s=n.hash,c=i.content,u=c.channel;if(u)if(function(e,t){return(e.store.proxy.mutedChannels||[]).includes(t)}(e,u))r(!0);else if(e.Store.getAllStores().some((function(e){return e.manager.findChannel(u).some((function(e){if(e.data&&(!a||e.data.href))return a=e.data.href||e.data.roHref,o=e.data.filename||e.data.title,!!e.data.href||void 0}))})),a){c.href=a,c.title=o;var l=m[u],f=l?l.data:void 0;m[u]={data:{type:t.type,hash:s}},r(!1,f)}else r(!0);else r(!0)},s.FORM_RESPONSE=function(e,t,n,r){var o=n.content.channel,a=m[o];a&&a.data&&a.data.hash===r&&delete m[o]};var g={};i.COMMENT_REPLY=function(e,t,r,o){var a=r.msg,i=r.hash,s=a.content;if(n.find(e.store.proxy,["settings","pad","disableNotif"]))o(!0);else{var c,u,l=s.channel;if(l)if(e.Store.getAllStores().some((function(e){return e.manager.findChannel(l).some((function(e){if(e.data&&(!u||e.data.href))return u=e.data.href||e.data.roHref,c=e.data.filename||e.data.title,!!e.data.href||void 0}))})),u){s.href=u,s.title=c;var f=g[l],d=f?f.data:void 0;g[l]={data:{type:t.type,hash:i}},o(!1,d)}else o(!0);else o(!0)}},s.COMMENT_REPLY=function(e,t,n,r){var o=n.content.channel,a=g[o];a&&a.data&&a.data.hash===r&&delete g[o]};var E,b,A={};i.MENTION=function(e,t,n,r){var o=n.msg,a=n.hash,i=o.content;if(c(e,n))r(!0);else{var s=i.channel;if(s){var u,l;e.Store.getAllStores().some((function(e){return e.manager.findChannel(s).some((function(e){if(e.data&&(!l||e.data.href))return l=e.data.href||e.data.roHref,u=e.data.filename||e.data.title,!!e.data.href||void 0}))})),i.href=l,i.title=u;var f=A[s],d=f?f.data:void 0;A[s]={data:{type:t.type,hash:a}},r(!1,d)}else r(!0)}},s.MENTION=function(e,t,n,r){var o=n.content.channel,a=A[o];a&&a.data&&a.data.hash===r&&delete A[o]},i.BROADCAST_MAINTENANCE=function(e,t,n,r){var o=n.msg.uid;e.Store.onMaintenanceUpdate(o),r(!0)},i.BROADCAST_SURVEY=function(e,t,n,r){var o=n.msg,a=o.content,i=o.uid,s=E;E={type:t.type,hash:n.hash},e.Store.onSurveyUpdate(i),r(!a.url,s)},i.BROADCAST_CUSTOM=function(e,t,n,r){var o=n.msg.uid,a=b;b={uid:o,type:t.type,hash:n.hash},r(!1,a)},i.BROADCAST_DELETE=function(e,t,n,r){var o=n.msg.content.uid;if(b&&b.uid===o)return r(!0,b),void(b=void 0);r(!0)};var _,w,O={};return i.SF_DELETED=function(e,t,n,r){var o=n.msg.content,a=o.team,i=o.sfId;if(O[i])r(!0);else if(O[i]=1,a){var s=e.store.proxy.teams[a];o.teamName=s.metadata&&s.metadata.name,r(!1)}else r(!1)},s.SF_DELETED=function(e,t,n){var r=n.content.sfId;delete O[r]},i.NEW_TICKET=function(e,t,r,o){var a=r.msg.content;a.time||(a.time=r.time);var i=n.find(e,["store","modules","support"]);a.isAdmin&&i.addUserTicket(a,o),i.addAdminTicket(a,o)},i.NOTIF_TICKET=function(e,t,r,o){var a=r.msg.content;a.time||(a.time=r.time);var i=n.find(e,["store","modules","support"]);if(a.isAdmin)return n.find(e,["store","proxy","support",a.channel])?(i.updateUserTicket(a),_?void o(!1,_):(_={channel:a.channel,type:t.type,hash:r.hash},void o(!1))):void o(!0);i.checkAdminTicket(a,(s=>{s?(i.updateAdminTicket(a),n.find(e.store.proxy,["settings","general","disableSupportNotif"])?o(!0):w?o(!1,w):(w={channel:a.channel,type:t.type,hash:r.hash},o(!1))):o(!0)}))},s.NOTIF_TICKET=function(e,t,n){var r=n.content.channel;_&&_.channel===r&&(_=void 0),w&&w.channel===r&&(w=void 0)},i.ADD_MODERATOR=function(e,t,r,o){var a=r.msg.content;n.find(e,["store","modules","support"]).updateAdminKey(a,o)},i.MODERATOR_NEW_KEY=function(e,t,r,o){var a=r.msg.content;n.find(e,["store","modules","support"]).updateAdminKey(a,(function(){o(!0)}))},{add:function(e,t,r,o){if(r.msg){var a=n.find(e,["store","proxy","curvePublic"]),s=n.find(r,["msg","content","user","curvePublic"])||n.find(r,["msg","content","curvePublic"]);if(s&&r.msg.author!==s&&r.msg.author!==a)return console.error("blocked"),void o(null,null,!0);var c=r.msg.type;if(i[c])try{i[c](e,t,r,o)}catch(e){console.error(e),o()}else o()}else o(null,null,!0)},remove:function(e,t,n,r){if(n){var o=n.type;if(s[o])try{s[o](e,t,n,r)}catch(e){console.error(e)}}}}})(Zt(),Fe(),Ne(),ye(),Gt())),ln),O(),ye()),dn}function gn(){if(yn)return pn;yn=1;return pn=((e,t,n,r,o,a,i,s,c)=>{let u={};let l=function(l,f,d,h){var p=l.version||0;s((function(){})).nThen((function(){var t,n,r,o,a;p<2&&(t="cryptpad.userlist-drawer",n="cryptpad.hide_poll_text",r="cryptpad.indentUnit",o="cryptpad.indentWithTabs",a=l.settings=l.settings||{},void 0!==l[r]&&(a.codemirror=a.codemirror||{},a.codemirror.indentUnit=l[r],delete l[r]),void 0!==l[o]&&(a.codemirror=a.codemirror||{},a.codemirror.indentWithTabs=l[o],delete l[o]),void 0!==l[t]&&(a.toolbar=a.toolbar||{},a.toolbar["userlist-drawer"]=l[t],delete l[t]),void 0!==l[n]&&(a.poll=a.poll||{},a.poll["hide-text"]=l[n],delete l[n]),e.send("Migrate-2",!0),l.version=p=2)})).nThen((function(){p<3&&(!function(){if(localStorage.CRYPTPAD_LANG){var e=localStorage.CRYPTPAD_LANG;l.settings.language=e}}(),e.send("Migrate-3",!0),l.version=p=3)})).nThen((function(){var t;p<4&&(t=l.settings=l.settings||{},void 0!==l.allowUserFeedback&&(t.general=t.general||{},t.general.allowUserFeedback=l.allowUserFeedback,delete l.allowUserFeedback),e.send("Migrate-4",!0),l.version=p=4)})).nThen((function(){p<5&&(!function(){var e=l.drive&&l.drive.filesData;if(e)for(var t in e)"number"!=typeof e[t].ctime&&(e[t].ctime=+new Date(e[t].ctime)),"number"!=typeof e[t].atime&&(e[t].atime=+new Date(e[t].atime))}(),e.send("Migrate-5",!0),l.version=p=5)})).nThen((function(n){var r,o,a,i,c;p<6&&(a=l.drive.filesData||{},i=s((function(){})),c=Object.keys(a).length,Object.keys(a).forEach((function(e,n){i=i.nThen((function(i){setTimeout(i((function(){if(r=a[e],o=t.parsePadUrl(r.href),r.href&&!r.channel){var i=t.getSecrets(o.type,o.hash,r.password);r.channel=i.channel,d(6,Math.round(100*n/c)),console.log("Adding missing channel in filesData ",r.channel)}})))}))})),i.nThen(n((function(){e.send("Migrate-6",!0),l.version=p=6}))))})).nThen((function(n){var r,o,a,i,c;p<7&&(a=l.drive.filesData,i=s((function(){})),c=Object.keys(a).length,Object.keys(a).forEach((function(e,n){i=i.nThen((function(i){setTimeout(i((function(){if((r=a[e]).href)if(-1!==r.href.indexOf("#"))if("pad"===(o=t.parsePadUrl(r.href)).hashData.type){if("view"===o.hashData.mode)r.roHref=r.href,delete r.href,console.log("Move href to roHref in filesData ",r.roHref);else{var i=t.getSecrets(o.type,o.hash,r.password),s=t.getViewHashFromKeys(i);s&&(r.roHref="/"+o.type+"/#"+s,console.log("Adding missing roHref in filesData ",r.href))}d(6,Math.round(100*n/c))}else d(7,Math.round(100*n/c));else d(7,Math.round(100*n/c));else d(7,Math.round(100*n/c))})))}))})),i.nThen(n((function(){e.send("Migrate-7",!0),l.version=p=7}))))})).nThen((function(){p<8&&(l.FS_hashes=n.deduplicateString(l.FS_hashes||[]),e.send("Migrate-8",!0),l.version=p=8)})).nThen((function(){p<9&&(!function(){var e=h.network,t={},n={store:h},o=r.createData(l),i=function(e){var n=t[e];if(n){try{n.wc.leave()}catch(e){}delete t[e]}};e.on("message",(function(r,s){try{!function(r,s){if(s===e.historyKeeper){var c=JSON.parse(r);if(!c.validateKey&&!c.owners||!c.channel){if(c.channel&&t[c.channel]){if(c.error&&"EINVAL"===c.error){var u=["GET_HISTORY",c.channel,{}];return void e.sendto(e.historyKeeper,JSON.stringify(u)).then((function(){}),(function(){}))}if(c.state&&1===c.state){o.channel=c.channel;var l=["UPDATE",o.curvePublic,+new Date,o],f=t[c.channel].encrypt(JSON.stringify(l));return t[c.channel].wc.bcast(f).then((function(){}),(function(e){console.error("Can't migrate this friend",t[c.channel].friend,e)})),void i(c.channel)}}else if(c.channel)return;var d=c[3];if(d&&t[d]){var h=t[d],p=h.decrypt(c[4]),y=JSON.parse(p);if("UPDATE"===y[0]){if(y[1]===o.curvePublic)return;var v=y[3];if(!v.notifications)return;h.friend.notifications=v.notifications,o.channel=d,a.sendTo(n,"UPDATE_DATA",o,{channel:v.notifications,curvePublic:v.curvePublic},(function(e){e&&e.error?console.error(e):console.log("friend migrated",h.friend)})),i(d)}}}}}(r,s)}catch(e){console.error(e)}}));var s=l.friends||{};Object.keys(s).forEach((function(n){if(44===n.length){var r=s[n];r.notifications||e.join(r.channel).then((function(n){var o=c.Curve.deriveKeys(r.curvePublic,l.curvePrivate,r.kemPublic,l.kemPublic),a=c.Curve.createEncryptor(o);t[r.channel]={wc:n,friend:r,decrypt:a.decrypt,encrypt:a.encrypt};var i={lastKnownHash:r.lastKnownHash},s=["GET_HISTORY",r.channel,i];e.sendto(e.historyKeeper,JSON.stringify(s)).then((function(){}),(function(e){console.error("Can't migrate this friend",r,e)}))}),(function(e){console.error("Can't migrate this friend",r,e)}))}}))}(),e.send("Migrate-9",!0),l.version=p=9)})).nThen((function(n){p<10&&function(){var i=h.proxy.todo;if(i){var c,f=n((function(){e.send("Migrate-10",!0),l.version=p=10})),d={network:h.network,initialState:"{}",metadata:{owners:h.proxy.edPublic?[h.proxy.edPublic]:[]}};s((function(e){o.get(i,e((function(t,n){if(t||!n)return e.abort(),void f();try{c=JSON.parse(n)}catch(e){}})),d)})).nThen((function(e){if(!c||"object"!=typeof c)return e.abort(),void f();var n={content:{data:{1:{id:"1",color:"color6",item:[],title:u.kanban_todo},2:{id:"2",color:"color3",item:[],title:u.kanban_working},3:{id:"3",color:"color5",item:[],title:u.kanban_done}},items:{},list:[1,2,3]},metadata:{title:u.type.todo,defaultTitle:u.type.todo,type:"kanban"}},s=4,p=!1;if((c.order||[]).forEach((function(e){var t=c.data[e];if(t&&t.task){p=!0;var r=t.state?"3":"1";n.content.data[r].item.push(s),n.content.items[s]={id:s,title:t.task},s++}})),!p)return e.abort(),void f();var y=t.createRandomHash("kanban"),v=t.getSecrets("kanban",y),m=t.getSecrets("todo",i);o.put(y,JSON.stringify(n),e((function(n){if(n)return e.abort(),void f();h.rpc&&(h.rpc.pin([v.channel],(function(){})),h.rpc.unpin([m.channel],(function(){})));var o=t.hashToHref(y,"kanban");h.manager.addPad(["root"],{title:u.type.todo,owners:d.metadata.owners,channel:v.channel,href:o,roHref:t.hashToHref(t.getViewHashFromKeys(v),"kanban"),atime:+new Date,ctime:+new Date},e((function(e){if(e)console.error(e);else{delete h.proxy.todo;var t=r.createData(l),n={store:h};a.sendTo(n,"MOVE_TODO",{user:t,href:o},{channel:t.notifications,curvePublic:t.curvePublic},(function(e){e&&e.error&&console.error(e)}))}})))})),d)})).nThen((function(){f()}))}}()})).nThen((function(t){if(!(p>=11)){var o=function(){e.send("Migrate-11",!0),l.version=p=11};if(void 0===n.find(l,["settings","security","unsafeLinks"])){var i={store:h},s=r.createData(l);s.curvePublic?a.sendTo(i,"SAFE_LINKS_DEFAULT",{user:s},{channel:s.notifications,curvePublic:s.curvePublic},t((function(e){e&&e.error?console.error(e):o()}))):o()}else o()}})).nThen((function(){i.whenRealtimeSyncs(h.realtime,n.mkAsync(n.bake(f)))}))};return l.setCustomize=e=>{u=e.Messages},l})(nt(),Fe(),Ne(),Zt(),cn(),mn(),mt(),Dt(),ye()),pn}var En,bn,An=o(et);var _n,wn,On,Dn,Sn=bn?En:(bn=1,_n=cn(),wn=Et(),Fe(),On=mt(),Dn={anonDriveIntoUser:function(e,t,n){t&&e.loggedIn||"function"!=typeof n?_n.get(t,(function(r,o){var a;if(r)console.error("Cannot migrate recent pads",r);else if(o){try{a=JSON.parse(o)}catch(e){return"function"==typeof n&&n(),void console.error("Cannot parsed recent pads",e)}if(a){var i=e.proxy,s=wn.init(a.drive,{readOnly:!1,loggedIn:!0,outer:!0}),c=function(){s.fixFiles(!0);var r=e.manager;s.getFiles([s.FILES_DATA]).forEach((function(e){var t=s.getFileData(e),n=t.channel,o=r.findChannel(n);if(0===o.length)t&&r.addPad(null,t,(function(e){e&&console.error("Cannot import file:",t,e)}));else{if(!t.href)return;o.forEach((function(e){e.data&&!e.data.href&&e.userObject.setHref(n,null,t.href)}))}})),i.FS_hashes&&Array.isArray(i.FS_hashes)||(i.FS_hashes=[]),-1===i.FS_hashes.indexOf(t)&&i.FS_hashes.push(t),"function"==typeof n&&On.whenRealtimeSyncs(e.realtime,n)};s&&"function"==typeof s.migrate?s.migrate(c):(console.log("oldFo.migrate is not a function"),c())}else"function"==typeof n&&n()}else"function"==typeof n&&n()})):n()}},En=Dn);const Tn=je.mkEvent(!0),Cn=je.mkEvent(!0),xn=je.mkEvent(),In=je.mkEvent(),Nn=(e,t)=>{var n,r;const o=e.store,a=e.Store;let i;if(t){const e=a.getStore(t);i=null===(r=null==e?void 0:e.proxy)||void 0===r?void 0:r.drive}else i=null===(n=o.drive)||void 0===n?void 0:n.proxy;return i},Pn={init:e=>{var t;const{broadcast:n,store:r,Store:o,account:a}=e,i=r.drive||(r.drive={});let s=null===(t=r.proxy)||void 0===t?void 0:t.drive;if((null==s?void 0:s.hash)||Ke.createRandomHash("drive"),!s.hash)return i.proxy=s,a.onAccountCacheReady((()=>{Tn.fire()})),a.onAccountReady((()=>{Cn.fire()})),{channel:"",onDriveCacheReady:Tn.reg,onDriveReady:Cn.reg,onDisconnect:xn.reg,onReconnect:In.reg};throw new Error("NOT IMPLEMENTED")},initAPI:e=>{const{broadcast:t,store:n,Store:r,account:o}=e,a={store:n,Store:r};return{exists:(e,t,r)=>{r({state:Boolean(n.proxy)})},get:(e,t,n)=>{let r=Nn(a,t.teamId);n(r?{drive:r}:{error:"ENOTFOUND"})},set:(e,t,n)=>{let o=Nn(a,t.teamId);var i,s;o?(i=o,s=t.value,Object.keys(i).forEach((e=>{delete i[e]})),Object.keys(s).forEach((e=>{i[e]=je.clone(s[e])})),r.onSync(t.teamId,n)):n({error:"ENOTFOUND"})},migrateAnon:(e,t,r)=>{Sn.anonDriveIntoUser(n,t.anonHash,r)}}}};var kn=o(Object.freeze({__proto__:null,Drive:Pn})),Rn=O(),Mn=r(Dt()),Fn=r(Xt()),Ln=St();const Hn=je.mkEvent(!0),Kn=je.mkEvent(!0),jn=(e,t,n,r)=>{const o=je.once(je.mkAsync(r)),{store:a,Store:i}=e;!a.offline&&a.anon_rpc?n.channel?32===n.channel.length&&Ke.isValidChannel(n.channel)?a.anon_rpc.send("GET_METADATA",n.channel,((e,t)=>{if(e)return void o({error:e});const r=t&&t[0]||{};o(r),r.rejected||i.getAllStores().forEach((e=>{const t=e.manager.findChannel(n.channel,!0);let o=!1;(t.forEach((e=>{Fn(e.data.owners)!==Fn(r.owners)&&(o=!0),e.data.owners=r.owners,e.data.atime=+new Date,r.expire&&(e.data.expire=+r.expire)})),o)&&(e.sendEvent||a.sendDriveEvent)("DRIVE_CHANGE",{path:["drive",Pt.FILES_DATA]})}))})):o({error:"EINVAL"}):o({error:"ENOTFOUND"}):o({error:"OFFLINE"})},Un=(e,t,n)=>{if(n.versionHash)return((e,t,n)=>{let r;const{Store:o,store:a,postMessage:i}=e,s=n.channel,c=n.versionHash,u=Ke.createChannelId();Mn((n=>{jn(e,0,{channel:s},n((e=>{if(e&&e.rejected)return i(t,"PAD_ERROR",{type:"ERESTRICTED"}),void n.abort();r=e.validateKey})))})).nThen((()=>{o.getHistoryRange(t,{cpCount:1,channel:s,lastKnownHash:c},(e=>{var n,o;if(e&&e.error)return i(t,"PAD_ERROR",e.error);const l=e.messages||[];if((null===(n=l[l.length-1])||void 0===n?void 0:n.serverHash)!==c)return i(t,"PAD_ERROR",{type:"HASH_NOT_FOUND"});i(t,"PAD_CONNECT",{myID:u,id:s,members:[u]}),(e.messages||[]).forEach((e=>{i(t,"PAD_MESSAGE",{msg:e.msg,time:e.time,user:u.slice(0,16)})})),r&&(null===(o=null==a?void 0:a.messenger)||void 0===o||o.storeValidateKey(s,r)),i(t,"PAD_READY")}))}))})(e,t,n);const{channels:r,store:o,Store:a,myDeletions:i,postMessage:s}=e,c=n.channel;if(!Ke.isValidChannel(c))return s(t,"PAD_ERROR","INVALID_CHAN");const u=void 0===r[c],l=r[c]||(r[c]={queue:[],data:{},clients:[],bcast:(e,t,n)=>{l.clients.forEach((function(r){r!==n&&s(r,e,t)}))},history:[],pushHistory:(e,t)=>{if(t){let t;for(l.history.push("cp|"+e),t=l.history.length-101;t>0&&!/^cp\|/.test(l.history[t]);t--);l.history=l.history.slice(t)}else l.history.push(e)}});if(-1===l.clients.indexOf(t)&&l.clients.push(t),!u&&l.wc)return s(t,"PAD_CONNECT",{myID:l.wc.myID,id:l.wc.id,members:l.wc.members}),l.wc.members.forEach((e=>{s(t,"PAD_JOIN",e)})),l.history.forEach((e=>{s(t,"PAD_MESSAGE",{msg:Rn.removeCp(e),user:l.wc.myID,validateKey:l.data.validateKey})})),void s(t,"PAD_READY");const f=t=>{const r=null==t?void 0:t.type;"EDELETED"===r&&i[c]&&(delete i[c],t.ownDeletion=!0),l.bcast("PAD_ERROR",t),"EDELETED"===r&&(null==Je?void 0:Ye.clearChannel)&&Ye.clearChannel(c),["EDELETED","EEXPIRED","ERESTRICTED"].includes(r)&&e.leavePad(null,n,(function(){}))},d={Cache:o.neverCache?void 0:Je,priority:1,onCacheStart:()=>{s(t,"PAD_CACHE")},onCacheReady:()=>{s(t,"PAD_CACHE_READY"),Kn.fire()},onReady:e=>{const n=e.metadata||{};l.data=n,(null==n?void 0:n.validateKey)&&o.messenger&&o.messenger.storeValidateKey(c,n.validateKey),s(t,"PAD_READY",e.noCache)},onMessage:function(e,t,n,r,o){l.lastHash=o,l.pushHistory(e,r),l.bcast("PAD_MESSAGE",{user:t,msg:e,validateKey:n})},onJoin:function(e){l.bcast("PAD_JOIN",e)},onLeave:function(e){l.bcast("PAD_LEAVE",e)},onError:f,onChannelError:f,onRejected:a.onRejected,onConnectionChange:e=>{e.state||l.bcast("PAD_DISCONNECT")},onMetadataUpdate:e=>{l.data=e||{},a.getAllStores().forEach((t=>{t.manager.findChannel(c,!0).forEach((t=>{t.data.owners=e.owners,t.data.atime=+new Date,e.expire&&(t.data.expire=+e.expire)}));(t.sendEvent||o.sendDriveEvent)("DRIVE_CHANGE",{path:["drive",Pt.FILES_DATA]})})),l.bcast("PAD_METADATA",e)},crypto:{encrypt:function(e){return e},decrypt:function(e){return e}},noChainPad:!0,channel:c,metadata:n.metadata,network:o.network||o.networkPromise,websocketURL:Ae.getWebsocketURL(),onInit:function(){Hn.fire()},onConnect:(e,n)=>{l.sendMessage=(t,r,o)=>{n(t,(n=>{n?o({error:n}):(l.lastHash=t.slice(0,64),l.pushHistory(Rn.removeCp(t),/^cp\|/.test(t)),l.bcast("PAD_MESSAGE",{user:e.myID,msg:Rn.removeCp(t),validateKey:l.data.validateKey},r),o())}))},l.wc=e,l.queue.forEach((function(e){l.sendMessage(e.message,t)})),l.queue=[],l.bcast("PAD_CONNECT",{myID:e.myID,id:e.id,members:e.members})}};l.cpNf=Rn.start(d)},Bn=(e,t)=>{var n,r,o,a,i,s;const c=e.store;if(null===(r=null===(n=c.messenger)||void 0===n?void 0:n.leavePad)||void 0===r||r.call(n,t),null===(a=null===(o=c.onlyoffice)||void 0===o?void 0:o.leavePad)||void 0===a||a.call(o,t),Object.keys(c.modules).forEach((e=>{var n,r;null===(r=null===(n=c.modules[e])||void 0===n?void 0:n.leavePad)||void 0===r||r.call(n,t)})),!((e,t)=>{const{store:n}=e;if(!n)return!1;if(n.driveChannel===t)return!0;if(Ln.isSharedFolderChannel(t))return!0;if(je.find(n,["proxy","teams"])){var r=je.find(n,["proxy","teams"])||{};return Object.keys(r).some((e=>r[e].channel===t))}if(je.find(n,["proxy","profile","href"])){let e=je.find(n,["proxy","profile","href"]);return Ke.hrefToHexChannelId(e)===t}})(e,t)){try{Ye.leaveChannel(t)}catch(e){console.error(e)}null===(s=null===(i=e.channels[t])||void 0===i?void 0:i.cpNf)||void 0===s||s.stop()}delete e.channels[t]},Vn={init:e=>{const{broadcast:t,postMessage:n,store:r,Store:o}=e,a={channels:[],postMessage:n,store:r,Store:o,myDeletions:[],leavePad:(e,t,n)=>{}},i=(e,t,n)=>{const r=a.channels[t.channel];(null==r?void 0:r.cpNf)?(Bn(a,t.channel),n()):n({error:"EINVAL"})};a.leavePad=i;return{join:(e,t,n)=>{Un(a,e,t)},destroy:(e,t,n)=>{((e,t,n,r)=>{const{store:o,Store:a,channels:i,myDeletions:s}=e;let c,u,l=n,f=!1;if(n&&"object"==typeof n&&({channel:l,force:f,teamId:c,reason:u}=n),l===o.driveChannel&&!f)return void r({error:"User drive removal blocked!"});const d=a.getStore(c);d?d.rpc?(i[l]&&(s[l]=!0),d.rpc.removeOwnedChannel(l,(e=>{e&&delete s[l],r({error:e})}),u)):r({error:"RPC_NOT_READY"}):r({error:"ENOTFOUND"})})(a,0,t,n)},clear:(e,t,n)=>{((e,t,n,r)=>{const{Store:o}=e,a=o.getStore(n&&n.teamId);a.rpc?a.rpc.clearOwnedChannel(n.channel,(e=>{r({error:e})})):r({error:"RPC_NOT_READY"})})(a,0,t,n)},setMetadata:(e,t,n)=>{((e,t,n,r)=>{if(!n.channel)return void r({error:"ENOTFOUND"});if(!n.command)return void r({error:"EINVAL"});const{Store:o}=e,a=o.getStore(n.teamId);if(!a)return void r({error:"ENOTFOUND"});const i=n.channels;delete n.channels,a.rpc.setMetadata(n,((e,t)=>{e?r({error:e}):Array.isArray(t)&&t.length?r(t[0]):r({})})),Array.isArray(i)&&i.forEach((e=>{var r=je.clone(n);r.channel=e,o.setPadMetadata(t,r,(()=>{}))}))})(a,e,t,n)},getMetadata:(e,t,n)=>{jn(a,0,t,n)},sendMessage:(e,t,n)=>{((e,t,n,r)=>{var o=n.msg,a=e.channels[n.channel];if(a)a.wc?a.sendMessage(o,t,r):(a.queue.push(o),r())})(a,e,t,n)},onCorruptedCache:(e,t,n)=>{((e,t,n)=>{var r=e.channels[n];r&&r.cpNf&&(Ye.clearChannel(n),r.cpNf.resetCache&&r.cpNf.resetCache())})(a,0,t)},getLastHash:(e,t,n)=>{((e,t,n,r)=>{var o=e.channels[n.channel];o?o.lastHash?r({hash:o.lastHash}):r({error:"EINVAL"}):r({error:"ENOCHAN"})})(a,0,t,n)},leave:i,removeClient:e=>{Object.keys(a.channels).forEach((t=>{let n=a.channels[t].clients.indexOf(e);-1!==n&&a.channels[t].clients.splice(n,1),0===a.channels[t].clients.length&&Bn(a,t)}))},onJoined:Hn.reg,onCacheReady:Kn.reg,getChannels:()=>a.channels}}};var Gn,Yn,Jn,qn,Wn,Qn,zn,Xn,Zn,$n,er,tr,nr,rr,or,ar,ir,sr,cr,ur,lr=o(Object.freeze({__proto__:null,Pad:Vn}));function fr(){if(Yn)return Gn;Yn=1;return Gn=((e,t,n)=>{const r={};let o={},a={};r.setCustomize=e=>{o=e.Messages,a=e.AppConfig};var i=function(e,t){t.degraded||t.clients.forEach((function(n){var r=e.clients[n];if(r){var o={id:r.id,cursor:r.cursor};t.sendMsg(JSON.stringify(o))}}))},s=function(e,t,n){var r=t.members,o=a.degradedLimit||8;n.degraded=r.length-1>=o,e.emit("DEGRADED",{degraded:n.degraded},n.clients)},c=function(e,t,r,o){var a=t.channel,c=t.secret;c.keys.cryptKey&&(c.keys.cryptKey=function(e){for(var t=Object.keys(e).length,n=new Uint8Array(t),r=0;r{const l={};let f={};l.setCustomize=e=>{f=e.ApiConfig};var d=function(e,t,n,r){let o=Object.keys(e.clients).filter((n=>Boolean(e.clients[n].admin)===t));o.length&&e.emit(n,{channel:r},[o])},h=function(t,n,r,o){var a=e.mkAsync(o);if(n&&!t.adminRdyEvt)return void a("EFORBIDDEN");let i=f.httpUnsafeOrigin;e.fetchApi(i,"config",!0,(o=>{t.moderatorKeys=o.moderatorKeys,t.adminKeys=o.adminKeys;var i=o.supportMailboxKey;if(i)if(n&&e.find(t.store.proxy,["mailboxes","supportteam","keys","curvePublic"])!==i)a("EFORBIDDEN");else{var s=o.supportMailboxKemKey;if(n)return t.adminRdyEvt.reg((()=>{a(null,{supportKey:i,supportKemKey:s,myCurve:r.adminCurvePrivate||e.find(t.store.proxy,["mailboxes","supportteam","keys","curvePrivate"]),theirPublic:r.curvePublic,myKem:t.store.proxy.kemPrivate,theirKem:r.kemPublic,notifKey:r.curvePublic})}));a(null,{supportKey:i,supportKemKey:s,myCurve:t.store.proxy.curvePrivate,theirPublic:r.curvePublic||i,myKem:t.store.proxy.kemPrivate,theirKem:r.kemPublic||s,notifKey:i})}else a("E_NOT_INIT")}))},p=function(t,n,r,o){var s,c,l,f,d=e.once(e.mkAsync(o));a((e=>{h(t,r,n,e(((t,n)=>{if(t)return e.abort(),void d({error:t});s=n.theirPublic,c=n.myCurve,l=n.theirKem,f=n.myKem})))})).nThen((()=>{var r,o=i.Curve.deriveKeys(s,c,l,f),a=i.Curve.createEncryptor(o),h={network:t.store.network,channel:n.channel,noChainPad:!0,crypto:a,owners:[]},p=[];d=e.both((function(){r&&"function"==typeof r.stop&&r.stop()}),d),h.onMessage=function(e,t,n,r,o,a,i){var s=i&&i.time;try{e=JSON.parse(e)}catch(e){return void console.error(e)}e.time=s,a&&(e.author=a),p.push(e)},h.onError=d,h.onChannelError=d,h.onReady=function(){d(null,p)},r=u.start(h)}))},y=function(n,r,o,s){var c=e.find(n,["store","mailbox"]),u=e.find(n,["store","anon_rpc"]);if(c)if(u){var l,f,d,p,y,v=r.channel,m=r.title,g=r.ticket,E=+new Date;a((e=>{h(n,o,r,e(((t,n)=>{if(t)return e.abort(),void s({error:t});l=n.supportKey,f=n.theirPublic,p=n.theirKem,y=n.myKem,d=n.myCurve})))})).nThen((e=>{var t=i.Curve.deriveKeys(f,d,p,y),n=i.Curve.createEncryptor(t),r=JSON.stringify(g),o=n.encrypt(r);u.send("WRITE_PRIVATE_MESSAGE",[v,o],e(((t,n)=>{if(t)return e.abort(),void s({error:t});E=n&&n[0]})))})).nThen((e=>{if(o){var t=n.adminDoc.proxy.tickets.active;if(t[v])return e.abort(),void s({error:"EEXISTS"});t[v]={title:g.title,restored:g.legacy,premium:!1,time:E,author:r.name,supportKey:l,lastAdmin:!0,authorKey:r.curvePublic,notifications:r.notifications}}})).nThen((e=>{o||(n.supportData[v]={time:+new Date,title:m,curvePublic:l},n.Store.onSync(null,e()))})).nThen((()=>{var a=o?r.notifications:t.getChannelIdFromKey(l);c.sendTo("NEW_TICKET",{title:m,channel:v,time:E,isAdmin:o,supportKey:l,premium:o?"":e.find(n,["store","account","plan"]),user:e.find(r.ticket,["sender","curvePublic"])?void 0:{supportTeam:!0}},{channel:a,curvePublic:f},(e=>{console.error(e),e&&e.error&&delete n.supportData[v],s(e)})),c.sendTo("NOTIF_TICKET",{title:m,channel:v,time:E,isAdmin:o,isNewTicket:!0,user:e.find(r.ticket,["sender","curvePublic"])?void 0:{supportTeam:!0}},{channel:a,curvePublic:f},(()=>{}))}))}else s({error:"anonymous rpc session not ready"});else s({error:"E_NOT_READY"})},v=function(n,r,o,s){var c,u,l,f,d,p,y=e.find(n,["store","mailbox"]),v=e.find(n,["store","anon_rpc"]);y?v?r?.ticket?a((e=>{h(n,o,r,e(((t,n)=>{if(t)return e.abort(),void s(t);c=n.theirPublic,u=n.myCurve,d=n.theirKem,f=n.myKem,l=n.notifKey})))})).nThen((e=>{var t=i.Curve.deriveKeys(c,u,d,f),n=i.Curve.createEncryptor(t),o=JSON.stringify(r.ticket),a=n.encrypt(o);v.send("WRITE_PRIVATE_MESSAGE",[r.channel,a],e(((t,n)=>{if(t)return e.abort(),void s(t);p=n&&n[0],s(void 0,p)})))})).nThen((()=>{var n=o?r.notifChannel:t.getChannelIdFromKey(l);n&&y.sendTo("NOTIF_TICKET",{isAdmin:o,title:r.ticket.title,isClose:r.ticket.close,channel:r.channel,time:p,user:e.find(r.ticket,["sender","curvePublic"])?void 0:{supportTeam:!0}},{channel:n,curvePublic:l},(()=>{}))})):s("E_NO_DATA"):s("anonymous rpc session not ready"):s("E_NOT_READY")},m=function(n,r,o){var a=t.getSecrets("support",r),u={data:{},channel:a.channel,crypto:i.createEncryptor(a.keys),userName:"support",ChainPad:c,classic:!0,network:n.store.network,metadata:{validateKey:a.keys.validateKey||void 0}},l=n.adminDoc=s.create(u);l.proxy.on("ready",(function(){var r=l.proxy;if(r.tickets=r.tickets||{},r.tickets.active=r.tickets.active||{},r.tickets.closed=r.tickets.closed||{},r.tickets.pending=r.tickets.pending||{},n.adminRdyEvt.fire(),o(),!n.supportRpc)return;let a=function(t){if(!t.adminDoc||!t.supportRpc)return;let n=t.adminDoc.metadata&&t.adminDoc.metadata.channel,r=t.adminDoc.proxy.tickets,o=[n,...Object.keys(r.active),...Object.keys(r.pending),...Object.keys(r.closed)];return e.deduplicateString(o).sort()}(n),i=t.hashChannelList(a);n.supportRpc.getServerHash((function(e,t){e?console.warn(e):t!==i&&n.supportRpc.reset(a,(function(e){e&&console.warn(e)}))}))})),l.proxy.on("change",["recorded"],(function(){d(n,!0,"RECORDED_CHANGE","")})),l.proxy.on("remove",["recorded"],(function(){d(n,!0,"RECORDED_CHANGE","")}))},g=function(n,o,s){let c=s(),u=n.store.proxy,l=e.find(u,["mailboxes","supportteam","keys","curvePublic"]),f=e.find(u,["mailboxes","supportteam","keys","curvePrivate"]);o||(n.adminRdyEvt=e.mkEvent(!0)),a((e=>{h(n,!1,{},e(((t,r)=>{if(setTimeout(c),t)e.abort();else if(r.theirPublic!==l){try{delete u.mailboxes.supportteam,n.store.mailbox.close("supportteam")}catch(e){}return delete n.adminRdyEvt,void e.abort()}})))})).nThen((t=>{!function(t,n){let o,a,s=e.mkAsync(n),c=t.store.proxy,u=e.find(c,["mailboxes","supportteam","keys","curvePrivate"]);if(u){try{let t=i.CryptoAgility.signKeyPairFromSeed(e.decodeBase64(u));o=e.encodeBase64(t.secretKey),a=e.encodeBase64(t.publicKey)}catch(e){return void s(e)}r.create(t.store.network,{edPublic:a,edPrivate:o},((e,n)=>{e?s(e):(console.log("Support RPC ready, public key is ",a),t.supportRpc=n,s())}))}else s("EFORBIDDEN")}(n,t((e=>{e&&console.error("Support RPC not ready",e)})))})).nThen((e=>{let r=f.slice(0,24),o=t.getEditHashFromKeys({version:2,type:"support",keys:{editKeyStr:r}});m(n,o,e())})).nThen((()=>{console.log("Support admin loaded")}))};var E=function(t,n,r,o){let a=t.store.proxy,i=e.find(a,["mailboxes","supportadmin"]);i?t.store.mailbox.open("supportadmin",i,(function(n){t.store.mailbox.close("supportadmin",(function(){}));let r=e.clone(n||{}),a=[];Object.keys(r).forEach((e=>{let n=r[e];if("CLOSE"===n.type)return void(a.includes(n.content.id)||a.push(n.content.id));let o=n.author,i=n.content&&n.content.title;((e,t,n)=>{let r=e.adminDoc.proxy;return["active","pending","closed"].some((e=>{let o=r.tickets[e];return Object.keys(o).some((e=>{let r=o[e];return r.authorKey===t&&r.title===n&&r.restored}))}))})(t,o,i)&&(a.includes(n.content.id)||a.push(n.content.id))})),Object.keys(r).forEach((e=>{let t=r[e];t.content&&a.includes(t.content.id)&&delete r[e]})),o(r)}),!0,{dump:!0}):o({error:"ENOENT"})};let b=(t,n,r,o,a)=>{let s;try{let t=i.CryptoAgility.signKeyPairFromSeed(e.decodeBase64(r));s=e.encodeBase64(t.publicKey)}catch(e){return void a(e)}t.Store.adminRpc(null,{cmd:"ADMIN_DECREE",data:["SET_SUPPORT_KEYS",[n,s,o]]},a)},A=(e,t,n,r)=>{e.Store.adminRpc(null,{cmd:"GET_MODERATORS",data:{}},r)};return l.init=function(r,s,c){var u={};if(r.store&&r.store.modules&&r.store.modules.support)return r.store.modules.support;var l=r.store,m=l.proxy.support=l.proxy.support||{},_={moderatorKeys:f.moderatorKeys,adminKeys:f.adminKeys,supportData:m,store:r.store,Store:r.Store,emit:c,clients:{}};return e.find(l,["proxy","mailboxes","supportteam"])&&g(_,!1,s),u.ctx=_,u.removeClient=function(e){delete _.clients[e]},u.leavePad=function(){},u.addAdminTicket=function(e,t){!function(e,t,r){e.adminRdyEvt?e.adminRdyEvt.reg((()=>{let o;a((n=>{h(e,!0,t,n(((e,t)=>{if(e)return n.abort(),void r(!0);o=t.supportKey})))})).nThen((()=>{var a=Math.floor(2e3*Math.random());setTimeout((()=>{var a=e.adminDoc.proxy;a.tickets.active[t.channel]||a.tickets.closed[t.channel]||a.tickets.pending[t.channel]?r(!0):(a.tickets.active[t.channel]={title:t.title,premium:t.premium,time:t.time,author:t.user&&t.user.displayName,supportKey:t.supportKey||o,authorKey:t.user&&t.user.curvePublic},n.whenRealtimeSyncs(e.adminDoc.realtime,(function(){r(!0)})),d(e,!0,"NEW_TICKET",t.channel),e.supportRpc&&e.supportRpc.pin([t.channel],(()=>{})))}),a)}))})):r(!0)}(_,e,t)},u.updateAdminTicket=function(e){!function(e,t){e.adminRdyEvt&&e.adminRdyEvt.reg((()=>{var n=Math.floor(2e3*Math.random());setTimeout((()=>{var n=e.adminDoc.proxy;let r=n.tickets.active[t.channel]||n.tickets.pending[t.channel];r&&(t.time<=r.time||(t.isClose&&(n.tickets.closed[t.channel]=r,delete n.tickets.active[t.channel],delete n.tickets.pending[t.channel]),r.time=t.time,r.lastAdmin=!1,d(e,!0,"UPDATE_TICKET",t.channel)))}),n)}))}(_,e)},u.updateAdminKey=function(n,r){((n,r,o)=>{let i=r.supportKey,s=t.getBoxPublicFromSecret(i),c=n.store.proxy;const u=e.find(c,["mailboxes","supportteam","keys","curvePrivate"]),l=e.find(c,["mailboxes","supportteam","keys","curvePublic"]);h(n,!1,{},((t,r)=>{if(t)return void o(!0);if(s!==r.theirPublic)return void o(!0);if(u===i||l===s)return void o(!0);let c=e.find(n,["store","mailbox"]);try{n.adminDoc&&n.adminDoc.stop(),c&&c.close("supportteam"),n.supportRpc&&n.supportRpc.destroy(),n.adminRdyEvt=e.mkEvent(!0)}catch(e){console.error(e)}n.Store.addAdminMailbox(null,{version:2,priv:i},(e=>{e&&e.error?o(!0):a((e=>{g(n,!0,e),n.adminRdyEvt.reg((()=>{d(n,!0,"UPDATE_RIGHTS"),o(!1)}))}))}))}))})(_,n,r)},u.checkAdminTicket=function(e,t){!function(e,t,n){e.adminRdyEvt?e.adminRdyEvt.reg((()=>{let r=e.adminDoc.proxy,o=r.tickets.active[t.channel]||r.tickets.pending[t.channel];n(o)})):n(!0)}(_,e,t)},u.addUserTicket=function(e,t){!function(e,t,n){if(!e.supportData)return void n(!0);let r=t.channel;e.supportData[r]={time:t.time,title:t.title,curvePublic:t.supportKey},e.Store.onSync(null,(function(){n(!0)}))}(_,e,t)},u.updateUserTicket=function(e){!function(e,t){if(d(e,!1,"UPDATE_TICKET",t.channel),t.isClose){let n=e.supportData[t.channel];if(!n)return;n.closed=!0}}(_,e)},u.execCommand=function(r,s,c){var u=s.cmd,l=s.data;"MAKE_TICKET"!==u?"GET_MY_TICKETS"!==u?"REPLY_TICKET"!==u?"CLOSE_TICKET"!==u?"DELETE_TICKET"!==u?"MAKE_TICKET_ADMIN"!==u?"LIST_TICKETS_ADMIN"!==u?"LOAD_TICKET_ADMIN"!==u?"REPLY_TICKET_ADMIN"!==u?"CLOSE_TICKET_ADMIN"!==u?"MOVE_TICKET_ADMIN"!==u?"GET_RECORDED"!==u?"SET_RECORDED"!==u?"USE_RECORDED"!==u?"SEARCH_ADMIN"!==u?"FILTER_TAGS_ADMIN"!==u?"SET_TAGS_ADMIN"!==u?"GET_LEGACY"!==u?"DUMP_LEGACY"!==u?"CLEAR_LEGACY"!==u?"RESTORE_LEGACY"!==u?"GET_PRIVATE_KEY"!==u?"DISABLE_SUPPORT"!==u?"ROTATE_KEYS"!==u?"ADD_MODERATOR"!==u?c({error:"NOT_SUPPORTED"}):function(t,n,r,o){let a=t.store.proxy;var i=e.find(t,["store","mailbox"]);let s=e.find(a,["mailboxes","supportteam","keys","curvePublic"]),c=e.find(a,["mailboxes","supportteam","keys","curvePrivate"]),u=e.find(a,["mailboxes","supportteam","lastKnownHash"]),l=a.edPublic;h(t,!1,{},((e,r)=>{e?o({error:e}):r.theirPublic===s&&t.moderatorKeys.includes(l)?i.sendTo("ADD_MODERATOR",{supportKey:c,lastKnownHash:u},{channel:n.mailbox,curvePublic:n.curvePublic},(()=>{o()})):o({error:"EFORBIDDEN"})}))}(_,l,0,c):function(n,r,s,c){let u,l=e.once(e.mkAsync(c)),f=n.store.proxy,d=f.edPublic;const p=i.CryptoAgility.curveKeyPair(),y=i.CryptoAgility.generateKemKeypair(),v=e.encodeBase64(p.publicKey),m=e.encodeBase64(p.secretKey),E=e.encodeBase64(y.publicKey),_=e.find(f,["mailboxes","supportteam","keys","curvePrivate"]),w=e.find(f,["mailboxes","supportteam","keys","curvePublic"]),O=e.find(f,["mailboxes","supportteam","keys","kemPublic"]);if(!m||!v)return void l({error:"INVALID_KEY"});let D;a((e=>{h(n,!1,{},e(((t,n)=>{if("E_NOT_INIT"!==t)return t?(l({error:t}),void e.abort()):void(u=n.theirPublic)})))})).nThen((e=>{if(!n.adminKeys.includes(d))return e.abort(),void l({error:"EFORBIDDEN"})})).nThen((e=>{if(u)return n.moderatorKeys.includes(d)?w!==u?(e.abort(),void l({error:"EFORBIDDEN"})):void 0:(e.abort(),void l({error:"EINVAL"}))})).nThen((e=>{u&&n.adminRdyEvt.reg((()=>{let r=n.adminDoc.proxy;D=n.adminDoc.metadata&&n.adminDoc.metadata.channel;let a=m.slice(0,24),i=t.getEditHashFromKeys({version:2,type:"support",keys:{editKeyStr:a}}),s={network:n.store.network,initialState:"{}"};(r.oldKeys=r.oldKeys||{})[w]={curvePrivate:_,rotatedOn:+new Date,rotatedBy:d},o.put(i,JSON.stringify(r),e((t=>{if(t)return e.abort(),void l({error:t})})),s)}))})).nThen((e=>{b(n,v,m,E,e((t=>{if(t&&t.error)return e.abort(),void l(t)})))})).nThen((()=>{if(!u)return;n.adminDoc&&n.adminDoc.stop();let t=e.find(n,["store","mailbox"]);t&&t.close("supportteam"),n.supportRpc&&n.supportRpc.destroy(),n.adminRdyEvt=e.mkEvent(!0)})).nThen((e=>{n.Store.addAdminMailbox(null,{version:2,priv:m},e((t=>{if(t&&t.error)return e.abort(),u?b(n,w,_,O,(()=>{l(t)})):void l(t)})))})).nThen((t=>{if(!u)return;let r=e.find(n,["store","mailbox"]);A(n,0,0,t((e=>{if(e&&e.error)return void l({success:!0,noNotify:!0});let t=e&&e[0];Object.keys(t||{}).forEach((e=>{let n=t[e];r.sendTo("MODERATOR_NEW_KEY",{supportKey:m},{channel:n.mailbox,curvePublic:n.curvePublic},(()=>{}))}))})))})).nThen((e=>{g(n,!0,e)})).nThen((e=>{D&&n.Store.adminRpc(null,{cmd:"ARCHIVE_DOCUMENT",data:{id:D,reason:"Deprecated support pad"}},e())})).nThen((()=>{l({success:!0})}))}(_,0,0,c):function(t,n,r,o){let i,s=e.once(e.mkAsync(o)),c=t.store.proxy.edPublic;a((e=>{h(t,!1,{},e((t=>{if(t)return s({error:t}),void e.abort()})))})).nThen((e=>{if(!t.adminKeys.includes(c))return e.abort(),void s({error:"EFORBIDDEN"})})).nThen((e=>{t.Store.adminRpc(null,{cmd:"ARCHIVE_SUPPORT",data:{}},e((t=>{if(t&&t.error)return e.abort(),void s(t)})))})).nThen((e=>{t.Store.adminRpc(null,{cmd:"ADMIN_DECREE",data:["SET_SUPPORT_KEYS",["","",""]]},e((function(t){if(t&&t.error)return e.abort(),void s(t)})))})).nThen((e=>{A(t,0,0,e((t=>{if(!t||t.error)return e.abort(),void s();i=t[0]||{}})))})).nThen((()=>{let e=a;Object.keys(i).forEach((n=>{e=e((e=>{t.Store.adminRpc(null,{cmd:"REMOVE_MODERATOR",data:n},e((e=>{e&&e.error&&console.error("Error removing moderator data",n,e.error)})))})).nThen})),e((()=>{s()}))}))}(_,0,0,c):function(t,n,r,o){let a=t.store.proxy,i=e.find(a,["mailboxes","supportteam","keys","curvePublic"]),s=e.find(a,["mailboxes","supportteam","keys","curvePrivate"]);h(t,!1,{},((e,t)=>{e?o({error:e}):(i&&t.theirPublic!==i&&(s=void 0),o({curvePrivate:s,curvePublic:t.theirPublic}))}))}(_,0,0,c):function(n,r,o,a){let i=n.store.proxy,s=e.find(i,["mailboxes","supportadmin"]);if(!s)return void a({error:"ENOENT"});if(!n.adminRdyEvt)return void a({error:"EFORBIDDEN"});let c=r.messages,u=r.hashes,l=c[0],f=c[c.length-1];l?n.adminRdyEvt.reg((()=>{let r={name:e.find(l,["sender","name"]),notifications:e.find(l,["sender","notifications"]),curvePublic:e.find(l,["sender","curvePublic"]),kemPublic:e.find(l,["sender","kemPublic"]),channel:t.createChannelId(),title:l.title,time:f.time,ticket:{legacy:!0,title:l.title,sender:l.sender,messages:c}};y(n,r,!0,(e=>{e&&e.error?a(e):(u.forEach((e=>{s.viewed.push(e)})),n.Store.onSync(null,(function(){a({done:!0})})))}))})):a({error:"EINVAL"})}(_,l,0,c):function(e,t,n,r){let o=e.store.proxy;e.store.mailbox.close("supportadmin",(function(){delete o.mailboxes.supportadmin,e.Store.onSync(null,(function(){r({done:!0})}))}))}(_,0,0,c):function(t,n,r,o){let a=t.store.proxy,i=e.find(a,["mailboxes","supportadmin"]);if(!i)return void o({error:"ENOENT"});let s=e.clone(i);s.lastKnownHash=void 0,s.viewed=[],t.store.mailbox.open("supportadmin",s,(function(e){t.store.mailbox.close("supportadmin",(function(){})),o(e)}),!0,{dump:!0})}(_,0,0,c):E(_,0,0,c):((e,t,r,o)=>{e.adminRdyEvt?e.adminRdyEvt.reg((()=>{let r=e.adminDoc.proxy.tickets,a=t.channel;(r.active[a]||r.pending[a]||r.closed[a]).tags=t.tags||[],n.whenRealtimeSyncs(e.adminDoc.realtime,(function(){let e=[];["active","pending","closed"].forEach((t=>{let n=r[t];Object.keys(n).forEach((t=>{(n[t].tags||[]).forEach((t=>{e.includes(t)||e.push(t)}))}))})),o({done:!0,allTags:e})}))})):o({error:"EFORBIDDEN"})})(_,l,0,c):((e,t,n,r)=>{if(!e.adminRdyEvt)return void r({error:"EFORBIDDEN"});let o=t.tags||[];e.adminRdyEvt.reg((()=>{let t=e.adminDoc.proxy.tickets;if(!o.length)return void r({all:!0});let n=[];["active","pending","closed"].forEach((e=>{let r=t[e];Object.keys(r).forEach((e=>{(r[e].tags||[]).some((e=>o.includes(e)))||n.push(e)}))})),r({tickets:n})}))})(_,l,0,c):((t,n,r,o)=>{if(!t.adminRdyEvt)return void o({error:"EFORBIDDEN"});let a=n.tags||[],i=(n.text||"").toLowerCase();t.adminRdyEvt.reg((()=>{let n=t.adminDoc.proxy.tickets,r={},s=(t,n,o)=>{let a=e.clone(n);a.category=o,r[t]=a};["active","pending","closed"].some((t=>{let o=n[t];return Object.keys(o).some((n=>{let c=o[n];if(a.length&&!(c.tags||[]).some((e=>a.includes(e))))return;let u=e.hexToBase64(n).slice(0,10);if(i===u)return r={},s(n,c,t),!0;(!i||c.title.toLowerCase().includes(i))&&s(n,c,t)}))})),o({tickets:r})}))})(_,l,0,c):function(e,t,n,r){if(!e.adminRdyEvt)return void r({error:"EFORBIDDEN"});let o=t.id;e.adminRdyEvt.reg((()=>{let t=e.adminDoc.proxy,n=(t.recorded=t.recorded||{})[o];n&&(n.count=(n.count||0)+1),r()}))}(_,l,0,c):function(e,t,r,o){if(!e.adminRdyEvt)return void o({error:"EFORBIDDEN"});let a=t.id,i=t.content,s=Boolean(t.remove);e.adminRdyEvt.reg((()=>{let t=e.adminDoc.proxy,r=t.recorded=t.recorded||{};s?delete r[a]:r[a]={content:i,count:0},n.whenRealtimeSyncs(e.adminDoc.realtime,(function(){o({done:!0})}))}))}(_,l,0,c):function(t,n,r,o){t.adminRdyEvt?t.adminRdyEvt.reg((()=>{let n=t.adminDoc.proxy,r=n.recorded=n.recorded||{};o({messages:e.clone(r)})})):o({error:"EFORBIDDEN"})}(_,0,0,c):function(e,t,r,o){if(!e.adminRdyEvt)return void o({error:"EFORBIDDEN"});let a=t.channel,i=t.from,s=t.to;e.adminRdyEvt.reg((()=>{let t=e.adminDoc.proxy,r=t.tickets[i],c=t.tickets[s];if(!i||!s)return void o({error:"EINVAL"});let u=r[a];u&&!c[a]?(c[a]=u,delete r[a],n.whenRealtimeSyncs(e.adminDoc.realtime,(function(){o({moved:!0})}))):o({error:"CANT_MOVE"})}))}(_,l,0,c):function(e,t,r,o){if(!e.adminRdyEvt)return void o({error:"EFORBIDDEN"});let a=t.supportKey;e.adminRdyEvt.reg((()=>{let r=e.adminDoc.proxy;r.oldKeys&&r.oldKeys[a]&&(t.adminCurvePrivate=r.oldKeys[a].curvePrivate),v(e,t,!0,(r=>{if(r)o({error:r});else{var a=e.adminDoc.proxy,i=a.tickets.active[t.channel]||a.tickets.pending[t.channel];i.time=+new Date,i.lastAdmin=!0,a.tickets.closed[t.channel]=i,delete a.tickets.active[t.channel],delete a.tickets.pending[t.channel],n.whenRealtimeSyncs(e.adminDoc.realtime,(function(){o({closed:!0})}))}}))}))}(_,l,0,c):function(e,t,n,r){if(!e.adminRdyEvt)return void r({error:"EFORBIDDEN"});let o=t.supportKey;e.adminRdyEvt.reg((()=>{let n=e.adminDoc.proxy;n.oldKeys&&n.oldKeys[o]&&(t.adminCurvePrivate=n.oldKeys[o].curvePrivate),v(e,t,!0,((n,o)=>{if(n)r({error:n});else{var a=e.adminDoc.proxy,i=a.tickets.active[t.channel]||a.tickets.pending[t.channel];i.time=o,i.lastAdmin=!0,r({sent:!0})}}))}))}(_,l,0,c):function(t,n,r,o){let a=n.supportKey;t.adminRdyEvt.reg((()=>{let r=t.adminDoc.proxy;r.oldKeys&&r.oldKeys[a]&&(n.adminCurvePrivate=r.oldKeys[a].curvePrivate),p(t,n,!0,(function(r,a){if(r)return void o({error:r});var i=t.adminDoc.proxy;if(!Array.isArray(a)||!a.length)return void o(a);a.sort(((e,t)=>e.time-t.time));let s=a[a.length-1],c=a.some((t=>{let r=e.find(t,["sender","curvePublic"]);if(n.curvePublic===r)return e.find(t,["sender","quota","plan"])}));var u=i.tickets.active[n.channel];u&&(s.legacy&&(s=Array.isArray(s.messages)&&s.messages[s.messages.length-1]),u.time=s.time,u.premium=c,s.sender&&(u.lastAdmin=!s.sender.blockLocation),s.close&&(i.tickets.closed[n.channel]=u,delete i.tickets.active[n.channel],d(t,!0,"UPDATE_TICKET",n.channel))),o(a)}))}))}(_,l,0,c):function(t,n,r,o){t.adminRdyEvt?(t.clients[r]||(t.clients[r]={admin:!0}),t.adminRdyEvt.reg((()=>{var r=t.adminDoc.proxy;return"pending"===n.type?o(e.clone(r.tickets.pending)):"closed"===n.type?o(e.clone(r.tickets.closed)):void o(e.clone(r.tickets.active))}))):o({error:"EFORBIDDEN"})}(_,l,r,c):function(e,t,n,r){e.adminRdyEvt?e.adminRdyEvt.reg((()=>{y(e,t,!0,r)})):r({error:"EFORBIDDEN"})}(_,l,0,c):function(e,t,n,r){let o=e.supportData,a=t.channel;o[a]&&o[a].closed?(delete o[a],r({deleted:!0})):r({error:"ENOTCLOSED"})}(_,l,0,c):function(e,t,n,r){v(e,t,!1,(e=>{r(e?{error:e}:{closed:!0})}))}(_,l,0,c):function(e,t,n,r){v(e,t,!1,(e=>{r(e?{error:e}:{sent:!0})}))}(_,l,0,c):function(t,n,r,o){var i=[],s=a;t.clients[r]||(t.clients[r]={admin:!1}),Object.keys(t.supportData).forEach((function(n){s=s((r=>{var o=e.clone(t.supportData[n]);p(t,{channel:n,curvePublic:o.curvePublic,kemPublic:o.kemPublic},!1,r(((e,r)=>{if(e){if("EDELETED"===e.type)return void delete t.supportData[n];o.error=e}else o.messages=r,r.length&&r[r.length-1].close&&(t.supportData[n].closed=!0,o.closed=!0);o.id=n,i.push(o)})))})).nThen})),s((()=>{i.sort(((e,t)=>e.closed&&t.closed?e.time-t.time:e.closed?1:t.closed?-1:e.time-t.time)),o({tickets:i})}))}(_,0,r,c):function(e,t,n,r){y(e,t,!1,r)}(_,l,0,c)},u},l})(Ne(),Fe(),mt(),sn(),cn(),Dt(),ye(),S(),I(),O()),Jn}function hr(){if(Qn)return Wn;Qn=1;var e,t,n;return e=ye(),n=function(t,n,r,o){var a=n.channel,i=n.secret;i.keys.cryptKey&&(i.keys.cryptKey=function(e){for(var t=Object.keys(e).length,n=new Uint8Array(t),r=0;r{e.pending[t.uid]?(delete e.pending[t.uid],r(n)):setTimeout(r,1e3)})),e.emit("MESSAGE",i,a.clients.filter((function(e){return e!==n})))}else r({error:"NO_CHAN"})}else r({error:"NO_CLIENT"})}(a,i,e,r):n(a,i,e,r)},o},Wn=t}function pr(){if(Xn)return zn;Xn=1;var e,t;return t=function(e,t,n){var r=e.clients[t];if(r){var o=e.channels[r.channel];o?(n(),o.history.forEach((function(n){e.emit("MESSAGE",{msg:n,validateKey:o.validateKey},[t])})),e.emit("HISTORY_SYNCED",{},[t])):n({error:"ENOCHAN"})}else n({error:"ENOENT"})},(e={}).init=function(e,n){var r={},o={store:e,emit:n,channels:{},clients:{}};return r.removeClient=function(e){!function(e,t){var n,r=function(e){return e!==t};for(var o in e.channels)(n=e.channels[o]).clients=n.clients.filter(r),0===n.clients.length&&(n.wc&&n.wc.leave(),delete e.channels[o]);if(e.clients[t]){var a=e.clients[t].channel,i=e.channels[a];i&&e.emit("LEAVE",{id:t},[i.clients[0]]),delete e.clients[t]}}(o,e)},r.leavePad=function(e){!function(e,t){Object.keys(e.channels).some((function(n){var r=e.channels[n];if(r.padChan===t)return r.wc&&r.wc.leave(),delete e.channels[n],!0}))}(o,e)},r.execCommand=function(e,n,r){var a=n.cmd,i=n.data;"SEND_MESSAGE"!==a?"UPDATE_HASH"!==a?"OPEN_CHANNEL"!==a?"GET_HISTORY"!==a?"REENCRYPT"!==a||function(e,t,n,r){var o=t.channel,a=e.store.network,i=function(e){var n=a.historyKeeper,o={metadata:t.metadata},i=["GET_HISTORY",e.id,o];a.sendto(n,JSON.stringify(i)),t.msgs.forEach((function(t){e.bcast(t)})),e.leave(),r()};e.store.anon_rpc.send("IS_NEW_CHANNEL",o,(function(e,t){var n;e?r({error:e}):(t&&t.length&&"object"==typeof t[0]?n=t[0].isNew:r({error:"INVALID_RESPONSE"}),n?a.join(o).then(i,(function(e){r({error:e})})):r({error:"EEXISTS"}))}))}(o,i,0,r):t(o,e,r):function(e,n,r,o){var a=n.channel,i=n.padChan,s=e.store.network,c=!0,u=e.clients[r];if(u)o();else{u=e.clients[r]={channel:a};var l=e.channels[a];if(l)return u.id||(u.id=l.wc.myID+"-"+r),t(e,r,(function(){e.emit("READY",l.clients,[r])})),l.clients.push(r),void o();var f=Math.floor(1e6*Math.random()),d=function(t){e.channels[a]=e.channels[a]||{history:[],validateKey:n.validateKey},(l=e.channels[a]).padChan=i,u.id||(u.id=t.myID+"-"+r),l.clients&&l.clients.forEach((function(n){e.clients[n]&&(e.clients[n].id=t.myID+"-"+n)})),t.on("join",(function(){})),t.on("leave",(function(){})),t.on("message",(function(t){l.history.push(t),e.emit("MESSAGE",{msg:t,validateKey:l.validateKey},l.clients)})),l.wc=t,l.sendMsg=function(e,n){n=n||function(){};var r=e.slice(0,64);t.bcast(e).then((function(){l.history.push(e),l.lastKnownHash=r,n()}),(function(e){n({error:e})}))},c&&(l.clients=[r],l.lastCpHash=n.lastCpHash,c=!1,o());var d=s.historyKeeper,h={txid:f,lastKnownHash:l.lastKnownHash||l.lastCpHash,metadata:{forcePlaceholder:!0,validateKey:n.validateKey,owners:n.owners,expire:n.expire}},p=["GET_HISTORY",t.id,h];d&&s.sendto(d,JSON.stringify(p)).then((function(){}),(function(e){console.error(e)}))};s.on("message",(function(t,n){if(e.channels[a]&&n===s.historyKeeper){var r;try{r=JSON.parse(t)}catch(e){}if(r&&!(r.txid&&r.txid!==f||r.channel&&r.channel!==a))if(r.validateKey&&r.channel)l.validateKey||(l.validateKey=r.validateKey);else if(r.state&&1===r.state&&r.channel)e.emit("READY",l.clients,l.clients);else if(r.error&&r.channel)e.emit("READY",l.clients,l.clients);else if(!(Array.isArray(r)&&r[0]&&r[0]!==f||(t=r[4],r[3]!==a))){var o=t.slice(0,64);o!==l.lastKnownHash&&o!==l.lastCpHash&&(l.lastKnownHash=o,e.emit("MESSAGE",{msg:t},l.clients),l.history.push(t))}}})),s.join(a).then(d,(function(e){o({error:e})})),s.on("reconnect",(function(){e.channels[a]&&s.join(a).then(d,(function(e){console.error(e)}))}))}}(o,i,e,r):function(e,t,n,r){var o=e.clients[n];if(o){var a=e.channels[o.channel];if(a){var i=t,s=-1;a.history.some((function(e,t){if(e.slice(0,64)===i)return s=t+1,!0})),-1!==s&&(a.history=a.history.slice(s)),r()}else r({error:"INVALID_CHANNEL"})}else r({error:"NOT_IN_CHANNEL"})}(o,i,e,r):function(e,t,n,r){var o=e.clients[n];if(o){var a=e.channels[o.channel];if(a){var i=function(o){o&&o.error?r(o):(e.emit("MESSAGE",{msg:t.msg},a.clients.filter((function(e){return e!==n}))),r())};t.isCp?a.sendMsg(t.isCp,i):a.sendMsg(t.msg,i)}else r({error:"INVALID_CHANNEL"})}else r({error:"NOT_IN_CHANNEL"})}(o,i,e,r)},r},zn=e}function yr(){if($n)return Zn;$n=1;return Zn=((e,t,n,r,o,a,i,s)=>{var c={};const u=e.mkEvent(!0);return c.init=function(c,l,f){var d={},h=c.store;if(h.loggedIn&&h.proxy.edPublic){var p={Store:c.Store,store:h,pinPads:c.pinPads,updateMetadata:c.updateMetadata,emit:f,onReadyHandlers:[],clients:[]};return p.profile=h.proxy.profile=h.proxy.profile||{},function(e,n){var r=e.profile;if(r.edit&&r.view)setTimeout(n);else{var o=t.createRandomHash("profile"),a=t.getSecrets("profile",o);e.pinPads([a.channel],(function(e){e.error?n(e.error):(r.edit=t.getEditHashFromKeys(a),r.view=t.getViewHashFromKeys(a),setTimeout(n))}))}}(p,l((function(r){r||function(r){var o=r.profile,c=t.getSecrets("profile",o.edit),l=i.createEncryptor(c.keys),f={data:{},network:r.store.network,channel:c.channel,crypto:l,owners:[r.store.proxy.edPublic],ChainPad:s,validateKey:c.keys.validateKey||void 0,userName:"profile",classic:!0},d=a.create(f);d.proxy.on("create",(function(){})).on("ready",(function(){if(d.proxy.name=r.store.proxy[n.displayNameKey]||"",r.listmap=d,d.proxy.curvePublic||(d.proxy.curvePublic=r.store.proxy.curvePublic),d.proxy.notifications||(d.proxy.notifications=e.find(r.store.proxy,["mailboxes","notifications","channel"])),d.proxy.edPublic||(d.proxy.edPublic=r.store.proxy.edPublic),!d.proxy.proof){let t=c.channel,n=e.decodeUTF8(t),o=e.decodeBase64(r.store.proxy.edPrivate),a=i.Nacl.sign(n,o),s=e.encodeBase64(a);d.proxy.proof=s}r.onReadyHandlers.length&&(r.onReadyHandlers.forEach((function(e){try{e(d.proxy)}catch(e){console.error(e)}})),r.onReadyHandlers=[]),u.fire()})).on("change",[],(function(){r.emit("UPDATE",d.proxy,r.clients)}))}(p)}))),d.setName=function(e){!function(e,t){e.listmap.proxy.name=t,r.whenRealtimeSyncs(e.listmap.realtime,(function(){e.listmap&&e.emit("UPDATE",e.listmap.proxy,e.clients)}))}(p,e)},d.removeClient=function(e){!function(e,t){var n=e.clients.indexOf(t);-1!==n&&e.clients.splice(n,1)}(p,e)},d.update=function(){p.listmap&&p.emit("UPDATE",p.listmap.proxy,p.clients)},d.execCommand=function(e,t,n){console.log(t);var a=t.cmd,i=t.data;"SUBSCRIBE"!==a?"SET"!==a||function(e,t,n,a){u.reg((()=>{var i=t.key,s=t.value;i&&(e.listmap.proxy[i]=s,r.whenRealtimeSyncs(e.listmap.realtime,(function(){e.emit("UPDATE",e.listmap.proxy,e.clients.filter((function(e){return e!==n}))),"badge"===i&&e.Store.set(null,{key:["profile","badge"],value:s||void 0},(()=>{o.updateMyData(e.store),e.updateMetadata()})),a(e.listmap.proxy)})))}))}(p,i,e,n):function(e,t,n,r){-1===e.clients.indexOf(n)&&e.clients.push(n),e.listmap?r(e.listmap.proxy):e.onReadyHandlers.push((function(e){r(e)}))}(p,0,e,n)},d}},c})(Ne(),Fe(),Oe(),mt(),Zt(),S(),ye(),I()),Zn}function vr(){if(tr)return er;tr=1;return er=function(e,t,n,r,o,a){var i={},s=function(e){return Boolean(e&&"object"==typeof e&&!Array.isArray(e))},c=function(e){return e.slice(0,64)},u=function(t,n){var r=e.find(n,[t,"role"]);return-1!==["OWNER","ADMIN"].indexOf(r)},l=function(t,n,r){var o=e.find(r,[t,"role"]);return!!o&&(!!function(e){return-1!==["OWNER","ADMIN","MEMBER","VIEWER"].indexOf(e)}(n)&&("OWNER"===o||"ADMIN"===o&&-1!==["ADMIN","MEMBER","VIEWER"].indexOf(n)))},f=function(e){return"string"==typeof e&&44===e.length},d=i.commands={};d.ADD=function(e,t,n){if(!s(e))throw new Error("INVALID ARGS");if(!n.internal.initialized)throw new Error("UNITIALIZED");if(void 0===n.state.members)throw new Error("CANNOT_ADD_TO_UNITIALIZED_ROSTER");var r=n.state.members;Object.keys(e).forEach((function(n){if(!f(n))throw console.log(n,n.length),new Error("INVALID_CURVE_KEY");if(!s(e[n]))throw new Error("INVALID_CONTENT");if(r[n])throw new Error("ALREADY_PRESENT");var o=e[n];if("string"!=typeof o.role&&(o.role="MEMBER"),!l(t,o.role,r))throw new Error("INSUFFICIENT_PERMISSIONS");if("string"!=typeof o.displayName)throw new Error("DISPLAYNAME_REQUIRED");if("string"!=typeof o.notifications)throw new Error("NOTIFICATIONS_REQUIRED")}));var o=!1;return Object.keys(e).forEach((function(t){o=!0,r[t]=e[t]})),o},d.RM=function(t,n,r){if(!Array.isArray(t))throw new Error("INVALID_ARGS");if(void 0===r.state.members)throw new Error("CANNOT_RM_FROM_UNITIALIZED_ROSTER");var o=r.state.members;t.forEach((function(t){if(!f(t))throw new Error("INVALID_CURVE_KEY");if(t!==n){var r=o[t].role;if(!function(t,n,r){var o=e.find(r,[t,"role"]);return!!o&&("OWNER"===o||"ADMIN"===o&&-1!==["ADMIN","MEMBER","VIEWER"].indexOf(n))}(n,r,o))throw new Error("INSUFFICIENT_PERMISSIONS")}}));var a=!1;return t.forEach((function(e){o[e]&&(a=!0,delete o[e])})),a},d.DESCRIBE=function(t,n,o){if(!t||"object"!=typeof t||Array.isArray(t))throw new Error("INVALID_ARGUMENTS");if(void 0===o.state.members)throw new Error("NOT_READY");var a=o.state.members;Object.keys(t).forEach((function(r){if(!f(r))throw new Error("INVALID_ID");if(!a[r])throw new Error("NOT_PRESENT");if(!function(t,n,r){if(!r[n])return!1;if(t===n&&r[n])return!0;var o=e.find(r,[t,"role"]),a=e.find(r,[n,"role"]);return!!o&&("OWNER"===o||"ADMIN"===o&&"OWNER"!==a)}(n,r,a))throw new Error("INSUFFICIENT_PERMISSIONS");var o=t[r];if(!s(o))throw new Error("INVALID_ARGUMENTS");var i=e.clone(a[r]);if("string"==typeof o.role&&!function(t,n,r,o){return!(t!==n||!o[n])&&("MEMBER"===e.find(o,[t,"role"])?"VIEWER"===r:void 0)}(n,r,o.role,a)&&!l(n,o.role,a))throw new Error("INSUFFICIENT_PERMISSIONS");if("string"!=typeof i.displayName&&"string"!=typeof o.displayName)throw new Error("DISPLAYNAME_REQUIRED");if(-1===["undefined","string"].indexOf(typeof o.displayName))throw new Error("INVALID_DISPLAYNAME");if("string"!=typeof i.notifications&&"string"!=typeof o.notifications)throw new Error("NOTIFICATIONS_REQUIRED");if(-1===["undefined","string"].indexOf(typeof o.notifications))throw new Error("INVALID_NOTIFICATIONS")}));var i=!1;return Object.keys(t).forEach((function(n){var o=e.clone(a[n]),s=t[n];Object.keys(s).forEach((function(e){void 0===o[e]||null!==s[e]?o[e]=s[e]:delete o[e]})),r(o)!==r(a[n])&&(i=!0,a[n]=o)})),i},d.CHECKPOINT=function(e,t,n){if(!s(e))throw new Error("INVALID_CHECKPOINT_STATE");if(!n.internal.initialized){n.state=e;var o=n.state.metadata=n.state.metadata||{};return o.topic=o.topic||"",o.name=o.name||"",o.avatar=o.avatar||"",n.internal.initialized=!0,!0}if(r(e)!==r(n.state))throw new Error("CHECKPOINT_DOES_NOT_MATCH_PREVIOUS_STATE");if(!u(t,n.state.members))throw new Error("INSUFFICIENT_PERMISSIONS");return n.state=e,!0};var h=["avatar","name","topic"];d.METADATA=function(t,n,r){if(!s(t))throw new Error("INVALID_ARGS");if(!function(t,n){var r=e.find(n,[t,"role"]);return Boolean(r&&-1!==["OWNER","ADMIN"].indexOf(r))}(n,r.state.members))throw new Error("INSUFFICIENT_PERMISSIONS");Object.keys(t).forEach((function(e){if(null===t[e]){if(-1===h.indexOf(e))return;throw new Error("CANNOT_REMOVE_MANDATORY_METADATA")}if("string"!=typeof t[e])throw new Error("INVALID_ARGUMENTS")}));var o=!1;return Object.keys(t).forEach((function(e){void 0!==r.state.metadata[e]&&null===t[e]&&(o=!0,delete r.state.metadata[e]),t[e]!==r.state.metadata[e]&&(o=!0,r.state.metadata[e]=t[e])})),o},d.INVITE=function(e,t,n){if(!s(e))throw new Error("INVALID_ARGS");if(!n.internal.initialized)throw new Error("UNINITIALIED");if(void 0===n.state.members)throw new Error("CANNOT+INVITE_TO_UNINITIALIED_ROSTER");var r=n.state.members;Object.keys(e).forEach((function(n){if(!f(n))throw console.log(n,n.length),new Error("INVALID_CURVE_KEY");if(!s(e[n]))throw new Error("INVALID_CONTENT");if(r[n])throw new Error("ARLEADY_PRESENT");var o=e[n];if("string"!=typeof o.role&&(o.role="VIEWER"),void 0===o.pending&&(o.pending=!0),!l(t,o.role,r))throw new Error("INSUFFICIENT_PERMISSIONS");if("string"!=typeof o.displayName||!o.displayName)throw new Error("DISPLAYNAME_REQUIRED")}));var o=!1;return Object.keys(e).forEach((function(t){o=!0,r[t]=e[t]})),o},d.ACCEPT=function(t,n,r){if(!r.internal.initialized)throw new Error("UNINITIALIED");if(void 0===r.state.members)throw new Error("CANNOT_ADD_TO_UNINITIALIED_ROSTER");var o=r.state.members;if(!s(o[n]))throw new Error("INSUFFICIENT_PERMISSIONS");if(!o[n].pending)throw new Error("ALREADY_PRESENT");if("string"!=typeof t)throw new Error("INVALID_ARGS");if(!f(t))throw new Error("INVALID_CURVE_KEY");var a=t;if(void 0!==o[a])throw new Error("MEMBER_ALREADY_PRESENT");var i=e.clone(o[n]);delete i.remaining,delete i.totalUses,delete i.inviteChannel,delete i.previewChannel,o[a]=i;var c=o[n].remaining||1;return-1===c||(c>1?o[n].remaining=c-1:delete o[n]),!0};var p=function(e,t,n){if(!Array.isArray(e)||"string"!=typeof t)throw new Error("INVALID ARGUMENTS");var r=e[0];if("function"!=typeof d[r])throw new Error("INVALID_COMMAND");return d[r](e[1],t,n)},y=function(t,n,r){return p(t,n,e.clone(r))};return i.create=function(t,i){if("function"!=typeof i)throw new Error("EXPECTED_CALLBACK");var l=e.once(e.mkAsync(i));if(t.network)if(t.channel&&"string"==typeof t.channel&&32===t.channel.length)if(t.keys&&"object"==typeof t.keys)if(t.store){var d=e.response((function(e,t){console.error("ROSTER_RESPONSE__"+e,t)})),h=t.store,v=t.keys,m=v.myCurvePublic,g=t.channel,E=t.lastKnownHash||-1;t.newTeam&&(E=void 0);var b={state:{members:{},metadata:{}},internal:{initialized:!1,sinceLastCheckpoint:0,lastCheckpointHash:E}},A={},_={change:e.mkEvent(),checkpoint:e.mkEvent()};A.on=function(e,t){if("object"!=typeof _[e])throw new Error("unsupported event");return _[e].reg(t),A},A.off=function(e,t){if("object"!=typeof _[e])throw new Error("unsupported event");return _[e].unreg(t),A},A.once=function(e,t){if("object"!=typeof _[e])throw new Error("unsupported event");var n=function(){t.apply(null,Array.prototype.slice.call(arguments)),_[e].unreg(n)};return _[e].reg(n),A},A.getState=function(){return e.clone(b.state)},A.getLastCheckpointHash=function(){return b.internal.lastCheckpointHash||-1};var w=function(){b.internal.pendingCheckpointId&&(d.clear(b.internal.pendingCheckpointId),delete b.internal.pendingCheckpointId),clearTimeout(b.internal.checkpointTimeout),delete b.internal.checkpointTimeout};A.stop=function(){b.internal.cpNetflux&&"function"==typeof b.internal.cpNetflux.stop?(b.internal.cpNetflux.stop(),w()):console.log("FAILED TO LEAVE")};var O,D,S,T=!1,C=function(){if(t.onCacheReady){var e=b.state;if(Object.keys(e.members||{}).length)t.onCacheReady(A);else{try{b.internal.cpNetflux.resetCache()}catch(e){console.error(e)}t.onCacheReady({error:"CORRUPTED"})}}},x=function(){T=!0,l(void 0,A)},I=function(e){e&&"EUNKNOWN"===e.type||(T?console.error("CHANNEL_ERROR",e):l(e))},N=function(e){e.state||(T=!1)},P=function(){console.log("ROSTER CONNECTED")},k=function(){return Boolean(T&&m)},R=function(t,n,r,o,a,i){O!==a&&b.internal.sinceLastCheckpoint++,O=a;var s=e.tryParse(t);if(s){var l,f;try{l=p(s,i,b)}catch(e){f=e.message}var h=c(a);if(d.expected(h)){if(f)return void d.handle(h,[f]);try{l?d.handle(h,[void 0,A.getState()]):(d.handle(h,["NO_CHANGE"]),console.log(t))}catch(e){console.log("CAUGHT",e)}}if("CHECKPOINT"===s[0]&&l?(k()&&_.checkpoint.fire(a),b.internal.sinceLastCheckpoint=0,b.internal.lastCheckpointHash=a):l&&k()&&_.change.fire(),w(),k()&&function(e,t){if(!u(e,t.state.members))return!1;var n=t.internal.sinceLastCheckpoint;return!(!n||"number"!=typeof n||n<25)}(m,b)){var y=1e3*Math.floor(20*Math.random())+5e3;b.internal.checkpointTimeout=setTimeout((function(){b.internal.pendingCheckpointId=A.checkpoint((function(e){e&&console.error(e)}))}),y)}}else console.error("could not parse")},M=function(t,n){var r=e.tryParse(t);return"CHECKPOINT"===r[0]&&y(r,n,b)},F=function(e,t){if(k()){var n=h.anon_rpc;if(n){var o=!1;try{o=y(e,v.myCurvePublic,b)}catch(e){return void t(e.message)}if(o){var a=S.encrypt(r(e)),i=c(a);return d.expect(i,(function(e,n){e?t(e):t(void 0,n,i)}),3e4),n.send("WRITE_PRIVATE_MESSAGE",[g,a],(function(e){if(e)return d.handle(i,[e.message||e])})),i}t("NO_CHANGE")}else t("ANON_RPC_NOT_READY")}else t("NOT_READY")};A.init=function(t,n){var r=e.once(e.mkAsync(n));if(b.internal.initialized)r("ALREADY_INITIALIZED");else if(s(t)){var o=e.clone(t);o.role="OWNER";var a={};a[m]=o,F(["CHECKPOINT",{members:a}],r)}else r("INVALID_ARGUMENTS")},A.checkpoint=function(t){var n=e.once(e.mkAsync(t));F(["CHECKPOINT",e.clone(b.state)],n)},A.add=function(t,n){var r=e.once(e.mkAsync(n));if(!b.internal.initialized)return r("UNINITIALIZED");if(s(t)){var o=e.clone(t);Object.keys(o).forEach((function(e){if(!f(e)||s(b.state.members[e]))return delete o[e]})),F(["ADD",o],r)}else r("INVALID_ARGUMENTS")},A.remove=function(t,n){var r=e.once(e.mkAsync(n)),o=b.state;if(!o)return r("UNINITIALIZED");if(Array.isArray(t)){var a=e.clone(t),i=[],s=Object.keys(o.members);a.forEach((function(e){-1!==s.indexOf(e)&&i.push(e)})),F(["RM",i],r)}else r("INVALID_ARGUMENTS")},A.describe=function(t,n){var r=e.once(e.mkAsync(n)),o=b.state;if(!o)return r("UNINITIALIZED");if(s(t)){var a=e.clone(t);Object.keys(a).some((function(e){var t=a[e];if(s(t)||delete a[e],!s(o.members[e]))return!0;Object.keys(t).forEach((function(n){t[n]===o.members[e][n]&&delete t[n]}))}))?r("INVALID_ARGUMENTS"):F(["DESCRIBE",a],r)}else r("INVALID_ARGUMENTS")},A.metadata=function(t,n){var r=e.once(e.mkAsync(n)),o=b.state.metadata;if(s(t)){var a=e.clone(t);Object.keys(a).forEach((function(e){a[e]===o[e]&&delete a[e]})),F(["METADATA",a],r)}else r("INVALID_ARGUMENTS")},A.invite=function(t,n){var r=e.once(e.mkAsync(n));if(!b.state)return r("UNINITIALIZED");if(!b.internal.initialized)return r("UNINITIALIZED");if(s(t)){var o=e.clone(t);Object.keys(o).forEach((function(e){if(!f(e)||s(b.state.members[e]))return delete o[e]})),F(["INVITE",o],r)}else r("INVALID_ARGUMENTS")},A.accept=function(t,n){var r=e.once(e.mkAsync(n));"string"==typeof t&&f(t)?F(["ACCEPT",t],r):r("INVALID_ARGUMENTS")},o((function(e){h.anon_rpc&&h.anon_rpc.send("GET_METADATA",g,(function(t,n){if(t)return e.abort(),void console.error(t);D=b.internal.metadata=n&&n[0]||void 0}))})).nThen((function(e){if(!t.keys.teamEdPublic&&D&&D.validateKey&&(t.keys.teamEdPublic=D.validateKey),!t.keys.teamEdPublic)return e.abort(),void l("NO_VALIDATE_KEY");if(!t.keys.teamKemPublic&&D.kemPublic&&(t.keys.teamKemPublic=D.kemPublic),!t.keys.teamDsaPublic&&D.dsaPublic&&(t.keys.teamDsaPublic=D.dsaPublic),!t.keys.teamKemPublic&&!t.keys.teamDsaPublic)return e.abort(),void l("NO_PQC_KEYS");try{S=a.Team.createEncryptor(t.keys)}catch(t){return e.abort(),void l(t)}})).nThen((function(){"string"==typeof E&&console.log("Synchronizing from checkpoint"),b.internal.cpNetflux=n.start({lastKnownHash:E,network:t.network,channel:t.channel,crypto:S,validateKey:t.keys.teamEdPublic,dsaValidateKey:t.keys.teamDsaPublic,owners:t.owners,Cache:t.Cache,isCacheCheckpoint:M,onCacheReady:C,onChannelError:I,onReady:x,onConnect:P,onConnectionChange:N,onMessage:R,noChainPad:!0})}))}else l("EXPECTED_STORE");else l("EXPECTED_CRYPTO_KEYS");else l("EXPECTED_CHANNEL");else l("EXPECTED_NETWORK")},i}(Ne(),Fe(),O(),Xt(),Dt(),ye()),er}function mr(){if(ar)return or;ar=1;return or=((e,t,n,r,o,a,i,s,c,u,l,f,d,h,p,y,v,m,g)=>{const E={};var b=e.mkEvent(!0),A=function(){},_=function(e,n,r,o){n&&(o||(r.on("change",["drive",a.SHARED_FOLDERS],(function(o,s,c){if(c.length>3&&"password"===c[3]){var u=c[2],l=r.drive[a.SHARED_FOLDERS][u],f=n.manager.user.userObject.getHref?n.manager.user.userObject.getHref(l):l.href,d=t.parsePadUrl(f),h=t.getSecrets(d.type,d.hash,o);return setTimeout((function(){i.updatePassword(e.Store,{oldChannel:h.channel,password:s,href:f},e.store.network,(function(){console.log("Shared folder password changed")}))})),!1}})),r.on("disconnect",(function(){n.offline=!0,n.sendEvent("NETWORK_DISCONNECT",n.id)})),r.on("reconnect",(function(){n.offline=!1,n.sendEvent("NETWORK_RECONNECT",n.id)}))),r.on("change",[],(function(t,r,i){if(o){if(i[0]===a.FILES_DATA&&"object"==typeof r&&r.channel&&!r.owners){var s=[r.channel];r.rtChannel&&s.push(r.rtChannel),r.lastVersion&&s.push(r.lastVersion),n.pin(s,(function(e){e&&e.error&&console.error(e.error)}))}if(i[0]===a.FILES_DATA&&"object"==typeof t&&t.channel&&!r){var c=[t.channel];n.manager.findChannel(t.channel).some((function(e){return e.fId!==o}))||(t.rtChannel&&c.push(t.rtChannel),t.lastVersion&&c.push(t.lastVersion),n.unpin(c,(function(e){e&&e.error&&console.error(e)})))}}t&&!r&&Array.isArray(i)&&(i[0]===a.FILES_DATA||"drive"===i[0]&&i[1]===a.FILES_DATA)&&setTimeout((function(){e.Store.checkDeletedPad(t&&t.channel)})),n.sendEvent("DRIVE_CHANGE",{id:o,old:t,new:r,path:i})})),r.on("remove",[],(function(e,t){n.sendEvent("DRIVE_REMOVE",{id:o,old:e,path:t})})))},w=function(e,t){var n=e.teams[t];if(n){try{n.listmap.stop()}catch(e){}try{n.roster.stop()}catch(e){}n.proxy={},n.stopped=!0,n?.rpc?.destroy(),delete e.teams[t],delete e.cache[t],delete e.store.proxy.teams[t],e.emit("LEAVE_TEAM",t,n.clients),e.updateMetadata(),e.store.calendar&&e.store.calendar.closeTeam(t),e.store.mailbox&&e.store.mailbox.close("team-"+t,(function(){}))}},O=function(e,t,n,r){t.rpc?r():n.edPrivate&&n.edPublic?h.create(e.store.network,n,(function(e,n){e?r(e):(t.rpc=n,t&&t.onRpcReadyEvt&&t.onRpcReadyEvt.fire(),r())}),d):r("EFORBIDDEN")},D=function(n,r,a,s,c,u,l){var f=e.once(e.mkAsync(l));if(n.cache[r])f();else{var d=a.proxy,h={id:r,proxy:d,listmap:a,clients:[],realtime:a.realtime,handleSharedFolder:function(e,t){!function(e,t,n,r){var o=e.teams[t];o&&(r?(o.sharedFolders[n]=r,_(e,o,r.proxy,n)):delete o.sharedFolders[n])}(n,r,e,t)},sharedFolders:{},roster:s,onRpcReadyEvt:e.mkEvent(!0),offline:!0};n.cache[r]=h,u&&h.clients.push(u),s.on("change",(function(){var t=s.getState(),o=e.find(n,["store","proxy","curvePublic"]);if(t.members&&Object.keys(t.members).length)if(t.members[o]){var a=e.find(n,["store","proxy","teams",r]);a&&(a.metadata=t.metadata),n.updateMetadata(),n.emit("ROSTER_CHANGE",r,h.clients)}else w(n,r);else console.error(JSON.stringify(t))})),s.on("checkpoint",(function(t){e.find(n,["store","proxy","teams",r,"keys","roster"]).lastKnownHash=t})),h.sendEvent=function(e,t,r){n.emit(e,t,h.clients.filter((function(e){return e!==r})))},h.getChatData=function(){var e=c.chat||{},n=e.edit||e.view;if(!n)return{};var o=t.getSecrets("chat",n);return{teamId:r,channel:o.channel,secret:o,validateKey:e.validateKey}},h.pin=function(e,t){c.drive.edPrivate?h.rpc?("function"!=typeof t&&console.error("expected a callback"),h.rpc.pin(e,(function(e,n){t(e?{error:e}:{hash:n})}))):t({error:"TEAM_RPC_NOT_READY"}):t({error:"EFORBIDDEN"})},h.unpin=function(e,t){c.drive.edPrivate?h.rpc?("function"!=typeof t&&console.error("expected a callback"),h.rpc.unpin(e,(function(e,n){t(e?{error:e}:{hash:n})}))):t({error:"TEAM_RPC_NOT_READY"}):t({error:"EFORBIDDEN"})};var p=n.store.proxy.teams[h.id],y=p.hash||p.roHash,v=t.getSecrets("team",y,p.password),m=h.manager=o.create(d.drive,{onSync:function(e){n.Store.onSync(r,e)},edPublic:c.drive.edPublic,pin:h.pin,unpin:h.unpin,loadSharedFolder:function(e,t,r,o){i.load({isNew:o,network:n.store.network||n.store.networkPromise,store:h,isNewChannel:n.Store.isNewChannel,Store:n.Store},e,t,r)},settings:{drive:e.find(n.store,["proxy","settings","drive"])},removeOwnedChannel:function(e,t){var o;"object"==typeof e?(e.teamId=r,o=e):o={channel:e,teamId:r},n.Store.pad.destroy("",o,t)},Store:n.Store,store:n.store},{teamId:h.id,outer:!0,edPublic:c.drive.edPublic,loggedIn:!0,log:function(e){h.sendEvent("DRIVE_LOG",e)},rt:h.realtime,editKey:v.keys.secondaryKey,readOnly:Boolean(!v.keys.secondaryKey)});h.secondaryKey=v&&v.keys.secondaryKey,h.userObject=m.user.userObject,g((function(e){n.teams[r]=h,_(n,h,d);var t=n.store.network||n.store.networkPromise;i.loadSharedFolders(n.Store,t,h,h.proxy.drive,h.userObject,e,(function(e){n.progress+=70/(n.numberOfTeams*e.max),n.updateProgress({progress:n.progress})}),!0)})).nThen((function(){n.store.modules.calendar&&n.store.modules.calendar.openTeam(r),f()}))}},S=function(n,r,o,a,s,c,u){var l,f=a.getState(),d=e.find(n,["store","proxy","teams",r]);d&&(d.metadata=f.metadata),delete n.nocache[r],n.store.proxy.teams[r]&&g((function(e){D(n,r,o,a,s,c,e()),l=n.teams[r]||n.cache[r],s.drive.edPrivate&&O(n,l,s.drive,e((function(){})))})).nThen((function(e){l.userObject.fixFiles(),i.checkMigration(l.secondaryKey,l.proxy?.drive,l.userObject,e()),i.loadSharedFolders(n.Store,n.store.network,l,l.proxy?.drive,l.userObject,e,(function(e){n.progress+=70/(n.numberOfTeams*e.max),n.updateProgress({progress:n.progress})}))})).nThen((function(){if(l.rpc){var o=function(t,n){var r=t.teams[n];if(!r)return null;var o=r.manager.getChannelsList("pin"),a=t.store.proxy.teams[n];o.push(`${a.channel}#drive`);var i=e.find(a,["keys","chat","channel"]),s=e.find(a,["keys","roster","channel"]),c=e.find(a,["keys","mailbox","channel"]);if(i&&o.push(i),s&&o.push(s),c&&o.push(c),r.proxy.calendars){var u=Object.keys(r.proxy.calendars).map((function(e){return r.proxy.calendars[e].channel}));o=o.concat(u)}var l=r.roster.getState();return l.members&&Object.keys(l.members).forEach((function(e){var t=l.members[e];t.inviteChannel&&t.pending&&o.push(t.inviteChannel),t.previewChannel&&t.pending&&o.push(t.previewChannel)})),o.sort(),o}(n,r),a=t.hashChannelList(o);l.rpc.getServerHash((function(e,t){e?console.warn(e):t!==a&&l.rpc.reset(o,(function(e){e&&console.warn(e)}))}))}})).nThen((function(){l.offline=!1,n.onReadyHandlers[r]&&n.onReadyHandlers[r].forEach((function(e){("function"==typeof e.cb&&e.cb(),e.cId)&&(-1===l.clients.indexOf(e.cId)&&l.clients.push(e.cId))})),delete n.onReadyHandlers[r],n.store.modules.calendar&&n.store.modules.calendar.openTeam(r),u()}))},T=function(e,t,n,r,o,a){var i=function(){(e.cache[t]||e.teams[t])&&w(e,t),delete e.store.proxy.teams[t],delete e.onReadyHandlers[t],o.abort(),a({error:"ENOENT"})};n&&e.store.anon_rpc.send("IS_NEW_CHANNEL",n,o((function(e,t){t&&t.length&&"object"==typeof t[0]&&t[0].isNew&&i()}))),r&&e.store.anon_rpc.send("IS_NEW_CHANNEL",r,o((function(e,t){t&&t.length&&"object"==typeof t[0]&&t[0].isNew&&i()})))},C=function(n,r,o,a,i){var l=e.once(e.mkAsync(a)),f=r.hash||r.roHash,h=t.getSecrets("team",f,r.password),v=y.createEncryptor(h.keys);r.roHash||(r.roHash=t.getViewHashFromKeys(h));var E,A,_=r.keys;if(!_.chat.validateKey&&_.chat.edit){var O=t.getSecrets("chat",_.chat.edit);_.chat.validateKey=O.keys.validateKey}var C={curvePublic:n.store.proxy.curvePublic,curvePrivate:n.store.proxy.curvePrivate,kemPublic:n.store.proxy.kemPublic,kemPrivate:n.store.proxy.kemPrivate},x=_.roster||{},I=x.edit?y.Team.deriveMemberKeys(x.edit,C):y.Team.deriveGuestKeys(x.view||"");g((function(e){if(i)return d.getChannelCache(h.channel,e((function(t,n){n&&n.c||(e.abort(),l({error:"NOCACHE"}))}))),void d.getChannelCache(I.channel,e((function(t,n){var r=n&&n.c,o=n&&n.k;o&&!I.teamEdPublic&&(I.teamEdPublic=o);var a=n&&n.dsaPublic;a&&!I.teamDsaPublic&&(I.teamDsaPublic=a),r||(e.abort(),l({error:"NOCACHE"}))})));n.Store.onReadyEvt.reg((()=>{T(n,o,h.channel,I.channel,e,l)}))})).nThen((function(t){var a={lm:!1,roster:!1,check:function(){this.lm&&this.roster&&i&&(n.progress+=30/n.numberOfTeams,n.updateProgress({progress:n.progress}),D(n,o,A,E,_,null,t(l)),this.check=function(){})}},u={data:{},readOnly:!Boolean(h.keys.signKey),network:n.store.network||n.store.networkPromise,channel:h.channel,crypto:v,ChainPad:m,Cache:d,metadata:{validateKey:h.keys.validateKey||void 0},userName:"team",classic:!0,onMetadataUpdate:function(){var e=n.teams[o];e&&n.emit("ROSTER_CHANGE",o,e.clients)}};(A=p.create(u)).proxy.on("cacheready",(function(){a.lm=!0,a.check()})),A.proxy.on("ready",t()),A.proxy.on("error",(function(e){e&&void 0!==e.loaded&&!e.loaded&&l({error:"ECONNECT"}),e&&e.error&&"EDELETED"===e.error&&w(n,o)})),s.create({network:n.store.network||n.store.networkPromise,channel:I.channel,keys:I,store:n.store,lastKnownHash:x.lastKnownHash,onCacheReady:function(e){if(i){if(e&&"CORRUPTED"===e.error)return console.error("Corrupted roster cache, cant load this team offline",r),A&&"function"==typeof A.stop&&A.stop(),t.abort(),void l({error:"CACHE_CORRUPTED_ROSTER"});E=e,a.roster=!0,a.check()}},Cache:d},t((function(r,o){if(r)return t.abort(),console.error(r),void l({error:"ROSTER_ERROR"});E=o,x.lastKnownHash=E.getLastCheckpointHash();var a=E.getState(),i=e.find(n,["store","proxy","curvePublic"]);a.members[i]&&b.reg((function(){if(x.edit){var e={},t=c.createData(n.store.proxy,!1);t.pending=!1,e[n.store.proxy.curvePublic]=t,E.describe(e,(function(e){e&&"NO_CHANGE"!==e&&console.error(e)}))}}))})))})).nThen((function(t){var a=E.getState(),i=e.find(n,["store","proxy","curvePublic"]);if(!a.members||!Object.keys(a.members).length)return A.stop(),E.stop(),A.proxy={},l({error:"EINVAL"}),t.abort(),console.error(JSON.stringify(a)),void u.send("ROSTER_CORRUPTED");if(!a.members[i])return A.stop(),E.stop(),A.proxy={},delete n.store.proxy.teams[o],n.updateMetadata(),l({error:"EFORBIDDEN"}),void t.abort();var s=a.members[i],c=e.find(r,["keys","drive","edPrivate"]);if(r.hash&&c||-1===["ADMIN","MEMBER"].indexOf(s.role))r.hash&&c||"OWNER"!==s.role||u.send("TEAM_RIGHTS_OWNER");else{console.warn("Missing edit rights: demote to viewer");var f={};f[n.store.proxy.curvePublic]={role:"VIEWER"},E.describe(f,(function(e){u.send("TEAM_RIGHTS_FIXED"),delete r.hash,delete r.keys.drive.edPrivate,delete r.keys.chat.edit,e&&"NO_CHANGE"!==e&&console.error(e)}))}})).nThen((function(){i||(n.progress+=30/n.numberOfTeams,n.updateProgress({progress:n.progress})),S(n,o,A,E,_,null,l)}))},x=function(t,n,r,o){var a=n.team;if(!((a.hash||a.roHash)&&a.channel&&a.password&&a.keys&&a.metadata))return void o({error:"EINVAL"});let i=t.store.proxy.teams;if(Object.values(i).some((e=>e.channel===a.channel)))o({error:"EEXISTS"});else{var s=e.createRandomInteger();t.store.proxy.teams[s]=a,t.onReadyHandlers[s]=[],C(t,a,s,(function(e){e&&e.error||console.debug("Team joined:"+s);var n=t.store.proxy.teams[s];t.store.mailbox.open("team-"+s,n.keys.mailbox,(function(){}),!0,{owners:n.keys.drive.edPublic}),t.updateMetadata(),o(e)}))}},I=function(t,n,r){var o=e.find(t,["store","proxy","teams",n]);if(!o)return{};var a=e.clone(o);return r||(delete a.hash,delete a.keys.drive.edPrivate,delete a.keys.chat.edit),delete a.owner,a},N=function(n,r,o){if(!r)return!0;var a=e.find(n,["store","proxy","teams",r]);if(!a)return!0;var s=n.teams[r];if(!s)return!0;var c=t.getSecrets("team",o||a.roHash,a.password);if(i.upgrade(a.channel,c),s.userObject&&s.userObject.setReadOnly(!c.keys.secondaryKey,c.keys.secondaryKey),c.keys.secondaryKey)try{n.store.modules.calendar.upgradeTeam(r)}catch(e){console.error(e)}!c.keys.secondaryKey&&s.rpc&&s.rpc.destroy();var u=e.find(s,["proxy","drive","sharedFolders"]);Object.keys(u||{}).forEach((function(n){var r=s.manager.getSharedFolderData(n),o=t.parsePadUrl(r.href||r.roHref),a=t.getSecrets(o.type,o.hash,r.password);i.upgrade(a.channel,a);var c=e.find(s,["manager","folders",n,"userObject"]);c&&c.setReadOnly(!a.keys.secondaryKey,a.keys.secondaryKey)})),n.updateMetadata(),n.emit("ROSTER_CHANGE_RIGHTS",r,s.clients)},P=function(n,r,o,a,i){if(r){var s=e.find(n,["store","proxy","teams",r]);if(s){var c=n.onReadyHandlers[r],u=n.teams[r];if(s.channel===a.channel&&s.password===a.password)if(o?(s.hash=a.hash,s.keys.drive.edPrivate=a.keys.drive.edPrivate,s.keys.chat.edit=a.keys.chat.edit):(delete s.hash,delete s.keys.drive.edPrivate,delete s.keys.chat.edit),u||!Array.isArray(c))if(u){if(o){O(n,u,s.keys.drive,(function(){u.manager.addPin(u.pin,u.unpin)}));var l=t.getSecrets("team",a.hash,s.password);u.secondaryKey=l&&l.keys.secondaryKey;var f=y.createEncryptor(l.keys);u.listmap.setReadOnly(!1,f)}else delete u.secondaryKey,u.rpc&&u.rpc.destroy&&u.rpc.destroy(),u.manager.removePin(),u.listmap.setReadOnly(!0);N(n,r,a.hash),i(!0)}else i(!1);else c.push({cb:function(){P(n,r,o,a,i)}});else i(!1)}else i(!1)}else i(!1)},k=function(t,n,r,o,a){n?e.find(t,["store","proxy","teams",n])&&t.teams[n]?t.store.mailbox.sendTo("TEAM_EDIT_RIGHTS",{state:o,teamData:I(t,n,o)},{channel:r.notifications,curvePublic:r.curvePublic},a):a({error:"ENOENT"}):a({error:"EINVAL"})},R=function(t,n,r,o){var a=n.teamId;if(a){var i=e.find(t,["store","proxy","teams",a]),s=t.teams[a];if(i&&s)if(s.roster)if(n.curvePublic&&n.data){var c,u=s.roster.getState().members[n.curvePublic];g((function(e){t.Store.pad.getMetadata(null,{channel:i.channel},e((function(e){c=e&&e.error?s.listmap.metadata||{}:e})))})).nThen((function(){if(u.pendingOwner=Array.isArray(c.pending_owners)&&-1!==c.pending_owners.indexOf(u.edPublic),"OWNER"!==u.role||"OWNER"===n.data.role){"VIEWER"===u.role&&"VIEWER"!==n.data.role&&k(t,a,u,!0,(function(e){o(e)})),"VIEWER"!==u.role&&"VIEWER"===n.data.role&&k(t,a,u,!1,(function(e){o(e)}));var r={};r[n.curvePublic]=n.data,s.roster.describe(r,(function(e){e?o({error:e}):o()}))}else!function(t,n,r,o){var a=e.once(o);if(n){var i=e.find(t,["store","proxy","teams",n]);if(i){var s=t.teams[n];if(s){var c=r.pendingOwner;g((function(n){var o=c?"RM_PENDING_OWNERS":"RM_OWNERS",s=function(e){var t=e&&e.error;if(t)return console.error(t),n.abort(),void a(t)},u=function(e){t.Store.pad.setMetadata(null,{channel:e,command:o,value:[r.edPublic]},n(s))};u(i.channel),u(e.find(i,["keys","roster","channel"])),u(e.find(i,["keys","chat","channel"]))})).nThen((function(e){var t={};t[r.curvePublic]={role:"ADMIN",pendingOwner:!1},s.roster.describe(t,e((function(e){e&&console.error(e)})))})).nThen((function(e){t.store.mailbox.sendTo("RM_OWNER",{teamChannel:i.channel,title:i.metadata.name,pending:c},{channel:r.notifications,curvePublic:r.curvePublic},e())})).nThen((function(){a()}))}else a({error:"ENOENT"})}else a({error:"ENOENT"})}else a({error:"EINVAL"})}(t,a,u,(function(e){e?(console.error(e),o({error:e})):o()}))}))}else o({error:"MISSING_DATA"});else o({error:"NO_ROSTER"});else o({error:"ENOENT"})}else o({error:"EINVAL"})},M=function(e,t){Object.keys(e.onReadyHandlers).forEach((function(n){var r=-1;e.onReadyHandlers[n].some((function(e,n){if(e.cId===t)return r=n,!0})),-1!==r&&e.onReadyHandlers[n].splice(r,1)})),Object.keys(e.teams).forEach((function(n){var r=e.teams[n].clients,o=r.indexOf(t);-1!==o&&r.splice(o,1)}))},F=function(t,n,r,o){var a,i=n.seeds;try{a=l.derivePreviewKeys(i.preview)}catch(e){return void o({error:"INVALID_SEEDS"})}f.get({channel:a.channel,type:"pad",version:2,keys:{cryptKey:a.cryptKey}},(function(t,n){if(t)o({error:t});else if(n){var r=e.tryParse(n);o(r||{error:"parseError"})}else o({error:"DELETED"})}),{network:t.store.network,initialState:"{}"})},L=function(t,n,r,o){var a,i;g((function(r){!function(t,n,r,o){var a,i=n.bytes64;try{a=l.deriveInviteKeys(i)}catch(e){return void o({error:"INVALID_SEEDS"})}f.get({channel:a.channel,type:"pad",version:2,keys:{cryptKey:a.cryptKey}},(function(t,n){if(t)o({error:t});else if(n){var r=e.tryParse(n);o(r||{error:"parseError"})}else o({error:"DELETED"})}),{network:t.store.network,initialState:"{}"})}(t,n,0,r((function(e){if(e&&e.error)return r.abort(),void o(e);a=e})))})).nThen((function(n){var r=e.find(a,["teamData","channel"]),u=t.store.proxy.teams||{};if(Object.keys(u).some((function(e){return u[e].channel===r})))return n.abort(),void o({error:"ALREADY_MEMBER"});var l=e.find(a,["teamData","keys","roster"]),f=a.ephemeral;if(!l||!f)return n.abort(),void o({error:"INVALID_INVITE_CONTENT"});var h=y.Team.deriveMemberKeys(l.edit,f);s.create({network:t.store.network||t.store.networkPromise,channel:l.channel,keys:h,store:t.store,Cache:d},n((function(e,r){if(e)return n.abort(),console.error(e),void o({error:"ROSTER_ERROR"});var a=c.createData(t.store.proxy,!1),s=r.getState();i=s.members[f.curvePublic],r.accept(a.curvePublic,n((function(e){if(r.stop(),e)return n.abort(),console.error(e),void o({error:"ACCEPT_ERROR"})})))})))})).nThen((function(){var e={};i.remaining&&1!==i.remaining||O(t,e,a.ephemeral,(function(t){if(!t){var n=e.rpc;i.inviteChannel&&n.removeOwnedChannel(i.inviteChannel,(function(e){e&&console.error(e)})),i.previewChannel&&n.removeOwnedChannel(i.previewChannel,(function(e){e&&console.error(e)}))}})),x(t,{team:a.teamData},0,o)}))},H=function(t){if(t){if(t.keys&&t.keys.mailbox)return t.keys.mailbox;var n=e.find(t,["keys","roster","edit"]);if(n){var r=y.CryptoAgility.createHash(e.decodeUTF8(n)),o=r.slice(0,32),a=e.uint8ArrayToHex(r.slice(32,48)),i=y.CryptoAgility.boxKeyPairFromSecretKey(o);return{channel:a,viewed:[],keys:{curvePrivate:e.encodeBase64(i.secretKey),curvePublic:e.encodeBase64(i.publicKey)}}}}};return E.init=function(n,r,o){var a={},i=n.store;if(i.loggedIn&&i.proxy.edPublic&&!i.modules?.team){var h={store:i,Store:n.Store,pinPads:n.pinPads,emit:o,onReadyHandlers:{},teams:{},cache:{},nocache:{},updateMetadata:n.updateMetadata,updateProgress:n.updateLoadingProgress,progress:0};i.proxy.teams||(i.proxy.teams={});var E=i.proxy.teams;h.numberOfTeams=Object.keys(E).length,h.store.proxy.on("change",["teams"],(function(e,t,n){"hash"===n[2]&&N(h,n[1],t)})),h.store.proxy.on("remove",["teams"],(function(e,t){"hash"===t[2]&&N(h,t[1])}));var _=function(t,n){if(!t||!n)return!0;try{var r=e.decodeBase64(t),o=y.CryptoAgility.signKeyPairFromSecretKey(r);return e.encodeBase64(o.publicKey)===n}catch(e){return!1}};Object.keys(E).forEach((function(t){h.onReadyHandlers[t]=[],e.find(E,[t,"keys","mailbox"])||(E[t].keys.mailbox=H(E[t])),C(h,E[t],t,r((function(e){if(e){delete h.onReadyHandlers[t],delete h.cache[t],"NOCACHE"===e?.error&&(h.nocache[t]=!0);var n="string"==typeof e?e:e.type||e.message;return u.send("TEAM_LOADING_ERROR="+n),void console.error(e)}console.debug("Team "+t+" cache ready")})),d.isEnabled())})),a.onReady=function(n){var r;r={},Object.keys(E).forEach((function(n){try{var o=E[n],a=r[o.channel],i=e.find(o,["keys","drive","edPrivate"]),s=e.find(o,["keys","drive","edPublic"]);if(s?i&&s&&!_(i,s)&&(u.send("TEAM_CORRUPTED_EDPRIVATE"),delete E[n].keys.drive.edPrivate,i=void 0):u.send("TEAM_CORRUPTED_EDPUBLIC"),o.hash&&2===t.parseTypeHash("drive",o.hash).version&&40!==o.hash.length&&u.send("TEAM_CORRUPTED_HASH"),!a)return void(r[o.channel]=n);var c=E[a],l=e.find(c,["keys","drive","edPrivate"]),f=e.find(c,["keys","chat","edit"]),d=e.find(o,["keys","chat","edit"]);!c.hash&&o.hash&&(c.hash=o.hash),!l&&i&&(c.keys.drive.edPrivate=i),!f&&d&&(c.keys.chat.edit=d),h.store.proxy.duplicateTeams=h.store.proxy.duplicateTeams||{},h.store.proxy.duplicateTeams[n]=E[n],delete E[n]}catch(e){console.error(e)}}));var o=function(e){return!E[e]&&(w(h,e),delete h.onReadyHandlers[e],!0)};Object.keys(h.teams).forEach(o),Object.keys(h.onReadyHandlers).forEach((function(t){if(!o(t)){var r=h.store.proxy.teams[t],a=e.find(r,["keys","roster","channel"]),i=e.once(e.mkAsync(n()));g((function(e){T(h,t,r.channel,a,e,i)})),h.onReadyHandlers[t].push({cb:i})}})),Object.keys(E).forEach((function(t){h.onReadyHandlers[t]||h.teams[t]||(h.onReadyHandlers[t]=[],e.find(E,[t,"keys","mailbox"])||(E[t].keys.mailbox=H(E[t])),C(h,E[t],t,n((function(e){if(e){var n="string"==typeof e?e:e.type||e.message;return u.send("TEAM_LOADING_ERROR="+n),void console.error(e)}console.debug("Team "+t+" ready")}))))})),A(),b.fire()},a.getTeam=function(e){return h.teams[e]},a.getTeamsData=function(t){var n={},r=!1;return-1!==["drive","teams","settings"].indexOf(t)&&(r=!0),Object.keys(E).forEach((function(t){if(h.teams[t]){var o=h.teams[t].proxy||{},a=o.drive&&Object.keys(o.drive.filesData||{}).length,i=o.drive&&Object.keys(o.drive.sharedFolders||{}).length;n[t]={owner:E[t].owner,name:E[t].metadata.name,channel:E[t].channel,numberPads:a,numberSf:i,roster:e.find(E[t],["keys","roster","channel"]),edPublic:e.find(E[t],["keys","drive","edPublic"]),avatar:e.find(E[t],["metadata","avatar"]),viewer:!e.find(E[t],["keys","drive","edPrivate"]),notifications:e.find(E[t],["keys","mailbox","channel"]),curvePublic:e.find(E[t],["keys","mailbox","keys","curvePublic"]),validKeys:_(e.find(E[t],["keys","drive","edPrivate"]),e.find(E[t],["keys","drive","edPublic"]))},r&&h.teams[t]&&(n[t].secondaryKey=h.teams[t].secondaryKey),h.teams[t]&&(n[t].hasSecondaryKey=Boolean(h.teams[t].secondaryKey))}})),n},a.getTeams=function(){return Object.keys(h.teams)};a.removeFromTeam=function(e,t,n){if(E[e]&&(!n||function(e,t){var n=h.teams[e];if(n){var r=n.roster&&n.roster.getState();if(r.members)return(r.members[t]||{}).pending}}(e,t)))if(h.onReadyHandlers[e])h.onReadyHandlers[e].push({cb:function(){h.teams[e].roster.remove([t],(function(e){e&&"NO_CHANGE"!==e&&console.error(e)}))}});else{var r=h.teams[e];r?r.roster.remove([t],(function(e){e&&"NO_CHANGE"!==e&&console.error(e)})):console.error("TEAM MODULE ERROR")}},a.changeMyRights=function(e,t,n,r){P(h,e,t,n,r)},a.updateMyData=function(e){Object.keys(h.teams).forEach((function(t){var n=h.teams[t];if(n.roster){var r={};r[e.curvePublic]=e,n.roster.describe(r,(function(e){e&&console.error(e)}))}}))},a.removeClient=function(e){M(h,e)};return a.execCommand=function(n,r,o){var a=r.cmd,i=r.data;if("SUBSCRIBE"!==a)if("LIST_TEAMS"!==a)if("OPEN_TEAM_CHAT"!==a)if("GET_TEAM_ROSTER"!==a)if("GET_TEAM_METADATA"!==a)if("SET_TEAM_METADATA"!==a){if("OFFER_OWNERSHIP"===a)return h.store.offline?void o({error:"OFFLINE"}):void function(t,n,r,o){var a=e.once(o),i=n.teamId;if(i){var s=e.find(t,["store","proxy","teams",i]);if(s){var c=t.teams[i];if(c)if(c.roster)if(n.curvePublic){var u=c.roster.getState().members[n.curvePublic];g((function(n){var r=function(e){var t=e&&e.error;if(t)return console.error(t),n.abort(),void a({error:t})},o=function(e){t.Store.pad.setMetadata(null,{channel:e,command:"ADD_PENDING_OWNERS",value:[u.edPublic]},n(r))};o(s.channel),o(e.find(s,["keys","roster","channel"])),o(e.find(s,["keys","chat","channel"]))})).nThen((function(e){var t={};t[u.curvePublic]={role:"OWNER"},c.roster.describe(t,e((function(e){e&&console.error(e)})))})).nThen((function(n){t.store.mailbox.sendTo("ADD_OWNER",{teamChannel:s.channel,chatChannel:e.find(s,["keys","chat","channel"]),rosterChannel:e.find(s,["keys","roster","channel"]),title:s.metadata.name},{channel:u.notifications,curvePublic:u.curvePublic},n())})).nThen((function(){a()}))}else a({error:"MISSING_DATA"});else a({error:"NO_ROSTER"});else a({error:"ENOENT"})}else a({error:"ENOENT"})}else a({error:"EINVAL"})}(h,i,0,o);if("ANSWER_OWNERSHIP"===a)return h.store.offline?void o({error:"OFFLINE"}):void function(t,n,r,o){var a,i=t.store.proxy.teams;if(Object.keys(i).forEach((function(e){if(i[e].channel===n.teamChannel)return a=e,!0})),a){var s=e.find(t,["store","proxy","teams",a]);if(s){var c=t.teams[a];if(c)if(c.roster){var u={};n.answer?s.owner=!0:(u[t.store.proxy.curvePublic]={role:"ADMIN"},c.roster.describe(u,(function(e){e?o({error:e}):o()})))}else o({error:"NO_ROSTER"});else o({error:"ENOENT"})}else o({error:"ENOENT"})}else o({error:"EINVAL"})}(h,i,0,o);if("DESCRIBE_USER"!==a){if("INVITE_TO_TEAM"===a)return h.store.offline?void o({error:"OFFLINE"}):void function(e,t,n,r){var o=t.teamId;if(o){var a=e.teams[o];if(a)if(a.roster){var i=t.user;if(i&&i.curvePublic&&i.notifications){delete i.channel,delete i.lastKnownHash,i.pending=!0;var s={};s[i.curvePublic]=i,s[i.curvePublic].role="VIEWER",a.roster.add(s,(function(t){t&&"NO_CHANGE"!==t?r({error:t}):e.store.mailbox.sendTo("INVITE_TO_TEAM",{team:I(e,o)},{channel:i.notifications,curvePublic:i.curvePublic},(function(e){r(e)}))}))}else r({error:"MISSING_DATA"})}else r({error:"NO_ROSTER"});else r({error:"ENOENT"})}else r({error:"EINVAL"})}(h,i,0,o);if("LEAVE_TEAM"!==a){if("JOIN_TEAM"===a)return h.store.offline?void o({error:"OFFLINE"}):void x(h,i,0,o);if("REMOVE_USER"!==a){if("DELETE_TEAM"===a)return h.store.offline?void o({error:"OFFLINE"}):void function(t,n,r,o){var a=n.teamId;if(a){var i=t.teams[a],s=e.find(t,["store","proxy","teams",a]);if(i&&s){var c=i.roster.getState(),l=e.find(t,["store","proxy","curvePublic"]),f=c.members[l];if(!f||"OWNER"!==f.role)return o({error:"EFORBIDDEN"});var d=e.find(t,["store","proxy","edPublic"]),h=e.find(s,["keys","drive","edPublic"]);g((function(e){t.Store.anonRpcMsg(null,{msg:"GET_METADATA",data:s.channel},e((function(t){if(t&&t.error)return e.abort(),o({error:t.error});var n=t[0];n&&Array.isArray(n.owners)&&-1!==n.owners.indexOf(d)||(e.abort(),o({error:"EFORBIDDEN"}))})))})).nThen((function(n){i.proxy.delete=!0;var r=i.manager.getChannelsList("owned"),o=e.Saferphore.create(10);r.forEach((function(e){var r=n();o.take((function(n){var o=!1;g((function(r){32===e.length&&t.Store.anonRpcMsg(null,{msg:"GET_METADATA",data:e},r((function(e){if(e&&e.error)return n(),void r.abort();var t=e[0];if(!t||!Array.isArray(t.owners)||-1===t.owners.indexOf(h))return n(),void r.abort();o=t.owners.some((function(e){return e!==h}))})))})).nThen((function(n){o?t.Store.pad.setMetadata(null,{channel:e,command:"RM_OWNERS",value:[h]},n()):i.rpc.removeOwnedChannel(e,n((function(e){e&&console.error(e)})))})).nThen((function(){n(),r()}))}))}))})).nThen((function(n){i.rpc.removePins(n((function(e){e&&console.error(e)})));var r=e.find(s,["keys","mailbox","channel"]);i.rpc.removeOwnedChannel(r,n((function(e){e&&console.error(e)})));var o=e.find(s,["keys","roster","channel"]);t.store.rpc.removeOwnedChannel(o,n((function(e){e&&console.error(e)})));var a=e.find(s,["keys","chat","channel"]);t.store.rpc.removeOwnedChannel(a,n((function(e){e&&console.error(e)}))),t.store.rpc.removeOwnedChannel(s.channel,n((function(e){e&&console.error(e)})))})).nThen((function(){u.send("TEAM_DELETION"),w(t,a),o()}))}else o({error:"ENOENT"})}else o({error:"EINVAL"})}(h,i,0,o);if("CREATE_TEAM"===a)return h.store.offline?void o({error:"OFFLINE"}):void function(n,r,o,a){var i,l=e.once(a),f=t.createChannelId(),h=t.createRandomHash("team",f),E=t.getSecrets("team",h,f),b=t.getViewHashFromKeys(E),A=y.CryptoAgility.signKeyPair(),_=y.CryptoAgility.curveKeyPair(),O=y.CryptoAgility.generateKemKeypair(),D=y.CryptoAgility.generateKemKeypair(),T=y.Team.createSeed(),C=y.Team.deriveMemberKeys(T,{curvePublic:n.store.proxy.curvePublic,curvePrivate:n.store.proxy.curvePrivate,kemPublic:n.store.proxy.kemPublic,kemPrivate:n.store.proxy.kemPrivate}),x=t.getSecrets("chat"),I=t.getHashes(x),N={network:n.store.network,channel:E.channel,data:{},validateKey:E.keys.validateKey,crypto:y.createEncryptor(E.keys),logLevel:1,classic:!0,ChainPad:m,Cache:d,owners:[n.store.proxy.edPublic]};g((function(e){s.create({network:n.store.network||n.store.networkPromise,channel:C.channel,owners:[n.store.proxy.edPublic],keys:C,store:n.store,lastKnownHash:void 0,newTeam:!0,Cache:d},e((function(t,r){if(t)return e.abort(),void l({error:"ROSTER_ERROR"});i=r;var o=c.createData(n.store.proxy);delete o.channel,i.init(o,e((function(t){if(t)return e.abort(),void l({error:"ROSTER_INIT_ERROR"})})))})));var t,r=y.createEncryptor(x.keys),o={network:n.store.network,channel:x.channel,noChainPad:!0,crypto:r,metadata:{validateKey:x.keys.validateKey,owners:[n.store.proxy.edPublic]}},a=e();o.onReady=function(){t&&t.stop(),a()},o.onError=function(){e.abort(),l({error:"CHAT_INIT_ERROR"})},t=v.start(o)})).nThen((function(e){i.metadata({name:r.name},e((function(t){if(t)return e.abort(),void l({error:"ROSTER_INIT_ERROR"})})))})).nThen((function(){var a=e.createRandomInteger();N.onMetadataUpdate=function(){var e=n.teams[a];e&&n.emit("ROSTER_CHANGE",a,e.clients)};var s=p.create(N),c=s.proxy;c.version=2,c.on("ready",(function(){var d={mailbox:{channel:t.createChannelId(),viewed:[],keys:{curvePrivate:e.encodeBase64(_.secretKey),curvePublic:e.encodeBase64(_.publicKey),kemPrivate:e.encodeBase64(O.secretKey),kemPublic:e.encodeBase64(O.publicKey)}},drive:{edPrivate:e.encodeBase64(A.secretKey),edPublic:e.encodeBase64(A.publicKey),dsaPrivate:e.encodeBase64(D.secretKey),dsaPublic:e.encodeBase64(D.publicKey)},chat:{edit:I.editHash,view:I.viewHash,validateKey:x.keys.validateKey,channel:x.channel},roster:{channel:C.channel,edit:T,view:C.viewKeyStr}},p=n.store.proxy.teams[a]={owner:!0,channel:E.channel,hash:h,roHash:b,password:f,keys:d,metadata:{name:r.name}};c.drive={},S(n,a,s,i,d,o,(function(){u.send("TEAM_CREATION"),n.store.mailbox.open("team-"+a,p.keys.mailbox,(function(){}),!0,{owners:p.keys.drive.edPublic}),n.updateMetadata(),l()}))})).on("error",(function(e){e&&void 0!==e.loaded&&!e.loaded&&l({error:"ECONNECT"}),e&&"EDELETED"===e.error&&w(n,a)}))}))}(h,i,n,o);if("GET_EDITABLE_FOLDERS"!==a)if("CREATE_INVITE_LINK"!==a){if("GET_PREVIEW_CONTENT"!==a)return"ACCEPT_LINK_INVITATION"===a?h.store.offline?void o({error:"OFFLINE"}):void L(h,i,0,o):void 0;F(h,i,0,o)}else!function(t,n,r,o){var a=e.mkAsync(e.once(o)),i=n.teamId,s=t.teams[n.teamId],u=n.seeds,d=n.bytes64;if(i&&s){var h,p=s.roster;try{h=p.getState().metadata.name}catch(e){return void a({error:"TEAM_NAME_ERR"})}var y=n.message,v=n.name,m=n.hash,E=e.find(t,["store","proxy","teams",i]);try{var b=l.encryptHash(m,E.hash)}catch(e){console.error(e)}var A=l.derivePreviewKeys(u.preview),_=l.deriveInviteKeys(d),w=l.generateKeys(),O=n.role||"VIEWER",D=n.uses||1;g((function(e){!function(){var n=l.generateSignPair(),r={initialState:"{}",network:t.store.network,metadata:{owners:[t.store.proxy.edPublic,w.edPublic]}};r.metadata.validateKey=n.validateKey;var o={teamName:h,message:y,author:c.createData(t.store.proxy,!1),displayName:v},i={channel:A.channel,type:"pad",version:2,keys:{cryptKey:A.cryptKey,validateKey:n.validateKey,signKey:n.signKey}};f.put(i,JSON.stringify(o),e((function(t){if(t)return console.error("CRYPTPUT_ERR",t),e.abort(),void a({error:"SET_PREVIEW_CONTENT"})})),r)}(),function(){var n=l.generateSignPair(),r={initialState:"{}",network:t.store.network,metadata:{owners:[t.store.proxy.edPublic,w.edPublic]}};r.metadata.validateKey=n.validateKey;var o={teamData:I(t,i,"MEMBER"===O),ephemeral:{edPublic:w.edPublic,edPrivate:w.edPrivate,curvePublic:w.curvePublic,curvePrivate:w.curvePrivate,kemPublic:w.kemPublic,kemPrivate:w.kemPrivate,dsaPublic:w.dsaPublic,dsaPrivate:w.dsaPrivate}},s={channel:_.channel,type:"pad",version:2,keys:{cryptKey:_.cryptKey,validateKey:n.validateKey,signKey:n.signKey}};f.put(s,JSON.stringify(o),e((function(t){if(t)return console.error("CRYPTPUT_ERR",t),e.abort(),void a({error:"SET_PREVIEW_CONTENT"})})),r)}()})).nThen((function(e){s.pin([_.channel,A.channel],(function(e){e&&e.error&&console.error(e.error)})),l.createRosterEntry(s.roster,{curvePublic:w.curvePublic,content:{curvePublic:w.curvePublic,displayName:n.name,pending:!0,remaining:D,totalUses:D,role:O,hash:b,inviteChannel:_.channel,previewChannel:A.channel}},e((function(t){t&&(e.abort(),a(t))})))})).nThen((function(){a()}))}else a({error:"EINVAL"})}(h,i,0,o);else!function(t,n,r,o){var a=n.teamId;if(a){var i=t.teams[a];if(i){var s=i.manager.folders||{};o(Object.keys(s).filter((function(e){return!s[e].proxy.version})).map((function(t){var n=e.find(i,["user","userObject"]);return{name:e.find(s,[t,"proxy","metadata","title"]),path:n?n.findFile(t)[0]:[]}})))}else o({error:"ENOENT"})}else o({error:"EINVAL"})}(h,i,0,o)}else!function(e,t,n,r){var o=t.teamId;if(o){var a=e.teams[o];if(a)if(a.roster)if(t.curvePublic){var i=a.roster.getState().members[t.curvePublic];a.roster.remove([t.curvePublic],(function(n){if(!n)return i&&i.notifications?void e.store.mailbox.sendTo("KICKED_FROM_TEAM",{pending:t.pending,teamChannel:I(e,o).channel,teamName:I(e,o).metadata.name},{channel:i.notifications,curvePublic:i.curvePublic},(function(e){r(e)})):r();r({error:n})}))}else r({error:"MISSING_DATA"});else r({error:"NO_ROSTER"});else r({error:"ENOENT"})}else r({error:"EINVAL"})}(h,i,0,o)}else!function(e,t,n,r){var o=t.teamId;if(o){var a=e.teams[o];if(a)if(a.roster){var i=e.store.proxy.curvePublic;a.roster.remove([i],(function(t){t?r({error:t}):(w(e,o),r())}))}else r({error:"NO_ROSTER"});else r({error:"ENOENT"})}else r({error:"EINVAL"})}(h,i,0,o)}else R(h,i,0,o)}else!function(e,t,n,r){var o=t.teamId;if(o){var a=e.teams[o];a?a.offline?r({error:"OFFLINE"}):a.roster?(t.metadata&&delete t.metadata.offline,a.roster.metadata(t.metadata,(function(n){if(n)r({error:n});else{var a=e.store.proxy.teams[o];a&&(a.metadata=t.metadata),r()}}))):r({error:"NO_ROSTER"}):r({error:"ENOENT"})}else r({error:"EINVAL"})}(h,i,0,o);else!function(e,t,n,r){var o=t.teamId;if(o){var a=e.teams[o];if(a)if(a.roster){var i=(a.roster.getState()||{}).metadata||{};i.offline=a.offline,r(i)}else r({error:"NO_ROSTER"});else r({error:"ENOENT"})}else r({error:"EINVAL"})}(h,i,0,o);else!function(t,n,r,o){var a=n.teamId;if(a){var i=e.find(t,["store","proxy","teams",a]);if(i){var s=t.teams[a];if(s)if(s.roster){var c,u=(s.roster.getState()||{}).members||{};g((function(e){t.Store.pad.getMetadata(null,{channel:i.channel},e((function(e){c=e&&e.error?s.listmap.metadata||{}:e})))})).nThen((function(){if(t.pending_owners=c.pending_owners,Array.isArray(c.pending_owners)&&c.pending_owners.forEach((function(n){var r;if(Object.keys(u).some((function(e){if(u[e].edPublic===n)return r=u[e],!0})),!r&&i.owner){var o=function(e){t.Store.pad.setMetadata(null,{channel:e,command:"RM_PENDING_OWNERS",value:[n]},(function(){}))};return o(i.channel),o(e.find(i,["keys","roster","channel"])),void o(e.find(i,["keys","chat","channel"]))}r.pendingOwner=!0})),t.store.messenger){var n=s.getChatData();(t.store.messenger.getOnlineList(n.channel)||[]).forEach((function(e){u[e]&&(u[e].online=!0)}))}Object.keys(u).forEach((function(e){var t=u[e];if(t.inviteChannel&&t.hash)if(i.hash)try{t.hash=l.decryptHash(t.hash,i.hash)}catch(e){console.error(e)}else delete t.hash})),o(u)}))}else o({error:"NO_ROSTER"});else o({error:"ENOENT"})}else o({error:"ENOENT"})}else o({error:"EINVAL"})}(h,i,0,o);else!function(e,t,n,r){var o=e.teams[t.teamId];if(o){var a=function(){e.emit("ROSTER_CHANGE",t.teamId,o.clients)};e.store.messenger?e.store.messenger.openTeamChat(o.getChatData(),a,n,r):A=function(){e.store.messenger.openTeamChat(o.getChatData(),a,n,r)}}else r({error:"ENOENT"})}(h,i,n,o);else!function(t){var n=e.clone(E);Object.keys(n).forEach((function(e){h.teams[e]?n[e].offline=h.teams[e].offline:(n[e].error=!0,h.nocache[e]&&(n[e].offline=!0))})),t(n)}(o);else!function(e,t,n,r){M(e,n);try{e.store.messenger.removeClient(n)}catch(e){}if(A=function(){},t)if(!e.onReadyHandlers[t]||e.teams[t])if(e.teams[t]){var o=e.teams[t].clients;-1===o.indexOf(n)&&o.push(n),r()}else r({error:"EINVAL"});else-1===e.onReadyHandlers[t].indexOf(n)&&e.onReadyHandlers[t].push({cId:n,cb:r});else r()}(h,i,n,o)},a}},E.anonGetPreviewContent=function(e,t,n){F(e,t,0,n)},E})(Ne(),Fe(),Oe(),mt(),Tt(),Et(),St(),vr(),Zt(),nt(),(rr||(rr=1,nr=function(e,t,n,r){var o={},a=e.encodeBase64,i=e.decodeBase64;o.generateKeys=function(){var e=r.CryptoAgility.signKeyPair(),t=r.CryptoAgility.curveKeyPair(),n=r.CryptoAgility.generateKemKeypair(),o=r.CryptoAgility.generateDsaKeypair();return{edPublic:a(e.publicKey),edPrivate:a(e.secretKey),curvePublic:a(t.publicKey),curvePrivate:a(t.secretKey),kemPublic:a(n.publicKey),kemPrivate:a(n.secretKey),dsaPublic:a(o.publicKey),dsaPrivate:a(o.secretKey)}},o.generateSignPair=function(){var e=r.CryptoAgility.signKeyPair(),t=r.CryptoAgility.generateKemKeypair();return{validateKey:a(e.publicKey),signKey:a(e.secretKey),dsaPublic:a(t.publicKey),dsaPrivate:a(t.secretKey)}};var s=function(n){var o=t.dispenser(i(n));return{channel:e.uint8ArrayToHex(o(16)),cryptKey:o(r.CryptoAgility.secretboxKeyLength())}};o.deriveInviteKeys=s,o.derivePreviewKeys=s,o.createRosterEntry=function(e,t,n){var r={};r[t.curvePublic]=t.content,e.invite(r,n)};var c=e.decodeUTF8;return o.encryptHash=function(e,t){var n=c(t),o=r.CryptoAgility.createHash(n).subarray(0,32);return r.encrypt(e,o)},o.decryptHash=function(e,t){var n=c(t),o=r.CryptoAgility.createHash(n).subarray(0,32);return r.decrypt(e,o)},o}(Ne(),st(),h(),ye())),nr),cn(),Ge(),sn(),S(),ye(),O(),I(),Dt(),h()),or}function gr(){if(sr)return ir;sr=1;return ir=((e,t,n,r,o,a,i,s)=>{var c=e.Curve;const u={};let l={};u.setCustomize=e=>{l=e.Messages};var f="MSG",d="UNFRIEND",h="MAP_ID",p="MAP_ID_ACK",y=function(e){return JSON.parse(JSON.stringify(e))},v=function(e){for(var t=Object.keys(e).length,n=new Uint8Array(t),r=0;r{const t=p.store.network||e;t.on("message",(function(e,t){x(p,e,t)})),t.on("disconnect",(function(){p.emit("DISCONNECT",null,N(p))})),t.on("reconnect",(function(){p.emit("RECONNECT",null,N(p))}))}));return h.networkPromise?.then(b),p.store.network&&b(),u.onFriendUpdate=function(e){var t=g(h.proxy,e);if(t&&t.channel){var n=p.channels[t.channel];n&&p.emit("UPDATE_DATA",{info:y(t),channel:t.channel},n.clients)}},u.onFriendAdded=function(e){if(p.friendsClients.length){var t=g(p.store.proxy,e.curvePublic);if("object"==typeof t)if(t.channel){var n=t.channel;p.channels[n]||k(p,null,t,(function(){c("FRIEND",{curvePublic:t.curvePublic},p.friendsClients)}))}}},u.onFriendRemoved=function(e,t){I(p,e,t)},u.getOnlineList=function(e){return function(e,t){var n=e.channels[t];if(n){var r=[],o=m(e.store.proxy,!1);return r.push(o.curvePublic),n.wc.members.forEach((function(t){if(t!==e.store.network.historyKeeper){var o=n.mapId[t]||{};o.curvePublic&&-1===r.indexOf(o.curvePublic)&&r.push(o.curvePublic)}})),r}}(p,e)},u.storeValidateKey=function(e,t){p.validateKeys[e]=t},u.leavePad=function(e){delete p.validateKeys[e],Object.keys(p.channels).some((function(t){var n=p.channels[t];if(n.padChan===e){n.wc&&n.wc.leave();var r=p.store.network;return n.onReconnect&&r.off("reconnect",n.onReconnect),n.stopped=!0,delete p.channels[t],!0}}))},u.openTeamChat=function(t,r,o,a){!function(t,r,o,a,i){var s=o,c=s.channel,u=s.secret;if(c&&u){var l=n.once(n.mkAsync((function(){t.emit("TEAMCHAT_READY",c,[r]),i({readOnly:"object"==typeof u.keys&&!u.keys.validateKey,channel:c})}))),f=t.channels[c];if(f)f.onReady.reg((function(){-1===f.clients.indexOf(r)&&f.clients.push(r),l()}));else{u.keys.cryptKey&&(u.keys.cryptKey=v(u.keys.cryptKey));var d=e.createEncryptor(u.keys),h=u.keys&&u.keys.validateKey||s.validateKey,p={teamId:o.teamId,readOnly:"object"==typeof u.keys&&!u.keys.validateKey,encryptor:d,channel:c,isTeamChat:!0,decrypt:function(e){return d.decrypt(e,h)},clients:[r],onUserlistUpdate:a,onReady:l};P(t,p)}}else i({error:"EINVAL"})}(p,o,t,r,a)},u.removeClient=function(e){!function(e,t){var n=e.friendsClients.indexOf(t);-1!==n&&e.friendsClients.splice(n,1),Object.keys(e.channels).forEach((function(n){var r=e.channels[n],o=r.clients,a=o.indexOf(t);if(-1!==a&&o.splice(a,1),0===o.length){r.wc&&r.wc.leave();var i=e.store.network;return r.onReconnect&&i.off("reconnect",r.onReconnect),r.stopped=!0,delete e.channels[n],!0}}))}(p,e)},u.execCommand=function(t,r,i){var c=r.cmd,u=r.data;"INIT_FRIENDS"!==c?"GET_ROOMS"!==c?"GET_MUTED_USERS"!==c?"GET_USERLIST"!==c?"OPEN_PAD_CHAT"!==c?"GET_MY_INFO"!==c?"REMOVE_FRIEND"!==c?"CANCEL_FRIEND"!==c?"MUTE_USER"!==c?"UNMUTE_USER"!==c?"GET_STATUS"!==c?"GET_MORE_HISTORY"!==c?"SEND_MESSAGE"!==c?"SET_CHANNEL_HEAD"!==c?"CLEAR_OWNED_CHANNEL"!==c||function(e,t,n){var r=e.channels[t];r?e.store.rpc?e.store.rpc.clearOwnedChannel(t,(function(o){n({error:o}),o||(r.messages=[],e.emit("CLEAR_CHANNEL",t,r.clients))})):n({error:"RPC_NOT_READY"}):n({error:"NO_CHANNEL"})}(p,u,i):D(p,u.id,u.sig,i):function(e,t,n,r){var o=e.channels[t];if(o)if(o.readOnly)r({error:"FORBIDDEN"});else if(e.store.network.webChannels.some((function(e){if(e.id===o.wc.id)return!0}))){var i=e.store.proxy||{},s=[f,i.curvePublic,+new Date,n];if(!o.isFriendChat){var c=i[a.displayNameKey]||l.anonymous+"#"+(i.uid||e.store.noDriveUid).slice(0,5);s.push(c)}var u=JSON.stringify(s),d=o.encrypt(u);o.wc.bcast(d).then((function(){C(e,o,d),r()}),(function(e){r({error:e})}))}else r({error:"NO_SUCH_CHANNEL"});else r({error:"NO_CHANNEL"})}(p,u.id,u.content,i):function(e,t,r,o,a){if("function"==typeof a)if("string"==typeof r){var i=e.channels[t];if(void 0!==i){var s=n.uid();_(e,s,t,a);var c=["GET_HISTORY_RANGE",i.id,{from:r,count:o,txid:s}],u=e.store.network;u.sendto(u.historyKeeper,JSON.stringify(c)).then((function(){}),(function(e){console.error(e)}))}else console.error("chan is undefined. we're going to have a problem here")}else a([])}(p,u.id,u.sig,u.count,i):function(e,t,n){var r=e.channels[t];if(r){r.onUserlistUpdate&&r.onUserlistUpdate();var o=e.store.proxy||{};n(r.wc.members.some((function(t){if(t!==e.store.network.historyKeeper){var n=r.mapId[t]||void 0;return!!n&&n.curvePublic!==o.curvePublic}})))}else n("NO_SUCH_CHANNEL")}(p,u,i):function(e,t,r){var o=n.once(n.mkAsync(r)),a=e.store.proxy,i=a.mutedUsers=a.mutedUsers||{};delete i[t],e.emit("UPDATE_MUTED",null,N(e)),o(Object.keys(i).length)}(p,u,i):function(e,t,r){var o=n.once(n.mkAsync(r)),a=e.store.proxy,i=a.mutedUsers=a.mutedUsers||{};i[t.curvePublic]||(i[t.curvePublic]=t,e.emit("UPDATE_MUTED",null,N(e))),o()}(p,u,i):function(e,t,r){var o=n.once(r);"function"==typeof o?e.Store.cancelFriendRequest(t,o):console.error("NO_CALLBACK")}(p,u,i):function(e,t,r){var a=n.once(r);if("function"==typeof a){var i=e.store.proxy,s=g(i,t);if(!s)return console.error("friend is not valid"),void a({error:"INVALID_FRIEND"});var c=e.channels[s.channel];if(e.store.mailbox&&s.curvePublic&&s.notifications)o.removeFriend(e.store,t,(function(t){t&&t.error?a({error:t.error}):(e.updateMetadata(),a(t))}));else if(c)try{var u=[d,i.curvePublic,+new Date],l=JSON.stringify(u),f=c.encrypt(l);c.wc.bcast(f).then((function(){I(e,t,s.channel),T(e,t,(function(){a()}))}),(function(n){n?a({error:n}):(I(e,t,s.channel),T(e,t,(function(){a()})))}))}catch(e){a({error:e})}else a({error:"NO_SUCH_CHANNEL"})}else console.error("NO_CALLBACK")}(p,u,i):function(e,t){var n=e.store.proxy||{};t({curvePublic:n.curvePublic,displayName:n[a.displayNameKey]})}(p,i):function(t,r,o,a){var i=o.channel,s=n.once(n.mkAsync((function(){t.emit("PADCHAT_READY",i,[r]),a()}))),c=t.channels[i];if(c)c.onReady.reg((function(){-1===c.clients.indexOf(r)&&c.clients.push(r),s()}));else{var u=o.secret;u.keys.cryptKey&&(u.keys.cryptKey=v(u.keys.cryptKey));var l=e.createEncryptor(u.keys),f=u.keys&&u.keys.validateKey||t.validateKeys[u.channel],d={padChan:o.secret&&o.secret.channel,readOnly:"object"==typeof u.keys&&!u.keys.validateKey,encryptor:l,channel:o.channel,isPadChat:!0,decrypt:function(e){return l.decrypt(e,f)},clients:[r],onReady:s};P(t,d)}}(p,t,u,i):function(e,t,n){var r=e.channels[t.id];if(r)if(r.isFriendChat){var o=A(e,t.id);if(!o)return void n({error:"NO_SUCH_FRIEND"});n([o])}else n([]);else n({error:"NO_SUCH_CHANNEL"})}(p,u,i):function(e,t){var n=e.store.proxy;if(!t)return n.mutedUsers||{};t(n.mutedUsers||{})}(p,i):function(e,t,n){var r=e.store.proxy;if(t&&t.curvePublic){var o=t.curvePublic,a=g(r,o);if(!a)return void n({error:"NO_SUCH_FRIEND"});var i=e.channels[a.channel];return i?void n([{id:i.id,isFriendChat:!0,name:a.displayName,lastKnownHash:a.lastKnownHash,curvePublic:a.curvePublic,messages:i.messages}]):void n({error:"NO_SUCH_CHANNEL"})}if(t&&t.padChat){var s=e.channels[t.padChat];return s?void n([{id:s.id,isPadChat:!0,messages:s.messages}]):void n({error:"NO_SUCH_CHANNEL"})}if(t&&t.teamChat){var c=e.channels[t.teamChat];return c?void n([{id:c.id,isTeamChat:!0,messages:c.messages}]):void n({error:"NO_SUCH_CHANNEL"})}var u=Object.keys(e.channels).map((function(t){var n,r,o,a=e.channels[t];if(a.isFriendChat){var i=A(e,t);if(!i)return null;n=i.displayName,r=i.lastKnownHash,o=i.curvePublic}else{if(a.isPadChat)return;if(a.isTeamChat)return}return{id:a.id,isFriendChat:a.isFriendChat,name:n,lastKnownHash:r,curvePublic:o,messages:a.messages}})).filter((function(e){return e}));n(u)}(p,u,i):function(e,t,n){var r=E(e.store.proxy);s((function(n){Object.keys(r).forEach((function(o){if("me"!==o){var a=y(r[o]);"object"==typeof a&&a.channel&&k(e,t,a,n())}else delete r.me.channel}))})).nThen((function(){-1===e.friendsClients.indexOf(t)&&e.friendsClients.push(t),n()}))}(p,t,i)},u},u})(ye(),Fe(),Ne(),mt(),Zt(),Oe(),Ft(),Dt()),ir}function Er(){if(ur)return cr;ur=1;return cr=((e,t,n,r)=>{const o={},a={};var i=function(t,n,o,a,i){var s,c=e.once(e.mkAsync(i)),u=function(t,n){if(!n)return e.find(t.store,["proxy","edPublic"]);var r=e.find(t,["store","proxy","teams",n]);return e.find(r,["keys","drive","edPublic"])}(t,a),l=t.Store,f=0,d=0,h=0;r((function(e){l.getFileSize(null,{channel:n},e((function(t){return t&&t.error?(e.abort(),void c(t)):void 0===t.size?(e.abort(),void c({error:"ENOENT"})):void(f=t.size)}))),l.getHistory(null,{channel:n,lastKnownHash:o},e((function(t){if(t&&t.error)return e.abort(),void c(t);if(!Array.isArray(t))return e.abort(),void c({error:"EINVAL"});if(t.length){s=t[0].hash;var n=t.map((function(e){return e.msg}));d=n.join("\n").length}})),!0),l.pad.getMetadata(null,{channel:n},e((function(t){if((!t||!t.error)&&t&&"object"==typeof t)return h=JSON.stringify(t).length,t&&Array.isArray(t.owners)&&-1!==t.owners.indexOf(u)?void 0:(e.abort(),void c({error:"INSUFFICIENT_PERMISSIONS"}))})))})).nThen((function(){c({size:f-h-d,hash:s})}))};return a.GET_HISTORY_SIZE=function(o,a,s,c){if(o.store.loggedIn&&o.store.rpc){var u=a.channels;if(Array.isArray(u)){var l=[];a.account?u=function(r){var o=[],a=e.find(r.store,["proxy","edPublic"]);-1!==(e.find(r.store,["driveMetadata","owners"])||[]).indexOf(a)&&o.push(r.store.driveChannel);var i=r.store.proxy.profile;if(i){var s=i.edit?t.hrefToHexChannelId("/profile/#"+i.edit,null):null;s&&o.push(s)}r.store.proxy.todo&&o.push(t.hrefToHexChannelId("/todo/#"+r.store.proxy.todo,null));var c=r.store.proxy.mailboxes;if(c){var u=Object.keys(c).map((function(e){return{lastKnownHash:c[e].lastKnownHash,channel:c[e].channel}}));Array.prototype.push.apply(o,u)}var l=r.store.proxy[n.SHARED_FOLDERS];if(l){var f=Object.keys(l).map((function(e){var t=l[e];if(t&&t.owners&&Array.isArray(t.owners)&&-1!==t.owners.indexOf(a))return t.channel})).filter(Boolean);Array.prototype.push.apply(o,f)}return o}(o):a.team&&(u=function(t,n){let r=e.find(t.store,["proxy","teams",n]);if(!r)return[];let o=[r.channel],a=r.keys.roster;return o.push({channel:a.channel,lastKnownHash:a.lastKnownHash}),o}(o,a.team));var f=0,d=[];r((function(e){u.forEach((function(t){var n,r=t;"object"==typeof t&&t.channel&&(r=t.channel,n=t.lastKnownHash),i(o,r,n,a.teamId,e((function(e){e&&e.error?l.push(e.error):(f+=e.size,e.hash&&d.push({channel:r,hash:e.hash}))})))}))})).nThen((function(){c({warning:l.length?l:void 0,channels:d,size:f})}))}else c({error:"EINVAL"})}else c({error:"INSUFFICIENT_PERMISSIONS"})},a.TRIM_HISTORY=function(e,t,n,o){if(e.store.loggedIn&&e.store.rpc){var a=t.channels;if(Array.isArray(a)){var i=function(e,t){if(!t)return e.store.rpc;var n=e.store.modules.team;if(n){var r=n.getTeam(t);if(r)return r.rpc}}(e,t.teamId);if(i){var s=[];r((function(e){a.forEach((function(t){i.trimHistory(t,e((function(e){e&&s.push(e)})))}))})).nThen((function(){1===a.length&&s.length?o({error:s[0]}):o({warning:s.length?s:void 0})}))}else o({error:"ENORPC"})}else o({error:"EINVAL"})}else o({error:"INSUFFICIENT_PERMISSIONS"})},o.init=function(e,t,n){var r={};if(e.store){var o={store:e.store,Store:e.Store,pinPads:e.pinPads,updateMetadata:e.updateMetadata,emit:n};return r.execCommand=function(e,t,n){var r=t.cmd,i=t.data;try{a[r](o,i,e,n)}catch(e){console.error(e)}},r}},o})(Ne(),Fe(),Et(),Dt()),cr}var br,Ar={exports:{}};function _r(){return br||(br=1,function(e){(()=>{const t=e=>{var t={};const n=globalThis;var r=function(){},o=t.getWeekNo=function(e,t){"number"!=typeof t&&(t=1);var n=new Date(e.getFullYear(),0,1),r=n.getDay()-t;r=r>=0?r:r+7;var o,a=Math.floor((e.getTime()-n.getTime())/864e5)+1;if(r<4){if((o=Math.floor((a+r-1)/7)+1)>52){var i=new Date(e.getFullYear()+1,0,1).getDay()-t;o=(i=i>=0?i:i+7)<4?1:53}}else o=Math.floor((a+r-1)/7);return o},a=function(e){var t=new Date(e.getFullYear(),0,0),n=e-t+60*(t.getTimezoneOffset()-e.getTimezoneOffset())*1e3;return Math.floor(n/864e5)},i=t.DAYORDER=["SU","MO","TU","WE","TH","FR","SA"],s=function(e){var t=Number(e.slice(0,-2)),n=i.indexOf(e.slice(-2));return t?[t,n]:n},c=function(e,t){var n=e.getDay();n>=(t="number"==typeof t?t:1)?e.setDate(e.getDate()-(n-t)):e.setDate(e.getDate()-(7+n-t))},u=function(e){return e.getFullYear()+"-"+(e.getMonth()+1)+"-"+e.getDate()},l={daily:function(e,t){e.setDate(e.getDate()+t)},weekly:function(e,t){e.setDate(e.getDate()+7*t)},monthly:function(e,t){e.setMonth(e.getMonth()+t)},yearly:function(e,t){e.setFullYear(e.getFullYear()+t)}},f={month:function(e,t,n){var r=new Date(t.start),o=(n-(e.getMonth()+1)+12)%12,a=e.getMonth()+o;if(e.setMonth(a),e.setDate(r.getDate()),e.getMonth()===a)return!0},weekno:function(e,t,n,r){var a=r&&r.wkst;"number"!=typeof a&&(a=1);var i=new Date(t.start),s=new Date(e.getFullYear(),11,31),u=o(s,a),l=1===u;1===u&&(u=52);var f=o(e,a);if(!n||n>u)return!1;n<0&&(n=u+n+1);var d=n-f,h=new Date(+e);h.setDate(h.getDate()+7*d),c(h,a);var p="aaaaaaa".split("").map((function(t,n){var r=new Date(+h);if(r.setDate(r.getDate()+n),r.getFullYear()===e.getFullYear())return r.toLocaleDateString()!==i.toLocaleDateString()&&r})).filter(Boolean);return 1===n&&l&&(c(s,a),"aaaaaaa".split("").some((function(t,n){var r=new Date(+s);if(r.setDate(r.getDate()+n),r.toLocaleDateString()!==i.toLocaleDateString())return r.getFullYear()>e.getFullYear()||void p.push(r)}))),p.length?p:void 0}};f.yearday=function(e,t,n){var r=e.getFullYear();if(function(e,t){if(!("number"!=typeof t||Math.abs(t)<1||Math.abs(t)>366))return t<0&&(t=a(new Date(e.getFullYear(),11,31))+t+1),e.setMonth(0),e.setDate(t),!0}(e,n)&&e.getFullYear()===r)return!0},f.monthday=function(e,t,n,r){if("number"!=typeof n||Math.abs(n)<1||Math.abs(n)>31)return!1;var o=function(e,t){var n=e.getMonth();t<0&&(t=new Date(e.getFullYear(),e.getMonth()+1,0).getDate()+t+1);return e.setDate(t),e.getMonth()===n};if("monthly"===r.freq)return o(e,n);var a="aaaaaaaaaaaa".split("").map((function(t,r){var a=new Date(e.getFullYear(),r,1);return o(a,n)?a:void 0})).filter(Boolean);return a.length?a:void 0},f.day=function(e,t,n,r){var o,a=s(n);Array.isArray(a)&&(o=a[0],a=a[1]);var i=[];if(![0,1,2,3,4,5,6].includes(a))return!1;var c,u=function(e){if(o){var t=[];"aaaaaaaaaaaa".split("").some((function(n,r){if(void 0===e||r===e){var a,s=i.filter((function(e){return e.getMonth()===r}));return a=o<0?s.length+o:o-1,t.push(s[a]),void 0!==e&&r===e}})),i=t.filter(Boolean)}};if("yearly"===r.freq){c=new Date(+e);for(var l=e.getFullYear();c.getDay()!==a;)c.setDate(c.getDate()+1);for(;c.getFullYear()===l;)i.push(new Date(+c)),c.setDate(c.getDate()+7);return u(),i}if("monthly"===r.freq){c=new Date(+e);for(var f=e.getMonth();c.getDay()!==a;)c.setDate(c.getDate()+1);for(;c.getMonth()===f;)i.push(new Date(+c)),c.setDate(c.getDate()+7);return u(f),i}if("weekly"===r.freq)for(;e.getDay()!==a;)e.setDate(e.getDate()+1);return!0};var d={month:function(e,t){return e.filter((function(e){return t.includes(e.getMonth()+1)}))},weekno:function(e,t,n){return e.filter((function(e){var r=n&&n.wkst;"number"!=typeof r&&(r=1);var a=new Date(e.getFullYear(),11,31),i=o(a,r);1===i&&(i=52);var s=o(e,r);return t.some((function(e){return e>0?e===s:s===i+e+1}))}))},yearday:function(e,t){return e.filter((function(e){var n=a(e),r=a(new Date(e.getFullYear(),11,31));return t.some((function(e){return e>0?e===n:n===r+e+1}))}))},monthday:function(t,n){return t.filter((function(t){var r=e.clone(n);return(r=r.map((function(e){e<0&&(e=new Date(t.getFullYear(),t.getMonth()+1,0).getDate()+e+1);return e}))).includes(t.getDate())}))},day:function(e,t,n){return e.filter((function(e){var r=e.toLocaleDateString(),o="yearly";return("monthly"===n.freq||"yearly"===n.freq&&n.by&&n.by.month)&&(o="monthly"),t.some((function(t){var n,a=s(t);if(Array.isArray(a)&&(n=a[0],a=a[1]),!n)return e.getDay()===a;var i=new Date(e.getFullYear(),e.getMonth(),1);return"yearly"===o&&i.setMonth(0),f.day(i,{},t,{freq:o}).some((function(e){return e.toLocaleDateString()===r}))}))}))},setpos:function(t,n){var r=t.slice(),o=e.deduplicateString(n.slice().map((function(e){return e>0?e-1:0!==e?r.length+e:void 0})));return t.filter((function(e){var t=r.indexOf(e);return o.includes(t)}))}},h=["month","weekno","yearday","monthday","day"],p=["month","monthday","day"];t.getMonthId=function(e){return e.getFullYear()+"-"+e.getMonth()};var y=n.CP_calendar_cache={},v={};t.resetCache=function(){y=n.CP_calendar_cache={},v={}};var m=function(t){if(!t.recUpdate)return[];var n={},r=t.recUpdate.from;return Object.keys(r||{}).forEach((function(e){var t=r[e];t.recurrenceRule&&(n[e]=t.recurrenceRule)})),Object.keys(n).sort((function(e,t){return Number(e)-Number(t)})).map((function(t){var r=e.clone(n[t]);if(l[r.freq]&&!(r.interval&&r.interval<1))return r._start=Number(t),r})).filter(Boolean)};t.getRecurring=function(o,i){n.CP_DEV_MODE&&(r=console.warn);var s=[];return o.forEach((function(n){var o=n.split("-"),g=new Date(o[0],o[1]),E=new Date(+g);E.setMonth(E.getMonth()+1),E.setMilliseconds(-1),r("Compute month",g.toLocaleDateString()),(i||[]).forEach((function(n){var o=new Date(n.start),i=new Date(n.end),b=n,A=n.recurrenceRule;if(A){var _=m(n),w=_.shift();if(!(o>=E)){for(var O=A.until,D=_.slice(),S=w;S&&S._start&&S._startt)){var n;if(t.getFullYear()===e.getFullYear())n=a(t)-a(e);else{var r=new Date(e.getFullYear(),11,31);for(n=a(r)-a(e)+a(t);r.getFullYear()+1=C)){r("Start iteration",i.toLocaleDateString());var m=function(t,n,o){var a=e.clone(n),i=new Date(a.start),s=a.id.split("|")[0],u=o.toLocaleDateString();y[s]=y[s]||{};var v=t.interval||1,m=t.freq,g=[],E=function(e,n){g=d[e](g,n,t)},b=function(e){return function(n){var r=new Date(+o);"yearly"===t.freq?(r.setMonth(0),r.setDate(1)):"monthly"===t.freq?r.setDate(1):"weekly"===t.freq?c(r,t.wkst):t.freq;var s=f[e](r,a,n,t);if(s)if(Array.isArray(s))s=s.filter((function(e){return e.toLocaleDateString()!==i.toLocaleDateString()})),Array.prototype.push.apply(g,s);else{if(r.toLocaleDateString()===i.toLocaleDateString())return;g.push(r)}}},A=e.once((function(){l[m](o,v)})),_=function(){"monthly"===m?o.setDate(15):"yearly"===m&&1===i.getMonth()&&29===i.getDate()&&o.setDate(28),A();var e=new Date(+o);if("monthly"===m||"yearly"===m){if(e.setDate(i.getDate()),e.getDate()!==i.getDate())return;if("yearly"===m&&e.getMonth()!==i.getMonth())return}g.push(e)};if(Array.isArray(y[s][u]))return r("Get cache",s,u),"monthly"===m?o.setDate(15):"yearly"===m&&1===i.getMonth()&&29===i.getDate()&&o.setDate(28),A(),y[s][u];if(t.by&&"yearly"===m){var w=h.slice(),O=!1;(t.by.weekno||t.by.yearday||t.by.monthday||t.by.day)&&(w.shift(),O=!0);var D=!0;w.forEach((function(e){var n=t.by[e];n&&(D?(n.forEach(b(e)),D=!1):"day"===e?t.by.yearday||t.by.monthday||t.by.weekno?E("day",t.by.day):t.by.day.forEach(b("day")):E(e,n))})),t.by.month&&O&&E("month",t.by.month)}t.by&&"monthly"===m&&(t.by.monthday||t.by.day?t.by.monthday?t.by.monthday.forEach(b("monthday")):t.by.day&&t.by.day.forEach(b("day")):_(),t.by.month&&E("month",t.by.month),t.by.day&&t.by.monthday&&E("day",t.by.day)),t.by&&"weekly"===m&&(t.by.day?t.by.day.forEach(b("day")):_(),t.by.month&&E("month",t.by.month)),t.by&&"daily"===m&&(_(),p.forEach((function(e){var n=t.by[e];n&&E(e,n)}))),g.sort((function(e,t){return e-t})),t.by&&t.by.setpos&&E("setpos",t.by.setpos),t.by&&Object.keys(t.by).length?A():_();var S=[];return g=g.filter((function(e){var t=new Date(+e).toLocaleDateString();return!S.includes(t)&&(S.push(t),!0)})),r("Set cache",s,u),y[s][u]=g,g}(A,n,i);if(r("Iteration results",JSON.stringify(m.map((function(e){return new Date(e).toLocaleDateString()})))),!m.length)return i.getFullYear()=C)return r(h.toLocaleDateString(),"count"),O=!0,!0;if(h>=E)return r(h.toLocaleDateString(),"endMonth"),O=!0,!0;if(A.until&&h>A.until)return r(h.toLocaleDateString(),"until"),O=!0,!0;if(!(h=E||h=g){if(v[c.id]&&v[c.id].includes(c.start))return;v[c.id]=v[c.id]||[],v[c.id].push(c.start)}if(b.timeZone&&!c.isAllDay){var m=function(e,t,n){var r=function(e,t){let n=e.toLocaleString("en-CA",{timeZone:t,hour12:!1}).replace(", ","T");return n+="."+e.getMilliseconds().toString().padStart(3,"0"),-(new Date(n+"Z")-e)},o=Intl.DateTimeFormat().resolvedOptions().timeZone,a=r(t,e)-r(n,e);return r(t,o)-r(n,o)-a}(b.timeZone,o,h);c.start+=m,c.end+=m}return s.push(c),D?(y(),!0):void 0}r(h.toLocaleDateString(),"start")})),O||I(i)}};I(o),r("Added this month (all events)",s.map((function(e){return new Date(e.start).toLocaleDateString()})))}}}}}))})),s},t.getAllOccurrences=function(e){if(!e.recurrenceRule)return[e.start];var n=e.recurrenceRule;if(!n.until&&!n.count)return!1;var r=[e.start],o=new Date(e.start);o.setDate(15);for(var a=[],i=0;(a=t.getRecurring([t.getMonthId(o)],[e]))&&(n.count?r.length=1e4;)n.setDate(n.getDate()-a),o++;return{d:o*=a,h:(n=new Date(t)).getHours()-r.getHours(),m:n.getMinutes()-r.getMinutes()}};return t.applyUpdates=function(e){return e.forEach((function(e){if(e.raw={start:e.start,end:e.end},e.recUpdate){var t,n=e.recUpdate.from||{},r=e.recUpdate.one||{},o=e.start,a=m(e).filter((function(e){return e._start>o})).shift(),i=function(t,n){var r=t[n],o=new Date(e.raw[n]);o.setDate(o.getDate()+r.d),o.setHours(o.getHours()+r.h),o.setMinutes(o.getMinutes()+r.m),e[n]=+o};(t=n,Object.keys(t).sort((function(e,t){return Number(e)-Number(t)}))).forEach((function(t){o",noCalendar:!1,now:new Date,onChange:[],onClose:[],onDayCreate:[],onDestroy:[],onKeyDown:[],onMonthChange:[],onOpen:[],onParseConfig:[],onReady:[],onValueUpdate:[],onYearChange:[],onPreCalendarPosition:[],plugins:[],position:"auto",positionElement:void 0,prevArrow:"",shorthandCurrentMonth:!1,showMonths:1,static:!1,time_24hr:!1,weekNumbers:!1,wrap:!1},o={weekdays:{shorthand:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],longhand:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},months:{shorthand:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],longhand:["January","February","March","April","May","June","July","August","September","October","November","December"]},daysInMonth:[31,28,31,30,31,30,31,31,30,31,30,31],firstDayOfWeek:0,ordinal:function(e){var t=e%100;if(t>3&&t<21)return"th";switch(t%10){case 1:return"st";case 2:return"nd";case 3:return"rd";default:return"th"}},rangeSeparator:" to ",weekAbbreviation:"Wk",scrollTitle:"Scroll to increment",toggleTitle:"Click to toggle",amPM:["AM","PM"],yearAriaLabel:"Year",monthAriaLabel:"Month",hourAriaLabel:"Hour",minuteAriaLabel:"Minute",time_24hr:!1},a=function(e,t){return void 0===t&&(t=2),("000"+e).slice(-1*t)},i=function(e){return!0===e?1:0};function s(e,t){var n;return function(){var r=this;clearTimeout(n),n=setTimeout((function(){return e.apply(r,arguments)}),t)}}var c=function(e){return e instanceof Array?e:[e]};function u(e,t,n){if(!0===n)return e.classList.add(t);e.classList.remove(t)}function l(e,t,n){var r=window.document.createElement(e);return t=t||"",n=n||"",r.className=t,void 0!==n&&(r.textContent=n),r}function f(e){for(;e.firstChild;)e.removeChild(e.firstChild)}function d(e,t){return t(e)?e:e.parentNode?d(e.parentNode,t):void 0}function h(e,t){var n=l("div","numInputWrapper"),r=l("input","numInput "+e),o=l("span","arrowUp"),a=l("span","arrowDown");if(-1===navigator.userAgent.indexOf("MSIE 9.0")?r.type="number":(r.type="text",r.pattern="\\d*"),void 0!==t)for(var i in t)r.setAttribute(i,t[i]);return n.appendChild(r),n.appendChild(o),n.appendChild(a),n}function p(e){try{return"function"==typeof e.composedPath?e.composedPath()[0]:e.target}catch(t){return e.target}}var y=function(){},v=function(e,t,n){return n.months[t?"shorthand":"longhand"][e]},m={D:y,F:function(e,t,n){e.setMonth(n.months.longhand.indexOf(t))},G:function(e,t){e.setHours(parseFloat(t))},H:function(e,t){e.setHours(parseFloat(t))},J:function(e,t){e.setDate(parseFloat(t))},K:function(e,t,n){e.setHours(e.getHours()%12+12*i(new RegExp(n.amPM[1],"i").test(t)))},M:function(e,t,n){e.setMonth(n.months.shorthand.indexOf(t))},S:function(e,t){e.setSeconds(parseFloat(t))},U:function(e,t){return new Date(1e3*parseFloat(t))},W:function(e,t,n){var r=parseInt(t),o=new Date(e.getFullYear(),0,2+7*(r-1),0,0,0,0);return o.setDate(o.getDate()-o.getDay()+n.firstDayOfWeek),o},Y:function(e,t){e.setFullYear(parseFloat(t))},Z:function(e,t){return new Date(t)},d:function(e,t){e.setDate(parseFloat(t))},h:function(e,t){e.setHours(parseFloat(t))},i:function(e,t){e.setMinutes(parseFloat(t))},j:function(e,t){e.setDate(parseFloat(t))},l:y,m:function(e,t){e.setMonth(parseFloat(t)-1)},n:function(e,t){e.setMonth(parseFloat(t)-1)},s:function(e,t){e.setSeconds(parseFloat(t))},u:function(e,t){return new Date(parseFloat(t))},w:y,y:function(e,t){e.setFullYear(2e3+parseFloat(t))}},g={D:"(\\w+)",F:"(\\w+)",G:"(\\d\\d|\\d)",H:"(\\d\\d|\\d)",J:"(\\d\\d|\\d)\\w+",K:"",M:"(\\w+)",S:"(\\d\\d|\\d)",U:"(.+)",W:"(\\d\\d|\\d)",Y:"(\\d{4})",Z:"(.+)",d:"(\\d\\d|\\d)",h:"(\\d\\d|\\d)",i:"(\\d\\d|\\d)",j:"(\\d\\d|\\d)",l:"(\\w+)",m:"(\\d\\d|\\d)",n:"(\\d\\d|\\d)",s:"(\\d\\d|\\d)",u:"(.+)",w:"(\\d\\d|\\d)",y:"(\\d{2})"},E={Z:function(e){return e.toISOString()},D:function(e,t,n){return t.weekdays.shorthand[E.w(e,t,n)]},F:function(e,t,n){return v(E.n(e,t,n)-1,!1,t)},G:function(e,t,n){return a(E.h(e,t,n))},H:function(e){return a(e.getHours())},J:function(e,t){return void 0!==t.ordinal?e.getDate()+t.ordinal(e.getDate()):e.getDate()},K:function(e,t){return t.amPM[i(e.getHours()>11)]},M:function(e,t){return v(e.getMonth(),!0,t)},S:function(e){return a(e.getSeconds())},U:function(e){return e.getTime()/1e3},W:function(e,t,n){return n.getWeek(e)},Y:function(e){return a(e.getFullYear(),4)},d:function(e){return a(e.getDate())},h:function(e){return e.getHours()%12?e.getHours()%12:12},i:function(e){return a(e.getMinutes())},j:function(e){return e.getDate()},l:function(e,t){return t.weekdays.longhand[e.getDay()]},m:function(e){return a(e.getMonth()+1)},n:function(e){return e.getMonth()+1},s:function(e){return e.getSeconds()},u:function(e){return e.getTime()},w:function(e){return e.getDay()},y:function(e){return String(e.getFullYear()).substring(2)}},b=function(e){var t=e.config,n=void 0===t?r:t,a=e.l10n,i=void 0===a?o:a,s=e.isMobile,c=void 0!==s&&s;return function(e,t,r){var o=r||i;return void 0===n.formatDate||c?t.split("").map((function(t,r,a){return E[t]&&"\\"!==a[r-1]?E[t](e,o,n):"\\"!==t?t:""})).join(""):n.formatDate(e,t,o)}},A=function(e){var t=e.config,n=void 0===t?r:t,a=e.l10n,i=void 0===a?o:a;return function(e,t,o,a){if(0===e||e){var s,c=a||i,u=e;if(e instanceof Date)s=new Date(e.getTime());else if("string"!=typeof e&&void 0!==e.toFixed)s=new Date(e);else if("string"==typeof e){var l=t||(n||r).dateFormat,f=String(e).trim();if("today"===f)s=new Date,o=!0;else if(/Z$/.test(f)||/GMT$/.test(f))s=new Date(e);else if(n&&n.parseDate)s=n.parseDate(e,l);else{s=n&&n.noCalendar?new Date((new Date).setHours(0,0,0,0)):new Date((new Date).getFullYear(),0,1,0,0,0,0);for(var d=void 0,h=[],p=0,y=0,v="";p=0?new Date:new Date(E.config.minDate.getTime()),n=O(E.config);t.setHours(n.hours,n.minutes,n.seconds,t.getMilliseconds()),E.selectedDates=[t],E.latestSelectedDateObj=t}void 0!==e&&"blur"!==e.type&&function(e){e.preventDefault();var t="keydown"===e.type,n=p(e),r=n;void 0!==E.amPM&&n===E.amPM&&(E.amPM.textContent=E.l10n.amPM[i(E.amPM.textContent===E.l10n.amPM[0])]);var o=parseFloat(r.getAttribute("min")),s=parseFloat(r.getAttribute("max")),c=parseFloat(r.getAttribute("step")),u=parseInt(r.value,10),l=u+c*(e.delta||(t?38===e.which?1:-1:0));if(void 0!==r.value&&2===r.value.length){var f=r===E.hourElement,d=r===E.minuteElement;ls&&(l=r===E.hourElement?l-s-i(!E.amPM):o,d&&L(void 0,1,E.hourElement)),E.amPM&&f&&(1===c?l+u===23:Math.abs(l-u)>c)&&(E.amPM.textContent=E.l10n.amPM[i(E.amPM.textContent===E.l10n.amPM[0])]),r.value=a(l)}}(e);var r=E._input.value;x(),be(),E._input.value!==r&&E._debouncedChange()}function x(){if(void 0!==E.hourElement&&void 0!==E.minuteElement){var e,t,n=(parseInt(E.hourElement.value.slice(-2),10)||0)%24,r=(parseInt(E.minuteElement.value,10)||0)%60,o=void 0!==E.secondElement?(parseInt(E.secondElement.value,10)||0)%60:0;void 0!==E.amPM&&(e=n,t=E.amPM.textContent,n=e%12+12*i(t===E.l10n.amPM[1]));var a=void 0!==E.config.minTime||E.config.minDate&&E.minDateHasTime&&E.latestSelectedDateObj&&0===_(E.latestSelectedDateObj,E.config.minDate,!0);if(void 0!==E.config.maxTime||E.config.maxDate&&E.maxDateHasTime&&E.latestSelectedDateObj&&0===_(E.latestSelectedDateObj,E.config.maxDate,!0)){var s=void 0!==E.config.maxTime?E.config.maxTime:E.config.maxDate;(n=Math.min(n,s.getHours()))===s.getHours()&&(r=Math.min(r,s.getMinutes())),r===s.getMinutes()&&(o=Math.min(o,s.getSeconds()))}if(a){var c=void 0!==E.config.minTime?E.config.minTime:E.config.minDate;(n=Math.max(n,c.getHours()))===c.getHours()&&r=12)]),void 0!==E.secondElement&&(E.secondElement.value=a(n)))}function P(e){var t=p(e),n=parseInt(t.value)+(e.delta||0);(n/1e3>1||"Enter"===e.key&&!/[^\d]/.test(n.toString()))&&Z(n)}function k(e,t,n,r){return t instanceof Array?t.forEach((function(t){return k(e,t,n,r)})):e instanceof Array?e.forEach((function(e){return k(e,t,n,r)})):(e.addEventListener(t,n,r),void E._handlers.push({remove:function(){return e.removeEventListener(t,n)}}))}function R(){ye("onChange")}function M(e,t){var n=void 0!==e?E.parseDate(e):E.latestSelectedDateObj||(E.config.minDate&&E.config.minDate>E.now?E.config.minDate:E.config.maxDate&&E.config.maxDate=0&&_(e,E.selectedDates[1])<=0}(t)&&!me(t)&&a.classList.add("inRange"),E.weekNumbers&&1===E.config.showMonths&&"prevMonthDay"!==e&&n%7==1&&E.weekNumbers.insertAdjacentHTML("beforeend",""+E.config.getWeek(t)+""),ye("onDayCreate",a),a}function K(e){e.focus(),"range"===E.config.mode&&re(e)}function j(e){for(var t=e>0?0:E.config.showMonths-1,n=e>0?E.config.showMonths:-1,r=t;r!=n;r+=e)for(var o=E.daysContainer.children[r],a=e>0?0:o.children.length-1,i=e>0?o.children.length:-1,s=a;s!=i;s+=e){var c=o.children[s];if(-1===c.className.indexOf("hidden")&&$(c.dateObj))return c}}function U(e,t){var n=ee(document.activeElement||document.body),r=void 0!==e?e:n?document.activeElement:void 0!==E.selectedDateElem&&ee(E.selectedDateElem)?E.selectedDateElem:void 0!==E.todayDateElem&&ee(E.todayDateElem)?E.todayDateElem:j(t>0?1:-1);void 0===r?E._input.focus():n?function(e,t){for(var n=-1===e.className.indexOf("Month")?e.dateObj.getMonth():E.currentMonth,r=t>0?E.config.showMonths:-1,o=t>0?1:-1,a=n-E.currentMonth;a!=r;a+=o)for(var i=E.daysContainer.children[a],s=n-E.currentMonth===a?e.$i+t:t<0?i.children.length-1:0,c=i.children.length,u=s;u>=0&&u0?c:-1);u+=o){var l=i.children[u];if(-1===l.className.indexOf("hidden")&&$(l.dateObj)&&Math.abs(e.$i-u)>=Math.abs(t))return K(l)}E.changeMonth(o),U(j(o),0)}(r,t):K(r)}function B(e,t){for(var n=(new Date(e,t,1).getDay()-E.l10n.firstDayOfWeek+7)%7,r=E.utils.getDaysInMonth((t-1+12)%12,e),o=E.utils.getDaysInMonth(t,e),a=window.document.createDocumentFragment(),i=E.config.showMonths>1,s=i?"prevMonthDay hidden":"prevMonthDay",c=i?"nextMonthDay hidden":"nextMonthDay",u=r+1-n,f=0;u<=r;u++,f++)a.appendChild(H(s,new Date(e,t-1,u),u,f));for(u=1;u<=o;u++,f++)a.appendChild(H("",new Date(e,t,u),u,f));for(var d=o+1;d<=42-n&&(1===E.config.showMonths||f%7!=0);d++,f++)a.appendChild(H(c,new Date(e,t+1,d%o),d,f));var h=l("div","dayContainer");return h.appendChild(a),h}function V(){if(void 0!==E.daysContainer){f(E.daysContainer),E.weekNumbers&&f(E.weekNumbers);for(var e=document.createDocumentFragment(),t=0;t1||"dropdown"!==E.config.monthSelectorType)){var e=function(e){return!(void 0!==E.config.minDate&&E.currentYear===E.config.minDate.getFullYear()&&eE.config.maxDate.getMonth())};E.monthsDropdownContainer.tabIndex=-1,E.monthsDropdownContainer.innerHTML="";for(var t=0;t<12;t++)if(e(t)){var n=l("option","flatpickr-monthDropdown-month");n.value=new Date(E.currentYear,t).getMonth().toString(),n.textContent=v(t,E.config.shorthandCurrentMonth,E.l10n),n.tabIndex=-1,E.currentMonth===t&&(n.selected=!0),E.monthsDropdownContainer.appendChild(n)}}}function Y(){var e,t=l("div","flatpickr-month"),n=window.document.createDocumentFragment();E.config.showMonths>1||"static"===E.config.monthSelectorType?e=l("span","cur-month"):(E.monthsDropdownContainer=l("select","flatpickr-monthDropdown-months"),E.monthsDropdownContainer.setAttribute("aria-label",E.l10n.monthAriaLabel),k(E.monthsDropdownContainer,"change",(function(e){var t=p(e),n=parseInt(t.value,10);E.changeMonth(n-E.currentMonth),ye("onMonthChange")})),G(),e=E.monthsDropdownContainer);var r=h("cur-year",{tabindex:"-1"}),o=r.getElementsByTagName("input")[0];o.setAttribute("aria-label",E.l10n.yearAriaLabel),E.config.minDate&&o.setAttribute("min",E.config.minDate.getFullYear().toString()),E.config.maxDate&&(o.setAttribute("max",E.config.maxDate.getFullYear().toString()),o.disabled=!!E.config.minDate&&E.config.minDate.getFullYear()===E.config.maxDate.getFullYear());var a=l("div","flatpickr-current-month");return a.appendChild(e),a.appendChild(r),n.appendChild(a),t.appendChild(n),{container:t,yearElement:o,monthElement:e}}function J(){f(E.monthNav),E.monthNav.appendChild(E.prevMonthNav),E.config.showMonths&&(E.yearElements=[],E.monthElements=[]);for(var e=E.config.showMonths;e--;){var t=Y();E.yearElements.push(t.yearElement),E.monthElements.push(t.monthElement),E.monthNav.appendChild(t.container)}E.monthNav.appendChild(E.nextMonthNav)}function q(){E.weekdayContainer?f(E.weekdayContainer):E.weekdayContainer=l("div","flatpickr-weekdays");for(var e=E.config.showMonths;e--;){var t=l("div","flatpickr-weekdaycontainer");E.weekdayContainer.appendChild(t)}return W(),E.weekdayContainer}function W(){if(E.weekdayContainer){var e=E.l10n.firstDayOfWeek,n=t(E.l10n.weekdays.shorthand);e>0&&e\n "+n.join("")+"\n \n "}}function Q(e,t){void 0===t&&(t=!0);var n=t?e:e-E.currentMonth;n<0&&!0===E._hidePrevMonthArrow||n>0&&!0===E._hideNextMonthArrow||(E.currentMonth+=n,(E.currentMonth<0||E.currentMonth>11)&&(E.currentYear+=E.currentMonth>11?1:-1,E.currentMonth=(E.currentMonth+12)%12,ye("onYearChange"),G()),V(),ye("onMonthChange"),ge())}function z(e){return!(!E.config.appendTo||!E.config.appendTo.contains(e))||E.calendarContainer.contains(e)}function X(e){if(E.isOpen&&!E.config.inline){var t=p(e),n=z(t),r=t===E.input||t===E.altInput||E.element.contains(t)||e.path&&e.path.indexOf&&(~e.path.indexOf(E.input)||~e.path.indexOf(E.altInput)),o="blur"===e.type?r&&e.relatedTarget&&!z(e.relatedTarget):!r&&!n&&!z(e.relatedTarget),a=!E.config.ignoredFocusElements.some((function(e){return e.contains(t)}));o&&a&&(void 0!==E.timeContainer&&void 0!==E.minuteElement&&void 0!==E.hourElement&&""!==E.input.value&&void 0!==E.input.value&&C(),E.close(),E.config&&"range"===E.config.mode&&1===E.selectedDates.length&&(E.clear(!1),E.redraw()))}}function Z(e){if(!(!e||E.config.minDate&&eE.config.maxDate.getFullYear())){var t=e,n=E.currentYear!==t;E.currentYear=t||E.currentYear,E.config.maxDate&&E.currentYear===E.config.maxDate.getFullYear()?E.currentMonth=Math.min(E.config.maxDate.getMonth(),E.currentMonth):E.config.minDate&&E.currentYear===E.config.minDate.getFullYear()&&(E.currentMonth=Math.max(E.config.minDate.getMonth(),E.currentMonth)),n&&(E.redraw(),ye("onYearChange"),G())}}function $(e,t){var n;void 0===t&&(t=!0);var r=E.parseDate(e,void 0,t);if(E.config.minDate&&r&&_(r,E.config.minDate,void 0!==t?t:!E.minDateHasTime)<0||E.config.maxDate&&r&&_(r,E.config.maxDate,void 0!==t?t:!E.maxDateHasTime)>0)return!1;if(!E.config.enable&&0===E.config.disable.length)return!0;if(void 0===r)return!1;for(var o=!!E.config.enable,a=null!==(n=E.config.enable)&&void 0!==n?n:E.config.disable,i=0,s=void 0;i=s.from.getTime()&&r.getTime()<=s.to.getTime())return o}return!o}function ee(e){return void 0!==E.daysContainer&&-1===e.className.indexOf("hidden")&&-1===e.className.indexOf("flatpickr-disabled")&&E.daysContainer.contains(e)}function te(e){e.target!==E._input||!(E.selectedDates.length>0||E._input.value.length>0)||e.relatedTarget&&z(e.relatedTarget)||E.setDate(E._input.value,!0,e.target===E.altInput?E.config.altFormat:E.config.dateFormat)}function ne(e){var t=p(e),n=E.config.wrap?y.contains(t):t===E._input,r=E.config.allowInput,o=E.isOpen&&(!r||!n),a=E.config.inline&&n&&!r;if(13===e.keyCode&&n){if(r)return E.setDate(E._input.value,!0,t===E.altInput?E.config.altFormat:E.config.dateFormat),t.blur();E.open()}else if(z(t)||o||a){var i=!!E.timeContainer&&E.timeContainer.contains(t);switch(e.keyCode){case 13:i?(e.preventDefault(),C(),le()):fe(e);break;case 27:e.preventDefault(),le();break;case 8:case 46:n&&!E.config.allowInput&&(e.preventDefault(),E.clear());break;case 37:case 39:if(i||n)E.hourElement&&E.hourElement.focus();else if(e.preventDefault(),void 0!==E.daysContainer&&(!1===r||document.activeElement&&ee(document.activeElement))){var s=39===e.keyCode?1:-1;e.ctrlKey?(e.stopPropagation(),Q(s),U(j(1),0)):U(void 0,s)}break;case 38:case 40:e.preventDefault();var c=40===e.keyCode?1:-1;E.daysContainer&&void 0!==t.$i||t===E.input||t===E.altInput?e.ctrlKey?(e.stopPropagation(),Z(E.currentYear-c),U(j(1),0)):i||U(void 0,7*c):t===E.currentYearElement?Z(E.currentYear-c):E.config.enableTime&&(!i&&E.hourElement&&E.hourElement.focus(),C(e),E._debouncedChange());break;case 9:if(i){var u=[E.hourElement,E.minuteElement,E.secondElement,E.amPM].concat(E.pluginElements).filter((function(e){return e})),l=u.indexOf(t);if(-1!==l){var f=u[l+(e.shiftKey?-1:1)];e.preventDefault(),(f||E._input).focus()}}else!E.config.noCalendar&&E.daysContainer&&E.daysContainer.contains(t)&&e.shiftKey&&(e.preventDefault(),E._input.focus())}}if(void 0!==E.amPM&&t===E.amPM)switch(e.key){case E.l10n.amPM[0].charAt(0):case E.l10n.amPM[0].charAt(0).toLowerCase():E.amPM.textContent=E.l10n.amPM[0],x(),be();break;case E.l10n.amPM[1].charAt(0):case E.l10n.amPM[1].charAt(0).toLowerCase():E.amPM.textContent=E.l10n.amPM[1],x(),be()}(n||z(t))&&ye("onKeyDown",e)}function re(e){if(1===E.selectedDates.length&&(!e||e.classList.contains("flatpickr-day")&&!e.classList.contains("flatpickr-disabled"))){for(var t=e?e.dateObj.getTime():E.days.firstElementChild.dateObj.getTime(),n=E.parseDate(E.selectedDates[0],void 0,!0).getTime(),r=Math.min(t,E.selectedDates[0].getTime()),o=Math.max(t,E.selectedDates[0].getTime()),a=!1,i=0,s=0,c=r;cr&&ci)?i=c:c>n&&(!s||c0&&h0&&h>s;return p?(d.classList.add("notAllowed"),["inRange","startRange","endRange"].forEach((function(e){d.classList.remove(e)})),"continue"):a&&!p?"continue":(["startRange","inRange","endRange","notAllowed"].forEach((function(e){d.classList.remove(e)})),void(void 0!==e&&(e.classList.add(t<=E.selectedDates[0].getTime()?"startRange":"endRange"),nt&&h===n&&d.classList.add("endRange"),h>=i&&(0===s||h<=s)&&(u=n,f=t,(c=h)>Math.min(u,f)&&c0||n.getMinutes()>0||n.getSeconds()>0),E.selectedDates&&(E.selectedDates=E.selectedDates.filter((function(e){return $(e)})),E.selectedDates.length||"min"!==e||I(n),be()),E.daysContainer&&(ue(),void 0!==n?E.currentYearElement[e]=n.getFullYear().toString():E.currentYearElement.removeAttribute(e),E.currentYearElement.disabled=!!r&&void 0!==n&&r.getFullYear()===n.getFullYear())}}function ie(){return E.config.wrap?y.querySelector("[data-input]"):y}function se(){"object"!=typeof E.config.locale&&void 0===T.l10ns[E.config.locale]&&E.config.errorHandler(new Error("flatpickr: invalid locale "+E.config.locale)),E.l10n=e(e({},T.l10ns.default),"object"==typeof E.config.locale?E.config.locale:"default"!==E.config.locale?T.l10ns[E.config.locale]:void 0),g.K="("+E.l10n.amPM[0]+"|"+E.l10n.amPM[1]+"|"+E.l10n.amPM[0].toLowerCase()+"|"+E.l10n.amPM[1].toLowerCase()+")",void 0===e(e({},m),JSON.parse(JSON.stringify(y.dataset||{}))).time_24hr&&void 0===T.defaultConfig.time_24hr&&(E.config.time_24hr=E.l10n.time_24hr),E.formatDate=b(E),E.parseDate=A({config:E.config,l10n:E.l10n})}function ce(e){if("function"!=typeof E.config.position){if(void 0!==E.calendarContainer){ye("onPreCalendarPosition");var t=e||E._positionElement,n=Array.prototype.reduce.call(E.calendarContainer.children,(function(e,t){return e+t.offsetHeight}),0),r=E.calendarContainer.offsetWidth,o=E.config.position.split(" "),a=o[0],i=o.length>1?o[1]:null,s=t.getBoundingClientRect(),c=window.innerHeight-s.bottom,l="above"===a||"below"!==a&&cn,f=window.pageYOffset+s.top+(l?-n-2:t.offsetHeight+2);if(u(E.calendarContainer,"arrowTop",!l),u(E.calendarContainer,"arrowBottom",l),!E.config.inline){var d=window.pageXOffset+s.left,h=!1,p=!1;"center"===i?(d-=(r-s.width)/2,h=!0):"right"===i&&(d-=r-s.width,p=!0),u(E.calendarContainer,"arrowLeft",!h&&!p),u(E.calendarContainer,"arrowCenter",h),u(E.calendarContainer,"arrowRight",p);var y=window.document.body.offsetWidth-(window.pageXOffset+s.right),v=d+r>window.document.body.offsetWidth,m=y+r>window.document.body.offsetWidth;if(u(E.calendarContainer,"rightMost",v),!E.config.static)if(E.calendarContainer.style.top=f+"px",v)if(m){var g=function(){for(var e=null,t=0;tE.currentMonth+E.config.showMonths-1)&&"range"!==E.config.mode;if(E.selectedDateElem=n,"single"===E.config.mode)E.selectedDates=[r];else if("multiple"===E.config.mode){var a=me(r);a?E.selectedDates.splice(parseInt(a),1):E.selectedDates.push(r)}else"range"===E.config.mode&&(2===E.selectedDates.length&&E.clear(!1,!1),E.latestSelectedDateObj=r,E.selectedDates.push(r),0!==_(r,E.selectedDates[0],!0)&&E.selectedDates.sort((function(e,t){return e.getTime()-t.getTime()})));if(x(),o){var i=E.currentYear!==r.getFullYear();E.currentYear=r.getFullYear(),E.currentMonth=r.getMonth(),i&&(ye("onYearChange"),G()),ye("onMonthChange")}if(ge(),V(),be(),o||"range"===E.config.mode||1!==E.config.showMonths?void 0!==E.selectedDateElem&&void 0===E.hourElement&&E.selectedDateElem&&E.selectedDateElem.focus():K(n),void 0!==E.hourElement&&void 0!==E.hourElement&&E.hourElement.focus(),E.config.closeOnSelect){var s="single"===E.config.mode&&!E.config.enableTime,c="range"===E.config.mode&&2===E.selectedDates.length&&!E.config.enableTime;(s||c)&&le()}R()}}E.parseDate=A({config:E.config,l10n:E.l10n}),E._handlers=[],E.pluginElements=[],E.loadedPlugins=[],E._bind=k,E._setHoursFromDate=I,E._positionCalendar=ce,E.changeMonth=Q,E.changeYear=Z,E.clear=function(e,t){if(void 0===e&&(e=!0),void 0===t&&(t=!0),E.input.value="",void 0!==E.altInput&&(E.altInput.value=""),void 0!==E.mobileInput&&(E.mobileInput.value=""),E.selectedDates=[],E.latestSelectedDateObj=void 0,!0===t&&(E.currentYear=E._initialDate.getFullYear(),E.currentMonth=E._initialDate.getMonth()),!0===E.config.enableTime){var n=O(E.config);N(n.hours,n.minutes,n.seconds)}E.redraw(),e&&ye("onChange")},E.close=function(){E.isOpen=!1,E.isMobile||(void 0!==E.calendarContainer&&E.calendarContainer.classList.remove("open"),void 0!==E._input&&E._input.classList.remove("active")),ye("onClose")},E._createElement=l,E.destroy=function(){void 0!==E.config&&ye("onDestroy");for(var e=E._handlers.length;e--;)E._handlers[e].remove();if(E._handlers=[],E.mobileInput)E.mobileInput.parentNode&&E.mobileInput.parentNode.removeChild(E.mobileInput),E.mobileInput=void 0;else if(E.calendarContainer&&E.calendarContainer.parentNode)if(E.config.static&&E.calendarContainer.parentNode){var t=E.calendarContainer.parentNode;if(t.lastChild&&t.removeChild(t.lastChild),t.parentNode){for(;t.firstChild;)t.parentNode.insertBefore(t.firstChild,t);t.parentNode.removeChild(t)}}else E.calendarContainer.parentNode.removeChild(E.calendarContainer);E.altInput&&(E.input.type="text",E.altInput.parentNode&&E.altInput.parentNode.removeChild(E.altInput),delete E.altInput),E.input&&(E.input.type=E.input._type,E.input.classList.remove("flatpickr-input"),E.input.removeAttribute("readonly")),["_showTimeInput","latestSelectedDateObj","_hideNextMonthArrow","_hidePrevMonthArrow","__hideNextMonthArrow","__hidePrevMonthArrow","isMobile","isOpen","selectedDateElem","minDateHasTime","maxDateHasTime","days","daysContainer","_input","_positionElement","innerContainer","rContainer","monthNav","todayDateElem","calendarContainer","weekdayContainer","prevMonthNav","nextMonthNav","monthsDropdownContainer","currentMonthElement","currentYearElement","navigationCurrentMonth","selectedDateElem","config"].forEach((function(e){try{delete E[e]}catch(e){}}))},E.isEnabled=$,E.jumpToDate=M,E.open=function(e,t){if(void 0===t&&(t=E._positionElement),!0===E.isMobile){if(e){e.preventDefault();var n=p(e);n&&n.blur()}return void 0!==E.mobileInput&&(E.mobileInput.focus(),E.mobileInput.click()),void ye("onOpen")}if(!E._input.disabled&&!E.config.inline){var r=E.isOpen;E.isOpen=!0,r||(E.calendarContainer.classList.add("open"),E._input.classList.add("active"),ye("onOpen"),ce(t)),!0===E.config.enableTime&&!0===E.config.noCalendar&&(!1!==E.config.allowInput||void 0!==e&&E.timeContainer.contains(e.relatedTarget)||setTimeout((function(){return E.hourElement.select()}),50))}},E.redraw=ue,E.set=function(e,t){if(null!==e&&"object"==typeof e)for(var r in Object.assign(E.config,e),e)void 0!==de[r]&&de[r].forEach((function(e){return e()}));else E.config[e]=t,void 0!==de[e]?de[e].forEach((function(e){return e()})):n.indexOf(e)>-1&&(E.config[e]=c(t));E.redraw(),be(!0)},E.setDate=function(e,t,n){if(void 0===t&&(t=!1),void 0===n&&(n=E.config.dateFormat),0!==e&&!e||e instanceof Array&&0===e.length)return E.clear(t);he(e,n),E.latestSelectedDateObj=E.selectedDates[E.selectedDates.length-1],E.redraw(),M(void 0,t),I(),0===E.selectedDates.length&&E.clear(!1),be(t),t&&ye("onChange")},E.toggle=function(e){if(!0===E.isOpen)return E.close();E.open(e)};var de={locale:[se,W],showMonths:[J,S,q],minDate:[M],maxDate:[M],clickOpens:[function(){!0===E.config.clickOpens?(k(E._input,"focus",E.open),k(E._input,"click",E.open)):(E._input.removeEventListener("focus",E.open),E._input.removeEventListener("click",E.open))}]};function he(e,t){var n=[];if(e instanceof Array)n=e.map((function(e){return E.parseDate(e,t)}));else if(e instanceof Date||"number"==typeof e)n=[E.parseDate(e,t)];else if("string"==typeof e)switch(E.config.mode){case"single":case"time":n=[E.parseDate(e,t)];break;case"multiple":n=e.split(E.config.conjunction).map((function(e){return E.parseDate(e,t)}));break;case"range":n=e.split(E.l10n.rangeSeparator).map((function(e){return E.parseDate(e,t)}))}else E.config.errorHandler(new Error("Invalid date supplied: "+JSON.stringify(e)));E.selectedDates=E.config.allowInvalidPreload?n:n.filter((function(e){return e instanceof Date&&$(e,!1)})),"range"===E.config.mode&&E.selectedDates.sort((function(e,t){return e.getTime()-t.getTime()}))}function pe(e){return e.slice().map((function(e){return"string"==typeof e||"number"==typeof e||e instanceof Date?E.parseDate(e,void 0,!0):e&&"object"==typeof e&&e.from&&e.to?{from:E.parseDate(e.from,void 0),to:E.parseDate(e.to,void 0)}:e})).filter((function(e){return e}))}function ye(e,t){if(void 0!==E.config){var n=E.config[e];if(void 0!==n&&n.length>0)for(var r=0;n[r]&&r1||"static"===E.config.monthSelectorType?E.monthElements[t].textContent=v(n.getMonth(),E.config.shorthandCurrentMonth,E.l10n)+" ":E.monthsDropdownContainer.value=n.getMonth().toString(),e.value=n.getFullYear().toString()})),E._hidePrevMonthArrow=void 0!==E.config.minDate&&(E.currentYear===E.config.minDate.getFullYear()?E.currentMonth<=E.config.minDate.getMonth():E.currentYearE.config.maxDate.getMonth():E.currentYear>E.config.maxDate.getFullYear()))}function Ee(e){return E.selectedDates.map((function(t){return E.formatDate(t,e)})).filter((function(e,t,n){return"range"!==E.config.mode||E.config.enableTime||n.indexOf(e)===t})).join("range"!==E.config.mode?E.config.conjunction:E.l10n.rangeSeparator)}function be(e){void 0===e&&(e=!0),void 0!==E.mobileInput&&E.mobileFormatStr&&(E.mobileInput.value=void 0!==E.latestSelectedDateObj?E.formatDate(E.latestSelectedDateObj,E.mobileFormatStr):""),E.input.value=Ee(E.config.dateFormat),void 0!==E.altInput&&(E.altInput.value=Ee(E.config.altFormat)),!1!==e&&ye("onValueUpdate")}function Ae(e){var t=p(e),n=E.prevMonthNav.contains(t),r=E.nextMonthNav.contains(t);n||r?Q(n?-1:1):E.yearElements.indexOf(t)>=0?t.select():t.classList.contains("arrowUp")?E.changeYear(E.currentYear+1):t.classList.contains("arrowDown")&&E.changeYear(E.currentYear-1)}return function(){E.element=E.input=y,E.isOpen=!1,function(){var t=["wrap","weekNumbers","allowInput","allowInvalidPreload","clickOpens","time_24hr","enableTime","noCalendar","altInput","shorthandCurrentMonth","inline","static","enableSeconds","disableMobile"],o=e(e({},JSON.parse(JSON.stringify(y.dataset||{}))),m),a={};E.config.parseDate=o.parseDate,E.config.formatDate=o.formatDate,Object.defineProperty(E.config,"enable",{get:function(){return E.config._enable},set:function(e){E.config._enable=pe(e)}}),Object.defineProperty(E.config,"disable",{get:function(){return E.config._disable},set:function(e){E.config._disable=pe(e)}});var i="time"===o.mode;if(!o.dateFormat&&(o.enableTime||i)){var s=T.defaultConfig.dateFormat||r.dateFormat;a.dateFormat=o.noCalendar||i?"H:i"+(o.enableSeconds?":S":""):s+" H:i"+(o.enableSeconds?":S":"")}if(o.altInput&&(o.enableTime||i)&&!o.altFormat){var u=T.defaultConfig.altFormat||r.altFormat;a.altFormat=o.noCalendar||i?"h:i"+(o.enableSeconds?":S K":" K"):u+" h:i"+(o.enableSeconds?":S":"")+" K"}Object.defineProperty(E.config,"minDate",{get:function(){return E.config._minDate},set:ae("min")}),Object.defineProperty(E.config,"maxDate",{get:function(){return E.config._maxDate},set:ae("max")});var l=function(e){return function(t){E.config["min"===e?"_minTime":"_maxTime"]=E.parseDate(t,"H:i:S")}};Object.defineProperty(E.config,"minTime",{get:function(){return E.config._minTime},set:l("min")}),Object.defineProperty(E.config,"maxTime",{get:function(){return E.config._maxTime},set:l("max")}),"time"===o.mode&&(E.config.noCalendar=!0,E.config.enableTime=!0),Object.assign(E.config,a,o);for(var f=0;f-1?E.config[h]=c(d[h]).map(D).concat(E.config[h]):void 0===o[h]&&(E.config[h]=d[h])}o.altInputClass||(E.config.altInputClass=ie().className+" "+E.config.altInputClass),ye("onParseConfig")}(),se(),E.input=ie(),E.input?(E.input._type=E.input.type,E.input.type="text",E.input.classList.add("flatpickr-input"),E._input=E.input,E.config.altInput&&(E.altInput=l(E.input.nodeName,E.config.altInputClass),E._input=E.altInput,E.altInput.placeholder=E.input.placeholder,E.altInput.disabled=E.input.disabled,E.altInput.required=E.input.required,E.altInput.tabIndex=E.input.tabIndex,E.altInput.type="text",E.input.setAttribute("type","hidden"),!E.config.static&&E.input.parentNode&&E.input.parentNode.insertBefore(E.altInput,E.input.nextSibling)),E.config.allowInput||E._input.setAttribute("readonly","readonly"),E._positionElement=E.config.positionElement||E._input):E.config.errorHandler(new Error("Invalid input element specified")),function(){E.selectedDates=[],E.now=E.parseDate(E.config.now)||new Date;var e=E.config.defaultDate||("INPUT"!==E.input.nodeName&&"TEXTAREA"!==E.input.nodeName||!E.input.placeholder||E.input.value!==E.input.placeholder?E.input.value:null);e&&he(e,E.config.dateFormat),E._initialDate=E.selectedDates.length>0?E.selectedDates[0]:E.config.minDate&&E.config.minDate.getTime()>E.now.getTime()?E.config.minDate:E.config.maxDate&&E.config.maxDate.getTime()0&&(E.latestSelectedDateObj=E.selectedDates[0]),void 0!==E.config.minTime&&(E.config.minTime=E.parseDate(E.config.minTime,"H:i")),void 0!==E.config.maxTime&&(E.config.maxTime=E.parseDate(E.config.maxTime,"H:i")),E.minDateHasTime=!!E.config.minDate&&(E.config.minDate.getHours()>0||E.config.minDate.getMinutes()>0||E.config.minDate.getSeconds()>0),E.maxDateHasTime=!!E.config.maxDate&&(E.config.maxDate.getHours()>0||E.config.maxDate.getMinutes()>0||E.config.maxDate.getSeconds()>0)}(),E.utils={getDaysInMonth:function(e,t){return void 0===e&&(e=E.currentMonth),void 0===t&&(t=E.currentYear),1===e&&(t%4==0&&t%100!=0||t%400==0)?29:E.l10n.daysInMonth[e]}},E.isMobile||function(){var e=window.document.createDocumentFragment();if(E.calendarContainer=l("div","flatpickr-calendar"),E.calendarContainer.tabIndex=-1,!E.config.noCalendar){if(e.appendChild((E.monthNav=l("div","flatpickr-months"),E.yearElements=[],E.monthElements=[],E.prevMonthNav=l("span","flatpickr-prev-month"),E.prevMonthNav.innerHTML=E.config.prevArrow,E.nextMonthNav=l("span","flatpickr-next-month"),E.nextMonthNav.innerHTML=E.config.nextArrow,J(),Object.defineProperty(E,"_hidePrevMonthArrow",{get:function(){return E.__hidePrevMonthArrow},set:function(e){E.__hidePrevMonthArrow!==e&&(u(E.prevMonthNav,"flatpickr-disabled",e),E.__hidePrevMonthArrow=e)}}),Object.defineProperty(E,"_hideNextMonthArrow",{get:function(){return E.__hideNextMonthArrow},set:function(e){E.__hideNextMonthArrow!==e&&(u(E.nextMonthNav,"flatpickr-disabled",e),E.__hideNextMonthArrow=e)}}),E.currentYearElement=E.yearElements[0],ge(),E.monthNav)),E.innerContainer=l("div","flatpickr-innerContainer"),E.config.weekNumbers){var t=function(){E.calendarContainer.classList.add("hasWeeks");var e=l("div","flatpickr-weekwrapper");e.appendChild(l("span","flatpickr-weekday",E.l10n.weekAbbreviation));var t=l("div","flatpickr-weeks");return e.appendChild(t),{weekWrapper:e,weekNumbers:t}}(),n=t.weekWrapper,r=t.weekNumbers;E.innerContainer.appendChild(n),E.weekNumbers=r,E.weekWrapper=n}E.rContainer=l("div","flatpickr-rContainer"),E.rContainer.appendChild(q()),E.daysContainer||(E.daysContainer=l("div","flatpickr-days"),E.daysContainer.tabIndex=-1),V(),E.rContainer.appendChild(E.daysContainer),E.innerContainer.appendChild(E.rContainer),e.appendChild(E.innerContainer)}E.config.enableTime&&e.appendChild(function(){E.calendarContainer.classList.add("hasTime"),E.config.noCalendar&&E.calendarContainer.classList.add("noCalendar");var e=O(E.config);E.timeContainer=l("div","flatpickr-time"),E.timeContainer.tabIndex=-1;var t=l("span","flatpickr-time-separator",":"),n=h("flatpickr-hour",{"aria-label":E.l10n.hourAriaLabel});E.hourElement=n.getElementsByTagName("input")[0];var r=h("flatpickr-minute",{"aria-label":E.l10n.minuteAriaLabel});if(E.minuteElement=r.getElementsByTagName("input")[0],E.hourElement.tabIndex=E.minuteElement.tabIndex=-1,E.hourElement.value=a(E.latestSelectedDateObj?E.latestSelectedDateObj.getHours():E.config.time_24hr?e.hours:function(e){switch(e%24){case 0:case 12:return 12;default:return e%12}}(e.hours)),E.minuteElement.value=a(E.latestSelectedDateObj?E.latestSelectedDateObj.getMinutes():e.minutes),E.hourElement.setAttribute("step",E.config.hourIncrement.toString()),E.minuteElement.setAttribute("step",E.config.minuteIncrement.toString()),E.hourElement.setAttribute("min",E.config.time_24hr?"0":"1"),E.hourElement.setAttribute("max",E.config.time_24hr?"23":"12"),E.hourElement.setAttribute("maxlength","2"),E.minuteElement.setAttribute("min","0"),E.minuteElement.setAttribute("max","59"),E.minuteElement.setAttribute("maxlength","2"),E.timeContainer.appendChild(n),E.timeContainer.appendChild(t),E.timeContainer.appendChild(r),E.config.time_24hr&&E.timeContainer.classList.add("time24hr"),E.config.enableSeconds){E.timeContainer.classList.add("hasSeconds");var o=h("flatpickr-second");E.secondElement=o.getElementsByTagName("input")[0],E.secondElement.value=a(E.latestSelectedDateObj?E.latestSelectedDateObj.getSeconds():e.seconds),E.secondElement.setAttribute("step",E.minuteElement.getAttribute("step")),E.secondElement.setAttribute("min","0"),E.secondElement.setAttribute("max","59"),E.secondElement.setAttribute("maxlength","2"),E.timeContainer.appendChild(l("span","flatpickr-time-separator",":")),E.timeContainer.appendChild(o)}return E.config.time_24hr||(E.amPM=l("span","flatpickr-am-pm",E.l10n.amPM[i((E.latestSelectedDateObj?E.hourElement.value:E.config.defaultHour)>11)]),E.amPM.title=E.l10n.toggleTitle,E.amPM.tabIndex=-1,E.timeContainer.appendChild(E.amPM)),E.timeContainer}()),u(E.calendarContainer,"rangeMode","range"===E.config.mode),u(E.calendarContainer,"animate",!0===E.config.animate),u(E.calendarContainer,"multiMonth",E.config.showMonths>1),E.calendarContainer.appendChild(e);var o=void 0!==E.config.appendTo&&void 0!==E.config.appendTo.nodeType;if((E.config.inline||E.config.static)&&(E.calendarContainer.classList.add(E.config.inline?"inline":"static"),E.config.inline&&(!o&&E.element.parentNode?E.element.parentNode.insertBefore(E.calendarContainer,E._input.nextSibling):void 0!==E.config.appendTo&&E.config.appendTo.appendChild(E.calendarContainer)),E.config.static)){var s=l("div","flatpickr-wrapper");E.element.parentNode&&E.element.parentNode.insertBefore(s,E.element),s.appendChild(E.element),E.altInput&&s.appendChild(E.altInput),s.appendChild(E.calendarContainer)}E.config.static||E.config.inline||(void 0!==E.config.appendTo?E.config.appendTo:window.document.body).appendChild(E.calendarContainer)}(),function(){if(E.config.wrap&&["open","close","toggle","clear"].forEach((function(e){Array.prototype.forEach.call(E.element.querySelectorAll("[data-"+e+"]"),(function(t){return k(t,"click",E[e])}))})),E.isMobile)!function(){var e=E.config.enableTime?E.config.noCalendar?"time":"datetime-local":"date";E.mobileInput=l("input",E.input.className+" flatpickr-mobile"),E.mobileInput.tabIndex=1,E.mobileInput.type=e,E.mobileInput.disabled=E.input.disabled,E.mobileInput.required=E.input.required,E.mobileInput.placeholder=E.input.placeholder,E.mobileFormatStr="datetime-local"===e?"Y-m-d\\TH:i:S":"date"===e?"Y-m-d":"H:i:S",E.selectedDates.length>0&&(E.mobileInput.defaultValue=E.mobileInput.value=E.formatDate(E.selectedDates[0],E.mobileFormatStr)),E.config.minDate&&(E.mobileInput.min=E.formatDate(E.config.minDate,"Y-m-d")),E.config.maxDate&&(E.mobileInput.max=E.formatDate(E.config.maxDate,"Y-m-d")),E.input.getAttribute("step")&&(E.mobileInput.step=String(E.input.getAttribute("step"))),E.input.type="hidden",void 0!==E.altInput&&(E.altInput.type="hidden");try{E.input.parentNode&&E.input.parentNode.insertBefore(E.mobileInput,E.input.nextSibling)}catch(e){}k(E.mobileInput,"change",(function(e){E.setDate(p(e).value,!1,E.mobileFormatStr),ye("onChange"),ye("onClose")}))}();else{var e=s(oe,50);if(E._debouncedChange=s(R,300),E.daysContainer&&!/iPhone|iPad|iPod/i.test(navigator.userAgent)&&k(E.daysContainer,"mouseover",(function(e){"range"===E.config.mode&&re(p(e))})),k(window.document.body,"keydown",ne),E.config.inline||E.config.static||k(window,"resize",e),void 0!==window.ontouchstart?k(window.document,"touchstart",X):k(window.document,"mousedown",X),k(window.document,"focus",X,{capture:!0}),!0===E.config.clickOpens&&(k(E._input,"focus",E.open),k(E._input,"click",E.open)),void 0!==E.daysContainer&&(k(E.monthNav,"click",Ae),k(E.monthNav,["keyup","increment"],P),k(E.daysContainer,"click",fe)),void 0!==E.timeContainer&&void 0!==E.minuteElement&&void 0!==E.hourElement){var t=function(e){return p(e).select()};k(E.timeContainer,["increment"],C),k(E.timeContainer,"blur",C,{capture:!0}),k(E.timeContainer,"click",F),k([E.hourElement,E.minuteElement],["focus","click"],t),void 0!==E.secondElement&&k(E.secondElement,"focus",(function(){return E.secondElement&&E.secondElement.select()})),void 0!==E.amPM&&k(E.amPM,"click",(function(e){C(e),R()}))}E.config.allowInput&&k(E._input,"blur",te)}}(),(E.selectedDates.length||E.config.noCalendar)&&(E.config.enableTime&&I(E.config.noCalendar?E.latestSelectedDateObj:void 0),be(!1)),S();var t=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);!E.isMobile&&t&&ce(),ye("onReady")}(),E}function S(e,t){for(var n=Array.prototype.slice.call(e).filter((function(e){return e instanceof HTMLElement})),r=[],o=0;o{var f={setCustomize:()=>{}},d=function(e,t){if(!t||1===t)return e.store;var n=e.store.modules&&e.store.modules.team;return n?n.getTeam(t):void 0},h=function(t,n){t.emit("UPDATE",{teams:n.stores,roTeams:n.roStores,id:n.channel,loading:!n.ready&&!n.cacheready,readOnly:n.readOnly||!n.ready&&n.cacheready||n.offline,offline:n.offline,deleted:!n.stores.length,restricted:n.restricted,owned:t.Store.isOwned(n.owners),content:e.clone(n.proxy),hashes:n.hashes},t.clients)},p=function(e,t){var n=e.calendars[t];n&&n.reminders&&Object.keys(n.reminders).forEach((function(e){Array.isArray(n.reminders[e])&&n.reminders[e].forEach((function(e){clearTimeout(e)}))}))},y=function(e,t){var n=e.calendars[t];n&&(n.stores.length||(n.lm.stop(),p(e,t),delete e.calendars[t]))},v=function(e,t,n){t.stores.forEach((function(r){var o=d(e,r);if(o&&o.proxy&&o.rpc&&o.proxy.calendars){var a=o.proxy.calendars[t.channel];a&&(a.color!==n.color&&(a.color=n.color),a.title!==n.title&&(a.title=n.title))}}))},m=function(t,n,r,o){var a=+new Date,i=e.clone(r),s=i.id;if(Array.isArray(n[s])&&n[s].forEach((function(e){clearTimeout(e)})),n[s]=[],!r.deleted){var u=e.find(t,["store","proxy","hideReminders",s])||[],l=t.store.data.lastVisit;if(i.isAllDay&&(i.startDay&&(i.start=+c.parseDate(i.startDay)),i.endDay)){var f=c.parseDate(i.endDay);f.setHours(23),f.setMinutes(59),f.setSeconds(59),i.end=+f}var d=a-6048e5,h=o&&i.start>l&&i.end<=a&&i.end>d;if(i.end<=a&&!h)return delete n[s],void function(t,n){var r=e.find(t,["store","proxy","hideReminders"])||{};Object.keys(r).filter((function(e){return e===n})).forEach((function(e){delete r[e]}))}(t,s);var p=!1,y=function(n){p=!0,t.Store.onReadyEvt.reg((function(){!function(n){if(!e.find(t,["store","proxy","settings","general","calendar","hideNotif"])){var r=i.start<=a?i.start:+new Date;t.store.mailbox.showMessage("reminders",{msg:{ctime:r,type:"REMINDER",missed:Boolean(h),content:i},hash:"REMINDER|"+s+"-"+n},null,(function(){}))}}(n)}))},v=i.reminders||[];v.sort((function(e,t){return e-t})),v.some((function(e){var t=a+6e4*e;if(!u.some((function(t){return e>=t})))return i.start-t>=2147483647||(i.start<=t?(y(e),!0):void n[s].push(setTimeout((function(){y(e)}),i.start-t)))})),p||t.Store.onReadyEvt.reg((function(){t.store.mailbox.hideMessage("reminders",{hash:"REMINDER|"+s},null,(function(){}))}))}},g=function(t,n,r,o){var i=function(e){var t=new Date,n=new Date(t.getFullYear(),t.getMonth()-1,15),r=new Date(t.getFullYear(),t.getMonth()+1,15),o=a.getMonthId(n),i=a.getMonthId(t),s=a.getMonthId(r),c=a.getRecurring([o,i,s],[e]),u=[e];return Array.prototype.push.apply(u,c),u}(e.clone(r));i.forEach((function(e){m(t,n,e,o)}))},E=function(e,t,n){var r=e.calendars[t];n&&r&&r.reminders&&(1===r.stores.length&&0===r.stores[0]||g(e,r.reminders,n))},b=function(t,n,r){var o=t.calendars[n];if(o&&o.reminders&&!Object.keys(o.reminders).length&&(1!==o.stores.length||0!==o.stores[0])){var a=e.find(o,["proxy","content"]);a&&Object.keys(a).forEach((function(e){g(t,o.reminders,a[e],r)}))}},A=function(n,r,a){var c=e.once(e.mkAsync(a||function(){})),f=r.storeId,y=r.data,m=y.channel;if(m){var g=n.calendars[m],A=function(){h(n,g)};if(g){if(g.readOnly&&y.href){var _=t.parsePadUrl(y.href),w=t.getSecrets("calendar",_.hash,y.password),O=u.createEncryptor(w.keys);g.hashes.editHash=t.getEditHashFromKeys(w),g.lm.setReadOnly(!1,O),g.readOnly=!1}else if(0===f)return 1===g.stores.length&&0===g.stores[0]&&g.tempId.length&&r.cId&&g.tempId.push(r.cId),void c();return-1!==g.roStores.indexOf(f)&&y.href&&(g.roStores.splice(g.roStores.indexOf(f),1),-1!==g.stores.indexOf(0)&&g.stores.splice(g.stores.indexOf(0),1),A()),g.stores&&-1!==g.stores.indexOf(f)?void c():(-1!==g.stores.indexOf(0)&&(g.stores.splice(g.stores.indexOf(0),1),g.tempId=[]),g.stores.push(f),y.href||g.roStores.push(f),A(),void c())}g=n.calendars[m]={ready:!1,channel:m,readOnly:!y.href,tempId:[],stores:[f],roStores:y.href?[]:[f],reminders:{},hashes:{}},0===f&&g.tempId.push(r.cId);var D=t.parsePadUrl(y.href||y.roHref),S=t.getSecrets("calendar",D.hash,y.password),T=u.createEncryptor(S.keys);g.hashes.viewHash=t.getViewHashFromKeys(S),y.href&&(g.hashes.editHash=t.getEditHashFromKeys(S)),g.proxy={metadata:{color:y.color,title:y.title}},A();var C=function(){g.stores.forEach((function(e){var t=d(n,e);t&&t.rpc&&t.proxy.calendars&&(delete t.proxy.calendars[m],(t.unpin||n.unpinPads)([m],(function(e){e&&e.error&&console.error(e.error)})))})),g.lm&&g.lm.stop(),g.stores=[],h(n,g),p(n,m),delete n.calendars[m]};i((function(e){n.store.network&&!r.isNew&&n.Store.isNewChannel(null,m,e((function(t){if(!t||!t.error)return t&&"boolean"==typeof t.isNew&&t.isNew?(C(),c({error:"EDELETED"}),void e.abort()):void 0})))})).nThen((function(){var e;if(1!==f&&f){var t=n.store.modules.team&&n.store.modules.team.getTeamsData(),a=t&&t[f];e=a?a.edPublic:void 0}else e=n.store.proxy.edPublic;var i={data:{},network:n.store.network||n.store.networkPromise,channel:S.channel,crypto:T,owners:[e],ChainPad:l,validateKey:S.keys.validateKey||void 0,userName:"calendar",Cache:o,classic:!0,onRejected:n.Store&&n.Store.onRejected},u=s.create(i);g.lm=u;var d=g.proxy=u.proxy,h=!1,p=function(){h||(h=!0,setTimeout((function(){h=!1,A()})))};u.proxy.on("cacheready",(function(){d.metadata&&(g.cacheready=!0,p(),c&&c(null,u.proxy),b(n,m,r.lastVisitNotif))})).on("ready",(function(e){var t=e.metadata;if(g.owners=t.owners||[],g.ready=!0,!d.metadata){if(!r.isNew)return void C();d.metadata={color:y.color,title:y.title}}p(),c&&c(null,u.proxy),b(n,m,r.lastVisitNotif)})).on("change",[],(function(){g.ready&&p()})).on("change",["content"],(function(e,t,r){2!==r.length||!t||e?2!==r.length||t||!e?(r.length>=3&&["start","reminders","isAllDay"].includes(r[2])||r.length>=6&&["start","reminders","isAllDay"].includes(r[5]))&&setTimeout((function(){E(n,m,d.content[r[1]])})):E(n,m,{id:r[1],start:0}):E(n,m,t)})).on("remove",["content"],(function(e,t){p(),(t.length>=3&&"reminders"===t[2]||t.length>=6&&"reminders"===t[5])&&setTimeout((function(){E(n,m,d.content[t[1]])}))})).on("change",["metadata"],(function(){var e=d.metadata;e&&e.title&&e.color&&v(n,g,e)})).on("disconnect",(function(){g.offline=!0,p()})).on("reconnect",(function(){g.offline=!1,p()})).on("error",(function(e){e&&e.error&&("EDELETED"!==e.error?("ERESTRICTED"===e.error&&(g.restricted=!0,p()),c(e)):C())}))}))}},_=function(e,t){if(t.href&&-1===t.href.indexOf("#"))if(e.secondaryKey)try{t.href=e.userObject.cryptor.decrypt(t.href)}catch(e){console.error(e),delete t.href}else delete t.href},w=function(t,n){var r=n.proxy.calendars,o=n.id||1;n.proxy.on("change",["calendars"],(function(r,a,i){i.length<2||(r&&!a&&function(){var e=i[1],n=t.calendars[e];if(n){var r=n.stores.indexOf(o);if(-1!==r){n.stores.splice(r,1);var a=n.roStores.indexOf(o);-1!==a&&n.roStores.splice(a,1),y(t,e),h(t,n)}}}(),!r&&a&&function(){var r=i[1],a=n.proxy.calendars[r];if(a){var s=e.clone(a);_(n,s),A(t,{storeId:o,data:s})}}())})),Object.keys(r||{}).forEach((function(a){var i=e.clone(r[a]);_(n,i),A(t,{storeId:o,lastVisitNotif:!0,data:i})}))},O=function(e,n,o,a){var i=d(e,n.teamId);if(i)if(i.rpc){var s,c,u,l=i.proxy.calendars=i.proxy.calendars||{},f=(s=t.createRandomHash("calendar"),c=t.getSecrets("calendar",s),u=t.getViewHashFromKeys(c),{href:t.hashToHref(s,"calendar"),roHref:t.hashToHref(u,"calendar"),channel:c.channel});f.color=n.color,f.title=n.title,A(e,{storeId:i.id||1,data:f,isNew:!0},(function(t){if(t)return console.error(t),void a({error:t.error});var n=e.calendars[f.channel];r.whenRealtimeSyncs(n.lm.realtime,(function(){l[f.channel]=f,(i.pin||e.pinPads)([f.channel],(function(e){e&&e.error&&console.error(e.error)})),e.Store.onSync(i.id,a)}))}))}else a({error:"EFORBIDDEN"});else a({error:"NO_STORE"})};return f.init=function(n,o,a){var s={},c=n.store,u={loggedIn:c.loggedIn&&c.proxy.edPublic,store:c,Store:n.Store,pinPads:n.pinPads,unpinPads:n.unpinPads,updateMetadata:n.updateMetadata,emit:a,onReady:e.mkEvent(!0),calendars:{},clients:[]};return function(e,t){var n=e.store.proxy;n.calendars=n.calendars||{},setTimeout(t)}(u,o((function(e){e||function(e){w(e,e.store);var t=e.store.modules.team&&e.store.modules.team.getTeamsData();t&&Object.keys(t).forEach((function(t){var n=d(e,t);w(e,n)}))}(u)}))),u.store.proxy.on("change",["hideReminders"],(function(e,t,n){var r=n[1].split("|")[0];Object.keys(u.calendars).some((function(e){var t=u.calendars[e];if(t&&t.proxy&&t.proxy.content)return t.proxy.content[r]?(setTimeout((function(){E(u,e,t.proxy.content[r])})),!0):void 0}))})),s.closeTeam=function(e){Object.keys(u.calendars).forEach((function(t){var n=u.calendars[t],r=n.stores.indexOf(e);if(-1!==r){n.stores.splice(r,1);var o=n.roStores.indexOf(e);-1!==o&&n.roStores.splice(o,1),y(u,t),h(u,n)}}))},s.openTeam=function(e){var t=d(u,e);t&&w(u,t)},s.upgradeTeam=function(t){if(t){var n=d(u,t);n&&Object.keys(u.calendars).forEach((function(r){var o=u.calendars[r];if(-1!==o.stores.indexOf(t)){var a=n.proxy.calendars[r],i=e.clone(a);_(n,i),A(u,{storeId:t,data:i}),h(u,o)}}))}},s.removeClient=function(e){!function(e,t){var n=e.clients.indexOf(t);-1!==n&&e.clients.splice(n,1),Object.keys(e.calendars).forEach((function(n){var r=e.calendars[n];if(1===r.stores.length&&0===r.stores[0]&&r.tempId.length){var o=r.tempId.indexOf(t);-1!==o&&r.tempId.splice(o,1),r.tempId.length||(r.stores=[],y(e,n))}}))}(u,e)},s.execCommand=function(n,o,a){var s=o.cmd,c=o.data;if("SUBSCRIBE"!==s){if("OPEN"!==s)return"IMPORT"===s?u.store.offline?void a({error:"OFFLINE"}):u.loggedIn?void function(n,r,o,a){var i=r.id,s=n.calendars[i];if(s)if(Array.isArray(s.stores)&&-1!==s.stores.indexOf(r.teamId)){var c=n.store,u=c.proxy.calendars=c.proxy.calendars||{},l=s.hashes.editHash,f=s.hashes.viewHash;u[i]={href:l&&t.hashToHref(l,"calendar"),roHref:f&&t.hashToHref(f,"calendar"),channel:i,color:e.find(s,["proxy","metadata","color"])||e.getRandomColor(),title:e.find(s,["proxy","metadata","title"])||"..."},n.Store.onSync(null,a),A(n,{storeId:1,data:{href:u[i].href,toHref:u[i].roHref,channel:i}})}else a({error:"EINVAL"});else a({error:"ENOENT"})}(u,c,0,a):void a({error:"NOT_LOGGED_IN"}):"IMPORT_ICS"===s?u.store.offline?void a({error:"OFFLINE"}):void function(e,t,n,o){var a=t.id,i=e.calendars[a];if(i&&i.proxy){var s=t.json;i.proxy.content=i.proxy.content||{},Object.keys(s).forEach((function(t){i.proxy.content[t]=s[t],E(e,a,s[t])})),r.whenRealtimeSyncs(i.lm.realtime,(function(){h(e,i),o()}))}else o({error:"ENOENT"})}(u,c,0,a):"ADD"===s?u.store.offline?void a({error:"OFFLINE"}):u.loggedIn?void function(n,r,o,a){var i=d(n,r.teamId);if(i)if(i.rpc){var s=i.proxy.calendars=i.proxy.calendars||{},c=t.parsePadUrl(r.href),u=t.getSecrets(c.type,c.hash,r.password);if(u.channel===r.channel){var l=t.getEditHashFromKeys(u),f=t.getViewHashFromKeys(u),h=l&&t.hashToHref(l,"calendar"),p={href:h,roHref:f&&t.hashToHref(f,"calendar"),color:r.color,title:r.title,channel:r.channel};!s[r.channel]||!s[r.channel].href&&p.href?(p.color=r.color,p.title=r.title,A(n,{storeId:i.id||1,data:e.clone(p)},(function(e){if(e)return console.error(e),void a({error:e.error});if(h&&i.id&&i.secondaryKey)try{p.href=i.userObject.cryptor.encrypt(h)}catch(e){console.error(e)}s[p.channel]=p,(i.pin||n.pinPads)([p.channel],(function(e){e&&e.error&&console.error(e.error)})),n.Store.onSync(i.id,a)}))):a()}else a({error:"EINVAL"})}else a({error:"EFORBIDDEN"});else a({error:"NO_STORE"})}(u,c,0,a):void a({error:"NOT_LOGGED_IN"}):"CREATE"===s?u.loggedIn?c.initialCalendar?void u.Store.onReadyEvt.reg((function(){O(u,c,0,a)})):u.store.offline?void a({error:"OFFLINE"}):void O(u,c,0,a):void a({error:"NOT_LOGGED_IN"}):"UPDATE"===s?u.store.offline?void a({error:"OFFLINE"}):void function(t,n,o,a){var i=n.id,s=t.calendars[i];if(s){var c=e.find(s,["proxy","metadata"]);c?(c.title=n.title,c.color=n.color,r.whenRealtimeSyncs(s.lm.realtime,a),h(t,s),v(t,s,n)):a({error:"EINVAL"})}else a({error:"ENOENT"})}(u,c,0,a):"DELETE"===s?u.store.offline?void a({error:"OFFLINE"}):u.loggedIn?void function(e,t,n,r){var o=d(e,t.teamId);if(o)if(o.rpc){if(o.proxy.calendars){var a=t.id;if(o.proxy.calendars[a]){delete o.proxy.calendars[a],(o.unpin||e.unpinPads)([a],(function(e){e&&e.error&&console.error(e.error)}));var i=e.calendars[a],s=i.stores.indexOf(o.id||1);i.stores.splice(s,1),y(e,a),e.Store.onSync(o.id,(function(){h(e,i),r()}))}else r()}}else r({error:"EFORBIDDEN"});else r({error:"NO_STORE"})}(u,c,0,a):void a({error:"NOT_LOGGED_IN"}):"CREATE_EVENT"===s?u.store.offline?void a({error:"OFFLINE"}):void function(e,t,n,o){var a=t.calendarId,i=e.calendars[a];if(i){var s=new Date(t.start),c=new Date(t.end);t.isAllDay?(t.startDay=s.getFullYear()+"-"+(s.getMonth()+1)+"-"+s.getDate(),t.endDay=c.getFullYear()+"-"+(c.getMonth()+1)+"-"+c.getDate()):(delete t.startDay,delete t.endDay),i.proxy.content=i.proxy.content||{},i.proxy.content[t.id]=t,r.whenRealtimeSyncs(i.lm.realtime,(function(){E(e,a,t),h(e,i),o()}))}else o({error:"ENOENT"})}(u,c,0,a):"UPDATE_EVENT"===s?u.store.offline?void a({error:"OFFLINE"}):void function(t,n,o,a){if(n&&n.ev){var s=n.ev.calendarId,c=t.calendars[s];if(c&&c.proxy&&c.proxy.content){var u=c.proxy.content[n.ev.id];if(u){n.rawData=n.rawData||{};var l,f=n.changes||{},d=n.type||{};if(f.calendarId){if(!(l=t.calendars[f.calendarId])||!l.proxy)return void a({error:"ENOENT"});l.proxy.content=l.proxy.content||{}}var p={one:{},from:{}};["one","from","all"].includes(d.which)&&(u.recUpdate=u.recUpdate||p,u.recUpdate.one||(u.recUpdate.one={}),u.recUpdate.from||(u.recUpdate.from={}));var y=u.recUpdate,v=["calendarId"],m=Object.keys(f).filter((function(e){return!v.includes(e)})),g=function(e){[y.from,y.one].forEach((function(t){Object.keys(t).forEach((function(n){Number(n){const r=[],o=null==Ir?void 0:Ir.httpUnsafeOrigin;je.fetchApi(o,"config",!0,(e=>{var o,a;(null===(o=null==e?void 0:e.adminKeys)||void 0===o?void 0:o.includes(t))&&r.push("admin");(null===(a=null==e?void 0:e.moderatorKeys)||void 0===a?void 0:a.includes(t))&&r.push("moderator"),n(r)}))},Pr=(e,t,n)=>{e.Store.anonRpcMsg("",{msg:"IS_PREMIUM",data:t},(e=>{let t=Array.isArray(e)&&e[0];n(t?["premium"]:[])}))},kr=(e,t,n,r)=>{var o,a;const i=[];null==Ir||Ir.httpUnsafeOrigin;const s=t.edPublic||(null===(a=null===(o=e.store)||void 0===o?void 0:o.proxy)||void 0===a?void 0:a.edPublic);Mn((e=>{Nr(0,s,e((e=>{Array.prototype.push.apply(i,e)})))})).nThen((t=>{Pr(e,s,t((e=>{Array.prototype.push.apply(i,e)})))})).nThen((()=>{r(i)}))},Rr={admin:Nr,moderator:Nr,premium:Pr},Mr={init:(e,t,n)=>{const r={store:e.store,Store:e.Store,updateMetadata:e.updateMetadata},o=r.Store;return o.onReadyEvt.reg((()=>{var e;const t=o.getMetadata(void 0,"drive",(()=>{})),n=(null===(e=null==t?void 0:t.user)||void 0===e?void 0:e.badge)||"";n&&kr(r,{},0,(e=>{var t,o;if(!e.includes(n)){const e=null===(o=null===(t=null==r?void 0:r.store)||void 0===t?void 0:t.modules)||void 0===o?void 0:o.profile;null==e||e.execCommand(void 0,{cmd:"SET",data:{key:"badge",value:""}},(()=>{}))}}))})),{listBadges:(e,t)=>{kr(r,e,0,t)},removeClient:()=>{},execCommand:(e,t,n)=>{const o=t.cmd,a=t.data;"LIST_BADGES"!==o?"CHECK_BADGE"!==o?n():((e,t,n,r)=>{const{badge:o,ed:a,sig:i,nid:s}=t,c=je.decodeBase64(a),u=je.decodeBase64(i),l=xr.sign.open(u,c);if(!l)return void r({verified:!1});if(je.encodeUTF8(l)!==s)return void r({verified:!1});let f=Rr[o];f?f(e,a,(e=>{r({verified:e.includes(o),badge:o})})):r({verified:!1,error:"EINVAL"})})(r,a,0,n):kr(r,a,0,n)}}},setCustomize:e=>{Ir=null==e?void 0:e.ApiConfig}};var Fr,Lr,Hr=o(Object.freeze({__proto__:null,Badge:Mr}));function Kr(){if(Lr)return Fr;Lr=1;return Fr=((e,t,n,r,o,a,i,s,c,u,l,f,d,h,p,y,v,m,g,E,b,A,_,w,O,D,S,T,C,x,I,N,P,k,R,M)=>{const F=p.Account,L=y.Drive,H=v.Pad,K=T.Badge,j=globalThis;globalThis.nacl=globalThis.nacl||I.Nacl;let U={},B={};const V=a.Saferphore;var G=a.mkEvent(!0),Y=a.mkEvent(!0),J=a.mkEvent(!0),q=a.mkEvent(!0);var W={drive:{hideDuplicate:!0},pad:{width:!0,spellcheck:!0},security:{unsafeLinks:!1},general:{allowUserFeedback:!0}};return{setCustomize:e=>{U=e.ApiConfig,B=e.AppConfig},create:function(p){var y=j.Cryptpad_Store={};let v=p.query||function(){},T=p.broadcast||function(){};var N=j.CryptPad_AsyncStore={modules:{}};y.onReadyEvt=G,y.pad=H.init({Store:y,store:N,postMessage:v,broadcast:T}),y.drive=L.initAPI({Store:y,store:N,postMessage:v,broadcast:T});var P=[],k=N.sendDriveEvent=function(e,t,n){P.forEach((function(r){r!==n&&v(r,e,t)}))},Q=y.getStore=function(e){if(!e)return N;try{var t=N.modules.team.getTeam(e);return t||void console.error("Team not found",e)}catch(t){return console.error(t),void console.error("Team not found",e)}},z=y.onSync=function(e,t){var n=Q(e);n?M((function(e){if(n.realtime&&c.whenRealtimeSyncs(n.realtime,e()),!n.id&&n.drive?.realtime&&c.whenRealtimeSyncs(n.drive.realtime,e()),n.sharedFolders&&"object"==typeof n.sharedFolders)for(var t in n.sharedFolders)n.sharedFolders[t].realtime&&c.whenRealtimeSyncs(n.sharedFolders[t].realtime,e())})).nThen((function(){t()})):t({error:"ENOTFOUND"})};y.get=function(e,t,n){var r=Q(t.teamId);r?r.proxy?n(a.find(r.proxy,t.key)):n({error:"ENODRIVE"}):n({error:"ENOTFOUND"})},y.set=function(e,t,n){var r=Q(t.teamId);if(r)if(r.proxy){var o=t.key.slice(),i=o.pop(),s=a.find(r.proxy,o);s&&"object"==typeof s?(void 0===t.value?delete s[i]:s[i]=t.value,t.teamId||(T([e],"UPDATE_METADATA"),Array.isArray(o)&&"profile"===o[0]&&N.messenger&&u.updateMyData(N)),z(t.teamId,n)):n({error:"INVALID_PATH"})}else n({error:"ENODRIVE"});else n({error:"ENOTFOUND"})},y.getSharedFolder=function(e,n,r){var o,i=Q(n.teamId),s=n.id;if(i&&i.manager){if(i.manager.folders[s])return(o=a.clone(i.manager.folders[s].proxy)).offline=Boolean(i.manager.folders[s].offline),void r(o);var c=a.find(i.proxy,["drive",t.SHARED_FOLDERS])||{};c[s]?y.loadSharedFolder(n.teamId,s,c[s],(function(){r(i.manager.folders[s].proxy)})):r({})}else r({error:"ENOTFOUND"})},y.restoreSharedFolder=function(e,t,n){if(t.sfId&&t.drive){var r=Q(t.teamId);r.sharedFolders[t.sfId]&&(Object.keys(t.drive).forEach((function(e){r.sharedFolders[t.sfId].proxy[e]=t.drive[e]})),Object.keys(r.sharedFolders[t.sfId].proxy).forEach((function(e){t.drive[e]||delete r.sharedFolders[t.sfId].proxy[e]}))),z(t.teamId,n)}else n({error:"EINVAL"})},y.hasSigningKeys=function(){if(N.proxy)return"string"==typeof N.proxy.edPrivate&&"string"==typeof N.proxy.edPublic},y.hasCurveKeys=function(){if(N.proxy)return"string"==typeof N.proxy.curvePrivate&&"string"==typeof N.proxy.curvePublic},y.isOwned=function(e){var t=N.proxy.edPublic;if(!t)return!1;if(!Array.isArray(e)||!e.length)return!1;if(-1!==e.indexOf(t))return!0;var n=N.proxy.teams;return!!n&&Object.keys(n).some((function(t){var r=a.find(n[t],["keys","drive","edPublic"]);return r&&-1!==e.indexOf(r)}))};var X=function(e){var t=e?N.manager.getChannelsList("expirable"):function(){var e=`${N.driveChannel}#drive`;if(!e)return null;var t=N.manager.getChannelsList("pin"),n=N.proxy.profile;if(n){var r=n.edit?o.hrefToHexChannelId("/profile/#"+n.edit,null):null;r&&t.push(r);var a=n.avatar?o.hrefToHexChannelId(n.avatar,null):null;a&&t.push(a)}if(N.proxy.todo&&t.push(o.hrefToHexChannelId("/todo/#"+N.proxy.todo,null)),N.proxy.friends){var i=u.getFriendChannelsList(N.proxy);t=t.concat(i)}if(N.proxy.mailboxes){var s=Object.keys(N.proxy.mailboxes).map((function(e){if("broadcast"!==e||N.isAdmin)return N.proxy.mailboxes[e].channel})).filter(Boolean);t=t.concat(s)}if(N.proxy.calendars){var c=Object.keys(N.proxy.calendars).map((function(e){return N.proxy.calendars[e].channel}));t=t.concat(c)}return t.push(e),N.data&&N.data.blockId&&t.push(`${N.data.blockId}#block`),t.sort(),t}();return a.deduplicateString(t).sort()};y.pinPads=function(e,t,n){if(t){var r=Q(t&&t.teamId);if(r.rpc){"function"!=typeof n&&(console.error("expected a callback"),n=function(){});var o=t.pads||t;r.rpc.pin(o,(function(e){n(e?{error:e}:{})}))}else n({error:"RPC_NOT_READY"})}else n({error:"EINVAL"})},y.unpinPads=function(e,t,n){if(t){var r=Q(t&&t.teamId);if(r.rpc){var o=t.pads||t;r.rpc.unpin(o,(function(e){n(e?{error:e}:{})}))}else n({error:"RPC_NOT_READY"})}else n({error:"EINVAL"})};var Z=N.account={};y.getPinnedUsage=function(e,t,n){var r=Q(t&&t.teamId);r&&r.rpc?r.rpc.getFileListSize((function(e,t){r.id||"number"!=typeof t||(Z.usage=t),n({bytes:t})})):n({error:"RPC_NOT_READY"})},y.getPinLimit=function(e,t,n){var r=Q(t&&t.teamId);r.rpc?r.rpc.getLimit((function(e,t,o,a){if(e)n({error:e});else{var i=r.id?{}:Z;i.limit=t,i.plan=o,i.note=a,n(i)}})):n({error:"RPC_NOT_READY"})};y.uploadComplete=function(e,t,n){var r=Q(t.teamId);r?r.rpc?t.owned?r.rpc.ownedUploadComplete(t.id,(function(e,t){n(e?{error:e}:t)})):r.rpc.uploadComplete(t.id,(function(e,t){n(e?{error:e}:t)})):n({error:"RPC_NOT_READY"}):n({error:"ENOTFOUND"})},y.uploadStatus=function(e,t,n){var r=Q(t.teamId);r?r.rpc?r.rpc.uploadStatus(t.size,(function(e,t){n(e?{error:e}:t)})):n({error:"RPC_NOT_READY"}):n({error:"ENOTFOUND"})},y.uploadCancel=function(e,t,n){var r=Q(t.teamId);r?r.rpc?r.rpc.uploadCancel(t.size,(function(e,t){n(e?{error:e}:t)})):n({error:"RPC_NOT_READY"}):n({error:"ENOTFOUND"})},y.uploadChunk=function(e,t,n){var r=Q(t.teamId);r?r.rpc?r.rpc.send.unauthenticated("UPLOAD",t.chunk,(function(e,t){n({error:e,msg:t})})):n({error:"RPC_NOT_READY"}):n({error:"ENOTFOUND"})};y.anonRpcMsg=function(e,t,n){N.anon_rpc?N.anon_rpc.send(t.msg,t.data,(function(e,t){n(e?{error:e}:t)})):n({error:"ANON_RPC_NOT_READY"})},y.getFileSize=function(e,t,n){var r=a.once(a.mkAsync(n));if(N.anon_rpc){var i=t.channel||o.hrefToHexChannelId(t.href,t.password);N.anon_rpc.send("GET_FILE_SIZE",i,(function(e,t){if(!e)return t&&t.length&&"number"==typeof t[0]?(0===t[0]&&d.clearChannel(i),void r({size:t[0]})):void r({error:"INVALID_RESPONSE"});r({error:e})}))}else r({error:"ANON_RPC_NOT_READY"})},y.isNewChannel=function(e,t,n){if(N.anon_rpc){var r=t.channel||o.hrefToHexChannelId(t.href,t.password);N.anon_rpc.send("IS_NEW_CHANNEL",r,(function(e,t){if(!e)return t&&t.length&&"object"==typeof t[0]?(t[0].isNew&&d.clearChannel(r),void n(t[0])):void n({error:"INVALID_RESPONSE"});n({error:e})}))}else n({error:"ANON_RPC_NOT_READY"})},y.getMultipleFileSize=function(e,t,n){N.anon_rpc?Array.isArray(t.files)?N.anon_rpc.send("GET_MULTIPLE_FILE_SIZE",t.files,(function(e,t){e?n({error:e}):t&&t.length&&"object"==typeof t[0]?n({size:t[0]}):n({error:"UNEXPECTED_RESPONSE"})})):n({error:"INVALID_FILE_LIST"}):n({error:"ANON_RPC_NOT_READY"})},y.getDeletedPads=function(e,t,n){if(N.anon_rpc){var r=t&&t.list||X(!0);Array.isArray(r)?N.anon_rpc.send("GET_DELETED_PADS",r,(function(e,t){e?n({error:e}):t&&t.length&&Array.isArray(t[0])?n(t[0]):n({error:"UNEXPECTED_RESPONSE"})})):n({error:"INVALID_FILE_LIST"})}else n({error:"ANON_RPC_NOT_READY"})};var $=function(e,t,n){N.anon_rpc?n():f.createAnonymous(N.network,(function(e,t){e?n({error:e}):(N.anon_rpc=t,n())}))},ee=y.getAllStores=function(){if(!N.proxy||!N.manager)return[];var e=[N],t=N.modules.team;if(t){var n=t.getTeams().map((function(e){return t.getTeam(e)}));Array.prototype.push.apply(e,n)}return e};y.getUserColor=function(){var e=a.find(N,["proxy","settings","general","cursor","color"]);return e||(e=a.getRandomColor(!0),y.setAttribute(null,{attr:["general","cursor","color"],value:e},(function(){}))),e},y.getMetadata=function(e,t,n){var r=N.proxy||{},s=a.find(r,["settings","general","disableThumbnails"]),c=N.modules.team&&N.modules.team.getTeamsData(t)||{};r.uid||(N.noDriveUid=N.noDriveUid||o.createChannelId());var u={user:{name:r[i.displayNameKey]||N.noDriveName||"",uid:r.uid||N.noDriveUid,avatar:a.find(r,["profile","avatar"]),profile:a.find(r,["profile","view"]),color:y.getUserColor(),notifications:a.find(r,["mailboxes","notifications","channel"]),curvePublic:r.curvePublic,kemPublic:r.kemPublic,edPublic:r.edPublic,dsaPublic:r.dsaPublic,netfluxId:N?.network?.webChannels?.[0]?.myID,badge:a.find(r,["profile","badge"])},priv:{clientId:e,edPublic:r.edPublic,edPrivate:r.edPrivate,dsaPublic:r.dsaPublic,dsaPrivate:r.dsaPrivate,friends:r.friends||{},settings:r.settings||W,thumbnails:!1===s,isDriveOwned:Boolean(a.find(N,["driveMetadata","owners"])),driveChannel:N.driveChannel,pendingFriends:r.friends_pending||{},supportPrivateKey:a.find(r,["mailboxes","supportadmin","keys","curvePrivate"]),accountName:r.login_name||"",offline:N.proxy&&N.offline,teams:c,plan:N.ready?Z.plan||"":void 0,mutedChannels:r.mutedChannels}};return n(JSON.parse(JSON.stringify(u))),u},y.onMaintenanceUpdate=function(){let e=U.httpUnsafeOrigin;a.fetchApi(e,"broadcast",!0,(e=>{e&&T([],"UNIVERSAL_EVENT",{type:"broadcast",data:{ev:"MAINTENANCE",data:e.maintenance}})}))},y.onSurveyUpdate=function(){let e=U.httpUnsafeOrigin;a.fetchApi(e,"broadcast",!0,(e=>{T([],"UNIVERSAL_EVENT",{type:"broadcast",data:{ev:"SURVEY",data:e.surveyURL}})}))};y.addPad=function(e,n,r){if(n.href||n.roHref){var a;if(!n.roHref){var i=o.parsePadUrl(n.href);"pad"===i.hashData.type&&(a=o.getSecrets(i.type,i.hash,n.password),n.roHref="/"+i.type+"/#"+o.getViewHashFromKeys(a))}var s,c,u,l,f=(s=n.href,c=n.roHref,u=n.title,l=+new Date,{href:s,roHref:c,atime:l,ctime:l,title:u||t.getDefaultName(o.parsePadUrl(s))});n.owners&&(f.owners=n.owners),n.expire&&(f.expire=n.expire),n.password&&(f.password=n.password),(n.channel||a)&&(f.channel=n.channel||a.channel),n.readme&&(f.readme=1),Object.keys(n.attributes||{}).forEach((e=>{n.attributes[e]&&(f[e]=n.attributes[e])})),-1===n.teamId&&(n.teamId=void 0);var d=Q(n.teamId);d&&d.manager?d.manager.addPad(n.path,f,(function(o){o?r({error:o}):(ee().forEach((function(n){(n.id?n.sendEvent:k)("DRIVE_CHANGE",{path:["drive",t.FILES_DATA]},e)})),z(n.teamId,r))})):r({error:"ENOTFOUND"})}else r({error:"NO_HREF"})};var te=function(e,t){var n=a.find(N,["proxy","edPublic"]),r=function(e){var t=[];return e?(N.proxy.todo&&t.push(o.hrefToHexChannelId("/todo/#"+N.proxy.todo,null)),N.proxy.profile&&N.proxy.profile.edit&&t.push(o.hrefToHexChannelId("/profile/#"+N.proxy.profile.edit,null)),N.proxy.mailboxes&&Object.keys(N.proxy.mailboxes||{}).forEach((function(e){if("supportadmin"!==e){var n=N.proxy.mailboxes[e];t.push(n.channel)}}))):t=N.manager.getChannelsList("owned"),t.filter((function(e){if("string"==typeof e)return-1!==[32,48].indexOf(e.length)}))}(e),i=V.create(10),s=function(t){e||N.manager.findChannel(t).forEach((function(e){var t=N.manager.findFile(e.id);N.manager.delete({paths:t})}))};r.forEach((function(e){var r=t();i.take((function(t){var o=!1;M((function(a){32===e.length&&y.anonRpcMsg(null,{msg:"GET_METADATA",data:e},a((function(i){if(i&&i.error)return t(),r(),void a.abort();var c=i[0];return Object.keys(c||{}).length?c&&Array.isArray(c.owners)&&-1!==c.owners.indexOf(n)?void(o=c.owners.some((function(e){return e!==n}))):(t(),r(),void a.abort()):(s(e),t(),r(),void a.abort())})))})).nThen((function(t){o?y.pad.setMetadata(null,{channel:e,command:"RM_OWNERS",value:[n]},t()):N.rpc.removeOwnedChannel(e,t((function(t){t?console.error(t):s(e)})))})).nThen((function(){t(),r()}))}))}))};y.removeOwnedPads=function(e,t,n){N.proxy.edPublic?M((function(e){te(!1,e)})).nThen(n):n({error:"NOT_LOGGED_IN"})},y.deleteAccount=function(t,n,r){var o=N.proxy.edPublic,s=n&&n.keys,c=n&&n.auth;y.anonRpcMsg(t,{msg:"GET_METADATA",data:N.driveChannel},(function(n){var u=n[0];if(u&&u.owners&&1===u.owners.length&&-1!==u.owners.indexOf(o))M((function(e){C.checkRights({auth:c,blockKeys:s},e((function(t){if(t)return e.abort(),console.error(t),void r({error:"INVALID_CODE"})})))})).nThen((function(e){globalThis.accountDeletion=t,N.proxy[i.tokenKey]="DELETED",z(null,e())})).nThen((function(e){N.rpc.removePins(e((function(e){e&&console.error(e)})))})).nThen((function(e){N.ownDeletion=!0,y.pad.destroy(t,{channel:N.driveChannel,force:!0},e())})).nThen((function(e){s&&C.removeLoginBlock({reason:"ARCHIVE_OWNED",auth:c,edPublic:o,blockKeys:s},e((function(e){e&&console.error(e)})))})).nThen((function(e){te(!0,e)})).nThen((function(){T([t],"DRIVE_DELETED","ARCHIVE_OWNED"),v(t,"DELETE_ACCOUNT","DELETED",(function(){})),N.network.disconnect(),r({state:!0})}));else{var l={intent:"Please delete my account."};l.drive=N.driveChannel,l.edPublic=o;var f=a.decodeBase64(N.proxy.edPrivate),d=I.CryptoAgility.signDetached(a.decodeUTF8(e(l)),f);I.Nacl.sign.detached.verify(a.decodeUTF8(e(l)),d,a.decodeBase64(o))||console.error("signed message failed verification");var h=a.encodeBase64(d);r({proof:h,toSign:JSON.parse(e(l))})}}))},y.setDisplayName=function(e,t,n){if(!N.proxy)return N.noDriveName=t,T([e],"UPDATE_METADATA"),void n();N.modules.profile&&N.modules.profile.setName(t),N.proxy[i.displayNameKey]=t,T([e],"UPDATE_METADATA"),u.updateMyData(N),z(null,n)},y.resetDrive=function(e,t,n){M((function(e){te(e)})).nThen((function(){N.proxy.drive=N.userObject.getStructure(),k("DRIVE_CHANGE",{path:["drive","filesData"]},e),z(null,n)}))},y.setPadAttribute=function(e,n,r){M((function(r){ee().forEach((function(o){o.manager.setPadAttribute(n,r((function(){(o.id?o.sendEvent:k)("DRIVE_CHANGE",{path:["drive",t.FILES_DATA]},e),z(o.id,r())})))}))})).nThen(r)},y.getPadAttribute=function(e,t,n){var r={};M((function(e){ee().forEach((function(n){n.manager.getPadAttribute(t,e((function(e,t){e||(t&&"object"==typeof t?(!r.value||r.atime{if(N.loggedIn&&N.proxy.edPublic){var t,r=N.modules.team,o=r&&r.getTeams()||[];-1!==e.indexOf(N.proxy.edPublic)?t=N:o.some((function(n){var o=a.find(N,["proxy","teams",n,"keys","drive","edPublic"]),i=a.find(N,["proxy","teams",n,"keys","drive","edPrivate"]);if(-1===e.indexOf(o))return!1;if(!i)return!1;var s=r.getTeam(n);return t=s,!0}));var i=function(){if(t){var e=t.rpc;e?e.send("COOKIE","",(function(e){n(e)})):n("ERESTRICTED")}else n("ERESTRICTED")};t&&t.onRpcReadyEvt?t.onRpcReadyEvt.reg((function(){i()})):i()}else n("ERESTRICTED")}))):n("ERESTRICTED")},y.changePadPasswordPin=function(e,t,n){var r=t.oldChannel,o=t.channel;M((function(e){ee().forEach((function(t){t.manager.findChannel(o).length&&(t.rpc.unpin([r],e()),t.rpc.pin([o],e()))}))})).nThen(n)},y.contactPadOwner=function(e,t,n){var r=t.owners;if(!Array.isArray(r)||!r.length)return n({state:!1});t.send?M((function(e){r.forEach((function(n){!function(e,n,r,o){if(N.mailbox&&!t.anon)return N.mailbox.sendTo(e,n,r,o);A.sendToAnon(N.anon_rpc,e,n,r,o)}(t.query,{channel:t.channel,data:t.msgData},{channel:n.notifications,curvePublic:n.curvePublic},e())}))})).nThen((function(){n({state:!0})})):n({state:!0})},y.givePadAccess=function(e,t,n){var r,o,a=N.proxy.edPublic,i=t.channel,s=N.manager.findChannel(i);t.user&&t.user.notifications&&t.user.curvePublic?s.some((function(e){if(e.data&&Array.isArray(e.data.owners)&&-1!==e.data.owners.indexOf(a)&&e.data.href)return r=e.data.href,o=e.data.title,!0}))?(N.mailbox.sendTo("GIVE_PAD_ACCESS",{channel:i,href:r,title:o},{channel:t.user.notifications,curvePublic:t.user.curvePublic}),n()):n({error:"ENOTFOUND"}):n({error:"EINVAL"})};y.burnPad=function(e,t){var n=t.channel,r=I.b64AddSlashes(t.ownerKey||"");if(n&&r)try{var a=o.decodeBase64(r),i=I.CryptoAgility.signKeyPairFromSecretKey(a);l.create(N.network,{edPublic:o.encodeBase64(i.publicKey),edPrivate:o.encodeBase64(i.secretKey)},(function(e,r){e?console.error(e):y.pad.getMetadata(null,{channel:n},(function(e){r.removeOwnedChannel(n,(function(n){n?console.error(n):function(e,t){var n=e.channel,r=e.href,a=o.parsePadUrl(r),i=o.getSecrets(a.type,a.hash,e.password);if((!t||!t.error)&&t.mailbox){var s,c=I.createEncryptor(i.keys),u=[];try{"string"==typeof t.mailbox?u.push(c.decrypt(t.mailbox,!0,!0)):Object.keys(t.mailbox).forEach((function(e){u.push(c.decrypt(t.mailbox[e],!0,!0))}))}catch(e){console.error(e)}try{s=N.proxy.curvePublic}catch(e){return void console.error(e)}u.forEach((function(e){var t=JSON.parse(e);t.curvePublic!==s&&N.mailbox.sendTo("OWNED_PAD_REMOVED",{channel:n},{channel:t.notifications,curvePublic:t.curvePublic},(function(){}))}))}}(t,e)}))}))}))}catch(e){console.error(e)}else console.error("Can't delete BAR pad")},y.deleteMailboxMessage=function(e,t,n){N.anon_rpc?N.anon_rpc.send("DELETE_MAILBOX_MESSAGE",t,(function(e){n({error:e})})):n({error:"RPC_NOT_READY"})},y.getFullHistory=function(e,t,n){var r=N.network,o=r.historyKeeper,a=[],i=!1,s=function(e){if(!i){var o=function(e){try{return JSON.parse(e)}catch(e){return null}}(e);if(o)return"FULL_HISTORY_END"===o[0]?(n(a),r.off("message",s),void(i=!0)):void("FULL_HISTORY"===o[0]&&(o[1]&&o[1].validateKey||o[1][3]===t.channel&&(e=o[1][4])&&(e=e.replace(/cp\|(([A-Za-z0-9+\/=]+)\|)?/,""),t.debug?a.push({serverHash:e.slice(0,64),msg:e,author:o[1][1],time:o[1][5]}):a.push(e))))}};r.on("message",s),r.sendto(o,JSON.stringify(["GET_FULL_HISTORY",t.channel,t.validateKey]))},y.getHistory=function(e,t,n,r){var o=a.once(a.mkAsync(n)),i=N.network,s=i.historyKeeper,c=Math.floor(1e6*Math.random()),u=[],l=!1,f=function(e,n){if(!l&&n===s){var a=function(e){try{return JSON.parse(e)}catch(e){return null}}(e);if(a&&!(a.txid&&a.txid!==c||a.validateKey&&a.channel))if(a.error&&a.channel)a.channel===t.channel&&(i.off("message",f),l=!0,o({error:a.error}));else{if(1===a.state&&a.channel){if(a.channel!==t.channel)return;return o(u),i.off("message",f),void(l=!0)}Array.isArray(a)&&a[0]&&a[0]!==c||a[3]===t.channel&&(a[4]&&r?u.push({msg:e,hash:a[4].slice(0,64)}):(e=a[4])&&(e=e.replace(/cp\|(([A-Za-z0-9+\/=]+)\|)?/,""),u.push(e)))}}};i.on("message",f);var d={txid:c,lastKnownHash:t.lastKnownHash},h=["GET_HISTORY",t.channel,d];i.sendto(s,JSON.stringify(h))},y.getHistoryRange=function(e,t,n){var r,o=N.network,i=o.historyKeeper,s=[],c=!0,u=!1,l=!1,f=a.uid();o.on("message",(function(e){if(!l){var o=function(e){try{return JSON.parse(e)}catch(e){return null}}(e);if(o[1]===f){if("HISTORY_RANGE_ERROR"===o[0]){let e=o[2];return"ENOENT"===e?.code?(l=!0,void n({messages:s,isFull:!0})):void n({error:o[2]})}if("HISTORY_RANGE_END"===o[0])return n({messages:s,isFull:u,lastKnownHash:r}),void(l=!0);"HISTORY_RANGE"===o[0]&&(o[2]&&o[1].validateKey||o[2][3]===t.channel&&(e=o[2][4])&&(c&&(/^cp\|/.test(e)||t.toHash||(u=!0),r=e.slice(0,64),c=!1),e=e.replace(/cp\|(([A-Za-z0-9+\/=]+)\|)?/,""),s.push({serverHash:e.slice(0,64),msg:e,author:o[2][1],time:o[2][5]})))}else console.log("bad txid")}})),o.sendto(i,JSON.stringify(["GET_HISTORY_RANGE",t.channel,{from:t.lastKnownHash,to:t.toHash,cpCount:t.cpCount||2,txid:f}]))};var oe=function(e,n){e&&(e.deprecated||e.restricted||(n||e.on("change",["drive",t.SHARED_FOLDERS],(function(n,r,a){if(a.length>3&&"password"===a[3]){var i=a[2],s=e.drive[t.SHARED_FOLDERS][i],c=N.manager.user.userObject.getHref?N.manager.user.userObject.getHref(s):s.href,u=o.parsePadUrl(c),l=o.getSecrets(u.type,u.hash,n);return h.updatePassword(y,{oldChannel:l.channel,password:r,href:c},N.network,(function(){console.log("Shared folder password changed")})),!1}})),e.on("change",[],(function(e,r,o){if(n){if(o[0]===t.FILES_DATA&&"object"==typeof r&&r.channel&&!r.owners){var a=[r.channel];r.rtChannel&&a.push(r.rtChannel),r.lastVersion&&a.push(r.lastVersion),y.pinPads(null,a,(function(e){console.error(e)}))}if(o[0]===t.FILES_DATA&&"object"==typeof e&&e.channel&&!r){var i=[e.channel];N.manager.findChannel(e.channel).some((function(e){return e.fId!==n}))||(e.rtChannel&&i.push(e.rtChannel),e.lastVersion&&i.push(e.lastVersion),y.unpinPads(null,i,(function(e){console.error(e)})))}}e&&!r&&Array.isArray(o)&&(o[0]===t.FILES_DATA||"drive"===o[0]&&o[1]===t.FILES_DATA)&&setTimeout((function(){y.checkDeletedPad(e&&e.channel)})),k("DRIVE_CHANGE",{id:n,old:e,new:r,path:o})})),e.on("remove",[],(function(e,t){k("DRIVE_REMOVE",{id:n,old:e,path:t})}))))};y.loadSharedFolder=function(e,t,n,r,a){var i=Q(e);if(i){var s=o.parsePadUrl(n.href||n.roHref);s||s.hashData?h.load({isNew:a,network:N.network||N.networkPromise,store:i,Store:y,isNewChannel:y.isNewChannel},t,n,r):r({error:"EINVAL"})}else r({error:"ENOTFOUND"})};var ae=function(e,t,n,r){y.loadSharedFolder(null,e,t,n,r)};y.loadSharedFolderAnon=function(e,t,n){y.loadSharedFolder(null,t.id,t.data,(function(e){n({error:e?void 0:"EDELETED"})}))},y.addSharedFolder=function(e,n,r){G.reg((function(){var o=Q(n.teamId);o.manager.addSharedFolder(n,(function(a){a&&"object"==typeof a&&a.error?r(a):((n.teamId?o.sendEvent:k)("DRIVE_CHANGE",{path:["drive",t.FILES_DATA]},e),r(a))}))}))},y.updateSharedFolderPassword=function(e,t,n){h.updatePassword(y,t,N.network,n)},y.userObjectCommand=function(e,n,r){if(n&&n.cmd){var o=Q(n.teamId);if(o.offline)return(o.id?o.sendEvent:k)("NETWORK_DISCONNECT"),void r({error:"OFFLINE"});o.manager.command(n,(function(o){ee().forEach((function(n){(n.id?n.sendEvent:k)("DRIVE_CHANGE",{path:["drive",t.FILES_DATA]},e)})),z(n.teamId,(function(){r(o)}))}))}},y._removeClient=function(e){var t=P.indexOf(e);-1!==t&&P.splice(t,1),N.onlyoffice?.removeClient?.(e),N.mailbox?.removeClient?.(e),Object.keys(N.modules).forEach((function(t){N.modules[t]?.removeClient?.(e)})),y.pad?.removeClient?.(e)};y.refreshDriveUI=function(){ee().forEach((function(e){(e.id?e.sendEvent:k)("DRIVE_CHANGE",{path:["drive",t.FILES_DATA]})}))};var ie=function(e,t){const r=a.mkAsync(t);var o=N.proxy,i=N.drive;if(N.manager)r();else{var s=N.manager=n.create(i.proxy,{onSync:function(e){z(null,e)},edPublic:o.edPublic,pin:function(e,t){N.loggedIn?y.pinPads(null,e,t):t()},unpin:function(e,t){N.loggedIn?y.unpinPads(null,e,t):t()},loadSharedFolder:ae,settings:o.settings,removeOwnedChannel:function(e,t){y.pad.destroy("",e,t)},store:N,Store:y},{outer:!0,edPublic:N.proxy.edPublic,loggedIn:N.loggedIn,log:function(e){k("DRIVE_LOG",e)},rt:i.realtime}),c=N.userObject=s.user.userObject;M((function(e){N.sharedFolders={},N.handleSharedFolder=function(e,t){t?(N.sharedFolders[e]=t,N.driveEvents&&oe(t.proxy,e)):delete N.sharedFolders[e]},c.migrate(e())})).nThen((function(t){var n=N.network||N.networkPromise;h.loadSharedFolders(y,n,N,i.proxy,c,t,(t=>{var n={type:"sf",progress:100*t.progress/t.max};v(e,"LOADING_DRIVE",n)}),!0)})).nThen((function(t){re(w,"team",t,e)})).nThen((function(e){re(S,"calendar",e)})).nThen((function(){r()}))}};const se=(e=function(){})=>{re(m,"cursor",e),re(E,"integration",e),re(O,"messenger",e),re(D,"history",e),re(K,"badge",e),N.onlyoffice||(N.onlyoffice=b.init(N,(function(e,t,n){n.forEach((function(n){v(n,"OO_EVENT",{ev:e,data:t})}))}))),N&&(N.messenger=N.modules.messenger)},ce=(e,t,n)=>{const r=a.mkAsync(n);ie(e,(function(){Y.fire(),r(t)}))};var ue=function(e,t,n){N.ready=!0;var c=N.proxy,u=N.manager,f=N.userObject;M((function(n){c.settings||(c.settings=W),c.forms||(c.forms={}),c.friends_pending||(c.friends_pending={}),c.form_seed||(c.form_seed=o.createChannelId()),u||(ce(e,t,n()),u=N.manager,f=N.userObject),$(0,0,n()),function(e,t,n){if(!N.loggedIn)return n();N.rpc?n(Z):l.create(N.network,N.proxy,(function(e,t){e?n({error:e}):(N.rpc=t,N.onRpcReadyEvt.fire(),y.getPinLimit(null,null,(function(e){e.error&&console.error(e.error),Z.limit=e.limit,Z.plan=e.plan,Z.note=e.note,n(e)})))}),d)}(0,0,n()),v(e,"LOADING_DRIVE",{type:"migrate",progress:0})})).nThen((function(t){void 0===c.version&&(c.version=11),r(c,t(),(function(t,n){v(e,"LOADING_DRIVE",{type:"migrate",progress:n})}),N)})).nThen((function(t){v(e,"LOADING_DRIVE",{type:"sf",progress:0}),f.fixFiles(),h.loadSharedFolders(y,N.network,N,N.drive.proxy,f,t,(t=>{var n={type:"sf",progress:100*t.progress/t.max};v(e,"LOADING_DRIVE",n)})),se(t),re(_,"profile",t),re(S,"calendar",t),re(g,"support",t),M((e=>{N.modules.team&&N.modules.team.onReady(e)}))})).nThen((function(){var e,r=function(){T([],"REQUEST_LOGIN")};N.loggedIn&&(function(e){if(N.rpc){var t=X(!1),n=o.hashChannelList(t);N.rpc.getServerHash((function(t,r){t?e(t):e(null,r===n)}))}else e({error:"RPC_NOT_READY"})}((function(e,t){t||function(e){if(N.rpc){var t=X(!1);N.rpc.reset(t,(function(t){e(t||null)}))}else e({error:"RPC_NOT_READY"})}((function(e){if(e)return console.error(e);console.log("RESET DONE")}))})),"number"!=typeof c.loginToken&&(c[i.tokenKey]=N.data.localToken||Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)),t[i.tokenKey]=c[i.tokenKey],N.data.localToken&&N.data.localToken!==c[i.tokenKey])?r():(t.feedback=a.find(c,["settings","general","allowUserFeedback"]),s.init(t.feedback),N.returned=t,"function"==typeof n&&n(t),N.offline=!1,k("NETWORK_RECONNECT"),T([],"UPDATE_METADATA"),T([],"STORE_READY",t),"string"==typeof c.uid&&32===c.uid.length||(console.log("generating a persistent identifier"),c.uid=o.createChannelId()),!N.loggedIn||y.hasSigningKeys()&&y.hasCurveKeys()?(c.on("change",[i.displayNameKey],(function(e,t){"string"==typeof t&&T([],"UPDATE_METADATA")})),c.on("change",["profile"],(function(){T([],"UPDATE_METADATA")})),c.on("change",["friends"],(function(e,t,n){if(T([],"UPDATE_METADATA"),N.messenger&&void 0===e){var r=n.slice(-1)[0],o=c.friends&&c.friends[r];N.messenger.onFriendAdded(o)}})),c.on("remove",["friends"],(function(e,t){if(T([],"UPDATE_METADATA"),N.messenger){var n=t[1];n&&"channel"===t[2]&&N.messenger.onFriendRemoved(n,e)}})),c.on("change",["friends_pending"],(function(){T([],"UPDATE_METADATA")})),c.on("remove",["friends_pending"],(function(){T([],"UPDATE_METADATA")})),c.on("change",["settings"],(function(){T([],"UPDATE_METADATA")})),c.on("change",[i.tokenKey],(function(){N.isDeleted||"DELETED"===c[i.tokenKey]||T([],"UPDATE_TOKEN",{token:c[i.tokenKey]})})),N.mailbox=A.init({Store:y,store:N,updateMetadata:function(){T([],"UPDATE_METADATA")},updateDrive:function(){k("DRIVE_CHANGE",{path:["drive","filesData"]})},pinPads:function(e,t){y.pinPads(null,e,t)}},e,(function(e,t,n,r){var o=a.once(r||function(){});n.forEach((function(n){v(n,"MAILBOX_EVENT",{ev:e,data:t},o)}))})),G.fire()):r())}))};const le=(e,t,n,r)=>{if(N.accountModule)return N.accountModule;const o=F.init({userHash:t.userHash,anonHash:t.anonHash,cache:t.cache,form_seed:t.form_seed,store:N,broadcast:T,postMessage:v});N.accountModule=o;const{channel:i,onAccountReady:s,onAccountCacheReady:c,onDisconnect:u,onReconnect:l}=o;N.driveChannel=i,c((e=>{N.cacheReturned||=e,n(e)})),s((e=>{N.returned||=e,r(e)})),u((()=>{k("NETWORK_DISCONNECT")})),l((()=>{k("NETWORK_RECONNECT")}));return setInterval((function(){var e=[];const t=y.pad.getChannels();Object.keys(t).forEach((function(n){var r=t[n].clients;Array.prototype.push.apply(e,r)})),(e=a.deduplicateString(e)).forEach((function(e){var t=0,n=function(){if(t>=2)return y._removeClient(e),v(e,"TIMEOUT"),void console.error("TIMEOUT",e);t++;var r=setTimeout(n,3e4);v(e,"PING",null,(function(e){e&&console.error(e),clearTimeout(r)}))};n()}))}),12e4),o},fe=(e,t,n,r)=>{const o=a.once((e=>{const t=L.init({account:e,store:N,broadcast:T,postMessage:v}),{onDriveReady:o,onDriveCacheReady:a,onDisconnect:i,onReconnect:s}=t;a((()=>{n(N.cacheReturned||N.returned)})),o((()=>{J.fire(),r(N.returned)})),i((()=>{})),s((()=>{}))})),i=()=>{},s=le(0,t,i,i);s.onAccountCacheReady((()=>{o(s)})),s.onAccountReady((()=>{o(s)}))};y.disableCache=function(e,t,n){t?d.disable():d.enable(),n()};var de=!1;const he=e=>{if(N?.network?.historyKeeper)return setTimeout(e);const t=t=>{N.network||=t;t.join("0000000000000000000000000000000000").then((function(n){let r;n.members.forEach((e=>{16===e.length&&(r=e)})),t.historyKeeper=r,n.leave(),e()}),(function(t){console.error(t),e({error:"GET_HK"})}))};if(N.network)return t(N.network);N.networkPromise?.then(t)};var pe=function(e,t,n){const r=a.once(t);var o=function(){se();let e=()=>{$(0,0,(function(){s.send("NO_DRIVE",!0),r({})}))};he((t=>{if(!t)return n?((e,t)=>{if(N.rpc)t(N.rpc);else{var n=I.CryptoAgility.signKeyPair(),r={edPublic:a.encodeBase64(n.publicKey),edPrivate:a.encodeBase64(n.secretKey)};l.create(N.network,r,(function(e,n){e?t({error:e}):(N.rpc=n,t(n))}))}})(0,e):void e()})),N.network||n||r({})};if(!N.network){var i=x.getWebsocketURL();return N.networkPromise=R.connect(i),o(),N.networkPromise.then((e=>{N.network!==e&&(N.network?(e.disconnect(),e=N.network):N.network=e)}),(function(e){console.error(e),r({error:"OFFLINE"})}))}o()};const ye=(e,t,n)=>{N.manager?Y.reg((function(){he((r=>{N.network||=r,ue(e,t,(()=>{n(t)}))}))})):ue(e,t,(()=>{n(t)}))};return y.init=function(e,t,n){var r=a.once((function(r){t.driveEvents&&function(e){Y.reg((()=>{-1===P.indexOf(e)&&P.push(e),N.driveEvents||(N.driveEvents=!0,oe(N.proxy),Object.keys(N.manager.folders).forEach((function(e){var t=N.manager.folders[e].proxy;oe(t,e)})))}))}(e),n(r)}));if(de&&!N.returned&&t.cache)Y.reg((function(){r({state:"ALREADY_INIT",returned:N.cacheReturned})}));else{if(de)return N.networkTimeout&&v(e,"LOADING_DRIVE",{type:"offline"}),void G.reg((function(){r({state:"ALREADY_INIT",returned:N.returned})}));t.disableCache&&d.disable(),t.noDrive&&!t.requires&&(t.requires="pad"),((e,t,n)=>{if(t.neverDrive||t.noDrive&&!t.userHash&&!t.anonHash)return t.neverDrive&&(N.neverCache=!0),void pe(0,(e=>{e?.error&&s.send("NO_DRIVE_ERROR",!0),t.neverDrive&&(e.tempKeys=N?.tempKeys),n(e)}),!!t.neverDrive);const r=t.requires,o=!t.noDrive;de=!0,N.data=t;let c=e=>{1===Object.keys(N.proxy).length&&s.send("FIRST_APP_USE",!0),e&&e.error&&(de=!1)};if("pad"===r&&!o)return void pe(0,(function(r){if(r&&r.error)return;n(r);let o=a.once((()=>{fe(0,t,(t=>{ce(e,t,c)}),(t=>{ye(e,t,c)}))}));y.pad.onCacheReady((()=>{N.network||o()})),y.pad.onJoined(o),q.reg(o)}));if("file"===r&&!o)return void pe(0,(function(r){r&&r.error||(n(r),fe(0,t,(t=>{ce(e,t,c)}),(t=>{ye(e,t,c)})))}));if("team"===r){let r=!1;const o=o=>a=>{r||(r=!0,M((e=>{o||$(0,0,e())})).nThen((t=>{re(w,"team",t,e)})).nThen((e=>{!o&&N.modules.team&&N.modules.team.onReady(e)})).nThen((()=>{n(a),fe(0,t,(t=>{ce(e,t,c)}),(t=>{ye(e,t,c)}))})))};return void le(0,t,o(!0),o(!1))}if("drive"===r)return void fe(0,t,(t=>{n(t),ce(e,t,c)}),(t=>{n(t),ye(e,t,c)}));let u=e=>{c(e);const t=i.prefersDriveRedirectKey,r=a.find(N,["proxy","settings","general",t]);e[t]=r,n(e)};fe(0,t,(t=>{ce(e,t,u)}),(t=>{ye(e,t,u)}))})(e,t,a.once((e=>{"GET_HK"!==e.error?r(e):r({error:"ERROR"})})))}},G.reg((function(){var e=+new Date-7776e6;d.getKeys((function(t,n){if(t)console.error(t);else{var r=function(){if(n.length){var t=n.pop();d.getTime(t,(function(n,o){n?r():!o||o{const t=(e,t={})=>({create:function(n,r,o){var a,i=[],s=e.mkEvent(!0);n.reg((function(e){if(!a){var t=e.data;if("_READY"===t)return r("_READY"),a=!0,s.fire(),void i.forEach((function(e){n.fire(e)}));i.push(t)}}));var c={},u={},l={},f=[],d={},h={};h.query=function(e,t,n,o){var a,i=Math.random().toString(16).replace("0.","")+Math.random().toString(16).replace("0.",""),c=(o=o||{}).timeout||3e4;c>0&&(a=setTimeout((function(){delete u[i],n("TIMEOUT")}),c)),l[i]=function(e){clearTimeout(a),delete l[i],e&&(delete u[i],n("UNHANDLED"))},u[i]=function(e,t){delete u[i],n(void 0,e.content,t)},s.reg((function(){var n={txid:i,content:t,q:e,raw:o.raw};r(o.raw?n:JSON.stringify(n))}))};var p=h.event=function(e,t,n){n=n||{},s.reg((function(){var o={content:t,q:e,raw:n.raw};r(n.raw?o:JSON.stringify(o))}))};h.on=function(e,t,n){var o=function(e,n,o){t(e.content,(function(t){var n={txid:e.txid,content:t};r(o?n:JSON.stringify(n))}),n)};return(c[e]=c[e]||[]).push(o),n||p("EV_REGISTER_HANDLER",e),{stop:function(){var t=c[e].indexOf(o);-1!==t&&c[e].splice(t,1)}}},h.whenReg=function(e,t,n){var r=n;f.indexOf(e)>-1?t():r=!0,r&&(d[e]=d[e]||[]).push(t)},h.onReg=function(e,t){h.whenReg(e,t,!0)},h.on("EV_REGISTER_HANDLER",(function(e){d[e]&&(d[e].forEach((function(e){e()})),delete d[e]),f.push(e)}));var y=!1;h.onReady=function(e){y?e():"function"==typeof e&&h.on("EV_RPC_READY",(function(){y=!0,e()}))},h.ready=function(){h.whenReg("EV_RPC_READY",(function(){h.event("EV_RPC_READY")}))};var v=[""];t.httpUnsafeOrigin?(v.push(t.httpUnsafeOrigin),v.push(t.httpSafeOrigin)):globalThis.location&&v.push(globalThis.location.origin),n.reg((function(e){if(a&&e.data&&"_READY"!==e.data&&v.includes(e.origin)){var t;try{t="object"==typeof e.data?e.data:JSON.parse(e.data)}catch(e){return void console.warn(e)}void 0!==t.ack?l[t.txid]&&l[t.txid](!t.ack):"string"==typeof t.q?c[t.q]?(t.txid&&r(JSON.stringify({txid:t.txid,ack:!0})),c[t.q].forEach((function(n){n(t||JSON.parse(e.data),e,t&&t.raw),t=void 0}))):t.txid&&r(JSON.stringify({txid:t.txid,ack:!1})):void 0===t.q&&u[t.txid]&&u[t.txid](t,e)}})),r("_READY"),o(h)}});e.exports&&(e.exports=t(Ne()))})()}(Qr)),Qr.exports}function Xr(){if(Jr)return Yr;Jr=1;var e;return Yr=((e,t,n)=>{const r={};let o,a,i={},s=()=>{};return r.init=t=>{if(a)return;a=e.create({query:(e,t,n,r)=>{r=r||function(){},i[e].chan.query(t,n,(function(e,t){r(e?{error:e}:t)}))},broadcast:(e,t,n,r)=>{r=r||function(){},Object.keys(i).forEach((o=>{-1===e.indexOf(+o)&&i[o].chan.query(t,n,((e,t)=>{r(e?{error:e}:t)}))}))}}),s=t},r.initClient=(e,r)=>{if(!a)return console.error("Not initialized"),void r("NOT_INIT");const{postMsg:c}=e,u=n.mkEvent(),l=Number(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)),f=()=>{a._removeClient(l)};t.create(u,c,(function(e){let t=i[l]={chan:e};console.debug("SharedW Channel created"),Object.keys(a.queries).forEach((function(n){"CONNECT"!==n&&"JOIN_PAD"!==n&&"SEND_PAD_MSG"!==n&&"STOPWORKER"!==n&&e.on(n,(function(e,r){try{a.queries[n](l,e,r)}catch(t){console.error("Error in webworker when executing query "+n),console.error(t),console.log(e)}"DISCONNECT"===n&&(f(),globalThis.accountDeletion&&globalThis.accountDeletion===t.id&&(a=void 0,o=void 0))}))})),e.on("STOPWORKER",(function(e,t){s(),a.queries.DISCONNECT(l,e,t)})),e.on("CONNECT",(function(e,t){console.debug("Connecting to store..."),a.queries.CONNECT(l,e,(function(e){if(e&&"ALREADY_INIT"===e.state)return console.debug("Store already exists!"),o=o||e.returned,void t(e);o=e,t(e)}))})),e.on("JOIN_PAD",(function(e,n){t.channelId=e.channel;try{a.queries.JOIN_PAD(l,e,n)}catch(t){console.error("Error in webworker when executing query JOIN_PAD"),console.error(t),console.log(e)}})),e.on("SEND_PAD_MSG",(function(e,n){var r={msg:e,channel:t.channelId};try{a.queries.SEND_PAD_MSG(l,r,n)}catch(e){console.error("Error in webworker when executing query SEND_PAD_MSG"),console.error(e),console.log(r)}})),r(u,f)}),!0)},r})((Ur||(Ur=1,e=Kr(),jr={create:function(t){var n=e.create(t),r={},o=r.queries={CONNECT:n.init,DISCONNECT:n.disconnect,PING:function(e,t,n){n()},CACHE_DISABLE:n.disableCache,GET_PIN_LIMIT:n.getPinLimit,PIN_PADS:n.pinPads,UNPIN_PADS:n.unpinPads,GET_PINNED_USAGE:n.getPinnedUsage,GET_DELETED_PADS:n.getDeletedPads,UPLOAD_CHUNK:n.uploadChunk,UPLOAD_COMPLETE:n.uploadComplete,UPLOAD_STATUS:n.uploadStatus,UPLOAD_CANCEL:n.uploadCancel,ANON_RPC_MESSAGE:n.anonRpcMsg,GET_FILE_SIZE:n.getFileSize,GET_MULTIPLE_FILE_SIZE:n.getMultipleFileSize,GET:n.get,SET:n.set,ADD_PAD:n.addPad,SET_PAD_TITLE:n.setPadTitle,MOVE_TO_TRASH:n.moveToTrash,RESET_DRIVE:n.resetDrive,GET_METADATA:n.getMetadata,IS_ONLY_IN_SHARED_FOLDER:n.isOnlyInSharedFolder,SET_DISPLAY_NAME:n.setDisplayName,SET_PAD_ATTRIBUTE:n.setPadAttribute,GET_PAD_ATTRIBUTE:n.getPadAttribute,SET_ATTRIBUTE:n.setAttribute,GET_ATTRIBUTE:n.getAttribute,LIST_ALL_TAGS:n.listAllTags,GET_TEMPLATES:n.getTemplates,GET_SECURE_FILES_LIST:n.getSecureFilesList,GET_PAD_DATA:n.getPadData,GET_PAD_DATA_FROM_CHANNEL:n.getPadDataFromChannel,GET_STRONGER_HASH:n.getStrongerHash,INCREMENT_TEMPLATE_USE:n.incrementTemplateUse,GET_SHARED_FOLDER:n.getSharedFolder,ADD_SHARED_FOLDER:n.addSharedFolder,LOAD_SHARED_FOLDER:n.loadSharedFolderAnon,RESTORE_SHARED_FOLDER:n.restoreSharedFolder,UPDATE_SHARED_FOLDER_PASSWORD:n.updateSharedFolderPassword,ANSWER_FRIEND_REQUEST:n.answerFriendRequest,SEND_FRIEND_REQUEST:n.sendFriendRequest,ANON_GET_PREVIEW_CONTENT:n.anonGetPreviewContent,OO_COMMAND:n.onlyoffice.execCommand,MAILBOX_COMMAND:n.mailbox.execCommand,UNIVERSAL_COMMAND:n.universal.execCommand,SEND_PAD_MSG:n.pad.sendMessage,JOIN_PAD:n.pad.join,LEAVE_PAD:n.pad.leave,REMOVE_OWNED_CHANNEL:n.pad.destroy,CLEAR_OWNED_CHANNEL:n.pad.clear,CORRUPTED_CACHE:n.pad.onCorruptedCache,GET_LAST_HASH:n.pad.getLastHash,GET_FULL_HISTORY:n.getFullHistory,GET_HISTORY:n.getHistory,GET_HISTORY_RANGE:n.getHistoryRange,IS_NEW_CHANNEL:n.isNewChannel,CONTACT_PAD_OWNER:n.contactPadOwner,GIVE_PAD_ACCESS:n.givePadAccess,BURN_PAD:n.burnPad,GET_PAD_METADATA:n.pad?.getMetadata,SET_PAD_METADATA:n.pad?.setMetadata,CHANGE_PAD_PASSWORD_PIN:n.changePadPasswordPin,GET_SNAPSHOT:n.getSnapshot,DELETE_MAILBOX_MESSAGE:n.deleteMailboxMessage,DRIVE_USEROBJECT:n.userObjectCommand,GET_DRIVE:n.drive.get,SET_DRIVE:n.drive.set,MIGRATE_ANON_DRIVE:n.drive.migrateAnon,HAS_DRIVE:n.drive.exists,DELETE_ACCOUNT:n.deleteAccount,REMOVE_OWNED_PADS:n.removeOwnedPads,ADMIN_RPC:n.adminRpc,ADMIN_ADD_MAILBOX:n.addAdminMailbox};return r.query=function(e,t,n){o[e]?o[e]("0",t,n):console.error("UNHANDLED_STORE_RPC")},r._removeClient=n._removeClient,r}}),jr),zr(),Ne()),Yr}var Zr,$r,eo=function(){if(Wr)return qr;Wr=1;const e=Xr();return qr={start:t=>{let n=!1,r=()=>{globalThis.close()};globalThis.window=globalThis,addEventListener("connect",(o=>{console.debug("New SharedWorker client");const a=o.ports[0],i=e=>{a.postMessage(e)};let s,c=!1,u=()=>{};a.onmessage=function(o){if("INIT"===o.data?.type){if((o=>{n||(t(o),e.init(r),n=!0)})(o.data.cfg),c)return;c=!0,e.initClient({postMsg:i},(function(e,t){s=e,u=t,i("SW_READY")}))}else"CLOSE"===o.data?(console.debug("leave"),u()):s&&s.fire(o)}}))}}}();var to,no,ro=function(){if($r)return Zr;$r=1;const e=Xr();return Zr={start:t=>{let n,r=!1;const o=()=>{globalThis.close()},a=e=>{postMessage(e)};globalThis.window=globalThis,onmessage=function(i){if("INIT"===i.data?.type){let s=i.data.cfg;if(r)return;return t(s),e.init(o),r=!0,void e.initClient({postMsg:a},(function(e){n=e,a("WW_READY")}))}n&&n.fire(i)}}}}();var oo=function(){if(no)return to;no=1;const e=Xr(),t=Ne();return to={start:n=>{let r,o=!1,a=!1;const i=t.mkEvent(),s=()=>{a=!0},c=e=>{a||i.fire(e)};return{init:t=>{o||(n(t),e.init(s),o=!0,e.initClient({postMsg:c},(function(e){r=e,c("STORE_READY")})))},onMessage:e=>{i.reg((t=>{setTimeout((()=>{e(t)}))}))},query:e=>{r&&!a&&r.fire({data:e,origin:""})}}}}}(),ao=gn(),io=t({__proto__:null,default:r(ao)},[ao]),so=mn(),co=t({__proto__:null,default:r(so)},[so]),uo=fr(),lo=t({__proto__:null,default:r(uo)},[uo]),fo=dr(),ho=t({__proto__:null,default:r(fo)},[fo]),po=gr(),yo=t({__proto__:null,default:r(po)},[po]),vo=Cr(),mo=t({__proto__:null,default:r(vo)},[vo]);let go=e=>{[at,kt,Te,Nt,_e,io,Qt,jt,dt,lo,ho,mo,Vr,Ze,co,yo,Mr].forEach((t=>{"function"==typeof t.setCustomize&&t.setCustomize(e)}))},Eo="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,bo="undefined"!=typeof SharedWorkerGlobalScope&&self instanceof SharedWorkerGlobalScope;e.store={},bo?eo.start(go):Eo?ro.start(go):("undefined"!=typeof module&&module.exports,e.store=oo.start(go)),e.start=go})); diff --git a/www/file/file-crypto.js b/www/file/file-crypto.js index 622e857e1..1ff579b8e 100644 --- a/www/file/file-crypto.js +++ b/www/file/file-crypto.js @@ -5,8 +5,9 @@ define([ '/common/common-util.js', '/components/tweetnacl/nacl-fast.min.js', -], function (Util) { - var Nacl = window.nacl; + '/components/chainpad-crypto/crypto.js' +], function (Util, Crypto) { + //var Nacl = window.nacl; //var PARANOIA = true; var plainChunkLength = 128 * 1024; @@ -91,7 +92,7 @@ define([ var metaBox = new Uint8Array(u8.subarray(2, 2 + metadataLength)); - var metaChunk = Nacl.secretbox.open(metaBox, nonce, key); + var metaChunk = Crypto.CryptoAgility.secretboxOpen(metaBox, nonce, key); increment(nonce); try { @@ -116,7 +117,7 @@ define([ var box = new Uint8Array(u8.subarray(start, end)); // decrypt the chunk - var plaintext = Nacl.secretbox.open(box, nonce, key); + var plaintext = Crypto.CryptoAgility.secretboxOpen(box, nonce, key); increment(nonce); if (!plaintext) { return cb('DECRYPTION_ERROR'); } @@ -184,7 +185,7 @@ define([ if (state === 0) { // metadata... part = new Uint8Array(plaintext); - box = Nacl.secretbox(part, nonce, key); + box = Crypto.CryptoAgility.secretbox(part, nonce, key); increment(nonce); if (box.length > 65535) { @@ -204,7 +205,7 @@ define([ end = start + plainChunkLength; part = u8.subarray(start, end); - box = Nacl.secretbox(part, nonce, key); + box = Crypto.CryptoAgility.secretbox(part, nonce, key); increment(nonce); i++; diff --git a/www/form/command-handler.js b/www/form/command-handler.js index ece6d2954..41e23387f 100644 --- a/www/form/command-handler.js +++ b/www/form/command-handler.js @@ -4,12 +4,13 @@ define([ '/common/common-util.js', - '/components/tweetnacl/nacl-fast.min.js' -], function (Util) { + '/components/tweetnacl/nacl-fast.min.js', + '/components/chainpad-crypto/crypto.js', +], function (Util, Nacl, Crypto) { var Handler = {}; - var Nacl = window.nacl; + //var Nacl = window.nacl; Handler.formCommandHandlers = function(sframeChan, Utils, nThen, Cryptpad) { sframeChan.on('EV_EXPORT_SHEET', function (data) { if (!data || !Array.isArray(data.content)) { return; } @@ -33,8 +34,8 @@ define([ }; var anonProof = function (channel, theirPub, anonKeys) { var u8_plain = Util.decodeUTF8(channel); - var u8_nonce = Nacl.randomBytes(Nacl.box.nonceLength); - var u8_cipher = Nacl.box( + var u8_nonce = Crypto.CryptoAgility.bytes(Crypto.CryptoAgility.boxNonceLength()); + var u8_cipher = Crypto.CryptoAgility.box( u8_plain, u8_nonce, Util.decodeBase64(theirPub), @@ -113,6 +114,7 @@ define([ var res = Utils.Crypto.Mailbox.openOwnSecretLetter(messages[0].msg, { validateKey: data.validateKey, ephemeral_private: Util.decodeBase64(answer.curvePrivate), + ephemeral_kem_private: Util.decodeBase64(answer.kemPrivate), my_private: Util.decodeBase64(finalKeys.curvePrivate), their_public: Util.decodeBase64(data.publicKey) }); @@ -143,9 +145,9 @@ define([ var proofTxt = proofObj.proof; try { var u8_bundle = Util.decodeBase64(proofTxt); - var u8_nonce = u8_slice(u8_bundle, 0, Nacl.box.nonceLength); - var u8_cipher = u8_slice(u8_bundle, Nacl.box.nonceLength); - var u8_plain = Nacl.box.open( + var u8_nonce = u8_slice(u8_bundle, 0, Crypto.CryptoAgility.boxNonceLength()); + var u8_cipher = u8_slice(u8_bundle, Crypto.CryptoAgility.boxNonceLength()); + var u8_plain = Crypto.CryptoAgility.boxOpen( u8_cipher, u8_nonce, Util.decodeBase64(pub), @@ -327,7 +329,7 @@ define([ var keys = Utils.secret && Utils.secret.keys; myKeys.signingKey = keys.secondarySignKey; - var ephemeral_keypair = Nacl.box.keyPair(); + var ephemeral_keypair = Crypto.CryptoAgility.curveKeyPair(); var ephemeral_private = Util.encodeBase64(ephemeral_keypair.secretKey); myKeys.ephemeral_keypair = ephemeral_keypair; diff --git a/www/recovery/main.js b/www/recovery/main.js index 1d91a225b..960833b6d 100644 --- a/www/recovery/main.js +++ b/www/recovery/main.js @@ -20,14 +20,15 @@ define([ '/common/outer/http-command.js', '/components/tweetnacl/nacl-fast.min.js', + '/components/chainpad-crypto/crypto.js', 'css!/components/components-font-awesome/css/font-awesome.min.css', ], function ($, Sortify, Login, Cryptpad, /*Test,*/ Cred, UI, Util, Realtime, Constants, Feedback, - Clipboard, LocalStore, Block, ServerCommand) { + Clipboard, LocalStore, Block, ServerCommand, Crypto) { if (window.top !== window) { return; } var Messages = Cryptpad.Messages; - var Nacl = window.nacl; + //var Nacl = window.nacl; $(function () { if (LocalStore.isLoggedIn()) { @@ -78,7 +79,7 @@ define([ date: new Date().toISOString(), blockId: Util.encodeBase64(pub), }; - var proof = Nacl.sign.detached(Util.decodeUTF8(Sortify(toSign)), sec); + var proof = Crypto.CryptoAgility.signDetached(Util.decodeUTF8(Sortify(toSign)), sec); toSign.proof = Util.encodeBase64(proof); proofStr = JSON.stringify(toSign, 0, 2); $mfaProof.html(proofStr); diff --git a/www/report/main.js b/www/report/main.js index 2a0205f5a..1d01e9aba 100644 --- a/www/report/main.js +++ b/www/report/main.js @@ -326,6 +326,7 @@ define([ channel: d.channel, crypto: crypto, validateKey: rosterKeys.teamEdPublic, + dsaValidateKey: rosterKeys.teamDsaPublic, // Add PQC validation key for ML-DSA Cache: Cache, noChainPad: true, onCacheReady: onCacheReady, diff --git a/www/support/inner.js b/www/support/inner.js index 7491cc5e3..5a7568892 100644 --- a/www/support/inner.js +++ b/www/support/inner.js @@ -105,6 +105,7 @@ define([ APP.supportModule.execCommand('CLOSE_TICKET', { channel: channel, curvePublic: data.curvePublic, // Support curve public for this ticket + kemPublic: data.kemPublic, // Support kem public for this ticket ticket: APP.support.getDebuggingData({ close: true }) }, function (obj) { if (obj && obj.error) { return void UI.warn(Messages.error); } @@ -116,6 +117,7 @@ define([ APP.supportModule.execCommand('REPLY_TICKET', { channel: channel, curvePublic: data.curvePublic, // Support curve public for this ticket + kemPublic: data.kemPublic, // Support kem public for this ticket ticket: formData }, function (obj) { if (obj && obj.error) { return void UI.warn(Messages.error); } diff --git a/www/teams/inner.js b/www/teams/inner.js index 90b39bb92..da372fa01 100644 --- a/www/teams/inner.js +++ b/www/teams/inner.js @@ -355,6 +355,7 @@ define([ toolbar: APP.toolbar, APP: driveAPP, edPublic: APP.teamEdPublic, + dsaPublic: APP.teamDsaPublic, editKey: teamData.secondaryKey }); APP.drive = drive;