text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const EventModifierInit = require("./EventModifierInit"); module.exports = { convertInherit(obj, ret) { EventModifierInit.convertInherit(obj, ret); let key, value; key = "charCode"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["unsigned long"](value); } else { ret[key] = 0; } key = "code"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["DOMString"](value); } else { ret[key] = ""; } key = "isComposing"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "key"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["DOMString"](value); } else { ret[key] = ""; } key = "keyCode"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["unsigned long"](value); } else { ret[key] = 0; } key = "location"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["unsigned long"](value); } else { ret[key] = 0; } key = "repeat"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "which"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["unsigned long"](value); } else { ret[key] = 0; } }, convert(obj) { if (obj !== undefined && typeof obj !== "object") { throw new TypeError("Dictionary has to be an object"); } if (obj instanceof Date || obj instanceof RegExp) { throw new TypeError("Dictionary may not be a Date or RegExp object"); } const ret = Object.create(null); module.exports.convertInherit(obj, ret); return ret; } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/KeyboardEventInit.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
595
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const EventInit = require("./EventInit"); module.exports = { convertInherit(obj, ret) { EventInit.convertInherit(obj, ret); let key, value; key = "detail"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = (value); } else { ret[key] = null; } }, convert(obj) { if (obj !== undefined && typeof obj !== "object") { throw new TypeError("Dictionary has to be an object"); } if (obj instanceof Date || obj instanceof RegExp) { throw new TypeError("Dictionary may not be a Date or RegExp object"); } const ret = Object.create(null); module.exports.convertInherit(obj, ret); return ret; } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/CustomEventInit.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
200
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const Impl = require("../events/ProgressEvent-impl.js"); const Event = require("./Event.js"); const impl = utils.implSymbol; const convertProgressEventInit = require("./ProgressEventInit").convert; function ProgressEvent(type) { if (!this || this[impl] || !(this instanceof ProgressEvent)) { throw new TypeError("Failed to construct 'ProgressEvent': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); } if (arguments.length < 1) { throw new TypeError("Failed to construct 'ProgressEvent': 1 argument required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 2; ++i) { args[i] = arguments[i]; } args[0] = conversions["DOMString"](args[0]); args[1] = convertProgressEventInit(args[1]); module.exports.setup(this, args); } ProgressEvent.prototype = Object.create(Event.interface.prototype); ProgressEvent.prototype.constructor = ProgressEvent; Object.defineProperty(ProgressEvent.prototype, "lengthComputable", { get() { return this[impl].lengthComputable; }, enumerable: true, configurable: true }); Object.defineProperty(ProgressEvent.prototype, "loaded", { get() { return this[impl].loaded; }, enumerable: true, configurable: true }); Object.defineProperty(ProgressEvent.prototype, "total", { get() { return this[impl].total; }, enumerable: true, configurable: true }); module.exports = { is(obj) { return !!obj && obj[impl] instanceof Impl.implementation; }, create(constructorArgs, privateData) { let obj = Object.create(ProgressEvent.prototype); this.setup(obj, constructorArgs, privateData); return obj; }, setup(obj, constructorArgs, privateData) { if (!privateData) privateData = {}; privateData.wrapper = obj; obj[impl] = new Impl.implementation(constructorArgs, privateData); obj[impl][utils.wrapperSymbol] = obj; }, interface: ProgressEvent, expose: { Window: { ProgressEvent: ProgressEvent }, DedicatedWorker: { ProgressEvent: ProgressEvent }, SharedWorker: { ProgressEvent: ProgressEvent } } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/ProgressEvent.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
532
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const EventModifierInit = require("./EventModifierInit"); module.exports = { convertInherit(obj, ret) { EventModifierInit.convertInherit(obj, ret); let key, value; key = "button"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["short"](value); } else { ret[key] = 0; } key = "buttons"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["unsigned short"](value); } else { ret[key] = 0; } key = "clientX"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["long"](value); } else { ret[key] = 0; } key = "clientY"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["long"](value); } else { ret[key] = 0; } key = "relatedTarget"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = (value); } else { ret[key] = null; } key = "screenX"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["long"](value); } else { ret[key] = 0; } key = "screenY"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["long"](value); } else { ret[key] = 0; } }, convert(obj) { if (obj !== undefined && typeof obj !== "object") { throw new TypeError("Dictionary has to be an object"); } if (obj instanceof Date || obj instanceof RegExp) { throw new TypeError("Dictionary may not be a Date or RegExp object"); } const ret = Object.create(null); module.exports.convertInherit(obj, ret); return ret; } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/MouseEventInit.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
539
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const EventInit = require("./EventInit"); module.exports = { convertInherit(obj, ret) { EventInit.convertInherit(obj, ret); let key, value; key = "newURL"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["DOMString"](value); } key = "oldURL"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["DOMString"](value); } }, convert(obj) { if (obj !== undefined && typeof obj !== "object") { throw new TypeError("Dictionary has to be an object"); } if (obj instanceof Date || obj instanceof RegExp) { throw new TypeError("Dictionary may not be a Date or RegExp object"); } const ret = Object.create(null); module.exports.convertInherit(obj, ret); return ret; } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/HashChangeEventInit.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
239
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const Impl = require("../events/KeyboardEvent-impl.js"); const UIEvent = require("./UIEvent.js"); const impl = utils.implSymbol; const convertKeyboardEventInit = require("./KeyboardEventInit").convert; function KeyboardEvent(typeArg) { if (!this || this[impl] || !(this instanceof KeyboardEvent)) { throw new TypeError("Failed to construct 'KeyboardEvent': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); } if (arguments.length < 1) { throw new TypeError("Failed to construct 'KeyboardEvent': 1 argument required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 2; ++i) { args[i] = arguments[i]; } args[0] = conversions["DOMString"](args[0]); args[1] = convertKeyboardEventInit(args[1]); module.exports.setup(this, args); } KeyboardEvent.prototype = Object.create(UIEvent.interface.prototype); KeyboardEvent.prototype.constructor = KeyboardEvent; KeyboardEvent.prototype.getModifierState = function getModifierState(keyArg) { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } if (arguments.length < 1) { throw new TypeError("Failed to execute 'getModifierState' on 'KeyboardEvent': 1 argument required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 1; ++i) { args[i] = arguments[i]; } args[0] = conversions["DOMString"](args[0]); return this[impl].getModifierState.apply(this[impl], args); }; KeyboardEvent.prototype.initKeyboardEvent = function initKeyboardEvent(typeArg, bubblesArg, cancelableArg, viewArg, keyArg, locationArg, modifiersListArg, repeat, locale) { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } if (arguments.length < 9) { throw new TypeError("Failed to execute 'initKeyboardEvent' on 'KeyboardEvent': 9 arguments required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 9; ++i) { args[i] = arguments[i]; } args[0] = conversions["DOMString"](args[0]); args[1] = conversions["boolean"](args[1]); args[2] = conversions["boolean"](args[2]); args[4] = conversions["DOMString"](args[4]); args[5] = conversions["unsigned long"](args[5]); args[6] = conversions["DOMString"](args[6]); args[7] = conversions["boolean"](args[7]); args[8] = conversions["DOMString"](args[8]); return this[impl].initKeyboardEvent.apply(this[impl], args); }; Object.defineProperty(KeyboardEvent, "DOM_KEY_LOCATION_STANDARD", { value: 0, enumerable: true }); Object.defineProperty(KeyboardEvent.prototype, "DOM_KEY_LOCATION_STANDARD", { value: 0, enumerable: true }); Object.defineProperty(KeyboardEvent, "DOM_KEY_LOCATION_LEFT", { value: 1, enumerable: true }); Object.defineProperty(KeyboardEvent.prototype, "DOM_KEY_LOCATION_LEFT", { value: 1, enumerable: true }); Object.defineProperty(KeyboardEvent, "DOM_KEY_LOCATION_RIGHT", { value: 2, enumerable: true }); Object.defineProperty(KeyboardEvent.prototype, "DOM_KEY_LOCATION_RIGHT", { value: 2, enumerable: true }); Object.defineProperty(KeyboardEvent, "DOM_KEY_LOCATION_NUMPAD", { value: 3, enumerable: true }); Object.defineProperty(KeyboardEvent.prototype, "DOM_KEY_LOCATION_NUMPAD", { value: 3, enumerable: true }); Object.defineProperty(KeyboardEvent.prototype, "key", { get() { return this[impl].key; }, enumerable: true, configurable: true }); Object.defineProperty(KeyboardEvent.prototype, "code", { get() { return this[impl].code; }, enumerable: true, configurable: true }); Object.defineProperty(KeyboardEvent.prototype, "location", { get() { return this[impl].location; }, enumerable: true, configurable: true }); Object.defineProperty(KeyboardEvent.prototype, "ctrlKey", { get() { return this[impl].ctrlKey; }, enumerable: true, configurable: true }); Object.defineProperty(KeyboardEvent.prototype, "shiftKey", { get() { return this[impl].shiftKey; }, enumerable: true, configurable: true }); Object.defineProperty(KeyboardEvent.prototype, "altKey", { get() { return this[impl].altKey; }, enumerable: true, configurable: true }); Object.defineProperty(KeyboardEvent.prototype, "metaKey", { get() { return this[impl].metaKey; }, enumerable: true, configurable: true }); Object.defineProperty(KeyboardEvent.prototype, "repeat", { get() { return this[impl].repeat; }, enumerable: true, configurable: true }); Object.defineProperty(KeyboardEvent.prototype, "isComposing", { get() { return this[impl].isComposing; }, enumerable: true, configurable: true }); Object.defineProperty(KeyboardEvent.prototype, "charCode", { get() { return this[impl].charCode; }, enumerable: true, configurable: true }); Object.defineProperty(KeyboardEvent.prototype, "keyCode", { get() { return this[impl].keyCode; }, enumerable: true, configurable: true }); Object.defineProperty(KeyboardEvent.prototype, "which", { get() { return this[impl].which; }, enumerable: true, configurable: true }); module.exports = { is(obj) { return !!obj && obj[impl] instanceof Impl.implementation; }, create(constructorArgs, privateData) { let obj = Object.create(KeyboardEvent.prototype); this.setup(obj, constructorArgs, privateData); return obj; }, setup(obj, constructorArgs, privateData) { if (!privateData) privateData = {}; privateData.wrapper = obj; obj[impl] = new Impl.implementation(constructorArgs, privateData); obj[impl][utils.wrapperSymbol] = obj; }, interface: KeyboardEvent, expose: { Window: { KeyboardEvent: KeyboardEvent } } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/KeyboardEvent.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,484
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const Impl = require("../events/ErrorEvent-impl.js"); const Event = require("./Event.js"); const impl = utils.implSymbol; const convertErrorEventInit = require("./ErrorEventInit").convert; function ErrorEvent(type) { if (!this || this[impl] || !(this instanceof ErrorEvent)) { throw new TypeError("Failed to construct 'ErrorEvent': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); } if (arguments.length < 1) { throw new TypeError("Failed to construct 'ErrorEvent': 1 argument required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 2; ++i) { args[i] = arguments[i]; } args[0] = conversions["DOMString"](args[0]); args[1] = convertErrorEventInit(args[1]); module.exports.setup(this, args); } ErrorEvent.prototype = Object.create(Event.interface.prototype); ErrorEvent.prototype.constructor = ErrorEvent; Object.defineProperty(ErrorEvent.prototype, "message", { get() { return this[impl].message; }, enumerable: true, configurable: true }); Object.defineProperty(ErrorEvent.prototype, "filename", { get() { return this[impl].filename; }, enumerable: true, configurable: true }); Object.defineProperty(ErrorEvent.prototype, "lineno", { get() { return this[impl].lineno; }, enumerable: true, configurable: true }); Object.defineProperty(ErrorEvent.prototype, "colno", { get() { return this[impl].colno; }, enumerable: true, configurable: true }); Object.defineProperty(ErrorEvent.prototype, "error", { get() { return this[impl].error; }, enumerable: true, configurable: true }); module.exports = { is(obj) { return !!obj && obj[impl] instanceof Impl.implementation; }, create(constructorArgs, privateData) { let obj = Object.create(ErrorEvent.prototype); this.setup(obj, constructorArgs, privateData); return obj; }, setup(obj, constructorArgs, privateData) { if (!privateData) privateData = {}; privateData.wrapper = obj; obj[impl] = new Impl.implementation(constructorArgs, privateData); obj[impl][utils.wrapperSymbol] = obj; }, interface: ErrorEvent, expose: { Window: { ErrorEvent: ErrorEvent }, Worker: { ErrorEvent: ErrorEvent } } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/ErrorEvent.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
583
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); module.exports = { convertInherit(obj, ret) { let key, value; key = "bubbles"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "cancelable"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } }, convert(obj) { if (obj !== undefined && typeof obj !== "object") { throw new TypeError("Dictionary has to be an object"); } if (obj instanceof Date || obj instanceof RegExp) { throw new TypeError("Dictionary may not be a Date or RegExp object"); } const ret = Object.create(null); module.exports.convertInherit(obj, ret); return ret; } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/EventInit.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
240
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const Impl = require("../events/HashChangeEvent-impl.js"); const Event = require("./Event.js"); const impl = utils.implSymbol; const convertHashChangeEventInit = require("./HashChangeEventInit").convert; function HashChangeEvent(type) { if (!this || this[impl] || !(this instanceof HashChangeEvent)) { throw new TypeError("Failed to construct 'HashChangeEvent': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); } if (arguments.length < 1) { throw new TypeError("Failed to construct 'HashChangeEvent': 1 argument required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 2; ++i) { args[i] = arguments[i]; } args[0] = conversions["DOMString"](args[0]); args[1] = convertHashChangeEventInit(args[1]); module.exports.setup(this, args); } HashChangeEvent.prototype = Object.create(Event.interface.prototype); HashChangeEvent.prototype.constructor = HashChangeEvent; Object.defineProperty(HashChangeEvent.prototype, "oldURL", { get() { return this[impl].oldURL; }, enumerable: true, configurable: true }); Object.defineProperty(HashChangeEvent.prototype, "newURL", { get() { return this[impl].newURL; }, enumerable: true, configurable: true }); module.exports = { is(obj) { return !!obj && obj[impl] instanceof Impl.implementation; }, create(constructorArgs, privateData) { let obj = Object.create(HashChangeEvent.prototype); this.setup(obj, constructorArgs, privateData); return obj; }, setup(obj, constructorArgs, privateData) { if (!privateData) privateData = {}; privateData.wrapper = obj; obj[impl] = new Impl.implementation(constructorArgs, privateData); obj[impl][utils.wrapperSymbol] = obj; }, interface: HashChangeEvent, expose: { Window: { HashChangeEvent: HashChangeEvent }, Worker: { HashChangeEvent: HashChangeEvent } } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/HashChangeEvent.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
484
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const Impl = require("../events/EventTarget-impl.js"); const impl = utils.implSymbol; function EventTarget() { throw new TypeError("Illegal constructor"); } EventTarget.prototype.addEventListener = function addEventListener(type, callback) { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } if (arguments.length < 2) { throw new TypeError("Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 3; ++i) { args[i] = arguments[i]; } args[0] = conversions["DOMString"](args[0]); if (args[2] !== undefined) { args[2] = conversions["boolean"](args[2]); } return this[impl].addEventListener.apply(this[impl], args); }; EventTarget.prototype.removeEventListener = function removeEventListener(type, callback) { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } if (arguments.length < 2) { throw new TypeError("Failed to execute 'removeEventListener' on 'EventTarget': 2 arguments required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 3; ++i) { args[i] = arguments[i]; } args[0] = conversions["DOMString"](args[0]); if (args[2] !== undefined) { args[2] = conversions["boolean"](args[2]); } return this[impl].removeEventListener.apply(this[impl], args); }; EventTarget.prototype.dispatchEvent = function dispatchEvent(event) { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } if (arguments.length < 1) { throw new TypeError("Failed to execute 'dispatchEvent' on 'EventTarget': 1 argument required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 1; ++i) { args[i] = arguments[i]; } return this[impl].dispatchEvent.apply(this[impl], args); }; module.exports = { is(obj) { return !!obj && obj[impl] instanceof Impl.implementation; }, create(constructorArgs, privateData) { let obj = Object.create(EventTarget.prototype); this.setup(obj, constructorArgs, privateData); return obj; }, setup(obj, constructorArgs, privateData) { if (!privateData) privateData = {}; privateData.wrapper = obj; obj[impl] = new Impl.implementation(constructorArgs, privateData); obj[impl][utils.wrapperSymbol] = obj; }, interface: EventTarget, expose: { Window: { EventTarget: EventTarget }, Worker: { EventTarget: EventTarget } } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
689
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const EventInit = require("./EventInit"); module.exports = { convertInherit(obj, ret) { EventInit.convertInherit(obj, ret); let key, value; key = "colno"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["unsigned long"](value); } key = "error"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = (value); } key = "filename"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["DOMString"](value); } key = "lineno"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["unsigned long"](value); } key = "message"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["DOMString"](value); } }, convert(obj) { if (obj !== undefined && typeof obj !== "object") { throw new TypeError("Dictionary has to be an object"); } if (obj instanceof Date || obj instanceof RegExp) { throw new TypeError("Dictionary may not be a Date or RegExp object"); } const ret = Object.create(null); module.exports.convertInherit(obj, ret); return ret; } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/ErrorEventInit.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
366
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const Impl = require("../elements/HTMLTemplateElement-impl.js"); const HTMLElement = require("./HTMLElement.js"); const impl = utils.implSymbol; function HTMLTemplateElement() { throw new TypeError("Illegal constructor"); } HTMLTemplateElement.prototype = Object.create(HTMLElement.interface.prototype); HTMLTemplateElement.prototype.constructor = HTMLTemplateElement; Object.defineProperty(HTMLTemplateElement.prototype, "content", { get() { return this[impl].content; }, enumerable: true, configurable: true }); module.exports = { is(obj) { return !!obj && obj[impl] instanceof Impl.implementation; }, create(constructorArgs, privateData) { let obj = Object.create(HTMLTemplateElement.prototype); this.setup(obj, constructorArgs, privateData); return obj; }, setup(obj, constructorArgs, privateData) { if (!privateData) privateData = {}; privateData.wrapper = obj; obj[impl] = new Impl.implementation(constructorArgs, privateData); obj[impl][utils.wrapperSymbol] = obj; }, interface: HTMLTemplateElement, expose: { Window: { HTMLTemplateElement: HTMLTemplateElement } } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/HTMLTemplateElement.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
274
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const Impl = require("../events/CustomEvent-impl.js"); const Event = require("./Event.js"); const impl = utils.implSymbol; const convertCustomEventInit = require("./CustomEventInit").convert; function CustomEvent(type) { if (!this || this[impl] || !(this instanceof CustomEvent)) { throw new TypeError("Failed to construct 'CustomEvent': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); } if (arguments.length < 1) { throw new TypeError("Failed to construct 'CustomEvent': 1 argument required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 2; ++i) { args[i] = arguments[i]; } args[0] = conversions["DOMString"](args[0]); args[1] = convertCustomEventInit(args[1]); module.exports.setup(this, args); } CustomEvent.prototype = Object.create(Event.interface.prototype); CustomEvent.prototype.constructor = CustomEvent; CustomEvent.prototype.initCustomEvent = function initCustomEvent(type, bubbles, cancelable, detail) { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } if (arguments.length < 4) { throw new TypeError("Failed to execute 'initCustomEvent' on 'CustomEvent': 4 arguments required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 4; ++i) { args[i] = arguments[i]; } args[0] = conversions["DOMString"](args[0]); args[1] = conversions["boolean"](args[1]); args[2] = conversions["boolean"](args[2]); return this[impl].initCustomEvent.apply(this[impl], args); }; Object.defineProperty(CustomEvent.prototype, "detail", { get() { return this[impl].detail; }, enumerable: true, configurable: true }); module.exports = { is(obj) { return !!obj && obj[impl] instanceof Impl.implementation; }, create(constructorArgs, privateData) { let obj = Object.create(CustomEvent.prototype); this.setup(obj, constructorArgs, privateData); return obj; }, setup(obj, constructorArgs, privateData) { if (!privateData) privateData = {}; privateData.wrapper = obj; obj[impl] = new Impl.implementation(constructorArgs, privateData); obj[impl][utils.wrapperSymbol] = obj; }, interface: CustomEvent, expose: { Window: { CustomEvent: CustomEvent }, Worker: { CustomEvent: CustomEvent } } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/CustomEvent.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
630
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const UIEventInit = require("./UIEventInit"); module.exports = { convertInherit(obj, ret) { UIEventInit.convertInherit(obj, ret); let key, value; key = "altKey"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "ctrlKey"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "metaKey"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "modifierAltGraph"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "modifierCapsLock"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "modifierFn"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "modifierFnLock"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "modifierHyper"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "modifierNumLock"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "modifierOS"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "modifierScrollLock"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "modifierSuper"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "modifierSymbol"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "modifierSymbolLock"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } key = "shiftKey"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["boolean"](value); } else { ret[key] = false; } }, convert(obj) { if (obj !== undefined && typeof obj !== "object") { throw new TypeError("Dictionary has to be an object"); } if (obj instanceof Date || obj instanceof RegExp) { throw new TypeError("Dictionary may not be a Date or RegExp object"); } const ret = Object.create(null); module.exports.convertInherit(obj, ret); return ret; } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/EventModifierInit.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
983
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const Impl = require("../events/UIEvent-impl.js"); const Event = require("./Event.js"); const impl = utils.implSymbol; const convertUIEventInit = require("./UIEventInit").convert; function UIEvent(type) { if (!this || this[impl] || !(this instanceof UIEvent)) { throw new TypeError("Failed to construct 'UIEvent': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); } if (arguments.length < 1) { throw new TypeError("Failed to construct 'UIEvent': 1 argument required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 2; ++i) { args[i] = arguments[i]; } args[0] = conversions["DOMString"](args[0]); args[1] = convertUIEventInit(args[1]); module.exports.setup(this, args); } UIEvent.prototype = Object.create(Event.interface.prototype); UIEvent.prototype.constructor = UIEvent; UIEvent.prototype.initUIEvent = function initUIEvent(typeArg, bubblesArg, cancelableArg, viewArg, detailArg) { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } if (arguments.length < 5) { throw new TypeError("Failed to execute 'initUIEvent' on 'UIEvent': 5 arguments required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 5; ++i) { args[i] = arguments[i]; } args[0] = conversions["DOMString"](args[0]); args[1] = conversions["boolean"](args[1]); args[2] = conversions["boolean"](args[2]); args[4] = conversions["long"](args[4]); return this[impl].initUIEvent.apply(this[impl], args); }; Object.defineProperty(UIEvent.prototype, "view", { get() { return this[impl].view; }, enumerable: true, configurable: true }); Object.defineProperty(UIEvent.prototype, "detail", { get() { return this[impl].detail; }, enumerable: true, configurable: true }); module.exports = { is(obj) { return !!obj && obj[impl] instanceof Impl.implementation; }, create(constructorArgs, privateData) { let obj = Object.create(UIEvent.prototype); this.setup(obj, constructorArgs, privateData); return obj; }, setup(obj, constructorArgs, privateData) { if (!privateData) privateData = {}; privateData.wrapper = obj; obj[impl] = new Impl.implementation(constructorArgs, privateData); obj[impl][utils.wrapperSymbol] = obj; }, interface: UIEvent, expose: { Window: { UIEvent: UIEvent } } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/UIEvent.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
673
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const EventInit = require("./EventInit"); module.exports = { convertInherit(obj, ret) { EventInit.convertInherit(obj, ret); let key, value; key = "data"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = (value); } key = "lastEventId"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["DOMString"](value); } key = "origin"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = conversions["DOMString"](value); } key = "ports"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = (value); } key = "source"; value = obj === undefined || obj === null ? undefined : obj[key]; if (value !== undefined) { ret[key] = (value); } }, convert(obj) { if (obj !== undefined && typeof obj !== "object") { throw new TypeError("Dictionary has to be an object"); } if (obj instanceof Date || obj instanceof RegExp) { throw new TypeError("Dictionary may not be a Date or RegExp object"); } const ret = Object.create(null); module.exports.convertInherit(obj, ret); return ret; } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/MessageEventInit.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
359
```javascript "use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const Impl = require("../attributes/Attr-impl.js"); const impl = utils.implSymbol; function Attr() { throw new TypeError("Illegal constructor"); } Object.defineProperty(Attr.prototype, "namespaceURI", { get() { return this[impl].namespaceURI; }, enumerable: true, configurable: true }); Object.defineProperty(Attr.prototype, "prefix", { get() { return this[impl].prefix; }, enumerable: true, configurable: true }); Object.defineProperty(Attr.prototype, "localName", { get() { return this[impl].localName; }, enumerable: true, configurable: true }); Object.defineProperty(Attr.prototype, "name", { get() { return this[impl].name; }, enumerable: true, configurable: true }); Object.defineProperty(Attr.prototype, "value", { get() { return this[impl].value; }, set(V) { V = conversions["DOMString"](V); this[impl].value = V; }, enumerable: true, configurable: true }); Object.defineProperty(Attr.prototype, "nodeValue", { get() { return this[impl].nodeValue; }, set(V) { V = conversions["DOMString"](V, { treatNullAsEmptyString: true }); this[impl].nodeValue = V; }, enumerable: true, configurable: true }); Object.defineProperty(Attr.prototype, "textContent", { get() { return this[impl].textContent; }, set(V) { V = conversions["DOMString"](V, { treatNullAsEmptyString: true }); this[impl].textContent = V; }, enumerable: true, configurable: true }); Object.defineProperty(Attr.prototype, "ownerElement", { get() { return this[impl].ownerElement; }, enumerable: true, configurable: true }); Object.defineProperty(Attr.prototype, "specified", { get() { return this[impl].specified; }, enumerable: true, configurable: true }); module.exports = { is(obj) { return !!obj && obj[impl] instanceof Impl.implementation; }, create(constructorArgs, privateData) { let obj = Object.create(Attr.prototype); this.setup(obj, constructorArgs, privateData); return obj; }, setup(obj, constructorArgs, privateData) { if (!privateData) privateData = {}; privateData.wrapper = obj; obj[impl] = new Impl.implementation(constructorArgs, privateData); obj[impl][utils.wrapperSymbol] = obj; }, interface: Attr, expose: { Window: { Attr: Attr } } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/generated/Attr.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
612
```javascript "use strict"; const SymbolTree = require("symbol-tree"); exports.cloningSteps = Symbol("cloning steps"); exports.locationInfo = Symbol("location info"); exports.accept = Symbol("accept"); exports.requestManager = Symbol("request manager"); exports.pool = Symbol("pool"); exports.agentOptions = Symbol("agentOptions"); // TODO: the many underscore-prefixed hooks should move here // E.g. _attrModified (which maybe should be split into its per-spec variants) /** * This SymbolTree is used to build the tree for all Node in a document */ exports.domSymbolTree = new SymbolTree("DOM SymbolTree"); ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/helpers/internal-constants.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
130
```javascript "use strict"; module.exports = function orderedSetParser(input) { return new Set(input.split(/\s+/).filter(Boolean)); }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/helpers/ordered-set-parser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
28
```javascript "use strict"; // path_to_url#event-handlers-on-elements,-document-objects,-and-window-objects module.exports = new Set(["onblur", "onerror", "onfocus", "onload", "onresize", "onscroll", "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onstorage", "onunload"]); // level2/html sets up setters/getters on HTMLBodyElement that proxy to the window (setting data properties there) // level1/core sets up so that modifying the appropriate attributes on body elements will forward to setting on // the window, with the appropriate `this`. ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/helpers/proxied-window-event-handlers.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
170
```javascript "use strict"; const xnv = require("xml-name-validator"); const DOMException = require("../../web-idl/DOMException"); // path_to_url#validate exports.name = function (name) { const result = xnv.name(name); if (!result.success) { throw new DOMException(DOMException.INVALID_CHARACTER_ERR, "\"" + name + "\" did not match the Name production: " + result.error); } }; exports.qname = function (qname) { exports.name(qname); const result = xnv.qname(qname); if (!result.success) { throw new DOMException(DOMException.NAMESPACE_ERR, "\"" + qname + "\" did not match the QName production: " + result.error); } }; exports.validateAndExtract = function (namespace, qualifiedName) { if (namespace === "") { namespace = null; } exports.qname(qualifiedName); let prefix = null; let localName = qualifiedName; const colonIndex = qualifiedName.indexOf(":"); if (colonIndex !== -1) { prefix = qualifiedName.substring(0, colonIndex); localName = qualifiedName.substring(colonIndex + 1); } if (prefix !== null && namespace === null) { throw new DOMException(DOMException.NAMESPACE_ERR, "A namespace was given but a prefix was also extracted from the qualifiedName"); } if (prefix === "xml" && namespace !== "path_to_url") { throw new DOMException(DOMException.NAMESPACE_ERR, "A prefix of \"xml\" was given but the namespace was not the XML namespace"); } if ((qualifiedName === "xmlns" || prefix === "xmlns") && namespace !== "path_to_url") { throw new DOMException(DOMException.NAMESPACE_ERR, "A prefix or qualifiedName of \"xmlns\" was given but the namespace was not the XMLNS namespace"); } if (namespace === "path_to_url" && qualifiedName !== "xmlns" && prefix !== "xmlns") { throw new DOMException(DOMException.NAMESPACE_ERR, "The XMLNS namespace was given but neither the prefix nor qualifiedName was \"xmlns\""); } return { namespace, prefix, localName }; }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/helpers/validate-names.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
478
```javascript "use strict"; const util = require("util"); const ErrorEvent = require("../generated/ErrorEvent").interface; const errorReportingMode = Symbol("error reporting mode"); // path_to_url#report-the-error // Omits script parameter and any check for muted errors; takes error object, message, and location as params, unlike // the spec. Returns whether the event was handled or not. function reportAnError(line, col, target, errorObject, message, location) { if (errorReportingMode in target) { return false; } target[errorReportingMode] = true; // TODO Events: use constructor directly, once they are no longer tied to a window. const event = new ErrorEvent("error", { bubbles: false, cancelable: true, message, filename: location, lineno: line, colno: col, error: errorObject }); target.dispatchEvent(event); delete target[errorReportingMode]; return event.defaultPrevented; } module.exports = function reportException(window, error, filenameHint) { // This function will give good results on real Error objects with stacks; poor ones otherwise const stack = error && error.stack; const lines = stack && stack.split("\n"); // Find the first line that matches; important for multi-line messages let pieces; if (lines) { for (let i = 1; i < lines.length && !pieces; ++i) { pieces = lines[i].match(/at (?:(.+)\s+)?\(?(?:(.+?):(\d+):(\d+)|([^)]+))\)?/); } } const fileName = pieces && pieces[2] || filenameHint || window._document._URL; const lineNumber = pieces && parseInt(pieces[3]) || 0; const columnNumber = pieces && parseInt(pieces[4]) || 0; const handled = reportAnError(lineNumber, columnNumber, window, error, error.message, fileName); if (!handled) { const jsdomError = new Error(`Uncaught ${util.inspect(error)}`); jsdomError.detail = error; window._virtualConsole.emit("jsdomError", jsdomError); } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
479
```javascript "use strict"; const internalQuerySelector = require("../selectors").querySelector; const internalGetAttr = require("../attributes").getAttributeValue; const URL = require("../../utils").URL; exports.documentBaseURL = function (document) { // path_to_url#document-base-url const firstBase = internalQuerySelector(document, "base[href]"); const fallbackBaseURL = exports.fallbackBaseURL(document); if (firstBase === null) { return fallbackBaseURL; } return exports.frozenBaseURL(firstBase, fallbackBaseURL); }; exports.fallbackBaseURL = function (document) { // path_to_url#fallback-base-url // Unimplemented: <iframe srcdoc> if (document._URL === "about:blank" && document._defaultView && document._defaultView._parent !== document._defaultView) { return module.exports.documentBaseURL(document._defaultView._parent._document); } return document._URL; }; exports.frozenBaseURL = function (baseElement, fallbackBaseURL) { // path_to_url#frozen-base-url // The spec is eager (setting the frozen base URL when things change); we are lazy (getting it when we need to) const baseHrefAttribute = internalGetAttr(baseElement, "href"); try { return new URL(baseHrefAttribute, fallbackBaseURL).href; } catch (e) { return fallbackBaseURL; } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/living/helpers/document-base-url.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
305
```javascript "use strict"; /* DOM Level2 Events implemented as described here: * * path_to_url * */ var core = require("../level1/core"), utils = require("../utils"), defineGetter = utils.defineGetter, defineSetter = utils.defineSetter, inheritFrom = utils.inheritFrom; // The dependencies here are a bit screwy; when we get a chance to move all events to living, things will get simpler. const Event = require("../living/generated/Event"); const CustomEvent = require("../living/generated/CustomEvent"); const MessageEvent = require("../living/generated/MessageEvent"); const ErrorEvent = require("../living/generated/ErrorEvent"); const HashChangeEvent = require("../living/generated/HashChangeEvent"); const UIEvent = require("../living/generated/UIEvent"); const MouseEvent = require("../living/generated/MouseEvent"); const KeyboardEvent = require("../living/generated/KeyboardEvent"); const TouchEvent = require("../living/generated/TouchEvent"); const MutationEvent = require("../living/generated/MutationEvent"); const ProgressEvent = require("../living/generated/ProgressEvent"); const domSymbolTree = require("../living/helpers/internal-constants").domSymbolTree; const NODE_TYPE = require("../living/node-type"); core.Event = Event.interface; core.CustomEvent = CustomEvent.interface; core.MessageEvent = MessageEvent.interface; core.ErrorEvent = ErrorEvent.interface; core.HashChangeEvent = HashChangeEvent.interface; core.UIEvent = UIEvent.interface; core.MouseEvent = MouseEvent.interface; core.KeyboardEvent = KeyboardEvent.interface; core.TouchEvent = TouchEvent.interface; core.MutationEvent = MutationEvent.interface; core.ProgressEvent = ProgressEvent.interface; core.EventTarget = require('../living/generated/EventTarget').interface; // Reinherit class heirarchy with EventTarget at its root inheritFrom(core.EventTarget, core.Node, core.Node.prototype); // Node inheritFrom(core.Node, core.Document, core.Document.prototype); inheritFrom(core.Node, core.DocumentFragment, core.DocumentFragment.prototype); inheritFrom(core.Node, core.Element, core.Element.prototype); function getDocument(el) { return el.nodeType == NODE_TYPE.DOCUMENT_NODE ? el : el._ownerDocument; } function mutationEventsEnabled(el) { return el.nodeType != NODE_TYPE.ATTRIBUTE_NODE && getDocument(el).implementation._hasFeature('MutationEvents'); } var insertBefore_super = core.Node.prototype.insertBefore; core.Node.prototype.insertBefore = function(newChild, refChild) { var ret = insertBefore_super.apply(this, arguments); if (mutationEventsEnabled(this)) { var doc = getDocument(this), ev = doc.createEvent("MutationEvents"); ev.initMutationEvent("DOMNodeInserted", true, false, this, null, null, null, null); newChild.dispatchEvent(ev); ev = doc.createEvent("MutationEvents"); ev.initMutationEvent("DOMSubtreeModified", true, false, this, null, null, null, null); this.dispatchEvent(ev); if (this.nodeType == NODE_TYPE.DOCUMENT_NODE || this._attachedToDocument) { ev = doc.createEvent("MutationEvents"); ev.initMutationEvent("DOMNodeInsertedIntoDocument", false, false, null, null, null, null, null); for (const el of domSymbolTree.treeIterator(newChild)) { if (el.nodeType == NODE_TYPE.ELEMENT_NODE) { el.dispatchEvent(ev); el._attachedToDocument = true; } } } } return ret; }; var removeChild_super = core.Node.prototype.removeChild; core.Node.prototype.removeChild = function (oldChild) { if (mutationEventsEnabled(this)) { var doc = getDocument(this), ev = doc.createEvent("MutationEvents"); ev.initMutationEvent("DOMNodeRemoved", true, false, this, null, null, null, null); oldChild.dispatchEvent(ev); ev = doc.createEvent("MutationEvents"); ev.initMutationEvent("DOMSubtreeModified", true, false, this, null, null, null, null); this.dispatchEvent(ev); ev = doc.createEvent("MutationEvents"); ev.initMutationEvent("DOMNodeRemovedFromDocument", false, false, null, null, null, null, null); for (const el of domSymbolTree.treeIterator(oldChild)) { if (el.nodeType == NODE_TYPE.ELEMENT_NODE) { el.dispatchEvent(ev); el._attachedToDocument = false; } } } return removeChild_super.apply(this, arguments); }; var _attrModified_super = core.Node.prototype._attrModified; core.Node.prototype._attrModified = function (name, value, oldValue) { var ret = _attrModified_super.apply(this, arguments); if (mutationEventsEnabled(this) && value !== oldValue) { var doc = getDocument(this), ev = doc.createEvent("MutationEvents"); ev.initMutationEvent("DOMSubtreeModified", true, false, this, null, null, null, null); this.dispatchEvent(ev); } return ret; }; var interfaceTable = { event: Event, events: Event, htmlevents: Event, mouseevent: MouseEvent, mouseevents: MouseEvent, uievent: UIEvent, uievents: UIEvent, messageevent: MessageEvent, customevent: CustomEvent, keyboardevent: KeyboardEvent, keyevents: KeyboardEvent, touchevent: TouchEvent, // old, not part of spec anymore mutationevents: MutationEvent }; core.Document.prototype.createEvent = function (type) { var typeLower = type.toLowerCase(); var Event = interfaceTable[typeLower] || null; if (!Event) { throw new core.DOMException(core.DOMException.NOT_SUPPORTED_ERR, "The provided event type (\"" + type + "\") is invalid"); } return Event.create([""]); }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/level2/events.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,211
```javascript "use strict"; var resourceLoader = require('../browser/resource-loader'), core = require("../level1/core"), utils = require("../utils"), defineGetter = utils.defineGetter, inheritFrom = utils.inheritFrom, cssom = require("cssom"), cssstyle = require("cssstyle"), resolveHref = require("../utils").resolveHref, assert = require('assert'); const domSymbolTree = require("../living/helpers/internal-constants").domSymbolTree; const NODE_TYPE = require("../living/node-type"); // What works now: // - Accessing the rules defined in individual stylesheets // - Modifications to style content attribute are reflected in style property // - Modifications to style property are reflected in style content attribute // TODO // - Modifications to style element's textContent are reflected in sheet property. // - Modifications to style element's sheet property are reflected in textContent. // - Modifications to link.href property are reflected in sheet property. // - Less-used features of link: disabled // - Less-used features of style: disabled, scoped, title // - CSSOM-View // - getComputedStyle(): requires default stylesheet, cascading, inheritance, // filtering by @media (screen? print?), layout for widths/heights // - Load events are not in the specs, but apparently some browsers // implement something. Should onload only fire after all @imports have been // loaded, or only the primary sheet? core.StyleSheet = cssom.StyleSheet; core.MediaList = cssom.MediaList; core.CSSStyleSheet = cssom.CSSStyleSheet; core.CSSRule = cssom.CSSRule; core.CSSStyleRule = cssom.CSSStyleRule; core.CSSMediaRule = cssom.CSSMediaRule; core.CSSImportRule = cssom.CSSImportRule; core.CSSStyleDeclaration = cssstyle.CSSStyleDeclaration; // Relavant specs // path_to_url (2000) // path_to_url (2008) // path_to_url (2010) Meant to replace DOM Level 2 Style // path_to_url HTML5, of course // path_to_url not sure what's new here // Objects that aren't in cssom library but should be: // CSSRuleList (cssom just uses array) // CSSFontFaceRule // CSSPageRule // These rules don't really make sense to implement, so CSSOM draft makes them // obsolete. // CSSCharsetRule // CSSUnknownRule // These objects are considered obsolete by CSSOM draft, although modern // browsers implement them. // CSSValue // CSSPrimitiveValue // CSSValueList // RGBColor // Rect // Counter // path_to_url#stylesheetlist function StyleSheetList() {} StyleSheetList.prototype.__proto__ = Array.prototype; StyleSheetList.prototype.item = function item(i) { return this[i]; }; core.StyleSheetList = StyleSheetList; // path_to_url#extensions-to-the-document-interface defineGetter(core.Document.prototype, 'styleSheets', function () { if (!this._styleSheets) { this._styleSheets = new StyleSheetList(); } // TODO: each style and link element should register its sheet on creation // and remove it on removal. return this._styleSheets; }); /** * @this {core.HTMLLinkElement|core.HTMLStyleElement} * @param {string} url * @param {cssom.CSSStyleSheet} sheet * @see path_to_url#requirements-on-user-agents-implementing0 */ function fetchStylesheet(url, sheet) { resourceLoader.load(this, url, function(data) { // TODO: abort if the content-type is not text/css, and the document is // in strict mode url = sheet.href = resourceLoader.resolveResourceUrl(this.ownerDocument, url); evaluateStylesheet.call(this, data, sheet, url); }); } /** * @this {core.HTMLLinkElement|core.HTMLStyleElement} * @param {string} data * @param {cssom.CSSStyleSheet} sheet * @param {string} baseUrl */ function evaluateStylesheet(data, sheet, baseUrl) { // this is the element var newStyleSheet = cssom.parse(data); var spliceArgs = newStyleSheet.cssRules; spliceArgs.unshift(0, sheet.cssRules.length); Array.prototype.splice.apply(sheet.cssRules, spliceArgs); scanForImportRules.call(this, sheet.cssRules, baseUrl); this.ownerDocument.styleSheets.push(sheet); } /** * @this {core.HTMLLinkElement|core.HTMLStyleElement} * @param {cssom.CSSStyleSheet} sheet * @param {string} baseUrl */ function scanForImportRules(cssRules, baseUrl) { if (!cssRules) return; for (var i = 0; i < cssRules.length; ++i) { if (cssRules[i].cssRules) { // @media rule: keep searching inside it. scanForImportRules.call(this, cssRules[i].cssRules, baseUrl); } else if (cssRules[i].href) { // @import rule: fetch the resource and evaluate it. // See path_to_url#css-import-rule // If loading of the style sheet fails its cssRules list is simply // empty. I.e. an @import rule always has an associated style sheet. fetchStylesheet.call(this, resolveHref(baseUrl, cssRules[i].href), this.sheet); } } } assert.equal(undefined, core.HTMLLinkElement._init); core.HTMLLinkElement._init = function() { this.addEventListener('DOMNodeInsertedIntoDocument', function() { if (!/(?:[ \t\n\r\f]|^)stylesheet(?:[ \t\n\r\f]|$)/i.test(this.rel)) { // rel is a space-separated list of tokens, and the original rel types // are case-insensitive. return; } if (this.href) { fetchStylesheet.call(this, this.href, this.sheet); } }); }; assert.equal(undefined, core.HTMLStyleElement._init); core.HTMLStyleElement._init = function() { //console.log('init style') this.addEventListener('DOMNodeInsertedIntoDocument', function() { //console.log('style inserted') //console.log('sheet: ', this.sheet); if (this.type && this.type !== 'text/css') { //console.log('bad type: ' + this.type) return; } let content = ''; for (const child of domSymbolTree.childrenIterator(this)) { if (child.nodeType === NODE_TYPE.TEXT_NODE) { content += child.nodeValue; } } evaluateStylesheet.call(this, content, this.sheet, this._ownerDocument.URL); }); }; // path_to_url#htmllinkelement: // HTMLLinkElement implements LinkStyle // path_to_url#htmlstyleelement: // HTMLStyleElement implements LinkStyle // from path_to_url#the-linkstyle-interface // A future refactoring would be to place _cssStyleSheet on all HTMLLinkElement and HTMLStyleElement instances, in // their constructor, initially set to null. Then, successful loading of the stylesheet object would set it to // non-null. The getter would just always return the current value. This would make it more correctly be null before // loading, and on load failure, and would allow access to _cssStyleSheet instead of the public .sheet API. function getOrCreateSheet() { if (!this._cssStyleSheet) { this._cssStyleSheet = new cssom.CSSStyleSheet(); } return this._cssStyleSheet; } defineGetter(core.HTMLLinkElement.prototype, 'sheet', getOrCreateSheet); defineGetter(core.HTMLStyleElement.prototype, 'sheet', getOrCreateSheet); ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/level2/style.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,646
```javascript var core = require("../level1/core"); var memoizeQuery = require('../utils').memoizeQuery; var validateAndExtract = require('../living/helpers/validate-names').validateAndExtract; var mapper = require("../utils").mapper; const createLiveNodeList = require("../living/node-list").createLive; const NODE_TYPE = require("../living/node-type"); core.Element.prototype.getElementsByTagNameNS = memoizeQuery(function(/* String */ namespaceURI, /* String */ localName) { function filterByTagName(child) { var localMatch = child.localName === localName, nsMatch = child.namespaceURI === namespaceURI; if ((localMatch || localName === "*") && (nsMatch || namespaceURI === "*")) { if (child.nodeType === NODE_TYPE.ELEMENT_NODE) { return true; } } return false; } return createLiveNodeList(this.ownerDocument || this, mapper(this, filterByTagName)); }); core.Document.prototype.getElementsByTagNameNS = function(/* String */ namespaceURI, /* String */ localName) { return core.Element.prototype.getElementsByTagNameNS.call(this, namespaceURI, localName); }; core.Document.prototype.getElementById = function(id) { // return the first element return (this._ids && this._ids[id] && this._ids[id].length > 0 ? this._ids[id][0] : null); }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/level2/core.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
292
```javascript "use strict"; /* ServerJS Javascript DOM Level 1 */ var inheritFrom = require("../utils").inheritFrom; var domToHtml = require("../browser/domtohtml").domToHtml; var defineGetter = require("../utils").defineGetter; var memoizeQuery = require("../utils").memoizeQuery; var validateName = require('../living/helpers/validate-names').name; var HtmlToDom = require("../browser/htmltodom").HtmlToDom; var Location = require("../browser/location"); var vm = require("vm"); var CookieJar = require('tough-cookie').CookieJar; var EventTarget = require("../living/generated/EventTarget"); var attributes = require("../living/attributes"); var mapper = require("../utils").mapper; var clone = require("../living/node").clone; var namedPropertiesWindow = require("../living/named-properties-window"); var Window = require('../browser/Window'); var proxiedWindowEventHandlers = require("../living/helpers/proxied-window-event-handlers"); const URL = require("../utils").URL; const domSymbolTree = require("../living/helpers/internal-constants").domSymbolTree; const NODE_TYPE = require("../living/node-type"); const resetDOMTokenList = require("../living/dom-token-list").reset; const createLiveNodeList = require("../living/node-list").createLive; const updateNodeList = require("../living/node-list").update; const updateHTMLCollection = require("../living/html-collection").update; // utility functions var attachId = function(id,elm,doc) { if (id && elm && doc) { if (!doc._ids[id]) { doc._ids[id] = []; } doc._ids[id].push(elm); } }; var detachId = function(id,elm,doc) { var elms, i; if (id && elm && doc) { if (doc._ids && doc._ids[id]) { elms = doc._ids[id]; for (i=0;i<elms.length;i++) { if (elms[i] === elm) { elms.splice(i,1); i--; } } if (elms.length === 0) { delete doc._ids[id]; } } } }; function setInnerHTML(document, node, html) { // Clear the children first: if (node._templateContents) { clearChildNodes(node._templateContents); } else { clearChildNodes(node); } if (html !== "") { if (node.nodeName === "#document") { document._htmlToDom.appendHtmlToDocument(html, node); } else { document._htmlToDom.appendHtmlToElement(html, node); } } } function clearChildNodes(node) { for (let child = null; child = domSymbolTree.firstChild(node);) { node.removeChild(child); } } var core = exports; core.DOMException = require("../web-idl/DOMException"); core.NamedNodeMap = require("../living/attributes").NamedNodeMap; core.DOMImplementation = function DOMImplementation(document, /* Object */ features) { throw new TypeError("Illegal constructor"); }; core.DOMImplementation.prototype = { // All of these are legacy, left because jsdom uses them internally :(. jsdom confused the idea of browser features // and jsdom features _removeFeature : function(feature, version) { feature = feature.toLowerCase(); if (this._features[feature]) { if (version) { var j = 0, versions = this._features[feature], l = versions.length; for (j; j<l; j++) { if (versions[j] === version) { versions.splice(j,1); return; } } } else { delete this._features[feature]; } } }, _addFeature: function(feature, version) { feature = feature.toLowerCase(); if (version) { if (!this._features[feature]) { this._features[feature] = []; } if (version instanceof Array) { Array.prototype.push.apply(this._features[feature], version); } else { this._features[feature].push(version); } if (feature === "processexternalresources" && (version === "script" || (version.indexOf && version.indexOf("script") !== -1)) && !vm.isContext(this._ownerDocument._global)) { vm.createContext(this._ownerDocument._global); this._ownerDocument._defaultView._globalProxy = vm.runInContext("this", this._ownerDocument._global); this._ownerDocument._defaultView = this._ownerDocument._defaultView._globalProxy; } } }, // The real hasFeature is in living/dom-implementation.js, and returns true always. // This one is used internally _hasFeature: function(/* string */ feature, /* string */ version) { feature = (feature) ? feature.toLowerCase() : ''; var versions = (this._features[feature]) ? this._features[feature] : false; if (!version && versions.length && versions.length > 0) { return true; } else if (typeof versions === 'string') { return versions === version; } else if (versions.indexOf && versions.length > 0) { for (var i = 0; i < versions.length; i++) { var found = versions[i] instanceof RegExp ? versions[i].test(version) : versions[i] === version; if (found) { return true; } } return false; } else { return false; } } }; core.Node = function Node(ownerDocument) { EventTarget.setup(this); domSymbolTree.initialize(this); this._childNodesList = null; this._ownerDocument = ownerDocument; this._childrenList = null; this._version = 0; this._memoizedQueries = {}; this._readonly = false; }; core.Node.ELEMENT_NODE = NODE_TYPE.ELEMENT_NODE; core.Node.ATTRIBUTE_NODE = NODE_TYPE.ATTRIBUTE_NODE; core.Node.TEXT_NODE = NODE_TYPE.TEXT_NODE; core.Node.CDATA_SECTION_NODE = NODE_TYPE.CDATA_SECTION_NODE; core.Node.ENTITY_REFERENCE_NODE = NODE_TYPE.ENTITY_REFERENCE_NODE; core.Node.ENTITY_NODE = NODE_TYPE.ENTITY_NODE; core.Node.PROCESSING_INSTRUCTION_NODE = NODE_TYPE.PROCESSING_INSTRUCTION_NODE; core.Node.COMMENT_NODE = NODE_TYPE.COMMENT_NODE; core.Node.DOCUMENT_NODE = NODE_TYPE.DOCUMENT_NODE; core.Node.DOCUMENT_TYPE_NODE = NODE_TYPE.DOCUMENT_TYPE_NODE; core.Node.DOCUMENT_FRAGMENT_NODE = NODE_TYPE.DOCUMENT_FRAGMENT_NODE; core.Node.NOTATION_NODE = NODE_TYPE.NOTATION_NODE; core.Node.prototype = { ELEMENT_NODE : NODE_TYPE.ELEMENT_NODE, ATTRIBUTE_NODE : NODE_TYPE.ATTRIBUTE_NODE, TEXT_NODE : NODE_TYPE.TEXT_NODE, CDATA_SECTION_NODE : NODE_TYPE.CDATA_SECTION_NODE, ENTITY_REFERENCE_NODE : NODE_TYPE.ENTITY_REFERENCE_NODE, ENTITY_NODE : NODE_TYPE.ENTITY_NODE, PROCESSING_INSTRUCTION_NODE : NODE_TYPE.PROCESSING_INSTRUCTION_NODE, COMMENT_NODE : NODE_TYPE.COMMENT_NODE, DOCUMENT_NODE : NODE_TYPE.DOCUMENT_NODE, DOCUMENT_TYPE_NODE : NODE_TYPE.DOCUMENT_TYPE_NODE, DOCUMENT_FRAGMENT_NODE : NODE_TYPE.DOCUMENT_FRAGMENT_NODE, NOTATION_NODE : NODE_TYPE.NOTATION_NODE, get nodeValue() { if (this.nodeType === NODE_TYPE.TEXT_NODE || this.nodeType === NODE_TYPE.COMMENT_NODE || this.nodeType === NODE_TYPE.PROCESSING_INSTRUCTION_NODE) { return this._data; } return null; }, set nodeValue(value) { if (this.nodeType === NODE_TYPE.TEXT_NODE || this.nodeType === NODE_TYPE.COMMENT_NODE || this.nodeType === NODE_TYPE.PROCESSING_INSTRUCTION_NODE) { this.replaceData(0, this.length, value); } }, get parentNode() { return domSymbolTree.parent(this); }, get nodeName() { switch (this.nodeType) { case NODE_TYPE.ELEMENT_NODE: return this.tagName; case NODE_TYPE.TEXT_NODE: return "#text"; case NODE_TYPE.PROCESSING_INSTRUCTION_NODE: return this.target; case NODE_TYPE.COMMENT_NODE: return "#comment"; case NODE_TYPE.DOCUMENT_NODE: return "#document"; case NODE_TYPE.DOCUMENT_TYPE_NODE: return this.name; case NODE_TYPE.DOCUMENT_FRAGMENT_NODE: return "#document-fragment"; } }, set nodeName(unused) { throw new core.DOMException();}, get firstChild() { return domSymbolTree.firstChild(this); }, get ownerDocument() { // TODO: when we move nodeType to Node.prototype and add an internal _nodeType, consult that instead. return this.nodeType === NODE_TYPE.DOCUMENT_NODE ? null : this._ownerDocument; }, get readonly() { return this._readonly;}, get lastChild() { return domSymbolTree.lastChild(this); }, get childNodes() { if (!this._childNodesList) { var self = this; this._childNodesList = createLiveNodeList(this, function() { return domSymbolTree.childrenToArray(self); }); } else { updateNodeList(this._childNodesList); } return this._childNodesList; }, set childNodes(unused) { throw new core.DOMException();}, get nextSibling() { return domSymbolTree.nextSibling(this); }, set nextSibling(unused) { throw new core.DOMException();}, get previousSibling() { return domSymbolTree.previousSibling(this); }, set previousSibling(unused) { throw new core.DOMException();}, /* returns Node */ insertBefore : function(/* Node */ newChild, /* Node*/ refChild) { if (arguments.length < 2) { throw new TypeError("Not enough arguments to Node.prototype.insertBefore"); } if (refChild === undefined) { refChild = null; } // TODO branding if (!newChild || !("nodeType" in newChild)) { throw new TypeError("First argument to Node.prototype.insertBefore must be a Node"); } if (refChild !== null && !("nodeType" in refChild)) { throw new TypeError("Second argument to Node.prototype.insertBefore must be a Node or null or undefined"); } if (this._readonly === true) { throw new core.DOMException(core.DOMException.NO_MODIFICATION_ALLOWED_ERR, 'Attempting to modify a read-only node'); } // DocumentType must be implicitly adopted if (newChild.nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE) newChild._ownerDocument = this._ownerDocument; // TODO - if (!newChild) then? if (!(this instanceof core.Document) && newChild._ownerDocument !== this._ownerDocument) { throw new core.DOMException(core.DOMException.WRONG_DOCUMENT_ERR); } if (newChild.nodeType && newChild.nodeType === NODE_TYPE.ATTRIBUTE_NODE) { throw new core.DOMException(core.DOMException.HIERARCHY_REQUEST_ERR); } // search for parents matching the newChild for (const ancestor of domSymbolTree.ancestorsIterator(this)) { if (ancestor === newChild) { throw new core.DOMException(core.DOMException.HIERARCHY_REQUEST_ERR); } } // fragments are merged into the element (except parser-created fragments in <template>) if (newChild.nodeType === NODE_TYPE.DOCUMENT_FRAGMENT_NODE) { let grandChild; while ((grandChild = domSymbolTree.firstChild(newChild))) { newChild.removeChild(grandChild); this.insertBefore(grandChild, refChild); } } else if (newChild === refChild) { return newChild; } else { const oldParent = domSymbolTree.parent(newChild); // if the newChild is already in the tree elsewhere, remove it first if (oldParent) { oldParent.removeChild(newChild); } if (refChild == null) { domSymbolTree.appendChild(this, newChild); } else { if (domSymbolTree.parent(refChild) !== this) { throw new core.DOMException(core.DOMException.NOT_FOUND_ERR); } domSymbolTree.insertBefore(refChild, newChild); } this._modified(); if (this._attached && newChild._attach) { newChild._attach(); } this._descendantAdded(this, newChild); } return newChild; }, // raises(DOMException); _modified: function() { this._version++; if (this._ownerDocument) { this._ownerDocument._version++; } if (this._childrenList) { updateHTMLCollection(this._childrenList); } if (this._childNodesList) { updateNodeList(this._childNodesList); } this._clearMemoizedQueries(); }, _clearMemoizedQueries: function() { this._memoizedQueries = {}; const myParent = domSymbolTree.parent(this); if (myParent) { myParent._clearMemoizedQueries(); } }, _descendantRemoved: function(parent, child) { const myParent = domSymbolTree.parent(this); if (myParent) { myParent._descendantRemoved(parent, child); } }, _descendantAdded: function(parent, child) { const myParent = domSymbolTree.parent(this); if (myParent) { myParent._descendantAdded(parent, child); } }, _attrModified: function(name, value, oldValue) { this._modified(); namedPropertiesWindow.elementAttributeModified(this, name, value, oldValue); if (name == 'id' && this._attached) { var doc = this._ownerDocument; detachId(oldValue,this,doc); attachId(value,this,doc); } // TODO event handlers: // The correct way to do this is lazy, and a bit more complicated; see // path_to_url#event-handler-content-attributes // It would only be possible if we had proper getters/setters for every event handler, which we don't right now. if (name.length > 2 && name[0] === 'o' && name[1] === 'n') { if (value) { var w = this._ownerDocument._global; var self = proxiedWindowEventHandlers.has(name) && this._localName === 'body' ? w : this; var vmOptions = { filename: this._ownerDocument._URL, displayErrors: false }; // The handler code probably refers to functions declared globally on the window, so we need to run it in // that context. In fact, it's worse; see // path_to_url#chromium/src/third_party/WebKit/Source/bindings/core/v8/V8LazyEventListener.cpp // plus the spec, which show how multiple nested scopes are technically required. We won't implement that // until someone asks for it, though. // path_to_url#the-event-handler-processing-algorithm if (name === "onerror" && self === w) { // path_to_url#getting-the-current-value-of-the-event-handler // step 10 self[name] = function (event, source, lineno, colno, error) { w.__tempEventHandlerThis = this; w.__tempEventHandlerEvent = event; w.__tempEventHandlerSource = source; w.__tempEventHandlerLineno = lineno; w.__tempEventHandlerColno = colno; w.__tempEventHandlerError = error; try { return vm.runInContext(` (function (event, source, lineno, colno, error) { ${value} }).call(__tempEventHandlerThis, __tempEventHandlerEvent, __tempEventHandlerSource, __tempEventHandlerLineno, __tempEventHandlerColno, __tempEventHandlerError)`, w, vmOptions); } finally { delete w.__tempEventHandlerThis; delete w.__tempEventHandlerEvent; delete w.__tempEventHandlerSource; delete w.__tempEventHandlerLineno; delete w.__tempEventHandlerColno; delete w.__tempEventHandlerError; } }; } else { self[name] = function (event) { w.__tempEventHandlerThis = this; w.__tempEventHandlerEvent = event; try { return vm.runInContext(` (function (event) { ${value} }).call(__tempEventHandlerThis, __tempEventHandlerEvent)`, w, vmOptions); } finally { delete w.__tempEventHandlerThis; delete w.__tempEventHandlerEvent; } }; } } else { this[name] = null; } } // TODO remove MutationEvents completely at some point if (value !== oldValue && this._ownerDocument && this._ownerDocument.implementation._hasFeature('MutationEvents')) { var ev = this._ownerDocument.createEvent("MutationEvents"); var attrChange = core.MutationEvent.MODIFICATION; if (value === null) { attrChange = core.MutationEvent.REMOVAL; } if (oldValue === null) { attrChange = core.MutationEvent.ADDITION; } ev.initMutationEvent("DOMAttrModified", true, false, this, oldValue, value, name, attrChange); this.dispatchEvent(ev); } // update classList if (name === "class" && value !== this.classList.toString()) { resetDOMTokenList(this.classList, value); } }, replaceChild(node, child) { if (arguments.length < 2) { throw new TypeError("Not enough arguments to Node.prototype.replaceChild"); } // TODO branding if (!node || !("nodeType" in node)) { throw new TypeError("First argument to Node.prototype.replaceChild must be a Node"); } if (!child || !("nodeType" in child)) { throw new TypeError("Second argument to Node.prototype.replaceChild must be a Node"); } this.insertBefore(node, child); return this.removeChild(child); }, /* returns void */ _attach : function() { this._attached = true; namedPropertiesWindow.nodeAttachedToDocument(this); if (this.id) { attachId(this.id,this,this._ownerDocument); } for (const child of domSymbolTree.childrenIterator(this)) { if (child._attach) { child._attach(); } } }, /* returns void */ _detach : function() { this._attached = false; namedPropertiesWindow.nodeDetachedFromDocument(this); if (this.id) { detachId(this.id,this,this._ownerDocument); } for (const child of domSymbolTree.childrenIterator(this)) { if (child._detach) { child._detach(); } } }, /* returns Node */ removeChild : function(/* Node */ oldChild){ if (this._readonly === true) { throw new core.DOMException(core.DOMException.NO_MODIFICATION_ALLOWED_ERR); } if (!oldChild || domSymbolTree.parent(oldChild) !== this) { throw new core.DOMException(core.DOMException.NOT_FOUND_ERR); } var oldPreviousSibling = oldChild.previousSibling; domSymbolTree.remove(oldChild); this._modified(); oldChild._detach(); this._descendantRemoved(this, oldChild); if (this._ownerDocument) { this._ownerDocument._runRemovingSteps(oldChild, this, oldPreviousSibling); } return oldChild; }, // raises(DOMException); /* returns Node */ appendChild : function(/* Node */ newChild) { if (arguments.length < 1) { throw new TypeError("Not enough arguments to Node.prototype.appendChild"); } // TODO branding if (!("nodeType" in newChild)) { throw new TypeError("First argument to Node.prototype.appendChild must be a Node"); } return this.insertBefore(newChild, null); }, // raises(DOMException); /* returns boolean */ hasChildNodes : function() { return domSymbolTree.hasChildren(this); }, /* returns void */ normalize: function() { for (const child of domSymbolTree.childrenIterator(this)) { if (child.normalize) { child.normalize(); } // Level2/core clean off empty nodes if (child.nodeValue === "") { this.removeChild(child); continue; } const prevChild = domSymbolTree.previousSibling(child); if (prevChild && prevChild.nodeType === NODE_TYPE.TEXT_NODE && child.nodeType === NODE_TYPE.TEXT_NODE) { // merge text nodes prevChild.appendData(child.nodeValue); this.removeChild(child); } } }, toString: function() { var id = ''; if (this.id) { id = '#' + this.id; } if (this.className) { var classes = this.className.split(/\s+/); for (var i = 0, len = classes.length; i < len; i++) { id += '.' + classes[i]; } } return '[ ' + this.tagName + id + ' ]'; } }; core.Element = function Element(document, localName) { core.Node.call(this, document); this._namespaceURI = null; this._prefix = null; this._localName = localName; this._attributes = attributes.createNamedNodeMap(this); }; inheritFrom(core.Node, core.Element, { get namespaceURI() { return this._namespaceURI; }, get prefix() { return this._prefix; }, get localName() { return this._localName; }, get tagName() { var qualifiedName = this._prefix !== null ? this._prefix + ":" + this._localName : this._localName; if (this.namespaceURI === "path_to_url" && this._ownerDocument._parsingMode === "html") { qualifiedName = qualifiedName.toUpperCase(); } return qualifiedName; }, get id() { var idAttr = this.getAttribute("id"); if (idAttr === null) { return ""; } return idAttr; }, nodeType : NODE_TYPE.ELEMENT_NODE, get attributes() { return this._attributes; }, get sourceIndex() { /* * According to QuirksMode: * Get the sourceIndex of element x. This is also the index number for * the element in the document.getElementsByTagName('*') array. * path_to_url#t77 */ var items = this.ownerDocument.getElementsByTagName('*'), len = items.length; for (var i = 0; i < len; i++) { if (items[i] === this) { return i; } } }, get outerHTML() { return domToHtml([this]); }, set outerHTML(html) { if (html === null) { html = ""; } var parent = domSymbolTree.parent(this); var document = this._ownerDocument; if (!parent) { return; } var contextElement; if (parent.nodeType === NODE_TYPE.DOCUMENT_NODE) { throw new core.DOMException(core.DOMException.NO_MODIFICATION_ALLOWED_ERR, "Modifications are not allowed for this document"); } else if (parent.nodeType === NODE_TYPE.DOCUMENT_FRAGMENT_NODE) { contextElement = document.createElementNS("path_to_url", "body"); } else if (parent.nodeType === NODE_TYPE.ELEMENT_NODE) { contextElement = clone(core, parent, undefined, false); } else { throw new TypeError("This should never happen"); } document._htmlToDom.appendHtmlToElement(html, contextElement); while (contextElement.firstChild) { parent.insertBefore(contextElement.firstChild, this); } parent.removeChild(this); }, get innerHTML() { var tagName = this.tagName; if (tagName === 'SCRIPT' || tagName === 'STYLE') { var type = this.getAttribute('type'); if (!type || /^text\//i.test(type) || /\/javascript$/i.test(type)) { return domToHtml(domSymbolTree.childrenIterator(this)); } } // In case of <template> we should pass its "template contents" fragment as a serialization root if we have one if (this._templateContents) { return domToHtml(domSymbolTree.childrenIterator(this._templateContents)); } return domToHtml(domSymbolTree.childrenIterator(this)); }, set innerHTML(html) { if (html === null) { html = ""; } setInnerHTML(this.ownerDocument, this, html); }, scrollTop: 0, scrollLeft: 0, /* returns NodeList */ getElementsByTagName: memoizeQuery(function(/* string */ name) { name = name.toLowerCase(); function filterByTagName(child) { if (child.nodeName && child.nodeType === NODE_TYPE.ELEMENT_NODE) { return name === "*" || (child.nodeName.toLowerCase() === name); } return false; } return createLiveNodeList(this._ownerDocument || this, mapper(this, filterByTagName, true)); }), }); core.DocumentFragment = function DocumentFragment(document) { core.Node.call(this, document); }; inheritFrom(core.Node, core.DocumentFragment, { nodeType : NODE_TYPE.DOCUMENT_FRAGMENT_NODE }); core.Document = function Document(options) { if (!options || !options.parsingMode || (options.parsingMode !== "html" && options.parsingMode !== "xml")) { throw new Error("options must exist and contain a parsingMode of html or xml"); } core.Node.call(this, this); this._parsingMode = options.parsingMode; this._htmlToDom = new HtmlToDom(core, options.parser, options.parsingMode); this._implementation = Object.create(core.DOMImplementation.prototype); this._implementation._ownerDocument = this; this._implementation._features = {}; this._defaultView = options.defaultView || null; this._global = options.global; this._documentElement = null; this._ids = Object.create(null); this._attached = true; this._readonly = false; this._currentScript = null; this._cookieJar = options.cookieJar === undefined ? new CookieJar(null, { looseMode: true }) : options.cookieJar; this._contentType = options.contentType; if (this._contentType === undefined) { this._contentType = this._parsingMode === "xml" ? "application/xml" : "text/html"; } this._URL = options.url === undefined ? "about:blank" : new URL(options.url).href; this._location = new Location(this._URL, this); if (options.cookie) { var cookies = Array.isArray(options.cookie) ? options.cookie: [options.cookie]; var document = this; cookies.forEach(function(cookieStr) { document._cookieJar.setCookieSync(cookieStr, document._URL, { ignoreError : true }); }); } this._activeNodeIterators = []; this._activeNodeIteratorsMax = options.concurrentNodeIterators === undefined ? 10 : Number(options.concurrentNodeIterators); if (isNaN(this._activeNodeIteratorsMax)) { throw new TypeError("The 'concurrentNodeIterators' option must be a Number"); } if (this._activeNodeIteratorsMax < 0) { throw new RangeError("The 'concurrentNodeIterators' option must be a non negative Number"); } }; core.Document._removingSteps = []; var tagRegEx = /[^\w:\d_\.-]+/i; var entRegEx = /[^\w\d_\-&;]+/; var invalidAttrRegEx = /[\s"'>/=\u0000-\u001A]/; inheritFrom(core.Node, core.Document, { nodeType : NODE_TYPE.DOCUMENT_NODE, _elementBuilders : { }, _defaultElementBuilder: function(document, tagName) { return new core.Element(document, tagName); }, get contentType() { return this._contentType;}, get compatMode() { return (this._parsingMode === "xml" || this.doctype) ? "CSS1Compat" : "BackCompat"; }, get charset() { return "UTF-8"; }, get characterSet() { return "UTF-8"; }, get inputEncoding() { return "UTF-8"; }, get doctype() { for (const childNode of domSymbolTree.childrenIterator(this)) { if (childNode.nodeType === NODE_TYPE.DOCUMENT_TYPE_NODE) { return childNode; } } return null; }, get URL() { return this._URL; }, get documentURI() { return this._URL; }, get location() { return this._defaultView ? this._location : null; }, get documentElement() { if (this._documentElement) { return this._documentElement; } for (const childNode of domSymbolTree.childrenIterator(this)) { if (childNode.nodeType === NODE_TYPE.ELEMENT_NODE) { this._documentElement = childNode; return childNode; } } return null; }, get implementation() { return this._implementation;}, set implementation(implementation) { this._implementation = implementation;}, get readonly() { return this._readonly;}, get defaultView() { return this._defaultView; }, get currentScript() { return this._currentScript; }, toString: function () { return '[object HTMLDocument]'; }, _createElementWithCorrectElementInterface: function (name, namespace) { // path_to_url#concept-element-interface // TODO: eventually we should re-write the element-builder system to be namespace aware, but for now it is not. return (this._elementBuilders[name.toLowerCase()] || this._defaultElementBuilder)(this, name, namespace); }, appendChild : function(/* Node */ arg) { if (this.documentElement && arg.nodeType == NODE_TYPE.ELEMENT_NODE) { throw new core.DOMException(core.DOMException.HIERARCHY_REQUEST_ERR); } return core.Node.prototype.appendChild.call(this, arg); }, removeChild : function(/* Node */ arg) { var ret = core.Node.prototype.removeChild.call(this, arg); if (arg == this._documentElement) { this._documentElement = null;// force a recalculation } return ret; }, _descendantRemoved: function(parent, child) { if (child.tagName === 'STYLE') { var index = this.styleSheets.indexOf(child.sheet); if (index > -1) { this.styleSheets.splice(index, 1); } } }, /* returns NodeList */ getElementsByTagName: memoizeQuery(function(/* string */ name) { function filterByTagName(child) { if (child.nodeName && child.nodeType === NODE_TYPE.ELEMENT_NODE) { if (name === "*") { return true; // case insensitivity for html } else if (child._ownerDocument && child._ownerDocument._doctype && //child._ownerDocument._doctype.name === "html" && child.nodeName.toLowerCase() === name.toLowerCase()) { return true; } else if (child.nodeName.toLowerCase() === name.toLowerCase()) { return true; } } return false; } return createLiveNodeList(this.documentElement || this, mapper(this, filterByTagName, true)); }), write: function () { var text = ""; for (var i = 0; i < arguments.length; ++i) { text += String(arguments[i]); } if (this._parsingMode === "xml") { throw new core.DOMException(core.DOMException.INVALID_STATE_ERR, "Cannot use document.write on XML documents"); } if (this._writeAfterElement) { // If called from an script element directly (during the first tick), // the new elements are inserted right after that element. var tempDiv = this.createElement('div'); setInnerHTML(this, tempDiv, text); var child = tempDiv.firstChild; var previous = this._writeAfterElement; var parent = this._writeAfterElement.parentNode; while (child) { var node = child; child = child.nextSibling; parent.insertBefore(node, previous.nextSibling); previous = node; } } else if (this.readyState === "loading") { // During page loading, document.write appends to the current element // Find the last child that has been added to the document. var node = this; while (node.lastChild && node.lastChild.nodeType === NODE_TYPE.ELEMENT_NODE) { node = node.lastChild; } setInnerHTML(this, node, text); } else if (text) { setInnerHTML(this, this, text); } }, writeln: function () { const args = []; for (let i = 0; i < arguments.length; ++i) { args.push(arguments[i]); } args.push("\n"); this.write.apply(this, args); }, _runRemovingSteps: function(oldNode, oldParent, oldPreviousSibling) { var listeners = core.Document._removingSteps; for (var i = 0; i < listeners.length; ++i) { listeners[i](this, oldNode, oldParent, oldPreviousSibling); } } }); ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/level1/core.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
7,232
```javascript "use strict"; const vm = require("vm"); const reportException = require("../../living/helpers/runtime-script-errors"); exports.javascript = function (element, code, filename) { const document = element.ownerDocument; const window = document && document._global; if (window) { window.document._currentScript = element; try { vm.runInContext(code, window, { filename, displayErrors: false }); } catch (e) { reportException(window, e, filename); } finally { window.document._currentScript = null; } } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/level2/languages/javascript.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
123
```javascript "use strict"; const resolveHref = require("../utils").resolveHref; const parseDataUrl = require("../utils").parseDataUrl; const fs = require("fs"); const request = require("request"); const documentBaseURL = require("../living/helpers/document-base-url").documentBaseURL; const internalConstants = require("../living/helpers/internal-constants"); const NODE_TYPE = require("../living/node-type"); /* eslint-disable no-restricted-modules */ // TODO: stop using the built-in URL in favor of the spec-compliant whatwg-url package // This legacy usage is in the process of being purged. const URL = require("url"); /* eslint-enable no-restricted-modules */ const IS_BROWSER = Object.prototype.toString.call(process) !== "[object process]"; function createResourceLoadHandler(element, resourceUrl, document, loadCallback) { return function (err, data) { const ev = document.createEvent("HTMLEvents"); if (!err) { try { loadCallback.call(element, data, resourceUrl); ev.initEvent("load", false, false); } catch (e) { err = e; } } if (err) { ev.initEvent("error", false, false); ev.error = err; const error = new Error(`Could not load ${element.localName}: "${resourceUrl}"`); error.detail = err; document._defaultView._virtualConsole.emit("jsdomError", error); } element.dispatchEvent(ev); }; } exports.readFile = function (filePath, callback) { const readableStream = fs.createReadStream(filePath, { encoding: "utf8" }); let data = ""; readableStream.on("error", callback); readableStream.on("data", chunk => { data += chunk; }); readableStream.on("end", () => { callback(null, data); }); return { abort() { readableStream.destroy(); callback(new Error("request canceled by user")); } }; }; // NOTE: request wraps tough-cookie cookie jar // (see: path_to_url // Therefore, to pass our cookie jar to the request, we need to create // request's wrapper and monkey patch it with our jar. function wrapCookieJarForRequest(cookieJar) { const jarWrapper = request.jar(); jarWrapper._jar = cookieJar; return jarWrapper; } function fetch(element, urlObj, cookieJar, referrer, pool, agentOptions, userAgent, callback) { let req = null; if (urlObj.protocol === "data:") { process.nextTick(() => { try { const buffer = parseDataUrl(urlObj.href).buffer; callback(null, buffer.toString()); } catch (err) { callback(err, null); } }); } else if (urlObj.hostname) { const requestOptions = { pool, agentOptions, headers: { "User-Agent": userAgent } }; if (element[internalConstants.accept]) { requestOptions.headers.Accept = element[internalConstants.accept]; } req = exports.download(urlObj, requestOptions, cookieJar, referrer, callback); } else { const filePath = urlObj.pathname .replace(/^file:\/\//, "") .replace(/^\/([a-z]):\//i, "$1:/") .replace(/%20/g, " "); req = exports.readFile(filePath, callback); } return req; } exports.enqueue = function (element, resourceUrl, callback) { const document = element.nodeType === NODE_TYPE.DOCUMENT_NODE ? element : element._ownerDocument; if (document._queue) { const loadHandler = createResourceLoadHandler(element, resourceUrl || document.URL, document, callback); return document._queue.push(loadHandler); } return function () { }; }; exports.resolveResourceUrl = function (document, url) { // if getAttribute returns null, there is no href // lets resolve to an empty string (nulls are not expected farther up) if (url === null) { return ""; } const baseUrl = documentBaseURL(document); return resolveHref(baseUrl, url); }; function objGetter(obj, prop) { const lprop = prop.toLowerCase(); for (const p in obj) { if (obj.hasOwnProperty(p) && lprop === p.toLowerCase()) { return obj[p]; } } return null; } exports.download = function (url, options, cookieJar, referrer, callback) { options = options || {}; options.gzip = true; options.jar = wrapCookieJarForRequest(cookieJar); options.headers = options.headers || {}; if (referrer && !IS_BROWSER) { options.headers.referer = referrer; } if (!objGetter(options.headers, "Accept")) { options.headers.Accept = "*/*"; } if (!objGetter(options.headers, "Accept-Language")) { options.headers["Accept-Language"] = "en"; } const req = request(url, options, (error, response, data) => callback(error, data, response)); return { abort() { req.abort(); callback(new Error("request canceled by user")); } }; }; exports.load = function (element, url, callback) { const document = element._ownerDocument; const documentImpl = document.implementation; if (!documentImpl._hasFeature("FetchExternalResources", element.tagName.toLowerCase())) { return; } // if getAttribute returns null, there is no href // lets resolve to an empty string (nulls are not expected farther up) const resourceUrl = exports.resolveResourceUrl(document, url); if (documentImpl._hasFeature("SkipExternalResources", resourceUrl)) { return; } const urlObj = URL.parse(resourceUrl); const baseUrl = documentBaseURL(document); const cookieJar = document._cookieJar; const enqueued = exports.enqueue(element, resourceUrl, callback); const customLoader = document._customResourceLoader; const requestManager = document[internalConstants.requestManager]; const pool = document[internalConstants.pool]; const agentOptions = document[internalConstants.agentOptions]; const userAgent = document._defaultView.navigator.userAgent; let req = null; function wrappedEnqueued() { if (req && requestManager) { requestManager.remove(req); } // do not trigger if the window is closed if (element._ownerDocument && element._ownerDocument.defaultView.document) { enqueued.apply(this, arguments); } } if (typeof customLoader === "function") { req = customLoader({ element, url: urlObj, cookie: cookieJar.getCookieStringSync(urlObj, { http: true }), baseUrl, defaultFetch(fetchCallback) { return fetch(element, urlObj, cookieJar, baseUrl, pool, agentOptions, userAgent, fetchCallback); } }, wrappedEnqueued); } else { req = fetch(element, urlObj, cookieJar, baseUrl, pool, agentOptions, userAgent, wrappedEnqueued); } if (req && requestManager) { requestManager.add(req); } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/browser/resource-loader.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,527
```javascript "use strict"; // Tree traversing exports.getFirstChild = function (node) { return node.childNodes[0]; }; exports.getChildNodes = function (node) { // parse5 treats template elements specially, assuming you return an array whose single item is the document fragment return node._templateContents ? [node._templateContents] : node.childNodes; }; exports.getParentNode = function (node) { return node.parentNode; }; exports.getAttrList = function (node) { return node.attributes; }; // Node data exports.getTagName = function (element) { return element.tagName.toLowerCase(); }; exports.getNamespaceURI = function (element) { return element.namespaceURI || "path_to_url"; }; exports.getTextNodeContent = function (textNode) { return textNode.nodeValue; }; exports.getCommentNodeContent = function (commentNode) { return commentNode.nodeValue; }; exports.getDocumentTypeNodeName = function (doctypeNode) { return doctypeNode.name; }; exports.getDocumentTypeNodePublicId = function (doctypeNode) { return doctypeNode.publicId || null; }; exports.getDocumentTypeNodeSystemId = function (doctypeNode) { return doctypeNode.systemId || null; }; // Node types exports.isTextNode = function (node) { return node.nodeName === "#text"; }; exports.isCommentNode = function (node) { return node.nodeName === "#comment"; }; exports.isDocumentTypeNode = function (node) { return node.nodeType === 10; }; exports.isElementNode = function (node) { return Boolean(node.tagName); }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/browser/documentAdapter.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
333
```javascript "use strict"; const whatwgURL = require("whatwg-url-compat"); const documentBaseURL = require("../living/helpers/document-base-url").documentBaseURL; const notImplemented = require("./not-implemented"); const URL = whatwgURL.createURLConstructor(); module.exports = Location; const document = Symbol("relevant document"); const oldParsedURL = Symbol("old parsed URL"); function Location(urlString, relevantDocument) { this[document] = relevantDocument; whatwgURL.setTheInput(this, urlString); try { this[oldParsedURL] = new URL(urlString); } catch (e) { this[oldParsedURL] = {}; } } whatwgURL.mixinURLUtils( Location.prototype, function getTheBase() { return documentBaseURL(this[document]); }, function updateSteps() { if (this[oldParsedURL].protocol !== this.protocol || this[oldParsedURL].username !== this.username || this[oldParsedURL].password !== this.password || this[oldParsedURL].hostname !== this.hostname || this[oldParsedURL].port !== this.port || this[oldParsedURL].pathname !== this.pathname || this[oldParsedURL].search !== this.search) { notImplemented("navigation via the location interface", this[document]._defaultView); } else if (this[oldParsedURL].hash !== this.hash) { const window = this[document].defaultView; const ev = new window.HashChangeEvent("hashchange", { bubbles: true, cancelable: false, oldURL: this[oldParsedURL].href, newURL: this.href }); window.setTimeout(() => { window.dispatchEvent(ev); }, 0); } this[oldParsedURL] = new URL(this.href); this[document]._URL = this.href; } ); Location.prototype.assign = function () { notImplemented("location.assign", this[document]._defaultView); }; Location.prototype.replace = function (url) { // This is nowhere near spec compliant, but has worked so far. whatwgURL.setTheInput(this, url); }; Location.prototype.reload = function () { notImplemented("location.reload", this[document]._defaultView); }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/browser/location.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
478
```javascript "use strict"; const CSSStyleDeclaration = require("cssstyle").CSSStyleDeclaration; const notImplemented = require("./not-implemented"); const History = require("./history"); const VirtualConsole = require("../virtual-console"); const define = require("../utils").define; const inherits = require("../utils").inheritFrom; const EventTarget = require("../living/generated/EventTarget"); const namedPropertiesWindow = require("../living/named-properties-window"); const cssom = require("cssom"); const postMessage = require("../living/post-message"); const DOMException = require("../web-idl/DOMException"); const btoa = require("abab").btoa; const atob = require("abab").atob; const idlUtils = require("../living/generated/utils"); const internalConstants = require("../living/helpers/internal-constants"); const createFileReader = require("../living/file-reader"); const createXMLHttpRequest = require("../living/xmlhttprequest"); // NB: the require() must be after assigning `module.export` because this require() is circular module.exports = Window; const dom = require("../living"); const cssSelectorSplitRE = /((?:[^,"']|"[^"]*"|'[^']*')+)/; const defaultStyleSheet = cssom.parse(require("./default-stylesheet")); dom.Window = Window; // NOTE: per path_to_url#Global, all properties on the Window object must be own-properties. // That is why we assign everything inside of the constructor, instead of using a shared prototype. // You can verify this in e.g. Firefox or Internet Explorer, which do a good job with Web IDL compliance. function Window(options) { EventTarget.setup(this); const window = this; ///// INTERFACES FROM THE DOM // TODO: consider a mode of some sort where these are not shared between all DOM instances // It'd be very memory-expensive in most cases, though. define(window, dom); ///// PRIVATE DATA PROPERTIES // vm initialization is defered until script processing is activated (in level1/core) this._globalProxy = this; this.__timers = []; // List options explicitly to be clear which are passed through this._document = new dom.HTMLDocument({ parsingMode: options.parsingMode, contentType: options.contentType, cookieJar: options.cookieJar, parser: options.parser, url: options.url, referrer: options.referrer, cookie: options.cookie, deferClose: options.deferClose, resourceLoader: options.resourceLoader, concurrentNodeIterators: options.concurrentNodeIterators, pool: options.pool, agentOptions: options.agentOptions, userAgent: options.userAgent, defaultView: this._globalProxy, global: this }); // Set up the window as if it's a top level window. // If it's not, then references will be corrected by frame/iframe code. this._parent = this._top = this._globalProxy; // This implements window.frames.length, since window.frames returns a // self reference to the window object. This value is incremented in the // HTMLFrameElement init function (see: level2/html.js). this._length = 0; if (options.virtualConsole) { if (options.virtualConsole instanceof VirtualConsole) { this._virtualConsole = options.virtualConsole; } else { throw new TypeError( "options.virtualConsole must be a VirtualConsole (from createVirtualConsole)"); } } else { this._virtualConsole = new VirtualConsole(); } ///// GETTERS define(this, { get length() { return window._length; }, get window() { return window._globalProxy; }, get frames() { return window._globalProxy; }, get self() { return window._globalProxy; }, get parent() { return window._parent; }, get top() { return window._top; }, get document() { return window._document; }, get location() { return window._document._location; } }); namedPropertiesWindow.initializeWindow(this, dom.HTMLCollection); ///// METHODS for [ImplicitThis] hack // See path_to_url this.addEventListener = this.addEventListener.bind(this); this.removeEventListener = this.removeEventListener.bind(this); this.dispatchEvent = this.dispatchEvent.bind(this); ///// METHODS this.setTimeout = function (fn, ms) { return startTimer(window, setTimeout, clearTimeout, fn, ms); }; this.setInterval = function (fn, ms) { return startTimer(window, setInterval, clearInterval, fn, ms); }; this.clearInterval = stopTimer.bind(this, window); this.clearTimeout = stopTimer.bind(this, window); this.__stopAllTimers = stopAllTimers.bind(this, window); this.Image = function (width, height) { const element = window._document.createElement("img"); element.width = width; element.height = height; return element; }; function wrapConsoleMethod(method) { return function () { const args = Array.prototype.slice.call(arguments); window._virtualConsole.emit.apply(window._virtualConsole, [method].concat(args)); }; } this.postMessage = postMessage; this.atob = function (str) { const result = atob(str); if (result === null) { throw new DOMException(DOMException.INVALID_CHARACTER_ERR, "The string to be decoded contains invalid characters."); } return result; }; this.btoa = function (str) { const result = btoa(str); if (result === null) { throw new DOMException(DOMException.INVALID_CHARACTER_ERR, "The string to be encoded contains invalid characters."); } return result; }; this.FileReader = createFileReader(this); this.XMLHttpRequest = createXMLHttpRequest(this); // TODO: necessary for Blob and FileReader due to different-globals weirdness; investigate how to avoid this. this.ArrayBuffer = ArrayBuffer; this.Int8Array = Int8Array; this.Uint8Array = Uint8Array; this.Uint8ClampedArray = Uint8ClampedArray; this.Int16Array = Int16Array; this.Uint16Array = Uint16Array; this.Int32Array = Int32Array; this.Uint32Array = Uint32Array; this.Float32Array = Float32Array; this.Float64Array = Float64Array; this.stop = function () { if (this._document[internalConstants.requestManager]) { this._document[internalConstants.requestManager].close(); } }; this.close = function () { // Recursively close child frame windows, then ourselves. const currentWindow = this; (function windowCleaner(windowToClean) { for (let i = 0; i < windowToClean.length; i++) { windowCleaner(windowToClean[i]); } // We"re already in our own window.close(). if (windowToClean !== currentWindow) { windowToClean.close(); } }(this)); // Clear out all listeners. Any in-flight or upcoming events should not get delivered. idlUtils.implForWrapper(this)._eventListeners = Object.create(null); if (this._document) { if (this._document.body) { this._document.body.innerHTML = ""; } if (this._document.close) { // It's especially important to clear out the listeners here because document.close() causes a "load" event to // fire. this._document._listeners = Object.create(null); this._document.close(); } const doc = this._document; delete this._document; // Stops the connections after document deletion because the listeners will not be triggered once document deleted if (doc[internalConstants.requestManager]) { doc[internalConstants.requestManager].close(); } } stopAllTimers(currentWindow); }; this.getComputedStyle = function (node) { const s = node.style; const cs = new CSSStyleDeclaration(); const forEach = Array.prototype.forEach; function setPropertiesFromRule(rule) { if (!rule.selectorText) { return; } const selectors = rule.selectorText.split(cssSelectorSplitRE); let matched = false; for (const selectorText of selectors) { if (selectorText !== "" && selectorText !== "," && !matched && matchesDontThrow(node, selectorText)) { matched = true; forEach.call(rule.style, property => { cs.setProperty(property, rule.style.getPropertyValue(property), rule.style.getPropertyPriority(property)); }); } } } function readStylesFromStyleSheet(sheet) { forEach.call(sheet.cssRules, rule => { if (rule.media) { if (Array.prototype.indexOf.call(rule.media, "screen") !== -1) { forEach.call(rule.cssRules, setPropertiesFromRule); } } else { setPropertiesFromRule(rule); } }); } readStylesFromStyleSheet(defaultStyleSheet); forEach.call(node.ownerDocument.styleSheets, readStylesFromStyleSheet); forEach.call(s, property => { cs.setProperty(property, s.getPropertyValue(property), s.getPropertyPriority(property)); }); return cs; }; ///// PUBLIC DATA PROPERTIES (TODO: should be getters) this.history = new History(this); this.console = { assert: wrapConsoleMethod("assert"), clear: wrapConsoleMethod("clear"), count: wrapConsoleMethod("count"), debug: wrapConsoleMethod("debug"), error: wrapConsoleMethod("error"), group: wrapConsoleMethod("group"), groupCollapse: wrapConsoleMethod("groupCollapse"), groupEnd: wrapConsoleMethod("groupEnd"), info: wrapConsoleMethod("info"), log: wrapConsoleMethod("log"), table: wrapConsoleMethod("table"), time: wrapConsoleMethod("time"), timeEnd: wrapConsoleMethod("timeEnd"), trace: wrapConsoleMethod("trace"), warn: wrapConsoleMethod("warn") }; function notImplementedMethod(name) { return function () { notImplemented(name, window); }; } define(this, { navigator: { get userAgent() { return options.userAgent; }, get appName() { return "Node.js jsDom"; }, get platform() { return process.platform; }, get appVersion() { return process.version; }, noUI: true, get cookieEnabled() { return true; } }, name: "nodejs", innerWidth: 1024, innerHeight: 768, outerWidth: 1024, outerHeight: 768, pageXOffset: 0, pageYOffset: 0, screenX: 0, screenY: 0, screenLeft: 0, screenTop: 0, scrollX: 0, scrollY: 0, scrollTop: 0, scrollLeft: 0, screen: { width: 0, height: 0 }, alert: notImplementedMethod("window.alert"), blur: notImplementedMethod("window.blur"), confirm: notImplementedMethod("window.confirm"), createPopup: notImplementedMethod("window.createPopup"), focus: notImplementedMethod("window.focus"), moveBy: notImplementedMethod("window.moveBy"), moveTo: notImplementedMethod("window.moveTo"), open: notImplementedMethod("window.open"), print: notImplementedMethod("window.print"), prompt: notImplementedMethod("window.prompt"), resizeBy: notImplementedMethod("window.resizeBy"), resizeTo: notImplementedMethod("window.resizeTo"), scroll: notImplementedMethod("window.scroll"), scrollBy: notImplementedMethod("window.scrollBy"), scrollTo: notImplementedMethod("window.scrollTo"), toString: () => { return "[object Window]"; } }); ///// INITIALIZATION process.nextTick(() => { if (!window.document) { return; // window might've been closed already } if (window.document.readyState === "complete") { const ev = window.document.createEvent("HTMLEvents"); ev.initEvent("load", false, false); window.dispatchEvent(ev); } else { window.document.addEventListener("load", () => { const ev = window.document.createEvent("HTMLEvents"); ev.initEvent("load", false, false); window.dispatchEvent(ev); }); } }); } inherits(EventTarget.interface, Window, EventTarget.interface.prototype); function matchesDontThrow(el, selector) { try { return el.matches(selector); } catch (e) { return false; } } function startTimer(window, startFn, stopFn, callback, ms) { const res = startFn(callback, ms); window.__timers.push([res, stopFn]); return res; } function stopTimer(window, id) { if (typeof id === "undefined") { return; } for (const i in window.__timers) { if (window.__timers[i][0] === id) { window.__timers[i][1].call(window, id); window.__timers.splice(i, 1); break; } } } function stopAllTimers(window) { for (const t of window.__timers) { t[1].call(window, t[0]); } window.__timers = []; } ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/browser/Window.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,886
```javascript "use strict"; const whatwgURL = require("whatwg-url-compat"); const resolveHref = require("../utils").resolveHref; function StateEntry(data, title, url) { this.data = data; this.title = title; this.url = url; } module.exports = History; function History(window) { this._states = [new StateEntry(null, "", window._document._URL)]; this._index = 0; this._window = window; this._location = window._document._location; } History.prototype = { constructor: History, get length() { return this._states.length; }, get state() { const state = this._states[this._index]; return state ? state.data : null; }, back() { this.go(-1); }, forward() { this.go(1); }, go(delta) { if (typeof delta === "undefined" || delta === 0) { this._location.reload(); return; } const newIndex = this._index + delta; if (newIndex < 0 || newIndex >= this.length) { return; } this._index = newIndex; const state = this._states[newIndex]; this._applyState(state); this._signalPopstate(state); }, pushState(data, title, url) { const state = new StateEntry(data, title, url); if (this._index + 1 !== this._states.length) { this._states = this._states.slice(0, this._index + 1); } this._states.push(state); this._applyState(state); this._index++; }, replaceState(data, title, url) { const state = new StateEntry(data, title, url); this._states[this._index] = state; this._applyState(state); }, _applyState(state) { whatwgURL.setTheInput(this._location, resolveHref(this._location.href, state.url)); }, _signalPopstate(state) { if (this._window.document) { const ev = this._window.document.createEvent("HTMLEvents"); ev.initEvent("popstate", false, false); ev.state = state.data; process.nextTick(() => this._window.dispatchEvent(ev)); } }, toString() { return "[object History]"; } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/browser/history.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
516
```javascript "use strict"; var resourceLoader = require('../browser/resource-loader'), core = require("../level1/core"), applyDocumentFeatures = require('../browser/documentfeatures').applyDocumentFeatures, defineGetter = require('../utils').defineGetter, defineSetter = require('../utils').defineSetter, inheritFrom = require("../utils").inheritFrom, URL = require("../utils").URL, Window = require("../browser/Window"), documentBaseURL = require("../living/helpers/document-base-url").documentBaseURL, fallbackBaseURL = require("../living/helpers/document-base-url").fallbackBaseURL, mapper = require("../utils").mapper, addConstants = require("../utils").addConstants, whatwgUrl = require("whatwg-url-compat"), mixinURLUtils = whatwgUrl.mixinURLUtils; const DOMException = require ('../web-idl/DOMException'); const getAttributeValue = require("../living/attributes").getAttributeValue; const cloningSteps = require("../living/helpers/internal-constants").cloningSteps; const clone = require("../living/node").clone; const notImplemented = require("../browser/not-implemented"); const proxiedWindowEventHandlers = require("../living/helpers/proxied-window-event-handlers"); const internalConstants = require("../living/helpers/internal-constants"); const domSymbolTree = internalConstants.domSymbolTree; const accept = internalConstants.accept; const createHTMLCollection = require("../living/html-collection").create; const NODE_TYPE = require("../living/node-type"); // Setup the javascript language processor core.languageProcessors = { javascript : require("./languages/javascript").javascript }; function define(elementClass, def) { var tagName = def.tagName, tagNames = def.tagNames || (tagName? [tagName] : []), parentClass = def.parentClass || core.HTMLElement, attrs = def.attributes || [], proto = def.proto || {}; proto.toString = function() { return '[object ' + elementClass + ']'; }; var elem = core[elementClass] = function(document, name) { parentClass.call(this, document, name || tagName.toUpperCase()); if (elem._init) { elem._init.call(this); } }; elem._init = def.init; inheritFrom(parentClass, elem, proto); attrs.forEach(function(n) { var prop = n.prop || n, attr = n.attr || prop.toLowerCase(); if (!n.prop || n.read !== false) { defineGetter(elem.prototype, prop, function() { var s = this.getAttribute(attr); if (n.type && n.type === 'boolean') { return s !== null; } if (n.type && n.type === 'long') { return +s; } if (typeof n === 'object' && n.normalize) { // see GH-491 return n.normalize(s); } if (s === null) { s = ''; } return s; }); } if (!n.prop || n.write !== false) { defineSetter(elem.prototype, prop, function(val) { if (!val) { this.removeAttribute(attr); } else { var s = val.toString(); if (typeof n === 'object' && n.normalize) { s = n.normalize(s); } this.setAttribute(attr, s); } }); } }); tagNames.forEach(function(tag) { core.Document.prototype._elementBuilders[tag.toLowerCase()] = function(doc, s) { return new elem(doc, s); }; }); } function closest(e, tagName) { tagName = tagName.toUpperCase(); while (e) { if (e.nodeName.toUpperCase() === tagName || (e.tagName && e.tagName.toUpperCase() === tagName)) { return e; } e = domSymbolTree.parent(e); } return null; } function descendants(e, tagName, recursive) { var owner = recursive ? e._ownerDocument || e : e; return createHTMLCollection(owner, mapper(e, function(n) { return n.tagName === tagName; }, recursive)); } function firstChild(e, tagName) { if (!e) { return null; } var c = descendants(e, tagName, false); return c.length > 0 ? c[0] : null; } function ResourceQueue(paused) { this.paused = !!paused; } ResourceQueue.prototype = { push: function(callback) { var q = this; var item = { prev: q.tail, check: function() { if (!q.paused && !this.prev && this.fired){ callback(this.err, this.data); if (this.next) { this.next.prev = null; this.next.check(); }else{//q.tail===this q.tail = null; } } } }; if (q.tail) { q.tail.next = item; } q.tail = item; return function(err, data) { item.fired = 1; item.err = err; item.data = data; item.check(); }; }, resume: function() { if(!this.paused){ return; } this.paused = false; var head = this.tail; while(head && head.prev){ head = head.prev; } if(head){ head.check(); } } }; class RequestManager { constructor() { this.openedRequests = []; } add(req) { this.openedRequests.push(req); } remove(req) { var idx = this.openedRequests.indexOf(req); if(idx !== -1) { this.openedRequests.splice(idx, 1); } } close() { for (const openedRequest of this.openedRequests) { openedRequest.abort(); } this.openedRequests = []; } size() { return this.openedRequests.length; } } core.HTMLDocument = function HTMLDocument(options) { core.Document.call(this, options); this._referrer = options.referrer; this._queue = new ResourceQueue(options.deferClose); this._customResourceLoader = options.resourceLoader; this[internalConstants.pool] = options.pool; this[internalConstants.agentOptions] = options.agentOptions; this[internalConstants.requestManager] = new RequestManager(); this.readyState = 'loading'; // Add level2 features this.implementation._addFeature('core' , '2.0'); this.implementation._addFeature('html' , '2.0'); this.implementation._addFeature('xhtml' , '2.0'); this.implementation._addFeature('xml' , '2.0'); }; var nonInheritedTags = new Set([ 'article', 'section', 'nav', 'aside', 'hgroup', 'header', 'footer', 'address', 'dt', 'dd', 'figure', 'figcaption', 'main', 'em', 'strong', 'small', 's', 'cite', 'dfn', 'abbr', 'ruby', 'rt', 'rp', 'code', 'var', 'samp', 'kbd', 'i', 'b', 'u', 'mark', 'bdi', 'bdo', 'wbr' ]); inheritFrom(core.Document, core.HTMLDocument, { _defaultElementBuilder: function (document, tagName) { if (nonInheritedTags.has(tagName.toLowerCase())) { return new core.HTMLElement(document, tagName); } else { return new core.HTMLUnknownElement(document, tagName); } }, _referrer : "", get referrer() { return this._referrer || ''; }, get domain() { return ""; }, get images() { return this.getElementsByTagName('IMG'); }, get applets() { return createHTMLCollection(this, mapper(this, function(el) { if (el && el.tagName) { var upper = el.tagName.toUpperCase(); if (upper === "APPLET") { return true; } else if (upper === "OBJECT" && el.getElementsByTagName('APPLET').length > 0) { return true; } } })); }, get links() { return createHTMLCollection(this, mapper(this, function(el) { if (el && el.tagName) { var upper = el.tagName.toUpperCase(); if (upper === "AREA" || (upper === "A" && el.href)) { return true; } } })); }, get forms() { return this.getElementsByTagName('FORM'); }, get anchors() { return this.getElementsByTagName('A'); }, open : function() { for (let child = null; child = domSymbolTree.firstChild(this);) { this.removeChild(child); } this._documentElement = null; this._modified(); return this; }, close : function() { this._queue.resume(); // Set the readyState to 'complete' once all resources are loaded. // As a side-effect the document's load-event will be dispatched. resourceLoader.enqueue(this, null, function() { this.readyState = 'complete'; var ev = this.createEvent('HTMLEvents'); ev.initEvent('DOMContentLoaded', false, false); this.dispatchEvent(ev); })(null, true); }, getElementsByName : function(elementName) { return createHTMLCollection(this, mapper(this, function(el) { return (el.getAttribute && el.getAttribute("name") === elementName); })); }, get title() { var head = this.head, title = head ? firstChild(head, 'TITLE') : null; return title ? title.textContent : ''; }, set title(val) { var title = firstChild(this.head, 'TITLE'); if (!title) { title = this.createElement('TITLE'); var head = this.head; if (!head) { head = this.createElement('HEAD'); this.documentElement.insertBefore(head, this.documentElement.firstChild); } head.appendChild(title); } title.textContent = val; }, get head() { return firstChild(this.documentElement, 'HEAD'); }, set head(unused) { /* noop */ }, get body() { var body = firstChild(this.documentElement, 'BODY'); if (!body) { body = firstChild(this.documentElement, 'FRAMESET'); } return body; } }); define('HTMLElement', { parentClass: core.Element, init: function () { this._settingCssText = false; var that = this; this._style = new core.CSSStyleDeclaration(function onCssTextChange(newCssText) { if (!that._settingCssText) { that.setAttribute('style', newCssText); } }); }, proto : { // Add default event behavior (click link to navigate, click button to submit // form, etc). We start by wrapping dispatchEvent so we can forward events to // the element's _eventDefault function (only events that did not incur // preventDefault). dispatchEvent : function (event) { var outcome = core.Node.prototype.dispatchEvent.call(this, event) if (!event.defaultPrevented && event.target._eventDefaults[event.type] && typeof event.target._eventDefaults[event.type] === 'function') { event.target._eventDefaults[event.type](event) } return outcome; }, getBoundingClientRect: function () { return { bottom: 0, height: 0, left: 0, right: 0, top: 0, width: 0 }; }, focus : function() { this._ownerDocument.activeElement = this; }, blur : function() { this._ownerDocument.activeElement = this._ownerDocument.body; }, click: function() { // path_to_url#dom-click // path_to_url#run-synthetic-click-activation-steps // Not completely spec compliant due to e.g. incomplete implementations of disabled for form controls, or no // implementation at all of isTrusted. if (this.disabled) { return false; } var event = new core.MouseEvent("click", { bubbles: true, cancelable: true }); this.dispatchEvent(event); }, get style() { return this._style; }, set style(value) { this._style.cssText = value; }, _eventDefaults : {}, _attrModified: function (name, value, oldValue) { if (name === 'style' && value !== oldValue && !this._settingCssText) { this._settingCssText = true; this._style.cssText = value; this._settingCssText = false; } core.Element.prototype._attrModified.apply(this, arguments); } }, attributes: [ 'id', 'title', 'lang', 'dir', {prop: 'className', attr: 'class', normalize: function(s) { return s || ''; }} ] }); define('HTMLUnknownElement', { // no additional properties & attributes }); // path_to_url#category-listed var listedElements = /button|fieldset|input|keygen|object|select|textarea/i; define('HTMLFormElement', { tagName: 'FORM', proto: { _descendantAdded: function(parent, child) { var form = this; for (const el of domSymbolTree.treeIterator(child)) { if (typeof el._changedFormOwner === 'function') { el._changedFormOwner(form); } }; core.HTMLElement.prototype._descendantAdded.apply(this, arguments); }, _descendantRemoved: function(parent, child) { for (const el of domSymbolTree.treeIterator(child)) { if (typeof el._changedFormOwner === 'function') { el._changedFormOwner(null); } } core.HTMLElement.prototype._descendantRemoved.apply(this, arguments); }, get elements() { return createHTMLCollection(this._ownerDocument, mapper(this, function(e) { return listedElements.test(e.nodeName) ; // TODO exclude <input type="image"> })); }, get length() { return this.elements.length; }, _dispatchSubmitEvent: function() { var ev = this._ownerDocument.createEvent('HTMLEvents'); ev.initEvent('submit', true, true); if (!this.dispatchEvent(ev)) { this.submit(); }; }, submit: function() { }, reset: function() { Array.prototype.forEach.call(this.elements, function(el) { if (typeof el._formReset === 'function') { el._formReset(); } }); } }, attributes: [ 'name', {prop: 'acceptCharset', attr: 'accept-charset'}, 'action', 'enctype', 'method', 'target' ] }); define('HTMLLinkElement', { tagName: 'LINK', proto: { get [accept]() { return "text/css,*/*;q=0.1"; }, get href() { return resourceLoader.resolveResourceUrl(this._ownerDocument, this.getAttribute('href')); } }, attributes: [ {prop: 'disabled', type: 'boolean'}, 'charset', 'href', 'hreflang', 'media', 'rel', 'rev', 'target', 'type' ] }); define('HTMLMetaElement', { tagName: 'META', attributes: [ 'content', {prop: 'httpEquiv', attr: 'http-equiv'}, 'name', 'scheme' ] }); define('HTMLHtmlElement', { tagName: 'HTML', attributes: [ 'version' ] }); define('HTMLHeadElement', { tagName: 'HEAD', attributes: [ 'profile' ] }); define('HTMLTitleElement', { tagName: 'TITLE', proto: { get text() { return this.innerHTML; }, set text(s) { this.innerHTML = s; } } }); function reparseAnchors(doc) { var anchors = doc.getElementsByTagName("a"); for (var i = 0; i < anchors.length; ++i) { whatwgUrl.reparse(anchors[i]); } } define('HTMLBaseElement', { tagName: 'BASE', attributes: [ 'target' ], proto: { get href() { if (!this.hasAttribute("href")) { return documentBaseURL(this._ownerDocument); } var fbbu = fallbackBaseURL(this._ownerDocument); var url = this.getAttribute("href"); try { return new URL(url, fbbu).href; } catch (e) { return ""; } }, set href(value) { this.setAttribute("href", String(value)); }, _attrModified: function (name, value, oldVal) { core.HTMLElement.prototype._attrModified.call(this, name, value, oldVal); if (name === 'href') { reparseAnchors(this._ownerDocument); } }, _detach: function () { core.HTMLElement.prototype._detach.call(this); reparseAnchors(this._ownerDocument); }, _attach: function () { core.HTMLElement.prototype._attach.call(this); reparseAnchors(this._ownerDocument); } } }); define('HTMLStyleElement', { tagName: 'STYLE', attributes: [ {prop: 'disabled', type: 'boolean'}, 'media', 'type', ] }); define('HTMLBodyElement', { proto: (function() { var proto = {}; proxiedWindowEventHandlers.forEach(function (name) { defineSetter(proto, name, function (handler) { const window = this._ownerDocument._defaultView; if (window) { window[name] = handler; } }); defineGetter(proto, name, function () { const window = this._ownerDocument._defaultView; return window ? window[name] : null; }); }); return proto; })(), tagName: 'BODY', attributes: [ 'aLink', 'background', 'bgColor', 'link', 'text', 'vLink' ] }); define('HTMLSelectElement', { tagName: 'SELECT', proto: { _formReset: function() { Array.prototype.forEach.call(this.options, function(option) { option._selectedness = option.defaultSelected; option._dirtyness = false; }); this._askedForAReset(); }, _askedForAReset: function() { if (this.hasAttribute('multiple')) { return; } var selected = Array.prototype.filter.call(this.options, function(option){ return option._selectedness; }); // size = 1 is default if not multiple if ((!this.size || this.size === 1) && !selected.length) { // select the first option that is not disabled for (var i = 0; i < this.options.length; ++i) { var option = this.options[i]; var disabled = option.disabled; const parentNode = domSymbolTree.parent(option); if (parentNode && parentNode.nodeName.toUpperCase() === 'OPTGROUP' && parentNode.disabled) { disabled = true; } if (!disabled) { // (do not set dirty) option._selectedness = true; break; } } } else if (selected.length >= 2) { // select the last selected option selected.forEach(function(option, index) { option._selectedness = index === selected.length - 1; }); } }, _descendantAdded: function(parent, child) { if (child.nodeType === NODE_TYPE.ELEMENT_NODE) { this._askedForAReset(); } core.HTMLElement.prototype._descendantAdded.apply(this, arguments); }, _descendantRemoved: function(parent, child) { if (child.nodeType === NODE_TYPE.ELEMENT_NODE) { this._askedForAReset(); } core.HTMLElement.prototype._descendantRemoved.apply(this, arguments); }, _attrModified: function(name, value) { if (name === 'multiple' || name === 'size') { this._askedForAReset(); } core.HTMLElement.prototype._attrModified.apply(this, arguments); }, get options() { // TODO: implement HTMLOptionsCollection return createHTMLCollection(this, mapper(this, function(n) { return n.nodeName === 'OPTION'; })); }, get length() { return this.options.length; }, get selectedIndex() { return Array.prototype.reduceRight.call(this.options, function(prev, option, i) { return option.selected ? i : prev; }, -1); }, set selectedIndex(index) { Array.prototype.forEach.call(this.options, function(option, i) { option.selected = i === index; }); }, get value() { var i = this.selectedIndex; if (this.options.length && (i === -1)) { i = 0; } if (i === -1) { return ''; } return this.options[i].value; }, set value(val) { var self = this; Array.prototype.forEach.call(this.options, function(option) { if (option.value === val) { option.selected = true; } else { if (!self.hasAttribute('multiple')) { // Remove the selected bit from all other options in this group // if the multiple attr is not present on the select option.selected = false; } } }); }, get form() { return closest(this, 'FORM'); }, get type() { return this.multiple ? 'select-multiple' : 'select-one'; }, add: function(opt, before) { if (before) { this.insertBefore(opt, before); } else { this.appendChild(opt); } }, remove: function(index) { var opts = this.options; if (index >= 0 && index < opts.length) { var el = opts[index]; domSymbolTree.parent(el).removeChild(el); } } }, attributes: [ {prop: 'disabled', type: 'boolean'}, {prop: 'multiple', type: 'boolean'}, 'name', {prop: 'size', type: 'long'}, {prop: 'tabIndex', type: 'long'}, ] }); define('HTMLOptGroupElement', { tagName: 'OPTGROUP', attributes: [ {prop: 'disabled', type: 'boolean'}, 'label' ] }); define('HTMLOptionElement', { tagName: 'OPTION', proto: { // whenever selectedness is set to true, make sure all // other options set selectedness to false _selectedness: false, _dirtyness: false, _removeOtherSelectedness: function() { //Remove the selectedness flag from all other options in this select var select = this._selectNode; if (select && !select.multiple) { var o = select.options; for (var i = 0; i < o.length; i++) { if (o[i] !== this) { o[i]._selectedness = false; } } } }, _askForAReset: function() { var select = this._selectNode; if (select) { select._askedForAReset(); } }, _attrModified: function(name, value) { if (!this._dirtyness && name === 'selected') { this._selectedness = this.defaultSelected; if (this._selectedness) { this._removeOtherSelectedness(); } this._askForAReset(); } core.HTMLElement.prototype._attrModified.apply(this, arguments); }, get _selectNode() { var select = domSymbolTree.parent(this); if (!select) return null; if (select.nodeName.toUpperCase() !== 'SELECT') { select = domSymbolTree.parent(select); if (!select) return null; if (select.nodeName.toUpperCase() !== 'SELECT') return null; } return select; }, get form() { return closest(this, 'FORM'); }, get defaultSelected() { return this.getAttribute('selected') !== null; }, set defaultSelected(s) { if (s) this.setAttribute('selected', 'selected'); else this.removeAttribute('selected'); }, get text() { return this.innerHTML; }, get value() { return (this.hasAttribute('value')) ? this.getAttribute('value') : this.innerHTML; }, set value(val) { this.setAttribute('value', val); }, get index() { return Array.prototype.indexOf.call(closest(this, 'SELECT').options, this); }, get selected() { return this._selectedness; }, set selected(s) { this._dirtyness = true; this._selectedness = !!s; if (this._selectedness) { this._removeOtherSelectedness(); } this._askForAReset(); } }, attributes: [ {prop: 'disabled', type: 'boolean'}, 'label' ] }); const filesSymbol = Symbol("files"); define('HTMLInputElement', { tagName: 'INPUT', init: function() { if (!this.type) { this.type = 'text'; } this._selectionStart = this._selectionEnd = 0; this._selectionDirection = "none"; }, proto: { _value: null, _dirtyValue: false, _checkedness: false, _dirtyCheckedness: false, _attrModified: function(name, value) { if (!this._dirtyValue && name === 'value') { this._value = this.defaultValue; } if (!this._dirtyCheckedness && name === 'checked') { this._checkedness = this.defaultChecked; if (this._checkedness) { this._removeOtherRadioCheckedness(); } } if (name === 'name' || name === 'type') { if (this._checkedness) { this._removeOtherRadioCheckedness(); } } core.HTMLElement.prototype._attrModified.apply(this, arguments); }, _formReset: function() { this._value = this.defaultValue; this._dirtyValue = false; this._checkedness = this.defaultChecked; this._dirtyCheckedness = false; if (this._checkedness) { this._removeOtherRadioCheckedness(); } }, _changedFormOwner: function(newForm) { if (this._checkedness) { this._removeOtherRadioCheckedness(); } }, _removeOtherRadioCheckedness: function() { var root = this._radioButtonGroupRoot; if (!root) { return; } var name = this.name.toLowerCase(); var radios = createHTMLCollection(this, mapper(root, function(el) { return el.type === 'radio' && el.name && el.name.toLowerCase() === name && el._radioButtonGroupRoot === root; })); Array.prototype.forEach.call(radios, function(radio) { if (radio !== this) { radio._checkedness = false; } }, this); }, get _radioButtonGroupRoot() { if (this.type !== 'radio' || !this.name) { return null; } var e = domSymbolTree.parent(this); while (e) { // root node of this home sub tree // or the form element we belong to if (!domSymbolTree.parent(e) || e.nodeName.toUpperCase() === 'FORM') { return e; } e = domSymbolTree.parent(e); } return null; }, get form() { return closest(this, 'FORM'); }, get defaultValue() { var val = this.getAttribute('value'); return val !== null ? val : ""; }, set defaultValue(val) { this.setAttribute('value', String(val)); }, get defaultChecked() { return this.getAttribute('checked') !== null; }, set defaultChecked(s) { if (s) this.setAttribute('checked', 'checked'); else this.removeAttribute('checked'); }, get checked() { return this._checkedness; }, set checked(checked) { this._checkedness = !!checked; this._dirtyCheckedness = true; if (this._checkedness) { this._removeOtherRadioCheckedness(); } }, get value() { if (this._value === null) { return ''; } return this._value; }, set value(val) { this._dirtyValue = true; if (val === null) { this._value = null; } else { this._value = String(val); } if (this._allowSelection()) { this._selectionStart = 0; this._selectionEnd = 0; this._selectionDirection = 'none'; } }, get files() { if (this.type === "file") { this[filesSymbol] = this[filesSymbol] || new core.FileList(); } else { this[filesSymbol] = null; } return this[filesSymbol]; }, get type() { var type = this.getAttribute('type'); return type ? type : 'text'; }, set type(type) { this.setAttribute('type', type); }, blur: function() { this._ownerDocument.activeElement = this._ownerDocument.body; }, focus: function() { this._ownerDocument.activeElement = this; }, //LIVING _dispatchSelectEvent: function() { var event = this._ownerDocument.createEvent("HTMLEvents"); event.initEvent("select", true, true); this.dispatchEvent(event); }, _getValueLength: function() { return typeof this.value === "string" ? this.value.length : 0; }, _allowSelection: function() { var type = this.type.toLowerCase(); return type === "text" || type === "search" || type === "tel" || type === "url" || type === "password"; }, select: function() { if (!this._allowSelection()) { throw new DOMException(DOMException.INVALID_STATE_ERR); } this._selectionStart = 0; this._selectionEnd = this._getValueLength(); this._selectionDirection = "none"; this._dispatchSelectEvent(); }, get selectionStart() { if (!this._allowSelection()) { throw new DOMException(DOMException.INVALID_STATE_ERR); } return this._selectionStart; }, set selectionStart(start) { this.setSelectionRange(start, Math.max(start, this._selectionEnd), this._selectionDirection); }, get selectionEnd() { if(!this._allowSelection()) { throw new DOMException(DOMException.INVALID_STATE_ERR); } return this._selectionEnd; }, set selectionEnd(end) { this.setSelectionRange(this._selectionStart, end, this._selectionDirection); }, get selectionDirection() { if(!this._allowSelection()) { throw new DOMException(DOMException.INVALID_STATE_ERR); } return this._selectionDirection; }, set selectionDirection(dir) { this.setSelectionRange(this._selectionStart, this._selectionEnd, dir); }, setSelectionRange: function(start, end, dir) { if (!this._allowSelection()) { throw new DOMException(DOMException.INVALID_STATE_ERR); } this._selectionEnd = Math.min(end, this._getValueLength()); this._selectionStart = Math.min(start, this._selectionEnd); this._selectionDirection = ((dir == "forward") || (dir == "backward")) ? dir : "none"; this._dispatchSelectEvent(); }, setRangeText: function(repl, start, end, selectionMode) { if (arguments.length < 2) { start = this._selectionStart; end = this._selectionEnd; } else if (start > end) { throw new core.DOMException(core.INDEX_SIZE_ERR); } start = Math.min(start, this._getValueLength()); end = Math.min(end, this._getValueLength()); var val = this.value; var selStart = this._selectionStart; var selEnd = this._selectionEnd; this.value = val.slice(0, start) + repl + val.slice(end); var newEnd = start + this.value.length; if (selectionMode == "select") { this.setSelectionRange(start, newEnd); } else if(selectionMode === "start") { this.setSelectionRange(start, start); } else if(selectionMode === "end") { this.setSelectionRange(newEnd, newEnd); } else {//preserve var delta = repl.length - (end - start); if (selStart > end) { selStart += delta; } else if (selStart > start) { selStart = start; } if (selEnd > end) { selEnd += delta; } else if (selEnd > start) { selEnd = newEnd; } this.setSelectionRange(selStart, selEnd); } }, _eventDefaults: { click: function (event) { var target = event.target; if (target.type === 'checkbox') { target.checked = !target.checked; } else if (target.type === 'radio') { target.checked = true; } else if (target.type === 'submit') { var form = this.form; if (form) { form._dispatchSubmitEvent(); } } } } }, attributes: [ 'accept', 'accessKey', 'align', 'alt', {prop: 'disabled', type: 'boolean'}, {prop: 'maxLength', type: 'long'}, 'name', {prop: 'readOnly', type: 'boolean'}, {prop: 'size', type: 'long'}, 'src', {prop: 'tabIndex', type: 'long'}, {prop: 'type', normalize: function(val) { return val ? val.toLowerCase() : 'text'; }}, 'useMap' ] }); define('HTMLTextAreaElement', { tagName: 'TEXTAREA', init: function() { this._selectionStart = this._selectionEnd = 0; this._selectionDirection = "none"; }, proto: { _apiValue: null, _dirtyValue: false, // "raw value" and "value" are not used here because jsdom has no GUI _formReset: function() { this._apiValue = null; this._dirtyValue = false; }, get form() { return closest(this, 'FORM'); }, get defaultValue() { return this.textContent; }, set defaultValue(val) { this.textContent = val; }, get value() { // The WHATWG specifies that when "textContent" changes, the "raw value" // (just the API value in jsdom) must also be updated. // This slightly different solution has identical results, but is a lot less complex. if (this._dirtyValue) { if (this._apiValue === null) { return ''; } return this._apiValue; } var val = this.defaultValue; val = val.replace(/\r\n|\r/g, '\n'); // API value normalizes line breaks per WHATWG return val; }, set value(val) { if (val) { val = val.replace(/\r\n|\r/g, '\n'); // API value normalizes line breaks per WHATWG } this._dirtyValue = true; this._apiValue = val; this._selectionStart = 0; this._selectionEnd = 0; this._selectionDirection = 'none'; }, get textLength() { return this.value.length; // code unit length (16 bit) }, get type() { return 'textarea'; }, blur : function() { this._ownerDocument.activeElement = this._ownerDocument.body; }, focus : function() { this._ownerDocument.activeElement = this; }, //LIVING _dispatchSelectEvent: function() { var event = this._ownerDocument.createEvent("HTMLEvents"); event.initEvent("select", true, true); this.dispatchEvent(event); }, _getValueLength: function() { return typeof this.value == "string" ? this.value.length : 0; }, select: function() { this._selectionStart = 0; this._selectionEnd = this._getValueLength(); this._selectionDirection = "none"; this._dispatchSelectEvent(); }, get selectionStart() { return this._selectionStart; }, set selectionStart(start) { this.setSelectionRange(start, Math.max(start, this._selectionEnd), this._selectionDirection); }, get selectionEnd() { return this._selectionEnd; }, set selectionEnd(end) { this.setSelectionRange(this._selectionStart, end, this._selectionDirection); }, get selectionDirection() { return this._selectionDirection; }, set selectionDirection(dir) { this.setSelectionRange(this._selectionStart, this._selectionEnd, dir); }, setSelectionRange: function(start, end, dir) { this._selectionEnd = Math.min(end, this._getValueLength()); this._selectionStart = Math.min(start, this._selectionEnd); this._selectionDirection = ((dir == "forward") || (dir == "backward")) ? dir : "none"; this._dispatchSelectEvent(); }, setRangeText: function(repl, start, end, selectionMode) { if (arguments.length < 2) { start = this._selectionStart; end = this._selectionEnd; } else if (start > end) { throw new core.DOMException(core.INDEX_SIZE_ERR); } start = Math.min(start, this._getValueLength()); end = Math.min(end, this._getValueLength()); var val = this.value; var selStart = this._selectionStart; var selEnd = this._selectionEnd; this.value = val.slice(0, start) + repl + val.slice(end); var newEnd = start + this.value.length; if (selectionMode === "select") { this.setSelectionRange(start, newEnd); } else if (selectionMode === "start") { this.setSelectionRange(start, start); } else if (selectionMode === "end") { this.setSelectionRange(newEnd, newEnd); } else {//preserve var delta = repl.length - (end-start); if(selStart > end) { selStart += delta; } else if(selStart > start) { selStart = start; } if (selEnd > end) { selEnd += delta; } else if (selEnd > start) { selEnd = newEnd; } this.setSelectionRange(selStart, selEnd); } } }, attributes: [ 'accessKey', {prop: 'cols', type: 'long'}, {prop: 'disabled', type: 'boolean'}, {prop: 'maxLength', type: 'long'}, 'name', {prop: 'readOnly', type: 'boolean'}, {prop: 'rows', type: 'long'}, {prop: 'tabIndex', type: 'long'} ] }); define('HTMLButtonElement', { tagName: 'BUTTON', proto: { get form() { return closest(this, 'FORM'); }, _eventDefaults: { click: function (event) { var target = event.target; var form = target.form; if (form) { if (target.type === 'submit') { form._dispatchSubmitEvent(); } } } }, get type() { const typeAttr = (this.getAttribute('type') || '').toLowerCase(); switch (typeAttr) { case 'submit': case 'reset': case 'button': case 'menu': return typeAttr; default: return 'submit'; } }, set type(v) { v = String(v).toLowerCase(); switch (v) { case 'submit': case 'reset': case 'button': case 'menu': this.setAttribute('type', v); break; default: this.setAttribute('type', 'submit'); break; } } }, attributes: [ 'accessKey', {prop: 'disabled', type: 'boolean'}, 'name', {prop: 'tabIndex', type: 'long'}, 'value' ] }); define('HTMLLabelElement', { tagName: 'LABEL', proto: { get form() { return closest(this, 'FORM'); } }, attributes: [ 'accessKey', {prop: 'htmlFor', attr: 'for'} ] }); define('HTMLFieldSetElement', { tagName: 'FIELDSET', proto: { get form() { return closest(this, 'FORM'); } } }); define('HTMLLegendElement', { tagName: 'LEGEND', proto: { get form() { return closest(this, 'FORM'); } }, attributes: [ 'accessKey', 'align' ] }); define('HTMLUListElement', { tagName: 'UL', attributes: [ {prop: 'compact', type: 'boolean'}, 'type' ] }); define('HTMLOListElement', { tagName: 'OL', attributes: [ {prop: 'compact', type: 'boolean'}, {prop: 'start', type: 'long'}, 'type' ] }); define('HTMLDListElement', { tagName: 'DL', attributes: [ {prop: 'compact', type: 'boolean'} ] }); define('HTMLDirectoryElement', { tagName: 'DIR', attributes: [ {prop: 'compact', type: 'boolean'} ] }); define('HTMLMenuElement', { tagName: 'MENU', attributes: [ {prop: 'compact', type: 'boolean'} ] }); define('HTMLLIElement', { tagName: 'LI', attributes: [ 'type', {prop: 'value', type: 'long'} ] }); define('HTMLCanvasElement', { tagName: 'CANVAS', init() { let Canvas; try { Canvas = require("canvas"); } catch (e) {} if (typeof Canvas === "function") { // in browserify, the require will succeed but return an empty object this._nodeCanvas = new Canvas(this.width, this.height); } }, proto: { _attrModified(name, value, oldValue) { if ((name == "width" || name === "height") && this._nodeCanvas) { const Canvas = require("canvas"); this._nodeCanvas = new Canvas(this.width, this.height); } return core.HTMLElement.prototype._attrModified.apply(this, arguments); }, getContext(contextId) { if (this._nodeCanvas) { return this._nodeCanvas.getContext(contextId) || null; } notImplemented("HTMLCanvasElement.prototype.getContext (without installing the canvas npm package)", this._ownerDocument._defaultView); }, probablySupportsContext(contextId) { if (this._nodeCanvas) { return contextId === "2d"; } return false; }, setContext(context) { notImplemented("HTMLCanvasElement.prototype.setContext"); }, toDataURL() { if (this._nodeCanvas) { return this._nodeCanvas.toDataURL.apply(this._nodeCanvas, arguments); } notImplemented("HTMLCanvasElement.prototype.toDataURL (without installing the canvas npm package)", this._ownerDocument._defaultView); }, get width() { const parsed = parseInt(this.getAttribute("width")); return (parsed < 0 || Number.isNaN(parsed)) ? 300 : parsed; }, set width(v) { v = parseInt(v); v = (Number.isNaN(v) || v < 0) ? 300 : v; this.setAttribute("width", v); }, get height() { const parsed = parseInt(this.getAttribute("height")); return (parsed < 0 || Number.isNaN(parsed)) ? 150 : parsed; }, set height(v) { v = parseInt(v); v = (Number.isNaN(v) || v < 0) ? 150 : v; this.setAttribute("height", v); } } }); define('HTMLDivElement', { tagName: 'DIV', attributes: [ 'align' ] }); define('HTMLParagraphElement', { tagName: 'P', attributes: [ 'align' ] }); define('HTMLHeadingElement', { tagNames: ['H1','H2','H3','H4','H5','H6'], attributes: [ 'align' ] }); define('HTMLQuoteElement', { tagNames: ['Q','BLOCKQUOTE'], attributes: [ 'cite' ] }); define('HTMLPreElement', { tagName: 'PRE', attributes: [ {prop: 'width', type: 'long'} ] }); define('HTMLBRElement', { tagName: 'BR', attributes: [ 'clear' ] }); define('HTMLBaseFontElement', { tagName: 'BASEFONT', attributes: [ 'color', 'face', {prop: 'size', type: 'long'} ] }); define('HTMLFontElement', { tagName: 'FONT', attributes: [ 'color', 'face', 'size' ] }); define('HTMLHRElement', { tagName: 'HR', attributes: [ 'align', {prop: 'noShade', type: 'boolean'}, 'size', 'width' ] }); define('HTMLModElement', { tagNames: ['INS', 'DEL'], attributes: [ 'cite', 'dateTime' ] }); define('HTMLAnchorElement', { tagName: 'A', init: function () { mixinURLUtils(this, function getTheBase() { return documentBaseURL(this._ownerDocument); }, function updateSteps(value) { this.setAttribute("href", value); }); }, proto: { _attrModified: function(name, value, oldVal) { if (name === 'href') { whatwgUrl.setTheInput(this, value); } core.HTMLElement.prototype._attrModified.call(this, name, value, oldVal); }, }, attributes: [ 'accessKey', 'charset', 'coords', 'hreflang', 'name', 'rel', 'rev', 'shape', {prop: 'tabIndex', type: 'long'}, 'target', 'type' ] }); define('HTMLImageElement', { tagName: 'IMG', proto: { _attrModified: function(name, value, oldVal) { if (name == 'src' && value !== oldVal) { resourceLoader.enqueue(this, null, function () { })(); } core.HTMLElement.prototype._attrModified.call(this, name, value, oldVal); }, get [accept]() { return "image/png,image/*;q=0.8,*/*;q=0.5"; }, get src() { return resourceLoader.resolveResourceUrl(this._ownerDocument, this.getAttribute('src')); } }, attributes: [ 'name', 'align', 'alt', 'border', {prop: 'height', type: 'long'}, {prop: 'hspace', type: 'long'}, {prop: 'isMap', type: 'boolean'}, 'longDesc', {prop: 'src', type: 'string', read: false}, 'useMap', {prop: 'vspace', type: 'long'}, {prop: 'width', type: 'long'} ] }); define('HTMLObjectElement', { tagName: 'OBJECT', proto: { get form() { return closest(this, 'FORM'); }, get contentDocument() { return null; } }, attributes: [ 'code', 'align', 'archive', 'border', 'codeBase', 'codeType', 'data', {prop: 'declare', type: 'boolean'}, {prop: 'height', type: 'long'}, {prop: 'hspace', type: 'long'}, 'name', 'standby', {prop: 'tabIndex', type: 'long'}, 'type', 'useMap', {prop: 'vspace', type: 'long'}, {prop: 'width', type: 'long'} ] }); define('HTMLParamElement', { tagName: 'PARAM', attributes: [ 'name', 'type', 'value', 'valueType' ] }); define('HTMLAppletElement', { tagName: 'APPLET', attributes: [ 'align', 'alt', 'archive', 'code', 'codeBase', 'height', {prop: 'hspace', type: 'long'}, 'name', 'object', {prop: 'vspace', type: 'long'}, 'width' ] }); define('HTMLMapElement', { tagName: 'MAP', proto: { get areas() { return this.getElementsByTagName("AREA"); } }, attributes: [ 'name' ] }); define('HTMLAreaElement', { tagName: 'AREA', attributes: [ 'accessKey', 'alt', 'coords', 'href', {prop: 'noHref', type: 'boolean'}, 'shape', {prop: 'tabIndex', type: 'long'}, 'target' ] }); define('HTMLScriptElement', { tagName: 'SCRIPT', init: function() { this.addEventListener('DOMNodeInsertedIntoDocument', function() { if (this.src) { resourceLoader.load(this, this.src, this._eval); } else { resourceLoader.enqueue(this, this._ownerDocument.URL, this._eval)(null, this.text); } }); }, proto: { _eval: function(text, filename) { if (this._ownerDocument.implementation._hasFeature("ProcessExternalResources", "script") && this.language && core.languageProcessors[this.language]) { this._ownerDocument._writeAfterElement = this; core.languageProcessors[this.language](this, text, filename); delete this._ownerDocument._writeAfterElement; } }, get language() { var type = this.type || "text/javascript"; return type.split("/").pop().toLowerCase(); }, get text() { let text = ''; for (const child of domSymbolTree.childrenIterator(this)) { text += child.nodeValue; } return text; }, set text(text) { for (let child = null; child = domSymbolTree.firstChild(this);) { this.removeChild(child); } this.appendChild(this._ownerDocument.createTextNode(text)); } }, attributes : [ {prop: 'defer', 'type': 'boolean'}, 'htmlFor', 'event', 'charset', 'type', 'src' ] }) define('HTMLTableElement', { tagName: 'TABLE', proto: { get caption() { return firstChild(this, 'CAPTION'); }, get tHead() { return firstChild(this, 'THEAD'); }, get tFoot() { return firstChild(this, 'TFOOT'); }, get rows() { if (!this._rows) { var table = this; this._rows = createHTMLCollection(this._ownerDocument, function() { const sections = []; if (table.tHead) { sections.push(table.tHead); } sections.push.apply(sections, table.tBodies); if (table.tFoot) { sections.push(table.tFoot); } if (sections.length === 0) { return domSymbolTree.childrenToArray(table, {filter: function(el) { return el.tagName === 'TR'; }}); } const rows = []; for (const s of sections) { rows.push.apply(rows, s.rows); } return rows; }); } return this._rows; }, get tBodies() { if (!this._tBodies) { this._tBodies = descendants(this, 'TBODY', false); } return this._tBodies; }, createTHead: function() { var el = this.tHead; if (!el) { el = this._ownerDocument.createElement('THEAD'); this.appendChild(el); } return el; }, deleteTHead: function() { var el = this.tHead; if (el) { domSymbolTree.parent(el).removeChild(el); } }, createTFoot: function() { var el = this.tFoot; if (!el) { el = this._ownerDocument.createElement('TFOOT'); this.appendChild(el); } return el; }, deleteTFoot: function() { var el = this.tFoot; if (el) { domSymbolTree.parent(el).removeChild(el); } }, createCaption: function() { var el = this.caption; if (!el) { el = this._ownerDocument.createElement('CAPTION'); this.appendChild(el); } return el; }, deleteCaption: function() { var c = this.caption; if (c) { domSymbolTree.parent(c).removeChild(c); } }, insertRow: function(index) { var tr = this._ownerDocument.createElement('TR'); if (!domSymbolTree.hasChildren(this)) { this.appendChild(this._ownerDocument.createElement('TBODY')); } var rows = this.rows; if (index < -1 || index > rows.length) { throw new core.DOMException(core.DOMException.INDEX_SIZE_ERR); } if (index === -1 || (index === 0 && rows.length === 0)) { this.tBodies.item(0).appendChild(tr); } else if (index === rows.length) { var ref = rows[index-1]; domSymbolTree.parent(ref).appendChild(tr); } else { var ref = rows[index]; domSymbolTree.parent(ref).insertBefore(tr, ref); } return tr; }, deleteRow: function(index) { var rows = this.rows, l = rows.length; if (index === -1) { index = l-1; } if (index < 0 || index >= l) { throw new core.DOMException(core.DOMException.INDEX_SIZE_ERR); } var tr = rows[index]; domSymbolTree.parent(tr).removeChild(tr); } }, attributes: [ 'align', 'bgColor', 'border', 'cellPadding', 'cellSpacing', 'frame', 'rules', 'summary', 'width' ] }); define('HTMLTableCaptionElement', { tagName: 'CAPTION', attributes: [ 'align' ] }); define('HTMLTableColElement', { tagNames: ['COL','COLGROUP'], attributes: [ { prop: 'span', type: 'long' }, 'align', { prop: 'ch', attr: 'char' }, { prop: 'chOff', attr: 'charoff' }, 'vAlign', 'width' ] }); define('HTMLTableSectionElement', { tagNames: ['THEAD','TBODY','TFOOT'], proto: { get rows() { if (!this._rows) { this._rows = descendants(this, 'TR', false); } return this._rows; }, insertRow: function(index) { var tr = this._ownerDocument.createElement('TR'); var rows = this.rows; if (index < -1 || index > rows.length) { throw new core.DOMException(core.DOMException.INDEX_SIZE_ERR); } if (index === -1 || index === rows.length) { this.appendChild(tr); } else { var ref = rows[index]; this.insertBefore(tr, ref); } return tr; }, deleteRow: function(index) { var rows = this.rows; if (index === -1) { index = rows.length-1; } if (index < 0 || index >= rows.length) { throw new core.DOMException(core.DOMException.INDEX_SIZE_ERR); } var tr = this.rows[index]; this.removeChild(tr); } }, attributes: [ 'align', {prop: 'ch', attr: 'char'}, {prop: 'chOff', attr: 'charoff'}, 'vAlign' ] }); define('HTMLTableRowElement', { tagName: 'TR', proto: { get cells() { if (!this._cells) { this._cells = createHTMLCollection(this, mapper(this, function(n) { return n.nodeName === 'TD' || n.nodeName === 'TH'; }, false)); } return this._cells; }, get rowIndex() { var table = closest(this, 'TABLE'); return table ? Array.prototype.indexOf.call(table.rows, this) : -1; }, get sectionRowIndex() { return Array.prototype.indexOf.call(domSymbolTree.parent(this).rows, this); }, insertCell: function(index) { var td = this._ownerDocument.createElement('TD'); var cells = this.cells; if (index < -1 || index > cells.length) { throw new core.DOMException(core.DOMException.INDEX_SIZE_ERR); } if (index === -1 || index === cells.length) { this.appendChild(td); } else { var ref = cells[index]; this.insertBefore(td, ref); } return td; }, deleteCell: function(index) { var cells = this.cells; if (index === -1) { index = cells.length-1; } if (index < 0 || index >= cells.length) { throw new core.DOMException(core.DOMException.INDEX_SIZE_ERR); } var td = this.cells[index]; this.removeChild(td); } }, attributes: [ 'align', { prop: 'ch', attr: 'char' }, { prop: 'chOff', attr: 'charoff' }, 'vAlign', 'bgColor' ] }); define('HTMLTableCellElement', { init() { this._headers = null; }, proto: { set headers(h) { if (h === '') { //Handle resetting headers so the dynamic getter returns a query this._headers = null; return; } if (!(h instanceof Array)) { h = [h]; } this._headers = h; }, get headers() { if (this._headers) { return this._headers.join(' '); } var cellIndex = this.cellIndex, headings = [], siblings = domSymbolTree.parent(this).getElementsByTagName(this.tagName); for (var i=0; i<siblings.length; i++) { if (siblings.item(i).cellIndex >= cellIndex) { break; } headings.push(siblings.item(i).id); } this._headers = headings; return headings.join(' '); }, get cellIndex() { return Array.prototype.indexOf.call(closest(this, 'TR').cells, this); } }, attributes: [ { prop: 'colSpan', type: 'long' }, { prop: 'rowSpan', type: 'long' }, 'align', 'axis', 'height', 'width', { prop: 'ch', attr: 'char' }, { prop: 'chOff', attr: 'charoff' }, { prop: 'noWrap', type: 'boolean' }, 'vAlign', 'bgColor' ] }); define('HTMLTableDataCellElement', { tagName: 'TD', parentClass: core.HTMLTableCellElement, attributes: [ 'abbr' ] }); define('HTMLTableHeaderCellElement', { tagName: 'TH', parentClass: core.HTMLTableCellElement, attributes: [ 'scope', 'abbr', 'sorted' ] }); define('HTMLFrameSetElement', { tagName: 'FRAMESET', attributes: [ 'cols', 'rows' ] }); function loadFrame (frame) { if (frame._contentDocument) { if (frame._contentDocument.defaultView) { // close calls delete on its document. frame._contentDocument.defaultView.close(); } else { delete frame._contentDocument; } } var parentDoc = frame._ownerDocument; // path_to_url#process-the-iframe-attributes let url; const srcAttribute = getAttributeValue(frame, "src"); if (srcAttribute === null || srcAttribute === "") { url = new URL("about:blank"); } else { try { url = new URL(srcAttribute, documentBaseURL(parentDoc)); } catch (e) { url = new URL("about:blank"); } } var wnd = new Window({ parsingMode: 'html', url: url.protocol === 'javascript:' || url.href === 'about:blank' ? parentDoc.URL : url.href, cookieJar: parentDoc._cookieJar }); var contentDoc = frame._contentDocument = wnd.document; applyDocumentFeatures(contentDoc, parentDoc.implementation._features); var parent = parentDoc.defaultView; var contentWindow = contentDoc.defaultView; contentWindow._parent = parent; contentWindow._top = parent.top; contentWindow._virtualConsole = parent._virtualConsole; // Handle about:blank with a simulated load of an empty document. if (url.href === 'about:blank') { // Cannot be done inside the enqueued callback; the documentElement etc. need to be immediately available. contentDoc.write("<html><head></head><body></body></html>"); contentDoc.close(); resourceLoader.enqueue(frame, undefined, function () { })(); // to fire the load event } else if (url.protocol === 'javascript:') { // Cannot be done inside the enqueued callback; the documentElement etc. need to be immediately available. contentDoc.write("<html><head></head><body></body></html>"); contentDoc.close(); contentWindow.eval(url.pathname); resourceLoader.enqueue(frame, undefined, function () { })(); // to fire the load event } else { resourceLoader.load(frame, url.href, function(html) { contentDoc.write(html); contentDoc.close(); }); } } function refreshAccessors(document) { var window = document._defaultView; if (!window) { return; } var frames = document.querySelectorAll("iframe,frame"); // delete accessors for all frames for (var i = 0; i < window._length; ++i) { delete window[i]; } window._length = frames.length; Array.prototype.forEach.call(frames, function (frame, i) { defineGetter(window, i, function () { return frame.contentWindow; }); }); } define('HTMLFrameElement', { tagName: 'FRAME', proto: { _attrModified: function (name, value, oldVal) { core.HTMLElement.prototype._attrModified.call(this, name, value, oldVal); if (name === 'src') { // iframe should never load in a document without a Window // (e.g. implementation.createHTMLDocument) if (this._attached && this._ownerDocument._defaultView) { loadFrame(this); } } }, _detach: function () { core.HTMLElement.prototype._detach.call(this); if (this.contentWindow) { this.contentWindow.close(); } refreshAccessors(this._ownerDocument); }, _attach: function () { core.HTMLElement.prototype._attach.call(this); if (this._ownerDocument._defaultView) { loadFrame(this); } refreshAccessors(this._ownerDocument); }, _contentDocument : null, get contentDocument() { return this._contentDocument; }, get contentWindow() { return this.contentDocument ? this.contentDocument.defaultView : null; } }, attributes: [ 'frameBorder', 'longDesc', 'marginHeight', 'marginWidth', 'name', {prop: 'noResize', type: 'boolean'}, 'scrolling', {prop: 'src', type: 'string', write: false} ] }); define('HTMLIFrameElement', { tagName: 'IFRAME', parentClass: core.HTMLFrameElement, attributes: [ 'align', 'frameBorder', 'height', 'longDesc', 'marginHeight', 'marginWidth', 'name', 'scrolling', 'src', 'width' ] }); // HTMLMediaElement and HTMLVideoElement back-ported from Facebook's Jest project: // path_to_url // They are not expected to be perfectly to-spec, and PRs to improve them over time are certainly appreciated. function getTimeRangeDummy() { return { length: 0, start: function() { return 0; }, end: function() { return 0; } }; } define('HTMLMediaElement', { init: function() { this._muted = this.defaultMuted; this._volume = 1.0; this.readyState = 0; }, proto: { // Implemented accoring to W3C Draft 22 August 2012 set defaultPlaybackRate(v) { if (v === 0.0) { throw new core.DOMException(core.NOT_SUPPORTED_ERR); } if (this._defaultPlaybackRate !== v) { this._defaultPlaybackRate = v; this._dispatchRateChange(); } }, _dispatchRateChange: function() { var ev = this._ownerDocument.createEvent('HTMLEvents'); ev.initEvent('ratechange', false, false); this.dispatchEvent(ev); }, get defaultPlaybackRate() { if (this._defaultPlaybackRate === undefined) { return 1.0; } return this._defaultPlaybackRate; }, get playbackRate() { if (this._playbackRate === undefined) { return 1.0; } return this._playbackRate; }, set playbackRate(v) { if (v !== this._playbackRate) { this._playbackRate = v; this._dispatchRateChange(); } }, get muted() { return this._muted; }, _dispatchVolumeChange: function() { var ev = this._ownerDocument.createEvent('HTMLEvents'); ev.initEvent('volumechange', false, false); this.dispatchEvent(ev); }, set muted(v) { if (v !== this._muted) { this._muted = v; this._dispatchVolumeChange(); } }, get defaultMuted() { return this.getAttribute('muted') !== null; }, set defaultMuted(v) { if (v) { this.setAttribute('muted', v); } else { this.removeAttribute('muted'); } }, get volume() { return this._volume; }, set volume(v) { if (v < 0 || v > 1) { throw new core.DOMException(core.INDEX_SIZE_ERR); } if (this._volume !== v) { this._volume = v; this._dispatchVolumeChange(); } }, // Not (yet) implemented according to spec // Should return sane default values currentSrc: '', buffered: getTimeRangeDummy(), networkState: 0, load: function() { }, canPlayType: function() { return false; }, seeking: false, duration: 0, startDate: NaN, paused: true, played: getTimeRangeDummy(), seekable: getTimeRangeDummy(), ended: false, play: function() { }, pause: function() { }, audioTracks: [], videoTracks: [], textTracks: [], addTextTrack: function() { } }, attributes: [ { prop: 'autoplay', type: 'boolean' }, { prop: 'controls', type: 'boolean' }, 'crossOrigin', 'currentTime', 'preload', { prop: 'loop', type: 'boolean' }, 'mediaGroup', ] }); addConstants(core.HTMLMediaElement, { NETWORK_EMPTY: 0, NETWORK_IDLE: 1, NETWORK_LOADED: 2, NETWORK_NO_SOURCE: 3, HAVE_NOTHING: 0, HAVE_METADATA: 1, HAVE_CURRENT_DATA: 2, HAVE_FUTURE_DATA: 3, HAVE_ENOUGH_DATA: 4 }); define('HTMLVideoElement', { tagName: 'VIDEO', parentClass: core.HTMLMediaElement, attributes: [ { prop: 'height', type: 'long' }, 'poster', { prop: 'videoHeight', type: 'long' }, { prop: 'videoWidth', type: 'long' }, { prop: 'width', type: 'long' } ] }); define('HTMLAudioElement', { tagName: 'AUDIO', parentClass: core.HTMLMediaElement }); define('HTMLDataElement', { tagName: 'DATA', attributes: [ 'value' ] }); define('HTMLSpanElement', { tagName: 'SPAN' }); define('HTMLTimeElement', { tagName: 'TIME', attributes: [ 'dateTime' ] }); // The following are stubs simply so that we have the correct tag name <-> interface correspondences. // Feel free to send PRs updating them! define('HTMLDataListElement', { tagName: 'DATALIST' }); define('HTMLDialogElement', { tagName: 'DIALOG' }); define('HTMLEmbedElement', { tagName: 'EMBED', attributes: [ 'src', 'type', { prop: 'width', type: 'long' }, { prop: 'height', type: 'long' }, 'align', 'name' ] }); define('HTMLMeterElement', { tagName: 'METER' }); define('HTMLOutputElement', { tagName: 'OUTPUT' }); define('HTMLProgressElement', { tagName: 'PROGRESS' }); define('HTMLSourceElement', { tagName: 'SOURCE', attributes: [ 'src', 'type', 'srcset', 'sizes', 'media' ] }); define('HTMLTemplateElement', { tagName: 'TEMPLATE', init() { // TODO: don't use this._ownerDocument; instead, create a new document this._templateContents = this._ownerDocument.createDocumentFragment(); }, proto: { get content() { return this._templateContents; }, [cloningSteps](copy, node, document, cloneChildren) { if (!cloneChildren) { return; } for (const child of domSymbolTree.childrenIterator(node._templateContents)) { const childCopy = clone(core, child, copy._templateContents._ownerDocument, true); copy._templateContents.appendChild(childCopy); } } } }); define('HTMLTrackElement', { tagName: 'TRACK', attributes: [ 'kind', 'src', 'srclang', 'label', { prop: 'default', type: 'boolean' } ], proto: { get readyState() { return 0; } } }); addConstants(core.HTMLTrackElement, { NONE: 0, LOADING: 1, LOADED: 2, ERROR: 3 }); ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/level2/html.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
15,861
```javascript // Ideally, we would use // path_to_url#the-css-user-agent-style-sheet-and-presentational-hints // but for now, just use the version from blink. This file is copied from // path_to_url // (removed a line which had octal literals inside since octal literals are not allowed in template strings) // We use a .js file because otherwise we can't browserify this. (brfs is unusable due to lack of ES2015 support) module.exports = ` /* * The default style sheet used to render HTML. * * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ @namespace "path_to_url"; html { display: block } :root { scroll-blocks-on: start-touch wheel-event } /* children of the <head> element all have display:none */ head { display: none } meta { display: none } title { display: none } link { display: none } style { display: none } script { display: none } /* generic block-level elements */ body { display: block; margin: 8px } body:-webkit-full-page-media { background-color: rgb(0, 0, 0) } p { display: block; -webkit-margin-before: 1__qem; -webkit-margin-after: 1__qem; -webkit-margin-start: 0; -webkit-margin-end: 0; } div { display: block } layer { display: block } article, aside, footer, header, hgroup, main, nav, section { display: block } marquee { display: inline-block; } address { display: block } blockquote { display: block; -webkit-margin-before: 1__qem; -webkit-margin-after: 1em; -webkit-margin-start: 40px; -webkit-margin-end: 40px; } figcaption { display: block } figure { display: block; -webkit-margin-before: 1em; -webkit-margin-after: 1em; -webkit-margin-start: 40px; -webkit-margin-end: 40px; } q { display: inline } q:before { content: open-quote; } q:after { content: close-quote; } center { display: block; /* special centering to be able to emulate the html4/netscape behaviour */ text-align: -webkit-center } hr { display: block; -webkit-margin-before: 0.5em; -webkit-margin-after: 0.5em; -webkit-margin-start: auto; -webkit-margin-end: auto; border-style: inset; border-width: 1px; box-sizing: border-box } map { display: inline } video { object-fit: contain; } /* heading elements */ h1 { display: block; font-size: 2em; -webkit-margin-before: 0.67__qem; -webkit-margin-after: 0.67em; -webkit-margin-start: 0; -webkit-margin-end: 0; font-weight: bold } :-webkit-any(article,aside,nav,section) h1 { font-size: 1.5em; -webkit-margin-before: 0.83__qem; -webkit-margin-after: 0.83em; } :-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) h1 { font-size: 1.17em; -webkit-margin-before: 1__qem; -webkit-margin-after: 1em; } :-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) h1 { font-size: 1.00em; -webkit-margin-before: 1.33__qem; -webkit-margin-after: 1.33em; } :-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) h1 { font-size: .83em; -webkit-margin-before: 1.67__qem; -webkit-margin-after: 1.67em; } :-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) :-webkit-any(article,aside,nav,section) h1 { font-size: .67em; -webkit-margin-before: 2.33__qem; -webkit-margin-after: 2.33em; } h2 { display: block; font-size: 1.5em; -webkit-margin-before: 0.83__qem; -webkit-margin-after: 0.83em; -webkit-margin-start: 0; -webkit-margin-end: 0; font-weight: bold } h3 { display: block; font-size: 1.17em; -webkit-margin-before: 1__qem; -webkit-margin-after: 1em; -webkit-margin-start: 0; -webkit-margin-end: 0; font-weight: bold } h4 { display: block; -webkit-margin-before: 1.33__qem; -webkit-margin-after: 1.33em; -webkit-margin-start: 0; -webkit-margin-end: 0; font-weight: bold } h5 { display: block; font-size: .83em; -webkit-margin-before: 1.67__qem; -webkit-margin-after: 1.67em; -webkit-margin-start: 0; -webkit-margin-end: 0; font-weight: bold } h6 { display: block; font-size: .67em; -webkit-margin-before: 2.33__qem; -webkit-margin-after: 2.33em; -webkit-margin-start: 0; -webkit-margin-end: 0; font-weight: bold } /* tables */ table { display: table; border-collapse: separate; border-spacing: 2px; border-color: gray } thead { display: table-header-group; vertical-align: middle; border-color: inherit } tbody { display: table-row-group; vertical-align: middle; border-color: inherit } tfoot { display: table-footer-group; vertical-align: middle; border-color: inherit } /* for tables without table section elements (can happen with XHTML or dynamically created tables) */ table > tr { vertical-align: middle; } col { display: table-column } colgroup { display: table-column-group } tr { display: table-row; vertical-align: inherit; border-color: inherit } td, th { display: table-cell; vertical-align: inherit } th { font-weight: bold } caption { display: table-caption; text-align: -webkit-center } /* lists */ ul, menu, dir { display: block; list-style-type: disc; -webkit-margin-before: 1__qem; -webkit-margin-after: 1em; -webkit-margin-start: 0; -webkit-margin-end: 0; -webkit-padding-start: 40px } ol { display: block; list-style-type: decimal; -webkit-margin-before: 1__qem; -webkit-margin-after: 1em; -webkit-margin-start: 0; -webkit-margin-end: 0; -webkit-padding-start: 40px } li { display: list-item; text-align: -webkit-match-parent; } ul ul, ol ul { list-style-type: circle } ol ol ul, ol ul ul, ul ol ul, ul ul ul { list-style-type: square } dd { display: block; -webkit-margin-start: 40px } dl { display: block; -webkit-margin-before: 1__qem; -webkit-margin-after: 1em; -webkit-margin-start: 0; -webkit-margin-end: 0; } dt { display: block } ol ul, ul ol, ul ul, ol ol { -webkit-margin-before: 0; -webkit-margin-after: 0 } /* form elements */ form { display: block; margin-top: 0__qem; } label { cursor: default; } legend { display: block; -webkit-padding-start: 2px; -webkit-padding-end: 2px; border: none } fieldset { display: block; -webkit-margin-start: 2px; -webkit-margin-end: 2px; -webkit-padding-before: 0.35em; -webkit-padding-start: 0.75em; -webkit-padding-end: 0.75em; -webkit-padding-after: 0.625em; border: 2px groove ThreeDFace; min-width: -webkit-min-content; } button { -webkit-appearance: button; } /* Form controls don't go vertical. */ input, textarea, keygen, select, button, meter, progress { -webkit-writing-mode: horizontal-tb !important; } input, textarea, keygen, select, button { margin: 0__qem; font: -webkit-small-control; text-rendering: auto; /* FIXME: Remove when tabs work with optimizeLegibility. */ color: initial; letter-spacing: normal; word-spacing: normal; line-height: normal; text-transform: none; text-indent: 0; text-shadow: none; display: inline-block; text-align: start; } input[type="hidden" i] { display: none } input { -webkit-appearance: textfield; padding: 1px; background-color: white; border: 2px inset; -webkit-rtl-ordering: logical; -webkit-user-select: text; cursor: auto; } input[type="search" i] { -webkit-appearance: searchfield; box-sizing: border-box; } input::-webkit-textfield-decoration-container { display: flex; align-items: center; -webkit-user-modify: read-only !important; content: none !important; } input[type="search" i]::-webkit-textfield-decoration-container { direction: ltr; } input::-webkit-clear-button { -webkit-appearance: searchfield-cancel-button; display: inline-block; flex: none; -webkit-user-modify: read-only !important; -webkit-margin-start: 2px; opacity: 0; pointer-events: none; } input:enabled:read-write:-webkit-any(:focus,:hover)::-webkit-clear-button { opacity: 1; pointer-events: auto; } input[type="search" i]::-webkit-search-cancel-button { -webkit-appearance: searchfield-cancel-button; display: block; flex: none; -webkit-user-modify: read-only !important; -webkit-margin-start: 1px; opacity: 0; pointer-events: none; } input[type="search" i]:enabled:read-write:-webkit-any(:focus,:hover)::-webkit-search-cancel-button { opacity: 1; pointer-events: auto; } input[type="search" i]::-webkit-search-decoration { -webkit-appearance: searchfield-decoration; display: block; flex: none; -webkit-user-modify: read-only !important; -webkit-align-self: flex-start; margin: auto 0; } input[type="search" i]::-webkit-search-results-decoration { -webkit-appearance: searchfield-results-decoration; display: block; flex: none; -webkit-user-modify: read-only !important; -webkit-align-self: flex-start; margin: auto 0; } input::-webkit-inner-spin-button { -webkit-appearance: inner-spin-button; display: inline-block; cursor: default; flex: none; align-self: stretch; -webkit-user-select: none; -webkit-user-modify: read-only !important; opacity: 0; pointer-events: none; } input:enabled:read-write:-webkit-any(:focus,:hover)::-webkit-inner-spin-button { opacity: 1; pointer-events: auto; } keygen, select { border-radius: 5px; } keygen::-webkit-keygen-select { margin: 0px; } textarea { -webkit-appearance: textarea; background-color: white; border: 1px solid; -webkit-rtl-ordering: logical; -webkit-user-select: text; flex-direction: column; resize: auto; cursor: auto; padding: 2px; white-space: pre-wrap; word-wrap: break-word; } ::-webkit-input-placeholder { -webkit-text-security: none; color: darkGray; display: block !important; pointer-events: none !important; } input::-webkit-input-placeholder { white-space: pre; word-wrap: normal; overflow: hidden; -webkit-user-modify: read-only !important; } input[type="password" i] { -webkit-text-security: disc !important; } input[type="hidden" i], input[type="image" i], input[type="file" i] { -webkit-appearance: initial; padding: initial; background-color: initial; border: initial; } input[type="file" i] { align-items: baseline; color: inherit; text-align: start !important; } input:-webkit-autofill, textarea:-webkit-autofill, select:-webkit-autofill { background-color: #FAFFBD !important; background-image:none !important; color: #000000 !important; } input[type="radio" i], input[type="checkbox" i] { margin: 3px 0.5ex; padding: initial; background-color: initial; border: initial; } input[type="button" i], input[type="submit" i], input[type="reset" i] { -webkit-appearance: push-button; -webkit-user-select: none; white-space: pre } input[type="file" i]::-webkit-file-upload-button { -webkit-appearance: push-button; -webkit-user-modify: read-only !important; white-space: nowrap; margin: 0; font-size: inherit; } input[type="button" i], input[type="submit" i], input[type="reset" i], input[type="file" i]::-webkit-file-upload-button, button { align-items: flex-start; text-align: center; cursor: default; color: ButtonText; padding: 2px 6px 3px 6px; border: 2px outset ButtonFace; background-color: ButtonFace; box-sizing: border-box } input[type="range" i] { -webkit-appearance: slider-horizontal; padding: initial; border: initial; margin: 2px; color: #909090; } input[type="range" i]::-webkit-slider-container, input[type="range" i]::-webkit-media-slider-container { flex: 1; min-width: 0; box-sizing: border-box; -webkit-user-modify: read-only !important; display: flex; } input[type="range" i]::-webkit-slider-runnable-track { flex: 1; min-width: 0; -webkit-align-self: center; box-sizing: border-box; -webkit-user-modify: read-only !important; display: block; } input[type="range" i]::-webkit-slider-thumb, input[type="range" i]::-webkit-media-slider-thumb { -webkit-appearance: sliderthumb-horizontal; box-sizing: border-box; -webkit-user-modify: read-only !important; display: block; } input[type="button" i]:disabled, input[type="submit" i]:disabled, input[type="reset" i]:disabled, input[type="file" i]:disabled::-webkit-file-upload-button, button:disabled, select:disabled, keygen:disabled, optgroup:disabled, option:disabled, select[disabled]>option { color: GrayText } input[type="button" i]:active, input[type="submit" i]:active, input[type="reset" i]:active, input[type="file" i]:active::-webkit-file-upload-button, button:active { border-style: inset } input[type="button" i]:active:disabled, input[type="submit" i]:active:disabled, input[type="reset" i]:active:disabled, input[type="file" i]:active:disabled::-webkit-file-upload-button, button:active:disabled { border-style: outset } option:-internal-spatial-navigation-focus { outline: black dashed 1px; outline-offset: -1px; } datalist { display: none } area { display: inline; cursor: pointer; } param { display: none } input[type="checkbox" i] { -webkit-appearance: checkbox; box-sizing: border-box; } input[type="radio" i] { -webkit-appearance: radio; box-sizing: border-box; } input[type="color" i] { -webkit-appearance: square-button; width: 44px; height: 23px; background-color: ButtonFace; /* Same as native_theme_base. */ border: 1px #a9a9a9 solid; padding: 1px 2px; } input[type="color" i]::-webkit-color-swatch-wrapper { display:flex; padding: 4px 2px; box-sizing: border-box; -webkit-user-modify: read-only !important; width: 100%; height: 100% } input[type="color" i]::-webkit-color-swatch { background-color: #000000; border: 1px solid #777777; flex: 1; min-width: 0; -webkit-user-modify: read-only !important; } input[type="color" i][list] { -webkit-appearance: menulist; width: 88px; height: 23px } input[type="color" i][list]::-webkit-color-swatch-wrapper { padding-left: 8px; padding-right: 24px; } input[type="color" i][list]::-webkit-color-swatch { border-color: #000000; } input::-webkit-calendar-picker-indicator { display: inline-block; width: 0.66em; height: 0.66em; padding: 0.17em 0.34em; -webkit-user-modify: read-only !important; opacity: 0; pointer-events: none; } input::-webkit-calendar-picker-indicator:hover { background-color: #eee; } input:enabled:read-write:-webkit-any(:focus,:hover)::-webkit-calendar-picker-indicator, input::-webkit-calendar-picker-indicator:focus { opacity: 1; pointer-events: auto; } input[type="date" i]:disabled::-webkit-clear-button, input[type="date" i]:disabled::-webkit-inner-spin-button, input[type="datetime-local" i]:disabled::-webkit-clear-button, input[type="datetime-local" i]:disabled::-webkit-inner-spin-button, input[type="month" i]:disabled::-webkit-clear-button, input[type="month" i]:disabled::-webkit-inner-spin-button, input[type="week" i]:disabled::-webkit-clear-button, input[type="week" i]:disabled::-webkit-inner-spin-button, input:disabled::-webkit-calendar-picker-indicator, input[type="date" i][readonly]::-webkit-clear-button, input[type="date" i][readonly]::-webkit-inner-spin-button, input[type="datetime-local" i][readonly]::-webkit-clear-button, input[type="datetime-local" i][readonly]::-webkit-inner-spin-button, input[type="month" i][readonly]::-webkit-clear-button, input[type="month" i][readonly]::-webkit-inner-spin-button, input[type="week" i][readonly]::-webkit-clear-button, input[type="week" i][readonly]::-webkit-inner-spin-button, input[readonly]::-webkit-calendar-picker-indicator { visibility: hidden; } select { -webkit-appearance: menulist; box-sizing: border-box; align-items: center; border: 1px solid; white-space: pre; -webkit-rtl-ordering: logical; color: black; background-color: white; cursor: default; } select:not(:-internal-list-box) { overflow: visible !important; } select:-internal-list-box { -webkit-appearance: listbox; align-items: flex-start; border: 1px inset gray; border-radius: initial; overflow-x: hidden; overflow-y: scroll; vertical-align: text-bottom; -webkit-user-select: none; white-space: nowrap; } optgroup { font-weight: bolder; display: block; } option { font-weight: normal; display: block; padding: 0 2px 1px 2px; white-space: pre; min-height: 1.2em; } select:-internal-list-box option, select:-internal-list-box optgroup { line-height: initial !important; } select:-internal-list-box:focus option:checked { background-color: -internal-active-list-box-selection !important; color: -internal-active-list-box-selection-text !important; } select:-internal-list-box option:checked { background-color: -internal-inactive-list-box-selection !important; color: -internal-inactive-list-box-selection-text !important; } select:-internal-list-box:disabled option:checked, select:-internal-list-box option:checked:disabled { color: gray !important; } select:-internal-list-box hr { border-style: none; } output { display: inline; } /* meter */ meter { -webkit-appearance: meter; box-sizing: border-box; display: inline-block; height: 1em; width: 5em; vertical-align: -0.2em; } meter::-webkit-meter-inner-element { -webkit-appearance: inherit; box-sizing: inherit; -webkit-user-modify: read-only !important; height: 100%; width: 100%; } meter::-webkit-meter-bar { background: linear-gradient(to bottom, #ddd, #eee 20%, #ccc 45%, #ccc 55%, #ddd); height: 100%; width: 100%; -webkit-user-modify: read-only !important; box-sizing: border-box; } meter::-webkit-meter-optimum-value { background: linear-gradient(to bottom, #ad7, #cea 20%, #7a3 45%, #7a3 55%, #ad7); height: 100%; -webkit-user-modify: read-only !important; box-sizing: border-box; } meter::-webkit-meter-suboptimum-value { background: linear-gradient(to bottom, #fe7, #ffc 20%, #db3 45%, #db3 55%, #fe7); height: 100%; -webkit-user-modify: read-only !important; box-sizing: border-box; } meter::-webkit-meter-even-less-good-value { background: linear-gradient(to bottom, #f77, #fcc 20%, #d44 45%, #d44 55%, #f77); height: 100%; -webkit-user-modify: read-only !important; box-sizing: border-box; } /* progress */ progress { -webkit-appearance: progress-bar; box-sizing: border-box; display: inline-block; height: 1em; width: 10em; vertical-align: -0.2em; } progress::-webkit-progress-inner-element { -webkit-appearance: inherit; box-sizing: inherit; -webkit-user-modify: read-only; height: 100%; width: 100%; } progress::-webkit-progress-bar { background-color: gray; height: 100%; width: 100%; -webkit-user-modify: read-only !important; box-sizing: border-box; } progress::-webkit-progress-value { background-color: green; height: 100%; width: 50%; /* should be removed later */ -webkit-user-modify: read-only !important; box-sizing: border-box; } /* inline elements */ u, ins { text-decoration: underline } strong, b { font-weight: bold } i, cite, em, var, address, dfn { font-style: italic } tt, code, kbd, samp { font-family: monospace } pre, xmp, plaintext, listing { display: block; font-family: monospace; white-space: pre; margin: 1__qem 0 } mark { background-color: yellow; color: black } big { font-size: larger } small { font-size: smaller } s, strike, del { text-decoration: line-through } sub { vertical-align: sub; font-size: smaller } sup { vertical-align: super; font-size: smaller } nobr { white-space: nowrap } /* states */ :focus { outline: auto 5px -webkit-focus-ring-color } /* Read-only text fields do not show a focus ring but do still receive focus */ html:focus, body:focus, input[readonly]:focus { outline: none } applet:focus, embed:focus, iframe:focus, object:focus { outline: none } input:focus, textarea:focus, keygen:focus, select:focus { outline-offset: -2px } input[type="button" i]:focus, input[type="checkbox" i]:focus, input[type="file" i]:focus, input[type="hidden" i]:focus, input[type="image" i]:focus, input[type="radio" i]:focus, input[type="reset" i]:focus, input[type="search" i]:focus, input[type="submit" i]:focus, input[type="file" i]:focus::-webkit-file-upload-button { outline-offset: 0 } a:-webkit-any-link { color: -webkit-link; text-decoration: underline; cursor: auto; } a:-webkit-any-link:active { color: -webkit-activelink } /* HTML5 ruby elements */ ruby, rt { text-indent: 0; /* blocks used for ruby rendering should not trigger this */ } rt { line-height: normal; -webkit-text-emphasis: none; } ruby > rt { display: block; font-size: 50%; text-align: start; } ruby > rp { display: none; } /* other elements */ noframes { display: none } frameset, frame { display: block } frameset { border-color: inherit } iframe { border: 2px inset } details { display: block } summary { display: block } summary::-webkit-details-marker { display: inline-block; width: 0.66em; height: 0.66em; -webkit-margin-end: 0.4em; } template { display: none } bdi, output { unicode-bidi: -webkit-isolate; } bdo { unicode-bidi: bidi-override; } textarea[dir=auto i] { unicode-bidi: -webkit-plaintext; } dialog:not([open]) { display: none } dialog { position: absolute; left: 0; right: 0; width: -webkit-fit-content; height: -webkit-fit-content; margin: auto; border: solid; padding: 1em; background: white; color: black } dialog::backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; background: rgba(0,0,0,0.1) } /* page */ @page { /* FIXME: Define the right default values for page properties. */ size: auto; margin: auto; padding: 0px; border-width: 0px; } /* noscript is handled internally, as it depends on settings. */ `; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/browser/default-stylesheet.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
6,423
```javascript "use strict"; exports.availableDocumentFeatures = [ "FetchExternalResources", "ProcessExternalResources", "MutationEvents", "SkipExternalResources" ]; exports.defaultDocumentFeatures = { FetchExternalResources: ["script", "link"], // omitted by default: "frame" ProcessExternalResources: ["script"], // omitted by default: "frame", "iframe" MutationEvents: "2.0", SkipExternalResources: false }; exports.applyDocumentFeatures = function (doc, features) { features = features || {}; for (let i = 0; i < exports.availableDocumentFeatures.length; ++i) { const featureName = exports.availableDocumentFeatures[i]; let featureSource; if (features[featureName] !== undefined) { featureSource = features[featureName]; // We have to check the lowercase version also because the Document feature // methods convert everything to lowercase. } else if (typeof features[featureName.toLowerCase()] !== "undefined") { featureSource = features[featureName.toLowerCase()]; } else if (exports.defaultDocumentFeatures[featureName]) { featureSource = exports.defaultDocumentFeatures[featureName]; } else { continue; } doc.implementation._removeFeature(featureName); if (featureSource !== undefined) { if (Array.isArray(featureSource)) { for (let j = 0; j < featureSource.length; ++j) { doc.implementation._addFeature(featureName, featureSource[j]); } } else { doc.implementation._addFeature(featureName, featureSource); } } } }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/browser/documentfeatures.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
343
```javascript "use strict"; module.exports = function (nameForErrorMessage, window) { if (!window) { // Do nothing for window-less documents. return; } window._virtualConsole.emit("jsdomError", new Error(`Not implemented: ${nameForErrorMessage}`)); }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/browser/not-implemented.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
60
```javascript "use strict"; const parse5 = require("parse5"); const documentAdapter = require("./documentAdapter"); const NODE_TYPE = require("../living/node-type"); const serializer = new parse5.TreeSerializer(documentAdapter); exports.domToHtml = function (iterable) { let ret = ""; for (const node of iterable) { if (node.nodeType === NODE_TYPE.DOCUMENT_NODE) { ret += serializer.serialize(node); } else { ret += serializer.serialize({ childNodes: [node] }); } } return ret; }; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/browser/domtohtml.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
114
```javascript "use strict"; const parse5 = require("parse5"); const sax = require("sax"); const attributes = require("../living/attributes"); const createDocumentTypeInternal = require("../living/document-type").create; const locationInfo = require("../living/helpers/internal-constants").locationInfo; class HtmlToDom { constructor(core, parser, parsingMode) { if (!parser) { if (parsingMode === "xml") { parser = sax; } else { parser = parse5; } } this.core = core; this.parser = parser; this.parsingMode = parsingMode; if (parser.DefaultHandler) { this.parserType = "htmlparser2"; } else if (parser.Parser && parser.TreeAdapters) { this.parserType = "parse5v1"; } else if (parser.moduleName === "HTML5") { this.parserType = "html5"; } else if (parser.parser) { this.parserType = "sax"; } } appendHtmlToElement(html, element) { if (typeof html !== "string") { html = String(html); } return this["_parseWith" + this.parserType](html, true, element); } appendHtmlToDocument(html, element) { if (typeof html !== "string") { html = String(html); } return this["_parseWith" + this.parserType](html, false, element); } _parseWithhtmlparser2(html, fragment, element) { const handler = new this.parser.DefaultHandler(); // Check if document is XML const isXML = this.parsingMode === "xml"; const parserInstance = new this.parser.Parser(handler, { xmlMode: isXML, lowerCaseTags: !isXML, lowerCaseAttributeNames: !isXML, decodeEntities: true }); parserInstance.includeLocation = false; parserInstance.parseComplete(html); const parsed = handler.dom; for (let i = 0; i < parsed.length; i++) { setChild(this.core, element, parsed[i]); } return element; } _parseWithparse5v1(html, fragment, element) { if (this.parsingMode === "xml") { throw new Error("Can't parse XML with parse5, please use htmlparser2 instead."); } const htmlparser2Adapter = this.parser.TreeAdapters.htmlparser2; let dom; if (fragment) { const instance = new this.parser.Parser(htmlparser2Adapter); const parentElement = htmlparser2Adapter.createElement(element.tagName.toLowerCase(), element.namespaceURI, []); dom = instance.parseFragment(html, parentElement); } else { const instance = new this.parser.Parser(htmlparser2Adapter, { locationInfo: true }); dom = instance.parse(html); } const parsed = dom.children; for (let i = 0; i < parsed.length; i++) { setChild(this.core, element, parsed[i]); } return element; } _parseWithhtml5(html, fragment, element) { if (element.nodeType === 9) { new this.parser.Parser({ document: element }).parse(html); } else { const p = new this.parser.Parser({ document: element.ownerDocument }); p.parse_fragment(html, element); } } _parseWithsax(html, fragment, element) { const SaxParser = this.parser.parser; const parser = new SaxParser(false, { xmlns: true }); parser.looseCase = "toString"; const openStack = [element]; parser.ontext = text => { setChild(this.core, openStack[openStack.length - 1], { type: "text", data: text }); }; parser.onopentag = arg => { const attrValues = {}; const attrPrefixes = {}; const attrNamespaces = {}; Object.keys(arg.attributes).forEach(key => { const localName = arg.attributes[key].local; attrValues[localName] = arg.attributes[key].value; attrPrefixes[localName] = arg.attributes[key].prefix || null; attrNamespaces[localName] = arg.attributes[key].uri || null; }); if (arg.local === "script" && arg.uri === "path_to_url") { openStack.push({ type: "tag", name: arg.local, prefix: arg.prefix, namespace: arg.uri, attribs: attrValues, "x-attribsPrefix": attrPrefixes, "x-attribsNamespace": attrNamespaces }); } else { const elem = setChild(this.core, openStack[openStack.length - 1], { type: "tag", name: arg.local, prefix: arg.prefix, namespace: arg.uri, attribs: attrValues, "x-attribsPrefix": attrPrefixes, "x-attribsNamespace": attrNamespaces }); openStack.push(elem); } }; parser.onclosetag = () => { const elem = openStack.pop(); if (elem.constructor.name === "Object") { // we have an empty script tag setChild(this.core, openStack[openStack.length - 1], elem); } }; parser.onscript = scriptText => { const tag = openStack.pop(); tag.children = [{ type: "text", data: scriptText }]; const elem = setChild(this.core, openStack[openStack.length - 1], tag); openStack.push(elem); }; parser.oncomment = comment => { setChild(this.core, openStack[openStack.length - 1], { type: "comment", data: comment }); }; parser.onprocessinginstruction = pi => { setChild(this.core, openStack[openStack.length - 1], { type: "directive", name: "?" + pi.name, data: "?" + pi.name + " " + pi.body + "?" }); }; parser.ondoctype = dt => { setChild(this.core, openStack[openStack.length - 1], { type: "directive", name: "!doctype", data: "!doctype " + dt }); }; parser.write(html).close(); } } // utility function for forgiving parser function setChild(core, parent, node) { const currentDocument = parent._ownerDocument || parent; let newNode; let isTemplateContents = false; switch (node.type) { case "tag": case "script": case "style": newNode = currentDocument._createElementWithCorrectElementInterface(node.name, node.namespace); newNode._localName = node.name; newNode._prefix = node.prefix || null; newNode._namespaceURI = node.namespace || null; break; case "root": // If we are in <template> then add all children to the parent's _templateContents; skip this virtual root node. if (parent.tagName === "TEMPLATE" && parent._namespaceURI === "path_to_url") { newNode = parent._templateContents; isTemplateContents = true; } break; case "text": // HTML entities should already be decoded by the parser, so no need to decode them newNode = currentDocument.createTextNode(node.data); break; case "comment": newNode = currentDocument.createComment(node.data); break; case "directive": if (node.name[0] === "?" && node.name.toLowerCase() !== "?xml") { const data = node.data.slice(node.name.length + 1, -1); newNode = currentDocument.createProcessingInstruction(node.name.substring(1), data); } else if (node.name.toLowerCase() === "!doctype") { if (node["x-name"] !== undefined) { // parse5 supports doctypes directly newNode = createDocumentTypeInternal(core, currentDocument, node["x-name"] || "", node["x-publicId"] || "", node["x-systemId"] || ""); } else { newNode = parseDocType(core, currentDocument, "<" + node.data + ">"); } } break; } if (!newNode) { return null; } newNode[locationInfo] = node.__location; if (node.attribs) { for (let localName in node.attribs) { const value = node.attribs[localName]; let prefix = node["x-attribsPrefix"] && node["x-attribsPrefix"][localName] || null; const namespace = node["x-attribsNamespace"] && node["x-attribsNamespace"][localName] || null; if (prefix === "xmlns" && localName === "") { // intended weirdness in node-sax, see path_to_url localName = prefix; prefix = null; } attributes.setAttributeValue(newNode, localName, value, prefix, namespace); } } if (node.children) { for (let c = 0; c < node.children.length; c++) { setChild(core, newNode, node.children[c]); } } if (!isTemplateContents) { if (parent._templateContents) { // Setting innerHTML on a <template> parent._templateContents.appendChild(newNode); } else { parent.appendChild(newNode); } } return newNode; } const HTML5_DOCTYPE = /<!doctype html>/i; const PUBLIC_DOCTYPE = /<!doctype\s+([^\s]+)\s+public\s+"([^"]+)"\s+"([^"]+)"/i; const SYSTEM_DOCTYPE = /<!doctype\s+([^\s]+)\s+system\s+"([^"]+)"/i; function parseDocType(core, doc, html) { if (HTML5_DOCTYPE.test(html)) { return createDocumentTypeInternal(core, doc, "html", "", ""); } const publicPieces = PUBLIC_DOCTYPE.exec(html); if (publicPieces) { return createDocumentTypeInternal(core, doc, publicPieces[1], publicPieces[2], publicPieces[3]); } const systemPieces = SYSTEM_DOCTYPE.exec(html); if (systemPieces) { return createDocumentTypeInternal(core, doc, systemPieces[1], "", systemPieces[2]); } // Shouldn't get here (the parser shouldn't let us know about invalid doctypes), but our logic likely isn't // real-world perfect, so let's fallback. return createDocumentTypeInternal(core, doc, "html", "", ""); } exports.HtmlToDom = HtmlToDom; ```
/content/code_sandbox/node_modules/jsdom/lib/jsdom/browser/htmltodom.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,302
```javascript // Acorn is a tiny, fast JavaScript parser written in JavaScript. // // Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and // various contributors and released under an MIT license. // // Git repositories for Acorn are available at // // path_to_url // path_to_url // // Please use the [github bug tracker][ghbt] to report issues. // // [ghbt]: path_to_url // // This file defines the main parser interface. The library also comes // with a [error-tolerant parser][dammit] and an // [abstract syntax tree walker][walk], defined in other files. // // [dammit]: acorn_loose.js // [walk]: util/walk.js import {Parser} from "./state" import "./parseutil" import "./statement" import "./lval" import "./expression" import "./location" export {Parser, plugins} from "./state" export {defaultOptions} from "./options" export {Position, SourceLocation, getLineInfo} from "./locutil" export {Node} from "./node" export {TokenType, types as tokTypes} from "./tokentype" export {TokContext, types as tokContexts} from "./tokencontext" export {isIdentifierChar, isIdentifierStart} from "./identifier" export {Token} from "./tokenize" export {isNewLine, lineBreak, lineBreakG} from "./whitespace" export const version = "2.7.0" // The main exported interface (under `self.acorn` when in the // browser) is a `parse` function that takes a code string and // returns an abstract syntax tree as specified by [Mozilla parser // API][api]. // // [api]: path_to_url export function parse(input, options) { return new Parser(options, input).parse() } // This function tries to parse a single expression at a given // offset in a string. Useful for parsing mixed-language formats // that embed JavaScript expressions. export function parseExpressionAt(input, pos, options) { let p = new Parser(options, input, pos) p.nextToken() return p.parseExpression() } // Acorn is organized as a tokenizer and a recursive-descent parser. // The `tokenizer` export provides an interface to the tokenizer. export function tokenizer(input, options) { return new Parser(options, input) } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
509
```javascript // ## Token types // The assignment of fine-grained, information-carrying type objects // allows the tokenizer to store the information it has about a // token in a way that is very cheap for the parser to look up. // All token type variables start with an underscore, to make them // easy to recognize. // The `beforeExpr` property is used to disambiguate between regular // expressions and divisions. It is set on all token types that can // be followed by an expression (thus, a slash after them would be a // regular expression). // // The `startsExpr` property is used to check if the token ends a // `yield` expression. It is set on all token types that either can // directly start an expression (like a quotation mark) or can // continue an expression (like the body of a string). // // `isLoop` marks a keyword as starting a loop, which is important // to know when parsing a label, in order to allow or disallow // continue jumps to that label. export class TokenType { constructor(label, conf = {}) { this.label = label this.keyword = conf.keyword this.beforeExpr = !!conf.beforeExpr this.startsExpr = !!conf.startsExpr this.isLoop = !!conf.isLoop this.isAssign = !!conf.isAssign this.prefix = !!conf.prefix this.postfix = !!conf.postfix this.binop = conf.binop || null this.updateContext = null } } function binop(name, prec) { return new TokenType(name, {beforeExpr: true, binop: prec}) } const beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true} export const types = { num: new TokenType("num", startsExpr), regexp: new TokenType("regexp", startsExpr), string: new TokenType("string", startsExpr), name: new TokenType("name", startsExpr), eof: new TokenType("eof"), // Punctuation token types. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), bracketR: new TokenType("]"), braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), braceR: new TokenType("}"), parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), parenR: new TokenType(")"), comma: new TokenType(",", beforeExpr), semi: new TokenType(";", beforeExpr), colon: new TokenType(":", beforeExpr), dot: new TokenType("."), question: new TokenType("?", beforeExpr), arrow: new TokenType("=>", beforeExpr), template: new TokenType("template"), ellipsis: new TokenType("...", beforeExpr), backQuote: new TokenType("`", startsExpr), dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), // Operators. These carry several kinds of properties to help the // parser use them properly (the presence of these properties is // what categorizes them as operators). // // `binop`, when present, specifies that this operator is a binary // operator, and will refer to its precedence. // // `prefix` and `postfix` mark the operator as a prefix or postfix // unary operator. // // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as // binary operators with a very low precedence, that should result // in AssignmentExpression nodes. eq: new TokenType("=", {beforeExpr: true, isAssign: true}), assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), prefix: new TokenType("prefix", {beforeExpr: true, prefix: true, startsExpr: true}), logicalOR: binop("||", 1), logicalAND: binop("&&", 2), bitwiseOR: binop("|", 3), bitwiseXOR: binop("^", 4), bitwiseAND: binop("&", 5), equality: binop("==/!=", 6), relational: binop("</>", 7), bitShift: binop("<</>>", 8), plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), modulo: binop("%", 10), star: binop("*", 10), slash: binop("/", 10) } // Map keyword names to token types. export const keywords = {} // Succinct definitions of keyword token types function kw(name, options = {}) { options.keyword = name keywords[name] = types["_" + name] = new TokenType(name, options) } kw("break") kw("case", beforeExpr) kw("catch") kw("continue") kw("debugger") kw("default", beforeExpr) kw("do", {isLoop: true, beforeExpr: true}) kw("else", beforeExpr) kw("finally") kw("for", {isLoop: true}) kw("function", startsExpr) kw("if") kw("return", beforeExpr) kw("switch") kw("throw", beforeExpr) kw("try") kw("var") kw("let") kw("const") kw("while", {isLoop: true}) kw("with") kw("new", {beforeExpr: true, startsExpr: true}) kw("this", startsExpr) kw("super", startsExpr) kw("class") kw("extends", beforeExpr) kw("export") kw("import") kw("yield", {beforeExpr: true, startsExpr: true}) kw("null", startsExpr) kw("true", startsExpr) kw("false", startsExpr) kw("in", {beforeExpr: true, binop: 7}) kw("instanceof", {beforeExpr: true, binop: 7}) kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}) kw("void", {beforeExpr: true, prefix: true, startsExpr: true}) kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/tokentype.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,365
```javascript // The algorithm used to determine whether a regexp can appear at a // given point in the program is loosely based on sweet.js' approach. // See path_to_url import {Parser} from "./state" import {types as tt} from "./tokentype" import {lineBreak} from "./whitespace" export class TokContext { constructor(token, isExpr, preserveSpace, override) { this.token = token this.isExpr = !!isExpr this.preserveSpace = !!preserveSpace this.override = override } } export const types = { b_stat: new TokContext("{", false), b_expr: new TokContext("{", true), b_tmpl: new TokContext("${", true), p_stat: new TokContext("(", false), p_expr: new TokContext("(", true), q_tmpl: new TokContext("`", true, true, p => p.readTmplToken()), f_expr: new TokContext("function", true) } const pp = Parser.prototype pp.initialContext = function() { return [types.b_stat] } pp.braceIsBlock = function(prevType) { if (prevType === tt.colon) { let parent = this.curContext() if (parent === types.b_stat || parent === types.b_expr) return !parent.isExpr } if (prevType === tt._return) return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR) return true if (prevType == tt.braceL) return this.curContext() === types.b_stat return !this.exprAllowed } pp.updateContext = function(prevType) { let update, type = this.type if (type.keyword && prevType == tt.dot) this.exprAllowed = false else if (update = type.updateContext) update.call(this, prevType) else this.exprAllowed = type.beforeExpr } // Token-specific context update code tt.parenR.updateContext = tt.braceR.updateContext = function() { if (this.context.length == 1) { this.exprAllowed = true return } let out = this.context.pop() if (out === types.b_stat && this.curContext() === types.f_expr) { this.context.pop() this.exprAllowed = false } else if (out === types.b_tmpl) { this.exprAllowed = true } else { this.exprAllowed = !out.isExpr } } tt.braceL.updateContext = function(prevType) { this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr) this.exprAllowed = true } tt.dollarBraceL.updateContext = function() { this.context.push(types.b_tmpl) this.exprAllowed = true } tt.parenL.updateContext = function(prevType) { let statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while this.context.push(statementParens ? types.p_stat : types.p_expr) this.exprAllowed = true } tt.incDec.updateContext = function() { // tokExprAllowed stays unchanged } tt._function.updateContext = function() { if (this.curContext() !== types.b_stat) this.context.push(types.f_expr) this.exprAllowed = false } tt.backQuote.updateContext = function() { if (this.curContext() === types.q_tmpl) this.context.pop() else this.context.push(types.q_tmpl) this.exprAllowed = false } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/tokencontext.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
815
```javascript import {types as tt} from "./tokentype" import {Parser} from "./state" import {has} from "./util" const pp = Parser.prototype // Convert existing expression atom to assignable pattern // if possible. pp.toAssignable = function(node, isBinding) { if (this.options.ecmaVersion >= 6 && node) { switch (node.type) { case "Identifier": case "ObjectPattern": case "ArrayPattern": break case "ObjectExpression": node.type = "ObjectPattern" for (let i = 0; i < node.properties.length; i++) { let prop = node.properties[i] if (prop.kind !== "init") this.raise(prop.key.start, "Object pattern can't contain getter or setter") this.toAssignable(prop.value, isBinding) } break case "ArrayExpression": node.type = "ArrayPattern" this.toAssignableList(node.elements, isBinding) break case "AssignmentExpression": if (node.operator === "=") { node.type = "AssignmentPattern" delete node.operator // falls through to AssignmentPattern } else { this.raise(node.left.end, "Only '=' operator can be used for specifying default value.") break; } case "AssignmentPattern": if (node.right.type === "YieldExpression") this.raise(node.right.start, "Yield expression cannot be a default value") break; case "ParenthesizedExpression": node.expression = this.toAssignable(node.expression, isBinding) break case "MemberExpression": if (!isBinding) break default: this.raise(node.start, "Assigning to rvalue") } } return node } // Convert list of expression atoms to binding list. pp.toAssignableList = function(exprList, isBinding) { let end = exprList.length if (end) { let last = exprList[end - 1] if (last && last.type == "RestElement") { --end } else if (last && last.type == "SpreadElement") { last.type = "RestElement" let arg = last.argument this.toAssignable(arg, isBinding) if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") this.unexpected(arg.start) --end } if (isBinding && last.type === "RestElement" && last.argument.type !== "Identifier") this.unexpected(last.argument.start); } for (let i = 0; i < end; i++) { let elt = exprList[i] if (elt) this.toAssignable(elt, isBinding) } return exprList } // Parses spread element. pp.parseSpread = function(refDestructuringErrors) { let node = this.startNode() this.next() node.argument = this.parseMaybeAssign(refDestructuringErrors) return this.finishNode(node, "SpreadElement") } pp.parseRest = function(allowNonIdent) { let node = this.startNode() this.next() // RestElement inside of a function parameter must be an identifier if (allowNonIdent) node.argument = this.type === tt.name ? this.parseIdent() : this.unexpected() else node.argument = this.type === tt.name || this.type === tt.bracketL ? this.parseBindingAtom() : this.unexpected() return this.finishNode(node, "RestElement") } // Parses lvalue (assignable) atom. pp.parseBindingAtom = function() { if (this.options.ecmaVersion < 6) return this.parseIdent() switch (this.type) { case tt.name: return this.parseIdent() case tt.bracketL: let node = this.startNode() this.next() node.elements = this.parseBindingList(tt.bracketR, true, true) return this.finishNode(node, "ArrayPattern") case tt.braceL: return this.parseObj(true) default: this.unexpected() } } pp.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowNonIdent) { let elts = [], first = true while (!this.eat(close)) { if (first) first = false else this.expect(tt.comma) if (allowEmpty && this.type === tt.comma) { elts.push(null) } else if (allowTrailingComma && this.afterTrailingComma(close)) { break } else if (this.type === tt.ellipsis) { let rest = this.parseRest(allowNonIdent) this.parseBindingListItem(rest) elts.push(rest) this.expect(close) break } else { let elem = this.parseMaybeDefault(this.start, this.startLoc) this.parseBindingListItem(elem) elts.push(elem) } } return elts } pp.parseBindingListItem = function(param) { return param } // Parses assignment pattern around given atom if possible. pp.parseMaybeDefault = function(startPos, startLoc, left) { left = left || this.parseBindingAtom() if (this.options.ecmaVersion < 6 || !this.eat(tt.eq)) return left let node = this.startNodeAt(startPos, startLoc) node.left = left node.right = this.parseMaybeAssign() return this.finishNode(node, "AssignmentPattern") } // Verify that a node is an lval something that can be assigned // to. pp.checkLVal = function(expr, isBinding, checkClashes) { switch (expr.type) { case "Identifier": if (this.strict && this.reservedWordsStrictBind.test(expr.name)) this.raise(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode") if (checkClashes) { if (has(checkClashes, expr.name)) this.raise(expr.start, "Argument name clash") checkClashes[expr.name] = true } break case "MemberExpression": if (isBinding) this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression") break case "ObjectPattern": for (let i = 0; i < expr.properties.length; i++) this.checkLVal(expr.properties[i].value, isBinding, checkClashes) break case "ArrayPattern": for (let i = 0; i < expr.elements.length; i++) { let elem = expr.elements[i] if (elem) this.checkLVal(elem, isBinding, checkClashes) } break case "AssignmentPattern": this.checkLVal(expr.left, isBinding, checkClashes) break case "RestElement": this.checkLVal(expr.argument, isBinding, checkClashes) break case "ParenthesizedExpression": this.checkLVal(expr.expression, isBinding, checkClashes) break default: this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue") } } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/lval.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,553
```javascript import {Parser} from "./state" import {Position, getLineInfo} from "./locutil" const pp = Parser.prototype // This function is used to raise exceptions on parse errors. It // takes an offset integer (into the current `input`) to indicate // the location of the error, attaches the position to the end // of the error message, and then raises a `SyntaxError` with that // message. pp.raise = function(pos, message) { let loc = getLineInfo(this.input, pos) message += " (" + loc.line + ":" + loc.column + ")" let err = new SyntaxError(message) err.pos = pos; err.loc = loc; err.raisedAt = this.pos throw err } pp.curPosition = function() { if (this.options.locations) { return new Position(this.curLine, this.pos - this.lineStart) } } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/location.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
193
```javascript import {Parser} from "./state" import {SourceLocation} from "./locutil" export class Node { constructor(parser, pos, loc) { this.type = "" this.start = pos this.end = 0 if (parser.options.locations) this.loc = new SourceLocation(parser, loc) if (parser.options.directSourceFile) this.sourceFile = parser.options.directSourceFile if (parser.options.ranges) this.range = [pos, 0] } } // Start an AST node, attaching a start offset. const pp = Parser.prototype pp.startNode = function() { return new Node(this, this.start, this.startLoc) } pp.startNodeAt = function(pos, loc) { return new Node(this, pos, loc) } // Finish an AST node, adding `type` and `end` properties. function finishNodeAt(node, type, pos, loc) { node.type = type node.end = pos if (this.options.locations) node.loc.end = loc if (this.options.ranges) node.range[1] = pos return node } pp.finishNode = function(node, type) { return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) } // Finish node at given position pp.finishNodeAt = function(node, type, pos, loc) { return finishNodeAt.call(this, node, type, pos, loc) } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/node.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
319
```javascript import {types as tt} from "./tokentype" import {Parser} from "./state" import {lineBreak} from "./whitespace" const pp = Parser.prototype // ### Statement parsing // Parse a program. Initializes the parser, reads any number of // statements, and wraps them in a Program node. Optionally takes a // `program` argument. If present, the statements will be appended // to its body instead of creating a new node. pp.parseTopLevel = function(node) { let first = true if (!node.body) node.body = [] while (this.type !== tt.eof) { let stmt = this.parseStatement(true, true) node.body.push(stmt) if (first) { if (this.isUseStrict(stmt)) this.setStrict(true) first = false } } this.next() if (this.options.ecmaVersion >= 6) { node.sourceType = this.options.sourceType } return this.finishNode(node, "Program") } const loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"} // Parse a single statement. // // If expecting a statement and finding a slash operator, parse a // regular expression literal. This is to handle cases like // `if (foo) /blah/.exec(foo)`, where looking at the previous token // does not help. pp.parseStatement = function(declaration, topLevel) { let starttype = this.type, node = this.startNode() // Most types of statements are recognized by the keyword they // start with. Many are trivial to parse, some require a bit of // complexity. switch (starttype) { case tt._break: case tt._continue: return this.parseBreakContinueStatement(node, starttype.keyword) case tt._debugger: return this.parseDebuggerStatement(node) case tt._do: return this.parseDoStatement(node) case tt._for: return this.parseForStatement(node) case tt._function: if (!declaration && this.options.ecmaVersion >= 6) this.unexpected() return this.parseFunctionStatement(node) case tt._class: if (!declaration) this.unexpected() return this.parseClass(node, true) case tt._if: return this.parseIfStatement(node) case tt._return: return this.parseReturnStatement(node) case tt._switch: return this.parseSwitchStatement(node) case tt._throw: return this.parseThrowStatement(node) case tt._try: return this.parseTryStatement(node) case tt._let: case tt._const: if (!declaration) this.unexpected() // NOTE: falls through to _var case tt._var: return this.parseVarStatement(node, starttype) case tt._while: return this.parseWhileStatement(node) case tt._with: return this.parseWithStatement(node) case tt.braceL: return this.parseBlock() case tt.semi: return this.parseEmptyStatement(node) case tt._export: case tt._import: if (!this.options.allowImportExportEverywhere) { if (!topLevel) this.raise(this.start, "'import' and 'export' may only appear at the top level") if (!this.inModule) this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'") } return starttype === tt._import ? this.parseImport(node) : this.parseExport(node) // If the statement does not start with a statement keyword or a // brace, it's an ExpressionStatement or LabeledStatement. We // simply start parsing an expression, and afterwards, if the // next token is a colon and the expression was a simple // Identifier node, we switch to interpreting it as a label. default: let maybeName = this.value, expr = this.parseExpression() if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon)) return this.parseLabeledStatement(node, maybeName, expr) else return this.parseExpressionStatement(node, expr) } } pp.parseBreakContinueStatement = function(node, keyword) { let isBreak = keyword == "break" this.next() if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null else if (this.type !== tt.name) this.unexpected() else { node.label = this.parseIdent() this.semicolon() } // Verify that there is an actual destination to break or // continue to. for (var i = 0; i < this.labels.length; ++i) { let lab = this.labels[i] if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) break if (node.label && isBreak) break } } if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword) return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") } pp.parseDebuggerStatement = function(node) { this.next() this.semicolon() return this.finishNode(node, "DebuggerStatement") } pp.parseDoStatement = function(node) { this.next() this.labels.push(loopLabel) node.body = this.parseStatement(false) this.labels.pop() this.expect(tt._while) node.test = this.parseParenExpression() if (this.options.ecmaVersion >= 6) this.eat(tt.semi) else this.semicolon() return this.finishNode(node, "DoWhileStatement") } // Disambiguating between a `for` and a `for`/`in` or `for`/`of` // loop is non-trivial. Basically, we have to parse the init `var` // statement or expression, disallowing the `in` operator (see // the second parameter to `parseExpression`), and then check // whether the next token is `in` or `of`. When there is no init // part (semicolon immediately after the opening parenthesis), it // is a regular `for` loop. pp.parseForStatement = function(node) { this.next() this.labels.push(loopLabel) this.expect(tt.parenL) if (this.type === tt.semi) return this.parseFor(node, null) if (this.type === tt._var || this.type === tt._let || this.type === tt._const) { let init = this.startNode(), varKind = this.type this.next() this.parseVar(init, true, varKind) this.finishNode(init, "VariableDeclaration") if ((this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init.declarations.length === 1 && !(varKind !== tt._var && init.declarations[0].init)) return this.parseForIn(node, init) return this.parseFor(node, init) } let refDestructuringErrors = {shorthandAssign: 0, trailingComma: 0} let init = this.parseExpression(true, refDestructuringErrors) if (this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) { this.checkPatternErrors(refDestructuringErrors, true) this.toAssignable(init) this.checkLVal(init) return this.parseForIn(node, init) } else { this.checkExpressionErrors(refDestructuringErrors, true) } return this.parseFor(node, init) } pp.parseFunctionStatement = function(node) { this.next() return this.parseFunction(node, true) } pp.parseIfStatement = function(node) { this.next() node.test = this.parseParenExpression() node.consequent = this.parseStatement(false) node.alternate = this.eat(tt._else) ? this.parseStatement(false) : null return this.finishNode(node, "IfStatement") } pp.parseReturnStatement = function(node) { if (!this.inFunction && !this.options.allowReturnOutsideFunction) this.raise(this.start, "'return' outside of function") this.next() // In `return` (and `break`/`continue`), the keywords with // optional arguments, we eagerly look for a semicolon or the // possibility to insert one. if (this.eat(tt.semi) || this.insertSemicolon()) node.argument = null else { node.argument = this.parseExpression(); this.semicolon() } return this.finishNode(node, "ReturnStatement") } pp.parseSwitchStatement = function(node) { this.next() node.discriminant = this.parseParenExpression() node.cases = [] this.expect(tt.braceL) this.labels.push(switchLabel) // Statements under must be grouped (by label) in SwitchCase // nodes. `cur` is used to keep the node that we are currently // adding statements to. for (var cur, sawDefault = false; this.type != tt.braceR;) { if (this.type === tt._case || this.type === tt._default) { let isCase = this.type === tt._case if (cur) this.finishNode(cur, "SwitchCase") node.cases.push(cur = this.startNode()) cur.consequent = [] this.next() if (isCase) { cur.test = this.parseExpression() } else { if (sawDefault) this.raise(this.lastTokStart, "Multiple default clauses") sawDefault = true cur.test = null } this.expect(tt.colon) } else { if (!cur) this.unexpected() cur.consequent.push(this.parseStatement(true)) } } if (cur) this.finishNode(cur, "SwitchCase") this.next() // Closing brace this.labels.pop() return this.finishNode(node, "SwitchStatement") } pp.parseThrowStatement = function(node) { this.next() if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) this.raise(this.lastTokEnd, "Illegal newline after throw") node.argument = this.parseExpression() this.semicolon() return this.finishNode(node, "ThrowStatement") } // Reused empty array added for node fields that are always empty. const empty = [] pp.parseTryStatement = function(node) { this.next() node.block = this.parseBlock() node.handler = null if (this.type === tt._catch) { let clause = this.startNode() this.next() this.expect(tt.parenL) clause.param = this.parseBindingAtom() this.checkLVal(clause.param, true) this.expect(tt.parenR) clause.body = this.parseBlock() node.handler = this.finishNode(clause, "CatchClause") } node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null if (!node.handler && !node.finalizer) this.raise(node.start, "Missing catch or finally clause") return this.finishNode(node, "TryStatement") } pp.parseVarStatement = function(node, kind) { this.next() this.parseVar(node, false, kind) this.semicolon() return this.finishNode(node, "VariableDeclaration") } pp.parseWhileStatement = function(node) { this.next() node.test = this.parseParenExpression() this.labels.push(loopLabel) node.body = this.parseStatement(false) this.labels.pop() return this.finishNode(node, "WhileStatement") } pp.parseWithStatement = function(node) { if (this.strict) this.raise(this.start, "'with' in strict mode") this.next() node.object = this.parseParenExpression() node.body = this.parseStatement(false) return this.finishNode(node, "WithStatement") } pp.parseEmptyStatement = function(node) { this.next() return this.finishNode(node, "EmptyStatement") } pp.parseLabeledStatement = function(node, maybeName, expr) { for (let i = 0; i < this.labels.length; ++i) if (this.labels[i].name === maybeName) this.raise(expr.start, "Label '" + maybeName + "' is already declared") let kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null for (let i = this.labels.length - 1; i >= 0; i--) { let label = this.labels[i] if (label.statementStart == node.start) { label.statementStart = this.start; label.kind = kind; } else break; } this.labels.push({name: maybeName, kind: kind, statementStart: this.start}) node.body = this.parseStatement(true) this.labels.pop() node.label = expr return this.finishNode(node, "LabeledStatement") } pp.parseExpressionStatement = function(node, expr) { node.expression = expr this.semicolon() return this.finishNode(node, "ExpressionStatement") } // Parse a semicolon-enclosed block of statements, handling `"use // strict"` declarations when `allowStrict` is true (used for // function bodies). pp.parseBlock = function(allowStrict) { let node = this.startNode(), first = true, oldStrict node.body = [] this.expect(tt.braceL) while (!this.eat(tt.braceR)) { let stmt = this.parseStatement(true) node.body.push(stmt) if (first && allowStrict && this.isUseStrict(stmt)) { oldStrict = this.strict this.setStrict(this.strict = true) } first = false } if (oldStrict === false) this.setStrict(false) return this.finishNode(node, "BlockStatement") } // Parse a regular `for` loop. The disambiguation code in // `parseStatement` will already have parsed the init statement or // expression. pp.parseFor = function(node, init) { node.init = init this.expect(tt.semi) node.test = this.type === tt.semi ? null : this.parseExpression() this.expect(tt.semi) node.update = this.type === tt.parenR ? null : this.parseExpression() this.expect(tt.parenR) node.body = this.parseStatement(false) this.labels.pop() return this.finishNode(node, "ForStatement") } // Parse a `for`/`in` and `for`/`of` loop, which are almost // same from parser's perspective. pp.parseForIn = function(node, init) { let type = this.type === tt._in ? "ForInStatement" : "ForOfStatement" this.next() node.left = init node.right = this.parseExpression() this.expect(tt.parenR) node.body = this.parseStatement(false) this.labels.pop() return this.finishNode(node, type) } // Parse a list of variable declarations. pp.parseVar = function(node, isFor, kind) { node.declarations = [] node.kind = kind.keyword for (;;) { let decl = this.startNode() this.parseVarId(decl) if (this.eat(tt.eq)) { decl.init = this.parseMaybeAssign(isFor) } else if (kind === tt._const && !(this.type === tt._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { this.unexpected() } else if (decl.id.type != "Identifier" && !(isFor && (this.type === tt._in || this.isContextual("of")))) { this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value") } else { decl.init = null } node.declarations.push(this.finishNode(decl, "VariableDeclarator")) if (!this.eat(tt.comma)) break } return node } pp.parseVarId = function(decl) { decl.id = this.parseBindingAtom() this.checkLVal(decl.id, true) } // Parse a function declaration or literal (depending on the // `isStatement` parameter). pp.parseFunction = function(node, isStatement, allowExpressionBody) { this.initFunction(node) if (this.options.ecmaVersion >= 6) node.generator = this.eat(tt.star) if (isStatement || this.type === tt.name) node.id = this.parseIdent() this.parseFunctionParams(node) this.parseFunctionBody(node, allowExpressionBody) return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression") } pp.parseFunctionParams = function(node) { this.expect(tt.parenL) node.params = this.parseBindingList(tt.parenR, false, false, true) } // Parse a class declaration or literal (depending on the // `isStatement` parameter). pp.parseClass = function(node, isStatement) { this.next() this.parseClassId(node, isStatement) this.parseClassSuper(node) let classBody = this.startNode() let hadConstructor = false classBody.body = [] this.expect(tt.braceL) while (!this.eat(tt.braceR)) { if (this.eat(tt.semi)) continue let method = this.startNode() let isGenerator = this.eat(tt.star) let isMaybeStatic = this.type === tt.name && this.value === "static" this.parsePropertyName(method) method.static = isMaybeStatic && this.type !== tt.parenL if (method.static) { if (isGenerator) this.unexpected() isGenerator = this.eat(tt.star) this.parsePropertyName(method) } method.kind = "method" let isGetSet = false if (!method.computed) { let {key} = method if (!isGenerator && key.type === "Identifier" && this.type !== tt.parenL && (key.name === "get" || key.name === "set")) { isGetSet = true method.kind = key.name key = this.parsePropertyName(method) } if (!method.static && (key.type === "Identifier" && key.name === "constructor" || key.type === "Literal" && key.value === "constructor")) { if (hadConstructor) this.raise(key.start, "Duplicate constructor in the same class") if (isGetSet) this.raise(key.start, "Constructor can't have get/set modifier") if (isGenerator) this.raise(key.start, "Constructor can't be a generator") method.kind = "constructor" hadConstructor = true } } this.parseClassMethod(classBody, method, isGenerator) if (isGetSet) { let paramCount = method.kind === "get" ? 0 : 1 if (method.value.params.length !== paramCount) { let start = method.value.start if (method.kind === "get") this.raise(start, "getter should have no params"); else this.raise(start, "setter should have exactly one param") } if (method.kind === "set" && method.value.params[0].type === "RestElement") this.raise(method.value.params[0].start, "Setter cannot use rest params") } } node.body = this.finishNode(classBody, "ClassBody") return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") } pp.parseClassMethod = function(classBody, method, isGenerator) { method.value = this.parseMethod(isGenerator) classBody.body.push(this.finishNode(method, "MethodDefinition")) } pp.parseClassId = function(node, isStatement) { node.id = this.type === tt.name ? this.parseIdent() : isStatement ? this.unexpected() : null } pp.parseClassSuper = function(node) { node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null } // Parses module export declaration. pp.parseExport = function(node) { this.next() // export * from '...' if (this.eat(tt.star)) { this.expectContextual("from") node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() this.semicolon() return this.finishNode(node, "ExportAllDeclaration") } if (this.eat(tt._default)) { // export default ... let expr = this.parseMaybeAssign() let needsSemi = true if (expr.type == "FunctionExpression" || expr.type == "ClassExpression") { needsSemi = false if (expr.id) { expr.type = expr.type == "FunctionExpression" ? "FunctionDeclaration" : "ClassDeclaration" } } node.declaration = expr if (needsSemi) this.semicolon() return this.finishNode(node, "ExportDefaultDeclaration") } // export var|const|let|function|class ... if (this.shouldParseExportStatement()) { node.declaration = this.parseStatement(true) node.specifiers = [] node.source = null } else { // export { x, y as z } [from '...'] node.declaration = null node.specifiers = this.parseExportSpecifiers() if (this.eatContextual("from")) { node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() } else { // check for keywords used as local names for (let i = 0; i < node.specifiers.length; i++) { if (this.keywords.test(node.specifiers[i].local.name) || this.reservedWords.test(node.specifiers[i].local.name)) { this.unexpected(node.specifiers[i].local.start) } } node.source = null } this.semicolon() } return this.finishNode(node, "ExportNamedDeclaration") } pp.shouldParseExportStatement = function() { return this.type.keyword } // Parses a comma-separated list of module exports. pp.parseExportSpecifiers = function() { let nodes = [], first = true // export { x, y as z } [from '...'] this.expect(tt.braceL) while (!this.eat(tt.braceR)) { if (!first) { this.expect(tt.comma) if (this.afterTrailingComma(tt.braceR)) break } else first = false let node = this.startNode() node.local = this.parseIdent(this.type === tt._default) node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local nodes.push(this.finishNode(node, "ExportSpecifier")) } return nodes } // Parses import declaration. pp.parseImport = function(node) { this.next() // import '...' if (this.type === tt.string) { node.specifiers = empty node.source = this.parseExprAtom() } else { node.specifiers = this.parseImportSpecifiers() this.expectContextual("from") node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected() } this.semicolon() return this.finishNode(node, "ImportDeclaration") } // Parses a comma-separated list of module imports. pp.parseImportSpecifiers = function() { let nodes = [], first = true if (this.type === tt.name) { // import defaultObj, { x, y as z } from '...' let node = this.startNode() node.local = this.parseIdent() this.checkLVal(node.local, true) nodes.push(this.finishNode(node, "ImportDefaultSpecifier")) if (!this.eat(tt.comma)) return nodes } if (this.type === tt.star) { let node = this.startNode() this.next() this.expectContextual("as") node.local = this.parseIdent() this.checkLVal(node.local, true) nodes.push(this.finishNode(node, "ImportNamespaceSpecifier")) return nodes } this.expect(tt.braceL) while (!this.eat(tt.braceR)) { if (!first) { this.expect(tt.comma) if (this.afterTrailingComma(tt.braceR)) break } else first = false let node = this.startNode() node.imported = this.parseIdent(true) if (this.eatContextual("as")) { node.local = this.parseIdent() } else { node.local = node.imported if (this.isKeyword(node.local.name)) this.unexpected(node.local.start) if (this.reservedWordsStrict.test(node.local.name)) this.raise(node.local.start, "The keyword '" + node.local.name + "' is reserved") } this.checkLVal(node.local, true) nodes.push(this.finishNode(node, "ImportSpecifier")) } return nodes } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/statement.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
5,438
```javascript import {types as tt} from "./tokentype" import {Parser} from "./state" import {lineBreak} from "./whitespace" const pp = Parser.prototype // ## Parser utilities // Test whether a statement node is the string literal `"use strict"`. pp.isUseStrict = function(stmt) { return this.options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && stmt.expression.raw.slice(1, -1) === "use strict" } // Predicate that tests whether the next token is of the given // type, and if yes, consumes it as a side effect. pp.eat = function(type) { if (this.type === type) { this.next() return true } else { return false } } // Tests whether parsed token is a contextual keyword. pp.isContextual = function(name) { return this.type === tt.name && this.value === name } // Consumes contextual keyword if possible. pp.eatContextual = function(name) { return this.value === name && this.eat(tt.name) } // Asserts that following token is given contextual keyword. pp.expectContextual = function(name) { if (!this.eatContextual(name)) this.unexpected() } // Test whether a semicolon can be inserted at the current position. pp.canInsertSemicolon = function() { return this.type === tt.eof || this.type === tt.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } pp.insertSemicolon = function() { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon) this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc) return true } } // Consume a semicolon, or, failing that, see if we are allowed to // pretend that there is a semicolon at this position. pp.semicolon = function() { if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected() } pp.afterTrailingComma = function(tokType) { if (this.type == tokType) { if (this.options.onTrailingComma) this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc) this.next() return true } } // Expect a token of a given type. If found, consume it, otherwise, // raise an unexpected token error. pp.expect = function(type) { this.eat(type) || this.unexpected() } // Raise an unexpected token error. pp.unexpected = function(pos) { this.raise(pos != null ? pos : this.start, "Unexpected token") } pp.checkPatternErrors = function(refDestructuringErrors, andThrow) { let pos = refDestructuringErrors && refDestructuringErrors.trailingComma if (!andThrow) return !!pos if (pos) this.raise(pos, "Trailing comma is not permitted in destructuring patterns") } pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { let pos = refDestructuringErrors && refDestructuringErrors.shorthandAssign if (!andThrow) return !!pos if (pos) this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns") } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/parseutil.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
723
```javascript // A recursive descent parser operates by defining functions for all // syntactic elements, and recursively calling those, each function // advancing the input stream and returning an AST node. Precedence // of constructs (for example, the fact that `!x[1]` means `!(x[1])` // instead of `(!x)[1]` is handled by the fact that the parser // function that parses unary prefix operators is called first, and // in turn calls the function that parses `[]` subscripts that // way, it'll receive the node for `x[1]` already parsed, and wraps // *that* in the unary operator node. // // Acorn uses an [operator precedence parser][opp] to handle binary // operator precedence, because it is much more compact than using // the technique outlined above, which uses different, nesting // functions to specify precedence, for all of the ten binary // precedence levels that JavaScript defines. // // [opp]: path_to_url import {types as tt} from "./tokentype" import {Parser} from "./state" const pp = Parser.prototype // Check if property name clashes with already added. // Object/class getters and setters are not allowed to clash // either with each other or with an init property and in // strict mode, init properties are also not allowed to be repeated. pp.checkPropClash = function(prop, propHash) { if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) return let {key} = prop, name switch (key.type) { case "Identifier": name = key.name; break case "Literal": name = String(key.value); break default: return } let {kind} = prop if (this.options.ecmaVersion >= 6) { if (name === "__proto__" && kind === "init") { if (propHash.proto) this.raise(key.start, "Redefinition of __proto__ property"); propHash.proto = true } return } name = "$" + name let other = propHash[name] if (other) { let isGetSet = kind !== "init" if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) this.raise(key.start, "Redefinition of property") } else { other = propHash[name] = { init: false, get: false, set: false } } other[kind] = true } // ### Expression parsing // These nest, from the most general expression type at the top to // 'atomic', nondivisible expression types at the bottom. Most of // the functions will simply let the function(s) below them parse, // and, *if* the syntactic construct they handle is present, wrap // the AST node that the inner parser gave them in another node. // Parse a full expression. The optional arguments are used to // forbid the `in` operator (in for loops initalization expressions) // and provide reference for storing '=' operator inside shorthand // property assignment in contexts where both object expression // and object pattern might appear (so it's possible to raise // delayed syntax error at correct position). pp.parseExpression = function(noIn, refDestructuringErrors) { let startPos = this.start, startLoc = this.startLoc let expr = this.parseMaybeAssign(noIn, refDestructuringErrors) if (this.type === tt.comma) { let node = this.startNodeAt(startPos, startLoc) node.expressions = [expr] while (this.eat(tt.comma)) node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors)) return this.finishNode(node, "SequenceExpression") } return expr } // Parse an assignment expression. This includes applications of // operators like `+=`. pp.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) { if (this.type == tt._yield && this.inGenerator) return this.parseYield() let validateDestructuring = false if (!refDestructuringErrors) { refDestructuringErrors = {shorthandAssign: 0, trailingComma: 0} validateDestructuring = true } let startPos = this.start, startLoc = this.startLoc if (this.type == tt.parenL || this.type == tt.name) this.potentialArrowAt = this.start let left = this.parseMaybeConditional(noIn, refDestructuringErrors) if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc) if (this.type.isAssign) { if (validateDestructuring) this.checkPatternErrors(refDestructuringErrors, true) let node = this.startNodeAt(startPos, startLoc) node.operator = this.value node.left = this.type === tt.eq ? this.toAssignable(left) : left refDestructuringErrors.shorthandAssign = 0 // reset because shorthand default was used correctly this.checkLVal(left) this.next() node.right = this.parseMaybeAssign(noIn) return this.finishNode(node, "AssignmentExpression") } else { if (validateDestructuring) this.checkExpressionErrors(refDestructuringErrors, true) } return left } // Parse a ternary conditional (`?:`) operator. pp.parseMaybeConditional = function(noIn, refDestructuringErrors) { let startPos = this.start, startLoc = this.startLoc let expr = this.parseExprOps(noIn, refDestructuringErrors) if (this.checkExpressionErrors(refDestructuringErrors)) return expr if (this.eat(tt.question)) { let node = this.startNodeAt(startPos, startLoc) node.test = expr node.consequent = this.parseMaybeAssign() this.expect(tt.colon) node.alternate = this.parseMaybeAssign(noIn) return this.finishNode(node, "ConditionalExpression") } return expr } // Start the precedence parser. pp.parseExprOps = function(noIn, refDestructuringErrors) { let startPos = this.start, startLoc = this.startLoc let expr = this.parseMaybeUnary(refDestructuringErrors) if (this.checkExpressionErrors(refDestructuringErrors)) return expr return this.parseExprOp(expr, startPos, startLoc, -1, noIn) } // Parse binary operators with the operator precedence parsing // algorithm. `left` is the left-hand side of the operator. // `minPrec` provides context that allows the function to stop and // defer further parser to one of its callers when it encounters an // operator that has a lower precedence than the set it is parsing. pp.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) { let prec = this.type.binop if (prec != null && (!noIn || this.type !== tt._in)) { if (prec > minPrec) { let node = this.startNodeAt(leftStartPos, leftStartLoc) node.left = left node.operator = this.value let op = this.type this.next() let startPos = this.start, startLoc = this.startLoc node.right = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec, noIn) this.finishNode(node, (op === tt.logicalOR || op === tt.logicalAND) ? "LogicalExpression" : "BinaryExpression") return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn) } } return left } // Parse unary operators, both prefix and postfix. pp.parseMaybeUnary = function(refDestructuringErrors) { if (this.type.prefix) { let node = this.startNode(), update = this.type === tt.incDec node.operator = this.value node.prefix = true this.next() node.argument = this.parseMaybeUnary() this.checkExpressionErrors(refDestructuringErrors, true) if (update) this.checkLVal(node.argument) else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") this.raise(node.start, "Deleting local variable in strict mode") return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression") } let startPos = this.start, startLoc = this.startLoc let expr = this.parseExprSubscripts(refDestructuringErrors) if (this.checkExpressionErrors(refDestructuringErrors)) return expr while (this.type.postfix && !this.canInsertSemicolon()) { let node = this.startNodeAt(startPos, startLoc) node.operator = this.value node.prefix = false node.argument = expr this.checkLVal(expr) this.next() expr = this.finishNode(node, "UpdateExpression") } return expr } // Parse call, dot, and `[]`-subscript expressions. pp.parseExprSubscripts = function(refDestructuringErrors) { let startPos = this.start, startLoc = this.startLoc let expr = this.parseExprAtom(refDestructuringErrors) let skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")"; if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) return expr return this.parseSubscripts(expr, startPos, startLoc) } pp.parseSubscripts = function(base, startPos, startLoc, noCalls) { for (;;) { if (this.eat(tt.dot)) { let node = this.startNodeAt(startPos, startLoc) node.object = base node.property = this.parseIdent(true) node.computed = false base = this.finishNode(node, "MemberExpression") } else if (this.eat(tt.bracketL)) { let node = this.startNodeAt(startPos, startLoc) node.object = base node.property = this.parseExpression() node.computed = true this.expect(tt.bracketR) base = this.finishNode(node, "MemberExpression") } else if (!noCalls && this.eat(tt.parenL)) { let node = this.startNodeAt(startPos, startLoc) node.callee = base node.arguments = this.parseExprList(tt.parenR, false) base = this.finishNode(node, "CallExpression") } else if (this.type === tt.backQuote) { let node = this.startNodeAt(startPos, startLoc) node.tag = base node.quasi = this.parseTemplate() base = this.finishNode(node, "TaggedTemplateExpression") } else { return base } } } // Parse an atomic expression either a single token that is an // expression, an expression started by a keyword like `function` or // `new`, or an expression wrapped in punctuation like `()`, `[]`, // or `{}`. pp.parseExprAtom = function(refDestructuringErrors) { let node, canBeArrow = this.potentialArrowAt == this.start switch (this.type) { case tt._super: if (!this.inFunction) this.raise(this.start, "'super' outside of function or class") case tt._this: let type = this.type === tt._this ? "ThisExpression" : "Super" node = this.startNode() this.next() return this.finishNode(node, type) case tt._yield: if (this.inGenerator) this.unexpected() case tt.name: let startPos = this.start, startLoc = this.startLoc let id = this.parseIdent(this.type !== tt.name) if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id]) return id case tt.regexp: let value = this.value node = this.parseLiteral(value.value) node.regex = {pattern: value.pattern, flags: value.flags} return node case tt.num: case tt.string: return this.parseLiteral(this.value) case tt._null: case tt._true: case tt._false: node = this.startNode() node.value = this.type === tt._null ? null : this.type === tt._true node.raw = this.type.keyword this.next() return this.finishNode(node, "Literal") case tt.parenL: return this.parseParenAndDistinguishExpression(canBeArrow) case tt.bracketL: node = this.startNode() this.next() // check whether this is array comprehension or regular array if (this.options.ecmaVersion >= 7 && this.type === tt._for) { return this.parseComprehension(node, false) } node.elements = this.parseExprList(tt.bracketR, true, true, refDestructuringErrors) return this.finishNode(node, "ArrayExpression") case tt.braceL: return this.parseObj(false, refDestructuringErrors) case tt._function: node = this.startNode() this.next() return this.parseFunction(node, false) case tt._class: return this.parseClass(this.startNode(), false) case tt._new: return this.parseNew() case tt.backQuote: return this.parseTemplate() default: this.unexpected() } } pp.parseLiteral = function(value) { let node = this.startNode() node.value = value node.raw = this.input.slice(this.start, this.end) this.next() return this.finishNode(node, "Literal") } pp.parseParenExpression = function() { this.expect(tt.parenL) let val = this.parseExpression() this.expect(tt.parenR) return val } pp.parseParenAndDistinguishExpression = function(canBeArrow) { let startPos = this.start, startLoc = this.startLoc, val if (this.options.ecmaVersion >= 6) { this.next() if (this.options.ecmaVersion >= 7 && this.type === tt._for) { return this.parseComprehension(this.startNodeAt(startPos, startLoc), true) } let innerStartPos = this.start, innerStartLoc = this.startLoc let exprList = [], first = true let refDestructuringErrors = {shorthandAssign: 0, trailingComma: 0}, spreadStart, innerParenStart while (this.type !== tt.parenR) { first ? first = false : this.expect(tt.comma) if (this.type === tt.ellipsis) { spreadStart = this.start exprList.push(this.parseParenItem(this.parseRest())) break } else { if (this.type === tt.parenL && !innerParenStart) { innerParenStart = this.start } exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)) } } let innerEndPos = this.start, innerEndLoc = this.startLoc this.expect(tt.parenR) if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) { this.checkPatternErrors(refDestructuringErrors, true) if (innerParenStart) this.unexpected(innerParenStart) return this.parseParenArrowList(startPos, startLoc, exprList) } if (!exprList.length) this.unexpected(this.lastTokStart) if (spreadStart) this.unexpected(spreadStart) this.checkExpressionErrors(refDestructuringErrors, true) if (exprList.length > 1) { val = this.startNodeAt(innerStartPos, innerStartLoc) val.expressions = exprList this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc) } else { val = exprList[0] } } else { val = this.parseParenExpression() } if (this.options.preserveParens) { let par = this.startNodeAt(startPos, startLoc) par.expression = val return this.finishNode(par, "ParenthesizedExpression") } else { return val } } pp.parseParenItem = function(item) { return item } pp.parseParenArrowList = function(startPos, startLoc, exprList) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) } // New's precedence is slightly tricky. It must allow its argument to // be a `[]` or dot subscript expression, but not a call at least, // not without wrapping it in parentheses. Thus, it uses the noCalls // argument to parseSubscripts to prevent it from consuming the // argument list. const empty = [] pp.parseNew = function() { let node = this.startNode() let meta = this.parseIdent(true) if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) { node.meta = meta node.property = this.parseIdent(true) if (node.property.name !== "target") this.raise(node.property.start, "The only valid meta property for new is new.target") if (!this.inFunction) this.raise(node.start, "new.target can only be used in functions") return this.finishNode(node, "MetaProperty") } let startPos = this.start, startLoc = this.startLoc node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true) if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, false) else node.arguments = empty return this.finishNode(node, "NewExpression") } // Parse template expression. pp.parseTemplateElement = function() { let elem = this.startNode() elem.value = { raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, '\n'), cooked: this.value } this.next() elem.tail = this.type === tt.backQuote return this.finishNode(elem, "TemplateElement") } pp.parseTemplate = function() { let node = this.startNode() this.next() node.expressions = [] let curElt = this.parseTemplateElement() node.quasis = [curElt] while (!curElt.tail) { this.expect(tt.dollarBraceL) node.expressions.push(this.parseExpression()) this.expect(tt.braceR) node.quasis.push(curElt = this.parseTemplateElement()) } this.next() return this.finishNode(node, "TemplateLiteral") } // Parse an object literal or binding pattern. pp.parseObj = function(isPattern, refDestructuringErrors) { let node = this.startNode(), first = true, propHash = {} node.properties = [] this.next() while (!this.eat(tt.braceR)) { if (!first) { this.expect(tt.comma) if (this.afterTrailingComma(tt.braceR)) break } else first = false let prop = this.startNode(), isGenerator, startPos, startLoc if (this.options.ecmaVersion >= 6) { prop.method = false prop.shorthand = false if (isPattern || refDestructuringErrors) { startPos = this.start startLoc = this.startLoc } if (!isPattern) isGenerator = this.eat(tt.star) } this.parsePropertyName(prop) this.parsePropertyValue(prop, isPattern, isGenerator, startPos, startLoc, refDestructuringErrors) this.checkPropClash(prop, propHash) node.properties.push(this.finishNode(prop, "Property")) } return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") } pp.parsePropertyValue = function(prop, isPattern, isGenerator, startPos, startLoc, refDestructuringErrors) { if (this.eat(tt.colon)) { prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors) prop.kind = "init" } else if (this.options.ecmaVersion >= 6 && this.type === tt.parenL) { if (isPattern) this.unexpected() prop.kind = "init" prop.method = true prop.value = this.parseMethod(isGenerator) } else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type != tt.comma && this.type != tt.braceR)) { if (isGenerator || isPattern) this.unexpected() prop.kind = prop.key.name this.parsePropertyName(prop) prop.value = this.parseMethod(false) let paramCount = prop.kind === "get" ? 0 : 1 if (prop.value.params.length !== paramCount) { let start = prop.value.start if (prop.kind === "get") this.raise(start, "getter should have no params"); else this.raise(start, "setter should have exactly one param") } if (prop.kind === "set" && prop.value.params[0].type === "RestElement") this.raise(prop.value.params[0].start, "Setter cannot use rest params") } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { prop.kind = "init" if (isPattern) { if (this.keywords.test(prop.key.name) || (this.strict ? this.reservedWordsStrictBind : this.reservedWords).test(prop.key.name)) this.raise(prop.key.start, "Binding " + prop.key.name) prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key) } else if (this.type === tt.eq && refDestructuringErrors) { if (!refDestructuringErrors.shorthandAssign) refDestructuringErrors.shorthandAssign = this.start prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key) } else { prop.value = prop.key } prop.shorthand = true } else this.unexpected() } pp.parsePropertyName = function(prop) { if (this.options.ecmaVersion >= 6) { if (this.eat(tt.bracketL)) { prop.computed = true prop.key = this.parseMaybeAssign() this.expect(tt.bracketR) return prop.key } else { prop.computed = false } } return prop.key = (this.type === tt.num || this.type === tt.string) ? this.parseExprAtom() : this.parseIdent(true) } // Initialize empty function node. pp.initFunction = function(node) { node.id = null if (this.options.ecmaVersion >= 6) { node.generator = false node.expression = false } } // Parse object or class method. pp.parseMethod = function(isGenerator) { let node = this.startNode() this.initFunction(node) this.expect(tt.parenL) node.params = this.parseBindingList(tt.parenR, false, false) if (this.options.ecmaVersion >= 6) node.generator = isGenerator this.parseFunctionBody(node, false) return this.finishNode(node, "FunctionExpression") } // Parse arrow function expression with given parameters. pp.parseArrowExpression = function(node, params) { this.initFunction(node) node.params = this.toAssignableList(params, true) this.parseFunctionBody(node, true) return this.finishNode(node, "ArrowFunctionExpression") } // Parse function body and check parameters. pp.parseFunctionBody = function(node, isArrowFunction) { let isExpression = isArrowFunction && this.type !== tt.braceL if (isExpression) { node.body = this.parseMaybeAssign() node.expression = true } else { // Start a new scope with regard to labels and the `inFunction` // flag (restore them to their old value afterwards). let oldInFunc = this.inFunction, oldInGen = this.inGenerator, oldLabels = this.labels this.inFunction = true; this.inGenerator = node.generator; this.labels = [] node.body = this.parseBlock(true) node.expression = false this.inFunction = oldInFunc; this.inGenerator = oldInGen; this.labels = oldLabels } // If this is a strict mode function, verify that argument names // are not repeated, and it does not try to bind the words `eval` // or `arguments`. if (this.strict || !isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) { let oldStrict = this.strict this.strict = true if (node.id) this.checkLVal(node.id, true) this.checkParams(node); this.strict = oldStrict } else if (isArrowFunction) { this.checkParams(node); } } // Checks function params for various disallowed patterns such as using "eval" // or "arguments" and duplicate parameters. pp.checkParams = function(node) { let nameHash = {}; for (let i = 0; i < node.params.length; i++) this.checkLVal(node.params[i], true, nameHash) }; // Parses a comma-separated list of expressions, and returns them as // an array. `close` is the token type that ends the list, and // `allowEmpty` can be turned on to allow subsequent commas with // nothing in between them to be parsed as `null` (which is needed // for array literals). pp.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { let elts = [], first = true while (!this.eat(close)) { if (!first) { this.expect(tt.comma) if (this.type === close && refDestructuringErrors && !refDestructuringErrors.trailingComma) { refDestructuringErrors.trailingComma = this.lastTokStart } if (allowTrailingComma && this.afterTrailingComma(close)) break } else first = false let elt if (allowEmpty && this.type === tt.comma) elt = null else if (this.type === tt.ellipsis) elt = this.parseSpread(refDestructuringErrors) else elt = this.parseMaybeAssign(false, refDestructuringErrors) elts.push(elt) } return elts } // Parse the next token as an identifier. If `liberal` is true (used // when parsing properties), it will also convert keywords into // identifiers. pp.parseIdent = function(liberal) { let node = this.startNode() if (liberal && this.options.allowReserved == "never") liberal = false if (this.type === tt.name) { if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).test(this.value) && (this.options.ecmaVersion >= 6 || this.input.slice(this.start, this.end).indexOf("\\") == -1)) this.raise(this.start, "The keyword '" + this.value + "' is reserved") node.name = this.value } else if (liberal && this.type.keyword) { node.name = this.type.keyword } else { this.unexpected() } this.next() return this.finishNode(node, "Identifier") } // Parses yield expression inside generator. pp.parseYield = function() { let node = this.startNode() this.next() if (this.type == tt.semi || this.canInsertSemicolon() || (this.type != tt.star && !this.type.startsExpr)) { node.delegate = false node.argument = null } else { node.delegate = this.eat(tt.star) node.argument = this.parseMaybeAssign() } return this.finishNode(node, "YieldExpression") } // Parses array and generator comprehensions. pp.parseComprehension = function(node, isGenerator) { node.blocks = [] while (this.type === tt._for) { let block = this.startNode() this.next() this.expect(tt.parenL) block.left = this.parseBindingAtom() this.checkLVal(block.left, true) this.expectContextual("of") block.right = this.parseExpression() this.expect(tt.parenR) node.blocks.push(this.finishNode(block, "ComprehensionBlock")) } node.filter = this.eat(tt._if) ? this.parseParenExpression() : null node.body = this.parseExpression() this.expect(isGenerator ? tt.parenR : tt.bracketR) node.generator = isGenerator return this.finishNode(node, "ComprehensionExpression") } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/expression.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
6,355
```javascript import {reservedWords, keywords} from "./identifier" import {types as tt} from "./tokentype" import {lineBreak} from "./whitespace" import {getOptions} from "./options" // Registered plugins export const plugins = {} function keywordRegexp(words) { return new RegExp("^(" + words.replace(/ /g, "|") + ")$") } export class Parser { constructor(options, input, startPos) { this.options = options = getOptions(options) this.sourceFile = options.sourceFile this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5]) let reserved = options.allowReserved ? "" : reservedWords[options.ecmaVersion] + (options.sourceType == "module" ? " await" : "") this.reservedWords = keywordRegexp(reserved) let reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict this.reservedWordsStrict = keywordRegexp(reservedStrict) this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords.strictBind) this.input = String(input) // Used to signal to callers of `readWord1` whether the word // contained any escape sequences. This is needed because words with // escape sequences must not be interpreted as keywords. this.containsEsc = false; // Load plugins this.loadPlugins(options.plugins) // Set up token state // The current position of the tokenizer in the input. if (startPos) { this.pos = startPos this.lineStart = Math.max(0, this.input.lastIndexOf("\n", startPos)) this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length } else { this.pos = this.lineStart = 0 this.curLine = 1 } // Properties of the current token: // Its type this.type = tt.eof // For tokens that include more information than their type, the value this.value = null // Its start and end offset this.start = this.end = this.pos // And, if locations are used, the {line, column} object // corresponding to those offsets this.startLoc = this.endLoc = this.curPosition() // Position information for the previous token this.lastTokEndLoc = this.lastTokStartLoc = null this.lastTokStart = this.lastTokEnd = this.pos // The context stack is used to superficially track syntactic // context to predict whether a regular expression is allowed in a // given position. this.context = this.initialContext() this.exprAllowed = true // Figure out if it's a module code. this.strict = this.inModule = options.sourceType === "module" // Used to signify the start of a potential arrow function this.potentialArrowAt = -1 // Flags to track whether we are in a function, a generator. this.inFunction = this.inGenerator = false // Labels in scope. this.labels = [] // If enabled, skip leading hashbang line. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === '#!') this.skipLineComment(2) } // DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them isKeyword(word) { return this.keywords.test(word) } isReservedWord(word) { return this.reservedWords.test(word) } extend(name, f) { this[name] = f(this[name]) } loadPlugins(pluginConfigs) { for (let name in pluginConfigs) { let plugin = plugins[name] if (!plugin) throw new Error("Plugin '" + name + "' not found") plugin(this, pluginConfigs[name]) } } parse() { let node = this.options.program || this.startNode() this.nextToken() return this.parseTopLevel(node) } } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/state.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
869
```javascript // This is a trick taken from Esprima. It turns out that, on // non-Chrome browsers, to check whether a string is in a set, a // predicate containing a big ugly `switch` statement is faster than // a regular expression, and on Chrome the two are about on par. // This function uses `eval` (non-lexical) to produce such a // predicate from a space-separated string of words. // // It starts by sorting the words by length. // Reserved word lists for various dialects of the language export const reservedWords = { 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", 5: "class enum extends super const export import", 6: "enum", strict: "implements interface let package private protected public static yield", strictBind: "eval arguments" } // And the keywords var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this" export const keywords = { 5: ecma5AndLessKeywords, 6: ecma5AndLessKeywords + " let const class extends export import yield super" } // ## Character categories // Big ugly regular expressions that match characters in the // whitespace, identifier, and identifier-start categories. These // are only applied when a character is found to actually have a // code point above 128. // Generated by `bin/generate-identifier-regex.js`. let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0-\u08b2\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua7ad\ua7b0\ua7b1\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab5f\uab64\uab65\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc" let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfc-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2d\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f" const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]") const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]") nonASCIIidentifierStartChars = nonASCIIidentifierChars = null // These are a run-length and offset encoded representation of the // >0xffff code points that are a valid part of identifiers. The // offset starts at 0x10000, and each pair of numbers represents an // offset to the next range, and then a size of the range. They were // generated by tools/generate-identifier-regex.js var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,17,26,6,37,11,29,3,35,5,7,2,4,43,157,99,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,98,21,11,25,71,55,7,1,65,0,16,3,2,2,2,26,45,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,955,52,76,44,33,24,27,35,42,34,4,0,13,47,15,3,22,0,38,17,2,24,133,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,32,4,287,47,21,1,2,0,185,46,82,47,21,0,60,42,502,63,32,0,449,56,1288,920,104,110,2962,1070,13266,568,8,30,114,29,19,47,17,3,32,20,6,18,881,68,12,0,67,12,16481,1,3071,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,1340,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,16355,541] var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,1306,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,52,0,13,2,49,13,16,9,83,11,168,11,6,9,8,2,57,0,2,6,3,1,3,2,10,0,11,1,3,6,4,4,316,19,13,9,214,6,3,8,112,16,16,9,82,12,9,9,535,9,20855,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,4305,6,792618,239] // This has a complexity linear to the value of the code. The // assumption is that looking up astral identifier characters is // rare. function isInAstralSet(code, set) { let pos = 0x10000 for (let i = 0; i < set.length; i += 2) { pos += set[i] if (pos > code) return false pos += set[i + 1] if (pos >= code) return true } } // Test whether a given character code starts an identifier. export function isIdentifierStart(code, astral) { if (code < 65) return code === 36 if (code < 91) return true if (code < 97) return code === 95 if (code < 123) return true if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) if (astral === false) return false return isInAstralSet(code, astralIdentifierStartCodes) } // Test whether a given character is part of an identifier. export function isIdentifierChar(code, astral) { if (code < 48) return code === 36 if (code < 58) return true if (code < 65) return false if (code < 91) return true if (code < 97) return code === 95 if (code < 123) return true if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) if (astral === false) return false return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/identifier.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
6,089
```javascript import {has, isArray} from "./util" import {SourceLocation} from "./locutil" // A second optional argument can be given to further configure // the parser process. These options are recognized: export const defaultOptions = { // `ecmaVersion` indicates the ECMAScript version to parse. Must // be either 3, or 5, or 6. This influences support for strict // mode, the set of reserved words, support for getters and // setters and other features. ecmaVersion: 5, // Source type ("script" or "module") for different semantics sourceType: "script", // `onInsertedSemicolon` can be a callback that will be called // when a semicolon is automatically inserted. It will be passed // th position of the comma as an offset, and if `locations` is // enabled, it is given the location as a `{line, column}` object // as second argument. onInsertedSemicolon: null, // `onTrailingComma` is similar to `onInsertedSemicolon`, but for // trailing commas. onTrailingComma: null, // By default, reserved words are only enforced if ecmaVersion >= 5. // Set `allowReserved` to a boolean value to explicitly turn this on // an off. When this option has the value "never", reserved words // and keywords can also not be used as property names. allowReserved: null, // When enabled, a return at the top level is not considered an // error. allowReturnOutsideFunction: false, // When enabled, import/export statements are not constrained to // appearing at the top of the program. allowImportExportEverywhere: false, // When enabled, hashbang directive in the beginning of file // is allowed and treated as a line comment. allowHashBang: false, // When `locations` is on, `loc` properties holding objects with // `start` and `end` properties in `{line, column}` form (with // line being 1-based and column 0-based) will be attached to the // nodes. locations: false, // A function can be passed as `onToken` option, which will // cause Acorn to call that function with object in the same // format as tokens returned from `tokenizer().getToken()`. Note // that you are not allowed to call the parser from the // callbackthat will corrupt its internal state. onToken: null, // A function can be passed as `onComment` option, which will // cause Acorn to call that function with `(block, text, start, // end)` parameters whenever a comment is skipped. `block` is a // boolean indicating whether this is a block (`/* */`) comment, // `text` is the content of the comment, and `start` and `end` are // character offsets that denote the start and end of the comment. // When the `locations` option is on, two more parameters are // passed, the full `{line, column}` locations of the start and // end of the comments. Note that you are not allowed to call the // parser from the callbackthat will corrupt its internal state. onComment: null, // Nodes have their start and end characters offsets recorded in // `start` and `end` properties (directly on the node, rather than // the `loc` object, which holds line/column data. To also add a // [semi-standardized][range] `range` property holding a `[start, // end]` array with the same numbers, set the `ranges` option to // `true`. // // [range]: path_to_url ranges: false, // It is possible to parse multiple files into a single AST by // passing the tree produced by parsing the first file as // `program` option in subsequent parses. This will add the // toplevel forms of the parsed file to the `Program` (top) node // of an existing parse tree. program: null, // When `locations` is on, you can pass this to record the source // file in every node's `loc` object. sourceFile: null, // This value, if given, is stored in every node, whether // `locations` is on or off. directSourceFile: null, // When enabled, parenthesized expressions are represented by // (non-standard) ParenthesizedExpression nodes preserveParens: false, plugins: {} } // Interpret and default an options object export function getOptions(opts) { let options = {} for (let opt in defaultOptions) options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt] if (options.allowReserved == null) options.allowReserved = options.ecmaVersion < 5 if (isArray(options.onToken)) { let tokens = options.onToken options.onToken = (token) => tokens.push(token) } if (isArray(options.onComment)) options.onComment = pushComment(options, options.onComment) return options } function pushComment(options, array) { return function (block, text, start, end, startLoc, endLoc) { let comment = { type: block ? 'Block' : 'Line', value: text, start: start, end: end } if (options.locations) comment.loc = new SourceLocation(this, startLoc, endLoc) if (options.ranges) comment.range = [start, end] array.push(comment) } } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/options.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,262
```javascript import {isIdentifierStart, isIdentifierChar} from "./identifier" import {types as tt, keywords as keywordTypes} from "./tokentype" import {Parser} from "./state" import {SourceLocation} from "./locutil" import {lineBreak, lineBreakG, isNewLine, nonASCIIwhitespace} from "./whitespace" // Object type used to represent tokens. Note that normally, tokens // simply exist as properties on the parser object. This is only // used for the onToken callback and the external tokenizer. export class Token { constructor(p) { this.type = p.type this.value = p.value this.start = p.start this.end = p.end if (p.options.locations) this.loc = new SourceLocation(p, p.startLoc, p.endLoc) if (p.options.ranges) this.range = [p.start, p.end] } } // ## Tokenizer const pp = Parser.prototype // Are we running under Rhino? const isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]" // Move to the next token pp.next = function() { if (this.options.onToken) this.options.onToken(new Token(this)) this.lastTokEnd = this.end this.lastTokStart = this.start this.lastTokEndLoc = this.endLoc this.lastTokStartLoc = this.startLoc this.nextToken() } pp.getToken = function() { this.next() return new Token(this) } // If we're in an ES6 environment, make parsers iterable if (typeof Symbol !== "undefined") pp[Symbol.iterator] = function () { let self = this return {next: function () { let token = self.getToken() return { done: token.type === tt.eof, value: token } }} } // Toggle strict mode. Re-reads the next number or string to please // pedantic tests (`"use strict"; 010;` should fail). pp.setStrict = function(strict) { this.strict = strict if (this.type !== tt.num && this.type !== tt.string) return this.pos = this.start if (this.options.locations) { while (this.pos < this.lineStart) { this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1 --this.curLine } } this.nextToken() } pp.curContext = function() { return this.context[this.context.length - 1] } // Read a single token, updating the parser object's token-related // properties. pp.nextToken = function() { let curContext = this.curContext() if (!curContext || !curContext.preserveSpace) this.skipSpace() this.start = this.pos if (this.options.locations) this.startLoc = this.curPosition() if (this.pos >= this.input.length) return this.finishToken(tt.eof) if (curContext.override) return curContext.override(this) else this.readToken(this.fullCharCodeAtPos()) } pp.readToken = function(code) { // Identifier or keyword. '\uXXXX' sequences are allowed in // identifiers, so '\' also dispatches to that. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) return this.readWord() return this.getTokenFromCode(code) } pp.fullCharCodeAtPos = function() { let code = this.input.charCodeAt(this.pos) if (code <= 0xd7ff || code >= 0xe000) return code let next = this.input.charCodeAt(this.pos + 1) return (code << 10) + next - 0x35fdc00 } pp.skipBlockComment = function() { let startLoc = this.options.onComment && this.curPosition() let start = this.pos, end = this.input.indexOf("*/", this.pos += 2) if (end === -1) this.raise(this.pos - 2, "Unterminated comment") this.pos = end + 2 if (this.options.locations) { lineBreakG.lastIndex = start let match while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { ++this.curLine this.lineStart = match.index + match[0].length } } if (this.options.onComment) this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition()) } pp.skipLineComment = function(startSkip) { let start = this.pos let startLoc = this.options.onComment && this.curPosition() let ch = this.input.charCodeAt(this.pos+=startSkip) while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) { ++this.pos ch = this.input.charCodeAt(this.pos) } if (this.options.onComment) this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition()) } // Called at the start of the parse and after every token. Skips // whitespace and comments, and. pp.skipSpace = function() { loop: while (this.pos < this.input.length) { let ch = this.input.charCodeAt(this.pos) switch (ch) { case 32: case 160: // ' ' ++this.pos break case 13: if (this.input.charCodeAt(this.pos + 1) === 10) { ++this.pos } case 10: case 8232: case 8233: ++this.pos if (this.options.locations) { ++this.curLine this.lineStart = this.pos } break case 47: // '/' switch (this.input.charCodeAt(this.pos + 1)) { case 42: // '*' this.skipBlockComment() break case 47: this.skipLineComment(2) break default: break loop } break default: if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { ++this.pos } else { break loop } } } } // Called at the end of every token. Sets `end`, `val`, and // maintains `context` and `exprAllowed`, and skips the space after // the token, so that the next one's `start` will point at the // right position. pp.finishToken = function(type, val) { this.end = this.pos if (this.options.locations) this.endLoc = this.curPosition() let prevType = this.type this.type = type this.value = val this.updateContext(prevType) } // ### Token reading // This is the function that is called to fetch the next token. It // is somewhat obscure, because it works in character codes rather // than characters, and because operator parsing has been inlined // into it. // // All in the name of speed. // pp.readToken_dot = function() { let next = this.input.charCodeAt(this.pos + 1) if (next >= 48 && next <= 57) return this.readNumber(true) let next2 = this.input.charCodeAt(this.pos + 2) if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' this.pos += 3 return this.finishToken(tt.ellipsis) } else { ++this.pos return this.finishToken(tt.dot) } } pp.readToken_slash = function() { // '/' let next = this.input.charCodeAt(this.pos + 1) if (this.exprAllowed) {++this.pos; return this.readRegexp();} if (next === 61) return this.finishOp(tt.assign, 2) return this.finishOp(tt.slash, 1) } pp.readToken_mult_modulo = function(code) { // '%*' let next = this.input.charCodeAt(this.pos + 1) if (next === 61) return this.finishOp(tt.assign, 2) return this.finishOp(code === 42 ? tt.star : tt.modulo, 1) } pp.readToken_pipe_amp = function(code) { // '|&' let next = this.input.charCodeAt(this.pos + 1) if (next === code) return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2) if (next === 61) return this.finishOp(tt.assign, 2) return this.finishOp(code === 124 ? tt.bitwiseOR : tt.bitwiseAND, 1) } pp.readToken_caret = function() { // '^' let next = this.input.charCodeAt(this.pos + 1) if (next === 61) return this.finishOp(tt.assign, 2) return this.finishOp(tt.bitwiseXOR, 1) } pp.readToken_plus_min = function(code) { // '+-' let next = this.input.charCodeAt(this.pos + 1) if (next === code) { if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 && lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) { // A `-->` line comment this.skipLineComment(3) this.skipSpace() return this.nextToken() } return this.finishOp(tt.incDec, 2) } if (next === 61) return this.finishOp(tt.assign, 2) return this.finishOp(tt.plusMin, 1) } pp.readToken_lt_gt = function(code) { // '<>' let next = this.input.charCodeAt(this.pos + 1) let size = 1 if (next === code) { size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2 if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1) return this.finishOp(tt.bitShift, size) } if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 && this.input.charCodeAt(this.pos + 3) == 45) { if (this.inModule) this.unexpected() // `<!--`, an XML-style comment that should be interpreted as a line comment this.skipLineComment(4) this.skipSpace() return this.nextToken() } if (next === 61) size = this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2 return this.finishOp(tt.relational, size) } pp.readToken_eq_excl = function(code) { // '=!' let next = this.input.charCodeAt(this.pos + 1) if (next === 61) return this.finishOp(tt.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>' this.pos += 2 return this.finishToken(tt.arrow) } return this.finishOp(code === 61 ? tt.eq : tt.prefix, 1) } pp.getTokenFromCode = function(code) { switch (code) { // The interpretation of a dot depends on whether it is followed // by a digit or another two dots. case 46: // '.' return this.readToken_dot() // Punctuation tokens. case 40: ++this.pos; return this.finishToken(tt.parenL) case 41: ++this.pos; return this.finishToken(tt.parenR) case 59: ++this.pos; return this.finishToken(tt.semi) case 44: ++this.pos; return this.finishToken(tt.comma) case 91: ++this.pos; return this.finishToken(tt.bracketL) case 93: ++this.pos; return this.finishToken(tt.bracketR) case 123: ++this.pos; return this.finishToken(tt.braceL) case 125: ++this.pos; return this.finishToken(tt.braceR) case 58: ++this.pos; return this.finishToken(tt.colon) case 63: ++this.pos; return this.finishToken(tt.question) case 96: // '`' if (this.options.ecmaVersion < 6) break ++this.pos return this.finishToken(tt.backQuote) case 48: // '0' let next = this.input.charCodeAt(this.pos + 1) if (next === 120 || next === 88) return this.readRadixNumber(16); // '0x', '0X' - hex number if (this.options.ecmaVersion >= 6) { if (next === 111 || next === 79) return this.readRadixNumber(8); // '0o', '0O' - octal number if (next === 98 || next === 66) return this.readRadixNumber(2); // '0b', '0B' - binary number } // Anything else beginning with a digit is an integer, octal // number, or float. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9 return this.readNumber(false) // Quotes produce strings. case 34: case 39: // '"', "'" return this.readString(code) // Operators are parsed inline in tiny state machines. '=' (61) is // often referred to. `finishOp` simply skips the amount of // characters it is given as second argument, and returns a token // of the type given by its first argument. case 47: // '/' return this.readToken_slash() case 37: case 42: // '%*' return this.readToken_mult_modulo(code) case 124: case 38: // '|&' return this.readToken_pipe_amp(code) case 94: // '^' return this.readToken_caret() case 43: case 45: // '+-' return this.readToken_plus_min(code) case 60: case 62: // '<>' return this.readToken_lt_gt(code) case 61: case 33: // '=!' return this.readToken_eq_excl(code) case 126: // '~' return this.finishOp(tt.prefix, 1) } this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'") } pp.finishOp = function(type, size) { let str = this.input.slice(this.pos, this.pos + size) this.pos += size return this.finishToken(type, str) } // Parse a regular expression. Some context-awareness is necessary, // since a '/' inside a '[]' set does not end the expression. function tryCreateRegexp(src, flags, throwErrorAt, parser) { try { return new RegExp(src, flags); } catch (e) { if (throwErrorAt !== undefined) { if (e instanceof SyntaxError) parser.raise(throwErrorAt, "Error parsing regular expression: " + e.message) throw e } } } var regexpUnicodeSupport = !!tryCreateRegexp("\uffff", "u"); pp.readRegexp = function() { let escaped, inClass, start = this.pos for (;;) { if (this.pos >= this.input.length) this.raise(start, "Unterminated regular expression") let ch = this.input.charAt(this.pos) if (lineBreak.test(ch)) this.raise(start, "Unterminated regular expression") if (!escaped) { if (ch === "[") inClass = true else if (ch === "]" && inClass) inClass = false else if (ch === "/" && !inClass) break escaped = ch === "\\" } else escaped = false ++this.pos } let content = this.input.slice(start, this.pos) ++this.pos // Need to use `readWord1` because '\uXXXX' sequences are allowed // here (don't ask). let mods = this.readWord1() let tmp = content if (mods) { let validFlags = /^[gim]*$/ if (this.options.ecmaVersion >= 6) validFlags = /^[gimuy]*$/ if (!validFlags.test(mods)) this.raise(start, "Invalid regular expression flag") if (mods.indexOf('u') >= 0 && !regexpUnicodeSupport) { // Replace each astral symbol and every Unicode escape sequence that // possibly represents an astral symbol or a paired surrogate with a // single ASCII symbol to avoid throwing on regular expressions that // are only valid in combination with the `/u` flag. // Note: replacing with the ASCII symbol `x` might cause false // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a // perfectly valid pattern that is equivalent to `[a-b]`, but it would // be replaced by `[x-b]` which throws an error. tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, (_match, code, offset) => { code = Number("0x" + code) if (code > 0x10FFFF) this.raise(start + offset + 3, "Code point out of bounds") return "x" }); tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x") } } // Detect invalid regular expressions. let value = null // Rhino's regular expression parser is flaky and throws uncatchable exceptions, // so don't do detection if we are running under Rhino if (!isRhino) { tryCreateRegexp(tmp, undefined, start, this); // Get a regular expression object for this pattern-flag pair, or `null` in // case the current environment doesn't support the flags it uses. value = tryCreateRegexp(content, mods) } return this.finishToken(tt.regexp, {pattern: content, flags: mods, value: value}) } // Read an integer in the given radix. Return null if zero digits // were read, the integer value otherwise. When `len` is given, this // will return `null` unless the integer has exactly `len` digits. pp.readInt = function(radix, len) { let start = this.pos, total = 0 for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) { let code = this.input.charCodeAt(this.pos), val if (code >= 97) val = code - 97 + 10; // a else if (code >= 65) val = code - 65 + 10; // A else if (code >= 48 && code <= 57) val = code - 48; // 0-9 else val = Infinity if (val >= radix) break ++this.pos total = total * radix + val } if (this.pos === start || len != null && this.pos - start !== len) return null return total } pp.readRadixNumber = function(radix) { this.pos += 2; // 0x let val = this.readInt(radix) if (val == null) this.raise(this.start + 2, "Expected number in radix " + radix) if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number") return this.finishToken(tt.num, val) } // Read an integer, octal integer, or floating-point number. pp.readNumber = function(startsWithDot) { let start = this.pos, isFloat = false, octal = this.input.charCodeAt(this.pos) === 48 if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number") let next = this.input.charCodeAt(this.pos) if (next === 46) { // '.' ++this.pos this.readInt(10) isFloat = true next = this.input.charCodeAt(this.pos) } if (next === 69 || next === 101) { // 'eE' next = this.input.charCodeAt(++this.pos) if (next === 43 || next === 45) ++this.pos; // '+-' if (this.readInt(10) === null) this.raise(start, "Invalid number") isFloat = true } if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number") let str = this.input.slice(start, this.pos), val if (isFloat) val = parseFloat(str) else if (!octal || str.length === 1) val = parseInt(str, 10) else if (/[89]/.test(str) || this.strict) this.raise(start, "Invalid number") else val = parseInt(str, 8) return this.finishToken(tt.num, val) } // Read a string value, interpreting backslash-escapes. pp.readCodePoint = function() { let ch = this.input.charCodeAt(this.pos), code if (ch === 123) { if (this.options.ecmaVersion < 6) this.unexpected() let codePos = ++this.pos code = this.readHexChar(this.input.indexOf('}', this.pos) - this.pos) ++this.pos if (code > 0x10FFFF) this.raise(codePos, "Code point out of bounds") } else { code = this.readHexChar(4) } return code } function codePointToString(code) { // UTF-16 Decoding if (code <= 0xFFFF) return String.fromCharCode(code) code -= 0x10000 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00) } pp.readString = function(quote) { let out = "", chunkStart = ++this.pos for (;;) { if (this.pos >= this.input.length) this.raise(this.start, "Unterminated string constant") let ch = this.input.charCodeAt(this.pos) if (ch === quote) break if (ch === 92) { // '\' out += this.input.slice(chunkStart, this.pos) out += this.readEscapedChar(false) chunkStart = this.pos } else { if (isNewLine(ch)) this.raise(this.start, "Unterminated string constant") ++this.pos } } out += this.input.slice(chunkStart, this.pos++) return this.finishToken(tt.string, out) } // Reads template string tokens. pp.readTmplToken = function() { let out = "", chunkStart = this.pos for (;;) { if (this.pos >= this.input.length) this.raise(this.start, "Unterminated template") let ch = this.input.charCodeAt(this.pos) if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${' if (this.pos === this.start && this.type === tt.template) { if (ch === 36) { this.pos += 2 return this.finishToken(tt.dollarBraceL) } else { ++this.pos return this.finishToken(tt.backQuote) } } out += this.input.slice(chunkStart, this.pos) return this.finishToken(tt.template, out) } if (ch === 92) { // '\' out += this.input.slice(chunkStart, this.pos) out += this.readEscapedChar(true) chunkStart = this.pos } else if (isNewLine(ch)) { out += this.input.slice(chunkStart, this.pos) ++this.pos switch (ch) { case 13: if (this.input.charCodeAt(this.pos) === 10) ++this.pos; case 10: out += "\n"; break; default: out += String.fromCharCode(ch); break; } if (this.options.locations) { ++this.curLine this.lineStart = this.pos } chunkStart = this.pos } else { ++this.pos } } } // Used to read escaped characters pp.readEscapedChar = function(inTemplate) { let ch = this.input.charCodeAt(++this.pos) ++this.pos switch (ch) { case 110: return "\n"; // 'n' -> '\n' case 114: return "\r"; // 'r' -> '\r' case 120: return String.fromCharCode(this.readHexChar(2)); // 'x' case 117: return codePointToString(this.readCodePoint()); // 'u' case 116: return "\t"; // 't' -> '\t' case 98: return "\b"; // 'b' -> '\b' case 118: return "\u000b"; // 'v' -> '\u000b' case 102: return "\f"; // 'f' -> '\f' case 13: if (this.input.charCodeAt(this.pos) === 10) ++this.pos; // '\r\n' case 10: // ' \n' if (this.options.locations) { this.lineStart = this.pos; ++this.curLine } return "" default: if (ch >= 48 && ch <= 55) { let octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0] let octal = parseInt(octalStr, 8) if (octal > 255) { octalStr = octalStr.slice(0, -1) octal = parseInt(octalStr, 8) } if (octalStr !== "0" && (this.strict || inTemplate)) { this.raise(this.pos - 2, "Octal literal in strict mode") } this.pos += octalStr.length - 1 return String.fromCharCode(octal) } return String.fromCharCode(ch) } } // Used to read character escape sequences ('\x', '\u', '\U'). pp.readHexChar = function(len) { let codePos = this.pos let n = this.readInt(16, len) if (n === null) this.raise(codePos, "Bad character escape sequence") return n } // Read an identifier, and return it as a string. Sets `this.containsEsc` // to whether the word contained a '\u' escape. // // Incrementally adds only escaped chars, adding other chunks as-is // as a micro-optimization. pp.readWord1 = function() { this.containsEsc = false let word = "", first = true, chunkStart = this.pos let astral = this.options.ecmaVersion >= 6 while (this.pos < this.input.length) { let ch = this.fullCharCodeAtPos() if (isIdentifierChar(ch, astral)) { this.pos += ch <= 0xffff ? 1 : 2 } else if (ch === 92) { // "\" this.containsEsc = true word += this.input.slice(chunkStart, this.pos) let escStart = this.pos if (this.input.charCodeAt(++this.pos) != 117) // "u" this.raise(this.pos, "Expecting Unicode escape sequence \\uXXXX") ++this.pos let esc = this.readCodePoint() if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) this.raise(escStart, "Invalid Unicode escape") word += codePointToString(esc) chunkStart = this.pos } else { break } first = false } return word + this.input.slice(chunkStart, this.pos) } // Read an identifier or keyword token. Will check for reserved // words when necessary. pp.readWord = function() { let word = this.readWord1() let type = tt.name if ((this.options.ecmaVersion >= 6 || !this.containsEsc) && this.keywords.test(word)) type = keywordTypes[word] return this.finishToken(type, word) } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/tokenize.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
6,303
```javascript import {lineBreakG} from "./whitespace" // These are used when `options.locations` is on, for the // `startLoc` and `endLoc` properties. export class Position { constructor(line, col) { this.line = line this.column = col } offset(n) { return new Position(this.line, this.column + n) } } export class SourceLocation { constructor(p, start, end) { this.start = start this.end = end if (p.sourceFile !== null) this.source = p.sourceFile } } // The `getLineInfo` function is mostly useful when the // `locations` option is off (for performance reasons) and you // want to find the line/column position for a given character // offset. `input` should be the code string that the offset refers // into. export function getLineInfo(input, offset) { for (let line = 1, cur = 0;;) { lineBreakG.lastIndex = cur let match = lineBreakG.exec(input) if (match && match.index < offset) { ++line cur = match.index + match[0].length } else { return new Position(line, offset - cur) } } } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/locutil.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
281
```javascript // Acorn: Loose parser // // This module provides an alternative parser (`parse_dammit`) that // exposes that same interface as `parse`, but will try to parse // anything as JavaScript, repairing syntax error the best it can. // There are circumstances in which it will raise an error and give // up, but they are very rare. The resulting AST will be a mostly // valid JavaScript AST (as per the [Mozilla parser API][api], except // that: // // - Return outside functions is allowed // // - Label consistency (no conflicts, break only to existing labels) // is not enforced. // // - Bogus Identifier nodes with a name of `""` are inserted whenever // the parser got too confused to return anything meaningful. // // [api]: path_to_url // // The expected use for this is to *first* try `acorn.parse`, and only // if that fails switch to `parse_dammit`. The loose parser might // parse badly indented code incorrectly, so **don't** use it as // your default parser. // // Quite a lot of acorn.js is duplicated here. The alternative was to // add a *lot* of extra cruft to that file, making it less readable // and slower. Copying and editing the code allowed me to make // invasive changes and simplifications without creating a complicated // tangle. import * as acorn from ".." import {LooseParser, pluginsLoose} from "./state" import "./tokenize" import "./statement" import "./expression" export {LooseParser, pluginsLoose} from "./state" acorn.defaultOptions.tabSize = 4 export function parse_dammit(input, options) { let p = new LooseParser(input, options) p.next() return p.parseTopLevel() } acorn.parse_dammit = parse_dammit acorn.LooseParser = LooseParser acorn.pluginsLoose = pluginsLoose ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/loose/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
423
```javascript import {LooseParser} from "./state" import {isDummy} from "./parseutil" import {getLineInfo, tokTypes as tt} from ".." const lp = LooseParser.prototype lp.parseTopLevel = function() { let node = this.startNodeAt(this.options.locations ? [0, getLineInfo(this.input, 0)] : 0) node.body = [] while (this.tok.type !== tt.eof) node.body.push(this.parseStatement()) this.last = this.tok if (this.options.ecmaVersion >= 6) { node.sourceType = this.options.sourceType } return this.finishNode(node, "Program") } lp.parseStatement = function() { let starttype = this.tok.type, node = this.startNode() switch (starttype) { case tt._break: case tt._continue: this.next() let isBreak = starttype === tt._break if (this.semicolon() || this.canInsertSemicolon()) { node.label = null } else { node.label = this.tok.type === tt.name ? this.parseIdent() : null this.semicolon() } return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") case tt._debugger: this.next() this.semicolon() return this.finishNode(node, "DebuggerStatement") case tt._do: this.next() node.body = this.parseStatement() node.test = this.eat(tt._while) ? this.parseParenExpression() : this.dummyIdent() this.semicolon() return this.finishNode(node, "DoWhileStatement") case tt._for: this.next() this.pushCx() this.expect(tt.parenL) if (this.tok.type === tt.semi) return this.parseFor(node, null) if (this.tok.type === tt._var || this.tok.type === tt._let || this.tok.type === tt._const) { let init = this.parseVar(true) if (init.declarations.length === 1 && (this.tok.type === tt._in || this.isContextual("of"))) { return this.parseForIn(node, init) } return this.parseFor(node, init) } let init = this.parseExpression(true) if (this.tok.type === tt._in || this.isContextual("of")) return this.parseForIn(node, this.toAssignable(init)) return this.parseFor(node, init) case tt._function: this.next() return this.parseFunction(node, true) case tt._if: this.next() node.test = this.parseParenExpression() node.consequent = this.parseStatement() node.alternate = this.eat(tt._else) ? this.parseStatement() : null return this.finishNode(node, "IfStatement") case tt._return: this.next() if (this.eat(tt.semi) || this.canInsertSemicolon()) node.argument = null else { node.argument = this.parseExpression(); this.semicolon() } return this.finishNode(node, "ReturnStatement") case tt._switch: let blockIndent = this.curIndent, line = this.curLineStart this.next() node.discriminant = this.parseParenExpression() node.cases = [] this.pushCx() this.expect(tt.braceL) let cur while (!this.closes(tt.braceR, blockIndent, line, true)) { if (this.tok.type === tt._case || this.tok.type === tt._default) { let isCase = this.tok.type === tt._case if (cur) this.finishNode(cur, "SwitchCase") node.cases.push(cur = this.startNode()) cur.consequent = [] this.next() if (isCase) cur.test = this.parseExpression() else cur.test = null this.expect(tt.colon) } else { if (!cur) { node.cases.push(cur = this.startNode()) cur.consequent = [] cur.test = null } cur.consequent.push(this.parseStatement()) } } if (cur) this.finishNode(cur, "SwitchCase") this.popCx() this.eat(tt.braceR) return this.finishNode(node, "SwitchStatement") case tt._throw: this.next() node.argument = this.parseExpression() this.semicolon() return this.finishNode(node, "ThrowStatement") case tt._try: this.next() node.block = this.parseBlock() node.handler = null if (this.tok.type === tt._catch) { let clause = this.startNode() this.next() this.expect(tt.parenL) clause.param = this.toAssignable(this.parseExprAtom(), true) this.expect(tt.parenR) clause.body = this.parseBlock() node.handler = this.finishNode(clause, "CatchClause") } node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null if (!node.handler && !node.finalizer) return node.block return this.finishNode(node, "TryStatement") case tt._var: case tt._let: case tt._const: return this.parseVar() case tt._while: this.next() node.test = this.parseParenExpression() node.body = this.parseStatement() return this.finishNode(node, "WhileStatement") case tt._with: this.next() node.object = this.parseParenExpression() node.body = this.parseStatement() return this.finishNode(node, "WithStatement") case tt.braceL: return this.parseBlock() case tt.semi: this.next() return this.finishNode(node, "EmptyStatement") case tt._class: return this.parseClass(true) case tt._import: return this.parseImport() case tt._export: return this.parseExport() default: let expr = this.parseExpression() if (isDummy(expr)) { this.next() if (this.tok.type === tt.eof) return this.finishNode(node, "EmptyStatement") return this.parseStatement() } else if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon)) { node.body = this.parseStatement() node.label = expr return this.finishNode(node, "LabeledStatement") } else { node.expression = expr this.semicolon() return this.finishNode(node, "ExpressionStatement") } } } lp.parseBlock = function() { let node = this.startNode() this.pushCx() this.expect(tt.braceL) let blockIndent = this.curIndent, line = this.curLineStart node.body = [] while (!this.closes(tt.braceR, blockIndent, line, true)) node.body.push(this.parseStatement()) this.popCx() this.eat(tt.braceR) return this.finishNode(node, "BlockStatement") } lp.parseFor = function(node, init) { node.init = init node.test = node.update = null if (this.eat(tt.semi) && this.tok.type !== tt.semi) node.test = this.parseExpression() if (this.eat(tt.semi) && this.tok.type !== tt.parenR) node.update = this.parseExpression() this.popCx() this.expect(tt.parenR) node.body = this.parseStatement() return this.finishNode(node, "ForStatement") } lp.parseForIn = function(node, init) { let type = this.tok.type === tt._in ? "ForInStatement" : "ForOfStatement" this.next() node.left = init node.right = this.parseExpression() this.popCx() this.expect(tt.parenR) node.body = this.parseStatement() return this.finishNode(node, type) } lp.parseVar = function(noIn) { let node = this.startNode() node.kind = this.tok.type.keyword this.next() node.declarations = [] do { let decl = this.startNode() decl.id = this.options.ecmaVersion >= 6 ? this.toAssignable(this.parseExprAtom(), true) : this.parseIdent() decl.init = this.eat(tt.eq) ? this.parseMaybeAssign(noIn) : null node.declarations.push(this.finishNode(decl, "VariableDeclarator")) } while (this.eat(tt.comma)) if (!node.declarations.length) { let decl = this.startNode() decl.id = this.dummyIdent() node.declarations.push(this.finishNode(decl, "VariableDeclarator")) } if (!noIn) this.semicolon() return this.finishNode(node, "VariableDeclaration") } lp.parseClass = function(isStatement) { let node = this.startNode() this.next() if (this.tok.type === tt.name) node.id = this.parseIdent() else if (isStatement) node.id = this.dummyIdent() else node.id = null node.superClass = this.eat(tt._extends) ? this.parseExpression() : null node.body = this.startNode() node.body.body = [] this.pushCx() let indent = this.curIndent + 1, line = this.curLineStart this.eat(tt.braceL) if (this.curIndent + 1 < indent) { indent = this.curIndent; line = this.curLineStart } while (!this.closes(tt.braceR, indent, line)) { if (this.semicolon()) continue let method = this.startNode(), isGenerator if (this.options.ecmaVersion >= 6) { method.static = false isGenerator = this.eat(tt.star) } this.parsePropertyName(method) if (isDummy(method.key)) { if (isDummy(this.parseMaybeAssign())) this.next(); this.eat(tt.comma); continue } if (method.key.type === "Identifier" && !method.computed && method.key.name === "static" && (this.tok.type != tt.parenL && this.tok.type != tt.braceL)) { method.static = true isGenerator = this.eat(tt.star) this.parsePropertyName(method) } else { method.static = false } if (this.options.ecmaVersion >= 5 && method.key.type === "Identifier" && !method.computed && (method.key.name === "get" || method.key.name === "set") && this.tok.type !== tt.parenL && this.tok.type !== tt.braceL) { method.kind = method.key.name this.parsePropertyName(method) method.value = this.parseMethod(false) } else { if (!method.computed && !method.static && !isGenerator && ( method.key.type === "Identifier" && method.key.name === "constructor" || method.key.type === "Literal" && method.key.value === "constructor")) { method.kind = "constructor" } else { method.kind = "method" } method.value = this.parseMethod(isGenerator) } node.body.body.push(this.finishNode(method, "MethodDefinition")) } this.popCx() if (!this.eat(tt.braceR)) { // If there is no closing brace, make the node span to the start // of the next token (this is useful for Tern) this.last.end = this.tok.start if (this.options.locations) this.last.loc.end = this.tok.loc.start } this.semicolon() this.finishNode(node.body, "ClassBody") return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") } lp.parseFunction = function(node, isStatement) { this.initFunction(node) if (this.options.ecmaVersion >= 6) { node.generator = this.eat(tt.star) } if (this.tok.type === tt.name) node.id = this.parseIdent() else if (isStatement) node.id = this.dummyIdent() node.params = this.parseFunctionParams() node.body = this.parseBlock() return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression") } lp.parseExport = function() { let node = this.startNode() this.next() if (this.eat(tt.star)) { node.source = this.eatContextual("from") ? this.parseExprAtom() : null return this.finishNode(node, "ExportAllDeclaration") } if (this.eat(tt._default)) { let expr = this.parseMaybeAssign() if (expr.id) { switch (expr.type) { case "FunctionExpression": expr.type = "FunctionDeclaration"; break case "ClassExpression": expr.type = "ClassDeclaration"; break } } node.declaration = expr this.semicolon() return this.finishNode(node, "ExportDefaultDeclaration") } if (this.tok.type.keyword) { node.declaration = this.parseStatement() node.specifiers = [] node.source = null } else { node.declaration = null node.specifiers = this.parseExportSpecifierList() node.source = this.eatContextual("from") ? this.parseExprAtom() : null this.semicolon() } return this.finishNode(node, "ExportNamedDeclaration") } lp.parseImport = function() { let node = this.startNode() this.next() if (this.tok.type === tt.string) { node.specifiers = [] node.source = this.parseExprAtom() node.kind = '' } else { let elt if (this.tok.type === tt.name && this.tok.value !== "from") { elt = this.startNode() elt.local = this.parseIdent() this.finishNode(elt, "ImportDefaultSpecifier") this.eat(tt.comma) } node.specifiers = this.parseImportSpecifierList() node.source = this.eatContextual("from") && this.tok.type == tt.string ? this.parseExprAtom() : this.dummyString() if (elt) node.specifiers.unshift(elt) } this.semicolon() return this.finishNode(node, "ImportDeclaration") } lp.parseImportSpecifierList = function() { let elts = [] if (this.tok.type === tt.star) { let elt = this.startNode() this.next() if (this.eatContextual("as")) elt.local = this.parseIdent() elts.push(this.finishNode(elt, "ImportNamespaceSpecifier")) } else { let indent = this.curIndent, line = this.curLineStart, continuedLine = this.nextLineStart this.pushCx() this.eat(tt.braceL) if (this.curLineStart > continuedLine) continuedLine = this.curLineStart while (!this.closes(tt.braceR, indent + (this.curLineStart <= continuedLine ? 1 : 0), line)) { let elt = this.startNode() if (this.eat(tt.star)) { elt.local = this.eatContextual("as") ? this.parseIdent() : this.dummyIdent() this.finishNode(elt, "ImportNamespaceSpecifier") } else { if (this.isContextual("from")) break elt.imported = this.parseIdent() if (isDummy(elt.imported)) break elt.local = this.eatContextual("as") ? this.parseIdent() : elt.imported this.finishNode(elt, "ImportSpecifier") } elts.push(elt) this.eat(tt.comma) } this.eat(tt.braceR) this.popCx() } return elts } lp.parseExportSpecifierList = function() { let elts = [] let indent = this.curIndent, line = this.curLineStart, continuedLine = this.nextLineStart this.pushCx() this.eat(tt.braceL) if (this.curLineStart > continuedLine) continuedLine = this.curLineStart while (!this.closes(tt.braceR, indent + (this.curLineStart <= continuedLine ? 1 : 0), line)) { if (this.isContextual("from")) break let elt = this.startNode() elt.local = this.parseIdent() if (isDummy(elt.local)) break elt.exported = this.eatContextual("as") ? this.parseIdent() : elt.local this.finishNode(elt, "ExportSpecifier") elts.push(elt) this.eat(tt.comma) } this.eat(tt.braceR) this.popCx() return elts } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/loose/statement.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,667
```javascript export function isDummy(node) { return node.name == "" } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/loose/parseutil.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
14
```javascript import {tokenizer, SourceLocation, tokTypes as tt, Node, lineBreak, isNewLine} from ".." // Registered plugins export const pluginsLoose = {} export class LooseParser { constructor(input, options) { this.toks = tokenizer(input, options) this.options = this.toks.options this.input = this.toks.input this.tok = this.last = {type: tt.eof, start: 0, end: 0} if (this.options.locations) { let here = this.toks.curPosition() this.tok.loc = new SourceLocation(this.toks, here, here) } this.ahead = []; // Tokens ahead this.context = []; // Indentation contexted this.curIndent = 0 this.curLineStart = 0 this.nextLineStart = this.lineEnd(this.curLineStart) + 1 // Load plugins this.options.pluginsLoose = options.pluginsLoose || {} this.loadPlugins(this.options.pluginsLoose) } startNode() { return new Node(this.toks, this.tok.start, this.options.locations ? this.tok.loc.start : null) } storeCurrentPos() { return this.options.locations ? [this.tok.start, this.tok.loc.start] : this.tok.start } startNodeAt(pos) { if (this.options.locations) { return new Node(this.toks, pos[0], pos[1]) } else { return new Node(this.toks, pos) } } finishNode(node, type) { node.type = type node.end = this.last.end if (this.options.locations) node.loc.end = this.last.loc.end if (this.options.ranges) node.range[1] = this.last.end return node } dummyNode(type) { let dummy = this.startNode() dummy.type = type dummy.end = dummy.start if (this.options.locations) dummy.loc.end = dummy.loc.start if (this.options.ranges) dummy.range[1] = dummy.start this.last = {type: tt.name, start: dummy.start, end: dummy.start, loc: dummy.loc} return dummy } dummyIdent() { let dummy = this.dummyNode("Identifier") dummy.name = "" return dummy } dummyString() { let dummy = this.dummyNode("Literal") dummy.value = dummy.raw = "" return dummy } eat(type) { if (this.tok.type === type) { this.next() return true } else { return false } } isContextual(name) { return this.tok.type === tt.name && this.tok.value === name } eatContextual(name) { return this.tok.value === name && this.eat(tt.name) } canInsertSemicolon() { return this.tok.type === tt.eof || this.tok.type === tt.braceR || lineBreak.test(this.input.slice(this.last.end, this.tok.start)) } semicolon() { return this.eat(tt.semi) } expect(type) { if (this.eat(type)) return true for (let i = 1; i <= 2; i++) { if (this.lookAhead(i).type == type) { for (let j = 0; j < i; j++) this.next() return true } } } pushCx() { this.context.push(this.curIndent) } popCx() { this.curIndent = this.context.pop() } lineEnd(pos) { while (pos < this.input.length && !isNewLine(this.input.charCodeAt(pos))) ++pos return pos } indentationAfter(pos) { for (let count = 0;; ++pos) { let ch = this.input.charCodeAt(pos) if (ch === 32) ++count else if (ch === 9) count += this.options.tabSize else return count } } closes(closeTok, indent, line, blockHeuristic) { if (this.tok.type === closeTok || this.tok.type === tt.eof) return true return line != this.curLineStart && this.curIndent < indent && this.tokenStartsLine() && (!blockHeuristic || this.nextLineStart >= this.input.length || this.indentationAfter(this.nextLineStart) < indent) } tokenStartsLine() { for (let p = this.tok.start - 1; p >= this.curLineStart; --p) { let ch = this.input.charCodeAt(p) if (ch !== 9 && ch !== 32) return false } return true } extend(name, f) { this[name] = f(this[name]) } loadPlugins(pluginConfigs) { for (let name in pluginConfigs) { let plugin = pluginsLoose[name] if (!plugin) throw new Error("Plugin '" + name + "' not found") plugin(this, pluginConfigs[name]) } } } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/loose/state.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,123
```javascript import {LooseParser} from "./state" import {isDummy} from "./parseutil" import {tokTypes as tt} from ".." const lp = LooseParser.prototype lp.checkLVal = function(expr) { if (!expr) return expr switch (expr.type) { case "Identifier": case "MemberExpression": return expr case "ParenthesizedExpression": expr.expression = this.checkLVal(expr.expression) return expr default: return this.dummyIdent() } } lp.parseExpression = function(noIn) { let start = this.storeCurrentPos() let expr = this.parseMaybeAssign(noIn) if (this.tok.type === tt.comma) { let node = this.startNodeAt(start) node.expressions = [expr] while (this.eat(tt.comma)) node.expressions.push(this.parseMaybeAssign(noIn)) return this.finishNode(node, "SequenceExpression") } return expr } lp.parseParenExpression = function() { this.pushCx() this.expect(tt.parenL) let val = this.parseExpression() this.popCx() this.expect(tt.parenR) return val } lp.parseMaybeAssign = function(noIn) { let start = this.storeCurrentPos() let left = this.parseMaybeConditional(noIn) if (this.tok.type.isAssign) { let node = this.startNodeAt(start) node.operator = this.tok.value node.left = this.tok.type === tt.eq ? this.toAssignable(left) : this.checkLVal(left) this.next() node.right = this.parseMaybeAssign(noIn) return this.finishNode(node, "AssignmentExpression") } return left } lp.parseMaybeConditional = function(noIn) { let start = this.storeCurrentPos() let expr = this.parseExprOps(noIn) if (this.eat(tt.question)) { let node = this.startNodeAt(start) node.test = expr node.consequent = this.parseMaybeAssign() node.alternate = this.expect(tt.colon) ? this.parseMaybeAssign(noIn) : this.dummyIdent() return this.finishNode(node, "ConditionalExpression") } return expr } lp.parseExprOps = function(noIn) { let start = this.storeCurrentPos() let indent = this.curIndent, line = this.curLineStart return this.parseExprOp(this.parseMaybeUnary(noIn), start, -1, noIn, indent, line) } lp.parseExprOp = function(left, start, minPrec, noIn, indent, line) { if (this.curLineStart != line && this.curIndent < indent && this.tokenStartsLine()) return left let prec = this.tok.type.binop if (prec != null && (!noIn || this.tok.type !== tt._in)) { if (prec > minPrec) { let node = this.startNodeAt(start) node.left = left node.operator = this.tok.value this.next() if (this.curLineStart != line && this.curIndent < indent && this.tokenStartsLine()) { node.right = this.dummyIdent() } else { let rightStart = this.storeCurrentPos() node.right = this.parseExprOp(this.parseMaybeUnary(noIn), rightStart, prec, noIn, indent, line) } this.finishNode(node, /&&|\|\|/.test(node.operator) ? "LogicalExpression" : "BinaryExpression") return this.parseExprOp(node, start, minPrec, noIn, indent, line) } } return left } lp.parseMaybeUnary = function(noIn) { if (this.tok.type.prefix) { let node = this.startNode(), update = this.tok.type === tt.incDec node.operator = this.tok.value node.prefix = true this.next() node.argument = this.parseMaybeUnary(noIn) if (update) node.argument = this.checkLVal(node.argument) return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression") } else if (this.tok.type === tt.ellipsis) { let node = this.startNode() this.next() node.argument = this.parseMaybeUnary(noIn) return this.finishNode(node, "SpreadElement") } let start = this.storeCurrentPos() let expr = this.parseExprSubscripts() while (this.tok.type.postfix && !this.canInsertSemicolon()) { let node = this.startNodeAt(start) node.operator = this.tok.value node.prefix = false node.argument = this.checkLVal(expr) this.next() expr = this.finishNode(node, "UpdateExpression") } return expr } lp.parseExprSubscripts = function() { let start = this.storeCurrentPos() return this.parseSubscripts(this.parseExprAtom(), start, false, this.curIndent, this.curLineStart) } lp.parseSubscripts = function(base, start, noCalls, startIndent, line) { for (;;) { if (this.curLineStart != line && this.curIndent <= startIndent && this.tokenStartsLine()) { if (this.tok.type == tt.dot && this.curIndent == startIndent) --startIndent else return base } if (this.eat(tt.dot)) { let node = this.startNodeAt(start) node.object = base if (this.curLineStart != line && this.curIndent <= startIndent && this.tokenStartsLine()) node.property = this.dummyIdent() else node.property = this.parsePropertyAccessor() || this.dummyIdent() node.computed = false base = this.finishNode(node, "MemberExpression") } else if (this.tok.type == tt.bracketL) { this.pushCx() this.next() let node = this.startNodeAt(start) node.object = base node.property = this.parseExpression() node.computed = true this.popCx() this.expect(tt.bracketR) base = this.finishNode(node, "MemberExpression") } else if (!noCalls && this.tok.type == tt.parenL) { let node = this.startNodeAt(start) node.callee = base node.arguments = this.parseExprList(tt.parenR) base = this.finishNode(node, "CallExpression") } else if (this.tok.type == tt.backQuote) { let node = this.startNodeAt(start) node.tag = base node.quasi = this.parseTemplate() base = this.finishNode(node, "TaggedTemplateExpression") } else { return base } } } lp.parseExprAtom = function() { let node switch (this.tok.type) { case tt._this: case tt._super: let type = this.tok.type === tt._this ? "ThisExpression" : "Super" node = this.startNode() this.next() return this.finishNode(node, type) case tt.name: let start = this.storeCurrentPos() let id = this.parseIdent() return this.eat(tt.arrow) ? this.parseArrowExpression(this.startNodeAt(start), [id]) : id case tt.regexp: node = this.startNode() let val = this.tok.value node.regex = {pattern: val.pattern, flags: val.flags} node.value = val.value node.raw = this.input.slice(this.tok.start, this.tok.end) this.next() return this.finishNode(node, "Literal") case tt.num: case tt.string: node = this.startNode() node.value = this.tok.value node.raw = this.input.slice(this.tok.start, this.tok.end) this.next() return this.finishNode(node, "Literal") case tt._null: case tt._true: case tt._false: node = this.startNode() node.value = this.tok.type === tt._null ? null : this.tok.type === tt._true node.raw = this.tok.type.keyword this.next() return this.finishNode(node, "Literal") case tt.parenL: let parenStart = this.storeCurrentPos() this.next() let inner = this.parseExpression() this.expect(tt.parenR) if (this.eat(tt.arrow)) { return this.parseArrowExpression(this.startNodeAt(parenStart), inner.expressions || (isDummy(inner) ? [] : [inner])) } if (this.options.preserveParens) { let par = this.startNodeAt(parenStart) par.expression = inner inner = this.finishNode(par, "ParenthesizedExpression") } return inner case tt.bracketL: node = this.startNode() node.elements = this.parseExprList(tt.bracketR, true) return this.finishNode(node, "ArrayExpression") case tt.braceL: return this.parseObj() case tt._class: return this.parseClass() case tt._function: node = this.startNode() this.next() return this.parseFunction(node, false) case tt._new: return this.parseNew() case tt._yield: node = this.startNode() this.next() if (this.semicolon() || this.canInsertSemicolon() || (this.tok.type != tt.star && !this.tok.type.startsExpr)) { node.delegate = false node.argument = null } else { node.delegate = this.eat(tt.star) node.argument = this.parseMaybeAssign() } return this.finishNode(node, "YieldExpression") case tt.backQuote: return this.parseTemplate() default: return this.dummyIdent() } } lp.parseNew = function() { let node = this.startNode(), startIndent = this.curIndent, line = this.curLineStart let meta = this.parseIdent(true) if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) { node.meta = meta node.property = this.parseIdent(true) return this.finishNode(node, "MetaProperty") } let start = this.storeCurrentPos() node.callee = this.parseSubscripts(this.parseExprAtom(), start, true, startIndent, line) if (this.tok.type == tt.parenL) { node.arguments = this.parseExprList(tt.parenR) } else { node.arguments = [] } return this.finishNode(node, "NewExpression") } lp.parseTemplateElement = function() { let elem = this.startNode() elem.value = { raw: this.input.slice(this.tok.start, this.tok.end).replace(/\r\n?/g, '\n'), cooked: this.tok.value } this.next() elem.tail = this.tok.type === tt.backQuote return this.finishNode(elem, "TemplateElement") } lp.parseTemplate = function() { let node = this.startNode() this.next() node.expressions = [] let curElt = this.parseTemplateElement() node.quasis = [curElt] while (!curElt.tail) { this.next() node.expressions.push(this.parseExpression()) if (this.expect(tt.braceR)) { curElt = this.parseTemplateElement() } else { curElt = this.startNode() curElt.value = {cooked: '', raw: ''} curElt.tail = true } node.quasis.push(curElt) } this.expect(tt.backQuote) return this.finishNode(node, "TemplateLiteral") } lp.parseObj = function() { let node = this.startNode() node.properties = [] this.pushCx() let indent = this.curIndent + 1, line = this.curLineStart this.eat(tt.braceL) if (this.curIndent + 1 < indent) { indent = this.curIndent; line = this.curLineStart } while (!this.closes(tt.braceR, indent, line)) { let prop = this.startNode(), isGenerator, start if (this.options.ecmaVersion >= 6) { start = this.storeCurrentPos() prop.method = false prop.shorthand = false isGenerator = this.eat(tt.star) } this.parsePropertyName(prop) if (isDummy(prop.key)) { if (isDummy(this.parseMaybeAssign())) this.next(); this.eat(tt.comma); continue } if (this.eat(tt.colon)) { prop.kind = "init" prop.value = this.parseMaybeAssign() } else if (this.options.ecmaVersion >= 6 && (this.tok.type === tt.parenL || this.tok.type === tt.braceL)) { prop.kind = "init" prop.method = true prop.value = this.parseMethod(isGenerator) } else if (this.options.ecmaVersion >= 5 && prop.key.type === "Identifier" && !prop.computed && (prop.key.name === "get" || prop.key.name === "set") && (this.tok.type != tt.comma && this.tok.type != tt.braceR)) { prop.kind = prop.key.name this.parsePropertyName(prop) prop.value = this.parseMethod(false) } else { prop.kind = "init" if (this.options.ecmaVersion >= 6) { if (this.eat(tt.eq)) { let assign = this.startNodeAt(start) assign.operator = "=" assign.left = prop.key assign.right = this.parseMaybeAssign() prop.value = this.finishNode(assign, "AssignmentExpression") } else { prop.value = prop.key } } else { prop.value = this.dummyIdent() } prop.shorthand = true } node.properties.push(this.finishNode(prop, "Property")) this.eat(tt.comma) } this.popCx() if (!this.eat(tt.braceR)) { // If there is no closing brace, make the node span to the start // of the next token (this is useful for Tern) this.last.end = this.tok.start if (this.options.locations) this.last.loc.end = this.tok.loc.start } return this.finishNode(node, "ObjectExpression") } lp.parsePropertyName = function(prop) { if (this.options.ecmaVersion >= 6) { if (this.eat(tt.bracketL)) { prop.computed = true prop.key = this.parseExpression() this.expect(tt.bracketR) return } else { prop.computed = false } } let key = (this.tok.type === tt.num || this.tok.type === tt.string) ? this.parseExprAtom() : this.parseIdent() prop.key = key || this.dummyIdent() } lp.parsePropertyAccessor = function() { if (this.tok.type === tt.name || this.tok.type.keyword) return this.parseIdent() } lp.parseIdent = function() { let name = this.tok.type === tt.name ? this.tok.value : this.tok.type.keyword if (!name) return this.dummyIdent() let node = this.startNode() this.next() node.name = name return this.finishNode(node, "Identifier") } lp.initFunction = function(node) { node.id = null node.params = [] if (this.options.ecmaVersion >= 6) { node.generator = false node.expression = false } } // Convert existing expression atom to assignable pattern // if possible. lp.toAssignable = function(node, binding) { if (!node || node.type == "Identifier" || (node.type == "MemberExpression" && !binding)) { // Okay } else if (node.type == "ParenthesizedExpression") { node.expression = this.toAssignable(node.expression, binding) } else if (this.options.ecmaVersion < 6) { return this.dummyIdent() } else if (node.type == "ObjectExpression") { node.type = "ObjectPattern" let props = node.properties for (let i = 0; i < props.length; i++) props[i].value = this.toAssignable(props[i].value, binding) } else if (node.type == "ArrayExpression") { node.type = "ArrayPattern" this.toAssignableList(node.elements, binding) } else if (node.type == "SpreadElement") { node.type = "RestElement" node.argument = this.toAssignable(node.argument, binding) } else if (node.type == "AssignmentExpression") { node.type = "AssignmentPattern" delete node.operator } else { return this.dummyIdent() } return node } lp.toAssignableList = function(exprList, binding) { for (let i = 0; i < exprList.length; i++) exprList[i] = this.toAssignable(exprList[i], binding) return exprList } lp.parseFunctionParams = function(params) { params = this.parseExprList(tt.parenR) return this.toAssignableList(params, true) } lp.parseMethod = function(isGenerator) { let node = this.startNode() this.initFunction(node) node.params = this.parseFunctionParams() node.generator = isGenerator || false node.expression = this.options.ecmaVersion >= 6 && this.tok.type !== tt.braceL node.body = node.expression ? this.parseMaybeAssign() : this.parseBlock() return this.finishNode(node, "FunctionExpression") } lp.parseArrowExpression = function(node, params) { this.initFunction(node) node.params = this.toAssignableList(params, true) node.expression = this.tok.type !== tt.braceL node.body = node.expression ? this.parseMaybeAssign() : this.parseBlock() return this.finishNode(node, "ArrowFunctionExpression") } lp.parseExprList = function(close, allowEmpty) { this.pushCx() let indent = this.curIndent, line = this.curLineStart, elts = [] this.next(); // Opening bracket while (!this.closes(close, indent + 1, line)) { if (this.eat(tt.comma)) { elts.push(allowEmpty ? null : this.dummyIdent()) continue } let elt = this.parseMaybeAssign() if (isDummy(elt)) { if (this.closes(close, indent, line)) break this.next() } else { elts.push(elt) } this.eat(tt.comma) } this.popCx() if (!this.eat(close)) { // If there is no closing brace, make the node span to the start // of the next token (this is useful for Tern) this.last.end = this.tok.start if (this.options.locations) this.last.loc.end = this.tok.loc.start } return elts } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/loose/expression.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
4,159
```javascript #!/usr/bin/env node import {basename} from "path" import {readFileSync as readFile} from "fs" import * as acorn from "../dist/acorn.js" let infile, forceFile, silent = false, compact = false, tokenize = false const options = {} function help(status) { const print = (status == 0) ? console.log : console.error print("usage: " + basename(process.argv[1]) + " [--ecma3|--ecma5|--ecma6]") print(" [--tokenize] [--locations] [---allow-hash-bang] [--compact] [--silent] [--module] [--help] [--] [infile]") process.exit(status) } for (let i = 2; i < process.argv.length; ++i) { const arg = process.argv[i] if ((arg == "-" || arg[0] != "-") && !infile) infile = arg else if (arg == "--" && !infile && i + 2 == process.argv.length) forceFile = infile = process.argv[++i] else if (arg == "--ecma3") options.ecmaVersion = 3 else if (arg == "--ecma5") options.ecmaVersion = 5 else if (arg == "--ecma6") options.ecmaVersion = 6 else if (arg == "--locations") options.locations = true else if (arg == "--allow-hash-bang") options.allowHashBang = true else if (arg == "--silent") silent = true else if (arg == "--compact") compact = true else if (arg == "--help") help(0) else if (arg == "--tokenize") tokenize = true else if (arg == "--module") options.sourceType = 'module' else help(1) } function run(code) { let result if (!tokenize) { try { result = acorn.parse(code, options) } catch(e) { console.error(e.message); process.exit(1) } } else { result = [] let tokenizer = acorn.tokenizer(code, options), token while (true) { try { token = tokenizer.getToken() } catch(e) { console.error(e.message); process.exit(1) } result.push(token) if (token.type == acorn.tokTypes.eof) break } } if (!silent) console.log(JSON.stringify(result, null, compact ? null : 2)) } if (forceFile || infile && infile != "-") { run(readFile(infile, "utf8")) } else { let code = "" process.stdin.resume() process.stdin.on("data", chunk => code += chunk) process.stdin.on("end", () => run(code)) } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/bin/acorn.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
600
```javascript var fs = require("fs"), path = require("path") var stream = require("stream") var browserify = require("browserify") var babel = require('babel-core') var babelify = require("babelify").configure({loose: "all"}) process.chdir(path.resolve(__dirname, "..")) browserify({standalone: "acorn"}) .plugin(require('browserify-derequire')) .transform(babelify) .require("./src/index.js", {entry: true}) .bundle() .on("error", function (err) { console.log("Error: " + err.message) }) .pipe(fs.createWriteStream("dist/acorn.js")) var ACORN_PLACEHOLDER = "this_function_call_should_be_replaced_with_a_call_to_load_acorn()"; function acornShimPrepare(file) { var tr = new stream.Transform if (file == path.resolve(__dirname, "../src/index.js")) { var sent = false tr._transform = function(chunk, _, callback) { if (!sent) { sent = true callback(null, ACORN_PLACEHOLDER); } else { callback() } } } else { tr._transform = function(chunk, _, callback) { callback(null, chunk) } } return tr } function acornShimComplete() { var tr = new stream.Transform var buffer = ""; tr._transform = function(chunk, _, callback) { buffer += chunk.toString("utf8"); callback(); }; tr._flush = function (callback) { tr.push(buffer.replace(ACORN_PLACEHOLDER, "module.exports = typeof acorn != 'undefined' ? acorn : require(\"./acorn\")")); callback(null); }; return tr; } browserify({standalone: "acorn.loose"}) .plugin(require('browserify-derequire')) .transform(acornShimPrepare) .transform(babelify) .require("./src/loose/index.js", {entry: true}) .bundle() .on("error", function (err) { console.log("Error: " + err.message) }) .pipe(acornShimComplete()) .pipe(fs.createWriteStream("dist/acorn_loose.js")) browserify({standalone: "acorn.walk"}) .plugin(require('browserify-derequire')) .transform(acornShimPrepare) .transform(babelify) .require("./src/walk/index.js", {entry: true}) .bundle() .on("error", function (err) { console.log("Error: " + err.message) }) .pipe(acornShimComplete()) .pipe(fs.createWriteStream("dist/walk.js")) babel.transformFile("./src/bin/acorn.js", function (err, result) { if (err) return console.log("Error: " + err.message) fs.writeFile("bin/acorn", result.code, function (err) { if (err) return console.log("Error: " + err.message) // Make bin/acorn executable if (process.platform === 'win32') return var stat = fs.statSync("bin/acorn") var newPerm = stat.mode | parseInt('111', 8) fs.chmodSync("bin/acorn", newPerm) }) }) ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/bin/build-acorn.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
713
```javascript // AST walker module for Mozilla Parser API compatible trees // A simple walk is one where you simply specify callbacks to be // called on specific nodes. The last two arguments are optional. A // simple use would be // // walk.simple(myTree, { // Expression: function(node) { ... } // }); // // to do something with all expressions. All Parser API node types // can be used to identify node types, as well as Expression, // Statement, and ScopeBody, which denote categories of nodes. // // The base argument can be used to pass a custom (recursive) // walker, and state can be used to give this walked an initial // state. export function simple(node, visitors, base, state, override) { if (!base) base = exports.base ;(function c(node, st, override) { let type = override || node.type, found = visitors[type] base[type](node, st, c) if (found) found(node, st) })(node, state, override) } // An ancestor walk builds up an array of ancestor nodes (including // the current node) and passes them to the callback as the state parameter. export function ancestor(node, visitors, base, state) { if (!base) base = exports.base if (!state) state = [] ;(function c(node, st, override) { let type = override || node.type, found = visitors[type] if (node != st[st.length - 1]) { st = st.slice() st.push(node) } base[type](node, st, c) if (found) found(node, st) })(node, state) } // A recursive walk is one where your functions override the default // walkers. They can modify and replace the state parameter that's // threaded through the walk, and can opt how and whether to walk // their child nodes (by calling their third argument on these // nodes). export function recursive(node, state, funcs, base, override) { let visitor = funcs ? exports.make(funcs, base) : base ;(function c(node, st, override) { visitor[override || node.type](node, st, c) })(node, state, override) } function makeTest(test) { if (typeof test == "string") return type => type == test else if (!test) return () => true else return test } class Found { constructor(node, state) { this.node = node; this.state = state } } // Find a node with a given start, end, and type (all are optional, // null can be used as wildcard). Returns a {node, state} object, or // undefined when it doesn't find a matching node. export function findNodeAt(node, start, end, test, base, state) { test = makeTest(test) if (!base) base = exports.base try { ;(function c(node, st, override) { let type = override || node.type if ((start == null || node.start <= start) && (end == null || node.end >= end)) base[type](node, st, c) if ((start == null || node.start == start) && (end == null || node.end == end) && test(type, node)) throw new Found(node, st) })(node, state) } catch (e) { if (e instanceof Found) return e throw e } } // Find the innermost node of a given type that contains the given // position. Interface similar to findNodeAt. export function findNodeAround(node, pos, test, base, state) { test = makeTest(test) if (!base) base = exports.base try { ;(function c(node, st, override) { let type = override || node.type if (node.start > pos || node.end < pos) return base[type](node, st, c) if (test(type, node)) throw new Found(node, st) })(node, state) } catch (e) { if (e instanceof Found) return e throw e } } // Find the outermost matching node after a given position. export function findNodeAfter(node, pos, test, base, state) { test = makeTest(test) if (!base) base = exports.base try { ;(function c(node, st, override) { if (node.end < pos) return let type = override || node.type if (node.start >= pos && test(type, node)) throw new Found(node, st) base[type](node, st, c) })(node, state) } catch (e) { if (e instanceof Found) return e throw e } } // Find the outermost matching node before a given position. export function findNodeBefore(node, pos, test, base, state) { test = makeTest(test) if (!base) base = exports.base let max ;(function c(node, st, override) { if (node.start > pos) return let type = override || node.type if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node)) max = new Found(node, st) base[type](node, st, c) })(node, state) return max } // Used to create a custom walker. Will fill in all missing node // type properties with the defaults. export function make(funcs, base) { if (!base) base = exports.base let visitor = {} for (var type in base) visitor[type] = base[type] for (var type in funcs) visitor[type] = funcs[type] return visitor } function skipThrough(node, st, c) { c(node, st) } function ignore(_node, _st, _c) {} // Node walkers. export const base = {} base.Program = base.BlockStatement = (node, st, c) => { for (let i = 0; i < node.body.length; ++i) c(node.body[i], st, "Statement") } base.Statement = skipThrough base.EmptyStatement = ignore base.ExpressionStatement = base.ParenthesizedExpression = (node, st, c) => c(node.expression, st, "Expression") base.IfStatement = (node, st, c) => { c(node.test, st, "Expression") c(node.consequent, st, "Statement") if (node.alternate) c(node.alternate, st, "Statement") } base.LabeledStatement = (node, st, c) => c(node.body, st, "Statement") base.BreakStatement = base.ContinueStatement = ignore base.WithStatement = (node, st, c) => { c(node.object, st, "Expression") c(node.body, st, "Statement") } base.SwitchStatement = (node, st, c) => { c(node.discriminant, st, "Expression") for (let i = 0; i < node.cases.length; ++i) { let cs = node.cases[i] if (cs.test) c(cs.test, st, "Expression") for (let j = 0; j < cs.consequent.length; ++j) c(cs.consequent[j], st, "Statement") } } base.ReturnStatement = base.YieldExpression = (node, st, c) => { if (node.argument) c(node.argument, st, "Expression") } base.ThrowStatement = base.SpreadElement = (node, st, c) => c(node.argument, st, "Expression") base.TryStatement = (node, st, c) => { c(node.block, st, "Statement") if (node.handler) { c(node.handler.param, st, "Pattern") c(node.handler.body, st, "ScopeBody") } if (node.finalizer) c(node.finalizer, st, "Statement") } base.WhileStatement = base.DoWhileStatement = (node, st, c) => { c(node.test, st, "Expression") c(node.body, st, "Statement") } base.ForStatement = (node, st, c) => { if (node.init) c(node.init, st, "ForInit") if (node.test) c(node.test, st, "Expression") if (node.update) c(node.update, st, "Expression") c(node.body, st, "Statement") } base.ForInStatement = base.ForOfStatement = (node, st, c) => { c(node.left, st, "ForInit") c(node.right, st, "Expression") c(node.body, st, "Statement") } base.ForInit = (node, st, c) => { if (node.type == "VariableDeclaration") c(node, st) else c(node, st, "Expression") } base.DebuggerStatement = ignore base.FunctionDeclaration = (node, st, c) => c(node, st, "Function") base.VariableDeclaration = (node, st, c) => { for (let i = 0; i < node.declarations.length; ++i) c(node.declarations[i], st) } base.VariableDeclarator = (node, st, c) => { c(node.id, st, "Pattern") if (node.init) c(node.init, st, "Expression") } base.Function = (node, st, c) => { if (node.id) c(node.id, st, "Pattern") for (let i = 0; i < node.params.length; i++) c(node.params[i], st, "Pattern") c(node.body, st, node.expression ? "ScopeExpression" : "ScopeBody") } // FIXME drop these node types in next major version // (They are awkward, and in ES6 every block can be a scope.) base.ScopeBody = (node, st, c) => c(node, st, "Statement") base.ScopeExpression = (node, st, c) => c(node, st, "Expression") base.Pattern = (node, st, c) => { if (node.type == "Identifier") c(node, st, "VariablePattern") else if (node.type == "MemberExpression") c(node, st, "MemberPattern") else c(node, st) } base.VariablePattern = ignore base.MemberPattern = skipThrough base.RestElement = (node, st, c) => c(node.argument, st, "Pattern") base.ArrayPattern = (node, st, c) => { for (let i = 0; i < node.elements.length; ++i) { let elt = node.elements[i] if (elt) c(elt, st, "Pattern") } } base.ObjectPattern = (node, st, c) => { for (let i = 0; i < node.properties.length; ++i) c(node.properties[i].value, st, "Pattern") } base.Expression = skipThrough base.ThisExpression = base.Super = base.MetaProperty = ignore base.ArrayExpression = (node, st, c) => { for (let i = 0; i < node.elements.length; ++i) { let elt = node.elements[i] if (elt) c(elt, st, "Expression") } } base.ObjectExpression = (node, st, c) => { for (let i = 0; i < node.properties.length; ++i) c(node.properties[i], st) } base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration base.SequenceExpression = base.TemplateLiteral = (node, st, c) => { for (let i = 0; i < node.expressions.length; ++i) c(node.expressions[i], st, "Expression") } base.UnaryExpression = base.UpdateExpression = (node, st, c) => { c(node.argument, st, "Expression") } base.BinaryExpression = base.LogicalExpression = (node, st, c) => { c(node.left, st, "Expression") c(node.right, st, "Expression") } base.AssignmentExpression = base.AssignmentPattern = (node, st, c) => { c(node.left, st, "Pattern") c(node.right, st, "Expression") } base.ConditionalExpression = (node, st, c) => { c(node.test, st, "Expression") c(node.consequent, st, "Expression") c(node.alternate, st, "Expression") } base.NewExpression = base.CallExpression = (node, st, c) => { c(node.callee, st, "Expression") if (node.arguments) for (let i = 0; i < node.arguments.length; ++i) c(node.arguments[i], st, "Expression") } base.MemberExpression = (node, st, c) => { c(node.object, st, "Expression") if (node.computed) c(node.property, st, "Expression") } base.ExportNamedDeclaration = base.ExportDefaultDeclaration = (node, st, c) => { if (node.declaration) c(node.declaration, st, node.type == "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression") if (node.source) c(node.source, st, "Expression") } base.ExportAllDeclaration = (node, st, c) => { c(node.source, st, "Expression") } base.ImportDeclaration = (node, st, c) => { for (let i = 0; i < node.specifiers.length; i++) c(node.specifiers[i], st) c(node.source, st, "Expression") } base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore base.TaggedTemplateExpression = (node, st, c) => { c(node.tag, st, "Expression") c(node.quasi, st) } base.ClassDeclaration = base.ClassExpression = (node, st, c) => c(node, st, "Class") base.Class = (node, st, c) => { if (node.id) c(node.id, st, "Pattern") if (node.superClass) c(node.superClass, st, "Expression") for (let i = 0; i < node.body.body.length; i++) c(node.body.body[i], st) } base.MethodDefinition = base.Property = (node, st, c) => { if (node.computed) c(node.key, st, "Expression") c(node.value, st, "Expression") } base.ComprehensionExpression = (node, st, c) => { for (let i = 0; i < node.blocks.length; i++) c(node.blocks[i].right, st, "Expression") c(node.body, st, "Expression") } ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/src/walk/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,237
```javascript (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}(g.acorn || (g.acorn = {})).walk = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ // AST walker module for Mozilla Parser API compatible trees // A simple walk is one where you simply specify callbacks to be // called on specific nodes. The last two arguments are optional. A // simple use would be // // walk.simple(myTree, { // Expression: function(node) { ... } // }); // // to do something with all expressions. All Parser API node types // can be used to identify node types, as well as Expression, // Statement, and ScopeBody, which denote categories of nodes. // // The base argument can be used to pass a custom (recursive) // walker, and state can be used to give this walked an initial // state. "use strict"; exports.__esModule = true; exports.simple = simple; exports.ancestor = ancestor; exports.recursive = recursive; exports.findNodeAt = findNodeAt; exports.findNodeAround = findNodeAround; exports.findNodeAfter = findNodeAfter; exports.findNodeBefore = findNodeBefore; exports.make = make; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function simple(node, visitors, base, state, override) { if (!base) base = exports.base;(function c(node, st, override) { var type = override || node.type, found = visitors[type]; base[type](node, st, c); if (found) found(node, st); })(node, state, override); } // An ancestor walk builds up an array of ancestor nodes (including // the current node) and passes them to the callback as the state parameter. function ancestor(node, visitors, base, state) { if (!base) base = exports.base; if (!state) state = [];(function c(node, st, override) { var type = override || node.type, found = visitors[type]; if (node != st[st.length - 1]) { st = st.slice(); st.push(node); } base[type](node, st, c); if (found) found(node, st); })(node, state); } // A recursive walk is one where your functions override the default // walkers. They can modify and replace the state parameter that's // threaded through the walk, and can opt how and whether to walk // their child nodes (by calling their third argument on these // nodes). function recursive(node, state, funcs, base, override) { var visitor = funcs ? exports.make(funcs, base) : base;(function c(node, st, override) { visitor[override || node.type](node, st, c); })(node, state, override); } function makeTest(test) { if (typeof test == "string") return function (type) { return type == test; };else if (!test) return function () { return true; };else return test; } var Found = function Found(node, state) { _classCallCheck(this, Found); this.node = node;this.state = state; } // Find a node with a given start, end, and type (all are optional, // null can be used as wildcard). Returns a {node, state} object, or // undefined when it doesn't find a matching node. ; function findNodeAt(node, start, end, test, base, state) { test = makeTest(test); if (!base) base = exports.base; try { ;(function c(node, st, override) { var type = override || node.type; if ((start == null || node.start <= start) && (end == null || node.end >= end)) base[type](node, st, c); if ((start == null || node.start == start) && (end == null || node.end == end) && test(type, node)) throw new Found(node, st); })(node, state); } catch (e) { if (e instanceof Found) return e; throw e; } } // Find the innermost node of a given type that contains the given // position. Interface similar to findNodeAt. function findNodeAround(node, pos, test, base, state) { test = makeTest(test); if (!base) base = exports.base; try { ;(function c(node, st, override) { var type = override || node.type; if (node.start > pos || node.end < pos) return; base[type](node, st, c); if (test(type, node)) throw new Found(node, st); })(node, state); } catch (e) { if (e instanceof Found) return e; throw e; } } // Find the outermost matching node after a given position. function findNodeAfter(node, pos, test, base, state) { test = makeTest(test); if (!base) base = exports.base; try { ;(function c(node, st, override) { if (node.end < pos) return; var type = override || node.type; if (node.start >= pos && test(type, node)) throw new Found(node, st); base[type](node, st, c); })(node, state); } catch (e) { if (e instanceof Found) return e; throw e; } } // Find the outermost matching node before a given position. function findNodeBefore(node, pos, test, base, state) { test = makeTest(test); if (!base) base = exports.base; var max = undefined;(function c(node, st, override) { if (node.start > pos) return; var type = override || node.type; if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node)) max = new Found(node, st); base[type](node, st, c); })(node, state); return max; } // Used to create a custom walker. Will fill in all missing node // type properties with the defaults. function make(funcs, base) { if (!base) base = exports.base; var visitor = {}; for (var type in base) visitor[type] = base[type]; for (var type in funcs) visitor[type] = funcs[type]; return visitor; } function skipThrough(node, st, c) { c(node, st); } function ignore(_node, _st, _c) {} // Node walkers. var base = {}; exports.base = base; base.Program = base.BlockStatement = function (node, st, c) { for (var i = 0; i < node.body.length; ++i) { c(node.body[i], st, "Statement"); } }; base.Statement = skipThrough; base.EmptyStatement = ignore; base.ExpressionStatement = base.ParenthesizedExpression = function (node, st, c) { return c(node.expression, st, "Expression"); }; base.IfStatement = function (node, st, c) { c(node.test, st, "Expression"); c(node.consequent, st, "Statement"); if (node.alternate) c(node.alternate, st, "Statement"); }; base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); }; base.BreakStatement = base.ContinueStatement = ignore; base.WithStatement = function (node, st, c) { c(node.object, st, "Expression"); c(node.body, st, "Statement"); }; base.SwitchStatement = function (node, st, c) { c(node.discriminant, st, "Expression"); for (var i = 0; i < node.cases.length; ++i) { var cs = node.cases[i]; if (cs.test) c(cs.test, st, "Expression"); for (var j = 0; j < cs.consequent.length; ++j) { c(cs.consequent[j], st, "Statement"); } } }; base.ReturnStatement = base.YieldExpression = function (node, st, c) { if (node.argument) c(node.argument, st, "Expression"); }; base.ThrowStatement = base.SpreadElement = function (node, st, c) { return c(node.argument, st, "Expression"); }; base.TryStatement = function (node, st, c) { c(node.block, st, "Statement"); if (node.handler) { c(node.handler.param, st, "Pattern"); c(node.handler.body, st, "ScopeBody"); } if (node.finalizer) c(node.finalizer, st, "Statement"); }; base.WhileStatement = base.DoWhileStatement = function (node, st, c) { c(node.test, st, "Expression"); c(node.body, st, "Statement"); }; base.ForStatement = function (node, st, c) { if (node.init) c(node.init, st, "ForInit"); if (node.test) c(node.test, st, "Expression"); if (node.update) c(node.update, st, "Expression"); c(node.body, st, "Statement"); }; base.ForInStatement = base.ForOfStatement = function (node, st, c) { c(node.left, st, "ForInit"); c(node.right, st, "Expression"); c(node.body, st, "Statement"); }; base.ForInit = function (node, st, c) { if (node.type == "VariableDeclaration") c(node, st);else c(node, st, "Expression"); }; base.DebuggerStatement = ignore; base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); }; base.VariableDeclaration = function (node, st, c) { for (var i = 0; i < node.declarations.length; ++i) { c(node.declarations[i], st); } }; base.VariableDeclarator = function (node, st, c) { c(node.id, st, "Pattern"); if (node.init) c(node.init, st, "Expression"); }; base.Function = function (node, st, c) { if (node.id) c(node.id, st, "Pattern"); for (var i = 0; i < node.params.length; i++) { c(node.params[i], st, "Pattern"); }c(node.body, st, node.expression ? "ScopeExpression" : "ScopeBody"); }; // FIXME drop these node types in next major version // (They are awkward, and in ES6 every block can be a scope.) base.ScopeBody = function (node, st, c) { return c(node, st, "Statement"); }; base.ScopeExpression = function (node, st, c) { return c(node, st, "Expression"); }; base.Pattern = function (node, st, c) { if (node.type == "Identifier") c(node, st, "VariablePattern");else if (node.type == "MemberExpression") c(node, st, "MemberPattern");else c(node, st); }; base.VariablePattern = ignore; base.MemberPattern = skipThrough; base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); }; base.ArrayPattern = function (node, st, c) { for (var i = 0; i < node.elements.length; ++i) { var elt = node.elements[i]; if (elt) c(elt, st, "Pattern"); } }; base.ObjectPattern = function (node, st, c) { for (var i = 0; i < node.properties.length; ++i) { c(node.properties[i].value, st, "Pattern"); } }; base.Expression = skipThrough; base.ThisExpression = base.Super = base.MetaProperty = ignore; base.ArrayExpression = function (node, st, c) { for (var i = 0; i < node.elements.length; ++i) { var elt = node.elements[i]; if (elt) c(elt, st, "Expression"); } }; base.ObjectExpression = function (node, st, c) { for (var i = 0; i < node.properties.length; ++i) { c(node.properties[i], st); } }; base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; base.SequenceExpression = base.TemplateLiteral = function (node, st, c) { for (var i = 0; i < node.expressions.length; ++i) { c(node.expressions[i], st, "Expression"); } }; base.UnaryExpression = base.UpdateExpression = function (node, st, c) { c(node.argument, st, "Expression"); }; base.BinaryExpression = base.LogicalExpression = function (node, st, c) { c(node.left, st, "Expression"); c(node.right, st, "Expression"); }; base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) { c(node.left, st, "Pattern"); c(node.right, st, "Expression"); }; base.ConditionalExpression = function (node, st, c) { c(node.test, st, "Expression"); c(node.consequent, st, "Expression"); c(node.alternate, st, "Expression"); }; base.NewExpression = base.CallExpression = function (node, st, c) { c(node.callee, st, "Expression"); if (node.arguments) for (var i = 0; i < node.arguments.length; ++i) { c(node.arguments[i], st, "Expression"); } }; base.MemberExpression = function (node, st, c) { c(node.object, st, "Expression"); if (node.computed) c(node.property, st, "Expression"); }; base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) { if (node.declaration) c(node.declaration, st, node.type == "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); if (node.source) c(node.source, st, "Expression"); }; base.ExportAllDeclaration = function (node, st, c) { c(node.source, st, "Expression"); }; base.ImportDeclaration = function (node, st, c) { for (var i = 0; i < node.specifiers.length; i++) { c(node.specifiers[i], st); }c(node.source, st, "Expression"); }; base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore; base.TaggedTemplateExpression = function (node, st, c) { c(node.tag, st, "Expression"); c(node.quasi, st); }; base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); }; base.Class = function (node, st, c) { if (node.id) c(node.id, st, "Pattern"); if (node.superClass) c(node.superClass, st, "Expression"); for (var i = 0; i < node.body.body.length; i++) { c(node.body.body[i], st); } }; base.MethodDefinition = base.Property = function (node, st, c) { if (node.computed) c(node.key, st, "Expression"); c(node.value, st, "Expression"); }; base.ComprehensionExpression = function (node, st, c) { for (var i = 0; i < node.blocks.length; i++) { c(node.blocks[i].right, st, "Expression"); }c(node.body, st, "Expression"); }; },{}]},{},[1])(1) }); ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/dist/walk.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,656
```javascript (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}(g.acorn || (g.acorn = {})).loose = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ "use strict"; module.exports = typeof acorn != 'undefined' ? acorn : require("./acorn"); },{}],2:[function(_dereq_,module,exports){ "use strict"; var _state = _dereq_("./state"); var _parseutil = _dereq_("./parseutil"); var _ = _dereq_(".."); var lp = _state.LooseParser.prototype; lp.checkLVal = function (expr) { if (!expr) return expr; switch (expr.type) { case "Identifier": case "MemberExpression": return expr; case "ParenthesizedExpression": expr.expression = this.checkLVal(expr.expression); return expr; default: return this.dummyIdent(); } }; lp.parseExpression = function (noIn) { var start = this.storeCurrentPos(); var expr = this.parseMaybeAssign(noIn); if (this.tok.type === _.tokTypes.comma) { var node = this.startNodeAt(start); node.expressions = [expr]; while (this.eat(_.tokTypes.comma)) node.expressions.push(this.parseMaybeAssign(noIn)); return this.finishNode(node, "SequenceExpression"); } return expr; }; lp.parseParenExpression = function () { this.pushCx(); this.expect(_.tokTypes.parenL); var val = this.parseExpression(); this.popCx(); this.expect(_.tokTypes.parenR); return val; }; lp.parseMaybeAssign = function (noIn) { var start = this.storeCurrentPos(); var left = this.parseMaybeConditional(noIn); if (this.tok.type.isAssign) { var node = this.startNodeAt(start); node.operator = this.tok.value; node.left = this.tok.type === _.tokTypes.eq ? this.toAssignable(left) : this.checkLVal(left); this.next(); node.right = this.parseMaybeAssign(noIn); return this.finishNode(node, "AssignmentExpression"); } return left; }; lp.parseMaybeConditional = function (noIn) { var start = this.storeCurrentPos(); var expr = this.parseExprOps(noIn); if (this.eat(_.tokTypes.question)) { var node = this.startNodeAt(start); node.test = expr; node.consequent = this.parseMaybeAssign(); node.alternate = this.expect(_.tokTypes.colon) ? this.parseMaybeAssign(noIn) : this.dummyIdent(); return this.finishNode(node, "ConditionalExpression"); } return expr; }; lp.parseExprOps = function (noIn) { var start = this.storeCurrentPos(); var indent = this.curIndent, line = this.curLineStart; return this.parseExprOp(this.parseMaybeUnary(noIn), start, -1, noIn, indent, line); }; lp.parseExprOp = function (left, start, minPrec, noIn, indent, line) { if (this.curLineStart != line && this.curIndent < indent && this.tokenStartsLine()) return left; var prec = this.tok.type.binop; if (prec != null && (!noIn || this.tok.type !== _.tokTypes._in)) { if (prec > minPrec) { var node = this.startNodeAt(start); node.left = left; node.operator = this.tok.value; this.next(); if (this.curLineStart != line && this.curIndent < indent && this.tokenStartsLine()) { node.right = this.dummyIdent(); } else { var rightStart = this.storeCurrentPos(); node.right = this.parseExprOp(this.parseMaybeUnary(noIn), rightStart, prec, noIn, indent, line); } this.finishNode(node, /&&|\|\|/.test(node.operator) ? "LogicalExpression" : "BinaryExpression"); return this.parseExprOp(node, start, minPrec, noIn, indent, line); } } return left; }; lp.parseMaybeUnary = function (noIn) { if (this.tok.type.prefix) { var node = this.startNode(), update = this.tok.type === _.tokTypes.incDec; node.operator = this.tok.value; node.prefix = true; this.next(); node.argument = this.parseMaybeUnary(noIn); if (update) node.argument = this.checkLVal(node.argument); return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); } else if (this.tok.type === _.tokTypes.ellipsis) { var node = this.startNode(); this.next(); node.argument = this.parseMaybeUnary(noIn); return this.finishNode(node, "SpreadElement"); } var start = this.storeCurrentPos(); var expr = this.parseExprSubscripts(); while (this.tok.type.postfix && !this.canInsertSemicolon()) { var node = this.startNodeAt(start); node.operator = this.tok.value; node.prefix = false; node.argument = this.checkLVal(expr); this.next(); expr = this.finishNode(node, "UpdateExpression"); } return expr; }; lp.parseExprSubscripts = function () { var start = this.storeCurrentPos(); return this.parseSubscripts(this.parseExprAtom(), start, false, this.curIndent, this.curLineStart); }; lp.parseSubscripts = function (base, start, noCalls, startIndent, line) { for (;;) { if (this.curLineStart != line && this.curIndent <= startIndent && this.tokenStartsLine()) { if (this.tok.type == _.tokTypes.dot && this.curIndent == startIndent) --startIndent;else return base; } if (this.eat(_.tokTypes.dot)) { var node = this.startNodeAt(start); node.object = base; if (this.curLineStart != line && this.curIndent <= startIndent && this.tokenStartsLine()) node.property = this.dummyIdent();else node.property = this.parsePropertyAccessor() || this.dummyIdent(); node.computed = false; base = this.finishNode(node, "MemberExpression"); } else if (this.tok.type == _.tokTypes.bracketL) { this.pushCx(); this.next(); var node = this.startNodeAt(start); node.object = base; node.property = this.parseExpression(); node.computed = true; this.popCx(); this.expect(_.tokTypes.bracketR); base = this.finishNode(node, "MemberExpression"); } else if (!noCalls && this.tok.type == _.tokTypes.parenL) { var node = this.startNodeAt(start); node.callee = base; node.arguments = this.parseExprList(_.tokTypes.parenR); base = this.finishNode(node, "CallExpression"); } else if (this.tok.type == _.tokTypes.backQuote) { var node = this.startNodeAt(start); node.tag = base; node.quasi = this.parseTemplate(); base = this.finishNode(node, "TaggedTemplateExpression"); } else { return base; } } }; lp.parseExprAtom = function () { var node = undefined; switch (this.tok.type) { case _.tokTypes._this: case _.tokTypes._super: var type = this.tok.type === _.tokTypes._this ? "ThisExpression" : "Super"; node = this.startNode(); this.next(); return this.finishNode(node, type); case _.tokTypes.name: var start = this.storeCurrentPos(); var id = this.parseIdent(); return this.eat(_.tokTypes.arrow) ? this.parseArrowExpression(this.startNodeAt(start), [id]) : id; case _.tokTypes.regexp: node = this.startNode(); var val = this.tok.value; node.regex = { pattern: val.pattern, flags: val.flags }; node.value = val.value; node.raw = this.input.slice(this.tok.start, this.tok.end); this.next(); return this.finishNode(node, "Literal"); case _.tokTypes.num:case _.tokTypes.string: node = this.startNode(); node.value = this.tok.value; node.raw = this.input.slice(this.tok.start, this.tok.end); this.next(); return this.finishNode(node, "Literal"); case _.tokTypes._null:case _.tokTypes._true:case _.tokTypes._false: node = this.startNode(); node.value = this.tok.type === _.tokTypes._null ? null : this.tok.type === _.tokTypes._true; node.raw = this.tok.type.keyword; this.next(); return this.finishNode(node, "Literal"); case _.tokTypes.parenL: var parenStart = this.storeCurrentPos(); this.next(); var inner = this.parseExpression(); this.expect(_.tokTypes.parenR); if (this.eat(_.tokTypes.arrow)) { return this.parseArrowExpression(this.startNodeAt(parenStart), inner.expressions || (_parseutil.isDummy(inner) ? [] : [inner])); } if (this.options.preserveParens) { var par = this.startNodeAt(parenStart); par.expression = inner; inner = this.finishNode(par, "ParenthesizedExpression"); } return inner; case _.tokTypes.bracketL: node = this.startNode(); node.elements = this.parseExprList(_.tokTypes.bracketR, true); return this.finishNode(node, "ArrayExpression"); case _.tokTypes.braceL: return this.parseObj(); case _.tokTypes._class: return this.parseClass(); case _.tokTypes._function: node = this.startNode(); this.next(); return this.parseFunction(node, false); case _.tokTypes._new: return this.parseNew(); case _.tokTypes._yield: node = this.startNode(); this.next(); if (this.semicolon() || this.canInsertSemicolon() || this.tok.type != _.tokTypes.star && !this.tok.type.startsExpr) { node.delegate = false; node.argument = null; } else { node.delegate = this.eat(_.tokTypes.star); node.argument = this.parseMaybeAssign(); } return this.finishNode(node, "YieldExpression"); case _.tokTypes.backQuote: return this.parseTemplate(); default: return this.dummyIdent(); } }; lp.parseNew = function () { var node = this.startNode(), startIndent = this.curIndent, line = this.curLineStart; var meta = this.parseIdent(true); if (this.options.ecmaVersion >= 6 && this.eat(_.tokTypes.dot)) { node.meta = meta; node.property = this.parseIdent(true); return this.finishNode(node, "MetaProperty"); } var start = this.storeCurrentPos(); node.callee = this.parseSubscripts(this.parseExprAtom(), start, true, startIndent, line); if (this.tok.type == _.tokTypes.parenL) { node.arguments = this.parseExprList(_.tokTypes.parenR); } else { node.arguments = []; } return this.finishNode(node, "NewExpression"); }; lp.parseTemplateElement = function () { var elem = this.startNode(); elem.value = { raw: this.input.slice(this.tok.start, this.tok.end).replace(/\r\n?/g, '\n'), cooked: this.tok.value }; this.next(); elem.tail = this.tok.type === _.tokTypes.backQuote; return this.finishNode(elem, "TemplateElement"); }; lp.parseTemplate = function () { var node = this.startNode(); this.next(); node.expressions = []; var curElt = this.parseTemplateElement(); node.quasis = [curElt]; while (!curElt.tail) { this.next(); node.expressions.push(this.parseExpression()); if (this.expect(_.tokTypes.braceR)) { curElt = this.parseTemplateElement(); } else { curElt = this.startNode(); curElt.value = { cooked: '', raw: '' }; curElt.tail = true; } node.quasis.push(curElt); } this.expect(_.tokTypes.backQuote); return this.finishNode(node, "TemplateLiteral"); }; lp.parseObj = function () { var node = this.startNode(); node.properties = []; this.pushCx(); var indent = this.curIndent + 1, line = this.curLineStart; this.eat(_.tokTypes.braceL); if (this.curIndent + 1 < indent) { indent = this.curIndent;line = this.curLineStart; } while (!this.closes(_.tokTypes.braceR, indent, line)) { var prop = this.startNode(), isGenerator = undefined, start = undefined; if (this.options.ecmaVersion >= 6) { start = this.storeCurrentPos(); prop.method = false; prop.shorthand = false; isGenerator = this.eat(_.tokTypes.star); } this.parsePropertyName(prop); if (_parseutil.isDummy(prop.key)) { if (_parseutil.isDummy(this.parseMaybeAssign())) this.next();this.eat(_.tokTypes.comma);continue; } if (this.eat(_.tokTypes.colon)) { prop.kind = "init"; prop.value = this.parseMaybeAssign(); } else if (this.options.ecmaVersion >= 6 && (this.tok.type === _.tokTypes.parenL || this.tok.type === _.tokTypes.braceL)) { prop.kind = "init"; prop.method = true; prop.value = this.parseMethod(isGenerator); } else if (this.options.ecmaVersion >= 5 && prop.key.type === "Identifier" && !prop.computed && (prop.key.name === "get" || prop.key.name === "set") && (this.tok.type != _.tokTypes.comma && this.tok.type != _.tokTypes.braceR)) { prop.kind = prop.key.name; this.parsePropertyName(prop); prop.value = this.parseMethod(false); } else { prop.kind = "init"; if (this.options.ecmaVersion >= 6) { if (this.eat(_.tokTypes.eq)) { var assign = this.startNodeAt(start); assign.operator = "="; assign.left = prop.key; assign.right = this.parseMaybeAssign(); prop.value = this.finishNode(assign, "AssignmentExpression"); } else { prop.value = prop.key; } } else { prop.value = this.dummyIdent(); } prop.shorthand = true; } node.properties.push(this.finishNode(prop, "Property")); this.eat(_.tokTypes.comma); } this.popCx(); if (!this.eat(_.tokTypes.braceR)) { // If there is no closing brace, make the node span to the start // of the next token (this is useful for Tern) this.last.end = this.tok.start; if (this.options.locations) this.last.loc.end = this.tok.loc.start; } return this.finishNode(node, "ObjectExpression"); }; lp.parsePropertyName = function (prop) { if (this.options.ecmaVersion >= 6) { if (this.eat(_.tokTypes.bracketL)) { prop.computed = true; prop.key = this.parseExpression(); this.expect(_.tokTypes.bracketR); return; } else { prop.computed = false; } } var key = this.tok.type === _.tokTypes.num || this.tok.type === _.tokTypes.string ? this.parseExprAtom() : this.parseIdent(); prop.key = key || this.dummyIdent(); }; lp.parsePropertyAccessor = function () { if (this.tok.type === _.tokTypes.name || this.tok.type.keyword) return this.parseIdent(); }; lp.parseIdent = function () { var name = this.tok.type === _.tokTypes.name ? this.tok.value : this.tok.type.keyword; if (!name) return this.dummyIdent(); var node = this.startNode(); this.next(); node.name = name; return this.finishNode(node, "Identifier"); }; lp.initFunction = function (node) { node.id = null; node.params = []; if (this.options.ecmaVersion >= 6) { node.generator = false; node.expression = false; } }; // Convert existing expression atom to assignable pattern // if possible. lp.toAssignable = function (node, binding) { if (!node || node.type == "Identifier" || node.type == "MemberExpression" && !binding) { // Okay } else if (node.type == "ParenthesizedExpression") { node.expression = this.toAssignable(node.expression, binding); } else if (this.options.ecmaVersion < 6) { return this.dummyIdent(); } else if (node.type == "ObjectExpression") { node.type = "ObjectPattern"; var props = node.properties; for (var i = 0; i < props.length; i++) { props[i].value = this.toAssignable(props[i].value, binding); } } else if (node.type == "ArrayExpression") { node.type = "ArrayPattern"; this.toAssignableList(node.elements, binding); } else if (node.type == "SpreadElement") { node.type = "RestElement"; node.argument = this.toAssignable(node.argument, binding); } else if (node.type == "AssignmentExpression") { node.type = "AssignmentPattern"; delete node.operator; } else { return this.dummyIdent(); } return node; }; lp.toAssignableList = function (exprList, binding) { for (var i = 0; i < exprList.length; i++) { exprList[i] = this.toAssignable(exprList[i], binding); }return exprList; }; lp.parseFunctionParams = function (params) { params = this.parseExprList(_.tokTypes.parenR); return this.toAssignableList(params, true); }; lp.parseMethod = function (isGenerator) { var node = this.startNode(); this.initFunction(node); node.params = this.parseFunctionParams(); node.generator = isGenerator || false; node.expression = this.options.ecmaVersion >= 6 && this.tok.type !== _.tokTypes.braceL; node.body = node.expression ? this.parseMaybeAssign() : this.parseBlock(); return this.finishNode(node, "FunctionExpression"); }; lp.parseArrowExpression = function (node, params) { this.initFunction(node); node.params = this.toAssignableList(params, true); node.expression = this.tok.type !== _.tokTypes.braceL; node.body = node.expression ? this.parseMaybeAssign() : this.parseBlock(); return this.finishNode(node, "ArrowFunctionExpression"); }; lp.parseExprList = function (close, allowEmpty) { this.pushCx(); var indent = this.curIndent, line = this.curLineStart, elts = []; this.next(); // Opening bracket while (!this.closes(close, indent + 1, line)) { if (this.eat(_.tokTypes.comma)) { elts.push(allowEmpty ? null : this.dummyIdent()); continue; } var elt = this.parseMaybeAssign(); if (_parseutil.isDummy(elt)) { if (this.closes(close, indent, line)) break; this.next(); } else { elts.push(elt); } this.eat(_.tokTypes.comma); } this.popCx(); if (!this.eat(close)) { // If there is no closing brace, make the node span to the start // of the next token (this is useful for Tern) this.last.end = this.tok.start; if (this.options.locations) this.last.loc.end = this.tok.loc.start; } return elts; }; },{"..":1,"./parseutil":4,"./state":5}],3:[function(_dereq_,module,exports){ // Acorn: Loose parser // // This module provides an alternative parser (`parse_dammit`) that // exposes that same interface as `parse`, but will try to parse // anything as JavaScript, repairing syntax error the best it can. // There are circumstances in which it will raise an error and give // up, but they are very rare. The resulting AST will be a mostly // valid JavaScript AST (as per the [Mozilla parser API][api], except // that: // // - Return outside functions is allowed // // - Label consistency (no conflicts, break only to existing labels) // is not enforced. // // - Bogus Identifier nodes with a name of `""` are inserted whenever // the parser got too confused to return anything meaningful. // // [api]: path_to_url // // The expected use for this is to *first* try `acorn.parse`, and only // if that fails switch to `parse_dammit`. The loose parser might // parse badly indented code incorrectly, so **don't** use it as // your default parser. // // Quite a lot of acorn.js is duplicated here. The alternative was to // add a *lot* of extra cruft to that file, making it less readable // and slower. Copying and editing the code allowed me to make // invasive changes and simplifications without creating a complicated // tangle. "use strict"; exports.__esModule = true; exports.parse_dammit = parse_dammit; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } var _ = _dereq_(".."); var acorn = _interopRequireWildcard(_); var _state = _dereq_("./state"); _dereq_("./tokenize"); _dereq_("./statement"); _dereq_("./expression"); exports.LooseParser = _state.LooseParser; exports.pluginsLoose = _state.pluginsLoose; acorn.defaultOptions.tabSize = 4; function parse_dammit(input, options) { var p = new _state.LooseParser(input, options); p.next(); return p.parseTopLevel(); } acorn.parse_dammit = parse_dammit; acorn.LooseParser = _state.LooseParser; acorn.pluginsLoose = _state.pluginsLoose; },{"..":1,"./expression":2,"./state":5,"./statement":6,"./tokenize":7}],4:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; exports.isDummy = isDummy; function isDummy(node) { return node.name == ""; } },{}],5:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _ = _dereq_(".."); // Registered plugins var pluginsLoose = {}; exports.pluginsLoose = pluginsLoose; var LooseParser = (function () { function LooseParser(input, options) { _classCallCheck(this, LooseParser); this.toks = _.tokenizer(input, options); this.options = this.toks.options; this.input = this.toks.input; this.tok = this.last = { type: _.tokTypes.eof, start: 0, end: 0 }; if (this.options.locations) { var here = this.toks.curPosition(); this.tok.loc = new _.SourceLocation(this.toks, here, here); } this.ahead = []; // Tokens ahead this.context = []; // Indentation contexted this.curIndent = 0; this.curLineStart = 0; this.nextLineStart = this.lineEnd(this.curLineStart) + 1; // Load plugins this.options.pluginsLoose = options.pluginsLoose || {}; this.loadPlugins(this.options.pluginsLoose); } LooseParser.prototype.startNode = function startNode() { return new _.Node(this.toks, this.tok.start, this.options.locations ? this.tok.loc.start : null); }; LooseParser.prototype.storeCurrentPos = function storeCurrentPos() { return this.options.locations ? [this.tok.start, this.tok.loc.start] : this.tok.start; }; LooseParser.prototype.startNodeAt = function startNodeAt(pos) { if (this.options.locations) { return new _.Node(this.toks, pos[0], pos[1]); } else { return new _.Node(this.toks, pos); } }; LooseParser.prototype.finishNode = function finishNode(node, type) { node.type = type; node.end = this.last.end; if (this.options.locations) node.loc.end = this.last.loc.end; if (this.options.ranges) node.range[1] = this.last.end; return node; }; LooseParser.prototype.dummyNode = function dummyNode(type) { var dummy = this.startNode(); dummy.type = type; dummy.end = dummy.start; if (this.options.locations) dummy.loc.end = dummy.loc.start; if (this.options.ranges) dummy.range[1] = dummy.start; this.last = { type: _.tokTypes.name, start: dummy.start, end: dummy.start, loc: dummy.loc }; return dummy; }; LooseParser.prototype.dummyIdent = function dummyIdent() { var dummy = this.dummyNode("Identifier"); dummy.name = ""; return dummy; }; LooseParser.prototype.dummyString = function dummyString() { var dummy = this.dummyNode("Literal"); dummy.value = dummy.raw = ""; return dummy; }; LooseParser.prototype.eat = function eat(type) { if (this.tok.type === type) { this.next(); return true; } else { return false; } }; LooseParser.prototype.isContextual = function isContextual(name) { return this.tok.type === _.tokTypes.name && this.tok.value === name; }; LooseParser.prototype.eatContextual = function eatContextual(name) { return this.tok.value === name && this.eat(_.tokTypes.name); }; LooseParser.prototype.canInsertSemicolon = function canInsertSemicolon() { return this.tok.type === _.tokTypes.eof || this.tok.type === _.tokTypes.braceR || _.lineBreak.test(this.input.slice(this.last.end, this.tok.start)); }; LooseParser.prototype.semicolon = function semicolon() { return this.eat(_.tokTypes.semi); }; LooseParser.prototype.expect = function expect(type) { if (this.eat(type)) return true; for (var i = 1; i <= 2; i++) { if (this.lookAhead(i).type == type) { for (var j = 0; j < i; j++) { this.next(); }return true; } } }; LooseParser.prototype.pushCx = function pushCx() { this.context.push(this.curIndent); }; LooseParser.prototype.popCx = function popCx() { this.curIndent = this.context.pop(); }; LooseParser.prototype.lineEnd = function lineEnd(pos) { while (pos < this.input.length && !_.isNewLine(this.input.charCodeAt(pos))) ++pos; return pos; }; LooseParser.prototype.indentationAfter = function indentationAfter(pos) { for (var count = 0;; ++pos) { var ch = this.input.charCodeAt(pos); if (ch === 32) ++count;else if (ch === 9) count += this.options.tabSize;else return count; } }; LooseParser.prototype.closes = function closes(closeTok, indent, line, blockHeuristic) { if (this.tok.type === closeTok || this.tok.type === _.tokTypes.eof) return true; return line != this.curLineStart && this.curIndent < indent && this.tokenStartsLine() && (!blockHeuristic || this.nextLineStart >= this.input.length || this.indentationAfter(this.nextLineStart) < indent); }; LooseParser.prototype.tokenStartsLine = function tokenStartsLine() { for (var p = this.tok.start - 1; p >= this.curLineStart; --p) { var ch = this.input.charCodeAt(p); if (ch !== 9 && ch !== 32) return false; } return true; }; LooseParser.prototype.extend = function extend(name, f) { this[name] = f(this[name]); }; LooseParser.prototype.loadPlugins = function loadPlugins(pluginConfigs) { for (var _name in pluginConfigs) { var plugin = pluginsLoose[_name]; if (!plugin) throw new Error("Plugin '" + _name + "' not found"); plugin(this, pluginConfigs[_name]); } }; return LooseParser; })(); exports.LooseParser = LooseParser; },{"..":1}],6:[function(_dereq_,module,exports){ "use strict"; var _state = _dereq_("./state"); var _parseutil = _dereq_("./parseutil"); var _ = _dereq_(".."); var lp = _state.LooseParser.prototype; lp.parseTopLevel = function () { var node = this.startNodeAt(this.options.locations ? [0, _.getLineInfo(this.input, 0)] : 0); node.body = []; while (this.tok.type !== _.tokTypes.eof) node.body.push(this.parseStatement()); this.last = this.tok; if (this.options.ecmaVersion >= 6) { node.sourceType = this.options.sourceType; } return this.finishNode(node, "Program"); }; lp.parseStatement = function () { var starttype = this.tok.type, node = this.startNode(); switch (starttype) { case _.tokTypes._break:case _.tokTypes._continue: this.next(); var isBreak = starttype === _.tokTypes._break; if (this.semicolon() || this.canInsertSemicolon()) { node.label = null; } else { node.label = this.tok.type === _.tokTypes.name ? this.parseIdent() : null; this.semicolon(); } return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); case _.tokTypes._debugger: this.next(); this.semicolon(); return this.finishNode(node, "DebuggerStatement"); case _.tokTypes._do: this.next(); node.body = this.parseStatement(); node.test = this.eat(_.tokTypes._while) ? this.parseParenExpression() : this.dummyIdent(); this.semicolon(); return this.finishNode(node, "DoWhileStatement"); case _.tokTypes._for: this.next(); this.pushCx(); this.expect(_.tokTypes.parenL); if (this.tok.type === _.tokTypes.semi) return this.parseFor(node, null); if (this.tok.type === _.tokTypes._var || this.tok.type === _.tokTypes._let || this.tok.type === _.tokTypes._const) { var _init = this.parseVar(true); if (_init.declarations.length === 1 && (this.tok.type === _.tokTypes._in || this.isContextual("of"))) { return this.parseForIn(node, _init); } return this.parseFor(node, _init); } var init = this.parseExpression(true); if (this.tok.type === _.tokTypes._in || this.isContextual("of")) return this.parseForIn(node, this.toAssignable(init)); return this.parseFor(node, init); case _.tokTypes._function: this.next(); return this.parseFunction(node, true); case _.tokTypes._if: this.next(); node.test = this.parseParenExpression(); node.consequent = this.parseStatement(); node.alternate = this.eat(_.tokTypes._else) ? this.parseStatement() : null; return this.finishNode(node, "IfStatement"); case _.tokTypes._return: this.next(); if (this.eat(_.tokTypes.semi) || this.canInsertSemicolon()) node.argument = null;else { node.argument = this.parseExpression();this.semicolon(); } return this.finishNode(node, "ReturnStatement"); case _.tokTypes._switch: var blockIndent = this.curIndent, line = this.curLineStart; this.next(); node.discriminant = this.parseParenExpression(); node.cases = []; this.pushCx(); this.expect(_.tokTypes.braceL); var cur = undefined; while (!this.closes(_.tokTypes.braceR, blockIndent, line, true)) { if (this.tok.type === _.tokTypes._case || this.tok.type === _.tokTypes._default) { var isCase = this.tok.type === _.tokTypes._case; if (cur) this.finishNode(cur, "SwitchCase"); node.cases.push(cur = this.startNode()); cur.consequent = []; this.next(); if (isCase) cur.test = this.parseExpression();else cur.test = null; this.expect(_.tokTypes.colon); } else { if (!cur) { node.cases.push(cur = this.startNode()); cur.consequent = []; cur.test = null; } cur.consequent.push(this.parseStatement()); } } if (cur) this.finishNode(cur, "SwitchCase"); this.popCx(); this.eat(_.tokTypes.braceR); return this.finishNode(node, "SwitchStatement"); case _.tokTypes._throw: this.next(); node.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node, "ThrowStatement"); case _.tokTypes._try: this.next(); node.block = this.parseBlock(); node.handler = null; if (this.tok.type === _.tokTypes._catch) { var clause = this.startNode(); this.next(); this.expect(_.tokTypes.parenL); clause.param = this.toAssignable(this.parseExprAtom(), true); this.expect(_.tokTypes.parenR); clause.body = this.parseBlock(); node.handler = this.finishNode(clause, "CatchClause"); } node.finalizer = this.eat(_.tokTypes._finally) ? this.parseBlock() : null; if (!node.handler && !node.finalizer) return node.block; return this.finishNode(node, "TryStatement"); case _.tokTypes._var: case _.tokTypes._let: case _.tokTypes._const: return this.parseVar(); case _.tokTypes._while: this.next(); node.test = this.parseParenExpression(); node.body = this.parseStatement(); return this.finishNode(node, "WhileStatement"); case _.tokTypes._with: this.next(); node.object = this.parseParenExpression(); node.body = this.parseStatement(); return this.finishNode(node, "WithStatement"); case _.tokTypes.braceL: return this.parseBlock(); case _.tokTypes.semi: this.next(); return this.finishNode(node, "EmptyStatement"); case _.tokTypes._class: return this.parseClass(true); case _.tokTypes._import: return this.parseImport(); case _.tokTypes._export: return this.parseExport(); default: var expr = this.parseExpression(); if (_parseutil.isDummy(expr)) { this.next(); if (this.tok.type === _.tokTypes.eof) return this.finishNode(node, "EmptyStatement"); return this.parseStatement(); } else if (starttype === _.tokTypes.name && expr.type === "Identifier" && this.eat(_.tokTypes.colon)) { node.body = this.parseStatement(); node.label = expr; return this.finishNode(node, "LabeledStatement"); } else { node.expression = expr; this.semicolon(); return this.finishNode(node, "ExpressionStatement"); } } }; lp.parseBlock = function () { var node = this.startNode(); this.pushCx(); this.expect(_.tokTypes.braceL); var blockIndent = this.curIndent, line = this.curLineStart; node.body = []; while (!this.closes(_.tokTypes.braceR, blockIndent, line, true)) node.body.push(this.parseStatement()); this.popCx(); this.eat(_.tokTypes.braceR); return this.finishNode(node, "BlockStatement"); }; lp.parseFor = function (node, init) { node.init = init; node.test = node.update = null; if (this.eat(_.tokTypes.semi) && this.tok.type !== _.tokTypes.semi) node.test = this.parseExpression(); if (this.eat(_.tokTypes.semi) && this.tok.type !== _.tokTypes.parenR) node.update = this.parseExpression(); this.popCx(); this.expect(_.tokTypes.parenR); node.body = this.parseStatement(); return this.finishNode(node, "ForStatement"); }; lp.parseForIn = function (node, init) { var type = this.tok.type === _.tokTypes._in ? "ForInStatement" : "ForOfStatement"; this.next(); node.left = init; node.right = this.parseExpression(); this.popCx(); this.expect(_.tokTypes.parenR); node.body = this.parseStatement(); return this.finishNode(node, type); }; lp.parseVar = function (noIn) { var node = this.startNode(); node.kind = this.tok.type.keyword; this.next(); node.declarations = []; do { var decl = this.startNode(); decl.id = this.options.ecmaVersion >= 6 ? this.toAssignable(this.parseExprAtom(), true) : this.parseIdent(); decl.init = this.eat(_.tokTypes.eq) ? this.parseMaybeAssign(noIn) : null; node.declarations.push(this.finishNode(decl, "VariableDeclarator")); } while (this.eat(_.tokTypes.comma)); if (!node.declarations.length) { var decl = this.startNode(); decl.id = this.dummyIdent(); node.declarations.push(this.finishNode(decl, "VariableDeclarator")); } if (!noIn) this.semicolon(); return this.finishNode(node, "VariableDeclaration"); }; lp.parseClass = function (isStatement) { var node = this.startNode(); this.next(); if (this.tok.type === _.tokTypes.name) node.id = this.parseIdent();else if (isStatement) node.id = this.dummyIdent();else node.id = null; node.superClass = this.eat(_.tokTypes._extends) ? this.parseExpression() : null; node.body = this.startNode(); node.body.body = []; this.pushCx(); var indent = this.curIndent + 1, line = this.curLineStart; this.eat(_.tokTypes.braceL); if (this.curIndent + 1 < indent) { indent = this.curIndent;line = this.curLineStart; } while (!this.closes(_.tokTypes.braceR, indent, line)) { if (this.semicolon()) continue; var method = this.startNode(), isGenerator = undefined; if (this.options.ecmaVersion >= 6) { method["static"] = false; isGenerator = this.eat(_.tokTypes.star); } this.parsePropertyName(method); if (_parseutil.isDummy(method.key)) { if (_parseutil.isDummy(this.parseMaybeAssign())) this.next();this.eat(_.tokTypes.comma);continue; } if (method.key.type === "Identifier" && !method.computed && method.key.name === "static" && (this.tok.type != _.tokTypes.parenL && this.tok.type != _.tokTypes.braceL)) { method["static"] = true; isGenerator = this.eat(_.tokTypes.star); this.parsePropertyName(method); } else { method["static"] = false; } if (this.options.ecmaVersion >= 5 && method.key.type === "Identifier" && !method.computed && (method.key.name === "get" || method.key.name === "set") && this.tok.type !== _.tokTypes.parenL && this.tok.type !== _.tokTypes.braceL) { method.kind = method.key.name; this.parsePropertyName(method); method.value = this.parseMethod(false); } else { if (!method.computed && !method["static"] && !isGenerator && (method.key.type === "Identifier" && method.key.name === "constructor" || method.key.type === "Literal" && method.key.value === "constructor")) { method.kind = "constructor"; } else { method.kind = "method"; } method.value = this.parseMethod(isGenerator); } node.body.body.push(this.finishNode(method, "MethodDefinition")); } this.popCx(); if (!this.eat(_.tokTypes.braceR)) { // If there is no closing brace, make the node span to the start // of the next token (this is useful for Tern) this.last.end = this.tok.start; if (this.options.locations) this.last.loc.end = this.tok.loc.start; } this.semicolon(); this.finishNode(node.body, "ClassBody"); return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); }; lp.parseFunction = function (node, isStatement) { this.initFunction(node); if (this.options.ecmaVersion >= 6) { node.generator = this.eat(_.tokTypes.star); } if (this.tok.type === _.tokTypes.name) node.id = this.parseIdent();else if (isStatement) node.id = this.dummyIdent(); node.params = this.parseFunctionParams(); node.body = this.parseBlock(); return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression"); }; lp.parseExport = function () { var node = this.startNode(); this.next(); if (this.eat(_.tokTypes.star)) { node.source = this.eatContextual("from") ? this.parseExprAtom() : null; return this.finishNode(node, "ExportAllDeclaration"); } if (this.eat(_.tokTypes._default)) { var expr = this.parseMaybeAssign(); if (expr.id) { switch (expr.type) { case "FunctionExpression": expr.type = "FunctionDeclaration";break; case "ClassExpression": expr.type = "ClassDeclaration";break; } } node.declaration = expr; this.semicolon(); return this.finishNode(node, "ExportDefaultDeclaration"); } if (this.tok.type.keyword) { node.declaration = this.parseStatement(); node.specifiers = []; node.source = null; } else { node.declaration = null; node.specifiers = this.parseExportSpecifierList(); node.source = this.eatContextual("from") ? this.parseExprAtom() : null; this.semicolon(); } return this.finishNode(node, "ExportNamedDeclaration"); }; lp.parseImport = function () { var node = this.startNode(); this.next(); if (this.tok.type === _.tokTypes.string) { node.specifiers = []; node.source = this.parseExprAtom(); node.kind = ''; } else { var elt = undefined; if (this.tok.type === _.tokTypes.name && this.tok.value !== "from") { elt = this.startNode(); elt.local = this.parseIdent(); this.finishNode(elt, "ImportDefaultSpecifier"); this.eat(_.tokTypes.comma); } node.specifiers = this.parseImportSpecifierList(); node.source = this.eatContextual("from") && this.tok.type == _.tokTypes.string ? this.parseExprAtom() : this.dummyString(); if (elt) node.specifiers.unshift(elt); } this.semicolon(); return this.finishNode(node, "ImportDeclaration"); }; lp.parseImportSpecifierList = function () { var elts = []; if (this.tok.type === _.tokTypes.star) { var elt = this.startNode(); this.next(); if (this.eatContextual("as")) elt.local = this.parseIdent(); elts.push(this.finishNode(elt, "ImportNamespaceSpecifier")); } else { var indent = this.curIndent, line = this.curLineStart, continuedLine = this.nextLineStart; this.pushCx(); this.eat(_.tokTypes.braceL); if (this.curLineStart > continuedLine) continuedLine = this.curLineStart; while (!this.closes(_.tokTypes.braceR, indent + (this.curLineStart <= continuedLine ? 1 : 0), line)) { var elt = this.startNode(); if (this.eat(_.tokTypes.star)) { elt.local = this.eatContextual("as") ? this.parseIdent() : this.dummyIdent(); this.finishNode(elt, "ImportNamespaceSpecifier"); } else { if (this.isContextual("from")) break; elt.imported = this.parseIdent(); if (_parseutil.isDummy(elt.imported)) break; elt.local = this.eatContextual("as") ? this.parseIdent() : elt.imported; this.finishNode(elt, "ImportSpecifier"); } elts.push(elt); this.eat(_.tokTypes.comma); } this.eat(_.tokTypes.braceR); this.popCx(); } return elts; }; lp.parseExportSpecifierList = function () { var elts = []; var indent = this.curIndent, line = this.curLineStart, continuedLine = this.nextLineStart; this.pushCx(); this.eat(_.tokTypes.braceL); if (this.curLineStart > continuedLine) continuedLine = this.curLineStart; while (!this.closes(_.tokTypes.braceR, indent + (this.curLineStart <= continuedLine ? 1 : 0), line)) { if (this.isContextual("from")) break; var elt = this.startNode(); elt.local = this.parseIdent(); if (_parseutil.isDummy(elt.local)) break; elt.exported = this.eatContextual("as") ? this.parseIdent() : elt.local; this.finishNode(elt, "ExportSpecifier"); elts.push(elt); this.eat(_.tokTypes.comma); } this.eat(_.tokTypes.braceR); this.popCx(); return elts; }; },{"..":1,"./parseutil":4,"./state":5}],7:[function(_dereq_,module,exports){ "use strict"; var _ = _dereq_(".."); var _state = _dereq_("./state"); var lp = _state.LooseParser.prototype; function isSpace(ch) { return ch < 14 && ch > 8 || ch === 32 || ch === 160 || _.isNewLine(ch); } lp.next = function () { this.last = this.tok; if (this.ahead.length) this.tok = this.ahead.shift();else this.tok = this.readToken(); if (this.tok.start >= this.nextLineStart) { while (this.tok.start >= this.nextLineStart) { this.curLineStart = this.nextLineStart; this.nextLineStart = this.lineEnd(this.curLineStart) + 1; } this.curIndent = this.indentationAfter(this.curLineStart); } }; lp.readToken = function () { for (;;) { try { this.toks.next(); if (this.toks.type === _.tokTypes.dot && this.input.substr(this.toks.end, 1) === "." && this.options.ecmaVersion >= 6) { this.toks.end++; this.toks.type = _.tokTypes.ellipsis; } return new _.Token(this.toks); } catch (e) { if (!(e instanceof SyntaxError)) throw e; // Try to skip some text, based on the error message, and then continue var msg = e.message, pos = e.raisedAt, replace = true; if (/unterminated/i.test(msg)) { pos = this.lineEnd(e.pos + 1); if (/string/.test(msg)) { replace = { start: e.pos, end: pos, type: _.tokTypes.string, value: this.input.slice(e.pos + 1, pos) }; } else if (/regular expr/i.test(msg)) { var re = this.input.slice(e.pos, pos); try { re = new RegExp(re); } catch (e) {} replace = { start: e.pos, end: pos, type: _.tokTypes.regexp, value: re }; } else if (/template/.test(msg)) { replace = { start: e.pos, end: pos, type: _.tokTypes.template, value: this.input.slice(e.pos, pos) }; } else { replace = false; } } else if (/invalid (unicode|regexp|number)|expecting unicode|octal literal|is reserved|directly after number|expected number in radix/i.test(msg)) { while (pos < this.input.length && !isSpace(this.input.charCodeAt(pos))) ++pos; } else if (/character escape|expected hexadecimal/i.test(msg)) { while (pos < this.input.length) { var ch = this.input.charCodeAt(pos++); if (ch === 34 || ch === 39 || _.isNewLine(ch)) break; } } else if (/unexpected character/i.test(msg)) { pos++; replace = false; } else if (/regular expression/i.test(msg)) { replace = true; } else { throw e; } this.resetTo(pos); if (replace === true) replace = { start: pos, end: pos, type: _.tokTypes.name, value: "" }; if (replace) { if (this.options.locations) replace.loc = new _.SourceLocation(this.toks, _.getLineInfo(this.input, replace.start), _.getLineInfo(this.input, replace.end)); return replace; } } } }; lp.resetTo = function (pos) { this.toks.pos = pos; var ch = this.input.charAt(pos - 1); this.toks.exprAllowed = !ch || /[\[\{\(,;:?\/*=+\-~!|&%^<>]/.test(ch) || /[enwfd]/.test(ch) && /\b(keywords|case|else|return|throw|new|in|(instance|type)of|delete|void)$/.test(this.input.slice(pos - 10, pos)); if (this.options.locations) { this.toks.curLine = 1; this.toks.lineStart = _.lineBreakG.lastIndex = 0; var match = undefined; while ((match = _.lineBreakG.exec(this.input)) && match.index < pos) { ++this.toks.curLine; this.toks.lineStart = match.index + match[0].length; } } }; lp.lookAhead = function (n) { while (n > this.ahead.length) this.ahead.push(this.readToken()); return this.ahead[n - 1]; }; },{"..":1,"./state":5}]},{},[3])(3) }); ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/dist/acorn_loose.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
11,603
```javascript /* jshint node: true */ (function () { "use strict"; function CookieAccessInfo(domain, path, secure, script) { if (this instanceof CookieAccessInfo) { this.domain = domain || undefined; this.path = path || "/"; this.secure = !!secure; this.script = !!script; return this; } return new CookieAccessInfo(domain, path, secure, script); } CookieAccessInfo.All = Object.freeze(Object.create(null)); exports.CookieAccessInfo = CookieAccessInfo; function Cookie(cookiestr, request_domain, request_path) { if (cookiestr instanceof Cookie) { return cookiestr; } if (this instanceof Cookie) { this.name = null; this.value = null; this.expiration_date = Infinity; this.path = String(request_path || "/"); this.explicit_path = false; this.domain = request_domain || null; this.explicit_domain = false; this.secure = false; //how to define default? this.noscript = false; //httponly if (cookiestr) { this.parse(cookiestr, request_domain, request_path); } return this; } return new Cookie(cookiestr, request_domain, request_path); } exports.Cookie = Cookie; Cookie.prototype.toString = function toString() { var str = [this.name + "=" + this.value]; if (this.expiration_date !== Infinity) { str.push("expires=" + (new Date(this.expiration_date)).toGMTString()); } if (this.domain) { str.push("domain=" + this.domain); } if (this.path) { str.push("path=" + this.path); } if (this.secure) { str.push("secure"); } if (this.noscript) { str.push("httponly"); } return str.join("; "); }; Cookie.prototype.toValueString = function toValueString() { return this.name + "=" + this.value; }; var cookie_str_splitter = /[:](?=\s*[a-zA-Z0-9_\-]+\s*[=])/g; Cookie.prototype.parse = function parse(str, request_domain, request_path) { if (this instanceof Cookie) { var parts = str.split(";").filter(function (value) { return !!value; }); var i; var pair = parts[0].match(/([^=]+)=([\s\S]*)/); if (!pair) { console.warn("Invalid cookie header encountered. Header: '"+str+"'"); return; } var key = pair[1]; var value = pair[2]; if ( typeof key !== 'string' || key.length === 0 || typeof value !== 'string' ) { console.warn("Unable to extract values from cookie header. Cookie: '"+str+"'"); return; } this.name = key; this.value = value; for (i = 1; i < parts.length; i += 1) { pair = parts[i].match(/([^=]+)(?:=([\s\S]*))?/); key = pair[1].trim().toLowerCase(); value = pair[2]; switch (key) { case "httponly": this.noscript = true; break; case "expires": this.expiration_date = value ? Number(Date.parse(value)) : Infinity; break; case "path": this.path = value ? value.trim() : ""; this.explicit_path = true; break; case "domain": this.domain = value ? value.trim() : ""; this.explicit_domain = !!this.domain; break; case "secure": this.secure = true; break; } } if (!this.explicit_path) { this.path = request_path || "/"; } if (!this.explicit_domain) { this.domain = request_domain; } return this; } return new Cookie().parse(str, request_domain, request_path); }; Cookie.prototype.matches = function matches(access_info) { if (access_info === CookieAccessInfo.All) { return true; } if (this.noscript && access_info.script || this.secure && !access_info.secure || !this.collidesWith(access_info)) { return false; } return true; }; Cookie.prototype.collidesWith = function collidesWith(access_info) { if ((this.path && !access_info.path) || (this.domain && !access_info.domain)) { return false; } if (this.path && access_info.path.indexOf(this.path) !== 0) { return false; } if (this.explicit_path && access_info.path.indexOf( this.path ) !== 0) { return false; } var access_domain = access_info.domain && access_info.domain.replace(/^[\.]/,''); var cookie_domain = this.domain && this.domain.replace(/^[\.]/,''); if (cookie_domain === access_domain) { return true; } if (cookie_domain) { if (!this.explicit_domain) { return false; // we already checked if the domains were exactly the same } var wildcard = access_domain.indexOf(cookie_domain); if (wildcard === -1 || wildcard !== access_domain.length - cookie_domain.length) { return false; } return true; } return true; }; function CookieJar() { var cookies, cookies_list, collidable_cookie; if (this instanceof CookieJar) { cookies = Object.create(null); //name: [Cookie] this.setCookie = function setCookie(cookie, request_domain, request_path) { var remove, i; cookie = new Cookie(cookie, request_domain, request_path); //Delete the cookie if the set is past the current time remove = cookie.expiration_date <= Date.now(); if (cookies[cookie.name] !== undefined) { cookies_list = cookies[cookie.name]; for (i = 0; i < cookies_list.length; i += 1) { collidable_cookie = cookies_list[i]; if (collidable_cookie.collidesWith(cookie)) { if (remove) { cookies_list.splice(i, 1); if (cookies_list.length === 0) { delete cookies[cookie.name]; } return false; } cookies_list[i] = cookie; return cookie; } } if (remove) { return false; } cookies_list.push(cookie); return cookie; } if (remove) { return false; } cookies[cookie.name] = [cookie]; return cookies[cookie.name]; }; //returns a cookie this.getCookie = function getCookie(cookie_name, access_info) { var cookie, i; cookies_list = cookies[cookie_name]; if (!cookies_list) { return; } for (i = 0; i < cookies_list.length; i += 1) { cookie = cookies_list[i]; if (cookie.expiration_date <= Date.now()) { if (cookies_list.length === 0) { delete cookies[cookie.name]; } continue; } if (cookie.matches(access_info)) { return cookie; } } }; //returns a list of cookies this.getCookies = function getCookies(access_info) { var matches = [], cookie_name, cookie; for (cookie_name in cookies) { cookie = this.getCookie(cookie_name, access_info); if (cookie) { matches.push(cookie); } } matches.toString = function toString() { return matches.join(":"); }; matches.toValueString = function toValueString() { return matches.map(function (c) { return c.toValueString(); }).join('; '); }; return matches; }; return this; } return new CookieJar(); } exports.CookieJar = CookieJar; //returns list of cookies that were set correctly. Cookies that are expired and removed are not returned. CookieJar.prototype.setCookies = function setCookies(cookies, request_domain, request_path) { cookies = Array.isArray(cookies) ? cookies : cookies.split(cookie_str_splitter); var successful = [], i, cookie; cookies = cookies.map(function(item){ return new Cookie(item, request_domain, request_path); }); for (i = 0; i < cookies.length; i += 1) { cookie = cookies[i]; if (this.setCookie(cookie, request_domain, request_path)) { successful.push(cookie); } } return successful; }; }()); ```
/content/code_sandbox/node_modules/cookiejar/cookiejar.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,895
```javascript var Stream = require('stream').Stream; var util = require('util'); module.exports = DelayedStream; function DelayedStream() { this.source = null; this.dataSize = 0; this.maxDataSize = 1024 * 1024; this.pauseStream = true; this._maxDataSizeExceeded = false; this._released = false; this._bufferedEvents = []; } util.inherits(DelayedStream, Stream); DelayedStream.create = function(source, options) { var delayedStream = new this(); options = options || {}; for (var option in options) { delayedStream[option] = options[option]; } delayedStream.source = source; var realEmit = source.emit; source.emit = function() { delayedStream._handleEmit(arguments); return realEmit.apply(source, arguments); }; source.on('error', function() {}); if (delayedStream.pauseStream) { source.pause(); } return delayedStream; }; Object.defineProperty(DelayedStream.prototype, 'readable', { configurable: true, enumerable: true, get: function() { return this.source.readable; } }); DelayedStream.prototype.setEncoding = function() { return this.source.setEncoding.apply(this.source, arguments); }; DelayedStream.prototype.resume = function() { if (!this._released) { this.release(); } this.source.resume(); }; DelayedStream.prototype.pause = function() { this.source.pause(); }; DelayedStream.prototype.release = function() { this._released = true; this._bufferedEvents.forEach(function(args) { this.emit.apply(this, args); }.bind(this)); this._bufferedEvents = []; }; DelayedStream.prototype.pipe = function() { var r = Stream.prototype.pipe.apply(this, arguments); this.resume(); return r; }; DelayedStream.prototype._handleEmit = function(args) { if (this._released) { this.emit.apply(this, args); return; } if (args[0] === 'data') { this.dataSize += args[1].length; this._checkIfMaxDataSizeExceeded(); } this._bufferedEvents.push(args); }; DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { if (this._maxDataSizeExceeded) { return; } if (this.dataSize <= this.maxDataSize) { return; } this._maxDataSizeExceeded = true; var message = 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' this.emit('error', new Error(message)); }; ```
/content/code_sandbox/node_modules/delayed-stream/lib/delayed_stream.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
578
```javascript /*! * statuses */ 'use strict' /** * Module dependencies. * @private */ var codes = require('./codes.json') /** * Module exports. * @public */ module.exports = status // status code to message map status.message = codes // status message (lower-case) to code map status.code = createMessageToStatusCodeMap(codes) // array of status codes status.codes = createStatusCodeList(codes) // status codes for redirects status.redirect = { 300: true, 301: true, 302: true, 303: true, 305: true, 307: true, 308: true } // status codes for empty bodies status.empty = { 204: true, 205: true, 304: true } // status codes for when you should retry the request status.retry = { 502: true, 503: true, 504: true } /** * Create a map of message to status code. * @private */ function createMessageToStatusCodeMap (codes) { var map = {} Object.keys(codes).forEach(function forEachCode (code) { var message = codes[code] var status = Number(code) // populate map map[message.toLowerCase()] = status }) return map } /** * Create a list of all status codes. * @private */ function createStatusCodeList (codes) { return Object.keys(codes).map(function mapCode (code) { return Number(code) }) } /** * Get the status code for given message. * @private */ function getStatusCode (message) { var msg = message.toLowerCase() if (!Object.prototype.hasOwnProperty.call(status.code, msg)) { throw new Error('invalid status message: "' + message + '"') } return status.code[msg] } /** * Get the status message for given code. * @private */ function getStatusMessage (code) { if (!Object.prototype.hasOwnProperty.call(status.message, code)) { throw new Error('invalid status code: ' + code) } return status.message[code] } /** * Get the status code. * * Given a number, this will throw if it is not a known status * code, otherwise the code will be returned. Given a string, * the string will be parsed for a number and return the code * if valid, otherwise will lookup the code assuming this is * the status message. * * @param {string|number} code * @returns {number} * @public */ function status (code) { if (typeof code === 'number') { return getStatusMessage(code) } if (typeof code !== 'string') { throw new TypeError('code must be a number or string') } // '403' var n = parseInt(code, 10) if (!isNaN(n)) { return getStatusMessage(n) } return getStatusCode(code) } ```
/content/code_sandbox/node_modules/statuses/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
635
```javascript /*! * mime-db */ /** * Module exports. */ module.exports = require('./db.json') ```
/content/code_sandbox/node_modules/mime-db/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
21
```javascript 'use strict'; // modified from path_to_url var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var slice = Array.prototype.slice; var isArgs = require('./isArguments'); var hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'); var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var blacklistedKeys = { $console: true, $frame: true, $frameElement: true, $frames: true, $parent: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { try { if (!blacklistedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; var keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = (function () { // Safari 5.0 bug return (Object.keys(arguments) || '').length === 2; }(1, 2)); if (!keysWorksWithArguments) { var originalKeys = Object.keys; Object.keys = function keys(object) { if (isArgs(object)) { return originalKeys(slice.call(object)); } else { return originalKeys(object); } }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; module.exports = keysShim; ```
/content/code_sandbox/node_modules/object-keys/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
883
```javascript 'use strict'; var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; ```
/content/code_sandbox/node_modules/object-keys/isArguments.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
107
```javascript 'use strict'; require('./isArguments'); require('./shim'); ```
/content/code_sandbox/node_modules/object-keys/test/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
14
```javascript /*! * http-errors */ 'use strict' /** * Module dependencies. * @private */ var deprecate = require('depd')('http-errors') var setPrototypeOf = require('setprototypeof') var statuses = require('statuses') var inherits = require('inherits') var toIdentifier = require('toidentifier') /** * Module exports. * @public */ module.exports = createError module.exports.HttpError = createHttpErrorConstructor() module.exports.isHttpError = createIsHttpErrorFunction(module.exports.HttpError) // Populate exports for all constructors populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) /** * Get the code class of a status code. * @private */ function codeClass (status) { return Number(String(status).charAt(0) + '00') } /** * Create a new HTTP Error. * * @returns {Error} * @public */ function createError () { // so much arity going on ~_~ var err var msg var status = 500 var props = {} for (var i = 0; i < arguments.length; i++) { var arg = arguments[i] var type = typeof arg if (type === 'object' && arg instanceof Error) { err = arg status = err.status || err.statusCode || status } else if (type === 'number' && i === 0) { status = arg } else if (type === 'string') { msg = arg } else if (type === 'object') { props = arg } else { throw new TypeError('argument #' + (i + 1) + ' unsupported type ' + type) } } if (typeof status === 'number' && (status < 400 || status >= 600)) { deprecate('non-error status code; use only 4xx or 5xx status codes') } if (typeof status !== 'number' || (!statuses.message[status] && (status < 400 || status >= 600))) { status = 500 } // constructor var HttpError = createError[status] || createError[codeClass(status)] if (!err) { // create error err = HttpError ? new HttpError(msg) : new Error(msg || statuses.message[status]) Error.captureStackTrace(err, createError) } if (!HttpError || !(err instanceof HttpError) || err.status !== status) { // add properties to generic error err.expose = status < 500 err.status = err.statusCode = status } for (var key in props) { if (key !== 'status' && key !== 'statusCode') { err[key] = props[key] } } return err } /** * Create HTTP error abstract base class. * @private */ function createHttpErrorConstructor () { function HttpError () { throw new TypeError('cannot construct abstract class') } inherits(HttpError, Error) return HttpError } /** * Create a constructor for a client error. * @private */ function createClientErrorConstructor (HttpError, name, code) { var className = toClassName(name) function ClientError (message) { // create the error object var msg = message != null ? message : statuses.message[code] var err = new Error(msg) // capture a stack trace to the construction point Error.captureStackTrace(err, ClientError) // adjust the [[Prototype]] setPrototypeOf(err, ClientError.prototype) // redefine the error message Object.defineProperty(err, 'message', { enumerable: true, configurable: true, value: msg, writable: true }) // redefine the error name Object.defineProperty(err, 'name', { enumerable: false, configurable: true, value: className, writable: true }) return err } inherits(ClientError, HttpError) nameFunc(ClientError, className) ClientError.prototype.status = code ClientError.prototype.statusCode = code ClientError.prototype.expose = true return ClientError } /** * Create function to test is a value is a HttpError. * @private */ function createIsHttpErrorFunction (HttpError) { return function isHttpError (val) { if (!val || typeof val !== 'object') { return false } if (val instanceof HttpError) { return true } return val instanceof Error && typeof val.expose === 'boolean' && typeof val.statusCode === 'number' && val.status === val.statusCode } } /** * Create a constructor for a server error. * @private */ function createServerErrorConstructor (HttpError, name, code) { var className = toClassName(name) function ServerError (message) { // create the error object var msg = message != null ? message : statuses.message[code] var err = new Error(msg) // capture a stack trace to the construction point Error.captureStackTrace(err, ServerError) // adjust the [[Prototype]] setPrototypeOf(err, ServerError.prototype) // redefine the error message Object.defineProperty(err, 'message', { enumerable: true, configurable: true, value: msg, writable: true }) // redefine the error name Object.defineProperty(err, 'name', { enumerable: false, configurable: true, value: className, writable: true }) return err } inherits(ServerError, HttpError) nameFunc(ServerError, className) ServerError.prototype.status = code ServerError.prototype.statusCode = code ServerError.prototype.expose = false return ServerError } /** * Set the name of a function, if possible. * @private */ function nameFunc (func, name) { var desc = Object.getOwnPropertyDescriptor(func, 'name') if (desc && desc.configurable) { desc.value = name Object.defineProperty(func, 'name', desc) } } /** * Populate the exports object with constructors for every error class. * @private */ function populateConstructorExports (exports, codes, HttpError) { codes.forEach(function forEachCode (code) { var CodeError var name = toIdentifier(statuses.message[code]) switch (codeClass(code)) { case 400: CodeError = createClientErrorConstructor(HttpError, name, code) break case 500: CodeError = createServerErrorConstructor(HttpError, name, code) break } if (CodeError) { // export the constructor exports[code] = CodeError exports[name] = CodeError } }) } /** * Get a class name from a name identifier. * @private */ function toClassName (name) { return name.substr(-5) !== 'Error' ? name + 'Error' : name } ```
/content/code_sandbox/node_modules/http-errors/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,503
```javascript "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; const get_uri_1 = __importDefault(require("get-uri")); const url_1 = require("url"); const agent_1 = __importDefault(require("./agent")); function createPacProxyAgent(uri, opts) { // was an options object passed in first? if (typeof uri === 'object') { opts = uri; // result of a url.parse() call? if (opts.href) { if (opts.path && !opts.pathname) { opts.pathname = opts.path; } opts.slashes = true; uri = url_1.format(opts); } else { uri = opts.uri; } } if (!opts) { opts = {}; } if (typeof uri !== 'string') { throw new TypeError('a PAC file URI must be specified!'); } return new agent_1.default(uri, opts); } (function (createPacProxyAgent) { createPacProxyAgent.PacProxyAgent = agent_1.default; /** * Supported "protocols". Delegates out to the `get-uri` module. */ createPacProxyAgent.protocols = Object.keys(get_uri_1.default.protocols); createPacProxyAgent.prototype = agent_1.default.prototype; })(createPacProxyAgent || (createPacProxyAgent = {})); module.exports = createPacProxyAgent; //# sourceMappingURL=index.js.map ```
/content/code_sandbox/node_modules/pac-proxy-agent/dist/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
334
```javascript "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()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const net_1 = __importDefault(require("net")); const tls_1 = __importDefault(require("tls")); const once_1 = __importDefault(require("@tootallnate/once")); const crypto_1 = __importDefault(require("crypto")); const get_uri_1 = __importDefault(require("get-uri")); const debug_1 = __importDefault(require("debug")); const raw_body_1 = __importDefault(require("raw-body")); const url_1 = require("url"); const http_proxy_agent_1 = require("http-proxy-agent"); const https_proxy_agent_1 = require("https-proxy-agent"); const socks_proxy_agent_1 = require("socks-proxy-agent"); const pac_resolver_1 = __importDefault(require("pac-resolver")); const agent_base_1 = require("agent-base"); const debug = debug_1.default('pac-proxy-agent'); /** * The `PacProxyAgent` class. * * A few different "protocol" modes are supported (supported protocols are * backed by the `get-uri` module): * * - "pac+data", "data" - refers to an embedded "data:" URI * - "pac+file", "file" - refers to a local file * - "pac+ftp", "ftp" - refers to a file located on an FTP server * - "pac+http", "http" - refers to an HTTP endpoint * - "pac+https", "https" - refers to an HTTPS endpoint * * @api public */ class PacProxyAgent extends agent_base_1.Agent { constructor(uri, opts = {}) { super(opts); this.clearResolverPromise = () => { this.resolverPromise = undefined; }; debug('Creating PacProxyAgent with URI %o and options %o', uri, opts); // Strip the "pac+" prefix this.uri = uri.replace(/^pac\+/i, ''); this.opts = Object.assign({}, opts); this.cache = undefined; this.resolver = undefined; this.resolverHash = ''; this.resolverPromise = undefined; // For `PacResolver` if (!this.opts.filename) { this.opts.filename = uri; } } /** * Loads the PAC proxy file from the source if necessary, and returns * a generated `FindProxyForURL()` resolver function to use. * * @api private */ getResolver() { if (!this.resolverPromise) { this.resolverPromise = this.loadResolver(); this.resolverPromise.then(this.clearResolverPromise, this.clearResolverPromise); } return this.resolverPromise; } loadResolver() { return __awaiter(this, void 0, void 0, function* () { try { // (Re)load the contents of the PAC file URI const code = yield this.loadPacFile(); // Create a sha1 hash of the JS code const hash = crypto_1.default .createHash('sha1') .update(code) .digest('hex'); if (this.resolver && this.resolverHash === hash) { debug('Same sha1 hash for code - contents have not changed, reusing previous proxy resolver'); return this.resolver; } // Cache the resolver debug('Creating new proxy resolver instance'); this.resolver = pac_resolver_1.default(code, this.opts); // Store that sha1 hash for future comparison purposes this.resolverHash = hash; return this.resolver; } catch (err) { if (this.resolver && err.code === 'ENOTMODIFIED') { debug('Got ENOTMODIFIED response, reusing previous proxy resolver'); return this.resolver; } throw err; } }); } /** * Loads the contents of the PAC proxy file. * * @api private */ loadPacFile() { return __awaiter(this, void 0, void 0, function* () { debug('Loading PAC file: %o', this.uri); const rs = yield get_uri_1.default(this.uri, { cache: this.cache }); debug('Got `Readable` instance for URI'); this.cache = rs; const buf = yield raw_body_1.default(rs); debug('Read %o byte PAC file from URI', buf.length); return buf.toString('utf8'); }); } /** * Called when the node-core HTTP client library is creating a new HTTP request. * * @api protected */ callback(req, opts) { return __awaiter(this, void 0, void 0, function* () { const { secureEndpoint } = opts; // First, get a generated `FindProxyForURL()` function, // either cached or retrieved from the source const resolver = yield this.getResolver(); // Calculate the `url` parameter const defaultPort = secureEndpoint ? 443 : 80; let path = req.path; let search = null; const firstQuestion = path.indexOf('?'); if (firstQuestion !== -1) { search = path.substring(firstQuestion); path = path.substring(0, firstQuestion); } const urlOpts = Object.assign(Object.assign({}, opts), { protocol: secureEndpoint ? 'https:' : 'http:', pathname: path, search, // need to use `hostname` instead of `host` otherwise `port` is ignored hostname: opts.host, host: null, href: null, // set `port` to null when it is the protocol default port (80 / 443) port: defaultPort === opts.port ? null : opts.port }); const url = url_1.format(urlOpts); debug('url: %o', url); let result = yield resolver(url); // Default to "DIRECT" if a falsey value was returned (or nothing) if (!result) { result = 'DIRECT'; } const proxies = String(result) .trim() .split(/\s*;\s*/g) .filter(Boolean); if (this.opts.fallbackToDirect && !proxies.includes('DIRECT')) { proxies.push('DIRECT'); } for (const proxy of proxies) { let agent = null; let socket = null; const [type, target] = proxy.split(/\s+/); debug('Attempting to use proxy: %o', proxy); if (type === 'DIRECT') { // Direct connection to the destination endpoint socket = secureEndpoint ? tls_1.default.connect(opts) : net_1.default.connect(opts); } else if (type === 'SOCKS' || type === 'SOCKS5') { // Use a SOCKSv5h proxy agent = new socks_proxy_agent_1.SocksProxyAgent(`socks://${target}`); } else if (type === 'SOCKS4') { // Use a SOCKSv4a proxy agent = new socks_proxy_agent_1.SocksProxyAgent(`socks4a://${target}`); } else if (type === 'PROXY' || type === 'HTTP' || type === 'HTTPS') { // Use an HTTP or HTTPS proxy // path_to_url const proxyURL = `${type === 'HTTPS' ? 'https' : 'http'}://${target}`; const proxyOpts = Object.assign(Object.assign({}, this.opts), url_1.parse(proxyURL)); if (secureEndpoint) { agent = new https_proxy_agent_1.HttpsProxyAgent(proxyOpts); } else { agent = new http_proxy_agent_1.HttpProxyAgent(proxyOpts); } } try { if (socket) { // "DIRECT" connection, wait for connection confirmation yield once_1.default(socket, 'connect'); req.emit('proxy', { proxy, socket }); return socket; } if (agent) { const s = yield agent.callback(req, opts); req.emit('proxy', { proxy, socket: s }); return s; } throw new Error(`Could not determine proxy type for: ${proxy}`); } catch (err) { debug('Got error for proxy %o: %o', proxy, err); req.emit('proxy', { proxy, error: err }); } } throw new Error(`Failed to establish a socket connection to proxies: ${JSON.stringify(proxies)}`); }); } } exports.default = PacProxyAgent; //# sourceMappingURL=agent.js.map ```
/content/code_sandbox/node_modules/pac-proxy-agent/dist/agent.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,046
```javascript // Generated by LiveScript 1.4.0 (function(){ var ref$, any, all, isItNaN, types, defaultType, customTypes, toString$ = {}.toString; ref$ = require('prelude-ls'), any = ref$.any, all = ref$.all, isItNaN = ref$.isItNaN; types = { Number: { typeOf: 'Number', validate: function(it){ return !isItNaN(it); } }, NaN: { typeOf: 'Number', validate: isItNaN }, Int: { typeOf: 'Number', validate: function(it){ return !isItNaN(it) && it % 1 === 0; } }, Float: { typeOf: 'Number', validate: function(it){ return !isItNaN(it); } }, Date: { typeOf: 'Date', validate: function(it){ return !isItNaN(it.getTime()); } } }; defaultType = { array: 'Array', tuple: 'Array' }; function checkArray(input, type){ return all(function(it){ return checkMultiple(it, type.of); }, input); } function checkTuple(input, type){ var i, i$, ref$, len$, types; i = 0; for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) { types = ref$[i$]; if (!checkMultiple(input[i], types)) { return false; } i++; } return input.length <= i; } function checkFields(input, type){ var inputKeys, numInputKeys, k, numOfKeys, key, ref$, types; inputKeys = {}; numInputKeys = 0; for (k in input) { inputKeys[k] = true; numInputKeys++; } numOfKeys = 0; for (key in ref$ = type.of) { types = ref$[key]; if (!checkMultiple(input[key], types)) { return false; } if (inputKeys[key]) { numOfKeys++; } } return type.subset || numInputKeys === numOfKeys; } function checkStructure(input, type){ if (!(input instanceof Object)) { return false; } switch (type.structure) { case 'fields': return checkFields(input, type); case 'array': return checkArray(input, type); case 'tuple': return checkTuple(input, type); } } function check(input, typeObj){ var type, structure, setting, that; type = typeObj.type, structure = typeObj.structure; if (type) { if (type === '*') { return true; } setting = customTypes[type] || types[type]; if (setting) { return setting.typeOf === toString$.call(input).slice(8, -1) && setting.validate(input); } else { return type === toString$.call(input).slice(8, -1) && (!structure || checkStructure(input, typeObj)); } } else if (structure) { if (that = defaultType[structure]) { if (that !== toString$.call(input).slice(8, -1)) { return false; } } return checkStructure(input, typeObj); } else { throw new Error("No type defined. Input: " + input + "."); } } function checkMultiple(input, types){ if (toString$.call(types).slice(8, -1) !== 'Array') { throw new Error("Types must be in an array. Input: " + input + "."); } return any(function(it){ return check(input, it); }, types); } module.exports = function(parsedType, input, options){ options == null && (options = {}); customTypes = options.customTypes || {}; return checkMultiple(input, parsedType); }; }).call(this); ```
/content/code_sandbox/node_modules/type-check/lib/check.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
898
```javascript // Generated by LiveScript 1.4.0 (function(){ var VERSION, parseType, parsedTypeCheck, typeCheck; VERSION = '0.3.2'; parseType = require('./parse-type'); parsedTypeCheck = require('./check'); typeCheck = function(type, input, options){ return parsedTypeCheck(parseType(type), input, options); }; module.exports = { VERSION: VERSION, typeCheck: typeCheck, parsedTypeCheck: parsedTypeCheck, parseType: parseType }; }).call(this); ```
/content/code_sandbox/node_modules/type-check/lib/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
122
```javascript // Generated by LiveScript 1.4.0 (function(){ var identifierRegex, tokenRegex; identifierRegex = /[\$\w]+/; function peek(tokens){ var token; token = tokens[0]; if (token == null) { throw new Error('Unexpected end of input.'); } return token; } function consumeIdent(tokens){ var token; token = peek(tokens); if (!identifierRegex.test(token)) { throw new Error("Expected text, got '" + token + "' instead."); } return tokens.shift(); } function consumeOp(tokens, op){ var token; token = peek(tokens); if (token !== op) { throw new Error("Expected '" + op + "', got '" + token + "' instead."); } return tokens.shift(); } function maybeConsumeOp(tokens, op){ var token; token = tokens[0]; if (token === op) { return tokens.shift(); } else { return null; } } function consumeArray(tokens){ var types; consumeOp(tokens, '['); if (peek(tokens) === ']') { throw new Error("Must specify type of Array - eg. [Type], got [] instead."); } types = consumeTypes(tokens); consumeOp(tokens, ']'); return { structure: 'array', of: types }; } function consumeTuple(tokens){ var components; components = []; consumeOp(tokens, '('); if (peek(tokens) === ')') { throw new Error("Tuple must be of at least length 1 - eg. (Type), got () instead."); } for (;;) { components.push(consumeTypes(tokens)); maybeConsumeOp(tokens, ','); if (')' === peek(tokens)) { break; } } consumeOp(tokens, ')'); return { structure: 'tuple', of: components }; } function consumeFields(tokens){ var fields, subset, ref$, key, types; fields = {}; consumeOp(tokens, '{'); subset = false; for (;;) { if (maybeConsumeOp(tokens, '...')) { subset = true; break; } ref$ = consumeField(tokens), key = ref$[0], types = ref$[1]; fields[key] = types; maybeConsumeOp(tokens, ','); if ('}' === peek(tokens)) { break; } } consumeOp(tokens, '}'); return { structure: 'fields', of: fields, subset: subset }; } function consumeField(tokens){ var key, types; key = consumeIdent(tokens); consumeOp(tokens, ':'); types = consumeTypes(tokens); return [key, types]; } function maybeConsumeStructure(tokens){ switch (tokens[0]) { case '[': return consumeArray(tokens); case '(': return consumeTuple(tokens); case '{': return consumeFields(tokens); } } function consumeType(tokens){ var token, wildcard, type, structure; token = peek(tokens); wildcard = token === '*'; if (wildcard || identifierRegex.test(token)) { type = wildcard ? consumeOp(tokens, '*') : consumeIdent(tokens); structure = maybeConsumeStructure(tokens); if (structure) { return structure.type = type, structure; } else { return { type: type }; } } else { structure = maybeConsumeStructure(tokens); if (!structure) { throw new Error("Unexpected character: " + token); } return structure; } } function consumeTypes(tokens){ var lookahead, types, typesSoFar, typeObj, type; if ('::' === peek(tokens)) { throw new Error("No comment before comment separator '::' found."); } lookahead = tokens[1]; if (lookahead != null && lookahead === '::') { tokens.shift(); tokens.shift(); } types = []; typesSoFar = {}; if ('Maybe' === peek(tokens)) { tokens.shift(); types = [ { type: 'Undefined' }, { type: 'Null' } ]; typesSoFar = { Undefined: true, Null: true }; } for (;;) { typeObj = consumeType(tokens), type = typeObj.type; if (!typesSoFar[type]) { types.push(typeObj); } typesSoFar[type] = true; if (!maybeConsumeOp(tokens, '|')) { break; } } return types; } tokenRegex = RegExp('\\.\\.\\.|::|->|' + identifierRegex.source + '|\\S', 'g'); module.exports = function(input){ var tokens, e; if (!input.length) { throw new Error('No type specified.'); } tokens = input.match(tokenRegex) || []; if (in$('->', tokens)) { throw new Error("Function types are not supported.\ To validate that something is a function, you may use 'Function'."); } try { return consumeTypes(tokens); } catch (e$) { e = e$; throw new Error(e.message + " - Remaining tokens: " + JSON.stringify(tokens) + " - Initial input: '" + input + "'"); } }; function in$(x, xs){ var i = -1, l = xs.length >>> 0; while (++i < l) if (x === xs[i]) return true; return false; } }).call(this); ```
/content/code_sandbox/node_modules/type-check/lib/parse-type.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,230
```javascript "use strict"; module.exports = CSSselect; var Pseudos = require("./lib/pseudos.js"), DomUtils = require("domutils"), findOne = DomUtils.findOne, findAll = DomUtils.findAll, getChildren = DomUtils.getChildren, removeSubsets = DomUtils.removeSubsets, falseFunc = require("boolbase").falseFunc, compile = require("./lib/compile.js"), compileUnsafe = compile.compileUnsafe, compileToken = compile.compileToken; function getSelectorFunc(searchFunc){ return function select(query, elems, options){ if(typeof query !== "function") query = compileUnsafe(query, options, elems); if(!Array.isArray(elems)) elems = getChildren(elems); else elems = removeSubsets(elems); return searchFunc(query, elems); }; } var selectAll = getSelectorFunc(function selectAll(query, elems){ return (query === falseFunc || !elems || elems.length === 0) ? [] : findAll(query, elems); }); var selectOne = getSelectorFunc(function selectOne(query, elems){ return (query === falseFunc || !elems || elems.length === 0) ? null : findOne(query, elems); }); function is(elem, query, options){ return (typeof query === "function" ? query : compile(query, options))(elem); } /* the exported interface */ function CSSselect(query, elems, options){ return selectAll(query, elems, options); } CSSselect.compile = compile; CSSselect.filters = Pseudos.filters; CSSselect.pseudos = Pseudos.pseudos; CSSselect.selectAll = selectAll; CSSselect.selectOne = selectOne; CSSselect.is = is; //legacy methods (might be removed) CSSselect.parse = compile; CSSselect.iterate = selectAll; //hooks CSSselect._compileUnsafe = compileUnsafe; CSSselect._compileToken = compileToken; ```
/content/code_sandbox/node_modules/css-select/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
403
```javascript (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.acorn = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ // A recursive descent parser operates by defining functions for all // syntactic elements, and recursively calling those, each function // advancing the input stream and returning an AST node. Precedence // of constructs (for example, the fact that `!x[1]` means `!(x[1])` // instead of `(!x)[1]` is handled by the fact that the parser // function that parses unary prefix operators is called first, and // in turn calls the function that parses `[]` subscripts that // way, it'll receive the node for `x[1]` already parsed, and wraps // *that* in the unary operator node. // // Acorn uses an [operator precedence parser][opp] to handle binary // operator precedence, because it is much more compact than using // the technique outlined above, which uses different, nesting // functions to specify precedence, for all of the ten binary // precedence levels that JavaScript defines. // // [opp]: path_to_url "use strict"; var _tokentype = _dereq_("./tokentype"); var _state = _dereq_("./state"); var pp = _state.Parser.prototype; // Check if property name clashes with already added. // Object/class getters and setters are not allowed to clash // either with each other or with an init property and in // strict mode, init properties are also not allowed to be repeated. pp.checkPropClash = function (prop, propHash) { if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) return; var key = prop.key;var name = undefined; switch (key.type) { case "Identifier": name = key.name;break; case "Literal": name = String(key.value);break; default: return; } var kind = prop.kind; if (this.options.ecmaVersion >= 6) { if (name === "__proto__" && kind === "init") { if (propHash.proto) this.raise(key.start, "Redefinition of __proto__ property"); propHash.proto = true; } return; } name = "$" + name; var other = propHash[name]; if (other) { var isGetSet = kind !== "init"; if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) this.raise(key.start, "Redefinition of property"); } else { other = propHash[name] = { init: false, get: false, set: false }; } other[kind] = true; }; // ### Expression parsing // These nest, from the most general expression type at the top to // 'atomic', nondivisible expression types at the bottom. Most of // the functions will simply let the function(s) below them parse, // and, *if* the syntactic construct they handle is present, wrap // the AST node that the inner parser gave them in another node. // Parse a full expression. The optional arguments are used to // forbid the `in` operator (in for loops initalization expressions) // and provide reference for storing '=' operator inside shorthand // property assignment in contexts where both object expression // and object pattern might appear (so it's possible to raise // delayed syntax error at correct position). pp.parseExpression = function (noIn, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeAssign(noIn, refDestructuringErrors); if (this.type === _tokentype.types.comma) { var node = this.startNodeAt(startPos, startLoc); node.expressions = [expr]; while (this.eat(_tokentype.types.comma)) node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors)); return this.finishNode(node, "SequenceExpression"); } return expr; }; // Parse an assignment expression. This includes applications of // operators like `+=`. pp.parseMaybeAssign = function (noIn, refDestructuringErrors, afterLeftParse) { if (this.type == _tokentype.types._yield && this.inGenerator) return this.parseYield(); var validateDestructuring = false; if (!refDestructuringErrors) { refDestructuringErrors = { shorthandAssign: 0, trailingComma: 0 }; validateDestructuring = true; } var startPos = this.start, startLoc = this.startLoc; if (this.type == _tokentype.types.parenL || this.type == _tokentype.types.name) this.potentialArrowAt = this.start; var left = this.parseMaybeConditional(noIn, refDestructuringErrors); if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc); if (this.type.isAssign) { if (validateDestructuring) this.checkPatternErrors(refDestructuringErrors, true); var node = this.startNodeAt(startPos, startLoc); node.operator = this.value; node.left = this.type === _tokentype.types.eq ? this.toAssignable(left) : left; refDestructuringErrors.shorthandAssign = 0; // reset because shorthand default was used correctly this.checkLVal(left); this.next(); node.right = this.parseMaybeAssign(noIn); return this.finishNode(node, "AssignmentExpression"); } else { if (validateDestructuring) this.checkExpressionErrors(refDestructuringErrors, true); } return left; }; // Parse a ternary conditional (`?:`) operator. pp.parseMaybeConditional = function (noIn, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprOps(noIn, refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors)) return expr; if (this.eat(_tokentype.types.question)) { var node = this.startNodeAt(startPos, startLoc); node.test = expr; node.consequent = this.parseMaybeAssign(); this.expect(_tokentype.types.colon); node.alternate = this.parseMaybeAssign(noIn); return this.finishNode(node, "ConditionalExpression"); } return expr; }; // Start the precedence parser. pp.parseExprOps = function (noIn, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeUnary(refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors)) return expr; return this.parseExprOp(expr, startPos, startLoc, -1, noIn); }; // Parse binary operators with the operator precedence parsing // algorithm. `left` is the left-hand side of the operator. // `minPrec` provides context that allows the function to stop and // defer further parser to one of its callers when it encounters an // operator that has a lower precedence than the set it is parsing. pp.parseExprOp = function (left, leftStartPos, leftStartLoc, minPrec, noIn) { var prec = this.type.binop; if (prec != null && (!noIn || this.type !== _tokentype.types._in)) { if (prec > minPrec) { var node = this.startNodeAt(leftStartPos, leftStartLoc); node.left = left; node.operator = this.value; var op = this.type; this.next(); var startPos = this.start, startLoc = this.startLoc; node.right = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec, noIn); this.finishNode(node, op === _tokentype.types.logicalOR || op === _tokentype.types.logicalAND ? "LogicalExpression" : "BinaryExpression"); return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn); } } return left; }; // Parse unary operators, both prefix and postfix. pp.parseMaybeUnary = function (refDestructuringErrors) { if (this.type.prefix) { var node = this.startNode(), update = this.type === _tokentype.types.incDec; node.operator = this.value; node.prefix = true; this.next(); node.argument = this.parseMaybeUnary(); this.checkExpressionErrors(refDestructuringErrors, true); if (update) this.checkLVal(node.argument);else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") this.raise(node.start, "Deleting local variable in strict mode"); return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); } var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprSubscripts(refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors)) return expr; while (this.type.postfix && !this.canInsertSemicolon()) { var node = this.startNodeAt(startPos, startLoc); node.operator = this.value; node.prefix = false; node.argument = expr; this.checkLVal(expr); this.next(); expr = this.finishNode(node, "UpdateExpression"); } return expr; }; // Parse call, dot, and `[]`-subscript expressions. pp.parseExprSubscripts = function (refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprAtom(refDestructuringErrors); var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")"; if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) return expr; return this.parseSubscripts(expr, startPos, startLoc); }; pp.parseSubscripts = function (base, startPos, startLoc, noCalls) { for (;;) { if (this.eat(_tokentype.types.dot)) { var node = this.startNodeAt(startPos, startLoc); node.object = base; node.property = this.parseIdent(true); node.computed = false; base = this.finishNode(node, "MemberExpression"); } else if (this.eat(_tokentype.types.bracketL)) { var node = this.startNodeAt(startPos, startLoc); node.object = base; node.property = this.parseExpression(); node.computed = true; this.expect(_tokentype.types.bracketR); base = this.finishNode(node, "MemberExpression"); } else if (!noCalls && this.eat(_tokentype.types.parenL)) { var node = this.startNodeAt(startPos, startLoc); node.callee = base; node.arguments = this.parseExprList(_tokentype.types.parenR, false); base = this.finishNode(node, "CallExpression"); } else if (this.type === _tokentype.types.backQuote) { var node = this.startNodeAt(startPos, startLoc); node.tag = base; node.quasi = this.parseTemplate(); base = this.finishNode(node, "TaggedTemplateExpression"); } else { return base; } } }; // Parse an atomic expression either a single token that is an // expression, an expression started by a keyword like `function` or // `new`, or an expression wrapped in punctuation like `()`, `[]`, // or `{}`. pp.parseExprAtom = function (refDestructuringErrors) { var node = undefined, canBeArrow = this.potentialArrowAt == this.start; switch (this.type) { case _tokentype.types._super: if (!this.inFunction) this.raise(this.start, "'super' outside of function or class"); case _tokentype.types._this: var type = this.type === _tokentype.types._this ? "ThisExpression" : "Super"; node = this.startNode(); this.next(); return this.finishNode(node, type); case _tokentype.types._yield: if (this.inGenerator) this.unexpected(); case _tokentype.types.name: var startPos = this.start, startLoc = this.startLoc; var id = this.parseIdent(this.type !== _tokentype.types.name); if (canBeArrow && !this.canInsertSemicolon() && this.eat(_tokentype.types.arrow)) return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id]); return id; case _tokentype.types.regexp: var value = this.value; node = this.parseLiteral(value.value); node.regex = { pattern: value.pattern, flags: value.flags }; return node; case _tokentype.types.num:case _tokentype.types.string: return this.parseLiteral(this.value); case _tokentype.types._null:case _tokentype.types._true:case _tokentype.types._false: node = this.startNode(); node.value = this.type === _tokentype.types._null ? null : this.type === _tokentype.types._true; node.raw = this.type.keyword; this.next(); return this.finishNode(node, "Literal"); case _tokentype.types.parenL: return this.parseParenAndDistinguishExpression(canBeArrow); case _tokentype.types.bracketL: node = this.startNode(); this.next(); // check whether this is array comprehension or regular array if (this.options.ecmaVersion >= 7 && this.type === _tokentype.types._for) { return this.parseComprehension(node, false); } node.elements = this.parseExprList(_tokentype.types.bracketR, true, true, refDestructuringErrors); return this.finishNode(node, "ArrayExpression"); case _tokentype.types.braceL: return this.parseObj(false, refDestructuringErrors); case _tokentype.types._function: node = this.startNode(); this.next(); return this.parseFunction(node, false); case _tokentype.types._class: return this.parseClass(this.startNode(), false); case _tokentype.types._new: return this.parseNew(); case _tokentype.types.backQuote: return this.parseTemplate(); default: this.unexpected(); } }; pp.parseLiteral = function (value) { var node = this.startNode(); node.value = value; node.raw = this.input.slice(this.start, this.end); this.next(); return this.finishNode(node, "Literal"); }; pp.parseParenExpression = function () { this.expect(_tokentype.types.parenL); var val = this.parseExpression(); this.expect(_tokentype.types.parenR); return val; }; pp.parseParenAndDistinguishExpression = function (canBeArrow) { var startPos = this.start, startLoc = this.startLoc, val = undefined; if (this.options.ecmaVersion >= 6) { this.next(); if (this.options.ecmaVersion >= 7 && this.type === _tokentype.types._for) { return this.parseComprehension(this.startNodeAt(startPos, startLoc), true); } var innerStartPos = this.start, innerStartLoc = this.startLoc; var exprList = [], first = true; var refDestructuringErrors = { shorthandAssign: 0, trailingComma: 0 }, spreadStart = undefined, innerParenStart = undefined; while (this.type !== _tokentype.types.parenR) { first ? first = false : this.expect(_tokentype.types.comma); if (this.type === _tokentype.types.ellipsis) { spreadStart = this.start; exprList.push(this.parseParenItem(this.parseRest())); break; } else { if (this.type === _tokentype.types.parenL && !innerParenStart) { innerParenStart = this.start; } exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); } } var innerEndPos = this.start, innerEndLoc = this.startLoc; this.expect(_tokentype.types.parenR); if (canBeArrow && !this.canInsertSemicolon() && this.eat(_tokentype.types.arrow)) { this.checkPatternErrors(refDestructuringErrors, true); if (innerParenStart) this.unexpected(innerParenStart); return this.parseParenArrowList(startPos, startLoc, exprList); } if (!exprList.length) this.unexpected(this.lastTokStart); if (spreadStart) this.unexpected(spreadStart); this.checkExpressionErrors(refDestructuringErrors, true); if (exprList.length > 1) { val = this.startNodeAt(innerStartPos, innerStartLoc); val.expressions = exprList; this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); } else { val = exprList[0]; } } else { val = this.parseParenExpression(); } if (this.options.preserveParens) { var par = this.startNodeAt(startPos, startLoc); par.expression = val; return this.finishNode(par, "ParenthesizedExpression"); } else { return val; } }; pp.parseParenItem = function (item) { return item; }; pp.parseParenArrowList = function (startPos, startLoc, exprList) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList); }; // New's precedence is slightly tricky. It must allow its argument to // be a `[]` or dot subscript expression, but not a call at least, // not without wrapping it in parentheses. Thus, it uses the noCalls // argument to parseSubscripts to prevent it from consuming the // argument list. var empty = []; pp.parseNew = function () { var node = this.startNode(); var meta = this.parseIdent(true); if (this.options.ecmaVersion >= 6 && this.eat(_tokentype.types.dot)) { node.meta = meta; node.property = this.parseIdent(true); if (node.property.name !== "target") this.raise(node.property.start, "The only valid meta property for new is new.target"); if (!this.inFunction) this.raise(node.start, "new.target can only be used in functions"); return this.finishNode(node, "MetaProperty"); } var startPos = this.start, startLoc = this.startLoc; node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); if (this.eat(_tokentype.types.parenL)) node.arguments = this.parseExprList(_tokentype.types.parenR, false);else node.arguments = empty; return this.finishNode(node, "NewExpression"); }; // Parse template expression. pp.parseTemplateElement = function () { var elem = this.startNode(); elem.value = { raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, '\n'), cooked: this.value }; this.next(); elem.tail = this.type === _tokentype.types.backQuote; return this.finishNode(elem, "TemplateElement"); }; pp.parseTemplate = function () { var node = this.startNode(); this.next(); node.expressions = []; var curElt = this.parseTemplateElement(); node.quasis = [curElt]; while (!curElt.tail) { this.expect(_tokentype.types.dollarBraceL); node.expressions.push(this.parseExpression()); this.expect(_tokentype.types.braceR); node.quasis.push(curElt = this.parseTemplateElement()); } this.next(); return this.finishNode(node, "TemplateLiteral"); }; // Parse an object literal or binding pattern. pp.parseObj = function (isPattern, refDestructuringErrors) { var node = this.startNode(), first = true, propHash = {}; node.properties = []; this.next(); while (!this.eat(_tokentype.types.braceR)) { if (!first) { this.expect(_tokentype.types.comma); if (this.afterTrailingComma(_tokentype.types.braceR)) break; } else first = false; var prop = this.startNode(), isGenerator = undefined, startPos = undefined, startLoc = undefined; if (this.options.ecmaVersion >= 6) { prop.method = false; prop.shorthand = false; if (isPattern || refDestructuringErrors) { startPos = this.start; startLoc = this.startLoc; } if (!isPattern) isGenerator = this.eat(_tokentype.types.star); } this.parsePropertyName(prop); this.parsePropertyValue(prop, isPattern, isGenerator, startPos, startLoc, refDestructuringErrors); this.checkPropClash(prop, propHash); node.properties.push(this.finishNode(prop, "Property")); } return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression"); }; pp.parsePropertyValue = function (prop, isPattern, isGenerator, startPos, startLoc, refDestructuringErrors) { if (this.eat(_tokentype.types.colon)) { prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); prop.kind = "init"; } else if (this.options.ecmaVersion >= 6 && this.type === _tokentype.types.parenL) { if (isPattern) this.unexpected(); prop.kind = "init"; prop.method = true; prop.value = this.parseMethod(isGenerator); } else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type != _tokentype.types.comma && this.type != _tokentype.types.braceR)) { if (isGenerator || isPattern) this.unexpected(); prop.kind = prop.key.name; this.parsePropertyName(prop); prop.value = this.parseMethod(false); var paramCount = prop.kind === "get" ? 0 : 1; if (prop.value.params.length !== paramCount) { var start = prop.value.start; if (prop.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param"); } if (prop.kind === "set" && prop.value.params[0].type === "RestElement") this.raise(prop.value.params[0].start, "Setter cannot use rest params"); } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { prop.kind = "init"; if (isPattern) { if (this.keywords.test(prop.key.name) || (this.strict ? this.reservedWordsStrictBind : this.reservedWords).test(prop.key.name)) this.raise(prop.key.start, "Binding " + prop.key.name); prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); } else if (this.type === _tokentype.types.eq && refDestructuringErrors) { if (!refDestructuringErrors.shorthandAssign) refDestructuringErrors.shorthandAssign = this.start; prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); } else { prop.value = prop.key; } prop.shorthand = true; } else this.unexpected(); }; pp.parsePropertyName = function (prop) { if (this.options.ecmaVersion >= 6) { if (this.eat(_tokentype.types.bracketL)) { prop.computed = true; prop.key = this.parseMaybeAssign(); this.expect(_tokentype.types.bracketR); return prop.key; } else { prop.computed = false; } } return prop.key = this.type === _tokentype.types.num || this.type === _tokentype.types.string ? this.parseExprAtom() : this.parseIdent(true); }; // Initialize empty function node. pp.initFunction = function (node) { node.id = null; if (this.options.ecmaVersion >= 6) { node.generator = false; node.expression = false; } }; // Parse object or class method. pp.parseMethod = function (isGenerator) { var node = this.startNode(); this.initFunction(node); this.expect(_tokentype.types.parenL); node.params = this.parseBindingList(_tokentype.types.parenR, false, false); if (this.options.ecmaVersion >= 6) node.generator = isGenerator; this.parseFunctionBody(node, false); return this.finishNode(node, "FunctionExpression"); }; // Parse arrow function expression with given parameters. pp.parseArrowExpression = function (node, params) { this.initFunction(node); node.params = this.toAssignableList(params, true); this.parseFunctionBody(node, true); return this.finishNode(node, "ArrowFunctionExpression"); }; // Parse function body and check parameters. pp.parseFunctionBody = function (node, isArrowFunction) { var isExpression = isArrowFunction && this.type !== _tokentype.types.braceL; if (isExpression) { node.body = this.parseMaybeAssign(); node.expression = true; } else { // Start a new scope with regard to labels and the `inFunction` // flag (restore them to their old value afterwards). var oldInFunc = this.inFunction, oldInGen = this.inGenerator, oldLabels = this.labels; this.inFunction = true;this.inGenerator = node.generator;this.labels = []; node.body = this.parseBlock(true); node.expression = false; this.inFunction = oldInFunc;this.inGenerator = oldInGen;this.labels = oldLabels; } // If this is a strict mode function, verify that argument names // are not repeated, and it does not try to bind the words `eval` // or `arguments`. if (this.strict || !isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) { var oldStrict = this.strict; this.strict = true; if (node.id) this.checkLVal(node.id, true); this.checkParams(node); this.strict = oldStrict; } else if (isArrowFunction) { this.checkParams(node); } }; // Checks function params for various disallowed patterns such as using "eval" // or "arguments" and duplicate parameters. pp.checkParams = function (node) { var nameHash = {}; for (var i = 0; i < node.params.length; i++) { this.checkLVal(node.params[i], true, nameHash); } }; // Parses a comma-separated list of expressions, and returns them as // an array. `close` is the token type that ends the list, and // `allowEmpty` can be turned on to allow subsequent commas with // nothing in between them to be parsed as `null` (which is needed // for array literals). pp.parseExprList = function (close, allowTrailingComma, allowEmpty, refDestructuringErrors) { var elts = [], first = true; while (!this.eat(close)) { if (!first) { this.expect(_tokentype.types.comma); if (this.type === close && refDestructuringErrors && !refDestructuringErrors.trailingComma) { refDestructuringErrors.trailingComma = this.lastTokStart; } if (allowTrailingComma && this.afterTrailingComma(close)) break; } else first = false; var elt = undefined; if (allowEmpty && this.type === _tokentype.types.comma) elt = null;else if (this.type === _tokentype.types.ellipsis) elt = this.parseSpread(refDestructuringErrors);else elt = this.parseMaybeAssign(false, refDestructuringErrors); elts.push(elt); } return elts; }; // Parse the next token as an identifier. If `liberal` is true (used // when parsing properties), it will also convert keywords into // identifiers. pp.parseIdent = function (liberal) { var node = this.startNode(); if (liberal && this.options.allowReserved == "never") liberal = false; if (this.type === _tokentype.types.name) { if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).test(this.value) && (this.options.ecmaVersion >= 6 || this.input.slice(this.start, this.end).indexOf("\\") == -1)) this.raise(this.start, "The keyword '" + this.value + "' is reserved"); node.name = this.value; } else if (liberal && this.type.keyword) { node.name = this.type.keyword; } else { this.unexpected(); } this.next(); return this.finishNode(node, "Identifier"); }; // Parses yield expression inside generator. pp.parseYield = function () { var node = this.startNode(); this.next(); if (this.type == _tokentype.types.semi || this.canInsertSemicolon() || this.type != _tokentype.types.star && !this.type.startsExpr) { node.delegate = false; node.argument = null; } else { node.delegate = this.eat(_tokentype.types.star); node.argument = this.parseMaybeAssign(); } return this.finishNode(node, "YieldExpression"); }; // Parses array and generator comprehensions. pp.parseComprehension = function (node, isGenerator) { node.blocks = []; while (this.type === _tokentype.types._for) { var block = this.startNode(); this.next(); this.expect(_tokentype.types.parenL); block.left = this.parseBindingAtom(); this.checkLVal(block.left, true); this.expectContextual("of"); block.right = this.parseExpression(); this.expect(_tokentype.types.parenR); node.blocks.push(this.finishNode(block, "ComprehensionBlock")); } node.filter = this.eat(_tokentype.types._if) ? this.parseParenExpression() : null; node.body = this.parseExpression(); this.expect(isGenerator ? _tokentype.types.parenR : _tokentype.types.bracketR); node.generator = isGenerator; return this.finishNode(node, "ComprehensionExpression"); }; },{"./state":10,"./tokentype":14}],2:[function(_dereq_,module,exports){ // This is a trick taken from Esprima. It turns out that, on // non-Chrome browsers, to check whether a string is in a set, a // predicate containing a big ugly `switch` statement is faster than // a regular expression, and on Chrome the two are about on par. // This function uses `eval` (non-lexical) to produce such a // predicate from a space-separated string of words. // // It starts by sorting the words by length. // Reserved word lists for various dialects of the language "use strict"; exports.__esModule = true; exports.isIdentifierStart = isIdentifierStart; exports.isIdentifierChar = isIdentifierChar; var reservedWords = { 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", 5: "class enum extends super const export import", 6: "enum", strict: "implements interface let package private protected public static yield", strictBind: "eval arguments" }; exports.reservedWords = reservedWords; // And the keywords var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; var keywords = { 5: ecma5AndLessKeywords, 6: ecma5AndLessKeywords + " let const class extends export import yield super" }; exports.keywords = keywords; // ## Character categories // Big ugly regular expressions that match characters in the // whitespace, identifier, and identifier-start categories. These // are only applied when a character is found to actually have a // code point above 128. // Generated by `bin/generate-identifier-regex.js`. var nonASCIIidentifierStartChars = "-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"; var nonASCIIidentifierChars = "-------------------------------------------------------------------------------------------------------------------------------------------------"; var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; // These are a run-length and offset encoded representation of the // >0xffff code points that are a valid part of identifiers. The // offset starts at 0x10000, and each pair of numbers represents an // offset to the next range, and then a size of the range. They were // generated by tools/generate-identifier-regex.js var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 17, 26, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 99, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 98, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 26, 45, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 955, 52, 76, 44, 33, 24, 27, 35, 42, 34, 4, 0, 13, 47, 15, 3, 22, 0, 38, 17, 2, 24, 133, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 32, 4, 287, 47, 21, 1, 2, 0, 185, 46, 82, 47, 21, 0, 60, 42, 502, 63, 32, 0, 449, 56, 1288, 920, 104, 110, 2962, 1070, 13266, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 881, 68, 12, 0, 67, 12, 16481, 1, 3071, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 4149, 196, 1340, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42710, 42, 4148, 12, 221, 16355, 541]; var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 1306, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 52, 0, 13, 2, 49, 13, 16, 9, 83, 11, 168, 11, 6, 9, 8, 2, 57, 0, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 316, 19, 13, 9, 214, 6, 3, 8, 112, 16, 16, 9, 82, 12, 9, 9, 535, 9, 20855, 9, 135, 4, 60, 6, 26, 9, 1016, 45, 17, 3, 19723, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 4305, 6, 792618, 239]; // This has a complexity linear to the value of the code. The // assumption is that looking up astral identifier characters is // rare. function isInAstralSet(code, set) { var pos = 0x10000; for (var i = 0; i < set.length; i += 2) { pos += set[i]; if (pos > code) return false; pos += set[i + 1]; if (pos >= code) return true; } } // Test whether a given character code starts an identifier. function isIdentifierStart(code, astral) { if (code < 65) return code === 36; if (code < 91) return true; if (code < 97) return code === 95; if (code < 123) return true; if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); if (astral === false) return false; return isInAstralSet(code, astralIdentifierStartCodes); } // Test whether a given character is part of an identifier. function isIdentifierChar(code, astral) { if (code < 48) return code === 36; if (code < 58) return true; if (code < 65) return false; if (code < 91) return true; if (code < 97) return code === 95; if (code < 123) return true; if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); if (astral === false) return false; return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); } },{}],3:[function(_dereq_,module,exports){ // Acorn is a tiny, fast JavaScript parser written in JavaScript. // // Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and // various contributors and released under an MIT license. // // Git repositories for Acorn are available at // // path_to_url // path_to_url // // Please use the [github bug tracker][ghbt] to report issues. // // [ghbt]: path_to_url // // This file defines the main parser interface. The library also comes // with a [error-tolerant parser][dammit] and an // [abstract syntax tree walker][walk], defined in other files. // // [dammit]: acorn_loose.js // [walk]: util/walk.js "use strict"; exports.__esModule = true; exports.parse = parse; exports.parseExpressionAt = parseExpressionAt; exports.tokenizer = tokenizer; var _state = _dereq_("./state"); _dereq_("./parseutil"); _dereq_("./statement"); _dereq_("./lval"); _dereq_("./expression"); _dereq_("./location"); exports.Parser = _state.Parser; exports.plugins = _state.plugins; var _options = _dereq_("./options"); exports.defaultOptions = _options.defaultOptions; var _locutil = _dereq_("./locutil"); exports.Position = _locutil.Position; exports.SourceLocation = _locutil.SourceLocation; exports.getLineInfo = _locutil.getLineInfo; var _node = _dereq_("./node"); exports.Node = _node.Node; var _tokentype = _dereq_("./tokentype"); exports.TokenType = _tokentype.TokenType; exports.tokTypes = _tokentype.types; var _tokencontext = _dereq_("./tokencontext"); exports.TokContext = _tokencontext.TokContext; exports.tokContexts = _tokencontext.types; var _identifier = _dereq_("./identifier"); exports.isIdentifierChar = _identifier.isIdentifierChar; exports.isIdentifierStart = _identifier.isIdentifierStart; var _tokenize = _dereq_("./tokenize"); exports.Token = _tokenize.Token; var _whitespace = _dereq_("./whitespace"); exports.isNewLine = _whitespace.isNewLine; exports.lineBreak = _whitespace.lineBreak; exports.lineBreakG = _whitespace.lineBreakG; var version = "2.7.0"; exports.version = version; // The main exported interface (under `self.acorn` when in the // browser) is a `parse` function that takes a code string and // returns an abstract syntax tree as specified by [Mozilla parser // API][api]. // // [api]: path_to_url function parse(input, options) { return new _state.Parser(options, input).parse(); } // This function tries to parse a single expression at a given // offset in a string. Useful for parsing mixed-language formats // that embed JavaScript expressions. function parseExpressionAt(input, pos, options) { var p = new _state.Parser(options, input, pos); p.nextToken(); return p.parseExpression(); } // Acorn is organized as a tokenizer and a recursive-descent parser. // The `tokenizer` export provides an interface to the tokenizer. function tokenizer(input, options) { return new _state.Parser(options, input); } },{"./expression":1,"./identifier":2,"./location":4,"./locutil":5,"./lval":6,"./node":7,"./options":8,"./parseutil":9,"./state":10,"./statement":11,"./tokencontext":12,"./tokenize":13,"./tokentype":14,"./whitespace":16}],4:[function(_dereq_,module,exports){ "use strict"; var _state = _dereq_("./state"); var _locutil = _dereq_("./locutil"); var pp = _state.Parser.prototype; // This function is used to raise exceptions on parse errors. It // takes an offset integer (into the current `input`) to indicate // the location of the error, attaches the position to the end // of the error message, and then raises a `SyntaxError` with that // message. pp.raise = function (pos, message) { var loc = _locutil.getLineInfo(this.input, pos); message += " (" + loc.line + ":" + loc.column + ")"; var err = new SyntaxError(message); err.pos = pos;err.loc = loc;err.raisedAt = this.pos; throw err; }; pp.curPosition = function () { if (this.options.locations) { return new _locutil.Position(this.curLine, this.pos - this.lineStart); } }; },{"./locutil":5,"./state":10}],5:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; exports.getLineInfo = getLineInfo; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _whitespace = _dereq_("./whitespace"); // These are used when `options.locations` is on, for the // `startLoc` and `endLoc` properties. var Position = (function () { function Position(line, col) { _classCallCheck(this, Position); this.line = line; this.column = col; } Position.prototype.offset = function offset(n) { return new Position(this.line, this.column + n); }; return Position; })(); exports.Position = Position; var SourceLocation = function SourceLocation(p, start, end) { _classCallCheck(this, SourceLocation); this.start = start; this.end = end; if (p.sourceFile !== null) this.source = p.sourceFile; } // The `getLineInfo` function is mostly useful when the // `locations` option is off (for performance reasons) and you // want to find the line/column position for a given character // offset. `input` should be the code string that the offset refers // into. ; exports.SourceLocation = SourceLocation; function getLineInfo(input, offset) { for (var line = 1, cur = 0;;) { _whitespace.lineBreakG.lastIndex = cur; var match = _whitespace.lineBreakG.exec(input); if (match && match.index < offset) { ++line; cur = match.index + match[0].length; } else { return new Position(line, offset - cur); } } } },{"./whitespace":16}],6:[function(_dereq_,module,exports){ "use strict"; var _tokentype = _dereq_("./tokentype"); var _state = _dereq_("./state"); var _util = _dereq_("./util"); var pp = _state.Parser.prototype; // Convert existing expression atom to assignable pattern // if possible. pp.toAssignable = function (node, isBinding) { if (this.options.ecmaVersion >= 6 && node) { switch (node.type) { case "Identifier": case "ObjectPattern": case "ArrayPattern": break; case "ObjectExpression": node.type = "ObjectPattern"; for (var i = 0; i < node.properties.length; i++) { var prop = node.properties[i]; if (prop.kind !== "init") this.raise(prop.key.start, "Object pattern can't contain getter or setter"); this.toAssignable(prop.value, isBinding); } break; case "ArrayExpression": node.type = "ArrayPattern"; this.toAssignableList(node.elements, isBinding); break; case "AssignmentExpression": if (node.operator === "=") { node.type = "AssignmentPattern"; delete node.operator; // falls through to AssignmentPattern } else { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); break; } case "AssignmentPattern": if (node.right.type === "YieldExpression") this.raise(node.right.start, "Yield expression cannot be a default value"); break; case "ParenthesizedExpression": node.expression = this.toAssignable(node.expression, isBinding); break; case "MemberExpression": if (!isBinding) break; default: this.raise(node.start, "Assigning to rvalue"); } } return node; }; // Convert list of expression atoms to binding list. pp.toAssignableList = function (exprList, isBinding) { var end = exprList.length; if (end) { var last = exprList[end - 1]; if (last && last.type == "RestElement") { --end; } else if (last && last.type == "SpreadElement") { last.type = "RestElement"; var arg = last.argument; this.toAssignable(arg, isBinding); if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") this.unexpected(arg.start); --end; } if (isBinding && last.type === "RestElement" && last.argument.type !== "Identifier") this.unexpected(last.argument.start); } for (var i = 0; i < end; i++) { var elt = exprList[i]; if (elt) this.toAssignable(elt, isBinding); } return exprList; }; // Parses spread element. pp.parseSpread = function (refDestructuringErrors) { var node = this.startNode(); this.next(); node.argument = this.parseMaybeAssign(refDestructuringErrors); return this.finishNode(node, "SpreadElement"); }; pp.parseRest = function (allowNonIdent) { var node = this.startNode(); this.next(); // RestElement inside of a function parameter must be an identifier if (allowNonIdent) node.argument = this.type === _tokentype.types.name ? this.parseIdent() : this.unexpected();else node.argument = this.type === _tokentype.types.name || this.type === _tokentype.types.bracketL ? this.parseBindingAtom() : this.unexpected(); return this.finishNode(node, "RestElement"); }; // Parses lvalue (assignable) atom. pp.parseBindingAtom = function () { if (this.options.ecmaVersion < 6) return this.parseIdent(); switch (this.type) { case _tokentype.types.name: return this.parseIdent(); case _tokentype.types.bracketL: var node = this.startNode(); this.next(); node.elements = this.parseBindingList(_tokentype.types.bracketR, true, true); return this.finishNode(node, "ArrayPattern"); case _tokentype.types.braceL: return this.parseObj(true); default: this.unexpected(); } }; pp.parseBindingList = function (close, allowEmpty, allowTrailingComma, allowNonIdent) { var elts = [], first = true; while (!this.eat(close)) { if (first) first = false;else this.expect(_tokentype.types.comma); if (allowEmpty && this.type === _tokentype.types.comma) { elts.push(null); } else if (allowTrailingComma && this.afterTrailingComma(close)) { break; } else if (this.type === _tokentype.types.ellipsis) { var rest = this.parseRest(allowNonIdent); this.parseBindingListItem(rest); elts.push(rest); this.expect(close); break; } else { var elem = this.parseMaybeDefault(this.start, this.startLoc); this.parseBindingListItem(elem); elts.push(elem); } } return elts; }; pp.parseBindingListItem = function (param) { return param; }; // Parses assignment pattern around given atom if possible. pp.parseMaybeDefault = function (startPos, startLoc, left) { left = left || this.parseBindingAtom(); if (this.options.ecmaVersion < 6 || !this.eat(_tokentype.types.eq)) return left; var node = this.startNodeAt(startPos, startLoc); node.left = left; node.right = this.parseMaybeAssign(); return this.finishNode(node, "AssignmentPattern"); }; // Verify that a node is an lval something that can be assigned // to. pp.checkLVal = function (expr, isBinding, checkClashes) { switch (expr.type) { case "Identifier": if (this.strict && this.reservedWordsStrictBind.test(expr.name)) this.raise(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); if (checkClashes) { if (_util.has(checkClashes, expr.name)) this.raise(expr.start, "Argument name clash"); checkClashes[expr.name] = true; } break; case "MemberExpression": if (isBinding) this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression"); break; case "ObjectPattern": for (var i = 0; i < expr.properties.length; i++) { this.checkLVal(expr.properties[i].value, isBinding, checkClashes); }break; case "ArrayPattern": for (var i = 0; i < expr.elements.length; i++) { var elem = expr.elements[i]; if (elem) this.checkLVal(elem, isBinding, checkClashes); } break; case "AssignmentPattern": this.checkLVal(expr.left, isBinding, checkClashes); break; case "RestElement": this.checkLVal(expr.argument, isBinding, checkClashes); break; case "ParenthesizedExpression": this.checkLVal(expr.expression, isBinding, checkClashes); break; default: this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue"); } }; },{"./state":10,"./tokentype":14,"./util":15}],7:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _state = _dereq_("./state"); var _locutil = _dereq_("./locutil"); var Node = function Node(parser, pos, loc) { _classCallCheck(this, Node); this.type = ""; this.start = pos; this.end = 0; if (parser.options.locations) this.loc = new _locutil.SourceLocation(parser, loc); if (parser.options.directSourceFile) this.sourceFile = parser.options.directSourceFile; if (parser.options.ranges) this.range = [pos, 0]; } // Start an AST node, attaching a start offset. ; exports.Node = Node; var pp = _state.Parser.prototype; pp.startNode = function () { return new Node(this, this.start, this.startLoc); }; pp.startNodeAt = function (pos, loc) { return new Node(this, pos, loc); }; // Finish an AST node, adding `type` and `end` properties. function finishNodeAt(node, type, pos, loc) { node.type = type; node.end = pos; if (this.options.locations) node.loc.end = loc; if (this.options.ranges) node.range[1] = pos; return node; } pp.finishNode = function (node, type) { return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc); }; // Finish node at given position pp.finishNodeAt = function (node, type, pos, loc) { return finishNodeAt.call(this, node, type, pos, loc); }; },{"./locutil":5,"./state":10}],8:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; exports.getOptions = getOptions; var _util = _dereq_("./util"); var _locutil = _dereq_("./locutil"); // A second optional argument can be given to further configure // the parser process. These options are recognized: var defaultOptions = { // `ecmaVersion` indicates the ECMAScript version to parse. Must // be either 3, or 5, or 6. This influences support for strict // mode, the set of reserved words, support for getters and // setters and other features. ecmaVersion: 5, // Source type ("script" or "module") for different semantics sourceType: "script", // `onInsertedSemicolon` can be a callback that will be called // when a semicolon is automatically inserted. It will be passed // th position of the comma as an offset, and if `locations` is // enabled, it is given the location as a `{line, column}` object // as second argument. onInsertedSemicolon: null, // `onTrailingComma` is similar to `onInsertedSemicolon`, but for // trailing commas. onTrailingComma: null, // By default, reserved words are only enforced if ecmaVersion >= 5. // Set `allowReserved` to a boolean value to explicitly turn this on // an off. When this option has the value "never", reserved words // and keywords can also not be used as property names. allowReserved: null, // When enabled, a return at the top level is not considered an // error. allowReturnOutsideFunction: false, // When enabled, import/export statements are not constrained to // appearing at the top of the program. allowImportExportEverywhere: false, // When enabled, hashbang directive in the beginning of file // is allowed and treated as a line comment. allowHashBang: false, // When `locations` is on, `loc` properties holding objects with // `start` and `end` properties in `{line, column}` form (with // line being 1-based and column 0-based) will be attached to the // nodes. locations: false, // A function can be passed as `onToken` option, which will // cause Acorn to call that function with object in the same // format as tokens returned from `tokenizer().getToken()`. Note // that you are not allowed to call the parser from the // callbackthat will corrupt its internal state. onToken: null, // A function can be passed as `onComment` option, which will // cause Acorn to call that function with `(block, text, start, // end)` parameters whenever a comment is skipped. `block` is a // boolean indicating whether this is a block (`/* */`) comment, // `text` is the content of the comment, and `start` and `end` are // character offsets that denote the start and end of the comment. // When the `locations` option is on, two more parameters are // passed, the full `{line, column}` locations of the start and // end of the comments. Note that you are not allowed to call the // parser from the callbackthat will corrupt its internal state. onComment: null, // Nodes have their start and end characters offsets recorded in // `start` and `end` properties (directly on the node, rather than // the `loc` object, which holds line/column data. To also add a // [semi-standardized][range] `range` property holding a `[start, // end]` array with the same numbers, set the `ranges` option to // `true`. // // [range]: path_to_url ranges: false, // It is possible to parse multiple files into a single AST by // passing the tree produced by parsing the first file as // `program` option in subsequent parses. This will add the // toplevel forms of the parsed file to the `Program` (top) node // of an existing parse tree. program: null, // When `locations` is on, you can pass this to record the source // file in every node's `loc` object. sourceFile: null, // This value, if given, is stored in every node, whether // `locations` is on or off. directSourceFile: null, // When enabled, parenthesized expressions are represented by // (non-standard) ParenthesizedExpression nodes preserveParens: false, plugins: {} }; exports.defaultOptions = defaultOptions; // Interpret and default an options object function getOptions(opts) { var options = {}; for (var opt in defaultOptions) { options[opt] = opts && _util.has(opts, opt) ? opts[opt] : defaultOptions[opt]; }if (options.allowReserved == null) options.allowReserved = options.ecmaVersion < 5; if (_util.isArray(options.onToken)) { (function () { var tokens = options.onToken; options.onToken = function (token) { return tokens.push(token); }; })(); } if (_util.isArray(options.onComment)) options.onComment = pushComment(options, options.onComment); return options; } function pushComment(options, array) { return function (block, text, start, end, startLoc, endLoc) { var comment = { type: block ? 'Block' : 'Line', value: text, start: start, end: end }; if (options.locations) comment.loc = new _locutil.SourceLocation(this, startLoc, endLoc); if (options.ranges) comment.range = [start, end]; array.push(comment); }; } },{"./locutil":5,"./util":15}],9:[function(_dereq_,module,exports){ "use strict"; var _tokentype = _dereq_("./tokentype"); var _state = _dereq_("./state"); var _whitespace = _dereq_("./whitespace"); var pp = _state.Parser.prototype; // ## Parser utilities // Test whether a statement node is the string literal `"use strict"`. pp.isUseStrict = function (stmt) { return this.options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && stmt.expression.raw.slice(1, -1) === "use strict"; }; // Predicate that tests whether the next token is of the given // type, and if yes, consumes it as a side effect. pp.eat = function (type) { if (this.type === type) { this.next(); return true; } else { return false; } }; // Tests whether parsed token is a contextual keyword. pp.isContextual = function (name) { return this.type === _tokentype.types.name && this.value === name; }; // Consumes contextual keyword if possible. pp.eatContextual = function (name) { return this.value === name && this.eat(_tokentype.types.name); }; // Asserts that following token is given contextual keyword. pp.expectContextual = function (name) { if (!this.eatContextual(name)) this.unexpected(); }; // Test whether a semicolon can be inserted at the current position. pp.canInsertSemicolon = function () { return this.type === _tokentype.types.eof || this.type === _tokentype.types.braceR || _whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); }; pp.insertSemicolon = function () { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon) this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); return true; } }; // Consume a semicolon, or, failing that, see if we are allowed to // pretend that there is a semicolon at this position. pp.semicolon = function () { if (!this.eat(_tokentype.types.semi) && !this.insertSemicolon()) this.unexpected(); }; pp.afterTrailingComma = function (tokType) { if (this.type == tokType) { if (this.options.onTrailingComma) this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); this.next(); return true; } }; // Expect a token of a given type. If found, consume it, otherwise, // raise an unexpected token error. pp.expect = function (type) { this.eat(type) || this.unexpected(); }; // Raise an unexpected token error. pp.unexpected = function (pos) { this.raise(pos != null ? pos : this.start, "Unexpected token"); }; pp.checkPatternErrors = function (refDestructuringErrors, andThrow) { var pos = refDestructuringErrors && refDestructuringErrors.trailingComma; if (!andThrow) return !!pos; if (pos) this.raise(pos, "Trailing comma is not permitted in destructuring patterns"); }; pp.checkExpressionErrors = function (refDestructuringErrors, andThrow) { var pos = refDestructuringErrors && refDestructuringErrors.shorthandAssign; if (!andThrow) return !!pos; if (pos) this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns"); }; },{"./state":10,"./tokentype":14,"./whitespace":16}],10:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _identifier = _dereq_("./identifier"); var _tokentype = _dereq_("./tokentype"); var _whitespace = _dereq_("./whitespace"); var _options = _dereq_("./options"); // Registered plugins var plugins = {}; exports.plugins = plugins; function keywordRegexp(words) { return new RegExp("^(" + words.replace(/ /g, "|") + ")$"); } var Parser = (function () { function Parser(options, input, startPos) { _classCallCheck(this, Parser); this.options = options = _options.getOptions(options); this.sourceFile = options.sourceFile; this.keywords = keywordRegexp(_identifier.keywords[options.ecmaVersion >= 6 ? 6 : 5]); var reserved = options.allowReserved ? "" : _identifier.reservedWords[options.ecmaVersion] + (options.sourceType == "module" ? " await" : ""); this.reservedWords = keywordRegexp(reserved); var reservedStrict = (reserved ? reserved + " " : "") + _identifier.reservedWords.strict; this.reservedWordsStrict = keywordRegexp(reservedStrict); this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + _identifier.reservedWords.strictBind); this.input = String(input); // Used to signal to callers of `readWord1` whether the word // contained any escape sequences. This is needed because words with // escape sequences must not be interpreted as keywords. this.containsEsc = false; // Load plugins this.loadPlugins(options.plugins); // Set up token state // The current position of the tokenizer in the input. if (startPos) { this.pos = startPos; this.lineStart = Math.max(0, this.input.lastIndexOf("\n", startPos)); this.curLine = this.input.slice(0, this.lineStart).split(_whitespace.lineBreak).length; } else { this.pos = this.lineStart = 0; this.curLine = 1; } // Properties of the current token: // Its type this.type = _tokentype.types.eof; // For tokens that include more information than their type, the value this.value = null; // Its start and end offset this.start = this.end = this.pos; // And, if locations are used, the {line, column} object // corresponding to those offsets this.startLoc = this.endLoc = this.curPosition(); // Position information for the previous token this.lastTokEndLoc = this.lastTokStartLoc = null; this.lastTokStart = this.lastTokEnd = this.pos; // The context stack is used to superficially track syntactic // context to predict whether a regular expression is allowed in a // given position. this.context = this.initialContext(); this.exprAllowed = true; // Figure out if it's a module code. this.strict = this.inModule = options.sourceType === "module"; // Used to signify the start of a potential arrow function this.potentialArrowAt = -1; // Flags to track whether we are in a function, a generator. this.inFunction = this.inGenerator = false; // Labels in scope. this.labels = []; // If enabled, skip leading hashbang line. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === '#!') this.skipLineComment(2); } // DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them Parser.prototype.isKeyword = function isKeyword(word) { return this.keywords.test(word); }; Parser.prototype.isReservedWord = function isReservedWord(word) { return this.reservedWords.test(word); }; Parser.prototype.extend = function extend(name, f) { this[name] = f(this[name]); }; Parser.prototype.loadPlugins = function loadPlugins(pluginConfigs) { for (var _name in pluginConfigs) { var plugin = plugins[_name]; if (!plugin) throw new Error("Plugin '" + _name + "' not found"); plugin(this, pluginConfigs[_name]); } }; Parser.prototype.parse = function parse() { var node = this.options.program || this.startNode(); this.nextToken(); return this.parseTopLevel(node); }; return Parser; })(); exports.Parser = Parser; },{"./identifier":2,"./options":8,"./tokentype":14,"./whitespace":16}],11:[function(_dereq_,module,exports){ "use strict"; var _tokentype = _dereq_("./tokentype"); var _state = _dereq_("./state"); var _whitespace = _dereq_("./whitespace"); var pp = _state.Parser.prototype; // ### Statement parsing // Parse a program. Initializes the parser, reads any number of // statements, and wraps them in a Program node. Optionally takes a // `program` argument. If present, the statements will be appended // to its body instead of creating a new node. pp.parseTopLevel = function (node) { var first = true; if (!node.body) node.body = []; while (this.type !== _tokentype.types.eof) { var stmt = this.parseStatement(true, true); node.body.push(stmt); if (first) { if (this.isUseStrict(stmt)) this.setStrict(true); first = false; } } this.next(); if (this.options.ecmaVersion >= 6) { node.sourceType = this.options.sourceType; } return this.finishNode(node, "Program"); }; var loopLabel = { kind: "loop" }, switchLabel = { kind: "switch" }; // Parse a single statement. // // If expecting a statement and finding a slash operator, parse a // regular expression literal. This is to handle cases like // `if (foo) /blah/.exec(foo)`, where looking at the previous token // does not help. pp.parseStatement = function (declaration, topLevel) { var starttype = this.type, node = this.startNode(); // Most types of statements are recognized by the keyword they // start with. Many are trivial to parse, some require a bit of // complexity. switch (starttype) { case _tokentype.types._break:case _tokentype.types._continue: return this.parseBreakContinueStatement(node, starttype.keyword); case _tokentype.types._debugger: return this.parseDebuggerStatement(node); case _tokentype.types._do: return this.parseDoStatement(node); case _tokentype.types._for: return this.parseForStatement(node); case _tokentype.types._function: if (!declaration && this.options.ecmaVersion >= 6) this.unexpected(); return this.parseFunctionStatement(node); case _tokentype.types._class: if (!declaration) this.unexpected(); return this.parseClass(node, true); case _tokentype.types._if: return this.parseIfStatement(node); case _tokentype.types._return: return this.parseReturnStatement(node); case _tokentype.types._switch: return this.parseSwitchStatement(node); case _tokentype.types._throw: return this.parseThrowStatement(node); case _tokentype.types._try: return this.parseTryStatement(node); case _tokentype.types._let:case _tokentype.types._const: if (!declaration) this.unexpected(); // NOTE: falls through to _var case _tokentype.types._var: return this.parseVarStatement(node, starttype); case _tokentype.types._while: return this.parseWhileStatement(node); case _tokentype.types._with: return this.parseWithStatement(node); case _tokentype.types.braceL: return this.parseBlock(); case _tokentype.types.semi: return this.parseEmptyStatement(node); case _tokentype.types._export: case _tokentype.types._import: if (!this.options.allowImportExportEverywhere) { if (!topLevel) this.raise(this.start, "'import' and 'export' may only appear at the top level"); if (!this.inModule) this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } return starttype === _tokentype.types._import ? this.parseImport(node) : this.parseExport(node); // If the statement does not start with a statement keyword or a // brace, it's an ExpressionStatement or LabeledStatement. We // simply start parsing an expression, and afterwards, if the // next token is a colon and the expression was a simple // Identifier node, we switch to interpreting it as a label. default: var maybeName = this.value, expr = this.parseExpression(); if (starttype === _tokentype.types.name && expr.type === "Identifier" && this.eat(_tokentype.types.colon)) return this.parseLabeledStatement(node, maybeName, expr);else return this.parseExpressionStatement(node, expr); } }; pp.parseBreakContinueStatement = function (node, keyword) { var isBreak = keyword == "break"; this.next(); if (this.eat(_tokentype.types.semi) || this.insertSemicolon()) node.label = null;else if (this.type !== _tokentype.types.name) this.unexpected();else { node.label = this.parseIdent(); this.semicolon(); } // Verify that there is an actual destination to break or // continue to. for (var i = 0; i < this.labels.length; ++i) { var lab = this.labels[i]; if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) break; if (node.label && isBreak) break; } } if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword); return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); }; pp.parseDebuggerStatement = function (node) { this.next(); this.semicolon(); return this.finishNode(node, "DebuggerStatement"); }; pp.parseDoStatement = function (node) { this.next(); this.labels.push(loopLabel); node.body = this.parseStatement(false); this.labels.pop(); this.expect(_tokentype.types._while); node.test = this.parseParenExpression(); if (this.options.ecmaVersion >= 6) this.eat(_tokentype.types.semi);else this.semicolon(); return this.finishNode(node, "DoWhileStatement"); }; // Disambiguating between a `for` and a `for`/`in` or `for`/`of` // loop is non-trivial. Basically, we have to parse the init `var` // statement or expression, disallowing the `in` operator (see // the second parameter to `parseExpression`), and then check // whether the next token is `in` or `of`. When there is no init // part (semicolon immediately after the opening parenthesis), it // is a regular `for` loop. pp.parseForStatement = function (node) { this.next(); this.labels.push(loopLabel); this.expect(_tokentype.types.parenL); if (this.type === _tokentype.types.semi) return this.parseFor(node, null); if (this.type === _tokentype.types._var || this.type === _tokentype.types._let || this.type === _tokentype.types._const) { var _init = this.startNode(), varKind = this.type; this.next(); this.parseVar(_init, true, varKind); this.finishNode(_init, "VariableDeclaration"); if ((this.type === _tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && _init.declarations.length === 1 && !(varKind !== _tokentype.types._var && _init.declarations[0].init)) return this.parseForIn(node, _init); return this.parseFor(node, _init); } var refDestructuringErrors = { shorthandAssign: 0, trailingComma: 0 }; var init = this.parseExpression(true, refDestructuringErrors); if (this.type === _tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) { this.checkPatternErrors(refDestructuringErrors, true); this.toAssignable(init); this.checkLVal(init); return this.parseForIn(node, init); } else { this.checkExpressionErrors(refDestructuringErrors, true); } return this.parseFor(node, init); }; pp.parseFunctionStatement = function (node) { this.next(); return this.parseFunction(node, true); }; pp.parseIfStatement = function (node) { this.next(); node.test = this.parseParenExpression(); node.consequent = this.parseStatement(false); node.alternate = this.eat(_tokentype.types._else) ? this.parseStatement(false) : null; return this.finishNode(node, "IfStatement"); }; pp.parseReturnStatement = function (node) { if (!this.inFunction && !this.options.allowReturnOutsideFunction) this.raise(this.start, "'return' outside of function"); this.next(); // In `return` (and `break`/`continue`), the keywords with // optional arguments, we eagerly look for a semicolon or the // possibility to insert one. if (this.eat(_tokentype.types.semi) || this.insertSemicolon()) node.argument = null;else { node.argument = this.parseExpression();this.semicolon(); } return this.finishNode(node, "ReturnStatement"); }; pp.parseSwitchStatement = function (node) { this.next(); node.discriminant = this.parseParenExpression(); node.cases = []; this.expect(_tokentype.types.braceL); this.labels.push(switchLabel); // Statements under must be grouped (by label) in SwitchCase // nodes. `cur` is used to keep the node that we are currently // adding statements to. for (var cur, sawDefault = false; this.type != _tokentype.types.braceR;) { if (this.type === _tokentype.types._case || this.type === _tokentype.types._default) { var isCase = this.type === _tokentype.types._case; if (cur) this.finishNode(cur, "SwitchCase"); node.cases.push(cur = this.startNode()); cur.consequent = []; this.next(); if (isCase) { cur.test = this.parseExpression(); } else { if (sawDefault) this.raise(this.lastTokStart, "Multiple default clauses"); sawDefault = true; cur.test = null; } this.expect(_tokentype.types.colon); } else { if (!cur) this.unexpected(); cur.consequent.push(this.parseStatement(true)); } } if (cur) this.finishNode(cur, "SwitchCase"); this.next(); // Closing brace this.labels.pop(); return this.finishNode(node, "SwitchStatement"); }; pp.parseThrowStatement = function (node) { this.next(); if (_whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) this.raise(this.lastTokEnd, "Illegal newline after throw"); node.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node, "ThrowStatement"); }; // Reused empty array added for node fields that are always empty. var empty = []; pp.parseTryStatement = function (node) { this.next(); node.block = this.parseBlock(); node.handler = null; if (this.type === _tokentype.types._catch) { var clause = this.startNode(); this.next(); this.expect(_tokentype.types.parenL); clause.param = this.parseBindingAtom(); this.checkLVal(clause.param, true); this.expect(_tokentype.types.parenR); clause.body = this.parseBlock(); node.handler = this.finishNode(clause, "CatchClause"); } node.finalizer = this.eat(_tokentype.types._finally) ? this.parseBlock() : null; if (!node.handler && !node.finalizer) this.raise(node.start, "Missing catch or finally clause"); return this.finishNode(node, "TryStatement"); }; pp.parseVarStatement = function (node, kind) { this.next(); this.parseVar(node, false, kind); this.semicolon(); return this.finishNode(node, "VariableDeclaration"); }; pp.parseWhileStatement = function (node) { this.next(); node.test = this.parseParenExpression(); this.labels.push(loopLabel); node.body = this.parseStatement(false); this.labels.pop(); return this.finishNode(node, "WhileStatement"); }; pp.parseWithStatement = function (node) { if (this.strict) this.raise(this.start, "'with' in strict mode"); this.next(); node.object = this.parseParenExpression(); node.body = this.parseStatement(false); return this.finishNode(node, "WithStatement"); }; pp.parseEmptyStatement = function (node) { this.next(); return this.finishNode(node, "EmptyStatement"); }; pp.parseLabeledStatement = function (node, maybeName, expr) { for (var i = 0; i < this.labels.length; ++i) { if (this.labels[i].name === maybeName) this.raise(expr.start, "Label '" + maybeName + "' is already declared"); }var kind = this.type.isLoop ? "loop" : this.type === _tokentype.types._switch ? "switch" : null; for (var i = this.labels.length - 1; i >= 0; i--) { var label = this.labels[i]; if (label.statementStart == node.start) { label.statementStart = this.start; label.kind = kind; } else break; } this.labels.push({ name: maybeName, kind: kind, statementStart: this.start }); node.body = this.parseStatement(true); this.labels.pop(); node.label = expr; return this.finishNode(node, "LabeledStatement"); }; pp.parseExpressionStatement = function (node, expr) { node.expression = expr; this.semicolon(); return this.finishNode(node, "ExpressionStatement"); }; // Parse a semicolon-enclosed block of statements, handling `"use // strict"` declarations when `allowStrict` is true (used for // function bodies). pp.parseBlock = function (allowStrict) { var node = this.startNode(), first = true, oldStrict = undefined; node.body = []; this.expect(_tokentype.types.braceL); while (!this.eat(_tokentype.types.braceR)) { var stmt = this.parseStatement(true); node.body.push(stmt); if (first && allowStrict && this.isUseStrict(stmt)) { oldStrict = this.strict; this.setStrict(this.strict = true); } first = false; } if (oldStrict === false) this.setStrict(false); return this.finishNode(node, "BlockStatement"); }; // Parse a regular `for` loop. The disambiguation code in // `parseStatement` will already have parsed the init statement or // expression. pp.parseFor = function (node, init) { node.init = init; this.expect(_tokentype.types.semi); node.test = this.type === _tokentype.types.semi ? null : this.parseExpression(); this.expect(_tokentype.types.semi); node.update = this.type === _tokentype.types.parenR ? null : this.parseExpression(); this.expect(_tokentype.types.parenR); node.body = this.parseStatement(false); this.labels.pop(); return this.finishNode(node, "ForStatement"); }; // Parse a `for`/`in` and `for`/`of` loop, which are almost // same from parser's perspective. pp.parseForIn = function (node, init) { var type = this.type === _tokentype.types._in ? "ForInStatement" : "ForOfStatement"; this.next(); node.left = init; node.right = this.parseExpression(); this.expect(_tokentype.types.parenR); node.body = this.parseStatement(false); this.labels.pop(); return this.finishNode(node, type); }; // Parse a list of variable declarations. pp.parseVar = function (node, isFor, kind) { node.declarations = []; node.kind = kind.keyword; for (;;) { var decl = this.startNode(); this.parseVarId(decl); if (this.eat(_tokentype.types.eq)) { decl.init = this.parseMaybeAssign(isFor); } else if (kind === _tokentype.types._const && !(this.type === _tokentype.types._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) { this.unexpected(); } else if (decl.id.type != "Identifier" && !(isFor && (this.type === _tokentype.types._in || this.isContextual("of")))) { this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); } else { decl.init = null; } node.declarations.push(this.finishNode(decl, "VariableDeclarator")); if (!this.eat(_tokentype.types.comma)) break; } return node; }; pp.parseVarId = function (decl) { decl.id = this.parseBindingAtom(); this.checkLVal(decl.id, true); }; // Parse a function declaration or literal (depending on the // `isStatement` parameter). pp.parseFunction = function (node, isStatement, allowExpressionBody) { this.initFunction(node); if (this.options.ecmaVersion >= 6) node.generator = this.eat(_tokentype.types.star); if (isStatement || this.type === _tokentype.types.name) node.id = this.parseIdent(); this.parseFunctionParams(node); this.parseFunctionBody(node, allowExpressionBody); return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression"); }; pp.parseFunctionParams = function (node) { this.expect(_tokentype.types.parenL); node.params = this.parseBindingList(_tokentype.types.parenR, false, false, true); }; // Parse a class declaration or literal (depending on the // `isStatement` parameter). pp.parseClass = function (node, isStatement) { this.next(); this.parseClassId(node, isStatement); this.parseClassSuper(node); var classBody = this.startNode(); var hadConstructor = false; classBody.body = []; this.expect(_tokentype.types.braceL); while (!this.eat(_tokentype.types.braceR)) { if (this.eat(_tokentype.types.semi)) continue; var method = this.startNode(); var isGenerator = this.eat(_tokentype.types.star); var isMaybeStatic = this.type === _tokentype.types.name && this.value === "static"; this.parsePropertyName(method); method["static"] = isMaybeStatic && this.type !== _tokentype.types.parenL; if (method["static"]) { if (isGenerator) this.unexpected(); isGenerator = this.eat(_tokentype.types.star); this.parsePropertyName(method); } method.kind = "method"; var isGetSet = false; if (!method.computed) { var key = method.key; if (!isGenerator && key.type === "Identifier" && this.type !== _tokentype.types.parenL && (key.name === "get" || key.name === "set")) { isGetSet = true; method.kind = key.name; key = this.parsePropertyName(method); } if (!method["static"] && (key.type === "Identifier" && key.name === "constructor" || key.type === "Literal" && key.value === "constructor")) { if (hadConstructor) this.raise(key.start, "Duplicate constructor in the same class"); if (isGetSet) this.raise(key.start, "Constructor can't have get/set modifier"); if (isGenerator) this.raise(key.start, "Constructor can't be a generator"); method.kind = "constructor"; hadConstructor = true; } } this.parseClassMethod(classBody, method, isGenerator); if (isGetSet) { var paramCount = method.kind === "get" ? 0 : 1; if (method.value.params.length !== paramCount) { var start = method.value.start; if (method.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param"); } if (method.kind === "set" && method.value.params[0].type === "RestElement") this.raise(method.value.params[0].start, "Setter cannot use rest params"); } } node.body = this.finishNode(classBody, "ClassBody"); return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); }; pp.parseClassMethod = function (classBody, method, isGenerator) { method.value = this.parseMethod(isGenerator); classBody.body.push(this.finishNode(method, "MethodDefinition")); }; pp.parseClassId = function (node, isStatement) { node.id = this.type === _tokentype.types.name ? this.parseIdent() : isStatement ? this.unexpected() : null; }; pp.parseClassSuper = function (node) { node.superClass = this.eat(_tokentype.types._extends) ? this.parseExprSubscripts() : null; }; // Parses module export declaration. pp.parseExport = function (node) { this.next(); // export * from '...' if (this.eat(_tokentype.types.star)) { this.expectContextual("from"); node.source = this.type === _tokentype.types.string ? this.parseExprAtom() : this.unexpected(); this.semicolon(); return this.finishNode(node, "ExportAllDeclaration"); } if (this.eat(_tokentype.types._default)) { // export default ... var expr = this.parseMaybeAssign(); var needsSemi = true; if (expr.type == "FunctionExpression" || expr.type == "ClassExpression") { needsSemi = false; if (expr.id) { expr.type = expr.type == "FunctionExpression" ? "FunctionDeclaration" : "ClassDeclaration"; } } node.declaration = expr; if (needsSemi) this.semicolon(); return this.finishNode(node, "ExportDefaultDeclaration"); } // export var|const|let|function|class ... if (this.shouldParseExportStatement()) { node.declaration = this.parseStatement(true); node.specifiers = []; node.source = null; } else { // export { x, y as z } [from '...'] node.declaration = null; node.specifiers = this.parseExportSpecifiers(); if (this.eatContextual("from")) { node.source = this.type === _tokentype.types.string ? this.parseExprAtom() : this.unexpected(); } else { // check for keywords used as local names for (var i = 0; i < node.specifiers.length; i++) { if (this.keywords.test(node.specifiers[i].local.name) || this.reservedWords.test(node.specifiers[i].local.name)) { this.unexpected(node.specifiers[i].local.start); } } node.source = null; } this.semicolon(); } return this.finishNode(node, "ExportNamedDeclaration"); }; pp.shouldParseExportStatement = function () { return this.type.keyword; }; // Parses a comma-separated list of module exports. pp.parseExportSpecifiers = function () { var nodes = [], first = true; // export { x, y as z } [from '...'] this.expect(_tokentype.types.braceL); while (!this.eat(_tokentype.types.braceR)) { if (!first) { this.expect(_tokentype.types.comma); if (this.afterTrailingComma(_tokentype.types.braceR)) break; } else first = false; var node = this.startNode(); node.local = this.parseIdent(this.type === _tokentype.types._default); node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local; nodes.push(this.finishNode(node, "ExportSpecifier")); } return nodes; }; // Parses import declaration. pp.parseImport = function (node) { this.next(); // import '...' if (this.type === _tokentype.types.string) { node.specifiers = empty; node.source = this.parseExprAtom(); } else { node.specifiers = this.parseImportSpecifiers(); this.expectContextual("from"); node.source = this.type === _tokentype.types.string ? this.parseExprAtom() : this.unexpected(); } this.semicolon(); return this.finishNode(node, "ImportDeclaration"); }; // Parses a comma-separated list of module imports. pp.parseImportSpecifiers = function () { var nodes = [], first = true; if (this.type === _tokentype.types.name) { // import defaultObj, { x, y as z } from '...' var node = this.startNode(); node.local = this.parseIdent(); this.checkLVal(node.local, true); nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); if (!this.eat(_tokentype.types.comma)) return nodes; } if (this.type === _tokentype.types.star) { var node = this.startNode(); this.next(); this.expectContextual("as"); node.local = this.parseIdent(); this.checkLVal(node.local, true); nodes.push(this.finishNode(node, "ImportNamespaceSpecifier")); return nodes; } this.expect(_tokentype.types.braceL); while (!this.eat(_tokentype.types.braceR)) { if (!first) { this.expect(_tokentype.types.comma); if (this.afterTrailingComma(_tokentype.types.braceR)) break; } else first = false; var node = this.startNode(); node.imported = this.parseIdent(true); if (this.eatContextual("as")) { node.local = this.parseIdent(); } else { node.local = node.imported; if (this.isKeyword(node.local.name)) this.unexpected(node.local.start); if (this.reservedWordsStrict.test(node.local.name)) this.raise(node.local.start, "The keyword '" + node.local.name + "' is reserved"); } this.checkLVal(node.local, true); nodes.push(this.finishNode(node, "ImportSpecifier")); } return nodes; }; },{"./state":10,"./tokentype":14,"./whitespace":16}],12:[function(_dereq_,module,exports){ // The algorithm used to determine whether a regexp can appear at a // given point in the program is loosely based on sweet.js' approach. // See path_to_url "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _state = _dereq_("./state"); var _tokentype = _dereq_("./tokentype"); var _whitespace = _dereq_("./whitespace"); var TokContext = function TokContext(token, isExpr, preserveSpace, override) { _classCallCheck(this, TokContext); this.token = token; this.isExpr = !!isExpr; this.preserveSpace = !!preserveSpace; this.override = override; }; exports.TokContext = TokContext; var types = { b_stat: new TokContext("{", false), b_expr: new TokContext("{", true), b_tmpl: new TokContext("${", true), p_stat: new TokContext("(", false), p_expr: new TokContext("(", true), q_tmpl: new TokContext("`", true, true, function (p) { return p.readTmplToken(); }), f_expr: new TokContext("function", true) }; exports.types = types; var pp = _state.Parser.prototype; pp.initialContext = function () { return [types.b_stat]; }; pp.braceIsBlock = function (prevType) { if (prevType === _tokentype.types.colon) { var _parent = this.curContext(); if (_parent === types.b_stat || _parent === types.b_expr) return !_parent.isExpr; } if (prevType === _tokentype.types._return) return _whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.start)); if (prevType === _tokentype.types._else || prevType === _tokentype.types.semi || prevType === _tokentype.types.eof || prevType === _tokentype.types.parenR) return true; if (prevType == _tokentype.types.braceL) return this.curContext() === types.b_stat; return !this.exprAllowed; }; pp.updateContext = function (prevType) { var update = undefined, type = this.type; if (type.keyword && prevType == _tokentype.types.dot) this.exprAllowed = false;else if (update = type.updateContext) update.call(this, prevType);else this.exprAllowed = type.beforeExpr; }; // Token-specific context update code _tokentype.types.parenR.updateContext = _tokentype.types.braceR.updateContext = function () { if (this.context.length == 1) { this.exprAllowed = true; return; } var out = this.context.pop(); if (out === types.b_stat && this.curContext() === types.f_expr) { this.context.pop(); this.exprAllowed = false; } else if (out === types.b_tmpl) { this.exprAllowed = true; } else { this.exprAllowed = !out.isExpr; } }; _tokentype.types.braceL.updateContext = function (prevType) { this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr); this.exprAllowed = true; }; _tokentype.types.dollarBraceL.updateContext = function () { this.context.push(types.b_tmpl); this.exprAllowed = true; }; _tokentype.types.parenL.updateContext = function (prevType) { var statementParens = prevType === _tokentype.types._if || prevType === _tokentype.types._for || prevType === _tokentype.types._with || prevType === _tokentype.types._while; this.context.push(statementParens ? types.p_stat : types.p_expr); this.exprAllowed = true; }; _tokentype.types.incDec.updateContext = function () { // tokExprAllowed stays unchanged }; _tokentype.types._function.updateContext = function () { if (this.curContext() !== types.b_stat) this.context.push(types.f_expr); this.exprAllowed = false; }; _tokentype.types.backQuote.updateContext = function () { if (this.curContext() === types.q_tmpl) this.context.pop();else this.context.push(types.q_tmpl); this.exprAllowed = false; }; },{"./state":10,"./tokentype":14,"./whitespace":16}],13:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _identifier = _dereq_("./identifier"); var _tokentype = _dereq_("./tokentype"); var _state = _dereq_("./state"); var _locutil = _dereq_("./locutil"); var _whitespace = _dereq_("./whitespace"); // Object type used to represent tokens. Note that normally, tokens // simply exist as properties on the parser object. This is only // used for the onToken callback and the external tokenizer. var Token = function Token(p) { _classCallCheck(this, Token); this.type = p.type; this.value = p.value; this.start = p.start; this.end = p.end; if (p.options.locations) this.loc = new _locutil.SourceLocation(p, p.startLoc, p.endLoc); if (p.options.ranges) this.range = [p.start, p.end]; } // ## Tokenizer ; exports.Token = Token; var pp = _state.Parser.prototype; // Are we running under Rhino? var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]"; // Move to the next token pp.next = function () { if (this.options.onToken) this.options.onToken(new Token(this)); this.lastTokEnd = this.end; this.lastTokStart = this.start; this.lastTokEndLoc = this.endLoc; this.lastTokStartLoc = this.startLoc; this.nextToken(); }; pp.getToken = function () { this.next(); return new Token(this); }; // If we're in an ES6 environment, make parsers iterable if (typeof Symbol !== "undefined") pp[Symbol.iterator] = function () { var self = this; return { next: function next() { var token = self.getToken(); return { done: token.type === _tokentype.types.eof, value: token }; } }; }; // Toggle strict mode. Re-reads the next number or string to please // pedantic tests (`"use strict"; 010;` should fail). pp.setStrict = function (strict) { this.strict = strict; if (this.type !== _tokentype.types.num && this.type !== _tokentype.types.string) return; this.pos = this.start; if (this.options.locations) { while (this.pos < this.lineStart) { this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1; --this.curLine; } } this.nextToken(); }; pp.curContext = function () { return this.context[this.context.length - 1]; }; // Read a single token, updating the parser object's token-related // properties. pp.nextToken = function () { var curContext = this.curContext(); if (!curContext || !curContext.preserveSpace) this.skipSpace(); this.start = this.pos; if (this.options.locations) this.startLoc = this.curPosition(); if (this.pos >= this.input.length) return this.finishToken(_tokentype.types.eof); if (curContext.override) return curContext.override(this);else this.readToken(this.fullCharCodeAtPos()); }; pp.readToken = function (code) { // Identifier or keyword. '\uXXXX' sequences are allowed in // identifiers, so '\' also dispatches to that. if (_identifier.isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) return this.readWord(); return this.getTokenFromCode(code); }; pp.fullCharCodeAtPos = function () { var code = this.input.charCodeAt(this.pos); if (code <= 0xd7ff || code >= 0xe000) return code; var next = this.input.charCodeAt(this.pos + 1); return (code << 10) + next - 0x35fdc00; }; pp.skipBlockComment = function () { var startLoc = this.options.onComment && this.curPosition(); var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); if (end === -1) this.raise(this.pos - 2, "Unterminated comment"); this.pos = end + 2; if (this.options.locations) { _whitespace.lineBreakG.lastIndex = start; var match = undefined; while ((match = _whitespace.lineBreakG.exec(this.input)) && match.index < this.pos) { ++this.curLine; this.lineStart = match.index + match[0].length; } } if (this.options.onComment) this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition()); }; pp.skipLineComment = function (startSkip) { var start = this.pos; var startLoc = this.options.onComment && this.curPosition(); var ch = this.input.charCodeAt(this.pos += startSkip); while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) { ++this.pos; ch = this.input.charCodeAt(this.pos); } if (this.options.onComment) this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition()); }; // Called at the start of the parse and after every token. Skips // whitespace and comments, and. pp.skipSpace = function () { loop: while (this.pos < this.input.length) { var ch = this.input.charCodeAt(this.pos); switch (ch) { case 32:case 160: // ' ' ++this.pos; break; case 13: if (this.input.charCodeAt(this.pos + 1) === 10) { ++this.pos; } case 10:case 8232:case 8233: ++this.pos; if (this.options.locations) { ++this.curLine; this.lineStart = this.pos; } break; case 47: // '/' switch (this.input.charCodeAt(this.pos + 1)) { case 42: // '*' this.skipBlockComment(); break; case 47: this.skipLineComment(2); break; default: break loop; } break; default: if (ch > 8 && ch < 14 || ch >= 5760 && _whitespace.nonASCIIwhitespace.test(String.fromCharCode(ch))) { ++this.pos; } else { break loop; } } } }; // Called at the end of every token. Sets `end`, `val`, and // maintains `context` and `exprAllowed`, and skips the space after // the token, so that the next one's `start` will point at the // right position. pp.finishToken = function (type, val) { this.end = this.pos; if (this.options.locations) this.endLoc = this.curPosition(); var prevType = this.type; this.type = type; this.value = val; this.updateContext(prevType); }; // ### Token reading // This is the function that is called to fetch the next token. It // is somewhat obscure, because it works in character codes rather // than characters, and because operator parsing has been inlined // into it. // // All in the name of speed. // pp.readToken_dot = function () { var next = this.input.charCodeAt(this.pos + 1); if (next >= 48 && next <= 57) return this.readNumber(true); var next2 = this.input.charCodeAt(this.pos + 2); if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' this.pos += 3; return this.finishToken(_tokentype.types.ellipsis); } else { ++this.pos; return this.finishToken(_tokentype.types.dot); } }; pp.readToken_slash = function () { // '/' var next = this.input.charCodeAt(this.pos + 1); if (this.exprAllowed) { ++this.pos;return this.readRegexp(); } if (next === 61) return this.finishOp(_tokentype.types.assign, 2); return this.finishOp(_tokentype.types.slash, 1); }; pp.readToken_mult_modulo = function (code) { // '%*' var next = this.input.charCodeAt(this.pos + 1); if (next === 61) return this.finishOp(_tokentype.types.assign, 2); return this.finishOp(code === 42 ? _tokentype.types.star : _tokentype.types.modulo, 1); }; pp.readToken_pipe_amp = function (code) { // '|&' var next = this.input.charCodeAt(this.pos + 1); if (next === code) return this.finishOp(code === 124 ? _tokentype.types.logicalOR : _tokentype.types.logicalAND, 2); if (next === 61) return this.finishOp(_tokentype.types.assign, 2); return this.finishOp(code === 124 ? _tokentype.types.bitwiseOR : _tokentype.types.bitwiseAND, 1); }; pp.readToken_caret = function () { // '^' var next = this.input.charCodeAt(this.pos + 1); if (next === 61) return this.finishOp(_tokentype.types.assign, 2); return this.finishOp(_tokentype.types.bitwiseXOR, 1); }; pp.readToken_plus_min = function (code) { // '+-' var next = this.input.charCodeAt(this.pos + 1); if (next === code) { if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 && _whitespace.lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) { // A `-->` line comment this.skipLineComment(3); this.skipSpace(); return this.nextToken(); } return this.finishOp(_tokentype.types.incDec, 2); } if (next === 61) return this.finishOp(_tokentype.types.assign, 2); return this.finishOp(_tokentype.types.plusMin, 1); }; pp.readToken_lt_gt = function (code) { // '<>' var next = this.input.charCodeAt(this.pos + 1); var size = 1; if (next === code) { size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(_tokentype.types.assign, size + 1); return this.finishOp(_tokentype.types.bitShift, size); } if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 && this.input.charCodeAt(this.pos + 3) == 45) { if (this.inModule) this.unexpected(); // `<!--`, an XML-style comment that should be interpreted as a line comment this.skipLineComment(4); this.skipSpace(); return this.nextToken(); } if (next === 61) size = this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2; return this.finishOp(_tokentype.types.relational, size); }; pp.readToken_eq_excl = function (code) { // '=!' var next = this.input.charCodeAt(this.pos + 1); if (next === 61) return this.finishOp(_tokentype.types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2); if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>' this.pos += 2; return this.finishToken(_tokentype.types.arrow); } return this.finishOp(code === 61 ? _tokentype.types.eq : _tokentype.types.prefix, 1); }; pp.getTokenFromCode = function (code) { switch (code) { // The interpretation of a dot depends on whether it is followed // by a digit or another two dots. case 46: // '.' return this.readToken_dot(); // Punctuation tokens. case 40: ++this.pos;return this.finishToken(_tokentype.types.parenL); case 41: ++this.pos;return this.finishToken(_tokentype.types.parenR); case 59: ++this.pos;return this.finishToken(_tokentype.types.semi); case 44: ++this.pos;return this.finishToken(_tokentype.types.comma); case 91: ++this.pos;return this.finishToken(_tokentype.types.bracketL); case 93: ++this.pos;return this.finishToken(_tokentype.types.bracketR); case 123: ++this.pos;return this.finishToken(_tokentype.types.braceL); case 125: ++this.pos;return this.finishToken(_tokentype.types.braceR); case 58: ++this.pos;return this.finishToken(_tokentype.types.colon); case 63: ++this.pos;return this.finishToken(_tokentype.types.question); case 96: // '`' if (this.options.ecmaVersion < 6) break; ++this.pos; return this.finishToken(_tokentype.types.backQuote); case 48: // '0' var next = this.input.charCodeAt(this.pos + 1); if (next === 120 || next === 88) return this.readRadixNumber(16); // '0x', '0X' - hex number if (this.options.ecmaVersion >= 6) { if (next === 111 || next === 79) return this.readRadixNumber(8); // '0o', '0O' - octal number if (next === 98 || next === 66) return this.readRadixNumber(2); // '0b', '0B' - binary number } // Anything else beginning with a digit is an integer, octal // number, or float. case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57: // 1-9 return this.readNumber(false); // Quotes produce strings. case 34:case 39: // '"', "'" return this.readString(code); // Operators are parsed inline in tiny state machines. '=' (61) is // often referred to. `finishOp` simply skips the amount of // characters it is given as second argument, and returns a token // of the type given by its first argument. case 47: // '/' return this.readToken_slash(); case 37:case 42: // '%*' return this.readToken_mult_modulo(code); case 124:case 38: // '|&' return this.readToken_pipe_amp(code); case 94: // '^' return this.readToken_caret(); case 43:case 45: // '+-' return this.readToken_plus_min(code); case 60:case 62: // '<>' return this.readToken_lt_gt(code); case 61:case 33: // '=!' return this.readToken_eq_excl(code); case 126: // '~' return this.finishOp(_tokentype.types.prefix, 1); } this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'"); }; pp.finishOp = function (type, size) { var str = this.input.slice(this.pos, this.pos + size); this.pos += size; return this.finishToken(type, str); }; // Parse a regular expression. Some context-awareness is necessary, // since a '/' inside a '[]' set does not end the expression. function tryCreateRegexp(src, flags, throwErrorAt, parser) { try { return new RegExp(src, flags); } catch (e) { if (throwErrorAt !== undefined) { if (e instanceof SyntaxError) parser.raise(throwErrorAt, "Error parsing regular expression: " + e.message); throw e; } } } var regexpUnicodeSupport = !!tryCreateRegexp("", "u"); pp.readRegexp = function () { var _this = this; var escaped = undefined, inClass = undefined, start = this.pos; for (;;) { if (this.pos >= this.input.length) this.raise(start, "Unterminated regular expression"); var ch = this.input.charAt(this.pos); if (_whitespace.lineBreak.test(ch)) this.raise(start, "Unterminated regular expression"); if (!escaped) { if (ch === "[") inClass = true;else if (ch === "]" && inClass) inClass = false;else if (ch === "/" && !inClass) break; escaped = ch === "\\"; } else escaped = false; ++this.pos; } var content = this.input.slice(start, this.pos); ++this.pos; // Need to use `readWord1` because '\uXXXX' sequences are allowed // here (don't ask). var mods = this.readWord1(); var tmp = content; if (mods) { var validFlags = /^[gim]*$/; if (this.options.ecmaVersion >= 6) validFlags = /^[gimuy]*$/; if (!validFlags.test(mods)) this.raise(start, "Invalid regular expression flag"); if (mods.indexOf('u') >= 0 && !regexpUnicodeSupport) { // Replace each astral symbol and every Unicode escape sequence that // possibly represents an astral symbol or a paired surrogate with a // single ASCII symbol to avoid throwing on regular expressions that // are only valid in combination with the `/u` flag. // Note: replacing with the ASCII symbol `x` might cause false // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a // perfectly valid pattern that is equivalent to `[a-b]`, but it would // be replaced by `[x-b]` which throws an error. tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, function (_match, code, offset) { code = Number("0x" + code); if (code > 0x10FFFF) _this.raise(start + offset + 3, "Code point out of bounds"); return "x"; }); tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x"); } } // Detect invalid regular expressions. var value = null; // Rhino's regular expression parser is flaky and throws uncatchable exceptions, // so don't do detection if we are running under Rhino if (!isRhino) { tryCreateRegexp(tmp, undefined, start, this); // Get a regular expression object for this pattern-flag pair, or `null` in // case the current environment doesn't support the flags it uses. value = tryCreateRegexp(content, mods); } return this.finishToken(_tokentype.types.regexp, { pattern: content, flags: mods, value: value }); }; // Read an integer in the given radix. Return null if zero digits // were read, the integer value otherwise. When `len` is given, this // will return `null` unless the integer has exactly `len` digits. pp.readInt = function (radix, len) { var start = this.pos, total = 0; for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) { var code = this.input.charCodeAt(this.pos), val = undefined; if (code >= 97) val = code - 97 + 10; // a else if (code >= 65) val = code - 65 + 10; // A else if (code >= 48 && code <= 57) val = code - 48; // 0-9 else val = Infinity; if (val >= radix) break; ++this.pos; total = total * radix + val; } if (this.pos === start || len != null && this.pos - start !== len) return null; return total; }; pp.readRadixNumber = function (radix) { this.pos += 2; // 0x var val = this.readInt(radix); if (val == null) this.raise(this.start + 2, "Expected number in radix " + radix); if (_identifier.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number"); return this.finishToken(_tokentype.types.num, val); }; // Read an integer, octal integer, or floating-point number. pp.readNumber = function (startsWithDot) { var start = this.pos, isFloat = false, octal = this.input.charCodeAt(this.pos) === 48; if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number"); var next = this.input.charCodeAt(this.pos); if (next === 46) { // '.' ++this.pos; this.readInt(10); isFloat = true; next = this.input.charCodeAt(this.pos); } if (next === 69 || next === 101) { // 'eE' next = this.input.charCodeAt(++this.pos); if (next === 43 || next === 45) ++this.pos; // '+-' if (this.readInt(10) === null) this.raise(start, "Invalid number"); isFloat = true; } if (_identifier.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number"); var str = this.input.slice(start, this.pos), val = undefined; if (isFloat) val = parseFloat(str);else if (!octal || str.length === 1) val = parseInt(str, 10);else if (/[89]/.test(str) || this.strict) this.raise(start, "Invalid number");else val = parseInt(str, 8); return this.finishToken(_tokentype.types.num, val); }; // Read a string value, interpreting backslash-escapes. pp.readCodePoint = function () { var ch = this.input.charCodeAt(this.pos), code = undefined; if (ch === 123) { if (this.options.ecmaVersion < 6) this.unexpected(); var codePos = ++this.pos; code = this.readHexChar(this.input.indexOf('}', this.pos) - this.pos); ++this.pos; if (code > 0x10FFFF) this.raise(codePos, "Code point out of bounds"); } else { code = this.readHexChar(4); } return code; }; function codePointToString(code) { // UTF-16 Decoding if (code <= 0xFFFF) return String.fromCharCode(code); code -= 0x10000; return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00); } pp.readString = function (quote) { var out = "", chunkStart = ++this.pos; for (;;) { if (this.pos >= this.input.length) this.raise(this.start, "Unterminated string constant"); var ch = this.input.charCodeAt(this.pos); if (ch === quote) break; if (ch === 92) { // '\' out += this.input.slice(chunkStart, this.pos); out += this.readEscapedChar(false); chunkStart = this.pos; } else { if (_whitespace.isNewLine(ch)) this.raise(this.start, "Unterminated string constant"); ++this.pos; } } out += this.input.slice(chunkStart, this.pos++); return this.finishToken(_tokentype.types.string, out); }; // Reads template string tokens. pp.readTmplToken = function () { var out = "", chunkStart = this.pos; for (;;) { if (this.pos >= this.input.length) this.raise(this.start, "Unterminated template"); var ch = this.input.charCodeAt(this.pos); if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${' if (this.pos === this.start && this.type === _tokentype.types.template) { if (ch === 36) { this.pos += 2; return this.finishToken(_tokentype.types.dollarBraceL); } else { ++this.pos; return this.finishToken(_tokentype.types.backQuote); } } out += this.input.slice(chunkStart, this.pos); return this.finishToken(_tokentype.types.template, out); } if (ch === 92) { // '\' out += this.input.slice(chunkStart, this.pos); out += this.readEscapedChar(true); chunkStart = this.pos; } else if (_whitespace.isNewLine(ch)) { out += this.input.slice(chunkStart, this.pos); ++this.pos; switch (ch) { case 13: if (this.input.charCodeAt(this.pos) === 10) ++this.pos; case 10: out += "\n"; break; default: out += String.fromCharCode(ch); break; } if (this.options.locations) { ++this.curLine; this.lineStart = this.pos; } chunkStart = this.pos; } else { ++this.pos; } } }; // Used to read escaped characters pp.readEscapedChar = function (inTemplate) { var ch = this.input.charCodeAt(++this.pos); ++this.pos; switch (ch) { case 110: return "\n"; // 'n' -> '\n' case 114: return "\r"; // 'r' -> '\r' case 120: return String.fromCharCode(this.readHexChar(2)); // 'x' case 117: return codePointToString(this.readCodePoint()); // 'u' case 116: return "\t"; // 't' -> '\t' case 98: return "\b"; // 'b' -> '\b' case 118: return "\u000b"; // 'v' -> '\u000b' case 102: return "\f"; // 'f' -> '\f' case 13: if (this.input.charCodeAt(this.pos) === 10) ++this.pos; // '\r\n' case 10: // ' \n' if (this.options.locations) { this.lineStart = this.pos;++this.curLine; } return ""; default: if (ch >= 48 && ch <= 55) { var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0]; var octal = parseInt(octalStr, 8); if (octal > 255) { octalStr = octalStr.slice(0, -1); octal = parseInt(octalStr, 8); } if (octalStr !== "0" && (this.strict || inTemplate)) { this.raise(this.pos - 2, "Octal literal in strict mode"); } this.pos += octalStr.length - 1; return String.fromCharCode(octal); } return String.fromCharCode(ch); } }; // Used to read character escape sequences ('\x', '\u', '\U'). pp.readHexChar = function (len) { var codePos = this.pos; var n = this.readInt(16, len); if (n === null) this.raise(codePos, "Bad character escape sequence"); return n; }; // Read an identifier, and return it as a string. Sets `this.containsEsc` // to whether the word contained a '\u' escape. // // Incrementally adds only escaped chars, adding other chunks as-is // as a micro-optimization. pp.readWord1 = function () { this.containsEsc = false; var word = "", first = true, chunkStart = this.pos; var astral = this.options.ecmaVersion >= 6; while (this.pos < this.input.length) { var ch = this.fullCharCodeAtPos(); if (_identifier.isIdentifierChar(ch, astral)) { this.pos += ch <= 0xffff ? 1 : 2; } else if (ch === 92) { // "\" this.containsEsc = true; word += this.input.slice(chunkStart, this.pos); var escStart = this.pos; if (this.input.charCodeAt(++this.pos) != 117) // "u" this.raise(this.pos, "Expecting Unicode escape sequence \\uXXXX"); ++this.pos; var esc = this.readCodePoint(); if (!(first ? _identifier.isIdentifierStart : _identifier.isIdentifierChar)(esc, astral)) this.raise(escStart, "Invalid Unicode escape"); word += codePointToString(esc); chunkStart = this.pos; } else { break; } first = false; } return word + this.input.slice(chunkStart, this.pos); }; // Read an identifier or keyword token. Will check for reserved // words when necessary. pp.readWord = function () { var word = this.readWord1(); var type = _tokentype.types.name; if ((this.options.ecmaVersion >= 6 || !this.containsEsc) && this.keywords.test(word)) type = _tokentype.keywords[word]; return this.finishToken(type, word); }; },{"./identifier":2,"./locutil":5,"./state":10,"./tokentype":14,"./whitespace":16}],14:[function(_dereq_,module,exports){ // ## Token types // The assignment of fine-grained, information-carrying type objects // allows the tokenizer to store the information it has about a // token in a way that is very cheap for the parser to look up. // All token type variables start with an underscore, to make them // easy to recognize. // The `beforeExpr` property is used to disambiguate between regular // expressions and divisions. It is set on all token types that can // be followed by an expression (thus, a slash after them would be a // regular expression). // // The `startsExpr` property is used to check if the token ends a // `yield` expression. It is set on all token types that either can // directly start an expression (like a quotation mark) or can // continue an expression (like the body of a string). // // `isLoop` marks a keyword as starting a loop, which is important // to know when parsing a label, in order to allow or disallow // continue jumps to that label. "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var TokenType = function TokenType(label) { var conf = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, TokenType); this.label = label; this.keyword = conf.keyword; this.beforeExpr = !!conf.beforeExpr; this.startsExpr = !!conf.startsExpr; this.isLoop = !!conf.isLoop; this.isAssign = !!conf.isAssign; this.prefix = !!conf.prefix; this.postfix = !!conf.postfix; this.binop = conf.binop || null; this.updateContext = null; }; exports.TokenType = TokenType; function binop(name, prec) { return new TokenType(name, { beforeExpr: true, binop: prec }); } var beforeExpr = { beforeExpr: true }, startsExpr = { startsExpr: true }; var types = { num: new TokenType("num", startsExpr), regexp: new TokenType("regexp", startsExpr), string: new TokenType("string", startsExpr), name: new TokenType("name", startsExpr), eof: new TokenType("eof"), // Punctuation token types. bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }), bracketR: new TokenType("]"), braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }), braceR: new TokenType("}"), parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }), parenR: new TokenType(")"), comma: new TokenType(",", beforeExpr), semi: new TokenType(";", beforeExpr), colon: new TokenType(":", beforeExpr), dot: new TokenType("."), question: new TokenType("?", beforeExpr), arrow: new TokenType("=>", beforeExpr), template: new TokenType("template"), ellipsis: new TokenType("...", beforeExpr), backQuote: new TokenType("`", startsExpr), dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }), // Operators. These carry several kinds of properties to help the // parser use them properly (the presence of these properties is // what categorizes them as operators). // // `binop`, when present, specifies that this operator is a binary // operator, and will refer to its precedence. // // `prefix` and `postfix` mark the operator as a prefix or postfix // unary operator. // // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as // binary operators with a very low precedence, that should result // in AssignmentExpression nodes. eq: new TokenType("=", { beforeExpr: true, isAssign: true }), assign: new TokenType("_=", { beforeExpr: true, isAssign: true }), incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }), prefix: new TokenType("prefix", { beforeExpr: true, prefix: true, startsExpr: true }), logicalOR: binop("||", 1), logicalAND: binop("&&", 2), bitwiseOR: binop("|", 3), bitwiseXOR: binop("^", 4), bitwiseAND: binop("&", 5), equality: binop("==/!=", 6), relational: binop("</>", 7), bitShift: binop("<</>>", 8), plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }), modulo: binop("%", 10), star: binop("*", 10), slash: binop("/", 10) }; exports.types = types; // Map keyword names to token types. var keywords = {}; exports.keywords = keywords; // Succinct definitions of keyword token types function kw(name) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; options.keyword = name; keywords[name] = types["_" + name] = new TokenType(name, options); } kw("break"); kw("case", beforeExpr); kw("catch"); kw("continue"); kw("debugger"); kw("default", beforeExpr); kw("do", { isLoop: true, beforeExpr: true }); kw("else", beforeExpr); kw("finally"); kw("for", { isLoop: true }); kw("function", startsExpr); kw("if"); kw("return", beforeExpr); kw("switch"); kw("throw", beforeExpr); kw("try"); kw("var"); kw("let"); kw("const"); kw("while", { isLoop: true }); kw("with"); kw("new", { beforeExpr: true, startsExpr: true }); kw("this", startsExpr); kw("super", startsExpr); kw("class"); kw("extends", beforeExpr); kw("export"); kw("import"); kw("yield", { beforeExpr: true, startsExpr: true }); kw("null", startsExpr); kw("true", startsExpr); kw("false", startsExpr); kw("in", { beforeExpr: true, binop: 7 }); kw("instanceof", { beforeExpr: true, binop: 7 }); kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true }); kw("void", { beforeExpr: true, prefix: true, startsExpr: true }); kw("delete", { beforeExpr: true, prefix: true, startsExpr: true }); },{}],15:[function(_dereq_,module,exports){ "use strict"; exports.__esModule = true; exports.isArray = isArray; exports.has = has; function isArray(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; } // Checks if an object has a property. function has(obj, propName) { return Object.prototype.hasOwnProperty.call(obj, propName); } },{}],16:[function(_dereq_,module,exports){ // Matches a whole line break (where CRLF is considered a single // line break). Used to count lines. "use strict"; exports.__esModule = true; exports.isNewLine = isNewLine; var lineBreak = /\r\n?|\n|\u2028|\u2029/; exports.lineBreak = lineBreak; var lineBreakG = new RegExp(lineBreak.source, "g"); exports.lineBreakG = lineBreakG; function isNewLine(code) { return code === 10 || code === 13 || code === 0x2028 || code == 0x2029; } var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/; exports.nonASCIIwhitespace = nonASCIIwhitespace; },{}]},{},[3])(3) }); ```
/content/code_sandbox/node_modules/jsdom/node_modules/acorn/dist/acorn.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
31,260
```javascript var DomUtils = require("domutils"), hasAttrib = DomUtils.hasAttrib, getAttributeValue = DomUtils.getAttributeValue, falseFunc = require("boolbase").falseFunc; //path_to_url#L469 var reChars = /[-[\]{}()*+?.,\\^$|#\s]/g; /* attribute selectors */ var attributeRules = { __proto__: null, equals: function(next, data){ var name = data.name, value = data.value; if(data.ignoreCase){ value = value.toLowerCase(); return function equalsIC(elem){ var attr = getAttributeValue(elem, name); return attr != null && attr.toLowerCase() === value && next(elem); }; } return function equals(elem){ return getAttributeValue(elem, name) === value && next(elem); }; }, hyphen: function(next, data){ var name = data.name, value = data.value, len = value.length; if(data.ignoreCase){ value = value.toLowerCase(); return function hyphenIC(elem){ var attr = getAttributeValue(elem, name); return attr != null && (attr.length === len || attr.charAt(len) === "-") && attr.substr(0, len).toLowerCase() === value && next(elem); }; } return function hyphen(elem){ var attr = getAttributeValue(elem, name); return attr != null && attr.substr(0, len) === value && (attr.length === len || attr.charAt(len) === "-") && next(elem); }; }, element: function(next, data){ var name = data.name, value = data.value; if(/\s/.test(value)){ return falseFunc; } value = value.replace(reChars, "\\$&"); var pattern = "(?:^|\\s)" + value + "(?:$|\\s)", flags = data.ignoreCase ? "i" : "", regex = new RegExp(pattern, flags); return function element(elem){ var attr = getAttributeValue(elem, name); return attr != null && regex.test(attr) && next(elem); }; }, exists: function(next, data){ var name = data.name; return function exists(elem){ return hasAttrib(elem, name) && next(elem); }; }, start: function(next, data){ var name = data.name, value = data.value, len = value.length; if(len === 0){ return falseFunc; } if(data.ignoreCase){ value = value.toLowerCase(); return function startIC(elem){ var attr = getAttributeValue(elem, name); return attr != null && attr.substr(0, len).toLowerCase() === value && next(elem); }; } return function start(elem){ var attr = getAttributeValue(elem, name); return attr != null && attr.substr(0, len) === value && next(elem); }; }, end: function(next, data){ var name = data.name, value = data.value, len = -value.length; if(len === 0){ return falseFunc; } if(data.ignoreCase){ value = value.toLowerCase(); return function endIC(elem){ var attr = getAttributeValue(elem, name); return attr != null && attr.substr(len).toLowerCase() === value && next(elem); }; } return function end(elem){ var attr = getAttributeValue(elem, name); return attr != null && attr.substr(len) === value && next(elem); }; }, any: function(next, data){ var name = data.name, value = data.value; if(value === ""){ return falseFunc; } if(data.ignoreCase){ var regex = new RegExp(value.replace(reChars, "\\$&"), "i"); return function anyIC(elem){ var attr = getAttributeValue(elem, name); return attr != null && regex.test(attr) && next(elem); }; } return function any(elem){ var attr = getAttributeValue(elem, name); return attr != null && attr.indexOf(value) >= 0 && next(elem); }; }, not: function(next, data){ var name = data.name, value = data.value; if(value === ""){ return function notEmpty(elem){ return !!getAttributeValue(elem, name) && next(elem); }; } else if(data.ignoreCase){ value = value.toLowerCase(); return function notIC(elem){ var attr = getAttributeValue(elem, name); return attr != null && attr.toLowerCase() !== value && next(elem); }; } return function not(elem){ return getAttributeValue(elem, name) !== value && next(elem); }; } }; module.exports = { compile: function(next, data, options){ if(options && options.strict && ( data.ignoreCase || data.action === "not" )) throw SyntaxError("Unsupported attribute selector"); return attributeRules[data.action](next, data); }, rules: attributeRules }; ```
/content/code_sandbox/node_modules/css-select/lib/attributes.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,108
```javascript module.exports = sortByProcedure; /* sort the parts of the passed selector, as there is potential for optimization (some types of selectors are faster than others) */ var procedure = require("./procedure.json"); var attributes = { __proto__: null, exists: 10, equals: 8, not: 7, start: 6, end: 6, any: 5, hyphen: 4, element: 4 }; function sortByProcedure(arr){ var procs = arr.map(getProcedure); for(var i = 1; i < arr.length; i++){ var procNew = procs[i]; if(procNew < 0) continue; for(var j = i - 1; j >= 0 && procNew < procs[j]; j--){ var token = arr[j + 1]; arr[j + 1] = arr[j]; arr[j] = token; procs[j + 1] = procs[j]; procs[j] = procNew; } } } function getProcedure(token){ var proc = procedure[token.type]; if(proc === procedure.attribute){ proc = attributes[token.action]; if(proc === attributes.equals && token.name === "id"){ //prefer ID selectors (eg. #ID) proc = 9; } if(token.ignoreCase){ //ignoreCase adds some overhead, prefer "normal" token //this is a binary operation, to ensure it's still an int proc >>= 1; } } else if(proc === procedure.pseudo){ if(!token.data){ proc = 3; } else if(token.name === "has" || token.name === "contains"){ proc = 0; //expensive in any case } else if(token.name === "matches" || token.name === "not"){ proc = 0; for(var i = 0; i < token.data.length; i++){ //TODO better handling of complex selectors if(token.data[i].length !== 1) continue; var cur = getProcedure(token.data[i][0]); //avoid executing :has or :contains if(cur === 0){ proc = 0; break; } if(cur > proc) proc = cur; } if(token.data.length > 1 && proc > 0) proc -= 1; } else { proc = 1; } } return proc; } ```
/content/code_sandbox/node_modules/css-select/lib/sort.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
550
```javascript var DomUtils = require("domutils"), isTag = DomUtils.isTag, getParent = DomUtils.getParent, getChildren = DomUtils.getChildren, getSiblings = DomUtils.getSiblings, getName = DomUtils.getName; /* all available rules */ module.exports = { __proto__: null, attribute: require("./attributes.js").compile, pseudo: require("./pseudos.js").compile, //tags tag: function(next, data){ var name = data.name; return function tag(elem){ return getName(elem) === name && next(elem); }; }, //traversal descendant: function(next, rule, options, context, acceptSelf){ return function descendant(elem){ if (acceptSelf && next(elem)) return true; var found = false; while(!found && (elem = getParent(elem))){ found = next(elem); } return found; }; }, parent: function(next, data, options){ if(options && options.strict) throw SyntaxError("Parent selector isn't part of CSS3"); return function parent(elem){ return getChildren(elem).some(test); }; function test(elem){ return isTag(elem) && next(elem); } }, child: function(next){ return function child(elem){ var parent = getParent(elem); return !!parent && next(parent); }; }, sibling: function(next){ return function sibling(elem){ var siblings = getSiblings(elem); for(var i = 0; i < siblings.length; i++){ if(isTag(siblings[i])){ if(siblings[i] === elem) break; if(next(siblings[i])) return true; } } return false; }; }, adjacent: function(next){ return function adjacent(elem){ var siblings = getSiblings(elem), lastElement; for(var i = 0; i < siblings.length; i++){ if(isTag(siblings[i])){ if(siblings[i] === elem) break; lastElement = siblings[i]; } } return !!lastElement && next(lastElement); }; }, universal: function(next){ return next; } }; ```
/content/code_sandbox/node_modules/css-select/lib/general.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
482
```javascript /* compiles a selector to an executable function */ module.exports = compile; module.exports.compileUnsafe = compileUnsafe; module.exports.compileToken = compileToken; var parse = require("css-what"), DomUtils = require("domutils"), isTag = DomUtils.isTag, Rules = require("./general.js"), sortRules = require("./sort.js"), BaseFuncs = require("boolbase"), trueFunc = BaseFuncs.trueFunc, falseFunc = BaseFuncs.falseFunc, procedure = require("./procedure.json"); function compile(selector, options, context){ var next = compileUnsafe(selector, options, context); return wrap(next); } function wrap(next){ return function base(elem){ return isTag(elem) && next(elem); }; } function compileUnsafe(selector, options, context){ var token = parse(selector, options); return compileToken(token, options, context); } function includesScopePseudo(t){ return t.type === "pseudo" && ( t.name === "scope" || ( Array.isArray(t.data) && t.data.some(function(data){ return data.some(includesScopePseudo); }) ) ); } var DESCENDANT_TOKEN = {type: "descendant"}, SCOPE_TOKEN = {type: "pseudo", name: "scope"}, PLACEHOLDER_ELEMENT = {}, getParent = DomUtils.getParent; //CSS 4 Spec (Draft): 3.3.1. Absolutizing a Scope-relative Selector //path_to_url#absolutizing function absolutize(token, context){ //TODO better check if context is document var hasContext = !!context && !!context.length && context.every(function(e){ return e === PLACEHOLDER_ELEMENT || !!getParent(e); }); token.forEach(function(t){ if(t.length > 0 && isTraversal(t[0]) && t[0].type !== "descendant"){ //don't return in else branch } else if(hasContext && !includesScopePseudo(t)){ t.unshift(DESCENDANT_TOKEN); } else { return; } t.unshift(SCOPE_TOKEN); }); } function compileToken(token, options, context){ token = token.filter(function(t){ return t.length > 0; }); token.forEach(sortRules); var isArrayContext = Array.isArray(context); context = (options && options.context) || context; if(context && !isArrayContext) context = [context]; absolutize(token, context); return token .map(function(rules){ return compileRules(rules, options, context, isArrayContext); }) .reduce(reduceRules, falseFunc); } function isTraversal(t){ return procedure[t.type] < 0; } function compileRules(rules, options, context, isArrayContext){ var acceptSelf = (isArrayContext && rules[0].name === "scope" && rules[1].type === "descendant"); return rules.reduce(function(func, rule, index){ if(func === falseFunc) return func; return Rules[rule.type](func, rule, options, context, acceptSelf && index === 1); }, options && options.rootFunc || trueFunc); } function reduceRules(a, b){ if(b === falseFunc || a === trueFunc){ return a; } if(a === falseFunc || b === trueFunc){ return b; } return function combine(elem){ return a(elem) || b(elem); }; } //:not, :has and :matches have to compile selectors //doing this in lib/pseudos.js would lead to circular dependencies, //so we add them here var Pseudos = require("./pseudos.js"), filters = Pseudos.filters, existsOne = DomUtils.existsOne, isTag = DomUtils.isTag, getChildren = DomUtils.getChildren; function containsTraversal(t){ return t.some(isTraversal); } filters.not = function(next, token, options, context){ var opts = { xmlMode: !!(options && options.xmlMode), strict: !!(options && options.strict) }; if(opts.strict){ if(token.length > 1 || token.some(containsTraversal)){ throw new SyntaxError("complex selectors in :not aren't allowed in strict mode"); } } var func = compileToken(token, opts, context); if(func === falseFunc) return next; if(func === trueFunc) return falseFunc; return function(elem){ return !func(elem) && next(elem); }; }; filters.has = function(next, token, options){ var opts = { xmlMode: !!(options && options.xmlMode), strict: !!(options && options.strict) }; //FIXME: Uses an array as a pointer to the current element (side effects) var context = token.some(containsTraversal) ? [PLACEHOLDER_ELEMENT] : null; var func = compileToken(token, opts, context); if(func === falseFunc) return falseFunc; if(func === trueFunc) return function(elem){ return getChildren(elem).some(isTag) && next(elem); }; func = wrap(func); if(context){ return function has(elem){ return next(elem) && ( (context[0] = elem), existsOne(func, getChildren(elem)) ); }; } return function has(elem){ return next(elem) && existsOne(func, getChildren(elem)); }; }; filters.matches = function(next, token, options, context){ var opts = { xmlMode: !!(options && options.xmlMode), strict: !!(options && options.strict), rootFunc: next }; return compileToken(token, opts, context); }; ```
/content/code_sandbox/node_modules/css-select/lib/compile.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,209
```javascript "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()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const debug_1 = __importDefault(require("debug")); const stream_1 = require("stream"); const crypto_1 = require("crypto"); const data_uri_to_buffer_1 = __importDefault(require("data-uri-to-buffer")); const notmodified_1 = __importDefault(require("./notmodified")); const debug = debug_1.default('get-uri:data'); class DataReadable extends stream_1.Readable { constructor(hash, buf) { super(); this.push(buf); this.push(null); this.hash = hash; } } /** * Returns a Readable stream from a "data:" URI. */ function get({ href: uri }, { cache }) { return __awaiter(this, void 0, void 0, function* () { // need to create a SHA1 hash of the URI string, for cacheability checks // in future `getUri()` calls with the same data URI passed in. const shasum = crypto_1.createHash('sha1'); shasum.update(uri); const hash = shasum.digest('hex'); debug('generated SHA1 hash for "data:" URI: %o', hash); // check if the cache is the same "data:" URI that was previously passed in. if (cache && cache.hash === hash) { debug('got matching cache SHA1 hash: %o', hash); throw new notmodified_1.default(); } else { debug('creating Readable stream from "data:" URI buffer'); const buf = data_uri_to_buffer_1.default(uri); return new DataReadable(hash, buf); } }); } exports.default = get; //# sourceMappingURL=data.js.map ```
/content/code_sandbox/node_modules/get-uri/dist/data.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
566
```javascript /* pseudo selectors --- they are available in two forms: * filters called when the selector is compiled and return a function that needs to return next() * pseudos get called on execution they need to return a boolean */ var DomUtils = require("domutils"), isTag = DomUtils.isTag, getText = DomUtils.getText, getParent = DomUtils.getParent, getChildren = DomUtils.getChildren, getSiblings = DomUtils.getSiblings, hasAttrib = DomUtils.hasAttrib, getName = DomUtils.getName, getAttribute= DomUtils.getAttributeValue, getNCheck = require("nth-check"), checkAttrib = require("./attributes.js").rules.equals, BaseFuncs = require("boolbase"), trueFunc = BaseFuncs.trueFunc, falseFunc = BaseFuncs.falseFunc; //helper methods function getFirstElement(elems){ for(var i = 0; elems && i < elems.length; i++){ if(isTag(elems[i])) return elems[i]; } } function getAttribFunc(name, value){ var data = {name: name, value: value}; return function attribFunc(next){ return checkAttrib(next, data); }; } function getChildFunc(next){ return function(elem){ return !!getParent(elem) && next(elem); }; } var filters = { contains: function(next, text){ return function contains(elem){ return next(elem) && getText(elem).indexOf(text) >= 0; }; }, icontains: function(next, text){ var itext = text.toLowerCase(); return function icontains(elem){ return next(elem) && getText(elem).toLowerCase().indexOf(itext) >= 0; }; }, //location specific methods "nth-child": function(next, rule){ var func = getNCheck(rule); if(func === falseFunc) return func; if(func === trueFunc) return getChildFunc(next); return function nthChild(elem){ var siblings = getSiblings(elem); for(var i = 0, pos = 0; i < siblings.length; i++){ if(isTag(siblings[i])){ if(siblings[i] === elem) break; else pos++; } } return func(pos) && next(elem); }; }, "nth-last-child": function(next, rule){ var func = getNCheck(rule); if(func === falseFunc) return func; if(func === trueFunc) return getChildFunc(next); return function nthLastChild(elem){ var siblings = getSiblings(elem); for(var pos = 0, i = siblings.length - 1; i >= 0; i--){ if(isTag(siblings[i])){ if(siblings[i] === elem) break; else pos++; } } return func(pos) && next(elem); }; }, "nth-of-type": function(next, rule){ var func = getNCheck(rule); if(func === falseFunc) return func; if(func === trueFunc) return getChildFunc(next); return function nthOfType(elem){ var siblings = getSiblings(elem); for(var pos = 0, i = 0; i < siblings.length; i++){ if(isTag(siblings[i])){ if(siblings[i] === elem) break; if(getName(siblings[i]) === getName(elem)) pos++; } } return func(pos) && next(elem); }; }, "nth-last-of-type": function(next, rule){ var func = getNCheck(rule); if(func === falseFunc) return func; if(func === trueFunc) return getChildFunc(next); return function nthLastOfType(elem){ var siblings = getSiblings(elem); for(var pos = 0, i = siblings.length - 1; i >= 0; i--){ if(isTag(siblings[i])){ if(siblings[i] === elem) break; if(getName(siblings[i]) === getName(elem)) pos++; } } return func(pos) && next(elem); }; }, //TODO determine the actual root element root: function(next){ return function(elem){ return !getParent(elem) && next(elem); }; }, scope: function(next, rule, options, context){ if(!context || context.length === 0){ //equivalent to :root return filters.root(next); } if(context.length === 1){ //NOTE: can't be unpacked, as :has uses this for side-effects return function(elem){ return context[0] === elem && next(elem); }; } return function(elem){ return context.indexOf(elem) >= 0 && next(elem); }; }, //jQuery extensions (others follow as pseudos) checkbox: getAttribFunc("type", "checkbox"), file: getAttribFunc("type", "file"), password: getAttribFunc("type", "password"), radio: getAttribFunc("type", "radio"), reset: getAttribFunc("type", "reset"), image: getAttribFunc("type", "image"), submit: getAttribFunc("type", "submit") }; //while filters are precompiled, pseudos get called when they are needed var pseudos = { empty: function(elem){ return !getChildren(elem).some(function(elem){ return isTag(elem) || elem.type === "text"; }); }, "first-child": function(elem){ return getFirstElement(getSiblings(elem)) === elem; }, "last-child": function(elem){ var siblings = getSiblings(elem); for(var i = siblings.length - 1; i >= 0; i--){ if(siblings[i] === elem) return true; if(isTag(siblings[i])) break; } return false; }, "first-of-type": function(elem){ var siblings = getSiblings(elem); for(var i = 0; i < siblings.length; i++){ if(isTag(siblings[i])){ if(siblings[i] === elem) return true; if(getName(siblings[i]) === getName(elem)) break; } } return false; }, "last-of-type": function(elem){ var siblings = getSiblings(elem); for(var i = siblings.length-1; i >= 0; i--){ if(isTag(siblings[i])){ if(siblings[i] === elem) return true; if(getName(siblings[i]) === getName(elem)) break; } } return false; }, "only-of-type": function(elem){ var siblings = getSiblings(elem); for(var i = 0, j = siblings.length; i < j; i++){ if(isTag(siblings[i])){ if(siblings[i] === elem) continue; if(getName(siblings[i]) === getName(elem)) return false; } } return true; }, "only-child": function(elem){ var siblings = getSiblings(elem); for(var i = 0; i < siblings.length; i++){ if(isTag(siblings[i]) && siblings[i] !== elem) return false; } return true; }, //:matches(a, area, link)[href] link: function(elem){ return hasAttrib(elem, "href"); }, visited: falseFunc, //seems to be a valid implementation //TODO: :any-link once the name is finalized (as an alias of :link) //forms //to consider: :target //:matches([selected], select:not([multiple]):not(> option[selected]) > option:first-of-type) selected: function(elem){ if(hasAttrib(elem, "selected")) return true; else if(getName(elem) !== "option") return false; //the first <option> in a <select> is also selected var parent = getParent(elem); if( !parent || getName(parent) !== "select" || hasAttrib(parent, "multiple") ) return false; var siblings = getChildren(parent), sawElem = false; for(var i = 0; i < siblings.length; i++){ if(isTag(siblings[i])){ if(siblings[i] === elem){ sawElem = true; } else if(!sawElem){ return false; } else if(hasAttrib(siblings[i], "selected")){ return false; } } } return sawElem; }, //path_to_url#disabled-elements //:matches( // :matches(button, input, select, textarea, menuitem, optgroup, option)[disabled], // optgroup[disabled] > option), // fieldset[disabled] * //TODO not child of first <legend> //) disabled: function(elem){ return hasAttrib(elem, "disabled"); }, enabled: function(elem){ return !hasAttrib(elem, "disabled"); }, //:matches(:matches(:radio, :checkbox)[checked], :selected) (TODO menuitem) checked: function(elem){ return hasAttrib(elem, "checked") || pseudos.selected(elem); }, //:matches(input, select, textarea)[required] required: function(elem){ return hasAttrib(elem, "required"); }, //:matches(input, select, textarea):not([required]) optional: function(elem){ return !hasAttrib(elem, "required"); }, //jQuery extensions //:not(:empty) parent: function(elem){ return !pseudos.empty(elem); }, //:matches(h1, h2, h3, h4, h5, h6) header: function(elem){ var name = getName(elem); return name === "h1" || name === "h2" || name === "h3" || name === "h4" || name === "h5" || name === "h6"; }, //:matches(button, input[type=button]) button: function(elem){ var name = getName(elem); return name === "button" || name === "input" && getAttribute(elem, "type") === "button"; }, //:matches(input, textarea, select, button) input: function(elem){ var name = getName(elem); return name === "input" || name === "textarea" || name === "select" || name === "button"; }, //input:matches(:not([type!='']), [type='text' i]) text: function(elem){ var attr; return getName(elem) === "input" && ( !(attr = getAttribute(elem, "type")) || attr.toLowerCase() === "text" ); } }; function verifyArgs(func, name, subselect){ if(subselect === null){ if(func.length > 1 && name !== "scope"){ throw new SyntaxError("pseudo-selector :" + name + " requires an argument"); } } else { if(func.length === 1){ throw new SyntaxError("pseudo-selector :" + name + " doesn't have any arguments"); } } } //FIXME this feels hacky var re_CSS3 = /^(?:(?:nth|last|first|only)-(?:child|of-type)|root|empty|(?:en|dis)abled|checked|not)$/; module.exports = { compile: function(next, data, options, context){ var name = data.name, subselect = data.data; if(options && options.strict && !re_CSS3.test(name)){ throw SyntaxError(":" + name + " isn't part of CSS3"); } if(typeof filters[name] === "function"){ verifyArgs(filters[name], name, subselect); return filters[name](next, subselect, options, context); } else if(typeof pseudos[name] === "function"){ var func = pseudos[name]; verifyArgs(func, name, subselect); if(next === trueFunc) return func; return function pseudoArgs(elem){ return func(elem, subselect) && next(elem); }; } else { throw new SyntaxError("unmatched pseudo-class :" + name); } }, filters: filters, pseudos: pseudos }; ```
/content/code_sandbox/node_modules/css-select/lib/pseudos.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,681
```javascript "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const https_1 = __importDefault(require("https")); const http_1 = __importDefault(require("./http")); /** * Returns a Readable stream from an "https:" URI. */ function get(parsed, opts) { return http_1.default(parsed, Object.assign(Object.assign({}, opts), { http: https_1.default })); } exports.default = get; //# sourceMappingURL=https.js.map ```
/content/code_sandbox/node_modules/get-uri/dist/https.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
130
```javascript "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; const debug_1 = __importDefault(require("debug")); const url_1 = require("url"); // Built-in protocols const data_1 = __importDefault(require("./data")); const file_1 = __importDefault(require("./file")); const ftp_1 = __importDefault(require("./ftp")); const http_1 = __importDefault(require("./http")); const https_1 = __importDefault(require("./https")); const debug = debug_1.default('get-uri'); function getUri(uri, opts, fn) { const p = new Promise((resolve, reject) => { debug('getUri(%o)', uri); if (typeof opts === 'function') { fn = opts; opts = undefined; } if (!uri) { reject(new TypeError('Must pass in a URI to "get"')); return; } const parsed = url_1.parse(uri); // Strip trailing `:` const protocol = (parsed.protocol || '').replace(/:$/, ''); if (!protocol) { reject(new TypeError(`URI does not contain a protocol: ${uri}`)); return; } const getter = getUri.protocols[protocol]; if (typeof getter !== 'function') { throw new TypeError(`Unsupported protocol "${protocol}" specified in URI: ${uri}`); } resolve(getter(parsed, opts || {})); }); if (typeof fn === 'function') { p.then(rtn => fn(null, rtn), err => fn(err)); } else { return p; } } (function (getUri) { getUri.protocols = { data: data_1.default, file: file_1.default, ftp: ftp_1.default, http: http_1.default, https: https_1.default }; })(getUri || (getUri = {})); module.exports = getUri; //# sourceMappingURL=index.js.map ```
/content/code_sandbox/node_modules/get-uri/dist/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
434
```javascript "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()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const http_1 = __importDefault(require("http")); const https_1 = __importDefault(require("https")); const once_1 = __importDefault(require("@tootallnate/once")); const debug_1 = __importDefault(require("debug")); const url_1 = require("url"); const http_error_1 = __importDefault(require("./http-error")); const notfound_1 = __importDefault(require("./notfound")); const notmodified_1 = __importDefault(require("./notmodified")); const debug = debug_1.default('get-uri:http'); /** * Returns a Readable stream from an "http:" URI. */ function get(parsed, opts) { return __awaiter(this, void 0, void 0, function* () { debug('GET %o', parsed.href); const cache = getCache(parsed, opts.cache); // first check the previous Expires and/or Cache-Control headers // of a previous response if a `cache` was provided if (cache && isFresh(cache) && typeof cache.statusCode === 'number') { // check for a 3xx "redirect" status code on the previous cache const type = (cache.statusCode / 100) | 0; if (type === 3 && cache.headers.location) { debug('cached redirect'); throw new Error('TODO: implement cached redirects!'); } // otherwise we assume that it's the destination endpoint, // since there's nowhere else to redirect to throw new notmodified_1.default(); } // 5 redirects allowed by default const maxRedirects = typeof opts.maxRedirects === 'number' ? opts.maxRedirects : 5; debug('allowing %o max redirects', maxRedirects); let mod; if (opts.http) { // the `https` module passed in from the "http.js" file mod = opts.http; debug('using secure `https` core module'); } else { mod = http_1.default; debug('using `http` core module'); } const options = Object.assign(Object.assign({}, opts), parsed); // add "cache validation" headers if a `cache` was provided if (cache) { if (!options.headers) { options.headers = {}; } const lastModified = cache.headers['last-modified']; if (lastModified) { options.headers['If-Modified-Since'] = lastModified; debug('added "If-Modified-Since" request header: %o', lastModified); } const etag = cache.headers.etag; if (etag) { options.headers['If-None-Match'] = etag; debug('added "If-None-Match" request header: %o', etag); } } const req = mod.get(options); const res = yield once_1.default(req, 'response'); const code = res.statusCode || 0; // assign a Date to this response for the "Cache-Control" delta calculation res.date = Date.now(); res.parsed = parsed; debug('got %o response status code', code); // any 2xx response is a "success" code let type = (code / 100) | 0; // check for a 3xx "redirect" status code let location = res.headers.location; if (type === 3 && location) { if (!opts.redirects) opts.redirects = []; let redirects = opts.redirects; if (redirects.length < maxRedirects) { debug('got a "redirect" status code with Location: %o', location); // flush this response - we're not going to use it res.resume(); // hang on to this Response object for the "redirects" Array redirects.push(res); let newUri = url_1.resolve(parsed.href, location); debug('resolved redirect URL: %o', newUri); let left = maxRedirects - redirects.length; debug('%o more redirects allowed after this one', left); // check if redirecting to a different protocol let parsedUrl = url_1.parse(newUri); if (parsedUrl.protocol !== parsed.protocol) { opts.http = parsedUrl.protocol === 'https:' ? https_1.default : undefined; } return get(parsedUrl, opts); } } // if we didn't get a 2xx "success" status code, then create an Error object if (type !== 2) { res.resume(); if (code === 304) { throw new notmodified_1.default(); } else if (code === 404) { throw new notfound_1.default(); } // other HTTP-level error throw new http_error_1.default(code); } if (opts.redirects) { // store a reference to the "redirects" Array on the Response object so that // they can be inspected during a subsequent call to GET the same URI res.redirects = opts.redirects; } return res; }); } exports.default = get; /** * Returns `true` if the provided cache's "freshness" is valid. That is, either * the Cache-Control header or Expires header values are still within the allowed * time period. * * @return {Boolean} * @api private */ function isFresh(cache) { let fresh = false; let expires = parseInt(cache.headers.expires || '', 10); const cacheControl = cache.headers['cache-control']; if (cacheControl) { // for Cache-Control rules, see: path_to_url#CACHE-CONTROL debug('Cache-Control: %o', cacheControl); const parts = cacheControl.split(/,\s*?\b/); for (let i = 0; i < parts.length; i++) { const part = parts[i]; const subparts = part.split('='); const name = subparts[0]; switch (name) { case 'max-age': expires = (cache.date || 0) + parseInt(subparts[1], 10) * 1000; fresh = Date.now() < expires; if (fresh) { debug('cache is "fresh" due to previous %o Cache-Control param', part); } return fresh; case 'must-revalidate': // XXX: what we supposed to do here? break; case 'no-cache': case 'no-store': debug('cache is "stale" due to explicit %o Cache-Control param', name); return false; default: // ignore unknown cache value break; } } } else if (expires) { // for Expires rules, see: path_to_url#EXPIRES debug('Expires: %o', expires); fresh = Date.now() < expires; if (fresh) { debug('cache is "fresh" due to previous Expires response header'); } return fresh; } return false; } /** * Attempts to return a previous Response object from a previous GET call to the * same URI. * * @api private */ function getCache(parsed, cache) { if (cache) { if (cache.parsed && cache.parsed.href === parsed.href) { return cache; } if (cache.redirects) { for (let i = 0; i < cache.redirects.length; i++) { const c = getCache(parsed, cache.redirects[i]); if (c) { return c; } } } } return null; } //# sourceMappingURL=http.js.map ```
/content/code_sandbox/node_modules/get-uri/dist/http.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,856
```javascript "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const http_1 = require("http"); /** * Error subclass to use when an HTTP application error has occurred. */ class HTTPError extends Error { constructor(statusCode, message = http_1.STATUS_CODES[statusCode]) { super(message); Object.setPrototypeOf(this, new.target.prototype); this.statusCode = statusCode; this.code = `E${String(message) .toUpperCase() .replace(/\s+/g, '')}`; } } exports.default = HTTPError; //# sourceMappingURL=http-error.js.map ```
/content/code_sandbox/node_modules/get-uri/dist/http-error.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
120
```javascript "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * Error subclass to use when the source has not been modified. * * @param {String} message optional "message" property to set * @api protected */ class NotModifiedError extends Error { constructor(message) { super(message || 'Source has not been modified since the provied "cache", re-use previous results'); this.code = 'ENOTMODIFIED'; Object.setPrototypeOf(this, new.target.prototype); } } exports.default = NotModifiedError; //# sourceMappingURL=notmodified.js.map ```
/content/code_sandbox/node_modules/get-uri/dist/notmodified.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
123
```javascript "use strict"; /** * Error subclass to use when the source does not exist at the specified endpoint. * * @param {String} message optional "message" property to set * @api protected */ Object.defineProperty(exports, "__esModule", { value: true }); class NotFoundError extends Error { constructor(message) { super(message || 'File does not exist at the specified endpoint'); this.code = 'ENOTFOUND'; Object.setPrototypeOf(this, new.target.prototype); } } exports.default = NotFoundError; //# sourceMappingURL=notfound.js.map ```
/content/code_sandbox/node_modules/get-uri/dist/notfound.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
114
```javascript "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()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const once_1 = __importDefault(require("@tootallnate/once")); const ftp_1 = __importDefault(require("ftp")); const path_1 = require("path"); const debug_1 = __importDefault(require("debug")); const notfound_1 = __importDefault(require("./notfound")); const notmodified_1 = __importDefault(require("./notmodified")); const debug = debug_1.default('get-uri:ftp'); /** * Returns a Readable stream from an "ftp:" URI. */ function get(parsed, opts) { return __awaiter(this, void 0, void 0, function* () { const { cache } = opts; const filepath = parsed.pathname; let lastModified = null; if (!filepath) { throw new TypeError('No "pathname"!'); } const client = new ftp_1.default(); client.once('greeting', (greeting) => { debug('FTP greeting: %o', greeting); }); function onend() { // close the FTP client socket connection client.end(); } try { opts.host = parsed.hostname || parsed.host || 'localhost'; opts.port = parseInt(parsed.port || '0', 10) || 21; opts.debug = debug; if (parsed.auth) { const [user, password] = parsed.auth.split(':'); opts.user = user; opts.password = password; } // await cb(_ => client.connect(opts, _)); const readyPromise = once_1.default(client, 'ready'); client.connect(opts); yield readyPromise; // first we have to figure out the Last Modified date. // try the MDTM command first, which is an optional extension command. try { lastModified = yield new Promise((resolve, reject) => { client.lastMod(filepath, (err, res) => { return err ? reject(err) : resolve(res); }); }); } catch (err) { // handle the "file not found" error code if (err.code === 550) { throw new notfound_1.default(); } } if (!lastModified) { // Try to get the last modified date via the LIST command (uses // more bandwidth, but is more compatible with older FTP servers const list = yield new Promise((resolve, reject) => { client.list(path_1.dirname(filepath), (err, res) => { return err ? reject(err) : resolve(res); }); }); // attempt to find the "entry" with a matching "name" const name = path_1.basename(filepath); const entry = list.find(e => e.name === name); if (entry) { lastModified = entry.date; } } if (lastModified) { if (isNotModified()) { throw new notmodified_1.default(); } } else { throw new notfound_1.default(); } // XXX: a small timeout seemed necessary otherwise FTP servers // were returning empty sockets for the file occasionally // setTimeout(client.get.bind(client, filepath, onfile), 10); const rs = (yield new Promise((resolve, reject) => { client.get(filepath, (err, res) => { return err ? reject(err) : resolve(res); }); })); rs.once('end', onend); rs.lastModified = lastModified; return rs; } catch (err) { client.destroy(); throw err; } // called when `lastModified` is set, and a "cache" stream was provided function isNotModified() { if (cache && cache.lastModified && lastModified) { return +cache.lastModified === +lastModified; } return false; } }); } exports.default = get; //# sourceMappingURL=ftp.js.map ```
/content/code_sandbox/node_modules/get-uri/dist/ftp.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,040
```javascript "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()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const debug_1 = __importDefault(require("debug")); const fs_1 = require("fs"); const fs_extra_1 = require("fs-extra"); const file_uri_to_path_1 = __importDefault(require("file-uri-to-path")); const notfound_1 = __importDefault(require("./notfound")); const notmodified_1 = __importDefault(require("./notmodified")); const debug = debug_1.default('get-uri:file'); /** * Returns a `fs.ReadStream` instance from a "file:" URI. */ function get({ href: uri }, opts) { return __awaiter(this, void 0, void 0, function* () { const { cache, flags = 'r', mode = 438 // =0666 } = opts; try { // Convert URI Path const filepath = file_uri_to_path_1.default(uri); debug('Normalized pathname: %o', filepath); // `open()` first to get a file descriptor and ensure that the file // exists. const fd = yield fs_extra_1.open(filepath, flags, mode); // Now `fstat()` to check the `mtime` and store the stat object for // the cache. const stat = yield fs_extra_1.fstat(fd); // if a `cache` was provided, check if the file has not been modified if (cache && cache.stat && stat && isNotModified(cache.stat, stat)) { throw new notmodified_1.default(); } // `fs.ReadStream` takes care of calling `fs.close()` on the // fd after it's done reading // @ts-ignore - `@types/node` doesn't allow `null` as file path :/ const rs = fs_1.createReadStream(null, Object.assign(Object.assign({ autoClose: true }, opts), { fd })); rs.stat = stat; return rs; } catch (err) { if (err.code === 'ENOENT') { throw new notfound_1.default(); } throw err; } }); } exports.default = get; // returns `true` if the `mtime` of the 2 stat objects are equal function isNotModified(prev, curr) { return +prev.mtime === +curr.mtime; } //# sourceMappingURL=file.js.map ```
/content/code_sandbox/node_modules/get-uri/dist/file.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
705
```javascript var types = require("./lib/types"); var parse = require("./lib/parser").parse; var Printer = require("./lib/printer").Printer; function print(node, options) { return new Printer(options).print(node); } function prettyPrint(node, options) { return new Printer(options).printGenerically(node); } function run(transformer, options) { return runFile(process.argv[2], transformer, options); } function runFile(path, transformer, options) { require("fs").readFile(path, "utf-8", function(err, code) { if (err) { console.error(err); return; } runString(code, transformer, options); }); } function defaultWriteback(output) { process.stdout.write(output); } function runString(code, transformer, options) { var writeback = options && options.writeback || defaultWriteback; transformer(parse(code, options), function(node) { writeback(print(node, options).code); }); } Object.defineProperties(exports, { /** * Parse a string of code into an augmented syntax tree suitable for * arbitrary modification and reprinting. */ parse: { enumerable: true, value: parse }, /** * Traverse and potentially modify an abstract syntax tree using a * convenient visitor syntax: * * recast.visit(ast, { * names: [], * visitIdentifier: function(path) { * var node = path.value; * this.visitor.names.push(node.name); * this.traverse(path); * } * }); */ visit: { enumerable: true, value: types.visit }, /** * Reprint a modified syntax tree using as much of the original source * code as possible. */ print: { enumerable: true, value: print }, /** * Print without attempting to reuse any original source code. */ prettyPrint: { enumerable: false, value: prettyPrint }, /** * Customized version of require("ast-types"). */ types: { enumerable: false, value: types }, /** * Convenient command-line interface (see e.g. example/add-braces). */ run: { enumerable: false, value: run } }); ```
/content/code_sandbox/node_modules/recast/main.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
506
```javascript // This module was originally created so that Recast could add its own // custom types to the AST type system (in particular, the File type), but // those types are now incorporated into ast-types, so this module doesn't // have much to do anymore. Still, it might prove useful in the future. module.exports = require("ast-types"); ```
/content/code_sandbox/node_modules/recast/lib/types.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
75
```javascript var assert = require("assert"); var types = require("./types"); var n = types.namedTypes; var b = types.builders; var isObject = types.builtInTypes.object; var isArray = types.builtInTypes.array; var isFunction = types.builtInTypes.function; var Patcher = require("./patcher").Patcher; var normalizeOptions = require("./options").normalize; var fromString = require("./lines").fromString; var attachComments = require("./comments").attach; var util = require("./util"); exports.parse = function parse(source, options) { options = normalizeOptions(options); var lines = fromString(source, options); var sourceWithoutTabs = lines.toString({ tabWidth: options.tabWidth, reuseWhitespace: false, useTabs: false }); var comments = []; var program = options.parser.parse(sourceWithoutTabs, { loc: true, locations: true, range: options.range, comment: true, onComment: comments, tolerant: options.tolerant, ecmaVersion: 6, sourceType: 'module' }); // If the source was empty, some parsers give loc.{start,end}.line // values of 0, instead of the minimum of 1. util.fixFaultyLocations(program, lines); program.loc = program.loc || { start: lines.firstPos(), end: lines.lastPos() }; program.loc.lines = lines; program.loc.indent = 0; // Expand the Program node's .loc to include all comments, since // typically its .loc.start and .loc.end will coincide with those of // the first and last statements, respectively, excluding any comments // that fall outside that region. var trueProgramLoc = util.getTrueLoc(program, lines); program.loc.start = trueProgramLoc.start; program.loc.end = trueProgramLoc.end; if (program.comments) { comments = program.comments; delete program.comments; } // In order to ensure we reprint leading and trailing program // comments, wrap the original Program node with a File node. var file = program; if (file.type === "Program") { var file = b.file(program); file.loc = { lines: lines, indent: 0, start: lines.firstPos(), end: lines.lastPos() }; } else if (file.type === "File") { program = file.program; } // Passing file.program here instead of just file means that initial // comments will be attached to program.body[0] instead of program. attachComments( comments, program.body.length ? file.program : file, lines ); // Return a copy of the original AST so that any changes made may be // compared to the original. return new TreeCopier(lines).copy(file); }; function TreeCopier(lines) { assert.ok(this instanceof TreeCopier); this.lines = lines; this.indent = 0; } var TCp = TreeCopier.prototype; TCp.copy = function(node) { if (isArray.check(node)) { return node.map(this.copy, this); } if (!isObject.check(node)) { return node; } util.fixFaultyLocations(node, this.lines); var copy = Object.create(Object.getPrototypeOf(node), { original: { // Provide a link from the copy to the original. value: node, configurable: false, enumerable: false, writable: true } }); var loc = node.loc; var oldIndent = this.indent; var newIndent = oldIndent; if (loc) { // When node is a comment, we set node.loc.indent to // node.loc.start.column so that, when/if we print the comment by // itself, we can strip that much whitespace from the left margin // of the comment. This only really matters for multiline Block // comments, but it doesn't hurt for Line comments. if (node.type === "Block" || node.type === "Line" || this.lines.isPrecededOnlyByWhitespace(loc.start)) { newIndent = this.indent = loc.start.column; } loc.lines = this.lines; loc.indent = newIndent; } var keys = Object.keys(node); var keyCount = keys.length; for (var i = 0; i < keyCount; ++i) { var key = keys[i]; if (key === "loc") { copy[key] = node[key]; } else { copy[key] = this.copy(node[key]); } } this.indent = oldIndent; return copy; }; ```
/content/code_sandbox/node_modules/recast/lib/parser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,012
```javascript var assert = require("assert"); var types = require("./types"); var n = types.namedTypes; var Node = n.Node; var isArray = types.builtInTypes.array; var isNumber = types.builtInTypes.number; function FastPath(value) { assert.ok(this instanceof FastPath); this.stack = [value]; } var FPp = FastPath.prototype; module.exports = FastPath; // Static convenience function for coercing a value to a FastPath. FastPath.from = function(obj) { if (obj instanceof FastPath) { // Return a defensive copy of any existing FastPath instances. return obj.copy(); } if (obj instanceof types.NodePath) { // For backwards compatibility, unroll NodePath instances into // lightweight FastPath [..., name, value] stacks. var copy = Object.create(FastPath.prototype); var stack = [obj.value]; for (var pp; (pp = obj.parentPath); obj = pp) stack.push(obj.name, pp.value); copy.stack = stack.reverse(); return copy; } // Otherwise use obj as the value of the new FastPath instance. return new FastPath(obj); }; FPp.copy = function copy() { var copy = Object.create(FastPath.prototype); copy.stack = this.stack.slice(0); return copy; }; // The name of the current property is always the penultimate element of // this.stack, and always a String. FPp.getName = function getName() { var s = this.stack; var len = s.length; if (len > 1) { return s[len - 2]; } // Since the name is always a string, null is a safe sentinel value to // return if we do not know the name of the (root) value. return null; }; // The value of the current property is always the final element of // this.stack. FPp.getValue = function getValue() { var s = this.stack; return s[s.length - 1]; }; function getNodeHelper(path, count) { var s = path.stack; for (var i = s.length - 1; i >= 0; i -= 2) { var value = s[i]; if (n.Node.check(value) && --count < 0) { return value; } } return null; } FPp.getNode = function getNode(count) { return getNodeHelper(this, ~~count); }; FPp.getParentNode = function getParentNode(count) { return getNodeHelper(this, ~~count + 1); }; // The length of the stack can be either even or odd, depending on whether // or not we have a name for the root value. The difference between the // index of the root value and the index of the final value is always // even, though, which allows us to return the root value in constant time // (i.e. without iterating backwards through the stack). FPp.getRootValue = function getRootValue() { var s = this.stack; if (s.length % 2 === 0) { return s[1]; } return s[0]; }; // Temporarily push properties named by string arguments given after the // callback function onto this.stack, then call the callback with a // reference to this (modified) FastPath object. Note that the stack will // be restored to its original state after the callback is finished, so it // is probably a mistake to retain a reference to the path. FPp.call = function call(callback/*, name1, name2, ... */) { var s = this.stack; var origLen = s.length; var value = s[origLen - 1]; var argc = arguments.length; for (var i = 1; i < argc; ++i) { var name = arguments[i]; value = value[name]; s.push(name, value); } var result = callback(this); s.length = origLen; return result; }; // Similar to FastPath.prototype.call, except that the value obtained by // accessing this.getValue()[name1][name2]... should be array-like. The // callback will be called with a reference to this path object for each // element of the array. FPp.each = function each(callback/*, name1, name2, ... */) { var s = this.stack; var origLen = s.length; var value = s[origLen - 1]; var argc = arguments.length; for (var i = 1; i < argc; ++i) { var name = arguments[i]; value = value[name]; s.push(name, value); } for (var i = 0; i < value.length; ++i) { if (i in value) { s.push(i, value[i]); // If the callback needs to know the value of i, call // path.getName(), assuming path is the parameter name. callback(this); s.length -= 2; } } s.length = origLen; }; // Similar to FastPath.prototype.each, except that the results of the // callback function invocations are stored in an array and returned at // the end of the iteration. FPp.map = function map(callback/*, name1, name2, ... */) { var s = this.stack; var origLen = s.length; var value = s[origLen - 1]; var argc = arguments.length; for (var i = 1; i < argc; ++i) { var name = arguments[i]; value = value[name]; s.push(name, value); } var result = new Array(value.length); for (var i = 0; i < value.length; ++i) { if (i in value) { s.push(i, value[i]); result[i] = callback(this, i); s.length -= 2; } } s.length = origLen; return result; }; // Inspired by require("ast-types").NodePath.prototype.needsParens, but // more efficient because we're iterating backwards through a stack. FPp.needsParens = function(assumeExpressionContext) { var parent = this.getParentNode(); if (!parent) { return false; } var name = this.getName(); var node = this.getNode(); // If the value of this path is some child of a Node and not a Node // itself, then it doesn't need parentheses. Only Node objects (in // fact, only Expression nodes) need parentheses. if (this.getValue() !== node) { return false; } // Only expressions need parentheses. if (!n.Expression.check(node)) { return false; } // Identifiers never need parentheses. if (node.type === "Identifier") { return false; } if (parent.type === "ParenthesizedExpression") { return false; } switch (node.type) { case "UnaryExpression": case "SpreadElement": case "SpreadProperty": return parent.type === "MemberExpression" && name === "object" && parent.object === node; case "BinaryExpression": case "LogicalExpression": switch (parent.type) { case "CallExpression": return name === "callee" && parent.callee === node; case "UnaryExpression": case "SpreadElement": case "SpreadProperty": return true; case "MemberExpression": return name === "object" && parent.object === node; case "BinaryExpression": case "LogicalExpression": var po = parent.operator; var pp = PRECEDENCE[po]; var no = node.operator; var np = PRECEDENCE[no]; if (pp > np) { return true; } if (pp === np && name === "right") { assert.strictEqual(parent.right, node); return true; } default: return false; } case "SequenceExpression": switch (parent.type) { case "ForStatement": // Although parentheses wouldn't hurt around sequence // expressions in the head of for loops, traditional style // dictates that e.g. i++, j++ should not be wrapped with // parentheses. return false; case "ExpressionStatement": return name !== "expression"; default: // Otherwise err on the side of overparenthesization, adding // explicit exceptions above if this proves overzealous. return true; } case "YieldExpression": switch (parent.type) { case "BinaryExpression": case "LogicalExpression": case "UnaryExpression": case "SpreadElement": case "SpreadProperty": case "CallExpression": case "MemberExpression": case "NewExpression": case "ConditionalExpression": case "YieldExpression": return true; default: return false; } case "Literal": return parent.type === "MemberExpression" && isNumber.check(node.value) && name === "object" && parent.object === node; case "AssignmentExpression": case "ConditionalExpression": switch (parent.type) { case "UnaryExpression": case "SpreadElement": case "SpreadProperty": case "BinaryExpression": case "LogicalExpression": return true; case "CallExpression": return name === "callee" && parent.callee === node; case "ConditionalExpression": return name === "test" && parent.test === node; case "MemberExpression": return name === "object" && parent.object === node; default: return false; } case "ArrowFunctionExpression": if(parent.type === 'CallExpression' && name === 'callee') { return true; }; return isBinary(parent); case "ObjectExpression": if (parent.type === "ArrowFunctionExpression" && name === "body") { return true; } default: if (parent.type === "NewExpression" && name === "callee" && parent.callee === node) { return containsCallExpression(node); } } if (assumeExpressionContext !== true && !this.canBeFirstInStatement() && this.firstInStatement()) return true; return false; }; function isBinary(node) { return n.BinaryExpression.check(node) || n.LogicalExpression.check(node); } function isUnaryLike(node) { return n.UnaryExpression.check(node) // I considered making SpreadElement and SpreadProperty subtypes // of UnaryExpression, but they're not really Expression nodes. || (n.SpreadElement && n.SpreadElement.check(node)) || (n.SpreadProperty && n.SpreadProperty.check(node)); } var PRECEDENCE = {}; [["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"] ].forEach(function(tier, i) { tier.forEach(function(op) { PRECEDENCE[op] = i; }); }); function containsCallExpression(node) { if (n.CallExpression.check(node)) { return true; } if (isArray.check(node)) { return node.some(containsCallExpression); } if (n.Node.check(node)) { return types.someField(node, function(name, child) { return containsCallExpression(child); }); } return false; } FPp.canBeFirstInStatement = function() { var node = this.getNode(); return !n.FunctionExpression.check(node) && !n.ObjectExpression.check(node); }; FPp.firstInStatement = function() { var s = this.stack; var parentName, parent; var childName, child; for (var i = s.length - 1; i >= 0; i -= 2) { if (n.Node.check(s[i])) { childName = parentName; child = parent; parentName = s[i - 1]; parent = s[i]; } if (!parent || !child) { continue; } if (n.BlockStatement.check(parent) && parentName === "body" && childName === 0) { assert.strictEqual(parent.body[0], child); return true; } if (n.ExpressionStatement.check(parent) && childName === "expression") { assert.strictEqual(parent.expression, child); return true; } if (n.SequenceExpression.check(parent) && parentName === "expressions" && childName === 0) { assert.strictEqual(parent.expressions[0], child); continue; } if (n.CallExpression.check(parent) && childName === "callee") { assert.strictEqual(parent.callee, child); continue; } if (n.MemberExpression.check(parent) && childName === "object") { assert.strictEqual(parent.object, child); continue; } if (n.ConditionalExpression.check(parent) && childName === "test") { assert.strictEqual(parent.test, child); continue; } if (isBinary(parent) && childName === "left") { assert.strictEqual(parent.left, child); continue; } if (n.UnaryExpression.check(parent) && !parent.prefix && childName === "argument") { assert.strictEqual(parent.argument, child); continue; } return false; } return true; }; ```
/content/code_sandbox/node_modules/recast/lib/fast-path.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,935
```javascript var assert = require("assert"); var types = require("./types"); var getFieldValue = types.getFieldValue; var n = types.namedTypes; var sourceMap = require("source-map"); var SourceMapConsumer = sourceMap.SourceMapConsumer; var SourceMapGenerator = sourceMap.SourceMapGenerator; var hasOwn = Object.prototype.hasOwnProperty; var util = exports; function getUnionOfKeys() { var result = {}; var argc = arguments.length; for (var i = 0; i < argc; ++i) { var keys = Object.keys(arguments[i]); var keyCount = keys.length; for (var j = 0; j < keyCount; ++j) { result[keys[j]] = true; } } return result; } util.getUnionOfKeys = getUnionOfKeys; function comparePos(pos1, pos2) { return (pos1.line - pos2.line) || (pos1.column - pos2.column); } util.comparePos = comparePos; function copyPos(pos) { return { line: pos.line, column: pos.column }; } util.copyPos = copyPos; util.composeSourceMaps = function(formerMap, latterMap) { if (formerMap) { if (!latterMap) { return formerMap; } } else { return latterMap || null; } var smcFormer = new SourceMapConsumer(formerMap); var smcLatter = new SourceMapConsumer(latterMap); var smg = new SourceMapGenerator({ file: latterMap.file, sourceRoot: latterMap.sourceRoot }); var sourcesToContents = {}; smcLatter.eachMapping(function(mapping) { var origPos = smcFormer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); var sourceName = origPos.source; if (sourceName === null) { return; } smg.addMapping({ source: sourceName, original: copyPos(origPos), generated: { line: mapping.generatedLine, column: mapping.generatedColumn }, name: mapping.name }); var sourceContent = smcFormer.sourceContentFor(sourceName); if (sourceContent && !hasOwn.call(sourcesToContents, sourceName)) { sourcesToContents[sourceName] = sourceContent; smg.setSourceContent(sourceName, sourceContent); } }); return smg.toJSON(); }; util.getTrueLoc = function(node, lines) { // It's possible that node is newly-created (not parsed by Esprima), // in which case it probably won't have a .loc property (or an // .original property for that matter). That's fine; we'll just // pretty-print it as usual. if (!node.loc) { return null; } var result = { start: node.loc.start, end: node.loc.end }; function include(node) { expandLoc(result, node.loc); } // If the node has any comments, their locations might contribute to // the true start/end positions of the node. if (node.comments) { node.comments.forEach(include); } // If the node is an export declaration and its .declaration has any // decorators, their locations might contribute to the true start/end // positions of the export declaration node. if (util.isExportDeclaration(node) && node.declaration.decorators) { node.declaration.decorators.forEach(include); } if (comparePos(result.start, result.end) < 0) { // Trim leading whitespace. result.start = copyPos(result.start); lines.skipSpaces(result.start, false, true); if (comparePos(result.start, result.end) < 0) { // Trim trailing whitespace, if the end location is not already the // same as the start location. result.end = copyPos(result.end); lines.skipSpaces(result.end, true, true); } } return result; }; function expandLoc(parentLoc, childLoc) { if (parentLoc && childLoc) { if (comparePos(childLoc.start, parentLoc.start) < 0) { parentLoc.start = childLoc.start; } if (comparePos(parentLoc.end, childLoc.end) < 0) { parentLoc.end = childLoc.end; } } } util.fixFaultyLocations = function(node, lines) { var loc = node.loc; if (loc) { if (loc.start.line < 1) { loc.start.line = 1; } if (loc.end.line < 1) { loc.end.line = 1; } } if (node.type === "TemplateLiteral") { fixTemplateLiteral(node, lines); } else if (loc && node.decorators) { // Expand the .loc of the node responsible for printing the decorators // (here, the decorated node) so that it includes node.decorators. node.decorators.forEach(function (decorator) { expandLoc(loc, decorator.loc); }); } else if (node.declaration && util.isExportDeclaration(node)) { // Nullify .loc information for the child declaration so that we never // try to reprint it without also reprinting the export declaration. node.declaration.loc = null; // Expand the .loc of the node responsible for printing the decorators // (here, the export declaration) so that it includes node.decorators. var decorators = node.declaration.decorators; if (decorators) { decorators.forEach(function (decorator) { expandLoc(loc, decorator.loc); }); } } else if ((n.MethodDefinition && n.MethodDefinition.check(node)) || (n.Property.check(node) && (node.method || node.shorthand))) { // If the node is a MethodDefinition or a .method or .shorthand // Property, then the location information stored in // node.value.loc is very likely untrustworthy (just the {body} // part of a method, or nothing in the case of shorthand // properties), so we null out that information to prevent // accidental reuse of bogus source code during reprinting. node.value.loc = null; if (n.FunctionExpression.check(node.value)) { // FunctionExpression method values should be anonymous, // because their .id fields are ignored anyway. node.value.id = null; } } }; function fixTemplateLiteral(node, lines) { assert.strictEqual(node.type, "TemplateLiteral"); if (node.quasis.length === 0) { // If there are no quasi elements, then there is nothing to fix. return; } // First we need to exclude the opening ` from the .loc of the first // quasi element, in case the parser accidentally decided to include it. var afterLeftBackTickPos = copyPos(node.loc.start); assert.strictEqual(lines.charAt(afterLeftBackTickPos), "`"); assert.ok(lines.nextPos(afterLeftBackTickPos)); var firstQuasi = node.quasis[0]; if (comparePos(firstQuasi.loc.start, afterLeftBackTickPos) < 0) { firstQuasi.loc.start = afterLeftBackTickPos; } // Next we need to exclude the closing ` from the .loc of the last quasi // element, in case the parser accidentally decided to include it. var rightBackTickPos = copyPos(node.loc.end); assert.ok(lines.prevPos(rightBackTickPos)); assert.strictEqual(lines.charAt(rightBackTickPos), "`"); var lastQuasi = node.quasis[node.quasis.length - 1]; if (comparePos(rightBackTickPos, lastQuasi.loc.end) < 0) { lastQuasi.loc.end = rightBackTickPos; } // Now we need to exclude ${ and } characters from the .loc's of all // quasi elements, since some parsers accidentally include them. node.expressions.forEach(function (expr, i) { // Rewind from expr.loc.start over any whitespace and the ${ that // precedes the expression. The position of the $ should be the same // as the .loc.end of the preceding quasi element, but some parsers // accidentally include the ${ in the .loc of the quasi element. var dollarCurlyPos = lines.skipSpaces(expr.loc.start, true, false); if (lines.prevPos(dollarCurlyPos) && lines.charAt(dollarCurlyPos) === "{" && lines.prevPos(dollarCurlyPos) && lines.charAt(dollarCurlyPos) === "$") { var quasiBefore = node.quasis[i]; if (comparePos(dollarCurlyPos, quasiBefore.loc.end) < 0) { quasiBefore.loc.end = dollarCurlyPos; } } // Likewise, some parsers accidentally include the } that follows // the expression in the .loc of the following quasi element. var rightCurlyPos = lines.skipSpaces(expr.loc.end, false, false); if (lines.charAt(rightCurlyPos) === "}") { assert.ok(lines.nextPos(rightCurlyPos)); // Now rightCurlyPos is technically the position just after the }. var quasiAfter = node.quasis[i + 1]; if (comparePos(quasiAfter.loc.start, rightCurlyPos) < 0) { quasiAfter.loc.start = rightCurlyPos; } } }); } util.isExportDeclaration = function (node) { if (node) switch (node.type) { case "ExportDeclaration": case "ExportDefaultSpecifier": case "DeclareExportDeclaration": case "ExportNamedDeclaration": case "ExportAllDeclaration": return true; } return false; }; util.getParentExportDeclaration = function (path) { var parentNode = path.getParentNode(); if (path.getName() === "declaration" && util.isExportDeclaration(parentNode)) { return parentNode; } return null; }; ```
/content/code_sandbox/node_modules/recast/lib/util.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,162
```javascript var assert = require("assert"); var sourceMap = require("source-map"); var printComments = require("./comments").printComments; var linesModule = require("./lines"); var fromString = linesModule.fromString; var concat = linesModule.concat; var normalizeOptions = require("./options").normalize; var getReprinter = require("./patcher").getReprinter; var types = require("./types"); var namedTypes = types.namedTypes; var isString = types.builtInTypes.string; var isObject = types.builtInTypes.object; var FastPath = require("./fast-path"); var util = require("./util"); function PrintResult(code, sourceMap) { assert.ok(this instanceof PrintResult); isString.assert(code); this.code = code; if (sourceMap) { isObject.assert(sourceMap); this.map = sourceMap; } } var PRp = PrintResult.prototype; var warnedAboutToString = false; PRp.toString = function() { if (!warnedAboutToString) { console.warn( "Deprecation warning: recast.print now returns an object with " + "a .code property. You appear to be treating the object as a " + "string, which might still work but is strongly discouraged." ); warnedAboutToString = true; } return this.code; }; var emptyPrintResult = new PrintResult(""); function Printer(originalOptions) { assert.ok(this instanceof Printer); var explicitTabWidth = originalOptions && originalOptions.tabWidth; var options = normalizeOptions(originalOptions); assert.notStrictEqual(options, originalOptions); // It's common for client code to pass the same options into both // recast.parse and recast.print, but the Printer doesn't need (and // can be confused by) options.sourceFileName, so we null it out. options.sourceFileName = null; function printWithComments(path) { assert.ok(path instanceof FastPath); return printComments(path, print); } function print(path, includeComments) { if (includeComments) return printWithComments(path); assert.ok(path instanceof FastPath); if (!explicitTabWidth) { var oldTabWidth = options.tabWidth; var loc = path.getNode().loc; if (loc && loc.lines && loc.lines.guessTabWidth) { options.tabWidth = loc.lines.guessTabWidth(); var lines = maybeReprint(path); options.tabWidth = oldTabWidth; return lines; } } return maybeReprint(path); } function maybeReprint(path) { var reprinter = getReprinter(path); if (reprinter) { // Since the print function that we pass to the reprinter will // be used to print "new" nodes, it's tempting to think we // should pass printRootGenerically instead of print, to avoid // calling maybeReprint again, but that would be a mistake // because the new nodes might not be entirely new, but merely // moved from elsewhere in the AST. The print function is the // right choice because it gives us the opportunity to reprint // such nodes using their original source. return maybeAddParens(path, reprinter(print)); } return printRootGenerically(path); } // Print the root node generically, but then resume reprinting its // children non-generically. function printRootGenerically(path, includeComments) { return includeComments ? printComments(path, printRootGenerically) : genericPrint(path, options, printWithComments); } // Print the entire AST generically. function printGenerically(path) { return genericPrint(path, options, printGenerically); } this.print = function(ast) { if (!ast) { return emptyPrintResult; } var lines = print(FastPath.from(ast), true); return new PrintResult( lines.toString(options), util.composeSourceMaps( options.inputSourceMap, lines.getSourceMap( options.sourceMapName, options.sourceRoot ) ) ); }; this.printGenerically = function(ast) { if (!ast) { return emptyPrintResult; } var path = FastPath.from(ast); var oldReuseWhitespace = options.reuseWhitespace; // Do not reuse whitespace (or anything else, for that matter) // when printing generically. options.reuseWhitespace = false; // TODO Allow printing of comments? var pr = new PrintResult(printGenerically(path).toString(options)); options.reuseWhitespace = oldReuseWhitespace; return pr; }; } exports.Printer = Printer; function maybeAddParens(path, lines) { return path.needsParens() ? concat(["(", lines, ")"]) : lines; } function genericPrint(path, options, printPath) { assert.ok(path instanceof FastPath); var node = path.getValue(); var parts = []; var needsParens = false; var linesWithoutParens = genericPrintNoParens(path, options, printPath); if (! node || linesWithoutParens.isEmpty()) { return linesWithoutParens; } if (node.decorators && node.decorators.length > 0 && // If the parent node is an export declaration, it will be // responsible for printing node.decorators. ! util.getParentExportDeclaration(path)) { path.each(function(decoratorPath) { parts.push(printPath(decoratorPath), "\n"); }, "decorators"); } else if (util.isExportDeclaration(node) && node.declaration && node.declaration.decorators) { // Export declarations are responsible for printing any decorators // that logically apply to node.declaration. path.each(function(decoratorPath) { parts.push(printPath(decoratorPath), "\n"); }, "declaration", "decorators"); } else { // Nodes with decorators can't have parentheses, so we can avoid // computing path.needsParens() except in this case. needsParens = path.needsParens(); } if (needsParens) { parts.unshift("("); } parts.push(linesWithoutParens); if (needsParens) { parts.push(")"); } return concat(parts); } function genericPrintNoParens(path, options, print) { var n = path.getValue(); if (!n) { return fromString(""); } if (typeof n === "string") { return fromString(n, options); } namedTypes.Printable.assert(n); switch (n.type) { case "File": return path.call(print, "program"); case "Program": return path.call(function(bodyPath) { return printStatementSequence(bodyPath, options, print); }, "body"); case "Noop": // Babel extension. case "EmptyStatement": return fromString(""); case "ExpressionStatement": return concat([path.call(print, "expression"), ";"]); case "ParenthesizedExpression": // Babel extension. return concat(["(", path.call(print, "expression"), ")"]); case "BinaryExpression": case "LogicalExpression": case "AssignmentExpression": return fromString(" ").join([ path.call(print, "left"), n.operator, path.call(print, "right") ]); case "AssignmentPattern": return concat([ path.call(print, "left"), "=", path.call(print, "right") ]); case "MemberExpression": var parts = [path.call(print, "object")]; var property = path.call(print, "property"); if (n.computed) { parts.push("[", property, "]"); } else { parts.push(".", property); } return concat(parts); case "MetaProperty": return concat([ path.call(print, "meta"), ".", path.call(print, "property") ]); case "BindExpression": var parts = []; if (n.object) { parts.push(path.call(print, "object")); } parts.push("::", path.call(print, "callee")); return concat(parts); case "Path": return fromString(".").join(n.body); case "Identifier": return concat([ fromString(n.name, options), path.call(print, "typeAnnotation") ]); case "SpreadElement": case "SpreadElementPattern": case "SpreadProperty": case "SpreadPropertyPattern": case "RestElement": return concat(["...", path.call(print, "argument")]); case "FunctionDeclaration": case "FunctionExpression": var parts = []; if (n.async) parts.push("async "); parts.push("function"); if (n.generator) parts.push("*"); if (n.id) { parts.push( " ", path.call(print, "id"), path.call(print, "typeParameters") ); } parts.push( "(", printFunctionParams(path, options, print), ")", path.call(print, "returnType"), " ", path.call(print, "body") ); return concat(parts); case "ArrowFunctionExpression": var parts = []; if (n.async) parts.push("async "); if ( n.params.length === 1 && !n.rest && n.params[0].type === 'Identifier' ) { parts.push(path.call(print, "params", 0)); } else { parts.push( "(", printFunctionParams(path, options, print), ")" ); } parts.push(" => ", path.call(print, "body")); return concat(parts); case "MethodDefinition": var parts = []; if (n.static) { parts.push("static "); } parts.push(printMethod(path, options, print)); return concat(parts); case "YieldExpression": var parts = ["yield"]; if (n.delegate) parts.push("*"); if (n.argument) parts.push(" ", path.call(print, "argument")); return concat(parts); case "AwaitExpression": var parts = ["await"]; if (n.all) parts.push("*"); if (n.argument) parts.push(" ", path.call(print, "argument")); return concat(parts); case "ModuleDeclaration": var parts = ["module", path.call(print, "id")]; if (n.source) { assert.ok(!n.body); parts.push("from", path.call(print, "source")); } else { parts.push(path.call(print, "body")); } return fromString(" ").join(parts); case "ImportSpecifier": var parts = []; if (n.imported) { parts.push(path.call(print, "imported")); if (n.local && n.local.name !== n.imported.name) { parts.push(" as ", path.call(print, "local")); } } else if (n.id) { parts.push(path.call(print, "id")); if (n.name) { parts.push(" as ", path.call(print, "name")); } } return concat(parts); case "ExportSpecifier": var parts = []; if (n.local) { parts.push(path.call(print, "local")); if (n.exported && n.exported.name !== n.local.name) { parts.push(" as ", path.call(print, "exported")); } } else if (n.id) { parts.push(path.call(print, "id")); if (n.name) { parts.push(" as ", path.call(print, "name")); } } return concat(parts); case "ExportBatchSpecifier": return fromString("*"); case "ImportNamespaceSpecifier": var parts = ["* as "]; if (n.local) { parts.push(path.call(print, "local")); } else if (n.id) { parts.push(path.call(print, "id")); } return concat(parts); case "ImportDefaultSpecifier": if (n.local) { return path.call(print, "local"); } return path.call(print, "id"); case "ExportDeclaration": case "ExportDefaultDeclaration": case "ExportNamedDeclaration": return printExportDeclaration(path, options, print); case "ExportAllDeclaration": var parts = ["export *"]; if (n.exported) { parts.push(" as ", path.call(print, "exported")); } parts.push( " from ", path.call(print, "source") ); return concat(parts); case "ExportNamespaceSpecifier": return concat(["* as ", path.call(print, "exported")]); case "ExportDefaultSpecifier": return path.call(print, "exported"); case "ImportDeclaration": var parts = ["import "]; if (n.importKind && n.importKind !== "value") { parts.push(n.importKind + " "); } if (n.specifiers && n.specifiers.length > 0) { var foundImportSpecifier = false; path.each(function(specifierPath) { var i = specifierPath.getName(); if (i > 0) { parts.push(", "); } var value = specifierPath.getValue(); if (namedTypes.ImportDefaultSpecifier.check(value) || namedTypes.ImportNamespaceSpecifier.check(value)) { assert.strictEqual(foundImportSpecifier, false); } else { namedTypes.ImportSpecifier.assert(value); if (!foundImportSpecifier) { foundImportSpecifier = true; parts.push("{"); } } parts.push(print(specifierPath)); }, "specifiers"); if (foundImportSpecifier) { parts.push("}"); } parts.push(" from "); } parts.push(path.call(print, "source"), ";"); return concat(parts); case "BlockStatement": var naked = path.call(function(bodyPath) { return printStatementSequence(bodyPath, options, print); }, "body"); if (naked.isEmpty()) { return fromString("{}"); } return concat([ "{\n", naked.indent(options.tabWidth), "\n}" ]); case "ReturnStatement": var parts = ["return"]; if (n.argument) { var argLines = path.call(print, "argument"); if (argLines.length > 1 && (namedTypes.XJSElement && namedTypes.XJSElement.check(n.argument) || namedTypes.JSXElement && namedTypes.JSXElement.check(n.argument))) { parts.push( " (\n", argLines.indent(options.tabWidth), "\n)" ); } else { parts.push(" ", argLines); } } parts.push(";"); return concat(parts); case "CallExpression": return concat([ path.call(print, "callee"), printArgumentsList(path, options, print) ]); case "ObjectExpression": case "ObjectPattern": case "ObjectTypeAnnotation": var allowBreak = false; var isTypeAnnotation = n.type === "ObjectTypeAnnotation"; var separator = isTypeAnnotation ? ';' : ','; var fields = []; if (isTypeAnnotation) { fields.push("indexers", "callProperties"); } fields.push("properties"); var len = 0; fields.forEach(function(field) { len += n[field].length; }); var oneLine = (isTypeAnnotation && len === 1) || len === 0; var parts = [oneLine ? "{" : "{\n"]; var i = 0; fields.forEach(function(field) { path.each(function(childPath) { var lines = print(childPath); if (!oneLine) { lines = lines.indent(options.tabWidth); } var multiLine = !isTypeAnnotation && lines.length > 1; if (multiLine && allowBreak) { // Similar to the logic for BlockStatement. parts.push("\n"); } parts.push(lines); if (i < len - 1) { // Add an extra line break if the previous object property // had a multi-line value. parts.push(separator + (multiLine ? "\n\n" : "\n")); allowBreak = !multiLine; } else if (len !== 1 && isTypeAnnotation) { parts.push(separator); } else if (options.trailingComma) { parts.push(separator); } i++; }, field); }); parts.push(oneLine ? "}" : "\n}"); return concat(parts); case "PropertyPattern": return concat([ path.call(print, "key"), ": ", path.call(print, "pattern") ]); case "Property": // Non-standard AST node type. if (n.method || n.kind === "get" || n.kind === "set") { return printMethod(path, options, print); } var parts = []; var key = path.call(print, "key"); if (n.computed) { parts.push("[", key, "]"); } else { parts.push(key); } if (! n.shorthand) { parts.push(": ", path.call(print, "value")); } return concat(parts); case "Decorator": return concat(["@", path.call(print, "expression")]); case "ArrayExpression": case "ArrayPattern": var elems = n.elements, len = elems.length; var printed = path.map(print, "elements"); var joined = fromString(", ").join(printed); var oneLine = joined.getLineLength(1) <= options.wrapColumn; var parts = [oneLine ? "[" : "[\n"]; path.each(function(elemPath) { var i = elemPath.getName(); var elem = elemPath.getValue(); if (!elem) { // If the array expression ends with a hole, that hole // will be ignored by the interpreter, but if it ends with // two (or more) holes, we need to write out two (or more) // commas so that the resulting code is interpreted with // both (all) of the holes. parts.push(","); } else { var lines = printed[i]; if (oneLine) { if (i > 0) parts.push(" "); } else { lines = lines.indent(options.tabWidth); } parts.push(lines); if (i < len - 1 || (!oneLine && options.trailingComma)) parts.push(","); if (!oneLine) parts.push("\n"); } }, "elements"); parts.push("]"); return concat(parts); case "SequenceExpression": return fromString(", ").join(path.map(print, "expressions")); case "ThisExpression": return fromString("this"); case "Super": return fromString("super"); case "Literal": if (typeof n.value !== "string") return fromString(n.value, options); return fromString(nodeStr(n.value, options), options); case "ModuleSpecifier": if (n.local) { throw new Error( "The ESTree ModuleSpecifier type should be abstract" ); } // The Esprima ModuleSpecifier type is just a string-valued // Literal identifying the imported-from module. return fromString(nodeStr(n.value, options), options); case "UnaryExpression": var parts = [n.operator]; if (/[a-z]$/.test(n.operator)) parts.push(" "); parts.push(path.call(print, "argument")); return concat(parts); case "UpdateExpression": var parts = [path.call(print, "argument"), n.operator]; if (n.prefix) parts.reverse(); return concat(parts); case "ConditionalExpression": return concat([ "(", path.call(print, "test"), " ? ", path.call(print, "consequent"), " : ", path.call(print, "alternate"), ")" ]); case "NewExpression": var parts = ["new ", path.call(print, "callee")]; var args = n.arguments; if (args) { parts.push(printArgumentsList(path, options, print)); } return concat(parts); case "VariableDeclaration": var parts = [n.kind, " "]; var maxLen = 0; var printed = path.map(function(childPath) { var lines = print(childPath); maxLen = Math.max(lines.length, maxLen); return lines; }, "declarations"); if (maxLen === 1) { parts.push(fromString(", ").join(printed)); } else if (printed.length > 1 ) { parts.push( fromString(",\n").join(printed) .indentTail(n.kind.length + 1) ); } else { parts.push(printed[0]); } // We generally want to terminate all variable declarations with a // semicolon, except when they are children of for loops. var parentNode = path.getParentNode(); if (!namedTypes.ForStatement.check(parentNode) && !namedTypes.ForInStatement.check(parentNode) && !(namedTypes.ForOfStatement && namedTypes.ForOfStatement.check(parentNode))) { parts.push(";"); } return concat(parts); case "VariableDeclarator": return n.init ? fromString(" = ").join([ path.call(print, "id"), path.call(print, "init") ]) : path.call(print, "id"); case "WithStatement": return concat([ "with (", path.call(print, "object"), ") ", path.call(print, "body") ]); case "IfStatement": var con = adjustClause(path.call(print, "consequent"), options), parts = ["if (", path.call(print, "test"), ")", con]; if (n.alternate) parts.push( endsWithBrace(con) ? " else" : "\nelse", adjustClause(path.call(print, "alternate"), options)); return concat(parts); case "ForStatement": // TODO Get the for (;;) case right. var init = path.call(print, "init"), sep = init.length > 1 ? ";\n" : "; ", forParen = "for (", indented = fromString(sep).join([ init, path.call(print, "test"), path.call(print, "update") ]).indentTail(forParen.length), head = concat([forParen, indented, ")"]), clause = adjustClause(path.call(print, "body"), options), parts = [head]; if (head.length > 1) { parts.push("\n"); clause = clause.trimLeft(); } parts.push(clause); return concat(parts); case "WhileStatement": return concat([ "while (", path.call(print, "test"), ")", adjustClause(path.call(print, "body"), options) ]); case "ForInStatement": // Note: esprima can't actually parse "for each (". return concat([ n.each ? "for each (" : "for (", path.call(print, "left"), " in ", path.call(print, "right"), ")", adjustClause(path.call(print, "body"), options) ]); case "ForOfStatement": return concat([ "for (", path.call(print, "left"), " of ", path.call(print, "right"), ")", adjustClause(path.call(print, "body"), options) ]); case "DoWhileStatement": var doBody = concat([ "do", adjustClause(path.call(print, "body"), options) ]), parts = [doBody]; if (endsWithBrace(doBody)) parts.push(" while"); else parts.push("\nwhile"); parts.push(" (", path.call(print, "test"), ");"); return concat(parts); case "DoExpression": var statements = path.call(function(bodyPath) { return printStatementSequence(bodyPath, options, print); }, "body"); return concat([ "do {\n", statements.indent(options.tabWidth), "\n}" ]); case "BreakStatement": var parts = ["break"]; if (n.label) parts.push(" ", path.call(print, "label")); parts.push(";"); return concat(parts); case "ContinueStatement": var parts = ["continue"]; if (n.label) parts.push(" ", path.call(print, "label")); parts.push(";"); return concat(parts); case "LabeledStatement": return concat([ path.call(print, "label"), ":\n", path.call(print, "body") ]); case "TryStatement": var parts = [ "try ", path.call(print, "block") ]; if (n.handler) { parts.push(" ", path.call(print, "handler")); } else if (n.handlers) { path.each(function(handlerPath) { parts.push(" ", print(handlerPath)); }, "handlers"); } if (n.finalizer) { parts.push(" finally ", path.call(print, "finalizer")); } return concat(parts); case "CatchClause": var parts = ["catch (", path.call(print, "param")]; if (n.guard) // Note: esprima does not recognize conditional catch clauses. parts.push(" if ", path.call(print, "guard")); parts.push(") ", path.call(print, "body")); return concat(parts); case "ThrowStatement": return concat(["throw ", path.call(print, "argument"), ";"]); case "SwitchStatement": return concat([ "switch (", path.call(print, "discriminant"), ") {\n", fromString("\n").join(path.map(print, "cases")), "\n}" ]); // Note: ignoring n.lexical because it has no printing consequences. case "SwitchCase": var parts = []; if (n.test) parts.push("case ", path.call(print, "test"), ":"); else parts.push("default:"); if (n.consequent.length > 0) { parts.push("\n", path.call(function(consequentPath) { return printStatementSequence(consequentPath, options, print); }, "consequent").indent(options.tabWidth)); } return concat(parts); case "DebuggerStatement": return fromString("debugger;"); // JSX extensions below. case "XJSAttribute": case "JSXAttribute": var parts = [path.call(print, "name")]; if (n.value) parts.push("=", path.call(print, "value")); return concat(parts); case "XJSIdentifier": case "JSXIdentifier": return fromString(n.name, options); case "XJSNamespacedName": case "JSXNamespacedName": return fromString(":").join([ path.call(print, "namespace"), path.call(print, "name") ]); case "XJSMemberExpression": case "JSXMemberExpression": return fromString(".").join([ path.call(print, "object"), path.call(print, "property") ]); case "XJSSpreadAttribute": case "JSXSpreadAttribute": return concat(["{...", path.call(print, "argument"), "}"]); case "XJSExpressionContainer": case "JSXExpressionContainer": return concat(["{", path.call(print, "expression"), "}"]); case "XJSElement": case "JSXElement": var openingLines = path.call(print, "openingElement"); if (n.openingElement.selfClosing) { assert.ok(!n.closingElement); return openingLines; } var childLines = concat( path.map(function(childPath) { var child = childPath.getValue(); if (namedTypes.Literal.check(child) && typeof child.value === "string") { if (/\S/.test(child.value)) { return child.value.replace(/^\s+|\s+$/g, ""); } else if (/\n/.test(child.value)) { return "\n"; } } return print(childPath); }, "children") ).indentTail(options.tabWidth); var closingLines = path.call(print, "closingElement"); return concat([ openingLines, childLines, closingLines ]); case "XJSOpeningElement": case "JSXOpeningElement": var parts = ["<", path.call(print, "name")]; var attrParts = []; path.each(function(attrPath) { attrParts.push(" ", print(attrPath)); }, "attributes"); var attrLines = concat(attrParts); var needLineWrap = ( attrLines.length > 1 || attrLines.getLineLength(1) > options.wrapColumn ); if (needLineWrap) { attrParts.forEach(function(part, i) { if (part === " ") { assert.strictEqual(i % 2, 0); attrParts[i] = "\n"; } }); attrLines = concat(attrParts).indentTail(options.tabWidth); } parts.push(attrLines, n.selfClosing ? " />" : ">"); return concat(parts); case "XJSClosingElement": case "JSXClosingElement": return concat(["</", path.call(print, "name"), ">"]); case "XJSText": case "JSXText": return fromString(n.value, options); case "XJSEmptyExpression": case "JSXEmptyExpression": return fromString(""); case "TypeAnnotatedIdentifier": return concat([ path.call(print, "annotation"), " ", path.call(print, "identifier") ]); case "ClassBody": if (n.body.length === 0) { return fromString("{}"); } return concat([ "{\n", path.call(function(bodyPath) { return printStatementSequence(bodyPath, options, print); }, "body").indent(options.tabWidth), "\n}" ]); case "ClassPropertyDefinition": var parts = ["static ", path.call(print, "definition")]; if (!namedTypes.MethodDefinition.check(n.definition)) parts.push(";"); return concat(parts); case "ClassProperty": var parts = []; if (n.static) parts.push("static "); parts.push(path.call(print, "key")); if (n.typeAnnotation) parts.push(path.call(print, "typeAnnotation")); if (n.value) parts.push(" = ", path.call(print, "value")); parts.push(";"); return concat(parts); case "ClassDeclaration": case "ClassExpression": var parts = []; parts.push("class"); if (n.id) { parts.push( " ", path.call(print, "id"), path.call(print, "typeParameters") ); } if (n.superClass) { parts.push( " extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters") ); } if (n["implements"] && n['implements'].length > 0) { parts.push( " implements ", fromString(", ").join(path.map(print, "implements")) ); } parts.push(" ", path.call(print, "body")); return concat(parts); case "TemplateElement": return fromString(n.value.raw, options).lockIndentTail(); case "TemplateLiteral": var expressions = path.map(print, "expressions"); var parts = ["`"]; path.each(function(childPath) { var i = childPath.getName(); parts.push(print(childPath)); if (i < expressions.length) { parts.push("${", expressions[i], "}"); } }, "quasis"); parts.push("`"); return concat(parts).lockIndentTail(); case "TaggedTemplateExpression": return concat([ path.call(print, "tag"), path.call(print, "quasi") ]); // These types are unprintable because they serve as abstract // supertypes for other (printable) types. case "Node": case "Printable": case "SourceLocation": case "Position": case "Statement": case "Function": case "Pattern": case "Expression": case "Declaration": case "Specifier": case "NamedSpecifier": case "Comment": // Supertype of Block and Line. case "MemberTypeAnnotation": // Flow case "TupleTypeAnnotation": // Flow case "Type": // Flow throw new Error("unprintable type: " + JSON.stringify(n.type)); case "CommentBlock": // Babel block comment. case "Block": // Esprima block comment. return concat(["/*", fromString(n.value, options), "*/"]); case "CommentLine": // Babel line comment. case "Line": // Esprima line comment. return concat(["//", fromString(n.value, options)]); // Type Annotations for Facebook Flow, typically stripped out or // transformed away before printing. case "TypeAnnotation": var parts = []; if (n.typeAnnotation) { if (n.typeAnnotation.type !== "FunctionTypeAnnotation") { parts.push(": "); } parts.push(path.call(print, "typeAnnotation")); return concat(parts); } return fromString(""); case "AnyTypeAnnotation": return fromString("any", options); case "MixedTypeAnnotation": return fromString("mixed", options); case "ArrayTypeAnnotation": return concat([ path.call(print, "elementType"), "[]" ]); case "BooleanTypeAnnotation": return fromString("boolean", options); case "BooleanLiteralTypeAnnotation": assert.strictEqual(typeof n.value, "boolean"); return fromString("" + n.value, options); case "DeclareClass": return printFlowDeclaration(path, [ "class ", path.call(print, "id"), " ", path.call(print, "body"), ]); case "DeclareFunction": return printFlowDeclaration(path, [ "function ", path.call(print, "id"), ";" ]); case "DeclareModule": return printFlowDeclaration(path, [ "module ", path.call(print, "id"), " ", path.call(print, "body"), ]); case "DeclareVariable": return printFlowDeclaration(path, [ "var ", path.call(print, "id"), ";" ]); case "DeclareExportDeclaration": return concat([ "declare ", printExportDeclaration(path, options, print) ]); case "FunctionTypeAnnotation": // FunctionTypeAnnotation is ambiguous: // declare function(a: B): void; OR // var A: (a: B) => void; var parts = []; var parent = path.getParentNode(0); var isArrowFunctionTypeAnnotation = !( namedTypes.ObjectTypeCallProperty.check(parent) || namedTypes.DeclareFunction.check(path.getParentNode(2)) ); var needsColon = isArrowFunctionTypeAnnotation && !namedTypes.FunctionTypeParam.check(parent); if (needsColon) { parts.push(": "); } parts.push( "(", fromString(", ").join(path.map(print, "params")), ")" ); // The returnType is not wrapped in a TypeAnnotation, so the colon // needs to be added separately. if (n.returnType) { parts.push( isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType") ); } return concat(parts); case "FunctionTypeParam": return concat([ path.call(print, "name"), ": ", path.call(print, "typeAnnotation"), ]); case "GenericTypeAnnotation": return concat([ path.call(print, "id"), path.call(print, "typeParameters") ]); case "InterfaceDeclaration": var parts = [ fromString("interface ", options), path.call(print, "id"), path.call(print, "typeParameters"), " " ]; if (n["extends"]) { parts.push( "extends ", fromString(", ").join(path.map(print, "extends")) ); } parts.push(" ", path.call(print, "body")); return concat(parts); case "ClassImplements": case "InterfaceExtends": return concat([ path.call(print, "id"), path.call(print, "typeParameters") ]); case "IntersectionTypeAnnotation": return fromString(" & ").join(path.map(print, "types")); case "NullableTypeAnnotation": return concat([ "?", path.call(print, "typeAnnotation") ]); case "NumberTypeAnnotation": return fromString("number", options); case "ObjectTypeCallProperty": return path.call(print, "value"); case "ObjectTypeIndexer": return concat([ "[", path.call(print, "id"), ": ", path.call(print, "key"), "]: ", path.call(print, "value") ]); case "ObjectTypeProperty": return concat([ path.call(print, "key"), ": ", path.call(print, "value") ]); case "QualifiedTypeIdentifier": return concat([ path.call(print, "qualification"), ".", path.call(print, "id") ]); case "StringLiteralTypeAnnotation": return fromString(nodeStr(n.value, options), options); case "NumberLiteralTypeAnnotation": assert.strictEqual(typeof n.value, "number"); return fromString("" + n.value, options); case "StringTypeAnnotation": return fromString("string", options); case "TypeAlias": return concat([ "type ", path.call(print, "id"), " = ", path.call(print, "right"), ";" ]); case "TypeCastExpression": return concat([ "(", path.call(print, "expression"), path.call(print, "typeAnnotation"), ")" ]); case "TypeParameterDeclaration": case "TypeParameterInstantiation": return concat([ "<", fromString(", ").join(path.map(print, "params")), ">" ]); case "TypeofTypeAnnotation": return concat([ fromString("typeof ", options), path.call(print, "argument") ]); case "UnionTypeAnnotation": return fromString(" | ").join(path.map(print, "types")); case "VoidTypeAnnotation": return fromString("void", options); // Unhandled types below. If encountered, nodes of these types should // be either left alone or desugared into AST types that are fully // supported by the pretty-printer. case "ClassHeritage": // TODO case "ComprehensionBlock": // TODO case "ComprehensionExpression": // TODO case "Glob": // TODO case "GeneratorExpression": // TODO case "LetStatement": // TODO case "LetExpression": // TODO case "GraphExpression": // TODO case "GraphIndexExpression": // TODO // XML types that nobody cares about or needs to print. case "XMLDefaultDeclaration": case "XMLAnyName": case "XMLQualifiedIdentifier": case "XMLFunctionQualifiedIdentifier": case "XMLAttributeSelector": case "XMLFilterExpression": case "XML": case "XMLElement": case "XMLList": case "XMLEscape": case "XMLText": case "XMLStartTag": case "XMLEndTag": case "XMLPointTag": case "XMLName": case "XMLAttribute": case "XMLCdata": case "XMLComment": case "XMLProcessingInstruction": default: debugger; throw new Error("unknown type: " + JSON.stringify(n.type)); } return p; } function printStatementSequence(path, options, print) { var inClassBody = namedTypes.ClassBody && namedTypes.ClassBody.check(path.getParentNode()); var filtered = []; var sawComment = false; var sawStatement = false; path.each(function(stmtPath) { var i = stmtPath.getName(); var stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy // "statements," it's safer simply to skip them. if (!stmt) { return; } // Skip printing EmptyStatement nodes to avoid leaving stray // semicolons lying around. if (stmt.type === "EmptyStatement") { return; } if (namedTypes.Comment.check(stmt)) { // The pretty printer allows a dangling Comment node to act as // a Statement when the Comment can't be attached to any other // non-Comment node in the tree. sawComment = true; } else if (namedTypes.Statement.check(stmt)) { sawStatement = true; } else { // When the pretty printer encounters a string instead of an // AST node, it just prints the string. This behavior can be // useful for fine-grained formatting decisions like inserting // blank lines. isString.assert(stmt); } // We can't hang onto stmtPath outside of this function, because // it's just a reference to a mutable FastPath object, so we have // to go ahead and print it here. filtered.push({ node: stmt, printed: print(stmtPath) }); }); if (sawComment) { assert.strictEqual( sawStatement, false, "Comments may appear as statements in otherwise empty statement " + "lists, but may not coexist with non-Comment nodes." ); } var prevTrailingSpace = null; var len = filtered.length; var parts = []; filtered.forEach(function(info, i) { var printed = info.printed; var stmt = info.node; var multiLine = printed.length > 1; var notFirst = i > 0; var notLast = i < len - 1; var leadingSpace; var trailingSpace; var lines = stmt && stmt.loc && stmt.loc.lines; var trueLoc = lines && options.reuseWhitespace && util.getTrueLoc(stmt, lines); if (notFirst) { if (trueLoc) { var beforeStart = lines.skipSpaces(trueLoc.start, true); var beforeStartLine = beforeStart ? beforeStart.line : 1; var leadingGap = trueLoc.start.line - beforeStartLine; leadingSpace = Array(leadingGap + 1).join("\n"); } else { leadingSpace = multiLine ? "\n\n" : "\n"; } } else { leadingSpace = ""; } if (notLast) { if (trueLoc) { var afterEnd = lines.skipSpaces(trueLoc.end); var afterEndLine = afterEnd ? afterEnd.line : lines.length; var trailingGap = afterEndLine - trueLoc.end.line; trailingSpace = Array(trailingGap + 1).join("\n"); } else { trailingSpace = multiLine ? "\n\n" : "\n"; } } else { trailingSpace = ""; } parts.push( maxSpace(prevTrailingSpace, leadingSpace), printed ); if (notLast) { prevTrailingSpace = trailingSpace; } else if (trailingSpace) { parts.push(trailingSpace); } }); return concat(parts); } function maxSpace(s1, s2) { if (!s1 && !s2) { return fromString(""); } if (!s1) { return fromString(s2); } if (!s2) { return fromString(s1); } var spaceLines1 = fromString(s1); var spaceLines2 = fromString(s2); if (spaceLines2.length > spaceLines1.length) { return spaceLines2; } return spaceLines1; } function printMethod(path, options, print) { var node = path.getNode(); var kind = node.kind; var parts = []; namedTypes.FunctionExpression.assert(node.value); if (node.value.async) { parts.push("async "); } if (!kind || kind === "init" || kind === "method" || kind === "constructor") { if (node.value.generator) { parts.push("*"); } } else { assert.ok(kind === "get" || kind === "set"); parts.push(kind, " "); } var key = path.call(print, "key"); if (node.computed) { key = concat(["[", key, "]"]); } parts.push( key, path.call(print, "value", "typeParameters"), "(", path.call(function(valuePath) { return printFunctionParams(valuePath, options, print); }, "value"), ")", path.call(print, "value", "returnType"), " ", path.call(print, "value", "body") ); return concat(parts); } function printArgumentsList(path, options, print) { var printed = path.map(print, "arguments"); var joined = fromString(", ").join(printed); if (joined.getLineLength(1) > options.wrapColumn) { joined = fromString(",\n").join(printed); return concat([ "(\n", joined.indent(options.tabWidth), options.trailingComma ? ",\n)" : "\n)" ]); } return concat(["(", joined, ")"]); } function printFunctionParams(path, options, print) { var fun = path.getValue(); namedTypes.Function.assert(fun); var printed = path.map(print, "params"); if (fun.defaults) { path.each(function(defExprPath) { var i = defExprPath.getName(); var p = printed[i]; if (p && defExprPath.getValue()) { printed[i] = concat([p, "=", print(defExprPath)]); } }, "defaults"); } if (fun.rest) { printed.push(concat(["...", path.call(print, "rest")])); } var joined = fromString(", ").join(printed); if (joined.length > 1 || joined.getLineLength(1) > options.wrapColumn) { joined = fromString(",\n").join(printed); if (options.trailingComma && !fun.rest) { joined = concat([joined, ",\n"]); } return concat(["\n", joined.indent(options.tabWidth)]); } return joined; } function printExportDeclaration(path, options, print) { var decl = path.getValue(); var parts = ["export "]; namedTypes.Declaration.assert(decl); if (decl["default"] || decl.type === "ExportDefaultDeclaration") { parts.push("default "); } if (decl.declaration) { parts.push(path.call(print, "declaration")); } else if (decl.specifiers && decl.specifiers.length > 0) { if (decl.specifiers.length === 1 && decl.specifiers[0].type === "ExportBatchSpecifier") { parts.push("*"); } else { parts.push( "{", fromString(", ").join(path.map(print, "specifiers")), "}" ); } if (decl.source) { parts.push(" from ", path.call(print, "source")); } } var lines = concat(parts); if (lastNonSpaceCharacter(lines) !== ";") { lines = concat([lines, ";"]); } return lines; } function printFlowDeclaration(path, parts) { var parentExportDecl = util.getParentExportDeclaration(path); if (parentExportDecl) { assert.strictEqual( parentExportDecl.type, "DeclareExportDeclaration" ); } else { // If the parent node has type DeclareExportDeclaration, then it // will be responsible for printing the "declare" token. Otherwise // it needs to be printed with this non-exported declaration node. parts.unshift("declare "); } return concat(parts); } function adjustClause(clause, options) { if (clause.length > 1) return concat([" ", clause]); return concat([ "\n", maybeAddSemicolon(clause).indent(options.tabWidth) ]); } function lastNonSpaceCharacter(lines) { var pos = lines.lastPos(); do { var ch = lines.charAt(pos); if (/\S/.test(ch)) return ch; } while (lines.prevPos(pos)); } function endsWithBrace(lines) { return lastNonSpaceCharacter(lines) === "}"; } function swapQuotes(str) { return str.replace(/['"]/g, function(m) { return m === '"' ? '\'' : '"'; }); } function nodeStr(str, options) { isString.assert(str); switch (options.quote) { case "auto": var double = JSON.stringify(str); var single = swapQuotes(JSON.stringify(swapQuotes(str))); return double.length > single.length ? single : double; case "single": return swapQuotes(JSON.stringify(swapQuotes(str))); case "double": default: return JSON.stringify(str); } } function maybeAddSemicolon(lines) { var eoc = lastNonSpaceCharacter(lines); if (!eoc || "\n};".indexOf(eoc) < 0) return concat([lines, ";"]); return lines; } ```
/content/code_sandbox/node_modules/recast/lib/printer.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
10,741
```javascript var assert = require("assert"); var sourceMap = require("source-map"); var normalizeOptions = require("./options").normalize; var secretKey = require("private").makeUniqueKey(); var types = require("./types"); var isString = types.builtInTypes.string; var comparePos = require("./util").comparePos; var Mapping = require("./mapping"); // Goals: // 1. Minimize new string creation. // 2. Keep (de)identation O(lines) time. // 3. Permit negative indentations. // 4. Enforce immutability. // 5. No newline characters. function getSecret(lines) { return lines[secretKey]; } function Lines(infos, sourceFileName) { assert.ok(this instanceof Lines); assert.ok(infos.length > 0); if (sourceFileName) { isString.assert(sourceFileName); } else { sourceFileName = null; } Object.defineProperty(this, secretKey, { value: { infos: infos, mappings: [], name: sourceFileName, cachedSourceMap: null } }); if (sourceFileName) { getSecret(this).mappings.push(new Mapping(this, { start: this.firstPos(), end: this.lastPos() })); } } // Exposed for instanceof checks. The fromString function should be used // to create new Lines objects. exports.Lines = Lines; var Lp = Lines.prototype; // These properties used to be assigned to each new object in the Lines // constructor, but we can more efficiently stuff them into the secret and // let these lazy accessors compute their values on-the-fly. Object.defineProperties(Lp, { length: { get: function() { return getSecret(this).infos.length; } }, name: { get: function() { return getSecret(this).name; } } }); function copyLineInfo(info) { return { line: info.line, indent: info.indent, locked: info.locked, sliceStart: info.sliceStart, sliceEnd: info.sliceEnd }; } var fromStringCache = {}; var hasOwn = fromStringCache.hasOwnProperty; var maxCacheKeyLen = 10; function countSpaces(spaces, tabWidth) { var count = 0; var len = spaces.length; for (var i = 0; i < len; ++i) { switch (spaces.charCodeAt(i)) { case 9: // '\t' assert.strictEqual(typeof tabWidth, "number"); assert.ok(tabWidth > 0); var next = Math.ceil(count / tabWidth) * tabWidth; if (next === count) { count += tabWidth; } else { count = next; } break; case 11: // '\v' case 12: // '\f' case 13: // '\r' case 0xfeff: // zero-width non-breaking space // These characters contribute nothing to indentation. break; case 32: // ' ' default: // Treat all other whitespace like ' '. count += 1; break; } } return count; } exports.countSpaces = countSpaces; var leadingSpaceExp = /^\s*/; // As specified here: path_to_url#sec-line-terminators var lineTerminatorSeqExp = /\u000D\u000A|\u000D(?!\u000A)|\u000A|\u2028|\u2029/; /** * @param {Object} options - Options object that configures printing. */ function fromString(string, options) { if (string instanceof Lines) return string; string += ""; var tabWidth = options && options.tabWidth; var tabless = string.indexOf("\t") < 0; var locked = !! (options && options.locked); var cacheable = !options && tabless && (string.length <= maxCacheKeyLen); assert.ok(tabWidth || tabless, "No tab width specified but encountered tabs in string\n" + string); if (cacheable && hasOwn.call(fromStringCache, string)) return fromStringCache[string]; var lines = new Lines(string.split(lineTerminatorSeqExp).map(function(line) { var spaces = leadingSpaceExp.exec(line)[0]; return { line: line, indent: countSpaces(spaces, tabWidth), // Boolean indicating whether this line can be reindented. locked: locked, sliceStart: spaces.length, sliceEnd: line.length }; }), normalizeOptions(options).sourceFileName); if (cacheable) fromStringCache[string] = lines; return lines; } exports.fromString = fromString; function isOnlyWhitespace(string) { return !/\S/.test(string); } Lp.toString = function(options) { return this.sliceString(this.firstPos(), this.lastPos(), options); }; Lp.getSourceMap = function(sourceMapName, sourceRoot) { if (!sourceMapName) { // Although we could make up a name or generate an anonymous // source map, instead we assume that any consumer who does not // provide a name does not actually want a source map. return null; } var targetLines = this; function updateJSON(json) { json = json || {}; isString.assert(sourceMapName); json.file = sourceMapName; if (sourceRoot) { isString.assert(sourceRoot); json.sourceRoot = sourceRoot; } return json; } var secret = getSecret(targetLines); if (secret.cachedSourceMap) { // Since Lines objects are immutable, we can reuse any source map // that was previously generated. Nevertheless, we return a new // JSON object here to protect the cached source map from outside // modification. return updateJSON(secret.cachedSourceMap.toJSON()); } var smg = new sourceMap.SourceMapGenerator(updateJSON()); var sourcesToContents = {}; secret.mappings.forEach(function(mapping) { var sourceCursor = mapping.sourceLines.skipSpaces( mapping.sourceLoc.start ) || mapping.sourceLines.lastPos(); var targetCursor = targetLines.skipSpaces( mapping.targetLoc.start ) || targetLines.lastPos(); while (comparePos(sourceCursor, mapping.sourceLoc.end) < 0 && comparePos(targetCursor, mapping.targetLoc.end) < 0) { var sourceChar = mapping.sourceLines.charAt(sourceCursor); var targetChar = targetLines.charAt(targetCursor); assert.strictEqual(sourceChar, targetChar); var sourceName = mapping.sourceLines.name; // Add mappings one character at a time for maximum resolution. smg.addMapping({ source: sourceName, original: { line: sourceCursor.line, column: sourceCursor.column }, generated: { line: targetCursor.line, column: targetCursor.column } }); if (!hasOwn.call(sourcesToContents, sourceName)) { var sourceContent = mapping.sourceLines.toString(); smg.setSourceContent(sourceName, sourceContent); sourcesToContents[sourceName] = sourceContent; } targetLines.nextPos(targetCursor, true); mapping.sourceLines.nextPos(sourceCursor, true); } }); secret.cachedSourceMap = smg; return smg.toJSON(); }; Lp.bootstrapCharAt = function(pos) { assert.strictEqual(typeof pos, "object"); assert.strictEqual(typeof pos.line, "number"); assert.strictEqual(typeof pos.column, "number"); var line = pos.line, column = pos.column, strings = this.toString().split(lineTerminatorSeqExp), string = strings[line - 1]; if (typeof string === "undefined") return ""; if (column === string.length && line < strings.length) return "\n"; if (column >= string.length) return ""; return string.charAt(column); }; Lp.charAt = function(pos) { assert.strictEqual(typeof pos, "object"); assert.strictEqual(typeof pos.line, "number"); assert.strictEqual(typeof pos.column, "number"); var line = pos.line, column = pos.column, secret = getSecret(this), infos = secret.infos, info = infos[line - 1], c = column; if (typeof info === "undefined" || c < 0) return ""; var indent = this.getIndentAt(line); if (c < indent) return " "; c += info.sliceStart - indent; if (c === info.sliceEnd && line < this.length) return "\n"; if (c >= info.sliceEnd) return ""; return info.line.charAt(c); }; Lp.stripMargin = function(width, skipFirstLine) { if (width === 0) return this; assert.ok(width > 0, "negative margin: " + width); if (skipFirstLine && this.length === 1) return this; var secret = getSecret(this); var lines = new Lines(secret.infos.map(function(info, i) { if (info.line && (i > 0 || !skipFirstLine)) { info = copyLineInfo(info); info.indent = Math.max(0, info.indent - width); } return info; })); if (secret.mappings.length > 0) { var newMappings = getSecret(lines).mappings; assert.strictEqual(newMappings.length, 0); secret.mappings.forEach(function(mapping) { newMappings.push(mapping.indent(width, skipFirstLine, true)); }); } return lines; }; Lp.indent = function(by) { if (by === 0) return this; var secret = getSecret(this); var lines = new Lines(secret.infos.map(function(info) { if (info.line && ! info.locked) { info = copyLineInfo(info); info.indent += by; } return info })); if (secret.mappings.length > 0) { var newMappings = getSecret(lines).mappings; assert.strictEqual(newMappings.length, 0); secret.mappings.forEach(function(mapping) { newMappings.push(mapping.indent(by)); }); } return lines; }; Lp.indentTail = function(by) { if (by === 0) return this; if (this.length < 2) return this; var secret = getSecret(this); var lines = new Lines(secret.infos.map(function(info, i) { if (i > 0 && info.line && ! info.locked) { info = copyLineInfo(info); info.indent += by; } return info; })); if (secret.mappings.length > 0) { var newMappings = getSecret(lines).mappings; assert.strictEqual(newMappings.length, 0); secret.mappings.forEach(function(mapping) { newMappings.push(mapping.indent(by, true)); }); } return lines; }; Lp.lockIndentTail = function () { if (this.length < 2) { return this; } var infos = getSecret(this).infos; return new Lines(infos.map(function (info, i) { info = copyLineInfo(info); info.locked = i > 0; return info; })); }; Lp.getIndentAt = function(line) { assert.ok(line >= 1, "no line " + line + " (line numbers start from 1)"); var secret = getSecret(this), info = secret.infos[line - 1]; return Math.max(info.indent, 0); }; Lp.guessTabWidth = function() { var secret = getSecret(this); if (hasOwn.call(secret, "cachedTabWidth")) { return secret.cachedTabWidth; } var counts = []; // Sparse array. var lastIndent = 0; for (var line = 1, last = this.length; line <= last; ++line) { var info = secret.infos[line - 1]; var sliced = info.line.slice(info.sliceStart, info.sliceEnd); // Whitespace-only lines don't tell us much about the likely tab // width of this code. if (isOnlyWhitespace(sliced)) { continue; } var diff = Math.abs(info.indent - lastIndent); counts[diff] = ~~counts[diff] + 1; lastIndent = info.indent; } var maxCount = -1; var result = 2; for (var tabWidth = 1; tabWidth < counts.length; tabWidth += 1) { if (hasOwn.call(counts, tabWidth) && counts[tabWidth] > maxCount) { maxCount = counts[tabWidth]; result = tabWidth; } } return secret.cachedTabWidth = result; }; Lp.isOnlyWhitespace = function() { return isOnlyWhitespace(this.toString()); }; Lp.isPrecededOnlyByWhitespace = function(pos) { var secret = getSecret(this); var info = secret.infos[pos.line - 1]; var indent = Math.max(info.indent, 0); var diff = pos.column - indent; if (diff <= 0) { // If pos.column does not exceed the indentation amount, then // there must be only whitespace before it. return true; } var start = info.sliceStart; var end = Math.min(start + diff, info.sliceEnd); var prefix = info.line.slice(start, end); return isOnlyWhitespace(prefix); }; Lp.getLineLength = function(line) { var secret = getSecret(this), info = secret.infos[line - 1]; return this.getIndentAt(line) + info.sliceEnd - info.sliceStart; }; Lp.nextPos = function(pos, skipSpaces) { var l = Math.max(pos.line, 0), c = Math.max(pos.column, 0); if (c < this.getLineLength(l)) { pos.column += 1; return skipSpaces ? !!this.skipSpaces(pos, false, true) : true; } if (l < this.length) { pos.line += 1; pos.column = 0; return skipSpaces ? !!this.skipSpaces(pos, false, true) : true; } return false; }; Lp.prevPos = function(pos, skipSpaces) { var l = pos.line, c = pos.column; if (c < 1) { l -= 1; if (l < 1) return false; c = this.getLineLength(l); } else { c = Math.min(c - 1, this.getLineLength(l)); } pos.line = l; pos.column = c; return skipSpaces ? !!this.skipSpaces(pos, true, true) : true; }; Lp.firstPos = function() { // Trivial, but provided for completeness. return { line: 1, column: 0 }; }; Lp.lastPos = function() { return { line: this.length, column: this.getLineLength(this.length) }; }; Lp.skipSpaces = function(pos, backward, modifyInPlace) { if (pos) { pos = modifyInPlace ? pos : { line: pos.line, column: pos.column }; } else if (backward) { pos = this.lastPos(); } else { pos = this.firstPos(); } if (backward) { while (this.prevPos(pos)) { if (!isOnlyWhitespace(this.charAt(pos)) && this.nextPos(pos)) { return pos; } } return null; } else { while (isOnlyWhitespace(this.charAt(pos))) { if (!this.nextPos(pos)) { return null; } } return pos; } }; Lp.trimLeft = function() { var pos = this.skipSpaces(this.firstPos(), false, true); return pos ? this.slice(pos) : emptyLines; }; Lp.trimRight = function() { var pos = this.skipSpaces(this.lastPos(), true, true); return pos ? this.slice(this.firstPos(), pos) : emptyLines; }; Lp.trim = function() { var start = this.skipSpaces(this.firstPos(), false, true); if (start === null) return emptyLines; var end = this.skipSpaces(this.lastPos(), true, true); assert.notStrictEqual(end, null); return this.slice(start, end); }; Lp.eachPos = function(callback, startPos, skipSpaces) { var pos = this.firstPos(); if (startPos) { pos.line = startPos.line, pos.column = startPos.column } if (skipSpaces && !this.skipSpaces(pos, false, true)) { return; // Encountered nothing but spaces. } do callback.call(this, pos); while (this.nextPos(pos, skipSpaces)); }; Lp.bootstrapSlice = function(start, end) { var strings = this.toString().split( lineTerminatorSeqExp ).slice( start.line - 1, end.line ); strings.push(strings.pop().slice(0, end.column)); strings[0] = strings[0].slice(start.column); return fromString(strings.join("\n")); }; Lp.slice = function(start, end) { if (!end) { if (!start) { // The client seems to want a copy of this Lines object, but // Lines objects are immutable, so it's perfectly adequate to // return the same object. return this; } // Slice to the end if no end position was provided. end = this.lastPos(); } var secret = getSecret(this); var sliced = secret.infos.slice(start.line - 1, end.line); if (start.line === end.line) { sliced[0] = sliceInfo(sliced[0], start.column, end.column); } else { assert.ok(start.line < end.line); sliced[0] = sliceInfo(sliced[0], start.column); sliced.push(sliceInfo(sliced.pop(), 0, end.column)); } var lines = new Lines(sliced); if (secret.mappings.length > 0) { var newMappings = getSecret(lines).mappings; assert.strictEqual(newMappings.length, 0); secret.mappings.forEach(function(mapping) { var sliced = mapping.slice(this, start, end); if (sliced) { newMappings.push(sliced); } }, this); } return lines; }; function sliceInfo(info, startCol, endCol) { var sliceStart = info.sliceStart; var sliceEnd = info.sliceEnd; var indent = Math.max(info.indent, 0); var lineLength = indent + sliceEnd - sliceStart; if (typeof endCol === "undefined") { endCol = lineLength; } startCol = Math.max(startCol, 0); endCol = Math.min(endCol, lineLength); endCol = Math.max(endCol, startCol); if (endCol < indent) { indent = endCol; sliceEnd = sliceStart; } else { sliceEnd -= lineLength - endCol; } lineLength = endCol; lineLength -= startCol; if (startCol < indent) { indent -= startCol; } else { startCol -= indent; indent = 0; sliceStart += startCol; } assert.ok(indent >= 0); assert.ok(sliceStart <= sliceEnd); assert.strictEqual(lineLength, indent + sliceEnd - sliceStart); if (info.indent === indent && info.sliceStart === sliceStart && info.sliceEnd === sliceEnd) { return info; } return { line: info.line, indent: indent, // A destructive slice always unlocks indentation. locked: false, sliceStart: sliceStart, sliceEnd: sliceEnd }; } Lp.bootstrapSliceString = function(start, end, options) { return this.slice(start, end).toString(options); }; Lp.sliceString = function(start, end, options) { if (!end) { if (!start) { // The client seems to want a copy of this Lines object, but // Lines objects are immutable, so it's perfectly adequate to // return the same object. return this; } // Slice to the end if no end position was provided. end = this.lastPos(); } options = normalizeOptions(options); var infos = getSecret(this).infos; var parts = []; var tabWidth = options.tabWidth; for (var line = start.line; line <= end.line; ++line) { var info = infos[line - 1]; if (line === start.line) { if (line === end.line) { info = sliceInfo(info, start.column, end.column); } else { info = sliceInfo(info, start.column); } } else if (line === end.line) { info = sliceInfo(info, 0, end.column); } var indent = Math.max(info.indent, 0); var before = info.line.slice(0, info.sliceStart); if (options.reuseWhitespace && isOnlyWhitespace(before) && countSpaces(before, options.tabWidth) === indent) { // Reuse original spaces if the indentation is correct. parts.push(info.line.slice(0, info.sliceEnd)); continue; } var tabs = 0; var spaces = indent; if (options.useTabs) { tabs = Math.floor(indent / tabWidth); spaces -= tabs * tabWidth; } var result = ""; if (tabs > 0) { result += new Array(tabs + 1).join("\t"); } if (spaces > 0) { result += new Array(spaces + 1).join(" "); } result += info.line.slice(info.sliceStart, info.sliceEnd); parts.push(result); } return parts.join(options.lineTerminator); }; Lp.isEmpty = function() { return this.length < 2 && this.getLineLength(1) < 1; }; Lp.join = function(elements) { var separator = this; var separatorSecret = getSecret(separator); var infos = []; var mappings = []; var prevInfo; function appendSecret(secret) { if (secret === null) return; if (prevInfo) { var info = secret.infos[0]; var indent = new Array(info.indent + 1).join(" "); var prevLine = infos.length; var prevColumn = Math.max(prevInfo.indent, 0) + prevInfo.sliceEnd - prevInfo.sliceStart; prevInfo.line = prevInfo.line.slice( 0, prevInfo.sliceEnd) + indent + info.line.slice( info.sliceStart, info.sliceEnd); // If any part of a line is indentation-locked, the whole line // will be indentation-locked. prevInfo.locked = prevInfo.locked || info.locked; prevInfo.sliceEnd = prevInfo.line.length; if (secret.mappings.length > 0) { secret.mappings.forEach(function(mapping) { mappings.push(mapping.add(prevLine, prevColumn)); }); } } else if (secret.mappings.length > 0) { mappings.push.apply(mappings, secret.mappings); } secret.infos.forEach(function(info, i) { if (!prevInfo || i > 0) { prevInfo = copyLineInfo(info); infos.push(prevInfo); } }); } function appendWithSeparator(secret, i) { if (i > 0) appendSecret(separatorSecret); appendSecret(secret); } elements.map(function(elem) { var lines = fromString(elem); if (lines.isEmpty()) return null; return getSecret(lines); }).forEach(separator.isEmpty() ? appendSecret : appendWithSeparator); if (infos.length < 1) return emptyLines; var lines = new Lines(infos); getSecret(lines).mappings = mappings; return lines; }; exports.concat = function(elements) { return emptyLines.join(elements); }; Lp.concat = function(other) { var args = arguments, list = [this]; list.push.apply(list, args); assert.strictEqual(list.length, args.length + 1); return emptyLines.join(list); }; // The emptyLines object needs to be created all the way down here so that // Lines.prototype will be fully populated. var emptyLines = fromString(""); ```
/content/code_sandbox/node_modules/recast/lib/lines.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
5,360
```javascript var assert = require("assert"); var types = require("./types"); var isString = types.builtInTypes.string; var isNumber = types.builtInTypes.number; var SourceLocation = types.namedTypes.SourceLocation; var Position = types.namedTypes.Position; var linesModule = require("./lines"); var comparePos = require("./util").comparePos; function Mapping(sourceLines, sourceLoc, targetLoc) { assert.ok(this instanceof Mapping); assert.ok(sourceLines instanceof linesModule.Lines); SourceLocation.assert(sourceLoc); if (targetLoc) { // In certain cases it's possible for targetLoc.{start,end}.column // values to be negative, which technically makes them no longer // valid SourceLocation nodes, so we need to be more forgiving. assert.ok( isNumber.check(targetLoc.start.line) && isNumber.check(targetLoc.start.column) && isNumber.check(targetLoc.end.line) && isNumber.check(targetLoc.end.column) ); } else { // Assume identity mapping if no targetLoc specified. targetLoc = sourceLoc; } Object.defineProperties(this, { sourceLines: { value: sourceLines }, sourceLoc: { value: sourceLoc }, targetLoc: { value: targetLoc } }); } var Mp = Mapping.prototype; module.exports = Mapping; Mp.slice = function(lines, start, end) { assert.ok(lines instanceof linesModule.Lines); Position.assert(start); if (end) { Position.assert(end); } else { end = lines.lastPos(); } var sourceLines = this.sourceLines; var sourceLoc = this.sourceLoc; var targetLoc = this.targetLoc; function skip(name) { var sourceFromPos = sourceLoc[name]; var targetFromPos = targetLoc[name]; var targetToPos = start; if (name === "end") { targetToPos = end; } else { assert.strictEqual(name, "start"); } return skipChars( sourceLines, sourceFromPos, lines, targetFromPos, targetToPos ); } if (comparePos(start, targetLoc.start) <= 0) { if (comparePos(targetLoc.end, end) <= 0) { targetLoc = { start: subtractPos(targetLoc.start, start.line, start.column), end: subtractPos(targetLoc.end, start.line, start.column) }; // The sourceLoc can stay the same because the contents of the // targetLoc have not changed. } else if (comparePos(end, targetLoc.start) <= 0) { return null; } else { sourceLoc = { start: sourceLoc.start, end: skip("end") }; targetLoc = { start: subtractPos(targetLoc.start, start.line, start.column), end: subtractPos(end, start.line, start.column) }; } } else { if (comparePos(targetLoc.end, start) <= 0) { return null; } if (comparePos(targetLoc.end, end) <= 0) { sourceLoc = { start: skip("start"), end: sourceLoc.end }; targetLoc = { // Same as subtractPos(start, start.line, start.column): start: { line: 1, column: 0 }, end: subtractPos(targetLoc.end, start.line, start.column) }; } else { sourceLoc = { start: skip("start"), end: skip("end") }; targetLoc = { // Same as subtractPos(start, start.line, start.column): start: { line: 1, column: 0 }, end: subtractPos(end, start.line, start.column) }; } } return new Mapping(this.sourceLines, sourceLoc, targetLoc); }; Mp.add = function(line, column) { return new Mapping(this.sourceLines, this.sourceLoc, { start: addPos(this.targetLoc.start, line, column), end: addPos(this.targetLoc.end, line, column) }); }; function addPos(toPos, line, column) { return { line: toPos.line + line - 1, column: (toPos.line === 1) ? toPos.column + column : toPos.column }; } Mp.subtract = function(line, column) { return new Mapping(this.sourceLines, this.sourceLoc, { start: subtractPos(this.targetLoc.start, line, column), end: subtractPos(this.targetLoc.end, line, column) }); }; function subtractPos(fromPos, line, column) { return { line: fromPos.line - line + 1, column: (fromPos.line === line) ? fromPos.column - column : fromPos.column }; } Mp.indent = function(by, skipFirstLine, noNegativeColumns) { if (by === 0) { return this; } var targetLoc = this.targetLoc; var startLine = targetLoc.start.line; var endLine = targetLoc.end.line; if (skipFirstLine && startLine === 1 && endLine === 1) { return this; } targetLoc = { start: targetLoc.start, end: targetLoc.end }; if (!skipFirstLine || startLine > 1) { var startColumn = targetLoc.start.column + by; targetLoc.start = { line: startLine, column: noNegativeColumns ? Math.max(0, startColumn) : startColumn }; } if (!skipFirstLine || endLine > 1) { var endColumn = targetLoc.end.column + by; targetLoc.end = { line: endLine, column: noNegativeColumns ? Math.max(0, endColumn) : endColumn }; } return new Mapping(this.sourceLines, this.sourceLoc, targetLoc); }; function skipChars( sourceLines, sourceFromPos, targetLines, targetFromPos, targetToPos ) { assert.ok(sourceLines instanceof linesModule.Lines); assert.ok(targetLines instanceof linesModule.Lines); Position.assert(sourceFromPos); Position.assert(targetFromPos); Position.assert(targetToPos); var targetComparison = comparePos(targetFromPos, targetToPos); if (targetComparison === 0) { // Trivial case: no characters to skip. return sourceFromPos; } if (targetComparison < 0) { // Skipping forward. var sourceCursor = sourceLines.skipSpaces(sourceFromPos); var targetCursor = targetLines.skipSpaces(targetFromPos); var lineDiff = targetToPos.line - targetCursor.line; sourceCursor.line += lineDiff; targetCursor.line += lineDiff; if (lineDiff > 0) { // If jumping to later lines, reset columns to the beginnings // of those lines. sourceCursor.column = 0; targetCursor.column = 0; } else { assert.strictEqual(lineDiff, 0); } while (comparePos(targetCursor, targetToPos) < 0 && targetLines.nextPos(targetCursor, true)) { assert.ok(sourceLines.nextPos(sourceCursor, true)); assert.strictEqual( sourceLines.charAt(sourceCursor), targetLines.charAt(targetCursor) ); } } else { // Skipping backward. var sourceCursor = sourceLines.skipSpaces(sourceFromPos, true); var targetCursor = targetLines.skipSpaces(targetFromPos, true); var lineDiff = targetToPos.line - targetCursor.line; sourceCursor.line += lineDiff; targetCursor.line += lineDiff; if (lineDiff < 0) { // If jumping to earlier lines, reset columns to the ends of // those lines. sourceCursor.column = sourceLines.getLineLength(sourceCursor.line); targetCursor.column = targetLines.getLineLength(targetCursor.line); } else { assert.strictEqual(lineDiff, 0); } while (comparePos(targetToPos, targetCursor) < 0 && targetLines.prevPos(targetCursor, true)) { assert.ok(sourceLines.prevPos(sourceCursor, true)); assert.strictEqual( sourceLines.charAt(sourceCursor), targetLines.charAt(targetCursor) ); } } return sourceCursor; } ```
/content/code_sandbox/node_modules/recast/lib/mapping.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,808