mirror of
https://ghproxy.cflmy.top/https://github.com/deepseek-ai/deepseek-harness.git
synced 2026-12-01 01:29:35 +08:00
build(vendor): add the element, HTTP and fetch-file packages IM renders through
The Satori packages IM mounts render through `element`, publish through `http` and fetch referenced files through `fetch-file`. All three are pinned by the vendor manifest and rescoped like the rest of `vendor/`.
This commit is contained in:
1 parent
8f236fef35
commit
2e0ea2c172
17 files changed
+1486
No files matched your search
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-present Shigma
|
||||
|
||||
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.
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
# @cordisjs/element
|
||||
Vendored
+54
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"name": "@deepseek-ai/cordis-element",
|
||||
"description": "Element Manipulation",
|
||||
"version": "0.3.0",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json",
|
||||
"./jsx-runtime": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./jsx-dev-runtime": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"src"
|
||||
],
|
||||
"author": "Shigma <shigma10826@gmail.com>",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
|
||||
"directory": "vendor/element"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/cordiverse/element/issues"
|
||||
},
|
||||
"keywords": [
|
||||
"cordis",
|
||||
"element",
|
||||
"segment",
|
||||
"component",
|
||||
"message",
|
||||
"utilities"
|
||||
],
|
||||
"dependencies": {
|
||||
"@deepseek-ai/cosmokit": "workspace:~"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/types/index.d.ts"
|
||||
}
|
||||
Vendored
+434
@@ -0,0 +1,434 @@
|
||||
import { type Awaitable, camelize, defineProperty, type Dict, hyphenate, isNullable, makeArray } from '@deepseek-ai/cosmokit'
|
||||
|
||||
const kElement = Symbol.for('cordis.element')
|
||||
|
||||
export interface Element {
|
||||
[kElement]: true
|
||||
type: string
|
||||
attrs: Dict
|
||||
children: Element[]
|
||||
source?: string
|
||||
getTagName(): string
|
||||
toAttrString(): string
|
||||
toString(strip?: boolean): string
|
||||
}
|
||||
|
||||
interface ElementConstructor extends Element {}
|
||||
|
||||
class ElementConstructor {
|
||||
getTagName() {
|
||||
if (this.type === 'component') {
|
||||
return this.attrs.is?.name ?? 'component'
|
||||
} else {
|
||||
return this.type
|
||||
}
|
||||
}
|
||||
|
||||
toAttrString() {
|
||||
return Object.entries(this.attrs).map(([key, value]) => {
|
||||
if (isNullable(value)) return ''
|
||||
key = hyphenate(key)
|
||||
if (value === true) return ` ${key}`
|
||||
if (value === false) return ` no-${key}`
|
||||
return ` ${key}="${escape('' + value, true)}"`
|
||||
}).join('')
|
||||
}
|
||||
|
||||
toString(strip = false) {
|
||||
if (this.type === 'text' && 'content' in this.attrs) {
|
||||
return strip ? this.attrs.content : escape(this.attrs.content)
|
||||
}
|
||||
const inner = this.children.map(child => child.toString(strip)).join('')
|
||||
if (strip) return inner
|
||||
const attrs = this.toAttrString()
|
||||
const tag = this.getTagName()
|
||||
if (!this.children.length) return `<${tag}${attrs}/>`
|
||||
return `<${tag}${attrs}>${inner}</${tag}>`
|
||||
}
|
||||
}
|
||||
|
||||
defineProperty(ElementConstructor.prototype, kElement, true)
|
||||
defineProperty(ElementConstructor.prototype, 'name', 'Element')
|
||||
|
||||
export const Fragment = ''
|
||||
export type Fragment = string | Element | (string | Element)[]
|
||||
|
||||
export type Render<T, S> = (attrs: Dict, children: Element[], session: S) => T
|
||||
type RenderFunction = Render<Fragment, any>
|
||||
|
||||
export function Element(type: string | RenderFunction, ...children: (Fragment | undefined)[]): Element
|
||||
export function Element(type: string | RenderFunction, attrs: Dict, ...children: (Fragment | undefined)[]): Element
|
||||
export function Element(type: string | RenderFunction, ...args: any[]) {
|
||||
const el = Object.create(ElementConstructor.prototype)
|
||||
const attrs: Dict = {}, children: Element[] = []
|
||||
if (args[0] && typeof args[0] === 'object' && !isElement(args[0]) && !Array.isArray(args[0])) {
|
||||
const props = args.shift()
|
||||
for (const [key, value] of Object.entries(props)) {
|
||||
if (isNullable(value)) continue
|
||||
// https://github.com/reactjs/rfcs/pull/107
|
||||
if (key === 'children') {
|
||||
args.push(...makeArray(value))
|
||||
} else {
|
||||
attrs[camelize(key)] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const child of args) {
|
||||
children.push(...toElementArray(child))
|
||||
}
|
||||
if (typeof type === 'function') {
|
||||
attrs.is = type
|
||||
type = 'component'
|
||||
}
|
||||
return Object.assign(el, { type, attrs, children })
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-new-func
|
||||
const evaluate = new Function('expr', 'context', `
|
||||
try {
|
||||
with (context) {
|
||||
return eval(expr)
|
||||
}
|
||||
} catch {}
|
||||
`) as ((expr: string, context: object) => string)
|
||||
|
||||
export type Visit<T, S> = (element: Element, session?: S) => T
|
||||
export type SyncTransform<S = never> = boolean | Fragment | Render<boolean | Fragment, S>
|
||||
export type Transform<S = never> = boolean | Fragment | Render<Awaitable<boolean | Fragment>, S>
|
||||
|
||||
type SyncVisitor<S> = Dict<SyncTransform<S>> | Visit<boolean | Fragment, S>
|
||||
type Visitor<S> = Dict<Transform<S>> | Visit<Awaitable<boolean | Fragment>, S>
|
||||
|
||||
export function isElement(source: any): source is Element {
|
||||
return source && typeof source === 'object' && source[kElement]
|
||||
}
|
||||
|
||||
export function toElement(content: string | Element) {
|
||||
if (typeof content === 'string' || typeof content === 'number' || typeof content === 'boolean') {
|
||||
content = '' + content
|
||||
if (content) return text(content)
|
||||
} else if (isElement(content)) {
|
||||
return content
|
||||
} else if (!isNullable(content)) {
|
||||
throw new TypeError(`Invalid content: ${content}`)
|
||||
}
|
||||
}
|
||||
|
||||
export function toElementArray(content: Fragment) {
|
||||
if (Array.isArray(content)) {
|
||||
return content.map(toElement).filter((x): x is Element => !!x)
|
||||
} else {
|
||||
return [toElement(content)].filter((x): x is Element => !!x)
|
||||
}
|
||||
}
|
||||
|
||||
export function normalize(source: Fragment, context?: any) {
|
||||
return typeof source === 'string' ? parse(source, context) : toElementArray(source)
|
||||
}
|
||||
|
||||
export function escape(source: string, inline = false) {
|
||||
const result = (source ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
return inline
|
||||
? result.replace(/"/g, '"')
|
||||
: result
|
||||
}
|
||||
|
||||
export function unescape(source: string) {
|
||||
return source
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/&#(\d+);/g, (_, code) => code === '38' ? _ : String.fromCharCode(+code))
|
||||
.replace(/&#x([0-9a-f]+);/gi, (_, code) => code === '26' ? _ : String.fromCharCode(parseInt(code, 16)))
|
||||
.replace(/&(amp|#38|#x26);/g, '&')
|
||||
}
|
||||
|
||||
type Combinator = ' ' | '>' | '+' | '~'
|
||||
|
||||
export interface Selector {
|
||||
type: string
|
||||
combinator: Combinator
|
||||
}
|
||||
|
||||
const combRegExp = / *([ >+~]) */g
|
||||
|
||||
export function parseSelector(input: string): Selector[][] {
|
||||
return input.split(',').map((query) => {
|
||||
const selectors: Selector[] = []
|
||||
query = query.trim()
|
||||
let combCap: RegExpExecArray | null, combinator: Combinator = ' '
|
||||
while ((combCap = combRegExp.exec(query))) {
|
||||
selectors.push({ type: query.slice(0, combCap.index), combinator })
|
||||
combinator = combCap[1] as Combinator
|
||||
query = query.slice(combCap.index + combCap[0].length)
|
||||
}
|
||||
selectors.push({ type: query, combinator })
|
||||
return selectors
|
||||
})
|
||||
}
|
||||
|
||||
export function select(source: string | Element[], query: string | Selector[][]): Element[] {
|
||||
if (!source || !query) return []
|
||||
if (typeof source === 'string') source = parse(source)
|
||||
if (typeof query === 'string') query = parseSelector(query)
|
||||
if (!query.length) return []
|
||||
let adjacent: Selector[][] = []
|
||||
const results: Element[] = []
|
||||
for (const [index, element] of source.entries()) {
|
||||
const inner: Selector[][] = []
|
||||
const local = [...query, ...adjacent]
|
||||
adjacent = []
|
||||
let matched = false
|
||||
for (const group of local) {
|
||||
const { type, combinator } = group[0]
|
||||
if (type === element.type || type === '*') {
|
||||
if (group.length === 1) {
|
||||
matched = true
|
||||
} else if ([' ', '>'].includes(group[1].combinator)) {
|
||||
inner.push(group.slice(1))
|
||||
} else if (group[1].combinator === '+') {
|
||||
adjacent.push(group.slice(1))
|
||||
} else {
|
||||
query.push(group.slice(1))
|
||||
}
|
||||
}
|
||||
if (combinator === ' ') {
|
||||
inner.push(group)
|
||||
}
|
||||
}
|
||||
if (matched) results.push(source[index])
|
||||
results.push(...select(element.children, inner))
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
export function interpolate(expr: string, context: any) {
|
||||
expr = expr.trim()
|
||||
if (!/^[\w.]+$/.test(expr)) {
|
||||
return evaluate(expr, context) ?? ''
|
||||
}
|
||||
let value = context
|
||||
for (const part of expr.split('.')) {
|
||||
value = value[part]
|
||||
if (isNullable(value)) return ''
|
||||
}
|
||||
return value ?? ''
|
||||
}
|
||||
|
||||
const tagRegExp1 = /(?<comment><!--[\s\S]*?-->)|(?<tag><(\/?)([^!\s>/]*)([^>]*?)\s*(\/?)>)/
|
||||
const tagRegExp2 = /(?<comment><!--[\s\S]*?-->)|(?<tag><(\/?)([^!\s>/]*)([^>]*?)\s*(\/?)>)|(?<curly>\{(?<derivative>[@:/#][^\s}]*)?[\s\S]*?\})/
|
||||
const attrRegExp1 = /([^\s=]+)(?:="(?<value1>[^"]*)"|='(?<value2>[^']*)')?/g
|
||||
const attrRegExp2 = /([^\s=]+)(?:="(?<value1>[^"]*)"|='(?<value2>[^']*)'|=\{(?<curly>[^}]+)\})?/g
|
||||
|
||||
const enum Position {
|
||||
OPEN,
|
||||
CLOSE,
|
||||
EMPTY,
|
||||
CONTINUE,
|
||||
}
|
||||
|
||||
interface Token {
|
||||
type: 'angle' | 'curly'
|
||||
name: string
|
||||
position: Position
|
||||
source: string
|
||||
extra: string
|
||||
children?: Dict<(string | Token)[]>
|
||||
}
|
||||
|
||||
export function parse(source: string, context?: any) {
|
||||
const tokens: (string | Token)[] = []
|
||||
function pushText(content: string) {
|
||||
if (content) tokens.push(content)
|
||||
}
|
||||
|
||||
const tagRegExp = context ? tagRegExp2 : tagRegExp1
|
||||
let tagCap: RegExpExecArray | null
|
||||
let trimStart = true
|
||||
while ((tagCap = tagRegExp.exec(source))) {
|
||||
const trimEnd = !tagCap.groups!.curly
|
||||
parseContent(source.slice(0, tagCap.index), trimStart, trimEnd)
|
||||
trimStart = trimEnd
|
||||
source = source.slice(tagCap.index + tagCap[0].length)
|
||||
const [_, , , close, type, extra, empty] = tagCap
|
||||
if (tagCap.groups!.comment) continue
|
||||
if (tagCap.groups!.curly) {
|
||||
let name = '', position = Position.EMPTY
|
||||
if (tagCap.groups!.derivative) {
|
||||
name = tagCap.groups!.derivative.slice(1)
|
||||
position = {
|
||||
'@': Position.EMPTY,
|
||||
'#': Position.OPEN,
|
||||
'/': Position.CLOSE,
|
||||
':': Position.CONTINUE,
|
||||
}[tagCap.groups!.derivative[0]]!
|
||||
}
|
||||
tokens.push({
|
||||
type: 'curly',
|
||||
name,
|
||||
position,
|
||||
source: tagCap.groups!.curly,
|
||||
extra: tagCap.groups!.curly.slice(1 + (tagCap.groups!.derivative ?? '').length, -1),
|
||||
})
|
||||
continue
|
||||
}
|
||||
tokens.push({
|
||||
type: 'angle',
|
||||
source: _,
|
||||
name: type || Fragment,
|
||||
position: close ? Position.CLOSE : empty ? Position.EMPTY : Position.OPEN,
|
||||
extra,
|
||||
})
|
||||
}
|
||||
|
||||
parseContent(source, trimStart, true)
|
||||
function parseContent(source: string, trimStart: boolean, trimEnd: boolean) {
|
||||
source = unescape(source)
|
||||
if (trimStart) source = source.replace(/^\s*\n\s*/, '')
|
||||
if (trimEnd) source = source.replace(/\s*\n\s*$/, '')
|
||||
pushText(source)
|
||||
}
|
||||
|
||||
return parseTokens(foldTokens(tokens), context)
|
||||
}
|
||||
|
||||
function foldTokens(tokens: (string | Token)[]) {
|
||||
const stack: [Required<Token>, string][] = [[{
|
||||
type: 'angle',
|
||||
name: Fragment,
|
||||
position: Position.OPEN,
|
||||
source: '',
|
||||
extra: '',
|
||||
children: { default: [] },
|
||||
}, 'default']]
|
||||
|
||||
function pushToken(...tokens: (string | Token)[]) {
|
||||
const [token, slot] = stack[0]
|
||||
token.children[slot].push(...tokens)
|
||||
}
|
||||
|
||||
for (const token of tokens) {
|
||||
if (typeof token === 'string') {
|
||||
pushToken(token)
|
||||
continue
|
||||
}
|
||||
const { name, position } = token
|
||||
if (position === Position.CLOSE) {
|
||||
if (stack[0][0].name === name) {
|
||||
stack.shift()
|
||||
}
|
||||
} else if (position === Position.CONTINUE) {
|
||||
stack[0][0].children[name] = []
|
||||
stack[0][1] = name
|
||||
} else if (position === Position.OPEN) {
|
||||
pushToken(token)
|
||||
token.children = { default: [] }
|
||||
stack.unshift([token as Required<Token>, 'default'])
|
||||
} else {
|
||||
pushToken(token)
|
||||
}
|
||||
}
|
||||
|
||||
return stack[stack.length - 1][0].children.default
|
||||
}
|
||||
|
||||
function parseTokens(tokens: (string | Token)[], context?: any) {
|
||||
const result: Element[] = []
|
||||
for (const token of tokens) {
|
||||
if (typeof token === 'string') {
|
||||
result.push(text(token))
|
||||
} else if (token.type === 'angle') {
|
||||
const attrs = {}
|
||||
const attrRegExp = context ? attrRegExp2 : attrRegExp1
|
||||
let attrCap: RegExpExecArray | null
|
||||
while ((attrCap = attrRegExp.exec(token.extra))) {
|
||||
const [, key, v1, v2 = v1, v3] = attrCap
|
||||
if (v3) {
|
||||
attrs[key] = interpolate(v3, context)
|
||||
} else if (!isNullable(v2)) {
|
||||
attrs[key] = unescape(v2)
|
||||
} else if (key.startsWith('no-')) {
|
||||
attrs[key.slice(3)] = false
|
||||
} else {
|
||||
attrs[key] = true
|
||||
}
|
||||
}
|
||||
result.push(Element(token.name, attrs, token.children && parseTokens(token.children.default, context)))
|
||||
} else if (!token.name) {
|
||||
result.push(...toElementArray(interpolate(token.extra, context)))
|
||||
} else if (token.name === 'if') {
|
||||
if (evaluate(token.extra, context)) {
|
||||
result.push(...parseTokens(token.children!.default, context))
|
||||
} else {
|
||||
result.push(...parseTokens(token.children!.else || [], context))
|
||||
}
|
||||
} else if (token.name === 'each') {
|
||||
const [expr, ident] = token.extra.split(/\s+as\s+/)
|
||||
const items = interpolate(expr, context)
|
||||
if (!items || !items[Symbol.iterator]) continue
|
||||
for (const item of items) {
|
||||
result.push(...parseTokens(token.children!.default, { ...context, [ident]: item }))
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function visit<S>(element: Element, rules: Visitor<S>, session?: S) {
|
||||
const { type, attrs, children } = element
|
||||
if (typeof rules === 'function') {
|
||||
return rules(element, session)
|
||||
} else {
|
||||
let result: any = rules[typeof type === 'string' ? type : ''] ?? rules.default ?? true
|
||||
if (typeof result === 'function') {
|
||||
result = result(attrs, children, session)
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
export function transform<S = never>(source: string, rules: SyncVisitor<S>, session?: S): string
|
||||
export function transform<S = never>(source: Element[], rules: SyncVisitor<S>, session?: S): Element[]
|
||||
export function transform<S>(source: string | Element[], rules: SyncVisitor<S>, session?: S) {
|
||||
const elements = typeof source === 'string' ? parse(source) : source
|
||||
const output: Element[] = []
|
||||
elements.forEach((element) => {
|
||||
const { type, attrs, children } = element
|
||||
const result = visit(element, rules, session)
|
||||
if (result === true) {
|
||||
output.push(Element(type, attrs, transform(children, rules, session)))
|
||||
} else if (result !== false) {
|
||||
output.push(...toElementArray(result))
|
||||
}
|
||||
})
|
||||
return typeof source === 'string' ? output.join('') : output
|
||||
}
|
||||
|
||||
export async function transformAsync<S = never>(source: string, rules: Visitor<S>, session?: S): Promise<string>
|
||||
export async function transformAsync<S = never>(source: Element[], rules: Visitor<S>, session?: S): Promise<Element[]>
|
||||
export async function transformAsync<S>(source: string | Element[], rules: Visitor<S>, session?: S) {
|
||||
const elements = typeof source === 'string' ? parse(source) : source
|
||||
const children = (await Promise.all(elements.map(async (element) => {
|
||||
const { type, attrs, children } = element
|
||||
const result = await visit(element, rules, session)
|
||||
if (result === true) {
|
||||
return [Element(type, attrs, await transformAsync(children, rules, session))]
|
||||
} else if (result !== false) {
|
||||
return toElementArray(result)
|
||||
} else {
|
||||
return []
|
||||
}
|
||||
}))).flat(1)
|
||||
return typeof source === 'string' ? children.join('') : children
|
||||
}
|
||||
|
||||
export function text(content: string) {
|
||||
return Element('text', { content })
|
||||
}
|
||||
|
||||
export default Element
|
||||
|
||||
export { Element as h, Element as jsx, Element as jsxs, Element as jsxDEV }
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types",
|
||||
"noUncheckedIndexedAccess": false,
|
||||
"exactOptionalPropertyTypes": false,
|
||||
"noImplicitOverride": false,
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noImplicitAny": false
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "../cosmokit"
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-present Shigma
|
||||
|
||||
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.
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
# @cordisjs/fetch-file
|
||||
|
||||
Fetch for `file:` URLs.
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import fetchFile from '@deepseek-ai/cordis-fetch-file';
|
||||
|
||||
const response = await fetchFile('file:///path/to/file.txt');
|
||||
```
|
||||
|
||||
`fetchFile` has the same API as [`fetch`](https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API).
|
||||
Vendored
+47
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "@deepseek-ai/cordis-fetch-file",
|
||||
"description": "Fetch for `file:` URLs",
|
||||
"version": "1.0.3",
|
||||
"sideEffects": false,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/types/node.d.ts",
|
||||
"node": "./lib/node.js",
|
||||
"default": "./lib/browser.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib/node.js",
|
||||
"lib/browser.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"src"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
|
||||
"directory": "vendor/fetch-file"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/cordiverse/fetch-file/issues"
|
||||
},
|
||||
"homepage": "https://github.com/cordiverse/fetch-file",
|
||||
"author": "Shigma <shigma10826@gmail.com>",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@deepseek-ai/cosmokit": "workspace:~",
|
||||
"file-type": "^20.4.1",
|
||||
"mime-types": "^3.0.2"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/mime-types": "^3.0.1"
|
||||
},
|
||||
"main": "lib/node.js",
|
||||
"types": "lib/types/node.d.ts"
|
||||
}
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
export default async function fetchFile() {
|
||||
return new Response(null, { status: 404, statusText: 'Not Found' })
|
||||
}
|
||||
Vendored
+47
@@ -0,0 +1,47 @@
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { basename } from 'node:path'
|
||||
import { createReadStream } from 'node:fs'
|
||||
import { Readable } from 'node:stream'
|
||||
import { fileTypeFromStream } from 'file-type'
|
||||
import { contentType } from 'mime-types'
|
||||
|
||||
namespace fetchFile {
|
||||
export interface Options {
|
||||
download?: boolean
|
||||
onError?: (reason: any) => void
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchFile(url: string | URL, init: RequestInit = {}, options: fetchFile.Options = {}) {
|
||||
url = new URL(url)
|
||||
try {
|
||||
const stream1 = Readable.toWeb(createReadStream(fileURLToPath(url)))
|
||||
const fileType = await fileTypeFromStream(stream1)
|
||||
const stream2 = Readable.toWeb(createReadStream(fileURLToPath(url))) as ReadableStream
|
||||
const filename = basename(url.pathname)
|
||||
return new Response(stream2, {
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: {
|
||||
'content-type': fileType?.mime || contentType(filename) || 'application/octet-stream',
|
||||
...options.download === true
|
||||
? { 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(filename)}` }
|
||||
: options.download === false
|
||||
? { 'content-disposition': 'inline' }
|
||||
: {},
|
||||
},
|
||||
})
|
||||
} catch (error: any) {
|
||||
if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR' || error?.code === 'EISDIR') {
|
||||
return new Response(null, { status: 404, statusText: 'Not Found' })
|
||||
} else if (error?.code === 'EACCES' || error?.code === 'EPERM') {
|
||||
return new Response(null, { status: 403, statusText: 'Forbidden' })
|
||||
} else if (error?.code === 'ENAMETOOLONG') {
|
||||
return new Response(null, { status: 414, statusText: 'URI Too Long' })
|
||||
}
|
||||
options.onError?.(error)
|
||||
return new Response(null, { status: 500, statusText: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
export default fetchFile
|
||||
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types",
|
||||
"noUncheckedIndexedAccess": false,
|
||||
"exactOptionalPropertyTypes": false,
|
||||
"noImplicitOverride": false,
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "../cosmokit"
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
import { defineConfig } from 'tsdown'
|
||||
|
||||
// Keep conditional entries self-contained, without shared output chunks.
|
||||
const shared = {
|
||||
outDir: 'lib',
|
||||
format: ['esm'],
|
||||
target: 'es2024',
|
||||
fixedExtension: false,
|
||||
dts: false,
|
||||
clean: false,
|
||||
} as const
|
||||
|
||||
export default defineConfig([
|
||||
{ ...shared, platform: 'node', entry: ['lib/types/node.js'] },
|
||||
{ ...shared, platform: 'browser', entry: ['lib/types/browser.js'] },
|
||||
])
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020-present Shigma
|
||||
|
||||
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.
|
||||
Vendored
+196
@@ -0,0 +1,196 @@
|
||||
# @cordisjs/http
|
||||
|
||||
Fetch-based HTTP client for [Cordis](https://cordis.io).
|
||||
|
||||
## Features
|
||||
|
||||
- Browser and Node.js support
|
||||
- Proxy agents (HTTP / HTTPS / SOCKS)
|
||||
- WebSocket
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import HTTP from '@deepseek-ai/cordis-plugin-http'
|
||||
|
||||
const ctx = new Context()
|
||||
ctx.plugin(HTTP)
|
||||
|
||||
const data = await ctx.http.get('https://example.com')
|
||||
const data = await ctx.http.post('https://example.com', body)
|
||||
const { status, data } = await ctx.http('https://example.com', { method: 'GET' })
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### Instance Methods
|
||||
|
||||
#### http(url, config?)
|
||||
|
||||
```ts
|
||||
interface HTTP {
|
||||
<T = any>(url: string | URL, config?: Config): Promise<Response<T>>
|
||||
}
|
||||
```
|
||||
|
||||
Send a request.
|
||||
|
||||
#### http.[get|delete|head](url, config?)
|
||||
|
||||
```ts
|
||||
interface HTTP {
|
||||
get: Request1
|
||||
delete: Request1
|
||||
head(url: string, config?: Config): Promise<Headers>
|
||||
}
|
||||
|
||||
interface Request1 {
|
||||
<K extends keyof ResponseTypes>(url: string, config: Config & { responseType: K }): Promise<ResponseTypes[K]>
|
||||
<T = any>(url: string, config?: Config): Promise<T>
|
||||
}
|
||||
```
|
||||
|
||||
Send a GET / DELETE / HEAD request.
|
||||
|
||||
#### http.[post|put|patch](url, data, config?)
|
||||
|
||||
```ts
|
||||
interface HTTP {
|
||||
patch: Request2
|
||||
post: Request2
|
||||
put: Request2
|
||||
}
|
||||
|
||||
interface Request2 {
|
||||
<K extends keyof ResponseTypes>(url: string, data: any, config: Config & { responseType: K }): Promise<ResponseTypes[K]>
|
||||
<T = any>(url: string, data?: any, config?: Config): Promise<T>
|
||||
}
|
||||
```
|
||||
|
||||
#### http.ws(url, config?)
|
||||
|
||||
```ts
|
||||
interface HTTP {
|
||||
ws(url: string | URL, config?: Config): WebSocket
|
||||
}
|
||||
```
|
||||
|
||||
Open a WebSocket connection.
|
||||
|
||||
> [!NOTE]
|
||||
>
|
||||
> Currently we will use [`ws`](https://github.com/websockets/ws) package to polyfill [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) in Node.js.
|
||||
>
|
||||
> Once Node.js has a stable WebSocket API, we will switch to it.
|
||||
|
||||
#### http.Error.is(error)
|
||||
|
||||
```ts
|
||||
function is(error: any): error is Http.Error
|
||||
```
|
||||
|
||||
### Config
|
||||
|
||||
```ts
|
||||
interface Config {
|
||||
baseUrl?: string
|
||||
method?: Method
|
||||
headers?: Record<string, string>
|
||||
redirect?: RequestRedirect
|
||||
keepAlive?: boolean
|
||||
params?: Record<string, any>
|
||||
data?: any
|
||||
responseType?: keyof ResponseTypes
|
||||
timeout?: number
|
||||
}
|
||||
```
|
||||
|
||||
#### config.baseUrl
|
||||
|
||||
The base URL of the request. If it is set, the `url` will be resolved against it.
|
||||
|
||||
See [URL#base](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL#base).
|
||||
|
||||
#### config.method
|
||||
|
||||
See [fetch#method](https://developer.mozilla.org/en-US/docs/Web/API/fetch#method).
|
||||
|
||||
#### config.headers
|
||||
|
||||
See [fetch#headers](https://developer.mozilla.org/en-US/docs/Web/API/fetch#headers).
|
||||
|
||||
#### config.redirect
|
||||
|
||||
See [fetch#redirect](https://developer.mozilla.org/en-US/docs/Web/API/fetch#redirect).
|
||||
|
||||
#### config.keepAlive
|
||||
|
||||
See [fetch#keepalive](https://developer.mozilla.org/en-US/docs/Web/API/fetch#keepalive).
|
||||
|
||||
#### config.params
|
||||
|
||||
Additional query parameters. They will be appended to the URL.
|
||||
|
||||
#### config.data
|
||||
|
||||
The request body. Currently support below types:
|
||||
|
||||
- string
|
||||
- URLSearchParams
|
||||
- ArrayBuffer / ArrayBufferView
|
||||
- Blob
|
||||
- FormData
|
||||
- Object (will be serialized to JSON)
|
||||
|
||||
#### config.responseType
|
||||
|
||||
Supported response types:
|
||||
|
||||
```ts
|
||||
interface ResponseTypes {
|
||||
json: any
|
||||
text: string
|
||||
stream: ReadableStream<Uint8Array>
|
||||
blob: Blob
|
||||
formdata: FormData
|
||||
arraybuffer: ArrayBuffer
|
||||
}
|
||||
```
|
||||
|
||||
#### config.timeout
|
||||
|
||||
The request timeout in milliseconds.
|
||||
|
||||
#### config.proxyAgent
|
||||
|
||||
> [!NOTE]
|
||||
>
|
||||
> In order to use a proxy agent, you need to install `@cordisjs/plugin-proxy-agent`.
|
||||
|
||||
### Response
|
||||
|
||||
```ts
|
||||
interface Response<T> {
|
||||
status: number
|
||||
statusText: string
|
||||
headers: Headers
|
||||
data: T
|
||||
}
|
||||
```
|
||||
|
||||
#### response.status
|
||||
|
||||
See [Response#status](https://developer.mozilla.org/en-US/docs/Web/API/Response/status).
|
||||
|
||||
#### response.statusText
|
||||
|
||||
See [Response#statusText](https://developer.mozilla.org/en-US/docs/Web/API/Response/statusText).
|
||||
|
||||
#### response.headers
|
||||
|
||||
See [Response#headers](https://developer.mozilla.org/en-US/docs/Web/API/Response/headers).
|
||||
|
||||
#### response.data
|
||||
|
||||
The decoded response body.
|
||||
Vendored
+67
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"name": "@deepseek-ai/cordis-plugin-http",
|
||||
"description": "Fetch-based axios-style HTTP client",
|
||||
"version": "1.5.1",
|
||||
"type": "module",
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"src"
|
||||
],
|
||||
"author": "Shigma <shigma10826@gmail.com>",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
|
||||
"directory": "vendor/http"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/cordiverse/http/issues"
|
||||
},
|
||||
"homepage": "https://github.com/cordiverse/http",
|
||||
"keywords": [
|
||||
"http",
|
||||
"fetch",
|
||||
"axios",
|
||||
"https",
|
||||
"undici",
|
||||
"client",
|
||||
"request",
|
||||
"cordis",
|
||||
"plugin"
|
||||
],
|
||||
"cordis": {
|
||||
"service": {
|
||||
"implements": [
|
||||
"http"
|
||||
]
|
||||
}
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "workspace:~"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/cordis-plugin-logger-console": "workspace:~",
|
||||
"@deepseek-ai/cordis": "workspace:~"
|
||||
},
|
||||
"dependencies": {
|
||||
"@deepseek-ai/cordis-fetch-file": "workspace:~",
|
||||
"@deepseek-ai/cosmokit": "workspace:~",
|
||||
"@deepseek-ai/schemastery": "workspace:~",
|
||||
"undici": "8.11.2"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/types/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json"
|
||||
}
|
||||
}
|
||||
Vendored
+471
@@ -0,0 +1,471 @@
|
||||
import { Context, Inject, Service } from '@deepseek-ai/cordis'
|
||||
import { type Awaitable, Binary, defineProperty, type Dict, isNullable } from '@deepseek-ai/cosmokit'
|
||||
import { createRequire } from 'node:module'
|
||||
import fetchFile from '@deepseek-ai/cordis-fetch-file'
|
||||
import type { Dispatcher, RequestInit, WebSocket, WebSocketInit } from 'undici'
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
|
||||
declare module '@deepseek-ai/cordis' {
|
||||
interface Context {
|
||||
http: Http
|
||||
}
|
||||
|
||||
interface Intercept {
|
||||
http: Http.Intercept
|
||||
}
|
||||
|
||||
interface Events {
|
||||
'http/fetch'(this: Http, url: URL, init: RequestInit, config: Http.Config, next: () => Promise<Response>): Promise<Response>
|
||||
'http/websocket'(this: Http, url: URL, init: WebSocketInit, config: Http.Config, next: () => WebSocket): WebSocket
|
||||
}
|
||||
}
|
||||
|
||||
const kHttpError = Symbol.for('cordis.http.error')
|
||||
const kHttpConfig = Symbol.for('cordis.http.config')
|
||||
|
||||
class HttpError extends Error {
|
||||
[kHttpError] = true
|
||||
|
||||
static is(error: any): error is HttpError {
|
||||
return !!error?.[kHttpError]
|
||||
}
|
||||
|
||||
constructor(message?: string, public code?: Http.Error.Code, public response?: Response) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
|
||||
*/
|
||||
function encodeRequest(data: any): [string | null, any] {
|
||||
if (data instanceof URLSearchParams) return [null, data]
|
||||
if (data instanceof ArrayBuffer) return [null, data]
|
||||
if (ArrayBuffer.isView(data)) return [null, data]
|
||||
if (data instanceof Blob) return [null, data]
|
||||
if (isFormData(data)) return [null, data]
|
||||
if (data instanceof ReadableStream) return [null, data]
|
||||
return ['application/json', JSON.stringify(data)]
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether data is a multipart form body. Node's global FormData and the
|
||||
* `undici` package's are distinct classes, and a request may carry either.
|
||||
* @param data - request data.
|
||||
* @returns true for a FormData of either class.
|
||||
*/
|
||||
function isFormData(data: unknown): boolean {
|
||||
const Native = Http.undici?.FormData as (new () => object) | undefined
|
||||
return data instanceof FormData || (Native !== undefined && data instanceof Native)
|
||||
}
|
||||
|
||||
export namespace Http {
|
||||
export interface ResponseTypes {
|
||||
json: any
|
||||
text: string
|
||||
stream: ReadableStream
|
||||
blob: Blob
|
||||
formdata: FormData
|
||||
arraybuffer: ArrayBuffer
|
||||
headers: Headers
|
||||
}
|
||||
|
||||
export interface Request1 {
|
||||
<K extends keyof ResponseTypes>(url: string | URL, config: Http.RequestConfig & { responseType: K }): Promise<ResponseTypes[K]>
|
||||
<T = any>(url: string | URL, config: Http.RequestConfig & { responseType: Decoder<T> }): Promise<T>
|
||||
<T = any>(url: string | URL, config?: Http.RequestConfig): Promise<T>
|
||||
}
|
||||
|
||||
export interface Request2 {
|
||||
<K extends keyof ResponseTypes>(url: string | URL, data: any, config: Http.RequestConfig & { responseType: K }): Promise<ResponseTypes[K]>
|
||||
<T = any>(url: string | URL, data: any, config: Http.RequestConfig & { responseType: Decoder<T> }): Promise<T>
|
||||
<T = any>(url: string | URL, data?: any, config?: Http.RequestConfig): Promise<T>
|
||||
}
|
||||
|
||||
export interface Intercept {
|
||||
baseUrl?: string
|
||||
headers?: Dict
|
||||
timeout?: number
|
||||
proxyAgent?: string
|
||||
}
|
||||
|
||||
export interface Config extends Intercept {}
|
||||
|
||||
export interface RequestConfig extends Config {
|
||||
method?: string
|
||||
params?: Dict
|
||||
data?: any
|
||||
keepAlive?: boolean
|
||||
redirect?: RequestRedirect
|
||||
signal?: AbortSignal
|
||||
responseType?: keyof ResponseTypes | Decoder
|
||||
validateStatus?: (status: number) => boolean
|
||||
}
|
||||
|
||||
export interface Response<T = any> {
|
||||
url: string
|
||||
data: T
|
||||
status: number
|
||||
statusText: string
|
||||
headers: Headers
|
||||
}
|
||||
|
||||
export interface AfterFetch {
|
||||
url: URL
|
||||
init: RequestInit
|
||||
config: RequestConfig
|
||||
response?: globalThis.Response
|
||||
error?: any
|
||||
}
|
||||
|
||||
export type Decoder<T = any> = (raw: globalThis.Response) => Awaitable<T>
|
||||
|
||||
export type Error = HttpError
|
||||
|
||||
export namespace Error {
|
||||
export type Code = 'TIMEOUT' | 'STATUS_ERROR'
|
||||
}
|
||||
}
|
||||
|
||||
export interface FileOptions {
|
||||
timeout?: number | string
|
||||
}
|
||||
|
||||
export interface Http {
|
||||
(url: string | URL, config?: Http.RequestConfig): Promise<Response>
|
||||
config: Http.Config
|
||||
get: Http.Request1
|
||||
delete: Http.Request1
|
||||
patch: Http.Request2
|
||||
post: Http.Request2
|
||||
put: Http.Request2
|
||||
}
|
||||
|
||||
// we don't use `raw.ok` because it may be a 3xx redirect
|
||||
const validateStatus = (status: number) => status < 400
|
||||
|
||||
export class Http extends Service<Http.Intercept> {
|
||||
static Error = HttpError
|
||||
|
||||
static undici: typeof import('undici')
|
||||
|
||||
static {
|
||||
const require = createRequire(import.meta.url)
|
||||
try {
|
||||
if (process.execArgv.includes('--expose-internals')) {
|
||||
this.undici = require('internal/deps/undici/undici')
|
||||
} else {
|
||||
this.undici = require('undici')
|
||||
}
|
||||
} catch {}
|
||||
|
||||
for (const method of ['get', 'delete'] as const) {
|
||||
defineProperty(Http.prototype, method, async function (this: Http, url: string | URL, config?: Http.Config) {
|
||||
const response = await this(url, { method, validateStatus, ...config })
|
||||
return this._decode(response)
|
||||
})
|
||||
}
|
||||
|
||||
for (const method of ['patch', 'post', 'put'] as const) {
|
||||
defineProperty(Http.prototype, method, async function (this: Http, url: string | URL, data?: any, config?: Http.Config) {
|
||||
const response = await this(url, { method, data, validateStatus, ...config })
|
||||
return this._decode(response)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
static Config: z<Http.Config> = z.object({
|
||||
timeout: z.natural().role('ms').description('等待请求的最长时间。'),
|
||||
keepAlive: z.boolean().description('是否保持连接。'),
|
||||
proxyAgent: z.string().description('代理服务器地址。'),
|
||||
})
|
||||
|
||||
Config: z<Http.Config> = z.object({
|
||||
baseUrl: z.string().description('基础 URL。'),
|
||||
timeout: z.natural().role('ms').description('等待请求的最长时间。'),
|
||||
keepAlive: z.boolean().description('是否保持连接。'),
|
||||
proxyAgent: z.string().description('代理服务器地址。'),
|
||||
})
|
||||
|
||||
public isError = HttpError.is
|
||||
|
||||
private _decoders: Dict = Object.create(null)
|
||||
private _proxies: Dict<(url: URL) => Dispatcher> = Object.create(null)
|
||||
|
||||
constructor(ctx: Context, public config: Http.Config = {}) {
|
||||
super(ctx, 'http')
|
||||
|
||||
this.decoder('json', (raw) => raw.json())
|
||||
this.decoder('text', (raw) => raw.text())
|
||||
this.decoder('blob', (raw) => raw.blob())
|
||||
this.decoder('arraybuffer', (raw) => raw.arrayBuffer())
|
||||
this.decoder('formdata', (raw) => raw.formData())
|
||||
this.decoder('stream', (raw) => raw.body!)
|
||||
this.decoder('headers', (raw) => raw.headers)
|
||||
|
||||
this.proxy(['http', 'https'], (url) => {
|
||||
return new this.undici.ProxyAgent(url.href)
|
||||
})
|
||||
|
||||
// file: URL
|
||||
this.ctx.on('http/fetch', async (url, init, config, next) => {
|
||||
if (url.protocol !== 'file:') return next()
|
||||
if (init.method !== 'GET') {
|
||||
return new Response(null, { status: 405, statusText: 'Method Not Allowed' })
|
||||
}
|
||||
return fetchFile(url, init as globalThis.RequestInit, {
|
||||
download: true,
|
||||
onError: ctx.logger.error,
|
||||
})
|
||||
}, { prepend: true })
|
||||
|
||||
// data: URL
|
||||
// https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Schemes/data
|
||||
this.ctx.on('http/fetch', async (url, init, config, next) => {
|
||||
// data:[<media-type>][;base64],<data>
|
||||
const capture = /^data:([^,]*),(.*)$/.exec(url.href)
|
||||
if (!capture) return next()
|
||||
if (init.method !== 'GET') {
|
||||
return new Response(null, { status: 405, statusText: 'Method Not Allowed' })
|
||||
}
|
||||
let [, type, data] = capture
|
||||
let bodyInit: BodyInit = data
|
||||
if (type.endsWith(';base64')) {
|
||||
type = type.slice(0, -7)
|
||||
bodyInit = Binary.fromBase64(data)
|
||||
} else {
|
||||
bodyInit = decodeURIComponent(data)
|
||||
}
|
||||
return new Response(bodyInit, {
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: { 'content-type': type },
|
||||
})
|
||||
}, { prepend: true })
|
||||
}
|
||||
|
||||
get undici() {
|
||||
if (Http.undici) return Http.undici
|
||||
throw new Error('please install `undici`')
|
||||
}
|
||||
|
||||
static mergeConfig = (target: Http.Config, source?: Http.Config) => ({
|
||||
...target,
|
||||
...source,
|
||||
headers: {
|
||||
...target?.headers,
|
||||
...source?.headers,
|
||||
},
|
||||
})
|
||||
|
||||
decoder<K extends keyof Http.ResponseTypes>(type: K, decoder: Http.Decoder<Http.ResponseTypes[K]>) {
|
||||
return this.ctx.effect(() => {
|
||||
this._decoders[type] = decoder
|
||||
return () => delete this._decoders[type]
|
||||
}, 'ctx.http.decoder()')
|
||||
}
|
||||
|
||||
proxy(name: string[], factory: (url: URL) => Dispatcher) {
|
||||
return this.ctx.effect(() => {
|
||||
for (const key of name) {
|
||||
this._proxies[key] = factory
|
||||
}
|
||||
return () => {
|
||||
for (const key of name) {
|
||||
delete this._proxies[key]
|
||||
}
|
||||
}
|
||||
}, 'ctx.http.proxy()')
|
||||
}
|
||||
|
||||
extend(config: Http.Config = {}) {
|
||||
return this[Service.extend]({
|
||||
config: Http.mergeConfig(this.config, config),
|
||||
})
|
||||
}
|
||||
|
||||
resolveConfig(init?: Http.RequestConfig): Http.RequestConfig {
|
||||
return this[Service.resolveConfig](this.config, init)
|
||||
}
|
||||
|
||||
resolveURL(url: string | URL, config: Http.RequestConfig, isWebSocket = false) {
|
||||
try {
|
||||
url = new URL(url, config.baseUrl)
|
||||
} catch (error) {
|
||||
// prettify the error message
|
||||
throw new TypeError(`Invalid URL: ${url}`)
|
||||
}
|
||||
if (isWebSocket) url.protocol = url.protocol.replace(/^http/, 'ws')
|
||||
for (const [key, value] of Object.entries(config.params ?? {})) {
|
||||
if (isNullable(value)) continue
|
||||
url.searchParams.append(key, value)
|
||||
}
|
||||
return url
|
||||
}
|
||||
|
||||
defaultDecoder(response: Response) {
|
||||
const type = response.headers.get('content-type')
|
||||
if (type?.startsWith('application/json')) {
|
||||
return response.json()
|
||||
} else if (type?.startsWith('text/')) {
|
||||
return response.text()
|
||||
} else {
|
||||
return response.arrayBuffer()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuild a multipart body in the FormData class the `undici` package
|
||||
* recognizes. Node's global FormData belongs to the builtin fetch, which is a
|
||||
* distinct class from the package's: undici coerces a foreign one to a string,
|
||||
* so the request would carry `[object FormData]` instead of the parts.
|
||||
* @param data - request data already recognized as a FormData.
|
||||
* @returns the same body, or an equivalent one built by undici's class.
|
||||
*/
|
||||
private adoptFormData(data: FormData): FormData {
|
||||
const Native = Http.undici?.FormData as (new () => FormData) | undefined
|
||||
if (Native === undefined || data.constructor === Native) return data
|
||||
const form = new Native()
|
||||
data.forEach((value, name) => {
|
||||
if (typeof value === 'string') form.append(name, value)
|
||||
else form.append(name, value, value.name)
|
||||
})
|
||||
return form
|
||||
}
|
||||
|
||||
async [Service.invoke](...args: any[]) {
|
||||
let method: string | undefined
|
||||
if (typeof args[1] === 'string' || args[1] instanceof URL) {
|
||||
method = args.shift()
|
||||
}
|
||||
const config = this.resolveConfig(args[1])
|
||||
const url = this.resolveURL(args[0], config)
|
||||
method ??= config.method ?? 'GET'
|
||||
|
||||
const controller = new AbortController()
|
||||
if (config.signal) {
|
||||
if (config.signal.aborted) {
|
||||
throw config.signal.reason
|
||||
}
|
||||
config.signal.addEventListener('abort', () => {
|
||||
controller.abort(config.signal!.reason)
|
||||
})
|
||||
}
|
||||
|
||||
const dispose = this.ctx.effect(() => {
|
||||
const timer = config.timeout && setTimeout(() => {
|
||||
controller.abort(new HttpError('request timeout', 'TIMEOUT'))
|
||||
}, config.timeout)
|
||||
return () => {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
})
|
||||
controller.signal.addEventListener('abort', () => dispose())
|
||||
|
||||
try {
|
||||
const headers = new Headers(config.headers)
|
||||
const init: RequestInit = {
|
||||
method,
|
||||
headers: headers as any,
|
||||
body: config.data,
|
||||
keepalive: config.keepAlive,
|
||||
redirect: config.redirect,
|
||||
signal: controller.signal,
|
||||
}
|
||||
|
||||
if (config.data && typeof config.data === 'object') {
|
||||
const [type, body] = encodeRequest(isFormData(config.data) ? this.adoptFormData(config.data) : config.data)
|
||||
init.body = body
|
||||
if (type && !headers.has('content-type')) {
|
||||
headers.append('content-type', type)
|
||||
}
|
||||
}
|
||||
|
||||
if (init.body) {
|
||||
(init as any).duplex = 'half'
|
||||
}
|
||||
|
||||
if (config.proxyAgent) {
|
||||
const proxyURL = new URL(config.proxyAgent)
|
||||
const factory = this._proxies[proxyURL.protocol.slice(0, -1)]
|
||||
if (!factory) throw new Error(`Cannot resolve proxy agent ${proxyURL}`)
|
||||
init.dispatcher = factory(proxyURL)
|
||||
}
|
||||
|
||||
const response = await this.ctx.waterfall(this, 'http/fetch', url, init, config, () => {
|
||||
this.ctx.logger('http:request').debug('%C %s', method, url.href)
|
||||
return this.undici.fetch(url, init) as any
|
||||
}).catch((cause) => {
|
||||
this.ctx.logger('http:request').debug('%C %s failed: %o', method, url.href, cause)
|
||||
if (Http.Error.is(cause)) throw cause
|
||||
const error = new Http.Error(`fetch ${url} failed`)
|
||||
error.cause = cause
|
||||
throw error
|
||||
})
|
||||
|
||||
this.ctx.logger('http:response').debug('%C %s %s %s', method, url.href, response.status, response.statusText)
|
||||
response[kHttpConfig] = config
|
||||
return response
|
||||
} finally {
|
||||
dispose()
|
||||
}
|
||||
}
|
||||
|
||||
private async _decode(response: Response) {
|
||||
const config: Http.RequestConfig = response[kHttpConfig]
|
||||
const validateStatus = config.validateStatus ?? (() => true)
|
||||
if (!validateStatus(response.status)) {
|
||||
throw new Http.Error(response.statusText, 'STATUS_ERROR', response)
|
||||
}
|
||||
|
||||
if (!config.responseType) {
|
||||
return this.defaultDecoder(response)
|
||||
}
|
||||
|
||||
let decoder: Http.Decoder
|
||||
if (typeof config.responseType === 'function') {
|
||||
decoder = config.responseType
|
||||
} else {
|
||||
decoder = this._decoders[config.responseType]
|
||||
if (!decoder) {
|
||||
throw new TypeError(`Unknown responseType: ${config.responseType}`)
|
||||
}
|
||||
}
|
||||
return decoder(response)
|
||||
}
|
||||
|
||||
async head(url: string | URL, config?: Http.RequestConfig) {
|
||||
const response = await this(url, { method: 'HEAD', responseType: 'headers', ...config })
|
||||
return this._decode(response)
|
||||
}
|
||||
|
||||
ws(url: string | URL, _config?: Http.Config) {
|
||||
const config = this.resolveConfig(_config)
|
||||
url = this.resolveURL(url, config, true)
|
||||
const headers = Object.fromEntries(new Headers(config.headers))
|
||||
const init: WebSocketInit = {
|
||||
headers,
|
||||
}
|
||||
|
||||
if (config.proxyAgent) {
|
||||
const proxyURL = new URL(config.proxyAgent)
|
||||
const factory = this._proxies[proxyURL.protocol.slice(0, -1)]
|
||||
if (!factory) throw new Error(`Cannot resolve proxy agent ${proxyURL}`)
|
||||
init.dispatcher = factory(proxyURL)
|
||||
}
|
||||
|
||||
const socket = this.ctx.waterfall(this, 'http/websocket', url, init, config, () => {
|
||||
this.ctx.logger('http:ws').debug('connect %s', url.href)
|
||||
return new this.undici.WebSocket(url, init)
|
||||
})
|
||||
const dispose = this.ctx.effect(() => {
|
||||
return () => socket.close(1000, 'context disposed')
|
||||
}, 'new WebSocket()')
|
||||
socket.addEventListener('close', () => {
|
||||
dispose()
|
||||
})
|
||||
return socket
|
||||
}
|
||||
}
|
||||
|
||||
export default Http
|
||||
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types",
|
||||
"noUncheckedIndexedAccess": false,
|
||||
"exactOptionalPropertyTypes": false,
|
||||
"noImplicitOverride": false,
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noImplicitAny": false
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "../cordis"
|
||||
},
|
||||
{
|
||||
"path": "../cosmokit"
|
||||
},
|
||||
{
|
||||
"path": "../fetch-file"
|
||||
},
|
||||
{
|
||||
"path": "../logger-console"
|
||||
},
|
||||
{
|
||||
"path": "../schemastery"
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user