@c-time/frelio-cli 2.3.0 → 2.5.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.
@@ -7,21 +7,22 @@
7
7
  import prompts from 'prompts';
8
8
  import fs from 'node:fs';
9
9
  import path from 'node:path';
10
- import { log, logStep, logSuccess, logError } from '../lib/shell.js';
11
- import { generateStagingDomain, buildWorkerNames, } from '../lib/templates.js';
10
+ import { log, logStep, logSuccess, logError, logWarning } from '../lib/shell.js';
11
+ import { buildWorkerNames, deriveFromAdminHost, derivePreviewUrl, } from '../lib/templates.js';
12
12
  import { buildResourceLinks } from '../lib/resource-links.js';
13
13
  import { validateContentRepo, validateR2PublicUrl, validateRequired, sanitizeCloudflareName, validateCloudflareName, } from '../lib/validators.js';
14
14
  // core functions
15
15
  import { checkPrerequisitesFor } from '../core/prerequisites.js';
16
16
  import { buildConfig } from '../core/config.js';
17
17
  import { createRepo, cloneRepo, getAuthenticatedUser } from '../core/github.js';
18
- import { setupCloudflareResources } from '../core/cloudflare.js';
18
+ import { createR2Bucket, setWorkerSecretByName, deployAdminWorker } from '../core/cloudflare.js';
19
19
  import { setupContactWorker } from '../core/contact.js';
20
20
  import { setupScheduledPublishWorker } from '../core/scheduled-publish.js';
21
+ import { setupFileDeliveryWorker } from '../core/file-delivery.js';
21
22
  import { createFullContentStructure } from '../core/content-structure.js';
22
23
  import { regenerateAllConfigFiles } from '../core/file-generators.js';
23
24
  import { installBundle } from '../core/bundle.js';
