-
-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy pathutils.ts
261 lines (224 loc) · 6.18 KB
/
utils.ts
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import fs from 'node:fs'
import path from 'node:path'
import { fdir } from 'fdir'
import picomatch from 'picomatch'
import resolveFrom from 'resolve-from'
import strip from 'strip-json-comments'
import type { Entry, Format } from './options'
export type MaybePromise<T> = T | Promise<T>
export type External =
| string
| RegExp
| ((id: string, parentId?: string) => boolean)
export function isExternal(
externals: External | External[],
id: string,
parentId?: string,
) {
id = slash(id)
if (!Array.isArray(externals)) {
externals = [externals]
}
for (const external of externals) {
if (
typeof external === 'string' &&
(id === external || id.includes(`/node_modules/${external}/`))
) {
return true
}
if (external instanceof RegExp && external.test(id)) {
return true
}
if (typeof external === 'function' && external(id, parentId)) {
return true
}
}
return false
}
export function getPostcss(): null | Awaited<typeof import('postcss')> {
return localRequire('postcss')
}
export function getApiExtractor(): null | Awaited<
typeof import('@microsoft/api-extractor')
> {
return localRequire('@microsoft/api-extractor')
}
export function localRequire(moduleName: string) {
const p = resolveFrom.silent(process.cwd(), moduleName)
return p && require(p)
}
export function pathExists(p: string) {
return new Promise((resolve) => {
fs.access(p, (err) => {
resolve(!err)
})
})
}
export async function removeFiles(patterns: string[], dir: string) {
const matchPatterns: string[] = []
const ignorePatterns: string[] = []
for (const pattern of patterns) {
if (pattern.startsWith('!') && pattern[1] !== '(') {
ignorePatterns.push(pattern.slice(1))
} else {
matchPatterns.push(pattern)
}
}
const matcher = picomatch(matchPatterns, {
dot: true,
ignore: ignorePatterns,
})
const files = await new fdir()
.withFullPaths()
.filter((file) => matcher(file))
.crawl(dir)
.withPromise()
files.forEach((file) => fs.existsSync(file) && fs.unlinkSync(file))
}
export function debouncePromise<T extends unknown[]>(
fn: (...args: T) => Promise<void>,
delay: number,
onError: (err: unknown) => void,
) {
let timeout: ReturnType<typeof setTimeout> | undefined
let promiseInFly: Promise<void> | undefined
let callbackPending: (() => void) | undefined
return function debounced(...args: Parameters<typeof fn>) {
if (promiseInFly) {
callbackPending = () => {
debounced(...args)
callbackPending = undefined
}
} else {
if (timeout != null) clearTimeout(timeout)
timeout = setTimeout(() => {
timeout = undefined
promiseInFly = fn(...args)
.catch(onError)
.finally(() => {
promiseInFly = undefined
if (callbackPending) callbackPending()
})
}, delay)
}
}
}
// Taken from https://github.com/sindresorhus/slash/blob/main/index.js (MIT)
export function slash(path: string) {
const isExtendedLengthPath = path.startsWith('\\\\?\\')
if (isExtendedLengthPath) {
return path
}
return path.replace(/\\/g, '/')
}
type Truthy<T> = T extends false | '' | 0 | null | undefined ? never : T // from lodash
export function truthy<T>(value: T): value is Truthy<T> {
return Boolean(value)
}
export function jsoncParse(data: string) {
try {
return new Function(`return ${strip(data).trim()}`)()
} catch {
// Silently ignore any error
// That's what tsc/jsonc-parser did after all
return {}
}
}
export function defaultOutExtension({
format,
pkgType,
}: {
format: Format
pkgType?: string
}): { js: string; dts: string } {
let jsExtension = '.js'
let dtsExtension = '.d.ts'
const isModule = pkgType === 'module'
if (isModule && format === 'cjs') {
jsExtension = '.cjs'
dtsExtension = '.d.cts'
}
if (!isModule && format === 'esm') {
jsExtension = '.mjs'
dtsExtension = '.d.mts'
}
if (format === 'iife') {
jsExtension = '.global.js'
}
return {
js: jsExtension,
dts: dtsExtension,
}
}
export function ensureTempDeclarationDir(): string {
const cwd = process.cwd()
const dirPath = path.join(cwd, '.tsup', 'declaration')
if (fs.existsSync(dirPath)) {
return dirPath
}
fs.mkdirSync(dirPath, { recursive: true })
const gitIgnorePath = path.join(cwd, '.tsup', '.gitignore')
writeFileSync(gitIgnorePath, '**/*\n')
return dirPath
}
// Make sure the entry is an object
// We use the base path (without extension) as the entry name
// To make declaration files work with multiple entrypoints
// See #316
export const toObjectEntry = (entry: string | Entry) => {
if (typeof entry === 'string') {
entry = [entry]
}
if (!Array.isArray(entry)) {
return entry
}
entry = entry.map((e) => e.replace(/\\/g, '/'))
const ancestor = findLowestCommonAncestor(entry)
return entry.reduce(
(result, item) => {
const key = item
.replace(ancestor, '')
.replace(/^\//, '')
.replace(/\.[a-z]+$/, '')
return {
...result,
[key]: item,
}
},
{} as Record<string, string>,
)
}
const findLowestCommonAncestor = (filepaths: string[]) => {
if (filepaths.length <= 1) return ''
const [first, ...rest] = filepaths
let ancestor = first.split('/')
for (const filepath of rest) {
const directories = filepath.split('/', ancestor.length)
let index = 0
for (const directory of directories) {
if (directory === ancestor[index]) {
index += 1
} else {
ancestor = ancestor.slice(0, index)
break
}
}
ancestor = ancestor.slice(0, index)
}
return ancestor.length <= 1 && ancestor[0] === ''
? `/${ancestor[0]}`
: ancestor.join('/')
}
export function toAbsolutePath(p: string, cwd?: string): string {
if (path.isAbsolute(p)) {
return p
}
return slash(path.normalize(path.join(cwd || process.cwd(), p)))
}
export function trimDtsExtension(fileName: string) {
return fileName.replace(/\.d\.(ts|mts|cts)x?$/, '')
}
export function writeFileSync(filePath: string, content: string) {
fs.mkdirSync(path.dirname(filePath), { recursive: true })
fs.writeFileSync(filePath, content)
}