@c-time/frelio-cli 2.2.1 → 2.4.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 CHANGED
@@ -521,9 +521,50 @@ CLI 完了後、Cloudflare Dashboard での設定が必要。
521
521
  ワークフローが `wrangler deploy` / `versions upload` を実行するため、content-repo の
522
522
  **Settings → Secrets and variables → Actions** に以下を設定する:
523
523
 
524
- - `CLOUDFLARE_API_TOKEN` — Workers のデプロイ権限を持つ API トークン
524
+ - `CLOUDFLARE_API_TOKEN` — Workers のデプロイ権限を持つ API トークン(種別と必要権限は下記)
525
525
  - `CLOUDFLARE_ACCOUNT_ID` — Cloudflare アカウント ID
526
526
 
527
+ #### 推奨: 対象アカウント配下の「アカウント API トークン」を使う
528
+
529
+ **ユーザー API トークン(プロフィール → API トークン)ではなく、対象アカウント配下の
530
+ 「アカウント API トークン」を推奨する。** 顧客ごとに Cloudflare アカウントを分ける運用では特に重要。
531
+
532
+ - 作成場所: ダッシュボード → 対象アカウント →「アカウントの管理」→ **API トークン**
533
+ (プロフィール →「API トークン」のユーザートークンとは**別物**)
534
+ - 対象アカウント配下でしか作れないため、**他の顧客アカウントを巻き込む余地が構造的に無い**
535
+ - 人に紐づかないので、アカウント引き渡し・メンバー離脱で壊れない
536
+
537
+ 一方、ユーザー API トークンは作成時に「アカウントリソース」で複数アカウントを選択でき、
538
+ 「すべてのアカウント」のまま作ると 1 顧客の CI に全顧客アカウントへの Workers 書き込み権限が載る。
539
+ また作成者に紐づくため、作成者がメンバーから外れると CI が理由不明のまま壊れる。
540
+ どうしてもユーザートークンを使う場合は「アカウントリソース」を**対象アカウント 1 つに限定**すること。
541
+
542
+ #### 必要権限(アカウントスコープ 3 行で足りる)
543
+
544
+ 通常運用(管理画面デプロイ / staging プレビュー)に必要なのは以下の 3 権限のみ。
545
+ 実地検証済み(`wrangler-action@v4` の `deploy` / `versions upload --preview-alias` がいずれも成功)。
546
+
547
+ | スコープ | 項目 | レベル | 用途 |
548
+ |---|---|---|---|
549
+ | アカウント | Workers スクリプト | 編集 | `wrangler deploy` / `versions upload --preview-alias` |
550
+ | アカウント | Workers R2 ストレージ | 編集 | `[[r2_buckets]]` バインディング |
551
+ | アカウント | アカウント設定 | 読み取り | アカウント情報の解決 |
552
+
553
+ 任意機能・構成に応じて追加する権限:
554
+
555
+ | スコープ | 項目 | レベル | いつ必要か |
556
+ |---|---|---|---|
557
+ | アカウント | D1 | 編集 | contact ワーカー(D1)を使う場合 |
558
+ | ゾーン | Workers ルート | 編集 | 独自ドメインへ Worker を割り当てる場合(DNS を Cloudflare 管理下に置いた後) |
559
+
560
+ **注意点:**
561
+
562
+ - アカウント API トークンには **User スコープの権限(`User → Memberships: Read` 等)を含められない**。
563
+ Cloudflare の「Cloudflare Workers を編集する」テンプレートはこれを含むため、そのままでは使いにくい。
564
+ → カスタムトークンで上記 3 行を付与するのが確実。
565
+ - ワークフローは `wrangler-action` に `accountId` を明示的に渡しているため、アカウント一覧の解決が不要で、
566
+ `Memberships: Read` が無くても実害はない(検証済み)。
567
+
527
568
  ### 2. 初回デプロイ(workers.dev サブドメインの登録)
528
569
 
529
570
  `admin` ブランチへ push すると `deploy-admin.yml` が管理画面 Worker をデプロイする。初回デプロイで
@@ -18,6 +18,9 @@ type InitOptions = {
18
18
  clientSecret?: string;
19
19
  /** Worker 名のランダム hex サフィックス(Issue #138)。既定 true、--no-random-suffix で false。 */
20
20
  randomSuffix?: boolean;
21
+ /** Worker 名の明示指定(Issue #216)。未指定ならリポジトリ名から導出する。 */
22
+ contentWorkerName?: string;
23
+ adminWorkerName?: string;
21
24
  };
22
25
  export declare function initCommand(options: InitOptions): Promise<void>;
23
26
  export {};
@@ -7,20 +7,21 @@
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';
10
+ import { log, logStep, logSuccess, logError, logWarning } from '../lib/shell.js';
11
11
  import { generateStagingDomain, buildWorkerNames, } from '../lib/templates.js';
12
12
  import { buildResourceLinks } from '../lib/resource-links.js';
13
- import { validateContentRepo, validateR2PublicUrl, validateRequired } from '../lib/validators.js';
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
18
  import { setupCloudflareResources } from '../core/cloudflare.js';
19
19
  import { setupContactWorker } from '../core/contact.js';
20
+ import { setupScheduledPublishWorker } from '../core/scheduled-publish.js';
20
21
  import { createFullContentStructure } from '../core/content-structure.js';
21
22
  import { regenerateAllConfigFiles } from '../core/file-generators.js';
22
23
  import { installBundle } from '../core/bundle.js';
