diff --git a/.npmignore b/.npmignore index c2dd518c763..ea37a1d02c9 100644 --- a/.npmignore +++ b/.npmignore @@ -1,7 +1,3 @@ -# exclude phantomjs tests -third_party/phantomjs/ -# exclude phantom_shim project -phantom_shim # exclude all tests test utils/node6-transform diff --git a/.travis.yml b/.travis.yml index e3927edbf07..bbf8e4c500a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,7 +15,6 @@ install: script: - 'if [ "$NODE7" = "true" ]; then yarn run lint; fi' - 'if [ "$NODE7" = "true" ]; then yarn run coverage; fi' - - 'if [ "$NODE7" = "true" ]; then yarn run test-phantom; fi' - 'if [ "$NODE6" = "true" ]; then yarn run node6; fi' - 'if [ "$NODE6" = "true" ]; then yarn run test-node6; fi' - 'if [ "$NODE6" = "true" ]; then yarn run node6-sanity; fi' diff --git a/package.json b/package.json index 6c4dffe0a48..f1e15d75ae1 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,6 @@ "scripts": { "unit": "jasmine test/test.js", "debug-unit": "DEBUG_TEST=true node --inspect-brk ./node_modules/.bin/jasmine test/test.js", - "test-phantom": "python third_party/phantomjs/test/run-tests.py", "test-doclint": "jasmine utils/doclint/check_public_api/test/test.js && jasmine utils/doclint/preprocessor/test.js", "test": "npm run lint --silent && npm run coverage && npm run test-phantom && npm run test-doclint && npm run test-node6", "install": "node install.js", diff --git a/phantom_shim/FileSystem.js b/phantom_shim/FileSystem.js deleted file mode 100644 index 5ff79af19fa..00000000000 --- a/phantom_shim/FileSystem.js +++ /dev/null @@ -1,375 +0,0 @@ -/** - * 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. - */ - -const path = require('path'); -const fs = require('fs'); -const deasync = require('deasync'); -const removeRecursive = require('rimraf').sync; -const 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) { - const content = fs.readFileSync(fromPath); - fs.writeFileSync(toPath, content); - } - - /** - * @param {string} fromPath - * @param {string} toPath - */ - move(fromPath, toPath) { - const 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 - * @return {boolean} - */ - lastModified(filePath) { - return fs.statSync(filePath).mtime; - } - - /** - * @param {string} dirPath - * @return {boolean} - */ - makeDirectory(dirPath) { - try { - fs.mkdirSync(dirPath); - return true; - } catch (e) { - return false; - } - } - - /** - * @param {string} dirPath - * @return {boolean} - */ - makeTree(dirPath) { - return this.makeDirectory(dirPath); - } - - /** - * @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) { - const 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); - } -} - -const fdwrite = deasync(fs.write); -const 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) { - const buffer = Buffer.from(data, this._encoding); - const 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) { - let position = this._position; - if (!size) { - size = fs.fstatSync(this._fd).size; - position = 0; - } - const buffer = new Buffer(size); - const 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/phantom_shim/Phantom.js b/phantom_shim/Phantom.js deleted file mode 100644 index dbbd93ad7fb..00000000000 --- a/phantom_shim/Phantom.js +++ /dev/null @@ -1,142 +0,0 @@ -/** - * 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. - */ - -const fs = require('fs'); -const path = require('path'); -const vm = require('vm'); -const url = require('url'); - -const VERSION = [0, 0, 1]; - -module.exports.version = VERSION; - -/** - * @param {!Object} context - * @param {string} scriptPath - */ -module.exports.create = function(context, scriptPath) { - const 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() { - return { - major: VERSION[0], - minor: VERSION[1], - patch: VERSION[2], - }; - }, - - /** - * @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; - let 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) { - const 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/phantom_shim/README.md b/phantom_shim/README.md deleted file mode 100644 index cdbe8e786ec..00000000000 --- a/phantom_shim/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# PhantomShim - -PhantomShim is a phantomJS script runner built atop of Puppeteer API. - -### Q: Can I use PhantomShim to run my scripts? -No. - -PhantomShim aims to pass PhantomJS tests rather then to be a valid PhantomJS script runner: -- PhantomShim shortcuts a lot of corners (e.g. [handling only a few keys](https://github.com/GoogleChrome/puppeteer/blob/4269f6a1bb0c2d1cc27a9ed1132017669c33a259/phantom_shim/WebPage.js#L75) that are necessary to pass tests). -- PhantomShim spawns [nested event loops](https://github.com/abbr/deasync) to emulate PhantomJS execution model. This might result in unpredictable side-effects, e.g. in [unexpected reenterability](https://github.com/GoogleChrome/puppeteer/blob/4269f6a1bb0c2d1cc27a9ed1132017669c33a259/phantom_shim/WebPage.js#L694). - -### Q: What's the purpose of PhantomShim? -The goal is to prove comprehensiveness of Puppeteer API. - -PhantomShim is built atop of Puppeteer API and is used to run PhantomJS tests. -Whenever PhantomShim can't implement certain capability to pass phantomJS test, Puppeteer API is improved to make it possible. - -### Q: Are there plans to evolve PhantomShim into a real PhantomJS script runner? -No. - -On the contrary, PhantomShim is likely to be removed from the Puppeteer repository as it passes all interesting PhantomJS tests. \ No newline at end of file diff --git a/phantom_shim/System.js b/phantom_shim/System.js deleted file mode 100644 index f8cc2dadf8c..00000000000 --- a/phantom_shim/System.js +++ /dev/null @@ -1,118 +0,0 @@ -/** - * 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. - */ - -const readline = require('readline'); -const await = require('./utilities').await; -const 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) { - const linePromise = new Promise(fulfill => this._readline.once('line', fulfill)); - await(linePromise); - } - return this._lines.shift(); - } - - /** - * @return {string} - */ - read() { - if (!this._closed) { - const closePromise = new Promise(fulfill => this._readline.once('close', fulfill)); - await(closePromise); - } - const 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/phantom_shim/WebPage.js b/phantom_shim/WebPage.js deleted file mode 100644 index 6b74937c050..00000000000 --- a/phantom_shim/WebPage.js +++ /dev/null @@ -1,748 +0,0 @@ -/** - * 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. - */ - -const await = require('./utilities').await; -const EventEmitter = require('events'); -const fs = require('fs'); -const path = require('path'); -const PageEvents = require('../lib/Page').Events; - -const 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.settings = options.settings || {}; - if (options.settings.userAgent) - this.settings.userAgent = options.settings.userAgent; - if (options.viewportSize) - await(this._page.setViewport(options.viewportSize)); - else - await(this._page.setViewport({width: 400, height: 300})); - - this.loading = false; - this.loadingProgress = 0; - this.clipRect = options.clipRect || {left: 0, top: 0, width: 0, height: 0}; - this.onConsoleMessage = null; - this.onLoadFinished = null; - this.onResourceError = null; - this.onResourceReceived = null; - this._onInitialized = undefined; - this._deferEvaluate = false; - this._customHeaders = {}; - - this._currentFrame = this._page.mainFrame(); - - this.libraryPath = path.dirname(scriptPath); - - this._onResourceRequestedCallback = undefined; - this._onConfirmCallback = undefined; - this._onPromptCallback = undefined; - this._onAlertCallback = undefined; - this._onError = noop; - - this._pageEvents = new AsyncEmitter(this._page); - this._pageEvents.on(PageEvents.Request, request => this._onRequest(request)); - this._pageEvents.on(PageEvents.Response, response => this._onResponseReceived(response)); - this._pageEvents.on(PageEvents.RequestFinished, request => this._onRequestFinished(request)); - this._pageEvents.on(PageEvents.RequestFailed, event => (this.onResourceError || noop).call(null, event)); - this._pageEvents.on(PageEvents.Console, (...args) => this._onConsole(...args)); - this._pageEvents.on(PageEvents.Confirm, message => this._onConfirm(message)); - this._pageEvents.on(PageEvents.Alert, message => this._onAlert(message)); - this._pageEvents.on(PageEvents.Dialog, dialog => this._onDialog(dialog)); - this._pageEvents.on(PageEvents.PageError, error => (this._onError || noop).call(null, error.message, error.stack)); - this.event = { - key: { - A: 65, - B: 66, - C: 67, - Home: ['Home'], - Delete: ['Delete'], - Backspace: ['Backspace'], - Cut: ['Cut'], - Paste: ['Paste'] - }, - modifier: { - shift: 'Shift' - } - }; - } - - /** - * @param {!Array} args - */ - _onConsole(...args) { - if (!this.onConsoleMessage) - return; - const text = args.join(' '); - this.onConsoleMessage(text); - } - - /** - * @return {string} - */ - currentFrameName() { - return this.frameName; - } - - /** - * @return {number} - */ - childFramesCount() { - return this.framesCount; - } - - /** - * @return {!Array} - */ - childFramesName() { - return this.framesName; - } - - /** - * @param {(string|number)} frameName - * @return {boolean} - */ - switchToChildFrame(frame) { - return this.switchToFrame(frame); - } - - /** - * @return {string} - */ - get frameName() { - return this._currentFrame.name(); - } - - /** - * @return {number} - */ - get framesCount() { - return this._currentFrame.childFrames().length; - } - - /** - * @return {!Array} - */ - get framesName() { - return this._currentFrame.childFrames().map(frame => frame.name()); - } - - /** - * @return {string} - */ - get focusedFrameName() { - const focusedFrame = this._focusedFrame(); - return focusedFrame ? focusedFrame.name() : ''; - } - - /** - * @return {?Frame} - */ - _focusedFrame() { - const frames = this._currentFrame.childFrames().slice(); - frames.push(this._currentFrame); - const promises = frames.map(frame => frame.evaluate(() => document.hasFocus())); - const result = await(Promise.all(promises)); - for (let i = 0; i < result.length; ++i) { - if (result[i]) - return frames[i]; - } - return null; - } - - switchToFocusedFrame() { - const frame = this._focusedFrame(); - this._currentFrame = frame; - } - - /** - * @param {(string|number)} frameName - * @return {boolean} - */ - switchToFrame(frameName) { - let frame = null; - if (typeof frameName === 'string') - frame = this._currentFrame.childFrames().find(frame => frame.name() === frameName); - else if (typeof frameName === 'number') - frame = this._currentFrame.childFrames()[frameName]; - if (!frame) - return false; - this._currentFrame = frame; - return true; - } - - /** - * @return {boolean} - */ - switchToParentFrame() { - const frame = this._currentFrame.parentFrame(); - if (!frame) - return false; - this._currentFrame = frame; - return true; - } - - switchToMainFrame() { - this._currentFrame = this._page.mainFrame(); - } - - get cookies() { - return await(this._page.cookies()); - } - - set cookies(cookies) { - const cookies2 = await(this._page.cookies()); - await(this._page.deleteCookie(...cookies2)); - await(this._page.setCookie(...cookies)); - - } - - addCookie(cookie) { - await(this._page.setCookie(cookie)); - } - - deleteCookie(cookieName) { - await(this._page.deleteCookie({name: cookieName})); - } - - get onInitialized() { - return this._onInitialized; - } - - set onInitialized(value) { - if (typeof value !== 'function') - this._onInitialized = undefined; - else - this._onInitialized = value; - } - - /** - * @return {?function(!Object, !Request)} - */ - get onResourceRequested() { - return this._onResourceRequestedCallback; - } - - /** - * @return {?function(!Object, !Request)} callback - */ - set onResourceRequested(callback) { - await(this._page.setRequestInterceptionEnabled(!!callback)); - this._onResourceRequestedCallback = callback; - } - - _onRequest(request) { - if (!this._onResourceRequestedCallback) - return; - const requestData = new RequestData(request); - const phantomRequest = new PhantomRequest(); - this._onResourceRequestedCallback.call(null, requestData, phantomRequest); - if (phantomRequest._aborted) { - request.abort(); - } else { - request.continue({ - url: phantomRequest._url, - headers: phantomRequest._headers, - }); - } - } - - _onResponseReceived(response) { - if (!this.onResourceReceived) - return; - const phantomResponse = new PhantomResponse(response, false /* isResponseFinished */); - this.onResourceReceived.call(null, phantomResponse); - } - - _onRequestFinished(request) { - if (!this.onResourceReceived) - return; - const phantomResponse = new PhantomResponse(request.response(), true /* isResponseFinished */); - this.onResourceReceived.call(null, phantomResponse); - } - - /** - * @param {string} url - * @param {function()} callback - */ - includeJs(url, callback) { - this._page.addScriptTag(url).then(callback); - } - - /** - * @return {!{width: number, height: number}} - */ - get viewportSize() { - return this._page.viewport(); - } - - /** - * @return {!Object} - */ - get customHeaders() { - return this._customHeaders; - } - - /** - * @param {!Object} value - */ - set customHeaders(value) { - this._customHeaders = value; - await(this._page.setExtraHTTPHeaders(new Map(Object.entries(value)))); - } - - /** - * @param {string} filePath - */ - injectJs(filePath) { - if (!fs.existsSync(filePath)) - filePath = path.resolve(this.libraryPath, filePath); - if (!fs.existsSync(filePath)) - return false; - await(this._page.injectFile(filePath)); - return true; - } - - /** - * @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._onConfirmCallback; - } - - /** - * @param {function()} handler - */ - set onConfirm(handler) { - if (typeof handler !== 'function') - handler = undefined; - this._onConfirmCallback = handler; - } - - /** - * @return {(function()|undefined)} - */ - get onPrompt() { - return this._onPromptCallback; - } - - /** - * @param {function()} handler - */ - set onPrompt(handler) { - if (typeof handler !== 'function') - handler = undefined; - this._onPromptCallback = handler; - } - - /** - * @return {(function()|undefined)} - */ - get onAlert() { - return this._onAlertCallback; - } - - /** - * @param {function()} handler - */ - set onAlert(handler) { - if (typeof handler !== 'function') - handler = undefined; - this._onAlertCallback = handler; - } - - /** - * @param {!Dialog} dialog - */ - _onDialog(dialog) { - if (dialog.type === 'alert' && this._onAlertCallback) { - this._onAlertCallback.call(null, dialog.message()); - await(dialog.accept()); - } else if (dialog.type === 'confirm' && this._onConfirmCallback) { - const result = this._onConfirmCallback.call(null, dialog.message()); - await(result ? dialog.accept() : dialog.dismiss()); - } else if (dialog.type === 'prompt' && this._onPromptCallback) { - const result = this._onPromptCallback.call(null, dialog.message(), dialog.defaultValue()); - await(result ? dialog.accept(result) : dialog.dismiss()); - } - } - - /** - * @return {string} - */ - get url() { - return await(this._page.url()); - } - - /** - * @param {string} html - */ - set content(html) { - await(this._page.setContent(html)); - } - - /** - * @param {string} selector - * @param {(string|!Array)} files - */ - uploadFile(selector, files) { - if (typeof files === 'string') - await(await(this._page.$(selector)).uploadFile(files)); - else - await(await(this._page.$(selector)).uploadFile(...files)); - } - - /** - * @param {string} eventType - * @param {!Array<*>} args - */ - sendEvent(eventType, ...args) { - if (eventType.startsWith('key')) - this._sendKeyboardEvent.apply(this, arguments); - else - this._sendMouseEvent.apply(this, arguments); - } - - /** - * @param {string} eventType - * @param {string} keyOrKeys - * @param {null} nop1 - * @param {null} nop2 - * @param {number} modifier - */ - _sendKeyboardEvent(eventType, keyOrKeys, nop1, nop2, modifier) { - switch (eventType) { - case 'keyup': - if (typeof keyOrKeys === 'number') { - await(this._page.keyboard.up(String.fromCharCode(keyOrKeys))); - break; - } - for (const key of keyOrKeys) - await(this._page.keyboard.up(key)); - break; - case 'keypress': - if (modifier & 0x04000000) - this._page.keyboard.down('Control'); - if (modifier & 0x02000000) - this._page.keyboard.down('Shift'); - if (keyOrKeys instanceof Array) { - this._page.keyboard.down(keyOrKeys[0]); - await(this._page.keyboard.up(keyOrKeys[0])); - } else if (typeof keyOrKeys === 'number') { - await(this._page.type(String.fromCharCode(keyOrKeys))); - } else { - await(this._page.type(keyOrKeys)); - } - if (modifier & 0x02000000) - this._page.keyboard.up('Shift'); - if (modifier & 0x04000000) - this._page.keyboard.up('Control'); - break; - case 'keydown': - if (typeof keyOrKeys === 'number') { - await(this._page.keyboard.down(String.fromCharCode(keyOrKeys))); - break; - } - for (const key of keyOrKeys) - await(this._page.keyboard.down(key)); - break; - } - } - - /** - * @param {string} eventType - * @param {number} x - * @param {number} y - * @param {string|undefined} button - * @param {number|undefined} modifier - */ - _sendMouseEvent(eventType, x, y, button, modifier) { - if (modifier) - await(this._page.keyboard.down(modifier)); - switch (eventType) { - case 'mousemove': - await(this._page.mouse.move(x, y)); - break; - case 'mousedown': - await(this._page.mouse.move(x, y)); - await(this._page.mouse.down({button})); - break; - case 'mouseup': - await(this._page.mouse.move(x, y)); - await(this._page.mouse.up({button})); - break; - case 'doubleclick': - await(this._page.mouse.click(x, y, {button})); - await(this._page.mouse.click(x, y, {button, clickCount: 2})); - break; - case 'click': - await(this._page.mouse.click(x, y, {button})); - break; - case 'contextmenu': - await(this._page.mouse.click(x, y, {button: 'right'})); - break; - } - if (modifier) - await(this._page.keyboard.up(modifier)); - } - /** - * @param {string} html - * @param {function()=} callback - */ - open(url, callback) { - console.assert(arguments.length <= 2, 'WebPage.open does not support METHOD and DATA arguments'); - this._deferEvaluate = true; - if (typeof this._onInitialized === 'function') - this._onInitialized(); - this._deferEvaluate = false; - this.loading = true; - this.loadingProgress = 50; - - const handleNavigation = (error, response) => { - this.loadingProgress = 100; - this.loading = false; - if (error) { - this.onResourceError.call(null, { - url, - errorString: 'SSL handshake failed' - }); - } - const status = error ? 'fail' : 'success'; - if (this.onLoadFinished) - this.onLoadFinished.call(null, status); - if (callback) - callback.call(null, status); - this.loadingProgress = 0; - }; - this._page.goto(url).then(response => handleNavigation(null, response)) - .catch(e => handleNavigation(e, null)); - } - - /** - * @param {!{width: number, height: number}} options - */ - set viewportSize(options) { - await(this._page.setViewport(options)); - } - - /** - * @param {function()|string} fun - * @param {!Array} args - */ - evaluate(fun, ...args) { - if (typeof fun === 'string') - fun = `(${fun})()`; - if (this._deferEvaluate) - return await(this._page.evaluateOnNewDocument(fun, ...args)); - return await(this._currentFrame.evaluate(fun, ...args)); - } - - /** - * {string} fileName - */ - render(fileName) { - if (fileName.endsWith('pdf')) { - const options = {}; - const paperSize = this.paperSize || {}; - options.margin = paperSize.margin; - options.format = paperSize.format; - options.landscape = paperSize.orientation === 'landscape'; - options.width = paperSize.width; - options.height = paperSize.height; - options.path = fileName; - await(this._page.pdf(options)); - } else { - const options = {}; - if (this.clipRect && (this.clipRect.left || this.clipRect.top || this.clipRect.width || this.clipRect.height)) { - options.clip = { - x: this.clipRect.left, - y: this.clipRect.top, - width: this.clipRect.width, - height: this.clipRect.height - }; - } - options.path = fileName; - await(this._page.screenshot(options)); - } - } - - 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.setUserAgent(value)); - } - - /** - * @return {string} - */ - get userAgent() { - return await(this._page.evaluate(() => window.navigator.userAgent)); - } -} - -class PhantomRequest { - constructor() { - this._url = undefined; - this._headers = undefined; - } - - /** - * @param {string} key - * @param {string} value - */ - setHeader(key, value) { - if (!this._headers) - this._headers = new Map(); - this._headers.set(key, value); - } - - abort() { - this._aborted = true; - } - - /** - * @param {string} url - */ - changeUrl(newUrl) { - this._url = newUrl; - } -} - -class PhantomResponse { - /** - * @param {!Response} response - * @param {boolean} isResponseFinished - */ - constructor(response, isResponseFinished) { - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.stage = isResponseFinished ? 'end' : 'start'; - this.headers = []; - for (const entry of response.headers.entries()) { - this.headers.push({ - name: entry[0], - value: entry[1] - }); - } - } -} - -class RequestData { - /** - * @param {!InterceptedRequest} request - */ - constructor(request) { - this.url = request.url, - this.headers = {}; - for (const entry of request.headers.entries()) - this.headers[entry[0]] = entry[1]; - } -} - -// 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. - const 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/phantom_shim/WebServer.js b/phantom_shim/WebServer.js deleted file mode 100644 index 96fe5ff7893..00000000000 --- a/phantom_shim/WebServer.js +++ /dev/null @@ -1,83 +0,0 @@ -/** - * 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. - */ - -const http = require('http'); -const 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); - const errorPromise = new Promise(x => this._server.once('error', x)); - const 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); - const headers = res.getHeaders(); - res.headers = []; - for (const key in headers) { - res.headers.push({ - name: key, - value: headers[key] - }); - } - res.header = res.getHeader; - res.setHeaders = headers => { - for (const 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/phantom_shim/runner.js b/phantom_shim/runner.js deleted file mode 100755 index 469fb42cb49..00000000000 --- a/phantom_shim/runner.js +++ /dev/null @@ -1,115 +0,0 @@ -#!/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. - */ - -const await = require('./utilities').await; -const vm = require('vm'); -const path = require('path'); -const fs = require('fs'); -const Phantom = require('./Phantom'); -const FileSystem = require('./FileSystem'); -const System = require('./System'); -const WebPage = require('./WebPage'); -const WebServer = require('./WebServer'); -const child_process = require('child_process'); -const puppeteer = require('..'); -const argv = require('minimist')(process.argv.slice(2), { - alias: { v: 'version' }, - boolean: ['headless'], - default: {'headless': true }, -}); - -if (argv.version) { - console.log('PhantomShim v' + Phantom.version.join('.')); - return; -} - -if (argv['ssl-certificates-path']) { - console.error('Flag --ssl-certificates-path is not supported.'); - process.exit(1); - return; -} - -const scriptArguments = argv._; -if (!scriptArguments.length) { - console.log(__filename.split('/').pop() + ' [scriptfile]'); - return; -} - -const scriptPath = path.resolve(process.cwd(), scriptArguments[0]); -if (!fs.existsSync(scriptPath)) { - console.error(`script not found: ${scriptPath}`); - process.exit(1); - return; -} - -const context = createPhantomContext(argv.headless, scriptPath, argv); -const scriptContent = fs.readFileSync(scriptPath, 'utf8'); -vm.runInContext(scriptContent, context); - -/** - * @param {boolean} headless - * @param {string} scriptPath - * @param {!Array} argv - * @return {!Object} - */ -function createPhantomContext(headless, scriptPath, argv) { - const context = {}; - let browser = null; - 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(ensureBrowser(), scriptPath, options); - - vm.createContext(context); - - const nativeExports = { - fs: new FileSystem(), - system: new System(argv._), - webpage: { - create: context.WebPage, - }, - webserver: { - create: () => new WebServer(), - }, - cookiejar: { - create: () => {}, - }, - child_process: child_process - }; - const bootstrapPath = path.join(__dirname, '..', 'third_party', 'phantomjs', 'bootstrap.js'); - const bootstrapCode = fs.readFileSync(bootstrapPath, 'utf8'); - vm.runInContext(bootstrapCode, context, { - filename: 'bootstrap.js' - })(nativeExports); - return context; - - function ensureBrowser() { - if (!browser) { - browser = await(puppeteer.launch({ - headless: argv.headless, - args: ['--no-sandbox'] - })); - } - return browser; - } -} - diff --git a/phantom_shim/utilities.js b/phantom_shim/utilities.js deleted file mode 100644 index 1f36ac94be7..00000000000 --- a/phantom_shim/utilities.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * 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. - */ - -const loopWhile = require('deasync').loopWhile; - -module.exports = { - await: function(promise) { - let error; - let result; - let 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 deleted file mode 100644 index d5256cfec4c..00000000000 --- a/third_party/phantomjs/CHANGES.md +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index d5dfdd1f661..00000000000 --- a/third_party/phantomjs/LICENSE.BSD +++ /dev/null @@ -1,22 +0,0 @@ -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 deleted file mode 100644 index f3a69c55009..00000000000 --- a/third_party/phantomjs/bootstrap.js +++ /dev/null @@ -1,235 +0,0 @@ -/*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 ) { - console.log(t--); - } else { - console.log("BLAST OFF!"); - phantom.exit(); - } - }, 1000); diff --git a/third_party/phantomjs/examples/detectsniff.js b/third_party/phantomjs/examples/detectsniff.js deleted file mode 100644 index f30867b35aa..00000000000 --- a/third_party/phantomjs/examples/detectsniff.js +++ /dev/null @@ -1,60 +0,0 @@ -// Detect if a web page sniffs the user agent or not. - -"use strict"; -var page = require('webpage').create(), - system = require('system'), - sniffed, - address; - -page.onInitialized = function () { - page.evaluate(function () { - - (function () { - var userAgent = window.navigator.userAgent, - platform = window.navigator.platform; - - window.navigator = { - appCodeName: 'Mozilla', - appName: 'Netscape', - cookieEnabled: false, - sniffed: false - }; - - window.navigator.__defineGetter__('userAgent', function () { - window.navigator.sniffed = true; - return userAgent; - }); - - window.navigator.__defineGetter__('platform', function () { - window.navigator.sniffed = true; - return platform; - }); - })(); - }); -}; - -if (system.args.length === 1) { - console.log('Usage: detectsniff.js '); - phantom.exit(1); -} else { - address = system.args[1]; - console.log('Checking ' + address + '...'); - page.open(address, function (status) { - if (status !== 'success') { - console.log('FAIL to load the address'); - phantom.exit(); - } else { - window.setTimeout(function () { - sniffed = page.evaluate(function () { - return navigator.sniffed; - }); - if (sniffed) { - console.log('The page tried to sniff the user agent.'); - } else { - console.log('The page did not try to sniff the user agent.'); - } - phantom.exit(); - }, 1500); - } - }); -} diff --git a/third_party/phantomjs/examples/echoToFile.js b/third_party/phantomjs/examples/echoToFile.js deleted file mode 100644 index cfb8858cb96..00000000000 --- a/third_party/phantomjs/examples/echoToFile.js +++ /dev/null @@ -1,24 +0,0 @@ -// echoToFile.js - Write in a given file all the parameters passed on the CLI -"use strict"; -var fs = require('fs'), - system = require('system'); - -if (system.args.length < 3) { - console.log("Usage: echoToFile.js DESTINATION_FILE "); - phantom.exit(1); -} else { - var content = '', - f = null, - i; - for ( i= 2; i < system.args.length; ++i ) { - content += system.args[i] + (i === system.args.length-1 ? '' : ' '); - } - - try { - fs.write(system.args[1], content, 'w'); - } catch(e) { - console.log(e); - } - - phantom.exit(); -} diff --git a/third_party/phantomjs/examples/features.js b/third_party/phantomjs/examples/features.js deleted file mode 100644 index 4c2a14acc13..00000000000 --- a/third_party/phantomjs/examples/features.js +++ /dev/null @@ -1,30 +0,0 @@ -"use strict"; -var feature, supported = [], unsupported = []; - -phantom.injectJs('modernizr.js'); -console.log('Detected features (using Modernizr ' + Modernizr._version + '):'); -for (feature in Modernizr) { - if (Modernizr.hasOwnProperty(feature)) { - if (feature[0] !== '_' && typeof Modernizr[feature] !== 'function' && - feature !== 'input' && feature !== 'inputtypes') { - if (Modernizr[feature]) { - supported.push(feature); - } else { - unsupported.push(feature); - } - } - } -} - -console.log(''); -console.log('Supported:'); -supported.forEach(function (e) { - console.log(' ' + e); -}); - -console.log(''); -console.log('Not supported:'); -unsupported.forEach(function (e) { - console.log(' ' + e); -}); -phantom.exit(); diff --git a/third_party/phantomjs/examples/fibo.js b/third_party/phantomjs/examples/fibo.js deleted file mode 100644 index 7ee472a9925..00000000000 --- a/third_party/phantomjs/examples/fibo.js +++ /dev/null @@ -1,10 +0,0 @@ -"use strict"; -var fibs = [0, 1]; -var ticker = window.setInterval(function () { - console.log(fibs[fibs.length - 1]); - fibs.push(fibs[fibs.length - 1] + fibs[fibs.length - 2]); - if (fibs.length > 10) { - window.clearInterval(ticker); - phantom.exit(); - } -}, 300); diff --git a/third_party/phantomjs/examples/hello.js b/third_party/phantomjs/examples/hello.js deleted file mode 100644 index 82d2dbbcc4e..00000000000 --- a/third_party/phantomjs/examples/hello.js +++ /dev/null @@ -1,3 +0,0 @@ -"use strict"; -console.log('Hello, world!'); -phantom.exit(); diff --git a/third_party/phantomjs/examples/injectme.js b/third_party/phantomjs/examples/injectme.js deleted file mode 100644 index 18d9fda52aa..00000000000 --- a/third_party/phantomjs/examples/injectme.js +++ /dev/null @@ -1,26 +0,0 @@ -// Use 'page.injectJs()' to load the script itself in the Page context - -"use strict"; -if ( typeof(phantom) !== "undefined" ) { - var page = require('webpage').create(); - - // Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this") - page.onConsoleMessage = function(msg) { - console.log(msg); - }; - - page.onAlert = function(msg) { - console.log(msg); - }; - - console.log("* Script running in the Phantom context."); - console.log("* Script will 'inject' itself in a page..."); - page.open("about:blank", function(status) { - if ( status === "success" ) { - console.log(page.injectJs("injectme.js") ? "... done injecting itself!" : "... fail! Check the $PWD?!"); - } - phantom.exit(); - }); -} else { - alert("* Script running in the Page context."); -} diff --git a/third_party/phantomjs/examples/loadspeed.js b/third_party/phantomjs/examples/loadspeed.js deleted file mode 100644 index 626a51cf333..00000000000 --- a/third_party/phantomjs/examples/loadspeed.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -var page = require('webpage').create(), - system = require('system'), - t, address; - -if (system.args.length === 1) { - console.log('Usage: loadspeed.js '); - phantom.exit(1); -} else { - t = Date.now(); - address = system.args[1]; - page.open(address, function (status) { - if (status !== 'success') { - console.log('FAIL to load the address'); - } else { - t = Date.now() - t; - console.log('Page title is ' + page.evaluate(function () { - return document.title; - })); - console.log('Loading time ' + t + ' msec'); - } - phantom.exit(); - }); -} diff --git a/third_party/phantomjs/examples/loadurlwithoutcss.js b/third_party/phantomjs/examples/loadurlwithoutcss.js deleted file mode 100644 index b6f13c6153a..00000000000 --- a/third_party/phantomjs/examples/loadurlwithoutcss.js +++ /dev/null @@ -1,26 +0,0 @@ -"use strict"; -var page = require('webpage').create(), - system = require('system'); - -if (system.args.length < 2) { - console.log('Usage: loadurlwithoutcss.js URL'); - phantom.exit(); -} - -var address = system.args[1]; - -page.onResourceRequested = function(requestData, request) { - if ((/http:\/\/.+?\.css/gi).test(requestData['url']) || requestData.headers['Content-Type'] == 'text/css') { - console.log('The url of the request is matching. Aborting: ' + requestData['url']); - request.abort(); - } -}; - -page.open(address, function(status) { - if (status === 'success') { - phantom.exit(); - } else { - console.log('Unable to load the address!'); - phantom.exit(); - } -}); diff --git a/third_party/phantomjs/examples/modernizr.js b/third_party/phantomjs/examples/modernizr.js deleted file mode 100644 index 24de6cc7513..00000000000 --- a/third_party/phantomjs/examples/modernizr.js +++ /dev/null @@ -1,1406 +0,0 @@ -/*! - * Modernizr v2.8.2 - * www.modernizr.com - * - * Copyright (c) Faruk Ates, Paul Irish, Alex Sexton - * Available under the BSD and MIT licenses: www.modernizr.com/license/ - */ - -/* - * Modernizr tests which native CSS3 and HTML5 features are available in - * the current UA and makes the results available to you in two ways: - * as properties on a global Modernizr object, and as classes on the - * element. This information allows you to progressively enhance - * your pages with a granular level of control over the experience. - * - * Modernizr has an optional (not included) conditional resource loader - * called Modernizr.load(), based on Yepnope.js (yepnopejs.com). - * To get a build that includes Modernizr.load(), as well as choosing - * which tests to include, go to www.modernizr.com/download/ - * - * Authors Faruk Ates, Paul Irish, Alex Sexton - * Contributors Ryan Seddon, Ben Alman - */ - -window.Modernizr = (function( window, document, undefined ) { - - var version = '2.8.2', - - Modernizr = {}, - - /*>>cssclasses*/ - // option for enabling the HTML classes to be added - enableClasses = true, - /*>>cssclasses*/ - - docElement = document.documentElement, - - /** - * Create our "modernizr" element that we do most feature tests on. - */ - mod = 'modernizr', - modElem = document.createElement(mod), - mStyle = modElem.style, - - /** - * Create the input element for various Web Forms feature tests. - */ - inputElem /*>>inputelem*/ = document.createElement('input') /*>>inputelem*/ , - - /*>>smile*/ - smile = ':)', - /*>>smile*/ - - toString = {}.toString, - - // TODO :: make the prefixes more granular - /*>>prefixes*/ - // List of property values to set for css tests. See ticket #21 - prefixes = ' -webkit- -moz- -o- -ms- '.split(' '), - /*>>prefixes*/ - - /*>>domprefixes*/ - // Following spec is to expose vendor-specific style properties as: - // elem.style.WebkitBorderRadius - // and the following would be incorrect: - // elem.style.webkitBorderRadius - - // Webkit ghosts their properties in lowercase but Opera & Moz do not. - // Microsoft uses a lowercase `ms` instead of the correct `Ms` in IE8+ - // erik.eae.net/archives/2008/03/10/21.48.10/ - - // More here: github.com/Modernizr/Modernizr/issues/issue/21 - omPrefixes = 'Webkit Moz O ms', - - cssomPrefixes = omPrefixes.split(' '), - - domPrefixes = omPrefixes.toLowerCase().split(' '), - /*>>domprefixes*/ - - /*>>ns*/ - ns = {'svg': 'http://www.w3.org/2000/svg'}, - /*>>ns*/ - - tests = {}, - inputs = {}, - attrs = {}, - - classes = [], - - slice = classes.slice, - - featureName, // used in testing loop - - - /*>>teststyles*/ - // Inject element with style element and some CSS rules - injectElementWithStyles = function( rule, callback, nodes, testnames ) { - - var style, ret, node, docOverflow, - div = document.createElement('div'), - // After page load injecting a fake body doesn't work so check if body exists - body = document.body, - // IE6 and 7 won't return offsetWidth or offsetHeight unless it's in the body element, so we fake it. - fakeBody = body || document.createElement('body'); - - if ( parseInt(nodes, 10) ) { - // In order not to give false positives we create a node for each test - // This also allows the method to scale for unspecified uses - while ( nodes-- ) { - node = document.createElement('div'); - node.id = testnames ? testnames[nodes] : mod + (nodes + 1); - div.appendChild(node); - } - } - - // '].join(''); - div.id = mod; - // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody. - // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270 - (body ? div : fakeBody).innerHTML += style; - fakeBody.appendChild(div); - if ( !body ) { - //avoid crashing IE8, if background image is used - fakeBody.style.background = ''; - //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible - fakeBody.style.overflow = 'hidden'; - docOverflow = docElement.style.overflow; - docElement.style.overflow = 'hidden'; - docElement.appendChild(fakeBody); - } - - ret = callback(div, rule); - // If this is done after page load we don't want to remove the body so check if body exists - if ( !body ) { - fakeBody.parentNode.removeChild(fakeBody); - docElement.style.overflow = docOverflow; - } else { - div.parentNode.removeChild(div); - } - - return !!ret; - - }, - /*>>teststyles*/ - - /*>>mq*/ - // adapted from matchMedia polyfill - // by Scott Jehl and Paul Irish - // gist.github.com/786768 - testMediaQuery = function( mq ) { - - var matchMedia = window.matchMedia || window.msMatchMedia; - if ( matchMedia ) { - return matchMedia(mq) && matchMedia(mq).matches || false; - } - - var bool; - - injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) { - bool = (window.getComputedStyle ? - getComputedStyle(node, null) : - node.currentStyle)['position'] == 'absolute'; - }); - - return bool; - - }, - /*>>mq*/ - - - /*>>hasevent*/ - // - // isEventSupported determines if a given element supports the given event - // kangax.github.com/iseventsupported/ - // - // The following results are known incorrects: - // Modernizr.hasEvent("webkitTransitionEnd", elem) // false negative - // Modernizr.hasEvent("textInput") // in Webkit. github.com/Modernizr/Modernizr/issues/333 - // ... - isEventSupported = (function() { - - var TAGNAMES = { - 'select': 'input', 'change': 'input', - 'submit': 'form', 'reset': 'form', - 'error': 'img', 'load': 'img', 'abort': 'img' - }; - - function isEventSupported( eventName, element ) { - - element = element || document.createElement(TAGNAMES[eventName] || 'div'); - eventName = 'on' + eventName; - - // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those - var isSupported = eventName in element; - - if ( !isSupported ) { - // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element - if ( !element.setAttribute ) { - element = document.createElement('div'); - } - if ( element.setAttribute && element.removeAttribute ) { - element.setAttribute(eventName, ''); - isSupported = is(element[eventName], 'function'); - - // If property was created, "remove it" (by setting value to `undefined`) - if ( !is(element[eventName], 'undefined') ) { - element[eventName] = undefined; - } - element.removeAttribute(eventName); - } - } - - element = null; - return isSupported; - } - return isEventSupported; - })(), - /*>>hasevent*/ - - // TODO :: Add flag for hasownprop ? didn't last time - - // hasOwnProperty shim by kangax needed for Safari 2.0 support - _hasOwnProperty = ({}).hasOwnProperty, hasOwnProp; - - if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) { - hasOwnProp = function (object, property) { - return _hasOwnProperty.call(object, property); - }; - } - else { - hasOwnProp = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */ - return ((property in object) && is(object.constructor.prototype[property], 'undefined')); - }; - } - - // Adapted from ES5-shim https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js - // es5.github.com/#x15.3.4.5 - - if (!Function.prototype.bind) { - Function.prototype.bind = function bind(that) { - - var target = this; - - if (typeof target != "function") { - throw new TypeError(); - } - - var args = slice.call(arguments, 1), - bound = function () { - - if (this instanceof bound) { - - var F = function(){}; - F.prototype = target.prototype; - var self = new F(); - - var result = target.apply( - self, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return self; - - } else { - - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - - } - - }; - - return bound; - }; - } - - /** - * setCss applies given styles to the Modernizr DOM node. - */ - function setCss( str ) { - mStyle.cssText = str; - } - - /** - * setCssAll extrapolates all vendor-specific css strings. - */ - function setCssAll( str1, str2 ) { - return setCss(prefixes.join(str1 + ';') + ( str2 || '' )); - } - - /** - * is returns a boolean for if typeof obj is exactly type. - */ - function is( obj, type ) { - return typeof obj === type; - } - - /** - * contains returns a boolean for if substr is found within str. - */ - function contains( str, substr ) { - return !!~('' + str).indexOf(substr); - } - - /*>>testprop*/ - - // testProps is a generic CSS / DOM property test. - - // In testing support for a given CSS property, it's legit to test: - // `elem.style[styleName] !== undefined` - // If the property is supported it will return an empty string, - // if unsupported it will return undefined. - - // We'll take advantage of this quick test and skip setting a style - // on our modernizr element, but instead just testing undefined vs - // empty string. - - // Because the testing of the CSS property names (with "-", as - // opposed to the camelCase DOM properties) is non-portable and - // non-standard but works in WebKit and IE (but not Gecko or Opera), - // we explicitly reject properties with dashes so that authors - // developing in WebKit or IE first don't end up with - // browser-specific content by accident. - - function testProps( props, prefixed ) { - for ( var i in props ) { - var prop = props[i]; - if ( !contains(prop, "-") && mStyle[prop] !== undefined ) { - return prefixed == 'pfx' ? prop : true; - } - } - return false; - } - /*>>testprop*/ - - // TODO :: add testDOMProps - /** - * testDOMProps is a generic DOM property test; if a browser supports - * a certain property, it won't return undefined for it. - */ - function testDOMProps( props, obj, elem ) { - for ( var i in props ) { - var item = obj[props[i]]; - if ( item !== undefined) { - - // return the property name as a string - if (elem === false) return props[i]; - - // let's bind a function - if (is(item, 'function')){ - // default to autobind unless override - return item.bind(elem || obj); - } - - // return the unbound function or obj or value - return item; - } - } - return false; - } - - /*>>testallprops*/ - /** - * testPropsAll tests a list of DOM properties we want to check against. - * We specify literally ALL possible (known and/or likely) properties on - * the element including the non-vendor prefixed one, for forward- - * compatibility. - */ - function testPropsAll( prop, prefixed, elem ) { - - var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1), - props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' '); - - // did they call .prefixed('boxSizing') or are we just testing a prop? - if(is(prefixed, "string") || is(prefixed, "undefined")) { - return testProps(props, prefixed); - - // otherwise, they called .prefixed('requestAnimationFrame', window[, elem]) - } else { - props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' '); - return testDOMProps(props, prefixed, elem); - } - } - /*>>testallprops*/ - - - /** - * Tests - * ----- - */ - - // The *new* flexbox - // dev.w3.org/csswg/css3-flexbox - - tests['flexbox'] = function() { - return testPropsAll('flexWrap'); - }; - - // The *old* flexbox - // www.w3.org/TR/2009/WD-css3-flexbox-20090723/ - - tests['flexboxlegacy'] = function() { - return testPropsAll('boxDirection'); - }; - - // On the S60 and BB Storm, getContext exists, but always returns undefined - // so we actually have to call getContext() to verify - // github.com/Modernizr/Modernizr/issues/issue/97/ - - tests['canvas'] = function() { - var elem = document.createElement('canvas'); - return !!(elem.getContext && elem.getContext('2d')); - }; - - tests['canvastext'] = function() { - return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function')); - }; - - // webk.it/70117 is tracking a legit WebGL feature detect proposal - - // We do a soft detect which may false positive in order to avoid - // an expensive context creation: bugzil.la/732441 - - tests['webgl'] = function() { - return !!window.WebGLRenderingContext; - }; - - /* - * The Modernizr.touch test only indicates if the browser supports - * touch events, which does not necessarily reflect a touchscreen - * device, as evidenced by tablets running Windows 7 or, alas, - * the Palm Pre / WebOS (touch) phones. - * - * Additionally, Chrome (desktop) used to lie about its support on this, - * but that has since been rectified: crbug.com/36415 - * - * We also test for Firefox 4 Multitouch Support. - * - * For more info, see: modernizr.github.com/Modernizr/touch.html - */ - - tests['touch'] = function() { - var bool; - - if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) { - bool = true; - } else { - injectElementWithStyles(['@media (',prefixes.join('touch-enabled),('),mod,')','{#modernizr{top:9px;position:absolute}}'].join(''), function( node ) { - bool = node.offsetTop === 9; - }); - } - - return bool; - }; - - - // geolocation is often considered a trivial feature detect... - // Turns out, it's quite tricky to get right: - // - // Using !!navigator.geolocation does two things we don't want. It: - // 1. Leaks memory in IE9: github.com/Modernizr/Modernizr/issues/513 - // 2. Disables page caching in WebKit: webk.it/43956 - // - // Meanwhile, in Firefox < 8, an about:config setting could expose - // a false positive that would throw an exception: bugzil.la/688158 - - tests['geolocation'] = function() { - return 'geolocation' in navigator; - }; - - - tests['postmessage'] = function() { - return !!window.postMessage; - }; - - - // Chrome incognito mode used to throw an exception when using openDatabase - // It doesn't anymore. - tests['websqldatabase'] = function() { - return !!window.openDatabase; - }; - - // Vendors had inconsistent prefixing with the experimental Indexed DB: - // - Webkit's implementation is accessible through webkitIndexedDB - // - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB - // For speed, we don't test the legacy (and beta-only) indexedDB - tests['indexedDB'] = function() { - return !!testPropsAll("indexedDB", window); - }; - - // documentMode logic from YUI to filter out IE8 Compat Mode - // which false positives. - tests['hashchange'] = function() { - return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7); - }; - - // Per 1.6: - // This used to be Modernizr.historymanagement but the longer - // name has been deprecated in favor of a shorter and property-matching one. - // The old API is still available in 1.6, but as of 2.0 will throw a warning, - // and in the first release thereafter disappear entirely. - tests['history'] = function() { - return !!(window.history && history.pushState); - }; - - tests['draganddrop'] = function() { - var div = document.createElement('div'); - return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div); - }; - - // FF3.6 was EOL'ed on 4/24/12, but the ESR version of FF10 - // will be supported until FF19 (2/12/13), at which time, ESR becomes FF17. - // FF10 still uses prefixes, so check for it until then. - // for more ESR info, see: mozilla.org/en-US/firefox/organizations/faq/ - tests['websockets'] = function() { - return 'WebSocket' in window || 'MozWebSocket' in window; - }; - - - // css-tricks.com/rgba-browser-support/ - tests['rgba'] = function() { - // Set an rgba() color and check the returned value - - setCss('background-color:rgba(150,255,150,.5)'); - - return contains(mStyle.backgroundColor, 'rgba'); - }; - - tests['hsla'] = function() { - // Same as rgba(), in fact, browsers re-map hsla() to rgba() internally, - // except IE9 who retains it as hsla - - setCss('background-color:hsla(120,40%,100%,.5)'); - - return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla'); - }; - - tests['multiplebgs'] = function() { - // Setting multiple images AND a color on the background shorthand property - // and then querying the style.background property value for the number of - // occurrences of "url(" is a reliable method for detecting ACTUAL support for this! - - setCss('background:url(https://),url(https://),red url(https://)'); - - // If the UA supports multiple backgrounds, there should be three occurrences - // of the string "url(" in the return value for elemStyle.background - - return (/(url\s*\(.*?){3}/).test(mStyle.background); - }; - - - - // this will false positive in Opera Mini - // github.com/Modernizr/Modernizr/issues/396 - - tests['backgroundsize'] = function() { - return testPropsAll('backgroundSize'); - }; - - tests['borderimage'] = function() { - return testPropsAll('borderImage'); - }; - - - // Super comprehensive table about all the unique implementations of - // border-radius: muddledramblings.com/table-of-css3-border-radius-compliance - - tests['borderradius'] = function() { - return testPropsAll('borderRadius'); - }; - - // WebOS unfortunately false positives on this test. - tests['boxshadow'] = function() { - return testPropsAll('boxShadow'); - }; - - // FF3.0 will false positive on this test - tests['textshadow'] = function() { - return document.createElement('div').style.textShadow === ''; - }; - - - tests['opacity'] = function() { - // Browsers that actually have CSS Opacity implemented have done so - // according to spec, which means their return values are within the - // range of [0.0,1.0] - including the leading zero. - - setCssAll('opacity:.55'); - - // The non-literal . in this regex is intentional: - // German Chrome returns this value as 0,55 - // github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632 - return (/^0.55$/).test(mStyle.opacity); - }; - - - // Note, Android < 4 will pass this test, but can only animate - // a single property at a time - // goo.gl/v3V4Gp - tests['cssanimations'] = function() { - return testPropsAll('animationName'); - }; - - - tests['csscolumns'] = function() { - return testPropsAll('columnCount'); - }; - - - tests['cssgradients'] = function() { - /** - * For CSS Gradients syntax, please see: - * webkit.org/blog/175/introducing-css-gradients/ - * developer.mozilla.org/en/CSS/-moz-linear-gradient - * developer.mozilla.org/en/CSS/-moz-radial-gradient - * dev.w3.org/csswg/css3-images/#gradients- - */ - - var str1 = 'background-image:', - str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));', - str3 = 'linear-gradient(left top,#9f9, white);'; - - setCss( - // legacy webkit syntax (FIXME: remove when syntax not in use anymore) - (str1 + '-webkit- '.split(' ').join(str2 + str1) + - // standard syntax // trailing 'background-image:' - prefixes.join(str3 + str1)).slice(0, -str1.length) - ); - - return contains(mStyle.backgroundImage, 'gradient'); - }; - - - tests['cssreflections'] = function() { - return testPropsAll('boxReflect'); - }; - - - tests['csstransforms'] = function() { - return !!testPropsAll('transform'); - }; - - - tests['csstransforms3d'] = function() { - - var ret = !!testPropsAll('perspective'); - - // Webkit's 3D transforms are passed off to the browser's own graphics renderer. - // It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in - // some conditions. As a result, Webkit typically recognizes the syntax but - // will sometimes throw a false positive, thus we must do a more thorough check: - if ( ret && 'webkitPerspective' in docElement.style ) { - - // Webkit allows this media query to succeed only if the feature is enabled. - // `@media (transform-3d),(-webkit-transform-3d){ ... }` - injectElementWithStyles('@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}', function( node, rule ) { - ret = node.offsetLeft === 9 && node.offsetHeight === 3; - }); - } - return ret; - }; - - - tests['csstransitions'] = function() { - return testPropsAll('transition'); - }; - - - /*>>fontface*/ - // @font-face detection routine by Diego Perini - // javascript.nwbox.com/CSSSupport/ - - // false positives: - // WebOS github.com/Modernizr/Modernizr/issues/342 - // WP7 github.com/Modernizr/Modernizr/issues/538 - tests['fontface'] = function() { - var bool; - - injectElementWithStyles('@font-face {font-family:"font";src:url("https://")}', function( node, rule ) { - var style = document.getElementById('smodernizr'), - sheet = style.sheet || style.styleSheet, - cssText = sheet ? (sheet.cssRules && sheet.cssRules[0] ? sheet.cssRules[0].cssText : sheet.cssText || '') : ''; - - bool = /src/i.test(cssText) && cssText.indexOf(rule.split(' ')[0]) === 0; - }); - - return bool; - }; - /*>>fontface*/ - - // CSS generated content detection - tests['generatedcontent'] = function() { - var bool; - - injectElementWithStyles(['#',mod,'{font:0/0 a}#',mod,':after{content:"',smile,'";visibility:hidden;font:3px/1 a}'].join(''), function( node ) { - bool = node.offsetHeight >= 3; - }); - - return bool; - }; - - - - // These tests evaluate support of the video/audio elements, as well as - // testing what types of content they support. - // - // We're using the Boolean constructor here, so that we can extend the value - // e.g. Modernizr.video // true - // Modernizr.video.ogg // 'probably' - // - // Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845 - // thx to NielsLeenheer and zcorpan - - // Note: in some older browsers, "no" was a return value instead of empty string. - // It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2 - // It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5 - - tests['video'] = function() { - var elem = document.createElement('video'), - bool = false; - - // IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224 - try { - if ( bool = !!elem.canPlayType ) { - bool = new Boolean(bool); - bool.ogg = elem.canPlayType('video/ogg; codecs="theora"') .replace(/^no$/,''); - - // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546 - bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"') .replace(/^no$/,''); - - bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,''); - } - - } catch(e) { } - - return bool; - }; - - tests['audio'] = function() { - var elem = document.createElement('audio'), - bool = false; - - try { - if ( bool = !!elem.canPlayType ) { - bool = new Boolean(bool); - bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,''); - bool.mp3 = elem.canPlayType('audio/mpeg;') .replace(/^no$/,''); - - // Mimetypes accepted: - // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements - // bit.ly/iphoneoscodecs - bool.wav = elem.canPlayType('audio/wav; codecs="1"') .replace(/^no$/,''); - bool.m4a = ( elem.canPlayType('audio/x-m4a;') || - elem.canPlayType('audio/aac;')) .replace(/^no$/,''); - } - } catch(e) { } - - return bool; - }; - - - // In FF4, if disabled, window.localStorage should === null. - - // Normally, we could not test that directly and need to do a - // `('localStorage' in window) && ` test first because otherwise Firefox will - // throw bugzil.la/365772 if cookies are disabled - - // Also in iOS5 Private Browsing mode, attempting to use localStorage.setItem - // will throw the exception: - // QUOTA_EXCEEDED_ERRROR DOM Exception 22. - // Peculiarly, getItem and removeItem calls do not throw. - - // Because we are forced to try/catch this, we'll go aggressive. - - // Just FWIW: IE8 Compat mode supports these features completely: - // www.quirksmode.org/dom/html5.html - // But IE8 doesn't support either with local files - - tests['localstorage'] = function() { - try { - localStorage.setItem(mod, mod); - localStorage.removeItem(mod); - return true; - } catch(e) { - return false; - } - }; - - tests['sessionstorage'] = function() { - try { - sessionStorage.setItem(mod, mod); - sessionStorage.removeItem(mod); - return true; - } catch(e) { - return false; - } - }; - - - tests['webworkers'] = function() { - return !!window.Worker; - }; - - - tests['applicationcache'] = function() { - return !!window.applicationCache; - }; - - - // Thanks to Erik Dahlstrom - tests['svg'] = function() { - return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect; - }; - - // specifically for SVG inline in HTML, not within XHTML - // test page: paulirish.com/demo/inline-svg - tests['inlinesvg'] = function() { - var div = document.createElement('div'); - div.innerHTML = ''; - return (div.firstChild && div.firstChild.namespaceURI) == ns.svg; - }; - - // SVG SMIL animation - tests['smil'] = function() { - return !!document.createElementNS && /SVGAnimate/.test(toString.call(document.createElementNS(ns.svg, 'animate'))); - }; - - // This test is only for clip paths in SVG proper, not clip paths on HTML content - // demo: srufaculty.sru.edu/david.dailey/svg/newstuff/clipPath4.svg - - // However read the comments to dig into applying SVG clippaths to HTML content here: - // github.com/Modernizr/Modernizr/issues/213#issuecomment-1149491 - tests['svgclippaths'] = function() { - return !!document.createElementNS && /SVGClipPath/.test(toString.call(document.createElementNS(ns.svg, 'clipPath'))); - }; - - /*>>webforms*/ - // input features and input types go directly onto the ret object, bypassing the tests loop. - // Hold this guy to execute in a moment. - function webforms() { - /*>>input*/ - // Run through HTML5's new input attributes to see if the UA understands any. - // We're using f which is the element created early on - // Mike Taylr has created a comprehensive resource for testing these attributes - // when applied to all input types: - // miketaylr.com/code/input-type-attr.html - // spec: www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary - - // Only input placeholder is tested while textarea's placeholder is not. - // Currently Safari 4 and Opera 11 have support only for the input placeholder - // Both tests are available in feature-detects/forms-placeholder.js - Modernizr['input'] = (function( props ) { - for ( var i = 0, len = props.length; i < len; i++ ) { - attrs[ props[i] ] = !!(props[i] in inputElem); - } - if (attrs.list){ - // safari false positive's on datalist: webk.it/74252 - // see also github.com/Modernizr/Modernizr/issues/146 - attrs.list = !!(document.createElement('datalist') && window.HTMLDataListElement); - } - return attrs; - })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' ')); - /*>>input*/ - - /*>>inputtypes*/ - // Run through HTML5's new input types to see if the UA understands any. - // This is put behind the tests runloop because it doesn't return a - // true/false like all the other tests; instead, it returns an object - // containing each input type with its corresponding true/false value - - // Big thanks to @miketaylr for the html5 forms expertise. miketaylr.com/ - Modernizr['inputtypes'] = (function(props) { - - for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) { - - inputElem.setAttribute('type', inputElemType = props[i]); - bool = inputElem.type !== 'text'; - - // We first check to see if the type we give it sticks.. - // If the type does, we feed it a textual value, which shouldn't be valid. - // If the value doesn't stick, we know there's input sanitization which infers a custom UI - if ( bool ) { - - inputElem.value = smile; - inputElem.style.cssText = 'position:absolute;visibility:hidden;'; - - if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) { - - docElement.appendChild(inputElem); - defaultView = document.defaultView; - - // Safari 2-4 allows the smiley as a value, despite making a slider - bool = defaultView.getComputedStyle && - defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' && - // Mobile android web browser has false positive, so must - // check the height to see if the widget is actually there. - (inputElem.offsetHeight !== 0); - - docElement.removeChild(inputElem); - - } else if ( /^(search|tel)$/.test(inputElemType) ){ - // Spec doesn't define any special parsing or detectable UI - // behaviors so we pass these through as true - - // Interestingly, opera fails the earlier test, so it doesn't - // even make it here. - - } else if ( /^(url|email)$/.test(inputElemType) ) { - // Real url and email support comes with prebaked validation. - bool = inputElem.checkValidity && inputElem.checkValidity() === false; - - } else { - // If the upgraded input compontent rejects the :) text, we got a winner - bool = inputElem.value != smile; - } - } - - inputs[ props[i] ] = !!bool; - } - return inputs; - })('search tel url email datetime date month week time datetime-local number range color'.split(' ')); - /*>>inputtypes*/ - } - /*>>webforms*/ - - - // End of test definitions - // ----------------------- - - - - // Run through all tests and detect their support in the current UA. - // todo: hypothetically we could be doing an array of tests and use a basic loop here. - for ( var feature in tests ) { - if ( hasOwnProp(tests, feature) ) { - // run the test, throw the return value into the Modernizr, - // then based on that boolean, define an appropriate className - // and push it into an array of classes we'll join later. - featureName = feature.toLowerCase(); - Modernizr[featureName] = tests[feature](); - - classes.push((Modernizr[featureName] ? '' : 'no-') + featureName); - } - } - - /*>>webforms*/ - // input tests need to run. - Modernizr.input || webforms(); - /*>>webforms*/ - - - /** - * addTest allows the user to define their own feature tests - * the result will be added onto the Modernizr object, - * as well as an appropriate className set on the html element - * - * @param feature - String naming the feature - * @param test - Function returning true if feature is supported, false if not - */ - Modernizr.addTest = function ( feature, test ) { - if ( typeof feature == 'object' ) { - for ( var key in feature ) { - if ( hasOwnProp( feature, key ) ) { - Modernizr.addTest( key, feature[ key ] ); - } - } - } else { - - feature = feature.toLowerCase(); - - if ( Modernizr[feature] !== undefined ) { - // we're going to quit if you're trying to overwrite an existing test - // if we were to allow it, we'd do this: - // var re = new RegExp("\\b(no-)?" + feature + "\\b"); - // docElement.className = docElement.className.replace( re, '' ); - // but, no rly, stuff 'em. - return Modernizr; - } - - test = typeof test == 'function' ? test() : test; - - if (typeof enableClasses !== "undefined" && enableClasses) { - docElement.className += ' ' + (test ? '' : 'no-') + feature; - } - Modernizr[feature] = test; - - } - - return Modernizr; // allow chaining. - }; - - - // Reset modElem.cssText to nothing to reduce memory footprint. - setCss(''); - modElem = inputElem = null; - - /*>>shiv*/ - /** - * @preserve HTML5 Shiv prev3.7.1 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed - */ - ;(function(window, document) { - /*jshint evil:true */ - /** version */ - var version = '3.7.0'; - - /** Preset options */ - var options = window.html5 || {}; - - /** Used to skip problem elements */ - var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i; - - /** Not all elements can be cloned in IE **/ - var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i; - - /** Detect whether the browser supports default html5 styles */ - var supportsHtml5Styles; - - /** Name of the expando, to work with multiple documents or to re-shiv one document */ - var expando = '_html5shiv'; - - /** The id for the the documents expando */ - var expanID = 0; - - /** Cached data for each document */ - var expandoData = {}; - - /** Detect whether the browser supports unknown elements */ - var supportsUnknownElements; - - (function() { - try { - var a = document.createElement('a'); - a.innerHTML = ''; - //if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles - supportsHtml5Styles = ('hidden' in a); - - supportsUnknownElements = a.childNodes.length == 1 || (function() { - // assign a false positive if unable to shiv - (document.createElement)('a'); - var frag = document.createDocumentFragment(); - return ( - typeof frag.cloneNode == 'undefined' || - typeof frag.createDocumentFragment == 'undefined' || - typeof frag.createElement == 'undefined' - ); - }()); - } catch(e) { - // assign a false positive if detection fails => unable to shiv - supportsHtml5Styles = true; - supportsUnknownElements = true; - } - - }()); - - /*--------------------------------------------------------------------------*/ - - /** - * Creates a style sheet with the given CSS text and adds it to the document. - * @private - * @param {Document} ownerDocument The document. - * @param {String} cssText The CSS text. - * @returns {StyleSheet} The style element. - */ - function addStyleSheet(ownerDocument, cssText) { - var p = ownerDocument.createElement('p'), - parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement; - - p.innerHTML = 'x'; - return parent.insertBefore(p.lastChild, parent.firstChild); - } - - /** - * Returns the value of `html5.elements` as an array. - * @private - * @returns {Array} An array of shived element node names. - */ - function getElements() { - var elements = html5.elements; - return typeof elements == 'string' ? elements.split(' ') : elements; - } - - /** - * Returns the data associated to the given document - * @private - * @param {Document} ownerDocument The document. - * @returns {Object} An object of data. - */ - function getExpandoData(ownerDocument) { - var data = expandoData[ownerDocument[expando]]; - if (!data) { - data = {}; - expanID++; - ownerDocument[expando] = expanID; - expandoData[expanID] = data; - } - return data; - } - - /** - * returns a shived element for the given nodeName and document - * @memberOf html5 - * @param {String} nodeName name of the element - * @param {Document} ownerDocument The context document. - * @returns {Object} The shived element. - */ - function createElement(nodeName, ownerDocument, data){ - if (!ownerDocument) { - ownerDocument = document; - } - if(supportsUnknownElements){ - return ownerDocument.createElement(nodeName); - } - if (!data) { - data = getExpandoData(ownerDocument); - } - var node; - - if (data.cache[nodeName]) { - node = data.cache[nodeName].cloneNode(); - } else if (saveClones.test(nodeName)) { - node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode(); - } else { - node = data.createElem(nodeName); - } - - // Avoid adding some elements to fragments in IE < 9 because - // * Attributes like `name` or `type` cannot be set/changed once an element - // is inserted into a document/fragment - // * Link elements with `src` attributes that are inaccessible, as with - // a 403 response, will cause the tab/window to crash - // * Script elements appended to fragments will execute when their `src` - // or `text` property is set - return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node; - } - - /** - * returns a shived DocumentFragment for the given document - * @memberOf html5 - * @param {Document} ownerDocument The context document. - * @returns {Object} The shived DocumentFragment. - */ - function createDocumentFragment(ownerDocument, data){ - if (!ownerDocument) { - ownerDocument = document; - } - if(supportsUnknownElements){ - return ownerDocument.createDocumentFragment(); - } - data = data || getExpandoData(ownerDocument); - var clone = data.frag.cloneNode(), - i = 0, - elems = getElements(), - l = elems.length; - for(;i>shiv*/ - - // Assign private properties to the return object with prefix - Modernizr._version = version; - - // expose these for the plugin API. Look in the source for how to join() them against your input - /*>>prefixes*/ - Modernizr._prefixes = prefixes; - /*>>prefixes*/ - /*>>domprefixes*/ - Modernizr._domPrefixes = domPrefixes; - Modernizr._cssomPrefixes = cssomPrefixes; - /*>>domprefixes*/ - - /*>>mq*/ - // Modernizr.mq tests a given media query, live against the current state of the window - // A few important notes: - // * If a browser does not support media queries at all (eg. oldIE) the mq() will always return false - // * A max-width or orientation query will be evaluated against the current state, which may change later. - // * You must specify values. Eg. If you are testing support for the min-width media query use: - // Modernizr.mq('(min-width:0)') - // usage: - // Modernizr.mq('only screen and (max-width:768)') - Modernizr.mq = testMediaQuery; - /*>>mq*/ - - /*>>hasevent*/ - // Modernizr.hasEvent() detects support for a given event, with an optional element to test on - // Modernizr.hasEvent('gesturestart', elem) - Modernizr.hasEvent = isEventSupported; - /*>>hasevent*/ - - /*>>testprop*/ - // Modernizr.testProp() investigates whether a given style property is recognized - // Note that the property names must be provided in the camelCase variant. - // Modernizr.testProp('pointerEvents') - Modernizr.testProp = function(prop){ - return testProps([prop]); - }; - /*>>testprop*/ - - /*>>testallprops*/ - // Modernizr.testAllProps() investigates whether a given style property, - // or any of its vendor-prefixed variants, is recognized - // Note that the property names must be provided in the camelCase variant. - // Modernizr.testAllProps('boxSizing') - Modernizr.testAllProps = testPropsAll; - /*>>testallprops*/ - - - /*>>teststyles*/ - // Modernizr.testStyles() allows you to add custom styles to the document and test an element afterwards - // Modernizr.testStyles('#modernizr { position:absolute }', function(elem, rule){ ... }) - Modernizr.testStyles = injectElementWithStyles; - /*>>teststyles*/ - - - /*>>prefixed*/ - // Modernizr.prefixed() returns the prefixed or nonprefixed property name variant of your input - // Modernizr.prefixed('boxSizing') // 'MozBoxSizing' - - // Properties must be passed as dom-style camelcase, rather than `box-sizing` hypentated style. - // Return values will also be the camelCase variant, if you need to translate that to hypenated style use: - // - // str.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-'); - - // If you're trying to ascertain which transition end event to bind to, you might do something like... - // - // var transEndEventNames = { - // 'WebkitTransition' : 'webkitTransitionEnd', - // 'MozTransition' : 'transitionend', - // 'OTransition' : 'oTransitionEnd', - // 'msTransition' : 'MSTransitionEnd', - // 'transition' : 'transitionend' - // }, - // transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ]; - - Modernizr.prefixed = function(prop, obj, elem){ - if(!obj) { - return testPropsAll(prop, 'pfx'); - } else { - // Testing DOM property e.g. Modernizr.prefixed('requestAnimationFrame', window) // 'mozRequestAnimationFrame' - return testPropsAll(prop, obj, elem); - } - }; - /*>>prefixed*/ - - - /*>>cssclasses*/ - // Remove "no-js" class from element, if it exists: - docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') + - - // Add the new classes to the element. - (enableClasses ? ' js ' + classes.join(' ') : ''); - /*>>cssclasses*/ - - return Modernizr; - -})(this, this.document); diff --git a/third_party/phantomjs/examples/module.js b/third_party/phantomjs/examples/module.js deleted file mode 100644 index c3826e9509a..00000000000 --- a/third_party/phantomjs/examples/module.js +++ /dev/null @@ -1,5 +0,0 @@ -"use strict"; -var universe = require('./universe'); -universe.start(); -console.log('The answer is ' + universe.answer); -phantom.exit(); diff --git a/third_party/phantomjs/examples/netlog.js b/third_party/phantomjs/examples/netlog.js deleted file mode 100644 index 0418c23f7ca..00000000000 --- a/third_party/phantomjs/examples/netlog.js +++ /dev/null @@ -1,26 +0,0 @@ -"use strict"; -var page = require('webpage').create(), - system = require('system'), - address; - -if (system.args.length === 1) { - console.log('Usage: netlog.js '); - phantom.exit(1); -} else { - address = system.args[1]; - - page.onResourceRequested = function (req) { - console.log('requested: ' + JSON.stringify(req, undefined, 4)); - }; - - page.onResourceReceived = function (res) { - console.log('received: ' + JSON.stringify(res, undefined, 4)); - }; - - page.open(address, function (status) { - if (status !== 'success') { - console.log('FAIL to load the address'); - } - phantom.exit(); - }); -} diff --git a/third_party/phantomjs/examples/netsniff.js b/third_party/phantomjs/examples/netsniff.js deleted file mode 100644 index 4655a364312..00000000000 --- a/third_party/phantomjs/examples/netsniff.js +++ /dev/null @@ -1,144 +0,0 @@ -"use strict"; -if (!Date.prototype.toISOString) { - Date.prototype.toISOString = function () { - function pad(n) { return n < 10 ? '0' + n : n; } - function ms(n) { return n < 10 ? '00'+ n : n < 100 ? '0' + n : n } - return this.getFullYear() + '-' + - pad(this.getMonth() + 1) + '-' + - pad(this.getDate()) + 'T' + - pad(this.getHours()) + ':' + - pad(this.getMinutes()) + ':' + - pad(this.getSeconds()) + '.' + - ms(this.getMilliseconds()) + 'Z'; - } -} - -function createHAR(address, title, startTime, resources) -{ - var entries = []; - - resources.forEach(function (resource) { - var request = resource.request, - startReply = resource.startReply, - endReply = resource.endReply; - - if (!request || !startReply || !endReply) { - return; - } - - // Exclude Data URI from HAR file because - // they aren't included in specification - if (request.url.match(/(^data:image\/.*)/i)) { - return; - } - - entries.push({ - startedDateTime: request.time.toISOString(), - time: endReply.time - request.time, - request: { - method: request.method, - url: request.url, - httpVersion: "HTTP/1.1", - cookies: [], - headers: request.headers, - queryString: [], - headersSize: -1, - bodySize: -1 - }, - response: { - status: endReply.status, - statusText: endReply.statusText, - httpVersion: "HTTP/1.1", - cookies: [], - headers: endReply.headers, - redirectURL: "", - headersSize: -1, - bodySize: startReply.bodySize, - content: { - size: startReply.bodySize, - mimeType: endReply.contentType - } - }, - cache: {}, - timings: { - blocked: 0, - dns: -1, - connect: -1, - send: 0, - wait: startReply.time - request.time, - receive: endReply.time - startReply.time, - ssl: -1 - }, - pageref: address - }); - }); - - return { - log: { - version: '1.2', - creator: { - name: "PhantomJS", - version: phantom.version.major + '.' + phantom.version.minor + - '.' + phantom.version.patch - }, - pages: [{ - startedDateTime: startTime.toISOString(), - id: address, - title: title, - pageTimings: { - onLoad: page.endTime - page.startTime - } - }], - entries: entries - } - }; -} - -var page = require('webpage').create(), - system = require('system'); - -if (system.args.length === 1) { - console.log('Usage: netsniff.js '); - phantom.exit(1); -} else { - - page.address = system.args[1]; - page.resources = []; - - page.onLoadStarted = function () { - page.startTime = new Date(); - }; - - page.onResourceRequested = function (req) { - page.resources[req.id] = { - request: req, - startReply: null, - endReply: null - }; - }; - - page.onResourceReceived = function (res) { - if (res.stage === 'start') { - page.resources[res.id].startReply = res; - } - if (res.stage === 'end') { - page.resources[res.id].endReply = res; - } - }; - - page.open(page.address, function (status) { - var har; - if (status !== 'success') { - console.log('FAIL to load the address'); - phantom.exit(1); - } else { - page.endTime = new Date(); - page.title = page.evaluate(function () { - return document.title; - }); - har = createHAR(page.address, page.title, page.startTime, page.resources); - console.log(JSON.stringify(har, undefined, 4)); - phantom.exit(); - } - }); -} diff --git a/third_party/phantomjs/examples/openurlwithproxy.js b/third_party/phantomjs/examples/openurlwithproxy.js deleted file mode 100644 index 30b6ffd42a7..00000000000 --- a/third_party/phantomjs/examples/openurlwithproxy.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; -var page = require('webpage').create(), - system = require('system'), - host, port, address; - -if (system.args.length < 4) { - console.log('Usage: openurlwithproxy.js '); - phantom.exit(1); -} else { - host = system.args[1]; - port = system.args[2]; - address = system.args[3]; - phantom.setProxy(host, port, 'manual', '', ''); - page.open(address, function (status) { - if (status !== 'success') { - console.log('FAIL to load the address "' + - address + '" using proxy "' + host + ':' + port + '"'); - } else { - console.log('Page title is ' + page.evaluate(function () { - return document.title; - })); - } - phantom.exit(); - }); -} diff --git a/third_party/phantomjs/examples/outputEncoding.js b/third_party/phantomjs/examples/outputEncoding.js deleted file mode 100644 index 82af2444c3f..00000000000 --- a/third_party/phantomjs/examples/outputEncoding.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -function helloWorld() { - console.log(phantom.outputEncoding + ": こんにちは、世界!"); -} - -console.log("Using default encoding..."); -helloWorld(); - -console.log("\nUsing other encodings..."); - -var encodings = ["euc-jp", "sjis", "utf8", "System"]; -for (var i = 0; i < encodings.length; i++) { - phantom.outputEncoding = encodings[i]; - helloWorld(); -} - -phantom.exit() diff --git a/third_party/phantomjs/examples/page_events.js b/third_party/phantomjs/examples/page_events.js deleted file mode 100644 index ef6563ec0c6..00000000000 --- a/third_party/phantomjs/examples/page_events.js +++ /dev/null @@ -1,147 +0,0 @@ -// The purpose of this is to show how and when events fire, considering 5 steps -// happening as follows: -// -// 1. Load URL -// 2. Load same URL, but adding an internal FRAGMENT to it -// 3. Click on an internal Link, that points to another internal FRAGMENT -// 4. Click on an external Link, that will send the page somewhere else -// 5. Close page -// -// Take particular care when going through the output, to understand when -// things happen (and in which order). Particularly, notice what DOESN'T -// happen during step 3. -// -// If invoked with "-v" it will print out the Page Resources as they are -// Requested and Received. -// -// NOTE.1: The "onConsoleMessage/onAlert/onPrompt/onConfirm" events are -// registered but not used here. This is left for you to have fun with. -// NOTE.2: This script is not here to teach you ANY JavaScript. It's aweful! -// NOTE.3: Main audience for this are people new to PhantomJS. - -"use strict"; -var sys = require("system"), - page = require("webpage").create(), - logResources = false, - step1url = "http://en.wikipedia.org/wiki/DOM_events", - step2url = "http://en.wikipedia.org/wiki/DOM_events#Event_flow"; - -if (sys.args.length > 1 && sys.args[1] === "-v") { - logResources = true; -} - -function printArgs() { - var i, ilen; - for (i = 0, ilen = arguments.length; i < ilen; ++i) { - console.log(" arguments[" + i + "] = " + JSON.stringify(arguments[i])); - } - console.log(""); -} - -//////////////////////////////////////////////////////////////////////////////// - -page.onInitialized = function() { - console.log("page.onInitialized"); - printArgs.apply(this, arguments); -}; -page.onLoadStarted = function() { - console.log("page.onLoadStarted"); - printArgs.apply(this, arguments); -}; -page.onLoadFinished = function() { - console.log("page.onLoadFinished"); - printArgs.apply(this, arguments); -}; -page.onUrlChanged = function() { - console.log("page.onUrlChanged"); - printArgs.apply(this, arguments); -}; -page.onNavigationRequested = function() { - console.log("page.onNavigationRequested"); - printArgs.apply(this, arguments); -}; -page.onRepaintRequested = function() { - console.log("page.onRepaintRequested"); - printArgs.apply(this, arguments); -}; - -if (logResources === true) { - page.onResourceRequested = function() { - console.log("page.onResourceRequested"); - printArgs.apply(this, arguments); - }; - page.onResourceReceived = function() { - console.log("page.onResourceReceived"); - printArgs.apply(this, arguments); - }; -} - -page.onClosing = function() { - console.log("page.onClosing"); - printArgs.apply(this, arguments); -}; - -// window.console.log(msg); -page.onConsoleMessage = function() { - console.log("page.onConsoleMessage"); - printArgs.apply(this, arguments); -}; - -// window.alert(msg); -page.onAlert = function() { - console.log("page.onAlert"); - printArgs.apply(this, arguments); -}; -// var confirmed = window.confirm(msg); -page.onConfirm = function() { - console.log("page.onConfirm"); - printArgs.apply(this, arguments); -}; -// var user_value = window.prompt(msg, default_value); -page.onPrompt = function() { - console.log("page.onPrompt"); - printArgs.apply(this, arguments); -}; - -//////////////////////////////////////////////////////////////////////////////// - -setTimeout(function() { - console.log(""); - console.log("### STEP 1: Load '" + step1url + "'"); - page.open(step1url); -}, 0); - -setTimeout(function() { - console.log(""); - console.log("### STEP 2: Load '" + step2url + "' (load same URL plus FRAGMENT)"); - page.open(step2url); -}, 5000); - -setTimeout(function() { - console.log(""); - console.log("### STEP 3: Click on page internal link (aka FRAGMENT)"); - page.evaluate(function() { - var ev = document.createEvent("MouseEvents"); - ev.initEvent("click", true, true); - document.querySelector("a[href='#Event_object']").dispatchEvent(ev); - }); -}, 10000); - -setTimeout(function() { - console.log(""); - console.log("### STEP 4: Click on page external link"); - page.evaluate(function() { - var ev = document.createEvent("MouseEvents"); - ev.initEvent("click", true, true); - document.querySelector("a[title='JavaScript']").dispatchEvent(ev); - }); -}, 15000); - -setTimeout(function() { - console.log(""); - console.log("### STEP 5: Close page and shutdown (with a delay)"); - page.close(); - setTimeout(function(){ - phantom.exit(); - }, 100); -}, 20000); diff --git a/third_party/phantomjs/examples/pagecallback.js b/third_party/phantomjs/examples/pagecallback.js deleted file mode 100644 index a14b57e8ce3..00000000000 --- a/third_party/phantomjs/examples/pagecallback.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -var p = require("webpage").create(); - -p.onConsoleMessage = function(msg) { console.log(msg); }; - -// Calls to "callPhantom" within the page 'p' arrive here -p.onCallback = function(msg) { - console.log("Received by the 'phantom' main context: "+msg); - return "Hello there, I'm coming to you from the 'phantom' context instead"; -}; - -p.evaluate(function() { - // Return-value of the "onCallback" handler arrive here - var callbackResponse = window.callPhantom("Hello, I'm coming to you from the 'page' context"); - console.log("Received by the 'page' context: "+callbackResponse); -}); - -phantom.exit(); diff --git a/third_party/phantomjs/examples/phantomwebintro.js b/third_party/phantomjs/examples/phantomwebintro.js deleted file mode 100644 index 6cb4e46d87c..00000000000 --- a/third_party/phantomjs/examples/phantomwebintro.js +++ /dev/null @@ -1,21 +0,0 @@ -// Read the Phantom webpage '#intro' element text using jQuery and "includeJs" - -"use strict"; -var page = require('webpage').create(); - -page.onConsoleMessage = function(msg) { - console.log(msg); -}; - -page.open("http://phantomjs.org/", function(status) { - if (status === "success") { - page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() { - page.evaluate(function() { - console.log("$(\".explanation\").text() -> " + $(".explanation").text()); - }); - phantom.exit(0); - }); - } else { - phantom.exit(1); - } -}); diff --git a/third_party/phantomjs/examples/post.js b/third_party/phantomjs/examples/post.js deleted file mode 100644 index 4b998b82a91..00000000000 --- a/third_party/phantomjs/examples/post.js +++ /dev/null @@ -1,15 +0,0 @@ -// Example using HTTP POST operation - -"use strict"; -var page = require('webpage').create(), - server = 'http://posttestserver.com/post.php?dump', - data = 'universe=expanding&answer=42'; - -page.open(server, 'post', data, function (status) { - if (status !== 'success') { - console.log('Unable to post!'); - } else { - console.log(page.content); - } - phantom.exit(); -}); diff --git a/third_party/phantomjs/examples/postjson.js b/third_party/phantomjs/examples/postjson.js deleted file mode 100644 index b02f4303783..00000000000 --- a/third_party/phantomjs/examples/postjson.js +++ /dev/null @@ -1,19 +0,0 @@ -// Example using HTTP POST operation - -"use strict"; -var page = require('webpage').create(), - server = 'http://posttestserver.com/post.php?dump', - data = '{"universe": "expanding", "answer": 42}'; - -var headers = { - "Content-Type": "application/json" -} - -page.open(server, 'post', data, headers, function (status) { - if (status !== 'success') { - console.log('Unable to post!'); - } else { - console.log(page.content); - } - phantom.exit(); -}); diff --git a/third_party/phantomjs/examples/postserver.js b/third_party/phantomjs/examples/postserver.js deleted file mode 100644 index e854701b28e..00000000000 --- a/third_party/phantomjs/examples/postserver.js +++ /dev/null @@ -1,35 +0,0 @@ -// Example using HTTP POST operation - -"use strict"; -var page = require('webpage').create(), - server = require('webserver').create(), - system = require('system'), - data = 'universe=expanding&answer=42'; - -if (system.args.length !== 2) { - console.log('Usage: postserver.js '); - phantom.exit(1); -} - -var port = system.args[1]; - -service = server.listen(port, function (request, response) { - console.log('Request received at ' + new Date()); - - response.statusCode = 200; - response.headers = { - 'Cache': 'no-cache', - 'Content-Type': 'text/plain;charset=utf-8' - }; - response.write(JSON.stringify(request, null, 4)); - response.close(); -}); - -page.open('http://localhost:' + port + '/', 'post', data, function (status) { - if (status !== 'success') { - console.log('Unable to post!'); - } else { - console.log(page.plainText); - } - phantom.exit(); -}); diff --git a/third_party/phantomjs/examples/printenv.js b/third_party/phantomjs/examples/printenv.js deleted file mode 100644 index 6baea038391..00000000000 --- a/third_party/phantomjs/examples/printenv.js +++ /dev/null @@ -1,10 +0,0 @@ -var system = require('system'), - env = system.env, - key; - -for (key in env) { - if (env.hasOwnProperty(key)) { - console.log(key + '=' + env[key]); - } -} -phantom.exit(); diff --git a/third_party/phantomjs/examples/printheaderfooter.js b/third_party/phantomjs/examples/printheaderfooter.js deleted file mode 100644 index 286af2b0abf..00000000000 --- a/third_party/phantomjs/examples/printheaderfooter.js +++ /dev/null @@ -1,90 +0,0 @@ -"use strict"; -var page = require('webpage').create(), - system = require('system'); - -function someCallback(pageNum, numPages) { - return "

