调整语法, 兼容bun

v2
yutent 2023-10-25 18:45:16 +08:00
parent 148684bf35
commit 6b3a44d387
8 changed files with 913 additions and 912 deletions

View File

@ -14,11 +14,11 @@ import PATH from 'path'
const DEFAULT_FORM_TYPE = 'application/x-www-form-urlencoded' const DEFAULT_FORM_TYPE = 'application/x-www-form-urlencoded'
var __dirname = PATH.dirname(URL.fileURLToPath(import.meta.url)) const __dirname = PATH.dirname(URL.fileURLToPath(import.meta.url))
var tmpdir = PATH.resolve(__dirname, '.tmp/') const tmpdir = PATH.resolve(__dirname, '.tmp/')
var encode = encodeURIComponent const encode = encodeURIComponent
var decode = decodeURIComponent const decode = decodeURIComponent
if (fs.isdir(tmpdir)) { if (fs.isdir(tmpdir)) {
fs.rm(tmpdir, true) fs.rm(tmpdir, true)
@ -44,7 +44,6 @@ export default class Request {
hideProperty(this, '__GET__', null) hideProperty(this, '__GET__', null)
hideProperty(this, '__POST__', null) hideProperty(this, '__POST__', null)
hideProperty(this, '__COOKIE__', parseCookie(this.header('cookie') || '')) hideProperty(this, '__COOKIE__', parseCookie(this.header('cookie') || ''))
this.__fixUrl() this.__fixUrl()
} }

View File

@ -4,16 +4,16 @@
*/ */
// var KEY_REGEXP = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/ // var KEY_REGEXP = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/
var SPLIT_REGEXP = /; */ const SPLIT_REGEXP = /; */
// var encode = encodeURIComponent // var encode = encodeURIComponent
var decode = decodeURIComponent const decode = decodeURIComponent
/** /**
* [parse 格式化字符串] * [parse 格式化字符串]
*/ */
export function parseCookie(str) { export function parseCookie(str) {
var obj = {} let obj = {}
var pairs let pairs
if (typeof str !== 'string') { if (typeof str !== 'string') {
return {} return {}
@ -27,8 +27,8 @@ export function parseCookie(str) {
continue continue
} }
var key = item[0].trim() let key = item[0].trim()
var val = item[1].trim() let val = item[1].trim()
obj[key] = decode(val) obj[key] = decode(val)
} }

View File

@ -1,70 +1,61 @@
import util from 'util' import { WriteStream } from 'node:fs'
import { WriteStream } from 'fs' import { EventEmitter } from 'node:events'
import { EventEmitter } from 'events'
import crypto from 'crypto'
export default function File(properties) {
EventEmitter.call(this)
this.size = 0 export default class File extends EventEmitter {
this.path = null
this.name = null
this.type = null
this.hash = null
this.lastModifiedDate = null
this._writeStream = null #stream = null
for (var key in properties) { size = 0
this[key] = properties[key] path = null
name = null
type = null
lastModifiedDate = null
constructor(props = {}){
super()
for (var key in props) {
this[key] = props[key]
}
} }
if (typeof this.hash === 'string') { open() {
this.hash = crypto.createHash(properties.hash) this.#stream = new WriteStream(this.path)
} else { }
this.hash = null
toJSON() {
return {
size: this.size,
path: this.path,
name: this.name,
type: this.type,
mtime: this.lastModifiedDate,
length: this.length,
filename: this.filename,
mime: this.mime
}
}
write(buffer, cb) {
this.#stream.write(buffer, _ =>{
this.lastModifiedDate = new Date()
this.size += buffer.length
this.emit('progress', this.size)
cb()
})
}
end(cb) {
this.#stream.end(() => {
this.emit('end')
cb()
})
} }
} }
util.inherits(File, EventEmitter)
File.prototype.open = function() {
this._writeStream = new WriteStream(this.path)
}
File.prototype.toJSON = function() {
return {
size: this.size,
path: this.path,
name: this.name,
type: this.type,
mtime: this.lastModifiedDate,
length: this.length,
filename: this.filename,
mime: this.mime
}
}
File.prototype.write = function(buffer, cb) {
var self = this
if (self.hash) {
self.hash.update(buffer)
}
this._writeStream.write(buffer, function() {
self.lastModifiedDate = new Date()
self.size += buffer.length
self.emit('progress', self.size)
cb()
})
}
File.prototype.end = function(cb) {
var self = this
if (self.hash) {
self.hash = self.hash.digest('hex')
}
this._writeStream.end(function() {
self.emit('end')
cb()
})
}

