# アーキテクチャ構成図

## システム全体構成図

```mermaid
flowchart TB
    subgraph Client["クライアント"]
        Browser["Webブラウザ"]
        Mobile["モバイルアプリ"]
        APIClient["APIクライアント"]
    end

    subgraph Gateway["Gateway Layer"]
        Caddy["Caddy<br/>リバースプロキシ"]
    end

    subgraph GhostCore["Ghost Core (Node.js/Express)"]
        subgraph WebLayer["Web Layer"]
            ExpressApp["Express App<br/>(ghost-server.js)"]
            Middleware["Middleware Chain<br/>- Sentry<br/>- Maintenance<br/>- VHost"]
        end

        subgraph Backend["Backend App"]
            AdminWeb["Admin Web<br/>/ghost/*"]
            APIRouter["API Router<br/>/ghost/api/*"]
        end

        subgraph Frontend["Frontend App"]
            ThemeRouter["Theme Router<br/>公開サイト"]
            MembersRouter["Members Router<br/>/members/*"]
        end
    end

    Browser --> Caddy
    Mobile --> Caddy
    APIClient --> Caddy
    Caddy --> ExpressApp
    ExpressApp --> Middleware
    Middleware --> Backend
    Middleware --> Frontend
```

## バックエンドレイヤー構成図

```mermaid
flowchart TB
    subgraph APILayer["API Layer"]
        AdminAPI["Admin API<br/>/ghost/api/admin/*"]
        ContentAPI["Content API<br/>/ghost/api/content/*"]
        MembersAPI["Members API<br/>/ghost/api/members/*"]
    end

    subgraph ServiceLayer["Service Layer (66+ Services)"]
        subgraph ContentServices["Content Domain"]
            PostsService["posts"]
            PagesService["pages"]
            TagsService["tags"]
            CollectionsService["collections"]
        end

        subgraph MemberServices["Members Domain"]
            MembersService["members"]
            TiersService["tiers"]
            OffersService["offers"]
            StripeService["stripe"]
        end

        subgraph EmailServices["Email Domain"]
            EmailService["email-service"]
            EmailAnalytics["email-analytics"]
            NewslettersService["newsletters"]
        end

        subgraph AuthServices["Auth Domain"]
            AuthService["auth"]
            PermissionsService["permissions"]
            SessionService["session"]
        end

        subgraph OtherServices["Other Domains"]
            ThemesService["themes"]
            URLService["url"]
            JobService["jobs"]
            WebhooksService["webhooks"]
        end
    end

    subgraph ModelLayer["Model Layer (70+ Models)"]
        PostModel["Post"]
        UserModel["User"]
        MemberModel["Member"]
        NewsletterModel["Newsletter"]
        SettingsModel["Settings"]
        OtherModels["...その他"]
    end

    subgraph DataLayer["Data Layer"]
        BookshelfORM["Bookshelf.js ORM"]
        KnexQuery["Knex Query Builder"]
        Schema["Schema Definition"]
        Migrations["Migrations"]
    end

    AdminAPI --> ContentServices
    AdminAPI --> MemberServices
    AdminAPI --> EmailServices
    AdminAPI --> AuthServices
    ContentAPI --> ContentServices
    MembersAPI --> MemberServices

    ContentServices --> PostModel
    MemberServices --> MemberModel
    EmailServices --> NewsletterModel
    AuthServices --> UserModel

    PostModel --> BookshelfORM
    UserModel --> BookshelfORM
    MemberModel --> BookshelfORM
    NewsletterModel --> BookshelfORM
    SettingsModel --> BookshelfORM
    OtherModels --> BookshelfORM

    BookshelfORM --> KnexQuery
    KnexQuery --> MySQL[(MySQL 8.4)]
```

## フロントエンドアプリケーション構成図

