code
stringlengths
2
1.05M
var tdf = require('./../index.js'); var expect = require('chai').expect; describe("events", function() { before(function() { tdf.quietDefine = true; }); after(function() { tdf.quietDefine = false; }); var calls, isCalled; beforeEach(function() { calls = 0; isCalled = function() { calls++; }; tdf.on("fail", isCalled); }) afterEach(function() { tdf.off("fail", isCalled); isCalled = undefined; calls = undefined; }); it("should emit events when a `define` fails", function() { var fn = tdf() .when() .returns({}) .define(function() {}); expect(calls).to.equal(1); }); });
var eventsService = require('../data/events'), usersService = require('../data/users'); var CONTROLLER_NAME = 'events'; module.exports = { getCreate: function (req, res, next) { res.render(CONTROLLER_NAME + '/event-create-form') }, create: function (req, res, next) { var userId = req.user._id; var newEventData = req.body; var creator = usersService.byId(userId) .exec(function (err, user) { if (err) { res.status(400); req.session.error = 'User not found!'; console.log(err.toString()); return; } if (!user.phone) { res.status(400); req.session.error = 'User must provide phone number in order to crate events!'; console.log(err.toString()); res.redirect('/'); //TODO } else { //TODO validate pls!!! if (user.initiatives.indexOf(newEventData.initiative) < 0) { } else if (user.initiatives.indexOf(newEventData.initiative) < 0) { } else { newEventData.creatorName = user.username; newEventData.creatorPhone = user.phone; eventsService.create(newEventData, function (err, event) { if (err) { req.session.err = 'Event creation failed see why...!!!' } // newEventData.users.push(user._id); console.log('event is created!'); res.redirect('/'); //todo ...... }) } } }) } };
"use strict"; const gcsstorage = require("@google-cloud/storage"); const GoogleCloudStorage = require("../index"); const chai = require("chai"); const expect = chai.expect; const assert = chai.assert; const bufferEqual = require("buffer-equal"); const request = require("request"); const fs = require("fs"); const path = require("path"); const logger = console.log.bind(console); const TEST_TIMEOUT = 30000; const keyFile = require("../key.json"); const gcsConfig = { projectId: process.env["GCS_CONFIIG_PROJECT"], credentials: { client_email: process.env["GCS_CONFIIG_CLIENT_EMAIL"], private_key: process.env["GCS_CONFIIG_PRIVATE_KEY"] } }; const gcsOptions = { loggingFunction: logger, bucket: "gcs-client-lib-testing", maxRetryTimeout: 5000 }; const gcsWrapper = new GoogleCloudStorage(gcsConfig, gcsOptions); describe("Google Cloud Storage Wrapper", () => { before(function (done) { gcsstorage(gcsConfig) .bucket(gcsOptions.bucket) .deleteFiles() .then(() => { done(); }).catch((error) => { console.log('Failed on cleaning bucket with reason, ', error); }); this.timeout(TEST_TIMEOUT); }); describe("UPLOADING method `save`", () => { it("should upload JSON object to the storage, read it back and compare", function (done) { let objectToSend = { str: "value", num: 85.543, bool: true, arr: [1, 2, 3], obj: { foo: "bar" } }; let gcsPath = "test-folder-1:object.json"; gcsWrapper.save(gcsPath, objectToSend).then(() => { gcsWrapper.readAsObject(gcsPath).then((rcvObject) => { assert.deepEqual(objectToSend, rcvObject, "Sent and received objects are not deep-equal"); done(); }).catch(done); }).catch(done); }); it("should upload Buffer to the storage, read it back and compare", function (done) { let buffer = fs.readFileSync(path.resolve(__dirname, "./files/tesla.png")); let gcsPath = "test-folder-1:tesla.png"; gcsWrapper.save(gcsPath, buffer).then(() => { gcsWrapper.readAsBuffer(gcsPath).then((rcvdBuffer) => { assert.ok(bufferEqual(buffer, rcvdBuffer), "Sent and received buffers are not equal"); done(); }).catch(done); }).catch(done); }); it("should upload file from local filesystem to the storage, read it back and compare", function (done) { let fileName = path.resolve(__dirname, "./files/tesla.png"); let buffer = fs.readFileSync(fileName); let gcsPath = "test-folder-1:tesla.png"; gcsWrapper.save(gcsPath, fileName).then(() => { gcsWrapper.readAsBuffer(gcsPath).then((rcvdBuffer) => { assert.ok(bufferEqual(buffer, rcvdBuffer), "Sent and received buffers are not equal"); done(); }).catch(done); }).catch(done); }); it("should upload file from local filesystem to the storage using stream, read it back and compare", function (done) { let fileName = path.resolve(__dirname, "./files/tesla.png"); let buffer = fs.readFileSync(fileName); let stream = fs.createReadStream(fileName); let gcsPath = "test-folder-1:tesla.png"; gcsWrapper.save(gcsPath, stream).then(() => { gcsWrapper.readAsBuffer(gcsPath).then((rcvdBuffer) => { assert.ok(bufferEqual(buffer, rcvdBuffer), "Sent and received buffers are not equal"); done(); }).catch(done); }).catch(done); }); it("should upload file from local filesystem to the storage, read it back and compare (with compression)", function (done) { this.timeout(TEST_TIMEOUT); let fileName = path.resolve(__dirname, "./files/tesla.png"); let buffer = fs.readFileSync(fileName); let gcsPath = "test-folder-1:tesla.png"; gcsWrapper.save(gcsPath, fileName, { compress: true }).then(() => { gcsWrapper.readAsBuffer(gcsPath).then((rcvdBuffer) => { assert.ok(bufferEqual(buffer, rcvdBuffer), "Sent and received buffers are not equal"); done(); }).catch(done); }).catch(done); }); it("should upload image with specified content type and then retrieve it via HTTP", function (done) { this.timeout(6000); let fileName = path.resolve(__dirname, "./files/tesla.png"); let buffer = fs.readFileSync(fileName); let gcsPath = "test-folder-1:tesla.png"; let contentType = "image/jpeg"; gcsWrapper.save(gcsPath, fileName, { contentType: contentType, getURL: true }).then((url) => { assert.ok(typeof url === "string", "File URL should be a string"); request.get(url, { encoding: null }, (err, res, body) => { assert.equal(res.statusCode, 200, "Status code was not 200"); assert.equal(res.headers["content-type"], contentType, "Content type is wrong for retrieved blob"); assert.ok(bufferEqual(body, buffer), "Sent object is not equal with object retrieved by URL"); done(); }); }).catch(done); }); it("should upload an object with additional metadata and then access the metadata via list()", function (done) { let fileName = "test-folder-1:metadata.json"; let metadataValue = Math.random().toString(); gcsWrapper.save(fileName, { a: 1 }, { metadata: { key: metadataValue } }).then(() => { gcsWrapper.list("test-folder-1:").then((list) => { let file = list.find((item) => item.fullBlobName === fileName); assert.ok(file.metadata["key"] === metadataValue, "Sent and received metadata value should be equal"); done(); }).catch(done); }).catch(done); }); it("should upload file from local filesystem to the storage using stream, read it back and write it localy", function (done) { let fileName = path.resolve(__dirname, "./files/tesla.png"); let buffer = fs.readFileSync(fileName); let stream = fs.createReadStream(fileName); let gcsPath = "test-folder-1:tesla.png"; let pathTOCopy = path.resolve(__dirname, "./files/tesla-copy.png"); gcsWrapper.save(gcsPath, stream).then(() => { let writableStream = fs.createWriteStream(pathTOCopy); gcsWrapper.read(gcsPath, writableStream); writableStream.on("finish", () => { let bufferOfDownloadedFile = fs.readFileSync(pathTOCopy); assert.ok(bufferEqual(buffer, bufferOfDownloadedFile), "Sent and received buffers are not equal"); fs.unlinkSync(pathTOCopy); done(); }); }).catch(done); }); }); describe("LISTING", function () { let gcsPathPrefix = "test-folder-1:"; it("should return an array of files with specified prefix", function (done) { this.timeout(TEST_TIMEOUT); gcsWrapper.list(gcsPathPrefix).then((list) => { assert.ok(Array.isArray(list), "List should be an array"); list.forEach((item) => assert.ok(item.fullBlobName.indexOf(gcsPathPrefix) !== -1, "Results contain item(s) from other folders")); done(); }).catch(done); }); }); describe("REMOVING", function () { it("should upload file and then remove it", function (done) { this.timeout(TEST_TIMEOUT); let gcsPath = "test-folder-2:object.json"; gcsWrapper.save(gcsPath, { a: 1 }).then(() => { gcsWrapper.delete(gcsPath).then((deleted) => { assert.ok(deleted, "Blob wasn\"t deleted"); gcsWrapper.list("test-folder-2:").then(list => { let file = list.filter((item) => item.fullBlobName === gcsPath); assert.ok(file.length === 0, "Listing should not contain deleted blob"); done(); }).catch(done); }).catch(done); }).catch(done); }); }); describe("RETRY", () => { it("should call tryToDoOrFail and succeed only on 3 time", function (done) { this.timeout(TEST_TIMEOUT); let numberOfCall = 0; gcsWrapper.tryToDoOrFail(() => { return new Promise((resolve, reject) => { if (numberOfCall < 2) { numberOfCall++; reject(new Error("No internet connection.")); } else { resolve(true); } }); }).then((result) => { done(); }); }); it("should fail on tryToDoOrFail after 3 times trying to succeed", function (done) { this.timeout(TEST_TIMEOUT); let numberOfCall = 0; let errorMesssage = new Error("No internet connection."); gcsWrapper.tryToDoOrFail(() => { return new Promise((resolve, reject) => { reject(errorMesssage); }); }).catch((error) => { assert.ok(error, "Error is not empty"); done(); }); }); it("should fail on tryToDoOrFail if async operation does not get final state for max timeout time.", function (done) { this.timeout(TEST_TIMEOUT); let numberOfCall = 0; let errorMesssage = new Error("No internet connection."); gcsWrapper.tryToDoOrFail(() => { return new Promise((resolve, reject) => { setTimeout(function () { reject(errorMesssage); }, 6000); }); }).catch((error) => { function throwError() { throw new Error(error); } expect(throwError).to.throw("Promise did not get final state in max retry timeout."); done(); }); }); }); });
/* bundleLogger ------------ Provides gulp style logs to the bundle method in browserify.js */ var gutil = require('gulp-util'); var prettyHrtime = require('pretty-hrtime'); var startTime; module.exports = { start: function() { startTime = process.hrtime(); gutil.log('Running', gutil.colors.green("'bundle'") + '...'); }, end: function() { var taskTime = process.hrtime(startTime); var prettyTime = prettyHrtime(taskTime); gutil.log('Finished', gutil.colors.green("'bundle'"), 'in', gutil.colors.magenta(prettyTime)); } };
import React from 'react'; import { prefixLink } from 'gatsby-helpers'; import DocumentTitle from 'react-document-title'; import Product from '../components/Product'; import Hexagon from '../components/Hexagon'; import ProductFinder from '../components/ProductFinder'; import CatalogueForm from '../components/CatalogueForm'; import CookieBanner from '../components/CookieBanner'; import { config } from 'config'; import content from '../content.yaml'; import styles from './index.module.scss'; import MediaQuery from 'react-responsive'; import Scroll from 'react-scroll'; import classNames from 'classnames'; const scroll = Scroll.animateScroll; Array.prototype.recurse = function (callback, delay) { delay = delay || 200; var self = this, idx = 0; setInterval(function () { callback(self[idx], idx); idx = (idx + 1 < self.length) ? idx + 1 : 0; }, delay); }; export default class Index extends React.Component { constructor(props) { super(props); this.state = { productId: 0, value: 10, prodForCalc: null, cycle: true }; } componentDidMount() { setInterval(() => { if (!this.state.cycle) return; let next = this.state.productId + 1; if (next > content.products.length - 1) next = 0; this.setState({ productId: next }); }, 2500); } handleProductClick = (productId) => { this.setState({ productId: productId, cycle: false }); }; handleStopCycle = () => { this.setState({ cycle: false }); }; handleCalculate = (productId) => { const el = document.getElementById('rechner'); this.setState({ prodForCalc: productId }); scroll.scrollTo(el.offsetTop); }; render() { const product = content.products[this.state.productId]; return ( <DocumentTitle title={config.siteTitle}> <div> <CookieBanner></CookieBanner> <Product data={product} onStopCycle={this.handleStopCycle} onCalculate={this.handleCalculate}/> <nav className={styles.productNav}> {this.renderNavItems()} </nav> <nav className={styles.nav}> <a href="#was">Was ist fugi-fix?</a> <a href="#katalog">Katalog anfordern</a> <a href="#werkzeuge">Werkzeuge</a> <a href="#kontakt">Kontakt</a> </nav> <div className={styles.what} id="was"> <div className={styles.grid}> <div className={styles.text}> <div className={styles.inner}> <h2> Was ist fugi-fix? </h2> <p>{content.general.what}</p> </div> </div> <div className={styles.image}> <img src={prefixLink('/images/shapebild01.png')}/> </div> </div> <div className={styles.grid}> <div className={styles.image}> <img src={prefixLink('/images/shapebild02.png')}/> </div> <div className={styles.text}> <div className={styles.inner}> <h2> Einsatz von fugi-fix </h2> <p>{content.general.detail}</p> </div> </div> </div> <div className={styles.grid}> <div className={styles.text}> <div className={styles.inner}> <h2>Ihre Vorteile</h2> <ul> {content.general.gain.map(text => <li>{text}</li>)} </ul> </div> </div> <div className={styles.image}> <img src={prefixLink('/images/shapebild03.png')}/> </div> </div> </div> <h2 className={styles.subtitle}> Welches fugi-fix brauche ich? </h2> <ProductFinder product={this.state.prodForCalc}/> <div className={classNames(styles.section, styles['section--alt'])} id="katalog"> <h2 className={styles.subtitle}> Katalog anfordern </h2> <div className="row"> <div className="small-8 small-shift-2"> <CatalogueForm product={this.state.prodForCalc}/> </div> </div> </div> <div className={styles.section} id="werkzeuge"> <h2 className={styles.subtitle}> Werkzeuge </h2> <p className="text-center"> Wir bieten Ihnen verschiedene Werkzeuge zur sauberen Verlegung des Pflasterfugenmörtels.<br/> Sollten Sie diese Dinge nicht bereits zu Hause haben, können Sie diese bei einer Mörtelbestellung gleich mitbestellen. </p> <br/> <div className={styles['tool-grid']}> <div className={styles.tool}> <img src={prefixLink('/images/besen01.png')}/> <span>Straßenbesen</span> <span>Vorreinigung der Fläche</span> </div> <div className={styles.tool}> <img src={prefixLink('/images/besen02.png')}/> <span>Feiner Haarbesen</span> <span>Endreinigung der Fläche</span> </div> <div className={styles.tool}> <img src={prefixLink('/images/wischer.png')}/> <span>Fliesenwischer</span> <span>Einarbeitung des Materials</span> </div> <div className={styles.tool}> <img src={prefixLink('/images/Messbecher.png')}/> <span>Messbecher</span> <span>Für die Wasserzugabe für 2K Mörtel</span> </div> </div> </div> <div className={classNames(styles.section, styles.section__contact, styles['section--alt'])} id="kontakt"> <h2 className={styles.subtitle}> Kontakt </h2> <div className="row"> <div className="small-12 text-center"> <address> <b>Nadler Straßentechnik GmbH</b><br/> Fraunhoferstraße 3<br/> 85301 Schweitenkirchen </address> <dl> <dt><i className="fa fa-phone"></i> Telefon</dt> <dd><a href="tel:00498441924000">08444 - 92400 - 0</a></dd> <dt><i className="fa fa-fax"></i> Fax</dt> <dd>08444 - 92400 - 40</dd> <dt><i className="fa fa-envelope"></i> E-Mail</dt> <dd><a href="mailto:info@strassentechnik.de">info@fugi-fix.de</a></dd> </dl> </div> </div> </div> </div> </DocumentTitle> ); } renderNavItems() { return content.products.map((p, i) => { return ( <a key={i} onClick={this.handleProductClick.bind(this, i)}> <MediaQuery query='(min-width: 48em)'> <span className={`bg--${p.color}`}>{p.title}</span> <Hexagon color={p.color} active={i === this.state.productId}/> </MediaQuery> <MediaQuery query='(max-width: 767px)'> <span className={`bg--${p.color}`}>{p.title}</span> <Hexagon width={30} strokeWidth={2} color={p.color} active={i === this.state.productId}/> </MediaQuery> </a> ); }); } }
var inputoperandA = document.querySelector("#operand_a"); var inputOperator = document.querySelector("#operator"); var output = document.querySelector("#output"); var error = document.querySelector("#error"); var showError = function(){ error.setAttribute("class", ""); }; var hideError = function(){ error.setAttribute("class", "hidden"); }; var showResult = function(result){ output.value = result + ""; }; var multiply = function(a, b){ return a * b; }; var isOperator = function(operator){ return operator == "コーラ" || operator == "スプライト" || operator == "オレンジジュース" || operator == "ビール" || operator == "ココア" || operator == "スタバ新作:チャンキークッキーフラペチーノ"; }; var isNumber = function(a){ return !Number.isNaN(a); //全ての数値 }; var isMultiplication = function(operator, a){ return operator == "コーラ" && isNumber(a)|| operator == "スプライト" && isNumber(a)|| operator == "オレンジジュース" && isNumber(a) || operator == "ビール" && isNumber(a) || operator == "ココア" && isNumber(a) || operator == "スタバ新作:チャンキークッキーフラペチーノ" && isNumber(a); } var isReady = function(operator, a, b){ return isMultiplication(operator, a, b); }; var startCalc = function(){ var operandA = inputoperandA.value; var operator = inputOperator.value; operandA = Number(operandA); hideError(); if(isReady(operator, operandA)){ var result = 0; if(operator == "コーラ"){ result = multiply(225, operandA); } else if (operator == "スプライト"){ result = multiply(205, operandA); } else if (operator == "オレンジジュース"){ result = multiply(214, operandA); } else if (operator == "ビール"){ result = multiply(200, operandA); } else if (operator == "ココア"){ result = multiply(2060, operandA); } else if (operator == "スタバ新作:チャンキークッキーフラペチーノ"){ result = multiply(553, operandA); } showResult(result); }else{ showError(); } console.log(operator); console.log(output); }; var initApp = function(){ var calcButton = document.querySelector("#calcButton"); calcButton.addEventListener("click", startCalc) }; initApp();
/** * Copyright 2014 GetHuman LLC * Author: Jeff Whelpley * Date: 10/21/14 * * */ var name = 'middleware/jng.pages'; var taste = require('../../pancakes.angular.taste'); var jng = taste.target(name); var utils = taste.target('middleware/jng.utils'); var filters = taste.target('middleware/jng.filters'); var jangular = require('jangular'); var pancakes = require('pancakes'); var _ = require('lodash'); describe('UNIT ' + name, function () { var appName = 'foo'; var context = { pancakes: pancakes }; _.extend(context, utils, jng, filters); describe('renderLayout()', function () { it('should return the rendered layout', function () { var layoutName = 'fake'; var dependencies = { model: { something: true, another: false, boo: 'blah' }}; jangular.addShortcutsToScope(dependencies); var expected = '<div><span><a href="/blah">hello, world</a></span><div ng-if="something" ng-bind="boo">blah</div></div>'; var actual = jng.renderLayout.call(context, appName, layoutName, dependencies); actual.should.equal(expected); }); }); describe('renderPage()', function () { var routeInfo = { appName: appName, strip: true }; var page = { defaults: { foo1: true }, subviews: { sub1: function (div) { return div({ 'ng-if': 'foo1' }, 'sub1'); }, sub2: function (span) { return span({ 'ng-if': 'foo2' }, 'sub2'); } }, view: function (div, subviews) { return div(subviews.sub1, subviews.sub2); } }; var model = { foo2: false }; var expected = '<div><div>sub1</div></div>'; var actual = jng.renderPage.call(context, routeInfo, page, model); actual.should.eventually.equal(expected); }); });
fleetManager.panel.Home = function (config) { config = config || {}; Ext.apply(config, { baseCls: 'modx-formpanel', layout: 'anchor', /* stateful: true, stateId: 'fleetmanager-panel-home', stateEvents: ['tabchange'], getState:function() {return {activeTab:this.items.indexOf(this.getActiveTab())};}, */ hideMode: 'offsets', items: [{ xtype: 'modx-tabs', defaults: {border: false, autoHeight: true}, border: false, hideMode: 'offsets', items: [{ title: _('fleetmanager_items'), layout: 'anchor', items: [{ html: _('fleetmanager_intro_msg'), cls: 'panel-desc', }, { xtype: 'fleetmanager-grid-items', cls: 'main-wrapper', }] }] }] }); fleetManager.panel.Home.superclass.constructor.call(this, config); }; Ext.extend(fleetManager.panel.Home, MODx.Panel); Ext.reg('fleetmanager-panel-home', fleetManager.panel.Home);
$(document).ready(function() { var container = $('.masonry-container'); container.imagesLoaded( function () { container.masonry({ columnWidth: '.initiative', itemSelector: '.initiative' }); }); $('.carousel').carousel({ interval: false }) });
// should-be-like.js /* * Copyright (c) 2016-2017 James Leigh, Some Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ const _ = require('underscore'); const like = require('../src/like.js'); const should = require('chai').use(like).use(require("chai-as-promised")).should(); const utils = require('mocha').utils; utils.canonicalize = _.wrap(utils.canonicalize, function(fn, value) { // moment objects don't need dissecting if (_.isObject(value) && _.isFunction(value.toJSON)) return value.toJSON(); if (_.isFunction(value)) return value.toString(); else return fn.apply(this, _.rest(arguments)); }); module.exports = like;
// Add your polyfills here
import React from 'react' import { Message } from 'shengnian-ui-react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' import ShorthandExample from 'docs/app/Components/ComponentDoc/ShorthandExample' const CheckboxTypesExamples = () => ( <ExampleSection title='Types'> <Message info> All checkbox types use an input with type <code>checkbox</code> unless <code>type</code> is provided. {' '}Use <code>type</code> if you'd like to mix and match style and behavior. {' '}For instance, <code>slider</code> with <code>type</code> radio for exclusive sliders. </Message> <ComponentExample title='Checkbox' description='A box for checking.' examplePath='modules/Checkbox/Types/CheckboxExampleCheckbox' /> <ShorthandExample description='You can define a label with a props object.' examplePath='modules/Checkbox/Types/CheckboxExampleShorthandObject' /> <ShorthandExample description='You can define a label by passing your own element.' examplePath='modules/Checkbox/Types/CheckboxExampleShorthandElement' /> <ComponentExample title='Toggle' description='A checkbox can toggle.' examplePath='modules/Checkbox/Types/CheckboxExampleToggle' /> <ComponentExample title='Slider' description='A checkbox can look like a slider.' examplePath='modules/Checkbox/Types/CheckboxExampleSlider' /> <ComponentExample title='Radio' description='A checkbox can be formatted as a radio element. This means it is an exclusive option.' examplePath='modules/Checkbox/Types/CheckboxExampleRadio' /> <ComponentExample title='Radio Group' examplePath='modules/Checkbox/Types/CheckboxExampleRadioGroup' > <Message warning> Radios in a group must be <a href='https://facebook.github.io/react/docs/forms.html#controlled-components' rel='noopener noreferrer' target='_blank' > &nbsp;controlled components. </a> </Message> </ComponentExample> </ExampleSection> ) export default CheckboxTypesExamples
/** * UserCountry schema * @type {SimpleSchema} */ Schemas.UserCountry = new SimpleSchema({ name: { type: String }, code: { type: String, regEx: /^[A-Z]{2}$/ } }); /** * UserProfile * @type {SimpleSchema} */ Schemas.UserProfile = new SimpleSchema({ picture: { type: String, optional: true, autoform: { afFieldInput: { type: 'fileUpload', collection: 'Images' } } }, firstName: { type: String, regEx: /^[a-zA-Z-]{2,25}$/, optional: true }, lastName: { type: String, regEx: /^[a-zA-Z]{2,25}$/, optional: true }, birthday: { type: Date, optional: true }, gender: { type: String, allowedValues: ['Male', 'Female'], optional: true, autoform: { options: [ {label: "Male", value: "Male"}, {label: "Female", value: "Female"} ] } }, organization : { type: String, regEx: /^[a-z0-9A-z .]{3,30}$/, optional: true }, website: { type: String, regEx: SimpleSchema.RegEx.Url, optional: true }, bio: { type: String, optional: true }, country: { type: Schemas.UserCountry, optional: true } }); /** * User schema * @type {SimpleSchema} */ Schemas.User = new SimpleSchema({ username: { type: String, regEx: /^[a-z0-9A-Z_]{3,35}$/, min: 3, max: 35, unique: true, custom: function () { if (Meteor.isClient && this.isSet) { Meteor.call("validUserName", this.value, function (error, result) { if (result) { Meteor.users.simpleSchema().namedContext("setUsername").addInvalidKeys([{name: "username", type: "notUnique"}]); } }); } }, optional: true }, emails: { type: [Object], // this must be optional if you also use other login services like facebook, // but if you use only accounts-password, then it can be required optional: true }, "emails.$.address": { type: String, regEx: SimpleSchema.RegEx.Email }, "emails.$.verified": { type: Boolean, optional: true }, // Force value to be current date (on both) upon insert // and prevent updates thereafter. createdAt: { type: Date, autoValue: function() { if (this.isInsert) { return new Date; } else if (this.isUpsert) { return {$setOnInsert: new Date}; } else { this.unset(); } } }, profile: { type: Schemas.UserProfile, optional: true }, services: { type: Object, optional: true, blackbox: true }, // Add `roles` to your schema if you use the meteor-roles package. // Option 1: Object type // If you specify that type as Object, you must also specify the // `Roles.GLOBAL_GROUP` group whenever you add a user to a role. // Example: // Roles.addUsersToRoles(userId, ["admin"], Roles.GLOBAL_GROUP); // You can't mix and match adding with and without a group since // you will fail validation in some cases. roles: { type: Object, optional: true, blackbox: true } /*, // Option 2: [String] type // If you are sure you will never need to use role groups, then // you can specify [String] as the type roles: { type: [String], optional: true } */ }); Meteor.users.attachSchema(Schemas.User);
export const levels = [ { xp: 200, reward: 100, name: "Nice" }, { xp: 700, reward: 500, name: "Good" }, { xp: 1400, reward: 1000, name: "Great" }, { xp: 3000, reward: 2000, name: "Excellent" }, { xp: 7000, reward: 5000, name: "Wondeful" }, { xp: 15000, reward: 10000, name: "Superb" }, { xp: 30000, reward: 20000, name: "Godlike" }, { xp: 55000, reward: 40000, name: "Funky" }, { xp: 115000, reward: 80000, name: "Fantastic" }, { xp: 145000, reward: 100000, name: "Amazing" } ]; /* * NICE.........+100 * GOOD.........+500 * GREAT........+1.000 * EXCELLENT....+2.000 * WONDERFUL....+5.000 * SUPERB.......+10.000 * GODLIKE......+20.000 * FUNKY........+40.000 * FANTASTIC....+80.000 * AMAZING(?)...+100.000 */ export const determineLevel = xp => { let processXP = xp; for (let index = 0; index < levels.length; index++) { const levelData = levels[index]; if (processXP < levelData.xp) return index; processXP -= levelData.xp; } return levels.length - 1; }; export const levelProgress = xp => { let processXP = xp; for (let index = 0; index < levels.length; index++) { const levelData = levels[index]; if (processXP < levelData.xp) return processXP / levelData.xp; processXP -= levelData.xp; } return 1; }; export const levelInfo = level => levels[level - 1];
'use strict'; angular.module('mean.auth').config(['$stateProvider', function($stateProvider) { $stateProvider.state('auth example page', { url: '/auth/example', templateUrl: 'auth/views/index.html' }); } ]);
(function () { "use strict"; window.app.views.CommentPlaceholder = Backbone.View.extend({ className: "comment comment--placeholder", tagName: "li", template: "comment-placeholder", render: function() { var template = this.compileTemplate(this.template); this.$el.html(template()); return this; } }); }());
var m = m || false; var imgs = []; if (m && m.images && m.images.length > 0) imgs = m.images; $(function(){ var visible = 0, add = false; var pswpElement = document.querySelectorAll('.pswp')[0]; var FixSize = (function(){ var E = function() { // Меряем размер панельки заголовков var WW = $(window).width(); var paddings = 20; if ($('#p').hasClass('mini')) { var pwidth = $('#p').data('W'); } else { var pwidth = 0; $('#p .cascade .pane, #p .right').each(function(){ pwidth += ($(this).width() + paddings); }); $('#p').data('W', pwidth) } if (WW >= pwidth + paddings) { console.log('Full Panel'); $('.place').html(''); $('#p').removeClass('mini'); } else { console.log('Small Panel'); var html = ''; var g = $('.pgtitle').html(); if (g) html += '<h2><a href="/">' +g+ '</a></h2>'; var a = $('.pmtitle').html(); if (a) html += '<h3>' +a+ '</h3>'; $('.place').html(html); $('#p').addClass('mini'); } FixWidth('.imgs.e', 'a', WW > 360 ? 200 : 120, 3); }; E(); $('.imgs.e').css({ height : 'auto' }); return E; }()); var ShowImages = (function(){ if (imgs.length == 0) return; var adding = false; var visibleImages = 0; var margin = 6; var Show = function() { if (adding) return; var area = $('.imgs.e').width(); var imageSize = $('.imgs.e a')[0].style.height; var size = Number(imageSize.replace('px','')) + margin; var height = $(window).height() + window.scrollY; var count = Math.round(height/size + 1) * Math.round(area/size); adding = setInterval(function(){ console.log(visibleImages); if (visibleImages < imgs.length && visibleImages < count) { var src = hard + imgs[visibleImages].src_xthumb; var img = '<img src="'+src+'" onload="$(this).fadeIn(250)" />'; $('[data-id="'+imgs[visibleImages].id+'"]').html(img); visibleImages++; } else { clearInterval(adding); adding = false; } }, 50); }; Show(); return Show; }()); window.onresize = function(){ Stack(FixSize, 300); Stack(ShowImages, 50); }; window.onscroll = function(){ Stack(ShowImages, 50); }; // Просмотр изображений в альбома (function(){ var items = []; for (var i in imgs) { var src = Picture.Src(imgs[i]); var size = Picture.Size(src); items.push({ 'src' : src, 'w' : size[0], 'h' : size[1], 'pid' : imgs[i].id }); } var gallery = false; var current = ''; setInterval(function(){ var id = GetID(); if (current != id) { current = id; if (current != '') OpenSwipe(id); console.log('> Changed'); } }, 100); $('.imgs.e a').click(function(e){ e.preventDefault(); OpenSwipe( $(this).data('id') ) }); function UpdateUrl(i) { var title = (i || i === 0) ? [imgs[i].title] : []; title.push(m.title, m.author, 'Мазепа'); $('title').html(title.join(' ∞ ')); var url = location.pathname.indexOf('/albums/') ? '/' : '/albums/'; url += Number(m.id).toString(32) + '.' + m.secret + '/'; if (i || i === 0) url += imgs[i].id; history.pushState(false, title.join(' ∞ '), url); } function OpenSwipe(id) { var image = $('[data-id="'+id+'"]'); if (image.length == 0) return UpdateUrl(); var index = image.data('i'); if (gallery) return gallery.goTo(index); var options = { index : index }; gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options); gallery.listen('close', function() { UpdateUrl(); gallery = false; }); gallery.listen('afterChange', function(e) { var index = $('[data-id="'+gallery.currItem.pid+'"]').data('i'); UpdateUrl(index); }); gallery.init(); } function GetID() { return location.pathname.split('/').slice(3)[0] || ''; } }()); // Bookmark (function() { var request = false; var e = $(".bookmark"); if (e.length == 0) return; if (m.bookmark) e.addClass('saved')[0].dataset.tooltip = 'Убрать из закладок'; e.click(function() { if (level == 0) return Login(); if (request) return; request = true; if (e.hasClass('saved')) { var add = 0; e.removeClass('saved')[0].dataset.tooltip = 'Добавить в закладки'; } else { var add = 1; e.addClass('saved')[0].dataset.tooltip = 'Убрать из закладок'; } Library('Bookmark', {aid : m.id, add : add}, function(){ request = false; }); }); }()); });
const ping = require('ping') const speech = require('../speech') /** * Ping the server. * @param {string} host IP or Domain * @param {number} [num=1] Ping count * @returns {Promise<object, object>} Object or Error */ const getPing = (host, num = 1) => { return new Promise((resolve, reject) => { if (/^(\d{1,3}\.){3}(\d{1,3})$/.test(host) || /^[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/.test(host)) { const count = !isNaN(num) ? parseInt(num) : 1 const options = { timeout: 10, extra: ['-c ' + count] } ping.promise.probe(host, options).then(result => { resolve(result) }).catch(err => { reject(new Error(err.message)) }) } else { reject(new Error(speech.ping.error)) } }) } module.exports = getPing if (require.main === module) { require('./ping')('google.com', 3).then(res => { console.log(res) }).catch(err => { console.log(err.message) }) }
/** * Created by 殿麒 on 2015/11/3. */ function GetQueryString(name) { var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if(r!=null)return unescape(r[2]); return null; } purchase.controller('goodsDetails',function($rootScope,$scope,$location,$cookieStore,goodsCartcookie,purchasePost,getAccessInfo){ var self_url = GetQueryString("productId"); if(self_url!= undefined){ var productId = self_url; }else{ var productId = $rootScope.GOODSINFO.productId; } var data = { productId:productId, sign:'sign', accessInfo:getAccessInfo.accessInfo } var path = 'product/detail'; purchasePost.postData(data,path).success(function(data){ var imgs = data.productInfo.images; // 这里因为数组中是字符串不是对象所以需要想将字符串变为对象 var imgArr = []; for(var i = 0,len = imgs.length; i < len;i++){ var obj = {src:imgs[i]}; imgArr.push(obj); } $scope.imgs = imgArr; $scope.goodsName = data.productInfo.title; $scope.saleNum = data.productInfo.salesCnt; $scope.limitBuy = data.productInfo.subTitle; $scope.nowSale = data.productInfo.price; $scope.originSale = data.productInfo.marketPrice || $scope.nowSale; console.log(data); $scope.goodsInfo = data.productInfo; }); $scope.addGoodscart = function(){ var goodscart_list = $cookieStore.get('goodscart_list'); $rootScope.GOODSCART_NUM += 1; $rootScope.GOODSCART_MONEY += $scope.goodsInfo.price; // 添加cookie goodsCartcookie.add_goodsCart_cookie(goodscart_list,$scope.goodsInfo); } }); purchase.controller('comment',function($rootScope,$scope,$cookieStore,purchasePost){ var self_url = GetQueryString("productId"); if(self_url!= undefined){ var productId = self_url; }else{ var productId = $rootScope.GOODSINFO.productId; } var requestPageInfo = { pageNo:1, pageSize:2 }; var shopId = $rootScope.GOODSINFO.shopId || GetQueryString("shopId") || null; var data = { shopId:shopId, requestPageInfo:requestPageInfo } var path = 'shop/reviewList'; purchasePost.postData(data,path).success(function(data){ $scope.totalCount = data["responsePageInfo"].totalCount; $scope.item_respList = data["item_respList"]; }); });
import 'velocity-animate'; import 'velocity-animate/velocity.ui'; import templateUrl from './template.html'; import ngModule from '../../module'; class AvLoaderController { constructor($element) { this.av = { $element }; this.active = false; } start() { this.active = true; this.animate(); } animate() { const self = this; this.av.$element .find('.loading-bullet') .velocity('transition.slideRightIn', { stagger: 250 }) .velocity({ opacity: 0 }, { delay: 750, duration: 500, complete() { if (self.active) { setTimeout( () => { self.animate() }, 500); } else { self.endAnimation(); } } }); } endAnimation = function() { this.av.$element.find('.loading-bullet').velocity('stop', true); this.av.$element.removeData(); } $destroy() { this.active = false; } $postLink() { this.start(); } } ngModule.directive('avLoader', () => { return { restrict: 'AE', replace: true, controller: AvLoaderController, templateUrl }; }); export default ngModule;
export default [ { x1: 18, y1: 50, x2: 30, y2: 50, }, { x1: 18, y1: 50, x2: 18, y2: 22, }, { x1: -6, y1: 22, x2: 18, y2: 22, }, { x1: 30, y1: 50, x2: 30, y2: 10, }, { x1: 6, y1: 10, x2: 30, y2: 10, }, { x1: -6, y1: 22, x2: -6, y2: 0, }, { x1: 6, y1: 10, x2: 6, y2: 0, }, ];
module.exports = { "parser": "babel-eslint", "rules": { "indent": [ 2, 2 ], "quotes": [ 2, "single" ], "linebreak-style": [ 2, "unix" ], "semi": [ 2, "always" ], "no-shadow" : 0, "no-cond-assign" : 2, "space-after-keywords" : 2, "key-spacing" : [2, {"align": "colon"}], "no-multiple-empty-lines" : [2, {"max": 2}], "wrap-iife" : [2, "inside"], "brace-style" : 2, "spaced-comment" : [2, "always", {"exceptions":["-","+"]}], "space-before-blocks" : 2, "no-implicit-coercion" : 2, "no-useless-call" : 2, "prefer-reflect" : 2, // ES6+ Rules "arrow-spacing" : [2, { "before": true, "after": true }], "constructor-super" : 2, "no-class-assign" : 2, "no-const-assign" : 2, "no-invalid-this" : 2, "no-this-before-super" : 2, "no-var" : 2, "object-shorthand" : 2, "prefer-const" : 2, "prefer-spread" : 2 }, "env": { "es6": true, "node": true }, "extends": "eslint:recommended" };
/* * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. AND ITS CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC. * OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @constructor * @implements {WebInspector.SearchScope} * @param {WebInspector.UISourceCodeProvider} uiSourceCodeProvider */ WebInspector.ScriptsSearchScope = function(uiSourceCodeProvider) { // FIXME: Add title once it is used by search controller. WebInspector.SearchScope.call(this) this._searchId = 0; this._uiSourceCodeProvider = uiSourceCodeProvider; } WebInspector.ScriptsSearchScope.prototype = { /** * @param {WebInspector.SearchConfig} searchConfig * @param {function(WebInspector.FileBasedSearchResultsPane.SearchResult)} searchResultCallback * @param {function(boolean)} searchFinishedCallback */ performSearch: function(searchConfig, searchResultCallback, searchFinishedCallback) { this.stopSearch(); var uiSourceCodes = this._sortedUISourceCodes(); var uiSourceCodeIndex = 0; function filterOutContentScripts(uiSourceCode) { return !uiSourceCode.isContentScript; } if (!WebInspector.settings.searchInContentScripts.get()) uiSourceCodes = uiSourceCodes.filter(filterOutContentScripts); function continueSearch() { // FIXME: Enable support for counting matches for incremental search. // FIXME: Enable support for bounding search results/matches number to keep inspector responsive. if (uiSourceCodeIndex < uiSourceCodes.length) { var uiSourceCode = uiSourceCodes[uiSourceCodeIndex++]; uiSourceCode.searchInContent(searchConfig.query, !searchConfig.ignoreCase, searchConfig.isRegex, searchCallbackWrapper.bind(this, this._searchId, uiSourceCode)); } else searchFinishedCallback(true); } function searchCallbackWrapper(searchId, uiSourceCode, searchMatches) { if (searchId !== this._searchId) { searchFinishedCallback(false); return; } var searchResult = new WebInspector.FileBasedSearchResultsPane.SearchResult(uiSourceCode, searchMatches); searchResultCallback(searchResult); if (searchId !== this._searchId) { searchFinishedCallback(false); return; } continueSearch.call(this); } continueSearch.call(this); return uiSourceCodes.length; }, stopSearch: function() { ++this._searchId; }, /** * @param {WebInspector.SearchConfig} searchConfig */ createSearchResultsPane: function(searchConfig) { return new WebInspector.FileBasedSearchResultsPane(searchConfig); }, /** * @return {Array.<WebInspector.UISourceCode>} */ _sortedUISourceCodes: function() { function filterOutAnonymous(uiSourceCode) { return !!uiSourceCode.url; } function comparator(a, b) { return a.url.localeCompare(b.url); } var uiSourceCodes = this._uiSourceCodeProvider.uiSourceCodes(); uiSourceCodes = uiSourceCodes.filter(filterOutAnonymous); uiSourceCodes.sort(comparator); return uiSourceCodes; } } WebInspector.ScriptsSearchScope.prototype.__proto__ = WebInspector.SearchScope.prototype; WebInspector.settings.searchInContentScripts = WebInspector.settings.createSetting("searchInContentScripts", false);
'use strict'; /* global routeToRegExp: false */ /** * @ngdoc object * @name angular.mock * @description * * Namespace from 'angular-mocks.js' which contains testing related code. * */ angular.mock = {}; /** * ! This is a private undocumented service ! * * @name $browser * * @description * This service is a mock implementation of {@link ng.$browser}. It provides fake * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr, * cookies, etc. * * The api of this service is the same as that of the real {@link ng.$browser $browser}, except * that there are several helper methods available which can be used in tests. */ angular.mock.$BrowserProvider = function() { this.$get = [ '$log', '$$taskTrackerFactory', function($log, $$taskTrackerFactory) { return new angular.mock.$Browser($log, $$taskTrackerFactory); } ]; }; angular.mock.$Browser = function($log, $$taskTrackerFactory) { var self = this; var taskTracker = $$taskTrackerFactory($log); this.isMock = true; self.$$url = 'http://server/'; self.$$lastUrl = self.$$url; // used by url polling fn self.pollFns = []; // Task-tracking API self.$$completeOutstandingRequest = taskTracker.completeTask; self.$$incOutstandingRequestCount = taskTracker.incTaskCount; self.notifyWhenNoOutstandingRequests = taskTracker.notifyWhenNoPendingTasks; // register url polling fn self.onUrlChange = function(listener) { self.pollFns.push( function() { if (self.$$lastUrl !== self.$$url || self.$$state !== self.$$lastState) { self.$$lastUrl = self.$$url; self.$$lastState = self.$$state; listener(self.$$url, self.$$state); } } ); return listener; }; self.$$applicationDestroyed = angular.noop; self.$$checkUrlChange = angular.noop; self.deferredFns = []; self.deferredNextId = 0; self.defer = function(fn, delay, taskType) { var timeoutId = self.deferredNextId++; delay = delay || 0; taskType = taskType || taskTracker.DEFAULT_TASK_TYPE; taskTracker.incTaskCount(taskType); self.deferredFns.push({ id: timeoutId, type: taskType, time: (self.defer.now + delay), fn: fn }); self.deferredFns.sort(function(a, b) { return a.time - b.time; }); return timeoutId; }; /** * @name $browser#defer.now * * @description * Current milliseconds mock time. */ self.defer.now = 0; self.defer.cancel = function(deferId) { var taskIndex; angular.forEach(self.deferredFns, function(task, index) { if (task.id === deferId) taskIndex = index; }); if (angular.isDefined(taskIndex)) { var task = self.deferredFns.splice(taskIndex, 1)[0]; taskTracker.completeTask(angular.noop, task.type); return true; } return false; }; /** * @name $browser#defer.flush * * @description * Flushes all pending requests and executes the defer callbacks. * * See {@link ngMock.$flushPendingsTasks} for more info. * * @param {number=} number of milliseconds to flush. See {@link #defer.now} */ self.defer.flush = function(delay) { var nextTime; if (angular.isDefined(delay)) { // A delay was passed so compute the next time nextTime = self.defer.now + delay; } else if (self.deferredFns.length) { // No delay was passed so set the next time so that it clears the deferred queue nextTime = self.deferredFns[self.deferredFns.length - 1].time; } else { // No delay passed, but there are no deferred tasks so flush - indicates an error! throw new Error('No deferred tasks to be flushed'); } while (self.deferredFns.length && self.deferredFns[0].time <= nextTime) { // Increment the time and call the next deferred function self.defer.now = self.deferredFns[0].time; var task = self.deferredFns.shift(); taskTracker.completeTask(task.fn, task.type); } // Ensure that the current time is correct self.defer.now = nextTime; }; /** * @name $browser#defer.getPendingTasks * * @description * Returns the currently pending tasks that need to be flushed. * You can request a specific type of tasks only, by specifying a `taskType`. * * @param {string=} taskType - The type tasks to return. */ self.defer.getPendingTasks = function(taskType) { return !taskType ? self.deferredFns : self.deferredFns.filter(function(task) { return task.type === taskType; }); }; /** * @name $browser#defer.formatPendingTasks * * @description * Formats each task in a list of pending tasks as a string, suitable for use in error messages. * * @param {Array<Object>} pendingTasks - A list of task objects. * @return {Array<string>} A list of stringified tasks. */ self.defer.formatPendingTasks = function(pendingTasks) { return pendingTasks.map(function(task) { return '{id: ' + task.id + ', type: ' + task.type + ', time: ' + task.time + '}'; }); }; /** * @name $browser#defer.verifyNoPendingTasks * * @description * Verifies that there are no pending tasks that need to be flushed. * You can check for a specific type of tasks only, by specifying a `taskType`. * * See {@link $verifyNoPendingTasks} for more info. * * @param {string=} taskType - The type tasks to check for. */ self.defer.verifyNoPendingTasks = function(taskType) { var pendingTasks = self.defer.getPendingTasks(taskType); if (pendingTasks.length) { var formattedTasks = self.defer.formatPendingTasks(pendingTasks).join('\n '); throw new Error('Deferred tasks to flush (' + pendingTasks.length + '):\n ' + formattedTasks); } }; self.$$baseHref = '/'; self.baseHref = function() { return this.$$baseHref; }; }; angular.mock.$Browser.prototype = { /** * @name $browser#poll * * @description * run all fns in pollFns */ poll: function poll() { angular.forEach(this.pollFns, function(pollFn) { pollFn(); }); }, url: function(url, replace, state) { if (angular.isUndefined(state)) { state = null; } if (url) { // The `$browser` service trims empty hashes; simulate it. this.$$url = url.replace(/#$/, ''); // Native pushState serializes & copies the object; simulate it. this.$$state = angular.copy(state); return this; } return this.$$url; }, state: function() { return this.$$state; } }; /** * @ngdoc service * @name $flushPendingTasks * * @description * Flushes all currently pending tasks and executes the corresponding callbacks. * * Optionally, you can also pass a `delay` argument to only flush tasks that are scheduled to be * executed within `delay` milliseconds. Currently, `delay` only applies to timeouts, since all * other tasks have a delay of 0 (i.e. they are scheduled to be executed as soon as possible, but * still asynchronously). * * If no delay is specified, it uses a delay such that all currently pending tasks are flushed. * * The types of tasks that are flushed include: * * - Pending timeouts (via {@link $timeout}). * - Pending tasks scheduled via {@link ng.$rootScope.Scope#$applyAsync $applyAsync}. * - Pending tasks scheduled via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}. * These include tasks scheduled via `$evalAsync()` indirectly (such as {@link $q} promises). * * <div class="alert alert-info"> * Periodic tasks scheduled via {@link $interval} use a different queue and are not flushed by * `$flushPendingTasks()`. Use {@link ngMock.$interval#flush $interval.flush(millis)} instead. * </div> * * @param {number=} delay - The number of milliseconds to flush. */ angular.mock.$FlushPendingTasksProvider = function() { this.$get = [ '$browser', function($browser) { return function $flushPendingTasks(delay) { return $browser.defer.flush(delay); }; } ]; }; /** * @ngdoc service * @name $verifyNoPendingTasks * * @description * Verifies that there are no pending tasks that need to be flushed. It throws an error if there are * still pending tasks. * * You can check for a specific type of tasks only, by specifying a `taskType`. * * Available task types: * * - `$timeout`: Pending timeouts (via {@link $timeout}). * - `$http`: Pending HTTP requests (via {@link $http}). * - `$route`: In-progress route transitions (via {@link $route}). * - `$applyAsync`: Pending tasks scheduled via {@link ng.$rootScope.Scope#$applyAsync $applyAsync}. * - `$evalAsync`: Pending tasks scheduled via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}. * These include tasks scheduled via `$evalAsync()` indirectly (such as {@link $q} promises). * * <div class="alert alert-info"> * Periodic tasks scheduled via {@link $interval} use a different queue and are not taken into * account by `$verifyNoPendingTasks()`. There is currently no way to verify that there are no * pending {@link $interval} tasks. * </div> * * @param {string=} taskType - The type of tasks to check for. */ angular.mock.$VerifyNoPendingTasksProvider = function() { this.$get = [ '$browser', function($browser) { return function $verifyNoPendingTasks(taskType) { return $browser.defer.verifyNoPendingTasks(taskType); }; } ]; }; /** * @ngdoc provider * @name $exceptionHandlerProvider * * @description * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors * passed to the `$exceptionHandler`. */ /** * @ngdoc service * @name $exceptionHandler * * @description * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed * to it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration * information. * * * ```js * describe('$exceptionHandlerProvider', function() { * * it('should capture log messages and exceptions', function() { * * module(function($exceptionHandlerProvider) { * $exceptionHandlerProvider.mode('log'); * }); * * inject(function($log, $exceptionHandler, $timeout) { * $timeout(function() { $log.log(1); }); * $timeout(function() { $log.log(2); throw 'banana peel'; }); * $timeout(function() { $log.log(3); }); * expect($exceptionHandler.errors).toEqual([]); * expect($log.assertEmpty()); * $timeout.flush(); * expect($exceptionHandler.errors).toEqual(['banana peel']); * expect($log.log.logs).toEqual([[1], [2], [3]]); * }); * }); * }); * ``` */ angular.mock.$ExceptionHandlerProvider = function() { var handler; /** * @ngdoc method * @name $exceptionHandlerProvider#mode * * @description * Sets the logging mode. * * @param {string} mode Mode of operation, defaults to `rethrow`. * * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log` * mode stores an array of errors in `$exceptionHandler.errors`, to allow later assertion of * them. See {@link ngMock.$log#assertEmpty assertEmpty()} and * {@link ngMock.$log#reset reset()}. * - `rethrow`: If any errors are passed to the handler in tests, it typically means that there * is a bug in the application or test, so this mock will make these tests fail. For any * implementations that expect exceptions to be thrown, the `rethrow` mode will also maintain * a log of thrown errors in `$exceptionHandler.errors`. */ this.mode = function(mode) { switch (mode) { case 'log': case 'rethrow': var errors = []; handler = function(e) { if (arguments.length === 1) { errors.push(e); } else { errors.push([].slice.call(arguments, 0)); } if (mode === 'rethrow') { throw e; } }; handler.errors = errors; break; default: throw new Error('Unknown mode \'' + mode + '\', only \'log\'/\'rethrow\' modes are allowed!'); } }; this.$get = function() { return handler; }; this.mode('rethrow'); }; /** * @ngdoc service * @name $log * * @description * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays * (one array per logging level). These arrays are exposed as `logs` property of each of the * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`. * */ angular.mock.$LogProvider = function() { var debug = true; function concat(array1, array2, index) { return array1.concat(Array.prototype.slice.call(array2, index)); } this.debugEnabled = function(flag) { if (angular.isDefined(flag)) { debug = flag; return this; } else { return debug; } }; this.$get = function() { var $log = { log: function() { $log.log.logs.push(concat([], arguments, 0)); }, warn: function() { $log.warn.logs.push(concat([], arguments, 0)); }, info: function() { $log.info.logs.push(concat([], arguments, 0)); }, error: function() { $log.error.logs.push(concat([], arguments, 0)); }, debug: function() { if (debug) { $log.debug.logs.push(concat([], arguments, 0)); } } }; /** * @ngdoc method * @name $log#reset * * @description * Reset all of the logging arrays to empty. */ $log.reset = function() { /** * @ngdoc property * @name $log#log.logs * * @description * Array of messages logged using {@link ng.$log#log `log()`}. * * @example * ```js * $log.log('Some Log'); * var first = $log.log.logs.unshift(); * ``` */ $log.log.logs = []; /** * @ngdoc property * @name $log#info.logs * * @description * Array of messages logged using {@link ng.$log#info `info()`}. * * @example * ```js * $log.info('Some Info'); * var first = $log.info.logs.unshift(); * ``` */ $log.info.logs = []; /** * @ngdoc property * @name $log#warn.logs * * @description * Array of messages logged using {@link ng.$log#warn `warn()`}. * * @example * ```js * $log.warn('Some Warning'); * var first = $log.warn.logs.unshift(); * ``` */ $log.warn.logs = []; /** * @ngdoc property * @name $log#error.logs * * @description * Array of messages logged using {@link ng.$log#error `error()`}. * * @example * ```js * $log.error('Some Error'); * var first = $log.error.logs.unshift(); * ``` */ $log.error.logs = []; /** * @ngdoc property * @name $log#debug.logs * * @description * Array of messages logged using {@link ng.$log#debug `debug()`}. * * @example * ```js * $log.debug('Some Error'); * var first = $log.debug.logs.unshift(); * ``` */ $log.debug.logs = []; }; /** * @ngdoc method * @name $log#assertEmpty * * @description * Assert that all of the logging methods have no logged messages. If any messages are present, * an exception is thrown. */ $log.assertEmpty = function() { var errors = []; angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) { angular.forEach($log[logLevel].logs, function(log) { angular.forEach(log, function(logItem) { errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || '')); }); }); }); if (errors.length) { errors.unshift('Expected $log to be empty! Either a message was logged unexpectedly, or ' + 'an expected log message was not checked and removed:'); errors.push(''); throw new Error(errors.join('\n---------\n')); } }; $log.reset(); return $log; }; }; /** * @ngdoc service * @name $interval * * @description * Mock implementation of the $interval service. * * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to * move forward by `millis` milliseconds and trigger any functions scheduled to run in that * time. * * @param {function()} fn A function that should be called repeatedly. * @param {number} delay Number of milliseconds between each function call. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat * indefinitely. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @param {...*=} Pass additional parameters to the executed function. * @returns {promise} A promise which will be notified on each iteration. */ angular.mock.$IntervalProvider = function() { this.$get = ['$browser', '$$intervalFactory', function($browser, $$intervalFactory) { var repeatFns = [], nextRepeatId = 0, now = 0, setIntervalFn = function(tick, delay, deferred, skipApply) { var id = nextRepeatId++; var fn = !skipApply ? tick : function() { tick(); $browser.defer.flush(); }; repeatFns.push({ nextTime: (now + (delay || 0)), delay: delay || 1, fn: fn, id: id, deferred: deferred }); repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime; }); return id; }, clearIntervalFn = function(id) { for (var fnIndex = repeatFns.length - 1; fnIndex >= 0; fnIndex--) { if (repeatFns[fnIndex].id === id) { repeatFns.splice(fnIndex, 1); break; } } }; var $interval = $$intervalFactory(setIntervalFn, clearIntervalFn); /** * @ngdoc method * @name $interval#cancel * * @description * Cancels a task associated with the `promise`. * * @param {promise} promise A promise from calling the `$interval` function. * @returns {boolean} Returns `true` if the task was successfully cancelled. */ $interval.cancel = function(promise) { if (!promise) return false; for (var fnIndex = repeatFns.length - 1; fnIndex >= 0; fnIndex--) { if (repeatFns[fnIndex].id === promise.$$intervalId) { var deferred = repeatFns[fnIndex].deferred; deferred.promise.then(undefined, function() {}); deferred.reject('canceled'); repeatFns.splice(fnIndex, 1); return true; } } return false; }; /** * @ngdoc method * @name $interval#flush * @description * * Runs interval tasks scheduled to be run in the next `millis` milliseconds. * * @param {number} millis maximum timeout amount to flush up until. * * @return {number} The amount of time moved forward. */ $interval.flush = function(millis) { var before = now; now += millis; while (repeatFns.length && repeatFns[0].nextTime <= now) { var task = repeatFns[0]; task.fn(); if (task.nextTime === before) { // this can only happen the first time // a zero-delay interval gets triggered task.nextTime++; } task.nextTime += task.delay; repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;}); } return millis; }; return $interval; }]; }; function jsonStringToDate(string) { // The R_ISO8061_STR regex is never going to fit into the 100 char limit! // eslit-disable-next-line max-len var R_ISO8061_STR = /^(-?\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; var match; if ((match = string.match(R_ISO8061_STR))) { var date = new Date(0), tzHour = 0, tzMin = 0; if (match[9]) { tzHour = toInt(match[9] + match[10]); tzMin = toInt(match[9] + match[11]); } date.setUTCFullYear(toInt(match[1]), toInt(match[2]) - 1, toInt(match[3])); date.setUTCHours(toInt(match[4] || 0) - tzHour, toInt(match[5] || 0) - tzMin, toInt(match[6] || 0), toInt(match[7] || 0)); return date; } return string; } function toInt(str) { return parseInt(str, 10); } function padNumberInMock(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while (num.length < digits) num = '0' + num; if (trim) { num = num.substr(num.length - digits); } return neg + num; } /** * @ngdoc type * @name angular.mock.TzDate * @description * * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`. * * Mock of the Date type which has its timezone specified via constructor arg. * * The main purpose is to create Date-like instances with timezone fixed to the specified timezone * offset, so that we can test code that depends on local timezone settings without dependency on * the time zone settings of the machine where the code is running. * * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored) * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC* * * @example * !!!! WARNING !!!!! * This is not a complete Date object so only methods that were implemented can be called safely. * To make matters worse, TzDate instances inherit stuff from Date via a prototype. * * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is * incomplete we might be missing some non-standard methods. This can result in errors like: * "Date.prototype.foo called on incompatible Object". * * ```js * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z'); * newYearInBratislava.getTimezoneOffset() => -60; * newYearInBratislava.getFullYear() => 2010; * newYearInBratislava.getMonth() => 0; * newYearInBratislava.getDate() => 1; * newYearInBratislava.getHours() => 0; * newYearInBratislava.getMinutes() => 0; * newYearInBratislava.getSeconds() => 0; * ``` * */ angular.mock.TzDate = function(offset, timestamp) { var self = new Date(0); if (angular.isString(timestamp)) { var tsStr = timestamp; self.origDate = jsonStringToDate(timestamp); timestamp = self.origDate.getTime(); if (isNaN(timestamp)) { // eslint-disable-next-line no-throw-literal throw { name: 'Illegal Argument', message: 'Arg \'' + tsStr + '\' passed into TzDate constructor is not a valid date string' }; } } else { self.origDate = new Date(timestamp); } var localOffset = new Date(timestamp).getTimezoneOffset(); self.offsetDiff = localOffset * 60 * 1000 - offset * 1000 * 60 * 60; self.date = new Date(timestamp + self.offsetDiff); self.getTime = function() { return self.date.getTime() - self.offsetDiff; }; self.toLocaleDateString = function() { return self.date.toLocaleDateString(); }; self.getFullYear = function() { return self.date.getFullYear(); }; self.getMonth = function() { return self.date.getMonth(); }; self.getDate = function() { return self.date.getDate(); }; self.getHours = function() { return self.date.getHours(); }; self.getMinutes = function() { return self.date.getMinutes(); }; self.getSeconds = function() { return self.date.getSeconds(); }; self.getMilliseconds = function() { return self.date.getMilliseconds(); }; self.getTimezoneOffset = function() { return offset * 60; }; self.getUTCFullYear = function() { return self.origDate.getUTCFullYear(); }; self.getUTCMonth = function() { return self.origDate.getUTCMonth(); }; self.getUTCDate = function() { return self.origDate.getUTCDate(); }; self.getUTCHours = function() { return self.origDate.getUTCHours(); }; self.getUTCMinutes = function() { return self.origDate.getUTCMinutes(); }; self.getUTCSeconds = function() { return self.origDate.getUTCSeconds(); }; self.getUTCMilliseconds = function() { return self.origDate.getUTCMilliseconds(); }; self.getDay = function() { return self.date.getDay(); }; // provide this method only on browsers that already have it if (self.toISOString) { self.toISOString = function() { return padNumberInMock(self.origDate.getUTCFullYear(), 4) + '-' + padNumberInMock(self.origDate.getUTCMonth() + 1, 2) + '-' + padNumberInMock(self.origDate.getUTCDate(), 2) + 'T' + padNumberInMock(self.origDate.getUTCHours(), 2) + ':' + padNumberInMock(self.origDate.getUTCMinutes(), 2) + ':' + padNumberInMock(self.origDate.getUTCSeconds(), 2) + '.' + padNumberInMock(self.origDate.getUTCMilliseconds(), 3) + 'Z'; }; } //hide all methods not implemented in this mock that the Date prototype exposes var unimplementedMethods = ['getUTCDay', 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString', 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf']; angular.forEach(unimplementedMethods, function(methodName) { self[methodName] = function() { throw new Error('Method \'' + methodName + '\' is not implemented in the TzDate mock'); }; }); return self; }; //make "tzDateInstance instanceof Date" return true angular.mock.TzDate.prototype = Date.prototype; /** * @ngdoc service * @name $animate * * @description * Mock implementation of the {@link ng.$animate `$animate`} service. Exposes two additional methods * for testing animations. * * You need to require the `ngAnimateMock` module in your test suite for instance `beforeEach(module('ngAnimateMock'))` */ angular.mock.animate = angular.module('ngAnimateMock', ['ng']) .info({ angularVersion: '"NG_VERSION_FULL"' }) .config(['$provide', function($provide) { $provide.factory('$$forceReflow', function() { function reflowFn() { reflowFn.totalReflows++; } reflowFn.totalReflows = 0; return reflowFn; }); $provide.factory('$$animateAsyncRun', function() { var queue = []; var queueFn = function() { return function(fn) { queue.push(fn); }; }; queueFn.flush = function() { if (queue.length === 0) return false; for (var i = 0; i < queue.length; i++) { queue[i](); } queue = []; return true; }; return queueFn; }); $provide.decorator('$$animateJs', ['$delegate', function($delegate) { var runners = []; var animateJsConstructor = function() { var animator = $delegate.apply($delegate, arguments); // If no javascript animation is found, animator is undefined if (animator) { runners.push(animator); } return animator; }; animateJsConstructor.$closeAndFlush = function() { runners.forEach(function(runner) { runner.end(); }); runners = []; }; return animateJsConstructor; }]); $provide.decorator('$animateCss', ['$delegate', function($delegate) { var runners = []; var animateCssConstructor = function(element, options) { var animator = $delegate(element, options); runners.push(animator); return animator; }; animateCssConstructor.$closeAndFlush = function() { runners.forEach(function(runner) { runner.end(); }); runners = []; }; return animateCssConstructor; }]); $provide.decorator('$animate', ['$delegate', '$timeout', '$browser', '$$rAF', '$animateCss', '$$animateJs', '$$forceReflow', '$$animateAsyncRun', '$rootScope', function($delegate, $timeout, $browser, $$rAF, $animateCss, $$animateJs, $$forceReflow, $$animateAsyncRun, $rootScope) { var animate = { queue: [], cancel: $delegate.cancel, on: $delegate.on, off: $delegate.off, pin: $delegate.pin, get reflows() { return $$forceReflow.totalReflows; }, enabled: $delegate.enabled, /** * @ngdoc method * @name $animate#closeAndFlush * @description * * This method will close all pending animations (both {@link ngAnimate#javascript-based-animations Javascript} * and {@link ngAnimate.$animateCss CSS}) and it will also flush any remaining animation frames and/or callbacks. */ closeAndFlush: function() { // we allow the flush command to swallow the errors // because depending on whether CSS or JS animations are // used, there may not be a RAF flush. The primary flush // at the end of this function must throw an exception // because it will track if there were pending animations this.flush(true); $animateCss.$closeAndFlush(); $$animateJs.$closeAndFlush(); this.flush(); }, /** * @ngdoc method * @name $animate#flush * @description * * This method is used to flush the pending callbacks and animation frames to either start * an animation or conclude an animation. Note that this will not actually close an * actively running animation (see {@link ngMock.$animate#closeAndFlush `closeAndFlush()`} for that). */ flush: function(hideErrors) { $rootScope.$digest(); var doNextRun, somethingFlushed = false; do { doNextRun = false; if ($$rAF.queue.length) { $$rAF.flush(); doNextRun = somethingFlushed = true; } if ($$animateAsyncRun.flush()) { doNextRun = somethingFlushed = true; } } while (doNextRun); if (!somethingFlushed && !hideErrors) { throw new Error('No pending animations ready to be closed or flushed'); } $rootScope.$digest(); } }; angular.forEach( ['animate','enter','leave','move','addClass','removeClass','setClass'], function(method) { animate[method] = function() { animate.queue.push({ event: method, element: arguments[0], options: arguments[arguments.length - 1], args: arguments }); return $delegate[method].apply($delegate, arguments); }; }); return animate; }]); }]); /** * @ngdoc function * @name angular.mock.dump * @description * * *NOTE*: This is not an injectable instance, just a globally available function. * * Method for serializing common AngularJS objects (scope, elements, etc..) into strings. * It is useful for logging objects to the console when debugging. * * @param {*} object - any object to turn into string. * @return {string} a serialized string of the argument */ angular.mock.dump = function(object) { return serialize(object); function serialize(object) { var out; if (angular.isElement(object)) { object = angular.element(object); out = angular.element('<div></div>'); angular.forEach(object, function(element) { out.append(angular.element(element).clone()); }); out = out.html(); } else if (angular.isArray(object)) { out = []; angular.forEach(object, function(o) { out.push(serialize(o)); }); out = '[ ' + out.join(', ') + ' ]'; } else if (angular.isObject(object)) { if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) { out = serializeScope(object); } else if (object instanceof Error) { out = object.stack || ('' + object.name + ': ' + object.message); } else { // TODO(i): this prevents methods being logged, // we should have a better way to serialize objects out = angular.toJson(object, true); } } else { out = String(object); } return out; } function serializeScope(scope, offset) { offset = offset || ' '; var log = [offset + 'Scope(' + scope.$id + '): {']; for (var key in scope) { if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) { log.push(' ' + key + ': ' + angular.toJson(scope[key])); } } var child = scope.$$childHead; while (child) { log.push(serializeScope(child, offset + ' ')); child = child.$$nextSibling; } log.push('}'); return log.join('\n' + offset); } }; /** * @ngdoc service * @name $httpBackend * @description * Fake HTTP backend implementation suitable for unit testing applications that use the * {@link ng.$http $http service}. * * <div class="alert alert-info"> * **Note**: For fake HTTP backend implementation suitable for end-to-end testing or backend-less * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}. * </div> * * During unit testing, we want our unit tests to run quickly and have no external dependencies so * we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or * [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is * to verify whether a certain request has been sent or not, or alternatively just let the * application make requests, respond with pre-trained responses and assert that the end result is * what we expect it to be. * * This mock implementation can be used to respond with static or dynamic responses via the * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc). * * When an AngularJS application needs some data from a server, it calls the $http service, which * sends the request to a real server using $httpBackend service. With dependency injection, it is * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify * the requests and respond with some testing data without sending a request to a real server. * * There are two ways to specify what test data should be returned as http responses by the mock * backend when the code under test makes http requests: * * - `$httpBackend.expect` - specifies a request expectation * - `$httpBackend.when` - specifies a backend definition * * * ## Request Expectations vs Backend Definitions * * Request expectations provide a way to make assertions about requests made by the application and * to define responses for those requests. The test will fail if the expected requests are not made * or they are made in the wrong order. * * Backend definitions allow you to define a fake backend for your application which doesn't assert * if a particular request was made or not, it just returns a trained response if a request is made. * The test will pass whether or not the request gets made during testing. * * * <table class="table"> * <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr> * <tr> * <th>Syntax</th> * <td>.expect(...).respond(...)</td> * <td>.when(...).respond(...)</td> * </tr> * <tr> * <th>Typical usage</th> * <td>strict unit tests</td> * <td>loose (black-box) unit testing</td> * </tr> * <tr> * <th>Fulfills multiple requests</th> * <td>NO</td> * <td>YES</td> * </tr> * <tr> * <th>Order of requests matters</th> * <td>YES</td> * <td>NO</td> * </tr> * <tr> * <th>Request required</th> * <td>YES</td> * <td>NO</td> * </tr> * <tr> * <th>Response required</th> * <td>optional (see below)</td> * <td>YES</td> * </tr> * </table> * * In cases where both backend definitions and request expectations are specified during unit * testing, the request expectations are evaluated first. * * If a request expectation has no response specified, the algorithm will search your backend * definitions for an appropriate response. * * If a request didn't match any expectation or if the expectation doesn't have the response * defined, the backend definitions are evaluated in sequential order to see if any of them match * the request. The response from the first matched definition is returned. * * * ## Flushing HTTP requests * * The $httpBackend used in production always responds to requests asynchronously. If we preserved * this behavior in unit testing, we'd have to create async unit tests, which are hard to write, * to follow and to maintain. But neither can the testing mock respond synchronously; that would * change the execution of the code under test. For this reason, the mock $httpBackend has a * `flush()` method, which allows the test to explicitly flush pending requests. This preserves * the async api of the backend, while allowing the test to execute synchronously. * * * ## Unit testing with mock $httpBackend * The following code shows how to setup and use the mock backend when unit testing a controller. * First we create the controller under test: * ```js // The module code angular .module('MyApp', []) .controller('MyController', MyController); // The controller code function MyController($scope, $http) { var authToken; $http.get('/auth.py').then(function(response) { authToken = response.headers('A-Token'); $scope.user = response.data; }).catch(function() { $scope.status = 'Failed...'; }); $scope.saveMessage = function(message) { var headers = { 'Authorization': authToken }; $scope.status = 'Saving...'; $http.post('/add-msg.py', message, { headers: headers } ).then(function(response) { $scope.status = ''; }).catch(function() { $scope.status = 'Failed...'; }); }; } ``` * * Now we setup the mock backend and create the test specs: * ```js // testing controller describe('MyController', function() { var $httpBackend, $rootScope, createController, authRequestHandler; // Set up the module beforeEach(module('MyApp')); beforeEach(inject(function($injector) { // Set up the mock http service responses $httpBackend = $injector.get('$httpBackend'); // backend definition common for all tests authRequestHandler = $httpBackend.when('GET', '/auth.py') .respond({userId: 'userX'}, {'A-Token': 'xxx'}); // Get hold of a scope (i.e. the root scope) $rootScope = $injector.get('$rootScope'); // The $controller service is used to create instances of controllers var $controller = $injector.get('$controller'); createController = function() { return $controller('MyController', {'$scope' : $rootScope }); }; })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it('should fetch authentication token', function() { $httpBackend.expectGET('/auth.py'); var controller = createController(); $httpBackend.flush(); }); it('should fail authentication', function() { // Notice how you can change the response even after it was set authRequestHandler.respond(401, ''); $httpBackend.expectGET('/auth.py'); var controller = createController(); $httpBackend.flush(); expect($rootScope.status).toBe('Failed...'); }); it('should send msg to server', function() { var controller = createController(); $httpBackend.flush(); // now you don’t care about the authentication, but // the controller will still send the request and // $httpBackend will respond without you having to // specify the expectation and response for this request $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, ''); $rootScope.saveMessage('message content'); expect($rootScope.status).toBe('Saving...'); $httpBackend.flush(); expect($rootScope.status).toBe(''); }); it('should send auth header', function() { var controller = createController(); $httpBackend.flush(); $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) { // check if the header was sent, if it wasn't the expectation won't // match the request and the test will fail return headers['Authorization'] === 'xxx'; }).respond(201, ''); $rootScope.saveMessage('whatever'); $httpBackend.flush(); }); }); ``` * * ## Dynamic responses * * You define a response to a request by chaining a call to `respond()` onto a definition or expectation. * If you provide a **callback** as the first parameter to `respond(callback)` then you can dynamically generate * a response based on the properties of the request. * * The `callback` function should be of the form `function(method, url, data, headers, params)`. * * ### Query parameters * * By default, query parameters on request URLs are parsed into the `params` object. So a request URL * of `/list?q=searchstr&orderby=-name` would set `params` to be `{q: 'searchstr', orderby: '-name'}`. * * ### Regex parameter matching * * If an expectation or definition uses a **regex** to match the URL, you can provide an array of **keys** via a * `params` argument. The index of each **key** in the array will match the index of a **group** in the * **regex**. * * The `params` object in the **callback** will now have properties with these keys, which hold the value of the * corresponding **group** in the **regex**. * * This also applies to the `when` and `expect` shortcut methods. * * * ```js * $httpBackend.expect('GET', /\/user\/(.+)/, undefined, undefined, ['id']) * .respond(function(method, url, data, headers, params) { * // for requested url of '/user/1234' params is {id: '1234'} * }); * * $httpBackend.whenPATCH(/\/user\/(.+)\/article\/(.+)/, undefined, undefined, ['user', 'article']) * .respond(function(method, url, data, headers, params) { * // for url of '/user/1234/article/567' params is {user: '1234', article: '567'} * }); * ``` * * ## Matching route requests * * For extra convenience, `whenRoute` and `expectRoute` shortcuts are available. These methods offer colon * delimited matching of the url path, ignoring the query string and trailing slashes. This allows declarations * similar to how application routes are configured with `$routeProvider`. Because these methods convert * the definition url to regex, declaration order is important. Combined with query parameter parsing, * the following is possible: * ```js $httpBackend.whenRoute('GET', '/users/:id') .respond(function(method, url, data, headers, params) { return [200, MockUserList[Number(params.id)]]; }); $httpBackend.whenRoute('GET', '/users') .respond(function(method, url, data, headers, params) { var userList = angular.copy(MockUserList), defaultSort = 'lastName', count, pages, isPrevious, isNext; // paged api response '/v1/users?page=2' params.page = Number(params.page) || 1; // query for last names '/v1/users?q=Archer' if (params.q) { userList = $filter('filter')({lastName: params.q}); } pages = Math.ceil(userList.length / pagingLength); isPrevious = params.page > 1; isNext = params.page < pages; return [200, { count: userList.length, previous: isPrevious, next: isNext, // sort field -> '/v1/users?sortBy=firstName' results: $filter('orderBy')(userList, params.sortBy || defaultSort) .splice((params.page - 1) * pagingLength, pagingLength) }]; }); ``` */ angular.mock.$httpBackendDecorator = ['$rootScope', '$timeout', '$delegate', createHttpBackendMock]; /** * General factory function for $httpBackend mock. * Returns instance for unit testing (when no arguments specified): * - passing through is disabled * - auto flushing is disabled * * Returns instance for e2e testing (when `$delegate` and `$browser` specified): * - passing through (delegating request to real backend) is enabled * - auto flushing is enabled * * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified) * @param {Object=} $browser Auto-flushing enabled if specified * @return {Object} Instance of $httpBackend mock */ function createHttpBackendMock($rootScope, $timeout, $delegate, $browser) { var definitions = [], expectations = [], matchLatestDefinition = false, responses = [], responsesPush = angular.bind(responses, responses.push), copy = angular.copy, // We cache the original backend so that if both ngMock and ngMockE2E override the // service the ngMockE2E version can pass through to the real backend originalHttpBackend = $delegate.$$originalHttpBackend || $delegate; function createResponse(status, data, headers, statusText) { if (angular.isFunction(status)) return status; return function() { return angular.isNumber(status) ? [status, data, headers, statusText, 'complete'] : [200, status, data, headers, 'complete']; }; } // TODO(vojta): change params to: method, url, data, headers, callback function $httpBackend(method, url, data, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) { var xhr = new MockXhr(), expectation = expectations[0], wasExpected = false; xhr.$$events = eventHandlers; xhr.upload.$$events = uploadEventHandlers; function prettyPrint(data) { return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp) ? data : angular.toJson(data); } function wrapResponse(wrapped) { if (!$browser && timeout) { if (timeout.then) { timeout.then(function() { handlePrematureEnd(angular.isDefined(timeout.$$timeoutId) ? 'timeout' : 'abort'); }); } else { $timeout(function() { handlePrematureEnd('timeout'); }, timeout); } } handleResponse.description = method + ' ' + url; return handleResponse; function handleResponse() { var response = wrapped.response(method, url, data, headers, wrapped.params(url)); xhr.$$respHeaders = response[2]; callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(), copy(response[3] || ''), copy(response[4])); } function handlePrematureEnd(reason) { for (var i = 0, ii = responses.length; i < ii; i++) { if (responses[i] === handleResponse) { responses.splice(i, 1); callback(-1, undefined, '', undefined, reason); break; } } } } function createFatalError(message) { var error = new Error(message); // In addition to being converted to a rejection, these errors also need to be passed to // the $exceptionHandler and be rethrown (so that the test fails). error.$$passToExceptionHandler = true; return error; } if (expectation && expectation.match(method, url)) { if (!expectation.matchData(data)) { throw createFatalError('Expected ' + expectation + ' with different data\n' + 'EXPECTED: ' + prettyPrint(expectation.data) + '\n' + 'GOT: ' + data); } if (!expectation.matchHeaders(headers)) { throw createFatalError('Expected ' + expectation + ' with different headers\n' + 'EXPECTED: ' + prettyPrint(expectation.headers) + '\n' + 'GOT: ' + prettyPrint(headers)); } expectations.shift(); if (expectation.response) { responses.push(wrapResponse(expectation)); return; } wasExpected = true; } var i = matchLatestDefinition ? definitions.length : -1, definition; while ((definition = definitions[matchLatestDefinition ? --i : ++i])) { if (definition.match(method, url, data, headers || {})) { if (definition.response) { // if $browser specified, we do auto flush all requests ($browser ? $browser.defer : responsesPush)(wrapResponse(definition)); } else if (definition.passThrough) { originalHttpBackend(method, url, data, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers); } else throw createFatalError('No response defined !'); return; } } if (wasExpected) { throw createFatalError('No response defined !'); } throw createFatalError('Unexpected request: ' + method + ' ' + url + '\n' + (expectation ? 'Expected ' + expectation : 'No more request expected')); } /** * @ngdoc method * @name $httpBackend#when * @description * Creates a new backend definition. * * @param {string} method HTTP method. * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. * * - respond – * ```js * {function([status,] data[, headers, statusText]) * | function(function(method, url, data, headers, params)} * ``` * – The respond method takes a set of static data to be returned or a function that can * return an array containing response status (number), response data (Array|Object|string), * response headers (Object), HTTP status text (string), and XMLHttpRequest status (string: * `complete`, `error`, `timeout` or `abort`). The respond method returns the `requestHandler` * object for possible overrides. */ $httpBackend.when = function(method, url, data, headers, keys) { assertArgDefined(arguments, 1, 'url'); var definition = new MockHttpExpectation(method, url, data, headers, keys), chain = { respond: function(status, data, headers, statusText) { definition.passThrough = undefined; definition.response = createResponse(status, data, headers, statusText); return chain; } }; if ($browser) { chain.passThrough = function() { definition.response = undefined; definition.passThrough = true; return chain; }; } definitions.push(definition); return chain; }; /** * @ngdoc method * @name $httpBackend#matchLatestDefinition * @description * This method can be used to change which mocked responses `$httpBackend` returns, when defining * them with {@link ngMock.$httpBackend#when $httpBackend.when()} (and shortcut methods). * By default, `$httpBackend` returns the first definition that matches. When setting * `$http.matchLatestDefinition(true)`, it will use the last response that matches, i.e. the * one that was added last. * * ```js * hb.when('GET', '/url1').respond(200, 'content', {}); * hb.when('GET', '/url1').respond(201, 'another', {}); * hb('GET', '/url1'); // receives "content" * * $http.matchLatestDefinition(true) * hb('GET', '/url1'); // receives "another" * * hb.when('GET', '/url1').respond(201, 'onemore', {}); * hb('GET', '/url1'); // receives "onemore" * ``` * * This is useful if a you have a default response that is overriden inside specific tests. * * Note that different from config methods on providers, `matchLatestDefinition()` can be changed * even when the application is already running. * * @param {Boolean=} value value to set, either `true` or `false`. Default is `false`. * If omitted, it will return the current value. * @return {$httpBackend|Boolean} self when used as a setter, and the current value when used * as a getter */ $httpBackend.matchLatestDefinitionEnabled = function(value) { if (isDefined(value)) { matchLatestDefinition = value; return this; } else { return matchLatestDefinition; } }; /** * @ngdoc method * @name $httpBackend#whenGET * @description * Creates a new backend definition for GET requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenHEAD * @description * Creates a new backend definition for HEAD requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenDELETE * @description * Creates a new backend definition for DELETE requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPOST * @description * Creates a new backend definition for POST requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPUT * @description * Creates a new backend definition for PUT requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenJSONP * @description * Creates a new backend definition for JSONP requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ createShortMethods('when'); /** * @ngdoc method * @name $httpBackend#whenRoute * @description * Creates a new backend definition that compares only with the requested route. * * @param {string} method HTTP method. * @param {string} url HTTP url string that supports colon param matching. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. * See {@link ngMock.$httpBackend#when `when`} for more info. */ $httpBackend.whenRoute = function(method, url) { var pathObj = routeToRegExp(url, {caseInsensitiveMatch: true, ignoreTrailingSlashes: true}); return $httpBackend.when(method, pathObj.regexp, undefined, undefined, pathObj.keys); }; /** * @ngdoc method * @name $httpBackend#expect * @description * Creates a new request expectation. * * @param {string} method HTTP method. * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current expectation. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. * * - respond – * ```js * {function([status,] data[, headers, statusText]) * | function(function(method, url, data, headers, params)} * ``` * – The respond method takes a set of static data to be returned or a function that can * return an array containing response status (number), response data (Array|Object|string), * response headers (Object), HTTP status text (string), and XMLHttpRequest status (string: * `complete`, `error`, `timeout` or `abort`). The respond method returns the `requestHandler` * object for possible overrides. */ $httpBackend.expect = function(method, url, data, headers, keys) { assertArgDefined(arguments, 1, 'url'); var expectation = new MockHttpExpectation(method, url, data, headers, keys), chain = { respond: function(status, data, headers, statusText) { expectation.response = createResponse(status, data, headers, statusText); return chain; } }; expectations.push(expectation); return chain; }; /** * @ngdoc method * @name $httpBackend#expectGET * @description * Creates a new request expectation for GET requests. For more info see `expect()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current expectation. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current expectation. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. See #expect for more info. */ /** * @ngdoc method * @name $httpBackend#expectHEAD * @description * Creates a new request expectation for HEAD requests. For more info see `expect()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current expectation. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current expectation. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectDELETE * @description * Creates a new request expectation for DELETE requests. For more info see `expect()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current expectation. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current expectation. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectPOST * @description * Creates a new request expectation for POST requests. For more info see `expect()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current expectation. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current expectation. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectPUT * @description * Creates a new request expectation for PUT requests. For more info see `expect()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current expectation. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current expectation. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectPATCH * @description * Creates a new request expectation for PATCH requests. For more info see `expect()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current expectation. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current expectation. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectJSONP * @description * Creates a new request expectation for JSONP requests. For more info see `expect()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives an url * and returns true if the url matches the current expectation. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ createShortMethods('expect'); /** * @ngdoc method * @name $httpBackend#expectRoute * @description * Creates a new request expectation that compares only with the requested route. * * @param {string} method HTTP method. * @param {string} url HTTP url string that supports colon param matching. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. * See {@link ngMock.$httpBackend#expect `expect`} for more info. */ $httpBackend.expectRoute = function(method, url) { var pathObj = routeToRegExp(url, {caseInsensitiveMatch: true, ignoreTrailingSlashes: true}); return $httpBackend.expect(method, pathObj.regexp, undefined, undefined, pathObj.keys); }; /** * @ngdoc method * @name $httpBackend#flush * @description * Flushes pending requests using the trained responses. Requests are flushed in the order they * were made, but it is also possible to skip one or more requests (for example to have them * flushed later). This is useful for simulating scenarios where responses arrive from the server * in any order. * * If there are no pending requests to flush when the method is called, an exception is thrown (as * this is typically a sign of programming error). * * @param {number=} count - Number of responses to flush. If undefined/null, all pending requests * (starting after `skip`) will be flushed. * @param {number=} [skip=0] - Number of pending requests to skip. For example, a value of `5` * would skip the first 5 pending requests and start flushing from the 6th onwards. */ $httpBackend.flush = function(count, skip, digest) { if (digest !== false) $rootScope.$digest(); skip = skip || 0; if (skip >= responses.length) throw new Error('No pending request to flush !'); if (angular.isDefined(count) && count !== null) { while (count--) { var part = responses.splice(skip, 1); if (!part.length) throw new Error('No more pending request to flush !'); part[0](); } } else { while (responses.length > skip) { responses.splice(skip, 1)[0](); } } $httpBackend.verifyNoOutstandingExpectation(digest); }; /** * @ngdoc method * @name $httpBackend#verifyNoOutstandingExpectation * @description * Verifies that all of the requests defined via the `expect` api were made. If any of the * requests were not made, verifyNoOutstandingExpectation throws an exception. * * Typically, you would call this method following each test case that asserts requests using an * "afterEach" clause. * * ```js * afterEach($httpBackend.verifyNoOutstandingExpectation); * ``` */ $httpBackend.verifyNoOutstandingExpectation = function(digest) { if (digest !== false) $rootScope.$digest(); if (expectations.length) { throw new Error('Unsatisfied requests: ' + expectations.join(', ')); } }; /** * @ngdoc method * @name $httpBackend#verifyNoOutstandingRequest * @description * Verifies that there are no outstanding requests that need to be flushed. * * Typically, you would call this method following each test case that asserts requests using an * "afterEach" clause. * * ```js * afterEach($httpBackend.verifyNoOutstandingRequest); * ``` */ $httpBackend.verifyNoOutstandingRequest = function(digest) { if (digest !== false) $rootScope.$digest(); if (responses.length) { var unflushedDescriptions = responses.map(function(res) { return res.description; }); throw new Error('Unflushed requests: ' + responses.length + '\n ' + unflushedDescriptions.join('\n ')); } }; /** * @ngdoc method * @name $httpBackend#resetExpectations * @description * Resets all request expectations, but preserves all backend definitions. Typically, you would * call resetExpectations during a multiple-phase test when you want to reuse the same instance of * $httpBackend mock. */ $httpBackend.resetExpectations = function() { expectations.length = 0; responses.length = 0; }; $httpBackend.$$originalHttpBackend = originalHttpBackend; return $httpBackend; function createShortMethods(prefix) { angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) { $httpBackend[prefix + method] = function(url, headers, keys) { assertArgDefined(arguments, 0, 'url'); // Change url to `null` if `undefined` to stop it throwing an exception further down if (angular.isUndefined(url)) url = null; return $httpBackend[prefix](method, url, undefined, headers, keys); }; }); angular.forEach(['PUT', 'POST', 'PATCH'], function(method) { $httpBackend[prefix + method] = function(url, data, headers, keys) { assertArgDefined(arguments, 0, 'url'); // Change url to `null` if `undefined` to stop it throwing an exception further down if (angular.isUndefined(url)) url = null; return $httpBackend[prefix](method, url, data, headers, keys); }; }); } } function assertArgDefined(args, index, name) { if (args.length > index && angular.isUndefined(args[index])) { throw new Error('Undefined argument `' + name + '`; the argument is provided but not defined'); } } function MockHttpExpectation(method, url, data, headers, keys) { function getUrlParams(u) { var params = u.slice(u.indexOf('?') + 1).split('&'); return params.sort(); } function compareUrl(u) { return (url.slice(0, url.indexOf('?')) === u.slice(0, u.indexOf('?')) && getUrlParams(url).join() === getUrlParams(u).join()); } this.data = data; this.headers = headers; this.match = function(m, u, d, h) { if (method !== m) return false; if (!this.matchUrl(u)) return false; if (angular.isDefined(d) && !this.matchData(d)) return false; if (angular.isDefined(h) && !this.matchHeaders(h)) return false; return true; }; this.matchUrl = function(u) { if (!url) return true; if (angular.isFunction(url.test)) return url.test(u); if (angular.isFunction(url)) return url(u); return (url === u || compareUrl(u)); }; this.matchHeaders = function(h) { if (angular.isUndefined(headers)) return true; if (angular.isFunction(headers)) return headers(h); return angular.equals(headers, h); }; this.matchData = function(d) { if (angular.isUndefined(data)) return true; if (data && angular.isFunction(data.test)) return data.test(d); if (data && angular.isFunction(data)) return data(d); if (data && !angular.isString(data)) { return angular.equals(angular.fromJson(angular.toJson(data)), angular.fromJson(d)); } // eslint-disable-next-line eqeqeq return data == d; }; this.toString = function() { return method + ' ' + url; }; this.params = function(u) { return angular.extend(parseQuery(), pathParams()); function pathParams() { var keyObj = {}; if (!url || !angular.isFunction(url.test) || !keys || keys.length === 0) return keyObj; var m = url.exec(u); if (!m) return keyObj; for (var i = 1, len = m.length; i < len; ++i) { var key = keys[i - 1]; var val = m[i]; if (key && val) { keyObj[key.name || key] = val; } } return keyObj; } function parseQuery() { var obj = {}, key_value, key, queryStr = u.indexOf('?') > -1 ? u.substring(u.indexOf('?') + 1) : ''; angular.forEach(queryStr.split('&'), function(keyValue) { if (keyValue) { key_value = keyValue.replace(/\+/g,'%20').split('='); key = tryDecodeURIComponent(key_value[0]); if (angular.isDefined(key)) { var val = angular.isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; if (!hasOwnProperty.call(obj, key)) { obj[key] = val; } else if (angular.isArray(obj[key])) { obj[key].push(val); } else { obj[key] = [obj[key],val]; } } } }); return obj; } function tryDecodeURIComponent(value) { try { return decodeURIComponent(value); } catch (e) { // Ignore any invalid uri component } } }; } function createMockXhr() { return new MockXhr(); } function MockXhr() { // hack for testing $http, $httpBackend MockXhr.$$lastInstance = this; this.open = function(method, url, async) { this.$$method = method; this.$$url = url; this.$$async = async; this.$$reqHeaders = {}; this.$$respHeaders = {}; }; this.send = function(data) { this.$$data = data; }; this.setRequestHeader = function(key, value) { this.$$reqHeaders[key] = value; }; this.getResponseHeader = function(name) { // the lookup must be case insensitive, // that's why we try two quick lookups first and full scan last var header = this.$$respHeaders[name]; if (header) return header; name = angular.$$lowercase(name); header = this.$$respHeaders[name]; if (header) return header; header = undefined; angular.forEach(this.$$respHeaders, function(headerVal, headerName) { if (!header && angular.$$lowercase(headerName) === name) header = headerVal; }); return header; }; this.getAllResponseHeaders = function() { var lines = []; angular.forEach(this.$$respHeaders, function(value, key) { lines.push(key + ': ' + value); }); return lines.join('\n'); }; this.abort = function() { if (isFunction(this.onabort)) { this.onabort(); } }; // This section simulates the events on a real XHR object (and the upload object) // When we are testing $httpBackend (inside the AngularJS project) we make partial use of this // but store the events directly ourselves on `$$events`, instead of going through the `addEventListener` this.$$events = {}; this.addEventListener = function(name, listener) { if (angular.isUndefined(this.$$events[name])) this.$$events[name] = []; this.$$events[name].push(listener); }; this.upload = { $$events: {}, addEventListener: this.addEventListener }; } /** * @ngdoc service * @name $timeout * @description * * This service is just a simple decorator for {@link ng.$timeout $timeout} service * that adds a "flush" and "verifyNoPendingTasks" methods. */ angular.mock.$TimeoutDecorator = ['$delegate', '$browser', function($delegate, $browser) { /** * @ngdoc method * @name $timeout#flush * * @deprecated * sinceVersion="1.7.3" * * This method flushes all types of tasks (not only timeouts), which is unintuitive. * It is recommended to use {@link ngMock.$flushPendingTasks} instead. * * @description * * Flushes the queue of pending tasks. * * _This method is essentially an alias of {@link ngMock.$flushPendingTasks}._ * * <div class="alert alert-warning"> * For historical reasons, this method will also flush non-`$timeout` pending tasks, such as * {@link $q} promises and tasks scheduled via * {@link ng.$rootScope.Scope#$applyAsync $applyAsync} and * {@link ng.$rootScope.Scope#$evalAsync $evalAsync}. * </div> * * @param {number=} delay maximum timeout amount to flush up until */ $delegate.flush = function(delay) { // For historical reasons, `$timeout.flush()` flushes all types of pending tasks. // Keep the same behavior for backwards compatibility (and because it doesn't make sense to // selectively flush scheduled events out of order). $browser.defer.flush(delay); }; /** * @ngdoc method * @name $timeout#verifyNoPendingTasks * * @deprecated * sinceVersion="1.7.3" * * This method takes all types of tasks (not only timeouts) into account, which is unintuitive. * It is recommended to use {@link ngMock.$verifyNoPendingTasks} instead, which additionally * allows checking for timeouts only (with `$verifyNoPendingTasks('$timeout')`). * * @description * * Verifies that there are no pending tasks that need to be flushed. It throws an error if there * are still pending tasks. * * _This method is essentially an alias of {@link ngMock.$verifyNoPendingTasks} (called with no * arguments)._ * * <div class="alert alert-warning"> * <p> * For historical reasons, this method will also verify non-`$timeout` pending tasks, such as * pending {@link $http} requests, in-progress {@link $route} transitions, unresolved * {@link $q} promises and tasks scheduled via * {@link ng.$rootScope.Scope#$applyAsync $applyAsync} and * {@link ng.$rootScope.Scope#$evalAsync $evalAsync}. * </p> * <p> * It is recommended to use {@link ngMock.$verifyNoPendingTasks} instead, which additionally * supports verifying a specific type of tasks. For example, you can verify there are no * pending timeouts with `$verifyNoPendingTasks('$timeout')`. * </p> * </div> */ $delegate.verifyNoPendingTasks = function() { // For historical reasons, `$timeout.verifyNoPendingTasks()` takes all types of pending tasks // into account. Keep the same behavior for backwards compatibility. var pendingTasks = $browser.defer.getPendingTasks(); if (pendingTasks.length) { var formattedTasks = $browser.defer.formatPendingTasks(pendingTasks).join('\n '); var hasPendingTimeout = pendingTasks.some(function(task) { return task.type === '$timeout'; }); var extraMessage = hasPendingTimeout ? '' : '\n\nNone of the pending tasks are timeouts. ' + 'If you only want to verify pending timeouts, use ' + '`$verifyNoPendingTasks(\'$timeout\')` instead.'; throw new Error('Deferred tasks to flush (' + pendingTasks.length + '):\n ' + formattedTasks + extraMessage); } }; return $delegate; }]; angular.mock.$RAFDecorator = ['$delegate', function($delegate) { var rafFn = function(fn) { var index = rafFn.queue.length; rafFn.queue.push(fn); return function() { rafFn.queue.splice(index, 1); }; }; rafFn.queue = []; rafFn.supported = $delegate.supported; rafFn.flush = function() { if (rafFn.queue.length === 0) { throw new Error('No rAF callbacks present'); } var length = rafFn.queue.length; for (var i = 0; i < length; i++) { rafFn.queue[i](); } rafFn.queue = rafFn.queue.slice(i); }; return rafFn; }]; /** * */ var originalRootElement; angular.mock.$RootElementProvider = function() { this.$get = ['$injector', function($injector) { originalRootElement = angular.element('<div ng-app></div>').data('$injector', $injector); return originalRootElement; }]; }; /** * @ngdoc service * @name $controller * @description * A decorator for {@link ng.$controller} with additional `bindings` parameter, useful when testing * controllers of directives that use {@link $compile#-bindtocontroller- `bindToController`}. * * ## Example * * ```js * * // Directive definition ... * * myMod.directive('myDirective', { * controller: 'MyDirectiveController', * bindToController: { * name: '@' * } * }); * * * // Controller definition ... * * myMod.controller('MyDirectiveController', ['$log', function($log) { * this.log = function() { * $log.info(this.name); * }; * }]); * * * // In a test ... * * describe('myDirectiveController', function() { * describe('log()', function() { * it('should write the bound name to the log', inject(function($controller, $log) { * var ctrl = $controller('MyDirectiveController', { /* no locals &#42;/ }, { name: 'Clark Kent' }); * ctrl.log(); * * expect(ctrl.name).toEqual('Clark Kent'); * expect($log.info.logs).toEqual(['Clark Kent']); * })); * }); * }); * * ``` * * @param {Function|string} constructor If called with a function then it's considered to be the * controller constructor function. Otherwise it's considered to be a string which is used * to retrieve the controller constructor using the following steps: * * * check if a controller with given name is registered via `$controllerProvider` * * check if evaluating the string on the current scope returns a constructor * * The string can use the `controller as property` syntax, where the controller instance is published * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this * to work correctly. * * @param {Object} locals Injection locals for Controller. * @param {Object=} bindings Properties to add to the controller instance. This is used to simulate * the `bindToController` feature and simplify certain kinds of tests. * @return {Object} Instance of given controller. */ function createControllerDecorator() { angular.mock.$ControllerDecorator = ['$delegate', function($delegate) { return function(expression, locals, later, ident) { if (later && typeof later === 'object') { var instantiate = $delegate(expression, locals, true, ident); var instance = instantiate(); angular.extend(instance, later); return instance; } return $delegate(expression, locals, later, ident); }; }]; return angular.mock.$ControllerDecorator; } /** * @ngdoc service * @name $componentController * @description * A service that can be used to create instances of component controllers. Useful for unit-testing. * * Be aware that the controller will be instantiated and attached to the scope as specified in * the component definition object. If you do not provide a `$scope` object in the `locals` param * then the helper will create a new isolated scope as a child of `$rootScope`. * * If you are using `$element` or `$attrs` in the controller, make sure to provide them as `locals`. * The `$element` must be a jqLite-wrapped DOM element, and `$attrs` should be an object that * has all properties / functions that you are using in the controller. If this is getting too complex, * you should compile the component instead and access the component's controller via the * {@link angular.element#methods `controller`} function. * * See also the section on {@link guide/component#unit-testing-component-controllers unit-testing component controllers} * in the guide. * * @param {string} componentName the name of the component whose controller we want to instantiate * @param {Object} locals Injection locals for Controller. * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used * to simulate the `bindToController` feature and simplify certain kinds of tests. * @param {string=} ident Override the property name to use when attaching the controller to the scope. * @return {Object} Instance of requested controller. */ angular.mock.$ComponentControllerProvider = ['$compileProvider', function ComponentControllerProvider($compileProvider) { this.$get = ['$controller','$injector', '$rootScope', function($controller, $injector, $rootScope) { return function $componentController(componentName, locals, bindings, ident) { // get all directives associated to the component name var directives = $injector.get(componentName + 'Directive'); // look for those directives that are components var candidateDirectives = directives.filter(function(directiveInfo) { // components have controller, controllerAs and restrict:'E' return directiveInfo.controller && directiveInfo.controllerAs && directiveInfo.restrict === 'E'; }); // check if valid directives found if (candidateDirectives.length === 0) { throw new Error('No component found'); } if (candidateDirectives.length > 1) { throw new Error('Too many components found'); } // get the info of the component var directiveInfo = candidateDirectives[0]; // create a scope if needed locals = locals || {}; locals.$scope = locals.$scope || $rootScope.$new(true); return $controller(directiveInfo.controller, locals, bindings, ident || directiveInfo.controllerAs); }; }]; }]; /** * @ngdoc module * @name ngMock * @packageName angular-mocks * @description * * The `ngMock` module provides support to inject and mock AngularJS services into unit tests. * In addition, ngMock also extends various core AngularJS services such that they can be * inspected and controlled in a synchronous manner within test code. * * @installation * * First, download the file: * * [Google CDN](https://developers.google.com/speed/libraries/devguide#angularjs) e.g. * `"//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-mocks.js"` * * [NPM](https://www.npmjs.com/) e.g. `npm install angular-mocks@X.Y.Z` * * [Yarn](https://yarnpkg.com) e.g. `yarn add angular-mocks@X.Y.Z` * * [Bower](http://bower.io) e.g. `bower install angular-mocks#X.Y.Z` * * [code.angularjs.org](https://code.angularjs.org/) (discouraged for production use) e.g. * `"//code.angularjs.org/X.Y.Z/angular-mocks.js"` * * where X.Y.Z is the AngularJS version you are running. * * Then, configure your test runner to load `angular-mocks.js` after `angular.js`. * This example uses <a href="http://karma-runner.github.io/">Karma</a>: * * ``` * config.set({ * files: [ * 'build/angular.js', // and other module files you need * 'build/angular-mocks.js', * '<path/to/application/files>', * '<path/to/spec/files>' * ] * }); * ``` * * Including the `angular-mocks.js` file automatically adds the `ngMock` module, so your tests * are ready to go! */ angular.module('ngMock', ['ng']).provider({ $browser: angular.mock.$BrowserProvider, $exceptionHandler: angular.mock.$ExceptionHandlerProvider, $log: angular.mock.$LogProvider, $interval: angular.mock.$IntervalProvider, $rootElement: angular.mock.$RootElementProvider, $componentController: angular.mock.$ComponentControllerProvider, $flushPendingTasks: angular.mock.$FlushPendingTasksProvider, $verifyNoPendingTasks: angular.mock.$VerifyNoPendingTasksProvider }).config(['$provide', '$compileProvider', function($provide, $compileProvider) { $provide.decorator('$timeout', angular.mock.$TimeoutDecorator); $provide.decorator('$$rAF', angular.mock.$RAFDecorator); $provide.decorator('$rootScope', angular.mock.$RootScopeDecorator); $provide.decorator('$controller', createControllerDecorator($compileProvider)); $provide.decorator('$httpBackend', angular.mock.$httpBackendDecorator); }]).info({ angularVersion: '"NG_VERSION_FULL"' }); /** * @ngdoc module * @name ngMockE2E * @module ngMockE2E * @packageName angular-mocks * @description * * The `ngMockE2E` is an AngularJS module which contains mocks suitable for end-to-end testing. * Currently there is only one mock present in this module - * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock. */ angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) { $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator); }]).info({ angularVersion: '"NG_VERSION_FULL"' }); /** * @ngdoc service * @name $httpBackend * @module ngMockE2E * @description * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of * applications that use the {@link ng.$http $http service}. * * <div class="alert alert-info"> * **Note**: For fake http backend implementation suitable for unit testing please see * {@link ngMock.$httpBackend unit-testing $httpBackend mock}. * </div> * * This implementation can be used to respond with static or dynamic responses via the `when` api * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch * templates from a webserver). * * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application * is being developed with the real backend api replaced with a mock, it is often desirable for * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch * templates or static files from the webserver). To configure the backend with this behavior * use the `passThrough` request handler of `when` instead of `respond`. * * Additionally, we don't want to manually have to flush mocked out requests like we do during unit * testing. For this reason the e2e $httpBackend flushes mocked out requests * automatically, closely simulating the behavior of the XMLHttpRequest object. * * To setup the application to run with this http backend, you have to create a module that depends * on the `ngMockE2E` and your application modules and defines the fake backend: * * ```js * var myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']); * myAppDev.run(function($httpBackend) { * var phones = [{name: 'phone1'}, {name: 'phone2'}]; * * // returns the current list of phones * $httpBackend.whenGET('/phones').respond(phones); * * // adds a new phone to the phones array * $httpBackend.whenPOST('/phones').respond(function(method, url, data) { * var phone = angular.fromJson(data); * phones.push(phone); * return [200, phone, {}]; * }); * $httpBackend.whenGET(/^\/templates\//).passThrough(); // Requests for templates are handled by the real server * //... * }); * ``` * * Afterwards, bootstrap your app with this new module. * * @example * <example name="httpbackend-e2e-testing" module="myAppE2E" deps="angular-mocks.js"> * <file name="app.js"> * var myApp = angular.module('myApp', []); * * myApp.controller('MainCtrl', function MainCtrl($http) { * var ctrl = this; * * ctrl.phones = []; * ctrl.newPhone = { * name: '' * }; * * ctrl.getPhones = function() { * $http.get('/phones').then(function(response) { * ctrl.phones = response.data; * }); * }; * * ctrl.addPhone = function(phone) { * $http.post('/phones', phone).then(function() { * ctrl.newPhone = {name: ''}; * return ctrl.getPhones(); * }); * }; * * ctrl.getPhones(); * }); * </file> * <file name="e2e.js"> * var myAppDev = angular.module('myAppE2E', ['myApp', 'ngMockE2E']); * * myAppDev.run(function($httpBackend) { * var phones = [{name: 'phone1'}, {name: 'phone2'}]; * * // returns the current list of phones * $httpBackend.whenGET('/phones').respond(phones); * * // adds a new phone to the phones array * $httpBackend.whenPOST('/phones').respond(function(method, url, data) { * var phone = angular.fromJson(data); * phones.push(phone); * return [200, phone, {}]; * }); * }); * </file> * <file name="index.html"> * <div ng-controller="MainCtrl as $ctrl"> * <form name="newPhoneForm" ng-submit="$ctrl.addPhone($ctrl.newPhone)"> * <input type="text" ng-model="$ctrl.newPhone.name"> * <input type="submit" value="Add Phone"> * </form> * <h1>Phones</h1> * <ul> * <li ng-repeat="phone in $ctrl.phones">{{phone.name}}</li> * </ul> * </div> * </file> * </example> * * */ /** * @ngdoc method * @name $httpBackend#when * @module ngMockE2E * @description * Creates a new backend definition. * * @param {string} method HTTP method. * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on * {@link ngMock.$httpBackend $httpBackend mock}. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. * * - respond – * ``` * { function([status,] data[, headers, statusText]) * | function(function(method, url, data, headers, params)} * ``` * – The respond method takes a set of static data to be returned or a function that can return * an array containing response status (number), response data (Array|Object|string), response * headers (Object), and the text for the status (string). * - passThrough – `{function()}` – Any request matching a backend definition with * `passThrough` handler will be passed through to the real backend (an XHR request will be made * to the server.) * - Both methods return the `requestHandler` object for possible overrides. */ /** * @ngdoc method * @name $httpBackend#whenGET * @module ngMockE2E * @description * Creates a new backend definition for GET requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on * {@link ngMock.$httpBackend $httpBackend mock}. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenHEAD * @module ngMockE2E * @description * Creates a new backend definition for HEAD requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on * {@link ngMock.$httpBackend $httpBackend mock}. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenDELETE * @module ngMockE2E * @description * Creates a new backend definition for DELETE requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on * {@link ngMock.$httpBackend $httpBackend mock}. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPOST * @module ngMockE2E * @description * Creates a new backend definition for POST requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on * {@link ngMock.$httpBackend $httpBackend mock}. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPUT * @module ngMockE2E * @description * Creates a new backend definition for PUT requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on * {@link ngMock.$httpBackend $httpBackend mock}. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPATCH * @module ngMockE2E * @description * Creates a new backend definition for PATCH requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on * {@link ngMock.$httpBackend $httpBackend mock}. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenJSONP * @module ngMockE2E * @description * Creates a new backend definition for JSONP requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on * {@link ngMock.$httpBackend $httpBackend mock}. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenRoute * @module ngMockE2E * @description * Creates a new backend definition that compares only with the requested route. * * @param {string} method HTTP method. * @param {string} url HTTP url string that supports colon param matching. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#matchLatestDefinition * @module ngMockE2E * @description * This method can be used to change which mocked responses `$httpBackend` returns, when defining * them with {@link ngMock.$httpBackend#when $httpBackend.when()} (and shortcut methods). * By default, `$httpBackend` returns the first definition that matches. When setting * `$http.matchLatestDefinition(true)`, it will use the last response that matches, i.e. the * one that was added last. * * ```js * hb.when('GET', '/url1').respond(200, 'content', {}); * hb.when('GET', '/url1').respond(201, 'another', {}); * hb('GET', '/url1'); // receives "content" * * $http.matchLatestDefinition(true) * hb('GET', '/url1'); // receives "another" * * hb.when('GET', '/url1').respond(201, 'onemore', {}); * hb('GET', '/url1'); // receives "onemore" * ``` * * This is useful if a you have a default response that is overriden inside specific tests. * * Note that different from config methods on providers, `matchLatestDefinition()` can be changed * even when the application is already running. * * @param {Boolean=} value value to set, either `true` or `false`. Default is `false`. * If omitted, it will return the current value. * @return {$httpBackend|Boolean} self when used as a setter, and the current value when used * as a getter */ angular.mock.e2e = {}; angular.mock.e2e.$httpBackendDecorator = ['$rootScope', '$timeout', '$delegate', '$browser', createHttpBackendMock]; /** * @ngdoc type * @name $rootScope.Scope * @module ngMock * @description * {@link ng.$rootScope.Scope Scope} type decorated with helper methods useful for testing. These * methods are automatically available on any {@link ng.$rootScope.Scope Scope} instance when * `ngMock` module is loaded. * * In addition to all the regular `Scope` methods, the following helper methods are available: */ angular.mock.$RootScopeDecorator = ['$delegate', function($delegate) { var $rootScopePrototype = Object.getPrototypeOf($delegate); $rootScopePrototype.$countChildScopes = countChildScopes; $rootScopePrototype.$countWatchers = countWatchers; return $delegate; // ------------------------------------------------------------------------------------------ // /** * @ngdoc method * @name $rootScope.Scope#$countChildScopes * @module ngMock * @this $rootScope.Scope * @description * Counts all the direct and indirect child scopes of the current scope. * * The current scope is excluded from the count. The count includes all isolate child scopes. * * @returns {number} Total number of child scopes. */ function countChildScopes() { var count = 0; // exclude the current scope var pendingChildHeads = [this.$$childHead]; var currentScope; while (pendingChildHeads.length) { currentScope = pendingChildHeads.shift(); while (currentScope) { count += 1; pendingChildHeads.push(currentScope.$$childHead); currentScope = currentScope.$$nextSibling; } } return count; } /** * @ngdoc method * @name $rootScope.Scope#$countWatchers * @this $rootScope.Scope * @module ngMock * @description * Counts all the watchers of direct and indirect child scopes of the current scope. * * The watchers of the current scope are included in the count and so are all the watchers of * isolate child scopes. * * @returns {number} Total number of watchers. */ function countWatchers() { var count = this.$$watchers ? this.$$watchers.length : 0; // include the current scope var pendingChildHeads = [this.$$childHead]; var currentScope; while (pendingChildHeads.length) { currentScope = pendingChildHeads.shift(); while (currentScope) { count += currentScope.$$watchers ? currentScope.$$watchers.length : 0; pendingChildHeads.push(currentScope.$$childHead); currentScope = currentScope.$$nextSibling; } } return count; } }]; (function(jasmineOrMocha) { if (!jasmineOrMocha) { return; } var currentSpec = null, injectorState = new InjectorState(), annotatedFunctions = [], wasInjectorCreated = function() { return !!currentSpec; }; angular.mock.$$annotate = angular.injector.$$annotate; angular.injector.$$annotate = function(fn) { if (typeof fn === 'function' && !fn.$inject) { annotatedFunctions.push(fn); } return angular.mock.$$annotate.apply(this, arguments); }; /** * @ngdoc function * @name angular.mock.module * @description * * *NOTE*: This function is also published on window for easy access.<br> * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha * * This function registers a module configuration code. It collects the configuration information * which will be used when the injector is created by {@link angular.mock.inject inject}. * * See {@link angular.mock.inject inject} for usage example * * @param {...(string|Function|Object)} fns any number of modules which are represented as string * aliases or as anonymous module initialization functions. The modules are used to * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an * object literal is passed each key-value pair will be registered on the module via * {@link auto.$provide $provide}.value, the key being the string name (or token) to associate * with the value on the injector. */ var module = window.module = angular.mock.module = function() { var moduleFns = Array.prototype.slice.call(arguments, 0); return wasInjectorCreated() ? workFn() : workFn; ///////////////////// function workFn() { if (currentSpec.$injector) { throw new Error('Injector already created, can not register a module!'); } else { var fn, modules = currentSpec.$modules || (currentSpec.$modules = []); angular.forEach(moduleFns, function(module) { if (angular.isObject(module) && !angular.isArray(module)) { fn = ['$provide', function($provide) { angular.forEach(module, function(value, key) { $provide.value(key, value); }); }]; } else { fn = module; } if (currentSpec.$providerInjector) { currentSpec.$providerInjector.invoke(fn); } else { modules.push(fn); } }); } } }; module.$$beforeAllHook = (window.before || window.beforeAll); module.$$afterAllHook = (window.after || window.afterAll); // purely for testing ngMock itself module.$$currentSpec = function(to) { if (arguments.length === 0) return to; currentSpec = to; }; /** * @ngdoc function * @name angular.mock.module.sharedInjector * @description * * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha * * This function ensures a single injector will be used for all tests in a given describe context. * This contrasts with the default behaviour where a new injector is created per test case. * * Use sharedInjector when you want to take advantage of Jasmine's `beforeAll()`, or mocha's * `before()` methods. Call `module.sharedInjector()` before you setup any other hooks that * will create (i.e call `module()`) or use (i.e call `inject()`) the injector. * * You cannot call `sharedInjector()` from within a context already using `sharedInjector()`. * * ## Example * * Typically beforeAll is used to make many assertions about a single operation. This can * cut down test run-time as the test setup doesn't need to be re-run, and enabling focussed * tests each with a single assertion. * * ```js * describe("Deep Thought", function() { * * module.sharedInjector(); * * beforeAll(module("UltimateQuestion")); * * beforeAll(inject(function(DeepThought) { * expect(DeepThought.answer).toBeUndefined(); * DeepThought.generateAnswer(); * })); * * it("has calculated the answer correctly", inject(function(DeepThought) { * // Because of sharedInjector, we have access to the instance of the DeepThought service * // that was provided to the beforeAll() hook. Therefore we can test the generated answer * expect(DeepThought.answer).toBe(42); * })); * * it("has calculated the answer within the expected time", inject(function(DeepThought) { * expect(DeepThought.runTimeMillennia).toBeLessThan(8000); * })); * * it("has double checked the answer", inject(function(DeepThought) { * expect(DeepThought.absolutelySureItIsTheRightAnswer).toBe(true); * })); * * }); * * ``` */ module.sharedInjector = function() { if (!(module.$$beforeAllHook && module.$$afterAllHook)) { throw Error('sharedInjector() cannot be used unless your test runner defines beforeAll/afterAll'); } var initialized = false; module.$$beforeAllHook(/** @this */ function() { if (injectorState.shared) { injectorState.sharedError = Error('sharedInjector() cannot be called inside a context that has already called sharedInjector()'); throw injectorState.sharedError; } initialized = true; currentSpec = this; injectorState.shared = true; }); module.$$afterAllHook(function() { if (initialized) { injectorState = new InjectorState(); module.$$cleanup(); } else { injectorState.sharedError = null; } }); }; module.$$beforeEach = function() { if (injectorState.shared && currentSpec && currentSpec !== this) { var state = currentSpec; currentSpec = this; angular.forEach(['$injector','$modules','$providerInjector', '$injectorStrict'], function(k) { currentSpec[k] = state[k]; state[k] = null; }); } else { currentSpec = this; originalRootElement = null; annotatedFunctions = []; } }; module.$$afterEach = function() { if (injectorState.cleanupAfterEach()) { module.$$cleanup(); } }; module.$$cleanup = function() { var injector = currentSpec.$injector; annotatedFunctions.forEach(function(fn) { delete fn.$inject; }); currentSpec.$injector = null; currentSpec.$modules = null; currentSpec.$providerInjector = null; currentSpec = null; if (injector) { // Ensure `$rootElement` is instantiated, before checking `originalRootElement` var $rootElement = injector.get('$rootElement'); var rootNode = $rootElement && $rootElement[0]; var cleanUpNodes = !originalRootElement ? [] : [originalRootElement[0]]; if (rootNode && (!originalRootElement || rootNode !== originalRootElement[0])) { cleanUpNodes.push(rootNode); } angular.element.cleanData(cleanUpNodes); // Ensure `$destroy()` is available, before calling it // (a mocked `$rootScope` might not implement it (or not even be an object at all)) var $rootScope = injector.get('$rootScope'); if ($rootScope && $rootScope.$destroy) $rootScope.$destroy(); } // clean up jquery's fragment cache angular.forEach(angular.element.fragments, function(val, key) { delete angular.element.fragments[key]; }); MockXhr.$$lastInstance = null; angular.forEach(angular.callbacks, function(val, key) { delete angular.callbacks[key]; }); angular.callbacks.$$counter = 0; }; (window.beforeEach || window.setup)(module.$$beforeEach); (window.afterEach || window.teardown)(module.$$afterEach); /** * @ngdoc function * @name angular.mock.inject * @description * * *NOTE*: This function is also published on window for easy access.<br> * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha * * The inject function wraps a function into an injectable function. The inject() creates new * instance of {@link auto.$injector $injector} per test, which is then used for * resolving references. * * * ## Resolving References (Underscore Wrapping) * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable * that is declared in the scope of the `describe()` block. Since we would, most likely, want * the variable to have the same name of the reference we have a problem, since the parameter * to the `inject()` function would hide the outer variable. * * To help with this, the injected parameters can, optionally, be enclosed with underscores. * These are ignored by the injector when the reference name is resolved. * * For example, the parameter `_myService_` would be resolved as the reference `myService`. * Since it is available in the function body as `_myService_`, we can then assign it to a variable * defined in an outer scope. * * ``` * // Defined out reference variable outside * var myService; * * // Wrap the parameter in underscores * beforeEach( inject( function(_myService_){ * myService = _myService_; * })); * * // Use myService in a series of tests. * it('makes use of myService', function() { * myService.doStuff(); * }); * * ``` * * See also {@link angular.mock.module angular.mock.module} * * ## Example * Example of what a typical jasmine tests looks like with the inject method. * ```js * * angular.module('myApplicationModule', []) * .value('mode', 'app') * .value('version', 'v1.0.1'); * * * describe('MyApp', function() { * * // You need to load modules that you want to test, * // it loads only the "ng" module by default. * beforeEach(module('myApplicationModule')); * * * // inject() is used to inject arguments of all given functions * it('should provide a version', inject(function(mode, version) { * expect(version).toEqual('v1.0.1'); * expect(mode).toEqual('app'); * })); * * * // The inject and module method can also be used inside of the it or beforeEach * it('should override a version and test the new version is injected', function() { * // module() takes functions or strings (module aliases) * module(function($provide) { * $provide.value('version', 'overridden'); // override version here * }); * * inject(function(version) { * expect(version).toEqual('overridden'); * }); * }); * }); * * ``` * * @param {...Function} fns any number of functions which will be injected using the injector. */ var ErrorAddingDeclarationLocationStack = function ErrorAddingDeclarationLocationStack(e, errorForStack) { this.message = e.message; this.name = e.name; if (e.line) this.line = e.line; if (e.sourceId) this.sourceId = e.sourceId; if (e.stack && errorForStack) this.stack = e.stack + '\n' + errorForStack.stack; if (e.stackArray) this.stackArray = e.stackArray; }; ErrorAddingDeclarationLocationStack.prototype = Error.prototype; window.inject = angular.mock.inject = function() { var blockFns = Array.prototype.slice.call(arguments, 0); var errorForStack = new Error('Declaration Location'); // IE10+ and PhanthomJS do not set stack trace information, until the error is thrown if (!errorForStack.stack) { try { throw errorForStack; } catch (e) { /* empty */ } } return wasInjectorCreated() ? WorkFn.call(currentSpec) : WorkFn; ///////////////////// function WorkFn() { var modules = currentSpec.$modules || []; var strictDi = !!currentSpec.$injectorStrict; modules.unshift(['$injector', function($injector) { currentSpec.$providerInjector = $injector; }]); modules.unshift('ngMock'); modules.unshift('ng'); var injector = currentSpec.$injector; if (!injector) { if (strictDi) { // If strictDi is enabled, annotate the providerInjector blocks angular.forEach(modules, function(moduleFn) { if (typeof moduleFn === 'function') { angular.injector.$$annotate(moduleFn); } }); } injector = currentSpec.$injector = angular.injector(modules, strictDi); currentSpec.$injectorStrict = strictDi; } for (var i = 0, ii = blockFns.length; i < ii; i++) { if (currentSpec.$injectorStrict) { // If the injector is strict / strictDi, and the spec wants to inject using automatic // annotation, then annotate the function here. injector.annotate(blockFns[i]); } try { injector.invoke(blockFns[i] || angular.noop, this); } catch (e) { if (e.stack && errorForStack) { throw new ErrorAddingDeclarationLocationStack(e, errorForStack); } throw e; } finally { errorForStack = null; } } } }; angular.mock.inject.strictDi = function(value) { value = arguments.length ? !!value : true; return wasInjectorCreated() ? workFn() : workFn; function workFn() { if (value !== currentSpec.$injectorStrict) { if (currentSpec.$injector) { throw new Error('Injector already created, can not modify strict annotations'); } else { currentSpec.$injectorStrict = value; } } } }; function InjectorState() { this.shared = false; this.sharedError = null; this.cleanupAfterEach = function() { return !this.shared || this.sharedError; }; } })(window.jasmine || window.mocha);
var Lab = require('lab'); var Code = require('code'); var Proxyquire = require('proxyquire'); var lab = exports.lab = Lab.script(); var stub = { RedirectActions: {}, xhr: function () { stub.xhr.guts.apply(this, arguments); } }; var JsonFetch = Proxyquire('../../../client/helpers/jsonFetch', { '../actions/Redirect': stub.RedirectActions, xhr: stub.xhr }); lab.experiment('JSON Fetch Helper', function () { lab.test('it makes a basic GET request', function (done) { stub.xhr.guts = function (options, callback) { callback(null, { statusCode: 200, headers: {} }, '{}'); }; var options = { method: 'GET', url: '/blamo' }; var callback = function (err, response) { Code.expect(err).to.not.exist(); done(); }; JsonFetch(options, callback); }); lab.test('it sends a csrf token header if crumb cookie is preset', function (done) { global.document.cookie = 'crumb=blamo!'; stub.xhr.guts = function (options, callback) { callback(null, { statusCode: 200, headers: {} }, '{}'); }; var options = { method: 'GET', url: '/blamo' }; var callback = function (err, response) { Code.expect(err).to.not.exist(); done(); }; JsonFetch(options, callback); }); lab.test('it redirects to login if the x-auth-required header is present', function (done) { stub.xhr.guts = function (options, callback) { var data = { statusCode: 200, headers: { 'x-auth-required': true } }; callback(null, data, {}); }; var options = { method: 'GET', url: '/blamo' }; stub.RedirectActions.saveReturnUrl = function () { done(); }; JsonFetch(options, function () {}); }); lab.test('it makes a GET request with query data', function (done) { stub.xhr.guts = function (options, callback) { callback(null, { statusCode: 200, headers: {} }, '{}'); }; var options = { method: 'GET', url: '/blamo', query: { foo: 'bar' } }; var callback = function (err, response) { Code.expect(err).to.not.exist(); done(); }; JsonFetch(options, callback); }); lab.test('it makes a basic POST request', function (done) { stub.xhr.guts = function (options, callback) { callback(null, { statusCode: 200, headers: {} }, '{}'); }; var options = { method: 'POST', url: '/blamo', data: { foo: 'bar' } }; var callback = function (err, response) { Code.expect(err).to.not.exist(); done(); }; JsonFetch(options, callback); }); lab.test('it makes a request and gets a less than 2xx response', function (done) { global.window.localStorage = { getItem: function () { return ''; } }; stub.xhr.guts = function (options, callback) { var response = { statusCode: 100, rawRequest: { statusText: 'Continue' } }; callback(null, response, '{}'); }; var options = { url: '/blamo' }; var callback = function (err, response) { Code.expect(err).to.exist(); done(); }; JsonFetch(options, callback); }); lab.test('it makes a request and gets a greater than 2xx response', function (done) { global.window.localStorage = { getItem: function () { return ''; } }; stub.xhr.guts = function (options, callback) { var response = { statusCode: 404, rawRequest: { statusText: 'Not Found' } }; callback(null, response, '{}'); }; var options = { url: '/blamo' }; var callback = function (err, response) { Code.expect(err).to.exist(); done(); }; JsonFetch(options, callback); }); lab.test('it handles an xhr error', function (done) { global.window.localStorage = { getItem: function () { return ''; } }; stub.xhr.guts = function (options, callback) { callback(new Error('Blamo')); }; var options = { url: '/blamo' }; var callback = function (err, response) { Code.expect(err).to.exist(); done(); }; JsonFetch(options, callback); }); });
import { describe, it, beforeEach, afterEach } from 'mocha'; import { expect } from 'chai'; import startApp from '../../../helpers/start-app'; import destroyApp from '../../../helpers/destroy-app'; describe('Acceptance: | route |', function() { let application; beforeEach(function() { application = startApp(); }); afterEach(function() { destroyApp(application); }); it('Should visit /address-book', function() { visit('/address-book'); andThen(function() { expect(currentPath()).to.equal('addressBook.index'); }); }); });
'use strict'; // Declare app level module which depends on views, and components var app = angular.module('myApp', [ 'ngRoute', 'ngCookies', 'myApp.viewAuctions', 'myApp.viewSuppliers', 'myApp.viewAuctionDetails', 'myApp.viewSupplierDetails', 'myApp.viewAccount', 'myApp.viewAdminPanel' ]); app.config(function($locationProvider, $routeProvider) { $locationProvider.hashPrefix('!'); $routeProvider.otherwise({ redirectTo: '/viewAuctions' }); }); app.controller('appCtrl', function($rootScope, $scope, UserService) { var vm = this; });
game.SpearThrow = me.Entity.extend({ init: function (x, y, settings, facing) { this._super(me.Entity, 'init', [x, y, { image: "spear", width: 48, height: 48, spritewidth: "48", spriteheight: "48", getShape: function(){ return (new me.Rect(0, 0, 32, 64)).toPolygon(); } }]); this.alwaysUpdate = true; this.body.setVelocity(8, 0); this.attack = game.data.ability3 * 3; this.type = "spear"; this.facing= facing; }, update: function(delta){ if(this.facing === "left"){ this.body.vel.x -= this.body.accel.x * me.timer.tick; }else{ this.body.vel.x += this.body.accel.x * me.timer.tick; } me.collision.check(this, true, this.collideHandler.bind(this), true); this.body.update(delta); this._super(me.Entity, "update", [delta]); return true; }, collideHandler: function(response){ if(response.b.type==='EnemyBase' || response.b.type === 'EnemyCreep'){ response.b.loseHealth(this.attack); me.game.world.removeChild(this); } } });
import codesEnum from "enum/codes.enum"; import a from "model/first.model"; import b from "model/second.model"; var models = {}; models[codesEnum.FIRST] = a; models[codesEnum.SECOND] = b; export default { getClass: function (type) { return models[type]; } };
'use strict'; var express = require('express'), app = express(), logger = require('./logger'), config = require('./config'); // Add the required parameters require('./setup')(app); require('./routes')(app); module.exports = app; var hostname = process.argv[2] || config.ip; var port = process.env.PORT || config.port; app.listen(port); logger('Server running at http://' + hostname + ':' + port);
'use strict'; const device = require('./device'); const types = require('./types'); const Scope = require('../base/scope'); class Uniform { get name() { return this._name; } get value() { return this._value; } set value(v) { this._value = v; this._write(); } get header() { return `${this._signature};`; } get source() { return `${this._signature} {\n\t${this._body}\n}`; } get inject() { return this._inject; } constructor(desc, owner) { this._name = desc.name; this._owner = owner; this._scope = owner.scope.clone(this._name); this._ownScope = this._scope.get(this._name); if (typeof desc.type === 'object') { this._uniType = desc.type.type; this._uniItems = desc.type.names.length; const typeScope = new Scope(); types.fillScope(this._uniType, typeScope, this._scope); desc.type.names.forEach( n => this._ownScope.set(n, typeScope) ); } else { this._uniType = desc.type; this._uniItems = 1; types.fillScope(this._uniType, this._ownScope, this._scope); } this._uniBytes = this._uniItems * types.sizeof(this._uniType); this._pos = device.uniforms.seize(this._uniBytes); this._array = new Uint8Array(this._uniBytes); this._value = desc.init; this._write(); const name = this._scope.get(`${this._name}`).name; this._signature = `${this._uniType} _uniform_${name}(__global char *_uniform_buffer_)`; this._body = `return *((__global ${this._uniType}*)(&_uniform_buffer_[${this._pos}]));`; this._inject = `\t${this._uniType} ${name} = _uniform_${name}(_uniform_buffer_);`; } compile() { } _write() { const buffer = device.uniforms.buffer; // console.log('BUF W', this._pos, this._uniBytes, this._array ); device.cl.enqueueWriteBuffer( device.queue, buffer, true, this._pos, this._uniBytes, this._array ); } }; module.exports = Uniform;
var simpleturing = (function() { function Machine(initial, states) { this.run = function(initialdata, position, defaultvalue) { var tape = initialdata.slice(); if (position == null) position = 0; var state = initial; while (true) { // console.log(tape); // console.log(state); // console.log(position); // console.log("--------"); var value = tape[position]; if (value == null) value = defaultvalue; next = states[state][value]; tape[position] = next[0]; state = next[1]; if (state == 'stop') return tape; position += next[2]; } } } return function(initial, states) { return new Machine(initial, states); } }()); if (typeof(window) === 'undefined') { module.exports = simpleturing; }
/* eslint-disable flowtype/require-valid-file-annotation */ export default from './Radio'; export Radio, { LabelRadio } from './Radio'; export RadioGroup from './RadioGroup';
/** * Created by Mark on 24-3-2016. */ 'use strict' module.exports = function(sequelize, DataTypes) { var Exhibition = sequelize.define('Exhibition', { id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true, allowNull: false }, name: { type: DataTypes.STRING, allowNull: false }, description: DataTypes.STRING, street_and_number: DataTypes.STRING(80), city: { type: DataTypes.STRING(40), allowNull: false }, postal_code: DataTypes.STRING(20), country: DataTypes.STRING(45), start_date: DataTypes.DATEONLY, end_date: DataTypes.DATEONLY, status: DataTypes.BOOLEAN, package_uuid:DataTypes.UUID }, { timestamps: false, associate: function (models) { Exhibition.belongsToMany(models.Article, {through: models.ExhibitionArticle, foreignKey: 'exhibition_id'}); Exhibition.belongsToMany(models.Artist, {through: 'ArtistExhibition', underscored: true, foreignKey: 'exhibition_id'}); Exhibition.belongsTo(models.Resource, {foreignKey: 'resource_id'}); } } ); return Exhibition; };
(function(ng){ 'use strict'; ng .module('AbsenceChecker',[ 'ionic', 'AbsenceChecker.config', 'AbsenceChecker.pages', 'AbsenceChecker.services' ]); })(angular);
import actionTypes from 'Actions/actionTypes'; export default (state = {}, action) => { switch (action.type) { case actionTypes.UPDATE_SCANS: { const scanForHost = state.scanForHost || {}; const scanForCurrHost = { [action.payload.host]: action.payload.scan, }; const newScanForHost = Object.assign( {}, scanForHost, scanForCurrHost, ); const newState = { ...state, ...newScanForHost, }; return newState; } default: { return state; } } };
/*! * jQuery Scrollify * Version 1.0.19 * * Requires: * - jQuery 1.7 or higher * * https://github.com/lukehaas/Scrollify * * Copyright 2016, Luke Haas * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. if touchScroll is false - update index */ (function (global, factory) { "use strict"; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], function ($) { return factory($, global, global.document); }); } else if (typeof module === 'object' && module.exports) { // Node/CommonJS module.exports = factory(require('jquery'), global, global.document); } else { // Browser globals factory(jQuery, global, global.document); } }(typeof window !== 'undefined' ? window : this, function ($, window, document, undefined) { "use strict"; var heights = [], names = [], elements = [], overflow = [], index = 0, currentIndex = 0, interstitialIndex = 1, hasLocation = false, timeoutId, timeoutId2, $window = $(window), portHeight, top = $window.scrollTop(), scrollable = false, locked = false, scrolled = false, manualScroll, swipeScroll, util, disabled = false, scrollSamples = [], scrollTime = new Date().getTime(), firstLoad = true, initialised = false, destination = 0, wheelEvent = 'onwheel' in document ? 'wheel' : document.onmousewheel !== undefined ? 'mousewheel' : 'DOMMouseScroll', settings = { //section should be an identifier that is the same for each section section: ".section", sectionName: "section-name", interstitialSection: "", easing: "easeOutExpo", scrollSpeed: 1100, offset: 0, scrollbars: true, target: "html,body", standardScrollElements: false, setHeights: true, overflowScroll: true, updateHash: true, touchScroll: true, before: function () { }, after: function () { }, afterResize: function () { }, afterRender: function () { } }; function getportHeight() { return ($window.height() + settings.offset); } function animateScroll(index, instant, callbacks, toTop) { if (currentIndex === index) { callbacks = false; } if (disabled === true) { return true; } if (names[index]) { scrollable = false; if (firstLoad === true) { settings.afterRender(); firstLoad = false; } if (callbacks) { if (typeof settings.before == 'function' && settings.before(index, elements) === false) { return true; } } interstitialIndex = 1; destination = heights[index]; if (firstLoad === false && currentIndex > index && toTop === false) { //We're going backwards if (overflow[index]) { portHeight = getportHeight(); interstitialIndex = parseInt(elements[index].outerHeight() / portHeight); destination = parseInt(heights[index]) + (elements[index].outerHeight() - portHeight); } } if (settings.updateHash && settings.sectionName && !(firstLoad === true && index === 0)) { if (history.pushState) { try { history.replaceState(null, null, names[index]); } catch (e) { if (window.console) { console.warn("Scrollify warning: Page must be hosted to manipulate the hash value."); } } } else { window.location.hash = names[index]; } } currentIndex = index; if (instant) { $(settings.target).stop().scrollTop(destination); if (callbacks) { settings.after(index, elements); } } else { locked = true; if ($().velocity) { $(settings.target).stop().velocity('scroll', { duration: settings.scrollSpeed, easing: settings.easing, offset: destination, mobileHA: false }); } else { $(settings.target).stop().animate({ scrollTop: destination }, settings.scrollSpeed, settings.easing); } if (window.location.hash.length && settings.sectionName && window.console) { try { if ($(window.location.hash).length) { console.warn("Scrollify warning: ID matches hash value - this will cause the page to anchor."); } } catch (e) { } } $(settings.target).promise().done(function () { locked = false; firstLoad = false; if (callbacks) { settings.after(index, elements); } }); } } } function isAccelerating(samples) { function average(num) { var sum = 0; var lastElements = samples.slice(Math.max(samples.length - num, 1)); for (var i = 0; i < lastElements.length; i++) { sum += lastElements[i]; } return Math.ceil(sum / num); } var avEnd = average(10); var avMiddle = average(70); if (avEnd >= avMiddle) { return true; } else { return false; } } var scrollify = function (options) { initialised = true; $.easing['easeOutExpo'] = function (x, t, b, c, d) { return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b; }; manualScroll = { handleMousedown: function () { if (disabled === true) { return true; } scrollable = false; scrolled = false; }, handleMouseup: function () { if (disabled === true) { return true; } scrollable = true; if (scrolled) { //instant,callbacks manualScroll.calculateNearest(false, true); } }, handleScroll: function () { if (disabled === true) { return true; } if (timeoutId) { clearTimeout(timeoutId); } timeoutId = setTimeout(function () { scrolled = true; if (scrollable === false) { return false; } scrollable = false; //instant,callbacks manualScroll.calculateNearest(false, true); }, 200); }, calculateNearest: function (instant, callbacks) { top = $window.scrollTop(); var i = 1, max = heights.length, closest = 0, prev = Math.abs(heights[0] - top), diff; for (; i < max; i++) { diff = Math.abs(heights[i] - top); if (diff < prev) { prev = diff; closest = i; } } if ((atBottom() && closest > index) || atTop()) { index = closest; //index, instant, callbacks, toTop animateScroll(closest, instant, callbacks, false); } }, wheelHandler: function (e) { if (disabled === true) { return true; } else if (settings.standardScrollElements) { if ($(e.target).is(settings.standardScrollElements) || $(e.target).closest(settings.standardScrollElements).length) { return true; } } if (!overflow[index]) { e.preventDefault(); } var currentScrollTime = new Date().getTime(); e = e || window.event; var value = e.originalEvent.wheelDelta || -e.originalEvent.deltaY || -e.originalEvent.detail; var delta = Math.max(-1, Math.min(1, value)); //delta = delta || -e.originalEvent.detail / 3 || e.originalEvent.wheelDelta / 120; if (scrollSamples.length > 149) { scrollSamples.shift(); } //scrollSamples.push(Math.abs(delta*10)); scrollSamples.push(Math.abs(value)); if ((currentScrollTime - scrollTime) > 200) { scrollSamples = []; } scrollTime = currentScrollTime; if (locked) { return false; } if (delta < 0) { if (index < heights.length - 1) { if (atBottom()) { if (isAccelerating(scrollSamples)) { e.preventDefault(); index++; locked = true; //index, instant, callbacks, toTop animateScroll(index, false, true, false); } else { return false; } } } } else if (delta > 0) { if (index > 0) { if (atTop()) { if (isAccelerating(scrollSamples)) { e.preventDefault(); index--; locked = true; //index, instant, callbacks, toTop animateScroll(index, false, true, false); } else { return false } } } } }, keyHandler: function (e) { if (disabled === true || document.activeElement.readOnly === false) { return true; } else if (settings.standardScrollElements) { if ($(e.target).is(settings.standardScrollElements) || $(e.target).closest(settings.standardScrollElements).length) { return true; } } if (locked === true) { return false; } if (e.keyCode == 38 || e.keyCode == 33) { if (index > 0) { if (atTop()) { e.preventDefault(); index--; //index, instant, callbacks, toTop animateScroll(index, false, true, false); } } } else if (e.keyCode == 40 || e.keyCode == 34) { if (index < heights.length - 1) { if (atBottom()) { e.preventDefault(); index++; //index, instant, callbacks, toTop animateScroll(index, false, true, false); } } } }, init: function () { if (settings.scrollbars) { $window.on('mousedown', manualScroll.handleMousedown); $window.on('mouseup', manualScroll.handleMouseup); $window.on('scroll', manualScroll.handleScroll); } else { $("body").css({ "overflow": "hidden" }); } $window.on(wheelEvent, manualScroll.wheelHandler); //$(document).bind(wheelEvent,manualScroll.wheelHandler); $window.on('keydown', manualScroll.keyHandler); } }; swipeScroll = { touches: { "touchstart": { "y": -1, "x": -1 }, "touchmove": { "y": -1, "x": -1 }, "touchend": false, "direction": "undetermined" }, options: { "distance": 30, "timeGap": 800, "timeStamp": new Date().getTime() }, touchHandler: function (event) { if (disabled === true) { return true; } else if (settings.standardScrollElements) { if ($(event.target).is(settings.standardScrollElements) || $(event.target).closest(settings.standardScrollElements).length) { return true; } } var touch; if (typeof event !== 'undefined') { if (typeof event.touches !== 'undefined') { touch = event.touches[0]; switch (event.type) { case 'touchstart': swipeScroll.touches.touchstart.y = touch.pageY; swipeScroll.touches.touchmove.y = -1; swipeScroll.touches.touchstart.x = touch.pageX; swipeScroll.touches.touchmove.x = -1; swipeScroll.options.timeStamp = new Date().getTime(); swipeScroll.touches.touchend = false; case 'touchmove': swipeScroll.touches.touchmove.y = touch.pageY; swipeScroll.touches.touchmove.x = touch.pageX; if (swipeScroll.touches.touchstart.y !== swipeScroll.touches.touchmove.y && (Math.abs(swipeScroll.touches.touchstart.y - swipeScroll.touches.touchmove.y) > Math.abs(swipeScroll.touches.touchstart.x - swipeScroll.touches.touchmove.x))) { //if(!overflow[index]) { event.preventDefault(); //} swipeScroll.touches.direction = "y"; if ((swipeScroll.options.timeStamp + swipeScroll.options.timeGap) < (new Date().getTime()) && swipeScroll.touches.touchend == false) { swipeScroll.touches.touchend = true; if (swipeScroll.touches.touchstart.y > -1) { if (Math.abs(swipeScroll.touches.touchmove.y - swipeScroll.touches.touchstart.y) > swipeScroll.options.distance) { if (swipeScroll.touches.touchstart.y < swipeScroll.touches.touchmove.y) { swipeScroll.up(); } else { swipeScroll.down(); } } } } } break; case 'touchend': if (swipeScroll.touches[event.type] === false) { swipeScroll.touches[event.type] = true; if (swipeScroll.touches.touchstart.y > -1 && swipeScroll.touches.touchmove.y > -1 && swipeScroll.touches.direction === "y") { if (Math.abs(swipeScroll.touches.touchmove.y - swipeScroll.touches.touchstart.y) > swipeScroll.options.distance) { if (swipeScroll.touches.touchstart.y < swipeScroll.touches.touchmove.y) { swipeScroll.up(); } else { swipeScroll.down(); } } swipeScroll.touches.touchstart.y = -1; swipeScroll.touches.touchstart.x = -1; swipeScroll.touches.direction = "undetermined"; } } default: break; } } } }, down: function () { if (index < heights.length) { if (atBottom() && index < heights.length - 1) { index++; //index, instant, callbacks, toTop animateScroll(index, false, true, false); } else { portHeight = getportHeight(); if (Math.floor(elements[index].height() / portHeight) > interstitialIndex) { interstitialScroll(parseInt(heights[index]) + (portHeight * interstitialIndex)); interstitialIndex += 1; } else { interstitialScroll(parseInt(heights[index]) + (elements[index].outerHeight() - portHeight)); } } } }, up: function () { if (index >= 0) { if (atTop() && index > 0) { index--; //index, instant, callbacks, toTop animateScroll(index, false, true, false); } else { if (interstitialIndex > 2) { portHeight = getportHeight(); interstitialIndex -= 1; interstitialScroll(parseInt(heights[index]) + (portHeight * interstitialIndex)); } else { interstitialIndex = 1; interstitialScroll(parseInt(heights[index])); } } } }, init: function () { if (document.addEventListener && settings.touchScroll) { var eventListenerOptions = { passive: false }; document.addEventListener('touchstart', swipeScroll.touchHandler, eventListenerOptions); document.addEventListener('touchmove', swipeScroll.touchHandler, eventListenerOptions); document.addEventListener('touchend', swipeScroll.touchHandler, eventListenerOptions); } } }; util = { refresh: function (withCallback, scroll) { clearTimeout(timeoutId2); timeoutId2 = setTimeout(function () { //retain position sizePanels(true); //scroll, firstLoad calculatePositions(scroll, false); if (withCallback) { settings.afterResize(); } }, 400); }, handleUpdate: function () { //callbacks, scroll //changed from false,true to false,false util.refresh(false, false); }, handleResize: function () { //callbacks, scroll util.refresh(true, false); }, handleOrientation: function () { //callbacks, scroll util.refresh(true, true); } }; settings = $.extend(settings, options); //retain position sizePanels(false); calculatePositions(false, true); if (true === hasLocation) { //index, instant, callbacks, toTop animateScroll(index, false, true, true); } else { setTimeout(function () { //instant,callbacks manualScroll.calculateNearest(true, false); }, 200); } if (heights.length) { manualScroll.init(); swipeScroll.init(); $window.on("resize", util.handleResize); if (document.addEventListener) { window.addEventListener("orientationchange", util.handleOrientation, false); } } function interstitialScroll(pos) { if ($().velocity) { $(settings.target).stop().velocity('scroll', { duration: settings.scrollSpeed, easing: settings.easing, offset: pos, mobileHA: false }); } else { $(settings.target).stop().animate({ scrollTop: pos }, settings.scrollSpeed, settings.easing); } } function sizePanels(keepPosition) { if (keepPosition) { top = $window.scrollTop(); } var selector = settings.section; overflow = []; if (settings.interstitialSection.length) { selector += "," + settings.interstitialSection; } if (settings.scrollbars === false) { settings.overflowScroll = false; } portHeight = getportHeight(); $(selector).each(function (i) { var $this = $(this); if (settings.setHeights) { if ($this.is(settings.interstitialSection)) { overflow[i] = false; } else { if (($this.css("height", "auto").outerHeight() < portHeight) || $this.css("overflow") === "hidden") { $this.css({ "height": portHeight }); overflow[i] = false; } else { $this.css({ "height": $this.height() }); if (settings.overflowScroll) { overflow[i] = true; } else { overflow[i] = false; } } } } else { if (($this.outerHeight() < portHeight) || (settings.overflowScroll === false)) { overflow[i] = false; } else { overflow[i] = true; } } }); if (keepPosition) { $window.scrollTop(top); } } function calculatePositions(scroll, firstLoad) { var selector = settings.section; if (settings.interstitialSection.length) { selector += "," + settings.interstitialSection; } heights = []; names = []; elements = []; $(selector).each(function (i) { var $this = $(this); if (i > 0) { heights[i] = parseInt($this.offset().top) + settings.offset; } else { heights[i] = parseInt($this.offset().top); } if (settings.sectionName && $this.data(settings.sectionName)) { names[i] = "#" + $this.data(settings.sectionName).toString().replace(/ /g, "-"); } else { if ($this.is(settings.interstitialSection) === false) { names[i] = "#" + (i + 1); } else { names[i] = "#"; if (i === $(selector).length - 1 && i > 1) { heights[i] = heights[i - 1] + (parseInt($($(selector)[i - 1]).outerHeight()) - parseInt($(window).height())) + parseInt($this.outerHeight()); } } } elements[i] = $this; try { if ($(names[i]).length && window.console) { console.warn("Scrollify warning: Section names can't match IDs - this will cause the browser to anchor."); } } catch (e) { } if (window.location.hash === names[i]) { index = i; hasLocation = true; } }); if (true === scroll) { //index, instant, callbacks, toTop animateScroll(index, false, false, false); } } function atTop() { if (!overflow[index]) { return true; } top = $window.scrollTop(); if (top > parseInt(heights[index])) { return false; } else { return true; } } function atBottom() { if (!overflow[index]) { return true; } top = $window.scrollTop(); portHeight = getportHeight(); if (top < parseInt(heights[index]) + (elements[index].outerHeight() - portHeight) - 28) { return false; } else { return true; } } } function move(panel, instant) { var z = names.length; for (; z >= 0; z--) { if (typeof panel === 'string') { if (names[z] === panel) { index = z; //index, instant, callbacks, toTop animateScroll(z, instant, true, true); } } else { if (z === panel) { index = z; //index, instant, callbacks, toTop animateScroll(z, instant, true, true); } } } } scrollify.move = function (panel) { if (panel === undefined) { return false; } if (panel.originalEvent) { panel = $(this).attr("href"); } move(panel, false); }; scrollify.instantMove = function (panel) { if (panel === undefined) { return false; } move(panel, true); }; scrollify.next = function () { if (index < names.length) { index += 1; //index, instant, callbacks, toTop animateScroll(index, false, true, true); } }; scrollify.previous = function () { if (index > 0) { index -= 1; //index, instant, callbacks, toTop animateScroll(index, false, true, true); } }; scrollify.instantNext = function () { if (index < names.length) { index += 1; //index, instant, callbacks, toTop animateScroll(index, true, true, true); } }; scrollify.instantPrevious = function () { if (index > 0) { index -= 1; //index, instant, callbacks, toTop animateScroll(index, true, true, true); } }; scrollify.destroy = function () { if (!initialised) { return false; } if (settings.setHeights) { $(settings.section).each(function () { $(this).css("height", "auto"); }); } $window.off("resize", util.handleResize); if (settings.scrollbars) { $window.off('mousedown', manualScroll.handleMousedown); $window.off('mouseup', manualScroll.handleMouseup); $window.off('scroll', manualScroll.handleScroll); } $window.off(wheelEvent, manualScroll.wheelHandler); $window.off('keydown', manualScroll.keyHandler); if (document.addEventListener && settings.touchScroll) { document.removeEventListener('touchstart', swipeScroll.touchHandler, false); document.removeEventListener('touchmove', swipeScroll.touchHandler, false); document.removeEventListener('touchend', swipeScroll.touchHandler, false); } heights = []; names = []; elements = []; overflow = []; }; scrollify.update = function () { if (!initialised) { return false; } util.handleUpdate(); }; scrollify.current = function () { return elements[index]; }; scrollify.currentIndex = function () { return index; }; scrollify.disable = function () { disabled = true; }; scrollify.enable = function () { disabled = false; if (initialised) { //instant,callbacks manualScroll.calculateNearest(false, false); } }; scrollify.isDisabled = function () { return disabled; }; scrollify.setOptions = function (updatedOptions) { if (!initialised) { return false; } if (typeof updatedOptions === "object") { settings = $.extend(settings, updatedOptions); util.handleUpdate(); } else if (window.console) { console.warn("Scrollify warning: setOptions expects an object."); } }; $.scrollify = scrollify; return scrollify; }));
module.exports = require('./lib/assets');
'use strict'; angular .module('angular.extras.core') .factory('AeTableService', ['NgTableParams', '$q', function () { return { /** * Process a row column bases object-array structure and generate excel like cell number. The input should be * like: * * var rows = [{ * columns: [{ * text: 'Foo' // any custom data * }, { * text: 'Bar' * }, { * text: 'Ok' * }] * }, { * columns: [{ * text: 'Foo Bar', * colspan: 2 // Supports colspan * }, { * text: 'Ok' * }] * }] * * This method will convert it to like: * * var rows = [{ * rowNumber: 1, * columns: [{ * text: 'Foo' * columnNumber: 1, * cellNumber: 'A1' * }, { * text: 'Bar' * columnNumber: 2, * cellNumber: 'B1' * }, { * text: 'Ok' * columnNumber: 3, * cellNumber: 'C1' * }] * }, { * columns: [{ * text: 'Foo Bar', * colspan: 2, * columnNumber: 1, * cellNumber: 'A2' * }, { * text: 'Ok', * columnNumber: 3, * cellNumber: 'C2' * }] * }] */ generateCellNumber: function (rows) { angular.forEach(rows, function (row, rowIndex) { row.rowNumber = rowIndex + 1; angular.forEach(row.columns, function (column, columnIndex) { var columnNumber = columnIndex + 1; row.mergedColumns = row.mergedColumns || 0; columnNumber += row.mergedColumns; // We need to also consider the colspan values in order to generate proper column number if (column.colspan) { row.mergedColumns += column.colspan; } if (column.colspan > 0) { row.mergedColumns--; } column.columnNumber = columnNumber; // Calculate the cell number like an excel sheet column.cellNumber = String.fromCharCode(columnNumber + 64) + row.rowNumber; }); }); } }; }]);
const massive = require("massive"); const aws = require('aws-sdk'); const spawn = require('lib/spawn'); const log = require('log-colors'); const sm = require('sitemap'); const get_slug = require('speakingurl'); const AWS_ACCESS_KEY_ID = process.env['AWS_ACCESS_KEY_ID']; const AWS_SECRET_ACCESS_KEY = process.env['AWS_SECRET_ACCESS_KEY']; const S3_BUCKET = process.env['S3_BUCKET']; const DB_HOST = process.env['DB_HOST']; const DB_PORT = process.env['DB_PORT']; const DB_USER = process.env['DB_USER']; const DB_PASSWD = process.env['DB_PASSWD']; const DB_NAME = process.env['DB_NAME']; const s3 = new aws.S3(); spawn(function*(){ var db = yield new Promise((resolve) => { log.info('connecting to db'); massive.connect({ connectionString: `postgres://${DB_USER}:${DB_PASSWD}@${DB_HOST}/${DB_NAME}` }, (err, _db) => { log.info('connected to db'); resolve(_db); }); }); var items = yield new Promise((resolve) => { db.run('select id, title from items', (err, items) => { if(err){ log.error(err); } resolve(items); }); }); log.info(`got ${items.length} items`); log.info(`processing items`); var files_count = Math.ceil(items.length / 50000); for(var counter = 0; counter < files_count; counter++){ var sitemap = sm.createSitemap ({ hostname: 'http://mightygoose.com', cacheTime: 600000 }); log.info(`crating sitemap #${counter}`); var items_portion = items.splice(0, 50000); items_portion.forEach((item) => { sitemap.add({url: `/post/${item.id}/${get_slug(item.title)}`, changefreq: 'monthly'}); }); log.info(`generating xml content`); var xml_body = yield new Promise((resolve, reject) => { sitemap.toXML(function (err, xml){ if(err){ reject(err); return; } resolve(xml); }); }); log.info(`saving sitemap file`); var s3_result = yield new Promise((resolve, reject) => { s3.putObject({ Bucket: S3_BUCKET, Key: `sitemap_${counter}.xml`, Body: xml_body }, function(err){ if(err){ reject(err); return; } resolve(true); }); }).catch((e) => { log.error(`couldn't save sitemap file, error: ${e}`); process.exit(0); }); } log.info(`sitemap updated`); process.exit(0); });
/*! * jQuery JavaScript Library v1.11.0 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-01-23T21:02Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ // var deletedIds = []; var slice = deletedIds.slice; var concat = deletedIds.concat; var push = deletedIds.push; var indexOf = deletedIds.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var trim = "".trim; var support = {}; var version = "1.11.0", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return a 'clean' array ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return just the object slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: deletedIds.sort, splice: deletedIds.splice }; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN return obj - parseFloat( obj ) >= 0; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( support.ownLast ) { for ( key in obj ) { return hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, type: function( obj ) { if ( obj == null ) { return obj + ""; } return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: trim && !trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( indexOf ) { return indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; while ( j < len ) { first[ i++ ] = second[ j++ ]; } // Support: IE<9 // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) if ( len !== len ) { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: function() { return +( new Date() ); }, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v1.10.16 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-01-13 */ (function( window ) { var i, support, Expr, getText, isXML, compile, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (jQuery #6963) if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== strundefined && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", function() { setDocument(); }, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", function() { setDocument(); }); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select t=''><option selected=''></option></select>"; // Support: IE8, Opera 10-12 // Nothing should be selected when empty strings follow ^= or $= or *= if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // Use the correct document accordingly with window argument (sandbox) document = window.document, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); jQuery.fn.extend({ has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !(--remaining) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } } }); /** * Clean-up method for dom ready events */ function detach() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } } /** * The ready event handler and self cleanup method */ function completed() { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; var strundefined = typeof undefined; // Support: IE<9 // Iteration over object's inherited properties before its own var i; for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Note: most support tests are defined in their respective modules. // false until the test is run support.inlineBlockNeedsLayout = false; jQuery(function() { // We need to execute this one support test ASAP because we need to know // if body.style.zoom needs to be set. var container, div, body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } // Setup container = document.createElement( "div" ); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; div = document.createElement( "div" ); body.appendChild( container ).appendChild( div ); if ( typeof div.style.zoom !== strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.style.cssText = "border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1"; if ( (support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 )) ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = null; }); (function() { var div = document.createElement( "div" ); // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } // Null elements to avoid leaks in IE. div = null; })(); /** * Determines whether an object can have data */ jQuery.acceptData = function( elem ) { var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ], nodeType = +elem.nodeType || 1; // Do not set data on non-element DOM nodes because it will not be cleared (#8335). return nodeType !== 1 && nodeType !== 9 ? false : // Nodes accept data unless otherwise specified; rejection can be conditional !noData || noData !== true && elem.getAttribute("classid") === noData; }; var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } function internalData( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements (space-suffixed to avoid Object.prototype collisions) // throw uncatchable exceptions if you attempt to set expando properties noData: { "applet ": true, "embed ": true, // ...but Flash objects (which have this classid) *can* handle expandos "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[0], attrs = elem && elem.attributes; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { i = attrs.length; while ( i-- ) { name = attrs[i].name; if ( name.indexOf("data-") === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { var fragment = document.createDocumentFragment(), div = document.createElement("div"), input = document.createElement("input"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a>"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName( "tbody" ).length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) input.type = "checkbox"; input.checked = true; fragment.appendChild( input ); support.appendChecked = input.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE6-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; // #11217 - WebKit loses check when the name is after the checked attribute fragment.appendChild( div ); div.innerHTML = "<input type='radio' checked='checked' name='t'/>"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() support.noCloneEvent = true; if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } // Null elements to avoid leaks in IE. fragment = div = input = null; })(); (function() { var i, eventName, div = document.createElement( "div" ); // Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event) for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; if ( !(support[ i + "Bubbles" ] = eventName in window) ) { // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) div.setAttribute( eventName, "t" ); support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false; } } // Null elements to avoid leaks in IE. div = null; })(); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && ( // Support: IE < 9 src.returnValue === false || // Support: Android < 4.0 src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); jQuery._removeData( doc, fix ); } else { jQuery._data( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!support.noCloneEvent || !support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } deletedIds.push( id ); } } } } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( support.htmlSerialize || !rnoshimcache.test( value ) ) && ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF window.getDefaultComputedStyle( elem[ 0 ] ).display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } (function() { var a, shrinkWrapBlocksVal, div = document.createElement( "div" ), divReset = "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;" + "display:block;padding:0;margin:0;border:0"; // Setup div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName( "a" )[ 0 ]; a.style.cssText = "float:left;opacity:.5"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Null elements to avoid leaks in IE. a = div = null; support.shrinkWrapBlocks = function() { var body, container, div, containerStyles; if ( shrinkWrapBlocksVal == null ) { body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body ) { // Test fired too early or in an unsupported environment, exit. return; } containerStyles = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px"; container = document.createElement( "div" ); div = document.createElement( "div" ); body.appendChild( container ).appendChild( div ); // Will be changed later if needed. shrinkWrapBlocksVal = false; if ( typeof div.style.zoom !== strundefined ) { // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.cssText = divReset + ";width:1px;padding:1px;zoom:1"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; shrinkWrapBlocksVal = div.offsetWidth !== 3; } body.removeChild( container ); // Null elements to avoid leaks in IE. body = container = div = null; } return shrinkWrapBlocksVal; }; })(); var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles, curCSS, rposition = /^(top|right|bottom|left)$/; if ( window.getComputedStyle ) { getStyles = function( elem ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); }; curCSS = function( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } // Support: IE // IE returns zIndex value as an integer. return ret === undefined ? ret : ret + ""; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, computed ) { var left, rs, rsLeft, ret, style = elem.style; computed = computed || getStyles( elem ); ret = computed ? computed[ name ] : undefined; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } // Support: IE // IE returns zIndex value as an integer. return ret === undefined ? ret : ret + "" || "auto"; }; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { var condition = conditionFn(); if ( condition == null ) { // The test was not ready at this point; screw the hook this time // but check again when needed next time. return; } if ( condition ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { var a, reliableHiddenOffsetsVal, boxSizingVal, boxSizingReliableVal, pixelPositionVal, reliableMarginRightVal, div = document.createElement( "div" ), containerStyles = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px", divReset = "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;" + "display:block;padding:0;margin:0;border:0"; // Setup div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName( "a" )[ 0 ]; a.style.cssText = "float:left;opacity:.5"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Null elements to avoid leaks in IE. a = div = null; jQuery.extend(support, { reliableHiddenOffsets: function() { if ( reliableHiddenOffsetsVal != null ) { return reliableHiddenOffsetsVal; } var container, tds, isSupported, div = document.createElement( "div" ), body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body ) { // Return for frameset docs that don't have a body return; } // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; container = document.createElement( "div" ); container.style.cssText = containerStyles; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height reliableHiddenOffsetsVal = isSupported && ( tds[ 0 ].offsetHeight === 0 ); body.removeChild( container ); // Null elements to avoid leaks in IE. div = body = null; return reliableHiddenOffsetsVal; }, boxSizing: function() { if ( boxSizingVal == null ) { computeStyleTests(); } return boxSizingVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computeStyleTests(); } return boxSizingReliableVal; }, pixelPosition: function() { if ( pixelPositionVal == null ) { computeStyleTests(); } return pixelPositionVal; }, reliableMarginRight: function() { var body, container, div, marginDiv; // Use window.getComputedStyle because jsdom on node.js will break without it. if ( reliableMarginRightVal == null && window.getComputedStyle ) { body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body ) { // Test fired too early or in an unsupported environment, exit. return; } container = document.createElement( "div" ); div = document.createElement( "div" ); container.style.cssText = containerStyles; body.appendChild( container ).appendChild( div ); // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement( "div" ) ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; reliableMarginRightVal = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); body.removeChild( container ); } return reliableMarginRightVal; } }); function computeStyleTests() { var container, div, body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body ) { // Test fired too early or in an unsupported environment, exit. return; } container = document.createElement( "div" ); div = document.createElement( "div" ); container.style.cssText = containerStyles; body.appendChild( container ).appendChild( div ); div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;" + "position:absolute;display:block;padding:1px;border:1px;width:4px;" + "margin-top:1%;top:1%"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { boxSizingVal = div.offsetWidth === 4; }); // Will be changed later if needed. boxSizingReliableVal = true; pixelPositionVal = false; reliableMarginRightVal = true; // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; boxSizingReliableVal = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; } body.removeChild( container ); // Null elements to avoid leaks in IE. div = body = null; } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = support.boxSizing() && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set. See: #7116 if ( value == null || value !== value ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Support: IE // Swallow errors from 'invalid' CSS values (#5509) try { // Support: Chrome, Safari // Setting style to blank string required to delete "style: x !important;" style[ name ] = ""; style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, support.boxSizing() && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; } }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, dDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); dDisplay = defaultDisplay( elem.nodeName ); if ( display === "none" ) { display = dDisplay; } if ( display === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !support.inlineBlockNeedsLayout || dDisplay === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !support.shrinkWrapBlocks() ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.timers = []; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }; (function() { var a, input, select, opt, div = document.createElement("div" ); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName("a")[ 0 ]; // First batch of tests. select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE8 only // Check if we can trust getAttribute("value") input = document.createElement( "input" ); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // Null elements to avoid leaks in IE. a = input = select = opt = div = null; })(); var rreturn = /\r/g; jQuery.fn.extend({ val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : jQuery.text( elem ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) { // Support: IE6 // When new option element is added to select box we need to // force reflow of newly added node in order to workaround delay // of initialization properties try { option.selected = optionSet = true; } catch ( _ ) { // Will be executed only in IE6 option.scrollHeight; } } else { option.selected = false; } } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return options; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = support.getSetAttribute, getSetInput = support.input; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } } }); // Hook for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; // Retrieve booleans specially jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; } : function( elem, name, isXML ) { if ( !isXML ) { return elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; } }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) if ( name === "value" || value === elem.getAttribute( name ) ) { return value; } } }; // Some attributes are constructed with empty-string values when not defined attrHandle.id = attrHandle.name = attrHandle.coords = function( elem, name, isXML ) { var ret; if ( !isXML ) { return (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; } }; // Fixing value retrieval on a button requires this module jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); if ( ret && ret.specified ) { return ret.value; } }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } if ( !support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } var rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } // Support: Safari, IE9+ // mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !support.enctype ) { jQuery.propFix.enctype = "encoding"; } var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; } }); // Return jQuery for attributes-only inclusion jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var nonce = jQuery.now(); var rquery = (/\?/); var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g; jQuery.parseJSON = function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { // Support: Android 2.3 // Workaround failure to string-cast null input return window.JSON.parse( data + "" ); } var requireNonComma, depth = null, str = jQuery.trim( data + "" ); // Guard against invalid (and possibly dangerous) input by ensuring that nothing remains // after removing valid tokens return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) { // Force termination if we see a misplaced comma if ( requireNonComma && comma ) { depth = 0; } // Perform no more replacements after returning to outermost depth if ( depth === 0 ) { return token; } // Commas must not follow "[", "{", or "," requireNonComma = open || comma; // Determine new depth // array/object open ("[" or "{"): depth += true - false (increment) // array/object close ("]" or "}"): depth += false - true (decrement) // other cases ("," or primitive): depth += true - true (numeric cast) depth += !close - !open; // Remove this token return ""; }) ) ? ( Function( "return " + str ) )() : jQuery.error( "Invalid JSON: " + data ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType.charAt( 0 ) === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; }); jQuery._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; jQuery.fn.extend({ wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!support.reliableHiddenOffsets() && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ? // Support: IE6+ function() { // XHR cannot access local files, always use ActiveX for that case return !this.isLocal && // Support: IE7-8 // oldIE XHR does not support non-RFC2616 methods (#13240) // See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx // and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9 // Although this check for six methods instead of eight // since IE also does not support "trace" and "connect" /^(get|post|head|put|delete|options)$/i.test( this.type ) && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; var xhrId = 0, xhrCallbacks = {}, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE<10 // Open requests must be manually aborted on unload (#5280) if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }); } // Determine support properties support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( options ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !options.crossDomain || support.cors ) { var callback; return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; // Open the socket xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { // Support: IE<9 // IE's ActiveXObject throws a 'Type Mismatch' exception when setting // request header to a null-value. // // To keep consistent with other XHR implementations, cast the value // to string and ignore `undefined`. if ( headers[ i ] !== undefined ) { xhr.setRequestHeader( i, headers[ i ] + "" ); } } // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( options.hasContent && options.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responses; // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Clean up delete xhrCallbacks[ id ]; callback = undefined; xhr.onreadystatechange = jQuery.noop; // Abort manually if needed if ( isAbort ) { if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; // Support: IE<10 // Accessing binary-data responseText throws an exception // (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && options.isLocal && !options.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, xhr.getAllResponseHeaders() ); } }; if ( !options.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { // Add to the list of active xhr callbacks xhr.onreadystatechange = xhrCallbacks[ id ] = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -1; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); }); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; })); (function($, undefined) { /** * Unobtrusive scripting adapter for jQuery * https://github.com/rails/jquery-ujs * * Requires jQuery 1.7.0 or later. * * Released under the MIT license * */ // Cut down on the number of issues from people inadvertently including jquery_ujs twice // by detecting and raising an error when it happens. if ( $.rails !== undefined ) { $.error('jquery-ujs has already been loaded!'); } // Shorthand to make it a little easier to call public rails functions from within rails.js var rails; var $document = $(document); $.rails = rails = { // Link elements bound by jquery-ujs linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote], a[data-disable-with]', // Button elements bound by jquery-ujs buttonClickSelector: 'button[data-remote]', // Select elements bound by jquery-ujs inputChangeSelector: 'select[data-remote], input[data-remote], textarea[data-remote]', // Form elements bound by jquery-ujs formSubmitSelector: 'form', // Form input elements bound by jquery-ujs formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type])', // Form input elements disabled during form submission disableSelector: 'input[data-disable-with], button[data-disable-with], textarea[data-disable-with]', // Form input elements re-enabled after form submission enableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled', // Form required input elements requiredInputSelector: 'input[name][required]:not([disabled]),textarea[name][required]:not([disabled])', // Form file input elements fileInputSelector: 'input[type=file]', // Link onClick disable selector with possible reenable after remote submission linkDisableSelector: 'a[data-disable-with]', // Make sure that every Ajax request sends the CSRF token CSRFProtection: function(xhr) { var token = $('meta[name="csrf-token"]').attr('content'); if (token) xhr.setRequestHeader('X-CSRF-Token', token); }, // making sure that all forms have actual up-to-date token(cached forms contain old one) refreshCSRFTokens: function(){ var csrfToken = $('meta[name=csrf-token]').attr('content'); var csrfParam = $('meta[name=csrf-param]').attr('content'); $('form input[name="' + csrfParam + '"]').val(csrfToken); }, // Triggers an event on an element and returns false if the event result is false fire: function(obj, name, data) { var event = $.Event(name); obj.trigger(event, data); return event.result !== false; }, // Default confirm dialog, may be overridden with custom confirm dialog in $.rails.confirm confirm: function(message) { return confirm(message); }, // Default ajax function, may be overridden with custom function in $.rails.ajax ajax: function(options) { return $.ajax(options); }, // Default way to get an element's href. May be overridden at $.rails.href. href: function(element) { return element.attr('href'); }, // Submits "remote" forms and links with ajax handleRemote: function(element) { var method, url, data, elCrossDomain, crossDomain, withCredentials, dataType, options; if (rails.fire(element, 'ajax:before')) { elCrossDomain = element.data('cross-domain'); crossDomain = elCrossDomain === undefined ? null : elCrossDomain; withCredentials = element.data('with-credentials') || null; dataType = element.data('type') || ($.ajaxSettings && $.ajaxSettings.dataType); if (element.is('form')) { method = element.attr('method'); url = element.attr('action'); data = element.serializeArray(); // memoized value from clicked submit button var button = element.data('ujs:submit-button'); if (button) { data.push(button); element.data('ujs:submit-button', null); } } else if (element.is(rails.inputChangeSelector)) { method = element.data('method'); url = element.data('url'); data = element.serialize(); if (element.data('params')) data = data + "&" + element.data('params'); } else if (element.is(rails.buttonClickSelector)) { method = element.data('method') || 'get'; url = element.data('url'); data = element.serialize(); if (element.data('params')) data = data + "&" + element.data('params'); } else { method = element.data('method'); url = rails.href(element); data = element.data('params') || null; } options = { type: method || 'GET', data: data, dataType: dataType, // stopping the "ajax:beforeSend" event will cancel the ajax request beforeSend: function(xhr, settings) { if (settings.dataType === undefined) { xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script); } return rails.fire(element, 'ajax:beforeSend', [xhr, settings]); }, success: function(data, status, xhr) { element.trigger('ajax:success', [data, status, xhr]); }, complete: function(xhr, status) { element.trigger('ajax:complete', [xhr, status]); }, error: function(xhr, status, error) { element.trigger('ajax:error', [xhr, status, error]); }, crossDomain: crossDomain }; // There is no withCredentials for IE6-8 when // "Enable native XMLHTTP support" is disabled if (withCredentials) { options.xhrFields = { withCredentials: withCredentials }; } // Only pass url to `ajax` options if not blank if (url) { options.url = url; } var jqxhr = rails.ajax(options); element.trigger('ajax:send', jqxhr); return jqxhr; } else { return false; } }, // Handles "data-method" on links such as: // <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a> handleMethod: function(link) { var href = rails.href(link), method = link.data('method'), target = link.attr('target'), csrfToken = $('meta[name=csrf-token]').attr('content'), csrfParam = $('meta[name=csrf-param]').attr('content'), form = $('<form method="post" action="' + href + '"></form>'), metadataInput = '<input name="_method" value="' + method + '" type="hidden" />'; if (csrfParam !== undefined && csrfToken !== undefined) { metadataInput += '<input name="' + csrfParam + '" value="' + csrfToken + '" type="hidden" />'; } if (target) { form.attr('target', target); } form.hide().append(metadataInput).appendTo('body'); form.submit(); }, /* Disables form elements: - Caches element value in 'ujs:enable-with' data store - Replaces element text with value of 'data-disable-with' attribute - Sets disabled property to true */ disableFormElements: function(form) { form.find(rails.disableSelector).each(function() { var element = $(this), method = element.is('button') ? 'html' : 'val'; element.data('ujs:enable-with', element[method]()); element[method](element.data('disable-with')); element.prop('disabled', true); }); }, /* Re-enables disabled form elements: - Replaces element text with cached value from 'ujs:enable-with' data store (created in `disableFormElements`) - Sets disabled property to false */ enableFormElements: function(form) { form.find(rails.enableSelector).each(function() { var element = $(this), method = element.is('button') ? 'html' : 'val'; if (element.data('ujs:enable-with')) element[method](element.data('ujs:enable-with')); element.prop('disabled', false); }); }, /* For 'data-confirm' attribute: - Fires `confirm` event - Shows the confirmation dialog - Fires the `confirm:complete` event Returns `true` if no function stops the chain and user chose yes; `false` otherwise. Attaching a handler to the element's `confirm` event that returns a `falsy` value cancels the confirmation dialog. Attaching a handler to the element's `confirm:complete` event that returns a `falsy` value makes this function return false. The `confirm:complete` event is fired whether or not the user answered true or false to the dialog. */ allowAction: function(element) { var message = element.data('confirm'), answer = false, callback; if (!message) { return true; } if (rails.fire(element, 'confirm')) { answer = rails.confirm(message); callback = rails.fire(element, 'confirm:complete', [answer]); } return answer && callback; }, // Helper function which checks for blank inputs in a form that match the specified CSS selector blankInputs: function(form, specifiedSelector, nonBlank) { var inputs = $(), input, valueToCheck, selector = specifiedSelector || 'input,textarea', allInputs = form.find(selector); allInputs.each(function() { input = $(this); valueToCheck = input.is('input[type=checkbox],input[type=radio]') ? input.is(':checked') : input.val(); // If nonBlank and valueToCheck are both truthy, or nonBlank and valueToCheck are both falsey if (!valueToCheck === !nonBlank) { // Don't count unchecked required radio if other radio with same name is checked if (input.is('input[type=radio]') && allInputs.filter('input[type=radio]:checked[name="' + input.attr('name') + '"]').length) { return true; // Skip to next input } inputs = inputs.add(input); } }); return inputs.length ? inputs : false; }, // Helper function which checks for non-blank inputs in a form that match the specified CSS selector nonBlankInputs: function(form, specifiedSelector) { return rails.blankInputs(form, specifiedSelector, true); // true specifies nonBlank }, // Helper function, needed to provide consistent behavior in IE stopEverything: function(e) { $(e.target).trigger('ujs:everythingStopped'); e.stopImmediatePropagation(); return false; }, // replace element's html with the 'data-disable-with' after storing original html // and prevent clicking on it disableElement: function(element) { element.data('ujs:enable-with', element.html()); // store enabled state element.html(element.data('disable-with')); // set to disabled state element.bind('click.railsDisable', function(e) { // prevent further clicking return rails.stopEverything(e); }); }, // restore element to its original state which was disabled by 'disableElement' above enableElement: function(element) { if (element.data('ujs:enable-with') !== undefined) { element.html(element.data('ujs:enable-with')); // set to old enabled state element.removeData('ujs:enable-with'); // clean up cache } element.unbind('click.railsDisable'); // enable element } }; if (rails.fire($document, 'rails:attachBindings')) { $.ajaxPrefilter(function(options, originalOptions, xhr){ if ( !options.crossDomain ) { rails.CSRFProtection(xhr); }}); $document.delegate(rails.linkDisableSelector, 'ajax:complete', function() { rails.enableElement($(this)); }); $document.delegate(rails.linkClickSelector, 'click.rails', function(e) { var link = $(this), method = link.data('method'), data = link.data('params'), metaClick = e.metaKey || e.ctrlKey; if (!rails.allowAction(link)) return rails.stopEverything(e); if (!metaClick && link.is(rails.linkDisableSelector)) rails.disableElement(link); if (link.data('remote') !== undefined) { if (metaClick && (!method || method === 'GET') && !data) { return true; } var handleRemote = rails.handleRemote(link); // response from rails.handleRemote() will either be false or a deferred object promise. if (handleRemote === false) { rails.enableElement(link); } else { handleRemote.error( function() { rails.enableElement(link); } ); } return false; } else if (link.data('method')) { rails.handleMethod(link); return false; } }); $document.delegate(rails.buttonClickSelector, 'click.rails', function(e) { var button = $(this); if (!rails.allowAction(button)) return rails.stopEverything(e); rails.handleRemote(button); return false; }); $document.delegate(rails.inputChangeSelector, 'change.rails', function(e) { var link = $(this); if (!rails.allowAction(link)) return rails.stopEverything(e); rails.handleRemote(link); return false; }); $document.delegate(rails.formSubmitSelector, 'submit.rails', function(e) { var form = $(this), remote = form.data('remote') !== undefined, blankRequiredInputs = rails.blankInputs(form, rails.requiredInputSelector), nonBlankFileInputs = rails.nonBlankInputs(form, rails.fileInputSelector); if (!rails.allowAction(form)) return rails.stopEverything(e); // skip other logic when required values are missing or file upload is present if (blankRequiredInputs && form.attr("novalidate") == undefined && rails.fire(form, 'ajax:aborted:required', [blankRequiredInputs])) { return rails.stopEverything(e); } if (remote) { if (nonBlankFileInputs) { // slight timeout so that the submit button gets properly serialized // (make it easy for event handler to serialize form without disabled values) setTimeout(function(){ rails.disableFormElements(form); }, 13); var aborted = rails.fire(form, 'ajax:aborted:file', [nonBlankFileInputs]); // re-enable form elements if event bindings return false (canceling normal form submission) if (!aborted) { setTimeout(function(){ rails.enableFormElements(form); }, 13); } return aborted; } rails.handleRemote(form); return false; } else { // slight timeout so that the submit button gets properly serialized setTimeout(function(){ rails.disableFormElements(form); }, 13); } }); $document.delegate(rails.formInputClickSelector, 'click.rails', function(event) { var button = $(this); if (!rails.allowAction(button)) return rails.stopEverything(event); // register the pressed submit button var name = button.attr('name'), data = name ? {name:name, value:button.val()} : null; button.closest('form').data('ujs:submit-button', data); }); $document.delegate(rails.formSubmitSelector, 'ajax:beforeSend.rails', function(event) { if (this == event.target) rails.disableFormElements($(this)); }); $document.delegate(rails.formSubmitSelector, 'ajax:complete.rails', function(event) { if (this == event.target) rails.enableFormElements($(this)); }); $(function(){ rails.refreshCSRFTokens(); }); } })( jQuery ); (function() { var CSRFToken, Click, ComponentUrl, Link, browserCompatibleDocumentParser, browserIsntBuggy, browserSupportsCustomEvents, browserSupportsPushState, browserSupportsTurbolinks, bypassOnLoadPopstate, cacheCurrentPage, cacheSize, changePage, constrainPageCacheTo, createDocument, currentState, enableTransitionCache, executeScriptTags, extractTitleAndBody, fetch, fetchHistory, fetchReplacement, historyStateIsDefined, initializeTurbolinks, installDocumentReadyPageEventTriggers, installHistoryChangeHandler, installJqueryAjaxSuccessPageUpdateTrigger, loadedAssets, pageCache, pageChangePrevented, pagesCached, popCookie, processResponse, recallScrollPosition, referer, reflectNewUrl, reflectRedirectedUrl, rememberCurrentState, rememberCurrentUrl, rememberReferer, removeNoscriptTags, requestMethodIsSafe, resetScrollPosition, transitionCacheEnabled, transitionCacheFor, triggerEvent, visit, xhr, _ref, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, __slice = [].slice; pageCache = {}; cacheSize = 10; transitionCacheEnabled = false; currentState = null; loadedAssets = null; referer = null; createDocument = null; xhr = null; fetch = function(url) { var cachedPage; url = new ComponentUrl(url); rememberReferer(); cacheCurrentPage(); reflectNewUrl(url); if (transitionCacheEnabled && (cachedPage = transitionCacheFor(url.absolute))) { fetchHistory(cachedPage); return fetchReplacement(url); } else { return fetchReplacement(url, resetScrollPosition); } }; transitionCacheFor = function(url) { var cachedPage; cachedPage = pageCache[url]; if (cachedPage && !cachedPage.transitionCacheDisabled) { return cachedPage; } }; enableTransitionCache = function(enable) { if (enable == null) { enable = true; } return transitionCacheEnabled = enable; }; fetchReplacement = function(url, onLoadFunction) { if (onLoadFunction == null) { onLoadFunction = (function(_this) { return function() {}; })(this); } triggerEvent('page:fetch', { url: url.absolute }); if (xhr != null) { xhr.abort(); } xhr = new XMLHttpRequest; xhr.open('GET', url.withoutHashForIE10compatibility(), true); xhr.setRequestHeader('Accept', 'text/html, application/xhtml+xml, application/xml'); xhr.setRequestHeader('X-XHR-Referer', referer); xhr.onload = function() { var doc; triggerEvent('page:receive'); if (doc = processResponse()) { changePage.apply(null, extractTitleAndBody(doc)); reflectRedirectedUrl(); onLoadFunction(); return triggerEvent('page:load'); } else { return document.location.href = url.absolute; } }; xhr.onloadend = function() { return xhr = null; }; xhr.onerror = function() { return document.location.href = url.absolute; }; return xhr.send(); }; fetchHistory = function(cachedPage) { if (xhr != null) { xhr.abort(); } changePage(cachedPage.title, cachedPage.body); recallScrollPosition(cachedPage); return triggerEvent('page:restore'); }; cacheCurrentPage = function() { var currentStateUrl; currentStateUrl = new ComponentUrl(currentState.url); pageCache[currentStateUrl.absolute] = { url: currentStateUrl.relative, body: document.body, title: document.title, positionY: window.pageYOffset, positionX: window.pageXOffset, cachedAt: new Date().getTime(), transitionCacheDisabled: document.querySelector('[data-no-transition-cache]') != null }; return constrainPageCacheTo(cacheSize); }; pagesCached = function(size) { if (size == null) { size = cacheSize; } if (/^[\d]+$/.test(size)) { return cacheSize = parseInt(size); } }; constrainPageCacheTo = function(limit) { var cacheTimesRecentFirst, key, pageCacheKeys, _i, _len, _results; pageCacheKeys = Object.keys(pageCache); cacheTimesRecentFirst = pageCacheKeys.map(function(url) { return pageCache[url].cachedAt; }).sort(function(a, b) { return b - a; }); _results = []; for (_i = 0, _len = pageCacheKeys.length; _i < _len; _i++) { key = pageCacheKeys[_i]; if (!(pageCache[key].cachedAt <= cacheTimesRecentFirst[limit])) { continue; } triggerEvent('page:expire', pageCache[key]); _results.push(delete pageCache[key]); } return _results; }; changePage = function(title, body, csrfToken, runScripts) { document.title = title; document.documentElement.replaceChild(body, document.body); if (csrfToken != null) { CSRFToken.update(csrfToken); } if (runScripts) { executeScriptTags(); } currentState = window.history.state; triggerEvent('page:change'); return triggerEvent('page:update'); }; executeScriptTags = function() { var attr, copy, nextSibling, parentNode, script, scripts, _i, _j, _len, _len1, _ref, _ref1; scripts = Array.prototype.slice.call(document.body.querySelectorAll('script:not([data-turbolinks-eval="false"])')); for (_i = 0, _len = scripts.length; _i < _len; _i++) { script = scripts[_i]; if (!((_ref = script.type) === '' || _ref === 'text/javascript')) { continue; } copy = document.createElement('script'); _ref1 = script.attributes; for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { attr = _ref1[_j]; copy.setAttribute(attr.name, attr.value); } copy.appendChild(document.createTextNode(script.innerHTML)); parentNode = script.parentNode, nextSibling = script.nextSibling; parentNode.removeChild(script); parentNode.insertBefore(copy, nextSibling); } }; removeNoscriptTags = function(node) { node.innerHTML = node.innerHTML.replace(/<noscript[\S\s]*?<\/noscript>/ig, ''); return node; }; reflectNewUrl = function(url) { if ((url = new ComponentUrl(url)).absolute !== referer) { return window.history.pushState({ turbolinks: true, url: url.absolute }, '', url.absolute); } }; reflectRedirectedUrl = function() { var location, preservedHash; if (location = xhr.getResponseHeader('X-XHR-Redirected-To')) { location = new ComponentUrl(location); preservedHash = location.hasNoHash() ? document.location.hash : ''; return window.history.replaceState(currentState, '', location.href + preservedHash); } }; rememberReferer = function() { return referer = document.location.href; }; rememberCurrentUrl = function() { return window.history.replaceState({ turbolinks: true, url: document.location.href }, '', document.location.href); }; rememberCurrentState = function() { return currentState = window.history.state; }; recallScrollPosition = function(page) { return window.scrollTo(page.positionX, page.positionY); }; resetScrollPosition = function() { if (document.location.hash) { return document.location.href = document.location.href; } else { return window.scrollTo(0, 0); } }; popCookie = function(name) { var value, _ref; value = ((_ref = document.cookie.match(new RegExp(name + "=(\\w+)"))) != null ? _ref[1].toUpperCase() : void 0) || ''; document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/'; return value; }; triggerEvent = function(name, data) { var event; event = document.createEvent('Events'); if (data) { event.data = data; } event.initEvent(name, true, true); return document.dispatchEvent(event); }; pageChangePrevented = function() { return !triggerEvent('page:before-change'); }; processResponse = function() { var assetsChanged, clientOrServerError, doc, extractTrackAssets, intersection, validContent; clientOrServerError = function() { var _ref; return (400 <= (_ref = xhr.status) && _ref < 600); }; validContent = function() { return xhr.getResponseHeader('Content-Type').match(/^(?:text\/html|application\/xhtml\+xml|application\/xml)(?:;|$)/); }; extractTrackAssets = function(doc) { var node, _i, _len, _ref, _results; _ref = doc.head.childNodes; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { node = _ref[_i]; if ((typeof node.getAttribute === "function" ? node.getAttribute('data-turbolinks-track') : void 0) != null) { _results.push(node.getAttribute('src') || node.getAttribute('href')); } } return _results; }; assetsChanged = function(doc) { var fetchedAssets; loadedAssets || (loadedAssets = extractTrackAssets(document)); fetchedAssets = extractTrackAssets(doc); return fetchedAssets.length !== loadedAssets.length || intersection(fetchedAssets, loadedAssets).length !== loadedAssets.length; }; intersection = function(a, b) { var value, _i, _len, _ref, _results; if (a.length > b.length) { _ref = [b, a], a = _ref[0], b = _ref[1]; } _results = []; for (_i = 0, _len = a.length; _i < _len; _i++) { value = a[_i]; if (__indexOf.call(b, value) >= 0) { _results.push(value); } } return _results; }; if (!clientOrServerError() && validContent()) { doc = createDocument(xhr.responseText); if (doc && !assetsChanged(doc)) { return doc; } } }; extractTitleAndBody = function(doc) { var title; title = doc.querySelector('title'); return [title != null ? title.textContent : void 0, removeNoscriptTags(doc.body), CSRFToken.get(doc).token, 'runScripts']; }; CSRFToken = { get: function(doc) { var tag; if (doc == null) { doc = document; } return { node: tag = doc.querySelector('meta[name="csrf-token"]'), token: tag != null ? typeof tag.getAttribute === "function" ? tag.getAttribute('content') : void 0 : void 0 }; }, update: function(latest) { var current; current = this.get(); if ((current.token != null) && (latest != null) && current.token !== latest) { return current.node.setAttribute('content', latest); } } }; browserCompatibleDocumentParser = function() { var createDocumentUsingDOM, createDocumentUsingParser, createDocumentUsingWrite, e, testDoc, _ref; createDocumentUsingParser = function(html) { return (new DOMParser).parseFromString(html, 'text/html'); }; createDocumentUsingDOM = function(html) { var doc; doc = document.implementation.createHTMLDocument(''); doc.documentElement.innerHTML = html; return doc; }; createDocumentUsingWrite = function(html) { var doc; doc = document.implementation.createHTMLDocument(''); doc.open('replace'); doc.write(html); doc.close(); return doc; }; try { if (window.DOMParser) { testDoc = createDocumentUsingParser('<html><body><p>test'); return createDocumentUsingParser; } } catch (_error) { e = _error; testDoc = createDocumentUsingDOM('<html><body><p>test'); return createDocumentUsingDOM; } finally { if ((testDoc != null ? (_ref = testDoc.body) != null ? _ref.childNodes.length : void 0 : void 0) !== 1) { return createDocumentUsingWrite; } } }; ComponentUrl = (function() { function ComponentUrl(original) { this.original = original != null ? original : document.location.href; if (this.original.constructor === ComponentUrl) { return this.original; } this._parse(); } ComponentUrl.prototype.withoutHash = function() { return this.href.replace(this.hash, ''); }; ComponentUrl.prototype.withoutHashForIE10compatibility = function() { return this.withoutHash(); }; ComponentUrl.prototype.hasNoHash = function() { return this.hash.length === 0; }; ComponentUrl.prototype._parse = function() { var _ref; (this.link != null ? this.link : this.link = document.createElement('a')).href = this.original; _ref = this.link, this.href = _ref.href, this.protocol = _ref.protocol, this.host = _ref.host, this.hostname = _ref.hostname, this.port = _ref.port, this.pathname = _ref.pathname, this.search = _ref.search, this.hash = _ref.hash; this.origin = [this.protocol, '//', this.hostname].join(''); if (this.port.length !== 0) { this.origin += ":" + this.port; } this.relative = [this.pathname, this.search, this.hash].join(''); return this.absolute = this.href; }; return ComponentUrl; })(); Link = (function(_super) { __extends(Link, _super); Link.HTML_EXTENSIONS = ['html']; Link.allowExtensions = function() { var extension, extensions, _i, _len; extensions = 1 <= arguments.length ? __slice.call(arguments, 0) : []; for (_i = 0, _len = extensions.length; _i < _len; _i++) { extension = extensions[_i]; Link.HTML_EXTENSIONS.push(extension); } return Link.HTML_EXTENSIONS; }; function Link(link) { this.link = link; if (this.link.constructor === Link) { return this.link; } this.original = this.link.href; Link.__super__.constructor.apply(this, arguments); } Link.prototype.shouldIgnore = function() { return this._crossOrigin() || this._anchored() || this._nonHtml() || this._optOut() || this._target(); }; Link.prototype._crossOrigin = function() { return this.origin !== (new ComponentUrl).origin; }; Link.prototype._anchored = function() { var current; return ((this.hash && this.withoutHash()) === (current = new ComponentUrl).withoutHash()) || (this.href === current.href + '#'); }; Link.prototype._nonHtml = function() { return this.pathname.match(/\.[a-z]+$/g) && !this.pathname.match(new RegExp("\\.(?:" + (Link.HTML_EXTENSIONS.join('|')) + ")?$", 'g')); }; Link.prototype._optOut = function() { var ignore, link; link = this.link; while (!(ignore || link === document)) { ignore = link.getAttribute('data-no-turbolink') != null; link = link.parentNode; } return ignore; }; Link.prototype._target = function() { return this.link.target.length !== 0; }; return Link; })(ComponentUrl); Click = (function() { Click.installHandlerLast = function(event) { if (!event.defaultPrevented) { document.removeEventListener('click', Click.handle, false); return document.addEventListener('click', Click.handle, false); } }; Click.handle = function(event) { return new Click(event); }; function Click(event) { this.event = event; if (this.event.defaultPrevented) { return; } this._extractLink(); if (this._validForTurbolinks()) { if (!pageChangePrevented()) { visit(this.link.href); } this.event.preventDefault(); } } Click.prototype._extractLink = function() { var link; link = this.event.target; while (!(!link.parentNode || link.nodeName === 'A')) { link = link.parentNode; } if (link.nodeName === 'A' && link.href.length !== 0) { return this.link = new Link(link); } }; Click.prototype._validForTurbolinks = function() { return (this.link != null) && !(this.link.shouldIgnore() || this._nonStandardClick()); }; Click.prototype._nonStandardClick = function() { return this.event.which > 1 || this.event.metaKey || this.event.ctrlKey || this.event.shiftKey || this.event.altKey; }; return Click; })(); bypassOnLoadPopstate = function(fn) { return setTimeout(fn, 500); }; installDocumentReadyPageEventTriggers = function() { return document.addEventListener('DOMContentLoaded', (function() { triggerEvent('page:change'); return triggerEvent('page:update'); }), true); }; installJqueryAjaxSuccessPageUpdateTrigger = function() { if (typeof jQuery !== 'undefined') { return jQuery(document).on('ajaxSuccess', function(event, xhr, settings) { if (!jQuery.trim(xhr.responseText)) { return; } return triggerEvent('page:update'); }); } }; installHistoryChangeHandler = function(event) { var cachedPage, _ref; if ((_ref = event.state) != null ? _ref.turbolinks : void 0) { if (cachedPage = pageCache[(new ComponentUrl(event.state.url)).absolute]) { cacheCurrentPage(); return fetchHistory(cachedPage); } else { return visit(event.target.location.href); } } }; initializeTurbolinks = function() { rememberCurrentUrl(); rememberCurrentState(); createDocument = browserCompatibleDocumentParser(); document.addEventListener('click', Click.installHandlerLast, true); return bypassOnLoadPopstate(function() { return window.addEventListener('popstate', installHistoryChangeHandler, false); }); }; historyStateIsDefined = window.history.state !== void 0 || navigator.userAgent.match(/Firefox\/2[6|7]/); browserSupportsPushState = window.history && window.history.pushState && window.history.replaceState && historyStateIsDefined; browserIsntBuggy = !navigator.userAgent.match(/CriOS\//); requestMethodIsSafe = (_ref = popCookie('request_method')) === 'GET' || _ref === ''; browserSupportsTurbolinks = browserSupportsPushState && browserIsntBuggy && requestMethodIsSafe; browserSupportsCustomEvents = document.addEventListener && document.createEvent; if (browserSupportsCustomEvents) { installDocumentReadyPageEventTriggers(); installJqueryAjaxSuccessPageUpdateTrigger(); } if (browserSupportsTurbolinks) { visit = fetch; initializeTurbolinks(); } else { visit = function(url) { return document.location.href = url; }; } this.Turbolinks = { visit: visit, pagesCached: pagesCached, enableTransitionCache: enableTransitionCache, allowLinkExtensions: Link.allowExtensions, supported: browserSupportsTurbolinks }; }).call(this); (function() { }).call(this); // This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // ;
// @flow import FetcherBase from '../rb-appbase-universal/fetcherBase' export default class FetcherClient extends FetcherBase { constructor( url: string, payloads: any, UserToken1: ?string, UserToken2: string ) { super( url, UserToken1, UserToken2 ) this.payloads = payloads } async fetch( ...args: any ) { if ( this.payloads.length ) { return this.payloads.shift() } return super.fetch( ...args ) } }
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.7-6-a-58 description: > Object.defineProperties - desc.[[Get]] and P.[[Get]] are two objects which refer to the different objects (8.12.9 step 6) includes: [runTestCase.js] ---*/ function testcase() { var obj = {}; function get_Func1() { return 10; } Object.defineProperty(obj, "foo", { get: get_Func1, configurable: true }); function get_Func2() { return 20; } Object.defineProperties(obj, { foo: { get: get_Func2 } }); var verifyEnumerable = false; for (var p in obj) { if (p === "foo") { verifyEnumerable = true; } } var verifyValue = false; verifyValue = (obj.foo === 20); var desc = Object.getOwnPropertyDescriptor(obj, "foo"); var verifyConfigurable = false; delete obj.foo; verifyConfigurable = obj.hasOwnProperty("foo"); return !verifyConfigurable && !verifyEnumerable && verifyValue && typeof (desc.set) === "undefined" && desc.get === get_Func2; } runTestCase(testcase);
/*jshint node:true*/ 'use strict'; module.exports = function(config) { return { compass: { files: [config.source + '/scss/**/*.{scss,sass}'], tasks: ['compass:server'] }, haychtml: { files: [config.pages + '/*.html'], tasks: ['haychtml'] }, livereload: { options: { livereload: config.livereloadPort }, files: [ config.deploy + '/*.html', config.deploy + '/static/{,*/}*.{css,js,png,jpg,jpeg,gif,webp,svg}' ] } } };
//= require modernizr /* * Test for SubPixel Font Rendering * (to infer if GDI or DirectWrite is used on Windows) * Authors: @derSchepp, @gerritvanaaken, @rodneyrehm, @yatil, @ryanseddon * Web: https://github.com/gerritvanaaken/subpixeldetect */ Modernizr.addTest('subpixelfont', function() { var bool, styles = "#modernizr{position: absolute; top: -10em; visibility:hidden; font: normal 10px arial;}#subpixel{float: left; font-size: 33.3333%;}"; // see https://github.com/Modernizr/Modernizr/blob/master/modernizr.js#L97 Modernizr.testStyles(styles, function(elem) { var subpixel = elem.firstChild; subpixel.innerHTML = 'This is a text written in Arial'; bool = window.getComputedStyle ? window.getComputedStyle(subpixel, null).getPropertyValue("width") !== '44px' : false; }, 1, ['subpixel']); return bool; });
'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.hogan_static = { setUp: function(done) { // setup here if necessary done(); }, default_options: function(test) { test.expect(2); var actual = grunt.file.read('tmp/simple.html'), expected = grunt.file.read('test/expected/simple.html'); test.equal(actual, expected, 'should properly handle simple templating.'); actual = grunt.file.read('tmp/array.html'); expected = grunt.file.read('test/expected/array.html'); test.equal(actual, expected, 'should properly handle array of options data.'); test.done(); }, partials: function(test) { test.expect(1); var actual = grunt.file.read('tmp/partials.html'), expected = grunt.file.read('test/expected/partials.html'); test.equal(actual, expected, 'should properly handle partial templates.'); test.done(); }, externalPartials: function(test) { test.expect(1); var actual = grunt.file.read('tmp/extPartials.html'), expected = grunt.file.read('test/expected/partials.html'); test.equal(actual, expected, 'should properly handle partial templates.'); test.done(); }, externalJson: function(test) { test.expect(1); var actual = grunt.file.read('tmp/extJSON.html'), expected = grunt.file.read('test/expected/simple.html'); test.equal(actual, expected, 'should properly handle external JSON data'); test.done(); }, delimiters: function(test) { test.expect(1); var actual = grunt.file.read('tmp/delimiters.html'), expected = grunt.file.read('test/expected/delimiters.html'); test.equal(actual, expected, 'should properly handle delimiter change.'); test.done(); }, perFileData: function(test) { test.expect(3); var actual = grunt.file.read('tmp/test1.html'), expected = grunt.file.read('test/expected/test1.html'); test.equal(actual, expected, 'should properly handle per file data'); actual = grunt.file.read('tmp/test2.html'); expected = grunt.file.read('test/expected/test2.html'); test.equal(actual, expected, 'should properly handle per file data'); actual = grunt.file.read('tmp/test3.html'); expected = grunt.file.read('test/expected/test3.html'); test.equal(actual, expected, 'should properly handle per file data'); test.done(); } };
// Automatically generated by scripts/createStyleInterpolations.js at Tue Jun 20 2017 00:01:09 GMT+0900 (JST) // Imported atelier-sulphurpool-dark.css file from highlight.js export default ` /* Base16 Atelier Sulphurpool Dark - Theme */ /* by Bram de Haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/sulphurpool) */ /* Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ /* Atelier-Sulphurpool Comment */ .hljs-comment, .hljs-quote { color: #898ea4; } /* Atelier-Sulphurpool Red */ .hljs-variable, .hljs-template-variable, .hljs-attribute, .hljs-tag, .hljs-name, .hljs-regexp, .hljs-link, .hljs-name, .hljs-selector-id, .hljs-selector-class { color: #c94922; } /* Atelier-Sulphurpool Orange */ .hljs-number, .hljs-meta, .hljs-built_in, .hljs-builtin-name, .hljs-literal, .hljs-type, .hljs-params { color: #c76b29; } /* Atelier-Sulphurpool Green */ .hljs-string, .hljs-symbol, .hljs-bullet { color: #ac9739; } /* Atelier-Sulphurpool Blue */ .hljs-title, .hljs-section { color: #3d8fd1; } /* Atelier-Sulphurpool Purple */ .hljs-keyword, .hljs-selector-tag { color: #6679cc; } .hljs { display: block; overflow-x: auto; background: #202746; color: #979db4; padding: 0.5em; } .hljs-emphasis { font-style: italic; } .hljs-strong { font-weight: bold; } `
var pkg = require('../package.json'); var txtdmn = pkg.theme_infos.textdomain; var setupindexphp = ['<?php', '/**', '* The main app file', '*', '@package '+pkg.name, '@since '+pkg.version, '*/', 'get_header();', '?>', '', '', '<!-- Example Top navbar fixed-->', '<header>', ' <div class="navbar-fixed">', ' <nav>', ' <div class="nav-wrapper">', ' <a href="#!" class="brand-logo">Logo</a>', ' <ul class="right hide-on-med-and-down">', ' <li><a href="#">Link1</a></li>', ' <li><a href="#">Link2</a></li>', ' </ul>', ' </div>', ' </nav>', ' </div>', ' <h1 class="center">'+pkg.name+'</h1>', '</header>', '', '', '', '<main class="row">', ' <router-view></router-view>', '</main>', '', '', '<?php get_footer();', ''] .join('\n'); exports.setupindexphp = setupindexphp; var setupheaderphp = ['<?php', '/**', '* Header file', '*', '@package '+pkg.name, '@since '+pkg.version, '*/', '?>', '<!DOCTYPE html>', '<html <?php language_attributes(); ?>>', ' <head>', ' <meta name="viewport" content="width=device-width, initial-scale=1" />', ' <?php wp_head(); ?>', ' </head>', ' <body>', ''] .join('\n'); exports.setupheaderphp = setupheaderphp; var setupfooterphp = ['<?php', '/**', '* Footer file', '*', '@package '+pkg.name, '@since '+pkg.version, '*/', '?>', ' <footer>', ' </footer>', ' <script src="https://code.createjs.com/preloadjs-0.6.2.min.js"></script>', ' <?php wp_footer(); ?>', '</body>', ''] .join('\n'); exports.setupfooterphp = setupfooterphp; var setupfuncphp = ['<?php', '// Useful global constants', '', 'define( "'+ txtdmn.toUpperCase()+'_VERSION","0.1.0" );', 'define( "'+ txtdmn.toUpperCase()+'_URL",get_stylesheet_directory_uri() );', 'define( "'+ txtdmn.toUpperCase()+'_TEMPLATE_URL", get_template_directory_uri() );', 'define( "'+ txtdmn.toUpperCase()+'_PATH",get_template_directory() . "/" );', 'define( "'+ txtdmn.toUpperCase()+'_INC",'+ txtdmn.toUpperCase()+'_PATH . "includes/" );', '', '', '/*************** ADD WORDPRESS SUPPORT', '***************************/', 'add_theme_support("post-thumbnails");', '', '', 'if( function_exists("register_api_field") ):', 'add_action( "init", "better_rest_api_featured_images_init", 12 );', '/**', '* Register our enhanced better_featured_image field to all public post types', '* that support post thumbnails.', '*', '* @since 1.0.0', '*/', 'function better_rest_api_featured_images_init() {', ' $post_types = get_post_types( array( "public" => true ), "objects" );', ' foreach ( $post_types as $post_type ) {', ' $post_type_name = $post_type->name;', ' $show_in_rest = ( isset( $post_type->show_in_rest ) && $post_type->show_in_rest ) ? true : false;', ' $supports_thumbnail = post_type_supports( $post_type_name, "thumbnail" );', ' // Only proceed if the post type is set to be accessible over the REST API', ' // and supports featured images.', ' if ( $show_in_rest && $supports_thumbnail ) {', ' // Compatibility with the REST API v2 beta 9+', ' if ( function_exists( "register_rest_field" ) ) {', ' register_rest_field( $post_type_name,', ' "post_images",', ' array(', ' "get_callback" => "better_rest_api_featured_images_get_field",', ' "schema" => null,', ' )', ' );', ' } elseif ( function_exists( "register_api_field" ) ) {', ' register_api_field( $post_type_name,', ' "post_images",', ' array(', ' "get_callback" => "better_rest_api_featured_images_get_field",', ' "schema" => null,', ' )', ' );', ' }', ' }', ' }', '}', '/**', '* Return the better_featured_image field.', '*', '* @since 1.0.0', '*', '* @return object|0', '*/', 'function better_rest_api_featured_images_get_field( $object, $field_name, $request ) {', ' // Only proceed if the post has a featured image.', ' if ( $object["featured_media"] ) {', ' $image_id = (int)$object["featured_media"];', ' } else {', ' return null;', ' }', ' $image = get_post( $image_id );', ' if ( ! $image ) {', ' return null;', ' }', ' // This is taken from WP_REST_Attachments_Controller::prepare_item_for_response()', ' $featured_image["id"] = $image_id;', ' $featured_image["alt_text"] = get_post_meta( $image_id, "_wp_attachment_image_alt", true );', ' $featured_image["caption"] = $image->post_excerpt;', ' $featured_image["description"] = $image->post_content;', ' $featured_image["media_type"] = wp_attachment_is_image( $image_id ) ? "image" : "file";', ' $featured_image["media_details"] = wp_get_attachment_metadata( $image_id );', ' $featured_image["post"] = ! empty( $image->post_parent ) ? (int) $image->post_parent : null;', ' $featured_image["source_url"] = wp_get_attachment_url( $image_id );', ' if ( empty( $featured_image["media_details"] ) ) {', ' $featured_image["media_details"] = new stdClass;', ' } elseif ( ! empty( $featured_image["media_details"]["sizes"] ) ) {', ' $img_url_basename = wp_basename( $featured_image["source_url"] );', ' foreach ( $featured_image["media_details"]["sizes"] as $size => &$size_data ) {', ' $image_src = wp_get_attachment_image_src( $image_id, $size );', ' if ( ! $image_src ) {', ' continue;', ' }', ' $size_data["source_url"] = $image_src[0];', ' }', ' } else {', ' $featured_image["media_details"]["sizes"] = new stdClass;', ' }', ' return $featured_image;', '}', 'endif;', '', '', '/**', '* Register an event example post type, with REST API support', '*', '* Based on example at: http://codex.wordpress.org/Function_Reference/register_post_type', '*/', 'add_action( "init", "my_event_cpt" );', 'function my_event_cpt() {', '$labels = array(', '"name" => _x( "events", "post type general name", "'+txtdmn+'" ),', '"singular_name" => _x( "event", "post type singular name", "'+txtdmn+'" ),', '"menu_name" => _x( "events", "admin menu", "'+txtdmn+'" ),', '"name_admin_bar" => _x( "event", "add new on admin bar", "'+txtdmn+'" ),', '"add_new" => _x( "Add New", "event", "'+txtdmn+'" ),', '"add_new_item" => __( "Add New event", "'+txtdmn+'" ),', '"new_item" => __( "New event", "'+txtdmn+'" ),', '"edit_item" => __( "Edit event", "'+txtdmn+'" ),', '"view_item" => __( "View event", "'+txtdmn+'" ),', '"all_items" => __( "All events", "'+txtdmn+'" ),', '"search_items" => __( "Search events", "'+txtdmn+'" ),', '"parent_item_colon" => __( "Parent events:", "'+txtdmn+'" ),', '"not_found" => __( "No events found.", "'+txtdmn+'" ),', '"not_found_in_trash" => __( "No events found in Trash.", "'+txtdmn+'" )', ');', '$args = array(', '"labels" => $labels,', '"description" => __( "Description.", "'+txtdmn+'" ),', '"public" => true,', '"publicly_queryable" => true,', '"show_ui" => true,', '"show_in_menu" => true,', '"query_var" => true,', '"rewrite" => array( "slug" => "event" ),', '"capability_type" => "post",', '"has_archive" => true,', '"hierarchical" => false,', '"menu_position" => null,', '"show_in_rest" => true,', '"rest_base" => "events-api",', '"rest_controller_class" => "WP_REST_Posts_Controller",', '"supports" => array( "title", "editor", "author", "thumbnail", "excerpt", "comments" )', ');', 'register_post_type( "event", $args );', '}', '', '', '/*************** CUSTOM IMAGES SIZES', '***************************/', 'add_image_size("bgImage", 1440, 9999, false);', 'add_image_size("cardImage", 768,480, true);', '', '', '// Include compartmentalized functions', 'require_once '+ txtdmn.toUpperCase()+'_INC . "functions/core.php";', ''].join('\n'); exports.setupfuncphp = setupfuncphp ; var setupcorephp = ['<?php', '/**', '* Enqueue scripts for front-end.', '*', '* @uses wp_enqueue_script() to load front end scripts.', '*', '*', '* @param bool $debug Whether to enable loading uncompressed/debugging assets. Default true.', '* @return void', '*/', 'add_action( "wp_enqueue_scripts", "scripts");', 'add_action( "wp_enqueue_scripts", "styles" );', 'function scripts() {', ' $debug = true;', ' $min="";', ' if(!$debug){', ' $min =".min";', ' }', ' // We unregister Wordpress jquery script, because we need Jquery 2.x (included in our bundle.js) for materialize to work properly.', ' wp_deregister_script( "jquery" );', '', ' wp_enqueue_script(', ' "'+txtdmn+'",', ' '+ txtdmn.toUpperCase()+'_TEMPLATE_URL . "/assets/js/'+txtdmn+'{$min}.js",', ' array(),', ' '+txtdmn.toUpperCase()+'_VERSION,', ' true', ' );', '', ' // pass Ajax Url to script.js', ' wp_localize_script("'+txtdmn+'", "ajaxurl", admin_url( "admin-ajax.php" ) );', '}', '/**', '* Enqueue styles for front-end.', '*', '* @uses wp_enqueue_script() to load front end scripts.', '*', '* @param bool $debug Whether to enable loading uncompressed/debugging assets. Default true.', '* @return void', '*/', 'function styles() {', ' $debug = true;', ' $min="";', ' if(!$debug){', ' $min =".min";', ' }', ' wp_enqueue_style(', ' "'+txtdmn+'css",', ' '+ txtdmn.toUpperCase()+'_TEMPLATE_URL . "/assets/css/'+txtdmn+'{$min}.css",', ' array(),', ' '+txtdmn.toUpperCase()+'_VERSION', ' );', '', '}', ''].join('\n'); exports.setupcorephp = setupcorephp; var setupmainscss = ['/**', '* The main scss file', '*', '@package '+pkg.name, '@since '+pkg.version, '*/', '', '@import "../../../node_modules/bourbon/app/assets/stylesheets/bourbon";', '@import "../../../node_modules/materialize-css/sass/materialize";', '@import "scss/variables";', '@import "scss/mixins";', '@import "scss/global";', ''] .join('\n'); exports.setupmainscss = setupmainscss; var setupmainjs = ['/**', '* The main js file', '*', '@package '+pkg.name, '@since '+pkg.version, '*/', '', 'var $ = require("jquery");', 'require("materialize");', 'var Vue = require("vue");', 'window.Vue = Vue;', 'VueResource = require("vue-resource");', 'VueRouter = require("vue-router");', 'Vue.use(VueResource);', 'Vue.use(VueRouter);', '', '', '', '//get our vue components', 'var postsPage = require("../../vues/page-home.vue");', '// configure router', 'var router = new VueRouter({', ' history:true,', ' root: "/wordpress",', ' hashbang :false', '});', '', '', 'router.map({', ' "/": {', ' component: postsPage,', ' },', '});', '', '', '$(document).ready(function(){', ' // start app', ' var App = Vue.extend({});', ' router.start(App, "html");', '});', ''] .join('\n'); exports.setupmainjs = setupmainjs;
/** * @license angular-data-router v0.3.10 * (c) 2017 Michal Dvorak https://github.com/mdvorak/angular-data-router * License: MIT */ (function dataRouterModule(angular) { "use strict"; /** * @ngdoc overview * @name mdvorakDataRouter * @requires mdvorakDataApi * * @description * Angular Data Router module. You should configure it using * {@link mdvorakDataRouter.$dataRouterProvider $dataRouterProvider}. */ var module = angular.module("mdvorakDataRouter", ['mdvorakDataApi']); /** * @ngdoc service * @name mdvorakDataRouter.$dataRouterRegistryProvider * * @description * This is the place where media types are configured to the views. */ module.provider('$dataRouterRegistry', ["$$dataRouterMatchMap", function $dataRouterRegistryProvider($$dataRouterMatchMap) { var provider = this; var views = provider.$$views = $$dataRouterMatchMap.create(); // Expression taken from ngController directive var CTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/; // Creates copy of the configuration, preprocesses it and validates it provider.$$parseConfig = function $$parseConfig(config, mediaType) { // Make our copy config = angular.copy(config); // Validate if (angular.isString(config.controller)) { var ctrlMatch = config.controller.match(CTRL_REG); if (!ctrlMatch) { throw new Error("Badly formed controller string '" + config.controller + "' for route '" + mediaType + "'."); } if (ctrlMatch[3] && config.controllerAs) { throw new Error("Defined both controllerAs and 'controller as' expressions for route '" + mediaType + "'."); } // Reconfigure config.controller = ctrlMatch[1]; if (ctrlMatch[3]) config.controllerAs = ctrlMatch[3]; } return config; }; /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterRegistryProvider * @name when * * @description * Configures view for given content type. * * _Note: Wildcard or function matchers are much slower then exact match. The are iterated one by one, in order of registration. * Exact string matchers also always takes precedence over function matchers._ * * @param {String|Function} mediaType Content type to match. When there is no `/` in the string, it is considered * subtype of `application/` type. You should not include suffixes * like `+json`, they are ignored by the matcher. Wildcards using `*` are supported. * * It can be function with signature `[boolean] function([string])` as well. * * @param {Object} config Configuration object, similar to ngRoute one. Allowed keys are: * `template`, `templateUrl`, `controller`, `controllerAs`, `dataAs`, `responseAs`, * `resolve`, `transformResponse`, * where either `template` or `templateUrl` must be specified. * `template` has precedence over `templateUrl`. * `controller` is optional. Can be either String reference or declaration * according to `$injector` rules. `resolve` is map of resolvables, that are * resolved before controller is created, and are injected into controller. * Same behavior as in ngRoute. */ provider.when = function when(mediaType, config) { // Parse config = provider.$$parseConfig(config, mediaType); // Add if (angular.isFunction(mediaType)) { // Matcher function views.addMatcher(mediaType, config); } else { // Normalize mimeType mediaType = provider.normalizeMediaType(mediaType); // Register views.addMatcher(mediaType, config); } return provider; }; /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterRegistryProvider * @name error * * @description * Configures view for error page. Error page is displayed when resource or view template cannot be loaded or * any of the resolvables fails. * * @param {Number|String=} status HTTP response status code this error view is for. * It can be both number or string representing numeric value. In string, `'?'` char * can be used as substitution for any number, allowing to match multiple codes with * one definition. `'4??'` will match any 4xx error code. * This is optional argument, you should always have defined generic error view as well. * @param {Object} config Configuration object, as in * {@link mdvorakDataRouter.$dataRouterRegistryProvider#methods_when when(config)}. */ provider.error = function error(status, config) { var name = '$error'; if (angular.isObject(status)) { config = status; } else { name = '$error_' + status; } // Parse and add views.addMatcher(name, provider.$$parseConfig(config, name)); return provider; }; /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterRegistryProvider * @name normalizeMediaType * * @description * Normalizes the media type. Removes format suffix (everything after +), and prepends `application/` if there is * just subtype provided. * * @param {String} mimeType Media type to match. * @returns {String} Normalized media type. */ provider.normalizeMediaType = function normalizeMediaType(mimeType) { if (!mimeType) return null; // Get rid of + end everything after mimeType = mimeType.replace(/\s*[\+;].*$/, ''); // Prepend application/ if here is only subtype if (mimeType.indexOf('/') < 0) { mimeType = 'application/' + mimeType; } return mimeType; }; /** * @ngdoc service * @name mdvorakDataRouter.$dataRouterRegistry */ this.$get = function $dataRouterRegistryFactory() { return { /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterRegistry * @name normalizeMediaType * * @description * Normalizes the media type. Removes format suffix (everything after +), and prepends `application/` if there is * just subtype provided. * * @param {String} mimeType Media type to match. * @returns {String} Normalized media type. */ normalizeMediaType: provider.normalizeMediaType, /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterRegistry * @name match * * @description * Matches the media type against registered media types. If found, view configuration is return. * * @param {String} mediaType Media type to be matched. It *MUST* be normalized, it is compared as is. * @returns {Object} Matched view or undefined. Note that original configuration object will be returned, * so don't modify it! */ match: function match(mediaType) { return views.match(mediaType); }, /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterRegistry * @name isKnownType * * @description * Determines whether type matches a registered view. * * @param {String} mediaType Matched content type. Doesn't have to be normalized. * @returns {boolean} `true` if type is has registered view, `false` if no match was found. */ isKnownType: function isKnownType(mediaType) { return mediaType && !!this.match(provider.normalizeMediaType(mediaType)); } }; }; }]); /** * @ngdoc service * @name mdvorakDataRouter.$dataRouterLoaderProvider * * @description * Provider allows configuration of loading and resolving views. Note that media types are registered in * {@link mdvorakDataRouter.$dataRouterRegistryProvider $dataRouterRegistryProvider} and not here. */ module.provider('$dataRouterLoader', function dataRouterLoaderProvider() { var provider = this; var toString = Object.prototype.toString; provider.globals = Object.create(null); /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterLoaderProvider * @name global * * @description * Sets global configuration for all routes. It is then merged into each view configuration, with view taking precedence. * * _Note: This method is also available directly on `$dataRouter` to ease configuration._ * * @example * This example shows how to load additional data from URL provided in the response. `relatedData` object will be * then available in view controllers. * * ```js * $dataRouterLoader.global({ * resolve: { * relatedData: function($http, $data) { * if ($data._links && $data._links.related) { * return $http.get($data._links.related.href) * .then(function(response) { * return response.data; * }); * } * * return null; * } * } * }); * ``` * * @param {Object} config Configuration object. Properties of object type are merged together instead of overwriting. * @returns {Object} Reference to the provider. */ provider.global = function global(config) { if (!config) return provider; provider.globals = $$mergeConfigObjects(provider.globals, config); return provider; }; /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterLoaderProvider * @name extractType * * @description * Extracts media type from given response. Default implementation returns `Content-Type` header. * * @example * Example of custom implementation. * ```js * $dataRouterLoader.extractType = function extractTypeFromJson(response) { * return response.data && response.data._type; * }; * ``` * * @param {Object} response Response object, see `$http` documentation for details. * * _Note that while `response` itself is never null, data property can be._ * * @returns {String} Media type of the response. It will be normalized afterwards. If the return value is empty, * `application/octet-stream` will be used. */ provider.extractType = function extractTypeFromContentType(response) { return response.headers('Content-Type'); }; provider.responseExtensions = { dataAs: function dataAs(scope, name, listener) { var _this = this; scope[name] = _this.data; this.$on('$routeUpdate', function() { // Update data scope[name] = _this.data; if (angular.isFunction(listener)) { listener(_this.data); } }, scope); } }; /** * @ngdoc service * @name mdvorakDataRouter.$dataRouterLoader * * @description * Abstraction of data loading and view preparation. It uses views registered in * {@link mdvorakDataRouter.$dataRouterRegistry $dataRouterRegistry}. */ this.$get = ["$log", "$sce", "$http", "$templateCache", "$q", "$injector", "$rootScope", "$dataRouterRegistry", "$$dataRouterEventSupport", function $dataRouterLoaderFactory($log, $sce, $http, $templateCache, $q, $injector, $rootScope, $dataRouterRegistry, $$dataRouterEventSupport) { var $dataRouterLoader = { /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterLoader * @name normalizeMediaType * * @description * Normalizes the media type. Removes format suffix (everything after +), and prepends application/ if there is * just subtype. * * @param {String} mimeType Media type to match. * @returns {String} Normalized media type. */ normalizeMediaType: $dataRouterRegistry.normalizeMediaType, /** * Extracts media type from the response, using configured * {@link mdvorakDataRouter.$dataRouterLoaderProvider#methods_extractType method}. * Unlike on provider, this method returns the type already * {@link mdvorakDataRouter.$dataRouterRegistry#methods_normalizeMediaType normalized}. * * @param response {Object} Response object. * @returns {String} Normalized media type of the response or null if it cannot be determined. */ extractType: function extractType(response) { return $dataRouterRegistry.normalizeMediaType(provider.extractType(response)); }, /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterLoader * @name prefetchTemplate * * @description * Eagerly fetches the template for the given media type. If media type is unknown, nothing happens. * This method returns immediately, no promise is returned. * * @param {String} mediaType Media type for which we want to prefetch the template. */ prefetchTemplate: function prefetchTemplate(mediaType) { var view = $dataRouterRegistry.match(mediaType); if (view) { $log.debug("Pre-fetching template for " + mediaType); $dataRouterLoader.$$loadTemplate(view, mediaType); } else { $log.debug("Cannot prefetch template for " + mediaType + ", type is not registered"); } }, /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterLoader * @name prepareView * * @description * Prepares the view to be displayed. Loads data from given URL, resolves view by its content type, * and then finally resolves template and all other resolvables. * * @param {String} url URL of the data to be fetched. They are always loaded using GET method. * @param {Object=} current Current response data. If provided and forceReload is false, routeDataUpdate flag * of the response may be set, indicating that view doesn't have to be reloaded. * @param {boolean=} forceReload When false, it allows just data update. Without current parameter does nothing. * @returns {Object} Promise of completely initialized response, including template and locals. */ prepareView: function prepareView(url, current, forceReload) { // Load data and view return $dataRouterLoader.$$loadData(url) .then(loadDataSuccess) .then(null, loadError); // This must be in the chain after loadDataSuccess // Note: We are not chaining promises directly, instead we are returning them, // which works in the end the same. However, the chain is shorter in case of failure. function loadDataSuccess(response) { // It is worth continuing? // Check whether whole view needs to be refreshed if (!forceReload && isSameView(current, response)) { // Update data response.routeDataUpdate = true; return response; } // Load view return $dataRouterLoader.$$loadView(response); } function loadError(response) { response.routeError = true; // Try specific view first, then generic response.type = '$error_' + response.status; response.view = $dataRouterRegistry.match(response.type); if (!response.view) { response.type = '$error'; response.view = $dataRouterRegistry.match('$error'); } // Load the view if (response.view) { return $dataRouterLoader.$$loadView(response); } else { return $q.reject(response); } } function isSameView(current, next) { return current && next && current.url === next.url && current.type === next.type; } }, /** * @methodOf mdvorakDataRouter.$dataRouterLoader * @name $$loadData * @private * * @description * Loads view data from given URL. * Tries to automatically match the view by the data Content-Type header. * If the view is found, and transformResponse key is set, response is automatically resolved. * * @param {String} url URL to load data from. They are always loaded using GET method. * @returns {Promise} Promise of the response. */ $$loadData: function $$loadData(url) { $log.debug("Loading resource " + url); // Fetch data and return promise return $http({ url: url, method: 'GET', dataRouter: true }).then(function dataLoaded(response) { // Match existing resource var type = $dataRouterRegistry.normalizeMediaType(provider.extractType(response)) || 'application/octet-stream'; var view = $dataRouterRegistry.match(type); // Unknown media type if (!view) { return $q.reject(asResponse({ url: url, status: 999, statusText: "Application Error", data: "Unknown content type " + type, config: response.config, headers: response.headers, type: type })); } // Merge view // Note: If this could be cached in some way, it would be nice view = $$mergeConfigObjects(Object.create(null), provider.globals, view); // Success var result = { url: url, status: response.status, statusText: response.statusText, headers: response.headers, config: response.config, type: type, data: response.data, view: view }; if (view.transformResponse) { return asResponse(view.transformResponse(result)); } else { return asResponse(result); } }, function dataFailed(response) { response.url = url; return $q.reject(asResponse(response)); }); }, /** * @methodOf mdvorakDataRouter.$dataRouterLoader * @name $$loadView * @private * * @description * Loads view template and initializes resolves. * * @param {Object|Promise} response Loaded data response. Can be promise. * @returns {Promise} Promise of loaded view. Promise is rejected if any of locals or template fails to resolve. */ $$loadView: function $$loadView(response) { return $q.when(response).then(function responseReady(response) { // Resolve view if (response.view) { // Prepare locals var locals = angular.extend(Object.create(null), provider.globals.resolve, response.view.resolve); var template; // Built-in locals var builtInLocals = { $data: response.data, $dataType: response.type, $dataUrl: response.url, $dataResponse: response }; // Resolve locals if (locals) { angular.forEach(locals, function resolveLocal(value, key) { locals[key] = angular.isString(value) ? $injector.get(value) : $injector.invoke(value, '$dataRouterLoader', builtInLocals); }); } else { locals = Object.create(null); } // Load template template = $dataRouterLoader.$$loadTemplate(response.view, response.type); if (angular.isDefined(template)) { locals['$template'] = template; } return $q.all(locals).then(function localsLoaded(locals) { // Built-in locals angular.extend(locals, builtInLocals); // Store locals and continue response.locals = locals; return response; }, function localsError() { // Failure return $q.reject(asResponse({ url: response.url, status: 999, statusText: "Application Error", data: "Failed to resolve view " + response.type, config: {}, headers: angular.noop })); }); } // Return original object return response; }); }, $$loadTemplate: function $$loadTemplate(view, mediaType) { // Ripped from ngRoute var template, templateUrl; if (angular.isDefined(template = view.template)) { if (angular.isFunction(template)) { template = template(mediaType); } } else if (angular.isDefined(templateUrl = view.templateUrl)) { if (angular.isFunction(templateUrl)) { templateUrl = templateUrl(mediaType); } templateUrl = view.loadedTemplateUrl || $sce.getTrustedResourceUrl(templateUrl); if (angular.isDefined(templateUrl)) { view.loadedTemplateUrl = templateUrl; template = $http.get(templateUrl, { cache: $templateCache }).then(function templateLoaded(response) { return response.data; }); } } return template; } }; // Converter function function asResponse(response) { return angular.extend($$dataRouterEventSupport.$new(), response, provider.responseExtensions); } // Return return $dataRouterLoader; }]; /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterLoaderProvider * @name $$mergeConfigObjects * @private * * @description * Merges configuration objects. Plain objects are merged, all other properties are overwritten. * `undefined` values in `src` are ignored. * * @param {Object} dst Target object. * @return {Object} Returns `dst` object. */ function $$mergeConfigObjects(dst) { if (!dst) dst = Object.create(null); // Multiple sources for (var i = 1; i < arguments.length; i++) { var src = arguments[i]; if (src) { // Manual merge var keys = Object.keys(src); for (var k = 0; k < keys.length; k++) { var key = keys[k]; // Skip undefined entries if (angular.isUndefined(src[key])) return; // Current value var val = dst[key]; // If both values are plain objects, merge them, otherwise overwrite if (isPlainObject(val) && isPlainObject(src[key])) { // Merge dst[key] = angular.extend(val, src[key]); } else { // Overwrite dst[key] = src[key]; } } } } return dst; } provider.$$mergeConfigObjects = $$mergeConfigObjects; /** * Checks whether object is plain Object, if it is Date or whatever, it returns true. * * @param {Object} obj Checked object * @returns {boolean} true for POJO, false otherwise. */ function isPlainObject(obj) { return angular.isObject(obj) && toString.call(obj) === '[object Object]'; } }); /** * @ngdoc service * @name mdvorakDataRouter.$dataRouterProvider * * @description * Allows simple configuration of all parts of the data router in one place. * * @example * ```javascript * angular.module('example', ['mdvorakDataRouter']) * .config(function configRouter($dataRouterProvider) { * // URL prefixes * $dataRouterProvider.apiPrefix('api/'); * * // Error route * $dataRouterProvider.error({ * templateUrl: 'error.html', * dataAs: 'error' * }); * * // Routes * $dataRouterProvider.when('application/x.example', { * templateUrl: 'example.html', * controller: 'ExampleCtrl' * }); * }); * ``` */ module.provider('$dataRouter', ["$$dataRouterMatchMap", "$dataRouterRegistryProvider", "$dataRouterLoaderProvider", "$dataApiProvider", function $dataRouterProvider($$dataRouterMatchMap, $dataRouterRegistryProvider, $dataRouterLoaderProvider, $dataApiProvider) { var provider = this; /** * Enables the router. May be used to disable the router event handling. Cannot be changed after config phase. * @type {boolean} */ provider.$enabled = true; /** * Map of redirects. Do not modify directly, use redirect function. * @type {Object} */ provider.$redirects = $$dataRouterMatchMap.create(); /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterProvider * @name apiPrefix * * @description * Configures prefix for default view to resource mapping. * * This is just an alias for {@link mdvorakDataApi.$dataApiProvider#methods_prefix $dataApiProvider.prefix(prefix)} * method, see its documentation for details. * * @param {String} prefix Relative URL prefix, relative to base href. * @return {String} API URL prefix. It's always normalized absolute URL, includes base href. */ provider.apiPrefix = function apiPrefix(prefix) { return $dataApiProvider.prefix(prefix); }; /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterProvider * @name when * * @description * Configures view for given content type. * * This is just an alias for * {@link mdvorakDataRouter.$dataRouterRegistryProvider#methods_when $dataRouterRegistryProvider.when(mediaType,config)} * method, see its documentation for details. * * @param {String|Function} mediaType Content type to match. * @param {Object} config Configuration object. */ provider.when = function when(mediaType, config) { $dataRouterRegistryProvider.when(mediaType, config); return provider; }; /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterProvider * @name error * * @description * Configures view for error page. Error page is displayed when resource or view template cannot be loaded or * any of the resolvables fails. * * This is just an alias for * {@link mdvorakDataRouter.$dataRouterRegistryProvider#methods_error $dataRouterRegistryProvider.error(config)} * method, see its documentation for details. * * @param {Number=} status HTTP response status code this error view is for. This is optional argument, you should * always have defined generic error view as well. * @param {Object} config Configuration object, as in * {@link mdvorakDataRouter.$dataRouterRegistryProvider#methods_when when(config)}. */ provider.error = function error(status, config) { $dataRouterRegistryProvider.error(status, config); return provider; }; /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterProvider * @name redirect * * @description * Forces redirect from one location to another. * * @param {String} path View to force redirect on. Supports wildcards. Parameters are not supported * @param {String} redirectTo View path which should be redirected to. * @returns {Object} Returns the provider. */ provider.redirect = function redirect(path, redirectTo) { if (redirectTo) { provider.$redirects.addMatcher(path, redirectTo); } return provider; }; /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterProvider * @name global * * @description * Sets global configuration for all routes. It is then merged into each view configuration, with view taking precedence. * * This is just an alias for * {@link mdvorakDataRouter.$dataRouterLoaderProvider#methods_global $dataRouterLoaderProvider.global(config)}, * see its documentation for details. * * @param {Object} config Configuration object. Currently only `"resolve"` key is supported. * @returns {Object} Reference to the provider. */ provider.global = function global(config) { $dataRouterLoaderProvider.global(config); return provider; }; /** * @ngdoc method * @methodOf mdvorakDataRouter.$dataRouterProvider * @name enabled * * @description * Enables or disables the router. May be used to disable the router event handling. * Cannot be changed after config phase. * * This method is intended mostly for unit tests. * * Enabled by default. * * @param {boolean} enabled Set to `false` to disable the router. * @returns {Object} Returns provider. */ provider.enabled = function enabledFn(enabled) { provider.$enabled = !!enabled; return provider; }; /** * @ngdoc service * @name mdvorakDataRouter.$dataRouter * * @description * Centerpiece of the data router. It tracks the `$location` and loads the main view data. */ this.$get = ["$log", "$location", "$rootScope", "$q", "$dataRouterRegistry", "$dataRouterLoader", "$dataApi", "$$dataRouterEventSupport", function $dataRouterFactory($log, $location, $rootScope, $q, $dataRouterRegistry, $dataRouterLoader, $dataApi, $$dataRouterEventSupport) { /** * @ngdoc event * @eventOf mdvorakDataRouter.$dataRouter * @name $routeChangeStart * @eventType broadcast on root scope * * @description * This event is broadcasted whenever main view is about to change. The change can be averted * by setting preventDefault on the vent. */ /** * @ngdoc event * @eventOf mdvorakDataRouter.$dataRouter * @name $routeChangeSuccess * @eventType broadcast on root scope * * @description * This event is broadcasted whenever main view has changed and the data are loaded. * View is ready to be displayed. */ /** * @ngdoc event * @eventOf mdvorakDataRouter.$dataRouter * @name $routeChangeError * @eventType broadcast on root scope * * @description * This event is broadcasted when the view or data failed to load and there is no error view configured * (or error view failed to load). There is not much you can do at this point, it probably means you have * configuration error in your application. */ var $dataRouter = { /** * @ngdoc property * @propertyOf mdvorakDataRouter.$dataRouter * @name api * @returns {Object} Reference to the {@link mdvorakDataApi.$dataApi $dataApi} instance. * * @description * Its here to make your life easier. */ api: $dataApi, /** * @ngdoc property * @propertyOf mdvorakDataRouter.$dataRouter * @name registry * @returns {Object} Reference to the {@link mdvorakDataRouter.$dataRouterRegistry $dataRouterRegistry} instance. * * @description * Its here to make your life easier. */ registry: $dataRouterRegistry, /** * @ngdoc property * @propertyOf mdvorakDataRouter.$dataRouter * @name current * @returns {Object} Currently loaded response for the main view is available here. * See {@link locals.$dataResponse $dataResponse} for its signature. * * @description * Note that you should in most cases use {@link locals.$dataResponse $dataResponse} object in the * controller to work with the data instead of this reference. */ current: undefined, /** * @ngdoc method * @propertyOf mdvorakDataRouter.$dataRouter * @name url * @description * Gets or sets current view resource URL using {@link mdvorakDataApi.$dataApi.url $dataApi.url()}. * * If the `url` is not in the configured API namespace, error is logged and nothing happens. * * @param {String=} url New resource URL. Performs location change. * @param {Boolean=} reload If `true`, data are reloaded even if `url` did not change. Default is `false`. * @returns {String} Resource URL that is being currently viewed. */ url: function urlFn(url, reload) { // Getter if (arguments.length < 1) { return $dataApi.url(); } // Setter if (reload && $dataApi.url() == url) { // Same URL, reload instead $dataRouter.reload(true); } else { // Change URL $dataApi.url(url); } return url; }, /** * @ngdoc method * @propertyOf mdvorakDataRouter.$dataRouter * @name navigate * @description * Navigates to resource URL. See {@link mdvorakDataRouter.$dataRouter.url $dataRouter.url()} for more details. * * @param {String=} url New resource URL. * @param {Boolean=} reload If `true`, data are reloaded even if `url` did not change. Default is `true`. */ navigate: function navigate(url, reload) { $dataRouter.url(url, reload !== false); }, /** * @ngdoc method * @propertyOf mdvorakDataRouter.$dataRouter * @name reload * @description * Reloads data at current location. If content type remains same, only data are refreshed, * and $routeUpdate event is invoked on $dataResponse object. If content type differs, * full view refresh is performed (that is, controller is destroyed and recreated). * <p> * If you refresh data, you must listen to the $routeUpdate event on $dataResponse object to be notified of the change. * * @param {boolean=} forceReload If true, page is always refreshed (controller recreated). Otherwise only * when needed. */ reload: function reload(forceReload) { var redirectTo; // Forced redirect (Note: This matches search params as well) if ((redirectTo = provider.$redirects.match($location.url() || '/'))) { $log.debug("Redirecting to " + redirectTo); $location.url(redirectTo).replace(); return; } // Load resource var url = $dataApi.url(); var next = $dataRouter.$$next = {}; // Load data and view $log.debug("Loading main view"); $dataRouterLoader.prepareView(url, $dataRouter.current, forceReload) .then(showView, routeChangeFailed); // Promise resolutions function showView(response) { if ($dataRouter.$$next === next) { // Remove marker $dataRouter.$$next = undefined; // Update view data if (response.routeDataUpdate && $dataRouter.current) { $log.debug("Replacing current data"); // Update current (preserve listeners) $$dataRouterEventSupport.$$extend($dataRouter.current, response); // Fire event on the response (only safe way for both main view and fragments) $dataRouter.current.$broadcast('$routeUpdate', $dataRouter.current); } else { $log.debug("Setting view to " + response.mediaType); // Add reload and navigate implementations response.reload = $dataRouter.reload; response.navigate = $dataRouter.navigate; // Set current $dataRouter.current = response; // Emit event $rootScope.$broadcast('$routeChangeSuccess', response); } } } function routeChangeFailed(response) { // Error handler if ($dataRouter.$$next === next) { // Remove next, but don't update current $dataRouter.$$next = undefined; // Show error view $log.error("Failed to load view or data and no error view defined", response); $rootScope.$broadcast('$routeChangeError', response); } } } }; if (provider.$enabled) { // Broadcast $routeChangeStart and cancel location change if it is prevented $rootScope.$on('$locationChangeStart', function locationChangeStart($locationEvent) { if ($rootScope.$broadcast('$routeChangeStart').defaultPrevented) { if ($locationEvent) { $locationEvent.preventDefault(); } } }); // Reload view on location change $rootScope.$on('$locationChangeSuccess', function locationChangeSuccess() { $dataRouter.reload(true); }); } return $dataRouter; }]; }]); // Note: It is constant so it can be used during config phase module.constant('$$dataRouterMatchMap', { create: function create() { return new DataRouterMatchMap(); } }); /** * Collection of matchers, both exact and matcher functions. * @constructor */ function DataRouterMatchMap() { this.$exact = Object.create(null); this.$matchers = []; var wildcardPattern = /[*?]/; this.addMatcher = function addMatcher(pattern, data) { if (angular.isFunction(pattern)) { this.$matchers.push({ m: pattern, d: data }); } else if (wildcardPattern.test(pattern)) { // Register matcher this.$matchers.push({ m: wildcardMatcherFactory(pattern), d: data }); } else { // Exact match this.$exact[pattern] = data; } }; this.match = function match(s) { // Exact match var data = this.$exact[s], i, matchers; if (data) return data; // Iterate matcher functions for (matchers = this.$matchers, i = 0; i < matchers.length; i++) { if (matchers[i].m(s)) { return matchers[i].d; } } }; // Helper functions function wildcardMatcherFactory(wildcard) { var pattern = new RegExp('^' + wildcardToRegex(wildcard) + '$'); // Register matcher return function wildcardMatcher(s) { return pattern.test(s); }; } function wildcardToRegex(s) { return s.replace(/([-()\[\]{}+.$\^|,:#<!\\])/g, '\\$1') .replace(/\x08/g, '\\x08') .replace(/[*]+/g, '.*') .replace(/[?]/g, '.'); } } module.factory('$$dataRouterEventSupport', ["$exceptionHandler", function dataRouterEventSupportFactory($exceptionHandler) { var slice = [].slice; // This code is ripped of Scope class function EventSupport() {} EventSupport.$new = function() { return new EventSupport(); }; EventSupport.$$extend = function(dst, src) { // Preserve listeners var $$listeners = dst.$$listeners; angular.extend(dst, src); dst.$$listeners = $$listeners; return dst; }; EventSupport.prototype = { constructor: EventSupport, $on: function(name, listener, scope) { if (!this.$$listeners) this.$$listeners = Object.create(null); var namedListeners = this.$$listeners[name]; if (!namedListeners) { namedListeners = this.$$listeners[name] = [listener]; } else { namedListeners.push(listener); } // Remove function var remove = function removeFn() { var indexOfListener = namedListeners.indexOf(listener); if (indexOfListener !== -1) { namedListeners[indexOfListener] = null; } }; if (scope) { var removeDestroy = scope.$on('$destroy', remove); return function combinedRemove() { remove(); removeDestroy(); }; } else { return remove; } }, $broadcast: function(name, args) { var event = { name: name, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }; var listeners = (this.$$listeners && this.$$listeners[name]) || []; var i, length; // Prepare arguments args = [event].concat(slice.call(arguments, 1)); for (i = 0, length = listeners.length; i < length; i++) { // if listeners were deregistered, defragment the array if (!listeners[i]) { listeners.splice(i, 1); i--; length--; continue; } try { listeners[i].apply(null, args); } catch (e) { $exceptionHandler(e); } } return event; } }; return EventSupport; }]); /** * @ngdoc directive * @name mdvorakDataRouter.apiHref * @restrict AC * @priority 90 * @element A * * @param {expression} apiHref Any URL. Behavior changes whether this URL is inside API base or not. * @param {template=} type Optional. Media type of target resource. If the type is supported, navigation is performed, if not, * browser performs full redirect. * It is recommended to use `api-type` attribute, which is expression (same as `api-href` itself). * @param {template=} target Optional. Target of the link according to HTML specification. If it is specified, full redirect * is always performed. To force full reload instead of navigation, set this to `_self`. * @param {expression} apiType Wrapper around `type` attribute. It is here to avoid confusion, when `api-href` is expression * and `type` is template. * It is recommend way of setting view type. * * @description * Translates API URL into view URL and sets it as href. It is replacement for ngHref directive. * It supports HTML 5 mode as well hasbang mode. * * Following code sets href to `#/users/12347` or `users/12347` for html5Mode respectively. * ```html * <a api-href="'api/users/12347;">User Detail</a> * ``` * * @example * This example shows behavior of the directive in different scenarios. * * * **Back** navigates to parent, since its maps to configured API. The template for the given type is * prefetched. This link would behave same even without type attribute, but template would not be prefetched. * * **External** performs full navigation, since URL cannot be mapped to API. Type attribute is ignored in this case. * * **Image** link shows image full screen or triggers download (depends on the server), since the type is not supported. * If the type would not be set, data would be downloaded and error page would be shown afterwards. * * **New Window** opens the link in new window, regardless where it points, since it has target specified. * * <example module="sample"> * <file name="index.html"> * <div ng-controller="sampleCtrl"> * <!-- href: api/some/parent type: application/x.example --> * <a api-href="links.parent.href" type="{{links.parent.type}}">Back</a> * <!-- href: external/url type: application/x.example --> * <a api-href="links.external.href" api-type="links.external.type">Website</a> * <!-- href: api/my/photo type: application/image.png --> * <a api-href="links.image.href" api-type="links.image.type">Image</a> * <!-- href: external/url type: application/x.example --> * <a api-href="links.external.href" target="_blank">New Window</a> * </div> * </file> * <file name="controller.js"> * angular.module('sample', ['mdvorakDataRouter']) * .config(function ($dataRouterProvider) { * $dataRouterProvider.apiPrefix('api/'); * * // application/x.example * $dataRouterProvider.when('x.example', { * templateUrl: 'example.html' * }); * }) * .controller('sampleCtrl', function sampleCtrl($scope) { * $scope.links = { * parent: {href: "api/some/parent", type: "application/x.example"}, * external: {href: "external/url", type: "application/x.example"}, * image: {href: "api/my/photo", type: "application/image.png"} * }; * }); * </file> * </example> * * When `apiHref` resolves to the configured api prefix, it redirects to the base href of the application. * <example module="apiPrefix"> * <file name="apiPrefix.html"> * <a api-href="'api/'">Api Prefix</a> * </file> * <file name="apiPrefix.js"> * angular.module('apiPrefix', ['mdvorakDataRouter']) * .config(function ($dataApiProvider) { * $dataApiProvider.prefix('api/'); * }); * </file> * </example> */ module.directive('apiHref', ["$dataApi", "$dataRouterRegistry", "$dataRouterLoader", "$location", "$browser", "$parse", function apiHrefFactory($dataApi, $dataRouterRegistry, $dataRouterLoader, $location, $browser, $parse) { return { restrict: 'AC', priority: 90, compile: function entryPointHrefCompile(element, attrs) { // #18 This will force angular-material to think, this really is an anchor attrs.href = null; // Return post-link function return apiHrefLink; } }; function apiHrefLink(scope, element, attrs) { var hasTarget = 'target' in attrs; var apiHrefGetter = $parse(attrs.apiHref); function setHref(href, target) { attrs.$set('href', href); if (!hasTarget) { attrs.$set('target', href ? target : null); } } function updateHref() { var href = apiHrefGetter(scope); // Do we have a type? And it is supported? if (attrs.type && !$dataRouterRegistry.isKnownType(attrs.type)) { // If not, do not modify the URL setHref(href, '_self'); return; } if (angular.isString(href)) { // Map URL var mappedHref = $dataApi.mapApiToView(href); // Use URL directly if (!angular.isString(mappedHref)) { setHref(href, '_self'); return; } // Hashbang mode if (!$location.$$html5) { mappedHref = '#/' + mappedHref; } else if (mappedHref === '') { // HTML 5 mode and we are going to the base, so force it // (it is special case, since href="" does not work with angular) // In normal cases, browser handles relative URLs on its own mappedHref = $browser.baseHref(); } setHref(mappedHref, null); } else { // Reset href setHref(); } } // Update href accordingly var offWatch = scope.$watch(attrs.apiHref, updateHref); element.on('$destroy', offWatch); // We don't have own scope, so don't rely on its destruction // Expression version of type attribute if (attrs.apiType) { scope.$watch(attrs.apiType, function(type) { attrs.$set('type', type); }); } // Watch for type attribute attrs.$observe('type', updateHref); // Click handler that pre-fetches templates element.on('click', function clickHandler() { // Invoke apply only if needed if (attrs.type && attrs.href) { scope.$applyAsync(function applyCallback() { // Race condition if (attrs.type) { $dataRouterLoader.prefetchTemplate(attrs.type); } }); } }); } }]); /** * @ngdoc directive * @name mdvorakDataRouter.dataview * @restrict EAC * * @description * Renders the view for the given data. This directive works in two modes. * * * **Main view** - It displays current data, specified by browser location, and mapped to the resource by * {@link mdvorakDataApi.$dataApi#methods_mapViewToApi $dataApi.mapViewToApi()} method. * * **Custom view** - When `src` attribute is set, the data are loaded by this directive itself and displayed * according to the configured view. * * @param {expression=} src API URL to be displayed. If not set, main view is shown. * @param {expression=} autoscroll Whether dataview should call `$anchorScroll` to scroll the viewport after the view * is updated. Applies only to the main view, that is, without the `src` attribute. * @param {expression=} onload Onload handler. * @param {expression=} name Name of the context, under which it will be published to the current scope. Works similar * to the name of the `form` directive. * @param {String=} type Type parameter, that is passed to child view on its scope under key `$viewType`. * If not set, value `default` is used. */ module.directive('dataview', ["$animate", "$anchorScroll", "$log", "$parse", "$dataRouterLoader", "$dataRouter", "$$dataRouterEventSupport", function dataViewFactory($animate, $anchorScroll, $log, $parse, $dataRouterLoader, $dataRouter, $$dataRouterEventSupport) { return { restrict: 'EAC', terminal: true, priority: 400, transclude: 'element', link: function dataViewLink(scope, $element, attr, ctrl, $transclude) { var currentHref, currentScope, currentElement, previousLeaveAnimation, autoScrollExp = attr.autoscroll, onloadExp = attr.onload || ''; // Store context var context; if (attr.hasOwnProperty('src')) { // Custom context context = { reload: reloadImpl, navigate: function navigateLocal(url, reload) { if (currentHref == url) { // true is default if (reload !== false) { // Reload reloadImpl(true); } } else { // Navigate, but don't change src attribute itself currentHref = url; reloadImpl(true); } } }; // Custom view - watch for href changes scope.$watch(attr.src, function hrefWatch(href) { currentHref = href; reloadImpl(true); }); } else { // Main view - use $dataRouter as context context = $dataRouter; // Show view on route change scope.$on('$routeChangeSuccess', showView); } // Publish if (attr.name) { $parse(attr.name).assign(scope, context); } // Implementation function cleanupLastView() { if (previousLeaveAnimation) { $animate.cancel(previousLeaveAnimation); previousLeaveAnimation = null; } if (currentScope) { currentScope.$destroy(); currentScope = null; } if (currentElement) { previousLeaveAnimation = $animate.leave(currentElement); previousLeaveAnimation.then(function onDataviewLeave() { previousLeaveAnimation = null; }); currentElement = null; } } function showView() { // Show view var locals = context.current && context.current.locals, template = locals && locals.$template; if (angular.isDefined(template)) { $log.debug("Setting view ", $element[0], " to ", context.current.type); var newScope = scope.$new(); newScope.$$dataRouterCtx = context; newScope.$viewType = attr.type || 'default'; // Note: This will also link all children of ng-view that were contained in the original // html. If that content contains controllers, ... they could pollute/change the scope. // However, using ng-view on an element with additional content does not make sense... // Note: We can't remove them in the cloneAttchFn of $transclude as that // function is called before linking the content, which would apply child // directives to non existing elements. currentElement = $transclude(newScope, function cloneLinkingFn(clone) { $animate.enter(clone, null, currentElement || $element).then(function onDataviewEnter() { if (angular.isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } }); cleanupLastView(); }); currentScope = context.current.scope = newScope; currentScope.$eval(onloadExp); } else { $log.debug("Resetting view ", $element[0], ", got no response"); cleanupLastView(); } } /** * Loads the data from currentHref and shows the view. * Used when this directive shows custom URL and not the main view. * * @param forceReload {boolean=} Specifies whether view needs to be refreshed or just $routeUpdate event will be fired. */ function reloadImpl(forceReload) { var next = attr.next = Object.create(null); if (currentHref) { // Load data $log.debug("Loading view data of ", $element[0]); $dataRouterLoader.prepareView(currentHref, context.current, forceReload).then(update, update); } else { // Reset update(); } function update(response) { if (next === attr.next) { // Update view data if (response && response.routeDataUpdate && context.current) { $log.debug("Replacing view data of ", $element[0]); // Update current (preserve listeners) $$dataRouterEventSupport.$$extend(context.current, response); // Fire event on the response (only safe way for both main view and fragments) context.current.$broadcast('$routeUpdate', context.current); } else { // Update current context.current = response; attr.next = undefined; // Add reload and navigate implementations if (response) { response.reload = reloadImpl; response.navigate = function navigateDelegate() { context.navigate.apply(context, arguments); }; } // Show view showView(); } } } } } }; }]); module.directive('dataview', ["$compile", "$controller", function dataViewFillContentFactory($compile, $controller) { // This directive is called during the $transclude call of the first `dataView` directive. // It will replace and compile the content of the element with the loaded template. // We need this directive so that the element content is already filled when // the link function of another directive on the same element as dataView // is called. return { restrict: 'EAC', priority: -400, link: function dataViewFillContentLink(scope, $element) { var context = scope.$$dataRouterCtx; // Get context var current = context.current; var view = current.view; var locals = current.locals; // delete context from the scope delete scope.$$dataRouterCtx; // Compile $element.html(locals.$template); var link = $compile($element.contents()); if (view) { $element.data('$dataResponse', current); if (view.dataAs) { scope[view.dataAs] = current.data; current.$on('$routeUpdate', function routeDataUpdated(e, response) { scope[view.dataAs] = response.data; }, scope); } if (view.responseAs) { scope[view.responseAs] = current; } if (view.controller) { locals.$scope = scope; locals.$viewType = scope.$viewType; var controller = $controller(view.controller, locals); if (view.controllerAs) { scope[view.controllerAs] = controller; } $element.data('$ngControllerController', controller); $element.children().data('$ngControllerController', controller); } } link(scope); } }; }]); /** * @ngdoc directive * @name mdvorakDataRouter.emptyHref * @restrict AC * @priority 0 * @element A * * @param {String} emptyHref Must be either `hide` or `disable`. Any other value is ignored and warning is logged. * * @description * Defines behavior when link has empty href attribute. It is complementary to {@link mdvorakDataRouter.apiHref apiHref} * or `ngHref` directives. * * @example * Usage * ```html * <a api-href="links.example.href" empty-href="hide">Hide when no link is given</a> * <a api-href="links.example.href" empty-href="disable">Disabled when no link is given</a> * <a api-href="links.example.href" empty-href="disabled">Same as disable</a> * <a api-href="links.example.href" empty-href="anything">Always visible and active, since attr is invalid</a> * ``` */ module.directive('emptyHref', ["$log", function emptyHrefFactory($log) { return { restrict: 'AC', priority: 0, link: function emptyHrefLink(scope, element, attrs) { var observer; // Modes switch (angular.lowercase(attrs['emptyHref'])) { case 'hide': observer = function hrefHideObserver(href) { element.toggleClass('ng-hide', !href && href !== ''); }; break; case 'disable': case 'disabled': observer = function hrefDisableObserver(href, oldHref) { // Handle empty string correctly if (href === '') href = true; if (oldHref === '') oldHref = true; // Boolean value has changed if (href && !oldHref) { // From disabled to enabled element.removeClass('disabled').off('click', disabledHandler); } else if (!href && oldHref) { // From enabled to disabled element.addClass('disabled').on('click', disabledHandler); } }; // Fix init in disabled state if (!attrs.href && attrs.href !== '') { // Handler modifies the object only when change occur. // But during init, oldHref is undefined, and link is not properly disabled. element.addClass('disabled').on('click', disabledHandler); } break; default: $log.warn("Unsupported empty-href value: " + attrs['emptyHref']); return; } // Watch for href attrs.$observe('href', observer); // Disabled handler function disabledHandler(e) { e.preventDefault(); } } }; }]); /** * @ngdoc directive * @name mdvorakDataRouter.entryPointHref * @restrict AC * @priority 90 * @element A * * @decription * Generates link to the application entry-point, that is root of the API. It produces same behavior as * calling `$location.path('/')`. * * Do not use in conjuction with `api-href` or `ng-href`. */ module.directive('entryPointHref', ["$browser", "$location", function entryPointHrefFactory($browser, $location) { // For hashbang mode, all we need is #/, otherwise use base href var baseHref = $location.$$html5 ? $browser.baseHref() : '#/'; return { restrict: 'AC', priority: 90, compile: function entryPointHrefCompile(element, attrs) { // #18 This will force angular-material to think, this really is an anchor attrs.href = null; // Return post-link function return function entryPointHrefLink(scope, element, attrs) { attrs.$set('href', baseHref); }; } }; }]); /** * @ngdoc overview * @name mdvorakDataApi * * @description * This is standalone module that allows two-way mapping of view and API URLs. * See {@link mdvorakDataApi.$dataApiProvider $dataApiProvider} provider for more details. */ /** * @ngdoc service * @name mdvorakDataApi.$dataApiProvider * * @description * Provider allows you to configure API {@link mdvorakDataApi.$dataApiProvider#methods_prefix prefix}. */ angular.module('mdvorakDataApi', []).provider('$dataApi', function $dataApiProvider() { var provider = this; // Intentionally using document object instead of $document var urlParsingNode = document.createElement("A"); /** * @ngdoc method * @methodOf mdvorakDataApi.$dataApiProvider * @name normalizeUrl * * @description * Normalizes the URL for current page. It takes into account base tag etc. It is browser dependent. * * It is browser dependent, and takes into account `<base>` tag or current URL. * Note that in HTML5 mode, there should be always specified base tag ending with `/` to get expected behavior. * * This method is also available on {@link mdvorakDataApi.$dataApi#methods_normalizeUrl $dataApi} object. * * @param {String} href URL to be normalized. Can be absolute, server-relative or context relative. * <p>If the href is empty string, base href is returned.</p> * <p>Otherwise, when it is `null` or `undefined`, `null` is returned.</p> * @returns {String} Normalized URL, including full hostname. */ provider.normalizeUrl = function normalizeUrl(href) { if (href === '') { // Special case - browser interprets empty string as current URL, while we need // what it considers a base if no base href is given. // Add /X to the path and then remove it. urlParsingNode.setAttribute("href", 'X'); return urlParsingNode.href.replace(/X$/, ''); } else if (href) { // Normalize thru href property urlParsingNode.setAttribute("href", href); return urlParsingNode.href; } // Empty return null; }; /** * Api prefix variable. Do not modify directly, use accessor function. * * @type {string} * @protected */ provider.$apiPrefix = provider.normalizeUrl(''); /** * @ngdoc method * @methodOf mdvorakDataApi.$dataApiProvider * @name prefix * * @description * Configures prefix for default view to resource mapping. * * It behaves just like Anchor href attribute. * * * It should always end with `/`, otherwise it will behave as configured, which may be weird in some cases. * * If it starts with `/`, it is server-relative, and `<base>` tag is ignored. * * _Note: This method also has shortcut on `$dataRouterProvider` as * {@link mdvorakDataRouter.$dataRouterProvider#methods_apiPrefix apiPrefix(prefix)}. * * @param {String} prefix Relative URL prefix, relative to base href. * @return {String} API URL prefix. It's always normalized absolute URL, includes base href. */ provider.prefix = function prefixFn(prefix) { if (arguments.length > 0) { provider.$apiPrefix = provider.normalizeUrl(prefix); } return provider.$apiPrefix; }; /** * @ngdoc method * @methodOf mdvorakDataApi.$dataApiProvider * @name mapViewToApi * * @description * Maps view path to resource URL. Can be overridden during configuration. * By default it maps path to API one to one. * * Counterpart to {@link mdvorakDataApi.$dataApiProvider#methods_mapApiToView mapApiToView}. * * This method is also available on {@link mdvorakDataApi.$dataApi#methods_mapApiToView $dataApi} object. * * @param {String} path View path, as in `$location.path()`. * @returns {String} Resource url, for e.g. HTTP requests. */ provider.mapViewToApi = function mapViewToApi(path) { // Path should always begin with slash, remove it if (path && path[0] === '/') { path = path.substring(1); } // Join // Note: API prefix MUST end with a slash, otherwise it will work as configured, which is most likely wrong. return provider.$apiPrefix + path; }; /** * @ngdoc method * @methodOf mdvorakDataApi.$dataApiProvider * @name mapApiToView * * @description * Maps resource URL to view path. Can be overridden during configuration. * By default it maps API url to view paths one to one. * * Counterpart to {@link mdvorakDataApi.$dataApiProvider#methods_mapViewToApi mapViewToApi}. * * This method is also available on {@link mdvorakDataApi.$dataApi#methods_mapViewToApi $dataApi} object. * * @param {String} url Resource url. It must be inside API namespace. If it is not, `null` is returned. * <p>If the url equals to api prefix, empty string is returned.</p> * @returns {String} View path. */ provider.mapApiToView = function mapApiToView(url) { // Normalize url = provider.normalizeUrl(url); if (url && url.indexOf(provider.$apiPrefix) === 0) { return url.substring(provider.$apiPrefix.length); } // Unable to map return null; }; /** * @ngdoc service * @name mdvorakDataApi.$dataApi * * @description * Extension of Angular `$location`. It maps view URLs to API and vice versa. * Use {@link mdvorakDataApi.$dataApi#methods_url url()} method to get or set current API location. */ this.$get = ["$log", "$location", function $dataApiFactory($log, $location) { $log.debug("Using API prefix " + provider.$apiPrefix); return { /** * @ngdoc method * @methodOf mdvorakDataApi.$dataApi * @name prefix * * @description * Returns configured API prefix. It cannot be changed at this point. * * @return {String} API URL prefix. It's absolute URL, includes base href. */ prefix: function apiPrefix() { return provider.prefix(); }, /** * @ngdoc method * @methodOf mdvorakDataApi.$dataApi * @name mapViewToApi * * @description * Maps view path to resource URL. Can be overridden during configuration. * By default it maps path to API one to one. * * Counterpart to {@link mdvorakDataApi.$dataApi#methods_mapApiToView mapApiToView}. * * @param {String} path View path, as in `$location.path()`. * @returns {String} Resource url, for e.g. HTTP requests. */ mapViewToApi: function mapViewToApi(path) { return provider.mapViewToApi(path); }, /** * @ngdoc method * @methodOf mdvorakDataApi.$dataApi * @name mapApiToView * * @description * Maps resource URL to view path. Can be overridden during configuration. * By default it maps API url to view paths one to one. * * Counterpart to {@link mdvorakDataApi.$dataApi#methods_mapViewToApi mapViewToApi}. * * @param {String} url Resource url. It must be inside API namespace. If it is not, `null` is returned. * <p>If the url equals to api prefix, empty string is returned.</p> * @returns {String} View path. */ mapApiToView: function mapApiToView(url) { return provider.mapApiToView(url); }, /** * @ngdoc method * @methodOf mdvorakDataApi.$dataApi * @name url * * @description * Gets or sets current view resource URL (it internally modifies `$location.url()`). * * * If the `url` is not in the configured API namespace, error is logged and nothing happens. * * If the `url` equals to api prefix, it is performed redirect to page base href. * * @param {String=} url New resource URL. Performs location change. * @returns {String} Resource URL that is being currently viewed. */ url: function urlFn(url) { // Getter if (arguments.length < 1) { // Map view URL to API. return provider.mapViewToApi($location.url()); } // Setter var path = provider.mapApiToView(url); if (path) { $location.url(path); return url; } else { $log.warn("Cannot navigate to URL " + url + ", it cannot be mapped to the API"); } }, /** * @ngdoc method * @methodOf mdvorakDataApi.$dataApi * @name normalizeUrl * * @description * Normalizes the URL for current page. It takes into account base tag etc. It is browser dependent. * * It is browser dependent, and takes into account `<base>` tag or current URL. * Note that in HTML5 mode, there should be always specified base tag ending with `/` to get expected behavior. * * @param {String} href URL to be normalized. Can be absolute, server-relative or context relative. * <p>If the href is empty string, base href is returned.</p> * <p>Otherwise, when it is `null` or `undefined`, `null` is returned.</p> * @returns {String} Normalized URL, including full hostname. */ normalizeUrl: function normalizeUrl(href) { return provider.normalizeUrl(href); } }; }]; }); })(angular);
// Helper functions that converts some common sub/unsub patterns // to useEffect model (i. e. make them return a unsubscripion function) import { useEffect } from 'react'; export function withEventListener(element, event, handler) { element.addEventListener(event, handler); return () => element.removeEventListener(event, handler); } export function withListener(emitter, event, handler) { emitter.addListener(event, handler); return () => emitter.removeListener(event, handler); } export function withTimeout(handler, timeout) { const timer = window.setTimeout(handler, timeout); return () => window.clearTimeout(timer); } export function withInterval(handler, timeout) { const timer = window.setInterval(handler, timeout); return () => window.clearInterval(timer); } export function useEventListener(ref, eventName, handler) { useEffect(() => { const el = ref.current; return el ? withEventListener(el, eventName, handler) : undefined; }, [ref, eventName, handler]); }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.provider = undefined; exports.shallowEqual = shallowEqual; exports.observeStore = observeStore; exports.configureStore = configureStore; var _redux = require('redux'); function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || _redux.compose; function shallowEqual(objA, objB) { if (objA === objB) return true; var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) return false; // Test for A's keys different from B. var hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } function observeStore(store, currState, select, onChange) { if (typeof onChange !== 'function') return null; var currentState = currState || {}; function handleChange() { var nextState = select(store.getState()); if (!shallowEqual(currentState, nextState)) { var previousState = currentState; currentState = nextState; onChange(currentState, previousState); } } var unsubscribe = store.subscribe(handleChange); handleChange(); return unsubscribe; } var provider = exports.provider = { set store(store) { this._store = store; }, get store() { return this._store; } }; function configureStore(reducer, preloadedState) { var middleware = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; return (0, _redux.createStore)(reducer, preloadedState, composeEnhancers(_redux.applyMiddleware.apply(undefined, _toConsumableArray(middleware)))); } //# sourceMappingURL=redux-helpers.js.map
import React from 'react'; import SvgIcon from '@material-ui/core/SvgIcon'; /* eslint-disable max-len */ const FacebookIcon = props => ( <SvgIcon viewBox="0 0 216 216" {...props}> <path d="M204.1,0H11.9C5.3,0,0,5.3,0,11.9v192.2c0,6.6,5.3,11.9,11.9,11.9h103.5v-83.6H87.2V99.8h28.1 v-24c0-27.9,17-43.1,41.9-43.1c11.9,0,22.2,0.9,25.2,1.3v29.2l-17.3,0c-13.5,0-16.2,6.4-16.2,15.9v20.8h32.3l-4.2,32.6H149V216h55 c6.6,0,11.9-5.3,11.9-11.9V11.9C216,5.3,210.7,0,204.1,0z" /> </SvgIcon> ); /* eslint-enable max-len */ export default FacebookIcon;
process.env.NO_DEPRECATION = 'send'; var assert = require('assert'); var fs = require('fs'); var http = require('http'); var path = require('path'); var request = require('supertest'); var send = require('..') var should = require('should'); // test server var dateRegExp = /^\w{3}, \d+ \w+ \d+ \d+:\d+:\d+ \w+$/; var fixtures = path.join(__dirname, 'fixtures'); var app = http.createServer(function(req, res){ function error(err) { res.statusCode = err.status; res.end(http.STATUS_CODES[err.status]); } function redirect() { res.statusCode = 301; res.setHeader('Location', req.url + '/'); res.end('Redirecting to ' + req.url + '/'); } send(req, req.url, {root: fixtures}) .on('error', error) .on('directory', redirect) .pipe(res); }); describe('send.mime', function(){ it('should be exposed', function(){ assert(send.mime); }) }) describe('send(file).pipe(res)', function(){ it('should stream the file contents', function(done){ request(app) .get('/name.txt') .expect('Content-Length', '4') .expect(200, 'tobi', done) }) it('should decode the given path as a URI', function(done){ request(app) .get('/some%20thing.txt') .expect(200, 'hey', done) }) it('should serve files with dots in name', function(done){ request(app) .get('/do..ts.txt') .expect(200, '...', done) }) it('should treat a malformed URI as a bad request', function(done){ request(app) .get('/some%99thing.txt') .expect(400, 'Bad Request', done) }) it('should 400 on NULL bytes', function(done){ request(app) .get('/some%00thing.txt') .expect(400, 'Bad Request', done) }) it('should treat an ENAMETOOLONG as a 404', function(done){ var path = Array(100).join('foobar'); request(app) .get('/' + path) .expect(404, done); }) it('should handle headers already sent error', function(done){ var app = http.createServer(function(req, res){ res.write('0'); send(req, req.url, {root: fixtures}) .on('error', function(err){ res.end(' - ' + err.message) }) .pipe(res); }); request(app) .get('/nums') .expect(200, '0 - Can\'t set headers after they are sent.', done); }) it('should support HEAD', function(done){ request(app) .head('/name.txt') .expect('Content-Length', '4') .expect(200, '', done) }) it('should add an ETag header field', function(done){ request(app) .get('/name.txt') .expect('etag', /^W\/"[^"]+"$/) .end(done); }) it('should add a Date header field', function(done){ request(app) .get('/name.txt') .expect('date', dateRegExp, done) }) it('should add a Last-Modified header field', function(done){ request(app) .get('/name.txt') .expect('last-modified', dateRegExp, done) }) it('should add a Accept-Ranges header field', function(done){ request(app) .get('/name.txt') .expect('Accept-Ranges', 'bytes', done) }) it('should 404 if the file does not exist', function(done){ request(app) .get('/meow') .expect(404, 'Not Found', done) }) it('should 301 if the directory exists', function(done){ request(app) .get('/pets') .expect('Location', '/pets/') .expect(301, 'Redirecting to /pets/', done) }) it('should not override content-type', function(done){ var app = http.createServer(function(req, res){ res.setHeader('Content-Type', 'application/x-custom') send(req, req.url, {root: fixtures}).pipe(res) }); request(app) .get('/nums') .expect('Content-Type', 'application/x-custom', done); }) it('should set Content-Type via mime map', function(done){ request(app) .get('/name.txt') .expect('Content-Type', 'text/plain; charset=UTF-8') .expect(200, function(err){ if (err) return done(err) request(app) .get('/tobi.html') .expect('Content-Type', 'text/html; charset=UTF-8') .expect(200, done) }); }) it('should 404 if file disappears after stat, before open', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: 'test/fixtures'}) .on('file', function(){ // simulate file ENOENT after on open, after stat var fn = this.send; this.send = function(path, stat){ path += '__xxx_no_exist'; fn.call(this, path, stat); }; }) .pipe(res); }); request(app) .get('/name.txt') .expect(404, done); }) it('should 500 on file stream error', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: 'test/fixtures'}) .on('stream', function(stream){ // simulate file error process.nextTick(function(){ stream.emit('error', new Error('boom!')); }); }) .pipe(res); }); request(app) .get('/name.txt') .expect(500, done); }) describe('"headers" event', function () { var args var fn var headers var server before(function () { server = http.createServer(function (req, res) { send(req, req.url, {root: fixtures}) .on('headers', function () { args = arguments headers = true fn && fn.apply(this, arguments) }) .pipe(res) }) }) beforeEach(function () { args = undefined fn = undefined headers = false }) it('should fire when sending file', function (done) { request(server) .get('/nums') .expect(200, '123456789', function (err, res) { if (err) return done(err) headers.should.be.true done() }) }) it('should not fire on 404', function (done) { request(server) .get('/bogus') .expect(404, function (err, res) { if (err) return done(err) headers.should.be.false done() }) }) it('should fire on index', function (done) { request(server) .get('/pets/') .expect(200, /tobi/, function (err, res) { if (err) return done(err) headers.should.be.true done() }) }) it('should not fire on redirect', function (done) { request(server) .get('/pets') .expect(301, function (err, res) { if (err) return done(err) headers.should.be.false done() }) }) it('should provide path', function (done) { request(server) .get('/nums') .expect(200, '123456789', function (err, res) { if (err) return done(err) headers.should.be.true args[1].should.endWith('nums') done() }) }) it('should provide stat', function (done) { request(server) .get('/nums') .expect(200, '123456789', function (err, res) { if (err) return done(err) headers.should.be.true args[2].should.have.property('mtime') done() }) }) it('should allow altering headers', function (done) { fn = function (res, path, stat) { res.setHeader('Cache-Control', 'no-cache') res.setHeader('Content-Type', 'text/x-custom') res.setHeader('ETag', 'W/"everything"') res.setHeader('X-Created', stat.ctime.toUTCString()) } request(server) .get('/nums') .expect('Cache-Control', 'no-cache') .expect('Content-Type', 'text/x-custom') .expect('ETag', 'W/"everything"') .expect('X-Created', dateRegExp) .expect(200, '123456789', done) }) }) describe('when no "directory" listeners are present', function(){ var server before(function(){ server = http.createServer(function(req, res){ send(req, req.url, {root: 'test/fixtures'}) .pipe(res) }) }) it('should respond with an HTML redirect', function(done){ request(server) .get('/pets') .expect('Location', '/pets/') .expect('Content-Type', 'text/html; charset=utf-8') .expect(301, 'Redirecting to <a href="/pets/">/pets/</a>\n', done) }) }) describe('when no "error" listeners are present', function(){ it('should respond to errors directly', function(done){ var app = http.createServer(function(req, res){ send(req, 'test/fixtures' + req.url).pipe(res); }); request(app) .get('/foobar') .expect(404, 'Not Found', done) }) }) describe('with conditional-GET', function(){ it('should respond with 304 on a match', function(done){ request(app) .get('/name.txt') .expect(200, function(err, res){ if (err) return done(err) request(app) .get('/name.txt') .set('If-None-Match', res.headers.etag) .expect(304, function(err, res){ if (err) return done(err) res.headers.should.not.have.property('content-type'); res.headers.should.not.have.property('content-length'); done(); }); }) }) it('should respond with 200 otherwise', function(done){ request(app) .get('/name.txt') .expect(200, function(err, res){ if (err) return done(err) request(app) .get('/name.txt') .set('If-None-Match', '"123"') .expect(200, 'tobi', done) }) }) }) describe('with Range request', function(){ it('should support byte ranges', function(done){ request(app) .get('/nums') .set('Range', 'bytes=0-4') .expect(206, '12345', done); }) it('should be inclusive', function(done){ request(app) .get('/nums') .set('Range', 'bytes=0-0') .expect(206, '1', done); }) it('should set Content-Range', function(done){ request(app) .get('/nums') .set('Range', 'bytes=2-5') .expect('Content-Range', 'bytes 2-5/9') .expect(206, done); }) it('should support -n', function(done){ request(app) .get('/nums') .set('Range', 'bytes=-3') .expect(206, '789', done); }) it('should support n-', function(done){ request(app) .get('/nums') .set('Range', 'bytes=3-') .expect(206, '456789', done); }) it('should respond with 206 "Partial Content"', function(done){ request(app) .get('/nums') .set('Range', 'bytes=0-4') .expect(206, done); }) it('should set Content-Length to the # of octets transferred', function(done){ request(app) .get('/nums') .set('Range', 'bytes=2-3') .expect('Content-Length', '2') .expect(206, '34', done); }) describe('when last-byte-pos of the range is greater the length', function(){ it('is taken to be equal to one less than the length', function(done){ request(app) .get('/nums') .set('Range', 'bytes=2-50') .expect('Content-Range', 'bytes 2-8/9') .expect(206, done); }) it('should adapt the Content-Length accordingly', function(done){ request(app) .get('/nums') .set('Range', 'bytes=2-50') .expect('Content-Length', '7') .expect(206, done); }) }) describe('when the first- byte-pos of the range is greater length', function(){ it('should respond with 416', function(done){ request(app) .get('/nums') .set('Range', 'bytes=9-50') .expect('Content-Range', 'bytes */9') .expect(416, done); }) }) describe('when syntactically invalid', function(){ it('should respond with 200 and the entire contents', function(done){ request(app) .get('/nums') .set('Range', 'asdf') .expect(200, '123456789', done); }) }) describe('when multiple ranges', function(){ it('should respond with 200 and the entire contents', function(done){ request(app) .get('/nums') .set('Range', 'bytes=1-1,3-') .expect(200, '123456789', done); }) }) describe('when if-range present', function(){ it('should respond with parts when etag unchanged', function(done){ request(app) .get('/nums') .expect(200, function(err, res){ if (err) return done(err); var etag = res.headers.etag; request(app) .get('/nums') .set('If-Range', etag) .set('Range', 'bytes=0-0') .expect(206, '1', done); }) }) it('should respond with 200 when etag changed', function(done){ request(app) .get('/nums') .expect(200, function(err, res){ if (err) return done(err); var etag = res.headers.etag.replace(/"(.)/, '"0$1'); request(app) .get('/nums') .set('If-Range', etag) .set('Range', 'bytes=0-0') .expect(200, '123456789', done); }) }) it('should respond with parts when modified unchanged', function(done){ request(app) .get('/nums') .expect(200, function(err, res){ if (err) return done(err); var modified = res.headers['last-modified'] request(app) .get('/nums') .set('If-Range', modified) .set('Range', 'bytes=0-0') .expect(206, '1', done); }) }) it('should respond with 200 when modified changed', function(done){ request(app) .get('/nums') .expect(200, function(err, res){ if (err) return done(err); var modified = Date.parse(res.headers['last-modified']) - 20000; request(app) .get('/nums') .set('If-Range', new Date(modified).toUTCString()) .set('Range', 'bytes=0-0') .expect(200, '123456789', done); }) }) }) }) describe('when "options" is specified', function(){ it('should support start/end', function(done){ var app = http.createServer(function(req, res){ var i = parseInt(req.url.slice(1)); send(req, 'test/fixtures/nums', { start:i*3, end:i*3+2 }).pipe(res); }); request(app) .get('/1') .expect(200, '456', done); }) it('should adjust too large end', function(done){ var app = http.createServer(function(req, res){ var i = parseInt(req.url.slice(1)); send(req, 'test/fixtures/nums', { start:i*3, end:90 }).pipe(res); }); request(app) .get('/1') .expect(200, '456789', done); }) it('should support start/end with Range request', function(done){ var app = http.createServer(function(req, res){ var i = parseInt(req.url.slice(1)); send(req, 'test/fixtures/nums', { start:i*3, end:i*3+2 }).pipe(res); }); request(app) .get('/0') .set('Range', 'bytes=-2') .expect(206, '23', done) }) }) describe('.etag()', function(){ it('should support disabling etags', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: fixtures}) .etag(false) .pipe(res); }); request(app) .get('/nums') .expect(200, function(err, res){ if (err) return done(err); res.headers.should.not.have.property('etag'); done(); }); }) }) describe('.from()', function(){ it('should set with deprecated from', function(done){ var app = http.createServer(function(req, res){ send(req, req.url) .from(__dirname + '/fixtures') .pipe(res); }); request(app) .get('/pets/../name.txt') .expect(200, 'tobi', done) }) }) describe('.hidden()', function(){ it('should default support sending hidden files', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: fixtures}) .hidden(true) .pipe(res); }); request(app) .get('/.hidden') .expect(200, /secret/, done); }) }) describe('.index()', function(){ it('should be configurable', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: fixtures}) .index('tobi.html') .pipe(res); }); request(app) .get('/') .expect(200, '<p>tobi</p>', done); }) it('should support disabling', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: fixtures}) .index(false) .pipe(res); }); request(app) .get('/pets/') .expect(403, done); }) it('should support fallbacks', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: fixtures}) .index(['default.htm', 'index.html']) .pipe(res); }); request(app) .get('/pets/') .expect(200, fs.readFileSync(path.join(fixtures, 'pets', 'index.html'), 'utf8'), done) }) }) describe('.maxage()', function(){ it('should default to 0', function(done){ var app = http.createServer(function(req, res){ send(req, 'test/fixtures/name.txt') .maxage(undefined) .pipe(res); }); request(app) .get('/name.txt') .expect('Cache-Control', 'public, max-age=0', done) }) it('should floor to integer', function(done){ var app = http.createServer(function(req, res){ send(req, 'test/fixtures/name.txt') .maxage(1234) .pipe(res); }); request(app) .get('/name.txt') .expect('Cache-Control', 'public, max-age=1', done) }) it('should accept string', function(done){ var app = http.createServer(function(req, res){ send(req, 'test/fixtures/name.txt') .maxage('30d') .pipe(res); }); request(app) .get('/name.txt') .expect('Cache-Control', 'public, max-age=2592000', done) }) it('should max at 1 year', function(done){ var app = http.createServer(function(req, res){ send(req, 'test/fixtures/name.txt') .maxage(Infinity) .pipe(res); }); request(app) .get('/name.txt') .expect('Cache-Control', 'public, max-age=31536000', done) }) }) describe('.root()', function(){ it('should set root', function(done){ var app = http.createServer(function(req, res){ send(req, req.url) .root(__dirname + '/fixtures') .pipe(res); }); request(app) .get('/pets/../name.txt') .expect(200, 'tobi', done) }) }) }) describe('send(file, options)', function(){ describe('etag', function(){ it('should support disabling etags', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {etag: false, root: fixtures}) .pipe(res); }); request(app) .get('/nums') .expect(200, function(err, res){ if (err) return done(err); res.headers.should.not.have.property('etag'); done(); }); }) }) describe('extensions', function () { it('should be not be enabled by default', function (done) { var server = createServer({root: fixtures}); request(server) .get('/tobi') .expect(404, done) }) it('should be configurable', function (done) { var server = createServer({extensions: 'txt', root: fixtures}) request(server) .get('/name') .expect(200, 'tobi', done) }) it('should support disabling extensions', function (done) { var server = createServer({extensions: false, root: fixtures}) request(server) .get('/name') .expect(404, done) }) it('should support fallbacks', function (done) { var server = createServer({extensions: ['htm', 'html', 'txt'], root: fixtures}) request(server) .get('/name') .expect(200, '<p>tobi</p>', done) }) it('should 404 if nothing found', function (done) { var server = createServer({extensions: ['htm', 'html', 'txt'], root: fixtures}) request(server) .get('/bob') .expect(404, done) }) it('should skip directories', function (done) { var server = createServer({extensions: ['file', 'dir'], root: fixtures}) request(server) .get('/name') .expect(404, done) }) it('should not search if file has extension', function (done) { var server = createServer({extensions: 'html', root: fixtures}) request(server) .get('/thing.html') .expect(404, done) }) }) describe('lastModified', function () { it('should support disabling last-modified', function (done) { var app = http.createServer(function(req, res){ send(req, req.url, {lastModified: false, root: fixtures}) .pipe(res) }) request(app) .get('/nums') .expect(200, function (err, res) { if (err) return done(err) res.headers.should.not.have.property('last-modified') done() }) }) }) describe('from', function(){ it('should set with deprecated from', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {from: __dirname + '/fixtures'}) .pipe(res) }); request(app) .get('/pets/../name.txt') .expect(200, 'tobi', done) }) }) describe('dotfiles', function () { it('should default to "ignore"', function (done) { request(createServer({root: fixtures})) .get('/.hidden') .expect(404, done) }) it('should allow file within dotfile directory for back-compat', function (done) { request(createServer({root: fixtures})) .get('/.mine/name.txt') .expect(200, /tobi/, done) }) it('should reject bad value', function (done) { request(createServer({dotfiles: 'bogus'})) .get('/nums') .expect(500, /dotfiles/, done) }) describe('when "allow"', function (done) { it('should send dotfile', function (done) { request(createServer({dotfiles: 'allow', root: fixtures})) .get('/.hidden') .expect(200, /secret/, done) }) it('should send within dotfile directory', function (done) { request(createServer({dotfiles: 'allow', root: fixtures})) .get('/.mine/name.txt') .expect(200, /tobi/, done) }) it('should 404 for non-existent dotfile', function (done) { request(createServer({dotfiles: 'allow', root: fixtures})) .get('/.nothere') .expect(404, done) }) }) describe('when "deny"', function (done) { it('should 403 for dotfile', function (done) { request(createServer({dotfiles: 'deny', root: fixtures})) .get('/.hidden') .expect(403, done) }) it('should 403 for dotfile directory', function (done) { request(createServer({dotfiles: 'deny', root: fixtures})) .get('/.mine') .expect(403, done) }) it('should 403 for dotfile directory with trailing slash', function (done) { request(createServer({dotfiles: 'deny', root: fixtures})) .get('/.mine/') .expect(403, done) }) it('should 403 for file within dotfile directory', function (done) { request(createServer({dotfiles: 'deny', root: fixtures})) .get('/.mine/name.txt') .expect(403, done) }) it('should 403 for non-existent dotfile', function (done) { request(createServer({dotfiles: 'deny', root: fixtures})) .get('/.nothere') .expect(403, done) }) it('should 403 for non-existent dotfile directory', function (done) { request(createServer({dotfiles: 'deny', root: fixtures})) .get('/.what/name.txt') .expect(403, done) }) it('should send files in root dotfile directory', function (done) { request(createServer({dotfiles: 'deny', root: path.join(fixtures, '.mine')})) .get('/name.txt') .expect(200, /tobi/, done) }) it('should 403 for dotfile without root', function (done) { var server = http.createServer(function onRequest(req, res) { send(req, fixtures + '/.mine' + req.url, {dotfiles: 'deny'}).pipe(res) }) request(server) .get('/name.txt') .expect(403, done) }) }) describe('when "ignore"', function (done) { it('should 404 for dotfile', function (done) { request(createServer({dotfiles: 'ignore', root: fixtures})) .get('/.hidden') .expect(404, done) }) it('should 404 for dotfile directory', function (done) { request(createServer({dotfiles: 'ignore', root: fixtures})) .get('/.mine') .expect(404, done) }) it('should 404 for dotfile directory with trailing slash', function (done) { request(createServer({dotfiles: 'ignore', root: fixtures})) .get('/.mine/') .expect(404, done) }) it('should 404 for file within dotfile directory', function (done) { request(createServer({dotfiles: 'ignore', root: fixtures})) .get('/.mine/name.txt') .expect(404, done) }) it('should 404 for non-existent dotfile', function (done) { request(createServer({dotfiles: 'ignore', root: fixtures})) .get('/.nothere') .expect(404, done) }) it('should 404 for non-existent dotfile directory', function (done) { request(createServer({dotfiles: 'ignore', root: fixtures})) .get('/.what/name.txt') .expect(404, done) }) it('should send files in root dotfile directory', function (done) { request(createServer({dotfiles: 'ignore', root: path.join(fixtures, '.mine')})) .get('/name.txt') .expect(200, /tobi/, done) }) it('should 404 for dotfile without root', function (done) { var server = http.createServer(function onRequest(req, res) { send(req, fixtures + '/.mine' + req.url, {dotfiles: 'ignore'}).pipe(res) }) request(server) .get('/name.txt') .expect(404, done) }) }) }) describe('hidden', function(){ it('should default to false', function(done){ request(app) .get('/.hidden') .expect(404, 'Not Found', done) }) it('should default support sending hidden files', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {hidden: true, root: fixtures}) .pipe(res); }); request(app) .get('/.hidden') .expect(200, /secret/, done) }) }) describe('maxAge', function(){ it('should default to 0', function(done){ request(app) .get('/name.txt') .expect('Cache-Control', 'public, max-age=0', done) }) it('should floor to integer', function(done){ var app = http.createServer(function(req, res){ send(req, 'test/fixtures/name.txt', {maxAge: 123956}) .pipe(res); }); request(app) .get('/name.txt') .expect('Cache-Control', 'public, max-age=123', done) }) it('should accept string', function(done){ var app = http.createServer(function(req, res){ send(req, 'test/fixtures/name.txt', {maxAge: '30d'}) .pipe(res); }); request(app) .get('/name.txt') .expect('Cache-Control', 'public, max-age=2592000', done) }) it('should max at 1 year', function(done){ var app = http.createServer(function(req, res){ send(req, 'test/fixtures/name.txt', {maxAge: Infinity}) .pipe(res); }); request(app) .get('/name.txt') .expect('Cache-Control', 'public, max-age=31536000', done) }) }) describe('index', function(){ it('should default to index.html', function(done){ request(app) .get('/pets/') .expect(fs.readFileSync(path.join(fixtures, 'pets', 'index.html'), 'utf8'), done) }) it('should be configurable', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: fixtures, index: 'tobi.html'}) .pipe(res); }); request(app) .get('/') .expect(200, '<p>tobi</p>', done); }) it('should support disabling', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: fixtures, index: false}) .pipe(res); }); request(app) .get('/pets/') .expect(403, done); }) it('should support fallbacks', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: fixtures, index: ['default.htm', 'index.html']}) .pipe(res); }); request(app) .get('/pets/') .expect(200, fs.readFileSync(path.join(fixtures, 'pets', 'index.html'), 'utf8'), done) }) it('should 404 if no index file found (file)', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: fixtures, index: 'default.htm'}) .pipe(res); }); request(app) .get('/pets/') .expect(404, done) }) it('should 404 if no index file found (dir)', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: fixtures, index: 'pets'}) .pipe(res); }); request(app) .get('/') .expect(404, done) }) it('should not follow directories', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: fixtures, index: ['pets', 'name.txt']}) .pipe(res); }); request(app) .get('/') .expect(200, 'tobi', done) }) it('should work without root', function (done) { var server = http.createServer(function(req, res){ var p = path.join(fixtures, 'pets').replace(/\\/g, '/') + '/'; send(req, p, {index: ['index.html']}) .pipe(res); }); request(server) .get('/') .expect(200, /tobi/, done) }) }) describe('root', function(){ describe('when given', function(){ it('should join root', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: __dirname + '/fixtures'}) .pipe(res); }); request(app) .get('/pets/../name.txt') .expect(200, 'tobi', done) }) it('should work with trailing slash', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: __dirname + '/fixtures/'}) .pipe(res); }); request(app) .get('/name.txt') .expect(200, 'tobi', done) }) it('should work with empty path', function(done){ var app = http.createServer(function(req, res){ send(req, '', {root: __dirname + '/fixtures'}) .pipe(res); }); request(app) .get('/name.txt') .expect(301, /Redirecting to/, done) }) it('should restrict paths to within root', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: __dirname + '/fixtures'}) .pipe(res); }); request(app) .get('/pets/../../send.js') .expect(403, done) }) it('should allow .. in root', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: __dirname + '/fixtures/../fixtures'}) .pipe(res); }); request(app) .get('/pets/../../send.js') .expect(403, done) }) it('should not allow root transversal', function(done){ var app = http.createServer(function(req, res){ send(req, req.url, {root: __dirname + '/fixtures/name.d'}) .pipe(res); }); request(app) .get('/../name.dir/name.txt') .expect(403, done) }) }) describe('when missing', function(){ it('should consider .. malicious', function(done){ var app = http.createServer(function(req, res){ send(req, fixtures + req.url) .pipe(res); }); request(app) .get('/../send.js') .expect(403, done) }) it('should still serve files with dots in name', function(done){ var app = http.createServer(function(req, res){ send(req, fixtures + req.url) .pipe(res); }); request(app) .get('/do..ts.txt') .expect(200, '...', done); }) }) }) }) function createServer(opts) { return http.createServer(function onRequest(req, res) { try { send(req, req.url, opts).pipe(res) } catch (err) { res.statusCode = 500 res.end(err.message) } }) }
'use strict'; angular.module('mapQuestApp') .controller('ParticipantsCtrl', ['$scope', '$routeParams', 'User', function ($scope, $routeParams, User) { $scope.view = {}; $scope.view.loading = true; $scope.view.participants = []; User.getParticipants($routeParams.quest) .then(function(result) { $scope.view.participants = result.data; $scope.view.loading = false; }); /** * Clear search filed and reset filtering */ $scope.clearSearch = function() { $scope.view.search = null; }; }]);
var spawn = require('child_process').spawn; var gaze = require('gaze'); // The process where the commands are being run var cmdProcess; var queue = []; var running = false; // Default options var options = { verbose: false, interrupt: true, useQueue: false, pattern: ['**/*', '!**/node_modules/**'] }; module.exports = function (argv) { // Get rid of 'node' and 'bin' arguments argv = argv.slice(2); if (argv.length === 0) { console.log('Usage: eye <command>'); console.log(''); console.log('Options:'); console.log(''); console.log(' --*glob=<pattern> Specify which files you want to watch'); console.log(''); console.log(' --*queue Have commands form a queue and be run one at a time until the queue is empty'); console.log(''); console.log(' --*continue If a file event is triggered while a command is being run, don\'t interrupt it'); console.log(''); console.log(' --*verbose Log files watched, text of the comand being run and more'); process.exit(1); } // Add all of the arguments to the commandArguments array unelss they are eye // options var commandArguments = []; for (var i = 0; i <argv.length; i++) { var argument = argv[i]; if (argument.indexOf('--*glob=') !== -1) { // Get everything after '=' and replace '%' with '!' because Unix // exectutes everything after '!' so we can't use it. And finally split // at comma to get an array of globs options.pattern = argument.split('=')[1].split('%').join('!').split(','); } else if (argument.indexOf('--*verbose') !== -1) { options.verbose = true; } else if (argument.indexOf('--*queue') !== -1) { options.useQueue = true; } else if (argument.indexOf('--*continue') !== -1) { options.interrupt = false; } else { commandArguments.push(argument); } } var commands = processArguments(commandArguments, []); if (options.verbose) { console.log('pattern is:'); console.log(options.pattern); } // Watch file selected by glob for changes gaze(options.pattern, function(err) { if (err) throw err; // Log startup message console.log('eye is watching...'); // Log watched files if (options.verbose) { console.log('watched files:'); console.log(this.watched()); } this.on('error', function(err) { throw err; }); this.on('all', function(event, filepath) { // Log file event if (options.verbose) console.log(filepath + ' was ' + event); if (options.useQueue) { // Add commands to queue queue = queue.concat(commands); } else if (! queue.length) { queue = [].concat(commands); } // If queue isn't being run, run it if (! running) { runCommands(commands); // If commands are in the process of running } else if (options.interrupt && cmdProcess) { // The closing of the command process will remove the first queue item // so we add and empty queue item so it won't remove the next command if (! options.queue) queue.unshift(''); cmdProcess.kill(); } }); }); }; function runCommands (commands) { running = true; // Run the first command in the queue var command = queue[0]; if (options.verbose) { console.log('running: ' + command.cmd + ' ' + command.options.join(' ')); console.log('result:'); } cmdProcess = spawn(command.cmd, command.options); cmdProcess.stdout.on('data', function (data) { process.stdout.write('' + data); }); cmdProcess.stderr.on('data', function (data) { process.stdout.write('' + data); }); cmdProcess.on('close', function () { // Remove executed command from queue queue.shift(); // If there are more commands in the queue, recurse if (queue.length > 0) runCommands(commands); running = false; }); } function processArguments (argv, commands) { // Create command, first argument is the command and the rest are options var command = { cmd: argv.splice(0, 1)[0], options: [] }; // Add arguemnts as options. If argument is 'and', add current command to // commands array and recurse to get next command for (var i = 0; i < argv.length; i++) { if (argv[i] !== 'and') { command.options.push(argv[i]); } else { commands.push(command); return processArguments(argv.slice(i + 1), commands); } } commands.push(command); return commands; }
export const LOGIN_STATUS = 'LOGIN_STATUS'; export const LOGIN_USER = 'LOGIN_USER'; export const REGISTER_USER = 'REGISTER_USER'; export const LOGOUT_USER = 'LOGOUT_USER'; export const CREATE_GAME = 'CREATE_GAME'; export const END_GAME = 'END_GAME'; export const JOIN_GAME = 'JOIN_GAME'; export const LEAVE_GAME = 'LEAVE_GAME'; export const SAVE_GAME = 'SAVE_GAME'; export const FINISH_GAME = 'FINISH_GAME';
module.exports = (function(){ console.log("--stateProvider"); this.game_state = {}; this.loadCurrentState = function(game_state){ this.game_state = game_state; }; this.getPot = function(){ //handle return 222; }; this.getCurrentState = function() { return this.game_state; }; this.getMyCards = function() { return this.game_state["players"][this.game_state["in_action"]]["hole_cards"] || []; }; this.getFlopCards = function() { return this.game_state["community_cards"]; }; return this; })();
(function (window, undefined) { 'use strict'; function setUpActiveTab() { if(localStorage.getItem('main-nav')){ $('a[href="'+ localStorage['main-nav'] + '"]').tab('show'); } } function setUpOptionsCheckboxes() { if(localStorage.getItem('options')){ var optionsArr = JSON.parse(localStorage.options), optionsForm = $('#options-form'); for(var i=0;i<optionsArr.length;i++){ var box = optionsForm.find('input:checkbox').eq(i); box.prop('checked', optionsArr[i]); setOptionDisplayState(box); } } } function setOptionDisplayState(box) { var cssName = $.trim(box.parent('label').text()).toLowerCase(); if(box.is(':checked')){ $('div.'+cssName).css('display', 'block'); $('li.'+cssName).css('display', 'block'); $('span.'+cssName).css('display', 'inline'); }else{ $('.'+cssName).css('display', 'none'); } } function setUpPrettyPrint() { var h = location.hash; $('.prettyprint.linenums').each(function(i, b) { var l = 1; $(b).find('ol li').each(function(i, n) { n.id = 'l' + l; l++; }); }); location.hash = ''; location.hash = h; } /* global $:true */ $(function() { $('[data-tabid]').on('click', function(event) { var tabToActivate = $(this).attr('data-tabid'), anchor = $(this).attr('data-anchor'); event.preventDefault(); $('[data-toggle=tab][href="'+ tabToActivate + '"]').click(); $(document).scrollTop( $(anchor).offset().top ); }); // ************************************************************************* // // Initializations + Event listeners // ************************************************************************* // // // Store last clicked tab in local storage // $('#main-nav li').on('click', function(e) { e.preventDefault(); localStorage['main-nav'] = $(this).find('a').attr('href'); }); // // Bind change events for options form checkboxes // $('#options-form input:checkbox').on('change', function(){ setOptionDisplayState($(this)); // Update localstorage var optionsArr = []; $('#options-form input:checkbox').each(function(i,el) { optionsArr.push($(el).is(':checked')); }); localStorage.options = JSON.stringify(optionsArr); }); // // Keyboard shortcut - 's' key // This brings the api search input into focus. // $(window).keyup(function(e) { // Listen for 's' key and focus search input if pressed if(e.keyCode === 83){ // 's' $('#api-tabview-filter input').focus(); } }); // // Keyboard shortcut - 'ctrl+left', 'ctrl+right', 'up', 'down' // These shortcuts offer sidebar navigation via keyboard, // *only* when sidebar or any element within has focus. // var nextIndex; $('#sidebar').keydown(function(e) { var $this = $(this); // Determine if the control/command key was pressed if(e.ctrlKey){ if(e.keyCode === 37){ // left arrow $('#main-nav li a:first').tab('show'); } else if(e.keyCode === 39){ // right arrow $('#main-nav li a:last').tab('show'); } } else { if(e.keyCode === 40){ // down arrow if ($('#api-tabview-filter input').is(':focus')) { // Scenario 1: We're focused on the search input; move down to the first li $this.find('.tab-content .tab-pane.active li:first a').focus(); } else if ($this.find('.tab-content .tab-pane.active li:last a').is(':focus')) { // Scenario 2: We're focused on the last li; move up to search input $('#api-tabview-filter input').focus(); } else { // Scenario 3: We're in the list but not on the last element, simply move down nextIndex = $this .find('.tab-content .tab-pane.active li') .find('a:focus') .parent('li').index() + 1; $this.find('.tab-content .tab-pane.active li:eq('+nextIndex+') a').focus(); } e.preventDefault(); // Stop page from scrolling } else if (e.keyCode === 38){ // up arrow if($('#api-tabview-filter input').is(':focus')) { // Scenario 1: We're focused on the search input; move down to the last li $this.find('.tab-content .tab-pane.active li:last a').focus(); }else if($this.find('.tab-content .tab-pane.active li:first a').is(':focus')){ // Scenario 2: We're focused on the first li; move up to search input $('#api-tabview-filter input').focus(); }else{ // Scenario 3: We're in the list but not on the first element, simply move up nextIndex = $this .find('.tab-content .tab-pane.active li') .find('a:focus') .parent('li').index() - 1; $this.find('.tab-content .tab-pane.active li:eq('+nextIndex+') a').focus(); } e.preventDefault(); // Stop page from scrolling } } }); // ************************************************************************* // // Immediate function calls // ************************************************************************* // /* global prettyPrint:true */ prettyPrint(); setUpPrettyPrint(); setUpActiveTab(); setUpOptionsCheckboxes(); }); })(this); // });
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./src/entry.js"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./src/agent.js": /*!**********************!*\ !*** ./src/agent.js ***! \**********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var car = __webpack_require__(/*! ./car.js */ "./src/car.js"); function agent(opt, world) { this.car = new car(world, {}); this.options = opt; this.world = world; this.frequency = 30; this.reward = 0; this.loaded = false; this.loss = 0; this.timer = 0.0; this.thrust = 0; this.steer = 0; this.velocity = []; if (this.options.dynamicallyLoaded !== true) { this.init(world.brains.actor.newConfiguration(), null); } }; agent.prototype.init = function (actor, critic) { var actions = 3 var temporal = 1 var states = this.car.sensors.dimensions var input = window.neurojs.Agent.getInputDimension(states, actions, temporal) this.brain = new window.neurojs.Agent({ actor: actor, critic: critic, states: states, actions: actions, algorithm: 'ddpg', temporalWindow: temporal, discount: 0.98, learningRate: { actor: 1e-4, critic: 1e-3 }, experience: 100e3, // buffer: window.neurojs.Buffers.UniformReplayBuffer, learningPerTick: 40, startLearningAt: 1200, theta: 0.050, // progressive copy alpha: 0.000, // advantage learning clipGradients: { action: 10, parameter: 10 }, // actionDecay: 1e-5 }) // this.world.brains.shared.add('actor', this.brain.algorithm.actor) this.world.brains.shared.add('critic', this.brain.algorithm.critic) this.actions = actions this.car.agent = this this.car.addToWorld() this.loaded = true }; function sigmoid(x) { return 1.0/(1.0 + Math.exp(-x)); } agent.prototype.step = function (dt) { if (!this.loaded) { return } this.timer += dt if (this.timer >= 1.0 / this.frequency) { this.car.update() this.reward = this.generateReward(); // Math.max(-1.0, reward); this.loss = this.brain.learn(this.reward); this.action = this.brain.policy(this.car.sensors.data); let thrust = this.action[0]; let steer = this.action[1]; if (isNaN(steer) || isNaN(thrust)) { alert("STOPPING.. some action value is NaN. steer: " + steer + "; thrust: " + thrust); } this.thrust = thrust; this.steer = steer; this.car.impact = 0; this.car.reward = this.reward; this.car.step(); this.timer = 0.0; } if (this.action) { this.car.handle(this.thrust, this.steer); } }; agent.prototype.generateReward = function () { let pos = this.car.chassisBody.position; let vel = this.car.speed.local; let speed = this.car.speed.velocity; let reward = 0; const velOneSecAgo = this.velocity.length >= this.frequency ? this.velocity.shift() : 0; // If we are not moving or have contact, this is bad. if (this.car.hasContact('obstacle') || this.car.hasContact('car')) { reward = -1; // avoid at all cost } else if (Math.abs(speed) < 0.05) { reward = -1; // standing still is bad } else if (speed < 0 || this.steer ** 2 > 0.50) { reward = 0; // no driving in circles } else { reward = Math.abs(vel[1]) / 36; } if (isNaN(reward)) { reward = 0; } this.velocity.push(vel[1]); return Math.min(Math.max(-1.0, reward), 2.0); }; agent.prototype.draw = function (context) { }; module.exports = agent; /***/ }), /***/ "./src/car.js": /*!********************!*\ !*** ./src/car.js ***! \********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var color = __webpack_require__(/*! ./color.js */ "./src/color.js"), sensors = __webpack_require__(/*! ./sensors.js */ "./src/sensors.js"), tc = __webpack_require__(/*! ./tiny-color.js */ "./src/tiny-color.js"); // var p2 = require('p2') class Car { constructor(world, opt) { this.maxSteer = Math.PI / 7 this.maxEngineForce = 10 this.maxBrakeForce = 20 this.maxBackwardForce = 2 this.linearDamping = 0.5 this.contacts = {"car": 0, "obstacle": 0, "other": 0} this.impact = 0 this.world = world this.agent = null this.init() } init() { this.createPhysicalBody() this.sensors = Car.Sensors.build(this) this.speed = this.sensors.getByType("speed")[0] } createPhysicalBody() { // Create a dynamic body for the chassis this.chassisBody = new p2.Body({ mass: 1, damping: 0.2, angularDamping: 0.3, ccdSpeedThreshold: 0, ccdIterations: 48 }); this.chassisBody.entity = 'car'; this.wheels = {} this.chassisBody.color = color.randomPastelHex(); this.chassisBody.car = true; this.chassisBody.damping = this.linearDamping; var boxShape = new p2.Box({ width: 0.5, height: 1 }); boxShape.material = this.world.materials.car this.chassisBody.addShape(boxShape); this.chassisBody.gl_create = (function (sprite, r) { this.overlay = new PIXI.Graphics(); this.overlay.visible = true; sprite.addChild(this.overlay); var wheels = new PIXI.Graphics() sprite.addChild(wheels) var w = 0.12, h = 0.22 var space = 0.07 var col = "#" + this.chassisBody.color.toString(16) col = parseInt(tc(col).darken(50).toHex(), 16) var alpha = 0.35, alphal = 0.9 var tl = new PIXI.Graphics() var tr = new PIXI.Graphics() tl.beginFill(col, alpha) tl.position.x = -0.25 tl.position.y = 0.5 - h / 2 - space tl.drawRect(-w / 2, -h / 2, w, h) tl.endFill() tr.beginFill(col, alpha) tr.position.x = 0.25 tr.position.y = 0.5 - h / 2 - space tr.drawRect(-w / 2, -h / 2, w, h) tr.endFill() this.wheels.topLeft = tl this.wheels.topRight = tr wheels.addChild(tl) wheels.addChild(tr) wheels.beginFill(col, alpha) // wheels.lineStyle(0.01, col, alphal) wheels.drawRect(-0.25 - w / 2, -0.5 + space, w, h) wheels.endFill() wheels.beginFill(col, alpha) // wheels.lineStyle(0.01, col, alphal) wheels.drawRect(0.25 - w / 2, -0.5 + space, w, h) wheels.endFill() }).bind(this); // Create the vehicle this.vehicle = new p2.TopDownVehicle(this.chassisBody); // Add one front wheel and one back wheel - we don't actually need four :) this.frontWheel = this.vehicle.addWheel({ localPosition: [0, 0.5] // front }); this.frontWheel.setSideFriction(50); // Back wheel this.backWheel = this.vehicle.addWheel({ localPosition: [0, -0.5] // back }); this.backWheel.setSideFriction(40); // Less side friction on back wheel makes it easier to drift } update() { this.sensors.update() } step() { this.draw() } draw() { if (this.overlay.visible !== true) { return } this.overlay.clear() if (this.agent) { this.overlay.lineStyle(0.1, 0, 0.5); this.overlay.moveTo(0, 0); this.overlay.lineTo(0, this.agent.reward); } this.sensors.draw(this.overlay) } handle(throttle, steer) { // Steer value zero means straight forward. Positive is left and negative right. this.frontWheel.steerValue = this.maxSteer * steer * Math.PI / 2 // Engine force forward var force = throttle * this.maxEngineForce if (force < 0) { if (this.backWheel.getSpeed() > 0.1) { this.backWheel.setBrakeForce(-throttle * this.maxBrakeForce) this.backWheel.engineForce = 0.0 } else { this.backWheel.setBrakeForce(0) this.backWheel.engineForce = throttle * this.maxBackwardForce } } else { this.backWheel.setBrakeForce(0) this.backWheel.engineForce = force } this.wheels.topLeft.rotation = this.frontWheel.steerValue * 0.7071067812 this.wheels.topRight.rotation = this.frontWheel.steerValue * 0.7071067812 } handleKeyboard(k) { // To enable control of a car through the keyboard, uncomment: // this.handle((k.getN(38) - k.getN(40)), (k.getN(37) - k.getN(39))) if (k.getD(83) === 1) { this.overlay.visible = !this.overlay.visible; } } addToWorld() { if (this.chassisBody.world) { return ; } this.chassisBody.position[0] = (Math.random() - .5) * this.world.size.w; this.chassisBody.position[1] = (Math.random() - .5) * this.world.size.h; this.chassisBody.angle = (Math.random() * 2.0 - 1.0) * Math.PI; this.world.p2.addBody(this.chassisBody) this.vehicle.addToWorld(this.world.p2) this.world.p2.on("beginContact", (event) => { let entity = null; if (event.bodyA === this.chassisBody) entity = event.bodyB.entity || 'other' else if (event.bodyB === this.chassisBody) entity = event.bodyA.entity || 'other' if (entity !== null && this.contacts[entity] !== undefined) { this.contacts[entity]++ } }); this.world.p2.on("endContact", (event) => { let entity = null; if (event.bodyA === this.chassisBody) entity = event.bodyB.entity || 'other' else if (event.bodyB === this.chassisBody) entity = event.bodyA.entity || 'other' if (entity !== null && this.contacts[entity] !== undefined) { this.contacts[entity]-- } }) this.world.p2.on("impact", (event) => { if ((event.bodyA === this.chassisBody || event.bodyB === this.chassisBody)) { this.impact = Math.sqrt( this.chassisBody.velocity[0] * this.chassisBody.velocity[0] + this.chassisBody.velocity[1] * this.chassisBody.velocity[1] ) } }) } hasContact(entity) { return this.contacts[entity] !== undefined && this.contacts[entity] > 0 } } Car.ShapeEntity = 2 Car.Sensors = (() => { var d = 0.05 var r = -0.25 + d, l = +0.25 - d var b = -0.50 + d, t = +0.50 - d return sensors.SensorBlueprint.compile([ { type: 'distance', angle: -45, length: 5 }, { type: 'distance', angle: -30, length: 5 }, { type: 'distance', angle: -15, length: 5 }, { type: 'distance', angle: +0, length: 5 }, { type: 'distance', angle: +15, length: 5 }, { type: 'distance', angle: +30, length: 5 }, { type: 'distance', angle: +45, length: 5 }, { type: 'distance', angle: -225, length: 3 }, { type: 'distance', angle: -195, length: 3 }, { type: 'distance', angle: -180, length: 5 }, { type: 'distance', angle: -165, length: 3 }, { type: 'distance', angle: -135, length: 3 }, { type: 'distance', angle: -10, length: 10 }, { type: 'distance', angle: -3, length: 10 }, { type: 'distance', angle: +0, length: 10 }, { type: 'distance', angle: +3, length: 10 }, { type: 'distance', angle: +10, length: 10 }, { type: 'distance', angle: +90, length: 7 }, { type: 'distance', angle: -90, length: 7 }, { type: 'speed' }, { type: 'contact' } ]) })() module.exports = Car; /***/ }), /***/ "./src/cardemo.js": /*!************************!*\ !*** ./src/cardemo.js ***! \************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { const app = __webpack_require__(/*! ./index.js */ "./src/index.js"); class CarDemo { constructor (element) { this.root = element // now to the more interesting part this.world = new app.world() this.renderer = new app.renderer(this.world, element) this.world.init(this.renderer) this.world.populate(4) // --- how many cars this.dispatcher = new app.dispatcher(this.renderer, this.world); this.dispatcher.begin() this.root.classList.add('booted') this.setLearning(false) } save() { const actorBuf = this.world.agents[0].brain.export(); const worldBuf = this.world.export(); const fusedBuf = neurojs.Binary.Writer.write([worldBuf, actorBuf]); downloadFile(new DataView(fusedBuf), "agent.bin"); } load(event, trackOnly = false) { var input = event.target; var reader = new FileReader(); reader.onload = () => { const buffer = reader.result if (trackOnly) { this.importTrack(buffer); } else { this.import(buffer); } }; reader.readAsArrayBuffer(input.files[0]); } import (buffer) { var imported = neurojs.Binary.Reader.read(buffer) this.importTrack(imported[0]) this.importBrain(imported[1]) } saveTrack() { downloadFile(this.exportTrack()) } exportTrack() { return this.world.export(); } importTrack (buffer) { this.world.import(buffer); } importBrain (buffer) { var imported = neurojs.NetOnDisk.readMultiPart(buffer); this.world.initialiseAgents(imported.actor, null); this.dispatcher.begin(); this.setLearning(false); } setLearning(learning) { for (var i = 0; i < this.world.agents.length; i++) { this.world.agents[i].brain.learning = learning; } this.world.plotRewardOnly = !learning; } setFreeze(freeze) { this.world.freeze = freeze; } } function downloadFile(dv, name) { var a; if (typeof window.downloadAnchor == 'undefined') { a = window.downloadAnchor = document.createElement("a"); a.style = "display: none"; document.body.appendChild(a); } else { a = window.downloadAnchor } var blob = new Blob([dv], { type: 'application/octet-binary' }), tmpURL = window.URL.createObjectURL(blob); a.href = tmpURL; a.download = name; a.click(); window.URL.revokeObjectURL(tmpURL); a.href = ""; } module.exports = CarDemo; /***/ }), /***/ "./src/color.js": /*!**********************!*\ !*** ./src/color.js ***! \**********************/ /*! no static exports found */ /***/ (function(module, exports) { //http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb function componentToHex(c) { var hex = c.toString(16); return hex.length === 1 ? "0" + hex : hex; } function rgbToHex(r, g, b) { return parseInt(componentToHex(r) + componentToHex(g) + componentToHex(b), 16); } //http://stackoverflow.com/questions/43044/algorithm-to-randomly-generate-an-aesthetically-pleasing-color-palette function randomPastelHex(){ var mix = [255,255,255]; var red = Math.floor(Math.random()*256); var green = Math.floor(Math.random()*256); var blue = Math.floor(Math.random()*256); // mix the color red = Math.floor((red + 3*mix[0]) / 4); green = Math.floor((green + 3*mix[1]) / 4); blue = Math.floor((blue + 3*mix[2]) / 4); return rgbToHex(red,green,blue); } module.exports = { randomPastelHex: randomPastelHex, rgbToHex: rgbToHex }; /***/ }), /***/ "./src/dispatcher.js": /*!***************************!*\ !*** ./src/dispatcher.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var requestAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); }; var keyboard = __webpack_require__(/*! ./keyboard.js */ "./src/keyboard.js"); function dispatcher(renderer, world) { this.renderer = renderer; this.world = world; this.animating = true; this.counter = 0; this.keyboard = new keyboard(); this.keyboard.subscribe((function (k) { for (var i = 0; i < this.world.agents.length; i++) { this.world.agents[i].car.handleKeyboard(k); } }).bind(this)); this.animationLoop = (now) => { if (this.animating) { requestAnimFrame(this.animationLoop.bind(this)); } const dt = this.dt(); this.step(dt); }; this.intervalLoop = () => { const dt = 1/60; this.step(dt); }; } dispatcher.prototype.dt = function () { var now = Date.now(); var diff = now - (this.prev || now); this.prev = now; return diff / 1000; }; dispatcher.prototype.step = function (dt) { // compute phyiscs this.world.step(dt); this.counter++; // draw everything if (this.animating || this.counter % 20 == 0) { this.renderer.render(); } }; dispatcher.prototype.begin = function (mode = 'animation') { if (this.interval) { clearInterval(this.interval); } if (mode === 'interval') { this.animating = false; this.interval = setInterval(this.intervalLoop, 0); } else if (mode === 'animation') { this.animating = true; requestAnimFrame(this.animationLoop); } else { throw 'Unknown mode.'; } this.mode = mode; }; dispatcher.prototype.goFast = function () { this.begin('interval'); }; dispatcher.prototype.goSlow = function () { this.begin('animation'); } dispatcher.prototype.stop = function () { this.animating = false; clearInterval(this.interval); }; module.exports = dispatcher; /***/ }), /***/ "./src/entry.js": /*!**********************!*\ !*** ./src/entry.js ***! \**********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { const CarDemo = __webpack_require__(/*! ./cardemo.js */ "./src/cardemo.js") function createLossChart() { var data = { series: [[], []] }; return new Chartist.Line('.ct-chart', data, { lineSmooth: Chartist.Interpolation.none() }); } function boot() { const el = document.getElementById("container"); const demo = new CarDemo(el); demo.world.chart = createLossChart(); return demo; }; const demo = boot(); window.demo = demo; const ageTextEl = document.getElementById('agent-age'); function updateAge() { ageTextEl.innerText = Math.floor(demo.world.age) + ''; } setInterval(updateAge, 450); /***/ }), /***/ "./src/index.js": /*!**********************!*\ !*** ./src/index.js ***! \**********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = { agent: __webpack_require__(/*! ./agent.js */ "./src/agent.js"), car: __webpack_require__(/*! ./car.js */ "./src/car.js"), dispatcher: __webpack_require__(/*! ./dispatcher.js */ "./src/dispatcher.js"), keyboard: __webpack_require__(/*! ./keyboard.js */ "./src/keyboard.js"), renderer: __webpack_require__(/*! ./renderer.js */ "./src/renderer.js"), world: __webpack_require__(/*! ./world.js */ "./src/world.js") }; /***/ }), /***/ "./src/keyboard.js": /*!*************************!*\ !*** ./src/keyboard.js ***! \*************************/ /*! no static exports found */ /***/ (function(module, exports) { function keyboard() { this.handlers = {}; this.subscribers = []; this.states = {}; document.onkeydown = this.keydown.bind(this); document.addEventListener('keydown', this.keydown.bind(this), true); document.addEventListener('keyup', this.keyup.bind(this), true); } keyboard.prototype.keydown = function (e) { this.states[e.keyCode] = this.states[e.keyCode] !== undefined ? this.states[e.keyCode] + 1 : 1; if (this.handlers[e.keyCode]) { this.handlers[e.keyCode](true); } for (var i = 0; i < this.subscribers.length; i++) { this.subscribers[i](this); } }; keyboard.prototype.keyup = function (e) { this.states[e.keyCode] = 0; if (this.handlers[e.keyCode]) { this.handlers[e.keyCode](false); } for (var i = 0; i < this.subscribers.length; i++) { this.subscribers[i](this); } }; keyboard.prototype.listen = function (key, callback) { this.handlers[key] = callback; }; keyboard.prototype.subscribe = function (callback) { this.subscribers.push(callback); }; keyboard.prototype.get = function (key) { if (this.states[key]) return this.states[key] > 0; return false; }; keyboard.prototype.getN = function (key) { if (this.states[key]) return this.states[key] > 0 ? 1 : 0; return 0; }; keyboard.prototype.getD = function (key) { if (this.states[key]) return this.states[key]; return 0; } module.exports = keyboard; /***/ }), /***/ "./src/renderer.js": /*!*************************!*\ !*** ./src/renderer.js ***! \*************************/ /*! no static exports found */ /***/ (function(module, exports) { function renderer(world, container) { this.world = world; this.world.p2.on("addBody", (e) => { this.add_body(e.body) }); this.world.p2.on("removeBody", (e) => { this.remove_body(e.body) }) if (container) { this.elementContainer = container } else { this.elementContainer = document.createElement("div"); this.elementContainer.style.width = "100%"; // this.elementContainer.style.height = "100%"; document.body.appendChild(this.elementContainer) } this.pixelRatio = window.devicePixelRatio || 1; this.pixi = new PIXI.autoDetectRenderer(0, 0, { antialias: true, resolution: this.pixelRatio, transparent: true }, false); // this.pixi.backgroundColor = 0xFFFFFF; this.stage = new PIXI.Container() this.container = new PIXI.DisplayObjectContainer(); this.stage.addChild(this.container) this.drawPoints = [] addEventListener(this.elementContainer, "touchstart mousedown", (e) => { this.mousedown(this.mousePositionFromEvent(e)) }); addEventListener(this.elementContainer, "touchmove mousemove", (e) => { if (!e.touches && e.which !== 1) return this.mousemove(this.mousePositionFromEvent(e)) }) addEventListener(this.elementContainer, "touchend touchcancel mouseup", (e) => { this.mouseup() }); this.pixi.view.style.width = "100%"; this.pixi.view.style.height = "100%"; this.pixi.view.style.border = "5px solid #EEE"; this.elementContainer.appendChild(this.pixi.view); this.bodies = []; this.viewport = { scale: 35, center: [0, 0], width: 0, height: 0 }; // resize the canvas to fill browser window dynamically window.addEventListener('resize', this.events.resize.bind(this), false); this.adjustBounds(); this.drawingGraphic = new PIXI.Graphics() this.container.addChild(this.drawingGraphic) }; renderer.prototype.events = {}; renderer.prototype.events.resize = function () { this.adjustBounds(); this.pixi.render(this.stage); }; renderer.prototype.mousePositionFromEvent = function (e) { var rect = this.pixi.view.getBoundingClientRect() if (e.touches) { var x = e.touches[0].clientX - rect.left var y = e.touches[0].clientY - rect.top } else if (e.clientX && e.clientY) { var x = e.clientX - rect.left var y = e.clientY - rect.top } else { return null; } return PIXI.interaction.InteractionData.prototype.getLocalPosition(this.stage, null, new PIXI.Point(x, y)) }; renderer.prototype.adjustBounds = function () { var outerW = this.elementContainer.offsetWidth var outerH = outerW / 3 * 2 this.viewport.width = outerW this.viewport.height = outerH this.viewport.scale = outerW / 1200 * 35 this.offset = this.pixi.view.getBoundingClientRect() this.offset = { top: this.offset.top + document.body.scrollTop, left: this.offset.left + document.body.scrollLeft } this.pixi.resize(this.viewport.width, this.viewport.height) }; renderer.prototype.render = function () { for (var i = 0; i < this.bodies.length; i++) { this.update_body(this.bodies[i]); } this.update_stage(this.stage); this.pixi.render(this.stage); }; renderer.prototype.update_stage = function (stage) { stage.scale.x = this.viewport.scale; stage.scale.y = this.viewport.scale; stage.position.x = this.viewport.center[0] + this.viewport.width / 2; stage.position.y = this.viewport.center[1] + this.viewport.height / 2; }; renderer.prototype.update_body = function (body) { body.gl_sprite.position.x = body.interpolatedPosition[0] body.gl_sprite.position.y = body.interpolatedPosition[1] body.gl_sprite.rotation = body.interpolatedAngle }; renderer.prototype.create_sprite = function (body) { var sprite = new PIXI.Graphics(); this.draw_sprite(body, sprite); this.stage.addChild(sprite); if (body.gl_create) { body.gl_create(sprite, this); } return sprite; }; renderer.prototype.draw_path = function (sprite, path, opt) { if (path.length < 2) return; if (typeof opt.line !== 'undefined') { sprite.lineStyle(opt.line.width, opt.line.color, opt.line.alpha); } if (typeof opt.fill !== 'undefined') { sprite.beginFill(opt.fill.color, opt.fill.alpha); } sprite.moveTo(path[0][0], path[0][1]); for (var i = 1; i < path.length; i++) { var p = path[i]; sprite.lineTo(p[0], p[1]); } if (opt.fill !== 'undefined') { sprite.endFill(); } } renderer.prototype.draw_rect = function (sprite, bounds, angle, opt) { var w = bounds.w, h = bounds.h, x = bounds.x, y = bounds.y; var path = [ [w / 2, h / 2], [-w / 2, h / 2], [-w / 2, -h / 2], [w / 2, -h / 2], [w / 2, h / 2] ]; // Rotate and add position for (var i = 0; i < path.length; i++) { var v = path[i]; p2.vec2.rotate(v, v, angle); p2.vec2.add(v, v, [x, y]); } this.draw_path(sprite, path, opt); } renderer.prototype.draw_sprite = function (body, sprite) { sprite.clear(); var color = body.color var opt = { line: { color: color, alpha: 1, width: 0.01 }, fill: { color: color, alpha: 1.0 } } if (body.concavePath) { var path = [] for (var j = 0; j !== body.concavePath.length; j++) { var v = body.concavePath[j] path.push([v[0], v[1]]) } this.draw_path(sprite, path, opt) return } for (var i = 0; i < body.shapes.length; i++) { var shape = body.shapes[i], offset = shape.position, angle = shape.angle; var shape_opt = opt if (shape.color) { shape_opt = { line: { color: shape.color, alpha: 1, width: 0.01 }, fill: { color: shape.color, alpha: 1.0 } } } if (shape instanceof p2.Box) { this.draw_rect(sprite, { w: shape.width, h: shape.height, x: offset[0], y: offset[1] }, angle, shape_opt); } else if (shape instanceof p2.Convex) { var path = [], v = p2.vec2.create(); for (var j = 0; j < shape.vertices.length; j++) { p2.vec2.rotate(v, shape.vertices[j], angle); path.push([v[0] + offset[0], v[1] + offset[1]]); } this.draw_path(sprite, path, shape_opt); } } }; renderer.prototype.add_body = function (body) { if (body instanceof p2.Body && body.shapes.length && !body.hidden) { body.gl_sprite = this.create_sprite(body); this.update_body(body); this.bodies.push(body); } }; renderer.prototype.remove_body = function (body) { if (body.gl_sprite) { this.stage.removeChild(body.gl_sprite) for (var i = this.bodies.length; --i;) { if (this.bodies[i] === body) { this.bodies.splice(i, 1); } } } }; renderer.prototype.zoom = function (factor) { this.viewport.scale *= factor; }; var sampling = 0.4 renderer.prototype.mousedown = function (pos) { this.drawPoints = [[pos.x, pos.y]] }; renderer.prototype.mousemove = function (pos) { pos = [pos.x, pos.y] var sqdist = p2.vec2.distance(pos, this.drawPoints[this.drawPoints.length - 1]); if (sqdist > sampling * sampling) { this.drawPoints.push(pos) this.drawingGraphic.clear() this.draw_path(this.drawingGraphic, this.drawPoints, { line: { width: 0.02, color: 0xFF0000, alpha: 0.9 } }) } } renderer.prototype.mouseup = function () { if (this.drawPoints.length > 2) { this.world.addBodyFromPoints(this.drawPoints) } this.drawPoints = [] this.drawingGraphic.clear() }; function addEventListener(el, names, listener) { var events = names.split(' '); for (let i = 0; i < events.length; i++) { el.addEventListener(events[i], listener, false); } } module.exports = renderer; /***/ }), /***/ "./src/sensors.js": /*!************************!*\ !*** ./src/sensors.js ***! \************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var color = __webpack_require__(/*! ./color.js */ "./src/color.js"); var car = __webpack_require__(/*! ./car.js */ "./src/car.js") // var p2 = require('p2') class Sensor {} class DistanceSensor extends Sensor { constructor(car, opt) { super() this.type = "distance" this.car = car this.angle = opt.angle / 180 * Math.PI this.length = opt.length || 10 this.absolute = opt.absolute || false this.direction = [ Math.sin(this.angle), Math.cos(this.angle) ] this.start = opt.start || [ 0, 0.1 ] this.localNormal = p2.vec2.create() this.globalRay = p2.vec2.create() this.ray = new p2.Ray({ mode: p2.Ray.CLOSEST, direction: this.direction, length: this.length, checkCollisionResponse: false, skipBackfaces: true }) this.setLength(this.length); this.castedResult = new p2.RaycastResult() this.hit = false this.distance = 0.0 this.entity = 'none' this.data = new Float64Array(DistanceSensor.dimensions) } setLength(v) { this.length = v this.ray.length = this.length this.end = [ this.start[0] + this.direction[0] * this.length, this.start[1] + this.direction[1] * this.length ] this.rayVector = [ this.end[0] - this.start[0], this.end[1] - this.start[1] ] } update() { var vehicleBody = this.car.chassisBody; if (vehicleBody.world === null) return; vehicleBody.toWorldFrame(this.ray.from, this.start); vehicleBody.toWorldFrame(this.ray.to, this.end); this.ray.update(); this.castedResult.reset(); vehicleBody.world.raycast(this.castedResult, this.ray); if (this.hit = this.castedResult.hasHit()) { this.distance = this.castedResult.fraction; this.entity = this.castedResult.body.entity || 'none'; vehicleBody.vectorToLocalFrame(this.localNormal, this.castedResult.normal); vehicleBody.vectorToWorldFrame(this.globalRay, this.rayVector); this.reflectionAngle = Math.atan2(this.castedResult.normal[1], this.castedResult.normal[0]) - Math.atan2(this.globalRay[1], this.globalRay[0]); // = Math.atan2( this.localNormal[1], this.localNormal[0] ) - Math.atan2( this.rayVector[1], this.rayVector[0] ) if (this.reflectionAngle > Math.PI / 2) this.reflectionAngle = Math.PI - this.reflectionAngle; if (this.reflectionAngle < -Math.PI / 2) this.reflectionAngle = Math.PI + this.reflectionAngle; } else { this.distance = 1.0; this.entity = 'none'; this.localNormal[0] = 0; this.localNormal[1] = 0; this.reflectionAngle = 0; } if (this.hit) { this.data[0] = 1.0 - this.distance; this.data[1] = this.reflectionAngle; this.data[2] = this.entity === 'car' ? 1.0 : 0.0; // is car? } else { this.data.fill(0.0); } } draw(g) { var dist = this.hit ? this.distance : 1.0 var c = color.rgbToHex(Math.floor((1-dist) * 255), Math.floor((dist) * 128), 128) g.lineStyle(this.highlighted ? 0.04 : 0.01, c, 0.5) g.moveTo(this.start[0], this.start[1]); g.lineTo(this.start[0] + this.direction[0] * this.length * dist, this.start[1] + this.direction[1] * this.length * dist); } } class SpeedSensor extends Sensor { constructor(car, opt) { super() this.type = "speed" this.car = car this.local = p2.vec2.create() this.data = new Float64Array(SpeedSensor.dimensions) } update() { this.car.chassisBody.vectorToLocalFrame(this.local, this.car.chassisBody.velocity) this.data[0] = this.velocity = p2.vec2.len(this.car.chassisBody.velocity) * (this.local[1] > 0 ? 1.0 : -1.0) this.data[1] = this.local[1] this.data[2] = this.local[0] } draw(g) { if (g.__label === undefined) { g.__label = new PIXI.Text('0 km/h', { font: '80px Helvetica Neue' }); g.__label.scale.x = (g.__label.scale.y = 3e-3); g.addChild(g.__label); } g.__label.text = Math.floor(this.velocity * 3.6) + ' km/h'; g.__label.rotation = -this.car.chassisBody.interpolatedAngle; } } class PositionSensor extends Sensor { constructor(car, opt) { super() this.type = "position" this.car = car this.data = new Float64Array(PositionSensor.dimensions) } update() { this.data[0] = this.car.chassisBody.position[0] this.data[1] = this.car.chassisBody.position[1] this.data[2] = Math.sin(this.car.chassisBody.angle) this.data[3] = Math.cos(this.car.chassisBody.angle) } draw(g) { } } class ContactSensor extends Sensor { constructor(car, opt) { super() this.type = "contact" this.car = car this.data = new Float64Array(ContactSensor.dimensions) } update() { this.data[0] = this.car.hasContact('obstacle') ? 1 : 0 this.data[1] = this.car.hasContact('car') ? 1 : 0 } draw(g) { } } class TargetSensor extends Sensor { constructor(car, opt) { super() this.type = "target" this.car = car this.car.target = new Float64Array(2) this.data = new Float64Array(TargetSensor.dimensions) } update() { this.data[0] = this.car.target[0] this.data[1] = this.car.target[1] var dx = this.car.target[0] - this.car.chassisBody.position[0] var dy = this.car.target[1] - this.car.chassisBody.position[1] this.data[2] = Math.sqrt(dx * dx + dy * dy) } draw(g) { if (g.__subgraphic === undefined) { g.__subgraphic = new PIXI.Graphics(); g.parent.parent.addChild(g.__subgraphic); } g.__subgraphic.beginFill(this.car.chassisBody.color); g.__subgraphic.drawCircle(0, 0, 0.3); // var p = p2.vec2.create() // this.car.chassisBody.toLocalFrame(p, this.car.target); g.__subgraphic.x = this.car.target[0] g.__subgraphic.y = this.car.target[1] } } const sensorTypes = { "distance": DistanceSensor, "speed": SpeedSensor, "position": PositionSensor, "target": TargetSensor, "contact": ContactSensor } DistanceSensor.dimensions = 3 SpeedSensor.dimensions = 3 PositionSensor.dimensions = 4 ContactSensor.dimensions = 2 TargetSensor.dimensions = 3 class SensorArray { constructor(car, blueprint) { this.sensors = [] this.dimensions = blueprint.dimensions this.data = new Float64Array(blueprint.dimensions) for (var i = 0; i < blueprint.list.length; i++) { var opt = blueprint.list[i] this.sensors.push(new sensorTypes[opt.type](car, opt)) } } update() { for (var i = 0, k = 0; i < this.sensors.length; k += this.sensors[i].data.length, i++) { this.sensors[i].update() this.data.set(this.sensors[i].data, k) } } draw(g) { for (var i = 0; i < this.sensors.length; i++) { this.sensors[i].draw(g) } } getByType(type) { for (var i = 0, found = []; i < this.sensors.length; i++) { if (this.sensors[i].type === type) { found.push(this.sensors[i]) } } return found } } class SensorBlueprint { constructor(list) { this.list = list this.dimensions = 0 for (var i = 0; i < this.list.length; i++) { var opt = this.list[i] this.dimensions += sensorTypes[opt.type].dimensions } } build(car) { return new SensorArray(car, this) } static compile(list) { return new SensorBlueprint(list) } } module.exports = { SensorArray, SensorBlueprint }; /***/ }), /***/ "./src/tiny-color.js": /*!***************************!*\ !*** ./src/tiny-color.js ***! \***************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;// TinyColor v1.4.1 // https://github.com/bgrins/TinyColor // Brian Grinstead, MIT License (function(Math) { var trimLeft = /^\s+/, trimRight = /\s+$/, tinyCounter = 0, mathRound = Math.round, mathMin = Math.min, mathMax = Math.max, mathRandom = Math.random; function tinycolor (color, opts) { color = (color) ? color : ''; opts = opts || { }; // If input is already a tinycolor, return itself if (color instanceof tinycolor) { return color; } // If we are called as a function, call using new instead if (!(this instanceof tinycolor)) { return new tinycolor(color, opts); } var rgb = inputToRGB(color); this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = mathRound(100*this._a) / 100, this._format = opts.format || rgb.format; this._gradientType = opts.gradientType; // Don't let the range of [0,255] come back in [0,1]. // Potentially lose a little bit of precision here, but will fix issues where // .5 gets interpreted as half of the total, instead of half of 1 // If it was supposed to be 128, this was already taken care of by `inputToRgb` if (this._r < 1) { this._r = mathRound(this._r); } if (this._g < 1) { this._g = mathRound(this._g); } if (this._b < 1) { this._b = mathRound(this._b); } this._ok = rgb.ok; this._tc_id = tinyCounter++; } tinycolor.prototype = { isDark: function() { return this.getBrightness() < 128; }, isLight: function() { return !this.isDark(); }, isValid: function() { return this._ok; }, getOriginalInput: function() { return this._originalInput; }, getFormat: function() { return this._format; }, getAlpha: function() { return this._a; }, getBrightness: function() { //http://www.w3.org/TR/AERT#color-contrast var rgb = this.toRgb(); return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; }, getLuminance: function() { //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef var rgb = this.toRgb(); var RsRGB, GsRGB, BsRGB, R, G, B; RsRGB = rgb.r/255; GsRGB = rgb.g/255; BsRGB = rgb.b/255; if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);} if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);} if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);} return (0.2126 * R) + (0.7152 * G) + (0.0722 * B); }, setAlpha: function(value) { this._a = boundAlpha(value); this._roundA = mathRound(100*this._a) / 100; return this; }, toHsv: function() { var hsv = rgbToHsv(this._r, this._g, this._b); return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a }; }, toHsvString: function() { var hsv = rgbToHsv(this._r, this._g, this._b); var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100); return (this._a == 1) ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")"; }, toHsl: function() { var hsl = rgbToHsl(this._r, this._g, this._b); return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a }; }, toHslString: function() { var hsl = rgbToHsl(this._r, this._g, this._b); var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100); return (this._a == 1) ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")"; }, toHex: function(allow3Char) { return rgbToHex(this._r, this._g, this._b, allow3Char); }, toHexString: function(allow3Char) { return '#' + this.toHex(allow3Char); }, toHex8: function(allow4Char) { return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char); }, toHex8String: function(allow4Char) { return '#' + this.toHex8(allow4Char); }, toRgb: function() { return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a }; }, toRgbString: function() { return (this._a == 1) ? "rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" : "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")"; }, toPercentageRgb: function() { return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a }; }, toPercentageRgbString: function() { return (this._a == 1) ? "rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" : "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; }, toName: function() { if (this._a === 0) { return "transparent"; } if (this._a < 1) { return false; } return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; }, toFilter: function(secondColor) { var hex8String = '#' + rgbaToArgbHex(this._r, this._g, this._b, this._a); var secondHex8String = hex8String; var gradientType = this._gradientType ? "GradientType = 1, " : ""; if (secondColor) { var s = tinycolor(secondColor); secondHex8String = '#' + rgbaToArgbHex(s._r, s._g, s._b, s._a); } return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")"; }, toString: function(format) { var formatSet = !!format; format = format || this._format; var formattedString = false; var hasAlpha = this._a < 1 && this._a >= 0; var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name"); if (needsAlphaFormat) { // Special case for "transparent", all other non-alpha formats // will return rgba when there is transparency. if (format === "name" && this._a === 0) { return this.toName(); } return this.toRgbString(); } if (format === "rgb") { formattedString = this.toRgbString(); } if (format === "prgb") { formattedString = this.toPercentageRgbString(); } if (format === "hex" || format === "hex6") { formattedString = this.toHexString(); } if (format === "hex3") { formattedString = this.toHexString(true); } if (format === "hex4") { formattedString = this.toHex8String(true); } if (format === "hex8") { formattedString = this.toHex8String(); } if (format === "name") { formattedString = this.toName(); } if (format === "hsl") { formattedString = this.toHslString(); } if (format === "hsv") { formattedString = this.toHsvString(); } return formattedString || this.toHexString(); }, clone: function() { return tinycolor(this.toString()); }, _applyModification: function(fn, args) { var color = fn.apply(null, [this].concat([].slice.call(args))); this._r = color._r; this._g = color._g; this._b = color._b; this.setAlpha(color._a); return this; }, lighten: function() { return this._applyModification(lighten, arguments); }, brighten: function() { return this._applyModification(brighten, arguments); }, darken: function() { return this._applyModification(darken, arguments); }, desaturate: function() { return this._applyModification(desaturate, arguments); }, saturate: function() { return this._applyModification(saturate, arguments); }, greyscale: function() { return this._applyModification(greyscale, arguments); }, spin: function() { return this._applyModification(spin, arguments); }, _applyCombination: function(fn, args) { return fn.apply(null, [this].concat([].slice.call(args))); }, analogous: function() { return this._applyCombination(analogous, arguments); }, complement: function() { return this._applyCombination(complement, arguments); }, monochromatic: function() { return this._applyCombination(monochromatic, arguments); }, splitcomplement: function() { return this._applyCombination(splitcomplement, arguments); }, triad: function() { return this._applyCombination(triad, arguments); }, tetrad: function() { return this._applyCombination(tetrad, arguments); } }; // If input is an object, force 1 into "1.0" to handle ratios properly // String input requires "1.0" as input, so 1 will be treated as 1 tinycolor.fromRatio = function(color, opts) { if (typeof color == "object") { var newColor = {}; for (var i in color) { if (color.hasOwnProperty(i)) { if (i === "a") { newColor[i] = color[i]; } else { newColor[i] = convertToPercentage(color[i]); } } } color = newColor; } return tinycolor(color, opts); }; // Given a string or object, convert that input to RGB // Possible string inputs: // // "red" // "#f00" or "f00" // "#ff0000" or "ff0000" // "#ff000000" or "ff000000" // "rgb 255 0 0" or "rgb (255, 0, 0)" // "rgb 1.0 0 0" or "rgb (1, 0, 0)" // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" // function inputToRGB(color) { var rgb = { r: 0, g: 0, b: 0 }; var a = 1; var s = null; var v = null; var l = null; var ok = false; var format = false; if (typeof color == "string") { color = stringInputToObject(color); } if (typeof color == "object") { if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) { rgb = rgbToRgb(color.r, color.g, color.b); ok = true; format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) { s = convertToPercentage(color.s); v = convertToPercentage(color.v); rgb = hsvToRgb(color.h, s, v); ok = true; format = "hsv"; } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) { s = convertToPercentage(color.s); l = convertToPercentage(color.l); rgb = hslToRgb(color.h, s, l); ok = true; format = "hsl"; } if (color.hasOwnProperty("a")) { a = color.a; } } a = boundAlpha(a); return { ok: ok, format: color.format || format, r: mathMin(255, mathMax(rgb.r, 0)), g: mathMin(255, mathMax(rgb.g, 0)), b: mathMin(255, mathMax(rgb.b, 0)), a: a }; } // Conversion Functions // -------------------- // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript> // `rgbToRgb` // Handle bounds / percentage checking to conform to CSS color spec // <http://www.w3.org/TR/css3-color/> // *Assumes:* r, g, b in [0, 255] or [0, 1] // *Returns:* { r, g, b } in [0, 255] function rgbToRgb(r, g, b){ return { r: bound01(r, 255) * 255, g: bound01(g, 255) * 255, b: bound01(b, 255) * 255 }; } // `rgbToHsl` // Converts an RGB color value to HSL. // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] // *Returns:* { h, s, l } in [0,1] function rgbToHsl(r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = mathMax(r, g, b), min = mathMin(r, g, b); var h, s, l = (max + min) / 2; if(max == min) { h = s = 0; // achromatic } else { var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch(max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, l: l }; } // `hslToRgb` // Converts an HSL color value to RGB. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] // *Returns:* { r, g, b } in the set [0, 255] function hslToRgb(h, s, l) { var r, g, b; h = bound01(h, 360); s = bound01(s, 100); l = bound01(l, 100); function hue2rgb(p, q, t) { if(t < 0) t += 1; if(t > 1) t -= 1; if(t < 1/6) return p + (q - p) * 6 * t; if(t < 1/2) return q; if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; return p; } if(s === 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1/3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1/3); } return { r: r * 255, g: g * 255, b: b * 255 }; } // `rgbToHsv` // Converts an RGB color value to HSV // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] // *Returns:* { h, s, v } in [0,1] function rgbToHsv(r, g, b) { r = bound01(r, 255); g = bound01(g, 255); b = bound01(b, 255); var max = mathMax(r, g, b), min = mathMin(r, g, b); var h, s, v = max; var d = max - min; s = max === 0 ? 0 : d / max; if(max == min) { h = 0; // achromatic } else { switch(max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h, s: s, v: v }; } // `hsvToRgb` // Converts an HSV color value to RGB. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] // *Returns:* { r, g, b } in the set [0, 255] function hsvToRgb(h, s, v) { h = bound01(h, 360) * 6; s = bound01(s, 100); v = bound01(v, 100); var i = Math.floor(h), f = h - i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s), mod = i % 6, r = [v, q, p, p, t, v][mod], g = [t, v, v, q, p, p][mod], b = [p, p, t, v, v, q][mod]; return { r: r * 255, g: g * 255, b: b * 255 }; } // `rgbToHex` // Converts an RGB color to hex // Assumes r, g, and b are contained in the set [0, 255] // Returns a 3 or 6 character hex function rgbToHex(r, g, b, allow3Char) { var hex = [ pad2(mathRound(r).toString(16)), pad2(mathRound(g).toString(16)), pad2(mathRound(b).toString(16)) ]; // Return a 3 character hex if possible if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); } return hex.join(""); } // `rgbaToHex` // Converts an RGBA color plus alpha transparency to hex // Assumes r, g, b are contained in the set [0, 255] and // a in [0, 1]. Returns a 4 or 8 character rgba hex function rgbaToHex(r, g, b, a, allow4Char) { var hex = [ pad2(mathRound(r).toString(16)), pad2(mathRound(g).toString(16)), pad2(mathRound(b).toString(16)), pad2(convertDecimalToHex(a)) ]; // Return a 4 character hex if possible if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) { return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0); } return hex.join(""); } // `rgbaToArgbHex` // Converts an RGBA color to an ARGB Hex8 string // Rarely used, but required for "toFilter()" function rgbaToArgbHex(r, g, b, a) { var hex = [ pad2(convertDecimalToHex(a)), pad2(mathRound(r).toString(16)), pad2(mathRound(g).toString(16)), pad2(mathRound(b).toString(16)) ]; return hex.join(""); } // `equals` // Can be called with any tinycolor input tinycolor.equals = function (color1, color2) { if (!color1 || !color2) { return false; } return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); }; tinycolor.random = function() { return tinycolor.fromRatio({ r: mathRandom(), g: mathRandom(), b: mathRandom() }); }; // Modification Functions // ---------------------- // Thanks to less.js for some of the basics here // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js> function desaturate(color, amount) { amount = (amount === 0) ? 0 : (amount || 10); var hsl = tinycolor(color).toHsl(); hsl.s -= amount / 100; hsl.s = clamp01(hsl.s); return tinycolor(hsl); } function saturate(color, amount) { amount = (amount === 0) ? 0 : (amount || 10); var hsl = tinycolor(color).toHsl(); hsl.s += amount / 100; hsl.s = clamp01(hsl.s); return tinycolor(hsl); } function greyscale(color) { return tinycolor(color).desaturate(100); } function lighten (color, amount) { amount = (amount === 0) ? 0 : (amount || 10); var hsl = tinycolor(color).toHsl(); hsl.l += amount / 100; hsl.l = clamp01(hsl.l); return tinycolor(hsl); } function brighten(color, amount) { amount = (amount === 0) ? 0 : (amount || 10); var rgb = tinycolor(color).toRgb(); rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100)))); rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100)))); rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100)))); return tinycolor(rgb); } function darken (color, amount) { amount = (amount === 0) ? 0 : (amount || 10); var hsl = tinycolor(color).toHsl(); hsl.l -= amount / 100; hsl.l = clamp01(hsl.l); return tinycolor(hsl); } // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. // Values outside of this range will be wrapped into this range. function spin(color, amount) { var hsl = tinycolor(color).toHsl(); var hue = (hsl.h + amount) % 360; hsl.h = hue < 0 ? 360 + hue : hue; return tinycolor(hsl); } // Combination Functions // --------------------- // Thanks to jQuery xColor for some of the ideas behind these // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js> function complement(color) { var hsl = tinycolor(color).toHsl(); hsl.h = (hsl.h + 180) % 360; return tinycolor(hsl); } function triad(color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h; return [ tinycolor(color), tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l }) ]; } function tetrad(color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h; return [ tinycolor(color), tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }), tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l }) ]; } function splitcomplement(color) { var hsl = tinycolor(color).toHsl(); var h = hsl.h; return [ tinycolor(color), tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}), tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l}) ]; } function analogous(color, results, slices) { results = results || 6; slices = slices || 30; var hsl = tinycolor(color).toHsl(); var part = 360 / slices; var ret = [tinycolor(color)]; for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) { hsl.h = (hsl.h + part) % 360; ret.push(tinycolor(hsl)); } return ret; } function monochromatic(color, results) { results = results || 6; var hsv = tinycolor(color).toHsv(); var h = hsv.h, s = hsv.s, v = hsv.v; var ret = []; var modification = 1 / results; while (results--) { ret.push(tinycolor({ h: h, s: s, v: v})); v = (v + modification) % 1; } return ret; } // Utility Functions // --------------------- tinycolor.mix = function(color1, color2, amount) { amount = (amount === 0) ? 0 : (amount || 50); var rgb1 = tinycolor(color1).toRgb(); var rgb2 = tinycolor(color2).toRgb(); var p = amount / 100; var rgba = { r: ((rgb2.r - rgb1.r) * p) + rgb1.r, g: ((rgb2.g - rgb1.g) * p) + rgb1.g, b: ((rgb2.b - rgb1.b) * p) + rgb1.b, a: ((rgb2.a - rgb1.a) * p) + rgb1.a }; return tinycolor(rgba); }; // Readability Functions // --------------------- // <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2) // `contrast` // Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2) tinycolor.readability = function(color1, color2) { var c1 = tinycolor(color1); var c2 = tinycolor(color2); return (Math.max(c1.getLuminance(),c2.getLuminance())+0.05) / (Math.min(c1.getLuminance(),c2.getLuminance())+0.05); }; // `isReadable` // Ensure that foreground and background color combinations meet WCAG2 guidelines. // The third argument is an optional Object. // the 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA'; // the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'. // If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}. // *Example* // tinycolor.isReadable("#000", "#111") => false // tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false tinycolor.isReadable = function(color1, color2, wcag2) { var readability = tinycolor.readability(color1, color2); var wcag2Parms, out; out = false; wcag2Parms = validateWCAG2Parms(wcag2); switch (wcag2Parms.level + wcag2Parms.size) { case "AAsmall": case "AAAlarge": out = readability >= 4.5; break; case "AAlarge": out = readability >= 3; break; case "AAAsmall": out = readability >= 7; break; } return out; }; // `mostReadable` // Given a base color and a list of possible foreground or background // colors for that base, returns the most readable color. // Optionally returns Black or White if the most readable color is unreadable. // *Example* // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" tinycolor.mostReadable = function(baseColor, colorList, args) { var bestColor = null; var bestScore = 0; var readability; var includeFallbackColors, level, size ; args = args || {}; includeFallbackColors = args.includeFallbackColors ; level = args.level; size = args.size; for (var i= 0; i < colorList.length ; i++) { readability = tinycolor.readability(baseColor, colorList[i]); if (readability > bestScore) { bestScore = readability; bestColor = tinycolor(colorList[i]); } } if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) { return bestColor; } else { args.includeFallbackColors=false; return tinycolor.mostReadable(baseColor,["#fff", "#000"],args); } }; // Big List of Colors // ------------------ // <http://www.w3.org/TR/css3-color/#svg-color> var names = tinycolor.names = { aliceblue: "f0f8ff", antiquewhite: "faebd7", aqua: "0ff", aquamarine: "7fffd4", azure: "f0ffff", beige: "f5f5dc", bisque: "ffe4c4", black: "000", blanchedalmond: "ffebcd", blue: "00f", blueviolet: "8a2be2", brown: "a52a2a", burlywood: "deb887", burntsienna: "ea7e5d", cadetblue: "5f9ea0", chartreuse: "7fff00", chocolate: "d2691e", coral: "ff7f50", cornflowerblue: "6495ed", cornsilk: "fff8dc", crimson: "dc143c", cyan: "0ff", darkblue: "00008b", darkcyan: "008b8b", darkgoldenrod: "b8860b", darkgray: "a9a9a9", darkgreen: "006400", darkgrey: "a9a9a9", darkkhaki: "bdb76b", darkmagenta: "8b008b", darkolivegreen: "556b2f", darkorange: "ff8c00", darkorchid: "9932cc", darkred: "8b0000", darksalmon: "e9967a", darkseagreen: "8fbc8f", darkslateblue: "483d8b", darkslategray: "2f4f4f", darkslategrey: "2f4f4f", darkturquoise: "00ced1", darkviolet: "9400d3", deeppink: "ff1493", deepskyblue: "00bfff", dimgray: "696969", dimgrey: "696969", dodgerblue: "1e90ff", firebrick: "b22222", floralwhite: "fffaf0", forestgreen: "228b22", fuchsia: "f0f", gainsboro: "dcdcdc", ghostwhite: "f8f8ff", gold: "ffd700", goldenrod: "daa520", gray: "808080", green: "008000", greenyellow: "adff2f", grey: "808080", honeydew: "f0fff0", hotpink: "ff69b4", indianred: "cd5c5c", indigo: "4b0082", ivory: "fffff0", khaki: "f0e68c", lavender: "e6e6fa", lavenderblush: "fff0f5", lawngreen: "7cfc00", lemonchiffon: "fffacd", lightblue: "add8e6", lightcoral: "f08080", lightcyan: "e0ffff", lightgoldenrodyellow: "fafad2", lightgray: "d3d3d3", lightgreen: "90ee90", lightgrey: "d3d3d3", lightpink: "ffb6c1", lightsalmon: "ffa07a", lightseagreen: "20b2aa", lightskyblue: "87cefa", lightslategray: "789", lightslategrey: "789", lightsteelblue: "b0c4de", lightyellow: "ffffe0", lime: "0f0", limegreen: "32cd32", linen: "faf0e6", magenta: "f0f", maroon: "800000", mediumaquamarine: "66cdaa", mediumblue: "0000cd", mediumorchid: "ba55d3", mediumpurple: "9370db", mediumseagreen: "3cb371", mediumslateblue: "7b68ee", mediumspringgreen: "00fa9a", mediumturquoise: "48d1cc", mediumvioletred: "c71585", midnightblue: "191970", mintcream: "f5fffa", mistyrose: "ffe4e1", moccasin: "ffe4b5", navajowhite: "ffdead", navy: "000080", oldlace: "fdf5e6", olive: "808000", olivedrab: "6b8e23", orange: "ffa500", orangered: "ff4500", orchid: "da70d6", palegoldenrod: "eee8aa", palegreen: "98fb98", paleturquoise: "afeeee", palevioletred: "db7093", papayawhip: "ffefd5", peachpuff: "ffdab9", peru: "cd853f", pink: "ffc0cb", plum: "dda0dd", powderblue: "b0e0e6", purple: "800080", rebeccapurple: "663399", red: "f00", rosybrown: "bc8f8f", royalblue: "4169e1", saddlebrown: "8b4513", salmon: "fa8072", sandybrown: "f4a460", seagreen: "2e8b57", seashell: "fff5ee", sienna: "a0522d", silver: "c0c0c0", skyblue: "87ceeb", slateblue: "6a5acd", slategray: "708090", slategrey: "708090", snow: "fffafa", springgreen: "00ff7f", steelblue: "4682b4", tan: "d2b48c", teal: "008080", thistle: "d8bfd8", tomato: "ff6347", turquoise: "40e0d0", violet: "ee82ee", wheat: "f5deb3", white: "fff", whitesmoke: "f5f5f5", yellow: "ff0", yellowgreen: "9acd32" }; // Make it easy to access colors via `hexNames[hex]` var hexNames = tinycolor.hexNames = flip(names); // Utilities // --------- // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` function flip(o) { var flipped = { }; for (var i in o) { if (o.hasOwnProperty(i)) { flipped[o[i]] = i; } } return flipped; } // Return a valid alpha value [0,1] with all invalid values being set to 1 function boundAlpha(a) { a = parseFloat(a); if (isNaN(a) || a < 0 || a > 1) { a = 1; } return a; } // Take input from [0, n] and return it as [0, 1] function bound01(n, max) { if (isOnePointZero(n)) { n = "100%"; } var processPercent = isPercentage(n); n = mathMin(max, mathMax(0, parseFloat(n))); // Automatically convert percentage into number if (processPercent) { n = parseInt(n * max, 10) / 100; } // Handle floating point rounding errors if ((Math.abs(n - max) < 0.000001)) { return 1; } // Convert into [0, 1] range if it isn't already return (n % max) / parseFloat(max); } // Force a number between 0 and 1 function clamp01(val) { return mathMin(1, mathMax(0, val)); } // Parse a base-16 hex value into a base-10 integer function parseIntFromHex(val) { return parseInt(val, 16); } // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0> function isOnePointZero(n) { return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1; } // Check to see if string passed in is a percentage function isPercentage(n) { return typeof n === "string" && n.indexOf('%') != -1; } // Force a hex value to have 2 characters function pad2(c) { return c.length == 1 ? '0' + c : '' + c; } // Replace a decimal with it's percentage value function convertToPercentage(n) { if (n <= 1) { n = (n * 100) + "%"; } return n; } // Converts a decimal to a hex value function convertDecimalToHex(d) { return Math.round(parseFloat(d) * 255).toString(16); } // Converts a hex value to a decimal function convertHexToDecimal(h) { return (parseIntFromHex(h) / 255); } var matchers = (function() { // <http://www.w3.org/TR/css3-values/#integers> var CSS_INTEGER = "[-\\+]?\\d+%?"; // <http://www.w3.org/TR/css3-values/#number-value> var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; // Actual matching. // Parentheses and commas are optional, but not required. // Whitespace can take the place of commas or opening paren var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; return { CSS_UNIT: new RegExp(CSS_UNIT), rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ }; })(); // `isValidCSSUnit` // Take in a single string / number and check to see if it looks like a CSS unit // (see `matchers` above for definition). function isValidCSSUnit(color) { return !!matchers.CSS_UNIT.exec(color); } // `stringInputToObject` // Permissive string parsing. Take in a number of formats, and output an object // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` function stringInputToObject(color) { color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase(); var named = false; if (names[color]) { color = names[color]; named = true; } else if (color == 'transparent') { return { r: 0, g: 0, b: 0, a: 0, format: "name" }; } // Try to match string input using regular expressions. // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] // Just return an object and let the conversion functions handle that. // This way the result will be the same whether the tinycolor is initialized with string or object. var match; if ((match = matchers.rgb.exec(color))) { return { r: match[1], g: match[2], b: match[3] }; } if ((match = matchers.rgba.exec(color))) { return { r: match[1], g: match[2], b: match[3], a: match[4] }; } if ((match = matchers.hsl.exec(color))) { return { h: match[1], s: match[2], l: match[3] }; } if ((match = matchers.hsla.exec(color))) { return { h: match[1], s: match[2], l: match[3], a: match[4] }; } if ((match = matchers.hsv.exec(color))) { return { h: match[1], s: match[2], v: match[3] }; } if ((match = matchers.hsva.exec(color))) { return { h: match[1], s: match[2], v: match[3], a: match[4] }; } if ((match = matchers.hex8.exec(color))) { return { r: parseIntFromHex(match[1]), g: parseIntFromHex(match[2]), b: parseIntFromHex(match[3]), a: convertHexToDecimal(match[4]), format: named ? "name" : "hex8" }; } if ((match = matchers.hex6.exec(color))) { return { r: parseIntFromHex(match[1]), g: parseIntFromHex(match[2]), b: parseIntFromHex(match[3]), format: named ? "name" : "hex" }; } if ((match = matchers.hex4.exec(color))) { return { r: parseIntFromHex(match[1] + '' + match[1]), g: parseIntFromHex(match[2] + '' + match[2]), b: parseIntFromHex(match[3] + '' + match[3]), a: convertHexToDecimal(match[4] + '' + match[4]), format: named ? "name" : "hex8" }; } if ((match = matchers.hex3.exec(color))) { return { r: parseIntFromHex(match[1] + '' + match[1]), g: parseIntFromHex(match[2] + '' + match[2]), b: parseIntFromHex(match[3] + '' + match[3]), format: named ? "name" : "hex" }; } return false; } function validateWCAG2Parms(parms) { // return valid WCAG2 parms for isReadable. // If input parms are invalid, return {"level":"AA", "size":"small"} var level, size; parms = parms || {"level":"AA", "size":"small"}; level = (parms.level || "AA").toUpperCase(); size = (parms.size || "small").toLowerCase(); if (level !== "AA" && level !== "AAA") { level = "AA"; } if (size !== "small" && size !== "large") { size = "small"; } return {"level":level, "size":size}; } // Node: Export function if ( true && module.exports) { module.exports = tinycolor; } // AMD/requirejs: Define the module else if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {return tinycolor;}).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } // Browser: Expose to window else {} })(Math); /***/ }), /***/ "./src/world.js": /*!**********************!*\ !*** ./src/world.js ***! \**********************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var agent = __webpack_require__(/*! ./agent.js */ "./src/agent.js") var color = __webpack_require__(/*! ./color.js */ "./src/color.js") var car = __webpack_require__(/*! ./car.js */ "./src/car.js") function world() { this.agents = []; this.p2 = new p2.World({ gravity : [0,0] }); this.p2.solver.tolerance = 0.02 this.p2.solver.iterations = 60 this.p2.setGlobalStiffness(1e6) this.p2.setGlobalRelaxation(4) this.materials = { car: new p2.Material(), obstacle: new p2.Material() } this.p2.addContactMaterial(new p2.ContactMaterial(this.materials.car, this.materials.obstacle, { friction: 0.01, relaxation: 4, restitution: 0.005, contactSkinSize: 0.1, stiffness: 1e6 })); this.p2.addContactMaterial(new p2.ContactMaterial(this.materials.car, this.materials.car, { friction: 0, relaxation: 4, restitution: 0, contactSkinSize: 0.1, stiffness: 1e6 })); this.age = 0.0 this.timer = 0 this.chartData = {} this.chartEphemeralData = [] this.chartFrequency = 60 this.chartDataPoints = 200 this.smoothReward = 0 this.plotRewardOnly = false this.freeze = false; this.obstacles = [] const temporal = 1 var state = car.Sensors.dimensions, actions = 3, input = (1 + temporal) * state + temporal * actions this.brains = { actor: new neurojs.Network.Model([ { type: 'input', size: input }, { type: 'fc', size: 50, activation: 'elu' }, { type: 'fc', size: 40, activation: 'elu', dropout: 0.50 }, { type: 'fc', size: 40, activation: 'elu', dropout: 0.10 }, { type: 'fc', size: 40, activation: 'elu', dropout: 0.10 }, { type: 'fc', size: 8, activation: 'relu' }, { type: 'fc', size: actions, activation: 'tanh' }, { type: 'regression' } ]), critic: new neurojs.Network.Model([ { type: 'input', size: input + actions }, { type: 'fc', size: 60, activation: 'relu' }, { type: 'fc', size: 50, activation: 'relu' }, { type: 'fc', size: 50, activation: 'relu' }, { type: 'fc', size: 50, activation: 'relu' }, { type: 'fc', size: 1 }, { type: 'regression' } ]) } this.brains.shared = new window.neurojs.Shared.ConfigPool() // this.brains.shared.set('actor', this.brains.actor.newConfiguration()) this.brains.shared.set('critic', this.brains.critic.newConfiguration()) }; world.prototype.addBodyFromCompressedPoints = function (outline) { if (outline.length % 2 !== 0) { throw 'Invalid outline.'; } var points = [] for (var i = 0; i < (outline.length / 2); i++) { var x = outline[i * 2 + 0] var y = outline[i * 2 + 1] points.push([ x, y ]) } this.addBodyFromPoints(points) }; world.prototype.addBodyFromPoints = function (points) { var body = new p2.Body({ mass : 0.0 }); body.color = color.randomPastelHex() body.entity = 'obstacle' if(!body.fromPolygon(points.slice(0), { removeCollinearPoints: 0.1 })) { return } for (let k = 0; k < body.shapes.length; ++k) { body.shapes[k].material = this.materials.obstacle; } var outline = new Float64Array(points.length * 2) for (var i = 0; i < points.length; i++) { outline[i * 2 + 0] = points[i][0] outline[i * 2 + 1] = points[i][1] } body.outline = outline this.addObstacle(body) this.p2.step(1, 1, 1) }; world.prototype.addObstacle = function (obstacle) { this.p2.addBody(obstacle) this.obstacles.push(obstacle) }; world.prototype.addWall = function (start, end, width) { var w = 0, h = 0, pos = [] if (start[0] === end[0]) { // hor h = end[1] - start[1]; w = width pos = [ start[0], start[1] + 0.5 * h ] } else if (start[1] === end[1]) { // ver w = end[0] - start[0] h = width pos = [ start[0] + 0.5 * w, start[1] ] } else throw 'error' // Create box var b = new p2.Body({ mass : 0.0, position : pos }); b.entity = 'obstacle' var rectangleShape = new p2.Box({ width: w, height: h }); // rectangleShape.color = 0xFFFFFF rectangleShape.material = this.materials.obstacle b.hidden = true; b.addShape(rectangleShape); this.p2.addBody(b); return b; } world.prototype.addPolygons = function (polys) { for (var i = 0; i < polys.length; i++) { var points = polys[i] var b = new p2.Body({ mass : 0.0 }); if (b.fromPolygon(points, { removeCollinearPoints: 0.1, skipSimpleCheck: true })) { this.p2.addBody(b) } } } world.prototype.init = function (renderer) { window.addEventListener('resize', this.resize.bind(this, renderer), false); var w = renderer.viewport.width / renderer.viewport.scale var h = renderer.viewport.height / renderer.viewport.scale var wx = w / 2, hx = h / 2 this.addWall( [ -wx - 0.25, -hx ], [ -wx - 0.25, hx ], 0.5 ) this.addWall( [ wx + 0.25, -hx ], [ wx + 0.25, hx ], 0.5 ) this.addWall( [ -wx, -hx - 0.25 ], [ wx, -hx - 0.25 ], 0.5 ) this.addWall( [ -wx, hx + 0.25 ], [ wx, hx + 0.25 ], 0.5 ) this.size = { w, h } }; world.prototype.initialiseAgents = function (actor, critic) { for (var i = 0; i < this.agents.length; i++) { this.agents[i].init(actor, critic); } }; world.prototype.populate = function (n) { for (var i = 0; i < n; i++) { var ag = new agent({}, this); this.agents.push(ag); } }; world.prototype.resize = function (renderer) { }; world.prototype.step = function (dt) { if (dt >= 0.1) { dt = 0.1; } if (this.freeze) { return } ++this.timer var loss = 0.0, reward = 0.0 for (var i = 0; i < this.agents.length; i++) { this.agents[i].step(dt); loss += this.agents[i].loss; reward += this.agents[i].reward; } this.brains.shared.step() if ((this.agents[0].brain.learning || this.plotRewardOnly) && this.chart) { this.chartEphemeralData.push({ loss: loss / this.agents.length, reward: reward / this.agents.length }) if (this.timer % this.chartFrequency == 0) { this.updateChart() this.chartEphemeralData = [] } } this.p2.step(1 / 60, dt, 10); this.age += dt }; world.prototype.updateChart = function () { var point = { loss: 0, reward: 0 } if (this.chartEphemeralData.length !== this.chartFrequency) { throw 'error' } for (var i = 0; i < this.chartFrequency; i++) { var subpoint = this.chartEphemeralData[i] for (var key in point) { point[key] += subpoint[key] / this.chartFrequency } } if (point.reward) { var f = 1e-2; this.smoothReward = this.smoothReward * (1.0 - f) + f * point.reward; point.smoothReward = this.smoothReward; } var series = [] for (var key in point) { if (!(key in this.chartData)) { this.chartData[key] = [] } this.chartData[key].push(point[key]) if (this.chartData[key].length > this.chartDataPoints) { this.chartData[key] = this.chartData[key].slice(-this.chartDataPoints) } if (this.plotRewardOnly && (key !== 'reward' && key !== 'smoothReward')) { series.push({ name: key, data: [] }) } else { series.push({ name: key, data: this.chartData[key] }) } } this.chart.update({ series }) }; world.prototype.export = function () { var contents = [] contents.push({ obstacles: this.obstacles.length }) for (var i = 0; i < this.obstacles.length; i++) { contents.push(this.obstacles[i].outline) } var agents = [] for (var i = 0; i < this.agents.length; i++) { agents.push({ location: this.agents[i].car.chassisBody.position, angle: this.agents[i].car.chassisBody.angle }) } contents.push(agents) return window.neurojs.Binary.Writer.write(contents) }; world.prototype.clearObstacles = function () { for (var i = 0; i < this.obstacles.length; i++) { this.p2.removeBody(this.obstacles[i]) } this.obstacles = [] }; world.prototype.import = function (buf) { this.clearObstacles() let contents = window.neurojs.Binary.Reader.read(buf) let meta = contents.shift() let agents = contents.pop() let obstacles = contents; if (agents.length < this.agents.length) { throw 'error'; } for (var i = 0; i < this.agents.length; i++) { let chassis = this.agents[i].car.chassisBody; chassis.setZeroForce(); p2.vec2.set(chassis.velocity, 0, 0); p2.vec2.copy(chassis.position, agents[i].location); chassis.angle = agents[i].angle; chassis.updateAABB(); } for (var i = 0; i < obstacles.length; i++) { this.addBodyFromCompressedPoints(obstacles[i]) } this.p2.step(1, 1, 1); }; module.exports = world; /***/ }) /******/ });
'use strict' var path = require('path'); var req = require.context("../../../../api/models", true, /\.js$/); // an array of all files in folder var fileNames = req.keys(); var serverModels = {}; for (var name in fileNames) { if (fileNames.hasOwnProperty(name)) { var model = req(fileNames[name]); if (model.hop) { var modelName = path.basename(fileNames[name], '.js') serverModels[modelName] = model; } } } module.exports = serverModels;
/** * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. * Oracle Mobile Cloud Service Sync JavaScript SDK, Release: 16.4.5.0, E76062-04 */ (function(g){ // disable RequireJS and AMD var _define, _exports; if(typeof define === 'function' && define.amd){ _define = define; define = undefined; } else if(typeof exports === 'object'){ _exports = exports; exports = undefined; } /** * LokiJS * @author Joe Minichino <joe.minichino@gmail.com> * @version 1.4.1 * A lightweight document oriented javascript database */ (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD define([], factory); } else if (typeof exports === 'object') { // CommonJS module.exports = factory(); } else { // Browser globals root.loki = factory(); } }(this, function () { return (function () { 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; var Utils = { copyProperties: function (src, dest) { var prop; for (prop in src) { dest[prop] = src[prop]; } }, // used to recursively scan hierarchical transform step object for param substitution resolveTransformObject: function (subObj, params, depth) { var prop, pname; if (typeof depth !== 'number') { depth = 0; } if (++depth >= 10) return subObj; for (prop in subObj) { if (typeof subObj[prop] === 'string' && subObj[prop].indexOf("[%lktxp]") === 0) { pname = subObj[prop].substring(8); if (params.hasOwnProperty(pname)) { subObj[prop] = params[pname]; } } else if (typeof subObj[prop] === "object") { subObj[prop] = Utils.resolveTransformObject(subObj[prop], params, depth); } } return subObj; }, // top level utility to resolve an entire (single) transform (array of steps) for parameter substitution resolveTransformParams: function (transform, params) { var idx, clonedStep, resolvedTransform = []; if (typeof params === 'undefined') return transform; // iterate all steps in the transform array for (idx = 0; idx < transform.length; idx++) { // clone transform so our scan and replace can operate directly on cloned transform clonedStep = JSON.parse(JSON.stringify(transform[idx])); resolvedTransform.push(Utils.resolveTransformObject(clonedStep, params)); } return resolvedTransform; } }; /** Helper function for determining 'less-than' conditions for ops, sorting, and binary indices. * In the future we might want $lt and $gt ops to use their own functionality/helper. * Since binary indices on a property might need to index [12, NaN, new Date(), Infinity], we * need this function (as well as gtHelper) to always ensure one value is LT, GT, or EQ to another. */ function ltHelper(prop1, prop2, equal) { var cv1, cv2; // 'falsy' and Boolean handling if (!prop1 || !prop2 || prop1 === true || prop2 === true) { if ((prop1 === true || prop1 === false) && (prop2 === true || prop2 === false)) { if (equal) { return prop1 === prop2; } else { if (prop1) { return false; } else { return prop2; } } } if (prop2 === undefined || prop2 === null || prop1 === true || prop2 === false) { return equal; } if (prop1 === undefined || prop1 === null || prop1 === false || prop2 === true) { return true; } } if (prop1 === prop2) { return equal; } if (prop1 < prop2) { return true; } if (prop1 > prop2) { return false; } // not strict equal nor less than nor gt so must be mixed types, convert to string and use that to compare cv1 = prop1.toString(); cv2 = prop2.toString(); if (cv1 == cv2) { return equal; } if (cv1 < cv2) { return true; } return false; } function gtHelper(prop1, prop2, equal) { var cv1, cv2; // 'falsy' and Boolean handling if (!prop1 || !prop2 || prop1 === true || prop2 === true) { if ((prop1 === true || prop1 === false) && (prop2 === true || prop2 === false)) { if (equal) { return prop1 === prop2; } else { if (prop1) { return !prop2; } else { return false; } } } if (prop1 === undefined || prop1 === null || prop1 === false || prop2 === true) { return equal; } if (prop2 === undefined || prop2 === null || prop1 === true || prop2 === false) { return true; } } if (prop1 === prop2) { return equal; } if (prop1 > prop2) { return true; } if (prop1 < prop2) { return false; } // not strict equal nor less than nor gt so must be mixed types, convert to string and use that to compare cv1 = prop1.toString(); cv2 = prop2.toString(); if (cv1 == cv2) { return equal; } if (cv1 > cv2) { return true; } return false; } function sortHelper(prop1, prop2, desc) { if (prop1 === prop2) { return 0; } if (ltHelper(prop1, prop2, false)) { return (desc) ? (1) : (-1); } if (gtHelper(prop1, prop2, false)) { return (desc) ? (-1) : (1); } // not lt, not gt so implied equality-- date compatible return 0; } /** * compoundeval() - helper function for compoundsort(), performing individual object comparisons * * @param {array} properties - array of property names, in order, by which to evaluate sort order * @param {object} obj1 - first object to compare * @param {object} obj2 - second object to compare * @returns {integer} 0, -1, or 1 to designate if identical (sortwise) or which should be first */ function compoundeval(properties, obj1, obj2) { var res = 0; var prop, field; for (var i = 0, len = properties.length; i < len; i++) { prop = properties[i]; field = prop[0]; res = sortHelper(obj1[field], obj2[field], prop[1]); if (res !== 0) { return res; } } return 0; } /** * dotSubScan - helper function used for dot notation queries. * * @param {object} root - object to traverse * @param {array} paths - array of properties to drill into * @param {function} fun - evaluation function to test with * @param {any} value - comparative value to also pass to (compare) fun */ function dotSubScan(root, paths, fun, value) { var path = paths[0]; if (typeof root === 'undefined' || root === null || !root.hasOwnProperty(path)) { return false; } var valueFound = false; var element = root[path]; if (Array.isArray(element)) { var index; for (index in element) { valueFound = valueFound || dotSubScan(element[index], paths.slice(1, paths.length), fun, value); if (valueFound === true) { break; } } } else if (typeof element === 'object') { valueFound = dotSubScan(element, paths.slice(1, paths.length), fun, value); } else { valueFound = fun(element, value); } return valueFound; } function containsCheckFn(a) { if (typeof a === 'string' || Array.isArray(a)) { return function (b) { return a.indexOf(b) !== -1; }; } else if (typeof a === 'object' && a !== null) { return function (b) { return hasOwnProperty.call(a, b); }; } return null; } function doQueryOp(val, op) { for (var p in op) { if (hasOwnProperty.call(op, p)) { return LokiOps[p](val, op[p]); } } return false; } var LokiOps = { // comparison operators // a is the value in the collection // b is the query value $eq: function (a, b) { return a === b; }, // abstract/loose equality $aeq: function (a, b) { return a == b; }, $ne: function (a, b) { // ecma 5 safe test for NaN if (b !== b) { // ecma 5 test value is not NaN return (a === a); } return a !== b; }, $dteq: function (a, b) { if (ltHelper(a, b, false)) { return false; } return !gtHelper(a, b, false); }, $gt: function (a, b) { return gtHelper(a, b, false); }, $gte: function (a, b) { return gtHelper(a, b, true); }, $lt: function (a, b) { return ltHelper(a, b, false); }, $lte: function (a, b) { return ltHelper(a, b, true); }, $in: function (a, b) { return b.indexOf(a) !== -1; }, $nin: function (a, b) { return b.indexOf(a) === -1; }, $keyin: function (a, b) { return a in b; }, $nkeyin: function (a, b) { return !(a in b); }, $definedin: function (a, b) { return b[a] !== undefined; }, $undefinedin: function (a, b) { return b[a] === undefined; }, $regex: function (a, b) { return b.test(a); }, $containsString: function (a, b) { return (typeof a === 'string') && (a.indexOf(b) !== -1); }, $containsNone: function (a, b) { return !LokiOps.$containsAny(a, b); }, $containsAny: function (a, b) { var checkFn = containsCheckFn(a); if (checkFn !== null) { return (Array.isArray(b)) ? (b.some(checkFn)) : (checkFn(b)); } return false; }, $contains: function (a, b) { var checkFn = containsCheckFn(a); if (checkFn !== null) { return (Array.isArray(b)) ? (b.every(checkFn)) : (checkFn(b)); } return false; }, $type: function (a, b) { var type = typeof a; if (type === 'object') { if (Array.isArray(a)) { type = 'array'; } else if (a instanceof Date) { type = 'date'; } } return (typeof b !== 'object') ? (type === b) : doQueryOp(type, b); }, $size: function (a, b) { if (Array.isArray(a)) { return (typeof b !== 'object') ? (a.length === b) : doQueryOp(a.length, b); } return false; }, $len: function (a, b) { if (typeof a === 'string') { return (typeof b !== 'object') ? (a.length === b) : doQueryOp(a.length, b); } return false; }, $where: function (a, b) { return b(a) === true; }, // field-level logical operators // a is the value in the collection // b is the nested query operation (for '$not') // or an array of nested query operations (for '$and' and '$or') $not: function (a, b) { return !doQueryOp(a, b); }, $and: function (a, b) { for (var idx = 0, len = b.length; idx < len; idx += 1) { if (!doQueryOp(a, b[idx])) { return false; } } return true; }, $or: function (a, b) { for (var idx = 0, len = b.length; idx < len; idx += 1) { if (doQueryOp(a, b[idx])) { return true; } } return false; } }; // making indexing opt-in... our range function knows how to deal with these ops : var indexedOpsList = ['$eq', '$aeq', '$dteq', '$gt', '$gte', '$lt', '$lte']; function clone(data, method) { var cloneMethod = method || 'parse-stringify', cloned; switch (cloneMethod) { case "parse-stringify": cloned = JSON.parse(JSON.stringify(data)); break; case "jquery-extend-deep": cloned = jQuery.extend(true, {}, data); break; case "shallow": cloned = Object.create(data.prototype || null); Object.keys(data).map(function (i) { cloned[i] = data[i]; }); break; default: break; } //if (cloneMethod === 'parse-stringify') { // cloned = JSON.parse(JSON.stringify(data)); //} return cloned; } function cloneObjectArray(objarray, method) { var i, result = []; if (method == "parse-stringify") { return clone(objarray, method); } i = objarray.length - 1; for (; i <= 0; i--) { result.push(clone(objarray[i], method)); } return result; } function localStorageAvailable() { try { return (window && window.localStorage !== undefined && window.localStorage !== null); } catch (e) { return false; } } /** * LokiEventEmitter is a minimalist version of EventEmitter. It enables any * constructor that inherits EventEmitter to emit events and trigger * listeners that have been added to the event through the on(event, callback) method * * @constructor LokiEventEmitter */ function LokiEventEmitter() {} /** * @prop {hashmap} events - a hashmap, with each property being an array of callbacks * @memberof LokiEventEmitter */ LokiEventEmitter.prototype.events = {}; /** * @prop {boolean} asyncListeners - boolean determines whether or not the callbacks associated with each event * should happen in an async fashion or not * Default is false, which means events are synchronous * @memberof LokiEventEmitter */ LokiEventEmitter.prototype.asyncListeners = false; /** * on(eventName, listener) - adds a listener to the queue of callbacks associated to an event * @param {string} eventName - the name of the event to listen to * @param {function} listener - callback function of listener to attach * @returns {int} the index of the callback in the array of listeners for a particular event * @memberof LokiEventEmitter */ LokiEventEmitter.prototype.on = function (eventName, listener) { var event = this.events[eventName]; if (!event) { event = this.events[eventName] = []; } event.push(listener); return listener; }; /** * emit(eventName, data) - emits a particular event * with the option of passing optional parameters which are going to be processed by the callback * provided signatures match (i.e. if passing emit(event, arg0, arg1) the listener should take two parameters) * @param {string} eventName - the name of the event * @param {object=} data - optional object passed with the event * @memberof LokiEventEmitter */ LokiEventEmitter.prototype.emit = function (eventName, data) { var self = this; if (eventName && this.events[eventName]) { this.events[eventName].forEach(function (listener) { if (self.asyncListeners) { setTimeout(function () { listener(data); }, 1); } else { listener(data); } }); } else { throw new Error('No event ' + eventName + ' defined'); } }; /** * removeListener() - removes the listener at position 'index' from the event 'eventName' * @param {string} eventName - the name of the event which the listener is attached to * @param {function} listener - the listener callback function to remove from emitter * @memberof LokiEventEmitter */ LokiEventEmitter.prototype.removeListener = function (eventName, listener) { if (this.events[eventName]) { var listeners = this.events[eventName]; listeners.splice(listeners.indexOf(listener), 1); } }; /** * Loki: The main database class * @constructor Loki * @implements LokiEventEmitter * @param {string} filename - name of the file to be saved to * @param {object=} options - (Optional) config options object * @param {string} options.env - override environment detection as 'NODEJS', 'BROWSER', 'CORDOVA' * @param {boolean} options.verbose - enable console output (default is 'false') * @param {boolean} options.autosave - enables autosave * @param {int} options.autosaveInterval - time interval (in milliseconds) between saves (if dirty) * @param {boolean} options.autoload - enables autoload on loki instantiation * @param {function} options.autoloadCallback - user callback called after database load * @param {adapter} options.adapter - an instance of a loki persistence adapter */ function Loki(filename, options) { this.filename = filename || 'loki.db'; this.collections = []; // persist version of code which created the database to the database. // could use for upgrade scenarios this.databaseVersion = 1.1; this.engineVersion = 1.1; // autosave support (disabled by default) // pass autosave: true, autosaveInterval: 6000 in options to set 6 second autosave this.autosave = false; this.autosaveInterval = 5000; this.autosaveHandle = null; this.options = {}; // currently keeping persistenceMethod and persistenceAdapter as loki level properties that // will not or cannot be deserialized. You are required to configure persistence every time // you instantiate a loki object (or use default environment detection) in order to load the database anyways. // persistenceMethod could be 'fs', 'localStorage', or 'adapter' // this is optional option param, otherwise environment detection will be used // if user passes their own adapter we will force this method to 'adapter' later, so no need to pass method option. this.persistenceMethod = null; // retain reference to optional (non-serializable) persistenceAdapter 'instance' this.persistenceAdapter = null; // enable console output if verbose flag is set (disabled by default) this.verbose = options && options.hasOwnProperty('verbose') ? options.verbose : false; this.events = { 'init': [], 'loaded': [], 'flushChanges': [], 'close': [], 'changes': [], 'warning': [] }; var getENV = function () { // if (typeof global !== 'undefined' && (global.android || global.NSObject)) { // //If no adapter is set use the default nativescript adapter // if (!options.adapter) { // var LokiNativescriptAdapter = require('./loki-nativescript-adapter'); // options.adapter=new LokiNativescriptAdapter(); // } // return 'NATIVESCRIPT'; //nativescript // } if (typeof window === 'undefined') { return 'NODEJS'; } if (typeof global !== 'undefined' && global.window) { return 'NODEJS'; //node-webkit } if (typeof document !== 'undefined') { if (document.URL.indexOf('http://') === -1 && document.URL.indexOf('https://') === -1) { return 'CORDOVA'; } return 'BROWSER'; } return 'CORDOVA'; }; // refactored environment detection due to invalid detection for browser environments. // if they do not specify an options.env we want to detect env rather than default to nodejs. // currently keeping two properties for similar thing (options.env and options.persistenceMethod) // might want to review whether we can consolidate. if (options && options.hasOwnProperty('env')) { this.ENV = options.env; } else { this.ENV = getENV(); } // not sure if this is necessary now that i have refactored the line above if (this.ENV === 'undefined') { this.ENV = 'NODEJS'; } //if (typeof (options) !== 'undefined') { this.configureOptions(options, true); //} this.on('init', this.clearChanges); } // db class is an EventEmitter Loki.prototype = new LokiEventEmitter(); // experimental support for browserify's abstract syntax scan to pick up dependency of indexed adapter. // Hopefully, once this hits npm a browserify require of lokijs should scan the main file and detect this indexed adapter reference. Loki.prototype.getIndexedAdapter = function () { var adapter; if (typeof require === 'function') { adapter = require("./loki-indexed-adapter.js"); } return adapter; }; /** * Allows reconfiguring database options * * @param {object} options - configuration options to apply to loki db object * @param {string} options.env - override environment detection as 'NODEJS', 'BROWSER', 'CORDOVA' * @param {boolean} options.verbose - enable console output (default is 'false') * @param {boolean} options.autosave - enables autosave * @param {int} options.autosaveInterval - time interval (in milliseconds) between saves (if dirty) * @param {boolean} options.autoload - enables autoload on loki instantiation * @param {function} options.autoloadCallback - user callback called after database load * @param {adapter} options.adapter - an instance of a loki persistence adapter * @param {boolean} initialConfig - (internal) true is passed when loki ctor is invoking * @memberof Loki */ Loki.prototype.configureOptions = function (options, initialConfig) { var defaultPersistence = { 'NODEJS': 'fs', 'BROWSER': 'localStorage', 'CORDOVA': 'localStorage' }, persistenceMethods = { 'fs': LokiFsAdapter, 'localStorage': LokiLocalStorageAdapter }; this.options = {}; this.persistenceMethod = null; // retain reference to optional persistence adapter 'instance' // currently keeping outside options because it can't be serialized this.persistenceAdapter = null; // process the options if (typeof (options) !== 'undefined') { this.options = options; if (this.options.hasOwnProperty('persistenceMethod')) { // check if the specified persistence method is known if (typeof (persistenceMethods[options.persistenceMethod]) == 'function') { this.persistenceMethod = options.persistenceMethod; this.persistenceAdapter = new persistenceMethods[options.persistenceMethod](); } // should be throw an error here, or just fall back to defaults ?? } // if user passes adapter, set persistence mode to adapter and retain persistence adapter instance if (this.options.hasOwnProperty('adapter')) { this.persistenceMethod = 'adapter'; this.persistenceAdapter = options.adapter; this.options.adapter = null; } // if they want to load database on loki instantiation, now is a good time to load... after adapter set and before possible autosave initiation if (options.autoload && initialConfig) { // for autoload, let the constructor complete before firing callback var self = this; setTimeout(function () { self.loadDatabase(options, options.autoloadCallback); }, 1); } if (this.options.hasOwnProperty('autosaveInterval')) { this.autosaveDisable(); this.autosaveInterval = parseInt(this.options.autosaveInterval, 10); } if (this.options.hasOwnProperty('autosave') && this.options.autosave) { this.autosaveDisable(); this.autosave = true; if (this.options.hasOwnProperty('autosaveCallback')) { this.autosaveEnable(options, options.autosaveCallback); } else { this.autosaveEnable(); } } } // end of options processing // if by now there is no adapter specified by user nor derived from persistenceMethod: use sensible defaults if (this.persistenceAdapter === null) { this.persistenceMethod = defaultPersistence[this.ENV]; if (this.persistenceMethod) { this.persistenceAdapter = new persistenceMethods[this.persistenceMethod](); } } }; /** * Shorthand method for quickly creating and populating an anonymous collection. * This collection is not referenced internally so upon losing scope it will be garbage collected. * * @example * var results = new loki().anonym(myDocArray).find({'age': {'$gt': 30} }); * * @param {Array} docs - document array to initialize the anonymous collection with * @param {object} options - configuration object, see {@link Loki#addCollection} options * @returns {Collection} New collection which you can query or chain * @memberof Loki */ Loki.prototype.anonym = function (docs, options) { var collection = new Collection('anonym', options); collection.insert(docs); if (this.verbose) collection.console = console; return collection; }; /** * Adds a collection to the database. * @param {string} name - name of collection to add * @param {object=} options - (optional) options to configure collection with. * @param {array} options.unique - array of property names to define unique constraints for * @param {array} options.exact - array of property names to define exact constraints for * @param {array} options.indices - array property names to define binary indexes for * @param {boolean} options.asyncListeners - default is false * @param {boolean} options.disableChangesApi - default is true * @param {boolean} options.autoupdate - use Object.observe to update objects automatically (default: false) * @param {boolean} options.clone - specify whether inserts and queries clone to/from user * @param {string} options.cloneMethod - 'parse-stringify' (default), 'jquery-extend-deep', 'shallow' * @param {int} options.ttlInterval - time interval for clearing out 'aged' documents; not set by default. * @returns {Collection} a reference to the collection which was just added * @memberof Loki */ Loki.prototype.addCollection = function (name, options) { var collection = new Collection(name, options); this.collections.push(collection); if (this.verbose) collection.console = console; return collection; }; Loki.prototype.loadCollection = function (collection) { if (!collection.name) { throw new Error('Collection must have a name property to be loaded'); } this.collections.push(collection); }; /** * Retrieves reference to a collection by name. * @param {string} collectionName - name of collection to look up * @returns {Collection} Reference to collection in database by that name, or null if not found * @memberof Loki */ Loki.prototype.getCollection = function (collectionName) { var i, len = this.collections.length; for (i = 0; i < len; i += 1) { if (this.collections[i].name === collectionName) { return this.collections[i]; } } // no such collection this.emit('warning', 'collection ' + collectionName + ' not found'); return null; }; Loki.prototype.listCollections = function () { var i = this.collections.length, colls = []; while (i--) { colls.push({ name: this.collections[i].name, type: this.collections[i].objType, count: this.collections[i].data.length }); } return colls; }; /** * Removes a collection from the database. * @param {string} collectionName - name of collection to remove * @memberof Loki */ Loki.prototype.removeCollection = function (collectionName) { var i, len = this.collections.length; for (i = 0; i < len; i += 1) { if (this.collections[i].name === collectionName) { var tmpcol = new Collection(collectionName, {}); var curcol = this.collections[i]; for (var prop in curcol) { if (curcol.hasOwnProperty(prop) && tmpcol.hasOwnProperty(prop)) { curcol[prop] = tmpcol[prop]; } } this.collections.splice(i, 1); return; } } }; Loki.prototype.getName = function () { return this.name; }; /** * serializeReplacer - used to prevent certain properties from being serialized * */ Loki.prototype.serializeReplacer = function (key, value) { switch (key) { case 'autosaveHandle': case 'persistenceAdapter': case 'constraints': return null; default: return value; } }; /** * Serialize database to a string which can be loaded via {@link Loki#loadJSON} * * @returns {string} Stringified representation of the loki database. * @memberof Loki */ Loki.prototype.serialize = function () { return JSON.stringify(this, this.serializeReplacer); }; // alias of serialize Loki.prototype.toJson = Loki.prototype.serialize; /** * Inflates a loki database from a serialized JSON string * * @param {string} serializedDb - a serialized loki database string * @param {object} options - apply or override collection level settings * @memberof Loki */ Loki.prototype.loadJSON = function (serializedDb, options) { var dbObject; if (serializedDb.length === 0) { dbObject = {}; } else { dbObject = JSON.parse(serializedDb); } this.loadJSONObject(dbObject, options); }; /** * Inflates a loki database from a JS object * * @param {object} dbObject - a serialized loki database string * @param {object} options - apply or override collection level settings * @memberof Loki */ Loki.prototype.loadJSONObject = function (dbObject, options) { var i = 0, len = dbObject.collections ? dbObject.collections.length : 0, coll, copyColl, clen, j; this.name = dbObject.name; // restore database version this.databaseVersion = 1.0; if (dbObject.hasOwnProperty('databaseVersion')) { this.databaseVersion = dbObject.databaseVersion; } this.collections = []; for (i; i < len; i += 1) { coll = dbObject.collections[i]; copyColl = this.addCollection(coll.name); copyColl.transactional = coll.transactional; copyColl.asyncListeners = coll.asyncListeners; copyColl.disableChangesApi = coll.disableChangesApi; copyColl.cloneObjects = coll.cloneObjects; copyColl.cloneMethod = coll.cloneMethod || "parse-stringify"; copyColl.autoupdate = coll.autoupdate; // load each element individually clen = coll.data.length; j = 0; if (options && options.hasOwnProperty(coll.name)) { var loader = options[coll.name].inflate ? options[coll.name].inflate : Utils.copyProperties; for (j; j < clen; j++) { var collObj = new(options[coll.name].proto)(); loader(coll.data[j], collObj); copyColl.data[j] = collObj; copyColl.addAutoUpdateObserver(collObj); } } else { for (j; j < clen; j++) { copyColl.data[j] = coll.data[j]; copyColl.addAutoUpdateObserver(copyColl.data[j]); } } copyColl.maxId = (coll.data.length === 0) ? 0 : coll.maxId; copyColl.idIndex = coll.idIndex; if (typeof (coll.binaryIndices) !== 'undefined') { copyColl.binaryIndices = coll.binaryIndices; } if (typeof coll.transforms !== 'undefined') { copyColl.transforms = coll.transforms; } copyColl.ensureId(); // regenerate unique indexes copyColl.uniqueNames = []; if (coll.hasOwnProperty("uniqueNames")) { copyColl.uniqueNames = coll.uniqueNames; for (j = 0; j < copyColl.uniqueNames.length; j++) { copyColl.ensureUniqueIndex(copyColl.uniqueNames[j]); } } // in case they are loading a database created before we added dynamic views, handle undefined if (typeof (coll.DynamicViews) === 'undefined') continue; // reinflate DynamicViews and attached Resultsets for (var idx = 0; idx < coll.DynamicViews.length; idx++) { var colldv = coll.DynamicViews[idx]; var dv = copyColl.addDynamicView(colldv.name, colldv.options); dv.resultdata = colldv.resultdata; dv.resultsdirty = colldv.resultsdirty; dv.filterPipeline = colldv.filterPipeline; dv.sortCriteria = colldv.sortCriteria; dv.sortFunction = null; dv.sortDirty = colldv.sortDirty; dv.resultset.filteredrows = colldv.resultset.filteredrows; dv.resultset.searchIsChained = colldv.resultset.searchIsChained; dv.resultset.filterInitialized = colldv.resultset.filterInitialized; dv.rematerialize({ removeWhereFilters: true }); } } }; /** * Emits the close event. In autosave scenarios, if the database is dirty, this will save and disable timer. * Does not actually destroy the db. * * @param {function=} callback - (Optional) if supplied will be registered with close event before emitting. * @memberof Loki */ Loki.prototype.close = function (callback) { // for autosave scenarios, we will let close perform final save (if dirty) // For web use, you might call from window.onbeforeunload to shutdown database, saving pending changes if (this.autosave) { this.autosaveDisable(); if (this.autosaveDirty()) { this.saveDatabase(callback); callback = undefined; } } if (callback) { this.on('close', callback); } this.emit('close'); }; /**-------------------------+ | Changes API | +--------------------------*/ /** * The Changes API enables the tracking the changes occurred in the collections since the beginning of the session, * so it's possible to create a differential dataset for synchronization purposes (possibly to a remote db) */ /** * (Changes API) : takes all the changes stored in each * collection and creates a single array for the entire database. If an array of names * of collections is passed then only the included collections will be tracked. * * @param {array=} optional array of collection names. No arg means all collections are processed. * @returns {array} array of changes * @see private method createChange() in Collection * @memberof Loki */ Loki.prototype.generateChangesNotification = function (arrayOfCollectionNames) { function getCollName(coll) { return coll.name; } var changes = [], selectedCollections = arrayOfCollectionNames || this.collections.map(getCollName); this.collections.forEach(function (coll) { if (selectedCollections.indexOf(getCollName(coll)) !== -1) { changes = changes.concat(coll.getChanges()); } }); return changes; }; /** * (Changes API) - stringify changes for network transmission * @returns {string} string representation of the changes * @memberof Loki */ Loki.prototype.serializeChanges = function (collectionNamesArray) { return JSON.stringify(this.generateChangesNotification(collectionNamesArray)); }; /** * (Changes API) : clears all the changes in all collections. * @memberof Loki */ Loki.prototype.clearChanges = function () { this.collections.forEach(function (coll) { if (coll.flushChanges) { coll.flushChanges(); } }); }; /*------------------+ | PERSISTENCE | -------------------*/ /** there are two build in persistence adapters for internal use * fs for use in Nodejs type environments * localStorage for use in browser environment * defined as helper classes here so its easy and clean to use */ /** * A loki persistence adapter which persists using node fs module * @constructor LokiFsAdapter */ function LokiFsAdapter() { this.fs = require('fs'); } /** * loadDatabase() - Load data from file, will throw an error if the file does not exist * @param {string} dbname - the filename of the database to load * @param {function} callback - the callback to handle the result * @memberof LokiFsAdapter */ LokiFsAdapter.prototype.loadDatabase = function loadDatabase(dbname, callback) { this.fs.readFile(dbname, { encoding: 'utf8' }, function readFileCallback(err, data) { if (err) { callback(new Error(err)); } else { callback(data); } }); }; /** * saveDatabase() - save data to file, will throw an error if the file can't be saved * might want to expand this to avoid dataloss on partial save * @param {string} dbname - the filename of the database to load * @param {function} callback - the callback to handle the result * @memberof LokiFsAdapter */ LokiFsAdapter.prototype.saveDatabase = function saveDatabase(dbname, dbstring, callback) { this.fs.writeFile(dbname, dbstring, callback); }; /** * deleteDatabase() - delete the database file, will throw an error if the * file can't be deleted * @param {string} dbname - the filename of the database to delete * @param {function} callback - the callback to handle the result * @memberof LokiFsAdapter */ LokiFsAdapter.prototype.deleteDatabase = function deleteDatabase(dbname, callback) { this.fs.unlink(dbname, function deleteDatabaseCallback(err) { if (err) { callback(new Error(err)); } else { callback(); } }); }; /** * A loki persistence adapter which persists to web browser's local storage object * @constructor LokiLocalStorageAdapter */ function LokiLocalStorageAdapter() {} /** * loadDatabase() - Load data from localstorage * @param {string} dbname - the name of the database to load * @param {function} callback - the callback to handle the result * @memberof LokiLocalStorageAdapter */ LokiLocalStorageAdapter.prototype.loadDatabase = function loadDatabase(dbname, callback) { if (localStorageAvailable()) { callback(localStorage.getItem(dbname)); } else { callback(new Error('localStorage is not available')); } }; /** * saveDatabase() - save data to localstorage, will throw an error if the file can't be saved * might want to expand this to avoid dataloss on partial save * @param {string} dbname - the filename of the database to load * @param {function} callback - the callback to handle the result * @memberof LokiLocalStorageAdapter */ LokiLocalStorageAdapter.prototype.saveDatabase = function saveDatabase(dbname, dbstring, callback) { if (localStorageAvailable()) { localStorage.setItem(dbname, dbstring); callback(null); } else { callback(new Error('localStorage is not available')); } }; /** * deleteDatabase() - delete the database from localstorage, will throw an error if it * can't be deleted * @param {string} dbname - the filename of the database to delete * @param {function} callback - the callback to handle the result * @memberof LokiLocalStorageAdapter */ LokiLocalStorageAdapter.prototype.deleteDatabase = function deleteDatabase(dbname, callback) { if (localStorageAvailable()) { localStorage.removeItem(dbname); callback(null); } else { callback(new Error('localStorage is not available')); } }; /** * Handles loading from file system, local storage, or adapter (indexeddb) * This method utilizes loki configuration options (if provided) to determine which * persistence method to use, or environment detection (if configuration was not provided). * * @param {object} options - not currently used (remove or allow overrides?) * @param {function=} callback - (Optional) user supplied async callback / error handler * @memberof Loki */ Loki.prototype.loadDatabase = function (options, callback) { var cFun = callback || function (err, data) { if (err) { throw err; } }, self = this; // the persistenceAdapter should be present if all is ok, but check to be sure. if (this.persistenceAdapter !== null) { this.persistenceAdapter.loadDatabase(this.filename, function loadDatabaseCallback(dbString) { if (typeof (dbString) === 'string') { var parseSuccess = false; try { self.loadJSON(dbString, options || {}); parseSuccess = true; } catch (err) { cFun(err); } if (parseSuccess) { cFun(null); self.emit('loaded', 'database ' + self.filename + ' loaded'); } } else { // if adapter has returned an js object (other than null or error) attempt to load from JSON object if (typeof (dbString) === "object" && dbString !== null && !(dbString instanceof Error)) { self.loadJSONObject(dbString, options || {}); cFun(null); // return null on success self.emit('loaded', 'database ' + self.filename + ' loaded'); } else { // error from adapter (either null or instance of error), pass on to 'user' callback cFun(dbString); } } }); } else { cFun(new Error('persistenceAdapter not configured')); } }; /** * Handles saving to file system, local storage, or adapter (indexeddb) * This method utilizes loki configuration options (if provided) to determine which * persistence method to use, or environment detection (if configuration was not provided). * * @param {function=} callback - (Optional) user supplied async callback / error handler * @memberof Loki */ Loki.prototype.saveDatabase = function (callback) { var cFun = callback || function (err) { if (err) { throw err; } return; }, self = this; // the persistenceAdapter should be present if all is ok, but check to be sure. if (this.persistenceAdapter !== null) { // check if the adapter is requesting (and supports) a 'reference' mode export if (this.persistenceAdapter.mode === "reference" && typeof this.persistenceAdapter.exportDatabase === "function") { // filename may seem redundant but loadDatabase will need to expect this same filename this.persistenceAdapter.exportDatabase(this.filename, this, function exportDatabaseCallback(err) { self.autosaveClearFlags(); cFun(err); }); } // otherwise just pass the serialized database to adapter else { this.persistenceAdapter.saveDatabase(this.filename, self.serialize(), function saveDatabasecallback(err) { self.autosaveClearFlags(); cFun(err); }); } } else { cFun(new Error('persistenceAdapter not configured')); } }; // alias Loki.prototype.save = Loki.prototype.saveDatabase; /** * Handles deleting a database from file system, local * storage, or adapter (indexeddb) * This method utilizes loki configuration options (if provided) to determine which * persistence method to use, or environment detection (if configuration was not provided). * * @param {object} options - not currently used (remove or allow overrides?) * @param {function=} callback - (Optional) user supplied async callback / error handler * @memberof Loki */ Loki.prototype.deleteDatabase = function (options, callback) { var cFun = callback || function (err, data) { if (err) { throw err; } }; // the persistenceAdapter should be present if all is ok, but check to be sure. if (this.persistenceAdapter !== null) { this.persistenceAdapter.deleteDatabase(this.filename, function deleteDatabaseCallback(err) { cFun(err); }); } else { cFun(new Error('persistenceAdapter not configured')); } }; /** * autosaveDirty - check whether any collections are 'dirty' meaning we need to save (entire) database * * @returns {boolean} - true if database has changed since last autosave, false if not. */ Loki.prototype.autosaveDirty = function () { for (var idx = 0; idx < this.collections.length; idx++) { if (this.collections[idx].dirty) { return true; } } return false; }; /** * autosaveClearFlags - resets dirty flags on all collections. * Called from saveDatabase() after db is saved. * */ Loki.prototype.autosaveClearFlags = function () { for (var idx = 0; idx < this.collections.length; idx++) { this.collections[idx].dirty = false; } }; /** * autosaveEnable - begin a javascript interval to periodically save the database. * * @param {object} options - not currently used (remove or allow overrides?) * @param {function=} callback - (Optional) user supplied async callback */ Loki.prototype.autosaveEnable = function (options, callback) { this.autosave = true; var delay = 5000, self = this; if (typeof (this.autosaveInterval) !== 'undefined' && this.autosaveInterval !== null) { delay = this.autosaveInterval; } this.autosaveHandle = setInterval(function autosaveHandleInterval() { // use of dirty flag will need to be hierarchical since mods are done at collection level with no visibility of 'db' // so next step will be to implement collection level dirty flags set on insert/update/remove // along with loki level isdirty() function which iterates all collections to see if any are dirty if (self.autosaveDirty()) { self.saveDatabase(callback); } }, delay); }; /** * autosaveDisable - stop the autosave interval timer. * */ Loki.prototype.autosaveDisable = function () { if (typeof (this.autosaveHandle) !== 'undefined' && this.autosaveHandle !== null) { clearInterval(this.autosaveHandle); this.autosaveHandle = null; } }; /** * Resultset class allowing chainable queries. Intended to be instanced internally. * Collection.find(), Collection.where(), and Collection.chain() instantiate this. * * @example * mycollection.chain() * .find({ 'doors' : 4 }) * .where(function(obj) { return obj.name === 'Toyota' }) * .data(); * * @constructor Resultset * @param {Collection} collection - The collection which this Resultset will query against. * @param {Object=} options - Object containing one or more options. * @param {string} options.queryObj - Optional mongo-style query object to initialize resultset with. * @param {function} options.queryFunc - Optional javascript filter function to initialize resultset with. * @param {bool} options.firstOnly - Optional boolean used by collection.findOne(). */ function Resultset(collection, options) { options = options || {}; options.queryObj = options.queryObj || null; options.queryFunc = options.queryFunc || null; options.firstOnly = options.firstOnly || false; // retain reference to collection we are querying against this.collection = collection; // if chain() instantiates with null queryObj and queryFunc, so we will keep flag for later this.searchIsChained = (!options.queryObj && !options.queryFunc); this.filteredrows = []; this.filterInitialized = false; // if user supplied initial queryObj or queryFunc, apply it if (typeof (options.queryObj) !== "undefined" && options.queryObj !== null) { return this.find(options.queryObj, options.firstOnly); } if (typeof (options.queryFunc) !== "undefined" && options.queryFunc !== null) { return this.where(options.queryFunc); } // otherwise return unfiltered Resultset for future filtering return this; } /** * reset() - Reset the resultset to its initial state. * * @returns {Resultset} Reference to this resultset, for future chain operations. */ Resultset.prototype.reset = function () { if (this.filteredrows.length > 0) { this.filteredrows = []; } this.filterInitialized = false; return this; }; /** * toJSON() - Override of toJSON to avoid circular references * */ Resultset.prototype.toJSON = function () { var copy = this.copy(); copy.collection = null; return copy; }; /** * Allows you to limit the number of documents passed to next chain operation. * A resultset copy() is made to avoid altering original resultset. * * @param {int} qty - The number of documents to return. * @returns {Resultset} Returns a copy of the resultset, limited by qty, for subsequent chain ops. * @memberof Resultset */ Resultset.prototype.limit = function (qty) { // if this is chained resultset with no filters applied, we need to populate filteredrows first if (this.searchIsChained && !this.filterInitialized && this.filteredrows.length === 0) { this.filteredrows = this.collection.prepareFullDocIndex(); } var rscopy = new Resultset(this.collection); rscopy.filteredrows = this.filteredrows.slice(0, qty); rscopy.filterInitialized = true; return rscopy; }; /** * Used for skipping 'pos' number of documents in the resultset. * * @param {int} pos - Number of documents to skip; all preceding documents are filtered out. * @returns {Resultset} Returns a copy of the resultset, containing docs starting at 'pos' for subsequent chain ops. * @memberof Resultset */ Resultset.prototype.offset = function (pos) { // if this is chained resultset with no filters applied, we need to populate filteredrows first if (this.searchIsChained && !this.filterInitialized && this.filteredrows.length === 0) { this.filteredrows = this.collection.prepareFullDocIndex(); } var rscopy = new Resultset(this.collection); rscopy.filteredrows = this.filteredrows.slice(pos); rscopy.filterInitialized = true; return rscopy; }; /** * copy() - To support reuse of resultset in branched query situations. * * @returns {Resultset} Returns a copy of the resultset (set) but the underlying document references will be the same. * @memberof Resultset */ Resultset.prototype.copy = function () { var result = new Resultset(this.collection); if (this.filteredrows.length > 0) { result.filteredrows = this.filteredrows.slice(); } result.filterInitialized = this.filterInitialized; return result; }; /** * Alias of copy() * @memberof Resultset */ Resultset.prototype.branch = Resultset.prototype.copy; /** * transform() - executes a named collection transform or raw array of transform steps against the resultset. * * @param transform {(string|array)} - name of collection transform or raw transform array * @param parameters {object=} - (Optional) object property hash of parameters, if the transform requires them. * @returns {Resultset} either (this) resultset or a clone of of this resultset (depending on steps) * @memberof Resultset */ Resultset.prototype.transform = function (transform, parameters) { var idx, step, rs = this; // if transform is name, then do lookup first if (typeof transform === 'string') { if (this.collection.transforms.hasOwnProperty(transform)) { transform = this.collection.transforms[transform]; } } // either they passed in raw transform array or we looked it up, so process if (typeof transform !== 'object' || !Array.isArray(transform)) { throw new Error("Invalid transform"); } if (typeof parameters !== 'undefined') { transform = Utils.resolveTransformParams(transform, parameters); } for (idx = 0; idx < transform.length; idx++) { step = transform[idx]; switch (step.type) { case "find": rs.find(step.value); break; case "where": rs.where(step.value); break; case "simplesort": rs.simplesort(step.property, step.desc); break; case "compoundsort": rs.compoundsort(step.value); break; case "sort": rs.sort(step.value); break; case "limit": rs = rs.limit(step.value); break; // limit makes copy so update reference case "offset": rs = rs.offset(step.value); break; // offset makes copy so update reference case "map": rs = rs.map(step.value); break; case "eqJoin": rs = rs.eqJoin(step.joinData, step.leftJoinKey, step.rightJoinKey, step.mapFun); break; // following cases break chain by returning array data so make any of these last in transform steps case "mapReduce": rs = rs.mapReduce(step.mapFunction, step.reduceFunction); break; // following cases update documents in current filtered resultset (use carefully) case "update": rs.update(step.value); break; case "remove": rs.remove(); break; default: break; } } return rs; }; /** * User supplied compare function is provided two documents to compare. (chainable) * @example * rslt.sort(function(obj1, obj2) { * if (obj1.name === obj2.name) return 0; * if (obj1.name > obj2.name) return 1; * if (obj1.name < obj2.name) return -1; * }); * * @param {function} comparefun - A javascript compare function used for sorting. * @returns {Resultset} Reference to this resultset, sorted, for future chain operations. * @memberof Resultset */ Resultset.prototype.sort = function (comparefun) { // if this is chained resultset with no filters applied, just we need to populate filteredrows first if (this.searchIsChained && !this.filterInitialized && this.filteredrows.length === 0) { this.filteredrows = this.collection.prepareFullDocIndex(); } var wrappedComparer = (function (userComparer, data) { return function (a, b) { return userComparer(data[a], data[b]); }; })(comparefun, this.collection.data); this.filteredrows.sort(wrappedComparer); return this; }; /** * Simpler, loose evaluation for user to sort based on a property name. (chainable). * Sorting based on the same lt/gt helper functions used for binary indices. * * @param {string} propname - name of property to sort by. * @param {bool=} isdesc - (Optional) If true, the property will be sorted in descending order * @returns {Resultset} Reference to this resultset, sorted, for future chain operations. * @memberof Resultset */ Resultset.prototype.simplesort = function (propname, isdesc) { // if this is chained resultset with no filters applied, just we need to populate filteredrows first if (this.searchIsChained && !this.filterInitialized && this.filteredrows.length === 0) { this.filteredrows = this.collection.prepareFullDocIndex(); } if (typeof (isdesc) === 'undefined') { isdesc = false; } var wrappedComparer = (function (prop, desc, data) { return function (a, b) { return sortHelper(data[a][prop], data[b][prop], desc); }; })(propname, isdesc, this.collection.data); this.filteredrows.sort(wrappedComparer); return this; }; /** * Allows sorting a resultset based on multiple columns. * @example * // to sort by age and then name (both ascending) * rs.compoundsort(['age', 'name']); * // to sort by age (ascending) and then by name (descending) * rs.compoundsort(['age', ['name', true]); * * @param {array} properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order * @returns {Resultset} Reference to this resultset, sorted, for future chain operations. * @memberof Resultset */ Resultset.prototype.compoundsort = function (properties) { if (properties.length === 0) { throw new Error("Invalid call to compoundsort, need at least one property"); } var prop; if (properties.length === 1) { prop = properties[0]; if (Array.isArray(prop)) { return this.simplesort(prop[0], prop[1]); } return this.simplesort(prop, false); } // unify the structure of 'properties' to avoid checking it repeatedly while sorting for (var i = 0, len = properties.length; i < len; i += 1) { prop = properties[i]; if (!Array.isArray(prop)) { properties[i] = [prop, false]; } } // if this is chained resultset with no filters applied, just we need to populate filteredrows first if (this.searchIsChained && !this.filterInitialized && this.filteredrows.length === 0) { this.filteredrows = this.collection.prepareFullDocIndex(); } var wrappedComparer = (function (props, data) { return function (a, b) { return compoundeval(props, data[a], data[b]); }; })(properties, this.collection.data); this.filteredrows.sort(wrappedComparer); return this; }; /** * calculateRange() - Binary Search utility method to find range/segment of values matching criteria. * this is used for collection.find() and first find filter of resultset/dynview * slightly different than get() binary search in that get() hones in on 1 value, * but we have to hone in on many (range) * @param {string} op - operation, such as $eq * @param {string} prop - name of property to calculate range for * @param {object} val - value to use for range calculation. * @returns {array} [start, end] index array positions */ Resultset.prototype.calculateRange = function (op, prop, val) { var rcd = this.collection.data; var index = this.collection.binaryIndices[prop].values; var min = 0; var max = index.length - 1; var mid = 0; // when no documents are in collection, return empty range condition if (rcd.length === 0) { return [0, -1]; } var minVal = rcd[index[min]][prop]; var maxVal = rcd[index[max]][prop]; // if value falls outside of our range return [0, -1] to designate no results switch (op) { case '$eq': case '$aeq': if (ltHelper(val, minVal, false) || gtHelper(val, maxVal, false)) { return [0, -1]; } break; case '$dteq': if (ltHelper(val, minVal, false) || gtHelper(val, maxVal, false)) { return [0, -1]; } break; case '$gt': if (gtHelper(val, maxVal, true)) { return [0, -1]; } break; case '$gte': if (gtHelper(val, maxVal, false)) { return [0, -1]; } break; case '$lt': if (ltHelper(val, minVal, true)) { return [0, -1]; } if (ltHelper(maxVal, val, false)) { return [0, rcd.length - 1]; } break; case '$lte': if (ltHelper(val, minVal, false)) { return [0, -1]; } if (ltHelper(maxVal, val, true)) { return [0, rcd.length - 1]; } break; } // hone in on start position of value while (min < max) { mid = (min + max) >> 1; if (ltHelper(rcd[index[mid]][prop], val, false)) { min = mid + 1; } else { max = mid; } } var lbound = min; // do not reset min, as the upper bound cannot be prior to the found low bound max = index.length - 1; // hone in on end position of value while (min < max) { mid = (min + max) >> 1; if (ltHelper(val, rcd[index[mid]][prop], false)) { max = mid; } else { min = mid + 1; } } var ubound = max; var lval = rcd[index[lbound]][prop]; var uval = rcd[index[ubound]][prop]; switch (op) { case '$eq': if (lval !== val) { return [0, -1]; } if (uval !== val) { ubound--; } return [lbound, ubound]; case '$dteq': if (lval > val || lval < val) { return [0, -1]; } if (uval > val || uval < val) { ubound--; } return [lbound, ubound]; case '$gt': if (ltHelper(uval, val, true)) { return [0, -1]; } return [ubound, rcd.length - 1]; case '$gte': if (ltHelper(lval, val, false)) { return [0, -1]; } return [lbound, rcd.length - 1]; case '$lt': if (lbound === 0 && ltHelper(lval, val, false)) { return [0, 0]; } return [0, lbound - 1]; case '$lte': if (uval !== val) { ubound--; } if (ubound === 0 && ltHelper(uval, val, false)) { return [0, 0]; } return [0, ubound]; default: return [0, rcd.length - 1]; } }; /** * findOr() - oversee the operation of OR'ed query expressions. * OR'ed expression evaluation runs each expression individually against the full collection, * and finally does a set OR on each expression's results. * Each evaluation can utilize a binary index to prevent multiple linear array scans. * * @param {array} expressionArray - array of expressions * @returns {Resultset} this resultset for further chain ops. */ Resultset.prototype.findOr = function (expressionArray) { var fr = null, fri = 0, frlen = 0, docset = [], idxset = [], idx = 0, origCount = this.count(); // If filter is already initialized, then we query against only those items already in filter. // This means no index utilization for fields, so hopefully its filtered to a smallish filteredrows. for (var ei = 0, elen = expressionArray.length; ei < elen; ei++) { // we need to branch existing query to run each filter separately and combine results fr = this.branch().find(expressionArray[ei]).filteredrows; frlen = fr.length; // if the find operation did not reduce the initial set, then the initial set is the actual result if (frlen === origCount) { return this; } // add any document 'hits' for (fri = 0; fri < frlen; fri++) { idx = fr[fri]; if (idxset[idx] === undefined) { idxset[idx] = true; docset.push(idx); } } } this.filteredrows = docset; this.filterInitialized = true; return this; }; Resultset.prototype.$or = Resultset.prototype.findOr; /** * findAnd() - oversee the operation of AND'ed query expressions. * AND'ed expression evaluation runs each expression progressively against the full collection, * internally utilizing existing chained resultset functionality. * Only the first filter can utilize a binary index. * * @param {array} expressionArray - array of expressions * @returns {Resultset} this resultset for further chain ops. */ Resultset.prototype.findAnd = function (expressionArray) { // we have already implementing method chaining in this (our Resultset class) // so lets just progressively apply user supplied and filters for (var i = 0, len = expressionArray.length; i < len; i++) { if (this.count() === 0) { return this; } this.find(expressionArray[i]); } return this; }; Resultset.prototype.$and = Resultset.prototype.findAnd; /** * Used for querying via a mongo-style query object. * * @param {object} query - A mongo-style query object used for filtering current results. * @param {boolean=} firstOnly - (Optional) Used by collection.findOne() * @returns {Resultset} this resultset for further chain ops. * @memberof Resultset */ Resultset.prototype.find = function (query, firstOnly) { if (this.collection.data.length === 0) { if (this.searchIsChained) { this.filteredrows = []; this.filterInitialized = true; return this; } return []; } var queryObject = query || 'getAll', p, property, queryObjectOp, operator, value, key, searchByIndex = false, result = [], index = null; // if this was note invoked via findOne() firstOnly = firstOnly || false; if (typeof queryObject === 'object') { for (p in queryObject) { if (hasOwnProperty.call(queryObject, p)) { property = p; queryObjectOp = queryObject[p]; break; } } } // apply no filters if they want all if (!property || queryObject === 'getAll') { // Chained queries can just do coll.chain().data() but let's // be versatile and allow this also coll.chain().find().data() // If a chained search, simply leave everything as-is. // Note: If no filter at this point, it will be properly // created by the follow-up queries or sorts that need it. // If not chained, then return the collection data array copy. return (this.searchIsChained) ? (this) : (this.collection.data.slice()); } // injecting $and and $or expression tree evaluation here. if (property === '$and' || property === '$or') { if (this.searchIsChained) { this[property](queryObjectOp); // for chained find with firstonly, if (firstOnly && this.filteredrows.length > 1) { this.filteredrows = this.filteredrows.slice(0, 1); } return this; } else { // our $and operation internally chains filters result = this.collection.chain()[property](queryObjectOp).data(); // if this was coll.findOne() return first object or empty array if null // since this is invoked from a constructor we can't return null, so we will // make null in coll.findOne(); if (firstOnly) { return (result.length === 0) ? ([]) : (result[0]); } // not first only return all results return result; } } // see if query object is in shorthand mode (assuming eq operator) if (queryObjectOp === null || (typeof queryObjectOp !== 'object' || queryObjectOp instanceof Date)) { operator = '$eq'; value = queryObjectOp; } else if (typeof queryObjectOp === 'object') { for (key in queryObjectOp) { if (hasOwnProperty.call(queryObjectOp, key)) { operator = key; value = queryObjectOp[key]; break; } } } else { throw new Error('Do not know what you want to do.'); } // for regex ops, precompile if (operator === '$regex') { if (Array.isArray(value)) { value = new RegExp(value[0], value[1]); } else if (!(value instanceof RegExp)) { value = new RegExp(value); } } // if user is deep querying the object such as find('name.first': 'odin') var usingDotNotation = (property.indexOf('.') !== -1); // if an index exists for the property being queried against, use it // for now only enabling for non-chained query (who's set of docs matches index) // or chained queries where it is the first filter applied and prop is indexed var doIndexCheck = !usingDotNotation && (!this.searchIsChained || !this.filterInitialized); if (doIndexCheck && this.collection.binaryIndices[property] && indexedOpsList.indexOf(operator) !== -1) { // this is where our lazy index rebuilding will take place // basically we will leave all indexes dirty until we need them // so here we will rebuild only the index tied to this property // ensureIndex() will only rebuild if flagged as dirty since we are not passing force=true param this.collection.ensureIndex(property); searchByIndex = true; index = this.collection.binaryIndices[property]; } // the comparison function var fun = LokiOps[operator]; // "shortcut" for collection data var t = this.collection.data; // filter data length var i = 0; // Query executed differently depending on : // - whether it is chained or not // - whether the property being queried has an index defined // - if chained, we handle first pass differently for initial filteredrows[] population // // For performance reasons, each case has its own if block to minimize in-loop calculations // If not a chained query, bypass filteredrows and work directly against data if (!this.searchIsChained) { if (!searchByIndex) { i = t.length; if (firstOnly) { if (usingDotNotation) { property = property.split('.'); while (i--) { if (dotSubScan(t[i], property, fun, value)) { return (t[i]); } } } else { while (i--) { if (fun(t[i][property], value)) { return (t[i]); } } } return []; } // if using dot notation then treat property as keypath such as 'name.first'. // currently supporting dot notation for non-indexed conditions only if (usingDotNotation) { property = property.split('.'); while (i--) { if (dotSubScan(t[i], property, fun, value)) { result.push(t[i]); } } } else { while (i--) { if (fun(t[i][property], value)) { result.push(t[i]); } } } } else { // searching by binary index via calculateRange() utility method var seg = this.calculateRange(operator, property, value); // not chained so this 'find' was designated in Resultset constructor // so return object itself if (firstOnly) { if (seg[1] !== -1) { return t[index.values[seg[0]]]; } return []; } for (i = seg[0]; i <= seg[1]; i++) { result.push(t[index.values[i]]); } } // not a chained query so return result as data[] return result; } // Otherwise this is a chained query var filter, rowIdx = 0; // If the filteredrows[] is already initialized, use it if (this.filterInitialized) { filter = this.filteredrows; i = filter.length; // currently supporting dot notation for non-indexed conditions only if (usingDotNotation) { property = property.split('.'); while (i--) { rowIdx = filter[i]; if (dotSubScan(t[rowIdx], property, fun, value)) { result.push(rowIdx); } } } else { while (i--) { rowIdx = filter[i]; if (fun(t[rowIdx][property], value)) { result.push(rowIdx); } } } } // first chained query so work against data[] but put results in filteredrows else { // if not searching by index if (!searchByIndex) { i = t.length; if (usingDotNotation) { property = property.split('.'); while (i--) { if (dotSubScan(t[i], property, fun, value)) { result.push(i); } } } else { while (i--) { if (fun(t[i][property], value)) { result.push(i); } } } } else { // search by index var segm = this.calculateRange(operator, property, value); for (i = segm[0]; i <= segm[1]; i++) { result.push(index.values[i]); } } this.filterInitialized = true; // next time work against filteredrows[] } this.filteredrows = result; return this; }; /** * where() - Used for filtering via a javascript filter function. * * @param {function} fun - A javascript function used for filtering current results by. * @returns {Resultset} this resultset for further chain ops. * @memberof Resultset */ Resultset.prototype.where = function (fun) { var viewFunction, result = []; if ('function' === typeof fun) { viewFunction = fun; } else { throw new TypeError('Argument is not a stored view or a function'); } try { // if not a chained query then run directly against data[] and return object [] if (!this.searchIsChained) { var i = this.collection.data.length; while (i--) { if (viewFunction(this.collection.data[i]) === true) { result.push(this.collection.data[i]); } } // not a chained query so returning result as data[] return result; } // else chained query, so run against filteredrows else { // If the filteredrows[] is already initialized, use it if (this.filterInitialized) { var j = this.filteredrows.length; while (j--) { if (viewFunction(this.collection.data[this.filteredrows[j]]) === true) { result.push(this.filteredrows[j]); } } this.filteredrows = result; return this; } // otherwise this is initial chained op, work against data, push into filteredrows[] else { var k = this.collection.data.length; while (k--) { if (viewFunction(this.collection.data[k]) === true) { result.push(k); } } this.filteredrows = result; this.filterInitialized = true; return this; } } } catch (err) { throw err; } }; /** * count() - returns the number of documents in the resultset. * * @returns {number} The number of documents in the resultset. * @memberof Resultset */ Resultset.prototype.count = function () { if (this.searchIsChained && this.filterInitialized) { return this.filteredrows.length; } return this.collection.count(); }; /** * Terminates the chain and returns array of filtered documents * * @param {object=} options - allows specifying 'forceClones' and 'forceCloneMethod' options. * @param {boolean} options.forceClones - Allows forcing the return of cloned objects even when * the collection is not configured for clone object. * @param {string} options.forceCloneMethod - Allows overriding the default or collection specified cloning method. * Possible values include 'parse-stringify', 'jquery-extend-deep', and 'shallow' * * @returns {array} Array of documents in the resultset * @memberof Resultset */ Resultset.prototype.data = function (options) { var result = [], data = this.collection.data, len, i, method; options = options || {}; // if this is chained resultset with no filters applied, just return collection.data if (this.searchIsChained && !this.filterInitialized) { if (this.filteredrows.length === 0) { // determine whether we need to clone objects or not if (this.collection.cloneObjects || options.forceClones) { len = data.length; method = options.forceCloneMethod || this.collection.cloneMethod; for (i = 0; i < len; i++) { result.push(clone(data[i], method)); } return result; } // otherwise we are not cloning so return sliced array with same object references else { return data.slice(); } } else { // filteredrows must have been set manually, so use it this.filterInitialized = true; } } var fr = this.filteredrows; len = fr.length; if (this.collection.cloneObjects || options.forceClones) { method = options.forceCloneMethod || this.collection.cloneMethod; for (i = 0; i < len; i++) { result.push(clone(data[fr[i]], method)); } } else { for (i = 0; i < len; i++) { result.push(data[fr[i]]); } } return result; }; /** * Used to run an update operation on all documents currently in the resultset. * * @param {function} updateFunction - User supplied updateFunction(obj) will be executed for each document object. * @returns {Resultset} this resultset for further chain ops. * @memberof Resultset */ Resultset.prototype.update = function (updateFunction) { if (typeof (updateFunction) !== "function") { throw new TypeError('Argument is not a function'); } // if this is chained resultset with no filters applied, we need to populate filteredrows first if (this.searchIsChained && !this.filterInitialized && this.filteredrows.length === 0) { this.filteredrows = this.collection.prepareFullDocIndex(); } var len = this.filteredrows.length, rcd = this.collection.data; for (var idx = 0; idx < len; idx++) { // pass in each document object currently in resultset to user supplied updateFunction updateFunction(rcd[this.filteredrows[idx]]); // notify collection we have changed this object so it can update meta and allow DynamicViews to re-evaluate this.collection.update(rcd[this.filteredrows[idx]]); } return this; }; /** * Removes all document objects which are currently in resultset from collection (as well as resultset) * * @returns {Resultset} this (empty) resultset for further chain ops. * @memberof Resultset */ Resultset.prototype.remove = function () { // if this is chained resultset with no filters applied, we need to populate filteredrows first if (this.searchIsChained && !this.filterInitialized && this.filteredrows.length === 0) { this.filteredrows = this.collection.prepareFullDocIndex(); } this.collection.remove(this.data()); this.filteredrows = []; return this; }; /** * data transformation via user supplied functions * * @param {function} mapFunction - this function accepts a single document for you to transform and return * @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value * @returns {value} The output of your reduceFunction * @memberof Resultset */ Resultset.prototype.mapReduce = function (mapFunction, reduceFunction) { try { return reduceFunction(this.data().map(mapFunction)); } catch (err) { throw err; } }; /** * eqJoin() - Left joining two sets of data. Join keys can be defined or calculated properties * eqJoin expects the right join key values to be unique. Otherwise left data will be joined on the last joinData object with that key * @param {Array} joinData - Data array to join to. * @param {(string|function)} leftJoinKey - Property name in this result set to join on or a function to produce a value to join on * @param {(string|function)} rightJoinKey - Property name in the joinData to join on or a function to produce a value to join on * @param {function=} mapFun - (Optional) A function that receives each matching pair and maps them into output objects - function(left,right){return joinedObject} * @returns {Resultset} A resultset with data in the format [{left: leftObj, right: rightObj}] * @memberof Resultset */ Resultset.prototype.eqJoin = function (joinData, leftJoinKey, rightJoinKey, mapFun) { var leftData = [], leftDataLength, rightData = [], rightDataLength, key, result = [], leftKeyisFunction = typeof leftJoinKey === 'function', rightKeyisFunction = typeof rightJoinKey === 'function', joinMap = {}; //get the left data leftData = this.data(); leftDataLength = leftData.length; //get the right data if (joinData instanceof Resultset) { rightData = joinData.data(); } else if (Array.isArray(joinData)) { rightData = joinData; } else { throw new TypeError('joinData needs to be an array or result set'); } rightDataLength = rightData.length; //construct a lookup table for (var i = 0; i < rightDataLength; i++) { key = rightKeyisFunction ? rightJoinKey(rightData[i]) : rightData[i][rightJoinKey]; joinMap[key] = rightData[i]; } if (!mapFun) { mapFun = function (left, right) { return { left: left, right: right }; }; } //Run map function over each object in the resultset for (var j = 0; j < leftDataLength; j++) { key = leftKeyisFunction ? leftJoinKey(leftData[j]) : leftData[j][leftJoinKey]; result.push(mapFun(leftData[j], joinMap[key] || {})); } //return return a new resultset with no filters this.collection = new Collection('joinData'); this.collection.insert(result); this.filteredrows = []; this.filterInitialized = false; return this; }; Resultset.prototype.map = function (mapFun) { var data = this.data().map(mapFun); //return return a new resultset with no filters this.collection = new Collection('mappedData'); this.collection.insert(data); this.filteredrows = []; this.filterInitialized = false; return this; }; /** * DynamicView class is a versatile 'live' view class which can have filters and sorts applied. * Collection.addDynamicView(name) instantiates this DynamicView object and notifies it * whenever documents are add/updated/removed so it can remain up-to-date. (chainable) * * @example * var mydv = mycollection.addDynamicView('test'); // default is non-persistent * mydv.applyFind({ 'doors' : 4 }); * mydv.applyWhere(function(obj) { return obj.name === 'Toyota'; }); * var results = mydv.data(); * * @constructor DynamicView * @implements LokiEventEmitter * @param {Collection} collection - A reference to the collection to work against * @param {string} name - The name of this dynamic view * @param {object=} options - (Optional) Pass in object with 'persistent' and/or 'sortPriority' options. * @param {boolean} options.persistent - indicates if view is to main internal results array in 'resultdata' * @param {string} options.sortPriority - 'passive' (sorts performed on call to data) or 'active' (after updates) * @param {number} options.minRebuildInterval - minimum rebuild interval (need clarification to docs here) * @see {@link Collection#addDynamicView} to construct instances of DynamicView */ function DynamicView(collection, name, options) { this.collection = collection; this.name = name; this.rebuildPending = false; this.options = options || {}; if (!this.options.hasOwnProperty('persistent')) { this.options.persistent = false; } // 'persistentSortPriority': // 'passive' will defer the sort phase until they call data(). (most efficient overall) // 'active' will sort async whenever next idle. (prioritizes read speeds) if (!this.options.hasOwnProperty('sortPriority')) { this.options.sortPriority = 'passive'; } if (!this.options.hasOwnProperty('minRebuildInterval')) { this.options.minRebuildInterval = 1; } this.resultset = new Resultset(collection); this.resultdata = []; this.resultsdirty = false; this.cachedresultset = null; // keep ordered filter pipeline this.filterPipeline = []; // sorting member variables // we only support one active search, applied using applySort() or applySimpleSort() this.sortFunction = null; this.sortCriteria = null; this.sortDirty = false; // for now just have 1 event for when we finally rebuilt lazy view // once we refactor transactions, i will tie in certain transactional events this.events = { 'rebuild': [] }; } DynamicView.prototype = new LokiEventEmitter(); /** * rematerialize() - intended for use immediately after deserialization (loading) * This will clear out and reapply filterPipeline ops, recreating the view. * Since where filters do not persist correctly, this method allows * restoring the view to state where user can re-apply those where filters. * * @param {Object=} options - (Optional) allows specification of 'removeWhereFilters' option * @returns {DynamicView} This dynamic view for further chained ops. * @memberof DynamicView * @fires DynamicView.rebuild */ DynamicView.prototype.rematerialize = function (options) { var fpl, fpi, idx; options = options || {}; this.resultdata = []; this.resultsdirty = true; this.resultset = new Resultset(this.collection); if (this.sortFunction || this.sortCriteria) { this.sortDirty = true; } if (options.hasOwnProperty('removeWhereFilters')) { // for each view see if it had any where filters applied... since they don't // serialize those functions lets remove those invalid filters fpl = this.filterPipeline.length; fpi = fpl; while (fpi--) { if (this.filterPipeline[fpi].type === 'where') { if (fpi !== this.filterPipeline.length - 1) { this.filterPipeline[fpi] = this.filterPipeline[this.filterPipeline.length - 1]; } this.filterPipeline.length--; } } } // back up old filter pipeline, clear filter pipeline, and reapply pipeline ops var ofp = this.filterPipeline; this.filterPipeline = []; // now re-apply 'find' filterPipeline ops fpl = ofp.length; for (idx = 0; idx < fpl; idx++) { this.applyFind(ofp[idx].val); } // during creation of unit tests, i will remove this forced refresh and leave lazy this.data(); // emit rebuild event in case user wants to be notified this.emit('rebuild', this); return this; }; /** * branchResultset() - Makes a copy of the internal resultset for branched queries. * Unlike this dynamic view, the branched resultset will not be 'live' updated, * so your branched query should be immediately resolved and not held for future evaluation. * * @param {(string|array=)} transform - Optional name of collection transform, or an array of transform steps * @param {object=} parameters - optional parameters (if optional transform requires them) * @returns {Resultset} A copy of the internal resultset for branched queries. * @memberof DynamicView */ DynamicView.prototype.branchResultset = function (transform, parameters) { var rs = this.resultset.branch(); if (typeof transform === 'undefined') { return rs; } return rs.transform(transform, parameters); }; /** * toJSON() - Override of toJSON to avoid circular references * */ DynamicView.prototype.toJSON = function () { var copy = new DynamicView(this.collection, this.name, this.options); copy.resultset = this.resultset; copy.resultdata = []; // let's not save data (copy) to minimize size copy.resultsdirty = true; copy.filterPipeline = this.filterPipeline; copy.sortFunction = this.sortFunction; copy.sortCriteria = this.sortCriteria; copy.sortDirty = this.sortDirty; // avoid circular reference, reapply in db.loadJSON() copy.collection = null; return copy; }; /** * removeFilters() - Used to clear pipeline and reset dynamic view to initial state. * Existing options should be retained. * @memberof DynamicView */ DynamicView.prototype.removeFilters = function () { this.rebuildPending = false; this.resultset.reset(); this.resultdata = []; this.resultsdirty = false; this.cachedresultset = null; // keep ordered filter pipeline this.filterPipeline = []; // sorting member variables // we only support one active search, applied using applySort() or applySimpleSort() this.sortFunction = null; this.sortCriteria = null; this.sortDirty = false; }; /** * applySort() - Used to apply a sort to the dynamic view * @example * dv.applySort(function(obj1, obj2) { * if (obj1.name === obj2.name) return 0; * if (obj1.name > obj2.name) return 1; * if (obj1.name < obj2.name) return -1; * }); * * @param {function} comparefun - a javascript compare function used for sorting * @returns {DynamicView} this DynamicView object, for further chain ops. * @memberof DynamicView */ DynamicView.prototype.applySort = function (comparefun) { this.sortFunction = comparefun; this.sortCriteria = null; this.queueSortPhase(); return this; }; /** * applySimpleSort() - Used to specify a property used for view translation. * @example * dv.applySimpleSort("name"); * * @param {string} propname - Name of property by which to sort. * @param {boolean=} isdesc - (Optional) If true, the sort will be in descending order. * @returns {DynamicView} this DynamicView object, for further chain ops. * @memberof DynamicView */ DynamicView.prototype.applySimpleSort = function (propname, isdesc) { this.sortCriteria = [ [propname, isdesc || false] ]; this.sortFunction = null; this.queueSortPhase(); return this; }; /** * applySortCriteria() - Allows sorting a resultset based on multiple columns. * @example * // to sort by age and then name (both ascending) * dv.applySortCriteria(['age', 'name']); * // to sort by age (ascending) and then by name (descending) * dv.applySortCriteria(['age', ['name', true]); * // to sort by age (descending) and then by name (descending) * dv.applySortCriteria(['age', true], ['name', true]); * * @param {array} properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order * @returns {DynamicView} Reference to this DynamicView, sorted, for future chain operations. * @memberof DynamicView */ DynamicView.prototype.applySortCriteria = function (criteria) { this.sortCriteria = criteria; this.sortFunction = null; this.queueSortPhase(); return this; }; /** * startTransaction() - marks the beginning of a transaction. * * @returns {DynamicView} this DynamicView object, for further chain ops. */ DynamicView.prototype.startTransaction = function () { this.cachedresultset = this.resultset.copy(); return this; }; /** * commit() - commits a transaction. * * @returns {DynamicView} this DynamicView object, for further chain ops. */ DynamicView.prototype.commit = function () { this.cachedresultset = null; return this; }; /** * rollback() - rolls back a transaction. * * @returns {DynamicView} this DynamicView object, for further chain ops. */ DynamicView.prototype.rollback = function () { this.resultset = this.cachedresultset; if (this.options.persistent) { // for now just rebuild the persistent dynamic view data in this worst case scenario // (a persistent view utilizing transactions which get rolled back), we already know the filter so not too bad. this.resultdata = this.resultset.data(); this.emit('rebuild', this); } return this; }; /** * Implementation detail. * _indexOfFilterWithId() - Find the index of a filter in the pipeline, by that filter's ID. * * @param {(string|number)} uid - The unique ID of the filter. * @returns {number}: index of the referenced filter in the pipeline; -1 if not found. */ DynamicView.prototype._indexOfFilterWithId = function (uid) { if (typeof uid === 'string' || typeof uid === 'number') { for (var idx = 0, len = this.filterPipeline.length; idx < len; idx += 1) { if (uid === this.filterPipeline[idx].uid) { return idx; } } } return -1; }; /** * Implementation detail. * _addFilter() - Add the filter object to the end of view's filter pipeline and apply the filter to the resultset. * * @param {object} filter - The filter object. Refer to applyFilter() for extra details. */ DynamicView.prototype._addFilter = function (filter) { this.filterPipeline.push(filter); this.resultset[filter.type](filter.val); }; /** * reapplyFilters() - Reapply all the filters in the current pipeline. * * @returns {DynamicView} this DynamicView object, for further chain ops. */ DynamicView.prototype.reapplyFilters = function () { this.resultset.reset(); this.cachedresultset = null; if (this.options.persistent) { this.resultdata = []; this.resultsdirty = true; } var filters = this.filterPipeline; this.filterPipeline = []; for (var idx = 0, len = filters.length; idx < len; idx += 1) { this._addFilter(filters[idx]); } if (this.sortFunction || this.sortCriteria) { this.queueSortPhase(); } else { this.queueRebuildEvent(); } return this; }; /** * applyFilter() - Adds or updates a filter in the DynamicView filter pipeline * * @param {object} filter - A filter object to add to the pipeline. * The object is in the format { 'type': filter_type, 'val', filter_param, 'uid', optional_filter_id } * @returns {DynamicView} this DynamicView object, for further chain ops. * @memberof DynamicView */ DynamicView.prototype.applyFilter = function (filter) { var idx = this._indexOfFilterWithId(filter.uid); if (idx >= 0) { this.filterPipeline[idx] = filter; return this.reapplyFilters(); } this.cachedresultset = null; if (this.options.persistent) { this.resultdata = []; this.resultsdirty = true; } this._addFilter(filter); if (this.sortFunction || this.sortCriteria) { this.queueSortPhase(); } else { this.queueRebuildEvent(); } return this; }; /** * applyFind() - Adds or updates a mongo-style query option in the DynamicView filter pipeline * * @param {object} query - A mongo-style query object to apply to pipeline * @param {(string|number)=} uid - Optional: The unique ID of this filter, to reference it in the future. * @returns {DynamicView} this DynamicView object, for further chain ops. * @memberof DynamicView */ DynamicView.prototype.applyFind = function (query, uid) { this.applyFilter({ type: 'find', val: query, uid: uid }); return this; }; /** * applyWhere() - Adds or updates a javascript filter function in the DynamicView filter pipeline * * @param {function} fun - A javascript filter function to apply to pipeline * @param {(string|number)=} uid - Optional: The unique ID of this filter, to reference it in the future. * @returns {DynamicView} this DynamicView object, for further chain ops. * @memberof DynamicView */ DynamicView.prototype.applyWhere = function (fun, uid) { this.applyFilter({ type: 'where', val: fun, uid: uid }); return this; }; /** * removeFilter() - Remove the specified filter from the DynamicView filter pipeline * * @param {(string|number)} uid - The unique ID of the filter to be removed. * @returns {DynamicView} this DynamicView object, for further chain ops. * @memberof DynamicView */ DynamicView.prototype.removeFilter = function (uid) { var idx = this._indexOfFilterWithId(uid); if (idx < 0) { throw new Error("Dynamic view does not contain a filter with ID: " + uid); } this.filterPipeline.splice(idx, 1); this.reapplyFilters(); return this; }; /** * count() - returns the number of documents representing the current DynamicView contents. * * @returns {number} The number of documents representing the current DynamicView contents. * @memberof DynamicView */ DynamicView.prototype.count = function () { if (this.options.persistent) { return this.resultdata.length; } return this.resultset.count(); }; /** * data() - resolves and pending filtering and sorting, then returns document array as result. * * @returns {array} An array of documents representing the current DynamicView contents. * @memberof DynamicView */ DynamicView.prototype.data = function () { // using final sort phase as 'catch all' for a few use cases which require full rebuild if (this.sortDirty || this.resultsdirty) { this.performSortPhase({ suppressRebuildEvent: true }); } return (this.options.persistent) ? (this.resultdata) : (this.resultset.data()); }; /** * queueRebuildEvent() - When the view is not sorted we may still wish to be notified of rebuild events. * This event will throttle and queue a single rebuild event when batches of updates affect the view. */ DynamicView.prototype.queueRebuildEvent = function () { if (this.rebuildPending) { return; } this.rebuildPending = true; var self = this; setTimeout(function () { if (self.rebuildPending) { self.rebuildPending = false; self.emit('rebuild', self); } }, this.options.minRebuildInterval); }; /** * queueSortPhase : If the view is sorted we will throttle sorting to either : * (1) passive - when the user calls data(), or * (2) active - once they stop updating and yield js thread control */ DynamicView.prototype.queueSortPhase = function () { // already queued? exit without queuing again if (this.sortDirty) { return; } this.sortDirty = true; var self = this; if (this.options.sortPriority === "active") { // active sorting... once they are done and yield js thread, run async performSortPhase() setTimeout(function () { self.performSortPhase(); }, this.options.minRebuildInterval); } else { // must be passive sorting... since not calling performSortPhase (until data call), lets use queueRebuildEvent to // potentially notify user that data has changed. this.queueRebuildEvent(); } }; /** * performSortPhase() - invoked synchronously or asynchronously to perform final sort phase (if needed) * */ DynamicView.prototype.performSortPhase = function (options) { // async call to this may have been pre-empted by synchronous call to data before async could fire if (!this.sortDirty && !this.resultsdirty) { return; } options = options || {}; if (this.sortDirty) { if (this.sortFunction) { this.resultset.sort(this.sortFunction); } else if (this.sortCriteria) { this.resultset.compoundsort(this.sortCriteria); } this.sortDirty = false; } if (this.options.persistent) { // persistent view, rebuild local resultdata array this.resultdata = this.resultset.data(); this.resultsdirty = false; } if (!options.suppressRebuildEvent) { this.emit('rebuild', this); } }; /** * evaluateDocument() - internal method for (re)evaluating document inclusion. * Called by : collection.insert() and collection.update(). * * @param {int} objIndex - index of document to (re)run through filter pipeline. * @param {bool} isNew - true if the document was just added to the collection. */ DynamicView.prototype.evaluateDocument = function (objIndex, isNew) { // if no filter applied yet, the result 'set' should remain 'everything' if (!this.resultset.filterInitialized) { if (this.options.persistent) { this.resultdata = this.resultset.data(); } // need to re-sort to sort new document if (this.sortFunction || this.sortCriteria) { this.queueSortPhase(); } else { this.queueRebuildEvent(); } return; } var ofr = this.resultset.filteredrows; var oldPos = (isNew) ? (-1) : (ofr.indexOf(+objIndex)); var oldlen = ofr.length; // creating a 1-element resultset to run filter chain ops on to see if that doc passes filters; // mostly efficient algorithm, slight stack overhead price (this function is called on inserts and updates) var evalResultset = new Resultset(this.collection); evalResultset.filteredrows = [objIndex]; evalResultset.filterInitialized = true; var filter; for (var idx = 0, len = this.filterPipeline.length; idx < len; idx++) { filter = this.filterPipeline[idx]; evalResultset[filter.type](filter.val); } // not a true position, but -1 if not pass our filter(s), 0 if passed filter(s) var newPos = (evalResultset.filteredrows.length === 0) ? -1 : 0; // wasn't in old, shouldn't be now... do nothing if (oldPos === -1 && newPos === -1) return; // wasn't in resultset, should be now... add if (oldPos === -1 && newPos !== -1) { ofr.push(objIndex); if (this.options.persistent) { this.resultdata.push(this.collection.data[objIndex]); } // need to re-sort to sort new document if (this.sortFunction || this.sortCriteria) { this.queueSortPhase(); } else { this.queueRebuildEvent(); } return; } // was in resultset, shouldn't be now... delete if (oldPos !== -1 && newPos === -1) { if (oldPos < oldlen - 1) { // http://dvolvr.davidwaterston.com/2013/06/09/restating-the-obvious-the-fastest-way-to-truncate-an-array-in-javascript/comment-page-1/ ofr[oldPos] = ofr[oldlen - 1]; ofr.length = oldlen - 1; if (this.options.persistent) { this.resultdata[oldPos] = this.resultdata[oldlen - 1]; this.resultdata.length = oldlen - 1; } } else { ofr.length = oldlen - 1; if (this.options.persistent) { this.resultdata.length = oldlen - 1; } } // in case changes to data altered a sort column if (this.sortFunction || this.sortCriteria) { this.queueSortPhase(); } else { this.queueRebuildEvent(); } return; } // was in resultset, should still be now... (update persistent only?) if (oldPos !== -1 && newPos !== -1) { if (this.options.persistent) { // in case document changed, replace persistent view data with the latest collection.data document this.resultdata[oldPos] = this.collection.data[objIndex]; } // in case changes to data altered a sort column if (this.sortFunction || this.sortCriteria) { this.queueSortPhase(); } else { this.queueRebuildEvent(); } return; } }; /** * removeDocument() - internal function called on collection.delete() */ DynamicView.prototype.removeDocument = function (objIndex) { // if no filter applied yet, the result 'set' should remain 'everything' if (!this.resultset.filterInitialized) { if (this.options.persistent) { this.resultdata = this.resultset.data(); } // in case changes to data altered a sort column if (this.sortFunction || this.sortCriteria) { this.queueSortPhase(); } else { this.queueRebuildEvent(); } return; } var ofr = this.resultset.filteredrows; var oldPos = ofr.indexOf(+objIndex); var oldlen = ofr.length; var idx; if (oldPos !== -1) { // if not last row in resultdata, swap last to hole and truncate last row if (oldPos < oldlen - 1) { ofr[oldPos] = ofr[oldlen - 1]; ofr.length = oldlen - 1; if (this.options.persistent) { this.resultdata[oldPos] = this.resultdata[oldlen - 1]; this.resultdata.length = oldlen - 1; } } // last row, so just truncate last row else { ofr.length = oldlen - 1; if (this.options.persistent) { this.resultdata.length = oldlen - 1; } } // in case changes to data altered a sort column if (this.sortFunction || this.sortCriteria) { this.queueSortPhase(); } else { this.queueRebuildEvent(); } } // since we are using filteredrows to store data array positions // if they remove a document (whether in our view or not), // we need to adjust array positions -1 for all document array references after that position oldlen = ofr.length; for (idx = 0; idx < oldlen; idx++) { if (ofr[idx] > objIndex) { ofr[idx]--; } } }; /** * mapReduce() - data transformation via user supplied functions * * @param {function} mapFunction - this function accepts a single document for you to transform and return * @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value * @returns The output of your reduceFunction * @memberof DynamicView */ DynamicView.prototype.mapReduce = function (mapFunction, reduceFunction) { try { return reduceFunction(this.data().map(mapFunction)); } catch (err) { throw err; } }; /** * Collection class that handles documents of same type * @constructor Collection * @implements LokiEventEmitter * @param {string} name - collection name * @param {(array|object)=} options - (optional) array of property names to be indicized OR a configuration object * @param {array} options.unique - array of property names to define unique constraints for * @param {array} options.exact - array of property names to define exact constraints for * @param {array} options.indices - array property names to define binary indexes for * @param {boolean} options.asyncListeners - default is false * @param {boolean} options.disableChangesApi - default is true * @param {boolean} options.autoupdate - use Object.observe to update objects automatically (default: false) * @param {boolean} options.clone - specify whether inserts and queries clone to/from user * @param {string} options.cloneMethod - 'parse-stringify' (default), 'jquery-extend-deep', 'shallow' * @param {int} options.ttlInterval - time interval for clearing out 'aged' documents; not set by default. * @see {@link Loki#addCollection} for normal creation of collections */ function Collection(name, options) { // the name of the collection this.name = name; // the data held by the collection this.data = []; this.idIndex = []; // index of id this.binaryIndices = {}; // user defined indexes this.constraints = { unique: {}, exact: {} }; // unique contraints contain duplicate object references, so they are not persisted. // we will keep track of properties which have unique contraint applied here, and regenerate on load this.uniqueNames = []; // transforms will be used to store frequently used query chains as a series of steps // which itself can be stored along with the database. this.transforms = {}; // the object type of the collection this.objType = name; // in autosave scenarios we will use collection level dirty flags to determine whether save is needed. // currently, if any collection is dirty we will autosave the whole database if autosave is configured. // defaulting to true since this is called from addCollection and adding a collection should trigger save this.dirty = true; // private holders for cached data this.cachedIndex = null; this.cachedBinaryIndex = null; this.cachedData = null; var self = this; /* OPTIONS */ options = options || {}; // exact match and unique constraints if (options.hasOwnProperty('unique')) { if (!Array.isArray(options.unique)) { options.unique = [options.unique]; } options.unique.forEach(function (prop) { self.uniqueNames.push(prop); // used to regenerate on subsequent database loads self.constraints.unique[prop] = new UniqueIndex(prop); }); } if (options.hasOwnProperty('exact')) { options.exact.forEach(function (prop) { self.constraints.exact[prop] = new ExactIndex(prop); }); } // is collection transactional this.transactional = options.hasOwnProperty('transactional') ? options.transactional : false; // options to clone objects when inserting them this.cloneObjects = options.hasOwnProperty('clone') ? options.clone : false; // default clone method (if enabled) is parse-stringify this.cloneMethod = options.hasOwnProperty('cloneMethod') ? options.cloneMethod : "parse-stringify"; // option to make event listeners async, default is sync this.asyncListeners = options.hasOwnProperty('asyncListeners') ? options.asyncListeners : false; // disable track changes this.disableChangesApi = options.hasOwnProperty('disableChangesApi') ? options.disableChangesApi : true; // option to observe objects and update them automatically, ignored if Object.observe is not supported this.autoupdate = options.hasOwnProperty('autoupdate') ? options.autoupdate : false; //option to activate a cleaner daemon - clears "aged" documents at set intervals. this.ttl = { age: null, ttlInterval: null, daemon: null }; this.setTTL(options.ttl || -1, options.ttlInterval); // currentMaxId - change manually at your own peril! this.maxId = 0; this.DynamicViews = []; // events this.events = { 'insert': [], 'update': [], 'pre-insert': [], 'pre-update': [], 'close': [], 'flushbuffer': [], 'error': [], 'delete': [], 'warning': [] }; // changes are tracked by collection and aggregated by the db this.changes = []; // initialize the id index this.ensureId(); var indices = []; // initialize optional user-supplied indices array ['age', 'lname', 'zip'] if (options && options.indices) { if (Object.prototype.toString.call(options.indices) === '[object Array]') { indices = options.indices; } else if (typeof options.indices === 'string') { indices = [options.indices]; } else { throw new TypeError('Indices needs to be a string or an array of strings'); } } for (var idx = 0; idx < indices.length; idx++) { this.ensureIndex(indices[idx]); } function observerCallback(changes) { var changedObjects = typeof Set === 'function' ? new Set() : []; if (!changedObjects.add) changedObjects.add = function (object) { if (this.indexOf(object) === -1) this.push(object); return this; }; changes.forEach(function (change) { changedObjects.add(change.object); }); changedObjects.forEach(function (object) { if (!hasOwnProperty.call(object, '$loki')) return self.removeAutoUpdateObserver(object); try { self.update(object); } catch (err) {} }); } this.observerCallback = observerCallback; /* * This method creates a clone of the current status of an object and associates operation and collection name, * so the parent db can aggregate and generate a changes object for the entire db */ function createChange(name, op, obj) { self.changes.push({ name: name, operation: op, obj: JSON.parse(JSON.stringify(obj)) }); } // clear all the changes function flushChanges() { self.changes = []; } this.getChanges = function () { return self.changes; }; this.flushChanges = flushChanges; /** * If the changes API is disabled make sure only metadata is added without re-evaluating everytime if the changesApi is enabled */ function insertMeta(obj) { if (!obj) { return; } if (!obj.meta) { obj.meta = {}; } obj.meta.created = (new Date()).getTime(); obj.meta.revision = 0; } function updateMeta(obj) { if (!obj) { return; } obj.meta.updated = (new Date()).getTime(); obj.meta.revision += 1; } function createInsertChange(obj) { createChange(self.name, 'I', obj); } function createUpdateChange(obj) { createChange(self.name, 'U', obj); } function insertMetaWithChange(obj) { insertMeta(obj); createInsertChange(obj); } function updateMetaWithChange(obj) { updateMeta(obj); createUpdateChange(obj); } /* assign correct handler based on ChangesAPI flag */ var insertHandler, updateHandler; function setHandlers() { insertHandler = self.disableChangesApi ? insertMeta : insertMetaWithChange; updateHandler = self.disableChangesApi ? updateMeta : updateMetaWithChange; } setHandlers(); this.setChangesApi = function (enabled) { self.disableChangesApi = !enabled; setHandlers(); }; /** * built-in events */ this.on('insert', function insertCallback(obj) { insertHandler(obj); }); this.on('update', function updateCallback(obj) { updateHandler(obj); }); this.on('delete', function deleteCallback(obj) { if (!self.disableChangesApi) { createChange(self.name, 'R', obj); } }); this.on('warning', function (warning) { self.console.warn(warning); }); // for de-serialization purposes flushChanges(); } Collection.prototype = new LokiEventEmitter(); Collection.prototype.console = { log: function () {}, warn: function () {}, error: function () {}, }; Collection.prototype.addAutoUpdateObserver = function (object) { if (!this.autoupdate || typeof Object.observe !== 'function') return; Object.observe(object, this.observerCallback, ['add', 'update', 'delete', 'reconfigure', 'setPrototype']); }; Collection.prototype.removeAutoUpdateObserver = function (object) { if (!this.autoupdate || typeof Object.observe !== 'function') return; Object.unobserve(object, this.observerCallback); }; /** * Adds a named collection transform to the collection * @param {string} name - name to associate with transform * @param {array} transform - an array of transformation 'step' objects to save into the collection * @memberof Collection */ Collection.prototype.addTransform = function (name, transform) { if (this.transforms.hasOwnProperty(name)) { throw new Error("a transform by that name already exists"); } this.transforms[name] = transform; }; /** * Updates a named collection transform to the collection * @param {string} name - name to associate with transform * @param {object} transform - a transformation object to save into collection * @memberof Collection */ Collection.prototype.setTransform = function (name, transform) { this.transforms[name] = transform; }; /** * Removes a named collection transform from the collection * @param {string} name - name of collection transform to remove * @memberof Collection */ Collection.prototype.removeTransform = function (name) { delete this.transforms[name]; }; Collection.prototype.byExample = function (template) { var k, obj, query; query = []; for (k in template) { if (!template.hasOwnProperty(k)) continue; query.push(( obj = {}, obj[k] = template[k], obj )); } return { '$and': query }; }; Collection.prototype.findObject = function (template) { return this.findOne(this.byExample(template)); }; Collection.prototype.findObjects = function (template) { return this.find(this.byExample(template)); }; /*----------------------------+ | TTL daemon | +----------------------------*/ Collection.prototype.ttlDaemonFuncGen = function () { var collection = this; var age = this.ttl.age; return function ttlDaemon() { var now = Date.now(); var toRemove = collection.chain().where(function daemonFilter(member) { var timestamp = member.meta.updated || member.meta.created; var diff = now - timestamp; return age < diff; }); toRemove.remove(); }; }; Collection.prototype.setTTL = function (age, interval) { if (age < 0) { clearInterval(this.ttl.daemon); } else { this.ttl.age = age; this.ttl.ttlInterval = interval; this.ttl.daemon = setInterval(this.ttlDaemonFuncGen(), interval); } }; /*----------------------------+ | INDEXING | +----------------------------*/ /** * create a row filter that covers all documents in the collection */ Collection.prototype.prepareFullDocIndex = function () { var len = this.data.length; var indexes = new Array(len); for (var i = 0; i < len; i += 1) { indexes[i] = i; } return indexes; }; /** * Ensure binary index on a certain field * @param {string} property - name of property to create binary index on * @param {boolean=} force - (Optional) flag indicating whether to construct index immediately * @memberof Collection */ Collection.prototype.ensureIndex = function (property, force) { // optional parameter to force rebuild whether flagged as dirty or not if (typeof (force) === 'undefined') { force = false; } if (property === null || property === undefined) { throw new Error('Attempting to set index without an associated property'); } if (this.binaryIndices[property] && !force) { if (!this.binaryIndices[property].dirty) return; } var index = { 'name': property, 'dirty': true, 'values': this.prepareFullDocIndex() }; this.binaryIndices[property] = index; var wrappedComparer = (function (p, data) { return function (a, b) { var objAp = data[a][p], objBp = data[b][p]; if (objAp !== objBp) { if (ltHelper(objAp, objBp, false)) return -1; if (gtHelper(objAp, objBp, false)) return 1; } return 0; }; })(property, this.data); index.values.sort(wrappedComparer); index.dirty = false; this.dirty = true; // for autosave scenarios }; Collection.prototype.getSequencedIndexValues = function (property) { var idx, idxvals = this.binaryIndices[property].values; var result = ""; for (idx = 0; idx < idxvals.length; idx++) { result += " [" + idx + "] " + this.data[idxvals[idx]][property]; } return result; }; Collection.prototype.ensureUniqueIndex = function (field) { var index = this.constraints.unique[field]; if (!index) { // keep track of new unique index for regenerate after database (re)load. if (this.uniqueNames.indexOf(field) == -1) { this.uniqueNames.push(field); } } // if index already existed, (re)loading it will likely cause collisions, rebuild always this.constraints.unique[field] = index = new UniqueIndex(field); this.data.forEach(function (obj) { index.set(obj); }); return index; }; /** * Ensure all binary indices */ Collection.prototype.ensureAllIndexes = function (force) { var key, bIndices = this.binaryIndices; for (key in bIndices) { if (hasOwnProperty.call(bIndices, key)) { this.ensureIndex(key, force); } } }; Collection.prototype.flagBinaryIndexesDirty = function () { var key, bIndices = this.binaryIndices; for (key in bIndices) { if (hasOwnProperty.call(bIndices, key)) { bIndices[key].dirty = true; } } }; Collection.prototype.flagBinaryIndexDirty = function (index) { if (this.binaryIndices[index]) this.binaryIndices[index].dirty = true; }; /** * Quickly determine number of documents in collection (or query) * @param {object=} query - (optional) query object to count results of * @returns {number} number of documents in the collection * @memberof Collection */ Collection.prototype.count = function (query) { if (!query) { return this.data.length; } return this.chain().find(query).filteredrows.length; }; /** * Rebuild idIndex */ Collection.prototype.ensureId = function () { var len = this.data.length, i = 0; this.idIndex = []; for (i; i < len; i += 1) { this.idIndex.push(this.data[i].$loki); } }; /** * Rebuild idIndex async with callback - useful for background syncing with a remote server */ Collection.prototype.ensureIdAsync = function (callback) { this.async(function () { this.ensureId(); }, callback); }; /** * Add a dynamic view to the collection * @param {string} name - name of dynamic view to add * @param {object=} options - (optional) options to configure dynamic view with * @param {boolean} options.persistent - indicates if view is to main internal results array in 'resultdata' * @param {string} options.sortPriority - 'passive' (sorts performed on call to data) or 'active' (after updates) * @param {number} options.minRebuildInterval - minimum rebuild interval (need clarification to docs here) * @returns {DynamicView} reference to the dynamic view added * @memberof Collection **/ Collection.prototype.addDynamicView = function (name, options) { var dv = new DynamicView(this, name, options); this.DynamicViews.push(dv); return dv; }; /** * Remove a dynamic view from the collection * @param {string} name - name of dynamic view to remove * @memberof Collection **/ Collection.prototype.removeDynamicView = function (name) { for (var idx = 0; idx < this.DynamicViews.length; idx++) { if (this.DynamicViews[idx].name === name) { this.DynamicViews.splice(idx, 1); } } }; /** * Look up dynamic view reference from within the collection * @param {string} name - name of dynamic view to retrieve reference of * @returns {DynamicView} A reference to the dynamic view with that name * @memberof Collection **/ Collection.prototype.getDynamicView = function (name) { for (var idx = 0; idx < this.DynamicViews.length; idx++) { if (this.DynamicViews[idx].name === name) { return this.DynamicViews[idx]; } } return null; }; /** * find and update: pass a filtering function to select elements to be updated * and apply the updatefunctino to those elements iteratively * @param {function} filterFunction - filter function whose results will execute update * @param {function} updateFunction - update function to run against filtered documents * @memberof Collection */ Collection.prototype.findAndUpdate = function (filterFunction, updateFunction) { var results = this.where(filterFunction), i = 0, obj; try { for (i; i < results.length; i++) { obj = updateFunction(results[i]); this.update(obj); } } catch (err) { this.rollback(); this.console.error(err.message); } }; /** * Adds object(s) to collection, ensure object(s) have meta properties, clone it if necessary, etc. * @param {(object|array)} doc - the document (or array of documents) to be inserted * @returns {(object|array)} document or documents inserted * @memberof Collection */ Collection.prototype.insert = function (doc) { if (!Array.isArray(doc)) { return this.insertOne(doc); } // holder to the clone of the object inserted if collections is set to clone objects var obj; var results = []; for (var i = 0, len = doc.length; i < len; i++) { obj = this.insertOne(doc[i]); if (!obj) { return undefined; } results.push(obj); } return results.length === 1 ? results[0] : results; }; /** * Adds a single object, ensures it has meta properties, clone it if necessary, etc. * @param {object} doc - the document to be inserted * @returns {object} document or 'undefined' if there was a problem inserting it * @memberof Collection */ Collection.prototype.insertOne = function (doc) { var err = null; if (typeof doc !== 'object') { err = new TypeError('Document needs to be an object'); } else if (doc === null) { err = new TypeError('Object cannot be null'); } if (err !== null) { this.emit('error', err); throw err; } // if configured to clone, do so now... otherwise just use same obj reference var obj = this.cloneObjects ? clone(doc, this.cloneMethod) : doc; if (typeof obj.meta === 'undefined') { obj.meta = { revision: 0, created: 0 }; } this.emit('pre-insert', obj); if (!this.add(obj)) { return undefined; } this.addAutoUpdateObserver(obj); this.emit('insert', obj); return obj; }; /** * Empties the collection. * @memberof Collection */ Collection.prototype.clear = function () { this.data = []; this.idIndex = []; this.binaryIndices = {}; this.cachedIndex = null; this.cachedBinaryIndex = null; this.cachedData = null; this.maxId = 0; this.DynamicViews = []; this.dirty = true; }; /** * Updates an object and notifies collection that the document has changed. * @param {object} doc - document to update within the collection * @memberof Collection */ Collection.prototype.update = function (doc) { this.flagBinaryIndexesDirty(); if (Array.isArray(doc)) { var k = 0, len = doc.length; for (k; k < len; k += 1) { this.update(doc[k]); } return; } // verify object is a properly formed document if (!hasOwnProperty.call(doc, '$loki')) { throw new Error('Trying to update unsynced document. Please save the document first by using insert() or addMany()'); } try { this.startTransaction(); var arr = this.get(doc.$loki, true), obj, position, self = this; obj = arr[0]; // -internal- obj ref position = arr[1]; // position in data array if (!arr) { throw new Error('Trying to update a document not in collection.'); } this.emit('pre-update', doc); Object.keys(this.constraints.unique).forEach(function (key) { self.constraints.unique[key].update(obj, doc); }); // operate the update this.data[position] = doc; if (obj !== doc) { this.addAutoUpdateObserver(doc); } // now that we can efficiently determine the data[] position of newly added document, // submit it for all registered DynamicViews to evaluate for inclusion/exclusion for (var idx = 0; idx < this.DynamicViews.length; idx++) { this.DynamicViews[idx].evaluateDocument(position, false); } this.idIndex[position] = obj.$loki; this.commit(); this.dirty = true; // for autosave scenarios this.emit('update', doc); return doc; } catch (err) { this.rollback(); this.console.error(err.message); this.emit('error', err); throw (err); // re-throw error so user does not think it succeeded } }; /** * Add object to collection */ Collection.prototype.add = function (obj) { // if parameter isn't object exit with throw if ('object' !== typeof obj) { throw new TypeError('Object being added needs to be an object'); } // if object you are adding already has id column it is either already in the collection // or the object is carrying its own 'id' property. If it also has a meta property, // then this is already in collection so throw error, otherwise rename to originalId and continue adding. if (typeof (obj.$loki) !== 'undefined') { throw new Error('Document is already in collection, please use update()'); } this.flagBinaryIndexesDirty(); /* * try adding object to collection */ try { this.startTransaction(); this.maxId++; if (isNaN(this.maxId)) { this.maxId = (this.data[this.data.length - 1].$loki + 1); } obj.$loki = this.maxId; obj.meta.version = 0; var key, constrUnique = this.constraints.unique; for (key in constrUnique) { if (hasOwnProperty.call(constrUnique, key)) { constrUnique[key].set(obj); } } // add new obj id to idIndex this.idIndex.push(obj.$loki); // add the object this.data.push(obj); // now that we can efficiently determine the data[] position of newly added document, // submit it for all registered DynamicViews to evaluate for inclusion/exclusion var addedPos = this.data.length - 1; var dvlen = this.DynamicViews.length; for (var i = 0; i < dvlen; i++) { this.DynamicViews[i].evaluateDocument(addedPos, true); } this.commit(); this.dirty = true; // for autosave scenarios return (this.cloneObjects) ? (clone(obj, this.cloneMethod)) : (obj); } catch (err) { this.rollback(); this.console.error(err.message); this.emit('error', err); throw (err); // re-throw error so user does not think it succeeded } }; /** * Remove all documents matching supplied filter object * @param {object} query - query object to filter on * @memberof Collection */ Collection.prototype.removeWhere = function (query) { var list; if (typeof query === 'function') { list = this.data.filter(query); } else { list = new Resultset(this, { queryObj: query }); } this.remove(list); }; Collection.prototype.removeDataOnly = function () { this.remove(this.data.slice()); }; /** * Remove a document from the collection * @param {object} doc - document to remove from collection * @memberof Collection */ Collection.prototype.remove = function (doc) { if (typeof doc === 'number') { doc = this.get(doc); } if ('object' !== typeof doc) { throw new Error('Parameter is not an object'); } if (Array.isArray(doc)) { var k = 0, len = doc.length; for (k; k < len; k += 1) { this.remove(doc[k]); } return; } if (!hasOwnProperty.call(doc, '$loki')) { throw new Error('Object is not a document stored in the collection'); } this.flagBinaryIndexesDirty(); try { this.startTransaction(); var arr = this.get(doc.$loki, true), // obj = arr[0], position = arr[1]; var self = this; Object.keys(this.constraints.unique).forEach(function (key) { if (doc[key] !== null && typeof doc[key] !== 'undefined') { self.constraints.unique[key].remove(doc[key]); } }); // now that we can efficiently determine the data[] position of newly added document, // submit it for all registered DynamicViews to remove for (var idx = 0; idx < this.DynamicViews.length; idx++) { this.DynamicViews[idx].removeDocument(position); } this.data.splice(position, 1); this.removeAutoUpdateObserver(doc); // remove id from idIndex this.idIndex.splice(position, 1); this.commit(); this.dirty = true; // for autosave scenarios this.emit('delete', arr[0]); delete doc.$loki; delete doc.meta; return doc; } catch (err) { this.rollback(); this.console.error(err.message); this.emit('error', err); return null; } }; /*---------------------+ | Finding methods | +----------------------*/ /** * Get by Id - faster than other methods because of the searching algorithm * @param {int} id - $loki id of document you want to retrieve * @param {boolean} returnPosition - if 'true' we will return [object, position] * @returns {(object|array|null)} Object reference if document was found, null if not, * or an array if 'returnPosition' was passed. * @memberof Collection */ Collection.prototype.get = function (id, returnPosition) { var retpos = returnPosition || false, data = this.idIndex, max = data.length - 1, min = 0, mid = (min + max) >> 1; id = typeof id === 'number' ? id : parseInt(id, 10); if (isNaN(id)) { throw new TypeError('Passed id is not an integer'); } while (data[min] < data[max]) { mid = (min + max) >> 1; if (data[mid] < id) { min = mid + 1; } else { max = mid; } } if (max === min && data[min] === id) { if (retpos) { return [this.data[min], min]; } return this.data[min]; } return null; }; /** * Retrieve doc by Unique index * @param {string} field - name of uniquely indexed property to use when doing lookup * @param {value} value - unique value to search for * @returns {object} document matching the value passed * @memberof Collection */ Collection.prototype.by = function (field, value) { var self; if (value === undefined) { self = this; return function (value) { return self.by(field, value); }; } var result = this.constraints.unique[field].get(value); if (!this.cloneObjects) { return result; } else { return clone(result, this.cloneMethod); } }; /** * Find one object by index property, by property equal to value * @param {object} query - query object used to perform search with * @returns {(object|null)} First matching document, or null if none * @memberof Collection */ Collection.prototype.findOne = function (query) { // Instantiate Resultset and exec find op passing firstOnly = true param var result = new Resultset(this, { queryObj: query, firstOnly: true }); if (Array.isArray(result) && result.length === 0) { return null; } else { if (!this.cloneObjects) { return result; } else { return clone(result, this.cloneMethod); } } }; /** * Chain method, used for beginning a series of chained find() and/or view() operations * on a collection. * * @param {array} transform - Ordered array of transform step objects similar to chain * @param {object} parameters - Object containing properties representing parameters to substitute * @returns {Resultset} (this) resultset, or data array if any map or join functions where called * @memberof Collection */ Collection.prototype.chain = function (transform, parameters) { var rs = new Resultset(this); if (typeof transform === 'undefined') { return rs; } return rs.transform(transform, parameters); }; /** * Find method, api is similar to mongodb. * for more complex queries use [chain()]{@link Collection#chain} or [where()]{@link Collection#where}. * @example {@tutorial Query Examples} * @param {object} query - 'mongo-like' query object * @returns {array} Array of matching documents * @memberof Collection */ Collection.prototype.find = function (query) { if (typeof (query) === 'undefined') { query = 'getAll'; } var results = new Resultset(this, { queryObj: query }); if (!this.cloneObjects) { return results; } else { return cloneObjectArray(results, this.cloneMethod); } }; /** * Find object by unindexed field by property equal to value, * simply iterates and returns the first element matching the query */ Collection.prototype.findOneUnindexed = function (prop, value) { var i = this.data.length, doc; while (i--) { if (this.data[i][prop] === value) { doc = this.data[i]; return doc; } } return null; }; /** * Transaction methods */ /** start the transation */ Collection.prototype.startTransaction = function () { if (this.transactional) { this.cachedData = clone(this.data, this.cloneMethod); this.cachedIndex = this.idIndex; this.cachedBinaryIndex = this.binaryIndices; // propagate startTransaction to dynamic views for (var idx = 0; idx < this.DynamicViews.length; idx++) { this.DynamicViews[idx].startTransaction(); } } }; /** commit the transation */ Collection.prototype.commit = function () { if (this.transactional) { this.cachedData = null; this.cachedIndex = null; this.cachedBinaryIndex = null; // propagate commit to dynamic views for (var idx = 0; idx < this.DynamicViews.length; idx++) { this.DynamicViews[idx].commit(); } } }; /** roll back the transation */ Collection.prototype.rollback = function () { if (this.transactional) { if (this.cachedData !== null && this.cachedIndex !== null) { this.data = this.cachedData; this.idIndex = this.cachedIndex; this.binaryIndices = this.cachedBinaryIndex; } // propagate rollback to dynamic views for (var idx = 0; idx < this.DynamicViews.length; idx++) { this.DynamicViews[idx].rollback(); } } }; // async executor. This is only to enable callbacks at the end of the execution. Collection.prototype.async = function (fun, callback) { setTimeout(function () { if (typeof fun === 'function') { fun(); callback(); } else { throw new TypeError('Argument passed for async execution is not a function'); } }, 0); }; /** * Query the collection by supplying a javascript filter function. * @example * var results = coll.where(function(obj) { * return obj.legs === 8; * }); * * @param {function} fun - filter function to run against all collection docs * @returns {array} all documents which pass your filter function * @memberof Collection */ Collection.prototype.where = function (fun) { var results = new Resultset(this, { queryFunc: fun }); if (!this.cloneObjects) { return results; } else { return cloneObjectArray(results, this.cloneMethod); } }; /** * Map Reduce operation * * @param {function} mapFunction - function to use as map function * @param {function} reduceFunction - function to use as reduce function * @returns {data} The result of your mapReduce operation * @memberof Collection */ Collection.prototype.mapReduce = function (mapFunction, reduceFunction) { try { return reduceFunction(this.data.map(mapFunction)); } catch (err) { throw err; } }; /** * Join two collections on specified properties * * @param {array} joinData - array of documents to 'join' to this collection * @param {string} leftJoinProp - property name in collection * @param {string} rightJoinProp - property name in joinData * @param {function=} mapFun - (Optional) map function to use * @returns {Resultset} Result of the mapping operation * @memberof Collection */ Collection.prototype.eqJoin = function (joinData, leftJoinProp, rightJoinProp, mapFun) { // logic in Resultset class return new Resultset(this).eqJoin(joinData, leftJoinProp, rightJoinProp, mapFun); }; /* ------ STAGING API -------- */ /** * stages: a map of uniquely identified 'stages', which hold copies of objects to be * manipulated without affecting the data in the original collection */ Collection.prototype.stages = {}; /** * (Staging API) create a stage and/or retrieve it * @memberof Collection */ Collection.prototype.getStage = function (name) { if (!this.stages[name]) { this.stages[name] = {}; } return this.stages[name]; }; /** * a collection of objects recording the changes applied through a commmitStage */ Collection.prototype.commitLog = []; /** * (Staging API) create a copy of an object and insert it into a stage * @memberof Collection */ Collection.prototype.stage = function (stageName, obj) { var copy = JSON.parse(JSON.stringify(obj)); this.getStage(stageName)[obj.$loki] = copy; return copy; }; /** * (Staging API) re-attach all objects to the original collection, so indexes and views can be rebuilt * then create a message to be inserted in the commitlog * @param {string} stageName - name of stage * @param {string} message * @memberof Collection */ Collection.prototype.commitStage = function (stageName, message) { var stage = this.getStage(stageName), prop, timestamp = new Date().getTime(); for (prop in stage) { this.update(stage[prop]); this.commitLog.push({ timestamp: timestamp, message: message, data: JSON.parse(JSON.stringify(stage[prop])) }); } this.stages[stageName] = {}; }; Collection.prototype.no_op = function () { return; }; /** * @memberof Collection */ Collection.prototype.extract = function (field) { var i = 0, len = this.data.length, isDotNotation = isDeepProperty(field), result = []; for (i; i < len; i += 1) { result.push(deepProperty(this.data[i], field, isDotNotation)); } return result; }; /** * @memberof Collection */ Collection.prototype.max = function (field) { return Math.max.apply(null, this.extract(field)); }; /** * @memberof Collection */ Collection.prototype.min = function (field) { return Math.min.apply(null, this.extract(field)); }; /** * @memberof Collection */ Collection.prototype.maxRecord = function (field) { var i = 0, len = this.data.length, deep = isDeepProperty(field), result = { index: 0, value: undefined }, max; for (i; i < len; i += 1) { if (max !== undefined) { if (max < deepProperty(this.data[i], field, deep)) { max = deepProperty(this.data[i], field, deep); result.index = this.data[i].$loki; } } else { max = deepProperty(this.data[i], field, deep); result.index = this.data[i].$loki; } } result.value = max; return result; }; /** * @memberof Collection */ Collection.prototype.minRecord = function (field) { var i = 0, len = this.data.length, deep = isDeepProperty(field), result = { index: 0, value: undefined }, min; for (i; i < len; i += 1) { if (min !== undefined) { if (min > deepProperty(this.data[i], field, deep)) { min = deepProperty(this.data[i], field, deep); result.index = this.data[i].$loki; } } else { min = deepProperty(this.data[i], field, deep); result.index = this.data[i].$loki; } } result.value = min; return result; }; /** * @memberof Collection */ Collection.prototype.extractNumerical = function (field) { return this.extract(field).map(parseBase10).filter(Number).filter(function (n) { return !(isNaN(n)); }); }; /** * Calculates the average numerical value of a property * * @param {string} field - name of property in docs to average * @returns {number} average of property in all docs in the collection * @memberof Collection */ Collection.prototype.avg = function (field) { return average(this.extractNumerical(field)); }; /** * Calculate standard deviation of a field * @memberof Collection * @param {string} field */ Collection.prototype.stdDev = function (field) { return standardDeviation(this.extractNumerical(field)); }; /** * @memberof Collection * @param {string} field */ Collection.prototype.mode = function (field) { var dict = {}, data = this.extract(field); data.forEach(function (obj) { if (dict[obj]) { dict[obj] += 1; } else { dict[obj] = 1; } }); var max, prop, mode; for (prop in dict) { if (max) { if (max < dict[prop]) { mode = prop; } } else { mode = prop; max = dict[prop]; } } return mode; }; /** * @memberof Collection * @param {string} field - property name */ Collection.prototype.median = function (field) { var values = this.extractNumerical(field); values.sort(sub); var half = Math.floor(values.length / 2); if (values.length % 2) { return values[half]; } else { return (values[half - 1] + values[half]) / 2.0; } }; /** * General utils, including statistical functions */ function isDeepProperty(field) { return field.indexOf('.') !== -1; } function parseBase10(num) { return parseFloat(num, 10); } function isNotUndefined(obj) { return obj !== undefined; } function add(a, b) { return a + b; } function sub(a, b) { return a - b; } function median(values) { values.sort(sub); var half = Math.floor(values.length / 2); return (values.length % 2) ? values[half] : ((values[half - 1] + values[half]) / 2.0); } function average(array) { return (array.reduce(add, 0)) / array.length; } function standardDeviation(values) { var avg = average(values); var squareDiffs = values.map(function (value) { var diff = value - avg; var sqrDiff = diff * diff; return sqrDiff; }); var avgSquareDiff = average(squareDiffs); var stdDev = Math.sqrt(avgSquareDiff); return stdDev; } function deepProperty(obj, property, isDeep) { if (isDeep === false) { // pass without processing return obj[property]; } var pieces = property.split('.'), root = obj; while (pieces.length > 0) { root = root[pieces.shift()]; } return root; } function binarySearch(array, item, fun) { var lo = 0, hi = array.length, compared, mid; while (lo < hi) { mid = (lo + hi) >> 1; compared = fun.apply(null, [item, array[mid]]); if (compared === 0) { return { found: true, index: mid }; } else if (compared < 0) { hi = mid; } else { lo = mid + 1; } } return { found: false, index: hi }; } function BSonSort(fun) { return function (array, item) { return binarySearch(array, item, fun); }; } function KeyValueStore() {} KeyValueStore.prototype = { keys: [], values: [], sort: function (a, b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); }, setSort: function (fun) { this.bs = new BSonSort(fun); }, bs: function () { return new BSonSort(this.sort); }, set: function (key, value) { var pos = this.bs(this.keys, key); if (pos.found) { this.values[pos.index] = value; } else { this.keys.splice(pos.index, 0, key); this.values.splice(pos.index, 0, value); } }, get: function (key) { return this.values[binarySearch(this.keys, key, this.sort).index]; } }; function UniqueIndex(uniqueField) { this.field = uniqueField; this.keyMap = {}; this.lokiMap = {}; } UniqueIndex.prototype.keyMap = {}; UniqueIndex.prototype.lokiMap = {}; UniqueIndex.prototype.set = function (obj) { var fieldValue = obj[this.field]; if (fieldValue !== null && typeof (fieldValue) !== 'undefined') { if (this.keyMap[fieldValue]) { throw new Error('Duplicate key for property ' + this.field + ': ' + fieldValue); } else { this.keyMap[fieldValue] = obj; this.lokiMap[obj.$loki] = fieldValue; } } }; UniqueIndex.prototype.get = function (key) { return this.keyMap[key]; }; UniqueIndex.prototype.byId = function (id) { return this.keyMap[this.lokiMap[id]]; }; /** * Updates a document's unique index given an updated object. * @param {Object} obj Original document object * @param {Object} doc New document object (likely the same as obj) */ UniqueIndex.prototype.update = function (obj, doc) { if (this.lokiMap[obj.$loki] !== doc[this.field]) { var old = this.lokiMap[obj.$loki]; this.set(doc); // make the old key fail bool test, while avoiding the use of delete (mem-leak prone) this.keyMap[old] = undefined; } else { this.keyMap[obj[this.field]] = doc; } }; UniqueIndex.prototype.remove = function (key) { var obj = this.keyMap[key]; if (obj !== null && typeof obj !== 'undefined') { this.keyMap[key] = undefined; this.lokiMap[obj.$loki] = undefined; } else { throw new Error('Key is not in unique index: ' + this.field); } }; UniqueIndex.prototype.clear = function () { this.keyMap = {}; this.lokiMap = {}; }; function ExactIndex(exactField) { this.index = {}; this.field = exactField; } // add the value you want returned to the key in the index ExactIndex.prototype = { set: function add(key, val) { if (this.index[key]) { this.index[key].push(val); } else { this.index[key] = [val]; } }, // remove the value from the index, if the value was the last one, remove the key remove: function remove(key, val) { var idxSet = this.index[key]; for (var i in idxSet) { if (idxSet[i] == val) { idxSet.splice(i, 1); } } if (idxSet.length < 1) { this.index[key] = undefined; } }, // get the values related to the key, could be more than one get: function get(key) { return this.index[key]; }, // clear will zap the index clear: function clear(key) { this.index = {}; } }; function SortedIndex(sortedField) { this.field = sortedField; } SortedIndex.prototype = { keys: [], values: [], // set the default sort sort: function (a, b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); }, bs: function () { return new BSonSort(this.sort); }, // and allow override of the default sort setSort: function (fun) { this.bs = new BSonSort(fun); }, // add the value you want returned to the key in the index set: function (key, value) { var pos = binarySearch(this.keys, key, this.sort); if (pos.found) { this.values[pos.index].push(value); } else { this.keys.splice(pos.index, 0, key); this.values.splice(pos.index, 0, [value]); } }, // get all values which have a key == the given key get: function (key) { var bsr = binarySearch(this.keys, key, this.sort); if (bsr.found) { return this.values[bsr.index]; } else { return []; } }, // get all values which have a key < the given key getLt: function (key) { var bsr = binarySearch(this.keys, key, this.sort); var pos = bsr.index; if (bsr.found) pos--; return this.getAll(key, 0, pos); }, // get all values which have a key > the given key getGt: function (key) { var bsr = binarySearch(this.keys, key, this.sort); var pos = bsr.index; if (bsr.found) pos++; return this.getAll(key, pos, this.keys.length); }, // get all vals from start to end getAll: function (key, start, end) { var results = []; for (var i = start; i < end; i++) { results = results.concat(this.values[i]); } return results; }, // just in case someone wants to do something smart with ranges getPos: function (key) { return binarySearch(this.keys, key, this.sort); }, // remove the value from the index, if the value was the last one, remove the key remove: function (key, value) { var pos = binarySearch(this.keys, key, this.sort).index; var idxSet = this.values[pos]; for (var i in idxSet) { if (idxSet[i] == value) idxSet.splice(i, 1); } if (idxSet.length < 1) { this.keys.splice(pos, 1); this.values.splice(pos, 1); } }, // clear will zap the index clear: function () { this.keys = []; this.values = []; } }; Loki.LokiOps = LokiOps; Loki.Collection = Collection; Loki.KeyValueStore = KeyValueStore; Loki.persistenceAdapters = { fs: LokiFsAdapter, localStorage: LokiLocalStorageAdapter }; return Loki; }()); })); /*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE * @version 3.2.1 */ (function() { "use strict"; function lib$es6$promise$utils$$objectOrFunction(x) { return typeof x === 'function' || (typeof x === 'object' && x !== null); } function lib$es6$promise$utils$$isFunction(x) { return typeof x === 'function'; } function lib$es6$promise$utils$$isMaybeThenable(x) { return typeof x === 'object' && x !== null; } var lib$es6$promise$utils$$_isArray; if (!Array.isArray) { lib$es6$promise$utils$$_isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { lib$es6$promise$utils$$_isArray = Array.isArray; } var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; var lib$es6$promise$asap$$len = 0; var lib$es6$promise$asap$$vertxNext; var lib$es6$promise$asap$$customSchedulerFn; var lib$es6$promise$asap$$asap = function asap(callback, arg) { lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; lib$es6$promise$asap$$len += 2; if (lib$es6$promise$asap$$len === 2) { // If len is 2, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. if (lib$es6$promise$asap$$customSchedulerFn) { lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush); } else { lib$es6$promise$asap$$scheduleFlush(); } } } function lib$es6$promise$asap$$setScheduler(scheduleFn) { lib$es6$promise$asap$$customSchedulerFn = scheduleFn; } function lib$es6$promise$asap$$setAsap(asapFn) { lib$es6$promise$asap$$asap = asapFn; } var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; var lib$es6$promise$asap$$isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; // test for web worker but not in IE10 var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function lib$es6$promise$asap$$useNextTick() { // node version 0.10.x displays a deprecation warning when nextTick is used recursively // see https://github.com/cujojs/when/issues/410 for details return function() { process.nextTick(lib$es6$promise$asap$$flush); }; } // vertx function lib$es6$promise$asap$$useVertxTimer() { return function() { lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); }; } function lib$es6$promise$asap$$useMutationObserver() { var iterations = 0; var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } // web worker function lib$es6$promise$asap$$useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = lib$es6$promise$asap$$flush; return function () { channel.port2.postMessage(0); }; } function lib$es6$promise$asap$$useSetTimeout() { return function() { setTimeout(lib$es6$promise$asap$$flush, 1); }; } var lib$es6$promise$asap$$queue = new Array(1000); function lib$es6$promise$asap$$flush() { for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { var callback = lib$es6$promise$asap$$queue[i]; var arg = lib$es6$promise$asap$$queue[i+1]; callback(arg); lib$es6$promise$asap$$queue[i] = undefined; lib$es6$promise$asap$$queue[i+1] = undefined; } lib$es6$promise$asap$$len = 0; } function lib$es6$promise$asap$$attemptVertx() { try { var r = require; var vertx = r('vertx'); lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; return lib$es6$promise$asap$$useVertxTimer(); } catch(e) { return lib$es6$promise$asap$$useSetTimeout(); } } var lib$es6$promise$asap$$scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (lib$es6$promise$asap$$isNode) { lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); } else if (lib$es6$promise$asap$$BrowserMutationObserver) { lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); } else if (lib$es6$promise$asap$$isWorker) { lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx(); } else { lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); } function lib$es6$promise$then$$then(onFulfillment, onRejection) { var parent = this; var child = new this.constructor(lib$es6$promise$$internal$$noop); if (child[lib$es6$promise$$internal$$PROMISE_ID] === undefined) { lib$es6$promise$$internal$$makePromise(child); } var state = parent._state; if (state) { var callback = arguments[state - 1]; lib$es6$promise$asap$$asap(function(){ lib$es6$promise$$internal$$invokeCallback(state, child, callback, parent._result); }); } else { lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); } return child; } var lib$es6$promise$then$$default = lib$es6$promise$then$$then; function lib$es6$promise$promise$resolve$$resolve(object) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor(lib$es6$promise$$internal$$noop); lib$es6$promise$$internal$$resolve(promise, object); return promise; } var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; var lib$es6$promise$$internal$$PROMISE_ID = Math.random().toString(36).substring(16); function lib$es6$promise$$internal$$noop() {} var lib$es6$promise$$internal$$PENDING = void 0; var lib$es6$promise$$internal$$FULFILLED = 1; var lib$es6$promise$$internal$$REJECTED = 2; var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); function lib$es6$promise$$internal$$selfFulfillment() { return new TypeError("You cannot resolve a promise with itself"); } function lib$es6$promise$$internal$$cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.'); } function lib$es6$promise$$internal$$getThen(promise) { try { return promise.then; } catch(error) { lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; return lib$es6$promise$$internal$$GET_THEN_ERROR; } } function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch(e) { return e; } } function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { lib$es6$promise$asap$$asap(function(promise) { var sealed = false; var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { if (sealed) { return; } sealed = true; if (thenable !== value) { lib$es6$promise$$internal$$resolve(promise, value); } else { lib$es6$promise$$internal$$fulfill(promise, value); } }, function(reason) { if (sealed) { return; } sealed = true; lib$es6$promise$$internal$$reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; lib$es6$promise$$internal$$reject(promise, error); } }, promise); } function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { lib$es6$promise$$internal$$fulfill(promise, thenable._result); } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { lib$es6$promise$$internal$$reject(promise, thenable._result); } else { lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { lib$es6$promise$$internal$$resolve(promise, value); }, function(reason) { lib$es6$promise$$internal$$reject(promise, reason); }); } } function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable, then) { if (maybeThenable.constructor === promise.constructor && then === lib$es6$promise$then$$default && constructor.resolve === lib$es6$promise$promise$resolve$$default) { lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); } else { if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); } else if (then === undefined) { lib$es6$promise$$internal$$fulfill(promise, maybeThenable); } else if (lib$es6$promise$utils$$isFunction(then)) { lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); } else { lib$es6$promise$$internal$$fulfill(promise, maybeThenable); } } } function lib$es6$promise$$internal$$resolve(promise, value) { if (promise === value) { lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment()); } else if (lib$es6$promise$utils$$objectOrFunction(value)) { lib$es6$promise$$internal$$handleMaybeThenable(promise, value, lib$es6$promise$$internal$$getThen(value)); } else { lib$es6$promise$$internal$$fulfill(promise, value); } } function lib$es6$promise$$internal$$publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } lib$es6$promise$$internal$$publish(promise); } function lib$es6$promise$$internal$$fulfill(promise, value) { if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } promise._result = value; promise._state = lib$es6$promise$$internal$$FULFILLED; if (promise._subscribers.length !== 0) { lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise); } } function lib$es6$promise$$internal$$reject(promise, reason) { if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } promise._state = lib$es6$promise$$internal$$REJECTED; promise._result = reason; lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise); } function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; parent._onerror = null; subscribers[length] = child; subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; if (length === 0 && parent._state) { lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent); } } function lib$es6$promise$$internal$$publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child, callback, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function lib$es6$promise$$internal$$ErrorObject() { this.error = null; } var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); function lib$es6$promise$$internal$$tryCatch(callback, detail) { try { return callback(detail); } catch(e) { lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; return lib$es6$promise$$internal$$TRY_CATCH_ERROR; } } function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { var hasCallback = lib$es6$promise$utils$$isFunction(callback), value, error, succeeded, failed; if (hasCallback) { value = lib$es6$promise$$internal$$tryCatch(callback, detail); if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== lib$es6$promise$$internal$$PENDING) { // noop } else if (hasCallback && succeeded) { lib$es6$promise$$internal$$resolve(promise, value); } else if (failed) { lib$es6$promise$$internal$$reject(promise, error); } else if (settled === lib$es6$promise$$internal$$FULFILLED) { lib$es6$promise$$internal$$fulfill(promise, value); } else if (settled === lib$es6$promise$$internal$$REJECTED) { lib$es6$promise$$internal$$reject(promise, value); } } function lib$es6$promise$$internal$$initializePromise(promise, resolver) { try { resolver(function resolvePromise(value){ lib$es6$promise$$internal$$resolve(promise, value); }, function rejectPromise(reason) { lib$es6$promise$$internal$$reject(promise, reason); }); } catch(e) { lib$es6$promise$$internal$$reject(promise, e); } } var lib$es6$promise$$internal$$id = 0; function lib$es6$promise$$internal$$nextId() { return lib$es6$promise$$internal$$id++; } function lib$es6$promise$$internal$$makePromise(promise) { promise[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$id++; promise._state = undefined; promise._result = undefined; promise._subscribers = []; } function lib$es6$promise$promise$all$$all(entries) { return new lib$es6$promise$enumerator$$default(this, entries).promise; } var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; function lib$es6$promise$promise$race$$race(entries) { /*jshint validthis:true */ var Constructor = this; if (!lib$es6$promise$utils$$isArray(entries)) { return new Constructor(function(resolve, reject) { reject(new TypeError('You must pass an array to race.')); }); } else { return new Constructor(function(resolve, reject) { var length = entries.length; for (var i = 0; i < length; i++) { Constructor.resolve(entries[i]).then(resolve, reject); } }); } } var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; function lib$es6$promise$promise$reject$$reject(reason) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(lib$es6$promise$$internal$$noop); lib$es6$promise$$internal$$reject(promise, reason); return promise; } var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; function lib$es6$promise$promise$$needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function lib$es6$promise$promise$$needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js var promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */ function lib$es6$promise$promise$$Promise(resolver) { this[lib$es6$promise$$internal$$PROMISE_ID] = lib$es6$promise$$internal$$nextId(); this._result = this._state = undefined; this._subscribers = []; if (lib$es6$promise$$internal$$noop !== resolver) { typeof resolver !== 'function' && lib$es6$promise$promise$$needsResolver(); this instanceof lib$es6$promise$promise$$Promise ? lib$es6$promise$$internal$$initializePromise(this, resolver) : lib$es6$promise$promise$$needsNew(); } } lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler; lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap; lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap; lib$es6$promise$promise$$Promise.prototype = { constructor: lib$es6$promise$promise$$Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript var result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript var author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ then: lib$es6$promise$then$$default, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ 'catch': function(onRejection) { return this.then(null, onRejection); } }; var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { this._instanceConstructor = Constructor; this.promise = new Constructor(lib$es6$promise$$internal$$noop); if (!this.promise[lib$es6$promise$$internal$$PROMISE_ID]) { lib$es6$promise$$internal$$makePromise(this.promise); } if (Array.isArray(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._result = new Array(this.length); if (this.length === 0) { lib$es6$promise$$internal$$fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { lib$es6$promise$$internal$$fulfill(this.promise, this._result); } } } else { lib$es6$promise$$internal$$reject(this.promise, lib$es6$promise$enumerator$$validationError()); } } function lib$es6$promise$enumerator$$validationError() { return new Error('Array Methods must be provided an Array'); } lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { var length = this.length; var input = this._input; for (var i = 0; this._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { this._eachEntry(input[i], i); } }; lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { var c = this._instanceConstructor; var resolve = c.resolve; if (resolve === lib$es6$promise$promise$resolve$$default) { var then = lib$es6$promise$$internal$$getThen(entry); if (then === lib$es6$promise$then$$default && entry._state !== lib$es6$promise$$internal$$PENDING) { this._settledAt(entry._state, i, entry._result); } else if (typeof then !== 'function') { this._remaining--; this._result[i] = entry; } else if (c === lib$es6$promise$promise$$default) { var promise = new c(lib$es6$promise$$internal$$noop); lib$es6$promise$$internal$$handleMaybeThenable(promise, entry, then); this._willSettleAt(promise, i); } else { this._willSettleAt(new c(function(resolve) { resolve(entry); }), i); } } else { this._willSettleAt(resolve(entry), i); } }; lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { var promise = this.promise; if (promise._state === lib$es6$promise$$internal$$PENDING) { this._remaining--; if (state === lib$es6$promise$$internal$$REJECTED) { lib$es6$promise$$internal$$reject(promise, value); } else { this._result[i] = value; } } if (this._remaining === 0) { lib$es6$promise$$internal$$fulfill(promise, this._result); } }; lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { var enumerator = this; lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); }, function(reason) { enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); }); }; function lib$es6$promise$polyfill$$polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof self !== 'undefined') { local = self; } else { try { local = Function('return this')(); } catch (e) { throw new Error('polyfill failed because global object is unavailable in this environment'); } } var P = local.Promise; if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { return; } local.Promise = lib$es6$promise$promise$$default; } var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; var lib$es6$promise$umd$$ES6Promise = { 'Promise': lib$es6$promise$promise$$default, 'polyfill': lib$es6$promise$polyfill$$default }; /* global define:true module:true window: true */ if (typeof define === 'function' && define['amd']) { define(function() { return lib$es6$promise$umd$$ES6Promise; }); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = lib$es6$promise$umd$$ES6Promise; } else if (typeof this !== 'undefined') { this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; } lib$es6$promise$polyfill$$default(); }).call(this); // parseUri 1.2.2 // (c) Steven Levithan <stevenlevithan.com> // MIT License // L.Pelov - this works in all situations and in the browsers since IE9+ // http://blog.stevenlevithan.com/archives/parseuri function parseUri(str) { var o = parseUri.options, m = o.parser[o.strictMode ? "strict" : "loose"].exec(str), uri = {}, i = 14; while (i--) uri[o.key[i]] = m[i] || ""; uri[o.q.name] = {}; uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { if ($1) uri[o.q.name][$1] = $2; }); return uri; }; parseUri.options = { strictMode: false, key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"], q: { name: "queryKey", parser: /(?:^|&)([^&=]*)=?([^&]*)/g }, parser: { strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ } }; /** * https://github.com/pillarjs/path-to-regexp * MIT License * * L.Pelov - Oracle A-Team, transformed the code to work in the browser! * @version 1.5.3 */ // polyfills var toString = Object.prototype.toString; var isarray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; }; /** * The main path matching regexp utility. * * @type {RegExp} */ var PATH_REGEXP = new RegExp([ // Match escaped characters that would otherwise appear in future matches. // This allows the user to escape special characters that won't transform. '(\\\\.)', // Match Express-style parameters and un-named parameters with a prefix // and optional suffixes. Matches appear as: // // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined] // "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined] // "/*" => ["/", undefined, undefined, undefined, undefined, "*"] '([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))' ].join('|'), 'g') /** * Parse a string for the raw tokens. * * @param {string} str * @return {!Array} */ function parse (str) { var tokens = [] var key = 0 var index = 0 var path = '' var res while ((res = PATH_REGEXP.exec(str)) != null) { var m = res[0] var escaped = res[1] var offset = res.index path += str.slice(index, offset) index = offset + m.length // Ignore already escaped sequences. if (escaped) { path += escaped[1] continue } var next = str[index] var prefix = res[2] var name = res[3] var capture = res[4] var group = res[5] var modifier = res[6] var asterisk = res[7] // Push the current path onto the tokens. if (path) { tokens.push(path) path = '' } var partial = prefix != null && next != null && next !== prefix var repeat = modifier === '+' || modifier === '*' var optional = modifier === '?' || modifier === '*' var delimiter = res[2] || '/' var pattern = capture || group || (asterisk ? '.*' : '[^' + delimiter + ']+?') tokens.push({ name: name || key++, prefix: prefix || '', delimiter: delimiter, optional: optional, repeat: repeat, partial: partial, asterisk: !!asterisk, pattern: escapeGroup(pattern) }) } // Match any characters still remaining. if (index < str.length) { path += str.substr(index) } // If the path exists, push it onto the end. if (path) { tokens.push(path) } return tokens } /** * Compile a string to a template function for the path. * * @param {string} str * @return {!function(Object=, Object=)} */ function compile (str) { return tokensToFunction(parse(str)) } /** * Prettier encoding of URI path segments. * * @param {string} * @return {string} */ function encodeURIComponentPretty (str) { return encodeURI(str).replace(/[\/?#]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() }) } /** * Encode the asterisk parameter. Similar to `pretty`, but allows slashes. * * @param {string} * @return {string} */ function encodeAsterisk (str) { return encodeURI(str).replace(/[?#]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() }) } /** * Expose a method for transforming tokens into the path function. */ function tokensToFunction (tokens) { // Compile all the tokens into regexps. var matches = new Array(tokens.length) // Compile all the patterns before compilation. for (var i = 0; i < tokens.length; i++) { if (typeof tokens[i] === 'object') { matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$') } } return function (obj, opts) { var path = '' var data = obj || {} var options = opts || {} var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent for (var i = 0; i < tokens.length; i++) { var token = tokens[i] if (typeof token === 'string') { path += token continue } var value = data[token.name] var segment if (value == null) { if (token.optional) { // Prepend partial segment prefixes. if (token.partial) { path += token.prefix } continue } else { throw new TypeError('Expected "' + token.name + '" to be defined') } } if (isarray(value)) { if (!token.repeat) { throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`') } if (value.length === 0) { if (token.optional) { continue } else { throw new TypeError('Expected "' + token.name + '" to not be empty') } } for (var j = 0; j < value.length; j++) { segment = encode(value[j]) if (!matches[i].test(segment)) { throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`') } path += (j === 0 ? token.prefix : token.delimiter) + segment } continue } segment = token.asterisk ? encodeAsterisk(value) : encode(value) if (!matches[i].test(segment)) { throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"') } path += token.prefix + segment } return path } } /** * Escape a regular expression string. * * @param {string} str * @return {string} */ function escapeString (str) { return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1') } /** * Escape the capturing group by escaping special characters and meaning. * * @param {string} group * @return {string} */ function escapeGroup (group) { return group.replace(/([=!:$\/()])/g, '\\$1') } /** * Attach the keys as a property of the regexp. * * @param {!RegExp} re * @param {Array} keys * @return {!RegExp} */ function attachKeys (re, keys) { re.keys = keys return re } /** * Get the flags for a regexp from the options. * * @param {Object} options * @return {string} */ function flags (options) { return options.sensitive ? '' : 'i' } /** * Pull out keys from a regexp. * * @param {!RegExp} path * @param {!Array} keys * @return {!RegExp} */ function regexpToRegexp (path, keys) { // Use a negative lookahead to match only capturing groups. var groups = path.source.match(/\((?!\?)/g) if (groups) { for (var i = 0; i < groups.length; i++) { keys.push({ name: i, prefix: null, delimiter: null, optional: false, repeat: false, partial: false, asterisk: false, pattern: null }) } } return attachKeys(path, keys) } /** * Transform an array into a regexp. * * @param {!Array} path * @param {Array} keys * @param {!Object} options * @return {!RegExp} */ function arrayToRegexp (path, keys, options) { var parts = [] for (var i = 0; i < path.length; i++) { parts.push(pathToRegexp(path[i], keys, options).source) } var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options)) return attachKeys(regexp, keys) } /** * Create a path regexp from string input. * * @param {string} path * @param {!Array} keys * @param {!Object} options * @return {!RegExp} */ function stringToRegexp (path, keys, options) { var tokens = parse(path) var re = tokensToRegExp(tokens, options) // Attach keys back to the regexp. for (var i = 0; i < tokens.length; i++) { if (typeof tokens[i] !== 'string') { keys.push(tokens[i]) } } return attachKeys(re, keys) } /** * Expose a function for taking tokens and returning a RegExp. * * @param {!Array} tokens * @param {Object=} options * @return {!RegExp} */ function tokensToRegExp (tokens, options) { options = options || {} var strict = options.strict var end = options.end !== false var route = '' var lastToken = tokens[tokens.length - 1] var endsWithSlash = typeof lastToken === 'string' && /\/$/.test(lastToken) // Iterate over the tokens and create our regexp string. for (var i = 0; i < tokens.length; i++) { var token = tokens[i] if (typeof token === 'string') { route += escapeString(token) } else { var prefix = escapeString(token.prefix) var capture = '(?:' + token.pattern + ')' if (token.repeat) { capture += '(?:' + prefix + capture + ')*' } if (token.optional) { if (!token.partial) { capture = '(?:' + prefix + '(' + capture + '))?' } else { capture = prefix + '(' + capture + ')?' } } else { capture = prefix + '(' + capture + ')' } route += capture } } // In non-strict mode we allow a slash at the end of match. If the path to // match already ends with a slash, we remove it for consistency. The slash // is valid at the end of a path match, not in the middle. This is important // in non-ending mode, where "/test/" shouldn't match "/test//route". if (!strict) { route = (endsWithSlash ? route.slice(0, -2) : route) + '(?:\\/(?=$))?' } if (end) { route += '$' } else { // In non-ending mode, we need the capturing groups to match as much as // possible by using a positive lookahead to the end or next path segment. route += strict && endsWithSlash ? '' : '(?=\\/|$)' } return new RegExp('^' + route, flags(options)) } /** * Normalize the given path string, returning a regular expression. * * An empty array can be passed in for the keys, which will hold the * placeholder key descriptions. For example, using `/user/:id`, `keys` will * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`. * * @param {(string|RegExp|Array)} path * @param {(Array|Object)=} keys * @param {Object=} options * @return {!RegExp} */ function pathToRegexp (path, keys, options) { keys = keys || [] if (!isarray(keys)) { options = /** @type {!Object} */ (keys) keys = [] } else if (!options) { options = {} } if (path instanceof RegExp) { return regexpToRegexp(path, /** @type {!Array} */ (keys)) } if (isarray(path)) { return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options) } return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options) } // uuid.js // // Copyright (c) 2010-2012 Robert Kieffer // MIT License - http://opensource.org/licenses/mit-license.php // // https://github.com/broofa/node-uuid /** * Generate a v4 (random) id * uuid.v4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' */ /*global window, require, define */ (function(_window) { 'use strict'; // Unique ID creation requires a high quality random # generator. We feature // detect to determine the best RNG source, normalizing to a function that // returns 128-bits of randomness, since that's what's usually required var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot; function setupBrowser() { // Allow for MSIE11 msCrypto var _crypto = _window.crypto || _window.msCrypto; if (!_rng && _crypto && _crypto.getRandomValues) { // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto // // Moderately fast, high quality try { var _rnds8 = new Uint8Array(16); _whatwgRNG = _rng = function whatwgRNG() { _crypto.getRandomValues(_rnds8); return _rnds8; }; _rng(); } catch(e) {} } if (!_rng) { // Math.random()-based (RNG) // // If all else fails, use Math.random(). It's fast, but is of unspecified // quality. var _rnds = new Array(16); _mathRNG = _rng = function() { for (var i = 0, r; i < 16; i++) { if ((i & 0x03) === 0) { r = Math.random() * 0x100000000; } _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; } return _rnds; }; if ('undefined' !== typeof console && console.warn) { console.warn("[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()"); } } } function setupNode() { // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html // // Moderately fast, high quality if ('function' === typeof require) { try { var _rb = require('crypto').randomBytes; _nodeRNG = _rng = _rb && function() {return _rb(16);}; _rng(); } catch(e) {} } } if (_window) { setupBrowser(); } else { setupNode(); } // Buffer class to use var BufferClass = ('function' === typeof Buffer) ? Buffer : Array; // Maps for number <-> hex string conversion var _byteToHex = []; var _hexToByte = {}; for (var i = 0; i < 256; i++) { _byteToHex[i] = (i + 0x100).toString(16).substr(1); _hexToByte[_byteToHex[i]] = i; } // **`parse()` - Parse a UUID into it's component bytes** function parse(s, buf, offset) { var i = (buf && offset) || 0, ii = 0; buf = buf || []; s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) { if (ii < 16) { // Don't overflow! buf[i + ii++] = _hexToByte[oct]; } }); // Zero out remaining bytes if string was short while (ii < 16) { buf[i + ii++] = 0; } return buf; } // **`unparse()` - Convert UUID byte array (ala parse()) into a string** function unparse(buf, offset) { var i = offset || 0, bth = _byteToHex; return bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + '-' + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]]; } // **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html // random #'s we need to init node and clockseq var _seedBytes = _rng(); // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) var _nodeId = [ _seedBytes[0] | 0x01, _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5] ]; // Per 4.2.2, randomize (14 bit) clockseq var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff; // Previous uuid creation time var _lastMSecs = 0, _lastNSecs = 0; // See https://github.com/broofa/node-uuid for API details function v1(options, buf, offset) { var i = buf && offset || 0; var b = buf || []; options = options || {}; var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq; // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. var msecs = (options.msecs != null) ? options.msecs : new Date().getTime(); // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq == null) { clockseq = clockseq + 1 & 0x3fff; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) { nsecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested if (nsecs >= 10000) { throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); } _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; // `time_low` var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff; // `time_mid` var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff; // `time_high_and_version` b[i++] = tmh >>> 24 & 0xf | 0x10; // include version b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` b[i++] = clockseq & 0xff; // `node` var node = options.node || _nodeId; for (var n = 0; n < 6; n++) { b[i + n] = node[n]; } return buf ? buf : unparse(b); } // **`v4()` - Generate random UUID** // See https://github.com/broofa/node-uuid for API details function v4(options, buf, offset) { // Deprecated - 'format' argument, as supported in v1.2 var i = buf && offset || 0; if (typeof(options) === 'string') { buf = (options === 'binary') ? new BufferClass(16) : null; options = null; } options = options || {}; var rnds = options.random || (options.rng || _rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = (rnds[6] & 0x0f) | 0x40; rnds[8] = (rnds[8] & 0x3f) | 0x80; // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ii++) { buf[i + ii] = rnds[ii]; } } return buf || unparse(rnds); } // Export public API var uuid = v4; uuid.v1 = v1; uuid.v4 = v4; uuid.parse = parse; uuid.unparse = unparse; uuid.BufferClass = BufferClass; uuid._rng = _rng; uuid._mathRNG = _mathRNG; uuid._nodeRNG = _nodeRNG; uuid._whatwgRNG = _whatwgRNG; if (('undefined' !== typeof module) && module.exports) { // Publish as node.js module module.exports = uuid; } else if (typeof define === 'function' && define.amd) { // Publish as AMD module define(function() {return uuid;}); } else { // Publish as global (in browsers) _previousRoot = _window.uuid; // **`noConflict()` - (browser only) to reset global 'uuid' var** uuid.noConflict = function() { _window.uuid = _previousRoot; return uuid; }; _window.uuid = uuid; } })('undefined' !== typeof window ? window : null); // POLYFILLS! /** * Polyfill in case we want to support browser IE8 and lower, all IE9+ browsers support this * out of box already */ if (!Array.isArray) { Array.isArray = function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; } if (!Array.prototype.findIndex) { Array.prototype.findIndex = function (predicate) { if (this === null) { throw new TypeError('Array.prototype.findIndex called on null or undefined'); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var list = Object(this); var length = list.length >>> 0; var thisArg = arguments[1]; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return i; } } return -1; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (fun/*, thisArg*/) { 'use strict'; if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } /** * Wrapper module with most common used functions from 3rd party frameworks! * * @type {{isEmpty, isArray, isFunction, isObject, isNull, extendOwn, extend}} */ function persistenceCommon() { 'use strict'; var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; var push = ArrayProto.push, slice = ArrayProto.slice, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind, nativeCreate = Object.create; return { isEmpty: isEmpty, isArray: isArray, isFunction: isFunction, isObject: isObject, isNull: isNull, isNumber: isNumber, isDate: isDate, isString: isString, isUndefined: isUndefined, has: has, isFinite: isFinite, isNaN: isNaN, isBoolean: isBoolean, deepExtend: deepExtend, extendOwn: extender(false), extend: extender(true), getUID: getUID, clone: clone, stringStartsWith: stringStartsWith, stringEndsWith: stringEndsWith, type: type, cleanObjects: cleanObjects, cleanObject: cleanObject }; /** * Checks given object type. This implementation is faster than using JS typeof(). * * Support: IE8+ * @param obj - could be number, string, function, boolean, null and so on * @returns {string} - string representative of the object type * http://youmightnotneedjquery.com/ */ function type(obj) { return Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase(); } /** * Checks if string starts with specific prefix! * * @param string * @param prefix * @returns {boolean} - returns also false when provided variable is not string! */ function stringStartsWith(string, prefix) { if (type(string) !== 'string') return false; return string.slice(0, prefix.length) == prefix; } /** * Checks if string ends with specific prefix! * * @param string * @param suffix * @returns {boolean} - false also when the provided variable is not string! */ function stringEndsWith(string, suffix) { if (type(string) !== 'string') return false; return suffix == '' || string.slice(-suffix.length) == suffix; } /** * Clones given JS object using the JSON stringify method to create new reference. * * @param obj * @returns {*} */ function clone(obj) { obj = obj || {}; var cloneObjects = true; return cloneObjects ? JSON.parse(JSON.stringify(obj)) : obj; } function cleanObjects(objects) { var result = []; for (var idx in objects) { // clean the object and return in the way the MCS would do! if (objects.hasOwnProperty(idx)) { var object = cleanObject(objects[idx]); result.push(object); } } return result; } function cleanObject(object) { var cloned = clone(object); // it's actually clear that this is from the DB delete cloned['$loki']; delete cloned['meta']; return cloned; } function getUID() { return Math.floor(Math.random() * 0x100000000); } function isTypeOf(name, obj) { return toString.call(obj) === '[object ' + name + ']'; } function isDate(value) { return isTypeOf('Date', value); } function isString(value) { return isTypeOf('String', value); } function isUndefined(value) { //return typeof value === 'undefined'; return value === void 0; } function has(obj, key) { return obj != null && hasOwnProperty.call(obj, key); } // Is a given object a finite number? function isFinite(value) { return isFinite(value) && !isNaN(parseFloat(value)); } // Is the given value `NaN`? (NaN is the only number which does not equal itself). function isNaN(value) { return isNumber(value) && value !== +value; } // Is a given value a boolean? function isBoolean(value) { return value === true || value === false || toString.call(value) === '[object Boolean]'; } function isEmpty(value) { if (value === null) { return true; } // check if the value has length if (isArrayLike(value) && (isArray(value) || typeof value === 'string' // is string || isFunction(value.splice) // is array || isFunction(value.callee))) { // is arguments return !value.length; } // check if the object iis set or map if (!!value && typeof value == 'object') { var str = value.toString(); if (str == '[object Map]' || str == '[object Set]') { return !value.size; } } // check if the object has properties for (var key in value) { if (value.hasOwnProperty(key)) { return false; } } if(!!value && isNumber(value)){ return false; } return true; } function isArrayLike(value) { return value && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && value.length % 1 === 0; } function isArray(value) { return Array.isArray(value); } function isFunction(value) { // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, // IE 11 (#1621), and in Safari 8 (#1929). return typeof value === "function" || false; } function isObject(value) { var type = typeof value; return type === 'function' || type === 'object' && !!value; } function isNull(value) { return value === null; } function isNumber(value) { if (typeof value == 'number') { return true; } return value.toString() == '[object Number]'; } /** * Copy the properties from one object to another, however this function does NOT have the deep copy * capabilities. * * @param allKeys * @returns {Function} */ function extender(allKeys) { return function (object) { var argLength = arguments.length; if (object == null || argLength < 2) { return object; } // run on all argument except first one for (var argIndex = 1; argIndex < argLength; argIndex++) { var source = arguments[argIndex]; if (source && isObject(source)) { for (var key in source) { if (allKeys || source.hasOwnProperty(key)) { object[key] = source[key]; } } } } return object; } } function identity(value) { return value; } /** * Deep extend capabilities taken from the JQuery implementation! * @returns {*|{}} */ function deepExtend() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, class2type = { "[object Boolean]": "boolean", "[object Number]": "number", "[object String]": "string", "[object Function]": "function", "[object Array]": "array", "[object Date]": "date", "[object RegExp]": "regexp", "[object Object]": "object" }, jQuery = { isFunction: function (obj) { return jQuery.type(obj) === "function" }, isArray: Array.isArray || function (obj) { return jQuery.type(obj) === "array" }, isWindow: function (obj) { return obj != null && obj == obj.window }, isNumeric: function (obj) { return !isNaN(parseFloat(obj)) && isFinite(obj) }, type: function (obj) { return obj == null ? String(obj) : class2type[toString.call(obj)] || "object" }, isPlainObject: function (obj) { if (!obj || jQuery.type(obj) !== "object" || obj.nodeType) { return false } try { if (obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) { return false } } catch (e) { return false } var key; for (key in obj) { } return key === undefined || hasOwn.call(obj, key) } }; if (typeof target === "boolean") { deep = target; target = arguments[1] || {}; i = 2; } if (typeof target !== "object" && !jQuery.isFunction(target)) { target = {} } if (length === i) { target = this; --i; } for (i; i < length; i++) { if ((options = arguments[i]) != null) { for (name in options) { src = target[name]; copy = options[name]; if (target === copy) { continue } if (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : [] } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // WARNING: RECURSION target[name] = deepExtend(deep, clone, copy); } else if (copy !== undefined) { target[name] = copy; } } } } return target; } } function persistenceUtils($common, $options) { 'use strict'; var _ = $common; /** * This simple implementation will check if specific path match and URL for persistence and return * object with all parameters. * * @param options * @returns {Function} * @throws Error - in case decoding of given parameter is not possible */ var pathMatch = function (options) { options = options || {}; return function (path) { var keys = []; var re = pathToRegexp(path, keys, options); return function (pathname, params) { var m = re.exec(pathname); if (!m) return false; // FIX: L.Pelov - use array to address that some properties could have same names params = params || []; var key, param, obj = {};; for (var i = 0; i < keys.length; i++) { key = keys[i]; param = m[i + 1]; if (!param) continue; obj = { name: key.name, value: decodeParam(param) } //params[key.name] = decodeParam(param); params.push(obj); if (key.repeat) { //params[key.name] = params[key.name].split(key.delimiter) params[params.length - 1].name = params[params.length - 1].name.split(key.delimiter) } } return params; } } }; /** * Decodes parameters from the url * * @param param * @returns {string} */ function decodeParam(param) { try { return decodeURIComponent(param); } catch (e) { throw Error('failed to decode param "' + param + '"'); } } /** * Cache in-memory all already parsed URLs! * @type {{}} */ var isPersistUrlCache = {}; /** * isPathConfiguredForPersistence method result * @callback Persistence.Sync~isPathConfiguredForPersistenceResult * @param url {String}. * @param match {Array} parsed matches. */ /** * Checks based on the pre-prefigured regexp in Persistence.Options if URL was configured for persistence. * * @param path {String} Url to check * @returns {Persistence.Sync~isPathConfiguredForPersistenceResult} - parsed url regexp and parsed matches */ var isPathConfiguredForPersistence = function (path) { if (path == null || typeof path !== 'string') { console.warn('isPersistentUrl -> path can be only string'); return false; } // check the cache first! if (path in isPersistUrlCache) { return isPersistUrlCache[path]; } var len = $options.persistUris.length, i = 0; //var re = pathToRegexp(['/api/v2/users', '/api/v1/users/:id(\\d+)?/:_path?/:name?'], [], {sensitive: true}); // go through the array and exec the given array of path for (; i < len; i++) { //var re = pathToRegexp($options.persistUris[i].reg, [], {sensitive: true}); var match = $options.persistUris[i].reg.exec(path); //var match = re.exec(url); // we have a much so this URL is configured for caching! if (match) { return isPersistUrlCache[path] = { uri: $options.persistUris[i], match: match } } } return isPersistUrlCache[path] = false; }; /** * Cache the parsed values for given URLs! * * @type {{}} */ var keyValuesFromPersistentUrlCache = {}; function isUrlRegexInteger(str) { return (str.indexOf('\d') >= 0) ? true : false } function nestedUrlPropertyToValue(prop) { if (!prop && !prop.value) return ""; return prop.isInteger ? parseInt(prop.value) : prop.value; } /** * Parse the URL parameters and store in the cache! * @param persistURL * @returns {*} */ function extractKeyValuesFromPersistentUrl2(persistURL) { // check the cache first! if (persistURL.match[0] in keyValuesFromPersistentUrlCache) { return keyValuesFromPersistentUrlCache[persistURL.match[0]]; } // get the tokens to use for CRUID operations against the DB! var query = { root: persistURL.uri.tokens[0], attr: [] }; var keys = persistURL.uri.tokens; var parsedKeys = 1; // first token is always the root path! go directly to the next one for (var pos = 1; pos < keys.length; pos++) { if (_.isObject(persistURL.uri.tokens[pos])) { var matchId = parsedKeys++; var interName = persistURL.uri.tokens[pos]; if (persistURL.match[matchId]) query.attr.push({ name: _.stringStartsWith(interName.name, '/') || _.stringStartsWith(interName.name, '_') ? interName.name.substring(1) : interName.name, // FIX: the real name is without the first chart, that indicates that this is obj property value: persistURL.match[matchId], pattern: interName.pattern, is: !!(_.stringStartsWith(interName.name, '/') || _.stringStartsWith(interName.name, '_')), isInteger: isUrlRegexInteger(interName.pattern) }); } else { // BUT if not then is just a property, so pass to the next one var interName = persistURL.uri.tokens[pos]; if (interName) query.attr.push({ name: interName, value: _.stringStartsWith(interName, '/') || _.stringStartsWith(interName, '_') ? interName.substring(1) : interName, is: false, isInteger: isUrlRegexInteger(interName) }); } } return keyValuesFromPersistentUrlCache[persistURL.match[0]] = query; } /** * Use this to transform payload before send to the server, in case that the payload is not JSON! * * @param payload * @returns {string} */ function transformQueryParams(payload) { var array = []; for (var key in payload) { array.push(encodeURIComponent(key) + "=" + encodeURIComponent(payload[key])); } return array.join("&"); } /** * Set the value to the object depending on the type of the existing object and the given new value! * * @param obj - existing object, usually from the db * @param val - new payload data to set to the existing object! */ function setValueToObject(obj, val) { // if array and the payload is only 1 object, then add to the array! // if array and the new payload also array then replace the array // if object and the payload array replace // if object and the payload object replace! // generally if the val is function, and this could happen for example when usign knockout or such throw error if ($common.isFunction(val)) { throw new Error('unknown payload object, cannot assign function to payload!'); } // TODO: Actually we should go over the array and check if the new payload has repeating elements and modify if (Array.isArray(obj) && Array.isArray(val)) { obj = val; } else if (Array.isArray(obj) && (!Array.isArray(val) && $common.isObject(val))) { obj.push(val); } else { obj = val; } return obj; } /** * Set new attribute to the existing object or update if exist. * Examples: * setData("key1", "updated value1"); // data.key1 == "updated value1" * setData("key2.nested1", 99); // data.key2.nested1 == 99 * * @param key * @param val * @param obj * @private */ var _setData = function (key, val, obj) { if (!obj) obj = {}; //outside (non-recursive) call, use "data" as our base object var ka = key.split(/\./); //split the key by the dots if (ka.length < 2) { obj[ka[0]] = val; //only one part (no dots) in key, just set value } else { if (!obj[ka[0]]) obj[ka[0]] = {}; //create our "new" base obj if it doesn't exist obj = obj[ka.shift()]; //remove the new "base" obj from string array, and hold actual object for recursive call _setData(ka.join("."), val, obj); //join the remaining parts back up with dots, and recursively set data on our new "base" obj } }; /** * * @param key * @param val * @param obj * @private */ var _setData2 = function (key, val, obj) { if (!obj) obj = {}; //outside (non-recursive) call, use "data" as our base object var ka = key.split(/\./); //split the key by the dots if (ka.length < 2) { // TODO: If the object does not exist you can do this directly, but if it exist, we have to check // if we want to replace that data and in which way! if (!obj[ka[0]]) { obj[ka[0]] = val; } else { //setValueToObject(obj[ka[0]], val); if (Array.isArray(obj[ka[0]]) && Array.isArray(val)) { obj[ka[0]] = val; } else if (Array.isArray(obj[ka[0]]) && (!Array.isArray(val) && $common.isObject(val))) { obj[ka[0]].push(val); } else { obj[ka[0]] = val; } } } else { if (!obj[ka[0]]) obj[ka[0]] = {}; //create our "new" base obj if it doesn't exist obj = obj[ka.shift()]; //remove the new "base" obj from string array, and hold actual object for recursive call _setData(ka.join("."), val, obj); //join the remaining parts back up with dots, and recursively set data on our new "base" obj } }; /** * Get value from nested JSON object payload * @param key * @param obj * @returns {*} * @private */ var _getData = function (key, obj) { if (!obj) return {}; //outside (non-recursive) call, use "data" as our base object var ka = key.split(/\./); //split the key by the dots if (ka.length < 2) { return obj[ka[0]]; //only one part (no dots) in key, just set value } else { if (!obj[ka[0]]) return {}; //create our "new" base obj if it doesn't exist obj = obj[ka.shift()]; //remove the new "base" obj from string array, and hold actual object for recursive call _getData(ka.join("."), obj); //join the remaining parts back up with dots, and recursively set data on our new "base" obj } } var isOfflinePersistObj = function (obj) { if ('meta' in obj && obj.meta.hasOwnProperty('offline-persist')) { return true; } return false; }; /** * Property structure * @typedef persistenceUtils~Property * @property name {String} name of property * @property value {String} value of property * @property isProperty {Boolean} show if this is a property (:_property) or an id (:id(\\d+)) * @property isInteger {Boolean} show if property value is integer */ /** * Check if given object has specific (nested)property and set the given value to that payload. In case that the value * of the nested property is Array, will try to find for given key:value and replace it, if not exist, add to it. * @deprecated * @param object - usually a object from the DB * @param property {persistenceUtils~Property} property structure to search into * @param value - payload usually from the REST call * @returns {*} - the final object */ function setNestedProperty(object, property, value) { if (object && typeof object == "object") { if (typeof property == "string" && property !== "") { //var isOfflineObj = isOfflinePersistObj(object); var split = property.split("."); return split.reduce(function (obj, prop, idx) { //console.log(obj, prop, idx); var keyValue = { name: null, value: null }; var propMatch = prop.match(/\[(.*?)\]/); if (!propMatch) { obj[prop] = obj[prop] || {}; } else { keyValue.name = prop.substr(0, prop.indexOf('[')); keyValue.value = propMatch[1]; } // do this only if this is the last element! if (split.length == (idx + 1)) { // the question is if there is key[value] or NOT! if (propMatch) { // ok here we have to check what the current object seams to be, but we would expect array! if (Array.isArray(obj)) { var index = obj.findIndex(function (item) { return item[keyValue.name] == keyValue.value; }); return (index > -1) ? _.deepExtend(value, obj[index]) : obj.push(value); } else { // handle as object! if (obj[keyValue.name] == keyValue.value) { return _.deepExtend(value, obj[keyValue.name]); } else { // that's a problem this object does not exist, create and add the payload obj[keyValue.name] = keyValue.value; return _.deepExtend(value, obj); } } } // handle usual property! else { return obj[prop] = value; } } if (propMatch) { if (Array.isArray(obj)) { var index = obj.findIndex(function (item) { item[keyValue.name] = keyValue.value; }); return (index > -1) ? obj[index] : {}; } else { // handle as object! if (obj[keyValue.name] == keyValue.value) { return obj[keyValue.name]; } else { // that's a problem this object does not exist, create it and add the payload, then return! return obj[keyValue.name] = keyValue.value; } } } else { return obj[prop]; } }, object); } else { return object; } } else { return object; } } /** * This should be the new way to go, using object directly, provides more stable logic! * * @param object * @param property {Array<persistenceRequestHandler~Property>} - property structure to search into: * { * name: String, * value: String, * isProperty: true/false, * isInteger: true/false * } * @param value * @returns {*} */ function setNestedProperty2(object, property, value) { if (!object || typeof object !== 'object') return object; if (!_.isArray(property) || !property.length > 0) return object; //var isOfflineObj = isOfflinePersistObj(object); return property.reduce(function (obj, prop, idx) { if (prop.isProperty) { obj[prop.name] = obj[prop.name] || []; } // do this only if this is the last element! if (property.length == (idx + 1)) { // the question is if there is key[value] or NOT! if (!prop.isProperty) { // ok here we have to check what the current object seams to be, but we would expect array! if (Array.isArray(obj)) { var index = obj.findIndex(function (item) { return item[prop.name] == nestedUrlPropertyToValue(prop); }); // if this item already exists in array, just update it if(index > -1){ _.deepExtend(obj[index], value); } else { value[prop.name] = nestedUrlPropertyToValue(prop); obj.push(value); } return value; } else { // handle as object! if (obj[prop.name] == nestedUrlPropertyToValue(prop)) { _.deepExtend(obj, value); return value; } else { // that's a problem this object does not exist, create and add the payload obj[prop.name] = nestedUrlPropertyToValue(prop); _.deepExtend(obj, value); return value; } } } // handle usual property with array value! else if(Array.isArray(value)) { obj[prop.name] = value; return value; } // handle usual property else { obj[prop.name].push(value); return value; } } // END if (!prop.isProperty) { if (Array.isArray(obj)) { var index = obj.findIndex(function (item) { item[prop.name] = nestedUrlPropertyToValue(prop); }); return (index > -1) ? obj[index] : {}; } else { // handle as object! if (obj[prop.name] == nestedUrlPropertyToValue(prop)) { return obj; } else { // that's a problem this object does not exist, create it and add the payload, then return! return obj[prop.name] = nestedUrlPropertyToValue(prop); } } } else { return obj[prop.name]; } }, object); } /** * Search for (nested)property in the given object! * * @param object - usually from the offline db * @param property - property to search for in the form: prop1.prop2[value1].prop3.... * @returns {*} */ function getNestedProperty(object, property) { if (!object || typeof object !== 'object') return object; if (!_.isArray(property) || !property.length > 0) return object; //var split = property.split("."); return property.reduce(function (obj, prop) { // check if this is key[value] property! //var propMatch = prop.match(/\[(.*?)\]/); if (prop.isProperty) { return obj && obj[prop.name]; } else { var keyValue = { name: prop.name, value: nestedUrlPropertyToValue(prop) }; // if the current obj is array, search into the array! if (Array.isArray(obj) && !prop.isProperty) { var index = obj.findIndex(function (item) { return item[keyValue.name] == keyValue.value; }); // return the given element or the current object or in case of sub property into that array! return (index > -1) ? obj[index] : (obj[keyValue.name] && obj); } else if (!prop.isProperty) { return (obj[keyValue.name] == keyValue.value) ? obj : (obj[keyValue.name] && obj); } else { return obj && obj[keyValue.name]; } } }, object); } /** * Match url with wild cards! * * Example: * var matchUrl = 'http://localhost:3000/internals/todo1'; * var excludeUri = ['http://localhost:3000/internals/*', 'http://localhost:3000/internals/todo3']; * * for (var url in excludeUri) { * console.log(matchUri(matchUrl, excludeUri[url])); * } * * @param str * @param rule * @returns {boolean} */ function matchUri(str, rule) { return new RegExp("^" + rule.replace("*", ".*") + "$").test(str); } /** * Parse XHR returned headers. * * Link: https://jsperf.com/parse-response-headers-from-xhr * * @param headerStr * @returns {{}} * @private */ function _parseResponseHeaders(headerStr) { var headers = {}; if (!headerStr) { return headers; } var headerPairs = headerStr.split('\u000d\u000a'); for (var i = 0, ilen = headerPairs.length; i < ilen; i++) { var headerPair = headerPairs[i]; var index = headerPair.indexOf('\u003a\u0020'); if (index > 0) { headers[headerPair.substring(0, index).toLowerCase()] = headerPair.substring(index + 2); } } return headers; } /** * Check if given link is configured for persistent. The host in the URL does not play a role, you can pass values * like http://server:port/path1/path2 or just /path1/path2 * * @param url * @returns {{uri, match}} */ function isPersistentURL(url) { var parsed = $options.parseURL(url); return isPathConfiguredForPersistence(parsed.path); } function _isURLConfiguredForPersistence(path, returnUrl) { // check if this URL was configured for sync operations var url = isPersistentURL(path); // do no work if the URL is not configured for persistence! if (_.isEmpty(url) || url === false) { throw new Error('give url was configured for persistence:' + path); } // extract the root and get the collections data if (!returnUrl) { return extractKeyValuesFromPersistentUrl2(url); } return url; } /** * Makes sure that it cleans the sync log object form the database form DB specific arguments. * * @param obj - object should be passed by value! * @param cloneObject - boolean value to notify if object should be clone! */ function cleanSyncLogObjectFromDBSpecificProperties(obj, cloneObject) { var _obj = cloneObject ? JSON.parse(JSON.stringify(obj)) : obj; if (_obj.hasOwnProperty('$loki') && typeof(_obj.$loki) === 'number' && !isNaN(_obj.$loki)) { delete _obj.$loki; } if (_obj.hasOwnProperty('meta')) { delete _obj.meta; } return _obj; } /** * Checks if the application runs in a web view! * @returns {boolean} Check if we are running within a WebView (such as Cordova). */ function _isWebView() { return !(!window.cordova && !window.PhoneGap && !window.phonegap && !window.forge); } function _isMcsSyncResourceType(xhr) { return true;// TODO: check this return var isMCS = false; try { var response = function (path) { return $options.getUrlCache(path); }; if (xhr == null) return response(xhr.responseURL); if (typeof xhr.getResponseHeader !== 'function') return response(xhr.responseURL); // this header identifies if the MCS response was using MSC Sync in the Custom Code isMCS = xhr.getResponseHeader('Oracle-Mobile-Sync-Resource-Type'); if (isMCS) { isMCS = true; // so next time when GET operation and dbFirst=true we can use the proper parse! return $options.setUrlCache({url: xhr.responseURL, mcs: true}); } else { return $options.setUrlCache({url: xhr.responseURL, mcs: false}); } return isMCS; } catch (e) { console.error('error during checking the MCS headers', e); return $options.setUrlCache({url: xhr.responseURL, mcs: false}); //return isMCS; } } /** * Checks if given object has the parsing method implemented for the HTTP method * @param obj * @param method * @returns {boolean} * @private */ function _isSupportedHTTPMethod(obj, method) { if (obj.hasOwnProperty(_normalizeMethod(method))) { return true; } return false; } // allowed methods! var methods = ['delete', 'get', 'head', 'options', 'post', 'put', 'patch']; function _normalizeMethod(method) { var upcased = method.toLowerCase(); return (methods.indexOf(upcased) > -1) ? upcased : method; } function _isLokiDbObj(obj) { if ('$loki' in obj && typeof(obj.$loki) === 'number' && !isNaN(obj.$loki)) { return true; } return false; } // public functions return { isPersistUrl: isPathConfiguredForPersistence, isPersistentURL: isPersistentURL, extractKeyValuesFromUrl2: extractKeyValuesFromPersistentUrl2, param: transformQueryParams, setData: _setData, parseResponseHeaders: _parseResponseHeaders, cleanSyncLogObjectFromDBSpecificProperties: cleanSyncLogObjectFromDBSpecificProperties, isWebView: _isWebView, isURLConfiguredForPersistence: _isURLConfiguredForPersistence, pathToMatch: pathMatch, isMcsSyncResourceType: _isMcsSyncResourceType, isSupportedHTTPMethod: _isSupportedHTTPMethod, normalizeMethod: _normalizeMethod, isLokiDbObj: _isLokiDbObj, isUrlRegexInteger: isUrlRegexInteger, setNestedProperty2: setNestedProperty2, getNestedProperty: getNestedProperty } } // TODO: L.Pelov - Reveal only the getters and setters /** * Module contains all public settings for the persistence library * revealing module with getter and setters! */ function persistenceOptions($common) { 'use strict'; // replace underscore with own implementation var _ = $common; var $db = null; var dbFirst = true; var isCordova = typeof window.cordova != 'undefined'; // default timeouts var timeout = 30000; // 30s, var syncTimeout = 30000; // 30s // use this to test if URL should be persisted var isPersistUri = {}; // set URI to be persisted, otherwise nothing is persisted var persistUri = []; // In-Memory cache for all checked persistent URLs var isPersistUrlCache = {}; var parseUrlCache = {}; // make sure that we have only one On, otherwise always off!!! var on = null; var passOne = false; var alwayson = true; // turn off var alwaysoff = false; var dbFirstFalseForNextCallBool = false; var maxsyncattempts = 0; // by default unlimited var autoremoveafterreachmaxattemps = false; var autoSync = false; //var workerlocation = 'persistence.worker.js'; var offlinedbname = 'offline'; var synclogdbname = 'synclog'; var dbprefix = 'persist'; var dbprefixchangehandler = function (oldval, newval) { console.log(' changed from ' + oldval + ' to ' + newval); return newval; }; // unit tests mode var isTest = false; // set which module should be used for the payload parsing! var module = null; /** * If not set the default is: PERIODIC_REFRESH_POLICY_REFRESH_NONE * * NOTE: http://docs.oracle.com/cloud/latest/mobilecs_gs/MCSUA/GUID-7C2A0D49-F898-4886-9A6A-4FF799F776F4.htm#MCSUA711 */ var periodicRefreshPolicy = { PERIODIC_REFRESH_POLICY_REFRESH_NONE: 'PERIODIC_REFRESH_POLICY_REFRESH_NONE', PERIODIC_REFRESH_POLICY_REFRESH_EXPIRED_ITEM_ON_STARTUP: 'PERIODIC_REFRESH_POLICY_REFRESH_EXPIRED_ITEM_ON_STARTUP', PERIODIC_REFRESH_POLICY_PERIODICALLY_REFRESH_EXPIRED_ITEMS: 'PERIODIC_REFRESH_POLICY_PERIODICALLY_REFRESH_EXPIRED_ITEMS' }; var fetchPolicy = { FETCH_FROM_CACHE: 'FETCH_FROM_CACHE', FETCH_FROM_SERVICE: 'FETCH_FROM_SERVICE', FETCH_FROM_SERVICE_IF_ONLINE: 'FETCH_FROM_SERVICE_IF_ONLINE', FETCH_FROM_SERVICE_ON_CACHE_MISS: 'FETCH_FROM_SERVICE_ON_CACHE_MISS', FETCH_FROM_SERVICE_ON_CACHE_MISS_OR_EXPIRY: 'FETCH_FROM_SERVICE_ON_CACHE_MISS_OR_EXPIRY', FETCH_FROM_CACHE_SCHEDULE_REFRESH: 'FETCH_FROM_CACHE_SCHEDULE_REFRESH', FETCH_WITH_REFRESH: 'FETCH_WITH_REFRESH' }; var expirationPolicy = { EXPIRE_ON_RESTART: 'EXPIRE_ON_RESTART', EXPIRE_AFTER: 'EXPIRE_AFTER', NEVER_EXPIRE: 'NEVER_EXPIRE' }; var evictionPolicy = { EVICT_ON_EXPIRY_AT_STARTUP: 'EVICT_ON_EXPIRY_AT_STARTUP', MANUAL_EVICTION: 'MANUAL_EVICTION' }; var updatePolicy = { UPDATE_IF_ONLINE: 'UPDATE_IF_ONLINE', QUEUE_IF_OFFLINE: 'QUEUE_IF_OFFLINE' }; var conflictPolicy = { CLIENT_WINS: 'CLIENT_WINS', PRESERVE_CONFLICT: 'PRESERVE_CONFLICT', SERVER_WINS: 'SERVER_WINS' }; var clientPolicies = { // set default clientPolicies periodicRefreshPolicy: periodicRefreshPolicy.PERIODIC_REFRESH_POLICY_REFRESH_NONE, periodicRefreshInterval: 120 }; /** * Specify the default clientPolicies! * * @type {{periodicRefreshPolicy: string}} */ var defaultPolicy = { //periodicRefreshPolicy: periodicRefreshPolicy.PERIODIC_REFRESH_POLICY_REFRESH_NONE, conflictResolutionPolicy: conflictPolicy.PRESERVE_CONFLICT, evictionPolicy: evictionPolicy.MANUAL_EVICTION, expirationPolicy: expirationPolicy.EXPIRE_ON_RESTART, expireAfter: Number.MAX_VALUE, fetchPolicy: fetchPolicy.FETCH_FROM_SERVICE_IF_ONLINE, noCache: false, updatePolicy: updatePolicy.UPDATE_IF_ONLINE }; clientPolicies['default'] = defaultPolicy; //clientPolicies['policies'] = []; /** * Set sync library config clientPolicies * @param config */ var setPolicies = function (config) { if (!config) { console.error('config cannot be empty object'); throw new Error('config cannot be empty object'); } if (!_.isObject(config)) { console.error('policy is not object'); throw new Error('policy is not object'); } // Only on ES5-compliant browsers IE9+ //if (!Object.keys(config).length) { // Yes it has at least one //} // alternative check var found = false, name; for (name in config) { if (config.hasOwnProperty(name)) { found = true; break; } } if (!found) { console.error('policy object does not contain any properties!'); throw new Error('policy object does not contain any properties!'); } // now check also that all properties are there, we start first with default properties setDefaultPolicies(config); // now that default config are clear we can setup the URL config! setUrlPolicies(config); }; /** * Replace the default policy config with the new one, if any * @param config */ var setDefaultPolicies = function (config) { if (!config.hasOwnProperty('default')) { //console.debug('given policy options does not have setup any default config'); return; } console.debug('apply new default policies'); if (config.default.conflictResolutionPolicy in conflictPolicy) { defaultPolicy.conflictResolutionPolicy = config.default.conflictResolutionPolicy || conflictPolicy.PRESERVE_CONFLICT; } if (config.default.evictionPolicy in evictionPolicy) { defaultPolicy.evictionPolicy = config.default.evictionPolicy || evictionPolicy.MANUAL_EVICTION; } if (config.default.expirationPolicy in expirationPolicy) { defaultPolicy.expirationPolicy = config.default.expirationPolicy || expirationPolicy.EXPIRE_ON_RESTART; } if (typeof config.default.expireAfter === 'number') { defaultPolicy.expireAfter = config.default.expireAfter || Number.MAX_VALUE; } if (config.default.fetchPolicy in fetchPolicy) { defaultPolicy.fetchPolicy = config.default.fetchPolicy || fetchPolicy.FETCH_FROM_SERVICE_IF_ONLINE; } if (typeof config.default.noCache === 'boolean') { defaultPolicy.noCache = config.default.noCache || false; } if (config.default.updatePolicy in updatePolicy) { defaultPolicy.updatePolicy = config.default.updatePolicy || updatePolicy.UPDATE_IF_ONLINE; } }; var setUrlPolicies = function (config) { // get first the major properties if any! if (config.hasOwnProperty('periodicRefreshPolicy') && periodicRefreshPolicy.hasOwnProperty(config.periodicRefreshPolicy)) { clientPolicies.periodicRefreshPolicy = config.periodicRefreshPolicy || periodicRefreshPolicy.PERIODIC_REFRESH_POLICY_REFRESH_NONE; } if (config.hasOwnProperty('periodicRefreshInterval') && typeof config.periodicRefreshInterval === 'number') { clientPolicies.periodicRefreshInterval = config.periodicRefreshInterval || 1000 * 120; // 2 mins } if (!config.hasOwnProperty('policies')) { console.error('synchronisation configuration requires path policies'); throw new Error('synchronisation configuration requires path policies'); } parsePathConfig(config.policies); }; // pass the object from given url clientPolicies, it will be match with the default and return the final properties var setPolicyForURL = function (urlPolicyObject) { // get a copy of the default clientPolicies! var urlPolicies = JSON.parse(JSON.stringify(defaultPolicy)); if ('conflictResolutionPolicy' in urlPolicyObject && urlPolicyObject.conflictResolutionPolicy in conflictPolicy) { urlPolicies.conflictResolutionPolicy = urlPolicyObject.conflictResolutionPolicy || conflictPolicy.PRESERVE_CONFLICT; } if ('evictionPolicy' in urlPolicyObject && urlPolicyObject.evictionPolicy in evictionPolicy) { urlPolicies.evictionPolicy = urlPolicyObject.evictionPolicy || evictionPolicy.MANUAL_EVICTION; } if ('expirationPolicy' in urlPolicyObject && urlPolicyObject.expirationPolicy in expirationPolicy) { urlPolicies.expirationPolicy = urlPolicyObject.expirationPolicy || expirationPolicy.EXPIRE_ON_RESTART; } if ('expireAfter' in urlPolicyObject && typeof urlPolicyObject.expireAfter === 'number') { urlPolicies.expireAfter = urlPolicyObject.expireAfter || Number.MAX_VALUE; } if ('fetchPolicy' in urlPolicyObject && urlPolicyObject.fetchPolicy in fetchPolicy) { urlPolicies.fetchPolicy = urlPolicyObject.fetchPolicy || fetchPolicy.FETCH_FROM_SERVICE_IF_ONLINE; } if ('noCache' in urlPolicyObject && typeof urlPolicyObject.noCache === 'boolean') { urlPolicies.noCache = urlPolicyObject.noCache || false; } if ('updatePolicy' in urlPolicyObject && urlPolicyObject.updatePolicy in updatePolicy) { urlPolicies.updatePolicy = urlPolicyObject.updatePolicy || updatePolicy.UPDATE_IF_ONLINE; } return urlPolicies; }; /** * go throw the path config settings and set it up * @param arrOfPaths */ var parsePathConfig = function (arrOfPaths) { if (!Array.isArray(arrOfPaths)) { console.error('Persistence.Options.persistUris', 'param should be array!'); throw new Error('Persistence.Options.persistUris', 'param should be array!'); } // this approach should replace the previous logic! var route = pathMatch({ // path-to-regexp options sensitive: true, strict: false, end: true, }); var persistRegUriArr = []; clientPolicies['policies'] = arrOfPaths; if (arrOfPaths != null && Array.isArray(arrOfPaths)) { // go through the objects and take compile the regex for faster access!!! var len = arrOfPaths.length, i = 0; // go through the array and compile the regexes for (; i < len; i++) { var tmpPersistURL = {}; if (arrOfPaths[i].hasOwnProperty('path')) { //tmpPersistURL['uri'] = arrOfPaths[i].uri; tmpPersistURL['uri'] = arrOfPaths[i].path; // this is for backward support for older version of the persistence library tmpPersistURL['reg'] = pathToRegexp(tmpPersistURL['uri'], [], {sensitive: true}); tmpPersistURL['tokens'] = parse(tmpPersistURL['uri']); // new approach!! tmpPersistURL['matchURI'] = route(tmpPersistURL['uri']); // set clientPolicies here! //clientPolicies.policies.push(setPolicyForURL(arrOfPaths[i])); tmpPersistURL['policies'] = setPolicyForURL(arrOfPaths[i]); clientPolicies['policies'][i] = tmpPersistURL['policies']; clientPolicies['policies'][i].path = tmpPersistURL['uri']; //clientPolicies.policies.push(); // how to get the first key, which is the unique key /* * http://stackoverflow.com/questions/983267/access-the-first-property-of-an-object * https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/keys * * var params = match('/users/1/emails'); * params[Object.keys(params)[0]]; // return the ID */ // push the object to the main property persistUri.push(tmpPersistURL); // create new array which can be used on the end to testify id we really want to run the regex persistRegUriArr.push(tmpPersistURL.uri); } } // END OF FOR // use this object to check if we really want to persist specific URL!!! //@depricated - should be remove in the next version! isPersistUri = pathToRegexp(persistRegUriArr, [], {sensitive: true}); } }; // *** private methods /** * This simple implementation will check if specific path match and URL for persistence and return * object with all parameters. * * @param options * @returns {Function} * @throws Error - in case decoding of given parameter is not possible */ var pathMatch = function (options) { options = options || {}; return function (path) { var keys = []; var re = pathToRegexp(path, keys, options); return function (pathname, params) { var m = re.exec(pathname); if (!m) return false; // FIX: L.Pelov - user array to address the issue that some properties could have the same name params = params || []; var key, param, obj = {}; for (var i = 0; i < keys.length; i++) { key = keys[i]; param = m[i + 1]; if (!param) continue; obj = { name: key.name, value: decodeParam(param) } //params[key.name] = decodeParam(param); params.push(obj); if (key.repeat) { //params[key.name] = params[key.name].split(key.delimiter) params[params.length - 1].name = params[params.length - 1].name.split(key.delimiter) } } return params; } } }; /** * Decodes parameters from the url * * @param param * @returns {string} */ function decodeParam(param) { try { return decodeURIComponent(param); } catch (e) { throw Error('failed to decode param "' + param + '"'); } } var ready = function (fn) { if (document.readyState != 'loading') { fn(); } else if (document.addEventListener) { document.addEventListener('DOMContentLoaded', fn); } else { document.attachEvent('onreadystatechange', function () { if (document.readyState != 'loading') fn(); }); } }; /** * This is the cordova implementation for when device ready! * * @param callback * @returns {deviceReady} */ function deviceReady(callback) { if (isCordova) { document.addEventListener('deviceready', function () { callback(true); }, false); } else { callback(false); } return deviceReady; } /** * change state depending on device mode! */ deviceReady(function (isCordova) { if (isCordova) { var onlineCallback = function () { console.log('online callback'); } var offlineCallback = function () { console.log('offline callback'); } var pauseCallback = function () { console.log('pauseAppCallback'); } var resumeCallback = function () { console.log('pauseAppCallback'); } // register callbacks in case the state changed! document.addEventListener("offline", offlineCallback, false); document.addEventListener("online", onlineCallback, false); document.addEventListener("resume", resumeCallback, false); document.addEventListener("pause", pauseCallback, false); } }); /** * Is going to check in the browser if computer is online or offline! */ var initNetworkModes = function () { var status = navigator.onLine ? "online" : "offline"; function updateOnlineStatus(event) { var condition = navigator.onLine ? "online" : "offline"; status = condition; console.log("before end", "Event: " + event.type + "; Status: " + condition); } window.addEventListener('online', updateOnlineStatus); window.addEventListener('offline', updateOnlineStatus); // not required anymore! // if (Persistence.DB) { // $db = Persistence.DB('persist.options'); // } }; // init methods to make sure that we could switch from network modes ready(initNetworkModes); /** * @deprecated - options table not required anymore! * @param options * @returns {*} */ var setUrlCache = function (options) { if (!_.isObject(options)) return; if (!options.hasOwnProperty('url')) return; if (!options.hasOwnProperty('mcs')) return; var persistentPath = isPersistentUrl(options.url); if (persistentPath === false) { throw new Error('Persistence.Options.setUrlCache()-> URI was not configured for persistence:' + options.url); } options['url'] = persistentPath.root; var col = $db.getCollectionByName('options'); var result = col.findOne({url: persistentPath.root}); if (result) { _.extendOwn(result, options); return col.update(result); } else { return col.insert(options); } }; /** * Checks if URL is configured for persistence and return the parameters * @param path - string with the current path to check * @returns {*} - object with the properties representing the values of the defined URL parameters */ function isPersistentUrl(path) { if (typeof path !== 'string') { console.warn('isPersistentUrl -> path can be only string'); return false; } // make sure that you parse the path! path = this.parseURL(path).path; // check the cache first! if (path in isPersistUrlCache) { return isPersistUrlCache[path]; } // go through the persistUri, and check the urls! var len = persistUri.length, i = 0; for (; i < len; i++) { try { var params = persistUri[i].matchURI(path); if (params === false) { // go to the next one continue; } return isPersistUrlCache[path] = { params: params, root: persistUri[i].tokens[0], path: path, tokens: persistUri[i].tokens.slice(1), policies: persistUri[i].policies, isPolicy: function (policy, value) { if (typeof policy !== 'string') return undefined; if (this.policies && this.policies.hasOwnProperty(policy)) { return value === undefined ? true : this.policies[policy] === value; } return false; } }; } catch (e) { console.error(e); return isPersistUrlCache[path] = false; } } return isPersistUrlCache[path] = false; } /** * @deprecated - options table not required anymore! * @param path * @returns {*} */ var getUrlCache = function (path) { return {mcs:true}; if (_.isEmpty(path)) return; var persistentPath = isPersistentUrl(path); if (persistentPath === false) { throw new Error('Persistence.Options.setUrlCache()-> URI was not configured for persistence:' + path); } var col = $db.getCollectionByName('options'); return col.findOne({url: persistentPath.root}); }; // reveal public methods return { isPersistentUrl: isPersistentUrl, /** * init on DOM ready to take eventually new settings! * support IE8+ * @param fn */ ready: ready, set dbFirst(yes) { if (typeof yes === "boolean") { dbFirst = yes; } }, get dbFirst() { return dbFirst; }, // set the new timeout in ms set timeout(ms) { if (typeof ms === 'number') { timeout = ms || timeout; } }, get timeout() { return timeout; }, set syncTimeOut(ms) { if (typeof ms === 'number') { syncTimeout = ms || syncTimeout; } }, get syncTimeOut() { return syncTimeout; }, parseURL: function (url) { if (typeof url !== 'string') { console.error('Persistence.Options.parseURL -> path can be only string'); throw new Error('Persistence.Options.parseURL -> path can be only string'); } // check the cache first! if (url in parseUrlCache) { return parseUrlCache[url]; } // parse, store to the cache and return return parseUrlCache[url] = parseUri(url); }, // get all persist URLs get persistUris() { return persistUri; }, set persistUris(arr) { parsePathConfig(arr); }, // global callbacks! set onTimeOut(callback) { if (typeof callback === 'function') { this.ontimeout = callback; } }, set onError(callback) { if (typeof callback === 'function') { this.onerror = callback; } }, set onSuccess(callback) { if (typeof callback === 'function') { this.onsuccess = callback; } }, // default callbacks! ontimeout: function (e) { console.error('xhr.ontimeout', e); }, onerror: function (e) { // NOTE: usually this is going to be network error here! console.error('xhr.onerror!', e); }, onsuccess: function (data, status, headers, requestid) { console.debug('xhr.onsuccess', data, status, headers, requestid); }, /** * More information can be found here: * https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine * * @returns {boolean} */ isOnline: function () { var networkState = (navigator && navigator.connection) ? navigator.connection.type : 'NULL'; //console.log('network: TYPE (%s), CORDOVA (%s)', networkState, (typeof window.cordova != 'undefined')); // this means you are probably working in the browser if ((networkState === '' || networkState === 'NULL')) { if (isCordova) { return false; } else { // browser by default always online! // navigator.onLine ? "online" : "offline"; return navigator.onLine ? true : false; // IE9+, Safari/iOS 8.4+ } } if (networkState === 'unknown' || networkState === 'none') { return false; } // you are online! return true; }, set isonline(callback) { if (typeof callback === 'function') { this.isOnline = callback; } }, isOn: function () { if (alwayson && !passOne) { return true; } if (passOne == true) { passOne = false; } if (on) { on = null; return true; } return (!!on); }, oneOn: function () { on = !!!on; return true; }, oneOff: function () { passOne = true; }, // always intercept the XHR set alwaysOn(bool) { if (bool) { // ok alwayson = true; } else { alwayson = false; } }, set off(bool) { typeof bool === "boolean" ? alwaysoff = bool : alwaysoff = false; }, get off() { return alwaysoff; }, dbFirstFalseForNextCall: function () { if (dbFirst === true) { dbFirstFalseForNextCallBool = true; } }, isDbFirst: function () { if (dbFirst === false && dbFirstFalseForNextCallBool === false) { return false; } else if (dbFirst === true && dbFirstFalseForNextCallBool === false) { return true; } // this means I have to return false! else if (dbFirst === true && dbFirstFalseForNextCallBool === true) { dbFirstFalseForNextCallBool = false; return false; } else { return dbFirst; } }, set maxSyncAttempts(attempts) { if (typeof attempts === 'number') { maxsyncattempts = attempts || maxsyncattempts; } }, get maxSyncAttempts() { return maxsyncattempts; }, set autoRemoveAfterReachMaxAttemps(bool) { if (typeof bool === "boolean") { autoremoveafterreachmaxattemps = bool || autoremoveafterreachmaxattemps; } }, get autoRemoveAfterReachMaxAttemps() { return autoremoveafterreachmaxattemps; }, set autoSync(bool) { if (typeof bool === "boolean") { autoSync = bool; } }, get autoSync() { return autoSync; }, ondbprefixchange: function (oldVal, newVal) { dbprefixchangehandler(oldVal, newVal); }, set onDbPrefixChange(callback) { if (typeof callback === 'function') { this.ondbprefixchange = callback; } }, set dbPrefix(prefix){ if (typeof prefix === 'string'){ var old = dbprefix; dbprefix = prefix; //dbprefixchangehandler(old, dbprefix); this.ondbprefixchange(old, dbprefix); } }, get dbPrefix() { return dbprefix; }, set offlineDBName(name) { if (typeof name === 'string') { offlinedbname = name; } }, get module() { return module; }, set module(implementation) { if (!implementation) throw new Error('provide module implementation'); module = implementation; }, /** * @deprecated replace with lowercase */ get Module() { return module; }, /** * @deprecated replace with lowercase */ set Module(implementation) { if (!implementation) throw new Error('provide module implementation'); module = implementation; }, get offlineDBName() { return offlinedbname; }, set syncLogDBName(name) { if (typeof name === 'string') { synclogdbname = name; } }, get syncLogDBName() { return synclogdbname; }, set Policies(policies) { setPolicies(policies); }, get Policies() { return clientPolicies; }, get DefaultPolicies() { return defaultPolicy; }, setUrlCache: setUrlCache, getUrlCache: getUrlCache, get isCordova() { return isCordova; }, deviceReady: deviceReady, // TODO: custom method reset: function (){ persistUri = []; clientPolicies.policies = []; }, get isTest() { return isTest; }, // set the new timeout in ms set isTest(value) { isTest = value; }, } } /** * Creates the offline database and return base API for external usage. * * @type {{getDB, getCollection, getCollectionByName, getCollections, save, close, flush}} */ function persistenceDB(name, $options) { 'use strict'; /** * Create internal JS offline persistence db. */ // default settings! var _db = null; var $name = name; var options = { autosave: true, autosaveInterval: 500,// in milliseconds autoload: true }; // like a constructor, init when DOM ready! function init(name) { if ($options.off === true || $options.isTest === true) { options = { autosave: false, autosaveInterval: 60 * 1000 * 60 * 24 * 30 * 12,// in milliseconds, something very high, 1 year+ autoload: false } } var dbName = $name || name || $options.offlineDBName || 'offline'; _db = new loki(dbName, options); _db.loadDatabase(); //_db.save(); } //init(); // exec on DOM ready! $options.ready(init); /** * Wraps the way collection should be taken from the database. If given collection name does not exist * it will create it. * * @param name - the name of the collection to get, create * @returns {*} * @param name */ function getCollection2(name) { var col = _db.getCollection(name); if (!col) { var options = { clone: true, // makes sure that objects are not returned by reference disableChangesApi: true, // not need for change api here transactional: true // make sure that operations are transactional }; col = _db.addCollection(name, options); } // BUG in Loki v1.3.16 - trigger save after each of the following operations // col.on('insert', function (result) { // _db.save(); // }) // // col.on('update', function () { // _db.save(); // }) // // col.on('delete', function () { // _db.save(); // }) return col; } /** * Return collection directly with promise. If collection does not exist it will be created. * * @param name - the name of the database collection * @returns {*} * @deprecated */ function getCollection(name) { return new Promise(function (resolve, reject) { _db.loadDatabase({}, function () { var col = _db.getCollection(name); if (!col) { var options = { clone: true, // makes sure that objects are not returned by reference disableChangesApi: true, // not need for change api here transactional: true // make sure that operations are transactional }; col = _db.addCollection(name/*, options*/); } resolve(col); }); }); } /** * In case developer explicitly wants to save the database, after db operation. */ function saveDatabase() { //_db.saveDatabase(); _db.save(); } /** * Returns all registered collections from the offline database. */ function getCollections() { return _db.listCollections(); } /** * Return the object to the internal created database * @returns {*} */ function internalDB() { return _db; } /** * Emits a close event with an optional callback. Note that this does not destroy the db or collections, * it's a utility method that can be called before closing the process or 'onbeforeunload' in a browser. * * @param callback - optional */ function close(callback) { _db.close(callback); } /** * This will go through all database collections and remove the data from them. */ function flush() { // go throw the collections and delete the data there! var collections = getCollections(); for (var i = 0; i < collections.length; i++) { // get the collection getCollection2(collections[i].name).removeDataOnly(); } return true; } // TODO: Use promises in all calls! return { //init: init, getDB: internalDB, getCollection: getCollection, getCollectionByName: getCollection2, getCollections: getCollections, save: saveDatabase, close: close, flush: function () { return new Promise(function (resolve) { resolve(flush()); }); } }; } /** * This module provide the MCS Persistent capabilities * @type {{}} */ function persistenceMCSHandler($options, $common, $utils) { 'use strict'; var URI_KEY = '$mcs$mcsPersistenceURI'; var ETAG_KEY = '$mcs$etag'; var HEADER_LOCATION = "location"; var HEADER_RESOURCE_TYPE = "oracle-mobile-sync-resource-type"; var dbname = 'mcs'; var prefix = $options.dbPrefix; // to ready/write data to specific collections var $db = persistenceDB(prefix + '.' + dbname, $options); // in case the db prefix has changed, re-init the db! $options.onDbPrefixChange = function (oldVal, newVal) { $db = persistenceDB(newVal + '.' + dbname, $options); }; // helper with common functions var _ = $common; var isPersistentRequest = function (request) { if (!request) { throw new Error('request cannot be undefined or null value'); } if (!_.isObject(request)) { throw new Error('request has to be defined object with properties like: url, data etc.'); } if (_.isEmpty(request)) { throw new Error('request cannot be empty object, it request properties like: url, data etc.'); } if (_.isArray(request) || _.isFunction(request)) { throw new Error('request cannot be array or function'); } // if response !false check that it has specific properties if (!'url' in request) { throw new Error('request.url was not specified'); } return true; }; /** * Check to see if this was also MCS payload! * * @param request * @returns {boolean} */ var isPersistentMcsGetRequest = function (request) { isPersistentRequest(request); if (_.isEmpty(request.data)) { throw new Error('cannot proceed with empty payload'); } if (!'items' in request.data) { throw new Error('items is not in the payload returned from MCS, probably not Sync Custom Code'); } if (!'uris' in request.data) { throw new Error('url is not in the payload returned from MCS, probably not Sync Custom Code'); } // don't know if this is mandatory! if (!'etags' in request.data) { throw new Error('etags is not in the payload returned from MCS, probably not Sync Custom Code'); } return true; }; var isPostRequest = function (request) { isPersistentRequest(request); if (!'data' in request) { throw new Error('request.data was not defined!'); } if (!_.isObject(request.data)) { throw new Error('request.data is not a object or array!'); } if (_.isFunction(request.data)) { throw new Error('request.data cannot be function'); } // all good! return true; }; var isOfflinePersistObj = function (obj) { if ('meta' in obj && obj.meta.hasOwnProperty('offline-persist')) { return true; } return false; }; /** * If forces, you could mark the object to be stored in the DB only and not synced! * * @param obj * @param force * @returns {*} */ var markObjAsOfflineIfForced = function (obj, force) { // only if force positive if (force) { if (isOfflinePersistObj(obj)) { delete obj.meta['offline-persist']; } return obj; } // since we updated that object make sure that is not going to be overridden if ('meta' in obj) { obj.meta['offline-persist'] = true; return obj; } obj['meta'] = {}; obj.meta['offline-persist'] = true; return obj; }; /** * Transform the payload and add it into the $db! * * NOTE: Such a transformations could hold a lot of resources! * * @param collection * @param payload * @returns {*} */ var handleMcsGetCollectionPayload = function (collection, payload) { // to go over the items var size = payload.items.length; // get the current time! var now = Date.now(); // get each object and create it in the $db for (var i = 0; i < size; i++) { var item = payload.items[i]; item[URI_KEY] = parseUri((_.stringStartsWith(payload.uris[i], '/') ? '' : '/') + payload.uris[i]).path; item[ETAG_KEY] = payload.etags[i]; var query = {}; query[URI_KEY] = item[URI_KEY]; var result = collection.findOne(query); // if already exist, update it if (result) { _.extendOwn(result, item); collection.update(result); } else { collection.insert(item); } } // clean everything that was not in the payload, so not updated or created! collection.removeWhere(function (dbObj) { //var diff = now - listeners[eventName].timestamp; return dbObj.meta.updated < now; }); // return all from the collection! return collection.find(); }; /** * Handle item payload from the MCS * * @param collection * @param payload * @param path * @returns {*} */ var handleMcsGetItemPayload = function (collection, payload, path) { // check first if this item already exist and update it, otherwise created it! var query = {}; query[URI_KEY] = path; var result = collection.findOne(query); if (result) { var item = payload; _.extendOwn(result, item); return collection.update(result); } else { var item = payload; item[URI_KEY] = path; // not here this is not having etag! return collection.insert(item); } }; /** * If nothing in the payload check get what is in the offline $db! * @param response - response is always array of objects! */ var handleMcsGet = function (response) { var persistentPath = $options.isPersistentUrl(response.url); if (persistentPath === false) { throw new Error('Persistence.handleMcsGet()-> URI was not configured for persistence:' + response.url); } var collection = $db.getCollectionByName(persistentPath.root); // if any attributes build the query and return the information if (_.isEmpty(persistentPath.params)) { // no way to find build the query so return empty array // return collection in format {items:[],uris:[],etags:[]} var result = collection.find(); var data = { //items: collection.find(), items: [], uris: [], etags: [] }; // for (var idx in data.items) { // if (data.items.hasOwnProperty(idx)) { // data.uris.push(data.items[idx].URI_KEY); // } // } // clean the object and return in the way the MCS would do! for (var idx in result) { if (result[idx].hasOwnProperty(URI_KEY)) { data.uris.push(result[idx][URI_KEY]); delete result[idx][URI_KEY]; } if (result[idx].hasOwnProperty(ETAG_KEY)) { data.etags.push(result[idx][ETAG_KEY]); delete result[idx][ETAG_KEY]; } // it's actually clear that this is from the DB delete result[idx]['$loki']; data.items.push(result[idx]); } return data; } var query = {}; query[URI_KEY] = persistentPath.path; return collection.findOne(query); // var result = collection.findOne(query); // if (result) { // result.meta[URI_KEY] = result[URI_KEY]; // result.meta[ETAG_KEY] = result[ETAG_KEY]; // // delete result['$loki']; // delete result[URI_KEY]; // delete result[ETAG_KEY]; // // return result; // } // // return '{}'; }; var handleMcsGetStore = function (response) { var persistentPath = $options.isPersistentUrl(response.url); if (persistentPath === false) { throw new Error('Persistence.handleMcsGetStore()-> URI was not configured for persistence:' + response.url); } // get the collection for the given url var collection = $db.getCollectionByName(persistentPath.root); // new reference! var payload = response.data; // since everything is in the payload, I don't have to bother with some complicate checking! // Oracle-Mobile-Sync-Resource-Type: item, collection // Content-Type header must be application/json var resourceTypeHeader = HEADER_RESOURCE_TYPE in response || response.headers[HEADER_RESOURCE_TYPE]; if (resourceTypeHeader === 'collection') { // work with collection return handleMcsGetCollectionPayload(collection, payload); } else if (resourceTypeHeader === 'item') { // work with item return handleMcsGetItemPayload(collection, payload, persistentPath.path); } else if (resourceTypeHeader) { // something else! console.error('unknown Oracle-Mobile-Sync-Resource-Type (%s)', resourceTypeHeader); throw new Error('unknown Oracle-Mobile-Sync-Resource-Type'); } else { // nothing to do the payload is not recognised! console.error('this is not MCS response, unable to handle the payload, no MCS header was specified: ', response); throw new Error('this is not MCS response, unable to handle the payload, no MCS header was specified'); } }; /** * Currently posts supports only adding new objects into the root! * * @param response * @param force */ var handleMcsPost = function (response, force) { // check if URL can be persist var persistentPath = $options.isPersistentUrl(response.url); if (persistentPath === false) { throw new Error('Persistence.handleMcsPost()-> URI was not configured for persistence:' + response.url); } // get the collection for the given url var collection = $db.getCollectionByName(persistentPath.root); // reference var payload = response.data; if (!_.isEmpty(persistentPath.params)) { throw new Error('you can add new objects only against the root REST resource endpoint'); } if (_.isArray(payload)) { throw new Error("the payload cannot be array"); } // just object payload else if (_.isObject(payload) && !_.isNull(payload) && !_.isFunction(payload)) { // update offline created object with new uri if (response.data && response.data[URI_KEY]) { return updatePayloadWithNewUri(collection, response); } else { var uri = null; if (response && response.headers && response.headers[HEADER_LOCATION]) { uri = _.stringStartsWith(response.headers[HEADER_LOCATION], '/') ? response.headers[HEADER_LOCATION] : '/' + response.headers[HEADER_LOCATION]; } var result = null; if (uri) { var query = {}; query[URI_KEY] = uri; result = collection.findOne(query); } if (!result) { payload[ETAG_KEY] = '"0-1B2M2Y8AsgTpgAmY7PhCfg"'; // empty e-tag result = collection.insert(payload); // this flag means that we created this directly in the offline $db markObjAsOfflineIfForced(result, force); } else { _.extendOwn(result, response.data); } if (!uri) { // L.Pelov - fix 02 Aug 2016 // EDGE case when you use Oracle JET with oj.Collection components! var key = (persistentPath.tokens.length > 0 && /^\w+$/.test(persistentPath.tokens[0].name)) ? persistentPath.tokens[0].name : null; var value = null; if (key) { value = (response.data.hasOwnProperty(key)) ? response.data[key] : _.getUID(); } uri = (value === null) ? persistentPath.root + '/' + _.getUID() : persistentPath.root + '/' + value; // on post check to see if the payload already has object with ID configured in the params //uri = persistentPath.root + '/' + _.getUID(); } result[URI_KEY] = uri; return collection.update(result); } } throw new Error("don't know what to do with the payload"); }; function updatePayloadWithNewUri(collection, response) { var query = {}; query[URI_KEY] = response.data[URI_KEY]; var result = collection.findOne(query); if (result) { _.extendOwn(result, response.data); //result[URI_KEY] = '/' + response.headers.Location; result[URI_KEY] = _.stringStartsWith(response.headers[HEADER_LOCATION], '/') ? response.headers[HEADER_LOCATION] : '/' + response.headers[HEADER_LOCATION]; return collection.update(result); } else { throw new Error("the payload was not found in collection:" + query[URI_KEY]); } } /** * Currently posts supports only adding new objects into the root! * * @param response * @param force */ var handleMcsPut = function (response, force) { // check if URL can be persist var persistentPath = $options.isPersistentUrl(response.url); if (persistentPath === false) { throw new Error('Persistence.handleMcsPut()-> URI was not configured for persistence:' + response.url); } // get the collection for the given url var collection = $db.getCollectionByName(persistentPath.root); // reference var payload = response.data; if (!_.isEmpty(persistentPath.params)) { // ok there is key so we can try to do the update if (_.isArray(payload)) { throw new Error("the payload cannot be array"); } // just object payload else if (_.isObject(payload) && !_.isNull(payload) && !_.isFunction(payload)) { var query = {}; query[URI_KEY] = persistentPath.path; var result = collection.findOne(query); if (result) { _.extendOwn(result, payload); markObjAsOfflineIfForced(result, force); return collection.update(result); } } } // don't know what to do! :)! throw new Error("you can execute update operations only against existing items in the offline database!"); }; /** * * @param response * @returns {*} */ var handleMcsDelete = function (response) { // check if URL can be persist var persistentPath = $options.isPersistentUrl(response.url); if (persistentPath === false) { throw new Error('Persistence.handleMcsDelete()-> URI was not configured for persistence:' + response.url); } // get the collection for the given url var collection = $db.getCollectionByName(persistentPath.root); // reference var payload = response.data; if (!_.isEmpty(persistentPath.params)) { var query = {}; query[URI_KEY] = persistentPath.path; var findOne = collection.findOne(query); if (findOne) { return collection.remove(findOne); } throw new Error('unable to find object with the given ID(%s) in the database', response.url); } }; // TODO: Yuri - move to helper or create base class, every handler will ahve such method function flush(path) { console.info('Persistence.MCS.flush()', path); // if no path delete everything if (_.isEmpty(path)) { return $db.flush(); } else { var parsed = $options.parseURL(path); var isPersistentUrl = $utils.isPersistUrl(parsed.path); return new Promise(function (resolve, reject) { // check if URL can be persist if (!isPersistentUrl) { reject(new Error('Persistence.MCS.flush() given URI not configured for persistence: ' + parsed.path)); } else { var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); resolve($db.getCollectionByName(queryParams.root).removeDataOnly()); } }); } } // public API this.get = function (request) { var doGet = function (request) { console.info('Persistence.MCS.get()'); isPersistentRequest(request); // copy the object to make sure that we don't work with the reference anymore! var _request = _.clone(request); if (!_request.hasOwnProperty('data') || _.isEmpty(_request.data)) { return _.clone(handleMcsGet(_request)); } // if it has data, check that it was MCS payload! isPersistentMcsGetRequest(request); return _.clone(handleMcsGetStore(_request)); }; // return all as a promise //return Promise.fcall(doGet, request); return new Promise(function (resolve) { resolve(doGet(request)); }); }; this.post = function (request, force) { var doPost = function (response, force) { console.info('Persistence.MCS.post()'); isPostRequest(request); // never work with reference, only use new copy! var _request = _.clone(request); return _.clone(handleMcsPost(_request, force)); }; // promise return new Promise(function (resolve) { resolve(doPost(request, force)); }); }; this.put = function (request, force) { var doPut = function (response, force) { console.info('Persistence.MCS.put()'); // requires the same like the post! isPostRequest(request); // never work with reference, only use new copy! var _request = _.clone(request); return _.clone(handleMcsPut(_request, force)); }; // promise return new Promise(function (resolve) { resolve(doPut(request, force)); }); }; this.delete = function (request, force) { var doDelete = function (response, force) { console.info('Persistence.MCS.delete()'); // requires the same like the post! isPersistentRequest(request); // never work with reference, only use new copy! var _request = _.clone(request); return _.clone(handleMcsDelete(_request, force)); }; // promise return new Promise(function (resolve) { resolve(doDelete(request, force)); }); }; this.router = function (request, force) { // IMPORTANT: Take the referecen outside the PROMISE! var self = this; return new Promise(function (resolve) { if (!_.isObject(request)) { console.error('Passed object is not defined request!', request); throw new Error('Passed object is not defined request!'); } // check if method provided! if (!request.hasOwnProperty('method')) { console.error('request.method was not provided!', request); throw new Error('request.method was not provided!'); } // copy the object to make sure that we don't work with the reference anymore! var _request = _.clone(request); // expects the router specified _request.method = $utils.normalizeMethod(_request.method); if (!self[_request.method]) { console.error('specified router is not implemented!'); throw new Error('specified router is not implemented!'); } resolve(self[_request.method](_request, force)); }); }; this.data = function (path) { function doData(path) { var persistentPath = $options.isPersistentUrl(path); // if (!persistentPath) { throw new Error('Persistence.BaseModule.data() given URI not configured for persistence: ' + path); } return $db.getCollectionByName(persistentPath.root); } // return new Promise(function (resolve) { resolve(doData(path)); }); }; this.flush = flush; this.getModuleName = function () { return 'MCS'; }; this.URI_KEY = URI_KEY; this.ETAG_KEY = ETAG_KEY; } /** * Request handler can be used directly, and is used to intercept the HTTP request to store objects offline. * * @type {{get, post, put, delete, data, router, flush}} */ // TODO: L.Pelov - rename to Generic in the next release function persistenceRequestHandler($options, $common, $utils) { 'use strict'; // private declarations // to ready/write data to specific collections // var $db = persistenceDB('persist.request'); var dbname = 'request'; var prefix = $options.dbPrefix; // to ready/write data to specific collections var $db = persistenceDB(prefix + '.' + dbname, $options); // in case the db prefix has changed, re-init the db! $options.onDbPrefixChange = function (oldVal, newVal) { $db = persistenceDB(newVal + '.' + dbname, $options); }; var _ = $common; var isPersistentRequest = function (request) { if (!request) { throw new Error('request cannot be undefined or null value'); } if (!_.isObject(request)) { throw new Error('request has to be defined object with properties like: url, data etc.'); } if (_.isEmpty(request)) { throw new Error('request cannot be empty object, it request properties like: url, data etc.'); } if (_.isArray(request) || _.isFunction(request)) { throw new Error('request cannot be array or function'); } // if response !false check that it has specific properties if (!'url' in request) { throw new Error('request.url was not specified'); } return true; }; var isPersistentGetRequest = function (request) { isPersistentRequest(request); return true; }; var isPostRequest = function (request) { isPersistentRequest(request); if (!'data' in request) { throw new Error('request.data was not defined!'); } if (!_.isObject(request.data)) { throw new Error('request.data is not a object or array!'); } if (_.isFunction(request.data)) { throw new Error('request.data cannot be function'); } // all good! return true; }; var isOfflinePersistObj = function (obj) { return !!('meta' in obj && obj.meta.hasOwnProperty('offline-persist')); }; var isLokiDbObj = function (obj) { return !!('$loki' in obj && typeof(obj.$loki) === 'number' && !isNaN(obj.$loki)); }; var buildFindQueryBasedOnUrlParams = function (urlQueryParams) { var dbQuery = {}; if (urlQueryParams.attr.length > 0) { var key = urlQueryParams.attr[0].name; dbQuery[key] = (urlQueryParams.attr[0].pattern.indexOf('\d') >= 0) ? parseInt(urlQueryParams.attr[0].value) : urlQueryParams.attr[0].value + ""; } return dbQuery; }; var buildUniqueIDValue = function (isPersistentUrl, value) { var isInt = function () { if ((isPersistentUrl.uri.tokens.length > 1)) { return isPersistentUrl.uri.tokens[isPersistentUrl.uri.tokens.length - 1].pattern.indexOf('\d') >= 0; } else { return false; } }; var parse = function (value) { return isInt() ? parseInt(value) : value + ""; }; if (_.isEmpty(value)) { return parse(_.getUID()); } if (typeof value === 'number' && isInt()) { return value } return parse(value); }; var handleGetRootArrayPayload = function (payload, isPersistentUrl, collection) { // check for key in the URL // 0 - in the tokens is always the /root path of the URL if (isPersistentUrl.uri.tokens.length > 1) { // so we know that this is the root, get everything var dbArray = collection.find(); // for the merging! if (dbArray.length > 0) { // get the name of the key to use to compare // this is the second element in the tokens[] array var keyNameToCompare = isPersistentUrl.uri.tokens[1].name; // TODO: L.Pelov - Change this algorithm later to be able to work with ranges! collection.removeWhere(function (dbObj) { // this adds some overhead if the payload is big, as it will search through every time, // however each time object was found in the payload it will be remove to increase search efficiency var foundObjectIndex = payload.findIndex(function (payloadObj) { // this will return true if object with the follow parameters found! return (payloadObj[keyNameToCompare] === dbObj[keyNameToCompare]); }); // if >-1 object was found if (foundObjectIndex > -1) { // now get the object and merge the properties! try { // merge the properties // if object was changed offline, don't override the offline staff! if (isOfflinePersistObj(dbObj)) { // don't override what was changed offline! dbObj = _.deepExtend(payload[foundObjectIndex], dbObj); } else { _.extendOwn(dbObj, payload[foundObjectIndex]); } // and update the database collection.update(dbObj); // remove the object from the payload, to increase search index efficiency! payload.splice(foundObjectIndex, 1); } catch (e) { console.error(e); } finally { // make sure that false is returned! return false; } } else { if (isOfflinePersistObj(dbObj)) { return false; } //bad for you baby you don't exist anymore, and you was not created offline, we have to delete you return true; } }); // now check to see if there is something left in the payload and insert it into the db payload.forEach(function (obj) { // this situation should not happen, but better test! if (isLokiDbObj(obj)) { collection.update(obj); } else { collection.insert(obj); } }); // on the end return the new collection return collection.find(); } // if we don't have anything in the collection then just insert the payload return collection.insert(payload); } // we don't have a chance to compare without key specified in the config settings // wipe out all information not created offline and add the new payload collection.removeWhere(function (obj) { return (!isOfflinePersistObj(obj)); //return true; }); // insert the new payload return collection.insert(payload); }; var handleGetRootObjectPayload = function (payload, isPersistentUrl, collection) { // check first again if we have key specified if (isPersistentUrl.uri.tokens.length > 1) { // get the name of the key to use to compare // this is usually the second in the tokens[] array var keyNameToCompare = isPersistentUrl.uri.tokens[1].name; // check if the object has the same key if (!payload.hasOwnProperty(keyNameToCompare)) { console.error('payload does not contain unique key specified in the URL settings'); throw new Error('payload does not contain unique key specified in the URL settings'); } // we could use the key from the payload to query the db and see if there is already object with // the same ID var findObjByKeyQuery = {}; findObjByKeyQuery[keyNameToCompare] = payload[keyNameToCompare]; // let see if there is object with the same id var result = collection.findOne(findObjByKeyQuery); // if result, the object exist in the db, update it then! if (result) { // ok we had something that much, remove the rest, but only if it's not marked offline if (isOfflinePersistObj(result)) { result = _.deepExtend(payload, result); } else { _.extendOwn(result, payload); } return collection.update(result); } // ok the object has the require ID but does not exist in the DB // so insert it now, but before that remove everything from here, except the offline objects we created! // collection.removeWhere(function(obj) { // return (!obj.meta.hasOwnProperty('offline-persist')); // }); // TODO: The question here is if we really want to save something that does not have any unique key defined! // if you here it means that the object does not exist in the DB, store it directly for now return collection.insert(payload); } // no keys specified delete everything that was not stored directly in the db and insert the new payload collection.removeWhere(function (obj) { return (!isOfflinePersistObj(obj)); }); // insert the new payload return collection.insert(payload); }; var setPayloadSingleObject = function (newObject, payload) { if (_.isArray(payload)) { _.extendOwn(newObject, payload[0]); } else if (_.isObject(payload) && !_.isFunction(payload)) { _.extendOwn(newObject, payload); } }; /** * Build nested property structure to be used in GET calls to setup or edit existing objects! * * @param queryParams query parameters properties! * @returns {string} prop1.prop2[value].prop3.... * @deprecated use buildNestedPropertyArrayParams */ function buildNestedPropertySearchString(queryParams) { var nestedProperty = ""; if (queryParams.attr.length > 1) { // skips the first key we know that this is the object unique key! for (var i = 1; i < queryParams.attr.length; i++) { // :_property if (queryParams.attr[i].is) { // prop.prop... if (nestedProperty.length > 0) nestedProperty += "." + queryParams.attr[i].name; else nestedProperty += queryParams.attr[i].name; } // :id(\\d+) else { // prop.prop[value]... if (nestedProperty.length > 0) { nestedProperty += "." + queryParams.attr[i].name + "[" + queryParams.attr[i].value + "]"; } else { //nestedProperty += queryParams.attr[i].name[queryParams.attr[i].value]; // TODO: Yuri - check with Lyudmil nestedProperty += queryParams.attr[i].value; } } } } return nestedProperty; } /** * Has to be build a string of properties which can be used when adding new elements! * * @param queryParams * @param isPersistentUrl * @param isNotGet * * @return {Array<persistenceUtils~Property>} - array of properties with parameters and values */ function buildNestedPropertyArrayParams(isPersistentUrl, queryParams, isNotGet) { // why string, it could be array of objects, easier to access and I can pass all properties I need! var nestedProperty = []; var params = queryParams.attr; // here we start from the if (Array.isArray(params) && params.length > 0) { var tokens = isPersistentUrl.uri.tokens.length > 1 ? isPersistentUrl.uri.tokens.slice(1) : []; // go over the parameters to construct the link for (var i = 0; i < params.length; i++) { var isLast = (params.length - 1) == i; // :_property if (params[i].is) { // prop.prop... // if (nestedProperty.length > 0) nestedProperty += "." + params[i].name; // else nestedProperty += params[i].name; nestedProperty.push({ name: params[i].name, value: null, isProperty: true, isInteger: false }); // So the issue here we have is following: // - this is the last element and is property, so we have to check if in the tokens there // another element after that that is key:value and if yes, we should use to generate the element // - FIX: L.Pelov - this should be done only in POST, PUT or DELETE cases! if (isLast && tokens[i + 1] && isNotGet) { // check if there is additional element in the match to identify the key of this property! // this will happen in case of POST, PUT DELETE //nestedProperty += "." + tokens[i].name + "[" + $common.getUID() + "]"; var isInt = $utils.isUrlRegexInteger(tokens[i + 1].pattern); nestedProperty.push({ name: tokens[i + 1].name, value: isInt ? $common.getUID() : $common.getUID() + "", isProperty: false, isInteger: isInt }); } } // :id(\\d+) else { // prop.prop[value]... // if the property is empty create value! var proValue = params[i].value || $common.getUID(); nestedProperty.push({ name: params[i].name, value: proValue, isProperty: false, isInteger: $utils.isUrlRegexInteger(tokens[i].pattern) }); } } } return nestedProperty; } /** * Search for that nested object and add the new payload to it, if any! * * @param obj * @param persistentUrlObj * @param queryParams * @param payload * @returns {{obj: *, result: *}} */ function createObjFromUrlParamsForExistingForPost(obj, persistentUrlObj, queryParams, payload) { var nestedProperty = buildNestedPropertyArrayParams(persistentUrlObj, queryParams); var result = obj; if (Array.isArray(nestedProperty) && nestedProperty.length > 0) { result = $utils.setNestedProperty2(obj, nestedProperty, payload); } else { _.extendOwn(obj, payload); } return { obj: obj, result: result }; } /** * In case of given DB object but we have URL with sub parameters, we have to check if those nested obj exist, * and create them if not and add the payload inside. * * @param obj - object form the offline DB * @param queryParams - URL parameters, usually what is returned from $utils.extractKeyValuesFromUrl2 * @param payload - from the REST API call * @return {{obj: *, result: *}} * @param persistentUrlObj */ function createObjFromUrlParamsForGETAction(obj, persistentUrlObj, queryParams, payload) { // NOTICE: since this is a get action we don't have to build the sub property var nestedProperty = buildNestedPropertyArrayParams(persistentUrlObj, queryParams, false); var result = obj; if (Array.isArray(nestedProperty) && nestedProperty.length > 0) { result = $utils.setNestedProperty2(obj, nestedProperty, payload); } return { obj: obj, result: result }; } /** * Try to find that nested object when offline or when no payload in GET * @param obj * @param persistentUrlObj * @param queryParams * @returns {*} */ function getNestedPropertyFromUrlParamsForExisting(obj, persistentUrlObj, queryParams) { // build the nested property array to use to search for the object var nestedProperty = buildNestedPropertyArrayParams(persistentUrlObj, queryParams, false); // do only if nested property search required if (Array.isArray(nestedProperty) && nestedProperty.length > 0) { return $utils.getNestedProperty(obj, nestedProperty); } return obj; } /** * if we have attributed then the first one should be the key we look for! * @deprecated - use buildNestedPropertyArrayParams */ function createObjFromUrlParameters(keyValueObj, queryParams, payload) { // this root does not exist create it with the given unique ID from the URL var newObject = keyValueObj; // NOTE that the first one key:value is the unique key! // TODO: L.Pelov - check performance! if (queryParams.attr.length > 1) { var nestedProperty = ""; for (var i = 1; i < queryParams.attr.length; i++) { // if object than we have key:value if (queryParams.attr[i].is) { $utils.setData(queryParams.attr[i].name, queryParams.attr[i].value, newObject); } else { if (nestedProperty.length > 0) nestedProperty += "." + queryParams.attr[i].value; else nestedProperty += queryParams.attr[i].value; // we just have empty property to nest with other properties $utils.setData(nestedProperty, {}, newObject); } } //if (nestedProperty.length > 0) { // $utils.setData(nestedProperty, payload, newObject); //} // once the nested property was created, extend with the new data! //_.extendOwn(newObject, payload); } else { //_.extendOwn(newObject, payload); } setPayloadSingleObject(newObject, payload); return newObject; } /** * @deprecated - use buildNestedPropertyArrayParams */ function createObjFromUrlParametersForEdit(keyValueObj, queryParams, payload) { var newObject = keyValueObj; if (queryParams.attr.length > 1) { var nestedProperty = ""; for (var i = 1; i < queryParams.attr.length; i++) { // if object that we have key:value if (queryParams.attr[i].is) { $utils.setData(queryParams.attr[i].name, queryParams.attr[i].value, newObject); } else { //console.log(query.attr[i].name, query.attr[i].value); if (nestedProperty.length > 0) nestedProperty += "." + queryParams.attr[i].value; else nestedProperty += queryParams.attr[i].value; // we just have empty property to nest with other properties $utils.setData(nestedProperty, {}, newObject); } } // ok the new object is ready, we can now merge with the result if (nestedProperty.length > 0) { $utils.setData(nestedProperty, payload, newObject); } // return the new object for merging return newObject; } // was not able to create new object return payload; } var markObjAsOfflineIfForced = function (obj, force) { // only if force positive if (force) { if (isOfflinePersistObj(obj)) { delete obj.meta['offline-persist']; } return obj; } // since we updated that object make sure that is not going to be overridden if ('meta' in obj) { obj.meta['offline-persist'] = true; return obj; } obj['meta'] = {}; obj.meta['offline-persist'] = true; return obj; }; /** * Use only if you have no new data, empty payload, and you want to return everything from the db, * depending on the GET URL * * TODO: should be extended to be able to query sub element! * @param response{url} * @returns {*} */ var handleGet = function (response) { // check first the URL if defined for persistence! var parsed = $options.parseURL(response.url); var isPersistentUrl = $utils.isPersistUrl(parsed.path); // no need to continue, if the URL was not configured! if (!isPersistentUrl) { throw new Error('Persistence.RequestHandler.get() given URI was not configured for persistence:' + parsed.path); } // get the parameters form the REST URL used to call the backend! var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); // get the collection for the given url var collection = $db.getCollectionByName(queryParams.root); // cache in between for easy access var payload = response.data; var keyValueObj = buildFindQueryBasedOnUrlParams(queryParams); // search and get!:) if (!_.isEmpty(keyValueObj)) { var result = collection.findOne(keyValueObj); // deep search in the object! if (result) { return _.cleanObject(getNestedPropertyFromUrlParamsForExisting(result, isPersistentUrl, queryParams)); } // nothing inside, sorry! return []; } console.info('unable to build find query for given url and payload, return all from db'); return _.cleanObjects(collection.find()); }; /** * Response property * @typedef persistenceRequestHandler~Response * @property url {String} * @property data {Object} */ /** * Stores/merges given payload into the offline db! * * @param response {persistenceRequestHandler~Response} * @returns {*} */ var handleGetStore = function (response) { // check first the URL if defined for persistence! var parsed = $options.parseURL(response.url); var isPersistentUrl = $utils.isPersistUrl(parsed.path); // no need to continue, if the URL was not configured! if (!isPersistentUrl) { throw new Error('Persistence.RequestHandler.get() given URI was not configured for persistence:' + parsed.path); } // get the parameters form the REST URL used to call the backend! var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); // get the collection for the given url var collection = $db.getCollectionByName(queryParams.root); // cache in between for easy access var payload = response.data; var keyValueObj = buildFindQueryBasedOnUrlParams(queryParams); if (!_.isEmpty(keyValueObj)) { var result = collection.findOne(keyValueObj); // this means that we have element with that key, so we have to update it if (result) { // TODO: Address the possibility that some object could be marked as offline only! var newObj = createObjFromUrlParamsForGETAction(result, isPersistentUrl, queryParams, payload); collection.update(newObj.obj); return newObj.result; } else { var newObj = createObjFromUrlParamsForGETAction(keyValueObj, isPersistentUrl, queryParams, payload); collection.insert(newObj.obj); return newObj.result; } } // ok no key in the url but we have payload and it should be added somewhere // this also means that we are in the root path! else if (_.isArray(payload) && !_.isFunction(payload) && !_.isEmpty(payload)) { // if it is array of objects in the payload, then make a intersection return handleGetRootArrayPayload(payload, isPersistentUrl, collection); } // this is the situation where we have only object in the root path payload call NOT array! else if (_.isObject(payload) && !_.isArray(payload) && !_.isFunction(payload) && !_.isEmpty(payload)) { return handleGetRootObjectPayload(payload, isPersistentUrl, collection); } else { // don't know what to do:)! console.error('Persistence.RequestHandler.get() unknown or empty object passed for the operation'); throw new Error('Persistence.RequestHandler.get() -> unknown or empty object passed for the operation'); } }; /** * Handle post array payload. * * @param payload * @param isPersistentUrl * @param collection * @param force * @returns {*} */ var handlePostRootArrayPayload = function (payload, isPersistentUrl, collection, force) { var keyNameToCompare = (isPersistentUrl.uri.tokens.length > 1) ? isPersistentUrl.uri.tokens[1].name : null; // go now throw what it was in the collection // and see if we have match to the new payload payload.forEach(function (obj) { if (isLokiDbObj(obj)) { markObjAsOfflineIfForced(obj, force); collection.update(obj); } // check if the payload has id, else if (keyNameToCompare && obj.hasOwnProperty(keyNameToCompare)) { // try to find the element in the db, if there update, otherwise inside! var result = collection.findOne({keyNameToCompare: obj[keyNameToCompare]}); if (result) { _.extendOwn(result, obj); markObjAsOfflineIfForced(result, force); collection.update(result); } else { // insert markObjAsOfflineIfForced(obj, force); collection.insert(obj); } } else { // if we don't have anything in the collection to compare var objInsertResult = collection.insert(obj); objInsertResult[keyNameToCompare] = buildUniqueIDValue(isPersistentUrl); //objInsertResult.$loki + ""; markObjAsOfflineIfForced(objInsertResult, force); return _.cleanObject(collection.update(objInsertResult)); } }); // on the end return the new collection return _.cleanObjects(collection.find()); }; /** * Handle post create object from only simple json object * @param payload * @param isPersistentUrl * @param collection * @param force * @returns {*} */ var handlePostRootObjectPayload = function (payload, isPersistentUrl, collection, force) { // well check first again if we have key specified in the $options var keyNameToCompare = (isPersistentUrl.uri.tokens.length > 1) ? isPersistentUrl.uri.tokens[1].name : ""; // check if the object has the same key if (keyNameToCompare && !payload.hasOwnProperty(keyNameToCompare)) { console.info('get payload', "does not have the key specified in the URL settings"); // if not then we have to create one empty payload[keyNameToCompare] = ""; // no need to query the db for this element // well this is completely new element and we should mark it as offline var insertResult = collection.insert(payload); if (insertResult) { insertResult[keyNameToCompare] = buildUniqueIDValue(isPersistentUrl)//insertResult.$loki + ""; // this flag means that we created this directly in the offline db markObjAsOfflineIfForced(insertResult, force); return _.cleanObject(collection.update(insertResult)); } // else we have an issue here throw new Error('unable to store the payload object'); } // ok this is the situation, where the key actually exist in the payload // let see if there is object with the same id if (keyNameToCompare && payload.hasOwnProperty(keyNameToCompare)) { // make sure that the payload var queryForObject = {}; queryForObject[keyNameToCompare] = payload[keyNameToCompare]; //var result = collection.findOne({keyNameToCompare: payload[keyNameToCompare]}); var result = collection.findOne(queryForObject); // this means that we have element with that key, so we have to update it if (result) { // merge properties! _.extendOwn(result, payload); markObjAsOfflineIfForced(result, force); return _.cleanObject(collection.update(result)); } // ok so if the above did not work, maybe there is a problem with the key string/int var rebuildKeyValue = buildUniqueIDValue(isPersistentUrl, payload[keyNameToCompare]); payload[keyNameToCompare] = rebuildKeyValue; } // if no key was specified in the URL option settings, we have no another option markObjAsOfflineIfForced(payload, force); return _.cleanObject(collection.insert(payload)); }; /** * Handle Post HTTP request! * * @param response {persistenceRequestHandler~Response} * @param force - it means that the meta['offline-persist'] property will be deleted to force update on next GET * @returns {*} */ var handlePost = function (response, force) { var parsed = $options.parseURL(response.url); var isPersistentUrl = $utils.isPersistUrl(parsed.path); // check if URL can be persist if (!isPersistentUrl) { throw new Error('Persistence.RequestHandler.post() given URI not configured for persistence: ' + parsed.path); } // get the parameters form the REST URL used to call the backend! var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); // get the collection for the given url var collection = $db.getCollectionByName(queryParams.root); // cache in between for easy access var payload = response.data; var keyValueObj = buildFindQueryBasedOnUrlParams(queryParams); // if not empty we can search if (!_.isEmpty(keyValueObj)) { // find parent object var result = collection.findOne(keyValueObj); // ok post used URL with key, so we have to create sub element here if (result) { var newObj = createObjFromUrlParamsForExistingForPost(result, isPersistentUrl, queryParams, payload); var propertyName = isPersistentUrl.uri.tokens[isPersistentUrl.uri.tokens.length - 1].name; newObj.result[propertyName] = buildUniqueIDValue(isPersistentUrl, newObj.result[propertyName]); markObjAsOfflineIfForced(newObj.obj, force); collection.update(newObj.obj); return _.cleanObject(newObj.result); } else { var newObj = createObjFromUrlParamsForExistingForPost(keyValueObj, isPersistentUrl, queryParams, payload); markObjAsOfflineIfForced(newObj.obj, force); collection.insert(newObj.obj); return _.cleanObject(newObj.result); } } // this situation will happen when we have ROOT path call, with no KEY specified // ok no key in the url but we have payload and it should be added somewhere // this also means that we are in the root! if (_.isArray(payload)) { return handlePostRootArrayPayload(payload, isPersistentUrl, collection, force); } // just object payload else if (_.isObject(payload) && !_.isArray(payload) && !_.isNull(payload)) { return handlePostRootObjectPayload(payload, isPersistentUrl, collection, force); } // dont' know what to do! :)! throw new Error("don't know what to do with the payload"); }; /** * Works like HTTP post * https://gist.github.com/wookiehangover/877067 * * @param response * @param force * @returns {*} */ var handlePut = function (response, force) { var parsed = $options.parseURL(response.url); var isPersistentUrl = $utils.isPersistUrl(parsed.path); // check if URL can be persist if (!isPersistentUrl) { throw new Error('Persistence.RequestHandler.post() given URI not configured for persistence: ' + parsed.path); } // get the parameters form the REST URL used to call the backend! var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); // get the collection for the given url var collection = $db.getCollectionByName(queryParams.root); // cache in between for easy access var payload = response.data; var keyValueObj = buildFindQueryBasedOnUrlParams(queryParams); // if we have attributed than the first one should be key we look for! if (!_.isEmpty(keyValueObj)) { var result = collection.findOne(keyValueObj); // this means that we have element with that key, so we have to update it if (result) { var newObj = createObjFromUrlParamsForExistingForPost(result, isPersistentUrl, queryParams, payload); markObjAsOfflineIfForced(newObj.obj, force); collection.update(newObj.obj); return newObj.result; } else { var newObj = createObjFromUrlParamsForExistingForPost(keyValueObj, isPersistentUrl, queryParams, payload); markObjAsOfflineIfForced(newObj.obj, force); collection.insert(newObj.obj); return newObj.result; } } // ok following is in the case that you call PUT on root with parameters! // makes PUT to work like POST! if (_.isArray(payload)) { return handlePostRootArrayPayload(payload, isPersistentUrl, collection, force); } // just object payload else if (_.isObject(payload) && !_.isArray(payload) && !_.isNull(payload)) { return handlePostRootObjectPayload(payload, isPersistentUrl, collection, force); } // dont' know:)! //throw new Error('unable to recognise the edit payload, it should be JSON Object or Array!'); throw new Error('no key specified to recognise obj in the database for editing!'); }; /** * Works like HTTP post * https://gist.github.com/wookiehangover/877067 * * @param response * @param force * @returns {*} */ var handlePatch = function (response, force) { var parsed = $options.parseURL(response.url); var isPersistentUrl = $utils.isPersistUrl(parsed.path); // check if URL can be persist if (!isPersistentUrl) { throw new Error('Persistence.RequestHandler.post() given URI not configured for persistence: ' + parsed.path); } // get the parameters form the REST URL used to call the backend! var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); // get the collection for the given url var collection = $db.getCollectionByName(queryParams.root); // cache in between for easy access var payload = response.data; var keyValueObj = buildFindQueryBasedOnUrlParams(queryParams); // if we have attributed than the first one should be key we look for! if (!_.isEmpty(keyValueObj)) { var result = collection.findOne(keyValueObj); // this means that we have element with that key, so we have to update it if (result) { var newObj = createObjFromUrlParamsForExistingForPost(result, isPersistentUrl, queryParams, payload); markObjAsOfflineIfForced(newObj.obj, force); collection.update(newObj.obj); return newObj.result; } else { var newObj = createObjFromUrlParamsForExistingForPost(keyValueObj, isPersistentUrl, queryParams, payload); markObjAsOfflineIfForced(newObj.obj, force); collection.insert(newObj.obj); return newObj.result; } } // ok following is in the case that you call PUT on root with parameters! // makes PUT to work like POST! if (_.isArray(payload)) { return handlePostRootArrayPayload(payload, isPersistentUrl, collection, force); } // just object payload else if (_.isObject(payload) && !_.isArray(payload) && !_.isNull(payload)) { return handlePostRootObjectPayload(payload, isPersistentUrl, collection, force); } // dont' know:)! //throw new Error('unable to recognise the edit payload, it should be JSON Object or Array!'); throw new Error('no key specified to recognise obj in the database for editing!'); }; /** * Delete specific element from the offline db * * @param request * @returns {*} */ var handleDelete = function (request) { var parsed = $options.parseURL(request.url); var isPersistentUrl = $utils.isPersistUrl(parsed.path); // check if URL can be persist if (!isPersistentUrl) { throw new Error('Persistence.RequestHandler.post() given URI not configured for persistence: ' + parsed.path); } var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); var collection = $db.getCollectionByName(queryParams.root); var keyValueObj = buildFindQueryBasedOnUrlParams(queryParams); // if we have attributed in the request URL specified!!! if (!_.isEmpty(keyValueObj)) { var findOne = collection.findOne(keyValueObj); if (findOne) { return _.cleanObject(collection.remove(findOne)); } throw new Error('unable to find object with the given ID(%s) in the database', keyValueObj); } // OK maybe the ID is in the payload! // NOTE: It is not good practice to have the ID in the payload, but it is possible! if (request.hasOwnProperty('data')) { var payload = request.data; if (!_.isEmpty(payload) && _.isObject(payload) && !_.isArray(payload)) { var keyNameToCompare = (isPersistentUrl.uri.tokens.length > 1) ? isPersistentUrl.uri.tokens[1].name : null; // check if the object has the same key if (keyNameToCompare && !request.data.hasOwnProperty(keyNameToCompare)) { throw new Error('payload does not have the key required to delete the object'); } var findOne = collection.findOne({keyNameToCompare: request.data[keyNameToCompare]}); if (findOne) { return _.cleanObject(collection.remove(findOne)); } } } console.error('payload does not have the key required to delete the object in the payload'); throw new Error('payload does not have the key required to delete the object in the payload'); }; // TODO: Yuri - move to helper or create base class, every handler will ahve such method function flush(path) { console.info('Persistence.RequestHandler.flush()', path); // if no path delete everything if (_.isEmpty(path)) { return $db.flush(); } else { var parsed = $options.parseURL(path); var isPersistentUrl = $utils.isPersistUrl(parsed.path); return new Promise(function (resolve, reject) { // check if URL can be persist if (!isPersistentUrl) { reject(new Error('Persistence.RequestHandler.flush() given URI not configured for persistence: ' + parsed.path)); } else { var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); resolve($db.getCollectionByName(queryParams.root).removeDataOnly()); } }); } } // public methods! this.getDB = function () { return $db; }; this.get = function (request) { var doGet = function (request) { console.info('Persistence.RequestHandler.get()'); isPersistentGetRequest(request); // copy the object to make sure that we don't work with the reference anymore! var _request = _.clone(request); if (!_request.hasOwnProperty('data') || _.isEmpty(_request.data)) { return _.clone(handleGet(_request)); } return _.clone(handleGetStore(_request)); }; // return all as a promise return new Promise(function (resolve) { resolve(doGet(request)); }); }; // actually this is the same as get but only for specific element this.post = function (request, force) { var doPost = function (request, force) { console.info('Persistence.RequestHandler.post()'); isPostRequest(request); // always clone before do some work with the object, // it takes some time but saves a lot of trouble! var _request = _.clone(request); //return handlePost(_request, force); return _.clone(handlePost(_request, force)); }; // promise return new Promise(function (resolve) { resolve(doPost(request, force)); }); }; this.put = function (request, force) { var doPut = function (request, force) { console.info('Persistence.RequestHandler.put()'); isPostRequest(request); // always clone the object before do some work var _request = _.clone(request); return _.clone(handlePut(_request, force)); }; // promise //return Promise.resolve(doPut(request, force)); return new Promise(function (resolve) { resolve(doPut(request, force)); }); }; this.patch = function (request, force) { var doPatch = function (request, force) { console.info('Persistence.RequestHandler.patch()'); isPostRequest(request); // always clone the object before do some work var _request = _.clone(request); return _.clone(handlePatch(_request, force)); }; // promise //return Promise.resolve(doPut(request, force)); return new Promise(function (resolve) { resolve(doPatch(request, force)); }); }; this.delete = function (request) { function doDelete(request) { console.info('Persistence.RequestHandler.delete()'); isPersistentRequest(request); // always clone the object before do some work var _request = _.clone(request); return _.clone(handleDelete(_request)); } // promise //return Promise.resolve(doDelete(request)); return new Promise(function (resolve) { resolve(doDelete(request)); }); }; // provide the url and you will get the collection for it, as result from promise! this.data = function (path) { function doData(path) { console.info('Persistence.RequestHandler.data()'); if (path == null) { throw new Error('Path cannot be empty!'); } var parsed = $options.parseURL(path); var isPersistentUrl = $utils.isPersistUrl(parsed.path); // check if URL can be persist if (!isPersistentUrl) { throw new Error('Persistence.RequestHandler.post() given URI not configured for persistence: ' + parsed.path); } var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); return $db.getCollectionByName(queryParams.root); } // promise //return Promise.resolve(doData(path)); return new Promise(function (resolve) { resolve(doData(path)); }); }; this.router = function (request, force) { var self = this; return new Promise(function (resolve) { //resolve(doRouting(request, force)); if (!isPersistentGetRequest(request)) { console.error('Passed object is not defined request for GET!', request.url); throw new Error('Passed object is not defined request for GET!'); } // check if method provided! if (!request.hasOwnProperty('method')) { console.error('request.method was not provided!', request); throw new Error('request.method was not provided!'); } // copy the object to make sure that we don't work with the reference anymore! var _request = _.clone(request); // do routing! // if (_request.method === 'GET') { // if (!_request.hasOwnProperty('data') || _.isEmpty(_request.data)) { // var result = handleGet(_request) // return clone(result); // } // var result = handleGetStore(_request); // return clone(result); // } // exec the router specified _request.method = $utils.normalizeMethod(_request.method); if (!self[_request.method]) { console.error('specified router is not implemented!'); throw new Error('specified router is not implemented!'); } // exec the method var result = self[_request.method](_request, force); resolve(result); }); }; // provide path and you delete everything from the collection this.flush = flush; this.getModuleName = function () { return 'MCS'; }; // private methods this._createObjFromUrlParamsForExistingForPost = createObjFromUrlParamsForExistingForPost; this._buildNestedPropertyAddString = buildNestedPropertyArrayParams; this._buildNestedPropertySearchString = buildNestedPropertySearchString; this._createObjFromUrlParamsForExisting = createObjFromUrlParamsForGETAction; this._buildNestedPropertyArrayParams = buildNestedPropertyArrayParams; } /** * This module provide the Oracle REST Persistent capabilities * @type {{}} */ function persistenceOracleRESTHandler($options, $common, $utils) { 'use strict'; // to ready/write data to specific collections // var $db = persistenceDB('persist.request'); var dbname = 'oraclerest'; var prefix = $options.dbPrefix; // to ready/write data to specific collections var $db = persistenceDB(prefix + '.' + dbname, $options); // in case the db prefix has changed, re-init the db! $options.onDbPrefixChange = function (oldVal, newVal) { $db = persistenceDB(newVal + '.' + dbname, $options); }; var _ = $common; function buildOracleRESTResponse(items) { return { items: items }; } var isPersistentRequest = function (request) { if (!request) { throw new Error('request cannot be undefined or null value'); } if (!_.isObject(request)) { throw new Error('request has to be defined object with properties like: url, data etc.'); } if (_.isEmpty(request)) { throw new Error('request cannot be empty object, it request properties like: url, data etc.'); } if (_.isArray(request) || _.isFunction(request)) { throw new Error('request cannot be array or function'); } // if response !false check that it has specific properties if (!'url' in request) { throw new Error('request.url was not specified'); } return true; }; var isPersistentGetRequest = function (request) { isPersistentRequest(request); return true; }; var isPostRequest = function (request) { isPersistentRequest(request); if (!'data' in request) { throw new Error('request.data was not defined!'); } if (!_.isObject(request.data)) { throw new Error('request.data is not a object or array!'); } if (_.isFunction(request.data)) { throw new Error('request.data cannot be function'); } // all good! return true; }; var isOfflinePersistObj = function (obj) { return !!('meta' in obj && obj.meta.hasOwnProperty('offline-persist')); }; var isLokiDbObj = function (obj) { return !!('$loki' in obj && typeof(obj.$loki) === 'number' && !isNaN(obj.$loki)); }; var buildFindQueryBasedOnUrlParams = function (urlQueryParams) { var dbQuery = {}; if (urlQueryParams.attr.length > 0) { var key = urlQueryParams.attr[0].name; dbQuery[key] = (urlQueryParams.attr[0].pattern.indexOf('\d') >= 0) ? parseInt(urlQueryParams.attr[0].value) : urlQueryParams.attr[0].value + ""; } return dbQuery; }; var buildUniqueIDValue = function (isPersistentUrl, value) { var isInt = function () { if ((isPersistentUrl.uri.tokens.length > 1)) { return isPersistentUrl.uri.tokens[isPersistentUrl.uri.tokens.length - 1].pattern.indexOf('\d') >= 0; } else { return false; } }; var parse = function (value) { return isInt() ? parseInt(value) : value + ""; }; if (_.isEmpty(value)) { return parse(_.getUID()); } if (typeof value === 'number' && isInt()) { return value } return parse(value); }; var handleGetRootArrayPayload = function (payload, isPersistentUrl, collection) { // check for key in the URL // 0 - in the tokens is always the /root path of the URL if (isPersistentUrl.uri.tokens.length > 1) { // so we know that this is the root, get everything var dbArray = collection.find(); // for the merging! if (dbArray.length > 0) { // get the name of the key to use to compare // this is the second element in the tokens[] array var keyNameToCompare = isPersistentUrl.uri.tokens[1].name; // TODO: L.Pelov - Change this algorithm later to be able to work with ranges! collection.removeWhere(function (dbObj) { // this adds some overhead if the payload is big, as it will search through every time, // however each time object was found in the payload it will be remove to increase search efficiency var foundObjectIndex = payload.findIndex(function (payloadObj) { // this will return true if object with the follow parameters found! return (payloadObj[keyNameToCompare] === dbObj[keyNameToCompare]); }); // if >-1 object was found if (foundObjectIndex > -1) { // now get the object and merge the properties! try { // merge the properties // if object was changed offline, don't override the offline staff! if (isOfflinePersistObj(dbObj)) { // don't override what was changed offline! dbObj = _.deepExtend(payload[foundObjectIndex], dbObj); } else { _.extendOwn(dbObj, payload[foundObjectIndex]); } // and update the database collection.update(dbObj); // remove the object from the payload, to increase search index efficiency! payload.splice(foundObjectIndex, 1); } catch (e) { console.error(e); } finally { // make sure that false is returned! return false; } } else { if (isOfflinePersistObj(dbObj)) { return false; } //bad for you baby you don't exist anymore, and you was not created offline, we have to delete you return true; } }); // now check to see if there is something left in the payload and insert it into the db payload.forEach(function (obj) { // this situation should not happen, but better test! if (isLokiDbObj(obj)) { collection.update(obj); } else { collection.insert(obj); } }); // on the end return the new collection return collection.find(); } // if we don't have anything in the collection then just insert the payload return collection.insert(payload); } // we don't have a chance to compare without key specified in the config settings // wipe out all information not created offline and add the new payload collection.removeWhere(function (obj) { return (!isOfflinePersistObj(obj)); //return true; }); // insert the new payload return collection.insert(payload); }; var handleGetRootObjectPayload = function (payload, isPersistentUrl, collection) { // check first again if we have key specified if (isPersistentUrl.uri.tokens.length > 1) { // get the name of the key to use to compare // this is usually the second in the tokens[] array var keyNameToCompare = isPersistentUrl.uri.tokens[1].name; // check if the object has the same key if (!payload.hasOwnProperty(keyNameToCompare)) { console.error('payload does not contain unique key specified in the URL settings'); throw new Error('payload does not contain unique key specified in the URL settings'); } // we could use the key from the payload to query the db and see if there is already object with // the same ID var findObjByKeyQuery = {}; findObjByKeyQuery[keyNameToCompare] = payload[keyNameToCompare]; // let see if there is object with the same id var result = collection.findOne(findObjByKeyQuery); // if result, the object exist in the db, update it then! if (result) { // ok we had something that much, remove the rest, but only if it's not marked offline if (isOfflinePersistObj(result)) { result = _.deepExtend(payload, result); } else { _.extendOwn(result, payload); } return collection.update(result); } // ok the object has the require ID but does not exist in the DB // so insert it now, but before that remove everything from here, except the offline objects we created! // collection.removeWhere(function(obj) { // return (!obj.meta.hasOwnProperty('offline-persist')); // }); // TODO: The question here is if we really want to save something that does not have any unique key defined! // if you here it means that the object does not exist in the DB, store it directly for now return collection.insert(payload); } // no keys specified delete everything that was not stored directly in the db and insert the new payload collection.removeWhere(function (obj) { return (!isOfflinePersistObj(obj)); }); // insert the new payload return collection.insert(payload); }; /** * Build nested property structure to be used in GET calls to setup or edit existing objects! * * @param queryParams query parameters properties! * @returns {string} prop1.prop2[value].prop3.... * @deprecated use buildNestedPropertyArrayParams */ function buildNestedPropertySearchString(queryParams) { var nestedProperty = ""; if (queryParams.attr.length > 1) { // skips the first key we know that this is the object unique key! for (var i = 1; i < queryParams.attr.length; i++) { // :_property if (queryParams.attr[i].is) { // prop.prop... if (nestedProperty.length > 0) nestedProperty += "." + queryParams.attr[i].name; else nestedProperty += queryParams.attr[i].name; } // :id(\\d+) else { // prop.prop[value]... if (nestedProperty.length > 0) { nestedProperty += "." + queryParams.attr[i].name + "[" + queryParams.attr[i].value + "]"; } else { //nestedProperty += queryParams.attr[i].name[queryParams.attr[i].value]; // TODO: Yuri - check with Lyudmil nestedProperty += queryParams.attr[i].value; } } } } return nestedProperty; } /** * Has to be build a string of properties which can be used when adding new elements! * * @param queryParams * @param isPersistentUrl * @param isNotGet * * @return {Array<persistenceUtils~Property>} - array of properties with parameters and values */ function buildNestedPropertyArrayParams(isPersistentUrl, queryParams, isNotGet) { // why string, it could be array of objects, easier to access and I can pass all properties I need! var nestedProperty = []; var params = queryParams.attr; // here we start from the if (Array.isArray(params) && params.length > 0) { var tokens = isPersistentUrl.uri.tokens.length > 1 ? isPersistentUrl.uri.tokens.slice(1) : []; // go over the parameters to construct the link for (var i = 0; i < params.length; i++) { var isLast = (params.length - 1) == i; // :_property if (params[i].is) { // prop.prop... // if (nestedProperty.length > 0) nestedProperty += "." + params[i].name; // else nestedProperty += params[i].name; nestedProperty.push({ name: params[i].name, value: null, isProperty: true, isInteger: false }); // So the issue here we have is following: // - this is the last element and is property, so we have to check if in the tokens there // another element after that that is key:value and if yes, we should use to generate the element // - FIX: L.Pelov - this should be done only in POST, PUT or DELETE cases! if (isLast && tokens[i + 1] && isNotGet) { // check if there is additional element in the match to identify the key of this property! // this will happen in case of POST, PUT DELETE //nestedProperty += "." + tokens[i].name + "[" + $common.getUID() + "]"; var isInt = $utils.isUrlRegexInteger(tokens[i + 1].pattern); nestedProperty.push({ name: tokens[i + 1].name, value: isInt ? $common.getUID() : $common.getUID() + "", isProperty: false, isInteger: isInt }); } } // :id(\\d+) else { // prop.prop[value]... // if the property is empty create value! var proValue = params[i].value || $common.getUID(); nestedProperty.push({ name: params[i].name, value: proValue, isProperty: false, isInteger: $utils.isUrlRegexInteger(tokens[i].pattern) }); } } } return nestedProperty; } /** * Search for that nested object and add the new payload to it, if any! * * @param obj * @param persistentUrlObj * @param queryParams * @param payload * @returns {{obj: *, result: *}} */ function createObjFromUrlParamsForExistingForPost(obj, persistentUrlObj, queryParams, payload) { var nestedProperty = buildNestedPropertyArrayParams(persistentUrlObj, queryParams); var result = obj; if (Array.isArray(nestedProperty) && nestedProperty.length > 0) { result = $utils.setNestedProperty2(obj, nestedProperty, payload); } else { _.extendOwn(obj, payload); } return { obj: obj, result: result }; } /** * In case of given DB object but we have URL with sub parameters, we have to check if those nested obj exist, * and create them if not and add the payload inside. * * @param obj - object form the offline DB * @param queryParams - URL parameters, usually what is returned from $utils.extractKeyValuesFromUrl2 * @param payload - from the REST API call * @return {{obj: *, result: *}} * @param persistentUrlObj */ function createObjFromUrlParamsForGETAction(obj, persistentUrlObj, queryParams, payload) { // NOTICE: since this is a get action we don't have to build the sub property var nestedProperty = buildNestedPropertyArrayParams(persistentUrlObj, queryParams, false); var result = obj; if (Array.isArray(nestedProperty) && nestedProperty.length > 0) { result = $utils.setNestedProperty2(obj, nestedProperty, payload); } return { obj: obj, result: result }; } /** * Try to find that nested object when offline or when no payload in GET * @param obj * @param persistentUrlObj * @param queryParams * @returns {*} */ function getNestedPropertyFromUrlParamsForExisting(obj, persistentUrlObj, queryParams) { // build the nested property array to use to search for the object var nestedProperty = buildNestedPropertyArrayParams(persistentUrlObj, queryParams, false); // do only if nested property search required if (Array.isArray(nestedProperty) && nestedProperty.length > 0) { return $utils.getNestedProperty(obj, nestedProperty); } return obj; } var markObjAsOfflineIfForced = function (obj, force) { // only if force positive if (force) { if (isOfflinePersistObj(obj)) { delete obj.meta['offline-persist']; } return obj; } // since we updated that object make sure that is not going to be overridden if ('meta' in obj) { obj.meta['offline-persist'] = true; return obj; } obj['meta'] = {}; obj.meta['offline-persist'] = true; return obj; }; /** * Use only if you have no new data, empty payload, and you want to return everything from the db, * depending on the GET URL * * TODO: should be extended to be able to query sub element! * @param response{url} * @returns {*} */ var handleGet = function (response) { // check first the URL if defined for persistence! var parsed = $options.parseURL(response.url); var isPersistentUrl = $utils.isPersistUrl(parsed.path); // no need to continue, if the URL was not configured! if (!isPersistentUrl) { throw new Error('Persistence.RequestHandler.get() given URI was not configured for persistence:' + parsed.path); } // get the parameters form the REST URL used to call the backend! var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); // get the collection for the given url var collection = $db.getCollectionByName(queryParams.root); // cache in between for easy access var payload = response.data; var keyValueObj = buildFindQueryBasedOnUrlParams(queryParams); // search and get!:) if (!_.isEmpty(keyValueObj)) { var result = collection.findOne(keyValueObj); // deep search in the object! if (result) { return _.cleanObject(getNestedPropertyFromUrlParamsForExisting(result, isPersistentUrl, queryParams)); } else { // nothing inside, sorry! return null; } } else { console.info('unable to build find query for given url and payload, return all from db'); return buildOracleRESTResponse(_.cleanObjects(collection.find())); } }; /** * Response property * @typedef persistenceRequestHandler~Response * @property url {String} * @property data {Object} */ /** * Stores/merges given payload into the offline db! * * @param response {persistenceRequestHandler~Response} * @returns {*} */ var handleGetStore = function (response) { // check first the URL if defined for persistence! var parsed = $options.parseURL(response.url); var isPersistentUrl = $utils.isPersistUrl(parsed.path); // no need to continue, if the URL was not configured! if (!isPersistentUrl) { throw new Error('Persistence.RequestHandler.get() given URI was not configured for persistence:' + parsed.path); } // get the parameters form the REST URL used to call the backend! var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); // get the collection for the given url var collection = $db.getCollectionByName(queryParams.root); // cache in between for easy access var payload = response.data; var keyValueObj = buildFindQueryBasedOnUrlParams(queryParams); if (!_.isEmpty(keyValueObj)) { var result = collection.findOne(keyValueObj); var newObj; // this means that we have element with that key, so we have to update it if (result) { // TODO: Address the possibility that some object could be marked as offline only! newObj = createObjFromUrlParamsForGETAction(result, isPersistentUrl, queryParams, payload); collection.update(newObj.obj); } else { newObj = createObjFromUrlParamsForGETAction(keyValueObj, isPersistentUrl, queryParams, payload); collection.insert(newObj.obj); } return newObj.result; } else { payload = response.data.items; // ok no key in the url but we have payload and it should be added somewhere // this also means that we are in the root path! if (_.isArray(payload) && !_.isFunction(payload) && !_.isEmpty(payload)) { // if it is array of objects in the payload, then make a intersection var items = handleGetRootArrayPayload(payload, isPersistentUrl, collection); // build oracle rest response return buildOracleRESTResponse(items); } // TODO: when is this case happen? // this is the situation where we have only object in the root path payload call NOT array! else if (_.isObject(payload) && !_.isArray(payload) && !_.isFunction(payload) && !_.isEmpty(payload)) { return handleGetRootObjectPayload(payload, isPersistentUrl, collection); } else { // don't know what to do:) console.error('Persistence.OracleRESTHandler.get() unknown or empty object passed for the operation'); throw new Error('Persistence.OracleRESTHandler.get() -> unknown or empty object passed for the operation'); } } }; /** * Handle post array payload. * * @param payload * @param isPersistentUrl * @param collection * @param force * @returns {*} */ var handlePostRootArrayPayload = function (payload, isPersistentUrl, collection, force) { var keyNameToCompare = (isPersistentUrl.uri.tokens.length > 1) ? isPersistentUrl.uri.tokens[1].name : null; // go now throw what it was in the collection // and see if we have match to the new payload payload.forEach(function (obj) { if (isLokiDbObj(obj)) { markObjAsOfflineIfForced(obj, force); collection.update(obj); } // check if the payload has id, else if (keyNameToCompare && obj.hasOwnProperty(keyNameToCompare)) { // try to find the element in the db, if there update, otherwise inside! var result = collection.findOne({keyNameToCompare: obj[keyNameToCompare]}); if (result) { _.extendOwn(result, obj); markObjAsOfflineIfForced(result, force); collection.update(result); } else { // insert markObjAsOfflineIfForced(obj, force); collection.insert(obj); } } else { // if we don't have anything in the collection to compare var objInsertResult = collection.insert(obj); objInsertResult[keyNameToCompare] = buildUniqueIDValue(isPersistentUrl); //objInsertResult.$loki + ""; markObjAsOfflineIfForced(objInsertResult, force); return _.cleanObject(collection.update(objInsertResult)); } }); // on the end return the new collection return _.cleanObjects(collection.find()); }; /** * Handle post create object from only simple json object * @param payload * @param isPersistentUrl * @param collection * @param force * @returns {*} */ var handlePostRootObjectPayload = function (payload, isPersistentUrl, collection, force) { // well check first again if we have key specified in the $options var keyNameToCompare = (isPersistentUrl.uri.tokens.length > 1) ? isPersistentUrl.uri.tokens[1].name : ""; // check if the object has the same key if (keyNameToCompare && !payload.hasOwnProperty(keyNameToCompare)) { console.info('get payload', "does not have the key specified in the URL settings"); // if not then we have to create one empty payload[keyNameToCompare] = ""; // no need to query the db for this element // well this is completely new element and we should mark it as offline var insertResult = collection.insert(payload); if (insertResult) { insertResult[keyNameToCompare] = buildUniqueIDValue(isPersistentUrl)//insertResult.$loki + ""; // this flag means that we created this directly in the offline db markObjAsOfflineIfForced(insertResult, force); return _.cleanObject(collection.update(insertResult)); } // else we have an issue here throw new Error('unable to store the payload object'); } // ok this is the situation, where the key actually exist in the payload // let see if there is object with the same id if (keyNameToCompare && payload.hasOwnProperty(keyNameToCompare)) { // make sure that the payload var queryForObject = {}; queryForObject[keyNameToCompare] = payload[keyNameToCompare]; //var result = collection.findOne({keyNameToCompare: payload[keyNameToCompare]}); var result = collection.findOne(queryForObject); // this means that we have element with that key, so we have to update it if (result) { // merge properties! _.extendOwn(result, payload); markObjAsOfflineIfForced(result, force); return _.cleanObject(collection.update(result)); } // ok so if the above did not work, maybe there is a problem with the key string/int var rebuildKeyValue = buildUniqueIDValue(isPersistentUrl, payload[keyNameToCompare]); payload[keyNameToCompare] = rebuildKeyValue; } // if no key was specified in the URL option settings, we have no another option markObjAsOfflineIfForced(payload, force); return _.cleanObject(collection.insert(payload)); }; /** * Handle Post HTTP request! * * @param response {persistenceRequestHandler~Response} * @param force - it means that the meta['offline-persist'] property will be deleted to force update on next GET * @returns {*} */ var handlePost = function (response, force) { var parsed = $options.parseURL(response.url); var isPersistentUrl = $utils.isPersistUrl(parsed.path); // check if URL can be persist if (!isPersistentUrl) { throw new Error('Persistence.RequestHandler.post() given URI not configured for persistence: ' + parsed.path); } // get the parameters form the REST URL used to call the backend! var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); // get the collection for the given url var collection = $db.getCollectionByName(queryParams.root); // cache in between for easy access var payload = response.data; var keyValueObj = buildFindQueryBasedOnUrlParams(queryParams); // if not empty we can search if (!_.isEmpty(keyValueObj)) { // find parent object var result = collection.findOne(keyValueObj); // ok post used URL with key, so we have to create sub element here if (result) { var newObj = createObjFromUrlParamsForExistingForPost(result, isPersistentUrl, queryParams, payload); var propertyName = isPersistentUrl.uri.tokens[isPersistentUrl.uri.tokens.length - 1].name; newObj.result[propertyName] = buildUniqueIDValue(isPersistentUrl, newObj.result[propertyName]); markObjAsOfflineIfForced(newObj.obj, force); collection.update(newObj.obj); return _.cleanObject(newObj.result); } else { var newObj = createObjFromUrlParamsForExistingForPost(keyValueObj, isPersistentUrl, queryParams, payload); markObjAsOfflineIfForced(newObj.obj, force); collection.insert(newObj.obj); return _.cleanObject(newObj.result); } } // this situation will happen when we have ROOT path call, with no KEY specified // ok no key in the url but we have payload and it should be added somewhere // this also means that we are in the root! if (_.isArray(payload)) { return handlePostRootArrayPayload(payload, isPersistentUrl, collection, force); } // just object payload else if (_.isObject(payload) && !_.isArray(payload) && !_.isNull(payload)) { return handlePostRootObjectPayload(payload, isPersistentUrl, collection, force); } // dont' know what to do! :)! throw new Error("don't know what to do with the payload"); }; /** * Works like HTTP post * https://gist.github.com/wookiehangover/877067 * * @param response * @param force * @returns {*} */ var handlePut = function (response, force) { var parsed = $options.parseURL(response.url); var isPersistentUrl = $utils.isPersistUrl(parsed.path); // check if URL can be persist if (!isPersistentUrl) { throw new Error('Persistence.RequestHandler.post() given URI not configured for persistence: ' + parsed.path); } // get the parameters form the REST URL used to call the backend! var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); // get the collection for the given url var collection = $db.getCollectionByName(queryParams.root); // cache in between for easy access var payload = response.data; var keyValueObj = buildFindQueryBasedOnUrlParams(queryParams); // if we have attributed than the first one should be key we look for! if (!_.isEmpty(keyValueObj)) { var result = collection.findOne(keyValueObj); // this means that we have element with that key, so we have to update it if (result) { var newObj = createObjFromUrlParamsForExistingForPost(result, isPersistentUrl, queryParams, payload); markObjAsOfflineIfForced(newObj.obj, force); collection.update(newObj.obj); return newObj.result; } else { var newObj = createObjFromUrlParamsForExistingForPost(keyValueObj, isPersistentUrl, queryParams, payload); markObjAsOfflineIfForced(newObj.obj, force); collection.insert(newObj.obj); return newObj.result; } } // ok following is in the case that you call PUT on root with parameters! // makes PUT to work like POST! if (_.isArray(payload)) { return handlePostRootArrayPayload(payload, isPersistentUrl, collection, force); } // just object payload else if (_.isObject(payload) && !_.isArray(payload) && !_.isNull(payload)) { return handlePostRootObjectPayload(payload, isPersistentUrl, collection, force); } // dont' know:)! //throw new Error('unable to recognise the edit payload, it should be JSON Object or Array!'); throw new Error('no key specified to recognise obj in the database for editing!'); }; /** * Works like HTTP post * https://gist.github.com/wookiehangover/877067 * * @param response * @param force * @returns {*} */ var handlePatch = function (response, force) { var parsed = $options.parseURL(response.url); var isPersistentUrl = $utils.isPersistUrl(parsed.path); // check if URL can be persist if (!isPersistentUrl) { throw new Error('Persistence.RequestHandler.post() given URI not configured for persistence: ' + parsed.path); } // get the parameters form the REST URL used to call the backend! var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); // get the collection for the given url var collection = $db.getCollectionByName(queryParams.root); // cache in between for easy access var payload = response.data; var keyValueObj = buildFindQueryBasedOnUrlParams(queryParams); // if we have attributed than the first one should be key we look for! if (!_.isEmpty(keyValueObj)) { var result = collection.findOne(keyValueObj); // this means that we have element with that key, so we have to update it if (result) { var newObj = createObjFromUrlParamsForExistingForPost(result, isPersistentUrl, queryParams, payload); markObjAsOfflineIfForced(newObj.obj, force); collection.update(newObj.obj); return newObj.result; } else { var newObj = createObjFromUrlParamsForExistingForPost(keyValueObj, isPersistentUrl, queryParams, payload); markObjAsOfflineIfForced(newObj.obj, force); collection.insert(newObj.obj); return newObj.result; } } // ok following is in the case that you call PUT on root with parameters! // makes PUT to work like POST! if (_.isArray(payload)) { return handlePostRootArrayPayload(payload, isPersistentUrl, collection, force); } // just object payload else if (_.isObject(payload) && !_.isArray(payload) && !_.isNull(payload)) { return handlePostRootObjectPayload(payload, isPersistentUrl, collection, force); } // dont' know:)! //throw new Error('unable to recognise the edit payload, it should be JSON Object or Array!'); throw new Error('no key specified to recognise obj in the database for editing!'); }; /** * Delete specific element from the offline db * * @param request * @returns {*} */ var handleDelete = function (request) { var parsed = $options.parseURL(request.url); var isPersistentUrl = $utils.isPersistUrl(parsed.path); // check if URL can be persist if (!isPersistentUrl) { throw new Error('Persistence.RequestHandler.post() given URI not configured for persistence: ' + parsed.path); } var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); var collection = $db.getCollectionByName(queryParams.root); var keyValueObj = buildFindQueryBasedOnUrlParams(queryParams); // if we have attributed in the request URL specified!!! if (!_.isEmpty(keyValueObj)) { var findOne = collection.findOne(keyValueObj); if (findOne) { return _.cleanObject(collection.remove(findOne)); } throw new Error('unable to find object with the given ID(%s) in the database', keyValueObj); } // OK maybe the ID is in the payload! // NOTE: It is not good practice to have the ID in the payload, but it is possible! if (request.hasOwnProperty('data')) { var payload = request.data; if (!_.isEmpty(payload) && _.isObject(payload) && !_.isArray(payload)) { var keyNameToCompare = (isPersistentUrl.uri.tokens.length > 1) ? isPersistentUrl.uri.tokens[1].name : null; // check if the object has the same key if (keyNameToCompare && !request.data.hasOwnProperty(keyNameToCompare)) { throw new Error('payload does not have the key required to delete the object'); } var findOne = collection.findOne({keyNameToCompare: request.data[keyNameToCompare]}); if (findOne) { return _.cleanObject(collection.remove(findOne)); } } } console.error('payload does not have the key required to delete the object in the payload'); throw new Error('payload does not have the key required to delete the object in the payload'); }; // TODO: Yuri - move to helper or create base class, every handler will ahve such method function flush(path) { console.info('Persistence.RequestHandler.flush()', path); // if no path delete everything if (_.isEmpty(path)) { return $db.flush(); } else { var parsed = $options.parseURL(path); var isPersistentUrl = $utils.isPersistUrl(parsed.path); return new Promise(function (resolve, reject) { // check if URL can be persist if (!isPersistentUrl) { reject(new Error('Persistence.RequestHandler.flush() given URI not configured for persistence: ' + parsed.path)); } else { var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); resolve($db.getCollectionByName(queryParams.root).removeDataOnly()); } }); } } // public methods! this.getDB = function () { return $db; }; this.get = function (request) { var doGet = function (request) { console.info('Persistence.RequestHandler.get()'); isPersistentGetRequest(request); // copy the object to make sure that we don't work with the reference anymore! var _request = _.clone(request); if (!_request.hasOwnProperty('data') || _.isEmpty(_request.data)) { return _.clone(handleGet(_request)); } return _.clone(handleGetStore(_request)); }; // return all as a promise return new Promise(function (resolve) { resolve(doGet(request)); }); }; // actually this is the same as get but only for specific element this.post = function (request, force) { var doPost = function (request, force) { console.info('Persistence.RequestHandler.post()'); isPostRequest(request); // always clone before do some work with the object, // it takes some time but saves a lot of trouble! var _request = _.clone(request); //return handlePost(_request, force); return _.clone(handlePost(_request, force)); }; // promise return new Promise(function (resolve) { resolve(doPost(request, force)); }); }; this.put = function (request, force) { var doPut = function (request, force) { console.info('Persistence.RequestHandler.put()'); isPostRequest(request); // always clone the object before do some work var _request = _.clone(request); return _.clone(handlePut(_request, force)); }; // promise //return Promise.resolve(doPut(request, force)); return new Promise(function (resolve) { resolve(doPut(request, force)); }); }; this.patch = function (request, force) { var doPatch = function (request, force) { console.info('Persistence.RequestHandler.patch()'); isPostRequest(request); // always clone the object before do some work var _request = _.clone(request); return _.clone(handlePatch(_request, force)); }; // promise //return Promise.resolve(doPut(request, force)); return new Promise(function (resolve) { resolve(doPatch(request, force)); }); }; this.delete = function (request) { function doDelete(request) { console.info('Persistence.RequestHandler.delete()'); isPersistentRequest(request); // always clone the object before do some work var _request = _.clone(request); return _.clone(handleDelete(_request)); } // promise //return Promise.resolve(doDelete(request)); return new Promise(function (resolve) { resolve(doDelete(request)); }); }; // provide the url and you will get the collection for it, as result from promise! this.data = function (path) { function doData(path) { console.info('Persistence.RequestHandler.data()'); if (path == null) { throw new Error('Path cannot be empty!'); } var parsed = $options.parseURL(path); var isPersistentUrl = $utils.isPersistUrl(parsed.path); // check if URL can be persist if (!isPersistentUrl) { throw new Error('Persistence.RequestHandler.post() given URI not configured for persistence: ' + parsed.path); } var queryParams = $utils.extractKeyValuesFromUrl2(isPersistentUrl); return $db.getCollectionByName(queryParams.root); } // promise //return Promise.resolve(doData(path)); return new Promise(function (resolve) { resolve(doData(path)); }); }; this.router = function (request, force) { var self = this; return new Promise(function (resolve) { //resolve(doRouting(request, force)); if (!isPersistentGetRequest(request)) { console.error('Passed object is not defined request for GET!', request.url); throw new Error('Passed object is not defined request for GET!'); } // check if method provided! if (!request.hasOwnProperty('method')) { console.error('request.method was not provided!', request); throw new Error('request.method was not provided!'); } // copy the object to make sure that we don't work with the reference anymore! var _request = _.clone(request); // do routing! // if (_request.method === 'GET') { // if (!_request.hasOwnProperty('data') || _.isEmpty(_request.data)) { // var result = handleGet(_request) // return clone(result); // } // var result = handleGetStore(_request); // return clone(result); // } // exec the router specified _request.method = $utils.normalizeMethod(_request.method); if (!self[_request.method]) { console.error('specified router is not implemented!'); throw new Error('specified router is not implemented!'); } // exec the method var result = self[_request.method](_request, force); resolve(result); }); }; // provide path and you delete everything from the collection this.flush = flush; this.getModuleName = function () { return 'MCS'; }; // private methods this._createObjFromUrlParamsForExistingForPost = createObjFromUrlParamsForExistingForPost; this._buildNestedPropertyAddString = buildNestedPropertyArrayParams; this._buildNestedPropertySearchString = buildNestedPropertySearchString; this._createObjFromUrlParamsForExisting = createObjFromUrlParamsForGETAction; } /** * Persistence handler to triggers events when XHR Request ID finished! The interesting part here is that * the events are created anonym for the client using the this API. * * NOTE: Support IE9+ * @type {{addListener, removeListener, getListener, dispatchEvent, removeAllListeners, getAllEvents, runClearDeamon, toString}} */ function persistenceHandler() { 'use strict'; var i = 0, listeners = {}; var ttl = 30000;//30sec //1000 * 60; // all in ms var ttlInterval = 100 * 60 * 20; // in ms - each 2mins var daemon = null; /** * Add internal anonym listener * * @param event * @param handler * @param capture * @returns {*} */ var addInternListener = function (event, handler, capture) { // clean unused events! cleanEventsJob(); if (event == null) { throw new Error('event name cannot be null or undefined'); } if (handler == null || typeof handler !== 'function') { throw new Error('event handler cannot be null or undefined function'); } var element = window; if (capture != null || typeof capture === 'boolean') { element.addEventListener(event, handler, capture); } else { element.addEventListener(event, handler); } listeners[event] = { event: event, element: element, handler: handler, capture: capture, timestamp: new Date().getTime() }; return listeners[event]; }; var removeInternListener = function (name) { // fix - much than it was before! if (name != null) { if (listeners.hasOwnProperty(name)) { // you have to make sure that you have the same handler! listeners[name].element.removeEventListener(listeners[name].event, listeners[name].handler, listeners[name].capture); delete listeners[name]; } } }; var removeAllListeners = function () { // iterate through all events and remove it for (var name in listeners) { if (listeners.hasOwnProperty(name)) { if (typeof listeners[name] === 'object') { listeners[name].element.removeEventListener(listeners[name].event, listeners[name].handler, listeners[name].capture); delete listeners[name]; } } } }; var showAll = function () { for (var name in listeners) { if (listeners.hasOwnProperty(name)) { console.log('event details: ', listeners[name]); } } }; var getInternAllEvents = function () { return listeners; }; var getInternListener = function (name) { if (listeners.hasOwnProperty(name)) { if (typeof listeners[name] === 'object') { return listeners[name]; } } }; /** * Dispatch custom event, if registered and remove it from the listeners! IE9+ * * Reference: http://stackoverflow.com/questions/5660131/how-to-removeeventlistener-that-is-addeventlistener-with-anonymous-function * * @param status - http status code, like 200,300 so on * @param statusText - the http status text, like 'OK' * @param payload - the payload * @param requestID - internal request id */ var dispatchInternEvent = function (status, statusText, payload, requestID) { // works on IE9+ browsers if (!window.CustomEvent) { return; } // if such an event was not registered, does not need the overheader if (!listeners.hasOwnProperty(requestID) && !typeof listeners[requestID] !== 'object') { return; } // creates the custom event! var anonymEvent = new CustomEvent( requestID, { detail: { status: status, statusText: statusText, data: payload, requestid: requestID, time: new Date().getTime() }, bubbles: true, cancelable: true }); // async setTimeout(function () { // dispatch event could throw exception! // reference: https://developer.mozilla.org/de/docs/Web/API/EventTarget/dispatchEvent try { // fire var cancelled = window.dispatchEvent(anonymEvent); } catch (e) { console.error(e); } finally { // ... and remove // this will make sure that no memory leaks will happen, the object will be remove from the GC setTimeout(function () { //if (cancelled) { removeInternListener(requestID); //} }, 0); } }, 0); }; /** * Periodically remove unused events after specified TTL (Time to Leave)! */ var cleanEventsJob = function () { //console.debug('clean events daemon'); var age = ttl; var now = Date.now(); var registeredEvents = getInternAllEvents(); for (var eventName in registeredEvents) { if (registeredEvents.hasOwnProperty(eventName)) { var diff = now - listeners[eventName].timestamp; if (age < diff) { // remove it here removeInternListener(eventName); } } } }; /** * This will set and start the demo, or stop if if age < 0 * * @param age - the max leave age, or if 0 stop the deamon * @param interval - the interval on which to run the deamon */ var setTTL = function (age, interval) { if (age < 0) { if (daemon != null) { clearInterval(daemon); } } else if (age == 0) { // run once cleanEventsJob(); } else { ttl = age || ttl; ttlInterval = interval || ttlInterval; daemon = setInterval(cleanEventsJob, ttlInterval); } }; return { addListener: addInternListener, removeListener: removeInternListener, getListener: getInternListener, dispatchEvent: dispatchInternEvent, removeAllListeners: removeAllListeners, getAllEvents: getInternAllEvents, runClearDeamon: setTTL, toString: showAll }; } /** * Usage example: * * Persistence.Events.$on('success', function(args) { console.log('on success event emited', args); }); Persistence.Events.$on('error', function(args) { console.log('on error event emited', args); }); Persistence.Events.$on('timeout', function(args) { console.log('on timeout event emitted', args); }); Persistence.Events.$on('timeout', function(args) { console.log('on timeout event emitted again', args); }); setTimeout(function(){ Persistence.Events.$emit('success', {name: 'Lyudmil'}); Persistence.Events.$emit('error', {status: 500, error: 'this is error message'}); Persistence.Events.$emit('timeout', {msg: 'this is timeout error'}); Persistence.Events.$flush('success'); Persistence.Events.$emit('success', {name: 'Lyudmil'}); },3000); * * @type {{}} */ function persistenceEvents() { var observers = { "success": [], "error": [], "timeout": [] }; return { $on: function (name, observer) { if (name !== null && typeof name === 'string') { if (observers.hasOwnProperty(name)) { if (typeof observer === 'function') { observers[name].push(observer); } } } }, $emit: function (name, obj) { if (name !== null && typeof name === 'string') { if (observers.hasOwnProperty(name)) { if (obj !== null) { for (var i = 0; i < observers[name].length; i++) { // fire event observers[name][i](obj); } } } } }, $flush: function (name) { if (name !== null && typeof name === 'string') { if (observers.hasOwnProperty(name)) { //for(var i = 0; i < observers[name].length; i++){ for (var i = observers[name].length - 1; i >= 0; i--) { // remove the event observers[name].splice(0, 1); } } } }, $show: function (name) { throw new Error('not implemented'); } }; } /** * Global event emitter handler, usually used only for internal modules process work! * NOTE: This class is equal to singleton it will exist only once! */ function persistenceEventsEmitter() { /** * Events property is a hashmap, with each property being an array of callbacks! * @type {{}} */ var events = {}; /** * boolean determines whether or not the callbacks associated with each event should be * proceeded async, default is false! * * @type {boolean} */ var asyncListeners = false; return { /** * Adds a listener to the queue of callbacks associated to an event * * @param eventName - the name of the event to associate * @param listener - the actual implementation * @returns {*} - returns the ID of the lister to be use to remove it later */ on: function (eventName, listener) { var event = events[eventName]; if (!event) { event = events[eventName] = []; } event.push(listener); return listener; }, /** * Fires event if specific event was registered, with the option of passing parameters which are going to be processed by the callback * (i.e. if passing emit(event, arg0, arg1) the listener should take two parameters) * * @param eventName * @param data - optional object passed to the event! */ emit: function (eventName, data) { if (eventName && events[eventName]) { events[eventName].forEach(function (listener) { if (asyncListeners) { setTimeout(function () { listener(data); }, 1); } else { listener(data); } }); } // if event is not registered else { throw new Error('No event ' + eventName + ' defined'); } }, /** * Remove listeners * * @param eventName * @param listener */ removeListener: function (eventName, listener) { if (events[eventName]) { var listeners = events[eventName]; listeners.splice(listeners.indexOf(listener), 1); } } } } /** * Global event emitter for all persistence class, it can be inherited only via NEW, which will make * sure that specific instance exist only for the module initiating it! * * @constructor */ function PersistenceEventEmitter() { } /** * Stores all registered listeners! It could be overridden if the object prototype this class! * @type {{}} */ PersistenceEventEmitter.prototype.events = {}; /** * If listener should be executed async, default false */ PersistenceEventEmitter.prototype.asyncListeners = false; /** * Register listener! * * @param eventName - name * @param listener - actual call back implementation * @returns {*} - returns the ID of the listener to be used to remove the listener later! */ PersistenceEventEmitter.prototype.on = function (eventName, listener) { var event = this.events[eventName]; if (!event) { event = this.events[eventName] = []; } event.push(listener); return listener; }; /** * Fires the events to already registered listeners! * * @param eventName - the name of the registered listener * @param data - optional to pass data to the registered listener! */ PersistenceEventEmitter.prototype.emit = function (eventName, data) { var self = this; if (eventName && this.events[eventName]) { this.events[eventName].forEach(function (listener) { if (self.asyncListeners) { setTimeout(function () { listener(data); }, 1); } else { listener(data); } }); } else { throw new Error('No event ' + eventName + ' defined'); } }; /** * Remove already registered listener! * * @param eventName * @param listener */ PersistenceEventEmitter.prototype.removeListener = function (eventName, listener) { if (this.events[eventName]) { var listeners = this.events[eventName]; listeners.splice(listeners.indexOf(listener), 1); } }; /** * This module provides the sync capabilities of the persistence library. It makes sure that POST, PUT, and DELETE * operations will be merged. This module is equal as singleton, it will be init only once even used in several locations * * @type {{getHistory, get, post, put, delete, sync, forceSync, removeSync, flush, clear}} * @return {{getDB: Persistence.Sync.getDB, getHistory: Persistence.Sync.getHistory, get: Persistence.Sync.get, post: Persistence.Sync.post, put: Persistence.Sync.put, delete: Persistence.Sync.delete, router: Persistence.Sync.router, sync: handleSync, run: syncWithoutWorker, forceSync: Persistence.Sync.forceSync, operations: {run, stop, status, reset}, removeSync: Persistence.Sync.removeSync, flush: deleteAll, clear: Persistence.Sync.clear, events: internEventEmitter, isSyncRunning: statusSyncTransaction}} */ function persistenceSync($events, $common, $options, $utils, $handler) { 'use strict'; // private declarations var _syncRuns = false, _syncObj = null, _isDBTransaction = false, _defaultDBDelay = 2000, //2secs because ajax operations could take some time! _syncLogDirty = false, // in case db operations during the sync operation _ = $common; // replace underscore with own implementation /** * Init the DB * @type {{getDB, getCollection, getCollectionByName, getCollections, save, close, flush}} * @private */ //var $db = Persistence.DB('persist.sync'); var dbname = 'sync'; var prefix = $options.dbPrefix; // to ready/write data to specific collections var $db = persistenceDB(prefix + '.' + dbname, $options); // in case the db prefix has changed, re-init the db! $options.onDbPrefixChange = function (oldVal, newVal) { $db = persistenceDB(newVal + '.' + dbname, $options); }; /** * Internal events, which could be user from outside! * @type {{changes: Array, warning: Array}} */ function internEventEmitter() { this.events = { 'pre-put': [], 'pre-patch': [], 'pre-post': [], 'pre-get': [], 'pre-delete': [], 'pre-sync': [], 'post-sync': [], 'error-sync': [], 'end-sync': [] } } // inherit the event emitter with the default pre-defined events internEventEmitter.prototype = new PersistenceEventEmitter(); var _moduleEventEmitter = new internEventEmitter(); /** * Get collection reference from the sync log. * * @param collection * @returns {*} */ function getSyncLog(collection) { return $db.getCollectionByName(collection); } /** * Marks when db operation starts */ function startDBTransaction() { return _isDBTransaction = true; } /** * Finish the db operation */ function commitDBTransaction(isError) { if (!isError)_syncLogDirty = true; return _isDBTransaction = false; } /** * Check if there is DB transaction status! * @returns {boolean} */ function isDBTransaction() { return _isDBTransaction; } var _dbTransactionLockCounter = 0; /** * Lock function, which will stop execution and repeat operation until db operation is released! * * @returns {number} - 1: when the lock is released, -1 if more then 10 times the lock was not released, 1 - if released * @type {number} */ function checkAndWaitUntilDbTransactionFinish() { _dbTransactionLockCounter++; if (isDBTransaction() === true) { if (_dbTransactionLockCounter > 10) { _dbTransactionLockCounter = 0; // reset the lock but return false, which means the DB operation did not return completion return -1; // this means we tries 10times and lock was not releases } return 0; // this pending } else { // release the lock! _dbTransactionLockCounter = 0; return 1; } } /** * Check if the given object is suitable for the sync log. * * @param options * @returns {boolean} */ var isSyncRequest = function (options) { if (_.isEmpty(options)) { throw new Error('sync options is empty object, cannot be synced!'); } if (!options.hasOwnProperty('url')) { throw new Error('options.url was not specified!'); } else { if (_.isEmpty(options.url)) { throw new Error('options.url cannot be empty!'); } } if (!options.hasOwnProperty('headers')) { throw new Error('options.headers were not specified!'); } else { if (!_.isObject(options.headers)) { throw new Error('options.headers is not a objects!'); } } if (!options.hasOwnProperty('data')) { throw new Error('options.data was not specified!'); } else { if (_.isEmpty(options.data)) { throw new Error('options.data cannot be empty object!'); } if (!_.isObject(options.data)) { throw new Error('options.data is not a object!'); } } return true; }; /** * Check if the provided request is suitable to be used as delete sync request. The major difference here, * that we do not check for data in the payload, as this is not required for the delete call! * * @param options * @returns {boolean} */ var isDeleteSyncRequest = function (options) { if (_.isEmpty(options)) { throw new Error('sync options is empty object, cannot be synced!'); } if (!options.hasOwnProperty('url')) { throw new Error('options.url was not specified!'); } else { if (_.isEmpty(options.url)) { throw new Error('options.url cannot be empty!'); } } if (!options.hasOwnProperty('headers')) { throw new Error('options.headers were not specified!'); } else { if (!_.isObject(options.headers)) { throw new Error('options.headers is not a objects!'); } } return true; }; /** * buildDBObjectFindQuery result * @callback Persistence.Sync~buildDBObjectFindQueryReturn * @param dbquery {String}. * @param url {String}. * @param queryUrl {String}. */ /** * Internal function only! Builds the query based on URL or Payload data, or if non of them provided based on * the internal db key. * * @param requestOptions - make sure that you check the object if correct before pass it here! * @returns {Persistence.Sync~buildDBObjectFindQueryReturn} * @deprecated - this should be inside the parsing payload module! */ var buildDBObjectFindQuery = function (requestOptions) { // parse the root var url = isURLConfiguredForPersistence(requestOptions.url, true); var dbQuery = {}; // the key in the URL has always higher priority! //if (query.attr.length > 0) { if (!_.isEmpty(url.params) && $options.Module.getModuleName() !== 'MCS') { //var key = 'data.' + query.attr[0].name; // returns the name of the FIRST key! var key = 'data.' + url.params[0].name //Object.keys(url.params)[0]; //var value = (query.attr[0].pattern.indexOf('\d') >= 0) ? parseInt(query.attr[0].value) : query.attr[0].value + ""; // get the value of the key //var value = (url.tokens[0].pattern.indexOf('\d') >= 0) ? parseInt(url.params[Object.keys(url.params)[0]]) : url.params[Object.keys(url.params)[0]] + ""; var value = (url.tokens[0].pattern.indexOf('\d') >= 0) ? parseInt(url.params[0].value, 10) : url.params[0].value + ""; dbQuery[key] = { '$eq': value }; } else if (url.tokens.length > 0 && $options.Module.getModuleName() !== 'MCS') { // check and get the key from the data payload // we can get the name of the key to compare var keyNameToCompare = url.tokens[0].name; if ('data' in requestOptions && keyNameToCompare in requestOptions.data) { var key = 'data.' + keyNameToCompare; dbQuery[key] = { '$eq': requestOptions.data[keyNameToCompare] }; } } else if ('data' in requestOptions && '$loki' in requestOptions.data && typeof (requestOptions.data.$loki) === 'number' && !isNaN(requestOptions.data.$loki)) { var key = 'data.$loki'; dbQuery[key] = { '$eq': requestOptions.data.$loki }; } // otherwise try to use the internal db key // note correct we can have more then one collection with the same db key! else if ('$loki' in requestOptions && typeof (requestOptions.$loki) === 'number' && !isNaN(requestOptions.$loki)) { dbQuery = { '$loki': { '$eq': requestOptions.$loki } }; } else { // sorry don't know what to do! } return { dbquery: dbQuery, url: url.path, queryUrl: url }; } /** * Internal function checks if the given URL is configured for persistence and returns * the parsed objects from it. * * @param path * @param returnUrl - boolean, if true it will return the URL properties frm the regex config, otherwise will extract the url directly for you * @returns {*} */ function isURLConfiguredForPersistence(path, returnUrl) { // check if this URL was configured for sync operations var persistentPath = $options.isPersistentUrl(path); if (persistentPath === false) { console.error('give url not configured for persistence', path); throw new Error('give url not configured for persistence:' + path); } // extract the root and get the collections data if (!returnUrl) { return persistentPath; } return persistentPath; } /** * Stores HTTP GET request in the sync log. * * NOTE: Get is always new entry in the DB, it doesn't matter if the sync runs or not! * @returns {*} * @param requestOptions */ function handleGet(requestOptions) { if (_.isEmpty(requestOptions)) { throw new Error('sync options is empty object, cannot be synced!'); } // we only need to check for URL here if (!requestOptions.hasOwnProperty('url')) { throw new Error('options.url was not specified!'); } else { if (_.isEmpty(requestOptions.url)) { throw new Error('options.url cannot be empty!'); } } if (!requestOptions.hasOwnProperty('headers')) { throw new Error('request headers were not specified!'); } // we can work only with empty objects to execute GET's, so clean the get data if any if (!_.isEmpty(requestOptions.data)) { requestOptions.data = {}; } requestOptions['method'] = "GET"; _moduleEventEmitter.emit('pre-get', requestOptions); // TODO: check whey getSyncLog called without collection name return getSyncLog().insert(requestOptions); }; /** * Create new object * NOTE: Each time you call POST, you will create new object! If you want to update object use PUT! * NOTE: This will always create new element, independent from the sync runs! * * @param requestOptions * @returns {*} */ function handlePost(requestOptions) { // check first if it's sync request isSyncRequest(requestOptions); var query = isURLConfiguredForPersistence(requestOptions.url); // remove the $loki from the request, otherwise it will prevent to store it again! // NOTE: This could happen only if you work with the DB objects directly! if ('$loki' in requestOptions && typeof (requestOptions.$loki) === 'number' && !isNaN(requestOptions.$loki)) { delete requestOptions.$loki; } // store if the data object has id from the offline database //if ('$loki' in requestOptions.data && typeof (requestOptions.data.$loki) === 'number' && !isNaN(requestOptions.data.$loki)) { // override to make clear that this is POST method requestOptions['method'] = "POST"; requestOptions['URI'] = query.root; // get the collection to be able to execute the operation _moduleEventEmitter.emit('pre-post', requestOptions); return getSyncLog().insert(requestOptions); } /** * Update existing object in the sync log! * * @param requestOptions */ function handlePut(requestOptions) { isSyncRequest(requestOptions) var urlParsedObjects = buildDBObjectFindQuery(requestOptions); var _syncLog = getSyncLog(); // query.root _moduleEventEmitter.emit('pre-put', requestOptions); // no dbquery is empty, it means that we never had this put before if (_.isEmpty(urlParsedObjects.dbquery)) { // ok so if non of the above just save directly to the sync log, as long as the request // has URL and headers the sync will try to execute it against the backend server! requestOptions['method'] = 'PUT'; requestOptions['URI'] = urlParsedObjects.queryUrl.root; return _syncLog.insert(requestOptions); } // parse the root //var query = isURLConfiguredForPersistence(requestOptions.url); // try to check first if there was a POST already for the same element! var _findInHistory = _syncLog.findOne({ '$and': [ urlParsedObjects.dbquery, { 'method': 'POST' }, { 'URI': urlParsedObjects.queryUrl.root }] }); // if not null, then there is POST element, so update it! // but check first if this entry is in the process queue! // check to see if this post is already in execution, is yes, wait until exec ready and go // throw the process again! if (_findInHistory) { //ok check first now if this entry is on process! if (_syncObj && !_.isEmpty(_syncObj)) { if ('$loki' in _syncObj && _syncObj.$loki === _findInHistory.$loki) { // repeat then 2sec later setTimeout(function () { // repeat handlePut(requestOptions); }, _defaultDBDelay); } } // POST was found, then merge the data _.extendOwn(_findInHistory.data, requestOptions.data); _.extendOwn(_findInHistory.headers, requestOptions.headers); // zero the errors so that it could be executed again! _findInHistory.$errorcounter = 0; return _syncLog.update(_findInHistory); } // search for existing/previous PUT with the same ID _findInHistory = _syncLog.findOne({ '$and': [ urlParsedObjects.dbquery, { 'method': 'PUT' }, { 'URI': urlParsedObjects.queryUrl.root }] }); // if found MERGE if (_findInHistory) { //ok check first now if this entry is on process! if (_syncObj && !_.isEmpty(_syncObj)) { if ('$loki' in _syncObj && _syncObj.$loki === _findInHistory.$loki) { // repeat then 2sec later setTimeout(function () { // repeat handlePut(requestOptions); }, _defaultDBDelay); } } _.extendOwn(_findInHistory, requestOptions); // zero the errors so that it could be executed again! _findInHistory.$errorcounter = 0; return _syncLog.update(_findInHistory); } // OK we had no POST and no PUT so insert the PUT // however store only if the data object has internal id from the DB //if ('$loki' in requestOptions && typeof (requestOptions.$loki) === 'number' && !isNaN(requestOptions.$loki)) { // insert as put requestOptions['method'] = 'PUT'; requestOptions['URI'] = urlParsedObjects.queryUrl.root; return _syncLog.insert(requestOptions); } /** * Update existing object in the sync log! * * @param requestOptions */ function handlePatch(requestOptions) { isSyncRequest(requestOptions); var urlParsedObjects = buildDBObjectFindQuery(requestOptions); var _syncLog = getSyncLog(); // query.root _moduleEventEmitter.emit('pre-patch', requestOptions); // no dbquery is empty, it means that we never had this put before if (_.isEmpty(urlParsedObjects.dbquery)) { // ok so if non of the above just save directly to the sync log, as long as the request // has URL and headers the sync will try to execute it against the backend server! requestOptions['method'] = 'PATCH'; requestOptions['URI'] = urlParsedObjects.queryUrl.root; return _syncLog.insert(requestOptions); } // parse the root //var query = isURLConfiguredForPersistence(requestOptions.url); // try to check first if there was a POST already for the same element! var _findInHistory = _syncLog.findOne({ '$and': [ urlParsedObjects.dbquery, { 'method': 'POST' }, { 'URI': urlParsedObjects.queryUrl.root }] }); // if not null, then there is POST element, so update it! // but check first if this entry is in the process queue! // check to see if this post is already in execution, is yes, wait until exec ready and go // throw the process again! if (_findInHistory) { //ok check first now if this entry is on process! if (_syncObj && !_.isEmpty(_syncObj)) { if ('$loki' in _syncObj && _syncObj.$loki === _findInHistory.$loki) { // repeat then 2sec later setTimeout(function () { // repeat handlePut(requestOptions); }, _defaultDBDelay); } } // POST was found, then merge the data _.extendOwn(_findInHistory.data, requestOptions.data); _.extendOwn(_findInHistory.headers, requestOptions.headers); // zero the errors so that it could be executed again! _findInHistory.$errorcounter = 0; return _syncLog.update(_findInHistory); } // search for existing/previous PATCH with the same ID _findInHistory = _syncLog.findOne({ '$and': [ urlParsedObjects.dbquery, { 'method': 'PATCH' }, { 'URI': urlParsedObjects.queryUrl.root }] }); // if found MERGE if (_findInHistory) { //ok check first now if this entry is on process! if (_syncObj && !_.isEmpty(_syncObj)) { if ('$loki' in _syncObj && _syncObj.$loki === _findInHistory.$loki) { // repeat then 2sec later setTimeout(function () { // repeat handlePatch(requestOptions); }, _defaultDBDelay); } } _.extendOwn(_findInHistory, requestOptions); // zero the errors so that it could be executed again! _findInHistory.$errorcounter = 0; return _syncLog.update(_findInHistory); } // OK we had no POST and no PATCH so insert the PATCH // however store only if the data object has internal id from the DB //if ('$loki' in requestOptions && typeof (requestOptions.$loki) === 'number' && !isNaN(requestOptions.$loki)) { // insert as put requestOptions['method'] = 'PATCH'; requestOptions['URI'] = urlParsedObjects.queryUrl.root; return _syncLog.insert(requestOptions); } /** * Delete object from the sync log * @param requestOptions */ function handleDelete(requestOptions) { isDeleteSyncRequest(requestOptions) var urlParsedObjects = buildDBObjectFindQuery(requestOptions); _moduleEventEmitter.emit('pre-delete', requestOptions); var _syncLog = getSyncLog(); //query.root if (_.isEmpty(urlParsedObjects.dbquery)) { // ok so if non of the above just save directly to the sync log, as long as the request // has URL and headers the sync will try to execute it against the backend server! requestOptions['method'] = 'DELETE'; requestOptions['URI'] = urlParsedObjects.queryUrl.root; return _syncLog.insert(requestOptions); } // find POST with the same ID var _findInHistory = _syncLog.findOne({ '$and': [ urlParsedObjects.dbquery, { 'URI': urlParsedObjects.queryUrl.root }, { 'method': { '$eq': 'POST' } }] }); // if not null, than there is POST element, remove it! if (_findInHistory) { //ok check first now if this entry is on process! if (_syncObj && !_.isEmpty(_syncObj)) { if ('$loki' in _syncObj && _syncObj.$loki === _findInHistory.$loki) { // repeat then 2sec later setTimeout(function () { // repeat handleDelete(requestOptions); }, _defaultDBDelay); } } // delete the object from the history table return _syncLog.remove(_findInHistory); } // OK check then if there was a PUT before! _findInHistory = _syncLog.findOne({ '$and': [ urlParsedObjects.dbquery, { 'URI': urlParsedObjects.queryUrl.root }, { 'method': { '$eq': 'PUT' } }] }); // if yes, remove the PUT and include the delete // this assumes the it always gonna be only one PUT, see handlePUT! if (_findInHistory) { //ok check first now if this entry is on process! if (_syncObj && !_.isEmpty(_syncObj)) { if ('$loki' in _syncObj && _syncObj.$loki === _findInHistory.$loki) { // repeat then 2sec later setTimeout(function () { // repeat handleDelete(requestOptions); }, _defaultDBDelay); } } // don't remove just update with the delete data, it will save operation _findInHistory['url'] = requestOptions['url']; _findInHistory['method'] = 'DELETE'; _findInHistory['URI'] = urlParsedObjects.queryUrl.root; if ('data' in requestOptions) { _findInHistory['data'] = requestOptions['data']; } // zero the errors so that it could be executed again! _findInHistory.$errorcounter = 0; return _syncLog.update(_findInHistory); } // if non of the above is working store the delete request! requestOptions['method'] = 'DELETE'; requestOptions['URI'] = urlParsedObjects.queryUrl.root; return _syncLog.insert(requestOptions); } /** * If sync operation for specific entry successful finished, remove the entry from the sync log table! * * @param request * @returns {*} */ function removeSync(request) { if (_.isEmpty(request)) { throw new Error('removeSync(request) is empty cannot be removed from the sync log!'); } if (!_.isObject(request)) { throw new Error('removeSync(request) is not a object!'); } // we only need to check for URL here if (!request.hasOwnProperty('url')) { throw new Error('request.url was not specified!'); } else { if (_.isEmpty(request.url)) { throw new Error('request.url cannot be empty!'); } } if (!('$loki' in request && typeof (request.$loki) === 'number' && !isNaN(request.$loki))) { throw new Error('removeSync(request.$loki) does not exist to be able to be removed from the sync table!'); } var _syncLogCollection = getSyncLog(); var _findInSyncLog = _syncLogCollection.findOne({'$loki': request.$loki}); // if exist if (_findInSyncLog) { // remove synced object! return _syncLogCollection.remove(_findInSyncLog); } // this doesn't necessarily means something bad, it could be that we had a POST and this entry was removed! //throw new Error('unable to find request with given id from the sync log to be removed'); return; } /** * Custom XHR internal error message! * * @param message - error message * @param code - http code * @param response - payload response * @constructor */ function XhrError(message, status, response, headers) { this.name = 'XhrError'; this.message = message || 'Error during XHR2 execution'; this.status = status || 0; this.response = response || ''; this.headers = headers || {}; this.stack = (new Error()).stack; } XhrError.prototype = Object.create(Error.prototype); XhrError.prototype.constructor = XhrError; /** * Uses XHR2 standard to execute ajax call to the backend server. In modern browser since IE9 all browsers * support XHR2, no polyfill required! * * @param method - http method, like POST, GET and son * @param url - to the backend server * @param headers - available headers * @param data * @param timeout * @returns {*} */ function syncXhr2(method, url, headers, data, responseType, timeout) { // TODO: Check the provided variables! return new Promise(function (resolve, reject) { // first make sure that we don't use the interceptor! $options.oneOff(); var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { xhr.withCredentials = true; } if(responseType){ xhr.responseType = responseType; } xhr.open(method, url, true); for (var key in headers) { if (headers.hasOwnProperty(key)) { var obj = headers[key]; xhr.setRequestHeader(key, obj); } } xhr.timeout = timeout || $options.timeout; xhr.ontimeout = function (e) { console.error('sync.xhr.ontimeout', e); $events.$emit('timeout', { event: e }); reject(new TypeError('Timeout during XHR load')); }; // http://docs.oracle.com/cloud/latest/mobilecs_gs/MCSUA/GUID-7C2A0D49-F898-4886-9A6A-4FF799F776F4.htm#MCSUA-GUID-1BF6EE73-A45B-4CE5-B390-3727F718FB92 xhr.onload = function () { //console.log('sync.xhr.onload', xhr); //console.log('sync.xhr.headers', xhr.getAllResponseHeaders()); // TODO: consider following link to adapt the the Oracle REST Error Codes! // todo: https://docs.oracle.com/cloud/latest/mobilecs_gs/MCSUA/GUID-12D976D7-5FCA-49C1-8D85-44A9BC438254.htm#MCSUA-GUID-EF96F2E5-8776-4169-9666-9C53EEA4F3F7 if (xhr.status >= 200 && xhr.status < 400) { resolve(xhr); } else { reject(xhr); } }; xhr.onerror = function () { console.log('sync.xhr.onerror', xhr); $events.$emit('error', { event: xhr }); reject(xhr); }; // send data if any! xhr.send((!data || typeof data === 'undefined' || data == null || method === 'DELETE') ? null : JSON.stringify(data)); }); } /** * Makes sure that it cleans the sync log object form the database form DB specific arguments. * * @param [obj] {Object} Should be passed by value! * @param [cloneObject] {Boolean} Value to notify if object should be clone! */ function cleanSyncLogObjectFromDBSpecificProperties(obj, cloneObject) { var _obj = cloneObject ? JSON.parse(JSON.stringify(obj)) : obj; if ('data' in _obj && _obj.data != null) { if (_.isObject(_obj.data) && !_.isEmpty(_obj.data)) { if ('$loki' in _obj.data && typeof(_obj.data.$loki) === 'number' && !isNaN(_obj.data.$loki)) { delete _obj.data.$loki; } if ('meta' in _obj.data) { delete _obj.data.meta; } // clean everything that starts with _$ for (var property in _obj.data) { if (_.stringStartsWith(property, '$mcs$')) { delete _obj.data[property]; } } } } return _obj; } /** * Completely delete all data for given collection path, or in case empty flush for all collections * @param path - url path to try to get specific collection to delete if empty remove all collections data */ function flushCollection(path) { console.info('Persistence.Sync.flush()', path); // if no path delete everything if (_.isEmpty(path)) { return $db.flush(); } else { // alright need to check first if this path really was defined! var query = isURLConfiguredForPersistence(path); return new Promise(function (resolve, reject) { // do this only if no sync is running! if (_syncRuns == true) { reject(new Error('unable to proceed with this operation, sync is in process')); } else { resolve(getSyncLog(query.root).removeDataOnly()); } }); } } /** * Mark flag that transaction is in execution. */ function startSyncTransaction() { _syncRuns = true; } /** * Stop current transaction execution */ function stopSyncTransaction() { _syncRuns = false; } /** * Current sync status. * * @returns {boolean} - true if it is running, otherwise false */ function statusSyncTransaction() { return _syncRuns; } /** * If you pass the promises, it will make sure that it change the transation flag before return the promise to the client * @param resolve * @param reject * @param promise */ function responsePromise(resolve, reject, promise) { promise.then(function (result) { commitDBTransaction(); resolve(result); }).catch(function (err) { commitDBTransaction(true); console.error(err); reject(err); }); } /** * Proceed XHR operation against a given sync obj * * @type {{run}} */ var syncProcess = (function () { var storeError = function (obj, message, code, response) { // collect all errors if (!Array.isArray(_syncObj.$error)) { obj.$error = []; } // make sure that you collect only the last maxSyncAttempts errors if (obj.$error.length > $options.maxSyncAttempts) { obj.$error.shift(); } obj.$error.push({ 'status': code || 0, 'response': response || [], 'message': message || 'Unknown error' }); // FIX: 26.06.2016 - counter should be equal the error array! obj.$errorcounter = obj.$error.length; getSyncLog().update(obj); }; var onError = function (xhr, obj) { try { console.error(xhr, obj); if (!xhr instanceof XMLHttpRequest) { if ('SYNCID' in obj) { $handler.dispatchEvent(400, 'Bad Request', undefined, obj.SYNCID); } throw new Error('unknown XHR error during the sync process'); } if ('SYNCID' in obj) { $handler.dispatchEvent(xhr.status, xhr.statusText, xhr, obj.SYNCID); } var response = ('response' in xhr) ? xhr.response : xhr.responseText || []; _moduleEventEmitter.emit('error-sync', { 'status': xhr.status || 0, 'response': response, 'message': xhr.statusText || 'Unknown error' }); storeError(obj, xhr.statusText, xhr.status, response); } catch (e) { console.error(e); } finally { return true; } }; var removeAfterReachHighCount = function (obj) { if ($options.autoRemoveAfterReachMaxAttemps === true) { var promise = new Promise(function (resolve) { resolve(removeSync(obj)); }); promise.catch(function (err) { onError(err.message, 0, ''); }); } }; var onSuccess = function (obj, xhr) { var response = { 'status': xhr.status, 'statusText': xhr.statusText, 'response': ('response' in xhr) ? xhr.response : xhr.responseText, 'headers': xhr.getAllResponseHeaders(), 'syncObj': obj // request object, used to proceed the XHR call }; // ok if we get to here all went good!:) _moduleEventEmitter.emit('post-sync', response); // dispatch event to the request listener, if any! if ('SYNCID' in obj) { $handler.dispatchEvent(response.status, response.statusText, xhr, obj.SYNCID); } return response; }; var postSuccessOperations = function (original, obj) { // remove offline tag if object was created updated only in the offline DB! if (obj.syncObj.method === 'POST' || obj.syncObj.method === 'PUT') { var cpObj = _.clone(obj); // do this only if URL configured for persistence and noCache is FALSE var persistentPath = $options.isPersistentUrl(cpObj.syncObj.url); if (persistentPath === false || persistentPath.isPolicy('noCache', true)) { console.debug('sync post success operation exist'); return; } var response = ''; if (_.isString(cpObj.response)) { response = JSON.parse(cpObj.response); } // merge the data from the response with the existing object in the db! response = _.extendOwn(cpObj.syncObj.data, response); // do this only if this is a db relevant //if ($utils.isLokiDbObj(response)) { //!obj.response ? obj.syncObj.data : _.extendOwn(obj.syncObj.data, response); var headers = $utils.parseResponseHeaders(cpObj.headers); // this will be executed actually after the db operation! var update = { url: cpObj.syncObj.url, data: response, // if we had already entry in the DB than just update it method: (persistentPath.isPolicy('fetchPolicy', 'FETCH_FROM_CACHE_SCHEDULE_REFRESH')) ? 'PUT' : cpObj.syncObj.method, //method: 'PUT', headers: headers }; // module defines what will be used! $options.Module.router(update, true).catch(function (err) { // error here does not have to be expose! console.error(err); }); } // return the merged object return response; }; /** * Process method parameter * @callback Persistence.Sync~processParam * @param url {String}. * @param headers {Array}. * @param data {Object}. * @param method {String} GTE, POST, DELETE. */ /** * Proceed XHR call with the object data * @param [obj] {Persistence.Sync~processParam} From the sync transaction log */ var process = function (obj) { return new Promise(function (resolve) { // attempt to sync if ($options.maxSyncAttempts === 0 || ((obj.$errorcounter || 0) <= $options.maxSyncAttempts)) { console.log('syncProcess.process', obj); _moduleEventEmitter.emit('pre-sync', obj); // clean the data from db specific elements before exec the XHR! var cleanDbObject = cleanSyncLogObjectFromDBSpecificProperties(obj, true); // - syncXhr2(cleanDbObject.method, cleanDbObject.url, cleanDbObject.headers, cleanDbObject.data, cleanDbObject.responseType, $options.syncTimeOut) .then(onSuccess.bind(this, obj)) .then(function (response) { removeSync(obj); return response; }) .then(postSuccessOperations.bind(this, obj)) .catch(function (e) { return onError(e, obj); }) .then(function () { resolve(true); }) } // in that case we may want to auto-clean the object! else { removeAfterReachHighCount(obj); resolve(true); } }); }; return { run: process } }()); /** * This inner class which will handle the transaction sync * * @type {{run, stop, status, reset}} */ var syncQueue = (function ($sync) { var $queue = [], $index = 0, $stopSync = false, $defaultDelay = $options.syncTimeOut, $isRunning = false, $forceRun = false; /** * Process given object, this is where we will execute the operation! */ var process = function (obj) { return new Promise(function (resolve, reject) { try { $sync.run(obj) .then(function () { resolve(true); }) .catch(function (e) { reject(e); }); } catch (e) { // error, what to do! console.error(e); reject(e); } }); }; /** * Execs all pending sync transactions, one by one, as stored in the transaction table! * */ var next = function () { if ($stopSync) return; // if db in lock, repeat few ms later // 1: when the lock is released, -1 if more then 10 times the lock was not released, 1 - if released var lockState = checkAndWaitUntilDbTransactionFinish(); if (lockState == -1) { console.warn('sync db lock not released, restart the sync process!'); // L.Pelov 4 Jul - alternative approach // setTimeout(next, 200); // 200ms later try again! next(); return; } else if (lockState == 0) { // loop again //delay = 500; //500ms next(); return; } var i = $index++ , nextObj = $queue[$index]; _syncObj = $queue[i]; if (!_syncObj) { rerun(); return; } process(_syncObj).then(function () { doNext(nextObj, _syncObj) && setTimeout(function () { // go for the next! next(); }, 1); }).catch(function (error) { console.log('unknown sync process error', error); //stop(); rerun(); // L.Pelov - fix to make possible that sync will rerun if error! }); }; var runSync = function (force) { // TODO: Add promise to return when operation is ready! // TODO: http://stackoverflow.com/questions/34255351/is-there-a-version-of-settimeout-that-returns-an-es6-promise // var ctrState, rejection, p = new Promise(function (resolve, reject) { // ctrState = setTimeout(resolve, ms); // rejection = reject; // }); // p.cancel = function () { // clearTimeout(ctrState); // rejection(Error("Sync process was cancelled!")); // }; // return p; if ($options.off) return; if (!force && typeof force !== "boolean") force = false; if ($options.autoSync === false && force === false) return; // check first if online, if not try later! if (!$options.isOnline()) { rerun(); return; } // do not exec again if the process is running! if ($isRunning) { $forceRun = true; return; } setTimeout(function () { $isRunning = true; $stopSync = false; // indicates that sync transaction runs now! startSyncTransaction(); // populate the sync table to the queue $queue = getSyncLog().find(); try { next(); } catch (e) { console.log(e); rerun(); } }, getDelay(force)); }; var doNext = function (obj, lastObj) { // there is next element, operation can continue if (obj) return true; // will restart the process after the specified timeout rerun(); // fire event that there are no more elements to sync! _moduleEventEmitter.emit('end-sync', lastObj); return false; }; var rerun = function () { // clean the tmp _syncObj = {}; reset(); // will restart the process after the specified timeout setTimeout(function () { runSync(); }, getDelay()); }; var stop = function () { stopSyncTransaction(); $stopSync = true; $isRunning = false; }; var reset = function () { stop(); $isRunning = false; $index = 0; $queue.length = 0; }; var status = function () { return { current: $index, obj: $queue[$index], size: $queue.length, isRunning: $isRunning } }; /** * Defines how often to repeat the process, auto-sync! * @param force * @returns {*} */ var getDelay = function (force) { if (force) { return 1; } if ($forceRun) { $isRunning = false; // L.Pelov - fix 05.08.2016 $forceRun = false; return 1; } if (_syncLogDirty) { _syncLogDirty = false; return 1; } return $defaultDelay; }; return { run: runSync, stop: stop, status: status, reset: reset } }(syncProcess)); // public API return { getDB: function () { return $db; }, /** * This is not save, it will always return the collection to the caller, so you can remove entries even * during the sync is running! * * @param options */ getHistory: function (options) { return new Promise(function (resolve) { resolve(getSyncLog(options)); }); }, get: function (options) { return new Promise(function (resolve, reject) { startDBTransaction(); var promise = new Promise(function (_resolve) { _resolve(handleGet(options)); }); responsePromise(resolve, reject, promise); }); }, post: function (options) { return new Promise(function (resolve, reject) { startDBTransaction(); var promise = new Promise(function (_resolve) { _resolve(handlePost(options)); }); responsePromise(resolve, reject, promise); }); }, put: function (options) { return new Promise(function (resolve, reject) { startDBTransaction(); var promise = new Promise(function (_resolve) { _resolve(handlePut(options)); }); responsePromise(resolve, reject, promise); }); }, patch: function (options) { return new Promise(function (resolve, reject) { startDBTransaction(); var promise = new Promise(function (_resolve) { _resolve(handlePatch(options)); }); responsePromise(resolve, reject, promise); }); }, delete: function (options) { return new Promise(function (resolve, reject) { startDBTransaction(); var promise = new Promise(function (_resolve) { _resolve(handleDelete(options)); }); responsePromise(resolve, reject, promise); }); }, router: function (options) { var self = this; // route the request and auto-start sync! var routing = function (options) { //console.log('Persistent.Sync.router'); if (_.isEmpty(options)) { console.error('sync router request was not provided!', options); throw new Error('sync router request was not provided!'); } // check if method provided! if (!options.hasOwnProperty('method') && !_.isEmpty(options.method)) { console.error('sync router method was not provided!', options); throw new Error('sync router method was not provided!'); } // exec the router specified var _options = _.clone(options); _options.method = $utils.normalizeMethod(_options.method); if (!self[_options.method]) { console.error('specified router is not implemented!'); throw new Error('specified router is not implemented!'); } // exec the method return new Promise(function (resolve) { //resolve(_.clone(self[request.method](options))); resolve(self[_options.method](_options)); }); }; // if the operation was successful run the sync job! return new Promise(function (resolve, reject) { var promise = new Promise(function (_resolve) { _resolve(routing(options)); }); // promise.then(function (result) { // re-run the sync to make sure that this new entry will be picked! // force sync log run! //syncQueue.run(true); // resolve should be returned only when async operation finished! resolve(result); }).catch(function (err) { reject(err); }); }); }, operations: syncQueue, removeSync: function (request) { return new Promise(function (resolve) { resolve(removeSync(_options)); }); }, flush: flushCollection, events: _moduleEventEmitter, /** * Return true with the sync process is running, otherwise return false! * Before proceed with XHR request we should always make sure that sync is executed! */ isSyncRunning: statusSyncTransaction }; } /** * Intercepts the XMLHTTPRequest * @type {{run, runWithoutReadInBackground, listener, registerRequestCompletedCallback}} */ // Run all Ajax calls with this helper if alwaysOn = false! function persistenceProcess($options, $common, $handler) { var REQUEST_ID = 'Request-ID'; return { run: function (callback) { // NOTE: I could generate ID here and pass this to the client, when // he runs the callback! $options.oneOn(); callback(); }, runWithoutReadInBackground: function (callback) { $options.dbFirstFalseForNextCall(); // in our case this will just change the policy! callback(); }, listener: function (requestID, callback) { // catch the background listener when finished // check first if the dbFirst=true, otherwise no event will be triggered //if ($options.isDbFirst()) { // make sure that the Persistence.Handler exist before using it // xhr.getResponseHeader("Request-ID") - gets the offline id from the header returned from // the library if (typeof $handler !== 'undefined' && requestID) // listen for the event $handler.addListener(requestID, function (e) { //console.log('$handler', e.detail.offlineid, e.detail.status, // e.detail.statusText, e.detail.response); callback(e.detail); }, false); //} }, registerRequestCompletedCallback: function (obj, callback) { //if ($options.isDbFirst()) { // make sure that the Persistence.Handler exist before using it // xhr.getResponseHeader("Request-ID") - gets the offline id from the header returned from // the library if (typeof $handler !== 'undefined' && obj !== null) // if number than go for it directly if ($common.isNumber(obj)) { $handler.addListener(obj, function (e) { callback(e.detail.data, e.detail.status, e.detail.statusText, e.detail.requestid, e.detail.time); }, false); } else if ($common.isObject(obj)) { if (obj.hasOwnProperty(REQUEST_ID)) { $handler.addListener(obj[REQUEST_ID], function (e) { callback(e.detail.data, e.detail.status, e.detail.statusText, e.detail.requestid, e.detail.time); }, false); } else if (typeof obj.getResponseHeader === 'function') { if (obj.getResponseHeader(REQUEST_ID) != null) { //data[REQUEST_ID] = xhr.getResponseHeader(REQUEST_ID); $handler.addListener(obj.getResponseHeader(REQUEST_ID), function (e) { callback(e.detail.data, e.detail.status, e.detail.statusText, e.detail.requestid, e.detail.time); }, false); } } } //} } }; } /** * * The response object has these properties: data – {string|Object} – The response body transformed with the transform functions. status – {number} – HTTP status code of the response. headers – {function([headerName])} – Header getter function. config – {Object} – The configuration object that was used to generate the request. statusText – {string} – HTTP status text of the response. */ /* A response status code between 200 and 299 is considered a success status and will result in the success callback being called. Any response status code outside of that range is considered an error status and will result in the error callback being called. Also, status codes less than -1 are normalized to zero. -1 usually means the request was aborted, e.g. using a config.timeout. Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning that the outcome (success or error) will be determined by the final response status code. */ // TODO: see also responseJSON: https://pixelsvsbytes.com/2011/12/teach-your-xmlhttprequest-some-json/ // Persistence implementation function persistenceXMLHttpRequestInstall(XHR, $sync, $utils, $options, $common, $handler, $events) { "use strict"; // get pointer to the original object! var OriginalXMLHttpRequest = XHR; var httpStatusCodes = { 100: "Continue", 101: "Switching Protocols", 200: "OK", 201: "Created", 202: "Accepted", 203: "Non-Authoritative Information", 204: "No Content", 205: "Reset Content", 206: "Partial Content", 300: "Multiple Choice", 301: "Moved Permanently", 302: "Found", 303: "See Other", 304: "Not Modified", 305: "Use Proxy", 307: "Temporary Redirect", 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 406: "Not Acceptable", 407: "Proxy Authentication Required", 408: "Request Timeout", 409: "Conflict", 410: "Gone", 411: "Length Required", 412: "Precondition Failed", 413: "Request Entity Too Large", 414: "Request-URI Too Long", 415: "Unsupported Media Type", 416: "Requested Range Not Satisfiable", 417: "Expectation Failed", 422: "Unprocessable Entity", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout", 505: "HTTP Version Not Supported" }; var unsafeHeaders = { "Accept-Charset": true, "Accept-Encoding": true, "Connection": true, "Content-Length": true, "Cookie": true, "Cookie2": true, "Content-Transfer-Encoding": true, "Date": true, "Expect": true, "Host": true, "Keep-Alive": true, "Referer": true, "TE": true, "Trailer": true, "Transfer-Encoding": true, "Upgrade": true, "User-Agent": true, "Via": true }; // TODO: http://stackoverflow.com/questions/24555370/how-can-i-catch-and-process-the-data-from-the-xhr-responses-using-casperjs/24561614#24561614 // TODO: MCS: https://docs.oracle.com/cloud/latest/mobilecs_gs/MCSUA/GUID-85B42EE5-82F7-4FA8-A712-DCFCFAF51CA7.htm#MCSUA3501 // XHR Proxy function SyncXMLHttpRequest() { var originalXHR = new OriginalXMLHttpRequest(); var defaultContentTypeHeader = "application/json; charset=utf-8"; // this is equal to FETCH_FROM_CACHE_SCHEDULE_REFRESH this.isDbFirst = $options.isDbFirst(); this._req = { url: '', headers: { "Content-Type": defaultContentTypeHeader }, data: undefined, method: '', username: '', password: '' }; // point yourself! var self = this; Object.defineProperty(self, 'xhr', { get: function () { return originalXHR; } }); this._setResponseHeaders = function (headers) { this.responseHeaders = {}; for (var header in headers) { if (headers.hasOwnProperty(header)) { this.responseHeaders[header] = headers[header]; } } if (this.forceMimeType) { this.responseHeaders['Content-Type'] = this.forceMimeType; } this.readyState = this.HEADERS_RECEIVED; }; // add all proxy getters, don't need to override these // "responseType", "readyState", "responseXML", ["upload"].forEach(function (item) { Object.defineProperty(self, item, { get: function () { return this.xhr[item]; } }); }); // add all pure proxy pass-through methods // "open", "addEventListener", "overrideMimeType", "getAllResponseHeaders" ["abort"].forEach(function (item) { Object.defineProperty(self, item, { value: function () { return this.xhr[item].apply(this.xhr, arguments); } }); }); // add all proxy getters/setters // "onload", ["ontimeout, timeout", "withCredentials", "onprogress"].forEach(function (item) { Object.defineProperty(self, item, { get: function () { return this.xhr[item]; }, set: function (val) { this.xhr[item] = val; } }); }); // proxy change event handler // http://stackoverflow.com/questions/24555370/how-can-i-catch-and-process-the-data-from-the-xhr-responses-using-casperjs/24561614#24561614 var restproperties = [ //"onabort", //"onerror", //"onload", "onloadstart", "onloadend", //"onprogress", //"readyState", //"responseText", //"responseType", //"responseXML", //"status", //"statusText", //"upload", //"withCredentials", "DONE", "UNSENT", "HEADERS_RECEIVED", "LOADING", "OPENED" ]; restproperties.forEach(function (item) { Object.defineProperty(self, item, { get: function () { return this.xhr[item]; }, set: function (obj) { this.xhr[item] = obj; } }); }); // uniqueID will be used from the event handler this.uniqueID = function () { if (!this.uniqueIDMemo) { // use the UUID v4 - which preferred! if (uuid) { this.uniqueIDMemo = uuid.v4(); } else { this.uniqueIDMemo = $common.getUID() } } return this.uniqueIDMemo; }; // NOTICE: L.Pelov - bellow code could be part of the SyncXHR class to hide internal methods! this.open = function (method, url, async, user, password) { console.log(url); // now check here if you want to continue with the proxy or if you defake! this.persistentPath = $options.isPersistentUrl(url); //console.debug('isPersistentUrl', this.persistentPath); if (this.persistentPath === false) { // defake and continue with the original object console.debug('defake XHR'); // non of the proxy methods will be used! this.defake(); return this.xhr.open(method, url, true, user, password); //send it on } else { // use the proxy console.debug('PROXY'); this.proxyXHR(); this._req.method = method; this._req.url = url; this._req.username = user; this._req.password = password; //return this.xhr.open(method, url, true, user, password); //send it on return this.xhr.open.apply(this.xhr, arguments); } }; return this; } /** * proxy following methods! */ SyncXMLHttpRequest.prototype.proxyXHR = function () { var self = this; Object.defineProperty(self, 'onerror', { get: function () { // this will probably never called return this.xhr.onerror; }, set: function (onerror) { var that = this.xhr; var realThis = this; self.originalonerror = onerror; that.onerror = function () { // intercept the call and set the vars self.synconerror(); onerror.call(realThis); } } }); Object.defineProperty(self, 'onload', { get: function () { return this.xhr.onload; }, set: function (onload) { var that = this.xhr; var realThis = this; self.originalonload = onload; that.onload = function () { // intercept the call and set the vars self.onreadystatechangefunction(); onload.call(realThis); } } }); Object.defineProperty(self, "onreadystatechange", { get: function () { return this.xhr.onreadystatechange; }, set: function (onreadystatechange) { var that = this.xhr; var realThis = this; self.originalonreadystate = onreadystatechange; that.onreadystatechange = function () { // request is fully loaded if (that.readyState == 4) { self.onreadystatechangefunction(); } else { // this is not interesting so use the defaults! realThis.readyState = that.readyState; realThis.response = that.response; realThis.responseText = that.responseText; realThis.responseXML = that.responseXML; realThis.status = that.status; realThis.statusText = that.statusText; realThis.responseType = that.responseType; } onreadystatechange.call(realThis); }; } }); SyncXMLHttpRequest.prototype.overrideMimeType = function (mimeType) { if (!this._req.headers) { this._req.headers = {}; } if (typeof mimeType === "string") { this.forceMimeType = mimeType.toLowerCase(); this._req.headers['Content-Type'] = this.forceMimeType; } this.xhr.overrideMimeType(mimeType); }; /** * Some developers prefer to use the event listener! * * @param event * @param callback * @returns {*} */ SyncXMLHttpRequest.prototype.addEventListener = function (event, callback) { var self = this; if (event === 'load') { self.onload = callback; // NOTICE: no need to pass this to the XHR event lister, as the proxy will do this // however we want to catch the callback to be able to exec it when required } else if (event === 'error') { self.onerror = callback; // NOTICE: no need to pass this to the XHR event lister, as the proxy will do this // however we want to catch the callback to be able to exec it when required } else { // not interested for now pass over!:) this.xhr.addEventListener(event, callback); } }; /** * Get the headers to properly intercept! * NOTICE: There is no need to check for unsafe headers, as the original XHR object will throw exceptions * if this is the case * * @param header * @param value * @returns {*} */ SyncXMLHttpRequest.prototype.setRequestHeader = function (header, value) { //console.log(header + ": " + value); //var self = this; if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) { throw new Error("Refused to set unsafe header \"" + header + "\""); } // NOTICE: this will throw exception for us if user try to pass unsafe header! this.xhr.setRequestHeader(header, value); // BUGFIX: IE - cache issue if (!this._req.headers) { this._req.headers = {}; } this._req.headers[header] = value; }; SyncXMLHttpRequest.prototype.getAllResponseHeaders = function getAllResponseHeaders() { var self = this; if (self.readyState < self.HEADERS_RECEIVED) { return ""; } var headers = ""; for (var header in this.responseHeaders) { if (this.responseHeaders.hasOwnProperty(header) && !/^Set-Cookie2?$/i.test(header)) { headers += header + ": " + this.responseHeaders[header] + "\r\n"; } } return headers; }; SyncXMLHttpRequest.prototype.getResponseHeader = function getResponseHeader(header) { var self = this; if (self.readyState < self.HEADERS_RECEIVED) { return null; } if (/^Set-Cookie2?$/i.test(header)) { return null; } header = header.toLowerCase(); for (var h in this.responseHeaders) { if (h.toLowerCase() == header) { return this.responseHeaders[h]; } } return null; }; /** * This interceptor will decide which way we want to go depending on user configurations! * @param postBody */ SyncXMLHttpRequest.prototype.send = function (postBody) { var self = this; if(self.responseType){ this._req.responseType = self.responseType; } // we currently only support JSON payloads, if this is not the case throw error try { if (postBody) { if (typeof postBody === 'string') { this._req.data = JSON.parse(postBody); } else { //BUG: to make sure that we work with a copy of the object, as some frameworks like knockout often override the objects! this._req.data = JSON.parse(JSON.stringify(postBody)); } } } catch (e) { throw new Error('persistence library could execute only JSON payload!'); } // well maybe check first if online, if not you don't have to do all that work var isOnline = $options.isOnline(); var whenOffline = function () { setTimeout(function () { console.debug('Sync XHR in OFF-LINE MODE'); handleOfflineRequest(self._req, true); }, 1); }; var whenOnline = function () { setTimeout(function () { console.debug('Sync XHR in ON-LINE MODE'); if (isPolicy('fetchPolicy', 'FETCH_FROM_CACHE_SCHEDULE_REFRESH') || self.isDbFirst) { // Instructs to fetch resources from the local cache and schedule a background refresh to update the cache with the latest version from the server. handleOfflineRequest(self._req, false); } // should not exec GET operation on object that was no synced! isObjectNeverSynced() && exeXHR(); }, 1) }; !isOnline ? whenOffline() : whenOnline(); var defaultContentHeaders = { "Content-Type": 'application/json; charset=utf-8', "Request-ID": self.uniqueID() }; var isPolicy = function (policy, value) { return self.persistentPath.isPolicy(policy, value); }; // how to respond to the client! var $respond = function (status, headers, body) { if (isPolicy('fetchPolicy', 'FETCH_FROM_CACHE_SCHEDULE_REFRESH') || self.isDbFirst) { $handler.dispatchEvent(status, httpStatusCodes[status], body, self.uniqueID()); } else { self.respond2(status, headers, body); } }; // what to do when offline! var handleOfflineRequest = function (req, toSync) { var parsingModule = $options.Module; // TODO: Yuri - check if this is the right place for this functionality // remove data from get offline request. if (req.method === 'GET') { delete req.data; } if (isPolicy('noCache', false) && $utils.isSupportedHTTPMethod(parsingModule, req.method)) { return parsingModule.router(req) .then(function (response) { if (req.hasOwnProperty('method')) { if (req.method !== 'GET') { // in case of error get the stored data and push to the sync! if (toSync === true) { self._req.data = response; $sync.router(self._req); } } } return response; }) .then(function (response) { if(!$common.isEmpty(response)) { self.respond2(200, defaultContentHeaders, response); } else { self.respond2(404, defaultContentHeaders, 'Offline Not Found'); } }) .catch(function (err) { console.error(err); self.respond2(400, defaultContentHeaders, err); }); } else { if (req.hasOwnProperty('method') && $utils.isSupportedHTTPMethod($sync, req.method)) { if (req.method !== 'GET') { // in case of error get the stored data and push to the sync! if (toSync === true) { self._req.data = req.data; $sync.router(req).then(function (result) { self.respond2(200, defaultContentHeaders, null); }).catch(function (error) { self.respond2(400, defaultContentHeaders, null); }); } else { self.respond2(0, defaultContentHeaders, null); } } else { // status 0 means no network! self.respond2(0, defaultContentHeaders, null); } } else { self.respond2(400, defaultContentHeaders, null); } } }; // checks if the object you try to send was ever synced! function isObjectNeverSynced() { if (!$common.isEmpty(postBody) && $common.isObject(postBody)) { if (postBody.hasOwnProperty('meta') && postBody.meta.hasOwnProperty('offline-persist')) { // don't need to proceed with the query since this object was not sync, // it exist only in the offline db! if (this._req.method === 'GET') return false; } else { // clean the object from internal properties if any! if (postBody.hasOwnProperty('$loki')) { delete postBody['$loki']; } if (postBody.hasOwnProperty('meta')) { delete postBody['meta']; } } } return true; } // exec the async call function exeXHR() { // generate unique sync ID to notify once there is response! var syncRequestID = self.uniqueID() + '-SYNC-' + Math.floor(Math.random() * 1000); self._req.SYNCID = syncRequestID; // store in the sync log first, and then execute $sync.router(self._req) .then(function () { // callback when the ajax call is ready,it should return the response to client after the policy sync operations $handler.addListener(syncRequestID, function (e) { // TODO: standardize response! // console.debug('request response', e); // status - e.detail.data.status // headers - e.detail.data.getAllResponseHeaders() // body - e.detail.data.responseText // console.log(typeof e.detail.data); reqListener(e.detail.data); }, false); // run the sync! $sync.operations.run(true); }) .catch(function (error) { console.error(error); $respond(400, defaultContentHeaders, error); }); } // what to do onload! /** * @deprecated - this should be moved the sync library! * @param event */ function reqListener(xhr) { var parsingModule = $options.Module; // get the response - and add it to the response message data! var xhrResponse = ('response' in xhr) ? xhr.response : xhr.responseText; // NOTE: this should be always 4 because we register onload event, and NOT using onreadystatechange! if (xhr.readyState === 4) { if ($common.isEmpty(xhrResponse)) { xhrResponse = "" } // Assigned the Request ID to the response headers to be returned to the client! var responseHeaders = $utils.parseResponseHeaders(xhr.getAllResponseHeaders()); responseHeaders['Request-ID'] = self.uniqueID(); // work only if following // 304 - means not changes so use the one from cache right! // get the latest data from the offline db on : status === 304 if (xhr.status >= 200 && xhr.status < 300) { $events.$emit('success', { data: xhrResponse, status: xhr.status, headers: xhr.getAllResponseHeaders(), requestID: self.uniqueID() }); // we can work only with JSON payloads! var contentTypeResponseHeader = xhr.getResponseHeader("Content-Type"); // OK this is a issues, we have a null content type, we cannot work with it, return error to the client! if (contentTypeResponseHeader === null) { if (self._req.method !== 'DELETE') { throw new Error('XHR did not return any HTTP headers!'); } } else { // get the response header text to compare! contentTypeResponseHeader = contentTypeResponseHeader && contentTypeResponseHeader.split(';', 1)[0]; // content-type should be JSON if ((contentTypeResponseHeader == null) || (contentTypeResponseHeader !== 'application/json')) { if (self._req.method !== 'DELETE') { throw new Error('persistence library could handle only JSON responses!'); } } else if(typeof xhrResponse === 'String'){ xhrResponse = JSON.parse(xhrResponse); } } // take the new headers! self._req.headers = responseHeaders; // NOTE: alright if I am here than everything is good and I can start working with the requests // check first that the method is implemented! if (isPolicy('noCache', false) && $utils.isSupportedHTTPMethod(parsingModule, self._req.method)) { self._req.data = xhrResponse; if (self._req.method === 'POST' || self._req.method === 'PUT' || self._req.method === 'PATCH') { if (self._req.data.meta !== undefined && self._req.data.meta.hasOwnProperty('offline-persist')) { delete self._req.data.meta['offline-persist']; } } // store the response in the offline db automatically parsingModule.router(self._req) .then(function () { $respond(xhr.status, responseHeaders, xhrResponse); }) .catch(function (err) { console.error(err); $respond(400, responseHeaders, err); }); } else { // well maybe we don't want to start the response! $respond(xhr.status, responseHeaders, xhrResponse); } } // something very bad happen here! else { //if status higher then 300, then we have a issue return this back to the client if ((xhr.status >= 300 && xhr.status != 304)) { $events.$emit('error', { event: event }); self._req.headers = responseHeaders; // if DB first and we were able to return something to the client, then do so // however if nothing, then return the error message and information if (isPolicy('noCache', false) && $utils.isSupportedHTTPMethod(parsingModule, self._req.method)) { if (self._req.method === 'GET') { // there is error we don't need the message from the server here, // we just want to return the offline db self._req.data = []; } parsingModule.router(self._req).then(function (result) { // If there is something to return !result ? $respond(xhr.status, responseHeaders, xhrResponse) : $respond(xhr.status, responseHeaders, result); }).catch(function (error) { $respond(400, responseHeaders, 'Error while executing operation against the offline database: ' + error, xhrResponse); }); } else { $respond(xhr.status, responseHeaders, xhrResponse); } } else { $respond(xhr.status, responseHeaders, xhrResponse); } } } //readyState something else than 4 - DONE, which is very unlikely but hey! else { // if readyState not 4 - you don't have access to the headers! $respond(xhr.status, defaultContentHeaders, xhrResponse); } } // this is if you don't want to use the sync to do the XHR call! // this.xhr.send(postBody); // example for immediate response // self.respond2(200, { // "Content-Type": "application/json; charset=utf-8", // "Content-Language": "neee" // }, '[{"name":"pelov - 1"}]'); }; // SEND END /** * Intercept on XHR error! */ SyncXMLHttpRequest.prototype.synconerror = function () { var self = this; self.readyState = this.xhr.readyState; //self.responseText = ('response' in this.xhr) ? this.xhr.response : this.xhr.responseText; self.responseText = this.xhr.responseText; self.responseType = this.xhr.responseType; self.response = this.xhr.response; self.responseXML = this.xhr.responseXML; self.status = this.xhr.status; self.statusText = this.xhr.statusText; }; /** * Manually set the response to the user. * * @param status - valid HTTP status code * @param headers - response headers * @param body - response body */ SyncXMLHttpRequest.prototype.respond2 = function (status, headers, body) { var self = this; self._setResponseHeaders(headers); self.readyState = self.DONE; self.status = status; self.statusText = httpStatusCodes[status]; // set the response which should be JSON if (body != null) { if (typeof body === 'string') { self.responseText = body; //self.response = self.responseText; } else if (typeof body === 'object') { if(self.responseType && self.responseType == 'json'){ self.response = body; } else { self.responseText = JSON.stringify(body); } } else { // don't recognise the body! self.responseText = null; self.response = self.responseText; } } else { self.responseText = null; self.response = self.responseText; } if (status != 0) { if (self.originalonload) { self.originalonload.call(this); } else if (self.originalonreadystate) { self.originalonreadystate.call(this); } else { throw new Error('no response XHR method was implemented!'); } } // TODO: Error should be only if the XHR thrown error! else { if (self.originalonerror) { self.originalonerror.call(this); } else if (self.originalonload) { self.originalonload.call(this); } else if (self.originalonreadystate) { self.originalonreadystate.call(this); } else { throw new Error('no response XHR method was implemented!'); } } //} }; /** * Prototype from the real object to easy catch the internal variables! * * @param e * @returns {*} */ SyncXMLHttpRequest.prototype.onreadystatechangefunction = function () { var self = this; var responseHeaders = $utils.parseResponseHeaders(this.xhr.getAllResponseHeaders()); self._setResponseHeaders(responseHeaders); self.readyState = self.DONE; self.status = this.xhr.status; self.statusText = this.xhr.statusText; //this.responseText = ('response' in this.xhr) ? this.xhr.response : this.xhr.responseText; this.responseText = this.xhr.responseText; this.response = this.xhr.response; this.responseXML = this.xhr.responseXML; //if (this.xhr.status >= 200 && this.xhr.status < 400) { // success! //} //else { // do something on error //} // END HERE!! return; }; }// END OF PROXY /** * Convert to the original XHR object! * * https://github.com/sinonjs/sinon/blob/master/lib/sinon/util/fake_xml_http_request.js * https://github.com/sinonjs/sinon/blob/master/lib/sinon/util/event.js * * @returns {SyncXMLHttpRequest} */ SyncXMLHttpRequest.prototype.defake = function () { // go throw the objects from the original XHR and pass them to the proxy! // ["open", "addEventListener", "overrideMimeType"].forEach(function (item) { // Object.defineProperty(self, item, { // value: function () { // return this.xhr[item].apply(this.xhr, arguments); // } // }); // }); var self = this; // Object.defineProperty(self, 'onerror', { // get: function () { // // this will probably never called // return this.xhr.onerror; // }, // set: function (onerror) { // var that = this.xhr; // that.onerror = function () { // onerror.call(that); // }; // } // }); // // Object.defineProperty(self, 'onload', { // get: function () { // return this.xhr.onload; // }, // set: function (onload) { // var that = this.xhr; // that.onload = function () { // onload.call(that); // }; // } // }); Object.defineProperty(self, "onreadystatechange", { get: function () { return this.xhr.onreadystatechange; }, set: function (onreadystatechange) { var that = this.xhr; that.onreadystatechange = function () { onreadystatechange.call(that); }; } }); // proxy ALL methods/properties var methods = [ //"abort", "setRequestHeader", "send", "addEventListener", "removeEventListener", "getResponseHeader", "getAllResponseHeaders", "dispatchEvent", "overrideMimeType" ]; methods.forEach(function (method) { Object.defineProperty(self, method, { value: function () { return this.xhr[method].apply(this.xhr, arguments); } }); }); var properties = [ "onabort", "onerror", "onload", "readyState", "responseText", "response", "responseType", "responseXML", "status", "statusText" ]; properties.forEach(function (item) { Object.defineProperty(self, item, { get: function () { return this.xhr[item]; }, set: function (obj) { this.xhr[item] = obj; } }); }); return this; }; /** * Here decision will be take if to intercept or not:), depending or initialisation settings! * * @param intercept * @returns {SyncXMLHttpRequest} * @constructor */ XMLHttpRequest = function (intercept) { // this means you definitely want to use the interceptor! if (typeof intercept === 'boolean') { if (intercept === true) { return new SyncXMLHttpRequest(); } if (intercept === false) { return new XHR(); } } // in that case if (!$options.isOn() || $options.off) { // in that case work with the original object! return new XHR(); } // OK non of the above we want to intercept! return new SyncXMLHttpRequest(); }; XMLHttpRequest.originalXMLHttpRequest = OriginalXMLHttpRequest; } function persistenceXMLHttpRequestUninstall(){ if(!XMLHttpRequest.originalXMLHttpRequest) { throw 'Sync Express not installed.'; } XMLHttpRequest = XMLHttpRequest.originalXMLHttpRequest; } "use strict"; // persistence library initialization function persistenceLibraryInitialization() { var _common = persistenceCommon(); var _handler = persistenceHandler(); var _events = persistenceEvents(); var _options = persistenceOptions(_common); var _utils = persistenceUtils(_common, _options); var _sync = persistenceSync(_events, _common, _options, _utils, _handler); _options.module = new persistenceMCSHandler(_options, _common, _utils); var _process = persistenceProcess(_options, _common, _handler); // syncXMLHttpRequest request initialization persistenceXMLHttpRequestInstall(XMLHttpRequest, _sync, _utils, _options, _common, _handler, _events); function flush(path) { return _options.module.flush(path) .then(_sync.flush.bind(_sync)); } function install() { persistenceXMLHttpRequestInstall(XMLHttpRequest, _sync, _utils, _options, _common, _handler, _events); } function uninstall() { persistenceXMLHttpRequestUninstall(); } /** * Persistence module. * @memberOf mcs.sync * @namespace sync * @ignore */ var sync = {}; /** * Module contains all public settings for the persistence library * @ignore */ sync.options = _options; /** * This module provide the MCS Persistent capabilities * @ignore */ sync.MCSHandler = function () { return new persistenceMCSHandler(_options, _common, _utils); }; /** * Request handler can be used directly, and is used to intercept the HTTP request to store objects offline. * @ignore */ sync.RequestHandler = function () { return new persistenceRequestHandler(_options, _common, _utils); }; /** * Oracle REST handler is used to intercept the HTTP request to store objects offline. * @ignore */ sync.OracleRestHandler = function () { return new persistenceOracleRESTHandler(_options, _common, _utils); }; /** * Intercepts the XMLHTTPRequest * @ignore */ sync.process = _process; sync._flush = flush; sync._install = install; sync._uninstall = uninstall; return sync; } g.mcs = {}; g.mcs._sync = persistenceLibraryInitialization(); // return RequireJS and AMD if(_define) { define = _define; _define = undefined; } else if(_exports) { exports = _exports; _exports = undefined; } }(this));
/** * Pipedrive API v1 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. * */ import ApiClient from '../ApiClient'; import DealSummaryPerStagesSTAGEIDCURRENCYID from './DealSummaryPerStagesSTAGEIDCURRENCYID'; /** * The DealSummaryPerStagesSTAGEID model module. * @module model/DealSummaryPerStagesSTAGEID * @version 1.0.0 */ class DealSummaryPerStagesSTAGEID { /** * Constructs a new <code>DealSummaryPerStagesSTAGEID</code>. * The currency summaries per stage. This parameter is dynamic and changes according to &#x60;stage_id&#x60; value. * @alias module:model/DealSummaryPerStagesSTAGEID */ constructor() { DealSummaryPerStagesSTAGEID.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>DealSummaryPerStagesSTAGEID</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/DealSummaryPerStagesSTAGEID} obj Optional instance to populate. * @return {module:model/DealSummaryPerStagesSTAGEID} The populated <code>DealSummaryPerStagesSTAGEID</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new DealSummaryPerStagesSTAGEID(); if (data.hasOwnProperty('CURRENCY_ID')) { obj['CURRENCY_ID'] = DealSummaryPerStagesSTAGEIDCURRENCYID.constructFromObject(data['CURRENCY_ID']); delete data['CURRENCY_ID']; } if (Object.keys(data).length > 0) { Object.assign(obj, data); } } return obj; } } /** * @member {module:model/DealSummaryPerStagesSTAGEIDCURRENCYID} CURRENCY_ID */ DealSummaryPerStagesSTAGEID.prototype['CURRENCY_ID'] = undefined; export default DealSummaryPerStagesSTAGEID;
var models = require('../models'); var Account = models.Account; var loginPage = function(req, res) { res.render('loggedOut', {csrfToken: req.csrfToken()}); }; var mainPage = function(req, res) { res.render('mainPage', {csrfToken: req.csrfToken()}); }; var logout = function(req, res){ req.session.destroy(); res.redirect('/login'); }; var login = function(req, res){ if(!req.body.username || !req.body.password) { return res.status(400).json({error: "Please enter both username and password"}); } Account.AccountModel.authenticate(req.body.username, req.body.password, function(err,account){ if(err || !account){ return res.status(401).json({error: "Username or Password is wrong!"}); } req.session.account = account.toAPI(); res.json({redirect: '/'}); }); }; var signup = function(req, res){ if(!req.body.username || !req.body.password1 || !req.body.password2) { return res.status(400).json({error: "Please input all needed information"}); } if(req.body.password1 !== req.body.password2) { return res.status(400).json({error: "Passwords do not match"}); } Account.AccountModel.generateHash(req.body.password1, function(salt, hash) { var accountData = { username: req.body.username, salt: salt, password: hash }; var newAccount = new Account.AccountModel(accountData); newAccount.save(function(err){ if(err){ console.log(err); return res.status(400).json({error: 'An error occured'}); } req.session.account = newAccount.toAPI(); res.json({redirect: '/'}); }); }); }; module.exports.loginPage = loginPage; module.exports.mainPage = mainPage; module.exports.login = login; module.exports.logout = logout; module.exports.signup = signup;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.toPairs = exports.spreadKeys = exports.or = exports.omitByUndefined = exports.mapValues = exports.isPlainObject = exports.get = exports.flow = exports.castArray = undefined; var _lodash = require('lodash.get'); var _lodash2 = _interopRequireDefault(_lodash); var _lodash3 = require('lodash.isplainobject'); var _lodash4 = _interopRequireDefault(_lodash3); var _lodash5 = require('lodash.mapvalues'); var _lodash6 = _interopRequireDefault(_lodash5); var _lodash7 = require('lodash.omitby'); var _lodash8 = _interopRequireDefault(_lodash7); var _lodash9 = require('lodash.set'); var _lodash10 = _interopRequireDefault(_lodash9); var _lodash11 = require('lodash.topairs'); var _lodash12 = _interopRequireDefault(_lodash11); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // exports var castArray = function castArray(value) { return Array.isArray(value) ? value : [value]; }; var flow = function flow() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } return function (initialSource) { for (var _len2 = arguments.length, additional = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { additional[_key2 - 1] = arguments[_key2]; } return funcs.reduce(function (source, func) { return func.apply(undefined, [source].concat(additional)); }, initialSource); }; }; var omitByUndefined = function omitByUndefined(source) { return (0, _lodash8.default)(source, function (value) { return typeof value === 'undefined'; }); }; var or = function or(defaultValue) { return function (value) { return value ? value : defaultValue; }; }; var spreadKeys = function spreadKeys(source) { return Object.keys(source).reduce(function (result, key) { (0, _lodash10.default)(result, key, source[key]); return result; }, {}); }; exports.castArray = castArray; exports.flow = flow; exports.get = _lodash2.default; exports.isPlainObject = _lodash4.default; exports.mapValues = _lodash6.default; exports.omitByUndefined = omitByUndefined; exports.or = or; exports.spreadKeys = spreadKeys; exports.toPairs = _lodash12.default;
'use strict'; angular.module('myApp.home', ['ngRoute','firebase']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/home', { templateUrl: 'home/home.html', controller: 'HomeCtrl' }); }]) .controller('HomeCtrl', ['$scope','$location','CommonProp','$firebaseAuth',function($scope,$location,CommonProp,$firebaseAuth) { var firebaseObj = new Firebase("https://yyear.firebaseio.com"); var loginObj = $firebaseAuth(firebaseObj); $scope.user = {}; $scope.SignIn = function(e) { e.preventDefault(); var username = $scope.user.email; var password = $scope.user.password; loginObj.$authWithPassword({ email: username, password: password }) .then(function(user) { //Success callback console.log('Authentication successful'); CommonProp.setUser(user.password.email); $location.path('/welcome'); }, function(error) { //Failure callback console.log('Authentication failure'); }); } }]) .service('CommonProp', function() { var user = ''; return { getUser: function() { return user; }, setUser: function(value) { user = value; } }; });
'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.devperf = { setUp: function(done) { // setup here if necessary done(); }, default_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/default_options'); var expected = grunt.file.read('test/expected/default_options'); test.equal(actual, expected, 'should describe what the default behavior is.'); test.done(); }, custom_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/custom_options'); var expected = grunt.file.read('test/expected/custom_options'); test.equal(actual, expected, 'should describe what the custom option(s) behavior is.'); test.done(); }, };
DeleteCommand = new Class({ Implements: ICommand, targetIndex: null, initialize: function(){}, setTargetIndex: function(val) { this.targetIndex = val; }, // Remove the target from the canvas execute: function() { this.canvas.removeChildAt(this.targetIndex); }, // Place target back in the display list revert: function(target) { this.canvas.addChildAt(this.target, this.targetIndex); }, toString: function() { return '{name: Delete, target: ' + this.target.toString() + '}'; } });
'use strict'; module.exports = function(express) { const router = express.Router(); const async = require('async'); const db = require('../server/db.js'); let users = require('../models/users.js'); let intolerances = require('../models/intolerances.js'); router.route('/') .put((req, res) => { let data = req.body; async.waterfall([ (callback) => { users.find(data, (err) => { res.status(500).json({ error: err }); }, (foundUser) => { callback(null, foundUser); }); }, (foundUser, callback) => { intolerances.create(data, (err) => { res.status(500).json({ error: err }); }, (createdIntolerance) => { callback(null, createdIntolerance); }); } ], (err, createdIntolerance) => { if(err) { res.status(500).json({ error: err }); } res.status(200).json({ createdIntolerance }); }); }) .delete((req, res) => { let data = req.body; async.waterfall([ (callback) => { intolerances.destroy(data, (err) => { res.status(500).json({ error: err }); }, (deletedIntolerance) => { callback(null, deletedIntolerance); }); } ], (err, deletedIntolerance) => { if(err) { res.status(500).json({ error: err }); } res.status(200).json({ deletedIntolerance }); }); }); router.route('/:userId') .get((req, res) => { let userId = req.params.userId; async.waterfall([ (callback) => { intolerances.findAll( (err) => { res.status(500).json({ error: err }); }, (allIntolerances) => { let userIntolerances = []; for(let i = 0; i < allIntolerances.length; i++) { if(allIntolerances[i].userId === userId) { userIntolerances.push(allIntolerances[i]); } } callback(null, userIntolerances); }); } ], (err, userIntolerances) => { if(err) { res.status(500).json({ error: err }); } res.status(200).json({ userIntolerances }); }); }); return router; };
/* ----------------------------------------------- /* How to use? : Check the GitHub README /* ----------------------------------------------- */ /* To load a config file (particles.json) you need to host this demo (MAMP/WAMP/local)... */ /* particlesJS.load('particles-js', 'particles.json', function() { console.log('particles.js loaded - callback'); }); */ /* Otherwise just put the config content (json): */ particlesJS('particles-js', { "particles": { "number": { "value": 80, "density": { "enable": true, "value_area": 800 } }, "color": { "value": "#ffffff" }, "shape": { "type": "circle", "stroke": { "width": 0, "color": "#000000" }, "polygon": { "nb_sides": 5 }, "image": { "src": "img/github.svg", "width": 100, "height": 100 } }, "opacity": { "value": 0.5, "random": false, "anim": { "enable": false, "speed": 1, "opacity_min": 0.1, "sync": false } }, "size": { "value": 5, "random": true, "anim": { "enable": false, "speed": 40, "size_min": 0.1, "sync": false } }, "line_linked": { "enable": true, "distance": 150, "color": "#ffffff", "opacity": 0.4, "width": 1 }, "move": { "enable": true, "speed": 6, "direction": "none", "random": false, "straight": false, "out_mode": "out", "attract": { "enable": false, "rotateX": 600, "rotateY": 1200 } } }, "interactivity": { "detect_on": "canvas", "events": { "onhover": { "enable": true, "mode": "repulse" }, "onclick": { "enable": true, "mode": "push" }, "resize": true }, "modes": { "grab": { "distance": 400, "line_linked": { "opacity": 1 } }, "bubble": { "distance": 400, "size": 40, "duration": 2, "opacity": 8, "speed": 3 }, "repulse": { "distance": 200 }, "push": { "particles_nb": 4 }, "remove": { "particles_nb": 2 } } }, "retina_detect": true, "config_demo": { "hide_card": false, "background_color": "#b61924", "background_image": "", "background_position": "50% 50%", "background_repeat": "no-repeat", "background_size": "cover" } } );
import MinifyPlugin from 'babel-minify-webpack-plugin' export default (env, argv) => { const PROD = !!(argv.mode && argv.mode === 'production') if (PROD) { process.env.NODE_ENV = 'production' } return { entry: './src/js/App.js', output: { path: PROD ? `${__dirname}/dist` : `${__dirname}/src/assets`, filename: 'bundle.js', publicPath: '/' }, devtool: PROD ? '' : 'source-map', module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' } } ] }, plugins: PROD ? [ new MinifyPlugin({ replace: { 'replacements': [ { 'identifierName': 'DEBUG', 'replacement': { 'type': 'numericLiteral', 'value': 0 } } ] } }, {}) ] : [ // development ] } }
// Relation // --------------- 'use strict'; const _ = require('lodash'); const inflection = require('inflection'); const Helpers = require('./helpers'); const ModelBase = require('./base/model'); const RelationBase = require('./base/relation'); const Promise = require('./base/promise'); const constants = require('./constants'); const push = Array.prototype.push; const removePivotPrefix = (key) => key.slice(constants.PIVOT_PREFIX.length); const hasPivotPrefix = (key) => _.startsWith(key, constants.PIVOT_PREFIX); const Relation = RelationBase.extend({ // Assembles the new model or collection we're creating an instance of, // gathering any relevant primitives from the parent object, // without keeping any hard references. init(parent) { this.parentId = parent.id; this.parentTableName = _.result(parent, 'tableName'); this.parentIdAttribute = this.attribute('parentIdAttribute', parent); // Use formatted attributes so that morphKey and foreignKey will match // attribute keys. this.parentAttributes = parent.format(_.clone(parent.attributes)); if (this.type === 'morphTo' && !parent._isEager) { // If the parent object is eager loading, and it's a polymorphic `morphTo` relation, // we can't know what the target will be until the models are sorted and matched. this.target = Helpers.morphCandidate(this.candidates, this.parentAttributes[this.key('morphKey')]); this.targetTableName = _.result(this.target.prototype, 'tableName'); } this.targetIdAttribute = this.attribute('targetIdAttribute', parent); this.parentFk = this.attribute('parentFk'); const target = this.target ? this.relatedInstance() : {}; target.relatedData = this; if (this.type === 'belongsToMany') { _.extend(target, pivotHelpers); } return target; }, // Initializes a `through` relation, setting the `Target` model and `options`, // which includes any additional keys for the relation. through(source, Target, options) { const type = this.type; if (type !== 'hasOne' && type !== 'hasMany' && type !== 'belongsToMany' && type !== 'belongsTo') { throw new Error('`through` is only chainable from `hasOne`, `belongsTo`, `hasMany`, or `belongsToMany`'); } this.throughTarget = Target; this.throughTableName = _.result(Target.prototype, 'tableName'); _.extend(this, options); _.extend(source, pivotHelpers); this.parentIdAttribute = this.attribute('parentIdAttribute'); this.targetIdAttribute = this.attribute('targetIdAttribute'); this.throughIdAttribute = this.attribute('throughIdAttribute', Target); this.parentFk = this.attribute('parentFk'); // Set the appropriate foreign key if we're doing a belongsToMany, for convenience. if (this.type === 'belongsToMany') { this.foreignKey = this.throughForeignKey; } else if (this.otherKey) { this.foreignKey = this.otherKey; } return source; }, // Generates and returns a specified key, for convenience... one of // `foreignKey`, `otherKey`, `throughForeignKey`. key(keyName) { if (this[keyName]) return this[keyName]; switch (keyName) { case 'otherKey': this[keyName] = singularMemo(this.targetTableName) + '_' + this.targetIdAttribute; break; case 'throughForeignKey': this[keyName] = singularMemo(this.joinTable()) + '_' + this.throughIdAttribute; break; case 'foreignKey': switch (this.type) { case 'morphTo': { const idKeyName = this.columnNames && this.columnNames[1] ? this.columnNames[1] : this.morphName + '_id'; this[keyName] = idKeyName; break; } case 'belongsTo': this[keyName] = singularMemo(this.targetTableName) + '_' + this.targetIdAttribute; break; default: if (this.isMorph()) { this[keyName] = this.columnNames && this.columnNames[1] ? this.columnNames[1] : this.morphName + '_id'; break; } this[keyName] = singularMemo(this.parentTableName) + '_' + this.parentIdAttribute; break; } break; case 'morphKey': this[keyName] = this.columnNames && this.columnNames[0] ? this.columnNames[0] : this.morphName + '_type'; break; case 'morphValue': this[keyName] = this.morphValue || this.parentTableName || this.targetTableName; break; } return this[keyName]; }, // Get the correct value for the following attributes: // parentIdAttribute, targetIdAttribute, throughIdAttribute and parentFk. attribute(attribute, parent) { switch (attribute) { case 'parentIdAttribute': if (this.isThrough()) { if (this.type === 'belongsTo' && this.throughForeignKey) { return this.throughForeignKey; } if (this.type === 'belongsToMany' && this.isThroughForeignKeyTargeted()) { return this.throughForeignKeyTarget; } if (this.isOtherKeyTargeted()) { return this.otherKeyTarget; } // Return attribute calculated on `init` by default. return this.parentIdAttribute; } if (this.type === 'belongsTo' && this.foreignKey) { return this.foreignKey; } if (this.type !== 'belongsTo' && this.isForeignKeyTargeted()) { return this.foreignKeyTarget; } return _.result(parent, 'idAttribute'); case 'targetIdAttribute': if (this.isThrough()) { if ((this.type === 'belongsToMany' || this.type === 'belongsTo') && this.isOtherKeyTargeted()) { return this.otherKeyTarget; } // Return attribute calculated on `init` by default. return this.targetIdAttribute; } if (this.type === 'morphTo' && !parent._isEager) { return _.result(this.target.prototype, 'idAttribute'); } if (this.type === 'belongsTo' && this.isForeignKeyTargeted()) { return this.foreignKeyTarget; } if (this.type === 'belongsToMany' && this.isOtherKeyTargeted()) { return this.otherKeyTarget; } return this.targetIdAttribute; case 'throughIdAttribute': if (this.type !== 'belongsToMany' && this.isThroughForeignKeyTargeted()) { return this.throughForeignKeyTarget; } if (this.type === 'belongsToMany' && this.throughForeignKey) { return this.throughForeignKey; } return _.result(parent.prototype, 'idAttribute'); case 'parentFk': if (!this.hasParentAttributes()) { return; } if (this.isThrough()) { if (this.type === 'belongsToMany' && this.isThroughForeignKeyTargeted()) { return this.parentAttributes[this.throughForeignKeyTarget]; } if (this.type === 'belongsTo') { return this.throughForeignKey ? this.parentAttributes[this.parentIdAttribute] : this.parentId; } if (this.isOtherKeyTargeted()) { return this.parentAttributes[this.otherKeyTarget]; } // Return attribute calculated on `init` by default. return this.parentFk; } return this.parentAttributes[this.isInverse() ? this.key('foreignKey') : this.parentIdAttribute]; } }, // Injects the necessary `select` constraints into a `knex` query builder. selectConstraints(knex, options) { const resp = options.parentResponse; // The `belongsToMany` and `through` relations have joins & pivot columns. if (this.isJoined()) this.joinClauses(knex); // Call the function, if one exists, to constrain the eager loaded query. if (options._beforeFn) options._beforeFn.call(knex, knex); // The base select column if (Array.isArray(options.columns)) { knex.columns(options.columns); } const currentColumns = _.find(knex._statements, {grouping: 'columns'}); if (!currentColumns || currentColumns.length === 0) { knex.distinct(this.targetTableName + '.*'); } if (this.isJoined()) this.joinColumns(knex); // If this is a single relation and we're not eager loading, // limit the query to a single item. if (this.isSingle() && !resp) knex.limit(1); // Finally, add (and validate) the where conditions, necessary for constraining the relation. this.whereClauses(knex, resp); }, // Inject & validates necessary `through` constraints for the current model. joinColumns(knex) { const columns = []; const joinTable = this.joinTable(); if (this.isThrough()) columns.push(this.throughIdAttribute); columns.push(this.key('foreignKey')); if (this.type === 'belongsToMany') columns.push(this.key('otherKey')); push.apply(columns, this.pivotColumns); knex.columns( _.map(columns, function(col) { return joinTable + '.' + col + ' as _pivot_' + col; }) ); }, // Generates the join clauses necessary for the current relation. joinClauses(knex) { const joinTable = this.joinTable(); if (this.type === 'belongsTo' || this.type === 'belongsToMany') { const targetKey = this.type === 'belongsTo' ? this.key('foreignKey') : this.key('otherKey'); knex.join(joinTable, joinTable + '.' + targetKey, '=', this.targetTableName + '.' + this.targetIdAttribute); // A `belongsTo` -> `through` is currently the only relation with two joins. if (this.type === 'belongsTo') { knex.join( this.parentTableName, joinTable + '.' + this.throughIdAttribute, '=', this.parentTableName + '.' + this.key('throughForeignKey') ); } } else { knex.join( joinTable, joinTable + '.' + this.throughIdAttribute, '=', this.targetTableName + '.' + this.key('throughForeignKey') ); } }, // Check that there isn't an incorrect foreign key set, vs. the one // passed in when the relation was formed. whereClauses(knex, response) { let key; if (this.isJoined()) { const isBelongsTo = this.type === 'belongsTo'; const targetTable = isBelongsTo ? this.parentTableName : this.joinTable(); const column = isBelongsTo ? this.parentIdAttribute : this.key('foreignKey'); key = `${targetTable}.${column}`; } else { const column = this.isInverse() ? this.targetIdAttribute : this.key('foreignKey'); key = `${this.targetTableName}.${column}`; } const method = response ? 'whereIn' : 'where'; const ids = response ? this.eagerKeys(response) : this.parentFk; knex[method](key, ids); if (this.isMorph()) { const table = this.targetTableName; const key = this.key('morphKey'); const value = this.key('morphValue'); knex.where(`${table}.${key}`, value); } }, // Fetches all `eagerKeys` from the current relation. eagerKeys(response) { const key = this.isInverse() && !this.isThrough() ? this.key('foreignKey') : this.parentIdAttribute; return _.reject( _(response) .map(key) .uniq() .value(), _.isNil ); }, // Generates the appropriate standard join table. joinTable() { if (this.isThrough()) return this.throughTableName; return this.joinTableName || [this.parentTableName, this.targetTableName].sort().join('_'); }, // Creates a new model or collection instance, depending on // the `relatedData` settings and the models passed in. relatedInstance(models, options) { models = models || []; options = options || {}; const Target = this.target; // If it's a single model, check whether there's already a model // we can pick from... otherwise create a new instance. if (this.isSingle()) { if (!(Target.prototype instanceof ModelBase)) { throw new Error(`The ${this.type} related object must be a Bookshelf.Model`); } return models[0] || new Target(); } // Allows us to just use a model, but create a temporary // collection for a "*-many" relation. if (Target.prototype instanceof ModelBase) { return Target.collection(models, { parse: true, merge: options.merge, remove: options.remove }); } return new Target(models, {parse: true}); }, // Groups the related response according to the type of relationship // we're handling, for easy attachment to the parent models. eagerPair(relationName, related, parentModels, options) { // If this is a morphTo, we only want to pair on the morphValue for the current relation. if (this.type === 'morphTo') { parentModels = _.filter(parentModels, (m) => { return m.get(this.key('morphKey')) === this.key('morphValue'); }); } // If this is a `through` or `belongsToMany` relation, we need to cleanup & setup the `interim` model. if (this.isJoined()) related = this.parsePivot(related); // Group all of the related models for easier association with their parent models. const idKey = (key) => (_.isBuffer(key) ? key.toString('hex') : key); const grouped = _.groupBy(related, (m) => { let key; if (m.pivot) { if (this.isInverse() && this.isThrough()) { key = this.isThroughForeignKeyTargeted() ? m.pivot.get(this.throughForeignKeyTarget) : m.pivot.id; } else { key = m.pivot.get(this.key('foreignKey')); } } else if (this.isInverse()) { key = this.isForeignKeyTargeted() ? m.get(this.foreignKeyTarget) : m.id; } else { key = m.get(this.key('foreignKey')); } return idKey(key); }); // Loop over the `parentModels` and attach the grouped sub-models, // keeping the `relatedData` on the new related instance. _.each(parentModels, (model) => { let groupedKey; if (!this.isInverse()) { const parsedKey = Object.keys(model.parse({[this.parentIdAttribute]: null}))[0]; groupedKey = idKey(model.get(parsedKey)); } else { const keyColumn = this.key(this.isThrough() ? 'throughForeignKey' : 'foreignKey'); const formatted = model.format(_.clone(model.attributes)); groupedKey = idKey(formatted[keyColumn]); } if (groupedKey != null) { const relation = (model.relations[relationName] = this.relatedInstance(grouped[groupedKey], options)); if (this.type === 'belongsToMany') { // If type is of "belongsToMany" then the relatedData need to be recreated through the parent model relation.relatedData = model[relationName]().relatedData; } else { relation.relatedData = this; } if (this.isJoined()) _.extend(relation, pivotHelpers); } }); // Now that related models have been successfully paired, update each with // its parsed attributes related.map((model) => { model.attributes = model.parse(model.attributes); model.formatTimestamps()._previousAttributes = _.cloneDeep(model.attributes); model._reset(); }); return related; }, parsePivot(models) { return _.map(models, (model) => { // Separate pivot attributes. const grouped = _.reduce( model.attributes, (acc, value, key) => { if (hasPivotPrefix(key)) { acc.pivot[removePivotPrefix(key)] = value; } else { acc.model[key] = value; } return acc; }, {model: {}, pivot: {}} ); // Assign non-pivot attributes to model. model.attributes = grouped.model; // If there are any pivot attributes, create a new pivot model with these // attributes. if (!_.isEmpty(grouped.pivot)) { const Through = this.throughTarget; const tableName = this.joinTable(); model.pivot = Through != null ? new Through(grouped.pivot) : new this.Model(grouped.pivot, {tableName}); } return model; }); }, // A few predicates to help clarify some of the logic above. isThrough() { return this.throughTarget != null; }, isJoined() { return this.type === 'belongsToMany' || this.isThrough(); }, isMorph() { return this.type === 'morphOne' || this.type === 'morphMany'; }, isSingle() { const type = this.type; return type === 'hasOne' || type === 'belongsTo' || type === 'morphOne' || type === 'morphTo'; }, isInverse() { return this.type === 'belongsTo' || this.type === 'morphTo'; }, isForeignKeyTargeted() { return this.foreignKeyTarget != null; }, isThroughForeignKeyTargeted() { return this.throughForeignKeyTarget != null; }, isOtherKeyTargeted() { return this.otherKeyTarget != null; }, hasParentAttributes() { return this.parentAttributes != null; }, // Sets the `pivotColumns` to be retrieved along with the current model. withPivot(columns) { if (!Array.isArray(columns)) columns = [columns]; this.pivotColumns = this.pivotColumns || []; push.apply(this.pivotColumns, columns); } }); // Simple memoization of the singularize call. const singularMemo = (function() { const cache = Object.create(null); return function(arg) { if (!(arg in cache)) { cache[arg] = inflection.singularize(arg); } return cache[arg]; }; })(); // Specific to many-to-many relationships, these methods are mixed // into the `belongsToMany` relationships when they are created, // providing helpers for attaching and detaching related models. const pivotHelpers = { /** * Attaches one or more `ids` or models from a foreign table to the current * table, on a {@linkplain many-to-many} relation. Creates and saves a new * model and attaches the model with the related model. * * var admin1 = new Admin({username: 'user1', password: 'test'}); * var admin2 = new Admin({username: 'user2', password: 'test'}); * * Promise.all([admin1.save(), admin2.save()]) * .then(function() { * return Promise.all([ * new Site({id: 1}).admins().attach([admin1, admin2]), * new Site({id: 2}).admins().attach(admin2) * ]); * }) * * This method (along with {@link Collection#detach} and {@link * Collection#updatePivot}) are mixed in to a {@link Collection} when * returned by a {@link Model#belongsToMany belongsToMany} relation. * * @method Collection#attach * @param {mixed|mixed[]} ids * One or more ID values or models to be attached to the relation. * @param {Object} options * A hash of options. * @param {Transaction} options.transacting * Optionally run the query in a transaction. * @returns {Promise<Collection>} * A promise resolving to the updated Collection where this method was called. */ attach(ids, options) { return Promise.try(() => this.triggerThen('attaching', this, ids, options)) .then(() => this._handler('insert', ids, options)) .then((response) => this.triggerThen('attached', this, response, options)) .return(this); }, /** * Detach one or more related objects from their pivot tables. If a model or * id is passed, it attempts to remove from the pivot table based on that * foreign key. If no parameters are specified, we assume we will detach all * related associations. * * This method (along with {@link Collection#attach} and {@link * Collection#updatePivot}) are mixed in to a {@link Collection} when returned * by a {@link Model#belongsToMany belongsToMany} relation. * * @method Collection#detach * @param {mixed|mixed[]} [ids] * One or more ID values or models to be detached from the relation. * @param {Object} options * A hash of options. * @param {Transaction} options.transacting * Optionally run the query in a transaction. * @returns {Promise<undefined>} * A promise resolving to the updated Collection where this method was called. */ detach(ids, options) { return Promise.try(() => this.triggerThen('detaching', this, ids, options)) .then(() => this._handler('delete', ids, options)) .then((response) => this.triggerThen('detached', this, response, options)) .return(this); }, /** * The `updatePivot` method is used exclusively on {@link Model#belongsToMany * belongsToMany} relations, and allows for updating pivot rows on the joining * table. * * This method (along with {@link Collection#attach} and {@link * Collection#detach}) are mixed in to a {@link Collection} when returned * by a {@link Model#belongsToMany belongsToMany} relation. * * @method Collection#updatePivot * @param {Object} attributes * Values to be set in the `update` query. * @param {Object} [options] * A hash of options. * @param {function|Object} [options.query] * Constrain the update query. Similar to the `method` argument to {@link * Model#query}. * @param {Boolean} [options.require=false] * Causes promise to be rejected with an Error if no rows were updated. * @param {Transaction} [options.transacting] * Optionally run the query in a transaction. * @returns {Promise<Number>} * A promise resolving to number of rows updated. */ updatePivot: function(attributes, options) { return this._handler('update', attributes, options); }, /** * The `withPivot` method is used exclusively on {@link Model#belongsToMany * belongsToMany} relations, and allows for additional fields to be pulled * from the joining table. * * var Tag = bookshelf.Model.extend({ * comments: function() { * return this.belongsToMany(Comment).withPivot(['created_at', 'order']); * } * }); * * @method Collection#withPivot * @param {string[]} columns * Names of columns to be included when retrieving pivot table rows. * @returns {Collection} * Self, this method is chainable. */ withPivot: function(columns) { this.relatedData.withPivot(columns); return this; }, // Helper for handling either the `attach` or `detach` call on // the `belongsToMany` or `hasOne` / `hasMany` :through relationship. _handler: Promise.method(function(method, ids, options) { const pending = []; if (ids == null) { if (method === 'insert') return Promise.resolve(this); if (method === 'delete') pending.push(this._processPivot(method, null, options)); } if (!Array.isArray(ids)) ids = ids ? [ids] : []; _.each(ids, (id) => pending.push(this._processPivot(method, id, options))); return Promise.all(pending).return(this); }), // Handles preparing the appropriate constraints and then delegates // the database interaction to _processPlainPivot for non-.through() // pivot definitions, or _processModelPivot for .through() models. // Returns a promise. _processPivot: Promise.method(function(method, item) { const relatedData = this.relatedData, args = Array.prototype.slice.call(arguments), fks = {}, data = {}; fks[relatedData.key('foreignKey')] = relatedData.parentFk; // If the item is an object, it's either a model // that we're looking to attach to this model, or // a hash of attributes to set in the relation. if (_.isObject(item)) { if (item instanceof ModelBase) { fks[relatedData.key('otherKey')] = item.id; } else if (method !== 'update') { _.extend(data, item); } } else if (item) { fks[relatedData.key('otherKey')] = item; } args.push(_.extend(data, fks), fks); if (this.relatedData.throughTarget) { return this._processModelPivot.apply(this, args); } return this._processPlainPivot.apply(this, args); }), // Applies constraints to the knex builder and handles shelling out // to either the `insert` or `delete` call for the current model, // returning a promise. _processPlainPivot: Promise.method(function(method, item, options, data) { const relatedData = this.relatedData; // Grab the `knex` query builder for the current model, and // check if we have any additional constraints for the query. const builder = this._builder(relatedData.joinTable()); if (options && options.query) { Helpers.query.call(null, {_knex: builder}, [options.query]); } if (options) { if (options.transacting) builder.transacting(options.transacting); if (options.debug) builder.debug(); } const collection = this; if (method === 'delete') { return builder .where(data) .del() .then(function() { if (!item) return collection.reset(); const model = collection.get(data[relatedData.key('otherKey')]); if (model) { collection.remove(model); } }); } if (method === 'update') { return builder .where(data) .update(item) .then(function(numUpdated) { if (options && options.require === true && numUpdated === 0) { throw new Error('No rows were updated'); } return numUpdated; }); } return this.triggerThen('creating', this, data, options).then(function() { return builder.insert(data).then(function() { collection.add(item); }); }); }), // Loads or prepares a pivot model based on the constraints and deals with // pivot model changes by calling the appropriate Bookshelf Model API // methods. Returns a promise. _processModelPivot: Promise.method(function(method, item, options, data, fks) { const relatedData = this.relatedData, JoinModel = relatedData.throughTarget, joinModel = new JoinModel(); fks = joinModel.parse(fks); data = joinModel.parse(data); if (method === 'insert') { return joinModel.set(data).save(null, options); } return joinModel .set(fks) .fetch({ require: true }) .then(function(instance) { if (method === 'delete') { return instance.destroy(options); } return instance.save(item, options); }); }) }; module.exports = Relation;
import React from "react" import { Grid, Container, Label, Segment, Header} from 'semantic-ui-react' import ContactForm from '../components/form' import SiteNav from '../components/site-nav' export default ({ data }) => { const post = data.markdownRemark return ( <div> <SiteNav></SiteNav> <Segment basic className={"fluid-grid"}> <Grid columns={1} className={'thumbnails-grid'}> <Grid.Column> {post.frontmatter.hero ? <img className="project-hero" src={post.frontmatter.hero.childImageSharp.resolutions.src} alt="Smiley face" /> : null} </Grid.Column> </Grid> </Segment> <Container> <Segment padded={'very'} basic> <Header as={'h2'} color={"purple"} className={"main-header"}>{post.frontmatter.title}</Header> {post.frontmatter.tags.map(i => <Label key={i} circular color={'black'}>{[i]}</Label>)} <div className='markdown-text'> <div dangerouslySetInnerHTML={{ __html: post.html }} /> </div> </Segment> </Container> <div className={"form"}> <Container> <Segment padded={"very"} basic className={"fluid-grid"}> <Header as={'h2'}>Like what you see? LETS TALK.</Header> <Header as={'h4'} className={"spaced"}>SUBMIT REQUEST</Header> <ContactForm/> </Segment> </Container> </div> </div> ) } export const query = graphql` query BlogPostQuery($slug: String!) { markdownRemark(fields: { slug: { eq: $slug } }) { html frontmatter { title tags hero { childImageSharp { resolutions(width: 3600) { src } } } } } } `
var express = require('express'); var router = express.Router(); router.get('/', function(req, res){ req.logout(); res.redirect('/login'); }); module.exports = router;
/** * * Link * */ import React from 'react'; import PropTypes from 'prop-types'; import Wrapper from './Wrapper'; function Link(props) { const { onClick } = props; return ( <Wrapper onClick={() => onClick()}> {props.children} </Wrapper> ); } Link.propTypes = { // properties children: PropTypes.node.isRequired, // actions onClick: PropTypes.func.isRequired, }; export default Link;
require('dotenv').config(); var assert = require('chai').assert; var expect = require('chai').expect; var Slamback = require('../slamback'); const readFile = require('fs-readfile-promise'); // https://my-ideas-slack.slack.com var configSet = {"slackChan":"#slamback-dev", "slackToken": process.env.SLACK_TOKEN}; // my-ideas.it@aws var s3Config = { bucket: 'slamback-dev-001', key: 'sample-zipped-artifact/afile.csv.zip' }; describe('Slamback unit test', function() { it('#constructor throw an Error if Slack token is missing', function () { expect(function () { var s = new new Slamback({}); }).to.throw(Error); }) }); describe('Slamback integration test (requires Slack and S3 access)', function() { describe('#postMessage', function() { it("send a message to slack", () => { return new Slamback(configSet) .postMessage('A sample message') .then((response) => assert.equal(response.ok, true)); }); }); describe('#getS3Object', function() { it("Get an object from S3 and put it in /tmp", function () { var s = new Slamback(configSet); return s.getS3Object(s3Config) .then(s.unzip) .then((path) => readFile(`${path}/afile.csv`)) .then((message) => assert.equal(message.toString(), "C'era una volta una gatta")) }); }); describe('#slackPostFile', function() { it("Can post a file to a slack channel", function () { return new Slamback(configSet).slackPostFile({ title: 'Elysium app', channels: '#slamback-dev', initial_comment: "Try the new release!", file: 'test-resources' }) .then(response => assert.equal(response[0].ok, true)); }); }); });
/** * Module dependencies. */ if(!process.env.NODE_ENV) process.env.NODE_ENV = 'development'; var express = require('express') , crypto = require('crypto') , jws = require('jws') , http = require('http') , https = require('https') , path = require('path') , fs = require('fs') , date = require('date-utils') , helmet = require('helmet') , nconf = require('nconf').file(process.env.NODE_ENV+'_settings.json') , nano = require('nano')(nconf.get('couchdb')) , db = nano.use('thmcards') , _ = require('underscore') , sanitizer = require('sanitizer') , passport = require('passport') , FacebookStrategy = require('passport-facebook').Strategy , TwitterStrategy = require('passport-twitter').Strategy , GoogleStrategy = require('passport-google').Strategy , app = express() ; var secret = 'some secret'; var sessionKey = 'express.sid'; var cookieParser = express.cookieParser(secret); var sessionStore = new express.session.MemoryStore() var https_server, http_server, io; if(process.env.NODE_ENV === 'production') { var options = { key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.crt') }; https_server = https.createServer(options, app); http_server = http.createServer(app); io = require('socket.io').listen(https_server, {secure: true}); } else { http_server = http.createServer(app); io = require('socket.io').listen(http_server); } function forceSSL(req, res, next) { if (!req.secure && process.env.NODE_ENV === 'production') { return res.redirect('https://' + req.get('host') + req.url); } return next(null); } app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon(__dirname + '/public/img/favicon.ico')); app.use(helmet.xframe()); app.use(helmet.xssFilter()); app.use(helmet.nosniff()); app.use(helmet.hsts({ maxAge: 7776000000 })); app.use(helmet.hidePoweredBy()); app.use(cookieParser); app.use(express.json()); app.use(express.methodOverride()); app.use(express.session({ store: sessionStore, key: sessionKey, cookie: { httpOnly: true } })); app.use(passport.initialize()); app.use(passport.session()); app.use((function(options) { var csrf = express.csrf(options); return function(req, res, next) { function onCsrfCalled() { var token = req.csrfToken(); var cookie = req.cookies['csrf.token']; if(token && cookie !== token) { res.cookie('csrf.token', token); } res.header('Vary', 'Cookie'); next(); } csrf(req, res, onCsrfCalled); } })()); app.use(app.router); app.use(express.compress()); app.use(express.staticCache()); app.use(express.static(path.join(__dirname, 'public'), { maxAge: 86400000 })); }); io.set('authorization', function(handshake, cb) { if(handshake.headers.cookie) { cookieParser(handshake, null, function(err) { if(handshake.signedCookies[sessionKey]) { handshake.sessionID = handshake.signedCookies[sessionKey]; handshake.sessionStore = sessionStore; //Session contstructor needs an Object with sessionStore set sessionStore.get(handshake.sessionID, function(err, session) { if(err) cb(err.message, false); else { var s = handshake.session = new express.session.Session(handshake, session); cb(null, true); } }); } else cb('Session cookie could not be found', false); }); } else cb('Session cookie could not be found', false); }); io.sockets.on('connection', function(socket) { console.log('Socket connected with SID: ' + socket.handshake.sessionID, socket.store.id); socket.set('sessionID', socket.handshake.sessionID); }); function getSocketBySessionID(sessionID) { var skt = null; _.each(io.sockets.clients(), function(socket) { if(sessionID == socket.store.data.sessionID) skt = socket; }) return skt; } function checkOwner(doc_id, owner, success_callback, error_callback) { db.get(doc_id, function(err, body){ if(_.has(body, "owner") && body.owner === owner) { success_callback(); } else { error_callback(); } }); } var redeemXPoints = function(name, value, username) { var now = new Date().getTime(); db.insert({ type: "xp", name: name, value: value, gained: now, owner: username }, function(err, body) { if(!err && body.ok) { console.log("XP '"+name+" ("+value+")' redemmed for user '"+username+"'"); } else { console.log("Wasn't able to redeem XP for user '"+username+"'"); } }); } var redeemLoginXPoints = function(username){ var msPerDay = 86400 * 1000; var now = new Date().getTime(); var todayStart = now - (now % msPerDay); todayStart += ((new Date).getTimezoneOffset() * 60 * 1000) var todayEnd = todayStart + (msPerDay-1000); db.view("xp", "by_owner_name_gained", { startkey: new Array(username, "daily_login", todayStart ), endkey: new Array(username, "daily_login", todayEnd)}, function(err, body){ if(!err) { if(!_.isUndefined(body.rows) && body.rows.length > 0) { console.log("Daily Login XP ALREADY redemmed for user '"+username+"'"); } else { db.insert({ type: "xp", name: "daily_login", value: 2, gained: now, owner: username }, function(err, body) { if(!err && body.ok) { console.log("Daily Login XP redemmed for user '"+username+"'"); } else { console.log("Wasn't able to redeem Daily Login XP for user '"+username+"'"); } }) } } }) } var xpForLevel = function(level) { var points = 0; output = 0; for (lvl = 1; lvl < level; lvl++) { points += Math.floor(lvl + 30 * Math.pow(2, lvl / 10.)); output = Math.floor(points / 4); } return output; } var levelForXp = function(pts) { var points = 0; var output = 0; var lvl = 1; while(pts > output) { points += Math.floor(lvl + 30 * Math.pow(2, lvl / 10.)); output = Math.floor(points / 4); if(pts >= output) lvl++; } return lvl; } var calcInterval = function(current_interval, last_rated, repeat, callback) { var interval; if((last_rated < 3) || (repeat == 1)) { interval = 1; } else { interval = parseInt(current_interval) + 1; } if(_.isUndefined(callback)) return interval; callback(interval); } var calcEF = function(ef_old, last_rated, callback) { var ef; ef= parseFloat(ef_old)+(0.1-(5-parseInt(last_rated))*(0.08+(5-parseInt(last_rated))*0.02)); if(ef<1.3) { ef = 1.3; } if(_.isUndefined(callback)) return ef; callback(ef); } var calcIntervalDays = function(interval, interval_days_before, ef) { var interval_days; if(interval == 1) { interval_days = 1; } if(interval == 2) { interval_days = 6; } if(interval > 2) { interval_days = Math.ceil(parseInt(interval_days_before) * parseFloat(ef)); } return interval_days; } //------------------------------------------------------------------------------------ //----------------------- LOGIN & AUTH ----------------------------------- //------------------------------------------------------------------------------------ passport.serializeUser(function(user, done) { done(null, user); }); passport.deserializeUser(function(user, done) { done(null, user); }); function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); var cookie = req.cookies.usr; if (cookie === undefined || req.cookies.usr.username !== user) { var usr = JSON.stringify({ //"id": user._id, "username": user.username, //"provider": user.provider }); res.cookie('usr', usr, { httpOnly: false }); } return next(null); } if(req.url != '/') { res.send(401); } else { res.redirect('/login'); } } var User = {}; User.findOrCreate = function(profile, done) { db.view('users', 'by_provider_and_username', { key: new Array(profile.provider, profile.username) }, function(err, body) { if(_.size(body.rows) > 0) { var user = _.map(body.rows, function(doc) { return doc.value}); return done(err, user); } else { var email = null; if(_.isArray(profile.emails)) { email = _.first(profile.emails); if(_.has(email, "value")) email = email.value; } db.insert( { "provider": profile.provider, "username": profile.username || null, "email": email, "profile": "public", "type": "user" }, function(err, body, header){ if(err) { console.log('[db.insert] ', err.message); return; } db.get(body.id, { revs_info: false }, function(err, body) { if(err) { console.log('[db.get] ', err.message); return; } var user = body; return done(err, user); }); }); } }); }; passport.use(new FacebookStrategy({ clientID: nconf.get("facebook_clientid"), clientSecret: nconf.get("facebook_clientsecret"), callbackURL: nconf.get('facebook_callback') }, function(accessToken, refreshToken, profile, done) { return User.findOrCreate(profile, done); } )); passport.use(new TwitterStrategy({ consumerKey: nconf.get("twitter_key"), consumerSecret: nconf.get("twitter_secret"), callbackURL: nconf.get('twitter_callback') }, function(token, tokenSecret, profile, done) { return User.findOrCreate(profile, done); })); passport.use(new GoogleStrategy({ returnURL: nconf.get("google_callback"), realm: nconf.get("google_realm") }, function(identifier, profile, done) { profile.openID = identifier; profile.provider = "google"; profile.username = profile.emails[0].value; return User.findOrCreate(profile, done); } )); app.get('/login', forceSSL, function(req, res) { if(req.isAuthenticated()) res.redirect('/'); fs.readFile(__dirname + '/views/welcome.html', 'utf8', function(err, text){ res.send(text); }); }); app.get('/impressum', forceSSL, function(req, res) { fs.readFile(__dirname + '/views/impressum.html', 'utf8', function(err, text){ res.send(text); }); }); app.get('/auth/twitter', passport.authenticate('twitter')); app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), function(req, res) { if(_.has(res.req, "user")) { var user = res.req.user; if(_.isArray(user)) user = _.first(user); redeemLoginXPoints(user.username); checkBadgeStammgast(user.username, res.sessionID); } res.redirect('/'); } ); app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email, user_about_me'] })); app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), function(req, res) { if(_.has(res.req, "user")) { var user = res.req.user; if(_.isArray(user)) user = _.first(user); redeemLoginXPoints(user.username); checkBadgeStammgast(user.username, res.sessionID); } res.redirect('/'); } ); app.get('/auth/google', passport.authenticate('google')); app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), function(req, res) { if(_.has(res.req, "user")) { var user = res.req.user; if(_.isArray(user)) user = _.first(user); redeemLoginXPoints(user.username); checkBadgeStammgast(user.username, res.sessionID); } res.redirect('/'); } ); app.get('/logout', forceSSL, function(req, res){ req.logout(); res.clearCookie('usr'); res.clearCookie('csrf.token'); res.redirect('/'); }); app.get('/whoami', ensureAuthenticated, function(req, res) { var user = req.session.passport.user; if(_.isArray(user)) user = _.first(user); res.json(_.pick(user, 'username', 'name', 'email')); }); //------------------------------------------------------------------------------------ app.get('/', forceSSL, ensureAuthenticated, function(req, res){ fs.readFile(__dirname + '/views/index.html', 'utf8', function(err, text){ res.send(text); }); }); app.get('/set/category', forceSSL, ensureAuthenticated, function(req, res){ db.view('misc', 'all_set_categories', { group: true }, function(err, body) { if (!err) { var docs = _.map(body.rows, function(doc) { return {name: _.first(doc.key), count: doc.value }}); res.json(docs); } else { console.log("[db.cards/by_set]", err.message); res.send(404); } }); }); app.get('/typeahead/set/category', forceSSL, function(req, res){ var query = ''; if(!_.isUndefined(req.query.q)) query = req.query.q; db.view('misc', 'all_set_categories', { group: true, startkey: new Array(query) }, function(err, body) { if (!err) { var docs = _.filter(body.rows, function(doc){ return _.first(doc.key).toLowerCase().indexOf(query.toLowerCase()) > -1; }); docs = _.map(docs, function(doc) { return {value: _.first(doc.key), tokens: doc.key, count: doc.value }}); res.json(docs); } else { console.log("[db.cards/by_set]", err.message); } }); }); app.get('/typeahead/set/visibility', forceSSL, function(req, res){ var query = ''; if(!_.isUndefined(req.query.q)) query = req.query.q; db.view('sets', 'by_visibility', { startkey: new Array(query) }, function(err, body) { if (!err) { var docs = _.filter(body.rows, function(doc){ return doc.value.name.toLowerCase().indexOf(query.toLowerCase()) > -1; }); var docs = _.map(docs, function(doc) { return {value: doc.value.name, tokens: _.uniq(_.compact(_.union(doc.value.description, doc.value.name))), description: doc.value.description, id: doc.value._id }}); res.json(docs); } else { console.log("[db.cards/by_set]", err.message); } }); }); app.get('/set/category/:category', forceSSL, function(req, res){ var category = sanitizer.sanitize(req.params.category); db.view('sets', 'by_category', { startkey: new Array(category), endkey: new Array(category, {}) }, function(err, body) { if (!err) { var docs = _.map(body.rows, function(doc) { return doc.value }); res.json(docs); } else { console.log("[db.cards/by_set]", err.message); res.json({}); } }); }); app.get('/set/:id/personalcard', forceSSL, function(req, res){ var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); var username = user.username; db.view('cards', 'personal_card', { startkey: new Array(req.params.id), endkey: new Array(req.params.id, {}) }, function(err, body) { var cards = _.filter(body.rows, function(row){ return (row.key[2] == 0); }) _.each(cards, function(card){ var persCard = _.filter(body.rows, function(row){ return ((row.key[2] == 1) && (row.value.cardId == card.value._id) && (row.value.owner == username)); }); card.value.persCard = persCard; }, this); cards = _.pluck(cards, "value"); res.json(_.sortBy(cards, function(card){ return card.created })); }); }); app.get('/set/learned', forceSSL, ensureAuthenticated, function(req, res){ var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); var username = user.username; db.view('cards', 'personal_card_by_owner', { startkey: new Array(username), endkey: new Array(username, {}) }, function(err, body) { if(!err && !_.isEmpty(body.rows)) { var cards = _.filter(body.rows, function(row){ return row.key[2] == 0; }); var setIds = new Array(); _.each(cards, function(card){ var persCard = _.filter(body.rows, function(row){ return ((row.key[2] == 1) && (row.value.cardId == card.value._id)); }); if(!_.isUndefined(persCard) && !_.isEmpty(persCard)) { setIds.push(card.value.setId); } }, this); setIds = _.uniq(setIds); var setIdKeys = new Array(); _.each(setIds, function(setId) { var s = new Array(setId, 0); setIdKeys.push(s); }); db.view('sets', 'by_id_with_cards', function(err, body) { var sets = _.filter(body.rows, function(row){ return ((row.key[1] == 0) && ( _.contains(setIds,row.value._id)) )}); _.each(sets, function(set){ var cardCnt = _.filter(body.rows, function(row){ return ((row.key[1] == 1) && (row.value.setId == set.value._id)); }); set.value.cardCnt = cardCnt.length; if(!_.has(set.value, "category") && _.isUndefined(set.value.category)) set.value.category = ""; }, this); sets = _.pluck(sets, "value"); sets = _.filter(sets, function(set){ return set.visibility == 'public' && set.cardCnt > 0; }); sets = _.map(sets, function(set){ set._id = sanitizer.sanitize(set._id); set._rev = sanitizer.sanitize(set._rev); set.owner = sanitizer.sanitize(set.owner); set.name = sanitizer.sanitize(set.name);; set.description = sanitizer.sanitize(set.description);; set.visibility = sanitizer.sanitize(set.visibility);; set.category = sanitizer.sanitize(set.category);; set.rating = (set.rating) ? set.rating : false; set.type = "set"; return set; }); res.json(_.sortBy(sets, function(set){ return set.name })); }); } else { console.log(err); res.json([]); } }); }); app.get('/set/:id/card', forceSSL, function(req, res){ db.view('cards', 'by_set', { key: new Array(req.params.id) }, function(err, body) { if (!err) { var docs = _.map(body.rows, function(doc) { doc.value._id = sanitizer.sanitize(doc.value._id); doc.value._rev = sanitizer.sanitize(doc.value._rev); doc.value.created = sanitizer.sanitize(doc.value.created); doc.value.owner = sanitizer.sanitize(doc.value.owner); doc.value.setId = sanitizer.sanitize(doc.value.setId); doc.value.front.text = sanitizer.sanitize(doc.value.front.text); doc.value.front.text_plain = sanitizer.sanitize(doc.value.front.text_plain); doc.value.front.picture = (doc.value.front.picture) ? sanitizer.sanitize(doc.value.front.picture) : ''; doc.value.front.video = sanitizer.sanitize(doc.value.front.video); doc.value.back.text = sanitizer.sanitize(doc.value.back.text); doc.value.back.text_plain = sanitizer.sanitize(doc.value.back.text_plain); doc.value.back.picture = (doc.value.back.picture) ? sanitizer.sanitize(doc.value.back.picture) : ''; doc.value.back.video = sanitizer.sanitize(doc.value.back.video); doc.value.type = "card"; return doc.value; }); res.json(docs); } else { console.log("[db.cards/by_set]", err.message); res.send(404); } }); }); app.get('/set/:id/memo/card', forceSSL, function(req, res){ var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); var username = user.username; var today = new Date.today(); db.view('cards', 'personal_card', { startkey: new Array(req.params.id), endkey: new Array(req.params.id, {}) }, function(err, body) { var cards = _.filter(body.rows, function(row){ return (row.key[2] == 0); }) _.each(cards, function(card){ var persCard = _.filter(body.rows, function(row){ return ((row.key[2] == 1) && (row.value.cardId == card.value._id) && (row.value.owner == username)); }); card.value.persCard = persCard; }, this); cards = _.pluck(cards, "value"); var cardsFiltered = _.filter(cards, function(card){ if(_.isEmpty(card.persCard)){ return card}; if(!_.isEmpty(card.persCard)){ var lastLearned = new Date(card.persCard[0].value.sm_last_learned); var nextDate = new Date(card.persCard[0].value.sm_next_date); if(Date.compare(today, nextDate) >= 0){ return card}; if(parseInt(card.persCard[0].value.sm_instant_repeat) == 1) { return card}; }; }) res.json(_.sortBy(cardsFiltered, function(card){ return card.created })); }); }); app.get('/set/:id', forceSSL, function(req, res){ db.view('sets', 'by_id', { key: new Array(req.params.id) }, function(err, body) { if (!err) { var docs = _.map(body.rows, function(doc) { doc.value._id = sanitizer.sanitize(doc.value._id); doc.value._rev = sanitizer.sanitize(doc.value._rev); doc.value.name = sanitizer.sanitize(doc.value.name); doc.value.description = sanitizer.sanitize(doc.value.description); doc.value.visibility = sanitizer.sanitize(doc.value.visibility); doc.value.category = sanitizer.sanitize(doc.value.category); doc.value.owner = sanitizer.sanitize(doc.value.owner); doc.value.type = 'set'; return doc.value; }); res.json(docs[0]); } else { console.log("[db.sets/by_id]", err.message); res.send(404); } }); }); app.get('/user/:username', forceSSL, ensureAuthenticated, function(req, res){ db.view('users', 'by_username', { key: req.params.username }, function(err, body) { if(!_.isUndefined(body.rows) && _.size(body.rows) > 0) { var userInfo = _.first(body.rows).value; userInfo._id = sanitizer.sanitize(userInfo._id); userInfo._rev = sanitizer.sanitize(userInfo._rev); userInfo.provider = sanitizer.sanitize(userInfo.provider); userInfo.username = sanitizer.sanitize(userInfo.username); userInfo.name = sanitizer.sanitize(userInfo.name); userInfo.email = (userInfo.email) ? sanitizer.sanitize(userInfo.email) : ''; userInfo.profile = sanitizer.sanitize(userInfo.profile); userInfo.type = 'user'; res.json(userInfo); } else { res.send(404); } }); }); app.put('/user/:username', forceSSL, ensureAuthenticated, function(req, res){ var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); if(req.params.username === user.username) { db.view('users', 'by_username', { key: user.username }, function(err, body) { if(!err) { var user = body.rows[0].value; user.name = req.body.name; user.email = req.body.email; user.profile = req.body.profile; db.insert(user, body.rows[0].id, function(err, body){ if(!err) { res.json(body); } else { console.log("[db.users/by_username]", err.message); res.send(404); } }); } else { console.log(err); } }); } }); app.get('/set/user/:username', forceSSL, ensureAuthenticated, function(req, res) { var username = req.params.username; if(!_.isUndefined(username)) { db.view('sets', 'by_id_with_cards', function(err, body) { var sets = _.filter(body.rows, function(row){ return ((row.key[1] == 0) && ( row.value.owner == username )); }) _.each(sets, function(set){ var cardCnt = _.filter(body.rows, function(row){ return ((row.key[1] == 1) && (row.value.setId == set.value._id)); }); set.value.cardCnt = cardCnt.length; if(!_.has(set.value, "category") && _.isUndefined(set.value.category)) set.value.category = ""; }, this); sets = _.pluck(sets, "value"); sets = _.filter(sets, function(set){ return set.visibility == 'public' && set.cardCnt > 0; }); sets = _.map(sets, function(set){ set._id = sanitizer.sanitize(set._id); set._rev = sanitizer.sanitize(set._rev); set.owner = sanitizer.sanitize(set.owner); set.name = sanitizer.sanitize(set.name);; set.description = sanitizer.sanitize(set.description);; set.visibility = sanitizer.sanitize(set.visibility);; set.category = sanitizer.sanitize(set.category);; set.rating = (set.rating) ? set.rating : false; set.type = "set"; return set; }); res.json(_.sortBy(sets, function(set){ return set.name })); }); } else { res.send(404); } }); app.get('/set', forceSSL, ensureAuthenticated, function(req, res){ var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); setTimeout(function(){ checkBadgeKritikerLiebling(user.username, req.sessionID); checkBadgeStreber(user.username, req.sessionID); checkBadgeMeteor(user.username, req.sessionID); checkBadgeKritiker(user.username, req.sessionID); checkBadgeAutor(user.username, req.sessionID); }, 1000); db.view('sets', 'by_id_with_cards', function(err, body) { var sets = _.filter(body.rows, function(row){ return ((row.key[1] == 0) && ( row.value.owner == user.username )); }) _.each(sets, function(set){ var cardCnt = _.filter(body.rows, function(row){ return ((row.key[1] == 1) && (row.value.setId == set.value._id)); }); set.value.cardCnt = cardCnt.length; if(!_.has(set.value, "category") && _.isUndefined(set.value.category)) set.value.category = ""; }, this); sets = _.pluck(sets, "value"); sets = _.map(sets, function(set){ set._id = sanitizer.sanitize(set._id); set._rev = sanitizer.sanitize(set._rev); set.owner = sanitizer.sanitize(set.owner); set.name = sanitizer.sanitize(set.name);; set.description = sanitizer.sanitize(set.description);; set.visibility = sanitizer.sanitize(set.visibility);; set.category = sanitizer.sanitize(set.category);; set.rating = (set.rating) ? set.rating : false; set.type = "set"; return set; }); res.json(_.sortBy(sets, function(set){ return set.name })); }); }); app.post('/set', forceSSL, ensureAuthenticated, function(req, res){ var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); var time = new Date().getTime(); var data = {}; data.owner = user.username; data.name = sanitizer.sanitize(req.body.name), data.description = sanitizer.sanitize(req.body.description), data.visibility = sanitizer.sanitize(req.body.visibility), data.category = sanitizer.sanitize(req.body.category), data.cardCnt = parseInt(sanitizer.sanitize(req.body.cardCnt)), data.rating = (req.body.rating === 'true') data.type = "set"; data.created = sanitizer.sanitize(time); db.insert( data, function(err, body, header){ if(err) { console.log('[db.insert] ', err.message); return; } redeemXPoints("create_set", 2, user.username); db.get(body.id, { revs_info: false }, function(err, body) { if (!err) res.json(body); }); }); }); app.put('/set/:setid', forceSSL, ensureAuthenticated, function(req, res){ db.view('sets', 'by_id', { key: new Array(req.body._id)}, function(err, body) { if (!err) { doc = _.map(body.rows, function(doc) { return doc.value}); var data = {}; data._id = sanitizer.sanitize(req.body._id); data._rev = sanitizer.sanitize(req.body._rev); data.cardCnt = parseInt(sanitizer.sanitize(req.body.cardCnt)); data.created = sanitizer.sanitize(req.body.created); data.type = "set"; data.name = sanitizer.sanitize(req.body.name); data.description = sanitizer.sanitize(req.body.description); data.visibility = sanitizer.sanitize(req.body.visibility); data.category = sanitizer.sanitize(req.body.category); data.rating = (req.body.rating === 'true'); db.insert(req.body, doc[0]._id, function(err, body, header){ if(err) { console.log('[db.insert] ', err.message); return; } db.get(body.id, { revs_info: false }, function(err, body) { if (!err) res.json(body); }); }); } else { console.log("[db.sets/by_id]", err.message); res.send(404); } }); }); app.delete('/set/:setid', forceSSL, ensureAuthenticated, function(req, res){ var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); checkOwner(req.params.setid, user.username, function(){ db.view('cards', 'by_set', { key: new Array(req.params.setid)}, function(err, body) { if (!err) { var docs = _.map(body.rows, function(doc) { return doc.value}); var cardIds = _.pluck(docs, "_id"); _.each(cardIds, function(cardId){ db.view('cards', 'personal_card_by_cardId', { key: new Array(cardId)}, function(err, body) { if (!err) { var docs = _.map(body.rows, function(doc) { return doc.value}); var personal = new Array(); _.each(docs, function(doc){ var doc = { _id: doc._id, _rev: doc._rev, _deleted: true } personal.push(doc) }, this); db.bulk({"docs": personal}, function(err, body) { var normalCard = new Array(); _.each(docs, function(doc){ var doc = { _id: doc._id, _rev: doc._rev, _deleted: true } normalCard.push(doc) }, this); db.bulk({"docs": normalCard}, function(err, body) { db.get(req.params.setid, function(err, body){ if(!err) { var doc = { _id: body._id, _rev: body._rev, _deleted: true }; db.bulk({"docs": new Array(doc)}, function(err, body){ console.log(err); }); } }); }); }); } else { console.log("[db.sets/by_id]", err.message); } }); }, this); db.get(req.params.setid, function(err, body){ if(!err) { var doc = { _id: body._id, _rev: body._rev, _deleted: true }; db.bulk({"docs": new Array(doc)}, function(err, body){ console.log(err); }); } }); res.json(body); } else { console.log("[db.sets/by_id]", err.message); } }); }, function(){ res.send(403); }); }); app.get('/card/:id', forceSSL, ensureAuthenticated, function(req, res){ db.view('cards', 'by_id', { key: new Array(req.params.id) }, function(err, body) { if (!_.isUndefined(body.rows) && !err && body.rows.length > 0) { var card = _.first(body.rows).value; if(!(card.front.text && card.back.text)) res.send(400); card._id = sanitizer.sanitize(card._id); card._rev = sanitizer.sanitize(card._rev); card.created = sanitizer.sanitize(card.created); card.owner = sanitizer.sanitize(card.owner); card.setId = sanitizer.sanitize(card.setId); card.front.text = sanitizer.sanitize(card.front.text); card.front.text_plain = sanitizer.sanitize(card.front.text_plain); card.front.picture = (card.front.picture) ? sanitizer.sanitize(card.front.picture) : ''; card.front.video = sanitizer.sanitize(card.front.video); card.back.text = sanitizer.sanitize(card.back.text); card.back.text_plain = sanitizer.sanitize(card.back.text_plain); card.back.picture = (card.back.picture) ? sanitizer.sanitize(card.back.picture) : ''; card.back.video = sanitizer.sanitize(card.back.video); card.type = "card"; res.json(card); } else { console.log("[db.cards/by_id]", err.message); res.json(404); } }); }); app.put('/card/:id', forceSSL, ensureAuthenticated, function(req, res){ var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); checkOwner(req.body._id, user.username, function(){ db.view('cards', 'by_id', { key: new Array(req.params.id) }, function(err, body) { var card = req.body; if(!(card.front.text && card.back.text)) res.send(400); card._id = sanitizer.sanitize(card._id); card._rev = sanitizer.sanitize(card._rev); card.created = sanitizer.sanitize(card.created); card.owner = sanitizer.sanitize(card.owner); card.setId = sanitizer.sanitize(card.setId); card.front.text = sanitizer.sanitize(card.front.text); card.front.text_plain = sanitizer.sanitize(card.front.text_plain); card.front.picture = (card.front.picture) ? sanitizer.sanitize(card.front.picture) : ''; card.front.video = sanitizer.sanitize(card.front.video); card.back.text = sanitizer.sanitize(card.back.text); card.back.text_plain = sanitizer.sanitize(card.back.text_plain); card.back.picture = (card.back.picture) ? sanitizer.sanitize(card.back.picture) : ''; card.back.video = sanitizer.sanitize(card.back.video); card.type = "card"; db.insert(card, req.params.id, function(err, body){ if(!err) { res.json(body); } else { console.log("[db.users/by_username]", err.message); } }); }); }, function(){ res.send(403); }); }); app.delete('/card/:id', forceSSL, ensureAuthenticated, function(req, res) { var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); checkOwner(req.params.id, user.username, function(){ db.get(req.params.id, function(err, body){ if(!err) { var doc = { _id: body._id, _rev: body._rev, _deleted: true }; db.bulk({"docs": new Array(doc)}, function(err, body){ if (!err) { db.view('cards', 'personal_card_by_cardId', { key: new Array(req.params.id)}, function(err, body) { if (!err) { var docs = _.map(body.rows, function(doc) { return doc.value}); var personal = new Array(); _.each(docs, function(doc){ var doc = { _id: doc._id, _rev: doc._rev, _deleted: true } personal.push(doc) }, this); db.bulk({"docs": personal}, function(err, body) { }); res.json(body); } }); } else { console.log('[db.delete] ', err.message); res.send(404); } }); } }); }, function(){ res.send(403); }); }); app.post('/card', forceSSL, ensureAuthenticated, function(req, res){ var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); var owner = user.username; checkOwner(req.body.setId, owner, function(){ var time = new Date().getTime(); var card = req.body; if(!(card.front.text && card.back.text)) res.send(400); card.created = time; card.owner = owner; card.setId = sanitizer.sanitize(card.setId); card.front.text = sanitizer.sanitize(card.front.text); card.front.text_plain = sanitizer.sanitize(card.front.text_plain); card.front.picture = (card.front.picture) ? sanitizer.sanitize(card.front.picture) : ''; card.front.video = sanitizer.sanitize(card.front.video); card.back.text = sanitizer.sanitize(card.back.text); card.back.text_plain = sanitizer.sanitize(card.back.text_plain); card.back.picture = (card.back.picture) ? sanitizer.sanitize(card.back.picture) : ''; card.back.video = sanitizer.sanitize(card.back.video); card.type = "card"; db.insert( card, function(err, body, header){ if(err) { console.log('[db.insert] ', err.message); return; } redeemXPoints("create_card", 2, owner); checkBadgeAutor(owner, req.sessionID); db.get(body.id, { revs_info: false }, function(err, body) { if (!err) res.json(body); }); }); }, function(){ res.send(403); }); }); app.post('/personalcard/:cardid', forceSSL, ensureAuthenticated, function(req, res){ var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); var time = new Date().getTime(); var username = user.username; var smTimesLearned; var smLastLearned; var smIntervalDays; var currentDate = Date.today();; var nextDate; var instantRepeat = "0"; if (_.has(req.body.persCard.value, "last_rated")){ smTimesLearned = 1; smLastLearned = Date.today(); smIntervalDays = 1; smInterval = 1; nextDate = currentDate.addDays(1); if (parseInt(req.body.persCard.value.last_rated) < 4) { instantRepeat = "1" } } else { smTimesLearned = 0; smLastLearned = 0; smIntervalDays = 0; smInterval = 0; nextDate = 0; } db.insert( { "created": time, "owner": user.username, "cardId": _.escape(req.body._id), "setId": _.escape(req.body.setId), "box": _.escape(req.body.persCard.value.box) || "1", "type": "personal_card", "times_learned": "1", "sm_times_learned": smTimesLearned, "sm_interval": smInterval, "sm_ef": "2.5", "sm_instant_repeat": instantRepeat, "sm_interval_days": smIntervalDays, "sm_last_learned": smLastLearned, "sm_next_date": nextDate }, function(err, body, header){ if(err) { console.log('[db.insert] ', err.message); return; } db.get(body.id, { revs_info: false }, function(err, body) { if (!err){ var persCard = {}; persCard.value = body; db.get(req.body._id, { revs_info: false }, function(err, body) { if (!err) body.persCard = persCard; res.json(body); }); } else { res.send(404); } }); }); }); app.put('/personalcard/:cardid', forceSSL, ensureAuthenticated, function(req, res){ var time = new Date().getTime(); var today = Date.today(); var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); var username = user.username; db.view('cards', 'personal_card_by_cardId', { key: new Array(req.body._id)}, function(err, body) { if (!err){ var docs = _.filter(body.rows, function(row){ return (row.value.owner == username ); }) docs = _.map(docs, function(doc) { return doc.value }); if (body.rows.length){ if (_.has(req.body.persCard.value, "last_rated")){ var instantRepeat = "0"; if (parseInt(req.body.persCard.value.last_rated) < 4) { instantRepeat = "1" } calcInterval(_.first(docs).sm_interval, _.escape(req.body.persCard.value.last_rated), parseInt(docs[0].sm_instant_repeat), function(interval){ calcEF(_.first(docs).sm_ef, _.escape(req.body.persCard.value.last_rated), function(ef){ var intervalDays = calcIntervalDays(interval, parseInt(docs[0].sm_interval_days), ef); var currentDate = today.clone(); var nextDate = currentDate.addDays(parseInt(intervalDays)); db.insert( { "_rev": docs[0]._rev, "created": docs[0].created, "owner": docs[0].owner, "cardId": docs[0].cardId, "setId": docs[0].setId, "type": docs[0].type, "box": docs[0].box, "times_learned": parseInt(docs[0].times_learned) + 1, "sm_times_learned": parseInt(docs[0].sm_times_learned) + 1, "sm_interval": interval, "sm_ef": ef, "sm_interval_days": intervalDays, "sm_instant_repeat": instantRepeat, "sm_last_learned": today, "sm_next_date": nextDate }, docs[0]._id, function(err, body, header){ if(err) { console.log('[db.insert] ', err.message); return; } db.get(body.id, { revs_info: false }, function(err, body) { if (!err){ var persCard = {}; persCard.value = body; db.get(docs[0].cardId, { revs_info: false }, function(err, body) { if (!err) body.persCard = persCard; res.json(body); }); } }); }); }); }); } if (!_.has(req.body.persCard.value, "last_rated")){ db.insert( { "_rev": docs[0]._rev, "created": docs[0].created, "owner": docs[0].owner, "cardId": docs[0].cardId, "setId": docs[0].setId, "type": docs[0].type, "box": _.escape(req.body.persCard.value.box) || docs[0].box, "times_learned": parseInt(docs[0].times_learned) + 1, "sm_times_learned": docs[0].sm_times_learned, "sm_interval": docs[0].sm_interval, "sm_ef": docs[0].sm_ef, "sm_interval_days": docs[0].sm_interval_days, "sm_instant_repeat": docs[0].sm_instant_repeat, "sm_last_learned": docs[0].sm_last_learned }, docs[0]._id, function(err, body, header){ if(err) { console.log('[db.insert] ', err.message); return; } db.get(body.id, { revs_info: false }, function(err, body) { if (!err){ var persCard = {}; persCard.value = body; db.get(docs[0].cardId, { revs_info: false }, function(err, body) { if (!err) body.persCard = persCard; res.json(body); }); } }); }); } } } else { console.log("[db.personalcard/by_cardId]", err.message); res.send(404); } }); }); app.get('/score/:username', forceSSL, ensureAuthenticated, function(req, res){ var game = "meteor"; var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); user = user.username; db.view('score', 'highscore_by_game_user', { startkey: new Array(game, user), endkey: new Array(game, user), group: true }, function(err, body) { if(!_.isUndefined(body.rows) && !err && body.rows.length > 0) { var gameHighscore = _.first(body.rows).value; db.view('score', 'score_by_game_user_set', { startkey: new Array(game, user), endkey: new Array(game, user, {}) }, function(err, body) { var scores = new Array(); _.each(body.rows, function(score){ scores.push({ setId: score.key[2], points: score.value }); }); scores = _.sortBy(scores, "points"); var groupedScores = _.groupBy(scores, function(score){ return score.setId }); var games = new Array(); var keys = new Array(); _.each(groupedScores, function(score){ var highscore = _.last(score); keys.push(new Array(game, highscore.setId)); games.push({ setId: highscore.setId, setName: "unknown", personalHighscore: highscore.points, position: 0, overallHighscore: 0 }); }); var setIds = _.pluck(games, "setId"); setIds = _.map(setIds, function(set) { return new Array(set)}); db.view('sets', 'by_id', { keys: setIds }, function(err, body) { var sets = _.pluck(body.rows, "value"); _.each(sets, function(set) { var game = _.findWhere(games, { setId: set._id }); game.setName = set.name; game.setId = set._id; }); db.view('score', 'score_by_game_set', { keys: keys }, function(err, body) { var setScores = _.pluck(body.rows, "value"); setScores = _.sortBy(setScores, "points"); groupedSetScores = _.groupBy(setScores, function(score){ return score.setId }); _.each(groupedSetScores, function(score){ var setHighscore = _.last(score); var game = _.findWhere(games, {setId: setHighscore.setId}) game.overallHighscore = setHighscore.points; var points = _.pluck(score, "points"); var pos = _.sortedIndex(points, game.personalHighscore); game.position = points.length-pos; }); res.json({ owner: user, game: "meteor", score: gameHighscore, gameCnt: scores.length || 0, games: games }); }); }); }); } else { res.json({ owner: user, game: "meteor", score: 0, gameCnt: 0, games: {} }); } }); }); app.get('/score/:username/:set', forceSSL, function(req, res){ var game = "meteor"; var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); user = user.username; var setId = req.params.set; var result = { score: 0, badges: 0, badgesTotal: 0 }; db.view('score', 'score_by_game_user_set', { key: new Array(game, user, setId) }, function(err, body) { if(!err) { if(!_.isUndefined(body.rows) && _.has(body, "rows") && !_.isEmpty(body.rows)) { var scores = _.sortBy(body.rows, function(score){ return -score.value }); var score = _.first(scores); result.score = score.value; res.json(result); } else { res.json({ score: 0 }); } } }); }); app.post('/score/:username', forceSSL, ensureAuthenticated, function(req, res){ var game = 'meteor'; var owner = sanitizer.sanitize(req.body.owner); var setId = sanitizer.sanitize(req.body.setId); var points = parseInt(req.body.points); var level = parseInt(sanitizer.sanitize(req.body.level)); var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); if(points > 0) { db.insert({ type: "score", game: game, level: level, owner: owner, setId: setId, points: points }, function(err, body) { if(!err) { checkBadgeMeteor(user.username, req.sessionID); } }); } db.view('score', 'score_by_game_set', { key: new Array(game, setId) }, function(err, body) { if(!err && !_.isUndefined(body) && _.has(body, "rows")) { var scores = new Array(); _.each(body.rows, function(score){ var player = false; if(score.value.owner == owner) { player = true; } scores.push({ setId: score.value.setId, points: score.value.points, owner: score.value.owner, isPlayer: player }); }); scores = _.sortBy(scores, "points").reverse(); var highscores = {}; _.each(scores, function(score){ if(_.has(highscores, score.owner)) { if(highscores[score.owner].points < score.points) highscores[score.owner] = score; } else { highscores[score.owner] = score; } }); highscores = _.flatten(highscores); var ownerScore = _.findWhere(highscores, {owner: owner}) highscores = _.toArray(highscores); var idx = _.indexOf(highscores, ownerScore); var x = new Array(); if(highscores.length == idx+1) { x.push(highscores[idx-2]); x.push(highscores[idx-1]); x.push(highscores[idx]); } else if(0 == idx) { x.push(highscores[idx]); x.push(highscores[idx+1]); x.push(highscores[idx+2]); } else { x.push(highscores[idx-1]); x.push(highscores[idx]); x.push(highscores[idx+1]); } x = _.compact(x); res.json(x); } }); }); app.get('/xp/:username', forceSSL, ensureAuthenticated, function(req, res){ var msPerDay = 86400 * 1000; var now = new Date().getTime(); var todayStart = now - (now % msPerDay); todayStart += ((new Date).getTimezoneOffset() * 60 * 1000) var todayEnd = todayStart + (msPerDay-1000); var yesterdayStart = todayStart - msPerDay; var yesterdayEnd = todayEnd - msPerDay; var lastSevenDaysStart = todayStart - (msPerDay*7); var lastSevenDaysEnd = todayEnd - (msPerDay*7); var pointsPerLevel = 10; var result = { totalXPoints: 0, todayXPoints: 0, yesterdayXPoints: 0, lastSevenDaysXPoints: 0, currentLevel: 1, pointsRemaining: pointsPerLevel, pointsLevel: pointsPerLevel } db.view('xp', 'by_owner', { key: new Array(req.params.username) }, function(err, body) { if(!_.isUndefined(body.rows) && !err && body.rows.length > 0) { var xpoints = _.pluck(body.rows, "value"); var groupedXPoints = _.groupBy(xpoints, "name"); var todayXPoints = _.reduce(_.pluck(_(xpoints).filter(function(point){ if(point.gained >= todayStart && point.gained <= todayEnd) return point; }), "value"), function(memo, num){ return memo + num; }, 0); var yesterdayXPoints = _.reduce(_.pluck(_(xpoints).filter(function(point){ if(point.gained >= yesterdayStart && point.gained <= yesterdayEnd) return point; }), "value"), function(memo, num){ return memo + num; }, 0); var lastSevenDaysXPoints = _.reduce(_.pluck(_(xpoints).filter(function(point){ if(point.gained >= lastSevenDaysStart && point.gained <= todayEnd) return point; }), "value"), function(memo, num){ return memo + num; }, 0); var totalXPpoints = 0 _.each(xpoints, function(point) { totalXPpoints += point.value; }); var lastRedeem = _.first(_.sortBy(xpoints, "gained").reverse()); var lastRedeemName = ''; if(lastRedeem.name == 'create_set') lastRedeemName = 'Kartensatz angelegt'; if(lastRedeem.name == 'create_card') lastRedeemName = 'Karte angelegt'; if(lastRedeem.name == 'daily_login') lastRedeemName = 'Login'; if(lastRedeem.name == 'rating') lastRedeemName = 'Kartensatz bewertet'; var currentLevel = levelForXp(totalXPpoints); var pointsRemaining = xpForLevel(currentLevel+1)-totalXPpoints; result = { totalXPoints: totalXPpoints, todayXPoints: todayXPoints, yesterdayXPoints: yesterdayXPoints, lastSevenDaysXPoints: lastSevenDaysXPoints, lastRedeem: { name: lastRedeemName, value: lastRedeem.value }, currentLevel: currentLevel, pointsRemaining: pointsRemaining, pointsLevel: pointsPerLevel } } res.json(result); }); }); app.get('/rating/avg/:setId', forceSSL, ensureAuthenticated, function(req, res){ var result = { totalValutations: 0, avgValutation: 0, setId: req.params.setId } db.view("rating", "by_set", { key: new Array(req.params.setId)}, function(err, body) { if(!_.isUndefined(body.rows) && !err && body.rows.length > 0) { var ratings = _.pluck(body.rows, "value"); var avgValutation = (_.reduce(_.pluck(ratings, "value"), function(memo, num){ return memo + num; }, 0))/ratings.length; result.avgValutation = avgValutation; result.totalValutations = ratings.length; res.json(result); } else { console.log("[rating/by_set]", err); res.json(result); } }); }); app.get('/rating/permission/:setId', forceSSL, ensureAuthenticated, function(req, res){ var setId = req.params.setId; var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); var owner = user.username; var ownerPermission = false; db.get(setId, function(err, body) { if (!err) { if(body.owner == owner) { res.json({"permission":false, "owner":false}); } } }); db.view("rating", "by_set_owner", { key: new Array(setId, owner)}, function(err, body) { if(!_.isUndefined(body.rows) && !err) { if(_.size(body.rows) == 0) { res.json({"permission": true}); } else { res.json({"permission": false}); } } else { console.log("[rating/by_set_owner]", err); res.send(404); } }); }); app.get('/set/rating/:setId', forceSSL, ensureAuthenticated, function(req, res){ db.view("rating", "by_set", { key: new Array(req.params.setId)}, function(err, body) { if(!_.isUndefined(body.rows) && !err && body.rows.length > 0) { var ratings = _.pluck(body.rows, "value"); res.json(ratings); } else { console.log("[rating/by_set]", err); res.json([]); } }); }); app.post('/set/rating/:setId', forceSSL, ensureAuthenticated, function(req, res){ var value = parseInt(sanitizer.sanitize(req.body.value)); var comment = sanitizer.sanitize(req.body.comment); var setId = sanitizer.sanitize(req.params.setId); var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); var owner = sanitizer.sanitize(user.username); if(!comment && !value) res.send(400); if(comment.length >= 60) { db.insert({ type: "rating", value: value, comment: comment, setId: setId, owner: owner }, function(err, body) { if(!err && body.ok) { redeemXPoints('rating', 1, owner); checkBadgeKritiker(user.username, req.sessionID); res.json(body); } else { res.send(404); } }); } else { res.send(400); } }); app.get('/badge/:username', forceSSL, ensureAuthenticated, function(req, res){ var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); user = user.username; db.view("badge", "by_name", function(err, body) { if(!_.isUndefined(body.rows) && !err && body.rows.length > 0) { var badges = _.pluck(body.rows, "value"); var idxBadges = _.indexBy(badges, "_id"); db.view("issuedBadge", "by_owner", { keys: new Array(user) }, function(err, body) { if(!_.isUndefined(body.rows) && !err && body.rows.length > 0) { var issuedBadges = _.sortBy(_.pluck(body.rows, "value"), function(badge) { return badge.rank; }); _.each(issuedBadges, function(badge){ var badgeType = badge.badge; var usrBadge = _.pick(badge, 'issuedOn', 'rank', 'score'); if(_.has(idxBadges[badgeType], "user")) { if(idxBadges[badgeType].user.rank > usrBadge.rank) idxBadges[badgeType].user = usrBadge; } else { idxBadges[badgeType].user = usrBadge; } }); } var results = _.flatten(idxBadges); db.view('badgeProgress', 'by_owner', { keys: new Array(user) }, function(err, body) { if(!err && _.size(body.rows) > 0) { var badgeProcess = _.pluck(body.rows, "value"); _.each(badgeProcess, function(process){ var b = _.findWhere(results, { _id: process.badge}); if(_.has(b, "user")) { b.user.progress = process.score; b.user.nextRank = process.nextRank; } else { b.user = {}; b.user.progress = process.score; b.user.nextRank = process.nextRank; b.user.rank = 3; } }); res.json(results); } else { res.json(results); } }); }); } else { res.send(404); } }); }); var checkDaysInRow = function(daysInRow, username, callback) { db.view("xp", "by_owner_name_gained", { startkey: new Array(username, "daily_login" ), endkey: new Array(username, "daily_login", {})}, function(err, body){ var keys = _.pluck(body.rows, "value"); keys = _.sortBy(keys, function(key) { return -key.gained}); var dates = _.pluck(keys, "gained"); dates = _.map(dates, function(date) { var d = new Date(date); return d; }); var row = 1; for(var i = 0; i < _.size(dates); i++) { if(i == 0) continue; var current = dates[i]; var prev = dates[i-1]; if(current.isBefore(prev)) { var daysBetween = current.getDaysBetween(prev); if(daysBetween == 1) { row++; } else if(daysBetween > 1) { break; } } } if(row >= daysInRow) { callback(true, row) } else { callback(false, row); } }); } var sendMessageToUser = function(sessionID, messageType, messageObject) { setTimeout(function(){ var socket = getSocketBySessionID(sessionID); if(socket != null) { socket.emit(messageType, messageObject); } }, 500); } var issueBadge = function(badge, owner, sessionID, rank, score, callback) { db.view("issuedBadge", "by_badge_owner_rank", { startkey: new Array(badge, owner, rank), endkey: new Array(badge, owner, rank)}, function(err, body){ if(!_.isUndefined(body.rows) && !err && _.size(body.rows) > 0) { console.log("Badge '"+badge+"' ("+rank+") ALREADY issued for user '"+owner+"'"); } else { db.insert({ type: "issuedBadge", badge: badge, rank: rank, score: score, issuedOn: Math.round((new Date()).getTime() / 1000), owner: owner }, function(err, body) { if(!err && body.ok) { console.log("Badge '"+badge+"' ("+rank+") issued for user '"+owner+"'"); db.get(badge, function(err, badge){ console.log(badge); sendMessageToUser(sessionID, "badge", { badge: badge._id, rank: rank, title: badge.name}); }) } else { console.log("No Badge for '"+username+"'"); } }); } if(callback) callback(); }); } var setBadgeProgress = function(badge, owner, score, nextRank) { var badgeShort = badge.split("/")[1]; var keys = new Array(owner, badge); db.get(owner+'/'+badge, function(err, body){ if(err) { var badgeProgress = {}; badgeProgress._id = owner+'/'+badge; badgeProgress.badge = badge; badgeProgress.owner = owner; badgeProgress.score = score; badgeProgress.nextRank = nextRank; badgeProgress.type = "badgeProgress"; db.insert(badgeProgress, function(err, body){ if(!err && body.ok) { } else { } }); } else { var badgeProgress = body; badgeProgress.score = score; badgeProgress.nextRank = nextRank; db.insert(badgeProgress, function(err, body) { if(!err && body.ok) { } else { } }); } }); } var checkBadgeStammgast = function(owner, sessionID) { var badge = 'badge/stammgast'; db.get(badge, function(err, body) { if (!err) { _.each(body.rank, function(days) { checkDaysInRow(days, owner, function(result, days){ var rank = _.indexOf(_.values(body.rank), days)+1; var nextRank = _.indexOf(_.values(body.rank), days); if(nextRank > 3 || nextRank < 1) nextRank = 3; if(result) { issueBadge(badge, owner, sessionID, rank, days); } setBadgeProgress(badge, owner, days, body.rank[nextRank]); }) }); } }); } var checkBadgeMeteor = function(owner, sessionID) { var badge = "badge/meteor"; db.get(badge, function(err, body) { if (!err) { var rank = body.rank; db.view('score', 'game_by_game_user', { keys: new Array(new Array("meteor", owner)) }, function(err, body) { if(!_.isUndefined(body) && _.has(body, "rows")) { var scores = _.pluck(body.rows, "value"); var level = _.filter(scores, function(score) { return score.level >= 10 }); var levels = _.groupBy(level, "setId"); var maxLevels = new Array(); _.each(levels, function(level) { maxLevels.push(_.max(level, function(lvl){ return lvl.level })); }); maxLevels = _.groupBy(maxLevels, "setId"); var xo = _.groupBy(_.flatten(maxLevels), function(lvl){ if(lvl.level >= 30) return "thirty"; if(lvl.level >= 20 && lvl.level < 30) return "twenty"; if(lvl.level < 20) return "ten"; }) var rankValue = rank[2]; var nextRank = rank[3]; if(_.has(xo, "ten")){ if(xo.ten.length >= 2) { issueBadge(badge, owner, sessionID, 3, xo.ten.length); } else { setBadgeProgress(badge, owner, 5-xo.ten.length, 10); } } if(_.has(xo, "twenty")){ if(xo.twenty.length >= 2) { issueBadge(badge, owner, sessionID, 3, xo.twenty.length); } else { setBadgeProgress(badge, owner, 5-xo.twenty.length, 20); } } if(_.has(xo, "thirty")){ if(xo.thirty.length >= 2) { issueBadge(badge, owner, sessionID, 3, xo.thirty.length); } else { setBadgeProgress(badge, owner, 5-xo.thirty.length, 30); } } if(!_.has(xo, "ten") && !_.has(xo, "twenty") && !_.has(xo, "thirty")) { setBadgeProgress(badge, owner, 0, 10); } } }); } }); } var checkBadgeAutor = function(owner, sessionID) { var badge = "badge/autor"; db.get(badge, function(err, body) { if (!err) { var rank = body.rank; db.view('sets', 'by_id_with_cards', function(err, body) { var sets = _.filter(body.rows, function(row){ return ((row.key[1] == 0) && ( row.value.owner == owner )); }) _.each(sets, function(set){ var cardCnt = _.filter(body.rows, function(row){ return ((row.key[1] == 1) && (row.value.setId == set.value._id)); }); set.value.cardCnt = cardCnt.length; if(!_.has(set.value, "category") && _.isUndefined(set.value.category)) set.value.category = ""; }, this); sets = _.pluck(sets, "value"); sets = _.filter(sets, function(set){ return set.cardCnt >= 5 && set.visibility == 'public' }); var rankValue = 3; var nextRank = rank[3]; _.each(rank, function(r){ if(sets.length >= r) { if(rank[_.indexOf(_.values(rank), r)] > nextRank) nextRank = rank[_.indexOf(_.values(rank), r)]; rankValue = _.indexOf(_.values(rank), r)+1; issueBadge(badge, owner, sessionID, rankValue, sets.length); } }); setBadgeProgress(badge, owner, sets.length, nextRank); }); } }); } function average (arr) { return _.reduce(arr, function(memo, num) { return memo + num; }, 0) / arr.length; } var checkBadgeKritikerLiebling = function(owner, sessionID) { var badge = "badge/krone"; db.get(badge, function(err, body) { if (!err) { var rank = body.rank; db.view('sets', 'by_owner', { startkey: new Array(owner), endkey: new Array(owner) }, function(err, body) { if(!err && _.size(body.rows) > 0) { var setIds = _.pluck(body.rows, "id"); setIds = _.map(setIds, function(set) { return new Array(set)}); db.view('rating', 'by_set', { keys: setIds }, function(err, body) { if(!err && _.size(body.rows) > 0) { var ratings = _.groupBy(_.pluck(body.rows, "value"), "setId"); var cntRatedSets = 0; _.each(ratings, function(rating) { if(rating.length >= 5) { var values = _.pluck(rating, "value"); var avg = average(values); if(avg >= 4.5) cntRatedSets++; } }); var rankValue = rank[2]; var nextRank = rank[3]; _.each(rank, function(r){ if(cntRatedSets >= r) { if(rank[_.indexOf(_.values(rank), r)] > nextRank) nextRank = rank[_.indexOf(_.values(rank), r)]; rankValue = _.indexOf(_.values(rank), r)+1; issueBadge(badge, owner, sessionID, rankValue, cntRatedSets); } }); setBadgeProgress(badge, owner, cntRatedSets, nextRank); } else { setBadgeProgress(badge, owner, 0, rank[3]); } }); } }); } }); } var checkBadgeStreber = function(owner, sessionID) { var badge = "badge/streber"; var username = owner; db.get(badge, function(err, body) { if (!err) { var rank = body.rank; db.view('cards', 'personal_card_by_owner', { startkey: new Array(username), endkey: new Array(username, {}) }, function(err, body) { if(!err && !_.isUndefined(body.rows) && _.size(body.rows) > 0) { var cards = _.filter(body.rows, function(row){ return row.key[2] == 0; }); var setIds = new Array(); _.each(cards, function(card){ var persCard = _.filter(body.rows, function(row){ return ((row.key[2] == 1) && (row.value.cardId == card.value._id)); }); if(!_.isUndefined(persCard) && !_.isEmpty(persCard)) { setIds.push(card.value.setId); } }, this); setIds = _.uniq(setIds); var setKeys = new Array(); _.each(setIds, function(id){ setKeys.push(new Array(id)); }) db.view('cards', 'by_set', { keys: setKeys }, function(err, body) { if (!err) { var docs = _.map(body.rows, function(doc) { return doc.value}); var cards = _.groupBy(docs, "setId"); var cardIds = _.pluck(docs, "_id"); var learnedCards = 0; var keys = new Array(); _.each(cardIds, function(id){ keys.push(new Array(id)); }); db.view('cards', 'personal_card_by_cardId', { keys: keys}, function(err, body) { if (!err) { var docs = _.map(body.rows, function(doc) { return doc.value}); var learnedCards = new Array(); _.each(docs, function(doc){ if(doc.times_learned >= 1) learnedCards.push(doc); }); var sets = _.groupBy(learnedCards, "setId"); if(_.has(sets, "undefined")) delete sets.undefined; var completeLearnedSets = 0; _.each(_.keys(sets), function(set){ if(_.size(sets[set]) == _.size(cards[set])) completeLearnedSets++; }); var rankValue = rank[2]; var nextRank = rank[3]; _.each(rank, function(r){ if(completeLearnedSets >= r) { if(rank[_.indexOf(_.values(rank), r)] > nextRank) nextRank = rank[_.indexOf(_.values(rank), r)]; rankValue = _.indexOf(_.values(rank), r)+1; issueBadge(badge, owner, sessionID, rankValue, completeLearnedSets); } }); setBadgeProgress(badge, owner, completeLearnedSets, nextRank); } }); } }); } }); } }); } var checkBadgeKritiker = function(owner, sessionID) { var badge = "badge/kritiker"; db.get(badge, function(err, body) { if (!err) { var rank = body.rank; db.view('rating', 'by_owner', { startkey: new Array(owner), endkey: new Array(owner) }, function(err, body) { var sets = _.pluck(body.rows, "value"); sets = _.filter(sets, function(set){ if(_.has(set, "comment")) { return set.comment.length >= 60; } else { return false; } }); var nextRank = rank[2]; var nextRank = rank[3]; _.each(rank, function(r){ if(sets.length >= r) { if(rank[_.indexOf(_.values(rank), r)] > nextRank) nextRank = rank[_.indexOf(_.values(rank), r)]; rankValue = _.indexOf(_.values(rank), r)+1; issueBadge(badge, owner, sessionID, rankValue, sets.length); } setBadgeProgress(badge, owner, sets.length, nextRank); }); }); } }); } app.get('/badges/issuer', function(req, res) { res.json({ name : "THM - Technische Hochschule Mittelhessen", url : "http://www.thm.de/" }); }); app.get('/badges/badge/:badge/:rank.json', function(req, res) { var badge = "badge/"+req.params.badge; var rank = req.params.rank; var badgeUrl = nconf.get("badge_url"); db.get(badge, function(err, badge){ if(!err) { var badgeClass = {}; var rankStr = "Gold"; if(rank == 3) rankStr = "Bronze"; if(rank == 2) rankStr = "Silber"; badgeClass.name = badge.name + " (" + rankStr + ")"; badgeClass.description = badge.description; badgeClass.image = badgeUrl + "/" + badge._id + "_" + rank + ".png"; badgeClass.criteria = badgeUrl + "/" + badge._id + ".html"; badgeClass.issuer = badgeUrl + "issuer"; res.json(badgeClass); } else { console.log(err); res.send(404); } }); }); app.get('/badges/badge/:badge:rank.html', function(req, res) { res.json({ everything: "cool html" }); }); app.get('/syncbadges', ensureAuthenticated, function(req, res) { var user = req.session.passport.user; if(_.isArray(user)) user = _.first(req.session.passport.user); var badgesToIssue = new Array(); var badgeUrl = nconf.get("badge_url"); db.view("issuedBadge", "by_owner", { keys: new Array(user.username) }, function(err, body) { if(!_.isUndefined(body.rows) && !err && _.size(body.rows) > 0 && user.email != null) { var issuedBadges = _.sortBy(_.pluck(body.rows, "value"), function(badge) { return badge.rank; }); db.view("users", "by_username", { keys: new Array(user.username) }, function(err, body) { if(!err && _.size(body.rows) > 0) { var user = _.first(body.rows).value; _.each(issuedBadges, function(badge){ var data = {}; data.uid = badge._id; data.recipient = { type: "email", hashed: false, identity: user.email }; data.image = badgeUrl + badge.badge + "_" + badge.rank + ".png"; data.evidence = badgeUrl + badge.badge + ".html"; data.issuedOn = badge.issuedOn; data.badge = badgeUrl + badge.badge + "/" + badge.rank + ".json"; data.verify = { type: "signed", url: badgeUrl + "public.pem" }; var signature = jws.sign({ header: { alg: 'rs256'}, payload: data, secret: fs.readFileSync('private.pem') }); badgesToIssue.push(signature); }); res.json(badgesToIssue); } }); } else { res.send(404); } }); }); if(process.env.NODE_ENV === 'production') { process.on('uncaughtException', function (err) { console.log(err); process.exit(1); }); https_server.listen(443, function(){ console.log("https_server listening on port " + 443); }); } http_server.listen(app.get("port"), function(){ console.log("http_server listening on port " + app.get("port")); });
/* --- name: "App.Behaviors" description: "DEPRECATED" license: - "[GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php)" - "[MIT License](http://opensource.org/licenses/mit-license.php)" authors: - "Shock <shocksilien@gmail.com>" requires: - LibCanvas provides: App.Behaviors ... */ /** @class App.Behaviors */ var Behaviors = declare( 'LibCanvas.App.Behaviors', { behaviors: {}, initialize: function (element) { this.element = element; this.behaviors = {}; }, /** @param [handler=false] */ getMouse: function (handler) { return this.element.layer.app.resources.get( handler ? 'mouseHandler' : 'mouse' ); }, add: function (Behaviour, args) { if (typeof Behaviour == 'string') { Behaviour = this.constructor[Behaviour]; } return this.behaviors[Behaviour.index] = new Behaviour(this, slice.call( arguments, 1 )); }, get: function (name) { return this.behaviors[name] || null; }, startAll: function (arg) { this.invoke('start', arguments); return this; }, stopAll: function () { this.invoke('stop', arguments); return this; }, /** @private */ invoke: function (method, args) { var i, b = this.behaviors; for (i in b) if (b.hasOwnProperty(i)) { b[i][method].apply(b[i], args); } return this; } }).own({ attach: function (target, types, arg) { target.behaviors = new Behaviors(target); types.forEach(function (type) { target.behaviors.add(type, arg); }); return target.behaviors; } }); declare( 'LibCanvas.App.Behaviors.Behavior', { started: false, /** @private */ eventArgs: function (args, eventName) { if (atom.core.isFunction(args[0])) { this.events.add( eventName, args[0] ); } }, /** @private */ changeStatus: function (status){ if (this.started == status) { return false; } else { this.started = status; return true; } } });
// import axios from 'axios' import EditableTextInput from './EditableTextInput' export default class EditableUrlInput { constructor (element) { this.element = element this.endpoint = this.element.dataset.endpoint this.url = this.element.dataset.url this.anchor = this.element.querySelector('a') const urlInput = this.element.querySelector('input') this.urlInput = new EditableTextInput(urlInput) this.urlInput.subscribeToSaved(this.onInputSave.bind(this)) return this } onInputSave (err) { if (err) console.error(err) else { this.anchor.setAttribute('href', this.urlInput.getValue()) } } }
import competitions from './competitions'; import auth from './auth'; import users from './users'; import leagues from './leagues'; import bets from './bets'; import info from './info'; export { competitions, auth, users, leagues, bets, info };
d3.json('/data/weekly.json', function(data) { nv.addGraph(function() { var chart = nv.models.stackedAreaChart() .margin({right: 100}) .x(function(d) { return d[0] }) //We can modify the data accessor functions... .y(function(d) { return d[1]*100 }) //...in case your data is formatted differently. .useInteractiveGuideline(false) //Tooltips which show all data points. Very nice! .rightAlignYAxis(true) //Let's move the y-axis to the right side. // .transitionDuration(500) .showControls(true) //Allow user to choose 'Stacked', 'Stream', 'Expanded' mode. .clipEdge(true); chart.xAxis .tickValues([1401595200000, 1404187200000, 1406865600000, 1409544000000, 1412136000000, 1414814400000, 1417410000000, 1420088400000, 1422766800000, 1425186000000, 1427860800000, 1430452800000, 1433131200000]) .tickFormat(function(d) { return d3.time.format('%b-%Y')(new Date(d)) }); chart.yAxis .tickFormat(d3.format('$,f')); d3.select('#chart4 svg') .datum(data) .call(chart); nv.utils.windowResize(chart.update); return chart; }); })
/* ======================================================================== * STAN Utils: Stan * Author: Andrew Womersley * ======================================================================== */ (function($STAN, CustomConfig) { 'use strict'; var Tag = !!CustomConfig.tag ? CustomConfig.tag : 'body'; var Config = { xs: { min_width: 0, classes: 'device-xs mobile', data: { mobile: true, desktop: false } }, sm: { min_width: 768, classes: 'device-sm mobile', data: { mobile: true, desktop: false } }, md: { min_width: 992, classes: 'device-md desktop', data: { mobile: false, desktop: true } }, lg: { min_width: 1200, classes: 'device-lg desktop', data: { mobile: false, desktop: true } } }; // Merge Config with CustomConfig for (var i in Config) { if (typeof CustomConfig[i] === 'object') Config[i] = $.extend(Config[i], CustomConfig[i]); } // Set Max Widths Config.xs.max_width = Config.sm.min_width; Config.sm.max_width = Config.md.min_width; Config.md.max_width = Config.lg.min_width; Config.lg.max_width = 9999; var _STAN = function() { //deferTrigger var device; var current_device; var triggers = []; var x; var bp; var ww; var wh; // Loop through breakpoints - reset data for (device in Config) { bp = Config[device]; // Remove classes - moved below $(Tag).removeClass(bp.classes); // Remove data attributes for (x in bp.data) $STAN[x] = false; } current_device = $STAN.device; // Loop through breakpoints - set data for (device in Config) { bp = Config[device]; ww = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); wh = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); $STAN.windowWidth = ww; $STAN.windowHeight = wh; if (bp.min_width <= ww && ww < bp.max_width) { // Add class $(Tag).addClass(bp.classes); if (current_device != device) triggers.push({ type: 'active', device: device }); // Add attributes $STAN.device = device; $STAN.classes = bp.classes; for (x in bp.data) $STAN[x] = bp.data[x]; } else { if (current_device == device) triggers.push({ type: 'deactive', device: device }); } } $STAN.Tag = Tag; // Init triggers for (var i in triggers) { var trigger = triggers[i]; $STAN.trigger('breakpoint.' + trigger.type, trigger.device); } }; var _STAN_Resize = function() { var ww = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); var wh = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); if (ww != $STAN.windowWidth || wh != $STAN.windowHeight) { _STAN(); $STAN.trigger('window.resize'); } }; // Set resize listener var timer; $(window).on('resize orientationchange', function() { window.clearTimeout(timer); timer = window.setTimeout(_STAN_Resize, 100); }); // Run _STAN(); })($STAN, ((typeof $STAN_Config === 'undefined') ? [] : $STAN_Config));
export function initialize(registry, application) { application.inject('route', 'ieCheck', 'service:ie-check'); application.inject('router:main', 'ieCheck', 'service:ie-check'); application.inject('controller', 'ieCheck', 'service:ie-check'); } export default { name: 'ie-check', initialize: initialize };
var path = require('path'); var appRoot = 'src/'; var outputRoot = 'dist/'; module.exports = { root: appRoot, source: appRoot + '**/*.ts', html: appRoot + '**/*.html', css: appRoot + '**/*.css', style: 'styles/**/*.css', output: outputRoot, doc:'./doc', e2eSpecsSrc: 'test/e2e/src/*.js', e2eSpecsDist: 'test/e2e/dist/' };
'use strict'; angular.module('raml') .value('snippets', { options: ['options:', ' description: <<insert text or markdown here>>'], head: ['head:', ' description: <<insert text or markdown here>>'], get: ['get:', ' description: <<insert text or markdown here>>'], post: ['post:', ' description: <<insert text or markdown here>>'], put: ['put:', ' description: <<insert text or markdown here>>'], delete: ['delete:', ' description: <<insert text or markdown here>>'], trace: ['trace:', ' description: <<insert text or markdown here>>'], connect: ['connect:', ' description: <<insert text or markdown here>>'], patch: ['patch:', ' description: <<insert text or markdown here>>'], '<resource>': ['/newResource:', ' displayName: resourceName'], title: ['title: My API'], version: ['version: v0.1'], baseuri: ['baseUri: http://server/api/{version}'] }) .factory('ramlSnippets', function (snippets) { var service = {}; service.getEmptyRaml = function () { return [ '#%RAML 0.8', 'title:' ].join('\n'); }; service.getSnippet = function getSnippet(suggestion) { var key = suggestion.key; var metadata = suggestion.metadata || {}; var snippet = snippets[key.toLowerCase()]; if (snippet) { return snippet; } if (metadata.isText) { //For text elements that are part of an array //we do not add an empty line break: return suggestion.isList ? [key] : [key, '']; } return [ key + ':' ]; }; return service; });
/* * * SettingsPage * */ import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import { FormattedMessage } from 'react-intl'; import { createStructuredSelector } from 'reselect'; import makeSelectSettingsPage from './selectors'; import messages from './messages'; import { logout } from 'containers/App/actions'; import CenterDiv from 'components/CenterDiv'; import LocaleToggle from 'containers/LocaleToggle'; import RaisedButton from 'material-ui/RaisedButton' export class SettingsPage extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <section> <CenterDiv> <Helmet title="SettingsPage" meta={[ { name: 'description', content: 'Settings Page' }, ]} /> <div> <LocaleToggle /> <RaisedButton style={{margin: '10px'}} type="button" onClick={this.props.askLogout} label={<FormattedMessage {...messages.logout} />} secondary /> </div> </CenterDiv> </section> ); } } SettingsPage.propTypes = { askLogout: PropTypes.func.isRequired, }; const mapStateToProps = createStructuredSelector({ SettingsPage: makeSelectSettingsPage(), }); function mapDispatchToProps(dispatch) { return { askLogout: (evt) => dispatch(logout()), }; } export default connect(mapStateToProps, mapDispatchToProps)(SettingsPage);
'use strict'; var key = 'YOURAPIKEY' , SparkPost = require('sparkpost') , client = new SparkPost(key) , options = { id: 'TEST_ID' , data: {} }; client.templates.preview(options, function(err, res) { if (err) { console.log(err); } else { console.log(res.body); console.log('Congrats you can use our SDK!'); } });
Template.somModels.events({ 'click .load-model':function(event) { FlowRouter.go('learn', {id: FlowRouter.getParam("id")}, {m: event.target.id}); }, 'click .del-model': function(event) { Meteor.call('SOM:delete', event.target.id); }, 'submit .compute-som': function(event, instance) { console.log('called submit'); event.preventDefault(); var project = Projects.findOne({_id: FlowRouter.getParam("id"), uid: Meteor.userId()}); var labelEnum = []; project.labels.forEach(function(label) { var enabled = event.target['label-' + label.tag].checked; if (enabled) { labelEnum.push({tag: label.tag, id: label.id, color: label.color}); } }); var props = { labels: labelEnum, gridSize: +event.target.gridSize.value, learningRate: +event.target.learning_rate.value, steps: +event.target.steps.value, lvq: event.target.lvq.checked, description: event.target.description.value } var projectId = FlowRouter.getParam("id"); var balance = event.target.balance.checked; if (event.target.cv.checked) { Meteor.call('SOM:cross-validate', projectId, props, balance); M.toast({html: 'Running cross validation', displayLength: 2000}); } else { Meteor.call('SOM:compute', projectId, props, balance); M.toast({html: 'Model building', displayLength: 2000}); } }, }) Template.somModels.helpers({ 'isDisabled': function(status) { if (status === 100) { return ''; } return 'disabled'; }, 'labels': function() { project = Projects.findOne({_id: FlowRouter.getParam("id"), uid: Meteor.userId()}); return project.labels; }, 'models':function() { return SOM.find({projectId: FlowRouter.getParam("id")}); }, 'round': function(number) { return number.toFixed(2); }, 'crumbs': function() { var project = Projects.findOne({_id: FlowRouter.getParam("id"), uid: Meteor.userId()}); return [ { path: '/projects', title: 'Projects' }, { path: '/projects/' + FlowRouter.getParam("id"), title: project.name }, { path: '/projects/' + FlowRouter.getParam("id") + '/models', title: 'Machine Learning' } ] }, })
#!/usr/bin/env node-canvas /*jslint indent: 2, node: true */ "use strict"; var Canvas = require('../lib/canvas'); var canvas = new Canvas(320, 320); var ctx = canvas.getContext('2d'); var fs = require('fs'); var eu = require('./util'); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.scale(3, 3); // Create gradients var lingrad = ctx.createLinearGradient(0, 0, 0, 150); lingrad.addColorStop(0, '#00ABEB'); lingrad.addColorStop(0.5, '#fff'); lingrad.addColorStop(0.5, '#26C000'); lingrad.addColorStop(1, '#fff'); var lingrad2 = ctx.createLinearGradient(0, 50, 0, 95); lingrad2.addColorStop(0.5, '#000'); lingrad2.addColorStop(1, 'rgba(0,0,0,0)'); // assign gradients to fill and stroke styles ctx.fillStyle = lingrad; ctx.strokeStyle = lingrad2; // draw shapes ctx.fillRect(10, 10, 130, 130); ctx.strokeRect(50, 50, 50, 50); // Default gradient stops ctx.fillStyle = '#008000'; ctx.fillRect(150, 0, 150, 150); lingrad = ctx.createLinearGradient(150, 0, 300, 150); ctx.fillStyle = lingrad; ctx.fillRect(160, 10, 130, 130); // Radial gradients ctx.fillStyle = '#a00000'; ctx.fillRect(0, 150, 150, 150); lingrad = ctx.createRadialGradient(30, 180, 50, 30, 180, 100); lingrad.addColorStop(0, '#00ABEB'); lingrad.addColorStop(0.5, '#fff'); lingrad.addColorStop(0.5, '#26C000'); lingrad.addColorStop(1, '#fff'); ctx.fillStyle = lingrad; ctx.fillRect(10, 160, 130, 130); canvas.vgSwapBuffers(); eu.handleTermination(); eu.waitForInput();
'use strict'; exports.generateAppleScript = dir => { const terminalCommand = `tell application "Terminal" do script "cd ${dir}" in front window end tell`.split('\n').map(line => (` -e '${line.trim()}'`)).join(''); const iTermCommand = `tell application "iTerm" tell current session of current window write text "cd ${dir}" end tell end tell`.split('\n').map(line => (` -e '${line.trim()}'`)).join(''); const currentApp = `tell application "System Events" set activeApp to name of first application process whose frontmost is true end tell`.split('\n').map(line => (` -e '${line.trim()}'`)).join(''); return `[ \`osascript ${currentApp}\` = "Terminal" ] && osascript ${terminalCommand} >/dev/null || osascript ${iTermCommand}`; };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { sources: 'https://newsapi.org/v1/sources', articles: 'https://newsapi.org/v1/articles' };
'use strict'; /** * @ngdoc module * @name ngAria * @description * * The `ngAria` module provides support for common * [<abbr title="Accessible Rich Internet Applications">ARIA</abbr>](http://www.w3.org/TR/wai-aria/) * attributes that convey state or semantic information about the application for users * of assistive technologies, such as screen readers. * * ## Usage * * For ngAria to do its magic, simply include the module `ngAria` as a dependency. The following * directives are supported: * `ngModel`, `ngChecked`, `ngReadonly`, `ngRequired`, `ngValue`, `ngDisabled`, `ngShow`, `ngHide`, * `ngClick`, `ngDblClick`, and `ngMessages`. * * Below is a more detailed breakdown of the attributes handled by ngAria: * * | Directive | Supported Attributes | * |---------------------------------------------|-----------------------------------------------------------------------------------------------------| * | {@link ng.directive:ngModel ngModel} | aria-checked, aria-valuemin, aria-valuemax, aria-valuenow, aria-invalid, aria-required, input roles | * | {@link ng.directive:ngDisabled ngDisabled} | aria-disabled | * | {@link ng.directive:ngRequired ngRequired} | aria-required | * | {@link ng.directive:ngChecked ngChecked} | aria-checked | * | {@link ng.directive:ngReadonly ngReadonly} | aria-readonly | * | {@link ng.directive:ngValue ngValue} | aria-checked | * | {@link ng.directive:ngShow ngShow} | aria-hidden | * | {@link ng.directive:ngHide ngHide} | aria-hidden | * | {@link ng.directive:ngDblclick ngDblclick} | tabindex | * | {@link module:ngMessages ngMessages} | aria-live | * | {@link ng.directive:ngClick ngClick} | tabindex, keydown event, button role | * * Find out more information about each directive by reading the * {@link guide/accessibility ngAria Developer Guide}. * * ## Example * Using ngDisabled with ngAria: * ```html * <md-checkbox ng-disabled="disabled"> * ``` * Becomes: * ```html * <md-checkbox ng-disabled="disabled" aria-disabled="true"> * ``` * * ## Disabling Specific Attributes * It is possible to disable individual attributes added by ngAria with the * {@link ngAria.$ariaProvider#config config} method. For more details, see the * {@link guide/accessibility Developer Guide}. * * ## Disabling `ngAria` on Specific Elements * It is possible to make `ngAria` ignore a specific element, by adding the `ng-aria-disable` * attribute on it. Note that only the element itself (and not its child elements) will be ignored. */ var ARIA_DISABLE_ATTR = 'ngAriaDisable'; var ngAriaModule = angular.module('ngAria', ['ng']). info({ angularVersion: '"NG_VERSION_FULL"' }). provider('$aria', $AriaProvider); /** * Internal Utilities */ var nodeBlackList = ['BUTTON', 'A', 'INPUT', 'TEXTAREA', 'SELECT', 'DETAILS', 'SUMMARY']; var isNodeOneOf = function(elem, nodeTypeArray) { if (nodeTypeArray.indexOf(elem[0].nodeName) !== -1) { return true; } }; /** * @ngdoc provider * @name $ariaProvider * @this * * @description * * Used for configuring the ARIA attributes injected and managed by ngAria. * * ```js * angular.module('myApp', ['ngAria'], function config($ariaProvider) { * $ariaProvider.config({ * ariaValue: true, * tabindex: false * }); * }); *``` * * ## Dependencies * Requires the {@link ngAria} module to be installed. * */ function $AriaProvider() { var config = { ariaHidden: true, ariaChecked: true, ariaReadonly: true, ariaDisabled: true, ariaRequired: true, ariaInvalid: true, ariaValue: true, tabindex: true, bindKeydown: true, bindRoleForClick: true }; /** * @ngdoc method * @name $ariaProvider#config * * @param {object} config object to enable/disable specific ARIA attributes * * - **ariaHidden** – `{boolean}` – Enables/disables aria-hidden tags * - **ariaChecked** – `{boolean}` – Enables/disables aria-checked tags * - **ariaReadonly** – `{boolean}` – Enables/disables aria-readonly tags * - **ariaDisabled** – `{boolean}` – Enables/disables aria-disabled tags * - **ariaRequired** – `{boolean}` – Enables/disables aria-required tags * - **ariaInvalid** – `{boolean}` – Enables/disables aria-invalid tags * - **ariaValue** – `{boolean}` – Enables/disables aria-valuemin, aria-valuemax and * aria-valuenow tags * - **tabindex** – `{boolean}` – Enables/disables tabindex tags * - **bindKeydown** – `{boolean}` – Enables/disables keyboard event binding on non-interactive * elements (such as `div` or `li`) using ng-click, making them more accessible to users of * assistive technologies * - **bindRoleForClick** – `{boolean}` – Adds role=button to non-interactive elements (such as * `div` or `li`) using ng-click, making them more accessible to users of assistive * technologies * * @description * Enables/disables various ARIA attributes */ this.config = function(newConfig) { config = angular.extend(config, newConfig); }; function watchExpr(attrName, ariaAttr, nodeBlackList, negate) { return function(scope, elem, attr) { if (attr.hasOwnProperty(ARIA_DISABLE_ATTR)) return; var ariaCamelName = attr.$normalize(ariaAttr); if (config[ariaCamelName] && !isNodeOneOf(elem, nodeBlackList) && !attr[ariaCamelName]) { scope.$watch(attr[attrName], function(boolVal) { // ensure boolean value boolVal = negate ? !boolVal : !!boolVal; elem.attr(ariaAttr, boolVal); }); } }; } /** * @ngdoc service * @name $aria * * @description * @priority 200 * * The $aria service contains helper methods for applying common * [ARIA](http://www.w3.org/TR/wai-aria/) attributes to HTML directives. * * ngAria injects common accessibility attributes that tell assistive technologies when HTML * elements are enabled, selected, hidden, and more. To see how this is performed with ngAria, * let's review a code snippet from ngAria itself: * *```js * ngAriaModule.directive('ngDisabled', ['$aria', function($aria) { * return $aria.$$watchExpr('ngDisabled', 'aria-disabled', nodeBlackList, false); * }]) *``` * Shown above, the ngAria module creates a directive with the same signature as the * traditional `ng-disabled` directive. But this ngAria version is dedicated to * solely managing accessibility attributes on custom elements. The internal `$aria` service is * used to watch the boolean attribute `ngDisabled`. If it has not been explicitly set by the * developer, `aria-disabled` is injected as an attribute with its value synchronized to the * value in `ngDisabled`. * * Because ngAria hooks into the `ng-disabled` directive, developers do not have to do * anything to enable this feature. The `aria-disabled` attribute is automatically managed * simply as a silent side-effect of using `ng-disabled` with the ngAria module. * * The full list of directives that interface with ngAria: * * **ngModel** * * **ngChecked** * * **ngReadonly** * * **ngRequired** * * **ngDisabled** * * **ngValue** * * **ngShow** * * **ngHide** * * **ngClick** * * **ngDblclick** * * **ngMessages** * * Read the {@link guide/accessibility ngAria Developer Guide} for a thorough explanation of each * directive. * * * ## Dependencies * Requires the {@link ngAria} module to be installed. */ this.$get = function() { return { config: function(key) { return config[key]; }, $$watchExpr: watchExpr }; }; } ngAriaModule.directive('ngShow', ['$aria', function($aria) { return $aria.$$watchExpr('ngShow', 'aria-hidden', [], true); }]) .directive('ngHide', ['$aria', function($aria) { return $aria.$$watchExpr('ngHide', 'aria-hidden', [], false); }]) .directive('ngValue', ['$aria', function($aria) { return $aria.$$watchExpr('ngValue', 'aria-checked', nodeBlackList, false); }]) .directive('ngChecked', ['$aria', function($aria) { return $aria.$$watchExpr('ngChecked', 'aria-checked', nodeBlackList, false); }]) .directive('ngReadonly', ['$aria', function($aria) { return $aria.$$watchExpr('ngReadonly', 'aria-readonly', nodeBlackList, false); }]) .directive('ngRequired', ['$aria', function($aria) { return $aria.$$watchExpr('ngRequired', 'aria-required', nodeBlackList, false); }]) .directive('ngModel', ['$aria', function($aria) { function shouldAttachAttr(attr, normalizedAttr, elem, allowBlacklistEls) { return $aria.config(normalizedAttr) && !elem.attr(attr) && (allowBlacklistEls || !isNodeOneOf(elem, nodeBlackList)) && (elem.attr('type') !== 'hidden' || elem[0].nodeName !== 'INPUT'); } function shouldAttachRole(role, elem) { // if element does not have role attribute // AND element type is equal to role (if custom element has a type equaling shape) <-- remove? // AND element is not in nodeBlackList return !elem.attr('role') && (elem.attr('type') === role) && !isNodeOneOf(elem, nodeBlackList); } function getShape(attr, elem) { var type = attr.type, role = attr.role; return ((type || role) === 'checkbox' || role === 'menuitemcheckbox') ? 'checkbox' : ((type || role) === 'radio' || role === 'menuitemradio') ? 'radio' : (type === 'range' || role === 'progressbar' || role === 'slider') ? 'range' : ''; } return { restrict: 'A', require: 'ngModel', priority: 200, //Make sure watches are fired after any other directives that affect the ngModel value compile: function(elem, attr) { if (attr.hasOwnProperty(ARIA_DISABLE_ATTR)) return; var shape = getShape(attr, elem); return { post: function(scope, elem, attr, ngModel) { var needsTabIndex = shouldAttachAttr('tabindex', 'tabindex', elem, false); function ngAriaWatchModelValue() { return ngModel.$modelValue; } function getRadioReaction(newVal) { // Strict comparison would cause a BC // eslint-disable-next-line eqeqeq var boolVal = (attr.value == ngModel.$viewValue); elem.attr('aria-checked', boolVal); } function getCheckboxReaction() { elem.attr('aria-checked', !ngModel.$isEmpty(ngModel.$viewValue)); } switch (shape) { case 'radio': case 'checkbox': if (shouldAttachRole(shape, elem)) { elem.attr('role', shape); } if (shouldAttachAttr('aria-checked', 'ariaChecked', elem, false)) { scope.$watch(ngAriaWatchModelValue, shape === 'radio' ? getRadioReaction : getCheckboxReaction); } if (needsTabIndex) { elem.attr('tabindex', 0); } break; case 'range': if (shouldAttachRole(shape, elem)) { elem.attr('role', 'slider'); } if ($aria.config('ariaValue')) { var needsAriaValuemin = !elem.attr('aria-valuemin') && (attr.hasOwnProperty('min') || attr.hasOwnProperty('ngMin')); var needsAriaValuemax = !elem.attr('aria-valuemax') && (attr.hasOwnProperty('max') || attr.hasOwnProperty('ngMax')); var needsAriaValuenow = !elem.attr('aria-valuenow'); if (needsAriaValuemin) { attr.$observe('min', function ngAriaValueMinReaction(newVal) { elem.attr('aria-valuemin', newVal); }); } if (needsAriaValuemax) { attr.$observe('max', function ngAriaValueMinReaction(newVal) { elem.attr('aria-valuemax', newVal); }); } if (needsAriaValuenow) { scope.$watch(ngAriaWatchModelValue, function ngAriaValueNowReaction(newVal) { elem.attr('aria-valuenow', newVal); }); } } if (needsTabIndex) { elem.attr('tabindex', 0); } break; } if (!attr.hasOwnProperty('ngRequired') && ngModel.$validators.required && shouldAttachAttr('aria-required', 'ariaRequired', elem, false)) { // ngModel.$error.required is undefined on custom controls attr.$observe('required', function() { elem.attr('aria-required', !!attr['required']); }); } if (shouldAttachAttr('aria-invalid', 'ariaInvalid', elem, true)) { scope.$watch(function ngAriaInvalidWatch() { return ngModel.$invalid; }, function ngAriaInvalidReaction(newVal) { elem.attr('aria-invalid', !!newVal); }); } } }; } }; }]) .directive('ngDisabled', ['$aria', function($aria) { return $aria.$$watchExpr('ngDisabled', 'aria-disabled', nodeBlackList, false); }]) .directive('ngMessages', function() { return { restrict: 'A', require: '?ngMessages', link: function(scope, elem, attr, ngMessages) { if (attr.hasOwnProperty(ARIA_DISABLE_ATTR)) return; if (!elem.attr('aria-live')) { elem.attr('aria-live', 'assertive'); } } }; }) .directive('ngClick',['$aria', '$parse', function($aria, $parse) { return { restrict: 'A', compile: function(elem, attr) { if (attr.hasOwnProperty(ARIA_DISABLE_ATTR)) return; var fn = $parse(attr.ngClick); return function(scope, elem, attr) { if (!isNodeOneOf(elem, nodeBlackList)) { if ($aria.config('bindRoleForClick') && !elem.attr('role')) { elem.attr('role', 'button'); } if ($aria.config('tabindex') && !elem.attr('tabindex')) { elem.attr('tabindex', 0); } if ($aria.config('bindKeydown') && !attr.ngKeydown && !attr.ngKeypress && !attr.ngKeyup) { elem.on('keydown', function(event) { var keyCode = event.which || event.keyCode; if (keyCode === 13 || keyCode === 32) { // If the event is triggered on a non-interactive element ... if (nodeBlackList.indexOf(event.target.nodeName) === -1) { // ... prevent the default browser behavior (e.g. scrolling when pressing spacebar) // See https://github.com/angular/angular.js/issues/16664 event.preventDefault(); } scope.$apply(callback); } function callback() { fn(scope, { $event: event }); } }); } } }; } }; }]) .directive('ngDblclick', ['$aria', function($aria) { return function(scope, elem, attr) { if (attr.hasOwnProperty(ARIA_DISABLE_ATTR)) return; if ($aria.config('tabindex') && !elem.attr('tabindex') && !isNodeOneOf(elem, nodeBlackList)) { elem.attr('tabindex', 0); } }; }]);
import React, { Component } from 'react'; import { connect } from 'react-redux'; const mapStateToProps = (state) => { return { teachers: state.adminReducer.teachers }; }; class TeachersDropdown extends Component { constructor(props) { super(props); this.state = { selectedTeacherId: null }; this.updateSelectedTeacher = this.updateSelectedTeacher.bind(this); } render() { return ( <div> <span className='signup-form-label'>Grade/Type</span> <div className='admin-select-wrapper'> <span className='admin-select-arrow'> <i className='material-icons'>keyboard_arrow_down</i> </span> <select className='admin-form-select' value={this.state.selectedTeacherId} onChange={this.updateSelectedTeacher} > <option>Select a teacher</option> {this.props.teachers.map(teacher => { return (<option key={teacher.id} value={teacher.id}>{teacher.user.name}</option>); })} </select> </div> </div> ); } updateSelectedTeacher(e) { const value = parseInt(e.target.value); this.setState({ selectedTeacherId: value }, (state) => { this.props.notifyParentForm(this.state.selectedTeacherId); }); } } export default connect(mapStateToProps, function() { return {}})(TeachersDropdown);
var system = require('system'); if (system.args.length === 1) { console.log('Try to pass some args when invoking this script'); phantom.exit(0); } else { system.args.forEach(function (arg, i, array) { console.log(i + ': ' + arg + ' [' + array + ']'); }); phantom.exit(0); }
var gulp = require('gulp'); var del = require('del'); var gulp_less = require('gulp-less'); var concat = require('gulp-concat'); var uglify = require('gulp-uglify'); var minifyCSS = require('gulp-minify-css'); var coffee = require("gulp-coffee"); var ngAnnotate = require('gulp-ng-annotate'); var gutil = require('gulp-util'); var rev = require('gulp-rev'); var gulpif = require('gulp-if'); var SprocketsChain = require("sprockets-chain"); var recess = require('gulp-recess'); var isCoffee = function(file) { return file.path.indexOf(".coffee") > -1 } var isLess = function(file) { return file.path.indexOf(".less") > -1 } var needsMinify = function(file) { return file.path.indexOf(".min") < 0 } gulp.task('clean', function(cb) { del([ 'public/assets/build/*', 'public/assets/*.css', 'public/assets/*.js', 'public/assets/*.json' ], { dot: true }, cb); }); gulp.task('build_application_css', function() { var sc = new SprocketsChain(); sc.appendPath("app/assets/stylesheets"); sc.appendPath("vendor/assets/components"); var chain = sc.depChain("application.css"); return gulp.src(chain) .pipe(concat('application.less')) .pipe(gulpif(isLess, gulp_less().on('error', gutil.log))) .pipe(minifyCSS({ keepBreaks: false, debugger: true }).on('error', gutil.log)) .pipe(gulp.dest('./public/assets/build')); }); gulp.task('build_vendor_css', function() { var sc = new SprocketsChain(); sc.appendPath("app/assets/stylesheets"); sc.appendPath("vendor/assets/stylesheets"); sc.appendPath("vendor/assets/components"); var chain = sc.depChain("vendor.css"); return gulp.src(chain) .pipe(concat('vendor.css')) .pipe(minifyCSS({ keepBreaks: false })) .pipe(gulp.dest('./public/assets/build')); }); gulp.task('build_application_js', function() { var sc = new SprocketsChain(); sc.appendPath("app/assets/javascripts"); sc.appendPath("vendor/assets/components"); var chain = sc.depChain("application.js"); return gulp.src(chain) .pipe(gulpif(isCoffee, coffee({ bare: true }) // Compile coffeescript .on("error", gutil.log) )) .pipe(concat('application.js')) .pipe(ngAnnotate()) .pipe(uglify()) .pipe(gulp.dest('./public/assets/build')); }); gulp.task('build_vendor_js', function() { var sc = new SprocketsChain(); sc.appendPath("app/assets/javascripts"); sc.appendPath("vendor/assets/javascripts"); sc.appendPath("vendor/assets/components"); var chain = sc.depChain("vendor.js"); return gulp.src(chain) .pipe(concat('vendor.js')) .pipe(ngAnnotate()) .pipe(gulpif(needsMinify, uglify())) .pipe(gulp.dest('./public/assets/build')); }); gulp.task('compile', ['clean', 'build_application_js', 'build_vendor_js', 'build_application_css', 'build_vendor_css'], function() { return gulp.src(['public/assets/build/*.css', 'public/assets/build/*.js']) .pipe(rev()) .pipe(gulp.dest('./public/assets')) .pipe(rev.manifest()) .pipe(gulp.dest('./public/assets')); }); gulp.task('lint', function () { return gulp.src('./app/assets/stylesheets/less/dashboard.css.less') .pipe(recess()) .pipe(recess.reporter()) .pipe(gulp.dest('./public/assets/build/')); }); gulp.task('default', ['compile'])
const Backbone = require('backbone'); require('backbone.marionette'); const Template = require('ui/template/loader.hbs'); module.exports = Backbone.Marionette.View.extend({ template: Template, modelEvents: { 'change:isLoading': 'render' } });
module.exports = { autoRoutesEnabled: true, clusteringEnabled: false, compressionEnabled: true, requestLimitKB: 5120, keepAliveTimeoutSeconds: 30, includeErrorStackInResponse: true, viewEngine: 'ejs', controllerPath: './controllers', controllerSuffix: '-controller', controllerType: 'mvc', viewPath: './views', modelPath: './models', requestSchemaSuffix: '-request', baseUrlPrefix: '', routes: null, requestModelMergeOrder: [ 'query', 'params', 'body' ], schemaValidation: { request: { //Ajv options http://epoberezkin.github.io/ajv/#options allErrors: false, format: 'fast', formats: {} } }, loggerAppenders: [ { type: "Console", options: { level: "silly", timestamp: true, handleExceptions: false, json: false, colorize: true, prettyPrint: true } } ], hooks: require('./Hooks'), internalViewPath: 'views' };
// App Start. (function() { console.warn('beep…boop…beep\n%c🙇 hello world!', 'font-size: 16px'); })();
import React from 'react'; import { storiesOf } from '@storybook/react'; import Container from './Container'; import Autocomplete from 'react-widgets/lib/Autocomplete'; let generateNames = global.generateNames; let props = { data: generateNames(), valueField: 'id', textField: 'fullName', placeholder: 'type something…', } class PlacesAutoComplete extends React.Component { state = { data: [], value: '' }; autocompleteService = new window.google.maps.places.AutocompleteService(); handleChange = (value) => { this.setState({ value }) if (!value || value.placeId) return; this.setState({ busy: true }) clearTimeout(this.timer); this.timer = setTimeout(() => { this.autocompleteService .getPlacePredictions({ input: value.text || value }, (predictions) => { this.setState({ busy: false }) if (!predictions) return; this.setState({ data: predictions.map(p => ({ text: p.description, placeId: p.place_id, ...p.structured_formatting, })) }) }); }, 500) } render() { return ( <Autocomplete value={this.state.value} onChange={this.handleChange} data={this.state.data} textField="text" valueField="placeId" busy={this.state.busy} placeholder="type to find places…" /> ) } } storiesOf('Autocomplete', module) .add('Autocomplete', () => <Container> <PlacesAutoComplete {...props} /> </Container> ) .add('busy', () => <Container> <Autocomplete {...props} busy defaultValue={props.data[1]} /> </Container> ) .add('disabled', () => <Container> <Autocomplete {...props} disabled defaultValue={props.data[1]} /> </Container> ) .add('disabled items', () => <Container> <Autocomplete {...props} open disabled={[props.data[2]]} defaultValue={props.data[1]} /> </Container> ) .add('disabled item, first focused', () => <Container> <Autocomplete {...props} open disabled={props.data.slice(0, 2)} /> </Container> ) .add('readOnly', () => <Container> <Autocomplete {...props} readOnly defaultValue={props.data[1]} /> </Container> ) .add('right to left', () => <Container> <Autocomplete {...props} isRtl defaultValue={props.data[1]} /> </Container> )
const authEvents = require('./events/auth') const contentEvents = require('./events/content') const preferenceEvents = require('./events/preference') const googlePhotosEvents = require('./events/google-photos') const googleAnalyticsEvents = require('./events/google-analytics') module.exports.init = () => { authEvents() contentEvents() preferenceEvents() googlePhotosEvents() googleAnalyticsEvents() }
// Export // ====== var example = { ip: '88.72.237.61', klab: { data : { lat : 52.5167, lng : 13.4, name : 'KLab-Berlin', details : 'Immer am Unterrichten' }, info : { type : 'Cluster', id : '42', city : 'Berlin/Würzburg', area : 'The Internet', country : 'Deutschland', nodes : 16 } }, spot : { // node type : 'Spot', id : 'muAPISpot01_4021_1421', ng_port : 4021, repl_port : 1421, ipv4 : '192.168.1.125', ipv6 : '123.456.7.890', city : 'Berlin', area : 'Berlin', country : 'Deutschland', memory : 20, cpu : 10, clients : 2 }, hub : { // node type : 'Hub', id : 'muAPISpot01_4021_1421', ng_port : 4021, repl_port : 1421, ipv4 : '192.168.1.125', ipv6 : '123.456.7.890', city : 'Berlin', area : 'Berlin', country : 'Deutschland', memory : 20, cpu : 10, clients : 2 }, client : { type : 'Client', id : 'vwcmu12345', ipv4 : '192.168.1.125', city : 'Würzburg', area : 'Bayern', country : 'Deutschland', email : 'a@b.de', _id : 1234, userType : 1, time : '12 min', desks : 4, documents : 18 }, cluster : { type : 'Cluster', id : 'cluster_01', city : 'Berlin', area : 'Berlin', country : 'Deutschland', nodes : 1 } }; module.exports = example;