File diff suppressed because it is too large Load Diff

View File

@ -1,33 +1,36 @@
export function JSONParser() { export class JSONParser {
this.data = Buffer.from('')
this.bytesWritten = 0
}
JSONParser.prototype.initWithLength = function(length) { data = Buffer.from('')
this.data = Buffer.alloc(length) bytesWritten = 0
}
JSONParser.prototype.write = function(buffer) { initWithLength(length) {
if (this.data.length >= this.bytesWritten + buffer.length) { this.data = Buffer.alloc(length)
buffer.copy(this.data, this.bytesWritten)
} else {
this.data = Buffer.concat([this.data, buffer])
}
this.bytesWritten += buffer.length
return buffer.length
}
JSONParser.prototype.end = function() {
var data = this.data.toString('utf8')
var fields
try {
fields = JSON.parse(data)
} catch (e) {
fields = Function(`try{return ${data}}catch(e){}`)() || data
} }
this.onField(false, fields) write(buffer) {
this.data = null if (this.data.length >= this.bytesWritten + buffer.length) {
buffer.copy(this.data, this.bytesWritten)
} else {
this.data = Buffer.concat([this.data, buffer])
}
this.bytesWritten += buffer.length
return buffer.length
}
end() {
var data = this.data.toString('utf8')
var fields
try {
fields = JSON.parse(data)
} catch (e) {
fields = Function(`try{return ${data}}catch(e){}`)() || data
}
this.onField(false, fields)
this.data = null
this.onEnd()
}
this.onEnd()
} }

View File