```mermaid
flowchart TB
    subgraph AdminUI["管理画面 (Ember.js + React)"]
        EmberAdmin["ghost/admin<br/>Ember.js App"]

        subgraph ReactApps["React Micro-Frontends"]
            AdminXSettings["admin-x-settings<br/>設定画面"]
            AdminXActPub["activitypub<br/>ActivityPub"]
            PostsApp["posts<br/>投稿管理"]
            StatsApp["stats<br/>統計"]
        end

        subgraph DesignSystems["Design Systems"]
            AdminXFramework["admin-x-framework<br/>共有フレームワーク"]
            Shade["shade<br/>shadcn/ui ベース"]
            LegacyDS["admin-x-design-system<br/>レガシー"]
        end
    end

    subgraph PublicUI["公開UI (UMD Bundles)"]
        Portal["portal<br/>メンバーポータル"]
        CommentsUI["comments-ui<br/>コメント"]
        SignupForm["signup-form<br/>サインアップ"]
        SodoSearch["sodo-search<br/>検索"]
        AnnouncementBar["announcement-bar<br/>告知"]
    end

    subgraph ThemeLayer["テーマレイヤー"]
        Handlebars["Handlebars<br/>テンプレートエンジン"]
        ThemeHelpers["Theme Helpers"]
        CustomThemeSettings["Custom Theme Settings"]
    end

    EmberAdmin --> ReactApps
    ReactApps --> AdminXFramework
    ReactApps --> Shade
    ReactApps --> LegacyDS

    Handlebars --> ThemeHelpers
    Handlebars --> PublicUI
    PublicUI -.->|"CDN/Asset Delivery"| Browser["ブラウザ"]
```

## データフロー図

### リクエスト処理フロー

```mermaid
sequenceDiagram
    participant Client as クライアント
    participant Caddy as Caddy Gateway
    participant Express as Express App
    participant Auth as Auth Middleware
    participant API as API Endpoint
    participant Service as Service Layer
    participant Model as Model Layer
    participant DB as MySQL

    Client->>Caddy: HTTP Request
    Caddy->>Express: Forward Request
    Express->>Express: Sentry Handler
    Express->>Express: Maintenance Check
    Express->>Express: VHost Routing
    Express->>Auth: Session/Token Auth
    Auth->>API: Authorized Request
    API->>API: Validation
    API->>Service: Business Logic
    Service->>Model: Data Access
    Model->>DB: SQL Query
    DB-->>Model: Result Set
    Model-->>Service: Domain Object
    Service-->>API: Response Data
    API-->>Client: JSON Response
```

### メール配信フロー

```mermaid
sequenceDiagram
    participant Admin as 管理者
    participant API as Posts API
    participant EmailSvc as Email Service
    participant JobMgr as Job Manager
    participant Mailgun as Mailgun API
    participant Analytics as Email Analytics
    participant Webhook as Webhook Handler

    Admin->>API: POST /posts/{id}/publish
    API->>API: Publish Post
    API->>EmailSvc: Trigger Newsletter
    EmailSvc->>EmailSvc: Generate Email Content
    EmailSvc->>EmailSvc: Create Batches
    EmailSvc->>JobMgr: Queue Send Jobs

    loop For Each Batch
        JobMgr->>Mailgun: Send Batch
        Mailgun-->>JobMgr: Accepted
    end

    Mailgun->>Webhook: Delivery Events
    Webhook->>Analytics: Process Events
    Analytics->>Analytics: Update Statistics
```

## 外部システム連携図

```mermaid
flowchart LR
    subgraph Ghost["Ghost Platform"]
        Core["Ghost Core"]
        Members["Members Service"]
        Email["Email Service"]
        Storage["Storage Adapter"]
        Analytics["Analytics"]
    end

    subgraph External["外部サービス"]
        Stripe["Stripe<br/>決済"]
        Mailgun["Mailgun<br/>メール配信"]
        S3["S3互換<br/>ストレージ"]
        Tinybird["Tinybird<br/>アナリティクス"]
    end

    subgraph Infrastructure["インフラ"]
        MySQL[(MySQL)]
        Redis[(Redis)]
    end

    Members <-->|REST API / Webhook| Stripe
    Email -->|REST API| Mailgun
    Mailgun -->|Webhook| Email
    Storage <-->|S3 API| S3
    Analytics -->|REST API| Tinybird

    Core <--> MySQL
    Core <--> Redis
```