24
- import { initialCommitAndBranches, getGitIdentity, setGitIdentity, } from '../core/git-operations.js';
25
+ import { initialCommitAndBranches, generateLockfile, getGitIdentity, setGitIdentity, } from '../core/git-operations.js';
25
26
  export async function initCommand(options) {
26
27
  log('');
27
28
  log('🚀 Frelio CMS プロジェクトセットアップ');
@@ -59,48 +60,20 @@ export async function initCommand(options) {
59
60
  // ── 予約反映(任意)──
60
61
  const scheduleInput = options.skipCloudflare ? null : await promptScheduledPublish();
61
62
  log('');
62
- // ── OAuth App 案内 ──
63
- log('🔑 GitHub OAuth App:');
64
- if (!config.githubClientId) {
65
- const isInteractive = process.stdin.isTTY === true;
66
- if (!isInteractive) {
67
- logError('非対話モードでは --client-id と --client-secret が必須です。');
68
- process.exit(1);
69
- }
70
- log(' ⚠ OAuth App は GitHub の Web UI で作成が必要です。');
71
- log(' → https://github.com/settings/developers');
72
- log(' → New OAuth App:');
73
- log(` - Application name: ${config.siteTitle || config.adminWorkerName} CMS`);
74
- log(` - Homepage URL: https://${config.adminWorkerName}.<your-subdomain>.workers.dev`);
75
- log(` - Callback URL: https://${config.adminWorkerName}.<your-subdomain>.workers.dev/api/auth/callback`);
76
- log(' (<your-subdomain> は管理画面 Worker 初回デプロイ後に確定する workers.dev サブドメイン。独自ドメイン運用ならそのドメインに読み替え)');
77
- log(' - Enable Device Flow: チェックしない(Disable のまま。Frelio は認可コードフローを使用)');
78
- log('');
79
- const oauthResponse = await prompts([
80
- {
81
- type: 'text',
82
- name: 'clientId',
83
- message: 'OAuth Client ID を入力:',
84
- validate: (v) => validateRequired(v, 'Client ID'),
85
- },
86
- {
87
- type: 'password',
88
- name: 'clientSecret',
89
- message: 'OAuth Client Secret を入力:',
90
- validate: (v) => validateRequired(v, 'Client Secret'),
91
- },
92
- ]);
93
- if (!oauthResponse.clientId) {
94
- log('セットアップをキャンセルしました。');
95
- process.exit(0);
96
- }
97
- config.githubClientId = oauthResponse.clientId;
98
- config.githubClientSecret =
99
- oauthResponse.clientSecret;
63
+ // ── ファイル限定配信(任意。フォーム送信後にダウンロード URL を期限付きメール配信)──
64
+ const fileDeliveryInput = options.skipCloudflare ? null : await promptFileDelivery(!!contactInput);
65
+ // 公開 URL を把握できていれば config.json(downloadApiUrl)へ焼き込む(後続の設定ファイル生成に反映)。
66
+ // 未確定(空)なら空のまま。初回デプロイ後に基本設定で設定する。
67
+ if (fileDeliveryInput?.publicBaseUrl) {
68
+ config.downloadApiUrl = fileDeliveryInput.publicBaseUrl;
100
69
  }
101
70
  log('');
71
+ // Issue #261: OAuth の収集は「管理画面 Worker のホスト確定後」に行う(下記 collectOAuth)。
72
+ // コールバック URL は admin のホストが決まらないと作れない(ニワトリ卵)ため、
73
+ // deploy-first(admin を一度デプロイしてホストを得る)か --admin-host 指定の後に収集する。
74
+ // 非対話で Client ID/Secret が未指定の場合は promptConfig 時点で既に弾かれている。
102
75
  // ── セットアップ実行 ──
103
- const totalSteps = getTotalSteps(options, !!contactInput, !!scheduleInput);
76
+ const totalSteps = getTotalSteps(options, !!contactInput, !!scheduleInput, !!fileDeliveryInput, !options.adminHost);
104
77
  let step = 0;
105
78
  // GitHub リポジトリ作成
106
79
  if (!options.skipGithub) {
@@ -171,38 +144,81 @@ export async function initCommand(options) {
171
144
  logError(configResult.error);
172
145
  process.exit(1);
173
146
  }
174
- // Cloudflare セットアップ
147
+ // package-lock.json 生成(初回コミットに含める)
148
+ // init は npm install を実行しないため、放置するとロックファイルが無いまま push され、
149
+ // admin ブランチ初回 push の deploy-admin(setup-node cache:'npm')や
150
+ // build-staging / promote-production(npm ci)が必ず1回失敗する。ここで生成しておくと
151
+ // 後続の初回コミット(git add -A)に含まれる。失敗は致命ではないので警告に留めて続行。
152
+ step++;
153
+ logStep(step, totalSteps, 'package-lock.json 生成...');
154
+ const lockResult = generateLockfile(projectDir);
155
+ if (lockResult.success) {
156
+ logSuccess('package-lock.json 生成完了');
157
+ }
158
+ else {
159
+ log(` ⚠ package-lock.json を生成できませんでした(${lockResult.error})。`);
160
+ log(' デプロイ前に `npm install` を実行し、package-lock.json をコミットしてください。');
161
+ }
162
+ // ── Cloudflare: R2 作成 → 管理画面 Worker のホスト確定(deploy-first / Issue #261)──
163
+ // workers.dev の「アカウント部」はアカウント固定値で、デプロイ前にはきれいに読めない。
164
+ // そこで admin Worker を一度デプロイし、その出力ホスト(<admin>.<account>.workers.dev)から
165
+ // アカウント部を取り出して実在 URL を確定する。--admin-host 指定時はデプロイ検出をスキップする。
166
+ let adminHost = (options.adminHost ?? '').trim();
167
+ let adminWorkerDeployed = false; // secret 投入はワーカー存在が前提(deploy 済みなら true)
175
168
  if (!options.skipCloudflare) {
176
169
  step++;
177
- logStep(step, totalSteps, 'Cloudflare セットアップ...');
178
- const secret = config.githubClientSecret;
179
- const cfResult = setupCloudflareResources(config, secret);
180
- if (cfResult.success) {
181
- const { r2Bucket, secrets, needsWorkersDevSubdomain } = cfResult.data;
182
- if (r2Bucket.success) {
183
- logSuccess(r2Bucket.alreadyExisted
184
- ? `R2 バケット "${config.r2BucketName}" は既に存在します`
185
- : `R2 バケット "${config.r2BucketName}" 作成完了`);
170
+ logStep(step, totalSteps, 'Cloudflare: R2 バケット作成...');
171
+ const r2Bucket = createR2Bucket(config.r2BucketName);
172
+ if (r2Bucket.success) {
173
+ logSuccess(r2Bucket.alreadyExisted
174
+ ? `R2 バケット "${config.r2BucketName}" は既に存在します`
175
+ : `R2 バケット "${config.r2BucketName}" 作成完了`);
176
+ }
177
+ else {
178
+ logError(r2Bucket.error);
179
+ }
180
+ // 管理画面 Worker のホストを確定する
181
+ if (!adminHost) {
182
+ step++;
183
+ logStep(step, totalSteps, '管理画面 Worker を初回デプロイしてホストを確定...');
184
+ const deployResult = deployAdminWorker(projectDir);
185
+ if (deployResult.success) {
186
+ adminHost = deployResult.data.host;
187
+ adminWorkerDeployed = true;
188
+ logSuccess(`管理画面 Worker をデプロイしました(${adminHost})`);
186
189
  }
187
190
  else {
188
- logError(r2Bucket.error);
189
- }
190
- // Issue #184: Worker は wrangler deploy 時に自動作成される(事前作成は不要)。
191
- // admin Worker のシークレット(GITHUB_CLIENT_SECRET)は
192
- // wrangler secret put が Worker を自動作成して設定する(初回デプロイ前でも可)。
193
- for (const s of secrets) {
194
- if (s.success) {
195
- logSuccess('admin Worker シークレット設定完了');
196
- }
197
- else {
198
- logError(s.error);
199
- }
200
- }
201
- if (needsWorkersDevSubdomain) {
202
- log(' ℹ staging プレビュー URL(<branch>-<worker>.<subdomain>.workers.dev)は、admin Worker の初回デプロイで workers.dev サブドメインが登録されてから有効になります。');
191
+ logError(deployResult.error);
192
+ log(' ⚠ ホストを自動確定できませんでした。確定済みなら `--admin-host <host>` を付けて再実行するか、');
193
+ log(' 初回デプロイ後に CMS「基本設定」で workers.dev サブドメイン等を設定してください。');
203
194
  }
204
195
  }
196
+ else {
197
+ logSuccess(`管理画面ホストを指定値で確定: ${adminHost}`);
198
+ }
199
+ }
200
+ else if (adminHost) {
201
+ logSuccess(`管理画面ホストを指定値で確定: ${adminHost}`);
205
202
  }
203
+ // ホストが確定したら、workers.dev のアカウント部と preview URL を config に反映して再生成する。
204
+ if (adminHost) {
205
+ const d = deriveFromAdminHost(adminHost);
206
+ if (d.isWorkersDev && d.workersSubdomain) {
207
+ config.workersSubdomain = d.workersSubdomain;
208
+ }
209
+ // 独自の staging ドメインが未設定なら workers.dev から preview URL を導く(Issue #261)。
210
+ if (!config.stagingDomain) {
211
+ config.previewUrl = derivePreviewUrl({
212
+ workersSubdomain: config.workersSubdomain,
213
+ contentWorkerName: config.contentWorkerName,
214
+ });
215
+ }
216
+ const regen = regenerateAllConfigFiles(projectDir, config);
217
+ if (!regen.success)
218
+ logError(regen.error);
219
+ }
220
+ // ── GitHub OAuth App(ホスト確定後に正確なコールバックを提示して収集)──
221
+ await collectAndApplyOAuth(config, options, projectDir, adminHost, adminWorkerDeployed);
206
222
  // お問い合わせワーカー(任意)
207
223
  if (contactInput) {
208
224
  step++;
@@ -242,6 +258,40 @@ export async function initCommand(options) {
242
258
  logError(scheduleResult.error);
243
259
  }
244
260
  }
261
+ // ファイル限定配信ワーカー(任意)
262
+ if (fileDeliveryInput) {
263
+ step++;
264
+ logStep(step, totalSteps, 'ファイル限定配信ワーカーのセットアップ(専用 R2・D1・wrangler.toml)...');
265
+ const deliveryResult = setupFileDeliveryWorker(projectDir, config, fileDeliveryInput);
266
+ if (deliveryResult.success) {
267
+ const d = deliveryResult.data;
268
+ logSuccess(d.bucketAlreadyExisted
269
+ ? `専用プライベート R2 バケット "${d.bucketName}" は既に存在します`
270
+ : `専用プライベート R2 バケット "${d.bucketName}" 作成完了`);
271
+ logSuccess(d.d1AlreadyExisted
272
+ ? `D1 "frelio_downloads" は既に存在します(id: ${d.databaseId})`
273
+ : `D1 "frelio_downloads" 作成完了(id: ${d.databaseId})`);
274
+ if (d.migrated)
275
+ logSuccess('D1 マイグレーション適用完了');
276
+ else
277
+ log(' ⚠ D1 マイグレーションは後で workers/file-delivery で `npx wrangler d1 migrations apply frelio_downloads --remote` を実行してください。');
278
+ if (d.wiredContact) {
279
+ logSuccess('contact ワーカーに DELIVERY Service Binding を配線しました(トークン発行が有効化)');
280
+ }
281
+ else if (fileDeliveryInput.wireContact) {
282
+ log(' ℹ contact ワーカーは既に DELIVERY 配線済みでした。');
283
+ }
284
+ else {
285
+ log(' ℹ お問い合わせ機能が未 opt-in のため DELIVERY 配線は行いませんでした。');
286
+ log(' 配信フォームには contact も必要です。後から contact をセットアップし、workers/contact/wrangler.toml に');
287
+ log(' [[services]] DELIVERY(entrypoint=DeliveryEntrypoint)を追記してください。');
288
+ }
289
+ logSuccess('ファイル限定配信ワーカーのセットアップ完了(deploy は workers/file-delivery で別途 → 基本設定で downloadApiUrl を設定)');
290
+ }
291
+ else {
292
+ logError(deliveryResult.error);
293
+ }
294
+ }
245
295
  // git identity 確認(commit 直前 — 未設定だとデフォルト値で commit author が埋まるのを防ぐ)
246
296
  if (!options.skipGithub) {
247
297
  step++;
@@ -264,11 +314,38 @@ export async function initCommand(options) {
264
314
  log('');
265
315
  log('✅ セットアップ完了!');
266
316
  log('');
267
- log(` 管理画面: https://${config.adminWorkerName}.<your-subdomain>.workers.dev/(admin Worker 初回デプロイ後)`);
317
+ // Issue #261: ホストが確定(deploy-first 検出 or --admin-host)していれば実在 URL、未確定ならプレースホルダ。
318
+ const adminDisplayUrl = adminHost
319
+ ? `https://${adminHost}/${adminWorkerDeployed ? '(デプロイ済み)' : ''}`
320
+ : `https://${config.adminWorkerName}.<your-subdomain>.workers.dev/(admin Worker 初回デプロイ後)`;
321
+ log(` 管理画面: ${adminDisplayUrl}`);
268
322
  // カスタムドメイン未設定時は staging ブランチのプレビューエイリアス(GitHub Actions の
269
323
  // wrangler versions upload --preview-alias で生成)を案内する。
270
324
  log(` プレビュー: ${config.previewUrl || `https://staging-${config.contentWorkerName}.<your-subdomain>.workers.dev`}`);
271
325
  log('');
326
+ // 公開に必須だが空のまま完了しうる値を警告(開発は動くが本番公開が成立しない)。
327
+ // 特に R2 公開URL はバケット作成後にしか確定しないため未入力で終わりやすい。
328
+ const publishBlockers = [];
329
+ if (!config.r2PublicUrl) {
330
+ publishBlockers.push({
331
+ label: 'R2 公開URL',
332
+ note: '未設定だと画像・ファイルが表示されません(R2 の r2.dev URL かカスタムドメインを設定)',
333
+ });
334
+ }
335
+ if (!config.productionUrl) {
336
+ publishBlockers.push({
337
+ label: '本番URL',
338
+ note: '未設定だと sitemap・OGP・正規URL 等の絶対URLが生成できません',
339
+ });
340
+ }
341
+ if (publishBlockers.length > 0) {
342
+ logWarning('公開に必要な設定が未入力のまま完了しました(開発・プレビューは動作しますが、本番公開はできません):');
343
+ for (const b of publishBlockers) {
344
+ logWarning(` - ${b.label}: ${b.note}`);
345
+ }
346
+ log(' → 管理画面の「基本設定」で設定し、「セットアップ検証」で確認してください。');
347
+ log('');
348
+ }
272
349
  // 作成したリソースへのリンク(確認・設定変更の導線)
273
350
  const resourceSections = buildResourceLinks(config, {
274
351
  github: !options.skipGithub,
@@ -286,7 +363,15 @@ export async function initCommand(options) {
286
363
  }
287
364
  log(' 残りの手動作業:');
288
365
  log(' 1. GitHub Actions シークレットを設定: CLOUDFLARE_API_TOKEN / CLOUDFLARE_ACCOUNT_ID');
289
- log(' 2. admin ブランチへ push して管理画面 Worker を初回デプロイ(workers.dev サブドメインが登録される)');
366
+ log(' ※ トークンは対象アカウント配下の「アカウント API トークン」推奨(他顧客アカウントを巻き込まない)');
367
+ log(' 必要権限(アカウントスコープ3行): Workers スクリプト=編集 / Workers R2 ストレージ=編集 / アカウント設定=読み取り');
368
+ log(' 詳細: packages/cli/README.md「GitHub Actions シークレットの設定」');
369
+ if (adminWorkerDeployed) {
370
+ log(' 2. 管理画面 Worker は init でデプロイ済み。以降の更新は admin ブランチへの push(Actions)で反映');
371
+ }
372
+ else {
373
+ log(' 2. admin ブランチへ push して管理画面 Worker を初回デプロイ(workers.dev サブドメインが登録される)');
374
+ }
290
375
  log(' 3. staging ブランチへ push してコンテンツのプレビュー、main で本番デプロイ');
291
376
  if (config.stagingDomain) {
292
377
  log(` 4. プレビュー用カスタムドメインを設定: ${config.stagingDomain}`);
@@ -297,11 +382,103 @@ export async function initCommand(options) {
297
382
  log(' - お問い合わせフォーム: workers/contact/README.md(init で未設定なら後から)');
298
383
  log(' - 予約反映(時刻ベースの自動公開/非公開): workers/scheduled-publish/README.md を参照して');
299
384
  log(' ワーカーをデプロイ(PAT: Actions=RW / Contents=RO)→ 管理画面の「基本設定」→「予約反映 API URL」に設定');
385
+ log(' - ファイル限定配信(フォーム送信後にダウンロード URL を期限付きメール配信): workers/file-delivery/README.md を参照して');
386
+ log(' ワーカーをデプロイ → wrangler.toml の PUBLIC_BASE_URL と 管理画面「基本設定」→「downloadApiUrl」に実 URL を設定');
387
+ log(' (contact ワーカーとの併用が前提。contact/wrangler.toml の DELIVERY 配線が必要)');
300
388
  log('');
301
389
  }
302
390
  // ---------------------------------------------------------------------------
303
391
  // UI helpers (prompts — commands 層に閉じる)
304
392
  // ---------------------------------------------------------------------------
393
+ /**
394
+ * GitHub OAuth App のコールバックを「ホスト確定後」に提示し、Client ID/Secret を収集・反映する(Issue #261)。
395
+ *
396
+ * deploy-first(admin Worker を一度デプロイ)か --admin-host で admin のホストが確定していれば、
397
+ * 正確なコールバック URL(`https://<host>/api/auth/callback`)を提示してから収集できる=ニワトリ卵の解消。
398
+ * 収集後、Client ID を wrangler.admin.toml / config.json に焼き込み、ワーカーが存在すれば
399
+ * GITHUB_CLIENT_SECRET を投入して再デプロイする(OAuth [vars] を反映)。
400
+ */
401
+ async function collectAndApplyOAuth(config, options, projectDir, adminHost, adminWorkerDeployed) {
402
+ log('🔑 GitHub OAuth App:');
403
+ const d = adminHost ? deriveFromAdminHost(adminHost) : null;
404
+ const homepageUrl = d ? d.adminOrigin : `https://${config.adminWorkerName}.<your-subdomain>.workers.dev`;
405
+ const callbackUrl = d
406
+ ? d.adminCallbackUrl
407
+ : `https://${config.adminWorkerName}.<your-subdomain>.workers.dev/api/auth/callback`;
408
+ if (!config.githubClientId) {
409
+ const isInteractive = process.stdin.isTTY === true;
410
+ if (!isInteractive) {
411
+ logError('非対話モードでは --client-id と --client-secret が必須です。');
412
+ process.exit(1);
413
+ }
414
+ log(' ⚠ OAuth App は GitHub の Web UI で作成します(下の Callback URL を確定してから作成できます)。');
415
+ log(' → https://github.com/settings/developers → New OAuth App:');
416
+ log(` - Application name: ${config.siteTitle || config.adminWorkerName} CMS`);
417
+ log(` - Homepage URL: ${homepageUrl}`);
418
+ log(` - Callback URL: ${callbackUrl}`);
419
+ if (!d) {
420
+ log(' (管理画面ホストが未確定です。確定済みなら --admin-host <host> を付けて再実行すると正確な URL を提示します。');
421
+ log(' 独自ドメイン運用ならそのドメインに読み替え)');
422
+ }
423
+ else if (d.isWorkersDev) {
424
+ log(' (検出した実在 URL。独自ドメイン化したら set-domain 実行後に OAuth App の URL も更新)');
425
+ }
426
+ log(' - Enable Device Flow: チェックしない(Frelio は認可コードフローを使用)');
427
+ log('');
428
+ const oauthResponse = await prompts([
429
+ {
430
+ type: 'text',
431
+ name: 'clientId',
432
+ message: 'OAuth Client ID を入力:',
433
+ validate: (v) => validateRequired(v, 'Client ID'),
434
+ },
435
+ {
436
+ type: 'password',
437
+ name: 'clientSecret',
438
+ message: 'OAuth Client Secret を入力:',
439
+ validate: (v) => validateRequired(v, 'Client Secret'),
440
+ },
441
+ ], { onCancel: () => process.exit(0) });
442
+ if (!oauthResponse.clientId) {
443
+ log('セットアップをキャンセルしました。');
444
+ process.exit(0);
445
+ }
446
+ config.githubClientId = oauthResponse.clientId;
447
+ config.githubClientSecret = oauthResponse.clientSecret;
448
+ // Client ID([vars])を wrangler.admin.toml / config.json に焼き込む
449
+ const regen = regenerateAllConfigFiles(projectDir, config);
450
+ if (!regen.success)
451
+ logError(regen.error);
452
+ }
453
+ else {
454
+ // 非対話(--client-id 指定)など、既に Client ID 判明。コールバック URL を案内するのみ。
455
+ log(` OAuth コールバック URL(GitHub OAuth App に設定): ${callbackUrl}`);
456
+ }
457
+ log('');
458
+ // GITHUB_CLIENT_SECRET はワーカーが存在(deploy 済み)してからでないと投入できない。
459
+ const secret = config.githubClientSecret;
460
+ if (!options.skipCloudflare && secret) {
461
+ if (adminWorkerDeployed) {
462
+ const put = setWorkerSecretByName(config.adminWorkerName, 'GITHUB_CLIENT_SECRET', secret);
463
+ if (put.success) {
464
+ logSuccess('admin Worker に GITHUB_CLIENT_SECRET を設定しました');
465
+ // Client ID([vars])の反映のため admin Worker を再デプロイ(best-effort)
466
+ const redeploy = deployAdminWorker(projectDir);
467
+ if (redeploy.success)
468
+ logSuccess('admin Worker を再デプロイしました(OAuth 設定を反映)');
469
+ else
470
+ log(` ⚠ 再デプロイに失敗(${redeploy.error})。admin ブランチ push 時の Actions で反映されます。`);
471
+ }
472
+ else {
473
+ logError(put.error);
474
+ }
475
+ }
476
+ else {
477
+ log(' ⚠ admin Worker 未デプロイのため GITHUB_CLIENT_SECRET は未投入です。初回デプロイ後に設定してください:');
478
+ log(` npx wrangler secret put GITHUB_CLIENT_SECRET --name ${config.adminWorkerName}`);
479
+ }
480
+ }
481
+ }
305
482
  /**
306
483
  * commit 直前に git identity(user.name / user.email)を確認する。
307
484
  * 未設定の場合:
@@ -380,6 +557,54 @@ async function promptScheduledPublish() {
380
557
  return null;
381
558
  return { dispatchToken: res.dispatchToken };
382
559
  }
560
+ /**
561
+ * ファイル限定配信(任意)のセットアップ入力を集める。
562
+ * 「フォーム送信後にダウンロード URL を期限付きでメール配信」機能の受け皿。
563
+ * 対話モードのみ。スキップ/非対話なら null(=セットアップしない)。
564
+ *
565
+ * @param contactEnabled お問い合わせ機能を opt-in 済みか(DELIVERY 配線の可否)。
566
+ */
567
+ async function promptFileDelivery(contactEnabled) {
568
+ const isInteractive = process.stdin.isTTY === true;
569
+ if (!isInteractive)
570
+ return null;
571
+ log('📦 ファイル限定配信(任意・フォーム送信後にダウンロード URL を期限付きメール配信):');
572
+ log(' 専用のプライベート R2 バケット(<project>-downloads)と D1(frelio_downloads)を作成します。');
573
+ log(' ※ この機能はお問い合わせ機能(contact)と併用する前提です(フォーム送信を起点にトークン発行)。');
574
+ if (!contactEnabled) {
575
+ log(' ⚠ お問い合わせ機能が未 opt-in です。今セットアップしても、配信フォームを使うには後から contact も');
576
+ log(' セットアップし、DELIVERY Service Binding を配線する必要があります。');
577
+ }
578
+ const enable = await prompts({
579
+ type: 'confirm',
580
+ name: 'value',
581
+ message: 'ファイル限定配信ワーカーをセットアップしますか?(後からでも設定可)',
582
+ initial: false,
583
+ }, { onCancel: () => process.exit(0) });
584
+ if (!enable.value)
585
+ return null;
586
+ log(' このワーカーの公開ベース URL(PUBLIC_BASE_URL / CMS の downloadApiUrl と同じ値・末尾スラッシュ無し)。');
587
+ log(' 初回デプロイまで未確定なら空欄で Enter(後から wrangler.toml と基本設定で設定)。');
588
+ const res = await prompts([
589
+ {
590
+ type: 'text',
591
+ name: 'publicBaseUrl',
592
+ message: '公開ベース URL(任意, 例: https://frelio-file-delivery.<subdomain>.workers.dev):',
593
+ initial: '',
594
+ },
595
+ {
596
+ type: 'text',
597
+ name: 'tokenRetentionDays',
598
+ message: '失効/期限切れトークンの保持日数(Cron で掃除。0 で無効):',
599
+ initial: '30',
600
+ },
601
+ ], { onCancel: () => process.exit(0) });
602
+ return {
603
+ publicBaseUrl: res.publicBaseUrl || '',
604
+ tokenRetentionDays: res.tokenRetentionDays || '30',
605
+ wireContact: contactEnabled,
606
+ };
607
+ }
383
608
  async function promptContact(config) {
384
609
  const isInteractive = process.stdin.isTTY === true;
385
610
  if (!isInteractive)
@@ -536,10 +761,13 @@ async function promptConfig(options) {
536
761
  initial: '',
537
762
  },
538
763
  {
764
+ // Issue #261: 独自の staging ドメインは「終盤のオプショナル工程」。init では空が既定。
765
+ // productionUrl からの自動生成(staging-<hash>.<本番ホスト>)はやめる(NXDOMAIN 回避)。
766
+ // workers.dev のホストは init が admin Worker をデプロイして自動確定するため、ここでは尋ねない。
539
767
  type: options.stagingDomain !== undefined ? null : 'text',
540
768
  name: 'stagingDomain',
541
- message: 'ステージングのドメイン(推測困難なハッシュ付き推奨):',
542
- initial: (_prev, values) => generateStagingDomain((options.productionUrl || values.productionUrl) || ''),
769
+ message: 'ステージングの独自ドメイン(任意・通常は空。独自ドメインは後で set-domain で設定):',
770
+ initial: '',
543
771
  },
544
772
  {
545
773
  type: options.r2BucketName !== undefined ? null : 'text',
@@ -583,8 +811,15 @@ async function promptConfig(options) {
583
811
  const repoName = contentRepo.split('/')[1];
584
812
  const repoSlug = sanitizeCloudflareName(repoName);
585
813
  const stagingDomain = options.stagingDomain ?? response.stagingDomain ?? '';
586
- const previewUrl = stagingDomain ? `https://${stagingDomain}` : '';
814
+ // Issue #261: workers.dev のアカウント部は、--admin-host 指定があればそこから導く。
815
+ // 未指定なら init のデプロイ検出フェーズで確定する(ここでは空)。
816
+ const workersSubdomain = options.adminHost
817
+ ? deriveFromAdminHost(options.adminHost).workersSubdomain
818
+ : '';
587
819
  const { contentWorkerName, adminWorkerName } = buildWorkerNames(repoName, options.randomSuffix ?? true, { contentWorkerName: options.contentWorkerName, adminWorkerName: options.adminWorkerName });
820
+ // previewUrl は独自 staging ドメイン優先、無ければ workers.dev サブドメインから
821
+ // CI の preview-alias 形式(staging-<contentWorker>.<sub>.workers.dev)を導く。
822
+ const previewUrl = derivePreviewUrl({ stagingDomain, workersSubdomain, contentWorkerName });
588
823
  const r2BucketName = options.r2BucketName ?? response.r2BucketName ?? `${repoSlug}-files`;
589
824
  // 導出/指定した名前が Cloudflare の命名規則を満たすか早期に検証する(Cloudflare 呼び出し前)
590
825
  for (const [label, value] of [
@@ -608,6 +843,7 @@ async function promptConfig(options) {
608
843
  r2PublicUrl: options.r2PublicUrl ?? response.r2PublicUrl ?? '',
609
844
  contentWorkerName,
610
845
  adminWorkerName,
846
+ workersSubdomain,
611
847
  ownerUsername: options.ownerUsername ?? response.ownerUsername ?? '',
612
848
  stagingDomain,
613
849
  saveTimezone: '+09:00',
@@ -624,6 +860,7 @@ function buildConfigFromOptions(options) {
624
860
  siteTitle: options.siteTitle,
625
861
  productionUrl: options.productionUrl,
626
862
  stagingDomain: options.stagingDomain,
863
+ workersSubdomain: options.adminHost ? deriveFromAdminHost(options.adminHost).workersSubdomain : undefined,
627
864
  r2BucketName: options.r2BucketName,
628
865
  r2PublicUrl: options.r2PublicUrl,
629
866
  ownerUsername: options.ownerUsername,
@@ -648,15 +885,20 @@ function buildConfigFromOptions(options) {
648
885
  githubClientSecret: options.clientSecret,
649
886
  };
650
887
  }
651
- function getTotalSteps(options, withContact = false, withSchedule = false) {
652
- let steps = 3; // content structure (includes workflows), bundle, config files
888
+ function getTotalSteps(options, withContact = false, withSchedule = false, withFileDelivery = false, willDeployAdmin = false) {
889
+ let steps = 4; // content structure (includes workflows), bundle, config files, lockfile
653
890
  if (!options.skipGithub)
654
891
  steps += 4; // create repo, clone, git identity, commit/push
655
- if (!options.skipCloudflare)
656
- steps += 1;
892
+ if (!options.skipCloudflare) {
893
+ steps += 1; // R2 bucket 作成
894
+ if (willDeployAdmin)
895
+ steps += 1; // deploy-first(admin Worker 初回デプロイでホスト確定)
896
+ }
657
897
  if (withContact)
658
898
  steps += 1;
659
899
  if (withSchedule)
660
900
  steps += 1;
901
+ if (withFileDelivery)
902
+ steps += 1;
661
903
  return steps;
662
904
  }
@@ -10,6 +10,7 @@ type SetDomainOptions = {
10
10
  previewUrl?: string;
11
11
  stagingDomain?: string;
12
12
  r2PublicUrl?: string;
13
+ downloadApiUrl?: string;
13
14
  regenStagingHash?: boolean;
14
15
  };
15
16
  export declare function setDomainCommand(options: SetDomainOptions): Promise<void>;
@@ -5,11 +5,19 @@
5
5
  * 派生ファイル(wrangler.toml ×2 等)を一括再生成する薄いオーケストレーター。
6
6
  * core/domain の changeDomain を呼ぶだけで、新規ロジックは持たない。
7
7
  */
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
8
10
  import prompts from 'prompts';
9
11
  import { log, logSuccess, logError } from '../lib/shell.js';
10
12
  import { validateProductionUrl, validateR2PublicUrl } from '../lib/validators.js';
11
13
  import { readConfig } from '../core/config.js';
12
14
  import { changeDomain } from '../core/domain.js';
15
+ /** ファイル限定配信ワーカーが opt-in 済みか(config に downloadApiUrl があるか wrangler.toml が存在する) */
16
+ function isFileDeliveryOptedIn(projectDir, currentDownloadApiUrl) {
17
+ if (currentDownloadApiUrl)
18
+ return true;
19
+ return fs.existsSync(path.join(projectDir, 'workers', 'file-delivery', 'wrangler.toml'));
20
+ }
13
21
  export async function setDomainCommand(options) {
14
22
  log('');
15
23
  log('🌐 ドメイン / URL の変更');
@@ -26,10 +34,12 @@ export async function setDomainCommand(options) {
26
34
  process.exit(1);
27
35
  }
28
36
  const current = configResult.data.config;
37
+ const downloadOptedIn = isFileDeliveryOptedIn(projectDir, current.downloadApiUrl ?? '');
29
38
  const hasFlags = options.productionUrl !== undefined ||
30
39
  options.previewUrl !== undefined ||
31
40
  options.stagingDomain !== undefined ||
32
- options.r2PublicUrl !== undefined;
41
+ options.r2PublicUrl !== undefined ||
42
+ options.downloadApiUrl !== undefined;
33
43
  // フラグ検証(指定されたもののみ)
34
44
  if (options.productionUrl !== undefined) {
35
45
  const c = validateProductionUrl(options.productionUrl);
@@ -45,6 +55,13 @@ export async function setDomainCommand(options) {
45
55
  process.exit(1);
46
56
  }
47
57
  }
58
+ if (options.downloadApiUrl !== undefined) {
59
+ const c = validateProductionUrl(options.downloadApiUrl);
60
+ if (c !== true) {
61
+ logError(`--download-api-url: ${c}`);
62
+ process.exit(1);
63
+ }
64
+ }
48
65
  const isInteractive = process.stdin.isTTY === true;
49
66
  const change = {};
50
67
  if (hasFlags) {
@@ -56,6 +73,8 @@ export async function setDomainCommand(options) {
56
73
  change.stagingDomain = options.stagingDomain;
57
74
  if (options.r2PublicUrl !== undefined)
58
75
  change.r2PublicUrl = options.r2PublicUrl;
76
+ if (options.downloadApiUrl !== undefined)
77
+ change.downloadApiUrl = options.downloadApiUrl;
59
78
  if (options.regenStagingHash)
60
79
  change.regenStagingHash = true;
61
80
  }
@@ -69,6 +88,9 @@ export async function setDomainCommand(options) {
69
88
  log(` 本番 URL : ${current.productionUrl || '(未設定)'}`);
70
89
  log(` プレビュー URL: ${current.previewUrl || '(未設定)'}`);
71
90
  log(` R2 公開 URL : ${current.r2PublicUrl || '(未設定)'}`);
91
+ if (downloadOptedIn) {
92
+ log(` 配信ワーカー URL: ${current.downloadApiUrl || '(未設定)'}`);
93
+ }
72
94
  log('');
73
95
  const res = await prompts([
74
96
  {
@@ -85,6 +107,14 @@ export async function setDomainCommand(options) {
85
107
  initial: current.r2PublicUrl || '',
86
108
  validate: (v) => validateR2PublicUrl(v),
87
109
  },
110
+ // ファイル限定配信ワーカーが opt-in 済みのときだけ聞く(PUBLIC_BASE_URL = downloadApiUrl)
111
+ {
112
+ type: downloadOptedIn ? 'text' : null,
113
+ name: 'downloadApiUrl',
114
+ message: '新しいファイル配信ワーカー URL(PUBLIC_BASE_URL と同値・変更しない場合は空欄):',
115
+ initial: current.downloadApiUrl || '',
116
+ validate: (v) => validateProductionUrl(v),
117
+ },
88
118
  {
89
119
  type: (_, values) => values.productionUrl && values.productionUrl !== current.productionUrl
90
120
  ? 'confirm'
@@ -101,6 +131,9 @@ export async function setDomainCommand(options) {
101
131
  if (res.r2PublicUrl && res.r2PublicUrl !== current.r2PublicUrl) {
102
132
  change.r2PublicUrl = res.r2PublicUrl;
103
133
  }
134
+ if (res.downloadApiUrl && res.downloadApiUrl !== current.downloadApiUrl) {
135
+ change.downloadApiUrl = res.downloadApiUrl;
136
+ }
104
137
  if (res.regenStagingHash)
105
138
  change.regenStagingHash = true;
106
139
  }
@@ -121,6 +154,9 @@ export async function setDomainCommand(options) {
121
154
  log(` 本番 URL : ${config.productionUrl || '(未設定)'}`);
122
155
  log(` プレビュー URL: ${config.previewUrl || '(未設定)'}`);
123
156
  log(` R2 公開 URL : ${config.r2PublicUrl || '(未設定)'}`);
157
+ if (config.downloadApiUrl) {
158
+ log(` 配信ワーカー URL: ${config.downloadApiUrl}`);
159
+ }
124
160
  log('');
125
161
  log(' 再生成したファイル:');
126
162
  for (const p of regeneratedPaths) {
@@ -135,7 +171,16 @@ export async function setDomainCommand(options) {
135
171
  log(' 4. GitHub OAuth App の Homepage / Callback URL を新ドメインに更新');
136
172
  log(' 5. file-upload Worker を別運用している場合は再デプロイ:');
137
173
  log(' cd workers/file-upload && npx wrangler deploy');
138
- log(' 6. 本番反映は CMS の「直接デプロイ」フローで実行');
139
- log(' 7. 必要に応じて旧ドメインからのリダイレクトと Cloudflare Access を再設定');
174
+ if (change.downloadApiUrl !== undefined) {
175
+ log(' 6. ファイル限定配信 Worker を再デプロイ(PUBLIC_BASE_URL 更新を反映):');
176
+ log(' cd workers/file-delivery && npx wrangler deploy');
177
+ log(' ※ 独自ドメイン化した場合は Cloudflare Dashboard で該当 Worker の Routes / カスタムドメインも合わせる');
178
+ log(' 7. 本番反映は CMS の「直接デプロイ」フローで実行');
179
+ log(' 8. 必要に応じて旧ドメインからのリダイレクトと Cloudflare Access を再設定');
180
+ }
181
+ else {
182
+ log(' 6. 本番反映は CMS の「直接デプロイ」フローで実行');
183
+ log(' 7. 必要に応じて旧ドメインからのリダイレクトと Cloudflare Access を再設定');
184
+ }
140
185
  log('');
141
186
  }