@ -30,298 +30,302 @@ var s = 0,
return c | 0x20 return c | 0x20
} }
export function MultipartParser() { export class MultipartParser {
this.boundary = null boundary = null
this.boundaryChars = null boundaryChars = null
this.lookbehind = null lookbehind = null
this.state = S.PARSER_UNINITIALIZED state = S.PARSER_UNINITIALIZED
this.index = null index = null
this.flags = 0 flags = 0
}
MultipartParser.stateToString = function(stateNumber) {
for (var state in S) {
var number = S[state]
if (number === stateNumber) return state
}
}
MultipartParser.prototype.initWithBoundary = function(str) { static stateToString(stateNumber) {
this.boundary = Buffer.alloc(str.length + 4) for (var state in S) {
this.boundary.write('\r\n--', 0) var number = S[state]
this.boundary.write(str, 4) if (number === stateNumber) return state
this.lookbehind = Buffer.alloc(this.boundary.length + 8)
this.state = S.START
this.boundaryChars = {}
for (var i = 0; i < this.boundary.length; i++) {
this.boundaryChars[this.boundary[i]] = true
}
}
MultipartParser.prototype.write = function(buffer) {
var self = this,
i = 0,
len = buffer.length,
prevIndex = this.index,
index = this.index,
state = this.state,
flags = this.flags,
lookbehind = this.lookbehind,
boundary = this.boundary,
boundaryChars = this.boundaryChars,
boundaryLength = this.boundary.length,
boundaryEnd = boundaryLength - 1,
bufferLength = buffer.length,
c,
cl,
mark = function(name) {
self[name + 'Mark'] = i
},
clear = function(name) {
delete self[name + 'Mark']
},
callback = function(name, buffer, start, end) {
if (start !== undefined && start === end) {
return
}
var callbackSymbol =
'on' + name.substr(0, 1).toUpperCase() + name.substr(1)
if (callbackSymbol in self) {
self[callbackSymbol](buffer, start, end)
}
},
dataCallback = function(name, clear) {
var markSymbol = name + 'Mark'
if (!(markSymbol in self)) {
return
}
if (!clear) {
callback(name, buffer, self[markSymbol], buffer.length)
self[markSymbol] = 0
} else {
callback(name, buffer, self[markSymbol], i)
delete self[markSymbol]
}
} }
}
for (i = 0; i < len; i++) {
c = buffer[i] initWithBoundary(str) {
switch (state) { this.boundary = Buffer.alloc(str.length + 4)
case S.PARSER_UNINITIALIZED: this.boundary.write('\r\n--', 0)
return i this.boundary.write(str, 4)
case S.START: this.lookbehind = Buffer.alloc(this.boundary.length + 8)
index = 0 this.state = S.START
state = S.START_BOUNDARY
case S.START_BOUNDARY: this.boundaryChars = {}
if (index == boundary.length - 2) { for (var i = 0; i < this.boundary.length; i++) {
if (c == HYPHEN) { this.boundaryChars[this.boundary[i]] = true
flags |= F.LAST_BOUNDARY }
} else if (c != CR) { }
return i
} write(buffer) {
index++ var self = this,
break i = 0,
} else if (index - 1 == boundary.length - 2) { len = buffer.length,
if (flags & F.LAST_BOUNDARY && c == HYPHEN) { prevIndex = this.index,
callback('end') index = this.index,
state = S.END state = this.state,
flags = 0 flags = this.flags,
} else if (!(flags & F.LAST_BOUNDARY) && c == LF) { lookbehind = this.lookbehind,
index = 0 boundary = this.boundary,
callback('partBegin') boundaryChars = this.boundaryChars,
state = S.HEADER_FIELD_START boundaryLength = this.boundary.length,
} else { boundaryEnd = boundaryLength - 1,
return i bufferLength = buffer.length,
} c,
break cl,
mark = function(name) {
self[name + 'Mark'] = i
},
clear = function(name) {
delete self[name + 'Mark']
},
callback = function(name, buffer, start, end) {
if (start !== undefined && start === end) {
return
} }
if (c != boundary[index + 2]) { var callbackSymbol =
index = -2 'on' + name.substr(0, 1).toUpperCase() + name.substr(1)
if (callbackSymbol in self) {
self[callbackSymbol](buffer, start, end)
} }
if (c == boundary[index + 2]) { },
index++ dataCallback = function(name, clear) {
} var markSymbol = name + 'Mark'
break if (!(markSymbol in self)) {
case S.HEADER_FIELD_START: return
state = S.HEADER_FIELD
mark('headerField')
index = 0
case S.HEADER_FIELD:
if (c == CR) {
clear('headerField')
state = S.HEADERS_ALMOST_DONE
break
} }
index++ if (!clear) {
if (c == HYPHEN) { callback(name, buffer, self[markSymbol], buffer.length)
break self[markSymbol] = 0
} else {
callback(name, buffer, self[markSymbol], i)
delete self[markSymbol]
} }
}
if (c == COLON) { for (i = 0; i < len; i++) {
if (index == 1) { c = buffer[i]
// empty header field switch (state) {
return i case S.PARSER_UNINITIALIZED:
}
dataCallback('headerField', true)
state = S.HEADER_VALUE_START
break
}
cl = lower(c)
if (cl < A || cl > Z) {
return i return i
} case S.START:
break index = 0
case S.HEADER_VALUE_START: state = S.START_BOUNDARY
if (c == SPACE) { case S.START_BOUNDARY:
break if (index == boundary.length - 2) {
} if (c == HYPHEN) {
flags |= F.LAST_BOUNDARY
mark('headerValue') } else if (c != CR) {
state = S.HEADER_VALUE return i
case S.HEADER_VALUE:
if (c == CR) {
dataCallback('headerValue', true)
callback('headerEnd')
state = S.HEADER_VALUE_ALMOST_DONE
}
break
case S.HEADER_VALUE_ALMOST_DONE:
if (c != LF) {
return i
}
state = S.HEADER_FIELD_START
break
case S.HEADERS_ALMOST_DONE:
if (c != LF) {
return i
}
callback('headersEnd')
state = S.PART_DATA_START
break
case S.PART_DATA_START:
state = S.PART_DATA
mark('partData')
case S.PART_DATA:
prevIndex = index
if (index === 0) {
// boyer-moore derrived algorithm to safely skip non-boundary data
i += boundaryEnd
while (i < bufferLength && !(buffer[i] in boundaryChars)) {
i += boundaryLength
}
i -= boundaryEnd
c = buffer[i]
}
if (index < boundary.length) {
if (boundary[index] == c) {
if (index === 0) {
dataCallback('partData', true)
} }
index++ index++
} else { break
index = 0 } else if (index - 1 == boundary.length - 2) {
} if (flags & F.LAST_BOUNDARY && c == HYPHEN) {
} else if (index == boundary.length) {
index++
if (c == CR) {
// CR = part boundary
flags |= F.PART_BOUNDARY
} else if (c == HYPHEN) {
// HYPHEN = end boundary
flags |= F.LAST_BOUNDARY
} else {
index = 0
}
} else if (index - 1 == boundary.length) {
if (flags & F.PART_BOUNDARY) {
index = 0
if (c == LF) {
// unset the PART_BOUNDARY flag
flags &= ~F.PART_BOUNDARY
callback('partEnd')
callback('partBegin')
state = S.HEADER_FIELD_START
break
}
} else if (flags & F.LAST_BOUNDARY) {
if (c == HYPHEN) {
callback('partEnd')
callback('end') callback('end')
state = S.END state = S.END
flags = 0 flags = 0
} else if (!(flags & F.LAST_BOUNDARY) && c == LF) {
index = 0
callback('partBegin')
state = S.HEADER_FIELD_START
} else {
return i
}
break
}
if (c != boundary[index + 2]) {
index = -2
}
if (c == boundary[index + 2]) {
index++
}
break
case S.HEADER_FIELD_START:
state = S.HEADER_FIELD
mark('headerField')
index = 0
case S.HEADER_FIELD:
if (c == CR) {
clear('headerField')
state = S.HEADERS_ALMOST_DONE
break
}
index++
if (c == HYPHEN) {
break
}
if (c == COLON) {
if (index == 1) {
// empty header field
return i
}
dataCallback('headerField', true)
state = S.HEADER_VALUE_START
break
}
cl = lower(c)
if (cl < A || cl > Z) {
return i
}
break
case S.HEADER_VALUE_START:
if (c == SPACE) {
break
}
mark('headerValue')
state = S.HEADER_VALUE
case S.HEADER_VALUE:
if (c == CR) {
dataCallback('headerValue', true)
callback('headerEnd')
state = S.HEADER_VALUE_ALMOST_DONE
}
break
case S.HEADER_VALUE_ALMOST_DONE:
if (c != LF) {
return i
}
state = S.HEADER_FIELD_START
break
case S.HEADERS_ALMOST_DONE:
if (c != LF) {
return i
}
callback('headersEnd')
state = S.PART_DATA_START
break
case S.PART_DATA_START:
state = S.PART_DATA
mark('partData')
case S.PART_DATA:
prevIndex = index
if (index === 0) {
// boyer-moore derrived algorithm to safely skip non-boundary data
i += boundaryEnd
while (i < bufferLength && !(buffer[i] in boundaryChars)) {
i += boundaryLength
}
i -= boundaryEnd
c = buffer[i]
}
if (index < boundary.length) {
if (boundary[index] == c) {
if (index === 0) {
dataCallback('partData', true)
}
index++
} else {
index = 0
}
} else if (index == boundary.length) {
index++
if (c == CR) {
// CR = part boundary
flags |= F.PART_BOUNDARY
} else if (c == HYPHEN) {
// HYPHEN = end boundary
flags |= F.LAST_BOUNDARY
} else {
index = 0
}
} else if (index - 1 == boundary.length) {
if (flags & F.PART_BOUNDARY) {
index = 0
if (c == LF) {
// unset the PART_BOUNDARY flag
flags &= ~F.PART_BOUNDARY
callback('partEnd')
callback('partBegin')
state = S.HEADER_FIELD_START
break
}
} else if (flags & F.LAST_BOUNDARY) {
if (c == HYPHEN) {
callback('partEnd')
callback('end')
state = S.END
flags = 0
} else {
index = 0
}
} else { } else {
index = 0 index = 0
} }
} else {
index = 0
} }
}
if (index > 0) { if (index > 0) {
// when matching a possible boundary, keep a lookbehind reference // when matching a possible boundary, keep a lookbehind reference
// in case it turns out to be a false lead // in case it turns out to be a false lead
lookbehind[index - 1] = c lookbehind[index - 1] = c
} else if (prevIndex > 0) { } else if (prevIndex > 0) {
// if our boundary turned out to be rubbish, the captured lookbehind // if our boundary turned out to be rubbish, the captured lookbehind
// belongs to partData // belongs to partData
callback('partData', lookbehind, 0, prevIndex) callback('partData', lookbehind, 0, prevIndex)
prevIndex = 0 prevIndex = 0
mark('partData') mark('partData')
// reconsider the current character even so it interrupted the sequence // reconsider the current character even so it interrupted the sequence
// it could be the beginning of a new sequence // it could be the beginning of a new sequence
i-- i--
} }
break break
case S.END: case S.END:
break break
default: default:
return i return i
}
}
dataCallback('headerField')
dataCallback('headerValue')
dataCallback('partData')
this.index = index
this.state = state
this.flags = flags
return len
}
end() {
var callback = function(self, name) {
var callbackSymbol = 'on' + name.substr(0, 1).toUpperCase() + name.substr(1)
if (callbackSymbol in self) {
self[callbackSymbol]()
}
}
if (
(this.state == S.HEADER_FIELD_START && this.index === 0) ||
(this.state == S.PART_DATA && this.index == this.boundary.length)
) {
callback(this, 'partEnd')
callback(this, 'end')
} else if (this.state != S.END) {
return new Error(
'MultipartParser.end(): stream ended unexpectedly: ' + this.explain()
)
} }
} }
dataCallback('headerField') explain() {
dataCallback('headerValue') return 'state = ' + MultipartParser.stateToString(this.state)
dataCallback('partData')
this.index = index
this.state = state
this.flags = flags
return len
}
MultipartParser.prototype.end = function() {
var callback = function(self, name) {
var callbackSymbol = 'on' + name.substr(0, 1).toUpperCase() + name.substr(1)
if (callbackSymbol in self) {
self[callbackSymbol]()
}
}
if (
(this.state == S.HEADER_FIELD_START && this.index === 0) ||
(this.state == S.PART_DATA && this.index == this.boundary.length)
) {
callback(this, 'partEnd')
callback(this, 'end')
} else if (this.state != S.END) {
return new Error(
'MultipartParser.end(): stream ended unexpectedly: ' + this.explain()
)
} }
} }
MultipartParser.prototype.explain = function() {
return 'state = ' + MultipartParser.stateToString(this.state)
}

