@ -0,0 +1,21 @@ | |||
var axios = require('axios') | |||
var http = require('http'); | |||
function getDataPromise() { | |||
return axios({ | |||
method: 'get', | |||
timeout: 8000, | |||
}) | |||
.then(res => res.data) | |||
.catch (err => console.error(err)) | |||
} | |||
http.createServer((request, response)=>{ | |||
getDataPromise() | |||
.then(res => console.log(res)); | |||
console.log(response.data) | |||
}).listen(8000); | |||
@ -0,0 +1,762 @@ | |||
File not exists: /home/alpcentaur/ProjektA/PermApp/favicon.ico | |||
oleola <ref *2> IncomingMessage { | |||
_readableState: ReadableState { | |||
objectMode: false, | |||
highWaterMark: 16384, | |||
buffer: BufferList { head: null, tail: null, length: 0 }, | |||
length: 0, | |||
pipes: [], | |||
flowing: null, | |||
ended: false, | |||
endEmitted: false, | |||
reading: false, | |||
sync: true, | |||
needReadable: false, | |||
emittedReadable: false, | |||
readableListening: false, | |||
resumeScheduled: false, | |||
errorEmitted: false, | |||
emitClose: true, | |||
autoDestroy: false, | |||
destroyed: false, | |||
errored: false, | |||
closed: false, | |||
closeEmitted: false, | |||
defaultEncoding: 'utf8', | |||
awaitDrainWriters: null, | |||
multiAwaitDrain: false, | |||
readingMore: true, | |||
decoder: null, | |||
encoding: null, | |||
[Symbol(kPaused)]: null | |||
}, | |||
_events: [Object: null prototype] {}, | |||
_eventsCount: 0, | |||
_maxListeners: undefined, | |||
socket: <ref *1> Socket { | |||
connecting: false, | |||
_hadError: false, | |||
_parent: null, | |||
_host: null, | |||
_readableState: ReadableState { | |||
objectMode: false, | |||
highWaterMark: 16384, | |||
buffer: BufferList { head: null, tail: null, length: 0 }, | |||
length: 0, | |||
pipes: [], | |||
flowing: true, | |||
ended: false, | |||
endEmitted: false, | |||
reading: true, | |||
sync: false, | |||
needReadable: true, | |||
emittedReadable: false, | |||
readableListening: false, | |||
resumeScheduled: false, | |||
errorEmitted: false, | |||
emitClose: false, | |||
autoDestroy: false, | |||
destroyed: false, | |||
errored: false, | |||
closed: false, | |||
closeEmitted: false, | |||
defaultEncoding: 'utf8', | |||
awaitDrainWriters: null, | |||
multiAwaitDrain: false, | |||
readingMore: false, | |||
decoder: null, | |||
encoding: null, | |||
[Symbol(kPaused)]: false | |||
}, | |||
_events: [Object: null prototype] { | |||
end: [Array], | |||
timeout: [Function: socketOnTimeout], | |||
data: [Function: bound socketOnData], | |||
error: [Function: socketOnError], | |||
close: [Array], | |||
drain: [Function: bound socketOnDrain], | |||
resume: [Function: onSocketResume], | |||
pause: [Function: onSocketPause] | |||
}, | |||
_eventsCount: 8, | |||
_maxListeners: undefined, | |||
_writableState: WritableState { | |||
objectMode: false, | |||
highWaterMark: 16384, | |||
finalCalled: false, | |||
needDrain: false, | |||
ending: false, | |||
ended: false, | |||
finished: false, | |||
destroyed: false, | |||
decodeStrings: false, | |||
defaultEncoding: 'utf8', | |||
length: 0, | |||
writing: false, | |||
corked: 0, | |||
sync: false, | |||
bufferProcessing: false, | |||
onwrite: [Function: bound onwrite], | |||
writecb: null, | |||
writelen: 0, | |||
afterWriteTickInfo: null, | |||
buffered: [], | |||
bufferedIndex: 0, | |||
allBuffers: true, | |||
allNoop: true, | |||
pendingcb: 0, | |||
prefinished: false, | |||
errorEmitted: false, | |||
emitClose: false, | |||
autoDestroy: false, | |||
errored: false, | |||
closed: false | |||
}, | |||
allowHalfOpen: true, | |||
_sockname: null, | |||
_pendingData: null, | |||
_pendingEncoding: '', | |||
server: Server { | |||
maxHeaderSize: undefined, | |||
insecureHTTPParser: undefined, | |||
_events: [Object: null prototype], | |||
_eventsCount: 2, | |||
_maxListeners: undefined, | |||
_connections: 2, | |||
_handle: [TCP], | |||
_usingWorkers: false, | |||
_workers: [], | |||
_unref: false, | |||
allowHalfOpen: true, | |||
pauseOnConnect: false, | |||
httpAllowHalfOpen: false, | |||
timeout: 0, | |||
keepAliveTimeout: 5000, | |||
maxHeadersCount: null, | |||
headersTimeout: 60000, | |||
_connectionKey: '6::::5000', | |||
[Symbol(IncomingMessage)]: [Function: IncomingMessage], | |||
[Symbol(ServerResponse)]: [Function: ServerResponse], | |||
[Symbol(kCapture)]: false, | |||
[Symbol(async_id_symbol)]: 2 | |||
}, | |||
_server: Server { | |||
maxHeaderSize: undefined, | |||
insecureHTTPParser: undefined, | |||
_events: [Object: null prototype], | |||
_eventsCount: 2, | |||
_maxListeners: undefined, | |||
_connections: 2, | |||
_handle: [TCP], | |||
_usingWorkers: false, | |||
_workers: [], | |||
_unref: false, | |||
allowHalfOpen: true, | |||
pauseOnConnect: false, | |||
httpAllowHalfOpen: false, | |||
timeout: 0, | |||
keepAliveTimeout: 5000, | |||
maxHeadersCount: null, | |||
headersTimeout: 60000, | |||
_connectionKey: '6::::5000', | |||
[Symbol(IncomingMessage)]: [Function: IncomingMessage], | |||
[Symbol(ServerResponse)]: [Function: ServerResponse], | |||
[Symbol(kCapture)]: false, | |||
[Symbol(async_id_symbol)]: 2 | |||
}, | |||
parser: HTTPParser { | |||
'0': [Function: parserOnHeaders], | |||
'1': [Function: parserOnHeadersComplete], | |||
'2': [Function: parserOnBody], | |||
'3': [Function: parserOnMessageComplete], | |||
'4': [Function: bound onParserExecute], | |||
'5': [Function: bound onParserTimeout], | |||
_headers: [], | |||
_url: '', | |||
socket: [Circular *1], | |||
incoming: [Circular *2], | |||
outgoing: null, | |||
maxHeaderPairs: 2000, | |||
_consumed: true, | |||
onIncoming: [Function: bound parserOnIncoming], | |||
[Symbol(resource_symbol)]: [HTTPServerAsyncResource] | |||
}, | |||
on: [Function: socketListenerWrap], | |||
addListener: [Function: socketListenerWrap], | |||
prependListener: [Function: socketListenerWrap], | |||
_paused: false, | |||
_httpMessage: ServerResponse { | |||
_events: [Object: null prototype], | |||
_eventsCount: 5, | |||
_maxListeners: undefined, | |||
outputData: [], | |||
outputSize: 0, | |||
writable: true, | |||
destroyed: false, | |||
_last: false, | |||
chunkedEncoding: true, | |||
shouldKeepAlive: true, | |||
useChunkedEncodingByDefault: true, | |||
sendDate: true, | |||
_removedConnection: false, | |||
_removedContLen: false, | |||
_removedTE: false, | |||
_contentLength: null, | |||
_hasBody: true, | |||
_trailer: '', | |||
finished: false, | |||
_headerSent: false, | |||
socket: [Circular *1], | |||
_header: 'HTTP/1.1 200 OK\r\n' + | |||
'Content-Type: text/plain\r\n' + | |||
'Date: Tue, 03 Nov 2020 11:11:59 GMT\r\n' + | |||
'Connection: keep-alive\r\n' + | |||
'Keep-Alive: timeout=5\r\n' + | |||
'Transfer-Encoding: chunked\r\n' + | |||
'\r\n', | |||
_keepAliveTimeout: 5000, | |||
_onPendingData: [Function: bound updateOutgoingData], | |||
_sent100: false, | |||
_expect_continue: false, | |||
statusMessage: 'OK', | |||
statusCode: 200, | |||
[Symbol(kCapture)]: false, | |||
[Symbol(kNeedDrain)]: false, | |||
[Symbol(corked)]: 0, | |||
[Symbol(kOutHeaders)]: null | |||
}, | |||
timeout: 0, | |||
[Symbol(async_id_symbol)]: 4, | |||
[Symbol(kHandle)]: TCP { | |||
reading: true, | |||
onconnection: null, | |||
_consumed: true, | |||
[Symbol(owner_symbol)]: [Circular *1] | |||
}, | |||
[Symbol(kSetNoDelay)]: false, | |||
[Symbol(lastWriteQueueSize)]: 0, | |||
[Symbol(timeout)]: Timeout { | |||
_idleTimeout: -1, | |||
_idlePrev: null, | |||
_idleNext: null, | |||
_idleStart: 4823, | |||
_onTimeout: null, | |||
_timerArgs: undefined, | |||
_repeat: null, | |||
_destroyed: true, | |||
[Symbol(refed)]: false, | |||
[Symbol(asyncId)]: 221, | |||
[Symbol(triggerId)]: 218 | |||
}, | |||
[Symbol(kBuffer)]: null, | |||
[Symbol(kBufferCb)]: null, | |||
[Symbol(kBufferGen)]: null, | |||
[Symbol(kCapture)]: false, | |||
[Symbol(kBytesRead)]: 0, | |||
[Symbol(kBytesWritten)]: 0 | |||
}, | |||
httpVersionMajor: 1, | |||
httpVersionMinor: 1, | |||
httpVersion: '1.1', | |||
complete: false, | |||
headers: { | |||
host: 'localhost:5000', | |||
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:79.0) Gecko/20100101 Firefox/79.0', | |||
accept: '*/*', | |||
'accept-language': 'en-US,en;q=0.5', | |||
'accept-encoding': 'gzip, deflate', | |||
'content-type': 'text/plain;charset=UTF-8', | |||
'content-length': '11', | |||
origin: 'http://localhost:5000', | |||
dnt: '1', | |||
connection: 'keep-alive', | |||
referer: 'http://localhost:5000/', | |||
'sec-gpc': '1' | |||
}, | |||
rawHeaders: [ | |||
'Host', | |||
'localhost:5000', | |||
'User-Agent', | |||
'Mozilla/5.0 (X11; Linux x86_64; rv:79.0) Gecko/20100101 Firefox/79.0', | |||
'Accept', | |||
'*/*', | |||
'Accept-Language', | |||
'en-US,en;q=0.5', | |||
'Accept-Encoding', | |||
'gzip, deflate', | |||
'Content-Type', | |||
'text/plain;charset=UTF-8', | |||
'Content-Length', | |||
'11', | |||
'Origin', | |||
'http://localhost:5000', | |||
'DNT', | |||
'1', | |||
'Connection', | |||
'keep-alive', | |||
'Referer', | |||
'http://localhost:5000/', | |||
'Sec-GPC', | |||
'1' | |||
], | |||
trailers: {}, | |||
rawTrailers: [], | |||
aborted: false, | |||
upgrade: false, | |||
url: '/public/data.json', | |||
method: 'POST', | |||
statusCode: null, | |||
statusMessage: null, | |||
client: <ref *1> Socket { | |||
connecting: false, | |||
_hadError: false, | |||
_parent: null, | |||
_host: null, | |||
_readableState: ReadableState { | |||
objectMode: false, | |||
highWaterMark: 16384, | |||
buffer: BufferList { head: null, tail: null, length: 0 }, | |||
length: 0, | |||
pipes: [], | |||
flowing: true, | |||
ended: false, | |||
endEmitted: false, | |||
reading: true, | |||
sync: false, | |||
needReadable: true, | |||
emittedReadable: false, | |||
readableListening: false, | |||
resumeScheduled: false, | |||
errorEmitted: false, | |||
emitClose: false, | |||
autoDestroy: false, | |||
destroyed: false, | |||
errored: false, | |||
closed: false, | |||
closeEmitted: false, | |||
defaultEncoding: 'utf8', | |||
awaitDrainWriters: null, | |||
multiAwaitDrain: false, | |||
readingMore: false, | |||
decoder: null, | |||
encoding: null, | |||
[Symbol(kPaused)]: false | |||
}, | |||
_events: [Object: null prototype] { | |||
end: [Array], | |||
timeout: [Function: socketOnTimeout], | |||
data: [Function: bound socketOnData], | |||
error: [Function: socketOnError], | |||
close: [Array], | |||
drain: [Function: bound socketOnDrain], | |||
resume: [Function: onSocketResume], | |||
pause: [Function: onSocketPause] | |||
}, | |||
_eventsCount: 8, | |||
_maxListeners: undefined, | |||
_writableState: WritableState { | |||
objectMode: false, | |||
highWaterMark: 16384, | |||
finalCalled: false, | |||
needDrain: false, | |||
ending: false, | |||
ended: false, | |||
finished: false, | |||
destroyed: false, | |||
decodeStrings: false, | |||
defaultEncoding: 'utf8', | |||
length: 0, | |||
writing: false, | |||
corked: 0, | |||
sync: false, | |||
bufferProcessing: false, | |||
onwrite: [Function: bound onwrite], | |||
writecb: null, | |||
writelen: 0, | |||
afterWriteTickInfo: null, | |||
buffered: [], | |||
bufferedIndex: 0, | |||
allBuffers: true, | |||
allNoop: true, | |||
pendingcb: 0, | |||
prefinished: false, | |||
errorEmitted: false, | |||
emitClose: false, | |||
autoDestroy: false, | |||
errored: false, | |||
closed: false | |||
}, | |||
allowHalfOpen: true, | |||
_sockname: null, | |||
_pendingData: null, | |||
_pendingEncoding: '', | |||
server: Server { | |||
maxHeaderSize: undefined, | |||
insecureHTTPParser: undefined, | |||
_events: [Object: null prototype], | |||
_eventsCount: 2, | |||
_maxListeners: undefined, | |||
_connections: 2, | |||
_handle: [TCP], | |||
_usingWorkers: false, | |||
_workers: [], | |||
_unref: false, | |||
allowHalfOpen: true, | |||
pauseOnConnect: false, | |||
httpAllowHalfOpen: false, | |||
timeout: 0, | |||
keepAliveTimeout: 5000, | |||
maxHeadersCount: null, | |||
headersTimeout: 60000, | |||
_connectionKey: '6::::5000', | |||
[Symbol(IncomingMessage)]: [Function: IncomingMessage], | |||
[Symbol(ServerResponse)]: [Function: ServerResponse], | |||
[Symbol(kCapture)]: false, | |||
[Symbol(async_id_symbol)]: 2 | |||
}, | |||
_server: Server { | |||
maxHeaderSize: undefined, | |||
insecureHTTPParser: undefined, | |||
_events: [Object: null prototype], | |||
_eventsCount: 2, | |||
_maxListeners: undefined, | |||
_connections: 2, | |||
_handle: [TCP], | |||
_usingWorkers: false, | |||
_workers: [], | |||
_unref: false, | |||
allowHalfOpen: true, | |||
pauseOnConnect: false, | |||
httpAllowHalfOpen: false, | |||
timeout: 0, | |||
keepAliveTimeout: 5000, | |||
maxHeadersCount: null, | |||
headersTimeout: 60000, | |||
_connectionKey: '6::::5000', | |||
[Symbol(IncomingMessage)]: [Function: IncomingMessage], | |||
[Symbol(ServerResponse)]: [Function: ServerResponse], | |||
[Symbol(kCapture)]: false, | |||
[Symbol(async_id_symbol)]: 2 | |||
}, | |||
parser: HTTPParser { | |||
'0': [Function: parserOnHeaders], | |||
'1': [Function: parserOnHeadersComplete], | |||
'2': [Function: parserOnBody], | |||
'3': [Function: parserOnMessageComplete], | |||
'4': [Function: bound onParserExecute], | |||
'5': [Function: bound onParserTimeout], | |||
_headers: [], | |||
_url: '', | |||
socket: [Circular *1], | |||
incoming: [Circular *2], | |||
outgoing: null, | |||
maxHeaderPairs: 2000, | |||
_consumed: true, | |||
onIncoming: [Function: bound parserOnIncoming], | |||
[Symbol(resource_symbol)]: [HTTPServerAsyncResource] | |||
}, | |||
on: [Function: socketListenerWrap], | |||
addListener: [Function: socketListenerWrap], | |||
prependListener: [Function: socketListenerWrap], | |||
_paused: false, | |||
_httpMessage: ServerResponse { | |||
_events: [Object: null prototype], | |||
_eventsCount: 5, | |||
_maxListeners: undefined, | |||
outputData: [], | |||
outputSize: 0, | |||
writable: true, | |||
destroyed: false, | |||
_last: false, | |||
chunkedEncoding: true, | |||
shouldKeepAlive: true, | |||
useChunkedEncodingByDefault: true, | |||
sendDate: true, | |||
_removedConnection: false, | |||
_removedContLen: false, | |||
_removedTE: false, | |||
_contentLength: null, | |||
_hasBody: true, | |||
_trailer: '', | |||
finished: false, | |||
_headerSent: false, | |||
socket: [Circular *1], | |||
_header: 'HTTP/1.1 200 OK\r\n' + | |||
'Content-Type: text/plain\r\n' + | |||
'Date: Tue, 03 Nov 2020 11:11:59 GMT\r\n' + | |||
'Connection: keep-alive\r\n' + | |||
'Keep-Alive: timeout=5\r\n' + | |||
'Transfer-Encoding: chunked\r\n' + | |||
'\r\n', | |||
_keepAliveTimeout: 5000, | |||
_onPendingData: [Function: bound updateOutgoingData], | |||
_sent100: false, | |||
_expect_continue: false, | |||
statusMessage: 'OK', | |||
statusCode: 200, | |||
[Symbol(kCapture)]: false, | |||
[Symbol(kNeedDrain)]: false, | |||
[Symbol(corked)]: 0, | |||
[Symbol(kOutHeaders)]: null | |||
}, | |||
timeout: 0, | |||
[Symbol(async_id_symbol)]: 4, | |||
[Symbol(kHandle)]: TCP { | |||
reading: true, | |||
onconnection: null, | |||
_consumed: true, | |||
[Symbol(owner_symbol)]: [Circular *1] | |||
}, | |||
[Symbol(kSetNoDelay)]: false, | |||
[Symbol(lastWriteQueueSize)]: 0, | |||
[Symbol(timeout)]: Timeout { | |||
_idleTimeout: -1, | |||
_idlePrev: null, | |||
_idleNext: null, | |||
_idleStart: 4823, | |||
_onTimeout: null, | |||
_timerArgs: undefined, | |||
_repeat: null, | |||
_destroyed: true, | |||
[Symbol(refed)]: false, | |||
[Symbol(asyncId)]: 221, | |||
[Symbol(triggerId)]: 218 | |||
}, | |||
[Symbol(kBuffer)]: null, | |||
[Symbol(kBufferCb)]: null, | |||
[Symbol(kBufferGen)]: null, | |||
[Symbol(kCapture)]: false, | |||
[Symbol(kBytesRead)]: 0, | |||
[Symbol(kBytesWritten)]: 0 | |||
}, | |||
_consuming: false, | |||
_dumped: false, | |||
[Symbol(kCapture)]: false | |||
} <ref *2> ServerResponse { | |||
_events: [Object: null prototype] { | |||
finish: [ [Function: bound resOnFinish], [Function] ], | |||
unpipe: [Function: onunpipe], | |||
error: [Function: onerror], | |||
close: [Function: bound onceWrapper] { listener: [Function: onclose] }, | |||
data: [Function (anonymous)] | |||
}, | |||
_eventsCount: 5, | |||
_maxListeners: undefined, | |||
outputData: [], | |||
outputSize: 0, | |||
writable: true, | |||
destroyed: false, | |||
_last: false, | |||
chunkedEncoding: true, | |||
shouldKeepAlive: true, | |||
useChunkedEncodingByDefault: true, | |||
sendDate: true, | |||
_removedConnection: false, | |||
_removedContLen: false, | |||
_removedTE: false, | |||
_contentLength: null, | |||
_hasBody: true, | |||
_trailer: '', | |||
finished: false, | |||
_headerSent: false, | |||
socket: <ref *1> Socket { | |||
connecting: false, | |||
_hadError: false, | |||
_parent: null, | |||
_host: null, | |||
_readableState: ReadableState { | |||
objectMode: false, | |||
highWaterMark: 16384, | |||
buffer: BufferList { head: null, tail: null, length: 0 }, | |||
length: 0, | |||
pipes: [], | |||
flowing: true, | |||
ended: false, | |||
endEmitted: false, | |||
reading: true, | |||
sync: false, | |||
needReadable: true, | |||
emittedReadable: false, | |||
readableListening: false, | |||
resumeScheduled: false, | |||
errorEmitted: false, | |||
emitClose: false, | |||
autoDestroy: false, | |||
destroyed: false, | |||
errored: false, | |||
closed: false, | |||
closeEmitted: false, | |||
defaultEncoding: 'utf8', | |||
awaitDrainWriters: null, | |||
multiAwaitDrain: false, | |||
readingMore: false, | |||
decoder: null, | |||
encoding: null, | |||
[Symbol(kPaused)]: false | |||
}, | |||
_events: [Object: null prototype] { | |||
end: [Array], | |||
timeout: [Function: socketOnTimeout], | |||
data: [Function: bound socketOnData], | |||
error: [Function: socketOnError], | |||
close: [Array], | |||
drain: [Function: bound socketOnDrain], | |||
resume: [Function: onSocketResume], | |||
pause: [Function: onSocketPause] | |||
}, | |||
_eventsCount: 8, | |||
_maxListeners: undefined, | |||
_writableState: WritableState { | |||
objectMode: false, | |||
highWaterMark: 16384, | |||
finalCalled: false, | |||
needDrain: false, | |||
ending: false, | |||
ended: false, | |||
finished: false, | |||
destroyed: false, | |||
decodeStrings: false, | |||
defaultEncoding: 'utf8', | |||
length: 0, | |||
writing: false, | |||
corked: 0, | |||
sync: false, | |||
bufferProcessing: false, | |||
onwrite: [Function: bound onwrite], | |||
writecb: null, | |||
writelen: 0, | |||
afterWriteTickInfo: null, | |||
buffered: [], | |||
bufferedIndex: 0, | |||
allBuffers: true, | |||
allNoop: true, | |||
pendingcb: 0, | |||
prefinished: false, | |||
errorEmitted: false, | |||
emitClose: false, | |||
autoDestroy: false, | |||
errored: false, | |||
closed: false | |||
}, | |||
allowHalfOpen: true, | |||
_sockname: null, | |||
_pendingData: null, | |||
_pendingEncoding: '', | |||
server: Server { | |||
maxHeaderSize: undefined, | |||
insecureHTTPParser: undefined, | |||
_events: [Object: null prototype], | |||
_eventsCount: 2, | |||
_maxListeners: undefined, | |||
_connections: 2, | |||
_handle: [TCP], | |||
_usingWorkers: false, | |||
_workers: [], | |||
_unref: false, | |||
allowHalfOpen: true, | |||
pauseOnConnect: false, | |||
httpAllowHalfOpen: false, | |||
timeout: 0, | |||
keepAliveTimeout: 5000, | |||
maxHeadersCount: null, | |||
headersTimeout: 60000, | |||
_connectionKey: '6::::5000', | |||
[Symbol(IncomingMessage)]: [Function: IncomingMessage], | |||
[Symbol(ServerResponse)]: [Function: ServerResponse], | |||
[Symbol(kCapture)]: false, | |||
[Symbol(async_id_symbol)]: 2 | |||
}, | |||
_server: Server { | |||
maxHeaderSize: undefined, | |||
insecureHTTPParser: undefined, | |||
_events: [Object: null prototype], | |||
_eventsCount: 2, | |||
_maxListeners: undefined, | |||
_connections: 2, | |||
_handle: [TCP], | |||
_usingWorkers: false, | |||
_workers: [], | |||
_unref: false, | |||
allowHalfOpen: true, | |||
pauseOnConnect: false, | |||
httpAllowHalfOpen: false, | |||
timeout: 0, | |||
keepAliveTimeout: 5000, | |||
maxHeadersCount: null, | |||
headersTimeout: 60000, | |||
_connectionKey: '6::::5000', | |||
[Symbol(IncomingMessage)]: [Function: IncomingMessage], | |||
[Symbol(ServerResponse)]: [Function: ServerResponse], | |||
[Symbol(kCapture)]: false, | |||
[Symbol(async_id_symbol)]: 2 | |||
}, | |||
parser: HTTPParser { | |||
'0': [Function: parserOnHeaders], | |||
'1': [Function: parserOnHeadersComplete], | |||
'2': [Function: parserOnBody], | |||
'3': [Function: parserOnMessageComplete], | |||
'4': [Function: bound onParserExecute], | |||
'5': [Function: bound onParserTimeout], | |||
_headers: [], | |||
_url: '', | |||
socket: [Circular *1], | |||
incoming: [IncomingMessage], | |||
outgoing: null, | |||
maxHeaderPairs: 2000, | |||
_consumed: true, | |||
onIncoming: [Function: bound parserOnIncoming], | |||
[Symbol(resource_symbol)]: [HTTPServerAsyncResource] | |||
}, | |||
on: [Function: socketListenerWrap], | |||
addListener: [Function: socketListenerWrap], | |||
prependListener: [Function: socketListenerWrap], | |||
_paused: false, | |||
_httpMessage: [Circular *2], | |||
timeout: 0, | |||
[Symbol(async_id_symbol)]: 4, | |||
[Symbol(kHandle)]: TCP { | |||
reading: true, | |||
onconnection: null, | |||
_consumed: true, | |||
[Symbol(owner_symbol)]: [Circular *1] | |||
}, | |||
[Symbol(kSetNoDelay)]: false, | |||
[Symbol(lastWriteQueueSize)]: 0, | |||
[Symbol(timeout)]: Timeout { | |||
_idleTimeout: -1, | |||
_idlePrev: null, | |||
_idleNext: null, | |||
_idleStart: 4823, | |||
_onTimeout: null, | |||
_timerArgs: undefined, | |||
_repeat: null, | |||
_destroyed: true, | |||
[Symbol(refed)]: false, | |||
[Symbol(asyncId)]: 221, | |||
[Symbol(triggerId)]: 218 | |||
}, | |||
[Symbol(kBuffer)]: null, | |||
[Symbol(kBufferCb)]: null, | |||
[Symbol(kBufferGen)]: null, | |||
[Symbol(kCapture)]: false, | |||
[Symbol(kBytesRead)]: 0, | |||
[Symbol(kBytesWritten)]: 0 | |||
}, | |||
_header: 'HTTP/1.1 200 OK\r\n' + | |||
'Content-Type: text/plain\r\n' + | |||
'Date: Tue, 03 Nov 2020 11:11:59 GMT\r\n' + | |||
'Connection: keep-alive\r\n' + | |||
'Keep-Alive: timeout=5\r\n' + | |||
'Transfer-Encoding: chunked\r\n' + | |||
'\r\n', | |||
_keepAliveTimeout: 5000, | |||
_onPendingData: [Function: bound updateOutgoingData], | |||
_sent100: false, | |||
_expect_continue: false, | |||
statusMessage: 'OK', | |||
statusCode: 200, | |||
[Symbol(kCapture)]: false, | |||
[Symbol(kNeedDrain)]: false, | |||
[Symbol(corked)]: 0, | |||
[Symbol(kOutHeaders)]: null | |||
} |
@ -0,0 +1,4 @@ | |||
#!/usr/bin/env node | |||
'use strict'; | |||
require('../dist/bin.js'); |
@ -0,0 +1,77 @@ | |||
#!/usr/bin/env node | |||
/* | |||
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com> | |||
Redistribution and use in source and binary forms, with or without | |||
modification, are permitted provided that the following conditions are met: | |||
* Redistributions of source code must retain the above copyright | |||
notice, this list of conditions and the following disclaimer. | |||
* Redistributions in binary form must reproduce the above copyright | |||
notice, this list of conditions and the following disclaimer in the | |||
documentation and/or other materials provided with the distribution. | |||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |||
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY | |||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | |||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | |||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | |||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF | |||
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |||
*/ | |||
/*jslint sloppy:true node:true */ | |||
var fs = require('fs'), | |||
path = require('path'), | |||
root = path.join(path.dirname(fs.realpathSync(__filename)), '..'), | |||
esprima = require('esprima'), | |||
escodegen = require(root), | |||
optionator = require('optionator')({ | |||
prepend: 'Usage: escodegen [options] file...', | |||
options: [ | |||
{ | |||
option: 'config', | |||
alias: 'c', | |||
type: 'String', | |||
description: 'configuration json for escodegen' | |||
} | |||
] | |||
}), | |||
args = optionator.parse(process.argv), | |||
files = args._, | |||
options, | |||
esprimaOptions = { | |||
raw: true, | |||
tokens: true, | |||
range: true, | |||
comment: true | |||
}; | |||
if (files.length === 0) { | |||
console.log(optionator.generateHelp()); | |||
process.exit(1); | |||
} | |||
if (args.config) { | |||
try { | |||
options = JSON.parse(fs.readFileSync(args.config, 'utf-8')); | |||
} catch (err) { | |||
console.error('Error parsing config: ', err); | |||
} | |||
} | |||
files.forEach(function (filename) { | |||
var content = fs.readFileSync(filename, 'utf-8'), | |||
syntax = esprima.parse(content, esprimaOptions); | |||
if (options.comment) { | |||
escodegen.attachComments(syntax, syntax.comments, syntax.tokens); | |||
} | |||
console.log(escodegen.generate(syntax, options)); | |||
}); | |||
/* vim: set sw=4 ts=4 et tw=80 : */ |
@ -0,0 +1,64 @@ | |||
#!/usr/bin/env node | |||
/* | |||
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com> | |||
Redistribution and use in source and binary forms, with or without | |||
modification, are permitted provided that the following conditions are met: | |||
* Redistributions of source code must retain the above copyright | |||
notice, this list of conditions and the following disclaimer. | |||
* Redistributions in binary form must reproduce the above copyright | |||
notice, this list of conditions and the following disclaimer in the | |||
documentation and/or other materials provided with the distribution. | |||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |||
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY | |||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | |||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | |||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | |||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF | |||
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |||
*/ | |||
/*jslint sloppy:true node:true */ | |||
var fs = require('fs'), | |||
path = require('path'), | |||
root = path.join(path.dirname(fs.realpathSync(__filename)), '..'), | |||
escodegen = require(root), | |||
optionator = require('optionator')({ | |||
prepend: 'Usage: esgenerate [options] file.json ...', | |||
options: [ | |||
{ | |||
option: 'config', | |||
alias: 'c', | |||
type: 'String', | |||
description: 'configuration json for escodegen' | |||
} | |||
] | |||
}), | |||
args = optionator.parse(process.argv), | |||
files = args._, | |||
options; | |||
if (files.length === 0) { | |||
console.log(optionator.generateHelp()); | |||
process.exit(1); | |||
} | |||
if (args.config) { | |||
try { | |||
options = JSON.parse(fs.readFileSync(args.config, 'utf-8')) | |||
} catch (err) { | |||
console.error('Error parsing config: ', err); | |||
} | |||
} | |||
files.forEach(function (filename) { | |||
var content = fs.readFileSync(filename, 'utf-8'); | |||
console.log(escodegen.generate(JSON.parse(content), options)); | |||
}); | |||
/* vim: set sw=4 ts=4 et tw=80 : */ |
@ -0,0 +1,139 @@ | |||
#!/usr/bin/env node | |||
/* | |||
Copyright JS Foundation and other contributors, https://js.foundation/ | |||
Redistribution and use in source and binary forms, with or without | |||
modification, are permitted provided that the following conditions are met: | |||
* Redistributions of source code must retain the above copyright | |||
notice, this list of conditions and the following disclaimer. | |||
* Redistributions in binary form must reproduce the above copyright | |||
notice, this list of conditions and the following disclaimer in the | |||
documentation and/or other materials provided with the distribution. | |||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |||
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY | |||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | |||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | |||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | |||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF | |||
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |||
*/ | |||
/*jslint sloppy:true node:true rhino:true */ | |||
var fs, esprima, fname, forceFile, content, options, syntax; | |||
if (typeof require === 'function') { | |||
fs = require('fs'); | |||
try { | |||
esprima = require('esprima'); | |||
} catch (e) { | |||
esprima = require('../'); | |||
} | |||
} else if (typeof load === 'function') { | |||
try { | |||
load('esprima.js'); | |||
} catch (e) { | |||
load('../esprima.js'); | |||
} | |||
} | |||
// Shims to Node.js objects when running under Rhino. | |||
if (typeof console === 'undefined' && typeof process === 'undefined') { | |||
console = { log: print }; | |||
fs = { readFileSync: readFile }; | |||
process = { argv: arguments, exit: quit }; | |||
process.argv.unshift('esparse.js'); | |||
process.argv.unshift('rhino'); | |||
} | |||
function showUsage() { | |||
console.log('Usage:'); | |||
console.log(' esparse [options] [file.js]'); | |||
console.log(); | |||
console.log('Available options:'); | |||
console.log(); | |||
console.log(' --comment Gather all line and block comments in an array'); | |||
console.log(' --loc Include line-column location info for each syntax node'); | |||
console.log(' --range Include index-based range for each syntax node'); | |||
console.log(' --raw Display the raw value of literals'); | |||
console.log(' --tokens List all tokens in an array'); | |||
console.log(' --tolerant Tolerate errors on a best-effort basis (experimental)'); | |||
console.log(' -v, --version Shows program version'); | |||
console.log(); | |||
process.exit(1); | |||
} | |||
options = {}; | |||
process.argv.splice(2).forEach(function (entry) { | |||
if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') { | |||
if (typeof fname === 'string') { | |||
console.log('Error: more than one input file.'); | |||
process.exit(1); | |||
} else { | |||
fname = entry; | |||
} | |||
} else if (entry === '-h' || entry === '--help') { | |||
showUsage(); | |||
} else if (entry === '-v' || entry === '--version') { | |||
console.log('ECMAScript Parser (using Esprima version', esprima.version, ')'); | |||
console.log(); | |||
process.exit(0); | |||
} else if (entry === '--comment') { | |||
options.comment = true; | |||
} else if (entry === '--loc') { | |||
options.loc = true; | |||
} else if (entry === '--range') { | |||
options.range = true; | |||
} else if (entry === '--raw') { | |||
options.raw = true; | |||
} else if (entry === '--tokens') { | |||
options.tokens = true; | |||
} else if (entry === '--tolerant') { | |||
options.tolerant = true; | |||
} else if (entry === '--') { | |||
forceFile = true; | |||
} else { | |||
console.log('Error: unknown option ' + entry + '.'); | |||
process.exit(1); | |||
} | |||
}); | |||
// Special handling for regular expression literal since we need to | |||
// convert it to a string literal, otherwise it will be decoded | |||
// as object "{}" and the regular expression would be lost. | |||
function adjustRegexLiteral(key, value) { | |||
if (key === 'value' && value instanceof RegExp) { | |||
value = value.toString(); | |||
} | |||
return value; | |||
} | |||
function run(content) { | |||
syntax = esprima.parse(content, options); | |||
console.log(JSON.stringify(syntax, adjustRegexLiteral, 4)); | |||
} | |||
try { | |||
if (fname && (fname !== '-' || forceFile)) { | |||
run(fs.readFileSync(fname, 'utf-8')); | |||
} else { | |||
var content = ''; | |||
process.stdin.resume(); | |||
process.stdin.on('data', function(chunk) { | |||
content += chunk; | |||
}); | |||
process.stdin.on('end', function() { | |||
run(content); | |||
}); | |||
} | |||
} catch (e) { | |||
console.log('Error: ' + e.message); | |||
process.exit(1); | |||
} |
@ -0,0 +1,236 @@ | |||
#!/usr/bin/env node | |||
/* | |||
Copyright JS Foundation and other contributors, https://js.foundation/ | |||
Redistribution and use in source and binary forms, with or without | |||
modification, are permitted provided that the following conditions are met: | |||
* Redistributions of source code must retain the above copyright | |||
notice, this list of conditions and the following disclaimer. | |||
* Redistributions in binary form must reproduce the above copyright | |||
notice, this list of conditions and the following disclaimer in the | |||
documentation and/or other materials provided with the distribution. | |||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | |||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | |||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | |||
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY | |||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | |||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | |||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | |||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | |||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF | |||
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |||
*/ | |||
/*jslint sloppy:true plusplus:true node:true rhino:true */ | |||
/*global phantom:true */ | |||
var fs, system, esprima, options, fnames, forceFile, count; | |||
if (typeof esprima === 'undefined') { | |||
// PhantomJS can only require() relative files | |||
if (typeof phantom === 'object') { | |||
fs = require('fs'); | |||
system = require('system'); | |||
esprima = require('./esprima'); | |||
} else if (typeof require === 'function') { | |||
fs = require('fs'); | |||
try { | |||
esprima = require('esprima'); | |||
} catch (e) { | |||
esprima = require('../'); | |||
} | |||
} else if (typeof load === 'function') { | |||
try { | |||
load('esprima.js'); | |||
} catch (e) { | |||
load('../esprima.js'); | |||
} | |||
} | |||
} | |||
// Shims to Node.js objects when running under PhantomJS 1.7+. | |||
if (typeof phantom === 'object') { | |||
fs.readFileSync = fs.read; | |||
process = { | |||
argv: [].slice.call(system.args), | |||
exit: phantom.exit, | |||
on: function (evt, callback) { | |||
callback(); | |||
} | |||
}; | |||
process.argv.unshift('phantomjs'); | |||
} | |||
// Shims to Node.js objects when running under Rhino. | |||
if (typeof console === 'undefined' && typeof process === 'undefined') { | |||
console = { log: print }; | |||
fs = { readFileSync: readFile }; | |||
process = { | |||
argv: arguments, | |||
exit: quit, | |||
on: function (evt, callback) { | |||
callback(); | |||
} | |||
}; | |||
process.argv.unshift('esvalidate.js'); | |||
process.argv.unshift('rhino'); | |||
} | |||
function showUsage() { | |||
console.log('Usage:'); | |||
console.log(' esvalidate [options] [file.js...]'); | |||
console.log(); | |||
console.log('Available options:'); | |||
console.log(); | |||
console.log(' --format=type Set the report format, plain (default) or junit'); | |||
console.log(' -v, --version Print program version'); | |||
console.log(); | |||
process.exit(1); | |||
} | |||
options = { | |||
format: 'plain' | |||
}; | |||
fnames = []; | |||
process.argv.splice(2).forEach(function (entry) { | |||
if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') { | |||
fnames.push(entry); | |||
} else if (entry === '-h' || entry === '--help') { | |||
showUsage(); | |||
} else if (entry === '-v' || entry === '--version') { | |||
console.log('ECMAScript Validator (using Esprima version', esprima.version, ')'); | |||
console.log(); | |||
process.exit(0); | |||
} else if (entry.slice(0, 9) === '--format=') { | |||
options.format = entry.slice(9); | |||
if (options.format !== 'plain' && options.format !== 'junit') { | |||
console.log('Error: unknown report format ' + options.format + '.'); | |||
process.exit(1); | |||
} | |||
} else if (entry === '--') { | |||
forceFile = true; | |||
} else { | |||
console.log('Error: unknown option ' + entry + '.'); | |||
process.exit(1); | |||
} | |||
}); | |||
if (fnames.length === 0) { | |||
fnames.push(''); | |||
} | |||
if (options.format === 'junit') { | |||
console.log('<?xml version="1.0" encoding="UTF-8"?>'); | |||
console.log('<testsuites>'); | |||
} | |||
count = 0; | |||
function run(fname, content) { | |||
var timestamp, syntax, name; | |||
try { | |||
if (typeof content !== 'string') { | |||
throw content; | |||
} | |||
if (content[0] === '#' && content[1] === '!') { | |||
content = '//' + content.substr(2, content.length); | |||
} | |||
timestamp = Date.now(); | |||
syntax = esprima.parse(content, { tolerant: true }); | |||
if (options.format === 'junit') { | |||
name = fname; | |||
if (name.lastIndexOf('/') >= 0) { | |||
name = name.slice(name.lastIndexOf('/') + 1); | |||
} | |||
console.log('<testsuite name="' + fname + '" errors="0" ' + | |||
' failures="' + syntax.errors.length + '" ' + | |||
' tests="' + syntax.errors.length + '" ' + | |||
' time="' + Math.round((Date.now() - timestamp) / 1000) + | |||
'">'); | |||
syntax.errors.forEach(function (error) { | |||
var msg = error.message; | |||
msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); | |||
console.log(' <testcase name="Line ' + error.lineNumber + ': ' + msg + '" ' + | |||
' time="0">'); | |||
console.log(' <error type="SyntaxError" message="' + error.message + '">' + | |||
error.message + '(' + name + ':' + error.lineNumber + ')' + | |||
'</error>'); | |||
console.log(' </testcase>'); | |||
}); | |||
console.log('</testsuite>'); | |||
} else if (options.format === 'plain') { | |||
syntax.errors.forEach(function (error) { | |||
var msg = error.message; | |||
msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); | |||
msg = fname + ':' + error.lineNumber + ': ' + msg; | |||
console.log(msg); | |||
++count; | |||
}); | |||
} | |||
} catch (e) { | |||
++count; | |||
if (options.format === 'junit') { | |||
console.log('<testsuite name="' + fname + '" errors="1" failures="0" tests="1" ' + | |||
' time="' + Math.round((Date.now() - timestamp) / 1000) + '">'); | |||
console.log(' <testcase name="' + e.message + '" ' + ' time="0">'); | |||
console.log(' <error type="ParseError" message="' + e.message + '">' + | |||
e.message + '(' + fname + ((e.lineNumber) ? ':' + e.lineNumber : '') + | |||
')</error>'); | |||
console.log(' </testcase>'); | |||
console.log('</testsuite>'); | |||
} else { | |||
console.log(fname + ':' + e.lineNumber + ': ' + e.message.replace(/^Line\ [0-9]*\:\ /, '')); | |||
} | |||
} | |||
} | |||
fnames.forEach(function (fname) { | |||
var content = ''; | |||
try { | |||
if (fname && (fname !== '-' || forceFile)) { | |||
content = fs.readFileSync(fname, 'utf-8'); | |||
} else { | |||
fname = ''; | |||
process.stdin.resume(); | |||
process.stdin.on('data', function(chunk) { | |||
content += chunk; | |||
}); | |||
process.stdin.on('end', function() { | |||
run(fname, content); | |||
}); | |||
return; | |||
} | |||
} catch (e) { | |||
content = e; | |||
} | |||
run(fname, content); | |||
}); | |||
process.on('exit', function () { | |||
if (options.format === 'junit') { | |||
console.log('</testsuites>'); | |||
} | |||
if (count > 0) { | |||
process.exit(1); | |||
} | |||
if (count === 0 && typeof phantom === 'object') { | |||
process.exit(0); | |||
} | |||
}); |
@ -0,0 +1,148 @@ | |||
#!/usr/bin/env node | |||
(function() { | |||
var fs = require('fs'); | |||
var he = require('../he.js'); | |||
var strings = process.argv.splice(2); | |||
var stdin = process.stdin; | |||
var data; | |||
var timeout; | |||
var action; | |||
var options = {}; | |||
var log = console.log; | |||
var main = function() { | |||
var option = strings[0]; | |||
var count = 0; | |||
if (/^(?:-h|--help|undefined)$/.test(option)) { | |||
log( | |||
'he v%s - https://mths.be/he', | |||
he.version | |||
); | |||
log([ | |||
'\nUsage:\n', | |||
'\the [--escape] string', | |||
'\the [--encode] [--use-named-refs] [--everything] [--allow-unsafe] [--decimal] string', | |||
'\the [--decode] [--attribute] [--strict] string', | |||
'\the [-v | --version]', | |||
'\the [-h | --help]', | |||
'\nExamples:\n', | |||
'\the --escape \\<img\\ src\\=\\\'x\\\'\\ onerror\\=\\"prompt\\(1\\)\\"\\>', | |||
'\techo \'© 𝌆\' | he --decode' | |||
].join('\n')); | |||
return process.exit(option ? 0 : 1); | |||
} | |||
if (/^(?:-v|--version)$/.test(option)) { | |||
log('v%s', he.version); | |||
return process.exit(0); | |||
} | |||
strings.forEach(function(string) { | |||
// Process options | |||
if (string == '--escape') { | |||
action = 'escape'; | |||
return; | |||
} | |||
if (string == '--encode') { | |||
action = 'encode'; | |||
return; | |||
} | |||
if (string == '--use-named-refs') { | |||
action = 'encode'; | |||
options.useNamedReferences = true; | |||
return; | |||
} | |||
if (string == '--everything') { | |||
action = 'encode'; | |||
options.encodeEverything = true; | |||
return; | |||
} | |||
if (string == '--allow-unsafe') { | |||
action = 'encode'; | |||
options.allowUnsafeSymbols = true; | |||
return; | |||
} | |||
if (string == '--decimal') { | |||
action = 'encode'; | |||
options.decimal = true; | |||
return; | |||
} | |||
if (string == '--decode') { | |||
action = 'decode'; | |||
return; | |||
} | |||
if (string == '--attribute') { | |||
action = 'decode'; | |||
options.isAttributeValue = true; | |||
return; | |||
} | |||
if (string == '--strict') { | |||
action = 'decode'; | |||
options.strict = true; | |||
return; | |||
} | |||
// Process string(s) | |||
var result; | |||
if (!action) { | |||
log('Error: he requires at least one option and a string argument.'); | |||
log('Try `he --help` for more information.'); | |||
return process.exit(1); | |||
} | |||
try { | |||
result = he[action](string, options); | |||
log(result); | |||
count++; | |||
} catch(error) { | |||
log(error.message + '\n'); | |||
log('Error: failed to %s.', action); | |||
log('If you think this is a bug in he, please report it:'); | |||
log('https://github.com/mathiasbynens/he/issues/new'); | |||
log( | |||
'\nStack trace using he@%s:\n', | |||
he.version | |||
); | |||
log(error.stack); | |||
return process.exit(1); | |||
} | |||
}); | |||
if (!count) { | |||
log('Error: he requires a string argument.'); | |||
log('Try `he --help` for more information.'); | |||
return process.exit(1); | |||
} | |||
// Return with exit status 0 outside of the `forEach` loop, in case | |||
// multiple strings were passed in. | |||
return process.exit(0); | |||
}; | |||
if (stdin.isTTY) { | |||
// handle shell arguments | |||
main(); | |||
} else { | |||
// Either the script is called from within a non-TTY context, or `stdin` | |||
// content is being piped in. | |||
if (!process.stdout.isTTY) { | |||
// The script was called from a non-TTY context. This is a rather uncommon | |||
// use case we don’t actively support. However, we don’t want the script | |||
// to wait forever in such cases, so… | |||
timeout = setTimeout(function() { | |||
// …if no piped data arrived after a whole minute, handle shell | |||
// arguments instead. | |||
main(); | |||
}, 60000); | |||
} | |||
data = ''; | |||
stdin.on('data', function(chunk) { | |||
clearTimeout(timeout); | |||
data += chunk; | |||
}); | |||
stdin.on('end', function() { | |||
strings.push(data.trim()); | |||
main(); | |||
}); | |||
stdin.resume(); | |||
} | |||
}()); |
@ -0,0 +1,8 @@ | |||
#!/usr/bin/env node | |||
var mime = require('./mime.js'); | |||
var file = process.argv[2]; | |||
var type = mime.lookup(file); | |||
process.stdout.write(type + '\n'); | |||
@ -0,0 +1,243 @@ | |||
#!/usr/bin/env node | |||
// -*- mode: js -*- | |||
// vim: set filetype=javascript : | |||
// Copyright 2018 Joyent, Inc. All rights reserved. | |||
var dashdash = require('dashdash'); | |||
var sshpk = require('../lib/index'); | |||
var fs = require('fs'); | |||
var path = require('path'); | |||
var tty = require('tty'); | |||
var readline = require('readline'); | |||
var getPassword = require('getpass').getPass; | |||
var options = [ | |||
{ | |||
names: ['outformat', 't'], | |||
type: 'string', | |||
help: 'Output format' | |||
}, | |||
{ | |||
names: ['informat', 'T'], | |||
type: 'string', | |||
help: 'Input format' | |||
}, | |||
{ | |||
names: ['file', 'f'], | |||
type: 'string', | |||
help: 'Input file name (default stdin)' | |||
}, | |||
{ | |||
names: ['out', 'o'], | |||
type: 'string', | |||
help: 'Output file name (default stdout)' | |||
}, | |||
{ | |||
names: ['private', 'p'], | |||
type: 'bool', | |||
help: 'Produce a private key as output' | |||
}, | |||
{ | |||
names: ['derive', 'd'], | |||
type: 'string', | |||
help: 'Output a new key derived from this one, with given algo' | |||
}, | |||
{ | |||
names: ['identify', 'i'], | |||
type: 'bool', | |||
help: 'Print key metadata instead of converting' | |||
}, | |||
{ | |||
names: ['fingerprint', 'F'], | |||
type: 'bool', | |||
help: 'Output key fingerprint' | |||
}, | |||
{ | |||
names: ['hash', 'H'], | |||
type: 'string', | |||
help: 'Hash function to use for key fingeprint with -F' | |||
}, | |||
{ | |||
names: ['spki', 's'], | |||
type: 'bool', | |||
help: 'With -F, generates an SPKI fingerprint instead of SSH' | |||
}, | |||
{ | |||
names: ['comment', 'c'], | |||
type: 'string', | |||
help: 'Set key comment, if output format supports' | |||
}, | |||
{ | |||
names: ['help', 'h'], | |||
type: 'bool', | |||
help: 'Shows this help text' | |||
} | |||
]; | |||
if (require.main === module) { | |||
var parser = dashdash.createParser({ | |||
options: options | |||
}); | |||
try { | |||
var opts = parser.parse(process.argv); | |||
} catch (e) { | |||
console.error('sshpk-conv: error: %s', e.message); | |||
process.exit(1); | |||
} | |||
if (opts.help || opts._args.length > 1) { | |||
var help = parser.help({}).trimRight(); | |||
console.error('sshpk-conv: converts between SSH key formats\n'); | |||
console.error(help); | |||
console.error('\navailable key formats:'); | |||
console.error(' - pem, pkcs1 eg id_rsa'); | |||
console.error(' - ssh eg id_rsa.pub'); | |||
console.error(' - pkcs8 format you want for openssl'); | |||
console.error(' - openssh like output of ssh-keygen -o'); | |||
console.error(' - rfc4253 raw OpenSSH wire format'); | |||
console.error(' - dnssec dnssec-keygen format'); | |||
console.error(' - putty PuTTY ppk format'); | |||
console.error('\navailable fingerprint formats:'); | |||
console.error(' - hex colon-separated hex for SSH'); | |||
console.error(' straight hex for SPKI'); | |||
console.error(' - base64 SHA256:* format from OpenSSH'); | |||
process.exit(1); | |||
} | |||
/* | |||
* Key derivation can only be done on private keys, so use of the -d | |||
* option necessarily implies -p. | |||
*/ | |||
if (opts.derive) | |||
opts.private = true; | |||
var inFile = process.stdin; | |||
var inFileName = 'stdin'; | |||
var inFilePath; | |||
if (opts.file) { | |||
inFilePath = opts.file; | |||
} else if (opts._args.length === 1) { | |||
inFilePath = opts._args[0]; | |||
} | |||
if (inFilePath) | |||
inFileName = path.basename(inFilePath); | |||
try { | |||
if (inFilePath) { | |||
fs.accessSync(inFilePath, fs.R_OK); | |||
inFile = fs.createReadStream(inFilePath); | |||
} | |||
} catch (e) { | |||
ifError(e, 'error opening input file'); | |||
} | |||
var outFile = process.stdout; | |||
try { | |||
if (opts.out && !opts.identify) { | |||
fs.accessSync(path.dirname(opts.out), fs.W_OK); | |||
outFile = fs.createWriteStream(opts.out); | |||
} | |||
} catch (e) { | |||
ifError(e, 'error opening output file'); | |||
} | |||
var bufs = []; | |||
inFile.on('readable', function () { | |||
var data; | |||
while ((data = inFile.read())) | |||
bufs.push(data); | |||
}); | |||
var parseOpts = {}; | |||
parseOpts.filename = inFileName; | |||
inFile.on('end', function processKey() { | |||
var buf = Buffer.concat(bufs); | |||
var fmt = 'auto'; | |||
if (opts.informat) | |||
fmt = opts.informat; | |||
var f = sshpk.parseKey; | |||
if (opts.private) | |||
f = sshpk.parsePrivateKey; | |||
try { | |||
var key = f(buf, fmt, parseOpts); | |||
} catch (e) { | |||
if (e.name === 'KeyEncryptedError') { | |||
getPassword(function (err, pw) { | |||
if (err) | |||
ifError(err); | |||
parseOpts.passphrase = pw; | |||
processKey(); | |||
}); | |||
return; | |||
} | |||
ifError(e); | |||
} | |||
if (opts.derive) | |||
key = key.derive(opts.derive); | |||
if (opts.comment) | |||
key.comment = opts.comment; | |||
if (opts.identify) { | |||
var kind = 'public'; | |||
if (sshpk.PrivateKey.isPrivateKey(key)) | |||
kind = 'private'; | |||
console.log('%s: a %d bit %s %s key', inFileName, | |||
key.size, key.type.toUpperCase(), kind); | |||
if (key.type === 'ecdsa') | |||
console.log('ECDSA curve: %s', key.curve); | |||
if (key.comment) | |||
console.log('Comment: %s', key.comment); | |||
console.log('SHA256 fingerprint: ' + | |||
key.fingerprint('sha256').toString()); | |||
console.log('MD5 fingerprint: ' + | |||
key.fingerprint('md5').toString()); | |||
console.log('SPKI-SHA256 fingerprint: ' + | |||
key.fingerprint('sha256', 'spki').toString()); | |||
process.exit(0); | |||
return; | |||
} | |||
if (opts.fingerprint) { | |||
var hash = opts.hash; | |||
var type = opts.spki ? 'spki' : 'ssh'; | |||
var format = opts.outformat; | |||
var fp = key.fingerprint(hash, type).toString(format); | |||
outFile.write(fp); | |||
outFile.write('\n'); | |||
outFile.once('drain', function () { | |||
process.exit(0); | |||
}); | |||
return; | |||
} | |||
fmt = undefined; | |||
if (opts.outformat) | |||
fmt = opts.outformat; | |||
outFile.write(key.toBuffer(fmt)); | |||
if (fmt === 'ssh' || | |||
(!opts.private && fmt === undefined)) | |||
outFile.write('\n'); | |||
outFile.once('drain', function () { | |||
process.exit(0); | |||
}); | |||
}); | |||
} | |||
function ifError(e, txt) { | |||
if (txt) | |||
txt = txt + ': '; | |||
else | |||
txt = ''; | |||
console.error('sshpk-conv: ' + txt + e.name + ': ' + e.message); | |||
if (process.env['DEBUG'] || process.env['V']) { | |||
console.error(e.stack); | |||
if (e.innerErr) | |||
console.error(e.innerErr.stack); | |||
} | |||
process.exit(1); | |||
} |
@ -0,0 +1,191 @@ | |||
#!/usr/bin/env node | |||
// -*- mode: js -*- | |||
// vim: set filetype=javascript : | |||
// Copyright 2015 Joyent, Inc. All rights reserved. | |||
var dashdash = require('dashdash'); | |||
var sshpk = require('../lib/index'); | |||
var fs = require('fs'); | |||
var path = require('path'); | |||
var getPassword = require('getpass').getPass; | |||
var options = [ | |||
{ | |||
names: ['hash', 'H'], | |||
type: 'string', | |||
help: 'Hash algorithm (sha1, sha256, sha384, sha512)' | |||
}, | |||
{ | |||
names: ['verbose', 'v'], | |||
type: 'bool', | |||
help: 'Display verbose info about key and hash used' | |||
}, | |||
{ | |||
names: ['identity', 'i'], | |||
type: 'string', | |||
help: 'Path to key to use' | |||
}, | |||
{ | |||
names: ['file', 'f'], | |||
type: 'string', | |||
help: 'Input filename' | |||
}, | |||
{ | |||
names: ['out', 'o'], | |||
type: 'string', | |||
help: 'Output filename' | |||
}, | |||
{ | |||
names: ['format', 't'], | |||
type: 'string', | |||
help: 'Signature format (asn1, ssh, raw)' | |||
}, | |||
{ | |||
names: ['binary', 'b'], | |||
type: 'bool', | |||
help: 'Output raw binary instead of base64' | |||
}, | |||
{ | |||
names: ['help', 'h'], | |||
type: 'bool', | |||
help: 'Shows this help text' | |||
} | |||
]; | |||
var parseOpts = {}; | |||
if (require.main === module) { | |||
var parser = dashdash.createParser({ | |||
options: options | |||
}); | |||
try { | |||
var opts = parser.parse(process.argv); | |||
} catch (e) { | |||
console.error('sshpk-sign: error: %s', e.message); | |||
process.exit(1); | |||
} | |||
if (opts.help || opts._args.length > 1) { | |||
var help = parser.help({}).trimRight(); | |||
console.error('sshpk-sign: sign data using an SSH key\n'); | |||
console.error(help); | |||
process.exit(1); | |||
} | |||
if (!opts.identity) { | |||
var help = parser.help({}).trimRight(); | |||
console.error('sshpk-sign: the -i or --identity option ' + | |||
'is required\n'); | |||
console.error(help); | |||
process.exit(1); | |||
} | |||
var keyData = fs.readFileSync(opts.identity); | |||
parseOpts.filename = opts.identity; | |||
run(); | |||
} | |||
function run() { | |||
var key; | |||
try { | |||
key = sshpk.parsePrivateKey(keyData, 'auto', parseOpts); | |||
} catch (e) { | |||
if (e.name === 'KeyEncryptedError') { | |||
getPassword(function (err, pw) { | |||
parseOpts.passphrase = pw; | |||
run(); | |||
}); | |||
return; | |||
} | |||
console.error('sshpk-sign: error loading private key "' + | |||
opts.identity + '": ' + e.name + ': ' + e.message); | |||
process.exit(1); | |||
} | |||
var hash = opts.hash || key.defaultHashAlgorithm(); | |||
var signer; | |||
try { | |||
signer = key.createSign(hash); | |||
} catch (e) { | |||
console.error('sshpk-sign: error creating signer: ' + | |||
e.name + ': ' + e.message); | |||
process.exit(1); | |||
} | |||
if (opts.verbose) { | |||
console.error('sshpk-sign: using %s-%s with a %d bit key', | |||
key.type, hash, key.size); | |||
} | |||
var inFile = process.stdin; | |||
var inFileName = 'stdin'; | |||
var inFilePath; | |||
if (opts.file) { | |||
inFilePath = opts.file; | |||
} else if (opts._args.length === 1) { | |||
inFilePath = opts._args[0]; | |||
} | |||
if (inFilePath) | |||
inFileName = path.basename(inFilePath); | |||
try { | |||
if (inFilePath) { | |||
fs.accessSync(inFilePath, fs.R_OK); | |||
inFile = fs.createReadStream(inFilePath); | |||
} | |||
} catch (e) { | |||
console.error('sshpk-sign: error opening input file' + | |||
': ' + e.name + ': ' + e.message); | |||
process.exit(1); | |||
} | |||
var outFile = process.stdout; | |||
try { | |||
if (opts.out && !opts.identify) { | |||
fs.accessSync(path.dirname(opts.out), fs.W_OK); | |||
outFile = fs.createWriteStream(opts.out); | |||
} | |||
} catch (e) { | |||
console.error('sshpk-sign: error opening output file' + | |||
': ' + e.name + ': ' + e.message); | |||
process.exit(1); | |||
} | |||
inFile.pipe(signer); | |||
inFile.on('end', function () { | |||
var sig; | |||
try { | |||
sig = signer.sign(); | |||
} catch (e) { | |||
console.error('sshpk-sign: error signing data: ' + | |||
e.name + ': ' + e.message); | |||
process.exit(1); | |||
} | |||
var fmt = opts.format || 'asn1'; | |||
var output; | |||
try { | |||
output = sig.toBuffer(fmt); | |||
if (!opts.binary) | |||
output = output.toString('base64'); | |||
} catch (e) { | |||
console.error('sshpk-sign: error converting signature' + | |||
' to ' + fmt + ' format: ' + e.name + ': ' + | |||
e.message); | |||
process.exit(1); | |||
} | |||
outFile.write(output); | |||
if (!opts.binary) | |||
outFile.write('\n'); | |||
outFile.once('drain', function () { | |||
process.exit(0); | |||
}); | |||
}); | |||
} |
@ -0,0 +1,167 @@ | |||
#!/usr/bin/env node | |||
// -*- mode: js -*- | |||
// vim: set filetype=javascript : | |||
// Copyright 2015 Joyent, Inc. All rights reserved. | |||
var dashdash = require('dashdash'); | |||
var sshpk = require('../lib/index'); | |||
var fs = require('fs'); | |||
var path = require('path'); | |||
var Buffer = require('safer-buffer').Buffer; | |||
var options = [ | |||
{ | |||
names: ['hash', 'H'], | |||
type: 'string', | |||
help: 'Hash algorithm (sha1, sha256, sha384, sha512)' | |||
}, | |||
{ | |||
names: ['verbose', 'v'], | |||
type: 'bool', | |||
help: 'Display verbose info about key and hash used' | |||
}, | |||
{ | |||
names: ['identity', 'i'], | |||
type: 'string', | |||
help: 'Path to (public) key to use' | |||
}, | |||
{ | |||
names: ['file', 'f'], | |||
type: 'string', | |||
help: 'Input filename' | |||
}, | |||
{ | |||
names: ['format', 't'], | |||
type: 'string', | |||
help: 'Signature format (asn1, ssh, raw)' | |||
}, | |||
{ | |||
names: ['signature', 's'], | |||
type: 'string', | |||
help: 'base64-encoded signature data' | |||
}, | |||
{ | |||
names: ['help', 'h'], | |||
type: 'bool', | |||
help: 'Shows this help text' | |||
} | |||
]; | |||
if (require.main === module) { | |||
var parser = dashdash.createParser({ | |||
options: options | |||
}); | |||
try { | |||
var opts = parser.parse(process.argv); | |||
} catch (e) { | |||
console.error('sshpk-verify: error: %s', e.message); | |||
process.exit(3); | |||
} | |||
if (opts.help || opts._args.length > 1) { | |||
var help = parser.help({}).trimRight(); | |||
console.error('sshpk-verify: sign data using an SSH key\n'); | |||
console.error(help); | |||
process.exit(3); | |||
} | |||
if (!opts.identity) { | |||
var help = parser.help({}).trimRight(); | |||
console.error('sshpk-verify: the -i or --identity option ' + | |||
'is required\n'); | |||
console.error(help); | |||
process.exit(3); | |||
} | |||
if (!opts.signature) { | |||
var help = parser.help({}).trimRight(); | |||
console.error('sshpk-verify: the -s or --signature option ' + | |||
'is required\n'); | |||
console.error(help); | |||
process.exit(3); | |||
} | |||
var keyData = fs.readFileSync(opts.identity); | |||
var key; | |||
try { | |||
key = sshpk.parseKey(keyData); | |||
} catch (e) { | |||
console.error('sshpk-verify: error loading key "' + | |||
opts.identity + '": ' + e.name + ': ' + e.message); | |||
process.exit(2); | |||
} | |||
var fmt = opts.format || 'asn1'; | |||
var sigData = Buffer.from(opts.signature, 'base64'); | |||
var sig; | |||
try { | |||
sig = sshpk.parseSignature(sigData, key.type, fmt); | |||
} catch (e) { | |||
console.error('sshpk-verify: error parsing signature: ' + | |||
e.name + ': ' + e.message); | |||
process.exit(2); | |||
} | |||
var hash = opts.hash || key.defaultHashAlgorithm(); | |||
var verifier; | |||
try { | |||
verifier = key.createVerify(hash); | |||
} catch (e) { | |||
console.error('sshpk-verify: error creating verifier: ' + | |||
e.name + ': ' + e.message); | |||
process.exit(2); | |||
} | |||
if (opts.verbose) { | |||
console.error('sshpk-verify: using %s-%s with a %d bit key', | |||
key.type, hash, key.size); | |||
} | |||
var inFile = process.stdin; | |||
var inFileName = 'stdin'; | |||
var inFilePath; | |||
if (opts.file) { | |||
inFilePath = opts.file; | |||
} else if (opts._args.length === 1) { | |||
inFilePath = opts._args[0]; | |||
} | |||
if (inFilePath) | |||
inFileName = path.basename(inFilePath); | |||
try { | |||
if (inFilePath) { | |||
fs.accessSync(inFilePath, fs.R_OK); | |||
inFile = fs.createReadStream(inFilePath); | |||
} | |||
} catch (e) { | |||
console.error('sshpk-verify: error opening input file' + | |||
': ' + e.name + ': ' + e.message); | |||
process.exit(2); | |||
} | |||
inFile.pipe(verifier); | |||
inFile.on('end', function () { | |||
var ret; | |||
try { | |||
ret = verifier.verify(sig); | |||
} catch (e) { | |||
console.error('sshpk-verify: error verifying data: ' + | |||
e.name + ': ' + e.message); | |||
process.exit(1); | |||
} | |||
if (ret) { | |||
console.error('OK'); | |||
process.exit(0); | |||
} | |||
console.error('NOT OK'); | |||
process.exit(1); | |||
}); | |||
} |
@ -0,0 +1,65 @@ | |||
#!/usr/bin/env node | |||
var assert = require('assert'); | |||
function usage() { | |||
console.log('Usage:'); | |||
console.log(' uuid'); | |||
console.log(' uuid v1'); | |||
console.log(' uuid v3 <name> <namespace uuid>'); | |||
console.log(' uuid v4'); | |||
console.log(' uuid v5 <name> <namespace uuid>'); | |||
console.log(' uuid --help'); | |||
console.log('\nNote: <namespace uuid> may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC4122'); | |||
} | |||
var args = process.argv.slice(2); | |||
if (args.indexOf('--help') >= 0) { | |||
usage(); | |||
process.exit(0); | |||
} | |||
var version = args.shift() || 'v4'; | |||
switch (version) { | |||
case 'v1': | |||
var uuidV1 = require('../v1'); | |||
console.log(uuidV1()); | |||
break; | |||
case 'v3': | |||
var uuidV3 = require('../v3'); | |||
var name = args.shift(); | |||
var namespace = args.shift(); | |||
assert(name != null, 'v3 name not specified'); | |||
assert(namespace != null, 'v3 namespace not specified'); | |||
if (namespace == 'URL') namespace = uuidV3.URL; | |||
if (namespace == 'DNS') namespace = uuidV3.DNS; | |||
console.log(uuidV3(name, namespace)); | |||
break; | |||
case 'v4': | |||
var uuidV4 = require('../v4'); | |||
console.log(uuidV4()); | |||
break; | |||
case 'v5': | |||
var uuidV5 = require('../v5'); | |||
var name = args.shift(); | |||
var namespace = args.shift(); | |||
assert(name != null, 'v5 name not specified'); | |||
assert(namespace != null, 'v5 namespace not specified'); | |||
if (namespace == 'URL') namespace = uuidV5.URL; | |||
if (namespace == 'DNS') namespace = uuidV5.DNS; | |||
console.log(uuidV5(name, namespace)); | |||
break; | |||
default: | |||
usage(); | |||
process.exit(1); | |||
} |
@ -0,0 +1,45 @@ | |||
## 2.0.5 | |||
- Use a lookup string in atobLookup and btoaLookup (@GiovanniFrigo in #38) | |||
- Dependency updates | |||
## 2.0.4 | |||
- Dependency updates | |||
## 2.0.3 | |||
- Use standard wording for BSD-3-Clause license (@PhilippWendler) | |||
## 2.0.2 | |||
- Correct license in `package.json` (@Haegin) | |||
## 2.0.1 | |||
- Add TypeScript type definitions, thanks to @LinusU | |||
## 2.0.0 | |||
Modernization updates thanks to @TimothyGu: | |||
- Use jsdom's eslint config, remove jscs | |||
- Move syntax to ES6 | |||
- Remove Babel | |||
- Via: https://github.com/jsdom/abab/pull/26 | |||
## 1.0.4 | |||
- Added license file | |||
## 1.0.3 | |||
- Replaced `let` with `var` in `lib/btoa.js` | |||
- Follow up from `1.0.2` | |||
- Resolves https://github.com/jsdom/abab/issues/18 | |||
## 1.0.2 | |||
- Replaced `const` with `var` in `index.js` | |||
- Allows use of `abab` in the browser without a transpilation step | |||
- Resolves https://github.com/jsdom/abab/issues/15 |
@ -0,0 +1,13 @@ | |||
Copyright © 2019 W3C and Jeff Carpenter \<jeffcarp@chromium.org\> | |||
Both the original source code and new contributions in this repository are released under the [3-Clause BSD license](https://opensource.org/licenses/BSD-3-Clause). | |||
# The 3-Clause BSD License | |||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: | |||
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. | |||
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. | |||
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. | |||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
@ -0,0 +1,51 @@ | |||
# abab [![npm version](https://badge.fury.io/js/abab.svg)](https://www.npmjs.com/package/abab) [![Build Status](https://travis-ci.org/jsdom/abab.svg?branch=master)](https://travis-ci.org/jsdom/abab) | |||
A JavaScript module that implements `window.atob` and `window.btoa` according the forgiving-base64 algorithm in the [Infra Standard](https://infra.spec.whatwg.org/#forgiving-base64). The original code was forked from [w3c/web-platform-tests](https://github.com/w3c/web-platform-tests/blob/master/html/webappapis/atob/base64.html). | |||
Compatibility: Node.js version 3+ and all major browsers. | |||
Install with `npm`: | |||
```sh | |||
npm install abab | |||
``` | |||
## API | |||
### `btoa` (base64 encode) | |||
```js | |||
const { btoa } = require('abab'); | |||
btoa('Hello, world!'); // 'SGVsbG8sIHdvcmxkIQ==' | |||
``` | |||
### `atob` (base64 decode) | |||
```js | |||
const { atob } = require('abab'); | |||
atob('SGVsbG8sIHdvcmxkIQ=='); // 'Hello, world!' | |||
``` | |||
#### Valid characters | |||
[Per the spec](https://html.spec.whatwg.org/multipage/webappapis.html#atob:dom-windowbase64-btoa-3), `btoa` will accept strings "containing only characters in the range `U+0000` to `U+00FF`." If passed a string with characters above `U+00FF`, `btoa` will return `null`. If `atob` is passed a string that is not base64-valid, it will also return `null`. In both cases when `null` is returned, the spec calls for throwing a `DOMException` of type `InvalidCharacterError`. | |||
## Browsers | |||
If you want to include just one of the methods to save bytes in your client-side code, you can `require` the desired module directly. | |||
```js | |||
const atob = require('abab/lib/atob'); | |||
const btoa = require('abab/lib/btoa'); | |||
``` | |||
## Development | |||
If you're **submitting a PR** or **deploying to npm**, please use the [checklists in CONTRIBUTING.md](CONTRIBUTING.md#checklists). | |||
## Remembering what `atob` and `btoa` stand for | |||
Base64 comes from IETF [RFC 4648](https://tools.ietf.org/html/rfc4648#section-4) (2006). | |||
- **`btoa`**, the encoder function, stands for **binary** to **ASCII**, meaning it converts any binary input into a subset of **ASCII** (Base64). | |||
- **`atob`**, the decoder function, converts **ASCII** (or Base64) to its original **binary** format. |
@ -0,0 +1,2 @@ | |||
export function atob(encodedData: string): string | null | |||
export function btoa(stringToEncode: string): string | null |
@ -0,0 +1,9 @@ | |||
"use strict"; | |||
const atob = require("./lib/atob"); | |||
const btoa = require("./lib/btoa"); | |||
module.exports = { | |||
atob, | |||
btoa | |||
}; |
@ -0,0 +1,97 @@ | |||
"use strict"; | |||
/** | |||
* Implementation of atob() according to the HTML and Infra specs, except that | |||
* instead of throwing INVALID_CHARACTER_ERR we return null. | |||
*/ | |||
function atob(data) { | |||
// Web IDL requires DOMStrings to just be converted using ECMAScript | |||
// ToString, which in our case amounts to using a template literal. | |||
data = `${data}`; | |||
// "Remove all ASCII whitespace from data." | |||
data = data.replace(/[ \t\n\f\r]/g, ""); | |||
// "If data's length divides by 4 leaving no remainder, then: if data ends | |||
// with one or two U+003D (=) code points, then remove them from data." | |||
if (data.length % 4 === 0) { | |||
data = data.replace(/==?$/, ""); | |||
} | |||
// "If data's length divides by 4 leaving a remainder of 1, then return | |||
// failure." | |||
// | |||
// "If data contains a code point that is not one of | |||
// | |||
// U+002B (+) | |||
// U+002F (/) | |||
// ASCII alphanumeric | |||
// | |||
// then return failure." | |||
if (data.length % 4 === 1 || /[^+/0-9A-Za-z]/.test(data)) { | |||
return null; | |||
} | |||
// "Let output be an empty byte sequence." | |||
let output = ""; | |||
// "Let buffer be an empty buffer that can have bits appended to it." | |||
// | |||
// We append bits via left-shift and or. accumulatedBits is used to track | |||
// when we've gotten to 24 bits. | |||
let buffer = 0; | |||
let accumulatedBits = 0; | |||
// "Let position be a position variable for data, initially pointing at the | |||
// start of data." | |||
// | |||
// "While position does not point past the end of data:" | |||
for (let i = 0; i < data.length; i++) { | |||
// "Find the code point pointed to by position in the second column of | |||
// Table 1: The Base 64 Alphabet of RFC 4648. Let n be the number given in | |||
// the first cell of the same row. | |||
// | |||
// "Append to buffer the six bits corresponding to n, most significant bit | |||
// first." | |||
// | |||
// atobLookup() implements the table from RFC 4648. | |||
buffer <<= 6; | |||
buffer |= atobLookup(data[i]); | |||
accumulatedBits += 6; | |||
// "If buffer has accumulated 24 bits, interpret them as three 8-bit | |||
// big-endian numbers. Append three bytes with values equal to those | |||
// numbers to output, in the same order, and then empty buffer." | |||
if (accumulatedBits === 24) { | |||
output += String.fromCharCode((buffer & 0xff0000) >> 16); | |||
output += String.fromCharCode((buffer & 0xff00) >> 8); | |||
output += String.fromCharCode(buffer & 0xff); | |||
buffer = accumulatedBits = 0; | |||
} | |||
// "Advance position by 1." | |||
} | |||
// "If buffer is not empty, it contains either 12 or 18 bits. If it contains | |||
// 12 bits, then discard the last four and interpret the remaining eight as | |||
// an 8-bit big-endian number. If it contains 18 bits, then discard the last | |||
// two and interpret the remaining 16 as two 8-bit big-endian numbers. Append | |||
// the one or two bytes with values equal to those one or two numbers to | |||
// output, in the same order." | |||
if (accumulatedBits === 12) { | |||
buffer >>= 4; | |||
output += String.fromCharCode(buffer); | |||
} else if (accumulatedBits === 18) { | |||
buffer >>= 2; | |||
output += String.fromCharCode((buffer & 0xff00) >> 8); | |||
output += String.fromCharCode(buffer & 0xff); | |||
} | |||
// "Return output." | |||
return output; | |||
} | |||
/** | |||
* A lookup table for atob(), which converts an ASCII character to the | |||
* corresponding six-bit number. | |||
*/ | |||
const keystr = | |||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | |||
function atobLookup(chr) { | |||
const index = keystr.indexOf(chr); | |||
// Throw exception if character is not in the lookup string; should not be hit in tests | |||
return index < 0 ? undefined : index; | |||
} | |||
module.exports = atob; |
@ -0,0 +1,58 @@ | |||
"use strict"; | |||
/** | |||
* btoa() as defined by the HTML and Infra specs, which mostly just references | |||
* RFC 4648. | |||
*/ | |||
function btoa(s) { | |||
let i; | |||
// String conversion as required by Web IDL. | |||
s = `${s}`; | |||
// "The btoa() method must throw an "InvalidCharacterError" DOMException if | |||
// data contains any character whose code point is greater than U+00FF." | |||
for (i = 0; i < s.length; i++) { | |||
if (s.charCodeAt(i) > 255) { | |||
return null; | |||
} | |||
} | |||
let out = ""; | |||
for (i = 0; i < s.length; i += 3) { | |||
const groupsOfSix = [undefined, undefined, undefined, undefined]; | |||
groupsOfSix[0] = s.charCodeAt(i) >> 2; | |||
groupsOfSix[1] = (s.charCodeAt(i) & 0x03) << 4; | |||
if (s.length > i + 1) { | |||
groupsOfSix[1] |= s.charCodeAt(i + 1) >> 4; | |||
groupsOfSix[2] = (s.charCodeAt(i + 1) & 0x0f) << 2; | |||
} | |||
if (s.length > i + 2) { | |||
groupsOfSix[2] |= s.charCodeAt(i + 2) >> 6; | |||
groupsOfSix[3] = s.charCodeAt(i + 2) & 0x3f; | |||
} | |||
for (let j = 0; j < groupsOfSix.length; j++) { | |||
if (typeof groupsOfSix[j] === "undefined") { | |||
out += "="; | |||
} else { | |||
out += btoaLookup(groupsOfSix[j]); | |||
} | |||
} | |||
} | |||
return out; | |||
} | |||
/** | |||
* Lookup table for btoa(), which converts a six-bit number into the | |||
* corresponding ASCII character. | |||
*/ | |||
const keystr = | |||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; | |||
function btoaLookup(index) { | |||
if (index >= 0 && index < 64) { | |||
return keystr[index]; | |||
} | |||
// Throw INVALID_CHARACTER_ERR exception here -- won't be hit in the tests. | |||
return undefined; | |||
} | |||
module.exports = btoa; |
@ -0,0 +1,71 @@ | |||
{ | |||
"_from": "abab@^2.0.3", | |||
"_id": "abab@2.0.5", | |||
"_inBundle": false, | |||
"_integrity": "sha512-9IK9EadsbHo6jLWIpxpR6pL0sazTXV6+SQv25ZB+F7Bj9mJNaOc4nCRabwd5M/JwmUa8idz6Eci6eKfJryPs6Q==", | |||
"_location": "/abab", | |||
"_phantomChildren": {}, | |||
"_requested": { | |||
"type": "range", | |||
"registry": true, | |||
"raw": "abab@^2.0.3", | |||
"name": "abab", | |||
"escapedName": "abab", | |||
"rawSpec": "^2.0.3", | |||
"saveSpec": null, | |||
"fetchSpec": "^2.0.3" | |||
}, | |||
"_requiredBy": [ | |||
"/data-urls", | |||
"/jsdom" | |||
], | |||
"_resolved": "https://registry.npmjs.org/abab/-/abab-2.0.5.tgz", | |||
"_shasum": "c0b678fb32d60fc1219c784d6a826fe385aeb79a", | |||
"_spec": "abab@^2.0.3", | |||
"_where": "/home/alpcentaur/ProjektA/PermApp/node_modules/jsdom", | |||
"author": { | |||
"name": "Jeff Carpenter", | |||
"email": "gcarpenterv@gmail.com" | |||
}, | |||
"bugs": { | |||
"url": "https://github.com/jsdom/abab/issues" | |||
}, | |||
"bundleDependencies": false, | |||
"deprecated": false, | |||
"description": "WHATWG spec-compliant implementations of window.atob and window.btoa.", | |||
"devDependencies": { | |||
"eslint": "^4.19.1", | |||
"karma": "^2.0.0", | |||
"karma-cli": "^1.0.1", | |||
"karma-firefox-launcher": "^1.1.0", | |||
"karma-mocha": "^1.3.0", | |||
"karma-webpack": "^3.0.0", | |||
"mocha": "^5.1.0", | |||
"webpack": "^4.5.0" | |||
}, | |||
"files": [ | |||
"index.d.ts", | |||
"index.js", | |||
"lib/" | |||
], | |||
"homepage": "https://github.com/jsdom/abab#readme", | |||
"keywords": [ | |||
"atob", | |||
"btoa", | |||
"browser" | |||
], | |||
"license": "BSD-3-Clause", | |||
"main": "index.js", | |||
"name": "abab", | |||
"repository": { | |||
"type": "git", | |||
"url": "git+https://github.com/jsdom/abab.git" | |||
}, | |||
"scripts": { | |||
"karma": "karma start", | |||
"lint": "eslint .", | |||
"mocha": "mocha test/node", | |||
"test": "npm run lint && npm run mocha && npm run karma" | |||
}, | |||
"version": "2.0.5" | |||
} |
@ -0,0 +1,236 @@ | |||
1.3.7 / 2019-04-29 | |||
================== | |||
* deps: negotiator@0.6.2 | |||
- Fix sorting charset, encoding, and language with extra parameters | |||
1.3.6 / 2019-04-28 | |||
================== | |||
* deps: mime-types@~2.1.24 | |||
- deps: mime-db@~1.40.0 | |||
1.3.5 / 2018-02-28 | |||
================== | |||
* deps: mime-types@~2.1.18 | |||
- deps: mime-db@~1.33.0 | |||
1.3.4 / 2017-08-22 | |||
================== | |||
* deps: mime-types@~2.1.16 | |||
- deps: mime-db@~1.29.0 | |||
1.3.3 / 2016-05-02 | |||
================== | |||
* deps: mime-types@~2.1.11 | |||
- deps: mime-db@~1.23.0 | |||
* deps: negotiator@0.6.1 | |||
- perf: improve `Accept` parsing speed | |||
- perf: improve `Accept-Charset` parsing speed | |||
- perf: improve `Accept-Encoding` parsing speed | |||
- perf: improve `Accept-Language` parsing speed | |||
1.3.2 / 2016-03-08 | |||
================== | |||
* deps: mime-types@~2.1.10 | |||
- Fix extension of `application/dash+xml` | |||
- Update primary extension for `audio/mp4` | |||
- deps: mime-db@~1.22.0 | |||
1.3.1 / 2016-01-19 | |||
================== | |||
* deps: mime-types@~2.1.9 | |||
- deps: mime-db@~1.21.0 | |||
1.3.0 / 2015-09-29 | |||
================== | |||
* deps: mime-types@~2.1.7 | |||
- deps: mime-db@~1.19.0 | |||
* deps: negotiator@0.6.0 | |||
- Fix including type extensions in parameters in `Accept` parsing | |||
- Fix parsing `Accept` parameters with quoted equals | |||
- Fix parsing `Accept` parameters with quoted semicolons | |||
- Lazy-load modules from main entry point | |||
- perf: delay type concatenation until needed | |||
- perf: enable strict mode | |||
- perf: hoist regular expressions | |||
- perf: remove closures getting spec properties | |||
- perf: remove a closure from media type parsing | |||
- perf: remove property delete from media type parsing | |||
1.2.13 / 2015-09-06 | |||
=================== | |||
* deps: mime-types@~2.1.6 | |||
- deps: mime-db@~1.18.0 | |||
1.2.12 / 2015-07-30 | |||
=================== | |||
* deps: mime-types@~2.1.4 | |||
- deps: mime-db@~1.16.0 | |||
1.2.11 / 2015-07-16 | |||
=================== | |||
* deps: mime-types@~2.1.3 | |||
- deps: mime-db@~1.15.0 | |||
1.2.10 / 2015-07-01 | |||
=================== | |||
* deps: mime-types@~2.1.2 | |||
- deps: mime-db@~1.14.0 | |||
1.2.9 / 2015-06-08 | |||
================== | |||
* deps: mime-types@~2.1.1 | |||
- perf: fix deopt during mapping | |||
1.2.8 / 2015-06-07 | |||
================== | |||
* deps: mime-types@~2.1.0 | |||
- deps: mime-db@~1.13.0 | |||
* perf: avoid argument reassignment & argument slice | |||
* perf: avoid negotiator recursive construction | |||
* perf: enable strict mode | |||
* perf: remove unnecessary bitwise operator | |||
1.2.7 / 2015-05-10 | |||
================== | |||
* deps: negotiator@0.5.3 | |||
- Fix media type parameter matching to be case-insensitive | |||
1.2.6 / 2015-05-07 | |||
================== | |||
* deps: mime-types@~2.0.11 | |||
- deps: mime-db@~1.9.1 | |||
* deps: negotiator@0.5.2 | |||
- Fix comparing media types with quoted values | |||
- Fix splitting media types with quoted commas | |||
1.2.5 / 2015-03-13 | |||
================== | |||
* deps: mime-types@~2.0.10 | |||
- deps: mime-db@~1.8.0 | |||
1.2.4 / 2015-02-14 | |||
================== | |||
* Support Node.js 0.6 | |||
* deps: mime-types@~2.0.9 | |||
- deps: mime-db@~1.7.0 | |||
* deps: negotiator@0.5.1 | |||
- Fix preference sorting to be stable for long acceptable lists | |||
1.2.3 / 2015-01-31 | |||
================== | |||
* deps: mime-types@~2.0.8 | |||
- deps: mime-db@~1.6.0 | |||
1.2.2 / 2014-12-30 | |||
================== | |||
* deps: mime-types@~2.0.7 | |||
- deps: mime-db@~1.5.0 | |||
1.2.1 / 2014-12-30 | |||
================== | |||
* deps: mime-types@~2.0.5 | |||
- deps: mime-db@~1.3.1 | |||
1.2.0 / 2014-12-19 | |||
================== | |||
* deps: negotiator@0.5.0 | |||
- Fix list return order when large accepted list | |||
- Fix missing identity encoding when q=0 exists | |||
- Remove dynamic building of Negotiator class | |||
1.1.4 / 2014-12-10 | |||
================== | |||
* deps: mime-types@~2.0.4 | |||
- deps: mime-db@~1.3.0 | |||
1.1.3 / 2014-11-09 | |||
================== | |||
* deps: mime-types@~2.0.3 | |||
- deps: mime-db@~1.2.0 | |||
1.1.2 / 2014-10-14 | |||
================== | |||
* deps: negotiator@0.4.9 | |||
- Fix error when media type has invalid parameter | |||
1.1.1 / 2014-09-28 | |||
================== | |||
* deps: mime-types@~2.0.2 | |||
- deps: mime-db@~1.1.0 | |||
* deps: negotiator@0.4.8 | |||
- Fix all negotiations to be case-insensitive | |||
- Stable sort preferences of same quality according to client order | |||
1.1.0 / 2014-09-02 | |||
================== | |||
* update `mime-types` | |||
1.0.7 / 2014-07-04 | |||
================== | |||
* Fix wrong type returned from `type` when match after unknown extension | |||
1.0.6 / 2014-06-24 | |||
================== | |||
* deps: negotiator@0.4.7 | |||
1.0.5 / 2014-06-20 | |||
================== | |||
* fix crash when unknown extension given | |||
1.0.4 / 2014-06-19 | |||
================== | |||
* use `mime-types` | |||
1.0.3 / 2014-06-11 | |||
================== | |||
* deps: negotiator@0.4.6 | |||
- Order by specificity when quality is the same | |||
1.0.2 / 2014-05-29 | |||
================== | |||
* Fix interpretation when header not in request | |||
* deps: pin negotiator@0.4.5 | |||
1.0.1 / 2014-01-18 | |||
================== | |||
* Identity encoding isn't always acceptable | |||
* deps: negotiator@~0.4.0 | |||
1.0.0 / 2013-12-27 | |||
================== | |||
* Genesis |
@ -0,0 +1,23 @@ | |||
(The MIT License) | |||
Copyright (c) 2014 Jonathan Ong <me@jongleberry.com> | |||
Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com> | |||
Permission is hereby granted, free of charge, to any person obtaining | |||
a copy of this software and associated documentation files (the | |||
'Software'), to deal in the Software without restriction, including | |||
without limitation the rights to use, copy, modify, merge, publish, | |||
distribute, sublicense, and/or sell copies of the Software, and to | |||
permit persons to whom the Software is furnished to do so, subject to | |||
the following conditions: | |||
The above copyright notice and this permission notice shall be | |||
included in all copies or substantial portions of the Software. | |||
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, | |||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | |||
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | |||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, | |||
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE | |||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
@ -0,0 +1,142 @@ | |||
# accepts | |||
[![NPM Version][npm-version-image]][npm-url] | |||
[![NPM Downloads][npm-downloads-image]][npm-url] | |||
[![Node.js Version][node-version-image]][node-version-url] | |||
[![Build Status][travis-image]][travis-url] | |||
[![Test Coverage][coveralls-image]][coveralls-url] | |||
Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). | |||
Extracted from [koa](https://www.npmjs.com/package/koa) for general use. | |||
In addition to negotiator, it allows: | |||
- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` | |||
as well as `('text/html', 'application/json')`. | |||
- Allows type shorthands such as `json`. | |||
- Returns `false` when no types match | |||
- Treats non-existent headers as `*` | |||
## Installation | |||
This is a [Node.js](https://nodejs.org/en/) module available through the | |||
[npm registry](https://www.npmjs.com/). Installation is done using the | |||
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): | |||
```sh | |||
$ npm install accepts | |||
``` | |||
## API | |||
<!-- eslint-disable no-unused-vars --> | |||
```js | |||
var accepts = require('accepts') | |||
``` | |||
### accepts(req) | |||
Create a new `Accepts` object for the given `req`. | |||
#### .charset(charsets) | |||
Return the first accepted charset. If nothing in `charsets` is accepted, | |||
then `false` is returned. | |||
#### .charsets() | |||
Return the charsets that the request accepts, in the order of the client's | |||
preference (most preferred first). | |||
#### .encoding(encodings) | |||
Return the first accepted encoding. If nothing in `encodings` is accepted, | |||
then `false` is returned. | |||
#### .encodings() | |||
Return the encodings that the request accepts, in the order of the client's | |||
preference (most preferred first). | |||
#### .language(languages) | |||
Return the first accepted language. If nothing in `languages` is accepted, | |||
then `false` is returned. | |||
#### .languages() | |||
Return the languages that the request accepts, in the order of the client's | |||
preference (most preferred first). | |||
#### .type(types) | |||
Return the first accepted type (and it is returned as the same text as what | |||
appears in the `types` array). If nothing in `types` is accepted, then `false` | |||
is returned. | |||
The `types` array can contain full MIME types or file extensions. Any value | |||
that is not a full MIME types is passed to `require('mime-types').lookup`. | |||
#### .types() | |||
Return the types that the request accepts, in the order of the client's | |||
preference (most preferred first). | |||
## Examples | |||
### Simple type negotiation | |||
This simple example shows how to use `accepts` to return a different typed | |||
respond body based on what the client wants to accept. The server lists it's | |||
preferences in order and will get back the best match between the client and | |||
server. | |||
```js | |||
var accepts = require('accepts') | |||
var http = require('http') | |||
function app (req, res) { | |||
var accept = accepts(req) | |||
// the order of this list is significant; should be server preferred order | |||
switch (accept.type(['json', 'html'])) { | |||
case 'json': | |||
res.setHeader('Content-Type', 'application/json') | |||
res.write('{"hello":"world!"}') | |||
break | |||
case 'html': | |||
res.setHeader('Content-Type', 'text/html') | |||
res.write('<b>hello, world!</b>') | |||
break | |||
default: | |||
// the fallback is text/plain, so no need to specify it above | |||
res.setHeader('Content-Type', 'text/plain') | |||
res.write('hello, world!') | |||
break | |||
} | |||
res.end() | |||
} | |||
http.createServer(app).listen(3000) | |||
``` | |||
You can test this out with the cURL program: | |||
```sh | |||
curl -I -H'Accept: text/html' http://localhost:3000/ | |||
``` | |||
## License | |||
[MIT](LICENSE) | |||
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master | |||
[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master | |||
[node-version-image]: https://badgen.net/npm/node/accepts | |||
[node-version-url]: https://nodejs.org/en/download | |||
[npm-downloads-image]: https://badgen.net/npm/dm/accepts | |||
[npm-url]: https://npmjs.org/package/accepts | |||
[npm-version-image]: https://badgen.net/npm/v/accepts | |||
[travis-image]: https://badgen.net/travis/jshttp/accepts/master | |||
[travis-url]: https://travis-ci.org/jshttp/accepts |
@ -0,0 +1,238 @@ | |||
/*! | |||
* accepts | |||
* Copyright(c) 2014 Jonathan Ong | |||
* Copyright(c) 2015 Douglas Christopher Wilson | |||
* MIT Licensed | |||
*/ | |||
'use strict' | |||
/** | |||
* Module dependencies. | |||
* @private | |||
*/ | |||
var Negotiator = require('negotiator') | |||
var mime = require('mime-types') | |||
/** | |||
* Module exports. | |||
* @public | |||
*/ | |||
module.exports = Accepts | |||
/** | |||
* Create a new Accepts object for the given req. | |||
* | |||
* @param {object} req | |||
* @public | |||
*/ | |||
function Accepts (req) { | |||
if (!(this instanceof Accepts)) { | |||
return new Accepts(req) | |||
} | |||
this.headers = req.headers | |||
this.negotiator = new Negotiator(req) | |||
} | |||
/** | |||
* Check if the given `type(s)` is acceptable, returning | |||
* the best match when true, otherwise `undefined`, in which | |||
* case you should respond with 406 "Not Acceptable". | |||
* | |||
* The `type` value may be a single mime type string | |||
* such as "application/json", the extension name | |||
* such as "json" or an array `["json", "html", "text/plain"]`. When a list | |||
* or array is given the _best_ match, if any is returned. | |||
* | |||
* Examples: | |||
* | |||
* // Accept: text/html | |||
* this.types('html'); | |||
* // => "html" | |||
* | |||
* // Accept: text/*, application/json | |||
* this.types('html'); | |||
* // => "html" | |||
* this.types('text/html'); | |||
* // => "text/html" | |||
* this.types('json', 'text'); | |||
* // => "json" | |||
* this.types('application/json'); | |||
* // => "application/json" | |||
* | |||
* // Accept: text/*, application/json | |||
* this.types('image/png'); | |||
* this.types('png'); | |||
* // => undefined | |||
* | |||
* // Accept: text/*;q=.5, application/json | |||
* this.types(['html', 'json']); | |||
* this.types('html', 'json'); | |||
* // => "json" | |||
* | |||
* @param {String|Array} types... | |||
* @return {String|Array|Boolean} | |||
* @public | |||
*/ | |||
Accepts.prototype.type = | |||
Accepts.prototype.types = function (types_) { | |||
var types = types_ | |||
// support flattened arguments | |||
if (types && !Array.isArray(types)) { | |||
types = new Array(arguments.length) | |||
for (var i = 0; i < types.length; i++) { | |||
types[i] = arguments[i] | |||
} | |||
} | |||
// no types, return all requested types | |||
if (!types || types.length === 0) { | |||
return this.negotiator.mediaTypes() | |||
} | |||
// no accept header, return first given type | |||
if (!this.headers.accept) { | |||
return types[0] | |||
} | |||
var mimes = types.map(extToMime) | |||
var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) | |||
var first = accepts[0] | |||
return first | |||
? types[mimes.indexOf(first)] | |||
: false | |||
} | |||
/** | |||
* Return accepted encodings or best fit based on `encodings`. | |||
* | |||
* Given `Accept-Encoding: gzip, deflate` | |||
* an array sorted by quality is returned: | |||
* | |||
* ['gzip', 'deflate'] | |||
* | |||
* @param {String|Array} encodings... | |||
* @return {String|Array} | |||
* @public | |||
*/ | |||
Accepts.prototype.encoding = | |||
Accepts.prototype.encodings = function (encodings_) { | |||
var encodings = encodings_ | |||
// support flattened arguments | |||
if (encodings && !Array.isArray(encodings)) { | |||
encodings = new Array(arguments.length) | |||
for (var i = 0; i < encodings.length; i++) { | |||
encodings[i] = arguments[i] | |||
} | |||
} | |||
// no encodings, return all requested encodings | |||
if (!encodings || encodings.length === 0) { | |||
return this.negotiator.encodings() | |||
} | |||
return this.negotiator.encodings(encodings)[0] || false | |||
} | |||
/** | |||
* Return accepted charsets or best fit based on `charsets`. | |||
* | |||
* Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` | |||
* an array sorted by quality is returned: | |||
* | |||
* ['utf-8', 'utf-7', 'iso-8859-1'] | |||
* | |||
* @param {String|Array} charsets... | |||
* @return {String|Array} | |||
* @public | |||
*/ | |||
Accepts.prototype.charset = | |||
Accepts.prototype.charsets = function (charsets_) { | |||
var charsets = charsets_ | |||
// support flattened arguments | |||
if (charsets && !Array.isArray(charsets)) { | |||
charsets = new Array(arguments.length) | |||
for (var i = 0; i < charsets.length; i++) { | |||
charsets[i] = arguments[i] | |||
} | |||
} | |||
// no charsets, return all requested charsets | |||
if (!charsets || charsets.length === 0) { | |||
return this.negotiator.charsets() | |||
} | |||
return this.negotiator.charsets(charsets)[0] || false | |||
} | |||
/** | |||
* Return accepted languages or best fit based on `langs`. | |||
* | |||
* Given `Accept-Language: en;q=0.8, es, pt` | |||
* an array sorted by quality is returned: | |||
* | |||
* ['es', 'pt', 'en'] | |||
* | |||
* @param {String|Array} langs... | |||
* @return {Array|String} | |||
* @public | |||
*/ | |||
Accepts.prototype.lang = | |||
Accepts.prototype.langs = | |||
Accepts.prototype.language = | |||
Accepts.prototype.languages = function (languages_) { | |||
var languages = languages_ | |||
// support flattened arguments | |||
if (languages && !Array.isArray(languages)) { | |||
languages = new Array(arguments.length) | |||
for (var i = 0; i < languages.length; i++) { | |||
languages[i] = arguments[i] | |||
} | |||
} | |||
// no languages, return all requested languages | |||
if (!languages || languages.length === 0) { | |||
return this.negotiator.languages() | |||
} | |||
return this.negotiator.languages(languages)[0] || false | |||
} | |||
/** | |||
* Convert extnames to mime. | |||
* | |||
* @param {String} type | |||
* @return {String} | |||
* @private | |||
*/ | |||
function extToMime (type) { | |||
return type.indexOf('/') === -1 | |||
? mime.lookup(type) | |||
: type | |||
} | |||
/** | |||
* Check if mime is valid. | |||
* | |||
* @param {String} type | |||
* @return {String} | |||
* @private | |||
*/ | |||
function validMime (type) { | |||
return typeof type === 'string' | |||
} |
@ -0,0 +1,86 @@ | |||
{ | |||
"_from": "accepts@~1.3.7", | |||
"_id": "accepts@1.3.7", | |||
"_inBundle": false, | |||
"_integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==", | |||
"_location": "/accepts", | |||
"_phantomChildren": {}, | |||
"_requested": { | |||
"type": "range", | |||
"registry": true, | |||
"raw": "accepts@~1.3.7", | |||
"name": "accepts", | |||
"escapedName": "accepts", | |||
"rawSpec": "~1.3.7", | |||
"saveSpec": null, | |||
"fetchSpec": "~1.3.7" | |||
}, | |||
"_requiredBy": [ | |||
"/express" | |||
], | |||
"_resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", | |||
"_shasum": "531bc726517a3b2b41f850021c6cc15eaab507cd", | |||
"_spec": "accepts@~1.3.7", | |||
"_where": "/home/alpcentaur/ProjektA/PermApp/node_modules/express", | |||
"bugs": { | |||
"url": "https://github.com/jshttp/accepts/issues" | |||
}, | |||
"bundleDependencies": false, | |||
"contributors": [ | |||
{ | |||
"name": "Douglas Christopher Wilson", | |||
"email": "doug@somethingdoug.com" | |||
}, | |||
{ | |||
"name": "Jonathan Ong", | |||
"email": "me@jongleberry.com", | |||
"url": "http://jongleberry.com" | |||
} | |||
], | |||
"dependencies": { | |||
"mime-types": "~2.1.24", | |||
"negotiator": "0.6.2" | |||
}, | |||
"deprecated": false, | |||
"description": "Higher-level content negotiation", | |||
"devDependencies": { | |||
"deep-equal": "1.0.1", | |||
"eslint": "5.16.0", | |||
"eslint-config-standard": "12.0.0", | |||
"eslint-plugin-import": "2.17.2", | |||
"eslint-plugin-markdown": "1.0.0", | |||
"eslint-plugin-node": "8.0.1", | |||
"eslint-plugin-promise": "4.1.1", | |||
"eslint-plugin-standard": "4.0.0", | |||
"mocha": "6.1.4", | |||
"nyc": "14.0.0" | |||
}, | |||
"engines": { | |||
"node": ">= 0.6" | |||
}, | |||
"files": [ | |||
"LICENSE", | |||
"HISTORY.md", | |||
"index.js" | |||
], | |||
"homepage": "https://github.com/jshttp/accepts#readme", | |||
"keywords": [ | |||
"content", | |||
"negotiation", | |||
"accept", | |||
"accepts" | |||
], | |||
"license": "MIT", | |||
"name": "accepts", | |||
"repository": { | |||
"type": "git", | |||
"url": "git+https://github.com/jshttp/accepts.git" | |||
}, | |||
"scripts": { | |||
"lint": "eslint --plugin markdown --ext js,md .", | |||
"test": "mocha --reporter spec --check-leaks --bail test/", | |||
"test-cov": "nyc --reporter=html --reporter=text npm test", | |||
"test-travis": "nyc --reporter=text npm test" | |||
}, | |||
"version": "1.3.7" | |||
} |
@ -0,0 +1,19 @@ | |||
Copyright (c) 2014 Forbes Lindesay | |||
Permission is hereby granted, free of charge, to any person obtaining a copy | |||
of this software and associated documentation files (the "Software"), to deal | |||
in the Software without restriction, including without limitation the rights | |||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |||
copies of the Software, and to permit persons to whom the Software is | |||
furnished to do so, subject to the following conditions: | |||
The above copyright notice and this permission notice shall be included in | |||
all copies or substantial portions of the Software. | |||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |||
THE SOFTWARE. |
@ -0,0 +1,81 @@ | |||
# acorn-globals | |||
Detect global variables in JavaScript using acorn | |||
[Get supported acorn-globals with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-acorn_globals?utm_source=npm-acorn-globals&utm_medium=referral&utm_campaign=readme) | |||
[![Build Status](https://img.shields.io/travis/ForbesLindesay/acorn-globals/master.svg)](https://travis-ci.org/ForbesLindesay/acorn-globals) | |||
[![Dependency Status](https://img.shields.io/david/ForbesLindesay/acorn-globals.svg)](https://david-dm.org/ForbesLindesay/acorn-globals) | |||
[![NPM version](https://img.shields.io/npm/v/acorn-globals.svg)](https://www.npmjs.org/package/acorn-globals) | |||
## Installation | |||
npm install acorn-globals | |||
## Usage | |||
detect.js | |||
```js | |||
var fs = require('fs'); | |||
var detect = require('acorn-globals'); | |||
var src = fs.readFileSync(__dirname + '/input.js', 'utf8'); | |||
var scope = detect(src); | |||
console.dir(scope); | |||
``` | |||
input.js | |||
```js | |||
var x = 5; | |||
var y = 3, z = 2; | |||
w.foo(); | |||
w = 2; | |||
RAWR=444; | |||
RAWR.foo(); | |||
BLARG=3; | |||
foo(function () { | |||
var BAR = 3; | |||
process.nextTick(function (ZZZZZZZZZZZZ) { | |||
console.log('beep boop'); | |||
var xyz = 4; | |||
x += 10; | |||
x.zzzzzz; | |||
ZZZ=6; | |||
}); | |||
function doom () { | |||
} | |||
ZZZ.foo(); | |||
}); | |||
console.log(xyz); | |||
``` | |||
output: | |||
``` | |||
$ node example/detect.js | |||
[ { name: 'BLARG', nodes: [ [Object] ] }, | |||
{ name: 'RAWR', nodes: [ [Object], [Object] ] }, | |||
{ name: 'ZZZ', nodes: [ [Object], [Object] ] }, | |||
{ name: 'console', nodes: [ [Object], [Object] ] }, | |||
{ name: 'foo', nodes: [ [Object] ] }, | |||
{ name: 'process', nodes: [ [Object] ] }, | |||
{ name: 'w', nodes: [ [Object], [Object] ] }, | |||
{ name: 'xyz', nodes: [ [Object] ] } ] | |||
``` | |||
## Security contact information | |||
To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. | |||
## License | |||
MIT |
@ -0,0 +1,179 @@ | |||
'use strict'; | |||
var acorn = require('acorn'); | |||
var walk = require('acorn-walk'); | |||
function isScope(node) { | |||
return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration' || node.type === 'ArrowFunctionExpression' || node.type === 'Program'; | |||
} | |||
function isBlockScope(node) { | |||
return node.type === 'BlockStatement' || isScope(node); | |||
} | |||
function declaresArguments(node) { | |||
return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration'; | |||
} | |||
function declaresThis(node) { | |||
return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration'; | |||
} | |||
function reallyParse(source, options) { | |||
var parseOptions = Object.assign({}, options, | |||
{ | |||
allowReturnOutsideFunction: true, | |||
allowImportExportEverywhere: true, | |||
allowHashBang: true | |||
} | |||
); | |||
return acorn.parse(source, parseOptions); | |||
} | |||
module.exports = findGlobals; | |||
module.exports.parse = reallyParse; | |||
function findGlobals(source, options) { | |||
options = options || {}; | |||
var globals = []; | |||
var ast; | |||
// istanbul ignore else | |||
if (typeof source === 'string') { | |||
ast = reallyParse(source, options); | |||
} else { | |||
ast = source; | |||
} | |||
// istanbul ignore if | |||
if (!(ast && typeof ast === 'object' && ast.type === 'Program')) { | |||
throw new TypeError('Source must be either a string of JavaScript or an acorn AST'); | |||
} | |||
var declareFunction = function (node) { | |||
var fn = node; | |||
fn.locals = fn.locals || Object.create(null); | |||
node.params.forEach(function (node) { | |||
declarePattern(node, fn); | |||
}); | |||
if (node.id) { | |||
fn.locals[node.id.name] = true; | |||
} | |||
}; | |||
var declareClass = function (node) { | |||
node.locals = node.locals || Object.create(null); | |||
if (node.id) { | |||
node.locals[node.id.name] = true; | |||
} | |||
}; | |||
var declarePattern = function (node, parent) { | |||
switch (node.type) { | |||
case 'Identifier': | |||
parent.locals[node.name] = true; | |||
break; | |||
case 'ObjectPattern': | |||
node.properties.forEach(function (node) { | |||
declarePattern(node.value || node.argument, parent); | |||
}); | |||
break; | |||
case 'ArrayPattern': | |||
node.elements.forEach(function (node) { | |||
if (node) declarePattern(node, parent); | |||
}); | |||
break; | |||
case 'RestElement': | |||
declarePattern(node.argument, parent); | |||
break; | |||
case 'AssignmentPattern': | |||
declarePattern(node.left, parent); | |||
break; | |||
// istanbul ignore next | |||
default: | |||
throw new Error('Unrecognized pattern type: ' + node.type); | |||
} | |||
}; | |||
var declareModuleSpecifier = function (node, parents) { | |||
ast.locals = ast.locals || Object.create(null); | |||
ast.locals[node.local.name] = true; | |||
}; | |||
walk.ancestor(ast, { | |||
'VariableDeclaration': function (node, parents) { | |||
var parent = null; | |||
for (var i = parents.length - 1; i >= 0 && parent === null; i--) { | |||
if (node.kind === 'var' ? isScope(parents[i]) : isBlockScope(parents[i])) { | |||
parent = parents[i]; | |||
} | |||
} | |||
parent.locals = parent.locals || Object.create(null); | |||
node.declarations.forEach(function (declaration) { | |||
declarePattern(declaration.id, parent); | |||
}); | |||
}, | |||
'FunctionDeclaration': function (node, parents) { | |||
var parent = null; | |||
for (var i = parents.length - 2; i >= 0 && parent === null; i--) { | |||
if (isScope(parents[i])) { | |||
parent = parents[i]; | |||
} | |||
} | |||
parent.locals = parent.locals || Object.create(null); | |||
if (node.id) { | |||
parent.locals[node.id.name] = true; | |||
} | |||
declareFunction(node); | |||
}, | |||
'Function': declareFunction, | |||
'ClassDeclaration': function (node, parents) { | |||
var parent = null; | |||
for (var i = parents.length - 2; i >= 0 && parent === null; i--) { | |||
if (isBlockScope(parents[i])) { | |||
parent = parents[i]; | |||
} | |||
} | |||
parent.locals = parent.locals || Object.create(null); | |||
if (node.id) { | |||
parent.locals[node.id.name] = true; | |||
} | |||
declareClass(node); | |||
}, | |||
'Class': declareClass, | |||
'TryStatement': function (node) { | |||
if (node.handler === null) return; | |||
node.handler.locals = node.handler.locals || Object.create(null); | |||
declarePattern(node.handler.param, node.handler); | |||
}, | |||
'ImportDefaultSpecifier': declareModuleSpecifier, | |||
'ImportSpecifier': declareModuleSpecifier, | |||
'ImportNamespaceSpecifier': declareModuleSpecifier | |||
}); | |||
function identifier(node, parents) { | |||
var name = node.name; | |||
if (name === 'undefined') return; | |||
for (var i = 0; i < parents.length; i++) { | |||
if (name === 'arguments' && declaresArguments(parents[i])) { | |||
return; | |||
} | |||
if (parents[i].locals && name in parents[i].locals) { | |||
return; | |||
} | |||
} | |||
node.parents = parents.slice(); | |||
globals.push(node); | |||
} | |||
walk.ancestor(ast, { | |||
'VariablePattern': identifier, | |||
'Identifier': identifier, | |||
'ThisExpression': function (node, parents) { | |||
for (var i = 0; i < parents.length; i++) { | |||
if (declaresThis(parents[i])) { | |||
return; | |||
} | |||
} | |||
node.parents = parents.slice(); | |||
globals.push(node); | |||
} | |||
}); | |||
var groupedGlobals = Object.create(null); | |||
globals.forEach(function (node) { | |||
var name = node.type === 'ThisExpression' ? 'this' : node.name; | |||
groupedGlobals[name] = (groupedGlobals[name] || []); | |||
groupedGlobals[name].push(node); | |||
}); | |||
return Object.keys(groupedGlobals).sort().map(function (name) { | |||
return {name: name, nodes: groupedGlobals[name]}; | |||
}); | |||
} |
@ -0,0 +1,66 @@ | |||
{ | |||
"_from": "acorn-globals@^6.0.0", | |||
"_id": "acorn-globals@6.0.0", | |||
"_inBundle": false, | |||
"_integrity": "sha512-ZQl7LOWaF5ePqqcX4hLuv/bLXYQNfNWw2c0/yX/TsPRKamzHcTGQnlCjHT3TsmkOUVEPS3crCxiPfdzE/Trlhg==", | |||
"_location": "/acorn-globals", | |||
"_phantomChildren": {}, | |||
"_requested": { | |||
"type": "range", | |||
"registry": true, | |||
"raw": "acorn-globals@^6.0.0", | |||
"name": "acorn-globals", | |||
"escapedName": "acorn-globals", | |||
"rawSpec": "^6.0.0", | |||
"saveSpec": null, | |||
"fetchSpec": "^6.0.0" | |||
}, | |||
"_requiredBy": [ | |||
"/jsdom" | |||
], | |||
"_resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-6.0.0.tgz", | |||
"_shasum": "46cdd39f0f8ff08a876619b55f5ac8a6dc770b45", | |||
"_spec": "acorn-globals@^6.0.0", | |||
"_where": "/home/alpcentaur/ProjektA/PermApp/node_modules/jsdom", | |||
"author": { | |||
"name": "ForbesLindesay" | |||
}, | |||
"bugs": { | |||
"url": "https://github.com/ForbesLindesay/acorn-globals/issues" | |||
}, | |||
"bundleDependencies": false, | |||
"dependencies": { | |||
"acorn": "^7.1.1", | |||
"acorn-walk": "^7.1.1" | |||
}, | |||
"deprecated": false, | |||
"description": "Detect global variables in JavaScript using acorn", | |||
"devDependencies": { | |||
"testit": "^3.1.0" | |||
}, | |||
"files": [ | |||
"index.js", | |||
"LICENSE" | |||
], | |||
"homepage": "https://github.com/ForbesLindesay/acorn-globals#readme", | |||
"keywords": [ | |||
"ast", | |||
"variable", | |||
"name", | |||
"lexical", | |||
"scope", | |||
"local", | |||
"global", | |||
"implicit" | |||
], | |||
"license": "MIT", | |||
"name": "acorn-globals", | |||
"repository": { | |||
"type": "git", | |||
"url": "git+https://github.com/ForbesLindesay/acorn-globals.git" | |||
}, | |||
"scripts": { | |||
"test": "node test" | |||
}, | |||
"version": "6.0.0" | |||
} |
@ -0,0 +1,131 @@ | |||
## 7.2.0 (2020-06-17) | |||
### New features | |||
Support optional chaining and nullish coalescing. | |||
Support `import.meta`. | |||
Add support for `export * as ns from "source"`. | |||
## 7.1.1 (2020-02-13) | |||
### Bug fixes | |||
Clean up the type definitions to actually work well with the main parser. | |||
## 7.1.0 (2020-02-11) | |||
### New features | |||
Add a TypeScript definition file for the library. | |||
## 7.0.0 (2017-08-12) | |||
### New features | |||
Support walking `ImportExpression` nodes. | |||
## 6.2.0 (2017-07-04) | |||
### New features | |||
Add support for `Import` nodes. | |||
## 6.1.0 (2018-09-28) | |||
### New features | |||
The walker now walks `TemplateElement` nodes. | |||
## 6.0.1 (2018-09-14) | |||
### Bug fixes | |||
Fix bad "main" field in package.json. | |||
## 6.0.0 (2018-09-14) | |||
### Breaking changes | |||
This is now a separate package, `acorn-walk`, rather than part of the main `acorn` package. | |||
The `ScopeBody` and `ScopeExpression` meta-node-types are no longer supported. | |||
## 5.7.1 (2018-06-15) | |||
### Bug fixes | |||
Make sure the walker and bin files are rebuilt on release (the previous release didn't get the up-to-date versions). | |||
## 5.7.0 (2018-06-15) | |||
### Bug fixes | |||
Fix crash in walker when walking a binding-less catch node. | |||
## 5.6.2 (2018-06-05) | |||
### Bug fixes | |||
In the walker, go back to allowing the `baseVisitor` argument to be null to default to the default base everywhere. | |||
## 5.6.1 (2018-06-01) | |||
### Bug fixes | |||
Fix regression when passing `null` as fourth argument to `walk.recursive`. | |||
## 5.6.0 (2018-05-31) | |||
### Bug fixes | |||
Fix a bug in the walker that caused a crash when walking an object pattern spread. | |||
## 5.5.1 (2018-03-06) | |||
### Bug fixes | |||
Fix regression in walker causing property values in object patterns to be walked as expressions. | |||
## 5.5.0 (2018-02-27) | |||
### Bug fixes | |||
Support object spread in the AST walker. | |||
## 5.4.1 (2018-02-02) | |||
### Bug fixes | |||
5.4.0 somehow accidentally included an old version of walk.js. | |||
## 5.2.0 (2017-10-30) | |||
### Bug fixes | |||
The `full` and `fullAncestor` walkers no longer visit nodes multiple times. | |||
## 5.1.0 (2017-07-05) | |||
### New features | |||
New walker functions `full` and `fullAncestor`. | |||
## 3.2.0 (2016-06-07) | |||
### New features | |||
Make it possible to use `visit.ancestor` with a walk state. | |||
## 3.1.0 (2016-04-18) | |||
### New features | |||
The walker now allows defining handlers for `CatchClause` nodes. | |||
## 2.5.2 (2015-10-27) | |||
### Fixes | |||
Fix bug where the walker walked an exported `let` statement as an expression. |
@ -0,0 +1,19 @@ | |||
Copyright (C) 2012-2018 by various contributors (see AUTHORS) | |||
Permission is hereby granted, free of charge, to any person obtaining a copy | |||
of this software and associated documentation files (the "Software"), to deal | |||
in the Software without restriction, including without limitation the rights | |||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |||
copies of the Software, and to permit persons to whom the Software is | |||
furnished to do so, subject to the following conditions: | |||
The above copyright notice and this permission notice shall be included in | |||
all copies or substantial portions of the Software. | |||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |||
THE SOFTWARE. |
@ -0,0 +1,126 @@ | |||
# Acorn AST walker | |||
An abstract syntax tree walker for the | |||
[ESTree](https://github.com/estree/estree) format. | |||
## Community | |||
Acorn is open source software released under an | |||
[MIT license](https://github.com/acornjs/acorn/blob/master/acorn-walk/LICENSE). | |||
You are welcome to | |||
[report bugs](https://github.com/acornjs/acorn/issues) or create pull | |||
requests on [github](https://github.com/acornjs/acorn). For questions | |||
and discussion, please use the | |||
[Tern discussion forum](https://discuss.ternjs.net). | |||
## Installation | |||
The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): | |||
```sh | |||
npm install acorn-walk | |||
``` | |||
Alternately, you can download the source and build acorn yourself: | |||
```sh | |||
git clone https://github.com/acornjs/acorn.git | |||
cd acorn | |||
npm install | |||
``` | |||
## Interface | |||
An algorithm for recursing through a syntax tree is stored as an | |||
object, with a property for each tree node type holding a function | |||
that will recurse through such a node. There are several ways to run | |||
such a walker. | |||
**simple**`(node, visitors, base, state)` does a 'simple' walk over a | |||
tree. `node` should be the AST node to walk, and `visitors` an object | |||
with properties whose names correspond to node types in the [ESTree | |||
spec](https://github.com/estree/estree). The properties should contain | |||
functions that will be called with the node object and, if applicable | |||
the state at that point. The last two arguments are optional. `base` | |||
is a walker algorithm, and `state` is a start state. The default | |||
walker will simply visit all statements and expressions and not | |||
produce a meaningful state. (An example of a use of state is to track | |||
scope at each point in the tree.) | |||
```js | |||
const acorn = require("acorn") | |||
const walk = require("acorn-walk") | |||
walk.simple(acorn.parse("let x = 10"), { | |||
Literal(node) { | |||
console.log(`Found a literal: ${node.value}`) | |||
} | |||
}) | |||
``` | |||
**ancestor**`(node, visitors, base, state)` does a 'simple' walk over | |||
a tree, building up an array of ancestor nodes (including the current node) | |||
and passing the array to the callbacks as a third parameter. | |||
```js | |||
const acorn = require("acorn") | |||
const walk = require("acorn-walk") | |||
walk.ancestor(acorn.parse("foo('hi')"), { | |||
Literal(_, ancestors) { | |||
console.log("This literal's ancestors are:", ancestors.map(n => n.type)) | |||
} | |||
}) | |||
``` | |||
**recursive**`(node, state, functions, base)` does a 'recursive' | |||
walk, where the walker functions are responsible for continuing the | |||
walk on the child nodes of their target node. `state` is the start | |||
state, and `functions` should contain an object that maps node types | |||
to walker functions. Such functions are called with `(node, state, c)` | |||
arguments, and can cause the walk to continue on a sub-node by calling | |||
the `c` argument on it with `(node, state)` arguments. The optional | |||
`base` argument provides the fallback walker functions for node types | |||
that aren't handled in the `functions` object. If not given, the | |||
default walkers will be used. | |||
**make**`(functions, base)` builds a new walker object by using the | |||
walker functions in `functions` and filling in the missing ones by | |||
taking defaults from `base`. | |||
**full**`(node, callback, base, state)` does a 'full' walk over a | |||
tree, calling the callback with the arguments (node, state, type) for | |||
each node | |||
**fullAncestor**`(node, callback, base, state)` does a 'full' walk | |||
over a tree, building up an array of ancestor nodes (including the | |||
current node) and passing the array to the callbacks as a third | |||
parameter. | |||
```js | |||
const acorn = require("acorn") | |||
const walk = require("acorn-walk") | |||
walk.full(acorn.parse("1 + 1"), node => { | |||
console.log(`There's a ${node.type} node at ${node.ch}`) | |||
}) | |||
``` | |||
**findNodeAt**`(node, start, end, test, base, state)` tries to locate | |||
a node in a tree at the given start and/or end offsets, which | |||
satisfies the predicate `test`. `start` and `end` can be either `null` | |||
(as wildcard) or a number. `test` may be a string (indicating a node | |||
type) or a function that takes `(nodeType, node)` arguments and | |||
returns a boolean indicating whether this node is interesting. `base` | |||
and `state` are optional, and can be used to specify a custom walker. | |||
Nodes are tested from inner to outer, so if two nodes match the | |||
boundaries, the inner one will be preferred. | |||
**findNodeAround**`(node, pos, test, base, state)` is a lot like | |||
`findNodeAt`, but will match any node that exists 'around' (spanning) | |||
the given position. | |||
**findNodeAfter**`(node, pos, test, base, state)` is similar to | |||
`findNodeAround`, but will match all nodes *after* the given position | |||
(testing outer nodes before inner nodes). |
@ -0,0 +1,112 @@ | |||
import {Node} from 'acorn'; | |||
declare module "acorn-walk" { | |||
type FullWalkerCallback<TState> = ( | |||
node: Node, | |||
state: TState, | |||
type: string | |||
) => void; | |||
type FullAncestorWalkerCallback<TState> = ( | |||
node: Node, | |||
state: TState | Node[], | |||
ancestors: Node[], | |||
type: string | |||
) => void; | |||
type WalkerCallback<TState> = (node: Node, state: TState) => void; | |||
type SimpleWalkerFn<TState> = ( | |||
node: Node, | |||
state: TState | |||
) => void; | |||
type AncestorWalkerFn<TState> = ( | |||
node: Node, | |||
state: TState| Node[], | |||
ancestors: Node[] | |||
) => void; | |||
type RecursiveWalkerFn<TState> = ( | |||
node: Node, | |||
state: TState, | |||
callback: WalkerCallback<TState> | |||
) => void; | |||
type SimpleVisitors<TState> = { | |||
[type: string]: SimpleWalkerFn<TState> | |||
}; | |||
type AncestorVisitors<TState> = { | |||
[type: string]: AncestorWalkerFn<TState> | |||
}; | |||
type RecursiveVisitors<TState> = { | |||
[type: string]: RecursiveWalkerFn<TState> | |||
}; | |||
type FindPredicate = (type: string, node: Node) => boolean; | |||
interface Found<TState> { | |||
node: Node, | |||
state: TState | |||
} | |||
export function simple<TState>( | |||
node: Node, | |||
visitors: SimpleVisitors<TState>, | |||
base?: RecursiveVisitors<TState>, | |||
state?: TState | |||
): void; | |||
export function ancestor<TState>( | |||
node: Node, | |||
visitors: AncestorVisitors<TState>, | |||
base?: RecursiveVisitors<TState>, | |||
state?: TState | |||
): void; | |||
export function recursive<TState>( | |||
node: Node, | |||
state: TState, | |||
functions: RecursiveVisitors<TState>, | |||
base?: RecursiveVisitors<TState> | |||
): void; | |||
export function full<TState>( | |||
node: Node, | |||
callback: FullWalkerCallback<TState>, | |||
base?: RecursiveVisitors<TState>, | |||
state?: TState | |||
): void; | |||
export function fullAncestor<TState>( | |||
node: Node, | |||
callback: FullAncestorWalkerCallback<TState>, | |||
base?: RecursiveVisitors<TState>, | |||
state?: TState | |||
): void; | |||
export function make<TState>( | |||
functions: RecursiveVisitors<TState>, | |||
base?: RecursiveVisitors<TState> | |||
): RecursiveVisitors<TState>; | |||
export function findNodeAt<TState>( | |||
node: Node, | |||
start: number | undefined, | |||
end?: number | undefined, | |||
type?: FindPredicate | string, | |||
base?: RecursiveVisitors<TState>, | |||
state?: TState | |||
): Found<TState> | undefined; | |||
export function findNodeAround<TState>( | |||
node: Node, | |||
start: number | undefined, | |||
type?: FindPredicate | string, | |||
base?: RecursiveVisitors<TState>, | |||
state?: TState | |||
): Found<TState> | undefined; | |||
export const findNodeAfter: typeof findNodeAround; | |||
} |
@ -0,0 +1,463 @@ | |||
(function (global, factory) { | |||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : | |||
typeof define === 'function' && define.amd ? define(['exports'], factory) : | |||
(global = global || self, factory((global.acorn = global.acorn || {}, global.acorn.walk = {}))); | |||
}(this, (function (exports) { 'use strict'; | |||
// 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 and | |||
// Statement, 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. | |||
function simple(node, visitors, baseVisitor, state, override) { | |||
if (!baseVisitor) { baseVisitor = base | |||
; }(function c(node, st, override) { | |||
var type = override || node.type, found = visitors[type]; | |||
baseVisitor[type](node, st, c); | |||
if (found) { found(node, st); } | |||
})(node, state, override); | |||
} | |||
// An ancestor walk keeps an array of ancestor nodes (including the | |||
// current node) and passes them to the callback as third parameter | |||
// (and also as state parameter when no other state is present). | |||
function ancestor(node, visitors, baseVisitor, state, override) { | |||
var ancestors = []; | |||
if (!baseVisitor) { baseVisitor = base | |||
; }(function c(node, st, override) { | |||
var type = override || node.type, found = visitors[type]; | |||
var isNew = node !== ancestors[ancestors.length - 1]; | |||
if (isNew) { ancestors.push(node); } | |||
baseVisitor[type](node, st, c); | |||
if (found) { found(node, st || ancestors, ancestors); } | |||
if (isNew) { ancestors.pop(); } | |||
})(node, state, override); | |||
} | |||
// 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, baseVisitor, override) { | |||
var visitor = funcs ? make(funcs, baseVisitor || undefined) : baseVisitor | |||
;(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) { this.node = node; this.state = state; }; | |||
// A full walk triggers the callback on each node | |||
function full(node, callback, baseVisitor, state, override) { | |||
if (!baseVisitor) { baseVisitor = base | |||
; }(function c(node, st, override) { | |||
var type = override || node.type; | |||
baseVisitor[type](node, st, c); | |||
if (!override) { callback(node, st, type); } | |||
})(node, state, override); | |||
} | |||
// An fullAncestor walk is like an ancestor walk, but triggers | |||
// the callback on each node | |||
function fullAncestor(node, callback, baseVisitor, state) { | |||
if (!baseVisitor) { baseVisitor = base; } | |||
var ancestors = [] | |||
;(function c(node, st, override) { | |||
var type = override || node.type; | |||
var isNew = node !== ancestors[ancestors.length - 1]; | |||
if (isNew) { ancestors.push(node); } | |||
baseVisitor[type](node, st, c); | |||
if (!override) { callback(node, st || ancestors, ancestors, type); } | |||
if (isNew) { ancestors.pop(); } | |||
})(node, 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, baseVisitor, state) { | |||
if (!baseVisitor) { baseVisitor = base; } | |||
test = makeTest(test); | |||
try { | |||
(function c(node, st, override) { | |||
var type = override || node.type; | |||
if ((start == null || node.start <= start) && | |||
(end == null || node.end >= end)) | |||
{ baseVisitor[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, baseVisitor, state) { | |||
test = makeTest(test); | |||
if (!baseVisitor) { baseVisitor = base; } | |||
try { | |||
(function c(node, st, override) { | |||
var type = override || node.type; | |||
if (node.start > pos || node.end < pos) { return } | |||
baseVisitor[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, baseVisitor, state) { | |||
test = makeTest(test); | |||
if (!baseVisitor) { baseVisitor = 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) } | |||
baseVisitor[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, baseVisitor, state) { | |||
test = makeTest(test); | |||
if (!baseVisitor) { baseVisitor = base; } | |||
var max | |||
;(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); } | |||
baseVisitor[type](node, st, c); | |||
})(node, state); | |||
return max | |||
} | |||
// Fallback to an Object.create polyfill for older environments. | |||
var create = Object.create || function(proto) { | |||
function Ctor() {} | |||
Ctor.prototype = proto; | |||
return new Ctor | |||
}; | |||
// Used to create a custom walker. Will fill in all missing node | |||
// type properties with the defaults. | |||
function make(funcs, baseVisitor) { | |||
var visitor = create(baseVisitor || base); | |||
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 = {}; | |||
base.Program = base.BlockStatement = function (node, st, c) { | |||
for (var i = 0, list = node.body; i < list.length; i += 1) | |||
{ | |||
var stmt = list[i]; | |||
c(stmt, st, "Statement"); | |||
} | |||
}; | |||
base.Statement = skipThrough; | |||
base.EmptyStatement = ignore; | |||
base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = | |||
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$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) { | |||
var cs = list$1[i$1]; | |||
if (cs.test) { c(cs.test, st, "Expression"); } | |||
for (var i = 0, list = cs.consequent; i < list.length; i += 1) | |||
{ | |||
var cons = list[i]; | |||
c(cons, st, "Statement"); | |||
} | |||
} | |||
}; | |||
base.SwitchCase = function (node, st, c) { | |||
if (node.test) { c(node.test, st, "Expression"); } | |||
for (var i = 0, list = node.consequent; i < list.length; i += 1) | |||
{ | |||
var cons = list[i]; | |||
c(cons, st, "Statement"); | |||
} | |||
}; | |||
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = 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, st); } | |||
if (node.finalizer) { c(node.finalizer, st, "Statement"); } | |||
}; | |||
base.CatchClause = function (node, st, c) { | |||
if (node.param) { c(node.param, st, "Pattern"); } | |||
c(node.body, 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, list = node.declarations; i < list.length; i += 1) | |||
{ | |||
var decl = list[i]; | |||
c(decl, 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, list = node.params; i < list.length; i += 1) | |||
{ | |||
var param = list[i]; | |||
c(param, st, "Pattern"); | |||
} | |||
c(node.body, st, node.expression ? "Expression" : "Statement"); | |||
}; | |||
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, list = node.elements; i < list.length; i += 1) { | |||
var elt = list[i]; | |||
if (elt) { c(elt, st, "Pattern"); } | |||
} | |||
}; | |||
base.ObjectPattern = function (node, st, c) { | |||
for (var i = 0, list = node.properties; i < list.length; i += 1) { | |||
var prop = list[i]; | |||
if (prop.type === "Property") { | |||
if (prop.computed) { c(prop.key, st, "Expression"); } | |||
c(prop.value, st, "Pattern"); | |||
} else if (prop.type === "RestElement") { | |||
c(prop.argument, st, "Pattern"); | |||
} | |||
} | |||
}; | |||
base.Expression = skipThrough; | |||
base.ThisExpression = base.Super = base.MetaProperty = ignore; | |||
base.ArrayExpression = function (node, st, c) { | |||
for (var i = 0, list = node.elements; i < list.length; i += 1) { | |||
var elt = list[i]; | |||
if (elt) { c(elt, st, "Expression"); } | |||
} | |||
}; | |||
base.ObjectExpression = function (node, st, c) { | |||
for (var i = 0, list = node.properties; i < list.length; i += 1) | |||
{ | |||
var prop = list[i]; | |||
c(prop, st); | |||
} | |||
}; | |||
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; | |||
base.SequenceExpression = function (node, st, c) { | |||
for (var i = 0, list = node.expressions; i < list.length; i += 1) | |||
{ | |||
var expr = list[i]; | |||
c(expr, st, "Expression"); | |||
} | |||
}; | |||
base.TemplateLiteral = function (node, st, c) { | |||
for (var i = 0, list = node.quasis; i < list.length; i += 1) | |||
{ | |||
var quasi = list[i]; | |||
c(quasi, st); | |||
} | |||
for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1) | |||
{ | |||
var expr = list$1[i$1]; | |||
c(expr, st, "Expression"); | |||
} | |||
}; | |||
base.TemplateElement = ignore; | |||
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, list = node.arguments; i < list.length; i += 1) | |||
{ | |||
var arg = list[i]; | |||
c(arg, 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) { | |||
if (node.exported) | |||
{ c(node.exported, st); } | |||
c(node.source, st, "Expression"); | |||
}; | |||
base.ImportDeclaration = function (node, st, c) { | |||
for (var i = 0, list = node.specifiers; i < list.length; i += 1) | |||
{ | |||
var spec = list[i]; | |||
c(spec, st); | |||
} | |||
c(node.source, st, "Expression"); | |||
}; | |||
base.ImportExpression = function (node, st, c) { | |||
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, "Expression"); | |||
}; | |||
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"); } | |||
c(node.body, st); | |||
}; | |||
base.ClassBody = function (node, st, c) { | |||
for (var i = 0, list = node.body; i < list.length; i += 1) | |||
{ | |||
var elt = list[i]; | |||
c(elt, st); | |||
} | |||
}; | |||
base.MethodDefinition = base.Property = function (node, st, c) { | |||
if (node.computed) { c(node.key, st, "Expression"); } | |||
c(node.value, st, "Expression"); | |||
}; | |||
exports.ancestor = ancestor; | |||
exports.base = base; | |||
exports.findNodeAfter = findNodeAfter; | |||
exports.findNodeAround = findNodeAround; | |||
exports.findNodeAt = findNodeAt; | |||
exports.findNodeBefore = findNodeBefore; | |||
exports.full = full; | |||
exports.fullAncestor = fullAncestor; | |||
exports.make = make; | |||
exports.recursive = recursive; | |||
exports.simple = simple; | |||
Object.defineProperty(exports, '__esModule', { value: true }); | |||
}))); |
@ -0,0 +1,443 @@ | |||
// 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 and | |||
// Statement, 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. | |||
function simple(node, visitors, baseVisitor, state, override) { | |||
if (!baseVisitor) { baseVisitor = base | |||
; }(function c(node, st, override) { | |||
var type = override || node.type, found = visitors[type]; | |||
baseVisitor[type](node, st, c); | |||
if (found) { found(node, st); } | |||
})(node, state, override); | |||
} | |||
// An ancestor walk keeps an array of ancestor nodes (including the | |||
// current node) and passes them to the callback as third parameter | |||
// (and also as state parameter when no other state is present). | |||
function ancestor(node, visitors, baseVisitor, state, override) { | |||
var ancestors = []; | |||
if (!baseVisitor) { baseVisitor = base | |||
; }(function c(node, st, override) { | |||
var type = override || node.type, found = visitors[type]; | |||
var isNew = node !== ancestors[ancestors.length - 1]; | |||
if (isNew) { ancestors.push(node); } | |||
baseVisitor[type](node, st, c); | |||
if (found) { found(node, st || ancestors, ancestors); } | |||
if (isNew) { ancestors.pop(); } | |||
})(node, state, override); | |||
} | |||
// 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, baseVisitor, override) { | |||
var visitor = funcs ? make(funcs, baseVisitor || undefined) : baseVisitor | |||
;(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) { this.node = node; this.state = state; }; | |||
// A full walk triggers the callback on each node | |||
function full(node, callback, baseVisitor, state, override) { | |||
if (!baseVisitor) { baseVisitor = base | |||
; }(function c(node, st, override) { | |||
var type = override || node.type; | |||
baseVisitor[type](node, st, c); | |||
if (!override) { callback(node, st, type); } | |||
})(node, state, override); | |||
} | |||
// An fullAncestor walk is like an ancestor walk, but triggers | |||
// the callback on each node | |||
function fullAncestor(node, callback, baseVisitor, state) { | |||
if (!baseVisitor) { baseVisitor = base; } | |||
var ancestors = [] | |||
;(function c(node, st, override) { | |||
var type = override || node.type; | |||
var isNew = node !== ancestors[ancestors.length - 1]; | |||
if (isNew) { ancestors.push(node); } | |||
baseVisitor[type](node, st, c); | |||
if (!override) { callback(node, st || ancestors, ancestors, type); } | |||
if (isNew) { ancestors.pop(); } | |||
})(node, 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, baseVisitor, state) { | |||
if (!baseVisitor) { baseVisitor = base; } | |||
test = makeTest(test); | |||
try { | |||
(function c(node, st, override) { | |||
var type = override || node.type; | |||
if ((start == null || node.start <= start) && | |||
(end == null || node.end >= end)) | |||
{ baseVisitor[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, baseVisitor, state) { | |||
test = makeTest(test); | |||
if (!baseVisitor) { baseVisitor = base; } | |||
try { | |||
(function c(node, st, override) { | |||
var type = override || node.type; | |||
if (node.start > pos || node.end < pos) { return } | |||
baseVisitor[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, baseVisitor, state) { | |||
test = makeTest(test); | |||
if (!baseVisitor) { baseVisitor = 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) } | |||
baseVisitor[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, baseVisitor, state) { | |||
test = makeTest(test); | |||
if (!baseVisitor) { baseVisitor = base; } | |||
var max | |||
;(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); } | |||
baseVisitor[type](node, st, c); | |||
})(node, state); | |||
return max | |||
} | |||
// Fallback to an Object.create polyfill for older environments. | |||
var create = Object.create || function(proto) { | |||
function Ctor() {} | |||
Ctor.prototype = proto; | |||
return new Ctor | |||
}; | |||
// Used to create a custom walker. Will fill in all missing node | |||
// type properties with the defaults. | |||
function make(funcs, baseVisitor) { | |||
var visitor = create(baseVisitor || base); | |||
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 = {}; | |||
base.Program = base.BlockStatement = function (node, st, c) { | |||
for (var i = 0, list = node.body; i < list.length; i += 1) | |||
{ | |||
var stmt = list[i]; | |||
c(stmt, st, "Statement"); | |||
} | |||
}; | |||
base.Statement = skipThrough; | |||
base.EmptyStatement = ignore; | |||
base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = | |||
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$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) { | |||
var cs = list$1[i$1]; | |||
if (cs.test) { c(cs.test, st, "Expression"); } | |||
for (var i = 0, list = cs.consequent; i < list.length; i += 1) | |||
{ | |||
var cons = list[i]; | |||
c(cons, st, "Statement"); | |||
} | |||
} | |||
}; | |||
base.SwitchCase = function (node, st, c) { | |||
if (node.test) { c(node.test, st, "Expression"); } | |||
for (var i = 0, list = node.consequent; i < list.length; i += 1) | |||
{ | |||
var cons = list[i]; | |||
c(cons, st, "Statement"); | |||
} | |||
}; | |||
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = 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, st); } | |||
if (node.finalizer) { c(node.finalizer, st, "Statement"); } | |||
}; | |||
base.CatchClause = function (node, st, c) { | |||
if (node.param) { c(node.param, st, "Pattern"); } | |||
c(node.body, 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, list = node.declarations; i < list.length; i += 1) | |||
{ | |||
var decl = list[i]; | |||
c(decl, 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, list = node.params; i < list.length; i += 1) | |||
{ | |||
var param = list[i]; | |||
c(param, st, "Pattern"); | |||
} | |||
c(node.body, st, node.expression ? "Expression" : "Statement"); | |||
}; | |||
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, list = node.elements; i < list.length; i += 1) { | |||
var elt = list[i]; | |||
if (elt) { c(elt, st, "Pattern"); } | |||
} | |||
}; | |||
base.ObjectPattern = function (node, st, c) { | |||
for (var i = 0, list = node.properties; i < list.length; i += 1) { | |||
var prop = list[i]; | |||
if (prop.type === "Property") { | |||
if (prop.computed) { c(prop.key, st, "Expression"); } | |||
c(prop.value, st, "Pattern"); | |||
} else if (prop.type === "RestElement") { | |||
c(prop.argument, st, "Pattern"); | |||
} | |||
} | |||
}; | |||
base.Expression = skipThrough; | |||
base.ThisExpression = base.Super = base.MetaProperty = ignore; | |||
base.ArrayExpression = function (node, st, c) { | |||
for (var i = 0, list = node.elements; i < list.length; i += 1) { | |||
var elt = list[i]; | |||
if (elt) { c(elt, st, "Expression"); } | |||
} | |||
}; | |||
base.ObjectExpression = function (node, st, c) { | |||
for (var i = 0, list = node.properties; i < list.length; i += 1) | |||
{ | |||
var prop = list[i]; | |||
c(prop, st); | |||
} | |||
}; | |||
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; | |||
base.SequenceExpression = function (node, st, c) { | |||
for (var i = 0, list = node.expressions; i < list.length; i += 1) | |||
{ | |||
var expr = list[i]; | |||
c(expr, st, "Expression"); | |||
} | |||
}; | |||
base.TemplateLiteral = function (node, st, c) { | |||
for (var i = 0, list = node.quasis; i < list.length; i += 1) | |||
{ | |||
var quasi = list[i]; | |||
c(quasi, st); | |||
} | |||
for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1) | |||
{ | |||
var expr = list$1[i$1]; | |||
c(expr, st, "Expression"); | |||
} | |||
}; | |||
base.TemplateElement = ignore; | |||
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, list = node.arguments; i < list.length; i += 1) | |||
{ | |||
var arg = list[i]; | |||
c(arg, 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) { | |||
if (node.exported) | |||
{ c(node.exported, st); } | |||
c(node.source, st, "Expression"); | |||
}; | |||
base.ImportDeclaration = function (node, st, c) { | |||
for (var i = 0, list = node.specifiers; i < list.length; i += 1) | |||
{ | |||
var spec = list[i]; | |||
c(spec, st); | |||
} | |||
c(node.source, st, "Expression"); | |||
}; | |||
base.ImportExpression = function (node, st, c) { | |||
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, "Expression"); | |||
}; | |||
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"); } | |||
c(node.body, st); | |||
}; | |||
base.ClassBody = function (node, st, c) { | |||
for (var i = 0, list = node.body; i < list.length; i += 1) | |||
{ | |||
var elt = list[i]; | |||
c(elt, st); | |||
} | |||
}; | |||
base.MethodDefinition = base.Property = function (node, st, c) { | |||
if (node.computed) { c(node.key, st, "Expression"); } | |||
c(node.value, st, "Expression"); | |||
}; | |||
export { ancestor, base, findNodeAfter, findNodeAround, findNodeAt, findNodeBefore, full, fullAncestor, make, recursive, simple }; |
@ -0,0 +1,64 @@ | |||
{ | |||
"_from": "acorn-walk@^7.1.1", | |||
"_id": "acorn-walk@7.2.0", | |||
"_inBundle": false, | |||
"_integrity": "sha512-OPdCF6GsMIP+Az+aWfAAOEt2/+iVDKE7oy6lJ098aoe59oAmK76qV6Gw60SbZ8jHuG2wH058GF4pLFbYamYrVA==", | |||
"_location": "/acorn-walk", | |||
"_phantomChildren": {}, | |||
"_requested": { | |||
"type": "range", | |||
"registry": true, | |||
"raw": "acorn-walk@^7.1.1", | |||
"name": "acorn-walk", | |||
"escapedName": "acorn-walk", | |||
"rawSpec": "^7.1.1", | |||
"saveSpec": null, | |||
"fetchSpec": "^7.1.1" | |||
}, | |||
"_requiredBy": [ | |||
"/acorn-globals" | |||
], | |||
"_resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-7.2.0.tgz", | |||
"_shasum": "0de889a601203909b0fbe07b8938dc21d2e967bc", | |||
"_spec": "acorn-walk@^7.1.1", | |||
"_where": "/home/alpcentaur/ProjektA/PermApp/node_modules/acorn-globals", | |||
"bugs": { | |||
"url": "https://github.com/acornjs/acorn/issues" | |||
}, | |||
"bundleDependencies": false, | |||
"deprecated": false, | |||
"description": "ECMAScript (ESTree) AST walker", | |||
"engines": { | |||
"node": ">=0.4.0" | |||
}, | |||
"homepage": "https://github.com/acornjs/acorn", | |||
"license": "MIT", | |||
"main": "dist/walk.js", | |||
"maintainers": [ | |||
{ | |||
"name": "Marijn Haverbeke", | |||
"email": "marijnh@gmail.com", | |||
"url": "https://marijnhaverbeke.nl" | |||
}, | |||
{ | |||
"name": "Ingvar Stepanyan", | |||
"email": "me@rreverser.com", | |||
"url": "https://rreverser.com/" | |||
}, | |||
{ | |||
"name": "Adrian Heine", | |||
"url": "http://adrianheine.de" | |||
} | |||
], | |||
"module": "dist/walk.mjs", | |||
"name": "acorn-walk", | |||
"repository": { | |||
"type": "git", | |||
"url": "git+https://github.com/acornjs/acorn.git" | |||
}, | |||
"scripts": { | |||
"prepare": "cd ..; npm run build:walk" | |||
}, | |||
"types": "dist/walk.d.ts", | |||
"version": "7.2.0" | |||
} |
@ -0,0 +1,620 @@ | |||
## 7.4.0 (2020-08-03) | |||
### New features | |||
Add support for logical assignment operators. | |||
Add support for numeric separators. | |||
## 7.3.1 (2020-06-11) | |||
### Bug fixes | |||
Make the string in the `version` export match the actual library version. | |||
## 7.3.0 (2020-06-11) | |||
### Bug fixes | |||
Fix a bug that caused parsing of object patterns with a property named `set` that had a default value to fail. | |||
### New features | |||
Add support for optional chaining (`?.`). | |||
## 7.2.0 (2020-05-09) | |||
### Bug fixes | |||
Fix precedence issue in parsing of async arrow functions. | |||
### New features | |||
Add support for nullish coalescing. | |||
Add support for `import.meta`. | |||
Support `export * as ...` syntax. | |||
Upgrade to Unicode 13. | |||
## 6.4.1 (2020-03-09) | |||
### Bug fixes | |||
More carefully check for valid UTF16 surrogate pairs in regexp validator. | |||
## 7.1.1 (2020-03-01) | |||
### Bug fixes | |||
Treat `\8` and `\9` as invalid escapes in template strings. | |||
Allow unicode escapes in property names that are keywords. | |||
Don't error on an exponential operator expression as argument to `await`. | |||
More carefully check for valid UTF16 surrogate pairs in regexp validator. | |||
## 7.1.0 (2019-09-24) | |||
### Bug fixes | |||
Disallow trailing object literal commas when ecmaVersion is less than 5. | |||
### New features | |||
Add a static `acorn` property to the `Parser` class that contains the entire module interface, to allow plugins to access the instance of the library that they are acting on. | |||
## 7.0.0 (2019-08-13) | |||
### Breaking changes | |||
Changes the node format for dynamic imports to use the `ImportExpression` node type, as defined in [ESTree](https://github.com/estree/estree/blob/master/es2020.md#importexpression). | |||
Makes 10 (ES2019) the default value for the `ecmaVersion` option. | |||
## 6.3.0 (2019-08-12) | |||
### New features | |||
`sourceType: "module"` can now be used even when `ecmaVersion` is less than 6, to parse module-style code that otherwise conforms to an older standard. | |||
## 6.2.1 (2019-07-21) | |||
### Bug fixes | |||
Fix bug causing Acorn to treat some characters as identifier characters that shouldn't be treated as such. | |||
Fix issue where setting the `allowReserved` option to `"never"` allowed reserved words in some circumstances. | |||
## 6.2.0 (2019-07-04) | |||
### Bug fixes | |||
Improve valid assignment checking in `for`/`in` and `for`/`of` loops. | |||
Disallow binding `let` in patterns. | |||
### New features | |||
Support bigint syntax with `ecmaVersion` >= 11. | |||
Support dynamic `import` syntax with `ecmaVersion` >= 11. | |||
Upgrade to Unicode version 12. | |||
## 6.1.1 (2019-02-27) | |||
### Bug fixes | |||
Fix bug that caused parsing default exports of with names to fail. | |||
## 6.1.0 (2019-02-08) | |||
### Bug fixes | |||
Fix scope checking when redefining a `var` as a lexical binding. | |||
### New features | |||
Split up `parseSubscripts` to use an internal `parseSubscript` method to make it easier to extend with plugins. | |||
## 6.0.7 (2019-02-04) | |||
### Bug fixes | |||
Check that exported bindings are defined. | |||
Don't treat `\u180e` as a whitespace character. | |||
Check for duplicate parameter names in methods. | |||
Don't allow shorthand properties when they are generators or async methods. | |||
Forbid binding `await` in async arrow function's parameter list. | |||
## 6.0.6 (2019-01-30) | |||
### Bug fixes | |||
The content of class declarations and expressions is now always parsed in strict mode. | |||
Don't allow `let` or `const` to bind the variable name `let`. | |||
Treat class declarations as lexical. | |||
Don't allow a generator function declaration as the sole body of an `if` or `else`. | |||
Ignore `"use strict"` when after an empty statement. | |||
Allow string line continuations with special line terminator characters. | |||
Treat `for` bodies as part of the `for` scope when checking for conflicting bindings. | |||
Fix bug with parsing `yield` in a `for` loop initializer. | |||
Implement special cases around scope checking for functions. | |||
## 6.0.5 (2019-01-02) | |||
### Bug fixes | |||
Fix TypeScript type for `Parser.extend` and add `allowAwaitOutsideFunction` to options type. | |||
Don't treat `let` as a keyword when the next token is `{` on the next line. | |||
Fix bug that broke checking for parentheses around an object pattern in a destructuring assignment when `preserveParens` was on. | |||
## 6.0.4 (2018-11-05) | |||
### Bug fixes | |||
Further improvements to tokenizing regular expressions in corner cases. | |||
## 6.0.3 (2018-11-04) | |||
### Bug fixes | |||
Fix bug in tokenizing an expression-less return followed by a function followed by a regular expression. | |||
Remove stray symlink in the package tarball. | |||
## 6.0.2 (2018-09-26) | |||
### Bug fixes | |||
Fix bug where default expressions could fail to parse inside an object destructuring assignment expression. | |||
## 6.0.1 (2018-09-14) | |||
### Bug fixes | |||
Fix wrong value in `version` export. | |||
## 6.0.0 (2018-09-14) | |||
### Bug fixes | |||
Better handle variable-redefinition checks for catch bindings and functions directly under if statements. | |||
Forbid `new.target` in top-level arrow functions. | |||
Fix issue with parsing a regexp after `yield` in some contexts. | |||
### New features | |||
The package now comes with TypeScript definitions. | |||
### Breaking changes | |||
The default value of the `ecmaVersion` option is now 9 (2018). | |||
Plugins work differently, and will have to be rewritten to work with this version. | |||
The loose parser and walker have been moved into separate packages (`acorn-loose` and `acorn-walk`). | |||
## 5.7.3 (2018-09-10) | |||
### Bug fixes | |||
Fix failure to tokenize regexps after expressions like `x.of`. | |||
Better error message for unterminated template literals. | |||
## 5.7.2 (2018-08-24) | |||
### Bug fixes | |||
Properly handle `allowAwaitOutsideFunction` in for statements. | |||
Treat function declarations at the top level of modules like let bindings. | |||
Don't allow async function declarations as the only statement under a label. | |||
## 5.7.0 (2018-06-15) | |||
### New features | |||
Upgraded to Unicode 11. | |||
## 5.6.0 (2018-05-31) | |||
### New features | |||
Allow U+2028 and U+2029 in string when ECMAVersion >= 10. | |||
Allow binding-less catch statements when ECMAVersion >= 10. | |||
Add `allowAwaitOutsideFunction` option for parsing top-level `await`. | |||
## 5.5.3 (2018-03-08) | |||
### Bug fixes | |||
A _second_ republish of the code in 5.5.1, this time with yarn, to hopefully get valid timestamps. | |||
## 5.5.2 (2018-03-08) | |||
### Bug fixes | |||
A republish of the code in 5.5.1 in an attempt to solve an issue with the file timestamps in the npm package being 0. | |||
## 5.5.1 (2018-03-06) | |||
### Bug fixes | |||
Fix misleading error message for octal escapes in template strings. | |||
## 5.5.0 (2018-02-27) | |||
### New features | |||
The identifier character categorization is now based on Unicode version 10. | |||
Acorn will now validate the content of regular expressions, including new ES9 features. | |||
## 5.4.0 (2018-02-01) | |||
### Bug fixes | |||
Disallow duplicate or escaped flags on regular expressions. | |||
Disallow octal escapes in strings in strict mode. | |||
### New features | |||
Add support for async iteration. | |||
Add support for object spread and rest. | |||
## 5.3.0 (2017-12-28) | |||
### Bug fixes | |||
Fix parsing of floating point literals with leading zeroes in loose mode. | |||
Allow duplicate property names in object patterns. | |||
Don't allow static class methods named `prototype`. | |||
Disallow async functions directly under `if` or `else`. | |||
Parse right-hand-side of `for`/`of` as an assignment expression. | |||
Stricter parsing of `for`/`in`. | |||
Don't allow unicode escapes in contextual keywords. | |||
### New features | |||
Parsing class members was factored into smaller methods to allow plugins to hook into it. | |||
## 5.2.1 (2017-10-30) | |||
### Bug fixes | |||
Fix a token context corruption bug. | |||
## 5.2.0 (2017-10-30) | |||
### Bug fixes | |||
Fix token context tracking for `class` and `function` in property-name position. | |||
Make sure `%*` isn't parsed as a valid operator. | |||
Allow shorthand properties `get` and `set` to be followed by default values. | |||
Disallow `super` when not in callee or object position. | |||
### New features | |||
Support [`directive` property](https://github.com/estree/estree/compare/b3de58c9997504d6fba04b72f76e6dd1619ee4eb...1da8e603237144f44710360f8feb7a9977e905e0) on directive expression statements. | |||
## 5.1.2 (2017-09-04) | |||
### Bug fixes | |||
Disable parsing of legacy HTML-style comments in modules. | |||
Fix parsing of async methods whose names are keywords. | |||
## 5.1.1 (2017-07-06) | |||
### Bug fixes | |||
Fix problem with disambiguating regexp and division after a class. | |||
## 5.1.0 (2017-07-05) | |||
### Bug fixes | |||
Fix tokenizing of regexps in an object-desctructuring `for`/`of` loop and after `yield`. | |||
Parse zero-prefixed numbers with non-octal digits as decimal. | |||
Allow object/array patterns in rest parameters. | |||
Don't error when `yield` is used as a property name. | |||
Allow `async` as a shorthand object property. | |||
### New features | |||
Implement the [template literal revision proposal](https://github.com/tc39/proposal-template-literal-revision) for ES9. | |||
## 5.0.3 (2017-04-01) | |||
### Bug fixes | |||
Fix spurious duplicate variable definition errors for named functions. | |||
## 5.0.2 (2017-03-30) | |||
### Bug fixes | |||
A binary operator after a parenthesized arrow expression is no longer incorrectly treated as an error. | |||
## 5.0.0 (2017-03-28) | |||
### Bug fixes | |||
Raise an error for duplicated lexical bindings. | |||
Fix spurious error when an assignement expression occurred after a spread expression. | |||
Accept regular expressions after `of` (in `for`/`of`), `yield` (in a generator), and braced arrow functions. | |||
Allow labels in front or `var` declarations, even in strict mode. | |||
### Breaking changes | |||
Parse declarations following `export default` as declaration nodes, not expressions. This means that class and function declarations nodes can now have `null` as their `id`. | |||
## 4.0.11 (2017-02-07) | |||
### Bug fixes | |||
Allow all forms of member expressions to be parenthesized as lvalue. | |||
## 4.0.10 (2017-02-07) | |||
### Bug fixes | |||
Don't expect semicolons after default-exported functions or classes, even when they are expressions. | |||
Check for use of `'use strict'` directives in non-simple parameter functions, even when already in strict mode. | |||
## 4.0.9 (2017-02-06) | |||
### Bug fixes | |||
Fix incorrect error raised for parenthesized simple assignment targets, so that `(x) = 1` parses again. | |||
## 4.0.8 (2017-02-03) | |||
### Bug fixes | |||
Solve spurious parenthesized pattern errors by temporarily erring on the side of accepting programs that our delayed errors don't handle correctly yet. | |||
## 4.0.7 (2017-02-02) | |||
### Bug fixes | |||
Accept invalidly rejected code like `(x).y = 2` again. | |||
Don't raise an error when a function _inside_ strict code has a non-simple parameter list. | |||
## 4.0.6 (2017-02-02) | |||
### Bug fixes | |||
Fix exponential behavior (manifesting itself as a complete hang for even relatively small source files) introduced by the new 'use strict' check. | |||
## 4.0.5 (2017-02-02) | |||
### Bug fixes | |||
Disallow parenthesized pattern expressions. | |||
Allow keywords as export names. | |||
Don't allow the `async` keyword to be parenthesized. | |||
Properly raise an error when a keyword contains a character escape. | |||
Allow `"use strict"` to appear after other string literal expressions. | |||
Disallow labeled declarations. | |||
## 4.0.4 (2016-12-19) | |||
### Bug fixes | |||
Fix crash when `export` was followed by a keyword that can't be | |||
exported. | |||
## 4.0.3 (2016-08-16) | |||
### Bug fixes | |||
Allow regular function declarations inside single-statement `if` branches in loose mode. Forbid them entirely in strict mode. | |||
Properly parse properties named `async` in ES2017 mode. | |||
Fix bug where reserved words were broken in ES2017 mode. | |||
## 4.0.2 (2016-08-11) | |||
### Bug fixes | |||
Don't ignore period or 'e' characters after octal numbers. | |||
Fix broken parsing for call expressions in default parameter values of arrow functions. | |||
## 4.0.1 (2016-08-08) | |||
### Bug fixes | |||
Fix false positives in duplicated export name errors. | |||
## 4.0.0 (2016-08-07) | |||
### Breaking changes | |||
The default `ecmaVersion` option value is now 7. | |||
A number of internal method signatures changed, so plugins might need to be updated. | |||
### Bug fixes | |||
The parser now raises errors on duplicated export names. | |||
`arguments` and `eval` can now be used in shorthand properties. | |||
Duplicate parameter names in non-simple argument lists now always produce an error. | |||
### New features | |||
The `ecmaVersion` option now also accepts year-style version numbers | |||
(2015, etc). | |||
Support for `async`/`await` syntax when `ecmaVersion` is >= 8. | |||
Support for trailing commas in call expressions when `ecmaVersion` is >= 8. | |||
## 3.3.0 (2016-07-25) | |||
### Bug fixes | |||
Fix bug in tokenizing of regexp operator after a function declaration. | |||
Fix parser crash when parsing an array pattern with a hole. | |||
### New features | |||
Implement check against complex argument lists in functions that enable strict mode in ES7. | |||
## 3.2.0 (2016-06-07) | |||
### Bug fixes | |||
Improve handling of lack of unicode regexp support in host | |||
environment. | |||
Properly reject shorthand properties whose name is a keyword. | |||
### New features | |||
Visitors created with `visit.make` now have their base as _prototype_, rather than copying properties into a fresh object. | |||
## 3.1.0 (2016-04-18) | |||
### Bug fixes | |||
Properly tokenize the division operator directly after a function expression. | |||
Allow trailing comma in destructuring arrays. | |||
## 3.0.4 (2016-02-25) | |||
### Fixes | |||
Allow update expressions as left-hand-side of the ES7 exponential operator. | |||
## 3.0.2 (2016-02-10) | |||
### Fixes | |||
Fix bug that accidentally made `undefined` a reserved word when parsing ES7. | |||
## 3.0.0 (2016-02-10) | |||
### Breaking changes | |||
The default value of the `ecmaVersion` option is now 6 (used to be 5). | |||
Support for comprehension syntax (which was dropped from the draft spec) has been removed. | |||
### Fixes | |||
`let` and `yield` are now “contextual keywords”, meaning you can mostly use them as identifiers in ES5 non-strict code. | |||
A parenthesized class or function expression after `export default` is now parsed correctly. | |||
### New features | |||
When `ecmaVersion` is set to 7, Acorn will parse the exponentiation operator (`**`). | |||
The identifier character ranges are now based on Unicode 8.0.0. | |||
Plugins can now override the `raiseRecoverable` method to override the way non-critical errors are handled. | |||
## 2.7.0 (2016-01-04) | |||
### Fixes | |||
Stop allowing rest parameters in setters. | |||
Disallow `y` rexexp flag in ES5. | |||
Disallow `\00` and `\000` escapes in strict mode. | |||
Raise an error when an import name is a reserved word. | |||
## 2.6.2 (2015-11-10) | |||
### Fixes | |||
Don't crash when no options object is passed. | |||
## 2.6.0 (2015-11-09) | |||
### Fixes | |||
Add `await` as a reserved word in module sources. | |||
Disallow `yield` in a parameter default value for a generator. | |||
Forbid using a comma after a rest pattern in an array destructuring. | |||
### New features | |||
Support parsing stdin in command-line tool. | |||
## 2.5.0 (2015-10-27) | |||
### Fixes | |||
Fix tokenizer support in the command-line tool. | |||
Stop allowing `new.target` outside of functions. | |||
Remove legacy `guard` and `guardedHandler` properties from try nodes. | |||
Stop allowing multiple `__proto__` properties on an object literal in strict mode. | |||
Don't allow rest parameters to be non-identifier patterns. | |||
Check for duplicate paramter names in arrow functions. |
@ -0,0 +1,21 @@ | |||
MIT License | |||
Copyright (C) 2012-2018 by various contributors (see AUTHORS) | |||
Permission is hereby granted, free of charge, to any person obtaining a copy | |||
of this software and associated documentation files (the "Software"), to deal | |||
in the Software without restriction, including without limitation the rights | |||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |||
copies of the Software, and to permit persons to whom the Software is | |||
furnished to do so, subject to the following conditions: | |||
The above copyright notice and this permission notice shall be included in | |||
all copies or substantial portions of the Software. | |||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |||
THE SOFTWARE. |
@ -0,0 +1,269 @@ | |||
# Acorn | |||
A tiny, fast JavaScript parser written in JavaScript. | |||
## Community | |||
Acorn is open source software released under an | |||
[MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE). | |||
You are welcome to | |||
[report bugs](https://github.com/acornjs/acorn/issues) or create pull | |||
requests on [github](https://github.com/acornjs/acorn). For questions | |||
and discussion, please use the | |||
[Tern discussion forum](https://discuss.ternjs.net). | |||
## Installation | |||
The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): | |||
```sh | |||
npm install acorn | |||
``` | |||
Alternately, you can download the source and build acorn yourself: | |||
```sh | |||
git clone https://github.com/acornjs/acorn.git | |||
cd acorn | |||
npm install | |||
``` | |||
## Interface | |||
**parse**`(input, options)` is the main interface to the library. The | |||
`input` parameter is a string, `options` can be undefined or an object | |||
setting some of the options listed below. The return value will be an | |||
abstract syntax tree object as specified by the [ESTree | |||
spec](https://github.com/estree/estree). | |||
```javascript | |||
let acorn = require("acorn"); | |||
console.log(acorn.parse("1 + 1")); | |||
``` | |||
When encountering a syntax error, the parser will raise a | |||
`SyntaxError` object with a meaningful message. The error object will | |||
have a `pos` property that indicates the string offset at which the | |||
error occurred, and a `loc` object that contains a `{line, column}` | |||
object referring to that same position. | |||
Options can be provided by passing a second argument, which should be | |||
an object containing any of these fields: | |||
- **ecmaVersion**: Indicates the ECMAScript version to parse. Must be | |||
either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), 10 (2019) or 11 | |||
(2020, partial support). This influences support for strict mode, | |||
the set of reserved words, and support for new syntax features. | |||
Default is 10. | |||
**NOTE**: Only 'stage 4' (finalized) ECMAScript features are being | |||
implemented by Acorn. Other proposed new features can be implemented | |||
through plugins. | |||
- **sourceType**: Indicate the mode the code should be parsed in. Can be | |||
either `"script"` or `"module"`. This influences global strict mode | |||
and parsing of `import` and `export` declarations. | |||
**NOTE**: If set to `"module"`, then static `import` / `export` syntax | |||
will be valid, even if `ecmaVersion` is less than 6. | |||
- **onInsertedSemicolon**: If given a callback, that callback will be | |||
called whenever a missing semicolon is inserted by the parser. The | |||
callback will be given the character offset of the point where the | |||
semicolon is inserted as argument, and if `locations` is on, also a | |||
`{line, column}` object representing this position. | |||
- **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing | |||
commas. | |||
- **allowReserved**: If `false`, using a reserved word will generate | |||
an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher | |||
versions. When given the value `"never"`, reserved words and | |||
keywords can also not be used as property names (as in Internet | |||
Explorer's old parser). | |||
- **allowReturnOutsideFunction**: By default, a return statement at | |||
the top level raises an error. Set this to `true` to accept such | |||
code. | |||
- **allowImportExportEverywhere**: By default, `import` and `export` | |||
declarations can only appear at a program's top level. Setting this | |||
option to `true` allows them anywhere where a statement is allowed. | |||
- **allowAwaitOutsideFunction**: By default, `await` expressions can | |||
only appear inside `async` functions. Setting this option to | |||
`true` allows to have top-level `await` expressions. They are | |||
still not allowed in non-`async` functions, though. | |||
- **allowHashBang**: When this is enabled (off by default), if the | |||
code starts with the characters `#!` (as in a shellscript), the | |||
first line will be treated as a comment. | |||
- **locations**: When `true`, each node has a `loc` object attached | |||
with `start` and `end` subobjects, each of which contains the | |||
one-based line and zero-based column numbers in `{line, column}` | |||
form. Default is `false`. | |||
- **onToken**: If a function is passed for this option, each found | |||
token will be passed in same format as tokens returned from | |||
`tokenizer().getToken()`. | |||
If array is passed, each found token is pushed to it. | |||
Note that you are not allowed to call the parser from the | |||
callback—that will corrupt its internal state. | |||
- **onComment**: If a function is passed for this option, whenever a | |||
comment is encountered the function will be called with the | |||
following parameters: | |||
- `block`: `true` if the comment is a block comment, false if it | |||
is a line comment. | |||
- `text`: The content of the comment. | |||
- `start`: Character offset of the start of the comment. | |||
- `end`: Character offset of the end of the comment. | |||
When the `locations` options is on, the `{line, column}` locations | |||
of the comment’s start and end are passed as two additional | |||
parameters. | |||
If array is passed for this option, each found comment is pushed | |||
to it as object in Esprima format: | |||
```javascript | |||
{ | |||
"type": "Line" | "Block", | |||
"value": "comment text", | |||
"start": Number, | |||
"end": Number, | |||
// If `locations` option is on: | |||
"loc": { | |||
"start": {line: Number, column: Number} | |||
"end": {line: Number, column: Number} | |||
}, | |||
// If `ranges` option is on: | |||
"range": [Number, Number] | |||
} | |||
``` | |||
Note that you are not allowed to call the parser from the | |||
callback—that will corrupt its internal state. | |||
- **ranges**: 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](https://bugzilla.mozilla.org/show_bug.cgi?id=745678) | |||
`range` property holding a `[start, end]` array with the same | |||
numbers, set the `ranges` option to `true`. | |||
- **program**: It is possible to parse multiple files into a single | |||
AST by passing the tree produced by parsing the first file as the | |||
`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. | |||
- **sourceFile**: When the `locations` option is `true`, you can pass | |||
this option to add a `source` attribute in every node’s `loc` | |||
object. Note that the contents of this option are not examined or | |||
processed in any way; you are free to use whatever format you | |||
choose. | |||
- **directSourceFile**: Like `sourceFile`, but a `sourceFile` property | |||
will be added (regardless of the `location` option) directly to the | |||
nodes, rather than the `loc` object. | |||
- **preserveParens**: If this option is `true`, parenthesized expressions | |||
are represented by (non-standard) `ParenthesizedExpression` nodes | |||
that have a single `expression` property containing the expression | |||
inside parentheses. | |||
**parseExpressionAt**`(input, offset, options)` will parse a single | |||
expression in a string, and return its AST. It will not complain if | |||
there is more of the string left after the expression. | |||
**tokenizer**`(input, options)` returns an object with a `getToken` | |||
method that can be called repeatedly to get the next token, a `{start, | |||
end, type, value}` object (with added `loc` property when the | |||
`locations` option is enabled and `range` property when the `ranges` | |||
option is enabled). When the token's type is `tokTypes.eof`, you | |||
should stop calling the method, since it will keep returning that same | |||
token forever. | |||
In ES6 environment, returned result can be used as any other | |||
protocol-compliant iterable: | |||
```javascript | |||
for (let token of acorn.tokenizer(str)) { | |||
// iterate over the tokens | |||
} | |||
// transform code to array of tokens: | |||
var tokens = [...acorn.tokenizer(str)]; | |||
``` | |||
**tokTypes** holds an object mapping names to the token type objects | |||
that end up in the `type` properties of tokens. | |||
**getLineInfo**`(input, offset)` can be used to get a `{line, | |||
column}` object for a given program string and offset. | |||
### The `Parser` class | |||
Instances of the **`Parser`** class contain all the state and logic | |||
that drives a parse. It has static methods `parse`, | |||
`parseExpressionAt`, and `tokenizer` that match the top-level | |||
functions by the same name. | |||
When extending the parser with plugins, you need to call these methods | |||
on the extended version of the class. To extend a parser with plugins, | |||
you can use its static `extend` method. | |||
```javascript | |||
var acorn = require("acorn"); | |||
var jsx = require("acorn-jsx"); | |||
var JSXParser = acorn.Parser.extend(jsx()); | |||
JSXParser.parse("foo(<bar/>)"); | |||
``` | |||
The `extend` method takes any number of plugin values, and returns a | |||
new `Parser` class that includes the extra parser logic provided by | |||
the plugins. | |||
## Command line interface | |||
The `bin/acorn` utility can be used to parse a file from the command | |||
line. It accepts as arguments its input file and the following | |||
options: | |||
- `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version | |||
to parse. Default is version 9. | |||
- `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. | |||
- `--locations`: Attaches a "loc" object to each node with "start" and | |||
"end" subobjects, each of which contains the one-based line and | |||
zero-based column numbers in `{line, column}` form. | |||
- `--allow-hash-bang`: If the code starts with the characters #! (as | |||
in a shellscript), the first line will be treated as a comment. | |||
- `--compact`: No whitespace is used in the AST output. | |||
- `--silent`: Do not output the AST, just return the exit status. | |||
- `--help`: Print the usage information and quit. | |||
The utility spits out the syntax tree as JSON data. | |||
## Existing plugins | |||
- [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) | |||
Plugins for ECMAScript proposals: | |||
- [`acorn-stage3`](https://github.com/acornjs/acorn-stage3): Parse most stage 3 proposals, bundling: | |||
- [`acorn-class-fields`](https://github.com/acornjs/acorn-class-fields): Parse [class fields proposal](https://github.com/tc39/proposal-class-fields) | |||
- [`acorn-import-meta`](https://github.com/acornjs/acorn-import-meta): Parse [import.meta proposal](https://github.com/tc39/proposal-import-meta) | |||
- [`acorn-private-methods`](https://github.com/acornjs/acorn-private-methods): parse [private methods, getters and setters proposal](https://github.com/tc39/proposal-private-methods)n |
@ -0,0 +1,4 @@ | |||
#!/usr/bin/env node | |||
'use strict'; | |||
require('../dist/bin.js'); |
@ -0,0 +1,209 @@ | |||
export as namespace acorn | |||
export = acorn | |||
declare namespace acorn { | |||
function parse(input: string, options?: Options): Node | |||
function parseExpressionAt(input: string, pos?: number, options?: Options): Node | |||
function tokenizer(input: string, options?: Options): { | |||
getToken(): Token | |||
[Symbol.iterator](): Iterator<Token> | |||
} | |||
interface Options { | |||
ecmaVersion?: 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | |||
sourceType?: 'script' | 'module' | |||
onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: Position) => void | |||
onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: Position) => void | |||
allowReserved?: boolean | 'never' | |||
allowReturnOutsideFunction?: boolean | |||
allowImportExportEverywhere?: boolean | |||
allowAwaitOutsideFunction?: boolean | |||
allowHashBang?: boolean | |||
locations?: boolean | |||
onToken?: ((token: Token) => any) | Token[] | |||
onComment?: (( | |||
isBlock: boolean, text: string, start: number, end: number, startLoc?: Position, | |||
endLoc?: Position | |||
) => void) | Comment[] | |||
ranges?: boolean | |||
program?: Node | |||
sourceFile?: string | |||
directSourceFile?: string | |||
preserveParens?: boolean | |||
} | |||
class Parser { | |||
constructor(options: Options, input: string, startPos?: number) | |||
parse(this: Parser): Node | |||
static parse(this: typeof Parser, input: string, options?: Options): Node | |||
static parseExpressionAt(this: typeof Parser, input: string, pos: number, options?: Options): Node | |||
static tokenizer(this: typeof Parser, input: string, options?: Options): { | |||
getToken(): Token | |||
[Symbol.iterator](): Iterator<Token> | |||
} | |||
static extend(this: typeof Parser, ...plugins: ((BaseParser: typeof Parser) => typeof Parser)[]): typeof Parser | |||
} | |||
interface Position { line: number; column: number; offset: number } | |||
const defaultOptions: Options | |||
function getLineInfo(input: string, offset: number): Position | |||
class SourceLocation { | |||
start: Position | |||
end: Position | |||
source?: string | null | |||
constructor(p: Parser, start: Position, end: Position) | |||
} | |||
class Node { | |||
type: string | |||
start: number | |||
end: number | |||
loc?: SourceLocation | |||
sourceFile?: string | |||
range?: [number, number] | |||
constructor(parser: Parser, pos: number, loc?: SourceLocation) | |||
} | |||
class TokenType { | |||
label: string | |||
keyword: string | |||
beforeExpr: boolean | |||
startsExpr: boolean | |||
isLoop: boolean | |||
isAssign: boolean | |||
prefix: boolean | |||
postfix: boolean | |||
binop: number | |||
updateContext?: (prevType: TokenType) => void | |||
constructor(label: string, conf?: any) | |||
} | |||
const tokTypes: { | |||
num: TokenType | |||
regexp: TokenType | |||
string: TokenType | |||
name: TokenType | |||
eof: TokenType | |||
bracketL: TokenType | |||
bracketR: TokenType | |||
braceL: TokenType | |||
braceR: TokenType | |||
parenL: TokenType | |||
parenR: TokenType | |||
comma: TokenType | |||
semi: TokenType | |||
colon: TokenType | |||
dot: TokenType | |||
question: TokenType | |||
arrow: TokenType | |||
template: TokenType | |||
ellipsis: TokenType | |||
backQuote: TokenType | |||
dollarBraceL: TokenType | |||
eq: TokenType | |||
assign: TokenType | |||
incDec: TokenType | |||
prefix: TokenType | |||
logicalOR: TokenType | |||
logicalAND: TokenType | |||
bitwiseOR: TokenType | |||
bitwiseXOR: TokenType | |||
bitwiseAND: TokenType | |||
equality: TokenType | |||
relational: TokenType | |||
bitShift: TokenType | |||
plusMin: TokenType | |||
modulo: TokenType | |||
star: TokenType | |||
slash: TokenType | |||
starstar: TokenType | |||
_break: TokenType | |||
_case: TokenType | |||
_catch: TokenType | |||
_continue: TokenType | |||
_debugger: TokenType | |||
_default: TokenType | |||
_do: TokenType | |||
_else: TokenType | |||
_finally: TokenType | |||
_for: TokenType | |||
_function: TokenType | |||
_if: TokenType | |||
_return: TokenType | |||
_switch: TokenType | |||
_throw: TokenType | |||
_try: TokenType | |||
_var: TokenType | |||
_const: TokenType | |||
_while: TokenType | |||
_with: TokenType | |||
_new: TokenType | |||
_this: TokenType | |||
_super: TokenType | |||
_class: TokenType | |||
_extends: TokenType | |||
_export: TokenType | |||
_import: TokenType | |||
_null: TokenType | |||
_true: TokenType | |||
_false: TokenType | |||
_in: TokenType | |||
_instanceof: TokenType | |||
_typeof: TokenType | |||
_void: TokenType | |||
_delete: TokenType | |||
} | |||
class TokContext { | |||
constructor(token: string, isExpr: boolean, preserveSpace: boolean, override?: (p: Parser) => void) | |||
} | |||
const tokContexts: { | |||
b_stat: TokContext | |||
b_expr: TokContext | |||
b_tmpl: TokContext | |||
p_stat: TokContext | |||
p_expr: TokContext | |||
q_tmpl: TokContext | |||
f_expr: TokContext | |||
} | |||
function isIdentifierStart(code: number, astral?: boolean): boolean | |||
function isIdentifierChar(code: number, astral?: boolean): boolean | |||
interface AbstractToken { | |||
} | |||
interface Comment extends AbstractToken { | |||
type: string | |||
value: string | |||
start: number | |||
end: number | |||
loc?: SourceLocation | |||
range?: [number, number] | |||
} | |||
class Token { | |||
type: TokenType | |||
value: any | |||
start: number | |||
end: number | |||
loc?: SourceLocation | |||
range?: [number, number] | |||
constructor(p: Parser) | |||
} | |||
function isNewLine(code: number): boolean | |||
const lineBreak: RegExp | |||
const lineBreakG: RegExp | |||
const version: string | |||
} |
@ -0,0 +1,2 @@ | |||
import * as acorn from "./acorn"; | |||
export = acorn; |
@ -0,0 +1,64 @@ | |||
'use strict'; | |||
var path = require('path'); | |||
var fs = require('fs'); | |||
var acorn = require('./acorn.js'); | |||
var infile, forceFile, silent = false, compact = false, tokenize = false; | |||
var options = {}; | |||
function help(status) { | |||
var print = (status === 0) ? console.log : console.error; | |||
print("usage: " + path.basename(process.argv[1]) + " [--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|...|--ecma2015|--ecma2016|--ecma2017|--ecma2018|...]"); | |||
print(" [--tokenize] [--locations] [---allow-hash-bang] [--compact] [--silent] [--module] [--help] [--] [infile]"); | |||
process.exit(status); | |||
} | |||
for (var i = 2; i < process.argv.length; ++i) { | |||
var 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 === "--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 { | |||
var match = arg.match(/^--ecma(\d+)$/); | |||
if (match) | |||
{ options.ecmaVersion = +match[1]; } | |||
else | |||
{ help(1); } | |||
} | |||
} | |||
function run(code) { | |||
var result; | |||
try { | |||
if (!tokenize) { | |||
result = acorn.parse(code, options); | |||
} else { | |||
result = []; | |||
var tokenizer = acorn.tokenizer(code, options), token; | |||
do { | |||
token = tokenizer.getToken(); | |||
result.push(token); | |||
} while (token.type !== acorn.tokTypes.eof) | |||
} | |||
} catch (e) { | |||
console.error(infile && infile !== "-" ? e.message.replace(/\(\d+:\d+\)$/, function (m) { return m.slice(0, 1) + infile + " " + m.slice(1); }) : e.message); | |||
process.exit(1); | |||
} | |||
if (!silent) { console.log(JSON.stringify(result, null, compact ? null : 2)); } | |||
} | |||
if (forceFile || infile && infile !== "-") { | |||
run(fs.readFileSync(infile, "utf8")); | |||
} else { | |||
var code = ""; | |||
process.stdin.resume(); | |||
process.stdin.on("data", function (chunk) { return code += chunk; }); | |||
process.stdin.on("end", function () { return run(code); }); | |||
} |
@ -0,0 +1,68 @@ | |||
{ | |||
"_from": "acorn@^7.1.1", | |||
"_id": "acorn@7.4.0", | |||
"_inBundle": false, | |||
"_integrity": "sha512-+G7P8jJmCHr+S+cLfQxygbWhXy+8YTVGzAkpEbcLo2mLoL7tij/VG41QSHACSf5QgYRhMZYHuNc6drJaO0Da+w==", | |||
"_location": "/acorn", | |||
"_phantomChildren": {}, | |||
"_requested": { | |||
"type": "range", | |||
"registry": true, | |||
"raw": "acorn@^7.1.1", | |||
"name": "acorn", | |||
"escapedName": "acorn", | |||
"rawSpec": "^7.1.1", | |||
"saveSpec": null, | |||
"fetchSpec": "^7.1.1" | |||
}, | |||
"_requiredBy": [ | |||
"/acorn-globals", | |||
"/jsdom" | |||
], | |||
"_resolved": "https://registry.npmjs.org/acorn/-/acorn-7.4.0.tgz", | |||
"_shasum": "e1ad486e6c54501634c6c397c5c121daa383607c", | |||
"_spec": "acorn@^7.1.1", | |||
"_where": "/home/alpcentaur/ProjektA/PermApp/node_modules/jsdom", | |||
"bin": { | |||
"acorn": "bin/acorn" | |||
}, | |||
"bugs": { | |||
"url": "https://github.com/acornjs/acorn/issues" | |||
}, | |||
"bundleDependencies": false, | |||
"deprecated": false, | |||
"description": "ECMAScript parser", | |||
"engines": { | |||
"node": ">=0.4.0" | |||
}, | |||
"homepage": "https://github.com/acornjs/acorn", | |||
"license": "MIT", | |||
"main": "dist/acorn.js", | |||
"maintainers": [ | |||
{ | |||
"name": "Marijn Haverbeke", | |||
"email": "marijnh@gmail.com", | |||
"url": "https://marijnhaverbeke.nl" | |||
}, | |||
{ | |||
"name": "Ingvar Stepanyan", | |||
"email": "me@rreverser.com", | |||
"url": "https://rreverser.com/" | |||
}, | |||
{ | |||
"name": "Adrian Heine", | |||
"url": "http://adrianheine.de" | |||
} | |||
], | |||
"module": "dist/acorn.mjs", | |||
"name": "acorn", | |||
"repository": { | |||
"type": "git", | |||
"url": "git+https://github.com/acornjs/acorn.git" | |||
}, | |||
"scripts": { | |||
"prepare": "cd ..; npm run build:main && npm run build:bin" | |||
}, | |||
"types": "dist/acorn.d.ts", | |||
"version": "7.4.0" | |||
} |
@ -0,0 +1,20 @@ | |||
var Ajv = require('ajv'); | |||
var ajv = new Ajv({allErrors: true}); | |||
var schema = { | |||
"properties": { | |||
"foo": { "type": "string" }, | |||
"bar": { "type": "number", "maximum": 3 } | |||
} | |||
}; | |||
var validate = ajv.compile(schema); | |||
test({"foo": "abc", "bar": 2}); | |||
test({"foo": 2, "bar": 4}); | |||
function test(data) { | |||
var valid = validate(data); | |||
if (valid) console.log('Valid!'); | |||
else console.log('Invalid: ' + ajv.errorsText(validate.errors)); | |||
} |
@ -0,0 +1,22 @@ | |||
The MIT License (MIT) | |||
Copyright (c) 2015-2017 Evgeny Poberezkin | |||
Permission is hereby granted, free of charge, to any person obtaining a copy | |||
of this software and associated documentation files (the "Software"), to deal | |||
in the Software without restriction, including without limitation the rights | |||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |||
copies of the Software, and to permit persons to whom the Software is | |||
furnished to do so, subject to the following conditions: | |||
The above copyright notice and this permission notice shall be included in all | |||
copies or substantial portions of the Software. | |||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |||
SOFTWARE. | |||
@ -0,0 +1,396 @@ | |||
declare var ajv: { | |||
(options?: ajv.Options): ajv.Ajv; | |||
new(options?: ajv.Options): ajv.Ajv; | |||
ValidationError: typeof AjvErrors.ValidationError; | |||
MissingRefError: typeof AjvErrors.MissingRefError; | |||
$dataMetaSchema: object; | |||
} | |||
declare namespace AjvErrors { | |||
class ValidationError extends Error { | |||
constructor(errors: Array<ajv.ErrorObject>); | |||
message: string; | |||
errors: Array<ajv.ErrorObject>; | |||
ajv: true; | |||
validation: true; | |||
} | |||
class MissingRefError extends Error { | |||
constructor(baseId: string, ref: string, message?: string); | |||
static message: (baseId: string, ref: string) => string; | |||
message: string; | |||
missingRef: string; | |||
missingSchema: string; | |||
} | |||
} | |||
declare namespace ajv { | |||
type ValidationError = AjvErrors.ValidationError; | |||
type MissingRefError = AjvErrors.MissingRefError; | |||
interface Ajv { | |||
/** | |||
* Validate data using schema | |||
* Schema will be compiled and cached (using serialized JSON as key, [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize by default). | |||
* @param {string|object|Boolean} schemaKeyRef key, ref or schema object | |||
* @param {Any} data to be validated | |||
* @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). | |||
*/ | |||
validate(schemaKeyRef: object | string | boolean, data: any): boolean | PromiseLike<any>; | |||
/** | |||
* Create validating function for passed schema. | |||
* @param {object|Boolean} schema schema object | |||
* @return {Function} validating function | |||
*/ | |||
compile(schema: object | boolean): ValidateFunction; | |||
/** | |||
* Creates validating function for passed schema with asynchronous loading of missing schemas. | |||
* `loadSchema` option should be a function that accepts schema uri and node-style callback. | |||
* @this Ajv | |||
* @param {object|Boolean} schema schema object | |||
* @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped | |||
* @param {Function} callback optional node-style callback, it is always called with 2 parameters: error (or null) and validating function. | |||
* @return {PromiseLike<ValidateFunction>} validating function | |||
*/ | |||
compileAsync(schema: object | boolean, meta?: Boolean, callback?: (err: Error, validate: ValidateFunction) => any): PromiseLike<ValidateFunction>; | |||
/** | |||
* Adds schema to the instance. | |||
* @param {object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. | |||
* @param {string} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. | |||
* @return {Ajv} this for method chaining | |||
*/ | |||
addSchema(schema: Array<object> | object, key?: string): Ajv; | |||
/** | |||
* Add schema that will be used to validate other schemas | |||
* options in META_IGNORE_OPTIONS are alway set to false | |||
* @param {object} schema schema object | |||
* @param {string} key optional schema key | |||
* @return {Ajv} this for method chaining | |||
*/ | |||
addMetaSchema(schema: object, key?: string): Ajv; | |||
/** | |||
* Validate schema | |||
* @param {object|Boolean} schema schema to validate | |||
* @return {Boolean} true if schema is valid | |||
*/ | |||
validateSchema(schema: object | boolean): boolean; | |||
/** | |||
* Get compiled schema from the instance by `key` or `ref`. | |||
* @param {string} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id). | |||
* @return {Function} schema validating function (with property `schema`). Returns undefined if keyRef can't be resolved to an existing schema. | |||
*/ | |||
getSchema(keyRef: string): ValidateFunction | undefined; | |||
/** | |||
* Remove cached schema(s). | |||
* If no parameter is passed all schemas but meta-schemas are removed. | |||
* If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. | |||
* Even if schema is referenced by other schemas it still can be removed as other schemas have local references. | |||
* @param {string|object|RegExp|Boolean} schemaKeyRef key, ref, pattern to match key/ref or schema object | |||
* @return {Ajv} this for method chaining | |||
*/ | |||
removeSchema(schemaKeyRef?: object | string | RegExp | boolean): Ajv; | |||
/** | |||
* Add custom format | |||
* @param {string} name format name | |||
* @param {string|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid) | |||
* @return {Ajv} this for method chaining | |||
*/ | |||
addFormat(name: string, format: FormatValidator | FormatDefinition): Ajv; | |||
/** | |||
* Define custom keyword | |||
* @this Ajv | |||
* @param {string} keyword custom keyword, should be a valid identifier, should be different from all standard, custom and macro keywords. | |||
* @param {object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. | |||
* @return {Ajv} this for method chaining | |||
*/ | |||
addKeyword(keyword: string, definition: KeywordDefinition): Ajv; | |||
/** | |||
* Get keyword definition | |||
* @this Ajv | |||
* @param {string} keyword pre-defined or custom keyword. | |||
* @return {object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise. | |||
*/ | |||
getKeyword(keyword: string): object | boolean; | |||
/** | |||
* Remove keyword | |||
* @this Ajv | |||
* @param {string} keyword pre-defined or custom keyword. | |||
* @return {Ajv} this for method chaining | |||
*/ | |||
removeKeyword(keyword: string): Ajv; | |||
/** | |||
* Validate keyword | |||
* @this Ajv | |||
* @param {object} definition keyword definition object | |||
* @param {boolean} throwError true to throw exception if definition is invalid | |||
* @return {boolean} validation result | |||
*/ | |||
validateKeyword(definition: KeywordDefinition, throwError: boolean): boolean; | |||
/** | |||
* Convert array of error message objects to string | |||
* @param {Array<object>} errors optional array of validation errors, if not passed errors from the instance are used. | |||
* @param {object} options optional options with properties `separator` and `dataVar`. | |||
* @return {string} human readable string with all errors descriptions | |||
*/ | |||
errorsText(errors?: Array<ErrorObject> | null, options?: ErrorsTextOptions): string; | |||
errors?: Array<ErrorObject> | null; | |||
} | |||
interface CustomLogger { | |||
log(...args: any[]): any; | |||
warn(...args: any[]): any; | |||
error(...args: any[]): any; | |||
} | |||
interface ValidateFunction { | |||
( | |||
data: any, | |||
dataPath?: string, | |||
parentData?: object | Array<any>, | |||
parentDataProperty?: string | number, | |||
rootData?: object | Array<any> | |||
): boolean | PromiseLike<any>; | |||
schema?: object | boolean; | |||
errors?: null | Array<ErrorObject>; | |||
refs?: object; | |||
refVal?: Array<any>; | |||
root?: ValidateFunction | object; | |||
$async?: true; | |||
source?: object; | |||
} | |||
interface Options { | |||
$data?: boolean; | |||
allErrors?: boolean; | |||
verbose?: boolean; | |||
jsonPointers?: boolean; | |||
uniqueItems?: boolean; | |||
unicode?: boolean; | |||
format?: false | string; | |||
formats?: object; | |||
keywords?: object; | |||
unknownFormats?: true | string[] | 'ignore'; | |||
schemas?: Array<object> | object; | |||
schemaId?: '$id' | 'id' | 'auto'; | |||
missingRefs?: true | 'ignore' | 'fail'; | |||
extendRefs?: true | 'ignore' | 'fail'; | |||
loadSchema?: (uri: string, cb?: (err: Error, schema: object) => void) => PromiseLike<object | boolean>; | |||
removeAdditional?: boolean | 'all' | 'failing'; | |||
useDefaults?: boolean | 'empty' | 'shared'; | |||
coerceTypes?: boolean | 'array'; | |||
strictDefaults?: boolean | 'log'; | |||
strictKeywords?: boolean | 'log'; | |||
strictNumbers?: boolean; | |||
async?: boolean | string; | |||
transpile?: string | ((code: string) => string); | |||
meta?: boolean | object; | |||
validateSchema?: boolean | 'log'; | |||
addUsedSchema?: boolean; | |||
inlineRefs?: boolean | number; | |||
passContext?: boolean; | |||
loopRequired?: number; | |||
ownProperties?: boolean; | |||
multipleOfPrecision?: boolean | number; | |||
errorDataPath?: string, | |||
messages?: boolean; | |||
sourceCode?: boolean; | |||
processCode?: (code: string, schema: object) => string; | |||
cache?: object; | |||
logger?: CustomLogger | false; | |||
nullable?: boolean; | |||
serialize?: ((schema: object | boolean) => any) | false; | |||
} | |||
type FormatValidator = string | RegExp | ((data: string) => boolean | PromiseLike<any>); | |||
type NumberFormatValidator = ((data: number) => boolean | PromiseLike<any>); | |||
interface NumberFormatDefinition { | |||
type: "number", | |||
validate: NumberFormatValidator; | |||
compare?: (data1: number, data2: number) => number; | |||
async?: boolean; | |||
} | |||
interface StringFormatDefinition { | |||
type?: "string", | |||
validate: FormatValidator; | |||
compare?: (data1: string, data2: string) => number; | |||
async?: boolean; | |||
} | |||
type FormatDefinition = NumberFormatDefinition | StringFormatDefinition; | |||
interface KeywordDefinition { | |||
type?: string | Array<string>; | |||
async?: boolean; | |||
$data?: boolean; | |||
errors?: boolean | string; | |||
metaSchema?: object; | |||
// schema: false makes validate not to expect schema (ValidateFunction) | |||
schema?: boolean; | |||
statements?: boolean; | |||
dependencies?: Array<string>; | |||
modifying?: boolean; | |||
valid?: boolean; | |||
// one and only one of the following properties should be present | |||
validate?: SchemaValidateFunction | ValidateFunction; | |||
compile?: (schema: any, parentSchema: object, it: CompilationContext) => ValidateFunction; | |||
macro?: (schema: any, parentSchema: object, it: CompilationContext) => object | boolean; | |||
inline?: (it: CompilationContext, keyword: string, schema: any, parentSchema: object) => string; | |||
} | |||
interface CompilationContext { | |||
level: number; | |||
dataLevel: number; | |||
dataPathArr: string[]; | |||
schema: any; | |||
schemaPath: string; | |||
baseId: string; | |||
async: boolean; | |||
opts: Options; | |||
formats: { | |||
[index: string]: FormatDefinition | undefined; | |||
}; | |||
keywords: { | |||
[index: string]: KeywordDefinition | undefined; | |||
}; | |||
compositeRule: boolean; | |||
validate: (schema: object) => boolean; | |||
util: { | |||
copy(obj: any, target?: any): any; | |||
toHash(source: string[]): { [index: string]: true | undefined }; | |||
equal(obj: any, target: any): boolean; | |||
getProperty(str: string): string; | |||
schemaHasRules(schema: object, rules: any): string; | |||
escapeQuotes(str: string): string; | |||
toQuotedString(str: string): string; | |||
getData(jsonPointer: string, dataLevel: number, paths: string[]): string; | |||
escapeJsonPointer(str: string): string; | |||
unescapeJsonPointer(str: string): string; | |||
escapeFragment(str: string): string; | |||
unescapeFragment(str: string): string; | |||
}; | |||
self: Ajv; | |||
} | |||
interface SchemaValidateFunction { | |||
( | |||
schema: any, | |||
data: any, | |||
parentSchema?: object, | |||
dataPath?: string, | |||
parentData?: object | Array<any>, | |||
parentDataProperty?: string | number, | |||
rootData?: object | Array<any> | |||
): boolean | PromiseLike<any>; | |||
errors?: Array<ErrorObject>; | |||
} | |||
interface ErrorsTextOptions { | |||
separator?: string; | |||
dataVar?: string; | |||
} | |||
interface ErrorObject { | |||
keyword: string; | |||
dataPath: string; | |||
schemaPath: string; | |||
params: ErrorParameters; | |||
// Added to validation errors of propertyNames keyword schema | |||
propertyName?: string; | |||
// Excluded if messages set to false. | |||
message?: string; | |||
// These are added with the `verbose` option. | |||
schema?: any; | |||
parentSchema?: object; | |||
data?: any; | |||
} | |||
type ErrorParameters = RefParams | LimitParams | AdditionalPropertiesParams | | |||
DependenciesParams | FormatParams | ComparisonParams | | |||
MultipleOfParams | PatternParams | RequiredParams | | |||
TypeParams | UniqueItemsParams | CustomParams | | |||
PatternRequiredParams | PropertyNamesParams | | |||
IfParams | SwitchParams | NoParams | EnumParams; | |||
interface RefParams { | |||
ref: string; | |||
} | |||
interface LimitParams { | |||
limit: number; | |||
} | |||
interface AdditionalPropertiesParams { | |||
additionalProperty: string; | |||
} | |||
interface DependenciesParams { | |||
property: string; | |||
missingProperty: string; | |||
depsCount: number; | |||
deps: string; | |||
} | |||
interface FormatParams { | |||
format: string | |||
} | |||
interface ComparisonParams { | |||
comparison: string; | |||
limit: number | string; | |||
exclusive: boolean; | |||
} | |||
interface MultipleOfParams { | |||
multipleOf: number; | |||
} | |||
interface PatternParams { | |||
pattern: string; | |||
} | |||
interface RequiredParams { | |||
missingProperty: string; | |||
} | |||
interface TypeParams { | |||
type: string; | |||
} | |||
interface UniqueItemsParams { | |||
i: number; | |||
j: number; | |||
} | |||
interface CustomParams { | |||
keyword: string; | |||
} | |||
interface PatternRequiredParams { | |||
missingPattern: string; | |||
} | |||
interface PropertyNamesParams { | |||
propertyName: string; | |||
} | |||
interface IfParams { | |||
failingKeyword: string; | |||
} | |||
interface SwitchParams { | |||
caseIndex: number; | |||
} | |||
interface NoParams { } | |||
interface EnumParams { | |||
allowedValues: Array<any>; | |||
} | |||
} | |||
export = ajv; |
@ -0,0 +1,506 @@ | |||
'use strict'; | |||
var compileSchema = require('./compile') | |||
, resolve = require('./compile/resolve') | |||
, Cache = require('./cache') | |||
, SchemaObject = require('./compile/schema_obj') | |||
, stableStringify = require('fast-json-stable-stringify') | |||
, formats = require('./compile/formats') | |||
, rules = require('./compile/rules') | |||
, $dataMetaSchema = require('./data') | |||
, util = require('./compile/util'); | |||
module.exports = Ajv; | |||
Ajv.prototype.validate = validate; | |||
Ajv.prototype.compile = compile; | |||
Ajv.prototype.addSchema = addSchema; | |||
Ajv.prototype.addMetaSchema = addMetaSchema; | |||
Ajv.prototype.validateSchema = validateSchema; | |||
Ajv.prototype.getSchema = getSchema; | |||
Ajv.prototype.removeSchema = removeSchema; | |||
Ajv.prototype.addFormat = addFormat; | |||
Ajv.prototype.errorsText = errorsText; | |||
Ajv.prototype._addSchema = _addSchema; | |||
Ajv.prototype._compile = _compile; | |||
Ajv.prototype.compileAsync = require('./compile/async'); | |||
var customKeyword = require('./keyword'); | |||
Ajv.prototype.addKeyword = customKeyword.add; | |||
Ajv.prototype.getKeyword = customKeyword.get; | |||
Ajv.prototype.removeKeyword = customKeyword.remove; | |||
Ajv.prototype.validateKeyword = customKeyword.validate; | |||
var errorClasses = require('./compile/error_classes'); | |||
Ajv.ValidationError = errorClasses.Validation; | |||
Ajv.MissingRefError = errorClasses.MissingRef; | |||
Ajv.$dataMetaSchema = $dataMetaSchema; | |||
var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; | |||
var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; | |||
var META_SUPPORT_DATA = ['/properties']; | |||
/** | |||
* Creates validator instance. | |||
* Usage: `Ajv(opts)` | |||
* @param {Object} opts optional options | |||
* @return {Object} ajv instance | |||
*/ | |||
function Ajv(opts) { | |||
if (!(this instanceof Ajv)) return new Ajv(opts); | |||
opts = this._opts = util.copy(opts) || {}; | |||
setLogger(this); | |||
this._schemas = {}; | |||
this._refs = {}; | |||
this._fragments = {}; | |||
this._formats = formats(opts.format); | |||
this._cache = opts.cache || new Cache; | |||
this._loadingSchemas = {}; | |||
this._compilations = []; | |||
this.RULES = rules(); | |||
this._getId = chooseGetId(opts); | |||
opts.loopRequired = opts.loopRequired || Infinity; | |||
if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; | |||
if (opts.serialize === undefined) opts.serialize = stableStringify; | |||
this._metaOpts = getMetaSchemaOptions(this); | |||
if (opts.formats) addInitialFormats(this); | |||
if (opts.keywords) addInitialKeywords(this); | |||
addDefaultMetaSchema(this); | |||
if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); | |||
if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}}); | |||
addInitialSchemas(this); | |||
} | |||
/** | |||
* Validate data using schema | |||
* Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. | |||
* @this Ajv | |||
* @param {String|Object} schemaKeyRef key, ref or schema object | |||
* @param {Any} data to be validated | |||
* @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). | |||
*/ | |||
function validate(schemaKeyRef, data) { | |||
var v; | |||
if (typeof schemaKeyRef == 'string') { | |||
v = this.getSchema(schemaKeyRef); | |||
if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); | |||
} else { | |||
var schemaObj = this._addSchema(schemaKeyRef); | |||
v = schemaObj.validate || this._compile(schemaObj); | |||
} | |||
var valid = v(data); | |||
if (v.$async !== true) this.errors = v.errors; | |||
return valid; | |||
} | |||
/** | |||
* Create validating function for passed schema. | |||
* @this Ajv | |||
* @param {Object} schema schema object | |||
* @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. | |||
* @return {Function} validating function | |||
*/ | |||
function compile(schema, _meta) { | |||
var schemaObj = this._addSchema(schema, undefined, _meta); | |||
return schemaObj.validate || this._compile(schemaObj); | |||
} | |||
/** | |||
* Adds schema to the instance. | |||
* @this Ajv | |||
* @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. | |||
* @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. | |||
* @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. | |||
* @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. | |||
* @return {Ajv} this for method chaining | |||
*/ | |||
function addSchema(schema, key, _skipValidation, _meta) { | |||
if (Array.isArray(schema)){ | |||
for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta); | |||
return this; | |||
} | |||
var id = this._getId(schema); | |||
if (id !== undefined && typeof id != 'string') | |||
throw new Error('schema id must be string'); | |||
key = resolve.normalizeId(key || id); | |||
checkUnique(this, key); | |||
this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true); | |||
return this; | |||
} | |||
/** | |||
* Add schema that will be used to validate other schemas | |||
* options in META_IGNORE_OPTIONS are alway set to false | |||
* @this Ajv | |||
* @param {Object} schema schema object | |||
* @param {String} key optional schema key | |||
* @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema | |||
* @return {Ajv} this for method chaining | |||
*/ | |||
function addMetaSchema(schema, key, skipValidation) { | |||
this.addSchema(schema, key, skipValidation, true); | |||
return this; | |||
} | |||
/** | |||
* Validate schema | |||
* @this Ajv | |||
* @param {Object} schema schema to validate | |||
* @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid | |||
* @return {Boolean} true if schema is valid | |||
*/ | |||
function validateSchema(schema, throwOrLogError) { | |||
var $schema = schema.$schema; | |||
if ($schema !== undefined && typeof $schema != 'string') | |||
throw new Error('$schema must be a string'); | |||
$schema = $schema || this._opts.defaultMeta || defaultMeta(this); | |||
if (!$schema) { | |||
this.logger.warn('meta-schema not available'); | |||
this.errors = null; | |||
return true; | |||
} | |||
var valid = this.validate($schema, schema); | |||
if (!valid && throwOrLogError) { | |||
var message = 'schema is invalid: ' + this.errorsText(); | |||
if (this._opts.validateSchema == 'log') this.logger.error(message); | |||
else throw new Error(message); | |||
} | |||
return valid; | |||
} | |||
function defaultMeta(self) { | |||
var meta = self._opts.meta; | |||
self._opts.defaultMeta = typeof meta == 'object' | |||
? self._getId(meta) || meta | |||
: self.getSchema(META_SCHEMA_ID) | |||
? META_SCHEMA_ID | |||
: undefined; | |||
return self._opts.defaultMeta; | |||
} | |||
/** | |||
* Get compiled schema from the instance by `key` or `ref`. | |||
* @this Ajv | |||
* @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id). | |||
* @return {Function} schema validating function (with property `schema`). | |||
*/ | |||
function getSchema(keyRef) { | |||
var schemaObj = _getSchemaObj(this, keyRef); | |||
switch (typeof schemaObj) { | |||
case 'object': return schemaObj.validate || this._compile(schemaObj); | |||
case 'string': return this.getSchema(schemaObj); | |||
case 'undefined': return _getSchemaFragment(this, keyRef); | |||
} | |||
} | |||
function _getSchemaFragment(self, ref) { | |||
var res = resolve.schema.call(self, { schema: {} }, ref); | |||
if (res) { | |||
var schema = res.schema | |||
, root = res.root | |||
, baseId = res.baseId; | |||
var v = compileSchema.call(self, schema, root, undefined, baseId); | |||
self._fragments[ref] = new SchemaObject({ | |||
ref: ref, | |||
fragment: true, | |||
schema: schema, | |||
root: root, | |||
baseId: baseId, | |||
validate: v | |||
}); | |||
return v; | |||
} | |||
} | |||
function _getSchemaObj(self, keyRef) { | |||
keyRef = resolve.normalizeId(keyRef); | |||
return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef]; | |||
} | |||
/** | |||
* Remove cached schema(s). | |||
* If no parameter is passed all schemas but meta-schemas are removed. | |||
* If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. | |||
* Even if schema is referenced by other schemas it still can be removed as other schemas have local references. | |||
* @this Ajv | |||
* @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object | |||
* @return {Ajv} this for method chaining | |||
*/ | |||
function removeSchema(schemaKeyRef) { | |||
if (schemaKeyRef instanceof RegExp) { | |||
_removeAllSchemas(this, this._schemas, schemaKeyRef); | |||
_removeAllSchemas(this, this._refs, schemaKeyRef); | |||
return this; | |||
} | |||
switch (typeof schemaKeyRef) { | |||
case 'undefined': | |||
_removeAllSchemas(this, this._schemas); | |||
_removeAllSchemas(this, this._refs); | |||
this._cache.clear(); | |||
return this; | |||
case 'string': | |||
var schemaObj = _getSchemaObj(this, schemaKeyRef); | |||
if (schemaObj) this._cache.del(schemaObj.cacheKey); | |||
delete this._schemas[schemaKeyRef]; | |||
delete this._refs[schemaKeyRef]; | |||
return this; | |||
case 'object': | |||
var serialize = this._opts.serialize; | |||
var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef; | |||
this._cache.del(cacheKey); | |||
var id = this._getId(schemaKeyRef); | |||
if (id) { | |||
id = resolve.normalizeId(id); | |||
delete this._schemas[id]; | |||
delete this._refs[id]; | |||
} | |||
} | |||
return this; | |||
} | |||
function _removeAllSchemas(self, schemas, regex) { | |||
for (var keyRef in schemas) { | |||
var schemaObj = schemas[keyRef]; | |||
if (!schemaObj.meta && (!regex || regex.test(keyRef))) { | |||
self._cache.del(schemaObj.cacheKey); | |||
delete schemas[keyRef]; | |||
} | |||
} | |||
} | |||
/* @this Ajv */ | |||
function _addSchema(schema, skipValidation, meta, shouldAddSchema) { | |||
if (typeof schema != 'object' && typeof schema != 'boolean') | |||
throw new Error('schema should be object or boolean'); | |||
var serialize = this._opts.serialize; | |||
var cacheKey = serialize ? serialize(schema) : schema; | |||
var cached = this._cache.get(cacheKey); | |||
if (cached) return cached; | |||
shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false; | |||
var id = resolve.normalizeId(this._getId(schema)); | |||
if (id && shouldAddSchema) checkUnique(this, id); | |||
var willValidate = this._opts.validateSchema !== false && !skipValidation; | |||
var recursiveMeta; | |||
if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema))) | |||
this.validateSchema(schema, true); | |||
var localRefs = resolve.ids.call(this, schema); | |||
var schemaObj = new SchemaObject({ | |||
id: id, | |||
schema: schema, | |||
localRefs: localRefs, | |||
cacheKey: cacheKey, | |||
meta: meta | |||
}); | |||
if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj; | |||
this._cache.put(cacheKey, schemaObj); | |||
if (willValidate && recursiveMeta) this.validateSchema(schema, true); | |||
return schemaObj; | |||
} | |||
/* @this Ajv */ | |||
function _compile(schemaObj, root) { | |||
if (schemaObj.compiling) { | |||
schemaObj.validate = callValidate; | |||
callValidate.schema = schemaObj.schema; | |||
callValidate.errors = null; | |||
callValidate.root = root ? root : callValidate; | |||
if (schemaObj.schema.$async === true) | |||
callValidate.$async = true; | |||
return callValidate; | |||
} | |||
schemaObj.compiling = true; | |||
var currentOpts; | |||
if (schemaObj.meta) { | |||
currentOpts = this._opts; | |||
this._opts = this._metaOpts; | |||
} | |||
var v; | |||
try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); } | |||
catch(e) { | |||
delete schemaObj.validate; | |||
throw e; | |||
} | |||
finally { | |||
schemaObj.compiling = false; | |||
if (schemaObj.meta) this._opts = currentOpts; | |||
} | |||
schemaObj.validate = v; | |||
schemaObj.refs = v.refs; | |||
schemaObj.refVal = v.refVal; | |||
schemaObj.root = v.root; | |||
return v; | |||
/* @this {*} - custom context, see passContext option */ | |||
function callValidate() { | |||
/* jshint validthis: true */ | |||
var _validate = schemaObj.validate; | |||
var result = _validate.apply(this, arguments); | |||
callValidate.errors = _validate.errors; | |||
return result; | |||
} | |||
} | |||
function chooseGetId(opts) { | |||
switch (opts.schemaId) { | |||
case 'auto': return _get$IdOrId; | |||
case 'id': return _getId; | |||
default: return _get$Id; | |||
} | |||
} | |||
/* @this Ajv */ | |||
function _getId(schema) { | |||
if (schema.$id) this.logger.warn('schema $id ignored', schema.$id); | |||
return schema.id; | |||
} | |||
/* @this Ajv */ | |||
function _get$Id(schema) { | |||
if (schema.id) this.logger.warn('schema id ignored', schema.id); | |||
return schema.$id; | |||
} | |||
function _get$IdOrId(schema) { | |||
if (schema.$id && schema.id && schema.$id != schema.id) | |||
throw new Error('schema $id is different from id'); | |||
return schema.$id || schema.id; | |||
} | |||
/** | |||
* Convert array of error message objects to string | |||
* @this Ajv | |||
* @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used. | |||
* @param {Object} options optional options with properties `separator` and `dataVar`. | |||
* @return {String} human readable string with all errors descriptions | |||
*/ | |||
function errorsText(errors, options) { | |||
errors = errors || this.errors; | |||
if (!errors) return 'No errors'; | |||
options = options || {}; | |||
var separator = options.separator === undefined ? ', ' : options.separator; | |||
var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; | |||
var text = ''; | |||
for (var i=0; i<errors.length; i++) { | |||
var e = errors[i]; | |||
if (e) text += dataVar + e.dataPath + ' ' + e.message + separator; | |||
} | |||
return text.slice(0, -separator.length); | |||
} | |||
/** | |||
* Add custom format | |||
* @this Ajv | |||
* @param {String} name format name | |||
* @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid) | |||
* @return {Ajv} this for method chaining | |||
*/ | |||
function addFormat(name, format) { | |||
if (typeof format == 'string') format = new RegExp(format); | |||
this._formats[name] = format; | |||
return this; | |||
} | |||
function addDefaultMetaSchema(self) { | |||
var $dataSchema; | |||
if (self._opts.$data) { | |||
$dataSchema = require('./refs/data.json'); | |||
self.addMetaSchema($dataSchema, $dataSchema.$id, true); | |||
} | |||
if (self._opts.meta === false) return; | |||
var metaSchema = require('./refs/json-schema-draft-07.json'); | |||
if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA); | |||
self.addMetaSchema(metaSchema, META_SCHEMA_ID, true); | |||
self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID; | |||
} | |||
function addInitialSchemas(self) { | |||
var optsSchemas = self._opts.schemas; | |||
if (!optsSchemas) return; | |||
if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas); | |||
else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key); | |||
} | |||
function addInitialFormats(self) { | |||
for (var name in self._opts.formats) { | |||
var format = self._opts.formats[name]; | |||
self.addFormat(name, format); | |||
} | |||
} | |||
function addInitialKeywords(self) { | |||
for (var name in self._opts.keywords) { | |||
var keyword = self._opts.keywords[name]; | |||
self.addKeyword(name, keyword); | |||
} | |||
} | |||
function checkUnique(self, id) { | |||
if (self._schemas[id] || self._refs[id]) | |||
throw new Error('schema with key or id "' + id + '" already exists'); | |||
} | |||
function getMetaSchemaOptions(self) { | |||
var metaOpts = util.copy(self._opts); | |||
for (var i=0; i<META_IGNORE_OPTIONS.length; i++) | |||
delete metaOpts[META_IGNORE_OPTIONS[i]]; | |||
return metaOpts; | |||
} | |||
function setLogger(self) { | |||
var logger = self._opts.logger; | |||
if (logger === false) { | |||
self.logger = {log: noop, warn: noop, error: noop}; | |||
} else { | |||
if (logger === undefined) logger = console; | |||
if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error)) | |||
throw new Error('logger must implement log, warn and error methods'); | |||
self.logger = logger; | |||
} | |||
} | |||
function noop() {} |
@ -0,0 +1,26 @@ | |||
'use strict'; | |||
var Cache = module.exports = function Cache() { | |||
this._cache = {}; | |||
}; | |||
Cache.prototype.put = function Cache_put(key, value) { | |||
this._cache[key] = value; | |||
}; | |||
Cache.prototype.get = function Cache_get(key) { | |||
return this._cache[key]; | |||
}; | |||
Cache.prototype.del = function Cache_del(key) { | |||
delete this._cache[key]; | |||
}; | |||
Cache.prototype.clear = function Cache_clear() { | |||
this._cache = {}; | |||
}; |
@ -0,0 +1,90 @@ | |||
'use strict'; | |||
var MissingRefError = require('./error_classes').MissingRef; | |||
module.exports = compileAsync; | |||
/** | |||
* Creates validating function for passed schema with asynchronous loading of missing schemas. | |||
* `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema. | |||
* @this Ajv | |||
* @param {Object} schema schema object | |||
* @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped | |||
* @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function. | |||
* @return {Promise} promise that resolves with a validating function. | |||
*/ | |||
function compileAsync(schema, meta, callback) { | |||
/* eslint no-shadow: 0 */ | |||
/* global Promise */ | |||
/* jshint validthis: true */ | |||
var self = this; | |||
if (typeof this._opts.loadSchema != 'function') | |||
throw new Error('options.loadSchema should be a function'); | |||
if (typeof meta == 'function') { | |||
callback = meta; | |||
meta = undefined; | |||
} | |||
var p = loadMetaSchemaOf(schema).then(function () { | |||
var schemaObj = self._addSchema(schema, undefined, meta); | |||
return schemaObj.validate || _compileAsync(schemaObj); | |||
}); | |||
if (callback) { | |||
p.then( | |||
function(v) { callback(null, v); }, | |||
callback | |||
); | |||
} | |||
return p; | |||
function loadMetaSchemaOf(sch) { | |||
var $schema = sch.$schema; | |||
return $schema && !self.getSchema($schema) | |||
? compileAsync.call(self, { $ref: $schema }, true) | |||
: Promise.resolve(); | |||
} | |||
function _compileAsync(schemaObj) { | |||
try { return self._compile(schemaObj); } | |||
catch(e) { | |||
if (e instanceof MissingRefError) return loadMissingSchema(e); | |||
throw e; | |||
} | |||
function loadMissingSchema(e) { | |||
var ref = e.missingSchema; | |||
if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'); | |||
var schemaPromise = self._loadingSchemas[ref]; | |||
if (!schemaPromise) { | |||
schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref); | |||
schemaPromise.then(removePromise, removePromise); | |||
} | |||
return schemaPromise.then(function (sch) { | |||
if (!added(ref)) { | |||
return loadMetaSchemaOf(sch).then(function () { | |||
if (!added(ref)) self.addSchema(sch, ref, undefined, meta); | |||
}); | |||
} | |||
}).then(function() { | |||
return _compileAsync(schemaObj); | |||
}); | |||
function removePromise() { | |||
delete self._loadingSchemas[ref]; | |||
} | |||
function added(ref) { | |||
return self._refs[ref] || self._schemas[ref]; | |||
} | |||
} | |||
} | |||
} |
@ -0,0 +1,5 @@ | |||
'use strict'; | |||
// do NOT remove this file - it would break pre-compiled schemas | |||
// https://github.com/ajv-validator/ajv/issues/889 | |||
module.exports = require('fast-deep-equal'); |
@ -0,0 +1,34 @@ | |||
'use strict'; | |||
var resolve = require('./resolve'); | |||
module.exports = { | |||
Validation: errorSubclass(ValidationError), | |||
MissingRef: errorSubclass(MissingRefError) | |||
}; | |||
function ValidationError(errors) { | |||
this.message = 'validation failed'; | |||
this.errors = errors; | |||
this.ajv = this.validation = true; | |||
} | |||
MissingRefError.message = function (baseId, ref) { | |||
return 'can\'t resolve reference ' + ref + ' from id ' + baseId; | |||
}; | |||
function MissingRefError(baseId, ref, message) { | |||
this.message = message || MissingRefError.message(baseId, ref); | |||
this.missingRef = resolve.url(baseId, ref); | |||
this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef)); | |||
} | |||
function errorSubclass(Subclass) { | |||
Subclass.prototype = Object.create(Error.prototype); | |||
Subclass.prototype.constructor = Subclass; | |||
return Subclass; | |||
} |
@ -0,0 +1,142 @@ | |||
'use strict'; | |||
var util = require('./util'); | |||
var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; | |||
var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31]; | |||
var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; | |||
var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; | |||
var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; | |||
var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; | |||
// uri-template: https://tools.ietf.org/html/rfc6570 | |||
var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; | |||
// For the source: https://gist.github.com/dperini/729294 | |||
// For test cases: https://mathiasbynens.be/demo/url-regex | |||
// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. | |||
// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; | |||
var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; | |||
var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; | |||
var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; | |||
var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; | |||
var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; | |||
module.exports = formats; | |||
function formats(mode) { | |||
mode = mode == 'full' ? 'full' : 'fast'; | |||
return util.copy(formats[mode]); | |||
} | |||
formats.fast = { | |||
// date: http://tools.ietf.org/html/rfc3339#section-5.6 | |||
date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, | |||
// date-time: http://tools.ietf.org/html/rfc3339#section-5.6 | |||
time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, | |||
'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, | |||
// uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js | |||
uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, | |||
'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, | |||
'uri-template': URITEMPLATE, | |||
url: URL, | |||
// email (sources from jsen validator): | |||
// http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 | |||
// http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') | |||
email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, | |||
hostname: HOSTNAME, | |||
// optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html | |||
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, | |||
// optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses | |||
ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, | |||
regex: regex, | |||
// uuid: http://tools.ietf.org/html/rfc4122 | |||
uuid: UUID, | |||
// JSON-pointer: https://tools.ietf.org/html/rfc6901 | |||
// uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A | |||
'json-pointer': JSON_POINTER, | |||
'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, | |||
// relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 | |||
'relative-json-pointer': RELATIVE_JSON_POINTER | |||
}; | |||
formats.full = { | |||
date: date, | |||
time: time, | |||
'date-time': date_time, | |||
uri: uri, | |||
'uri-reference': URIREF, | |||
'uri-template': URITEMPLATE, | |||
url: URL, | |||
email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, | |||
hostname: HOSTNAME, | |||
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, | |||
ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, | |||
regex: regex, | |||
uuid: UUID, | |||
'json-pointer': JSON_POINTER, | |||
'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, | |||
'relative-json-pointer': RELATIVE_JSON_POINTER | |||
}; | |||
function isLeapYear(year) { | |||
// https://tools.ietf.org/html/rfc3339#appendix-C | |||
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); | |||
} | |||
function date(str) { | |||
// full-date from http://tools.ietf.org/html/rfc3339#section-5.6 | |||
var matches = str.match(DATE); | |||
if (!matches) return false; | |||
var year = +matches[1]; | |||
var month = +matches[2]; | |||
var day = +matches[3]; | |||
return month >= 1 && month <= 12 && day >= 1 && | |||
day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); | |||
} | |||
function time(str, full) { | |||
var matches = str.match(TIME); | |||
if (!matches) return false; | |||
var hour = matches[1]; | |||
var minute = matches[2]; | |||
var second = matches[3]; | |||
var timeZone = matches[5]; | |||
return ((hour <= 23 && minute <= 59 && second <= 59) || | |||
(hour == 23 && minute == 59 && second == 60)) && | |||
(!full || timeZone); | |||
} | |||
var DATE_TIME_SEPARATOR = /t|\s/i; | |||
function date_time(str) { | |||
// http://tools.ietf.org/html/rfc3339#section-5.6 | |||
var dateTime = str.split(DATE_TIME_SEPARATOR); | |||
return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); | |||
} | |||
var NOT_URI_FRAGMENT = /\/|:/; | |||
function uri(str) { | |||
// http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." | |||
return NOT_URI_FRAGMENT.test(str) && URI.test(str); | |||
} | |||
var Z_ANCHOR = /[^\\]\\Z/; | |||
function regex(str) { | |||
if (Z_ANCHOR.test(str)) return false; | |||
try { | |||
new RegExp(str); | |||
return true; | |||
} catch(e) { | |||
return false; | |||
} | |||
} |
@ -0,0 +1,387 @@ | |||
'use strict'; | |||
var resolve = require('./resolve') | |||
, util = require('./util') | |||
, errorClasses = require('./error_classes') | |||
, stableStringify = require('fast-json-stable-stringify'); | |||
var validateGenerator = require('../dotjs/validate'); | |||
/** | |||
* Functions below are used inside compiled validations function | |||
*/ | |||
var ucs2length = util.ucs2length; | |||
var equal = require('fast-deep-equal'); | |||
// this error is thrown by async schemas to return validation errors via exception | |||
var ValidationError = errorClasses.Validation; | |||
module.exports = compile; | |||
/** | |||
* Compiles schema to validation function | |||
* @this Ajv | |||
* @param {Object} schema schema object | |||
* @param {Object} root object with information about the root schema for this schema | |||
* @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution | |||
* @param {String} baseId base ID for IDs in the schema | |||
* @return {Function} validation function | |||
*/ | |||
function compile(schema, root, localRefs, baseId) { | |||
/* jshint validthis: true, evil: true */ | |||
/* eslint no-shadow: 0 */ | |||
var self = this | |||
, opts = this._opts | |||
, refVal = [ undefined ] | |||
, refs = {} | |||
, patterns = [] | |||
, patternsHash = {} | |||
, defaults = [] | |||
, defaultsHash = {} | |||
, customRules = []; | |||
root = root || { schema: schema, refVal: refVal, refs: refs }; | |||
var c = checkCompiling.call(this, schema, root, baseId); | |||
var compilation = this._compilations[c.index]; | |||
if (c.compiling) return (compilation.callValidate = callValidate); | |||
var formats = this._formats; | |||
var RULES = this.RULES; | |||
try { | |||
var v = localCompile(schema, root, localRefs, baseId); | |||
compilation.validate = v; | |||
var cv = compilation.callValidate; | |||
if (cv) { | |||
cv.schema = v.schema; | |||
cv.errors = null; | |||
cv.refs = v.refs; | |||
cv.refVal = v.refVal; | |||
cv.root = v.root; | |||
cv.$async = v.$async; | |||
if (opts.sourceCode) cv.source = v.source; | |||
} | |||
return v; | |||
} finally { | |||
endCompiling.call(this, schema, root, baseId); | |||
} | |||
/* @this {*} - custom context, see passContext option */ | |||
function callValidate() { | |||
/* jshint validthis: true */ | |||
var validate = compilation.validate; | |||
var result = validate.apply(this, arguments); | |||
callValidate.errors = validate.errors; | |||
return result; | |||
} | |||
function localCompile(_schema, _root, localRefs, baseId) { | |||
var isRoot = !_root || (_root && _root.schema == _schema); | |||
if (_root.schema != root.schema) | |||
return compile.call(self, _schema, _root, localRefs, baseId); | |||
var $async = _schema.$async === true; | |||
var sourceCode = validateGenerator({ | |||
isTop: true, | |||
schema: _schema, | |||
isRoot: isRoot, | |||
baseId: baseId, | |||
root: _root, | |||
schemaPath: '', | |||
errSchemaPath: '#', | |||
errorPath: '""', | |||
MissingRefError: errorClasses.MissingRef, | |||
RULES: RULES, | |||
validate: validateGenerator, | |||
util: util, | |||
resolve: resolve, | |||
resolveRef: resolveRef, | |||
usePattern: usePattern, | |||
useDefault: useDefault, | |||
useCustomRule: useCustomRule, | |||
opts: opts, | |||
formats: formats, | |||
logger: self.logger, | |||
self: self | |||
}); | |||
sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) | |||
+ vars(defaults, defaultCode) + vars(customRules, customRuleCode) | |||
+ sourceCode; | |||
if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema); | |||
// console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); | |||
var validate; | |||
try { | |||
var makeValidate = new Function( | |||
'self', | |||
'RULES', | |||
'formats', | |||
'root', | |||
'refVal', | |||
'defaults', | |||
'customRules', | |||
'equal', | |||
'ucs2length', | |||
'ValidationError', | |||
sourceCode | |||
); | |||
validate = makeValidate( | |||
self, | |||
RULES, | |||
formats, | |||
root, | |||
refVal, | |||
defaults, | |||
customRules, | |||
equal, | |||
ucs2length, | |||
ValidationError | |||
); | |||
refVal[0] = validate; | |||
} catch(e) { | |||
self.logger.error('Error compiling schema, function code:', sourceCode); | |||
throw e; | |||
} | |||
validate.schema = _schema; | |||
validate.errors = null; | |||
validate.refs = refs; | |||
validate.refVal = refVal; | |||
validate.root = isRoot ? validate : _root; | |||
if ($async) validate.$async = true; | |||
if (opts.sourceCode === true) { | |||
validate.source = { | |||
code: sourceCode, | |||
patterns: patterns, | |||
defaults: defaults | |||
}; | |||
} | |||
return validate; | |||
} | |||
function resolveRef(baseId, ref, isRoot) { | |||
ref = resolve.url(baseId, ref); | |||
var refIndex = refs[ref]; | |||
var _refVal, refCode; | |||
if (refIndex !== undefined) { | |||
_refVal = refVal[refIndex]; | |||
refCode = 'refVal[' + refIndex + ']'; | |||
return resolvedRef(_refVal, refCode); | |||
} | |||
if (!isRoot && root.refs) { | |||
var rootRefId = root.refs[ref]; | |||
if (rootRefId !== undefined) { | |||
_refVal = root.refVal[rootRefId]; | |||
refCode = addLocalRef(ref, _refVal); | |||
return resolvedRef(_refVal, refCode); | |||
} | |||
} | |||
refCode = addLocalRef(ref); | |||
var v = resolve.call(self, localCompile, root, ref); | |||
if (v === undefined) { | |||
var localSchema = localRefs && localRefs[ref]; | |||
if (localSchema) { | |||
v = resolve.inlineRef(localSchema, opts.inlineRefs) | |||
? localSchema | |||
: compile.call(self, localSchema, root, localRefs, baseId); | |||
} | |||
} | |||
if (v === undefined) { | |||
removeLocalRef(ref); | |||
} else { | |||
replaceLocalRef(ref, v); | |||
return resolvedRef(v, refCode); | |||
} | |||
} | |||
function addLocalRef(ref, v) { | |||
var refId = refVal.length; | |||
refVal[refId] = v; | |||
refs[ref] = refId; | |||
return 'refVal' + refId; | |||
} | |||
function removeLocalRef(ref) { | |||
delete refs[ref]; | |||
} | |||
function replaceLocalRef(ref, v) { | |||
var refId = refs[ref]; | |||
refVal[refId] = v; | |||
} | |||
function resolvedRef(refVal, code) { | |||
return typeof refVal == 'object' || typeof refVal == 'boolean' | |||
? { code: code, schema: refVal, inline: true } | |||
: { code: code, $async: refVal && !!refVal.$async }; | |||
} | |||
function usePattern(regexStr) { | |||
var index = patternsHash[regexStr]; | |||
if (index === undefined) { | |||
index = patternsHash[regexStr] = patterns.length; | |||
patterns[index] = regexStr; | |||
} | |||
return 'pattern' + index; | |||
} | |||
function useDefault(value) { | |||
switch (typeof value) { | |||
case 'boolean': | |||
case 'number': | |||
return '' + value; | |||
case 'string': | |||
return util.toQuotedString(value); | |||
case 'object': | |||
if (value === null) return 'null'; | |||
var valueStr = stableStringify(value); | |||
var index = defaultsHash[valueStr]; | |||
if (index === undefined) { | |||
index = defaultsHash[valueStr] = defaults.length; | |||
defaults[index] = value; | |||
} | |||
return 'default' + index; | |||
} | |||
} | |||
function useCustomRule(rule, schema, parentSchema, it) { | |||
if (self._opts.validateSchema !== false) { | |||
var deps = rule.definition.dependencies; | |||
if (deps && !deps.every(function(keyword) { | |||
return Object.prototype.hasOwnProperty.call(parentSchema, keyword); | |||
})) | |||
throw new Error('parent schema must have all required keywords: ' + deps.join(',')); | |||
var validateSchema = rule.definition.validateSchema; | |||
if (validateSchema) { | |||
var valid = validateSchema(schema); | |||
if (!valid) { | |||
var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); | |||
if (self._opts.validateSchema == 'log') self.logger.error(message); | |||
else throw new Error(message); | |||
} | |||
} | |||
} | |||
var compile = rule.definition.compile | |||
, inline = rule.definition.inline | |||
, macro = rule.definition.macro; | |||
var validate; | |||
if (compile) { | |||
validate = compile.call(self, schema, parentSchema, it); | |||
} else if (macro) { | |||
validate = macro.call(self, schema, parentSchema, it); | |||
if (opts.validateSchema !== false) self.validateSchema(validate, true); | |||
} else if (inline) { | |||
validate = inline.call(self, it, rule.keyword, schema, parentSchema); | |||
} else { | |||
validate = rule.definition.validate; | |||
if (!validate) return; | |||
} | |||
if (validate === undefined) | |||
throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); | |||
var index = customRules.length; | |||
customRules[index] = validate; | |||
return { | |||
code: 'customRule' + index, | |||
validate: validate | |||
}; | |||
} | |||
} | |||
/** | |||
* Checks if the schema is currently compiled | |||
* @this Ajv | |||
* @param {Object} schema schema to compile | |||
* @param {Object} root root object | |||
* @param {String} baseId base schema ID | |||
* @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) | |||
*/ | |||
function checkCompiling(schema, root, baseId) { | |||
/* jshint validthis: true */ | |||
var index = compIndex.call(this, schema, root, baseId); | |||
if (index >= 0) return { index: index, compiling: true }; | |||
index = this._compilations.length; | |||
this._compilations[index] = { | |||
schema: schema, | |||
root: root, | |||
baseId: baseId | |||
}; | |||
return { index: index, compiling: false }; | |||
} | |||
/** | |||
* Removes the schema from the currently compiled list | |||
* @this Ajv | |||
* @param {Object} schema schema to compile | |||
* @param {Object} root root object | |||
* @param {String} baseId base schema ID | |||
*/ | |||
function endCompiling(schema, root, baseId) { | |||
/* jshint validthis: true */ | |||
var i = compIndex.call(this, schema, root, baseId); | |||
if (i >= 0) this._compilations.splice(i, 1); | |||
} | |||
/** | |||
* Index of schema compilation in the currently compiled list | |||
* @this Ajv | |||
* @param {Object} schema schema to compile | |||
* @param {Object} root root object | |||
* @param {String} baseId base schema ID | |||
* @return {Integer} compilation index | |||
*/ | |||
function compIndex(schema, root, baseId) { | |||
/* jshint validthis: true */ | |||
for (var i=0; i<this._compilations.length; i++) { | |||
var c = this._compilations[i]; | |||
if (c.schema == schema && c.root == root && c.baseId == baseId) return i; | |||
} | |||
return -1; | |||
} | |||
function patternCode(i, patterns) { | |||
return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');'; | |||
} | |||
function defaultCode(i) { | |||
return 'var default' + i + ' = defaults[' + i + '];'; | |||
} | |||
function refValCode(i, refVal) { | |||
return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];'; | |||
} | |||
function customRuleCode(i) { | |||
return 'var customRule' + i + ' = customRules[' + i + '];'; | |||
} | |||
function vars(arr, statement) { | |||
if (!arr.length) return ''; | |||
var code = ''; | |||
for (var i=0; i<arr.length; i++) | |||
code += statement(i, arr); | |||
return code; | |||
} |
@ -0,0 +1,270 @@ | |||
'use strict'; | |||
var URI = require('uri-js') | |||
, equal = require('fast-deep-equal') | |||
, util = require('./util') | |||
, SchemaObject = require('./schema_obj') | |||
, traverse = require('json-schema-traverse'); | |||
module.exports = resolve; | |||
resolve.normalizeId = normalizeId; | |||
resolve.fullPath = getFullPath; | |||
resolve.url = resolveUrl; | |||
resolve.ids = resolveIds; | |||
resolve.inlineRef = inlineRef; | |||
resolve.schema = resolveSchema; | |||
/** | |||
* [resolve and compile the references ($ref)] | |||
* @this Ajv | |||
* @param {Function} compile reference to schema compilation funciton (localCompile) | |||
* @param {Object} root object with information about the root schema for the current schema | |||
* @param {String} ref reference to resolve | |||
* @return {Object|Function} schema object (if the schema can be inlined) or validation function | |||
*/ | |||
function resolve(compile, root, ref) { | |||
/* jshint validthis: true */ | |||
var refVal = this._refs[ref]; | |||
if (typeof refVal == 'string') { | |||
if (this._refs[refVal]) refVal = this._refs[refVal]; | |||
else return resolve.call(this, compile, root, refVal); | |||
} | |||
refVal = refVal || this._schemas[ref]; | |||
if (refVal instanceof SchemaObject) { | |||
return inlineRef(refVal.schema, this._opts.inlineRefs) | |||
? refVal.schema | |||
: refVal.validate || this._compile(refVal); | |||
} | |||
var res = resolveSchema.call(this, root, ref); | |||
var schema, v, baseId; | |||
if (res) { | |||
schema = res.schema; | |||
root = res.root; | |||
baseId = res.baseId; | |||
} | |||
if (schema instanceof SchemaObject) { | |||
v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId); | |||
} else if (schema !== undefined) { | |||
v = inlineRef(schema, this._opts.inlineRefs) | |||
? schema | |||
: compile.call(this, schema, root, undefined, baseId); | |||
} | |||
return v; | |||
} | |||
/** | |||
* Resolve schema, its root and baseId | |||
* @this Ajv | |||
* @param {Object} root root object with properties schema, refVal, refs | |||
* @param {String} ref reference to resolve | |||
* @return {Object} object with properties schema, root, baseId | |||
*/ | |||
function resolveSchema(root, ref) { | |||
/* jshint validthis: true */ | |||
var p = URI.parse(ref) | |||
, refPath = _getFullPath(p) | |||
, baseId = getFullPath(this._getId(root.schema)); | |||
if (Object.keys(root.schema).length === 0 || refPath !== baseId) { | |||
var id = normalizeId(refPath); | |||
var refVal = this._refs[id]; | |||
if (typeof refVal == 'string') { | |||
return resolveRecursive.call(this, root, refVal, p); | |||
} else if (refVal instanceof SchemaObject) { | |||
if (!refVal.validate) this._compile(refVal); | |||
root = refVal; | |||
} else { | |||
refVal = this._schemas[id]; | |||
if (refVal instanceof SchemaObject) { | |||
if (!refVal.validate) this._compile(refVal); | |||
if (id == normalizeId(ref)) | |||
return { schema: refVal, root: root, baseId: baseId }; | |||
root = refVal; | |||
} else { | |||
return; | |||
} | |||
} | |||
if (!root.schema) return; | |||
baseId = getFullPath(this._getId(root.schema)); | |||
} | |||
return getJsonPointer.call(this, p, baseId, root.schema, root); | |||
} | |||
/* @this Ajv */ | |||
function resolveRecursive(root, ref, parsedRef) { | |||
/* jshint validthis: true */ | |||
var res = resolveSchema.call(this, root, ref); | |||
if (res) { | |||
var schema = res.schema; | |||
var baseId = res.baseId; | |||
root = res.root; | |||
var id = this._getId(schema); | |||
if (id) baseId = resolveUrl(baseId, id); | |||
return getJsonPointer.call(this, parsedRef, baseId, schema, root); | |||
} | |||
} | |||
var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']); | |||
/* @this Ajv */ | |||
function getJsonPointer(parsedRef, baseId, schema, root) { | |||
/* jshint validthis: true */ | |||
parsedRef.fragment = parsedRef.fragment || ''; | |||
if (parsedRef.fragment.slice(0,1) != '/') return; | |||
var parts = parsedRef.fragment.split('/'); | |||
for (var i = 1; i < parts.length; i++) { | |||
var part = parts[i]; | |||
if (part) { | |||
part = util.unescapeFragment(part); | |||
schema = schema[part]; | |||
if (schema === undefined) break; | |||
var id; | |||
if (!PREVENT_SCOPE_CHANGE[part]) { | |||
id = this._getId(schema); | |||
if (id) baseId = resolveUrl(baseId, id); | |||
if (schema.$ref) { | |||
var $ref = resolveUrl(baseId, schema.$ref); | |||
var res = resolveSchema.call(this, root, $ref); | |||
if (res) { | |||
schema = res.schema; | |||
root = res.root; | |||
baseId = res.baseId; | |||
} | |||
} | |||
} | |||
} | |||
} | |||
if (schema !== undefined && schema !== root.schema) | |||
return { schema: schema, root: root, baseId: baseId }; | |||
} | |||
var SIMPLE_INLINED = util.toHash([ | |||
'type', 'format', 'pattern', | |||
'maxLength', 'minLength', | |||
'maxProperties', 'minProperties', | |||
'maxItems', 'minItems', | |||
'maximum', 'minimum', | |||
'uniqueItems', 'multipleOf', | |||
'required', 'enum' | |||
]); | |||
function inlineRef(schema, limit) { | |||
if (limit === false) return false; | |||
if (limit === undefined || limit === true) return checkNoRef(schema); | |||
else if (limit) return countKeys(schema) <= limit; | |||
} | |||
function checkNoRef(schema) { | |||
var item; | |||
if (Array.isArray(schema)) { | |||
for (var i=0; i<schema.length; i++) { | |||
item = schema[i]; | |||
if (typeof item == 'object' && !checkNoRef(item)) return false; | |||
} | |||
} else { | |||
for (var key in schema) { | |||
if (key == '$ref') return false; | |||
item = schema[key]; | |||
if (typeof item == 'object' && !checkNoRef(item)) return false; | |||
} | |||
} | |||
return true; | |||
} | |||
function countKeys(schema) { | |||
var count = 0, item; | |||
if (Array.isArray(schema)) { | |||
for (var i=0; i<schema.length; i++) { | |||
item = schema[i]; | |||
if (typeof item == 'object') count += countKeys(item); | |||
if (count == Infinity) return Infinity; | |||
} | |||
} else { | |||
for (var key in schema) { | |||
if (key == '$ref') return Infinity; | |||
if (SIMPLE_INLINED[key]) { | |||
count++; | |||
} else { | |||
item = schema[key]; | |||
if (typeof item == 'object') count += countKeys(item) + 1; | |||
if (count == Infinity) return Infinity; | |||
} | |||
} | |||
} | |||
return count; | |||
} | |||
function getFullPath(id, normalize) { | |||
if (normalize !== false) id = normalizeId(id); | |||
var p = URI.parse(id); | |||
return _getFullPath(p); | |||
} | |||
function _getFullPath(p) { | |||
return URI.serialize(p).split('#')[0] + '#'; | |||
} | |||
var TRAILING_SLASH_HASH = /#\/?$/; | |||
function normalizeId(id) { | |||
return id ? id.replace(TRAILING_SLASH_HASH, '') : ''; | |||
} | |||
function resolveUrl(baseId, id) { | |||
id = normalizeId(id); | |||
return URI.resolve(baseId, id); | |||
} | |||
/* @this Ajv */ | |||
function resolveIds(schema) { | |||
var schemaId = normalizeId(this._getId(schema)); | |||
var baseIds = {'': schemaId}; | |||
var fullPaths = {'': getFullPath(schemaId, false)}; | |||
var localRefs = {}; | |||
var self = this; | |||
traverse(schema, {allKeys: true}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { | |||
if (jsonPtr === '') return; | |||
var id = self._getId(sch); | |||
var baseId = baseIds[parentJsonPtr]; | |||
var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword; | |||
if (keyIndex !== undefined) | |||
fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex)); | |||
if (typeof id == 'string') { | |||
id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id); | |||
var refVal = self._refs[id]; | |||
if (typeof refVal == 'string') refVal = self._refs[refVal]; | |||
if (refVal && refVal.schema) { | |||
if (!equal(sch, refVal.schema)) | |||
throw new Error('id "' + id + '" resolves to more than one schema'); | |||
} else if (id != normalizeId(fullPath)) { | |||
if (id[0] == '#') { | |||
if (localRefs[id] && !equal(sch, localRefs[id])) | |||
throw new Error('id "' + id + '" resolves to more than one schema'); | |||
localRefs[id] = sch; | |||
} else { | |||
self._refs[id] = fullPath; | |||
} | |||
} | |||
} | |||
baseIds[jsonPtr] = baseId; | |||
fullPaths[jsonPtr] = fullPath; | |||
}); | |||
return localRefs; | |||
} |
@ -0,0 +1,66 @@ | |||
'use strict'; | |||
var ruleModules = require('../dotjs') | |||
, toHash = require('./util').toHash; | |||
module.exports = function rules() { | |||
var RULES = [ | |||
{ type: 'number', | |||
rules: [ { 'maximum': ['exclusiveMaximum'] }, | |||
{ 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] }, | |||
{ type: 'string', | |||
rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] }, | |||
{ type: 'array', | |||
rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] }, | |||
{ type: 'object', | |||
rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames', | |||
{ 'properties': ['additionalProperties', 'patternProperties'] } ] }, | |||
{ rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] } | |||
]; | |||
var ALL = [ 'type', '$comment' ]; | |||
var KEYWORDS = [ | |||
'$schema', '$id', 'id', '$data', '$async', 'title', | |||
'description', 'default', 'definitions', | |||
'examples', 'readOnly', 'writeOnly', | |||
'contentMediaType', 'contentEncoding', | |||
'additionalItems', 'then', 'else' | |||
]; | |||
var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ]; | |||
RULES.all = toHash(ALL); | |||
RULES.types = toHash(TYPES); | |||
RULES.forEach(function (group) { | |||
group.rules = group.rules.map(function (keyword) { | |||
var implKeywords; | |||
if (typeof keyword == 'object') { | |||
var key = Object.keys(keyword)[0]; | |||
implKeywords = keyword[key]; | |||
keyword = key; | |||
implKeywords.forEach(function (k) { | |||
ALL.push(k); | |||
RULES.all[k] = true; | |||
}); | |||
} | |||
ALL.push(keyword); | |||
var rule = RULES.all[keyword] = { | |||
keyword: keyword, | |||
code: ruleModules[keyword], | |||
implements: implKeywords | |||
}; | |||
return rule; | |||
}); | |||
RULES.all.$comment = { | |||
keyword: '$comment', | |||
code: ruleModules.$comment | |||
}; | |||
if (group.type) RULES.types[group.type] = group; | |||
}); | |||
RULES.keywords = toHash(ALL.concat(KEYWORDS)); | |||
RULES.custom = {}; | |||
return RULES; | |||
}; |
@ -0,0 +1,9 @@ | |||
'use strict'; | |||
var util = require('./util'); | |||
module.exports = SchemaObject; | |||
function SchemaObject(obj) { | |||
util.copy(obj, this); | |||
} |
@ -0,0 +1,20 @@ | |||
'use strict'; | |||
// https://mathiasbynens.be/notes/javascript-encoding | |||
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode | |||
module.exports = function ucs2length(str) { | |||
var length = 0 | |||
, len = str.length | |||
, pos = 0 | |||
, value; | |||
while (pos < len) { | |||
length++; | |||
value = str.charCodeAt(pos++); | |||
if (value >= 0xD800 && value <= 0xDBFF && pos < len) { | |||
// high surrogate, and there is a next character | |||
value = str.charCodeAt(pos); | |||
if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate | |||
} | |||
} | |||
return length; | |||
}; |
@ -0,0 +1,239 @@ | |||
'use strict'; | |||
module.exports = { | |||
copy: copy, | |||
checkDataType: checkDataType, | |||
checkDataTypes: checkDataTypes, | |||
coerceToTypes: coerceToTypes, | |||
toHash: toHash, | |||
getProperty: getProperty, | |||
escapeQuotes: escapeQuotes, | |||
equal: require('fast-deep-equal'), | |||
ucs2length: require('./ucs2length'), | |||
varOccurences: varOccurences, | |||
varReplace: varReplace, | |||
schemaHasRules: schemaHasRules, | |||
schemaHasRulesExcept: schemaHasRulesExcept, | |||
schemaUnknownRules: schemaUnknownRules, | |||
toQuotedString: toQuotedString, | |||
getPathExpr: getPathExpr, | |||
getPath: getPath, | |||
getData: getData, | |||
unescapeFragment: unescapeFragment, | |||
unescapeJsonPointer: unescapeJsonPointer, | |||
escapeFragment: escapeFragment, | |||
escapeJsonPointer: escapeJsonPointer | |||
}; | |||
function copy(o, to) { | |||
to = to || {}; | |||
for (var key in o) to[key] = o[key]; | |||
return to; | |||
} | |||
function checkDataType(dataType, data, strictNumbers, negate) { | |||
var EQUAL = negate ? ' !== ' : ' === ' | |||
, AND = negate ? ' || ' : ' && ' | |||
, OK = negate ? '!' : '' | |||
, NOT = negate ? '' : '!'; | |||
switch (dataType) { | |||
case 'null': return data + EQUAL + 'null'; | |||
case 'array': return OK + 'Array.isArray(' + data + ')'; | |||
case 'object': return '(' + OK + data + AND + | |||
'typeof ' + data + EQUAL + '"object"' + AND + | |||
NOT + 'Array.isArray(' + data + '))'; | |||
case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + | |||
NOT + '(' + data + ' % 1)' + | |||
AND + data + EQUAL + data + | |||
(strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; | |||
case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' + | |||
(strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; | |||
default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; | |||
} | |||
} | |||
function checkDataTypes(dataTypes, data, strictNumbers) { | |||
switch (dataTypes.length) { | |||
case 1: return checkDataType(dataTypes[0], data, strictNumbers, true); | |||
default: | |||
var code = ''; | |||
var types = toHash(dataTypes); | |||
if (types.array && types.object) { | |||
code = types.null ? '(': '(!' + data + ' || '; | |||
code += 'typeof ' + data + ' !== "object")'; | |||
delete types.null; | |||
delete types.array; | |||
delete types.object; | |||
} | |||
if (types.number) delete types.integer; | |||
for (var t in types) | |||
code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true); | |||
return code; | |||
} | |||
} | |||
var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); | |||
function coerceToTypes(optionCoerceTypes, dataTypes) { | |||
if (Array.isArray(dataTypes)) { | |||
var types = []; | |||
for (var i=0; i<dataTypes.length; i++) { | |||
var t = dataTypes[i]; | |||
if (COERCE_TO_TYPES[t]) types[types.length] = t; | |||
else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t; | |||
} | |||
if (types.length) return types; | |||
} else if (COERCE_TO_TYPES[dataTypes]) { | |||
return [dataTypes]; | |||
} else if (optionCoerceTypes === 'array' && dataTypes === 'array') { | |||
return ['array']; | |||
} | |||
} | |||
function toHash(arr) { | |||
var hash = {}; | |||
for (var i=0; i<arr.length; i++) hash[arr[i]] = true; | |||
return hash; | |||
} | |||
var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; | |||
var SINGLE_QUOTE = /'|\\/g; | |||
function getProperty(key) { | |||
return typeof key == 'number' | |||
? '[' + key + ']' | |||
: IDENTIFIER.test(key) | |||
? '.' + key | |||
: "['" + escapeQuotes(key) + "']"; | |||
} | |||
function escapeQuotes(str) { | |||
return str.replace(SINGLE_QUOTE, '\\$&') | |||
.replace(/\n/g, '\\n') | |||
.replace(/\r/g, '\\r') | |||
.replace(/\f/g, '\\f') | |||
.replace(/\t/g, '\\t'); | |||
} | |||
function varOccurences(str, dataVar) { | |||
dataVar += '[^0-9]'; | |||
var matches = str.match(new RegExp(dataVar, 'g')); | |||
return matches ? matches.length : 0; | |||
} | |||
function varReplace(str, dataVar, expr) { | |||
dataVar += '([^0-9])'; | |||
expr = expr.replace(/\$/g, '$$$$'); | |||
return str.replace(new RegExp(dataVar, 'g'), expr + '$1'); | |||
} | |||
function schemaHasRules(schema, rules) { | |||
if (typeof schema == 'boolean') return !schema; | |||
for (var key in schema) if (rules[key]) return true; | |||
} | |||
function schemaHasRulesExcept(schema, rules, exceptKeyword) { | |||
if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not'; | |||
for (var key in schema) if (key != exceptKeyword && rules[key]) return true; | |||
} | |||
function schemaUnknownRules(schema, rules) { | |||
if (typeof schema == 'boolean') return; | |||
for (var key in schema) if (!rules[key]) return key; | |||
} | |||
function toQuotedString(str) { | |||
return '\'' + escapeQuotes(str) + '\''; | |||
} | |||
function getPathExpr(currentPath, expr, jsonPointers, isNumber) { | |||
var path = jsonPointers // false by default | |||
? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')') | |||
: (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\''); | |||
return joinPaths(currentPath, path); | |||
} | |||
function getPath(currentPath, prop, jsonPointers) { | |||
var path = jsonPointers // false by default | |||
? toQuotedString('/' + escapeJsonPointer(prop)) | |||
: toQuotedString(getProperty(prop)); | |||
return joinPaths(currentPath, path); | |||
} | |||
var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; | |||
var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; | |||
function getData($data, lvl, paths) { | |||
var up, jsonPointer, data, matches; | |||
if ($data === '') return 'rootData'; | |||
if ($data[0] == '/') { | |||
if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data); | |||
jsonPointer = $data; | |||
data = 'rootData'; | |||
} else { | |||
matches = $data.match(RELATIVE_JSON_POINTER); | |||
if (!matches) throw new Error('Invalid JSON-pointer: ' + $data); | |||
up = +matches[1]; | |||
jsonPointer = matches[2]; | |||
if (jsonPointer == '#') { | |||
if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); | |||
return paths[lvl - up]; | |||
} | |||
if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); | |||
data = 'data' + ((lvl - up) || ''); | |||
if (!jsonPointer) return data; | |||
} | |||
var expr = data; | |||
var segments = jsonPointer.split('/'); | |||
for (var i=0; i<segments.length; i++) { | |||
var segment = segments[i]; | |||
if (segment) { | |||
data += getProperty(unescapeJsonPointer(segment)); | |||
expr += ' && ' + data; | |||
} | |||
} | |||
return expr; | |||
} | |||
function joinPaths (a, b) { | |||
if (a == '""') return b; | |||
return (a + ' + ' + b).replace(/([^\\])' \+ '/g, '$1'); | |||
} | |||
function unescapeFragment(str) { | |||
return unescapeJsonPointer(decodeURIComponent(str)); | |||
} | |||
function escapeFragment(str) { | |||
return encodeURIComponent(escapeJsonPointer(str)); | |||
} | |||
function escapeJsonPointer(str) { | |||
return str.replace(/~/g, '~0').replace(/\//g, '~1'); | |||
} | |||
function unescapeJsonPointer(str) { | |||
return str.replace(/~1/g, '/').replace(/~0/g, '~'); | |||
} |
@ -0,0 +1,49 @@ | |||
'use strict'; | |||
var KEYWORDS = [ | |||
'multipleOf', | |||
'maximum', | |||
'exclusiveMaximum', | |||
'minimum', | |||
'exclusiveMinimum', | |||
'maxLength', | |||
'minLength', | |||
'pattern', | |||
'additionalItems', | |||
'maxItems', | |||
'minItems', | |||
'uniqueItems', | |||
'maxProperties', | |||
'minProperties', | |||
'required', | |||
'additionalProperties', | |||
'enum', | |||
'format', | |||
'const' | |||
]; | |||
module.exports = function (metaSchema, keywordsJsonPointers) { | |||
for (var i=0; i<keywordsJsonPointers.length; i++) { | |||
metaSchema = JSON.parse(JSON.stringify(metaSchema)); | |||
var segments = keywordsJsonPointers[i].split('/'); | |||
var keywords = metaSchema; | |||
var j; | |||
for (j=1; j<segments.length; j++) | |||
keywords = keywords[segments[j]]; | |||
for (j=0; j<KEYWORDS.length; j++) { | |||
var key = KEYWORDS[j]; | |||
var schema = keywords[key]; | |||
if (schema) { | |||
keywords[key] = { | |||
anyOf: [ | |||
schema, | |||
{ $ref: 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' } | |||
] | |||
}; | |||
} | |||
} | |||
} | |||
return metaSchema; | |||
}; |
@ -0,0 +1,37 @@ | |||
'use strict'; | |||
var metaSchema = require('./refs/json-schema-draft-07.json'); | |||
module.exports = { | |||
$id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js', | |||
definitions: { | |||
simpleTypes: metaSchema.definitions.simpleTypes | |||
}, | |||
type: 'object', | |||
dependencies: { | |||
schema: ['validate'], | |||
$data: ['validate'], | |||
statements: ['inline'], | |||
valid: {not: {required: ['macro']}} | |||
}, | |||
properties: { | |||
type: metaSchema.properties.type, | |||
schema: {type: 'boolean'}, | |||
statements: {type: 'boolean'}, | |||
dependencies: { | |||
type: 'array', | |||
items: {type: 'string'} | |||
}, | |||
metaSchema: {type: 'object'}, | |||
modifying: {type: 'boolean'}, | |||
valid: {type: 'boolean'}, | |||
$data: {type: 'boolean'}, | |||
async: {type: 'boolean'}, | |||
errors: { | |||
anyOf: [ | |||
{type: 'boolean'}, | |||
{const: 'full'} | |||
] | |||
} | |||
} | |||
}; |
@ -0,0 +1,113 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.$data }} | |||
{{## def.setExclusiveLimit: | |||
$exclusive = true; | |||
$errorKeyword = $exclusiveKeyword; | |||
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; | |||
#}} | |||
{{ | |||
var $isMax = $keyword == 'maximum' | |||
, $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum' | |||
, $schemaExcl = it.schema[$exclusiveKeyword] | |||
, $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data | |||
, $op = $isMax ? '<' : '>' | |||
, $notOp = $isMax ? '>' : '<' | |||
, $errorKeyword = undefined; | |||
if (!($isData || typeof $schema == 'number' || $schema === undefined)) { | |||
throw new Error($keyword + ' must be number'); | |||
} | |||
if (!($isDataExcl || $schemaExcl === undefined | |||
|| typeof $schemaExcl == 'number' | |||
|| typeof $schemaExcl == 'boolean')) { | |||
throw new Error($exclusiveKeyword + ' must be number or boolean'); | |||
} | |||
}} | |||
{{? $isDataExcl }} | |||
{{ | |||
var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr) | |||
, $exclusive = 'exclusive' + $lvl | |||
, $exclType = 'exclType' + $lvl | |||
, $exclIsNumber = 'exclIsNumber' + $lvl | |||
, $opExpr = 'op' + $lvl | |||
, $opStr = '\' + ' + $opExpr + ' + \''; | |||
}} | |||
var schemaExcl{{=$lvl}} = {{=$schemaValueExcl}}; | |||
{{ $schemaValueExcl = 'schemaExcl' + $lvl; }} | |||
var {{=$exclusive}}; | |||
var {{=$exclType}} = typeof {{=$schemaValueExcl}}; | |||
if ({{=$exclType}} != 'boolean' && {{=$exclType}} != 'undefined' && {{=$exclType}} != 'number') { | |||
{{ var $errorKeyword = $exclusiveKeyword; }} | |||
{{# def.error:'_exclusiveLimit' }} | |||
} else if ({{# def.$dataNotType:'number' }} | |||
{{=$exclType}} == 'number' | |||
? ( | |||
({{=$exclusive}} = {{=$schemaValue}} === undefined || {{=$schemaValueExcl}} {{=$op}}= {{=$schemaValue}}) | |||
? {{=$data}} {{=$notOp}}= {{=$schemaValueExcl}} | |||
: {{=$data}} {{=$notOp}} {{=$schemaValue}} | |||
) | |||
: ( | |||
({{=$exclusive}} = {{=$schemaValueExcl}} === true) | |||
? {{=$data}} {{=$notOp}}= {{=$schemaValue}} | |||
: {{=$data}} {{=$notOp}} {{=$schemaValue}} | |||
) | |||
|| {{=$data}} !== {{=$data}}) { | |||
var op{{=$lvl}} = {{=$exclusive}} ? '{{=$op}}' : '{{=$op}}='; | |||
{{ | |||
if ($schema === undefined) { | |||
$errorKeyword = $exclusiveKeyword; | |||
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; | |||
$schemaValue = $schemaValueExcl; | |||
$isData = $isDataExcl; | |||
} | |||
}} | |||
{{??}} | |||
{{ | |||
var $exclIsNumber = typeof $schemaExcl == 'number' | |||
, $opStr = $op; /*used in error*/ | |||
}} | |||
{{? $exclIsNumber && $isData }} | |||
{{ var $opExpr = '\'' + $opStr + '\''; /*used in error*/ }} | |||
if ({{# def.$dataNotType:'number' }} | |||
( {{=$schemaValue}} === undefined | |||
|| {{=$schemaExcl}} {{=$op}}= {{=$schemaValue}} | |||
? {{=$data}} {{=$notOp}}= {{=$schemaExcl}} | |||
: {{=$data}} {{=$notOp}} {{=$schemaValue}} ) | |||
|| {{=$data}} !== {{=$data}}) { | |||
{{??}} | |||
{{ | |||
if ($exclIsNumber && $schema === undefined) { | |||
{{# def.setExclusiveLimit }} | |||
$schemaValue = $schemaExcl; | |||
$notOp += '='; | |||
} else { | |||
if ($exclIsNumber) | |||
$schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); | |||
if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { | |||
{{# def.setExclusiveLimit }} | |||
$notOp += '='; | |||
} else { | |||
$exclusive = false; | |||
$opStr += '='; | |||
} | |||
} | |||
var $opExpr = '\'' + $opStr + '\''; /*used in error*/ | |||
}} | |||
if ({{# def.$dataNotType:'number' }} | |||
{{=$data}} {{=$notOp}} {{=$schemaValue}} | |||
|| {{=$data}} !== {{=$data}}) { | |||
{{?}} | |||
{{?}} | |||
{{ $errorKeyword = $errorKeyword || $keyword; }} | |||
{{# def.error:'_limit' }} | |||
} {{? $breakOnError }} else { {{?}} |
@ -0,0 +1,12 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.$data }} | |||
{{# def.numberKeyword }} | |||
{{ var $op = $keyword == 'maxItems' ? '>' : '<'; }} | |||
if ({{# def.$dataNotType:'number' }} {{=$data}}.length {{=$op}} {{=$schemaValue}}) { | |||
{{ var $errorKeyword = $keyword; }} | |||
{{# def.error:'_limitItems' }} | |||
} {{? $breakOnError }} else { {{?}} |
@ -0,0 +1,12 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.$data }} | |||
{{# def.numberKeyword }} | |||
{{ var $op = $keyword == 'maxLength' ? '>' : '<'; }} | |||
if ({{# def.$dataNotType:'number' }} {{# def.strLength }} {{=$op}} {{=$schemaValue}}) { | |||
{{ var $errorKeyword = $keyword; }} | |||
{{# def.error:'_limitLength' }} | |||
} {{? $breakOnError }} else { {{?}} |
@ -0,0 +1,12 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.$data }} | |||
{{# def.numberKeyword }} | |||
{{ var $op = $keyword == 'maxProperties' ? '>' : '<'; }} | |||
if ({{# def.$dataNotType:'number' }} Object.keys({{=$data}}).length {{=$op}} {{=$schemaValue}}) { | |||
{{ var $errorKeyword = $keyword; }} | |||
{{# def.error:'_limitProperties' }} | |||
} {{? $breakOnError }} else { {{?}} |
@ -0,0 +1,32 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.setupNextLevel }} | |||
{{ | |||
var $currentBaseId = $it.baseId | |||
, $allSchemasEmpty = true; | |||
}} | |||
{{~ $schema:$sch:$i }} | |||
{{? {{# def.nonEmptySchema:$sch }} }} | |||
{{ | |||
$allSchemasEmpty = false; | |||
$it.schema = $sch; | |||
$it.schemaPath = $schemaPath + '[' + $i + ']'; | |||
$it.errSchemaPath = $errSchemaPath + '/' + $i; | |||
}} | |||
{{# def.insertSubschemaCode }} | |||
{{# def.ifResultValid }} | |||
{{?}} | |||
{{~}} | |||
{{? $breakOnError }} | |||
{{? $allSchemasEmpty }} | |||
if (true) { | |||
{{??}} | |||
{{= $closingBraces.slice(0,-1) }} | |||
{{?}} | |||
{{?}} |
@ -0,0 +1,46 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.setupNextLevel }} | |||
{{ | |||
var $noEmptySchema = $schema.every(function($sch) { | |||
return {{# def.nonEmptySchema:$sch }}; | |||
}); | |||
}} | |||
{{? $noEmptySchema }} | |||
{{ var $currentBaseId = $it.baseId; }} | |||
var {{=$errs}} = errors; | |||
var {{=$valid}} = false; | |||
{{# def.setCompositeRule }} | |||
{{~ $schema:$sch:$i }} | |||
{{ | |||
$it.schema = $sch; | |||
$it.schemaPath = $schemaPath + '[' + $i + ']'; | |||
$it.errSchemaPath = $errSchemaPath + '/' + $i; | |||
}} | |||
{{# def.insertSubschemaCode }} | |||
{{=$valid}} = {{=$valid}} || {{=$nextValid}}; | |||
if (!{{=$valid}}) { | |||
{{ $closingBraces += '}'; }} | |||
{{~}} | |||
{{# def.resetCompositeRule }} | |||
{{= $closingBraces }} | |||
if (!{{=$valid}}) { | |||
{{# def.extraError:'anyOf' }} | |||
} else { | |||
{{# def.resetErrors }} | |||
{{? it.opts.allErrors }} } {{?}} | |||
{{??}} | |||
{{? $breakOnError }} | |||
if (true) { | |||
{{?}} | |||
{{?}} |
@ -0,0 +1,51 @@ | |||
{{## def.coerceType: | |||
{{ | |||
var $dataType = 'dataType' + $lvl | |||
, $coerced = 'coerced' + $lvl; | |||
}} | |||
var {{=$dataType}} = typeof {{=$data}}; | |||
var {{=$coerced}} = undefined; | |||
{{? it.opts.coerceTypes == 'array' }} | |||
if ({{=$dataType}} == 'object' && Array.isArray({{=$data}}) && {{=$data}}.length == 1) { | |||
{{=$data}} = {{=$data}}[0]; | |||
{{=$dataType}} = typeof {{=$data}}; | |||
if ({{=it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)}}) {{=$coerced}} = {{=$data}}; | |||
} | |||
{{?}} | |||
if ({{=$coerced}} !== undefined) ; | |||
{{~ $coerceToTypes:$type:$i }} | |||
{{? $type == 'string' }} | |||
else if ({{=$dataType}} == 'number' || {{=$dataType}} == 'boolean') | |||
{{=$coerced}} = '' + {{=$data}}; | |||
else if ({{=$data}} === null) {{=$coerced}} = ''; | |||
{{?? $type == 'number' || $type == 'integer' }} | |||
else if ({{=$dataType}} == 'boolean' || {{=$data}} === null | |||
|| ({{=$dataType}} == 'string' && {{=$data}} && {{=$data}} == +{{=$data}} | |||
{{? $type == 'integer' }} && !({{=$data}} % 1){{?}})) | |||
{{=$coerced}} = +{{=$data}}; | |||
{{?? $type == 'boolean' }} | |||
else if ({{=$data}} === 'false' || {{=$data}} === 0 || {{=$data}} === null) | |||
{{=$coerced}} = false; | |||
else if ({{=$data}} === 'true' || {{=$data}} === 1) | |||
{{=$coerced}} = true; | |||
{{?? $type == 'null' }} | |||
else if ({{=$data}} === '' || {{=$data}} === 0 || {{=$data}} === false) | |||
{{=$coerced}} = null; | |||
{{?? it.opts.coerceTypes == 'array' && $type == 'array' }} | |||
else if ({{=$dataType}} == 'string' || {{=$dataType}} == 'number' || {{=$dataType}} == 'boolean' || {{=$data}} == null) | |||
{{=$coerced}} = [{{=$data}}]; | |||
{{?}} | |||
{{~}} | |||
else { | |||
{{# def.error:'type' }} | |||
} | |||
if ({{=$coerced}} !== undefined) { | |||
{{# def.setParentData }} | |||
{{=$data}} = {{=$coerced}}; | |||
{{? !$dataLvl }}if ({{=$parentData}} !== undefined){{?}} | |||
{{=$parentData}}[{{=$parentDataProperty}}] = {{=$coerced}}; | |||
} | |||
#}} |
@ -0,0 +1,9 @@ | |||
{{# def.definitions }} | |||
{{# def.setupKeyword }} | |||
{{ var $comment = it.util.toQuotedString($schema); }} | |||
{{? it.opts.$comment === true }} | |||
console.log({{=$comment}}); | |||
{{?? typeof it.opts.$comment == 'function' }} | |||
self._opts.$comment({{=$comment}}, {{=it.util.toQuotedString($errSchemaPath)}}, validate.root.schema); | |||
{{?}} |
@ -0,0 +1,11 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.$data }} | |||
{{? !$isData }} | |||
var schema{{=$lvl}} = validate.schema{{=$schemaPath}}; | |||
{{?}} | |||
var {{=$valid}} = equal({{=$data}}, schema{{=$lvl}}); | |||
{{# def.checkError:'const' }} | |||
{{? $breakOnError }} else { {{?}} |
@ -0,0 +1,55 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.setupNextLevel }} | |||
{{ | |||
var $idx = 'i' + $lvl | |||
, $dataNxt = $it.dataLevel = it.dataLevel + 1 | |||
, $nextData = 'data' + $dataNxt | |||
, $currentBaseId = it.baseId | |||
, $nonEmptySchema = {{# def.nonEmptySchema:$schema }}; | |||
}} | |||
var {{=$errs}} = errors; | |||
var {{=$valid}}; | |||
{{? $nonEmptySchema }} | |||
{{# def.setCompositeRule }} | |||
{{ | |||
$it.schema = $schema; | |||
$it.schemaPath = $schemaPath; | |||
$it.errSchemaPath = $errSchemaPath; | |||
}} | |||
var {{=$nextValid}} = false; | |||
for (var {{=$idx}} = 0; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) { | |||
{{ | |||
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); | |||
var $passData = $data + '[' + $idx + ']'; | |||
$it.dataPathArr[$dataNxt] = $idx; | |||
}} | |||
{{# def.generateSubschemaCode }} | |||
{{# def.optimizeValidate }} | |||
if ({{=$nextValid}}) break; | |||
} | |||
{{# def.resetCompositeRule }} | |||
{{= $closingBraces }} | |||
if (!{{=$nextValid}}) { | |||
{{??}} | |||
if ({{=$data}}.length == 0) { | |||
{{?}} | |||
{{# def.error:'contains' }} | |||
} else { | |||
{{? $nonEmptySchema }} | |||
{{# def.resetErrors }} | |||
{{?}} | |||
{{? it.opts.allErrors }} } {{?}} |
@ -0,0 +1,191 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.$data }} | |||
{{ | |||
var $rule = this | |||
, $definition = 'definition' + $lvl | |||
, $rDef = $rule.definition | |||
, $closingBraces = ''; | |||
var $validate = $rDef.validate; | |||
var $compile, $inline, $macro, $ruleValidate, $validateCode; | |||
}} | |||
{{? $isData && $rDef.$data }} | |||
{{ | |||
$validateCode = 'keywordValidate' + $lvl; | |||
var $validateSchema = $rDef.validateSchema; | |||
}} | |||
var {{=$definition}} = RULES.custom['{{=$keyword}}'].definition; | |||
var {{=$validateCode}} = {{=$definition}}.validate; | |||
{{??}} | |||
{{ | |||
$ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); | |||
if (!$ruleValidate) return; | |||
$schemaValue = 'validate.schema' + $schemaPath; | |||
$validateCode = $ruleValidate.code; | |||
$compile = $rDef.compile; | |||
$inline = $rDef.inline; | |||
$macro = $rDef.macro; | |||
}} | |||
{{?}} | |||
{{ | |||
var $ruleErrs = $validateCode + '.errors' | |||
, $i = 'i' + $lvl | |||
, $ruleErr = 'ruleErr' + $lvl | |||
, $asyncKeyword = $rDef.async; | |||
if ($asyncKeyword && !it.async) | |||
throw new Error('async keyword in sync schema'); | |||
}} | |||
{{? !($inline || $macro) }}{{=$ruleErrs}} = null;{{?}} | |||
var {{=$errs}} = errors; | |||
var {{=$valid}}; | |||
{{## def.callRuleValidate: | |||
{{=$validateCode}}.call( | |||
{{? it.opts.passContext }}this{{??}}self{{?}} | |||
{{? $compile || $rDef.schema === false }} | |||
, {{=$data}} | |||
{{??}} | |||
, {{=$schemaValue}} | |||
, {{=$data}} | |||
, validate.schema{{=it.schemaPath}} | |||
{{?}} | |||
, {{# def.dataPath }} | |||
{{# def.passParentData }} | |||
, rootData | |||
) | |||
#}} | |||
{{## def.extendErrors:_inline: | |||
for (var {{=$i}}={{=$errs}}; {{=$i}}<errors; {{=$i}}++) { | |||
var {{=$ruleErr}} = vErrors[{{=$i}}]; | |||
if ({{=$ruleErr}}.dataPath === undefined) | |||
{{=$ruleErr}}.dataPath = (dataPath || '') + {{= it.errorPath }}; | |||
{{# _inline ? 'if (\{\{=$ruleErr\}\}.schemaPath === undefined) {' : '' }} | |||
{{=$ruleErr}}.schemaPath = "{{=$errSchemaPath}}"; | |||
{{# _inline ? '}' : '' }} | |||
{{? it.opts.verbose }} | |||
{{=$ruleErr}}.schema = {{=$schemaValue}}; | |||
{{=$ruleErr}}.data = {{=$data}}; | |||
{{?}} | |||
} | |||
#}} | |||
{{? $isData && $rDef.$data }} | |||
{{ $closingBraces += '}'; }} | |||
if ({{=$schemaValue}} === undefined) { | |||
{{=$valid}} = true; | |||
} else { | |||
{{? $validateSchema }} | |||
{{ $closingBraces += '}'; }} | |||
{{=$valid}} = {{=$definition}}.validateSchema({{=$schemaValue}}); | |||
if ({{=$valid}}) { | |||
{{?}} | |||
{{?}} | |||
{{? $inline }} | |||
{{? $rDef.statements }} | |||
{{= $ruleValidate.validate }} | |||
{{??}} | |||
{{=$valid}} = {{= $ruleValidate.validate }}; | |||
{{?}} | |||
{{?? $macro }} | |||
{{# def.setupNextLevel }} | |||
{{ | |||
$it.schema = $ruleValidate.validate; | |||
$it.schemaPath = ''; | |||
}} | |||
{{# def.setCompositeRule }} | |||
{{ var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); }} | |||
{{# def.resetCompositeRule }} | |||
{{= $code }} | |||
{{??}} | |||
{{# def.beginDefOut}} | |||
{{# def.callRuleValidate }} | |||
{{# def.storeDefOut:def_callRuleValidate }} | |||
{{? $rDef.errors === false }} | |||
{{=$valid}} = {{? $asyncKeyword }}await {{?}}{{= def_callRuleValidate }}; | |||
{{??}} | |||
{{? $asyncKeyword }} | |||
{{ $ruleErrs = 'customErrors' + $lvl; }} | |||
var {{=$ruleErrs}} = null; | |||
try { | |||
{{=$valid}} = await {{= def_callRuleValidate }}; | |||
} catch (e) { | |||
{{=$valid}} = false; | |||
if (e instanceof ValidationError) {{=$ruleErrs}} = e.errors; | |||
else throw e; | |||
} | |||
{{??}} | |||
{{=$ruleErrs}} = null; | |||
{{=$valid}} = {{= def_callRuleValidate }}; | |||
{{?}} | |||
{{?}} | |||
{{?}} | |||
{{? $rDef.modifying }} | |||
if ({{=$parentData}}) {{=$data}} = {{=$parentData}}[{{=$parentDataProperty}}]; | |||
{{?}} | |||
{{= $closingBraces }} | |||
{{## def.notValidationResult: | |||
{{? $rDef.valid === undefined }} | |||
!{{? $macro }}{{=$nextValid}}{{??}}{{=$valid}}{{?}} | |||
{{??}} | |||
{{= !$rDef.valid }} | |||
{{?}} | |||
#}} | |||
{{? $rDef.valid }} | |||
{{? $breakOnError }} if (true) { {{?}} | |||
{{??}} | |||
if ({{# def.notValidationResult }}) { | |||
{{ $errorKeyword = $rule.keyword; }} | |||
{{# def.beginDefOut}} | |||
{{# def.error:'custom' }} | |||
{{# def.storeDefOut:def_customError }} | |||
{{? $inline }} | |||
{{? $rDef.errors }} | |||
{{? $rDef.errors != 'full' }} | |||
{{# def.extendErrors:true }} | |||
{{?}} | |||
{{??}} | |||
{{? $rDef.errors === false}} | |||
{{= def_customError }} | |||
{{??}} | |||
if ({{=$errs}} == errors) { | |||
{{= def_customError }} | |||
} else { | |||
{{# def.extendErrors:true }} | |||
} | |||
{{?}} | |||
{{?}} | |||
{{?? $macro }} | |||
{{# def.extraError:'custom' }} | |||
{{??}} | |||
{{? $rDef.errors === false}} | |||
{{= def_customError }} | |||
{{??}} | |||
if (Array.isArray({{=$ruleErrs}})) { | |||
if (vErrors === null) vErrors = {{=$ruleErrs}}; | |||
else vErrors = vErrors.concat({{=$ruleErrs}}); | |||
errors = vErrors.length; | |||
{{# def.extendErrors:false }} | |||
} else { | |||
{{= def_customError }} | |||
} | |||
{{?}} | |||
{{?}} | |||
} {{? $breakOnError }} else { {{?}} | |||
{{?}} |
@ -0,0 +1,47 @@ | |||
{{## def.assignDefault: | |||
{{? it.compositeRule }} | |||
{{ | |||
if (it.opts.strictDefaults) { | |||
var $defaultMsg = 'default is ignored for: ' + $passData; | |||
if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); | |||
else throw new Error($defaultMsg); | |||
} | |||
}} | |||
{{??}} | |||
if ({{=$passData}} === undefined | |||
{{? it.opts.useDefaults == 'empty' }} | |||
|| {{=$passData}} === null | |||
|| {{=$passData}} === '' | |||
{{?}} | |||
) | |||
{{=$passData}} = {{? it.opts.useDefaults == 'shared' }} | |||
{{= it.useDefault($sch.default) }} | |||
{{??}} | |||
{{= JSON.stringify($sch.default) }} | |||
{{?}}; | |||
{{?}} | |||
#}} | |||
{{## def.defaultProperties: | |||
{{ | |||
var $schema = it.schema.properties | |||
, $schemaKeys = Object.keys($schema); }} | |||
{{~ $schemaKeys:$propertyKey }} | |||
{{ var $sch = $schema[$propertyKey]; }} | |||
{{? $sch.default !== undefined }} | |||
{{ var $passData = $data + it.util.getProperty($propertyKey); }} | |||
{{# def.assignDefault }} | |||
{{?}} | |||
{{~}} | |||
#}} | |||
{{## def.defaultItems: | |||
{{~ it.schema.items:$sch:$i }} | |||
{{? $sch.default !== undefined }} | |||
{{ var $passData = $data + '[' + $i + ']'; }} | |||
{{# def.assignDefault }} | |||
{{?}} | |||
{{~}} | |||
#}} |
@ -0,0 +1,203 @@ | |||
{{## def.setupKeyword: | |||
{{ | |||
var $lvl = it.level; | |||
var $dataLvl = it.dataLevel; | |||
var $schema = it.schema[$keyword]; | |||
var $schemaPath = it.schemaPath + it.util.getProperty($keyword); | |||
var $errSchemaPath = it.errSchemaPath + '/' + $keyword; | |||
var $breakOnError = !it.opts.allErrors; | |||
var $errorKeyword; | |||
var $data = 'data' + ($dataLvl || ''); | |||
var $valid = 'valid' + $lvl; | |||
var $errs = 'errs__' + $lvl; | |||
}} | |||
#}} | |||
{{## def.setCompositeRule: | |||
{{ | |||
var $wasComposite = it.compositeRule; | |||
it.compositeRule = $it.compositeRule = true; | |||
}} | |||
#}} | |||
{{## def.resetCompositeRule: | |||
{{ it.compositeRule = $it.compositeRule = $wasComposite; }} | |||
#}} | |||
{{## def.setupNextLevel: | |||
{{ | |||
var $it = it.util.copy(it); | |||
var $closingBraces = ''; | |||
$it.level++; | |||
var $nextValid = 'valid' + $it.level; | |||
}} | |||
#}} | |||
{{## def.ifValid: | |||
{{? $breakOnError }} | |||
if ({{=$valid}}) { | |||
{{ $closingBraces += '}'; }} | |||
{{?}} | |||
#}} | |||
{{## def.ifResultValid: | |||
{{? $breakOnError }} | |||
if ({{=$nextValid}}) { | |||
{{ $closingBraces += '}'; }} | |||
{{?}} | |||
#}} | |||
{{## def.elseIfValid: | |||
{{? $breakOnError }} | |||
{{ $closingBraces += '}'; }} | |||
else { | |||
{{?}} | |||
#}} | |||
{{## def.nonEmptySchema:_schema: | |||
(it.opts.strictKeywords | |||
? (typeof _schema == 'object' && Object.keys(_schema).length > 0) | |||
|| _schema === false | |||
: it.util.schemaHasRules(_schema, it.RULES.all)) | |||
#}} | |||
{{## def.strLength: | |||
{{? it.opts.unicode === false }} | |||
{{=$data}}.length | |||
{{??}} | |||
ucs2length({{=$data}}) | |||
{{?}} | |||
#}} | |||
{{## def.willOptimize: | |||
it.util.varOccurences($code, $nextData) < 2 | |||
#}} | |||
{{## def.generateSubschemaCode: | |||
{{ | |||
var $code = it.validate($it); | |||
$it.baseId = $currentBaseId; | |||
}} | |||
#}} | |||
{{## def.insertSubschemaCode: | |||
{{= it.validate($it) }} | |||
{{ $it.baseId = $currentBaseId; }} | |||
#}} | |||
{{## def._optimizeValidate: | |||
it.util.varReplace($code, $nextData, $passData) | |||
#}} | |||
{{## def.optimizeValidate: | |||
{{? {{# def.willOptimize}} }} | |||
{{= {{# def._optimizeValidate }} }} | |||
{{??}} | |||
var {{=$nextData}} = {{=$passData}}; | |||
{{= $code }} | |||
{{?}} | |||
#}} | |||
{{## def.$data: | |||
{{ | |||
var $isData = it.opts.$data && $schema && $schema.$data | |||
, $schemaValue; | |||
}} | |||
{{? $isData }} | |||
var schema{{=$lvl}} = {{= it.util.getData($schema.$data, $dataLvl, it.dataPathArr) }}; | |||
{{ $schemaValue = 'schema' + $lvl; }} | |||
{{??}} | |||
{{ $schemaValue = $schema; }} | |||
{{?}} | |||
#}} | |||
{{## def.$dataNotType:_type: | |||
{{?$isData}} ({{=$schemaValue}} !== undefined && typeof {{=$schemaValue}} != _type) || {{?}} | |||
#}} | |||
{{## def.check$dataIsArray: | |||
if (schema{{=$lvl}} === undefined) {{=$valid}} = true; | |||
else if (!Array.isArray(schema{{=$lvl}})) {{=$valid}} = false; | |||
else { | |||
#}} | |||
{{## def.numberKeyword: | |||
{{? !($isData || typeof $schema == 'number') }} | |||
{{ throw new Error($keyword + ' must be number'); }} | |||
{{?}} | |||
#}} | |||
{{## def.beginDefOut: | |||
{{ | |||
var $$outStack = $$outStack || []; | |||
$$outStack.push(out); | |||
out = ''; | |||
}} | |||
#}} | |||
{{## def.storeDefOut:_variable: | |||
{{ | |||
var _variable = out; | |||
out = $$outStack.pop(); | |||
}} | |||
#}} | |||
{{## def.dataPath:(dataPath || ''){{? it.errorPath != '""'}} + {{= it.errorPath }}{{?}}#}} | |||
{{## def.setParentData: | |||
{{ | |||
var $parentData = $dataLvl ? 'data' + (($dataLvl-1)||'') : 'parentData' | |||
, $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; | |||
}} | |||
#}} | |||
{{## def.passParentData: | |||
{{# def.setParentData }} | |||
, {{= $parentData }} | |||
, {{= $parentDataProperty }} | |||
#}} | |||
{{## def.iterateProperties: | |||
{{? $ownProperties }} | |||
{{=$dataProperties}} = {{=$dataProperties}} || Object.keys({{=$data}}); | |||
for (var {{=$idx}}=0; {{=$idx}}<{{=$dataProperties}}.length; {{=$idx}}++) { | |||
var {{=$key}} = {{=$dataProperties}}[{{=$idx}}]; | |||
{{??}} | |||
for (var {{=$key}} in {{=$data}}) { | |||
{{?}} | |||
#}} | |||
{{## def.noPropertyInData: | |||
{{=$useData}} === undefined | |||
{{? $ownProperties }} | |||
|| !{{# def.isOwnProperty }} | |||
{{?}} | |||
#}} | |||
{{## def.isOwnProperty: | |||
Object.prototype.hasOwnProperty.call({{=$data}}, '{{=it.util.escapeQuotes($propertyKey)}}') | |||
#}} |
@ -0,0 +1,79 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.missing }} | |||
{{# def.setupKeyword }} | |||
{{# def.setupNextLevel }} | |||
{{## def.propertyInData: | |||
{{=$data}}{{= it.util.getProperty($property) }} !== undefined | |||
{{? $ownProperties }} | |||
&& Object.prototype.hasOwnProperty.call({{=$data}}, '{{=it.util.escapeQuotes($property)}}') | |||
{{?}} | |||
#}} | |||
{{ | |||
var $schemaDeps = {} | |||
, $propertyDeps = {} | |||
, $ownProperties = it.opts.ownProperties; | |||
for ($property in $schema) { | |||
if ($property == '__proto__') continue; | |||
var $sch = $schema[$property]; | |||
var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps; | |||
$deps[$property] = $sch; | |||
} | |||
}} | |||
var {{=$errs}} = errors; | |||
{{ var $currentErrorPath = it.errorPath; }} | |||
var missing{{=$lvl}}; | |||
{{ for (var $property in $propertyDeps) { }} | |||
{{ $deps = $propertyDeps[$property]; }} | |||
{{? $deps.length }} | |||
if ({{# def.propertyInData }} | |||
{{? $breakOnError }} | |||
&& ({{# def.checkMissingProperty:$deps }})) { | |||
{{# def.errorMissingProperty:'dependencies' }} | |||
{{??}} | |||
) { | |||
{{~ $deps:$propertyKey }} | |||
{{# def.allErrorsMissingProperty:'dependencies' }} | |||
{{~}} | |||
{{?}} | |||
} {{# def.elseIfValid }} | |||
{{?}} | |||
{{ } }} | |||
{{ | |||
it.errorPath = $currentErrorPath; | |||
var $currentBaseId = $it.baseId; | |||
}} | |||
{{ for (var $property in $schemaDeps) { }} | |||
{{ var $sch = $schemaDeps[$property]; }} | |||
{{? {{# def.nonEmptySchema:$sch }} }} | |||
{{=$nextValid}} = true; | |||
if ({{# def.propertyInData }}) { | |||
{{ | |||
$it.schema = $sch; | |||
$it.schemaPath = $schemaPath + it.util.getProperty($property); | |||
$it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); | |||
}} | |||
{{# def.insertSubschemaCode }} | |||
} | |||
{{# def.ifResultValid }} | |||
{{?}} | |||
{{ } }} | |||
{{? $breakOnError }} | |||
{{= $closingBraces }} | |||
if ({{=$errs}} == errors) { | |||
{{?}} |
@ -0,0 +1,30 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.$data }} | |||
{{ | |||
var $i = 'i' + $lvl | |||
, $vSchema = 'schema' + $lvl; | |||
}} | |||
{{? !$isData }} | |||
var {{=$vSchema}} = validate.schema{{=$schemaPath}}; | |||
{{?}} | |||
var {{=$valid}}; | |||
{{?$isData}}{{# def.check$dataIsArray }}{{?}} | |||
{{=$valid}} = false; | |||
for (var {{=$i}}=0; {{=$i}}<{{=$vSchema}}.length; {{=$i}}++) | |||
if (equal({{=$data}}, {{=$vSchema}}[{{=$i}}])) { | |||
{{=$valid}} = true; | |||
break; | |||
} | |||
{{? $isData }} } {{?}} | |||
{{# def.checkError:'enum' }} | |||
{{? $breakOnError }} else { {{?}} |
@ -0,0 +1,194 @@ | |||
{{# def.definitions }} | |||
{{## def._error:_rule: | |||
{{ 'istanbul ignore else'; }} | |||
{{? it.createErrors !== false }} | |||
{ | |||
keyword: '{{= $errorKeyword || _rule }}' | |||
, dataPath: (dataPath || '') + {{= it.errorPath }} | |||
, schemaPath: {{=it.util.toQuotedString($errSchemaPath)}} | |||
, params: {{# def._errorParams[_rule] }} | |||
{{? it.opts.messages !== false }} | |||
, message: {{# def._errorMessages[_rule] }} | |||
{{?}} | |||
{{? it.opts.verbose }} | |||
, schema: {{# def._errorSchemas[_rule] }} | |||
, parentSchema: validate.schema{{=it.schemaPath}} | |||
, data: {{=$data}} | |||
{{?}} | |||
} | |||
{{??}} | |||
{} | |||
{{?}} | |||
#}} | |||
{{## def._addError:_rule: | |||
if (vErrors === null) vErrors = [err]; | |||
else vErrors.push(err); | |||
errors++; | |||
#}} | |||
{{## def.addError:_rule: | |||
var err = {{# def._error:_rule }}; | |||
{{# def._addError:_rule }} | |||
#}} | |||
{{## def.error:_rule: | |||
{{# def.beginDefOut}} | |||
{{# def._error:_rule }} | |||
{{# def.storeDefOut:__err }} | |||
{{? !it.compositeRule && $breakOnError }} | |||
{{ 'istanbul ignore if'; }} | |||
{{? it.async }} | |||
throw new ValidationError([{{=__err}}]); | |||
{{??}} | |||
validate.errors = [{{=__err}}]; | |||
return false; | |||
{{?}} | |||
{{??}} | |||
var err = {{=__err}}; | |||
{{# def._addError:_rule }} | |||
{{?}} | |||
#}} | |||
{{## def.extraError:_rule: | |||
{{# def.addError:_rule}} | |||
{{? !it.compositeRule && $breakOnError }} | |||
{{ 'istanbul ignore if'; }} | |||
{{? it.async }} | |||
throw new ValidationError(vErrors); | |||
{{??}} | |||
validate.errors = vErrors; | |||
return false; | |||
{{?}} | |||
{{?}} | |||
#}} | |||
{{## def.checkError:_rule: | |||
if (!{{=$valid}}) { | |||
{{# def.error:_rule }} | |||
} | |||
#}} | |||
{{## def.resetErrors: | |||
errors = {{=$errs}}; | |||
if (vErrors !== null) { | |||
if ({{=$errs}}) vErrors.length = {{=$errs}}; | |||
else vErrors = null; | |||
} | |||
#}} | |||
{{## def.concatSchema:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=$schema}}{{?}}#}} | |||
{{## def.appendSchema:{{?$isData}}' + {{=$schemaValue}}{{??}}{{=$schemaValue}}'{{?}}#}} | |||
{{## def.concatSchemaEQ:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=it.util.escapeQuotes($schema)}}{{?}}#}} | |||
{{## def._errorMessages = { | |||
'false schema': "'boolean schema is false'", | |||
$ref: "'can\\\'t resolve reference {{=it.util.escapeQuotes($schema)}}'", | |||
additionalItems: "'should NOT have more than {{=$schema.length}} items'", | |||
additionalProperties: "'{{? it.opts._errorDataPathProperty }}is an invalid additional property{{??}}should NOT have additional properties{{?}}'", | |||
anyOf: "'should match some schema in anyOf'", | |||
const: "'should be equal to constant'", | |||
contains: "'should contain a valid item'", | |||
dependencies: "'should have {{? $deps.length == 1 }}property {{= it.util.escapeQuotes($deps[0]) }}{{??}}properties {{= it.util.escapeQuotes($deps.join(\", \")) }}{{?}} when property {{= it.util.escapeQuotes($property) }} is present'", | |||
'enum': "'should be equal to one of the allowed values'", | |||
format: "'should match format \"{{#def.concatSchemaEQ}}\"'", | |||
'if': "'should match \"' + {{=$ifClause}} + '\" schema'", | |||
_limit: "'should be {{=$opStr}} {{#def.appendSchema}}", | |||
_exclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'", | |||
_limitItems: "'should NOT have {{?$keyword=='maxItems'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} items'", | |||
_limitLength: "'should NOT be {{?$keyword=='maxLength'}}longer{{??}}shorter{{?}} than {{#def.concatSchema}} characters'", | |||
_limitProperties:"'should NOT have {{?$keyword=='maxProperties'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} properties'", | |||
multipleOf: "'should be multiple of {{#def.appendSchema}}", | |||
not: "'should NOT be valid'", | |||
oneOf: "'should match exactly one schema in oneOf'", | |||
pattern: "'should match pattern \"{{#def.concatSchemaEQ}}\"'", | |||
propertyNames: "'property name \\'{{=$invalidName}}\\' is invalid'", | |||
required: "'{{? it.opts._errorDataPathProperty }}is a required property{{??}}should have required property \\'{{=$missingProperty}}\\'{{?}}'", | |||
type: "'should be {{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}'", | |||
uniqueItems: "'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)'", | |||
custom: "'should pass \"{{=$rule.keyword}}\" keyword validation'", | |||
patternRequired: "'should have property matching pattern \\'{{=$missingPattern}}\\''", | |||
switch: "'should pass \"switch\" keyword validation'", | |||
_formatLimit: "'should be {{=$opStr}} \"{{#def.concatSchemaEQ}}\"'", | |||
_formatExclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'" | |||
} #}} | |||
{{## def.schemaRefOrVal: {{?$isData}}validate.schema{{=$schemaPath}}{{??}}{{=$schema}}{{?}} #}} | |||
{{## def.schemaRefOrQS: {{?$isData}}validate.schema{{=$schemaPath}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}} | |||
{{## def._errorSchemas = { | |||
'false schema': "false", | |||
$ref: "{{=it.util.toQuotedString($schema)}}", | |||
additionalItems: "false", | |||
additionalProperties: "false", | |||
anyOf: "validate.schema{{=$schemaPath}}", | |||
const: "validate.schema{{=$schemaPath}}", | |||
contains: "validate.schema{{=$schemaPath}}", | |||
dependencies: "validate.schema{{=$schemaPath}}", | |||
'enum': "validate.schema{{=$schemaPath}}", | |||
format: "{{#def.schemaRefOrQS}}", | |||
'if': "validate.schema{{=$schemaPath}}", | |||
_limit: "{{#def.schemaRefOrVal}}", | |||
_exclusiveLimit: "validate.schema{{=$schemaPath}}", | |||
_limitItems: "{{#def.schemaRefOrVal}}", | |||
_limitLength: "{{#def.schemaRefOrVal}}", | |||
_limitProperties:"{{#def.schemaRefOrVal}}", | |||
multipleOf: "{{#def.schemaRefOrVal}}", | |||
not: "validate.schema{{=$schemaPath}}", | |||
oneOf: "validate.schema{{=$schemaPath}}", | |||
pattern: "{{#def.schemaRefOrQS}}", | |||
propertyNames: "validate.schema{{=$schemaPath}}", | |||
required: "validate.schema{{=$schemaPath}}", | |||
type: "validate.schema{{=$schemaPath}}", | |||
uniqueItems: "{{#def.schemaRefOrVal}}", | |||
custom: "validate.schema{{=$schemaPath}}", | |||
patternRequired: "validate.schema{{=$schemaPath}}", | |||
switch: "validate.schema{{=$schemaPath}}", | |||
_formatLimit: "{{#def.schemaRefOrQS}}", | |||
_formatExclusiveLimit: "validate.schema{{=$schemaPath}}" | |||
} #}} | |||
{{## def.schemaValueQS: {{?$isData}}{{=$schemaValue}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}} | |||
{{## def._errorParams = { | |||
'false schema': "{}", | |||
$ref: "{ ref: '{{=it.util.escapeQuotes($schema)}}' }", | |||
additionalItems: "{ limit: {{=$schema.length}} }", | |||
additionalProperties: "{ additionalProperty: '{{=$additionalProperty}}' }", | |||
anyOf: "{}", | |||
const: "{ allowedValue: schema{{=$lvl}} }", | |||
contains: "{}", | |||
dependencies: "{ property: '{{= it.util.escapeQuotes($property) }}', missingProperty: '{{=$missingProperty}}', depsCount: {{=$deps.length}}, deps: '{{= it.util.escapeQuotes($deps.length==1 ? $deps[0] : $deps.join(\", \")) }}' }", | |||
'enum': "{ allowedValues: schema{{=$lvl}} }", | |||
format: "{ format: {{#def.schemaValueQS}} }", | |||
'if': "{ failingKeyword: {{=$ifClause}} }", | |||
_limit: "{ comparison: {{=$opExpr}}, limit: {{=$schemaValue}}, exclusive: {{=$exclusive}} }", | |||
_exclusiveLimit: "{}", | |||
_limitItems: "{ limit: {{=$schemaValue}} }", | |||
_limitLength: "{ limit: {{=$schemaValue}} }", | |||
_limitProperties:"{ limit: {{=$schemaValue}} }", | |||
multipleOf: "{ multipleOf: {{=$schemaValue}} }", | |||
not: "{}", | |||
oneOf: "{ passingSchemas: {{=$passingSchemas}} }", | |||
pattern: "{ pattern: {{#def.schemaValueQS}} }", | |||
propertyNames: "{ propertyName: '{{=$invalidName}}' }", | |||
required: "{ missingProperty: '{{=$missingProperty}}' }", | |||
type: "{ type: '{{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}' }", | |||
uniqueItems: "{ i: i, j: j }", | |||
custom: "{ keyword: '{{=$rule.keyword}}' }", | |||
patternRequired: "{ missingPattern: '{{=$missingPattern}}' }", | |||
switch: "{ caseIndex: {{=$caseIndex}} }", | |||
_formatLimit: "{ comparison: {{=$opExpr}}, limit: {{#def.schemaValueQS}}, exclusive: {{=$exclusive}} }", | |||
_formatExclusiveLimit: "{}" | |||
} #}} |
@ -0,0 +1,106 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{## def.skipFormat: | |||
{{? $breakOnError }} if (true) { {{?}} | |||
{{ return out; }} | |||
#}} | |||
{{? it.opts.format === false }}{{# def.skipFormat }}{{?}} | |||
{{# def.$data }} | |||
{{## def.$dataCheckFormat: | |||
{{# def.$dataNotType:'string' }} | |||
({{? $unknownFormats != 'ignore' }} | |||
({{=$schemaValue}} && !{{=$format}} | |||
{{? $allowUnknown }} | |||
&& self._opts.unknownFormats.indexOf({{=$schemaValue}}) == -1 | |||
{{?}}) || | |||
{{?}} | |||
({{=$format}} && {{=$formatType}} == '{{=$ruleType}}' | |||
&& !(typeof {{=$format}} == 'function' | |||
? {{? it.async}} | |||
(async{{=$lvl}} ? await {{=$format}}({{=$data}}) : {{=$format}}({{=$data}})) | |||
{{??}} | |||
{{=$format}}({{=$data}}) | |||
{{?}} | |||
: {{=$format}}.test({{=$data}})))) | |||
#}} | |||
{{## def.checkFormat: | |||
{{ | |||
var $formatRef = 'formats' + it.util.getProperty($schema); | |||
if ($isObject) $formatRef += '.validate'; | |||
}} | |||
{{? typeof $format == 'function' }} | |||
{{=$formatRef}}({{=$data}}) | |||
{{??}} | |||
{{=$formatRef}}.test({{=$data}}) | |||
{{?}} | |||
#}} | |||
{{ | |||
var $unknownFormats = it.opts.unknownFormats | |||
, $allowUnknown = Array.isArray($unknownFormats); | |||
}} | |||
{{? $isData }} | |||
{{ | |||
var $format = 'format' + $lvl | |||
, $isObject = 'isObject' + $lvl | |||
, $formatType = 'formatType' + $lvl; | |||
}} | |||
var {{=$format}} = formats[{{=$schemaValue}}]; | |||
var {{=$isObject}} = typeof {{=$format}} == 'object' | |||
&& !({{=$format}} instanceof RegExp) | |||
&& {{=$format}}.validate; | |||
var {{=$formatType}} = {{=$isObject}} && {{=$format}}.type || 'string'; | |||
if ({{=$isObject}}) { | |||
{{? it.async}} | |||
var async{{=$lvl}} = {{=$format}}.async; | |||
{{?}} | |||
{{=$format}} = {{=$format}}.validate; | |||
} | |||
if ({{# def.$dataCheckFormat }}) { | |||
{{??}} | |||
{{ var $format = it.formats[$schema]; }} | |||
{{? !$format }} | |||
{{? $unknownFormats == 'ignore' }} | |||
{{ it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); }} | |||
{{# def.skipFormat }} | |||
{{?? $allowUnknown && $unknownFormats.indexOf($schema) >= 0 }} | |||
{{# def.skipFormat }} | |||
{{??}} | |||
{{ throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); }} | |||
{{?}} | |||
{{?}} | |||
{{ | |||
var $isObject = typeof $format == 'object' | |||
&& !($format instanceof RegExp) | |||
&& $format.validate; | |||
var $formatType = $isObject && $format.type || 'string'; | |||
if ($isObject) { | |||
var $async = $format.async === true; | |||
$format = $format.validate; | |||
} | |||
}} | |||
{{? $formatType != $ruleType }} | |||
{{# def.skipFormat }} | |||
{{?}} | |||
{{? $async }} | |||
{{ | |||
if (!it.async) throw new Error('async format in sync schema'); | |||
var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; | |||
}} | |||
if (!(await {{=$formatRef}}({{=$data}}))) { | |||
{{??}} | |||
if (!{{# def.checkFormat }}) { | |||
{{?}} | |||
{{?}} | |||
{{# def.error:'format' }} | |||
} {{? $breakOnError }} else { {{?}} |
@ -0,0 +1,73 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.setupNextLevel }} | |||
{{## def.validateIfClause:_clause: | |||
{{ | |||
$it.schema = it.schema['_clause']; | |||
$it.schemaPath = it.schemaPath + '._clause'; | |||
$it.errSchemaPath = it.errSchemaPath + '/_clause'; | |||
}} | |||
{{# def.insertSubschemaCode }} | |||
{{=$valid}} = {{=$nextValid}}; | |||
{{? $thenPresent && $elsePresent }} | |||
{{ $ifClause = 'ifClause' + $lvl; }} | |||
var {{=$ifClause}} = '_clause'; | |||
{{??}} | |||
{{ $ifClause = '\'_clause\''; }} | |||
{{?}} | |||
#}} | |||
{{ | |||
var $thenSch = it.schema['then'] | |||
, $elseSch = it.schema['else'] | |||
, $thenPresent = $thenSch !== undefined && {{# def.nonEmptySchema:$thenSch }} | |||
, $elsePresent = $elseSch !== undefined && {{# def.nonEmptySchema:$elseSch }} | |||
, $currentBaseId = $it.baseId; | |||
}} | |||
{{? $thenPresent || $elsePresent }} | |||
{{ | |||
var $ifClause; | |||
$it.createErrors = false; | |||
$it.schema = $schema; | |||
$it.schemaPath = $schemaPath; | |||
$it.errSchemaPath = $errSchemaPath; | |||
}} | |||
var {{=$errs}} = errors; | |||
var {{=$valid}} = true; | |||
{{# def.setCompositeRule }} | |||
{{# def.insertSubschemaCode }} | |||
{{ $it.createErrors = true; }} | |||
{{# def.resetErrors }} | |||
{{# def.resetCompositeRule }} | |||
{{? $thenPresent }} | |||
if ({{=$nextValid}}) { | |||
{{# def.validateIfClause:then }} | |||
} | |||
{{? $elsePresent }} | |||
else { | |||
{{?}} | |||
{{??}} | |||
if (!{{=$nextValid}}) { | |||
{{?}} | |||
{{? $elsePresent }} | |||
{{# def.validateIfClause:else }} | |||
} | |||
{{?}} | |||
if (!{{=$valid}}) { | |||
{{# def.extraError:'if' }} | |||
} | |||
{{? $breakOnError }} else { {{?}} | |||
{{??}} | |||
{{? $breakOnError }} | |||
if (true) { | |||
{{?}} | |||
{{?}} | |||
@ -0,0 +1,98 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.setupNextLevel }} | |||
{{## def.validateItems:startFrom: | |||
for (var {{=$idx}} = {{=startFrom}}; {{=$idx}} < {{=$data}}.length; {{=$idx}}++) { | |||
{{ | |||
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); | |||
var $passData = $data + '[' + $idx + ']'; | |||
$it.dataPathArr[$dataNxt] = $idx; | |||
}} | |||
{{# def.generateSubschemaCode }} | |||
{{# def.optimizeValidate }} | |||
{{? $breakOnError }} | |||
if (!{{=$nextValid}}) break; | |||
{{?}} | |||
} | |||
#}} | |||
{{ | |||
var $idx = 'i' + $lvl | |||
, $dataNxt = $it.dataLevel = it.dataLevel + 1 | |||
, $nextData = 'data' + $dataNxt | |||
, $currentBaseId = it.baseId; | |||
}} | |||
var {{=$errs}} = errors; | |||
var {{=$valid}}; | |||
{{? Array.isArray($schema) }} | |||
{{ /* 'items' is an array of schemas */}} | |||
{{ var $additionalItems = it.schema.additionalItems; }} | |||
{{? $additionalItems === false }} | |||
{{=$valid}} = {{=$data}}.length <= {{= $schema.length }}; | |||
{{ | |||
var $currErrSchemaPath = $errSchemaPath; | |||
$errSchemaPath = it.errSchemaPath + '/additionalItems'; | |||
}} | |||
{{# def.checkError:'additionalItems' }} | |||
{{ $errSchemaPath = $currErrSchemaPath; }} | |||
{{# def.elseIfValid}} | |||
{{?}} | |||
{{~ $schema:$sch:$i }} | |||
{{? {{# def.nonEmptySchema:$sch }} }} | |||
{{=$nextValid}} = true; | |||
if ({{=$data}}.length > {{=$i}}) { | |||
{{ | |||
var $passData = $data + '[' + $i + ']'; | |||
$it.schema = $sch; | |||
$it.schemaPath = $schemaPath + '[' + $i + ']'; | |||
$it.errSchemaPath = $errSchemaPath + '/' + $i; | |||
$it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); | |||
$it.dataPathArr[$dataNxt] = $i; | |||
}} | |||
{{# def.generateSubschemaCode }} | |||
{{# def.optimizeValidate }} | |||
} | |||
{{# def.ifResultValid }} | |||
{{?}} | |||
{{~}} | |||
{{? typeof $additionalItems == 'object' && {{# def.nonEmptySchema:$additionalItems }} }} | |||
{{ | |||
$it.schema = $additionalItems; | |||
$it.schemaPath = it.schemaPath + '.additionalItems'; | |||
$it.errSchemaPath = it.errSchemaPath + '/additionalItems'; | |||
}} | |||
{{=$nextValid}} = true; | |||
if ({{=$data}}.length > {{= $schema.length }}) { | |||
{{# def.validateItems: $schema.length }} | |||
} | |||
{{# def.ifResultValid }} | |||
{{?}} | |||
{{?? {{# def.nonEmptySchema:$schema }} }} | |||
{{ /* 'items' is a single schema */}} | |||
{{ | |||
$it.schema = $schema; | |||
$it.schemaPath = $schemaPath; | |||
$it.errSchemaPath = $errSchemaPath; | |||
}} | |||
{{# def.validateItems: 0 }} | |||
{{?}} | |||
{{? $breakOnError }} | |||
{{= $closingBraces }} | |||
if ({{=$errs}} == errors) { | |||
{{?}} |
@ -0,0 +1,39 @@ | |||
{{## def.checkMissingProperty:_properties: | |||
{{~ _properties:$propertyKey:$i }} | |||
{{?$i}} || {{?}} | |||
{{ | |||
var $prop = it.util.getProperty($propertyKey) | |||
, $useData = $data + $prop; | |||
}} | |||
( ({{# def.noPropertyInData }}) && (missing{{=$lvl}} = {{= it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) }}) ) | |||
{{~}} | |||
#}} | |||
{{## def.errorMissingProperty:_error: | |||
{{ | |||
var $propertyPath = 'missing' + $lvl | |||
, $missingProperty = '\' + ' + $propertyPath + ' + \''; | |||
if (it.opts._errorDataPathProperty) { | |||
it.errorPath = it.opts.jsonPointers | |||
? it.util.getPathExpr($currentErrorPath, $propertyPath, true) | |||
: $currentErrorPath + ' + ' + $propertyPath; | |||
} | |||
}} | |||
{{# def.error:_error }} | |||
#}} | |||
{{## def.allErrorsMissingProperty:_error: | |||
{{ | |||
var $prop = it.util.getProperty($propertyKey) | |||
, $missingProperty = it.util.escapeQuotes($propertyKey) | |||
, $useData = $data + $prop; | |||
if (it.opts._errorDataPathProperty) { | |||
it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); | |||
} | |||
}} | |||
if ({{# def.noPropertyInData }}) { | |||
{{# def.addError:_error }} | |||
} | |||
#}} |
@ -0,0 +1,22 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.$data }} | |||
{{# def.numberKeyword }} | |||
var division{{=$lvl}}; | |||
if ({{?$isData}} | |||
{{=$schemaValue}} !== undefined && ( | |||
typeof {{=$schemaValue}} != 'number' || | |||
{{?}} | |||
(division{{=$lvl}} = {{=$data}} / {{=$schemaValue}}, | |||
{{? it.opts.multipleOfPrecision }} | |||
Math.abs(Math.round(division{{=$lvl}}) - division{{=$lvl}}) > 1e-{{=it.opts.multipleOfPrecision}} | |||
{{??}} | |||
division{{=$lvl}} !== parseInt(division{{=$lvl}}) | |||
{{?}} | |||
) | |||
{{?$isData}} ) {{?}} ) { | |||
{{# def.error:'multipleOf' }} | |||
} {{? $breakOnError }} else { {{?}} |
@ -0,0 +1,43 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.setupNextLevel }} | |||
{{? {{# def.nonEmptySchema:$schema }} }} | |||
{{ | |||
$it.schema = $schema; | |||
$it.schemaPath = $schemaPath; | |||
$it.errSchemaPath = $errSchemaPath; | |||
}} | |||
var {{=$errs}} = errors; | |||
{{# def.setCompositeRule }} | |||
{{ | |||
$it.createErrors = false; | |||
var $allErrorsOption; | |||
if ($it.opts.allErrors) { | |||
$allErrorsOption = $it.opts.allErrors; | |||
$it.opts.allErrors = false; | |||
} | |||
}} | |||
{{= it.validate($it) }} | |||
{{ | |||
$it.createErrors = true; | |||
if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; | |||
}} | |||
{{# def.resetCompositeRule }} | |||
if ({{=$nextValid}}) { | |||
{{# def.error:'not' }} | |||
} else { | |||
{{# def.resetErrors }} | |||
{{? it.opts.allErrors }} } {{?}} | |||
{{??}} | |||
{{# def.addError:'not' }} | |||
{{? $breakOnError}} | |||
if (false) { | |||
{{?}} | |||
{{?}} |
@ -0,0 +1,54 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.setupNextLevel }} | |||
{{ | |||
var $currentBaseId = $it.baseId | |||
, $prevValid = 'prevValid' + $lvl | |||
, $passingSchemas = 'passingSchemas' + $lvl; | |||
}} | |||
var {{=$errs}} = errors | |||
, {{=$prevValid}} = false | |||
, {{=$valid}} = false | |||
, {{=$passingSchemas}} = null; | |||
{{# def.setCompositeRule }} | |||
{{~ $schema:$sch:$i }} | |||
{{? {{# def.nonEmptySchema:$sch }} }} | |||
{{ | |||
$it.schema = $sch; | |||
$it.schemaPath = $schemaPath + '[' + $i + ']'; | |||
$it.errSchemaPath = $errSchemaPath + '/' + $i; | |||
}} | |||
{{# def.insertSubschemaCode }} | |||
{{??}} | |||
var {{=$nextValid}} = true; | |||
{{?}} | |||
{{? $i }} | |||
if ({{=$nextValid}} && {{=$prevValid}}) { | |||
{{=$valid}} = false; | |||
{{=$passingSchemas}} = [{{=$passingSchemas}}, {{=$i}}]; | |||
} else { | |||
{{ $closingBraces += '}'; }} | |||
{{?}} | |||
if ({{=$nextValid}}) { | |||
{{=$valid}} = {{=$prevValid}} = true; | |||
{{=$passingSchemas}} = {{=$i}}; | |||
} | |||
{{~}} | |||
{{# def.resetCompositeRule }} | |||
{{= $closingBraces }} | |||
if (!{{=$valid}}) { | |||
{{# def.extraError:'oneOf' }} | |||
} else { | |||
{{# def.resetErrors }} | |||
{{? it.opts.allErrors }} } {{?}} |
@ -0,0 +1,14 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.$data }} | |||
{{ | |||
var $regexp = $isData | |||
? '(new RegExp(' + $schemaValue + '))' | |||
: it.usePattern($schema); | |||
}} | |||
if ({{# def.$dataNotType:'string' }} !{{=$regexp}}.test({{=$data}}) ) { | |||
{{# def.error:'pattern' }} | |||
} {{? $breakOnError }} else { {{?}} |
@ -0,0 +1,245 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.setupNextLevel }} | |||
{{## def.validateAdditional: | |||
{{ /* additionalProperties is schema */ | |||
$it.schema = $aProperties; | |||
$it.schemaPath = it.schemaPath + '.additionalProperties'; | |||
$it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; | |||
$it.errorPath = it.opts._errorDataPathProperty | |||
? it.errorPath | |||
: it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); | |||
var $passData = $data + '[' + $key + ']'; | |||
$it.dataPathArr[$dataNxt] = $key; | |||
}} | |||
{{# def.generateSubschemaCode }} | |||
{{# def.optimizeValidate }} | |||
#}} | |||
{{ | |||
var $key = 'key' + $lvl | |||
, $idx = 'idx' + $lvl | |||
, $dataNxt = $it.dataLevel = it.dataLevel + 1 | |||
, $nextData = 'data' + $dataNxt | |||
, $dataProperties = 'dataProperties' + $lvl; | |||
var $schemaKeys = Object.keys($schema || {}).filter(notProto) | |||
, $pProperties = it.schema.patternProperties || {} | |||
, $pPropertyKeys = Object.keys($pProperties).filter(notProto) | |||
, $aProperties = it.schema.additionalProperties | |||
, $someProperties = $schemaKeys.length || $pPropertyKeys.length | |||
, $noAdditional = $aProperties === false | |||
, $additionalIsSchema = typeof $aProperties == 'object' | |||
&& Object.keys($aProperties).length | |||
, $removeAdditional = it.opts.removeAdditional | |||
, $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional | |||
, $ownProperties = it.opts.ownProperties | |||
, $currentBaseId = it.baseId; | |||
var $required = it.schema.required; | |||
if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) { | |||
var $requiredHash = it.util.toHash($required); | |||
} | |||
function notProto(p) { return p !== '__proto__'; } | |||
}} | |||
var {{=$errs}} = errors; | |||
var {{=$nextValid}} = true; | |||
{{? $ownProperties }} | |||
var {{=$dataProperties}} = undefined; | |||
{{?}} | |||
{{? $checkAdditional }} | |||
{{# def.iterateProperties }} | |||
{{? $someProperties }} | |||
var isAdditional{{=$lvl}} = !(false | |||
{{? $schemaKeys.length }} | |||
{{? $schemaKeys.length > 8 }} | |||
|| validate.schema{{=$schemaPath}}.hasOwnProperty({{=$key}}) | |||
{{??}} | |||
{{~ $schemaKeys:$propertyKey }} | |||
|| {{=$key}} == {{= it.util.toQuotedString($propertyKey) }} | |||
{{~}} | |||
{{?}} | |||
{{?}} | |||
{{? $pPropertyKeys.length }} | |||
{{~ $pPropertyKeys:$pProperty:$i }} | |||
|| {{= it.usePattern($pProperty) }}.test({{=$key}}) | |||
{{~}} | |||
{{?}} | |||
); | |||
if (isAdditional{{=$lvl}}) { | |||
{{?}} | |||
{{? $removeAdditional == 'all' }} | |||
delete {{=$data}}[{{=$key}}]; | |||
{{??}} | |||
{{ | |||
var $currentErrorPath = it.errorPath; | |||
var $additionalProperty = '\' + ' + $key + ' + \''; | |||
if (it.opts._errorDataPathProperty) { | |||
it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); | |||
} | |||
}} | |||
{{? $noAdditional }} | |||
{{? $removeAdditional }} | |||
delete {{=$data}}[{{=$key}}]; | |||
{{??}} | |||
{{=$nextValid}} = false; | |||
{{ | |||
var $currErrSchemaPath = $errSchemaPath; | |||
$errSchemaPath = it.errSchemaPath + '/additionalProperties'; | |||
}} | |||
{{# def.error:'additionalProperties' }} | |||
{{ $errSchemaPath = $currErrSchemaPath; }} | |||
{{? $breakOnError }} break; {{?}} | |||
{{?}} | |||
{{?? $additionalIsSchema }} | |||
{{? $removeAdditional == 'failing' }} | |||
var {{=$errs}} = errors; | |||
{{# def.setCompositeRule }} | |||
{{# def.validateAdditional }} | |||
if (!{{=$nextValid}}) { | |||
errors = {{=$errs}}; | |||
if (validate.errors !== null) { | |||
if (errors) validate.errors.length = errors; | |||
else validate.errors = null; | |||
} | |||
delete {{=$data}}[{{=$key}}]; | |||
} | |||
{{# def.resetCompositeRule }} | |||
{{??}} | |||
{{# def.validateAdditional }} | |||
{{? $breakOnError }} if (!{{=$nextValid}}) break; {{?}} | |||
{{?}} | |||
{{?}} | |||
{{ it.errorPath = $currentErrorPath; }} | |||
{{?}} | |||
{{? $someProperties }} | |||
} | |||
{{?}} | |||
} | |||
{{# def.ifResultValid }} | |||
{{?}} | |||
{{ var $useDefaults = it.opts.useDefaults && !it.compositeRule; }} | |||
{{? $schemaKeys.length }} | |||
{{~ $schemaKeys:$propertyKey }} | |||
{{ var $sch = $schema[$propertyKey]; }} | |||
{{? {{# def.nonEmptySchema:$sch}} }} | |||
{{ | |||
var $prop = it.util.getProperty($propertyKey) | |||
, $passData = $data + $prop | |||
, $hasDefault = $useDefaults && $sch.default !== undefined; | |||
$it.schema = $sch; | |||
$it.schemaPath = $schemaPath + $prop; | |||
$it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); | |||
$it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); | |||
$it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); | |||
}} | |||
{{# def.generateSubschemaCode }} | |||
{{? {{# def.willOptimize }} }} | |||
{{ | |||
$code = {{# def._optimizeValidate }}; | |||
var $useData = $passData; | |||
}} | |||
{{??}} | |||
{{ var $useData = $nextData; }} | |||
var {{=$nextData}} = {{=$passData}}; | |||
{{?}} | |||
{{? $hasDefault }} | |||
{{= $code }} | |||
{{??}} | |||
{{? $requiredHash && $requiredHash[$propertyKey] }} | |||
if ({{# def.noPropertyInData }}) { | |||
{{=$nextValid}} = false; | |||
{{ | |||
var $currentErrorPath = it.errorPath | |||
, $currErrSchemaPath = $errSchemaPath | |||
, $missingProperty = it.util.escapeQuotes($propertyKey); | |||
if (it.opts._errorDataPathProperty) { | |||
it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); | |||
} | |||
$errSchemaPath = it.errSchemaPath + '/required'; | |||
}} | |||
{{# def.error:'required' }} | |||
{{ $errSchemaPath = $currErrSchemaPath; }} | |||
{{ it.errorPath = $currentErrorPath; }} | |||
} else { | |||
{{??}} | |||
{{? $breakOnError }} | |||
if ({{# def.noPropertyInData }}) { | |||
{{=$nextValid}} = true; | |||
} else { | |||
{{??}} | |||
if ({{=$useData}} !== undefined | |||
{{? $ownProperties }} | |||
&& {{# def.isOwnProperty }} | |||
{{?}} | |||
) { | |||
{{?}} | |||
{{?}} | |||
{{= $code }} | |||
} | |||
{{?}} {{ /* $hasDefault */ }} | |||
{{?}} {{ /* def.nonEmptySchema */ }} | |||
{{# def.ifResultValid }} | |||
{{~}} | |||
{{?}} | |||
{{? $pPropertyKeys.length }} | |||
{{~ $pPropertyKeys:$pProperty }} | |||
{{ var $sch = $pProperties[$pProperty]; }} | |||
{{? {{# def.nonEmptySchema:$sch}} }} | |||
{{ | |||
$it.schema = $sch; | |||
$it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); | |||
$it.errSchemaPath = it.errSchemaPath + '/patternProperties/' | |||
+ it.util.escapeFragment($pProperty); | |||
}} | |||
{{# def.iterateProperties }} | |||
if ({{= it.usePattern($pProperty) }}.test({{=$key}})) { | |||
{{ | |||
$it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); | |||
var $passData = $data + '[' + $key + ']'; | |||
$it.dataPathArr[$dataNxt] = $key; | |||
}} | |||
{{# def.generateSubschemaCode }} | |||
{{# def.optimizeValidate }} | |||
{{? $breakOnError }} if (!{{=$nextValid}}) break; {{?}} | |||
} | |||
{{? $breakOnError }} else {{=$nextValid}} = true; {{?}} | |||
} | |||
{{# def.ifResultValid }} | |||
{{?}} {{ /* def.nonEmptySchema */ }} | |||
{{~}} | |||
{{?}} | |||
{{? $breakOnError }} | |||
{{= $closingBraces }} | |||
if ({{=$errs}} == errors) { | |||
{{?}} |
@ -0,0 +1,52 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{# def.setupNextLevel }} | |||
var {{=$errs}} = errors; | |||
{{? {{# def.nonEmptySchema:$schema }} }} | |||
{{ | |||
$it.schema = $schema; | |||
$it.schemaPath = $schemaPath; | |||
$it.errSchemaPath = $errSchemaPath; | |||
}} | |||
{{ | |||
var $key = 'key' + $lvl | |||
, $idx = 'idx' + $lvl | |||
, $i = 'i' + $lvl | |||
, $invalidName = '\' + ' + $key + ' + \'' | |||
, $dataNxt = $it.dataLevel = it.dataLevel + 1 | |||
, $nextData = 'data' + $dataNxt | |||
, $dataProperties = 'dataProperties' + $lvl | |||
, $ownProperties = it.opts.ownProperties | |||
, $currentBaseId = it.baseId; | |||
}} | |||
{{? $ownProperties }} | |||
var {{=$dataProperties}} = undefined; | |||
{{?}} | |||
{{# def.iterateProperties }} | |||
var startErrs{{=$lvl}} = errors; | |||
{{ var $passData = $key; }} | |||
{{# def.setCompositeRule }} | |||
{{# def.generateSubschemaCode }} | |||
{{# def.optimizeValidate }} | |||
{{# def.resetCompositeRule }} | |||
if (!{{=$nextValid}}) { | |||
for (var {{=$i}}=startErrs{{=$lvl}}; {{=$i}}<errors; {{=$i}}++) { | |||
vErrors[{{=$i}}].propertyName = {{=$key}}; | |||
} | |||
{{# def.extraError:'propertyNames' }} | |||
{{? $breakOnError }} break; {{?}} | |||
} | |||
} | |||
{{?}} | |||
{{? $breakOnError }} | |||
{{= $closingBraces }} | |||
if ({{=$errs}} == errors) { | |||
{{?}} |
@ -0,0 +1,85 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.setupKeyword }} | |||
{{## def._validateRef:_v: | |||
{{? it.opts.passContext }} | |||
{{=_v}}.call(this, | |||
{{??}} | |||
{{=_v}}( | |||
{{?}} | |||
{{=$data}}, {{# def.dataPath }}{{# def.passParentData }}, rootData) | |||
#}} | |||
{{ var $async, $refCode; }} | |||
{{? $schema == '#' || $schema == '#/' }} | |||
{{ | |||
if (it.isRoot) { | |||
$async = it.async; | |||
$refCode = 'validate'; | |||
} else { | |||
$async = it.root.schema.$async === true; | |||
$refCode = 'root.refVal[0]'; | |||
} | |||
}} | |||
{{??}} | |||
{{ var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); }} | |||
{{? $refVal === undefined }} | |||
{{ var $message = it.MissingRefError.message(it.baseId, $schema); }} | |||
{{? it.opts.missingRefs == 'fail' }} | |||
{{ it.logger.error($message); }} | |||
{{# def.error:'$ref' }} | |||
{{? $breakOnError }} if (false) { {{?}} | |||
{{?? it.opts.missingRefs == 'ignore' }} | |||
{{ it.logger.warn($message); }} | |||
{{? $breakOnError }} if (true) { {{?}} | |||
{{??}} | |||
{{ throw new it.MissingRefError(it.baseId, $schema, $message); }} | |||
{{?}} | |||
{{?? $refVal.inline }} | |||
{{# def.setupNextLevel }} | |||
{{ | |||
$it.schema = $refVal.schema; | |||
$it.schemaPath = ''; | |||
$it.errSchemaPath = $schema; | |||
}} | |||
{{ var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); }} | |||
{{= $code }} | |||
{{? $breakOnError}} | |||
if ({{=$nextValid}}) { | |||
{{?}} | |||
{{??}} | |||
{{ | |||
$async = $refVal.$async === true || (it.async && $refVal.$async !== false); | |||
$refCode = $refVal.code; | |||
}} | |||
{{?}} | |||
{{?}} | |||
{{? $refCode }} | |||
{{# def.beginDefOut}} | |||
{{# def._validateRef:$refCode }} | |||
{{# def.storeDefOut:__callValidate }} | |||
{{? $async }} | |||
{{ if (!it.async) throw new Error('async schema referenced by sync schema'); }} | |||
{{? $breakOnError }} var {{=$valid}}; {{?}} | |||
try { | |||
await {{=__callValidate}}; | |||
{{? $breakOnError }} {{=$valid}} = true; {{?}} | |||
} catch (e) { | |||
if (!(e instanceof ValidationError)) throw e; | |||
if (vErrors === null) vErrors = e.errors; | |||
else vErrors = vErrors.concat(e.errors); | |||
errors = vErrors.length; | |||
{{? $breakOnError }} {{=$valid}} = false; {{?}} | |||
} | |||
{{? $breakOnError }} if ({{=$valid}}) { {{?}} | |||
{{??}} | |||
if (!{{=__callValidate}}) { | |||
if (vErrors === null) vErrors = {{=$refCode}}.errors; | |||
else vErrors = vErrors.concat({{=$refCode}}.errors); | |||
errors = vErrors.length; | |||
} {{? $breakOnError }} else { {{?}} | |||
{{?}} | |||
{{?}} |
@ -0,0 +1,108 @@ | |||
{{# def.definitions }} | |||
{{# def.errors }} | |||
{{# def.missing }} | |||
{{# def.setupKeyword }} | |||
{{# def.$data }} | |||
{{ var $vSchema = 'schema' + $lvl; }} | |||
{{## def.setupLoop: | |||
{{? !$isData }} | |||
var {{=$vSchema}} = validate.schema{{=$schemaPath}}; | |||
{{?}} | |||
{{ | |||
var $i = 'i' + $lvl | |||
, $propertyPath = 'schema' + $lvl + '[' + $i + ']' | |||
, $missingProperty = '\' + ' + $propertyPath + ' + \''; | |||
if (it.opts._errorDataPathProperty) { | |||
it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); | |||
} | |||
}} | |||
#}} | |||
{{## def.isRequiredOwnProperty: | |||
Object.prototype.hasOwnProperty.call({{=$data}}, {{=$vSchema}}[{{=$i}}]) | |||
#}} | |||
{{? !$isData }} | |||
{{? $schema.length < it.opts.loopRequired && | |||
it.schema.properties && Object.keys(it.schema.properties).length }} | |||
{{ var $required = []; }} | |||
{{~ $schema:$property }} | |||
{{ var $propertySch = it.schema.properties[$property]; }} | |||
{{? !($propertySch && {{# def.nonEmptySchema:$propertySch}}) }} | |||
{{ $required[$required.length] = $property; }} | |||
{{?}} | |||
{{~}} | |||
{{??}} | |||
{{ var $required = $schema; }} | |||
{{?}} | |||
{{?}} | |||
{{? $isData || $required.length }} | |||
{{ | |||
var $currentErrorPath = it.errorPath | |||
, $loopRequired = $isData || $required.length >= it.opts.loopRequired | |||
, $ownProperties = it.opts.ownProperties; | |||
}} | |||
{{? $breakOnError }} | |||
var missing{{=$lvl}}; | |||
{{? $loopRequired }} | |||
{{# def.setupLoop }} | |||
var {{=$valid}} = true; | |||
{{?$isData}}{{# def.check$dataIsArray }}{{?}} | |||
for (var {{=$i}} = 0; {{=$i}} < {{=$vSchema}}.length; {{=$i}}++) { | |||
{{=$valid}} = {{=$data}}[{{=$vSchema}}[{{=$i}}]] !== undefined | |||
{{? $ownProperties }} | |||
&& {{# def.isRequiredOwnProperty }} | |||
{{?}}; | |||
if (!{{=$valid}}) break; | |||
} | |||
{{? $isData }} } {{?}} | |||
{{# def.checkError:'required' }} | |||
else { | |||
{{??}} | |||
if ({{# def.checkMissingProperty:$required }}) { | |||
{{# def.errorMissingProperty:'required' }} | |||
} else { | |||
{{?}} | |||
{{??}} | |||
{{? $loopRequired }} | |||
{{# def.setupLoop }} | |||
{{? $isData }} | |||
if ({{=$vSchema}} && !Array.isArray({{=$vSchema}})) { | |||
{{# def.addError:'required' }} | |||
} else if ({{=$vSchema}} !== undefined) { | |||
{{?}} | |||
for (var {{=$i}} = 0; {{=$i}} < {{=$vSchema}}.length; {{=$i}}++) { | |||
if ({{=$data}}[{{=$vSchema}}[{{=$i}}]] === undefined | |||
{{? $ownProperties }} | |||
|| !{{# def.isRequiredOwnProperty }} | |||
{{?}}) { | |||
{{# def.addError:'required' }} | |||
} | |||
} | |||
{{? $isData }} } {{?}} | |||
{{??}} | |||
{{~ $required:$propertyKey }} | |||
{{# def.allErrorsMissingProperty:'required' }} | |||
{{~}} | |||
{{?}} | |||
{{?}} | |||
{{ it.errorPath = $currentErrorPath; }} | |||
{{?? $breakOnError }} | |||
if (true) { | |||
{{?}} |