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AAC,EAAS,KACzB,KAAK,IAAI,OAAO,IACZ,EAAS,GACL,EACA,EAAO,GAGP,GACJ,GACF,GAEV,GACJ,CACA,OAAA,CAAQ,GACJ,KAAK,MAAQ,CACjB,CACA,aAAA,CAAc,GACV,KAAK,WAAa,EAClB,KAAK,eAAe,UAAU,EAClC,EAEJ,OAAO,QAAU","file":"/npm/firebase-server-alt@1.1.0/dist/index.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/firebase-server-alt@1.1.0/dist/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","\"use strict\";\n/*\n * firebase-server 1.0.2\n * License: MIT.\n * Copyright (C) 2013, 2014, 2015, 2016, 2017, 2018, 2019, Uri Shaked and contributors.\n */\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n    return new (P || (P = Promise))(function (resolve, reject) {\n        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n        function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n        step((generator = generator.apply(thisArg, _arguments || [])).next());\n    });\n};\nconst debug = require(\"debug\");\nconst firebase = require(\"firebase\");\nconst _ = require(\"lodash\");\nconst ws_1 = require(\"ws\");\nconst firebase_hash_1 = require(\"./lib/firebase-hash\");\nconst http_server_1 = require(\"./lib/http-server\");\nconst token_validator_1 = require(\"./lib/token-validator\");\n// tslint:disable:no-var-requires\nconst targaryen = require('targaryen');\nconst log = debug('firebase-server');\n// In order to produce new Firebase clients that do not conflict with existing\n// instances of the Firebase client, each one must have a unique name.\n// We use this incrementing number to ensure that each Firebase App name we\n// create is unique.\nlet serverID = 0;\nfunction getSnap(ref) {\n    return new Promise((resolve) => {\n        ref.once('value', (snap) => {\n            resolve(snap);\n        });\n    });\n}\nfunction exportData(ref) {\n    return getSnap(ref).then((snap) => snap.exportVal());\n}\nfunction normalizePath(fullPath) {\n    let path = fullPath;\n    const isPriorityPath = /\\/?\\.priority$/.test(path);\n    if (isPriorityPath) {\n        path = path.replace(/\\/?\\.priority$/, '');\n    }\n    if (path.charAt(0) === '/') {\n        // Normally, a path would start with a slash (\"/\"), but some clients\n        // (notably Android) don't always send it.\n        path = path.substr(1);\n    }\n    return {\n        fullPath,\n        isPriorityPath,\n        path,\n    };\n}\nclass FirebaseServer {\n    constructor(portOrOptions, name = 'mock.firebase.server', data = null) {\n        this.name = name;\n        this.clock = null;\n        // Firebase is more than just a \"database\" now; the \"realtime database\" is\n        // just one of many services provided by a Firebase \"App\" container.\n        // The Firebase library must be initialized with an App, and that app\n        // must have a name - either a name you choose, or '[DEFAULT]' which\n        // the library will substitute for you if you do not provide one.\n        // An important aspect of App names is that multiple instances of the\n        // Firebase client with the same name will share a local cache instead of\n        // talking \"through\" our server. So to prevent that from happening, we are\n        // choosing a probably-unique name that a developer would not choose for\n        // their \"real\" Firebase client instances.\n        const appName = `firebase-server-internal-${this.name}-${serverID++}`;\n        // We must pass a \"valid looking\" configuration to initializeApp for its\n        // internal checks to pass.\n        const config = {\n            databaseURL: 'ws://fakeserver.firebaseio.test',\n        };\n        this.app = firebase.initializeApp(config, appName);\n        this.app.database().goOffline();\n        this.baseRef = this.app.database().ref();\n        this.baseRef.set(data);\n        this.targaryen = targaryen.database({\n            rules: {\n                '.read': true,\n                '.write': true,\n            },\n        }, data);\n        let options;\n        let port;\n        if (typeof portOrOptions === 'object') {\n            options = portOrOptions;\n            if (options.server) {\n                const address = options.server.address();\n                if (address) {\n                    port = address.port;\n                }\n                else if (options.port) {\n                    port = options.port;\n                }\n                else {\n                    throw new Error('Port not given in options and also not obtainable from server');\n                }\n            }\n            else {\n                port = options.port;\n            }\n        }\n        else {\n            port = portOrOptions;\n            options = { port };\n        }\n        if (options.server && options.rest) {\n            throw new Error('Incompatible options: server, rest');\n        }\n        else if (options.rest) {\n            this.https = http_server_1.HttpServer(port, options.address, this.app.database());\n            options = { server: this.https };\n        }\n        if (options.address) {\n            options = Object.assign({}, options, { host: options.address });\n        }\n        if (options.maxFrameLength) {\n            this.maxFrameLength = options.maxFrameLength;\n        }\n        else {\n            // The default maximum incoming frame length in the Java client\n            // is 16384; the maximum possible is 65536.\n            this.maxFrameLength = 16384;\n        }\n        this.wss = new ws_1.Server(options);\n        this.tokenValidator = token_validator_1.TokenValidator(null);\n        this.wss.on('connection', this.handleConnection.bind(this));\n        log(`Listening for connections on port ${port}`);\n    }\n    handleConnection(ws) {\n        log(`New connection from ${ws._socket.remoteAddress}:${ws._socket.remotePort}`);\n        const server = this;\n        let authToken = null;\n        function send(message) {\n            const payload = JSON.stringify(message);\n            log(`Sending message: ${payload}`);\n            try {\n                const numFragments = Math.ceil(payload.length / server.maxFrameLength);\n                ws.send(String(numFragments));\n                for (let startIdx = 0; startIdx < payload.length; startIdx += server.maxFrameLength) {\n                    ws.send(payload.substr(startIdx, server.maxFrameLength));\n                }\n            }\n            catch (e) {\n                log(`Send failed: ${e}`);\n            }\n        }\n        function authData() {\n            let data;\n            if (authToken) {\n                try {\n                    const decodedToken = server.tokenValidator.decode(authToken);\n                    if ('d' in decodedToken) {\n                        data = decodedToken.d;\n                    }\n                    else {\n                        data = {\n                            // 'user_id' is firebase-specific and may be\n                            // convenience only; 'sub' is standard JWT.\n                            provider: decodedToken.provider_id,\n                            token: decodedToken,\n                            uid: decodedToken.user_id || decodedToken.sub,\n                        };\n                    }\n                }\n                catch (e) {\n                    authToken = null;\n                }\n            }\n            return data;\n        }\n        function pushData(path, data) {\n            send({ d: { a: 'd', b: { p: path, d: data } }, t: 'd' });\n        }\n        function permissionDenied(requestId) {\n            send({ d: { r: requestId, b: { s: 'permission_denied', d: 'Permission denied' } }, t: 'd' });\n        }\n        function replaceServerTimestamp(value, data) {\n            if (_.isEqual(data, firebase.database.ServerValue.TIMESTAMP)) {\n                return value;\n            }\n            else if (_.isObject(data) && typeof data === 'object') {\n                return _.mapValues(data, replaceServerTimestamp.bind(this, value));\n            }\n            else {\n                return data;\n            }\n        }\n        function tryRead(requestId, path) {\n            const result = server.targaryen.as(authData()).read(path);\n            if (!result.allowed) {\n                permissionDenied(requestId);\n                throw new Error(`Permission denied for client to read from ${path}: ${result.info}`);\n            }\n        }\n        function tryPatch(requestId, path, newData, now) {\n            const result = server.targaryen.as(authData()).update(path, newData, now);\n            if (!result.allowed) {\n                permissionDenied(requestId);\n                throw new Error(`Permission denied for client to update at ${path}: ${result.info}`);\n            }\n            server.targaryen = result.newDatabase;\n        }\n        function tryWrite(requestId, path, newData, now) {\n            const result = server.targaryen.as(authData()).write(path, newData, now);\n            if (!result.allowed) {\n                permissionDenied(requestId);\n                throw new Error(`Permission denied for client to write to ${path}: ${result.info}`);\n            }\n            server.targaryen = result.newDatabase;\n        }\n        function handleListen(requestId, normalizedPath, fbRef) {\n            const path = normalizedPath.path;\n            log(`Client listen ${path}`);\n            try {\n                tryRead(requestId, path);\n            }\n            catch (e) {\n                log(e);\n                return;\n            }\n            let sendOk = true;\n            fbRef.on('value', (snap) => {\n                if (snap) {\n                    // BUG: tryRead() here, and if it throws, cancel the listener.\n                    // See https://github.com/urish/firebase-server/pull/100#issuecomment-323509408\n                    pushData(path, snap.exportVal());\n                    if (sendOk) {\n                        sendOk = false;\n                        send({ d: { r: requestId, b: { s: 'ok', d: {} } }, t: 'd' });\n                    }\n                }\n            });\n        }\n        function handleUpdate(requestId, normalizedPath, fbRef, newData) {\n            const path = normalizedPath.path;\n            log(`Client update ${path}`);\n            const now = server.clock || new Date().getTime();\n            newData = replaceServerTimestamp(now, newData);\n            try {\n                tryPatch(requestId, path, newData, now);\n            }\n            catch (e) {\n                log(e);\n                return;\n            }\n            fbRef.update(newData);\n            send({ d: { r: requestId, b: { s: 'ok', d: {} } }, t: 'd' });\n        }\n        function handleSet(requestId, normalizedPath, fbRef, newData, hash) {\n            log(`Client set ${normalizedPath.fullPath}`);\n            let progress = Promise.resolve();\n            const path = normalizedPath.path;\n            const now = server.clock || new Date().getTime();\n            newData = replaceServerTimestamp(now, newData);\n            if (normalizedPath.isPriorityPath) {\n                progress = exportData(fbRef).then((parentData) => {\n                    if (_.isObject(parentData)) {\n                        parentData['.priority'] = newData;\n                    }\n                    else {\n                        parentData = {\n                            '.priority': newData,\n                            '.value': parentData,\n                        };\n                    }\n                    newData = parentData;\n                });\n            }\n            progress = progress.then(() => {\n                tryWrite(requestId, path, newData, now);\n            });\n            if (typeof hash !== 'undefined') {\n                progress = progress.then(() => getSnap(fbRef)).then((snap) => {\n                    const calculatedHash = firebase_hash_1.getFirebaseHash(snap.exportVal());\n                    if (hash !== calculatedHash) {\n                        pushData(path, snap.exportVal());\n                        send({ d: { r: requestId, b: { s: 'datastale', d: 'Transaction hash does not match' } }, t: 'd' });\n                        throw new Error(`Transaction hash does not match: ${hash} !== ${calculatedHash}`);\n                    }\n                });\n            }\n            progress.then(() => {\n                fbRef.set(newData);\n                fbRef.once('value', (snap) => {\n                    send({ d: { r: requestId, b: { s: 'ok', d: {} } }, t: 'd' });\n                });\n            }).catch(log);\n        }\n        function handleAuth(requestId, credential) {\n            if (server.authSecret === credential) {\n                return send({\n                    d: {\n                        b: {\n                            d: token_validator_1.normalize({ auth: null, admin: true, exp: null }),\n                            s: 'ok',\n                        },\n                        r: requestId,\n                    },\n                    t: 'd',\n                });\n            }\n            try {\n                const decoded = server.tokenValidator.decode(credential);\n                authToken = credential;\n                return send({ t: 'd', d: { r: requestId, b: { s: 'ok', d: token_validator_1.normalize(decoded) } } });\n            }\n            catch (e) {\n                return send({ t: 'd', d: { r: requestId, b: { s: 'invalid_token', d: 'Could not parse auth token.' } } });\n            }\n        }\n        function accumulateFrames(data) {\n            // Accumulate buffer until websocket frame is complete\n            if (typeof ws.frameBuffer === 'undefined') {\n                ws.frameBuffer = '';\n            }\n            try {\n                const parsed = JSON.parse(ws.frameBuffer + data);\n                ws.frameBuffer = '';\n                return parsed;\n            }\n            catch (e) {\n                ws.frameBuffer += data;\n            }\n            return '';\n        }\n        ws.on('message', (data) => {\n            log(`Client message: ${data.toString()}`);\n            if (data.toString() === '0') {\n                return;\n            }\n            const parsed = accumulateFrames(data.toString());\n            if (parsed && parsed.t === 'd') {\n                let path;\n                if (typeof parsed.d.b.p !== 'undefined') {\n                    path = parsed.d.b.p;\n                }\n                path = normalizePath(path || '');\n                const requestId = parsed.d.r;\n                const fbRef = path.path ? this.baseRef.child(path.path) : this.baseRef;\n                if (parsed.d.a === 'l' || parsed.d.a === 'q') {\n                    handleListen(requestId, path, fbRef);\n                }\n                if (parsed.d.a === 'm') {\n                    handleUpdate(requestId, path, fbRef, parsed.d.b.d);\n                }\n                if (parsed.d.a === 'p') {\n                    handleSet(requestId, path, fbRef, parsed.d.b.d, parsed.d.b.h);\n                }\n                if (parsed.d.a === 'auth' || parsed.d.a === 'gauth') {\n                    handleAuth(requestId, parsed.d.b.cred);\n                }\n            }\n        });\n        send({ d: { t: 'h', d: { ts: new Date().getTime(), v: '5', h: this.name, s: '' } }, t: 'c' });\n    }\n    setRules(rules) {\n        this.targaryen = this.targaryen.with({ rules });\n    }\n    getData(ref) {\n        // tslint:disable-next-line:no-console\n        console.warn('FirebaseServer.getData() is deprecated! Please use FirebaseServer.getValue() instead');\n        let result = null;\n        this.baseRef.once('value', (snap) => {\n            result = snap.val();\n        });\n        return result;\n    }\n    getSnap(ref) {\n        return getSnap(ref || this.baseRef);\n    }\n    getValue(ref) {\n        return this.getSnap(ref).then((snap) => snap.val());\n    }\n    exportData(ref) {\n        return exportData(ref || this.baseRef);\n    }\n    address() {\n        return this.wss.address();\n    }\n    getPort() {\n        const address = this.address();\n        return typeof address === 'string' ? 0 : address.port;\n    }\n    close(callback = (() => 0)) {\n        return __awaiter(this, void 0, void 0, function* () {\n            if (this.https) {\n                yield new Promise((resolve) => this.https.close(resolve));\n            }\n            return new Promise((resolve, reject) => {\n                this.wss.close((err) => {\n                    callback(err);\n                    if (err) {\n                        reject(err);\n                    }\n                    else {\n                        resolve();\n                    }\n                });\n            });\n        });\n    }\n    setTime(newTime) {\n        this.clock = newTime;\n    }\n    setAuthSecret(newSecret) {\n        this.authSecret = newSecret;\n        this.tokenValidator.setSecret(newSecret);\n    }\n}\nmodule.exports = FirebaseServer;\n"]}