@enlt-bakusoku/nuxt4 0.0.0-stage → 2.1.0
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.
- package/README.md +38 -2
- package/dist/module.d.mts +25 -0
- package/dist/module.json +9 -0
- package/dist/module.mjs +208 -0
- package/dist/runtime/shared/schemas/user.d.ts +40 -0
- package/dist/runtime/shared/schemas/user.js +21 -0
- package/dist/runtime/tasks-catalog.d.ts +6 -0
- package/dist/runtime/tasks-catalog.js +7 -0
- package/dist/types.d.mts +9 -0
- package/package.json +120 -3
- package/scripts/bakusoku-dev.mjs +387 -0
- package/scripts/dev-log-relay.mjs +96 -0
- package/scripts/predeploy.mjs +24 -0
- package/scripts/prepare-firebase-artifact.mjs +43 -0
- package/scripts/setup-worktree.sh +59 -0
- package/scripts/verify-firebase-artifacts.mjs +70 -0
- package/src/layer/app/components/admin/AdminExecutionHistory.vue +137 -0
- package/src/layer/app/components/admin/TaskRunDialog.vue +162 -0
- package/src/layer/app/components/admin/UserManagementPage.vue +342 -0
- package/src/layer/app/components/debug/DebugApplicationLogs.vue +87 -0
- package/src/layer/app/components/debug/DebugErrorLogs.vue +47 -0
- package/src/layer/app/components/debug/DebugFirestoreOperations.vue +48 -0
- package/src/layer/app/components/debug/DebugHttpRequests.vue +86 -0
- package/src/layer/app/components/debug/DebugNavigation.vue +60 -0
- package/src/layer/app/components/debug/DebugNowControl.vue +243 -0
- package/src/layer/app/components/debug/DebugPublicConfig.vue +24 -0
- package/src/layer/app/components/debug/DebugTestAdmin.vue +67 -0
- package/src/layer/app/components/demo/DemoDebug.vue +266 -0
- package/src/layer/app/components/demo/DemoHome.vue +347 -0
- package/src/layer/app/components/demo/DemoLogin.vue +391 -0
- package/src/layer/app/components/demo/DemoPassword.vue +224 -0
- package/src/layer/app/components/demo/DemoRegister.vue +148 -0
- package/src/layer/app/components/home/HomePage.vue +77 -0
- package/src/layer/app/layouts/dashboard.vue +126 -0
- package/src/layer/app/layouts/default.vue +3 -0
- package/src/layer/app/middleware/admin.ts +15 -0
- package/src/layer/app/middleware/authenticated.ts +19 -0
- package/src/layer/app/pages/admin/migrations.vue +463 -0
- package/src/layer/app/pages/admin/tasks/[id].vue +276 -0
- package/src/layer/app/pages/admin/tasks/index.vue +220 -0
- package/src/layer/app/pages/admin/users.vue +17 -0
- package/src/layer/app/pages/bakusoku-devtools.vue +294 -0
- package/src/layer/app/plugins/auth-init.ts +36 -0
- package/src/layer/app/plugins/debug-devtools.client.ts +20 -0
- package/src/layer/app/plugins/debug-errors.client.ts +78 -0
- package/src/layer/app/plugins/debug-http.client.ts +154 -0
- package/src/layer/app/plugins/debug-nav.client.ts +28 -0
- package/src/layer/app/plugins/vuefire-inspect.ts +18 -0
- package/src/layer/app/stores/auth.ts +462 -0
- package/src/layer/app/stores/datetime.ts +41 -0
- package/src/layer/app/stores/debug.ts +235 -0
- package/src/layer/app/stores/user.ts +170 -0
- package/src/layer/app/utils/admin-execution.ts +48 -0
- package/src/layer/app/utils/dashboard-heading.ts +36 -0
- package/src/layer/app/utils/debug-bridge.ts +270 -0
- package/src/layer/app/utils/debug-firestore.ts +38 -0
- package/src/layer/app/utils/debug-format.ts +19 -0
- package/src/layer/app/utils/execution-refresh.ts +66 -0
- package/src/layer/app/utils/framework-version.ts +4 -0
- package/src/layer/app/utils/inspect-nuxt-vuefire.ts +288 -0
- package/src/layer/app/utils/is-debug-enabled.ts +13 -0
- package/src/layer/app/utils/logger.ts +235 -0
- package/src/layer/app/utils/map-auth-error.ts +11 -0
- package/src/layer/app/utils/mask-secrets.ts +100 -0
- package/src/layer/app/utils/resolve-auth-user.ts +53 -0
- package/src/layer/app/utils/resolve-firestore.ts +20 -0
- package/src/layer/app/utils/task-run.ts +15 -0
- package/src/layer/build-credentials.mjs +33 -0
- package/src/layer/nuxt.config.ts +86 -0
- package/src/layer/package.json +5 -0
- package/src/layer/server/api/debug/test-admin.post.ts +38 -0
- package/src/layer/server/api/tasks/executions/cancel.post.ts +21 -0
- package/src/layer/server/api/tasks/executions/index.get.ts +22 -0
- package/src/layer/server/api/tasks/executions/index.post.ts +25 -0
- package/src/layer/server/api/tasks/index.get.ts +70 -0
- package/src/layer/server/api/tasks/migrations/index.post.ts +27 -0
- package/src/layer/server/api/tasks/migrations/recovery.post.ts +20 -0
- package/src/layer/server/api/users/[id].delete.ts +57 -0
- package/src/layer/server/api/users/[id].put.ts +110 -0
- package/src/layer/server/api/users/index.post.ts +232 -0
- package/src/layer/server/utils/admin-access.ts +32 -0
- package/src/layer/server/utils/debug-test-admin.ts +17 -0
- package/src/layer/server/utils/firebase-admin.ts +22 -0
- package/src/layer/server/utils/logger.ts +172 -0
- package/src/layer/server/utils/tasks-gateway.ts +57 -0
- package/src/layer/server/utils/user-mutations.ts +103 -0
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { spawn } from 'node:child_process'
|
|
4
|
+
import { createHash } from 'node:crypto'
|
|
5
|
+
import { existsSync, lstatSync, mkdirSync, realpathSync, readFileSync, statSync, unlinkSync } from 'node:fs'
|
|
6
|
+
import { createConnection, createServer } from 'node:net'
|
|
7
|
+
import { dirname, join } from 'node:path'
|
|
8
|
+
import { createInterface } from 'node:readline'
|
|
9
|
+
import { setTimeout as delay } from 'node:timers/promises'
|
|
10
|
+
import { parseEnv, stripVTControlCharacters } from 'node:util'
|
|
11
|
+
import { openDevLogRelay } from './dev-log-relay.mjs'
|
|
12
|
+
|
|
13
|
+
const usage = 'Usage: bakusoku-dev <all|backend|emulators:start|emulators:stop|functions:shell>'
|
|
14
|
+
|
|
15
|
+
/** 現在のディレクトリから Firebase と npm の設定を持つプロジェクトルートを探す。 */
|
|
16
|
+
function findProject() {
|
|
17
|
+
let root = process.cwd()
|
|
18
|
+
while (!['firebase.json', 'package.json'].every(file => existsSync(join(root, file)))) {
|
|
19
|
+
const parent = dirname(root)
|
|
20
|
+
if (parent === root) {
|
|
21
|
+
throw new Error('プロジェクトルートが見つかりません(firebase.json と package.json が必要です)')
|
|
22
|
+
}
|
|
23
|
+
root = parent
|
|
24
|
+
}
|
|
25
|
+
return realpathSync(root)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** プロジェクトの環境変数を読み込み、Firebase プロジェクト ID を検証する。 */
|
|
29
|
+
function projectEnv(root) {
|
|
30
|
+
const dotenv = join(root, '.env')
|
|
31
|
+
const env = { ...(existsSync(dotenv) ? parseEnv(readFileSync(dotenv, 'utf8')) : {}), ...process.env }
|
|
32
|
+
if (!env.NUXT_PUBLIC_FIREBASE_PROJECT_ID) {
|
|
33
|
+
throw new Error('NUXT_PUBLIC_FIREBASE_PROJECT_ID が必要です(.env を確認してください)')
|
|
34
|
+
}
|
|
35
|
+
return env
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** リレーが未使用の場合は、子プロセスの出力を直接端末へ流す。 */
|
|
39
|
+
function writeJobLog(label, line, stderr) {
|
|
40
|
+
const output = stderr ? process.stderr : process.stdout
|
|
41
|
+
output.write(`[${label}] ${line}\n`)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 子プロセスを起動し、終了結果と割り込み手段を返す。 */
|
|
45
|
+
function start(command, args, { root, env, label, stopping, report = writeJobLog }) {
|
|
46
|
+
// Background jobs get their own process group. Interactive commands share the terminal.
|
|
47
|
+
const childEnv = label
|
|
48
|
+
? {
|
|
49
|
+
...env,
|
|
50
|
+
FORCE_COLOR: env.FORCE_COLOR ?? '1',
|
|
51
|
+
}
|
|
52
|
+
: env
|
|
53
|
+
const child = spawn(command, args, {
|
|
54
|
+
cwd: root,
|
|
55
|
+
env: childEnv,
|
|
56
|
+
detached: Boolean(label),
|
|
57
|
+
stdio: label ? ['ignore', 'pipe', 'pipe'] : 'inherit',
|
|
58
|
+
})
|
|
59
|
+
if (label) {
|
|
60
|
+
for (const [input, stderr] of [[child.stdout, false], [child.stderr, true]]) {
|
|
61
|
+
createInterface({ input }).on('line', line => {
|
|
62
|
+
// pnpm can print a lifecycle failure when its watcher receives our shutdown signal.
|
|
63
|
+
if (stopping?.aborted && /^\s*ELIFECYCLE\b/.test(stripVTControlCharacters(line))) return
|
|
64
|
+
report(label, line, stderr)
|
|
65
|
+
})
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
let exited = false
|
|
69
|
+
const done = new Promise(resolve => {
|
|
70
|
+
child.once('error', error => resolve({ error }))
|
|
71
|
+
child.once('exit', () => { exited = true })
|
|
72
|
+
child.once('close', (code, signal) => resolve({ code, signal }))
|
|
73
|
+
})
|
|
74
|
+
return {
|
|
75
|
+
done,
|
|
76
|
+
/** バックグラウンド実行ではプロセスグループ全体に SIGINT を送る。 */
|
|
77
|
+
interrupt() {
|
|
78
|
+
if (!child.pid || (!label && exited)) return
|
|
79
|
+
try {
|
|
80
|
+
process.kill(label ? -child.pid : child.pid, 'SIGINT')
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (error.code !== 'ESRCH') throw error
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 子プロセスの終了結果を検証し、起動や実行の失敗を例外として伝える。 */
|
|
89
|
+
function requireSuccess(result, label) {
|
|
90
|
+
if (result.error) throw result.error
|
|
91
|
+
if (result.code !== 0) {
|
|
92
|
+
throw new Error(`${label} が終了しました (${result.signal ?? result.code})`)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Functions パッケージに監視ビルド用のスクリプトがあるか確認する。 */
|
|
97
|
+
function hasFunctionsWatch(root) {
|
|
98
|
+
const path = join(root, 'functions', 'package.json')
|
|
99
|
+
return existsSync(path) && Boolean(JSON.parse(readFileSync(path, 'utf8')).scripts?.['build:watch'])
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** 待ち受け設定を接続確認に使えるホスト名とポートに変換する。 */
|
|
103
|
+
function emulatorAddress(config, port) {
|
|
104
|
+
const host = config?.host
|
|
105
|
+
return {
|
|
106
|
+
host: !host || host === '0.0.0.0' || host === '::' ? '127.0.0.1' : host,
|
|
107
|
+
port: config?.port ?? port,
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** IPv6 の括弧を含め、接続先をホストとポートの文字列に整える。 */
|
|
112
|
+
function addressText({ host, port }) {
|
|
113
|
+
return `${host.includes(':') ? `[${host}]` : host}:${port}`
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** 指定された接続先への TCP 接続が成立するか確認する。 */
|
|
117
|
+
function tcpReady(address, signal) {
|
|
118
|
+
return new Promise(resolve => {
|
|
119
|
+
const socket = createConnection({ ...address, signal })
|
|
120
|
+
let connected = false
|
|
121
|
+
socket.once('connect', () => {
|
|
122
|
+
connected = true
|
|
123
|
+
socket.destroy()
|
|
124
|
+
})
|
|
125
|
+
socket.once('error', () => {})
|
|
126
|
+
socket.setTimeout(1000, () => socket.destroy())
|
|
127
|
+
socket.once('close', () => resolve(connected))
|
|
128
|
+
})
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** UI と設定済みのエミュレーターが接続可能になるまで待つ。 */
|
|
132
|
+
async function waitReady(emulators, stopping) {
|
|
133
|
+
const timeout = AbortSignal.timeout(60_000)
|
|
134
|
+
const signal = AbortSignal.any([stopping, timeout])
|
|
135
|
+
const checks = []
|
|
136
|
+
if (emulators.ui?.enabled !== false) {
|
|
137
|
+
const url = `http://${addressText(emulatorAddress(emulators.ui, 4000))}/`
|
|
138
|
+
checks.push([url, async () => {
|
|
139
|
+
try {
|
|
140
|
+
const response = await fetch(url, { signal: AbortSignal.any([signal, AbortSignal.timeout(2000)]) })
|
|
141
|
+
await response.body?.cancel()
|
|
142
|
+
return true
|
|
143
|
+
} catch {
|
|
144
|
+
return false
|
|
145
|
+
}
|
|
146
|
+
}])
|
|
147
|
+
}
|
|
148
|
+
for (const [name, defaultPort] of [['auth', 9099], ['firestore', 8080]]) {
|
|
149
|
+
if (emulators[name]) {
|
|
150
|
+
const address = emulatorAddress(emulators[name], defaultPort)
|
|
151
|
+
checks.push([addressText(address), () => tcpReady(address, signal)])
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
await Promise.all(checks.map(async ([address, ready]) => {
|
|
155
|
+
try {
|
|
156
|
+
signal.throwIfAborted()
|
|
157
|
+
while (!await ready()) {
|
|
158
|
+
await delay(500, undefined, { signal })
|
|
159
|
+
}
|
|
160
|
+
} catch (error) {
|
|
161
|
+
if (timeout.aborted && !stopping.aborted) {
|
|
162
|
+
throw new Error(`Emulator の起動待ちがタイムアウトしました: ${address}`, { cause: error })
|
|
163
|
+
}
|
|
164
|
+
throw error
|
|
165
|
+
}
|
|
166
|
+
}))
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** プロジェクトごとの制御ソケットのパスを求め、親ディレクトリのアクセス権を検証する。 */
|
|
170
|
+
function controlPath(root) {
|
|
171
|
+
const uid = process.getuid()
|
|
172
|
+
const dir = `/tmp/bakusoku-dev-${uid}`
|
|
173
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
174
|
+
const info = lstatSync(dir)
|
|
175
|
+
if (!info.isDirectory() || info.uid !== uid || (info.mode & 0o077) !== 0) {
|
|
176
|
+
throw new Error(`Emulator の制御ディレクトリを使用できません: ${dir}`)
|
|
177
|
+
}
|
|
178
|
+
const projectKey = createHash('sha256').update(root).digest('hex').slice(0, 32)
|
|
179
|
+
return join(dir, `${projectKey}.sock`)
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** 制御ソケットに接続し、必要に応じて停止を要求する。 */
|
|
183
|
+
function requestControl(path, stop) {
|
|
184
|
+
return new Promise((resolve, reject) => {
|
|
185
|
+
const client = createConnection(path)
|
|
186
|
+
client.once('connect', () => client.end(stop ? '1' : undefined))
|
|
187
|
+
client.once('error', reject)
|
|
188
|
+
client.once('end', resolve)
|
|
189
|
+
})
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** 起動確認や停止要求を受け付ける制御ソケットを開く。 */
|
|
193
|
+
async function openControl(path, stop) {
|
|
194
|
+
const clients = new Set()
|
|
195
|
+
const server = createServer({ allowHalfOpen: true }, client => {
|
|
196
|
+
clients.add(client)
|
|
197
|
+
client.once('close', () => clients.delete(client))
|
|
198
|
+
client.on('error', () => client.destroy())
|
|
199
|
+
client.on('data', data => {
|
|
200
|
+
if (data.includes(49)) stop()
|
|
201
|
+
})
|
|
202
|
+
client.once('end', () => {
|
|
203
|
+
// A connection without a stop request is only checking for a live server.
|
|
204
|
+
if (client.bytesRead === 0) client.end()
|
|
205
|
+
})
|
|
206
|
+
})
|
|
207
|
+
/** 制御ソケットでの待ち受け開始を Promise で扱う。 */
|
|
208
|
+
const listen = () => new Promise((resolve, reject) => {
|
|
209
|
+
server.once('error', reject)
|
|
210
|
+
server.listen(path, () => {
|
|
211
|
+
server.off('error', reject)
|
|
212
|
+
resolve()
|
|
213
|
+
})
|
|
214
|
+
})
|
|
215
|
+
try {
|
|
216
|
+
await listen()
|
|
217
|
+
} catch (error) {
|
|
218
|
+
// 既存のプロセスから応答がある場合は、その制御ソケットを維持する。
|
|
219
|
+
if (error.code !== 'EADDRINUSE') throw error
|
|
220
|
+
const socket = statSync(path, { throwIfNoEntry: false })
|
|
221
|
+
try {
|
|
222
|
+
await requestControl(path, false)
|
|
223
|
+
} catch (probeError) {
|
|
224
|
+
if (!['ENOENT', 'ECONNREFUSED'].includes(probeError.code)) throw probeError
|
|
225
|
+
const current = statSync(path, { throwIfNoEntry: false })
|
|
226
|
+
// 確認中に別のプロセスがソケットを作り直した場合に備え、確認したものと同じときだけ削除する。
|
|
227
|
+
if (current?.isSocket() && current.ino === socket?.ino) unlinkSync(path)
|
|
228
|
+
await listen()
|
|
229
|
+
return () => closeControl(server, clients)
|
|
230
|
+
}
|
|
231
|
+
throw new Error('このプロジェクトの Emulator はすでに起動しています', { cause: error })
|
|
232
|
+
}
|
|
233
|
+
return () => closeControl(server, clients)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** 制御ソケットの待ち受けを止め、接続しているクライアントを閉じる。 */
|
|
237
|
+
function closeControl(server, clients) {
|
|
238
|
+
server.close()
|
|
239
|
+
for (const client of clients) client.end()
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** コマンドに応じてエミュレーターと開発用プロセスを起動し、終了を管理する。 */
|
|
243
|
+
async function runEmulators(command, root, env) {
|
|
244
|
+
const stack = command !== 'emulators:start'
|
|
245
|
+
const watch = stack && hasFunctionsWatch(root)
|
|
246
|
+
const emulators = stack ? JSON.parse(readFileSync(join(root, 'firebase.json'), 'utf8')).emulators ?? {} : {}
|
|
247
|
+
const abort = new AbortController()
|
|
248
|
+
const jobs = []
|
|
249
|
+
let relay
|
|
250
|
+
/** 停止を通知し、起動済みのプロセスに割り込みを送る。 */
|
|
251
|
+
const stop = () => {
|
|
252
|
+
if (abort.signal.aborted) return
|
|
253
|
+
abort.abort()
|
|
254
|
+
const report = relay?.report ?? writeJobLog
|
|
255
|
+
report('emulators', '終了しています。データのエクスポート完了をお待ちください。', true)
|
|
256
|
+
for (const job of jobs) job.interrupt()
|
|
257
|
+
}
|
|
258
|
+
const closeControl = await openControl(controlPath(root), stop)
|
|
259
|
+
process.on('SIGINT', stop)
|
|
260
|
+
process.on('SIGTERM', stop)
|
|
261
|
+
const rawMode = process.stdin.isRaw
|
|
262
|
+
/** 開発用プロセスを起動して終了管理の対象に加える。 */
|
|
263
|
+
const launch = (bin, args, options) => {
|
|
264
|
+
const job = start(bin, args, { root, env, report: relay?.report, ...options })
|
|
265
|
+
jobs.push(job)
|
|
266
|
+
return job.done
|
|
267
|
+
}
|
|
268
|
+
try {
|
|
269
|
+
if (command === 'all' && process.stdin.isTTY && process.stdout.isTTY && !env.CI && env.NUXT_TUI !== 'plain') {
|
|
270
|
+
try {
|
|
271
|
+
relay = await openDevLogRelay(writeJobLog)
|
|
272
|
+
} catch (error) {
|
|
273
|
+
console.warn('[emulators] Nuxt のログに接続できないため、端末へ直接出力します。', error.message)
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
abort.signal.throwIfAborted()
|
|
277
|
+
const emulator = launch('firebase', [
|
|
278
|
+
'emulators:start', `--project=${env.NUXT_PUBLIC_FIREBASE_PROJECT_ID}`,
|
|
279
|
+
'--import=./data', '--export-on-exit',
|
|
280
|
+
], { label: 'emulators' })
|
|
281
|
+
if (!stack) {
|
|
282
|
+
const result = await emulator
|
|
283
|
+
if (!abort.signal.aborted) requireSuccess(result, 'Emulator')
|
|
284
|
+
return
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const workers = []
|
|
288
|
+
const emulatorExit = emulator.then(result => {
|
|
289
|
+
requireSuccess(result, 'Emulator')
|
|
290
|
+
throw new Error('Emulator が終了しました')
|
|
291
|
+
})
|
|
292
|
+
if (watch || command === 'all') {
|
|
293
|
+
// 依存先の起動完了を待つ間にエミュレーターが終了した場合は、開発用プロセスの起動を中断する。
|
|
294
|
+
await Promise.race([waitReady(emulators, abort.signal), emulatorExit])
|
|
295
|
+
abort.signal.throwIfAborted()
|
|
296
|
+
}
|
|
297
|
+
const pnpmPath = env.npm_config_user_agent?.startsWith('pnpm/') ? env.npm_execpath : undefined
|
|
298
|
+
const [pnpm, ...pnpmArgs] = pnpmPath && /\.[cm]?js$/.test(pnpmPath)
|
|
299
|
+
? [process.execPath, pnpmPath]
|
|
300
|
+
: [pnpmPath || 'pnpm']
|
|
301
|
+
if (watch) {
|
|
302
|
+
workers.push(launch(pnpm, [...pnpmArgs, '--dir', join(root, 'functions'), 'build:watch'], {
|
|
303
|
+
label: 'functions',
|
|
304
|
+
stopping: abort.signal,
|
|
305
|
+
})
|
|
306
|
+
.then(result => {
|
|
307
|
+
requireSuccess(result, 'Functions build:watch')
|
|
308
|
+
throw new Error('Functions build:watch が終了しました')
|
|
309
|
+
}))
|
|
310
|
+
}
|
|
311
|
+
if (command === 'all') {
|
|
312
|
+
const project = env.NUXT_PUBLIC_FIREBASE_PROJECT_ID
|
|
313
|
+
const nuxtEnv = {
|
|
314
|
+
...env,
|
|
315
|
+
GCLOUD_PROJECT: project,
|
|
316
|
+
GOOGLE_CLOUD_PROJECT: project,
|
|
317
|
+
CLOUD_TASKS_EMULATOR_HOST: env.CLOUD_TASKS_EMULATOR_HOST || addressText(emulatorAddress(emulators.tasks, 9499)),
|
|
318
|
+
...(relay ? { BAKUSOKU_DEV_LOG_SOCKET: relay.path } : {}),
|
|
319
|
+
}
|
|
320
|
+
relay?.waitForNuxt()
|
|
321
|
+
workers.push(launch(pnpm, [...pnpmArgs, 'dev'], { env: nuxtEnv }).then(result => requireSuccess(result, 'Nuxt')))
|
|
322
|
+
}
|
|
323
|
+
await Promise.race([emulatorExit, ...workers])
|
|
324
|
+
} catch (error) {
|
|
325
|
+
if (!abort.signal.aborted) throw error
|
|
326
|
+
} finally {
|
|
327
|
+
try {
|
|
328
|
+
if (stack || abort.signal.aborted) stop()
|
|
329
|
+
await Promise.all(jobs.map(job => job.done))
|
|
330
|
+
} finally {
|
|
331
|
+
if (process.stdin.isTTY && process.stdin.isRaw !== rawMode) process.stdin.setRawMode(rawMode)
|
|
332
|
+
closeControl()
|
|
333
|
+
process.off('SIGINT', stop)
|
|
334
|
+
process.off('SIGTERM', stop)
|
|
335
|
+
await relay?.close()
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** コマンドを検証し、対応する開発用処理を実行する。 */
|
|
341
|
+
async function main(args) {
|
|
342
|
+
const [command] = args
|
|
343
|
+
if (args.length === 0 || (args.length === 1 && ['-h', '--help'].includes(command))) {
|
|
344
|
+
console.log(usage)
|
|
345
|
+
return
|
|
346
|
+
}
|
|
347
|
+
if (args.length !== 1 || !['all', 'backend', 'emulators:start', 'emulators:stop', 'functions:shell'].includes(command)) {
|
|
348
|
+
throw new Error(usage)
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const root = findProject()
|
|
352
|
+
if (command === 'emulators:stop') {
|
|
353
|
+
try {
|
|
354
|
+
await requestControl(controlPath(root), true)
|
|
355
|
+
} catch (error) {
|
|
356
|
+
if (!['ENOENT', 'ECONNREFUSED'].includes(error.code)) throw error
|
|
357
|
+
console.log('このプロジェクトで bakusoku-dev が起動した Emulator は実行されていません。')
|
|
358
|
+
}
|
|
359
|
+
return
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const env = projectEnv(root)
|
|
363
|
+
if (command === 'functions:shell') {
|
|
364
|
+
const job = start('firebase', ['functions:shell', `--project=${env.NUXT_PUBLIC_FIREBASE_PROJECT_ID}`], { root, env })
|
|
365
|
+
/** 終了シグナルを Functions シェルに転送する。 */
|
|
366
|
+
const forward = () => job.interrupt()
|
|
367
|
+
process.on('SIGINT', forward)
|
|
368
|
+
process.on('SIGTERM', forward)
|
|
369
|
+
try {
|
|
370
|
+
const result = await job.done
|
|
371
|
+
if (result.error) throw result.error
|
|
372
|
+
process.exitCode = result.code ?? (result.signal === 'SIGINT' ? 130 : 1)
|
|
373
|
+
} finally {
|
|
374
|
+
process.off('SIGINT', forward)
|
|
375
|
+
process.off('SIGTERM', forward)
|
|
376
|
+
}
|
|
377
|
+
return
|
|
378
|
+
}
|
|
379
|
+
await runEmulators(command, root, env)
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
try {
|
|
383
|
+
await main(process.argv.slice(2))
|
|
384
|
+
} catch (error) {
|
|
385
|
+
console.error(error.message)
|
|
386
|
+
process.exitCode = 1
|
|
387
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { mkdtemp, rm } from 'node:fs/promises'
|
|
2
|
+
import { createServer } from 'node:net'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { stripVTControlCharacters } from 'node:util'
|
|
5
|
+
|
|
6
|
+
const HISTORY_LIMIT = 200
|
|
7
|
+
const CONNECTION_TIMEOUT_MS = 10_000
|
|
8
|
+
|
|
9
|
+
/** 子プロセスの出力を Nuxt へ渡し、接続できない場合は端末への出力に戻す。 */
|
|
10
|
+
export async function openDevLogRelay(writeToTerminal) {
|
|
11
|
+
const directory = await mkdtemp('/tmp/bakusoku-logs-')
|
|
12
|
+
const path = join(directory, 'logs.sock')
|
|
13
|
+
const queued = []
|
|
14
|
+
let connection
|
|
15
|
+
let forwarding = false
|
|
16
|
+
let fallback
|
|
17
|
+
|
|
18
|
+
/** まだ端末に出していないログを、リレーを使わずに表示する。 */
|
|
19
|
+
function flushToTerminal() {
|
|
20
|
+
forwarding = false
|
|
21
|
+
for (const item of queued) {
|
|
22
|
+
if (!item.printed) {
|
|
23
|
+
writeToTerminal(item.label, item.line, item.stderr)
|
|
24
|
+
item.printed = true
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Nuxt の起動中や再起動中に出たログを、接続が来るまで一時保管する。 */
|
|
30
|
+
function waitForNuxt() {
|
|
31
|
+
clearTimeout(fallback)
|
|
32
|
+
forwarding = true
|
|
33
|
+
fallback = setTimeout(flushToTerminal, CONNECTION_TIMEOUT_MS)
|
|
34
|
+
fallback.unref()
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 端末操作用の制御文字を除き、ログを1行ずつ Nuxt に渡す。 */
|
|
38
|
+
function forward(socket, { label, line, stderr }) {
|
|
39
|
+
const text = stripVTControlCharacters(line).replace(/\p{Cc}/gu, char => char === '\t' ? char : '')
|
|
40
|
+
if (text.trim()) socket.write(JSON.stringify({ message: `[${label}] ${text}`, stderr }) + '\n')
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const server = createServer((socket) => {
|
|
44
|
+
connection?.destroy()
|
|
45
|
+
connection = socket
|
|
46
|
+
clearTimeout(fallback)
|
|
47
|
+
forwarding = true
|
|
48
|
+
socket.on('error', () => socket.destroy())
|
|
49
|
+
socket.on('close', () => {
|
|
50
|
+
if (connection !== socket) return
|
|
51
|
+
connection = undefined
|
|
52
|
+
waitForNuxt()
|
|
53
|
+
})
|
|
54
|
+
for (const item of queued.splice(0)) forward(socket, item)
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
try {
|
|
58
|
+
await new Promise((resolve, reject) => {
|
|
59
|
+
server.once('error', reject)
|
|
60
|
+
server.listen(path, () => {
|
|
61
|
+
server.off('error', reject)
|
|
62
|
+
resolve()
|
|
63
|
+
})
|
|
64
|
+
})
|
|
65
|
+
} catch (error) {
|
|
66
|
+
await rm(directory, { recursive: true, force: true })
|
|
67
|
+
throw error
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return {
|
|
71
|
+
path,
|
|
72
|
+
waitForNuxt,
|
|
73
|
+
/** 起動前のログも保持し、Nuxt 接続後は端末への二重出力を避ける。 */
|
|
74
|
+
report(label, line, stderr) {
|
|
75
|
+
const item = { label, line, stderr, printed: !forwarding }
|
|
76
|
+
if (connection?.writable && connection.writableLength < 256 * 1024) {
|
|
77
|
+
forward(connection, item)
|
|
78
|
+
return
|
|
79
|
+
}
|
|
80
|
+
if (connection?.writable) connection.destroy()
|
|
81
|
+
if (item.printed) writeToTerminal(label, line, stderr)
|
|
82
|
+
queued.push(item)
|
|
83
|
+
if (queued.length > HISTORY_LIMIT) queued.shift()
|
|
84
|
+
},
|
|
85
|
+
/** 保留中のログを表示し、今回の起動専用のソケットを片付ける。 */
|
|
86
|
+
async close() {
|
|
87
|
+
clearTimeout(fallback)
|
|
88
|
+
const socket = connection
|
|
89
|
+
connection = undefined
|
|
90
|
+
socket?.destroy()
|
|
91
|
+
await new Promise(resolve => server.close(resolve))
|
|
92
|
+
flushToTerminal()
|
|
93
|
+
await rm(directory, { recursive: true, force: true })
|
|
94
|
+
},
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { execFile, execFileSync } from 'node:child_process'
|
|
4
|
+
import { copyFileSync, existsSync } from 'node:fs'
|
|
5
|
+
import { promisify } from 'node:util'
|
|
6
|
+
|
|
7
|
+
const mode = process.argv[2]
|
|
8
|
+
if (mode !== 'ssr' && mode !== 'ssg') {
|
|
9
|
+
throw new Error('Usage: bakusoku-predeploy <ssr|ssg>')
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const project = process.env.GCLOUD_PROJECT
|
|
13
|
+
|| (await promisify(execFile)('firebase', ['use'])).stdout.trim()
|
|
14
|
+
const projectEnv = `.env.${project}`
|
|
15
|
+
const dotenv = mode === 'ssg' && !existsSync(projectEnv) ? '.env' : projectEnv
|
|
16
|
+
if (!existsSync(dotenv)) {
|
|
17
|
+
throw new Error(`${dotenv} が存在しません。デプロイ用の環境変数ファイルを作成してください。`)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const args = mode === 'ssr' ? ['build', '--preset', 'firebase'] : ['generate']
|
|
21
|
+
execFileSync('pnpm', ['run', ...args, '--dotenv', dotenv], { stdio: 'inherit' })
|
|
22
|
+
if (mode === 'ssr') {
|
|
23
|
+
copyFileSync(dotenv, '.output/server/.env')
|
|
24
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { copyFileSync, readFileSync, writeFileSync, rmSync } from 'node:fs'
|
|
2
|
+
import { resolve } from 'node:path'
|
|
3
|
+
import { execFileSync } from 'node:child_process'
|
|
4
|
+
|
|
5
|
+
// Firebase CLI v15 で SSR をデプロイした際、.output/server の
|
|
6
|
+
// firebase-functions のバージョン解決と lib/v2/index.js の読み込みが失敗した。
|
|
7
|
+
// SSR の Nitro 設定では traceInclude で CLI が読む CommonJS エントリを含める。
|
|
8
|
+
// ここでは Cloud Build が .output/server 単体から公開依存を再インストールできるよう、
|
|
9
|
+
// 実行用の package.json と、成果物の依存に合う pnpm-lock.yaml を用意する。
|
|
10
|
+
const root = process.cwd()
|
|
11
|
+
const serverDir = resolve(process.argv[2] || resolve(root, '.output/server'))
|
|
12
|
+
const source = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'))
|
|
13
|
+
const manifestPath = resolve(serverDir, 'package.json')
|
|
14
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
|
|
15
|
+
|
|
16
|
+
manifest.packageManager = source.packageManager
|
|
17
|
+
manifest.main = 'index.mjs'
|
|
18
|
+
if (source.engines) {
|
|
19
|
+
manifest.engines = source.engines
|
|
20
|
+
}
|
|
21
|
+
if (source.pnpm) {
|
|
22
|
+
manifest.pnpm = source.pnpm
|
|
23
|
+
}
|
|
24
|
+
manifest.dependencies ??= {}
|
|
25
|
+
const frameworkVersion = source.dependencies?.['@google-cloud/functions-framework']
|
|
26
|
+
if (frameworkVersion) {
|
|
27
|
+
manifest.dependencies['@google-cloud/functions-framework'] = frameworkVersion
|
|
28
|
+
}
|
|
29
|
+
delete manifest.devDependencies
|
|
30
|
+
delete manifest.scripts
|
|
31
|
+
writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
|
|
32
|
+
writeFileSync(resolve(serverDir, '.npmrc'), 'registry=https://registry.npmjs.org/\nnode-linker=hoisted\n')
|
|
33
|
+
|
|
34
|
+
// Seed resolution from the imported lock to retain existing dependency versions.
|
|
35
|
+
copyFileSync(resolve(root, 'pnpm-lock.yaml'), resolve(serverDir, 'pnpm-lock.yaml'))
|
|
36
|
+
for (const name of ['package-lock.json', 'yarn.lock']) {
|
|
37
|
+
rmSync(resolve(serverDir, name), { force: true })
|
|
38
|
+
}
|
|
39
|
+
execFileSync('pnpm', ['install', '--lockfile-only', '--ignore-scripts', '--prefer-offline', '--no-frozen-lockfile'], {
|
|
40
|
+
cwd: serverDir,
|
|
41
|
+
stdio: 'inherit',
|
|
42
|
+
})
|
|
43
|
+
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# ワークツリーのルートで実行:
|
|
3
|
+
# bakusoku-setup-worktree [コピー元のリポジトリ]
|
|
4
|
+
set -euo pipefail
|
|
5
|
+
|
|
6
|
+
if [[ $# -gt 1 ]]; then
|
|
7
|
+
printf 'Usage: bakusoku-setup-worktree [source-repository]\n' >&2
|
|
8
|
+
exit 1
|
|
9
|
+
fi
|
|
10
|
+
|
|
11
|
+
target_dir="$(git rev-parse --show-toplevel)"
|
|
12
|
+
common_dir="$(git rev-parse --path-format=absolute --git-common-dir)"
|
|
13
|
+
source_dir="${1:-$(dirname "$common_dir")}"
|
|
14
|
+
|
|
15
|
+
if [[ ! -f "$target_dir/package.json" ]]; then
|
|
16
|
+
printf 'Error: 実行先に package.json がありません。\n' >&2
|
|
17
|
+
exit 1
|
|
18
|
+
fi
|
|
19
|
+
command -v pnpm >/dev/null || { printf 'Error: pnpm が必要です。\n' >&2; exit 1; }
|
|
20
|
+
|
|
21
|
+
if [[ -e "$target_dir/.env" || -L "$target_dir/.env" ]]; then
|
|
22
|
+
printf '既存の .env を保持します。\n'
|
|
23
|
+
else
|
|
24
|
+
if [[ ! -f "$source_dir/.env" ]]; then
|
|
25
|
+
printf 'Error: コピー元の .env がありません。コピー元を引数で指定してください。\n' >&2
|
|
26
|
+
exit 1
|
|
27
|
+
fi
|
|
28
|
+
(umask 077; cp -- "$source_dir/.env" "$target_dir/.env")
|
|
29
|
+
chmod 600 "$target_dir/.env"
|
|
30
|
+
printf '.env をコピーしました。\n'
|
|
31
|
+
fi
|
|
32
|
+
|
|
33
|
+
if [[ -e "$target_dir/data" || -L "$target_dir/data" ]]; then
|
|
34
|
+
printf '既存の data/ を保持します。\n'
|
|
35
|
+
else
|
|
36
|
+
if [[ ! -d "$source_dir/data" ]]; then
|
|
37
|
+
printf 'Error: コピー元の data/ がありません。コピー元を引数で指定してください。\n' >&2
|
|
38
|
+
exit 1
|
|
39
|
+
fi
|
|
40
|
+
cp -a -- "$source_dir/data" "$target_dir/data"
|
|
41
|
+
printf 'data/ を丸ごとコピーしました。\n'
|
|
42
|
+
fi
|
|
43
|
+
|
|
44
|
+
# npmjs 用のプロジェクト設定を雛形から用意する。
|
|
45
|
+
if [[ -e "$target_dir/.npmrc" || -L "$target_dir/.npmrc" ]]; then
|
|
46
|
+
printf '既存の .npmrc を保持します。\n'
|
|
47
|
+
elif [[ -f "$target_dir/.npmrc.example" ]]; then
|
|
48
|
+
(umask 077; cp -- "$target_dir/.npmrc.example" "$target_dir/.npmrc")
|
|
49
|
+
chmod 600 "$target_dir/.npmrc"
|
|
50
|
+
printf '.npmrc をコピーしました。\n'
|
|
51
|
+
fi
|
|
52
|
+
|
|
53
|
+
printf 'ルートの依存関係をインストールします。\n'
|
|
54
|
+
(cd "$target_dir" && pnpm install)
|
|
55
|
+
if [[ -f "$target_dir/functions/package.json" ]]; then
|
|
56
|
+
printf 'functions の依存関係をインストールします。\n'
|
|
57
|
+
(cd "$target_dir/functions" && pnpm install)
|
|
58
|
+
fi
|
|
59
|
+
printf 'ワークツリーの準備が完了しました。\n'
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { cpSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, existsSync, writeFileSync } from 'node:fs'
|
|
4
|
+
import { tmpdir } from 'node:os'
|
|
5
|
+
import { resolve, join, sep } from 'node:path'
|
|
6
|
+
import { execFileSync } from 'node:child_process'
|
|
7
|
+
import { createRequire } from 'node:module'
|
|
8
|
+
|
|
9
|
+
const root = process.cwd()
|
|
10
|
+
const sources = process.argv.length > 2 ? process.argv.slice(2) : ['.output/server']
|
|
11
|
+
if (process.argv.length === 2 && existsSync(resolve(root, 'functions', 'package.json'))) {
|
|
12
|
+
sources.unshift('functions/.firebase')
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
for (const source of sources) {
|
|
16
|
+
const target = mkdtempSync(join(tmpdir(), 'bakusoku-deploy-'))
|
|
17
|
+
try {
|
|
18
|
+
for (const name of ['package.json', 'pnpm-lock.yaml', '.npmrc']) {
|
|
19
|
+
const from = resolve(root, source, name)
|
|
20
|
+
if (!existsSync(from)) {
|
|
21
|
+
throw new Error(`Missing ${source}/${name}. Run a firebase preset build first for .output/server.`)
|
|
22
|
+
}
|
|
23
|
+
cpSync(from, join(target, name), { recursive: true })
|
|
24
|
+
}
|
|
25
|
+
// Copy only compiled application code, never local environment files.
|
|
26
|
+
for (const name of source.endsWith('/.firebase') ? ['.output'] : ['index.mjs', 'chunks']) {
|
|
27
|
+
cpSync(resolve(root, source, name), join(target, name), { recursive: true })
|
|
28
|
+
}
|
|
29
|
+
const cleanHome = join(target, '.clean-home')
|
|
30
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) =>
|
|
31
|
+
!/token|npm_config|pnpm_|corepack_/i.test(key)))
|
|
32
|
+
env.HOME = cleanHome
|
|
33
|
+
env.NPM_CONFIG_USERCONFIG = join(target, '.empty-npmrc')
|
|
34
|
+
writeFileSync(env.NPM_CONFIG_USERCONFIG, '')
|
|
35
|
+
execFileSync('pnpm', ['install', '--prod', '--frozen-lockfile', '--store-dir', join(target, '.store')], {
|
|
36
|
+
cwd: target, stdio: 'inherit', env,
|
|
37
|
+
})
|
|
38
|
+
const require = createRequire(join(target, 'package.json'))
|
|
39
|
+
for (const name of ['firebase-functions', 'firebase-admin', '@google-cloud/functions-framework']) {
|
|
40
|
+
if (!require.resolve(name).startsWith(target + sep)) throw new Error(`External dependency: ${name}`)
|
|
41
|
+
require(name)
|
|
42
|
+
}
|
|
43
|
+
// Firebase CLI reads this CommonJS path on disk; package "exports" may block require.resolve.
|
|
44
|
+
const v2Entry = join(target, 'node_modules/firebase-functions/lib/v2/index.js')
|
|
45
|
+
if (!existsSync(v2Entry)) {
|
|
46
|
+
throw new Error('Missing firebase-functions/lib/v2/index.js in the artifact')
|
|
47
|
+
}
|
|
48
|
+
/** 配備成果物のシンボリックリンクを走査して参照先を検証する。 */
|
|
49
|
+
function checkLinks(dir) {
|
|
50
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
51
|
+
const path = join(dir, entry.name)
|
|
52
|
+
if (entry.isSymbolicLink() && !realpathSync(path).startsWith(target + sep)) {
|
|
53
|
+
throw new Error('Deployment contains an external symlink')
|
|
54
|
+
}
|
|
55
|
+
if (entry.isDirectory()) checkLinks(path)
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
checkLinks(target)
|
|
59
|
+
const manifest = JSON.parse(readFileSync(join(target, 'package.json'), 'utf8'))
|
|
60
|
+
execFileSync(process.execPath, ['--input-type=module', '-e',
|
|
61
|
+
`await import(${JSON.stringify('./' + manifest.main)}); process.exit(0)`], {
|
|
62
|
+
cwd: target,
|
|
63
|
+
stdio: 'inherit',
|
|
64
|
+
timeout: 30000,
|
|
65
|
+
})
|
|
66
|
+
console.log(`${source}: production install, module loading and symlinks verified`)
|
|
67
|
+
} finally {
|
|
68
|
+
rmSync(target, { recursive: true, force: true })
|
|
69
|
+
}
|
|
70
|
+
}
|