## モノレポパッケージ依存関係図

```mermaid
flowchart TB
    subgraph Monorepo["Ghost Monorepo"]
        subgraph GhostPackages["ghost/*"]
            GhostCore["ghost/core<br/>メインアプリ"]
            GhostAdmin["ghost/admin<br/>Ember Admin"]
            GhostI18n["ghost/i18n<br/>国際化"]
        end

        subgraph AppsPackages["apps/*"]
            subgraph AdminApps["Admin Embedded"]
                AdminXSettings["admin-x-settings"]
                ActivityPub["activitypub"]
                PostsApp["posts"]
                StatsApp["stats"]
            end

            subgraph PublicApps["Public UMD"]
                Portal["portal"]
                CommentsUI["comments-ui"]
                SignupForm["signup-form"]
                SodoSearch["sodo-search"]
            end

            subgraph Foundation["Foundation"]
                AdminXFramework["admin-x-framework"]
                Shade["shade"]
                AdminXDS["admin-x-design-system"]
            end
        end
    end

    GhostCore --> GhostI18n
    GhostAdmin --> GhostI18n
    GhostAdmin --> AdminApps

    AdminApps --> AdminXFramework
    AdminApps --> Shade
    AdminXFramework --> AdminXDS

    PublicApps --> GhostI18n
```

## ブートシーケンス図

```mermaid
flowchart TB
    subgraph Boot["Ghost Boot Sequence"]
        Start["Start"]
        LoadConfig["Load Config<br/>shared/config"]
        LoadLogging["Load Logging<br/>@tryghost/logging"]
        InitSentry["Init Sentry"]
        StartServer["Start HTTP Server<br/>GhostServer"]
        InitDB["Init Database<br/>DatabaseStateManager"]
        InitCore["Init Core<br/>Models, Settings, URL Service"]
        InitFrontendServices["Init Frontend Services<br/>Themes, Routes, Redirects"]
        InitFrontend["Init Frontend<br/>Proxy, Helpers"]
        InitExpressApps["Init Express Apps<br/>Backend + Frontend"]
        InitDynamicRouting["Init Dynamic Routing"]
        InitServices["Init Services<br/>66+ Services並列初期化"]
        MountApp["Mount Ghost App"]
        Ready["Server Ready"]
        InitBackground["Init Background Services<br/>Email Analytics, Update Check"]
    end

    Start --> LoadConfig
    LoadConfig --> LoadLogging
    LoadLogging --> InitSentry
    InitSentry --> StartServer
    StartServer --> InitDB
    InitDB --> InitCore
    InitCore --> InitFrontendServices
    InitFrontendServices --> InitFrontend
    InitFrontend --> InitExpressApps
    InitExpressApps --> InitDynamicRouting
    InitDynamicRouting --> InitServices
    InitServices --> MountApp
    MountApp --> Ready
    Ready --> InitBackground
```

## データベーススキーマ概要図

```mermaid
erDiagram
    posts ||--o{ posts_authors : has
    posts ||--o{ posts_tags : has
    posts ||--o{ comments : has
    posts ||--o{ emails : generates

    users ||--o{ posts_authors : writes
    users ||--o{ roles_users : has

    tags ||--o{ posts_tags : categorizes

    members ||--o{ members_products : subscribes
    members ||--o{ members_newsletters : receives
    members ||--o{ comments : writes
    members ||--o{ members_stripe_customers : linked

    products ||--o{ members_products : offered_to
    products ||--o{ offers : has

    newsletters ||--o{ members_newsletters : sent_to
    newsletters ||--o{ emails : uses

    emails ||--o{ email_batches : split_into
    email_batches ||--o{ email_recipients : contains

    members_stripe_customers ||--o{ subscriptions : has

    posts {
        string id PK
        string uuid
        string title
        text lexical
        text html
        string status
        datetime published_at
    }

    users {
        string id PK
        string name
        string email
        string role
    }

    members {
        string id PK
        string uuid
        string email
        string status
    }

    newsletters {
        string id PK
        string name
        string status
    }

    products {
        string id PK
        string name
        string type
    }
```