someCallback: " + pageNum + " / " + numPages + "

"; -} - -if (system.args.length < 3) { - console.log('Usage: printheaderfooter.js URL filename'); - phantom.exit(1); -} else { - var address = system.args[1]; - var output = system.args[2]; - page.viewportSize = { width: 600, height: 600 }; - page.paperSize = { - format: 'A4', - margin: "1cm", - /* default header/footer for pages that don't have custom overwrites (see below) */ - header: { - height: "1cm", - contents: phantom.callback(function(pageNum, numPages) { - if (pageNum == 1) { - return ""; - } - return "

Header " + pageNum + " / " + numPages + "

"; - }) - }, - footer: { - height: "1cm", - contents: phantom.callback(function(pageNum, numPages) { - if (pageNum == numPages) { - return ""; - } - return "

Footer " + pageNum + " / " + numPages + "

"; - }) - } - }; - page.open(address, function (status) { - if (status !== 'success') { - console.log('Unable to load the address!'); - } else { - /* check whether the loaded page overwrites the header/footer setting, - i.e. whether a PhantomJSPriting object exists. Use that then instead - of our defaults above. - - example: - - - - -

asdfadsf

asdfadsfycvx

- - */ - if (page.evaluate(function(){return typeof PhantomJSPrinting == "object";})) { - paperSize = page.paperSize; - paperSize.header.height = page.evaluate(function() { - return PhantomJSPrinting.header.height; - }); - paperSize.header.contents = phantom.callback(function(pageNum, numPages) { - return page.evaluate(function(pageNum, numPages){return PhantomJSPrinting.header.contents(pageNum, numPages);}, pageNum, numPages); - }); - paperSize.footer.height = page.evaluate(function() { - return PhantomJSPrinting.footer.height; - }); - paperSize.footer.contents = phantom.callback(function(pageNum, numPages) { - return page.evaluate(function(pageNum, numPages){return PhantomJSPrinting.footer.contents(pageNum, numPages);}, pageNum, numPages); - }); - page.paperSize = paperSize; - console.log(page.paperSize.header.height); - console.log(page.paperSize.footer.height); - } - window.setTimeout(function () { - page.render(output); - phantom.exit(); - }, 200); - } - }); -} diff --git a/third_party/phantomjs/examples/printmargins.js b/third_party/phantomjs/examples/printmargins.js deleted file mode 100644 index 57c1acc19c5..00000000000 --- a/third_party/phantomjs/examples/printmargins.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; -var page = require('webpage').create(), - system = require('system'); - -if (system.args.length < 7) { - console.log('Usage: printmargins.js URL filename LEFT TOP RIGHT BOTTOM'); - console.log(' margin examples: "1cm", "10px", "7mm", "5in"'); - phantom.exit(1); -} else { - var address = system.args[1]; - var output = system.args[2]; - var marginLeft = system.args[3]; - var marginTop = system.args[4]; - var marginRight = system.args[5]; - var marginBottom = system.args[6]; - page.viewportSize = { width: 600, height: 600 }; - page.paperSize = { - format: 'A4', - margin: { - left: marginLeft, - top: marginTop, - right: marginRight, - bottom: marginBottom - } - }; - page.open(address, function (status) { - if (status !== 'success') { - console.log('Unable to load the address!'); - } else { - window.setTimeout(function () { - page.render(output); - phantom.exit(); - }, 200); - } - }); -} diff --git a/third_party/phantomjs/examples/rasterize.js b/third_party/phantomjs/examples/rasterize.js deleted file mode 100644 index c0950deb4e8..00000000000 --- a/third_party/phantomjs/examples/rasterize.js +++ /dev/null @@ -1,49 +0,0 @@ -"use strict"; -var page = require('webpage').create(), - system = require('system'), - address, output, size; - -if (system.args.length < 3 || system.args.length > 5) { - console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]'); - console.log(' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"'); - console.log(' image (png/jpg output) examples: "1920px" entire page, window width 1920px'); - console.log(' "800px*600px" window, clipped to 800x600'); - phantom.exit(1); -} else { - address = system.args[1]; - output = system.args[2]; - page.viewportSize = { width: 600, height: 600 }; - if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") { - size = system.args[3].split('*'); - page.paperSize = size.length === 2 ? { width: size[0], height: size[1], margin: '0px' } - : { format: system.args[3], orientation: 'portrait', margin: '1cm' }; - } else if (system.args.length > 3 && system.args[3].substr(-2) === "px") { - size = system.args[3].split('*'); - if (size.length === 2) { - pageWidth = parseInt(size[0], 10); - pageHeight = parseInt(size[1], 10); - page.viewportSize = { width: pageWidth, height: pageHeight }; - page.clipRect = { top: 0, left: 0, width: pageWidth, height: pageHeight }; - } else { - console.log("size:", system.args[3]); - pageWidth = parseInt(system.args[3], 10); - pageHeight = parseInt(pageWidth * 3/4, 10); // it's as good an assumption as any - console.log ("pageHeight:",pageHeight); - page.viewportSize = { width: pageWidth, height: pageHeight }; - } - } - if (system.args.length > 4) { - page.zoomFactor = system.args[4]; - } - page.open(address, function (status) { - if (status !== 'success') { - console.log('Unable to load the address!'); - phantom.exit(1); - } else { - window.setTimeout(function () { - page.render(output); - phantom.exit(); - }, 200); - } - }); -} diff --git a/third_party/phantomjs/examples/render_multi_url.js b/third_party/phantomjs/examples/render_multi_url.js deleted file mode 100644 index 9f7348debc6..00000000000 --- a/third_party/phantomjs/examples/render_multi_url.js +++ /dev/null @@ -1,74 +0,0 @@ -// Render Multiple URLs to file - -"use strict"; -var RenderUrlsToFile, arrayOfUrls, system; - -system = require("system"); - -/* -Render given urls -@param array of URLs to render -@param callbackPerUrl Function called after finishing each URL, including the last URL -@param callbackFinal Function called after finishing everything -*/ -RenderUrlsToFile = function(urls, callbackPerUrl, callbackFinal) { - var getFilename, next, page, retrieve, urlIndex, webpage; - urlIndex = 0; - webpage = require("webpage"); - page = null; - getFilename = function() { - return "rendermulti-" + urlIndex + ".png"; - }; - next = function(status, url, file) { - page.close(); - callbackPerUrl(status, url, file); - return retrieve(); - }; - retrieve = function() { - var url; - if (urls.length > 0) { - url = urls.shift(); - urlIndex++; - page = webpage.create(); - page.viewportSize = { - width: 800, - height: 600 - }; - page.settings.userAgent = "Phantom.js bot"; - return page.open("http://" + url, function(status) { - var file; - file = getFilename(); - if (status === "success") { - return window.setTimeout((function() { - page.render(file); - return next(status, url, file); - }), 200); - } else { - return next(status, url, file); - } - }); - } else { - return callbackFinal(); - } - }; - return retrieve(); -}; - -arrayOfUrls = null; - -if (system.args.length > 1) { - arrayOfUrls = Array.prototype.slice.call(system.args, 1); -} else { - console.log("Usage: phantomjs render_multi_url.js [domain.name1, domain.name2, ...]"); - arrayOfUrls = ["www.google.com", "www.bbc.co.uk", "phantomjs.org"]; -} - -RenderUrlsToFile(arrayOfUrls, (function(status, url, file) { - if (status !== "success") { - return console.log("Unable to render '" + url + "'"); - } else { - return console.log("Rendered '" + url + "' at '" + file + "'"); - } -}), function() { - return phantom.exit(); -}); diff --git a/third_party/phantomjs/examples/responsive-screenshot.js b/third_party/phantomjs/examples/responsive-screenshot.js deleted file mode 100644 index 35aac605f53..00000000000 --- a/third_party/phantomjs/examples/responsive-screenshot.js +++ /dev/null @@ -1,181 +0,0 @@ -/** - * Captures the full height document even if it's not showing on the screen or captures with the provided range of screen sizes. - * - * A basic example for taking a screen shot using phantomjs which is sampled for https://nodejs-dersleri.github.io/ - * - * usage : phantomjs responsive-screenshot.js {url} [output format] [doClipping] - * - * examples > - * phantomjs responsive-screenshot.js https://nodejs-dersleri.github.io/ - * phantomjs responsive-screenshot.js https://nodejs-dersleri.github.io/ pdf - * phantomjs responsive-screenshot.js https://nodejs-dersleri.github.io/ true - * phantomjs responsive-screenshot.js https://nodejs-dersleri.github.io/ png true - * - * @author Salih sagdilek - */ - -/** - * http://phantomjs.org/api/system/property/args.html - * - * Queries and returns a list of the command-line arguments. - * The first one is always the script name, which is then followed by the subsequent arguments. - */ -var args = require('system').args; -/** - * http://phantomjs.org/api/fs/ - * - * file system api - */ -var fs = require('fs'); - -/** - * http://phantomjs.org/api/webpage/ - * - * Web page api - */ -var page = new WebPage(); - -/** - * if url address does not exist, exit phantom - */ -if ( 1 === args.length ) { - console.log('Url address is required'); - phantom.exit(); -} - -/** - * setup url address (second argument); - */ -var urlAddress = args[1].toLowerCase(); - - -/** - * set output extension format - * @type {*} - */ -var ext = getFileExtension(); - -/** - * set if clipping ? - * @type {boolean} - */ -var clipping = getClipping(); - -/** - * setup viewports - */ -var viewports = [ - { - width : 1200, - height : 800 - }, - { - width : 1024, - height : 768 - }, - { - width : 768, - height : 1024 - }, - { - width : 480, - height : 640 - }, - { - width : 320, - height : 480 - } -]; - -page.open(urlAddress, function (status) { - if ( 'success' !== status ) { - console.log('Unable to load the url address!'); - } else { - var folder = urlToDir(urlAddress); - var output, key; - - function render(n) { - if ( !!n ) { - key = n - 1; - page.viewportSize = viewports[key]; - if ( clipping ) { - page.clipRect = viewports[key]; - } - output = folder + "/" + getFileName(viewports[key]); - console.log('Saving ' + output); - page.render(output); - render(key); - } - } - - render(viewports.length); - } - phantom.exit(); -}); - -/** - * filename generator helper - * @param viewport - * @returns {string} - */ -function getFileName(viewport) { - var d = new Date(); - var date = [ - d.getUTCFullYear(), - d.getUTCMonth() + 1, - d.getUTCDate() - ]; - var time = [ - d.getHours() <= 9 ? '0' + d.getHours() : d.getHours(), - d.getMinutes() <= 9 ? '0' + d.getMinutes() : d.getMinutes(), - d.getSeconds() <= 9 ? '0' + d.getSeconds() : d.getSeconds(), - d.getMilliseconds() - ]; - var resolution = viewport.width + (clipping ? "x" + viewport.height : ''); - - return date.join('-') + '_' + time.join('-') + "_" + resolution + ext; -} - -/** - * output extension format helper - * - * @returns {*} - */ -function getFileExtension() { - if ( 'true' != args[2] && !!args[2] ) { - return '.' + args[2]; - } - return '.png'; -} - -/** - * check if clipping - * - * @returns {boolean} - */ -function getClipping() { - if ( 'true' == args[3] ) { - return !!args[3]; - } else if ( 'true' == args[2] ) { - return !!args[2]; - } - return false; -} - -/** - * url to directory helper - * - * @param url - * @returns {string} - */ -function urlToDir(url) { - var dir = url - .replace(/^(http|https):\/\//, '') - .replace(/\/$/, ''); - - if ( !fs.makeTree(dir) ) { - console.log('"' + dir + '" is NOT created.'); - phantom.exit(); - } - return dir; -} diff --git a/third_party/phantomjs/examples/run-jasmine.js b/third_party/phantomjs/examples/run-jasmine.js deleted file mode 100644 index 652bb61ec84..00000000000 --- a/third_party/phantomjs/examples/run-jasmine.js +++ /dev/null @@ -1,92 +0,0 @@ -"use strict"; -var system = require('system'); - -/** - * Wait until the test condition is true or a timeout occurs. Useful for waiting - * on a server response or for a ui change (fadeIn, etc.) to occur. - * - * @param testFx javascript condition that evaluates to a boolean, - * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or - * as a callback function. - * @param onReady what to do when testFx condition is fulfilled, - * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or - * as a callback function. - * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used. - */ -function waitFor(testFx, onReady, timeOutMillis) { - var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3001, //< Default Max Timeout is 3s - start = new Date().getTime(), - condition = false, - interval = setInterval(function() { - if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) { - // If not time-out yet and condition not yet fulfilled - condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code - } else { - if(!condition) { - // If condition still not fulfilled (timeout but condition is 'false') - console.log("'waitFor()' timeout"); - phantom.exit(1); - } else { - // Condition fulfilled (timeout and/or condition is 'true') - console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms."); - typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled - clearInterval(interval); //< Stop this interval - } - } - }, 100); //< repeat check every 100ms -}; - - -if (system.args.length !== 2) { - console.log('Usage: run-jasmine.js URL'); - phantom.exit(1); -} - -var page = require('webpage').create(); - -// Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this") -page.onConsoleMessage = function(msg) { - console.log(msg); -}; - -page.open(system.args[1], function(status){ - if (status !== "success") { - console.log("Unable to open " + system.args[1]); - phantom.exit(1); - } else { - waitFor(function(){ - return page.evaluate(function(){ - return document.body.querySelector('.symbolSummary .pending') === null - }); - }, function(){ - var exitCode = page.evaluate(function(){ - try { - console.log(''); - console.log(document.body.querySelector('.description').innerText); - var list = document.body.querySelectorAll('.results > #details > .specDetail.failed'); - if (list && list.length > 0) { - console.log(''); - console.log(list.length + ' test(s) FAILED:'); - for (i = 0; i < list.length; ++i) { - var el = list[i], - desc = el.querySelector('.description'), - msg = el.querySelector('.resultMessage.fail'); - console.log(''); - console.log(desc.innerText); - console.log(msg.innerText); - console.log(''); - } - return 1; - } else { - console.log(document.body.querySelector('.alert > .passingAlert.bar').innerText); - return 0; - } - } catch (ex) { - console.log(ex); - return 1; - } - }); - phantom.exit(exitCode); - }); - } -}); diff --git a/third_party/phantomjs/examples/run-jasmine2.js b/third_party/phantomjs/examples/run-jasmine2.js deleted file mode 100644 index 343117ab0d6..00000000000 --- a/third_party/phantomjs/examples/run-jasmine2.js +++ /dev/null @@ -1,94 +0,0 @@ -"use strict"; -var system = require('system'); - -/** - * Wait until the test condition is true or a timeout occurs. Useful for waiting - * on a server response or for a ui change (fadeIn, etc.) to occur. - * - * @param testFx javascript condition that evaluates to a boolean, - * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or - * as a callback function. - * @param onReady what to do when testFx condition is fulfilled, - * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or - * as a callback function. - * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used. - */ -function waitFor(testFx, onReady, timeOutMillis) { - var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3001, //< Default Max Timeout is 3s - start = new Date().getTime(), - condition = false, - interval = setInterval(function() { - if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) { - // If not time-out yet and condition not yet fulfilled - condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code - } else { - if(!condition) { - // If condition still not fulfilled (timeout but condition is 'false') - console.log("'waitFor()' timeout"); - phantom.exit(1); - } else { - // Condition fulfilled (timeout and/or condition is 'true') - console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms."); - typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled - clearInterval(interval); //< Stop this interval - } - } - }, 100); //< repeat check every 100ms -}; - - -if (system.args.length !== 2) { - console.log('Usage: run-jasmine2.js URL'); - phantom.exit(1); -} - -var page = require('webpage').create(); - -// Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this") -page.onConsoleMessage = function(msg) { - console.log(msg); -}; - -page.open(system.args[1], function(status){ - if (status !== "success") { - console.log("Unable to access network"); - phantom.exit(); - } else { - waitFor(function(){ - return page.evaluate(function(){ - return (document.body.querySelector('.symbolSummary .pending') === null && - document.body.querySelector('.duration') !== null); - }); - }, function(){ - var exitCode = page.evaluate(function(){ - console.log(''); - - var title = 'Jasmine'; - var version = document.body.querySelector('.version').innerText; - var duration = document.body.querySelector('.duration').innerText; - var banner = title + ' ' + version + ' ' + duration; - console.log(banner); - - var list = document.body.querySelectorAll('.results > .failures > .spec-detail.failed'); - if (list && list.length > 0) { - console.log(''); - console.log(list.length + ' test(s) FAILED:'); - for (i = 0; i < list.length; ++i) { - var el = list[i], - desc = el.querySelector('.description'), - msg = el.querySelector('.messages > .result-message'); - console.log(''); - console.log(desc.innerText); - console.log(msg.innerText); - console.log(''); - } - return 1; - } else { - console.log(document.body.querySelector('.alert > .bar.passed,.alert > .bar.skipped').innerText); - return 0; - } - }); - phantom.exit(exitCode); - }); - } -}); diff --git a/third_party/phantomjs/examples/run-qunit.js b/third_party/phantomjs/examples/run-qunit.js deleted file mode 100644 index d3cbf5b9c9a..00000000000 --- a/third_party/phantomjs/examples/run-qunit.js +++ /dev/null @@ -1,77 +0,0 @@ -"use strict"; -var system = require('system'); - -/** - * Wait until the test condition is true or a timeout occurs. Useful for waiting - * on a server response or for a ui change (fadeIn, etc.) to occur. - * - * @param testFx javascript condition that evaluates to a boolean, - * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or - * as a callback function. - * @param onReady what to do when testFx condition is fulfilled, - * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or - * as a callback function. - * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used. - */ -function waitFor(testFx, onReady, timeOutMillis) { - var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3001, //< Default Max Timout is 3s - start = new Date().getTime(), - condition = false, - interval = setInterval(function() { - if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) { - // If not time-out yet and condition not yet fulfilled - condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code - } else { - if(!condition) { - // If condition still not fulfilled (timeout but condition is 'false') - console.log("'waitFor()' timeout"); - phantom.exit(1); - } else { - // Condition fulfilled (timeout and/or condition is 'true') - console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms."); - typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled - clearInterval(interval); //< Stop this interval - } - } - }, 100); //< repeat check every 250ms -}; - - -if (system.args.length !== 2) { - console.log('Usage: run-qunit.js URL'); - phantom.exit(1); -} - -var page = require('webpage').create(); - -// Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this") -page.onConsoleMessage = function(msg) { - console.log(msg); -}; - -page.open(system.args[1], function(status){ - if (status !== "success") { - console.log("Unable to access network"); - phantom.exit(1); - } else { - waitFor(function(){ - return page.evaluate(function(){ - var el = document.getElementById('qunit-testresult'); - if (el && el.innerText.match('completed')) { - return true; - } - return false; - }); - }, function(){ - var failedNum = page.evaluate(function(){ - var el = document.getElementById('qunit-testresult'); - console.log(el.innerText); - try { - return el.getElementsByClassName('failed')[0].innerHTML; - } catch (e) { } - return 10000; - }); - phantom.exit((parseInt(failedNum, 10) > 0) ? 1 : 0); - }); - } -}); diff --git a/third_party/phantomjs/examples/scandir.js b/third_party/phantomjs/examples/scandir.js deleted file mode 100644 index 73943679a10..00000000000 --- a/third_party/phantomjs/examples/scandir.js +++ /dev/null @@ -1,24 +0,0 @@ -// List all the files in a Tree of Directories - -"use strict"; -var system = require('system'); - -if (system.args.length !== 2) { - console.log("Usage: phantomjs scandir.js DIRECTORY_TO_SCAN"); - phantom.exit(1); -} - -var scanDirectory = function (path) { - var fs = require('fs'); - if (fs.exists(path) && fs.isFile(path)) { - console.log(path); - } else if (fs.isDirectory(path)) { - fs.list(path).forEach(function (e) { - if ( e !== "." && e !== ".." ) { //< Avoid loops - scanDirectory(path + '/' + e); - } - }); - } -}; -scanDirectory(system.args[1]); -phantom.exit(); diff --git a/third_party/phantomjs/examples/server.js b/third_party/phantomjs/examples/server.js deleted file mode 100644 index ff5ef3d2f81..00000000000 --- a/third_party/phantomjs/examples/server.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; -var page = require('webpage').create(); -var server = require('webserver').create(); -var system = require('system'); -var host, port; - -if (system.args.length !== 2) { - console.log('Usage: server.js '); - phantom.exit(1); -} else { - port = system.args[1]; - var listening = server.listen(port, function (request, response) { - console.log("GOT HTTP REQUEST"); - console.log(JSON.stringify(request, null, 4)); - - // we set the headers here - response.statusCode = 200; - response.headers = {"Cache": "no-cache", "Content-Type": "text/html"}; - // this is also possible: - response.setHeader("foo", "bar"); - // now we write the body - // note: the headers above will now be sent implictly - response.write("YES!"); - // note: writeBody can be called multiple times - response.write("

pretty cool :)"); - response.close(); - }); - if (!listening) { - console.log("could not create web server listening on port " + port); - phantom.exit(); - } - var url = "http://localhost:" + port + "/foo/bar.php?asdf=true"; - console.log("SENDING REQUEST TO:"); - console.log(url); - page.open(url, function (status) { - if (status !== 'success') { - console.log('FAIL to load the address'); - } else { - console.log("GOT REPLY FROM SERVER:"); - console.log(page.content); - } - phantom.exit(); - }); -} diff --git a/third_party/phantomjs/examples/serverkeepalive.js b/third_party/phantomjs/examples/serverkeepalive.js deleted file mode 100644 index 00b462aaa83..00000000000 --- a/third_party/phantomjs/examples/serverkeepalive.js +++ /dev/null @@ -1,35 +0,0 @@ -"use strict"; -var port, server, service, - system = require('system'); - -if (system.args.length !== 2) { - console.log('Usage: serverkeepalive.js '); - phantom.exit(1); -} else { - port = system.args[1]; - server = require('webserver').create(); - - service = server.listen(port, { keepAlive: true }, function (request, response) { - console.log('Request at ' + new Date()); - console.log(JSON.stringify(request, null, 4)); - - var body = JSON.stringify(request, null, 4); - response.statusCode = 200; - response.headers = { - 'Cache': 'no-cache', - 'Content-Type': 'text/plain', - 'Connection': 'Keep-Alive', - 'Keep-Alive': 'timeout=5, max=100', - 'Content-Length': body.length - }; - response.write(body); - response.close(); - }); - - if (service) { - console.log('Web server running on port ' + port); - } else { - console.log('Error: Could not create web server listening on port ' + port); - phantom.exit(); - } -} diff --git a/third_party/phantomjs/examples/simpleserver.js b/third_party/phantomjs/examples/simpleserver.js deleted file mode 100644 index ba4779a95e8..00000000000 --- a/third_party/phantomjs/examples/simpleserver.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; -var port, server, service, - system = require('system'); - -if (system.args.length !== 2) { - console.log('Usage: simpleserver.js '); - phantom.exit(1); -} else { - port = system.args[1]; - server = require('webserver').create(); - - service = server.listen(port, function (request, response) { - - console.log('Request at ' + new Date()); - console.log(JSON.stringify(request, null, 4)); - - response.statusCode = 200; - response.headers = { - 'Cache': 'no-cache', - 'Content-Type': 'text/html' - }; - response.write(''); - response.write(''); - response.write('Hello, world!'); - response.write(''); - response.write(''); - response.write('

This is from PhantomJS web server.

'); - response.write('

Request data:

'); - response.write('
');
-        response.write(JSON.stringify(request, null, 4));
-        response.write('
'); - response.write(''); - response.write(''); - response.close(); - }); - - if (service) { - console.log('Web server running on port ' + port); - } else { - console.log('Error: Could not create web server listening on port ' + port); - phantom.exit(); - } -} diff --git a/third_party/phantomjs/examples/sleepsort.js b/third_party/phantomjs/examples/sleepsort.js deleted file mode 100644 index 7959799567b..00000000000 --- a/third_party/phantomjs/examples/sleepsort.js +++ /dev/null @@ -1,27 +0,0 @@ -// sleepsort.js - Sort integers from the commandline in a very ridiculous way: leveraging timeouts :P - -"use strict"; -var system = require('system'); - -function sleepSort(array, callback) { - var sortedCount = 0, - i, len; - for ( i = 0, len = array.length; i < len; ++i ) { - setTimeout((function(j){ - return function() { - console.log(array[j]); - ++sortedCount; - (len === sortedCount) && callback(); - }; - }(i)), array[i]); - } -} - -if ( system.args.length < 2 ) { - console.log("Usage: phantomjs sleepsort.js PUT YOUR INTEGERS HERE SEPARATED BY SPACES"); - phantom.exit(1); -} else { - sleepSort(system.args.slice(1), function() { - phantom.exit(); - }); -} diff --git a/third_party/phantomjs/examples/stdin-stdout-stderr.js b/third_party/phantomjs/examples/stdin-stdout-stderr.js deleted file mode 100644 index 4161ba3b233..00000000000 --- a/third_party/phantomjs/examples/stdin-stdout-stderr.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -var system = require('system'); - -system.stdout.write('Hello, system.stdout.write!'); -system.stdout.writeLine('\nHello, system.stdout.writeLine!'); - -system.stderr.write('Hello, system.stderr.write!'); -system.stderr.writeLine('\nHello, system.stderr.writeLine!'); - -system.stdout.writeLine('system.stdin.readLine(): '); -var line = system.stdin.readLine(); -system.stdout.writeLine(JSON.stringify(line)); - -// This is essentially a `readAll` -system.stdout.writeLine('system.stdin.read(5): (ctrl+D to end)'); -var input = system.stdin.read(5); -system.stdout.writeLine(JSON.stringify(input)); - -phantom.exit(0); diff --git a/third_party/phantomjs/examples/universe.js b/third_party/phantomjs/examples/universe.js deleted file mode 100644 index 2655aaf4a83..00000000000 --- a/third_party/phantomjs/examples/universe.js +++ /dev/null @@ -1,10 +0,0 @@ -// This is to be used by "module.js" (and "module.coffee") example(s). -// There should NOT be a "universe.coffee" as only 1 of the 2 would -// ever be loaded unless the file extension was specified. - -"use strict"; -exports.answer = 42; - -exports.start = function () { - console.log('Starting the universe....'); -} diff --git a/third_party/phantomjs/examples/unrandomize.js b/third_party/phantomjs/examples/unrandomize.js deleted file mode 100644 index 7f0e1bbf5e0..00000000000 --- a/third_party/phantomjs/examples/unrandomize.js +++ /dev/null @@ -1,25 +0,0 @@ -// Modify global object at the page initialization. -// In this example, effectively Math.random() always returns 0.42. - -"use strict"; -var page = require('webpage').create(); - -page.onInitialized = function () { - page.evaluate(function () { - Math.random = function() { - return 42 / 100; - }; - }); -}; - -page.open('http://ariya.github.com/js/random/', function (status) { - var result; - if (status !== 'success') { - console.log('Network error.'); - } else { - console.log(page.evaluate(function () { - return document.getElementById('numbers').textContent; - })); - } - phantom.exit(); -}); diff --git a/third_party/phantomjs/examples/useragent.js b/third_party/phantomjs/examples/useragent.js deleted file mode 100644 index 5a48091a38c..00000000000 --- a/third_party/phantomjs/examples/useragent.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -var page = require('webpage').create(); -console.log('The default user agent is ' + page.settings.userAgent); -page.settings.userAgent = 'SpecialAgent'; -page.open('http://www.httpuseragent.org', function (status) { - if (status !== 'success') { - console.log('Unable to access network'); - } else { - var ua = page.evaluate(function () { - return document.getElementById('myagent').innerText; - }); - console.log(ua); - } - phantom.exit(); -}); diff --git a/third_party/phantomjs/examples/version.js b/third_party/phantomjs/examples/version.js deleted file mode 100644 index dfda4f8edcb..00000000000 --- a/third_party/phantomjs/examples/version.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; -console.log('using PhantomJS version ' + - phantom.version.major + '.' + - phantom.version.minor + '.' + - phantom.version.patch); -phantom.exit(); diff --git a/third_party/phantomjs/examples/waitfor.js b/third_party/phantomjs/examples/waitfor.js deleted file mode 100644 index c470a92b653..00000000000 --- a/third_party/phantomjs/examples/waitfor.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Wait until the test condition is true or a timeout occurs. Useful for waiting - * on a server response or for a ui change (fadeIn, etc.) to occur. - * - * @param testFx javascript condition that evaluates to a boolean, - * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or - * as a callback function. - * @param onReady what to do when testFx condition is fulfilled, - * it can be passed in as a string (e.g.: "1 == 1" or "$('#bar').is(':visible')" or - * as a callback function. - * @param timeOutMillis the max amount of time to wait. If not specified, 3 sec is used. - */ - -"use strict"; -function waitFor(testFx, onReady, timeOutMillis) { - var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s - start = new Date().getTime(), - condition = false, - interval = setInterval(function() { - if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) { - // If not time-out yet and condition not yet fulfilled - condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code - } else { - if(!condition) { - // If condition still not fulfilled (timeout but condition is 'false') - console.log("'waitFor()' timeout"); - phantom.exit(1); - } else { - // Condition fulfilled (timeout and/or condition is 'true') - console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms."); - typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled - clearInterval(interval); //< Stop this interval - } - } - }, 250); //< repeat check every 250ms -}; - - -var page = require('webpage').create(); - -// Open Twitter on 'sencha' profile and, onPageLoad, do... -page.open("http://twitter.com/#!/sencha", function (status) { - // Check for page load success - if (status !== "success") { - console.log("Unable to access network"); - } else { - // Wait for 'signin-dropdown' to be visible - waitFor(function() { - // Check in the page if a specific element is now visible - return page.evaluate(function() { - return $("#signin-dropdown").is(":visible"); - }); - }, function() { - console.log("The sign-in dialog should be visible now."); - phantom.exit(); - }); - } -}); diff --git a/third_party/phantomjs/examples/walk_through_frames.js b/third_party/phantomjs/examples/walk_through_frames.js deleted file mode 100644 index d0fabfcde90..00000000000 --- a/third_party/phantomjs/examples/walk_through_frames.js +++ /dev/null @@ -1,73 +0,0 @@ -"use strict"; -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); -} - -p.open("../test/webpage-spec-frames/index.html", function(status) { - console.log("pageTitle(): " + pageTitle(p)); - console.log("currentFrameName(): "+p.currentFrameName()); - console.log("childFramesCount(): "+p.childFramesCount()); - console.log("childFramesName(): "+p.childFramesName()); - console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited"); - console.log(""); - - console.log("p.switchToChildFrame(\"frame1\"): "+p.switchToChildFrame("frame1")); - console.log("pageTitle(): " + pageTitle(p)); - console.log("currentFrameName(): "+p.currentFrameName()); - console.log("childFramesCount(): "+p.childFramesCount()); - console.log("childFramesName(): "+p.childFramesName()); - console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited"); - console.log(""); - - console.log("p.switchToChildFrame(\"frame1-2\"): "+p.switchToChildFrame("frame1-2")); - console.log("pageTitle(): " + pageTitle(p)); - console.log("currentFrameName(): "+p.currentFrameName()); - console.log("childFramesCount(): "+p.childFramesCount()); - console.log("childFramesName(): "+p.childFramesName()); - console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited"); - console.log(""); - - console.log("p.switchToParentFrame(): "+p.switchToParentFrame()); - console.log("pageTitle(): " + pageTitle(p)); - console.log("currentFrameName(): "+p.currentFrameName()); - console.log("childFramesCount(): "+p.childFramesCount()); - console.log("childFramesName(): "+p.childFramesName()); - console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited"); - console.log(""); - - console.log("p.switchToChildFrame(0): "+p.switchToChildFrame(0)); - console.log("pageTitle(): " + pageTitle(p)); - console.log("currentFrameName(): "+p.currentFrameName()); - console.log("childFramesCount(): "+p.childFramesCount()); - console.log("childFramesName(): "+p.childFramesName()); - console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited"); - console.log(""); - - console.log("p.switchToMainFrame()"); p.switchToMainFrame(); - console.log("pageTitle(): " + pageTitle(p)); - console.log("currentFrameName(): "+p.currentFrameName()); - console.log("childFramesCount(): "+p.childFramesCount()); - console.log("childFramesName(): "+p.childFramesName()); - console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited"); - console.log(""); - - console.log("p.switchToChildFrame(\"frame2\"): "+p.switchToChildFrame("frame2")); - console.log("pageTitle(): " + pageTitle(p)); - console.log("currentFrameName(): "+p.currentFrameName()); - console.log("childFramesCount(): "+p.childFramesCount()); - console.log("childFramesName(): "+p.childFramesName()); - console.log("setPageTitle(CURRENT TITLE+'-visited')"); setPageTitle(p, pageTitle(p) + "-visited"); - console.log(""); - - phantom.exit(); -}); diff --git a/third_party/phantomjs/test/basics/exit0.js b/third_party/phantomjs/test/basics/exit0.js deleted file mode 100644 index 13243eadbed..00000000000 --- a/third_party/phantomjs/test/basics/exit0.js +++ /dev/null @@ -1,8 +0,0 @@ -//! no-harness -//! expect-exit: 0 -//! expect-stdout: "we are alive" - -var sys = require('system'); -sys.stdout.write("we are alive\n"); -phantom.exit(); -sys.stdout.write("ERROR control passed beyond phantom.exit"); diff --git a/third_party/phantomjs/test/basics/exit23.js b/third_party/phantomjs/test/basics/exit23.js deleted file mode 100644 index eb3e05aa3c2..00000000000 --- a/third_party/phantomjs/test/basics/exit23.js +++ /dev/null @@ -1,8 +0,0 @@ -//! no-harness -//! expect-exit: 23 -//! expect-stdout: "we are alive" - -var sys = require('system'); -sys.stdout.write("we are alive\n"); -phantom.exit(23); -sys.stdout.write("ERROR control passed beyond phantom.exit"); diff --git a/third_party/phantomjs/test/basics/module.js b/third_party/phantomjs/test/basics/module.js deleted file mode 100644 index 58e8b33cd3b..00000000000 --- a/third_party/phantomjs/test/basics/module.js +++ /dev/null @@ -1,27 +0,0 @@ -// Test the properties of the 'module' object. -// Assumes the 'dummy_exposed' module is to be found in a directory -// named 'node_modules'. - -// Module load might fail, so do it in a setup function. -var module; -setup(function () { - module = require("dummy_exposed"); -}); - -test(function() { - assert_regexp_match(module.filename, /\/node_modules\/dummy_exposed\.js$/); -}, "module.filename is the absolute pathname of the module .js file"); - -test(function() { - assert_regexp_match(module.dirname, /\/node_modules$/); -}, "module.dirname is the absolute pathname of the directory containing "+ - "the module"); - -test(function() { - assert_equals(module.id, module.filename); -}, "module.id equals module.filename"); - -test(function() { - var dummy_file = module.require('./dummy_file'); - assert_equals(dummy_file, 'spec/node_modules/dummy_file'); -}, "module.require is callable and resolves relative to the module"); diff --git a/third_party/phantomjs/test/basics/phantom-object.js b/third_party/phantomjs/test/basics/phantom-object.js deleted file mode 100644 index c046351a58f..00000000000 --- a/third_party/phantomjs/test/basics/phantom-object.js +++ /dev/null @@ -1,39 +0,0 @@ -test(function () { - assert_type_of(phantom, 'object'); -}, "phantom object"); - -test(function () { - assert_own_property(phantom, 'libraryPath'); - assert_type_of(phantom.libraryPath, 'string'); - assert_greater_than(phantom.libraryPath.length, 0); -}, "phantom.libraryPath"); - -test(function () { - assert_own_property(phantom, 'outputEncoding'); - assert_type_of(phantom.outputEncoding, 'string'); - assert_equals(phantom.outputEncoding.toLowerCase(), 'utf-8'); // default -}, "phantom.outputEncoding"); - -test(function () { - assert_own_property(phantom, 'injectJs'); - assert_type_of(phantom.injectJs, 'function'); -}, "phantom.injectJs"); - -test(function () { - assert_own_property(phantom, 'exit'); - assert_type_of(phantom.exit, 'function'); -}, "phantom.exit"); - -test(function () { - assert_own_property(phantom, 'cookiesEnabled'); - assert_type_of(phantom.cookiesEnabled, 'boolean'); - assert_is_true(phantom.cookiesEnabled); -}, "phantom.cookiesEnabled"); - -test(function () { - assert_own_property(phantom, 'version'); - assert_type_of(phantom.version, 'object'); - assert_type_of(phantom.version.major, 'number'); - assert_type_of(phantom.version.minor, 'number'); - assert_type_of(phantom.version.patch, 'number'); -}, "phantom.version"); diff --git a/third_party/phantomjs/test/basics/require.js b/third_party/phantomjs/test/basics/require.js deleted file mode 100644 index 02a2d638048..00000000000 --- a/third_party/phantomjs/test/basics/require.js +++ /dev/null @@ -1,10 +0,0 @@ -/* The require tests need to run inside a module to work correctly; that - module is require/require_spec.js. (That directory also contains a - bunch of other files used by this test.) The module exports an array - of test functions in the form expected by generate_tests(). */ - -var rtests = require("require/require_spec.js").tests; - -for (var i = 0; i < rtests.length; i++) { - test.apply(null, rtests[i]); -} diff --git a/third_party/phantomjs/test/basics/require/a.js b/third_party/phantomjs/test/basics/require/a.js deleted file mode 100644 index 02cf3f554e7..00000000000 --- a/third_party/phantomjs/test/basics/require/a.js +++ /dev/null @@ -1,2 +0,0 @@ -var b = require('./b'); -exports.b = b; diff --git a/third_party/phantomjs/test/basics/require/b.js b/third_party/phantomjs/test/basics/require/b.js deleted file mode 100644 index 69660fca3a3..00000000000 --- a/third_party/phantomjs/test/basics/require/b.js +++ /dev/null @@ -1,2 +0,0 @@ -var a = require('./a'); -exports.a = a; diff --git a/third_party/phantomjs/test/basics/require/dir/dummy.js b/third_party/phantomjs/test/basics/require/dir/dummy.js deleted file mode 100644 index 0705990b1dd..00000000000 --- a/third_party/phantomjs/test/basics/require/dir/dummy.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = 'dir/dummy'; diff --git a/third_party/phantomjs/test/basics/require/dir/subdir/dummy.js b/third_party/phantomjs/test/basics/require/dir/subdir/dummy.js deleted file mode 100644 index a8cfec5a4fc..00000000000 --- a/third_party/phantomjs/test/basics/require/dir/subdir/dummy.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = 'subdir/dummy'; diff --git a/third_party/phantomjs/test/basics/require/dir/subdir/loader.js b/third_party/phantomjs/test/basics/require/dir/subdir/loader.js deleted file mode 100644 index 5033ccb6699..00000000000 --- a/third_party/phantomjs/test/basics/require/dir/subdir/loader.js +++ /dev/null @@ -1 +0,0 @@ -exports.dummyFile2 = require('dummy_file2'); diff --git a/third_party/phantomjs/test/basics/require/dir/subdir2/loader.js b/third_party/phantomjs/test/basics/require/dir/subdir2/loader.js deleted file mode 100644 index 620991106a4..00000000000 --- a/third_party/phantomjs/test/basics/require/dir/subdir2/loader.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = 'require/subdir2/loader' diff --git a/third_party/phantomjs/test/basics/require/dummy.js b/third_party/phantomjs/test/basics/require/dummy.js deleted file mode 100644 index 96425ed22dc..00000000000 --- a/third_party/phantomjs/test/basics/require/dummy.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = 'require/dummy'; diff --git a/third_party/phantomjs/test/basics/require/empty.js b/third_party/phantomjs/test/basics/require/empty.js deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/third_party/phantomjs/test/basics/require/json_dummy.json b/third_party/phantomjs/test/basics/require/json_dummy.json deleted file mode 100644 index 78ad073b667..00000000000 --- a/third_party/phantomjs/test/basics/require/json_dummy.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "message": "hello" -} diff --git a/third_party/phantomjs/test/basics/require/node_modules/dummy_file.js b/third_party/phantomjs/test/basics/require/node_modules/dummy_file.js deleted file mode 100644 index a1427b93b70..00000000000 --- a/third_party/phantomjs/test/basics/require/node_modules/dummy_file.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = 'require/node_modules/dummy_file'; diff --git a/third_party/phantomjs/test/basics/require/node_modules/dummy_module/libdir/dummy_module.js b/third_party/phantomjs/test/basics/require/node_modules/dummy_module/libdir/dummy_module.js deleted file mode 100644 index 55016f51dd9..00000000000 --- a/third_party/phantomjs/test/basics/require/node_modules/dummy_module/libdir/dummy_module.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = 'require/node_modules/dummy_module'; diff --git a/third_party/phantomjs/test/basics/require/node_modules/dummy_module/package.json b/third_party/phantomjs/test/basics/require/node_modules/dummy_module/package.json deleted file mode 100644 index 8345e9bbddb..00000000000 --- a/third_party/phantomjs/test/basics/require/node_modules/dummy_module/package.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "name": "dummy", - "main": "./libdir/dummy_module.js" -} diff --git a/third_party/phantomjs/test/basics/require/node_modules/dummy_module2/index.js b/third_party/phantomjs/test/basics/require/node_modules/dummy_module2/index.js deleted file mode 100644 index f360c638607..00000000000 --- a/third_party/phantomjs/test/basics/require/node_modules/dummy_module2/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = 'require/node_modules/dummy_module2'; diff --git a/third_party/phantomjs/test/basics/require/not_found.js b/third_party/phantomjs/test/basics/require/not_found.js deleted file mode 100644 index fbc35327f1c..00000000000 --- a/third_party/phantomjs/test/basics/require/not_found.js +++ /dev/null @@ -1,3 +0,0 @@ -exports.requireNonExistent = function() { - require('./non_existent'); -}; diff --git a/third_party/phantomjs/test/basics/require/require_spec.js b/third_party/phantomjs/test/basics/require/require_spec.js deleted file mode 100644 index 655654f8607..00000000000 --- a/third_party/phantomjs/test/basics/require/require_spec.js +++ /dev/null @@ -1,131 +0,0 @@ -var fs = require('fs'); -var tests = []; -exports.tests = tests; - -tests.push([function () { - assert_no_property(window, 'CoffeeScript'); - assert_own_property(window, 'require'); - - assert_own_property(require('webpage'), 'create'); - assert_own_property(require('webserver'), 'create'); - assert_own_property(require('cookiejar'), 'create'); - - assert_own_property(require('fs'), 'separator'); - assert_equals(require('system').platform, 'phantomjs'); - -}, "native modules"]); - -tests.push([function () { - assert_equals(require('./json_dummy').message, 'hello'); - assert_equals(require('./dummy.js'), 'require/dummy'); -}, "JS and JSON modules"]); - -tests.push([function () { - require('./empty').hello = 'hola'; - assert_equals(require('./empty').hello, 'hola'); - - // assert_own_property rejects Functions - assert_equals(require.hasOwnProperty('cache'), true); - - var exposed = require('dummy_exposed'); - assert_equals(require.cache[exposed.filename], exposed); - -}, "module caching"]); - -tests.push([function () { - var a = require('./a'); - var b = require('./b'); - assert_equals(a.b, b); - assert_equals(b.a, a); -}, "circular dependencies"]); - -tests.push([function () { - assert_throws("Cannot find module 'dummy_missing'", - function () { require('dummy_missing'); }); - - try { - require('./not_found').requireNonExistent(); - } catch (e) { - assert_regexp_match(e.stack, /at require /); - } -}, "error handling 1"]); - -tests.push([function error_handling_2 () { - try { - require('./thrower').fn(); - } catch (e) { - assert_regexp_match(e.toString() + "\n" + e.stack, - /^Error: fn\nError: fn\n at Object.thrower/); - } -}, "error handling 2"]); - -tests.push([function () { - assert_equals(require('./stubber').stubbed, 'stubbed module'); - assert_equals(require('./stubber').child.stubbed, 'stubbed module'); - assert_throws("Cannot find module 'stubbed'", - function () { require('stubbed'); }); - - var count = 0; - require.stub('lazily_stubbed', function() { - ++count; - return 'lazily stubbed module'; - }); - - assert_equals(require('lazily_stubbed'), 'lazily stubbed module'); - require('lazily_stubbed'); - assert_equals(count, 1); - -}, "stub modules"]); - -tests.push([function () { - assert_equals(require('./dummy'), 'require/dummy'); - assert_equals(require('../fixtures/dummy'), 'spec/dummy'); - assert_equals(require('./dir/dummy'), 'dir/dummy'); - assert_equals(require('./dir/subdir/dummy'), 'subdir/dummy'); - assert_equals(require('./dir/../dummy'), 'require/dummy'); - assert_equals(require('./dir/./dummy'), 'dir/dummy'); - assert_equals(require( - fs.absolute(module.dirname + '/dummy.js')), 'require/dummy'); - -}, "relative and absolute paths"]); - -tests.push([function () { - assert_equals(require('dummy_file'), 'require/node_modules/dummy_file'); - assert_equals(require('dummy_file2'), 'spec/node_modules/dummy_file2'); - assert_equals(require('./dir/subdir/loader').dummyFile2, - 'spec/node_modules/dummy_file2'); - assert_equals(require('dummy_module'), - 'require/node_modules/dummy_module'); - assert_equals(require('dummy_module2'), - 'require/node_modules/dummy_module2'); -}, "loading from node_modules"]); - -function require_paths_tests_1 () { - assert_equals(require('loader').dummyFile2, - 'spec/node_modules/dummy_file2'); - assert_equals(require('../subdir2/loader'), - 'require/subdir2/loader'); - assert_equals(require('../fixtures/dummy'), 'spec/dummy'); -} -function require_paths_tests_2 () { - assert_throws("Cannot find module 'loader'", - function () { require('loader'); }); -} - -tests.push([function () { - require.paths.push('dir/subdir'); - this.add_cleanup(function () { require.paths.pop(); }); - require_paths_tests_1(); -}, "relative paths in require.paths"]); - -tests.push([ - require_paths_tests_2, "relative paths in require paths (after removal)"]); - -tests.push([function () { - require.paths.push(fs.absolute(module.dirname + '/dir/subdir')); - this.add_cleanup(function () { require.paths.pop(); }); - require_paths_tests_1(); -}, "absolute paths in require.paths"]); - -tests.push([ - require_paths_tests_2, "relative paths in require paths (after removal)"]); diff --git a/third_party/phantomjs/test/basics/require/stubber.js b/third_party/phantomjs/test/basics/require/stubber.js deleted file mode 100644 index 727d10484ca..00000000000 --- a/third_party/phantomjs/test/basics/require/stubber.js +++ /dev/null @@ -1,5 +0,0 @@ -require.stub('stubbed', 'stubbed module'); -exports.stubbed = require('stubbed'); -try { - exports.child = require('./stubber_child'); -} catch (e) {} diff --git a/third_party/phantomjs/test/basics/require/stubber_child.js b/third_party/phantomjs/test/basics/require/stubber_child.js deleted file mode 100644 index 527c14fd812..00000000000 --- a/third_party/phantomjs/test/basics/require/stubber_child.js +++ /dev/null @@ -1 +0,0 @@ -exports.stubbed = require('stubbed'); diff --git a/third_party/phantomjs/test/basics/require/thrower.js b/third_party/phantomjs/test/basics/require/thrower.js deleted file mode 100644 index 6a98c3fd0a1..00000000000 --- a/third_party/phantomjs/test/basics/require/thrower.js +++ /dev/null @@ -1,3 +0,0 @@ -exports.fn = function thrower() { - throw new Error('fn'); -}; diff --git a/third_party/phantomjs/test/basics/stacktrace.js b/third_party/phantomjs/test/basics/stacktrace.js deleted file mode 100644 index d195144e0e7..00000000000 --- a/third_party/phantomjs/test/basics/stacktrace.js +++ /dev/null @@ -1,12 +0,0 @@ -// A SyntaxError leaks to phantom.onError, despite the try-catch. -setup({ allow_uncaught_exception: true }); - -test(function () { - var helperFile = "../fixtures/parse-error-helper.js"; - try { - phantom.injectJs(helperFile); - assert_is_true(false); - } catch (e) { - assert_is_true(e.stack.indexOf('fixtures/parse-error-helper.js:2') !== -1); - } -}, "stack trace from syntax error in injected file"); diff --git a/third_party/phantomjs/test/basics/test-server.js b/third_party/phantomjs/test/basics/test-server.js deleted file mode 100644 index 0b8d2149bec..00000000000 --- a/third_party/phantomjs/test/basics/test-server.js +++ /dev/null @@ -1,33 +0,0 @@ -//! unsupported -/* Test the test server itself. */ - -var webpage = require('webpage'); - -function test_one_page(url) { - var page = webpage.create(); - page.onResourceReceived = this.step_func(function (response) { - assert_equals(response.status, 200); - }); - page.onResourceError = this.unreached_func(); - page.onResourceTimeout = this.unreached_func(); - page.onLoadFinished = this.step_func_done(function (status) { - assert_equals(status, 'success'); - }); - page.open(url); -} - -function do_test(path) { - var http_url = TEST_HTTP_BASE + path; - var https_url = TEST_HTTPS_BASE + path; - var http_test = async_test(http_url); - var https_test = async_test(https_url); - http_test.step(test_one_page, null, http_url); - https_test.step(test_one_page, null, https_url); -} - -[ - 'hello.html', - 'status?200', - 'echo' -] - .forEach(do_test); diff --git a/third_party/phantomjs/test/basics/timeout.js b/third_party/phantomjs/test/basics/timeout.js deleted file mode 100644 index 7a753543215..00000000000 --- a/third_party/phantomjs/test/basics/timeout.js +++ /dev/null @@ -1,7 +0,0 @@ -//! unsupported -//! no-harness -//! expect-exit: -15 -//! expect-stderr: TIMEOUT: Process terminated after 0.25 seconds. -//! timeout: 0.25 - -// no code, so phantom will just sleep forever diff --git a/third_party/phantomjs/test/basics/url-utils.js b/third_party/phantomjs/test/basics/url-utils.js deleted file mode 100644 index 80a5265c73b..00000000000 --- a/third_party/phantomjs/test/basics/url-utils.js +++ /dev/null @@ -1,16 +0,0 @@ -// These are cursory tests; we assume the underlying Qt -// features are properly tested elsewhere. - -test(function () { - assert_equals( - phantom.resolveRelativeUrl( - "../scripts/foo.js", - "http://example.com/topic/page.html"), - "http://example.com/scripts/foo.js"); - - assert_equals( - phantom.fullyDecodeUrl( - "https://ja.wikipedia.org/wiki/%E8%87%A8%E6%B5%B7%E5%AD%A6%E6%A0%A1"), - "https://ja.wikipedia.org/wiki/臨海学校"); - -}, "resolveRelativeUrl and fullyDecodeUrl"); diff --git a/third_party/phantomjs/test/basics/version.js b/third_party/phantomjs/test/basics/version.js deleted file mode 100644 index 39e28dbe349..00000000000 --- a/third_party/phantomjs/test/basics/version.js +++ /dev/null @@ -1,7 +0,0 @@ -// This is separate from basics/phantom-object.js because it has to be -// updated with every release. -test(function () { - assert_equals(phantom.version.major, 0); - assert_equals(phantom.version.minor, 0); - assert_equals(phantom.version.patch, 1); -}, "PhantomJS version number is accurate"); diff --git a/third_party/phantomjs/test/certs/https-snakeoil.crt b/third_party/phantomjs/test/certs/https-snakeoil.crt deleted file mode 100644 index 74e5158f3fc..00000000000 --- a/third_party/phantomjs/test/certs/https-snakeoil.crt +++ /dev/null @@ -1,18 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIC+zCCAeOgAwIBAgIJAJ7HwZBrgnLwMA0GCSqGSIb3DQEBCwUAMBQxEjAQBgNV -BAMMCWxvY2FsaG9zdDAeFw0xNTA4MTEyMjU4MTZaFw0yNTA4MTAyMjU4MTZaMBQx -EjAQBgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC -ggEBANFha8c5JKjYrHc7BTqmuFSAxYsSKbUUa0k+0PFpjhj7Io/NOeHhxfdLJX/B -LVQXEDhvOlSTDBgC3RQkxCZJmMzKZjMDlj0cxY0esZtcqt0sRpwRvT+EBE9SlFu4 -TWM2BQ6k5E4OIX/9aUk9HQ99pSjqmhu/7n76n/5DfqxGwkfVZengI1KwfezaB5+Q -wAvoS7tadROqTyynV1kd+OF9BJZwO1eR9lAiGc139J/BHegVcqdrI043oR+1vyTw -BFpodw4HYdJHNgo7DKAtmXoDAws5myqx2GcnVng1wyzu6LdM65nMV4/p5Y/Y6Ziy -RqeV1gVbtpxTcrLmWFnI8BRwFBUCAwEAAaNQME4wHQYDVR0OBBYEFPP1YOkZpJmE -x/W48Kwv2N1QC1oDMB8GA1UdIwQYMBaAFPP1YOkZpJmEx/W48Kwv2N1QC1oDMAwG -A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAA1NxsrmKxGecAS6TEHNBqFZ -9NhV23kXY5sdv8zl7HUmzR+vIBumd9lkSZdOwAy5/hmj6ACReSJ9f2xpyi0fOtx5 -WZ8Vcrg9Qjuy17qmGi66yL860yr0h6hltzCWCi7e26Eybawm3/9PmbNV3Hcwgxug -D+gv4LZLlyj4JI4lg/8RVXaNXqGBZ39YhRH0LFVjbYiFWUGqzfAT9YBoC67Ov8Yv -Bl1PoV3sJcagx67X6y8ru+gecc/OOXKJHxSidhjRqhKB6WOWIPfugsMOl1g2FMPv -tuPFsIQNSaln7V+ECeDOipJOSp9KAyM5fNcVjldd/e4V+qwcyoOijFywNfSK10M= ------END CERTIFICATE----- diff --git a/third_party/phantomjs/test/certs/https-snakeoil.key b/third_party/phantomjs/test/certs/https-snakeoil.key deleted file mode 100644 index ab989325df6..00000000000 --- a/third_party/phantomjs/test/certs/https-snakeoil.key +++ /dev/null @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDRYWvHOSSo2Kx3 -OwU6prhUgMWLEim1FGtJPtDxaY4Y+yKPzTnh4cX3SyV/wS1UFxA4bzpUkwwYAt0U -JMQmSZjMymYzA5Y9HMWNHrGbXKrdLEacEb0/hARPUpRbuE1jNgUOpORODiF//WlJ -PR0PfaUo6pobv+5++p/+Q36sRsJH1WXp4CNSsH3s2gefkMAL6Eu7WnUTqk8sp1dZ -HfjhfQSWcDtXkfZQIhnNd/SfwR3oFXKnayNON6Eftb8k8ARaaHcOB2HSRzYKOwyg -LZl6AwMLOZsqsdhnJ1Z4NcMs7ui3TOuZzFeP6eWP2OmYskanldYFW7acU3Ky5lhZ -yPAUcBQVAgMBAAECggEAOwI/w8fhAwz9niSuFpeB/57DDayywGveyKfBbygWegfc -97YZCAX/KvCswtKImdheI+mFAOzoTaQQ9mpeNYQsYhrwrpPmNZb0Pg9WcritFuQx -ii6drVbheBGH6kmI1dsVlcj25uCopE+g6pkkpYb9kwh7IjL3XiX4DUqsWpUej+ub -2iL/luW7nYHHIRqzOFgP3v/f29sFHNvYcgihphBMHtgb4VpeYQ/f7AC7k1bFYfA/ -TmvfUcXdiPwJf0XICZOaLrT/6pigk0bRiLNn8npISu7Wlf4jF60bNAe4+krBVU4O -p8UjW99LiGKLDh8GpoudnzlnnngZ3SA5+bO7kwTjCQKBgQDvJwUShOWm2+5wJsr4 -hWieTVDaZEDb+1WTe7DwtqRWNBWXchh8is9buWeXIe6+1WldBYYiQjgdggQCw8xG -IFFg1j1E6kPqk/kzrHYSsJ+/u8uaxypvvrVBhUqt5FduOxFojW2REX9W5n8HTdT4 -32BGR4mGpuXzR+BsVK00QRgM+wKBgQDgIXtu6rbfx+mdXTFi6apWJoyu5bRWcrL2 -mGoR+IjCk6NefcvBE33q54H/dk3+0Sxp6+uFo7lyKv4EL3lozQO2oga6sp2LOIEK -DUo+KQVOmntCNrjuN/PbjSu2s1j5QDnLNR9VvXGiYBWdpZ7k3YzoKJ1I4ZyB3kGs -H/lCXv52LwKBgER1HvaWJEcHXdGsyR0q0y+9Yg+h8w8FexGkrpm5LoGely+q8Wd1 -NLZE9GpGxFjMLkT6d9MGsZmAxjUkZy0Lwz+9E/zOMnLLuOIZ1BK1jIUN9NJxgKxM -IwaGaUItwvlC31DWay7Dm3f8sxAcL4KuLpjvkWaCEAD76joYYxw6JfBRAoGADMe7 -+xolLWN/3bpHq6U5UkpGcV6lxtwpekg8nCO44Kd8hFHWAX90CaYD0qZTUjlpN+z8 -9BTe6TSsYV63pJM0KADbM2Al/Z9ONF2Hoz3BkLbcWm02ZFcKb7WADZ3yb9wKr5yq -2b/AsAqckO21vsUnWMGgHlzHCNy8j+0O0IsMJX8CgYAORhyGaU7x5t4kEvqBNIan -mOzuB0b5nYV9mHxmyFhOsa8LeM25SA4n1rFpTb8h6vmZF1y9+4Zy4uNfCR2wXg0v -I51qtZ8npbIksYvNqvHaTPg8ZBcFK5mHr3TDxXJCcc0ylzM98ze08D+qKr0joX4w -KlqN6KjGmYfb+RHehLk9sw== ------END PRIVATE KEY----- diff --git a/third_party/phantomjs/test/fixtures/dummy.js b/third_party/phantomjs/test/fixtures/dummy.js deleted file mode 100644 index 4def305e706..00000000000 --- a/third_party/phantomjs/test/fixtures/dummy.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = 'spec/dummy'; diff --git a/third_party/phantomjs/test/fixtures/error-helper.js b/third_party/phantomjs/test/fixtures/error-helper.js deleted file mode 100644 index 3619b16da31..00000000000 --- a/third_party/phantomjs/test/fixtures/error-helper.js +++ /dev/null @@ -1,9 +0,0 @@ -ErrorHelper = { - foo: function() { - this.bar() - }, - - bar: function bar() { - referenceError - } -}; diff --git a/third_party/phantomjs/test/fixtures/parse-error-helper.js b/third_party/phantomjs/test/fixtures/parse-error-helper.js deleted file mode 100644 index 5538cb451ca..00000000000 --- a/third_party/phantomjs/test/fixtures/parse-error-helper.js +++ /dev/null @@ -1,2 +0,0 @@ -var ok; -bar("run away" \ No newline at end of file diff --git a/third_party/phantomjs/test/manual/standards/ecma-test262.js b/third_party/phantomjs/test/manual/standards/ecma-test262.js deleted file mode 100644 index edb19941932..00000000000 --- a/third_party/phantomjs/test/manual/standards/ecma-test262.js +++ /dev/null @@ -1,36 +0,0 @@ -// Launch the official test suite for ECMA-262 - -var webpage = require('webpage'); - -page = webpage.create(); -page.onError = function() {}; - -page.open('http://test262.ecmascript.org/', function() { - page.evaluate(function() { $('a#run').click(); }); - page.evaluate(function() { $('img#btnRunAll').click(); }); - - function monitor() { - - var data = page.evaluate(function() { - return { - ran: $('#totalCounter').text(), - total: $('#testsToRun').text(), - pass: $('#Pass').text(), - fail: $('#Fail').text(), - progress: $('div#progressbar').text() - }; - }); - - console.log('Tests: ', data.ran, 'of', data.total, - ' Pass:', data.pass, ' Fail:', data.fail); - - if (data.progress.indexOf('complete') > 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 deleted file mode 100644 index 4c9e4cc4c76..00000000000 --- a/third_party/phantomjs/test/module/cookiejar/cookiejar.js +++ /dev/null @@ -1,93 +0,0 @@ -//! 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 deleted file mode 100644 index 7528e3fc578..00000000000 --- a/third_party/phantomjs/test/module/cookiejar/to-map.js +++ /dev/null @@ -1,52 +0,0 @@ -//! 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 deleted file mode 100644 index c522ab7f299..00000000000 --- a/third_party/phantomjs/test/module/fs/basics.js +++ /dev/null @@ -1,220 +0,0 @@ -// 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 deleted file mode 100644 index f973abbaeb2..00000000000 --- a/third_party/phantomjs/test/module/fs/fileattrs.js +++ /dev/null @@ -1,91 +0,0 @@ - -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 deleted file mode 100644 index 0910f20bb3d..00000000000 --- a/third_party/phantomjs/test/module/fs/paths.js +++ /dev/null @@ -1,72 +0,0 @@ - -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 deleted file mode 100644 index 8a08f2631cf..00000000000 --- a/third_party/phantomjs/test/module/system/stdin.js +++ /dev/null @@ -1,22 +0,0 @@ -//! 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 deleted file mode 100644 index 2281b42fdd8..00000000000 --- a/third_party/phantomjs/test/module/system/stdout-err.js +++ /dev/null @@ -1,14 +0,0 @@ -//! 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 deleted file mode 100644 index ae5422d041b..00000000000 --- a/third_party/phantomjs/test/module/system/system.js +++ /dev/null @@ -1,77 +0,0 @@ -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 deleted file mode 100644 index 06430e14b0a..00000000000 --- a/third_party/phantomjs/test/module/webpage/abort-network-request.js +++ /dev/null @@ -1,36 +0,0 @@ -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", { timeout: 5000 }); diff --git a/third_party/phantomjs/test/module/webpage/add-header.js b/third_party/phantomjs/test/module/webpage/add-header.js deleted file mode 100644 index 46b70bb1b0e..00000000000 --- a/third_party/phantomjs/test/module/webpage/add-header.js +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index c8edb1b4b8c..00000000000 --- a/third_party/phantomjs/test/module/webpage/callback.js +++ /dev/null @@ -1,16 +0,0 @@ -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", { expected_fail : true }); diff --git a/third_party/phantomjs/test/module/webpage/capture-content.js b/third_party/phantomjs/test/module/webpage/capture-content.js deleted file mode 100644 index 99f64ad57c4..00000000000 --- a/third_party/phantomjs/test/module/webpage/capture-content.js +++ /dev/null @@ -1,50 +0,0 @@ -//! 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 deleted file mode 100644 index 37778a73e6c..00000000000 --- a/third_party/phantomjs/test/module/webpage/change-request-encoded-url.js +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index ea8e7e8a583..00000000000 --- a/third_party/phantomjs/test/module/webpage/change-request-url.js +++ /dev/null @@ -1,40 +0,0 @@ -//! 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 deleted file mode 100644 index afd653c6982..00000000000 --- a/third_party/phantomjs/test/module/webpage/cjk-text-codecs.js +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index 46c9e40d840..00000000000 --- a/third_party/phantomjs/test/module/webpage/clip-rect.js +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 42d67371d49..00000000000 --- a/third_party/phantomjs/test/module/webpage/construction-with-options.js +++ /dev/null @@ -1,59 +0,0 @@ -//! 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 deleted file mode 100644 index 7716ba51f9f..00000000000 --- a/third_party/phantomjs/test/module/webpage/contextclick-event.js +++ /dev/null @@ -1,32 +0,0 @@ -test(function () { - var page = require('webpage').create(); - - page.evaluate(function() { - window.addEventListener('contextmenu', function(event) { - window.loggedEvent = window.loggedEvent || {}; - window.loggedEvent.contextmenu = {clientX: event.clientX, clientY: event.clientY, shiftKey: event.shiftKey}; - }, 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 = {clientX: event.clientX, clientY: event.clientY, shiftKey: event.shiftKey}; - }, 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 deleted file mode 100644 index 344dffb1916..00000000000 --- a/third_party/phantomjs/test/module/webpage/cookies.js +++ /dev/null @@ -1,112 +0,0 @@ -async_test(function () { - var url = TEST_HTTP_BASE + "echo"; - var webpage = require('webpage'); - - var page = webpage.create(); - - 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()/1000) + 3600 - }]; - - 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 webpage = require('webpage'); - - var page = webpage.create(); - - 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 webpage = require('webpage'); - - var page = webpage.create(); - - 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' : 5 - },{ // 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' : (Date.now()/1000) - 10 //< 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 deleted file mode 100644 index 0aaefd79dc7..00000000000 --- a/third_party/phantomjs/test/module/webpage/custom-headers.js +++ /dev/null @@ -1,30 +0,0 @@ -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 deleted file mode 100644 index 1f1d263598e..00000000000 --- a/third_party/phantomjs/test/module/webpage/evaluate-broken-json.js +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 780ffd7bcaa..00000000000 --- a/third_party/phantomjs/test/module/webpage/file-upload.js +++ /dev/null @@ -1,54 +0,0 @@ -// Note: uses various files in module/webpage as things to be uploaded. -// Which files they are doesn't matter. - -var page; -setup(function () { - page = require('webpage').create(); - 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].name); - } - 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: false }); - -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 deleted file mode 100644 index 54e5b7484ef..00000000000 --- a/third_party/phantomjs/test/module/webpage/frame-switching-deprecated.js +++ /dev/null @@ -1,68 +0,0 @@ -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 deleted file mode 100644 index a821320330f..00000000000 --- a/third_party/phantomjs/test/module/webpage/frame-switching.js +++ /dev/null @@ -1,97 +0,0 @@ -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 deleted file mode 100644 index fcdb7d4878b..00000000000 --- a/third_party/phantomjs/test/module/webpage/https-bad-cert.js +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index af9cf075c83..00000000000 --- a/third_party/phantomjs/test/module/webpage/https-good-cert.js +++ /dev/null @@ -1,14 +0,0 @@ -//! 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 deleted file mode 100644 index df3d922ebb2..00000000000 --- a/third_party/phantomjs/test/module/webpage/includejs.js +++ /dev/null @@ -1,42 +0,0 @@ -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 deleted file mode 100644 index ec9d52edf63..00000000000 --- a/third_party/phantomjs/test/module/webpage/keydown-event.js +++ /dev/null @@ -1,20 +0,0 @@ -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.which); - }, 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], 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 deleted file mode 100644 index b3b86ca77b5..00000000000 --- a/third_party/phantomjs/test/module/webpage/keypress-event.js +++ /dev/null @@ -1,67 +0,0 @@ -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.which); - }, 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], 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(), ''); - - - // Joel: This works, but it causes you to lose your clipboard when running the tests. - // 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', page.event.key.Cut); - // assert_equals(getText(), ''); - // page.sendEvent('keypress', page.event.key.Paste); - // 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 deleted file mode 100644 index 383582a6869..00000000000 --- a/third_party/phantomjs/test/module/webpage/keyup-event.js +++ /dev/null @@ -1,20 +0,0 @@ -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.which); - }, 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], 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 deleted file mode 100644 index 6af3324429d..00000000000 --- a/third_party/phantomjs/test/module/webpage/loading.js +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index 3144299b318..00000000000 --- a/third_party/phantomjs/test/module/webpage/local-urls-disabled-iframe.js +++ /dev/null @@ -1,23 +0,0 @@ -//! 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 deleted file mode 100644 index 07853d86e8f..00000000000 --- a/third_party/phantomjs/test/module/webpage/local-urls-disabled.js +++ /dev/null @@ -1,22 +0,0 @@ -//! 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 deleted file mode 100644 index 76d05a5aade..00000000000 --- a/third_party/phantomjs/test/module/webpage/local-urls-enabled-iframe.js +++ /dev/null @@ -1,23 +0,0 @@ -//! 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 deleted file mode 100644 index b3f74bf5de5..00000000000 --- a/third_party/phantomjs/test/module/webpage/local-urls-enabled.js +++ /dev/null @@ -1,23 +0,0 @@ -//! 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 deleted file mode 100644 index e8ce46a9c01..00000000000 --- a/third_party/phantomjs/test/module/webpage/long-running-javascript.js +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index b7ba7814a5f..00000000000 --- a/third_party/phantomjs/test/module/webpage/modify-header.js +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index 917c91a487b..00000000000 --- a/third_party/phantomjs/test/module/webpage/mouseclick-event.js +++ /dev/null @@ -1,38 +0,0 @@ -test(function () { - var page = require('webpage').create(); - - page.evaluate(function() { - window.addEventListener('mousedown', function(event) { - window.loggedEvent = window.loggedEvent || {}; - window.loggedEvent.mousedown = {clientX: event.clientX, clientY: event.clientY, shiftKey: event.shiftKey}; - }, false); - window.addEventListener('mouseup', function(event) { - window.loggedEvent = window.loggedEvent || {}; - window.loggedEvent.mouseup = {clientX: event.clientX, clientY: event.clientY, shiftKey: event.shiftKey}; - }, 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 = {clientX: event.clientX, clientY: event.clientY, shiftKey: event.shiftKey}; - }, 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 deleted file mode 100644 index f98dd2cd750..00000000000 --- a/third_party/phantomjs/test/module/webpage/mousedoubleclick-event.js +++ /dev/null @@ -1,30 +0,0 @@ -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 = {clientX: event.clientX, clientY: event.clientY, shiftKey: event.shiftKey}; - }, 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 deleted file mode 100644 index e79fa85af45..00000000000 --- a/third_party/phantomjs/test/module/webpage/mousedown-event.js +++ /dev/null @@ -1,26 +0,0 @@ -test(function () { - var page = require('webpage').create(); - - page.evaluate(function() { - window.addEventListener('mousedown', function(event) { - window.loggedEvent = window.loggedEvent || []; - window.loggedEvent.push({clientX: event.clientX, clientY: event.clientY, shiftKey: event.shiftKey}); - }, 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 deleted file mode 100644 index ece419a0a21..00000000000 --- a/third_party/phantomjs/test/module/webpage/mousemove-event.js +++ /dev/null @@ -1,18 +0,0 @@ -test(function () { - var page = require('webpage').create(); - - page.evaluate(function() { - window.addEventListener('mousemove', function(event) { - window.loggedEvent = window.loggedEvent || []; - window.loggedEvent.push({clientX: event.clientX, clientY: event.clientY}); - }, 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 deleted file mode 100644 index e4b973821f5..00000000000 --- a/third_party/phantomjs/test/module/webpage/mouseup-event.js +++ /dev/null @@ -1,26 +0,0 @@ -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({clientX: event.clientX, clientY: event.clientY, shiftKey: event.shiftKey}); - }, 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 deleted file mode 100644 index 41c1509419f..00000000000 --- a/third_party/phantomjs/test/module/webpage/navigation.js +++ /dev/null @@ -1,31 +0,0 @@ -//! 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 deleted file mode 100644 index 1e563f2a9b9..00000000000 --- a/third_party/phantomjs/test/module/webpage/no-plugin.js +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index d0920e28120..00000000000 --- a/third_party/phantomjs/test/module/webpage/object.js +++ /dev/null @@ -1,77 +0,0 @@ -//! 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 deleted file mode 100644 index f4f6e31c872..00000000000 --- a/third_party/phantomjs/test/module/webpage/on-confirm.js +++ /dev/null @@ -1,33 +0,0 @@ -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"); diff --git a/third_party/phantomjs/test/module/webpage/on-error.js b/third_party/phantomjs/test/module/webpage/on-error.js deleted file mode 100644 index f5f892a7645..00000000000 --- a/third_party/phantomjs/test/module/webpage/on-error.js +++ /dev/null @@ -1,110 +0,0 @@ -//! 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 deleted file mode 100644 index 3f8c735c118..00000000000 --- a/third_party/phantomjs/test/module/webpage/on-initialized.js +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index ff7ef855a70..00000000000 --- a/third_party/phantomjs/test/module/webpage/open.js +++ /dev/null @@ -1,53 +0,0 @@ -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 deleted file mode 100644 index dd3d725fa92..00000000000 --- a/third_party/phantomjs/test/module/webpage/postdata.js +++ /dev/null @@ -1,47 +0,0 @@ -//! 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 deleted file mode 100644 index d1f099e4ada..00000000000 --- a/third_party/phantomjs/test/module/webpage/prompt.js +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index 900a870fe2d..00000000000 --- a/third_party/phantomjs/test/module/webpage/remove-header.js +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index 7a1fb4343fe..00000000000 --- a/third_party/phantomjs/test/module/webpage/render.js +++ /dev/null @@ -1,68 +0,0 @@ -//! unsupported -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 deleted file mode 100644 index 47e83b6a7ea..00000000000 --- a/third_party/phantomjs/test/module/webpage/renders/index.js +++ /dev/null @@ -1,7 +0,0 @@ -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 deleted file mode 100644 index b597dba47fb..00000000000 Binary files a/third_party/phantomjs/test/module/webpage/renders/test.jpg and /dev/null differ diff --git a/third_party/phantomjs/test/module/webpage/renders/test.pdf b/third_party/phantomjs/test/module/webpage/renders/test.pdf deleted file mode 100644 index b1beecd1d73..00000000000 Binary files a/third_party/phantomjs/test/module/webpage/renders/test.pdf and /dev/null differ diff --git a/third_party/phantomjs/test/module/webpage/renders/test.png b/third_party/phantomjs/test/module/webpage/renders/test.png deleted file mode 100644 index 7932eeb11bb..00000000000 Binary files a/third_party/phantomjs/test/module/webpage/renders/test.png and /dev/null differ diff --git a/third_party/phantomjs/test/module/webpage/renders/test50.jpg b/third_party/phantomjs/test/module/webpage/renders/test50.jpg deleted file mode 100644 index a3e04420682..00000000000 Binary files a/third_party/phantomjs/test/module/webpage/renders/test50.jpg and /dev/null differ diff --git a/third_party/phantomjs/test/module/webpage/repaint-requested.js b/third_party/phantomjs/test/module/webpage/repaint-requested.js deleted file mode 100644 index bb3bb355d5e..00000000000 --- a/third_party/phantomjs/test/module/webpage/repaint-requested.js +++ /dev/null @@ -1,20 +0,0 @@ -//! 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 deleted file mode 100644 index dae581e1115..00000000000 --- a/third_party/phantomjs/test/module/webpage/resource-received-error.js +++ /dev/null @@ -1,33 +0,0 @@ -//! 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 deleted file mode 100644 index 0f150362392..00000000000 --- a/third_party/phantomjs/test/module/webpage/resource-request-error.js +++ /dev/null @@ -1,27 +0,0 @@ -//! 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 deleted file mode 100644 index a1550531a14..00000000000 --- a/third_party/phantomjs/test/module/webpage/scroll-position.js +++ /dev/null @@ -1,18 +0,0 @@ -//! 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 deleted file mode 100644 index 52e823368c1..00000000000 --- a/third_party/phantomjs/test/module/webpage/set-content.js +++ /dev/null @@ -1,20 +0,0 @@ -//! 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 deleted file mode 100644 index 392b664d6a8..00000000000 --- a/third_party/phantomjs/test/module/webpage/subwindows.js +++ /dev/null @@ -1,130 +0,0 @@ -//! 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 deleted file mode 100644 index d0026dc40cc..00000000000 --- a/third_party/phantomjs/test/module/webpage/url-encoding.js +++ /dev/null @@ -1,134 +0,0 @@ -//! 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 deleted file mode 100644 index 1dc1962ea8e..00000000000 --- a/third_party/phantomjs/test/module/webpage/user-agent.js +++ /dev/null @@ -1,22 +0,0 @@ -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 deleted file mode 100644 index dc2412c2793..00000000000 --- a/third_party/phantomjs/test/module/webpage/viewport-size.js +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index c8ddaaf63ce..00000000000 --- a/third_party/phantomjs/test/module/webpage/window.js +++ /dev/null @@ -1,4 +0,0 @@ -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 deleted file mode 100644 index f8f447e4eca..00000000000 --- a/third_party/phantomjs/test/module/webpage/zoom-factor.js +++ /dev/null @@ -1,18 +0,0 @@ -//! 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 deleted file mode 100644 index 4f124cc4202..00000000000 --- a/third_party/phantomjs/test/module/webserver/basics.js +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index f8d4e8b9f1f..00000000000 --- a/third_party/phantomjs/test/module/webserver/requests.js +++ /dev/null @@ -1,179 +0,0 @@ -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": 3000 }); - -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 deleted file mode 100644 index 143519bddd5..00000000000 --- a/third_party/phantomjs/test/node_modules/dummy_exposed.js +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index a18d8a9185a..00000000000 --- a/third_party/phantomjs/test/node_modules/dummy_file.js +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 77e02ec1ebf..00000000000 --- a/third_party/phantomjs/test/node_modules/dummy_file2.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = 'spec/node_modules/dummy_file2'; diff --git a/third_party/phantomjs/test/regression/README b/third_party/phantomjs/test/regression/README deleted file mode 100644 index 2e8394c9e3d..00000000000 --- a/third_party/phantomjs/test/regression/README +++ /dev/null @@ -1,3 +0,0 @@ -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 deleted file mode 100644 index 7e45c82d45e..00000000000 --- a/third_party/phantomjs/test/regression/pjs-10690.js +++ /dev/null @@ -1,14 +0,0 @@ -// 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 deleted file mode 100644 index 7df89dd3540..00000000000 --- a/third_party/phantomjs/test/regression/pjs-12482.js +++ /dev/null @@ -1,48 +0,0 @@ -//! 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 deleted file mode 100644 index 73236b2cb9d..00000000000 --- a/third_party/phantomjs/test/regression/pjs-13551.js +++ /dev/null @@ -1,52 +0,0 @@ -//! 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 deleted file mode 100644 index 46280936f6a..00000000000 --- a/third_party/phantomjs/test/regression/webkit-60448.js +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100755 index 038dda6d2cc..00000000000 --- a/third_party/phantomjs/test/run-tests.py +++ /dev/null @@ -1,1051 +0,0 @@ -#!/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 ["node", self.phantomjs_exe] - elif debugger == "gdb": - return ["gdb", "--args", "node", self.phantomjs_exe] - elif debugger == "lldb": - return ["lldb", "--", "node", self.phantomjs_exe] - elif debugger == "valgrind": - return ["valgrind", "node", 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 + '/../../../phantom_shim/runner.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 deleted file mode 100644 index 7b17aba81c8..00000000000 --- a/third_party/phantomjs/test/standards/console/console_log.js +++ /dev/null @@ -1,9 +0,0 @@ -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 deleted file mode 100644 index b2a1f97f83a..00000000000 --- a/third_party/phantomjs/test/standards/javascript/date.js +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 2b6f4734c76..00000000000 --- a/third_party/phantomjs/test/standards/javascript/function.js +++ /dev/null @@ -1,46 +0,0 @@ -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 deleted file mode 100644 index 706048b3d79..00000000000 --- a/third_party/phantomjs/test/testharness.js +++ /dev/null @@ -1,1489 +0,0 @@ -/* 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 deleted file mode 100644 index c04f27beaa0..00000000000 --- a/third_party/phantomjs/test/writing-tests.md +++ /dev/null @@ -1,596 +0,0 @@ -# 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 deleted file mode 100644 index b2858867a75..00000000000 --- a/third_party/phantomjs/test/www/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# 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 deleted file mode 100644 index 9653499eb8b..00000000000 --- a/third_party/phantomjs/test/www/delay.py +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index 8a7ba2d9693..00000000000 --- a/third_party/phantomjs/test/www/echo.py +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index c80ec458368..00000000000 --- a/third_party/phantomjs/test/www/frameset/frame1-1.html +++ /dev/null @@ -1,8 +0,0 @@ - - - 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 deleted file mode 100644 index b0c38d2f4a3..00000000000 --- a/third_party/phantomjs/test/www/frameset/frame1-2.html +++ /dev/null @@ -1,8 +0,0 @@ - - - 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 deleted file mode 100644 index b23c274193c..00000000000 --- a/third_party/phantomjs/test/www/frameset/frame1.html +++ /dev/null @@ -1,9 +0,0 @@ - - - frame1 - - - - - - diff --git a/third_party/phantomjs/test/www/frameset/frame2-1.html b/third_party/phantomjs/test/www/frameset/frame2-1.html deleted file mode 100644 index 2f7c121a9ff..00000000000 --- a/third_party/phantomjs/test/www/frameset/frame2-1.html +++ /dev/null @@ -1,8 +0,0 @@ - - - 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 deleted file mode 100644 index 99f603d78f6..00000000000 --- a/third_party/phantomjs/test/www/frameset/frame2-2.html +++ /dev/null @@ -1,8 +0,0 @@ - - - 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 deleted file mode 100644 index b6f18089dec..00000000000 --- a/third_party/phantomjs/test/www/frameset/frame2-3.html +++ /dev/null @@ -1,8 +0,0 @@ - - - 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 deleted file mode 100644 index d3484bd15cc..00000000000 --- a/third_party/phantomjs/test/www/frameset/frame2.html +++ /dev/null @@ -1,10 +0,0 @@ - - - frame2 - - - - - - - diff --git a/third_party/phantomjs/test/www/frameset/index.html b/third_party/phantomjs/test/www/frameset/index.html deleted file mode 100644 index dbe01bb5d02..00000000000 --- a/third_party/phantomjs/test/www/frameset/index.html +++ /dev/null @@ -1,9 +0,0 @@ - - - index - - - - - - diff --git a/third_party/phantomjs/test/www/hello.html b/third_party/phantomjs/test/www/hello.html deleted file mode 100644 index ee4bc5924a5..00000000000 --- a/third_party/phantomjs/test/www/hello.html +++ /dev/null @@ -1,8 +0,0 @@ - - - Hello - - -

Hello, world!

- - diff --git a/third_party/phantomjs/test/www/iframe.html b/third_party/phantomjs/test/www/iframe.html deleted file mode 100644 index ce62c6dc654..00000000000 --- a/third_party/phantomjs/test/www/iframe.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - diff --git a/third_party/phantomjs/test/www/includejs.js b/third_party/phantomjs/test/www/includejs.js deleted file mode 100644 index 5c0e4bd619a..00000000000 --- a/third_party/phantomjs/test/www/includejs.js +++ /dev/null @@ -1,3 +0,0 @@ -function getTitle () { - return document.title; -} diff --git a/third_party/phantomjs/test/www/includejs1.html b/third_party/phantomjs/test/www/includejs1.html deleted file mode 100644 index 4be4b1fb603..00000000000 --- a/third_party/phantomjs/test/www/includejs1.html +++ /dev/null @@ -1,2 +0,0 @@ - -i am includejs one diff --git a/third_party/phantomjs/test/www/includejs2.html b/third_party/phantomjs/test/www/includejs2.html deleted file mode 100644 index 89aeab2a62a..00000000000 --- a/third_party/phantomjs/test/www/includejs2.html +++ /dev/null @@ -1,2 +0,0 @@ - -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 deleted file mode 100644 index 6dcb77525c0..00000000000 --- a/third_party/phantomjs/test/www/js-infinite-loop.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/third_party/phantomjs/test/www/logo.html b/third_party/phantomjs/test/www/logo.html deleted file mode 100644 index 1323ffdf5a4..00000000000 --- a/third_party/phantomjs/test/www/logo.html +++ /dev/null @@ -1,8 +0,0 @@ - - - Show logo - - - - - diff --git a/third_party/phantomjs/test/www/logo.png b/third_party/phantomjs/test/www/logo.png deleted file mode 100644 index 7b44e54189f..00000000000 Binary files a/third_party/phantomjs/test/www/logo.png and /dev/null differ diff --git a/third_party/phantomjs/test/www/missing-img.html b/third_party/phantomjs/test/www/missing-img.html deleted file mode 100644 index cc142eca16b..00000000000 --- a/third_party/phantomjs/test/www/missing-img.html +++ /dev/null @@ -1,8 +0,0 @@ - - - Missing image - - - - - diff --git a/third_party/phantomjs/test/www/navigation/dest.html b/third_party/phantomjs/test/www/navigation/dest.html deleted file mode 100644 index e336f9cbb3e..00000000000 --- a/third_party/phantomjs/test/www/navigation/dest.html +++ /dev/null @@ -1,2 +0,0 @@ - -DEST diff --git a/third_party/phantomjs/test/www/navigation/index.html b/third_party/phantomjs/test/www/navigation/index.html deleted file mode 100644 index 9d3b35f2d1d..00000000000 --- a/third_party/phantomjs/test/www/navigation/index.html +++ /dev/null @@ -1,2 +0,0 @@ - -INDEX diff --git a/third_party/phantomjs/test/www/phantomjs.png b/third_party/phantomjs/test/www/phantomjs.png deleted file mode 100644 index 381a3789b75..00000000000 Binary files a/third_party/phantomjs/test/www/phantomjs.png and /dev/null 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 deleted file mode 100644 index 22c8e697c7b..00000000000 Binary files a/third_party/phantomjs/test/www/regression/pjs-10690/Windsong.ttf and /dev/null 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 deleted file mode 100644 index 959d531cb35..00000000000 --- a/third_party/phantomjs/test/www/regression/pjs-10690/font.css +++ /dev/null @@ -1,7 +0,0 @@ -@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 deleted file mode 100644 index 6d4d3cfb12d..00000000000 --- a/third_party/phantomjs/test/www/regression/pjs-10690/index.html +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - -

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 deleted file mode 100644 index f66a95ce6cb..00000000000 --- a/third_party/phantomjs/test/www/regression/pjs-10690/jquery.js +++ /dev/null @@ -1,9441 +0,0 @@ -/*! - * 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 deleted file mode 100644 index 1f9ee6573d9..00000000000 --- a/third_party/phantomjs/test/www/regression/pjs-13551/child1.html +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/third_party/phantomjs/test/www/regression/pjs-13551/child1a.html b/third_party/phantomjs/test/www/regression/pjs-13551/child1a.html deleted file mode 100644 index fdaa7f100d1..00000000000 --- a/third_party/phantomjs/test/www/regression/pjs-13551/child1a.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - diff --git a/third_party/phantomjs/test/www/regression/pjs-13551/child2.html b/third_party/phantomjs/test/www/regression/pjs-13551/child2.html deleted file mode 100644 index 93322fc8179..00000000000 --- a/third_party/phantomjs/test/www/regression/pjs-13551/child2.html +++ /dev/null @@ -1,9 +0,0 @@ - - - - -

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 deleted file mode 100644 index 5ad4d2bd91d..00000000000 --- a/third_party/phantomjs/test/www/regression/pjs-13551/closing-parent.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - 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 deleted file mode 100644 index 6364ec6c2f5..00000000000 --- a/third_party/phantomjs/test/www/regression/pjs-13551/reloading-parent.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - diff --git a/third_party/phantomjs/test/www/regression/webkit-60448.html b/third_party/phantomjs/test/www/regression/webkit-60448.html deleted file mode 100644 index 1de358b3cd4..00000000000 --- a/third_party/phantomjs/test/www/regression/webkit-60448.html +++ /dev/null @@ -1,15 +0,0 @@ - - -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 deleted file mode 100644 index 53de7f6f13f..00000000000 Binary files a/third_party/phantomjs/test/www/render/image.jpg and /dev/null differ diff --git a/third_party/phantomjs/test/www/render/index.html b/third_party/phantomjs/test/www/render/index.html deleted file mode 100644 index aa7e80f24a2..00000000000 --- a/third_party/phantomjs/test/www/render/index.html +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - diff --git a/third_party/phantomjs/test/www/status.py b/third_party/phantomjs/test/www/status.py deleted file mode 100644 index e7a1c3e403f..00000000000 --- a/third_party/phantomjs/test/www/status.py +++ /dev/null @@ -1,50 +0,0 @@ -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 deleted file mode 100644 index 300dfdcba35..00000000000 --- a/third_party/phantomjs/test/www/url-encoding.py +++ /dev/null @@ -1,85 +0,0 @@ -# -*- 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 deleted file mode 100644 index adab8e830d7..00000000000 --- a/third_party/phantomjs/test/www/user-agent.html +++ /dev/null @@ -1,9 +0,0 @@ - - -User Agent - - -

User agent is: Unknown.

- - -