23
- import { initialCommitAndBranches, getGitIdentity, setGitIdentity, } from '../core/git-operations.js';
24
+ import { initialCommitAndBranches, generateLockfile, getGitIdentity, setGitIdentity, } from '../core/git-operations.js';
24
25
  export async function initCommand(options) {
25
26
  log('');
26
27
  log('🚀 Frelio CMS プロジェクトセットアップ');
@@ -55,6 +56,9 @@ export async function initCommand(options) {
55
56
  // ── お問い合わせ機能(任意)──
56
57
  const contactInput = options.skipCloudflare ? null : await promptContact(config);
57
58
  log('');
59
+ // ── 予約反映(任意)──
60
+ const scheduleInput = options.skipCloudflare ? null : await promptScheduledPublish();
61
+ log('');
58
62
  // ── OAuth App 案内 ──
59
63
  log('🔑 GitHub OAuth App:');
60
64
  if (!config.githubClientId) {
@@ -96,7 +100,7 @@ export async function initCommand(options) {
96
100
  }
97
101
  log('');
98
102
  // ── セットアップ実行 ──
99
- const totalSteps = getTotalSteps(options, !!contactInput);
103
+ const totalSteps = getTotalSteps(options, !!contactInput, !!scheduleInput);
100
104
  let step = 0;
101
105
  // GitHub リポジトリ作成
102
106
  if (!options.skipGithub) {
@@ -167,6 +171,21 @@ export async function initCommand(options) {
167
171
  logError(configResult.error);
168
172
  process.exit(1);
169
173
  }
174
+ // package-lock.json 生成(初回コミットに含める)
175
+ // init は npm install を実行しないため、放置するとロックファイルが無いまま push され、
176
+ // admin ブランチ初回 push の deploy-admin(setup-node cache:'npm')や
177
+ // build-staging / promote-production(npm ci)が必ず1回失敗する。ここで生成しておくと
178
+ // 後続の初回コミット(git add -A)に含まれる。失敗は致命ではないので警告に留めて続行。
179
+ step++;
180
+ logStep(step, totalSteps, 'package-lock.json 生成...');
181
+ const lockResult = generateLockfile(projectDir);
182
+ if (lockResult.success) {
183
+ logSuccess('package-lock.json 生成完了');
184
+ }
185
+ else {
186
+ log(` ⚠ package-lock.json を生成できませんでした(${lockResult.error})。`);
187
+ log(' デプロイ前に `npm install` を実行し、package-lock.json をコミットしてください。');
188
+ }
170
189
  // Cloudflare セットアップ
171
190
  if (!options.skipCloudflare) {
172
191
  step++;
@@ -222,6 +241,22 @@ export async function initCommand(options) {
222
241
  logError(contactResult.error);
223
242
  }
224
243
  }
244
+ // 予約反映ワーカー(任意)
245
+ if (scheduleInput) {
246
+ step++;
247
+ logStep(step, totalSteps, '予約反映ワーカーのセットアップ(wrangler.toml・シークレット)...');
248
+ const scheduleResult = setupScheduledPublishWorker(projectDir, config, scheduleInput);
249
+ if (scheduleResult.success) {
250
+ if (!scheduleResult.data.secret.success) {
251
+ log(' ⚠ GITHUB_DISPATCH_TOKEN の投入は初回デプロイ後に再実行してください:');
252
+ log(' cd workers/scheduled-publish && npx wrangler secret put GITHUB_DISPATCH_TOKEN');
253
+ }
254
+ logSuccess('予約反映ワーカーのセットアップ完了(deploy は workers/scheduled-publish で別途 → 基本設定で scheduleApiUrl を設定)');
255
+ }
256
+ else {
257
+ logError(scheduleResult.error);
258
+ }
259
+ }
225
260
  // git identity 確認(commit 直前 — 未設定だとデフォルト値で commit author が埋まるのを防ぐ)
226
261
  if (!options.skipGithub) {
227
262
  step++;
@@ -249,6 +284,29 @@ export async function initCommand(options) {
249
284
  // wrangler versions upload --preview-alias で生成)を案内する。
250
285
  log(` プレビュー: ${config.previewUrl || `https://staging-${config.contentWorkerName}.<your-subdomain>.workers.dev`}`);
251
286
  log('');
287
+ // 公開に必須だが空のまま完了しうる値を警告(開発は動くが本番公開が成立しない)。
288
+ // 特に R2 公開URL はバケット作成後にしか確定しないため未入力で終わりやすい。
289
+ const publishBlockers = [];
290
+ if (!config.r2PublicUrl) {
291
+ publishBlockers.push({
292
+ label: 'R2 公開URL',
293
+ note: '未設定だと画像・ファイルが表示されません(R2 の r2.dev URL かカスタムドメインを設定)',
294
+ });
295
+ }
296
+ if (!config.productionUrl) {
297
+ publishBlockers.push({
298
+ label: '本番URL',
299
+ note: '未設定だと sitemap・OGP・正規URL 等の絶対URLが生成できません',
300
+ });
301
+ }
302
+ if (publishBlockers.length > 0) {
303
+ logWarning('公開に必要な設定が未入力のまま完了しました(開発・プレビューは動作しますが、本番公開はできません):');
304
+ for (const b of publishBlockers) {
305
+ logWarning(` - ${b.label}: ${b.note}`);
306
+ }
307
+ log(' → 管理画面の「基本設定」で設定し、「セットアップ検証」で確認してください。');
308
+ log('');
309
+ }
252
310
  // 作成したリソースへのリンク(確認・設定変更の導線)
253
311
  const resourceSections = buildResourceLinks(config, {
254
312
  github: !options.skipGithub,
@@ -266,6 +324,9 @@ export async function initCommand(options) {
266
324
  }
267
325
  log(' 残りの手動作業:');
268
326
  log(' 1. GitHub Actions シークレットを設定: CLOUDFLARE_API_TOKEN / CLOUDFLARE_ACCOUNT_ID');
327
+ log(' ※ トークンは対象アカウント配下の「アカウント API トークン」推奨(他顧客アカウントを巻き込まない)');
328
+ log(' 必要権限(アカウントスコープ3行): Workers スクリプト=編集 / Workers R2 ストレージ=編集 / アカウント設定=読み取り');
329
+ log(' 詳細: packages/cli/README.md「GitHub Actions シークレットの設定」');
269
330
  log(' 2. admin ブランチへ push して管理画面 Worker を初回デプロイ(workers.dev サブドメインが登録される)');
270
331
  log(' 3. staging ブランチへ push してコンテンツのプレビュー、main で本番デプロイ');
271
332
  if (config.stagingDomain) {
@@ -273,6 +334,11 @@ export async function initCommand(options) {
273
334
  }
274
335
  log(` ${config.stagingDomain ? '5' : '4'}. ステージングのアクセス制限を設定(Cloudflare Access 推奨)`);
275
336
  log('');
337
+ log(' 任意機能:');
338
+ log(' - お問い合わせフォーム: workers/contact/README.md(init で未設定なら後から)');
339
+ log(' - 予約反映(時刻ベースの自動公開/非公開): workers/scheduled-publish/README.md を参照して');
340
+ log(' ワーカーをデプロイ(PAT: Actions=RW / Contents=RO)→ 管理画面の「基本設定」→「予約反映 API URL」に設定');
341
+ log('');
276
342
  }
277
343
  // ---------------------------------------------------------------------------
278
344
  // UI helpers (prompts — commands 層に閉じる)
@@ -329,6 +395,32 @@ async function ensureGitIdentity(projectDir, ownerUsername) {
329
395
  * お問い合わせ機能(任意)のセットアップ入力を集める。
330
396
  * 対話モードのみ。スキップ/非対話なら null(=セットアップしない)。
331
397
  */
398
+ async function promptScheduledPublish() {
399
+ const isInteractive = process.stdin.isTTY === true;
400
+ if (!isInteractive)
401
+ return null;
402
+ log('⏰ 予約反映(任意・時刻ベースの自動公開/非公開):');
403
+ const enable = await prompts({
404
+ type: 'confirm',
405
+ name: 'value',
406
+ message: '予約反映ワーカーをセットアップしますか?(後からでも設定可)',
407
+ initial: false,
408
+ }, { onCancel: () => process.exit(0) });
409
+ if (!enable.value)
410
+ return null;
411
+ log(' 発火用の fine-grained PAT が必要です(対象 repo に Actions: Read and write + Contents: Read-only)。');
412
+ log(' → https://github.com/settings/tokens?type=beta');
413
+ log(' ※ 組織リポジトリは無期限にできません(最長1年)。期限切れで発火が止まるため更新運用に注意。');
414
+ const res = await prompts({
415
+ type: 'password',
416
+ name: 'dispatchToken',
417
+ message: '発火用 PAT(GITHUB_DISPATCH_TOKEN):',
418
+ validate: (v) => validateRequired(v, 'PAT'),
419
+ }, { onCancel: () => process.exit(0) });
420
+ if (!res.dispatchToken)
421
+ return null;
422
+ return { dispatchToken: res.dispatchToken };
423
+ }
332
424
  async function promptContact(config) {
333
425
  const isInteractive = process.stdin.isTTY === true;
334
426
  if (!isInteractive)
@@ -496,7 +588,7 @@ async function promptConfig(options) {
496
588
  message: 'R2 バケット名:',
497
589
  initial: (_prev, values) => {
498
590
  const repo = (options.contentRepo || values.contentRepo)?.split('/')[1] || 'site';
499
- return `${repo}-files`;
591
+ return `${sanitizeCloudflareName(repo)}-files`;
500
592
  },
501
593
  },
502
594
  {
@@ -530,16 +622,30 @@ async function promptConfig(options) {
530
622
  if (!contentRepo)
531
623
  return null;
532
624
  const repoName = contentRepo.split('/')[1];
625
+ const repoSlug = sanitizeCloudflareName(repoName);
533
626
  const stagingDomain = options.stagingDomain ?? response.stagingDomain ?? '';
534
627
  const previewUrl = stagingDomain ? `https://${stagingDomain}` : '';
535
- const { contentWorkerName, adminWorkerName } = buildWorkerNames(repoName, options.randomSuffix ?? true);
628
+ const { contentWorkerName, adminWorkerName } = buildWorkerNames(repoName, options.randomSuffix ?? true, { contentWorkerName: options.contentWorkerName, adminWorkerName: options.adminWorkerName });
629
+ const r2BucketName = options.r2BucketName ?? response.r2BucketName ?? `${repoSlug}-files`;
630
+ // 導出/指定した名前が Cloudflare の命名規則を満たすか早期に検証する(Cloudflare 呼び出し前)
631
+ for (const [label, value] of [
632
+ ['contentWorkerName', contentWorkerName],
633
+ ['adminWorkerName', adminWorkerName],
634
+ ['r2BucketName', r2BucketName],
635
+ ]) {
636
+ const check = validateCloudflareName(value);
637
+ if (check !== true) {
638
+ logError(`${label} ("${value}"): ${check}`);
639
+ process.exit(1);
640
+ }
641
+ }
536
642
  const config = {
537
643
  contentRepo,
538
644
  githubClientId: options.clientId || '',
539
645
  siteTitle: options.siteTitle ?? response.siteTitle ?? '',
540
646
  productionUrl: options.productionUrl ?? response.productionUrl ?? '',
541
647
  previewUrl,
542
- r2BucketName: options.r2BucketName ?? response.r2BucketName ?? `${repoName}-files`,
648
+ r2BucketName,
543
649
  r2PublicUrl: options.r2PublicUrl ?? response.r2PublicUrl ?? '',
544
650
  contentWorkerName,
545
651
  adminWorkerName,
@@ -563,6 +669,8 @@ function buildConfigFromOptions(options) {
563
669
  r2PublicUrl: options.r2PublicUrl,
564
670
  ownerUsername: options.ownerUsername,
565
671
  randomSuffix: options.randomSuffix,
672
+ contentWorkerName: options.contentWorkerName,
673
+ adminWorkerName: options.adminWorkerName,
566
674
  });
567
675
  if (!result.success) {
568
676
  logError(result.error);
@@ -581,13 +689,15 @@ function buildConfigFromOptions(options) {
581
689
  githubClientSecret: options.clientSecret,
582
690
  };
583
691
  }
584
- function getTotalSteps(options, withContact = false) {
585
- let steps = 3; // content structure (includes workflows), bundle, config files
692
+ function getTotalSteps(options, withContact = false, withSchedule = false) {
693
+ let steps = 4; // content structure (includes workflows), bundle, config files, lockfile
586
694
  if (!options.skipGithub)
587
695
  steps += 4; // create repo, clone, git identity, commit/push
588
696
  if (!options.skipCloudflare)
589
697
  steps += 1;
590
698
  if (withContact)
591
699
  steps += 1;
700
+ if (withSchedule)
701
+ steps += 1;
592
702
  return steps;
593
703
  }
@@ -8,7 +8,7 @@ import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { ok, okVoid, fail, } from './types.js';
10
10
  import { generateStagingDomain, buildWorkerNames } from '../lib/templates.js';
11
- import { validateContentRepo, validateR2PublicUrl, } from '../lib/validators.js';
11
+ import { validateContentRepo, validateR2PublicUrl, sanitizeCloudflareName, validateCloudflareName, } from '../lib/validators.js';
12
12
  /** read-only フィールド(updateConfig で上書き不可) */
13
13
  const READ_ONLY_FIELDS = ['contentRepo', 'githubClientId'];
14
14
  /** config.json の相対パス */
@@ -121,16 +121,30 @@ export function buildConfig(params) {
121
121
  }
122
122
  }
123
123
  const repoName = params.contentRepo.split('/')[1];
124
+ // Cloudflare-safe な slug(アンダースコア/大文字等を除去)を R2・Worker 名の基底にする(Issue #216)
125
+ const repoSlug = sanitizeCloudflareName(repoName);
124
126
  const stagingDomain = params.stagingDomain ?? generateStagingDomain(params.productionUrl || '');
125
127
  const previewUrl = stagingDomain ? `https://${stagingDomain}` : '';
126
- const { contentWorkerName, adminWorkerName } = buildWorkerNames(repoName, params.randomSuffix ?? true);
128
+ const { contentWorkerName, adminWorkerName } = buildWorkerNames(repoName, params.randomSuffix ?? true, { contentWorkerName: params.contentWorkerName, adminWorkerName: params.adminWorkerName });
129
+ const r2BucketName = params.r2BucketName ?? `${repoSlug}-files`;
130
+ // 導出/指定した名前が Cloudflare の命名規則を満たすか早期に検証する(Cloudflare API 呼び出し前)
131
+ for (const [label, value] of [
132
+ ['contentWorkerName', contentWorkerName],
133
+ ['adminWorkerName', adminWorkerName],
134
+ ['r2BucketName', r2BucketName],
135
+ ]) {
136
+ const check = validateCloudflareName(value);
137
+ if (check !== true) {
138
+ return fail(`${label} ("${value}"): ${check}`, 'VALIDATION_ERROR');
139
+ }
140
+ }
127
141
  const config = {
128
142
  contentRepo: params.contentRepo,
129
143
  githubClientId: params.githubClientId || '',
130
144
  siteTitle: params.siteTitle || '',
131
145
  productionUrl: params.productionUrl || '',
132
146
  previewUrl,
133
- r2BucketName: params.r2BucketName ?? `${repoName}-files`,
147
+ r2BucketName,
134
148
  r2PublicUrl: params.r2PublicUrl || '',
135
149
  contentWorkerName,
136
150
  adminWorkerName,
@@ -6,6 +6,22 @@ export declare function initialCommitAndBranches(projectDir: string, contentRepo
6
6
  branches: string[];
7
7
  defaultBranch: string;
8
8
  }>;
9
+ /**
10
+ * package-lock.json を生成する(`npm install --package-lock-only`)。
11
+ *
12
+ * init は package.json を配置するが `npm install` を実行しないため、そのままでは
13
+ * package-lock.json が生成されず初回コミットに含まれない。GitHub Actions の各デプロイ
14
+ * ワークフローはロックファイルの存在を前提とするため、これが無いと **admin ブランチへの
15
+ * 初回 push で必ず1回失敗**していた(`deploy-admin` は setup-node の `cache:'npm'` が
16
+ * ロックファイルを要求し、`build-staging` / `promote-production` / `scheduled-publish` /
17
+ * `_deploy` は `npm ci` がロックファイルを要求する)。
18
+ *
19
+ * ここで生成しておくと {@link initialCommitAndBranches} の `git add -A` が拾い、初回コミット
20
+ * に含めて push できる。`--package-lock-only` なので node_modules は作らず軽量。ネットワーク
21
+ * 不通等で失敗しても後から `npm install` で生成できるため best-effort とし、呼び出し側は
22
+ * 警告に留めて続行する。既にロックファイルがあれば何もしない。
23
+ */
24
+ export declare function generateLockfile(projectDir: string): OperationResult<void>;
9
25
  /**
10
26
  * commit author に使われる git identity を取得する。
11
27
  * projectDir 内で実行するため、git が commit 時に解決する値(local→global→system)と一致する。
@@ -30,6 +30,39 @@ export function initialCommitAndBranches(projectDir, contentRepo) {
30
30
  }
31
31
  }
32
32
  // ---------------------------------------------------------------------------
33
+ // Lockfile generation (pre-commit)
34
+ // ---------------------------------------------------------------------------
35
+ /**
36
+ * package-lock.json を生成する(`npm install --package-lock-only`)。
37
+ *
38
+ * init は package.json を配置するが `npm install` を実行しないため、そのままでは
39
+ * package-lock.json が生成されず初回コミットに含まれない。GitHub Actions の各デプロイ
40
+ * ワークフローはロックファイルの存在を前提とするため、これが無いと **admin ブランチへの
41
+ * 初回 push で必ず1回失敗**していた(`deploy-admin` は setup-node の `cache:'npm'` が
42
+ * ロックファイルを要求し、`build-staging` / `promote-production` / `scheduled-publish` /
43
+ * `_deploy` は `npm ci` がロックファイルを要求する)。
44
+ *
45
+ * ここで生成しておくと {@link initialCommitAndBranches} の `git add -A` が拾い、初回コミット
46
+ * に含めて push できる。`--package-lock-only` なので node_modules は作らず軽量。ネットワーク
47
+ * 不通等で失敗しても後から `npm install` で生成できるため best-effort とし、呼び出し側は
48
+ * 警告に留めて続行する。既にロックファイルがあれば何もしない。
49
+ */
50
+ export function generateLockfile(projectDir) {
51
+ if (!fs.existsSync(`${projectDir}/package.json`)) {
52
+ return fail('package.json が見つかりません。', 'NOT_FOUND');
53
+ }
54
+ if (fs.existsSync(`${projectDir}/package-lock.json`)) {
55
+ return okVoid();
56
+ }
57
+ try {
58
+ exec('npm install --package-lock-only --ignore-scripts', { cwd: projectDir, silent: true });
59
+ return okVoid();
60
+ }
61
+ catch (e) {
62
+ return fail(`package-lock.json 生成失敗: ${e.message}`, 'EXEC_FAILED');
63
+ }
64
+ }
65
+ // ---------------------------------------------------------------------------
33
66
  // Git identity (user.name / user.email)
34
67
  // ---------------------------------------------------------------------------
35
68
  /**
@@ -18,4 +18,4 @@ export { createFullContentStructure } from './content-structure.js';
18
18
  export { scaffoldFromTemplate } from './template-scaffold.js';
19
19
  export { generateAndWriteConfigJson, generateAndWriteWorkerWranglerToml, generateAndWriteContentWorkerSiteMode, generateAndWriteContentWorkerWranglerToml, generateAndWriteAdminWorkerWranglerToml, regenerateAllConfigFiles, } from './file-generators.js';
20
20
  export { installBundle, updateBundle, getBundleVersion } from './bundle.js';
21
- export { initialCommitAndBranches, createBranch, checkWorkflowBranchCoverage, } from './git-operations.js';
21
+ export { initialCommitAndBranches, generateLockfile, createBranch, checkWorkflowBranchCoverage, } from './git-operations.js';
@@ -25,4 +25,4 @@ export { generateAndWriteConfigJson, generateAndWriteWorkerWranglerToml, generat
25
25
  // Bundle
26
26
  export { installBundle, updateBundle, getBundleVersion } from './bundle.js';
27
27
  // Git operations
28
- export { initialCommitAndBranches, createBranch, checkWorkflowBranchCoverage, } from './git-operations.js';
28
+ export { initialCommitAndBranches, generateLockfile, createBranch, checkWorkflowBranchCoverage, } from './git-operations.js';
@@ -0,0 +1,22 @@
1
+ /**
2
+ * core/scheduled-publish — 予約反映ワーカー(workers/scheduled-publish)のセットアップ
3
+ *
4
+ * 任意機能。wrangler.toml 生成 → 発火用 PAT(GITHUB_DISPATCH_TOKEN)を secret 投入。
5
+ * D1 は不要。wrangler.toml は CONTENT_REPO 等ユーザー設定を含むため init 時に一度だけ生成し、
6
+ * update では上書きしない(template-refresh の PROTECTED_CONFIG)。
7
+ *
8
+ * デプロイ(`wrangler deploy`)と CMS の `scheduleApiUrl` 設定は、ワーカー URL が確定してから
9
+ * ユーザーが行う(contact ワーカーと同じ方針)。secret 投入は初回デプロイ前だと失敗しうるため、
10
+ * 失敗は致命的とせず案内に留める。
11
+ */
12
+ import { type ProjectConfig, type OperationResult } from './types.js';
13
+ export type ScheduledPublishSetupInput = {
14
+ /** 発火用 PAT(fine-grained: Actions:write + Contents:read、secret) */
15
+ dispatchToken: string;
16
+ };
17
+ export type ScheduledPublishSetupResult = {
18
+ /** GITHUB_DISPATCH_TOKEN 投入結果(初回デプロイ前は失敗しうる) */
19
+ secret: OperationResult;
20
+ };
21
+ /** 予約反映ワーカーをセットアップする(wrangler.toml 生成+secret 投入) */
22
+ export declare function setupScheduledPublishWorker(projectDir: string, config: ProjectConfig, input: ScheduledPublishSetupInput): OperationResult<ScheduledPublishSetupResult>;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * core/scheduled-publish — 予約反映ワーカー(workers/scheduled-publish)のセットアップ
3
+ *
4
+ * 任意機能。wrangler.toml 生成 → 発火用 PAT(GITHUB_DISPATCH_TOKEN)を secret 投入。
5
+ * D1 は不要。wrangler.toml は CONTENT_REPO 等ユーザー設定を含むため init 時に一度だけ生成し、
6
+ * update では上書きしない(template-refresh の PROTECTED_CONFIG)。
7
+ *
8
+ * デプロイ(`wrangler deploy`)と CMS の `scheduleApiUrl` 設定は、ワーカー URL が確定してから
9
+ * ユーザーが行う(contact ワーカーと同じ方針)。secret 投入は初回デプロイ前だと失敗しうるため、
10
+ * 失敗は致命的とせず案内に留める。
11
+ */
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { ok, fail } from './types.js';
15
+ import { setWorkerSecret } from './cloudflare.js';
16
+ import { generateScheduledPublishWranglerToml } from '../lib/templates.js';
17
+ const WORKER_SUBDIR = 'workers/scheduled-publish';
18
+ /** 予約反映ワーカーをセットアップする(wrangler.toml 生成+secret 投入) */
19
+ export function setupScheduledPublishWorker(projectDir, config, input) {
20
+ const workerDir = path.join(projectDir, WORKER_SUBDIR);
21
+ if (!fs.existsSync(workerDir)) {
22
+ return fail(`予約反映ワーカーが見つかりません(${WORKER_SUBDIR})。バンドル展開(frelio-cli update)を先に行ってください。`, 'NOT_FOUND');
23
+ }
24
+ // 1. wrangler.toml 生成(CONTENT_REPO / ALLOWED_ORIGINS 等を埋め込む)
25
+ const toml = generateScheduledPublishWranglerToml(config);
26
+ fs.writeFileSync(path.join(workerDir, 'wrangler.toml'), toml, 'utf-8');
27
+ // 2. 発火用 PAT を secret 投入(初回デプロイ前は失敗しうる=致命的ではない)
28
+ const secret = setWorkerSecret('GITHUB_DISPATCH_TOKEN', input.dispatchToken, workerDir);
29
+ return ok({ secret });
30
+ }
@@ -52,6 +52,8 @@ export const PROTECTED_CONFIG = new Set([
52
52
  'workers/file-upload/wrangler.toml',
53
53
  // database_id を含み init 時に一度だけ生成するため update では保持する
54
54
  'workers/contact/wrangler.toml',
55
+ // 予約反映ワーカー。CONTENT_REPO / ALLOWED_ORIGINS 等のユーザー設定を含むため update では保持する
56
+ 'workers/scheduled-publish/wrangler.toml',
55
57
  ]);
56
58
  function toPosix(p) {
57
59
  return p.split(path.sep).join('/');
@@ -51,4 +51,10 @@ export type BuildConfigParams = {
51
51
  * 既定(未指定)は true。false で従来の単純名(`<repo>` / `<repo>-admin`)を使う。
52
52
  */
53
53
  randomSuffix?: boolean;
54
+ /**
55
+ * Worker 名の明示指定(Issue #216)。未指定ならリポジトリ名から導出する。
56
+ * サニタイズで別リポジトリ名と衝突する場合の手動制御に使う。
57
+ */
58
+ contentWorkerName?: string;
59
+ adminWorkerName?: string;
54
60
  };
package/dist/index.js CHANGED
@@ -29,6 +29,8 @@ program
29
29
  .option('--production-url <url>', 'Production URL')
30
30
  .option('--staging-domain <domain>', 'Staging domain')
31
31
  .option('--r2-bucket-name <name>', 'R2 bucket name')
32
+ .option('--content-worker-name <name>', 'コンテンツ配信 Worker 名を明示指定(未指定ならリポジトリ名から導出。サニタイズで別リポジトリ名と衝突する場合の手動制御に使う)')
33
+ .option('--admin-worker-name <name>', '管理画面 Worker 名を明示指定(未指定ならリポジトリ名から導出。サニタイズで別リポジトリ名と衝突する場合の手動制御に使う)')
32
34
  .option('--r2-public-url <url>', 'R2 公開 URL(アップロードファイルの配信元・例: https://files.example.com)')
33
35
  .option('--owner-username <user>', 'Admin GitHub username')
34
36
  .option('--client-id <id>', 'GitHub OAuth Client ID')
@@ -10,3 +10,4 @@ export declare function log(message: string): void;
10
10
  export declare function logStep(step: number, total: number, message: string): void;
11
11
  export declare function logSuccess(message: string): void;
12
12
  export declare function logError(message: string): void;
13
+ export declare function logWarning(message: string): void;
package/dist/lib/shell.js CHANGED
@@ -38,3 +38,6 @@ export function logSuccess(message) {
38
38
  export function logError(message) {
39
39
  console.error(` ✗ ${message}`);
40
40
  }
41
+ export function logWarning(message) {
42
+ console.warn(` ⚠ ${message}`);
43
+ }
@@ -30,6 +30,9 @@ export function projectConfigToVars(config) {
30
30
  // お問い合わせワーカー(frelio-contact)の URL(任意機能・CMS「基本設定」で設定)。
31
31
  // 再生成時に既存値を保持する(Issue #198。未設定時のみ空)。
32
32
  contactApiUrl: config.contactApiUrl ?? '',
33
+ // 予約反映ワーカー(frelio-scheduled-publish)の URL(任意機能・CMS「基本設定」で設定)。
34
+ // 再生成時に既存値を保持する(未設定時のみ空)。
35
+ scheduleApiUrl: config.scheduleApiUrl ?? '',
33
36
  contentWorkerName: config.contentWorkerName,
34
37
  adminWorkerName: config.adminWorkerName,
35
38
  r2BucketName: config.r2BucketName,
@@ -22,6 +22,11 @@ export type ProjectConfig = {
22
22
  * 再生成(set-mode / set-domain)でも既存値を保持する(Issue #198)。未設定時は空。
23
23
  */
24
24
  contactApiUrl?: string;
25
+ /**
26
+ * 予約反映ワーカー(frelio-scheduled-publish)の URL(任意機能)。CMS「基本設定」で設定でき、
27
+ * 再生成(set-mode / set-domain)でも既存値を保持する。未設定時は空。
28
+ */
29
+ scheduleApiUrl?: string;
25
30
  r2BucketName: string;
26
31
  r2PublicUrl: string;
27
32
  /** コンテンツ配信 Worker 名(旧称 pagesProjectName)。 */
@@ -54,14 +59,23 @@ export declare function generateHash(): string;
54
59
  */
55
60
  export declare function generateHexSuffix(): string;
56
61
  /**
57
- * Worker 名(content 用・admin 用)を導出する(Issue #138)。
62
+ * Worker 名(content 用・admin 用)を導出する(Issue #138 / #216)。
58
63
  * randomSuffix=true なら content/admin それぞれに**別々の** hex サフィックスを付ける
59
64
  * (片方の名前が露出しても、もう片方を推測されないようにする)。
60
65
  *
66
+ * repoName は Cloudflare-safe な slug にサニタイズしてから使う(Issue #216)。
67
+ * overrides を指定するとその名前をそのまま採用する(`--content-worker-name` 等での明示指定)。
68
+ * override 値の検証は呼び出し側(buildConfig / promptConfig)で行う。
69
+ *
61
70
  * 例: ("website", true) → { contentWorkerName: "website-1a2b3c4d",
62
71
  * adminWorkerName: "website-admin-e5f6a7b8" }
72
+ * ("frelio_website", false) → { contentWorkerName: "frelio-website",
73
+ * adminWorkerName: "frelio-website-admin" }
63
74
  */
64
- export declare function buildWorkerNames(repoName: string, randomSuffix: boolean): {
75
+ export declare function buildWorkerNames(repoName: string, randomSuffix: boolean, overrides?: {
76
+ contentWorkerName?: string;
77
+ adminWorkerName?: string;
78
+ }): {
65
79
  contentWorkerName: string;
66
80
  adminWorkerName: string;
67
81
  };
@@ -118,6 +132,14 @@ export type ContactWorkerOptions = {
118
132
  * パスワード等のシークレットは wrangler secret で別途投入する(ここには書かない)。
119
133
  */
120
134
  export declare function generateContactWranglerToml(config: ProjectConfig, opts: ContactWorkerOptions): string;
135
+ /**
136
+ * 予約反映ワーカー(workers/scheduled-publish)の wrangler.toml を生成する(任意機能)。
137
+ *
138
+ * Durable Object(SQLite backend)の Alarm で発火する。CONTENT_REPO / ALLOWED_ORIGINS 等の
139
+ * ユーザー設定を含むため init 時に一度だけ生成し、update では上書きしない(PROTECTED_CONFIG)。
140
+ * 発火用 PAT(GITHUB_DISPATCH_TOKEN, Actions:write + Contents:read)は wrangler secret で投入する。
141
+ */
142
+ export declare function generateScheduledPublishWranglerToml(config: ProjectConfig): string;
121
143
  /**
122
144
  * コンテンツ配信 Worker の siteMode 焼き込みモジュール(worker/site-mode.ts)を生成する(Issue #184)。
123
145
  *
@@ -3,6 +3,7 @@
3
3
  */
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
+ import { sanitizeCloudflareName } from './validators.js';
6
7
  /** 本番ゲートのサイト公開状態(Issue #93) */
7
8
  export const SITE_MODES = ['live', 'prelaunch', 'maintenance', 'closed'];
8
9
  /** config.siteMode を正規化する(未知値・未指定は 'live') */
@@ -34,20 +35,30 @@ export function generateHexSuffix() {
34
35
  return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
35
36
  }
36
37
  /**
37
- * Worker 名(content 用・admin 用)を導出する(Issue #138)。
38
+ * Worker 名(content 用・admin 用)を導出する(Issue #138 / #216)。
38
39
  * randomSuffix=true なら content/admin それぞれに**別々の** hex サフィックスを付ける
39
40
  * (片方の名前が露出しても、もう片方を推測されないようにする)。
40
41
  *
42
+ * repoName は Cloudflare-safe な slug にサニタイズしてから使う(Issue #216)。
43
+ * overrides を指定するとその名前をそのまま採用する(`--content-worker-name` 等での明示指定)。
44
+ * override 値の検証は呼び出し側(buildConfig / promptConfig)で行う。
45
+ *
41
46
  * 例: ("website", true) → { contentWorkerName: "website-1a2b3c4d",
42
47
  * adminWorkerName: "website-admin-e5f6a7b8" }
48
+ * ("frelio_website", false) → { contentWorkerName: "frelio-website",
49
+ * adminWorkerName: "frelio-website-admin" }
43
50
  */
44
- export function buildWorkerNames(repoName, randomSuffix) {
45
- if (!randomSuffix) {
46
- return { contentWorkerName: repoName, adminWorkerName: `${repoName}-admin` };
47
- }
51
+ export function buildWorkerNames(repoName, randomSuffix, overrides) {
52
+ const base = sanitizeCloudflareName(repoName);
53
+ const derived = randomSuffix
54
+ ? {
55
+ contentWorkerName: `${base}-${generateHexSuffix()}`,
56
+ adminWorkerName: `${base}-admin-${generateHexSuffix()}`,
57
+ }
58
+ : { contentWorkerName: base, adminWorkerName: `${base}-admin` };
48
59
  return {
49
- contentWorkerName: `${repoName}-${generateHexSuffix()}`,
50
- adminWorkerName: `${repoName}-admin-${generateHexSuffix()}`,
60
+ contentWorkerName: overrides?.contentWorkerName || derived.contentWorkerName,
61
+ adminWorkerName: overrides?.adminWorkerName || derived.adminWorkerName,
51
62
  };
52
63
  }
53
64
  /**
@@ -98,6 +109,9 @@ export function generateConfigJson(config) {
98
109
  // お問い合わせワーカー(frelio-contact)の URL(任意機能・CMS「基本設定」で設定)。
99
110
  // 再生成時に既存値を保持する(Issue #198。未設定時のみ空)。以前はハードコード空で silent data-loss だった。
100
111
  contactApiUrl: config.contactApiUrl ?? '',
112
+ // 予約反映ワーカー(frelio-scheduled-publish)の URL(任意機能・CMS「基本設定」で設定)。
113
+ // 再生成時に既存値を保持する(未設定時のみ空)。
114
+ scheduleApiUrl: config.scheduleApiUrl ?? '',
101
115
  siteTitle: config.siteTitle,
102
116
  productionUrl: config.productionUrl,
103
117
  previewUrl: config.previewUrl,
@@ -198,6 +212,45 @@ ${smtpBlock}
198
212
  crons = ["0 3 * * *"]
199
213
  `;
200
214
  }
215
+ /**
216
+ * 予約反映ワーカー(workers/scheduled-publish)の wrangler.toml を生成する(任意機能)。
217
+ *
218
+ * Durable Object(SQLite backend)の Alarm で発火する。CONTENT_REPO / ALLOWED_ORIGINS 等の
219
+ * ユーザー設定を含むため init 時に一度だけ生成し、update では上書きしない(PROTECTED_CONFIG)。
220
+ * 発火用 PAT(GITHUB_DISPATCH_TOKEN, Actions:write + Contents:read)は wrangler secret で投入する。
221
+ */
222
+ export function generateScheduledPublishWranglerToml(config) {
223
+ const allowedOrigins = buildAllowedOrigins(config);
224
+ return `name = "frelio-scheduled-publish"
225
+ main = "src/index.ts"
226
+ compatibility_date = "2024-09-23"
227
+
228
+ [[durable_objects.bindings]]
229
+ name = "SCHEDULER"
230
+ class_name = "SchedulerDO"
231
+
232
+ [[migrations]]
233
+ tag = "v1"
234
+ new_sqlite_classes = ["SchedulerDO"]
235
+
236
+ [vars]
237
+ CONTENT_REPO = "${config.contentRepo}"
238
+ WORKFLOW_FILE = "scheduled-publish.yml"
239
+ REF = "develop"
240
+ ADMIN_DATA_BRANCH = "develop"
241
+ SCHEDULE_QUEUE_PATH = "frelio-data/admin/structure/schedule-queue.json"
242
+ USERS_JSON_PATH = "frelio-data/admin/structure/users.json"
243
+ # /notify の CORS 許可オリジン。CMS 管理画面のオリジンを含める(初回デプロイ後の workers.dev / 独自ドメイン)
244
+ ALLOWED_ORIGINS = "${allowedOrigins}"
245
+
246
+ # シークレットは wrangler secret put で投入(ここには書かない):
247
+ # GITHUB_DISPATCH_TOKEN - fine-grained PAT(Actions: write + Contents: read のみ)
248
+
249
+ [triggers]
250
+ # 1時間毎の reconcile(保険)。通常の発火は Durable Object の Alarm が指定時刻ちょうどに行う。
251
+ crons = ["0 * * * *"]
252
+ `;
253
+ }
201
254
  /**
202
255
  * コンテンツ配信 Worker の siteMode 焼き込みモジュール(worker/site-mode.ts)を生成する(Issue #184)。
203
256
  *
@@ -270,8 +323,9 @@ directory = "./admin"
270
323
  binding = "ASSETS"
271
324
  # SPA: 未マッチ URL は index.html へフォールバック(クライアントサイドルーティング)
272
325
  not_found_handling = "single-page-application"
273
- # /api/* のみ Worker を経由(SPA アセットは直接配信=コスト0)
274
- run_worker_first = ["/api/*"]
326
+ # /api/*(ルーター)と /storage/*(R2 公開配信・本文インライン画像の相対URL解決)のみ
327
+ # Worker を経由(SPA アセットは直接配信=コスト0)
328
+ run_worker_first = ["/api/*", "/storage/*"]
275
329
 
276
330
  [vars]
277
331
  R2_PUBLIC_URL = "${config.r2PublicUrl}"
@@ -7,3 +7,20 @@ export declare function validateR2PublicUrl(v: string): true | string;
7
7
  export declare function validateProductionUrl(v: string): true | string;
8
8
  export declare function validateStagingName(v: string): true | string;
9
9
  export declare function validateRequired(v: string, label: string): true | string;
10
+ /**
11
+ * 文字列を Cloudflare の Worker 名 / R2 バケット名として安全な slug に変換する(Issue #216)。
12
+ * 命名規則: 英小文字・数字・ハイフンのみ。アンダースコア不可。先頭/末尾ハイフン不可。
13
+ *
14
+ * 変換: toLowerCase → `[^a-z0-9-]` をハイフンに置換 → 連続ハイフン圧縮 → 先頭/末尾ハイフン除去
15
+ * → 末尾に付く可能性のあるサフィックス(`-admin-<8hex>` 等)や `-files` の余白を残すため
16
+ * base を最大 40 文字に切り詰める(63 文字上限内に収める)。
17
+ *
18
+ * 例: "frelio_website" → "frelio-website", "My-Repo" → "my-repo"
19
+ */
20
+ export declare function sanitizeCloudflareName(name: string): string;
21
+ /**
22
+ * Cloudflare の Worker 名 / R2 バケット名の命名規則を満たすか検証する(Issue #216)。
23
+ * 英小文字・数字・ハイフンのみ、先頭/末尾はハイフン不可、長さ 1〜63 文字。
24
+ * (R2 の下限 3 文字は導出名では実質満たされるため共通で 1〜63 を許容する)
25
+ */
26
+ export declare function validateCloudflareName(v: string): true | string;
@@ -33,3 +33,37 @@ export function validateStagingName(v) {
33
33
  export function validateRequired(v, label) {
34
34
  return v.length > 0 || `${label}は必須です`;
35
35
  }
36
+ /**
37
+ * 文字列を Cloudflare の Worker 名 / R2 バケット名として安全な slug に変換する(Issue #216)。
38
+ * 命名規則: 英小文字・数字・ハイフンのみ。アンダースコア不可。先頭/末尾ハイフン不可。
39
+ *
40
+ * 変換: toLowerCase → `[^a-z0-9-]` をハイフンに置換 → 連続ハイフン圧縮 → 先頭/末尾ハイフン除去
41
+ * → 末尾に付く可能性のあるサフィックス(`-admin-<8hex>` 等)や `-files` の余白を残すため
42
+ * base を最大 40 文字に切り詰める(63 文字上限内に収める)。
43
+ *
44
+ * 例: "frelio_website" → "frelio-website", "My-Repo" → "my-repo"
45
+ */
46
+ export function sanitizeCloudflareName(name) {
47
+ return name
48
+ .toLowerCase()
49
+ .replace(/[^a-z0-9-]+/g, '-')
50
+ .replace(/-+/g, '-')
51
+ .replace(/^-+|-+$/g, '')
52
+ .slice(0, 40)
53
+ .replace(/-+$/g, '');
54
+ }
55
+ /**
56
+ * Cloudflare の Worker 名 / R2 バケット名の命名規則を満たすか検証する(Issue #216)。
57
+ * 英小文字・数字・ハイフンのみ、先頭/末尾はハイフン不可、長さ 1〜63 文字。
58
+ * (R2 の下限 3 文字は導出名では実質満たされるため共通で 1〜63 を許容する)
59
+ */
60
+ export function validateCloudflareName(v) {
61
+ if (!v)
62
+ return '名前が空です';
63
+ if (v.length > 63)
64
+ return '63 文字以内で指定してください';
65
+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(v)) {
66
+ return '小文字英数字とハイフンのみ使用可能です(先頭/末尾はハイフン不可、アンダースコア不可)';
67
+ }
68
+ return true;
69
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@c-time/frelio-cli",
3
- "version": "2.2.1",
3
+ "version": "2.4.0",
4
4
  "description": "Frelio CMS setup CLI",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -23,8 +23,8 @@
23
23
  "prepublishOnly": "npm run build"
24
24
  },
25
25
  "dependencies": {
26
- "@c-time/frelio-data-json": "^2.2.1",
27
- "@c-time/frelio-gentl": "^2.2.1",
26
+ "@c-time/frelio-data-json": "^2.4.0",
27
+ "@c-time/frelio-gentl": "^2.4.0",
28
28
  "commander": "^13.0.0",
29
29
  "prompts": "^2.4.2",
30
30
  "tar": "^7.0.0"