diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000000..8b2754cd9d4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/node_modules/ +/.local-chromium/ +/.dev_profile* +.DS_Store +*.swp +*.pyc diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000000..ae319c70aca --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,23 @@ +# How to Contribute + +We'd love to accept your patches and contributions to this project. There are +just a few small guidelines you need to follow. + +## Contributor License Agreement + +Contributions to this project must be accompanied by a Contributor License +Agreement. You (or your employer) retain the copyright to your contribution, +this simply gives us permission to use and redistribute your contributions as +part of the project. Head over to to see +your current agreements on file or to sign a new one. + +You generally only need to submit a CLA once, so if you've already submitted one +(even if it was for a different project), you probably don't need to do it +again. + +## Code reviews + +All submissions, including submissions by project members, require review. We +use GitHub pull requests for this purpose. Consult +[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more +information on using pull requests. diff --git a/README.md b/README.md index 50eee758267..699aa6915f8 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,36 @@ -# puppeteer -Headless Chrome Node API +### Status + +Test results on Mac OS X in headless mode: +``` + 111 passed + 20 failed as expected + 1 skipped + 49 unsupported +``` + +### Installing + +```bash +npm i +npm link # this adds puppeteer to $PATH +``` + +### Run + +```bash +# run phantomjs script +puppeteer third_party/phantomjs/examples/colorwheel.js + +# run 'headful' +puppeteer --no-headless third_party/phantomjs/examples/colorwheel.js + +# run puppeteer example +node examples/screenshot.js +``` + +### Tests + +Run phantom.js tests using puppeteer: +``` +./third_party/phantomjs/test/run-tests.py +``` diff --git a/examples/custom-chromium-revision.js b/examples/custom-chromium-revision.js new file mode 100644 index 00000000000..e49b3f6a80f --- /dev/null +++ b/examples/custom-chromium-revision.js @@ -0,0 +1,41 @@ +/** + * Copyright 2017 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var Browser = require('../lib/Browser'); +var Downloader = require('../lib/Downloader'); + +var revision = "464642"; +console.log('Downloading custom chromium revision - ' + revision); +Downloader.downloadChromium(revision).then(async () => { + console.log('Done.'); + var executablePath = Downloader.executablePath(revision); + var browser1 = new Browser({ + remoteDebuggingPort: 9228, + executablePath, + }); + var browser2 = new Browser({ + remoteDebuggingPort: 9229, + }); + var [version1, version2] = await Promise.all([ + browser1.version(), + browser2.version() + ]); + console.log('browser1: ' + version1); + console.log('browser2: ' + version2); + browser1.close(); + browser2.close(); +}); + diff --git a/examples/screenshot.js b/examples/screenshot.js new file mode 100644 index 00000000000..51a2f69f02c --- /dev/null +++ b/examples/screenshot.js @@ -0,0 +1,27 @@ +/** + * Copyright 2017 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var Browser = require('./lib/Browser'); +var Page = require('./lib/Page'); +var fs = require('fs'); +var browser = new Browser(); + +browser.newPage().then(async page => { + await page.navigate('http://example.com'); + var screenshotBuffer = await page.screenshot(Page.ScreenshotTypes.PNG); + fs.writeFileSync('example.png', screenshotBuffer); + browser.close(); +}); diff --git a/index.js b/index.js new file mode 100755 index 00000000000..1053460736b --- /dev/null +++ b/index.js @@ -0,0 +1,60 @@ +#!/usr/bin/env node +/** + * Copyright 2017 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var vm = require('vm'); +var fs = require('fs'); +var path = require('path'); +var Browser = require('./lib/Browser'); +var argv = require('minimist')(process.argv.slice(2), { + alias: { v: 'version' }, + boolean: ['headless'], + default: {'headless': true }, +}); + +if (argv.version) { + console.log('Puppeteer v' + require('./package.json').version); + return; +} + +if (argv['ssl-certificates-path']) { + console.error('Flag --ssl-certificates-path is not currently supported.\nMore information at https://github.com/aslushnikov/puppeteer/issues/1'); + process.exit(1); + return; +} + +var scriptArguments = argv._; +if (!scriptArguments.length) { + console.log('puppeteer [scriptfile]'); + return; +} + +var scriptPath = path.resolve(process.cwd(), scriptArguments[0]); +if (!fs.existsSync(scriptPath)) { + console.error(`script not found: ${scriptPath}`); + process.exit(1); + return; +} + +var browser = new Browser({ + remoteDebuggingPort: 9229, + headless: argv.headless, +}); + +var PhatomJs = require('./phantomjs'); +var context = PhatomJs.createContext(browser, scriptPath, argv); +var scriptContent = fs.readFileSync(scriptPath, 'utf8'); +vm.runInContext(scriptContent, context); diff --git a/install.js b/install.js new file mode 100644 index 00000000000..1a0cfae017b --- /dev/null +++ b/install.js @@ -0,0 +1,32 @@ +var Downloader = require('./lib/Downloader'); +var revision = require('./package').puppeteer.chromium_revision; +var fs = require('fs'); +var ProgressBar = require('progress'); + +var executable = Downloader.executablePath(revision); +if (fs.existsSync(executable)) + return; + +Downloader.downloadChromium(revision, onProgress) + .catch(error => { + console.error('Download failed: ' + error.message); + }); + +var progressBar = null; +function onProgress(bytesTotal, delta) { + if (!progressBar) { + progressBar = new ProgressBar(`Downloading Chromium - ${toMegabytes(bytesTotal)} [:bar] :percent :etas `, { + complete: '=', + incomplete: ' ', + width: 20, + total: bytesTotal, + }); + } + progressBar.tick(delta); +} + +function toMegabytes(bytes) { + var mb = bytes / 1024 / 1024; + return (Math.round(mb * 10) / 10) + ' Mb'; +} + diff --git a/lib/Browser.js b/lib/Browser.js new file mode 100644 index 00000000000..20b09ecfa9c --- /dev/null +++ b/lib/Browser.js @@ -0,0 +1,142 @@ +/** + * Copyright 2017 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var CDP = require('chrome-remote-interface'); +var http = require('http'); +var path = require('path'); +var removeRecursive = require('rimraf').sync; +var Page = require('./Page'); +var childProcess = require('child_process'); +var Downloader = require('./Downloader'); + +var CHROME_PROFILE_PATH = path.resolve(__dirname, '..', '.dev_profile'); +var browserId = 0; + +var DEFAULT_ARGS = [ + '--disable-background-timer-throttling', + '--no-first-run', +]; + +class Browser { + /** + * @param {(!Object|undefined)} options + */ + constructor(options) { + options = options || {}; + ++browserId; + this._userDataDir = CHROME_PROFILE_PATH + browserId; + this._remoteDebuggingPort = 9229; + if (typeof options.remoteDebuggingPort === 'number') + this._remoteDebuggingPort = options.remoteDebuggingPort; + this._chromeArguments = DEFAULT_ARGS.concat([ + `--user-data-dir=${this._userDataDir}`, + `--remote-debugging-port=${this._remoteDebuggingPort}`, + ]); + if (typeof options.headless !== 'boolean' || options.headless) { + this._chromeArguments.push(...[ + `--headless`, + `--disable-gpu`, + ]); + } + if (typeof options.executablePath === 'string') { + this._chromeExecutable = options.executablePath; + } else { + var chromiumRevision = require('../package.json').puppeteer.chromium_revision; + this._chromeExecutable = Downloader.executablePath(chromiumRevision); + } + if (Array.isArray(options.args)) + this._chromeArguments.push(...options.args); + this._chromeProcess = null; + this._tabSymbol = Symbol('Browser.TabSymbol'); + } + + /** + * @return {!Promise} + */ + async newPage() { + await this._ensureChromeIsRunning(); + if (!this._chromeProcess || this._chromeProcess.killed) + throw new Error('ERROR: this chrome instance is not alive any more!'); + var tab = await CDP.New({port: this._remoteDebuggingPort}); + var client = await CDP({tab: tab, port: this._remoteDebuggingPort}); + var page = await Page.create(this, client); + page[this._tabSymbol] = tab; + return page; + } + + /** + * @param {!Page} page + */ + async closePage(page) { + if (!this._chromeProcess || this._chromeProcess.killed) + throw new Error('ERROR: this chrome instance is not running'); + var tab = page[this._tabSymbol]; + if (!tab) + throw new Error('ERROR: page does not belong to this chrome instance'); + await CDP.Close({id: tab.id, port: this._remoteDebuggingPort}); + } + + /** + * @return {string} + */ + async version() { + await this._ensureChromeIsRunning(); + var version = await CDP.Version({port: this._remoteDebuggingPort}); + return version.Browser; + } + + async _ensureChromeIsRunning() { + if (this._chromeProcess) + return; + this._chromeProcess = childProcess.spawn(this._chromeExecutable, this._chromeArguments, {}); + // Cleanup as processes exit. + process.on('exit', () => this._chromeProcess.kill()); + this._chromeProcess.on('exit', () => removeRecursive(this._userDataDir)); + + await waitForChromeResponsive(this._remoteDebuggingPort); + } + + close() { + if (!this._chromeProcess) + return; + this._chromeProcess.kill(); + } +} + +module.exports = Browser; + +function waitForChromeResponsive(remoteDebuggingPort) { + var fulfill; + var promise = new Promise(x => fulfill = x); + var options = { + method: 'GET', + host: 'localhost', + port: remoteDebuggingPort, + path: '/json/list' + }; + var probeTimeout = 100; + var probeAttempt = 1; + sendRequest(); + return promise; + + function sendRequest() { + var req = http.request(options, res => { + fulfill() + }); + req.on('error', e => setTimeout(sendRequest, probeTimeout)); + req.end(); + } +} diff --git a/lib/Downloader.js b/lib/Downloader.js new file mode 100644 index 00000000000..5b63cfefc41 --- /dev/null +++ b/lib/Downloader.js @@ -0,0 +1,123 @@ +/** + * Copyright 2017 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var os = require('os'); +var https = require('https'); +var fs = require('fs'); +var path = require('path'); +var extract = require('extract-zip'); +var util = require('util'); + +var CHROMIUM_PATH = path.join(__dirname, '..', '.local-chromium'); + +var downloadURLs = { + linux: 'https://storage.googleapis.com/chromium-browser-snapshots/Linux_x64/%d/chrome-linux.zip', + darwin: 'https://storage.googleapis.com/chromium-browser-snapshots/Mac/%d/chrome-mac.zip', + win32: 'https://storage.googleapis.com/chromium-browser-snapshots/Win/%d/chrome-win32.zip', + win64: 'https://storage.googleapis.com/chromium-browser-snapshots/Win_x64/%d/chrome-win32.zip', +}; + +module.exports = { + downloadChromium, + executablePath, +}; + +/** + * @param {string} revision + * @param {?function(number, number)} progressCallback + * @return {!Promise} + */ +async function downloadChromium(revision, progressCallback) { + var url = null; + var platform = os.platform(); + if (platform === 'darwin') + url = downloadURLs.darwin; + else if (platform === 'linux') + url = downloadURLs.linux; + else if (platform === 'win32') + url = os.arch() === 'x64' ? downloadURLs.win64 : downloadURLs.win32; + console.assert(url, `Unsupported platform: ${platform}`); + url = util.format(url, revision); + var zipPath = path.join(CHROMIUM_PATH, `download-${revision}.zip`); + var folderPath = path.join(CHROMIUM_PATH, revision); + if (fs.existsSync(folderPath)) + return; + try { + if (!fs.existsSync(CHROMIUM_PATH)) + fs.mkdirSync(CHROMIUM_PATH); + await downloadFile(url, zipPath, progressCallback); + await extractZip(zipPath, folderPath); + } finally { + if (fs.existsSync(zipPath)) + fs.unlinkSync(zipPath); + } +} + +/** + * @return {string} + */ +function executablePath(revision) { + var platform = os.platform(); + if (platform === 'darwin') + return path.join(CHROMIUM_PATH, revision, 'chrome-mac', 'Chromium.app', 'Contents', 'MacOS', 'Chromium'); + if (platform === 'linux') + return path.join(CHROMIUM_PATH, revision, 'chrome-linux', 'chrome'); + if (platform === 'win32') + return path.join(CHROMIUM_PATH, revision, 'chrome-win32', 'chrome.exe'); + throw new Error(`Unsupported platform: ${platform}`); +} + +/** + * @param {string} url + * @param {string} destinationPath + * @param {?function(number, number)} progressCallback + * @return {!Promise} + */ +function downloadFile(url, destinationPath, progressCallback) { + var fulfill, reject; + var promise = new Promise((x, y) => { fulfill = x; reject = y; }); + var request = https.get(url, response => { + if (response.statusCode !== 200) { + var error = new Error(`Download failed: server returned code ${response.statusCode}. URL: ${url}`); + // consume response data to free up memory + response.resume(); + reject(error); + return; + } + var file = fs.createWriteStream(destinationPath); + file.on('finish', () => fulfill()); + file.on('error', error => reject(error)); + response.pipe(file); + var totalBytes = parseInt(response.headers['content-length'], 10); + if (progressCallback) + response.on('data', onData.bind(null, totalBytes)); + }); + request.on('error', error => reject(error)); + return promise; + + function onData(totalBytes, chunk) { + progressCallback(totalBytes, chunk.length); + } +} + +/** + * @param {string} zipPath + * @param {string} folderPath + * @return {!Promise} + */ +function extractZip(zipPath, folderPath) { + return new Promise(fulfill => extract(zipPath, {dir: folderPath}, fulfill)); +} diff --git a/lib/Page.js b/lib/Page.js new file mode 100644 index 00000000000..5553cd16c50 --- /dev/null +++ b/lib/Page.js @@ -0,0 +1,350 @@ +/** + * Copyright 2017 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var fs = require('fs'); +var EventEmitter = require('events'); +var helpers = require('./helpers'); + +class Page extends EventEmitter { + /** + * @param {!Browser} browser + * @param {!CDP} client + * @return {!Promise} + */ + static async create(browser, client) { + await Promise.all([ + client.send('Network.enable', {}), + client.send('Page.enable', {}), + client.send('Runtime.enable', {}), + client.send('Security.enable', {}), + ]); + var screenDPI = await helpers.evaluate(client, () => window.devicePixelRatio, []); + var page = new Page(browser, client, screenDPI.result.value); + // Initialize default page size. + await page.setSize({width: 400, height: 300}); + return page; + } + + /** + * @param {!Browser} browser + * @param {!CDP} client + * @param {number} screenDPI + */ + constructor(browser, client, screenDPI) { + super(); + this._browser = browser; + this._client = client; + this._screenDPI = screenDPI; + this._extraHeaders = {}; + /** @type {!Map} */ + this._scriptIdToPageCallback = new Map(); + /** @type {!Map} */ + this._scriptIdToCallbackName = new Map(); + + client.on('Debugger.paused', event => this._onDebuggerPaused(event)); + client.on('Network.responseReceived', event => this.emit(Page.Events.ResponseReceived, event.response)); + client.on('Network.loadingFailed', event => this.emit(Page.Events.ResourceLoadingFailed, event)); + client.on('Runtime.consoleAPICalled', event => this._onConsoleAPI(event)); + client.on('Page.javascriptDialogOpening', dialog => this.emit(Page.Events.DialogOpened, dialog)); + client.on('Runtime.exceptionThrown', exception => this._handleException(exception.exceptionDetails)); + } + + /** + * @param {string} name + * @param {function(?)} callback + */ + async setInPageCallback(name, callback) { + var hasCallback = await this.evaluate(function(name) { + return !!window[name]; + }, name); + if (hasCallback) + throw new Error(`Failed to set in-page callback with name ${name}: window['${name}'] already exists!`); + + var sourceURL = '__in_page_callback__' + name; + // Ensure debugger is enabled. + await this._client.send('Debugger.enable', {}); + var scriptPromise = helpers.waitForScriptWithURL(this._client, sourceURL); + helpers.evaluate(this._client, inPageCallback, [name], false /* awaitPromise */, sourceURL); + var script = await scriptPromise; + if (!script) + throw new Error(`Failed to set in-page callback with name "${name}"`); + this._scriptIdToPageCallback.set(script.scriptId, callback); + this._scriptIdToCallbackName.set(script.scriptId, name); + + function inPageCallback(callbackName) { + window[callbackName] = (...args) => { + window[callbackName].__args = args; + window[callbackName].__result = undefined; + debugger; + return window[callbackName].__result; + }; + } + } + + /** + * @param {string} scriptId + */ + async _handleInPageCallback(scriptId) { + var name = /** @type {string} */ (this._scriptIdToCallbackName.get(scriptId)); + var callback = /** @type {function()} */ (this._scriptIdToPageCallback.get(scriptId)); + var args = await this.evaluate(callbackName => window[callbackName].__args, name); + var result = callback.apply(null, args); + await this.evaluate(assignResult, name, result); + this._client.send('Debugger.resume'); + + /** + * @param {string} callbackName + * @param {string} callbackResult + */ + function assignResult(callbackName, callbackResult) { + window[callbackName].__result = callbackResult; + } + } + + _onDebuggerPaused(event) { + var location = event.callFrames[0] ? event.callFrames[0].location : null; + if (location && this._scriptIdToPageCallback.has(location.scriptId)) { + this._handleInPageCallback(location.scriptId); + return; + } + this._client.send('Debugger.resume'); + } + + /** + * @param {!Object} headers + * @return {!Promise} + */ + async setExtraHTTPHeaders(headers) { + this._extraHeaders = {}; + // Note: header names are case-insensitive. + for (var key of Object.keys(headers)) + this._extraHeaders[key.toLowerCase()] = headers[key]; + return this._client.send('Network.setExtraHTTPHeaders', { headers }); + } + + /** + * @return {!Object} + */ + extraHTTPHeaders() { + return Object.assign({}, this._extraHeaders); + } + + /** + * @param {string} userAgent + * @return {!Promise} + */ + async setUserAgentOverride(userAgent) { + this._userAgent = userAgent; + return this._client.send('Network.setUserAgentOverride', { userAgent }); + } + + /** + * @return {string} + */ + userAgentOverride() { + return this._userAgent; + } + + _handleException(exceptionDetails) { + var stack = []; + if (exceptionDetails.stackTrace) { + stack = exceptionDetails.stackTrace.callFrames.map(cf => cf.url); + } + var stackTrace = exceptionDetails.stackTrace; + this.emit(Page.Events.ExceptionThrown, exceptionDetails.exception.description, stack); + } + + _onConsoleAPI(event) { + var values = event.args.map(arg => arg.value || arg.description || ''); + this.emit(Page.Events.ConsoleMessageAdded, values.join(' ')); + } + + /** + * @param {boolean} accept + * @param {string} promptText + * @return {!Promise} + */ + async handleDialog(accept, promptText) { + return this._client.send('Page.handleJavaScriptDialog', {accept, promptText}); + } + + /** + * @return {!Promise} + */ + async url() { + return this.evaluate(function() { + return window.location.href; + }); + } + + /** + * @param {string} html + * @return {!Promise} + */ + async setContent(html) { + var resourceTree = await this._client.send('Page.getResourceTree', {}); + await this._client.send('Page.setDocumentContent', { + frameId: resourceTree.frameTree.frame.id, + html: html + }); + } + + /** + * @param {string} html + * @return {!Promise} + */ + async navigate(url) { + var loadPromise = new Promise(fulfill => this._client.once('Page.loadEventFired', fulfill)).then(() => true); + var interstitialPromise = new Promise(fulfill => this._client.once('Security.certificateError', fulfill)).then(() => false); + var referrer = this._extraHeaders.referer; + // Await for the command to throw exception in case of illegal arguments. + await this._client.send('Page.navigate', {url, referrer}); + return await Promise.race([loadPromise, interstitialPromise]); + } + + /** + * @param {!{width: number, height: number}} size + * @return {!Promise} + */ + async setSize(size) { + this._size = size; + var width = size.width; + var height = size.height; + var zoom = this._screenDPI; + return Promise.all([ + this._client.send('Emulation.setDeviceMetricsOverride', { + width, + height, + deviceScaleFactor: 1, + scale: 1 / zoom, + mobile: false, + fitWindow: false + }), + this._client.send('Emulation.setVisibleSize', { + width: width / zoom, + height: height / zoom, + }) + ]); + } + + /** + * @return {!{width: number, height: number}} + */ + size() { + return this._size; + } + + /** + * @param {function()} fun + * @param {!Array<*>} args + * @return {!Promise<(!Object|udndefined)>} + */ + async evaluate(fun, ...args) { + var response = await helpers.evaluate(this._client, fun, args, false /* awaitPromise */); + if (response.exceptionDetails) { + this._handleException(response.exceptionDetails); + return; + } + return response.result.value; + } + + /** + * @param {function()} fun + * @param {!Array<*>} args + * @return {!Promise<(!Object|udndefined)>} + */ + async evaluateAsync(fun, ...args) { + var response = await helpers.evaluate(this._client, fun, args, true /* awaitPromise */); + if (response.exceptionDetails) { + this._handleException(response.exceptionDetails); + return; + } + return response.result.value; + } + + /** + * @param {!Page.ScreenshotType} screenshotType + * @param {?{x: number, y: number, width: number, height: number}} clipRect + * @return {!Promise} + */ + async screenshot(screenshotType, clipRect) { + if (clipRect) { + await Promise.all([ + this._client.send('Emulation.setVisibleSize', { + width: clipRect.width / this._screenDPI, + height: clipRect.height / this._screenDPI, + }), + this._client.send('Emulation.forceViewport', { + x: clipRect.x / this._screenDPI, + y: clipRect.y / this._screenDPI, + scale: 1, + }) + ]); + } + var result = await this._client.send('Page.captureScreenshot', { + fromSurface: true, + format: screenshotType, + }); + if (clipRect) { + await Promise.all([ + this.setSize(this.size()), + this._client.send('Emulation.resetViewport') + ]); + } + return new Buffer(result.data, 'base64'); + } + + /** + * @return {!Promise} + */ + async plainText() { + return this.evaluate(function() { + return document.body.innerText; + }); + } + + /** + * @return {!Promise} + */ + async title() { + return this.evaluate(function() { + return document.title; + }); + } + + /** + * @return {!Promise} + */ + async close() { + return this._browser.closePage(this); + } +} + +/** @enum {string} */ +Page.ScreenshotTypes = { + PNG: "png", + JPG: "jpeg", +}; + +Page.Events = { + ConsoleMessageAdded: 'Page.Events.ConsoleMessageAdded', + DialogOpened: 'Page.Events.DialogOpened', + ExceptionThrown: 'Page.Events.ExceptionThrown', + ResourceLoadingFailed: 'Page.Events.ResourceLoadingFailed', + ResponseReceived: 'Page.Events.ResponseReceived', +}; + +module.exports = Page; diff --git a/lib/helpers.js b/lib/helpers.js new file mode 100644 index 00000000000..b5a868e0f3b --- /dev/null +++ b/lib/helpers.js @@ -0,0 +1,68 @@ +/** + * Copyright 2017 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +module.exports = { + /** + * @param {!CDP} client + * @param {string} url + * @return {!Promise} + */ + waitForScriptWithURL: function(client, url) { + var fulfill; + var promise = new Promise(x => fulfill = x); + client.on('Debugger.scriptParsed', onScriptParsed); + client.on('Debugger.scriptFailedToParse', onScriptFailedToParse); + return promise; + + function onScriptParsed(event) { + if (event.url !== url) + return; + client.removeListener('Debugger.scriptParsed', onScriptParsed); + client.removeListener('Debugger.scriptFailedToParse', onScriptFailedToParse); + fulfill(event); + } + + function onScriptFailedToParse(event) { + if (event.url !== url) + return; + client.removeListener('Debugger.scriptParsed', onScriptParsed); + client.removeListener('Debugger.scriptFailedToParse', onScriptFailedToParse); + fulfill(null); + } + }, + + /** + * @param {!CDP} client + * @param {function()} fun + * @param {!Array<*>} args + * @param {boolean} awaitPromise + * @param {string=} sourceURL + * @return {!Promise} + */ + evaluate: function(client, fun, args, awaitPromise, sourceURL) { + var argsString = args.map(x => JSON.stringify(x)).join(','); + var code = `(${fun.toString()})(${argsString})`; + if (awaitPromise) + code = `Promise.resolve(${code})`; + if (sourceURL) + code += `\n//# sourceURL=${sourceURL}`; + return client.send('Runtime.evaluate', { + expression: code, + awaitPromise: awaitPromise, + returnByValue: true + }); + }, +} diff --git a/package.json b/package.json new file mode 100644 index 00000000000..4fa90178da6 --- /dev/null +++ b/package.json @@ -0,0 +1,28 @@ +{ + "name": "puppeteer", + "version": "0.0.1", + "description": "", + "main": "index.js", + "scripts": { + "test": "python third_party/phantomjs/test/run-tests.py", + "install": "node install.js" + }, + "author": "The Chromium Authors", + "license": "SEE LICENSE IN LICENSE", + "dependencies": { + "chrome-remote-interface": "^0.18.0", + "deasync": "^0.1.9", + "extract-zip": "^1.6.5", + "mime": "^1.3.4", + "minimist": "^1.2.0", + "ncp": "^2.0.0", + "progress": "^2.0.0", + "rimraf": "^2.6.1" + }, + "bin": { + "puppeteer": "index.js" + }, + "puppeteer": { + "chromium_revision": "468266" + } +} diff --git a/phantomjs/FileSystem.js b/phantomjs/FileSystem.js new file mode 100644 index 00000000000..bbc5d575ccd --- /dev/null +++ b/phantomjs/FileSystem.js @@ -0,0 +1,365 @@ +/** + * Copyright 2017 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var path = require('path'); +var fs = require('fs'); +var deasync = require('deasync'); +var removeRecursive = require('rimraf').sync; +var copyRecursive = deasync(require('ncp').ncp); + +class FileSystem { + constructor() { + this.separator = path.sep; + } + + /** + * @return {string} + */ + get workingDirectory() { + return process.cwd(); + } + + /** + * @param {string} directoryPath + */ + changeWorkingDirectory(directoryPath) { + try { + process.chdir(directoryPath); + return true; + } catch (e){ + return false; + } + } + + /** + * @param {string} relativePath + * @return {string} + */ + absolute(relativePath) { + relativePath = path.normalize(relativePath); + if (path.isAbsolute(relativePath)) + return relativePath; + return path.resolve(path.join(process.cwd(), relativePath)); + } + + /** + * @param {string} filePath + * @return {boolean} + */ + exists(filePath) { + return fs.existsSync(filePath); + } + + /** + * @param {string} fromPath + * @param {string} toPath + */ + copy(fromPath, toPath) { + var content = fs.readFileSync(fromPath); + fs.writeFileSync(toPath, content); + } + + /** + * @param {string} fromPath + * @param {string} toPath + */ + move(fromPath, toPath) { + var content = fs.readFileSync(fromPath); + fs.writeFileSync(toPath, content); + fs.unlinkSync(fromPath); + } + + /** + * @param {string} filePath + * @return {number} + */ + size(filePath) { + return fs.statSync(filePath).size; + } + + /** + * @param {string} filePath + */ + touch(filePath) { + fs.closeSync(fs.openSync(filePath, 'a')); + } + + /** + * @param {string} filePath + */ + remove(filePath) { + fs.unlinkSync(filePath); + } + + /** + * @param {string} filePath + */ + lastModified(filePath) { + return fs.statSync(filePath).mtime; + } + + /** + * @param {string} dirPath + */ + makeDirectory(dirPath) { + try { + fs.mkdirSync(dirPath); + return true; + } catch (e) { + return false; + } + } + + /** + * @param {string} dirPath + */ + removeTree(dirPath) { + removeRecursive(dirPath); + } + + /** + * @param {string} fromPath + * @param {string} toPath + */ + copyTree(fromPath, toPath) { + copyRecursive(fromPath, toPath); + } + + /** + * @param {string} dirPath + * @return {!Array} + */ + list(dirPath) { + return fs.readdirSync(dirPath); + } + + /** + * @param {string} linkPath + * @return {string} + */ + readLink(linkPath) { + return fs.readlinkSync(linkPath); + } + + /** + * @param {string} filePath + * @param {Object} data + * @param {string} mode + */ + write(filePath, data, mode) { + var fd = new FileDescriptor(filePath, mode, 'utf8'); + fd.write(data); + fd.close(); + } + + /** + * @param {string} somePath + * @return {boolean} + */ + isAbsolute(somePath) { + return path.isAbsolute(somePath); + } + + /** + * @return {string} + */ + read(filePath) { + return fs.readFileSync(filePath, 'utf8'); + } + + /** + * @param {string} filePath + * @return {boolean} + */ + isFile(filePath) { + return fs.existsSync(filePath) && fs.lstatSync(filePath).isFile(); + } + + /** + * @param {string} dirPath + * @return {boolean} + */ + isDirectory(dirPath) { + return fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory(); + } + + /** + * @param {string} filePath + * @return {boolean} + */ + isLink(filePath) { + return fs.existsSync(filePath) && fs.lstatSync(filePath).isSymbolicLink(); + } + + /** + * @param {string} filePath + * @return {boolean} + */ + isReadable(filePath) { + try { + fs.accessSync(filePath, fs.constants.R_OK); + return true; + } catch (e) { + return false; + } + } + + /** + * @param {string} filePath + * @return {boolean} + */ + isWritable(filePath) { + try { + fs.accessSync(filePath, fs.constants.W_OK); + return true; + } catch (e) { + return false; + } + } + + /** + * @param {string} filePath + * @return {boolean} + */ + isExecutable(filePath) { + try { + fs.accessSync(filePath, fs.constants.X_OK); + return true; + } catch (e) { + return false; + } + } + + /** + * @param {string} somePath + * @return {!Array} + */ + split(somePath) { + somePath = path.normalize(somePath); + if (somePath.endsWith(path.sep)) + somePath = somePath.substring(0, somePath.length - path.sep.length); + return somePath.split(path.sep); + } + + /** + * @param {string} path1 + * @param {string} path2 + * @return {string} + */ + join(...args) { + if (args[0] === '' && args.length > 1) + args[0] = path.sep; + args = args.filter(part => typeof part === 'string'); + return path.join.apply(path, args); + } + + /** + * @param {string} filePath + * @param {(string|!Object)} option + * @return {!FileDescriptor} + */ + open(filePath, option) { + if (typeof option === 'string') + return new FileDescriptor(filePath, option); + return new FileDescriptor(filePath, option.mode); + } +} + +var fdwrite = deasync(fs.write); +var fdread = deasync(fs.read); + +class FileDescriptor { + /** + * @param {string} filePath + * @param {string} mode + */ + constructor(filePath, mode) { + this._position = 0; + this._encoding = 'utf8'; + if (mode === 'rb') { + this._mode = 'r'; + this._encoding = 'latin1'; + } else if (mode === 'wb' || mode === 'b') { + this._mode = 'w'; + this._encoding = 'latin1'; + } else if (mode === 'rw+') { + this._mode = 'a+'; + this._position = fs.existsSync(filePath) ? fs.statSync(filePath).size : 0; + } else { + this._mode = mode; + } + this._fd = fs.openSync(filePath, this._mode); + } + + /** + * @param {string} data + */ + write(data) { + var buffer = Buffer.from(data, this._encoding); + var written = fdwrite(this._fd, buffer, 0, buffer.length, this._position); + this._position += written; + } + + getEncoding() { + return 'UTF-8'; + } + + /** + * @param {string} data + */ + writeLine(data) { + this.write(data + '\n'); + } + + /** + * @param {number=} size + * @return {string} + */ + read(size) { + var position = this._position; + if (!size) { + size = fs.fstatSync(this._fd).size; + position = 0; + } + var buffer = new Buffer(size); + var bytesRead = fdread(this._fd, buffer, 0, size, position); + this._position += bytesRead; + return buffer.toString(this._encoding); + } + + flush() { + // noop. + } + + /** + * @param {number} position + */ + seek(position) { + this._position = position; + } + + close() { + fs.closeSync(this._fd); + } + + /** + * @return {boolean} + */ + atEnd() { + } +} + +module.exports = FileSystem; diff --git a/phantomjs/Phantom.js b/phantomjs/Phantom.js new file mode 100644 index 00000000000..ed0269681ee --- /dev/null +++ b/phantomjs/Phantom.js @@ -0,0 +1,139 @@ +/** + * Copyright 2017 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var fs = require('fs'); +var path = require('path'); +var vm = require('vm'); +var url = require('url'); + +/** + * @param {!Object} context + * @param {string} scriptPath + */ +module.exports.create = function(context, scriptPath) { + var phantom = { + page: { + onConsoleMessage: null, + }, + + /** + * @param {string} relative + * @param {string} base + * @return {string} + */ + resolveRelativeUrl: function(relative, base) { + return url.resolve(base, relative); + }, + + /** + * @param {string} url + * @return {string} + */ + fullyDecodeUrl: function(url) { + return decodeURI(url); + }, + + libraryPath: path.dirname(scriptPath), + + onError: null, + + /** + * @return {string} + */ + get outputEncoding() { + return 'UTF-8'; + }, + + /** + * @param {string} value + */ + set outputEncoding(value) { + throw new Error('Phantom.outputEncoding setter is not implemented'); + }, + + /** + * @return {boolean} + */ + get cookiesEnabled() { + return true; + }, + + /** + * @param {boolean} value + */ + set cookiesEnabled(value) { + throw new Error('Phantom.cookiesEnabled setter is not implemented'); + }, + + /** + * @return {!{major: number, minor: number, patch: number}} + */ + get version() { + var versionParts = require('../package.json').version.split('.'); + return { + major: parseInt(versionParts[0], 10), + minor: parseInt(versionParts[1], 10), + patch: parseInt(versionParts[2], 10), + }; + }, + + /** + * @param {number=} code + */ + exit: function(code) { + process.exit(code); + }, + + /** + * @param {string} filePath + * @return {boolean} + */ + injectJs: function(filePath) { + filePath = path.resolve(phantom.libraryPath, filePath); + if (!fs.existsSync(filePath)) + return false; + var code = fs.readFileSync(filePath, 'utf8'); + if (code.startsWith('#!')) + code = code.substring(code.indexOf('\n')); + vm.runInContext(code, context, { + filename: filePath, + displayErrors: true + }); + return true; + }, + + /** + * @param {string} moduleSource + * @param {string} filename + */ + loadModule: function(moduleSource, filename) { + var code = [ + "(function(require, exports, module) {\n", + moduleSource, + "\n}.call({},", + "require.cache['" + filename + "']._getRequire(),", + "require.cache['" + filename + "'].exports,", + "require.cache['" + filename + "']", + "));" + ].join(''); + vm.runInContext(code, context, { + filename: filename, + displayErrors: true + }); + }, + }; + return phantom; +} diff --git a/phantomjs/System.js b/phantomjs/System.js new file mode 100644 index 00000000000..770929350ba --- /dev/null +++ b/phantomjs/System.js @@ -0,0 +1,118 @@ +/** + * Copyright 2017 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var readline = require('readline'); +var await = require('./utilities').await; +var os = require('os'); + +class System { + /** + * @param {!Array} args + */ + constructor(args) { + this.args = args; + this.env = {}; + Object.assign(this.env, process.env); + this.stdin = new StandardInput(process.stdin); + this.stdout = new StandardOutput(process.stdout); + this.stderr = new StandardOutput(process.stderr); + this.platform = "phantomjs"; + this.pid = process.pid; + this.isSSLSupported = false; + this.os = { + architecture: os.arch(), + name: os.type(), + version: os.release() + }; + } +} + +class StandardInput { + /** + * @param {!Readable} readableStream + */ + constructor(readableStream) { + this._readline = readline.createInterface({ + input: readableStream + }); + this._lines = []; + this._closed = false; + this._readline.on('line', line => this._lines.push(line)); + this._readline.on('close', () => this._closed = true); + } + + /** + * @return {string} + */ + readLine() { + if (this._closed && !this._lines.length) + return ''; + if (!this._lines.length) { + var linePromise = new Promise(fulfill => this._readline.once('line', fulfill)); + await(linePromise); + } + return this._lines.shift(); + } + + /** + * @return {string} + */ + read() { + if (!this._closed) { + var closePromise = new Promise(fulfill => this._readline.once('close', fulfill)); + await(closePromise); + } + var text = this._lines.join('\n'); + this._lines = []; + return text; + } + + close() { + this._readline.close(); + } +} + +class StandardOutput { + /** + * @param {!Writable} writableStream + */ + constructor(writableStream) { + this._stream = writableStream; + } + + /** + * @param {string} data + */ + write(data) { + this._stream.write(data); + } + + /** + * @param {string} data + */ + writeLine(data) { + this._stream.write(data + '\n'); + } + + flush() { + } + + close() { + this._stream.end(); + } +} + +module.exports = System; diff --git a/phantomjs/WebPage.js b/phantomjs/WebPage.js new file mode 100644 index 00000000000..2ea290a2311 --- /dev/null +++ b/phantomjs/WebPage.js @@ -0,0 +1,327 @@ +/** + * Copyright 2017 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var await = require('./utilities').await; +var EventEmitter = require('events'); +var fs = require('fs'); +var path = require('path'); +var mime = require('mime'); + +var PageEvents = require('../lib/Page').Events; +var ScreenshotTypes = require('../lib/Page').ScreenshotTypes; + +var noop = function() { }; + +class WebPage { + /** + * @param {!Browser} browser + * @param {string} scriptPath + * @param {!Object=} options + */ + constructor(browser, scriptPath, options) { + this._page = await(browser.newPage()); + this.settings = new WebPageSettings(this._page); + + options = options || {}; + options.settings = options.settings || {}; + if (options.settings.userAgent) + this.settings.userAgent = options.settings.userAgent; + if (options.viewportSize) + await(this._page.setSize(options.viewportSize)); + + await(this._page.setInPageCallback('callPhantom', (...args) => { + return this.onCallback.apply(null, args); + })); + + this.clipRect = options.clipRect || {left: 0, top: 0, width: 0, height: 0}; + this.onCallback = null; + this.onConsoleMessage = null; + this.onLoadFinished = null; + this.onResourceError = null; + this.onResourceReceived = null; + this.libraryPath = path.dirname(scriptPath); + + this._onConfirm = undefined; + this._onError = noop; + + this._pageEvents = new AsyncEmitter(this._page); + this._pageEvents.on(PageEvents.ResponseReceived, response => this._onResponseReceived(response)); + this._pageEvents.on(PageEvents.ResourceLoadingFailed, event => (this.onResourceError || noop).call(null, event)); + this._pageEvents.on(PageEvents.ConsoleMessageAdded, msg => (this.onConsoleMessage || noop).call(null, msg)); + this._pageEvents.on(PageEvents.DialogOpened, dialog => this._onDialog(dialog)); + this._pageEvents.on(PageEvents.ExceptionThrown, (exception, stack) => (this._onError || noop).call(null, exception, stack)); + } + + _onResponseReceived(response) { + if (!this.onResourceReceived) + return; + var headers = []; + for (var key in response.headers) { + headers.push({ + name: key, + value: response.headers[key] + }); + } + response.headers = headers; + this.onResourceReceived.call(null, response); + } + + /** + * @param {string} url + * @param {function()} callback + */ + includeJs(url, callback) { + this._page.evaluateAsync(include, url).then(callback); + + function include(url) { + var script = document.createElement('script'); + script.src = url; + var promise = new Promise(x => script.onload = x); + document.head.appendChild(script); + return promise; + } + } + + /** + * @return {!{width: number, height: number}} + */ + get viewportSize() { + return this._page.size(); + } + + /** + * @return {!Object} + */ + get customHeaders() { + return this._page.extraHTTPHeaders(); + } + + /** + * @param {!Object} value + */ + set customHeaders(value) { + await(this._page.setExtraHTTPHeaders(value)); + } + + /** + * @param {string} filePath + */ + injectJs(filePath) { + if (!fs.existsSync(filePath)) + filePath = path.resolve(this.libraryPath, filePath); + if (!fs.existsSync(filePath)) + return; + var code = fs.readFileSync(filePath, 'utf8'); + this.evaluate(code); + } + + /** + * @return {string} + */ + get plainText() { + return await(this._page.plainText()); + } + + /** + * @return {string} + */ + get title() { + return await(this._page.title()); + } + + /** + * @return {(function()|undefined)} + */ + get onError() { + return this._onError; + } + + /** + * @param {(function()|undefined)} handler + */ + set onError(handler) { + if (typeof handler !== 'function') + handler = undefined; + this._onError = handler; + } + + /** + * @return {(function()|undefined)} + */ + get onConfirm() { + return this._onConfirm; + } + + /** + * @param {function()} handler + */ + set onConfirm(handler) { + if (typeof handler !== 'function') + handler = undefined; + this._onConfirm = handler; + } + + _onDialog(dialog) { + if (!this._onConfirm) + return; + var accept = this._onConfirm.call(null); + await(this._page.handleDialog(accept)); + } + + /** + * @return {string} + */ + get url() { + return await(this._page.url()); + } + + /** + * @param {string} html + */ + set content(html) { + await(this._page.setContent(html)); + } + + /** + * @param {string} html + * @param {function()=} callback + */ + open(url, callback) { + console.assert(arguments.length <= 2, 'WebPage.open does not support METHOD and DATA arguments'); + this._page.navigate(url).then(result => { + var status = result ? 'success' : 'fail'; + if (!result) { + this.onResourceError.call(null, { + url, + errorString: 'SSL handshake failed' + }); + } + if (this.onLoadFinished) + this.onLoadFinished.call(null, status); + if (callback) + callback.call(null, status); + }); + } + + /** + * @param {!{width: number, height: number}} options + */ + set viewportSize(options) { + await(this._page.setSize(options)); + } + + /** + * @param {function()} fun + * @param {!Array} args + */ + evaluate(fun, ...args) { + return await(this._page.evaluate(fun, ...args)); + } + + /** + * {string} fileName + */ + render(fileName) { + var mimeType = mime.lookup(fileName); + var screenshotType = null; + if (mimeType === 'image/png') + screenshotType = ScreenshotTypes.PNG; + else if (mimeType === 'image/jpeg') + screenshotType = ScreenshotTypes.JPG; + if (!screenshotType) + throw new Error(`Cannot render to file ${fileName} - unsupported mimeType ${mimeType}`); + var clipRect = null; + if (this.clipRect && (this.clipRect.left || this.clipRect.top || this.clipRect.width || this.clipRect.height)) { + clipRect = { + x: this.clipRect.left, + y: this.clipRect.top, + width: this.clipRect.width, + height: this.clipRect.height + }; + } + var imageBuffer = await(this._page.screenshot(screenshotType, clipRect)); + fs.writeFileSync(fileName, imageBuffer); + } + + release() { + this._page.close(); + } + + close() { + this._page.close(); + } +} + +class WebPageSettings { + /** + * @param {!Page} page + */ + constructor(page) { + this._page = page; + } + + /** + * @param {string} value + */ + set userAgent(value) { + await(this._page.setUserAgentOverride(value)); + } + + /** + * @return {string} + */ + get userAgent() { + return this._page.userAgentOverride(); + } +} + +// To prevent reenterability, eventemitters should emit events +// only being in a consistent state. +// This is not the case for 'ws' npm module: https://goo.gl/sy3dJY +// +// Since out phantomjs environment uses nested event loops, we +// exploit this condition in 'ws', which probably never happens +// in case of regular I/O. +// +// This class is a wrapper around EventEmitter which re-emits events asynchronously, +// helping to overcome the issue. +class AsyncEmitter extends EventEmitter { + /** + * @param {!Page} page + */ + constructor(page) { + super(); + this._page = page; + this._symbol = Symbol('AsyncEmitter'); + this.on('newListener', this._onListenerAdded); + this.on('removeListener', this._onListenerRemoved); + } + + _onListenerAdded(event, listener) { + // Async listener calls original listener on next tick. + var asyncListener = (...args) => { + process.nextTick(() => listener.apply(null, args)); + }; + listener[this._symbol] = asyncListener; + this._page.on(event, asyncListener); + } + + _onListenerRemoved(event, listener) { + this._page.removeListener(event, listener[this._symbol]); + } +} + +module.exports = WebPage; diff --git a/phantomjs/WebServer.js b/phantomjs/WebServer.js new file mode 100644 index 00000000000..4d99b3246d7 --- /dev/null +++ b/phantomjs/WebServer.js @@ -0,0 +1,83 @@ +/** + * Copyright 2017 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var http = require('http'); +var await = require('./utilities').await; + +class WebServer { + constructor() { + this._server = http.createServer(); + this.objectName = 'WebServer'; + this.listenOnPort = this.listen; + this.newRequest = function(req, res) { } + Object.defineProperty(this, 'port', { + get: () => { + if (!this._server.listening) + return ''; + return this._server.address().port + ''; + }, + enumerable: true, + configurable: false + }); + } + + close() { + this._server.close(); + } + + /** + * @param {nubmer} port + * @return {boolean} + */ + listen(port, callback) { + if (this._server.listening) + return false; + this.newRequest = callback; + this._server.listen(port); + var errorPromise = new Promise(x => this._server.once('error', x)); + var successPromise = new Promise(x => this._server.once('listening', x)); + await(Promise.race([errorPromise, successPromise])); + if (!this._server.listening) + return false; + + this._server.on('request', (req, res) => { + res.close = res.end.bind(res); + var headers = res.getHeaders(); + res.headers = []; + for (var key in headers) { + res.headers.push({ + name: key, + value: headers[key] + }); + } + res.header = res.getHeader; + res.setHeaders = (headers) => { + for (var key in headers) + res.setHeader(key, headers[key]); + } + Object.defineProperty(res, 'statusCode', { + enumerable: true, + configurable: true, + writable: true, + value: res.statusCode + }); + this.newRequest.call(null, req, res); + }); + return true; + } +} + +module.exports = WebServer; diff --git a/phantomjs/index.js b/phantomjs/index.js new file mode 100644 index 00000000000..4dca15dfd02 --- /dev/null +++ b/phantomjs/index.js @@ -0,0 +1,71 @@ +/** + * Copyright 2017 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var vm = require('vm'); +var path = require('path'); +var fs = require('fs'); +var Phantom = require('./Phantom'); +var FileSystem = require('./FileSystem'); +var System = require('./System'); +var WebPage = require('./WebPage'); +var WebServer = require('./WebServer'); +var child_process = require('child_process'); + +var bootstrapPath = path.join(__dirname, '..', 'third_party', 'phantomjs', 'bootstrap.js'); +var bootstrapCode = fs.readFileSync(bootstrapPath, 'utf8'); + +module.exports = { + /** + * @param {!Browser} browser + * @param {string} scriptPath + * @param {!Array} argv + * @return {!Object} + */ + createContext(browser, scriptPath, argv) { + var context = {}; + context.setInterval = setInterval; + context.setTimeout = setTimeout; + context.clearInterval = clearInterval; + context.clearTimeout = clearTimeout; + + context.phantom = Phantom.create(context, scriptPath); + context.console = console; + context.window = context; + context.WebPage = (options) => new WebPage(browser, scriptPath, options); + + vm.createContext(context); + + var nativeExports = { + fs: new FileSystem(), + system: new System(argv._), + webpage: { + create: context.WebPage, + }, + webserver: { + create: () => new WebServer(), + }, + cookiejar: { + create: () => {}, + }, + child_process: child_process + }; + vm.runInContext(bootstrapCode, context, { + filename: 'bootstrap.js' + })(nativeExports); + return context; + } +} + diff --git a/phantomjs/utilities.js b/phantomjs/utilities.js new file mode 100644 index 00000000000..9663d196611 --- /dev/null +++ b/phantomjs/utilities.js @@ -0,0 +1,33 @@ +/** + * Copyright 2017 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +var loopWhile = require('deasync').loopWhile; + +module.exports = { + await: function(promise) { + var error; + var result; + var done = false; + promise.then(r => result = r) + .catch(err => error = err) + .then(() => done = true); + loopWhile(() => !done); + if (error) + throw error; + return result; + } +} + diff --git a/third_party/phantomjs/CHANGES.md b/third_party/phantomjs/CHANGES.md new file mode 100644 index 00000000000..d5256cfec4c --- /dev/null +++ b/third_party/phantomjs/CHANGES.md @@ -0,0 +1,19 @@ +Short Name: phantomjs +URL: https://github.com/ariya/phantomjs/tree/2.1.1 +Version: 2.1.1 +License: BSD +License File: LICENSE.BSD +Security Critical: no + +Description: +This package is used to aid puppeteer in running phantom.js scripts: +- test/ - testsuite is used to validate puppeteer running phantom.js scripts +- boostrap.js - used to bootstrap puppeteer environment + +Local Modifications: + +- test/run_test.py was changed to run puppeteer instead of phantomjs +- Certain tests under test/ were changed where tests were unreasonably strict in their expectations + (e.g. validating the exact format of error messages) +- bootstrap.js was changed to accept native modules as function arguments. +- test/run_test.py was enhanced to support "unsupported" directive diff --git a/third_party/phantomjs/LICENSE.BSD b/third_party/phantomjs/LICENSE.BSD new file mode 100644 index 00000000000..d5dfdd1f661 --- /dev/null +++ b/third_party/phantomjs/LICENSE.BSD @@ -0,0 +1,22 @@ +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of the 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 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. diff --git a/third_party/phantomjs/bootstrap.js b/third_party/phantomjs/bootstrap.js new file mode 100644 index 00000000000..f3a69c55009 --- /dev/null +++ b/third_party/phantomjs/bootstrap.js @@ -0,0 +1,235 @@ +/*jslint sloppy: true, nomen: true */ +/*global window:true,phantom:true */ + +/* + This file is part of the PhantomJS project from Ofi Labs. + + Copyright (C) 2011 Ariya Hidayat + Copyright (C) 2011 Ivan De Marino + Copyright (C) 2011 James Roe + Copyright (C) 2011 execjosh, http://execjosh.blogspot.com + Copyright (C) 2012 James M. Greene + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of the 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 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. +*/ + +(function(nativeExports) { + // CommonJS module implementation follows + + window.global = window; + // fs is loaded at the end, when everything is ready + var fs; + var cache = {}; + var paths = []; + var extensions = { + '.js': function(module, filename) { + var code = fs.read(filename); + module._compile(code); + }, + + '.json': function(module, filename) { + module.exports = JSON.parse(fs.read(filename)); + } + }; + + function dirname(path) { + var replaced = path.replace(/\/[^\/]*\/?$/, ''); + if (replaced == path) { + replaced = ''; + } + return replaced; + } + + function basename(path) { + return path.replace(/.*\//, ''); + } + + function joinPath() { + // It should be okay to hard-code a slash here. + // The FileSystem module returns a platform-specific + // separator, but the JavaScript engine only expects + // the slash. + var args = Array.prototype.slice.call(arguments); + return args.join('/'); + } + + function tryFile(path) { + if (fs.isFile(path)) return path; + return null; + } + + function tryExtensions(path) { + var filename, exts = Object.keys(extensions); + for (var i=0; i 0) { + page.render('report.png'); + phantom.exit(); + } else { + setTimeout(monitor, 1000); + } + } + + setTimeout(monitor, 0); +}); diff --git a/third_party/phantomjs/test/module/cookiejar/cookiejar.js b/third_party/phantomjs/test/module/cookiejar/cookiejar.js new file mode 100644 index 00000000000..4c9e4cc4c76 --- /dev/null +++ b/third_party/phantomjs/test/module/cookiejar/cookiejar.js @@ -0,0 +1,93 @@ +//! unsupported +var cookie0 = { + 'name': 'Valid-Cookie-Name', + 'value': 'Valid-Cookie-Value', + 'domain': 'localhost', + 'path': '/foo', + 'httponly': true, + 'secure': false +}; +var cookie1 = { + 'name': 'Valid-Cookie-Name-1', + 'value': 'Valid-Cookie-Value', + 'domain': 'localhost', + 'path': '/foo', + 'httponly': true, + 'secure': false +}; +var cookie2 = { + 'name': 'Valid-Cookie-Name-2', + 'value': 'Valid-Cookie-Value', + 'domain': 'localhost', + 'path': '/foo', + 'httponly': true, + 'secure': false +}; +var cookies = [{ + 'name': 'Valid-Cookie-Name', + 'value': 'Valid-Cookie-Value', + 'domain': 'localhost', + 'path': '/foo', + 'httponly': true, + 'secure': false +},{ + 'name': 'Valid-Cookie-Name-Sec', + 'value': 'Valid-Cookie-Value-Sec', + 'domain': 'localhost', + 'path': '/foo', + 'httponly': true, + 'secure': false, + 'expires': new Date().getTime() + 3600 //< expires in 1h +}]; + +var cookiejar, jar1, jar2; +setup(function () { + cookiejar = require('cookiejar'); + jar1 = cookiejar.create(); + jar2 = cookiejar.create(); +}); + +test(function () { + assert_type_of(jar1, 'object'); + assert_not_equals(jar1, null); + assert_type_of(jar1.cookies, 'object'); + + assert_type_of(jar1.addCookie, 'function'); + assert_type_of(jar1.deleteCookie, 'function'); + assert_type_of(jar1.clearCookies, 'function'); +}, "cookie jar properties"); + +test(function () { + assert_equals(jar1.cookies.length, 0); + + jar1.addCookie(cookie0); + assert_equals(jar1.cookies.length, 1); + + jar1.deleteCookie('Valid-Cookie-Name'); + assert_equals(jar1.cookies.length, 0); +}, "adding and removing cookies"); + +test(function () { + assert_equals(jar1.cookies.length, 0); + + jar1.cookies = cookies; + assert_equals(jar1.cookies.length, 2); + + jar1.clearCookies(); + assert_equals(jar1.cookies.length, 0); +}, "setting and clearing a cookie jar"); + +test(function () { + jar1.addCookie(cookie1); + assert_equals(jar1.cookies.length, 1); + assert_equals(jar2.cookies.length, 0); + + jar2.addCookie(cookie2); + jar1.deleteCookie('Valid-Cookie-Name-1'); + assert_equals(jar1.cookies.length, 0); + assert_equals(jar2.cookies.length, 1); + + jar1.close(); + jar2.close(); + +}, "cookie jar isolation"); diff --git a/third_party/phantomjs/test/module/cookiejar/to-map.js b/third_party/phantomjs/test/module/cookiejar/to-map.js new file mode 100644 index 00000000000..7528e3fc578 --- /dev/null +++ b/third_party/phantomjs/test/module/cookiejar/to-map.js @@ -0,0 +1,52 @@ +//! unsupported +var cookies = { + 'beforeExpires': { + 'name': 'beforeExpires', + 'value': 'expireValue', + 'domain': '.abc.com', + 'path': '/', + 'httponly': false, + 'secure': false, + 'expires': 'Tue, 10 Jun 2025 12:28:29 GMT' + }, + 'noExpiresDate': { + 'name': 'noExpiresDate', + 'value': 'value', + 'domain': '.abc.com', + 'path': '/', + 'httponly': false, + 'secure': false, + 'expires': null + }, + 'afterExpires': { + 'name': 'afterExpires', + 'value': 'value', + 'domain': '.abc.com', + 'path': '/', + 'httponly': false, + 'secure': false, + 'expires': 'Mon, 10 Jun 2024 12:28:29 GMT' + } +}; + +test(function () { + var i, c, d, prop; + for (i in cookies) { + if (!cookies.hasOwnProperty(i)) continue; + phantom.addCookie(cookies[i]); + } + for (i in phantom.cookies) { + d = phantom.cookies[i]; + c = cookies[d.name]; + for (prop in c) { + if (!c.hasOwnProperty(prop)) continue; + if (c[prop] === null) { + assert_no_property(d, prop); + } else { + assert_own_property(d, prop); + assert_equals(c[prop], d[prop]); + } + } + } + +}, "optional cookie properties should not leak"); diff --git a/third_party/phantomjs/test/module/fs/basics.js b/third_party/phantomjs/test/module/fs/basics.js new file mode 100644 index 00000000000..c522ab7f299 --- /dev/null +++ b/third_party/phantomjs/test/module/fs/basics.js @@ -0,0 +1,220 @@ +// Basic Files API (read, write, remove, ...) + +var FILENAME = "temp-01.test", + FILENAME_COPY = FILENAME + ".copy", + FILENAME_MOVED = FILENAME + ".moved", + FILENAME_EMPTY = FILENAME + ".empty", + FILENAME_ENC = FILENAME + ".enc", + FILENAME_BIN = FILENAME + ".bin", + ABSENT = "absent-01.test"; + +var fs; + +setup(function () { + fs = require('fs'); + var f = fs.open(FILENAME, "w"); + + f.write("hello"); + f.writeLine(""); + f.writeLine("world"); + f.close(); +}); + +test(function () { + assert_is_true(fs.exists(FILENAME)); + // we might've gotten DOS line endings + assert_greater_than_equal(fs.size(FILENAME), "hello\nworld\n".length); + +}, "create a file with contents"); + +test(function () { + assert_is_false(fs.exists(FILENAME_EMPTY)); + fs.touch(FILENAME_EMPTY); + assert_is_true(fs.exists(FILENAME_EMPTY)); + assert_equals(fs.size(FILENAME_EMPTY), 0); + +}, "create (touch) an empty file"); + +test(function () { + var content = ""; + var f = fs.open(FILENAME, "r"); + this.add_cleanup(function () { f.close(); }); + + content = f.read(); + assert_equals(content, "hello\nworld\n"); + +}, "read content from a file"); + +test(function () { + var content = ""; + var f = fs.open(FILENAME, "r"); + this.add_cleanup(function () { f.close(); }); + + f.seek(3); + content = f.read(5); + assert_equals(content, "lo\nwo"); + +}, "read specific number of bytes from a specific position in a file"); + +test(function () { + var content = ""; + var f = fs.open(FILENAME, "rw+"); + this.add_cleanup(function () { f.close(); }); + + f.writeLine("asdf"); + content = f.read(); + assert_equals(content, "hello\nworld\nasdf\n"); + +}, "append content to a file"); + +test(function () { + var f = fs.open(FILENAME, "r"); + this.add_cleanup(function () { f.close(); }); + assert_equals(f.getEncoding(), "UTF-8"); + +}, "get the file encoding (default: UTF-8)"); + +test(function () { + var f = fs.open(FILENAME, { charset: "UTF-8", mode: "r" }); + this.add_cleanup(function () { f.close(); }); + assert_equals(f.getEncoding(), "UTF-8"); + + var g = fs.open(FILENAME, { charset: "SJIS", mode: "r" }); + this.add_cleanup(function () { g.close(); }); + assert_equals(g.getEncoding(), "Shift_JIS"); + +}, "set the encoding on open", {/* unsupported */expected_fail: true}); + +test(function () { + var f = fs.open(FILENAME, { charset: "UTF-8", mode: "r" }); + this.add_cleanup(function () { f.close(); }); + assert_equals(f.getEncoding(), "UTF-8"); + f.setEncoding("utf8"); + assert_equals(f.getEncoding(), "UTF-8"); + + var g = fs.open(FILENAME, { charset: "SJIS", mode: "r" }); + this.add_cleanup(function () { g.close(); }); + assert_equals(g.getEncoding(), "Shift_JIS"); + g.setEncoding("eucjp"); + assert_equals(g.getEncoding(), "EUC-JP"); + +}, "change the encoding using setEncoding", {/* unsupported */expected_fail: true}); + +test(function () { + assert_is_false(fs.exists(FILENAME_COPY)); + fs.copy(FILENAME, FILENAME_COPY); + assert_is_true(fs.exists(FILENAME_COPY)); + assert_equals(fs.read(FILENAME), fs.read(FILENAME_COPY)); + +}, "copy a file"); + +test(function () { + assert_is_true(fs.exists(FILENAME)); + var contentBeforeMove = fs.read(FILENAME); + fs.move(FILENAME, FILENAME_MOVED); + assert_is_false(fs.exists(FILENAME)); + assert_is_true(fs.exists(FILENAME_MOVED)); + assert_equals(fs.read(FILENAME_MOVED), contentBeforeMove); + +}, "move a file"); + +test(function () { + assert_is_true(fs.exists(FILENAME_MOVED)); + assert_is_true(fs.exists(FILENAME_COPY)); + assert_is_true(fs.exists(FILENAME_EMPTY)); + + fs.remove(FILENAME_MOVED); + fs.remove(FILENAME_COPY); + fs.remove(FILENAME_EMPTY); + + assert_is_false(fs.exists(FILENAME_MOVED)); + assert_is_false(fs.exists(FILENAME_COPY)); + assert_is_false(fs.exists(FILENAME_EMPTY)); + +}, "remove a file"); + +test(function () { + assert_throws("Unable to open file '"+ ABSENT +"'", + function () { fs.open(ABSENT, "r"); }); + + assert_throws("Unable to copy file '" + ABSENT + + "' at '" + FILENAME_COPY + "'", + function () { fs.copy(ABSENT, FILENAME_COPY); }); + +}, "operations on nonexistent files throw an exception", {/* unsupported */expected_fail: true}); + +test(function () { + var data = "ÄABCÖ"; + var data_b = String.fromCharCode( + 0xC3, 0x84, 0x41, 0x42, 0x43, 0xC3, 0x96); + + var f = fs.open(FILENAME_ENC, "w"); + this.add_cleanup(function () { + f.close(); + fs.remove(FILENAME_ENC); + }); + + f.write(data); + f.close(); + + f = fs.open(FILENAME_ENC, "r"); + assert_equals(f.read(), data); + + var g = fs.open(FILENAME_ENC, "rb"); + this.add_cleanup(function () { g.close(); }); + assert_equals(g.read(), data_b); + +}, "read/write UTF-8 text by default"); + +test(function () { + var data = "ピタゴラスイッチ"; + var data_b = String.fromCharCode( + 0x83, 0x73, 0x83, 0x5e, 0x83, 0x53, 0x83, 0x89, + 0x83, 0x58, 0x83, 0x43, 0x83, 0x62, 0x83, 0x60); + + var f = fs.open(FILENAME_ENC, { mode: "w", charset: "Shift_JIS" }); + this.add_cleanup(function () { + f.close(); + fs.remove(FILENAME_ENC); + }); + + f.write(data); + f.close(); + + f = fs.open(FILENAME_ENC, { mode: "r", charset: "Shift_JIS" }); + assert_equals(f.read(), data); + + var g = fs.open(FILENAME_ENC, "rb"); + this.add_cleanup(function () { g.close(); }); + assert_equals(g.read(), data_b); + +}, "read/write Shift-JIS text with options", {/* unsupported */expected_fail: true}); + +test(function () { + var data = String.fromCharCode(0, 1, 2, 3, 4, 5); + + var f = fs.open(FILENAME_BIN, "wb"); + this.add_cleanup(function () { + f.close(); + fs.remove(FILENAME_BIN); + }); + + f.write(data); + f.close(); + + f = fs.open(FILENAME_BIN, "rb"); + assert_equals(f.read(), data); + +}, "read/write binary data"); + +test(function () { + var data = String.fromCharCode(0, 1, 2, 3, 4, 5); + + fs.write(FILENAME_BIN, data, "b"); + this.add_cleanup(function () { + fs.remove(FILENAME_BIN); + }); + + assert_equals(fs.read(FILENAME_BIN, "b"), data); + +}, "read/write binary data (shortcuts)"); diff --git a/third_party/phantomjs/test/module/fs/fileattrs.js b/third_party/phantomjs/test/module/fs/fileattrs.js new file mode 100644 index 00000000000..f973abbaeb2 --- /dev/null +++ b/third_party/phantomjs/test/module/fs/fileattrs.js @@ -0,0 +1,91 @@ + +var fs = require('fs'); + +var ABSENT_DIR = "absentdir02", + ABSENT_FILE = "absentfile02", + TEST_DIR = "testdir02", + TEST_FILE = "temp-02.test", + TEST_FILE_PATH = fs.join(TEST_DIR, TEST_FILE), + TEST_CONTENT = "test content", + CONTENT_MULTIPLIER = 1024; + +test(function () { + assert_throws("Unable to read file '"+ ABSENT_FILE +"' size", + function () { fs.size(ABSENT_FILE); }); + + assert_equals(fs.lastModified(ABSENT_FILE), null); + +}, "size/date queries on nonexistent files", {/* unsupported */expected_fail: true}); + +test(function () { + // Round down to the nearest multiple of two seconds, because + // file timestamps might only have that much precision. + var before_creation = Math.floor(Date.now() / 2000) * 2000; + + var f = fs.open(TEST_FILE, "w"); + this.add_cleanup(function () { + if (f !== null) f.close(); + fs.remove(TEST_FILE); + }); + + for (var i = 0; i < CONTENT_MULTIPLIER; i++) { + f.write(TEST_CONTENT); + } + f.close(); f = null; + + // Similarly, but round _up_. + var after_creation = Math.ceil(Date.now() / 2000) * 2000; + + assert_equals(fs.size(TEST_FILE), + TEST_CONTENT.length * CONTENT_MULTIPLIER); + + var flm = fs.lastModified(TEST_FILE).getTime(); + + assert_greater_than_equal(flm, before_creation); + assert_less_than_equal(flm, after_creation); + +}, "size/date queries on existing files"); + +test(function () { + fs.makeDirectory(TEST_DIR); + this.add_cleanup(function () { fs.removeTree(TEST_DIR); }); + fs.write(TEST_FILE_PATH, TEST_CONTENT, "w"); + + assert_is_true(fs.exists(TEST_FILE_PATH)); + assert_is_true(fs.exists(TEST_DIR)); + assert_is_false(fs.exists(ABSENT_FILE)); + assert_is_false(fs.exists(ABSENT_DIR)); + + assert_is_true(fs.isDirectory(TEST_DIR)); + assert_is_false(fs.isDirectory(ABSENT_DIR)); + + + assert_is_true(fs.isFile(TEST_FILE_PATH)); + assert_is_false(fs.isFile(ABSENT_FILE)); + + var absPath = fs.absolute(TEST_FILE_PATH); + assert_is_false(fs.isAbsolute(TEST_FILE_PATH)); + assert_is_true(fs.isAbsolute(absPath)); + + assert_is_true(fs.isReadable(TEST_FILE_PATH)); + assert_is_true(fs.isWritable(TEST_FILE_PATH)); + assert_is_false(fs.isExecutable(TEST_FILE_PATH)); + + assert_is_false(fs.isReadable(ABSENT_FILE)); + assert_is_false(fs.isWritable(ABSENT_FILE)); + assert_is_false(fs.isExecutable(ABSENT_FILE)); + + assert_is_true(fs.isReadable(TEST_DIR)); + assert_is_true(fs.isWritable(TEST_DIR)); + assert_is_true(fs.isExecutable(TEST_DIR)); + + assert_is_false(fs.isReadable(ABSENT_DIR)); + assert_is_false(fs.isWritable(ABSENT_DIR)); + assert_is_false(fs.isExecutable(ABSENT_DIR)); + + assert_is_false(fs.isLink(TEST_DIR)); + assert_is_false(fs.isLink(TEST_FILE_PATH)); + assert_is_false(fs.isLink(ABSENT_DIR)); + assert_is_false(fs.isLink(ABSENT_FILE)); + +}, "file types and access modes"); diff --git a/third_party/phantomjs/test/module/fs/paths.js b/third_party/phantomjs/test/module/fs/paths.js new file mode 100644 index 00000000000..0910f20bb3d --- /dev/null +++ b/third_party/phantomjs/test/module/fs/paths.js @@ -0,0 +1,72 @@ + +var fs = require('fs'); +var system = require('system'); + +var TEST_DIR = "testdir", + TEST_FILE = "testfile", + START_CWD = fs.workingDirectory; + +test(function () { + assert_is_true(fs.makeDirectory(TEST_DIR)); + this.add_cleanup(function () { fs.removeTree(TEST_DIR); }); + + assert_is_true(fs.changeWorkingDirectory(TEST_DIR)); + this.add_cleanup(function () { fs.changeWorkingDirectory(START_CWD); }); + + fs.write(TEST_FILE, TEST_FILE, "w"); + var suffix = fs.join("", TEST_DIR, TEST_FILE), + abs = fs.absolute(".." + suffix), + lastIndex = abs.lastIndexOf(suffix); + + assert_not_equals(lastIndex, -1); + assert_equals(lastIndex + suffix.length, abs.length); + +}, "manipulation of current working directory"); + +test(function () { + + fs.copyTree(phantom.libraryPath, TEST_DIR); + this.add_cleanup(function () { fs.removeTree(TEST_DIR); }); + + assert_deep_equals(fs.list(phantom.libraryPath), fs.list(TEST_DIR)); + +}, "copying a directory tree"); + +test(function () { + assert_type_of(fs.readLink, 'function'); + // TODO: test the actual functionality once we can create symlinks. +}, "fs.readLink exists"); + +generate_tests(function fs_join_test (parts, expected) { + var actual = fs.join.apply(null, parts); + assert_equals(actual, expected); +}, [ + [ "fs.join: []", [], "." ], + [ "fs.join: nonsense", [[], null], "." ], + [ "fs.join: 1 element", [""], "." ], + [ "fs.join: 2 elements", ["", "a"], "/a" ], + [ "fs.join: 3 elements", ["a", "b", "c"], "a/b/c" ], + [ "fs.join: 4 elements", ["", "a", "b", "c"], "/a/b/c" ], + [ "fs.join: empty elements", ["", "a", "", "b", "", "c"], "/a/b/c" ], + [ "fs.join: empty elements 2", ["a", "", "b", "", "c"], "a/b/c" ] +]); + +generate_tests(function fs_split_test (input, expected) { + var path = input.join(fs.separator); + var actual = fs.split(path); + assert_deep_equals(actual, expected); +}, [ + [ "fs.split: absolute", + ["", "a", "b", "c", "d"], ["", "a", "b", "c", "d"] ], + [ "fs.split: absolute, trailing", + ["", "a", "b", "c", "d", ""], ["", "a", "b", "c", "d"] ], + [ "fs.split: non-absolute", + ["a", "b", "c", "d"], ["a", "b", "c", "d"] ], + [ "fs.split: non-absolute, trailing", + ["a", "b", "c", "d", ""], ["a", "b", "c", "d"] ], + [ "fs.split: repeated separators", + ["a", "", "", "", + "b", "", + "c", "", "", + "d", "", "", ""], ["a", "b", "c", "d"] ] +]); diff --git a/third_party/phantomjs/test/module/system/stdin.js b/third_party/phantomjs/test/module/system/stdin.js new file mode 100644 index 00000000000..8a08f2631cf --- /dev/null +++ b/third_party/phantomjs/test/module/system/stdin.js @@ -0,0 +1,22 @@ +//! stdin: Victor jagt zwölf Boxkämpfer quer über den großen Sylter Deich +//! stdin: いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす + +//^ first line: pangram in German +//^ second line: pan+isogram in hiragana (the Iroha) + +var stdin; +setup(function () { stdin = require("system").stdin; }); + +test(function () { + assert_equals(stdin.readLine(), + "Victor jagt zwölf Boxkämpfer quer über den großen Sylter Deich"); +}, "input line one (German)"); + +test(function () { + assert_equals(stdin.readLine(), + "いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす"); +}, "input line two (Japanese)"); + +test(function () { + assert_equals(stdin.readLine(), ""); +}, "input line three (EOF)"); diff --git a/third_party/phantomjs/test/module/system/stdout-err.js b/third_party/phantomjs/test/module/system/stdout-err.js new file mode 100644 index 00000000000..2281b42fdd8 --- /dev/null +++ b/third_party/phantomjs/test/module/system/stdout-err.js @@ -0,0 +1,14 @@ +//! no-harness +//! expect-stdout: Victor jagt zwölf Boxkämpfer quer über den großen Sylter Deich +//! expect-stderr: いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす + +//^ stdout: pangram in German +//^ stderr: pan+isogram in hiragana (the Iroha) + +phantom.onError = function () { phantom.exit(1); }; + +var sys = require("system"); + +sys.stdout.write("Victor jagt zwölf Boxkämpfer quer über den großen Sylter Deich\n"); +sys.stderr.write("いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす"); +phantom.exit(0); diff --git a/third_party/phantomjs/test/module/system/system.js b/third_party/phantomjs/test/module/system/system.js new file mode 100644 index 00000000000..ae5422d041b --- /dev/null +++ b/third_party/phantomjs/test/module/system/system.js @@ -0,0 +1,77 @@ +var system = require('system'); + +test(function () { + assert_type_of(system, 'object'); + assert_not_equals(system, null); +}, "system object"); + +test(function () { + assert_own_property(system, 'pid'); + assert_type_of(system.pid, 'number'); + assert_greater_than(system.pid, 0); +}, "system.pid"); + +test(function () { + assert_own_property(system, 'isSSLSupported'); + assert_type_of(system.isSSLSupported, 'boolean'); + assert_equals(system.isSSLSupported, true); +}, "system.isSSLSupported", {/* unsupported */expected_fail: true}); + +test(function () { + assert_own_property(system, 'args'); + assert_type_of(system.args, 'object'); + assert_instance_of(system.args, Array); + assert_greater_than_equal(system.args.length, 1); + + // args[0] will be the test harness. + assert_regexp_match(system.args[0], /\btestharness\.js$/); +}, "system.args", {/* unsupported */expected_fail: true}); + +test(function () { + assert_own_property(system, 'env'); + assert_type_of(system.env, 'object'); +}, "system.env"); + +test(function () { + assert_own_property(system, 'platform'); + assert_type_of(system.platform, 'string'); + assert_equals(system.platform, 'phantomjs'); +}, "system.platform"); + +test(function () { + assert_own_property(system, 'os'); + assert_type_of(system.os, 'object'); + + assert_type_of(system.os.architecture, 'string'); + assert_type_of(system.os.name, 'string'); + assert_type_of(system.os.version, 'string'); + + if (system.os.name === 'mac') { + // release is x.y.z with x = 10 for Snow Leopard and 14 for Yosemite + assert_type_of(system.os.release, 'string'); + assert_greater_than_equal(parseInt(system.os.release, 10), 10); + } +}, "system.os"); + +test(function () { + assert_type_of(system.stdin, 'object'); + assert_type_of(system.stdin.read, 'function'); + assert_type_of(system.stdin.readLine, 'function'); + assert_type_of(system.stdin.close, 'function'); +}, "system.stdin"); + +test(function () { + assert_type_of(system.stdout, 'object'); + assert_type_of(system.stdout.write, 'function'); + assert_type_of(system.stdout.writeLine, 'function'); + assert_type_of(system.stdout.flush, 'function'); + assert_type_of(system.stdout.close, 'function'); +}, "system.stdout"); + +test(function () { + assert_type_of(system.stderr, 'object'); + assert_type_of(system.stderr.write, 'function'); + assert_type_of(system.stderr.writeLine, 'function'); + assert_type_of(system.stderr.flush, 'function'); + assert_type_of(system.stderr.close, 'function'); +}, "system.stderr"); diff --git a/third_party/phantomjs/test/module/webpage/abort-network-request.js b/third_party/phantomjs/test/module/webpage/abort-network-request.js new file mode 100644 index 00000000000..e6718ff7435 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/abort-network-request.js @@ -0,0 +1,37 @@ +//! unsupported +var webpage = require('webpage'); + +async_test(function () { + var page = webpage.create(); + var abortCount = 0; + var errorCount = 0; + var abortedIds = {}; + var urlToBlockRegExp = /logo\.png$/i; + + page.onResourceRequested = this.step_func(function(requestData, request) { + assert_type_of(request, 'object'); + assert_type_of(request.abort, 'function'); + if (urlToBlockRegExp.test(requestData.url)) { + request.abort(); + ++abortCount; + abortedIds[requestData.id] = 1; + } + }); + page.onResourceError = this.step_func(function(error) { + // We can't match up errors to requests by URL because error.url will + // be the empty string in this case. FIXME. + assert_own_property(abortedIds, error.id); + ++errorCount; + }); + page.onResourceReceived = this.step_func(function(response) { + assert_regexp_not_match(response.url, urlToBlockRegExp); + }); + + page.open(TEST_HTTP_BASE + 'logo.html', + this.step_func_done(function (status) { + assert_equals(status, 'success'); + assert_equals(abortCount, 1); + assert_equals(errorCount, 1); + })); + +}, "can abort network requests"); diff --git a/third_party/phantomjs/test/module/webpage/add-header.js b/third_party/phantomjs/test/module/webpage/add-header.js new file mode 100644 index 00000000000..5594f4e2834 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/add-header.js @@ -0,0 +1,25 @@ +//! unsupported +async_test(function () { + var webpage = require('webpage'); + + // NOTE: HTTP header names are case-insensitive. Our test server + // returns the name in lowercase. + + var page = webpage.create(); + assert_type_of(page.customHeaders, 'object'); + assert_deep_equals(page.customHeaders, {}); + + page.onResourceRequested = this.step_func(function(requestData, request) { + assert_type_of(request.setHeader, 'function'); + request.setHeader('CustomHeader', 'CustomValue'); + }); + page.open(TEST_HTTP_BASE + 'echo', this.step_func_done(function (status) { + var json, headers; + assert_equals(status, 'success'); + json = JSON.parse(page.plainText); + headers = json.headers; + assert_own_property(headers, 'customheader'); + assert_equals(headers.customheader, 'CustomValue'); + })); + +}, "add custom headers in onResourceRequested"); diff --git a/third_party/phantomjs/test/module/webpage/callback.js b/third_party/phantomjs/test/module/webpage/callback.js new file mode 100644 index 00000000000..0c14c44105e --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/callback.js @@ -0,0 +1,16 @@ +test(function () { + var page = require('webpage').create(); + + var msgA = "a", + msgB = "b", + result, + expected = msgA + msgB; + page.onCallback = function(a, b) { + return a + b; + }; + result = page.evaluate(function(a, b) { + return window.callPhantom(a, b); + }, msgA, msgB); + + assert_equals(result, expected); +}, "page.onCallback"); diff --git a/third_party/phantomjs/test/module/webpage/capture-content.js b/third_party/phantomjs/test/module/webpage/capture-content.js new file mode 100644 index 00000000000..99f64ad57c4 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/capture-content.js @@ -0,0 +1,50 @@ +//! unsupported +var content; +setup(function () { + var fs = require('fs'); + // libraryPath is test/module/webpage + content = fs.read(fs.join(phantom.libraryPath, + "../../www/hello.html")); +}); + +// XFAIL: This feature had to be backed out for breaking WebSockets. +async_test(function () { + var page = require('webpage').create(); + var lastChunk = ""; + var bodySize = 0; + page.captureContent = ['.*']; + // Not a step function because it may be called several times + // and doesn't need to make assertions. + page.onResourceReceived = function (resource) { + lastChunk = resource.body; + bodySize = resource.bodySize; + }; + page.open(TEST_HTTP_BASE + "hello.html", + this.step_func_done(function (status) { + assert_equals(status, "success"); + assert_equals(bodySize, content.length); + assert_equals(lastChunk, content); + })); + +}, "onResourceReceived sees the body if captureContent is activated", + { expected_fail: true } +); + +async_test(function () { + var page = require('webpage').create(); + var lastChunk = ""; + var bodySize = 0; + page.captureContent = ['/some/other/url']; + // Not a step function because it may be called several times + // and doesn't need to make assertions. + page.onResourceReceived = function (resource) { + lastChunk = resource.body; + bodySize = resource.bodySize; + }; + page.open(TEST_HTTP_BASE + "hello.html", + this.step_func_done(function (status) { + assert_equals(status, "success"); + assert_equals(bodySize, 0); + assert_equals(lastChunk, ""); + })); +}, "onResourceReceived doesn't see the body if captureContent doesn't match"); diff --git a/third_party/phantomjs/test/module/webpage/change-request-encoded-url.js b/third_party/phantomjs/test/module/webpage/change-request-encoded-url.js new file mode 100644 index 00000000000..b6d5327b280 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/change-request-encoded-url.js @@ -0,0 +1,27 @@ +//! unsupported +var webpage = require('webpage'); + +async_test(function () { + var page = webpage.create(); + + var url = TEST_HTTP_BASE + "cdn-cgi/pe/bag?r%5B%5D="+ + "http%3A%2F%2Fwww.example.org%2Fcdn-cgi%2Fnexp%2F"+ + "abv%3D927102467%2Fapps%2Fabetterbrowser.js"; + var receivedUrl; + + page.onResourceRequested = this.step_func(function(requestData, request) { + request.changeUrl(requestData.url); + }); + + page.onResourceReceived = this.step_func(function(data) { + if (data.stage === 'end') { + receivedUrl = data.url; + } + }); + + page.open(url, this.step_func_done(function (status) { + assert_equals(status, 'success'); + assert_equals(receivedUrl, url); + })); + +}, "encoded URLs properly round-trip through request.changeUrl"); diff --git a/third_party/phantomjs/test/module/webpage/change-request-url.js b/third_party/phantomjs/test/module/webpage/change-request-url.js new file mode 100644 index 00000000000..ea8e7e8a583 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/change-request-url.js @@ -0,0 +1,40 @@ +//! unsupported +var webpage = require('webpage'); + +async_test(function () { + + var page = webpage.create(); + var urlToChange = TEST_HTTP_BASE + 'logo.png'; + var alternativeUrl = TEST_HTTP_BASE + 'phantomjs-logo.gif'; + var startStage = 0; + var endStage = 0; + + page.onResourceRequested = this.step_func(function(requestData, request) { + if (requestData.url === urlToChange) { + assert_type_of(request, 'object'); + assert_type_of(request.changeUrl, 'function'); + request.changeUrl(alternativeUrl); + } + }); + + page.onResourceReceived = this.step_func(function(data) { + if (data.url === alternativeUrl && data.stage === 'start') { + ++startStage; + } + if (data.url === alternativeUrl && data.stage === 'end') { + ++endStage; + } + }); + + page.open(TEST_HTTP_BASE + 'logo.html', + this.step_func_done(function (status) { + assert_equals(status, 'success'); + assert_equals(startStage, 1); + assert_equals(endStage, 1); + + // The page HTML should still refer to the original image. + assert_regexp_match(page.content, /logo\.png/); + assert_regexp_not_match(page.content, /logo\.gif/); + })); + +}, "request.changeUrl"); diff --git a/third_party/phantomjs/test/module/webpage/cjk-text-codecs.js b/third_party/phantomjs/test/module/webpage/cjk-text-codecs.js new file mode 100644 index 00000000000..afd653c6982 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/cjk-text-codecs.js @@ -0,0 +1,33 @@ +var webpage = require('webpage'); + +function test_one(text) { + var t = async_test(text.codec); + t.step(function () { + var page = webpage.create(); + page.open(text.url, t.step_func_done(function () { + var decodedText = page.evaluate(function() { + return document.querySelector('pre').innerText; + }); + var regex = '^' + text.reference + '$'; + assert_regexp_match(text.reference, new RegExp(regex)); + })); + }); +} + +function Text(codec, base64, reference) { + this.codec = codec; + this.base64 = base64; + this.reference = reference; + this.url = 'data:text/plain;charset=' + this.codec + + ';base64,' + this.base64; +} + +[ + new Text('Shift_JIS', 'g3SDQIOTg2eDgA==', 'ファントム'), + new Text('EUC-JP', 'pdWloaXzpcil4A0K', 'ファントム'), + new Text('ISO-2022-JP', 'GyRCJVUlISVzJUglYBsoQg0K', 'ファントム'), + new Text('Big5', 'pNu2SA0K', '幻象'), + new Text('GBK', 'u8PP8w0K', '幻象'), + new Text('EUC-KR', 'yK+/tQ==', '환영'), +] + .forEach(test_one); diff --git a/third_party/phantomjs/test/module/webpage/clip-rect.js b/third_party/phantomjs/test/module/webpage/clip-rect.js new file mode 100644 index 00000000000..46c9e40d840 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/clip-rect.js @@ -0,0 +1,19 @@ +var webpage = require('webpage'); + +test(function () { + var defaultPage = webpage.create(); + assert_deep_equals(defaultPage.clipRect, {height:0,left:0,top:0,width:0}); +}, "default page.clipRect"); + +test(function () { + var options = { + clipRect: { + height: 100, + left: 10, + top: 20, + width: 200 + } + }; + var customPage = webpage.create(options); + assert_deep_equals(customPage.clipRect, options.clipRect); +}, "custom page.clipRect"); diff --git a/third_party/phantomjs/test/module/webpage/construction-with-options.js b/third_party/phantomjs/test/module/webpage/construction-with-options.js new file mode 100644 index 00000000000..42d67371d49 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/construction-with-options.js @@ -0,0 +1,59 @@ +//! unsupported +test(function () { + var opts = {}, + page = new WebPage(opts); + assert_type_of(page, 'object'); + assert_not_equals(page, null); +}, "webpage constructor accepts an opts object"); + +async_test(function () { + var opts = { + onConsoleMessage: this.step_func_done(function (msg) { + assert_equals(msg, "test log"); + }) + }; + var page = new WebPage(opts); + assert_equals(page.onConsoleMessage, opts.onConsoleMessage); + page.evaluate(function () {console.log('test log');}); + +}, "specifying onConsoleMessage with opts"); + +async_test(function () { + var page_opened = false; + var opts = { + onLoadStarted: this.step_func_done(function (msg) { + assert_is_true(page_opened); + }) + }; + var page = new WebPage(opts); + assert_equals(page.onLoadStarted, opts.onLoadStarted); + page_opened = true; + page.open("about:blank"); + +}, "specifying onLoadStarted with opts"); + +async_test(function () { + var page_opened = false; + var opts = { + onLoadFinished: this.step_func_done(function (msg) { + assert_is_true(page_opened); + }) + }; + var page = new WebPage(opts); + assert_equals(page.onLoadFinished, opts.onLoadFinished); + page_opened = true; + page.open("about:blank"); + +}, "specifying onLoadFinished with opts"); + +// FIXME: Actually test that the timeout is effective. +test(function () { + var opts = { + settings: { + timeout: 100 // time in ms + } + }; + var page = new WebPage(opts); + assert_equals(page.settings.timeout, opts.settings.timeout); + +}, "specifying timeout with opts"); diff --git a/third_party/phantomjs/test/module/webpage/contextclick-event.js b/third_party/phantomjs/test/module/webpage/contextclick-event.js new file mode 100644 index 00000000000..af046110d89 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/contextclick-event.js @@ -0,0 +1,33 @@ +//! unsupported +test(function () { + var page = require('webpage').create(); + + page.evaluate(function() { + window.addEventListener('contextmenu', function(event) { + window.loggedEvent = window.loggedEvent || {}; + window.loggedEvent.contextmenu = event; + }, false); + }); + page.sendEvent('contextmenu', 42, 217); + + var event = page.evaluate(function() { + return window.loggedEvent; + }); + assert_equals(event.contextmenu.clientX, 42); + assert_equals(event.contextmenu.clientY, 217); + + // click with modifier key + page.evaluate(function() { + window.addEventListener('contextmenu', function(event) { + window.loggedEvent = window.loggedEvent || {}; + window.loggedEvent.contextmenu = event; + }, false); + }); + page.sendEvent('contextmenu', 100, 100, 'left', page.event.modifier.shift); + + var event = page.evaluate(function() { + return window.loggedEvent.contextmenu; + }); + assert_is_true(event.shiftKey); + +}, "context click events"); diff --git a/third_party/phantomjs/test/module/webpage/cookies.js b/third_party/phantomjs/test/module/webpage/cookies.js new file mode 100644 index 00000000000..e1137a5dcd0 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/cookies.js @@ -0,0 +1,112 @@ +//! unsupported +async_test(function () { + var url = TEST_HTTP_BASE + "echo"; + var page = new WebPage(); + + page.cookies = [{ + 'name' : 'Valid-Cookie-Name', + 'value' : 'Valid-Cookie-Value', + 'domain' : 'localhost', + 'path' : '/', + 'httponly' : true, + 'secure' : false + },{ + 'name' : 'Valid-Cookie-Name-Sec', + 'value' : 'Valid-Cookie-Value-Sec', + 'domain' : 'localhost', + 'path' : '/', + 'httponly' : true, + 'secure' : false, + 'expires' : Date.now() + 3600 //< expires in 1h + }]; + + page.open(url, this.step_func(function (status) { + assert_equals(status, "success"); + var headers = JSON.parse(page.plainText).headers; + assert_own_property(headers, 'cookie'); + assert_regexp_match(headers.cookie, /\bValid-Cookie-Name\b/); + assert_regexp_match(headers.cookie, /\bValid-Cookie-Value\b/); + assert_regexp_match(headers.cookie, /\bValid-Cookie-Name-Sec\b/); + assert_regexp_match(headers.cookie, /\bValid-Cookie-Value-Sec\b/); + assert_not_equals(page.cookies.length, 0); + + page.cookies = []; + page.open(url, this.step_func_done(function (status) { + assert_equals(status, "success"); + var headers = JSON.parse(page.plainText).headers; + assert_no_property(headers, 'cookie'); + })); + })); +}, "adding and deleting cookies with page.cookies"); + +async_test(function () { + var url = TEST_HTTP_BASE + "echo"; + var page = new WebPage(); + + page.addCookie({ + 'name' : 'Added-Cookie-Name', + 'value' : 'Added-Cookie-Value', + 'domain' : 'localhost' + }); + + page.open(url, this.step_func(function (status) { + assert_equals(status, "success"); + var headers = JSON.parse(page.plainText).headers; + assert_own_property(headers, 'cookie'); + assert_regexp_match(headers.cookie, /\bAdded-Cookie-Name\b/); + assert_regexp_match(headers.cookie, /\bAdded-Cookie-Value\b/); + + page.deleteCookie("Added-Cookie-Name"); + page.open(url, this.step_func_done(function (status) { + assert_equals(status, "success"); + var headers = JSON.parse(page.plainText).headers; + assert_no_property(headers, 'cookie'); + })); + })); + +}, "adding and deleting cookies with page.addCookie and page.deleteCookie"); + +async_test(function () { + var url = TEST_HTTP_BASE + "echo"; + var page = new WebPage(); + + page.cookies = [ + { // domain mismatch. + 'name' : 'Invalid-Cookie-Name-1', + 'value' : 'Invalid-Cookie-Value-1', + 'domain' : 'foo.example' + },{ // path mismatch: the cookie will be set, + // but won't be visible from the given URL (not same path). + 'name' : 'Invalid-Cookie-Name-2', + 'value' : 'Invalid-Cookie-Value-2', + 'domain' : 'localhost', + 'path' : '/bar' + },{ // cookie expired. + 'name' : 'Invalid-Cookie-Name-3', + 'value' : 'Invalid-Cookie-Value-3', + 'domain' : 'localhost', + 'expires' : 'Sat, 01 Jan 2000 00:00:00 GMT' + },{ // https only: the cookie will be set, + // but won't be visible from the given URL (not https). + 'name' : 'Invalid-Cookie-Name-4', + 'value' : 'Invalid-Cookie-Value-4', + 'domain' : 'localhost', + 'secure' : true + },{ // cookie expired (date in "sec since epoch"). + 'name' : 'Invalid-Cookie-Name-5', + 'value' : 'Invalid-Cookie-Value-5', + 'domain' : 'localhost', + 'expires' : new Date().getTime() - 1 //< date in the past + },{ // cookie expired (date in "sec since epoch" - using "expiry"). + 'name' : 'Invalid-Cookie-Name-6', + 'value' : 'Invalid-Cookie-Value-6', + 'domain' : 'localhost', + 'expiry' : new Date().getTime() - 1 //< date in the past + }]; + + page.open(url, this.step_func_done(function (status) { + assert_equals(status, "success"); + var headers = JSON.parse(page.plainText).headers; + assert_no_property(headers, 'cookie'); + })); +}, "page.cookies provides cookies only to appropriate requests"); diff --git a/third_party/phantomjs/test/module/webpage/custom-headers.js b/third_party/phantomjs/test/module/webpage/custom-headers.js new file mode 100644 index 00000000000..0aaefd79dc7 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/custom-headers.js @@ -0,0 +1,30 @@ +async_test(function () { + var webpage = require('webpage'); + var page = webpage.create(); + assert_type_of(page.customHeaders, 'object'); + assert_deep_equals(page.customHeaders, {}); + + // NOTE: HTTP header names are case-insensitive. Our test server + // returns the name in lowercase. + page.customHeaders = { + 'Custom-Key': 'Custom-Value', + 'User-Agent': 'Overriden-UA', + 'Referer': 'http://example.com/' + }; + page.open(TEST_HTTP_BASE + 'echo', this.step_func_done(function (status) { + var json, headers; + assert_equals(status, 'success'); + json = JSON.parse(page.plainText); + assert_type_of(json, 'object'); + headers = json.headers; + assert_type_of(headers, 'object'); + + assert_own_property(headers, 'custom-key'); + assert_own_property(headers, 'user-agent'); + assert_own_property(headers, 'referer'); + assert_equals(headers['custom-key'], 'Custom-Value'); + assert_equals(headers['user-agent'], 'Overriden-UA'); + assert_equals(headers['referer'], 'http://example.com/'); + })); + +}, "adding custom headers with page.customHeaders"); diff --git a/third_party/phantomjs/test/module/webpage/evaluate-broken-json.js b/third_party/phantomjs/test/module/webpage/evaluate-broken-json.js new file mode 100644 index 00000000000..1f1d263598e --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/evaluate-broken-json.js @@ -0,0 +1,14 @@ +test(function () { + var webpage = require('webpage'); + var page = webpage.create(); + + // Hijack JSON.parse to something completely useless. + page.content = ''; + + var result = page.evaluate(function(obj) { + return obj.value * obj.value; + }, { value: 4 }); + + assert_equals(result, 16); + +}, "page script should not interfere with page.evaluate"); diff --git a/third_party/phantomjs/test/module/webpage/file-upload.js b/third_party/phantomjs/test/module/webpage/file-upload.js new file mode 100644 index 00000000000..711ef30c82c --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/file-upload.js @@ -0,0 +1,56 @@ +//! unsupported + +// Note: uses various files in module/webpage as things to be uploaded. +// Which files they are doesn't matter. + +var page; +setup(function () { + page = new WebPage(); + page.content = + '\n' + + '\n' + + '' + + ''; + page.uploadFile("#file", "file-upload.js"); + page.uploadFile("#file2", "file-upload.js"); + page.uploadFile("#file3", ["file-upload.js", "object.js"]); +}); + +function test_one_elt(id, names) { + var files = page.evaluate(function (id) { + var elt = document.getElementById(id); + var rv = []; + for (var i = 0; i < elt.files.length; i++) { + rv.push(elt.files[i].fileName); + } + return rv; + }, id); + assert_deep_equals(files, names); +} + +generate_tests(test_one_elt, [ + ["single upload single file", "file", ["file-upload.js"]], + ["multiple upload single file", "file2", ["file-upload.js"]], + ["multiple upload multiple file", "file3", ["file-upload.js", "object.js"]], +], { expected_fail: true }); + +async_test(function () { + page.onFilePicker = this.step_func(function (oldFile) { + assert_equals(oldFile, ""); + return "no-plugin.js"; + }); + + test_one_elt("file4", []); + + page.evaluate(function () { + var fileUp = document.querySelector("#file4"); + var ev = document.createEvent("MouseEvents"); + ev.initEvent("click", true, true); + fileUp.dispatchEvent(ev); + }); + + setTimeout(this.step_func_done(function () { + test_one_elt("file4", ["no-plugin.js"]); + }, 0)); + +}, "page.onFilePicker", { expected_fail: true }); diff --git a/third_party/phantomjs/test/module/webpage/frame-switching-deprecated.js b/third_party/phantomjs/test/module/webpage/frame-switching-deprecated.js new file mode 100644 index 00000000000..f20938c9a6f --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/frame-switching-deprecated.js @@ -0,0 +1,69 @@ +//! unsupported +async_test(function () { + var p = require("webpage").create(); + + function pageTitle(page) { + return page.evaluate(function(){ + return window.document.title; + }); + } + + function setPageTitle(page, newTitle) { + page.evaluate(function(newTitle){ + window.document.title = newTitle; + }, newTitle); + } + + function testFrameSwitchingDeprecated() { + assert_equals(pageTitle(p), "index"); + assert_equals(p.currentFrameName(), ""); + assert_equals(p.childFramesCount(), 2); + assert_deep_equals(p.childFramesName(), ["frame1", "frame2"]); + setPageTitle(p, pageTitle(p) + "-visited"); + + assert_is_true(p.switchToChildFrame("frame1")); + assert_equals(pageTitle(p), "frame1"); + assert_equals(p.currentFrameName(), "frame1"); + assert_equals(p.childFramesCount(), 2); + assert_deep_equals(p.childFramesName(), ["frame1-1", "frame1-2"]); + setPageTitle(p, pageTitle(p) + "-visited"); + + assert_is_true(p.switchToChildFrame("frame1-2")); + assert_equals(pageTitle(p), "frame1-2"); + assert_equals(p.currentFrameName(), "frame1-2"); + assert_equals(p.childFramesCount(), 0); + assert_deep_equals(p.childFramesName(), []); + setPageTitle(p, pageTitle(p) + "-visited"); + + assert_is_true(p.switchToParentFrame()); + assert_equals(pageTitle(p), "frame1-visited"); + assert_equals(p.currentFrameName(), "frame1"); + assert_equals(p.childFramesCount(), 2); + assert_deep_equals(p.childFramesName(), ["frame1-1", "frame1-2"]); + + assert_is_true(p.switchToChildFrame(0)); + assert_equals(pageTitle(p), "frame1-1"); + assert_equals(p.currentFrameName(), "frame1-1"); + assert_equals(p.childFramesCount(), 0); + assert_deep_equals(p.childFramesName(), []); + + assert_equals(p.switchToMainFrame(), undefined); + assert_equals(pageTitle(p), "index-visited"); + assert_equals(p.currentFrameName(), ""); + assert_equals(p.childFramesCount(), 2); + assert_deep_equals(p.childFramesName(), ["frame1", "frame2"]); + + assert_is_true(p.switchToChildFrame("frame2")); + assert_equals(pageTitle(p), "frame2"); + assert_equals(p.currentFrameName(), "frame2"); + assert_equals(p.childFramesCount(), 3); + assert_deep_equals(p.childFramesName(), + ["frame2-1", "frame2-2", "frame2-3"]); + } + + p.open(TEST_HTTP_BASE + "frameset", this.step_func_done(function (s) { + assert_equals(s, "success"); + testFrameSwitchingDeprecated(); + })); + +}, "frame switching deprecated API"); diff --git a/third_party/phantomjs/test/module/webpage/frame-switching.js b/third_party/phantomjs/test/module/webpage/frame-switching.js new file mode 100644 index 00000000000..295bf37776d --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/frame-switching.js @@ -0,0 +1,98 @@ +//! unsupported +async_test(function () { + var p = require("webpage").create(); + + function pageTitle(page) { + return page.evaluate(function(){ + return window.document.title; + }); + } + + function setPageTitle(page, newTitle) { + page.evaluate(function(newTitle){ + window.document.title = newTitle; + }, newTitle); + } + + function testFrameSwitching() { + assert_equals(pageTitle(p), "index"); + assert_equals(p.frameName, ""); + assert_equals(p.framesCount, 2); + assert_deep_equals(p.framesName, ["frame1", "frame2"]); + setPageTitle(p, pageTitle(p) + "-visited"); + + assert_is_true(p.switchToFrame("frame1")); + assert_equals(pageTitle(p), "frame1"); + assert_equals(p.frameName, "frame1"); + assert_equals(p.framesCount, 2); + assert_deep_equals(p.framesName, ["frame1-1", "frame1-2"]); + setPageTitle(p, pageTitle(p) + "-visited"); + + assert_is_true(p.switchToFrame("frame1-2")); + assert_equals(pageTitle(p), "frame1-2"); + assert_equals(p.frameName, "frame1-2"); + assert_equals(p.framesCount, 0); + assert_deep_equals(p.framesName, []); + setPageTitle(p, pageTitle(p) + "-visited"); + + assert_is_true(p.switchToParentFrame()); + assert_equals(pageTitle(p), "frame1-visited"); + assert_equals(p.frameName, "frame1"); + assert_equals(p.framesCount, 2); + assert_deep_equals(p.framesName, ["frame1-1", "frame1-2"]); + + assert_is_true(p.switchToFrame(0)); + assert_equals(pageTitle(p), "frame1-1"); + assert_equals(p.frameName, "frame1-1"); + assert_equals(p.framesCount, 0); + assert_deep_equals(p.framesName, []); + + assert_equals(p.switchToMainFrame(), undefined); + assert_equals(pageTitle(p), "index-visited"); + assert_equals(p.frameName, ""); + assert_equals(p.framesCount, 2); + assert_deep_equals(p.framesName, ["frame1", "frame2"]); + + assert_is_true(p.switchToFrame("frame2")); + assert_equals(pageTitle(p), "frame2"); + assert_equals(p.frameName, "frame2"); + assert_equals(p.framesCount, 3); + assert_deep_equals(p.framesName, + ["frame2-1", "frame2-2", "frame2-3"]); + + assert_equals(p.focusedFrameName, ""); + + p.evaluate(function(){ + window.focus(); + }); + assert_equals(p.focusedFrameName, "frame2"); + + assert_is_true(p.switchToFrame("frame2-1")); + p.evaluate(function(){ + window.focus(); + }); + assert_equals(p.focusedFrameName, "frame2-1"); + + assert_equals(p.switchToMainFrame(), undefined); + p.evaluate(function(){ + window.focus(); + }); + assert_equals(p.focusedFrameName, ""); + + p.evaluate(function(){ + window.frames[0].focus(); + }); + assert_equals(p.focusedFrameName, "frame1"); + assert_equals(p.frameName, ""); + + assert_equals(p.switchToFocusedFrame(), undefined); + assert_equals(p.frameName, "frame1"); + } + + p.open(TEST_HTTP_BASE + "frameset", + this.step_func_done(function (s) { + assert_equals(s, "success"); + testFrameSwitching(); + })); + +}, "frame switching API"); diff --git a/third_party/phantomjs/test/module/webpage/https-bad-cert.js b/third_party/phantomjs/test/module/webpage/https-bad-cert.js new file mode 100644 index 00000000000..fcdb7d4878b --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/https-bad-cert.js @@ -0,0 +1,15 @@ +async_test(function () { + // This loads the same page as https-good-cert.js, but does not + // tell PhantomJS to trust the snakeoil certificate that the test + // HTTPS server uses, so it should fail. + + var page = require('webpage').create(); + var url = TEST_HTTPS_BASE; + page.onResourceError = this.step_func(function (err) { + assert_equals(err.url, url); + assert_equals(err.errorString, "SSL handshake failed"); + }); + page.open(url, this.step_func_done(function (status) { + assert_not_equals(status, "success"); + })); +}, "should fail to load an HTTPS webpage with a self-signed certificate"); diff --git a/third_party/phantomjs/test/module/webpage/https-good-cert.js b/third_party/phantomjs/test/module/webpage/https-good-cert.js new file mode 100644 index 00000000000..af9cf075c83 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/https-good-cert.js @@ -0,0 +1,14 @@ +//! unsupported +//! snakeoil +async_test(function () { + // This loads the same page as https-bad-cert.js, but tells + // PhantomJS to trust the snakeoil certificate + // that the test HTTPS server uses, so it should succeed. + + var page = require('webpage').create(); + var url = TEST_HTTPS_BASE; + page.onResourceError = this.unreached_func(); + page.open(url, this.step_func_done(function (status) { + assert_equals(status, "success"); + })); +}, "loading an HTTPS webpage"); diff --git a/third_party/phantomjs/test/module/webpage/includejs.js b/third_party/phantomjs/test/module/webpage/includejs.js new file mode 100644 index 00000000000..df3d922ebb2 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/includejs.js @@ -0,0 +1,42 @@ +var webpage = require('webpage'); + +async_test(function () { + var page = webpage.create(); + page.open(TEST_HTTP_BASE + 'includejs1.html', + this.step_func(function (status) { + assert_equals(status, 'success'); + page.includeJs(TEST_HTTP_BASE + 'includejs.js', + this.step_func_done(function () { + var title = page.evaluate('getTitle'); + assert_equals(title, 'i am includejs one'); + })); + })); + +}, "including JS in a page"); + +async_test(function () { + var page = webpage.create(); + var already = false; + page.open(TEST_HTTP_BASE + 'includejs1.html', + this.step_func(function (status) { + assert_equals(status, 'success'); + page.includeJs(TEST_HTTP_BASE + 'includejs.js', + this.step_func(function () { + assert_is_false(already); + already = true; + var title = page.evaluate('getTitle'); + assert_equals(title, 'i am includejs one'); + page.open(TEST_HTTP_BASE + 'includejs2.html', + this.step_func(function (status) { + assert_equals(status, 'success'); + page.includeJs(TEST_HTTP_BASE + 'includejs.js', + this.step_func_done(function () { + assert_is_true(already); + var title = page.evaluate('getTitle'); + assert_equals(title, 'i am includejs two'); + })); + })); + })); + })); + +}, "after-inclusion callbacks should fire only once"); diff --git a/third_party/phantomjs/test/module/webpage/keydown-event.js b/third_party/phantomjs/test/module/webpage/keydown-event.js new file mode 100644 index 00000000000..12bca8ab0b3 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/keydown-event.js @@ -0,0 +1,21 @@ +//! unsupported +test(function () { + var webpage = require('webpage'); + + var page = webpage.create(); + + page.evaluate(function() { + window.addEventListener('keydown', function(event) { + window.loggedEvent = window.loggedEvent || []; + window.loggedEvent.push(event); + }, false); + }); + + page.sendEvent('keydown', page.event.key.A); + var loggedEvent = page.evaluate(function() { + return window.loggedEvent; + }); + + assert_equals(loggedEvent.length, 1); + assert_equals(loggedEvent[0].which, page.event.key.A); +}, "key-down events"); diff --git a/third_party/phantomjs/test/module/webpage/keypress-event.js b/third_party/phantomjs/test/module/webpage/keypress-event.js new file mode 100644 index 00000000000..e781fdad5a6 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/keypress-event.js @@ -0,0 +1,66 @@ +//! unsupported +test(function () { + var webpage = require('webpage'); + + var page = webpage.create(); + + page.evaluate(function() { + window.addEventListener('keypress', function(event) { + window.loggedEvent = window.loggedEvent || []; + window.loggedEvent.push(event); + }, false); + }); + + page.sendEvent('keypress', page.event.key.C); + var loggedEvent = page.evaluate(function() { + return window.loggedEvent; + }); + + assert_equals(loggedEvent.length, 1); + assert_equals(loggedEvent[0].which, page.event.key.C); + + + // Send keypress events to an input element and observe the effect. + + page.content = ''; + page.evaluate(function() { + document.querySelector('input').focus(); + }); + + function getText() { + return page.evaluate(function() { + return document.querySelector('input').value; + }); + } + + page.sendEvent('keypress', page.event.key.A); + assert_equals(getText(), 'A'); + page.sendEvent('keypress', page.event.key.B); + assert_equals(getText(), 'AB'); + page.sendEvent('keypress', page.event.key.Backspace); + assert_equals(getText(), 'A'); + page.sendEvent('keypress', page.event.key.Backspace); + assert_equals(getText(), ''); + + page.sendEvent('keypress', 'XYZ'); + assert_equals(getText(), 'XYZ'); + + // Special character: A with umlaut + page.sendEvent('keypress', 'ä'); + assert_equals(getText(), 'XYZä'); + + // 0x02000000 is the Shift modifier. + page.sendEvent('keypress', page.event.key.Home, null, null, 0x02000000); + page.sendEvent('keypress', page.event.key.Delete); + assert_equals(getText(), ''); + + // Cut and Paste + // 0x04000000 is the Control modifier. + page.sendEvent('keypress', 'ABCD'); + assert_equals(getText(), 'ABCD'); + page.sendEvent('keypress', page.event.key.Home, null, null, 0x02000000); + page.sendEvent('keypress', 'x', null, null, 0x04000000); + assert_equals(getText(), ''); + page.sendEvent('keypress', 'v', null, null, 0x04000000); + assert_equals(getText(), 'ABCD'); +}, "key press events"); diff --git a/third_party/phantomjs/test/module/webpage/keyup-event.js b/third_party/phantomjs/test/module/webpage/keyup-event.js new file mode 100644 index 00000000000..c22fe9990ff --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/keyup-event.js @@ -0,0 +1,21 @@ +//! unsupported +test(function () { + var webpage = require('webpage'); + + var page = webpage.create(); + + page.evaluate(function() { + window.addEventListener('keyup', function(event) { + window.loggedEvent = window.loggedEvent || []; + window.loggedEvent.push(event); + }, false); + }); + + page.sendEvent('keyup', page.event.key.B); + var loggedEvent = page.evaluate(function() { + return window.loggedEvent; + }); + + assert_equals(loggedEvent.length, 1); + assert_equals(loggedEvent[0].which, page.event.key.B); +}, "key-up events"); diff --git a/third_party/phantomjs/test/module/webpage/loading.js b/third_party/phantomjs/test/module/webpage/loading.js new file mode 100644 index 00000000000..52cc7d4420c --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/loading.js @@ -0,0 +1,22 @@ +//! unsupported +async_test(function () { + var webpage = require('webpage'); + var page = webpage.create(); + + assert_type_of(page, 'object'); + assert_type_of(page.loading, 'boolean'); + assert_type_of(page.loadingProgress, 'number'); + + assert_is_false(page.loading); + assert_equals(page.loadingProgress, 0); + + page.open(TEST_HTTP_BASE + 'hello.html', + this.step_func_done(function (status) { + assert_equals(status, 'success'); + assert_equals(page.loading, false); + assert_equals(page.loadingProgress, 100); + })); + + assert_is_true(page.loading); + assert_greater_than(page.loadingProgress, 0); +}, "page loading progress"); diff --git a/third_party/phantomjs/test/module/webpage/local-urls-disabled-iframe.js b/third_party/phantomjs/test/module/webpage/local-urls-disabled-iframe.js new file mode 100644 index 00000000000..3144299b318 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/local-urls-disabled-iframe.js @@ -0,0 +1,23 @@ +//! unsupported +//! phantomjs: --web-security=no --local-url-access=no + +var webpage = require("webpage"); + +async_test(function () { + var page = webpage.create(); + var url = TEST_HTTP_BASE + "iframe.html#file:///nonexistent"; + var rsErrorCalled = false; + + page.onResourceError = this.step_func(function (error) { + rsErrorCalled = true; + assert_equals(error.url, "file:///nonexistent"); + assert_equals(error.errorCode, 301); + assert_equals(error.errorString, 'Protocol "file" is unknown'); + }); + + page.open(url, this.step_func_done(function () { + assert_is_true(rsErrorCalled); + })); + +}, +"doesn't attempt to load a file: URL in an iframe with --local-url-access=no"); diff --git a/third_party/phantomjs/test/module/webpage/local-urls-disabled.js b/third_party/phantomjs/test/module/webpage/local-urls-disabled.js new file mode 100644 index 00000000000..07853d86e8f --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/local-urls-disabled.js @@ -0,0 +1,22 @@ +//! unsupported +//! phantomjs: --local-url-access=no + +var webpage = require("webpage"); + +async_test(function () { + var page = webpage.create(); + var url = "file:///nonexistent"; + var rsErrorCalled = false; + + page.onResourceError = this.step_func(function (error) { + rsErrorCalled = true; + assert_equals(error.url, url); + assert_equals(error.errorCode, 301); + assert_equals(error.errorString, 'Protocol "file" is unknown'); + }); + + page.open(url, this.step_func_done(function () { + assert_is_true(rsErrorCalled); + })); + +}, "doesn't attempt to load a file: URL with --local-url-access=no"); diff --git a/third_party/phantomjs/test/module/webpage/local-urls-enabled-iframe.js b/third_party/phantomjs/test/module/webpage/local-urls-enabled-iframe.js new file mode 100644 index 00000000000..76d05a5aade --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/local-urls-enabled-iframe.js @@ -0,0 +1,23 @@ +//! unsupported +//! phantomjs: --web-security=no --local-url-access=yes + +var webpage = require("webpage"); + +async_test(function () { + var page = webpage.create(); + var url = TEST_HTTP_BASE + "iframe.html#file:///nonexistent"; + var rsErrorCalled = false; + + page.onResourceError = this.step_func(function (error) { + rsErrorCalled = true; + assert_equals(error.url, "file:///nonexistent"); + assert_equals(error.errorCode, 203); + assert_regexp_match(error.errorString, + /^Error opening\b.*?\bnonexistent:/); + }); + + page.open(url, this.step_func_done(function () { + assert_is_true(rsErrorCalled); + })); + +}, "attempts to load a file: URL in an iframe with --local-url-access=yes"); diff --git a/third_party/phantomjs/test/module/webpage/local-urls-enabled.js b/third_party/phantomjs/test/module/webpage/local-urls-enabled.js new file mode 100644 index 00000000000..b3f74bf5de5 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/local-urls-enabled.js @@ -0,0 +1,23 @@ +//! unsupported +//! phantomjs: --local-url-access=yes + +var webpage = require("webpage"); + +async_test(function () { + var page = webpage.create(); + var url = "file:///nonexistent"; + var rsErrorCalled = false; + + page.onResourceError = this.step_func(function (error) { + rsErrorCalled = true; + assert_equals(error.url, url); + assert_equals(error.errorCode, 203); + assert_regexp_match(error.errorString, + /^Error opening\b.*?\bnonexistent:/); + }); + + page.open(url, this.step_func_done(function () { + assert_is_true(rsErrorCalled); + })); + +}, "attempts to load a file: URL with --local-url-access=yes"); diff --git a/third_party/phantomjs/test/module/webpage/long-running-javascript.js b/third_party/phantomjs/test/module/webpage/long-running-javascript.js new file mode 100644 index 00000000000..fa07bafbc7a --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/long-running-javascript.js @@ -0,0 +1,19 @@ +//! unsupported +async_test(function () { + var page = require('webpage').create(); + + page.onLongRunningScript = this.step_func_done(function () { + page.stopJavaScript(); + }); + + page.open(TEST_HTTP_BASE + "js-infinite-loop.html", + this.step_func(function (s) { + assert_equals(s, "success"); + })); + +}, "page.onLongRunningScript can interrupt scripts", { + skip: true // https://github.com/ariya/phantomjs/issues/13490 + // The underlying WebKit feature is so broken that an + // infinite loop in a _page_ script prevents timeouts + // from firing in the _controller_! +}); diff --git a/third_party/phantomjs/test/module/webpage/modify-header.js b/third_party/phantomjs/test/module/webpage/modify-header.js new file mode 100644 index 00000000000..b37d2473261 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/modify-header.js @@ -0,0 +1,28 @@ +//! unsupported +async_test(function () { + var webpage = require('webpage'); + + // NOTE: HTTP header names are case-insensitive. Our test server + // returns the name in lowercase. + + var page = webpage.create(); + assert_type_of(page.customHeaders, 'object'); + assert_deep_equals(page.customHeaders, {}); + + page.customHeaders = { 'CustomHeader': 'CustomValue' }; + + page.onResourceRequested = this.step_func(function(requestData, request) { + assert_type_of(request.setHeader, 'function'); + request.setHeader('CustomHeader', 'ModifiedCustomValue'); + }); + + page.open(TEST_HTTP_BASE + 'echo', this.step_func_done(function (status) { + var json, headers; + assert_equals(status, 'success'); + json = JSON.parse(page.plainText); + headers = json.headers; + assert_own_property(headers, 'customheader'); + assert_equals(headers.customheader, 'ModifiedCustomValue'); + })); + +}, "modifying HTTP headers"); diff --git a/third_party/phantomjs/test/module/webpage/mouseclick-event.js b/third_party/phantomjs/test/module/webpage/mouseclick-event.js new file mode 100644 index 00000000000..44734bfa680 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/mouseclick-event.js @@ -0,0 +1,39 @@ +//! unsupported +test(function () { + var page = require('webpage').create(); + + page.evaluate(function() { + window.addEventListener('mousedown', function(event) { + window.loggedEvent = window.loggedEvent || {}; + window.loggedEvent.mousedown = event; + }, false); + window.addEventListener('mouseup', function(event) { + window.loggedEvent = window.loggedEvent || {}; + window.loggedEvent.mouseup = event; + }, false); + }); + page.sendEvent('click', 42, 217); + + var event = page.evaluate(function() { + return window.loggedEvent; + }); + assert_equals(event.mouseup.clientX, 42); + assert_equals(event.mouseup.clientY, 217); + assert_equals(event.mousedown.clientX, 42); + assert_equals(event.mousedown.clientY, 217); + + // click with modifier key + page.evaluate(function() { + window.addEventListener('click', function(event) { + window.loggedEvent = window.loggedEvent || {}; + window.loggedEvent.click = event; + }, false); + }); + page.sendEvent('click', 100, 100, 'left', page.event.modifier.shift); + + var event = page.evaluate(function() { + return window.loggedEvent.click; + }); + assert_is_true(event.shiftKey); + +}, "mouse click events"); diff --git a/third_party/phantomjs/test/module/webpage/mousedoubleclick-event.js b/third_party/phantomjs/test/module/webpage/mousedoubleclick-event.js new file mode 100644 index 00000000000..3a777f9a72a --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/mousedoubleclick-event.js @@ -0,0 +1,31 @@ +//! unsupported +test(function () { + var page = require('webpage').create(); + + page.content = ''; + var point = page.evaluate(function () { + var el = document.querySelector('input'); + var rect = el.getBoundingClientRect(); + return { x: rect.left + Math.floor(rect.width / 2), y: rect.top + (rect.height / 2) }; + }); + page.sendEvent('doubleclick', point.x, point.y); + + var text = page.evaluate(function () { + return document.querySelector('input').value; + }); + assert_equals(text, "doubleclicked"); + + // click with modifier key + page.evaluate(function() { + window.addEventListener('dblclick', function(event) { + window.loggedEvent = window.loggedEvent || {}; + window.loggedEvent.dblclick = event; + }, false); + }); + page.sendEvent('doubleclick', 100, 100, 'left', page.event.modifier.shift); + + var event = page.evaluate(function() { + return window.loggedEvent.dblclick; + }); + assert_is_true(event.shiftKey); +}, "mouse double-click events"); diff --git a/third_party/phantomjs/test/module/webpage/mousedown-event.js b/third_party/phantomjs/test/module/webpage/mousedown-event.js new file mode 100644 index 00000000000..ee67275b58b --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/mousedown-event.js @@ -0,0 +1,27 @@ +//! unsupported +test(function () { + var page = require('webpage').create(); + + page.evaluate(function() { + window.addEventListener('mousedown', function(event) { + window.loggedEvent = window.loggedEvent || []; + window.loggedEvent.push(event); + }, false); + }); + + page.sendEvent('mousedown', 42, 217); + var loggedEvent = page.evaluate(function() { + return window.loggedEvent; + }); + assert_equals(loggedEvent.length, 1); + assert_equals(loggedEvent[0].clientX, 42); + assert_equals(loggedEvent[0].clientY, 217); + + page.sendEvent('mousedown', 100, 100, 'left', page.event.modifier.shift); + loggedEvent = page.evaluate(function() { + return window.loggedEvent; + }); + assert_equals(loggedEvent.length, 2); + assert_is_true(loggedEvent[1].shiftKey); + +}, "mouse-down events"); diff --git a/third_party/phantomjs/test/module/webpage/mousemove-event.js b/third_party/phantomjs/test/module/webpage/mousemove-event.js new file mode 100644 index 00000000000..c2beaadca1e --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/mousemove-event.js @@ -0,0 +1,19 @@ +//! unsupported +test(function () { + var page = require('webpage').create(); + + page.evaluate(function() { + window.addEventListener('mousemove', function(event) { + window.loggedEvent = window.loggedEvent || []; + window.loggedEvent.push(event); + }, false); + }); + + page.sendEvent('mousemove', 14, 3); + var loggedEvent = page.evaluate(function() { + return window.loggedEvent; + }); + assert_equals(loggedEvent.length, 1); + assert_equals(loggedEvent[0].clientX, 14); + assert_equals(loggedEvent[0].clientY, 3); +}, "mouse-move events"); diff --git a/third_party/phantomjs/test/module/webpage/mouseup-event.js b/third_party/phantomjs/test/module/webpage/mouseup-event.js new file mode 100644 index 00000000000..80c3496eca4 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/mouseup-event.js @@ -0,0 +1,27 @@ +//! unsupported +test(function () { + var webpage = require('webpage'); + var page = webpage.create(); + + page.evaluate(function() { + window.addEventListener('mouseup', function(event) { + window.loggedEvent = window.loggedEvent || []; + window.loggedEvent.push(event); + }, false); + }); + + page.sendEvent('mouseup', 42, 217); + var loggedEvent = page.evaluate(function() { + return window.loggedEvent; + }); + assert_equals(loggedEvent.length, 1); + assert_equals(loggedEvent[0].clientX, 42); + assert_equals(loggedEvent[0].clientY, 217); + + page.sendEvent('mouseup', 100, 100, 'left', page.event.modifier.shift); + loggedEvent = page.evaluate(function() { + return window.loggedEvent; + }); + assert_equals(loggedEvent.length, 2); + assert_is_true(loggedEvent[1].shiftKey); +}, "mouse-up events"); diff --git a/third_party/phantomjs/test/module/webpage/navigation.js b/third_party/phantomjs/test/module/webpage/navigation.js new file mode 100644 index 00000000000..41c1509419f --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/navigation.js @@ -0,0 +1,31 @@ +//! unsupported +async_test(function () { + var page = require("webpage").create(); + var url1 = TEST_HTTP_BASE + "navigation/index.html"; + var url2 = TEST_HTTP_BASE + "navigation/dest.html"; + + var onLoadFinished1 = this.step_func(function (status) { + assert_equals(status, "success"); + assert_equals(page.url, url1); + assert_equals(page.evaluate(function () { + return document.body.innerHTML; + }), "INDEX\n"); + + page.onLoadFinished = onLoadFinished2; + page.evaluate(function() { + window.location = "dest.html"; + }); + }); + + var onLoadFinished2 = this.step_func_done(function (status) { + assert_equals(status, "success"); + assert_equals(page.url, url2); + assert_equals(page.evaluate(function () { + return document.body.innerHTML; + }), "DEST\n"); + }); + + page.onLoadFinished = onLoadFinished1; + page.open(url1); + +}, "navigating to a relative URL using window.location"); diff --git a/third_party/phantomjs/test/module/webpage/no-plugin.js b/third_party/phantomjs/test/module/webpage/no-plugin.js new file mode 100644 index 00000000000..1e563f2a9b9 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/no-plugin.js @@ -0,0 +1,19 @@ +async_test(function () { + var webpage = require('webpage'); + var page = webpage.create(); + + var pluginLength = page.evaluate(function() { + return window.navigator.plugins.length; + }); + assert_equals(pluginLength, 0); + + page.open(TEST_HTTP_BASE + 'hello.html', + this.step_func_done(function (status) { + assert_equals(status, 'success'); + var pluginLength = page.evaluate(function() { + return window.navigator.plugins.length; + }); + assert_equals(pluginLength, 0); + })); + +}, "window.navigator.plugins is empty"); diff --git a/third_party/phantomjs/test/module/webpage/object.js b/third_party/phantomjs/test/module/webpage/object.js new file mode 100644 index 00000000000..d0920e28120 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/object.js @@ -0,0 +1,77 @@ +//! unsupported +var webpage = require("webpage"); +var page = webpage.create(); + +test(function () { + assert_equals(webpage.create, WebPage); +}, "require('webpage').create === global WebPage"); + +test(function () { + assert_type_of(page, 'object'); + assert_not_equals(page, null); + + assert_equals(page.objectName, 'WebPage'); + assert_deep_equals(page.paperSize, {}); + + assert_not_equals(page.settings, null); + assert_not_equals(page.settings, {}); + + assert_type_of(page.canGoForward, 'boolean'); + assert_type_of(page.canGoBack, 'boolean'); + assert_type_of(page.clipRect, 'object'); + assert_type_of(page.content, 'string'); + assert_type_of(page.cookieJar, 'object'); + assert_type_of(page.cookies, 'object'); + assert_type_of(page.customHeaders, 'object'); + assert_type_of(page.event, 'object'); + assert_type_of(page.libraryPath, 'string'); + assert_type_of(page.loading, 'boolean'); + assert_type_of(page.loadingProgress, 'number'); + assert_type_of(page.navigationLocked, 'boolean'); + assert_type_of(page.offlineStoragePath, 'string'); + assert_type_of(page.offlineStorageQuota, 'number'); + assert_type_of(page.paperSize, 'object'); + assert_type_of(page.plainText, 'string'); + assert_type_of(page.scrollPosition, 'object'); + assert_type_of(page.settings, 'object'); + assert_type_of(page.title, 'string'); + assert_type_of(page.url, 'string'); + assert_type_of(page.frameUrl, 'string'); + assert_type_of(page.viewportSize, 'object'); + assert_type_of(page.windowName, 'string'); + assert_type_of(page.zoomFactor, 'number'); + +}, "page object properties"); + +test(function () { + assert_type_of(page.childFramesCount, 'function'); + assert_type_of(page.childFramesName, 'function'); + assert_type_of(page.clearMemoryCache, 'function'); + assert_type_of(page.close, 'function'); + assert_type_of(page.currentFrameName, 'function'); + assert_type_of(page.deleteLater, 'function'); + assert_type_of(page.destroyed, 'function'); + assert_type_of(page.evaluate, 'function'); + assert_type_of(page.initialized, 'function'); + assert_type_of(page.injectJs, 'function'); + assert_type_of(page.javaScriptAlertSent, 'function'); + assert_type_of(page.javaScriptConsoleMessageSent, 'function'); + assert_type_of(page.loadFinished, 'function'); + assert_type_of(page.loadStarted, 'function'); + assert_type_of(page.openUrl, 'function'); + assert_type_of(page.release, 'function'); + assert_type_of(page.render, 'function'); + assert_type_of(page.resourceError, 'function'); + assert_type_of(page.resourceReceived, 'function'); + assert_type_of(page.resourceRequested, 'function'); + assert_type_of(page.uploadFile, 'function'); + assert_type_of(page.sendEvent, 'function'); + assert_type_of(page.setContent, 'function'); + assert_type_of(page.switchToChildFrame, 'function'); + assert_type_of(page.switchToMainFrame, 'function'); + assert_type_of(page.switchToParentFrame, 'function'); + + assert_type_of(page.addCookie, 'function'); + assert_type_of(page.deleteCookie, 'function'); + assert_type_of(page.clearCookies, 'function'); +}, "page object methods"); diff --git a/third_party/phantomjs/test/module/webpage/on-confirm.js b/third_party/phantomjs/test/module/webpage/on-confirm.js new file mode 100644 index 00000000000..2f0f2ac83d4 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/on-confirm.js @@ -0,0 +1,36 @@ +test(function () { + var page = require('webpage').create(); + + var msg = "message body", + result, + expected = true; + + assert_equals(page.onConfirm, undefined); + + var onConfirmTrue = function(msg) { + return true; + }; + page.onConfirm = onConfirmTrue; + assert_equals(page.onConfirm, onConfirmTrue); + + result = page.evaluate(function(m) { + return window.confirm(m); + }, msg); + + assert_equals(result, expected); + + var onConfirmFunc = function() { return !!"y"; }; + page.onConfirm = onConfirmFunc; + assert_equals(page.onConfirm, onConfirmFunc); + assert_not_equals(page.onConfirm, onConfirmTrue); + + page.onConfirm = null; + // Will only allow setting to a function value, so setting it to `null` returns `undefined` + assert_equals(page.onConfirm, undefined); + page.onConfirm = undefined; + assert_equals(page.onConfirm, undefined); + +}, "page.onConfirm", { + /* @see crbug.com/718235 */ + expected_fail: true +}); diff --git a/third_party/phantomjs/test/module/webpage/on-error.js b/third_party/phantomjs/test/module/webpage/on-error.js new file mode 100644 index 00000000000..f5f892a7645 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/on-error.js @@ -0,0 +1,110 @@ +//! unsupported +var webpage = require('webpage'); + +test(function () { + var page = webpage.create(); + assert_not_equals(page.onError, undefined); + + var onErrorFunc1 = function() { return !"x"; }; + page.onError = onErrorFunc1; + assert_equals(page.onError, onErrorFunc1); + + var onErrorFunc2 = function() { return !!"y"; }; + page.onError = onErrorFunc2; + assert_equals(page.onError, onErrorFunc2); + assert_not_equals(page.onError, onErrorFunc1); + + page.onError = null; + // Will only allow setting to a function value, so setting it to `null` returns `undefined` + assert_equals(page.onError, undefined); + page.onError = undefined; + assert_equals(page.onError, undefined); +}, "setting and clearing page.onError"); + +test(function () { + var page = webpage.create(); + var lastError = null; + page.onError = function(message) { lastError = message; }; + + page.evaluate(function() { referenceError2(); }); + assert_equals(lastError, "ReferenceError: Can't find variable: referenceError2"); + + page.evaluate(function() { throw "foo"; }); + assert_equals(lastError, "foo"); + + page.evaluate(function() { throw Error("foo"); }); + assert_equals(lastError, "Error: foo"); +}, "basic error reporting"); + +async_test(function () { + var page = webpage.create(); + var lastError = null; + page.onError = this.step_func_done(function(message) { + assert_equals(message, "ReferenceError: Can't find variable: referenceError"); + }); + + page.evaluate(function() { + setTimeout(function() { referenceError(); }, 0); + }); + +}, "error reporting from async events"); + +test(function () { + var page = webpage.create(); + var hadError = false; + page.onError = function() { hadError = true; }; + page.evaluate(function() { + window.caughtError = false; + + try { + referenceError(); + } catch(e) { + window.caughtError = true; + } + }); + + assert_equals(hadError, false); + assert_is_true(page.evaluate(function() { return window.caughtError; })); +}, "should not report errors that were caught"); + +function check_stack(message, stack) { + assert_equals(message, + "ReferenceError: Can't find variable: referenceError"); + + if (typeof stack === "string") { + var lines = stack.split("\n"); + assert_regexp_match(lines[0], RegExp("^bar@.*?"+helperBase+":7:23$")); + assert_regexp_match(lines[1], RegExp("^foo@.*?"+helperBase+":3:17$")); + } else { + assert_regexp_match(stack[0].file, RegExp(helperBase)); + assert_equals(stack[0].line, 7); + assert_equals(stack[0]["function"], "bar"); + + assert_regexp_match(stack[1].file, RegExp(helperBase)); + assert_equals(stack[1].line, 3); + assert_equals(stack[1]["function"], "foo"); + } +} + +var helperBase = "error-helper.js"; +var helperFile = "../../fixtures/" + helperBase; +assert_is_true(phantom.injectJs(helperFile)); + +test(function () { + try { + ErrorHelper.foo(); + } catch (e) { + check_stack(e.toString(), e.stack); + } +}, "stack trace accuracy (controller script)"); + +async_test(function () { + var page = webpage.create(); + page.libraryPath = phantom.libraryPath; + assert_is_true(page.injectJs(helperFile)); + + page.onError = this.step_func_done(check_stack); + page.evaluate(function () { + setTimeout(function () { ErrorHelper.foo(); }, 0); + }); +}, "stack trace accuracy (webpage script)"); diff --git a/third_party/phantomjs/test/module/webpage/on-initialized.js b/third_party/phantomjs/test/module/webpage/on-initialized.js new file mode 100644 index 00000000000..a32d1f58fb0 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/on-initialized.js @@ -0,0 +1,22 @@ +//! unsupported +test(function () { + var page = require('webpage').create(); + + assert_equals(page.onInitialized, undefined); + + var onInitialized1 = function() { var x = "x"; }; + page.onInitialized = onInitialized1; + assert_equals(page.onInitialized, onInitialized1); + + var onInitialized2 = function() { var y = "y"; }; + page.onInitialized = onInitialized2; + assert_equals(page.onInitialized, onInitialized2); + assert_not_equals(page.onInitialized, onInitialized1); + + page.onInitialized = null; + // Will only allow setting to a function value, so setting it to `null` returns `undefined` + assert_equals(page.onInitialized, undefined); + + page.onInitialized = undefined; + assert_equals(page.onInitialized, undefined); +}, "page.onInitialized"); diff --git a/third_party/phantomjs/test/module/webpage/open.js b/third_party/phantomjs/test/module/webpage/open.js new file mode 100644 index 00000000000..ff7ef855a70 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/open.js @@ -0,0 +1,53 @@ +async_test(function () { + var webpage = require('webpage'); + var page = webpage.create(); + assert_type_of(page, 'object'); + + page.onResourceReceived = this.step_func(function (resource) { + assert_equals(resource.status, 200); + }); + page.open(TEST_HTTP_BASE + 'hello.html', + this.step_func_done(function (status) { + assert_equals(status, 'success'); + assert_type_of(page.title, 'string'); + assert_equals(page.title, 'Hello'); + assert_type_of(page.plainText, 'string'); + assert_equals(page.plainText, 'Hello, world!'); + })); +}, "opening a webpage"); + +async_test(function () { + var webpage = require('webpage'); + var page = webpage.create(); + + // both onResourceReceived and onResourceError should be called + page.onResourceReceived = this.step_func(function (resource) { + assert_equals(resource.status, 401); + }); + page.onResourceError = this.step_func(function (err) { + assert_equals(err.errorString, "Operation canceled"); + }); + + page.open(TEST_HTTP_BASE + 'status?status=401' + + '&WWW-Authenticate=Basic%20realm%3D%22PhantomJS%20test%22', + this.step_func_done(function (status) { + assert_equals(status, 'fail'); + })); + +}, "proper handling of HTTP error responses", {/* unsupported */expected_fail: true}); + +async_test(function () { + var webpage = require('webpage'); + var page = webpage.create(); + + page.settings.resourceTimeout = 1; + + // This is all you have to do to assert that a hook does get called. + page.onResourceTimeout = this.step_func(function(){}); + + page.open(TEST_HTTP_BASE + "delay?5", + this.step_func_done(function (s) { + assert_not_equals(s, "success"); + })); + +}, "onResourceTimeout fires after resourceTimeout ms", {/* unsupported */expected_fail: true}); diff --git a/third_party/phantomjs/test/module/webpage/postdata.js b/third_party/phantomjs/test/module/webpage/postdata.js new file mode 100644 index 00000000000..dd3d725fa92 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/postdata.js @@ -0,0 +1,47 @@ +//! unsupported +function validate_echo_response (status, page, postdata) { + assert_equals(status, 'success'); + + var desc = JSON.parse(page.plainText); + assert_equals(desc.command, "POST"); + assert_equals(desc.postdata, postdata); + assert_equals(desc.headers['content-type'], + 'application/x-www-form-urlencoded'); +} + +async_test(function () { + + var utfString = '안녕'; + var openOptions = { + operation: 'POST', + data: utfString, + encoding: 'utf8' + }; + var pageOptions = { + onLoadFinished: this.step_func_done(function(status) { + validate_echo_response(status, page, utfString); + }) + }; + var page = new WebPage(pageOptions); + page.openUrl(TEST_HTTP_BASE + "echo", openOptions, {}); + + +}, "processing request body for POST"); + +async_test(function () { + + var postdata = "ab=cd"; + var pageOptions = { + onResourceRequested: this.step_func(function (request) { + assert_equals(request.postData, postdata); + }), + onLoadFinished: this.step_func_done(function (status) { + validate_echo_response(status, page, postdata); + }) + }; + + var page = new WebPage(pageOptions); + page.open(TEST_HTTP_BASE + "echo", 'post', postdata); + + +}, "POST data is available in onResourceRequested"); diff --git a/third_party/phantomjs/test/module/webpage/prompt.js b/third_party/phantomjs/test/module/webpage/prompt.js new file mode 100644 index 00000000000..2826acf3cd2 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/prompt.js @@ -0,0 +1,17 @@ +//! unsupported +test(function () { + var page = require('webpage').create(); + + var msg = "message", + value = "value", + result, + expected = "extra-value"; + page.onPrompt = function(msg, value) { + return "extra-"+value; + }; + result = page.evaluate(function(m, v) { + return window.prompt(m, v); + }, msg, value); + + assert_equals(result, expected); +}, "page.onPrompt"); diff --git a/third_party/phantomjs/test/module/webpage/remove-header.js b/third_party/phantomjs/test/module/webpage/remove-header.js new file mode 100644 index 00000000000..24a4519969a --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/remove-header.js @@ -0,0 +1,27 @@ +//! unsupported +var webpage = require('webpage'); + +// NOTE: HTTP header names are case-insensitive. Our test server +// returns the name in lowercase. +async_test(function () { + var page = webpage.create(); + assert_type_of(page.customHeaders, 'object'); + assert_deep_equals(page.customHeaders, {}); + + page.customHeaders = { 'CustomHeader': 'ModifiedCustomValue' }; + + page.onResourceRequested = this.step_func(function(requestData, request) { + assert_type_of(request.setHeader, 'function'); + request.setHeader('CustomHeader', null); + }); + + page.open(TEST_HTTP_BASE + 'echo', + this.step_func_done(function (status) { + var json, headers; + assert_equals(status, 'success'); + json = JSON.parse(page.plainText); + headers = json.headers; + assert_no_property(headers, 'customheader'); + assert_no_property(headers, 'CustomHeader'); + })); +}); diff --git a/third_party/phantomjs/test/module/webpage/render.js b/third_party/phantomjs/test/module/webpage/render.js new file mode 100644 index 00000000000..230192ccfc3 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/render.js @@ -0,0 +1,67 @@ +var fs = require("fs"); +var system = require("system"); +var webpage = require("webpage"); +var renders = require("./renders"); + +function clean_pdf(data) { + // FIXME: This is not nearly enough normalization. + data = data.replace(/\/(Title|Creator|Producer|CreationDate) \([^\n]*\)/g, "/$1 ()"); + data = data.replace(/\nxref\n[0-9 nf\n]+trailer\b/, "\ntrailer"); + data = data.replace(/\nstartxref\n[0-9]+\n%%EOF\n/, "\n"); + return data; +} + +function render_test(format, option) { + var opt = option || {}; + var scratch = "temp_render"; + if (!opt.format) { + scratch += "."; + scratch += format; + } + var expect_content = renders.get(format, opt.quality || ""); + var p = webpage.create(); + + p.paperSize = { width: '300px', height: '300px', border: '0px' }; + p.clipRect = { top: 0, left: 0, width: 300, height: 300}; + p.viewportSize = { width: 300, height: 300}; + + p.open(TEST_HTTP_BASE + "render/", this.step_func_done(function (status) { + p.render(scratch, opt); + this.add_cleanup(function () { fs.remove(scratch); }); + var content = fs.read(scratch, "b"); + + // expected variation in PDF output + if (format === "pdf") { + content = clean_pdf(content); + expect_content = clean_pdf(expect_content); + } + + // Don't dump entire images to the log on failure. + assert_is_true(content === expect_content); + })); +} + +[ + ["PDF", "pdf", {}], + ["PDF (format option)", "pdf", {format: "pdf"}], + ["PNG", "png", {}], + ["PNG (format option)", "png", {format: "png"}], + ["JPEG", "jpg", {}], + ["JPEG (format option)", "jpg", {format: "jpg"}], + ["JPEG (quality option)", "jpg", {quality: 50}], + ["JPEG (format and quality options)", "jpg", {format: "jpg", quality: 50}], +] +.forEach(function (arr) { + var label = arr[0]; + var format = arr[1]; + var opt = arr[2]; + var props = {}; + + // All tests fail on Linux. All tests except JPG fail on Mac. + // Currently unknown which tests fail on Windows. + if (format !== "jpg" || system.os.name !== "mac") + props.expected_fail = true; + + async_test(function () { render_test.call(this, format, opt); }, + label, props); +}); diff --git a/third_party/phantomjs/test/module/webpage/renders/index.js b/third_party/phantomjs/test/module/webpage/renders/index.js new file mode 100644 index 00000000000..47e83b6a7ea --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/renders/index.js @@ -0,0 +1,7 @@ +var fs = require("fs"); + +exports.get = function get(format, quality) { + var expect_file = fs.join( + module.dirname, "test" + quality + "." + format); + return fs.read(expect_file, "b"); +}; diff --git a/third_party/phantomjs/test/module/webpage/renders/test.jpg b/third_party/phantomjs/test/module/webpage/renders/test.jpg new file mode 100644 index 00000000000..b597dba47fb Binary files /dev/null and b/third_party/phantomjs/test/module/webpage/renders/test.jpg differ diff --git a/third_party/phantomjs/test/module/webpage/renders/test.pdf b/third_party/phantomjs/test/module/webpage/renders/test.pdf new file mode 100644 index 00000000000..b1beecd1d73 Binary files /dev/null and b/third_party/phantomjs/test/module/webpage/renders/test.pdf differ diff --git a/third_party/phantomjs/test/module/webpage/renders/test.png b/third_party/phantomjs/test/module/webpage/renders/test.png new file mode 100644 index 00000000000..7932eeb11bb Binary files /dev/null and b/third_party/phantomjs/test/module/webpage/renders/test.png differ diff --git a/third_party/phantomjs/test/module/webpage/renders/test50.jpg b/third_party/phantomjs/test/module/webpage/renders/test50.jpg new file mode 100644 index 00000000000..a3e04420682 Binary files /dev/null and b/third_party/phantomjs/test/module/webpage/renders/test50.jpg differ diff --git a/third_party/phantomjs/test/module/webpage/repaint-requested.js b/third_party/phantomjs/test/module/webpage/repaint-requested.js new file mode 100644 index 00000000000..bb3bb355d5e --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/repaint-requested.js @@ -0,0 +1,20 @@ +//! unsupported +var webpage = require('webpage'); + +async_test(function () { + var page = webpage.create(); + var requestCount = 0; + + page.onRepaintRequested = this.step_func(function(x, y, w, h) { + if ((w > 0) && (h > 0)) { + ++requestCount; + } + }); + + page.open(TEST_HTTP_BASE + 'hello.html', + this.step_func_done(function (status) { + assert_equals(status, 'success'); + assert_greater_than(requestCount, 0); + })); + +}, "onRepaintRequested should be called at least once for each page load"); diff --git a/third_party/phantomjs/test/module/webpage/resource-received-error.js b/third_party/phantomjs/test/module/webpage/resource-received-error.js new file mode 100644 index 00000000000..dae581e1115 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/resource-received-error.js @@ -0,0 +1,33 @@ +//! unsupported +var webpage = require('webpage'); + +async_test(function () { + var page = webpage.create(); + var url = TEST_HTTP_BASE + 'status?400'; + var startStage = 0; + var endStage = 0; + var errors = 0; + + page.onResourceReceived = this.step_func(function (resource) { + assert_equals(resource.url, url); + if (resource.stage === 'start') { + ++startStage; + } + if (resource.stage === 'end') { + ++endStage; + } + }); + page.onResourceError = this.step_func(function (error) { + assert_equals(error.url, url); + assert_equals(error.status, 400); + ++errors; + }); + + page.open(url, this.step_func_done(function (status) { + assert_equals(status, 'success'); + assert_equals(startStage, 1); + assert_equals(endStage, 1); + assert_equals(errors, 1); + })); + +}, "onResourceReceived should still be called for failed requests"); diff --git a/third_party/phantomjs/test/module/webpage/resource-request-error.js b/third_party/phantomjs/test/module/webpage/resource-request-error.js new file mode 100644 index 00000000000..0f150362392 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/resource-request-error.js @@ -0,0 +1,27 @@ +//! unsupported +var webpage = require('webpage'); + +async_test(function () { + var page = webpage.create(); + var resourceErrors = 0; + + page.onResourceError = this.step_func(function(err) { + ++resourceErrors; + + assert_equals(err.status, 404); + assert_equals(err.statusText, 'File not found'); + assert_equals(err.url, TEST_HTTP_BASE + 'notExist.png'); + assert_equals(err.errorCode, 203); + assert_regexp_match(err.errorString, + /Error downloading http:\/\/localhost:[0-9]+\/notExist\.png/); + assert_regexp_match(err.errorString, + /server replied: File not found/); + }); + + page.open(TEST_HTTP_BASE + 'missing-img.html', + this.step_func_done(function (status) { + assert_equals(status, 'success'); + assert_equals(resourceErrors, 1); + })); + +}, "resourceError basic functionality"); diff --git a/third_party/phantomjs/test/module/webpage/scroll-position.js b/third_party/phantomjs/test/module/webpage/scroll-position.js new file mode 100644 index 00000000000..a1550531a14 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/scroll-position.js @@ -0,0 +1,18 @@ +//! unsupported +var webpage = require('webpage'); + +test(function () { + var defaultPage = webpage.create(); + assert_deep_equals(defaultPage.scrollPosition, {left:0,top:0}); +}, "default scroll position"); + +test(function () { + var options = { + scrollPosition: { + left: 1, + top: 2 + } + }; + var customPage = webpage.create(options); + assert_deep_equals(customPage.scrollPosition, options.scrollPosition); +}, "custom scroll position"); diff --git a/third_party/phantomjs/test/module/webpage/set-content.js b/third_party/phantomjs/test/module/webpage/set-content.js new file mode 100644 index 00000000000..52e823368c1 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/set-content.js @@ -0,0 +1,20 @@ +//! unsupported +var webpage = require('webpage'); + +test(function () { + var page = webpage.create(); + var expectedContent = '
Test div
'; + var expectedLocation = 'http://www.phantomjs.org/'; + page.setContent(expectedContent, expectedLocation); + + var actualContent = page.evaluate(function() { + return document.documentElement.textContent; + }); + assert_equals(actualContent, 'Test div'); + + var actualLocation = page.evaluate(function() { + return window.location.href; + }); + assert_equals(actualLocation, expectedLocation); + +}, "manually set page content and location"); diff --git a/third_party/phantomjs/test/module/webpage/subwindows.js b/third_party/phantomjs/test/module/webpage/subwindows.js new file mode 100644 index 00000000000..392b664d6a8 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/subwindows.js @@ -0,0 +1,130 @@ +//! unsupported +async_test(function () { + var test = this; + var top = require('webpage').create(); + var pages_created = 0; + var expect_to_close = null; + var after_close = null; + + top.onPageCreated = function (page) { + pages_created++; + page.onClosing = test.step_func(function (page) { + assert_equals(page.windowName, expect_to_close); + setTimeout(after_close, 0); + }); + if (pages_created === 3) { + setTimeout(after_open_3, 0); + } + }; + + var after_open_3 = test.step_func(function () { + assert_equals(top.pages.length, 3); + assert_deep_equals(top.pagesWindowName, ["A", "B", "C"]); + + after_close = after_close_1; + expect_to_close = "A"; + top.evaluate(function () { window.wA.close(); }); + }); + + var after_close_1 = test.step_func(function () { + assert_equals(top.pages.length, 2); + assert_deep_equals(top.pagesWindowName, ["B", "C"]); + + + var pageB = top.getPage("B"); + assert_not_equals(pageB, null); + + after_close = after_close_2; + expect_to_close = "B"; + pageB.close(); + }); + + var after_close_2 = test.step_func(function () { + assert_equals(top.pages.length, 1); + assert_deep_equals(top.pagesWindowName, ["C"]); + + // Must close C as well, because its onclosing hook is a step + // function that hasn't run yet. + after_close = test.step_func_done(); + expect_to_close = "C"; + top.close(); + }); + + top.evaluate(function () { + var w = window; + w.wA = w.open("data:text/html,%3Ctitle%3Epage%20A%3C/title%3E", "A"); + w.wB = w.open("data:text/html,%3Ctitle%3Epage%20B%3C/title%3E", "B"); + w.wC = w.open("data:text/html,%3Ctitle%3Epage%20C%3C/title%3E", "C"); + }); + +}, "pages and pagesWindowName arrays; onPageCreated and onClosing hooks"); + +async_test(function () { + var test = this; + var pages_opened = 1, pages_closed = 0; + var top = require("webpage").create(); + + var onPageCreated = test.step_func(function onPageCreated(page) { + pages_opened++; + page.onPageCreated = onPageCreated; + page.onClosing = onClosing; + if (pages_opened === 4) { + setTimeout(after_open_4, 0); + } + }); + var onClosing = test.step_func(function onClosing(page) { + pages_closed++; + if (pages_opened === pages_closed) { + test.done(); + } + }); + + // This can't be inlined into onPageCreated because + // pagesWindowName is not quite up-to-date when that hook fires. + var after_open_4 = test.step_func(function () { + assert_equals(top.pages.length, 3); + assert_deep_equals(top.pagesWindowName, ["A", "B", "C"]); + top.close(); + }); + + top.onPageCreated = onPageCreated; + top.onClosing = onClosing; + + top.evaluate(function () { + var w = window; + w.wA = w.open("data:text/html,%3Ctitle%3Epage%20A%3C/title%3E", "A"); + w.wB = w.open("data:text/html,%3Ctitle%3Epage%20B%3C/title%3E", "B"); + w.wC = w.open("data:text/html,%3Ctitle%3Epage%20C%3C/title%3E", "C"); + }); + +}, "close subwindows when parent page is closed (default behavior)"); + +async_test(function () { + var test = this; + var pages_opened = 1; + var top = require("webpage").create(); + top.ownsPages = false; + + var onPageCreated = test.step_func(function onPageCreated(page) { + pages_opened++; + page.onPageCreated = onPageCreated; + page.onClosing = test.unreached_func(); + if (pages_opened === 4) { + assert_equals(top.pages.length, 0); + assert_deep_equals(top.pagesWindowName, []); + top.close(); + } + }); + top.onPageCreated = onPageCreated; + + top.onClosing = test.step_func(function onTopClosing(page) { + setTimeout(function () { test.done(); }, 50); + }); + + top.evaluate(function () { + var w = window; + w.wA = w.open("data:text/html,%3Ctitle%3Epage%20A%3C/title%3E", "A"); + w.wB = w.open("data:text/html,%3Ctitle%3Epage%20B%3C/title%3E", "B"); + w.wC = w.open("data:text/html,%3Ctitle%3Epage%20C%3C/title%3E", "C"); + }); +}, "don't close subwindows when parent page is closed (ownsPages=false)"); diff --git a/third_party/phantomjs/test/module/webpage/url-encoding.js b/third_party/phantomjs/test/module/webpage/url-encoding.js new file mode 100644 index 00000000000..d0026dc40cc --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/url-encoding.js @@ -0,0 +1,134 @@ +//! unsupported +var webpage = require('webpage'); + +// Many of the URLs used in this file contain text encoded in +// Shift_JIS, so that they will not round-trip correctly if +// misinterpreted at any point as UTF-8 (and thus, the test will +// fail). See www/url-encoding.py for Unicode equivalents. + +function URL(path) { + return TEST_HTTP_BASE + 'url-encoding?' + path; +} + +async_test(function () { + var p = webpage.create(); + p.open(URL('/'), this.step_func_done(function (status) { + assert_equals(status, 'success'); + assert_equals(p.url, URL('/%83y%81[%83W')); + assert_equals(p.plainText, 'PASS'); + })); + +}, "page.url"); + +async_test(function () { + var p = webpage.create(); + p.open(URL('/f'), this.step_func_done(function (status) { + assert_equals(status, 'success'); + assert_equals(p.url, URL('/f')); + assert_equals(p.framesCount, 2); + + assert_is_true(p.switchToFrame('a')); + assert_equals(p.frameUrl, URL('/%98g')); + assert_equals(p.framePlainText, 'PASS'); + + assert_is_true(p.switchToParentFrame()); + assert_is_true(p.switchToFrame('b')); + assert_equals(p.frameUrl, URL('/%95s%96%D1%82%C8%98_%91%88')); + assert_equals(p.framePlainText, 'FRAME'); + })); + +}, "page.frameUrl"); + +async_test(function () { + var p = webpage.create(); + var n = 0; + var expectedUrls = [ URL('/'), URL('/%83y%81[%83W') ]; + + p.onNavigationRequested = this.step_func(function (url, ty, will, main) { + assert_equals(url, expectedUrls[n]); + assert_equals(ty, 'Other'); + assert_is_true(will); + assert_is_true(main); + n++; + + if (n === expectedUrls.length) { + p.onNavigationRequested = this.unreached_func(); + } + }); + p.open(URL('/'), this.step_func_done(function (status) { + assert_equals(status, 'success'); + assert_equals(n, expectedUrls.length); + assert_equals(p.plainText, 'PASS'); + })); + +}, "arguments to onNavigationRequested"); + +async_test(function () { + var p = webpage.create(); + var n = 0; + var n_req = 0; + var n_recv = 0; + var expectedUrls = [ URL('/r'), URL('/%8F%91') ]; + var receivedUrls = {}; + + p.onResourceRequested = this.step_func(function (req, nr) { + assert_equals(req.url, expectedUrls[n_req]); + n_req++; + if (n_req === expectedUrls.length) { + p.onResourceRequested = this.unreached_func(); + } + }); + + p.onResourceReceived = this.step_func(function (resp) { + // This function may be called more than once per URL. + if (receivedUrls.hasOwnProperty(resp.url)) + return; + receivedUrls[resp.url] = true; + assert_equals(resp.url, expectedUrls[n_recv]); + n_recv++; + }); + + p.open(URL('/r'), this.step_func_done(function (status) { + assert_equals(status, 'success'); + assert_equals(n_req, expectedUrls.length); + assert_equals(n_recv, expectedUrls.length); + assert_equals(p.plainText, 'PASS'); + })); + +}, "arguments to onResourceRequested and onResourceReceived"); + +async_test(function () { + var p = webpage.create(); + p.settings.resourceTimeout = 100; + + var n_timeout = 0; + var n_error = 0; + var expectedUrls_timeout = [ URL('/%89i%8Bv') ]; + // the error hook is called for timeouts as well + var expectedUrls_error = [ URL('/%8C%CC%8F%E1'), URL('/%89i%8Bv') ]; + + p.onResourceTimeout = this.step_func(function (req) { + assert_equals(req.url, expectedUrls_timeout[n_timeout]); + n_timeout++; + + if (n_timeout === expectedUrls_timeout.length) { + p.onResourceTimeout = this.unreached_func(); + } + }); + + p.onResourceError = this.step_func(function (err) { + assert_equals(err.url, expectedUrls_error[n_error]); + n_error++; + + if (n_error === expectedUrls_error.length) { + p.onResourceTimeout = this.unreached_func(); + } + }); + + p.open(URL("/re"), this.step_func_done(function (status) { + assert_equals(status, 'success'); + assert_equals(n_timeout, expectedUrls_timeout.length); + assert_equals(n_error, expectedUrls_error.length); + })); + +}, " arguments to onResourceError and onResourceTimeout"); diff --git a/third_party/phantomjs/test/module/webpage/user-agent.js b/third_party/phantomjs/test/module/webpage/user-agent.js new file mode 100644 index 00000000000..1dc1962ea8e --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/user-agent.js @@ -0,0 +1,22 @@ +var webpage = require('webpage'); + +async_test(function () { + var ua = 'PHANTOMJS-TEST-USER-AGENT'; + var page = webpage.create({ + settings: { + userAgent: ua + } + }); + + assert_equals(page.settings.userAgent, ua); + + page.open(TEST_HTTP_BASE + 'user-agent.html', + this.step_func_done(function (status) { + assert_equals(status, 'success'); + var agent = page.evaluate(function() { + return document.getElementById('ua').textContent; + }); + assert_equals(agent, ua); + })); + +}, "load a page with a custom user agent"); diff --git a/third_party/phantomjs/test/module/webpage/viewport-size.js b/third_party/phantomjs/test/module/webpage/viewport-size.js new file mode 100644 index 00000000000..dc2412c2793 --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/viewport-size.js @@ -0,0 +1,17 @@ +var webpage = require('webpage'); + +test(function () { + var defaultPage = webpage.create(); + assert_deep_equals(defaultPage.viewportSize, {height:300,width:400}); +}, "default viewport size"); + +test(function () { + var options = { + viewportSize: { + height: 100, + width: 200 + } + }; + var customPage = webpage.create(options); + assert_deep_equals(customPage.viewportSize, options.viewportSize); +}, "custom viewport size"); diff --git a/third_party/phantomjs/test/module/webpage/window.js b/third_party/phantomjs/test/module/webpage/window.js new file mode 100644 index 00000000000..c8ddaaf63ce --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/window.js @@ -0,0 +1,4 @@ +test(function () { + assert_own_property(window, 'WebPage'); + assert_type_of(window.WebPage, 'function'); +}, "window.WebPage global property"); diff --git a/third_party/phantomjs/test/module/webpage/zoom-factor.js b/third_party/phantomjs/test/module/webpage/zoom-factor.js new file mode 100644 index 00000000000..f8f447e4eca --- /dev/null +++ b/third_party/phantomjs/test/module/webpage/zoom-factor.js @@ -0,0 +1,18 @@ +//! unsupported +var webpage = require('webpage'); + +test(function () { + var page = webpage.create(); + assert_equals(page.zoomFactor, 1.0); + + page.zoomFactor = 1.5; + assert_equals(page.zoomFactor, 1.5); + + page.zoomFactor = 2.0; + assert_equals(page.zoomFactor, 2.0); + + page.zoomFactor = 0.5; + assert_equals(page.zoomFactor, 0.5); +}, "page.zoomFactor"); + +// TODO: render using zoomFactor != 1 and check the result diff --git a/third_party/phantomjs/test/module/webserver/basics.js b/third_party/phantomjs/test/module/webserver/basics.js new file mode 100644 index 00000000000..4f124cc4202 --- /dev/null +++ b/third_party/phantomjs/test/module/webserver/basics.js @@ -0,0 +1,25 @@ +test(function () { + assert_no_property(window, "WebServer", + "WebServer constructor should not be global"); + + var WebServer = require("webserver").create; + assert_type_of(WebServer, "function"); + +}, "WebServer constructor"); + +test(function () { + var server = require("webserver").create(); + + assert_not_equals(server, null); + assert_type_of(server, "object"); + assert_equals(server.objectName, "WebServer"); + + assert_own_property(server, "port"); + assert_type_of(server.port, "string"); + assert_equals(server.port, ""); + + assert_type_of(server.listenOnPort, "function"); + assert_type_of(server.newRequest, "function"); + assert_type_of(server.close, "function"); + +}, "WebServer object properties"); diff --git a/third_party/phantomjs/test/module/webserver/requests.js b/third_party/phantomjs/test/module/webserver/requests.js new file mode 100644 index 00000000000..843a041c578 --- /dev/null +++ b/third_party/phantomjs/test/module/webserver/requests.js @@ -0,0 +1,179 @@ +var server, port, request_cb; +setup(function () { + server = require("webserver").create(); + + // Should be unable to listen on port 1 (FIXME: this might succeed if + // the test suite is being run with root privileges). + assert_is_false(server.listen(1, function () {})); + assert_equals(server.port, ""); + + // Find an unused port in the 1024--32767 range on which to run the + // rest of the tests. The function in "request_cb" will be called + // for each request; it is set appropriately by each test case. + for (var i = 1024; i < 32768; i++) { + if (server.listen(i, function(rq,rs){return request_cb(rq,rs);})) { + assert_equals(server.port, i.toString()); + port = server.port; + return; + } + } + assert_unreached("unable to find a free TCP port for server tests"); +}, + { "test_timeout": 1000 }); + +function arm_check_request (test, expected_postdata, expected_bindata, + expected_mimetype) { + request_cb = test.step_func(function check_request (request, response) { + try { + assert_type_of(request, "object"); + assert_own_property(request, "url"); + assert_own_property(request, "method"); + assert_own_property(request, "httpVersion"); + assert_own_property(request, "headers"); + assert_type_of(request.headers, "object"); + + assert_type_of(response, "object"); + assert_own_property(response, "statusCode"); + assert_own_property(response, "headers"); + assert_type_of(response.setHeaders, "function"); + assert_type_of(response.setHeader, "function"); + assert_type_of(response.header, "function"); + assert_type_of(response.write, "function"); + assert_type_of(response.writeHead, "function"); + + if (expected_postdata !== false) { + assert_equals(request.method, "POST"); + assert_own_property(request, "post"); + if (request.headers["Content-Type"] === + "application/x-www-form-urlencoded") { + assert_own_property(request, "postRaw"); + assert_type_of(request.postRaw, "string"); + assert_type_of(request.post, "object"); + assert_deep_equals(request.post, expected_postdata); + } else { + assert_no_property(request, "postRaw"); + assert_type_of(request.post, "string"); + assert_not_equals(request.post, expected_postdata); + } + } + + response.setHeader("X-Request-URL", request.url); + + if (expected_bindata !== false) { + response.setEncoding("binary"); + response.setHeader("Content-Type", expected_mimetype); + response.write(expected_bindata); + } else { + response.write("request handled"); + } + } finally { + response.close(); + request_cb = test.unreached_func(); + } + }); +} + +async_test(function () { + var page = require("webpage").create(); + var url = "http://localhost:"+port+"/foo/bar.php?asdf=true"; + + arm_check_request(this, false, false); + page.open(url, this.step_func_done(function (status) { + assert_equals(status, "success"); + assert_equals(page.plainText, "request handled"); + })); + +}, "basic request handling"); + +async_test(function () { + var page = require("webpage").create(); + var url = "http://localhost:"+port+"/%95s%96%D1%82%C8%98_%91%88"; + var already = false; + + arm_check_request(this, false, false); + page.onResourceReceived = this.step_func(function (resp) { + if (already) return; + already = true; + + var found = false; + resp.headers.forEach(function (hdr) { + if (hdr.name.toLowerCase() === "x-request-url") { + assert_equals(hdr.value, "/%95s%96%D1%82%C8%98_%91%88"); + found = true; + } + }); + assert_is_true(found); + }); + + page.open(url, this.step_func_done(function (status) { + assert_equals(status, "success"); + assert_equals(page.plainText, "request handled"); + })); + +}, "round-trip of URLs containing encoded non-Unicode text"); + +async_test(function () { + var page = require("webpage").create(); + var url = "http://localhost:"+port+"/foo/bar.txt?asdf=true"; + + arm_check_request(this, + {"answer" : "42", "universe" : "expanding"}, false); + + page.open(url, "post", "universe=expanding&answer=42", + { "Content-Type" : "application/x-www-form-urlencoded" }, + this.step_func_done(function (status) { + assert_equals(status, "success"); + assert_equals(page.plainText, "request handled"); + })); + +}, "handling POST with application/x-www-form-urlencoded data", { + expected_fail: true /* unsupported */ +}); + +async_test(function () { + var page = require("webpage").create(); + var url = "http://localhost:"+port+"/foo/bar.txt?asdf=true"; + + arm_check_request(this, + {"answer" : "42", "universe" : "expanding"}, false); + + page.open(url, "post", "universe=expanding&answer=42", + { "Content-Type" : "application/json;charset=UTF-8" }, + this.step_func_done(function (status) { + assert_equals(status, "success"); + assert_equals(page.plainText, "request handled"); + })); + +}, "handling POST with ill-formed application/json data", { + expected_fail: true /* unsupported */ +}); + +async_test(function () { + var page = require("webpage").create(); + var url = "http://localhost:"+port+"/"; + var fs = require("fs"); + var png = fs.read(fs.join(phantom.libraryPath, + "../../www/phantomjs.png"), "b"); + + arm_check_request(this, false, png, "image/png"); + page.open(url, "get", this.step_func_done(function (status) { + assert_equals(status, "success"); + function checkImg() { + var img = document.querySelector("img"); + if (img) { + return { w: img.width, h: img.height }; + } else { + return {}; + } + } + // XFAIL: image doesn't load properly and we receive the dimensions of + // the ?-in-a-box placeholder + assert_deep_equals(page.evaluate(checkImg), { w: 200, h: 200 }); + })); + +}, "handling binary data", { + skip: true, // crash: https://github.com/ariya/phantomjs/issues/13461 + expected_fail: true // received image is corrupt: + // https://github.com/ariya/phantomjs/issues/13026 + // and perhaps others +}); diff --git a/third_party/phantomjs/test/node_modules/dummy_exposed.js b/third_party/phantomjs/test/node_modules/dummy_exposed.js new file mode 100644 index 00000000000..143519bddd5 --- /dev/null +++ b/third_party/phantomjs/test/node_modules/dummy_exposed.js @@ -0,0 +1 @@ +module.exports = module; diff --git a/third_party/phantomjs/test/node_modules/dummy_file.js b/third_party/phantomjs/test/node_modules/dummy_file.js new file mode 100644 index 00000000000..a18d8a9185a --- /dev/null +++ b/third_party/phantomjs/test/node_modules/dummy_file.js @@ -0,0 +1 @@ +module.exports = 'spec/node_modules/dummy_file'; diff --git a/third_party/phantomjs/test/node_modules/dummy_file2.js b/third_party/phantomjs/test/node_modules/dummy_file2.js new file mode 100644 index 00000000000..77e02ec1ebf --- /dev/null +++ b/third_party/phantomjs/test/node_modules/dummy_file2.js @@ -0,0 +1 @@ +module.exports = 'spec/node_modules/dummy_file2'; diff --git a/third_party/phantomjs/test/regression/README b/third_party/phantomjs/test/regression/README new file mode 100644 index 00000000000..2e8394c9e3d --- /dev/null +++ b/third_party/phantomjs/test/regression/README @@ -0,0 +1,3 @@ +Tests in this directory are named for their bug number. +pjs-NNNN corresponds to https://github.com/ariya/phantomjs/issues/NNNN. +webkit-NNNN corresponds to ​https://bugs.webkit.org/show_bug.cgi?id=NNNN. diff --git a/third_party/phantomjs/test/regression/pjs-10690.js b/third_party/phantomjs/test/regression/pjs-10690.js new file mode 100644 index 00000000000..7e45c82d45e --- /dev/null +++ b/third_party/phantomjs/test/regression/pjs-10690.js @@ -0,0 +1,14 @@ +// Issue 10690: the second page load used to crash on OSX. + +var url = TEST_HTTP_BASE + 'regression/pjs-10690/index.html'; +function do_test() { + var page = require('webpage').create(); + + page.open(url, this.step_func_done (function (status) { + assert_equals(status, "success"); + page.release(); + })); +} + +async_test(do_test, "load a page with a downloadable font, once"); +async_test(do_test, "load a page with a downloadable font, again"); diff --git a/third_party/phantomjs/test/regression/pjs-12482.js b/third_party/phantomjs/test/regression/pjs-12482.js new file mode 100644 index 00000000000..7df89dd3540 --- /dev/null +++ b/third_party/phantomjs/test/regression/pjs-12482.js @@ -0,0 +1,48 @@ +//! no-harness + +// https://github.com/ariya/phantomjs/issues/12482 +// regression caused by fix for +// https://github.com/ariya/phantomjs/issues/12431 + +var webpage = require('webpage'); +var sys = require('system'); + +var pages = [ + webpage.create(), + webpage.create(), + webpage.create() +]; + +var loaded = 0; + +sys.stdout.write("1.." + pages.length + "\n"); +setTimeout(function () { phantom.exit(1); }, 200); + +function loadHook (status) { + loaded++; + if (status === "success") { + sys.stdout.write("ok " + loaded + " loading page\n"); + } else { + sys.stdout.write("not ok " + loaded + " loading page\n"); + } + + if (loaded === pages.length) { + pages[1].close(); + setTimeout(function(){ + phantom.exit(0); + sys.stdout.write("not ok " + (pages.length+1) + + " should not get here # TODO\n"); + }, 50); + } +} +function consoleHook (msg) { + sys.stdout.write(msg + "\n"); +} + +for (var i = 0; i < pages.length; i++) { + pages[i].onConsoleMessage = consoleHook; + pages[i].open( + "data:text/html,", + loadHook); +} diff --git a/third_party/phantomjs/test/regression/pjs-13551.js b/third_party/phantomjs/test/regression/pjs-13551.js new file mode 100644 index 00000000000..73236b2cb9d --- /dev/null +++ b/third_party/phantomjs/test/regression/pjs-13551.js @@ -0,0 +1,52 @@ +//! unsupported +// Issue #13551: Crash when switching "back" from frame that no longer +// exists (for whatever reason) + +var webpage = require('webpage'); + +function test_template(parent, action) { + var page; + var url = TEST_HTTP_BASE + + "/regression/pjs-13551/" + parent + "-parent.html"; + var s_callback0, s_callback1, s_callback2; + + function callback0 (n) { + assert_equals(n, 0); + page.onCallback = s_callback1; + page.evaluate(function () { + document.getElementById("prepare").click(); + }); + } + function callback1 (n) { + assert_equals(n, 1); + page.onCallback = s_callback2; + assert_equals(page.switchToFrame("target"), true); + assert_equals(page.switchToFrame("actor"), true); + page.evaluate(function () { + document.getElementById("execute").click(); + }); + } + function callback2 (n) { + assert_equals(n, 2); + assert_is_true(action == 'main' || action == 'parent'); + if (action == 'main') { + page.switchToMainFrame(); // Crash here + } else { + page.switchToParentFrame(); // Or here + } + } + + return function test_action () { + page = webpage.create(); + s_callback0 = this.step_func(callback0); + s_callback1 = this.step_func(callback1); + s_callback2 = this.step_func_done(callback2); + page.onCallback = s_callback0; + page.open(url); + }; +} + +async_test(test_template('closing', 'main'), "main from closed"); +async_test(test_template('closing', 'parent'), "parent from closed"); +async_test(test_template('reloading', 'main'), "main from reloaded"); +async_test(test_template('reloading', 'parent'), "parent from reloaded"); diff --git a/third_party/phantomjs/test/regression/webkit-60448.js b/third_party/phantomjs/test/regression/webkit-60448.js new file mode 100644 index 00000000000..46280936f6a --- /dev/null +++ b/third_party/phantomjs/test/regression/webkit-60448.js @@ -0,0 +1,12 @@ +var url = TEST_HTTP_BASE + "regression/webkit-60448.html"; + +async_test(function () { + var p = require("webpage").create(); + p.open(url, this.step_func_done(function (status) { + assert_equals(status, "success"); + assert_is_true(p.evaluate(function () { + return document.getElementById("test") === null; + })); + })); +}, +"remove an inline HTML element from the document"); diff --git a/third_party/phantomjs/test/run-tests.py b/third_party/phantomjs/test/run-tests.py new file mode 100755 index 00000000000..9262c43c544 --- /dev/null +++ b/third_party/phantomjs/test/run-tests.py @@ -0,0 +1,1051 @@ +#!/usr/bin/env python + +import argparse +import collections +import errno +import glob +import imp +import os +import platform +import posixpath +import re +import shlex +import SimpleHTTPServer +import socket +import SocketServer +import ssl +import string +import cStringIO as StringIO +import subprocess +import sys +import threading +import time +import traceback +import urllib + +# All files matching one of these glob patterns will be run as tests. +TESTS = [ + 'basics/*.js', + 'module/*/*.js', + 'standards/*/*.js', + 'regression/*.js', +] + +TIMEOUT = 7 # Maximum duration of PhantomJS execution (in seconds). + # This is a backstop; testharness.js imposes a shorter + # timeout. Both can be increased if necessary. + +# +# Utilities +# + +# FIXME: assumes ANSI/VT100 escape sequences +# properly this should use curses, but that's an awful lot of work +# One of colors 30 ("black" -- usually a dark gray) and 37 ("white" -- +# usually a very light gray) will almost certainly be illegible +# against the terminal background, so we provide neither. +# The colorization mode is global because so is sys.stdout. +_COLOR_NONE = { + "_": "", "^": "", + "r": "", "R": "", + "g": "", "G": "", + "y": "", "Y": "", + "b": "", "B": "", + "m": "", "M": "", + "c": "", "C": "", +} +_COLOR_ON = { + "_": "\033[0m", "^": "\033[1m", + "r": "\033[31m", "R": "\033[1;31m", + "g": "\033[32m", "G": "\033[1;32m", + "y": "\033[33m", "Y": "\033[1;33m", + "b": "\033[34m", "B": "\033[1;34m", + "m": "\033[35m", "M": "\033[1;35m", + "c": "\033[36m", "C": "\033[1;36m", +} +_COLOR_BOLD = { + "_": "\033[0m", "^": "\033[1m", + "r": "\033[0m", "R": "\033[1m", + "g": "\033[0m", "G": "\033[1m", + "y": "\033[0m", "Y": "\033[1m", + "b": "\033[0m", "B": "\033[1m", + "m": "\033[0m", "M": "\033[1m", + "c": "\033[0m", "C": "\033[1m", +} +_COLORS = None +def activate_colorization(options): + global _COLORS + if options.color == "always": + _COLORS = _COLOR_ON + elif options.color == "never": + _COLORS = _COLOR_NONE + else: + if sys.stdout.isatty() and platform.system() != "Windows": + try: + n = int(subprocess.check_output(["tput", "colors"])) + if n >= 8: + _COLORS = _COLOR_ON + else: + _COLORS = _COLOR_BOLD + except subprocess.CalledProcessError: + _COLORS = _COLOR_NONE + else: + _COLORS = _COLOR_NONE + +def colorize(color, message): + return _COLORS[color] + message + _COLORS["_"] + +# create_default_context and SSLContext were only added in 2.7.9, +# which is newer than the python2 that ships with OSX :-( +# The fallback tries to mimic what create_default_context(CLIENT_AUTH) +# does. Security obviously isn't important in itself for a test +# server, but making sure the PJS client can talk to a server +# configured according to modern TLS best practices _is_ important. +# Unfortunately, there is no way to set things like OP_NO_SSL2 or +# OP_CIPHER_SERVER_PREFERENCE prior to 2.7.9. +CIPHERLIST_2_7_9 = ( + 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:' + 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:' + '!eNULL:!MD5:!DSS:!RC4' +) +def wrap_socket_ssl(sock, base_path): + crtfile = os.path.join(base_path, 'certs/https-snakeoil.crt') + keyfile = os.path.join(base_path, 'certs/https-snakeoil.key') + + try: + ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) + ctx.load_cert_chain(crtfile, keyfile) + return ctx.wrap_socket(sock, server_side=True) + + except AttributeError: + return ssl.wrap_socket(sock, + keyfile=keyfile, + certfile=crtfile, + server_side=True, + ciphers=CIPHERLIST_2_7_9) + +# This should be in the standard library somewhere, but as far as I +# can tell, it isn't. +class ResponseHookImporter(object): + def __init__(self, www_path): + # All Python response hooks, no matter how deep below www_path, + # are treated as direct children of the fake "test_www" package. + if 'test_www' not in sys.modules: + imp.load_source('test_www', www_path + '/__init__.py') + + self.tr = string.maketrans('-./%', '____') + + def __call__(self, path): + modname = 'test_www.' + path.translate(self.tr) + try: + return sys.modules[modname] + except KeyError: + return imp.load_source(modname, path) + +# This should also be in the standard library somewhere, and +# definitely isn't. +# +# FIXME: This currently involves *three* threads for every process, +# and a fourth if the process takes input. (On Unix, clever use of +# select() might be able to get that down to one, but zero is Hard. +# On Windows, we're hosed. 3.4's asyncio module would make everything +# better, but 3.4 is its own can of worms.) +try: + devnull = subprocess.DEVNULL +except: + devnull = os.open(os.devnull, os.O_RDONLY) + +def do_call_subprocess(command, verbose, stdin_data, timeout): + + def read_thread(linebuf, fp): + while True: + line = fp.readline().rstrip() + if not line: break # EOF + line = line.rstrip() + if line: + linebuf.append(line) + if verbose >= 3: + sys.stdout.write(line + '\n') + + def write_thread(data, fp): + fp.writelines(data) + fp.close() + + def reap_thread(proc, timed_out): + if proc.returncode is None: + proc.terminate() + timed_out[0] = True + + class DummyThread: + def start(self): pass + def join(self): pass + + if stdin_data: + stdin = subprocess.PIPE + else: + stdin = devnull + + proc = subprocess.Popen(command, + stdin=stdin, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + + if stdin_data: + sithrd = threading.Thread(target=write_thread, + args=(stdin_data, proc.stdin)) + else: + sithrd = DummyThread() + + stdout = [] + stderr = [] + timed_out = [False] + sothrd = threading.Thread(target=read_thread, args=(stdout, proc.stdout)) + sethrd = threading.Thread(target=read_thread, args=(stderr, proc.stderr)) + rpthrd = threading.Timer(timeout, reap_thread, args=(proc, timed_out)) + + sithrd.start() + sothrd.start() + sethrd.start() + rpthrd.start() + + proc.wait() + if not timed_out[0]: rpthrd.cancel() + + sithrd.join() + sothrd.join() + sethrd.join() + rpthrd.join() + + if timed_out[0]: + stderr.append("TIMEOUT: Process terminated after {} seconds." + .format(timeout)) + if verbose >= 3: + sys.stdout.write(stderr[-1] + "\n") + + rc = proc.returncode + if verbose >= 3: + if rc < 0: + sys.stdout.write("## killed by signal {}\n".format(-rc)) + else: + sys.stdout.write("## exit {}\n".format(rc)) + return proc.returncode, stdout, stderr + +# +# HTTP/HTTPS server, presented on localhost to the tests +# + +class FileHandler(SimpleHTTPServer.SimpleHTTPRequestHandler, object): + + def __init__(self, *args, **kwargs): + self._cached_untranslated_path = None + self._cached_translated_path = None + self.postdata = None + super(FileHandler, self).__init__(*args, **kwargs) + + # silent, do not pollute stdout nor stderr. + def log_message(self, format, *args): + return + + # accept POSTs, read the postdata and stash it in an instance variable, + # then forward to do_GET; handle_request hooks can vary their behavior + # based on the presence of postdata and/or the command verb. + def do_POST(self): + try: + ln = int(self.headers.get('content-length')) + except TypeError, ValueError: + self.send_response(400, 'Bad Request') + self.send_header('Content-Type', 'text/plain') + self.end_headers() + self.wfile.write("No or invalid Content-Length in POST (%r)" + % self.headers.get('content-length')) + return + + self.postdata = self.rfile.read(ln) + self.do_GET() + + # allow provision of a .py file that will be interpreted to + # produce the response. + def send_head(self): + path = self.translate_path(self.path) + + # do not allow direct references to .py(c) files, + # or indirect references to __init__.py + if (path.endswith('.py') or path.endswith('.pyc') or + path.endswith('__init__')): + self.send_error(404, 'File not found') + return None + + if os.path.exists(path): + return super(FileHandler, self).send_head() + + py = path + '.py' + if os.path.exists(py): + try: + mod = self.get_response_hook(py) + return mod.handle_request(self) + except: + self.send_error(500, 'Internal Server Error in '+py) + raise + + self.send_error(404, 'File not found') + return None + + # modified version of SimpleHTTPRequestHandler's translate_path + # to resolve the URL relative to the www/ directory + # (e.g. /foo -> test/www/foo) + def translate_path(self, path): + + # Cache for efficiency, since our send_head calls this and + # then, in the normal case, the parent class's send_head + # immediately calls it again. + if (self._cached_translated_path is not None and + self._cached_untranslated_path == path): + return self._cached_translated_path + + orig_path = path + + # Strip query string and/or fragment, if present. + x = path.find('?') + if x != -1: path = path[:x] + x = path.find('#') + if x != -1: path = path[:x] + + # Ensure consistent encoding of special characters, then + # lowercase everything so that the tests behave consistently + # whether or not the local filesystem is case-sensitive. + path = urllib.quote(urllib.unquote(path)).lower() + + # Prevent access to files outside www/. + # At this point we want specifically POSIX-like treatment of 'path' + # because it is still a URL component and not a filesystem path. + # SimpleHTTPRequestHandler.send_head() expects us to preserve the + # distinction between paths with and without a trailing slash, but + # posixpath.normpath() discards that distinction. + trailing_slash = path.endswith('/') + path = posixpath.normpath(path) + while path.startswith('/'): + path = path[1:] + while path.startswith('../'): + path = path[3:] + + # Now resolve the normalized, clamped path relative to the www/ + # directory, according to local OS conventions. + path = os.path.normpath(os.path.join(self.www_path, *path.split('/'))) + if trailing_slash: + # it must be a '/' even on Windows + path += '/' + + self._cached_untranslated_path = orig_path + self._cached_translated_path = path + return path + +class TCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): + # This is how you are officially supposed to set SO_REUSEADDR per + # https://docs.python.org/2/library/socketserver.html#SocketServer.BaseServer.allow_reuse_address + allow_reuse_address = True + + def __init__(self, use_ssl, handler, base_path, signal_error): + SocketServer.TCPServer.__init__(self, ('localhost', 0), handler) + if use_ssl: + self.socket = wrap_socket_ssl(self.socket, base_path) + self._signal_error = signal_error + + def handle_error(self, request, client_address): + # Ignore errors which can occur naturally if the client + # disconnects in the middle of a request. EPIPE and + # ECONNRESET *should* be the only such error codes + # (according to the OSX manpage for send()). + _, exval, _ = sys.exc_info() + if getattr(exval, 'errno', None) in (errno.EPIPE, errno.ECONNRESET): + return + + # Otherwise, report the error to the test runner. + self._signal_error(sys.exc_info()) + +class HTTPTestServer(object): + def __init__(self, base_path, signal_error, verbose): + self.httpd = None + self.httpsd = None + self.base_path = base_path + self.www_path = os.path.join(base_path, 'www') + self.signal_error = signal_error + self.verbose = verbose + + def __enter__(self): + handler = FileHandler + handler.extensions_map.update({ + '.htm': 'text/html', + '.html': 'text/html', + '.css': 'text/css', + '.js': 'application/javascript', + '.json': 'application/json' + }) + handler.www_path = self.www_path + handler.get_response_hook = ResponseHookImporter(self.www_path) + + self.httpd = TCPServer(False, handler, + self.base_path, self.signal_error) + os.environ['TEST_HTTP_BASE'] = \ + 'http://localhost:{}/'.format(self.httpd.server_address[1]) + httpd_thread = threading.Thread(target=self.httpd.serve_forever) + httpd_thread.daemon = True + httpd_thread.start() + if self.verbose >= 3: + sys.stdout.write("## HTTP server at {}\n".format( + os.environ['TEST_HTTP_BASE'])) + + self.httpsd = TCPServer(True, handler, + self.base_path, self.signal_error) + os.environ['TEST_HTTPS_BASE'] = \ + 'https://localhost:{}/'.format(self.httpsd.server_address[1]) + httpsd_thread = threading.Thread(target=self.httpsd.serve_forever) + httpsd_thread.daemon = True + httpsd_thread.start() + if self.verbose >= 3: + sys.stdout.write("## HTTPS server at {}\n".format( + os.environ['TEST_HTTPS_BASE'])) + + return self + + def __exit__(self, *dontcare): + self.httpd.shutdown() + del os.environ['TEST_HTTP_BASE'] + self.httpsd.shutdown() + del os.environ['TEST_HTTPS_BASE'] + +# +# Running tests and interpreting their results +# +class TestDetailCode(collections.namedtuple("TestDetailCode", ( + "idx", "color", "short_label", "label", "long_label"))): + def __index__(self): return self.idx + def __hash__(self): return self.idx + def __eq__(self, other): return self.idx == other.idx + def __ne__(self, other): return self.idx != other.idx + +class T(object): + PASS = TestDetailCode(0, "g", ".", "pass", "passed") + FAIL = TestDetailCode(1, "R", "F", "FAIL", "failed") + XFAIL = TestDetailCode(2, "y", "f", "xfail", "failed as expected") + XPASS = TestDetailCode(3, "Y", "P", "XPASS", "passed unexpectedly") + ERROR = TestDetailCode(4, "R", "E", "ERROR", "had errors") + SKIP = TestDetailCode(5, "m", "s", "skip", "skipped") + UNSUPPORTED = TestDetailCode(6, "y", "u", "unsupported", "unsupported") + MAX = 7 + +class TestDetail(object): + """Holds one block of details about a test that failed.""" + # types of details: + + def __init__(self, message, test_id, detail_type): + if not isinstance(message, list): + message = [message] + self.message = [line.rstrip() + for chunk in message + for line in chunk.split("\n")] + + self.dtype = detail_type + self.test_id = test_id + + def report(self, fp): + col, label = self.dtype.color, self.dtype.label + if self.test_id: + fp.write("{:>5}: {}\n".format(colorize(col, label), + self.test_id)) + lo = 0 + else: + fp.write("{:>5}: {}\n".format(colorize(col, label), + self.message[0])) + lo = 1 + for line in self.message[lo:]: + fp.write(" {}\n".format(colorize("b", line))) + +class TestGroup(object): + """Holds the result of one group of tests (that is, one .js file), + parsed from the output of run_phantomjs (see below). + Subclasses specify what the output means. + A test with zero details is considered to be successful. + """ + + def __init__(self, name): + self.name = name + self.n = [0]*T.MAX + self.details = [] + + def parse(self, rc, out, err): + raise NotImplementedError + + def _add_d(self, message, test_id, dtype): + self.n[dtype] += 1 + self.details.append(TestDetail(message, test_id, dtype)) + + def add_pass (self, m, t): self._add_d(m, t, T.PASS) + def add_fail (self, m, t): self._add_d(m, t, T.FAIL) + def add_xpass(self, m, t): self._add_d(m, t, T.XPASS) + def add_xfail(self, m, t): self._add_d(m, t, T.XFAIL) + def add_error(self, m, t): self._add_d(m, t, T.ERROR) + def add_skip (self, m, t): self._add_d(m, t, T.SKIP) + def add_unsupported (self, m, t): self._add_d(m, t, T.UNSUPPORTED) + + def default_interpret_exit_code(self, rc): + if rc == 0: + if not self.is_successful() and not self.n[T.ERROR]: + self.add_error([], + "PhantomJS exited successfully when test failed") + + # Exit code -15 indicates a timeout. + elif rc == 1 or rc == -15: + if self.is_successful(): + self.add_error([], "PhantomJS exited unsuccessfully") + + elif rc >= 2: + self.add_error([], "PhantomJS exited with code {}".format(rc)) + else: + self.add_error([], "PhantomJS killed by signal {}".format(-rc)) + + def is_successful(self): + return self.n[T.FAIL] + self.n[T.XPASS] + self.n[T.ERROR] == 0 + + def worst_code(self): + # worst-to-best ordering + for code in (T.ERROR, T.FAIL, T.XPASS, T.SKIP, T.XFAIL, T.PASS, T.UNSUPPORTED): + if self.n[code] > 0: + return code + return T.PASS + + def one_char_summary(self, fp): + code = self.worst_code() + fp.write(colorize(code.color, code.short_label)) + fp.flush() + + def line_summary(self, fp): + code = self.worst_code() + fp.write("{}: {}\n".format(colorize("^", self.name), + colorize(code.color, code.label))) + + def report(self, fp, show_all): + self.line_summary(fp) + need_blank_line = False + for detail in self.details: + if show_all or detail.dtype not in (T.PASS, T.XFAIL, T.SKIP): + detail.report(fp) + need_blank_line = True + if need_blank_line: + fp.write("\n") + + def report_for_verbose_level(self, fp, verbose): + if verbose == 0: + self.one_char_summary(sys.stdout) + elif verbose == 1: + self.report(sys.stdout, False) + else: + self.report(sys.stdout, True) + +class UnsupportedTestGroup(TestGroup): + """Test group which is currently unsupported and should + be skipped altogether. + """ + def __init__(self, name): + TestGroup.__init__(self, name) + self.add_unsupported('', 'Skipping the whole file'); + + +class ExpectTestGroup(TestGroup): + """Test group whose output must be exactly as specified by directives + in the file. This is how you test for an _unsuccessful_ exit code, + or for output appearing on a specific one of stdout/stderr. + """ + def __init__(self, name, rc_exp, stdout_exp, stderr_exp, + rc_xfail, stdout_xfail, stderr_xfail): + TestGroup.__init__(self, name) + if rc_exp is None: rc_exp = 0 + self.rc_exp = rc_exp + self.stdout_exp = stdout_exp + self.stderr_exp = stderr_exp + self.rc_xfail = rc_xfail + self.stdout_xfail = stdout_xfail + self.stderr_xfail = stderr_xfail + + def parse(self, rc, out, err): + self.parse_output("stdout", self.stdout_exp, out, self.stdout_xfail) + self.parse_output("stderr", self.stderr_exp, err, self.stderr_xfail) + + exit_msg = ["expected exit code {} got {}" + .format(self.rc_exp, rc)] + + if rc != self.rc_exp: + exit_desc = "did not exit as expected" + if self.rc_xfail: + self.add_xfail(exit_msg, exit_desc) + else: + self.add_fail(exit_msg, exit_desc) + else: + exit_desc = "exited as expected" + if self.rc_xfail: + self.add_xpass(exit_msg, exit_desc) + else: + self.add_pass(exit_msg, exit_desc) + + def parse_output(self, what, exp, got, xfail): + diff = [] + le = len(exp) + lg = len(got) + for i in range(max(le, lg)): + e = "" + g = "" + if i < le: e = exp[i] + if i < lg: g = got[i] + if e != g: + diff.extend(("{}: line {} not as expected".format(what, i+1), + "-" + repr(e)[1:-1], + "+" + repr(g)[1:-1])) + + if diff: + desc = what + " not as expected" + if xfail: + self.add_xfail(diff, desc) + else: + self.add_fail(diff, desc) + else: + desc = what + " as expected" + if xfail: + self.add_xpass(diff, desc) + else: + self.add_pass(diff, desc) + + +class TAPTestGroup(TestGroup): + """Test group whose output is interpreted according to a variant of the + Test Anything Protocol (http://testanything.org/tap-specification.html). + + Relative to that specification, these are the changes: + + * Plan-at-the-end, explanations for directives, and "Bail out!" + are not supported. ("1..0 # SKIP: explanation" *is* supported.) + * "Anything else" lines are an error. + * Repeating a test point number, or using one outside the plan + range, is an error (this is unspecified in TAP proper). + * Diagnostic lines beginning with # are taken as additional + information about the *next* test point. Diagnostic lines + beginning with ## are ignored. + * Directives are case sensitive. + + """ + + diag_r = re.compile(r"^#(#*)\s*(.*)$") + plan_r = re.compile(r"^1..(\d+)(?:\s*\#\s*SKIP(?::\s*(.*)))?$") + test_r = re.compile(r"^(not ok|ok)\s*" + r"([0-9]+)?\s*" + r"([^#]*)(?:# (TODO|SKIP))?$") + + def parse(self, rc, out, err): + self.parse_tap(out, err) + self.default_interpret_exit_code(rc) + + def parse_tap(self, out, err): + points_already_used = set() + messages = [] + + # Look for the plan. + # Diagnostic lines are allowed to appear above the plan, but not + # test lines. + for i in range(len(out)): + line = out[i] + m = self.diag_r.match(line) + if m: + if not m.group(1): + messages.append(m.group(2)) + continue + + m = self.plan_r.match(line) + if m: + break + + messages.insert(0, line) + self.add_error(messages, "Plan line not interpretable") + if i + 1 < len(out): + self.add_skip(out[(i+1):], "All further output ignored") + return + else: + self.add_error(messages, "No plan line detected in output") + return + + max_point = int(m.group(1)) + if max_point == 0: + if any(msg.startswith("ERROR:") for msg in messages): + self.add_error(messages, m.group(2) or "Test group skipped") + else: + self.add_skip(messages, m.group(2) or "Test group skipped") + if i + 1 < len(out): + self.add_skip(out[(i+1):], "All further output ignored") + return + + prev_point = 0 + + for i in range(i+1, len(out)): + line = out[i] + m = self.diag_r.match(line) + if m: + if not m.group(1): + messages.append(m.group(2)) + continue + m = self.test_r.match(line) + if m: + status = m.group(1) + point = m.group(2) + desc = m.group(3) + dirv = m.group(4) + + if point: + point = int(point) + else: + point = prev_point + 1 + + if point in points_already_used: + # A reused test point is an error. + self.add_error(messages, desc + " [test point repeated]") + else: + points_already_used.add(point) + # A point above the plan limit is an automatic *fail*. + # The test suite relies on this in testing exit(). + if point > max_point: + status = "not ok" + + if status == "ok": + if not dirv: + self.add_pass(messages, desc) + elif dirv == "TODO": + self.add_xpass(messages, desc) + elif dirv == "SKIP": + self.add_skip(messages, desc) + else: + self.add_error(messages, desc + + " [ok, with invalid directive "+dirv+"]") + else: + if not dirv: + self.add_fail(messages, desc) + elif dirv == "TODO": + self.add_xfail(messages, desc) + else: + self.add_error(messages, desc + + " [not ok, with invalid directive "+dirv+"]") + + del messages[:] + prev_point = point + + else: + self.add_error([line], "neither a test nor a diagnostic") + + # Any output on stderr is an error, with one exception: the timeout + # message added by record_process_output, which is treated as an + # unnumbered "not ok". + if err: + if len(err) == 1 and err[0].startswith("TIMEOUT: "): + points_already_used.add(prev_point + 1) + self.add_fail(messages, err[0][len("TIMEOUT: "):]) + else: + self.add_error(err, "Unexpected output on stderr") + + # Any missing test points are fails. + for pt in range(1, max_point+1): + if pt not in points_already_used: + self.add_fail([], "test {} did not report status".format(pt)) + +class TestRunner(object): + def __init__(self, base_path, phantomjs_exe, options): + self.base_path = base_path + self.cert_path = os.path.join(base_path, 'certs') + self.harness = os.path.join(base_path, 'testharness.js') + self.phantomjs_exe = phantomjs_exe + self.verbose = options.verbose + self.debugger = options.debugger + self.to_run = options.to_run + self.run_unsupported = options.run_unsupported + self.server_errs = [] + + def signal_server_error(self, exc_info): + self.server_errs.append(exc_info) + + def get_base_command(self, debugger): + if debugger is None: + return [self.phantomjs_exe] + elif debugger == "gdb": + return ["gdb", "--args", self.phantomjs_exe] + elif debugger == "lldb": + return ["lldb", "--", self.phantomjs_exe] + elif debugger == "valgrind": + return ["valgrind", self.phantomjs_exe] + else: + raise RuntimeError("Don't know how to invoke " + self.debugger) + + def run_phantomjs(self, script, + script_args=[], pjs_args=[], stdin_data=[], + timeout=TIMEOUT, silent=False): + verbose = self.verbose + debugger = self.debugger + if silent: + verbose = False + debugger = None + + output = [] + command = self.get_base_command(debugger) + command.extend(pjs_args) + command.append(script) + if verbose: + command.append('--verbose={}'.format(verbose)) + command.extend(script_args) + + if verbose >= 3: + sys.stdout.write("## running {}\n".format(" ".join(command))) + + if debugger: + # FIXME: input-feed mode doesn't work with a debugger, + # because how do you tell the debugger that the *debuggee* + # needs to read from a pipe? + subprocess.call(command) + return 0, [], [] + else: + return do_call_subprocess(command, verbose, stdin_data, timeout) + + def run_test(self, script, name): + script_args = [] + pjs_args = [] + use_harness = True + use_snakeoil = False + stdin_data = [] + stdout_exp = [] + stderr_exp = [] + rc_exp = None + stdout_xfail = False + stderr_xfail = False + rc_xfail = False + timeout = TIMEOUT + unsupported = False + + def require_args(what, i, tokens): + if i+1 == len(tokens): + raise ValueError(what + "directive requires an argument") + + if self.verbose >= 3: + sys.stdout.write(colorize("^", name) + ":\n") + # Parse any directives at the top of the script. + try: + with open(script, "rt") as s: + for line in s: + if not line.startswith("//!"): + break + tokens = shlex.split(line[3:], comments=True) + + skip = False + for i in range(len(tokens)): + if skip: + skip = False + continue + tok = tokens[i] + if tok == "unsupported": + unsupported = True + elif tok == "no-harness": + use_harness = False + elif tok == "snakeoil": + use_snakeoil = True + elif tok == "expect-exit-fails": + rc_xfail = True + elif tok == "expect-stdout-fails": + stdout_xfail = True + elif tok == "expect-stderr-fails": + stderr_xfail = True + elif tok == "timeout:": + require_args(tok, i, tokens) + timeout = float(tokens[i+1]) + if timeout <= 0: + raise ValueError("timeout must be positive") + skip = True + elif tok == "expect-exit:": + require_args(tok, i, tokens) + rc_exp = int(tokens[i+1]) + skip = True + elif tok == "phantomjs:": + require_args(tok, i, tokens) + pjs_args.extend(tokens[(i+1):]) + break + elif tok == "script:": + require_args(tok, i, tokens) + script_args.extend(tokens[(i+1):]) + break + elif tok == "stdin:": + require_args(tok, i, tokens) + stdin_data.append(" ".join(tokens[(i+1):]) + "\n") + break + elif tok == "expect-stdout:": + require_args(tok, i, tokens) + stdout_exp.append(" ".join(tokens[(i+1):])) + break + elif tok == "expect-stderr:": + require_args(tok, i, tokens) + stderr_exp.append(" ".join(tokens[(i+1):])) + break + else: + raise ValueError("unrecognized directive: " + tok) + + except Exception as e: + grp = TestGroup(name) + if hasattr(e, 'strerror') and hasattr(e, 'filename'): + grp.add_error([], '{} ({}): {}\n' + .format(name, e.filename, e.strerror)) + else: + grp.add_error([], '{} ({}): {}\n' + .format(name, script, str(e))) + return grp + + if use_harness: + script_args.insert(0, script) + script = self.harness + + if use_snakeoil: + pjs_args.insert(0, '--ssl-certificates-path=' + self.cert_path) + + if unsupported and not self.run_unsupported: + return UnsupportedTestGroup(name) + rc, out, err = self.run_phantomjs(script, script_args, pjs_args, + stdin_data, timeout) + + if rc_exp or stdout_exp or stderr_exp: + grp = ExpectTestGroup(name, + rc_exp, stdout_exp, stderr_exp, + rc_xfail, stdout_xfail, stderr_xfail) + else: + grp = TAPTestGroup(name) + grp.parse(rc, out, err) + return grp + + def run_tests(self): + start = time.time() + base = self.base_path + nlen = len(base) + 1 + + results = [] + + for test_glob in TESTS: + test_glob = os.path.join(base, test_glob) + + for test_script in sorted(glob.glob(test_glob)): + tname = os.path.splitext(test_script)[0][nlen:] + if self.to_run: + for to_run in self.to_run: + if to_run in tname: + break + else: + continue + + any_executed = True + grp = self.run_test(test_script, tname) + grp.report_for_verbose_level(sys.stdout, self.verbose) + results.append(grp) + + grp = TestGroup("HTTP server errors") + for ty, val, tb in self.server_errs: + grp.add_error(traceback.format_tb(tb, 5), + traceback.format_exception_only(ty, val)[-1]) + grp.report_for_verbose_level(sys.stdout, self.verbose) + results.append(grp) + + sys.stdout.write("\n") + return self.report(results, time.time() - start) + + def report(self, results, elapsed): + # There is always one test group, for the HTTP server errors. + if len(results) == 1: + sys.stderr.write("No tests selected for execution.\n") + return 1 + + n = [0] * T.MAX + + for grp in results: + if self.verbose == 0 and not grp.is_successful(): + grp.report(sys.stdout, False) + for i, x in enumerate(grp.n): n[i] += x + + sys.stdout.write("{:6.3f}s elapsed\n".format(elapsed)) + for s in (T.PASS, T.FAIL, T.XPASS, T.XFAIL, T.ERROR, T.SKIP, T.UNSUPPORTED): + if n[s]: + sys.stdout.write(" {:>4} {}\n".format(n[s], s.long_label)) + + if n[T.FAIL] == 0 and n[T.XPASS] == 0 and n[T.ERROR] == 0: + return 0 + else: + return 1 + +def init(): + base_path = os.path.normpath(os.path.dirname(os.path.abspath(__file__))) + phantomjs_exe = os.path.normpath(base_path + '/../../../index.js') + if not os.path.isfile(phantomjs_exe): + sys.stdout.write("{} is unavailable, cannot run tests.\n" + .format(phantomjs_exe)) + sys.exit(1) + + parser = argparse.ArgumentParser(description='Run PhantomJS tests.') + parser.add_argument('-v', '--verbose', action='count', default=0, + help='Increase verbosity of logs (repeat for more)') + parser.add_argument('to_run', nargs='*', metavar='test', + help='tests to run (default: all of them)') + parser.add_argument('--debugger', default=None, + help="Run PhantomJS under DEBUGGER") + parser.add_argument('--run-unsupported', action='count', default=0, + help='Run unsupported tests.') + parser.add_argument('--color', metavar="WHEN", default='auto', + choices=['always', 'never', 'auto'], + help="colorize the output; can be 'always'," + " 'never', or 'auto' (the default)") + + options = parser.parse_args() + activate_colorization(options) + runner = TestRunner(base_path, phantomjs_exe, options) + if options.verbose: + rc, ver, err = runner.run_phantomjs('--version', silent=True) + if rc != 0 or len(ver) != 1 or len(err) != 0: + sys.stdout.write(colorize("R", "FATAL")+": Version check failed\n") + for l in ver: + sys.stdout.write(colorize("b", "## " + l) + "\n") + for l in err: + sys.stdout.write(colorize("b", "## " + l) + "\n") + sys.stdout.write(colorize("b", "## exit {}".format(rc)) + "\n") + sys.exit(1) + + sys.stdout.write(colorize("b", "## Testing PhantomJS "+ver[0])+"\n") + + # Run all the tests in Chatham Islands Standard Time, UTC+12:45. + # This timezone is deliberately chosen to be unusual: it's not a + # whole number of hours offset from UTC *and* it's more than twelve + # hours offset from UTC. + # + # The Chatham Islands do observe daylight savings, but we don't + # implement that because testsuite issues only reproducible on two + # particular days out of the year are too much tsuris. + # + # Note that the offset in a TZ value is the negative of the way it's + # usually written, e.g. UTC+1 would be xxx-1:00. + os.environ["TZ"] = "CIST-12:45:00" + + return runner + +def main(): + runner = init() + try: + with HTTPTestServer(runner.base_path, + runner.signal_server_error, + runner.verbose): + sys.exit(runner.run_tests()) + + except Exception: + trace = traceback.format_exc(5).split("\n") + # there will be a blank line at the end of 'trace' + sys.stdout.write(colorize("R", "FATAL") + ": " + trace[-2] + "\n") + for line in trace[:-2]: + sys.stdout.write(colorize("b", "## " + line) + "\n") + + sys.exit(1) + + except KeyboardInterrupt: + sys.exit(2) + +main() diff --git a/third_party/phantomjs/test/standards/console/console_log.js b/third_party/phantomjs/test/standards/console/console_log.js new file mode 100644 index 00000000000..7b17aba81c8 --- /dev/null +++ b/third_party/phantomjs/test/standards/console/console_log.js @@ -0,0 +1,9 @@ +async_test(function () { + var page = require('webpage').create(); + page.onConsoleMessage = this.step_func_done(function (msg) { + assert_equals(msg, "answer 42"); + }); + page.evaluate(function () { + console.log('answer', 42); + }); +}, "console.log should support multiple arguments"); diff --git a/third_party/phantomjs/test/standards/javascript/date.js b/third_party/phantomjs/test/standards/javascript/date.js new file mode 100644 index 00000000000..b2a1f97f83a --- /dev/null +++ b/third_party/phantomjs/test/standards/javascript/date.js @@ -0,0 +1,12 @@ +test(function() { + var date = new Date('2012-09-07'); + assert_not_equals(date.toString(), 'Invalid Date'); + assert_equals(date.getUTCDate(), 7); + assert_equals(date.getUTCMonth(), 8); + assert_equals(date.getYear(), 112); +}, "new Date()"); + +test(function () { + var date = Date.parse("2012-01-01"); + assert_equals(date, 1325376000000); +}, "Date.parse()"); diff --git a/third_party/phantomjs/test/standards/javascript/function.js b/third_party/phantomjs/test/standards/javascript/function.js new file mode 100644 index 00000000000..2b6f4734c76 --- /dev/null +++ b/third_party/phantomjs/test/standards/javascript/function.js @@ -0,0 +1,46 @@ +test(function () { + assert_type_of(Function.length, 'number'); + assert_type_of(Function.prototype, 'function'); + assert_type_of(Function.prototype.apply, 'function'); + assert_type_of(Function.prototype.bind, 'function'); + assert_type_of(Function.prototype.call, 'function'); + assert_type_of(Function.prototype.name, 'string'); + assert_type_of(Function.prototype.toString, 'function'); +}, "Function properties"); + +test(function () { + var f = function foo(){}; + assert_equals(f.name, 'foo'); +}, ".name"); + +test(function () { + assert_equals(Function.length, 1); + assert_equals(function(){}.length, 0); + assert_equals(function(x){}.length, 1); + assert_equals(function(x, y){}.length, 2); + assert_equals(function(x, y){}.length, 2); +}, ".length"); + +test(function () { + var args, keys, str, enumerable; + (function() { + args = arguments; + keys = Object.keys(arguments); + str = JSON.stringify(arguments); + enumerable = false; + for (var i in arguments) enumerable = true; + })(14); + + assert_type_of(args, 'object'); + assert_type_of(args.length, 'number'); + assert_equals(args.toString(), '[object Arguments]'); + assert_equals(args.length, 1); + assert_equals(args[0], 14); + + assert_type_of(keys.length, 'number'); + assert_equals(keys.length, 1); + assert_equals(keys[0], "0"); + + assert_equals(str, '{"0":14}'); + assert_is_true(enumerable); +}, "arguments object"); diff --git a/third_party/phantomjs/test/testharness.js b/third_party/phantomjs/test/testharness.js new file mode 100644 index 00000000000..706048b3d79 --- /dev/null +++ b/third_party/phantomjs/test/testharness.js @@ -0,0 +1,1489 @@ +/* vim: set expandtab shiftwidth=4 tabstop=4: */ +/*global require, phantom, setTimeout, clearTimeout */ + +/* + This file is part of the PhantomJS project from Ofi Labs. + + Copyright 2015 Zachary Weinberg + + Based on testharness.js + produced by the W3C and distributed under the W3C 3-Clause BSD + License . + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of the 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 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. + + */ + +(function () { + +"use strict"; + +/** Public API: Defining and running tests. + * + * Compared to the W3C testharness.js, a number of minor changes have + * been made to fit the rather different PhantomJS controller + * environment, but the basic API is the same. + */ + +/** Define an asynchronous test. Returns a Test object. In response + to appropriate events, call the Test object's step() method, + passing a function containing assertions (as for synch tests). + Eventually, call the Test object's done() method (inside a step). + + All arguments are optional. If |func| is provided, it is called + immediately (after the previous test completes) as the first step + function. |properties| is the same as for test(). + + Test has several convenience methods for creating step functions, + see below. */ +function async_test(func, name, properties) { + var test_obj; + + if (func && typeof func !== "function") { + properties = name; + name = func; + func = null; + } + test_obj = new Test(test_name(func, name), properties); + if (func) { + test_obj.step(func); + } + return test_obj; +} +expose(async_test, 'async_test'); + +/** Define a synchronous test, which is just an asynchronous test that + calls done() immediately after its first step function (func) returns. + + |func| is a function containing the test code, and |name| + (optionally) is a descriptive name for the test. |func| will be + called (after the previous test completes), with |this| a Test + object (see below), and should make use of the global assert_* + functions. |properties| is an optional dictionary of test + properties; currently only one is defined: + + timeout - Timeout for this test, in milliseconds. */ +function test(func, name, properties) { + return async_test(function sync_step () { + func.call(this); + this.done(); + }, name, properties); +} +expose(test, 'test'); + +/** Define a series of synchronous tests all at once. + Easiest to explain by example: + + generate_tests(assert_equals, [ + ["Sum one and one", 1+1, 2], + ["Sum one and zero", 1+0, 1] + ]); + + is equivalent to + + test(function() {assert_equals(1+1, 2)}, "Sum one and one"); + test(function() {assert_equals(1+0, 1)}, "Sum one and zero"); + + The first argument can be an arbitrary function, and you can provide + as many arguments in each test vector entry as you like. + + The properties argument can be a single dictionary, which is applied to + all the tests, or an array, applied entry-by-entry. + */ +function generate_tests(func, args, properties) { + function generate_one_test(argv) { + return function generated_step () { + // 'this' will be set by bind() inside test(). + func.apply(this, argv); + }; + } + + var i; + for (i = 0; i < args.length; i++) { + test(generate_one_test(args[i].slice(1)), + args[i][0], + Array.isArray(properties) ? properties[i] : properties); + } +} +expose(generate_tests, 'generate_tests'); + +/** Set up the test harness. Does nothing if called after any test has + begun execution. May be called as setup(func), setup(properties), or + setup(func, properties). |func| is a function to call synchronously; + if it throws an exception the entire test group is considered failed. + |properties| is a dictionary containing one or more of these keys: + + explicit_done - Wait for an explicit call to done() before + declaring all tests complete (see below; implicitly true for + single-test files) + + allow_uncaught_exception - Don't treat an uncaught exception from + non-test code as an error. (Exceptions thrown out of test + functions are still errors.) + + timeout - Global timeout in milliseconds (default: 5 seconds) + test_timeout - Per-test timeout in milliseconds, unless overridden + by the timeout property on a specific test (default: none) + */ +function setup(func_or_properties, maybe_properties) { + var func = null, + properties = {}; + + if (arguments.length === 2) { + func = func_or_properties; + properties = maybe_properties; + } else if (typeof func_or_properties === "function") { + func = func_or_properties; + } else { + properties = func_or_properties; + } + tests.setup(func, properties); +} +expose(setup, 'setup'); + +/** Signal that all tests are complete. Must be called explicitly if + setup({explicit_done: true}) was used; otherwise implicitly + happens when all individual tests are done. */ +function done() { + tests.end_wait(); +} +expose(done, 'done'); + + +/** Public API: Assertions. + * All assertion functions take a |description| argument which is used to + * annotate any failing tests. + */ + +/** Assert that |actual| is strictly true. */ +function assert_is_true(actual, description) { + assert(actual === true, "assert_is_true", description, + "expected true got ${actual}", {actual: actual}); +} +expose(assert_is_true, 'assert_is_true'); + +/** Assert that |actual| is strictly false. */ +function assert_is_false(actual, description) { + assert(actual === false, "assert_is_false", description, + "expected false got ${actual}", {actual: actual}); +} +expose(assert_is_false, 'assert_is_false'); + +/** Assert that |actual| is strictly equal to |expected|. + The test is even more stringent than === (see same_value, below). */ +function assert_equals(actual, expected, description) { + if (typeof actual !== typeof expected) { + assert(false, "assert_equals", description, + "expected (${expectedT}) ${expected} " + + "but got (${actualT}) ${actual}", + {expectedT: typeof expected, + expected: expected, + actualT: typeof actual, + actual: actual}); + } + assert(same_value(actual, expected), "assert_equals", description, + "expected ${expected} but got ${actual}", + {expected: expected, actual: actual}); +} +expose(assert_equals, 'assert_equals'); + +/** Assert that |actual| is not strictly equal to |expected|, using the + same extra-stringent criterion as for assert_equals. */ +function assert_not_equals(actual, expected, description) { + if (typeof actual !== typeof expected) { + return; + } + assert(!same_value(actual, expected), "assert_not_equals", description, + "got disallowed value ${actual}", + {actual: actual}); +} +expose(assert_not_equals, 'assert_not_equals'); + +/** Assert that |expected|, a duck-typed array, contains |actual|, + according to indexOf. */ +function assert_in_array(actual, expected, description) { + assert(expected.indexOf(actual) !== -1, "assert_in_array", description, + "value ${actual} not in array ${expected}", + {actual: actual, expected: expected}); +} +expose(assert_in_array, 'assert_in_array'); + +/** Assert that |expected| and |actual| have all the same properties, + which are, recursively, strictly equal. For primitive types this + is the same as |assert_equals|. + */ +function assert_deep_equals(actual, expected, description) { + var stack = []; + function check_equal_r(act, exp) { + if (is_primitive_value(exp) || is_primitive_value(act)) { + assert(same_value(act, exp), + "assert_deep_equals", description, + "expected ${exp} but got ${act}" + + " (top level: expected ${expected} but got ${actual})", + {exp: exp, act: act, expected: expected, actual: actual}); + + } else if (stack.indexOf(act) === -1) { + var ka = {}, ke = {}, k; + stack.push(act); + + Object.getOwnPropertyNames(actual).forEach(function (x) { + ka[x] = true; + }); + Object.getOwnPropertyNames(expected).forEach(function (x) { + ke[x] = true; + }); + + for (k in ke) { + assert(k in ka, + "assert_deep_equals", description, + "expected property ${k} missing" + + " (top level: expected ${expected} but got ${actual})", + {k: k, expected: expected, actual: actual}); + + check_equal_r(act[k], exp[k]); + delete ka[k]; + } + for (k in ka) { + assert(false, "assert_deep_equals", description, + "unexpected property ${k}" + + " (top level: expected ${expected} but got ${actual})", + {k: k, expected: expected, actual: actual}); + } + + stack.pop(); + } + } + check_equal_r(actual, expected); +} +expose(assert_deep_equals, 'assert_deep_equals'); + +/** Assert that |expected| and |actual|, both primitive numbers, are + within |epsilon| of each other. */ +function assert_approx_equals(actual, expected, epsilon, description) { + assert(typeof actual === "number", + "assert_approx_equals", description, + "expected a number but got a ${type_actual}", + {type_actual: typeof actual}); + assert(typeof expected === "number", + "assert_approx_equals", description, + "expectation should be a number, got a ${type_expected}", + {type_expected: typeof expected}); + assert(typeof epsilon === "number", + "assert_approx_equals", description, + "epsilon should be a number but got a ${type_epsilon}", + {type_epsilon: typeof epsilon}); + + assert(Math.abs(actual - expected) <= epsilon, + "assert_approx_equals", description, + "expected ${expected} +/- ${epsilon} but got ${actual}", + {expected: expected, actual: actual, epsilon: epsilon}); +} +expose(assert_approx_equals, 'assert_approx_equals'); + +/** Assert that |actual| is less than |expected|, where both are + primitive numbers. */ +function assert_less_than(actual, expected, description) { + assert(typeof actual === "number", + "assert_less_than", description, + "expected a number but got a ${type_actual}", + {type_actual: typeof actual}); + assert(typeof expected === "number", + "assert_approx_equals", description, + "expectation should be a number, got a ${type_expected}", + {type_expected: typeof expected}); + + assert(actual < expected, + "assert_less_than", description, + "expected a number less than ${expected} but got ${actual}", + {expected: expected, actual: actual}); +} +expose(assert_less_than, 'assert_less_than'); + +/** Assert that |actual| is greater than |expected|, where both are + primitive numbers. */ +function assert_greater_than(actual, expected, description) { + assert(typeof actual === "number", + "assert_greater_than", description, + "expected a number but got a ${type_actual}", + {type_actual: typeof actual}); + assert(typeof expected === "number", + "assert_approx_equals", description, + "expectation should be a number, got a ${type_expected}", + {type_expected: typeof expected}); + + assert(actual > expected, + "assert_greater_than", description, + "expected a number greater than ${expected} but got ${actual}", + {expected: expected, actual: actual}); +} +expose(assert_greater_than, 'assert_greater_than'); + +/** Assert that |actual| is less than or equal to |expected|, where + both are primitive numbers. */ +function assert_less_than_equal(actual, expected, description) { + assert(typeof actual === "number", + "assert_less_than_equal", description, + "expected a number but got a ${type_actual}", + {type_actual: typeof actual}); + assert(typeof expected === "number", + "assert_approx_equals", description, + "expectation should be a number, got a ${type_expected}", + {type_expected: typeof expected}); + + assert(actual <= expected, + "assert_less_than", description, + "expected a number less than or equal to ${expected} "+ + "but got ${actual}", + {expected: expected, actual: actual}); +} +expose(assert_less_than_equal, 'assert_less_than_equal'); + +/** Assert that |actual| is greater than or equal to |expected|, where + both are primitive numbers. */ +function assert_greater_than_equal(actual, expected, description) { + assert(typeof actual === "number", + "assert_greater_than_equal", description, + "expected a number but got a ${type_actual}", + {type_actual: typeof actual}); + assert(typeof expected === "number", + "assert_approx_equals", description, + "expectation should be a number, got a ${type_expected}", + {type_expected: typeof expected}); + + assert(actual >= expected, + "assert_greater_than_equal", description, + "expected a number greater than or equal to ${expected} "+ + "but got ${actual}", + {expected: expected, actual: actual}); +} +expose(assert_greater_than_equal, 'assert_greater_than_equal'); + +/** Assert that |actual|, a string, matches a regexp, |expected|. */ +function assert_regexp_match(actual, expected, description) { + assert(expected.test(actual), + "assert_regexp_match", description, + "expected ${actual} to match ${expected}", + {expected: expected, actual: actual}); +} +expose(assert_regexp_match, 'assert_regexp_match'); + +/** Assert that |actual|, a string, does _not_ match a regexp, |expected|. */ +function assert_regexp_not_match(actual, expected, description) { + assert(!expected.test(actual), + "assert_regexp_not_match", description, + "expected ${actual} not to match ${expected}", + {expected: expected, actual: actual}); +} +expose(assert_regexp_not_match, 'assert_regexp_not_match'); + +/** Assert that |typeof object| is strictly equal to |type|. */ +function assert_type_of(object, type, description) { + assert(typeof object === type, + "assert_type_of", description, + "expected typeof ${object} to be ${expected}, got ${actual}", + {object: object, expected: type, actual: typeof object}); +} +expose(assert_type_of, 'assert_type_of'); + +/** Assert that |object instanceof type|. */ +function assert_instance_of(object, type, description) { + assert(object instanceof type, + "assert_instance_of", description, + "expected ${object} to be instanceof ${expected}", + {object: object, expected: type}); +} +expose(assert_instance_of, 'assert_instance_of'); + +/** Assert that |object| has the class string |expected|. */ +function assert_class_string(object, expected, description) { + var actual = ({}).toString.call(object).slice(8, -1); + assert(actual === expected, + "assert_class_string", description, + "expected ${object} to have class string ${expected}, "+ + "but got ${actual}", + {object: object, expected: expected, actual: actual}); +} +expose(assert_class_string, 'assert_class_string'); + +/** Assert that |object| has a property named |name|. */ +function assert_own_property(object, name, description) { + assert(typeof object === "object", + "assert_own_property", description, + "provided value is not an object"); + + assert("hasOwnProperty" in object, + "assert_own_property", description, + "provided value is an object but has no hasOwnProperty method"); + + assert(object.hasOwnProperty(name), + "assert_own_property", description, + "expected property ${name} missing", {name: name}); +} +expose(assert_own_property, 'assert_own_property'); + +/** Assert that |object| inherits a property named |name|. + Note: this assertion will fail for objects that have an + own-property named |name|. */ +function assert_inherits(object, name, description) { + assert(typeof object === "object", + "assert_inherits", description, + "provided value is not an object"); + + assert("hasOwnProperty" in object, + "assert_inherits", description, + "provided value is an object but has no hasOwnProperty method"); + + assert(!object.hasOwnProperty(name), + "assert_inherits", description, + "property ${p} found on object, expected only in prototype chain", + {p: name}); + + assert(name in object, + "assert_inherits", description, + "property ${p} not found in prototype chain", + {p: name}); + +} +expose(assert_inherits, 'assert_inherits'); + +/** Assert that |object| neither has nor inherits a property named |name|. */ +function assert_no_property(object, name, description) { + assert(typeof object === "object", + "assert_no_property", description, + "provided value is not an object"); + + assert("hasOwnProperty" in object, + "assert_no_property", description, + "provided value is an object but has no hasOwnProperty method"); + + assert(!object.hasOwnProperty(name), + "assert_no_property", description, + "property ${p} found on object, expected to be absent", + {p: name}); + + assert(!(name in object), + "assert_no_property", description, + "property ${p} found in prototype chain, expected to be absent", + {p: name}); +} +expose(assert_no_property, 'assert_no_property'); + +/** Assert that property |name| of |object| is read-only according + to its property descriptor. */ +function assert_readonly(object, name, description) { + var o = {}, desc; + + assert('getOwnPropertyDescriptor' in o, + "assert_readonly", description, + "Object.getOwnPropertyDescriptor is missing"); + + assert(object.hasOwnProperty(name), + "assert_readonly", description, + "expected property ${name} missing", {name: name}); + + desc = o.getOwnPropertyDescriptor.call(object, name); + if ('writable' in desc) { + assert(!desc.writable, "assert_readonly", description, + "data property ${name} is writable (expected read-only)", + {name: name}); + } else { + assert('get' in desc && 'set' in desc, + "assert_readonly", description, + "unrecognized type of property descriptor "+ + "for ${name}: ${desc}", + {name: name, desc: desc}); + assert(desc.set === undefined, + "assert_readonly", description, + "property ${name} has a setter (expected read-only)", + {name: name, desc: desc}); + } +} +expose(assert_readonly, 'assert_readonly'); + +/** Assert that |func| throws an exception described by |code|. + |func| is called with no arguments and no |this| -- use bind() if + that's a problem. |code| can take one of two forms: + + string - the thrown exception must be a DOMException with the + given name, e.g., "TimeoutError", or else it must + stringify to this string. + + object - must have one or more of the properties "code", "name", + and "message". Whichever properties are present must + match the corresponding properties of the thrown + exception. As a special case, "message" will also match + the stringification of the exception. +*/ + +function assert_throws(code, func, description) { + var name_code_map = { + IndexSizeError: 1, + HierarchyRequestError: 3, + WrongDocumentError: 4, + InvalidCharacterError: 5, + NoModificationAllowedError: 7, + NotFoundError: 8, + NotSupportedError: 9, + InvalidStateError: 11, + SyntaxError: 12, + InvalidModificationError: 13, + NamespaceError: 14, + InvalidAccessError: 15, + TypeMismatchError: 17, + SecurityError: 18, + NetworkError: 19, + AbortError: 20, + URLMismatchError: 21, + QuotaExceededError: 22, + TimeoutError: 23, + InvalidNodeTypeError: 24, + DataCloneError: 25, + + UnknownError: 0, + ConstraintError: 0, + DataError: 0, + TransactionInactiveError: 0, + ReadOnlyError: 0, + VersionError: 0 + }; + + if (typeof code === "object") { + assert("name" in code || "code" in code || "message" in code, + "assert_throws", description, + "exception spec ${code} has no 'name', 'code', or 'message'" + + "properties", + {code: code}); + } else if (name_code_map.hasOwnProperty(code)) { + code = { name: code, + code: name_code_map[code] }; + } else { + code = { message: code.toString() }; + } + + try { + func(); + assert(false, "assert_throws", description, + "${func} did not throw", {func: func}); + } catch (e) { + if (e instanceof AssertionError) { + throw e; + } + + // Backward compatibility wart for DOMExceptions identified + // only by numeric code. + if ("code" in code && code.code !== 0 && + (!("name" in e) || e.name === e.name.toUpperCase() || + e.name === "DOMException")) + delete code.name; + + if ("name" in code) { + assert("name" in e && e.name === code.name, + "assert_throws", description, + "${func} threw ${actual} (${actual_name}), "+ + "expected ${expected} (${expected_name})", + {func: func, actual: e, actual_name: e.name, + expected: code, + expected_name: code.name}); + } + if ("code" in code) { + assert("code" in e && e.code === code.code, + "assert_throws", description, + "${func} threw ${actual} (${actual_code}), "+ + "expected ${expected} (${expected_code})", + {func: func, actual: e, actual_code: e.code, + expected: code, + expected_code: code.code}); + } + if ("message" in code) { + if (Object.hasOwnProperty.call(e, "message")) { + assert(e.message === code.message, + "assert_throws", description, + "${func} threw ${actual} (${actual_message}), "+ + "expected ${expected} (${expected_message})", + {func: func, actual: e, actual_message: e.message, + expected: code, expected_message: code.message}); + } else { + // Intentional use of loose equality + assert(e == code.message, + "assert_throws", description, + "${func} threw ${actual}, expected ${expected})", + {func: func, actual: e, expected: code.message}); + } + } + } +} +expose(assert_throws, 'assert_throws'); + +/** Assert that control flow cannot reach the point where this + assertion appears. */ +function assert_unreached(description) { + assert(false, "assert_unreached", description, + "reached unreachable code"); +} +expose(assert_unreached, 'assert_unreached'); + +/** Test object. + * These must be created by calling test() or async_test(), but + * many of their methods are part of the public API. + */ + +function Test(name, properties) { + this.name = name; + this.phase = Test.phases.INITIAL; + this.in_done = false; + this.status = Test.NOTRUN; + this.timeout_id = null; + this.message = null; + this.steps = []; + this.cleanup_callbacks = []; + + if (!properties) { + properties = {}; + } + this.properties = properties; + this.timeout_length = properties.timeout ? properties.timeout + : tests.test_timeout_length; + this.should_run = !properties.skip; + tests.push(this); + this.number = tests.tests.length; + + if (!this.should_run) { + // Fake initial step that _does_ run, but short-circuits the test. + // All other steps will be marked not to be run via the defaults + // in step(). The step function does not call done() because that + // would record a success. We can't do this ourselves because the + // plan line has not been emitted yet. + var stepdata = this.step(function () { + this.phase = Test.phases.COMPLETE; + tests.result(this); + }); + stepdata.should_run = true; + stepdata.auto_run = true; + } +} + +Test.phases = { + INITIAL: 0, + STARTED: 1, + HAS_RESULT: 2, + COMPLETE: 3 +}; +Test.statuses = { + NOTRUN: -1, + PASS: 0, + FAIL: 1, + XFAIL: 4, + XPASS: 5 +}; +Test.prototype.phases = Test.phases; +Test.prototype.statuses = Test.phases; + +(function() { + var x; + var o = Test.statuses; + for (x in o) { + if (o.hasOwnProperty(x)) { + Test[x] = Test.statuses[x]; + Test.prototype[x] = Test.statuses[x]; + } + } +})(); + +/** Queue one step of a test. |func| will eventually be called, with + |this| set to |this_obj|, or to the Test object if |this_obj| is + absent. Any further arguments will be passed down to |func|. It + should carry out some tests using assert_* and eventually return. + |func| will _not_ be called if a previous step of the test has + already failed. + + Returns an object which can be passed to this.perform_step() to + cause |func| actually to be called -- but you should not do this + yourself unless absolutely unavoidable. + */ +Test.prototype.step = function step(func, this_obj) { + if (this_obj == null) { + this_obj = this; + } + func = func.bind(this_obj, ...Array.prototype.slice.call(arguments, 2)); + + var stepdata = { + func: func, + should_run: this.should_run, + auto_run: this.should_run, + has_run: false + }; + + this.steps.push(stepdata); + return stepdata; +}; + +/** Internal: perform one step of a test. + */ +Test.prototype.perform_step = function perform_step(stepdata) { + var message; + + if (this.phase > this.phases.STARTED || + tests.phase > tests.phases.HAVE_RESULTS) { + return undefined; + } + + this.phase = this.phases.STARTED; + tests.started = true; + stepdata.has_run = true; + + // Arm the local timeout if it hasn't happened already. + if (this.timeout_id === null && this.timeout_length !== null) { + this.timeout_id = setTimeout(this.force_timeout.bind(this), + this.timeout_length); + } + + var rv = undefined; + try { + rv = stepdata.func(); + } catch (e) { + this.fail(format_exception(e)); + } + return rv; +}; + +/** Mark this test as failed. */ +Test.prototype.fail = function fail(message) { + if (this.phase < this.phases.HAS_RESULT) { + this.message = message; + this.status = this.FAIL; + this.phase = this.phases.HAS_RESULT; + if (!this.in_done) { + this.done(); + } + } else { + tests.output.error(message); + } +}; + +/** Mark this test as completed. */ +Test.prototype.done = function done() { + var i; + + this.in_done = true; + + if (this.timeout_id !== null) { + clearTimeout(this.timeout_id); + this.timeout_id = null; + } + + if (this.phase == this.phases.COMPLETE) { + return; + } + + // Cleanups run in reverse order (most recently added first). + for (i = this.cleanup_callbacks.length - 1; i >= 0; i--) { + try { + this.cleanup_callbacks[i].call(this); + } catch (e) { + this.fail("In cleanup: " + format_exception(e)); + } + } + + // If any step of the test was not run (except those that are not + // _supposed_ to run), and no previous error was detected, that is + // an error. + if (this.phase < this.phases.HAS_RESULT) { + for (i = 0; i < this.steps.length; i++) { + if (this.steps[i].should_run && !this.steps[i].has_run) { + this.fail("Step "+i+" was not run"); + } else if (!this.steps[i].should_run && this.steps[i].has_run) { + this.fail("Step "+i+" should not have run"); + } + } + } + + if (this.phase == this.phases.STARTED) { + this.message = null; + this.status = this.PASS; + } + + if (this.properties.expected_fail) { + if (this.status === this.PASS) { + this.status = this.XPASS; + } else if (this.status === this.FAIL) { + this.status = this.XFAIL; + } + } + + this.phase = this.phases.COMPLETE; + + tests.result(this); + +}; + +/** Register |func| as a step function, and return a function that + will run |func|'s step when called. The arguments to |func| are + whatever the arguments to the callback were, and |this| is + |this_obj|, which defaults to the Test object. Useful as an event + handler, for instance. */ +Test.prototype.step_func = function(func, this_obj) { + var test_this = this; + var cb_args = []; + if (arguments.length === 1) { + this_obj = test_this; + } + + // The function returned stashes its arguments in |cb_args|, then + // the registered step function uses them to call |func| with the + // appropriate arguments. We have to do it this way because + // perform_step() doesn't forward its arguments. + var stepdata = this.step(function cb_step () { + return func.apply(this_obj, cb_args); + }); + + stepdata.auto_run = false; + return function() { + cb_args = Array.prototype.slice.call(arguments); + return test_this.perform_step(stepdata); + }; +}; + +/** As |step_func|, but the step calls this.done() after |func| + returns (regardless of what it returns). |func| may be omitted, + in which case the step just calls this.done(). */ +Test.prototype.step_func_done = function(func, this_obj) { + var test_this = this; + var cb_args = []; + + if (arguments.length <= 1) { + this_obj = test_this; + } + if (!func) { + func = function () {}; + } + + // The function returned stashes its arguments in |cb_args|, then + // the registered step function uses them to call |func| with the + // appropriate arguments. We have to do it this way because + // perform_step() doesn't forward its arguments. + var stepdata = this.step(function cb_done_step () { + var rv = func.apply(this_obj, cb_args); + test_this.done(); + return rv; + }); + + stepdata.auto_run = false; + return function() { + cb_args = Array.prototype.slice.call(arguments); + return test_this.perform_step(stepdata); + }; +}; + +/** Returns a function that, if called, will call assert_unreached() + inside a perform_step() invocation. Use to set event handlers for + events that should _not_ happen. */ +Test.prototype.unreached_func = function unreached_func(description) { + var test_this = this; + var stepdata = this.step(function unreached_step () { + assert_unreached(description); + }); + stepdata.should_run = false; + stepdata.auto_run = false; + + return function() { test_this.perform_step(stepdata); }; +}; + +/** Register |callback| to be called once this test is done. */ +Test.prototype.add_cleanup = function add_cleanup(callback) { + this.cleanup_callbacks.push(callback); +}; + +/** Treat this test as having timed out. */ +Test.prototype.force_timeout = function force_timeout() { + this.message = "Test timed out"; + this.status = this.FAIL; + this.phase = this.phases.HAS_RESULT; + this.done(); +}; + + +/* + * Private implementation logic begins at this point. + */ + +/* + * The Tests object is responsible for tracking the complete set of + * tests in this file. + */ + +function Tests(output) { + this.tests = []; + this.num_pending = 0; + + this.all_loaded = false; + this.wait_for_finish = false; + this.allow_uncaught_exception = false; + + this.test_timeout_length = settings.test_timeout; + this.harness_timeout_length = settings.harness_timeout; + this.timeout_id = null; + + this.properties = {}; + this.phase = Test.phases.INITIAL; + this.output = output; + + var this_obj = this; + phantom.onError = function (message, stack) { + if (!tests.allow_uncaught_exception) { + this_obj.output.error(message); + } + if (this_obj.all_done()) { + this_obj.complete(); + } + }; + phantom.page.onConsoleMessage = function (message) { + if (!tests.allow_uncaught_exception) { + this_obj.output.error("stray console message: " + message); + } + }; + this.set_timeout(); +} + +Tests.phases = { + INITIAL: 0, + SETUP: 1, + HAVE_TESTS: 2, + HAVE_RESULTS: 3, + ABANDONED: 4, + COMPLETE: 5 +}; +Tests.prototype.phases = Tests.phases; + +Tests.prototype.setup = function setup(func, properties) { + if (this.phase >= this.phases.HAVE_RESULTS) { + return; + } + + if (this.phase < this.phases.SETUP) { + this.phase = this.phases.SETUP; + } + + this.properties = properties; + + for (var p in properties) { + if (properties.hasOwnProperty(p)) { + var value = properties[p]; + if (p == "allow_uncaught_exception") { + this.allow_uncaught_exception = value; + } else if (p == "explicit_done" && value) { + this.wait_for_finish = true; + } else if (p == "timeout" && value) { + this.harness_timeout_length = value; + } else if (p == "test_timeout") { + this.test_timeout_length = value; + } + } + } + this.set_timeout(); + + if (func) { + try { + func(); + } catch (e) { + this.output.error(e); + this.phase = this.phases.ABANDONED; + } + } +}; + +Tests.prototype.set_timeout = function set_timeout() { + var this_obj = this; + clearTimeout(this.timeout_id); + if (this.harness_timeout_length !== null) { + this.timeout_id = setTimeout(function () { this_obj.timeout(); }, + this.harness_timeout_length); + } +}; + +Tests.prototype.timeout = function timeout() { + this.output.error("Global timeout expired"); + for (var i = 0; i < tests.tests.length; i++) { + var t = tests.tests[i]; + if (t.phase < Test.phases.HAS_RESULT) { + t.force_timeout(); + } + } + this.complete(); +}; + +Tests.prototype.end_wait = function end_wait() { + this.wait_for_finish = false; + if (this.all_done()) { + this.complete(); + } +}; + +Tests.prototype.push = function push(test) +{ + if (this.phase < this.phases.HAVE_TESTS) { + this.phase = this.phases.HAVE_TESTS; + } + this.num_pending++; + this.tests.push(test); +}; + +Tests.prototype.all_done = function all_done() { + return (this.tests.length > 0 && + this.all_loaded && + this.num_pending === 0 && + !this.wait_for_finish); +}; + +Tests.prototype.result = function result(test) { + if (this.phase < this.phases.HAVE_RESULTS) { + this.phase = this.phases.HAVE_RESULTS; + } + this.num_pending--; + this.output.result(test); + if (this.all_done()) { + this.complete(); + } else { + setTimeout(this.run_tests.bind(this), 0); + } +}; + +Tests.prototype.run_tests = function run_tests() { + if (this.phase >= this.phases.COMPLETE) { + return; + } + if (this.all_done() || this.phase >= this.phases.ABANDONED) { + this.complete(); + return; + } + for (var i = 0; i < this.tests.length; i++) { + var t = this.tests[i]; + if (t.phase < t.phases.STARTED && t.steps.length > 0) { + for (var j = 0; j < t.steps.length; j++) { + if (t.steps[j].auto_run) { + t.perform_step(t.steps[j]); + } + } + // We will come back here via the setTimeout in + // Tests.prototype.result. + break; + } + } +}; + +Tests.prototype.begin = function begin() { + this.all_loaded = true; + this.output.begin(this.tests.length, this.phase); + this.run_tests(); + if (this.all_done()) { + this.complete(); + } +}; + +Tests.prototype.complete = function complete() { + var i, x; + + if (this.phase === this.phases.COMPLETE) { + return; + } + for (i = 0; i < this.tests.length; i++) { + this.tests[i].done(); + } + + this.phase = this.phases.COMPLETE; + this.output.complete(this); +}; + +/* + * The Output object is responsible for reporting the status of each + * test. For PhantomJS, output is much simpler than for the W3C + * harness; we basically just log things to the console as + * appropriate. The output format is meant to be compatible with + * TAP (http://testanything.org/tap-specification.html). + */ + +function Output(fp, verbose) { + this.fp = fp; + this.verbose = verbose; + this.failed = false; +} + +Output.prototype.begin = function begin(n, phase) { + if (phase === Tests.phases.ABANDONED) { + this.fp.write("1..0 # SKIP: setup failed\n"); + } else { + this.fp.write("1.." + n + "\n"); + } +}; + +Output.prototype.diagnostic = function diagnostic(message, is_info) { + var fp = this.fp; + var prefix = "# "; + if (is_info) { + prefix = "## "; + } + message.split("\n").forEach(function (line) { + fp.write(prefix + line + "\n"); + }); +}; + +Output.prototype.error = function error(message) { + this.diagnostic("ERROR: " + message); + this.failed = true; +}; + +Output.prototype.info = function info(message) { + this.diagnostic(message, true); +}; + +Output.prototype.result = function result(test) { + if (test.message) { + this.diagnostic(test.message); + } + var prefix, directive = ""; + switch (test.status) { + case Test.PASS: prefix = "ok "; break; + case Test.FAIL: prefix = "not ok "; break; + case Test.XPASS: prefix = "ok "; directive = " # TODO"; break; + case Test.XFAIL: prefix = "not ok "; directive = " # TODO"; break; + case Test.NOTRUN: prefix = "ok "; directive = " # SKIP"; break; + default: + this.error("Unrecognized test status " + test.status); + prefix = "not ok "; + } + if ((prefix === "not ok " && directive !== " # TODO") || + (prefix === "ok " && directive === " # TODO")) { + this.failed = true; + } + this.fp.write(prefix + test.number + " " + test.name + directive + "\n"); +}; + +Output.prototype.complete = function complete(tests) { + phantom.exit(this.failed ? 1 : 0); +}; + +/* + * Utilities. + */ + +function expose(fn, name) { + window[name] = fn; +} + +/** This function is not part of the public API, but its + *behavior* is part of the contract of several assert_* functions. */ +function same_value(x, y) { + if (x === y) { + // Distinguish +0 and -0 + if (x === 0 && y === 0) { + return 1/x === 1/y; + } + return true; + } else { + // NaN !== _everything_, including another NaN. + // Make it same_value as itself. + if (x !== x) { + return y !== y; + } + // Compare Date and RegExp by value. + if (x instanceof Date) { + return y instanceof Date && x.getTime() === y.getTime(); + } + if (x instanceof RegExp) { + return y instanceof RegExp && x.toString() === y.toString(); + } + return false; + } +} + +/** Similarly, this function's behavior is part of the contract of + assert_deep_equals. (These are the things for which it will just + call same_value rather than doing a recursive property comparison.) */ +function is_primitive_value(val) { + return (val === undefined || val === null || typeof val !== 'object' || + val instanceof Date || val instanceof RegExp); +} + +var names_used = {}; +function test_name(func, name) { + var n, c; + + if (name) + ; + else if (func && func.displayName) + name = func.displayName; + else if (func && func.name) + name = func.name; + else + name = "test"; + + n = name; + c = 0; + while (n in names_used) { + n = name + "." + c.toString(); + c += 1; + } + return n; +} + +function AssertionError(message) { + this.message = message; +} + +AssertionError.prototype.toString = function toString() { + return this.message; +}; + +function assert(expected_true, name, description, error, substitutions) { + if (expected_true !== true) { + throw new AssertionError(make_message( + name, description, error, substitutions)); + } else if (output.verbose >= 4) { + output.info(make_message(name, description, error, substitutions)); + } +} + +function make_message(function_name, description, error, substitutions) { + var p, message; + + for (p in substitutions) { + if (substitutions.hasOwnProperty(p)) { + substitutions[p] = format_value(substitutions[p]); + } + } + + if (description) { + description += ": "; + } else { + description = ""; + } + + return (function_name + ": " + description + + error.replace(/\$\{[^}]+\}/g, function (match) { + return substitutions[match.slice(2,-1)]; + })); +} + +function format_value(val, seen) { + if (seen === undefined) + seen = []; + + var s; + function truncate(s, len) { + if (s.length > len) { + return s.slice(-3) + "..."; + } + return s; + } + + switch (typeof val) { + case "number": + // In JavaScript, -0 === 0 and String(-0) == "0", so we have to + // special-case. + if (val === -0 && 1/val === -Infinity) { + return "-0"; + } + // falls through + case "boolean": + case "undefined": + return String(val); + + case "string": + // Escape ", \, all C0 and C1 control characters, and + // Unicode's LINE SEPARATOR and PARAGRAPH SEPARATOR. + // The latter two are the only characters above U+009F + // that may not appear verbatim in a JS string constant. + val = val.replace(/["\\\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, + function (c) { + switch (c) { + case "\b": return "\\b"; + case "\f": return "\\f"; + case "\n": return "\\n"; + case "\r": return "\\r"; + case "\t": return "\\t"; + case "\v": return "\\v"; + case "\\": return "\\\\"; + case "\"": return "\\\""; + default: + // We know by construction that c is + // a single BMP character. + c = c.charCodeAt(0); + if (c < 0x0080) { + return "\\x" + + ("00" + c.toString(16)).slice(-2); + } else { + return "\\u" + + ("0000" + c.toString(16)).slice(-4); + } + } + }); + return '"' + val + '"'; + + case "object": + if (val === null) { + return "null"; + } + if (seen.indexOf(val) >= 0) { + return ""; + } + seen.push(val); + + if (Array.isArray(val)) { + return "[" + val.map(function (x) { + return format_value(x, seen); + }).join(", ") + "]"; + } + + s = String(val); + if (s != "[object Object]") { + return truncate(s, 60); + } + return "{ " + Object.keys(val).map(function (k) { + return format_value(k, seen) + ": " + format_value(val[k], seen); + }).join(", ") + "}"; + + default: + return typeof val + ' "' + truncate(String(val), 60) + '"'; + } +} + +function format_exception (e) { + var message = (typeof e === "object" && e !== null) ? e.message : e; + if (typeof e.stack != "undefined" && typeof e.message == "string") { + // Prune the stack. This knows the format of WebKit's stack traces. + var stack = e.stack.split("\n"); + var lo, hi; + // We do not need to hear about initial lines naming the + // assertion function. + for (lo = 0; lo < stack.length; lo++) { + if (!/^assert(?:_[a-z0-9_]+)?@.*?testharness\.js:/ + .test(stack[lo])) { + break; + } + } + // We do not need to hear about how we got _to_ the test function. + // The caller of the test function is guaranteed to have "_step" in + // its name. + for (hi = lo; hi < stack.length; hi++) { + if (/^[a-z_]+_step.*?testharness\.js:/.test(stack[hi])) { + break; + } + } + if (lo < stack.length && lo < hi) { + stack = stack.slice(lo, hi); + } + message += "\n"; + message += stack.join("\n"); + } + return message; +} + +function process_command_line(sys) { + function usage(error) { + sys.stderr.write("error: " + error + "\n"); + sys.stderr.write("usage: " + sys.args[0] + + " [--verbose=N] test_script.js ...\n"); + } + var args = { verbose: -1, + test_script: "" }; + + for (var i = 1; i < sys.args.length; i++) { + if (sys.args[i].length === 0) { + usage("empty argument is not meaningful"); + return args; + } + if (sys.args[i][0] !== '-') { + args.test_script = sys.args[i]; + break; + } + var n = "--verbose=".length; + var v = sys.args[i].slice(0, n); + var a = sys.args[i].slice(n); + if (v === "--verbose=" && /^[0-9]+$/.test(a)) { + if (args.verbose === -1) { + args.verbose = parseInt(a, 10); + continue; + } else { + usage("--verbose specified twice"); + return args; + } + } + usage("unrecognized option " + format_value(sys.args[i])); + return args; + } + + if (args.test_script === "") { + usage("no test script specified"); + return args; + } + + if (args.verbose === -1) { + args.verbose = 0; + } + + return args; +} + +/* + * Global state + */ + +var settings = { + harness_timeout: 5000, + test_timeout: null +}; + +var sys = require('system'); +var fs = require('fs'); +var args = process_command_line(sys); + +if (args.test_script === "") { + // process_command_line has already issued an error message. + phantom.exit(2); +} else { + // Reset the library paths for injectJs and require to the + // directory containing the test script, so relative imports work + // as expected. Unfortunately, phantom.libraryPath is not a + // proper search path -- it can only hold one directory at a time. + // require.paths has no such limitation. + var test_script = fs.absolute(args.test_script); + phantom.libraryPath = test_script.slice(0, + test_script.lastIndexOf(fs.separator)); + require.paths.push(phantom.libraryPath); + + // run-tests.py sets these environment variables to the base URLs + // of its HTTP and HTTPS servers. + expose(sys.env['TEST_HTTP_BASE'], 'TEST_HTTP_BASE'); + expose(sys.env['TEST_HTTPS_BASE'], 'TEST_HTTPS_BASE'); + + var output = new Output(sys.stdout, args.verbose); + var tests = new Tests(output); + + // This evaluates the test script synchronously. + // Any errors should be caught by our onError hook. + phantom.injectJs(test_script); + + tests.begin(); +} + +})(); diff --git a/third_party/phantomjs/test/writing-tests.md b/third_party/phantomjs/test/writing-tests.md new file mode 100644 index 00000000000..c04f27beaa0 --- /dev/null +++ b/third_party/phantomjs/test/writing-tests.md @@ -0,0 +1,596 @@ +# How to Write Tests for PhantomJS + +PhantomJS's automated tests are `.js` files located in subdirectories +of this directory. The test runner, [`run-tests.py`](run-tests.py), +executes each as a PhantomJS controller script. (Not all +subdirectories of this directory contain tests; the authoritative list +of test subdirectories is in +[the `TESTS` variable in `run-tests.py`](run-tests.py#L26).) + +In addition to all of the usual PhantomJS API, these scripts have +access to a special testing API, loosely based on +[W3C testharness.js](https://github.com/w3c/testharness.js) and +defined in [`testharness.js`](testharness.js) in this directory. They +also have access to HTTP and HTTPS servers on `localhost`, which serve +the files in the [`www`](www) directory. + +## The Structure of Test Scripts + +Test scripts are divided into _subtests_. There are two kinds of +subtest: synchronous and asynchronous. The only difference is that a +synchronous subtest consists of a single JavaScript function (plus +anything it calls) and is considered to be complete when that function +returns. An asynchronous subtest, however, consists of many +JavaScript functions; these functions are referred to as _steps_. One +step will be invoked to start the subtest, and the others are called +in response to events. Eventually one of the steps will indicate that +the subtest is complete. (The single function used for a synchronous +subtest is also referred to as a step, when the difference doesn't +matter.) + +All of the code in a test script should be part of a subtest, or part +of a setup function (see below). You may define helper functions at +top level, so long as they are only ever _called_ from subtests. You +may also initialize global variables at top level if this +initialization cannot possibly fail, e.g. with constant data or with +`require` calls for core PhantomJS modules. + +The testing API is visible to a test script as a collection of global +functions and variables, documented below. + +A subtest is considered to have failed if any of its steps throws a +JavaScript exception, if an `unreached_func` is called, if the +per-test timeout expires, or if `done` is called before all of its +steps have run. It is considered to succeed if `done` is called +(explicitly or implicitly) after all of its steps have run to +completion. Normally, you should use the assertion functions to detect +failure conditions; these ensure that clear diagnostic information is +printed when a test fails. + +Subtests are executed strictly in the order they appear in the file, +even if some of them are synchronous and some are asynchronous. The +order of steps *within* an asynchronous subtest, however, may be +unpredictable. Also, subtests do not begin to execute until after all +top-level code in the file has been evaluated. + +Some anomalous conditions are reported not as a failure, but as an +"error". For instance, if PhantomJS crashes during a test run, or if +an exception is thrown from outside a step, that is an error, and the +entire test will be abandoned. + +**WARNING:** The harness will become confused if any function passed +as the `func` argument to `test`, `async_test`, `generate_tests`, +`Test.step`, `Test.step_func`, `Test.step_func_done`, or +`Test.add_cleanup` has a name that ends with `_step`. + +### Accessing the HTTP and HTTPS Test Servers + +The global variables `TEST_HTTP_BASE` and `TEST_HTTPS_BASE` are the +base URLs of the test HTTP and HTTPS servers, respectively. Their +values are guaranteed to match the regex `/https?:\/\/localhost:[0-9]+\//`, +but the port number is dynamically assigned for each test run, so you +must not hardwire it. + +### Synchronous Subtests + +There are two functions for defining synchronous subtests. + +* `test(func, name, properties)` + + Run `func` as a subtest; the subtest is considered to be complete as + soon as it returns. `name` is an optional descriptive name for the + subtest. `func` will be called with no arguments, and `this` set to + a `Test` object (see below). `properties` is an optional object + containing properties to apply to the test. Currently there are + three meaningful properties; any other keys in the `properties` + object are ignored: + + * `timeout` - Maximum amount of time the subtest is allowed to run, in + milliseconds. If the timeout expires, the subtest will be + considered to have failed. + + * `expected_fail`: If truthy, this subtest is expected to fail. It will + still be run, but a failure will be considered "normal" and the + overall test will be reported as successful. Conversely, if the + subtest *succeeds* that is considered "abnormal" and the overall + test will be reported as failing. + + * `skip`: If truthy, this subtest will not be run at all, will be + reported as "skipped" rather than "succeeded" or "failed", and + will not affect the overall outcome of the test. Use `skip` only + when `expected_fail` will not do—for instance, when a test + provokes a PhantomJS crash (there currently being no way to label + a crash as "expected"). + + `test` returns the same `Test` object that is available as `this` + within `func`. + +* `generate_tests(func, args, properties)` + + Define a group of synchronous subtests, each of which will call + `func`, but with different arguments. This is easiest to explain by + example: + + generate_tests(assert_equals, [ + ["Sum one and one", 1 + 1, 2], + ["Sum one and zero", 1 + 0, 1] + ]); + + ... is equivalent to ... + + test(function() {assert_equals(1+1, 2)}, "Sum one and one"); + test(function() {assert_equals(1+0, 1)}, "Sum one and zero"); + + Of course `func` may be as complicated as you like, and there is no + limit either to the number of arguments passed to each subtest, or + to the number of subtests. + + The `properties` argument may be a single properties object, which + will be applied uniformly to all the subtests, or an array of the + same length as `args`, containing appropriate property objects for + each subtest. + + `generate_tests` returns no value. + +### Asynchronous Subtests + +An asynchronous subtest consists of one or more _step_ functions, and +unlike a synchronous subtest, it is not considered to be complete until +the `done` method is called on its `Test` object. When this happens, +if any of the step functions have not been executed, the subtest is a +failure. + +Asynchronous subtests are defined with the `async_test` function, which +is almost the same as `test`: + +* `async_test(func, name, properties)` + + Define an asynchronous subtest. The arguments and their + interpretation are the same as for `test`, except that `func` is + optional, and the subtest is *not* considered to be complete after + `func` returns; `func` (if present) is only the first step of the + subtest. Additional steps may be defined, either within `func` or + outside the call to `async_test`, by use of methods on the `Test` + object that is returned (and available as `this` within `func`). + + Normally, an asynchronous subtest's first step will set up whatever + is being tested, and define the remainder of the steps, which will + be run in response to events. + +### Test Object Methods + +These methods are provided by the `Test` object which is returned by +`test` and `async_test`, and available as `this` within step +functions. + +* `Test.step(func[, this_obj, ...])` + + Queue one step of a subtest. `func` will eventually be called, with + `this` set to `this_obj`, or (if `this_obj` is null or absent) to + the `Test` object. Any further arguments will be passed down to + `func`. `func` will _not_ be called if a previous step has failed. + + Do not use this function to define steps that should run in response + to event callbacks; only steps that should be automatically run by + the test harness. + + The object returned by this function is private. Please let us know + if you think you need to use it. + +* `Test.done()` + + Indicate that this subtest is complete. One, and only one, step of + an asynchronous subtest must call this function, or the subtest will + never complete (and eventually it will time out). + + If an asynchronous subtest has several steps, but not all of them + have run when `done` is called, the subtest is considered to have + failed. + +* `Test.step_func(func[, this_obj])` + + Register `func` as a step that will *not* be run automatically by + the test harness. Instead, the function *returned* by this function + (the "callback") will run `func`'s step when it is called. + (`func`'s step must still somehow get run before `done` is called, + or the subtest will be considered to have failed.) + + `this_obj` will be supplied as `this` to `func`; if omitted, it + defaults to the `Test` object. Further arguments are ignored. + However, `func` will receive all of the arguments passed to the + callback, and the callback will return whatever `func` returns. + + This is the normal way to register a step that should run in + response to an event. For instance, here is a minimal test of a + page load: + + async_test(function () { + var p = require('webpage').create(); + p.open(TEST_HTTP_BASE + 'hello.html', + this.step_func(function (status) { + assert_equals(status, 'success'); + this.done(); + })); + }); + + This also serves to illustrate why asynchronous subtests may be + necessary: this subtest is not complete when its first step returns, + only when the `onLoadFinished` event fires. + +* `Test.step_func_done([func[, this_obj]])` + + Same as `Test.step_func`, but the callback additionally calls `done` + after `func` returns. `func` may be omitted, in which case the + callback just calls `done`. + + The example above can be shortened to + + async_test(function () { + var p = require('webpage').create(); + p.open(TEST_HTTP_BASE + 'hello.html', + this.step_func_done(function (status) { + assert_equals(status, 'success'); + })); + }); + +* `Test.unreached_func([description])` + + Returns a function that, if called, will call + `assert_unreached(description)` inside a step. Use this to set + event handlers for events that should _not_ happen. You need to use + this method instead of `step_func(function () { assert_unreached(); })` + so the step is properly marked as expected _not_ to run; otherwise + the test will fail whether or not the event happens. + + A slightly more thorough test of a page load might read + + async_test(function () { + var p = require('webpage').create(); + p.onResourceError = this.unreached_func("onResourceError"); + p.open(TEST_HTTP_BASE + 'hello.html', + this.step_func_done(function (status) { + assert_equals(status, 'success'); + })); + }); + +* `Test.add_cleanup(func)` + + Register `func` to be called (with no arguments, and `this` set to + the `Test` object) when `done` is called, whether or not the subtest + has failed. Use this to deallocate persistent resources or undo + changes to global state. For example, a subtest that uses a scratch + file might read + + test(function () { + var fs = require('fs'); + var f = fs.open('scratch_file', 'w'); + this.add_cleanup(function () { + f.close(); + fs.remove('scratch_file'); + }); + + // ... more test logic here ... + }); + + If the step function had simply deleted the file at its end, the + file would only get deleted when the test succeeds. This example + could be rewritten using `try ... finally ...`, but that will not + work for asynchronous tests. + +* `Test.fail(message)` + + Explicitly mark this subtest has having failed, with failure message + `message`. You should not normally need to call this function yourself. + +* `Test.force_timeout()` + + Explicitly mark this subtest as having failed because its timeout has + expired. You should not normally need to call this function yourself. + +### Test Script-Wide Setup + +All of the subtests of a test script are normally run, even if one of +them fails. Complex tests may involve complex initialization actions +that may fail, in which case the entire test script should be aborted. +There is also a small amount of harness-wide configuration that is +possible. Both these tasks are handled by the global function +`setup`. + +* `setup([func], [properties])` + + One may specify either `func` or `properties` or both, but if both + are specified, `func` must be first. + + `func` is called immediately, with no arguments. If it throws an + exception, the entire test script is considered to have failed and + none of the subtests are run. + + `properties` is an object containing one or more of the following + keys: + + * `explicit_done`: Wait for the global function `done` (not to be + confused with `Test.done` to be called, before declaring the test + script complete. + + * `allow_uncaught_exception`: Don't treat an uncaught exception from + non-test code as an error. (Exceptions thrown out of test steps + are still errors.) + + * `timeout`: Overall timeout for the test script, in milliseconds. + The default is five seconds. Note that `run-tests.py` imposes a + "backstop" timeout itself; if you raise this timeout you may also + need to raise that one. + + * `test_timeout`: Default timeout for individual subtests. This may + be overridden by the `timeout` property on a specific subtest. + The default is not to have a timeout for individual subtests. + + +### Assertions + +Whenever possible, use these functions to detect failure conditions. +All of them either throw a JavaScript exception (when the test fails) +or return no value (when the test succeeds). All take one or more +values to be tested, and an optional _description_. If present, the +description should be a string to be printed to clarify why the test +has failed. (The assertions all go to some length to print out values +that were not as expected in a clear format, so descriptions will +often not be necessary.) + +* `assert_is_true(value[, description])` + + `value` must be strictly equal to `true`. + +* `assert_is_false(value[, description])` + + `value` must be strictly equal to `false`. + +* `assert_equals(actual, expected[, description])` + + `actual` and `expected` must be shallowly, strictly equal. The + criterion used is `===` with the following exceptions: + + * If `x === y`, but one of them is `+0` and the other is `-0`, they + are *not* considered equal. + + * If `x !== y`, but one of the following cases holds, they *are* + considered equal: + * both are `NaN` + * both are `Date` objects and `x.getTime() === y.getTime()` + * both are `RegExp` objects and `x.toString() === y.toString()` + +* `assert_not_equals(actual, expected[, description])` + + `actual` and `expected` must *not* be shallowly, strictly equal, + using the same criterion as `assert_equals`. + +* `assert_deep_equals(actual, expected[, description])` + + If `actual` and `expected` are not objects, or if they are + `Date` or `RegExp` objects, this is the same as `assert_equals`. + + Objects that are not `Date` or `RegExp` must have the same set of + own-properties (including non-enumerable own-properties), and each + pair of values for with each own-property must be `deep_equals`, + recursively. Prototype chains are ignored. Back-references are + detected and ignored; they will not cause an infinite recursion. + +* `assert_approx_equals(actual, expected, epsilon[, description])` + + The absolute value of the difference between `actual` and `expected` + must be no greater than `epsilon`. All three arguments must be + primitive numbers. + +* `assert_less_than(actual, expected[, description])` +* `assert_less_than_equal(actual, expected[, description])` +* `assert_greater_than(actual, expected[, description])` +* `assert_greater_than_equal(actual, expected[, description])` + + `actual` and `expected` must be primitive numbers, and `actual` must + be, respectively: less than, less than or equal to, greater than, + greater than or equal to `expected`. + +* `assert_in_array(value, array[, description])` + + `array` must contain `value` according to `Array.indexOf`. + +* `assert_regexp_match(string, regexp[, description])` + + The regular expression `regexp` must match the string `string`, + according to `RegExp.test()`. + +* `assert_regexp_not_match(string, regexp[, description])` + + The regular expression `regexp` must *not* match the string `string`, + according to `RegExp.test()`. + +* `assert_type_of(object, type[, description])` + + `typeof object` must be strictly equal to `type`. + +* `assert_instance_of(object, type[, description])` + + `object instanceof type` must be true. + +* `assert_class_string(object, expected[, description])` + + `object` must have the class string `expected`. The class string is + the second word in the string returned by `Object.prototype.toString`: + for instance, `({}).toString.call([])` returns `[object Array]`, so + `[]`'s class string is `Array`. + +* `assert_own_property(object, name[, description])` + + `object` must have an own-property named `name`. + +* `assert_inherits(object, name[, description])` + + `object` must inherit a property named `name`; that is, + `name in object` must be true but `object.hasOwnProperty(name)` + must be false. + +* `assert_no_property(object, name[, description])` + + `object` must neither have nor inherit a property named `name`. + +* `assert_readonly(object, name[, description])` + + `object` must have an own-property named `name` which is marked + read-only (according to `Object.getOwnPropertyDescriptor`). + +* `assert_throws(code, func[, description])` + + `func` must throw an exception described by `code`. `func` is + called with no arguments and no `this` (you can supply arguments + using `bind`). `code` can take one of two forms. If it is a + string, the thrown exception must either stringify to that string, + or it must be a DOMException whose `name` property is that string. + Otherwise, `code` must be an object with one or more of the + properties `code`, `name`, and `message`; whichever properties are + present must be `===` to the corresponding properties of the + exception. As a special case, if `message` is present in the + `code` object but *not* on the exception object, and the exception + stringifies to the same string as `message`, that's also considered + valid. + + `assert_throws` cannot be used to catch the exception thrown by any + of the other `assert_*` functions when they fail. (You might be + looking for the `expected_fail` property on a subtest.) + +* `assert_unreached([description])` + + Control flow must not reach the point where this assertion appears. + (In other words, this assertion fails unconditionally.) + +## Test Annotations + +Some tests need to be run in a special way. You can indicate this to +the test runner with _annotations_. Annotations are lines in the test +script that begin with the three characters '`//!`'. They must be all +together at the very top of the script; `run-tests.py` stops parsing +at the first line that does _not_ begin with the annotation marker. + +Annotation lines are split into _tokens_ in a shell-like fashion, +which means they are normally separated by whitespace, but you can use +backslashes or quotes to put whitespace inside a token. Backslashes +are significant inside double quotes, but not inside single quotes. +There can be any number of tokens on a line. Everything following an +unquoted, un-backslashed `#` is discarded. (The exact algorithm is +[`shlex.split`](https://docs.python.org/2/library/shlex.html), in +`comments=True`, `posix=True` mode.) + +These are the recognized tokens: + +* `no-harness`: Run this test script directly; the testing API + described above will not be available. This is necessary to + test PhantomJS features that `testharness.js` reserves for its + own use, such as `phantom.onError` and `phantom.exit`. No-harness + tests will usually also be output-expectations tests (see below) + but this is not required. + +* `snakeoil`: Instruct PhantomJS to accept the self-signed + certificate presented by the HTTPS test server. + +* `timeout:` The next token on the line must be a positive + floating-point number. `run-tests.py` will kill the PhantomJS + process, and consider the test to have failed, if it runs for longer + than that many seconds. The default timeout is seven seconds. + + This timeout is separate from the per-subtest and global timeouts + enforced by the testing API. It is intended as a backstop against + bugs which cause PhantomJS to stop executing the controller script. + (In no-harness mode, it's the only timeout, unless you implement + your own.) + +* `phantomjs:` All subsequent tokens on the line will be passed as + command-line arguments to PhantomJS, before the controller script. + Note that `run-tests.py` sets several PhantomJS command line options + itself; you must take care not to do something contradictory. + +* `script:` All subsequent tokens on the line will be passed as + command-line arguments to the *controller script*; that is, they + will be available in + [`system.args`](http://phantomjs.org/api/system/property/args.html). + Note that your controller script will only be `system.args[0]` if + you are using no-harness mode, and that `run-tests.py` may pass + additional script arguments of its own. + +* `stdin:` All subsequent tokens on the line will be concatenated + (separated by a single space) and fed to PhantomJS's standard input, + with a trailing newline. If this token is used more than once, + that produces several lines of input. If this token is not used at + all, standard input will read as empty. + +* `unsupported:` The whole file will be skipped. + This directive should be used to notify that the functionality is not yet + implemented by Puppeteer. Tests could be run ignoring this directive + with the `--run-unsupported` flag. + +## Output-Expectations Tests + +Normally, `run-tests.py` expects each test to produce parseable output +in the [TAP](http://testanything.org/tap-specification.html) format. +This is too inflexible for testing things like `system.stdout.write`, +so there is also a mode in which you specify exactly what output the +test should produce, with additional annotations. Output-expectations +tests are not *required* to be no-harness tests, but the only reason +to use this mode for harness tests would be to test the harness +itself, and it's not sophisticated enough for that. + +Using any of the following annotations makes a test an +output-expectations test: + +* `expect-exit:` The next token on the line must be an integer. If it + is nonnegative, the PhantomJS process is expected to exit with that + exit code. If it is negative, the process is expected to be + terminated by the signal whose number is the absolute value of the + token. (For instance, `expect-exit: -15` for a test that is + expected to hit the backstop timeout.) + +* `expect-stdout:` All subsequent tokens on the line are concatenated, + with spaces in between, and a newline is appeneded. The PhantomJS + process is expected to emit that text, verbatim, on its standard + output. If used more than once, that produces multiple lines of + expected output. + +* `expect-stderr:` Same as `expect-stdout`, but the output is expected + to appear on standard error. + +* `expect-exit-fails`, `expect-stdout-fails`, `expect-stderr-fails`: + The corresponding test (of the exit code, stdout, or stderr) is + expected to fail. + +If some but not all of these annotations are used in a test, the +omitted ones default to exit code 0 (success) and no output on their +respective streams. + +## Test Server Modules + +The HTTP and HTTPS servers exposed to the test suite serve the static +files in the `www` subdirectory with URLs corresponding to their paths +relative to that directory. If you need more complicated server +behavior than that, you can write custom Python code that executes +when the server receives a request. Any `.py` file below the `www` +directory will be invoked to provide the response for that path +*without* the `.py` suffix. (For instance, `www/echo.py` provides +responses for `TEST_HTTP_BASE + 'echo'`.) Such files must define a +top-level function named `handle_request`. This function receives a +single argument, which is an instance of a subclass of +[`BaseHTTPServer.BaseHTTPRequestHandler`](https://docs.python.org/2/library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler). +The request headers and body (if any) may be retrieved from this +object. The function must use the `send_response`, `send_header`, and +`end_headers` methods of this object to generate HTTP response +headers, and then return a *file-like object* (**not** a string) +containing the response body. The function is responsible for +generating appropriate `Content-Type` and `Content-Length` headers; +the server framework does not do this automatically. + +Test server modules cannot directly cause a test to fail; the server +does not know which test is responsible for any given request. If +there is something wrong with a request, generate an HTTP error +response; then write your test to fail if it receives an error +response. + +Python exceptions thrown by test server modules are treated as +failures *of the testsuite*, but they are all attributed to a virtual +"HTTP server errors" test. diff --git a/third_party/phantomjs/test/www/__init__.py b/third_party/phantomjs/test/www/__init__.py new file mode 100644 index 00000000000..b2858867a75 --- /dev/null +++ b/third_party/phantomjs/test/www/__init__.py @@ -0,0 +1,2 @@ +# This file makes test/www/ into a "package" so that +# importing Python response hooks works correctly. diff --git a/third_party/phantomjs/test/www/delay.py b/third_party/phantomjs/test/www/delay.py new file mode 100644 index 00000000000..9653499eb8b --- /dev/null +++ b/third_party/phantomjs/test/www/delay.py @@ -0,0 +1,15 @@ +import cStringIO as StringIO +import urlparse +import time + +def handle_request(req): + url = urlparse.urlparse(req.path) + delay = float(int(url.query)) + time.sleep(delay / 1000) # argument is in milliseconds + + body = "OK ({}ms delayed)\n".format(delay) + req.send_response(200) + req.send_header('Content-Type', 'text/plain') + req.send_header('Content-Length', str(len(body))) + req.end_headers() + return StringIO.StringIO(body) diff --git a/third_party/phantomjs/test/www/echo.py b/third_party/phantomjs/test/www/echo.py new file mode 100644 index 00000000000..8a7ba2d9693 --- /dev/null +++ b/third_party/phantomjs/test/www/echo.py @@ -0,0 +1,29 @@ +import json +import urlparse +import cStringIO as StringIO + +def handle_request(req): + url = urlparse.urlparse(req.path) + headers = {} + for name, value in req.headers.items(): + headers[name] = value.rstrip() + + d = dict( + command = req.command, + version = req.protocol_version, + origin = req.client_address, + url = req.path, + path = url.path, + params = url.params, + query = url.query, + fragment = url.fragment, + headers = headers, + postdata = req.postdata + ) + body = json.dumps(d, indent=2) + '\n' + + req.send_response(200) + req.send_header('Content-Type', 'application/json') + req.send_header('Content-Length', str(len(body))) + req.end_headers() + return StringIO.StringIO(body) diff --git a/third_party/phantomjs/test/www/frameset/frame1-1.html b/third_party/phantomjs/test/www/frameset/frame1-1.html new file mode 100644 index 00000000000..c80ec458368 --- /dev/null +++ b/third_party/phantomjs/test/www/frameset/frame1-1.html @@ -0,0 +1,8 @@ + + + frame1-1 + + +

index > frame1 > frame1-1

+ + diff --git a/third_party/phantomjs/test/www/frameset/frame1-2.html b/third_party/phantomjs/test/www/frameset/frame1-2.html new file mode 100644 index 00000000000..b0c38d2f4a3 --- /dev/null +++ b/third_party/phantomjs/test/www/frameset/frame1-2.html @@ -0,0 +1,8 @@ + + + frame1-2 + + +

index > frame1 > frame1-2

+ + diff --git a/third_party/phantomjs/test/www/frameset/frame1.html b/third_party/phantomjs/test/www/frameset/frame1.html new file mode 100644 index 00000000000..b23c274193c --- /dev/null +++ b/third_party/phantomjs/test/www/frameset/frame1.html @@ -0,0 +1,9 @@ + + + frame1 + + + + + + diff --git a/third_party/phantomjs/test/www/frameset/frame2-1.html b/third_party/phantomjs/test/www/frameset/frame2-1.html new file mode 100644 index 00000000000..2f7c121a9ff --- /dev/null +++ b/third_party/phantomjs/test/www/frameset/frame2-1.html @@ -0,0 +1,8 @@ + + + frame2-1 + + +

index > frame2 > frame2-1

+ + diff --git a/third_party/phantomjs/test/www/frameset/frame2-2.html b/third_party/phantomjs/test/www/frameset/frame2-2.html new file mode 100644 index 00000000000..99f603d78f6 --- /dev/null +++ b/third_party/phantomjs/test/www/frameset/frame2-2.html @@ -0,0 +1,8 @@ + + + frame2-2 + + +

index > frame2 > frame2-2

+ + diff --git a/third_party/phantomjs/test/www/frameset/frame2-3.html b/third_party/phantomjs/test/www/frameset/frame2-3.html new file mode 100644 index 00000000000..b6f18089dec --- /dev/null +++ b/third_party/phantomjs/test/www/frameset/frame2-3.html @@ -0,0 +1,8 @@ + + + frame2-3 + + +

index > frame2 > frame2-3

+ + diff --git a/third_party/phantomjs/test/www/frameset/frame2.html b/third_party/phantomjs/test/www/frameset/frame2.html new file mode 100644 index 00000000000..d3484bd15cc --- /dev/null +++ b/third_party/phantomjs/test/www/frameset/frame2.html @@ -0,0 +1,10 @@ + + + frame2 + + + + + + + diff --git a/third_party/phantomjs/test/www/frameset/index.html b/third_party/phantomjs/test/www/frameset/index.html new file mode 100644 index 00000000000..dbe01bb5d02 --- /dev/null +++ b/third_party/phantomjs/test/www/frameset/index.html @@ -0,0 +1,9 @@ + + + index + + + + + + diff --git a/third_party/phantomjs/test/www/hello.html b/third_party/phantomjs/test/www/hello.html new file mode 100644 index 00000000000..ee4bc5924a5 --- /dev/null +++ b/third_party/phantomjs/test/www/hello.html @@ -0,0 +1,8 @@ + + + Hello + + +

Hello, world!

+ + diff --git a/third_party/phantomjs/test/www/iframe.html b/third_party/phantomjs/test/www/iframe.html new file mode 100644 index 00000000000..ce62c6dc654 --- /dev/null +++ b/third_party/phantomjs/test/www/iframe.html @@ -0,0 +1,17 @@ + + + + + + + + + + diff --git a/third_party/phantomjs/test/www/includejs.js b/third_party/phantomjs/test/www/includejs.js new file mode 100644 index 00000000000..5c0e4bd619a --- /dev/null +++ b/third_party/phantomjs/test/www/includejs.js @@ -0,0 +1,3 @@ +function getTitle () { + return document.title; +} diff --git a/third_party/phantomjs/test/www/includejs1.html b/third_party/phantomjs/test/www/includejs1.html new file mode 100644 index 00000000000..4be4b1fb603 --- /dev/null +++ b/third_party/phantomjs/test/www/includejs1.html @@ -0,0 +1,2 @@ + +i am includejs one diff --git a/third_party/phantomjs/test/www/includejs2.html b/third_party/phantomjs/test/www/includejs2.html new file mode 100644 index 00000000000..89aeab2a62a --- /dev/null +++ b/third_party/phantomjs/test/www/includejs2.html @@ -0,0 +1,2 @@ + +i am includejs two diff --git a/third_party/phantomjs/test/www/js-infinite-loop.html b/third_party/phantomjs/test/www/js-infinite-loop.html new file mode 100644 index 00000000000..6dcb77525c0 --- /dev/null +++ b/third_party/phantomjs/test/www/js-infinite-loop.html @@ -0,0 +1,12 @@ + + + + + + + + \ No newline at end of file diff --git a/third_party/phantomjs/test/www/logo.html b/third_party/phantomjs/test/www/logo.html new file mode 100644 index 00000000000..1323ffdf5a4 --- /dev/null +++ b/third_party/phantomjs/test/www/logo.html @@ -0,0 +1,8 @@ + + + Show logo + + + + + diff --git a/third_party/phantomjs/test/www/logo.png b/third_party/phantomjs/test/www/logo.png new file mode 100644 index 00000000000..7b44e54189f Binary files /dev/null and b/third_party/phantomjs/test/www/logo.png differ diff --git a/third_party/phantomjs/test/www/missing-img.html b/third_party/phantomjs/test/www/missing-img.html new file mode 100644 index 00000000000..cc142eca16b --- /dev/null +++ b/third_party/phantomjs/test/www/missing-img.html @@ -0,0 +1,8 @@ + + + Missing image + + + + + diff --git a/third_party/phantomjs/test/www/navigation/dest.html b/third_party/phantomjs/test/www/navigation/dest.html new file mode 100644 index 00000000000..e336f9cbb3e --- /dev/null +++ b/third_party/phantomjs/test/www/navigation/dest.html @@ -0,0 +1,2 @@ + +DEST diff --git a/third_party/phantomjs/test/www/navigation/index.html b/third_party/phantomjs/test/www/navigation/index.html new file mode 100644 index 00000000000..9d3b35f2d1d --- /dev/null +++ b/third_party/phantomjs/test/www/navigation/index.html @@ -0,0 +1,2 @@ + +INDEX diff --git a/third_party/phantomjs/test/www/phantomjs.png b/third_party/phantomjs/test/www/phantomjs.png new file mode 100644 index 00000000000..381a3789b75 Binary files /dev/null and b/third_party/phantomjs/test/www/phantomjs.png differ diff --git a/third_party/phantomjs/test/www/regression/pjs-10690/Windsong.ttf b/third_party/phantomjs/test/www/regression/pjs-10690/Windsong.ttf new file mode 100644 index 00000000000..22c8e697c7b Binary files /dev/null and b/third_party/phantomjs/test/www/regression/pjs-10690/Windsong.ttf differ diff --git a/third_party/phantomjs/test/www/regression/pjs-10690/font.css b/third_party/phantomjs/test/www/regression/pjs-10690/font.css new file mode 100644 index 00000000000..959d531cb35 --- /dev/null +++ b/third_party/phantomjs/test/www/regression/pjs-10690/font.css @@ -0,0 +1,7 @@ +@font-face { + font-family: 'WindsongRegular'; + src: url("Windsong.ttf") format("truetype"); +} +h1 { + font: 90px/98px "WindsongRegular", Arial, sans-serif; +} diff --git a/third_party/phantomjs/test/www/regression/pjs-10690/index.html b/third_party/phantomjs/test/www/regression/pjs-10690/index.html new file mode 100644 index 00000000000..6d4d3cfb12d --- /dev/null +++ b/third_party/phantomjs/test/www/regression/pjs-10690/index.html @@ -0,0 +1,9 @@ + + + + + + +

Hello World

+ + diff --git a/third_party/phantomjs/test/www/regression/pjs-10690/jquery.js b/third_party/phantomjs/test/www/regression/pjs-10690/jquery.js new file mode 100644 index 00000000000..f66a95ce6cb --- /dev/null +++ b/third_party/phantomjs/test/www/regression/pjs-10690/jquery.js @@ -0,0 +1,9441 @@ +/*! + * jQuery JavaScript Library v1.8.2 + * http://jquery.com/ + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * + * Copyright 2012 jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: Thu Sep 20 2012 21:13:05 GMT-0400 (Eastern Daylight Time) + */ + +(function( window, undefined ) { +var + // A central reference to the root jQuery(document) + rootjQuery, + + // The deferred used on DOM ready + readyList, + + // Use the correct document accordingly with window argument (sandbox) + document = window.document, + location = window.location, + navigator = window.navigator, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // Save a reference to some core methods + core_push = Array.prototype.push, + core_slice = Array.prototype.slice, + core_indexOf = Array.prototype.indexOf, + core_toString = Object.prototype.toString, + core_hasOwn = Object.prototype.hasOwnProperty, + core_trim = String.prototype.trim, + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Used for matching numbers + core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, + + // Used for detecting and trimming whitespace + core_rnotwhite = /\S/, + core_rspace = /\s+/, + + // 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, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, + rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/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(); + }, + + // The ready event handler and self cleanup method + DOMContentLoaded = function() { + if ( document.addEventListener ) { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + } else if ( document.readyState === "complete" ) { + // we're here because readyState === "complete" in oldIE + // which is good enough for us to call the dom ready! + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }, + + // [[Class]] -> type pairs + class2type = {}; + +jQuery.fn = jQuery.prototype = { + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem, ret, doc; + + // Handle $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + 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; + doc = ( context && context.nodeType ? context.ownerDocument || context : document ); + + // scripts is true for back-compat + selector = jQuery.parseHTML( match[1], doc, true ); + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + this.attr.call( selector, context, true ); + } + + return jQuery.merge( this, selector ); + + // 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: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.8.2", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return core_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 + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + + // 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; + + if ( name === "find" ) { + ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; + } else if ( name ) { + ret.selector = this.selector + "." + name + "(" + selector + ")"; + } + + // 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 ); + }, + + ready: function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; + }, + + eq: function( i ) { + i = +i; + return i === -1 ? + this.slice( i ) : + this.slice( i, i + 1 ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + slice: function() { + return this.pushStack( core_slice.apply( this, arguments ), + "slice", core_slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: core_push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // 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 ( length === i ) { + 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({ + noConflict: function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // 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, 1 ); + } + + // 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"); + } + }, + + // 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 ) { + return obj != null && obj == obj.window; + }, + + isNumeric: function( obj ) { + return !isNaN( parseFloat(obj) ) && isFinite( obj ); + }, + + type: function( obj ) { + return obj == null ? + String( obj ) : + class2type[ core_toString.call(obj) ] || "object"; + }, + + isPlainObject: function( obj ) { + // 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 && + !core_hasOwn.call(obj, "constructor") && + !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || core_hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw new Error( msg ); + }, + + // data: string of html + // context (optional): If specified, the fragment will be created in this context, defaults to document + // scripts (optional): If true, will include scripts passed in the html string + parseHTML: function( data, context, scripts ) { + var parsed; + if ( !data || typeof data !== "string" ) { + return null; + } + if ( typeof context === "boolean" ) { + scripts = context; + context = 0; + } + context = context || document; + + // Single tag + if ( (parsed = rsingleTag.exec( data )) ) { + return [ context.createElement( parsed[1] ) ]; + } + + parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); + return jQuery.merge( [], + (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); + }, + + parseJSON: function( data ) { + if ( !data || typeof data !== "string") { + return null; + } + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + // Attempt to parse using the native JSON parser first + if ( window.JSON && window.JSON.parse ) { + return window.JSON.parse( data ); + } + + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test( data.replace( rvalidescape, "@" ) + .replace( rvalidtokens, "]" ) + .replace( rvalidbraces, "")) ) { + + return ( new Function( "return " + data ) )(); + + } + jQuery.error( "Invalid JSON: " + data ); + }, + + // Cross-browser xml parsing + 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; + }, + + noop: function() {}, + + // 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 && core_rnotwhite.test( 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 name, + i = 0, + length = obj.length, + isObj = length === undefined || jQuery.isFunction( obj ); + + if ( args ) { + if ( isObj ) { + for ( name in obj ) { + if ( callback.apply( obj[ name ], args ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.apply( obj[ i++ ], args ) === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isObj ) { + for ( name in obj ) { + if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { + break; + } + } + } + } + + return obj; + }, + + // Use native String.trim function wherever possible + trim: core_trim && !core_trim.call("\uFEFF\xA0") ? + function( text ) { + return text == null ? + "" : + core_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 type, + ret = results || []; + + if ( arr != null ) { + // The window, strings (and functions) also have 'length' + // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 + type = jQuery.type( arr ); + + if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { + core_push.call( ret, arr ); + } else { + jQuery.merge( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + var len; + + if ( arr ) { + if ( core_indexOf ) { + return core_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 l = second.length, + i = first.length, + j = 0; + + if ( typeof l === "number" ) { + for ( ; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var retVal, + ret = [], + i = 0, + length = elems.length; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, key, + ret = [], + i = 0, + length = elems.length, + // jquery objects are treated as arrays + isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( key in elems ) { + value = callback( elems[ key ], key, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return ret.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 tmp, args, proxy; + + 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 = core_slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context, args.concat( core_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; + }, + + // Multifunctional method to get and set values of a collection + // The value/s can optionally be executed if it's a function + access: function( elems, fn, key, value, chainable, emptyGet, pass ) { + var exec, + bulk = key == null, + i = 0, + length = elems.length; + + // Sets many values + if ( key && typeof key === "object" ) { + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); + } + chainable = 1; + + // Sets one value + } else if ( value !== undefined ) { + // Optionally, function values get executed if exec is true + exec = pass === undefined && jQuery.isFunction( value ); + + if ( bulk ) { + // Bulk operations only iterate when executing function values + if ( exec ) { + exec = fn; + fn = function( elem, key, value ) { + return exec.call( jQuery( elem ), value ); + }; + + // Otherwise they run against the entire set + } else { + fn.call( elems, value ); + fn = null; + } + } + + if ( fn ) { + for (; i < length; i++ ) { + fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + } + } + + chainable = 1; + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + length ? fn( elems[0], key ) : emptyGet; + }, + + now: function() { + return ( new Date() ).getTime(); + } +}); + +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, 1 ); + + // Standards-based browsers support DOMContentLoaded + } else if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); + + // If IE event model is used + } else { + // Ensure firing before onload, maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", DOMContentLoaded ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); + + // 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 ); + } + + // and execute any waiting functions + jQuery.ready(); + } + })(); + } + } + } + return readyList.promise( obj ); +}; + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); +// 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.split( core_rspace ), 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 // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // Flag to know if list is currently firing + firing, + // First callback to fire (used internally by add and fireWith) + firingStart, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // 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" && ( !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; + }, + // Control if a given callback is in the list + has: function( fn ) { + return jQuery.inArray( fn, list ) > -1; + }, + // Remove all callbacks from the list + empty: function() { + list = []; + 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 ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( list && ( !fired || stack ) ) { + 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 action = tuple[ 0 ], + fn = fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? + function() { + var returned = fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); + } + } : + newDefer[ action ] + ); + }); + 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 ] = list.fire + deferred[ tuple[0] ] = list.fire; + 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 = core_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 ? core_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(); + } +}); +jQuery.support = (function() { + + var support, + all, + a, + select, + opt, + input, + fragment, + eventName, + i, + isSupported, + clickFn, + div = document.createElement("div"); + + // Preliminary tests + div.setAttribute( "className", "t" ); + div.innerHTML = "
a"; + + all = div.getElementsByTagName("*"); + a = div.getElementsByTagName("a")[ 0 ]; + a.style.cssText = "top:1px;float:left;opacity:.5"; + + // Can't get basic test support + if ( !all || !all.length ) { + return {}; + } + + // First batch of supports tests + select = document.createElement("select"); + opt = select.appendChild( document.createElement("option") ); + input = div.getElementsByTagName("input")[ 0 ]; + + support = { + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: ( div.firstChild.nodeType === 3 ), + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName("tbody").length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName("link").length, + + // Get the style information from getAttribute + // (IE uses .cssText instead) + style: /top/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: ( a.getAttribute("href") === "/a" ), + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.5/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Make sure that if no value is specified for a checkbox + // that it defaults to "on". + // (WebKit defaults to "" instead) + checkOn: ( input.value === "on" ), + + // 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) + optSelected: opt.selected, + + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + getSetAttribute: div.className !== "t", + + // Tests for enctype support on a form(#6743) + enctype: !!document.createElement("form").enctype, + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", + + // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode + boxModel: ( document.compatMode === "CSS1Compat" ), + + // Will be defined later + submitBubbles: true, + changeBubbles: true, + focusinBubbles: false, + deleteExpando: true, + noCloneEvent: true, + inlineBlockNeedsLayout: false, + shrinkWrapBlocks: false, + reliableMarginRight: true, + boxSizingReliable: true, + pixelPosition: false + }; + + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // 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; + + // Test to see if it's possible to delete an expando from an element + // Fails in Internet Explorer + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + + if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { + div.attachEvent( "onclick", clickFn = function() { + // Cloning a node shouldn't copy over any + // bound event handlers (IE does this) + support.noCloneEvent = false; + }); + div.cloneNode( true ).fireEvent("onclick"); + div.detachEvent( "onclick", clickFn ); + } + + // Check if a radio maintains its value + // after being appended to the DOM + input = document.createElement("input"); + input.value = "t"; + input.setAttribute( "type", "radio" ); + support.radioValue = input.value === "t"; + + input.setAttribute( "checked", "checked" ); + + // #11217 - WebKit loses check when the name is after the checked attribute + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + fragment = document.createDocumentFragment(); + fragment.appendChild( div.lastChild ); + + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; + + fragment.removeChild( input ); + fragment.appendChild( div ); + + // Technique from Juriy Zaytsev + // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ + // We only care about the case where non-standard event systems + // are used, namely in IE. Short-circuiting here helps us to + // avoid an eval call (in setAttribute) which can cause CSP + // to go haywire. See: https://developer.mozilla.org/en/Security/CSP + if ( div.attachEvent ) { + for ( i in { + submit: true, + change: true, + focusin: true + }) { + eventName = "on" + i; + isSupported = ( eventName in div ); + if ( !isSupported ) { + div.setAttribute( eventName, "return;" ); + isSupported = ( typeof div[ eventName ] === "function" ); + } + support[ i + "Bubbles" ] = isSupported; + } + } + + // Run tests that need a body at doc ready + jQuery(function() { + var container, div, tds, marginDiv, + divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", + body = document.getElementsByTagName("body")[0]; + + if ( !body ) { + // Return for frameset docs that don't have a body + return; + } + + container = document.createElement("div"); + container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; + body.insertBefore( container, body.firstChild ); + + // Construct the test element + div = document.createElement("div"); + container.appendChild( div ); + + // 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). + // (only IE 8 fails this test) + div.innerHTML = "
t
"; + 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"; + + // Check if empty table cells still have offsetWidth/Height + // (IE <= 8 fail this test) + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + + // Check box-sizing and margin behavior + div.innerHTML = ""; + div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; + support.boxSizing = ( div.offsetWidth === 4 ); + support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); + + // NOTE: To any future maintainer, we've window.getComputedStyle + // because jsdom on node.js will break without it. + if ( window.getComputedStyle ) { + support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; + support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. For more + // info see bug #3333 + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + marginDiv = document.createElement("div"); + marginDiv.style.cssText = div.style.cssText = divReset; + marginDiv.style.marginRight = marginDiv.style.width = "0"; + div.style.width = "1px"; + div.appendChild( marginDiv ); + support.reliableMarginRight = + !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); + } + + if ( typeof div.style.zoom !== "undefined" ) { + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + // (IE < 8 does this) + div.innerHTML = ""; + div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); + + // Check if elements with layout shrink-wrap their children + // (IE 6 does this) + div.style.display = "block"; + div.style.overflow = "visible"; + div.innerHTML = "
"; + div.firstChild.style.width = "5px"; + support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); + + container.style.zoom = 1; + } + + // Null elements to avoid leaks in IE + body.removeChild( container ); + container = div = tds = marginDiv = null; + }); + + // Null elements to avoid leaks in IE + fragment.removeChild( div ); + all = a = select = opt = input = fragment = div = null; + + return support; +})(); +var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, + rmultiDash = /([A-Z])/g; + +jQuery.extend({ + cache: {}, + + deletedIds: [], + + // Remove at next major release (1.9/2.0) + uuid: 0, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet": true + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, ret, + internalKey = jQuery.expando, + getByName = typeof name === "string", + + // 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)) && getByName && data === undefined ) { + 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 ) { + elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + + // Avoids exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + if ( !isNode ) { + cache[ id ].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 ( getByName ) { + + // 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; + }, + + removeData: function( elem, name, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, l, + + 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(" "); + } + } + } + + for ( i = 0, l = name.length; i < l; 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 : 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) + } else if ( jQuery.support.deleteExpando || cache != cache.window ) { + delete cache[ id ]; + + // When all else fails, null + } else { + cache[ id ] = null; + } + }, + + // For internal use only. + _data: function( elem, name, data ) { + return jQuery.data( elem, name, data, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; + + // nodes accept data unless otherwise specified; rejection can be conditional + return !noData || noData !== true && elem.getAttribute("classid") === noData; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var parts, part, attr, name, l, + elem = this[0], + i = 0, + data = null; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = jQuery.data( elem ); + + if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { + attr = elem.attributes; + for ( l = attr.length; i < l; i++ ) { + name = attr[i].name; + + if ( !name.indexOf( "data-" ) ) { + name = jQuery.camelCase( name.substring(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 ); + }); + } + + parts = key.split( ".", 2 ); + parts[1] = parts[1] ? "." + parts[1] : ""; + part = parts[1] + "!"; + + return jQuery.access( this, function( value ) { + + if ( value === undefined ) { + data = this.triggerHandler( "getData" + part, [ parts[0] ] ); + + // Try to fetch any internally stored data first + if ( data === undefined && elem ) { + data = jQuery.data( elem, key ); + data = dataAttr( elem, key, data ); + } + + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + } + + parts[1] = value; + this.each(function() { + var self = jQuery( this ); + + self.triggerHandler( "setData" + part, parts ); + jQuery.data( this, key, value ); + self.triggerHandler( "changeData" + part, parts ); + }); + }, null, value, arguments.length > 1, null, false ); + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + +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; +} +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", true ); + jQuery.removeData( elem, key, true ); + }) + }); + } +}); + +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 ); + }); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + 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 ); + }; + }); + }, + 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 nodeHook, boolHook, fixSpecified, + rclass = /[\t\r\n]/g, + rreturn = /\r/g, + rtype = /^(?:button|input)$/i, + rfocusable = /^(?:button|input|object|select|textarea)$/i, + rclickable = /^a(?:rea|)$/i, + rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, + getSetAttribute = jQuery.support.getSetAttribute; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, + + prop: function( name, value ) { + return jQuery.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 ) {} + }); + }, + + addClass: function( value ) { + var classNames, i, l, elem, + setClass, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call(this, j, this.className) ); + }); + } + + if ( value && typeof value === "string" ) { + classNames = value.split( core_rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 ) { + if ( !elem.className && classNames.length === 1 ) { + elem.className = value; + + } else { + setClass = " " + elem.className + " "; + + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) { + setClass += classNames[ c ] + " "; + } + } + elem.className = jQuery.trim( setClass ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var removes, className, elem, c, cl, i, l; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call(this, j, this.className) ); + }); + } + if ( (value && typeof value === "string") || value === undefined ) { + removes = ( value || "" ).split( core_rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + if ( elem.nodeType === 1 && elem.className ) { + + className = (" " + elem.className + " ").replace( rclass, " " ); + + // loop over each item in the removal list + for ( c = 0, cl = removes.length; c < cl; c++ ) { + // Remove until there is nothing to remove, + while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) { + className = className.replace( " " + removes[ c ] + " " , " " ); + } + } + elem.className = value ? jQuery.trim( className ) : ""; + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + 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 ), + state = stateVal, + classNames = value.split( core_rspace ); + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space separated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // toggle whole className + 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; + }, + + 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, + self = jQuery(this); + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, self.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 ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + }, + select: { + get: function( elem ) { + var value, i, max, option, + index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type === "select-one"; + + // Nothing was selected + if ( index < 0 ) { + return null; + } + + // Loop through all the selected options + i = one ? index : 0; + max = one ? index + 1 : options.length; + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Don't return options that are disabled or in a disabled optgroup + if ( option.selected && (jQuery.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 ); + } + } + + // Fixes Bug #2551 -- select.val() broken in IE after form.reset() + if ( one && !values.length && options.length ) { + return jQuery( options[ index ] ).val(); + } + + return values; + }, + + set: function( elem, value ) { + var values = jQuery.makeArray( value ); + + jQuery(elem).find("option").each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 + attrFn: {}, + + attr: function( elem, name, value, pass ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { + return jQuery( elem )[ name ]( value ); + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( notxml ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + + } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, value + "" ); + return value; + } + + } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + + ret = elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return ret === null ? + undefined : + ret; + } + }, + + removeAttr: function( elem, value ) { + var propName, attrNames, name, isBool, + i = 0; + + if ( value && elem.nodeType === 1 ) { + + attrNames = value.split( core_rspace ); + + for ( ; i < attrNames.length; i++ ) { + name = attrNames[ i ]; + + if ( name ) { + propName = jQuery.propFix[ name ] || name; + isBool = rboolean.test( name ); + + // See #9699 for explanation of this approach (setting first, then removal) + // Do not do this for boolean attributes (see #10870) + if ( !isBool ) { + jQuery.attr( elem, name, "" ); + } + elem.removeAttribute( getSetAttribute ? name : propName ); + + // Set corresponding property to false for boolean attributes + if ( isBool && propName in elem ) { + elem[ propName ] = false; + } + } + } + } + }, + + attrHooks: { + type: { + set: function( elem, value ) { + // We can't allow the type property to be changed (since it causes problems in IE) + if ( rtype.test( elem.nodeName ) && elem.parentNode ) { + jQuery.error( "type property can't be changed" ); + } else if ( !jQuery.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 it's default in case type is set after value + // This is for element creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + }, + // Use the value property for back compat + // Use the nodeHook for button elements in IE6/7 (#1954) + value: { + get: function( elem, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.get( elem, name ); + } + return name in elem ? + elem.value : + null; + }, + set: function( elem, value, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.set( elem, value, name ); + } + // Does not return so that setAttribute is also used + elem.value = value; + } + } + }, + + propFix: { + tabindex: "tabIndex", + readonly: "readOnly", + "for": "htmlFor", + "class": "className", + maxlength: "maxLength", + cellspacing: "cellSpacing", + cellpadding: "cellPadding", + rowspan: "rowSpan", + colspan: "colSpan", + usemap: "useMap", + frameborder: "frameBorder", + contenteditable: "contentEditable" + }, + + 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 ) { + if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + return ( elem[ name ] = value ); + } + + } else { + if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + return 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/ + var attributeNode = elem.getAttributeNode("tabindex"); + + return attributeNode && attributeNode.specified ? + parseInt( attributeNode.value, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + } + } +}); + +// Hook for boolean attributes +boolHook = { + get: function( elem, name ) { + // Align boolean attributes with corresponding properties + // Fall back to attribute presence where some booleans are not supported + var attrNode, + property = jQuery.prop( elem, name ); + return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? + name.toLowerCase() : + undefined; + }, + set: function( elem, value, name ) { + var propName; + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + // value is true since we know at this point it's type boolean and not false + // Set boolean attributes to the same name and set the DOM property + propName = jQuery.propFix[ name ] || name; + if ( propName in elem ) { + // Only set the IDL specifically if it already exists on the element + elem[ propName ] = true; + } + + elem.setAttribute( name, name.toLowerCase() ); + } + return name; + } +}; + +// IE6/7 do not support getting/setting some attributes with get/setAttribute +if ( !getSetAttribute ) { + + fixSpecified = { + name: true, + id: true, + coords: true + }; + + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = jQuery.valHooks.button = { + get: function( elem, name ) { + var ret; + ret = elem.getAttributeNode( name ); + return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ? + ret.value : + undefined; + }, + set: function( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + ret = document.createAttribute( name ); + elem.setAttributeNode( ret ); + } + return ( ret.value = value + "" ); + } + }; + + // 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 ] = jQuery.extend( jQuery.attrHooks[ name ], { + set: function( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + }); + }); + + // Set contenteditable to false on removals(#10429) + // Setting to empty string throws an error as an invalid value + jQuery.attrHooks.contenteditable = { + get: nodeHook.get, + set: function( elem, value, name ) { + if ( value === "" ) { + value = "false"; + } + nodeHook.set( elem, value, name ); + } + }; +} + + +// Some attributes require a special call on IE +if ( !jQuery.support.hrefNormalized ) { + jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + get: function( elem ) { + var ret = elem.getAttribute( name, 2 ); + return ret === null ? undefined : ret; + } + }); + }); +} + +if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get: function( elem ) { + // Return undefined in the case of empty string + // Normalize to lowercase since IE uppercases css property names + return elem.style.cssText.toLowerCase() || undefined; + }, + set: function( elem, value ) { + return ( elem.style.cssText = value + "" ); + } + }; +} + +// Safari mis-reports the default selected property of an option +// Accessing the parent's selectedIndex property fixes it +if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = jQuery.extend( 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; + } + }); +} + +// IE6/7 call enctype encoding +if ( !jQuery.support.enctype ) { + jQuery.propFix.enctype = "encoding"; +} + +// Radios and checkboxes getter/setter +if ( !jQuery.support.checkOn ) { + jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + get: function( elem ) { + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + } + }; + }); +} +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); + } + } + }); +}); +var rformElems = /^(?:textarea|input|select)$/i, + rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, + rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + hoverHack = function( events ) { + return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); + }; + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + add: function( elem, types, handler, data, selector ) { + + var elemData, eventHandle, events, + t, tns, type, namespaces, handleObj, + handleObjIn, handlers, special; + + // Don't attach events to noData or text/comment nodes (allow plain objects tho) + if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { + 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 + events = elemData.events; + if ( !events ) { + elemData.events = events = {}; + } + eventHandle = elemData.handle; + if ( !eventHandle ) { + elemData.handle = eventHandle = 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 !== "undefined" && (!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 + // jQuery(...).bind("mouseover mouseout", fn); + types = jQuery.trim( hoverHack(types) ).split( " " ); + for ( t = 0; t < types.length; t++ ) { + + tns = rtypenamespace.exec( types[t] ) || []; + type = tns[1]; + namespaces = ( tns[2] || "" ).split( "." ).sort(); + + // 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: tns[1], + 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 + handlers = events[ type ]; + if ( !handlers ) { + 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; + }, + + global: {}, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var t, tns, type, origType, namespaces, origCount, + j, events, special, eventType, handleObj, + 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 = jQuery.trim( hoverHack( types || "" ) ).split(" "); + for ( t = 0; t < types.length; t++ ) { + tns = rtypenamespace.exec( types[t] ) || []; + type = origType = tns[1]; + namespaces = tns[2]; + + // 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; + eventType = events[ type ] || []; + origCount = eventType.length; + namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; + + // Remove matching events + for ( j = 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !namespaces || namespaces.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + eventType.splice( j--, 1 ); + + if ( handleObj.selector ) { + eventType.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 ( eventType.length === 0 && origCount !== eventType.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", true ); + } + }, + + // Events that are safe to short-circuit if no handlers are attached. + // Native DOM events should not be added, they may have inline handlers. + customEvent: { + "getData": true, + "setData": true, + "changeData": true + }, + + trigger: function( event, data, elem, onlyHandlers ) { + // Don't do events on text and comment nodes + if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { + return; + } + + // Event object or event type + var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, + type = event.type || event, + namespaces = []; + + // 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 ) { + // Exclusive events trigger only for the exact event (no namespaces) + type = type.slice(0, -1); + exclusive = true; + } + + if ( type.indexOf( "." ) >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + + if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { + // No jQuery handlers for this event type, and it can't have inline handlers + return; + } + + // Caller can pass in an Event, Object, or just an event type string + event = typeof event === "object" ? + // jQuery.Event object + event[ jQuery.expando ] ? event : + // Object literal + new jQuery.Event( type, event ) : + // Just the event type (string) + new jQuery.Event( type ); + + event.type = type; + event.isTrigger = true; + event.exclusive = exclusive; + event.namespace = namespaces.join( "." ); + event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; + ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; + + // Handle a global trigger + if ( !elem ) { + + // TODO: Stop taunting the data cache; remove global events and always attach to document + cache = jQuery.cache; + for ( i in cache ) { + if ( cache[ i ].events && cache[ i ].events[ type ] ) { + jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); + } + } + return; + } + + // 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 ? jQuery.makeArray( data ) : []; + data.unshift( event ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( 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) + eventPath = [[ elem, special.bindType || type ]]; + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; + for ( old = elem; cur; cur = cur.parentNode ) { + eventPath.push([ cur, bubbleType ]); + old = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( old === (elem.ownerDocument || document) ) { + eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); + } + } + + // Fire handlers on the event path + for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { + + cur = eventPath[i][0]; + event.type = eventPath[i][1]; + + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + // Note that this is a bare JS function and not a jQuery handler + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === 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( elem.ownerDocument, data ) === false) && + !(type === "click" && jQuery.nodeName( elem, "a" )) && 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) + // IE<9 dies on focus/blur to hidden element (#1486) + if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + old = elem[ ontype ]; + + if ( old ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + jQuery.event.triggered = undefined; + + if ( old ) { + elem[ ontype ] = old; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event || window.event ); + + var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, + handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), + delegateCount = handlers.delegateCount, + args = core_slice.call( arguments ), + run_all = !event.exclusive && !event.namespace, + special = jQuery.event.special[ event.type ] || {}, + handlerQueue = []; + + // 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 that should run if there are delegated events + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && !(event.button && event.type === "click") ) { + + for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { + + // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.disabled !== true || event.type !== "click" ) { + selMatch = {}; + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + sel = handleObj.selector; + + if ( selMatch[ sel ] === undefined ) { + selMatch[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( selMatch[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, matches: matches }); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( handlers.length > delegateCount ) { + handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); + } + + // Run delegates first; they may want to stop propagation beneath us + for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { + matched = handlerQueue[ i ]; + event.currentTarget = matched.elem; + + for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { + handleObj = matched.matches[ j ]; + + // Triggered event must either 1) be non-exclusive and have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { + + event.data = handleObj.data; + event.handleObj = handleObj; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + event.result = ret; + if ( 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; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** + props: "attrChange attrName relatedNode srcElement 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 eventDoc, doc, body, + 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; + } + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, + originalEvent = event, + fixHook = jQuery.event.fixHooks[ event.type ] || {}, + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = jQuery.Event( originalEvent ); + + for ( i = copy.length; i; ) { + prop = copy[ --i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Target should not be a text node (#504, Safari) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) + event.metaKey = !!event.metaKey; + + return fixHook.filter? fixHook.filter( event, originalEvent ) : event; + }, + + special: { + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + + focus: { + delegateType: "focusin" + }, + blur: { + delegateType: "focusout" + }, + + beforeunload: { + setup: function( data, namespaces, eventHandle ) { + // We only want to do this special case on windows + if ( jQuery.isWindow( this ) ) { + this.onbeforeunload = eventHandle; + } + }, + + teardown: function( namespaces, eventHandle ) { + if ( this.onbeforeunload === eventHandle ) { + this.onbeforeunload = null; + } + } + } + }, + + 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(); + } + } +}; + +// Some plugins are using, but it's undocumented/deprecated and will be removed. +// The 1.7 special event interface should provide all the hooks needed now. +jQuery.event.handle = jQuery.event.dispatch; + +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 ] === "undefined" ) { + 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.returnValue === false || + 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; +}; + +function returnFalse() { + return false; +} +function returnTrue() { + return 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 = { + preventDefault: function() { + this.isDefaultPrevented = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + + // if preventDefault exists run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // otherwise set the returnValue property of the original event to false (IE) + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + this.isPropagationStopped = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + // if stopPropagation exists run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + // otherwise set the cancelBubble property of the original event to true (IE) + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + }, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse +}; + +// 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, + selector = handleObj.selector; + + // 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 ( !jQuery.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, "_submit_attached" ) ) { + jQuery.event.add( form, "submit._submit", function( event ) { + event._submit_bubble = true; + }); + jQuery._data( form, "_submit_attached", 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 ( !jQuery.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, "_change_attached" ) ) { + 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, "_change_attached", 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 ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { // && selector != null + // ( 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 ); + }); + }, + + bind: function( types, data, fn ) { + return this.on( types, null, data, fn ); + }, + unbind: function( types, fn ) { + return this.off( types, null, fn ); + }, + + live: function( types, data, fn ) { + jQuery( this.context ).on( types, this.selector, data, fn ); + return this; + }, + die: function( types, fn ) { + jQuery( this.context ).off( types, this.selector || "**", fn ); + return this; + }, + + 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 ); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + if ( this[0] ) { + return jQuery.event.trigger( type, data, this[0], true ); + } + }, + + toggle: function( fn ) { + // Save reference to arguments for access in closure + var args = arguments, + guid = fn.guid || jQuery.guid++, + i = 0, + toggler = function( event ) { + // Figure out which function to execute + var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; + jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); + + // Make sure that clicks stop + event.preventDefault(); + + // and execute the function + return args[ lastToggle ].apply( this, arguments ) || false; + }; + + // link all the functions, so any of them can unbind this click handler + toggler.guid = guid; + while ( i < args.length ) { + args[ i++ ].guid = guid; + } + + return this.click( toggler ); + }, + + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +}); + +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 ) { + if ( fn == null ) { + fn = data; + data = null; + } + + return arguments.length > 0 ? + this.on( name, null, data, fn ) : + this.trigger( name ); + }; + + if ( rkeyEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; + } + + if ( rmouseEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; + } +}); +/*! + * Sizzle CSS Selector Engine + * Copyright 2012 jQuery Foundation and other contributors + * Released under the MIT license + * http://sizzlejs.com/ + */ +(function( window, undefined ) { + +var cachedruns, + assertGetIdNotName, + Expr, + getText, + isXML, + contains, + compile, + sortOrder, + hasDuplicate, + outermostContext, + + baseHasDuplicate = true, + strundefined = "undefined", + + expando = ( "sizcache" + Math.random() ).replace( ".", "" ), + + Token = String, + document = window.document, + docElem = document.documentElement, + dirruns = 0, + done = 0, + pop = [].pop, + push = [].push, + slice = [].slice, + // Use a stripped-down indexOf if a native one is unavailable + indexOf = [].indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; + } + } + return -1; + }, + + // Augment a function for special use by Sizzle + markFunction = function( fn, value ) { + fn[ expando ] = value == null || value; + return fn; + }, + + createCache = function() { + var cache = {}, + keys = []; + + return markFunction(function( key, value ) { + // Only keep the most recent entries + if ( keys.push( key ) > Expr.cacheLength ) { + delete cache[ keys.shift() ]; + } + + return (cache[ key ] = value); + }, cache ); + }, + + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + + // Regex + + // 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 + operators = "([*^$|!~]?=)", + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", + + // Prefer arguments not in parens/brackets, + // then attribute selectors and non-pseudos (denoted by :), + // then anything else + // These preferences are here to reduce the number of selectors + // needing tokenize in the PSEUDO preFilter + pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)", + + // For matchExpr.POS and matchExpr.needsContext + pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", + + // 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 + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), + rpseudo = new RegExp( pseudos ), + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, + + rnot = /^:not/, + rsibling = /[\x20\t\r\n\f]*[+~]/, + rendsWithNot = /:not\($/, + + rheader = /h\d/i, + rinputs = /input|select|textarea|button/i, + + rbackslash = /\\(?!\\)/g, + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "POS": new RegExp( pos, "i" ), + "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + // For use in libraries implementing .is() + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) + }, + + // Support + + // Used for testing something on an element + assert = function( fn ) { + var div = document.createElement("div"); + + try { + return fn( div ); + } catch (e) { + return false; + } finally { + // release memory in IE + div = null; + } + }, + + // Check if getElementsByTagName("*") returns only elements + assertTagNameNoComments = assert(function( div ) { + div.appendChild( document.createComment("") ); + return !div.getElementsByTagName("*").length; + }), + + // Check if getAttribute returns normalized href attributes + assertHrefNotNormalized = assert(function( div ) { + div.innerHTML = ""; + return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && + div.firstChild.getAttribute("href") === "#"; + }), + + // Check if attributes should be retrieved by attribute nodes + assertAttributes = assert(function( div ) { + div.innerHTML = ""; + var type = typeof div.lastChild.getAttribute("multiple"); + // IE8 returns a string for some attributes even when not present + return type !== "boolean" && type !== "string"; + }), + + // Check if getElementsByClassName can be trusted + assertUsableClassName = assert(function( div ) { + // Opera can't find a second classname (in 9.6) + div.innerHTML = ""; + if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { + return false; + } + + // Safari 3.2 caches class attributes and doesn't catch changes + div.lastChild.className = "e"; + return div.getElementsByClassName("e").length === 2; + }), + + // Check if getElementById returns elements by name + // Check if getElementsByName privileges form controls or returns elements by ID + assertUsableName = assert(function( div ) { + // Inject content + div.id = expando + 0; + div.innerHTML = "
"; + docElem.insertBefore( div, docElem.firstChild ); + + // Test + var pass = document.getElementsByName && + // buggy browsers will return fewer than the correct 2 + document.getElementsByName( expando ).length === 2 + + // buggy browsers will return more than the correct 0 + document.getElementsByName( expando + 0 ).length; + assertGetIdNotName = !document.getElementById( expando ); + + // Cleanup + docElem.removeChild( div ); + + return pass; + }); + +// If slice is not available, provide a backup +try { + slice.call( docElem.childNodes, 0 )[0].nodeType; +} catch ( e ) { + slice = function( i ) { + var elem, + results = []; + for ( ; (elem = this[i]); i++ ) { + results.push( elem ); + } + return results; + }; +} + +function Sizzle( selector, context, results, seed ) { + results = results || []; + context = context || document; + var match, elem, xml, m, + nodeType = context.nodeType; + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + if ( nodeType !== 1 && nodeType !== 9 ) { + return []; + } + + xml = isXML( context ); + + if ( !xml && !seed ) { + 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 #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, slice.call(context.getElementsByTagName( selector ), 0) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) { + push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); + return results; + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed, xml ); +} + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + return Sizzle( expr, null, null, [ elem ] ).length > 0; +}; + +// Returns a function to use in pseudos for input types +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 +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 +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]); + } + } + }); + }); +} + +/** + * 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 ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (see #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 + } else { + + // If no nodeType, this is expected to be an array + for ( ; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } + return ret; +}; + +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; +}; + +// Element contains another +contains = Sizzle.contains = 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) ); + } : + docElem.compareDocumentPosition ? + function( a, b ) { + return b && !!( a.compareDocumentPosition( b ) & 16 ); + } : + function( a, b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + return false; + }; + +Sizzle.attr = function( elem, name ) { + var val, + xml = isXML( elem ); + + if ( !xml ) { + name = name.toLowerCase(); + } + if ( (val = Expr.attrHandle[ name ]) ) { + return val( elem ); + } + if ( xml || assertAttributes ) { + return elem.getAttribute( name ); + } + val = elem.getAttributeNode( name ); + return val ? + typeof elem[ name ] === "boolean" ? + elem[ name ] ? name : null : + val.specified ? val.value : null : + null; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + // IE6/7 return a modified href + attrHandle: assertHrefNotNormalized ? + {} : + { + "href": function( elem ) { + return elem.getAttribute( "href", 2 ); + }, + "type": function( elem ) { + return elem.getAttribute("type"); + } + }, + + find: { + "ID": assertGetIdNotName ? + function( id, context, xml ) { + if ( typeof context.getElementById !== strundefined && !xml ) { + 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] : []; + } + } : + function( id, context, xml ) { + if ( typeof context.getElementById !== strundefined && !xml ) { + var m = context.getElementById( id ); + + return m ? + m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? + [m] : + undefined : + []; + } + }, + + "TAG": assertTagNameNoComments ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + var elem, + tmp = [], + i = 0; + + for ( ; (elem = results[i]); i++ ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }, + + "NAME": assertUsableName && function( tag, context ) { + if ( typeof context.getElementsByName !== strundefined ) { + return context.getElementsByName( name ); + } + }, + + "CLASS": assertUsableClassName && function( className, context, xml ) { + if ( typeof context.getElementsByClassName !== strundefined && !xml ) { + return context.getElementsByClassName( className ); + } + } + }, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( rbackslash, "" ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 3 xn-component of xn+y argument ([+-]?\d*n|) + 4 sign of xn-component + 5 x of xn-component + 6 sign of y-component + 7 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1] === "nth" ) { + // nth-child requires argument + if ( !match[2] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); + match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); + + // other types prohibit arguments + } else if ( match[2] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var unquoted, excess; + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + if ( match[3] ) { + match[2] = match[3]; + } else if ( (unquoted = match[4]) ) { + // Only check arguments that contain a pseudo + if ( 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 + unquoted = unquoted.slice( 0, excess ); + match[0] = match[0].slice( 0, excess ); + } + match[2] = unquoted; + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + "ID": assertGetIdNotName ? + function( id ) { + id = id.replace( rbackslash, "" ); + return function( elem ) { + return elem.getAttribute("id") === id; + }; + } : + function( id ) { + id = id.replace( rbackslash, "" ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); + return node && node.value === id; + }; + }, + + "TAG": function( nodeName ) { + if ( nodeName === "*" ) { + return function() { return true; }; + } + nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); + + return function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ expando ][ className ]; + if ( !pattern ) { + pattern = classCache( className, new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)") ); + } + return function( elem ) { + return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); + }; + }, + + "ATTR": function( name, operator, check ) { + return function( elem, context ) { + 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.substr( result.length - check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, argument, first, last ) { + + if ( type === "nth" ) { + return function( elem ) { + var node, diff, + parent = elem.parentNode; + + if ( first === 1 && last === 0 ) { + return true; + } + + if ( parent ) { + diff = 0; + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + diff++; + if ( elem === node ) { + break; + } + } + } + } + + // Incorporate the offset (or cast to NaN), then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + }; + } + + return function( elem ) { + var node = elem; + + switch ( type ) { + case "only": + case "first": + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + if ( type === "first" ) { + return true; + } + + node = elem; + + /* falls through */ + case "last": + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + return true; + } + }; + }, + + "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: { + "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; + }; + }), + + "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; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), + // not comment, processing instructions, or others + // Thanks to Diego Perini for the nodeName shortcut + // Greater than "@" means alpha characters (specifically not starting with "#" or "?") + var nodeType; + elem = elem.firstChild; + while ( elem ) { + if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { + return false; + } + elem = elem.nextSibling; + } + return true; + }, + + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "text": function( elem ) { + var type, attr; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && + (type = elem.type) === "text" && + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); + }, + + // Input types + "radio": createInputPseudo("radio"), + "checkbox": createInputPseudo("checkbox"), + "file": createInputPseudo("file"), + "password": createInputPseudo("password"), + "image": createInputPseudo("image"), + + "submit": createButtonPseudo("submit"), + "reset": createButtonPseudo("reset"), + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "focus": function( elem ) { + var doc = elem.ownerDocument; + return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href); + }, + + "active": function( elem ) { + return elem === elem.ownerDocument.activeElement; + }, + + // Positional types + "first": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length, argument ) { + for ( var i = 0; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length, argument ) { + for ( var i = 1; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +function siblingCheck( a, b, ret ) { + if ( a === b ) { + return ret; + } + + var cur = a.nextSibling; + + while ( cur ) { + if ( cur === b ) { + return -1; + } + + cur = cur.nextSibling; + } + + return 1; +} + +sortOrder = docElem.compareDocumentPosition ? + function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? + a.compareDocumentPosition : + a.compareDocumentPosition(b) & 4 + ) ? -1 : 1; + } : + function( a, b ) { + // The nodes are identical, we can exit early + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Fallback to using sourceIndex (in IE) if it's available on both nodes + } else if ( a.sourceIndex && b.sourceIndex ) { + return a.sourceIndex - b.sourceIndex; + } + + var al, bl, + ap = [], + bp = [], + aup = a.parentNode, + bup = b.parentNode, + cur = aup; + + // If the nodes are siblings (or identical) we can do a quick check + if ( aup === bup ) { + return siblingCheck( a, b ); + + // If no parents were found then the nodes are disconnected + } else if ( !aup ) { + return -1; + + } else if ( !bup ) { + return 1; + } + + // Otherwise they're somewhere else in the tree so we need + // to build up a full list of the parentNodes for comparison + while ( cur ) { + ap.unshift( cur ); + cur = cur.parentNode; + } + + cur = bup; + + while ( cur ) { + bp.unshift( cur ); + cur = cur.parentNode; + } + + al = ap.length; + bl = bp.length; + + // Start walking down the tree looking for a discrepancy + for ( var i = 0; i < al && i < bl; i++ ) { + if ( ap[i] !== bp[i] ) { + return siblingCheck( ap[i], bp[i] ); + } + } + + // We ended someplace up the tree so do a sibling check + return i === al ? + siblingCheck( a, bp[i], -1 ) : + siblingCheck( ap[i], b, 1 ); + }; + +// Always assume the presence of duplicates if sort doesn't +// pass them to our comparison function (as in Google Chrome). +[0, 0].sort( sortOrder ); +baseHasDuplicate = !hasDuplicate; + +// Document sorting and removing duplicates +Sizzle.uniqueSort = function( results ) { + var elem, + i = 1; + + hasDuplicate = baseHasDuplicate; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( ; (elem = results[i]); i++ ) { + if ( elem === results[ i - 1 ] ) { + results.splice( i--, 1 ); + } + } + } + + return results; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +function tokenize( selector, parseOnly ) { + var matched, match, tokens, type, soFar, groups, preFilters, + cached = tokenCache[ expando ][ 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 ) { + soFar = soFar.slice( match[0].length ); + } + groups.push( tokens = [] ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + tokens.push( matched = new Token( match.shift() ) ); + soFar = soFar.slice( matched.length ); + + // Cast descendant combinators to space + matched.type = match[0].replace( rtrim, " " ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + // The last two arguments here are (context, xml) for backCompat + (match = preFilters[ type ]( match, document, true ))) ) { + + tokens.push( matched = new Token( match.shift() ) ); + soFar = soFar.slice( matched.length ); + matched.type = type; + matched.matches = match; + } + } + + 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 addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && combinator.dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( checkNonElements || elem.nodeType === 1 ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( !xml ) { + var cache, + dirkey = dirruns + " " + doneName + " ", + cachedkey = dirkey + cachedruns; + while ( (elem = elem[ dir ]) ) { + if ( checkNonElements || elem.nodeType === 1 ) { + if ( (cache = elem[ expando ]) === cachedkey ) { + return elem.sizset; + } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { + if ( elem.sizset ) { + return elem; + } + } else { + elem[ expando ] = cachedkey; + if ( matcher( elem, context, xml ) ) { + elem.sizset = true; + return elem; + } + elem.sizset = false; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( checkNonElements || elem.nodeType === 1 ) { + if ( matcher( elem, context, xml ) ) { + return elem; + } + } + } + } + }; +} + +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 ) { + // Positional selectors apply to seed elements, so it is invalid to follow them with relative ones + if ( seed && postFinder ) { + return; + } + + var i, elem, postFilterIn, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [], seed ), + + // 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 ) { + postFilterIn = condense( matcherOut, postMap ); + postFilter( postFilterIn, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = postFilterIn.length; + while ( i-- ) { + if ( (elem = postFilterIn[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + // Keep seed and results synchronized + if ( seed ) { + // Ignore postFinder because it can't coexist with seed + i = preFilter && matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + seed[ preMap[i] ] = !(results[ preMap[i] ] = elem); + } + } + } 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 { + // The concatenated values are (context, xml) for backCompat + 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 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && tokens.join("") + ); + } + 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, expandContext ) { + var elem, j, matcher, + setMatched = [], + matchedCount = 0, + i = "0", + unmatched = seed && [], + outermost = expandContext != null, + contextBackup = outermostContext, + // We must always have either seed elements or context + elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), + // Nested matchers should use non-integer dirruns + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); + + if ( outermost ) { + outermostContext = context !== document && context; + cachedruns = superMatcher.el; + } + + // Add elements passing elementMatchers directly to results + for ( ; (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + for ( j = 0; (matcher = elementMatchers[j]); j++ ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + cachedruns = ++superMatcher.el; + } + } + + // 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 ) { + for ( j = 0; (matcher = setMatchers[j]); 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; + }; + + superMatcher.el = 0; + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ expando ][ 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, seed ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results, seed ); + } + return results; +} + +function select( selector, context, results, seed, xml ) { + var i, tokens, token, type, find, + match = tokenize( selector ), + j = match.length; + + 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" && + context.nodeType === 9 && !xml && + Expr.relative[ tokens[1].type ] ) { + + context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0]; + if ( !context ) { + return results; + } + + selector = selector.slice( tokens.shift().length ); + } + + // Fetch a seed set for right-to-left matching + for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; 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( rbackslash, "" ), + rsibling.test( tokens[0].type ) && context.parentNode || context, + xml + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && tokens.join(""); + if ( !selector ) { + push.apply( results, slice.call( seed, 0 ) ); + 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, + xml, + results, + rsibling.test( selector ) + ); + return results; +} + +if ( document.querySelectorAll ) { + (function() { + var disconnectedMatch, + oldSelect = select, + rescape = /'|\\/g, + rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, + + // qSa(:focus) reports false when true (Chrome 21), + // A support test would require too much code (would include document ready) + rbuggyQSA = [":focus"], + + // matchesSelector(:focus) reports false when true (Chrome 21), + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + // A support test would require too much code (would include document ready) + // just skip matchesSelector for :active + rbuggyMatches = [ ":active", ":focus" ], + matches = docElem.matchesSelector || + docElem.mozMatchesSelector || + docElem.webkitMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector; + + // 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 explictly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + div.innerHTML = ""; + + // IE8 - Some boolean attributes are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here (do not put tests after this one) + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + }); + + assert(function( div ) { + + // Opera 10-12/IE9 - ^= $= *= and empty values + // Should not select anything + div.innerHTML = "

"; + if ( div.querySelectorAll("[test^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here (do not put tests after this one) + div.innerHTML = ""; + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push(":enabled", ":disabled"); + } + }); + + // rbuggyQSA always contains :focus, so no need for a length check + rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") ); + + select = function( selector, context, results, seed, xml ) { + // Only use querySelectorAll when not filtering, + // when this is not xml, + // and when no QSA bugs apply + if ( !seed && !xml && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + var groups, i, + old = true, + nid = expando, + newContext = context, + newSelector = context.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 ( context.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 + groups[i].join(""); + } + newContext = rsibling.test( selector ) && context.parentNode || context; + newSelector = groups.join(","); + } + + if ( newSelector ) { + try { + push.apply( results, slice.call( newContext.querySelectorAll( + newSelector + ), 0 ) ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } + } + } + + return oldSelect( selector, context, results, seed, xml ); + }; + + if ( matches ) { + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + try { + matches.call( div, "[test!='']:sizzle" ); + rbuggyMatches.push( "!=", pseudos ); + } catch ( e ) {} + }); + + // rbuggyMatches always contains :active and :focus, so no need for a length check + rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); + + Sizzle.matchesSelector = function( elem, expr ) { + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + // rbuggyMatches always contains :active, so no need for an existence check + if ( !isXML( elem ) && !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 || 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, null, null, [ elem ] ).length > 0; + }; + } + })(); +} + +// Deprecated +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Back-compat +function setFilters() {} +Expr.filters = setFilters.prototype = Expr.pseudos; +Expr.setFilters = new setFilters(); + +// Override sizzle attribute retrieval +Sizzle.attr = jQuery.attr; +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; + + +})( window ); +var runtil = /Until$/, + rparentsprev = /^(?:parents|prev(?:Until|All))/, + isSimple = /^.[^:#\[\.,]*$/, + rneedsContext = jQuery.expr.match.needsContext, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var i, l, length, n, r, ret, + self = this; + + if ( typeof selector !== "string" ) { + return jQuery( selector ).filter(function() { + for ( i = 0, l = self.length; i < l; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }); + } + + ret = this.pushStack( "", "find", selector ); + + for ( i = 0, l = this.length; i < l; i++ ) { + length = ret.length; + jQuery.find( selector, this[i], ret ); + + if ( i > 0 ) { + // Make sure that the results are unique + for ( n = length; n < ret.length; n++ ) { + for ( r = 0; r < length; r++ ) { + if ( ret[r] === ret[n] ) { + ret.splice(n--, 1); + break; + } + } + } + } + } + + return ret; + }, + + 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; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false), "not", selector); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true), "filter", selector ); + }, + + is: function( selector ) { + return !!selector && ( + typeof selector === "string" ? + // 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". + rneedsContext.test( selector ) ? + jQuery( selector, this.context ).index( this[0] ) >= 0 : + jQuery.filter( selector, this ).length > 0 : + this.filter( selector ).length > 0 ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + ret = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + cur = this[i]; + + while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { + if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { + ret.push( cur ); + break; + } + cur = cur.parentNode; + } + } + + ret = ret.length > 1 ? jQuery.unique( ret ) : ret; + + return this.pushStack( ret, "closest", selectors ); + }, + + // 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.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 ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? + all : + jQuery.unique( all ) ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); + } +}); + +jQuery.fn.andSelf = jQuery.fn.addBack; + +// A painfully simple check to see if an element is disconnected +// from a document (should be improved, where feasible). +function isDisconnected( node ) { + return !node || !node.parentNode || node.parentNode.nodeType === 11; +} + +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 ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + + if ( this.length > 1 && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret, name, core_slice.call( arguments ).join(",") ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : + jQuery.find.matches(expr, elems); + }, + + 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; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, keep ) { + + // Can't pass null or undefined to indexOf in Firefox 4 + // Set to 0 to skip string check + qualifier = qualifier || 0; + + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem, i ) { + return ( elem === qualifier ) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem, i ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; + }); +} +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, + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, + rtagName = /<([\w:]+)/, + rtbody = /]", "i"), + rcheckableType = /^(?:checkbox|radio)$/, + // checked="checked" or checked + rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, + rscriptType = /\/(java|ecma)script/i, + rcleanScript = /^\s*\s*$/g, + wrapMap = { + option: [ 1, "" ], + legend: [ 1, "
", "
" ], + thead: [ 1, "", "
" ], + tr: [ 2, "", "
" ], + td: [ 3, "", "
" ], + col: [ 2, "", "
" ], + area: [ 1, "", "" ], + _default: [ 0, "", "" ] + }, + 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; + +// 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. +if ( !jQuery.support.htmlSerialize ) { + wrapMap._default = [ 1, "X
", "
" ]; +} + +jQuery.fn.extend({ + text: function( value ) { + return jQuery.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 ); + }, + + 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(); + }, + + append: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 ) { + this.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 ) { + this.insertBefore( elem, this.firstChild ); + } + }); + }, + + before: function() { + if ( !isDisconnected( this[0] ) ) { + return this.domManip(arguments, false, function( elem ) { + this.parentNode.insertBefore( elem, this ); + }); + } + + if ( arguments.length ) { + var set = jQuery.clean( arguments ); + return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); + } + }, + + after: function() { + if ( !isDisconnected( this[0] ) ) { + return this.domManip(arguments, false, function( elem ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + }); + } + + if ( arguments.length ) { + var set = jQuery.clean( arguments ); + return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); + } + }, + + // keepData is for internal use only--do not document + remove: function( selector, keepData ) { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName("*") ); + jQuery.cleanData( [ elem ] ); + } + + if ( elem.parentNode ) { + 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( elem.getElementsByTagName("*") ); + } + + // Remove any remaining nodes + while ( elem.firstChild ) { + elem.removeChild( elem.firstChild ); + } + } + + 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 jQuery.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 ) && + ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && + ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && + !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { + + value = value.replace( rxhtmlTag, "<$1>" ); + + try { + for (; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + elem = this[i] || {}; + if ( elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName( "*" ) ); + 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( value ) { + if ( !isDisconnected( this[0] ) ) { + // Make sure that the elements are removed from the DOM before they are inserted + // this can help fix replacing a parent with child elements + if ( jQuery.isFunction( value ) ) { + return this.each(function(i) { + var self = jQuery(this), old = self.html(); + self.replaceWith( value.call( this, i, old ) ); + }); + } + + if ( typeof value !== "string" ) { + value = jQuery( value ).detach(); + } + + return this.each(function() { + var next = this.nextSibling, + parent = this.parentNode; + + jQuery( this ).remove(); + + if ( next ) { + jQuery(next).before( value ); + } else { + jQuery(parent).append( value ); + } + }); + } + + return this.length ? + this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : + this; + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, table, callback ) { + + // Flatten any nested arrays + args = [].concat.apply( [], args ); + + var results, first, fragment, iNoClone, + i = 0, + value = args[0], + scripts = [], + l = this.length; + + // We can't cloneNode fragments that contain checked, in WebKit + if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { + return this.each(function() { + jQuery(this).domManip( args, table, callback ); + }); + } + + if ( jQuery.isFunction(value) ) { + return this.each(function(i) { + var self = jQuery(this); + args[0] = value.call( this, i, table ? self.html() : undefined ); + self.domManip( args, table, callback ); + }); + } + + if ( this[0] ) { + results = jQuery.buildFragment( args, this, scripts ); + fragment = results.fragment; + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + if ( first ) { + table = table && jQuery.nodeName( first, "tr" ); + + // Use the original fragment for the last item instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + // Fragments from the fragment cache must always be cloned and never used in place. + for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { + callback.call( + table && jQuery.nodeName( this[i], "table" ) ? + findOrAppend( this[i], "tbody" ) : + this[i], + i === iNoClone ? + fragment : + jQuery.clone( fragment, true, true ) + ); + } + } + + // Fix #11809: Avoid leaking memory + fragment = first = null; + + if ( scripts.length ) { + jQuery.each( scripts, function( i, elem ) { + if ( elem.src ) { + if ( jQuery.ajax ) { + jQuery.ajax({ + url: elem.src, + type: "GET", + dataType: "script", + async: false, + global: false, + "throws": true + }); + } else { + jQuery.error("no ajax"); + } + } else { + jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); + } + + if ( elem.parentNode ) { + elem.parentNode.removeChild( elem ); + } + }); + } + } + + return this; + } +}); + +function findOrAppend( elem, tag ) { + return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); +} + +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 cloneFixAttributes( src, dest ) { + var nodeName; + + // We do not need to do anything for non-Elements + if ( dest.nodeType !== 1 ) { + return; + } + + // clearAttributes removes the attributes, which we don't want, + // but also removes the attachEvent events, which we *do* want + if ( dest.clearAttributes ) { + dest.clearAttributes(); + } + + // mergeAttributes, in contrast, only merges back on the + // original attributes, not the events + if ( dest.mergeAttributes ) { + dest.mergeAttributes( src ); + } + + nodeName = dest.nodeName.toLowerCase(); + + if ( nodeName === "object" ) { + // IE6-10 improperly clones children of object elements using classid. + // IE10 throws NoModificationAllowedError if parent is null, #12132. + 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 ( jQuery.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.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; + + // IE blanks contents when cloning scripts + } else if ( nodeName === "script" && dest.text !== src.text ) { + dest.text = src.text; + } + + // Event data gets referenced instead of copied if the expando + // gets copied too + dest.removeAttribute( jQuery.expando ); +} + +jQuery.buildFragment = function( args, context, scripts ) { + var fragment, cacheable, cachehit, + first = args[ 0 ]; + + // Set context from what may come in as undefined or a jQuery collection or a node + // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 & + // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception + context = context || document; + context = !context.nodeType && context[0] || context; + context = context.ownerDocument || context; + + // Only cache "small" (1/2 KB) HTML strings that are associated with the main document + // Cloning options loses the selected state, so don't cache them + // IE 6 doesn't like it when you put or elements in a fragment + // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache + // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 + if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && + first.charAt(0) === "<" && !rnocache.test( first ) && + (jQuery.support.checkClone || !rchecked.test( first )) && + (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { + + // Mark cacheable and look for a hit + cacheable = true; + fragment = jQuery.fragments[ first ]; + cachehit = fragment !== undefined; + } + + if ( !fragment ) { + fragment = context.createDocumentFragment(); + jQuery.clean( args, context, fragment, scripts ); + + // Update the cache, but only store false + // unless this is a second parsing of the same content + if ( cacheable ) { + jQuery.fragments[ first ] = cachehit && fragment; + } + } + + return { fragment: fragment, cacheable: cacheable }; +}; + +jQuery.fragments = {}; + +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 ), + l = insert.length, + parent = this.length === 1 && this[0].parentNode; + + if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { + insert[ original ]( this[0] ); + return this; + } else { + for ( ; i < l; i++ ) { + elems = ( i > 0 ? this.clone(true) : this ).get(); + jQuery( insert[i] )[ original ]( elems ); + ret = ret.concat( elems ); + } + + return this.pushStack( ret, name, insert.selector ); + } + }; +}); + +function getAll( elem ) { + if ( typeof elem.getElementsByTagName !== "undefined" ) { + return elem.getElementsByTagName( "*" ); + + } else if ( typeof elem.querySelectorAll !== "undefined" ) { + return elem.querySelectorAll( "*" ); + + } else { + return []; + } +} + +// Used in clean, fixes the defaultChecked property +function fixDefaultChecked( elem ) { + if ( rcheckableType.test( elem.type ) ) { + elem.defaultChecked = elem.checked; + } +} + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var srcElements, + destElements, + i, + clone; + + if ( jQuery.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 ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && + (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + // IE copies events bound via attachEvent when using cloneNode. + // Calling detachEvent on the clone will also remove the events + // from the original. In order to get around this, we use some + // proprietary methods to clear the events. Thanks to MooTools + // guys for this hotness. + + cloneFixAttributes( elem, clone ); + + // Using Sizzle here is crazy slow, so we use getElementsByTagName instead + srcElements = getAll( elem ); + destElements = getAll( clone ); + + // Weird iteration because IE will replace the length property + // with an element if you are cloning the body and one of the + // elements on the page has a name or id of "length" + for ( i = 0; srcElements[i]; ++i ) { + // Ensure that the destination node is not null; Fixes #9587 + if ( destElements[i] ) { + cloneFixAttributes( srcElements[i], destElements[i] ); + } + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + cloneCopyEvent( elem, clone ); + + if ( deepDataAndEvents ) { + srcElements = getAll( elem ); + destElements = getAll( clone ); + + for ( i = 0; srcElements[i]; ++i ) { + cloneCopyEvent( srcElements[i], destElements[i] ); + } + } + } + + srcElements = destElements = null; + + // Return the cloned set + return clone; + }, + + clean: function( elems, context, fragment, scripts ) { + var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, + safe = context === document && safeFragment, + ret = []; + + // Ensure that context is a document + if ( !context || typeof context.createDocumentFragment === "undefined" ) { + context = document; + } + + // Use the already-created safe fragment if context permits + for ( i = 0; (elem = elems[i]) != null; i++ ) { + if ( typeof elem === "number" ) { + elem += ""; + } + + if ( !elem ) { + continue; + } + + // Convert html string into DOM nodes + if ( typeof elem === "string" ) { + if ( !rhtml.test( elem ) ) { + elem = context.createTextNode( elem ); + } else { + // Ensure a safe container in which to render the html + safe = safe || createSafeFragment( context ); + div = context.createElement("div"); + safe.appendChild( div ); + + // Fix "XHTML"-style tags in all browsers + elem = elem.replace(rxhtmlTag, "<$1>"); + + // Go to html and back, then peel off extra wrappers + tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + depth = wrap[0]; + div.innerHTML = wrap[1] + elem + wrap[2]; + + // Move to the right depth + while ( depth-- ) { + div = div.lastChild; + } + + // Remove IE's autoinserted from table fragments + if ( !jQuery.support.tbody ) { + + // String was a , *may* have spurious + hasBody = rtbody.test(elem); + tbody = tag === "table" && !hasBody ? + div.firstChild && div.firstChild.childNodes : + + // String was a bare or + wrap[1] === "
" && !hasBody ? + div.childNodes : + []; + + for ( j = tbody.length - 1; j >= 0 ; --j ) { + if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { + tbody[ j ].parentNode.removeChild( tbody[ j ] ); + } + } + } + + // IE completely kills leading whitespace when innerHTML is used + if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); + } + + elem = div.childNodes; + + // Take out of fragment container (we need a fresh div each time) + div.parentNode.removeChild( div ); + } + } + + if ( elem.nodeType ) { + ret.push( elem ); + } else { + jQuery.merge( ret, elem ); + } + } + + // Fix #11356: Clear elements from safeFragment + if ( div ) { + elem = div = safe = null; + } + + // Reset defaultChecked for any radios and checkboxes + // about to be appended to the DOM in IE 6/7 (#8060) + if ( !jQuery.support.appendChecked ) { + for ( i = 0; (elem = ret[i]) != null; i++ ) { + if ( jQuery.nodeName( elem, "input" ) ) { + fixDefaultChecked( elem ); + } else if ( typeof elem.getElementsByTagName !== "undefined" ) { + jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); + } + } + } + + // Append elements to a provided document fragment + if ( fragment ) { + // Special handling of each script element + handleScript = function( elem ) { + // Check if we consider it executable + if ( !elem.type || rscriptType.test( elem.type ) ) { + // Detach the script and store it in the scripts array (if provided) or the fragment + // Return truthy to indicate that it has been handled + return scripts ? + scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : + fragment.appendChild( elem ); + } + }; + + for ( i = 0; (elem = ret[i]) != null; i++ ) { + // Check if we're done after handling an executable script + if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { + // Append to fragment and handle embedded scripts + fragment.appendChild( elem ); + if ( typeof elem.getElementsByTagName !== "undefined" ) { + // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration + jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); + + // Splice the scripts into ret after their former ancestor and advance our index beyond them + ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); + i += jsTags.length; + } + } + } + } + + return ret; + }, + + cleanData: function( elems, /* internal */ acceptData ) { + var data, id, elem, type, + i = 0, + internalKey = jQuery.expando, + cache = jQuery.cache, + deleteExpando = jQuery.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 ( elem.removeAttribute ) { + elem.removeAttribute( internalKey ); + + } else { + elem[ internalKey ] = null; + } + + jQuery.deletedIds.push( id ); + } + } + } + } + } +}); +// Limit scope pollution from any deprecated API +(function() { + +var matched, browser; + +// Use of jQuery.browser is frowned upon. +// More details: http://api.jquery.com/jQuery.browser +// jQuery.uaMatch maintained for back-compat +jQuery.uaMatch = function( ua ) { + ua = ua.toLowerCase(); + + var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || + /(webkit)[ \/]([\w.]+)/.exec( ua ) || + /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || + /(msie) ([\w.]+)/.exec( ua ) || + ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || + []; + + return { + browser: match[ 1 ] || "", + version: match[ 2 ] || "0" + }; +}; + +matched = jQuery.uaMatch( navigator.userAgent ); +browser = {}; + +if ( matched.browser ) { + browser[ matched.browser ] = true; + browser.version = matched.version; +} + +// Chrome is Webkit, but Webkit is also Safari. +if ( browser.chrome ) { + browser.webkit = true; +} else if ( browser.webkit ) { + browser.safari = true; +} + +jQuery.browser = browser; + +jQuery.sub = function() { + function jQuerySub( selector, context ) { + return new jQuerySub.fn.init( selector, context ); + } + jQuery.extend( true, jQuerySub, this ); + jQuerySub.superclass = this; + jQuerySub.fn = jQuerySub.prototype = this(); + jQuerySub.fn.constructor = jQuerySub; + jQuerySub.sub = this.sub; + jQuerySub.fn.init = function init( selector, context ) { + if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { + context = jQuerySub( context ); + } + + return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); + }; + jQuerySub.fn.init.prototype = jQuerySub.fn; + var rootjQuerySub = jQuerySub(document); + return jQuerySub; +}; + +})(); +var curCSS, iframe, iframeDoc, + ralpha = /alpha\([^)]*\)/i, + ropacity = /opacity=([^)]*)/, + rposition = /^(top|right|bottom|left)$/, + // 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]).+)/, + rmargin = /^margin/, + rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), + rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), + rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ), + elemdisplay = {}, + + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: 0, + fontWeight: 400 + }, + + cssExpand = [ "Top", "Right", "Bottom", "Left" ], + cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], + + eventsToggle = jQuery.fn.toggle; + +// 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 isHidden( elem, el ) { + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); +} + +function showHide( elements, show ) { + var elem, display, + values = [], + index = 0, + length = elements.length; + + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + values[ index ] = jQuery._data( elem, "olddisplay" ); + if ( show ) { + // Reset the inline display of this element to learn if it is + // being hidden by cascaded rules or not + if ( !values[ index ] && elem.style.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", css_defaultDisplay(elem.nodeName) ); + } + } else { + display = curCSS( elem, "display" ); + + if ( !values[ index ] && display !== "none" ) { + jQuery._data( elem, "olddisplay", 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; +} + +jQuery.fn.extend({ + css: function( name, value ) { + return jQuery.access( this, function( elem, name, value ) { + 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, fn2 ) { + var bool = typeof state === "boolean"; + + if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) { + return eventsToggle.apply( this, arguments ); + } + + return this.each(function() { + if ( bool ? state : isHidden( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + }); + } +}); + +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; + + } + } + } + }, + + // Exclude the following css properties to add px + cssNumber: { + "fillOpacity": true, + "fontWeight": true, + "lineHeight": true, + "opacity": 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": jQuery.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 NaN and null values aren't set. See: #7116 + if ( value == null || type === "number" && isNaN( 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"; + } + + // 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 ) { + // Wrapped to prevent IE from throwing errors when 'invalid' values are provided + // Fixes bug #5509 + try { + 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, numeric, extra ) { + var val, num, 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 ); + } + + //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 ( numeric || extra !== undefined ) { + num = parseFloat( val ); + return numeric || jQuery.isNumeric( num ) ? num || 0 : val; + } + return val; + }, + + // A method for quickly swapping in/out CSS properties to get correct calculations + swap: function( elem, options, callback ) { + 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.call( elem ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; + } +}); + +// NOTE: To any future maintainer, we've window.getComputedStyle +// because jsdom on node.js will break without it. +if ( window.getComputedStyle ) { + curCSS = function( elem, name ) { + var ret, width, minWidth, maxWidth, + computed = window.getComputedStyle( elem, null ), + style = elem.style; + + if ( computed ) { + + ret = computed[ name ]; + 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 ) ) { + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret; + }; +} else if ( document.documentElement.currentStyle ) { + curCSS = function( elem, name ) { + var left, rsLeft, + ret = elem.currentStyle && elem.currentStyle[ name ], + style = elem.style; + + // 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; + rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; + + // Put in the new values to get a computed value out + if ( rsLeft ) { + elem.runtimeStyle.left = elem.currentStyle.left; + } + style.left = name === "fontSize" ? "1em" : ret; + ret = style.pixelLeft + "px"; + + // Revert the changed values + style.left = left; + if ( rsLeft ) { + elem.runtimeStyle.left = rsLeft; + } + } + + return ret === "" ? "auto" : ret; + }; +} + +function setPositiveNumber( elem, value, subtract ) { + var matches = rnumsplit.exec( value ); + return matches ? + Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : + value; +} + +function augmentWidthOrHeight( elem, name, extra, isBorderBox ) { + 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" ) { + // we use jQuery.css instead of curCSS here + // because of the reliableMarginRight CSS hook! + val += jQuery.css( elem, extra + cssExpand[ i ], true ); + } + + // From this point on we use curCSS for maximum performance (relevant in animations) + if ( isBorderBox ) { + // border-box includes padding, so remove it if we want content + if ( extra === "content" ) { + val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; + } + + // at this point, extra isn't border nor margin, so remove border + if ( extra !== "margin" ) { + val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; + } + } else { + // at this point, extra isn't content, so add padding + val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; + + // at this point, extra isn't content nor padding, so add border + if ( extra !== "padding" ) { + val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; + } + } + } + + return val; +} + +function getWidthOrHeight( elem, name, extra ) { + + // Start with offset property, which is equivalent to the border-box value + var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, + valueIsBorderBox = true, + isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "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 ); + 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 && ( jQuery.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 + ) + ) + "px"; +} + + +// Try to determine the default display value of an element +function css_defaultDisplay( nodeName ) { + if ( elemdisplay[ nodeName ] ) { + return elemdisplay[ nodeName ]; + } + + var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ), + display = elem.css("display"); + elem.remove(); + + // If the simple way fails, + // get element's real default display by attaching it to a temp iframe + if ( display === "none" || display === "" ) { + // Use the already-created iframe if possible + iframe = document.body.appendChild( + iframe || jQuery.extend( document.createElement("iframe"), { + frameBorder: 0, + width: 0, + height: 0 + }) + ); + + // Create a cacheable copy of the iframe document on first call. + // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML + // document to it; WebKit & Firefox won't allow reusing the iframe document. + if ( !iframeDoc || !iframe.createElement ) { + iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; + iframeDoc.write(""); + iframeDoc.close(); + } + + elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) ); + + display = curCSS( elem, "display" ); + document.body.removeChild( iframe ); + } + + // Store the correct default display + elemdisplay[ nodeName ] = display; + + return display; +} + +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 + if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) { + return jQuery.swap( elem, cssShow, function() { + return getWidthOrHeight( elem, name, extra ); + }); + } else { + return getWidthOrHeight( elem, name, extra ); + } + } + }, + + set: function( elem, value, extra ) { + return setPositiveNumber( elem, value, extra ? + augmentWidthOrHeight( + elem, + name, + extra, + jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box" + ) : 0 + ); + } + }; +}); + +if ( !jQuery.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 >= 1 && 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 there is no filter style applied in a css rule, we are done + if ( currentStyle && !currentStyle.filter ) { + return; + } + } + + // otherwise, set new filter values + style.filter = ralpha.test( filter ) ? + filter.replace( ralpha, opacity ) : + filter + " " + opacity; + } + }; +} + +// These hooks cannot be added until DOM ready because the support test +// for it is not run until after DOM ready +jQuery(function() { + if ( !jQuery.support.reliableMarginRight ) { + jQuery.cssHooks.marginRight = { + get: function( elem, 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" }, function() { + if ( computed ) { + return curCSS( elem, "marginRight" ); + } + }); + } + }; + } + + // 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 + if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { + jQuery.each( [ "top", "left" ], function( i, prop ) { + jQuery.cssHooks[ prop ] = { + get: function( elem, computed ) { + if ( computed ) { + var ret = curCSS( elem, prop ); + // if curCSS returns percentage, fallback to offset + return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret; + } + } + }; + }); + } + +}); + +if ( jQuery.expr && jQuery.expr.filters ) { + jQuery.expr.filters.hidden = function( elem ) { + return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none"); + }; + + jQuery.expr.filters.visible = function( elem ) { + return !jQuery.expr.filters.hidden( elem ); + }; +} + +// 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, + + // assumes a single number if not a string + parts = typeof value === "string" ? value.split(" ") : [ value ], + expanded = {}; + + for ( i = 0; 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; + } +}); +var r20 = /%20/g, + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, + rselectTextarea = /^(?:select|textarea)/i; + +jQuery.fn.extend({ + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map(function(){ + return this.elements ? jQuery.makeArray( this.elements ) : this; + }) + .filter(function(){ + return this.name && !this.disabled && + ( this.checked || rselectTextarea.test( this.nodeName ) || + rinput.test( this.type ) ); + }) + .map(function( i, elem ){ + var val = jQuery( this ).val(); + + return val == null ? + null : + jQuery.isArray( val ) ? + jQuery.map( val, function( val, i ){ + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + }) : + { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + }).get(); + } +}); + +//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, "+" ); +}; + +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 { + // If array item is non-scalar (array or object), encode its + // numeric index to resolve deserialization ambiguity issues. + // Note that rack (as of 1.0.0) can't currently deserialize + // nested arrays properly, and attempting to do so may cause + // a server error. Possible fixes are to modify rack's + // deserialization algorithm or to provide an option or flag + // to force array serialization to be shallow. + 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 ); + } +} +var + // Document location + ajaxLocParts, + ajaxLocation, + + rhash = /#.*$/, + 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 = /^\/\//, + rquery = /\?/, + rscript = /)<[^<]*)*<\/script>/gi, + rts = /([?&])_=[^&]*/, + rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, + + // Keep a copy of the old load method + _load = jQuery.fn.load, + + /* 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 = ["*/"] + ["*"]; + +// #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, list, placeBefore, + dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), + i = 0, + length = dataTypes.length; + + if ( jQuery.isFunction( func ) ) { + // For each dataType in the dataTypeExpression + for ( ; i < length; i++ ) { + dataType = dataTypes[ i ]; + // We control if we're asked to add before + // any existing element + placeBefore = /^\+/.test( dataType ); + if ( placeBefore ) { + dataType = dataType.substr( 1 ) || "*"; + } + list = structure[ dataType ] = structure[ dataType ] || []; + // then we add to the structure accordingly + list[ placeBefore ? "unshift" : "push" ]( func ); + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, + dataType /* internal */, inspected /* internal */ ) { + + dataType = dataType || options.dataTypes[ 0 ]; + inspected = inspected || {}; + + inspected[ dataType ] = true; + + var selection, + list = structure[ dataType ], + i = 0, + length = list ? list.length : 0, + executeOnly = ( structure === prefilters ); + + for ( ; i < length && ( executeOnly || !selection ); i++ ) { + selection = list[ i ]( options, originalOptions, jqXHR ); + // If we got redirected to another dataType + // we try there if executing only and not done already + if ( typeof selection === "string" ) { + if ( !executeOnly || inspected[ selection ] ) { + selection = undefined; + } else { + options.dataTypes.unshift( selection ); + selection = inspectPrefiltersOrTransports( + structure, options, originalOptions, jqXHR, selection, inspected ); + } + } + } + // If we're only executing or nothing was selected + // we try the catchall dataType if not done already + if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { + selection = inspectPrefiltersOrTransports( + structure, options, originalOptions, jqXHR, "*", inspected ); + } + // unnecessary when only executing (prefilters) + // but it'll be ignored by the caller in that case + return selection; +} + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes #9887 +function ajaxExtend( target, src ) { + var key, deep, + 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 ); + } +} + +jQuery.fn.load = function( url, params, callback ) { + if ( typeof url !== "string" && _load ) { + return _load.apply( this, arguments ); + } + + // Don't do a request if no elements are being requested + if ( !this.length ) { + return this; + } + + var selector, type, response, + 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"; + } + + // Request the remote document + jQuery.ajax({ + url: url, + + // if "type" variable is undefined, then "GET" method will be used + type: type, + dataType: "html", + data: params, + complete: function( jqXHR, status ) { + if ( callback ) { + self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); + } + } + }).done(function( responseText ) { + + // Save response for use in complete callback + response = arguments; + + // See if a selector was specified + self.html( selector ? + + // Create a dummy div to hold the results + jQuery("
") + + // inject the contents of the document in, removing the scripts + // to avoid any 'Permission Denied' errors in IE + .append( responseText.replace( rscript, "" ) ) + + // Locate the specified elements + .find( selector ) : + + // If not, just inject the full result + responseText ); + + }); + + return this; +}; + +// Attach a bunch of functions for handling common AJAX events +jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ + jQuery.fn[ o ] = function( f ){ + return this.on( o, f ); + }; +}); + +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({ + type: method, + url: url, + data: data, + success: callback, + dataType: type + }); + }; +}); + +jQuery.extend({ + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + // 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 ) { + if ( settings ) { + // Building a settings object + ajaxExtend( target, jQuery.ajaxSettings ); + } else { + // Extending ajaxSettings + settings = target; + target = jQuery.ajaxSettings; + } + ajaxExtend( target, settings ); + return target; + }, + + ajaxSettings: { + url: ajaxLocation, + isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), + global: true, + type: "GET", + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + processData: true, + async: true, + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + xml: "application/xml, text/xml", + html: "text/html", + text: "text/plain", + json: "application/json, text/javascript", + "*": allTypes + }, + + contents: { + xml: /xml/, + html: /html/, + json: /json/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText" + }, + + // List of data converters + // 1) key format is "source_type destination_type" (a single space in-between) + // 2) the catchall symbol "*" can be used for source_type + converters: { + + // Convert anything to text + "* text": window.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: { + context: true, + url: true + } + }, + + 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 // ifModified key + ifModifiedKey, + // Response headers + responseHeadersString, + responseHeaders, + // transport + transport, + // timeout handle + timeoutTimer, + // Cross-domain detection vars + parts, + // To know if global events are to be dispatched + fireGlobals, + // Loop variable + i, + // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + // Callbacks context + callbackContext = s.context || s, + // Context for global events + // It's the callbackContext if one was provided in the options + // and if it's a DOM node or a jQuery collection + globalEventContext = callbackContext !== s && + ( callbackContext.nodeType || callbackContext instanceof 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, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( !state ) { + var lname = name.toLowerCase(); + name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Raw string + getAllResponseHeaders: function() { + return state === 2 ? responseHeadersString : null; + }, + + // 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 === undefined ? null : match; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( !state ) { + s.mimeType = type; + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + statusText = statusText || strAbort; + if ( transport ) { + transport.abort( statusText ); + } + done( 0, statusText ); + return this; + } + }; + + // Callback for when everything is done + // It is defined here because jslint complains if it is declared + // at the end of the function (which would be more logical and readable) + 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; + + // Get response data + if ( responses ) { + response = ajaxHandleResponses( s, jqXHR, responses ); + } + + // If successful, handle type chaining + if ( status >= 200 && status < 300 || status === 304 ) { + + // 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[ ifModifiedKey ] = modified; + } + modified = jqXHR.getResponseHeader("Etag"); + if ( modified ) { + jQuery.etag[ ifModifiedKey ] = modified; + } + } + + // If not modified + if ( status === 304 ) { + + statusText = "notmodified"; + isSuccess = true; + + // If we have data + } else { + + isSuccess = ajaxConvert( s, response ); + statusText = isSuccess.state; + success = isSuccess.data; + error = isSuccess.error; + isSuccess = !error; + } + } else { + // We extract error from statusText + // then normalize statusText and status for non-aborts + error = statusText; + if ( !statusText || status ) { + 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( "ajax" + ( isSuccess ? "Success" : "Error" ), + [ 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" ); + } + } + } + + // Attach deferreds + deferred.promise( jqXHR ); + jqXHR.success = jqXHR.done; + jqXHR.error = jqXHR.fail; + jqXHR.complete = completeDeferred.add; + + // Status-dependent callbacks + jqXHR.statusCode = function( map ) { + if ( map ) { + var tmp; + if ( state < 2 ) { + for ( tmp in map ) { + statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; + } + } else { + tmp = map[ jqXHR.status ]; + jqXHR.always( tmp ); + } + } + return this; + }; + + // Remove hash character (#7531: and string promotion) + // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) + // We also use the url parameter if available + s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); + + // Extract dataTypes list + s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); + + // 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() ) || false; + s.crossDomain = parts && ( parts.join(":") + ( parts[ 3 ] ? "" : parts[ 1 ] === "http:" ? 80 : 443 ) ) !== + ( ajaxLocParts.join(":") + ( 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; + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // If data is available, append data to url + if ( s.data ) { + s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; + // #9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Get ifModifiedKey before adding the anti-cache parameter + ifModifiedKey = s.url; + + // Add anti-cache in url if needed + if ( s.cache === false ) { + + var ts = jQuery.now(), + // try replacing _= if it is there + ret = s.url.replace( rts, "$1_=" + ts ); + + // if nothing was replaced, add timestamp to the end + s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); + } + } + + // 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 If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + ifModifiedKey = ifModifiedKey || s.url; + if ( jQuery.lastModified[ ifModifiedKey ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); + } + if ( jQuery.etag[ ifModifiedKey ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); + } + } + + // 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; + } + } + } + + return jqXHR; + }, + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {} + +}); + +/* Handles responses to an ajax request: + * - sets all responseXXX fields accordingly + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jqXHR, responses ) { + + var ct, type, finalDataType, firstDataType, + contents = s.contents, + dataTypes = s.dataTypes, + responseFields = s.responseFields; + + // Fill responseXXX fields + for ( type in responseFields ) { + if ( type in responses ) { + jqXHR[ responseFields[type] ] = responses[ type ]; + } + } + + // 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 +function ajaxConvert( s, response ) { + + var conv, conv2, current, tmp, + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(), + prev = dataTypes[ 0 ], + converters = {}, + i = 0; + + // Apply the dataFilter if provided + if ( s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + // Convert to each sequential dataType, tolerating list modification + for ( ; (current = dataTypes[++i]); ) { + + // There's only work to do if current dataType is non-auto + if ( current !== "*" ) { + + // Convert response if prev dataType is non-auto and differs from current + 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.splice( i--, 0, current ); + } + + 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 }; + } + } + } + } + + // Update prev for next iteration + prev = current; + } + } + + return { state: "success", data: response }; +} +var oldCallbacks = [], + rquestion = /\?/, + rjsonp = /(=)\?(?=&|$)|\?\?/, + nonce = jQuery.now(); + +// 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, + data = s.data, + url = s.url, + hasCallback = s.jsonp !== false, + replaceInUrl = hasCallback && rjsonp.test( url ), + replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && + !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && + rjsonp.test( data ); + + // Handle iff the expected data type is "jsonp" or we have a parameter to set + if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { + + // Get callback name, remembering preexisting value associated with it + callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? + s.jsonpCallback() : + s.jsonpCallback; + overwritten = window[ callbackName ]; + + // Insert callback into url or form data + if ( replaceInUrl ) { + s.url = url.replace( rjsonp, "$1" + callbackName ); + } else if ( replaceInData ) { + s.data = data.replace( rjsonp, "$1" + callbackName ); + } else if ( hasCallback ) { + s.url += ( rquestion.test( 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 + 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"; + } +}); +// Install script dataType +jQuery.ajaxSetup({ + accepts: { + script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /javascript|ecmascript/ + }, + 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 || document.getElementsByTagName( "head" )[0] || document.documentElement; + + return { + + send: function( _, callback ) { + + script = document.createElement( "script" ); + + script.async = "async"; + + 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 ( head && script.parentNode ) { + head.removeChild( script ); + } + + // Dereference the script + script = undefined; + + // Callback if not abort + if ( !isAbort ) { + callback( 200, "success" ); + } + } + }; + // Use insertBefore instead of appendChild to circumvent an IE6 bug. + // This arises when a base node is used (#2709 and #4378). + head.insertBefore( script, head.firstChild ); + }, + + abort: function() { + if ( script ) { + script.onload( 0, 1 ); + } + } + }; + } +}); +var xhrCallbacks, + // #5280: Internet Explorer will keep connections alive if we don't abort on unload + xhrOnUnloadAbort = window.ActiveXObject ? function() { + // Abort all pending requests + for ( var key in xhrCallbacks ) { + xhrCallbacks[ key ]( 0, 1 ); + } + } : false, + xhrId = 0; + +// Functions to create xhrs +function createStandardXHR() { + try { + return new window.XMLHttpRequest(); + } catch( e ) {} +} + +function createActiveXHR() { + try { + return new window.ActiveXObject( "Microsoft.XMLHTTP" ); + } catch( e ) {} +} + +// Create the request object +// (This is still attached to ajaxSettings for backward compatibility) +jQuery.ajaxSettings.xhr = window.ActiveXObject ? + /* Microsoft failed to properly + * implement the XMLHttpRequest in IE7 (can't request local files), + * so we use the ActiveXObject when it is available + * Additionally XMLHttpRequest can be disabled in IE7/IE8 so + * we need a fallback. + */ + function() { + return !this.isLocal && createStandardXHR() || createActiveXHR(); + } : + // For all other browsers, use the standard XMLHttpRequest object + createStandardXHR; + +// Determine support properties +(function( xhr ) { + jQuery.extend( jQuery.support, { + ajax: !!xhr, + cors: !!xhr && ( "withCredentials" in xhr ) + }); +})( jQuery.ajaxSettings.xhr() ); + +// Create transport if the browser can provide an xhr +if ( jQuery.support.ajax ) { + + jQuery.ajaxTransport(function( s ) { + // Cross domain only allowed if supported through XMLHttpRequest + if ( !s.crossDomain || jQuery.support.cors ) { + + var callback; + + return { + send: function( headers, complete ) { + + // Get a new xhr + var handle, i, + xhr = s.xhr(); + + // Open the socket + // Passing null username, generates a login popup on Opera (#2865) + if ( s.username ) { + xhr.open( s.type, s.url, s.async, s.username, s.password ); + } else { + xhr.open( s.type, s.url, s.async ); + } + + // Apply custom fields if provided + if ( s.xhrFields ) { + for ( i in s.xhrFields ) { + xhr[ i ] = s.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( s.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( s.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 ( !s.crossDomain && !headers["X-Requested-With"] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Need an extra try/catch for cross domain requests in Firefox 3 + try { + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + } catch( _ ) {} + + // Do send the request + // This may raise an exception which is actually + // handled in jQuery.ajax (so no try/catch here) + xhr.send( ( s.hasContent && s.data ) || null ); + + // Listener + callback = function( _, isAbort ) { + + var status, + statusText, + responseHeaders, + responses, + xml; + + // Firefox throws exceptions when accessing properties + // of an xhr when a network error occurred + // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) + try { + + // Was never called and is aborted or complete + if ( callback && ( isAbort || xhr.readyState === 4 ) ) { + + // Only called once + callback = undefined; + + // Do not keep as active anymore + if ( handle ) { + xhr.onreadystatechange = jQuery.noop; + if ( xhrOnUnloadAbort ) { + delete xhrCallbacks[ handle ]; + } + } + + // If it's an abort + if ( isAbort ) { + // Abort it manually if needed + if ( xhr.readyState !== 4 ) { + xhr.abort(); + } + } else { + status = xhr.status; + responseHeaders = xhr.getAllResponseHeaders(); + responses = {}; + xml = xhr.responseXML; + + // Construct response list + if ( xml && xml.documentElement /* #4958 */ ) { + responses.xml = xml; + } + + // When requesting binary data, IE6-9 will throw an exception + // on any attempt to access responseText (#11426) + try { + responses.text = xhr.responseText; + } catch( _ ) { + } + + // 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 && s.isLocal && !s.crossDomain ) { + status = responses.text ? 200 : 404; + // IE - #1450: sometimes returns 1223 when it should be 204 + } else if ( status === 1223 ) { + status = 204; + } + } + } + } catch( firefoxAccessException ) { + if ( !isAbort ) { + complete( -1, firefoxAccessException ); + } + } + + // Call complete if needed + if ( responses ) { + complete( status, statusText, responses, responseHeaders ); + } + }; + + if ( !s.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, 0 ); + } else { + handle = ++xhrId; + if ( xhrOnUnloadAbort ) { + // Create the active xhrs callbacks list if needed + // and attach the unload handler + if ( !xhrCallbacks ) { + xhrCallbacks = {}; + jQuery( window ).unload( xhrOnUnloadAbort ); + } + // Add to list of active xhrs callbacks + xhrCallbacks[ handle ] = callback; + } + xhr.onreadystatechange = callback; + } + }, + + abort: function() { + if ( callback ) { + callback(0,1); + } + } + }; + } + }); +} +var fxNow, timerId, + rfxtypes = /^(?:toggle|show|hide)$/, + rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), + rrun = /queueHooks$/, + animationPrefilters = [ defaultPrefilter ], + tweeners = { + "*": [function( prop, value ) { + var end, unit, + tween = this.createTween( prop, value ), + parts = rfxnum.exec( value ), + target = tween.cur(), + start = +target || 0, + scale = 1, + maxIterations = 20; + + if ( parts ) { + end = +parts[2]; + unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + + // We need to compute starting value + if ( unit !== "px" && start ) { + // Iteratively approximate from a nonzero starting point + // Prefer the current property, because this process will be trivial if it uses the same units + // Fallback to end or a simple constant + start = jQuery.css( tween.elem, prop, true ) || end || 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 ); + } + + tween.unit = unit; + tween.start = start; + // If a +=/-= token was provided, we're doing a relative animation + tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; + } + return tween; + }] + }; + +// Animations created synchronously will run synchronously +function createFxNow() { + setTimeout(function() { + fxNow = undefined; + }, 0 ); + return ( fxNow = jQuery.now() ); +} + +function createTweens( animation, props ) { + jQuery.each( props, function( prop, value ) { + var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), + index = 0, + length = collection.length; + for ( ; index < length; index++ ) { + if ( collection[ index ].call( animation, prop, value ) ) { + + // we're done with this property + return; + } + } + }); +} + +function Animation( elem, properties, options ) { + var result, + index = 0, + tweenerIndex = 0, + length = animationPrefilters.length, + deferred = jQuery.Deferred().always( function() { + // don't match elem in the :animated selector + delete tick.elem; + }), + tick = function() { + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + percent = 1 - ( remaining / animation.duration || 0 ), + 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, easing ) { + 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; + + 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; + } + } + + createTweens( animation, props ); + + if ( jQuery.isFunction( animation.opts.start ) ) { + animation.opts.start.call( elem, animation ); + } + + jQuery.fx.timer( + jQuery.extend( tick, { + anim: animation, + queue: animation.opts.queue, + elem: elem + }) + ); + + // 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 ); +} + +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; + } + } +} + +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 ); + } + } +}); + +function defaultPrefilter( elem, props, opts ) { + var index, prop, value, length, dataShow, tween, hooks, oldfire, + anim = this, + style = elem.style, + orig = {}, + handled = [], + hidden = elem.nodeType && isHidden( elem ); + + // 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 + if ( jQuery.css( elem, "display" ) === "inline" && + jQuery.css( elem, "float" ) === "none" ) { + + // inline-level elements accept inline-block; + // block-level elements need to be inline with layout + if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { + style.display = "inline-block"; + + } else { + style.zoom = 1; + } + } + } + + if ( opts.overflow ) { + style.overflow = "hidden"; + if ( !jQuery.support.shrinkWrapBlocks ) { + anim.done(function() { + style.overflow = opts.overflow[ 0 ]; + style.overflowX = opts.overflow[ 1 ]; + style.overflowY = opts.overflow[ 2 ]; + }); + } + } + + + // show/hide pass + for ( index in props ) { + value = props[ index ]; + if ( rfxtypes.exec( value ) ) { + delete props[ index ]; + if ( value === ( hidden ? "hide" : "show" ) ) { + continue; + } + handled.push( index ); + } + } + + length = handled.length; + if ( length ) { + dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); + if ( hidden ) { + jQuery( elem ).show(); + } else { + anim.done(function() { + jQuery( elem ).hide(); + }); + } + anim.done(function() { + var prop; + jQuery.removeData( elem, "fxshow", true ); + for ( prop in orig ) { + jQuery.style( elem, prop, orig[ prop ] ); + } + }); + for ( index = 0 ; index < length ; index++ ) { + prop = handled[ index ]; + tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); + orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); + + if ( !( prop in dataShow ) ) { + dataShow[ prop ] = tween.start; + if ( hidden ) { + tween.end = tween.start; + tween.start = prop === "width" || prop === "height" ? 1 : 0; + } + } + } + } +} + +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 any value as a 4th 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, false, "" ); + // 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; + } + } + } +}; + +// Remove in 2.0 - this supports IE8's 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.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" || + // special check for .toggle( handler, handler, ... ) + ( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ? + cssFn.apply( this, arguments ) : + this.animate( genFx( name, true ), speed, easing, callback ); + }; +}); + +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 resolve immediately + if ( empty ) { + anim.stop( true ); + } + }; + + 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 ); + } + }); + } +}); + +// 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; +} + +// 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.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.easing = { + linear: function( p ) { + return p; + }, + swing: function( p ) { + return 0.5 - Math.cos( p*Math.PI ) / 2; + } +}; + +jQuery.timers = []; +jQuery.fx = Tween.prototype.init; +jQuery.fx.tick = function() { + var timer, + timers = jQuery.timers, + i = 0; + + 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(); + } +}; + +jQuery.fx.timer = function( timer ) { + if ( timer() && jQuery.timers.push( timer ) && !timerId ) { + timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); + } +}; + +jQuery.fx.interval = 13; + +jQuery.fx.stop = function() { + clearInterval( timerId ); + timerId = null; +}; + +jQuery.fx.speeds = { + slow: 600, + fast: 200, + // Default speed + _default: 400 +}; + +// Back Compat <1.8 extension point +jQuery.fx.step = {}; + +if ( jQuery.expr && jQuery.expr.filters ) { + jQuery.expr.filters.animated = function( elem ) { + return jQuery.grep(jQuery.timers, function( fn ) { + return elem === fn.elem; + }).length; + }; +} +var rroot = /^(?:body|html)$/i; + +jQuery.fn.offset = function( options ) { + if ( arguments.length ) { + return options === undefined ? + this : + this.each(function( i ) { + jQuery.offset.setOffset( this, options, i ); + }); + } + + var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, + box = { top: 0, left: 0 }, + elem = this[ 0 ], + doc = elem && elem.ownerDocument; + + if ( !doc ) { + return; + } + + if ( (body = doc.body) === elem ) { + return jQuery.offset.bodyOffset( elem ); + } + + 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 !== "undefined" ) { + box = elem.getBoundingClientRect(); + } + win = getWindow( doc ); + clientTop = docElem.clientTop || body.clientTop || 0; + clientLeft = docElem.clientLeft || body.clientLeft || 0; + scrollTop = win.pageYOffset || docElem.scrollTop; + scrollLeft = win.pageXOffset || docElem.scrollLeft; + return { + top: box.top + scrollTop - clientTop, + left: box.left + scrollLeft - clientLeft + }; +}; + +jQuery.offset = { + + bodyOffset: function( body ) { + var top = body.offsetTop, + left = body.offsetLeft; + + if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { + top += parseFloat( jQuery.css(body, "marginTop") ) || 0; + left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; + } + + return { top: top, left: left }; + }, + + setOffset: function( elem, options, i ) { + var position = jQuery.css( elem, "position" ); + + // set position first, in-case top/left are set even on static elem + if ( position === "static" ) { + elem.style.position = "relative"; + } + + var curElem = jQuery( elem ), + curOffset = curElem.offset(), + curCSSTop = jQuery.css( elem, "top" ), + curCSSLeft = jQuery.css( elem, "left" ), + calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, + props = {}, curPosition = {}, curTop, curLeft; + + // 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({ + + position: function() { + if ( !this[0] ) { + return; + } + + var elem = this[0], + + // Get *real* offsetParent + offsetParent = this.offsetParent(), + + // Get correct offsets + offset = this.offset(), + parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); + + // Subtract 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 + offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; + offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; + + // Add offsetParent borders + parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; + parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; + + // Subtract the two offsets + return { + top: offset.top - parentOffset.top, + left: offset.left - parentOffset.left + }; + }, + + offsetParent: function() { + return this.map(function() { + var offsetParent = this.offsetParent || document.body; + while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { + offsetParent = offsetParent.offsetParent; + } + return offsetParent || document.body; + }); + } +}); + + +// 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 jQuery.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 ); + }; +}); + +function getWindow( elem ) { + return jQuery.isWindow( elem ) ? + elem : + elem.nodeType === 9 ? + elem.defaultView || elem.parentWindow : + false; +} +// 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 jQuery.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, value, extra ) : + + // Set width or height on the element + jQuery.style( elem, type, value, extra ); + }, type, chainable ? margin : undefined, chainable, null ); + }; + }); +}); +// Expose jQuery to the global object +window.jQuery = window.$ = jQuery; + +// Expose jQuery as an AMD module, but only for AMD loaders that +// understand the issues with loading multiple versions of jQuery +// in a page that all might call define(). The loader will indicate +// they have special allowances for multiple jQuery versions by +// specifying define.amd.jQuery = true. Register as a named module, +// since jQuery can be concatenated with other files that may use define, +// but not use 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.amd.jQuery ) { + define( "jquery", [], function () { return jQuery; } ); +} + +})( window ); diff --git a/third_party/phantomjs/test/www/regression/pjs-13551/child1.html b/third_party/phantomjs/test/www/regression/pjs-13551/child1.html new file mode 100644 index 00000000000..1f9ee6573d9 --- /dev/null +++ b/third_party/phantomjs/test/www/regression/pjs-13551/child1.html @@ -0,0 +1,2 @@ + + diff --git a/third_party/phantomjs/test/www/regression/pjs-13551/child1a.html b/third_party/phantomjs/test/www/regression/pjs-13551/child1a.html new file mode 100644 index 00000000000..fdaa7f100d1 --- /dev/null +++ b/third_party/phantomjs/test/www/regression/pjs-13551/child1a.html @@ -0,0 +1,12 @@ + + + + diff --git a/third_party/phantomjs/test/www/regression/pjs-13551/child2.html b/third_party/phantomjs/test/www/regression/pjs-13551/child2.html new file mode 100644 index 00000000000..93322fc8179 --- /dev/null +++ b/third_party/phantomjs/test/www/regression/pjs-13551/child2.html @@ -0,0 +1,9 @@ + + + + +

success

diff --git a/third_party/phantomjs/test/www/regression/pjs-13551/closing-parent.html b/third_party/phantomjs/test/www/regression/pjs-13551/closing-parent.html new file mode 100644 index 00000000000..5ad4d2bd91d --- /dev/null +++ b/third_party/phantomjs/test/www/regression/pjs-13551/closing-parent.html @@ -0,0 +1,23 @@ + + + + diff --git a/third_party/phantomjs/test/www/regression/pjs-13551/reloading-parent.html b/third_party/phantomjs/test/www/regression/pjs-13551/reloading-parent.html new file mode 100644 index 00000000000..6364ec6c2f5 --- /dev/null +++ b/third_party/phantomjs/test/www/regression/pjs-13551/reloading-parent.html @@ -0,0 +1,22 @@ + + + + diff --git a/third_party/phantomjs/test/www/regression/webkit-60448.html b/third_party/phantomjs/test/www/regression/webkit-60448.html new file mode 100644 index 00000000000..1de358b3cd4 --- /dev/null +++ b/third_party/phantomjs/test/www/regression/webkit-60448.html @@ -0,0 +1,15 @@ + + +Test passes if it does not crash. + +
+ + + \ No newline at end of file diff --git a/third_party/phantomjs/test/www/render/image.jpg b/third_party/phantomjs/test/www/render/image.jpg new file mode 100644 index 00000000000..53de7f6f13f Binary files /dev/null and b/third_party/phantomjs/test/www/render/image.jpg differ diff --git a/third_party/phantomjs/test/www/render/index.html b/third_party/phantomjs/test/www/render/index.html new file mode 100644 index 00000000000..aa7e80f24a2 --- /dev/null +++ b/third_party/phantomjs/test/www/render/index.html @@ -0,0 +1,15 @@ + + + + + + + + + + + diff --git a/third_party/phantomjs/test/www/status.py b/third_party/phantomjs/test/www/status.py new file mode 100644 index 00000000000..e7a1c3e403f --- /dev/null +++ b/third_party/phantomjs/test/www/status.py @@ -0,0 +1,50 @@ +import cStringIO as StringIO +import urlparse + +def html_esc(s): + return s.replace('&','&').replace('<','<').replace('>','>') + +def handle_request(req): + url = urlparse.urlparse(req.path) + headers = [] + body = "" + + try: + query = urlparse.parse_qsl(url.query, strict_parsing=True) + status = None + for key, value in query: + if key == 'status': + if status is not None: + raise ValueError("status can only be specified once") + status = int(value) + elif key == 'Content-Type' or key == 'Content-Length': + raise ValueError("cannot override " + key) + else: + headers.append((key, value)) + + if status is None: + status = 200 + + body = "

Status: {}

".format(status) + if headers: + body += "
"
+            for key, value in headers:
+                body += html_esc("{}: {}\n".format(key, value))
+            body += "
" + + except Exception as e: + try: + status = int(url.query) + body = "

Status: {}

".format(status) + except: + status = 400 + body = "

Status: 400

" + body += "
" + html_esc(str(e)) + "
" + + req.send_response(status) + req.send_header('Content-Type', 'text/html') + req.send_header('Content-Length', str(len(body))) + for key, value in headers: + req.send_header(key, value) + req.end_headers() + return StringIO.StringIO(body) diff --git a/third_party/phantomjs/test/www/url-encoding.py b/third_party/phantomjs/test/www/url-encoding.py new file mode 100644 index 00000000000..300dfdcba35 --- /dev/null +++ b/third_party/phantomjs/test/www/url-encoding.py @@ -0,0 +1,85 @@ +# -*- encoding: utf-8 -*- +import urlparse +from cStringIO import StringIO +import time + +def html_esc(s): + return s.replace('&','&').replace('<','<').replace('>','>') + +def do_response(req, body, code=200, headers={}): + req.send_response(code) + req.send_header('Content-Length', str(len(body))) + if 'Content-Type' not in headers: + req.send_header('Content-Type', 'text/html') + for k, v in headers.items(): + if k != 'Content-Length': + req.send_header(k, v) + req.end_headers() + return StringIO(body) + +def do_redirect(req, target): + return do_response(req, + 'Go here'.format(target), + code=302, headers={ 'Location': target }) + +def handle_request(req): + url = urlparse.urlparse(req.path) + + # This handler returns one of several different documents, + # depending on the query string. Many of the URLs involved contain + # text encoded in Shift_JIS, and will not round-trip correctly if + # misinterpreted as UTF-8. Comments indicate the Unicode equivalent. + + if url.query == '/': + return do_redirect(req, '?/%83y%81[%83W') + + elif url.query == '/f': + return do_response(req, + '' + 'framed' + '' + '' + '' + '') + + elif url.query == "/r": + return do_response(req, + '') + + elif url.query == "/re": + return do_response(req, + '' + '' + '') + + elif url.query == "/%83y%81[%83W": # ページ + return do_response(req, '

PASS

') + + elif url.query == "/%98g": # 枠 + return do_response(req, '

PASS

') + + elif url.query == "/%95s%96%D1%82%C8%98_%91%88": # 不毛な論争 + return do_response(req, '

FRAME

') + + elif url.query == "/%8F%91": # 書 + return do_response(req, + 'window.onload=function(){' + 'document.body.innerHTML="

PASS

";};', + headers={'Content-Type': 'application/javascript'}) + + elif url.query == "/%8C%CC%8F%E1": # 故障 + return do_response(req, + 'internal server error', + code=500) + + elif url.query == "/%89i%8Bv": # 永久 + time.sleep(5) + return do_response(req, '', code=204) + + else: + return do_response(req, + '404 Not Found' + '

URL not found: {}

' + .format(html_esc(req.path)), + code=404) diff --git a/third_party/phantomjs/test/www/user-agent.html b/third_party/phantomjs/test/www/user-agent.html new file mode 100644 index 00000000000..adab8e830d7 --- /dev/null +++ b/third_party/phantomjs/test/www/user-agent.html @@ -0,0 +1,9 @@ + + +User Agent + + +

User agent is: Unknown.

+ + +