forked from zehfernandes/get-vercel-source-code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
173 lines (161 loc) · 5.72 KB
/
index.js
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
#!/usr/bin/env node
import 'dotenv/config'
import * as fs from 'node:fs'
import got from 'got'
import pc from 'picocolors'
import { oraPromise } from 'ora'
const VERCEL_TOKEN = process.env.VERCEL_TOKEN
const VERCEL_DEPLOYMENT = process.argv[2]
const DEST_DIR = process.argv[3] || VERCEL_DEPLOYMENT
const VERCEL_TEAM = process.env.VERCEL_TEAM
const VERCEL_API = 'https://api.vercel.com'
try {
if (VERCEL_TOKEN === undefined) {
console.error('Missing VERCEL_TOKEN in .env file.',
'\nLook at README for more information'
)
} else if (VERCEL_DEPLOYMENT === undefined) {
console.error('Missing deployment URL or id')
console.log(
'\ne.g: node index.js example-5ik51k4n7.vercel.app',
'\ne.g: node index.js dpl_6CR1uw9hBdpWgrMvPkncsTGRC18A'
)
} else {
await main()
}
} catch (err) {
console.error(err.stack || err)
}
/**
* Asynchronously executes the main function.
*
* @return {Promise<void>} A promise that resolves when the main function completes execution.
*/
async function main () {
console.log(`\n${pc.blue(DEST_DIR)}`)
const deploymentId = VERCEL_DEPLOYMENT.startsWith('dpl_')
? VERCEL_DEPLOYMENT
: await oraPromise(getDeploymentId(VERCEL_DEPLOYMENT), 'Getting deployment id 🏷️')
const srcFiles = await oraPromise(getDeploymentSource(deploymentId), 'Loading source files tree 🗃️')
if (fs.existsSync(DEST_DIR)) fs.rmSync(DEST_DIR, { recursive: true })
fs.mkdirSync(DEST_DIR)
Promise.allSettled(
srcFiles
.map((file) => {
const pathname = file.name.replace('src', DEST_DIR)
if (fs.existsSync(pathname)) return null
if (file.type === 'directory') {
fs.mkdirSync(pathname)
return null
}
if (file.type === 'file') {
return oraPromise(downloadFile(deploymentId, file.uid, pathname), `Downloading ${pc.green(new URL('file://' + pathname).pathname)}`)
}
return null
})
.filter(Boolean)
)
}
/**
* Retrieves the deployment source files for the specified ID.
*
* @param {string} id - The ID of the deployment.
* @return {Promise<Object>} A promise that resolves to the deployment source files.
*/
async function getDeploymentSource (id) {
let path = `/v7/deployments/${id}/files`
if (VERCEL_TEAM) path += `?teamId=${VERCEL_TEAM}`
const files = await getJSONFromAPI(path)
// Get only src directory
const source = files.find((x) => x.name === 'src')
// Flatten tree structure to list of files/dirs for easier downloading
return flattenTree(source)
}
/**
* Retrieves the deployment ID for a given domain.
*
* @param {string} domain - The domain for which to retrieve the deployment ID.
* @return {Promise<string>} The ID of the deployment.
*/
async function getDeploymentId (domain) {
const deployment = await getJSONFromAPI(`/v13/deployments/${domain}`)
return deployment.id
}
/**
* Downloads a file from the API and saves it to the specified destination.
*
* @param {string} deploymentId - The ID of the deployment.
* @param {string} fileId - The ID of the file to download.
* @param {string} destination - The path where the file should be saved.
* @returns {Promise} A promise that resolves when the file has been successfully downloaded and saved.
*/
async function downloadFile (deploymentId, fileId, destination) {
let path = `/v7/deployments/${deploymentId}/files/${fileId}`
if (VERCEL_TEAM) path += `?teamId=${VERCEL_TEAM}`
const response = await getFromAPI(path)
return new Promise((resolve, reject) => {
const encodedValue = JSON.parse(response.body).data
const decodedValue = Buffer.from(encodedValue, 'base64') // Decode base64 to binary buffer
fs.writeFile(destination, decodedValue, function (err) {
if (err) reject(err)
resolve()
})
})
}
/**
* Retrieves data from an API endpoint.
*
* @param {string} path - The path of the API endpoint.
* @param {boolean} [binary=false] - Whether the response should be treated as binary data.
* @returns {Promise} A Promise that resolves to the response from the API.
*/
function getFromAPI (path, binary = false) {
return (binary ? got.stream : got)(VERCEL_API + path, {
headers: {
Authorization: `Bearer ${VERCEL_TOKEN}`
},
responseType: 'buffer',
retry: {
limit: 0
}
})
}
/**
* Retrieves JSON data from the API at the specified path.
*
* @param {string} path - The path to the API endpoint.
* @return {Promise} A Promise that resolves to the JSON data returned by the API.
*/
function getJSONFromAPI (path) {
return getFromAPI(path).json()
}
/**
* Flattens a tree structure by recursively concatenating the name of each node with its children's names.
*
* @param {Object} node - The root node of the tree.
* @param {string} node.name - The name of the node.
* @param {Array} [node.children] - The children of the node (optional).
* @return {Array} - An array containing all the nodes in the flattened tree.
*/
function flattenTree ({ name, children = [] }) {
const childrenNamed = children.map(child => ({
...child,
name: `${name}/${child.name}`
}))
const flattenedChildren = childrenNamed.flatMap(flattenTree)
return [...childrenNamed, ...flattenedChildren]
}
/**
* Retrieves the deployment ID for a given project.
*
* @param {string} projectName - The name of the project.
* @return {string} The ID of the successful deployment.
*/
async function getDeploymentId(projectName) {
const { deployments } = await getJSONFromAPI(`/v12/projects/${projectName}/deployments?limit=1&sort=created`);
const successfulDeployments = deployments.filter((deployment) => deployment.readyState === 'READY');
if (successfulDeployments.length > 0) {
return successfulDeployments[0].uid;
}
throw new Error('No successful deployments found for the project');
}