From e36e57be7b39bf934a0a9049f5edf375985e0dc8 Mon Sep 17 00:00:00 2001 From: Teko012 <112829523+Teko012@users.noreply.github.com> Date: Sat, 22 Oct 2022 22:30:34 +0200 Subject: [PATCH 1/3] Update packages Update to latest packages --- node_modules/.bin/uuid | 1 + node_modules/.package-lock.json | 65 + node_modules/@actions/core/LICENSE.md | 9 + node_modules/@actions/core/README.md | 209 +- node_modules/@actions/core/lib/command.d.ts | 13 +- node_modules/@actions/core/lib/command.js | 60 +- node_modules/@actions/core/lib/command.js.map | 2 +- node_modules/@actions/core/lib/core.d.ts | 112 +- node_modules/@actions/core/lib/core.js | 177 +- node_modules/@actions/core/lib/core.js.map | 2 +- .../@actions/core/lib/file-command.d.ts | 2 + .../@actions/core/lib/file-command.js | 58 + .../@actions/core/lib/file-command.js.map | 1 + .../@actions/core/lib/oidc-utils.d.ts | 7 + node_modules/@actions/core/lib/oidc-utils.js | 77 + .../@actions/core/lib/oidc-utils.js.map | 1 + .../@actions/core/lib/path-utils.d.ts | 25 + node_modules/@actions/core/lib/path-utils.js | 58 + .../@actions/core/lib/path-utils.js.map | 1 + node_modules/@actions/core/lib/summary.d.ts | 202 + node_modules/@actions/core/lib/summary.js | 283 + node_modules/@actions/core/lib/summary.js.map | 1 + node_modules/@actions/core/lib/utils.d.ts | 14 + node_modules/@actions/core/lib/utils.js | 40 + node_modules/@actions/core/lib/utils.js.map | 1 + node_modules/@actions/core/package.json | 67 +- node_modules/@actions/http-client/LICENSE | 21 + node_modules/@actions/http-client/README.md | 73 + .../@actions/http-client/lib/auth.d.ts | 26 + node_modules/@actions/http-client/lib/auth.js | 81 + .../@actions/http-client/lib/auth.js.map | 1 + .../@actions/http-client/lib/index.d.ts | 123 + .../@actions/http-client/lib/index.js | 605 ++ .../@actions/http-client/lib/index.js.map | 1 + .../@actions/http-client/lib/interfaces.d.ts | 44 + .../@actions/http-client/lib/interfaces.js | 3 + .../http-client/lib/interfaces.js.map | 1 + .../@actions/http-client/lib/proxy.d.ts | 2 + .../@actions/http-client/lib/proxy.js | 61 + .../@actions/http-client/lib/proxy.js.map | 1 + .../@actions/http-client/package.json | 48 + node_modules/minimist/.eslintrc | 54 + node_modules/minimist/.github/FUNDING.yml | 12 + node_modules/minimist/.nycrc | 14 + node_modules/minimist/.travis.yml | 8 - node_modules/minimist/CHANGELOG.md | 212 + .../minimist/{readme.markdown => README.md} | 56 +- node_modules/minimist/example/parse.js | 2 +- node_modules/minimist/index.js | 19 +- node_modules/minimist/package.json | 109 +- node_modules/minimist/test/bool.js | 12 + node_modules/minimist/test/proto.js | 60 + node_modules/tunnel/.travis.yml | 6 + node_modules/tunnel/CHANGELOG.md | 22 + node_modules/tunnel/LICENSE | 21 + node_modules/tunnel/README.md | 185 + node_modules/tunnel/index.js | 1 + node_modules/tunnel/lib/tunnel.js | 264 + node_modules/tunnel/package.json | 34 + node_modules/uuid/CHANGELOG.md | 229 + node_modules/uuid/CONTRIBUTING.md | 18 + node_modules/uuid/LICENSE.md | 9 + node_modules/uuid/README.md | 505 + node_modules/uuid/dist/bin/uuid | 2 + node_modules/uuid/dist/esm-browser/index.js | 9 + node_modules/uuid/dist/esm-browser/md5.js | 215 + node_modules/uuid/dist/esm-browser/nil.js | 1 + node_modules/uuid/dist/esm-browser/parse.js | 35 + node_modules/uuid/dist/esm-browser/regex.js | 1 + node_modules/uuid/dist/esm-browser/rng.js | 19 + node_modules/uuid/dist/esm-browser/sha1.js | 96 + .../uuid/dist/esm-browser/stringify.js | 30 + node_modules/uuid/dist/esm-browser/v1.js | 95 + node_modules/uuid/dist/esm-browser/v3.js | 4 + node_modules/uuid/dist/esm-browser/v35.js | 64 + node_modules/uuid/dist/esm-browser/v4.js | 24 + node_modules/uuid/dist/esm-browser/v5.js | 4 + .../uuid/dist/esm-browser/validate.js | 7 + node_modules/uuid/dist/esm-browser/version.js | 11 + node_modules/uuid/dist/esm-node/index.js | 9 + node_modules/uuid/dist/esm-node/md5.js | 13 + node_modules/uuid/dist/esm-node/nil.js | 1 + node_modules/uuid/dist/esm-node/parse.js | 35 + node_modules/uuid/dist/esm-node/regex.js | 1 + node_modules/uuid/dist/esm-node/rng.js | 12 + node_modules/uuid/dist/esm-node/sha1.js | 13 + node_modules/uuid/dist/esm-node/stringify.js | 29 + node_modules/uuid/dist/esm-node/v1.js | 95 + node_modules/uuid/dist/esm-node/v3.js | 4 + node_modules/uuid/dist/esm-node/v35.js | 64 + node_modules/uuid/dist/esm-node/v4.js | 24 + node_modules/uuid/dist/esm-node/v5.js | 4 + node_modules/uuid/dist/esm-node/validate.js | 7 + node_modules/uuid/dist/esm-node/version.js | 11 + node_modules/uuid/dist/index.js | 79 + node_modules/uuid/dist/md5-browser.js | 223 + node_modules/uuid/dist/md5.js | 23 + node_modules/uuid/dist/nil.js | 8 + node_modules/uuid/dist/parse.js | 45 + node_modules/uuid/dist/regex.js | 8 + node_modules/uuid/dist/rng-browser.js | 26 + node_modules/uuid/dist/rng.js | 24 + node_modules/uuid/dist/sha1-browser.js | 104 + node_modules/uuid/dist/sha1.js | 23 + node_modules/uuid/dist/stringify.js | 39 + node_modules/uuid/dist/umd/uuid.min.js | 1 + node_modules/uuid/dist/umd/uuidNIL.min.js | 1 + node_modules/uuid/dist/umd/uuidParse.min.js | 1 + .../uuid/dist/umd/uuidStringify.min.js | 1 + .../uuid/dist/umd/uuidValidate.min.js | 1 + node_modules/uuid/dist/umd/uuidVersion.min.js | 1 + node_modules/uuid/dist/umd/uuidv1.min.js | 1 + node_modules/uuid/dist/umd/uuidv3.min.js | 1 + node_modules/uuid/dist/umd/uuidv4.min.js | 1 + node_modules/uuid/dist/umd/uuidv5.min.js | 1 + node_modules/uuid/dist/uuid-bin.js | 85 + node_modules/uuid/dist/v1.js | 107 + node_modules/uuid/dist/v3.js | 16 + node_modules/uuid/dist/v35.js | 78 + node_modules/uuid/dist/v4.js | 37 + node_modules/uuid/dist/v5.js | 16 + node_modules/uuid/dist/validate.js | 17 + node_modules/uuid/dist/version.js | 21 + node_modules/uuid/package.json | 135 + node_modules/uuid/wrapper.mjs | 10 + node_modules/xmldom/.npmignore | 5 - node_modules/xmldom/.travis.yml | 22 - node_modules/xmldom/CHANGELOG.md | 228 + node_modules/xmldom/LICENSE | 10 +- node_modules/xmldom/__package__.js | 4 - node_modules/xmldom/changelog | 14 - node_modules/xmldom/component.json | 10 - node_modules/xmldom/lib/.eslintrc.yml | 2 + node_modules/xmldom/{ => lib}/dom-parser.js | 40 +- node_modules/xmldom/{ => lib}/dom.js | 83 +- node_modules/xmldom/lib/entities.js | 243 + node_modules/xmldom/{ => lib}/sax.js | 101 +- node_modules/xmldom/package.json | 148 +- node_modules/xmldom/readme.md | 75 +- node_modules/xpath/.npmignore | 1 - node_modules/xpath/LICENSE | 22 + node_modules/xpath/docs/XPathEvaluator.md | 12 +- node_modules/xpath/docs/function resolvers.md | 30 +- node_modules/xpath/package.json | 59 +- node_modules/xpath/test.js | 2082 ++-- node_modules/xpath/xpath.d.ts | 8 +- node_modules/xpath/xpath.js | 9111 +++++++++-------- package-lock.json | 97 +- package.json | 8 +- 149 files changed, 12832 insertions(+), 6087 deletions(-) create mode 120000 node_modules/.bin/uuid create mode 100644 node_modules/.package-lock.json create mode 100644 node_modules/@actions/core/LICENSE.md create mode 100644 node_modules/@actions/core/lib/file-command.d.ts create mode 100644 node_modules/@actions/core/lib/file-command.js create mode 100644 node_modules/@actions/core/lib/file-command.js.map create mode 100644 node_modules/@actions/core/lib/oidc-utils.d.ts create mode 100644 node_modules/@actions/core/lib/oidc-utils.js create mode 100644 node_modules/@actions/core/lib/oidc-utils.js.map create mode 100644 node_modules/@actions/core/lib/path-utils.d.ts create mode 100644 node_modules/@actions/core/lib/path-utils.js create mode 100644 node_modules/@actions/core/lib/path-utils.js.map create mode 100644 node_modules/@actions/core/lib/summary.d.ts create mode 100644 node_modules/@actions/core/lib/summary.js create mode 100644 node_modules/@actions/core/lib/summary.js.map create mode 100644 node_modules/@actions/core/lib/utils.d.ts create mode 100644 node_modules/@actions/core/lib/utils.js create mode 100644 node_modules/@actions/core/lib/utils.js.map create mode 100644 node_modules/@actions/http-client/LICENSE create mode 100644 node_modules/@actions/http-client/README.md create mode 100644 node_modules/@actions/http-client/lib/auth.d.ts create mode 100644 node_modules/@actions/http-client/lib/auth.js create mode 100644 node_modules/@actions/http-client/lib/auth.js.map create mode 100644 node_modules/@actions/http-client/lib/index.d.ts create mode 100644 node_modules/@actions/http-client/lib/index.js create mode 100644 node_modules/@actions/http-client/lib/index.js.map create mode 100644 node_modules/@actions/http-client/lib/interfaces.d.ts create mode 100644 node_modules/@actions/http-client/lib/interfaces.js create mode 100644 node_modules/@actions/http-client/lib/interfaces.js.map create mode 100644 node_modules/@actions/http-client/lib/proxy.d.ts create mode 100644 node_modules/@actions/http-client/lib/proxy.js create mode 100644 node_modules/@actions/http-client/lib/proxy.js.map create mode 100644 node_modules/@actions/http-client/package.json create mode 100644 node_modules/minimist/.eslintrc create mode 100644 node_modules/minimist/.github/FUNDING.yml create mode 100644 node_modules/minimist/.nycrc delete mode 100644 node_modules/minimist/.travis.yml create mode 100644 node_modules/minimist/CHANGELOG.md rename node_modules/minimist/{readme.markdown => README.md} (54%) create mode 100644 node_modules/minimist/test/proto.js create mode 100644 node_modules/tunnel/.travis.yml create mode 100644 node_modules/tunnel/CHANGELOG.md create mode 100644 node_modules/tunnel/LICENSE create mode 100644 node_modules/tunnel/README.md create mode 100644 node_modules/tunnel/index.js create mode 100644 node_modules/tunnel/lib/tunnel.js create mode 100644 node_modules/tunnel/package.json create mode 100644 node_modules/uuid/CHANGELOG.md create mode 100644 node_modules/uuid/CONTRIBUTING.md create mode 100644 node_modules/uuid/LICENSE.md create mode 100644 node_modules/uuid/README.md create mode 100755 node_modules/uuid/dist/bin/uuid create mode 100644 node_modules/uuid/dist/esm-browser/index.js create mode 100644 node_modules/uuid/dist/esm-browser/md5.js create mode 100644 node_modules/uuid/dist/esm-browser/nil.js create mode 100644 node_modules/uuid/dist/esm-browser/parse.js create mode 100644 node_modules/uuid/dist/esm-browser/regex.js create mode 100644 node_modules/uuid/dist/esm-browser/rng.js create mode 100644 node_modules/uuid/dist/esm-browser/sha1.js create mode 100644 node_modules/uuid/dist/esm-browser/stringify.js create mode 100644 node_modules/uuid/dist/esm-browser/v1.js create mode 100644 node_modules/uuid/dist/esm-browser/v3.js create mode 100644 node_modules/uuid/dist/esm-browser/v35.js create mode 100644 node_modules/uuid/dist/esm-browser/v4.js create mode 100644 node_modules/uuid/dist/esm-browser/v5.js create mode 100644 node_modules/uuid/dist/esm-browser/validate.js create mode 100644 node_modules/uuid/dist/esm-browser/version.js create mode 100644 node_modules/uuid/dist/esm-node/index.js create mode 100644 node_modules/uuid/dist/esm-node/md5.js create mode 100644 node_modules/uuid/dist/esm-node/nil.js create mode 100644 node_modules/uuid/dist/esm-node/parse.js create mode 100644 node_modules/uuid/dist/esm-node/regex.js create mode 100644 node_modules/uuid/dist/esm-node/rng.js create mode 100644 node_modules/uuid/dist/esm-node/sha1.js create mode 100644 node_modules/uuid/dist/esm-node/stringify.js create mode 100644 node_modules/uuid/dist/esm-node/v1.js create mode 100644 node_modules/uuid/dist/esm-node/v3.js create mode 100644 node_modules/uuid/dist/esm-node/v35.js create mode 100644 node_modules/uuid/dist/esm-node/v4.js create mode 100644 node_modules/uuid/dist/esm-node/v5.js create mode 100644 node_modules/uuid/dist/esm-node/validate.js create mode 100644 node_modules/uuid/dist/esm-node/version.js create mode 100644 node_modules/uuid/dist/index.js create mode 100644 node_modules/uuid/dist/md5-browser.js create mode 100644 node_modules/uuid/dist/md5.js create mode 100644 node_modules/uuid/dist/nil.js create mode 100644 node_modules/uuid/dist/parse.js create mode 100644 node_modules/uuid/dist/regex.js create mode 100644 node_modules/uuid/dist/rng-browser.js create mode 100644 node_modules/uuid/dist/rng.js create mode 100644 node_modules/uuid/dist/sha1-browser.js create mode 100644 node_modules/uuid/dist/sha1.js create mode 100644 node_modules/uuid/dist/stringify.js create mode 100644 node_modules/uuid/dist/umd/uuid.min.js create mode 100644 node_modules/uuid/dist/umd/uuidNIL.min.js create mode 100644 node_modules/uuid/dist/umd/uuidParse.min.js create mode 100644 node_modules/uuid/dist/umd/uuidStringify.min.js create mode 100644 node_modules/uuid/dist/umd/uuidValidate.min.js create mode 100644 node_modules/uuid/dist/umd/uuidVersion.min.js create mode 100644 node_modules/uuid/dist/umd/uuidv1.min.js create mode 100644 node_modules/uuid/dist/umd/uuidv3.min.js create mode 100644 node_modules/uuid/dist/umd/uuidv4.min.js create mode 100644 node_modules/uuid/dist/umd/uuidv5.min.js create mode 100644 node_modules/uuid/dist/uuid-bin.js create mode 100644 node_modules/uuid/dist/v1.js create mode 100644 node_modules/uuid/dist/v3.js create mode 100644 node_modules/uuid/dist/v35.js create mode 100644 node_modules/uuid/dist/v4.js create mode 100644 node_modules/uuid/dist/v5.js create mode 100644 node_modules/uuid/dist/validate.js create mode 100644 node_modules/uuid/dist/version.js create mode 100644 node_modules/uuid/package.json create mode 100644 node_modules/uuid/wrapper.mjs delete mode 100644 node_modules/xmldom/.npmignore delete mode 100644 node_modules/xmldom/.travis.yml create mode 100644 node_modules/xmldom/CHANGELOG.md delete mode 100644 node_modules/xmldom/__package__.js delete mode 100644 node_modules/xmldom/changelog delete mode 100644 node_modules/xmldom/component.json create mode 100644 node_modules/xmldom/lib/.eslintrc.yml rename node_modules/xmldom/{ => lib}/dom-parser.js (91%) rename node_modules/xmldom/{ => lib}/dom.js (93%) create mode 100644 node_modules/xmldom/lib/entities.js rename node_modules/xmldom/{ => lib}/sax.js (90%) delete mode 100644 node_modules/xpath/.npmignore create mode 100644 node_modules/xpath/LICENSE diff --git a/node_modules/.bin/uuid b/node_modules/.bin/uuid new file mode 120000 index 0000000..588f70e --- /dev/null +++ b/node_modules/.bin/uuid @@ -0,0 +1 @@ +../uuid/dist/bin/uuid \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..176b955 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,65 @@ +{ + "name": "get-xml-info", + "version": "1.1.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "node_modules/@actions/core": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.10.0.tgz", + "integrity": "sha512-2aZDDa3zrrZbP5ZYg159sNoLRb61nQ7awl5pSvIq5Qpj81vwDzdMRKzkWJGJuwVvWpvZKx7vspJALyvaaIQyug==", + "dependencies": { + "@actions/http-client": "^2.0.1", + "uuid": "^8.3.2" + } + }, + "node_modules/@actions/http-client": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.0.1.tgz", + "integrity": "sha512-PIXiMVtz6VvyaRsGY268qvj57hXQEpsYogYOu2nrQhlf+XCGmZstmuZBbAybUl1nQGnvS1k1eEsQ69ZoD7xlSw==", + "dependencies": { + "tunnel": "^0.0.6" + } + }, + "node_modules/minimist": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz", + "integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tunnel": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz", + "integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==", + "engines": { + "node": ">=0.6.11 <=0.7.0 || >=0.7.3" + } + }, + "node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/xmldom": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/xmldom/-/xmldom-0.6.0.tgz", + "integrity": "sha512-iAcin401y58LckRZ0TkI4k0VSM1Qg0KGSc3i8rU+xrxe19A/BN1zHyVSJY7uoutVlaTSzYyk/v5AmkewAP7jtg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/xpath": { + "version": "0.0.32", + "resolved": "https://registry.npmjs.org/xpath/-/xpath-0.0.32.tgz", + "integrity": "sha512-rxMJhSIoiO8vXcWvSifKqhvV96GjiD5wYb8/QHdoRyQvraTpp4IEv944nhGausZZ3u7dhQXteZuZbaqfpB7uYw==", + "engines": { + "node": ">=0.6.0" + } + } + } +} diff --git a/node_modules/@actions/core/LICENSE.md b/node_modules/@actions/core/LICENSE.md new file mode 100644 index 0000000..dbae2ed --- /dev/null +++ b/node_modules/@actions/core/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright 2019 GitHub + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@actions/core/README.md b/node_modules/@actions/core/README.md index 457f73c..3c20c8e 100644 --- a/node_modules/@actions/core/README.md +++ b/node_modules/@actions/core/README.md @@ -16,11 +16,14 @@ import * as core from '@actions/core'; #### Inputs/Outputs -Action inputs can be read with `getInput`. Outputs can be set with `setOutput` which makes them available to be mapped into inputs of other actions to ensure they are decoupled. +Action inputs can be read with `getInput` which returns a `string` or `getBooleanInput` which parses a boolean based on the [yaml 1.2 specification](https://yaml.org/spec/1.2/spec.html#id2804923). If `required` set to be false, the input should have a default value in `action.yml`. + +Outputs can be set with `setOutput` which makes them available to be mapped into inputs of other actions to ensure they are decoupled. ```js const myInput = core.getInput('inputName', { required: true }); - +const myBooleanInput = core.getBooleanInput('booleanInputName', { required: true }); +const myMultilineInput = core.getMultilineInput('multilineInputName', { required: true }); core.setOutput('outputKey', 'outputVal'); ``` @@ -62,11 +65,10 @@ catch (err) { // setFailed logs the message and sets a failing exit code core.setFailed(`Action failed with error ${err}`); } +``` Note that `setNeutral` is not yet implemented in actions V2 but equivalent functionality is being planned. -``` - #### Logging Finally, this library provides some utilities for logging. Note that debug logging is hidden from the logs by default. This behavior can be toggled by enabling the [Step Debug Logs](../../docs/action-debugging.md#step-debug-logs). @@ -82,7 +84,16 @@ try { core.warning('myInput was not set'); } + if (core.isDebug()) { + // curl -v https://github.com + } else { + // curl https://github.com + } + // Do stuff + core.info('Output to the actions build log') + + core.notice('This is a message that will also emit an annotation') } catch (err) { core.error(`Error ${err}, action may still succeed though`); @@ -106,11 +117,123 @@ const result = await core.group('Do something async', async () => { }) ``` +#### Annotations + +This library has 3 methods that will produce [annotations](https://docs.github.com/en/rest/reference/checks#create-a-check-run). +```js +core.error('This is a bad error. This will also fail the build.') + +core.warning('Something went wrong, but it\'s not bad enough to fail the build.') + +core.notice('Something happened that you might want to know about.') +``` + +These will surface to the UI in the Actions page and on Pull Requests. They look something like this: + +![Annotations Image](../../docs/assets/annotations.png) + +These annotations can also be attached to particular lines and columns of your source files to show exactly where a problem is occuring. + +These options are: +```typescript +export interface AnnotationProperties { + /** + * A title for the annotation. + */ + title?: string + + /** + * The name of the file for which the annotation should be created. + */ + file?: string + + /** + * The start line for the annotation. + */ + startLine?: number + + /** + * The end line for the annotation. Defaults to `startLine` when `startLine` is provided. + */ + endLine?: number + + /** + * The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values. + */ + startColumn?: number + + /** + * The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values. + * Defaults to `startColumn` when `startColumn` is provided. + */ + endColumn?: number +} +``` + +#### Styling output + +Colored output is supported in the Action logs via standard [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code). 3/4 bit, 8 bit and 24 bit colors are all supported. + +Foreground colors: + +```js +// 3/4 bit +core.info('\u001b[35mThis foreground will be magenta') + +// 8 bit +core.info('\u001b[38;5;6mThis foreground will be cyan') + +// 24 bit +core.info('\u001b[38;2;255;0;0mThis foreground will be bright red') +``` + +Background colors: + +```js +// 3/4 bit +core.info('\u001b[43mThis background will be yellow'); + +// 8 bit +core.info('\u001b[48;5;6mThis background will be cyan') + +// 24 bit +core.info('\u001b[48;2;255;0;0mThis background will be bright red') +``` + +Special styles: + +```js +core.info('\u001b[1mBold text') +core.info('\u001b[3mItalic text') +core.info('\u001b[4mUnderlined text') +``` + +ANSI escape codes can be combined with one another: + +```js +core.info('\u001b[31;46mRed foreground with a cyan background and \u001b[1mbold text at the end'); +``` + +> Note: Escape codes reset at the start of each line + +```js +core.info('\u001b[35mThis foreground will be magenta') +core.info('This foreground will reset to the default') +``` + +Manually typing escape codes can be a little difficult, but you can use third party modules such as [ansi-styles](https://github.com/chalk/ansi-styles). + +```js +const style = require('ansi-styles'); +core.info(style.color.ansi16m.hex('#abcdef') + 'Hello world!') +``` + #### Action state -You can use this library to save state and get state for sharing information between a given wrapper action: +You can use this library to save state and get state for sharing information between a given wrapper action: + +**action.yml**: -**action.yml** ```yaml name: 'Wrapper action sample' inputs: @@ -131,10 +254,82 @@ core.saveState("pidToKill", 12345); ``` In action's `cleanup.js`: + ```js const core = require('@actions/core'); var pid = core.getState("pidToKill"); process.kill(pid); -``` \ No newline at end of file +``` + +#### OIDC Token + +You can use these methods to interact with the GitHub OIDC provider and get a JWT ID token which would help to get access token from third party cloud providers. + +**Method Name**: getIDToken() + +**Inputs** + +audience : optional + +**Outputs** + +A [JWT](https://jwt.io/) ID Token + +In action's `main.ts`: +```js +const core = require('@actions/core'); +async function getIDTokenAction(): Promise { + + const audience = core.getInput('audience', {required: false}) + + const id_token1 = await core.getIDToken() // ID Token with default audience + const id_token2 = await core.getIDToken(audience) // ID token with custom audience + + // this id_token can be used to get access token from third party cloud providers +} +getIDTokenAction() +``` + +In action's `actions.yml`: + +```yaml +name: 'GetIDToken' +description: 'Get ID token from Github OIDC provider' +inputs: + audience: + description: 'Audience for which the ID token is intended for' + required: false +outputs: + id_token1: + description: 'ID token obtained from OIDC provider' + id_token2: + description: 'ID token obtained from OIDC provider' +runs: + using: 'node12' + main: 'dist/index.js' +``` + +#### Filesystem path helpers + +You can use these methods to manipulate file paths across operating systems. + +The `toPosixPath` function converts input paths to Posix-style (Linux) paths. +The `toWin32Path` function converts input paths to Windows-style paths. These +functions work independently of the underlying runner operating system. + +```js +toPosixPath('\\foo\\bar') // => /foo/bar +toWin32Path('/foo/bar') // => \foo\bar +``` + +The `toPlatformPath` function converts input paths to the expected value on the runner's operating system. + +```js +// On a Windows runner. +toPlatformPath('/foo/bar') // => \foo\bar + +// On a Linux runner. +toPlatformPath('\\foo\\bar') // => /foo/bar +``` diff --git a/node_modules/@actions/core/lib/command.d.ts b/node_modules/@actions/core/lib/command.d.ts index 7f6fecb..53f8f4b 100644 --- a/node_modules/@actions/core/lib/command.d.ts +++ b/node_modules/@actions/core/lib/command.d.ts @@ -1,16 +1,15 @@ -interface CommandProperties { - [key: string]: string; +export interface CommandProperties { + [key: string]: any; } /** * Commands * * Command Format: - * ##[name key=value;key=value]message + * ::name key=value,key=value::message * * Examples: - * ##[warning]This is the user warning message - * ##[set-secret name=mypassword]definitelyNotAPassword! + * ::warning::This is the message + * ::set-env name=MY_VAR::some value */ -export declare function issueCommand(command: string, properties: CommandProperties, message: string): void; +export declare function issueCommand(command: string, properties: CommandProperties, message: any): void; export declare function issue(name: string, message?: string): void; -export {}; diff --git a/node_modules/@actions/core/lib/command.js b/node_modules/@actions/core/lib/command.js index b0ea009..0b28c66 100644 --- a/node_modules/@actions/core/lib/command.js +++ b/node_modules/@actions/core/lib/command.js @@ -1,15 +1,36 @@ "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; Object.defineProperty(exports, "__esModule", { value: true }); -const os = require("os"); +exports.issue = exports.issueCommand = void 0; +const os = __importStar(require("os")); +const utils_1 = require("./utils"); /** * Commands * * Command Format: - * ##[name key=value;key=value]message + * ::name key=value,key=value::message * * Examples: - * ##[warning]This is the user warning message - * ##[set-secret name=mypassword]definitelyNotAPassword! + * ::warning::This is the message + * ::set-env name=MY_VAR::some value */ function issueCommand(command, properties, message) { const cmd = new Command(command, properties, message); @@ -34,33 +55,38 @@ class Command { let cmdStr = CMD_STRING + this.command; if (this.properties && Object.keys(this.properties).length > 0) { cmdStr += ' '; + let first = true; for (const key in this.properties) { if (this.properties.hasOwnProperty(key)) { const val = this.properties[key]; if (val) { - // safely append the val - avoid blowing up when attempting to - // call .replace() if message is not a string for some reason - cmdStr += `${key}=${escape(`${val || ''}`)},`; + if (first) { + first = false; + } + else { + cmdStr += ','; + } + cmdStr += `${key}=${escapeProperty(val)}`; } } } } - cmdStr += CMD_STRING; - // safely append the message - avoid blowing up when attempting to - // call .replace() if message is not a string for some reason - const message = `${this.message || ''}`; - cmdStr += escapeData(message); + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; return cmdStr; } } function escapeData(s) { - return s.replace(/\r/g, '%0D').replace(/\n/g, '%0A'); + return utils_1.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); } -function escape(s) { - return s +function escapeProperty(s) { + return utils_1.toCommandValue(s) + .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') - .replace(/]/g, '%5D') - .replace(/;/g, '%3B'); + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); } //# sourceMappingURL=command.js.map \ No newline at end of file diff --git a/node_modules/@actions/core/lib/command.js.map b/node_modules/@actions/core/lib/command.js.map index 918ab25..51c7c63 100644 --- a/node_modules/@actions/core/lib/command.js.map +++ b/node_modules/@actions/core/lib/command.js.map @@ -1 +1 @@ -{"version":3,"file":"command.js","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":";;AAAA,yBAAwB;AAQxB;;;;;;;;;GASG;AACH,SAAgB,YAAY,CAC1B,OAAe,EACf,UAA6B,EAC7B,OAAe;IAEf,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAA;IACrD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AAC/C,CAAC;AAPD,oCAOC;AAED,SAAgB,KAAK,CAAC,IAAY,EAAE,UAAkB,EAAE;IACtD,YAAY,CAAC,IAAI,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;AACjC,CAAC;AAFD,sBAEC;AAED,MAAM,UAAU,GAAG,IAAI,CAAA;AAEvB,MAAM,OAAO;IAKX,YAAY,OAAe,EAAE,UAA6B,EAAE,OAAe;QACzE,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO,GAAG,iBAAiB,CAAA;SAC5B;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;IAED,QAAQ;QACN,IAAI,MAAM,GAAG,UAAU,GAAG,IAAI,CAAC,OAAO,CAAA;QAEtC,IAAI,IAAI,CAAC,UAAU,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YAC9D,MAAM,IAAI,GAAG,CAAA;YACb,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,UAAU,EAAE;gBACjC,IAAI,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE;oBACvC,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;oBAChC,IAAI,GAAG,EAAE;wBACP,8DAA8D;wBAC9D,6DAA6D;wBAC7D,MAAM,IAAI,GAAG,GAAG,IAAI,MAAM,CAAC,GAAG,GAAG,IAAI,EAAE,EAAE,CAAC,GAAG,CAAA;qBAC9C;iBACF;aACF;SACF;QAED,MAAM,IAAI,UAAU,CAAA;QAEpB,kEAAkE;QAClE,6DAA6D;QAC7D,MAAM,OAAO,GAAG,GAAG,IAAI,CAAC,OAAO,IAAI,EAAE,EAAE,CAAA;QACvC,MAAM,IAAI,UAAU,CAAC,OAAO,CAAC,CAAA;QAE7B,OAAO,MAAM,CAAA;IACf,CAAC;CACF;AAED,SAAS,UAAU,CAAC,CAAS;IAC3B,OAAO,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;AACtD,CAAC;AAED,SAAS,MAAM,CAAC,CAAS;IACvB,OAAO,CAAC;SACL,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;AACzB,CAAC"} \ No newline at end of file +{"version":3,"file":"command.js","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAwB;AACxB,mCAAsC;AAWtC;;;;;;;;;GASG;AACH,SAAgB,YAAY,CAC1B,OAAe,EACf,UAA6B,EAC7B,OAAY;IAEZ,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAA;IACrD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AAC/C,CAAC;AAPD,oCAOC;AAED,SAAgB,KAAK,CAAC,IAAY,EAAE,OAAO,GAAG,EAAE;IAC9C,YAAY,CAAC,IAAI,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;AACjC,CAAC;AAFD,sBAEC;AAED,MAAM,UAAU,GAAG,IAAI,CAAA;AAEvB,MAAM,OAAO;IAKX,YAAY,OAAe,EAAE,UAA6B,EAAE,OAAe;QACzE,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO,GAAG,iBAAiB,CAAA;SAC5B;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;IAED,QAAQ;QACN,IAAI,MAAM,GAAG,UAAU,GAAG,IAAI,CAAC,OAAO,CAAA;QAEtC,IAAI,IAAI,CAAC,UAAU,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YAC9D,MAAM,IAAI,GAAG,CAAA;YACb,IAAI,KAAK,GAAG,IAAI,CAAA;YAChB,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,UAAU,EAAE;gBACjC,IAAI,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE;oBACvC,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;oBAChC,IAAI,GAAG,EAAE;wBACP,IAAI,KAAK,EAAE;4BACT,KAAK,GAAG,KAAK,CAAA;yBACd;6BAAM;4BACL,MAAM,IAAI,GAAG,CAAA;yBACd;wBAED,MAAM,IAAI,GAAG,GAAG,IAAI,cAAc,CAAC,GAAG,CAAC,EAAE,CAAA;qBAC1C;iBACF;aACF;SACF;QAED,MAAM,IAAI,GAAG,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAA;QACpD,OAAO,MAAM,CAAA;IACf,CAAC;CACF;AAED,SAAS,UAAU,CAAC,CAAM;IACxB,OAAO,sBAAc,CAAC,CAAC,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;AAC1B,CAAC;AAED,SAAS,cAAc,CAAC,CAAM;IAC5B,OAAO,sBAAc,CAAC,CAAC,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;AACzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@actions/core/lib/core.d.ts b/node_modules/@actions/core/lib/core.d.ts index 6483c3c..1defb57 100644 --- a/node_modules/@actions/core/lib/core.d.ts +++ b/node_modules/@actions/core/lib/core.d.ts @@ -4,6 +4,8 @@ export interface InputOptions { /** Optional. Whether the input is required. If required and not present, will throw. Defaults to false */ required?: boolean; + /** Optional. Whether leading/trailing whitespace will be trimmed for the input. Defaults to true */ + trimWhitespace?: boolean; } /** * The code to exit an action @@ -18,12 +20,43 @@ export declare enum ExitCode { */ Failure = 1 } +/** + * Optional properties that can be sent with annotatation commands (notice, error, and warning) + * See: https://docs.github.com/en/rest/reference/checks#create-a-check-run for more information about annotations. + */ +export interface AnnotationProperties { + /** + * A title for the annotation. + */ + title?: string; + /** + * The path of the file for which the annotation should be created. + */ + file?: string; + /** + * The start line for the annotation. + */ + startLine?: number; + /** + * The end line for the annotation. Defaults to `startLine` when `startLine` is provided. + */ + endLine?: number; + /** + * The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values. + */ + startColumn?: number; + /** + * The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values. + * Defaults to `startColumn` when `startColumn` is provided. + */ + endColumn?: number; +} /** * Sets env variable for this action and future actions in the job * @param name the name of the variable to set - * @param val the value of the variable + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify */ -export declare function exportVariable(name: string, val: string): void; +export declare function exportVariable(name: string, val: any): void; /** * Registers a secret which will get masked from logs * @param secret value of the secret @@ -35,26 +68,58 @@ export declare function setSecret(secret: string): void; */ export declare function addPath(inputPath: string): void; /** - * Gets the value of an input. The value is also trimmed. + * Gets the value of an input. + * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. + * Returns an empty string if the value is not defined. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string */ export declare function getInput(name: string, options?: InputOptions): string; +/** + * Gets the values of an multiline input. Each value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string[] + * + */ +export declare function getMultilineInput(name: string, options?: InputOptions): string[]; +/** + * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. + * Support boolean input list: `true | True | TRUE | false | False | FALSE` . + * The return value is also in boolean type. + * ref: https://yaml.org/spec/1.2/spec.html#id2804923 + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns boolean + */ +export declare function getBooleanInput(name: string, options?: InputOptions): boolean; /** * Sets the value of an output. * * @param name name of the output to set - * @param value value to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ -export declare function setOutput(name: string, value: string): void; +export declare function setOutput(name: string, value: any): void; +/** + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * + */ +export declare function setCommandEcho(enabled: boolean): void; /** * Sets the action status to failed. * When the action exits it will be with an exit code of 1 * @param message add error issue message */ -export declare function setFailed(message: string): void; +export declare function setFailed(message: string | Error): void; +/** + * Gets whether Actions Step Debug is on or not + */ +export declare function isDebug(): boolean; /** * Writes debug message to user log * @param message debug message @@ -62,14 +127,22 @@ export declare function setFailed(message: string): void; export declare function debug(message: string): void; /** * Adds an error issue - * @param message error issue message + * @param message error issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +export declare function error(message: string | Error, properties?: AnnotationProperties): void; +/** + * Adds a warning issue + * @param message warning issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. */ -export declare function error(message: string): void; +export declare function warning(message: string | Error, properties?: AnnotationProperties): void; /** - * Adds an warning issue - * @param message warning issue message + * Adds a notice issue + * @param message notice issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. */ -export declare function warning(message: string): void; +export declare function notice(message: string | Error, properties?: AnnotationProperties): void; /** * Writes info to log with console.log. * @param message info message @@ -100,9 +173,9 @@ export declare function group(name: string, fn: () => Promise): Promise * Saves state for current action, the state can only be retrieved by this action's post job execution. * * @param name name of the state to store - * @param value value to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ -export declare function saveState(name: string, value: string): void; +export declare function saveState(name: string, value: any): void; /** * Gets the value of an state set by this action's main execution. * @@ -110,3 +183,16 @@ export declare function saveState(name: string, value: string): void; * @returns string */ export declare function getState(name: string): string; +export declare function getIDToken(aud?: string): Promise; +/** + * Summary exports + */ +export { summary } from './summary'; +/** + * @deprecated use core.summary + */ +export { markdownSummary } from './summary'; +/** + * Path exports + */ +export { toPosixPath, toWin32Path, toPlatformPath } from './path-utils'; diff --git a/node_modules/@actions/core/lib/core.js b/node_modules/@actions/core/lib/core.js index f43d507..48df6ad 100644 --- a/node_modules/@actions/core/lib/core.js +++ b/node_modules/@actions/core/lib/core.js @@ -1,4 +1,23 @@ "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { @@ -9,9 +28,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; Object.defineProperty(exports, "__esModule", { value: true }); +exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; const command_1 = require("./command"); -const os = require("os"); -const path = require("path"); +const file_command_1 = require("./file-command"); +const utils_1 = require("./utils"); +const os = __importStar(require("os")); +const path = __importStar(require("path")); +const oidc_utils_1 = require("./oidc-utils"); /** * The code to exit an action */ @@ -32,11 +55,17 @@ var ExitCode; /** * Sets env variable for this action and future actions in the job * @param name the name of the variable to set - * @param val the value of the variable + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any function exportVariable(name, val) { - process.env[name] = val; - command_1.issueCommand('set-env', { name }, val); + const convertedVal = utils_1.toCommandValue(val); + process.env[name] = convertedVal; + const filePath = process.env['GITHUB_ENV'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); + } + command_1.issueCommand('set-env', { name }, convertedVal); } exports.exportVariable = exportVariable; /** @@ -52,12 +81,20 @@ exports.setSecret = setSecret; * @param inputPath */ function addPath(inputPath) { - command_1.issueCommand('add-path', {}, inputPath); + const filePath = process.env['GITHUB_PATH'] || ''; + if (filePath) { + file_command_1.issueFileCommand('PATH', inputPath); + } + else { + command_1.issueCommand('add-path', {}, inputPath); + } process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } exports.addPath = addPath; /** - * Gets the value of an input. The value is also trimmed. + * Gets the value of an input. + * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. + * Returns an empty string if the value is not defined. * * @param name name of the input to get * @param options optional. See InputOptions. @@ -68,19 +105,77 @@ function getInput(name, options) { if (options && options.required && !val) { throw new Error(`Input required and not supplied: ${name}`); } + if (options && options.trimWhitespace === false) { + return val; + } return val.trim(); } exports.getInput = getInput; +/** + * Gets the values of an multiline input. Each value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string[] + * + */ +function getMultilineInput(name, options) { + const inputs = getInput(name, options) + .split('\n') + .filter(x => x !== ''); + if (options && options.trimWhitespace === false) { + return inputs; + } + return inputs.map(input => input.trim()); +} +exports.getMultilineInput = getMultilineInput; +/** + * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. + * Support boolean input list: `true | True | TRUE | false | False | FALSE` . + * The return value is also in boolean type. + * ref: https://yaml.org/spec/1.2/spec.html#id2804923 + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns boolean + */ +function getBooleanInput(name, options) { + const trueValue = ['true', 'True', 'TRUE']; + const falseValue = ['false', 'False', 'FALSE']; + const val = getInput(name, options); + if (trueValue.includes(val)) + return true; + if (falseValue.includes(val)) + return false; + throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + + `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); +} +exports.getBooleanInput = getBooleanInput; /** * Sets the value of an output. * * @param name name of the output to set - * @param value value to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { - command_1.issueCommand('set-output', { name }, value); + const filePath = process.env['GITHUB_OUTPUT'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); + } + process.stdout.write(os.EOL); + command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); } exports.setOutput = setOutput; +/** + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * + */ +function setCommandEcho(enabled) { + command_1.issue('echo', enabled ? 'on' : 'off'); +} +exports.setCommandEcho = setCommandEcho; //----------------------------------------------------------------------- // Results //----------------------------------------------------------------------- @@ -97,6 +192,13 @@ exports.setFailed = setFailed; //----------------------------------------------------------------------- // Logging Commands //----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; +} +exports.isDebug = isDebug; /** * Writes debug message to user log * @param message debug message @@ -107,20 +209,31 @@ function debug(message) { exports.debug = debug; /** * Adds an error issue - * @param message error issue message + * @param message error issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. */ -function error(message) { - command_1.issue('error', message); +function error(message, properties = {}) { + command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); } exports.error = error; /** - * Adds an warning issue - * @param message warning issue message + * Adds a warning issue + * @param message warning issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. */ -function warning(message) { - command_1.issue('warning', message); +function warning(message, properties = {}) { + command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); } exports.warning = warning; +/** + * Adds a notice issue + * @param message notice issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function notice(message, properties = {}) { + command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +exports.notice = notice; /** * Writes info to log with console.log. * @param message info message @@ -176,10 +289,15 @@ exports.group = group; * Saves state for current action, the state can only be retrieved by this action's post job execution. * * @param name name of the state to store - * @param value value to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any function saveState(name, value) { - command_1.issueCommand('save-state', { name }, value); + const filePath = process.env['GITHUB_STATE'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); + } + command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value)); } exports.saveState = saveState; /** @@ -192,4 +310,27 @@ function getState(name) { return process.env[`STATE_${name}`] || ''; } exports.getState = getState; +function getIDToken(aud) { + return __awaiter(this, void 0, void 0, function* () { + return yield oidc_utils_1.OidcClient.getIDToken(aud); + }); +} +exports.getIDToken = getIDToken; +/** + * Summary exports + */ +var summary_1 = require("./summary"); +Object.defineProperty(exports, "summary", { enumerable: true, get: function () { return summary_1.summary; } }); +/** + * @deprecated use core.summary + */ +var summary_2 = require("./summary"); +Object.defineProperty(exports, "markdownSummary", { enumerable: true, get: function () { return summary_2.markdownSummary; } }); +/** + * Path exports + */ +var path_utils_1 = require("./path-utils"); +Object.defineProperty(exports, "toPosixPath", { enumerable: true, get: function () { return path_utils_1.toPosixPath; } }); +Object.defineProperty(exports, "toWin32Path", { enumerable: true, get: function () { return path_utils_1.toWin32Path; } }); +Object.defineProperty(exports, "toPlatformPath", { enumerable: true, get: function () { return path_utils_1.toPlatformPath; } }); //# sourceMappingURL=core.js.map \ No newline at end of file diff --git a/node_modules/@actions/core/lib/core.js.map b/node_modules/@actions/core/lib/core.js.map index 6eda8da..99f7fd8 100644 --- a/node_modules/@actions/core/lib/core.js.map +++ b/node_modules/@actions/core/lib/core.js.map @@ -1 +1 @@ -{"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"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"} \ No newline at end of file +{"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/@actions/core/lib/file-command.d.ts b/node_modules/@actions/core/lib/file-command.d.ts new file mode 100644 index 0000000..2d1f2f4 --- /dev/null +++ b/node_modules/@actions/core/lib/file-command.d.ts @@ -0,0 +1,2 @@ +export declare function issueFileCommand(command: string, message: any): void; +export declare function prepareKeyValueMessage(key: string, value: any): string; diff --git a/node_modules/@actions/core/lib/file-command.js b/node_modules/@actions/core/lib/file-command.js new file mode 100644 index 0000000..2d0d738 --- /dev/null +++ b/node_modules/@actions/core/lib/file-command.js @@ -0,0 +1,58 @@ +"use strict"; +// For internal use, subject to change. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +const fs = __importStar(require("fs")); +const os = __importStar(require("os")); +const uuid_1 = require("uuid"); +const utils_1 = require("./utils"); +function issueFileCommand(command, message) { + const filePath = process.env[`GITHUB_${command}`]; + if (!filePath) { + throw new Error(`Unable to find environment variable for file command ${command}`); + } + if (!fs.existsSync(filePath)) { + throw new Error(`Missing file at path: ${filePath}`); + } + fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { + encoding: 'utf8' + }); +} +exports.issueFileCommand = issueFileCommand; +function prepareKeyValueMessage(key, value) { + const delimiter = `ghadelimiter_${uuid_1.v4()}`; + const convertedValue = utils_1.toCommandValue(value); + // These should realistically never happen, but just in case someone finds a + // way to exploit uuid generation let's not allow keys or values that contain + // the delimiter. + if (key.includes(delimiter)) { + throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); + } + if (convertedValue.includes(delimiter)) { + throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); + } + return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; +} +exports.prepareKeyValueMessage = prepareKeyValueMessage; +//# sourceMappingURL=file-command.js.map \ No newline at end of file diff --git a/node_modules/@actions/core/lib/file-command.js.map b/node_modules/@actions/core/lib/file-command.js.map new file mode 100644 index 0000000..b1a9d54 --- /dev/null +++ b/node_modules/@actions/core/lib/file-command.js.map @@ -0,0 +1 @@ +{"version":3,"file":"file-command.js","sourceRoot":"","sources":["../src/file-command.ts"],"names":[],"mappings":";AAAA,uCAAuC;;;;;;;;;;;;;;;;;;;;;;AAEvC,mCAAmC;AACnC,uDAAuD;AAEvD,uCAAwB;AACxB,uCAAwB;AACxB,+BAAiC;AACjC,mCAAsC;AAEtC,SAAgB,gBAAgB,CAAC,OAAe,EAAE,OAAY;IAC5D,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,OAAO,EAAE,CAAC,CAAA;IACjD,IAAI,CAAC,QAAQ,EAAE;QACb,MAAM,IAAI,KAAK,CACb,wDAAwD,OAAO,EAAE,CAClE,CAAA;KACF;IACD,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE;QAC5B,MAAM,IAAI,KAAK,CAAC,yBAAyB,QAAQ,EAAE,CAAC,CAAA;KACrD;IAED,EAAE,CAAC,cAAc,CAAC,QAAQ,EAAE,GAAG,sBAAc,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE;QACjE,QAAQ,EAAE,MAAM;KACjB,CAAC,CAAA;AACJ,CAAC;AAdD,4CAcC;AAED,SAAgB,sBAAsB,CAAC,GAAW,EAAE,KAAU;IAC5D,MAAM,SAAS,GAAG,gBAAgB,SAAM,EAAE,EAAE,CAAA;IAC5C,MAAM,cAAc,GAAG,sBAAc,CAAC,KAAK,CAAC,CAAA;IAE5C,4EAA4E;IAC5E,6EAA6E;IAC7E,iBAAiB;IACjB,IAAI,GAAG,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAC3B,MAAM,IAAI,KAAK,CACb,4DAA4D,SAAS,GAAG,CACzE,CAAA;KACF;IAED,IAAI,cAAc,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QACtC,MAAM,IAAI,KAAK,CACb,6DAA6D,SAAS,GAAG,CAC1E,CAAA;KACF;IAED,OAAO,GAAG,GAAG,KAAK,SAAS,GAAG,EAAE,CAAC,GAAG,GAAG,cAAc,GAAG,EAAE,CAAC,GAAG,GAAG,SAAS,EAAE,CAAA;AAC9E,CAAC;AApBD,wDAoBC"} \ No newline at end of file diff --git a/node_modules/@actions/core/lib/oidc-utils.d.ts b/node_modules/@actions/core/lib/oidc-utils.d.ts new file mode 100644 index 0000000..657c7f4 --- /dev/null +++ b/node_modules/@actions/core/lib/oidc-utils.d.ts @@ -0,0 +1,7 @@ +export declare class OidcClient { + private static createHttpClient; + private static getRequestToken; + private static getIDTokenUrl; + private static getCall; + static getIDToken(audience?: string): Promise; +} diff --git a/node_modules/@actions/core/lib/oidc-utils.js b/node_modules/@actions/core/lib/oidc-utils.js new file mode 100644 index 0000000..f701277 --- /dev/null +++ b/node_modules/@actions/core/lib/oidc-utils.js @@ -0,0 +1,77 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OidcClient = void 0; +const http_client_1 = require("@actions/http-client"); +const auth_1 = require("@actions/http-client/lib/auth"); +const core_1 = require("./core"); +class OidcClient { + static createHttpClient(allowRetry = true, maxRetry = 10) { + const requestOptions = { + allowRetries: allowRetry, + maxRetries: maxRetry + }; + return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); + } + static getRequestToken() { + const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; + if (!token) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); + } + return token; + } + static getIDTokenUrl() { + const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; + if (!runtimeUrl) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); + } + return runtimeUrl; + } + static getCall(id_token_url) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const httpclient = OidcClient.createHttpClient(); + const res = yield httpclient + .getJson(id_token_url) + .catch(error => { + throw new Error(`Failed to get ID Token. \n + Error Code : ${error.statusCode}\n + Error Message: ${error.result.message}`); + }); + const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; + if (!id_token) { + throw new Error('Response json body do not have ID Token field'); + } + return id_token; + }); + } + static getIDToken(audience) { + return __awaiter(this, void 0, void 0, function* () { + try { + // New ID Token is requested from action service + let id_token_url = OidcClient.getIDTokenUrl(); + if (audience) { + const encodedAudience = encodeURIComponent(audience); + id_token_url = `${id_token_url}&audience=${encodedAudience}`; + } + core_1.debug(`ID token url is ${id_token_url}`); + const id_token = yield OidcClient.getCall(id_token_url); + core_1.setSecret(id_token); + return id_token; + } + catch (error) { + throw new Error(`Error message: ${error.message}`); + } + }); + } +} +exports.OidcClient = OidcClient; +//# sourceMappingURL=oidc-utils.js.map \ No newline at end of file diff --git a/node_modules/@actions/core/lib/oidc-utils.js.map b/node_modules/@actions/core/lib/oidc-utils.js.map new file mode 100644 index 0000000..284fa1d --- /dev/null +++ b/node_modules/@actions/core/lib/oidc-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"oidc-utils.js","sourceRoot":"","sources":["../src/oidc-utils.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,sDAA+C;AAC/C,wDAAqE;AACrE,iCAAuC;AAKvC,MAAa,UAAU;IACb,MAAM,CAAC,gBAAgB,CAC7B,UAAU,GAAG,IAAI,EACjB,QAAQ,GAAG,EAAE;QAEb,MAAM,cAAc,GAAmB;YACrC,YAAY,EAAE,UAAU;YACxB,UAAU,EAAE,QAAQ;SACrB,CAAA;QAED,OAAO,IAAI,wBAAU,CACnB,qBAAqB,EACrB,CAAC,IAAI,8BAAuB,CAAC,UAAU,CAAC,eAAe,EAAE,CAAC,CAAC,EAC3D,cAAc,CACf,CAAA;IACH,CAAC;IAEO,MAAM,CAAC,eAAe;QAC5B,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAA;QAC3D,IAAI,CAAC,KAAK,EAAE;YACV,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAA;SACF;QACD,OAAO,KAAK,CAAA;IACd,CAAC;IAEO,MAAM,CAAC,aAAa;QAC1B,MAAM,UAAU,GAAG,OAAO,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAA;QAC9D,IAAI,CAAC,UAAU,EAAE;YACf,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAA;SAC3E;QACD,OAAO,UAAU,CAAA;IACnB,CAAC;IAEO,MAAM,CAAO,OAAO,CAAC,YAAoB;;;YAC/C,MAAM,UAAU,GAAG,UAAU,CAAC,gBAAgB,EAAE,CAAA;YAEhD,MAAM,GAAG,GAAG,MAAM,UAAU;iBACzB,OAAO,CAAgB,YAAY,CAAC;iBACpC,KAAK,CAAC,KAAK,CAAC,EAAE;gBACb,MAAM,IAAI,KAAK,CACb;uBACa,KAAK,CAAC,UAAU;yBACd,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,CACtC,CAAA;YACH,CAAC,CAAC,CAAA;YAEJ,MAAM,QAAQ,SAAG,GAAG,CAAC,MAAM,0CAAE,KAAK,CAAA;YAClC,IAAI,CAAC,QAAQ,EAAE;gBACb,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAA;aACjE;YACD,OAAO,QAAQ,CAAA;;KAChB;IAED,MAAM,CAAO,UAAU,CAAC,QAAiB;;YACvC,IAAI;gBACF,gDAAgD;gBAChD,IAAI,YAAY,GAAW,UAAU,CAAC,aAAa,EAAE,CAAA;gBACrD,IAAI,QAAQ,EAAE;oBACZ,MAAM,eAAe,GAAG,kBAAkB,CAAC,QAAQ,CAAC,CAAA;oBACpD,YAAY,GAAG,GAAG,YAAY,aAAa,eAAe,EAAE,CAAA;iBAC7D;gBAED,YAAK,CAAC,mBAAmB,YAAY,EAAE,CAAC,CAAA;gBAExC,MAAM,QAAQ,GAAG,MAAM,UAAU,CAAC,OAAO,CAAC,YAAY,CAAC,CAAA;gBACvD,gBAAS,CAAC,QAAQ,CAAC,CAAA;gBACnB,OAAO,QAAQ,CAAA;aAChB;YAAC,OAAO,KAAK,EAAE;gBACd,MAAM,IAAI,KAAK,CAAC,kBAAkB,KAAK,CAAC,OAAO,EAAE,CAAC,CAAA;aACnD;QACH,CAAC;KAAA;CACF;AAzED,gCAyEC"} \ No newline at end of file diff --git a/node_modules/@actions/core/lib/path-utils.d.ts b/node_modules/@actions/core/lib/path-utils.d.ts new file mode 100644 index 0000000..1fee9f3 --- /dev/null +++ b/node_modules/@actions/core/lib/path-utils.d.ts @@ -0,0 +1,25 @@ +/** + * toPosixPath converts the given path to the posix form. On Windows, \\ will be + * replaced with /. + * + * @param pth. Path to transform. + * @return string Posix path. + */ +export declare function toPosixPath(pth: string): string; +/** + * toWin32Path converts the given path to the win32 form. On Linux, / will be + * replaced with \\. + * + * @param pth. Path to transform. + * @return string Win32 path. + */ +export declare function toWin32Path(pth: string): string; +/** + * toPlatformPath converts the given path to a platform-specific path. It does + * this by replacing instances of / and \ with the platform-specific path + * separator. + * + * @param pth The path to platformize. + * @return string The platform-specific path. + */ +export declare function toPlatformPath(pth: string): string; diff --git a/node_modules/@actions/core/lib/path-utils.js b/node_modules/@actions/core/lib/path-utils.js new file mode 100644 index 0000000..7251c82 --- /dev/null +++ b/node_modules/@actions/core/lib/path-utils.js @@ -0,0 +1,58 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; +const path = __importStar(require("path")); +/** + * toPosixPath converts the given path to the posix form. On Windows, \\ will be + * replaced with /. + * + * @param pth. Path to transform. + * @return string Posix path. + */ +function toPosixPath(pth) { + return pth.replace(/[\\]/g, '/'); +} +exports.toPosixPath = toPosixPath; +/** + * toWin32Path converts the given path to the win32 form. On Linux, / will be + * replaced with \\. + * + * @param pth. Path to transform. + * @return string Win32 path. + */ +function toWin32Path(pth) { + return pth.replace(/[/]/g, '\\'); +} +exports.toWin32Path = toWin32Path; +/** + * toPlatformPath converts the given path to a platform-specific path. It does + * this by replacing instances of / and \ with the platform-specific path + * separator. + * + * @param pth The path to platformize. + * @return string The platform-specific path. + */ +function toPlatformPath(pth) { + return pth.replace(/[/\\]/g, path.sep); +} +exports.toPlatformPath = toPlatformPath; +//# sourceMappingURL=path-utils.js.map \ No newline at end of file diff --git a/node_modules/@actions/core/lib/path-utils.js.map b/node_modules/@actions/core/lib/path-utils.js.map new file mode 100644 index 0000000..7ab1cac --- /dev/null +++ b/node_modules/@actions/core/lib/path-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"path-utils.js","sourceRoot":"","sources":["../src/path-utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,2CAA4B;AAE5B;;;;;;GAMG;AACH,SAAgB,WAAW,CAAC,GAAW;IACrC,OAAO,GAAG,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;AAClC,CAAC;AAFD,kCAEC;AAED;;;;;;GAMG;AACH,SAAgB,WAAW,CAAC,GAAW;IACrC,OAAO,GAAG,CAAC,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;AAClC,CAAC;AAFD,kCAEC;AAED;;;;;;;GAOG;AACH,SAAgB,cAAc,CAAC,GAAW;IACxC,OAAO,GAAG,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,CAAC,GAAG,CAAC,CAAA;AACxC,CAAC;AAFD,wCAEC"} \ No newline at end of file diff --git a/node_modules/@actions/core/lib/summary.d.ts b/node_modules/@actions/core/lib/summary.d.ts new file mode 100644 index 0000000..bb79255 --- /dev/null +++ b/node_modules/@actions/core/lib/summary.d.ts @@ -0,0 +1,202 @@ +export declare const SUMMARY_ENV_VAR = "GITHUB_STEP_SUMMARY"; +export declare const SUMMARY_DOCS_URL = "https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary"; +export declare type SummaryTableRow = (SummaryTableCell | string)[]; +export interface SummaryTableCell { + /** + * Cell content + */ + data: string; + /** + * Render cell as header + * (optional) default: false + */ + header?: boolean; + /** + * Number of columns the cell extends + * (optional) default: '1' + */ + colspan?: string; + /** + * Number of rows the cell extends + * (optional) default: '1' + */ + rowspan?: string; +} +export interface SummaryImageOptions { + /** + * The width of the image in pixels. Must be an integer without a unit. + * (optional) + */ + width?: string; + /** + * The height of the image in pixels. Must be an integer without a unit. + * (optional) + */ + height?: string; +} +export interface SummaryWriteOptions { + /** + * Replace all existing content in summary file with buffer contents + * (optional) default: false + */ + overwrite?: boolean; +} +declare class Summary { + private _buffer; + private _filePath?; + constructor(); + /** + * Finds the summary file path from the environment, rejects if env var is not found or file does not exist + * Also checks r/w permissions. + * + * @returns step summary file path + */ + private filePath; + /** + * Wraps content in an HTML tag, adding any HTML attributes + * + * @param {string} tag HTML tag to wrap + * @param {string | null} content content within the tag + * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add + * + * @returns {string} content wrapped in HTML element + */ + private wrap; + /** + * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. + * + * @param {SummaryWriteOptions} [options] (optional) options for write operation + * + * @returns {Promise} summary instance + */ + write(options?: SummaryWriteOptions): Promise; + /** + * Clears the summary buffer and wipes the summary file + * + * @returns {Summary} summary instance + */ + clear(): Promise; + /** + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer + */ + stringify(): string; + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer(): boolean; + /** + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance + */ + emptyBuffer(): Summary; + /** + * Adds raw text to the summary buffer + * + * @param {string} text content to add + * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) + * + * @returns {Summary} summary instance + */ + addRaw(text: string, addEOL?: boolean): Summary; + /** + * Adds the operating system-specific end-of-line marker to the buffer + * + * @returns {Summary} summary instance + */ + addEOL(): Summary; + /** + * Adds an HTML codeblock to the summary buffer + * + * @param {string} code content to render within fenced code block + * @param {string} lang (optional) language to syntax highlight code + * + * @returns {Summary} summary instance + */ + addCodeBlock(code: string, lang?: string): Summary; + /** + * Adds an HTML list to the summary buffer + * + * @param {string[]} items list of items to render + * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) + * + * @returns {Summary} summary instance + */ + addList(items: string[], ordered?: boolean): Summary; + /** + * Adds an HTML table to the summary buffer + * + * @param {SummaryTableCell[]} rows table rows + * + * @returns {Summary} summary instance + */ + addTable(rows: SummaryTableRow[]): Summary; + /** + * Adds a collapsable HTML details element to the summary buffer + * + * @param {string} label text for the closed state + * @param {string} content collapsable content + * + * @returns {Summary} summary instance + */ + addDetails(label: string, content: string): Summary; + /** + * Adds an HTML image tag to the summary buffer + * + * @param {string} src path to the image you to embed + * @param {string} alt text description of the image + * @param {SummaryImageOptions} options (optional) addition image attributes + * + * @returns {Summary} summary instance + */ + addImage(src: string, alt: string, options?: SummaryImageOptions): Summary; + /** + * Adds an HTML section heading element + * + * @param {string} text heading text + * @param {number | string} [level=1] (optional) the heading level, default: 1 + * + * @returns {Summary} summary instance + */ + addHeading(text: string, level?: number | string): Summary; + /** + * Adds an HTML thematic break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addSeparator(): Summary; + /** + * Adds an HTML line break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addBreak(): Summary; + /** + * Adds an HTML blockquote to the summary buffer + * + * @param {string} text quote text + * @param {string} cite (optional) citation url + * + * @returns {Summary} summary instance + */ + addQuote(text: string, cite?: string): Summary; + /** + * Adds an HTML anchor tag to the summary buffer + * + * @param {string} text link text/content + * @param {string} href hyperlink + * + * @returns {Summary} summary instance + */ + addLink(text: string, href: string): Summary; +} +/** + * @deprecated use `core.summary` + */ +export declare const markdownSummary: Summary; +export declare const summary: Summary; +export {}; diff --git a/node_modules/@actions/core/lib/summary.js b/node_modules/@actions/core/lib/summary.js new file mode 100644 index 0000000..04a335b --- /dev/null +++ b/node_modules/@actions/core/lib/summary.js @@ -0,0 +1,283 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; +const os_1 = require("os"); +const fs_1 = require("fs"); +const { access, appendFile, writeFile } = fs_1.promises; +exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; +exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; +class Summary { + constructor() { + this._buffer = ''; + } + /** + * Finds the summary file path from the environment, rejects if env var is not found or file does not exist + * Also checks r/w permissions. + * + * @returns step summary file path + */ + filePath() { + return __awaiter(this, void 0, void 0, function* () { + if (this._filePath) { + return this._filePath; + } + const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; + if (!pathFromEnv) { + throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); + } + try { + yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); + } + catch (_a) { + throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + } + this._filePath = pathFromEnv; + return this._filePath; + }); + } + /** + * Wraps content in an HTML tag, adding any HTML attributes + * + * @param {string} tag HTML tag to wrap + * @param {string | null} content content within the tag + * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add + * + * @returns {string} content wrapped in HTML element + */ + wrap(tag, content, attrs = {}) { + const htmlAttrs = Object.entries(attrs) + .map(([key, value]) => ` ${key}="${value}"`) + .join(''); + if (!content) { + return `<${tag}${htmlAttrs}>`; + } + return `<${tag}${htmlAttrs}>${content}`; + } + /** + * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. + * + * @param {SummaryWriteOptions} [options] (optional) options for write operation + * + * @returns {Promise} summary instance + */ + write(options) { + return __awaiter(this, void 0, void 0, function* () { + const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); + const filePath = yield this.filePath(); + const writeFunc = overwrite ? writeFile : appendFile; + yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); + return this.emptyBuffer(); + }); + } + /** + * Clears the summary buffer and wipes the summary file + * + * @returns {Summary} summary instance + */ + clear() { + return __awaiter(this, void 0, void 0, function* () { + return this.emptyBuffer().write({ overwrite: true }); + }); + } + /** + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer + */ + stringify() { + return this._buffer; + } + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer() { + return this._buffer.length === 0; + } + /** + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance + */ + emptyBuffer() { + this._buffer = ''; + return this; + } + /** + * Adds raw text to the summary buffer + * + * @param {string} text content to add + * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) + * + * @returns {Summary} summary instance + */ + addRaw(text, addEOL = false) { + this._buffer += text; + return addEOL ? this.addEOL() : this; + } + /** + * Adds the operating system-specific end-of-line marker to the buffer + * + * @returns {Summary} summary instance + */ + addEOL() { + return this.addRaw(os_1.EOL); + } + /** + * Adds an HTML codeblock to the summary buffer + * + * @param {string} code content to render within fenced code block + * @param {string} lang (optional) language to syntax highlight code + * + * @returns {Summary} summary instance + */ + addCodeBlock(code, lang) { + const attrs = Object.assign({}, (lang && { lang })); + const element = this.wrap('pre', this.wrap('code', code), attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML list to the summary buffer + * + * @param {string[]} items list of items to render + * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) + * + * @returns {Summary} summary instance + */ + addList(items, ordered = false) { + const tag = ordered ? 'ol' : 'ul'; + const listItems = items.map(item => this.wrap('li', item)).join(''); + const element = this.wrap(tag, listItems); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML table to the summary buffer + * + * @param {SummaryTableCell[]} rows table rows + * + * @returns {Summary} summary instance + */ + addTable(rows) { + const tableBody = rows + .map(row => { + const cells = row + .map(cell => { + if (typeof cell === 'string') { + return this.wrap('td', cell); + } + const { header, data, colspan, rowspan } = cell; + const tag = header ? 'th' : 'td'; + const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); + return this.wrap(tag, data, attrs); + }) + .join(''); + return this.wrap('tr', cells); + }) + .join(''); + const element = this.wrap('table', tableBody); + return this.addRaw(element).addEOL(); + } + /** + * Adds a collapsable HTML details element to the summary buffer + * + * @param {string} label text for the closed state + * @param {string} content collapsable content + * + * @returns {Summary} summary instance + */ + addDetails(label, content) { + const element = this.wrap('details', this.wrap('summary', label) + content); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML image tag to the summary buffer + * + * @param {string} src path to the image you to embed + * @param {string} alt text description of the image + * @param {SummaryImageOptions} options (optional) addition image attributes + * + * @returns {Summary} summary instance + */ + addImage(src, alt, options) { + const { width, height } = options || {}; + const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); + const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML section heading element + * + * @param {string} text heading text + * @param {number | string} [level=1] (optional) the heading level, default: 1 + * + * @returns {Summary} summary instance + */ + addHeading(text, level) { + const tag = `h${level}`; + const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) + ? tag + : 'h1'; + const element = this.wrap(allowedTag, text); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML thematic break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addSeparator() { + const element = this.wrap('hr', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML line break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addBreak() { + const element = this.wrap('br', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML blockquote to the summary buffer + * + * @param {string} text quote text + * @param {string} cite (optional) citation url + * + * @returns {Summary} summary instance + */ + addQuote(text, cite) { + const attrs = Object.assign({}, (cite && { cite })); + const element = this.wrap('blockquote', text, attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML anchor tag to the summary buffer + * + * @param {string} text link text/content + * @param {string} href hyperlink + * + * @returns {Summary} summary instance + */ + addLink(text, href) { + const element = this.wrap('a', text, { href }); + return this.addRaw(element).addEOL(); + } +} +const _summary = new Summary(); +/** + * @deprecated use `core.summary` + */ +exports.markdownSummary = _summary; +exports.summary = _summary; +//# sourceMappingURL=summary.js.map \ No newline at end of file diff --git a/node_modules/@actions/core/lib/summary.js.map b/node_modules/@actions/core/lib/summary.js.map new file mode 100644 index 0000000..d598f26 --- /dev/null +++ b/node_modules/@actions/core/lib/summary.js.map @@ -0,0 +1 @@ +{"version":3,"file":"summary.js","sourceRoot":"","sources":["../src/summary.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/@actions/core/lib/utils.d.ts b/node_modules/@actions/core/lib/utils.d.ts new file mode 100644 index 0000000..3b9e28d --- /dev/null +++ b/node_modules/@actions/core/lib/utils.d.ts @@ -0,0 +1,14 @@ +import { AnnotationProperties } from './core'; +import { CommandProperties } from './command'; +/** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ +export declare function toCommandValue(input: any): string; +/** + * + * @param annotationProperties + * @returns The command properties to send with the actual annotation command + * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 + */ +export declare function toCommandProperties(annotationProperties: AnnotationProperties): CommandProperties; diff --git a/node_modules/@actions/core/lib/utils.js b/node_modules/@actions/core/lib/utils.js new file mode 100644 index 0000000..9b5ca44 --- /dev/null +++ b/node_modules/@actions/core/lib/utils.js @@ -0,0 +1,40 @@ +"use strict"; +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toCommandProperties = exports.toCommandValue = void 0; +/** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; + } + else if (typeof input === 'string' || input instanceof String) { + return input; + } + return JSON.stringify(input); +} +exports.toCommandValue = toCommandValue; +/** + * + * @param annotationProperties + * @returns The command properties to send with the actual annotation command + * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 + */ +function toCommandProperties(annotationProperties) { + if (!Object.keys(annotationProperties).length) { + return {}; + } + return { + title: annotationProperties.title, + file: annotationProperties.file, + line: annotationProperties.startLine, + endLine: annotationProperties.endLine, + col: annotationProperties.startColumn, + endColumn: annotationProperties.endColumn + }; +} +exports.toCommandProperties = toCommandProperties; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@actions/core/lib/utils.js.map b/node_modules/@actions/core/lib/utils.js.map new file mode 100644 index 0000000..8211bb7 --- /dev/null +++ b/node_modules/@actions/core/lib/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";AAAA,mCAAmC;AACnC,uDAAuD;;;AAKvD;;;GAGG;AACH,SAAgB,cAAc,CAAC,KAAU;IACvC,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,EAAE;QACzC,OAAO,EAAE,CAAA;KACV;SAAM,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,YAAY,MAAM,EAAE;QAC/D,OAAO,KAAe,CAAA;KACvB;IACD,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;AAC9B,CAAC;AAPD,wCAOC;AAED;;;;;GAKG;AACH,SAAgB,mBAAmB,CACjC,oBAA0C;IAE1C,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC,MAAM,EAAE;QAC7C,OAAO,EAAE,CAAA;KACV;IAED,OAAO;QACL,KAAK,EAAE,oBAAoB,CAAC,KAAK;QACjC,IAAI,EAAE,oBAAoB,CAAC,IAAI;QAC/B,IAAI,EAAE,oBAAoB,CAAC,SAAS;QACpC,OAAO,EAAE,oBAAoB,CAAC,OAAO;QACrC,GAAG,EAAE,oBAAoB,CAAC,WAAW;QACrC,SAAS,EAAE,oBAAoB,CAAC,SAAS;KAC1C,CAAA;AACH,CAAC;AAfD,kDAeC"} \ No newline at end of file diff --git a/node_modules/@actions/core/package.json b/node_modules/@actions/core/package.json index f2e5ef3..1f3824d 100644 --- a/node_modules/@actions/core/package.json +++ b/node_modules/@actions/core/package.json @@ -1,54 +1,24 @@ { - "_from": "@actions/core", - "_id": "@actions/core@1.2.0", - "_inBundle": false, - "_integrity": "sha512-ZKdyhlSlyz38S6YFfPnyNgCDZuAF2T0Qv5eHflNWytPS8Qjvz39bZFMry9Bb/dpSnqWcNeav5yM2CTYpJeY+Dw==", - "_location": "/@actions/core", - "_phantomChildren": {}, - "_requested": { - "type": "tag", - "registry": true, - "raw": "@actions/core", - "name": "@actions/core", - "escapedName": "@actions%2fcore", - "scope": "@actions", - "rawSpec": "", - "saveSpec": null, - "fetchSpec": "latest" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.0.tgz", - "_shasum": "aa5f52b26c362c821d41557e599371a42f6c0b3d", - "_spec": "@actions/core", - "_where": "C:\\MyTools\\projects\\get-xml-info", - "bugs": { - "url": "https://github.com/actions/toolkit/issues" - }, - "bundleDependencies": false, - "deprecated": false, + "name": "@actions/core", + "version": "1.10.0", "description": "Actions core lib", - "devDependencies": { - "@types/node": "^12.0.2" - }, - "directories": { - "lib": "lib", - "test": "__tests__" - }, - "files": [ - "lib" - ], - "homepage": "https://github.com/actions/toolkit/tree/master/packages/core", "keywords": [ "github", "actions", "core" ], + "homepage": "https://github.com/actions/toolkit/tree/main/packages/core", "license": "MIT", "main": "lib/core.js", - "name": "@actions/core", + "types": "lib/core.d.ts", + "directories": { + "lib": "lib", + "test": "__tests__" + }, + "files": [ + "lib", + "!.DS_Store" + ], "publishConfig": { "access": "public" }, @@ -58,8 +28,19 @@ "directory": "packages/core" }, "scripts": { + "audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json", "test": "echo \"Error: run tests from root\" && exit 1", "tsc": "tsc" }, - "version": "1.2.0" + "bugs": { + "url": "https://github.com/actions/toolkit/issues" + }, + "dependencies": { + "@actions/http-client": "^2.0.1", + "uuid": "^8.3.2" + }, + "devDependencies": { + "@types/node": "^12.0.2", + "@types/uuid": "^8.3.4" + } } diff --git a/node_modules/@actions/http-client/LICENSE b/node_modules/@actions/http-client/LICENSE new file mode 100644 index 0000000..5823a51 --- /dev/null +++ b/node_modules/@actions/http-client/LICENSE @@ -0,0 +1,21 @@ +Actions Http Client for Node.js + +Copyright (c) GitHub, Inc. + +All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/@actions/http-client/README.md b/node_modules/@actions/http-client/README.md new file mode 100644 index 0000000..7e06ade --- /dev/null +++ b/node_modules/@actions/http-client/README.md @@ -0,0 +1,73 @@ +# `@actions/http-client` + +A lightweight HTTP client optimized for building actions. + +## Features + + - HTTP client with TypeScript generics and async/await/Promises + - Typings included! + - [Proxy support](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/about-self-hosted-runners#using-a-proxy-server-with-self-hosted-runners) just works with actions and the runner + - Targets ES2019 (runner runs actions with node 12+). Only supported on node 12+. + - Basic, Bearer and PAT Support out of the box. Extensible handlers for others. + - Redirects supported + +Features and releases [here](./RELEASES.md) + +## Install + +``` +npm install @actions/http-client --save +``` + +## Samples + +See the [tests](./__tests__) for detailed examples. + +## Errors + +### HTTP + +The HTTP client does not throw unless truly exceptional. + +* A request that successfully executes resulting in a 404, 500 etc... will return a response object with a status code and a body. +* Redirects (3xx) will be followed by default. + +See the [tests](./__tests__) for detailed examples. + +## Debugging + +To enable detailed console logging of all HTTP requests and responses, set the NODE_DEBUG environment varible: + +```shell +export NODE_DEBUG=http +``` + +## Node support + +The http-client is built using the latest LTS version of Node 12. It may work on previous node LTS versions but it's tested and officially supported on Node12+. + +## Support and Versioning + +We follow semver and will hold compatibility between major versions and increment the minor version with new features and capabilities (while holding compat). + +## Contributing + +We welcome PRs. Please create an issue and if applicable, a design before proceeding with code. + +once: + +``` +npm install +``` + +To build: + +``` +npm run build +``` + +To run all tests: + +``` +npm test +``` diff --git a/node_modules/@actions/http-client/lib/auth.d.ts b/node_modules/@actions/http-client/lib/auth.d.ts new file mode 100644 index 0000000..8cc9fc3 --- /dev/null +++ b/node_modules/@actions/http-client/lib/auth.d.ts @@ -0,0 +1,26 @@ +/// +import * as http from 'http'; +import * as ifm from './interfaces'; +import { HttpClientResponse } from './index'; +export declare class BasicCredentialHandler implements ifm.RequestHandler { + username: string; + password: string; + constructor(username: string, password: string); + prepareRequest(options: http.RequestOptions): void; + canHandleAuthentication(): boolean; + handleAuthentication(): Promise; +} +export declare class BearerCredentialHandler implements ifm.RequestHandler { + token: string; + constructor(token: string); + prepareRequest(options: http.RequestOptions): void; + canHandleAuthentication(): boolean; + handleAuthentication(): Promise; +} +export declare class PersonalAccessTokenCredentialHandler implements ifm.RequestHandler { + token: string; + constructor(token: string); + prepareRequest(options: http.RequestOptions): void; + canHandleAuthentication(): boolean; + handleAuthentication(): Promise; +} diff --git a/node_modules/@actions/http-client/lib/auth.js b/node_modules/@actions/http-client/lib/auth.js new file mode 100644 index 0000000..2c150a3 --- /dev/null +++ b/node_modules/@actions/http-client/lib/auth.js @@ -0,0 +1,81 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; +class BasicCredentialHandler { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.BasicCredentialHandler = BasicCredentialHandler; +class BearerCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.BearerCredentialHandler = BearerCredentialHandler; +class PersonalAccessTokenCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; +//# sourceMappingURL=auth.js.map \ No newline at end of file diff --git a/node_modules/@actions/http-client/lib/auth.js.map b/node_modules/@actions/http-client/lib/auth.js.map new file mode 100644 index 0000000..7d3a18a --- /dev/null +++ b/node_modules/@actions/http-client/lib/auth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,MAAa,sBAAsB;IAIjC,YAAY,QAAgB,EAAE,QAAgB;QAC5C,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;IAC1B,CAAC;IAED,cAAc,CAAC,OAA4B;QACzC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YACpB,MAAM,KAAK,CAAC,4BAA4B,CAAC,CAAA;SAC1C;QACD,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,SAAS,MAAM,CAAC,IAAI,CACrD,GAAG,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,QAAQ,EAAE,CACpC,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAA;IACxB,CAAC;IAED,iCAAiC;IACjC,uBAAuB;QACrB,OAAO,KAAK,CAAA;IACd,CAAC;IAEK,oBAAoB;;YACxB,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAA;QACpC,CAAC;KAAA;CACF;AA1BD,wDA0BC;AAED,MAAa,uBAAuB;IAGlC,YAAY,KAAa;QACvB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;IAED,yCAAyC;IACzC,sDAAsD;IACtD,cAAc,CAAC,OAA4B;QACzC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YACpB,MAAM,KAAK,CAAC,4BAA4B,CAAC,CAAA;SAC1C;QACD,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,UAAU,IAAI,CAAC,KAAK,EAAE,CAAA;IAC3D,CAAC;IAED,iCAAiC;IACjC,uBAAuB;QACrB,OAAO,KAAK,CAAA;IACd,CAAC;IAEK,oBAAoB;;YACxB,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAA;QACpC,CAAC;KAAA;CACF;AAxBD,0DAwBC;AAED,MAAa,oCAAoC;IAI/C,YAAY,KAAa;QACvB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;IAED,yCAAyC;IACzC,sDAAsD;IACtD,cAAc,CAAC,OAA4B;QACzC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YACpB,MAAM,KAAK,CAAC,4BAA4B,CAAC,CAAA;SAC1C;QACD,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,SAAS,MAAM,CAAC,IAAI,CACrD,OAAO,IAAI,CAAC,KAAK,EAAE,CACpB,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAA;IACxB,CAAC;IAED,iCAAiC;IACjC,uBAAuB;QACrB,OAAO,KAAK,CAAA;IACd,CAAC;IAEK,oBAAoB;;YACxB,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAA;QACpC,CAAC;KAAA;CACF;AA3BD,oFA2BC"} \ No newline at end of file diff --git a/node_modules/@actions/http-client/lib/index.d.ts b/node_modules/@actions/http-client/lib/index.d.ts new file mode 100644 index 0000000..fe733d1 --- /dev/null +++ b/node_modules/@actions/http-client/lib/index.d.ts @@ -0,0 +1,123 @@ +/// +import * as http from 'http'; +import * as ifm from './interfaces'; +export declare enum HttpCodes { + OK = 200, + MultipleChoices = 300, + MovedPermanently = 301, + ResourceMoved = 302, + SeeOther = 303, + NotModified = 304, + UseProxy = 305, + SwitchProxy = 306, + TemporaryRedirect = 307, + PermanentRedirect = 308, + BadRequest = 400, + Unauthorized = 401, + PaymentRequired = 402, + Forbidden = 403, + NotFound = 404, + MethodNotAllowed = 405, + NotAcceptable = 406, + ProxyAuthenticationRequired = 407, + RequestTimeout = 408, + Conflict = 409, + Gone = 410, + TooManyRequests = 429, + InternalServerError = 500, + NotImplemented = 501, + BadGateway = 502, + ServiceUnavailable = 503, + GatewayTimeout = 504 +} +export declare enum Headers { + Accept = "accept", + ContentType = "content-type" +} +export declare enum MediaTypes { + ApplicationJson = "application/json" +} +/** + * Returns the proxy URL, depending upon the supplied url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ +export declare function getProxyUrl(serverUrl: string): string; +export declare class HttpClientError extends Error { + constructor(message: string, statusCode: number); + statusCode: number; + result?: any; +} +export declare class HttpClientResponse { + constructor(message: http.IncomingMessage); + message: http.IncomingMessage; + readBody(): Promise; +} +export declare function isHttps(requestUrl: string): boolean; +export declare class HttpClient { + userAgent: string | undefined; + handlers: ifm.RequestHandler[]; + requestOptions: ifm.RequestOptions | undefined; + private _ignoreSslError; + private _socketTimeout; + private _allowRedirects; + private _allowRedirectDowngrade; + private _maxRedirects; + private _allowRetries; + private _maxRetries; + private _agent; + private _proxyAgent; + private _keepAlive; + private _disposed; + constructor(userAgent?: string, handlers?: ifm.RequestHandler[], requestOptions?: ifm.RequestOptions); + options(requestUrl: string, additionalHeaders?: http.OutgoingHttpHeaders): Promise; + get(requestUrl: string, additionalHeaders?: http.OutgoingHttpHeaders): Promise; + del(requestUrl: string, additionalHeaders?: http.OutgoingHttpHeaders): Promise; + post(requestUrl: string, data: string, additionalHeaders?: http.OutgoingHttpHeaders): Promise; + patch(requestUrl: string, data: string, additionalHeaders?: http.OutgoingHttpHeaders): Promise; + put(requestUrl: string, data: string, additionalHeaders?: http.OutgoingHttpHeaders): Promise; + head(requestUrl: string, additionalHeaders?: http.OutgoingHttpHeaders): Promise; + sendStream(verb: string, requestUrl: string, stream: NodeJS.ReadableStream, additionalHeaders?: http.OutgoingHttpHeaders): Promise; + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl: string, additionalHeaders?: http.OutgoingHttpHeaders): Promise>; + postJson(requestUrl: string, obj: any, additionalHeaders?: http.OutgoingHttpHeaders): Promise>; + putJson(requestUrl: string, obj: any, additionalHeaders?: http.OutgoingHttpHeaders): Promise>; + patchJson(requestUrl: string, obj: any, additionalHeaders?: http.OutgoingHttpHeaders): Promise>; + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb: string, requestUrl: string, data: string | NodeJS.ReadableStream | null, headers?: http.OutgoingHttpHeaders): Promise; + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose(): void; + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info: ifm.RequestInfo, data: string | NodeJS.ReadableStream | null): Promise; + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info: ifm.RequestInfo, data: string | NodeJS.ReadableStream | null, onResult: (err?: Error, res?: HttpClientResponse) => void): void; + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl: string): http.Agent; + private _prepareRequest; + private _mergeHeaders; + private _getExistingOrDefaultHeader; + private _getAgent; + private _performExponentialBackoff; + private _processResponse; +} diff --git a/node_modules/@actions/http-client/lib/index.js b/node_modules/@actions/http-client/lib/index.js new file mode 100644 index 0000000..a1b7d03 --- /dev/null +++ b/node_modules/@actions/http-client/lib/index.js @@ -0,0 +1,605 @@ +"use strict"; +/* eslint-disable @typescript-eslint/no-explicit-any */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; +const http = __importStar(require("http")); +const https = __importStar(require("https")); +const pm = __importStar(require("./proxy")); +const tunnel = __importStar(require("tunnel")); +var HttpCodes; +(function (HttpCodes) { + HttpCodes[HttpCodes["OK"] = 200] = "OK"; + HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; + HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; + HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; + HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; + HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; + HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; + HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; + HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; + HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); +var Headers; +(function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; +})(Headers = exports.Headers || (exports.Headers = {})); +var MediaTypes; +(function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; +})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); +/** + * Returns the proxy URL, depending upon the supplied url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ +function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ''; +} +exports.getProxyUrl = getProxyUrl; +const HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +const HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; +const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; +const ExponentialBackoffCeiling = 10; +const ExponentialBackoffTimeSlice = 5; +class HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = 'HttpClientError'; + this.statusCode = statusCode; + Object.setPrototypeOf(this, HttpClientError.prototype); + } +} +exports.HttpClientError = HttpClientError; +class HttpClientResponse { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on('data', (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on('end', () => { + resolve(output.toString()); + }); + })); + }); + } +} +exports.HttpClientResponse = HttpClientResponse; +function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === 'https:'; +} +exports.isHttps = isHttps; +class HttpClient { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } + } + options(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('GET', requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('POST', requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PUT', requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error('Client has already been disposed.'); + } + const parsedUrl = new URL(requestUrl); + let info = this._prepareRequest(verb, parsedUrl, headers); + // Only perform retries on reads since writes may not be idempotent. + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) + ? this._maxRetries + 1 + : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info, data); + // Check if it's an authentication challenge + if (response && + response.message && + response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info, data); + } + else { + // We have received an unauthorized response but have no handlers to handle it. + // Let the response return to the caller. + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && + HttpRedirectCodes.includes(response.message.statusCode) && + this._allowRedirects && + redirectsRemaining > 0) { + const redirectUrl = response.message.headers['location']; + if (!redirectUrl) { + // if there's no location to redirect to, we won't + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === 'https:' && + parsedUrl.protocol !== parsedRedirectUrl.protocol && + !this._allowRedirectDowngrade) { + throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); + } + // we need to finish reading the response before reassigning response + // which will leak the open socket. + yield response.readBody(); + // strip authorization header if redirected to a different hostname + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + // header names are case insensitive + if (header.toLowerCase() === 'authorization') { + delete headers[header]; + } + } + } + // let's make the request with the new redirectUrl + info = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info, data); + redirectsRemaining--; + } + if (!response.message.statusCode || + !HttpResponseRetryCodes.includes(response.message.statusCode)) { + // If not a retry code, return immediately instead of retrying + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info, data) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } + else if (!res) { + // If `err` is not passed, then `res` must be passed. + reject(new Error('Unknown error')); + } + else { + resolve(res); + } + } + this.requestRawWithCallback(info, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info, data, onResult) { + if (typeof data === 'string') { + if (!info.options.headers) { + info.options.headers = {}; + } + info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info.httpModule.request(info.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(undefined, res); + }); + let socket; + req.on('socket', sock => { + socket = sock; + }); + // If we ever get disconnected, we want the socket to timeout eventually + req.setTimeout(this._socketTimeout || 3 * 60000, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info.options.path}`)); + }); + req.on('error', function (err) { + // err has statusCode property + // res should have headers + handleResult(err); + }); + if (data && typeof data === 'string') { + req.write(data, 'utf8'); + } + if (data && typeof data !== 'string') { + data.on('close', function () { + req.end(); + }); + data.pipe(req); + } + else { + req.end(); + } + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info = {}; + info.parsedUrl = requestUrl; + const usingSsl = info.parsedUrl.protocol === 'https:'; + info.httpModule = usingSsl ? https : http; + const defaultPort = usingSsl ? 443 : 80; + info.options = {}; + info.options.host = info.parsedUrl.hostname; + info.options.port = info.parsedUrl.port + ? parseInt(info.parsedUrl.port) + : defaultPort; + info.options.path = + (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); + info.options.method = method; + info.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info.options.headers['user-agent'] = this.userAgent; + } + info.options.agent = this._getAgent(info.parsedUrl); + // gives handlers an opportunity to participate + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info.options); + } + } + return info; + } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (this._keepAlive && !useProxy) { + agent = this._agent; + } + // if agent is already assigned use that agent. + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + })), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === 'https:'; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } + else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + // if reusing agent across request and tunneling agent isn't assigned create a new agent + if (this._keepAlive && !agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https.Agent(options) : new http.Agent(options); + this._agent = agent; + } + // if not using private agent and tunnel agent isn't setup then use global agent + if (!agent) { + agent = usingSsl ? https.globalAgent : http.globalAgent; + } + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise(resolve => setTimeout(() => resolve(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + // not found leads to null obj returned + if (statusCode === HttpCodes.NotFound) { + resolve(response); + } + // get the result from the body + function dateTimeDeserializer(key, value) { + if (typeof value === 'string') { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } + else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } + catch (err) { + // Invalid resource (contents not json); leaving result obj null + } + // note that 3xx redirects are handled by the http layer. + if (statusCode > 299) { + let msg; + // if exception/error in body, attempt to get better error + if (obj && obj.message) { + msg = obj.message; + } + else if (contents && contents.length > 0) { + // it may be the case that the exception is in the body message as string + msg = contents; + } + else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } + else { + resolve(response); + } + })); + }); + } +} +exports.HttpClient = HttpClient; +const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@actions/http-client/lib/index.js.map b/node_modules/@actions/http-client/lib/index.js.map new file mode 100644 index 0000000..ca8ea41 --- /dev/null +++ b/node_modules/@actions/http-client/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/@actions/http-client/lib/interfaces.d.ts b/node_modules/@actions/http-client/lib/interfaces.d.ts new file mode 100644 index 0000000..54fd4a8 --- /dev/null +++ b/node_modules/@actions/http-client/lib/interfaces.d.ts @@ -0,0 +1,44 @@ +/// +import * as http from 'http'; +import * as https from 'https'; +import { HttpClientResponse } from './index'; +export interface HttpClient { + options(requestUrl: string, additionalHeaders?: http.OutgoingHttpHeaders): Promise; + get(requestUrl: string, additionalHeaders?: http.OutgoingHttpHeaders): Promise; + del(requestUrl: string, additionalHeaders?: http.OutgoingHttpHeaders): Promise; + post(requestUrl: string, data: string, additionalHeaders?: http.OutgoingHttpHeaders): Promise; + patch(requestUrl: string, data: string, additionalHeaders?: http.OutgoingHttpHeaders): Promise; + put(requestUrl: string, data: string, additionalHeaders?: http.OutgoingHttpHeaders): Promise; + sendStream(verb: string, requestUrl: string, stream: NodeJS.ReadableStream, additionalHeaders?: http.OutgoingHttpHeaders): Promise; + request(verb: string, requestUrl: string, data: string | NodeJS.ReadableStream, headers: http.OutgoingHttpHeaders): Promise; + requestRaw(info: RequestInfo, data: string | NodeJS.ReadableStream): Promise; + requestRawWithCallback(info: RequestInfo, data: string | NodeJS.ReadableStream, onResult: (err?: Error, res?: HttpClientResponse) => void): void; +} +export interface RequestHandler { + prepareRequest(options: http.RequestOptions): void; + canHandleAuthentication(response: HttpClientResponse): boolean; + handleAuthentication(httpClient: HttpClient, requestInfo: RequestInfo, data: string | NodeJS.ReadableStream | null): Promise; +} +export interface RequestInfo { + options: http.RequestOptions; + parsedUrl: URL; + httpModule: typeof http | typeof https; +} +export interface RequestOptions { + headers?: http.OutgoingHttpHeaders; + socketTimeout?: number; + ignoreSslError?: boolean; + allowRedirects?: boolean; + allowRedirectDowngrade?: boolean; + maxRedirects?: number; + maxSockets?: number; + keepAlive?: boolean; + deserializeDates?: boolean; + allowRetries?: boolean; + maxRetries?: number; +} +export interface TypedResponse { + statusCode: number; + result: T | null; + headers: http.IncomingHttpHeaders; +} diff --git a/node_modules/@actions/http-client/lib/interfaces.js b/node_modules/@actions/http-client/lib/interfaces.js new file mode 100644 index 0000000..db91911 --- /dev/null +++ b/node_modules/@actions/http-client/lib/interfaces.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=interfaces.js.map \ No newline at end of file diff --git a/node_modules/@actions/http-client/lib/interfaces.js.map b/node_modules/@actions/http-client/lib/interfaces.js.map new file mode 100644 index 0000000..8fb5f7d --- /dev/null +++ b/node_modules/@actions/http-client/lib/interfaces.js.map @@ -0,0 +1 @@ +{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@actions/http-client/lib/proxy.d.ts b/node_modules/@actions/http-client/lib/proxy.d.ts new file mode 100644 index 0000000..4599865 --- /dev/null +++ b/node_modules/@actions/http-client/lib/proxy.d.ts @@ -0,0 +1,2 @@ +export declare function getProxyUrl(reqUrl: URL): URL | undefined; +export declare function checkBypass(reqUrl: URL): boolean; diff --git a/node_modules/@actions/http-client/lib/proxy.js b/node_modules/@actions/http-client/lib/proxy.js new file mode 100644 index 0000000..528ffe4 --- /dev/null +++ b/node_modules/@actions/http-client/lib/proxy.js @@ -0,0 +1,61 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.checkBypass = exports.getProxyUrl = void 0; +function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === 'https:'; + if (checkBypass(reqUrl)) { + return undefined; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env['https_proxy'] || process.env['HTTPS_PROXY']; + } + else { + return process.env['http_proxy'] || process.env['HTTP_PROXY']; + } + })(); + if (proxyVar) { + return new URL(proxyVar); + } + else { + return undefined; + } +} +exports.getProxyUrl = getProxyUrl; +function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; + if (!noProxy) { + return false; + } + // Determine the request port + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } + else if (reqUrl.protocol === 'http:') { + reqPort = 80; + } + else if (reqUrl.protocol === 'https:') { + reqPort = 443; + } + // Format the request hostname and hostname with port + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === 'number') { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + // Compare request host against noproxy + for (const upperNoProxyItem of noProxy + .split(',') + .map(x => x.trim().toUpperCase()) + .filter(x => x)) { + if (upperReqHosts.some(x => x === upperNoProxyItem)) { + return true; + } + } + return false; +} +exports.checkBypass = checkBypass; +//# sourceMappingURL=proxy.js.map \ No newline at end of file diff --git a/node_modules/@actions/http-client/lib/proxy.js.map b/node_modules/@actions/http-client/lib/proxy.js.map new file mode 100644 index 0000000..4440de9 --- /dev/null +++ b/node_modules/@actions/http-client/lib/proxy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"proxy.js","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":";;;AAAA,SAAgB,WAAW,CAAC,MAAW;IACrC,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,KAAK,QAAQ,CAAA;IAE7C,IAAI,WAAW,CAAC,MAAM,CAAC,EAAE;QACvB,OAAO,SAAS,CAAA;KACjB;IAED,MAAM,QAAQ,GAAG,CAAC,GAAG,EAAE;QACrB,IAAI,QAAQ,EAAE;YACZ,OAAO,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAA;SAChE;aAAM;YACL,OAAO,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,CAAA;SAC9D;IACH,CAAC,CAAC,EAAE,CAAA;IAEJ,IAAI,QAAQ,EAAE;QACZ,OAAO,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAA;KACzB;SAAM;QACL,OAAO,SAAS,CAAA;KACjB;AACH,CAAC;AApBD,kCAoBC;AAED,SAAgB,WAAW,CAAC,MAAW;IACrC,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE;QACpB,OAAO,KAAK,CAAA;KACb;IAED,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,EAAE,CAAA;IACxE,IAAI,CAAC,OAAO,EAAE;QACZ,OAAO,KAAK,CAAA;KACb;IAED,6BAA6B;IAC7B,IAAI,OAA2B,CAAA;IAC/B,IAAI,MAAM,CAAC,IAAI,EAAE;QACf,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;KAC9B;SAAM,IAAI,MAAM,CAAC,QAAQ,KAAK,OAAO,EAAE;QACtC,OAAO,GAAG,EAAE,CAAA;KACb;SAAM,IAAI,MAAM,CAAC,QAAQ,KAAK,QAAQ,EAAE;QACvC,OAAO,GAAG,GAAG,CAAA;KACd;IAED,qDAAqD;IACrD,MAAM,aAAa,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAA;IACrD,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;QAC/B,aAAa,CAAC,IAAI,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,IAAI,OAAO,EAAE,CAAC,CAAA;KACrD;IAED,uCAAuC;IACvC,KAAK,MAAM,gBAAgB,IAAI,OAAO;SACnC,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;SAChC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE;QACjB,IAAI,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,gBAAgB,CAAC,EAAE;YACnD,OAAO,IAAI,CAAA;SACZ;KACF;IAED,OAAO,KAAK,CAAA;AACd,CAAC;AArCD,kCAqCC"} \ No newline at end of file diff --git a/node_modules/@actions/http-client/package.json b/node_modules/@actions/http-client/package.json new file mode 100644 index 0000000..c1de221 --- /dev/null +++ b/node_modules/@actions/http-client/package.json @@ -0,0 +1,48 @@ +{ + "name": "@actions/http-client", + "version": "2.0.1", + "description": "Actions Http Client", + "keywords": [ + "github", + "actions", + "http" + ], + "homepage": "https://github.com/actions/toolkit/tree/main/packages/http-client", + "license": "MIT", + "main": "lib/index.js", + "types": "lib/index.d.ts", + "directories": { + "lib": "lib", + "test": "__tests__" + }, + "files": [ + "lib", + "!.DS_Store" + ], + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/actions/toolkit.git", + "directory": "packages/http-client" + }, + "scripts": { + "audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json", + "test": "echo \"Error: run tests from root\" && exit 1", + "build": "tsc", + "format": "prettier --write **/*.ts", + "format-check": "prettier --check **/*.ts", + "tsc": "tsc" + }, + "bugs": { + "url": "https://github.com/actions/toolkit/issues" + }, + "devDependencies": { + "@types/tunnel": "0.0.3", + "proxy": "^1.0.1" + }, + "dependencies": { + "tunnel": "^0.0.6" + } +} diff --git a/node_modules/minimist/.eslintrc b/node_modules/minimist/.eslintrc new file mode 100644 index 0000000..137f67b --- /dev/null +++ b/node_modules/minimist/.eslintrc @@ -0,0 +1,54 @@ +{ + "root": true, + + "extends": "@ljharb/eslint-config/node/0.4", + + "rules": { + "array-bracket-spacing": 0, + "array-element-newline": 0, + "brace-style": 1, + "camelcase": 1, + "comma-dangle": 1, + "comma-spacing": 1, + "complexity": 0, + "curly": 1, + "dot-notation": 1, + "eol-last": 1, + "func-style": 1, + "function-paren-newline": 1, + "indent": [1, 4], + "key-spacing": 1, + "max-lines-per-function": 0, + "max-nested-callbacks": 1, + "max-statements": 0, + "multiline-comment-style": 1, + "no-array-constructor": 1, + "no-continue": 1, + "no-div-regex": 1, + "no-extra-parens": 1, + "no-mixed-operators": 1, + "no-multi-spaces": 1, + "no-multiple-empty-lines": 1, + "no-param-reassign": 1, + "no-plusplus": 1, + "no-proto": 1, + "no-redeclare": 1, + "no-restricted-syntax": 1, + "no-shadow": 1, + "no-trailing-spaces": 1, + "no-unused-vars": 1, + "no-use-before-define": 1, + "object-curly-newline": 1, + "object-curly-spacing": 1, + "operator-linebreak": 1, + "quote-props": 1, + "quotes": 1, + "semi-style": 1, + "semi": 1, + "space-before-blocks": 1, + "space-before-function-paren": 1, + "space-infix-ops": 1, + "strict": 1, + "wrap-regex": 1, + }, +} diff --git a/node_modules/minimist/.github/FUNDING.yml b/node_modules/minimist/.github/FUNDING.yml new file mode 100644 index 0000000..a936622 --- /dev/null +++ b/node_modules/minimist/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/minimist +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/minimist/.nycrc b/node_modules/minimist/.nycrc new file mode 100644 index 0000000..55c3d29 --- /dev/null +++ b/node_modules/minimist/.nycrc @@ -0,0 +1,14 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "example", + "test" + ] +} diff --git a/node_modules/minimist/.travis.yml b/node_modules/minimist/.travis.yml deleted file mode 100644 index 74c57bf..0000000 --- a/node_modules/minimist/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: node_js -node_js: - - "0.8" - - "0.10" - - "0.12" - - "iojs" -before_install: - - npm install -g npm@~1.4.6 diff --git a/node_modules/minimist/CHANGELOG.md b/node_modules/minimist/CHANGELOG.md new file mode 100644 index 0000000..e0e00bd --- /dev/null +++ b/node_modules/minimist/CHANGELOG.md @@ -0,0 +1,212 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.7](https://github.com/minimistjs/minimist/compare/v1.2.6...v1.2.7) - 2022-10-10 + +### Commits + +- [meta] add `auto-changelog` [`0ebf4eb`](https://github.com/minimistjs/minimist/commit/0ebf4ebcd5f7787a5524d31a849ef41316b83c3c) +- [actions] add reusable workflows [`e115b63`](https://github.com/minimistjs/minimist/commit/e115b63fa9d3909f33b00a2db647ff79068388de) +- [eslint] add eslint; rules to enable later are warnings [`f58745b`](https://github.com/minimistjs/minimist/commit/f58745b9bb84348e1be72af7dbba5840c7c13013) +- [Dev Deps] switch from `covert` to `nyc` [`ab03356`](https://github.com/minimistjs/minimist/commit/ab033567b9c8b31117cb026dc7f1e592ce455c65) +- [readme] rename and add badges [`236f4a0`](https://github.com/minimistjs/minimist/commit/236f4a07e4ebe5ee44f1496ec6974991ab293ffd) +- [meta] create FUNDING.yml; add `funding` in package.json [`783a49b`](https://github.com/minimistjs/minimist/commit/783a49bfd47e8335d3098a8cac75662cf71eb32a) +- [meta] use `npmignore` to autogenerate an npmignore file [`f81ece6`](https://github.com/minimistjs/minimist/commit/f81ece6aaec2fa14e69ff4f1e0407a8c4e2635a2) +- Only apps should have lockfiles [`56cad44`](https://github.com/minimistjs/minimist/commit/56cad44c7f879b9bb5ec18fcc349308024a89bfc) +- [Dev Deps] update `covert`, `tape`; remove unnecessary `tap` [`49c5f9f`](https://github.com/minimistjs/minimist/commit/49c5f9fb7e6a92db9eb340cc679de92fb3aacded) +- [Tests] add `aud` in `posttest` [`228ae93`](https://github.com/minimistjs/minimist/commit/228ae938f3cd9db9dfd8bd7458b076a7b2aef280) +- [meta] add `safe-publish-latest` [`01fc23f`](https://github.com/minimistjs/minimist/commit/01fc23f5104f85c75059972e01dd33796ab529ff) +- [meta] update repo URLs [`6b164c7`](https://github.com/minimistjs/minimist/commit/6b164c7d68e0b6bf32f894699effdfb7c63041dd) + +## [v1.2.6](https://github.com/minimistjs/minimist/compare/v1.2.5...v1.2.6) - 2022-03-21 + +### Commits + +- test from prototype pollution PR [`bc8ecee`](https://github.com/minimistjs/minimist/commit/bc8ecee43875261f4f17eb20b1243d3ed15e70eb) +- isConstructorOrProto adapted from PR [`c2b9819`](https://github.com/minimistjs/minimist/commit/c2b981977fa834b223b408cfb860f933c9811e4d) +- security notice for additional prototype pollution issue [`ef88b93`](https://github.com/minimistjs/minimist/commit/ef88b9325f77b5ee643ccfc97e2ebda577e4c4e2) + +## [v1.2.5](https://github.com/minimistjs/minimist/compare/v1.2.4...v1.2.5) - 2020-03-12 + +## [v1.2.4](https://github.com/minimistjs/minimist/compare/v1.2.3...v1.2.4) - 2020-03-11 + +### Commits + +- security notice [`4cf1354`](https://github.com/minimistjs/minimist/commit/4cf1354839cb972e38496d35e12f806eea92c11f) +- additional test for constructor prototype pollution [`1043d21`](https://github.com/minimistjs/minimist/commit/1043d212c3caaf871966e710f52cfdf02f9eea4b) + +## [v1.2.3](https://github.com/minimistjs/minimist/compare/v1.2.2...v1.2.3) - 2020-03-10 + +### Commits + +- more failing proto pollution tests [`13c01a5`](https://github.com/minimistjs/minimist/commit/13c01a5327736903704984b7f65616b8476850cc) +- even more aggressive checks for protocol pollution [`38a4d1c`](https://github.com/minimistjs/minimist/commit/38a4d1caead72ef99e824bb420a2528eec03d9ab) + +## [v1.2.2](https://github.com/minimistjs/minimist/compare/v1.2.1...v1.2.2) - 2020-03-10 + +### Commits + +- failing test for protocol pollution [`0efed03`](https://github.com/minimistjs/minimist/commit/0efed0340ec8433638758f7ca0c77cb20a0bfbab) +- cleanup [`67d3722`](https://github.com/minimistjs/minimist/commit/67d3722413448d00a62963d2d30c34656a92d7e2) +- console.dir -> console.log [`47acf72`](https://github.com/minimistjs/minimist/commit/47acf72c715a630bf9ea013867f47f1dd69dfc54) +- don't assign onto __proto__ [`63e7ed0`](https://github.com/minimistjs/minimist/commit/63e7ed05aa4b1889ec2f3b196426db4500cbda94) + +## [v1.2.1](https://github.com/minimistjs/minimist/compare/v1.2.0...v1.2.1) - 2020-03-10 + +### Merged + +- move the `opts['--']` example back where it belongs [`#63`](https://github.com/minimistjs/minimist/pull/63) + +### Commits + +- add test [`6be5dae`](https://github.com/minimistjs/minimist/commit/6be5dae35a32a987bcf4137fcd6c19c5200ee909) +- fix bad boolean regexp [`ac3fc79`](https://github.com/minimistjs/minimist/commit/ac3fc796e63b95128fdbdf67ea7fad71bd59aa76) + +## [v1.2.0](https://github.com/minimistjs/minimist/compare/v1.1.3...v1.2.0) - 2015-08-24 + +### Commits + +- failing -k=v short test [`63416b8`](https://github.com/minimistjs/minimist/commit/63416b8cd1d0d70e4714564cce465a36e4dd26d7) +- kv short fix [`6bbe145`](https://github.com/minimistjs/minimist/commit/6bbe14529166245e86424f220a2321442fe88dc3) +- failing kv short test [`f72ab7f`](https://github.com/minimistjs/minimist/commit/f72ab7f4572adc52902c9b6873cc969192f01b10) +- fixed kv test [`f5a48c3`](https://github.com/minimistjs/minimist/commit/f5a48c3e50e40ca54f00c8e84de4b4d6e9897fa8) +- enforce space between arg key and value [`86b321a`](https://github.com/minimistjs/minimist/commit/86b321affe648a8e016c095a4f0efa9d9074f502) + +## [v1.1.3](https://github.com/minimistjs/minimist/compare/v1.1.2...v1.1.3) - 2015-08-06 + +### Commits + +- add failing test - boolean alias array [`0fa3c5b`](https://github.com/minimistjs/minimist/commit/0fa3c5b3dd98551ddecf5392831b4c21211743fc) +- fix boolean values with multiple aliases [`9c0a6e7`](https://github.com/minimistjs/minimist/commit/9c0a6e7de25a273b11bbf9a7464f0bd833779795) + +## [v1.1.2](https://github.com/minimistjs/minimist/compare/v1.1.1...v1.1.2) - 2015-07-22 + +### Commits + +- Convert boolean arguments to boolean values [`8f3dc27`](https://github.com/minimistjs/minimist/commit/8f3dc27cf833f1d54671b6d0bcb55c2fe19672a9) +- use non-ancient npm, node 0.12 and iojs [`61ed1d0`](https://github.com/minimistjs/minimist/commit/61ed1d034b9ec7282764ce76f3992b1a0b4906ae) +- an older npm for 0.8 [`25cf778`](https://github.com/minimistjs/minimist/commit/25cf778b1220e7838a526832ad6972f75244054f) + +## [v1.1.1](https://github.com/minimistjs/minimist/compare/v1.1.0...v1.1.1) - 2015-03-10 + +### Commits + +- check that they type of a value is a boolean, not just that it is currently set to a boolean [`6863198`](https://github.com/minimistjs/minimist/commit/6863198e36139830ff1f20ffdceaddd93f2c1db9) +- upgrade tape, fix type issues from old tape version [`806712d`](https://github.com/minimistjs/minimist/commit/806712df91604ed02b8e39aa372b84aea659ee34) +- test for setting a boolean to a null default [`8c444fe`](https://github.com/minimistjs/minimist/commit/8c444fe89384ded7d441c120915ea60620b01dd3) +- if the previous value was a boolean, without an default (or with an alias) don't make an array either [`e5f419a`](https://github.com/minimistjs/minimist/commit/e5f419a3b5b3bc3f9e5ac71b7040621af70ed2dd) + +## [v1.1.0](https://github.com/minimistjs/minimist/compare/v1.0.0...v1.1.0) - 2014-08-10 + +### Commits + +- add support for handling "unknown" options not registered with the parser. [`6f3cc5d`](https://github.com/minimistjs/minimist/commit/6f3cc5d4e84524932a6ef2ce3592acc67cdd4383) +- reformat package.json [`02ed371`](https://github.com/minimistjs/minimist/commit/02ed37115194d3697ff358e8e25e5e66bab1d9f8) +- coverage script [`e5531ba`](https://github.com/minimistjs/minimist/commit/e5531ba0479da3b8138d3d8cac545d84ccb1c8df) +- extra fn to get 100% coverage again [`a6972da`](https://github.com/minimistjs/minimist/commit/a6972da89e56bf77642f8ec05a13b6558db93498) + +## [v1.0.0](https://github.com/minimistjs/minimist/compare/v0.2.1...v1.0.0) - 2014-08-10 + +### Commits + +- added stopEarly option [`471c7e4`](https://github.com/minimistjs/minimist/commit/471c7e4a7e910fc7ad8f9df850a186daf32c64e9) +- fix list [`fef6ae7`](https://github.com/minimistjs/minimist/commit/fef6ae79c38b9dc1c49569abb7cd04eb965eac5e) + +## [v0.2.1](https://github.com/minimistjs/minimist/compare/v0.2.0...v0.2.1) - 2020-03-12 + +## [v0.2.0](https://github.com/minimistjs/minimist/compare/v0.1.0...v0.2.0) - 2014-06-19 + +### Commits + +- support all-boolean mode [`450a97f`](https://github.com/minimistjs/minimist/commit/450a97f6e2bc85c7a4a13185c19a818d9a5ebe69) + +## [v0.1.0](https://github.com/minimistjs/minimist/compare/v0.0.10...v0.1.0) - 2014-05-12 + +### Commits + +- Provide a mechanism to segregate -- arguments [`ce4a1e6`](https://github.com/minimistjs/minimist/commit/ce4a1e63a7e8d5ab88d2a3768adefa6af98a445a) +- documented argv['--'] [`14db0e6`](https://github.com/minimistjs/minimist/commit/14db0e6dbc6d2b9e472adaa54dad7004b364634f) +- Adding a test-case for notFlags segregation [`715c1e3`](https://github.com/minimistjs/minimist/commit/715c1e3714be223f998f6c537af6b505f0236c16) + +## [v0.0.10](https://github.com/minimistjs/minimist/compare/v0.0.9...v0.0.10) - 2014-05-11 + +### Commits + +- dedicated boolean test [`46e448f`](https://github.com/minimistjs/minimist/commit/46e448f9f513cfeb2bcc8b688b9b47ba1e515c2b) +- dedicated num test [`9bf2d36`](https://github.com/minimistjs/minimist/commit/9bf2d36f1d3b8795be90b8f7de0a937f098aa394) +- aliased values treated as strings [`1ab743b`](https://github.com/minimistjs/minimist/commit/1ab743bad4484d69f1259bed42f9531de01119de) +- cover the case of already numbers, at 100% coverage [`b2bb044`](https://github.com/minimistjs/minimist/commit/b2bb04436599d77a2ce029e8e555e25b3aa55d13) +- another test for higher coverage [`3662624`](https://github.com/minimistjs/minimist/commit/3662624be976d5489d486a856849c048d13be903) + +## [v0.0.9](https://github.com/minimistjs/minimist/compare/v0.0.8...v0.0.9) - 2014-05-08 + +### Commits + +- Eliminate `longest` fn. [`824f642`](https://github.com/minimistjs/minimist/commit/824f642038d1b02ede68b6261d1d65163390929a) + +## [v0.0.8](https://github.com/minimistjs/minimist/compare/v0.0.7...v0.0.8) - 2014-02-20 + +### Commits + +- return '' if flag is string and empty [`fa63ed4`](https://github.com/minimistjs/minimist/commit/fa63ed4651a4ef4eefddce34188e0d98d745a263) +- handle joined single letters [`66c248f`](https://github.com/minimistjs/minimist/commit/66c248f0241d4d421d193b022e9e365f11178534) + +## [v0.0.7](https://github.com/minimistjs/minimist/compare/v0.0.6...v0.0.7) - 2014-02-08 + +### Commits + +- another swap of .test for .match [`d1da408`](https://github.com/minimistjs/minimist/commit/d1da40819acbe846d89a5c02721211e3c1260dde) + +## [v0.0.6](https://github.com/minimistjs/minimist/compare/v0.0.5...v0.0.6) - 2014-02-08 + +### Commits + +- use .test() instead of .match() to not crash on non-string values in the arguments array [`7e0d1ad`](https://github.com/minimistjs/minimist/commit/7e0d1add8c9e5b9b20a4d3d0f9a94d824c578da1) + +## [v0.0.5](https://github.com/minimistjs/minimist/compare/v0.0.4...v0.0.5) - 2013-09-18 + +### Commits + +- Improve '--' handling. [`b11822c`](https://github.com/minimistjs/minimist/commit/b11822c09cc9d2460f30384d12afc0b953c037a4) + +## [v0.0.4](https://github.com/minimistjs/minimist/compare/v0.0.3...v0.0.4) - 2013-09-17 + +## [v0.0.3](https://github.com/minimistjs/minimist/compare/v0.0.2...v0.0.3) - 2013-09-12 + +### Commits + +- failing test for single dash preceeding a double dash [`b465514`](https://github.com/minimistjs/minimist/commit/b465514b82c9ae28972d714facd951deb2ad762b) +- fix for the dot test [`6a095f1`](https://github.com/minimistjs/minimist/commit/6a095f1d364c8fab2d6753d2291a0649315d297a) + +## [v0.0.2](https://github.com/minimistjs/minimist/compare/v0.0.1...v0.0.2) - 2013-08-28 + +### Commits + +- allow dotted aliases & defaults [`321c33e`](https://github.com/minimistjs/minimist/commit/321c33e755485faaeb44eeb1c05d33b2e0a5a7c4) +- use a better version of ff [`e40f611`](https://github.com/minimistjs/minimist/commit/e40f61114cf7be6f7947f7b3eed345853a67dbbb) + +## [v0.0.1](https://github.com/minimistjs/minimist/compare/v0.0.0...v0.0.1) - 2013-06-25 + +### Commits + +- remove trailing commas [`6ff0fa0`](https://github.com/minimistjs/minimist/commit/6ff0fa055064f15dbe06d50b89d5173a6796e1db) + +## v0.0.0 - 2013-06-25 + +### Commits + +- half of the parse test ported [`3079326`](https://github.com/minimistjs/minimist/commit/307932601325087de6cf94188eb798ffc4f3088a) +- stripped down code and a passing test from optimist [`7cced88`](https://github.com/minimistjs/minimist/commit/7cced88d82e399d1a03ed23eb667f04d3f320d10) +- ported parse tests completely over [`9448754`](https://github.com/minimistjs/minimist/commit/944875452e0820df6830b1408c26a0f7d3e1db04) +- docs, package.json [`a5bf46a`](https://github.com/minimistjs/minimist/commit/a5bf46ac9bb3bd114a9c340276c62c1091e538d5) +- move more short tests into short.js [`503edb5`](https://github.com/minimistjs/minimist/commit/503edb5c41d89c0d40831ee517154fc13b0f18b9) +- default bool test was wrong, not the code [`1b9f5db`](https://github.com/minimistjs/minimist/commit/1b9f5db4741b49962846081b68518de824992097) +- passing long tests ripped out of parse.js [`7972c4a`](https://github.com/minimistjs/minimist/commit/7972c4aff1f4803079e1668006658e2a761a0428) +- badges [`84c0370`](https://github.com/minimistjs/minimist/commit/84c037063664d42878aace715fe6572ce01b6f3b) +- all the tests now ported, some failures [`64239ed`](https://github.com/minimistjs/minimist/commit/64239edfe92c711c4eb0da254fcdfad2a5fdb605) +- failing short test [`f8a5341`](https://github.com/minimistjs/minimist/commit/f8a534112dd1138d2fad722def56a848480c446f) +- fixed the numeric test [`6b034f3`](https://github.com/minimistjs/minimist/commit/6b034f37c79342c60083ed97fd222e16928aac51) diff --git a/node_modules/minimist/readme.markdown b/node_modules/minimist/README.md similarity index 54% rename from node_modules/minimist/readme.markdown rename to node_modules/minimist/README.md index 30a74cf..30ff92d 100644 --- a/node_modules/minimist/readme.markdown +++ b/node_modules/minimist/README.md @@ -1,19 +1,22 @@ -# minimist +# minimist [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] parse argument options This module is the guts of optimist's argument parser without all the fanciful decoration. -[![browser support](https://ci.testling.com/substack/minimist.png)](http://ci.testling.com/substack/minimist) - -[![build status](https://secure.travis-ci.org/substack/minimist.png)](http://travis-ci.org/substack/minimist) - # example ``` js var argv = require('minimist')(process.argv.slice(2)); -console.dir(argv); +console.log(argv); ``` ``` @@ -33,6 +36,16 @@ $ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz beep: 'boop' } ``` +# security + +Previous versions had a prototype pollution bug that could cause privilege +escalation in some circumstances when handling untrusted user input. + +Please use version 1.2.6 or later: + +* https://security.snyk.io/vuln/SNYK-JS-MINIMIST-2429795 (version <=1.2.5) +* https://snyk.io/vuln/SNYK-JS-MINIMIST-559764 (version <=1.2.3) + # methods ``` js @@ -65,19 +78,20 @@ argument names to use as aliases first non-option * `opts['--']` - when true, populate `argv._` with everything before the `--` and `argv['--']` with everything after the `--`. Here's an example: + + ``` + > require('./')('one two three -- four five --six'.split(' '), { '--': true }) + { _: [ 'one', 'two', 'three' ], + '--': [ 'four', 'five', '--six' ] } + ``` + + Note that with `opts['--']` set, parsing for arguments still stops after the + `--`. + * `opts.unknown` - a function which is invoked with a command line parameter not defined in the `opts` configuration object. If the function returns `false`, the unknown option is not added to `argv`. -``` -> require('./')('one two three -- four five --six'.split(' '), { '--': true }) -{ _: [ 'one', 'two', 'three' ], - '--': [ 'four', 'five', '--six' ] } -``` - -Note that with `opts['--']` set, parsing for arguments still stops after the -`--`. - # install With [npm](https://npmjs.org) do: @@ -89,3 +103,15 @@ npm install minimist # license MIT + +[package-url]: https://npmjs.org/package/minimist +[npm-version-svg]: https://versionbadg.es/minimistjs/minimist.svg +[npm-badge-png]: https://nodei.co/npm/minimist.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/minimist.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/minimist.svg +[downloads-url]: https://npm-stat.com/charts.html?package=minimist +[codecov-image]: https://codecov.io/gh/minimistjs/minimist/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/minimistjs/minimist/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/minimistjs/minimist +[actions-url]: https://github.com/minimistjs/minimist/actions diff --git a/node_modules/minimist/example/parse.js b/node_modules/minimist/example/parse.js index abff3e8..f7c8d49 100644 --- a/node_modules/minimist/example/parse.js +++ b/node_modules/minimist/example/parse.js @@ -1,2 +1,2 @@ var argv = require('../')(process.argv.slice(2)); -console.dir(argv); +console.log(argv); diff --git a/node_modules/minimist/index.js b/node_modules/minimist/index.js index 6a0559d..d9c3eb7 100644 --- a/node_modules/minimist/index.js +++ b/node_modules/minimist/index.js @@ -68,12 +68,21 @@ module.exports = function (args, opts) { function setKey (obj, keys, value) { var o = obj; - keys.slice(0,-1).forEach(function (key) { + for (var i = 0; i < keys.length-1; i++) { + var key = keys[i]; + if (isConstructorOrProto(o, key)) return; if (o[key] === undefined) o[key] = {}; + if (o[key] === Object.prototype || o[key] === Number.prototype + || o[key] === String.prototype) o[key] = {}; + if (o[key] === Array.prototype) o[key] = []; o = o[key]; - }); + } var key = keys[keys.length - 1]; + if (isConstructorOrProto(o, key)) return; + if (o === Object.prototype || o === Number.prototype + || o === String.prototype) o = {}; + if (o === Array.prototype) o = []; if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') { o[key] = value; } @@ -171,7 +180,7 @@ module.exports = function (args, opts) { setArg(key, args[i+1], arg); i++; } - else if (args[i+1] && /true|false/.test(args[i+1])) { + else if (args[i+1] && /^(true|false)$/.test(args[i+1])) { setArg(key, args[i+1] === 'true', arg); i++; } @@ -234,3 +243,7 @@ function isNumber (x) { return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); } + +function isConstructorOrProto (obj, key) { + return key === 'constructor' && typeof obj[key] === 'function' || key === '__proto__'; +} diff --git a/node_modules/minimist/package.json b/node_modules/minimist/package.json index c4b7c4e..89a639e 100644 --- a/node_modules/minimist/package.json +++ b/node_modules/minimist/package.json @@ -1,61 +1,30 @@ { - "_from": "minimist", - "_id": "minimist@1.2.0", - "_inBundle": false, - "_integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", - "_location": "/minimist", - "_phantomChildren": {}, - "_requested": { - "type": "tag", - "registry": true, - "raw": "minimist", - "name": "minimist", - "escapedName": "minimist", - "rawSpec": "", - "saveSpec": null, - "fetchSpec": "latest" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", - "_shasum": "a35008b20f41383eec1fb914f4cd5df79a264284", - "_spec": "minimist", - "_where": "C:\\MyTools\\projects\\get-xml-info", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "bugs": { - "url": "https://github.com/substack/minimist/issues" - }, - "bundleDependencies": false, - "deprecated": false, + "name": "minimist", + "version": "1.2.7", "description": "parse argument options", - "devDependencies": { - "covert": "^1.0.0", - "tap": "~0.4.0", - "tape": "^3.5.0" - }, - "homepage": "https://github.com/substack/minimist", - "keywords": [ - "argv", - "getopt", - "parser", - "optimist" - ], - "license": "MIT", "main": "index.js", - "name": "minimist", - "repository": { - "type": "git", - "url": "git://github.com/substack/minimist.git" + "devDependencies": { + "@ljharb/eslint-config": "^21.0.0", + "aud": "^2.0.1", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.6.1" }, "scripts": { - "coverage": "covert test/*.js", - "test": "tap test/*.js" + "prepack": "npmignore --auto --commentLines=auto", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape test/*.js", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" }, "testling": { "files": "test/*.js", @@ -70,5 +39,37 @@ "opera/12" ] }, - "version": "1.2.0" + "repository": { + "type": "git", + "url": "git://github.com/minimistjs/minimist.git" + }, + "homepage": "https://github.com/minimistjs/minimist", + "keywords": [ + "argv", + "getopt", + "parser", + "optimist" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } } diff --git a/node_modules/minimist/test/bool.js b/node_modules/minimist/test/bool.js index 14b0717..5f7dbde 100644 --- a/node_modules/minimist/test/bool.js +++ b/node_modules/minimist/test/bool.js @@ -164,3 +164,15 @@ test('boolean --boool=false', function (t) { t.same(parsed.boool, false); t.end(); }); + +test('boolean using something similar to true', function (t) { + var opts = { boolean: 'h' }; + var result = parse(['-h', 'true.txt'], opts); + var expected = { + h: true, + '_': ['true.txt'] + }; + + t.same(result, expected); + t.end(); +}); \ No newline at end of file diff --git a/node_modules/minimist/test/proto.js b/node_modules/minimist/test/proto.js new file mode 100644 index 0000000..4ac62df --- /dev/null +++ b/node_modules/minimist/test/proto.js @@ -0,0 +1,60 @@ +var parse = require('../'); +var test = require('tape'); + +test('proto pollution', function (t) { + var argv = parse(['--__proto__.x','123']); + t.equal({}.x, undefined); + t.equal(argv.__proto__.x, undefined); + t.equal(argv.x, undefined); + t.end(); +}); + +test('proto pollution (array)', function (t) { + var argv = parse(['--x','4','--x','5','--x.__proto__.z','789']); + t.equal({}.z, undefined); + t.deepEqual(argv.x, [4,5]); + t.equal(argv.x.z, undefined); + t.equal(argv.x.__proto__.z, undefined); + t.end(); +}); + +test('proto pollution (number)', function (t) { + var argv = parse(['--x','5','--x.__proto__.z','100']); + t.equal({}.z, undefined); + t.equal((4).z, undefined); + t.equal(argv.x, 5); + t.equal(argv.x.z, undefined); + t.end(); +}); + +test('proto pollution (string)', function (t) { + var argv = parse(['--x','abc','--x.__proto__.z','def']); + t.equal({}.z, undefined); + t.equal('...'.z, undefined); + t.equal(argv.x, 'abc'); + t.equal(argv.x.z, undefined); + t.end(); +}); + +test('proto pollution (constructor)', function (t) { + var argv = parse(['--constructor.prototype.y','123']); + t.equal({}.y, undefined); + t.equal(argv.y, undefined); + t.end(); +}); + +test('proto pollution (constructor function)', function (t) { + var argv = parse(['--_.concat.constructor.prototype.y', '123']); + function fnToBeTested() {} + t.equal(fnToBeTested.y, undefined); + t.equal(argv.y, undefined); + t.end(); +}); + +// powered by snyk - https://github.com/backstage/backstage/issues/10343 +test('proto pollution (constructor function) snyk', function (t) { + var argv = parse('--_.constructor.constructor.prototype.foo bar'.split(' ')); + t.equal((function(){}).foo, undefined); + t.equal(argv.y, undefined); + t.end(); +}) diff --git a/node_modules/tunnel/.travis.yml b/node_modules/tunnel/.travis.yml new file mode 100644 index 0000000..cb6e182 --- /dev/null +++ b/node_modules/tunnel/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "4" + - "6" + - "8" + - "10" diff --git a/node_modules/tunnel/CHANGELOG.md b/node_modules/tunnel/CHANGELOG.md new file mode 100644 index 0000000..baf6b18 --- /dev/null +++ b/node_modules/tunnel/CHANGELOG.md @@ -0,0 +1,22 @@ +# Changelog + + - 0.0.6 (2018/09/11) + - Fix `localAddress` not working (#25) + - Fix `Host:` header for CONNECT method by @tmurakam (#29, #30) + - Fix default port for https (#32) + - Fix error handling when the proxy send illegal response body (#33) + + - 0.0.5 (2017/06/12) + - Fix socket leak. + + - 0.0.4 (2016/01/23) + - supported Node v0.12 or later. + + - 0.0.3 (2014/01/20) + - fixed package.json + + - 0.0.1 (2012/02/18) + - supported Node v0.6.x (0.6.11 or later). + + - 0.0.0 (2012/02/11) + - first release. diff --git a/node_modules/tunnel/LICENSE b/node_modules/tunnel/LICENSE new file mode 100644 index 0000000..8b8a895 --- /dev/null +++ b/node_modules/tunnel/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Koichi Kobayashi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/tunnel/README.md b/node_modules/tunnel/README.md new file mode 100644 index 0000000..f54bca5 --- /dev/null +++ b/node_modules/tunnel/README.md @@ -0,0 +1,185 @@ +# node-tunnel - HTTP/HTTPS Agents for tunneling proxies + +[![Build Status](https://img.shields.io/travis/koichik/node-tunnel.svg?style=flat)](https://travis-ci.org/koichik/node-tunnel) +[![Dependency Status](http://img.shields.io/david/koichik/node-tunnel.svg?style=flat)](https://david-dm.org/koichik/node-tunnel#info=dependencies) +[![DevDependency Status](http://img.shields.io/david/dev/koichik/node-tunnel.svg?style=flat)](https://david-dm.org/koichik/node-tunnel#info=devDependencies) + +## Example + +```javascript +var tunnel = require('tunnel'); + +var tunnelingAgent = tunnel.httpsOverHttp({ + proxy: { + host: 'localhost', + port: 3128 + } +}); + +var req = https.request({ + host: 'example.com', + port: 443, + agent: tunnelingAgent +}); +``` + +## Installation + + $ npm install tunnel + +## Usages + +### HTTP over HTTP tunneling + +```javascript +var tunnelingAgent = tunnel.httpOverHttp({ + maxSockets: poolSize, // Defaults to http.Agent.defaultMaxSockets + + proxy: { // Proxy settings + host: proxyHost, // Defaults to 'localhost' + port: proxyPort, // Defaults to 80 + localAddress: localAddress, // Local interface if necessary + + // Basic authorization for proxy server if necessary + proxyAuth: 'user:password', + + // Header fields for proxy server if necessary + headers: { + 'User-Agent': 'Node' + } + } +}); + +var req = http.request({ + host: 'example.com', + port: 80, + agent: tunnelingAgent +}); +``` + +### HTTPS over HTTP tunneling + +```javascript +var tunnelingAgent = tunnel.httpsOverHttp({ + maxSockets: poolSize, // Defaults to http.Agent.defaultMaxSockets + + // CA for origin server if necessary + ca: [ fs.readFileSync('origin-server-ca.pem')], + + // Client certification for origin server if necessary + key: fs.readFileSync('origin-server-key.pem'), + cert: fs.readFileSync('origin-server-cert.pem'), + + proxy: { // Proxy settings + host: proxyHost, // Defaults to 'localhost' + port: proxyPort, // Defaults to 80 + localAddress: localAddress, // Local interface if necessary + + // Basic authorization for proxy server if necessary + proxyAuth: 'user:password', + + // Header fields for proxy server if necessary + headers: { + 'User-Agent': 'Node' + }, + } +}); + +var req = https.request({ + host: 'example.com', + port: 443, + agent: tunnelingAgent +}); +``` + +### HTTP over HTTPS tunneling + +```javascript +var tunnelingAgent = tunnel.httpOverHttps({ + maxSockets: poolSize, // Defaults to http.Agent.defaultMaxSockets + + proxy: { // Proxy settings + host: proxyHost, // Defaults to 'localhost' + port: proxyPort, // Defaults to 443 + localAddress: localAddress, // Local interface if necessary + + // Basic authorization for proxy server if necessary + proxyAuth: 'user:password', + + // Header fields for proxy server if necessary + headers: { + 'User-Agent': 'Node' + }, + + // CA for proxy server if necessary + ca: [ fs.readFileSync('origin-server-ca.pem')], + + // Server name for verification if necessary + servername: 'example.com', + + // Client certification for proxy server if necessary + key: fs.readFileSync('origin-server-key.pem'), + cert: fs.readFileSync('origin-server-cert.pem'), + } +}); + +var req = http.request({ + host: 'example.com', + port: 80, + agent: tunnelingAgent +}); +``` + +### HTTPS over HTTPS tunneling + +```javascript +var tunnelingAgent = tunnel.httpsOverHttps({ + maxSockets: poolSize, // Defaults to http.Agent.defaultMaxSockets + + // CA for origin server if necessary + ca: [ fs.readFileSync('origin-server-ca.pem')], + + // Client certification for origin server if necessary + key: fs.readFileSync('origin-server-key.pem'), + cert: fs.readFileSync('origin-server-cert.pem'), + + proxy: { // Proxy settings + host: proxyHost, // Defaults to 'localhost' + port: proxyPort, // Defaults to 443 + localAddress: localAddress, // Local interface if necessary + + // Basic authorization for proxy server if necessary + proxyAuth: 'user:password', + + // Header fields for proxy server if necessary + headers: { + 'User-Agent': 'Node' + } + + // CA for proxy server if necessary + ca: [ fs.readFileSync('origin-server-ca.pem')], + + // Server name for verification if necessary + servername: 'example.com', + + // Client certification for proxy server if necessary + key: fs.readFileSync('origin-server-key.pem'), + cert: fs.readFileSync('origin-server-cert.pem'), + } +}); + +var req = https.request({ + host: 'example.com', + port: 443, + agent: tunnelingAgent +}); +``` + +## CONTRIBUTORS +* [Aleksis Brezas (abresas)](https://github.com/abresas) +* [Jackson Tian (JacksonTian)](https://github.com/JacksonTian) +* [Dmitry Sorin (1999)](https://github.com/1999) + +## License + +Licensed under the [MIT](https://github.com/koichik/node-tunnel/blob/master/LICENSE) license. diff --git a/node_modules/tunnel/index.js b/node_modules/tunnel/index.js new file mode 100644 index 0000000..2947757 --- /dev/null +++ b/node_modules/tunnel/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/tunnel'); diff --git a/node_modules/tunnel/lib/tunnel.js b/node_modules/tunnel/lib/tunnel.js new file mode 100644 index 0000000..10cc382 --- /dev/null +++ b/node_modules/tunnel/lib/tunnel.js @@ -0,0 +1,264 @@ +'use strict'; + +var net = require('net'); +var tls = require('tls'); +var http = require('http'); +var https = require('https'); +var events = require('events'); +var assert = require('assert'); +var util = require('util'); + + +exports.httpOverHttp = httpOverHttp; +exports.httpsOverHttp = httpsOverHttp; +exports.httpOverHttps = httpOverHttps; +exports.httpsOverHttps = httpsOverHttps; + + +function httpOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + return agent; +} + +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} + +function httpOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + return agent; +} + +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} + + +function TunnelingAgent(options) { + var self = this; + self.options = options || {}; + self.proxyOptions = self.options.proxy || {}; + self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; + self.requests = []; + self.sockets = []; + + self.on('free', function onFree(socket, host, port, localAddress) { + var options = toOptions(host, port, localAddress); + for (var i = 0, len = self.requests.length; i < len; ++i) { + var pending = self.requests[i]; + if (pending.host === options.host && pending.port === options.port) { + // Detect the request to connect same origin server, + // reuse the connection. + self.requests.splice(i, 1); + pending.request.onSocket(socket); + return; + } + } + socket.destroy(); + self.removeSocket(socket); + }); +} +util.inherits(TunnelingAgent, events.EventEmitter); + +TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { + var self = this; + var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); + + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push(options); + return; + } + + // If we are under maxSockets create a new one. + self.createSocket(options, function(socket) { + socket.on('free', onFree); + socket.on('close', onCloseOrRemove); + socket.on('agentRemove', onCloseOrRemove); + req.onSocket(socket); + + function onFree() { + self.emit('free', socket, options); + } + + function onCloseOrRemove(err) { + self.removeSocket(socket); + socket.removeListener('free', onFree); + socket.removeListener('close', onCloseOrRemove); + socket.removeListener('agentRemove', onCloseOrRemove); + } + }); +}; + +TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this; + var placeholder = {}; + self.sockets.push(placeholder); + + var connectOptions = mergeOptions({}, self.proxyOptions, { + method: 'CONNECT', + path: options.host + ':' + options.port, + agent: false, + headers: { + host: options.host + ':' + options.port + } + }); + if (options.localAddress) { + connectOptions.localAddress = options.localAddress; + } + if (connectOptions.proxyAuth) { + connectOptions.headers = connectOptions.headers || {}; + connectOptions.headers['Proxy-Authorization'] = 'Basic ' + + new Buffer(connectOptions.proxyAuth).toString('base64'); + } + + debug('making CONNECT request'); + var connectReq = self.request(connectOptions); + connectReq.useChunkedEncodingByDefault = false; // for v0.6 + connectReq.once('response', onResponse); // for v0.6 + connectReq.once('upgrade', onUpgrade); // for v0.6 + connectReq.once('connect', onConnect); // for v0.7 or later + connectReq.once('error', onError); + connectReq.end(); + + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; + } + + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); + } + + function onConnect(res, socket, head) { + connectReq.removeAllListeners(); + socket.removeAllListeners(); + + if (res.statusCode !== 200) { + debug('tunneling socket could not be established, statusCode=%d', + res.statusCode); + socket.destroy(); + var error = new Error('tunneling socket could not be established, ' + + 'statusCode=' + res.statusCode); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + if (head.length > 0) { + debug('got illegal response body from proxy'); + socket.destroy(); + var error = new Error('got illegal response body from proxy'); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + debug('tunneling connection has established'); + self.sockets[self.sockets.indexOf(placeholder)] = socket; + return cb(socket); + } + + function onError(cause) { + connectReq.removeAllListeners(); + + debug('tunneling socket could not be established, cause=%s\n', + cause.message, cause.stack); + var error = new Error('tunneling socket could not be established, ' + + 'cause=' + cause.message); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + } +}; + +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) { + return; + } + this.sockets.splice(pos, 1); + + var pending = this.requests.shift(); + if (pending) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(pending, function(socket) { + pending.request.onSocket(socket); + }); + } +}; + +function createSecureSocket(options, cb) { + var self = this; + TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { + var hostHeader = options.request.getHeader('host'); + var tlsOptions = mergeOptions({}, self.options, { + socket: socket, + servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host + }); + + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, tlsOptions); + self.sockets[self.sockets.indexOf(socket)] = secureSocket; + cb(secureSocket); + }); +} + + +function toOptions(host, port, localAddress) { + if (typeof host === 'string') { // since v0.10 + return { + host: host, + port: port, + localAddress: localAddress + }; + } + return host; // for v0.11 or later +} + +function mergeOptions(target) { + for (var i = 1, len = arguments.length; i < len; ++i) { + var overrides = arguments[i]; + if (typeof overrides === 'object') { + var keys = Object.keys(overrides); + for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { + var k = keys[j]; + if (overrides[k] !== undefined) { + target[k] = overrides[k]; + } + } + } + } + return target; +} + + +var debug; +if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { + debug = function() { + var args = Array.prototype.slice.call(arguments); + if (typeof args[0] === 'string') { + args[0] = 'TUNNEL: ' + args[0]; + } else { + args.unshift('TUNNEL:'); + } + console.error.apply(console, args); + } +} else { + debug = function() {}; +} +exports.debug = debug; // for test diff --git a/node_modules/tunnel/package.json b/node_modules/tunnel/package.json new file mode 100644 index 0000000..bcd7b95 --- /dev/null +++ b/node_modules/tunnel/package.json @@ -0,0 +1,34 @@ +{ + "name": "tunnel", + "version": "0.0.6", + "description": "Node HTTP/HTTPS Agents for tunneling proxies", + "keywords": [ + "http", + "https", + "agent", + "proxy", + "tunnel" + ], + "homepage": "https://github.com/koichik/node-tunnel/", + "bugs": "https://github.com/koichik/node-tunnel/issues", + "license": "MIT", + "author": "Koichi Kobayashi ", + "main": "./index.js", + "directories": { + "lib": "./lib" + }, + "repository": { + "type": "git", + "url": "https://github.com/koichik/node-tunnel.git" + }, + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "mocha": "^5.2.0", + "should": "^13.2.3" + }, + "engines": { + "node": ">=0.6.11 <=0.7.0 || >=0.7.3" + } +} diff --git a/node_modules/uuid/CHANGELOG.md b/node_modules/uuid/CHANGELOG.md new file mode 100644 index 0000000..7519d19 --- /dev/null +++ b/node_modules/uuid/CHANGELOG.md @@ -0,0 +1,229 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +### [8.3.2](https://github.com/uuidjs/uuid/compare/v8.3.1...v8.3.2) (2020-12-08) + +### Bug Fixes + +- lazy load getRandomValues ([#537](https://github.com/uuidjs/uuid/issues/537)) ([16c8f6d](https://github.com/uuidjs/uuid/commit/16c8f6df2f6b09b4d6235602d6a591188320a82e)), closes [#536](https://github.com/uuidjs/uuid/issues/536) + +### [8.3.1](https://github.com/uuidjs/uuid/compare/v8.3.0...v8.3.1) (2020-10-04) + +### Bug Fixes + +- support expo>=39.0.0 ([#515](https://github.com/uuidjs/uuid/issues/515)) ([c65a0f3](https://github.com/uuidjs/uuid/commit/c65a0f3fa73b901959d638d1e3591dfacdbed867)), closes [#375](https://github.com/uuidjs/uuid/issues/375) + +## [8.3.0](https://github.com/uuidjs/uuid/compare/v8.2.0...v8.3.0) (2020-07-27) + +### Features + +- add parse/stringify/validate/version/NIL APIs ([#479](https://github.com/uuidjs/uuid/issues/479)) ([0e6c10b](https://github.com/uuidjs/uuid/commit/0e6c10ba1bf9517796ff23c052fc0468eedfd5f4)), closes [#475](https://github.com/uuidjs/uuid/issues/475) [#478](https://github.com/uuidjs/uuid/issues/478) [#480](https://github.com/uuidjs/uuid/issues/480) [#481](https://github.com/uuidjs/uuid/issues/481) [#180](https://github.com/uuidjs/uuid/issues/180) + +## [8.2.0](https://github.com/uuidjs/uuid/compare/v8.1.0...v8.2.0) (2020-06-23) + +### Features + +- improve performance of v1 string representation ([#453](https://github.com/uuidjs/uuid/issues/453)) ([0ee0b67](https://github.com/uuidjs/uuid/commit/0ee0b67c37846529c66089880414d29f3ae132d5)) +- remove deprecated v4 string parameter ([#454](https://github.com/uuidjs/uuid/issues/454)) ([88ce3ca](https://github.com/uuidjs/uuid/commit/88ce3ca0ba046f60856de62c7ce03f7ba98ba46c)), closes [#437](https://github.com/uuidjs/uuid/issues/437) +- support jspm ([#473](https://github.com/uuidjs/uuid/issues/473)) ([e9f2587](https://github.com/uuidjs/uuid/commit/e9f2587a92575cac31bc1d4ae944e17c09756659)) + +### Bug Fixes + +- prepare package exports for webpack 5 ([#468](https://github.com/uuidjs/uuid/issues/468)) ([8d6e6a5](https://github.com/uuidjs/uuid/commit/8d6e6a5f8965ca9575eb4d92e99a43435f4a58a8)) + +## [8.1.0](https://github.com/uuidjs/uuid/compare/v8.0.0...v8.1.0) (2020-05-20) + +### Features + +- improve v4 performance by reusing random number array ([#435](https://github.com/uuidjs/uuid/issues/435)) ([bf4af0d](https://github.com/uuidjs/uuid/commit/bf4af0d711b4d2ed03d1f74fd12ad0baa87dc79d)) +- optimize V8 performance of bytesToUuid ([#434](https://github.com/uuidjs/uuid/issues/434)) ([e156415](https://github.com/uuidjs/uuid/commit/e156415448ec1af2351fa0b6660cfb22581971f2)) + +### Bug Fixes + +- export package.json required by react-native and bundlers ([#449](https://github.com/uuidjs/uuid/issues/449)) ([be1c8fe](https://github.com/uuidjs/uuid/commit/be1c8fe9a3206c358e0059b52fafd7213aa48a52)), closes [ai/nanoevents#44](https://github.com/ai/nanoevents/issues/44#issuecomment-602010343) [#444](https://github.com/uuidjs/uuid/issues/444) + +## [8.0.0](https://github.com/uuidjs/uuid/compare/v7.0.3...v8.0.0) (2020-04-29) + +### ⚠ BREAKING CHANGES + +- For native ECMAScript Module (ESM) usage in Node.js only named exports are exposed, there is no more default export. + + ```diff + -import uuid from 'uuid'; + -console.log(uuid.v4()); // -> 'cd6c3b08-0adc-4f4b-a6ef-36087a1c9869' + +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' + ``` + +- Deep requiring specific algorithms of this library like `require('uuid/v4')`, which has been deprecated in `uuid@7`, is no longer supported. + + Instead use the named exports that this module exports. + + For ECMAScript Modules (ESM): + + ```diff + -import uuidv4 from 'uuid/v4'; + +import { v4 as uuidv4 } from 'uuid'; + uuidv4(); + ``` + + For CommonJS: + + ```diff + -const uuidv4 = require('uuid/v4'); + +const { v4: uuidv4 } = require('uuid'); + uuidv4(); + ``` + +### Features + +- native Node.js ES Modules (wrapper approach) ([#423](https://github.com/uuidjs/uuid/issues/423)) ([2d9f590](https://github.com/uuidjs/uuid/commit/2d9f590ad9701d692625c07ed62f0a0f91227991)), closes [#245](https://github.com/uuidjs/uuid/issues/245) [#419](https://github.com/uuidjs/uuid/issues/419) [#342](https://github.com/uuidjs/uuid/issues/342) +- remove deep requires ([#426](https://github.com/uuidjs/uuid/issues/426)) ([daf72b8](https://github.com/uuidjs/uuid/commit/daf72b84ceb20272a81bb5fbddb05dd95922cbba)) + +### Bug Fixes + +- add CommonJS syntax example to README quickstart section ([#417](https://github.com/uuidjs/uuid/issues/417)) ([e0ec840](https://github.com/uuidjs/uuid/commit/e0ec8402c7ad44b7ef0453036c612f5db513fda0)) + +### [7.0.3](https://github.com/uuidjs/uuid/compare/v7.0.2...v7.0.3) (2020-03-31) + +### Bug Fixes + +- make deep require deprecation warning work in browsers ([#409](https://github.com/uuidjs/uuid/issues/409)) ([4b71107](https://github.com/uuidjs/uuid/commit/4b71107d8c0d2ef56861ede6403fc9dc35a1e6bf)), closes [#408](https://github.com/uuidjs/uuid/issues/408) + +### [7.0.2](https://github.com/uuidjs/uuid/compare/v7.0.1...v7.0.2) (2020-03-04) + +### Bug Fixes + +- make access to msCrypto consistent ([#393](https://github.com/uuidjs/uuid/issues/393)) ([8bf2a20](https://github.com/uuidjs/uuid/commit/8bf2a20f3565df743da7215eebdbada9d2df118c)) +- simplify link in deprecation warning ([#391](https://github.com/uuidjs/uuid/issues/391)) ([bb2c8e4](https://github.com/uuidjs/uuid/commit/bb2c8e4e9f4c5f9c1eaaf3ea59710c633cd90cb7)) +- update links to match content in readme ([#386](https://github.com/uuidjs/uuid/issues/386)) ([44f2f86](https://github.com/uuidjs/uuid/commit/44f2f86e9d2bbf14ee5f0f00f72a3db1292666d4)) + +### [7.0.1](https://github.com/uuidjs/uuid/compare/v7.0.0...v7.0.1) (2020-02-25) + +### Bug Fixes + +- clean up esm builds for node and browser ([#383](https://github.com/uuidjs/uuid/issues/383)) ([59e6a49](https://github.com/uuidjs/uuid/commit/59e6a49e7ce7b3e8fb0f3ee52b9daae72af467dc)) +- provide browser versions independent from module system ([#380](https://github.com/uuidjs/uuid/issues/380)) ([4344a22](https://github.com/uuidjs/uuid/commit/4344a22e7aed33be8627eeaaf05360f256a21753)), closes [#378](https://github.com/uuidjs/uuid/issues/378) + +## [7.0.0](https://github.com/uuidjs/uuid/compare/v3.4.0...v7.0.0) (2020-02-24) + +### ⚠ BREAKING CHANGES + +- The default export, which used to be the v4() method but which was already discouraged in v3.x of this library, has been removed. +- Explicitly note that deep imports of the different uuid version functions are deprecated and no longer encouraged and that ECMAScript module named imports should be used instead. Emit a deprecation warning for people who deep-require the different algorithm variants. +- Remove builtin support for insecure random number generators in the browser. Users who want that will have to supply their own random number generator function. +- Remove support for generating v3 and v5 UUIDs in Node.js<4.x +- Convert code base to ECMAScript Modules (ESM) and release CommonJS build for node and ESM build for browser bundlers. + +### Features + +- add UMD build to npm package ([#357](https://github.com/uuidjs/uuid/issues/357)) ([4e75adf](https://github.com/uuidjs/uuid/commit/4e75adf435196f28e3fbbe0185d654b5ded7ca2c)), closes [#345](https://github.com/uuidjs/uuid/issues/345) +- add various es module and CommonJS examples ([b238510](https://github.com/uuidjs/uuid/commit/b238510bf352463521f74bab175a3af9b7a42555)) +- ensure that docs are up-to-date in CI ([ee5e77d](https://github.com/uuidjs/uuid/commit/ee5e77db547474f5a8f23d6c857a6d399209986b)) +- hybrid CommonJS & ECMAScript modules build ([a3f078f](https://github.com/uuidjs/uuid/commit/a3f078faa0baff69ab41aed08e041f8f9c8993d0)) +- remove insecure fallback random number generator ([3a5842b](https://github.com/uuidjs/uuid/commit/3a5842b141a6e5de0ae338f391661e6b84b167c9)), closes [#173](https://github.com/uuidjs/uuid/issues/173) +- remove support for pre Node.js v4 Buffer API ([#356](https://github.com/uuidjs/uuid/issues/356)) ([b59b5c5](https://github.com/uuidjs/uuid/commit/b59b5c5ecad271c5453f1a156f011671f6d35627)) +- rename repository to github:uuidjs/uuid ([#351](https://github.com/uuidjs/uuid/issues/351)) ([c37a518](https://github.com/uuidjs/uuid/commit/c37a518e367ac4b6d0aa62dba1bc6ce9e85020f7)), closes [#338](https://github.com/uuidjs/uuid/issues/338) + +### Bug Fixes + +- add deep-require proxies for local testing and adjust tests ([#365](https://github.com/uuidjs/uuid/issues/365)) ([7fedc79](https://github.com/uuidjs/uuid/commit/7fedc79ac8fda4bfd1c566c7f05ef4ac13b2db48)) +- add note about removal of default export ([#372](https://github.com/uuidjs/uuid/issues/372)) ([12749b7](https://github.com/uuidjs/uuid/commit/12749b700eb49db8a9759fd306d8be05dbfbd58c)), closes [#370](https://github.com/uuidjs/uuid/issues/370) +- deprecated deep requiring of the different algorithm versions ([#361](https://github.com/uuidjs/uuid/issues/361)) ([c0bdf15](https://github.com/uuidjs/uuid/commit/c0bdf15e417639b1aeb0b247b2fb11f7a0a26b23)) + +## [3.4.0](https://github.com/uuidjs/uuid/compare/v3.3.3...v3.4.0) (2020-01-16) + +### Features + +- rename repository to github:uuidjs/uuid ([#351](https://github.com/uuidjs/uuid/issues/351)) ([e2d7314](https://github.com/uuidjs/uuid/commit/e2d7314)), closes [#338](https://github.com/uuidjs/uuid/issues/338) + +## [3.3.3](https://github.com/uuidjs/uuid/compare/v3.3.2...v3.3.3) (2019-08-19) + +### Bug Fixes + +- no longer run ci tests on node v4 +- upgrade dependencies + +## [3.3.2](https://github.com/uuidjs/uuid/compare/v3.3.1...v3.3.2) (2018-06-28) + +### Bug Fixes + +- typo ([305d877](https://github.com/uuidjs/uuid/commit/305d877)) + +## [3.3.1](https://github.com/uuidjs/uuid/compare/v3.3.0...v3.3.1) (2018-06-28) + +### Bug Fixes + +- fix [#284](https://github.com/uuidjs/uuid/issues/284) by setting function name in try-catch ([f2a60f2](https://github.com/uuidjs/uuid/commit/f2a60f2)) + +# [3.3.0](https://github.com/uuidjs/uuid/compare/v3.2.1...v3.3.0) (2018-06-22) + +### Bug Fixes + +- assignment to readonly property to allow running in strict mode ([#270](https://github.com/uuidjs/uuid/issues/270)) ([d062fdc](https://github.com/uuidjs/uuid/commit/d062fdc)) +- fix [#229](https://github.com/uuidjs/uuid/issues/229) ([c9684d4](https://github.com/uuidjs/uuid/commit/c9684d4)) +- Get correct version of IE11 crypto ([#274](https://github.com/uuidjs/uuid/issues/274)) ([153d331](https://github.com/uuidjs/uuid/commit/153d331)) +- mem issue when generating uuid ([#267](https://github.com/uuidjs/uuid/issues/267)) ([c47702c](https://github.com/uuidjs/uuid/commit/c47702c)) + +### Features + +- enforce Conventional Commit style commit messages ([#282](https://github.com/uuidjs/uuid/issues/282)) ([cc9a182](https://github.com/uuidjs/uuid/commit/cc9a182)) + +## [3.2.1](https://github.com/uuidjs/uuid/compare/v3.2.0...v3.2.1) (2018-01-16) + +### Bug Fixes + +- use msCrypto if available. Fixes [#241](https://github.com/uuidjs/uuid/issues/241) ([#247](https://github.com/uuidjs/uuid/issues/247)) ([1fef18b](https://github.com/uuidjs/uuid/commit/1fef18b)) + +# [3.2.0](https://github.com/uuidjs/uuid/compare/v3.1.0...v3.2.0) (2018-01-16) + +### Bug Fixes + +- remove mistakenly added typescript dependency, rollback version (standard-version will auto-increment) ([09fa824](https://github.com/uuidjs/uuid/commit/09fa824)) +- use msCrypto if available. Fixes [#241](https://github.com/uuidjs/uuid/issues/241) ([#247](https://github.com/uuidjs/uuid/issues/247)) ([1fef18b](https://github.com/uuidjs/uuid/commit/1fef18b)) + +### Features + +- Add v3 Support ([#217](https://github.com/uuidjs/uuid/issues/217)) ([d94f726](https://github.com/uuidjs/uuid/commit/d94f726)) + +# [3.1.0](https://github.com/uuidjs/uuid/compare/v3.1.0...v3.0.1) (2017-06-17) + +### Bug Fixes + +- (fix) Add .npmignore file to exclude test/ and other non-essential files from packing. (#183) +- Fix typo (#178) +- Simple typo fix (#165) + +### Features + +- v5 support in CLI (#197) +- V5 support (#188) + +# 3.0.1 (2016-11-28) + +- split uuid versions into separate files + +# 3.0.0 (2016-11-17) + +- remove .parse and .unparse + +# 2.0.0 + +- Removed uuid.BufferClass + +# 1.4.0 + +- Improved module context detection +- Removed public RNG functions + +# 1.3.2 + +- Improve tests and handling of v1() options (Issue #24) +- Expose RNG option to allow for perf testing with different generators + +# 1.3.0 + +- Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)! +- Support for node.js crypto API +- De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code diff --git a/node_modules/uuid/CONTRIBUTING.md b/node_modules/uuid/CONTRIBUTING.md new file mode 100644 index 0000000..4a4503d --- /dev/null +++ b/node_modules/uuid/CONTRIBUTING.md @@ -0,0 +1,18 @@ +# Contributing + +Please feel free to file GitHub Issues or propose Pull Requests. We're always happy to discuss improvements to this library! + +## Testing + +```shell +npm test +``` + +## Releasing + +Releases are supposed to be done from master, version bumping is automated through [`standard-version`](https://github.com/conventional-changelog/standard-version): + +```shell +npm run release -- --dry-run # verify output manually +npm run release # follow the instructions from the output of this command +``` diff --git a/node_modules/uuid/LICENSE.md b/node_modules/uuid/LICENSE.md new file mode 100644 index 0000000..3934168 --- /dev/null +++ b/node_modules/uuid/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2010-2020 Robert Kieffer and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/uuid/README.md b/node_modules/uuid/README.md new file mode 100644 index 0000000..ed27e57 --- /dev/null +++ b/node_modules/uuid/README.md @@ -0,0 +1,505 @@ + + +# uuid [![CI](https://github.com/uuidjs/uuid/workflows/CI/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ACI) [![Browser](https://github.com/uuidjs/uuid/workflows/Browser/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ABrowser) + +For the creation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDs + +- **Complete** - Support for RFC4122 version 1, 3, 4, and 5 UUIDs +- **Cross-platform** - Support for ... + - CommonJS, [ECMAScript Modules](#ecmascript-modules) and [CDN builds](#cdn-builds) + - Node 8, 10, 12, 14 + - Chrome, Safari, Firefox, Edge, IE 11 browsers + - Webpack and rollup.js module bundlers + - [React Native / Expo](#react-native--expo) +- **Secure** - Cryptographically-strong random values +- **Small** - Zero-dependency, small footprint, plays nice with "tree shaking" packagers +- **CLI** - Includes the [`uuid` command line](#command-line) utility + +**Upgrading from `uuid@3.x`?** Your code is probably okay, but check out [Upgrading From `uuid@3.x`](#upgrading-from-uuid3x) for details. + +## Quickstart + +To create a random UUID... + +**1. Install** + +```shell +npm install uuid +``` + +**2. Create a UUID** (ES6 module syntax) + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' +``` + +... or using CommonJS syntax: + +```javascript +const { v4: uuidv4 } = require('uuid'); +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +For timestamp UUIDs, namespace UUIDs, and other options read on ... + +## API Summary + +| | | | +| --- | --- | --- | +| [`uuid.NIL`](#uuidnil) | The nil UUID string (all zeros) | New in `uuid@8.3` | +| [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `uuid@8.3` | +| [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `uuid@8.3` | +| [`uuid.v1()`](#uuidv1options-buffer-offset) | Create a version 1 (timestamp) UUID | | +| [`uuid.v3()`](#uuidv3name-namespace-buffer-offset) | Create a version 3 (namespace w/ MD5) UUID | | +| [`uuid.v4()`](#uuidv4options-buffer-offset) | Create a version 4 (random) UUID | | +| [`uuid.v5()`](#uuidv5name-namespace-buffer-offset) | Create a version 5 (namespace w/ SHA-1) UUID | | +| [`uuid.validate()`](#uuidvalidatestr) | Test a string to see if it is a valid UUID | New in `uuid@8.3` | +| [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `uuid@8.3` | + +## API + +### uuid.NIL + +The nil UUID string (all zeros). + +Example: + +```javascript +import { NIL as NIL_UUID } from 'uuid'; + +NIL_UUID; // ⇨ '00000000-0000-0000-0000-000000000000' +``` + +### uuid.parse(str) + +Convert UUID string to array of bytes + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Uint8Array[16]` | +| _throws_ | `TypeError` if `str` is not a valid UUID | + +Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { parse as uuidParse } from 'uuid'; + +// Parse a UUID +const bytes = uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); + +// Convert to hex strings to show byte order (for documentation purposes) +[...bytes].map((v) => v.toString(16).padStart(2, '0')); // ⇨ + // [ + // '6e', 'c0', 'bd', '7f', + // '11', 'c0', '43', 'da', + // '97', '5e', '2a', '8a', + // 'd9', 'eb', 'ae', '0b' + // ] +``` + +### uuid.stringify(arr[, offset]) + +Convert array of bytes to UUID string + +| | | +| -------------- | ---------------------------------------------------------------------------- | +| `arr` | `Array`-like collection of 16 values (starting from `offset`) between 0-255. | +| [`offset` = 0] | `Number` Starting index in the Array | +| _returns_ | `String` | +| _throws_ | `TypeError` if a valid UUID string cannot be generated | + +Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { stringify as uuidStringify } from 'uuid'; + +const uuidBytes = [ + 0x6e, + 0xc0, + 0xbd, + 0x7f, + 0x11, + 0xc0, + 0x43, + 0xda, + 0x97, + 0x5e, + 0x2a, + 0x8a, + 0xd9, + 0xeb, + 0xae, + 0x0b, +]; + +uuidStringify(uuidBytes); // ⇨ '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b' +``` + +### uuid.v1([options[, buffer[, offset]]]) + +Create an RFC version 1 (timestamp) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.node` ] | RFC "node" field as an `Array[6]` of byte values (per 4.1.6) | +| [`options.clockseq`] | RFC "clock sequence" as a `Number` between 0 - 0x3fff | +| [`options.msecs`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) | +| [`options.nsecs`] | RFC "timestamp" field (`Number` of nanseconds to add to `msecs`, should be 0-10,000) | +| [`options.random`] | `Array` of 16 random bytes (0-255) | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | +| _throws_ | `Error` if more than 10M UUIDs/sec are requested | + +Note: The default [node id](https://tools.ietf.org/html/rfc4122#section-4.1.6) (the last 12 digits in the UUID) is generated once, randomly, on process startup, and then remains unchanged for the duration of the process. + +Note: `options.random` and `options.rng` are only meaningful on the very first call to `v1()`, where they may be passed to initialize the internal `node` and `clockseq` fields. + +Example: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d' +``` + +Example using `options`: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +const v1options = { + node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], + clockseq: 0x1234, + msecs: new Date('2011-11-01').getTime(), + nsecs: 5678, +}; +uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab' +``` + +### uuid.v3(name, namespace[, buffer[, offset]]) + +Create an RFC version 3 (namespace w/ MD5) UUID + +API is identical to `v5()`, but uses "v3" instead. + +⚠️ Note: Per the RFC, "_If backward compatibility is not an issue, SHA-1 [Version 5] is preferred_." + +### uuid.v4([options[, buffer[, offset]]]) + +Create an RFC version 4 (random) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.random`] | `Array` of 16 random bytes (0-255) | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Example: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +Example using predefined `random` values: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +const v4options = { + random: [ + 0x10, + 0x91, + 0x56, + 0xbe, + 0xc4, + 0xfb, + 0xc1, + 0xea, + 0x71, + 0xb4, + 0xef, + 0xe1, + 0x67, + 0x1c, + 0x58, + 0x36, + ], +}; +uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836' +``` + +### uuid.v5(name, namespace[, buffer[, offset]]) + +Create an RFC version 5 (namespace w/ SHA-1) UUID + +| | | +| --- | --- | +| `name` | `String \| Array` | +| `namespace` | `String \| Array[16]` Namespace UUID | +| [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Note: The RFC `DNS` and `URL` namespaces are available as `v5.DNS` and `v5.URL`. + +Example with custom namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +// Define a custom namespace. Readers, create your own using something like +// https://www.uuidgenerator.net/ +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; + +uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681' +``` + +Example with RFC `URL` namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +uuidv5('https://www.w3.org/', uuidv5.URL); // ⇨ 'c106a26a-21bb-5538-8bf2-57095d1976c1' +``` + +### uuid.validate(str) + +Test a string to see if it is a valid UUID + +| | | +| --------- | --------------------------------------------------- | +| `str` | `String` to validate | +| _returns_ | `true` if string is a valid UUID, `false` otherwise | + +Example: + +```javascript +import { validate as uuidValidate } from 'uuid'; + +uuidValidate('not a UUID'); // ⇨ false +uuidValidate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ true +``` + +Using `validate` and `version` together it is possible to do per-version validation, e.g. validate for only v4 UUIds. + +```javascript +import { version as uuidVersion } from 'uuid'; +import { validate as uuidValidate } from 'uuid'; + +function uuidValidateV4(uuid) { + return uuidValidate(uuid) && uuidVersion(uuid) === 4; +} + +const v1Uuid = 'd9428888-122b-11e1-b85c-61cd3cbb3210'; +const v4Uuid = '109156be-c4fb-41ea-b1b4-efe1671c5836'; + +uuidValidateV4(v4Uuid); // ⇨ true +uuidValidateV4(v1Uuid); // ⇨ false +``` + +### uuid.version(str) + +Detect RFC version of a UUID + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Number` The RFC version of the UUID | +| _throws_ | `TypeError` if `str` is not a valid UUID | + +Example: + +```javascript +import { version as uuidVersion } from 'uuid'; + +uuidVersion('45637ec4-c85f-11ea-87d0-0242ac130003'); // ⇨ 1 +uuidVersion('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ 4 +``` + +## Command Line + +UUIDs can be generated from the command line using `uuid`. + +```shell +$ uuid +ddeb27fb-d9a0-4624-be4d-4615062daed4 +``` + +The default is to generate version 4 UUIDS, however the other versions are supported. Type `uuid --help` for details: + +```shell +$ uuid --help + +Usage: + uuid + uuid v1 + uuid v3 + uuid v4 + uuid v5 + uuid --help + +Note: may be "URL" or "DNS" to use the corresponding UUIDs +defined by RFC4122 +``` + +## ECMAScript Modules + +This library comes with [ECMAScript Modules](https://www.ecma-international.org/ecma-262/6.0/#sec-modules) (ESM) support for Node.js versions that support it ([example](./examples/node-esmodules/)) as well as bundlers like [rollup.js](https://rollupjs.org/guide/en/#tree-shaking) ([example](./examples/browser-rollup/)) and [webpack](https://webpack.js.org/guides/tree-shaking/) ([example](./examples/browser-webpack/)) (targeting both, Node.js and browser environments). + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +To run the examples you must first create a dist build of this library in the module root: + +```shell +npm run build +``` + +## CDN Builds + +### ECMAScript Modules + +To load this module directly into modern browsers that [support loading ECMAScript Modules](https://caniuse.com/#feat=es6-module) you can make use of [jspm](https://jspm.org/): + +```html + +``` + +### UMD + +To load this module directly into older browsers you can use the [UMD (Universal Module Definition)](https://github.com/umdjs/umd) builds from any of the following CDNs: + +**Using [UNPKG](https://unpkg.com/uuid@latest/dist/umd/)**: + +```html + +``` + +**Using [jsDelivr](https://cdn.jsdelivr.net/npm/uuid@latest/dist/umd/)**: + +```html + +``` + +**Using [cdnjs](https://cdnjs.com/libraries/uuid)**: + +```html + +``` + +These CDNs all provide the same [`uuidv4()`](#uuidv4options-buffer-offset) method: + +```html + +``` + +Methods for the other algorithms ([`uuidv1()`](#uuidv1options-buffer-offset), [`uuidv3()`](#uuidv3name-namespace-buffer-offset) and [`uuidv5()`](#uuidv5name-namespace-buffer-offset)) are available from the files `uuidv1.min.js`, `uuidv3.min.js` and `uuidv5.min.js` respectively. + +## "getRandomValues() not supported" + +This error occurs in environments where the standard [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) API is not supported. This issue can be resolved by adding an appropriate polyfill: + +### React Native / Expo + +1. Install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values#readme) +1. Import it _before_ `uuid`. Since `uuid` might also appear as a transitive dependency of some other imports it's safest to just import `react-native-get-random-values` as the very first thing in your entry point: + +```javascript +import 'react-native-get-random-values'; +import { v4 as uuidv4 } from 'uuid'; +``` + +Note: If you are using Expo, you must be using at least `react-native-get-random-values@1.5.0` and `expo@39.0.0`. + +### Web Workers / Service Workers (Edge <= 18) + +[In Edge <= 18, Web Crypto is not supported in Web Workers or Service Workers](https://caniuse.com/#feat=cryptography) and we are not aware of a polyfill (let us know if you find one, please). + +## Upgrading From `uuid@7.x` + +### Only Named Exports Supported When Using with Node.js ESM + +`uuid@7.x` did not come with native ECMAScript Module (ESM) support for Node.js. Importing it in Node.js ESM consequently imported the CommonJS source with a default export. This library now comes with true Node.js ESM support and only provides named exports. + +Instead of doing: + +```javascript +import uuid from 'uuid'; +uuid.v4(); +``` + +you will now have to use the named exports: + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); +``` + +### Deep Requires No Longer Supported + +Deep requires like `require('uuid/v4')` [which have been deprecated in `uuid@7.x`](#deep-requires-now-deprecated) are no longer supported. + +## Upgrading From `uuid@3.x` + +"_Wait... what happened to `uuid@4.x` - `uuid@6.x`?!?_" + +In order to avoid confusion with RFC [version 4](#uuidv4options-buffer-offset) and [version 5](#uuidv5name-namespace-buffer-offset) UUIDs, and a possible [version 6](http://gh.peabody.io/uuidv6/), releases 4 thru 6 of this module have been skipped. + +### Deep Requires Now Deprecated + +`uuid@3.x` encouraged the use of deep requires to minimize the bundle size of browser builds: + +```javascript +const uuidv4 = require('uuid/v4'); // <== NOW DEPRECATED! +uuidv4(); +``` + +As of `uuid@7.x` this library now provides ECMAScript modules builds, which allow packagers like Webpack and Rollup to do "tree-shaking" to remove dead code. Instead, use the `import` syntax: + +```javascript +import { v4 as uuidv4 } from 'uuid'; +uuidv4(); +``` + +... or for CommonJS: + +```javascript +const { v4: uuidv4 } = require('uuid'); +uuidv4(); +``` + +### Default Export Removed + +`uuid@3.x` was exporting the Version 4 UUID method as a default export: + +```javascript +const uuid = require('uuid'); // <== REMOVED! +``` + +This usage pattern was already discouraged in `uuid@3.x` and has been removed in `uuid@7.x`. + +---- +Markdown generated from [README_js.md](README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) \ No newline at end of file diff --git a/node_modules/uuid/dist/bin/uuid b/node_modules/uuid/dist/bin/uuid new file mode 100755 index 0000000..f38d2ee --- /dev/null +++ b/node_modules/uuid/dist/bin/uuid @@ -0,0 +1,2 @@ +#!/usr/bin/env node +require('../uuid-bin'); diff --git a/node_modules/uuid/dist/esm-browser/index.js b/node_modules/uuid/dist/esm-browser/index.js new file mode 100644 index 0000000..1db6f6d --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/index.js @@ -0,0 +1,9 @@ +export { default as v1 } from './v1.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as NIL } from './nil.js'; +export { default as version } from './version.js'; +export { default as validate } from './validate.js'; +export { default as stringify } from './stringify.js'; +export { default as parse } from './parse.js'; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-browser/md5.js b/node_modules/uuid/dist/esm-browser/md5.js new file mode 100644 index 0000000..8b5d46a --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/md5.js @@ -0,0 +1,215 @@ +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (var i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + var output = []; + var length32 = input.length * 32; + var hexTab = '0123456789abcdef'; + + for (var i = 0; i < length32; i += 8) { + var x = input[i >> 5] >>> i % 32 & 0xff; + var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + var d = 271733878; + + for (var i = 0; i < x.length; i += 16) { + var olda = a; + var oldb = b; + var oldc = c; + var oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + var length8 = input.length * 8; + var output = new Uint32Array(getOutputLength(length8)); + + for (var i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + var lsw = (x & 0xffff) + (y & 0xffff); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +export default md5; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-browser/nil.js b/node_modules/uuid/dist/esm-browser/nil.js new file mode 100644 index 0000000..b36324c --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-browser/parse.js b/node_modules/uuid/dist/esm-browser/parse.js new file mode 100644 index 0000000..7c5b1d5 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/parse.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; + +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + var v; + var arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +export default parse; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-browser/regex.js b/node_modules/uuid/dist/esm-browser/regex.js new file mode 100644 index 0000000..3da8673 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/regex.js @@ -0,0 +1 @@ +export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-browser/rng.js b/node_modules/uuid/dist/esm-browser/rng.js new file mode 100644 index 0000000..8abbf2e --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/rng.js @@ -0,0 +1,19 @@ +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +var getRandomValues; +var rnds8 = new Uint8Array(16); +export default function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, + // find the complete implementation of crypto (msCrypto) on IE11. + getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto); + + if (!getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } + } + + return getRandomValues(rnds8); +} \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-browser/sha1.js b/node_modules/uuid/dist/esm-browser/sha1.js new file mode 100644 index 0000000..940548b --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/sha1.js @@ -0,0 +1,96 @@ +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (var i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + var l = bytes.length / 4 + 2; + var N = Math.ceil(l / 16); + var M = new Array(N); + + for (var _i = 0; _i < N; ++_i) { + var arr = new Uint32Array(16); + + for (var j = 0; j < 16; ++j) { + arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3]; + } + + M[_i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (var _i2 = 0; _i2 < N; ++_i2) { + var W = new Uint32Array(80); + + for (var t = 0; t < 16; ++t) { + W[t] = M[_i2][t]; + } + + for (var _t = 16; _t < 80; ++_t) { + W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1); + } + + var a = H[0]; + var b = H[1]; + var c = H[2]; + var d = H[3]; + var e = H[4]; + + for (var _t2 = 0; _t2 < 80; ++_t2) { + var s = Math.floor(_t2 / 20); + var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +export default sha1; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-browser/stringify.js b/node_modules/uuid/dist/esm-browser/stringify.js new file mode 100644 index 0000000..3102111 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/stringify.js @@ -0,0 +1,30 @@ +import validate from './validate.js'; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ + +var byteToHex = []; + +for (var i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).substr(1)); +} + +function stringify(arr) { + var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +export default stringify; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-browser/v1.js b/node_modules/uuid/dist/esm-browser/v1.js new file mode 100644 index 0000000..1a22591 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v1.js @@ -0,0 +1,95 @@ +import rng from './rng.js'; +import stringify from './stringify.js'; // **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +var _nodeId; + +var _clockseq; // Previous uuid creation time + + +var _lastMSecs = 0; +var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || new Array(16); + options = options || {}; + var node = options.node || _nodeId; + var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + var seedBytes = options.random || (options.rng || rng)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + var tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (var n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || stringify(b); +} + +export default v1; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-browser/v3.js b/node_modules/uuid/dist/esm-browser/v3.js new file mode 100644 index 0000000..c9ab9a4 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v3.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import md5 from './md5.js'; +var v3 = v35('v3', 0x30, md5); +export default v3; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-browser/v35.js b/node_modules/uuid/dist/esm-browser/v35.js new file mode 100644 index 0000000..31dd8a1 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v35.js @@ -0,0 +1,64 @@ +import stringify from './stringify.js'; +import parse from './parse.js'; + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + var bytes = []; + + for (var i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +export var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +export var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +export default function (name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + if (typeof value === 'string') { + value = stringToBytes(value); + } + + if (typeof namespace === 'string') { + namespace = parse(namespace); + } + + if (namespace.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + var bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (var i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return stringify(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-browser/v4.js b/node_modules/uuid/dist/esm-browser/v4.js new file mode 100644 index 0000000..404810a --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v4.js @@ -0,0 +1,24 @@ +import rng from './rng.js'; +import stringify from './stringify.js'; + +function v4(options, buf, offset) { + options = options || {}; + var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (var i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return stringify(rnds); +} + +export default v4; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-browser/v5.js b/node_modules/uuid/dist/esm-browser/v5.js new file mode 100644 index 0000000..c08d96b --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/v5.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import sha1 from './sha1.js'; +var v5 = v35('v5', 0x50, sha1); +export default v5; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-browser/validate.js b/node_modules/uuid/dist/esm-browser/validate.js new file mode 100644 index 0000000..f1cdc7a --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/validate.js @@ -0,0 +1,7 @@ +import REGEX from './regex.js'; + +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} + +export default validate; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-browser/version.js b/node_modules/uuid/dist/esm-browser/version.js new file mode 100644 index 0000000..77530e9 --- /dev/null +++ b/node_modules/uuid/dist/esm-browser/version.js @@ -0,0 +1,11 @@ +import validate from './validate.js'; + +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.substr(14, 1), 16); +} + +export default version; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-node/index.js b/node_modules/uuid/dist/esm-node/index.js new file mode 100644 index 0000000..1db6f6d --- /dev/null +++ b/node_modules/uuid/dist/esm-node/index.js @@ -0,0 +1,9 @@ +export { default as v1 } from './v1.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as NIL } from './nil.js'; +export { default as version } from './version.js'; +export { default as validate } from './validate.js'; +export { default as stringify } from './stringify.js'; +export { default as parse } from './parse.js'; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-node/md5.js b/node_modules/uuid/dist/esm-node/md5.js new file mode 100644 index 0000000..4d68b04 --- /dev/null +++ b/node_modules/uuid/dist/esm-node/md5.js @@ -0,0 +1,13 @@ +import crypto from 'crypto'; + +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return crypto.createHash('md5').update(bytes).digest(); +} + +export default md5; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-node/nil.js b/node_modules/uuid/dist/esm-node/nil.js new file mode 100644 index 0000000..b36324c --- /dev/null +++ b/node_modules/uuid/dist/esm-node/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-node/parse.js b/node_modules/uuid/dist/esm-node/parse.js new file mode 100644 index 0000000..6421c5d --- /dev/null +++ b/node_modules/uuid/dist/esm-node/parse.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; + +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +export default parse; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-node/regex.js b/node_modules/uuid/dist/esm-node/regex.js new file mode 100644 index 0000000..3da8673 --- /dev/null +++ b/node_modules/uuid/dist/esm-node/regex.js @@ -0,0 +1 @@ +export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-node/rng.js b/node_modules/uuid/dist/esm-node/rng.js new file mode 100644 index 0000000..8006244 --- /dev/null +++ b/node_modules/uuid/dist/esm-node/rng.js @@ -0,0 +1,12 @@ +import crypto from 'crypto'; +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; +export default function rng() { + if (poolPtr > rnds8Pool.length - 16) { + crypto.randomFillSync(rnds8Pool); + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-node/sha1.js b/node_modules/uuid/dist/esm-node/sha1.js new file mode 100644 index 0000000..e23850b --- /dev/null +++ b/node_modules/uuid/dist/esm-node/sha1.js @@ -0,0 +1,13 @@ +import crypto from 'crypto'; + +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return crypto.createHash('sha1').update(bytes).digest(); +} + +export default sha1; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-node/stringify.js b/node_modules/uuid/dist/esm-node/stringify.js new file mode 100644 index 0000000..f9bca12 --- /dev/null +++ b/node_modules/uuid/dist/esm-node/stringify.js @@ -0,0 +1,29 @@ +import validate from './validate.js'; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ + +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).substr(1)); +} + +function stringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +export default stringify; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-node/v1.js b/node_modules/uuid/dist/esm-node/v1.js new file mode 100644 index 0000000..ebf81ac --- /dev/null +++ b/node_modules/uuid/dist/esm-node/v1.js @@ -0,0 +1,95 @@ +import rng from './rng.js'; +import stringify from './stringify.js'; // **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || rng)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || stringify(b); +} + +export default v1; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-node/v3.js b/node_modules/uuid/dist/esm-node/v3.js new file mode 100644 index 0000000..09063b8 --- /dev/null +++ b/node_modules/uuid/dist/esm-node/v3.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import md5 from './md5.js'; +const v3 = v35('v3', 0x30, md5); +export default v3; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-node/v35.js b/node_modules/uuid/dist/esm-node/v35.js new file mode 100644 index 0000000..22f6a19 --- /dev/null +++ b/node_modules/uuid/dist/esm-node/v35.js @@ -0,0 +1,64 @@ +import stringify from './stringify.js'; +import parse from './parse.js'; + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +export const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +export const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +export default function (name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + if (typeof value === 'string') { + value = stringToBytes(value); + } + + if (typeof namespace === 'string') { + namespace = parse(namespace); + } + + if (namespace.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return stringify(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-node/v4.js b/node_modules/uuid/dist/esm-node/v4.js new file mode 100644 index 0000000..efad926 --- /dev/null +++ b/node_modules/uuid/dist/esm-node/v4.js @@ -0,0 +1,24 @@ +import rng from './rng.js'; +import stringify from './stringify.js'; + +function v4(options, buf, offset) { + options = options || {}; + const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return stringify(rnds); +} + +export default v4; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-node/v5.js b/node_modules/uuid/dist/esm-node/v5.js new file mode 100644 index 0000000..e87fe31 --- /dev/null +++ b/node_modules/uuid/dist/esm-node/v5.js @@ -0,0 +1,4 @@ +import v35 from './v35.js'; +import sha1 from './sha1.js'; +const v5 = v35('v5', 0x50, sha1); +export default v5; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-node/validate.js b/node_modules/uuid/dist/esm-node/validate.js new file mode 100644 index 0000000..f1cdc7a --- /dev/null +++ b/node_modules/uuid/dist/esm-node/validate.js @@ -0,0 +1,7 @@ +import REGEX from './regex.js'; + +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} + +export default validate; \ No newline at end of file diff --git a/node_modules/uuid/dist/esm-node/version.js b/node_modules/uuid/dist/esm-node/version.js new file mode 100644 index 0000000..77530e9 --- /dev/null +++ b/node_modules/uuid/dist/esm-node/version.js @@ -0,0 +1,11 @@ +import validate from './validate.js'; + +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.substr(14, 1), 16); +} + +export default version; \ No newline at end of file diff --git a/node_modules/uuid/dist/index.js b/node_modules/uuid/dist/index.js new file mode 100644 index 0000000..bf13b10 --- /dev/null +++ b/node_modules/uuid/dist/index.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "v1", { + enumerable: true, + get: function () { + return _v.default; + } +}); +Object.defineProperty(exports, "v3", { + enumerable: true, + get: function () { + return _v2.default; + } +}); +Object.defineProperty(exports, "v4", { + enumerable: true, + get: function () { + return _v3.default; + } +}); +Object.defineProperty(exports, "v5", { + enumerable: true, + get: function () { + return _v4.default; + } +}); +Object.defineProperty(exports, "NIL", { + enumerable: true, + get: function () { + return _nil.default; + } +}); +Object.defineProperty(exports, "version", { + enumerable: true, + get: function () { + return _version.default; + } +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function () { + return _validate.default; + } +}); +Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function () { + return _stringify.default; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function () { + return _parse.default; + } +}); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +var _nil = _interopRequireDefault(require("./nil.js")); + +var _version = _interopRequireDefault(require("./version.js")); + +var _validate = _interopRequireDefault(require("./validate.js")); + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } \ No newline at end of file diff --git a/node_modules/uuid/dist/md5-browser.js b/node_modules/uuid/dist/md5-browser.js new file mode 100644 index 0000000..7a4582a --- /dev/null +++ b/node_modules/uuid/dist/md5-browser.js @@ -0,0 +1,223 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ +function md5(bytes) { + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = new Uint8Array(msg.length); + + for (let i = 0; i < msg.length; ++i) { + bytes[i] = msg.charCodeAt(i); + } + } + + return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8)); +} +/* + * Convert an array of little-endian words to an array of bytes + */ + + +function md5ToHexEncodedArray(input) { + const output = []; + const length32 = input.length * 32; + const hexTab = '0123456789abcdef'; + + for (let i = 0; i < length32; i += 8) { + const x = input[i >> 5] >>> i % 32 & 0xff; + const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16); + output.push(hex); + } + + return output; +} +/** + * Calculate output length with padding and bit length + */ + + +function getOutputLength(inputLength8) { + return (inputLength8 + 64 >>> 9 << 4) + 14 + 1; +} +/* + * Calculate the MD5 of an array of little-endian words, and a bit length. + */ + + +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << len % 32; + x[getOutputLength(len) - 1] = len; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + + return [a, b, c, d]; +} +/* + * Convert an array bytes to an array of little-endian words + * Characters >255 have their high-byte silently ignored. + */ + + +function bytesToWords(input) { + if (input.length === 0) { + return []; + } + + const length8 = input.length * 8; + const output = new Uint32Array(getOutputLength(length8)); + + for (let i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[i / 8] & 0xff) << i % 32; + } + + return output; +} +/* + * Add integers, wrapping at 2^32. This uses 16-bit operations internally + * to work around bugs in some JS interpreters. + */ + + +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 0xffff; +} +/* + * Bitwise rotate a 32-bit number to the left. + */ + + +function bitRotateLeft(num, cnt) { + return num << cnt | num >>> 32 - cnt; +} +/* + * These functions implement the four basic operations the algorithm uses. + */ + + +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} + +function md5ff(a, b, c, d, x, s, t) { + return md5cmn(b & c | ~b & d, a, b, x, s, t); +} + +function md5gg(a, b, c, d, x, s, t) { + return md5cmn(b & d | c & ~d, a, b, x, s, t); +} + +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} + +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/uuid/dist/md5.js b/node_modules/uuid/dist/md5.js new file mode 100644 index 0000000..824d481 --- /dev/null +++ b/node_modules/uuid/dist/md5.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('md5').update(bytes).digest(); +} + +var _default = md5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/uuid/dist/nil.js b/node_modules/uuid/dist/nil.js new file mode 100644 index 0000000..7ade577 --- /dev/null +++ b/node_modules/uuid/dist/nil.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/uuid/dist/parse.js b/node_modules/uuid/dist/parse.js new file mode 100644 index 0000000..4c69fc3 --- /dev/null +++ b/node_modules/uuid/dist/parse.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ + + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ + + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ + + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ + + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} + +var _default = parse; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/uuid/dist/regex.js b/node_modules/uuid/dist/regex.js new file mode 100644 index 0000000..1ef91d6 --- /dev/null +++ b/node_modules/uuid/dist/regex.js @@ -0,0 +1,8 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/uuid/dist/rng-browser.js b/node_modules/uuid/dist/rng-browser.js new file mode 100644 index 0000000..91faeae --- /dev/null +++ b/node_modules/uuid/dist/rng-browser.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; +// Unique ID creation requires a high quality random # generator. In the browser we therefore +// require the crypto API and do not support built-in fallback to lower quality random number +// generators (like Math.random()). +let getRandomValues; +const rnds8 = new Uint8Array(16); + +function rng() { + // lazy load so that environments that need to polyfill have a chance to do so + if (!getRandomValues) { + // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also, + // find the complete implementation of crypto (msCrypto) on IE11. + getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto); + + if (!getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } + } + + return getRandomValues(rnds8); +} \ No newline at end of file diff --git a/node_modules/uuid/dist/rng.js b/node_modules/uuid/dist/rng.js new file mode 100644 index 0000000..3507f93 --- /dev/null +++ b/node_modules/uuid/dist/rng.js @@ -0,0 +1,24 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; + +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + _crypto.default.randomFillSync(rnds8Pool); + + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} \ No newline at end of file diff --git a/node_modules/uuid/dist/sha1-browser.js b/node_modules/uuid/dist/sha1-browser.js new file mode 100644 index 0000000..24cbced --- /dev/null +++ b/node_modules/uuid/dist/sha1-browser.js @@ -0,0 +1,104 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +function f(s, x, y, z) { + switch (s) { + case 0: + return x & y ^ ~x & z; + + case 1: + return x ^ y ^ z; + + case 2: + return x & y ^ x & z ^ y & z; + + case 3: + return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return x << n | x >>> 32 - n; +} + +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof bytes === 'string') { + const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + + bytes = []; + + for (let i = 0; i < msg.length; ++i) { + bytes.push(msg.charCodeAt(i)); + } + } else if (!Array.isArray(bytes)) { + // Convert Array-like to Array + bytes = Array.prototype.slice.call(bytes); + } + + bytes.push(0x80); + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + + for (let j = 0; j < 16; ++j) { + arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3]; + } + + M[i] = arr; + } + + M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff; + + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = H[0] + a >>> 0; + H[1] = H[1] + b >>> 0; + H[2] = H[2] + c >>> 0; + H[3] = H[3] + d >>> 0; + H[4] = H[4] + e >>> 0; + } + + return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff]; +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/uuid/dist/sha1.js b/node_modules/uuid/dist/sha1.js new file mode 100644 index 0000000..03bdd63 --- /dev/null +++ b/node_modules/uuid/dist/sha1.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _crypto = _interopRequireDefault(require("crypto")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + + return _crypto.default.createHash('sha1').update(bytes).digest(); +} + +var _default = sha1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/uuid/dist/stringify.js b/node_modules/uuid/dist/stringify.js new file mode 100644 index 0000000..b8e7519 --- /dev/null +++ b/node_modules/uuid/dist/stringify.js @@ -0,0 +1,39 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; + +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).substr(1)); +} + +function stringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + + return uuid; +} + +var _default = stringify; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/uuid/dist/umd/uuid.min.js b/node_modules/uuid/dist/umd/uuid.min.js new file mode 100644 index 0000000..639ca2f --- /dev/null +++ b/node_modules/uuid/dist/umd/uuid.min.js @@ -0,0 +1 @@ +!function(r,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((r="undefined"!=typeof globalThis?globalThis:r||self).uuid={})}(this,(function(r){"use strict";var e,n=new Uint8Array(16);function t(){if(!e&&!(e="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return e(n)}var o=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function a(r){return"string"==typeof r&&o.test(r)}for(var i,u,f=[],s=0;s<256;++s)f.push((s+256).toString(16).substr(1));function c(r){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=(f[r[e+0]]+f[r[e+1]]+f[r[e+2]]+f[r[e+3]]+"-"+f[r[e+4]]+f[r[e+5]]+"-"+f[r[e+6]]+f[r[e+7]]+"-"+f[r[e+8]]+f[r[e+9]]+"-"+f[r[e+10]]+f[r[e+11]]+f[r[e+12]]+f[r[e+13]]+f[r[e+14]]+f[r[e+15]]).toLowerCase();if(!a(n))throw TypeError("Stringified UUID is invalid");return n}var l=0,d=0;function v(r){if(!a(r))throw TypeError("Invalid UUID");var e,n=new Uint8Array(16);return n[0]=(e=parseInt(r.slice(0,8),16))>>>24,n[1]=e>>>16&255,n[2]=e>>>8&255,n[3]=255&e,n[4]=(e=parseInt(r.slice(9,13),16))>>>8,n[5]=255&e,n[6]=(e=parseInt(r.slice(14,18),16))>>>8,n[7]=255&e,n[8]=(e=parseInt(r.slice(19,23),16))>>>8,n[9]=255&e,n[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,n[11]=e/4294967296&255,n[12]=e>>>24&255,n[13]=e>>>16&255,n[14]=e>>>8&255,n[15]=255&e,n}function p(r,e,n){function t(r,t,o,a){if("string"==typeof r&&(r=function(r){r=unescape(encodeURIComponent(r));for(var e=[],n=0;n>>9<<4)+1}function y(r,e){var n=(65535&r)+(65535&e);return(r>>16)+(e>>16)+(n>>16)<<16|65535&n}function g(r,e,n,t,o,a){return y((i=y(y(e,r),y(t,a)))<<(u=o)|i>>>32-u,n);var i,u}function m(r,e,n,t,o,a,i){return g(e&n|~e&t,r,e,o,a,i)}function w(r,e,n,t,o,a,i){return g(e&t|n&~t,r,e,o,a,i)}function b(r,e,n,t,o,a,i){return g(e^n^t,r,e,o,a,i)}function A(r,e,n,t,o,a,i){return g(n^(e|~t),r,e,o,a,i)}var U=p("v3",48,(function(r){if("string"==typeof r){var e=unescape(encodeURIComponent(r));r=new Uint8Array(e.length);for(var n=0;n>5]>>>o%32&255,i=parseInt(t.charAt(a>>>4&15)+t.charAt(15&a),16);e.push(i)}return e}(function(r,e){r[e>>5]|=128<>5]|=(255&r[t/8])<>>32-e}var R=p("v5",80,(function(r){var e=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof r){var t=unescape(encodeURIComponent(r));r=[];for(var o=0;o>>0;w=m,m=g,g=C(y,30)>>>0,y=h,h=U}n[0]=n[0]+h>>>0,n[1]=n[1]+y>>>0,n[2]=n[2]+g>>>0,n[3]=n[3]+m>>>0,n[4]=n[4]+w>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,255&n[0],n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,255&n[1],n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,255&n[2],n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,255&n[3],n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,255&n[4]]}));r.NIL="00000000-0000-0000-0000-000000000000",r.parse=v,r.stringify=c,r.v1=function(r,e,n){var o=e&&n||0,a=e||new Array(16),f=(r=r||{}).node||i,s=void 0!==r.clockseq?r.clockseq:u;if(null==f||null==s){var v=r.random||(r.rng||t)();null==f&&(f=i=[1|v[0],v[1],v[2],v[3],v[4],v[5]]),null==s&&(s=u=16383&(v[6]<<8|v[7]))}var p=void 0!==r.msecs?r.msecs:Date.now(),h=void 0!==r.nsecs?r.nsecs:d+1,y=p-l+(h-d)/1e4;if(y<0&&void 0===r.clockseq&&(s=s+1&16383),(y<0||p>l)&&void 0===r.nsecs&&(h=0),h>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");l=p,d=h,u=s;var g=(1e4*(268435455&(p+=122192928e5))+h)%4294967296;a[o++]=g>>>24&255,a[o++]=g>>>16&255,a[o++]=g>>>8&255,a[o++]=255&g;var m=p/4294967296*1e4&268435455;a[o++]=m>>>8&255,a[o++]=255&m,a[o++]=m>>>24&15|16,a[o++]=m>>>16&255,a[o++]=s>>>8|128,a[o++]=255&s;for(var w=0;w<6;++w)a[o+w]=f[w];return e||c(a)},r.v3=U,r.v4=function(r,e,n){var o=(r=r||{}).random||(r.rng||t)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,e){n=n||0;for(var a=0;a<16;++a)e[n+a]=o[a];return e}return c(o)},r.v5=R,r.validate=a,r.version=function(r){if(!a(r))throw TypeError("Invalid UUID");return parseInt(r.substr(14,1),16)},Object.defineProperty(r,"__esModule",{value:!0})})); \ No newline at end of file diff --git a/node_modules/uuid/dist/umd/uuidNIL.min.js b/node_modules/uuid/dist/umd/uuidNIL.min.js new file mode 100644 index 0000000..30b28a7 --- /dev/null +++ b/node_modules/uuid/dist/umd/uuidNIL.min.js @@ -0,0 +1 @@ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e="undefined"!=typeof globalThis?globalThis:e||self).uuidNIL=n()}(this,(function(){"use strict";return"00000000-0000-0000-0000-000000000000"})); \ No newline at end of file diff --git a/node_modules/uuid/dist/umd/uuidParse.min.js b/node_modules/uuid/dist/umd/uuidParse.min.js new file mode 100644 index 0000000..d48ea6a --- /dev/null +++ b/node_modules/uuid/dist/umd/uuidParse.min.js @@ -0,0 +1 @@ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e="undefined"!=typeof globalThis?globalThis:e||self).uuidParse=n()}(this,(function(){"use strict";var e=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;return function(n){if(!function(n){return"string"==typeof n&&e.test(n)}(n))throw TypeError("Invalid UUID");var t,i=new Uint8Array(16);return i[0]=(t=parseInt(n.slice(0,8),16))>>>24,i[1]=t>>>16&255,i[2]=t>>>8&255,i[3]=255&t,i[4]=(t=parseInt(n.slice(9,13),16))>>>8,i[5]=255&t,i[6]=(t=parseInt(n.slice(14,18),16))>>>8,i[7]=255&t,i[8]=(t=parseInt(n.slice(19,23),16))>>>8,i[9]=255&t,i[10]=(t=parseInt(n.slice(24,36),16))/1099511627776&255,i[11]=t/4294967296&255,i[12]=t>>>24&255,i[13]=t>>>16&255,i[14]=t>>>8&255,i[15]=255&t,i}})); \ No newline at end of file diff --git a/node_modules/uuid/dist/umd/uuidStringify.min.js b/node_modules/uuid/dist/umd/uuidStringify.min.js new file mode 100644 index 0000000..fd39adc --- /dev/null +++ b/node_modules/uuid/dist/umd/uuidStringify.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).uuidStringify=t()}(this,(function(){"use strict";var e=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function t(t){return"string"==typeof t&&e.test(t)}for(var i=[],n=0;n<256;++n)i.push((n+256).toString(16).substr(1));return function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,f=(i[e[n+0]]+i[e[n+1]]+i[e[n+2]]+i[e[n+3]]+"-"+i[e[n+4]]+i[e[n+5]]+"-"+i[e[n+6]]+i[e[n+7]]+"-"+i[e[n+8]]+i[e[n+9]]+"-"+i[e[n+10]]+i[e[n+11]]+i[e[n+12]]+i[e[n+13]]+i[e[n+14]]+i[e[n+15]]).toLowerCase();if(!t(f))throw TypeError("Stringified UUID is invalid");return f}})); \ No newline at end of file diff --git a/node_modules/uuid/dist/umd/uuidValidate.min.js b/node_modules/uuid/dist/umd/uuidValidate.min.js new file mode 100644 index 0000000..378e5b9 --- /dev/null +++ b/node_modules/uuid/dist/umd/uuidValidate.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).uuidValidate=t()}(this,(function(){"use strict";var e=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;return function(t){return"string"==typeof t&&e.test(t)}})); \ No newline at end of file diff --git a/node_modules/uuid/dist/umd/uuidVersion.min.js b/node_modules/uuid/dist/umd/uuidVersion.min.js new file mode 100644 index 0000000..274bb09 --- /dev/null +++ b/node_modules/uuid/dist/umd/uuidVersion.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).uuidVersion=t()}(this,(function(){"use strict";var e=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;return function(t){if(!function(t){return"string"==typeof t&&e.test(t)}(t))throw TypeError("Invalid UUID");return parseInt(t.substr(14,1),16)}})); \ No newline at end of file diff --git a/node_modules/uuid/dist/umd/uuidv1.min.js b/node_modules/uuid/dist/umd/uuidv1.min.js new file mode 100644 index 0000000..2622889 --- /dev/null +++ b/node_modules/uuid/dist/umd/uuidv1.min.js @@ -0,0 +1 @@ +!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?module.exports=o():"function"==typeof define&&define.amd?define(o):(e="undefined"!=typeof globalThis?globalThis:e||self).uuidv1=o()}(this,(function(){"use strict";var e,o=new Uint8Array(16);function t(){if(!e&&!(e="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return e(o)}var n=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function r(e){return"string"==typeof e&&n.test(e)}for(var i,u,s=[],a=0;a<256;++a)s.push((a+256).toString(16).substr(1));var d=0,f=0;return function(e,o,n){var a=o&&n||0,c=o||new Array(16),l=(e=e||{}).node||i,p=void 0!==e.clockseq?e.clockseq:u;if(null==l||null==p){var v=e.random||(e.rng||t)();null==l&&(l=i=[1|v[0],v[1],v[2],v[3],v[4],v[5]]),null==p&&(p=u=16383&(v[6]<<8|v[7]))}var y=void 0!==e.msecs?e.msecs:Date.now(),m=void 0!==e.nsecs?e.nsecs:f+1,g=y-d+(m-f)/1e4;if(g<0&&void 0===e.clockseq&&(p=p+1&16383),(g<0||y>d)&&void 0===e.nsecs&&(m=0),m>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");d=y,f=m,u=p;var h=(1e4*(268435455&(y+=122192928e5))+m)%4294967296;c[a++]=h>>>24&255,c[a++]=h>>>16&255,c[a++]=h>>>8&255,c[a++]=255&h;var w=y/4294967296*1e4&268435455;c[a++]=w>>>8&255,c[a++]=255&w,c[a++]=w>>>24&15|16,c[a++]=w>>>16&255,c[a++]=p>>>8|128,c[a++]=255&p;for(var b=0;b<6;++b)c[a+b]=l[b];return o||function(e){var o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,t=(s[e[o+0]]+s[e[o+1]]+s[e[o+2]]+s[e[o+3]]+"-"+s[e[o+4]]+s[e[o+5]]+"-"+s[e[o+6]]+s[e[o+7]]+"-"+s[e[o+8]]+s[e[o+9]]+"-"+s[e[o+10]]+s[e[o+11]]+s[e[o+12]]+s[e[o+13]]+s[e[o+14]]+s[e[o+15]]).toLowerCase();if(!r(t))throw TypeError("Stringified UUID is invalid");return t}(c)}})); \ No newline at end of file diff --git a/node_modules/uuid/dist/umd/uuidv3.min.js b/node_modules/uuid/dist/umd/uuidv3.min.js new file mode 100644 index 0000000..8d37b62 --- /dev/null +++ b/node_modules/uuid/dist/umd/uuidv3.min.js @@ -0,0 +1 @@ +!function(n,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(n="undefined"!=typeof globalThis?globalThis:n||self).uuidv3=r()}(this,(function(){"use strict";var n=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function r(r){return"string"==typeof r&&n.test(r)}for(var e=[],t=0;t<256;++t)e.push((t+256).toString(16).substr(1));function i(n){return 14+(n+64>>>9<<4)+1}function o(n,r){var e=(65535&n)+(65535&r);return(n>>16)+(r>>16)+(e>>16)<<16|65535&e}function a(n,r,e,t,i,a){return o((f=o(o(r,n),o(t,a)))<<(u=i)|f>>>32-u,e);var f,u}function f(n,r,e,t,i,o,f){return a(r&e|~r&t,n,r,i,o,f)}function u(n,r,e,t,i,o,f){return a(r&t|e&~t,n,r,i,o,f)}function c(n,r,e,t,i,o,f){return a(r^e^t,n,r,i,o,f)}function s(n,r,e,t,i,o,f){return a(e^(r|~t),n,r,i,o,f)}return function(n,t,i){function o(n,o,a,f){if("string"==typeof n&&(n=function(n){n=unescape(encodeURIComponent(n));for(var r=[],e=0;e>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=255&e,t[4]=(e=parseInt(n.slice(9,13),16))>>>8,t[5]=255&e,t[6]=(e=parseInt(n.slice(14,18),16))>>>8,t[7]=255&e,t[8]=(e=parseInt(n.slice(19,23),16))>>>8,t[9]=255&e,t[10]=(e=parseInt(n.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=255&e,t}(o)),16!==o.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var u=new Uint8Array(16+n.length);if(u.set(o),u.set(n,o.length),(u=i(u))[6]=15&u[6]|t,u[8]=63&u[8]|128,a){f=f||0;for(var c=0;c<16;++c)a[f+c]=u[c];return a}return function(n){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=(e[n[t+0]]+e[n[t+1]]+e[n[t+2]]+e[n[t+3]]+"-"+e[n[t+4]]+e[n[t+5]]+"-"+e[n[t+6]]+e[n[t+7]]+"-"+e[n[t+8]]+e[n[t+9]]+"-"+e[n[t+10]]+e[n[t+11]]+e[n[t+12]]+e[n[t+13]]+e[n[t+14]]+e[n[t+15]]).toLowerCase();if(!r(i))throw TypeError("Stringified UUID is invalid");return i}(u)}try{o.name=n}catch(n){}return o.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",o.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",o}("v3",48,(function(n){if("string"==typeof n){var r=unescape(encodeURIComponent(n));n=new Uint8Array(r.length);for(var e=0;e>5]>>>i%32&255,a=parseInt(t.charAt(o>>>4&15)+t.charAt(15&o),16);r.push(a)}return r}(function(n,r){n[r>>5]|=128<>5]|=(255&n[t/8])<1&&void 0!==arguments[1]?arguments[1]:0,o=(i[t[e+0]]+i[t[e+1]]+i[t[e+2]]+i[t[e+3]]+"-"+i[t[e+4]]+i[t[e+5]]+"-"+i[t[e+6]]+i[t[e+7]]+"-"+i[t[e+8]]+i[t[e+9]]+"-"+i[t[e+10]]+i[t[e+11]]+i[t[e+12]]+i[t[e+13]]+i[t[e+14]]+i[t[e+15]]).toLowerCase();if(!r(o))throw TypeError("Stringified UUID is invalid");return o}(u)}})); \ No newline at end of file diff --git a/node_modules/uuid/dist/umd/uuidv5.min.js b/node_modules/uuid/dist/umd/uuidv5.min.js new file mode 100644 index 0000000..ba6fc63 --- /dev/null +++ b/node_modules/uuid/dist/umd/uuidv5.min.js @@ -0,0 +1 @@ +!function(r,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(r="undefined"!=typeof globalThis?globalThis:r||self).uuidv5=e()}(this,(function(){"use strict";var r=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function e(e){return"string"==typeof e&&r.test(e)}for(var t=[],n=0;n<256;++n)t.push((n+256).toString(16).substr(1));function a(r,e,t,n){switch(r){case 0:return e&t^~e&n;case 1:return e^t^n;case 2:return e&t^e&n^t&n;case 3:return e^t^n}}function o(r,e){return r<>>32-e}return function(r,n,a){function o(r,o,i,f){if("string"==typeof r&&(r=function(r){r=unescape(encodeURIComponent(r));for(var e=[],t=0;t>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=255&t,n[4]=(t=parseInt(r.slice(9,13),16))>>>8,n[5]=255&t,n[6]=(t=parseInt(r.slice(14,18),16))>>>8,n[7]=255&t,n[8]=(t=parseInt(r.slice(19,23),16))>>>8,n[9]=255&t,n[10]=(t=parseInt(r.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=255&t,n}(o)),16!==o.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var s=new Uint8Array(16+r.length);if(s.set(o),s.set(r,o.length),(s=a(s))[6]=15&s[6]|n,s[8]=63&s[8]|128,i){f=f||0;for(var u=0;u<16;++u)i[f+u]=s[u];return i}return function(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,a=(t[r[n+0]]+t[r[n+1]]+t[r[n+2]]+t[r[n+3]]+"-"+t[r[n+4]]+t[r[n+5]]+"-"+t[r[n+6]]+t[r[n+7]]+"-"+t[r[n+8]]+t[r[n+9]]+"-"+t[r[n+10]]+t[r[n+11]]+t[r[n+12]]+t[r[n+13]]+t[r[n+14]]+t[r[n+15]]).toLowerCase();if(!e(a))throw TypeError("Stringified UUID is invalid");return a}(s)}try{o.name=r}catch(r){}return o.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",o.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",o}("v5",80,(function(r){var e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if("string"==typeof r){var n=unescape(encodeURIComponent(r));r=[];for(var i=0;i>>0;A=U,U=w,w=o(b,30)>>>0,b=g,g=C}t[0]=t[0]+g>>>0,t[1]=t[1]+b>>>0,t[2]=t[2]+w>>>0,t[3]=t[3]+U>>>0,t[4]=t[4]+A>>>0}return[t[0]>>24&255,t[0]>>16&255,t[0]>>8&255,255&t[0],t[1]>>24&255,t[1]>>16&255,t[1]>>8&255,255&t[1],t[2]>>24&255,t[2]>>16&255,t[2]>>8&255,255&t[2],t[3]>>24&255,t[3]>>16&255,t[3]>>8&255,255&t[3],t[4]>>24&255,t[4]>>16&255,t[4]>>8&255,255&t[4]]}))})); \ No newline at end of file diff --git a/node_modules/uuid/dist/uuid-bin.js b/node_modules/uuid/dist/uuid-bin.js new file mode 100644 index 0000000..50a7a9f --- /dev/null +++ b/node_modules/uuid/dist/uuid-bin.js @@ -0,0 +1,85 @@ +"use strict"; + +var _assert = _interopRequireDefault(require("assert")); + +var _v = _interopRequireDefault(require("./v1.js")); + +var _v2 = _interopRequireDefault(require("./v3.js")); + +var _v3 = _interopRequireDefault(require("./v4.js")); + +var _v4 = _interopRequireDefault(require("./v5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function usage() { + console.log('Usage:'); + console.log(' uuid'); + console.log(' uuid v1'); + console.log(' uuid v3 '); + console.log(' uuid v4'); + console.log(' uuid v5 '); + console.log(' uuid --help'); + console.log('\nNote: may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC4122'); +} + +const args = process.argv.slice(2); + +if (args.indexOf('--help') >= 0) { + usage(); + process.exit(0); +} + +const version = args.shift() || 'v4'; + +switch (version) { + case 'v1': + console.log((0, _v.default)()); + break; + + case 'v3': + { + const name = args.shift(); + let namespace = args.shift(); + (0, _assert.default)(name != null, 'v3 name not specified'); + (0, _assert.default)(namespace != null, 'v3 namespace not specified'); + + if (namespace === 'URL') { + namespace = _v2.default.URL; + } + + if (namespace === 'DNS') { + namespace = _v2.default.DNS; + } + + console.log((0, _v2.default)(name, namespace)); + break; + } + + case 'v4': + console.log((0, _v3.default)()); + break; + + case 'v5': + { + const name = args.shift(); + let namespace = args.shift(); + (0, _assert.default)(name != null, 'v5 name not specified'); + (0, _assert.default)(namespace != null, 'v5 namespace not specified'); + + if (namespace === 'URL') { + namespace = _v4.default.URL; + } + + if (namespace === 'DNS') { + namespace = _v4.default.DNS; + } + + console.log((0, _v4.default)(name, namespace)); + break; + } + + default: + usage(); + process.exit(1); +} \ No newline at end of file diff --git a/node_modules/uuid/dist/v1.js b/node_modules/uuid/dist/v1.js new file mode 100644 index 0000000..abb9b3d --- /dev/null +++ b/node_modules/uuid/dist/v1.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; + +let _clockseq; // Previous uuid creation time + + +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + } + + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + + + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + + + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + + msecs += 12219292800000; // `time_low` + + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` + + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf || (0, _stringify.default)(b); +} + +var _default = v1; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/uuid/dist/v3.js b/node_modules/uuid/dist/v3.js new file mode 100644 index 0000000..6b47ff5 --- /dev/null +++ b/node_modules/uuid/dist/v3.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _md = _interopRequireDefault(require("./md5.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/uuid/dist/v35.js b/node_modules/uuid/dist/v35.js new file mode 100644 index 0000000..f784c63 --- /dev/null +++ b/node_modules/uuid/dist/v35.js @@ -0,0 +1,78 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; +exports.URL = exports.DNS = void 0; + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +var _parse = _interopRequireDefault(require("./parse.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + + return bytes; +} + +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; + +function _default(name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + if (typeof value === 'string') { + value = stringToBytes(value); + } + + if (typeof namespace === 'string') { + namespace = (0, _parse.default)(namespace); + } + + if (namespace.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + + + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; + } + + return (0, _stringify.default)(bytes); + } // Function#name is not settable on some platforms (#270) + + + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support + + + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} \ No newline at end of file diff --git a/node_modules/uuid/dist/v4.js b/node_modules/uuid/dist/v4.js new file mode 100644 index 0000000..838ce0b --- /dev/null +++ b/node_modules/uuid/dist/v4.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rng = _interopRequireDefault(require("./rng.js")); + +var _stringify = _interopRequireDefault(require("./stringify.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function v4(options, buf, offset) { + options = options || {}; + + const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; + } + + return (0, _stringify.default)(rnds); +} + +var _default = v4; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/uuid/dist/v5.js b/node_modules/uuid/dist/v5.js new file mode 100644 index 0000000..99d615e --- /dev/null +++ b/node_modules/uuid/dist/v5.js @@ -0,0 +1,16 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _v = _interopRequireDefault(require("./v35.js")); + +var _sha = _interopRequireDefault(require("./sha1.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/uuid/dist/validate.js b/node_modules/uuid/dist/validate.js new file mode 100644 index 0000000..fd05215 --- /dev/null +++ b/node_modules/uuid/dist/validate.js @@ -0,0 +1,17 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _regex = _interopRequireDefault(require("./regex.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); +} + +var _default = validate; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/uuid/dist/version.js b/node_modules/uuid/dist/version.js new file mode 100644 index 0000000..b72949c --- /dev/null +++ b/node_modules/uuid/dist/version.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _validate = _interopRequireDefault(require("./validate.js")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + + return parseInt(uuid.substr(14, 1), 16); +} + +var _default = version; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/uuid/package.json b/node_modules/uuid/package.json new file mode 100644 index 0000000..f0ab371 --- /dev/null +++ b/node_modules/uuid/package.json @@ -0,0 +1,135 @@ +{ + "name": "uuid", + "version": "8.3.2", + "description": "RFC4122 (v1, v4, and v5) UUIDs", + "commitlint": { + "extends": [ + "@commitlint/config-conventional" + ] + }, + "keywords": [ + "uuid", + "guid", + "rfc4122" + ], + "license": "MIT", + "bin": { + "uuid": "./dist/bin/uuid" + }, + "sideEffects": false, + "main": "./dist/index.js", + "exports": { + ".": { + "node": { + "module": "./dist/esm-node/index.js", + "require": "./dist/index.js", + "import": "./wrapper.mjs" + }, + "default": "./dist/esm-browser/index.js" + }, + "./package.json": "./package.json" + }, + "module": "./dist/esm-node/index.js", + "browser": { + "./dist/md5.js": "./dist/md5-browser.js", + "./dist/rng.js": "./dist/rng-browser.js", + "./dist/sha1.js": "./dist/sha1-browser.js", + "./dist/esm-node/index.js": "./dist/esm-browser/index.js" + }, + "files": [ + "CHANGELOG.md", + "CONTRIBUTING.md", + "LICENSE.md", + "README.md", + "dist", + "wrapper.mjs" + ], + "devDependencies": { + "@babel/cli": "7.11.6", + "@babel/core": "7.11.6", + "@babel/preset-env": "7.11.5", + "@commitlint/cli": "11.0.0", + "@commitlint/config-conventional": "11.0.0", + "@rollup/plugin-node-resolve": "9.0.0", + "babel-eslint": "10.1.0", + "bundlewatch": "0.3.1", + "eslint": "7.10.0", + "eslint-config-prettier": "6.12.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.22.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-prettier": "3.1.4", + "eslint-plugin-promise": "4.2.1", + "eslint-plugin-standard": "4.0.1", + "husky": "4.3.0", + "jest": "25.5.4", + "lint-staged": "10.4.0", + "npm-run-all": "4.1.5", + "optional-dev-dependency": "2.0.1", + "prettier": "2.1.2", + "random-seed": "0.3.0", + "rollup": "2.28.2", + "rollup-plugin-terser": "7.0.2", + "runmd": "1.3.2", + "standard-version": "9.0.0" + }, + "optionalDevDependencies": { + "@wdio/browserstack-service": "6.4.0", + "@wdio/cli": "6.4.0", + "@wdio/jasmine-framework": "6.4.0", + "@wdio/local-runner": "6.4.0", + "@wdio/spec-reporter": "6.4.0", + "@wdio/static-server-service": "6.4.0", + "@wdio/sync": "6.4.0" + }, + "scripts": { + "examples:browser:webpack:build": "cd examples/browser-webpack && npm install && npm run build", + "examples:browser:rollup:build": "cd examples/browser-rollup && npm install && npm run build", + "examples:node:commonjs:test": "cd examples/node-commonjs && npm install && npm test", + "examples:node:esmodules:test": "cd examples/node-esmodules && npm install && npm test", + "lint": "npm run eslint:check && npm run prettier:check", + "eslint:check": "eslint src/ test/ examples/ *.js", + "eslint:fix": "eslint --fix src/ test/ examples/ *.js", + "pretest": "[ -n $CI ] || npm run build", + "test": "BABEL_ENV=commonjs node --throw-deprecation node_modules/.bin/jest test/unit/", + "pretest:browser": "optional-dev-dependency && npm run build && npm-run-all --parallel examples:browser:**", + "test:browser": "wdio run ./wdio.conf.js", + "pretest:node": "npm run build", + "test:node": "npm-run-all --parallel examples:node:**", + "test:pack": "./scripts/testpack.sh", + "pretest:benchmark": "npm run build", + "test:benchmark": "cd examples/benchmark && npm install && npm test", + "prettier:check": "prettier --ignore-path .prettierignore --check '**/*.{js,jsx,json,md}'", + "prettier:fix": "prettier --ignore-path .prettierignore --write '**/*.{js,jsx,json,md}'", + "bundlewatch": "npm run pretest:browser && bundlewatch --config bundlewatch.config.json", + "md": "runmd --watch --output=README.md README_js.md", + "docs": "( node --version | grep -q 'v12' ) && ( npm run build && runmd --output=README.md README_js.md )", + "docs:diff": "npm run docs && git diff --quiet README.md", + "build": "./scripts/build.sh", + "prepack": "npm run build", + "release": "standard-version --no-verify" + }, + "repository": { + "type": "git", + "url": "https://github.com/uuidjs/uuid.git" + }, + "husky": { + "hooks": { + "commit-msg": "commitlint -E HUSKY_GIT_PARAMS", + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "*.{js,jsx,json,md}": [ + "prettier --write" + ], + "*.{js,jsx}": [ + "eslint --fix" + ] + }, + "standard-version": { + "scripts": { + "postchangelog": "prettier --write CHANGELOG.md" + } + } +} diff --git a/node_modules/uuid/wrapper.mjs b/node_modules/uuid/wrapper.mjs new file mode 100644 index 0000000..c31e9ce --- /dev/null +++ b/node_modules/uuid/wrapper.mjs @@ -0,0 +1,10 @@ +import uuid from './dist/index.js'; +export const v1 = uuid.v1; +export const v3 = uuid.v3; +export const v4 = uuid.v4; +export const v5 = uuid.v5; +export const NIL = uuid.NIL; +export const version = uuid.version; +export const validate = uuid.validate; +export const stringify = uuid.stringify; +export const parse = uuid.parse; diff --git a/node_modules/xmldom/.npmignore b/node_modules/xmldom/.npmignore deleted file mode 100644 index b094a44..0000000 --- a/node_modules/xmldom/.npmignore +++ /dev/null @@ -1,5 +0,0 @@ -test -t -travis.yml -.project -changelog diff --git a/node_modules/xmldom/.travis.yml b/node_modules/xmldom/.travis.yml deleted file mode 100644 index b95408e..0000000 --- a/node_modules/xmldom/.travis.yml +++ /dev/null @@ -1,22 +0,0 @@ -language: node_js - -node_js: - - '0.10' - -branches: - only: - - master - - proof - - travis-ci - -# Not using `npm install --dev` because it is recursive. It will pull in the all -# development dependencies for CoffeeScript. Way too much spew in the Travis CI -# build output. - -before_install: - - npm install - - npm install istanbul coveralls - -env: - global: - - secure: "BxUHTsa1WVANLQoimilbZwa1MCWSdM9hOmPWBE/rsYb7uT/iiqkRXXwnWhKtN5CLvTvIQbiAzq4iyPID0S8UHrnxClYQrOuA6QkrtwgIEuDAmijao/bgxobPOremvkwXcpMGIwzYKyYQQtSEaEIQbqf6gSSKW9dBh/GZ/vfTsqo=" diff --git a/node_modules/xmldom/CHANGELOG.md b/node_modules/xmldom/CHANGELOG.md new file mode 100644 index 0000000..27fb375 --- /dev/null +++ b/node_modules/xmldom/CHANGELOG.md @@ -0,0 +1,228 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.6.0](https://github.com/xmldom/xmldom/compare/0.5.0...0.6.0) + +### Fixes + +- Stop serializing empty namespace values like `xmlns:ds=""` [`#168`](https://github.com/xmldom/xmldom/pull/168) + BREAKING CHANGE: If your code expected empty namespaces attributes to be serialized. + Thank you [@pdecat](https://github.com/pdecat) and [@FranckDepoortere](https://github.com/FranckDepoortere) +- Escape `<` to `<` when serializing attribute values [`#198`](https://github.com/xmldom/xmldom/issues/198) / [`#199`](https://github.com/xmldom/xmldom/pull/199) + +## 0.5.0 + +### Fixes +- Avoid misinterpretation of malicious XML input - [`GHSA-h6q6-9hqw-rwfv`](https://github.com/xmldom/xmldom/security/advisories/GHSA-h6q6-9hqw-rwfv) (CVE-2021-21366) + - Improve error reporting; throw on duplicate attribute\ + BREAKING CHANGE: It is currently not clear how to consistently deal with duplicate attributes, so it's also safer for our users to fail when detecting them. + It's possible to configure the `DOMParser.errorHandler` before parsing, to handle those errors differently. + + To accomplish this and also be able to verify it in tests I needed to + - create a new `Error` type `ParseError` and export it + - Throw `ParseError` from `errorHandler.fatalError` and prevent those from being caught in `XMLReader`. + - export `DOMHandler` constructor as `__DOMHandler` + - Preserve quotes in DOCTYPE declaration + Since the only purpose of parsing the DOCTYPE is to be able to restore it when serializing, we decided that it would be best to leave the parsed `publicId` and `systemId` as is, including any quotes. + BREAKING CHANGE: If somebody relies on the actual unquoted values of those ids, they will need to take care of either single or double quotes and the right escaping. + (Without this change this would not have been possible because the SAX parser already dropped the information about the quotes that have been used in the source.) + + https://www.w3.org/TR/2006/REC-xml11-20060816/#dtd + https://www.w3.org/TR/2006/REC-xml11-20060816/#IDAX1KS (External Entity Declaration) + +- Fix breaking preprocessors' directives when parsing attributes [`#171`](https://github.com/xmldom/xmldom/pull/171) +- fix(dom): Escape `]]>` when serializing CharData [`#181`](https://github.com/xmldom/xmldom/pull/181) +- Switch to (only) MIT license (drop problematic LGPL license option) [`#178`](https://github.com/xmldom/xmldom/pull/178) +- Export DOMException; remove custom assertions; etc. [`#174`](https://github.com/xmldom/xmldom/pull/174) + +### Docs +- Update MDN links in `readme.md` [`#188`](https://github.com/xmldom/xmldom/pull/188) + +## 0.4.0 + +[Commits](https://github.com/xmldom/xmldom/compare/0.3.0...0.4.0) + +### Fixes +- **BREAKING** Restore ` ` behavior from v0.1.27 [`#67`](https://github.com/xmldom/xmldom/pull/67) +- **BREAKING** Typecheck source param before parsing [`#113`](https://github.com/xmldom/xmldom/pull/113) +- Include documents in package files list [`#156`](https://github.com/xmldom/xmldom/pull/156) +- Preserve doctype with sysid [`#144`](https://github.com/xmldom/xmldom/pull/144) +- Remove ES6 syntax from getElementsByClassName [`#91`](https://github.com/xmldom/xmldom/pull/91) +- Revert "Add lowercase of åäö in entityMap" due to duplicate entries [`#84`](https://github.com/xmldom/xmldom/pull/84) +- fix: Convert all line separators to LF [`#66`](https://github.com/xmldom/xmldom/pull/66) + +### Docs +- Update CHANGELOG.md through version 0.3.0 [`#63`](https://github.com/xmldom/xmldom/pull/63) +- Update badges [`#78`](https://github.com/xmldom/xmldom/pull/78) +- Add .editorconfig file [`#104`](https://github.com/xmldom/xmldom/pull/104) +- Add note about import [`#79`](https://github.com/xmldom/xmldom/pull/79) +- Modernize & improve the example in readme.md [`#81`](https://github.com/xmldom/xmldom/pull/81) + +### CI +- Add Stryker Mutator [`#70`](https://github.com/xmldom/xmldom/pull/70) +- Add Stryker action to update dashboard [`#77`](https://github.com/xmldom/xmldom/pull/77) +- Add Node GitHub action workflow [`#64`](https://github.com/xmldom/xmldom/pull/64) +- add & enable eslint [`#106`](https://github.com/xmldom/xmldom/pull/106) +- Use eslint-plugin-es5 to enforce ES5 syntax [`#107`](https://github.com/xmldom/xmldom/pull/107) +- Recover `vows` tests, drop `proof` tests [`#59`](https://github.com/xmldom/xmldom/pull/59) +- Add jest tessuite and first tests [`#114`](https://github.com/xmldom/xmldom/pull/114) +- Add jest testsuite with `xmltest` cases [`#112`](https://github.com/xmldom/xmldom/pull/112) +- Configure Renovate [`#108`](https://github.com/xmldom/xmldom/pull/108) +- Test European HTML entities [`#86`](https://github.com/xmldom/xmldom/pull/86) +- Updated devDependencies + +### Other +- Remove files that are not of any use [`#131`](https://github.com/xmldom/xmldom/pull/131), [`#65`](https://github.com/xmldom/xmldom/pull/65), [`#33`](https://github.com/xmldom/xmldom/pull/33) + +## 0.3.0 + +[Commits](https://github.com/xmldom/xmldom/compare/0.2.1...0.3.0) + +- **BREAKING** Node >=10.x is now required. +- **BREAKING** Remove `component.json` (deprecated package manager https://github.com/componentjs/guide) +- **BREAKING** Move existing sources into `lib` subdirectory. +- **POSSIBLY BREAKING** Introduce `files` entry in `package.json` and remove use of `.npmignore`. +- [Add `Document.getElementsByClassName`](https://github.com/xmldom/xmldom/issues/24). +- [Add `Node` to the list of exports](https://github.com/xmldom/xmldom/pull/27) +- [Add lowercase of åäö in `entityMap`](https://github.com/xmldom/xmldom/pull/23). +- Move CHANGELOG to markdown file. +- Move LICENSE to markdown file. + +## 0.2.1 + +[Commits](https://github.com/xmldom/xmldom/compare/0.2.0...0.2.1) + +- Correct `homepage`, `repository` and `bugs` URLs in `package.json`. + +## 0.2.0 + +[Commits](https://github.com/xmldom/xmldom/compare/v0.1.27...0.2.0) + +- Includes all **BREAKING** changes introduced in [`xmldom-alpha@v0.1.28`](#0128) by the original authors. +- **POSSIBLY BREAKING** [remove the `Object.create` check from the `_extends` method of `dom.js` that added a `__proto__` property](https://github.com/xmldom/xmldom/commit/0be2ae910a8a22c9ec2cac042e04de4c04317d2a#diff-7d1c5d97786fdf9af5446a241d0b6d56L19-L22) (). +- **POSSIBLY BREAKING** [remove code that added a `__proto__` property](https://github.com/xmldom/xmldom/commit/366159a76a181ce9a0d83f5dc48205686cfaf9cc) +- formatting/corrections in `package.json` + +## 0.1.31 + +[Commits](https://github.com/xmldom/xmldom/compare/v0.1.27...v0.1.31) + +The patch versions (`v0.1.29` - `v0.1.31`) that have been released on the [v0.1.x branch](https://github.com/xmldom/xmldom/tree/0.1.x), to reflect the changed maintainers, **are branched off from [`v0.1.27`](#0127) so they don't include the breaking changes introduced in [`xmldom-alpha@v0.1.28`](#0128)**: + +## Maintainer changes + +After the last commit to the original repository on the 9th of May 2017, the first commit to is from the 19th of December 2019. [The fork has been announced in the original repository on the 2nd of March 2020.](https://github.com/jindw/xmldom/issues/259) + +The versions listed below have been published to one or both of the following packages: +- +- + +It is currently not planned to continue publishing the `xmldom-alpha` package. + +The new maintainers did not invest time to understand changes that led to the last `xmldom` version [`0.1.27`](#0127) published by the original maintainer, but consider it the basis for their work. +A timeline of all the changes that happened from that version until `0.3.0` is available in . Any related questions should be asked there. + +## 0.1.28 + +[Commits](https://github.com/xmldom/xmldom/compare/v0.1.27...xmldom-alpha@v0.1.28) + +Published by @jindw on the 9th of May 2017 as +- `xmldom-alpha@0.1.28` + +- **BREAKING** includes [regression regarding ` ` (issue #57)](https://github.com/xmldom/xmldom/issues/57) +- [Fix `license` field in `package.json`](https://github.com/jindw/xmldom/pull/178) +- [Conditional converting of HTML entities](https://github.com/jindw/xmldom/pull/80) +- Fix `dom.js` serialization issue for missing document element ([example that failed on `toString()` before this change](https://github.com/xmldom/xmldom/blob/a58dcf7a265522e80ce520fe3be0cddb1b976f6f/test/parse/unclosedcomment.js#L10-L11)) +- Add new module `entities.js` + +## 0.1.27 + +Published by @jindw on the 28th of Nov 2016 as +- `xmldom@0.1.27` +- `xmldom-alpha@0.1.27` + +- Various bug fixes. + +## 0.1.26 + +Published on the 18th of Nov 2016 +as `xmldom@0.1.26` + +- Details unknown + +## 0.1.25 + +Published on the 18th of Nov 2016 as +- `xmldom@0.1.25` + +- Details unknown + +## 0.1.24 + +Published on the 27th of November 2016 as +- `xmldom@0.1.24` +- `xmldom-alpha@0.1.24` + +- Added node filter. + +## 0.1.23 + +Published on the 5th of May 2016 as +- `xmldom-alpha@0.1.23` + +- Add namespace support for nest node serialize. +- Various other bug fixes. + +## 0.1.22 + +- Merge XMLNS serialization. +- Remove \r from source string. +- Print namespaces for child elements. +- Switch references to nodeType to use named constants. +- Add nodelist toString support. + +## 0.1.21 + +- Fix serialize bug. + +## 0.1.20 + +- Optimize invalid XML support. +- Add toString sorter for attributes output. +- Add html self closed node button. +- Add `*` NS support for getElementsByTagNameNS. +- Convert attribute's value to string in setAttributeNS. +- Add support for HTML entities for HTML docs only. +- Fix TypeError when Document is created with DocumentType. + +## 0.1.19 + +- Fix [infinite loop on unclosed comment (jindw/xmldom#68)](https://github.com/jindw/xmldom/issues/68) +- Add error report for unclosed tag. +- Various other fixes. + +## 0.1.18 + +- Add default `ns` support. +- parseFromString now renders entirely plain text documents as textNode. +- Enable option to ignore white space on parsing. + +## 0.1.17 + +**Details missing for this and potential earlier version** + +## 0.1.16 + +- Correctly handle multibyte Unicode greater than two byts. #57. #56. +- Initial unit testing and test coverage. #53. #46. #19. +- Create Bower `component.json` #52. + +## 0.1.8 + +- Add: some test case from node-o3-xml(excludes xpath support) +- Fix: remove existed attribute before setting (bug introduced in v0.1.5) +- Fix: index direct access for childNodes and any NodeList collection(not w3c standard) +- Fix: remove last child bug diff --git a/node_modules/xmldom/LICENSE b/node_modules/xmldom/LICENSE index 68a9b5e..b95f569 100644 --- a/node_modules/xmldom/LICENSE +++ b/node_modules/xmldom/LICENSE @@ -1,8 +1,8 @@ -You can choose any one of those: +Copyright 2019 - present Christopher J. Brody and other contributors, as listed in: https://github.com/xmldom/xmldom/graphs/contributors +Copyright 2012 - 2017 @jindw and other contributors, as listed in: https://github.com/jindw/xmldom/graphs/contributors -The MIT License (MIT): +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -link:http://opensource.org/licenses/MIT +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -LGPL: -http://www.gnu.org/licenses/lgpl.html +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/xmldom/__package__.js b/node_modules/xmldom/__package__.js deleted file mode 100644 index b4cad28..0000000 --- a/node_modules/xmldom/__package__.js +++ /dev/null @@ -1,4 +0,0 @@ -this.addScript('dom.js',['DOMImplementation','XMLSerializer']); -this.addScript('dom-parser.js',['DOMHandler','DOMParser'], - ['DOMImplementation','XMLReader']); -this.addScript('sax.js','XMLReader'); \ No newline at end of file diff --git a/node_modules/xmldom/changelog b/node_modules/xmldom/changelog deleted file mode 100644 index ab815bb..0000000 --- a/node_modules/xmldom/changelog +++ /dev/null @@ -1,14 +0,0 @@ -### Version 0.1.16 - -Sat May 4 14:58:03 UTC 2013 - - * Correctly handle multibyte Unicode greater than two byts. #57. #56. - * Initial unit testing and test coverage. #53. #46. #19. - * Create Bower `component.json` #52. - -### Version 0.1.8 - - * Add: some test case from node-o3-xml(excludes xpath support) - * Fix: remove existed attribute before setting (bug introduced in v0.1.5) - * Fix: index direct access for childNodes and any NodeList collection(not w3c standard) - * Fix: remove last child bug diff --git a/node_modules/xmldom/component.json b/node_modules/xmldom/component.json deleted file mode 100644 index 93b4d57..0000000 --- a/node_modules/xmldom/component.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "xmldom", - "version": "0.1.15", - "main": "dom-parser.js", - "ignore": [ - "**/.*", - "node_modules", - "components" - ] -} diff --git a/node_modules/xmldom/lib/.eslintrc.yml b/node_modules/xmldom/lib/.eslintrc.yml new file mode 100644 index 0000000..3eb98ab --- /dev/null +++ b/node_modules/xmldom/lib/.eslintrc.yml @@ -0,0 +1,2 @@ +extends: + - 'plugin:es5/no-es2015' diff --git a/node_modules/xmldom/dom-parser.js b/node_modules/xmldom/lib/dom-parser.js similarity index 91% rename from node_modules/xmldom/dom-parser.js rename to node_modules/xmldom/lib/dom-parser.js index 41d5226..2ad090d 100644 --- a/node_modules/xmldom/dom-parser.js +++ b/node_modules/xmldom/lib/dom-parser.js @@ -1,7 +1,7 @@ function DOMParser(options){ this.options = options ||{locator:{}}; - } + DOMParser.prototype.parseFromString = function(source,mimeType){ var options = this.options; var sax = new XMLReader(); @@ -9,20 +9,19 @@ DOMParser.prototype.parseFromString = function(source,mimeType){ var errorHandler = options.errorHandler; var locator = options.locator; var defaultNSMap = options.xmlns||{}; - var entityMap = {'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"} + var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1; + var entityMap = isHTML?htmlEntity.entityMap:{'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"}; if(locator){ domBuilder.setDocumentLocator(locator) } - + sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator); sax.domBuilder = options.domBuilder || domBuilder; - if(/\/x?html?$/.test(mimeType)){ - entityMap.nbsp = '\xa0'; - entityMap.copy = '\xa9'; + if(isHTML){ defaultNSMap['']= 'http://www.w3.org/1999/xhtml'; } defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace'; - if(source){ + if(source && typeof source === 'string'){ sax.parse(source,defaultNSMap,entityMap); }else{ sax.errorHandler.error("invalid doc source"); @@ -58,8 +57,8 @@ function buildErrorHandler(errorImpl,domBuilder,locator){ /** * +ContentHandler+ErrorHandler * +LexicalHandler+EntityResolver2 - * -DeclHandler-DTDHandler - * + * -DeclHandler-DTDHandler + * * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2 * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html @@ -74,7 +73,7 @@ function position(locator,node){ /** * @see org.xml.sax.ContentHandler#startDocument * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html - */ + */ DOMHandler.prototype = { startDocument : function() { this.doc = new DOMImplementation().createDocument(null, null, null); @@ -88,7 +87,7 @@ DOMHandler.prototype = { var len = attrs.length; appendElement(this, el); this.currentElement = el; - + this.locator && position(this.locator,el) for (var i = 0 ; i < len; i++) { var namespaceURI = attrs.getURI(i); @@ -151,7 +150,7 @@ DOMHandler.prototype = { this.locator && position(this.locator,comm) appendElement(this, comm); }, - + startCDATA:function() { //used in characters() methods this.cdata = true; @@ -159,7 +158,7 @@ DOMHandler.prototype = { endCDATA:function() { this.cdata = false; }, - + startDTD:function(name, publicId, systemId) { var impl = this.doc.implementation; if (impl && impl.createDocumentType) { @@ -179,8 +178,7 @@ DOMHandler.prototype = { console.error('[xmldom error]\t'+error,_locator(this.locator)); }, fatalError:function(error) { - console.error('[xmldom fatalError]\t'+error,_locator(this.locator)); - throw error; + throw new ParseError(error, this.locator); } } function _locator(l){ @@ -244,8 +242,12 @@ function appendElement (hander,node) { }//appendChild and setAttributeNS are preformance key //if(typeof require == 'function'){ - var XMLReader = require('./sax').XMLReader; - var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation; - exports.XMLSerializer = require('./dom').XMLSerializer ; - exports.DOMParser = DOMParser; +var htmlEntity = require('./entities'); +var sax = require('./sax'); +var XMLReader = sax.XMLReader; +var ParseError = sax.ParseError; +var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation; +exports.XMLSerializer = require('./dom').XMLSerializer ; +exports.DOMParser = DOMParser; +exports.__DOMHandler = DOMHandler; //} diff --git a/node_modules/xmldom/dom.js b/node_modules/xmldom/lib/dom.js similarity index 93% rename from node_modules/xmldom/dom.js rename to node_modules/xmldom/lib/dom.js index b290df0..12288c8 100644 --- a/node_modules/xmldom/dom.js +++ b/node_modules/xmldom/lib/dom.js @@ -1,10 +1,3 @@ -/* - * DOM Level 2 - * Object DOMException - * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html - * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - */ - function copy(src,dest){ for(var p in src){ dest[p] = src[p]; @@ -16,10 +9,6 @@ function copy(src,dest){ */ function _extends(Class,Super){ var pt = Class.prototype; - if(Object.create){ - var ppt = Object.create(Super.prototype) - pt.__proto__ = ppt; - } if(!(pt instanceof Super)){ function t(){}; t.prototype = Super.prototype; @@ -70,7 +59,12 @@ var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((Exce var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14); var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15); - +/** + * DOM Level 2 + * Object DOMException + * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html + * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html + */ function DOMException(code, message) { if(message instanceof Error){ var error = message; @@ -612,6 +606,21 @@ Document.prototype = { return rtv; }, + getElementsByClassName: function(className) { + var pattern = new RegExp("(^|\\s)" + className + "(\\s|$)"); + return new LiveNodeList(this, function(base) { + var ls = []; + _visitNode(base.documentElement, function(node) { + if(node !== base && node.nodeType == ELEMENT_NODE) { + if(pattern.test(node.getAttribute('class'))) { + ls.push(node); + } + } + }); + return ls; + }); + }, + //document factory method: createElement : function(tagName){ var node = new Element(); @@ -916,7 +925,7 @@ XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){ Node.prototype.toString = nodeSerializeToString; function nodeSerializeToString(isHtml,nodeFilter){ var buf = []; - var refNode = this.nodeType == 9?this.documentElement:this; + var refNode = this.nodeType == 9 && this.documentElement || this; var prefix = refNode.prefix; var uri = refNode.namespaceURI; @@ -1015,9 +1024,13 @@ function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){ if (needNamespaceDefine(node,isHTML, visibleNamespaces)) { var prefix = node.prefix||''; var uri = node.namespaceURI; - var ns = prefix ? ' xmlns:' + prefix : " xmlns"; - buf.push(ns, '="' , uri , '"'); - visibleNamespaces.push({ prefix: prefix, namespace:uri }); + if (uri) { + // Avoid empty namespace value like xmlns:ds="" + // Empty namespace URL will we produce an invalid XML document + var ns = prefix ? ' xmlns:' + prefix : " xmlns"; + buf.push(ns, '="' , uri , '"'); + visibleNamespaces.push({ prefix: prefix, namespace:uri }); + } } if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){ @@ -1055,9 +1068,33 @@ function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){ } return; case ATTRIBUTE_NODE: - return buf.push(' ',node.name,'="',node.value.replace(/[<&"]/g,_xmlEncoder),'"'); + /** + * Well-formedness constraint: No < in Attribute Values + * The replacement text of any entity referred to directly or indirectly in an attribute value must not contain a <. + * @see https://www.w3.org/TR/xml/#CleanAttrVals + * @see https://www.w3.org/TR/xml/#NT-AttValue + */ + return buf.push(' ', node.name, '="', node.value.replace(/[<&"]/g,_xmlEncoder), '"'); case TEXT_NODE: - return buf.push(node.data.replace(/[<&]/g,_xmlEncoder)); + /** + * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, + * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. + * If they are needed elsewhere, they must be escaped using either numeric character references or the strings + * `&` and `<` respectively. + * The right angle bracket (>) may be represented using the string " > ", and must, for compatibility, + * be escaped using either `>` or a character reference when it appears in the string `]]>` in content, + * when that string is not marking the end of a CDATA section. + * + * In the content of elements, character data is any string of characters + * which does not contain the start-delimiter of any markup + * and does not include the CDATA-section-close delimiter, `]]>`. + * + * @see https://www.w3.org/TR/xml/#NT-CharData + */ + return buf.push(node.data + .replace(/[<&]/g,_xmlEncoder) + .replace(/]]>/g, ']]>') + ); case CDATA_SECTION_NODE: return buf.push( ''); case COMMENT_NODE: @@ -1067,13 +1104,13 @@ function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){ var sysid = node.systemId; buf.push(''); + buf.push('>'); }else if(sysid && sysid!='.'){ - buf.push(' SYSTEM "',sysid,'">'); + buf.push(' SYSTEM ', sysid, '>'); }else{ var sub = node.internalSubset; if(sub){ @@ -1239,6 +1276,8 @@ try{ } //if(typeof require == 'function'){ + exports.Node = Node; + exports.DOMException = DOMException; exports.DOMImplementation = DOMImplementation; exports.XMLSerializer = XMLSerializer; //} diff --git a/node_modules/xmldom/lib/entities.js b/node_modules/xmldom/lib/entities.js new file mode 100644 index 0000000..aef4238 --- /dev/null +++ b/node_modules/xmldom/lib/entities.js @@ -0,0 +1,243 @@ +exports.entityMap = { + lt: '<', + gt: '>', + amp: '&', + quot: '"', + apos: "'", + Agrave: "À", + Aacute: "Á", + Acirc: "Â", + Atilde: "Ã", + Auml: "Ä", + Aring: "Å", + AElig: "Æ", + Ccedil: "Ç", + Egrave: "È", + Eacute: "É", + Ecirc: "Ê", + Euml: "Ë", + Igrave: "Ì", + Iacute: "Í", + Icirc: "Î", + Iuml: "Ï", + ETH: "Ð", + Ntilde: "Ñ", + Ograve: "Ò", + Oacute: "Ó", + Ocirc: "Ô", + Otilde: "Õ", + Ouml: "Ö", + Oslash: "Ø", + Ugrave: "Ù", + Uacute: "Ú", + Ucirc: "Û", + Uuml: "Ü", + Yacute: "Ý", + THORN: "Þ", + szlig: "ß", + agrave: "à", + aacute: "á", + acirc: "â", + atilde: "ã", + auml: "ä", + aring: "å", + aelig: "æ", + ccedil: "ç", + egrave: "è", + eacute: "é", + ecirc: "ê", + euml: "ë", + igrave: "ì", + iacute: "í", + icirc: "î", + iuml: "ï", + eth: "ð", + ntilde: "ñ", + ograve: "ò", + oacute: "ó", + ocirc: "ô", + otilde: "õ", + ouml: "ö", + oslash: "ø", + ugrave: "ù", + uacute: "ú", + ucirc: "û", + uuml: "ü", + yacute: "ý", + thorn: "þ", + yuml: "ÿ", + nbsp: "\u00a0", + iexcl: "¡", + cent: "¢", + pound: "£", + curren: "¤", + yen: "¥", + brvbar: "¦", + sect: "§", + uml: "¨", + copy: "©", + ordf: "ª", + laquo: "«", + not: "¬", + shy: "­­", + reg: "®", + macr: "¯", + deg: "°", + plusmn: "±", + sup2: "²", + sup3: "³", + acute: "´", + micro: "µ", + para: "¶", + middot: "·", + cedil: "¸", + sup1: "¹", + ordm: "º", + raquo: "»", + frac14: "¼", + frac12: "½", + frac34: "¾", + iquest: "¿", + times: "×", + divide: "÷", + forall: "∀", + part: "∂", + exist: "∃", + empty: "∅", + nabla: "∇", + isin: "∈", + notin: "∉", + ni: "∋", + prod: "∏", + sum: "∑", + minus: "−", + lowast: "∗", + radic: "√", + prop: "∝", + infin: "∞", + ang: "∠", + and: "∧", + or: "∨", + cap: "∩", + cup: "∪", + 'int': "∫", + there4: "∴", + sim: "∼", + cong: "≅", + asymp: "≈", + ne: "≠", + equiv: "≡", + le: "≤", + ge: "≥", + sub: "⊂", + sup: "⊃", + nsub: "⊄", + sube: "⊆", + supe: "⊇", + oplus: "⊕", + otimes: "⊗", + perp: "⊥", + sdot: "⋅", + Alpha: "Α", + Beta: "Β", + Gamma: "Γ", + Delta: "Δ", + Epsilon: "Ε", + Zeta: "Ζ", + Eta: "Η", + Theta: "Θ", + Iota: "Ι", + Kappa: "Κ", + Lambda: "Λ", + Mu: "Μ", + Nu: "Ν", + Xi: "Ξ", + Omicron: "Ο", + Pi: "Π", + Rho: "Ρ", + Sigma: "Σ", + Tau: "Τ", + Upsilon: "Υ", + Phi: "Φ", + Chi: "Χ", + Psi: "Ψ", + Omega: "Ω", + alpha: "α", + beta: "β", + gamma: "γ", + delta: "δ", + epsilon: "ε", + zeta: "ζ", + eta: "η", + theta: "θ", + iota: "ι", + kappa: "κ", + lambda: "λ", + mu: "μ", + nu: "ν", + xi: "ξ", + omicron: "ο", + pi: "π", + rho: "ρ", + sigmaf: "ς", + sigma: "σ", + tau: "τ", + upsilon: "υ", + phi: "φ", + chi: "χ", + psi: "ψ", + omega: "ω", + thetasym: "ϑ", + upsih: "ϒ", + piv: "ϖ", + OElig: "Œ", + oelig: "œ", + Scaron: "Š", + scaron: "š", + Yuml: "Ÿ", + fnof: "ƒ", + circ: "ˆ", + tilde: "˜", + ensp: " ", + emsp: " ", + thinsp: " ", + zwnj: "‌", + zwj: "‍", + lrm: "‎", + rlm: "‏", + ndash: "–", + mdash: "—", + lsquo: "‘", + rsquo: "’", + sbquo: "‚", + ldquo: "“", + rdquo: "”", + bdquo: "„", + dagger: "†", + Dagger: "‡", + bull: "•", + hellip: "…", + permil: "‰", + prime: "′", + Prime: "″", + lsaquo: "‹", + rsaquo: "›", + oline: "‾", + euro: "€", + trade: "™", + larr: "←", + uarr: "↑", + rarr: "→", + darr: "↓", + harr: "↔", + crarr: "↵", + lceil: "⌈", + rceil: "⌉", + lfloor: "⌊", + rfloor: "⌋", + loz: "◊", + spades: "♠", + clubs: "♣", + hearts: "♥", + diams: "♦" +}; diff --git a/node_modules/xmldom/sax.js b/node_modules/xmldom/lib/sax.js similarity index 90% rename from node_modules/xmldom/sax.js rename to node_modules/xmldom/lib/sax.js index b33635f..ad9f184 100644 --- a/node_modules/xmldom/sax.js +++ b/node_modules/xmldom/lib/sax.js @@ -18,6 +18,21 @@ var S_ATTR_END = 5;//attr value end and no space(quot end) var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer) var S_TAG_CLOSE = 7;//closed el +/** + * Creates an error that will not be caught by XMLReader aka the SAX parser. + * + * @param {string} message + * @param {any?} locator Optional, can provide details about the location in the source + * @constructor + */ +function ParseError(message, locator) { + this.message = message + this.locator = locator + if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError); +} +ParseError.prototype = new Error(); +ParseError.prototype.name = ParseError.name + function XMLReader(){ } @@ -105,7 +120,6 @@ function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){ if(end<0){ tagName = source.substring(tagStart+2).replace(/[\s<].*/,''); - //console.error('#@@@@@@'+tagName) errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName); end = tagStart+1+tagName.length; }else if(tagName.match(/\sstart){ start = end; @@ -211,6 +223,16 @@ function copyLocator(f,t){ * @return end of the elementStartPart(end of elementEndPart for selfClosed el) */ function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){ + + /** + * @param {string} qname + * @param {string} value + * @param {number} startIndex + */ + function addAttribute(qname, value, startIndex) { + if (qname in el.attributeNames) errorHandler.fatalError('Attribute ' + qname + ' redefined') + el.addValue(qname, value, startIndex) + } var attrName; var value; var p = ++start; @@ -226,7 +248,7 @@ function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,error s = S_EQ; }else{ //fatalError: equal must after attrName or space after attrName - throw new Error('attribute equal must after attrName'); + throw new Error('attribute equal must after attrName'); // No known test case } break; case '\'': @@ -241,7 +263,7 @@ function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,error p = source.indexOf(c,start) if(p>0){ value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); - el.add(attrName,value,start-1); + addAttribute(attrName, value, start-1); s = S_ATTR_END; }else{ //fatalError: no end quot match @@ -250,14 +272,14 @@ function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,error }else if(s == S_ATTR_NOQUOT_VALUE){ value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); //console.log(attrName,value,start,p) - el.add(attrName,value,start); + addAttribute(attrName, value, start); //console.dir(el) errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!'); start = p+1; s = S_ATTR_END }else{ //fatalError: no equal before - throw new Error('attribute value must after "="'); + throw new Error('attribute value must after "="'); // No known test case } break; case '/': @@ -275,11 +297,10 @@ function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,error break; //case S_EQ: default: - throw new Error("attribute invalid close char('/')") + throw new Error("attribute invalid close char('/')") // No known test case } break; case ''://end document - //throw new Error('unexpected end of input') errorHandler.error('unexpected end of input'); if(s == S_TAG){ el.setTagName(source.slice(start,p)); @@ -305,13 +326,13 @@ function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,error value = attrName; } if(s == S_ATTR_NOQUOT_VALUE){ - errorHandler.warning('attribute "'+value+'" missed quot(")!!'); - el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start) + errorHandler.warning('attribute "'+value+'" missed quot(")!'); + addAttribute(attrName, value.replace(/&#?\w+;/g,entityReplacer), start) }else{ if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){ errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!') } - el.add(value,value,start) + addAttribute(value, value, start) } break; case S_EQ: @@ -336,7 +357,7 @@ function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,error case S_ATTR_NOQUOT_VALUE: var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); errorHandler.warning('attribute "'+value+'" missed quot(")!!'); - el.add(attrName,value,start) + addAttribute(attrName, value, start) case S_ATTR_END: s = S_TAG_SPACE; break; @@ -359,7 +380,7 @@ function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,error if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){ errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!') } - el.add(attrName,attrName,start); + addAttribute(attrName, attrName, start); start = p; s = S_ATTR; break; @@ -531,11 +552,18 @@ function parseDCC(source,start,domBuilder,errorHandler){//sure start with '1 && /!doctype/i.test(matchs[0][0])){ var name = matchs[1][0]; - var pubid = len>3 && /^public$/i.test(matchs[2][0]) && matchs[3][0] - var sysid = len>4 && matchs[4][0]; + var pubid = false; + var sysid = false; + if(len>3){ + if(/^public$/i.test(matchs[2][0])){ + pubid = matchs[3][0]; + sysid = len>4 && matchs[4][0]; + }else if(/^system$/i.test(matchs[2][0])){ + sysid = matchs[3][0]; + } + } var lastMatch = matchs[len-1] - domBuilder.startDTD(name,pubid && pubid.replace(/^(['"])(.*?)\1$/,'$2'), - sysid && sysid.replace(/^(['"])(.*?)\1$/,'$2')); + domBuilder.startDTD(name, pubid, sysid); domBuilder.endDTD(); return lastMatch.index+lastMatch[0].length @@ -561,11 +589,8 @@ function parseInstruction(source,start,domBuilder){ return -1; } -/** - * @param source - */ -function ElementAttributes(source){ - +function ElementAttributes(){ + this.attributeNames = {} } ElementAttributes.prototype = { setTagName:function(tagName){ @@ -574,10 +599,11 @@ ElementAttributes.prototype = { } this.tagName = tagName }, - add:function(qName,value,offset){ + addValue:function(qName, value, offset) { if(!tagNamePattern.test(qName)){ throw new Error('invalid attribute:'+qName) } + this.attributeNames[qName] = this.length; this[this.length++] = {qName:qName,value:value,offset:offset} }, length:0, @@ -600,23 +626,6 @@ ElementAttributes.prototype = { - -function _set_proto_(thiz,parent){ - thiz.__proto__ = parent; - return thiz; -} -if(!(_set_proto_({},_set_proto_.prototype) instanceof _set_proto_)){ - _set_proto_ = function(thiz,parent){ - function p(){}; - p.prototype = parent; - p = new p(); - for(parent in thiz){ - p[parent] = thiz[parent]; - } - return p; - } -} - function split(source,start){ var match; var buf = []; @@ -630,4 +639,4 @@ function split(source,start){ } exports.XMLReader = XMLReader; - +exports.ParseError = ParseError; diff --git a/node_modules/xmldom/package.json b/node_modules/xmldom/package.json index 0307333..003dd91 100644 --- a/node_modules/xmldom/package.json +++ b/node_modules/xmldom/package.json @@ -1,96 +1,98 @@ { - "_from": "xmldom", - "_id": "xmldom@0.1.27", - "_inBundle": false, - "_integrity": "sha1-1QH5ezvbQDr4757MIFcxh6rawOk=", - "_location": "/xmldom", - "_phantomChildren": {}, - "_requested": { - "type": "tag", - "registry": true, - "raw": "xmldom", - "name": "xmldom", - "escapedName": "xmldom", - "rawSpec": "", - "saveSpec": null, - "fetchSpec": "latest" + "name": "xmldom", + "version": "0.6.0", + "description": "A pure JavaScript W3C standard-based (XML DOM Level 2 Core) DOMParser and XMLSerializer module.", + "keywords": [ + "w3c", + "dom", + "xml", + "parser", + "javascript", + "DOMParser", + "XMLSerializer" + ], + "author": "jindw (http://www.xidea.org)", + "homepage": "https://github.com/xmldom/xmldom", + "repository": { + "type": "git", + "url": "git://github.com/xmldom/xmldom.git" }, - "_requiredBy": [ - "#USER", - "/" + "main": "lib/dom-parser.js", + "files": [ + "CHANGELOG.md", + "LICENSE", + "readme.md", + "lib" ], - "_resolved": "https://registry.npmjs.org/xmldom/-/xmldom-0.1.27.tgz", - "_shasum": "d501f97b3bdb403af8ef9ecc20573187aadac0e9", - "_spec": "xmldom", - "_where": "C:\\MyTools\\projects\\get-xml-info", - "author": { - "name": "jindw", - "email": "jindw@xidea.org", - "url": "http://www.xidea.org" + "scripts": { + "lint": "npm-run-all lint:eslint", + "lint:eslint": "eslint lib test", + "start": "nodemon --watch package.json --watch lib --watch test --exec 'npm --silent run test'", + "stryker": "stryker run", + "test": "npm-run-all test:unit lint", + "test:unit": "npm-run-all test:jest", + "test:jest": "jest" }, - "bugs": { - "url": "http://github.com/jindw/xmldom/issues", - "email": "jindw@xidea.org" + "engines": { + "node": ">=10.0.0" }, - "bundleDependencies": false, + "dependencies": {}, + "devDependencies": { + "@stryker-mutator/core": "^4.5.1", + "dom-js": "0.0.9", + "eslint": "^7.23.0", + "eslint-config-prettier": "^8.1.0", + "eslint-plugin-es5": "^1.5.0", + "eslint-plugin-prettier": "^3.3.1", + "get-stream": "^6.0.0", + "jest": "^26.6.3", + "nodemon": "^2.0.7", + "npm-run-all": "^4.1.5", + "prettier": "^2.2.1", + "xmltest": "^1.5.0", + "yauzl": "^2.10.0" + }, + "maintainers": [ + { + "name": "brodybits", + "email": "chris@brody.consulting", + "url": "https://github.com/brodybits" + } + ], "contributors": [ + { + "name": "jindw", + "email": "jindw@xidea.org", + "url": "http://www.xidea.org" + }, { "name": "Yaron Naveh", "email": "yaronn01@gmail.com", - "url": "http://webservices20.blogspot.com/" + "web": "http://webservices20.blogspot.com/" }, { "name": "Harutyun Amirjanyan", "email": "amirjanyan@gmail.com", - "url": "https://github.com/nightwing" + "web": "https://github.com/nightwing" }, { "name": "Alan Gutierrez", "email": "alan@prettyrobots.com", - "url": "http://www.prettyrobots.com/" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "A W3C Standard XML DOM(Level2 CORE) implementation and parser(DOMParser/XMLSerializer).", - "devDependencies": { - "proof": "0.0.28" - }, - "engines": { - "node": ">=0.1" - }, - "homepage": "https://github.com/jindw/xmldom", - "keywords": [ - "w3c", - "dom", - "xml", - "parser", - "javascript", - "DOMParser", - "XMLSerializer" - ], - "licenses": [ + "web": "http://www.prettyrobots.com/" + }, { - "type": "LGPL", - "url": "http://www.gnu.org/licenses/lgpl.html", - "MIT": "http://opensource.org/licenses/MIT" - } - ], - "main": "./dom-parser.js", - "maintainers": [ + "name": "Eric Newport", + "email": "kethinov@gmail.com", + "web": "https://github.com/kethinov" + }, { - "name": "jindw", - "email": "jindw@xidea.org", - "url": "http://www.xidea.org" + "name": "Christian Bewernitz", + "email": "coder@karfau.de", + "web": "https://github.com/karfau" } ], - "name": "xmldom", - "repository": { - "type": "git", - "url": "git://github.com/jindw/xmldom.git" - }, - "scripts": { - "test": "proof platform win32 && proof test */*/*.t.js || t/test" + "bugs": { + "url": "https://github.com/xmldom/xmldom/issues" }, - "version": "0.1.27" + "license": "MIT" } diff --git a/node_modules/xmldom/readme.md b/node_modules/xmldom/readme.md index f832c44..479c077 100644 --- a/node_modules/xmldom/readme.md +++ b/node_modules/xmldom/readme.md @@ -1,9 +1,17 @@ -# XMLDOM [![Build Status](https://secure.travis-ci.org/bigeasy/xmldom.png?branch=master)](http://travis-ci.org/bigeasy/xmldom) [![Coverage Status](https://coveralls.io/repos/bigeasy/xmldom/badge.png?branch=master)](https://coveralls.io/r/bigeasy/xmldom) [![NPM version](https://badge.fury.io/js/xmldom.png)](http://badge.fury.io/js/xmldom) +# XMLDOM + +[![license](https://img.shields.io/npm/l/xmldom?color=blue&style=flat-square)](LICENSE) +[![npm](https://img.shields.io/npm/v/xmldom?style=flat-square)](https://www.npmjs.com/package/xmldom) +[![bug issues](https://img.shields.io/github/issues/xmldom/xmldom/bug?color=red&style=flat-square)](https://github.com/xmldom/xmldom/issues?q=is%3Aissue+is%3Aopen+label%3Abug) +[!["help wanted" issues](https://img.shields.io/github/issues/xmldom/xmldom/help%20wanted?color=darkgreen&style=flat-square)](https://github.com/xmldom/xmldom/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) +[![Mutation report](https://camo.githubusercontent.com/ee312c4ebce7784ce9f785757eba5d6e33e6d950/68747470733a2f2f696d672e736869656c64732e696f2f656e64706f696e743f7374796c653d666c61742675726c3d687474707325334125324625324662616467652d6170692e737472796b65722d6d757461746f722e696f2532466769746875622e636f6d25324662726f647962697473253246786d6c646f6d2532466d6173746572)](https://dashboard.stryker-mutator.io/reports/github.com/brodybits/xmldom/master) A JavaScript implementation of W3C DOM for Node.js, Rhino and the browser. Fully compatible with `W3C DOM level2`; and some compatible with `level3`. Supports `DOMParser` and `XMLSerializer` interface such as in browser. +**Original project location:** + Install: ------- >npm install xmldom @@ -11,24 +19,34 @@ Install: Example: ==== ```javascript -var DOMParser = require('xmldom').DOMParser; -var doc = new DOMParser().parseFromString( - '\n'+ - '\ttest\n'+ - '\t\n'+ - '\t\n'+ - '' - ,'text/xml'); -doc.documentElement.setAttribute('x','y'); -doc.documentElement.setAttributeNS('./lite','c:x','y2'); -var nsAttr = doc.documentElement.getAttributeNS('./lite','x') -console.info(nsAttr) +const { DOMParser } = require('xmldom') + +const doc = new DOMParser().parseFromString( + '\n' + + '\ttest\n' + + '\t\n' + + '\t\n' + + '', + 'text/xml' +) +doc.documentElement.setAttribute('x', 'y') +doc.documentElement.setAttributeNS('./lite', 'c:x', 'y2') console.info(doc) + +const nsAttr = doc.documentElement.getAttributeNS('./lite', 'x') +console.info(nsAttr) ``` + +Note: in Typescript and ES6 you can use the import approach, as follows: + +```javascript +import { DOMParser } from 'xmldom' +``` + API Reference ===== - * [DOMParser](https://developer.mozilla.org/en/DOMParser): + * [DOMParser](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser): ```javascript parseFromString(xmlsource,mimeType) @@ -56,7 +74,7 @@ API Reference ``` - * [XMLSerializer](https://developer.mozilla.org/en/XMLSerializer) + * [XMLSerializer](https://developer.mozilla.org/en-US/docs/Web/API/XMLSerializer) ```javascript serializeToString(node) @@ -80,6 +98,30 @@ DOM level2 method and attribute: normalize() isSupported(feature, version) hasAttributes() +* [DOMException](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html) + The DOMException class has the following constants (and `value` of type `Number`): + + 1. `DOMException.INDEX_SIZE_ERR` (`1`) + 1. `DOMException.DOMSTRING_SIZE_ERR` (`2`) + 1. `DOMException.HIERARCHY_REQUEST_ERR` (`3`) + 1. `DOMException.WRONG_DOCUMENT_ERR` (`4`) + 1. `DOMException.INVALID_CHARACTER_ERR` (`5`) + 1. `DOMException.NO_DATA_ALLOWED_ERR` (`6`) + 1. `DOMException.NO_MODIFICATION_ALLOWED_ERR` (`7`) + 1. `DOMException.NOT_FOUND_ERR` (`8`) + 1. `DOMException.NOT_SUPPORTED_ERR` (`9`) + 1. `DOMException.INUSE_ATTRIBUTE_ERR` (`10`) + 1. `DOMException.INVALID_STATE_ERR` (`11`) + 1. `DOMException.SYNTAX_ERR` (`12`) + 1. `DOMException.INVALID_MODIFICATION_ERR` (`13`) + 1. `DOMException.NAMESPACE_ERR` (`14`) + 1. `DOMException.INVALID_ACCESS_ERR` (`15`) + + The DOMException object has the following properties: + code + This property is of type Number. + + * extends the Error type thrown as part of DOM API: * [DOMImplementation](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-102161490) @@ -210,7 +252,8 @@ DOM level 3 support: DOM extension by xmldom --- - * [Node] Source position extension; + +* [Node] Source position extension; attribute: //Numbered starting from '1' diff --git a/node_modules/xpath/.npmignore b/node_modules/xpath/.npmignore deleted file mode 100644 index c2658d7..0000000 --- a/node_modules/xpath/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules/ diff --git a/node_modules/xpath/LICENSE b/node_modules/xpath/LICENSE new file mode 100644 index 0000000..e9a0bae --- /dev/null +++ b/node_modules/xpath/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2018 Cameron McCormack + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/xpath/docs/XPathEvaluator.md b/node_modules/xpath/docs/XPathEvaluator.md index 471cfec..fe0999b 100644 --- a/node_modules/xpath/docs/XPathEvaluator.md +++ b/node_modules/xpath/docs/XPathEvaluator.md @@ -2,15 +2,15 @@ The `xpath.parse()` method returns an `XPathEvaluator`, which contains the following methods. -Each of these methods takes an optional `options` object, which can contain any of the following properties: +Each of these methods takes an optional `options` object, which can contain any of the following properties. See the links for each item for further details: -`namespaces` - a namespace resolver. See the [documentation page](namespace%20resolvers.md) for details. +- `namespaces` - a [namespace resolver](namespace%20resolvers.md) -`variables` - a variable resolver. See the [documentation page](variable%20resolvers.md) for details. +- `variables` - a [variable resolver](variable%20resolvers.md) -`functions` - a function resolver. See the [documentation page](function%20resolvers.md) for details. +- `functions` - a [function resolver](function%20resolvers.md) -`node` - the context node for evaluating the expression +- `node` - the context node for evaluating the expression Example usage: @@ -56,7 +56,7 @@ This is only valid for expressions that evaluate to a node set. `select1([options])` -Evaluates the XPath expression and the first node in the resulting node set, in document order. Returns `undefined` +Evaluates the XPath expression and the first node in the resulting node set, in document order. Returns `undefined` if the resulting node set is empty. This is only valid for expressions that evaluate to a node set. diff --git a/node_modules/xpath/docs/function resolvers.md b/node_modules/xpath/docs/function resolvers.md index 918af9f..ad369a6 100644 --- a/node_modules/xpath/docs/function resolvers.md +++ b/node_modules/xpath/docs/function resolvers.md @@ -31,11 +31,11 @@ Example usage: ```js var evaluator = xpath.parse('squareRoot(10)'); var aboutPi = evaluator.evaluateNumber({ - functions: { - 'squareRoot': function (c, value) { - return Math.sqrt(value.numberValue()); - } - } + functions: { + 'squareRoot': function (c, value) { + return Math.sqrt(value.numberValue()); + } + } }); ``` @@ -49,13 +49,13 @@ Example usage: ```js var evaluator = xpath.parse('math:squareRoot(10)'); var aboutPi = evaluator.evaluateNumber({ - functions: function (name, namespace) { + functions: function (name, namespace) { if (name === 'squareRoot' && namespace === 'http://sample.org/math/') { - return function (c, value) { - return Math.sqrt(value.numberValue()); - }; + return function (c, value) { + return Math.sqrt(value.numberValue()); + }; } - }, + }, namespaces: { math: 'http://sample.org/math/' } @@ -72,14 +72,14 @@ Example usage: ```js var evaluator = xpath.parse('math:squareRoot(10)'); var aboutPi = evaluator.evaluateNumber({ - functions: { + functions: { getFunction: function (name, namespace) { if (name === 'squareRoot' && namespace === 'http://sample.org/math/') { - return function (c, value) { - return Math.sqrt(value.numberValue()); - }; + return function (c, value) { + return Math.sqrt(value.numberValue()); + }; } - } + } }, namespaces: { math: 'http://sample.org/math/' diff --git a/node_modules/xpath/package.json b/node_modules/xpath/package.json index 8afde7d..ea8e2b2 100644 --- a/node_modules/xpath/package.json +++ b/node_modules/xpath/package.json @@ -1,35 +1,13 @@ { - "_from": "xpath", - "_id": "xpath@0.0.27", - "_inBundle": false, - "_integrity": "sha512-fg03WRxtkCV6ohClePNAECYsmpKKTv5L8y/X3Dn1hQrec3POx2jHZ/0P2qQ6HvsrU1BmeqXcof3NGGueG6LxwQ==", - "_location": "/xpath", - "_phantomChildren": {}, - "_requested": { - "type": "tag", - "registry": true, - "raw": "xpath", - "name": "xpath", - "escapedName": "xpath", - "rawSpec": "", - "saveSpec": null, - "fetchSpec": "latest" + "name": "xpath", + "version": "0.0.32", + "description": "DOM 3 XPath implemention and helper for node.js.", + "engines": { + "node": ">=0.6.0" }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/xpath/-/xpath-0.0.27.tgz", - "_shasum": "dd3421fbdcc5646ac32c48531b4d7e9d0c2cfa92", - "_spec": "xpath", - "_where": "C:\\MyTools\\projects\\get-xml-info", "author": { "name": "Cameron McCormack" }, - "bugs": { - "url": "https://github.com/goto100/xpath/issues" - }, - "bundleDependencies": false, "contributors": [ { "name": "goto100" @@ -39,30 +17,21 @@ } ], "dependencies": {}, - "deprecated": false, - "description": "DOM 3 XPath implemention and helper for node.js.", "devDependencies": { - "nodeunit": ">=0.6.4", "xmldom": "^0.1.19" }, - "engines": { - "node": ">=0.6.0" + "typings": "./xpath.d.ts", + "scripts": { + "test": "mocha" }, - "homepage": "https://github.com/goto100/xpath#readme", + "repository": { + "type": "git", + "url": "https://github.com/goto100/xpath.git" + }, + "main": "./xpath.js", "keywords": [ "xpath", "xml" ], - "license": "MIT", - "main": "./xpath.js", - "name": "xpath", - "repository": { - "type": "git", - "url": "git+https://github.com/goto100/xpath.git" - }, - "scripts": { - "test": "nodeunit test.js" - }, - "typings": "./xpath.d.ts", - "version": "0.0.27" + "license": "MIT" } diff --git a/node_modules/xpath/test.js b/node_modules/xpath/test.js index b7f81a4..76d4ca5 100644 --- a/node_modules/xpath/test.js +++ b/node_modules/xpath/test.js @@ -1,1092 +1,1050 @@ -var xpath = require('./xpath.js') -, dom = require('xmldom').DOMParser -, assert = require('assert'); +const xpath = require('./xpath.js'); +const dom = require('xmldom').DOMParser; +const assert = require('assert'); var xhtmlNs = 'http://www.w3.org/1999/xhtml'; -module.exports = { - 'api': function(test) { - assert.ok(xpath.evaluate, 'evaluate api ok.'); - assert.ok(xpath.select, 'select api ok.'); - assert.ok(xpath.parse, 'parse api ok.'); - test.done(); - }, - - 'evaluate': function(test) { - var xml = 'Harry Potter'; - var doc = new dom().parseFromString(xml); - var nodes = xpath.evaluate('//title', doc, null, xpath.XPathResult.ANY_TYPE, null).nodes; - assert.equal('title', nodes[0].localName); - assert.equal('Harry Potter', nodes[0].firstChild.data); - assert.equal('Harry Potter', nodes[0].toString()); - test.done(); - }, - - 'select': function(test) { - var xml = 'Harry Potter'; - var doc = new dom().parseFromString(xml); - var nodes = xpath.select('//title', doc); - assert.equal('title', nodes[0].localName); - assert.equal('Harry Potter', nodes[0].firstChild.data); - assert.equal('Harry Potter', nodes[0].toString()); - - var nodes2 = xpath.select('//node()', doc); - assert.equal(7, nodes2.length); - - var pis = xpath.select("/processing-instruction('series')", doc); - assert.equal(2, pis.length); - assert.equal('books="7"', pis[1].data); - - test.done(); - }, - - 'select single node': function(test) { - var xml = 'Harry Potter'; - var doc = new dom().parseFromString(xml); - - assert.equal('title', xpath.select('//title[1]', doc)[0].localName); - - test.done(); - }, - - 'select text node': function (test) { - var xml = 'HarryPotter'; - var doc = new dom().parseFromString(xml); - - assert.deepEqual('book', xpath.select('local-name(/book)', doc)); - assert.deepEqual('Harry,Potter', xpath.select('//title/text()', doc).toString()); - - test.done(); - }, - - 'select number value': function(test) { - var xml = 'HarryPotter'; - var doc = new dom().parseFromString(xml); - - assert.deepEqual(2, xpath.select('count(//title)', doc)); - - test.done(); - }, - - 'select xpath with namespaces': function (test) { - var xml = 'Harry Potter'; - var doc = new dom().parseFromString(xml); - - var nodes = xpath.select('//*[local-name(.)="title" and namespace-uri(.)="myns"]', doc); - assert.equal('title', nodes[0].localName); - assert.equal('myns', nodes[0].namespaceURI) ; - - var nodes2 = xpath.select('/*/title', doc); - - assert.equal(0, nodes2.length); - - test.done(); - }, - - 'select xpath with namespaces, using a resolver': function (test) { - var xml = 'NarniaHarry PotterJKR'; - var doc = new dom().parseFromString(xml); - - var resolver = { - mappings: { - 'testns': 'http://example.com/test' - }, - lookupNamespaceURI: function(prefix) { - return this.mappings[prefix]; - } - } - - var nodes = xpath.selectWithResolver('//testns:title/text()', doc, resolver); - assert.equal('Harry Potter', xpath.selectWithResolver('//testns:title/text()', doc, resolver)[0].nodeValue); - assert.equal('JKR', xpath.selectWithResolver('//testns:field[@testns:type="author"]/text()', doc, resolver)[0].nodeValue); - - var nodes2 = xpath.selectWithResolver('/*/testns:*', doc, resolver); - - assert.equal(2, nodes2.length); - - test.done(); - }, - - 'select xpath with default namespace, using a resolver': function (test) { - var xml = 'Harry PotterJKR'; - var doc = new dom().parseFromString(xml); - - var resolver = { - mappings: { - 'testns': 'http://example.com/test' - }, - lookupNamespaceURI: function(prefix) { - return this.mappings[prefix]; - } - } - - var nodes = xpath.selectWithResolver('//testns:title/text()', doc, resolver); - assert.equal('Harry Potter', xpath.selectWithResolver('//testns:title/text()', doc, resolver)[0].nodeValue); - assert.equal('JKR', xpath.selectWithResolver('//testns:field[@type="author"]/text()', doc, resolver)[0].nodeValue); - - test.done(); - }, - - 'select xpath with namespaces, prefixes different in xml and xpath, using a resolver': function (test) { - var xml = 'Harry PotterJKR'; - var doc = new dom().parseFromString(xml); - - var resolver = { - mappings: { - 'ns': 'http://example.com/test' - }, - lookupNamespaceURI: function(prefix) { - return this.mappings[prefix]; - } - } - - var nodes = xpath.selectWithResolver('//ns:title/text()', doc, resolver); - assert.equal('Harry Potter', xpath.selectWithResolver('//ns:title/text()', doc, resolver)[0].nodeValue); - assert.equal('JKR', xpath.selectWithResolver('//ns:field[@ns:type="author"]/text()', doc, resolver)[0].nodeValue); - - test.done(); - }, - - 'select xpath with namespaces, using namespace mappings': function (test) { - var xml = 'Harry PotterJKR'; - var doc = new dom().parseFromString(xml); - var select = xpath.useNamespaces({'testns': 'http://example.com/test'}); - - assert.equal('Harry Potter', select('//testns:title/text()', doc)[0].nodeValue); - assert.equal('JKR', select('//testns:field[@testns:type="author"]/text()', doc)[0].nodeValue); - - test.done(); - }, - - - 'select attribute': function (test) { - var xml = ''; - var doc = new dom().parseFromString(xml); - - var author = xpath.select1('/author/@name', doc).value; - assert.equal('J. K. Rowling', author); - - test.done(); - } - - ,'select with multiple predicates': function (test) { - var xml = ''; - var doc = new dom().parseFromString(xml); - - var characters = xpath.select('/*/character[@sex = "M"][@age > 40]/@name', doc); - - assert.equal(1, characters.length); - assert.equal('Snape', characters[0].textContent); - - test.done(); - } - - // https://github.com/goto100/xpath/issues/37 - ,'select multiple attributes': function (test) { - var xml = ''; - var doc = new dom().parseFromString(xml); - - var authors = xpath.select('/authors/author/@name', doc); - assert.equal(2, authors.length); - assert.equal('J. K. Rowling', authors[0].value); - - // https://github.com/goto100/xpath/issues/41 - doc = new dom().parseFromString(''); - var nodes = xpath.select("/chapters/chapter/@v", doc); - var values = nodes.map(function(n) { return n.value; }); - - assert.equal(3, values.length); - assert.equal("1", values[0]); - assert.equal("2", values[1]); - assert.equal("3", values[2]); - - test.done(); - } - - ,'XPathException acts like Error': function (test) { - try { - xpath.evaluate('1', null, null, null); - assert.fail(null, null, 'evaluate() should throw exception'); - } catch (e) { - assert.ok('code' in e, 'must have a code'); - assert.ok('stack' in e, 'must have a stack'); - } - - test.done(); - }, - - 'string() with no arguments': function (test) { - var doc = new dom().parseFromString('Harry Potter'); - - var rootElement = xpath.select1('/book', doc); - assert.ok(rootElement, 'rootElement is null'); - - assert.equal('Harry Potter', xpath.select1('string()', doc)); - - test.done(); - }, - - 'string value of document fragment': function (test) { - var doc = new dom().parseFromString(''); - var docFragment = doc.createDocumentFragment(); - - var el = doc.createElement("book"); - docFragment.appendChild(el); - - var testValue = "Harry Potter"; - - el.appendChild(doc.createTextNode(testValue)); - - assert.equal(testValue, xpath.select1("string()", docFragment)); - - test.done(); - }, - - 'compare string of a number with a number': function (test) { - assert.ok(xpath.select1('"000" = 0'), '000'); - assert.ok(xpath.select1('"45.0" = 45'), '45'); - - test.done(); - }, - - 'string(boolean) is a string': function (test) { - assert.equal('string', typeof xpath.select1('string(true())')); - assert.equal('string', typeof xpath.select1('string(false())')); - assert.equal('string', typeof xpath.select1('string(1 = 2)')); - assert.ok(xpath.select1('"true" = string(true())'), '"true" = string(true())'); - - test.done(); - }, - - 'string should downcast to boolean': function (test) { - assert.equal(false, xpath.select1('"false" = false()'), '"false" = false()'); - assert.equal(true, xpath.select1('"a" = true()'), '"a" = true()'); - assert.equal(true, xpath.select1('"" = false()'), '"" = false()'); - - test.done(); - }, - - 'string(number) is a string': function (test) { - assert.equal('string', typeof xpath.select1('string(45)')); - assert.ok(xpath.select1('"45" = string(45)'), '"45" = string(45)'); - - test.done(); - }, - - 'correct string to number conversion': function (test) { - assert.equal(45.2, xpath.select1('number("45.200")')); - assert.equal(55.0, xpath.select1('number("000055")')); - assert.equal(65.0, xpath.select1('number(" 65 ")')); - - assert.equal(true, xpath.select1('"" != 0'), '"" != 0'); - assert.equal(false, xpath.select1('"" = 0'), '"" = 0'); - assert.equal(false, xpath.select1('0 = ""'), '0 = ""'); - assert.equal(false, xpath.select1('0 = " "'), '0 = " "'); - - assert.ok(Number.isNaN(xpath.select('number("")')), 'number("")'); - assert.ok(Number.isNaN(xpath.select('number("45.8g")')), 'number("45.8g")'); - assert.ok(Number.isNaN(xpath.select('number("2e9")')), 'number("2e9")'); - assert.ok(Number.isNaN(xpath.select('number("+33")')), 'number("+33")'); - - test.done(); - } - - ,'correct number to string conversion': function (test) { - assert.equal('0.0000000000000000000000005250000000000001', xpath.parse('0.525 div 1000000 div 1000000 div 1000000 div 1000000').evaluateString()); - assert.equal('525000000000000000000000', xpath.parse('0.525 * 1000000 * 1000000 * 1000000 * 1000000').evaluateString()); - - test.done(); - } - - ,'local-name() and name() of processing instruction': function (test) { - var xml = 'Harry Potter'; - var doc = new dom().parseFromString(xml); - var expectedName = 'book-record'; - var localName = xpath.select('local-name(/processing-instruction())', doc); - var name = xpath.select('name(/processing-instruction())', doc); - - assert.deepEqual(expectedName, localName, 'local-name() - "' + expectedName + '" !== "' + localName + '"'); - assert.deepEqual(expectedName, name, 'name() - "' + expectedName + '" !== "' + name + '"'); - - test.done(); - }, - - 'evaluate substring-after': function (test) { - var xml = 'Hermione'; - var doc = new dom().parseFromString(xml); - - var part = xpath.select('substring-after(/classmate, "Her")', doc); - assert.deepEqual('mione', part); - - test.done(); - } - - ,'parsed expression with no options': function (test) { - var parsed = xpath.parse('5 + 7'); - - assert.equal(typeof parsed, "object", "parse() should return an object"); - assert.equal(typeof parsed.evaluate, "function", "parsed.evaluate should be a function"); - assert.equal(typeof parsed.evaluateNumber, "function", "parsed.evaluateNumber should be a function"); - - assert.equal(parsed.evaluateNumber(), 12); - - // evaluating twice should yield the same result - assert.equal(parsed.evaluateNumber(), 12); - - test.done(); - } - - ,'select1() on parsed expression': function (test) { - var xml = 'Harry Potter'; - var doc = new dom().parseFromString(xml); - var parsed = xpath.parse('/*/title'); - - assert.equal(typeof parsed, 'object', 'parse() should return an object'); - - assert.equal(typeof parsed.select1, 'function', 'parsed.select1 should be a function'); - - var single = parsed.select1({ node: doc }); - - assert.equal('title', single.localName); - assert.equal('Harry Potter', single.firstChild.data); - assert.equal('Harry Potter', single.toString()); - - test.done(); - } - - ,'select() on parsed expression': function (test) { - var xml = 'Harry Potter'; - var doc = new dom().parseFromString(xml); - var parsed = xpath.parse('/*/title'); - - assert.equal(typeof parsed, 'object', 'parse() should return an object'); - - assert.equal(typeof parsed.select, 'function', 'parsed.select should be a function'); - - var nodes = parsed.select({ node: doc }); - - assert.ok(nodes, 'parsed.select() should return a value'); - assert.equal(1, nodes.length); - assert.equal('title', nodes[0].localName); - assert.equal('Harry Potter', nodes[0].firstChild.data); - assert.equal('Harry Potter', nodes[0].toString()); - - test.done(); - } - - ,'evaluateString(), and evaluateNumber() on parsed expression with node': function (test) { - var xml = 'Harry Potter7'; - var doc = new dom().parseFromString(xml); - var parsed = xpath.parse('/*/numVolumes'); - - assert.equal(typeof parsed, 'object', 'parse() should return an object'); - - assert.equal(typeof parsed.evaluateString, 'function', 'parsed.evaluateString should be a function'); - assert.equal('7', parsed.evaluateString({ node: doc })); - - assert.equal(typeof parsed.evaluateBoolean, 'function', 'parsed.evaluateBoolean should be a function'); - assert.equal(true, parsed.evaluateBoolean({ node: doc })); - - assert.equal(typeof parsed.evaluateNumber, 'function', 'parsed.evaluateNumber should be a function'); - assert.equal(7, parsed.evaluateNumber({ node: doc })); - - test.done(); - } - - ,'evaluateBoolean() on parsed empty node set and boolean expressions': function (test) { - var xml = 'Harry Potter'; - var doc = new dom().parseFromString(xml); - var context = { node: doc }; - - function evaluate(path) { - return xpath.parse(path).evaluateBoolean({ node: doc }); - } - - assert.equal(false, evaluate('/*/myrtle'), 'boolean value of empty node set should be false'); - - assert.equal(true, evaluate('not(/*/myrtle)'), 'not() of empty nodeset should be true'); - - assert.equal(true, evaluate('/*/title'), 'boolean value of non-empty nodeset should be true'); - - assert.equal(true, evaluate('/*/title = "Harry Potter"'), 'title equals Harry Potter'); - - assert.equal(false, evaluate('/*/title != "Harry Potter"'), 'title != Harry Potter should be false'); - - assert.equal(false, evaluate('/*/title = "Percy Jackson"'), 'title should not equal Percy Jackson'); - - test.done(); - } - - ,'namespaces with parsed expression': function (test) { - var xml = '' + - 'QuirrellFluffy' + - 'MyrtleTom Riddle' + - ''; - var doc = new dom().parseFromString(xml); - - var expr = xpath.parse('/characters/c:character'); - var countExpr = xpath.parse('count(/characters/c:character)'); - var csns = 'http://chamber-secrets.com'; - - function resolve(prefix) { - if (prefix === 'c') { - return csns; +describe('xpath', () => { + describe('api', () => { + it('should contain the correct methods', () => { + assert.ok(xpath.evaluate, 'evaluate api ok.'); + assert.ok(xpath.select, 'select api ok.'); + assert.ok(xpath.parse, 'parse api ok.'); + }); + + it('should support .evaluate()', () => { + var xml = 'Harry Potter'; + var doc = new dom().parseFromString(xml); + var nodes = xpath.evaluate('//title', doc, null, xpath.XPathResult.ANY_TYPE, null).nodes; + + assert.strictEqual('title', nodes[0].localName); + assert.strictEqual('Harry Potter', nodes[0].firstChild.data); + assert.strictEqual('Harry Potter', nodes[0].toString()); + }); + + it('should support .select()', () => { + var xml = 'Harry Potter'; + var doc = new dom().parseFromString(xml); + var nodes = xpath.select('//title', doc); + assert.strictEqual('title', nodes[0].localName); + assert.strictEqual('Harry Potter', nodes[0].firstChild.data); + assert.strictEqual('Harry Potter', nodes[0].toString()); + + var nodes2 = xpath.select('//node()', doc); + assert.strictEqual(7, nodes2.length); + + var pis = xpath.select("/processing-instruction('series')", doc); + assert.strictEqual(2, pis.length); + assert.strictEqual('books="7"', pis[1].data); + }); + }); + + describe('parsing', () => { + it('should detect unterminated string literals', () => { + function testUnterminated(path) { + assert.throws(function () { + xpath.evaluate('"hello'); + }, function (err) { + return err.message.indexOf('Unterminated') !== -1; + }); } - } - - function testContext(context, description) { - try { - var value = expr.evaluateString(context); - var count = countExpr.evaluateNumber(context); - - assert.equal('Myrtle', value, description + ' - string value - ' + value); - assert.equal(2, count, description + ' map - count - ' + count); - } catch(e) { - e.message = description + ': ' + (e.message || ''); - throw e; + + testUnterminated('"Hello'); + testUnterminated("'Hello"); + testUnterminated('self::text() = "\""'); + testUnterminated('"\""'); + }); + }); + + describe('.select()', () => { + it('should select single nodes', () => { + var xml = 'Harry Potter'; + var doc = new dom().parseFromString(xml); + + assert.strictEqual('title', xpath.select('//title[1]', doc)[0].localName); + }); + + it('should select text nodes', () => { + var xml = 'HarryPotter'; + var doc = new dom().parseFromString(xml); + + assert.deepEqual('book', xpath.select('local-name(/book)', doc)); + assert.deepEqual('Harry,Potter', xpath.select('//title/text()', doc).toString()); + }); + + it('should select number values', () => { + var xml = 'HarryPotter'; + var doc = new dom().parseFromString(xml); + + assert.deepEqual(2, xpath.select('count(//title)', doc)); + }); + + it('should select with namespaces', () => { + var xml = 'Harry Potter'; + var doc = new dom().parseFromString(xml); + + var nodes = xpath.select('//*[local-name(.)="title" and namespace-uri(.)="myns"]', doc); + assert.strictEqual('title', nodes[0].localName); + assert.strictEqual('myns', nodes[0].namespaceURI); + + var nodes2 = xpath.select('/*/title', doc); + + assert.strictEqual(0, nodes2.length); + }); + + it('should select with namespaces, using a resolver', () => { + var xml = 'NarniaHarry PotterJKR'; + var doc = new dom().parseFromString(xml); + + var resolver = { + mappings: { + 'testns': 'http://example.com/test' + }, + lookupNamespaceURI: function (prefix) { + return this.mappings[prefix]; + } + }; + + var nodes = xpath.selectWithResolver('//testns:title/text()', doc, resolver); + assert.strictEqual('Harry Potter', nodes[0].nodeValue); + + assert.strictEqual('JKR', xpath.selectWithResolver('//testns:field[@testns:type="author"]/text()', doc, resolver)[0].nodeValue); + + var nodes2 = xpath.selectWithResolver('/*/testns:*', doc, resolver); + + assert.strictEqual(2, nodes2.length); + }); + + it('should select from xml with a default namespace, using a resolver', () => { + var xml = 'Harry PotterJKR'; + var doc = new dom().parseFromString(xml); + + var resolver = { + mappings: { + 'testns': 'http://example.com/test' + }, + lookupNamespaceURI: function (prefix) { + return this.mappings[prefix]; + } } - } - - testContext({ - node: doc, - namespaces: { - c: csns + + var nodes = xpath.selectWithResolver('//testns:title/text()', doc, resolver); + assert.strictEqual('Harry Potter', xpath.selectWithResolver('//testns:title/text()', doc, resolver)[0].nodeValue); + assert.strictEqual('JKR', xpath.selectWithResolver('//testns:field[@type="author"]/text()', doc, resolver)[0].nodeValue); + }); + + it('should select with namespaces, prefixes different in xml and xpath, using a resolver', () => { + var xml = 'Harry PotterJKR'; + var doc = new dom().parseFromString(xml); + + var resolver = { + mappings: { + 'ns': 'http://example.com/test' + }, + lookupNamespaceURI: function (prefix) { + return this.mappings[prefix]; + } } - }, 'Namespace map'); - - testContext({ - node: doc, - namespaces: resolve - }, 'Namespace function'); - - testContext({ - node: doc, - namespaces: { - getNamespace: resolve + + var nodes = xpath.selectWithResolver('//ns:title/text()', doc, resolver); + assert.strictEqual('Harry Potter', nodes[0].nodeValue); + + assert.strictEqual('JKR', xpath.selectWithResolver('//ns:field[@ns:type="author"]/text()', doc, resolver)[0].nodeValue); + }); + + it('should select with namespaces, using namespace mappings', () => { + var xml = 'Harry PotterJKR'; + var doc = new dom().parseFromString(xml); + var select = xpath.useNamespaces({ 'testns': 'http://example.com/test' }); + + assert.strictEqual('Harry Potter', select('//testns:title/text()', doc)[0].nodeValue); + assert.strictEqual('JKR', select('//testns:field[@testns:type="author"]/text()', doc)[0].nodeValue); + }); + + it('should select attributes', () => { + var xml = ''; + var doc = new dom().parseFromString(xml); + + var author = xpath.select1('/author/@name', doc).value; + assert.strictEqual('J. K. Rowling', author); + }); + }); + + describe('selection', () => { + it('should select with multiple predicates', () => { + var xml = ''; + var doc = new dom().parseFromString(xml); + + var characters = xpath.select('/*/character[@sex = "M"][@age > 40]/@name', doc); + + assert.strictEqual(1, characters.length); + assert.strictEqual('Snape', characters[0].textContent); + }); + + // https://github.com/goto100/xpath/issues/37 + it('should select multiple attributes', () => { + var xml = ''; + var doc = new dom().parseFromString(xml); + + var authors = xpath.select('/authors/author/@name', doc); + assert.strictEqual(2, authors.length); + assert.strictEqual('J. K. Rowling', authors[0].value); + + // https://github.com/goto100/xpath/issues/41 + doc = new dom().parseFromString(''); + var nodes = xpath.select("/chapters/chapter/@v", doc); + var values = nodes.map(function (n) { return n.value; }); + + assert.strictEqual(3, values.length); + assert.strictEqual("1", values[0]); + assert.strictEqual("2", values[1]); + assert.strictEqual("3", values[2]); + }); + + it('should compare string values of numbers with numbers', () => { + assert.ok(xpath.select1('"000" = 0'), '000'); + assert.ok(xpath.select1('"45.0" = 45'), '45'); + }); + + it('should correctly compare strings with booleans', () => { + // string should downcast to boolean + assert.strictEqual(false, xpath.select1('"false" = false()'), '"false" = false()'); + assert.strictEqual(true, xpath.select1('"a" = true()'), '"a" = true()'); + assert.strictEqual(true, xpath.select1('"" = false()'), '"" = false()'); + }); + + it('should evaluate local-name() and name() on processing instructions', () => { + var xml = 'Harry Potter'; + var doc = new dom().parseFromString(xml); + var expectedName = 'book-record'; + var localName = xpath.select('local-name(/processing-instruction())', doc); + var name = xpath.select('name(/processing-instruction())', doc); + + assert.deepEqual(expectedName, localName, 'local-name() - "' + expectedName + '" !== "' + localName + '"'); + assert.deepEqual(expectedName, name, 'name() - "' + expectedName + '" !== "' + name + '"'); + }); + + it('should support substring-after()', () => { + var xml = 'Hermione'; + var doc = new dom().parseFromString(xml); + + var part = xpath.select('substring-after(/classmate, "Her")', doc); + assert.deepEqual('mione', part); + }); + + it('should support preceding:: on document fragments', () => { + var doc = new dom().parseFromString(''), + df = doc.createDocumentFragment(), + root = doc.createElement('book'); + + df.appendChild(root); + + for (var i = 0; i < 10; i += 1) { + root.appendChild(doc.createElement('chapter')); } - }, 'Namespace object'); - - test.done(); - } - - ,'custom functions': function (test) { - var xml = 'Harry Potter'; - var doc = new dom().parseFromString(xml); - - var parsed = xpath.parse('concat(double(/*/title), " is cool")'); - - function doubleString(context, value) { - assert.equal(2, arguments.length); - var str = value.stringValue(); - return str + str; - } - - function functions(name, namespace) { - if(name === 'double') { - return doubleString; + + var chapter = xpath.select1("book/chapter[5]", df); + + assert.ok(chapter, 'chapter'); + + assert.strictEqual(xpath.select("count(preceding::chapter)", chapter), 4); + }); + + it('should allow getting sorted and unsorted arrays from nodesets', () => { + const doc = new dom().parseFromString('HarryRonHermione'); + const path = xpath.parse("/*/*[3] | /*/*[2] | /*/*[1]"); + const nset = path.evaluateNodeSet({ node: doc }); + const sorted = nset.toArray(); + const unsorted = nset.toUnsortedArray(); + + assert.strictEqual(sorted.length, 3); + assert.strictEqual(unsorted.length, 3); + + assert.strictEqual(sorted[0].textContent, 'Harry'); + assert.strictEqual(sorted[1].textContent, 'Ron'); + assert.strictEqual(sorted[2].textContent, 'Hermione'); + + assert.notEqual(sorted[0], unsorted[0], "first nodeset element equal"); + }); + + it('should compare nodesets to nodesets (=)', () => { + var xml = '' + + 'HarryHermione' + + 'DracoCrabbe' + + 'LunaCho' + + '' + + 'HermioneLuna'; + + var doc = new dom().parseFromString(xml); + var houses = xpath.parse('/school/houses/house[student = /school/honorStudents/student]').select({ node: doc }); + + assert.strictEqual(houses.length, 2); + + var houseNames = houses.map(function (node) { return node.getAttribute('name'); }).sort(); + + assert.strictEqual(houseNames[0], 'Gryffindor'); + assert.strictEqual(houseNames[1], 'Ravenclaw'); + }); + + it('should compare nodesets to nodesets (>=)', () => { + var xml = '' + + 'HarryHermione' + + 'GoyleCrabbe' + + 'LunaCho' + + '' + + 'DADACharms' + + ''; + + var doc = new dom().parseFromString(xml); + var houses = xpath.parse('/school/houses/house[student/@level >= /school/courses/course/@minLevel]').select({ node: doc }); + + assert.strictEqual(houses.length, 2); + + var houseNames = houses.map(function (node) { return node.getAttribute('name'); }).sort(); + + assert.strictEqual(houseNames[0], 'Gryffindor'); + assert.strictEqual(houseNames[1], 'Ravenclaw'); + }); + + it('should support various inequality expressions on nodesets', () => { + var xml = ""; + var doc = new dom().parseFromString(xml); + + var options = { node: doc, variables: { theNumber: 3, theString: '3', theBoolean: true } }; + + var numberPaths = [ + '/books/book[$theNumber <= @num]', + '/books/book[$theNumber < @num]', + '/books/book[$theNumber >= @num]', + '/books/book[$theNumber > @num]' + ]; + + var stringPaths = [ + '/books/book[$theString <= @num]', + '/books/book[$theString < @num]', + '/books/book[$theString >= @num]', + '/books/book[$theString > @num]' + ]; + + var booleanPaths = [ + '/books/book[$theBoolean <= @num]', + '/books/book[$theBoolean < @num]', + '/books/book[$theBoolean >= @num]', + '/books/book[$theBoolean > @num]' + ]; + + var lhsPaths = [ + '/books/book[@num <= $theNumber]', + '/books/book[@num < $theNumber]' + ]; + + function countNodes(paths) { + return paths + .map(xpath.parse) + .map(function (path) { return path.select(options) }) + .map(function (arr) { return arr.length; }); } - return null; - } - - function testContext(context, description) { - try{ - var actual = parsed.evaluateString(context); - var expected = 'Harry PotterHarry Potter is cool'; - assert.equal(expected, actual, description + ' - ' + expected + ' != ' + actual); - } catch (e) { - e.message = description + ": " + (e.message || ''); - throw e; + + assert.deepEqual(countNodes(numberPaths), [5, 4, 3, 2], 'numbers'); + assert.deepEqual(countNodes(stringPaths), [5, 4, 3, 2], 'strings'); + assert.deepEqual(countNodes(booleanPaths), [7, 6, 1, 0], 'numbers'); + assert.deepEqual(countNodes(lhsPaths), [3, 2], 'lhs'); + }); + + it('should correctly evaluate context position', () => { + var doc = new dom().parseFromString("The boy who livedThe vanishing glassThe worst birthdayDobby's warningThe burrow"); + + var chapters = xpath.parse('/books/book/chapter[2]').select({ node: doc }); + + assert.strictEqual(2, chapters.length); + assert.strictEqual('The vanishing glass', chapters[0].textContent); + assert.strictEqual("Dobby's warning", chapters[1].textContent); + + var lastChapters = xpath.parse('/books/book/chapter[last()]').select({ node: doc }); + + assert.strictEqual(2, lastChapters.length); + assert.strictEqual('The vanishing glass', lastChapters[0].textContent); + assert.strictEqual("The burrow", lastChapters[1].textContent); + + var secondChapter = xpath.parse('(/books/book/chapter)[2]').select({ node: doc }); + + assert.strictEqual(1, secondChapter.length); + assert.strictEqual('The vanishing glass', chapters[0].textContent); + + var lastChapter = xpath.parse('(/books/book/chapter)[last()]').select({ node: doc }); + + assert.strictEqual(1, lastChapter.length); + assert.strictEqual("The burrow", lastChapter[0].textContent); + }); + }); + + describe('string()', () => { + it('should work with no arguments', () => { + var doc = new dom().parseFromString('Harry Potter'); + + var rootElement = xpath.select1('/book', doc); + assert.ok(rootElement, 'rootElement is null'); + + assert.strictEqual('Harry Potter', xpath.select1('string()', doc)); + }); + + it('should work on document fragments', () => { + var doc = new dom().parseFromString(''); + var docFragment = doc.createDocumentFragment(); + + var el = doc.createElement("book"); + docFragment.appendChild(el); + + var testValue = "Harry Potter"; + + el.appendChild(doc.createTextNode(testValue)); + + assert.strictEqual(testValue, xpath.select1("string()", docFragment)); + }); + + it('should work correctly on boolean values', () => { + assert.strictEqual('string', typeof xpath.select1('string(true())')); + assert.strictEqual('string', typeof xpath.select1('string(false())')); + assert.strictEqual('string', typeof xpath.select1('string(1 = 2)')); + assert.ok(xpath.select1('"true" = string(true())'), '"true" = string(true())'); + }); + + it('should work correctly on numbers', () => { + assert.strictEqual('string', typeof xpath.select1('string(45)')); + assert.ok(xpath.select1('"45" = string(45)'), '"45" = string(45)'); + }); + }); + + describe('type conversion', () => { + it('should convert strings to numbers correctly', () => { + assert.strictEqual(45.2, xpath.select1('number("45.200")')); + assert.strictEqual(55.0, xpath.select1('number("000055")')); + assert.strictEqual(65.0, xpath.select1('number(" 65 ")')); + + assert.strictEqual(true, xpath.select1('"" != 0'), '"" != 0'); + assert.strictEqual(false, xpath.select1('"" = 0'), '"" = 0'); + assert.strictEqual(false, xpath.select1('0 = ""'), '0 = ""'); + assert.strictEqual(false, xpath.select1('0 = " "'), '0 = " "'); + + assert.ok(Number.isNaN(xpath.select('number("")')), 'number("")'); + assert.ok(Number.isNaN(xpath.select('number("45.8g")')), 'number("45.8g")'); + assert.ok(Number.isNaN(xpath.select('number("2e9")')), 'number("2e9")'); + assert.ok(Number.isNaN(xpath.select('number("+33")')), 'number("+33")'); + }); + + it('should convert numbers to strings correctly', () => { + assert.strictEqual('0.0000000000000000000000005250000000000001', xpath.parse('0.525 div 1000000 div 1000000 div 1000000 div 1000000').evaluateString()); + assert.strictEqual('525000000000000000000000', xpath.parse('0.525 * 1000000 * 1000000 * 1000000 * 1000000').evaluateString()); + }); + + it('should provide correct string value for cdata sections', () => { + const xml = "Ron "; + const doc = new dom().parseFromString(xml); + + const person1 = xpath.parse("/people/person").evaluateString({ node: doc }); + const person2 = xpath.parse("/people/person/text()").evaluateString({ node: doc }); + const person3 = xpath.select("string(/people/person/text())", doc); + const person4 = xpath.parse("/people/person[2]").evaluateString({ node: doc }); + + assert.strictEqual(person1, 'Harry Potter'); + assert.strictEqual(person2, 'Harry Potter'); + assert.strictEqual(person3, 'Harry Potter'); + assert.strictEqual(person4, 'Ron Weasley'); + }); + + it('should convert various node types to string values', () => { + var xml = "<![CDATA[Harry Potter & the Philosopher's Stone]]>Harry Potter", + doc = new dom().parseFromString(xml), + allText = xpath.parse('.').evaluateString({ node: doc }), + ns = xpath.parse('*/namespace::*[name() = "hp"]').evaluateString({ node: doc }), + title = xpath.parse('*/title').evaluateString({ node: doc }), + child = xpath.parse('*/*').evaluateString({ node: doc }), + titleLang = xpath.parse('*/*/@lang').evaluateString({ node: doc }), + pi = xpath.parse('*/processing-instruction()').evaluateString({ node: doc }), + comment = xpath.parse('*/comment()').evaluateString({ node: doc }); + + assert.strictEqual(allText, "Harry Potter & the Philosopher's StoneHarry Potter"); + assert.strictEqual(ns, 'http://harry'); + assert.strictEqual(title, "Harry Potter & the Philosopher's Stone"); + assert.strictEqual(child, "Harry Potter & the Philosopher's Stone"); + assert.strictEqual(titleLang, 'en'); + assert.strictEqual(pi.trim(), "name='J.K. Rowling'"); + assert.strictEqual(comment, ' This describes the Harry Potter Book '); + }); + + it('should convert booleans to numbers correctly', () => { + var num = xpath.parse('"a" = "b"').evaluateNumber(); + + assert.strictEqual(num, 0); + + var str = xpath.select('substring("expelliarmus", 1, "a" = "a")'); + + assert.strictEqual(str, 'e'); + }); + }); + + describe('parsed expressions', () => { + it('should work with no options', () => { + var parsed = xpath.parse('5 + 7'); + + assert.strictEqual(typeof parsed, "object", "parse() should return an object"); + assert.strictEqual(typeof parsed.evaluate, "function", "parsed.evaluate should be a function"); + assert.strictEqual(typeof parsed.evaluateNumber, "function", "parsed.evaluateNumber should be a function"); + + assert.strictEqual(parsed.evaluateNumber(), 12); + + // evaluating twice should yield the same result + assert.strictEqual(parsed.evaluateNumber(), 12); + }); + + it('should support select1()', () => { + var xml = 'Harry Potter'; + var doc = new dom().parseFromString(xml); + var parsed = xpath.parse('/*/title'); + + assert.strictEqual(typeof parsed, 'object', 'parse() should return an object'); + + assert.strictEqual(typeof parsed.select1, 'function', 'parsed.select1 should be a function'); + + var single = parsed.select1({ node: doc }); + + assert.strictEqual('title', single.localName); + assert.strictEqual('Harry Potter', single.firstChild.data); + assert.strictEqual('Harry Potter', single.toString()); + }); + + it('should support select()', () => { + var xml = 'Harry Potter'; + var doc = new dom().parseFromString(xml); + var parsed = xpath.parse('/*/title'); + + assert.strictEqual(typeof parsed, 'object', 'parse() should return an object'); + + assert.strictEqual(typeof parsed.select, 'function', 'parsed.select should be a function'); + + var nodes = parsed.select({ node: doc }); + + assert.ok(nodes, 'parsed.select() should return a value'); + assert.strictEqual(1, nodes.length); + assert.strictEqual('title', nodes[0].localName); + assert.strictEqual('Harry Potter', nodes[0].firstChild.data); + assert.strictEqual('Harry Potter', nodes[0].toString()); + }); + + it('should support .evaluateString() and .evaluateNumber()', () => { + var xml = 'Harry Potter7'; + var doc = new dom().parseFromString(xml); + var parsed = xpath.parse('/*/numVolumes'); + + assert.strictEqual(typeof parsed, 'object', 'parse() should return an object'); + + assert.strictEqual(typeof parsed.evaluateString, 'function', 'parsed.evaluateString should be a function'); + assert.strictEqual('7', parsed.evaluateString({ node: doc })); + + assert.strictEqual(typeof parsed.evaluateBoolean, 'function', 'parsed.evaluateBoolean should be a function'); + assert.strictEqual(true, parsed.evaluateBoolean({ node: doc })); + + assert.strictEqual(typeof parsed.evaluateNumber, 'function', 'parsed.evaluateNumber should be a function'); + assert.strictEqual(7, parsed.evaluateNumber({ node: doc })); + }); + + it('should support .evaluateBoolean()', () => { + var xml = 'Harry Potter'; + var doc = new dom().parseFromString(xml); + var context = { node: doc }; + + function evaluate(path) { + return xpath.parse(path).evaluateBoolean(context); } - } - - testContext({ - node: doc, - functions: functions - }, 'Functions function'); - - testContext({ - node: doc, - functions: { - getFunction: functions + + assert.strictEqual(false, evaluate('/*/myrtle'), 'boolean value of empty node set should be false'); + + assert.strictEqual(true, evaluate('not(/*/myrtle)'), 'not() of empty nodeset should be true'); + + assert.strictEqual(true, evaluate('/*/title'), 'boolean value of non-empty nodeset should be true'); + + assert.strictEqual(true, evaluate('/*/title = "Harry Potter"'), 'title equals Harry Potter'); + + assert.strictEqual(false, evaluate('/*/title != "Harry Potter"'), 'title != Harry Potter should be false'); + + assert.strictEqual(false, evaluate('/*/title = "Percy Jackson"'), 'title should not equal Percy Jackson'); + }); + + it('should support namespaces', () => { + var xml = '' + + 'QuirrellFluffy' + + 'MyrtleTom Riddle' + + ''; + var doc = new dom().parseFromString(xml); + + var expr = xpath.parse('/characters/c:character'); + var countExpr = xpath.parse('count(/characters/c:character)'); + var csns = 'http://chamber-secrets.com'; + + function resolve(prefix) { + if (prefix === 'c') { + return csns; + } } - }, 'Functions object'); - - testContext({ - node: doc, - functions: { - double: doubleString + + function testContext(context, description) { + try { + var value = expr.evaluateString(context); + var count = countExpr.evaluateNumber(context); + + assert.strictEqual('Myrtle', value, description + ' - string value - ' + value); + assert.strictEqual(2, count, description + ' map - count - ' + count); + } catch (e) { + e.message = description + ': ' + (e.message || ''); + throw e; + } } - }, 'Functions map'); - - test.done(); - } - - ,'custom function namespaces': function (test) { - var xml = 'Harry PotterRonHermioneNeville'; - var doc = new dom().parseFromString(xml); - - var parsed = xpath.parse('concat(hp:double(/*/title), " is 2 cool ", hp:square(2), " school")'); - var hpns = 'http://harry-potter.com'; - - var namespaces = { - hp: hpns - }; - - var context = { - node: doc, - namespaces: { - hp: hpns - }, - functions: function (name, namespace) { - if (namespace === hpns) { - switch (name) { - case "double": - return function (context, value) { - assert.equal(2, arguments.length); - var str = value.stringValue(); - return str + str; - }; - case "square": - return function (context, value) { - var num = value.numberValue(); - return num * num; - }; - - case "xor": - return function (context, l, r) { - assert.equal(3, arguments.length); - var lbool = l.booleanValue(); - var rbool = r.booleanValue(); - return (lbool || rbool) && !(lbool && rbool); - }; - - case "second": - return function (context, nodes) { - var nodesArr = nodes.toArray(); - var second = nodesArr[1]; - return second ? [second] : []; - }; - } + + testContext({ + node: doc, + namespaces: { + c: csns + } + }, 'Namespace map'); + + testContext({ + node: doc, + namespaces: resolve + }, 'Namespace function'); + + testContext({ + node: doc, + namespaces: { + getNamespace: resolve + } + }, 'Namespace object'); + }); + + it('should support custom functions', () => { + var xml = 'Harry Potter'; + var doc = new dom().parseFromString(xml); + + var parsed = xpath.parse('concat(double(/*/title), " is cool")'); + + function doubleString(context, value) { + assert.strictEqual(2, arguments.length); + var str = value.stringValue(); + return str + str; + } + + function functions(name, namespace) { + if (name === 'double') { + return doubleString; } return null; } - }; - - assert.equal('Harry PotterHarry Potter is 2 cool 4 school', parsed.evaluateString(context)); - - assert.equal(false, xpath.parse('hp:xor(false(), false())').evaluateBoolean(context)); - assert.equal(true, xpath.parse('hp:xor(false(), true())').evaluateBoolean(context)); - assert.equal(true, xpath.parse('hp:xor(true(), false())').evaluateBoolean(context)); - assert.equal(false, xpath.parse('hp:xor(true(), true())').evaluateBoolean(context)); - - assert.equal('Hermione', xpath.parse('hp:second(/*/friend)').evaluateString(context)); - assert.equal(1, xpath.parse('count(hp:second(/*/friend))').evaluateNumber(context)); - assert.equal(0, xpath.parse('count(hp:second(/*/friendz))').evaluateNumber(context)); - - test.done(); - } - - ,'xpath variables': function (test) { - var xml = 'Harry Potter7'; - var doc = new dom().parseFromString(xml); - - var variables = { - title: 'Harry Potter', - notTitle: 'Percy Jackson', - houses: 4 - }; - - function variableFunction(name) { - return variables[name]; - } - - function testContext(context, description) { - try{ - assert.equal(true, xpath.parse('$title = /*/title').evaluateBoolean(context)); - assert.equal(false, xpath.parse('$notTitle = /*/title').evaluateBoolean(context)); - assert.equal(11, xpath.parse('$houses + /*/volumes').evaluateNumber(context)); - } catch (e) { - e.message = description + ": " + (e.message || ''); - throw e; + + function testContext(context, description) { + try { + var actual = parsed.evaluateString(context); + var expected = 'Harry PotterHarry Potter is cool'; + assert.strictEqual(expected, actual, description + ' - ' + expected + ' != ' + actual); + } catch (e) { + e.message = description + ": " + (e.message || ''); + throw e; + } } - } - testContext({ - node: doc, - variables: variableFunction - }, 'Variables function'); + testContext({ + node: doc, + functions: functions + }, 'Functions function'); - testContext({ - node: doc, - variables: { - getVariable: variableFunction - } - }, 'Variables object'); - - testContext({ - node: doc, - variables: variables - }, 'Variables map'); - - test.done(); - } - - ,'xpath variable namespaces': function (test) { - var xml = 'Harry Potter7'; - var doc = new dom().parseFromString(xml); - var hpns = 'http://harry-potter.com'; - - var context = { - node: doc, - namespaces: { + testContext({ + node: doc, + functions: { + getFunction: functions + } + }, 'Functions object'); + + testContext({ + node: doc, + functions: { + double: doubleString + } + }, 'Functions map'); + }); + + it('should support custom functions in namespaces', () => { + var xml = 'Harry PotterRonHermioneNeville'; + var doc = new dom().parseFromString(xml); + + var parsed = xpath.parse('concat(hp:double(/*/title), " is 2 cool ", hp:square(2), " school")'); + var hpns = 'http://harry-potter.com'; + + var namespaces = { hp: hpns - }, - variables: function(name, namespace) { - if (namespace === hpns) { - switch (name) { - case 'title': return 'Harry Potter'; - case 'houses': return 4; - case 'false': return false; - case 'falseStr': return 'false'; - } - } else if (namespace === '') { - switch (name) { - case 'title': return 'World'; + }; + + var context = { + node: doc, + namespaces: { + hp: hpns + }, + functions: function (name, namespace) { + if (namespace === hpns) { + switch (name) { + case "double": + return function (context, value) { + assert.strictEqual(2, arguments.length); + var str = value.stringValue(); + return str + str; + }; + case "square": + return function (context, value) { + var num = value.numberValue(); + return num * num; + }; + + case "xor": + return function (context, l, r) { + assert.strictEqual(3, arguments.length); + var lbool = l.booleanValue(); + var rbool = r.booleanValue(); + return (lbool || rbool) && !(lbool && rbool); + }; + + case "second": + return function (context, nodes) { + var nodesArr = nodes.toArray(); + var second = nodesArr[1]; + return second ? [second] : []; + }; + } } + return null; + } + }; + + assert.strictEqual('Harry PotterHarry Potter is 2 cool 4 school', parsed.evaluateString(context)); + + assert.strictEqual(false, xpath.parse('hp:xor(false(), false())').evaluateBoolean(context)); + assert.strictEqual(true, xpath.parse('hp:xor(false(), true())').evaluateBoolean(context)); + assert.strictEqual(true, xpath.parse('hp:xor(true(), false())').evaluateBoolean(context)); + assert.strictEqual(false, xpath.parse('hp:xor(true(), true())').evaluateBoolean(context)); + + assert.strictEqual('Hermione', xpath.parse('hp:second(/*/friend)').evaluateString(context)); + assert.strictEqual(1, xpath.parse('count(hp:second(/*/friend))').evaluateNumber(context)); + assert.strictEqual(0, xpath.parse('count(hp:second(/*/friendz))').evaluateNumber(context)); + }); + + it('should support xpath variables', () => { + var xml = 'Harry Potter7'; + var doc = new dom().parseFromString(xml); + + var variables = { + title: 'Harry Potter', + notTitle: 'Percy Jackson', + houses: 4 + }; + + function variableFunction(name) { + return variables[name]; + } + + function testContext(context, description) { + try { + assert.strictEqual(true, xpath.parse('$title = /*/title').evaluateBoolean(context)); + assert.strictEqual(false, xpath.parse('$notTitle = /*/title').evaluateBoolean(context)); + assert.strictEqual(11, xpath.parse('$houses + /*/volumes').evaluateNumber(context)); + } catch (e) { + e.message = description + ": " + (e.message || ''); + throw e; } - - return null; } - }; - - assert.equal(true, xpath.parse('$hp:title = /*/title').evaluateBoolean(context)); - assert.equal(false, xpath.parse('$title = /*/title').evaluateBoolean(context)); - assert.equal('World', xpath.parse('$title').evaluateString(context)); - assert.equal(false, xpath.parse('$hp:false').evaluateBoolean(context)); - assert.notEqual(false, xpath.parse('$hp:falseStr').evaluateBoolean(context)); - assert.throws(function () { - xpath.parse('$hp:hello').evaluateString(context); - }, function (err) { - return err.message === 'Undeclared variable: $hp:hello'; + + testContext({ + node: doc, + variables: variableFunction + }, 'Variables function'); + + testContext({ + node: doc, + variables: { + getVariable: variableFunction + } + }, 'Variables object'); + + testContext({ + node: doc, + variables: variables + }, 'Variables map'); + }); - - test.done(); - } - ,"detect unterminated string literals": function (test) { - function testUnterminated(path) { + it('should support variables with namespaces', () => { + var xml = 'Harry Potter7'; + var doc = new dom().parseFromString(xml); + var hpns = 'http://harry-potter.com'; + + var context = { + node: doc, + namespaces: { + hp: hpns + }, + variables: function (name, namespace) { + if (namespace === hpns) { + switch (name) { + case 'title': return 'Harry Potter'; + case 'houses': return 4; + case 'false': return false; + case 'falseStr': return 'false'; + } + } else if (namespace === '') { + switch (name) { + case 'title': return 'World'; + } + } + + return null; + } + }; + + assert.strictEqual(true, xpath.parse('$hp:title = /*/title').evaluateBoolean(context)); + assert.strictEqual(false, xpath.parse('$title = /*/title').evaluateBoolean(context)); + assert.strictEqual('World', xpath.parse('$title').evaluateString(context)); + assert.strictEqual(false, xpath.parse('$hp:false').evaluateBoolean(context)); + assert.notEqual(false, xpath.parse('$hp:falseStr').evaluateBoolean(context)); assert.throws(function () { - xpath.evaluate('"hello'); + xpath.parse('$hp:hello').evaluateString(context); }, function (err) { - return err.message.indexOf('Unterminated') !== -1; + return err.message === 'Undeclared variable: $hp:hello'; }); - } - - testUnterminated('"Hello'); - testUnterminated("'Hello"); - testUnterminated('self::text() = "\""'); - testUnterminated('"\""'); - - test.done(); - } - - ,"string value for CDATA sections": function (test) { - var xml = "Ron ", - doc = new dom().parseFromString(xml), - person1 = xpath.parse("/people/person").evaluateString({ node: doc }), - person2 = xpath.parse("/people/person/text()").evaluateString({ node: doc }), - person3 = xpath.select("string(/people/person/text())", doc); - person4 = xpath.parse("/people/person[2]").evaluateString({ node: doc }); - - assert.equal(person1, 'Harry Potter'); - assert.equal(person2, 'Harry Potter'); - assert.equal(person3, 'Harry Potter'); - assert.equal(person4, 'Ron Weasley'); - - test.done(); - } - - ,"string value of various node types": function (test) { - var xml = "<![CDATA[Harry Potter & the Philosopher's Stone]]>Harry Potter", - doc = new dom().parseFromString(xml), - allText = xpath.parse('.').evaluateString({ node: doc }), - ns = xpath.parse('*/namespace::*[name() = "hp"]').evaluateString({ node: doc }), - title = xpath.parse('*/title').evaluateString({ node: doc }), - child = xpath.parse('*/*').evaluateString({ node: doc }), - titleLang = xpath.parse('*/*/@lang').evaluateString({ node: doc }), - pi = xpath.parse('*/processing-instruction()').evaluateString({ node: doc }), - comment = xpath.parse('*/comment()').evaluateString({ node: doc }); - - assert.equal(allText, "Harry Potter & the Philosopher's StoneHarry Potter"); - assert.equal(ns, 'http://harry'); - assert.equal(title, "Harry Potter & the Philosopher's Stone"); - assert.equal(child, "Harry Potter & the Philosopher's Stone"); - assert.equal(titleLang, 'en'); - assert.equal(pi.trim(), "name='J.K. Rowling'"); - assert.equal(comment, ' This describes the Harry Potter Book '); - - test.done(); - } - - ,"exposes custom types": function (test) { - assert.ok(xpath.XPath, "xpath.XPath"); - assert.ok(xpath.XPathParser, "xpath.XPathParser"); - assert.ok(xpath.XPathResult, "xpath.XPathResult"); - - assert.ok(xpath.Step, "xpath.Step"); - assert.ok(xpath.NodeTest, "xpath.NodeTest"); - assert.ok(xpath.BarOperation, "xpath.BarOperation"); - - assert.ok(xpath.NamespaceResolver, "xpath.NamespaceResolver"); - assert.ok(xpath.FunctionResolver, "xpath.FunctionResolver"); - assert.ok(xpath.VariableResolver, "xpath.VariableResolver"); - - assert.ok(xpath.Utilities, "xpath.Utilities"); - - assert.ok(xpath.XPathContext, "xpath.XPathContext"); - assert.ok(xpath.XNodeSet, "xpath.XNodeSet"); - assert.ok(xpath.XBoolean, "xpath.XBoolean"); - assert.ok(xpath.XString, "xpath.XString"); - assert.ok(xpath.XNumber, "xpath.XNumber"); - - test.done(); - } - - ,"work with nodes created using DOM1 createElement()": function (test) { - var doc = new dom().parseFromString(''); - - doc.documentElement.appendChild(doc.createElement('characters')); - - assert.ok(xpath.select1('/book/characters', doc)); - - assert.equal(xpath.select1('local-name(/book/characters)', doc), 'characters'); - - test.done(); - } - - ,"preceding:: axis works on document fragments": function (test) { - var doc = new dom().parseFromString(''), - df = doc.createDocumentFragment(), - root = doc.createElement('book'); - - df.appendChild(root); - - for (var i = 0; i < 10; i += 1) { - root.appendChild(doc.createElement('chapter')); - } - - var chapter = xpath.select1("book/chapter[5]", df); - - assert.ok(chapter, 'chapter'); - - assert.equal(xpath.select("count(preceding::chapter)", chapter), 4); - - test.done(); - } - - ,"node set sorted and unsorted arrays": function (test) { - var doc = new dom().parseFromString('HarryRonHermione'), - path = xpath.parse("/*/*[3] | /*/*[2] | /*/*[1]") - nset = path.evaluateNodeSet({ node: doc }), - sorted = nset.toArray(), - unsorted = nset.toUnsortedArray(); - - assert.equal(sorted.length, 3); - assert.equal(unsorted.length, 3); - - assert.equal(sorted[0].textContent, 'Harry'); - assert.equal(sorted[1].textContent, 'Ron'); - assert.equal(sorted[2].textContent, 'Hermione'); - - assert.notEqual(sorted[0], unsorted[0], "first nodeset element equal"); - - test.done(); - } - - ,'meaningful error for invalid function': function(test) { - var path = xpath.parse('invalidFunc()'); - - assert.throws(function () { - path.evaluateString(); - }, function (err) { - return err.message.indexOf('invalidFunc') !== -1; }); - - var path2 = xpath.parse('funcs:invalidFunc()'); - - assert.throws(function () { - path2.evaluateString({ - namespaces: { - funcs: 'myfunctions' - } + + it('should support .toString()', () => { + var parser = new xpath.XPathParser(); + + var simpleStep = parser.parse('my:book'); + + assert.strictEqual(simpleStep.toString(), 'child::my:book'); + + var precedingSib = parser.parse('preceding-sibling::my:chapter'); + + assert.strictEqual(precedingSib.toString(), 'preceding-sibling::my:chapter'); + + var withPredicates = parser.parse('book[number > 3][contains(title, "and the")]'); + + assert.strictEqual(withPredicates.toString(), "child::book[(child::number > 3)][contains(child::title, 'and the')]"); + + var parenthesisWithPredicate = parser.parse('(/books/book/chapter)[7]'); + + assert.strictEqual(parenthesisWithPredicate.toString(), '(/child::books/child::book/child::chapter)[7]'); + + var charactersOver20 = parser.parse('heroes[age > 20] | villains[age > 20]'); + + assert.strictEqual(charactersOver20.toString(), 'child::heroes[(child::age > 20)] | child::villains[(child::age > 20)]'); + }); + }); + + describe('html-mode support', () => { + it('should allow null namespaces for nodes with no prefix', () => { + var markup = ` + + +

Hi Ron!

+ Hi Draco!

+

Hi Hermione!

+ + `; + + var docHtml = new dom().parseFromString(markup, 'text/html'); + + var noPrefixPath = xpath.parse('/html/body/p[2]'); + + var greetings1 = noPrefixPath.select({ node: docHtml, allowAnyNamespaceForNoPrefix: false }); + + assert.strictEqual(0, greetings1.length); + + var allowAnyNamespaceOptions = { node: docHtml, allowAnyNamespaceForNoPrefix: true }; + + // if allowAnyNamespaceForNoPrefix specified, allow using prefix-less node tests to match nodes with no prefix + var greetings2 = noPrefixPath.select(allowAnyNamespaceOptions); + + assert.strictEqual(1, greetings2.length); + assert.strictEqual('Hi Hermione!', greetings2[0].textContent); + + var allGreetings = xpath.parse('/html/body/p').select(allowAnyNamespaceOptions); + + assert.strictEqual(2, allGreetings.length); + + var nsm = { html: xhtmlNs, other: 'http://www.example.com/other' }; + + var prefixPath = xpath.parse('/html:html/body/html:p'); + var optionsWithNamespaces = { node: docHtml, allowAnyNamespaceForNoPrefix: true, namespaces: nsm }; + + // if the path uses prefixes, they have to match + var greetings3 = prefixPath.select(optionsWithNamespaces); + + assert.strictEqual(2, greetings3.length); + + var badPrefixPath = xpath.parse('/html:html/other:body/html:p'); + + var greetings4 = badPrefixPath.select(optionsWithNamespaces); + + assert.strictEqual(0, greetings4.length); + }); + + it('should support the isHtml option', () => { + var markup = '

Hi Ron!

Hi Draco!

Hi Hermione!

'; + var docHtml = new dom().parseFromString(markup, 'text/html'); + + var ns = { h: xhtmlNs }; + + // allow matching on unprefixed nodes + var greetings1 = xpath.parse('/html/body/p').select({ node: docHtml, isHtml: true }); + + assert.strictEqual(2, greetings1.length); + + // allow case insensitive match + var greetings2 = xpath.parse('/h:html/h:bOdY/h:p').select({ node: docHtml, namespaces: ns, isHtml: true }); + + assert.strictEqual(2, greetings2.length); + + // non-html mode: allow select if case and namespaces match + var greetings3 = xpath.parse('/h:html/h:body/h:p').select({ node: docHtml, namespaces: ns }); + + assert.strictEqual(2, greetings3.length); + + // non-html mode: require namespaces + var greetings4 = xpath.parse('/html/body/p').select({ node: docHtml, namespaces: ns }); + + assert.strictEqual(0, greetings4.length); + + // non-html mode: require case to match + var greetings5 = xpath.parse('/h:html/h:bOdY/h:p').select({ node: docHtml, namespaces: ns }); + + assert.strictEqual(0, greetings5.length); + }); + }); + + describe('functions', () => { + it('should provide a meaningful error for invalid functions', () => { + var path = xpath.parse('invalidFunc()'); + + assert.throws(function () { + path.evaluateString(); + }, function (err) { + return err.message.indexOf('invalidFunc') !== -1; }); - }, function (err) { - return err.message.indexOf('invalidFunc') !== -1; + + var path2 = xpath.parse('funcs:invalidFunc()'); + + assert.throws(function () { + path2.evaluateString({ + namespaces: { + funcs: 'myfunctions' + } + }); + }, function (err) { + return err.message.indexOf('invalidFunc') !== -1; + }); + }); + + // https://github.com/goto100/xpath/issues/32 + it('should support the contains() function on attributes', () => { + var doc = new dom().parseFromString(""), + andTheBooks = xpath.select("/books/book[contains(@title, ' ')]", doc), + secretBooks = xpath.select("/books/book[contains(@title, 'Secrets')]", doc); + + assert.strictEqual(andTheBooks.length, 2); + assert.strictEqual(secretBooks.length, 1); + }); + + it('should support builtin functions', () => { + var translated = xpath.parse('translate("hello", "lhho", "yHb")').evaluateString(); + + assert.strictEqual('Heyy', translated); + + var characters = new dom().parseFromString('HarryRonHermione'); + + var firstTwo = xpath.parse('/characters/character[position() <= 2]').select({ node: characters }); + + assert.strictEqual(2, firstTwo.length); + assert.strictEqual('Harry', firstTwo[0].textContent); + assert.strictEqual('Ron', firstTwo[1].textContent); + + var last = xpath.parse('/characters/character[last()]').select({ node: characters }); + + assert.strictEqual(1, last.length); + assert.strictEqual('Hermione', last[0].textContent); }); + }); + + describe('.parse()', () => { + it('should correctly set types on path steps', () => { + const parsed = xpath.parse('./my:*/my:name'); + + const steps = parsed.expression.expression.locationPath.steps; + + const step0 = steps[0]; + + assert.strictEqual(xpath.NodeTest.NODE, step0.nodeTest.type); + + const step1 = steps[1]; + + assert.strictEqual(xpath.NodeTest.NAMETESTPREFIXANY, step1.nodeTest.type); + assert.strictEqual('my', step1.nodeTest.prefix); + + const step2 = steps[2]; - test.done(); - } - - // https://github.com/goto100/xpath/issues/32 - ,'supports contains() function on attributes': function (test) { - var doc = new dom().parseFromString(""), - andTheBooks = xpath.select("/books/book[contains(@title, ' ')]", doc), - secretBooks = xpath.select("/books/book[contains(@title, 'Secrets')]", doc); - - assert.equal(andTheBooks.length, 2); - assert.equal(secretBooks.length, 1); - - test.done(); - } - - ,'compare multiple nodes to multiple nodes (equals)': function (test) { - var xml = '' + - 'HarryHermione' + - 'DracoCrabbe' + - 'LunaCho' + - '' + - 'HermioneLuna'; - - var doc = new dom().parseFromString(xml); - var houses = xpath.parse('/school/houses/house[student = /school/honorStudents/student]').select({ node: doc }); - - assert.equal(houses.length, 2); - - var houseNames = houses.map(function (node) { return node.getAttribute('name'); }).sort(); - - assert.equal(houseNames[0], 'Gryffindor'); - assert.equal(houseNames[1], 'Ravenclaw'); - - test.done(); - } - - ,'compare multiple nodes to multiple nodes (gte)': function (test) { - var xml = '' + - 'HarryHermione' + - 'GoyleCrabbe' + - 'LunaCho' + - '' + - 'DADACharms' + - ''; - - var doc = new dom().parseFromString(xml); - var houses = xpath.parse('/school/houses/house[student/@level >= /school/courses/course/@minLevel]').select({ node: doc }); - - assert.equal(houses.length, 2); - - var houseNames = houses.map(function (node) { return node.getAttribute('name'); }).sort(); - - assert.equal(houseNames[0], 'Gryffindor'); - assert.equal(houseNames[1], 'Ravenclaw'); - - test.done(); - } - - ,'inequality comparisons with nodesets': function (test) { - var xml = ""; - var doc = new dom().parseFromString(xml); - - var options = { node: doc, variables: { theNumber: 3, theString: '3', theBoolean: true }}; - - var numberPaths = [ - '/books/book[$theNumber <= @num]', - '/books/book[$theNumber < @num]', - '/books/book[$theNumber >= @num]', - '/books/book[$theNumber > @num]' - ]; - - var stringPaths = [ - '/books/book[$theString <= @num]', - '/books/book[$theString < @num]', - '/books/book[$theString >= @num]', - '/books/book[$theString > @num]' - ]; - - var booleanPaths = [ - '/books/book[$theBoolean <= @num]', - '/books/book[$theBoolean < @num]', - '/books/book[$theBoolean >= @num]', - '/books/book[$theBoolean > @num]' - ]; - - var lhsPaths = [ - '/books/book[@num <= $theNumber]', - '/books/book[@num < $theNumber]' - ]; - - function countNodes(paths){ - return paths - .map(xpath.parse) - .map(function (path) { return path.select(options) }) - .map(function (arr) { return arr.length; }); - } - - assert.deepEqual(countNodes(numberPaths), [5, 4, 3, 2], 'numbers'); - assert.deepEqual(countNodes(stringPaths), [5, 4, 3, 2], 'strings'); - assert.deepEqual(countNodes(booleanPaths), [7, 6, 1, 0], 'numbers'); - assert.deepEqual(countNodes(lhsPaths), [3, 2], 'lhs'); - - test.done(); - } - - ,'error when evaluating boolean as number': function (test) { - var num = xpath.parse('"a" = "b"').evaluateNumber(); - - assert.equal(num, 0); - - var str = xpath.select('substring("expelliarmus", 1, "a" = "a")'); - - assert.equal(str, 'e'); - - test.done(); - } - - ,'string values of parsed expressions': function (test) { - var parser = new xpath.XPathParser(); - - var simpleStep = parser.parse('my:book'); - - assert.equal(simpleStep.toString(), 'child::my:book'); - - var precedingSib = parser.parse('preceding-sibling::my:chapter'); - - assert.equal(precedingSib.toString(), 'preceding-sibling::my:chapter'); - - var withPredicates = parser.parse('book[number > 3][contains(title, "and the")]'); - - assert.equal(withPredicates.toString(), "child::book[(child::number > 3)][contains(child::title, 'and the')]"); - - var parenthesisWithPredicate = parser.parse('(/books/book/chapter)[7]'); - - assert.equal(parenthesisWithPredicate.toString(), '(/child::books/child::book/child::chapter)[7]'); - - var charactersOver20 = parser.parse('heroes[age > 20] | villains[age > 20]'); - - assert.equal(charactersOver20.toString(), 'child::heroes[(child::age > 20)] | child::villains[(child::age > 20)]'); - - test.done(); - } - - ,'context position should work correctly': function (test) { - var doc = new dom().parseFromString("The boy who livedThe vanishing glassThe worst birthdayDobby's warningThe burrow"); - - var chapters = xpath.parse('/books/book/chapter[2]').select({ node: doc }); - - assert.equal(2, chapters.length); - assert.equal('The vanishing glass', chapters[0].textContent); - assert.equal("Dobby's warning", chapters[1].textContent); - - var lastChapters = xpath.parse('/books/book/chapter[last()]').select({ node: doc }); - - assert.equal(2, lastChapters.length); - assert.equal('The vanishing glass', lastChapters[0].textContent); - assert.equal("The burrow", lastChapters[1].textContent); - - var secondChapter = xpath.parse('(/books/book/chapter)[2]').select({ node: doc }); - - assert.equal(1, secondChapter.length); - assert.equal('The vanishing glass', chapters[0].textContent); - - var lastChapter = xpath.parse('(/books/book/chapter)[last()]').select({ node: doc }); - - assert.equal(1, lastChapter.length); - assert.equal("The burrow", lastChapter[0].textContent); - - - test.done(); - } - - ,'should allow null namespaces for null prefixes': function (test) { - var markup = '

Hi Ron!

Hi Draco!

Hi Hermione!

'; - var docHtml = new dom().parseFromString(markup, 'text/html'); - - var noPrefixPath = xpath.parse('/html/body/p[2]'); - - var greetings1 = noPrefixPath.select({ node: docHtml, allowAnyNamespaceForNoPrefix: false }); - - assert.equal(0, greetings1.length); - - var allowAnyNamespaceOptions = { node: docHtml, allowAnyNamespaceForNoPrefix: true }; - - // if allowAnyNamespaceForNoPrefix specified, allow using prefix-less node tests to match nodes with no prefix - var greetings2 = noPrefixPath.select(allowAnyNamespaceOptions); - - assert.equal(1, greetings2.length); - assert.equal('Hi Hermione!', greetings2[0].textContent); - - var allGreetings = xpath.parse('/html/body/p').select(allowAnyNamespaceOptions); - - assert.equal(2, allGreetings.length); - - var nsm = { html: xhtmlNs, other: 'http://www.example.com/other' }; - - var prefixPath = xpath.parse('/html:html/body/html:p'); - var optionsWithNamespaces = { node: docHtml, allowAnyNamespaceForNoPrefix: true, namespaces: nsm }; - - // if the path uses prefixes, they have to match - var greetings3 = prefixPath.select(optionsWithNamespaces); - - assert.equal(2, greetings3.length); - - var badPrefixPath = xpath.parse('/html:html/other:body/html:p'); - - var greetings4 = badPrefixPath.select(optionsWithNamespaces); - - test.done(); - } - - ,'support isHtml option' : function (test){ - var markup = '

Hi Ron!

Hi Draco!

Hi Hermione!

'; - var docHtml = new dom().parseFromString(markup, 'text/html'); - - var ns = { h: xhtmlNs }; - - // allow matching on unprefixed nodes - var greetings1 = xpath.parse('/html/body/p').select({ node: docHtml, isHtml: true }); - - assert.equal(2, greetings1.length); - - // allow case insensitive match - var greetings2 = xpath.parse('/h:html/h:bOdY/h:p').select({ node: docHtml, namespaces: ns, isHtml: true }); - - assert.equal(2, greetings2.length); - - // non-html mode: allow select if case and namespaces match - var greetings3 = xpath.parse('/h:html/h:body/h:p').select({ node: docHtml, namespaces: ns }); - - assert.equal(2, greetings3.length); - - // non-html mode: require namespaces - var greetings4 = xpath.parse('/html/body/p').select({ node: docHtml, namespaces: ns }); - - assert.equal(0, greetings4.length); - - // non-html mode: require case to match - var greetings5 = xpath.parse('/h:html/h:bOdY/h:p').select({ node: docHtml, namespaces: ns }); - - assert.equal(0, greetings5.length); - - test.done(); - } - - ,"builtin functions": function (test) { - var translated = xpath.parse('translate("hello", "lhho", "yHb")').evaluateString(); - - assert.equal('Heyy', translated); - - var characters = new dom().parseFromString('HarryRonHermione'); - - var firstTwo = xpath.parse('/characters/character[position() <= 2]').select({ node: characters }); - - assert.equal(2, firstTwo.length); - assert.equal('Harry', firstTwo[0].textContent); - assert.equal('Ron', firstTwo[1].textContent); - - var last = xpath.parse('/characters/character[last()]').select({ node: characters }); - - assert.equal(1, last.length); - assert.equal('Hermione', last[0].textContent); - - test.done(); - } -} + assert.strictEqual(xpath.NodeTest.NAMETESTQNAME, step2.nodeTest.type); + assert.strictEqual('my', step2.nodeTest.prefix); + assert.strictEqual('name', step2.nodeTest.localName); + assert.strictEqual('my:name', step2.nodeTest.name); + }); + }) + + describe('miscellaneous', () => { + it('should create XPathExceptions that act like Errors', () => { + try { + xpath.evaluate('1', null, null, null); + assert.fail(null, null, 'evaluate() should throw exception'); + } catch (e) { + assert.ok('code' in e, 'must have a code'); + assert.ok('stack' in e, 'must have a stack'); + } + }); + + it('should expose custom types', () => { + assert.ok(xpath.XPath, "xpath.XPath"); + assert.ok(xpath.XPathParser, "xpath.XPathParser"); + assert.ok(xpath.XPathResult, "xpath.XPathResult"); + + assert.ok(xpath.Step, "xpath.Step"); + assert.ok(xpath.NodeTest, "xpath.NodeTest"); + + assert.ok(xpath.OrOperation, "xpath.OrOperation"); + assert.ok(xpath.AndOperation, "xpath.AndOperation"); + + assert.ok(xpath.BarOperation, "xpath.BarOperation"); + + assert.ok(xpath.NamespaceResolver, "xpath.NamespaceResolver"); + assert.ok(xpath.FunctionResolver, "xpath.FunctionResolver"); + assert.ok(xpath.VariableResolver, "xpath.VariableResolver"); + + assert.ok(xpath.Utilities, "xpath.Utilities"); + + assert.ok(xpath.XPathContext, "xpath.XPathContext"); + assert.ok(xpath.XNodeSet, "xpath.XNodeSet"); + assert.ok(xpath.XBoolean, "xpath.XBoolean"); + assert.ok(xpath.XString, "xpath.XString"); + assert.ok(xpath.XNumber, "xpath.XNumber"); + }); + + it('should work with nodes created using DOM1 createElement()', () => { + var doc = new dom().parseFromString(''); + + doc.documentElement.appendChild(doc.createElement('characters')); + + assert.ok(xpath.select1('/book/characters', doc)); + + assert.strictEqual(xpath.select1('local-name(/book/characters)', doc), 'characters'); + }); + }); +}); \ No newline at end of file diff --git a/node_modules/xpath/xpath.d.ts b/node_modules/xpath/xpath.d.ts index ac95996..d774463 100644 --- a/node_modules/xpath/xpath.d.ts +++ b/node_modules/xpath/xpath.d.ts @@ -1,9 +1,11 @@ +/// + type SelectedValue = Node | Attr | string | number | boolean; interface XPathSelect { (expression: string, node?: Node): Array; - (expression: string, node: Node, single: true): SelectedValue; + (expression: string, node: Node, single: true): SelectedValue | undefined; } export var select: XPathSelect; -export function select1(expression: string, node?: Node): SelectedValue; -export function evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver, type: number, result: XPathResult): XPathResult; +export function select1(expression: string, node?: Node): SelectedValue | undefined; +export function evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver | null, type: number, result: XPathResult | null): XPathResult; export function useNamespaces(namespaceMap: { [name: string]: string }): XPathSelect; diff --git a/node_modules/xpath/xpath.js b/node_modules/xpath/xpath.js index 02732c0..e274280 100644 --- a/node_modules/xpath/xpath.js +++ b/node_modules/xpath/xpath.js @@ -14,7 +14,7 @@ * Revision 19: November 29, 2005 * Nodesets now store their nodes in a height balanced tree, increasing * performance for the common case of selecting nodes in document order, - * thanks to S閎astien Cramatte . + * thanks to Sébastien Cramatte . * AVL tree code adapted from Raimund Neumann . * * Revision 18: October 27, 2005 @@ -26,7 +26,7 @@ * Revision 17: October 25, 2005 * Some core XPath function fixes and a patch to avoid crashing certain * versions of MSXML in PathExpr.prototype.getOwnerElement, thanks to - * S閎astien Cramatte . + * Sébastien Cramatte . * * Revision 16: September 22, 2005 * Workarounds for some IE 5.5 deficiencies. @@ -98,4667 +98,4750 @@ // non-node wrapper var xpath = (typeof exports === 'undefined') ? {} : exports; -(function(exports) { -"use strict"; +(function (exports) { + "use strict"; -// functional helpers -function curry( func ) { - var slice = Array.prototype.slice, - totalargs = func.length, - partial = function( args, fn ) { - return function( ) { - return fn.apply( this, args.concat( slice.call( arguments ) ) ); + // functional helpers + function curry(func) { + var slice = Array.prototype.slice, + totalargs = func.length, + partial = function (args, fn) { + return function () { + return fn.apply(this, args.concat(slice.call(arguments))); + } + }, + fn = function () { + var args = slice.call(arguments); + return (args.length < totalargs) ? + partial(args, fn) : + func.apply(this, slice.apply(arguments, [0, totalargs])); + }; + return fn; + } + + var forEach = function (f, xs) { + for (var i = 0; i < xs.length; i += 1) { + f(xs[i], i, xs); + } + }; + + var reduce = function (f, seed, xs) { + var acc = seed; + + forEach(function (x, i) { acc = f(acc, x, i); }, xs); + + return acc; + }; + + var map = function (f, xs) { + var mapped = new Array(xs.length); + + forEach(function (x, i) { mapped[i] = f(x); }, xs); + + return mapped; + }; + + var filter = function (f, xs) { + var filtered = []; + + forEach(function (x, i) { if (f(x, i)) { filtered.push(x); } }, xs); + + return filtered; + }; + + var includes = function (values, value) { + for (var i = 0; i < values.length; i += 1) { + if (values[i] === value) { + return true; } - }, - fn = function( ) { - var args = slice.call( arguments ); - return ( args.length < totalargs ) ? - partial( args, fn ) : - func.apply( this, slice.apply( arguments, [ 0, totalargs ] ) ); + } + + return false; + }; + + function always(value) { return function () { return value; } } + + function toString(x) { return x.toString(); } + var join = function (s, xs) { return xs.join(s); }; + var wrap = function (pref, suf, str) { return pref + str + suf; }; + + var prototypeConcat = Array.prototype.concat; + + // .apply() fails above a certain number of arguments - https://github.com/goto100/xpath/pull/98 + var MAX_ARGUMENT_LENGTH = 32767; + + function flatten(arr) { + var result = []; + + for (var start = 0; start < arr.length; start += MAX_ARGUMENT_LENGTH) { + var chunk = arr.slice(start, start + MAX_ARGUMENT_LENGTH); + + result = prototypeConcat.apply(result, chunk); + } + + return result; + } + + function assign(target, varArgs) { // .length of function is 2 + var to = Object(target); + + for (var index = 1; index < arguments.length; index++) { + var nextSource = arguments[index]; + + if (nextSource != null) { // Skip over if undefined or null + for (var nextKey in nextSource) { + // Avoid bugs when hasOwnProperty is shadowed + if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { + to[nextKey] = nextSource[nextKey]; + } + } + } + } + + return to; + } + + // XPathParser /////////////////////////////////////////////////////////////// + + XPathParser.prototype = new Object(); + XPathParser.prototype.constructor = XPathParser; + XPathParser.superclass = Object.prototype; + + function XPathParser() { + this.init(); + } + + XPathParser.prototype.init = function () { + this.reduceActions = []; + + this.reduceActions[3] = function (rhs) { + return new OrOperation(rhs[0], rhs[2]); + }; + this.reduceActions[5] = function (rhs) { + return new AndOperation(rhs[0], rhs[2]); + }; + this.reduceActions[7] = function (rhs) { + return new EqualsOperation(rhs[0], rhs[2]); + }; + this.reduceActions[8] = function (rhs) { + return new NotEqualOperation(rhs[0], rhs[2]); + }; + this.reduceActions[10] = function (rhs) { + return new LessThanOperation(rhs[0], rhs[2]); + }; + this.reduceActions[11] = function (rhs) { + return new GreaterThanOperation(rhs[0], rhs[2]); + }; + this.reduceActions[12] = function (rhs) { + return new LessThanOrEqualOperation(rhs[0], rhs[2]); + }; + this.reduceActions[13] = function (rhs) { + return new GreaterThanOrEqualOperation(rhs[0], rhs[2]); + }; + this.reduceActions[15] = function (rhs) { + return new PlusOperation(rhs[0], rhs[2]); + }; + this.reduceActions[16] = function (rhs) { + return new MinusOperation(rhs[0], rhs[2]); + }; + this.reduceActions[18] = function (rhs) { + return new MultiplyOperation(rhs[0], rhs[2]); + }; + this.reduceActions[19] = function (rhs) { + return new DivOperation(rhs[0], rhs[2]); + }; + this.reduceActions[20] = function (rhs) { + return new ModOperation(rhs[0], rhs[2]); + }; + this.reduceActions[22] = function (rhs) { + return new UnaryMinusOperation(rhs[1]); + }; + this.reduceActions[24] = function (rhs) { + return new BarOperation(rhs[0], rhs[2]); + }; + this.reduceActions[25] = function (rhs) { + return new PathExpr(undefined, undefined, rhs[0]); + }; + this.reduceActions[27] = function (rhs) { + rhs[0].locationPath = rhs[2]; + return rhs[0]; + }; + this.reduceActions[28] = function (rhs) { + rhs[0].locationPath = rhs[2]; + rhs[0].locationPath.steps.unshift(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, [])); + return rhs[0]; + }; + this.reduceActions[29] = function (rhs) { + return new PathExpr(rhs[0], [], undefined); + }; + this.reduceActions[30] = function (rhs) { + if (Utilities.instance_of(rhs[0], PathExpr)) { + if (rhs[0].filterPredicates == undefined) { + rhs[0].filterPredicates = []; + } + rhs[0].filterPredicates.push(rhs[1]); + return rhs[0]; + } else { + return new PathExpr(rhs[0], [rhs[1]], undefined); + } + }; + this.reduceActions[32] = function (rhs) { + return rhs[1]; + }; + this.reduceActions[33] = function (rhs) { + return new XString(rhs[0]); + }; + this.reduceActions[34] = function (rhs) { + return new XNumber(rhs[0]); + }; + this.reduceActions[36] = function (rhs) { + return new FunctionCall(rhs[0], []); + }; + this.reduceActions[37] = function (rhs) { + return new FunctionCall(rhs[0], rhs[2]); + }; + this.reduceActions[38] = function (rhs) { + return [rhs[0]]; + }; + this.reduceActions[39] = function (rhs) { + rhs[2].unshift(rhs[0]); + return rhs[2]; + }; + this.reduceActions[43] = function (rhs) { + return new LocationPath(true, []); + }; + this.reduceActions[44] = function (rhs) { + rhs[1].absolute = true; + return rhs[1]; + }; + this.reduceActions[46] = function (rhs) { + return new LocationPath(false, [rhs[0]]); + }; + this.reduceActions[47] = function (rhs) { + rhs[0].steps.push(rhs[2]); + return rhs[0]; + }; + this.reduceActions[49] = function (rhs) { + return new Step(rhs[0], rhs[1], []); + }; + this.reduceActions[50] = function (rhs) { + return new Step(Step.CHILD, rhs[0], []); + }; + this.reduceActions[51] = function (rhs) { + return new Step(rhs[0], rhs[1], rhs[2]); + }; + this.reduceActions[52] = function (rhs) { + return new Step(Step.CHILD, rhs[0], rhs[1]); + }; + this.reduceActions[54] = function (rhs) { + return [rhs[0]]; + }; + this.reduceActions[55] = function (rhs) { + rhs[1].unshift(rhs[0]); + return rhs[1]; + }; + this.reduceActions[56] = function (rhs) { + if (rhs[0] == "ancestor") { + return Step.ANCESTOR; + } else if (rhs[0] == "ancestor-or-self") { + return Step.ANCESTORORSELF; + } else if (rhs[0] == "attribute") { + return Step.ATTRIBUTE; + } else if (rhs[0] == "child") { + return Step.CHILD; + } else if (rhs[0] == "descendant") { + return Step.DESCENDANT; + } else if (rhs[0] == "descendant-or-self") { + return Step.DESCENDANTORSELF; + } else if (rhs[0] == "following") { + return Step.FOLLOWING; + } else if (rhs[0] == "following-sibling") { + return Step.FOLLOWINGSIBLING; + } else if (rhs[0] == "namespace") { + return Step.NAMESPACE; + } else if (rhs[0] == "parent") { + return Step.PARENT; + } else if (rhs[0] == "preceding") { + return Step.PRECEDING; + } else if (rhs[0] == "preceding-sibling") { + return Step.PRECEDINGSIBLING; + } else if (rhs[0] == "self") { + return Step.SELF; + } + return -1; + }; + this.reduceActions[57] = function (rhs) { + return Step.ATTRIBUTE; + }; + this.reduceActions[59] = function (rhs) { + if (rhs[0] == "comment") { + return NodeTest.commentTest; + } else if (rhs[0] == "text") { + return NodeTest.textTest; + } else if (rhs[0] == "processing-instruction") { + return NodeTest.anyPiTest; + } else if (rhs[0] == "node") { + return NodeTest.nodeTest; + } + return new NodeTest(-1, undefined); + }; + this.reduceActions[60] = function (rhs) { + return new NodeTest.PITest(rhs[2]); + }; + this.reduceActions[61] = function (rhs) { + return rhs[1]; + }; + this.reduceActions[63] = function (rhs) { + rhs[1].absolute = true; + rhs[1].steps.unshift(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, [])); + return rhs[1]; + }; + this.reduceActions[64] = function (rhs) { + rhs[0].steps.push(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, [])); + rhs[0].steps.push(rhs[2]); + return rhs[0]; + }; + this.reduceActions[65] = function (rhs) { + return new Step(Step.SELF, NodeTest.nodeTest, []); + }; + this.reduceActions[66] = function (rhs) { + return new Step(Step.PARENT, NodeTest.nodeTest, []); + }; + this.reduceActions[67] = function (rhs) { + return new VariableReference(rhs[1]); }; - return fn; -} - -var forEach = curry(function (f, xs) { - for (var i = 0; i < xs.length; i += 1) { - f(xs[i], i, xs); - } -}); - -var reduce = curry(function (f, seed, xs) { - var acc = seed; - - forEach(function (x, i) { acc = f(acc, x, i); }, xs); - - return acc; -}); - -var map = curry(function (f, xs) { - var mapped = new Array(xs.length); - - forEach(function (x, i) { mapped[i] = f(x); }, xs); - - return mapped; -}); - -var filter = curry(function (f, xs) { - var filtered = []; - - forEach(function (x, i) { if(f(x, i)) { filtered.push(x); } }, xs); - - return filtered; -}); - -function compose() { - if (arguments.length === 0) { throw new Error('compose requires at least one argument'); } - - var funcs = Array.prototype.slice.call(arguments).reverse(); - - var f0 = funcs[0]; - var fRem = funcs.slice(1); - - return function () { - return reduce(function (acc, next) { - return next(acc); - }, f0.apply(null, arguments), fRem); - }; -} - -var includes = curry(function (values, value) { - for (var i = 0; i < values.length; i += 1) { - if (values[i] === value){ - return true; - } - } - - return false; -}); - -function always(value) { return function () { return value ;} } - -var prop = curry(function (name, obj) { return obj[name]; }); - -function toString (x) { return x.toString(); } -var join = curry(function (s, xs) { return xs.join(s); }); -var wrap = curry(function (pref, suf, str) { return pref + str + suf; }); - -function assign(target) { // .length of function is 2 - var to = Object(target); - - for (var index = 1; index < arguments.length; index++) { - var nextSource = arguments[index]; - - if (nextSource != null) { // Skip over if undefined or null - for (var nextKey in nextSource) { - // Avoid bugs when hasOwnProperty is shadowed - if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { - to[nextKey] = nextSource[nextKey]; + this.reduceActions[68] = function (rhs) { + return NodeTest.nameTestAny; + }; + this.reduceActions[69] = function (rhs) { + return new NodeTest.NameTestPrefixAny(rhs[0].split(':')[0]); + }; + this.reduceActions[70] = function (rhs) { + return new NodeTest.NameTestQName(rhs[0]); + }; + }; + + XPathParser.actionTable = [ + " s s sssssssss s ss s ss", + " s ", + "r rrrrrrrrr rrrrrrr rr r ", + " rrrrr ", + " s s sssssssss s ss s ss", + "rs rrrrrrrr s sssssrrrrrr rrs rs ", + " s s sssssssss s ss s ss", + " s ", + " s ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + " s ", + " s ", + " s s sssss s s ", + "r rrrrrrrrr rrrrrrr rr r ", + "a ", + "r s rr r ", + "r sr rr r ", + "r s rr s rr r ", + "r rssrr rss rr r ", + "r rrrrr rrrss rr r ", + "r rrrrrsss rrrrr rr r ", + "r rrrrrrrr rrrrr rr r ", + "r rrrrrrrr rrrrrs rr r ", + "r rrrrrrrr rrrrrr rr r ", + "r rrrrrrrr rrrrrr rr r ", + "r srrrrrrrr rrrrrrs rr sr ", + "r srrrrrrrr rrrrrrs rr r ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrr rrrrrr rr r ", + "r rrrrrrrr rrrrrr rr r ", + "r rrrrrrrrr rrrrrrr rr r ", + "r rrrrrrrrr rrrrrrr rr r ", + " sssss ", + "r rrrrrrrrr rrrrrrr rr sr ", + "r rrrrrrrrr rrrrrrr rr r ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + " s ", + "r srrrrrrrr rrrrrrs rr r ", + "r rrrrrrrr rrrrr rr r ", + " s ", + " s ", + " rrrrr ", + " s s sssssssss s sss s ss", + "r srrrrrrrr rrrrrrs rr r ", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss s ss s ss", + " s s sssssssss ss s ss", + " s s sssssssss s ss s ss", + " s s sssss s s ", + " s s sssss s s ", + "r rrrrrrrrr rrrrrrr rr rr ", + " s s sssss s s ", + " s s sssss s s ", + "r rrrrrrrrr rrrrrrr rr sr ", + "r rrrrrrrrr rrrrrrr rr sr ", + "r rrrrrrrrr rrrrrrr rr r ", + "r rrrrrrrrr rrrrrrr rr rr ", + " s ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + " rr ", + " s ", + " rs ", + "r sr rr r ", + "r s rr s rr r ", + "r rssrr rss rr r ", + "r rssrr rss rr r ", + "r rrrrr rrrss rr r ", + "r rrrrr rrrss rr r ", + "r rrrrr rrrss rr r ", + "r rrrrr rrrss rr r ", + "r rrrrrsss rrrrr rr r ", + "r rrrrrsss rrrrr rr r ", + "r rrrrrrrr rrrrr rr r ", + "r rrrrrrrr rrrrr rr r ", + "r rrrrrrrr rrrrr rr r ", + "r rrrrrrrr rrrrrr rr r ", + " r ", + " s ", + "r srrrrrrrr rrrrrrs rr r ", + "r srrrrrrrr rrrrrrs rr r ", + "r rrrrrrrrr rrrrrrr rr r ", + "r rrrrrrrrr rrrrrrr rr r ", + "r rrrrrrrrr rrrrrrr rr r ", + "r rrrrrrrrr rrrrrrr rr r ", + "r rrrrrrrrr rrrrrrr rr rr ", + "r rrrrrrrrr rrrrrrr rr rr ", + " s s sssssssss s ss s ss", + "r rrrrrrrrr rrrrrrr rr rr ", + " r " + ]; + + XPathParser.actionTableNumber = [ + " 1 0 /.-,+*)(' & %$ # \"!", + " J ", + "a aaaaaaaaa aaaaaaa aa a ", + " YYYYY ", + " 1 0 /.-,+*)(' & %$ # \"!", + "K1 KKKKKKKK . +*)('KKKKKK KK# K\" ", + " 1 0 /.-,+*)(' & %$ # \"!", + " N ", + " O ", + "e eeeeeeeee eeeeeee ee ee ", + "f fffffffff fffffff ff ff ", + "d ddddddddd ddddddd dd dd ", + "B BBBBBBBBB BBBBBBB BB BB ", + "A AAAAAAAAA AAAAAAA AA AA ", + " P ", + " Q ", + " 1 . +*)(' # \" ", + "b bbbbbbbbb bbbbbbb bb b ", + " ", + "! S !! ! ", + "\" T\" \"\" \" ", + "$ V $$ U $$ $ ", + "& &ZY&& &XW && & ", + ") ))))) )))\\[ )) ) ", + ". ....._^] ..... .. . ", + "1 11111111 11111 11 1 ", + "5 55555555 55555` 55 5 ", + "7 77777777 777777 77 7 ", + "9 99999999 999999 99 9 ", + ": c:::::::: ::::::b :: a: ", + "I fIIIIIIII IIIIIIe II I ", + "= ========= ======= == == ", + "? ????????? ??????? ?? ?? ", + "C CCCCCCCCC CCCCCCC CC CC ", + "J JJJJJJJJ JJJJJJ JJ J ", + "M MMMMMMMM MMMMMM MM M ", + "N NNNNNNNNN NNNNNNN NN N ", + "P PPPPPPPPP PPPPPPP PP P ", + " +*)(' ", + "R RRRRRRRRR RRRRRRR RR aR ", + "U UUUUUUUUU UUUUUUU UU U ", + "Z ZZZZZZZZZ ZZZZZZZ ZZ ZZ ", + "c ccccccccc ccccccc cc cc ", + " j ", + "L fLLLLLLLL LLLLLLe LL L ", + "6 66666666 66666 66 6 ", + " k ", + " l ", + " XXXXX ", + " 1 0 /.-,+*)(' & %$m # \"!", + "_ f________ ______e __ _ ", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 0 /.-,+*)(' %$ # \"!", + " 1 0 /.-,+*)(' & %$ # \"!", + " 1 . +*)(' # \" ", + " 1 . +*)(' # \" ", + "> >>>>>>>>> >>>>>>> >> >> ", + " 1 . +*)(' # \" ", + " 1 . +*)(' # \" ", + "Q QQQQQQQQQ QQQQQQQ QQ aQ ", + "V VVVVVVVVV VVVVVVV VV aV ", + "T TTTTTTTTT TTTTTTT TT T ", + "@ @@@@@@@@@ @@@@@@@ @@ @@ ", + " \x87 ", + "[ [[[[[[[[[ [[[[[[[ [[ [[ ", + "D DDDDDDDDD DDDDDDD DD DD ", + " HH ", + " \x88 ", + " F\x89 ", + "# T# ## # ", + "% V %% U %% % ", + "' 'ZY'' 'XW '' ' ", + "( (ZY(( (XW (( ( ", + "+ +++++ +++\\[ ++ + ", + "* ***** ***\\[ ** * ", + "- ----- ---\\[ -- - ", + ", ,,,,, ,,,\\[ ,, , ", + "0 00000_^] 00000 00 0 ", + "/ /////_^] ///// // / ", + "2 22222222 22222 22 2 ", + "3 33333333 33333 33 3 ", + "4 44444444 44444 44 4 ", + "8 88888888 888888 88 8 ", + " ^ ", + " \x8a ", + "; f;;;;;;;; ;;;;;;e ;; ; ", + "< f<<<<<<<< <<<<<?@ AB CDEFGH IJ ", + " ", + " ", + " ", + "L456789:;<=>?@ AB CDEFGH IJ ", + " M EFGH IJ ", + " N;<=>?@ AB CDEFGH IJ ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " S EFGH IJ ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " e ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " h J ", + " i j ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + "o456789:;<=>?@ ABpqCDEFGH IJ ", + " ", + " r6789:;<=>?@ AB CDEFGH IJ ", + " s789:;<=>?@ AB CDEFGH IJ ", + " t89:;<=>?@ AB CDEFGH IJ ", + " u89:;<=>?@ AB CDEFGH IJ ", + " v9:;<=>?@ AB CDEFGH IJ ", + " w9:;<=>?@ AB CDEFGH IJ ", + " x9:;<=>?@ AB CDEFGH IJ ", + " y9:;<=>?@ AB CDEFGH IJ ", + " z:;<=>?@ AB CDEFGH IJ ", + " {:;<=>?@ AB CDEFGH IJ ", + " |;<=>?@ AB CDEFGH IJ ", + " };<=>?@ AB CDEFGH IJ ", + " ~;<=>?@ AB CDEFGH IJ ", + " \x7f=>?@ AB CDEFGH IJ ", + "\x80456789:;<=>?@ AB CDEFGH IJ\x81", + " \x82 EFGH IJ ", + " \x83 EFGH IJ ", + " ", + " \x84 GH IJ ", + " \x85 GH IJ ", + " i \x86 ", + " i \x87 ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + "o456789:;<=>?@ AB\x8cqCDEFGH IJ ", + " ", + " " + ]; + + XPathParser.productions = [ + [1, 1, 2], + [2, 1, 3], + [3, 1, 4], + [3, 3, 3, -9, 4], + [4, 1, 5], + [4, 3, 4, -8, 5], + [5, 1, 6], + [5, 3, 5, -22, 6], + [5, 3, 5, -5, 6], + [6, 1, 7], + [6, 3, 6, -23, 7], + [6, 3, 6, -24, 7], + [6, 3, 6, -6, 7], + [6, 3, 6, -7, 7], + [7, 1, 8], + [7, 3, 7, -25, 8], + [7, 3, 7, -26, 8], + [8, 1, 9], + [8, 3, 8, -12, 9], + [8, 3, 8, -11, 9], + [8, 3, 8, -10, 9], + [9, 1, 10], + [9, 2, -26, 9], + [10, 1, 11], + [10, 3, 10, -27, 11], + [11, 1, 12], + [11, 1, 13], + [11, 3, 13, -28, 14], + [11, 3, 13, -4, 14], + [13, 1, 15], + [13, 2, 13, 16], + [15, 1, 17], + [15, 3, -29, 2, -30], + [15, 1, -15], + [15, 1, -16], + [15, 1, 18], + [18, 3, -13, -29, -30], + [18, 4, -13, -29, 19, -30], + [19, 1, 20], + [19, 3, 20, -31, 19], + [20, 1, 2], + [12, 1, 14], + [12, 1, 21], + [21, 1, -28], + [21, 2, -28, 14], + [21, 1, 22], + [14, 1, 23], + [14, 3, 14, -28, 23], + [14, 1, 24], + [23, 2, 25, 26], + [23, 1, 26], + [23, 3, 25, 26, 27], + [23, 2, 26, 27], + [23, 1, 28], + [27, 1, 16], + [27, 2, 16, 27], + [25, 2, -14, -3], + [25, 1, -32], + [26, 1, 29], + [26, 3, -20, -29, -30], + [26, 4, -21, -29, -15, -30], + [16, 3, -33, 30, -34], + [30, 1, 2], + [22, 2, -4, 14], + [24, 3, 14, -4, 23], + [28, 1, -35], + [28, 1, -2], + [17, 2, -36, -18], + [29, 1, -17], + [29, 1, -19], + [29, 1, -18] + ]; + + XPathParser.DOUBLEDOT = 2; + XPathParser.DOUBLECOLON = 3; + XPathParser.DOUBLESLASH = 4; + XPathParser.NOTEQUAL = 5; + XPathParser.LESSTHANOREQUAL = 6; + XPathParser.GREATERTHANOREQUAL = 7; + XPathParser.AND = 8; + XPathParser.OR = 9; + XPathParser.MOD = 10; + XPathParser.DIV = 11; + XPathParser.MULTIPLYOPERATOR = 12; + XPathParser.FUNCTIONNAME = 13; + XPathParser.AXISNAME = 14; + XPathParser.LITERAL = 15; + XPathParser.NUMBER = 16; + XPathParser.ASTERISKNAMETEST = 17; + XPathParser.QNAME = 18; + XPathParser.NCNAMECOLONASTERISK = 19; + XPathParser.NODETYPE = 20; + XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL = 21; + XPathParser.EQUALS = 22; + XPathParser.LESSTHAN = 23; + XPathParser.GREATERTHAN = 24; + XPathParser.PLUS = 25; + XPathParser.MINUS = 26; + XPathParser.BAR = 27; + XPathParser.SLASH = 28; + XPathParser.LEFTPARENTHESIS = 29; + XPathParser.RIGHTPARENTHESIS = 30; + XPathParser.COMMA = 31; + XPathParser.AT = 32; + XPathParser.LEFTBRACKET = 33; + XPathParser.RIGHTBRACKET = 34; + XPathParser.DOT = 35; + XPathParser.DOLLAR = 36; + + XPathParser.prototype.tokenize = function (s1) { + var types = []; + var values = []; + var s = s1 + '\0'; + + var pos = 0; + var c = s.charAt(pos++); + while (1) { + while (c == ' ' || c == '\t' || c == '\r' || c == '\n') { + c = s.charAt(pos++); + } + if (c == '\0' || pos >= s.length) { + break; + } + + if (c == '(') { + types.push(XPathParser.LEFTPARENTHESIS); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == ')') { + types.push(XPathParser.RIGHTPARENTHESIS); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == '[') { + types.push(XPathParser.LEFTBRACKET); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == ']') { + types.push(XPathParser.RIGHTBRACKET); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == '@') { + types.push(XPathParser.AT); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == ',') { + types.push(XPathParser.COMMA); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == '|') { + types.push(XPathParser.BAR); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == '+') { + types.push(XPathParser.PLUS); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == '-') { + types.push(XPathParser.MINUS); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == '=') { + types.push(XPathParser.EQUALS); + values.push(c); + c = s.charAt(pos++); + continue; + } + if (c == '$') { + types.push(XPathParser.DOLLAR); + values.push(c); + c = s.charAt(pos++); + continue; + } + + if (c == '.') { + c = s.charAt(pos++); + if (c == '.') { + types.push(XPathParser.DOUBLEDOT); + values.push(".."); + c = s.charAt(pos++); + continue; + } + if (c >= '0' && c <= '9') { + var number = "." + c; + c = s.charAt(pos++); + while (c >= '0' && c <= '9') { + number += c; + c = s.charAt(pos++); + } + types.push(XPathParser.NUMBER); + values.push(number); + continue; + } + types.push(XPathParser.DOT); + values.push('.'); + continue; + } + + if (c == '\'' || c == '"') { + var delimiter = c; + var literal = ""; + while (pos < s.length && (c = s.charAt(pos)) !== delimiter) { + literal += c; + pos += 1; + } + if (c !== delimiter) { + throw XPathException.fromMessage("Unterminated string literal: " + delimiter + literal); + } + pos += 1; + types.push(XPathParser.LITERAL); + values.push(literal); + c = s.charAt(pos++); + continue; + } + + if (c >= '0' && c <= '9') { + var number = c; + c = s.charAt(pos++); + while (c >= '0' && c <= '9') { + number += c; + c = s.charAt(pos++); + } + if (c == '.') { + if (s.charAt(pos) >= '0' && s.charAt(pos) <= '9') { + number += c; + number += s.charAt(pos++); + c = s.charAt(pos++); + while (c >= '0' && c <= '9') { + number += c; + c = s.charAt(pos++); + } + } + } + types.push(XPathParser.NUMBER); + values.push(number); + continue; + } + + if (c == '*') { + if (types.length > 0) { + var last = types[types.length - 1]; + if (last != XPathParser.AT + && last != XPathParser.DOUBLECOLON + && last != XPathParser.LEFTPARENTHESIS + && last != XPathParser.LEFTBRACKET + && last != XPathParser.AND + && last != XPathParser.OR + && last != XPathParser.MOD + && last != XPathParser.DIV + && last != XPathParser.MULTIPLYOPERATOR + && last != XPathParser.SLASH + && last != XPathParser.DOUBLESLASH + && last != XPathParser.BAR + && last != XPathParser.PLUS + && last != XPathParser.MINUS + && last != XPathParser.EQUALS + && last != XPathParser.NOTEQUAL + && last != XPathParser.LESSTHAN + && last != XPathParser.LESSTHANOREQUAL + && last != XPathParser.GREATERTHAN + && last != XPathParser.GREATERTHANOREQUAL) { + types.push(XPathParser.MULTIPLYOPERATOR); + values.push(c); + c = s.charAt(pos++); + continue; + } + } + types.push(XPathParser.ASTERISKNAMETEST); + values.push(c); + c = s.charAt(pos++); + continue; + } + + if (c == ':') { + if (s.charAt(pos) == ':') { + types.push(XPathParser.DOUBLECOLON); + values.push("::"); + pos++; + c = s.charAt(pos++); + continue; + } + } + + if (c == '/') { + c = s.charAt(pos++); + if (c == '/') { + types.push(XPathParser.DOUBLESLASH); + values.push("//"); + c = s.charAt(pos++); + continue; + } + types.push(XPathParser.SLASH); + values.push('/'); + continue; + } + + if (c == '!') { + if (s.charAt(pos) == '=') { + types.push(XPathParser.NOTEQUAL); + values.push("!="); + pos++; + c = s.charAt(pos++); + continue; + } + } + + if (c == '<') { + if (s.charAt(pos) == '=') { + types.push(XPathParser.LESSTHANOREQUAL); + values.push("<="); + pos++; + c = s.charAt(pos++); + continue; + } + types.push(XPathParser.LESSTHAN); + values.push('<'); + c = s.charAt(pos++); + continue; + } + + if (c == '>') { + if (s.charAt(pos) == '=') { + types.push(XPathParser.GREATERTHANOREQUAL); + values.push(">="); + pos++; + c = s.charAt(pos++); + continue; } + types.push(XPathParser.GREATERTHAN); + values.push('>'); + c = s.charAt(pos++); + continue; } + + if (c == '_' || Utilities.isLetter(c.charCodeAt(0))) { + var name = c; + c = s.charAt(pos++); + while (Utilities.isNCNameChar(c.charCodeAt(0))) { + name += c; + c = s.charAt(pos++); + } + if (types.length > 0) { + var last = types[types.length - 1]; + if (last != XPathParser.AT + && last != XPathParser.DOUBLECOLON + && last != XPathParser.LEFTPARENTHESIS + && last != XPathParser.LEFTBRACKET + && last != XPathParser.AND + && last != XPathParser.OR + && last != XPathParser.MOD + && last != XPathParser.DIV + && last != XPathParser.MULTIPLYOPERATOR + && last != XPathParser.SLASH + && last != XPathParser.DOUBLESLASH + && last != XPathParser.BAR + && last != XPathParser.PLUS + && last != XPathParser.MINUS + && last != XPathParser.EQUALS + && last != XPathParser.NOTEQUAL + && last != XPathParser.LESSTHAN + && last != XPathParser.LESSTHANOREQUAL + && last != XPathParser.GREATERTHAN + && last != XPathParser.GREATERTHANOREQUAL) { + if (name == "and") { + types.push(XPathParser.AND); + values.push(name); + continue; + } + if (name == "or") { + types.push(XPathParser.OR); + values.push(name); + continue; + } + if (name == "mod") { + types.push(XPathParser.MOD); + values.push(name); + continue; + } + if (name == "div") { + types.push(XPathParser.DIV); + values.push(name); + continue; + } + } + } + if (c == ':') { + if (s.charAt(pos) == '*') { + types.push(XPathParser.NCNAMECOLONASTERISK); + values.push(name + ":*"); + pos++; + c = s.charAt(pos++); + continue; + } + if (s.charAt(pos) == '_' || Utilities.isLetter(s.charCodeAt(pos))) { + name += ':'; + c = s.charAt(pos++); + while (Utilities.isNCNameChar(c.charCodeAt(0))) { + name += c; + c = s.charAt(pos++); + } + if (c == '(') { + types.push(XPathParser.FUNCTIONNAME); + values.push(name); + continue; + } + types.push(XPathParser.QNAME); + values.push(name); + continue; + } + if (s.charAt(pos) == ':') { + types.push(XPathParser.AXISNAME); + values.push(name); + continue; + } + } + if (c == '(') { + if (name == "comment" || name == "text" || name == "node") { + types.push(XPathParser.NODETYPE); + values.push(name); + continue; + } + if (name == "processing-instruction") { + if (s.charAt(pos) == ')') { + types.push(XPathParser.NODETYPE); + } else { + types.push(XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL); + } + values.push(name); + continue; + } + types.push(XPathParser.FUNCTIONNAME); + values.push(name); + continue; + } + types.push(XPathParser.QNAME); + values.push(name); + continue; + } + + throw new Error("Unexpected character " + c); + } + types.push(1); + values.push("[EOF]"); + return [types, values]; + }; + + XPathParser.SHIFT = 's'; + XPathParser.REDUCE = 'r'; + XPathParser.ACCEPT = 'a'; + + XPathParser.prototype.parse = function (s) { + var types; + var values; + var res = this.tokenize(s); + if (res == undefined) { + return undefined; + } + types = res[0]; + values = res[1]; + var tokenPos = 0; + var state = []; + var tokenType = []; + var tokenValue = []; + var s; + var a; + var t; + + state.push(0); + tokenType.push(1); + tokenValue.push("_S"); + + a = types[tokenPos]; + t = values[tokenPos++]; + while (1) { + s = state[state.length - 1]; + switch (XPathParser.actionTable[s].charAt(a - 1)) { + case XPathParser.SHIFT: + tokenType.push(-a); + tokenValue.push(t); + state.push(XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32); + a = types[tokenPos]; + t = values[tokenPos++]; + break; + case XPathParser.REDUCE: + var num = XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][1]; + var rhs = []; + for (var i = 0; i < num; i++) { + tokenType.pop(); + rhs.unshift(tokenValue.pop()); + state.pop(); + } + var s_ = state[state.length - 1]; + tokenType.push(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0]); + if (this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32] == undefined) { + tokenValue.push(rhs[0]); + } else { + tokenValue.push(this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32](rhs)); + } + state.push(XPathParser.gotoTable[s_].charCodeAt(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0] - 2) - 33); + break; + case XPathParser.ACCEPT: + return new XPath(tokenValue.pop()); + default: + throw new Error("XPath parse error"); + } + } + }; + + // XPath ///////////////////////////////////////////////////////////////////// + + XPath.prototype = new Object(); + XPath.prototype.constructor = XPath; + XPath.superclass = Object.prototype; + + function XPath(e) { + this.expression = e; + } + + XPath.prototype.toString = function () { + return this.expression.toString(); + }; + + function setIfUnset(obj, prop, value) { + if (!(prop in obj)) { + obj[prop] = value; + } + } + + XPath.prototype.evaluate = function (c) { + c.contextNode = c.expressionContextNode; + c.contextSize = 1; + c.contextPosition = 1; + + // [2017-11-25] Removed usage of .implementation.hasFeature() since it does + // not reliably detect HTML DOMs (always returns false in xmldom and true in browsers) + if (c.isHtml) { + setIfUnset(c, 'caseInsensitive', true); + setIfUnset(c, 'allowAnyNamespaceForNoPrefix', true); + } + + setIfUnset(c, 'caseInsensitive', false); + + return this.expression.evaluate(c); + }; + + XPath.XML_NAMESPACE_URI = "http://www.w3.org/XML/1998/namespace"; + XPath.XMLNS_NAMESPACE_URI = "http://www.w3.org/2000/xmlns/"; + + // Expression //////////////////////////////////////////////////////////////// + + Expression.prototype = new Object(); + Expression.prototype.constructor = Expression; + Expression.superclass = Object.prototype; + + function Expression() { + } + + Expression.prototype.init = function () { + }; + + Expression.prototype.toString = function () { + return ""; + }; + + Expression.prototype.evaluate = function (c) { + throw new Error("Could not evaluate expression."); + }; + + // UnaryOperation //////////////////////////////////////////////////////////// + + UnaryOperation.prototype = new Expression(); + UnaryOperation.prototype.constructor = UnaryOperation; + UnaryOperation.superclass = Expression.prototype; + + function UnaryOperation(rhs) { + if (arguments.length > 0) { + this.init(rhs); + } + } + + UnaryOperation.prototype.init = function (rhs) { + this.rhs = rhs; + }; + + // UnaryMinusOperation /////////////////////////////////////////////////////// + + UnaryMinusOperation.prototype = new UnaryOperation(); + UnaryMinusOperation.prototype.constructor = UnaryMinusOperation; + UnaryMinusOperation.superclass = UnaryOperation.prototype; + + function UnaryMinusOperation(rhs) { + if (arguments.length > 0) { + this.init(rhs); + } + } + + UnaryMinusOperation.prototype.init = function (rhs) { + UnaryMinusOperation.superclass.init.call(this, rhs); + }; + + UnaryMinusOperation.prototype.evaluate = function (c) { + return this.rhs.evaluate(c).number().negate(); + }; + + UnaryMinusOperation.prototype.toString = function () { + return "-" + this.rhs.toString(); + }; + + // BinaryOperation /////////////////////////////////////////////////////////// + + BinaryOperation.prototype = new Expression(); + BinaryOperation.prototype.constructor = BinaryOperation; + BinaryOperation.superclass = Expression.prototype; + + function BinaryOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + BinaryOperation.prototype.init = function (lhs, rhs) { + this.lhs = lhs; + this.rhs = rhs; + }; + + // OrOperation /////////////////////////////////////////////////////////////// + + OrOperation.prototype = new BinaryOperation(); + OrOperation.prototype.constructor = OrOperation; + OrOperation.superclass = BinaryOperation.prototype; + + function OrOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + OrOperation.prototype.init = function (lhs, rhs) { + OrOperation.superclass.init.call(this, lhs, rhs); + }; + + OrOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " or " + this.rhs.toString() + ")"; + }; + + OrOperation.prototype.evaluate = function (c) { + var b = this.lhs.evaluate(c).bool(); + if (b.booleanValue()) { + return b; + } + return this.rhs.evaluate(c).bool(); + }; + + // AndOperation ////////////////////////////////////////////////////////////// + + AndOperation.prototype = new BinaryOperation(); + AndOperation.prototype.constructor = AndOperation; + AndOperation.superclass = BinaryOperation.prototype; + + function AndOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + AndOperation.prototype.init = function (lhs, rhs) { + AndOperation.superclass.init.call(this, lhs, rhs); + }; + + AndOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " and " + this.rhs.toString() + ")"; + }; + + AndOperation.prototype.evaluate = function (c) { + var b = this.lhs.evaluate(c).bool(); + if (!b.booleanValue()) { + return b; + } + return this.rhs.evaluate(c).bool(); + }; + + // EqualsOperation /////////////////////////////////////////////////////////// + + EqualsOperation.prototype = new BinaryOperation(); + EqualsOperation.prototype.constructor = EqualsOperation; + EqualsOperation.superclass = BinaryOperation.prototype; + + function EqualsOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + EqualsOperation.prototype.init = function (lhs, rhs) { + EqualsOperation.superclass.init.call(this, lhs, rhs); + }; + + EqualsOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " = " + this.rhs.toString() + ")"; + }; + + EqualsOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).equals(this.rhs.evaluate(c)); + }; + + // NotEqualOperation ///////////////////////////////////////////////////////// + + NotEqualOperation.prototype = new BinaryOperation(); + NotEqualOperation.prototype.constructor = NotEqualOperation; + NotEqualOperation.superclass = BinaryOperation.prototype; + + function NotEqualOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); } } - return to; -} - -// XPathParser /////////////////////////////////////////////////////////////// - -XPathParser.prototype = new Object(); -XPathParser.prototype.constructor = XPathParser; -XPathParser.superclass = Object.prototype; - -function XPathParser() { - this.init(); -} - -XPathParser.prototype.init = function() { - this.reduceActions = []; - - this.reduceActions[3] = function(rhs) { - return new OrOperation(rhs[0], rhs[2]); - }; - this.reduceActions[5] = function(rhs) { - return new AndOperation(rhs[0], rhs[2]); - }; - this.reduceActions[7] = function(rhs) { - return new EqualsOperation(rhs[0], rhs[2]); - }; - this.reduceActions[8] = function(rhs) { - return new NotEqualOperation(rhs[0], rhs[2]); - }; - this.reduceActions[10] = function(rhs) { - return new LessThanOperation(rhs[0], rhs[2]); - }; - this.reduceActions[11] = function(rhs) { - return new GreaterThanOperation(rhs[0], rhs[2]); - }; - this.reduceActions[12] = function(rhs) { - return new LessThanOrEqualOperation(rhs[0], rhs[2]); - }; - this.reduceActions[13] = function(rhs) { - return new GreaterThanOrEqualOperation(rhs[0], rhs[2]); - }; - this.reduceActions[15] = function(rhs) { - return new PlusOperation(rhs[0], rhs[2]); - }; - this.reduceActions[16] = function(rhs) { - return new MinusOperation(rhs[0], rhs[2]); - }; - this.reduceActions[18] = function(rhs) { - return new MultiplyOperation(rhs[0], rhs[2]); - }; - this.reduceActions[19] = function(rhs) { - return new DivOperation(rhs[0], rhs[2]); - }; - this.reduceActions[20] = function(rhs) { - return new ModOperation(rhs[0], rhs[2]); - }; - this.reduceActions[22] = function(rhs) { - return new UnaryMinusOperation(rhs[1]); - }; - this.reduceActions[24] = function(rhs) { - return new BarOperation(rhs[0], rhs[2]); - }; - this.reduceActions[25] = function(rhs) { - return new PathExpr(undefined, undefined, rhs[0]); - }; - this.reduceActions[27] = function(rhs) { - rhs[0].locationPath = rhs[2]; - return rhs[0]; - }; - this.reduceActions[28] = function(rhs) { - rhs[0].locationPath = rhs[2]; - rhs[0].locationPath.steps.unshift(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, [])); - return rhs[0]; - }; - this.reduceActions[29] = function(rhs) { - return new PathExpr(rhs[0], [], undefined); - }; - this.reduceActions[30] = function(rhs) { - if (Utilities.instance_of(rhs[0], PathExpr)) { - if (rhs[0].filterPredicates == undefined) { - rhs[0].filterPredicates = []; - } - rhs[0].filterPredicates.push(rhs[1]); - return rhs[0]; - } else { - return new PathExpr(rhs[0], [rhs[1]], undefined); - } - }; - this.reduceActions[32] = function(rhs) { - return rhs[1]; - }; - this.reduceActions[33] = function(rhs) { - return new XString(rhs[0]); - }; - this.reduceActions[34] = function(rhs) { - return new XNumber(rhs[0]); - }; - this.reduceActions[36] = function(rhs) { - return new FunctionCall(rhs[0], []); - }; - this.reduceActions[37] = function(rhs) { - return new FunctionCall(rhs[0], rhs[2]); - }; - this.reduceActions[38] = function(rhs) { - return [ rhs[0] ]; - }; - this.reduceActions[39] = function(rhs) { - rhs[2].unshift(rhs[0]); - return rhs[2]; - }; - this.reduceActions[43] = function(rhs) { - return new LocationPath(true, []); - }; - this.reduceActions[44] = function(rhs) { - rhs[1].absolute = true; - return rhs[1]; - }; - this.reduceActions[46] = function(rhs) { - return new LocationPath(false, [ rhs[0] ]); - }; - this.reduceActions[47] = function(rhs) { - rhs[0].steps.push(rhs[2]); - return rhs[0]; - }; - this.reduceActions[49] = function(rhs) { - return new Step(rhs[0], rhs[1], []); - }; - this.reduceActions[50] = function(rhs) { - return new Step(Step.CHILD, rhs[0], []); - }; - this.reduceActions[51] = function(rhs) { - return new Step(rhs[0], rhs[1], rhs[2]); - }; - this.reduceActions[52] = function(rhs) { - return new Step(Step.CHILD, rhs[0], rhs[1]); - }; - this.reduceActions[54] = function(rhs) { - return [ rhs[0] ]; - }; - this.reduceActions[55] = function(rhs) { - rhs[1].unshift(rhs[0]); - return rhs[1]; - }; - this.reduceActions[56] = function(rhs) { - if (rhs[0] == "ancestor") { - return Step.ANCESTOR; - } else if (rhs[0] == "ancestor-or-self") { - return Step.ANCESTORORSELF; - } else if (rhs[0] == "attribute") { - return Step.ATTRIBUTE; - } else if (rhs[0] == "child") { - return Step.CHILD; - } else if (rhs[0] == "descendant") { - return Step.DESCENDANT; - } else if (rhs[0] == "descendant-or-self") { - return Step.DESCENDANTORSELF; - } else if (rhs[0] == "following") { - return Step.FOLLOWING; - } else if (rhs[0] == "following-sibling") { - return Step.FOLLOWINGSIBLING; - } else if (rhs[0] == "namespace") { - return Step.NAMESPACE; - } else if (rhs[0] == "parent") { - return Step.PARENT; - } else if (rhs[0] == "preceding") { - return Step.PRECEDING; - } else if (rhs[0] == "preceding-sibling") { - return Step.PRECEDINGSIBLING; - } else if (rhs[0] == "self") { - return Step.SELF; - } - return -1; - }; - this.reduceActions[57] = function(rhs) { - return Step.ATTRIBUTE; - }; - this.reduceActions[59] = function(rhs) { - if (rhs[0] == "comment") { - return NodeTest.commentTest; - } else if (rhs[0] == "text") { - return NodeTest.textTest; - } else if (rhs[0] == "processing-instruction") { - return NodeTest.anyPiTest; - } else if (rhs[0] == "node") { - return NodeTest.nodeTest; - } - return new NodeTest(-1, undefined); - }; - this.reduceActions[60] = function(rhs) { - return new NodeTest.PITest(rhs[2]); - }; - this.reduceActions[61] = function(rhs) { - return rhs[1]; - }; - this.reduceActions[63] = function(rhs) { - rhs[1].absolute = true; - rhs[1].steps.unshift(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, [])); - return rhs[1]; - }; - this.reduceActions[64] = function(rhs) { - rhs[0].steps.push(new Step(Step.DESCENDANTORSELF, NodeTest.nodeTest, [])); - rhs[0].steps.push(rhs[2]); - return rhs[0]; - }; - this.reduceActions[65] = function(rhs) { - return new Step(Step.SELF, NodeTest.nodeTest, []); - }; - this.reduceActions[66] = function(rhs) { - return new Step(Step.PARENT, NodeTest.nodeTest, []); - }; - this.reduceActions[67] = function(rhs) { - return new VariableReference(rhs[1]); - }; - this.reduceActions[68] = function(rhs) { - return NodeTest.nameTestAny; - }; - this.reduceActions[69] = function(rhs) { - return new NodeTest.NameTestPrefixAny(rhs[0].split(':')[0]); - }; - this.reduceActions[70] = function(rhs) { - return new NodeTest.NameTestQName(rhs[0]); - }; -}; - -XPathParser.actionTable = [ - " s s sssssssss s ss s ss", - " s ", - "r rrrrrrrrr rrrrrrr rr r ", - " rrrrr ", - " s s sssssssss s ss s ss", - "rs rrrrrrrr s sssssrrrrrr rrs rs ", - " s s sssssssss s ss s ss", - " s ", - " s ", - "r rrrrrrrrr rrrrrrr rr rr ", - "r rrrrrrrrr rrrrrrr rr rr ", - "r rrrrrrrrr rrrrrrr rr rr ", - "r rrrrrrrrr rrrrrrr rr rr ", - "r rrrrrrrrr rrrrrrr rr rr ", - " s ", - " s ", - " s s sssss s s ", - "r rrrrrrrrr rrrrrrr rr r ", - "a ", - "r s rr r ", - "r sr rr r ", - "r s rr s rr r ", - "r rssrr rss rr r ", - "r rrrrr rrrss rr r ", - "r rrrrrsss rrrrr rr r ", - "r rrrrrrrr rrrrr rr r ", - "r rrrrrrrr rrrrrs rr r ", - "r rrrrrrrr rrrrrr rr r ", - "r rrrrrrrr rrrrrr rr r ", - "r srrrrrrrr rrrrrrs rr sr ", - "r srrrrrrrr rrrrrrs rr r ", - "r rrrrrrrrr rrrrrrr rr rr ", - "r rrrrrrrrr rrrrrrr rr rr ", - "r rrrrrrrrr rrrrrrr rr rr ", - "r rrrrrrrr rrrrrr rr r ", - "r rrrrrrrr rrrrrr rr r ", - "r rrrrrrrrr rrrrrrr rr r ", - "r rrrrrrrrr rrrrrrr rr r ", - " sssss ", - "r rrrrrrrrr rrrrrrr rr sr ", - "r rrrrrrrrr rrrrrrr rr r ", - "r rrrrrrrrr rrrrrrr rr rr ", - "r rrrrrrrrr rrrrrrr rr rr ", - " s ", - "r srrrrrrrr rrrrrrs rr r ", - "r rrrrrrrr rrrrr rr r ", - " s ", - " s ", - " rrrrr ", - " s s sssssssss s sss s ss", - "r srrrrrrrr rrrrrrs rr r ", - " s s sssssssss s ss s ss", - " s s sssssssss s ss s ss", - " s s sssssssss s ss s ss", - " s s sssssssss s ss s ss", - " s s sssssssss s ss s ss", - " s s sssssssss s ss s ss", - " s s sssssssss s ss s ss", - " s s sssssssss s ss s ss", - " s s sssssssss s ss s ss", - " s s sssssssss s ss s ss", - " s s sssssssss s ss s ss", - " s s sssssssss s ss s ss", - " s s sssssssss s ss s ss", - " s s sssssssss ss s ss", - " s s sssssssss s ss s ss", - " s s sssss s s ", - " s s sssss s s ", - "r rrrrrrrrr rrrrrrr rr rr ", - " s s sssss s s ", - " s s sssss s s ", - "r rrrrrrrrr rrrrrrr rr sr ", - "r rrrrrrrrr rrrrrrr rr sr ", - "r rrrrrrrrr rrrrrrr rr r ", - "r rrrrrrrrr rrrrrrr rr rr ", - " s ", - "r rrrrrrrrr rrrrrrr rr rr ", - "r rrrrrrrrr rrrrrrr rr rr ", - " rr ", - " s ", - " rs ", - "r sr rr r ", - "r s rr s rr r ", - "r rssrr rss rr r ", - "r rssrr rss rr r ", - "r rrrrr rrrss rr r ", - "r rrrrr rrrss rr r ", - "r rrrrr rrrss rr r ", - "r rrrrr rrrss rr r ", - "r rrrrrsss rrrrr rr r ", - "r rrrrrsss rrrrr rr r ", - "r rrrrrrrr rrrrr rr r ", - "r rrrrrrrr rrrrr rr r ", - "r rrrrrrrr rrrrr rr r ", - "r rrrrrrrr rrrrrr rr r ", - " r ", - " s ", - "r srrrrrrrr rrrrrrs rr r ", - "r srrrrrrrr rrrrrrs rr r ", - "r rrrrrrrrr rrrrrrr rr r ", - "r rrrrrrrrr rrrrrrr rr r ", - "r rrrrrrrrr rrrrrrr rr r ", - "r rrrrrrrrr rrrrrrr rr r ", - "r rrrrrrrrr rrrrrrr rr rr ", - "r rrrrrrrrr rrrrrrr rr rr ", - " s s sssssssss s ss s ss", - "r rrrrrrrrr rrrrrrr rr rr ", - " r " -]; - -XPathParser.actionTableNumber = [ - " 1 0 /.-,+*)(' & %$ # \"!", - " J ", - "a aaaaaaaaa aaaaaaa aa a ", - " YYYYY ", - " 1 0 /.-,+*)(' & %$ # \"!", - "K1 KKKKKKKK . +*)('KKKKKK KK# K\" ", - " 1 0 /.-,+*)(' & %$ # \"!", - " N ", - " O ", - "e eeeeeeeee eeeeeee ee ee ", - "f fffffffff fffffff ff ff ", - "d ddddddddd ddddddd dd dd ", - "B BBBBBBBBB BBBBBBB BB BB ", - "A AAAAAAAAA AAAAAAA AA AA ", - " P ", - " Q ", - " 1 . +*)(' # \" ", - "b bbbbbbbbb bbbbbbb bb b ", - " ", - "! S !! ! ", - "\" T\" \"\" \" ", - "$ V $$ U $$ $ ", - "& &ZY&& &XW && & ", - ") ))))) )))\\[ )) ) ", - ". ....._^] ..... .. . ", - "1 11111111 11111 11 1 ", - "5 55555555 55555` 55 5 ", - "7 77777777 777777 77 7 ", - "9 99999999 999999 99 9 ", - ": c:::::::: ::::::b :: a: ", - "I fIIIIIIII IIIIIIe II I ", - "= ========= ======= == == ", - "? ????????? ??????? ?? ?? ", - "C CCCCCCCCC CCCCCCC CC CC ", - "J JJJJJJJJ JJJJJJ JJ J ", - "M MMMMMMMM MMMMMM MM M ", - "N NNNNNNNNN NNNNNNN NN N ", - "P PPPPPPPPP PPPPPPP PP P ", - " +*)(' ", - "R RRRRRRRRR RRRRRRR RR aR ", - "U UUUUUUUUU UUUUUUU UU U ", - "Z ZZZZZZZZZ ZZZZZZZ ZZ ZZ ", - "c ccccccccc ccccccc cc cc ", - " j ", - "L fLLLLLLLL LLLLLLe LL L ", - "6 66666666 66666 66 6 ", - " k ", - " l ", - " XXXXX ", - " 1 0 /.-,+*)(' & %$m # \"!", - "_ f________ ______e __ _ ", - " 1 0 /.-,+*)(' & %$ # \"!", - " 1 0 /.-,+*)(' & %$ # \"!", - " 1 0 /.-,+*)(' & %$ # \"!", - " 1 0 /.-,+*)(' & %$ # \"!", - " 1 0 /.-,+*)(' & %$ # \"!", - " 1 0 /.-,+*)(' & %$ # \"!", - " 1 0 /.-,+*)(' & %$ # \"!", - " 1 0 /.-,+*)(' & %$ # \"!", - " 1 0 /.-,+*)(' & %$ # \"!", - " 1 0 /.-,+*)(' & %$ # \"!", - " 1 0 /.-,+*)(' & %$ # \"!", - " 1 0 /.-,+*)(' & %$ # \"!", - " 1 0 /.-,+*)(' & %$ # \"!", - " 1 0 /.-,+*)(' %$ # \"!", - " 1 0 /.-,+*)(' & %$ # \"!", - " 1 . +*)(' # \" ", - " 1 . +*)(' # \" ", - "> >>>>>>>>> >>>>>>> >> >> ", - " 1 . +*)(' # \" ", - " 1 . +*)(' # \" ", - "Q QQQQQQQQQ QQQQQQQ QQ aQ ", - "V VVVVVVVVV VVVVVVV VV aV ", - "T TTTTTTTTT TTTTTTT TT T ", - "@ @@@@@@@@@ @@@@@@@ @@ @@ ", - " \x87 ", - "[ [[[[[[[[[ [[[[[[[ [[ [[ ", - "D DDDDDDDDD DDDDDDD DD DD ", - " HH ", - " \x88 ", - " F\x89 ", - "# T# ## # ", - "% V %% U %% % ", - "' 'ZY'' 'XW '' ' ", - "( (ZY(( (XW (( ( ", - "+ +++++ +++\\[ ++ + ", - "* ***** ***\\[ ** * ", - "- ----- ---\\[ -- - ", - ", ,,,,, ,,,\\[ ,, , ", - "0 00000_^] 00000 00 0 ", - "/ /////_^] ///// // / ", - "2 22222222 22222 22 2 ", - "3 33333333 33333 33 3 ", - "4 44444444 44444 44 4 ", - "8 88888888 888888 88 8 ", - " ^ ", - " \x8a ", - "; f;;;;;;;; ;;;;;;e ;; ; ", - "< f<<<<<<<< <<<<<?@ AB CDEFGH IJ ", - " ", - " ", - " ", - "L456789:;<=>?@ AB CDEFGH IJ ", - " M EFGH IJ ", - " N;<=>?@ AB CDEFGH IJ ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " S EFGH IJ ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " e ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " h J ", - " i j ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - "o456789:;<=>?@ ABpqCDEFGH IJ ", - " ", - " r6789:;<=>?@ AB CDEFGH IJ ", - " s789:;<=>?@ AB CDEFGH IJ ", - " t89:;<=>?@ AB CDEFGH IJ ", - " u89:;<=>?@ AB CDEFGH IJ ", - " v9:;<=>?@ AB CDEFGH IJ ", - " w9:;<=>?@ AB CDEFGH IJ ", - " x9:;<=>?@ AB CDEFGH IJ ", - " y9:;<=>?@ AB CDEFGH IJ ", - " z:;<=>?@ AB CDEFGH IJ ", - " {:;<=>?@ AB CDEFGH IJ ", - " |;<=>?@ AB CDEFGH IJ ", - " };<=>?@ AB CDEFGH IJ ", - " ~;<=>?@ AB CDEFGH IJ ", - " \x7f=>?@ AB CDEFGH IJ ", - "\x80456789:;<=>?@ AB CDEFGH IJ\x81", - " \x82 EFGH IJ ", - " \x83 EFGH IJ ", - " ", - " \x84 GH IJ ", - " \x85 GH IJ ", - " i \x86 ", - " i \x87 ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - "o456789:;<=>?@ AB\x8cqCDEFGH IJ ", - " ", - " " -]; - -XPathParser.productions = [ - [1, 1, 2], - [2, 1, 3], - [3, 1, 4], - [3, 3, 3, -9, 4], - [4, 1, 5], - [4, 3, 4, -8, 5], - [5, 1, 6], - [5, 3, 5, -22, 6], - [5, 3, 5, -5, 6], - [6, 1, 7], - [6, 3, 6, -23, 7], - [6, 3, 6, -24, 7], - [6, 3, 6, -6, 7], - [6, 3, 6, -7, 7], - [7, 1, 8], - [7, 3, 7, -25, 8], - [7, 3, 7, -26, 8], - [8, 1, 9], - [8, 3, 8, -12, 9], - [8, 3, 8, -11, 9], - [8, 3, 8, -10, 9], - [9, 1, 10], - [9, 2, -26, 9], - [10, 1, 11], - [10, 3, 10, -27, 11], - [11, 1, 12], - [11, 1, 13], - [11, 3, 13, -28, 14], - [11, 3, 13, -4, 14], - [13, 1, 15], - [13, 2, 13, 16], - [15, 1, 17], - [15, 3, -29, 2, -30], - [15, 1, -15], - [15, 1, -16], - [15, 1, 18], - [18, 3, -13, -29, -30], - [18, 4, -13, -29, 19, -30], - [19, 1, 20], - [19, 3, 20, -31, 19], - [20, 1, 2], - [12, 1, 14], - [12, 1, 21], - [21, 1, -28], - [21, 2, -28, 14], - [21, 1, 22], - [14, 1, 23], - [14, 3, 14, -28, 23], - [14, 1, 24], - [23, 2, 25, 26], - [23, 1, 26], - [23, 3, 25, 26, 27], - [23, 2, 26, 27], - [23, 1, 28], - [27, 1, 16], - [27, 2, 16, 27], - [25, 2, -14, -3], - [25, 1, -32], - [26, 1, 29], - [26, 3, -20, -29, -30], - [26, 4, -21, -29, -15, -30], - [16, 3, -33, 30, -34], - [30, 1, 2], - [22, 2, -4, 14], - [24, 3, 14, -4, 23], - [28, 1, -35], - [28, 1, -2], - [17, 2, -36, -18], - [29, 1, -17], - [29, 1, -19], - [29, 1, -18] -]; - -XPathParser.DOUBLEDOT = 2; -XPathParser.DOUBLECOLON = 3; -XPathParser.DOUBLESLASH = 4; -XPathParser.NOTEQUAL = 5; -XPathParser.LESSTHANOREQUAL = 6; -XPathParser.GREATERTHANOREQUAL = 7; -XPathParser.AND = 8; -XPathParser.OR = 9; -XPathParser.MOD = 10; -XPathParser.DIV = 11; -XPathParser.MULTIPLYOPERATOR = 12; -XPathParser.FUNCTIONNAME = 13; -XPathParser.AXISNAME = 14; -XPathParser.LITERAL = 15; -XPathParser.NUMBER = 16; -XPathParser.ASTERISKNAMETEST = 17; -XPathParser.QNAME = 18; -XPathParser.NCNAMECOLONASTERISK = 19; -XPathParser.NODETYPE = 20; -XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL = 21; -XPathParser.EQUALS = 22; -XPathParser.LESSTHAN = 23; -XPathParser.GREATERTHAN = 24; -XPathParser.PLUS = 25; -XPathParser.MINUS = 26; -XPathParser.BAR = 27; -XPathParser.SLASH = 28; -XPathParser.LEFTPARENTHESIS = 29; -XPathParser.RIGHTPARENTHESIS = 30; -XPathParser.COMMA = 31; -XPathParser.AT = 32; -XPathParser.LEFTBRACKET = 33; -XPathParser.RIGHTBRACKET = 34; -XPathParser.DOT = 35; -XPathParser.DOLLAR = 36; - -XPathParser.prototype.tokenize = function(s1) { - var types = []; - var values = []; - var s = s1 + '\0'; - - var pos = 0; - var c = s.charAt(pos++); - while (1) { - while (c == ' ' || c == '\t' || c == '\r' || c == '\n') { - c = s.charAt(pos++); - } - if (c == '\0' || pos >= s.length) { - break; - } - - if (c == '(') { - types.push(XPathParser.LEFTPARENTHESIS); - values.push(c); - c = s.charAt(pos++); - continue; - } - if (c == ')') { - types.push(XPathParser.RIGHTPARENTHESIS); - values.push(c); - c = s.charAt(pos++); - continue; - } - if (c == '[') { - types.push(XPathParser.LEFTBRACKET); - values.push(c); - c = s.charAt(pos++); - continue; - } - if (c == ']') { - types.push(XPathParser.RIGHTBRACKET); - values.push(c); - c = s.charAt(pos++); - continue; - } - if (c == '@') { - types.push(XPathParser.AT); - values.push(c); - c = s.charAt(pos++); - continue; - } - if (c == ',') { - types.push(XPathParser.COMMA); - values.push(c); - c = s.charAt(pos++); - continue; - } - if (c == '|') { - types.push(XPathParser.BAR); - values.push(c); - c = s.charAt(pos++); - continue; - } - if (c == '+') { - types.push(XPathParser.PLUS); - values.push(c); - c = s.charAt(pos++); - continue; - } - if (c == '-') { - types.push(XPathParser.MINUS); - values.push(c); - c = s.charAt(pos++); - continue; - } - if (c == '=') { - types.push(XPathParser.EQUALS); - values.push(c); - c = s.charAt(pos++); - continue; - } - if (c == '$') { - types.push(XPathParser.DOLLAR); - values.push(c); - c = s.charAt(pos++); - continue; - } - - if (c == '.') { - c = s.charAt(pos++); - if (c == '.') { - types.push(XPathParser.DOUBLEDOT); - values.push(".."); - c = s.charAt(pos++); - continue; - } - if (c >= '0' && c <= '9') { - var number = "." + c; - c = s.charAt(pos++); - while (c >= '0' && c <= '9') { - number += c; - c = s.charAt(pos++); - } - types.push(XPathParser.NUMBER); - values.push(number); - continue; - } - types.push(XPathParser.DOT); - values.push('.'); - continue; - } - - if (c == '\'' || c == '"') { - var delimiter = c; - var literal = ""; - while (pos < s.length && (c = s.charAt(pos)) !== delimiter) { - literal += c; - pos += 1; - } - if (c !== delimiter) { - throw XPathException.fromMessage("Unterminated string literal: " + delimiter + literal); - } - pos += 1; - types.push(XPathParser.LITERAL); - values.push(literal); - c = s.charAt(pos++); - continue; - } - - if (c >= '0' && c <= '9') { - var number = c; - c = s.charAt(pos++); - while (c >= '0' && c <= '9') { - number += c; - c = s.charAt(pos++); - } - if (c == '.') { - if (s.charAt(pos) >= '0' && s.charAt(pos) <= '9') { - number += c; - number += s.charAt(pos++); - c = s.charAt(pos++); - while (c >= '0' && c <= '9') { - number += c; - c = s.charAt(pos++); - } - } - } - types.push(XPathParser.NUMBER); - values.push(number); - continue; - } - - if (c == '*') { - if (types.length > 0) { - var last = types[types.length - 1]; - if (last != XPathParser.AT - && last != XPathParser.DOUBLECOLON - && last != XPathParser.LEFTPARENTHESIS - && last != XPathParser.LEFTBRACKET - && last != XPathParser.AND - && last != XPathParser.OR - && last != XPathParser.MOD - && last != XPathParser.DIV - && last != XPathParser.MULTIPLYOPERATOR - && last != XPathParser.SLASH - && last != XPathParser.DOUBLESLASH - && last != XPathParser.BAR - && last != XPathParser.PLUS - && last != XPathParser.MINUS - && last != XPathParser.EQUALS - && last != XPathParser.NOTEQUAL - && last != XPathParser.LESSTHAN - && last != XPathParser.LESSTHANOREQUAL - && last != XPathParser.GREATERTHAN - && last != XPathParser.GREATERTHANOREQUAL) { - types.push(XPathParser.MULTIPLYOPERATOR); - values.push(c); - c = s.charAt(pos++); - continue; - } - } - types.push(XPathParser.ASTERISKNAMETEST); - values.push(c); - c = s.charAt(pos++); - continue; - } - - if (c == ':') { - if (s.charAt(pos) == ':') { - types.push(XPathParser.DOUBLECOLON); - values.push("::"); - pos++; - c = s.charAt(pos++); - continue; - } - } - - if (c == '/') { - c = s.charAt(pos++); - if (c == '/') { - types.push(XPathParser.DOUBLESLASH); - values.push("//"); - c = s.charAt(pos++); - continue; - } - types.push(XPathParser.SLASH); - values.push('/'); - continue; - } - - if (c == '!') { - if (s.charAt(pos) == '=') { - types.push(XPathParser.NOTEQUAL); - values.push("!="); - pos++; - c = s.charAt(pos++); - continue; - } - } - - if (c == '<') { - if (s.charAt(pos) == '=') { - types.push(XPathParser.LESSTHANOREQUAL); - values.push("<="); - pos++; - c = s.charAt(pos++); - continue; - } - types.push(XPathParser.LESSTHAN); - values.push('<'); - c = s.charAt(pos++); - continue; - } - - if (c == '>') { - if (s.charAt(pos) == '=') { - types.push(XPathParser.GREATERTHANOREQUAL); - values.push(">="); - pos++; - c = s.charAt(pos++); - continue; - } - types.push(XPathParser.GREATERTHAN); - values.push('>'); - c = s.charAt(pos++); - continue; - } - - if (c == '_' || Utilities.isLetter(c.charCodeAt(0))) { - var name = c; - c = s.charAt(pos++); - while (Utilities.isNCNameChar(c.charCodeAt(0))) { - name += c; - c = s.charAt(pos++); - } - if (types.length > 0) { - var last = types[types.length - 1]; - if (last != XPathParser.AT - && last != XPathParser.DOUBLECOLON - && last != XPathParser.LEFTPARENTHESIS - && last != XPathParser.LEFTBRACKET - && last != XPathParser.AND - && last != XPathParser.OR - && last != XPathParser.MOD - && last != XPathParser.DIV - && last != XPathParser.MULTIPLYOPERATOR - && last != XPathParser.SLASH - && last != XPathParser.DOUBLESLASH - && last != XPathParser.BAR - && last != XPathParser.PLUS - && last != XPathParser.MINUS - && last != XPathParser.EQUALS - && last != XPathParser.NOTEQUAL - && last != XPathParser.LESSTHAN - && last != XPathParser.LESSTHANOREQUAL - && last != XPathParser.GREATERTHAN - && last != XPathParser.GREATERTHANOREQUAL) { - if (name == "and") { - types.push(XPathParser.AND); - values.push(name); - continue; - } - if (name == "or") { - types.push(XPathParser.OR); - values.push(name); - continue; - } - if (name == "mod") { - types.push(XPathParser.MOD); - values.push(name); - continue; - } - if (name == "div") { - types.push(XPathParser.DIV); - values.push(name); - continue; - } - } - } - if (c == ':') { - if (s.charAt(pos) == '*') { - types.push(XPathParser.NCNAMECOLONASTERISK); - values.push(name + ":*"); - pos++; - c = s.charAt(pos++); - continue; - } - if (s.charAt(pos) == '_' || Utilities.isLetter(s.charCodeAt(pos))) { - name += ':'; - c = s.charAt(pos++); - while (Utilities.isNCNameChar(c.charCodeAt(0))) { - name += c; - c = s.charAt(pos++); - } - if (c == '(') { - types.push(XPathParser.FUNCTIONNAME); - values.push(name); - continue; - } - types.push(XPathParser.QNAME); - values.push(name); - continue; - } - if (s.charAt(pos) == ':') { - types.push(XPathParser.AXISNAME); - values.push(name); - continue; - } - } - if (c == '(') { - if (name == "comment" || name == "text" || name == "node") { - types.push(XPathParser.NODETYPE); - values.push(name); - continue; - } - if (name == "processing-instruction") { - if (s.charAt(pos) == ')') { - types.push(XPathParser.NODETYPE); - } else { - types.push(XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL); - } - values.push(name); - continue; - } - types.push(XPathParser.FUNCTIONNAME); - values.push(name); - continue; - } - types.push(XPathParser.QNAME); - values.push(name); - continue; - } - - throw new Error("Unexpected character " + c); - } - types.push(1); - values.push("[EOF]"); - return [types, values]; -}; - -XPathParser.SHIFT = 's'; -XPathParser.REDUCE = 'r'; -XPathParser.ACCEPT = 'a'; - -XPathParser.prototype.parse = function(s) { - var types; - var values; - var res = this.tokenize(s); - if (res == undefined) { - return undefined; - } - types = res[0]; - values = res[1]; - var tokenPos = 0; - var state = []; - var tokenType = []; - var tokenValue = []; - var s; - var a; - var t; - - state.push(0); - tokenType.push(1); - tokenValue.push("_S"); - - a = types[tokenPos]; - t = values[tokenPos++]; - while (1) { - s = state[state.length - 1]; - switch (XPathParser.actionTable[s].charAt(a - 1)) { - case XPathParser.SHIFT: - tokenType.push(-a); - tokenValue.push(t); - state.push(XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32); - a = types[tokenPos]; - t = values[tokenPos++]; - break; - case XPathParser.REDUCE: - var num = XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][1]; - var rhs = []; - for (var i = 0; i < num; i++) { - tokenType.pop(); - rhs.unshift(tokenValue.pop()); - state.pop(); - } - var s_ = state[state.length - 1]; - tokenType.push(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0]); - if (this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32] == undefined) { - tokenValue.push(rhs[0]); - } else { - tokenValue.push(this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32](rhs)); - } - state.push(XPathParser.gotoTable[s_].charCodeAt(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0] - 2) - 33); - break; - case XPathParser.ACCEPT: - return new XPath(tokenValue.pop()); - default: - throw new Error("XPath parse error"); - } - } -}; - -// XPath ///////////////////////////////////////////////////////////////////// - -XPath.prototype = new Object(); -XPath.prototype.constructor = XPath; -XPath.superclass = Object.prototype; - -function XPath(e) { - this.expression = e; -} - -XPath.prototype.toString = function() { - return this.expression.toString(); -}; - -function setIfUnset(obj, prop, value) { - if (!(prop in obj)) { - obj[prop] = value; - } -} - -XPath.prototype.evaluate = function(c) { - c.contextNode = c.expressionContextNode; - c.contextSize = 1; - c.contextPosition = 1; - - // [2017-11-25] Removed usage of .implementation.hasFeature() since it does - // not reliably detect HTML DOMs (always returns false in xmldom and true in browsers) - if (c.isHtml) { - setIfUnset(c, 'caseInsensitive', true); - setIfUnset(c, 'allowAnyNamespaceForNoPrefix', true); - } - - setIfUnset(c, 'caseInsensitive', false); - - return this.expression.evaluate(c); -}; - -XPath.XML_NAMESPACE_URI = "http://www.w3.org/XML/1998/namespace"; -XPath.XMLNS_NAMESPACE_URI = "http://www.w3.org/2000/xmlns/"; - -// Expression //////////////////////////////////////////////////////////////// - -Expression.prototype = new Object(); -Expression.prototype.constructor = Expression; -Expression.superclass = Object.prototype; - -function Expression() { -} - -Expression.prototype.init = function() { -}; - -Expression.prototype.toString = function() { - return ""; -}; - -Expression.prototype.evaluate = function(c) { - throw new Error("Could not evaluate expression."); -}; - -// UnaryOperation //////////////////////////////////////////////////////////// - -UnaryOperation.prototype = new Expression(); -UnaryOperation.prototype.constructor = UnaryOperation; -UnaryOperation.superclass = Expression.prototype; - -function UnaryOperation(rhs) { - if (arguments.length > 0) { - this.init(rhs); - } -} - -UnaryOperation.prototype.init = function(rhs) { - this.rhs = rhs; -}; - -// UnaryMinusOperation /////////////////////////////////////////////////////// - -UnaryMinusOperation.prototype = new UnaryOperation(); -UnaryMinusOperation.prototype.constructor = UnaryMinusOperation; -UnaryMinusOperation.superclass = UnaryOperation.prototype; - -function UnaryMinusOperation(rhs) { - if (arguments.length > 0) { - this.init(rhs); - } -} - -UnaryMinusOperation.prototype.init = function(rhs) { - UnaryMinusOperation.superclass.init.call(this, rhs); -}; - -UnaryMinusOperation.prototype.evaluate = function(c) { - return this.rhs.evaluate(c).number().negate(); -}; - -UnaryMinusOperation.prototype.toString = function() { - return "-" + this.rhs.toString(); -}; - -// BinaryOperation /////////////////////////////////////////////////////////// - -BinaryOperation.prototype = new Expression(); -BinaryOperation.prototype.constructor = BinaryOperation; -BinaryOperation.superclass = Expression.prototype; - -function BinaryOperation(lhs, rhs) { - if (arguments.length > 0) { - this.init(lhs, rhs); - } -} - -BinaryOperation.prototype.init = function(lhs, rhs) { - this.lhs = lhs; - this.rhs = rhs; -}; - -// OrOperation /////////////////////////////////////////////////////////////// - -OrOperation.prototype = new BinaryOperation(); -OrOperation.prototype.constructor = OrOperation; -OrOperation.superclass = BinaryOperation.prototype; - -function OrOperation(lhs, rhs) { - if (arguments.length > 0) { - this.init(lhs, rhs); - } -} - -OrOperation.prototype.init = function(lhs, rhs) { - OrOperation.superclass.init.call(this, lhs, rhs); -}; + NotEqualOperation.prototype.init = function (lhs, rhs) { + NotEqualOperation.superclass.init.call(this, lhs, rhs); + }; + + NotEqualOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " != " + this.rhs.toString() + ")"; + }; + + NotEqualOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).notequal(this.rhs.evaluate(c)); + }; + + // LessThanOperation ///////////////////////////////////////////////////////// + + LessThanOperation.prototype = new BinaryOperation(); + LessThanOperation.prototype.constructor = LessThanOperation; + LessThanOperation.superclass = BinaryOperation.prototype; + + function LessThanOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + LessThanOperation.prototype.init = function (lhs, rhs) { + LessThanOperation.superclass.init.call(this, lhs, rhs); + }; + + LessThanOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).lessthan(this.rhs.evaluate(c)); + }; + + LessThanOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " < " + this.rhs.toString() + ")"; + }; + + // GreaterThanOperation ////////////////////////////////////////////////////// + + GreaterThanOperation.prototype = new BinaryOperation(); + GreaterThanOperation.prototype.constructor = GreaterThanOperation; + GreaterThanOperation.superclass = BinaryOperation.prototype; + + function GreaterThanOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + GreaterThanOperation.prototype.init = function (lhs, rhs) { + GreaterThanOperation.superclass.init.call(this, lhs, rhs); + }; + + GreaterThanOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).greaterthan(this.rhs.evaluate(c)); + }; + + GreaterThanOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " > " + this.rhs.toString() + ")"; + }; + + // LessThanOrEqualOperation ////////////////////////////////////////////////// + + LessThanOrEqualOperation.prototype = new BinaryOperation(); + LessThanOrEqualOperation.prototype.constructor = LessThanOrEqualOperation; + LessThanOrEqualOperation.superclass = BinaryOperation.prototype; + + function LessThanOrEqualOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + LessThanOrEqualOperation.prototype.init = function (lhs, rhs) { + LessThanOrEqualOperation.superclass.init.call(this, lhs, rhs); + }; + + LessThanOrEqualOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).lessthanorequal(this.rhs.evaluate(c)); + }; + + LessThanOrEqualOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " <= " + this.rhs.toString() + ")"; + }; + + // GreaterThanOrEqualOperation /////////////////////////////////////////////// + + GreaterThanOrEqualOperation.prototype = new BinaryOperation(); + GreaterThanOrEqualOperation.prototype.constructor = GreaterThanOrEqualOperation; + GreaterThanOrEqualOperation.superclass = BinaryOperation.prototype; + + function GreaterThanOrEqualOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + GreaterThanOrEqualOperation.prototype.init = function (lhs, rhs) { + GreaterThanOrEqualOperation.superclass.init.call(this, lhs, rhs); + }; + + GreaterThanOrEqualOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).greaterthanorequal(this.rhs.evaluate(c)); + }; + + GreaterThanOrEqualOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " >= " + this.rhs.toString() + ")"; + }; + + // PlusOperation ///////////////////////////////////////////////////////////// + + PlusOperation.prototype = new BinaryOperation(); + PlusOperation.prototype.constructor = PlusOperation; + PlusOperation.superclass = BinaryOperation.prototype; + + function PlusOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + PlusOperation.prototype.init = function (lhs, rhs) { + PlusOperation.superclass.init.call(this, lhs, rhs); + }; + + PlusOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).number().plus(this.rhs.evaluate(c).number()); + }; + + PlusOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " + " + this.rhs.toString() + ")"; + }; + + // MinusOperation //////////////////////////////////////////////////////////// + + MinusOperation.prototype = new BinaryOperation(); + MinusOperation.prototype.constructor = MinusOperation; + MinusOperation.superclass = BinaryOperation.prototype; + + function MinusOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + MinusOperation.prototype.init = function (lhs, rhs) { + MinusOperation.superclass.init.call(this, lhs, rhs); + }; + + MinusOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).number().minus(this.rhs.evaluate(c).number()); + }; + + MinusOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " - " + this.rhs.toString() + ")"; + }; + + // MultiplyOperation ///////////////////////////////////////////////////////// + + MultiplyOperation.prototype = new BinaryOperation(); + MultiplyOperation.prototype.constructor = MultiplyOperation; + MultiplyOperation.superclass = BinaryOperation.prototype; + + function MultiplyOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + MultiplyOperation.prototype.init = function (lhs, rhs) { + MultiplyOperation.superclass.init.call(this, lhs, rhs); + }; + + MultiplyOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).number().multiply(this.rhs.evaluate(c).number()); + }; + + MultiplyOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " * " + this.rhs.toString() + ")"; + }; + + // DivOperation ////////////////////////////////////////////////////////////// + + DivOperation.prototype = new BinaryOperation(); + DivOperation.prototype.constructor = DivOperation; + DivOperation.superclass = BinaryOperation.prototype; + + function DivOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + DivOperation.prototype.init = function (lhs, rhs) { + DivOperation.superclass.init.call(this, lhs, rhs); + }; + + DivOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).number().div(this.rhs.evaluate(c).number()); + }; + + DivOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " div " + this.rhs.toString() + ")"; + }; + + // ModOperation ////////////////////////////////////////////////////////////// + + ModOperation.prototype = new BinaryOperation(); + ModOperation.prototype.constructor = ModOperation; + ModOperation.superclass = BinaryOperation.prototype; + + function ModOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + ModOperation.prototype.init = function (lhs, rhs) { + ModOperation.superclass.init.call(this, lhs, rhs); + }; + + ModOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).number().mod(this.rhs.evaluate(c).number()); + }; + + ModOperation.prototype.toString = function () { + return "(" + this.lhs.toString() + " mod " + this.rhs.toString() + ")"; + }; + + // BarOperation ////////////////////////////////////////////////////////////// + + BarOperation.prototype = new BinaryOperation(); + BarOperation.prototype.constructor = BarOperation; + BarOperation.superclass = BinaryOperation.prototype; + + function BarOperation(lhs, rhs) { + if (arguments.length > 0) { + this.init(lhs, rhs); + } + } + + BarOperation.prototype.init = function (lhs, rhs) { + BarOperation.superclass.init.call(this, lhs, rhs); + }; + + BarOperation.prototype.evaluate = function (c) { + return this.lhs.evaluate(c).nodeset().union(this.rhs.evaluate(c).nodeset()); + }; + + BarOperation.prototype.toString = function () { + return map(toString, [this.lhs, this.rhs]).join(' | '); + }; + + // PathExpr ////////////////////////////////////////////////////////////////// + + PathExpr.prototype = new Expression(); + PathExpr.prototype.constructor = PathExpr; + PathExpr.superclass = Expression.prototype; + + function PathExpr(filter, filterPreds, locpath) { + if (arguments.length > 0) { + this.init(filter, filterPreds, locpath); + } + } + + PathExpr.prototype.init = function (filter, filterPreds, locpath) { + PathExpr.superclass.init.call(this); + this.filter = filter; + this.filterPredicates = filterPreds; + this.locationPath = locpath; + }; + + /** + * Returns the topmost node of the tree containing node + */ + function findRoot(node) { + while (node && node.parentNode) { + node = node.parentNode; + } + + return node; + } + + PathExpr.applyPredicates = function (predicates, c, nodes) { + if (predicates.length === 0) { + return nodes; + } + + var ctx = c.extend({}); + + return reduce( + function (inNodes, pred) { + ctx.contextSize = inNodes.length; + + return filter( + function (node, i) { + ctx.contextNode = node; + ctx.contextPosition = i + 1; + + return PathExpr.predicateMatches(pred, ctx); + }, + inNodes + ); + }, + nodes, + predicates + ); + }; + + PathExpr.getRoot = function (xpc, nodes) { + var firstNode = nodes[0]; + + if (firstNode.nodeType === 9 /*Node.DOCUMENT_NODE*/) { + return firstNode; + } + + if (xpc.virtualRoot) { + return xpc.virtualRoot; + } + + var ownerDoc = firstNode.ownerDocument; + + if (ownerDoc) { + return ownerDoc; + } + + // IE 5.5 doesn't have ownerDocument? + var n = firstNode; + while (n.parentNode != null) { + n = n.parentNode; + } + return n; + } + + PathExpr.applyStep = function (step, xpc, node) { + var self = this; + var newNodes = []; + xpc.contextNode = node; + + switch (step.axis) { + case Step.ANCESTOR: + // look at all the ancestor nodes + if (xpc.contextNode === xpc.virtualRoot) { + break; + } + var m; + if (xpc.contextNode.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) { + m = PathExpr.getOwnerElement(xpc.contextNode); + } else { + m = xpc.contextNode.parentNode; + } + while (m != null) { + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + if (m === xpc.virtualRoot) { + break; + } + m = m.parentNode; + } + break; + + case Step.ANCESTORORSELF: + // look at all the ancestor nodes and the current node + for (var m = xpc.contextNode; m != null; m = m.nodeType == 2 /*Node.ATTRIBUTE_NODE*/ ? PathExpr.getOwnerElement(m) : m.parentNode) { + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + if (m === xpc.virtualRoot) { + break; + } + } + break; + + case Step.ATTRIBUTE: + // look at the attributes + var nnm = xpc.contextNode.attributes; + if (nnm != null) { + for (var k = 0; k < nnm.length; k++) { + var m = nnm.item(k); + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + } + } + break; + + case Step.CHILD: + // look at all child elements + for (var m = xpc.contextNode.firstChild; m != null; m = m.nextSibling) { + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + } + break; + + case Step.DESCENDANT: + // look at all descendant nodes + var st = [xpc.contextNode.firstChild]; + while (st.length > 0) { + for (var m = st.pop(); m != null;) { + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + if (m.firstChild != null) { + st.push(m.nextSibling); + m = m.firstChild; + } else { + m = m.nextSibling; + } + } + } + break; + + case Step.DESCENDANTORSELF: + // look at self + if (step.nodeTest.matches(xpc.contextNode, xpc)) { + newNodes.push(xpc.contextNode); + } + // look at all descendant nodes + var st = [xpc.contextNode.firstChild]; + while (st.length > 0) { + for (var m = st.pop(); m != null;) { + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + if (m.firstChild != null) { + st.push(m.nextSibling); + m = m.firstChild; + } else { + m = m.nextSibling; + } + } + } + break; + + case Step.FOLLOWING: + if (xpc.contextNode === xpc.virtualRoot) { + break; + } + var st = []; + if (xpc.contextNode.firstChild != null) { + st.unshift(xpc.contextNode.firstChild); + } else { + st.unshift(xpc.contextNode.nextSibling); + } + for (var m = xpc.contextNode.parentNode; m != null && m.nodeType != 9 /*Node.DOCUMENT_NODE*/ && m !== xpc.virtualRoot; m = m.parentNode) { + st.unshift(m.nextSibling); + } + do { + for (var m = st.pop(); m != null;) { + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + if (m.firstChild != null) { + st.push(m.nextSibling); + m = m.firstChild; + } else { + m = m.nextSibling; + } + } + } while (st.length > 0); + break; + + case Step.FOLLOWINGSIBLING: + if (xpc.contextNode === xpc.virtualRoot) { + break; + } + for (var m = xpc.contextNode.nextSibling; m != null; m = m.nextSibling) { + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + } + break; + + case Step.NAMESPACE: + var n = {}; + if (xpc.contextNode.nodeType == 1 /*Node.ELEMENT_NODE*/) { + n["xml"] = XPath.XML_NAMESPACE_URI; + n["xmlns"] = XPath.XMLNS_NAMESPACE_URI; + for (var m = xpc.contextNode; m != null && m.nodeType == 1 /*Node.ELEMENT_NODE*/; m = m.parentNode) { + for (var k = 0; k < m.attributes.length; k++) { + var attr = m.attributes.item(k); + var nm = String(attr.name); + if (nm == "xmlns") { + if (n[""] == undefined) { + n[""] = attr.value; + } + } else if (nm.length > 6 && nm.substring(0, 6) == "xmlns:") { + var pre = nm.substring(6, nm.length); + if (n[pre] == undefined) { + n[pre] = attr.value; + } + } + } + } + for (var pre in n) { + var nsn = new XPathNamespace(pre, n[pre], xpc.contextNode); + if (step.nodeTest.matches(nsn, xpc)) { + newNodes.push(nsn); + } + } + } + break; + + case Step.PARENT: + m = null; + if (xpc.contextNode !== xpc.virtualRoot) { + if (xpc.contextNode.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) { + m = PathExpr.getOwnerElement(xpc.contextNode); + } else { + m = xpc.contextNode.parentNode; + } + } + if (m != null && step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + break; + + case Step.PRECEDING: + var st; + if (xpc.virtualRoot != null) { + st = [xpc.virtualRoot]; + } else { + // cannot rely on .ownerDocument because the node may be in a document fragment + st = [findRoot(xpc.contextNode)]; + } + outer: while (st.length > 0) { + for (var m = st.pop(); m != null;) { + if (m == xpc.contextNode) { + break outer; + } + if (step.nodeTest.matches(m, xpc)) { + newNodes.unshift(m); + } + if (m.firstChild != null) { + st.push(m.nextSibling); + m = m.firstChild; + } else { + m = m.nextSibling; + } + } + } + break; + + case Step.PRECEDINGSIBLING: + if (xpc.contextNode === xpc.virtualRoot) { + break; + } + for (var m = xpc.contextNode.previousSibling; m != null; m = m.previousSibling) { + if (step.nodeTest.matches(m, xpc)) { + newNodes.push(m); + } + } + break; + + case Step.SELF: + if (step.nodeTest.matches(xpc.contextNode, xpc)) { + newNodes.push(xpc.contextNode); + } + break; + + default: + } + + return newNodes; + }; + + function applyStepWithPredicates(step, xpc, node) { + return PathExpr.applyPredicates( + step.predicates, + xpc, + PathExpr.applyStep(step, xpc, node) + ); + } + + function applyStepToNodes(context, nodes, step) { + return flatten( + map( + applyStepWithPredicates.bind(null, step, context), + nodes + ) + ); + } + + PathExpr.applySteps = function (steps, xpc, nodes) { + return reduce( + applyStepToNodes.bind(null, xpc), + nodes, + steps + ); + } + + PathExpr.prototype.applyFilter = function (c, xpc) { + if (!this.filter) { + return { nodes: [c.contextNode] }; + } + + var ns = this.filter.evaluate(c); + + if (!Utilities.instance_of(ns, XNodeSet)) { + if (this.filterPredicates != null && this.filterPredicates.length > 0 || this.locationPath != null) { + throw new Error("Path expression filter must evaluate to a nodeset if predicates or location path are used"); + } + + return { nonNodes: ns }; + } + + return { + nodes: PathExpr.applyPredicates(this.filterPredicates || [], xpc, ns.toUnsortedArray()) + }; + }; + + PathExpr.applyLocationPath = function (locationPath, xpc, nodes) { + if (!locationPath) { + return nodes; + } + + var startNodes = locationPath.absolute ? [PathExpr.getRoot(xpc, nodes)] : nodes; + + return PathExpr.applySteps(locationPath.steps, xpc, startNodes); + }; + + PathExpr.prototype.evaluate = function (c) { + var xpc = assign(new XPathContext(), c); + + var filterResult = this.applyFilter(c, xpc); + + if ('nonNodes' in filterResult) { + return filterResult.nonNodes; + } + + var ns = new XNodeSet(); + ns.addArray(PathExpr.applyLocationPath(this.locationPath, xpc, filterResult.nodes)); + return ns; + }; + + PathExpr.predicateMatches = function (pred, c) { + var res = pred.evaluate(c); + + return Utilities.instance_of(res, XNumber) + ? c.contextPosition === res.numberValue() + : res.booleanValue(); + }; + + PathExpr.predicateString = function (predicate) { + return wrap('[', ']', predicate.toString()); + } + + PathExpr.predicatesString = function (predicates) { + return join( + '', + map(PathExpr.predicateString, predicates) + ); + } + + PathExpr.prototype.toString = function () { + if (this.filter != undefined) { + var filterStr = toString(this.filter); + + if (Utilities.instance_of(this.filter, XString)) { + return wrap("'", "'", filterStr); + } + if (this.filterPredicates != undefined && this.filterPredicates.length) { + return wrap('(', ')', filterStr) + + PathExpr.predicatesString(this.filterPredicates); + } + if (this.locationPath != undefined) { + return filterStr + + (this.locationPath.absolute ? '' : '/') + + toString(this.locationPath); + } + + return filterStr; + } + + return toString(this.locationPath); + }; + + PathExpr.getOwnerElement = function (n) { + // DOM 2 has ownerElement + if (n.ownerElement) { + return n.ownerElement; + } + // DOM 1 Internet Explorer can use selectSingleNode (ironically) + try { + if (n.selectSingleNode) { + return n.selectSingleNode(".."); + } + } catch (e) { + } + // Other DOM 1 implementations must use this egregious search + var doc = n.nodeType == 9 /*Node.DOCUMENT_NODE*/ + ? n + : n.ownerDocument; + var elts = doc.getElementsByTagName("*"); + for (var i = 0; i < elts.length; i++) { + var elt = elts.item(i); + var nnm = elt.attributes; + for (var j = 0; j < nnm.length; j++) { + var an = nnm.item(j); + if (an === n) { + return elt; + } + } + } + return null; + }; + + // LocationPath ////////////////////////////////////////////////////////////// + + LocationPath.prototype = new Object(); + LocationPath.prototype.constructor = LocationPath; + LocationPath.superclass = Object.prototype; + + function LocationPath(abs, steps) { + if (arguments.length > 0) { + this.init(abs, steps); + } + } + + LocationPath.prototype.init = function (abs, steps) { + this.absolute = abs; + this.steps = steps; + }; + + LocationPath.prototype.toString = function () { + return ( + (this.absolute ? '/' : '') + + map(toString, this.steps).join('/') + ); + }; + + // Step ////////////////////////////////////////////////////////////////////// + + Step.prototype = new Object(); + Step.prototype.constructor = Step; + Step.superclass = Object.prototype; + + function Step(axis, nodetest, preds) { + if (arguments.length > 0) { + this.init(axis, nodetest, preds); + } + } + + Step.prototype.init = function (axis, nodetest, preds) { + this.axis = axis; + this.nodeTest = nodetest; + this.predicates = preds; + }; + + Step.prototype.toString = function () { + return Step.STEPNAMES[this.axis] + + "::" + + this.nodeTest.toString() + + PathExpr.predicatesString(this.predicates); + }; + + + Step.ANCESTOR = 0; + Step.ANCESTORORSELF = 1; + Step.ATTRIBUTE = 2; + Step.CHILD = 3; + Step.DESCENDANT = 4; + Step.DESCENDANTORSELF = 5; + Step.FOLLOWING = 6; + Step.FOLLOWINGSIBLING = 7; + Step.NAMESPACE = 8; + Step.PARENT = 9; + Step.PRECEDING = 10; + Step.PRECEDINGSIBLING = 11; + Step.SELF = 12; + + Step.STEPNAMES = reduce(function (acc, x) { return acc[x[0]] = x[1], acc; }, {}, [ + [Step.ANCESTOR, 'ancestor'], + [Step.ANCESTORORSELF, 'ancestor-or-self'], + [Step.ATTRIBUTE, 'attribute'], + [Step.CHILD, 'child'], + [Step.DESCENDANT, 'descendant'], + [Step.DESCENDANTORSELF, 'descendant-or-self'], + [Step.FOLLOWING, 'following'], + [Step.FOLLOWINGSIBLING, 'following-sibling'], + [Step.NAMESPACE, 'namespace'], + [Step.PARENT, 'parent'], + [Step.PRECEDING, 'preceding'], + [Step.PRECEDINGSIBLING, 'preceding-sibling'], + [Step.SELF, 'self'] + ]); + + // NodeTest ////////////////////////////////////////////////////////////////// + + NodeTest.prototype = new Object(); + NodeTest.prototype.constructor = NodeTest; + NodeTest.superclass = Object.prototype; + + function NodeTest(type, value) { + if (arguments.length > 0) { + this.init(type, value); + } + } + + NodeTest.prototype.init = function (type, value) { + this.type = type; + this.value = value; + }; + + NodeTest.prototype.toString = function () { + return ""; + }; + + NodeTest.prototype.matches = function (n, xpc) { + console.warn('unknown node test type'); + }; + + NodeTest.NAMETESTANY = 0; + NodeTest.NAMETESTPREFIXANY = 1; + NodeTest.NAMETESTQNAME = 2; + NodeTest.COMMENT = 3; + NodeTest.TEXT = 4; + NodeTest.PI = 5; + NodeTest.NODE = 6; + + NodeTest.isNodeType = function (types) { + return function (node) { + return includes(types, node.nodeType); + }; + }; + + NodeTest.makeNodeTestType = function (type, members, ctor) { + var newType = ctor || function () { }; + + newType.prototype = new NodeTest(type); + newType.prototype.constructor = newType; + + assign(newType.prototype, members); + + return newType; + }; + // create invariant node test for certain node types + NodeTest.makeNodeTypeTest = function (type, nodeTypes, stringVal) { + return new (NodeTest.makeNodeTestType(type, { + matches: NodeTest.isNodeType(nodeTypes), + toString: always(stringVal) + }))(); + }; + + NodeTest.hasPrefix = function (node) { + return node.prefix || (node.nodeName || node.tagName).indexOf(':') !== -1; + }; + + NodeTest.isElementOrAttribute = NodeTest.isNodeType([1, 2]); + NodeTest.nameSpaceMatches = function (prefix, xpc, n) { + var nNamespace = (n.namespaceURI || ''); + + if (!prefix) { + return !nNamespace || (xpc.allowAnyNamespaceForNoPrefix && !NodeTest.hasPrefix(n)); + } + + var ns = xpc.namespaceResolver.getNamespace(prefix, xpc.expressionContextNode); + + if (ns == null) { + throw new Error("Cannot resolve QName " + prefix); + } + + return ns === nNamespace; + }; + NodeTest.localNameMatches = function (localName, xpc, n) { + var nLocalName = (n.localName || n.nodeName); + + return xpc.caseInsensitive + ? localName.toLowerCase() === nLocalName.toLowerCase() + : localName === nLocalName; + }; + + NodeTest.NameTestPrefixAny = NodeTest.makeNodeTestType( + NodeTest.NAMETESTPREFIXANY, + { + matches: function (n, xpc) { + return NodeTest.isElementOrAttribute(n) && + NodeTest.nameSpaceMatches(this.prefix, xpc, n); + }, + toString: function () { + return this.prefix + ":*"; + } + }, + function NameTestPrefixAny(prefix) { this.prefix = prefix; } + ); + + NodeTest.NameTestQName = NodeTest.makeNodeTestType( + NodeTest.NAMETESTQNAME, + { + matches: function (n, xpc) { + return NodeTest.isNodeType([1, 2, XPathNamespace.XPATH_NAMESPACE_NODE])(n) && + NodeTest.nameSpaceMatches(this.prefix, xpc, n) && + NodeTest.localNameMatches(this.localName, xpc, n); + }, + toString: function () { + return this.name; + } + }, + function NameTestQName(name) { + var nameParts = name.split(':'); + + this.name = name; + this.prefix = nameParts.length > 1 ? nameParts[0] : null; + this.localName = nameParts[nameParts.length > 1 ? 1 : 0]; + } + ); + + NodeTest.PITest = NodeTest.makeNodeTestType(NodeTest.PI, { + matches: function (n, xpc) { + return NodeTest.isNodeType([7])(n) && (n.target || n.nodeName) === this.name; + }, + toString: function () { + return wrap('processing-instruction("', '")', this.name); + } + }, function (name) { this.name = name; }) + + // singletons + + // elements, attributes, namespaces + NodeTest.nameTestAny = NodeTest.makeNodeTypeTest(NodeTest.NAMETESTANY, [1, 2, XPathNamespace.XPATH_NAMESPACE_NODE], '*'); + // text, cdata + NodeTest.textTest = NodeTest.makeNodeTypeTest(NodeTest.TEXT, [3, 4], 'text()'); + NodeTest.commentTest = NodeTest.makeNodeTypeTest(NodeTest.COMMENT, [8], 'comment()'); + // elements, attributes, text, cdata, PIs, comments, document nodes + NodeTest.nodeTest = NodeTest.makeNodeTypeTest(NodeTest.NODE, [1, 2, 3, 4, 7, 8, 9], 'node()'); + NodeTest.anyPiTest = NodeTest.makeNodeTypeTest(NodeTest.PI, [7], 'processing-instruction()'); + + // VariableReference ///////////////////////////////////////////////////////// + + VariableReference.prototype = new Expression(); + VariableReference.prototype.constructor = VariableReference; + VariableReference.superclass = Expression.prototype; + + function VariableReference(v) { + if (arguments.length > 0) { + this.init(v); + } + } + + VariableReference.prototype.init = function (v) { + this.variable = v; + }; + + VariableReference.prototype.toString = function () { + return "$" + this.variable; + }; + + VariableReference.prototype.evaluate = function (c) { + var parts = Utilities.resolveQName(this.variable, c.namespaceResolver, c.contextNode, false); + + if (parts[0] == null) { + throw new Error("Cannot resolve QName " + fn); + } + var result = c.variableResolver.getVariable(parts[1], parts[0]); + if (!result) { + throw XPathException.fromMessage("Undeclared variable: " + this.toString()); + } + return result; + }; + + // FunctionCall ////////////////////////////////////////////////////////////// + + FunctionCall.prototype = new Expression(); + FunctionCall.prototype.constructor = FunctionCall; + FunctionCall.superclass = Expression.prototype; + + function FunctionCall(fn, args) { + if (arguments.length > 0) { + this.init(fn, args); + } + } + + FunctionCall.prototype.init = function (fn, args) { + this.functionName = fn; + this.arguments = args; + }; + + FunctionCall.prototype.toString = function () { + var s = this.functionName + "("; + for (var i = 0; i < this.arguments.length; i++) { + if (i > 0) { + s += ", "; + } + s += this.arguments[i].toString(); + } + return s + ")"; + }; + + FunctionCall.prototype.evaluate = function (c) { + var f = FunctionResolver.getFunctionFromContext(this.functionName, c); + + if (!f) { + throw new Error("Unknown function " + this.functionName); + } + + var a = [c].concat(this.arguments); + return f.apply(c.functionResolver.thisArg, a); + }; + + // Operators ///////////////////////////////////////////////////////////////// + + var Operators = new Object(); + + Operators.equals = function (l, r) { + return l.equals(r); + }; + + Operators.notequal = function (l, r) { + return l.notequal(r); + }; + + Operators.lessthan = function (l, r) { + return l.lessthan(r); + }; + + Operators.greaterthan = function (l, r) { + return l.greaterthan(r); + }; + + Operators.lessthanorequal = function (l, r) { + return l.lessthanorequal(r); + }; + + Operators.greaterthanorequal = function (l, r) { + return l.greaterthanorequal(r); + }; + + // XString /////////////////////////////////////////////////////////////////// + + XString.prototype = new Expression(); + XString.prototype.constructor = XString; + XString.superclass = Expression.prototype; + + function XString(s) { + if (arguments.length > 0) { + this.init(s); + } + } + + XString.prototype.init = function (s) { + this.str = String(s); + }; + + XString.prototype.toString = function () { + return this.str; + }; + + XString.prototype.evaluate = function (c) { + return this; + }; + + XString.prototype.string = function () { + return this; + }; + + XString.prototype.number = function () { + return new XNumber(this.str); + }; + + XString.prototype.bool = function () { + return new XBoolean(this.str); + }; + + XString.prototype.nodeset = function () { + throw new Error("Cannot convert string to nodeset"); + }; + + XString.prototype.stringValue = function () { + return this.str; + }; + + XString.prototype.numberValue = function () { + return this.number().numberValue(); + }; + + XString.prototype.booleanValue = function () { + return this.bool().booleanValue(); + }; + + XString.prototype.equals = function (r) { + if (Utilities.instance_of(r, XBoolean)) { + return this.bool().equals(r); + } + if (Utilities.instance_of(r, XNumber)) { + return this.number().equals(r); + } + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithString(this, Operators.equals); + } + return new XBoolean(this.str == r.str); + }; + + XString.prototype.notequal = function (r) { + if (Utilities.instance_of(r, XBoolean)) { + return this.bool().notequal(r); + } + if (Utilities.instance_of(r, XNumber)) { + return this.number().notequal(r); + } + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithString(this, Operators.notequal); + } + return new XBoolean(this.str != r.str); + }; + + XString.prototype.lessthan = function (r) { + return this.number().lessthan(r); + }; + + XString.prototype.greaterthan = function (r) { + return this.number().greaterthan(r); + }; + + XString.prototype.lessthanorequal = function (r) { + return this.number().lessthanorequal(r); + }; + + XString.prototype.greaterthanorequal = function (r) { + return this.number().greaterthanorequal(r); + }; + + // XNumber /////////////////////////////////////////////////////////////////// + + XNumber.prototype = new Expression(); + XNumber.prototype.constructor = XNumber; + XNumber.superclass = Expression.prototype; + + function XNumber(n) { + if (arguments.length > 0) { + this.init(n); + } + } + + XNumber.prototype.init = function (n) { + this.num = typeof n === "string" ? this.parse(n) : Number(n); + }; + + XNumber.prototype.numberFormat = /^\s*-?[0-9]*\.?[0-9]+\s*$/; + + XNumber.prototype.parse = function (s) { + // XPath representation of numbers is more restrictive than what Number() or parseFloat() allow + return this.numberFormat.test(s) ? parseFloat(s) : Number.NaN; + }; + + function padSmallNumber(numberStr) { + var parts = numberStr.split('e-'); + var base = parts[0].replace('.', ''); + var exponent = Number(parts[1]); + + for (var i = 0; i < exponent - 1; i += 1) { + base = '0' + base; + } + + return '0.' + base; + } + + function padLargeNumber(numberStr) { + var parts = numberStr.split('e'); + var base = parts[0].replace('.', ''); + var exponent = Number(parts[1]); + var zerosToAppend = exponent + 1 - base.length; + + for (var i = 0; i < zerosToAppend; i += 1) { + base += '0'; + } + + return base; + } + + XNumber.prototype.toString = function () { + var strValue = this.num.toString(); + + if (strValue.indexOf('e-') !== -1) { + return padSmallNumber(strValue); + } + + if (strValue.indexOf('e') !== -1) { + return padLargeNumber(strValue); + } + + return strValue; + }; + + XNumber.prototype.evaluate = function (c) { + return this; + }; + + XNumber.prototype.string = function () { + + + return new XString(this.toString()); + }; + + XNumber.prototype.number = function () { + return this; + }; + + XNumber.prototype.bool = function () { + return new XBoolean(this.num); + }; + + XNumber.prototype.nodeset = function () { + throw new Error("Cannot convert number to nodeset"); + }; + + XNumber.prototype.stringValue = function () { + return this.string().stringValue(); + }; + + XNumber.prototype.numberValue = function () { + return this.num; + }; + + XNumber.prototype.booleanValue = function () { + return this.bool().booleanValue(); + }; + + XNumber.prototype.negate = function () { + return new XNumber(-this.num); + }; + + XNumber.prototype.equals = function (r) { + if (Utilities.instance_of(r, XBoolean)) { + return this.bool().equals(r); + } + if (Utilities.instance_of(r, XString)) { + return this.equals(r.number()); + } + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithNumber(this, Operators.equals); + } + return new XBoolean(this.num == r.num); + }; + + XNumber.prototype.notequal = function (r) { + if (Utilities.instance_of(r, XBoolean)) { + return this.bool().notequal(r); + } + if (Utilities.instance_of(r, XString)) { + return this.notequal(r.number()); + } + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithNumber(this, Operators.notequal); + } + return new XBoolean(this.num != r.num); + }; + + XNumber.prototype.lessthan = function (r) { + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithNumber(this, Operators.greaterthan); + } + if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { + return this.lessthan(r.number()); + } + return new XBoolean(this.num < r.num); + }; + + XNumber.prototype.greaterthan = function (r) { + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithNumber(this, Operators.lessthan); + } + if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { + return this.greaterthan(r.number()); + } + return new XBoolean(this.num > r.num); + }; + + XNumber.prototype.lessthanorequal = function (r) { + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithNumber(this, Operators.greaterthanorequal); + } + if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { + return this.lessthanorequal(r.number()); + } + return new XBoolean(this.num <= r.num); + }; + + XNumber.prototype.greaterthanorequal = function (r) { + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithNumber(this, Operators.lessthanorequal); + } + if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { + return this.greaterthanorequal(r.number()); + } + return new XBoolean(this.num >= r.num); + }; + + XNumber.prototype.plus = function (r) { + return new XNumber(this.num + r.num); + }; + + XNumber.prototype.minus = function (r) { + return new XNumber(this.num - r.num); + }; + + XNumber.prototype.multiply = function (r) { + return new XNumber(this.num * r.num); + }; + + XNumber.prototype.div = function (r) { + return new XNumber(this.num / r.num); + }; + + XNumber.prototype.mod = function (r) { + return new XNumber(this.num % r.num); + }; + + // XBoolean ////////////////////////////////////////////////////////////////// + + XBoolean.prototype = new Expression(); + XBoolean.prototype.constructor = XBoolean; + XBoolean.superclass = Expression.prototype; + + function XBoolean(b) { + if (arguments.length > 0) { + this.init(b); + } + } + + XBoolean.prototype.init = function (b) { + this.b = Boolean(b); + }; + + XBoolean.prototype.toString = function () { + return this.b.toString(); + }; + + XBoolean.prototype.evaluate = function (c) { + return this; + }; + + XBoolean.prototype.string = function () { + return new XString(this.b); + }; + + XBoolean.prototype.number = function () { + return new XNumber(this.b); + }; + + XBoolean.prototype.bool = function () { + return this; + }; + + XBoolean.prototype.nodeset = function () { + throw new Error("Cannot convert boolean to nodeset"); + }; + + XBoolean.prototype.stringValue = function () { + return this.string().stringValue(); + }; + + XBoolean.prototype.numberValue = function () { + return this.number().numberValue(); + }; + + XBoolean.prototype.booleanValue = function () { + return this.b; + }; + + XBoolean.prototype.not = function () { + return new XBoolean(!this.b); + }; + + XBoolean.prototype.equals = function (r) { + if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) { + return this.equals(r.bool()); + } + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithBoolean(this, Operators.equals); + } + return new XBoolean(this.b == r.b); + }; + + XBoolean.prototype.notequal = function (r) { + if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) { + return this.notequal(r.bool()); + } + if (Utilities.instance_of(r, XNodeSet)) { + return r.compareWithBoolean(this, Operators.notequal); + } + return new XBoolean(this.b != r.b); + }; + + XBoolean.prototype.lessthan = function (r) { + return this.number().lessthan(r); + }; + + XBoolean.prototype.greaterthan = function (r) { + return this.number().greaterthan(r); + }; + + XBoolean.prototype.lessthanorequal = function (r) { + return this.number().lessthanorequal(r); + }; + + XBoolean.prototype.greaterthanorequal = function (r) { + return this.number().greaterthanorequal(r); + }; + + XBoolean.true_ = new XBoolean(true); + XBoolean.false_ = new XBoolean(false); + + // AVLTree /////////////////////////////////////////////////////////////////// + + AVLTree.prototype = new Object(); + AVLTree.prototype.constructor = AVLTree; + AVLTree.superclass = Object.prototype; + + function AVLTree(n) { + this.init(n); + } + + AVLTree.prototype.init = function (n) { + this.left = null; + this.right = null; + this.node = n; + this.depth = 1; + }; + + AVLTree.prototype.balance = function () { + var ldepth = this.left == null ? 0 : this.left.depth; + var rdepth = this.right == null ? 0 : this.right.depth; + + if (ldepth > rdepth + 1) { + // LR or LL rotation + var lldepth = this.left.left == null ? 0 : this.left.left.depth; + var lrdepth = this.left.right == null ? 0 : this.left.right.depth; + + if (lldepth < lrdepth) { + // LR rotation consists of a RR rotation of the left child + this.left.rotateRR(); + // plus a LL rotation of this node, which happens anyway + } + this.rotateLL(); + } else if (ldepth + 1 < rdepth) { + // RR or RL rorarion + var rrdepth = this.right.right == null ? 0 : this.right.right.depth; + var rldepth = this.right.left == null ? 0 : this.right.left.depth; + + if (rldepth > rrdepth) { + // RR rotation consists of a LL rotation of the right child + this.right.rotateLL(); + // plus a RR rotation of this node, which happens anyway + } + this.rotateRR(); + } + }; + + AVLTree.prototype.rotateLL = function () { + // the left side is too long => rotate from the left (_not_ leftwards) + var nodeBefore = this.node; + var rightBefore = this.right; + this.node = this.left.node; + this.right = this.left; + this.left = this.left.left; + this.right.left = this.right.right; + this.right.right = rightBefore; + this.right.node = nodeBefore; + this.right.updateInNewLocation(); + this.updateInNewLocation(); + }; + + AVLTree.prototype.rotateRR = function () { + // the right side is too long => rotate from the right (_not_ rightwards) + var nodeBefore = this.node; + var leftBefore = this.left; + this.node = this.right.node; + this.left = this.right; + this.right = this.right.right; + this.left.right = this.left.left; + this.left.left = leftBefore; + this.left.node = nodeBefore; + this.left.updateInNewLocation(); + this.updateInNewLocation(); + }; + + AVLTree.prototype.updateInNewLocation = function () { + this.getDepthFromChildren(); + }; + + AVLTree.prototype.getDepthFromChildren = function () { + this.depth = this.node == null ? 0 : 1; + if (this.left != null) { + this.depth = this.left.depth + 1; + } + if (this.right != null && this.depth <= this.right.depth) { + this.depth = this.right.depth + 1; + } + }; + + function nodeOrder(n1, n2) { + if (n1 === n2) { + return 0; + } + + if (n1.compareDocumentPosition) { + var cpos = n1.compareDocumentPosition(n2); + + if (cpos & 0x01) { + // not in the same document; return an arbitrary result (is there a better way to do this) + return 1; + } + if (cpos & 0x0A) { + // n2 precedes or contains n1 + return 1; + } + if (cpos & 0x14) { + // n2 follows or is contained by n1 + return -1; + } + + return 0; + } + + var d1 = 0, + d2 = 0; + for (var m1 = n1; m1 != null; m1 = m1.parentNode || m1.ownerElement) { + d1++; + } + for (var m2 = n2; m2 != null; m2 = m2.parentNode || m2.ownerElement) { + d2++; + } + + // step up to same depth + if (d1 > d2) { + while (d1 > d2) { + n1 = n1.parentNode || n1.ownerElement; + d1--; + } + if (n1 === n2) { + return 1; + } + } else if (d2 > d1) { + while (d2 > d1) { + n2 = n2.parentNode || n2.ownerElement; + d2--; + } + if (n1 === n2) { + return -1; + } + } + + var n1Par = n1.parentNode || n1.ownerElement, + n2Par = n2.parentNode || n2.ownerElement; + + // find common parent + while (n1Par !== n2Par) { + n1 = n1Par; + n2 = n2Par; + n1Par = n1.parentNode || n1.ownerElement; + n2Par = n2.parentNode || n2.ownerElement; + } + + var n1isAttr = Utilities.isAttribute(n1); + var n2isAttr = Utilities.isAttribute(n2); + + if (n1isAttr && !n2isAttr) { + return -1; + } + if (!n1isAttr && n2isAttr) { + return 1; + } + + if (n1Par) { + var cn = n1isAttr ? n1Par.attributes : n1Par.childNodes, + len = cn.length; + for (var i = 0; i < len; i += 1) { + var n = cn[i]; + if (n === n1) { + return -1; + } + if (n === n2) { + return 1; + } + } + } + + throw new Error('Unexpected: could not determine node order'); + } + + AVLTree.prototype.add = function (n) { + if (n === this.node) { + return false; + } + + var o = nodeOrder(n, this.node); + + var ret = false; + if (o == -1) { + if (this.left == null) { + this.left = new AVLTree(n); + ret = true; + } else { + ret = this.left.add(n); + if (ret) { + this.balance(); + } + } + } else if (o == 1) { + if (this.right == null) { + this.right = new AVLTree(n); + ret = true; + } else { + ret = this.right.add(n); + if (ret) { + this.balance(); + } + } + } + + if (ret) { + this.getDepthFromChildren(); + } + return ret; + }; + + // XNodeSet ////////////////////////////////////////////////////////////////// + + XNodeSet.prototype = new Expression(); + XNodeSet.prototype.constructor = XNodeSet; + XNodeSet.superclass = Expression.prototype; + + function XNodeSet() { + this.init(); + } + + XNodeSet.prototype.init = function () { + this.tree = null; + this.nodes = []; + this.size = 0; + }; + + XNodeSet.prototype.toString = function () { + var p = this.first(); + if (p == null) { + return ""; + } + return this.stringForNode(p); + }; + + XNodeSet.prototype.evaluate = function (c) { + return this; + }; + + XNodeSet.prototype.string = function () { + return new XString(this.toString()); + }; + + XNodeSet.prototype.stringValue = function () { + return this.toString(); + }; + + XNodeSet.prototype.number = function () { + return new XNumber(this.string()); + }; + + XNodeSet.prototype.numberValue = function () { + return Number(this.string()); + }; + + XNodeSet.prototype.bool = function () { + return new XBoolean(this.booleanValue()); + }; + + XNodeSet.prototype.booleanValue = function () { + return !!this.size; + }; + + XNodeSet.prototype.nodeset = function () { + return this; + }; + + XNodeSet.prototype.stringForNode = function (n) { + if (n.nodeType == 9 /*Node.DOCUMENT_NODE*/ || + n.nodeType == 1 /*Node.ELEMENT_NODE */ || + n.nodeType === 11 /*Node.DOCUMENT_FRAGMENT*/) { + return this.stringForContainerNode(n); + } + if (n.nodeType === 2 /* Node.ATTRIBUTE_NODE */) { + return n.value || n.nodeValue; + } + if (n.isNamespaceNode) { + return n.namespace; + } + return n.nodeValue; + }; + + XNodeSet.prototype.stringForContainerNode = function (n) { + var s = ""; + for (var n2 = n.firstChild; n2 != null; n2 = n2.nextSibling) { + var nt = n2.nodeType; + // Element, Text, CDATA, Document, Document Fragment + if (nt === 1 || nt === 3 || nt === 4 || nt === 9 || nt === 11) { + s += this.stringForNode(n2); + } + } + return s; + }; + + XNodeSet.prototype.buildTree = function () { + if (!this.tree && this.nodes.length) { + this.tree = new AVLTree(this.nodes[0]); + for (var i = 1; i < this.nodes.length; i += 1) { + this.tree.add(this.nodes[i]); + } + } + + return this.tree; + }; + + XNodeSet.prototype.first = function () { + var p = this.buildTree(); + if (p == null) { + return null; + } + while (p.left != null) { + p = p.left; + } + return p.node; + }; + + XNodeSet.prototype.add = function (n) { + for (var i = 0; i < this.nodes.length; i += 1) { + if (n === this.nodes[i]) { + return; + } + } + + this.tree = null; + this.nodes.push(n); + this.size += 1; + }; + + XNodeSet.prototype.addArray = function (ns) { + var self = this; + + forEach(function (x) { self.add(x); }, ns); + }; + + /** + * Returns an array of the node set's contents in document order + */ + XNodeSet.prototype.toArray = function () { + var a = []; + this.toArrayRec(this.buildTree(), a); + return a; + }; + + XNodeSet.prototype.toArrayRec = function (t, a) { + if (t != null) { + this.toArrayRec(t.left, a); + a.push(t.node); + this.toArrayRec(t.right, a); + } + }; + + /** + * Returns an array of the node set's contents in arbitrary order + */ + XNodeSet.prototype.toUnsortedArray = function () { + return this.nodes.slice(); + }; + + XNodeSet.prototype.compareWithString = function (r, o) { + var a = this.toUnsortedArray(); + for (var i = 0; i < a.length; i++) { + var n = a[i]; + var l = new XString(this.stringForNode(n)); + var res = o(l, r); + if (res.booleanValue()) { + return res; + } + } + return new XBoolean(false); + }; + + XNodeSet.prototype.compareWithNumber = function (r, o) { + var a = this.toUnsortedArray(); + for (var i = 0; i < a.length; i++) { + var n = a[i]; + var l = new XNumber(this.stringForNode(n)); + var res = o(l, r); + if (res.booleanValue()) { + return res; + } + } + return new XBoolean(false); + }; + + XNodeSet.prototype.compareWithBoolean = function (r, o) { + return o(this.bool(), r); + }; + + XNodeSet.prototype.compareWithNodeSet = function (r, o) { + var arr = this.toUnsortedArray(); + var oInvert = function (lop, rop) { return o(rop, lop); }; + + for (var i = 0; i < arr.length; i++) { + var l = new XString(this.stringForNode(arr[i])); + + var res = r.compareWithString(l, oInvert); + if (res.booleanValue()) { + return res; + } + } + + return new XBoolean(false); + }; + + XNodeSet.compareWith = curry(function (o, r) { + if (Utilities.instance_of(r, XString)) { + return this.compareWithString(r, o); + } + if (Utilities.instance_of(r, XNumber)) { + return this.compareWithNumber(r, o); + } + if (Utilities.instance_of(r, XBoolean)) { + return this.compareWithBoolean(r, o); + } + return this.compareWithNodeSet(r, o); + }); + + XNodeSet.prototype.equals = XNodeSet.compareWith(Operators.equals); + XNodeSet.prototype.notequal = XNodeSet.compareWith(Operators.notequal); + XNodeSet.prototype.lessthan = XNodeSet.compareWith(Operators.lessthan); + XNodeSet.prototype.greaterthan = XNodeSet.compareWith(Operators.greaterthan); + XNodeSet.prototype.lessthanorequal = XNodeSet.compareWith(Operators.lessthanorequal); + XNodeSet.prototype.greaterthanorequal = XNodeSet.compareWith(Operators.greaterthanorequal); + + XNodeSet.prototype.union = function (r) { + var ns = new XNodeSet(); + ns.addArray(this.toUnsortedArray()); + ns.addArray(r.toUnsortedArray()); + return ns; + }; + + // XPathNamespace //////////////////////////////////////////////////////////// + + XPathNamespace.prototype = new Object(); + XPathNamespace.prototype.constructor = XPathNamespace; + XPathNamespace.superclass = Object.prototype; + + function XPathNamespace(pre, ns, p) { + this.isXPathNamespace = true; + this.ownerDocument = p.ownerDocument; + this.nodeName = "#namespace"; + this.prefix = pre; + this.localName = pre; + this.namespaceURI = ns; + this.nodeValue = ns; + this.ownerElement = p; + this.nodeType = XPathNamespace.XPATH_NAMESPACE_NODE; + } + + XPathNamespace.prototype.toString = function () { + return "{ \"" + this.prefix + "\", \"" + this.namespaceURI + "\" }"; + }; + + // XPathContext ////////////////////////////////////////////////////////////// + + XPathContext.prototype = new Object(); + XPathContext.prototype.constructor = XPathContext; + XPathContext.superclass = Object.prototype; + + function XPathContext(vr, nr, fr) { + this.variableResolver = vr != null ? vr : new VariableResolver(); + this.namespaceResolver = nr != null ? nr : new NamespaceResolver(); + this.functionResolver = fr != null ? fr : new FunctionResolver(); + } + + XPathContext.prototype.extend = function (newProps) { + return assign(new XPathContext(), this, newProps); + }; + + // VariableResolver ////////////////////////////////////////////////////////// + + VariableResolver.prototype = new Object(); + VariableResolver.prototype.constructor = VariableResolver; + VariableResolver.superclass = Object.prototype; + + function VariableResolver() { + } + + VariableResolver.prototype.getVariable = function (ln, ns) { + return null; + }; + + // FunctionResolver ////////////////////////////////////////////////////////// + + FunctionResolver.prototype = new Object(); + FunctionResolver.prototype.constructor = FunctionResolver; + FunctionResolver.superclass = Object.prototype; + + function FunctionResolver(thisArg) { + this.thisArg = thisArg != null ? thisArg : Functions; + this.functions = new Object(); + this.addStandardFunctions(); + } + + FunctionResolver.prototype.addStandardFunctions = function () { + this.functions["{}last"] = Functions.last; + this.functions["{}position"] = Functions.position; + this.functions["{}count"] = Functions.count; + this.functions["{}id"] = Functions.id; + this.functions["{}local-name"] = Functions.localName; + this.functions["{}namespace-uri"] = Functions.namespaceURI; + this.functions["{}name"] = Functions.name; + this.functions["{}string"] = Functions.string; + this.functions["{}concat"] = Functions.concat; + this.functions["{}starts-with"] = Functions.startsWith; + this.functions["{}contains"] = Functions.contains; + this.functions["{}substring-before"] = Functions.substringBefore; + this.functions["{}substring-after"] = Functions.substringAfter; + this.functions["{}substring"] = Functions.substring; + this.functions["{}string-length"] = Functions.stringLength; + this.functions["{}normalize-space"] = Functions.normalizeSpace; + this.functions["{}translate"] = Functions.translate; + this.functions["{}boolean"] = Functions.boolean_; + this.functions["{}not"] = Functions.not; + this.functions["{}true"] = Functions.true_; + this.functions["{}false"] = Functions.false_; + this.functions["{}lang"] = Functions.lang; + this.functions["{}number"] = Functions.number; + this.functions["{}sum"] = Functions.sum; + this.functions["{}floor"] = Functions.floor; + this.functions["{}ceiling"] = Functions.ceiling; + this.functions["{}round"] = Functions.round; + }; + + FunctionResolver.prototype.addFunction = function (ns, ln, f) { + this.functions["{" + ns + "}" + ln] = f; + }; + + FunctionResolver.getFunctionFromContext = function (qName, context) { + var parts = Utilities.resolveQName(qName, context.namespaceResolver, context.contextNode, false); + + if (parts[0] === null) { + throw new Error("Cannot resolve QName " + name); + } + + return context.functionResolver.getFunction(parts[1], parts[0]); + }; + + FunctionResolver.prototype.getFunction = function (localName, namespace) { + return this.functions["{" + namespace + "}" + localName]; + }; + + // NamespaceResolver ///////////////////////////////////////////////////////// + + NamespaceResolver.prototype = new Object(); + NamespaceResolver.prototype.constructor = NamespaceResolver; + NamespaceResolver.superclass = Object.prototype; + + function NamespaceResolver() { + } + + NamespaceResolver.prototype.getNamespace = function (prefix, n) { + if (prefix == "xml") { + return XPath.XML_NAMESPACE_URI; + } else if (prefix == "xmlns") { + return XPath.XMLNS_NAMESPACE_URI; + } + if (n.nodeType == 9 /*Node.DOCUMENT_NODE*/) { + n = n.documentElement; + } else if (n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) { + n = PathExpr.getOwnerElement(n); + } else if (n.nodeType != 1 /*Node.ELEMENT_NODE*/) { + n = n.parentNode; + } + while (n != null && n.nodeType == 1 /*Node.ELEMENT_NODE*/) { + var nnm = n.attributes; + for (var i = 0; i < nnm.length; i++) { + var a = nnm.item(i); + var aname = a.name || a.nodeName; + if ((aname === "xmlns" && prefix === "") + || aname === "xmlns:" + prefix) { + return String(a.value || a.nodeValue); + } + } + n = n.parentNode; + } + return null; + }; + + // Functions ///////////////////////////////////////////////////////////////// + + var Functions = new Object(); + + Functions.last = function (c) { + if (arguments.length != 1) { + throw new Error("Function last expects ()"); + } + + return new XNumber(c.contextSize); + }; + + Functions.position = function (c) { + if (arguments.length != 1) { + throw new Error("Function position expects ()"); + } + + return new XNumber(c.contextPosition); + }; + + Functions.count = function () { + var c = arguments[0]; + var ns; + if (arguments.length != 2 || !Utilities.instance_of(ns = arguments[1].evaluate(c), XNodeSet)) { + throw new Error("Function count expects (node-set)"); + } + return new XNumber(ns.size); + }; + + Functions.id = function () { + var c = arguments[0]; + var id; + if (arguments.length != 2) { + throw new Error("Function id expects (object)"); + } + id = arguments[1].evaluate(c); + if (Utilities.instance_of(id, XNodeSet)) { + id = id.toArray().join(" "); + } else { + id = id.stringValue(); + } + var ids = id.split(/[\x0d\x0a\x09\x20]+/); + var count = 0; + var ns = new XNodeSet(); + var doc = c.contextNode.nodeType == 9 /*Node.DOCUMENT_NODE*/ + ? c.contextNode + : c.contextNode.ownerDocument; + for (var i = 0; i < ids.length; i++) { + var n; + if (doc.getElementById) { + n = doc.getElementById(ids[i]); + } else { + n = Utilities.getElementById(doc, ids[i]); + } + if (n != null) { + ns.add(n); + count++; + } + } + return ns; + }; + + Functions.localName = function (c, eNode) { + var n; + + if (arguments.length == 1) { + n = c.contextNode; + } else if (arguments.length == 2) { + n = eNode.evaluate(c).first(); + } else { + throw new Error("Function local-name expects (node-set?)"); + } + + if (n == null) { + return new XString(""); + } + + return new XString( + n.localName || // standard elements and attributes + n.baseName || // IE + n.target || // processing instructions + n.nodeName || // DOM1 elements + "" // fallback + ); + }; + + Functions.namespaceURI = function () { + var c = arguments[0]; + var n; + if (arguments.length == 1) { + n = c.contextNode; + } else if (arguments.length == 2) { + n = arguments[1].evaluate(c).first(); + } else { + throw new Error("Function namespace-uri expects (node-set?)"); + } + if (n == null) { + return new XString(""); + } + return new XString(n.namespaceURI); + }; + + Functions.name = function () { + var c = arguments[0]; + var n; + if (arguments.length == 1) { + n = c.contextNode; + } else if (arguments.length == 2) { + n = arguments[1].evaluate(c).first(); + } else { + throw new Error("Function name expects (node-set?)"); + } + if (n == null) { + return new XString(""); + } + if (n.nodeType == 1 /*Node.ELEMENT_NODE*/) { + return new XString(n.nodeName); + } else if (n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) { + return new XString(n.name || n.nodeName); + } else if (n.nodeType === 7 /*Node.PROCESSING_INSTRUCTION_NODE*/) { + return new XString(n.target || n.nodeName); + } else if (n.localName == null) { + return new XString(""); + } else { + return new XString(n.localName); + } + }; + + Functions.string = function () { + var c = arguments[0]; + if (arguments.length == 1) { + return new XString(XNodeSet.prototype.stringForNode(c.contextNode)); + } else if (arguments.length == 2) { + return arguments[1].evaluate(c).string(); + } + throw new Error("Function string expects (object?)"); + }; -OrOperation.prototype.toString = function() { - return "(" + this.lhs.toString() + " or " + this.rhs.toString() + ")"; -}; + Functions.concat = function (c) { + if (arguments.length < 3) { + throw new Error("Function concat expects (string, string[, string]*)"); + } + var s = ""; + for (var i = 1; i < arguments.length; i++) { + s += arguments[i].evaluate(c).stringValue(); + } + return new XString(s); + }; -OrOperation.prototype.evaluate = function(c) { - var b = this.lhs.evaluate(c).bool(); - if (b.booleanValue()) { - return b; - } - return this.rhs.evaluate(c).bool(); -}; - -// AndOperation ////////////////////////////////////////////////////////////// - -AndOperation.prototype = new BinaryOperation(); -AndOperation.prototype.constructor = AndOperation; -AndOperation.superclass = BinaryOperation.prototype; - -function AndOperation(lhs, rhs) { - if (arguments.length > 0) { - this.init(lhs, rhs); - } -} - -AndOperation.prototype.init = function(lhs, rhs) { - AndOperation.superclass.init.call(this, lhs, rhs); -}; - -AndOperation.prototype.toString = function() { - return "(" + this.lhs.toString() + " and " + this.rhs.toString() + ")"; -}; - -AndOperation.prototype.evaluate = function(c) { - var b = this.lhs.evaluate(c).bool(); - if (!b.booleanValue()) { - return b; - } - return this.rhs.evaluate(c).bool(); -}; - -// EqualsOperation /////////////////////////////////////////////////////////// - -EqualsOperation.prototype = new BinaryOperation(); -EqualsOperation.prototype.constructor = EqualsOperation; -EqualsOperation.superclass = BinaryOperation.prototype; - -function EqualsOperation(lhs, rhs) { - if (arguments.length > 0) { - this.init(lhs, rhs); - } -} - -EqualsOperation.prototype.init = function(lhs, rhs) { - EqualsOperation.superclass.init.call(this, lhs, rhs); -}; - -EqualsOperation.prototype.toString = function() { - return "(" + this.lhs.toString() + " = " + this.rhs.toString() + ")"; -}; - -EqualsOperation.prototype.evaluate = function(c) { - return this.lhs.evaluate(c).equals(this.rhs.evaluate(c)); -}; - -// NotEqualOperation ///////////////////////////////////////////////////////// - -NotEqualOperation.prototype = new BinaryOperation(); -NotEqualOperation.prototype.constructor = NotEqualOperation; -NotEqualOperation.superclass = BinaryOperation.prototype; - -function NotEqualOperation(lhs, rhs) { - if (arguments.length > 0) { - this.init(lhs, rhs); - } -} - -NotEqualOperation.prototype.init = function(lhs, rhs) { - NotEqualOperation.superclass.init.call(this, lhs, rhs); -}; - -NotEqualOperation.prototype.toString = function() { - return "(" + this.lhs.toString() + " != " + this.rhs.toString() + ")"; -}; - -NotEqualOperation.prototype.evaluate = function(c) { - return this.lhs.evaluate(c).notequal(this.rhs.evaluate(c)); -}; - -// LessThanOperation ///////////////////////////////////////////////////////// - -LessThanOperation.prototype = new BinaryOperation(); -LessThanOperation.prototype.constructor = LessThanOperation; -LessThanOperation.superclass = BinaryOperation.prototype; - -function LessThanOperation(lhs, rhs) { - if (arguments.length > 0) { - this.init(lhs, rhs); - } -} - -LessThanOperation.prototype.init = function(lhs, rhs) { - LessThanOperation.superclass.init.call(this, lhs, rhs); -}; - -LessThanOperation.prototype.evaluate = function(c) { - return this.lhs.evaluate(c).lessthan(this.rhs.evaluate(c)); -}; - -LessThanOperation.prototype.toString = function() { - return "(" + this.lhs.toString() + " < " + this.rhs.toString() + ")"; -}; + Functions.startsWith = function () { + var c = arguments[0]; + if (arguments.length != 3) { + throw new Error("Function startsWith expects (string, string)"); + } + var s1 = arguments[1].evaluate(c).stringValue(); + var s2 = arguments[2].evaluate(c).stringValue(); + return new XBoolean(s1.substring(0, s2.length) == s2); + }; -// GreaterThanOperation ////////////////////////////////////////////////////// + Functions.contains = function () { + var c = arguments[0]; + if (arguments.length != 3) { + throw new Error("Function contains expects (string, string)"); + } + var s1 = arguments[1].evaluate(c).stringValue(); + var s2 = arguments[2].evaluate(c).stringValue(); + return new XBoolean(s1.indexOf(s2) !== -1); + }; -GreaterThanOperation.prototype = new BinaryOperation(); -GreaterThanOperation.prototype.constructor = GreaterThanOperation; -GreaterThanOperation.superclass = BinaryOperation.prototype; - -function GreaterThanOperation(lhs, rhs) { - if (arguments.length > 0) { - this.init(lhs, rhs); - } -} + Functions.substringBefore = function () { + var c = arguments[0]; + if (arguments.length != 3) { + throw new Error("Function substring-before expects (string, string)"); + } + var s1 = arguments[1].evaluate(c).stringValue(); + var s2 = arguments[2].evaluate(c).stringValue(); + return new XString(s1.substring(0, s1.indexOf(s2))); + }; -GreaterThanOperation.prototype.init = function(lhs, rhs) { - GreaterThanOperation.superclass.init.call(this, lhs, rhs); -}; + Functions.substringAfter = function () { + var c = arguments[0]; + if (arguments.length != 3) { + throw new Error("Function substring-after expects (string, string)"); + } + var s1 = arguments[1].evaluate(c).stringValue(); + var s2 = arguments[2].evaluate(c).stringValue(); + if (s2.length == 0) { + return new XString(s1); + } + var i = s1.indexOf(s2); + if (i == -1) { + return new XString(""); + } + return new XString(s1.substring(i + s2.length)); + }; -GreaterThanOperation.prototype.evaluate = function(c) { - return this.lhs.evaluate(c).greaterthan(this.rhs.evaluate(c)); -}; + Functions.substring = function () { + var c = arguments[0]; + if (!(arguments.length == 3 || arguments.length == 4)) { + throw new Error("Function substring expects (string, number, number?)"); + } + var s = arguments[1].evaluate(c).stringValue(); + var n1 = Math.round(arguments[2].evaluate(c).numberValue()) - 1; + var n2 = arguments.length == 4 ? n1 + Math.round(arguments[3].evaluate(c).numberValue()) : undefined; + return new XString(s.substring(n1, n2)); + }; -GreaterThanOperation.prototype.toString = function() { - return "(" + this.lhs.toString() + " > " + this.rhs.toString() + ")"; -}; + Functions.stringLength = function () { + var c = arguments[0]; + var s; + if (arguments.length == 1) { + s = XNodeSet.prototype.stringForNode(c.contextNode); + } else if (arguments.length == 2) { + s = arguments[1].evaluate(c).stringValue(); + } else { + throw new Error("Function string-length expects (string?)"); + } + return new XNumber(s.length); + }; -// LessThanOrEqualOperation ////////////////////////////////////////////////// + Functions.normalizeSpace = function () { + var c = arguments[0]; + var s; + if (arguments.length == 1) { + s = XNodeSet.prototype.stringForNode(c.contextNode); + } else if (arguments.length == 2) { + s = arguments[1].evaluate(c).stringValue(); + } else { + throw new Error("Function normalize-space expects (string?)"); + } + var i = 0; + var j = s.length - 1; + while (Utilities.isSpace(s.charCodeAt(j))) { + j--; + } + var t = ""; + while (i <= j && Utilities.isSpace(s.charCodeAt(i))) { + i++; + } + while (i <= j) { + if (Utilities.isSpace(s.charCodeAt(i))) { + t += " "; + while (i <= j && Utilities.isSpace(s.charCodeAt(i))) { + i++; + } + } else { + t += s.charAt(i); + i++; + } + } + return new XString(t); + }; -LessThanOrEqualOperation.prototype = new BinaryOperation(); -LessThanOrEqualOperation.prototype.constructor = LessThanOrEqualOperation; -LessThanOrEqualOperation.superclass = BinaryOperation.prototype; + Functions.translate = function (c, eValue, eFrom, eTo) { + if (arguments.length != 4) { + throw new Error("Function translate expects (string, string, string)"); + } -function LessThanOrEqualOperation(lhs, rhs) { - if (arguments.length > 0) { - this.init(lhs, rhs); - } -} + var value = eValue.evaluate(c).stringValue(); + var from = eFrom.evaluate(c).stringValue(); + var to = eTo.evaluate(c).stringValue(); -LessThanOrEqualOperation.prototype.init = function(lhs, rhs) { - LessThanOrEqualOperation.superclass.init.call(this, lhs, rhs); -}; + var cMap = reduce(function (acc, ch, i) { + if (!(ch in acc)) { + acc[ch] = i > to.length ? '' : to[i]; + } + return acc; + }, {}, from); -LessThanOrEqualOperation.prototype.evaluate = function(c) { - return this.lhs.evaluate(c).lessthanorequal(this.rhs.evaluate(c)); -}; + var t = join( + '', + map(function (ch) { + return ch in cMap ? cMap[ch] : ch; + }, value) + ); -LessThanOrEqualOperation.prototype.toString = function() { - return "(" + this.lhs.toString() + " <= " + this.rhs.toString() + ")"; -}; + return new XString(t); + }; -// GreaterThanOrEqualOperation /////////////////////////////////////////////// + Functions.boolean_ = function () { + var c = arguments[0]; + if (arguments.length != 2) { + throw new Error("Function boolean expects (object)"); + } + return arguments[1].evaluate(c).bool(); + }; -GreaterThanOrEqualOperation.prototype = new BinaryOperation(); -GreaterThanOrEqualOperation.prototype.constructor = GreaterThanOrEqualOperation; -GreaterThanOrEqualOperation.superclass = BinaryOperation.prototype; + Functions.not = function (c, eValue) { + if (arguments.length != 2) { + throw new Error("Function not expects (object)"); + } + return eValue.evaluate(c).bool().not(); + }; -function GreaterThanOrEqualOperation(lhs, rhs) { - if (arguments.length > 0) { - this.init(lhs, rhs); - } -} + Functions.true_ = function () { + if (arguments.length != 1) { + throw new Error("Function true expects ()"); + } + return XBoolean.true_; + }; -GreaterThanOrEqualOperation.prototype.init = function(lhs, rhs) { - GreaterThanOrEqualOperation.superclass.init.call(this, lhs, rhs); -}; + Functions.false_ = function () { + if (arguments.length != 1) { + throw new Error("Function false expects ()"); + } + return XBoolean.false_; + }; -GreaterThanOrEqualOperation.prototype.evaluate = function(c) { - return this.lhs.evaluate(c).greaterthanorequal(this.rhs.evaluate(c)); -}; + Functions.lang = function () { + var c = arguments[0]; + if (arguments.length != 2) { + throw new Error("Function lang expects (string)"); + } + var lang; + for (var n = c.contextNode; n != null && n.nodeType != 9 /*Node.DOCUMENT_NODE*/; n = n.parentNode) { + var a = n.getAttributeNS(XPath.XML_NAMESPACE_URI, "lang"); + if (a != null) { + lang = String(a); + break; + } + } + if (lang == null) { + return XBoolean.false_; + } + var s = arguments[1].evaluate(c).stringValue(); + return new XBoolean(lang.substring(0, s.length) == s + && (lang.length == s.length || lang.charAt(s.length) == '-')); + }; -GreaterThanOrEqualOperation.prototype.toString = function() { - return "(" + this.lhs.toString() + " >= " + this.rhs.toString() + ")"; -}; + Functions.number = function () { + var c = arguments[0]; + if (!(arguments.length == 1 || arguments.length == 2)) { + throw new Error("Function number expects (object?)"); + } + if (arguments.length == 1) { + return new XNumber(XNodeSet.prototype.stringForNode(c.contextNode)); + } + return arguments[1].evaluate(c).number(); + }; -// PlusOperation ///////////////////////////////////////////////////////////// + Functions.sum = function () { + var c = arguments[0]; + var ns; + if (arguments.length != 2 || !Utilities.instance_of((ns = arguments[1].evaluate(c)), XNodeSet)) { + throw new Error("Function sum expects (node-set)"); + } + ns = ns.toUnsortedArray(); + var n = 0; + for (var i = 0; i < ns.length; i++) { + n += new XNumber(XNodeSet.prototype.stringForNode(ns[i])).numberValue(); + } + return new XNumber(n); + }; -PlusOperation.prototype = new BinaryOperation(); -PlusOperation.prototype.constructor = PlusOperation; -PlusOperation.superclass = BinaryOperation.prototype; + Functions.floor = function () { + var c = arguments[0]; + if (arguments.length != 2) { + throw new Error("Function floor expects (number)"); + } + return new XNumber(Math.floor(arguments[1].evaluate(c).numberValue())); + }; -function PlusOperation(lhs, rhs) { - if (arguments.length > 0) { - this.init(lhs, rhs); - } -} + Functions.ceiling = function () { + var c = arguments[0]; + if (arguments.length != 2) { + throw new Error("Function ceiling expects (number)"); + } + return new XNumber(Math.ceil(arguments[1].evaluate(c).numberValue())); + }; -PlusOperation.prototype.init = function(lhs, rhs) { - PlusOperation.superclass.init.call(this, lhs, rhs); -}; + Functions.round = function () { + var c = arguments[0]; + if (arguments.length != 2) { + throw new Error("Function round expects (number)"); + } + return new XNumber(Math.round(arguments[1].evaluate(c).numberValue())); + }; -PlusOperation.prototype.evaluate = function(c) { - return this.lhs.evaluate(c).number().plus(this.rhs.evaluate(c).number()); -}; + // Utilities ///////////////////////////////////////////////////////////////// -PlusOperation.prototype.toString = function() { - return "(" + this.lhs.toString() + " + " + this.rhs.toString() + ")"; -}; + var Utilities = new Object(); -// MinusOperation //////////////////////////////////////////////////////////// + Utilities.isAttribute = function (val) { + return val && (val.nodeType === 2 || val.ownerElement); + } -MinusOperation.prototype = new BinaryOperation(); -MinusOperation.prototype.constructor = MinusOperation; -MinusOperation.superclass = BinaryOperation.prototype; + Utilities.splitQName = function (qn) { + var i = qn.indexOf(":"); + if (i == -1) { + return [null, qn]; + } + return [qn.substring(0, i), qn.substring(i + 1)]; + }; -function MinusOperation(lhs, rhs) { - if (arguments.length > 0) { - this.init(lhs, rhs); - } -} + Utilities.resolveQName = function (qn, nr, n, useDefault) { + var parts = Utilities.splitQName(qn); + if (parts[0] != null) { + parts[0] = nr.getNamespace(parts[0], n); + } else { + if (useDefault) { + parts[0] = nr.getNamespace("", n); + if (parts[0] == null) { + parts[0] = ""; + } + } else { + parts[0] = ""; + } + } + return parts; + }; -MinusOperation.prototype.init = function(lhs, rhs) { - MinusOperation.superclass.init.call(this, lhs, rhs); -}; + Utilities.isSpace = function (c) { + return c == 0x9 || c == 0xd || c == 0xa || c == 0x20; + }; -MinusOperation.prototype.evaluate = function(c) { - return this.lhs.evaluate(c).number().minus(this.rhs.evaluate(c).number()); -}; + Utilities.isLetter = function (c) { + return c >= 0x0041 && c <= 0x005A || + c >= 0x0061 && c <= 0x007A || + c >= 0x00C0 && c <= 0x00D6 || + c >= 0x00D8 && c <= 0x00F6 || + c >= 0x00F8 && c <= 0x00FF || + c >= 0x0100 && c <= 0x0131 || + c >= 0x0134 && c <= 0x013E || + c >= 0x0141 && c <= 0x0148 || + c >= 0x014A && c <= 0x017E || + c >= 0x0180 && c <= 0x01C3 || + c >= 0x01CD && c <= 0x01F0 || + c >= 0x01F4 && c <= 0x01F5 || + c >= 0x01FA && c <= 0x0217 || + c >= 0x0250 && c <= 0x02A8 || + c >= 0x02BB && c <= 0x02C1 || + c == 0x0386 || + c >= 0x0388 && c <= 0x038A || + c == 0x038C || + c >= 0x038E && c <= 0x03A1 || + c >= 0x03A3 && c <= 0x03CE || + c >= 0x03D0 && c <= 0x03D6 || + c == 0x03DA || + c == 0x03DC || + c == 0x03DE || + c == 0x03E0 || + c >= 0x03E2 && c <= 0x03F3 || + c >= 0x0401 && c <= 0x040C || + c >= 0x040E && c <= 0x044F || + c >= 0x0451 && c <= 0x045C || + c >= 0x045E && c <= 0x0481 || + c >= 0x0490 && c <= 0x04C4 || + c >= 0x04C7 && c <= 0x04C8 || + c >= 0x04CB && c <= 0x04CC || + c >= 0x04D0 && c <= 0x04EB || + c >= 0x04EE && c <= 0x04F5 || + c >= 0x04F8 && c <= 0x04F9 || + c >= 0x0531 && c <= 0x0556 || + c == 0x0559 || + c >= 0x0561 && c <= 0x0586 || + c >= 0x05D0 && c <= 0x05EA || + c >= 0x05F0 && c <= 0x05F2 || + c >= 0x0621 && c <= 0x063A || + c >= 0x0641 && c <= 0x064A || + c >= 0x0671 && c <= 0x06B7 || + c >= 0x06BA && c <= 0x06BE || + c >= 0x06C0 && c <= 0x06CE || + c >= 0x06D0 && c <= 0x06D3 || + c == 0x06D5 || + c >= 0x06E5 && c <= 0x06E6 || + c >= 0x0905 && c <= 0x0939 || + c == 0x093D || + c >= 0x0958 && c <= 0x0961 || + c >= 0x0985 && c <= 0x098C || + c >= 0x098F && c <= 0x0990 || + c >= 0x0993 && c <= 0x09A8 || + c >= 0x09AA && c <= 0x09B0 || + c == 0x09B2 || + c >= 0x09B6 && c <= 0x09B9 || + c >= 0x09DC && c <= 0x09DD || + c >= 0x09DF && c <= 0x09E1 || + c >= 0x09F0 && c <= 0x09F1 || + c >= 0x0A05 && c <= 0x0A0A || + c >= 0x0A0F && c <= 0x0A10 || + c >= 0x0A13 && c <= 0x0A28 || + c >= 0x0A2A && c <= 0x0A30 || + c >= 0x0A32 && c <= 0x0A33 || + c >= 0x0A35 && c <= 0x0A36 || + c >= 0x0A38 && c <= 0x0A39 || + c >= 0x0A59 && c <= 0x0A5C || + c == 0x0A5E || + c >= 0x0A72 && c <= 0x0A74 || + c >= 0x0A85 && c <= 0x0A8B || + c == 0x0A8D || + c >= 0x0A8F && c <= 0x0A91 || + c >= 0x0A93 && c <= 0x0AA8 || + c >= 0x0AAA && c <= 0x0AB0 || + c >= 0x0AB2 && c <= 0x0AB3 || + c >= 0x0AB5 && c <= 0x0AB9 || + c == 0x0ABD || + c == 0x0AE0 || + c >= 0x0B05 && c <= 0x0B0C || + c >= 0x0B0F && c <= 0x0B10 || + c >= 0x0B13 && c <= 0x0B28 || + c >= 0x0B2A && c <= 0x0B30 || + c >= 0x0B32 && c <= 0x0B33 || + c >= 0x0B36 && c <= 0x0B39 || + c == 0x0B3D || + c >= 0x0B5C && c <= 0x0B5D || + c >= 0x0B5F && c <= 0x0B61 || + c >= 0x0B85 && c <= 0x0B8A || + c >= 0x0B8E && c <= 0x0B90 || + c >= 0x0B92 && c <= 0x0B95 || + c >= 0x0B99 && c <= 0x0B9A || + c == 0x0B9C || + c >= 0x0B9E && c <= 0x0B9F || + c >= 0x0BA3 && c <= 0x0BA4 || + c >= 0x0BA8 && c <= 0x0BAA || + c >= 0x0BAE && c <= 0x0BB5 || + c >= 0x0BB7 && c <= 0x0BB9 || + c >= 0x0C05 && c <= 0x0C0C || + c >= 0x0C0E && c <= 0x0C10 || + c >= 0x0C12 && c <= 0x0C28 || + c >= 0x0C2A && c <= 0x0C33 || + c >= 0x0C35 && c <= 0x0C39 || + c >= 0x0C60 && c <= 0x0C61 || + c >= 0x0C85 && c <= 0x0C8C || + c >= 0x0C8E && c <= 0x0C90 || + c >= 0x0C92 && c <= 0x0CA8 || + c >= 0x0CAA && c <= 0x0CB3 || + c >= 0x0CB5 && c <= 0x0CB9 || + c == 0x0CDE || + c >= 0x0CE0 && c <= 0x0CE1 || + c >= 0x0D05 && c <= 0x0D0C || + c >= 0x0D0E && c <= 0x0D10 || + c >= 0x0D12 && c <= 0x0D28 || + c >= 0x0D2A && c <= 0x0D39 || + c >= 0x0D60 && c <= 0x0D61 || + c >= 0x0E01 && c <= 0x0E2E || + c == 0x0E30 || + c >= 0x0E32 && c <= 0x0E33 || + c >= 0x0E40 && c <= 0x0E45 || + c >= 0x0E81 && c <= 0x0E82 || + c == 0x0E84 || + c >= 0x0E87 && c <= 0x0E88 || + c == 0x0E8A || + c == 0x0E8D || + c >= 0x0E94 && c <= 0x0E97 || + c >= 0x0E99 && c <= 0x0E9F || + c >= 0x0EA1 && c <= 0x0EA3 || + c == 0x0EA5 || + c == 0x0EA7 || + c >= 0x0EAA && c <= 0x0EAB || + c >= 0x0EAD && c <= 0x0EAE || + c == 0x0EB0 || + c >= 0x0EB2 && c <= 0x0EB3 || + c == 0x0EBD || + c >= 0x0EC0 && c <= 0x0EC4 || + c >= 0x0F40 && c <= 0x0F47 || + c >= 0x0F49 && c <= 0x0F69 || + c >= 0x10A0 && c <= 0x10C5 || + c >= 0x10D0 && c <= 0x10F6 || + c == 0x1100 || + c >= 0x1102 && c <= 0x1103 || + c >= 0x1105 && c <= 0x1107 || + c == 0x1109 || + c >= 0x110B && c <= 0x110C || + c >= 0x110E && c <= 0x1112 || + c == 0x113C || + c == 0x113E || + c == 0x1140 || + c == 0x114C || + c == 0x114E || + c == 0x1150 || + c >= 0x1154 && c <= 0x1155 || + c == 0x1159 || + c >= 0x115F && c <= 0x1161 || + c == 0x1163 || + c == 0x1165 || + c == 0x1167 || + c == 0x1169 || + c >= 0x116D && c <= 0x116E || + c >= 0x1172 && c <= 0x1173 || + c == 0x1175 || + c == 0x119E || + c == 0x11A8 || + c == 0x11AB || + c >= 0x11AE && c <= 0x11AF || + c >= 0x11B7 && c <= 0x11B8 || + c == 0x11BA || + c >= 0x11BC && c <= 0x11C2 || + c == 0x11EB || + c == 0x11F0 || + c == 0x11F9 || + c >= 0x1E00 && c <= 0x1E9B || + c >= 0x1EA0 && c <= 0x1EF9 || + c >= 0x1F00 && c <= 0x1F15 || + c >= 0x1F18 && c <= 0x1F1D || + c >= 0x1F20 && c <= 0x1F45 || + c >= 0x1F48 && c <= 0x1F4D || + c >= 0x1F50 && c <= 0x1F57 || + c == 0x1F59 || + c == 0x1F5B || + c == 0x1F5D || + c >= 0x1F5F && c <= 0x1F7D || + c >= 0x1F80 && c <= 0x1FB4 || + c >= 0x1FB6 && c <= 0x1FBC || + c == 0x1FBE || + c >= 0x1FC2 && c <= 0x1FC4 || + c >= 0x1FC6 && c <= 0x1FCC || + c >= 0x1FD0 && c <= 0x1FD3 || + c >= 0x1FD6 && c <= 0x1FDB || + c >= 0x1FE0 && c <= 0x1FEC || + c >= 0x1FF2 && c <= 0x1FF4 || + c >= 0x1FF6 && c <= 0x1FFC || + c == 0x2126 || + c >= 0x212A && c <= 0x212B || + c == 0x212E || + c >= 0x2180 && c <= 0x2182 || + c >= 0x3041 && c <= 0x3094 || + c >= 0x30A1 && c <= 0x30FA || + c >= 0x3105 && c <= 0x312C || + c >= 0xAC00 && c <= 0xD7A3 || + c >= 0x4E00 && c <= 0x9FA5 || + c == 0x3007 || + c >= 0x3021 && c <= 0x3029; + }; -MinusOperation.prototype.toString = function() { - return "(" + this.lhs.toString() + " - " + this.rhs.toString() + ")"; -}; + Utilities.isNCNameChar = function (c) { + return c >= 0x0030 && c <= 0x0039 + || c >= 0x0660 && c <= 0x0669 + || c >= 0x06F0 && c <= 0x06F9 + || c >= 0x0966 && c <= 0x096F + || c >= 0x09E6 && c <= 0x09EF + || c >= 0x0A66 && c <= 0x0A6F + || c >= 0x0AE6 && c <= 0x0AEF + || c >= 0x0B66 && c <= 0x0B6F + || c >= 0x0BE7 && c <= 0x0BEF + || c >= 0x0C66 && c <= 0x0C6F + || c >= 0x0CE6 && c <= 0x0CEF + || c >= 0x0D66 && c <= 0x0D6F + || c >= 0x0E50 && c <= 0x0E59 + || c >= 0x0ED0 && c <= 0x0ED9 + || c >= 0x0F20 && c <= 0x0F29 + || c == 0x002E + || c == 0x002D + || c == 0x005F + || Utilities.isLetter(c) + || c >= 0x0300 && c <= 0x0345 + || c >= 0x0360 && c <= 0x0361 + || c >= 0x0483 && c <= 0x0486 + || c >= 0x0591 && c <= 0x05A1 + || c >= 0x05A3 && c <= 0x05B9 + || c >= 0x05BB && c <= 0x05BD + || c == 0x05BF + || c >= 0x05C1 && c <= 0x05C2 + || c == 0x05C4 + || c >= 0x064B && c <= 0x0652 + || c == 0x0670 + || c >= 0x06D6 && c <= 0x06DC + || c >= 0x06DD && c <= 0x06DF + || c >= 0x06E0 && c <= 0x06E4 + || c >= 0x06E7 && c <= 0x06E8 + || c >= 0x06EA && c <= 0x06ED + || c >= 0x0901 && c <= 0x0903 + || c == 0x093C + || c >= 0x093E && c <= 0x094C + || c == 0x094D + || c >= 0x0951 && c <= 0x0954 + || c >= 0x0962 && c <= 0x0963 + || c >= 0x0981 && c <= 0x0983 + || c == 0x09BC + || c == 0x09BE + || c == 0x09BF + || c >= 0x09C0 && c <= 0x09C4 + || c >= 0x09C7 && c <= 0x09C8 + || c >= 0x09CB && c <= 0x09CD + || c == 0x09D7 + || c >= 0x09E2 && c <= 0x09E3 + || c == 0x0A02 + || c == 0x0A3C + || c == 0x0A3E + || c == 0x0A3F + || c >= 0x0A40 && c <= 0x0A42 + || c >= 0x0A47 && c <= 0x0A48 + || c >= 0x0A4B && c <= 0x0A4D + || c >= 0x0A70 && c <= 0x0A71 + || c >= 0x0A81 && c <= 0x0A83 + || c == 0x0ABC + || c >= 0x0ABE && c <= 0x0AC5 + || c >= 0x0AC7 && c <= 0x0AC9 + || c >= 0x0ACB && c <= 0x0ACD + || c >= 0x0B01 && c <= 0x0B03 + || c == 0x0B3C + || c >= 0x0B3E && c <= 0x0B43 + || c >= 0x0B47 && c <= 0x0B48 + || c >= 0x0B4B && c <= 0x0B4D + || c >= 0x0B56 && c <= 0x0B57 + || c >= 0x0B82 && c <= 0x0B83 + || c >= 0x0BBE && c <= 0x0BC2 + || c >= 0x0BC6 && c <= 0x0BC8 + || c >= 0x0BCA && c <= 0x0BCD + || c == 0x0BD7 + || c >= 0x0C01 && c <= 0x0C03 + || c >= 0x0C3E && c <= 0x0C44 + || c >= 0x0C46 && c <= 0x0C48 + || c >= 0x0C4A && c <= 0x0C4D + || c >= 0x0C55 && c <= 0x0C56 + || c >= 0x0C82 && c <= 0x0C83 + || c >= 0x0CBE && c <= 0x0CC4 + || c >= 0x0CC6 && c <= 0x0CC8 + || c >= 0x0CCA && c <= 0x0CCD + || c >= 0x0CD5 && c <= 0x0CD6 + || c >= 0x0D02 && c <= 0x0D03 + || c >= 0x0D3E && c <= 0x0D43 + || c >= 0x0D46 && c <= 0x0D48 + || c >= 0x0D4A && c <= 0x0D4D + || c == 0x0D57 + || c == 0x0E31 + || c >= 0x0E34 && c <= 0x0E3A + || c >= 0x0E47 && c <= 0x0E4E + || c == 0x0EB1 + || c >= 0x0EB4 && c <= 0x0EB9 + || c >= 0x0EBB && c <= 0x0EBC + || c >= 0x0EC8 && c <= 0x0ECD + || c >= 0x0F18 && c <= 0x0F19 + || c == 0x0F35 + || c == 0x0F37 + || c == 0x0F39 + || c == 0x0F3E + || c == 0x0F3F + || c >= 0x0F71 && c <= 0x0F84 + || c >= 0x0F86 && c <= 0x0F8B + || c >= 0x0F90 && c <= 0x0F95 + || c == 0x0F97 + || c >= 0x0F99 && c <= 0x0FAD + || c >= 0x0FB1 && c <= 0x0FB7 + || c == 0x0FB9 + || c >= 0x20D0 && c <= 0x20DC + || c == 0x20E1 + || c >= 0x302A && c <= 0x302F + || c == 0x3099 + || c == 0x309A + || c == 0x00B7 + || c == 0x02D0 + || c == 0x02D1 + || c == 0x0387 + || c == 0x0640 + || c == 0x0E46 + || c == 0x0EC6 + || c == 0x3005 + || c >= 0x3031 && c <= 0x3035 + || c >= 0x309D && c <= 0x309E + || c >= 0x30FC && c <= 0x30FE; + }; -// MultiplyOperation ///////////////////////////////////////////////////////// + Utilities.coalesceText = function (n) { + for (var m = n.firstChild; m != null; m = m.nextSibling) { + if (m.nodeType == 3 /*Node.TEXT_NODE*/ || m.nodeType == 4 /*Node.CDATA_SECTION_NODE*/) { + var s = m.nodeValue; + var first = m; + m = m.nextSibling; + while (m != null && (m.nodeType == 3 /*Node.TEXT_NODE*/ || m.nodeType == 4 /*Node.CDATA_SECTION_NODE*/)) { + s += m.nodeValue; + var del = m; + m = m.nextSibling; + del.parentNode.removeChild(del); + } + if (first.nodeType == 4 /*Node.CDATA_SECTION_NODE*/) { + var p = first.parentNode; + if (first.nextSibling == null) { + p.removeChild(first); + p.appendChild(p.ownerDocument.createTextNode(s)); + } else { + var next = first.nextSibling; + p.removeChild(first); + p.insertBefore(p.ownerDocument.createTextNode(s), next); + } + } else { + first.nodeValue = s; + } + if (m == null) { + break; + } + } else if (m.nodeType == 1 /*Node.ELEMENT_NODE*/) { + Utilities.coalesceText(m); + } + } + }; -MultiplyOperation.prototype = new BinaryOperation(); -MultiplyOperation.prototype.constructor = MultiplyOperation; -MultiplyOperation.superclass = BinaryOperation.prototype; + Utilities.instance_of = function (o, c) { + while (o != null) { + if (o.constructor === c) { + return true; + } + if (o === Object) { + return false; + } + o = o.constructor.superclass; + } + return false; + }; -function MultiplyOperation(lhs, rhs) { - if (arguments.length > 0) { - this.init(lhs, rhs); - } -} - -MultiplyOperation.prototype.init = function(lhs, rhs) { - MultiplyOperation.superclass.init.call(this, lhs, rhs); -}; + Utilities.getElementById = function (n, id) { + // Note that this does not check the DTD to check for actual + // attributes of type ID, so this may be a bit wrong. + if (n.nodeType == 1 /*Node.ELEMENT_NODE*/) { + if (n.getAttribute("id") == id + || n.getAttributeNS(null, "id") == id) { + return n; + } + } + for (var m = n.firstChild; m != null; m = m.nextSibling) { + var res = Utilities.getElementById(m, id); + if (res != null) { + return res; + } + } + return null; + }; -MultiplyOperation.prototype.evaluate = function(c) { - return this.lhs.evaluate(c).number().multiply(this.rhs.evaluate(c).number()); -}; + // XPathException //////////////////////////////////////////////////////////// -MultiplyOperation.prototype.toString = function() { - return "(" + this.lhs.toString() + " * " + this.rhs.toString() + ")"; -}; + var XPathException = (function () { + function getMessage(code, exception) { + var msg = exception ? ": " + exception.toString() : ""; + switch (code) { + case XPathException.INVALID_EXPRESSION_ERR: + return "Invalid expression" + msg; + case XPathException.TYPE_ERR: + return "Type error" + msg; + } + return null; + } -// DivOperation ////////////////////////////////////////////////////////////// - -DivOperation.prototype = new BinaryOperation(); -DivOperation.prototype.constructor = DivOperation; -DivOperation.superclass = BinaryOperation.prototype; - -function DivOperation(lhs, rhs) { - if (arguments.length > 0) { - this.init(lhs, rhs); - } -} - -DivOperation.prototype.init = function(lhs, rhs) { - DivOperation.superclass.init.call(this, lhs, rhs); -}; + function XPathException(code, error, message) { + var err = Error.call(this, getMessage(code, error) || message); -DivOperation.prototype.evaluate = function(c) { - return this.lhs.evaluate(c).number().div(this.rhs.evaluate(c).number()); -}; + err.code = code; + err.exception = error; -DivOperation.prototype.toString = function() { - return "(" + this.lhs.toString() + " div " + this.rhs.toString() + ")"; -}; + return err; + } -// ModOperation ////////////////////////////////////////////////////////////// - -ModOperation.prototype = new BinaryOperation(); -ModOperation.prototype.constructor = ModOperation; -ModOperation.superclass = BinaryOperation.prototype; - -function ModOperation(lhs, rhs) { - if (arguments.length > 0) { - this.init(lhs, rhs); - } -} - -ModOperation.prototype.init = function(lhs, rhs) { - ModOperation.superclass.init.call(this, lhs, rhs); -}; + XPathException.prototype = Object.create(Error.prototype); + XPathException.prototype.constructor = XPathException; + XPathException.superclass = Error; -ModOperation.prototype.evaluate = function(c) { - return this.lhs.evaluate(c).number().mod(this.rhs.evaluate(c).number()); -}; + XPathException.prototype.toString = function () { + return this.message; + }; -ModOperation.prototype.toString = function() { - return "(" + this.lhs.toString() + " mod " + this.rhs.toString() + ")"; -}; + XPathException.fromMessage = function (message, error) { + return new XPathException(null, error, message); + }; -// BarOperation ////////////////////////////////////////////////////////////// - -BarOperation.prototype = new BinaryOperation(); -BarOperation.prototype.constructor = BarOperation; -BarOperation.superclass = BinaryOperation.prototype; - -function BarOperation(lhs, rhs) { - if (arguments.length > 0) { - this.init(lhs, rhs); - } -} - -BarOperation.prototype.init = function(lhs, rhs) { - BarOperation.superclass.init.call(this, lhs, rhs); -}; + XPathException.INVALID_EXPRESSION_ERR = 51; + XPathException.TYPE_ERR = 52; -BarOperation.prototype.evaluate = function(c) { - return this.lhs.evaluate(c).nodeset().union(this.rhs.evaluate(c).nodeset()); -}; + return XPathException; + })(); -BarOperation.prototype.toString = function() { - return map(toString, [this.lhs, this.rhs]).join(' | '); -}; + // XPathExpression /////////////////////////////////////////////////////////// -// PathExpr ////////////////////////////////////////////////////////////////// - -PathExpr.prototype = new Expression(); -PathExpr.prototype.constructor = PathExpr; -PathExpr.superclass = Expression.prototype; - -function PathExpr(filter, filterPreds, locpath) { - if (arguments.length > 0) { - this.init(filter, filterPreds, locpath); - } -} - -PathExpr.prototype.init = function(filter, filterPreds, locpath) { - PathExpr.superclass.init.call(this); - this.filter = filter; - this.filterPredicates = filterPreds; - this.locationPath = locpath; -}; + XPathExpression.prototype = {}; + XPathExpression.prototype.constructor = XPathExpression; + XPathExpression.superclass = Object.prototype; -/** - * Returns the topmost node of the tree containing node - */ -function findRoot(node) { - while (node && node.parentNode) { - node = node.parentNode; + function XPathExpression(e, r, p) { + this.xpath = p.parse(e); + this.context = new XPathContext(); + this.context.namespaceResolver = new XPathNSResolverWrapper(r); } - return node; -} - -PathExpr.applyPredicates = function (predicates, c, nodes) { - return reduce(function (inNodes, pred) { - var ctx = c.extend({ contextSize: inNodes.length }); - - return filter(function (node, i) { - return PathExpr.predicateMatches(pred, ctx.extend({ contextNode: node, contextPosition: i + 1 })); - }, inNodes); - }, nodes, predicates); -}; - -PathExpr.getRoot = function (xpc, nodes) { - var firstNode = nodes[0]; - - if (firstNode.nodeType === 9 /*Node.DOCUMENT_NODE*/) { - return firstNode; - } - - if (xpc.virtualRoot) { - return xpc.virtualRoot; - } - - var ownerDoc = firstNode.ownerDocument; - - if (ownerDoc) { - return ownerDoc; - } - - // IE 5.5 doesn't have ownerDocument? - var n = firstNode; - while (n.parentNode != null) { - n = n.parentNode; - } - return n; -} - -PathExpr.applyStep = function (step, xpc, node) { - var self = this; - var newNodes = []; - xpc.contextNode = node; - - switch (step.axis) { - case Step.ANCESTOR: - // look at all the ancestor nodes - if (xpc.contextNode === xpc.virtualRoot) { - break; - } - var m; - if (xpc.contextNode.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) { - m = PathExpr.getOwnerElement(xpc.contextNode); - } else { - m = xpc.contextNode.parentNode; - } - while (m != null) { - if (step.nodeTest.matches(m, xpc)) { - newNodes.push(m); - } - if (m === xpc.virtualRoot) { - break; - } - m = m.parentNode; - } - break; - - case Step.ANCESTORORSELF: - // look at all the ancestor nodes and the current node - for (var m = xpc.contextNode; m != null; m = m.nodeType == 2 /*Node.ATTRIBUTE_NODE*/ ? PathExpr.getOwnerElement(m) : m.parentNode) { - if (step.nodeTest.matches(m, xpc)) { - newNodes.push(m); - } - if (m === xpc.virtualRoot) { - break; - } - } - break; - - case Step.ATTRIBUTE: - // look at the attributes - var nnm = xpc.contextNode.attributes; - if (nnm != null) { - for (var k = 0; k < nnm.length; k++) { - var m = nnm.item(k); - if (step.nodeTest.matches(m, xpc)) { - newNodes.push(m); - } - } - } - break; - - case Step.CHILD: - // look at all child elements - for (var m = xpc.contextNode.firstChild; m != null; m = m.nextSibling) { - if (step.nodeTest.matches(m, xpc)) { - newNodes.push(m); - } - } - break; - - case Step.DESCENDANT: - // look at all descendant nodes - var st = [ xpc.contextNode.firstChild ]; - while (st.length > 0) { - for (var m = st.pop(); m != null; ) { - if (step.nodeTest.matches(m, xpc)) { - newNodes.push(m); - } - if (m.firstChild != null) { - st.push(m.nextSibling); - m = m.firstChild; - } else { - m = m.nextSibling; - } - } - } - break; - - case Step.DESCENDANTORSELF: - // look at self - if (step.nodeTest.matches(xpc.contextNode, xpc)) { - newNodes.push(xpc.contextNode); - } - // look at all descendant nodes - var st = [ xpc.contextNode.firstChild ]; - while (st.length > 0) { - for (var m = st.pop(); m != null; ) { - if (step.nodeTest.matches(m, xpc)) { - newNodes.push(m); - } - if (m.firstChild != null) { - st.push(m.nextSibling); - m = m.firstChild; - } else { - m = m.nextSibling; - } - } - } - break; - - case Step.FOLLOWING: - if (xpc.contextNode === xpc.virtualRoot) { - break; - } - var st = []; - if (xpc.contextNode.firstChild != null) { - st.unshift(xpc.contextNode.firstChild); - } else { - st.unshift(xpc.contextNode.nextSibling); - } - for (var m = xpc.contextNode.parentNode; m != null && m.nodeType != 9 /*Node.DOCUMENT_NODE*/ && m !== xpc.virtualRoot; m = m.parentNode) { - st.unshift(m.nextSibling); - } - do { - for (var m = st.pop(); m != null; ) { - if (step.nodeTest.matches(m, xpc)) { - newNodes.push(m); - } - if (m.firstChild != null) { - st.push(m.nextSibling); - m = m.firstChild; - } else { - m = m.nextSibling; - } - } - } while (st.length > 0); - break; - - case Step.FOLLOWINGSIBLING: - if (xpc.contextNode === xpc.virtualRoot) { - break; - } - for (var m = xpc.contextNode.nextSibling; m != null; m = m.nextSibling) { - if (step.nodeTest.matches(m, xpc)) { - newNodes.push(m); - } - } - break; - - case Step.NAMESPACE: - var n = {}; - if (xpc.contextNode.nodeType == 1 /*Node.ELEMENT_NODE*/) { - n["xml"] = XPath.XML_NAMESPACE_URI; - n["xmlns"] = XPath.XMLNS_NAMESPACE_URI; - for (var m = xpc.contextNode; m != null && m.nodeType == 1 /*Node.ELEMENT_NODE*/; m = m.parentNode) { - for (var k = 0; k < m.attributes.length; k++) { - var attr = m.attributes.item(k); - var nm = String(attr.name); - if (nm == "xmlns") { - if (n[""] == undefined) { - n[""] = attr.value; - } - } else if (nm.length > 6 && nm.substring(0, 6) == "xmlns:") { - var pre = nm.substring(6, nm.length); - if (n[pre] == undefined) { - n[pre] = attr.value; - } - } - } - } - for (var pre in n) { - var nsn = new XPathNamespace(pre, n[pre], xpc.contextNode); - if (step.nodeTest.matches(nsn, xpc)) { - newNodes.push(nsn); - } - } - } - break; - - case Step.PARENT: - m = null; - if (xpc.contextNode !== xpc.virtualRoot) { - if (xpc.contextNode.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) { - m = PathExpr.getOwnerElement(xpc.contextNode); - } else { - m = xpc.contextNode.parentNode; - } - } - if (m != null && step.nodeTest.matches(m, xpc)) { - newNodes.push(m); - } - break; - - case Step.PRECEDING: - var st; - if (xpc.virtualRoot != null) { - st = [ xpc.virtualRoot ]; - } else { - // cannot rely on .ownerDocument because the node may be in a document fragment - st = [findRoot(xpc.contextNode)]; - } - outer: while (st.length > 0) { - for (var m = st.pop(); m != null; ) { - if (m == xpc.contextNode) { - break outer; - } - if (step.nodeTest.matches(m, xpc)) { - newNodes.unshift(m); - } - if (m.firstChild != null) { - st.push(m.nextSibling); - m = m.firstChild; - } else { - m = m.nextSibling; - } - } - } - break; - - case Step.PRECEDINGSIBLING: - if (xpc.contextNode === xpc.virtualRoot) { - break; - } - for (var m = xpc.contextNode.previousSibling; m != null; m = m.previousSibling) { - if (step.nodeTest.matches(m, xpc)) { - newNodes.push(m); - } - } - break; - - case Step.SELF: - if (step.nodeTest.matches(xpc.contextNode, xpc)) { - newNodes.push(xpc.contextNode); - } - break; - - default: - } - - return newNodes; -}; - -PathExpr.applySteps = function (steps, xpc, nodes) { - return reduce(function (inNodes, step) { - return [].concat.apply([], map(function (node) { - return PathExpr.applyPredicates(step.predicates, xpc, PathExpr.applyStep(step, xpc, node)); - }, inNodes)); - }, nodes, steps); -} - -PathExpr.prototype.applyFilter = function(c, xpc) { - if (!this.filter) { - return { nodes: [ c.contextNode ] }; - } - - var ns = this.filter.evaluate(c); - - if (!Utilities.instance_of(ns, XNodeSet)) { - if (this.filterPredicates != null && this.filterPredicates.length > 0 || this.locationPath != null) { - throw new Error("Path expression filter must evaluate to a nodeset if predicates or location path are used"); - } - - return { nonNodes: ns }; - } - - return { - nodes: PathExpr.applyPredicates(this.filterPredicates || [], xpc, ns.toUnsortedArray()) - }; -}; - -PathExpr.applyLocationPath = function (locationPath, xpc, nodes) { - if (!locationPath) { - return nodes; - } - - var startNodes = locationPath.absolute ? [ PathExpr.getRoot(xpc, nodes) ] : nodes; - - return PathExpr.applySteps(locationPath.steps, xpc, startNodes); -}; - -PathExpr.prototype.evaluate = function(c) { - var xpc = assign(new XPathContext(), c); - - var filterResult = this.applyFilter(c, xpc); - - if ('nonNodes' in filterResult) { - return filterResult.nonNodes; - } - - var ns = new XNodeSet(); - ns.addArray(PathExpr.applyLocationPath(this.locationPath, xpc, filterResult.nodes)); - return ns; -}; - -PathExpr.predicateMatches = function(pred, c) { - var res = pred.evaluate(c); - - return Utilities.instance_of(res, XNumber) - ? c.contextPosition == res.numberValue() - : res.booleanValue(); -}; - -PathExpr.predicateString = compose(wrap('[', ']'), toString); -PathExpr.predicatesString = compose(join(''), map(PathExpr.predicateString)); - -PathExpr.prototype.toString = function() { - if (this.filter != undefined) { - var filterStr = toString(this.filter); - - if (Utilities.instance_of(this.filter, XString)) { - return wrap("'", "'", filterStr); - } - if (this.filterPredicates != undefined && this.filterPredicates.length) { - return wrap('(', ')', filterStr) + - PathExpr.predicatesString(this.filterPredicates); - } - if (this.locationPath != undefined) { - return filterStr + - (this.locationPath.absolute ? '' : '/') + - toString(this.locationPath); - } - - return filterStr; - } - - return toString(this.locationPath); -}; - -PathExpr.getOwnerElement = function(n) { - // DOM 2 has ownerElement - if (n.ownerElement) { - return n.ownerElement; - } - // DOM 1 Internet Explorer can use selectSingleNode (ironically) - try { - if (n.selectSingleNode) { - return n.selectSingleNode(".."); - } - } catch (e) { - } - // Other DOM 1 implementations must use this egregious search - var doc = n.nodeType == 9 /*Node.DOCUMENT_NODE*/ - ? n - : n.ownerDocument; - var elts = doc.getElementsByTagName("*"); - for (var i = 0; i < elts.length; i++) { - var elt = elts.item(i); - var nnm = elt.attributes; - for (var j = 0; j < nnm.length; j++) { - var an = nnm.item(j); - if (an === n) { - return elt; - } - } - } - return null; -}; - -// LocationPath ////////////////////////////////////////////////////////////// - -LocationPath.prototype = new Object(); -LocationPath.prototype.constructor = LocationPath; -LocationPath.superclass = Object.prototype; - -function LocationPath(abs, steps) { - if (arguments.length > 0) { - this.init(abs, steps); - } -} - -LocationPath.prototype.init = function(abs, steps) { - this.absolute = abs; - this.steps = steps; -}; - -LocationPath.prototype.toString = function() { - return ( - (this.absolute ? '/' : '') + - map(toString, this.steps).join('/') - ); -}; - -// Step ////////////////////////////////////////////////////////////////////// - -Step.prototype = new Object(); -Step.prototype.constructor = Step; -Step.superclass = Object.prototype; - -function Step(axis, nodetest, preds) { - if (arguments.length > 0) { - this.init(axis, nodetest, preds); - } -} - -Step.prototype.init = function(axis, nodetest, preds) { - this.axis = axis; - this.nodeTest = nodetest; - this.predicates = preds; -}; - -Step.prototype.toString = function() { - return Step.STEPNAMES[this.axis] + - "::" + - this.nodeTest.toString() + - PathExpr.predicatesString(this.predicates); -}; - - -Step.ANCESTOR = 0; -Step.ANCESTORORSELF = 1; -Step.ATTRIBUTE = 2; -Step.CHILD = 3; -Step.DESCENDANT = 4; -Step.DESCENDANTORSELF = 5; -Step.FOLLOWING = 6; -Step.FOLLOWINGSIBLING = 7; -Step.NAMESPACE = 8; -Step.PARENT = 9; -Step.PRECEDING = 10; -Step.PRECEDINGSIBLING = 11; -Step.SELF = 12; - -Step.STEPNAMES = reduce(function (acc, x) { return acc[x[0]] = x[1], acc; }, {}, [ - [Step.ANCESTOR, 'ancestor'], - [Step.ANCESTORORSELF, 'ancestor-or-self'], - [Step.ATTRIBUTE, 'attribute'], - [Step.CHILD, 'child'], - [Step.DESCENDANT, 'descendant'], - [Step.DESCENDANTORSELF, 'descendant-or-self'], - [Step.FOLLOWING, 'following'], - [Step.FOLLOWINGSIBLING, 'following-sibling'], - [Step.NAMESPACE, 'namespace'], - [Step.PARENT, 'parent'], - [Step.PRECEDING, 'preceding'], - [Step.PRECEDINGSIBLING, 'preceding-sibling'], - [Step.SELF, 'self'] - ]); - -// NodeTest ////////////////////////////////////////////////////////////////// - -NodeTest.prototype = new Object(); -NodeTest.prototype.constructor = NodeTest; -NodeTest.superclass = Object.prototype; - -function NodeTest(type, value) { - if (arguments.length > 0) { - this.init(type, value); - } -} - -NodeTest.prototype.init = function(type, value) { - this.type = type; - this.value = value; -}; - -NodeTest.prototype.toString = function() { - return ""; -}; - -NodeTest.prototype.matches = function (n, xpc) { - console.warn('unknown node test type'); -}; - -NodeTest.NAMETESTANY = 0; -NodeTest.NAMETESTPREFIXANY = 1; -NodeTest.NAMETESTQNAME = 2; -NodeTest.COMMENT = 3; -NodeTest.TEXT = 4; -NodeTest.PI = 5; -NodeTest.NODE = 6; - -NodeTest.isNodeType = function (types){ - return compose(includes(types), prop('nodeType')); -}; - -NodeTest.makeNodeTestType = function (type, members, ctor) { - var newType = ctor || function () {}; - - newType.prototype = new NodeTest(members.type); - newType.prototype.constructor = type; - - for (var key in members) { - newType.prototype[key] = members[key]; - } - - return newType; -}; -// create invariant node test for certain node types -NodeTest.makeNodeTypeTest = function (type, nodeTypes, stringVal) { - return new (NodeTest.makeNodeTestType(type, { - matches: NodeTest.isNodeType(nodeTypes), - toString: always(stringVal) - }))(); -}; - -NodeTest.hasPrefix = function (node) { - return node.prefix || (node.nodeName || node.tagName).indexOf(':') !== -1; -}; - -NodeTest.isElementOrAttribute = NodeTest.isNodeType([1, 2]); -NodeTest.nameSpaceMatches = function (prefix, xpc, n) { - var nNamespace = (n.namespaceURI || ''); - - if (!prefix) { - return !nNamespace || (xpc.allowAnyNamespaceForNoPrefix && !NodeTest.hasPrefix(n)); - } - - var ns = xpc.namespaceResolver.getNamespace(prefix, xpc.expressionContextNode); - - if (ns == null) { - throw new Error("Cannot resolve QName " + prefix); + XPathExpression.getOwnerDocument = function (n) { + return n.nodeType === 9 /*Node.DOCUMENT_NODE*/ ? n : n.ownerDocument; } - return ns === nNamespace; -}; -NodeTest.localNameMatches = function (localName, xpc, n) { - var nLocalName = (n.localName || n.nodeName); - - return xpc.caseInsensitive - ? localName.toLowerCase() === nLocalName.toLowerCase() - : localName === nLocalName; -}; - -NodeTest.NameTestPrefixAny = NodeTest.makeNodeTestType(NodeTest.NAMETESTPREFIXANY, { - matches: function (n, xpc){ - return NodeTest.isElementOrAttribute(n) && - NodeTest.nameSpaceMatches(this.prefix, xpc, n); - }, - toString: function () { - return this.prefix + ":*"; - } -}, function (prefix) { this.prefix = prefix; }); - -NodeTest.NameTestQName = NodeTest.makeNodeTestType(NodeTest.NAMETESTQNAME, { - matches: function (n, xpc) { - return NodeTest.isNodeType([1, 2, XPathNamespace.XPATH_NAMESPACE_NODE])(n) && - NodeTest.nameSpaceMatches(this.prefix, xpc, n) && - NodeTest.localNameMatches(this.localName, xpc, n); - }, - toString: function () { - return this.name; - } -}, function (name) { - var nameParts = name.split(':'); - - this.name = name; - this.prefix = nameParts.length > 1 ? nameParts[0] : null; - this.localName = nameParts[nameParts.length > 1 ? 1 : 0]; -}); - -NodeTest.PITest = NodeTest.makeNodeTestType(NodeTest.PI, { - matches: function (n, xpc) { - return NodeTest.isNodeType([7])(n) && (n.target || n.nodeName) === this.name; - }, - toString: function () { - return wrap('processing-instruction("', '")', this.name); - } -}, function (name) { this.name = name; }) - -// singletons - -// elements, attributes, namespaces -NodeTest.nameTestAny = NodeTest.makeNodeTypeTest(NodeTest.NAMETESTANY, [1, 2, XPathNamespace.XPATH_NAMESPACE_NODE], '*'); -// text, cdata -NodeTest.textTest = NodeTest.makeNodeTypeTest(NodeTest.TEXT, [3, 4], 'text()'); -NodeTest.commentTest = NodeTest.makeNodeTypeTest(NodeTest.COMMENT, [8], 'comment()'); -// elements, attributes, text, cdata, PIs, comments, document nodes -NodeTest.nodeTest = NodeTest.makeNodeTypeTest(NodeTest.NODE, [1, 2, 3, 4, 7, 8, 9], 'node()'); -NodeTest.anyPiTest = NodeTest.makeNodeTypeTest(NodeTest.PI, [7], 'processing-instruction()'); - -// VariableReference ///////////////////////////////////////////////////////// - -VariableReference.prototype = new Expression(); -VariableReference.prototype.constructor = VariableReference; -VariableReference.superclass = Expression.prototype; - -function VariableReference(v) { - if (arguments.length > 0) { - this.init(v); - } -} - -VariableReference.prototype.init = function(v) { - this.variable = v; -}; - -VariableReference.prototype.toString = function() { - return "$" + this.variable; -}; - -VariableReference.prototype.evaluate = function(c) { - var parts = Utilities.resolveQName(this.variable, c.namespaceResolver, c.contextNode, false); - - if (parts[0] == null) { - throw new Error("Cannot resolve QName " + fn); - } - var result = c.variableResolver.getVariable(parts[1], parts[0]); - if (!result) { - throw XPathException.fromMessage("Undeclared variable: " + this.toString()); - } - return result; -}; + XPathExpression.detectHtmlDom = function (n) { + if (!n) { return false; } -// FunctionCall ////////////////////////////////////////////////////////////// - -FunctionCall.prototype = new Expression(); -FunctionCall.prototype.constructor = FunctionCall; -FunctionCall.superclass = Expression.prototype; - -function FunctionCall(fn, args) { - if (arguments.length > 0) { - this.init(fn, args); - } -} + var doc = XPathExpression.getOwnerDocument(n); -FunctionCall.prototype.init = function(fn, args) { - this.functionName = fn; - this.arguments = args; -}; - -FunctionCall.prototype.toString = function() { - var s = this.functionName + "("; - for (var i = 0; i < this.arguments.length; i++) { - if (i > 0) { - s += ", "; - } - s += this.arguments[i].toString(); - } - return s + ")"; -}; - -FunctionCall.prototype.evaluate = function(c) { - var f = FunctionResolver.getFunctionFromContext(this.functionName, c); - - if (!f) { - throw new Error("Unknown function " + this.functionName); - } - - var a = [c].concat(this.arguments); - return f.apply(c.functionResolver.thisArg, a); -}; - -// Operators ///////////////////////////////////////////////////////////////// - -var Operators = new Object(); - -Operators.equals = function(l, r) { - return l.equals(r); -}; - -Operators.notequal = function(l, r) { - return l.notequal(r); -}; - -Operators.lessthan = function(l, r) { - return l.lessthan(r); -}; - -Operators.greaterthan = function(l, r) { - return l.greaterthan(r); -}; - -Operators.lessthanorequal = function(l, r) { - return l.lessthanorequal(r); -}; - -Operators.greaterthanorequal = function(l, r) { - return l.greaterthanorequal(r); -}; - -// XString /////////////////////////////////////////////////////////////////// - -XString.prototype = new Expression(); -XString.prototype.constructor = XString; -XString.superclass = Expression.prototype; - -function XString(s) { - if (arguments.length > 0) { - this.init(s); - } -} - -XString.prototype.init = function(s) { - this.str = String(s); -}; - -XString.prototype.toString = function() { - return this.str; -}; - -XString.prototype.evaluate = function(c) { - return this; -}; - -XString.prototype.string = function() { - return this; -}; - -XString.prototype.number = function() { - return new XNumber(this.str); -}; - -XString.prototype.bool = function() { - return new XBoolean(this.str); -}; - -XString.prototype.nodeset = function() { - throw new Error("Cannot convert string to nodeset"); -}; - -XString.prototype.stringValue = function() { - return this.str; -}; - -XString.prototype.numberValue = function() { - return this.number().numberValue(); -}; - -XString.prototype.booleanValue = function() { - return this.bool().booleanValue(); -}; - -XString.prototype.equals = function(r) { - if (Utilities.instance_of(r, XBoolean)) { - return this.bool().equals(r); - } - if (Utilities.instance_of(r, XNumber)) { - return this.number().equals(r); - } - if (Utilities.instance_of(r, XNodeSet)) { - return r.compareWithString(this, Operators.equals); - } - return new XBoolean(this.str == r.str); -}; - -XString.prototype.notequal = function(r) { - if (Utilities.instance_of(r, XBoolean)) { - return this.bool().notequal(r); - } - if (Utilities.instance_of(r, XNumber)) { - return this.number().notequal(r); - } - if (Utilities.instance_of(r, XNodeSet)) { - return r.compareWithString(this, Operators.notequal); - } - return new XBoolean(this.str != r.str); -}; - -XString.prototype.lessthan = function(r) { - return this.number().lessthan(r); -}; - -XString.prototype.greaterthan = function(r) { - return this.number().greaterthan(r); -}; - -XString.prototype.lessthanorequal = function(r) { - return this.number().lessthanorequal(r); -}; - -XString.prototype.greaterthanorequal = function(r) { - return this.number().greaterthanorequal(r); -}; - -// XNumber /////////////////////////////////////////////////////////////////// - -XNumber.prototype = new Expression(); -XNumber.prototype.constructor = XNumber; -XNumber.superclass = Expression.prototype; - -function XNumber(n) { - if (arguments.length > 0) { - this.init(n); - } -} - -XNumber.prototype.init = function(n) { - this.num = typeof n === "string" ? this.parse(n) : Number(n); -}; - -XNumber.prototype.numberFormat = /^\s*-?[0-9]*\.?[0-9]+\s*$/; - -XNumber.prototype.parse = function(s) { - // XPath representation of numbers is more restrictive than what Number() or parseFloat() allow - return this.numberFormat.test(s) ? parseFloat(s) : Number.NaN; -}; - -function padSmallNumber(numberStr) { - var parts = numberStr.split('e-'); - var base = parts[0].replace('.', ''); - var exponent = Number(parts[1]); - - for (var i = 0; i < exponent - 1; i += 1) { - base = '0' + base; - } - - return '0.' + base; -} - -function padLargeNumber(numberStr) { - var parts = numberStr.split('e'); - var base = parts[0].replace('.', ''); - var exponent = Number(parts[1]); - var zerosToAppend = exponent + 1 - base.length; - - for (var i = 0; i < zerosToAppend; i += 1){ - base += '0'; - } - - return base; -} - -XNumber.prototype.toString = function() { - var strValue = this.num.toString(); - - if (strValue.indexOf('e-') !== -1) { - return padSmallNumber(strValue); - } - - if (strValue.indexOf('e') !== -1) { - return padLargeNumber(strValue); - } - - return strValue; -}; - -XNumber.prototype.evaluate = function(c) { - return this; -}; - -XNumber.prototype.string = function() { - - - return new XString(this.toString()); -}; - -XNumber.prototype.number = function() { - return this; -}; - -XNumber.prototype.bool = function() { - return new XBoolean(this.num); -}; - -XNumber.prototype.nodeset = function() { - throw new Error("Cannot convert number to nodeset"); -}; - -XNumber.prototype.stringValue = function() { - return this.string().stringValue(); -}; - -XNumber.prototype.numberValue = function() { - return this.num; -}; - -XNumber.prototype.booleanValue = function() { - return this.bool().booleanValue(); -}; - -XNumber.prototype.negate = function() { - return new XNumber(-this.num); -}; - -XNumber.prototype.equals = function(r) { - if (Utilities.instance_of(r, XBoolean)) { - return this.bool().equals(r); - } - if (Utilities.instance_of(r, XString)) { - return this.equals(r.number()); - } - if (Utilities.instance_of(r, XNodeSet)) { - return r.compareWithNumber(this, Operators.equals); - } - return new XBoolean(this.num == r.num); -}; - -XNumber.prototype.notequal = function(r) { - if (Utilities.instance_of(r, XBoolean)) { - return this.bool().notequal(r); - } - if (Utilities.instance_of(r, XString)) { - return this.notequal(r.number()); - } - if (Utilities.instance_of(r, XNodeSet)) { - return r.compareWithNumber(this, Operators.notequal); - } - return new XBoolean(this.num != r.num); -}; - -XNumber.prototype.lessthan = function(r) { - if (Utilities.instance_of(r, XNodeSet)) { - return r.compareWithNumber(this, Operators.greaterthan); - } - if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { - return this.lessthan(r.number()); - } - return new XBoolean(this.num < r.num); -}; - -XNumber.prototype.greaterthan = function(r) { - if (Utilities.instance_of(r, XNodeSet)) { - return r.compareWithNumber(this, Operators.lessthan); - } - if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { - return this.greaterthan(r.number()); - } - return new XBoolean(this.num > r.num); -}; - -XNumber.prototype.lessthanorequal = function(r) { - if (Utilities.instance_of(r, XNodeSet)) { - return r.compareWithNumber(this, Operators.greaterthanorequal); - } - if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { - return this.lessthanorequal(r.number()); - } - return new XBoolean(this.num <= r.num); -}; - -XNumber.prototype.greaterthanorequal = function(r) { - if (Utilities.instance_of(r, XNodeSet)) { - return r.compareWithNumber(this, Operators.lessthanorequal); - } - if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) { - return this.greaterthanorequal(r.number()); - } - return new XBoolean(this.num >= r.num); -}; - -XNumber.prototype.plus = function(r) { - return new XNumber(this.num + r.num); -}; - -XNumber.prototype.minus = function(r) { - return new XNumber(this.num - r.num); -}; - -XNumber.prototype.multiply = function(r) { - return new XNumber(this.num * r.num); -}; - -XNumber.prototype.div = function(r) { - return new XNumber(this.num / r.num); -}; - -XNumber.prototype.mod = function(r) { - return new XNumber(this.num % r.num); -}; - -// XBoolean ////////////////////////////////////////////////////////////////// - -XBoolean.prototype = new Expression(); -XBoolean.prototype.constructor = XBoolean; -XBoolean.superclass = Expression.prototype; - -function XBoolean(b) { - if (arguments.length > 0) { - this.init(b); - } -} - -XBoolean.prototype.init = function(b) { - this.b = Boolean(b); -}; - -XBoolean.prototype.toString = function() { - return this.b.toString(); -}; - -XBoolean.prototype.evaluate = function(c) { - return this; -}; - -XBoolean.prototype.string = function() { - return new XString(this.b); -}; - -XBoolean.prototype.number = function() { - return new XNumber(this.b); -}; - -XBoolean.prototype.bool = function() { - return this; -}; - -XBoolean.prototype.nodeset = function() { - throw new Error("Cannot convert boolean to nodeset"); -}; - -XBoolean.prototype.stringValue = function() { - return this.string().stringValue(); -}; - -XBoolean.prototype.numberValue = function() { - return this.number().numberValue(); -}; - -XBoolean.prototype.booleanValue = function() { - return this.b; -}; - -XBoolean.prototype.not = function() { - return new XBoolean(!this.b); -}; - -XBoolean.prototype.equals = function(r) { - if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) { - return this.equals(r.bool()); - } - if (Utilities.instance_of(r, XNodeSet)) { - return r.compareWithBoolean(this, Operators.equals); - } - return new XBoolean(this.b == r.b); -}; - -XBoolean.prototype.notequal = function(r) { - if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) { - return this.notequal(r.bool()); - } - if (Utilities.instance_of(r, XNodeSet)) { - return r.compareWithBoolean(this, Operators.notequal); - } - return new XBoolean(this.b != r.b); -}; - -XBoolean.prototype.lessthan = function(r) { - return this.number().lessthan(r); -}; - -XBoolean.prototype.greaterthan = function(r) { - return this.number().greaterthan(r); -}; - -XBoolean.prototype.lessthanorequal = function(r) { - return this.number().lessthanorequal(r); -}; - -XBoolean.prototype.greaterthanorequal = function(r) { - return this.number().greaterthanorequal(r); -}; - -XBoolean.true_ = new XBoolean(true); -XBoolean.false_ = new XBoolean(false); - -// AVLTree /////////////////////////////////////////////////////////////////// - -AVLTree.prototype = new Object(); -AVLTree.prototype.constructor = AVLTree; -AVLTree.superclass = Object.prototype; - -function AVLTree(n) { - this.init(n); -} - -AVLTree.prototype.init = function(n) { - this.left = null; - this.right = null; - this.node = n; - this.depth = 1; -}; - -AVLTree.prototype.balance = function() { - var ldepth = this.left == null ? 0 : this.left.depth; - var rdepth = this.right == null ? 0 : this.right.depth; - - if (ldepth > rdepth + 1) { - // LR or LL rotation - var lldepth = this.left.left == null ? 0 : this.left.left.depth; - var lrdepth = this.left.right == null ? 0 : this.left.right.depth; - - if (lldepth < lrdepth) { - // LR rotation consists of a RR rotation of the left child - this.left.rotateRR(); - // plus a LL rotation of this node, which happens anyway - } - this.rotateLL(); - } else if (ldepth + 1 < rdepth) { - // RR or RL rorarion - var rrdepth = this.right.right == null ? 0 : this.right.right.depth; - var rldepth = this.right.left == null ? 0 : this.right.left.depth; - - if (rldepth > rrdepth) { - // RR rotation consists of a LL rotation of the right child - this.right.rotateLL(); - // plus a RR rotation of this node, which happens anyway - } - this.rotateRR(); - } -}; - -AVLTree.prototype.rotateLL = function() { - // the left side is too long => rotate from the left (_not_ leftwards) - var nodeBefore = this.node; - var rightBefore = this.right; - this.node = this.left.node; - this.right = this.left; - this.left = this.left.left; - this.right.left = this.right.right; - this.right.right = rightBefore; - this.right.node = nodeBefore; - this.right.updateInNewLocation(); - this.updateInNewLocation(); -}; - -AVLTree.prototype.rotateRR = function() { - // the right side is too long => rotate from the right (_not_ rightwards) - var nodeBefore = this.node; - var leftBefore = this.left; - this.node = this.right.node; - this.left = this.right; - this.right = this.right.right; - this.left.right = this.left.left; - this.left.left = leftBefore; - this.left.node = nodeBefore; - this.left.updateInNewLocation(); - this.updateInNewLocation(); -}; - -AVLTree.prototype.updateInNewLocation = function() { - this.getDepthFromChildren(); -}; - -AVLTree.prototype.getDepthFromChildren = function() { - this.depth = this.node == null ? 0 : 1; - if (this.left != null) { - this.depth = this.left.depth + 1; - } - if (this.right != null && this.depth <= this.right.depth) { - this.depth = this.right.depth + 1; + try { + return doc.implementation.hasFeature("HTML", "2.0"); + } catch (e) { + return true; + } } -}; -function nodeOrder(n1, n2) { - if (n1 === n2) { - return 0; - } + XPathExpression.prototype.evaluate = function (n, t, res) { + this.context.expressionContextNode = n; + // backward compatibility - no reliable way to detect whether the DOM is HTML, but + // this library has been using this method up until now, so we will continue to use it + // ONLY when using an XPathExpression + this.context.caseInsensitive = XPathExpression.detectHtmlDom(n); - if (n1.compareDocumentPosition) { - var cpos = n1.compareDocumentPosition(n2); + var result = this.xpath.evaluate(this.context); + return new XPathResult(result, t); + } - if (cpos & 0x01) { - // not in the same document; return an arbitrary result (is there a better way to do this) - return 1; - } - if (cpos & 0x0A) { - // n2 precedes or contains n1 - return 1; - } - if (cpos & 0x14) { - // n2 follows or is contained by n1 - return -1; - } + // XPathNSResolverWrapper //////////////////////////////////////////////////// - return 0; - } - - var d1 = 0, - d2 = 0; - for (var m1 = n1; m1 != null; m1 = m1.parentNode || m1.ownerElement) { - d1++; - } - for (var m2 = n2; m2 != null; m2 = m2.parentNode || m2.ownerElement) { - d2++; - } - - // step up to same depth - if (d1 > d2) { - while (d1 > d2) { - n1 = n1.parentNode || n1.ownerElement; - d1--; - } - if (n1 === n2) { - return 1; - } - } else if (d2 > d1) { - while (d2 > d1) { - n2 = n2.parentNode || n2.ownerElement; - d2--; - } - if (n1 === n2) { - return -1; - } - } - - var n1Par = n1.parentNode || n1.ownerElement, - n2Par = n2.parentNode || n2.ownerElement; - - // find common parent - while (n1Par !== n2Par) { - n1 = n1Par; - n2 = n2Par; - n1Par = n1.parentNode || n1.ownerElement; - n2Par = n2.parentNode || n2.ownerElement; - } - - var n1isAttr = Utilities.isAttribute(n1); - var n2isAttr = Utilities.isAttribute(n2); - - if (n1isAttr && !n2isAttr) { - return -1; - } - if (!n1isAttr && n2isAttr) { - return 1; + XPathNSResolverWrapper.prototype = {}; + XPathNSResolverWrapper.prototype.constructor = XPathNSResolverWrapper; + XPathNSResolverWrapper.superclass = Object.prototype; + + function XPathNSResolverWrapper(r) { + this.xpathNSResolver = r; } - - if(n1Par) { - var cn = n1isAttr ? n1Par.attributes : n1Par.childNodes, - len = cn.length; - for (var i = 0; i < len; i += 1) { - var n = cn[i]; - if (n === n1) { - return -1; - } - if (n === n2) { - return 1; - } + + XPathNSResolverWrapper.prototype.getNamespace = function (prefix, n) { + if (this.xpathNSResolver == null) { + return null; } - } - - throw new Error('Unexpected: could not determine node order'); -} + return this.xpathNSResolver.lookupNamespaceURI(prefix); + }; -AVLTree.prototype.add = function(n) { - if (n === this.node) { - return false; + // NodeXPathNSResolver /////////////////////////////////////////////////////// + + NodeXPathNSResolver.prototype = {}; + NodeXPathNSResolver.prototype.constructor = NodeXPathNSResolver; + NodeXPathNSResolver.superclass = Object.prototype; + + function NodeXPathNSResolver(n) { + this.node = n; + this.namespaceResolver = new NamespaceResolver(); } - var o = nodeOrder(n, this.node); + NodeXPathNSResolver.prototype.lookupNamespaceURI = function (prefix) { + return this.namespaceResolver.getNamespace(prefix, this.node); + }; - var ret = false; - if (o == -1) { - if (this.left == null) { - this.left = new AVLTree(n); - ret = true; - } else { - ret = this.left.add(n); - if (ret) { - this.balance(); + // XPathResult /////////////////////////////////////////////////////////////// + + XPathResult.prototype = {}; + XPathResult.prototype.constructor = XPathResult; + XPathResult.superclass = Object.prototype; + + function XPathResult(v, t) { + if (t == XPathResult.ANY_TYPE) { + if (v.constructor === XString) { + t = XPathResult.STRING_TYPE; + } else if (v.constructor === XNumber) { + t = XPathResult.NUMBER_TYPE; + } else if (v.constructor === XBoolean) { + t = XPathResult.BOOLEAN_TYPE; + } else if (v.constructor === XNodeSet) { + t = XPathResult.UNORDERED_NODE_ITERATOR_TYPE; } } - } else if (o == 1) { - if (this.right == null) { - this.right = new AVLTree(n); - ret = true; - } else { - ret = this.right.add(n); - if (ret) { - this.balance(); - } + this.resultType = t; + switch (t) { + case XPathResult.NUMBER_TYPE: + this.numberValue = v.numberValue(); + return; + case XPathResult.STRING_TYPE: + this.stringValue = v.stringValue(); + return; + case XPathResult.BOOLEAN_TYPE: + this.booleanValue = v.booleanValue(); + return; + case XPathResult.ANY_UNORDERED_NODE_TYPE: + case XPathResult.FIRST_ORDERED_NODE_TYPE: + if (v.constructor === XNodeSet) { + this.singleNodeValue = v.first(); + return; + } + break; + case XPathResult.UNORDERED_NODE_ITERATOR_TYPE: + case XPathResult.ORDERED_NODE_ITERATOR_TYPE: + if (v.constructor === XNodeSet) { + this.invalidIteratorState = false; + this.nodes = v.toArray(); + this.iteratorIndex = 0; + return; + } + break; + case XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE: + case XPathResult.ORDERED_NODE_SNAPSHOT_TYPE: + if (v.constructor === XNodeSet) { + this.nodes = v.toArray(); + this.snapshotLength = this.nodes.length; + return; + } + break; } - } + throw new XPathException(XPathException.TYPE_ERR); + }; - if (ret) { - this.getDepthFromChildren(); - } - return ret; -}; - -// XNodeSet ////////////////////////////////////////////////////////////////// - -XNodeSet.prototype = new Expression(); -XNodeSet.prototype.constructor = XNodeSet; -XNodeSet.superclass = Expression.prototype; - -function XNodeSet() { - this.init(); -} - -XNodeSet.prototype.init = function() { - this.tree = null; - this.nodes = []; - this.size = 0; -}; - -XNodeSet.prototype.toString = function() { - var p = this.first(); - if (p == null) { - return ""; - } - return this.stringForNode(p); -}; - -XNodeSet.prototype.evaluate = function(c) { - return this; -}; - -XNodeSet.prototype.string = function() { - return new XString(this.toString()); -}; - -XNodeSet.prototype.stringValue = function() { - return this.toString(); -}; - -XNodeSet.prototype.number = function() { - return new XNumber(this.string()); -}; - -XNodeSet.prototype.numberValue = function() { - return Number(this.string()); -}; - -XNodeSet.prototype.bool = function() { - return new XBoolean(this.booleanValue()); -}; - -XNodeSet.prototype.booleanValue = function() { - return !!this.size; -}; - -XNodeSet.prototype.nodeset = function() { - return this; -}; - -XNodeSet.prototype.stringForNode = function(n) { - if (n.nodeType == 9 /*Node.DOCUMENT_NODE*/ || - n.nodeType == 1 /*Node.ELEMENT_NODE */ || - n.nodeType === 11 /*Node.DOCUMENT_FRAGMENT*/) { - return this.stringForContainerNode(n); - } - if (n.nodeType === 2 /* Node.ATTRIBUTE_NODE */) { - return n.value || n.nodeValue; - } - if (n.isNamespaceNode) { - return n.namespace; - } - return n.nodeValue; -}; - -XNodeSet.prototype.stringForContainerNode = function(n) { - var s = ""; - for (var n2 = n.firstChild; n2 != null; n2 = n2.nextSibling) { - var nt = n2.nodeType; - // Element, Text, CDATA, Document, Document Fragment - if (nt === 1 || nt === 3 || nt === 4 || nt === 9 || nt === 11) { - s += this.stringForNode(n2); - } - } - return s; -}; - -XNodeSet.prototype.buildTree = function () { - if (!this.tree && this.nodes.length) { - this.tree = new AVLTree(this.nodes[0]); - for (var i = 1; i < this.nodes.length; i += 1) { - this.tree.add(this.nodes[i]); + XPathResult.prototype.iterateNext = function () { + if (this.resultType != XPathResult.UNORDERED_NODE_ITERATOR_TYPE + && this.resultType != XPathResult.ORDERED_NODE_ITERATOR_TYPE) { + throw new XPathException(XPathException.TYPE_ERR); } - } + return this.nodes[this.iteratorIndex++]; + }; - return this.tree; -}; - -XNodeSet.prototype.first = function() { - var p = this.buildTree(); - if (p == null) { - return null; - } - while (p.left != null) { - p = p.left; - } - return p.node; -}; - -XNodeSet.prototype.add = function(n) { - for (var i = 0; i < this.nodes.length; i += 1) { - if (n === this.nodes[i]) { - return; + XPathResult.prototype.snapshotItem = function (i) { + if (this.resultType != XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE + && this.resultType != XPathResult.ORDERED_NODE_SNAPSHOT_TYPE) { + throw new XPathException(XPathException.TYPE_ERR); } - } - - this.tree = null; - this.nodes.push(n); - this.size += 1; -}; + return this.nodes[i]; + }; -XNodeSet.prototype.addArray = function(ns) { - var self = this; - - forEach(function (x) { self.add(x); }, ns); -}; + XPathResult.ANY_TYPE = 0; + XPathResult.NUMBER_TYPE = 1; + XPathResult.STRING_TYPE = 2; + XPathResult.BOOLEAN_TYPE = 3; + XPathResult.UNORDERED_NODE_ITERATOR_TYPE = 4; + XPathResult.ORDERED_NODE_ITERATOR_TYPE = 5; + XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE = 6; + XPathResult.ORDERED_NODE_SNAPSHOT_TYPE = 7; + XPathResult.ANY_UNORDERED_NODE_TYPE = 8; + XPathResult.FIRST_ORDERED_NODE_TYPE = 9; + + // DOM 3 XPath support /////////////////////////////////////////////////////// + + function installDOM3XPathSupport(doc, p) { + doc.createExpression = function (e, r) { + try { + return new XPathExpression(e, r, p); + } catch (e) { + throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, e); + } + }; + doc.createNSResolver = function (n) { + return new NodeXPathNSResolver(n); + }; + doc.evaluate = function (e, cn, r, t, res) { + if (t < 0 || t > 9) { + throw { code: 0, toString: function () { return "Request type not supported"; } }; + } + return doc.createExpression(e, r, p).evaluate(cn, t, res); + }; + }; -/** - * Returns an array of the node set's contents in document order - */ -XNodeSet.prototype.toArray = function() { - var a = []; - this.toArrayRec(this.buildTree(), a); - return a; -}; - -XNodeSet.prototype.toArrayRec = function(t, a) { - if (t != null) { - this.toArrayRec(t.left, a); - a.push(t.node); - this.toArrayRec(t.right, a); - } -}; - -/** - * Returns an array of the node set's contents in arbitrary order - */ -XNodeSet.prototype.toUnsortedArray = function () { - return this.nodes.slice(); -}; - -XNodeSet.prototype.compareWithString = function(r, o) { - var a = this.toUnsortedArray(); - for (var i = 0; i < a.length; i++) { - var n = a[i]; - var l = new XString(this.stringForNode(n)); - var res = o(l, r); - if (res.booleanValue()) { - return res; - } - } - return new XBoolean(false); -}; - -XNodeSet.prototype.compareWithNumber = function(r, o) { - var a = this.toUnsortedArray(); - for (var i = 0; i < a.length; i++) { - var n = a[i]; - var l = new XNumber(this.stringForNode(n)); - var res = o(l, r); - if (res.booleanValue()) { - return res; - } - } - return new XBoolean(false); -}; - -XNodeSet.prototype.compareWithBoolean = function(r, o) { - return o(this.bool(), r); -}; - -XNodeSet.prototype.compareWithNodeSet = function(r, o) { - var arr = this.toUnsortedArray(); - var oInvert = function (lop, rop) { return o(rop, lop); }; - - for (var i = 0; i < arr.length; i++) { - var l = new XString(this.stringForNode(arr[i])); - - var res = r.compareWithString(l, oInvert); - if (res.booleanValue()) { - return res; - } - } - - return new XBoolean(false); -}; - -XNodeSet.compareWith = curry(function (o, r) { - if (Utilities.instance_of(r, XString)) { - return this.compareWithString(r, o); - } - if (Utilities.instance_of(r, XNumber)) { - return this.compareWithNumber(r, o); - } - if (Utilities.instance_of(r, XBoolean)) { - return this.compareWithBoolean(r, o); - } - return this.compareWithNodeSet(r, o); -}); - -XNodeSet.prototype.equals = XNodeSet.compareWith(Operators.equals); -XNodeSet.prototype.notequal = XNodeSet.compareWith(Operators.notequal); -XNodeSet.prototype.lessthan = XNodeSet.compareWith(Operators.lessthan); -XNodeSet.prototype.greaterthan = XNodeSet.compareWith(Operators.greaterthan); -XNodeSet.prototype.lessthanorequal = XNodeSet.compareWith(Operators.lessthanorequal); -XNodeSet.prototype.greaterthanorequal = XNodeSet.compareWith(Operators.greaterthanorequal); - -XNodeSet.prototype.union = function(r) { - var ns = new XNodeSet(); - ns.addArray(this.toUnsortedArray()); - ns.addArray(r.toUnsortedArray()); - return ns; -}; - -// XPathNamespace //////////////////////////////////////////////////////////// - -XPathNamespace.prototype = new Object(); -XPathNamespace.prototype.constructor = XPathNamespace; -XPathNamespace.superclass = Object.prototype; - -function XPathNamespace(pre, ns, p) { - this.isXPathNamespace = true; - this.ownerDocument = p.ownerDocument; - this.nodeName = "#namespace"; - this.prefix = pre; - this.localName = pre; - this.namespaceURI = ns; - this.nodeValue = ns; - this.ownerElement = p; - this.nodeType = XPathNamespace.XPATH_NAMESPACE_NODE; -} - -XPathNamespace.prototype.toString = function() { - return "{ \"" + this.prefix + "\", \"" + this.namespaceURI + "\" }"; -}; - -// XPathContext ////////////////////////////////////////////////////////////// - -XPathContext.prototype = new Object(); -XPathContext.prototype.constructor = XPathContext; -XPathContext.superclass = Object.prototype; - -function XPathContext(vr, nr, fr) { - this.variableResolver = vr != null ? vr : new VariableResolver(); - this.namespaceResolver = nr != null ? nr : new NamespaceResolver(); - this.functionResolver = fr != null ? fr : new FunctionResolver(); -} - -XPathContext.prototype.extend = function (newProps) { - return assign(new XPathContext(), this, newProps); -}; - -// VariableResolver ////////////////////////////////////////////////////////// - -VariableResolver.prototype = new Object(); -VariableResolver.prototype.constructor = VariableResolver; -VariableResolver.superclass = Object.prototype; - -function VariableResolver() { -} - -VariableResolver.prototype.getVariable = function(ln, ns) { - return null; -}; - -// FunctionResolver ////////////////////////////////////////////////////////// - -FunctionResolver.prototype = new Object(); -FunctionResolver.prototype.constructor = FunctionResolver; -FunctionResolver.superclass = Object.prototype; - -function FunctionResolver(thisArg) { - this.thisArg = thisArg != null ? thisArg : Functions; - this.functions = new Object(); - this.addStandardFunctions(); -} - -FunctionResolver.prototype.addStandardFunctions = function() { - this.functions["{}last"] = Functions.last; - this.functions["{}position"] = Functions.position; - this.functions["{}count"] = Functions.count; - this.functions["{}id"] = Functions.id; - this.functions["{}local-name"] = Functions.localName; - this.functions["{}namespace-uri"] = Functions.namespaceURI; - this.functions["{}name"] = Functions.name; - this.functions["{}string"] = Functions.string; - this.functions["{}concat"] = Functions.concat; - this.functions["{}starts-with"] = Functions.startsWith; - this.functions["{}contains"] = Functions.contains; - this.functions["{}substring-before"] = Functions.substringBefore; - this.functions["{}substring-after"] = Functions.substringAfter; - this.functions["{}substring"] = Functions.substring; - this.functions["{}string-length"] = Functions.stringLength; - this.functions["{}normalize-space"] = Functions.normalizeSpace; - this.functions["{}translate"] = Functions.translate; - this.functions["{}boolean"] = Functions.boolean_; - this.functions["{}not"] = Functions.not; - this.functions["{}true"] = Functions.true_; - this.functions["{}false"] = Functions.false_; - this.functions["{}lang"] = Functions.lang; - this.functions["{}number"] = Functions.number; - this.functions["{}sum"] = Functions.sum; - this.functions["{}floor"] = Functions.floor; - this.functions["{}ceiling"] = Functions.ceiling; - this.functions["{}round"] = Functions.round; -}; - -FunctionResolver.prototype.addFunction = function(ns, ln, f) { - this.functions["{" + ns + "}" + ln] = f; -}; - -FunctionResolver.getFunctionFromContext = function(qName, context) { - var parts = Utilities.resolveQName(qName, context.namespaceResolver, context.contextNode, false); - - if (parts[0] === null) { - throw new Error("Cannot resolve QName " + name); - } + // --------------------------------------------------------------------------- - return context.functionResolver.getFunction(parts[1], parts[0]); -}; - -FunctionResolver.prototype.getFunction = function(localName, namespace) { - return this.functions["{" + namespace + "}" + localName]; -}; - -// NamespaceResolver ///////////////////////////////////////////////////////// - -NamespaceResolver.prototype = new Object(); -NamespaceResolver.prototype.constructor = NamespaceResolver; -NamespaceResolver.superclass = Object.prototype; - -function NamespaceResolver() { -} - -NamespaceResolver.prototype.getNamespace = function(prefix, n) { - if (prefix == "xml") { - return XPath.XML_NAMESPACE_URI; - } else if (prefix == "xmlns") { - return XPath.XMLNS_NAMESPACE_URI; - } - if (n.nodeType == 9 /*Node.DOCUMENT_NODE*/) { - n = n.documentElement; - } else if (n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) { - n = PathExpr.getOwnerElement(n); - } else if (n.nodeType != 1 /*Node.ELEMENT_NODE*/) { - n = n.parentNode; - } - while (n != null && n.nodeType == 1 /*Node.ELEMENT_NODE*/) { - var nnm = n.attributes; - for (var i = 0; i < nnm.length; i++) { - var a = nnm.item(i); - var aname = a.name || a.nodeName; - if ((aname === "xmlns" && prefix === "") - || aname === "xmlns:" + prefix) { - return String(a.value || a.nodeValue); - } - } - n = n.parentNode; - } - return null; -}; - -// Functions ///////////////////////////////////////////////////////////////// - -var Functions = new Object(); - -Functions.last = function(c) { - if (arguments.length != 1) { - throw new Error("Function last expects ()"); - } - - return new XNumber(c.contextSize); -}; - -Functions.position = function(c) { - if (arguments.length != 1) { - throw new Error("Function position expects ()"); - } - - return new XNumber(c.contextPosition); -}; - -Functions.count = function() { - var c = arguments[0]; - var ns; - if (arguments.length != 2 || !Utilities.instance_of(ns = arguments[1].evaluate(c), XNodeSet)) { - throw new Error("Function count expects (node-set)"); - } - return new XNumber(ns.size); -}; - -Functions.id = function() { - var c = arguments[0]; - var id; - if (arguments.length != 2) { - throw new Error("Function id expects (object)"); - } - id = arguments[1].evaluate(c); - if (Utilities.instance_of(id, XNodeSet)) { - id = id.toArray().join(" "); - } else { - id = id.stringValue(); - } - var ids = id.split(/[\x0d\x0a\x09\x20]+/); - var count = 0; - var ns = new XNodeSet(); - var doc = c.contextNode.nodeType == 9 /*Node.DOCUMENT_NODE*/ - ? c.contextNode - : c.contextNode.ownerDocument; - for (var i = 0; i < ids.length; i++) { - var n; - if (doc.getElementById) { - n = doc.getElementById(ids[i]); - } else { - n = Utilities.getElementById(doc, ids[i]); - } - if (n != null) { - ns.add(n); - count++; - } - } - return ns; -}; - -Functions.localName = function(c, eNode) { - var n; - - if (arguments.length == 1) { - n = c.contextNode; - } else if (arguments.length == 2) { - n = eNode.evaluate(c).first(); - } else { - throw new Error("Function local-name expects (node-set?)"); - } - - if (n == null) { - return new XString(""); - } - - return new XString(n.localName || // standard elements and attributes - n.baseName || // IE - n.target || // processing instructions - n.nodeName || // DOM1 elements - ""); // fallback -}; - -Functions.namespaceURI = function() { - var c = arguments[0]; - var n; - if (arguments.length == 1) { - n = c.contextNode; - } else if (arguments.length == 2) { - n = arguments[1].evaluate(c).first(); - } else { - throw new Error("Function namespace-uri expects (node-set?)"); - } - if (n == null) { - return new XString(""); - } - return new XString(n.namespaceURI); -}; - -Functions.name = function() { - var c = arguments[0]; - var n; - if (arguments.length == 1) { - n = c.contextNode; - } else if (arguments.length == 2) { - n = arguments[1].evaluate(c).first(); - } else { - throw new Error("Function name expects (node-set?)"); - } - if (n == null) { - return new XString(""); - } - if (n.nodeType == 1 /*Node.ELEMENT_NODE*/) { - return new XString(n.nodeName); - } else if (n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) { - return new XString(n.name || n.nodeName); - } else if (n.nodeType === 7 /*Node.PROCESSING_INSTRUCTION_NODE*/) { - return new XString(n.target || n.nodeName); - } else if (n.localName == null) { - return new XString(""); - } else { - return new XString(n.localName); - } -}; - -Functions.string = function() { - var c = arguments[0]; - if (arguments.length == 1) { - return new XString(XNodeSet.prototype.stringForNode(c.contextNode)); - } else if (arguments.length == 2) { - return arguments[1].evaluate(c).string(); - } - throw new Error("Function string expects (object?)"); -}; - -Functions.concat = function(c) { - if (arguments.length < 3) { - throw new Error("Function concat expects (string, string[, string]*)"); - } - var s = ""; - for (var i = 1; i < arguments.length; i++) { - s += arguments[i].evaluate(c).stringValue(); - } - return new XString(s); -}; - -Functions.startsWith = function() { - var c = arguments[0]; - if (arguments.length != 3) { - throw new Error("Function startsWith expects (string, string)"); - } - var s1 = arguments[1].evaluate(c).stringValue(); - var s2 = arguments[2].evaluate(c).stringValue(); - return new XBoolean(s1.substring(0, s2.length) == s2); -}; - -Functions.contains = function() { - var c = arguments[0]; - if (arguments.length != 3) { - throw new Error("Function contains expects (string, string)"); - } - var s1 = arguments[1].evaluate(c).stringValue(); - var s2 = arguments[2].evaluate(c).stringValue(); - return new XBoolean(s1.indexOf(s2) !== -1); -}; - -Functions.substringBefore = function() { - var c = arguments[0]; - if (arguments.length != 3) { - throw new Error("Function substring-before expects (string, string)"); - } - var s1 = arguments[1].evaluate(c).stringValue(); - var s2 = arguments[2].evaluate(c).stringValue(); - return new XString(s1.substring(0, s1.indexOf(s2))); -}; - -Functions.substringAfter = function() { - var c = arguments[0]; - if (arguments.length != 3) { - throw new Error("Function substring-after expects (string, string)"); - } - var s1 = arguments[1].evaluate(c).stringValue(); - var s2 = arguments[2].evaluate(c).stringValue(); - if (s2.length == 0) { - return new XString(s1); - } - var i = s1.indexOf(s2); - if (i == -1) { - return new XString(""); - } - return new XString(s1.substring(i + s2.length)); -}; - -Functions.substring = function() { - var c = arguments[0]; - if (!(arguments.length == 3 || arguments.length == 4)) { - throw new Error("Function substring expects (string, number, number?)"); - } - var s = arguments[1].evaluate(c).stringValue(); - var n1 = Math.round(arguments[2].evaluate(c).numberValue()) - 1; - var n2 = arguments.length == 4 ? n1 + Math.round(arguments[3].evaluate(c).numberValue()) : undefined; - return new XString(s.substring(n1, n2)); -}; - -Functions.stringLength = function() { - var c = arguments[0]; - var s; - if (arguments.length == 1) { - s = XNodeSet.prototype.stringForNode(c.contextNode); - } else if (arguments.length == 2) { - s = arguments[1].evaluate(c).stringValue(); - } else { - throw new Error("Function string-length expects (string?)"); - } - return new XNumber(s.length); -}; - -Functions.normalizeSpace = function() { - var c = arguments[0]; - var s; - if (arguments.length == 1) { - s = XNodeSet.prototype.stringForNode(c.contextNode); - } else if (arguments.length == 2) { - s = arguments[1].evaluate(c).stringValue(); - } else { - throw new Error("Function normalize-space expects (string?)"); - } - var i = 0; - var j = s.length - 1; - while (Utilities.isSpace(s.charCodeAt(j))) { - j--; - } - var t = ""; - while (i <= j && Utilities.isSpace(s.charCodeAt(i))) { - i++; - } - while (i <= j) { - if (Utilities.isSpace(s.charCodeAt(i))) { - t += " "; - while (i <= j && Utilities.isSpace(s.charCodeAt(i))) { - i++; - } - } else { - t += s.charAt(i); - i++; - } - } - return new XString(t); -}; - -Functions.translate = function(c, eValue, eFrom, eTo) { - if (arguments.length != 4) { - throw new Error("Function translate expects (string, string, string)"); - } - - var value = eValue.evaluate(c).stringValue(); - var from = eFrom.evaluate(c).stringValue(); - var to = eTo.evaluate(c).stringValue(); - - var cMap = reduce(function (acc, ch, i) { - if (!(ch in acc)) { - acc[ch] = i > to.length ? '' : to[i]; - } - return acc; - }, {}, from); - - var t = join('', map(function (ch) { - return ch in cMap ? cMap[ch] : ch; - }, value)); - - return new XString(t); -}; - -Functions.boolean_ = function() { - var c = arguments[0]; - if (arguments.length != 2) { - throw new Error("Function boolean expects (object)"); - } - return arguments[1].evaluate(c).bool(); -}; - -Functions.not = function(c, eValue) { - if (arguments.length != 2) { - throw new Error("Function not expects (object)"); - } - return eValue.evaluate(c).bool().not(); -}; - -Functions.true_ = function() { - if (arguments.length != 1) { - throw new Error("Function true expects ()"); - } - return XBoolean.true_; -}; - -Functions.false_ = function() { - if (arguments.length != 1) { - throw new Error("Function false expects ()"); - } - return XBoolean.false_; -}; - -Functions.lang = function() { - var c = arguments[0]; - if (arguments.length != 2) { - throw new Error("Function lang expects (string)"); - } - var lang; - for (var n = c.contextNode; n != null && n.nodeType != 9 /*Node.DOCUMENT_NODE*/; n = n.parentNode) { - var a = n.getAttributeNS(XPath.XML_NAMESPACE_URI, "lang"); - if (a != null) { - lang = String(a); - break; - } - } - if (lang == null) { - return XBoolean.false_; - } - var s = arguments[1].evaluate(c).stringValue(); - return new XBoolean(lang.substring(0, s.length) == s - && (lang.length == s.length || lang.charAt(s.length) == '-')); -}; - -Functions.number = function() { - var c = arguments[0]; - if (!(arguments.length == 1 || arguments.length == 2)) { - throw new Error("Function number expects (object?)"); - } - if (arguments.length == 1) { - return new XNumber(XNodeSet.prototype.stringForNode(c.contextNode)); - } - return arguments[1].evaluate(c).number(); -}; - -Functions.sum = function() { - var c = arguments[0]; - var ns; - if (arguments.length != 2 || !Utilities.instance_of((ns = arguments[1].evaluate(c)), XNodeSet)) { - throw new Error("Function sum expects (node-set)"); - } - ns = ns.toUnsortedArray(); - var n = 0; - for (var i = 0; i < ns.length; i++) { - n += new XNumber(XNodeSet.prototype.stringForNode(ns[i])).numberValue(); - } - return new XNumber(n); -}; - -Functions.floor = function() { - var c = arguments[0]; - if (arguments.length != 2) { - throw new Error("Function floor expects (number)"); - } - return new XNumber(Math.floor(arguments[1].evaluate(c).numberValue())); -}; - -Functions.ceiling = function() { - var c = arguments[0]; - if (arguments.length != 2) { - throw new Error("Function ceiling expects (number)"); - } - return new XNumber(Math.ceil(arguments[1].evaluate(c).numberValue())); -}; - -Functions.round = function() { - var c = arguments[0]; - if (arguments.length != 2) { - throw new Error("Function round expects (number)"); - } - return new XNumber(Math.round(arguments[1].evaluate(c).numberValue())); -}; - -// Utilities ///////////////////////////////////////////////////////////////// - -var Utilities = new Object(); - -Utilities.isAttribute = function (val) { - return val && (val.nodeType === 2 || val.ownerElement); -} - -Utilities.splitQName = function(qn) { - var i = qn.indexOf(":"); - if (i == -1) { - return [ null, qn ]; - } - return [ qn.substring(0, i), qn.substring(i + 1) ]; -}; - -Utilities.resolveQName = function(qn, nr, n, useDefault) { - var parts = Utilities.splitQName(qn); - if (parts[0] != null) { - parts[0] = nr.getNamespace(parts[0], n); - } else { - if (useDefault) { - parts[0] = nr.getNamespace("", n); - if (parts[0] == null) { - parts[0] = ""; - } - } else { - parts[0] = ""; - } - } - return parts; -}; - -Utilities.isSpace = function(c) { - return c == 0x9 || c == 0xd || c == 0xa || c == 0x20; -}; - -Utilities.isLetter = function(c) { - return c >= 0x0041 && c <= 0x005A || - c >= 0x0061 && c <= 0x007A || - c >= 0x00C0 && c <= 0x00D6 || - c >= 0x00D8 && c <= 0x00F6 || - c >= 0x00F8 && c <= 0x00FF || - c >= 0x0100 && c <= 0x0131 || - c >= 0x0134 && c <= 0x013E || - c >= 0x0141 && c <= 0x0148 || - c >= 0x014A && c <= 0x017E || - c >= 0x0180 && c <= 0x01C3 || - c >= 0x01CD && c <= 0x01F0 || - c >= 0x01F4 && c <= 0x01F5 || - c >= 0x01FA && c <= 0x0217 || - c >= 0x0250 && c <= 0x02A8 || - c >= 0x02BB && c <= 0x02C1 || - c == 0x0386 || - c >= 0x0388 && c <= 0x038A || - c == 0x038C || - c >= 0x038E && c <= 0x03A1 || - c >= 0x03A3 && c <= 0x03CE || - c >= 0x03D0 && c <= 0x03D6 || - c == 0x03DA || - c == 0x03DC || - c == 0x03DE || - c == 0x03E0 || - c >= 0x03E2 && c <= 0x03F3 || - c >= 0x0401 && c <= 0x040C || - c >= 0x040E && c <= 0x044F || - c >= 0x0451 && c <= 0x045C || - c >= 0x045E && c <= 0x0481 || - c >= 0x0490 && c <= 0x04C4 || - c >= 0x04C7 && c <= 0x04C8 || - c >= 0x04CB && c <= 0x04CC || - c >= 0x04D0 && c <= 0x04EB || - c >= 0x04EE && c <= 0x04F5 || - c >= 0x04F8 && c <= 0x04F9 || - c >= 0x0531 && c <= 0x0556 || - c == 0x0559 || - c >= 0x0561 && c <= 0x0586 || - c >= 0x05D0 && c <= 0x05EA || - c >= 0x05F0 && c <= 0x05F2 || - c >= 0x0621 && c <= 0x063A || - c >= 0x0641 && c <= 0x064A || - c >= 0x0671 && c <= 0x06B7 || - c >= 0x06BA && c <= 0x06BE || - c >= 0x06C0 && c <= 0x06CE || - c >= 0x06D0 && c <= 0x06D3 || - c == 0x06D5 || - c >= 0x06E5 && c <= 0x06E6 || - c >= 0x0905 && c <= 0x0939 || - c == 0x093D || - c >= 0x0958 && c <= 0x0961 || - c >= 0x0985 && c <= 0x098C || - c >= 0x098F && c <= 0x0990 || - c >= 0x0993 && c <= 0x09A8 || - c >= 0x09AA && c <= 0x09B0 || - c == 0x09B2 || - c >= 0x09B6 && c <= 0x09B9 || - c >= 0x09DC && c <= 0x09DD || - c >= 0x09DF && c <= 0x09E1 || - c >= 0x09F0 && c <= 0x09F1 || - c >= 0x0A05 && c <= 0x0A0A || - c >= 0x0A0F && c <= 0x0A10 || - c >= 0x0A13 && c <= 0x0A28 || - c >= 0x0A2A && c <= 0x0A30 || - c >= 0x0A32 && c <= 0x0A33 || - c >= 0x0A35 && c <= 0x0A36 || - c >= 0x0A38 && c <= 0x0A39 || - c >= 0x0A59 && c <= 0x0A5C || - c == 0x0A5E || - c >= 0x0A72 && c <= 0x0A74 || - c >= 0x0A85 && c <= 0x0A8B || - c == 0x0A8D || - c >= 0x0A8F && c <= 0x0A91 || - c >= 0x0A93 && c <= 0x0AA8 || - c >= 0x0AAA && c <= 0x0AB0 || - c >= 0x0AB2 && c <= 0x0AB3 || - c >= 0x0AB5 && c <= 0x0AB9 || - c == 0x0ABD || - c == 0x0AE0 || - c >= 0x0B05 && c <= 0x0B0C || - c >= 0x0B0F && c <= 0x0B10 || - c >= 0x0B13 && c <= 0x0B28 || - c >= 0x0B2A && c <= 0x0B30 || - c >= 0x0B32 && c <= 0x0B33 || - c >= 0x0B36 && c <= 0x0B39 || - c == 0x0B3D || - c >= 0x0B5C && c <= 0x0B5D || - c >= 0x0B5F && c <= 0x0B61 || - c >= 0x0B85 && c <= 0x0B8A || - c >= 0x0B8E && c <= 0x0B90 || - c >= 0x0B92 && c <= 0x0B95 || - c >= 0x0B99 && c <= 0x0B9A || - c == 0x0B9C || - c >= 0x0B9E && c <= 0x0B9F || - c >= 0x0BA3 && c <= 0x0BA4 || - c >= 0x0BA8 && c <= 0x0BAA || - c >= 0x0BAE && c <= 0x0BB5 || - c >= 0x0BB7 && c <= 0x0BB9 || - c >= 0x0C05 && c <= 0x0C0C || - c >= 0x0C0E && c <= 0x0C10 || - c >= 0x0C12 && c <= 0x0C28 || - c >= 0x0C2A && c <= 0x0C33 || - c >= 0x0C35 && c <= 0x0C39 || - c >= 0x0C60 && c <= 0x0C61 || - c >= 0x0C85 && c <= 0x0C8C || - c >= 0x0C8E && c <= 0x0C90 || - c >= 0x0C92 && c <= 0x0CA8 || - c >= 0x0CAA && c <= 0x0CB3 || - c >= 0x0CB5 && c <= 0x0CB9 || - c == 0x0CDE || - c >= 0x0CE0 && c <= 0x0CE1 || - c >= 0x0D05 && c <= 0x0D0C || - c >= 0x0D0E && c <= 0x0D10 || - c >= 0x0D12 && c <= 0x0D28 || - c >= 0x0D2A && c <= 0x0D39 || - c >= 0x0D60 && c <= 0x0D61 || - c >= 0x0E01 && c <= 0x0E2E || - c == 0x0E30 || - c >= 0x0E32 && c <= 0x0E33 || - c >= 0x0E40 && c <= 0x0E45 || - c >= 0x0E81 && c <= 0x0E82 || - c == 0x0E84 || - c >= 0x0E87 && c <= 0x0E88 || - c == 0x0E8A || - c == 0x0E8D || - c >= 0x0E94 && c <= 0x0E97 || - c >= 0x0E99 && c <= 0x0E9F || - c >= 0x0EA1 && c <= 0x0EA3 || - c == 0x0EA5 || - c == 0x0EA7 || - c >= 0x0EAA && c <= 0x0EAB || - c >= 0x0EAD && c <= 0x0EAE || - c == 0x0EB0 || - c >= 0x0EB2 && c <= 0x0EB3 || - c == 0x0EBD || - c >= 0x0EC0 && c <= 0x0EC4 || - c >= 0x0F40 && c <= 0x0F47 || - c >= 0x0F49 && c <= 0x0F69 || - c >= 0x10A0 && c <= 0x10C5 || - c >= 0x10D0 && c <= 0x10F6 || - c == 0x1100 || - c >= 0x1102 && c <= 0x1103 || - c >= 0x1105 && c <= 0x1107 || - c == 0x1109 || - c >= 0x110B && c <= 0x110C || - c >= 0x110E && c <= 0x1112 || - c == 0x113C || - c == 0x113E || - c == 0x1140 || - c == 0x114C || - c == 0x114E || - c == 0x1150 || - c >= 0x1154 && c <= 0x1155 || - c == 0x1159 || - c >= 0x115F && c <= 0x1161 || - c == 0x1163 || - c == 0x1165 || - c == 0x1167 || - c == 0x1169 || - c >= 0x116D && c <= 0x116E || - c >= 0x1172 && c <= 0x1173 || - c == 0x1175 || - c == 0x119E || - c == 0x11A8 || - c == 0x11AB || - c >= 0x11AE && c <= 0x11AF || - c >= 0x11B7 && c <= 0x11B8 || - c == 0x11BA || - c >= 0x11BC && c <= 0x11C2 || - c == 0x11EB || - c == 0x11F0 || - c == 0x11F9 || - c >= 0x1E00 && c <= 0x1E9B || - c >= 0x1EA0 && c <= 0x1EF9 || - c >= 0x1F00 && c <= 0x1F15 || - c >= 0x1F18 && c <= 0x1F1D || - c >= 0x1F20 && c <= 0x1F45 || - c >= 0x1F48 && c <= 0x1F4D || - c >= 0x1F50 && c <= 0x1F57 || - c == 0x1F59 || - c == 0x1F5B || - c == 0x1F5D || - c >= 0x1F5F && c <= 0x1F7D || - c >= 0x1F80 && c <= 0x1FB4 || - c >= 0x1FB6 && c <= 0x1FBC || - c == 0x1FBE || - c >= 0x1FC2 && c <= 0x1FC4 || - c >= 0x1FC6 && c <= 0x1FCC || - c >= 0x1FD0 && c <= 0x1FD3 || - c >= 0x1FD6 && c <= 0x1FDB || - c >= 0x1FE0 && c <= 0x1FEC || - c >= 0x1FF2 && c <= 0x1FF4 || - c >= 0x1FF6 && c <= 0x1FFC || - c == 0x2126 || - c >= 0x212A && c <= 0x212B || - c == 0x212E || - c >= 0x2180 && c <= 0x2182 || - c >= 0x3041 && c <= 0x3094 || - c >= 0x30A1 && c <= 0x30FA || - c >= 0x3105 && c <= 0x312C || - c >= 0xAC00 && c <= 0xD7A3 || - c >= 0x4E00 && c <= 0x9FA5 || - c == 0x3007 || - c >= 0x3021 && c <= 0x3029; -}; - -Utilities.isNCNameChar = function(c) { - return c >= 0x0030 && c <= 0x0039 - || c >= 0x0660 && c <= 0x0669 - || c >= 0x06F0 && c <= 0x06F9 - || c >= 0x0966 && c <= 0x096F - || c >= 0x09E6 && c <= 0x09EF - || c >= 0x0A66 && c <= 0x0A6F - || c >= 0x0AE6 && c <= 0x0AEF - || c >= 0x0B66 && c <= 0x0B6F - || c >= 0x0BE7 && c <= 0x0BEF - || c >= 0x0C66 && c <= 0x0C6F - || c >= 0x0CE6 && c <= 0x0CEF - || c >= 0x0D66 && c <= 0x0D6F - || c >= 0x0E50 && c <= 0x0E59 - || c >= 0x0ED0 && c <= 0x0ED9 - || c >= 0x0F20 && c <= 0x0F29 - || c == 0x002E - || c == 0x002D - || c == 0x005F - || Utilities.isLetter(c) - || c >= 0x0300 && c <= 0x0345 - || c >= 0x0360 && c <= 0x0361 - || c >= 0x0483 && c <= 0x0486 - || c >= 0x0591 && c <= 0x05A1 - || c >= 0x05A3 && c <= 0x05B9 - || c >= 0x05BB && c <= 0x05BD - || c == 0x05BF - || c >= 0x05C1 && c <= 0x05C2 - || c == 0x05C4 - || c >= 0x064B && c <= 0x0652 - || c == 0x0670 - || c >= 0x06D6 && c <= 0x06DC - || c >= 0x06DD && c <= 0x06DF - || c >= 0x06E0 && c <= 0x06E4 - || c >= 0x06E7 && c <= 0x06E8 - || c >= 0x06EA && c <= 0x06ED - || c >= 0x0901 && c <= 0x0903 - || c == 0x093C - || c >= 0x093E && c <= 0x094C - || c == 0x094D - || c >= 0x0951 && c <= 0x0954 - || c >= 0x0962 && c <= 0x0963 - || c >= 0x0981 && c <= 0x0983 - || c == 0x09BC - || c == 0x09BE - || c == 0x09BF - || c >= 0x09C0 && c <= 0x09C4 - || c >= 0x09C7 && c <= 0x09C8 - || c >= 0x09CB && c <= 0x09CD - || c == 0x09D7 - || c >= 0x09E2 && c <= 0x09E3 - || c == 0x0A02 - || c == 0x0A3C - || c == 0x0A3E - || c == 0x0A3F - || c >= 0x0A40 && c <= 0x0A42 - || c >= 0x0A47 && c <= 0x0A48 - || c >= 0x0A4B && c <= 0x0A4D - || c >= 0x0A70 && c <= 0x0A71 - || c >= 0x0A81 && c <= 0x0A83 - || c == 0x0ABC - || c >= 0x0ABE && c <= 0x0AC5 - || c >= 0x0AC7 && c <= 0x0AC9 - || c >= 0x0ACB && c <= 0x0ACD - || c >= 0x0B01 && c <= 0x0B03 - || c == 0x0B3C - || c >= 0x0B3E && c <= 0x0B43 - || c >= 0x0B47 && c <= 0x0B48 - || c >= 0x0B4B && c <= 0x0B4D - || c >= 0x0B56 && c <= 0x0B57 - || c >= 0x0B82 && c <= 0x0B83 - || c >= 0x0BBE && c <= 0x0BC2 - || c >= 0x0BC6 && c <= 0x0BC8 - || c >= 0x0BCA && c <= 0x0BCD - || c == 0x0BD7 - || c >= 0x0C01 && c <= 0x0C03 - || c >= 0x0C3E && c <= 0x0C44 - || c >= 0x0C46 && c <= 0x0C48 - || c >= 0x0C4A && c <= 0x0C4D - || c >= 0x0C55 && c <= 0x0C56 - || c >= 0x0C82 && c <= 0x0C83 - || c >= 0x0CBE && c <= 0x0CC4 - || c >= 0x0CC6 && c <= 0x0CC8 - || c >= 0x0CCA && c <= 0x0CCD - || c >= 0x0CD5 && c <= 0x0CD6 - || c >= 0x0D02 && c <= 0x0D03 - || c >= 0x0D3E && c <= 0x0D43 - || c >= 0x0D46 && c <= 0x0D48 - || c >= 0x0D4A && c <= 0x0D4D - || c == 0x0D57 - || c == 0x0E31 - || c >= 0x0E34 && c <= 0x0E3A - || c >= 0x0E47 && c <= 0x0E4E - || c == 0x0EB1 - || c >= 0x0EB4 && c <= 0x0EB9 - || c >= 0x0EBB && c <= 0x0EBC - || c >= 0x0EC8 && c <= 0x0ECD - || c >= 0x0F18 && c <= 0x0F19 - || c == 0x0F35 - || c == 0x0F37 - || c == 0x0F39 - || c == 0x0F3E - || c == 0x0F3F - || c >= 0x0F71 && c <= 0x0F84 - || c >= 0x0F86 && c <= 0x0F8B - || c >= 0x0F90 && c <= 0x0F95 - || c == 0x0F97 - || c >= 0x0F99 && c <= 0x0FAD - || c >= 0x0FB1 && c <= 0x0FB7 - || c == 0x0FB9 - || c >= 0x20D0 && c <= 0x20DC - || c == 0x20E1 - || c >= 0x302A && c <= 0x302F - || c == 0x3099 - || c == 0x309A - || c == 0x00B7 - || c == 0x02D0 - || c == 0x02D1 - || c == 0x0387 - || c == 0x0640 - || c == 0x0E46 - || c == 0x0EC6 - || c == 0x3005 - || c >= 0x3031 && c <= 0x3035 - || c >= 0x309D && c <= 0x309E - || c >= 0x30FC && c <= 0x30FE; -}; - -Utilities.coalesceText = function(n) { - for (var m = n.firstChild; m != null; m = m.nextSibling) { - if (m.nodeType == 3 /*Node.TEXT_NODE*/ || m.nodeType == 4 /*Node.CDATA_SECTION_NODE*/) { - var s = m.nodeValue; - var first = m; - m = m.nextSibling; - while (m != null && (m.nodeType == 3 /*Node.TEXT_NODE*/ || m.nodeType == 4 /*Node.CDATA_SECTION_NODE*/)) { - s += m.nodeValue; - var del = m; - m = m.nextSibling; - del.parentNode.removeChild(del); - } - if (first.nodeType == 4 /*Node.CDATA_SECTION_NODE*/) { - var p = first.parentNode; - if (first.nextSibling == null) { - p.removeChild(first); - p.appendChild(p.ownerDocument.createTextNode(s)); - } else { - var next = first.nextSibling; - p.removeChild(first); - p.insertBefore(p.ownerDocument.createTextNode(s), next); - } - } else { - first.nodeValue = s; - } - if (m == null) { - break; - } - } else if (m.nodeType == 1 /*Node.ELEMENT_NODE*/) { - Utilities.coalesceText(m); - } - } -}; - -Utilities.instance_of = function(o, c) { - while (o != null) { - if (o.constructor === c) { - return true; - } - if (o === Object) { - return false; - } - o = o.constructor.superclass; - } - return false; -}; - -Utilities.getElementById = function(n, id) { - // Note that this does not check the DTD to check for actual - // attributes of type ID, so this may be a bit wrong. - if (n.nodeType == 1 /*Node.ELEMENT_NODE*/) { - if (n.getAttribute("id") == id - || n.getAttributeNS(null, "id") == id) { - return n; - } - } - for (var m = n.firstChild; m != null; m = m.nextSibling) { - var res = Utilities.getElementById(m, id); - if (res != null) { - return res; - } - } - return null; -}; - -// XPathException //////////////////////////////////////////////////////////// - -var XPathException = (function () { - function getMessage(code, exception) { - var msg = exception ? ": " + exception.toString() : ""; - switch (code) { - case XPathException.INVALID_EXPRESSION_ERR: - return "Invalid expression" + msg; - case XPathException.TYPE_ERR: - return "Type error" + msg; + // Install DOM 3 XPath support for the current document. + try { + var shouldInstall = true; + try { + if (document.implementation + && document.implementation.hasFeature + && document.implementation.hasFeature("XPath", null)) { + shouldInstall = false; + } + } catch (e) { } - return null; - } - - function XPathException(code, error, message) { - var err = Error.call(this, getMessage(code, error) || message); - - err.code = code; - err.exception = error; - - return err; + if (shouldInstall) { + installDOM3XPathSupport(document, new XPathParser()); + } + } catch (e) { } - XPathException.prototype = Object.create(Error.prototype); - XPathException.prototype.constructor = XPathException; - XPathException.superclass = Error; + // --------------------------------------------------------------------------- + // exports for node.js - XPathException.prototype.toString = function() { - return this.message; - }; - - XPathException.fromMessage = function(message, error) { - return new XPathException(null, error, message); - }; - - XPathException.INVALID_EXPRESSION_ERR = 51; - XPathException.TYPE_ERR = 52; + installDOM3XPathSupport(exports, new XPathParser()); - return XPathException; -})(); + (function () { + var parser = new XPathParser(); -// XPathExpression /////////////////////////////////////////////////////////// + var defaultNSResolver = new NamespaceResolver(); + var defaultFunctionResolver = new FunctionResolver(); + var defaultVariableResolver = new VariableResolver(); -XPathExpression.prototype = {}; -XPathExpression.prototype.constructor = XPathExpression; -XPathExpression.superclass = Object.prototype; + function makeNSResolverFromFunction(func) { + return { + getNamespace: function (prefix, node) { + var ns = func(prefix, node); -function XPathExpression(e, r, p) { - this.xpath = p.parse(e); - this.context = new XPathContext(); - this.context.namespaceResolver = new XPathNSResolverWrapper(r); -} + return ns || defaultNSResolver.getNamespace(prefix, node); + } + }; + } -XPathExpression.getOwnerDocument = function (n) { - return n.nodeType === 9 /*Node.DOCUMENT_NODE*/ ? n : n.ownerDocument; -} + function makeNSResolverFromObject(obj) { + return makeNSResolverFromFunction(obj.getNamespace.bind(obj)); + } -XPathExpression.detectHtmlDom = function (n) { - if (!n) { return false; } - - var doc = XPathExpression.getOwnerDocument(n); - - try { - return doc.implementation.hasFeature("HTML", "2.0"); - } catch (e) { - return true; - } -} + function makeNSResolverFromMap(map) { + return makeNSResolverFromFunction(function (prefix) { + return map[prefix]; + }); + } -XPathExpression.prototype.evaluate = function(n, t, res) { - this.context.expressionContextNode = n; - // backward compatibility - no reliable way to detect whether the DOM is HTML, but - // this library has been using this method up until now, so we will continue to use it - // ONLY when using an XPathExpression - this.context.caseInsensitive = XPathExpression.detectHtmlDom(n); - - var result = this.xpath.evaluate(this.context); - return new XPathResult(result, t); -} + function makeNSResolver(resolver) { + if (resolver && typeof resolver.getNamespace === "function") { + return makeNSResolverFromObject(resolver); + } -// XPathNSResolverWrapper //////////////////////////////////////////////////// + if (typeof resolver === "function") { + return makeNSResolverFromFunction(resolver); + } -XPathNSResolverWrapper.prototype = {}; -XPathNSResolverWrapper.prototype.constructor = XPathNSResolverWrapper; -XPathNSResolverWrapper.superclass = Object.prototype; + // assume prefix -> uri mapping + if (typeof resolver === "object") { + return makeNSResolverFromMap(resolver); + } -function XPathNSResolverWrapper(r) { - this.xpathNSResolver = r; -} + return defaultNSResolver; + } -XPathNSResolverWrapper.prototype.getNamespace = function(prefix, n) { - if (this.xpathNSResolver == null) { - return null; - } - return this.xpathNSResolver.lookupNamespaceURI(prefix); -}; - -// NodeXPathNSResolver /////////////////////////////////////////////////////// - -NodeXPathNSResolver.prototype = {}; -NodeXPathNSResolver.prototype.constructor = NodeXPathNSResolver; -NodeXPathNSResolver.superclass = Object.prototype; - -function NodeXPathNSResolver(n) { - this.node = n; - this.namespaceResolver = new NamespaceResolver(); -} - -NodeXPathNSResolver.prototype.lookupNamespaceURI = function(prefix) { - return this.namespaceResolver.getNamespace(prefix, this.node); -}; - -// XPathResult /////////////////////////////////////////////////////////////// - -XPathResult.prototype = {}; -XPathResult.prototype.constructor = XPathResult; -XPathResult.superclass = Object.prototype; - -function XPathResult(v, t) { - if (t == XPathResult.ANY_TYPE) { - if (v.constructor === XString) { - t = XPathResult.STRING_TYPE; - } else if (v.constructor === XNumber) { - t = XPathResult.NUMBER_TYPE; - } else if (v.constructor === XBoolean) { - t = XPathResult.BOOLEAN_TYPE; - } else if (v.constructor === XNodeSet) { - t = XPathResult.UNORDERED_NODE_ITERATOR_TYPE; - } - } - this.resultType = t; - switch (t) { - case XPathResult.NUMBER_TYPE: - this.numberValue = v.numberValue(); - return; - case XPathResult.STRING_TYPE: - this.stringValue = v.stringValue(); - return; - case XPathResult.BOOLEAN_TYPE: - this.booleanValue = v.booleanValue(); - return; - case XPathResult.ANY_UNORDERED_NODE_TYPE: - case XPathResult.FIRST_ORDERED_NODE_TYPE: - if (v.constructor === XNodeSet) { - this.singleNodeValue = v.first(); - return; - } - break; - case XPathResult.UNORDERED_NODE_ITERATOR_TYPE: - case XPathResult.ORDERED_NODE_ITERATOR_TYPE: - if (v.constructor === XNodeSet) { - this.invalidIteratorState = false; - this.nodes = v.toArray(); - this.iteratorIndex = 0; - return; - } - break; - case XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE: - case XPathResult.ORDERED_NODE_SNAPSHOT_TYPE: - if (v.constructor === XNodeSet) { - this.nodes = v.toArray(); - this.snapshotLength = this.nodes.length; - return; - } - break; - } - throw new XPathException(XPathException.TYPE_ERR); -}; - -XPathResult.prototype.iterateNext = function() { - if (this.resultType != XPathResult.UNORDERED_NODE_ITERATOR_TYPE - && this.resultType != XPathResult.ORDERED_NODE_ITERATOR_TYPE) { - throw new XPathException(XPathException.TYPE_ERR); - } - return this.nodes[this.iteratorIndex++]; -}; - -XPathResult.prototype.snapshotItem = function(i) { - if (this.resultType != XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE - && this.resultType != XPathResult.ORDERED_NODE_SNAPSHOT_TYPE) { - throw new XPathException(XPathException.TYPE_ERR); - } - return this.nodes[i]; -}; - -XPathResult.ANY_TYPE = 0; -XPathResult.NUMBER_TYPE = 1; -XPathResult.STRING_TYPE = 2; -XPathResult.BOOLEAN_TYPE = 3; -XPathResult.UNORDERED_NODE_ITERATOR_TYPE = 4; -XPathResult.ORDERED_NODE_ITERATOR_TYPE = 5; -XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE = 6; -XPathResult.ORDERED_NODE_SNAPSHOT_TYPE = 7; -XPathResult.ANY_UNORDERED_NODE_TYPE = 8; -XPathResult.FIRST_ORDERED_NODE_TYPE = 9; - -// DOM 3 XPath support /////////////////////////////////////////////////////// - -function installDOM3XPathSupport(doc, p) { - doc.createExpression = function(e, r) { - try { - return new XPathExpression(e, r, p); - } catch (e) { - throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, e); - } - }; - doc.createNSResolver = function(n) { - return new NodeXPathNSResolver(n); - }; - doc.evaluate = function(e, cn, r, t, res) { - if (t < 0 || t > 9) { - throw { code: 0, toString: function() { return "Request type not supported"; } }; - } - return doc.createExpression(e, r, p).evaluate(cn, t, res); - }; -}; - -// --------------------------------------------------------------------------- - -// Install DOM 3 XPath support for the current document. -try { - var shouldInstall = true; - try { - if (document.implementation - && document.implementation.hasFeature - && document.implementation.hasFeature("XPath", null)) { - shouldInstall = false; - } - } catch (e) { - } - if (shouldInstall) { - installDOM3XPathSupport(document, new XPathParser()); - } -} catch (e) { -} - -// --------------------------------------------------------------------------- -// exports for node.js - -installDOM3XPathSupport(exports, new XPathParser()); - -(function() { - var parser = new XPathParser(); - - var defaultNSResolver = new NamespaceResolver(); - var defaultFunctionResolver = new FunctionResolver(); - var defaultVariableResolver = new VariableResolver(); - - function makeNSResolverFromFunction(func) { - return { - getNamespace: function (prefix, node) { - var ns = func(prefix, node); + /** Converts native JavaScript types to their XPath library equivalent */ + function convertValue(value) { + if (value === null || + typeof value === "undefined" || + value instanceof XString || + value instanceof XBoolean || + value instanceof XNumber || + value instanceof XNodeSet) { + return value; + } - return ns || defaultNSResolver.getNamespace(prefix, node); + switch (typeof value) { + case "string": return new XString(value); + case "boolean": return new XBoolean(value); + case "number": return new XNumber(value); } - }; - } - function makeNSResolverFromObject(obj) { - return makeNSResolverFromFunction(obj.getNamespace.bind(obj)); - } + // assume node(s) + var ns = new XNodeSet(); + ns.addArray([].concat(value)); + return ns; + } - function makeNSResolverFromMap(map) { - return makeNSResolverFromFunction(function (prefix) { - return map[prefix]; - }); - } + function makeEvaluator(func) { + return function (context) { + var args = Array.prototype.slice.call(arguments, 1).map(function (arg) { + return arg.evaluate(context); + }); + var result = func.apply(this, [].concat(context, args)); + return convertValue(result); + }; + } - function makeNSResolver(resolver) { - if (resolver && typeof resolver.getNamespace === "function") { - return makeNSResolverFromObject(resolver); + function makeFunctionResolverFromFunction(func) { + return { + getFunction: function (name, namespace) { + var found = func(name, namespace); + if (found) { + return makeEvaluator(found); + } + return defaultFunctionResolver.getFunction(name, namespace); + } + }; } - if (typeof resolver === "function") { - return makeNSResolverFromFunction(resolver); + function makeFunctionResolverFromObject(obj) { + return makeFunctionResolverFromFunction(obj.getFunction.bind(obj)); } - // assume prefix -> uri mapping - if (typeof resolver === "object") { - return makeNSResolverFromMap(resolver); + function makeFunctionResolverFromMap(map) { + return makeFunctionResolverFromFunction(function (name) { + return map[name]; + }); } - return defaultNSResolver; - } + function makeFunctionResolver(resolver) { + if (resolver && typeof resolver.getFunction === "function") { + return makeFunctionResolverFromObject(resolver); + } + + if (typeof resolver === "function") { + return makeFunctionResolverFromFunction(resolver); + } + + // assume map + if (typeof resolver === "object") { + return makeFunctionResolverFromMap(resolver); + } - /** Converts native JavaScript types to their XPath library equivalent */ - function convertValue(value) { - if (value === null || - typeof value === "undefined" || - value instanceof XString || - value instanceof XBoolean || - value instanceof XNumber || - value instanceof XNodeSet) { - return value; + return defaultFunctionResolver; } - switch (typeof value) { - case "string": return new XString(value); - case "boolean": return new XBoolean(value); - case "number": return new XNumber(value); + function makeVariableResolverFromFunction(func) { + return { + getVariable: function (name, namespace) { + var value = func(name, namespace); + return convertValue(value); + } + }; } - // assume node(s) - var ns = new XNodeSet(); - ns.addArray([].concat(value)); - return ns; - } + function makeVariableResolver(resolver) { + if (resolver) { + if (typeof resolver.getVariable === "function") { + return makeVariableResolverFromFunction(resolver.getVariable.bind(resolver)); + } - function makeEvaluator(func) { - return function (context) { - var args = Array.prototype.slice.call(arguments, 1).map(function (arg) { - return arg.evaluate(context); - }); - var result = func.apply(this, [].concat(context, args)); - return convertValue(result); - }; - } + if (typeof resolver === "function") { + return makeVariableResolverFromFunction(resolver); + } - function makeFunctionResolverFromFunction(func) { - return { - getFunction: function (name, namespace) { - var found = func(name, namespace); - if (found) { - return makeEvaluator(found); + // assume map + if (typeof resolver === "object") { + return makeVariableResolverFromFunction(function (name) { + return resolver[name]; + }); } - return defaultFunctionResolver.getFunction(name, namespace); } - }; - } - - function makeFunctionResolverFromObject(obj) { - return makeFunctionResolverFromFunction(obj.getFunction.bind(obj)); - } - function makeFunctionResolverFromMap(map) { - return makeFunctionResolverFromFunction(function (name) { - return map[name]; - }); - } + return defaultVariableResolver; + } - function makeFunctionResolver(resolver) { - if (resolver && typeof resolver.getFunction === "function") { - return makeFunctionResolverFromObject(resolver); + function copyIfPresent(prop, dest, source) { + if (prop in source) { dest[prop] = source[prop]; } } - if (typeof resolver === "function") { - return makeFunctionResolverFromFunction(resolver); + function makeContext(options) { + var context = new XPathContext(); + + if (options) { + context.namespaceResolver = makeNSResolver(options.namespaces); + context.functionResolver = makeFunctionResolver(options.functions); + context.variableResolver = makeVariableResolver(options.variables); + context.expressionContextNode = options.node; + copyIfPresent('allowAnyNamespaceForNoPrefix', context, options); + copyIfPresent('isHtml', context, options); + } else { + context.namespaceResolver = defaultNSResolver; + } + + return context; } - // assume map - if (typeof resolver === "object") { - return makeFunctionResolverFromMap(resolver); + function evaluate(parsedExpression, options) { + var context = makeContext(options); + + return parsedExpression.evaluate(context); } - return defaultFunctionResolver; - } + var evaluatorPrototype = { + evaluate: function (options) { + return evaluate(this.expression, options); + } - function makeVariableResolverFromFunction(func) { - return { - getVariable: function (name, namespace) { - var value = func(name, namespace); - return convertValue(value); + , evaluateNumber: function (options) { + return this.evaluate(options).numberValue(); } - }; - } - function makeVariableResolver(resolver) { - if (resolver) { - if (typeof resolver.getVariable === "function") { - return makeVariableResolverFromFunction(resolver.getVariable.bind(resolver)); + , evaluateString: function (options) { + return this.evaluate(options).stringValue(); } - if (typeof resolver === "function") { - return makeVariableResolverFromFunction(resolver); + , evaluateBoolean: function (options) { + return this.evaluate(options).booleanValue(); } - // assume map - if (typeof resolver === "object") { - return makeVariableResolverFromFunction(function (name) { - return resolver[name]; - }); + , evaluateNodeSet: function (options) { + return this.evaluate(options).nodeset(); } - } - return defaultVariableResolver; - } - - function copyIfPresent(prop, dest, source) { - if (prop in source) { dest[prop] = source[prop]; } - } - - function makeContext(options) { - var context = new XPathContext(); - - if (options) { - context.namespaceResolver = makeNSResolver(options.namespaces); - context.functionResolver = makeFunctionResolver(options.functions); - context.variableResolver = makeVariableResolver(options.variables); - context.expressionContextNode = options.node; - copyIfPresent('allowAnyNamespaceForNoPrefix', context, options); - copyIfPresent('isHtml', context, options); - } else { - context.namespaceResolver = defaultNSResolver; + , select: function (options) { + return this.evaluateNodeSet(options).toArray() + } + + , select1: function (options) { + return this.select(options)[0]; + } + }; + + function parse(xpath) { + var parsed = parser.parse(xpath); + + return Object.create(evaluatorPrototype, { + expression: { + value: parsed + } + }); } - return context; - } + exports.parse = parse; + })(); - function evaluate(parsedExpression, options) { - var context = makeContext(options); + assign( + exports, + { + XPath, + XPathParser, + XPathResult, - return parsedExpression.evaluate(context); - } + Step, + PathExpr, + NodeTest, + LocationPath, - var evaluatorPrototype = { - evaluate: function (options) { - return evaluate(this.expression, options); - } + OrOperation, + AndOperation, - ,evaluateNumber: function (options) { - return this.evaluate(options).numberValue(); - } + BarOperation, - ,evaluateString: function (options) { - return this.evaluate(options).stringValue(); - } + EqualsOperation, + NotEqualOperation, + LessThanOperation, + GreaterThanOperation, + LessThanOrEqualOperation, + GreaterThanOrEqualOperation, - ,evaluateBoolean: function (options) { - return this.evaluate(options).booleanValue(); - } + PlusOperation, + MinusOperation, + MultiplyOperation, + DivOperation, + ModOperation, + UnaryMinusOperation, - ,evaluateNodeSet: function (options) { - return this.evaluate(options).nodeset(); - } + FunctionCall, + VariableReference, - ,select: function (options) { - return this.evaluateNodeSet(options).toArray() - } + XPathContext, - ,select1: function (options) { - return this.select(options)[0]; + XNodeSet, + XBoolean, + XString, + XNumber, + + NamespaceResolver, + FunctionResolver, + VariableResolver, + + Utilities, } + ); + + // helper + exports.select = function (e, doc, single) { + return exports.selectWithResolver(e, doc, null, single); }; - function parse(xpath) { - var parsed = parser.parse(xpath); + exports.useNamespaces = function (mappings) { + var resolver = { + mappings: mappings || {}, + lookupNamespaceURI: function (prefix) { + return this.mappings[prefix]; + } + }; + + return function (e, doc, single) { + return exports.selectWithResolver(e, doc, resolver, single); + }; + }; + + exports.selectWithResolver = function (e, doc, resolver, single) { + var expression = new XPathExpression(e, resolver, new XPathParser()); + var type = XPathResult.ANY_TYPE; - return Object.create(evaluatorPrototype, { - expression: { - value: parsed + var result = expression.evaluate(doc, type, null); + + if (result.resultType == XPathResult.STRING_TYPE) { + result = result.stringValue; + } + else if (result.resultType == XPathResult.NUMBER_TYPE) { + result = result.numberValue; + } + else if (result.resultType == XPathResult.BOOLEAN_TYPE) { + result = result.booleanValue; + } + else { + result = result.nodes; + if (single) { + result = result[0]; } - }); - } + } + + return result; + }; + + exports.select1 = function (e, doc) { + return exports.select(e, doc, true); + }; - exports.parse = parse; -})(); - -exports.XPath = XPath; -exports.XPathParser = XPathParser; -exports.XPathResult = XPathResult; - -exports.Step = Step; -exports.NodeTest = NodeTest; -exports.BarOperation = BarOperation; - -exports.NamespaceResolver = NamespaceResolver; -exports.FunctionResolver = FunctionResolver; -exports.VariableResolver = VariableResolver; - -exports.Utilities = Utilities; - -exports.XPathContext = XPathContext; -exports.XNodeSet = XNodeSet; -exports.XBoolean = XBoolean; -exports.XString = XString; -exports.XNumber = XNumber; - -// helper -exports.select = function(e, doc, single) { - return exports.selectWithResolver(e, doc, null, single); -}; - -exports.useNamespaces = function(mappings) { - var resolver = { - mappings: mappings || {}, - lookupNamespaceURI: function(prefix) { - return this.mappings[prefix]; - } - }; - - return function(e, doc, single) { - return exports.selectWithResolver(e, doc, resolver, single); - }; -}; - -exports.selectWithResolver = function(e, doc, resolver, single) { - var expression = new XPathExpression(e, resolver, new XPathParser()); - var type = XPathResult.ANY_TYPE; - - var result = expression.evaluate(doc, type, null); - - if (result.resultType == XPathResult.STRING_TYPE) { - result = result.stringValue; - } - else if (result.resultType == XPathResult.NUMBER_TYPE) { - result = result.numberValue; - } - else if (result.resultType == XPathResult.BOOLEAN_TYPE) { - result = result.booleanValue; - } - else { - result = result.nodes; - if (single) { - result = result[0]; - } - } - - return result; -}; - -exports.select1 = function(e, doc) { - return exports.select(e, doc, true); -}; - -// end non-node wrapper + // end non-node wrapper })(xpath); diff --git a/package-lock.json b/package-lock.json index b6e275f..f5afb31 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,13 +1,84 @@ { "name": "get-xml-info", "version": "1.1.0", - "lockfileVersion": 1, + "lockfileVersion": 2, "requires": true, + "packages": { + "": { + "name": "get-xml-info", + "version": "1.1.0", + "license": "ISC", + "dependencies": { + "@actions/core": "^1.10.0", + "minimist": "^1.2.7", + "xmldom": "^0.6.0", + "xpath": "0.0.32" + }, + "devDependencies": {} + }, + "node_modules/@actions/core": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.10.0.tgz", + "integrity": "sha512-2aZDDa3zrrZbP5ZYg159sNoLRb61nQ7awl5pSvIq5Qpj81vwDzdMRKzkWJGJuwVvWpvZKx7vspJALyvaaIQyug==", + "dependencies": { + "@actions/http-client": "^2.0.1", + "uuid": "^8.3.2" + } + }, + "node_modules/@actions/http-client": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.0.1.tgz", + "integrity": "sha512-PIXiMVtz6VvyaRsGY268qvj57hXQEpsYogYOu2nrQhlf+XCGmZstmuZBbAybUl1nQGnvS1k1eEsQ69ZoD7xlSw==", + "dependencies": { + "tunnel": "^0.0.6" + } + }, + "node_modules/minimist": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz", + "integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tunnel": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz", + "integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==", + "engines": { + "node": ">=0.6.11 <=0.7.0 || >=0.7.3" + } + }, + "node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/xmldom": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/xmldom/-/xmldom-0.6.0.tgz", + "integrity": "sha512-iAcin401y58LckRZ0TkI4k0VSM1Qg0KGSc3i8rU+xrxe19A/BN1zHyVSJY7uoutVlaTSzYyk/v5AmkewAP7jtg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/xpath": { + "version": "0.0.32", + "resolved": "https://registry.npmjs.org/xpath/-/xpath-0.0.32.tgz", + "integrity": "sha512-rxMJhSIoiO8vXcWvSifKqhvV96GjiD5wYb8/QHdoRyQvraTpp4IEv944nhGausZZ3u7dhQXteZuZbaqfpB7uYw==", + "engines": { + "node": ">=0.6.0" + } + } + }, "dependencies": { "@actions/core": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.9.1.tgz", - "integrity": "sha512-5ad+U2YGrmmiw6du20AQW5XuWo7UKN2052FjSV7MX+Wfjf8sCqcsZe62NfgHys4QI4/Y+vQvLKYL8jWtA1ZBTA==", + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.10.0.tgz", + "integrity": "sha512-2aZDDa3zrrZbP5ZYg159sNoLRb61nQ7awl5pSvIq5Qpj81vwDzdMRKzkWJGJuwVvWpvZKx7vspJALyvaaIQyug==", "requires": { "@actions/http-client": "^2.0.1", "uuid": "^8.3.2" @@ -22,9 +93,9 @@ } }, "minimist": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz", - "integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==" + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.7.tgz", + "integrity": "sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==" }, "tunnel": { "version": "0.0.6", @@ -37,14 +108,14 @@ "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==" }, "xmldom": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/xmldom/-/xmldom-0.5.0.tgz", - "integrity": "sha512-Foaj5FXVzgn7xFzsKeNIde9g6aFBxTPi37iwsno8QvApmtg7KYrr+OPyRHcJF7dud2a5nGRBXK3n0dL62Gf7PA==" + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/xmldom/-/xmldom-0.6.0.tgz", + "integrity": "sha512-iAcin401y58LckRZ0TkI4k0VSM1Qg0KGSc3i8rU+xrxe19A/BN1zHyVSJY7uoutVlaTSzYyk/v5AmkewAP7jtg==" }, "xpath": { - "version": "0.0.27", - "resolved": "https://registry.npmjs.org/xpath/-/xpath-0.0.27.tgz", - "integrity": "sha512-fg03WRxtkCV6ohClePNAECYsmpKKTv5L8y/X3Dn1hQrec3POx2jHZ/0P2qQ6HvsrU1BmeqXcof3NGGueG6LxwQ==" + "version": "0.0.32", + "resolved": "https://registry.npmjs.org/xpath/-/xpath-0.0.32.tgz", + "integrity": "sha512-rxMJhSIoiO8vXcWvSifKqhvV96GjiD5wYb8/QHdoRyQvraTpp4IEv944nhGausZZ3u7dhQXteZuZbaqfpB7uYw==" } } } diff --git a/package.json b/package.json index caf1220..d0b4df7 100644 --- a/package.json +++ b/package.json @@ -10,10 +10,10 @@ "author": "", "license": "ISC", "dependencies": { - "@actions/core": "^1.9.1", - "minimist": "^1.2.6", - "xmldom": "^0.5.0", - "xpath": "0.0.27" + "@actions/core": "^1.10.0", + "minimist": "^1.2.7", + "xmldom": "^0.6.0", + "xpath": "0.0.32" }, "devDependencies": {}, "repository": { From b4ea4530e67ee22ee79aab5682111cc1fdc8710b Mon Sep 17 00:00:00 2001 From: Teko012 <112829523+Teko012@users.noreply.github.com> Date: Sat, 22 Oct 2022 22:31:03 +0200 Subject: [PATCH 2/3] Update to node16 Update to use Node16 --- action.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/action.yml b/action.yml index 6629960..7bda82c 100644 --- a/action.yml +++ b/action.yml @@ -14,5 +14,5 @@ inputs: required: true default: '//element' runs: - using: 'node12' + using: 'node16' main: 'index.js' From 66d740a01d74a260037146b6cbf252d272f066f9 Mon Sep 17 00:00:00 2001 From: Teko012 <112829523+Teko012@users.noreply.github.com> Date: Sat, 22 Oct 2022 23:11:17 +0200 Subject: [PATCH 3/3] Convert output to string --- index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.js b/index.js index 29a3618..8ef03da 100644 --- a/index.js +++ b/index.js @@ -46,7 +46,7 @@ try { output.push(node.value); } } - core.setOutput('info', output); + core.setOutput('info', String(output)); console.log(`Output: ${output}`); } else {