@c-time/frelio-cli 2.2.0 → 2.3.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.
@@ -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 {};
@@ -10,13 +10,14 @@ import path from 'node:path';
10
10
  import { log, logStep, logSuccess, logError } 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';
@@ -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) {
@@ -222,6 +226,22 @@ export async function initCommand(options) {
222
226
  logError(contactResult.error);
223
227
  }
224
228
  }
229
+ // 予約反映ワーカー(任意)
230
+ if (scheduleInput) {
231
+ step++;
232
+ logStep(step, totalSteps, '予約反映ワーカーのセットアップ(wrangler.toml・シークレット)...');
233
+ const scheduleResult = setupScheduledPublishWorker(projectDir, config, scheduleInput);
234
+ if (scheduleResult.success) {
235
+ if (!scheduleResult.data.secret.success) {
236
+ log(' ⚠ GITHUB_DISPATCH_TOKEN の投入は初回デプロイ後に再実行してください:');
237
+ log(' cd workers/scheduled-publish && npx wrangler secret put GITHUB_DISPATCH_TOKEN');
238
+ }
239
+ logSuccess('予約反映ワーカーのセットアップ完了(deploy は workers/scheduled-publish で別途 → 基本設定で scheduleApiUrl を設定)');
240
+ }
241
+ else {
242
+ logError(scheduleResult.error);
243
+ }
244
+ }
225
245
  // git identity 確認(commit 直前 — 未設定だとデフォルト値で commit author が埋まるのを防ぐ)
226
246
  if (!options.skipGithub) {
227
247
  step++;
@@ -273,6 +293,11 @@ export async function initCommand(options) {
273
293
  }
274
294
  log(` ${config.stagingDomain ? '5' : '4'}. ステージングのアクセス制限を設定(Cloudflare Access 推奨)`);
275
295
  log('');
296
+ log(' 任意機能:');
297
+ log(' - お問い合わせフォーム: workers/contact/README.md(init で未設定なら後から)');
298
+ log(' - 予約反映(時刻ベースの自動公開/非公開): workers/scheduled-publish/README.md を参照して');
299
+ log(' ワーカーをデプロイ(PAT: Actions=RW / Contents=RO)→ 管理画面の「基本設定」→「予約反映 API URL」に設定');
300
+ log('');
276
301
  }
277
302
  // ---------------------------------------------------------------------------
278
303
  // UI helpers (prompts — commands 層に閉じる)