View File

@ -1,17 +1,15 @@
import { EventEmitter } from 'events' import { EventEmitter } from 'events'
import util from 'util'
export function OctetParser() {
EventEmitter.call(this)
}
util.inherits(OctetParser, EventEmitter) export class OctetParser extends EventEmitter {
write(buffer) {
OctetParser.prototype.write = function(buffer) {
this.emit('data', buffer) this.emit('data', buffer)
return buffer.length return buffer.length
} }
OctetParser.prototype.end = function() { end () {
this.emit('end') this.emit('end')
} }
}

View File

@ -1,6 +1,6 @@
// This is a buffering parser, not quite as nice as the multipart one. // This is a buffering parser, not quite as nice as the multipart one.
// If I find time I'll rewrite this to be fully streaming as well // If I find time I'll rewrite this to be fully streaming as well
import querystring from 'querystring' import {parse} from 'node:querystring'
export class QuerystringParser { export class QuerystringParser {
constructor(maxKeys) { constructor(maxKeys) {
@ -14,7 +14,7 @@ export class QuerystringParser {
} }
end() { end() {
var fields = querystring.parse(this.buffer, '&', '=', { var fields = parse(this.buffer, '&', '=', {
maxKeys: this.maxKeys maxKeys: this.maxKeys
}) })
for (var field in fields) { for (var field in fields) {