-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
utils.ts
310 lines (250 loc) · 9.38 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import { join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import fs from 'fs-extra'
import matter from 'gray-matter'
import YAML from 'js-yaml'
import Git from 'simple-git'
import type { PackageIndexes, VueUseFunction } from '@vueuse/metadata'
import { $fetch } from 'ofetch'
import { getCategories } from '../packages/metadata/utils'
import { packages } from '../meta/packages'
export const git = Git()
export const DOCS_URL = 'https://vueuse.org'
const __dirname = fileURLToPath(new URL('.', import.meta.url))
export const DIR_ROOT = resolve(__dirname, '..')
export const DIR_SRC = resolve(__dirname, '../packages')
const DIR_TYPES = resolve(__dirname, '../types/packages')
export async function getTypeDefinition(pkg: string, name: string): Promise<string | undefined> {
const typingFilepath = join(DIR_TYPES, `${pkg}/${name}/index.d.ts`)
if (!fs.existsSync(typingFilepath))
return
let types = await fs.readFile(typingFilepath, 'utf-8')
if (!types)
return
// clean up types
types = types
.replace(/import\(.*?\)\./g, '')
.replace(/import[\s\S]+?from ?["'][\s\S]+?["']/g, '')
.replace(/export {}/g, '')
const prettier = await import('prettier')
return (await prettier
.format(
types,
{
semi: false,
parser: 'typescript',
},
))
.trim()
}
export async function updateImport({ packages, functions }: PackageIndexes) {
for (const { name, dir, manualImport } of Object.values(packages)) {
if (manualImport)
continue
let imports: string[]
if (name === 'components') {
imports = functions
.sort((a, b) => a.name.localeCompare(b.name))
.flatMap((fn) => {
const arr: string[] = []
// don't include integration components
if (fn.package === 'integrations')
return arr
if (fn.component)
arr.push(`export * from '../${fn.package}/${fn.name}/component'`)
if (fn.directive)
arr.push(`export * from '../${fn.package}/${fn.name}/directive'`)
return arr
})
}
else {
imports = functions
.filter(i => i.package === name)
.map(f => f.name)
.sort()
.map(name => `export * from './${name}'`)
}
if (name === 'core') {
imports.push(
'export * from \'./types\'',
'export * from \'@vueuse/shared\'',
'export * from \'./ssr-handlers\'',
)
}
if (name === 'nuxt') {
imports.push(
'export * from \'@vueuse/core\'',
)
}
await fs.writeFile(join(dir, 'index.ts'), `${imports.join('\n')}\n`)
// temporary file for export-size
await fs.remove(join(dir, 'index.mjs'))
}
}
export function uniq<T extends any[]>(a: T) {
return Array.from(new Set(a))
}
export function stringifyFunctions(functions: VueUseFunction[], title = true) {
let list = ''
const categories = getCategories(functions)
for (const category of categories) {
if (category.startsWith('_'))
continue
if (title)
list += `### ${category}\n`
const categoryFunctions = functions
.filter(i => i.category === category)
.sort((a, b) => a.name.localeCompare(b.name))
for (const { name, docs, description, deprecated } of categoryFunctions) {
if (deprecated)
continue
const desc = description ? ` — ${description}` : ''
list += `- [\`${name}\`](${docs})${desc}\n`
}
list += '\n'
}
return list
}
export function replacer(code: string, value: string, key: string, insert: 'head' | 'tail' | 'none' = 'none') {
const START = `<!--${key}_STARTS-->`
const END = `<!--${key}_ENDS-->`
const regex = new RegExp(`${START}[\\s\\S]*?${END}`, 'im')
const target = value ? `${START}\n\n${value.trim()}\n\n${END}` : `${START}${END}`
if (!code.match(regex)) {
if (insert === 'none')
return code
else if (insert === 'head')
return `${target}\n\n${code}`
else
return `${code}\n\n${target}`
}
return code.replace(regex, target)
}
export async function updatePackageREADME({ packages, functions }: PackageIndexes) {
for (const { name, dir } of Object.values(packages)) {
const readmePath = join(dir, 'README.md')
if (!fs.existsSync(readmePath))
continue
const functionMD = stringifyFunctions(functions.filter(i => i.package === name), false)
let readme = await fs.readFile(readmePath, 'utf-8')
readme = replacer(readme, functionMD, 'FUNCTIONS_LIST').trim().replace(/\r\n/g, '\n')
await fs.writeFile(readmePath, `${readme}\n`, 'utf-8')
}
}
export async function updateIndexREADME({ packages, functions }: PackageIndexes) {
let readme = await fs.readFile('README.md', 'utf-8')
const functionsCount = functions.filter(i => !i.internal).length
readme = readme.replace(
/img\.shields\.io\/badge\/-(.+?)%20functions/,
`img.shields.io/badge/-${functionsCount}%20functions`,
).trim().replace(/\r\n/g, '\n')
await fs.writeFile('README.md', `${readme}\n`, 'utf-8')
}
export async function updateFunctionsMD({ packages, functions }: PackageIndexes) {
let mdAddons = await fs.readFile('packages/add-ons.md', 'utf-8')
const addons = Object.values(packages)
.filter(i => i.addon && !i.deprecated)
.map(({ docs, name, display, description }) => {
return `## ${display} - [\`@vueuse/${name}\`](${docs})\n\n${description?.trim()}\n\n${
stringifyFunctions(functions.filter(i => i.package === name), false)}`.trim()
})
.join('\n\n')
mdAddons = replacer(mdAddons, addons, 'ADDONS_LIST').replace(/\r\n/g, '\n')
await fs.writeFile('packages/add-ons.md', mdAddons, 'utf-8')
}
export async function updateFunctionREADME(indexes: PackageIndexes) {
const hasTypes = fs.existsSync(DIR_TYPES)
if (!hasTypes)
console.warn('No types dist found, run `npm run build:types` first.')
for (const fn of indexes.functions) {
const mdPath = `packages/${fn.package}/${fn.name}/index.md`
if (!fs.existsSync(mdPath))
continue
let readme = await fs.readFile(mdPath, 'utf-8')
const { content, data = {} } = matter(readme)
data.category = fn.category || 'Unknown'
readme = `---\n${YAML.dump(data)}---\n\n${content.trim()}`.trim().replace(/\r\n/g, '\n')
await fs.writeFile(mdPath, `${readme}\n`, 'utf-8')
}
}
export async function updateCountBadge(indexes: PackageIndexes) {
const functionsCount = indexes.functions.filter(i => !i.internal).length
const url = `https://img.shields.io/badge/-${functionsCount}%20functions-13708a`
const data = await $fetch(url, { responseType: 'text' })
await fs.writeFile(join(DIR_ROOT, 'packages/public/badge-function-count.svg'), data, 'utf-8')
}
export async function updatePackageJSON(indexes: PackageIndexes) {
const { version } = await fs.readJSON('package.json')
for (const { name, description, author, submodules, iife } of packages) {
const packageDir = join(DIR_SRC, name)
const packageJSONPath = join(packageDir, 'package.json')
const packageJSON = await fs.readJSON(packageJSONPath)
packageJSON.version = version
packageJSON.description = description || packageJSON.description
packageJSON.author = author || 'Anthony Fu <https://github.com/antfu>'
packageJSON.bugs = {
url: 'https://github.com/vueuse/vueuse/issues',
}
packageJSON.homepage = name === 'core'
? 'https://github.com/vueuse/vueuse#readme'
: `https://github.com/vueuse/vueuse/tree/main/packages/${name}#readme`
packageJSON.repository = {
type: 'git',
url: 'git+https://github.com/vueuse/vueuse.git',
directory: `packages/${name}`,
}
packageJSON.main = './index.cjs'
packageJSON.types = packageJSON.type === 'module' ? './index.d.ts' : './index.d.cts'
packageJSON.module = './index.mjs'
if (iife !== false) {
packageJSON.unpkg = './index.iife.min.js'
packageJSON.jsdelivr = './index.iife.min.js'
}
packageJSON.exports = {
'.': {
import: './index.mjs',
require: './index.cjs',
},
'./*': './*',
...packageJSON.exports,
}
if (submodules) {
indexes.functions
.filter(i => i.package === name)
.forEach((i) => {
packageJSON.exports[`./${i.name}`] = {
import: `./${i.name}.mjs`,
require: `./${i.name}.cjs`,
}
if (i.component) {
packageJSON.exports[`./${i.name}/component`] = {
import: `./${i.name}/component.mjs`,
require: `./${i.name}/component.cjs`,
}
}
})
}
await fs.writeJSON(packageJSONPath, packageJSON, { spaces: 2 })
}
}
async function fetchContributors(page = 1) {
const additional = ['egoist']
const collaborators: string[] = []
const data = await $fetch<{ login: string }[]>(`https://api.github.com/repos/vueuse/vueuse/contributors?per_page=100&page=${page}`, {
method: 'get',
headers: {
'content-type': 'application/json',
},
}) || []
collaborators.push(...data.map(i => i.login))
if (data.length === 100)
collaborators.push(...(await fetchContributors(page + 1)))
return Array.from(new Set([
...collaborators.filter(collaborator => !['renovate[bot]', 'dependabot[bot]', 'renovate-bot'].includes(collaborator)),
...additional,
]))
}
export async function updateContributors() {
const collaborators = await fetchContributors()
await fs.writeFile(join(DIR_SRC, './contributors.json'), `${JSON.stringify(collaborators, null, 2)}\n`, 'utf8')
}