From 867f65f3b4d3e2d5bce087dbf4e99710b5da0060 Mon Sep 17 00:00:00 2001 From: SweetRetry Date: Fri, 16 Oct 2026 21:01:41 +0800 Subject: [PATCH 01/25] refactor!: remove Next.js app, Node server, Postgres and observability packages Void on Cloudflare replaces the split web/server processes: one Worker, D1 instead of Postgres, Workers Observability instead of the Node OTel SDK. ADRs and the stale TS 7 research note are deleted; their reasoning moves into docs/ in a later commit. Biome is replaced by Vite+ (vp fmt / vp lint). Co-Authored-By: Claude Opus 5.5 --- .oxlintrc.json | 29 -- apps/server/.env.example | 35 -- apps/server/drizzle.config.ts | 18 - .../drizzle/0000_great_silver_centurion.sql | 70 --- .../drizzle/0001_natural_puff_adder.sql | 1 - apps/server/drizzle/meta/0000_snapshot.json | 493 ------------------ apps/server/drizzle/meta/0001_snapshot.json | 389 -------------- apps/server/drizzle/meta/_journal.json | 20 - apps/server/package.json | 50 -- apps/server/src/ai.ts | 40 -- apps/server/src/auth-config.ts | 17 - apps/server/src/auth.ts | 46 -- apps/server/src/create-app.ts | 361 ------------- apps/server/src/database/client.ts | 15 - apps/server/src/database/schema.ts | 97 ---- apps/server/src/env.ts | 58 --- apps/server/src/index.ts | 78 --- apps/server/src/observability.ts | 45 -- apps/server/test/http-contract.test.ts | 183 ------- apps/server/tsconfig.json | 11 - apps/server/tsconfig.test.json | 10 - apps/server/vitest.config.ts | 9 - apps/web/.env.example | 7 - apps/web/AGENTS.md | 9 - apps/web/CLAUDE.md | 1 - apps/web/app/favicon.ico | Bin 25931 -> 0 bytes apps/web/app/layout.tsx | 40 -- apps/web/app/page.tsx | 26 - apps/web/app/sign-in/page.tsx | 48 -- apps/web/app/sign-up/page.tsx | 48 -- apps/web/components.json | 20 - apps/web/components/analytics.tsx | 91 ---- apps/web/components/auth-layout.tsx | 23 - apps/web/components/consent-banner.tsx | 53 -- apps/web/components/providers.tsx | 33 -- apps/web/components/server-status.tsx | 19 - apps/web/components/sign-in-form.tsx | 92 ---- apps/web/components/sign-up-form.tsx | 111 ---- apps/web/components/social-login.tsx | 47 -- apps/web/hooks/.gitkeep | 0 apps/web/lib/analytics.ts | 140 ----- apps/web/lib/api.ts | 16 - apps/web/lib/auth-client.ts | 7 - apps/web/lib/consent.ts | 29 -- apps/web/lib/dayjs.ts | 1 - apps/web/lib/env.ts | 10 - apps/web/lib/form.ts | 3 - apps/web/lib/toast.ts | 1 - apps/web/next-env.d.ts | 7 - apps/web/next.config.mjs | 14 - apps/web/package.json | 40 -- apps/web/postcss.config.mjs | 1 - apps/web/public/auth-bg.webp | Bin 168230 -> 0 bytes apps/web/test/analytics.test.ts | 31 -- apps/web/tsconfig.json | 18 - apps/web/vitest.config.ts | 9 - biome.json | 67 --- compose.yaml | 19 - .../0001-architecture-runtime-boundaries.md | 24 - docs/adr/0002-opentelemetry-observability.md | 25 - docs/adr/0005-http-api-shape.md | 23 - docs/adr/0006-trace-context-contract.md | 40 -- ...0007-runtime-assembly-and-app-ownership.md | 27 - docs/adr/README.md | 10 - docs/research/README.md | 15 - docs/research/typescript-7-upgrade.md | 162 ------ packages/logger/package.json | 30 -- packages/logger/src/index.ts | 73 --- packages/logger/test/redaction.test.ts | 77 --- packages/logger/tsconfig.json | 9 - packages/logger/tsconfig.test.json | 10 - packages/logger/vitest.config.ts | 9 - packages/observability/package.json | 30 -- packages/observability/src/agent-traces.ts | 164 ------ .../observability/test/agent-traces.test.ts | 143 ----- packages/observability/tsconfig.json | 9 - packages/observability/tsconfig.test.json | 10 - packages/observability/vitest.config.ts | 9 - packages/request/package.json | 33 -- packages/request/src/contract.ts | 136 ----- packages/request/src/http.ts | 90 ---- packages/request/test/contract.test.ts | 93 ---- packages/request/test/http.test.ts | 122 ----- packages/request/tsconfig.json | 10 - packages/request/tsconfig.test.json | 11 - packages/request/vitest.config.ts | 9 - packages/tracing/package.json | 28 - packages/tracing/src/index.ts | 114 ---- packages/tracing/test/trace-context.test.ts | 195 ------- packages/tracing/tsconfig.json | 10 - packages/tracing/tsconfig.test.json | 11 - packages/tracing/vitest.config.ts | 9 - packages/typescript-config/nextjs.json | 13 - vitest.config.ts | 7 - 94 files changed, 4946 deletions(-) delete mode 100644 .oxlintrc.json delete mode 100644 apps/server/.env.example delete mode 100644 apps/server/drizzle.config.ts delete mode 100644 apps/server/drizzle/0000_great_silver_centurion.sql delete mode 100644 apps/server/drizzle/0001_natural_puff_adder.sql delete mode 100644 apps/server/drizzle/meta/0000_snapshot.json delete mode 100644 apps/server/drizzle/meta/0001_snapshot.json delete mode 100644 apps/server/drizzle/meta/_journal.json delete mode 100644 apps/server/package.json delete mode 100644 apps/server/src/ai.ts delete mode 100644 apps/server/src/auth-config.ts delete mode 100644 apps/server/src/auth.ts delete mode 100644 apps/server/src/create-app.ts delete mode 100644 apps/server/src/database/client.ts delete mode 100644 apps/server/src/database/schema.ts delete mode 100644 apps/server/src/env.ts delete mode 100644 apps/server/src/index.ts delete mode 100644 apps/server/src/observability.ts delete mode 100644 apps/server/test/http-contract.test.ts delete mode 100644 apps/server/tsconfig.json delete mode 100644 apps/server/tsconfig.test.json delete mode 100644 apps/server/vitest.config.ts delete mode 100644 apps/web/.env.example delete mode 100644 apps/web/AGENTS.md delete mode 100644 apps/web/CLAUDE.md delete mode 100644 apps/web/app/favicon.ico delete mode 100644 apps/web/app/layout.tsx delete mode 100644 apps/web/app/page.tsx delete mode 100644 apps/web/app/sign-in/page.tsx delete mode 100644 apps/web/app/sign-up/page.tsx delete mode 100644 apps/web/components.json delete mode 100644 apps/web/components/analytics.tsx delete mode 100644 apps/web/components/auth-layout.tsx delete mode 100644 apps/web/components/consent-banner.tsx delete mode 100644 apps/web/components/providers.tsx delete mode 100644 apps/web/components/server-status.tsx delete mode 100644 apps/web/components/sign-in-form.tsx delete mode 100644 apps/web/components/sign-up-form.tsx delete mode 100644 apps/web/components/social-login.tsx delete mode 100644 apps/web/hooks/.gitkeep delete mode 100644 apps/web/lib/analytics.ts delete mode 100644 apps/web/lib/api.ts delete mode 100644 apps/web/lib/auth-client.ts delete mode 100644 apps/web/lib/consent.ts delete mode 100644 apps/web/lib/dayjs.ts delete mode 100644 apps/web/lib/env.ts delete mode 100644 apps/web/lib/form.ts delete mode 100644 apps/web/lib/toast.ts delete mode 100644 apps/web/next-env.d.ts delete mode 100644 apps/web/next.config.mjs delete mode 100644 apps/web/package.json delete mode 100644 apps/web/postcss.config.mjs delete mode 100644 apps/web/public/auth-bg.webp delete mode 100644 apps/web/test/analytics.test.ts delete mode 100644 apps/web/tsconfig.json delete mode 100644 apps/web/vitest.config.ts delete mode 100644 biome.json delete mode 100644 compose.yaml delete mode 100644 docs/adr/0001-architecture-runtime-boundaries.md delete mode 100644 docs/adr/0002-opentelemetry-observability.md delete mode 100644 docs/adr/0005-http-api-shape.md delete mode 100644 docs/adr/0006-trace-context-contract.md delete mode 100644 docs/adr/0007-runtime-assembly-and-app-ownership.md delete mode 100644 docs/adr/README.md delete mode 100644 docs/research/README.md delete mode 100644 docs/research/typescript-7-upgrade.md delete mode 100644 packages/logger/package.json delete mode 100644 packages/logger/src/index.ts delete mode 100644 packages/logger/test/redaction.test.ts delete mode 100644 packages/logger/tsconfig.json delete mode 100644 packages/logger/tsconfig.test.json delete mode 100644 packages/logger/vitest.config.ts delete mode 100644 packages/observability/package.json delete mode 100644 packages/observability/src/agent-traces.ts delete mode 100644 packages/observability/test/agent-traces.test.ts delete mode 100644 packages/observability/tsconfig.json delete mode 100644 packages/observability/tsconfig.test.json delete mode 100644 packages/observability/vitest.config.ts delete mode 100644 packages/request/package.json delete mode 100644 packages/request/src/contract.ts delete mode 100644 packages/request/src/http.ts delete mode 100644 packages/request/test/contract.test.ts delete mode 100644 packages/request/test/http.test.ts delete mode 100644 packages/request/tsconfig.json delete mode 100644 packages/request/tsconfig.test.json delete mode 100644 packages/request/vitest.config.ts delete mode 100644 packages/tracing/package.json delete mode 100644 packages/tracing/src/index.ts delete mode 100644 packages/tracing/test/trace-context.test.ts delete mode 100644 packages/tracing/tsconfig.json delete mode 100644 packages/tracing/tsconfig.test.json delete mode 100644 packages/tracing/vitest.config.ts delete mode 100644 packages/typescript-config/nextjs.json delete mode 100644 vitest.config.ts diff --git a/.oxlintrc.json b/.oxlintrc.json deleted file mode 100644 index f6cacb3..0000000 --- a/.oxlintrc.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "$schema": "./node_modules/oxlint/configuration_schema.json", - "jsPlugins": ["@shadcn/lint"], - "settings": { - "shadcn": { - "note": "外观归属与变体落点见 AGENTS.md › 架构约定;设计规则按 DESIGN.md 路由。", - "componentImports": ["^@workspace/ui/components"] - } - }, - "rules": { - "shadcn/no-restyle": [ - "error", - { - "allow": ["layout"] - } - ], - "shadcn/no-raw-colors": "error", - "shadcn/no-unknown-classes": "error", - "shadcn/require-static-classes": "error", - "shadcn/no-inline-styles": "error", - "shadcn/no-arbitrary-values": [ - "error", - { - "allow": ["layout"] - } - ] - }, - "ignorePatterns": ["packages/ui/src/components/**"] -} diff --git a/apps/server/.env.example b/apps/server/.env.example deleted file mode 100644 index e666aea..0000000 --- a/apps/server/.env.example +++ /dev/null @@ -1,35 +0,0 @@ -# ─── Runtime ───────────────────────────────────────────── -NODE_ENV=development - -# ─── URLs ──────────────────────────────────────────────── -SERVER_URL=http://localhost:43111 -WEB_URL=http://localhost:43110 - -# ─── Auth ──────────────────────────────────────────────── -BETTER_AUTH_SECRET=replace-with-at-least-32-random-characters -# GOOGLE_CLIENT_ID= -# GOOGLE_CLIENT_SECRET= - -# ─── Database ──────────────────────────────────────────── -DATABASE_URL=postgresql://sweet:sweet@localhost:5432/sweet_kit - -# ─── Server ────────────────────────────────────────────── -PORT=43111 - -# 仅在服务确实部署在可信代理之后时设为 true:启用后才读取 x-forwarded-for -TRUST_PROXY=false - -# ─── AI provider ──────────────────────────────────────── -# 未设置时 /api/assistant/reply 返回 503 SERVICE_UNAVAILABLE -# OPENAI_API_KEY=sk-... -# OPENAI_MODEL=gpt-4o - -# ─── Logger ────────────────────────────────────────────── -LOG_LEVEL=info -LOG_PRETTY=false - -# ─── OpenTelemetry ─────────────────────────────────────── -OTEL_METRICS_EXPORTER=none -OTEL_LOGS_EXPORTER=none -# OTEL_TRACES_EXPORTER=otlp -# OTEL_EXPORTER_OTLP_ENDPOINT=https://collector.example.com diff --git a/apps/server/drizzle.config.ts b/apps/server/drizzle.config.ts deleted file mode 100644 index 16c12f1..0000000 --- a/apps/server/drizzle.config.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { config } from "dotenv" -import { defineConfig } from "drizzle-kit" -import { z } from "zod" - -// drizzle-kit 默认只加载 `.env`,而本仓库的本地配置在 `.env.local`(与 server / worker 运行期一致)。 -// dotenv 不覆盖已存在的变量,因此 CI 或显式传入的 DATABASE_URL 仍然生效。 -config({ path: process.env.DOTENV_CONFIG_PATH ?? ".env.local", quiet: true }) - -const databaseUrl = z.url().parse(process.env.DATABASE_URL) - -export default defineConfig({ - dialect: "postgresql", - schema: "./src/database/schema.ts", - out: "./drizzle", - dbCredentials: { - url: databaseUrl, - }, -}) diff --git a/apps/server/drizzle/0000_great_silver_centurion.sql b/apps/server/drizzle/0000_great_silver_centurion.sql deleted file mode 100644 index dbf2696..0000000 --- a/apps/server/drizzle/0000_great_silver_centurion.sql +++ /dev/null @@ -1,70 +0,0 @@ -CREATE TABLE "account" ( - "id" text PRIMARY KEY NOT NULL, - "issuer" text NOT NULL, - "account_id" text NOT NULL, - "provider_id" text NOT NULL, - "user_id" text NOT NULL, - "access_token" text, - "refresh_token" text, - "id_token" text, - "access_token_expires_at" timestamp, - "refresh_token_expires_at" timestamp, - "scope" text, - "password" text, - "created_at" timestamp DEFAULT now() NOT NULL, - "updated_at" timestamp NOT NULL -); ---> statement-breakpoint -CREATE TABLE "device_code" ( - "id" text PRIMARY KEY NOT NULL, - "device_code" text NOT NULL, - "user_code" text NOT NULL, - "user_id" text, - "expires_at" timestamp NOT NULL, - "status" text NOT NULL, - "last_polled_at" timestamp, - "polling_interval" integer, - "client_id" text, - "scope" text -); ---> statement-breakpoint -CREATE TABLE "session" ( - "id" text PRIMARY KEY NOT NULL, - "expires_at" timestamp NOT NULL, - "token" text NOT NULL, - "created_at" timestamp DEFAULT now() NOT NULL, - "updated_at" timestamp NOT NULL, - "ip_address" text, - "user_agent" text, - "user_id" text NOT NULL, - CONSTRAINT "session_token_unique" UNIQUE("token") -); ---> statement-breakpoint -CREATE TABLE "user" ( - "id" text PRIMARY KEY NOT NULL, - "name" text NOT NULL, - "email" text NOT NULL, - "email_verified" boolean DEFAULT false NOT NULL, - "image" text, - "created_at" timestamp DEFAULT now() NOT NULL, - "updated_at" timestamp DEFAULT now() NOT NULL, - CONSTRAINT "user_email_unique" UNIQUE("email") -); ---> statement-breakpoint -CREATE TABLE "verification" ( - "id" text PRIMARY KEY NOT NULL, - "identifier" text NOT NULL, - "value" text NOT NULL, - "expires_at" timestamp NOT NULL, - "created_at" timestamp DEFAULT now() NOT NULL, - "updated_at" timestamp DEFAULT now() NOT NULL -); ---> statement-breakpoint -ALTER TABLE "account" ADD CONSTRAINT "account_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "session" ADD CONSTRAINT "session_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -CREATE UNIQUE INDEX "account_issuer_accountId_uidx" ON "account" USING btree ("issuer","account_id");--> statement-breakpoint -CREATE INDEX "account_userId_idx" ON "account" USING btree ("user_id");--> statement-breakpoint -CREATE UNIQUE INDEX "deviceCode_deviceCode_uidx" ON "device_code" USING btree ("device_code");--> statement-breakpoint -CREATE UNIQUE INDEX "deviceCode_userCode_uidx" ON "device_code" USING btree ("user_code");--> statement-breakpoint -CREATE INDEX "session_userId_idx" ON "session" USING btree ("user_id");--> statement-breakpoint -CREATE INDEX "verification_identifier_idx" ON "verification" USING btree ("identifier"); diff --git a/apps/server/drizzle/0001_natural_puff_adder.sql b/apps/server/drizzle/0001_natural_puff_adder.sql deleted file mode 100644 index 22652da..0000000 --- a/apps/server/drizzle/0001_natural_puff_adder.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE "device_code" CASCADE; \ No newline at end of file diff --git a/apps/server/drizzle/meta/0000_snapshot.json b/apps/server/drizzle/meta/0000_snapshot.json deleted file mode 100644 index 3710b60..0000000 --- a/apps/server/drizzle/meta/0000_snapshot.json +++ /dev/null @@ -1,493 +0,0 @@ -{ - "id": "aaefce62-3064-4c0f-860a-04e1d3bffbae", - "prevId": "00000000-0000-0000-0000-000000000000", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.account": { - "name": "account", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "issuer": { - "name": "issuer", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "account_id": { - "name": "account_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "provider_id": { - "name": "provider_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "access_token": { - "name": "access_token", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "refresh_token": { - "name": "refresh_token", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "id_token": { - "name": "id_token", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "access_token_expires_at": { - "name": "access_token_expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": false - }, - "refresh_token_expires_at": { - "name": "refresh_token_expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": false - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "password": { - "name": "password", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - } - }, - "indexes": { - "account_issuer_accountId_uidx": { - "name": "account_issuer_accountId_uidx", - "columns": [ - { - "expression": "issuer", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "account_id", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - }, - "account_userId_idx": { - "name": "account_userId_idx", - "columns": [ - { - "expression": "user_id", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": false, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "foreignKeys": { - "account_user_id_user_id_fk": { - "name": "account_user_id_user_id_fk", - "tableFrom": "account", - "tableTo": "user", - "columnsFrom": ["user_id"], - "columnsTo": ["id"], - "onDelete": "cascade", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.device_code": { - "name": "device_code", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "device_code": { - "name": "device_code", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_code": { - "name": "user_code", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "status": { - "name": "status", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "last_polled_at": { - "name": "last_polled_at", - "type": "timestamp", - "primaryKey": false, - "notNull": false - }, - "polling_interval": { - "name": "polling_interval", - "type": "integer", - "primaryKey": false, - "notNull": false - }, - "client_id": { - "name": "client_id", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - } - }, - "indexes": { - "deviceCode_deviceCode_uidx": { - "name": "deviceCode_deviceCode_uidx", - "columns": [ - { - "expression": "device_code", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - }, - "deviceCode_userCode_uidx": { - "name": "deviceCode_userCode_uidx", - "columns": [ - { - "expression": "user_code", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.session": { - "name": "session", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "token": { - "name": "token", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "ip_address": { - "name": "ip_address", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "user_agent": { - "name": "user_agent", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "user_id": { - "name": "user_id", - "type": "text", - "primaryKey": false, - "notNull": true - } - }, - "indexes": { - "session_userId_idx": { - "name": "session_userId_idx", - "columns": [ - { - "expression": "user_id", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": false, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "foreignKeys": { - "session_user_id_user_id_fk": { - "name": "session_user_id_user_id_fk", - "tableFrom": "session", - "tableTo": "user", - "columnsFrom": ["user_id"], - "columnsTo": ["id"], - "onDelete": "cascade", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "session_token_unique": { - "name": "session_token_unique", - "nullsNotDistinct": false, - "columns": ["token"] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.user": { - "name": "user", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "email": { - "name": "email", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "email_verified": { - "name": "email_verified", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "image": { - "name": "image", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "user_email_unique": { - "name": "user_email_unique", - "nullsNotDistinct": false, - "columns": ["email"] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.verification": { - "name": "verification", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "identifier": { - "name": "identifier", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "value": { - "name": "value", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "verification_identifier_idx": { - "name": "verification_identifier_idx", - "columns": [ - { - "expression": "identifier", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": false, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": {}, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} diff --git a/apps/server/drizzle/meta/0001_snapshot.json b/apps/server/drizzle/meta/0001_snapshot.json deleted file mode 100644 index 1729178..0000000 --- a/apps/server/drizzle/meta/0001_snapshot.json +++ /dev/null @@ -1,389 +0,0 @@ -{ - "id": "340e166b-9398-4125-9db9-2b2977b07be1", - "prevId": "aaefce62-3064-4c0f-860a-04e1d3bffbae", - "version": "7", - "dialect": "postgresql", - "tables": { - "public.account": { - "name": "account", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "issuer": { - "name": "issuer", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "account_id": { - "name": "account_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "provider_id": { - "name": "provider_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "user_id": { - "name": "user_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "access_token": { - "name": "access_token", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "refresh_token": { - "name": "refresh_token", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "id_token": { - "name": "id_token", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "access_token_expires_at": { - "name": "access_token_expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": false - }, - "refresh_token_expires_at": { - "name": "refresh_token_expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": false - }, - "scope": { - "name": "scope", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "password": { - "name": "password", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - } - }, - "indexes": { - "account_issuer_accountId_uidx": { - "name": "account_issuer_accountId_uidx", - "columns": [ - { - "expression": "issuer", - "isExpression": false, - "asc": true, - "nulls": "last" - }, - { - "expression": "account_id", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": true, - "concurrently": false, - "method": "btree", - "with": {} - }, - "account_userId_idx": { - "name": "account_userId_idx", - "columns": [ - { - "expression": "user_id", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": false, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "foreignKeys": { - "account_user_id_user_id_fk": { - "name": "account_user_id_user_id_fk", - "tableFrom": "account", - "tableTo": "user", - "columnsFrom": ["user_id"], - "columnsTo": ["id"], - "onDelete": "cascade", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.session": { - "name": "session", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "token": { - "name": "token", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "ip_address": { - "name": "ip_address", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "user_agent": { - "name": "user_agent", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "user_id": { - "name": "user_id", - "type": "text", - "primaryKey": false, - "notNull": true - } - }, - "indexes": { - "session_userId_idx": { - "name": "session_userId_idx", - "columns": [ - { - "expression": "user_id", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": false, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "foreignKeys": { - "session_user_id_user_id_fk": { - "name": "session_user_id_user_id_fk", - "tableFrom": "session", - "tableTo": "user", - "columnsFrom": ["user_id"], - "columnsTo": ["id"], - "onDelete": "cascade", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "session_token_unique": { - "name": "session_token_unique", - "nullsNotDistinct": false, - "columns": ["token"] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.user": { - "name": "user", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "name": { - "name": "name", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "email": { - "name": "email", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "email_verified": { - "name": "email_verified", - "type": "boolean", - "primaryKey": false, - "notNull": true, - "default": false - }, - "image": { - "name": "image", - "type": "text", - "primaryKey": false, - "notNull": false - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": { - "user_email_unique": { - "name": "user_email_unique", - "nullsNotDistinct": false, - "columns": ["email"] - } - }, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - }, - "public.verification": { - "name": "verification", - "schema": "", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true - }, - "identifier": { - "name": "identifier", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "value": { - "name": "value", - "type": "text", - "primaryKey": false, - "notNull": true - }, - "expires_at": { - "name": "expires_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true - }, - "created_at": { - "name": "created_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - }, - "updated_at": { - "name": "updated_at", - "type": "timestamp", - "primaryKey": false, - "notNull": true, - "default": "now()" - } - }, - "indexes": { - "verification_identifier_idx": { - "name": "verification_identifier_idx", - "columns": [ - { - "expression": "identifier", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": false, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "policies": {}, - "checkConstraints": {}, - "isRLSEnabled": false - } - }, - "enums": {}, - "schemas": {}, - "sequences": {}, - "roles": {}, - "policies": {}, - "views": {}, - "_meta": { - "columns": {}, - "schemas": {}, - "tables": {} - } -} diff --git a/apps/server/drizzle/meta/_journal.json b/apps/server/drizzle/meta/_journal.json deleted file mode 100644 index e6d0636..0000000 --- a/apps/server/drizzle/meta/_journal.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "version": "7", - "dialect": "postgresql", - "entries": [ - { - "idx": 0, - "version": "7", - "when": 1787326507047, - "tag": "0000_great_silver_centurion", - "breakpoints": true - }, - { - "idx": 1, - "version": "7", - "when": 1789876446629, - "tag": "0001_natural_puff_adder", - "breakpoints": true - } - ] -} diff --git a/apps/server/package.json b/apps/server/package.json deleted file mode 100644 index 826427c..0000000 --- a/apps/server/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "server", - "version": "0.0.0", - "type": "module", - "private": true, - "scripts": { - "build": "tsc -p tsconfig.json", - "dev": "NODE_OPTIONS=--conditions=development DOTENV_CONFIG_PATH=.env.local tsx watch src/index.ts", - "start": "DOTENV_CONFIG_PATH=.env.local node dist/index.js", - "auth:generate": "NODE_OPTIONS=--conditions=development DOTENV_CONFIG_PATH=.env.local auth generate --config src/auth-config.ts --output src/database/schema.ts --yes && pnpm exec biome check --write src/database/schema.ts", - "db:generate": "drizzle-kit generate --config drizzle.config.ts && pnpm exec biome format --write drizzle/meta/*.json", - "db:migrate": "drizzle-kit migrate --config drizzle.config.ts", - "lint": "biome check .", - "lint:fix": "biome check --write .", - "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json" - }, - "dependencies": { - "@ai-sdk/openai": "^4.0.51", - "@better-auth/drizzle-adapter": "^1.7.2", - "@hono/node-server": "^2.1.1", - "@hono/otel": "^1.1.2", - "@hono/zod-openapi": "^1.6.1", - "@opentelemetry/sdk-node": "^0.221.0", - "@opentelemetry/sdk-trace-base": "^2.10.0", - "@scalar/hono-api-reference": "^0.12.0", - "@workspace/logger": "workspace:*", - "@workspace/observability": "workspace:*", - "@workspace/request": "workspace:*", - "@workspace/tracing": "workspace:*", - "ai": "^7.0.84", - "better-auth": "^1.7.2", - "dotenv": "^17.4.2", - "drizzle-orm": "^0.45.2", - "hono": "^4.13.5", - "hono-pino": "^0.10.3", - "hono-rate-limiter": "^0.5.3", - "pg": "^8.23.0", - "zod": "^4.5.2" - }, - "devDependencies": { - "@types/node": "^26.4.0", - "@types/pg": "^8.23.1", - "@workspace/typescript-config": "workspace:*", - "auth": "^1.7.2", - "drizzle-kit": "^0.31.10", - "tsx": "^4.23.12", - "typescript": "^7.0.2", - "vitest": "^4.1.11" - } -} diff --git a/apps/server/src/ai.ts b/apps/server/src/ai.ts deleted file mode 100644 index f385e91..0000000 --- a/apps/server/src/ai.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { createOpenAI } from "@ai-sdk/openai" -import { generateText, type LanguageModel } from "ai" - -export interface AiProviderOptions { - apiKey: string - modelId: string -} - -/** - * AI provider 的装配入口。 - * - * 凭据与模型名由应用环境变量提供(见 `src/env.ts`),这里只把 provider 客户端 - * 收敛成 `generateText` 可用的 model;装配位置在 composition root(`src/index.ts`), - * 见 [ADR 0007](../../../docs/adr/0007-runtime-assembly-and-app-ownership.md)。 - */ -export function createAiModel(options: AiProviderOptions): LanguageModel { - return createOpenAI({ apiKey: options.apiKey })(options.modelId) -} - -/** - * 生成一次回复。 - * - * `telemetry` 打开后 provider 调用会产出 span,本地开发时进入 trace projection, - * 由 `data/traces.jsonl` 查看,见 [docs/observability.md](../../../docs/observability.md)。 - */ -export async function generateAssistantReply( - model: LanguageModel, - prompt: string -): Promise { - const { text } = await generateText({ - model, - prompt, - telemetry: { - functionId: "assistant.reply", - isEnabled: true, - }, - }) - - return text -} diff --git a/apps/server/src/auth-config.ts b/apps/server/src/auth-config.ts deleted file mode 100644 index c12c506..0000000 --- a/apps/server/src/auth-config.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { createAuth } from "./auth.ts" -import { createDatabase } from "./database/client.ts" -import { serverEnv } from "./env.ts" - -/** - * Better Auth CLI 的配置入口(`pnpm --filter server auth:generate --config src/auth-config.ts`), - * 只为 schema 生成而存在,进程运行时由 `src/index.ts` 装配。 - */ -export const db = createDatabase(serverEnv.databaseUrl) - -export const auth = createAuth({ - baseURL: serverEnv.serverUrl, - database: db, - google: serverEnv.google, - secret: serverEnv.authSecret, - trustedOrigins: [serverEnv.webUrl], -}) diff --git a/apps/server/src/auth.ts b/apps/server/src/auth.ts deleted file mode 100644 index 667eb6b..0000000 --- a/apps/server/src/auth.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { drizzleAdapter } from "@better-auth/drizzle-adapter" -import { betterAuth } from "better-auth/minimal" -import { bearer } from "better-auth/plugins" - -import type { Database } from "./database/client.ts" -import * as schema from "./database/schema.ts" - -interface SocialProviderOptions { - clientId: string - clientSecret: string -} - -export interface AuthOptions { - baseURL: string - database: Database - google?: SocialProviderOptions - secret: string - trustedOrigins: string[] -} - -export function createAuth(options: AuthOptions) { - return betterAuth({ - appName: "Sweet Kit", - baseURL: options.baseURL, - database: drizzleAdapter(options.database, { - provider: "pg", - schema, - }), - emailAndPassword: { - enabled: true, - }, - secret: options.secret, - socialProviders: { - ...(options.google && { - google: { - clientId: options.google.clientId, - clientSecret: options.google.clientSecret, - }, - }), - }, - trustedOrigins: options.trustedOrigins, - plugins: [bearer()], - }) -} - -export type Auth = ReturnType diff --git a/apps/server/src/create-app.ts b/apps/server/src/create-app.ts deleted file mode 100644 index 89048cd..0000000 --- a/apps/server/src/create-app.ts +++ /dev/null @@ -1,361 +0,0 @@ -import { getConnInfo } from "@hono/node-server/conninfo" -import { httpInstrumentationMiddleware } from "@hono/otel" -import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi" -import { Scalar } from "@scalar/hono-api-reference" -import type { Logger } from "@workspace/logger" -import { - createProblemDetails, - ErrorCode, - getErrorStatus, - PROBLEM_MEDIA_TYPE, -} from "@workspace/request/contract" -import { - getActiveSpanContext, - TRACE_ID_PATTERN, - TRACE_PARENT_HEADER, - traceResponseHeaders, -} from "@workspace/tracing" -import type { Context } from "hono" -import { cors } from "hono/cors" -import { requestId } from "hono/request-id" -import { type Env as HonoPinoEnv, pinoLogger } from "hono-pino" -import { rateLimiter } from "hono-rate-limiter" - -import { type AiProviderOptions, createAiModel, generateAssistantReply } from "./ai.ts" -import type { Auth } from "./auth.ts" - -const RATE_LIMIT_WINDOW_MS = 60_000 -const RATE_LIMIT_MAX = 100 - -const HealthSchema = z - .object({ - status: z.literal("ok"), - service: z.literal("sweet-kit-server"), - }) - .openapi("Health") - -const UserSchema = z - .object({ - id: z.string(), - email: z.email(), - name: z.string(), - }) - .openapi("User") - -const AssistantRequestSchema = z - .object({ - prompt: z.string().min(1).max(2_000), - }) - .openapi("AssistantRequest") - -const AssistantReplySchema = z - .object({ - text: z.string(), - }) - .openapi("AssistantReply") - -const ProblemDetailsSchema = z - .object({ - type: z.string(), - title: z.string(), - status: z.number().int(), - detail: z.string(), - code: z.enum(ErrorCode), - traceId: z.string().regex(new RegExp(TRACE_ID_PATTERN)).optional(), - }) - .openapi("ProblemDetails") - -const problemContent = { [PROBLEM_MEDIA_TYPE]: { schema: ProblemDetailsSchema } } - -const validationErrorResponse = { - content: problemContent, - description: "Request validation failed", -} - -const unauthorizedResponse = { - content: problemContent, - description: "Authentication required", -} - -const tooManyRequestsResponse = { - content: problemContent, - description: "Rate limit exceeded, see Retry-After", -} - -const serviceUnavailableResponse = { - content: problemContent, - description: "Feature is not configured in this deployment", -} - -const internalErrorResponse = { - content: problemContent, - description: "Internal server error with trace correlation", -} - -function problemResponse(c: Context, code: C, detail: string) { - const status = getErrorStatus(code) - const body = createProblemDetails(code, detail, { traceId: getActiveSpanContext()?.traceId }) - - return c.json(body, status, { "Content-Type": PROBLEM_MEDIA_TYPE }) -} - -/** - * 校验失败的统一出口。 - * - * `@hono/zod-openapi` 在未提供 hook 时会把 ZodError 整体序列化进响应体, - * 这里改成 problem details:detail 只带出错位置与原因,不带内部结构。 - */ -function describeValidationFailure(result: { error: z.ZodError; target: string }): string { - const [issue] = result.error.issues - - if (!issue) { - return `${result.target} 未通过校验` - } - - const location = issue.path.length > 0 ? `${issue.path.join(".")} ` : "" - - return `${result.target} 校验失败:${location}${issue.message}` -} - -/** - * 限流使用的客户端标识。 - * - * `x-forwarded-for` 可被客户端伪造,因此只有部署在可信代理之后(`TRUST_PROXY=true`) - * 才读取它,且取最右侧一项——它由可信代理追加,客户端伪造的前缀覆盖不到。 - */ -function clientAddress(c: Context, trustProxy: boolean): string { - if (trustProxy) { - const forwarded = c.req - .header("x-forwarded-for") - ?.split(",") - .map((value) => value.trim()) - .filter(Boolean) - .at(-1) - - if (forwarded) { - return forwarded - } - } - - try { - return getConnInfo(c).remote.address ?? "unknown" - } catch { - return "unknown" - } -} - -const healthRoute = createRoute({ - method: "get", - path: "/api/health", - tags: ["System"], - summary: "Server health", - responses: { - 200: { - content: { "application/json": { schema: HealthSchema } }, - description: "Server health", - }, - 429: tooManyRequestsResponse, - 500: internalErrorResponse, - }, -}) - -const meRoute = createRoute({ - method: "get", - path: "/api/me", - tags: ["Account"], - summary: "Current authenticated user", - security: [{ bearerAuth: [] }], - responses: { - 200: { - content: { "application/json": { schema: UserSchema } }, - description: "Current authenticated user", - }, - 401: unauthorizedResponse, - 429: tooManyRequestsResponse, - 500: internalErrorResponse, - }, -}) - -const assistantRoute = createRoute({ - method: "post", - path: "/api/assistant/reply", - tags: ["Assistant"], - summary: "Generate a reply through the configured AI provider", - description: - "需要登录;上游凭据由部署环境提供(OPENAI_API_KEY)。未配置时返回 503,provider 调用会参与 trace 关联。", - security: [{ bearerAuth: [] }], - request: { - body: { - content: { "application/json": { schema: AssistantRequestSchema } }, - required: true, - }, - }, - responses: { - 200: { - content: { "application/json": { schema: AssistantReplySchema } }, - description: "Generated reply", - }, - 400: validationErrorResponse, - 401: unauthorizedResponse, - 429: tooManyRequestsResponse, - 500: internalErrorResponse, - 503: serviceUnavailableResponse, - }, -}) - -interface CreateServerAppOptions { - ai?: AiProviderOptions - auth: Auth - logger: Logger - trustProxy: boolean - webUrl: string -} - -export function createServerApp(options: CreateServerAppOptions) { - const app = new OpenAPIHono({ - defaultHook: (result, c) => { - if (result.success) return - - return problemResponse( - c, - ErrorCode.VALIDATION_ERROR, - describeValidationFailure({ error: result.error, target: result.target }) - ) - }, - }) - - const aiModel = options.ai ? createAiModel(options.ai) : undefined - - app.openAPIRegistry.registerComponent("securitySchemes", "bearerAuth", { - type: "http", - scheme: "bearer", - }) - - app.use( - "*", - httpInstrumentationMiddleware({ - serviceName: "sweet-kit-server", - serviceVersion: "0.0.1", - }) - ) - app.use("*", requestId()) - app.use( - "*", - pinoLogger({ - pino: options.logger, - http: { - onResBindings: (c) => ({ - res: { - status: c.res.status, - }, - ...(c.error ? { err: c.error } : {}), - }), - onResLevel: (c) => { - if (c.res.status >= 500) return "error" - if (c.res.status >= 400) return "warn" - return "info" - }, - }, - }) - ) - app.use("*", async (c, next) => { - await next() - for (const [name, value] of Object.entries(traceResponseHeaders())) c.header(name, value) - }) - - app.use( - "/api/*", - cors({ - origin: options.webUrl, - credentials: true, - exposeHeaders: ["x-request-id", TRACE_PARENT_HEADER], - }) - ) - - app.use( - "/api/*", - /** - * 默认 store 是进程内 MemoryStore:多实例部署时限流按实例计算, - * 需要跨实例一致时换成共享 store(如 Redis)。 - */ - rateLimiter({ - windowMs: RATE_LIMIT_WINDOW_MS, - limit: RATE_LIMIT_MAX, - keyGenerator: (c) => clientAddress(c, options.trustProxy), - handler: (c) => { - c.header("Retry-After", String(RATE_LIMIT_WINDOW_MS / 1_000)) - - return problemResponse(c, ErrorCode.TOO_MANY_REQUESTS, "请求过于频繁,请稍后重试") - }, - }) - ) - - app.all("/api/auth/*", (c) => options.auth.handler(c.req.raw)) - - app.openapi(healthRoute, (c) => c.json({ status: "ok", service: "sweet-kit-server" }, 200)) - - app.openapi(meRoute, async (c) => { - const session = await options.auth.api.getSession({ headers: c.req.raw.headers }) - - if (!session) { - return problemResponse(c, ErrorCode.UNAUTHORIZED, "Authentication required") - } - - return c.json( - { - id: session.user.id, - email: session.user.email, - name: session.user.name, - }, - 200 - ) - }) - - app.openapi(assistantRoute, async (c) => { - const session = await options.auth.api.getSession({ headers: c.req.raw.headers }) - - if (!session) { - return problemResponse(c, ErrorCode.UNAUTHORIZED, "Authentication required") - } - - if (!aiModel) { - return problemResponse( - c, - ErrorCode.SERVICE_UNAVAILABLE, - "此部署未配置 AI provider:需要 OPENAI_API_KEY" - ) - } - - const { prompt } = c.req.valid("json") - const text = await generateAssistantReply(aiModel, prompt) - - return c.json({ text }, 200) - }) - - app.doc31("/openapi.json", { - openapi: "3.1.0", - info: { - title: "Sweet Kit API", - version: "0.1.0", - }, - }) - - app.get( - "/docs", - Scalar({ - pageTitle: "Sweet Kit API", - url: "/openapi.json", - }) - ) - - app.notFound((c) => - problemResponse(c, ErrorCode.NOT_FOUND, `未找到 ${c.req.method} ${c.req.path}`) - ) - - app.onError((error, c) => { - c.get("logger").error({ err: error }, "request.failed") - return problemResponse(c, ErrorCode.INTERNAL_SERVER_ERROR, "Internal Server Error") - }) - - return app -} diff --git a/apps/server/src/database/client.ts b/apps/server/src/database/client.ts deleted file mode 100644 index 6699393..0000000 --- a/apps/server/src/database/client.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { drizzle } from "drizzle-orm/node-postgres" -import { Pool } from "pg" - -import * as schema from "./schema.ts" - -export function createDatabase(connectionString: string) { - const pool = new Pool({ connectionString }) - return drizzle(pool, { schema }) -} - -export type Database = ReturnType - -export async function closeDatabase(database: Database): Promise { - await database.$client.end() -} diff --git a/apps/server/src/database/schema.ts b/apps/server/src/database/schema.ts deleted file mode 100644 index fa26ecb..0000000 --- a/apps/server/src/database/schema.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { relations } from "drizzle-orm" -import { boolean, index, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core" - -export const user = pgTable("user", { - id: text("id").primaryKey(), - name: text("name").notNull(), - email: text("email").notNull().unique(), - emailVerified: boolean("email_verified").default(false).notNull(), - image: text("image"), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at") - .defaultNow() - .$onUpdate(() => /* @__PURE__ */ new Date()) - .notNull(), -}) - -export const session = pgTable( - "session", - { - id: text("id").primaryKey(), - expiresAt: timestamp("expires_at").notNull(), - token: text("token").notNull().unique(), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at") - .$onUpdate(() => /* @__PURE__ */ new Date()) - .notNull(), - ipAddress: text("ip_address"), - userAgent: text("user_agent"), - userId: text("user_id") - .notNull() - .references(() => user.id, { onDelete: "cascade" }), - }, - (table) => [index("session_userId_idx").on(table.userId)] -) - -export const account = pgTable( - "account", - { - id: text("id").primaryKey(), - issuer: text("issuer").notNull(), - accountId: text("account_id").notNull(), - providerId: text("provider_id").notNull(), - userId: text("user_id") - .notNull() - .references(() => user.id, { onDelete: "cascade" }), - accessToken: text("access_token"), - refreshToken: text("refresh_token"), - idToken: text("id_token"), - accessTokenExpiresAt: timestamp("access_token_expires_at"), - refreshTokenExpiresAt: timestamp("refresh_token_expires_at"), - scope: text("scope"), - password: text("password"), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at") - .$onUpdate(() => /* @__PURE__ */ new Date()) - .notNull(), - }, - (table) => [ - uniqueIndex("account_issuer_accountId_uidx").on(table.issuer, table.accountId), - index("account_userId_idx").on(table.userId), - ] -) - -export const verification = pgTable( - "verification", - { - id: text("id").primaryKey(), - identifier: text("identifier").notNull(), - value: text("value").notNull(), - expiresAt: timestamp("expires_at").notNull(), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at") - .defaultNow() - .$onUpdate(() => /* @__PURE__ */ new Date()) - .notNull(), - }, - (table) => [index("verification_identifier_idx").on(table.identifier)] -) - -export const userRelations = relations(user, ({ many }) => ({ - sessions: many(session), - accounts: many(account), -})) - -export const sessionRelations = relations(session, ({ one }) => ({ - user: one(user, { - fields: [session.userId], - references: [user.id], - }), -})) - -export const accountRelations = relations(account, ({ one }) => ({ - user: one(user, { - fields: [account.userId], - references: [user.id], - }), -})) diff --git a/apps/server/src/env.ts b/apps/server/src/env.ts deleted file mode 100644 index 47c5614..0000000 --- a/apps/server/src/env.ts +++ /dev/null @@ -1,58 +0,0 @@ -import path from "node:path" -import { z } from "zod" - -/** AI provider 未显式指定模型时的默认值;取值由 `OPENAI_MODEL` 覆盖 */ -const DEFAULT_AI_MODEL_ID = "gpt-4o" - -const values = z - .object({ - BETTER_AUTH_SECRET: z.string().min(32), - DATABASE_URL: z.url(), - GOOGLE_CLIENT_ID: z.string().min(1).optional(), - GOOGLE_CLIENT_SECRET: z.string().min(1).optional(), - LOG_LEVEL: z.string().min(1), - LOG_PRETTY: z.enum(["true", "false"]), - NODE_ENV: z.enum(["development", "test", "production"]), - OPENAI_API_KEY: z.string().min(1).optional(), - OPENAI_MODEL: z.string().min(1).optional(), - OTEL_TRACES_EXPORTER: z.string().optional(), - PORT: z.coerce.number().int().min(1).max(65_535), - SERVER_URL: z.url(), - SWEET_KIT_TRACE_FILE: z.string().min(1).optional(), - TRUST_PROXY: z.enum(["true", "false"]).default("false"), - WEB_URL: z.url(), - }) - .parse(process.env) - -export const serverEnv = { - agentTraceFile: - values.SWEET_KIT_TRACE_FILE ?? - (values.NODE_ENV !== "production" && values.OTEL_TRACES_EXPORTER === undefined - ? path.resolve("data/traces.jsonl") - : undefined), - ai: values.OPENAI_API_KEY - ? { - apiKey: values.OPENAI_API_KEY, - modelId: values.OPENAI_MODEL ?? DEFAULT_AI_MODEL_ID, - } - : undefined, - authSecret: values.BETTER_AUTH_SECRET, - databaseUrl: values.DATABASE_URL, - google: - values.GOOGLE_CLIENT_ID && values.GOOGLE_CLIENT_SECRET - ? { clientId: values.GOOGLE_CLIENT_ID, clientSecret: values.GOOGLE_CLIENT_SECRET } - : undefined, - logger: { - environment: values.NODE_ENV, - level: values.LOG_LEVEL, - pretty: values.LOG_PRETTY === "true", - }, - port: values.PORT, - serverUrl: values.SERVER_URL, - /** - * 是否信任 `x-forwarded-for`。默认关闭:只在确实部署在可信代理之后时启用, - * 否则客户端可自行伪造该 header 绕过基于 IP 的限流。 - */ - trustProxy: values.TRUST_PROXY === "true", - webUrl: values.WEB_URL, -} diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts deleted file mode 100644 index 4ea3b31..0000000 --- a/apps/server/src/index.ts +++ /dev/null @@ -1,78 +0,0 @@ -import "dotenv/config" -import { serverEnv } from "./env.ts" -import { startObservability } from "./observability.ts" - -/** - * Server composition root:先起 telemetry(instrumentation 需要在被观测模块加载前就位), - * 再装配 database、auth、logger 与 app,最后注册关停流程。 - * 装配归属见 [ADR 0007](../../../docs/adr/0007-runtime-assembly-and-app-ownership.md)。 - */ -const observability = startObservability() - -const [ - { serve }, - { createServerApp }, - { createLogger }, - { createAuth }, - { closeDatabase, createDatabase }, -] = await Promise.all([ - import("@hono/node-server"), - import("./create-app.ts"), - import("@workspace/logger"), - import("./auth.ts"), - import("./database/client.ts"), -]) - -const logger = createLogger({ ...serverEnv.logger, service: "sweet-kit-server" }) -const db = createDatabase(serverEnv.databaseUrl) -const auth = createAuth({ - baseURL: serverEnv.serverUrl, - database: db, - google: serverEnv.google, - secret: serverEnv.authSecret, - trustedOrigins: [serverEnv.webUrl], -}) -const app = createServerApp({ - ai: serverEnv.ai, - auth, - logger, - trustProxy: serverEnv.trustProxy, - webUrl: serverEnv.webUrl, -}) - -const server = serve({ - fetch: app.fetch, - port: serverEnv.port, -}) - -logger.info( - { - port: serverEnv.port, - url: serverEnv.serverUrl, - ...(observability.localTraceFile ? { agentTraceFile: observability.localTraceFile } : {}), - }, - "server.started" -) - -let shuttingDown = false - -async function shutdown(signal: NodeJS.Signals) { - if (shuttingDown) return - shuttingDown = true - logger.info({ signal }, "server.stopping") - - await new Promise((resolve, reject) => { - server.close((error) => (error ? reject(error) : resolve())) - }) - await closeDatabase(db) - await observability.shutdown() -} - -for (const signal of ["SIGINT", "SIGTERM"] as const) { - process.once(signal, () => { - shutdown(signal).catch((error: unknown) => { - logger.error({ err: error }, "server.shutdown.failed") - process.exitCode = 1 - }) - }) -} diff --git a/apps/server/src/observability.ts b/apps/server/src/observability.ts deleted file mode 100644 index c4b1249..0000000 --- a/apps/server/src/observability.ts +++ /dev/null @@ -1,45 +0,0 @@ -import path from "node:path" -import { NodeSDK } from "@opentelemetry/sdk-node" -import { SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base" -import { AgentTraceFileExporter } from "@workspace/observability/agent-traces" -import { createTracePropagator } from "@workspace/tracing" - -import { serverEnv } from "./env.ts" - -export interface Observability { - localTraceFile?: string - shutdown(): Promise -} - -/** - * Server 进程的 telemetry 装配(composition root)。 - * 本地开发把 span 投影到 JSONL 供按行检索,生产由 OTel 环境变量选择 OTLP; - * 这里只固定 service name 与项目采用的 W3C propagator。 - * - * 本地用 SimpleSpanProcessor 而非默认的 BatchSpanProcessor:批处理是为了摊薄 OTLP 的网络开销, - * 对本地文件追加只剩延迟(默认 5s),会让刚发完的请求查不到自己的 trace。 - */ -export function startObservability(): Observability { - const localTraceFile = serverEnv.agentTraceFile - ? path.resolve(serverEnv.agentTraceFile) - : undefined - - const sdk = new NodeSDK({ - serviceName: process.env.OTEL_SERVICE_NAME ?? "sweet-kit-server", - textMapPropagator: createTracePropagator(), - ...(localTraceFile - ? { - spanProcessors: [new SimpleSpanProcessor(new AgentTraceFileExporter(localTraceFile))], - metricReaders: [], - logRecordProcessors: [], - } - : {}), - }) - - sdk.start() - - return { - ...(localTraceFile ? { localTraceFile } : {}), - shutdown: () => sdk.shutdown(), - } -} diff --git a/apps/server/test/http-contract.test.ts b/apps/server/test/http-contract.test.ts deleted file mode 100644 index 0df7aa5..0000000 --- a/apps/server/test/http-contract.test.ts +++ /dev/null @@ -1,183 +0,0 @@ -import { randomUUID } from "node:crypto" -import { Writable } from "node:stream" -import { createLogger } from "@workspace/logger" -import { PROBLEM_MEDIA_TYPE } from "@workspace/request/contract" -import { afterAll, beforeAll, describe, expect, it } from "vitest" - -import { type Auth, createAuth } from "../src/auth.ts" -import { createServerApp } from "../src/create-app.ts" -import { closeDatabase, createDatabase, type Database } from "../src/database/client.ts" - -/** - * 应用响应测试:验证路由与中间件的错误出口符合 `rules/api-contract.md`。 - * - * 需要 PostgreSQL(`DATABASE_URL`)与已执行的 migration;未提供时跳过, - * 由 CI 的 integration environment 提供,不在测试内启动 container runtime。 - */ -const databaseUrl = process.env.DATABASE_URL -const baseUrl = "http://localhost:43111" -const webUrl = "http://localhost:43110" - -let db: Database -let auth: Auth -let app: ReturnType - -function createApp(database: Database, options?: { ai?: boolean }) { - return createServerApp({ - ai: options?.ai ? { apiKey: "test-key", modelId: "gpt-4o" } : undefined, - auth: createAuth({ - baseURL: baseUrl, - database, - secret: "integration-test-secret-at-least-32-characters", - trustedOrigins: [webUrl], - }), - logger: createLogger({ - destination: new Writable({ write: (_chunk, _encoding, callback) => callback() }), - environment: "test", - level: "info", - pretty: false, - service: "sweet-kit-server-test", - }), - trustProxy: false, - webUrl, - }) -} - -async function problem(response: Response) { - // Hono 默认追加 charset;problem 响应显式声明媒体类型,因此只断言前缀 - expect(response.headers.get("content-type")).toContain(PROBLEM_MEDIA_TYPE) - - return (await response.json()) as { code: string; detail: string; status: number; type: string } -} - -describe.skipIf(!databaseUrl)("HTTP 错误出口", () => { - beforeAll(() => { - db = createDatabase(databaseUrl ?? "") - auth = createAuth({ - baseURL: baseUrl, - database: db, - secret: "integration-test-secret-at-least-32-characters", - trustedOrigins: [webUrl], - }) - app = createApp(db) - }) - - afterAll(async () => { - await closeDatabase(db) - }) - - it("未匹配路由返回 404 problem details", async () => { - const response = await app.request(`${baseUrl}/api/does-not-exist`) - const body = await problem(response) - - expect(response.status).toBe(404) - expect(body).toMatchObject({ code: "NOT_FOUND", status: 404 }) - expect(body.type.endsWith("/not-found")).toBe(true) - expect(body.detail).toContain("/api/does-not-exist") - }) - - it("请求体校验失败返回 400 problem details,不带 Zod 内部结构", async () => { - const response = await app.request(`${baseUrl}/api/assistant/reply`, { - body: JSON.stringify({ prompt: "" }), - headers: { "content-type": "application/json" }, - method: "POST", - }) - const body = await problem(response) - - expect(response.status).toBe(400) - expect(body).toMatchObject({ code: "VALIDATION_ERROR", status: 400 }) - expect(body.detail).toContain("prompt") - expect(body).not.toHaveProperty("error") - }) - - it("缺少凭据返回 401,不泄漏部署配置", async () => { - const response = await problem(await app.request(`${baseUrl}/api/me`)) - - expect(response).toMatchObject({ code: "UNAUTHORIZED", status: 401 }) - }) - - it("未配置 AI provider 时登录用户得到 503", async () => { - const cookie = await signUp() - - const anonymous = await app.request(`${baseUrl}/api/assistant/reply`, { - body: JSON.stringify({ prompt: "hello" }), - headers: { "content-type": "application/json" }, - method: "POST", - }) - expect(anonymous.status).toBe(401) - - const response = await app.request(`${baseUrl}/api/assistant/reply`, { - body: JSON.stringify({ prompt: "hello" }), - headers: { "content-type": "application/json", cookie }, - method: "POST", - }) - const body = await problem(response) - - expect(response.status).toBe(503) - expect(body).toMatchObject({ code: "SERVICE_UNAVAILABLE", status: 503 }) - }) - - it("已认证时 /api/me 返回当前用户", async () => { - const email = `contract-${randomUUID()}@example.com` - const cookie = await signUp(email) - const response = await app.request(`${baseUrl}/api/me`, { headers: { cookie } }) - - expect(response.status).toBe(200) - expect(await response.json()).toMatchObject({ email }) - }) - - it("超过窗口阈值返回 429 problem details,并带 Retry-After", async () => { - const localDb = createDatabase(databaseUrl ?? "") - const localApp = createApp(localDb) - - try { - for (let index = 0; index < 100; index += 1) { - const response = await localApp.request(`${baseUrl}/api/health`) - expect(response.status).toBe(200) - } - - const limited = await localApp.request(`${baseUrl}/api/health`) - const body = await problem(limited) - - expect(limited.status).toBe(429) - expect(body).toMatchObject({ code: "TOO_MANY_REQUESTS", status: 429 }) - expect(limited.headers.get("retry-after")).toBe("60") - } finally { - await closeDatabase(localDb) - } - }) - - it("OpenAPI 为每个错误状态声明 problem 媒体类型", async () => { - const document = (await (await app.request(`${baseUrl}/openapi.json`)).json()) as { - paths: Record }>> - } - - for (const [path, operations] of Object.entries(document.paths)) { - for (const [method, operation] of Object.entries(operations)) { - for (const [status, response] of Object.entries(operation.responses)) { - if (Number(status) < 400) continue - - const content = (response as { content?: Record }).content ?? {} - - expect(Object.keys(content), `${method.toUpperCase()} ${path} ${status}`).toContain( - PROBLEM_MEDIA_TYPE - ) - } - } - } - }) -}) - -async function signUp(email = `contract-${randomUUID()}@example.com`): Promise { - const result = await auth.api.signUpEmail({ - body: { email, name: "Contract", password: "contract-password" }, - returnHeaders: true, - }) - const cookie = result.headers.get("set-cookie") - - if (!cookie) { - throw new Error("sign-up 未返回 session cookie") - } - - return cookie -} diff --git a/apps/server/tsconfig.json b/apps/server/tsconfig.json deleted file mode 100644 index 68eb3eb..0000000 --- a/apps/server/tsconfig.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "extends": "@workspace/typescript-config/base.json", - "compilerOptions": { - "declaration": false, - "declarationMap": false, - "outDir": "dist", - "rootDir": "src" - }, - "include": ["src"], - "exclude": ["node_modules", "dist"] -} diff --git a/apps/server/tsconfig.test.json b/apps/server/tsconfig.test.json deleted file mode 100644 index 68cb4d6..0000000 --- a/apps/server/tsconfig.test.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "@workspace/typescript-config/base.json", - "compilerOptions": { - "declaration": false, - "declarationMap": false, - "noEmit": true - }, - "include": ["src", "test", "vitest.config.ts"], - "exclude": ["node_modules", "dist"] -} diff --git a/apps/server/vitest.config.ts b/apps/server/vitest.config.ts deleted file mode 100644 index decd39e..0000000 --- a/apps/server/vitest.config.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { defineProject } from "vitest/config" - -export default defineProject({ - test: { - environment: "node", - include: ["test/**/*.test.ts"], - name: "server", - }, -}) diff --git a/apps/web/.env.example b/apps/web/.env.example deleted file mode 100644 index 745ffd5..0000000 --- a/apps/web/.env.example +++ /dev/null @@ -1,7 +0,0 @@ -# ─── URLs ──────────────────────────────────────────────── -NEXT_PUBLIC_SERVER_URL=http://localhost:43111 - -# ─── Analytics ───────────────────────────────────────── -# NEXT_PUBLIC_GOOGLE_ANALYTICS_ID=G-XXXXXXXXXX -# NEXT_PUBLIC_MICROSOFT_UET_TAG_ID=000000000 -# NEXT_PUBLIC_META_PIXEL_ID=000000000000000 diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md deleted file mode 100644 index 643577d..0000000 --- a/apps/web/AGENTS.md +++ /dev/null @@ -1,9 +0,0 @@ - - -# This is NOT the Next.js you know - -This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices. - -This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean. - - diff --git a/apps/web/CLAUDE.md b/apps/web/CLAUDE.md deleted file mode 100644 index 43c994c..0000000 --- a/apps/web/CLAUDE.md +++ /dev/null @@ -1 +0,0 @@ -@AGENTS.md diff --git a/apps/web/app/favicon.ico b/apps/web/app/favicon.ico deleted file mode 100644 index 718d6fea4835ec2d246af9800eddb7ffb276240c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 25931 zcmeHv30#a{`}aL_*G&7qml|y<+KVaDM2m#dVr!KsA!#An?kSQM(q<_dDNCpjEux83 zLb9Z^XxbDl(w>%i@8hT6>)&Gu{h#Oeyszu?xtw#Zb1mO{pgX9699l+Qppw7jXaYf~-84xW z)w4x8?=youko|}Vr~(D$UXIbiXABHh`p1?nn8Po~fxRJv}|0e(BPs|G`(TT%kKVJAdg5*Z|x0leQq0 zkdUBvb#>9F()jo|T~kx@OM8$9wzs~t2l;K=woNssA3l6|sx2r3+kdfVW@e^8e*E}v zA1y5{bRi+3Z`uD3{F7LgFJDdv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wLq^*T_9-z^&UE@A(z9oGYtFy6EZef LrJugUA?W`A8`#=m diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx deleted file mode 100644 index faec268..0000000 --- a/apps/web/app/layout.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import type { Metadata } from "next" -import { Geist, Geist_Mono } from "next/font/google" -import "@workspace/ui/globals.css" -import { Analytics } from "@/components/analytics" -import { Providers } from "@/components/providers" -import { webEnv } from "@/lib/env" - -const fontSans = Geist({ - subsets: ["latin"], - variable: "--font-sans", -}) - -const fontMono = Geist_Mono({ - subsets: ["latin"], - variable: "--font-mono", -}) - -export const metadata: Metadata = { - title: "Sweet Kit", - description: "A full-stack TypeScript development kit", -} - -export default function RootLayout({ - children, -}: Readonly<{ - children: React.ReactNode -}>) { - return ( - - - - {children} - - - ) -} diff --git a/apps/web/app/page.tsx b/apps/web/app/page.tsx deleted file mode 100644 index 1626ca8..0000000 --- a/apps/web/app/page.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { Button } from "@workspace/ui/components/button" -import Link from "next/link" - -import { ServerStatus } from "@/components/server-status" - -export default function Page() { - return ( -
-
-

