vercel 28.11.0 → 28.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,223 @@
1
+ /**
2
+ * This file is spawned in the background and checks npm for the latest version
3
+ * of the CLI, then writes the version to the cache file.
4
+ *
5
+ * NOTE: Since this file runs asynchronously in the background, it's possible
6
+ * for multiple instances of this file to be running at the same time leading
7
+ * to a race condition where the most recent instance will overwrite the
8
+ * previous cache file resetting the `notified` flag and cause the update
9
+ * notification to appear for multiple consequetive commands. Not the end of
10
+ * the world, but something to be aware of.
11
+ *
12
+ * IMPORTANT! This file must NOT depend on any 3rd party dependencies. This
13
+ * file is NOT bundled by `ncc` and thus any 3rd party dependencies will never
14
+ * be available.
15
+ */
16
+
17
+ const https = require('https');
18
+ const { mkdirSync, writeFileSync } = require('fs');
19
+ const { access, mkdir, readFile, unlink, writeFile } = require('fs/promises');
20
+ const path = require('path');
21
+ const { format, inspect } = require('util');
22
+
23
+ /**
24
+ * An simple output helper which accumulates error and debug log messages in
25
+ * memory for potential persistance to disk while immediately outputting errors
26
+ * and debug messages, when the `--debug` flag is set, to `stderr`.
27
+ */
28
+ class WorkerOutput {
29
+ debugLog = [];
30
+ logFile = null;
31
+
32
+ constructor({ debug = true }) {
33
+ this.debugOutputEnabled = debug;
34
+ }
35
+
36
+ debug(...args) {
37
+ this.print('debug', args);
38
+ }
39
+
40
+ error(...args) {
41
+ this.print('error', args);
42
+ }
43
+
44
+ print(type, args) {
45
+ const str = format(
46
+ ...args.map(s => (typeof s === 'string' ? s : inspect(s)))
47
+ );
48
+ this.debugLog.push(`[${new Date().toISOString()}] [${type}] ${str}`);
49
+ if (type === 'debug' && this.debugOutputEnabled) {
50
+ console.error(`> '[debug] [${new Date().toISOString()}] ${str}`);
51
+ } else if (type === 'error') {
52
+ console.error(`Error: ${str}`);
53
+ }
54
+ }
55
+
56
+ setLogFile(file) {
57
+ // wire up the exit handler the first time the log file is set
58
+ if (this.logFile === null) {
59
+ process.on('exit', () => {
60
+ if (this.debugLog.length) {
61
+ mkdirSync(path.dirname(this.logFile), { recursive: true });
62
+ writeFileSync(this.logFile, this.debugLog.join('\n'));
63
+ }
64
+ });
65
+ }
66
+ this.logFile = file;
67
+ }
68
+ }
69
+
70
+ const output = new WorkerOutput({
71
+ // enable the debug logging if the `--debug` is set or if this worker script
72
+ // was directly executed
73
+ debug: process.argv.includes('--debug') || !process.connected,
74
+ });
75
+
76
+ process.on('unhandledRejection', err => {
77
+ output.error('Exiting worker due to unhandled rejection:', err);
78
+ process.exit(1);
79
+ });
80
+
81
+ // this timer will prevent this worker process from running longer than 10s
82
+ const timer = setTimeout(() => {
83
+ output.error('Worker timed out after 10 seconds');
84
+ process.exit(1);
85
+ }, 10000);
86
+
87
+ // wait for the parent to give us the work payload
88
+ process.once('message', async msg => {
89
+ output.debug('Received message from parent:', msg);
90
+
91
+ output.debug('Disconnecting from parent');
92
+ process.disconnect();
93
+
94
+ const { cacheFile, distTag, name, updateCheckInterval } = msg;
95
+ const cacheFileParsed = path.parse(cacheFile);
96
+ await mkdir(cacheFileParsed.dir, { recursive: true });
97
+
98
+ output.setLogFile(
99
+ path.join(cacheFileParsed.dir, `${cacheFileParsed.name}.log`)
100
+ );
101
+
102
+ const lockFile = path.join(
103
+ cacheFileParsed.dir,
104
+ `${cacheFileParsed.name}.lock`
105
+ );
106
+
107
+ try {
108
+ // check for a lock file and either bail if running or write our pid and continue
109
+ output.debug(`Checking lock file: ${lockFile}`);
110
+ if (await isRunning(lockFile)) {
111
+ output.debug('Worker already running, exiting');
112
+ process.exit(1);
113
+ }
114
+ output.debug(`Initializing lock file with pid ${process.pid}`);
115
+ await writeFile(lockFile, String(process.pid), 'utf-8');
116
+
117
+ // fetch the latest version from npm
118
+ const agent = new https.Agent({
119
+ keepAlive: true,
120
+ maxSockets: 15, // See: `npm config get maxsockets`
121
+ });
122
+ const headers = {
123
+ accept:
124
+ 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*',
125
+ };
126
+ const url = `https://registry.npmjs.org/-/package/${name}/dist-tags`;
127
+ output.debug(`Fetching ${url}`);
128
+
129
+ const tags = await new Promise((resolve, reject) => {
130
+ const req = https.get(
131
+ url,
132
+ {
133
+ agent,
134
+ headers,
135
+ },
136
+ res => {
137
+ let buf = '';
138
+ res.on('data', chunk => {
139
+ buf += chunk;
140
+ });
141
+ res.on('end', () => {
142
+ try {
143
+ resolve(JSON.parse(buf));
144
+ } catch (err) {
145
+ reject(err);
146
+ }
147
+ });
148
+ }
149
+ );
150
+
151
+ req.on('error', reject);
152
+ req.end();
153
+ });
154
+
155
+ const version = tags[distTag];
156
+
157
+ if (version) {
158
+ output.debug(`Found dist tag "${distTag}" with version "${version}"`);
159
+ } else {
160
+ output.error(`Dist tag "${distTag}" not found`);
161
+ output.debug('Available dist tags:', Object.keys(tags));
162
+ }
163
+
164
+ output.debug(`Writing cache file: ${cacheFile}`);
165
+ await writeFile(
166
+ cacheFile,
167
+ JSON.stringify({
168
+ expireAt: Date.now() + updateCheckInterval,
169
+ notified: false,
170
+ version,
171
+ })
172
+ );
173
+ } catch (err) {
174
+ output.error(`Failed to get package info:`, err);
175
+ } finally {
176
+ clearTimeout(timer);
177
+
178
+ if (await fileExists(lockFile)) {
179
+ output.debug(`Releasing lock file: ${lockFile}`);
180
+ await unlink(lockFile);
181
+ }
182
+
183
+ output.debug(`Worker finished successfully!`);
184
+
185
+ // force the worker to exit
186
+ process.exit(0);
187
+ }
188
+ });
189
+
190
+ // signal the parent process we're ready
191
+ if (process.connected) {
192
+ output.debug("Notifying parent we're ready");
193
+ process.send({ type: 'ready' });
194
+ } else {
195
+ console.error('No IPC bridge detected, exiting');
196
+ process.exit(1);
197
+ }
198
+
199
+ async function fileExists(file) {
200
+ return access(file)
201
+ .then(() => true)
202
+ .catch(() => false);
203
+ }
204
+
205
+ async function isRunning(lockFile) {
206
+ try {
207
+ const pid = parseInt(await readFile(lockFile, 'utf-8'));
208
+ output.debug(`Found lock file with pid: ${pid}`);
209
+
210
+ // checks for existence of a process; throws if not found
211
+ process.kill(pid, 0);
212
+
213
+ // process is still running
214
+ return true;
215
+ } catch (err) {
216
+ if (await fileExists(lockFile)) {
217
+ // lock file does not exist or process is not running and pid is stale
218
+ output.debug(`Resetting lock file: ${err.toString()}`);
219
+ await unlink(lockFile);
220
+ }
221
+ return false;
222
+ }
223
+ }