-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwrangler-env.ts
More file actions
189 lines (164 loc) · 4.56 KB
/
Copy pathwrangler-env.ts
File metadata and controls
189 lines (164 loc) · 4.56 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
177
178
179
180
181
182
183
184
185
186
187
188
189
import { existsSync } from 'node:fs'
import path from 'node:path'
import { setTimeout as delay } from 'node:timers/promises'
import net from 'node:net'
import getPort from 'get-port'
import { getRemoteAiLocalDevStartupError } from '#shared/ai-env-validation.ts'
const envName = process.env.CLOUDFLARE_ENV ?? 'production'
const portWaitTimeoutMs = 5000
const args = process.argv.slice(2)
const hasEnvFlag = args.includes('--env') || args.includes('-e')
const isDevCommand = args[0] === 'dev'
const isLocalDevCommand = isDevCommand && args.includes('--local')
const hasPortFlag = args.includes('--port')
const hasInspectorPortFlag = args.some(
(arg) => arg === '--inspector-port' || arg.startsWith('--inspector-port='),
)
if (isLocalDevCommand) {
const startupError = getRemoteAiLocalDevStartupError(process.env)
if (startupError) {
throw new Error(startupError)
}
}
const commandArgs = [...args]
if (!hasEnvFlag) {
commandArgs.push('--env', envName)
}
if (isDevCommand) {
commandArgs.push('--var', 'WRANGLER_IS_LOCAL_DEV:true')
}
let resolvedPort = process.env.PORT
if (isDevCommand && hasPortFlag) {
resolvedPort = getPortArg(args) ?? resolvedPort
}
if (isDevCommand && !hasPortFlag) {
if (process.env.PORT) {
resolvedPort = process.env.PORT
} else {
const desiredPort = 3742
const portRange = Array.from(
{ length: 10 },
(_, index) => desiredPort + index,
)
resolvedPort = String(
await getPort({
port: portRange,
}),
)
}
commandArgs.push('--port', resolvedPort)
}
if (isDevCommand && !hasInspectorPortFlag) {
const parsedPort = resolvedPort ? Number.parseInt(resolvedPort, 10) : NaN
const inspectorPortRange = Number.isFinite(parsedPort)
? (() => {
const preferredBase =
parsedPort + 10_000 <= 65_535
? parsedPort + 10_000
: parsedPort - 10_000
const safeBase = Math.max(1, preferredBase)
return Array.from(
{ length: 10 },
(_, index) => safeBase + index,
).filter((port) => port > 0 && port <= 65_535)
})()
: undefined
const resolvedInspectorPort = String(
await getPort({
host: '127.0.0.1',
...(inspectorPortRange ? { port: inspectorPortRange } : {}),
}),
)
commandArgs.push('--inspector-port', resolvedInspectorPort)
}
const processEnv = {
...process.env,
CLOUDFLARE_ENV: envName,
...(resolvedPort ? { PORT: resolvedPort } : {}),
}
const localWranglerPath = path.join(
process.cwd(),
'node_modules',
'.bin',
process.platform === 'win32' ? 'wrangler.cmd' : 'wrangler',
)
const wranglerCommand =
(existsSync(localWranglerPath) && localWranglerPath) ||
Bun.which('wrangler') ||
'wrangler'
const proc = Bun.spawn([wranglerCommand, ...commandArgs], {
stdio: ['inherit', 'inherit', 'inherit'],
env: processEnv,
})
let isShuttingDown = false
function handleSignal(signal: NodeJS.Signals) {
if (isShuttingDown) return
isShuttingDown = true
proc.kill(signal)
setTimeout(() => {
if (!proc.killed) proc.kill('SIGKILL')
process.exit(1)
}, 5_000).unref()
}
process.on('SIGINT', () => handleSignal('SIGINT'))
process.on('SIGTERM', () => handleSignal('SIGTERM'))
process.on('exit', () => {
if (!proc.killed) proc.kill('SIGKILL')
})
const exitCode = await proc.exited
if (isDevCommand && resolvedPort) {
const didFreePort = await waitForPortFree(
Number.parseInt(resolvedPort, 10),
portWaitTimeoutMs,
)
if (!didFreePort) {
console.warn(
`Timed out waiting for port ${resolvedPort} to free up before exit.`,
)
}
}
process.exit(exitCode)
function getPortArg(argumentList: ReadonlyArray<string>) {
const inlinePortArg = argumentList.find((arg) => arg.startsWith('--port='))
if (inlinePortArg) {
const [, value] = inlinePortArg.split('=')
return value || undefined
}
const portIndex = argumentList.findIndex((arg) => arg === '--port')
if (portIndex >= 0) {
const value = argumentList[portIndex + 1]
return value || undefined
}
return undefined
}
async function waitForPortFree(port: number, timeoutMs: number) {
const start = Date.now()
while (await isPortInUse(port)) {
if (Date.now() - start >= timeoutMs) {
return false
}
await delay(100)
}
return true
}
function isPortInUse(port: number) {
return new Promise<boolean>((resolve) => {
const socket = new net.Socket()
const finish = (inUse: boolean) => {
socket.removeAllListeners()
socket.destroy()
resolve(inUse)
}
socket.setTimeout(250)
socket.once('connect', () => finish(true))
socket.once('timeout', () => finish(true))
socket.once('error', (error) => {
if ('code' in error && error.code === 'ECONNREFUSED') {
finish(false)
return
}
finish(true)
})
socket.connect(port, '127.0.0.1')
})
}