- Full-stack TypeScript development kit -

-

Sweet Kit

-

- Next.js frontend, Hono server, OpenAPI contract, and aspect-oriented packages. -

- -
- -
-
-
- ) -} diff --git a/apps/web/app/sign-in/page.tsx b/apps/web/app/sign-in/page.tsx deleted file mode 100644 index 8f7d966..0000000 --- a/apps/web/app/sign-in/page.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import Link from "next/link" - -import { AuthLayout } from "@/components/auth-layout" -import { SignInForm } from "@/components/sign-in-form" -import { SocialLogin } from "@/components/social-login" - -function safeRedirect(value: string | undefined) { - return value?.startsWith("/") && !value.startsWith("//") ? value : "/" -} - -export default async function SignInPage({ - searchParams, -}: { - searchParams: Promise<{ redirect?: string }> -}) { - const { redirect } = await searchParams - - return ( - -
-
-

登录 Sweet Kit

-

选择登录方式继续

-
- - - -
-
- -
-
- OR -
-
- - - -
- 没有账号?{" "} - - 创建账号 - -
-
-
- ) -} diff --git a/apps/web/app/sign-up/page.tsx b/apps/web/app/sign-up/page.tsx deleted file mode 100644 index 788a8bc..0000000 --- a/apps/web/app/sign-up/page.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import Link from "next/link" - -import { AuthLayout } from "@/components/auth-layout" -import { SignUpForm } from "@/components/sign-up-form" -import { SocialLogin } from "@/components/social-login" - -function safeRedirect(value: string | undefined) { - return value?.startsWith("/") && !value.startsWith("//") ? value : "/" -} - -export default async function SignUpPage({ - searchParams, -}: { - searchParams: Promise<{ redirect?: string }> -}) { - const { redirect } = await searchParams - - return ( - -
-
-

创建账号

-

注册以开始使用 Sweet Kit

-
- - - -
-
- -
-
- OR -
-
- - - -
- 已有账号?{" "} - - 登录 - -
-
-
- ) -} diff --git a/apps/web/components.json b/apps/web/components.json deleted file mode 100644 index 1fd99d3..0000000 --- a/apps/web/components.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "$schema": "https://ui.shadcn.com/schema.json", - "style": "new-york", - "rsc": true, - "tsx": true, - "tailwind": { - "config": "", - "css": "../../packages/ui/src/styles/globals.css", - "baseColor": "neutral", - "cssVariables": true - }, - "iconLibrary": "lucide", - "aliases": { - "components": "@/components", - "hooks": "@/hooks", - "lib": "@/lib", - "utils": "@workspace/ui/lib/utils", - "ui": "@workspace/ui/components" - } -} diff --git a/apps/web/components/analytics.tsx b/apps/web/components/analytics.tsx deleted file mode 100644 index 3aabd1b..0000000 --- a/apps/web/components/analytics.tsx +++ /dev/null @@ -1,91 +0,0 @@ -"use client" - -import { usePathname } from "next/navigation" -import Script from "next/script" -import { useEffect } from "react" - -import { - initializeGoogleAnalytics, - initializeMetaPixel, - initializeMicrosoftUet, - trackMetaPageView, -} from "@/lib/analytics" -import { useConsentStore } from "@/lib/consent" - -interface AnalyticsProps { - googleAnalyticsId?: string - metaPixelId?: string - microsoftUetTagId?: string -} - -/** - * 第三方统计装配。 - * - * 未取得同意(`consent.status !== "granted"`)时不加载任何脚本,也不上报 pageview: - * 登录、注册与授权页同样适用。决定入口见 `components/consent-banner.tsx`。 - */ -export function Analytics({ googleAnalyticsId, metaPixelId, microsoftUetTagId }: AnalyticsProps) { - const pathname = usePathname() - const granted = useConsentStore((state) => state.status) === "granted" - - useEffect(() => { - if (granted && googleAnalyticsId) { - initializeGoogleAnalytics(googleAnalyticsId) - } - }, [granted, googleAnalyticsId]) - - useEffect(() => { - if (granted && metaPixelId) { - initializeMetaPixel(metaPixelId) - } - }, [granted, metaPixelId]) - - useEffect(() => { - if (granted && metaPixelId) { - trackMetaPageView(metaPixelId, pathname) - } - }, [granted, metaPixelId, pathname]) - - if (!granted) { - return null - } - - return ( - <> - {googleAnalyticsId ? ( -