-
Notifications
You must be signed in to change notification settings - Fork 963
Expand file tree
/
Copy pathutils.ts
More file actions
176 lines (146 loc) · 4.78 KB
/
Copy pathutils.ts
File metadata and controls
176 lines (146 loc) · 4.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import platform from 'platform'
declare let window: any
type Runtime =
| 'node'
| 'browser'
| 'deno'
| 'bun'
| 'vercel-edge'
| 'cloudflare-worker'
| 'unknown'
function getRuntime(): { runtime: Runtime; version: string } {
// @ts-ignore
if ((globalThis as any).Bun) {
// @ts-ignore
return { runtime: 'bun', version: globalThis.Bun.version }
}
// @ts-ignore
if ((globalThis as any).Deno) {
// @ts-ignore
return { runtime: 'deno', version: globalThis.Deno.version.deno }
}
if ((globalThis as any).process?.release?.name === 'node') {
return { runtime: 'node', version: platform.version || 'unknown' }
}
// @ts-ignore
if (typeof EdgeRuntime === 'string') {
return { runtime: 'vercel-edge', version: 'unknown' }
}
if ((globalThis as any).navigator?.userAgent === 'Cloudflare-Workers') {
return { runtime: 'cloudflare-worker', version: 'unknown' }
}
if (typeof window !== 'undefined') {
return { runtime: 'browser', version: platform.version || 'unknown' }
}
return { runtime: 'unknown', version: 'unknown' }
}
export const { runtime, version: runtimeVersion } = getRuntime()
export async function sha256(data: string): Promise<string> {
// Use WebCrypto API if available
if (typeof crypto !== 'undefined') {
const encoder = new TextEncoder()
const dataBuffer = encoder.encode(data)
const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer)
const hashArray = new Uint8Array(hashBuffer)
return btoa(String.fromCharCode(...hashArray))
}
// Use Node.js crypto if WebCrypto is not available
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { createHash } = require('node:crypto')
const hash = createHash('sha256').update(data, 'utf8').digest()
return hash.toString('base64')
}
export function timeoutToSeconds(timeout: number): number {
return Math.ceil(timeout / 1000)
}
export function parseRetryAfter(retryAfter: string | null | undefined) {
if (!retryAfter) {
return
}
const trimmed = retryAfter.trim()
if (/^\d+$/.test(trimmed)) {
return Number(trimmed)
}
if (/^[+-]?\d/.test(trimmed)) {
return
}
const retryAt = Date.parse(trimmed)
if (!Number.isNaN(retryAt)) {
return Math.max(0, Math.ceil((retryAt - Date.now()) / 1000))
}
}
export function dynamicRequire<T>(module: string): T {
if (runtime === 'browser') {
throw new Error('Browser runtime is not supported for require')
}
return require(module)
}
export async function dynamicImport<T>(module: string): Promise<T> {
if (runtime === 'browser') {
throw new Error('Browser runtime is not supported for dynamic import')
}
// @ts-ignore
return await import(module)
}
// Source: https://github.com/chalk/ansi-regex/blob/main/index.js
function ansiRegex({ onlyFirst = false } = {}) {
// Valid string terminator sequences are BEL, ESC\, and 0x9c
const ST = '(?:\\u0007|\\u001B\\u005C|\\u009C)'
// OSC sequences only: ESC ] ... ST (non-greedy until the first ST)
const osc = `(?:\\u001B\\][\\s\\S]*?${ST})`
// CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :) then final byte
const csi =
'[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]'
const pattern = `${osc}|${csi}`
return new RegExp(pattern, onlyFirst ? undefined : 'g')
}
export function stripAnsi(text: string): string {
return text.replace(ansiRegex(), '')
}
export async function wait(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
/**
* Convert data to a Blob, avoiding unnecessary conversions when possible.
*/
export function toBlob(
data: string | ArrayBuffer | Blob | ReadableStream
): Blob | Promise<Blob> {
// Already a Blob - use directly
if (data instanceof Blob) {
return data
}
// String or ArrayBuffer - create Blob
if (typeof data === 'string' || data instanceof ArrayBuffer) {
return new Blob([data])
}
// ReadableStream - must consume to get Blob
return new Response(data).blob()
}
/**
* Escape a string for safe inclusion in a single-quoted shell argument.
* Equivalent to Python's shlex.quote().
*/
export function shellQuote(s: string): string {
return "'" + s.replace(/'/g, "'\\''") + "'"
}
/**
* Prepare data for upload as a BodyInit, optionally gzip-compressed.
* When gzip is enabled, compresses the data and returns a Blob.
*/
export async function toUploadBody(
data: string | ArrayBuffer | Blob | ReadableStream,
gzip?: boolean
): Promise<BodyInit> {
if (gzip) {
const stream =
data instanceof ReadableStream
? data
: data instanceof Blob
? data.stream()
: new Blob([data]).stream()
const compressed = stream.pipeThrough(new CompressionStream('gzip'))
return new Response(compressed).blob()
}
return toBlob(data)
}