@@ -329,6 +354,32 @@ async function ensureGitIdentity(projectDir, ownerUsername) {
329
354
  * お問い合わせ機能(任意)のセットアップ入力を集める。
330
355
  * 対話モードのみ。スキップ/非対話なら null(=セットアップしない)。
331
356
  */
357
+ async function promptScheduledPublish() {
358
+ const isInteractive = process.stdin.isTTY === true;
359
+ if (!isInteractive)
360
+ return null;
361
+ log('⏰ 予約反映(任意・時刻ベースの自動公開/非公開):');
362
+ const enable = await prompts({
363
+ type: 'confirm',
364
+ name: 'value',
365
+ message: '予約反映ワーカーをセットアップしますか?(後からでも設定可)',
366
+ initial: false,
367
+ }, { onCancel: () => process.exit(0) });
368
+ if (!enable.value)
369
+ return null;
370
+ log(' 発火用の fine-grained PAT が必要です(対象 repo に Actions: Read and write + Contents: Read-only)。');
371
+ log(' → https://github.com/settings/tokens?type=beta');
372
+ log(' ※ 組織リポジトリは無期限にできません(最長1年)。期限切れで発火が止まるため更新運用に注意。');
373
+ const res = await prompts({
374
+ type: 'password',
375
+ name: 'dispatchToken',
376
+ message: '発火用 PAT(GITHUB_DISPATCH_TOKEN):',
377
+ validate: (v) => validateRequired(v, 'PAT'),
378
+ }, { onCancel: () => process.exit(0) });
379
+ if (!res.dispatchToken)
380
+ return null;
381
+ return { dispatchToken: res.dispatchToken };
382
+ }
332
383
  async function promptContact(config) {
333
384
  const isInteractive = process.stdin.isTTY === true;
334
385
  if (!isInteractive)
@@ -496,7 +547,7 @@ async function promptConfig(options) {
496
547
  message: 'R2 バケット名:',
497
548
  initial: (_prev, values) => {
498
549
  const repo = (options.contentRepo || values.contentRepo)?.split('/')[1] || 'site';
499
- return `${repo}-files`;
550
+ return `${sanitizeCloudflareName(repo)}-files`;
500
551
  },
501
552
  },
502
553
  {
@@ -530,16 +581,30 @@ async function promptConfig(options) {
530
581
  if (!contentRepo)
531
582
  return null;
532
583
  const repoName = contentRepo.split('/')[1];
584
+ const repoSlug = sanitizeCloudflareName(repoName);
533
585
  const stagingDomain = options.stagingDomain ?? response.stagingDomain ?? '';
534
586
  const previewUrl = stagingDomain ? `https://${stagingDomain}` : '';
535
- const { contentWorkerName, adminWorkerName } = buildWorkerNames(repoName, options.randomSuffix ?? true);
587
+ const { contentWorkerName, adminWorkerName } = buildWorkerNames(repoName, options.randomSuffix ?? true, { contentWorkerName: options.contentWorkerName, adminWorkerName: options.adminWorkerName });
588
+ const r2BucketName = options.r2BucketName ?? response.r2BucketName ?? `${repoSlug}-files`;
589
+ // 導出/指定した名前が Cloudflare の命名規則を満たすか早期に検証する(Cloudflare 呼び出し前)
590
+ for (const [label, value] of [
591
+ ['contentWorkerName', contentWorkerName],
592
+ ['adminWorkerName', adminWorkerName],
593
+ ['r2BucketName', r2BucketName],
594
+ ]) {
595
+ const check = validateCloudflareName(value);
596
+ if (check !== true) {
597
+ logError(`${label} ("${value}"): ${check}`);
598
+ process.exit(1);
599
+ }
600
+ }
536
601
  const config = {
537
602
  contentRepo,
538
603
  githubClientId: options.clientId || '',
539
604
  siteTitle: options.siteTitle ?? response.siteTitle ?? '',
540
605
  productionUrl: options.productionUrl ?? response.productionUrl ?? '',
541
606
  previewUrl,
542
- r2BucketName: options.r2BucketName ?? response.r2BucketName ?? `${repoName}-files`,
607
+ r2BucketName,
543
608
  r2PublicUrl: options.r2PublicUrl ?? response.r2PublicUrl ?? '',
544
609
  contentWorkerName,
545
610
  adminWorkerName,
@@ -563,6 +628,8 @@ function buildConfigFromOptions(options) {
563
628
  r2PublicUrl: options.r2PublicUrl,
564
629
  ownerUsername: options.ownerUsername,
565
630
  randomSuffix: options.randomSuffix,
631
+ contentWorkerName: options.contentWorkerName,
632
+ adminWorkerName: options.adminWorkerName,
566
633
  });
567
634
  if (!result.success) {
568
635
  logError(result.error);
@@ -581,7 +648,7 @@ function buildConfigFromOptions(options) {
581
648
  githubClientSecret: options.clientSecret,
582
649
  };
583
650
  }
584
- function getTotalSteps(options, withContact = false) {
651
+ function getTotalSteps(options, withContact = false, withSchedule = false) {
585
652
  let steps = 3; // content structure (includes workflows), bundle, config files
586
653
  if (!options.skipGithub)
587
654
  steps += 4; // create repo, clone, git identity, commit/push
@@ -589,5 +656,7 @@ function getTotalSteps(options, withContact = false) {
589
656
  steps += 1;
590
657
  if (withContact)
591
658
  steps += 1;
659
+ if (withSchedule)
660
+ steps += 1;
592
661
  return steps;
593
662
  }
@@ -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,
@@ -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')
@@ -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
  *
@@ -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.0",
3
+ "version": "2.3.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.0",
27
- "@c-time/frelio-gentl": "^2.2.0",
26
+ "@c-time/frelio-data-json": "^2.3.0",
27
+ "@c-time/frelio-gentl": "^2.3.0",
28
28
  "commander": "^13.0.0",
29
29
  "prompts": "^2.4.2",
30
30
  "tar": "^7.0.0"