@damiangilgonzalez/copypasta 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +227 -2
- package/catalog.yaml +140 -0
- package/cli/copypasta.js +4 -0
- package/cli/lib/catalog.js +131 -0
- package/cli/lib/commands.js +162 -0
- package/cli/lib/index.js +4 -0
- package/cli/lib/main.js +130 -0
- package/package.json +38 -4
- package/recipes/agents/agent-memory/RECIPE.md +75 -0
- package/recipes/agents/agent-memory/files/agentic/memory/__init__.py +25 -0
- package/recipes/agents/agent-memory/files/agentic/memory/base.py +101 -0
- package/recipes/agents/agent-memory/files/agentic/memory/factory.py +33 -0
- package/recipes/agents/agent-memory/files/agentic/memory/in_memory.py +59 -0
- package/recipes/agents/agent-memory/files/agentic/memory/models.py +66 -0
- package/recipes/agents/agent-memory/files/agentic/memory/settings.py +24 -0
- package/recipes/agents/agent-memory/files/agentic/memory/sql.py +177 -0
- package/recipes/agents/agent-memory/files/pytest.ini +5 -0
- package/recipes/agents/agent-memory/files/tests/__init__.py +0 -0
- package/recipes/agents/agent-memory/files/tests/memory_conformance.py +158 -0
- package/recipes/agents/agent-memory/files/tests/test_memory.py +74 -0
- package/recipes/agents/langchain-agent/RECIPE.md +101 -0
- package/recipes/agents/langchain-agent/files/agentic/__init__.py +10 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/__init__.py +13 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/agents.py +43 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/base_agent.py +126 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/models.py +46 -0
- package/recipes/agents/langchain-agent/files/agentic/context.py +21 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/__init__.py +5 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/models.py +45 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/provider.py +78 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/settings.py +62 -0
- package/recipes/agents/langchain-agent/files/agentic/middleware/__init__.py +3 -0
- package/recipes/agents/langchain-agent/files/agentic/middleware/language.py +28 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/__init__.py +3 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.en.yaml +15 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.es.yaml +15 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/loader.py +69 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/__init__.py +25 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/base_tool.py +62 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/search_documents.py +42 -0
- package/recipes/agents/langchain-agent/files/pytest.ini +5 -0
- package/recipes/agents/langchain-agent/files/tests/__init__.py +0 -0
- package/recipes/agents/langchain-agent/files/tests/fakes.py +30 -0
- package/recipes/agents/langchain-agent/files/tests/test_agents.py +151 -0
- package/recipes/agents/langgraph-graph/RECIPE.md +63 -0
- package/recipes/agents/langgraph-graph/files/agentic/conversation.py +73 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/__init__.py +17 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/builder.py +37 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/edges.py +8 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/event_processor.py +48 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/events.py +30 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/graph.py +60 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/nodes.py +63 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/state.py +31 -0
- package/recipes/agents/langgraph-graph/files/agentic/registry.py +85 -0
- package/recipes/agents/langgraph-graph/files/tests/test_graph.py +145 -0
- package/recipes/backend/.gitkeep +0 -0
- package/recipes/backend/agent-chat-api/RECIPE.md +69 -0
- package/recipes/backend/agent-chat-api/files/api/agent/guards.py +35 -0
- package/recipes/backend/agent-chat-api/files/api/agent/router.py +86 -0
- package/recipes/backend/agent-chat-api/files/api/agent/sanitize.py +22 -0
- package/recipes/backend/agent-chat-api/files/api/agent/schemas.py +26 -0
- package/recipes/backend/agent-chat-api/files/api/agent/settings.py +14 -0
- package/recipes/backend/agent-chat-api/files/api/agent/tracing.py +38 -0
- package/recipes/backend/agent-chat-api/files/api/app.py +67 -0
- package/recipes/backend/agent-chat-api/files/api/auth.py +73 -0
- package/recipes/backend/agent-chat-api/files/pytest.ini +5 -0
- package/recipes/backend/agent-chat-api/files/tests/test_agent_api.py +237 -0
- package/recipes/backend/agent-feedback/RECIPE.md +63 -0
- package/recipes/backend/agent-feedback/files/api/feedback/__init__.py +0 -0
- package/recipes/backend/agent-feedback/files/api/feedback/router.py +72 -0
- package/recipes/backend/agent-feedback/files/api/feedback/schemas.py +44 -0
- package/recipes/backend/agent-feedback/files/feedback/__init__.py +25 -0
- package/recipes/backend/agent-feedback/files/feedback/base.py +53 -0
- package/recipes/backend/agent-feedback/files/feedback/factory.py +30 -0
- package/recipes/backend/agent-feedback/files/feedback/in_memory.py +29 -0
- package/recipes/backend/agent-feedback/files/feedback/models.py +48 -0
- package/recipes/backend/agent-feedback/files/feedback/settings.py +17 -0
- package/recipes/backend/agent-feedback/files/feedback/sql.py +102 -0
- package/recipes/backend/agent-feedback/files/pytest.ini +5 -0
- package/recipes/backend/agent-feedback/files/tests/feedback_conformance.py +89 -0
- package/recipes/backend/agent-feedback/files/tests/test_feedback.py +63 -0
- package/recipes/backend/agent-feedback/files/tests/test_feedback_api.py +95 -0
- package/recipes/backend/auth-verifier/RECIPE.md +63 -0
- package/recipes/backend/auth-verifier/files/api/auth.py +73 -0
- package/recipes/backend/auth-verifier/files/auth/__init__.py +23 -0
- package/recipes/backend/auth-verifier/files/auth/factory.py +28 -0
- package/recipes/backend/auth-verifier/files/auth/jwt_verifier.py +101 -0
- package/recipes/backend/auth-verifier/files/auth/models.py +29 -0
- package/recipes/backend/auth-verifier/files/auth/settings.py +45 -0
- package/recipes/backend/auth-verifier/files/auth/supabase.py +80 -0
- package/recipes/backend/auth-verifier/files/pytest.ini +5 -0
- package/recipes/backend/auth-verifier/files/tests/__init__.py +0 -0
- package/recipes/backend/auth-verifier/files/tests/test_auth.py +229 -0
- package/recipes/backend/conversation-history/RECIPE.md +49 -0
- package/recipes/backend/conversation-history/files/api/conversations/__init__.py +0 -0
- package/recipes/backend/conversation-history/files/api/conversations/router.py +55 -0
- package/recipes/backend/conversation-history/files/api/conversations/schemas.py +57 -0
- package/recipes/backend/conversation-history/files/pytest.ini +5 -0
- package/recipes/backend/conversation-history/files/tests/test_conversations_api.py +127 -0
- package/recipes/backend/fastapi-base/RECIPE.md +57 -0
- package/recipes/backend/fastapi-base/files/api/app.py +37 -0
- package/recipes/backend/fastapi-base/files/api/base.py +54 -0
- package/recipes/backend/fastapi-base/files/api/errors.py +31 -0
- package/recipes/backend/fastapi-base/files/api/health.py +19 -0
- package/recipes/backend/fastapi-base/files/api/logging_setup.py +26 -0
- package/recipes/backend/fastapi-base/files/api/request_id.py +62 -0
- package/recipes/backend/fastapi-base/files/api/settings.py +32 -0
- package/recipes/backend/fastapi-base/files/pytest.ini +5 -0
- package/recipes/backend/fastapi-base/files/tests/__init__.py +0 -0
- package/recipes/backend/fastapi-base/files/tests/test_api_base.py +136 -0
- package/recipes/backend/observability/RECIPE.md +68 -0
- package/recipes/backend/observability/files/observability/__init__.py +34 -0
- package/recipes/backend/observability/files/observability/factory.py +73 -0
- package/recipes/backend/observability/files/observability/langfuse_tracer.py +29 -0
- package/recipes/backend/observability/files/observability/langsmith_tracer.py +23 -0
- package/recipes/backend/observability/files/observability/models.py +90 -0
- package/recipes/backend/observability/files/observability/opik_tracer.py +30 -0
- package/recipes/backend/observability/files/observability/settings.py +58 -0
- package/recipes/backend/observability/files/observability/tracer.py +142 -0
- package/recipes/backend/observability/files/observability/usage.py +61 -0
- package/recipes/backend/observability/files/pytest.ini +5 -0
- package/recipes/backend/observability/files/tests/__init__.py +0 -0
- package/recipes/backend/observability/files/tests/test_observability.py +219 -0
- package/recipes/backend/project-settings/RECIPE.md +40 -0
- package/recipes/backend/project-settings/files/.env.example +7 -0
- package/recipes/backend/project-settings/files/core/__init__.py +0 -0
- package/recipes/backend/project-settings/files/core/config.py +41 -0
- package/recipes/backend/project-settings/files/pytest.ini +3 -0
- package/recipes/backend/project-settings/files/tests/__init__.py +0 -0
- package/recipes/backend/project-settings/files/tests/test_settings.py +44 -0
- package/recipes/backend/rag-retriever/RECIPE.md +79 -0
- package/recipes/backend/rag-retriever/files/pytest.ini +5 -0
- package/recipes/backend/rag-retriever/files/rag/__init__.py +53 -0
- package/recipes/backend/rag-retriever/files/rag/base.py +106 -0
- package/recipes/backend/rag-retriever/files/rag/chunking.py +84 -0
- package/recipes/backend/rag-retriever/files/rag/document_search.py +60 -0
- package/recipes/backend/rag-retriever/files/rag/embeddings.py +91 -0
- package/recipes/backend/rag-retriever/files/rag/factory.py +82 -0
- package/recipes/backend/rag-retriever/files/rag/in_memory.py +52 -0
- package/recipes/backend/rag-retriever/files/rag/models.py +107 -0
- package/recipes/backend/rag-retriever/files/rag/pgvector.py +138 -0
- package/recipes/backend/rag-retriever/files/rag/qdrant.py +96 -0
- package/recipes/backend/rag-retriever/files/rag/settings.py +48 -0
- package/recipes/backend/rag-retriever/files/tests/__init__.py +0 -0
- package/recipes/backend/rag-retriever/files/tests/rag_conformance.py +95 -0
- package/recipes/backend/rag-retriever/files/tests/test_rag.py +270 -0
- package/recipes/backend/rate-limit-quota/RECIPE.md +77 -0
- package/recipes/backend/rate-limit-quota/files/api/agent/guards.py +62 -0
- package/recipes/backend/rate-limit-quota/files/api/limits/__init__.py +0 -0
- package/recipes/backend/rate-limit-quota/files/api/limits/router.py +38 -0
- package/recipes/backend/rate-limit-quota/files/limits/__init__.py +43 -0
- package/recipes/backend/rate-limit-quota/files/limits/base.py +161 -0
- package/recipes/backend/rate-limit-quota/files/limits/factory.py +69 -0
- package/recipes/backend/rate-limit-quota/files/limits/in_memory.py +36 -0
- package/recipes/backend/rate-limit-quota/files/limits/models.py +108 -0
- package/recipes/backend/rate-limit-quota/files/limits/settings.py +32 -0
- package/recipes/backend/rate-limit-quota/files/limits/sql.py +94 -0
- package/recipes/backend/rate-limit-quota/files/pytest.ini +5 -0
- package/recipes/backend/rate-limit-quota/files/tests/limits_conformance.py +146 -0
- package/recipes/backend/rate-limit-quota/files/tests/test_limits.py +167 -0
- package/recipes/backend/rate-limit-quota/files/tests/test_limits_api.py +100 -0
- package/recipes/backend/voice-providers/RECIPE.md +73 -0
- package/recipes/backend/voice-providers/files/api/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/api/voice/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/api/voice/router.py +113 -0
- package/recipes/backend/voice-providers/files/pytest.ini +5 -0
- package/recipes/backend/voice-providers/files/tests/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/tests/fake_openai.py +44 -0
- package/recipes/backend/voice-providers/files/tests/test_voice.py +164 -0
- package/recipes/backend/voice-providers/files/tests/test_voice_api.py +106 -0
- package/recipes/backend/voice-providers/files/tests/voice_conformance.py +80 -0
- package/recipes/backend/voice-providers/files/voice/__init__.py +29 -0
- package/recipes/backend/voice-providers/files/voice/base.py +116 -0
- package/recipes/backend/voice-providers/files/voice/factory.py +48 -0
- package/recipes/backend/voice-providers/files/voice/fake.py +51 -0
- package/recipes/backend/voice-providers/files/voice/models.py +85 -0
- package/recipes/backend/voice-providers/files/voice/openai_provider.py +116 -0
- package/recipes/backend/voice-providers/files/voice/settings.py +48 -0
- package/recipes/frontend/.gitkeep +0 -0
- package/recipes/frontend/playwright-e2e/RECIPE.md +48 -0
- package/recipes/frontend/playwright-e2e/files/.github/workflows/frontend.yml +35 -0
- package/recipes/frontend/playwright-e2e/files/e2e/helpers.ts +25 -0
- package/recipes/frontend/playwright-e2e/files/e2e/home.spec.ts +10 -0
- package/recipes/frontend/playwright-e2e/files/e2e/login.spec.ts +26 -0
- package/recipes/frontend/playwright-e2e/files/e2e/navigation.spec.ts +27 -0
- package/recipes/frontend/playwright-e2e/files/playwright.config.ts +35 -0
- package/recipes/frontend/react-agent-chat/RECIPE.md +69 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat-api.ts +27 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.css +18 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.test.tsx +139 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/ChatView.tsx +22 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Composer.tsx +40 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Markdown.tsx +20 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/MessageList.tsx +42 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/events.ts +42 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/fake-chat-api.ts +44 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/index.ts +6 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.test.ts +97 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.ts +85 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/use-chat.ts +136 -0
- package/recipes/frontend/react-app-router/RECIPE.md +58 -0
- package/recipes/frontend/react-app-router/files/src/App.test.tsx +54 -0
- package/recipes/frontend/react-app-router/files/src/App.tsx +14 -0
- package/recipes/frontend/react-app-router/files/src/router/ErrorScreen.tsx +21 -0
- package/recipes/frontend/react-app-router/files/src/router/Layout.tsx +28 -0
- package/recipes/frontend/react-app-router/files/src/router/NotFoundScreen.tsx +12 -0
- package/recipes/frontend/react-app-router/files/src/router/index.ts +1 -0
- package/recipes/frontend/react-app-router/files/src/router/router.css +29 -0
- package/recipes/frontend/react-app-router/files/src/router/router.test.tsx +65 -0
- package/recipes/frontend/react-app-router/files/src/router/routes.tsx +59 -0
- package/recipes/frontend/react-app-router/files/src/screens/SettingsScreen.tsx +10 -0
- package/recipes/frontend/react-supabase-auth/RECIPE.md +77 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/LoginScreen.tsx +64 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/SignOutButton.tsx +12 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.css +33 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.test.ts +149 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.ts +59 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/fake-auth.ts +87 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/fake-gotrue.ts +85 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/index.ts +7 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/make-auth.ts +20 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session-context.tsx +35 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session-store.ts +63 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session.test.tsx +56 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/settings.ts +30 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/supabase-auth.ts +85 -0
- package/recipes/frontend/vite-react-base/RECIPE.md +69 -0
- package/recipes/frontend/vite-react-base/files/.env +6 -0
- package/recipes/frontend/vite-react-base/files/.env.fake +2 -0
- package/recipes/frontend/vite-react-base/files/index.html +12 -0
- package/recipes/frontend/vite-react-base/files/package.json +30 -0
- package/recipes/frontend/vite-react-base/files/src/App.test.tsx +49 -0
- package/recipes/frontend/vite-react-base/files/src/App.tsx +13 -0
- package/recipes/frontend/vite-react-base/files/src/api/api.ts +37 -0
- package/recipes/frontend/vite-react-base/files/src/api/fake/fake-api.ts +29 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-api.ts +16 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-client.test.ts +84 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-client.ts +94 -0
- package/recipes/frontend/vite-react-base/files/src/api/make-api.ts +30 -0
- package/recipes/frontend/vite-react-base/files/src/api/types.ts +7 -0
- package/recipes/frontend/vite-react-base/files/src/app-context.tsx +24 -0
- package/recipes/frontend/vite-react-base/files/src/auth/token-provider.ts +27 -0
- package/recipes/frontend/vite-react-base/files/src/config.ts +18 -0
- package/recipes/frontend/vite-react-base/files/src/hooks/use-load.ts +46 -0
- package/recipes/frontend/vite-react-base/files/src/main.tsx +27 -0
- package/recipes/frontend/vite-react-base/files/src/screens/HomeScreen.tsx +28 -0
- package/recipes/frontend/vite-react-base/files/src/styles/global.css +25 -0
- package/recipes/frontend/vite-react-base/files/src/styles/tokens.css +33 -0
- package/recipes/frontend/vite-react-base/files/src/styles/tokens.test.ts +45 -0
- package/recipes/frontend/vite-react-base/files/src/test-setup.ts +8 -0
- package/recipes/frontend/vite-react-base/files/src/vite-env.d.ts +11 -0
- package/recipes/frontend/vite-react-base/files/tsconfig.json +18 -0
- package/recipes/frontend/vite-react-base/files/vite.config.ts +19 -0
- package/unpacked-files.json +3 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `Auth` on supabase-js. The client persists the session in localStorage (`sb-<ref>-auth-token`) and
|
|
3
|
+
* refreshes the token on its own before it expires; `refresh()` is the explicit path the HTTP client takes
|
|
4
|
+
* after a 401. Loaded with a dynamic import by `makeAuth`, so the fake build never ships supabase-js.
|
|
5
|
+
*
|
|
6
|
+
* `fetcher` is the test seam: the tests run the real supabase-js against a fake GoTrue (see fake-gotrue.ts).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { createClient, isAuthApiError, type Session as SupabaseSession, type SupabaseClient } from '@supabase/supabase-js'
|
|
10
|
+
|
|
11
|
+
import { AuthError, type Auth, type AuthErrorCode, type Session } from './auth'
|
|
12
|
+
|
|
13
|
+
export type SupabaseAuthOptions = {
|
|
14
|
+
url: string
|
|
15
|
+
anonKey: string
|
|
16
|
+
fetcher?: typeof fetch
|
|
17
|
+
storage?: Storage
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function createSupabaseAuth(options: SupabaseAuthOptions): Auth {
|
|
21
|
+
const client: SupabaseClient = createClient(options.url, options.anonKey, {
|
|
22
|
+
auth: {
|
|
23
|
+
persistSession: true,
|
|
24
|
+
autoRefreshToken: true,
|
|
25
|
+
detectSessionInUrl: false, // no OAuth/magic-link callback in this recipe
|
|
26
|
+
...(options.storage ? { storage: options.storage } : {}),
|
|
27
|
+
},
|
|
28
|
+
...(options.fetcher ? { global: { fetch: options.fetcher } } : {}),
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
async getSession() {
|
|
33
|
+
try {
|
|
34
|
+
return toSession((await client.auth.getSession()).data.session)
|
|
35
|
+
} catch {
|
|
36
|
+
return null
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
|
|
40
|
+
async signIn({ email, password }) {
|
|
41
|
+
const { data, error } = await client.auth.signInWithPassword({ email: email.trim(), password })
|
|
42
|
+
if (error) throw new AuthError(codeOf(error), error)
|
|
43
|
+
const session = toSession(data.session)
|
|
44
|
+
if (!session) throw new AuthError('unavailable')
|
|
45
|
+
return session
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
async signOut() {
|
|
49
|
+
// Clears localStorage at once; the request to GoTrue is a courtesy (the token expires anyway).
|
|
50
|
+
await client.auth.signOut({ scope: 'local' }).catch(() => undefined)
|
|
51
|
+
},
|
|
52
|
+
|
|
53
|
+
async refresh() {
|
|
54
|
+
try {
|
|
55
|
+
const { data, error } = await client.auth.refreshSession()
|
|
56
|
+
if (error) {
|
|
57
|
+
// A rejected refresh token = the session is over. A network failure is not: keep the session.
|
|
58
|
+
if (isAuthApiError(error)) await client.auth.signOut({ scope: 'local' }).catch(() => undefined)
|
|
59
|
+
return null
|
|
60
|
+
}
|
|
61
|
+
return toSession(data.session)
|
|
62
|
+
} catch {
|
|
63
|
+
return null
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
|
|
67
|
+
onChange(listener) {
|
|
68
|
+
const { data } = client.auth.onAuthStateChange((_event, session) => listener(toSession(session)))
|
|
69
|
+
return () => data.subscription.unsubscribe()
|
|
70
|
+
},
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function toSession(session: SupabaseSession | null): Session | null {
|
|
75
|
+
if (!session?.access_token) return null
|
|
76
|
+
return { accessToken: session.access_token, user: { id: session.user.id, email: session.user.email ?? '' } }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Only the code leaves this module: supabase's message is kept as `cause`, not shown. */
|
|
80
|
+
function codeOf(error: { status?: number; code?: string }): AuthErrorCode {
|
|
81
|
+
if (error.code === 'email_not_confirmed') return 'email_not_confirmed'
|
|
82
|
+
if (error.status === 429) return 'rate_limited'
|
|
83
|
+
if (error.code === 'invalid_credentials' || error.status === 400 || error.status === 401) return 'invalid_credentials'
|
|
84
|
+
return 'unavailable'
|
|
85
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# vite-react-base
|
|
2
|
+
|
|
3
|
+
## Cuándo usarla
|
|
4
|
+
|
|
5
|
+
Para el **frontend de una app con backend propio en Python** (FastAPI): una SPA de Vite + React + TypeScript que llama directamente a la API. No sirve si necesitas SSR o SEO; en ese caso, Next.js.
|
|
6
|
+
|
|
7
|
+
No depende de otras recetas.
|
|
8
|
+
|
|
9
|
+
## Qué incluye
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
package.json scripts: dev, dev:fake, build (tsc + vite), preview, typecheck, test
|
|
13
|
+
vite.config.ts proxy /api → backend en dev y preview (BACKEND_URL); config de Vitest
|
|
14
|
+
tsconfig.json strict, noUnused*
|
|
15
|
+
index.html
|
|
16
|
+
.env defaults públicos: VITE_API_MODE=http, VITE_API_URL=/api
|
|
17
|
+
.env.fake VITE_API_MODE=fake (npm run dev:fake)
|
|
18
|
+
src/
|
|
19
|
+
main.tsx arranque: lee la config → construye los servicios con la factory → render
|
|
20
|
+
config.ts CONFIG: el ÚNICO sitio que lee import.meta.env
|
|
21
|
+
vite-env.d.ts tipos de las VITE_*
|
|
22
|
+
App.tsx raíz: recibe sus servicios desde fuera
|
|
23
|
+
app-context.tsx AppServices + useApp() (los servicios llegan por contexto)
|
|
24
|
+
api/
|
|
25
|
+
api.ts type Api (el contrato) + ApiError + NetworkError
|
|
26
|
+
types.ts tipos de los datos que se intercambian con el backend
|
|
27
|
+
http-client.ts createHttpClient: base URL, Bearer, refresh y reintento en 401, errores tipados, stream()
|
|
28
|
+
http-api.ts createHttpApi(client): Api real (pasa de snake_case a camelCase)
|
|
29
|
+
fake/fake-api.ts createFakeApi(): Api en memoria
|
|
30
|
+
make-api.ts makeApi({mode}): factory que elige entre http y fake
|
|
31
|
+
auth/token-provider.ts TokenProvider (de dónde sale el token) + noAuth + staticToken
|
|
32
|
+
hooks/use-load.ts useLoad(load, deps): {data, loading, error, reload}, descarta respuestas obsoletas
|
|
33
|
+
screens/HomeScreen.tsx pantalla de ejemplo con sus tres estados
|
|
34
|
+
styles/tokens.css variables de diseño (claro y oscuro)
|
|
35
|
+
styles/global.css
|
|
36
|
+
test-setup.ts
|
|
37
|
+
*.test.ts(x) 23 tests: cliente HTTP, factory, App con el fake, contraste WCAG de los tokens
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Decisiones
|
|
41
|
+
|
|
42
|
+
- **Vite + React y no Next.js.** El backend ya es Python. Next añadiría un servidor Node en medio.
|
|
43
|
+
- **La API es un tipo con dos implementaciones.** `Api` define el contrato, y `createHttpApi` y `createFakeApi` lo cumplen. El fake usa `satisfies Api`, así que el compilador avisa si le falta un método. Ningún componente llama a `fetch`.
|
|
44
|
+
- **El backend se elige en la configuración.** `VITE_API_MODE=http|fake` y `makeApi` construye la implementación. Pasar a fake (para una demo, un e2e o trabajar sin backend) es cambiar una variable: `npm run dev:fake`. Un valor desconocido lanza un error, nunca un valor por defecto silencioso. El fake se carga con `import()`, así que es un chunk aparte que la app en modo `http` nunca descarga.
|
|
45
|
+
- **Los servicios llegan por contexto** (`useApp()`), no importando singletons. Así los tests montan los mismos componentes con un fake.
|
|
46
|
+
- **Cliente HTTP inyectable.** `fetcher` y `tokens` entran por opciones, así que se prueba sin red.
|
|
47
|
+
- En un 401 renueva el token una sola vez y reintenta. Si sigue fallando, llama a `onSessionExpired`.
|
|
48
|
+
- Errores: `ApiError(status, code)` lee tanto `{"error": {"code"}}` como el `{"detail"}` de FastAPI. `NetworkError` cubre el caso sin conexión o un 5xx sin cuerpo.
|
|
49
|
+
- Cancelar no se considera un error.
|
|
50
|
+
- **La auth queda detrás de `TokenProvider`.** Supabase, un JWT propio o nada: se cambia sin tocar el cliente. Hay un ejemplo con Supabase en el propio archivo.
|
|
51
|
+
- **El proxy de Vite** reenvía `/api` al backend: en desarrollo no hay CORS y el SSE pasa sin cambios. En producción, sirve el frontend en el mismo dominio que la API o cambia `VITE_API_URL`.
|
|
52
|
+
- **CSS con variables de diseño, sin framework.** Hay un test que comprueba el contraste WCAG AA de los pares texto/fondo.
|
|
53
|
+
- **Sin router ni librería de estado.** No había un patrón común en los proyectos de origen. Si lo necesitas, añade `react-router`.
|
|
54
|
+
|
|
55
|
+
## Cómo adaptarla
|
|
56
|
+
|
|
57
|
+
1. Copia `files/` a `frontend/`. Sustituye `{{app_name}}` en `package.json`, `index.html` y `src/config.ts`. Después ejecuta `npm install`.
|
|
58
|
+
2. **Endpoints:** para añadir uno, pon el método en `Api` (`api/api.ts`), su tipo en `types.ts` y su implementación en `http-api.ts` y en `fake/fake-api.ts`. Si crecen mucho, sepáralos por grupos: `http-api.users.ts` devuelve un `Pick<Api, ...>`.
|
|
59
|
+
3. **Auth:** escribe tu `TokenProvider` y pásalo en `main.tsx`. Que `onSessionExpired` lleve al login.
|
|
60
|
+
4. **Pantallas:** en `screens/` o en `features/<nombre>/`. Usa `useApp()` y `useLoad()`.
|
|
61
|
+
5. **Estilos:** cambia los valores de `tokens.css`. Si añades pares de color, inclúyelos en `tokens.test.ts`.
|
|
62
|
+
6. Desarrollo: `npm run dev` (con el backend en `BACKEND_URL`, por defecto `127.0.0.1:8000`) o `npm run dev:fake`. Para comprobar todo: `npm run typecheck && npm test && npm run build`.
|
|
63
|
+
|
|
64
|
+
**Dependencias** (probado con vite 8.3.8, react 19.3.1, typescript 7.0.2 y vitest 5.1.0): ya están en `package.json`.
|
|
65
|
+
|
|
66
|
+
## Origen
|
|
67
|
+
|
|
68
|
+
- Probado en producción: interfaz `Api` con implementaciones HTTP y falsa, elegida en el arranque y con el fake cargado por `import()`; servicios por contexto; cliente con dependencias inyectadas que renueva el token una vez en 401 y reintenta; `ApiError` y `NetworkError`; `useLoad`; variables de diseño con test de contraste; proxy de Vite.
|
|
69
|
+
- Nuevo en esta receta: `TokenProvider` y el error por modo desconocido, siguiendo la regla de no tener valores por defecto de los backends Python.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
# Committed defaults (public: only VITE_* vars reach the browser, never put secrets here). Override locally in .env.local.
|
|
2
|
+
|
|
3
|
+
# http | fake. `fake` runs the whole app without backend (demos, e2e, frontend-only work).
|
|
4
|
+
VITE_API_MODE=http
|
|
5
|
+
# Base URL of the backend API. Relative ("/api") uses the Vite proxy in dev and the same origin in prod.
|
|
6
|
+
VITE_API_URL=/api
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="es">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
|
+
<title>{{app_name}}</title>
|
|
7
|
+
</head>
|
|
8
|
+
<body>
|
|
9
|
+
<div id="root"></div>
|
|
10
|
+
<script type="module" src="/src/main.tsx"></script>
|
|
11
|
+
</body>
|
|
12
|
+
</html>
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "{{app_name}}-frontend",
|
|
3
|
+
"private": true,
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"dev": "vite --host",
|
|
8
|
+
"dev:fake": "vite --host --mode fake",
|
|
9
|
+
"build": "tsc --noEmit && vite build",
|
|
10
|
+
"preview": "vite preview --host",
|
|
11
|
+
"typecheck": "tsc --noEmit",
|
|
12
|
+
"test": "vitest run"
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"react": "^19.3.1",
|
|
16
|
+
"react-dom": "^19.3.1"
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"@testing-library/react": "^16.3.3",
|
|
20
|
+
"@testing-library/user-event": "^14.6.9",
|
|
21
|
+
"@types/node": "^24.0.0",
|
|
22
|
+
"@types/react": "^19.3.0",
|
|
23
|
+
"@types/react-dom": "^19.3.0",
|
|
24
|
+
"@vitejs/plugin-react": "^6.3.0",
|
|
25
|
+
"jsdom": "^31.0.0",
|
|
26
|
+
"typescript": "^7.0.2",
|
|
27
|
+
"vite": "^8.3.8",
|
|
28
|
+
"vitest": "^5.1.0"
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { render, screen } from '@testing-library/react'
|
|
2
|
+
import userEvent from '@testing-library/user-event'
|
|
3
|
+
import { describe, expect, it } from 'vitest'
|
|
4
|
+
|
|
5
|
+
import { App } from './App'
|
|
6
|
+
import { ApiError, NetworkError, type Api } from './api/api'
|
|
7
|
+
import { createFakeApi } from './api/fake/fake-api'
|
|
8
|
+
import { makeApi } from './api/make-api'
|
|
9
|
+
|
|
10
|
+
describe('App with the fake api', () => {
|
|
11
|
+
it('renders data loaded through the context', async () => {
|
|
12
|
+
render(<App services={{ api: createFakeApi({ latencyMs: 0 }) }} />)
|
|
13
|
+
|
|
14
|
+
expect(await screen.findByRole('heading', { name: 'Hola, Demo User' })).toBeTruthy()
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
it('shows an error by code and retries', async () => {
|
|
18
|
+
let calls = 0
|
|
19
|
+
const api: Api = {
|
|
20
|
+
...createFakeApi({ latencyMs: 0 }),
|
|
21
|
+
me: async () => {
|
|
22
|
+
calls += 1
|
|
23
|
+
if (calls === 1) throw new ApiError(403, 'forbidden')
|
|
24
|
+
return { userId: 'u', tenantId: 't', name: 'Ana' }
|
|
25
|
+
},
|
|
26
|
+
}
|
|
27
|
+
render(<App services={{ api }} />)
|
|
28
|
+
|
|
29
|
+
expect((await screen.findByRole('alert')).textContent).toContain('forbidden')
|
|
30
|
+
await userEvent.click(screen.getByRole('button', { name: 'Reintentar' }))
|
|
31
|
+
expect(await screen.findByRole('heading', { name: 'Hola, Ana' })).toBeTruthy()
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('tells offline apart from an API error', async () => {
|
|
35
|
+
const api: Api = { me: async () => Promise.reject(new NetworkError()) }
|
|
36
|
+
render(<App services={{ api }} />)
|
|
37
|
+
expect((await screen.findByRole('alert')).textContent).toContain('Sin conexión')
|
|
38
|
+
})
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
describe('makeApi factory', () => {
|
|
42
|
+
it('builds the implementation the settings name', async () => {
|
|
43
|
+
const fake = await makeApi({ mode: 'fake', apiUrl: '/api' })
|
|
44
|
+
expect(await fake.me()).toMatchObject({ name: 'Demo User' })
|
|
45
|
+
|
|
46
|
+
const http = await makeApi({ mode: 'http', apiUrl: '/api' })
|
|
47
|
+
expect(typeof http.me).toBe('function')
|
|
48
|
+
})
|
|
49
|
+
})
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { AppProvider, type AppServices } from './app-context'
|
|
2
|
+
import { HomeScreen } from './screens/HomeScreen'
|
|
3
|
+
|
|
4
|
+
/** Root component. Gets its services from outside (main.tsx or a test), so it never builds an Api itself. */
|
|
5
|
+
export function App({ services }: { services: AppServices }) {
|
|
6
|
+
return (
|
|
7
|
+
<AppProvider services={services}>
|
|
8
|
+
<main className="layout">
|
|
9
|
+
<HomeScreen />
|
|
10
|
+
</main>
|
|
11
|
+
</AppProvider>
|
|
12
|
+
)
|
|
13
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The API contract of the app. Components only know this type; never `fetch`.
|
|
3
|
+
*
|
|
4
|
+
* Two implementations satisfy it: `createHttpApi` (the real backend) and `createFakeApi` (in memory).
|
|
5
|
+
* `makeApi` picks one from the settings (VITE_API_MODE). Add an endpoint = a method here, then in both.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { Identity } from './types'
|
|
9
|
+
|
|
10
|
+
/** The backend answered with an error status. `code` is stable and machine-readable; show messages by code. */
|
|
11
|
+
export class ApiError extends Error {
|
|
12
|
+
constructor(
|
|
13
|
+
readonly status: number,
|
|
14
|
+
readonly code: string,
|
|
15
|
+
readonly details?: unknown,
|
|
16
|
+
) {
|
|
17
|
+
super(`API error ${status}: ${code}`)
|
|
18
|
+
this.name = 'ApiError'
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
get isUnauthorized(): boolean {
|
|
22
|
+
return this.status === 401
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The request never got an answer (offline, DNS, CORS, 5xx without body). Usually worth a retry. */
|
|
27
|
+
export class NetworkError extends Error {
|
|
28
|
+
constructor(readonly cause?: unknown) {
|
|
29
|
+
super('Network error')
|
|
30
|
+
this.name = 'NetworkError'
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type Api = {
|
|
35
|
+
/** Who is signed in. */
|
|
36
|
+
me(): Promise<Identity>
|
|
37
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-memory implementation of `Api`: the app runs with no backend (VITE_API_MODE=fake).
|
|
3
|
+
* Used by demos, tests and e2e. Loaded with a dynamic import: it is a separate chunk that an `http` app never downloads.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { Api } from '../api'
|
|
7
|
+
import type { Identity } from '../types'
|
|
8
|
+
|
|
9
|
+
export type FakeApiOptions = {
|
|
10
|
+
/** Simulated latency in ms. 0 in tests. */
|
|
11
|
+
latencyMs?: number
|
|
12
|
+
identity?: Identity
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const FAKE_IDENTITY: Identity = { userId: 'user-1', tenantId: 'tenant-1', name: 'Demo User' }
|
|
16
|
+
|
|
17
|
+
export function createFakeApi(options: FakeApiOptions = {}): Api {
|
|
18
|
+
const { latencyMs = 200, identity = FAKE_IDENTITY } = options
|
|
19
|
+
const wait = () => new Promise((resolve) => setTimeout(resolve, latencyMs))
|
|
20
|
+
|
|
21
|
+
// `satisfies` (not `as`): the compiler fails if the fake misses a method of Api.
|
|
22
|
+
const api = {
|
|
23
|
+
async me() {
|
|
24
|
+
await wait()
|
|
25
|
+
return identity
|
|
26
|
+
},
|
|
27
|
+
} satisfies Api
|
|
28
|
+
return api
|
|
29
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** The real implementation of `Api`, over the HTTP client. Maps backend payloads (snake_case) to app types. */
|
|
2
|
+
|
|
3
|
+
import type { Api } from './api'
|
|
4
|
+
import type { HttpClient } from './http-client'
|
|
5
|
+
import type { Identity } from './types'
|
|
6
|
+
|
|
7
|
+
type IdentityBody = { user_id: string; tenant_id: string; name: string }
|
|
8
|
+
|
|
9
|
+
export function createHttpApi(client: HttpClient): Api {
|
|
10
|
+
return {
|
|
11
|
+
async me(): Promise<Identity> {
|
|
12
|
+
const body = await client.get<IdentityBody>('/me')
|
|
13
|
+
return { userId: body.user_id, tenantId: body.tenant_id, name: body.name }
|
|
14
|
+
},
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { describe, expect, it, vi, type Mock } from 'vitest'
|
|
2
|
+
|
|
3
|
+
import type { TokenProvider } from '../auth/token-provider'
|
|
4
|
+
import { staticToken } from '../auth/token-provider'
|
|
5
|
+
import { ApiError, NetworkError } from './api'
|
|
6
|
+
import { createHttpApi } from './http-api'
|
|
7
|
+
import { createHttpClient } from './http-client'
|
|
8
|
+
|
|
9
|
+
const json = (status: number, body?: unknown) =>
|
|
10
|
+
new Response(body === undefined ? null : JSON.stringify(body), {
|
|
11
|
+
status,
|
|
12
|
+
headers: { 'Content-Type': 'application/json' },
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
function clientWith(answers: Response[], tokens: TokenProvider = staticToken('t1'), onSessionExpired = vi.fn()) {
|
|
16
|
+
const fetcher = vi.fn<typeof fetch>(async () => answers.shift() ?? json(500))
|
|
17
|
+
const client = createHttpClient({ baseUrl: '/api', tokens, fetcher, onSessionExpired })
|
|
18
|
+
return { client, fetcher, onSessionExpired }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const authHeader = (fetcher: Mock<typeof fetch>, call: number) =>
|
|
22
|
+
(fetcher.mock.calls[call][1] as RequestInit & { headers: Record<string, string> }).headers.Authorization
|
|
23
|
+
|
|
24
|
+
describe('http client', () => {
|
|
25
|
+
it('sends the bearer token and parses json', async () => {
|
|
26
|
+
const { client, fetcher } = clientWith([json(200, { ok: true })])
|
|
27
|
+
|
|
28
|
+
expect(await client.get('/ping')).toEqual({ ok: true })
|
|
29
|
+
expect(fetcher.mock.calls[0][0]).toBe('/api/ping')
|
|
30
|
+
expect(authHeader(fetcher, 0)).toBe('Bearer t1')
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('refreshes once on 401 and retries with the new token', async () => {
|
|
34
|
+
const tokens: TokenProvider = { getToken: async () => 'old', refresh: async () => 'new' }
|
|
35
|
+
const { client, fetcher, onSessionExpired } = clientWith([json(401), json(200, { ok: 1 })], tokens)
|
|
36
|
+
|
|
37
|
+
expect(await client.get('/x')).toEqual({ ok: 1 })
|
|
38
|
+
expect(fetcher).toHaveBeenCalledTimes(2)
|
|
39
|
+
expect(authHeader(fetcher, 1)).toBe('Bearer new')
|
|
40
|
+
expect(onSessionExpired).not.toHaveBeenCalled()
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('reports the session as expired when the refresh does not help', async () => {
|
|
44
|
+
const { client, onSessionExpired } = clientWith([json(401)])
|
|
45
|
+
|
|
46
|
+
await expect(client.get('/x')).rejects.toMatchObject({ status: 401 })
|
|
47
|
+
expect(onSessionExpired).toHaveBeenCalledOnce()
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it('maps error bodies to ApiError codes (own format and FastAPI detail)', async () => {
|
|
51
|
+
const { client } = clientWith([
|
|
52
|
+
json(409, { error: { code: 'already_exists', details: { id: 1 } } }),
|
|
53
|
+
json(429, { detail: { code: 'quota_exceeded' } }),
|
|
54
|
+
json(422, { detail: 'bad input' }),
|
|
55
|
+
])
|
|
56
|
+
|
|
57
|
+
await expect(client.post('/a', {})).rejects.toEqual(new ApiError(409, 'already_exists', { id: 1 }))
|
|
58
|
+
await expect(client.post('/b', {})).rejects.toMatchObject({ code: 'quota_exceeded' })
|
|
59
|
+
await expect(client.post('/c', {})).rejects.toMatchObject({ code: 'http_422', details: 'bad input' })
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('turns a failed fetch and an unreadable 5xx into NetworkError', async () => {
|
|
63
|
+
const offline = createHttpClient({ baseUrl: '', fetcher: async () => Promise.reject(new TypeError('offline')) })
|
|
64
|
+
await expect(offline.get('/x')).rejects.toBeInstanceOf(NetworkError)
|
|
65
|
+
|
|
66
|
+
const { client } = clientWith([new Response('<html>bad gateway</html>', { status: 502 })])
|
|
67
|
+
await expect(client.get('/x')).rejects.toBeInstanceOf(NetworkError)
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
it('does not turn a cancel into a NetworkError', async () => {
|
|
71
|
+
const controller = new AbortController()
|
|
72
|
+
const fetcher = async () => {
|
|
73
|
+
controller.abort()
|
|
74
|
+
throw new DOMException('aborted', 'AbortError')
|
|
75
|
+
}
|
|
76
|
+
const client = createHttpClient({ baseUrl: '', fetcher })
|
|
77
|
+
await expect(client.get('/x', controller.signal)).rejects.toMatchObject({ name: 'AbortError' })
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
it('http api maps snake_case payloads to app types', async () => {
|
|
81
|
+
const { client } = clientWith([json(200, { user_id: 'u', tenant_id: 't', name: 'Ana' })])
|
|
82
|
+
expect(await createHttpApi(client).me()).toEqual({ userId: 'u', tenantId: 't', name: 'Ana' })
|
|
83
|
+
})
|
|
84
|
+
})
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Low-level HTTP client: base URL, bearer token, one refresh-and-retry on 401, typed errors.
|
|
3
|
+
* Every dependency comes in by option (`fetcher`, `tokens`), so it is tested without a network.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { TokenProvider } from '../auth/token-provider'
|
|
7
|
+
import { noAuth } from '../auth/token-provider'
|
|
8
|
+
import { ApiError, NetworkError } from './api'
|
|
9
|
+
|
|
10
|
+
export type HttpClientOptions = {
|
|
11
|
+
baseUrl: string
|
|
12
|
+
tokens?: TokenProvider
|
|
13
|
+
/** Called once when a 401 survives the refresh: sign out, go to login... */
|
|
14
|
+
onSessionExpired?: () => void
|
|
15
|
+
fetcher?: typeof fetch
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
|
|
19
|
+
|
|
20
|
+
export function createHttpClient(options: HttpClientOptions) {
|
|
21
|
+
const { baseUrl, tokens = noAuth, onSessionExpired } = options
|
|
22
|
+
const fetcher = options.fetcher ?? ((input, init) => fetch(input, init))
|
|
23
|
+
|
|
24
|
+
async function send(method: Method, path: string, body: unknown, signal: AbortSignal | undefined, token: string | null) {
|
|
25
|
+
const headers: Record<string, string> = { Accept: 'application/json' }
|
|
26
|
+
if (body !== undefined) headers['Content-Type'] = 'application/json'
|
|
27
|
+
if (token) headers.Authorization = `Bearer ${token}`
|
|
28
|
+
try {
|
|
29
|
+
return await fetcher(`${baseUrl}${path}`, {
|
|
30
|
+
method,
|
|
31
|
+
headers,
|
|
32
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
33
|
+
signal,
|
|
34
|
+
})
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if (signal?.aborted) throw error // a cancel is not a network failure
|
|
37
|
+
throw new NetworkError(error)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Sends the request; on 401 refreshes the token ONCE and retries. Returns only 2xx responses. */
|
|
42
|
+
async function call(method: Method, path: string, body?: unknown, signal?: AbortSignal): Promise<Response> {
|
|
43
|
+
let response = await send(method, path, body, signal, await tokens.getToken())
|
|
44
|
+
if (response.status === 401) {
|
|
45
|
+
const fresh = await tokens.refresh()
|
|
46
|
+
if (fresh) response = await send(method, path, body, signal, fresh)
|
|
47
|
+
if (response.status === 401) onSessionExpired?.()
|
|
48
|
+
}
|
|
49
|
+
if (!response.ok) throw await toError(response)
|
|
50
|
+
return response
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function json<T>(method: Method, path: string, body?: unknown, signal?: AbortSignal): Promise<T> {
|
|
54
|
+
const response = await call(method, path, body, signal)
|
|
55
|
+
if (response.status === 204) return undefined as T
|
|
56
|
+
return (await response.json()) as T
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
get: <T>(path: string, signal?: AbortSignal) => json<T>('GET', path, undefined, signal),
|
|
61
|
+
post: <T>(path: string, body?: unknown, signal?: AbortSignal) => json<T>('POST', path, body, signal),
|
|
62
|
+
put: <T>(path: string, body?: unknown, signal?: AbortSignal) => json<T>('PUT', path, body, signal),
|
|
63
|
+
patch: <T>(path: string, body?: unknown, signal?: AbortSignal) => json<T>('PATCH', path, body, signal),
|
|
64
|
+
delete: <T>(path: string, signal?: AbortSignal) => json<T>('DELETE', path, undefined, signal),
|
|
65
|
+
/** POST that returns the raw body stream (SSE). Same auth and errors as the rest. */
|
|
66
|
+
stream: async (path: string, body: unknown, signal?: AbortSignal): Promise<ReadableStream<Uint8Array>> => {
|
|
67
|
+
const response = await call('POST', path, body, signal)
|
|
68
|
+
if (!response.body) throw new NetworkError('empty stream')
|
|
69
|
+
return response.body
|
|
70
|
+
},
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export type HttpClient = ReturnType<typeof createHttpClient>
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Error body: `{"error": {"code", "details"}}` or FastAPI's `{"detail": ...}`.
|
|
78
|
+
* A 5xx without a readable body is a NetworkError (a proxy or crash, not an answer of the API).
|
|
79
|
+
*/
|
|
80
|
+
async function toError(response: Response): Promise<Error> {
|
|
81
|
+
let body: unknown
|
|
82
|
+
try {
|
|
83
|
+
body = await response.json()
|
|
84
|
+
} catch {
|
|
85
|
+
if (response.status >= 500) return new NetworkError(`HTTP ${response.status}`)
|
|
86
|
+
return new ApiError(response.status, `http_${response.status}`)
|
|
87
|
+
}
|
|
88
|
+
const record = (body ?? {}) as Record<string, unknown>
|
|
89
|
+
const error = record.error as { code?: string; details?: unknown } | undefined
|
|
90
|
+
if (error?.code) return new ApiError(response.status, error.code, error.details)
|
|
91
|
+
const detail = record.detail as { code?: string } | string | undefined
|
|
92
|
+
if (detail && typeof detail === 'object' && detail.code) return new ApiError(response.status, detail.code, detail)
|
|
93
|
+
return new ApiError(response.status, `http_${response.status}`, detail ?? body)
|
|
94
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Factory: builds the `Api` the settings name (VITE_API_MODE). Switching backend = changing a variable.
|
|
3
|
+
* The fake is a dynamic import: Vite emits it as a separate chunk that is only downloaded in `fake` mode.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { TokenProvider } from '../auth/token-provider'
|
|
7
|
+
import type { ApiMode } from '../config'
|
|
8
|
+
import type { Api } from './api'
|
|
9
|
+
import { createHttpApi } from './http-api'
|
|
10
|
+
import { createHttpClient } from './http-client'
|
|
11
|
+
|
|
12
|
+
export type MakeApiOptions = {
|
|
13
|
+
mode: ApiMode
|
|
14
|
+
apiUrl: string
|
|
15
|
+
tokens?: TokenProvider
|
|
16
|
+
onSessionExpired?: () => void
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function makeApi(options: MakeApiOptions): Promise<Api> {
|
|
20
|
+
switch (options.mode) {
|
|
21
|
+
case 'http':
|
|
22
|
+
return createHttpApi(
|
|
23
|
+
createHttpClient({ baseUrl: options.apiUrl, tokens: options.tokens, onSessionExpired: options.onSessionExpired }),
|
|
24
|
+
)
|
|
25
|
+
case 'fake': {
|
|
26
|
+
const { createFakeApi } = await import('./fake/fake-api')
|
|
27
|
+
return createFakeApi()
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* App services reach components through context, never through imports of singletons:
|
|
3
|
+
* tests render the same components with a fake `Api`.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { createContext, useContext, type ReactNode } from 'react'
|
|
7
|
+
|
|
8
|
+
import type { Api } from './api/api'
|
|
9
|
+
|
|
10
|
+
export type AppServices = {
|
|
11
|
+
api: Api
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const AppContext = createContext<AppServices | null>(null)
|
|
15
|
+
|
|
16
|
+
export function AppProvider({ services, children }: { services: AppServices; children: ReactNode }) {
|
|
17
|
+
return <AppContext.Provider value={services}>{children}</AppContext.Provider>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function useApp(): AppServices {
|
|
21
|
+
const services = useContext(AppContext)
|
|
22
|
+
if (!services) throw new Error('useApp() outside <AppProvider>')
|
|
23
|
+
return services
|
|
24
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the bearer token comes from. The HTTP client only knows this interface, so the auth
|
|
3
|
+
* system (Supabase, own JWT, none) is swapped without touching the client.
|
|
4
|
+
*
|
|
5
|
+
* Supabase, for example:
|
|
6
|
+
* const tokens: TokenProvider = {
|
|
7
|
+
* getToken: async () => (await supabase.auth.getSession()).data.session?.access_token ?? null,
|
|
8
|
+
* refresh: async () => (await supabase.auth.refreshSession()).data.session?.access_token ?? null,
|
|
9
|
+
* }
|
|
10
|
+
*/
|
|
11
|
+
export type TokenProvider = {
|
|
12
|
+
/** Current access token, or null when signed out. */
|
|
13
|
+
getToken(): Promise<string | null>
|
|
14
|
+
/** Try to get a fresh token after a 401. Null = the session is over. */
|
|
15
|
+
refresh(): Promise<string | null>
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** No auth (public API, or local dev without login). */
|
|
19
|
+
export const noAuth: TokenProvider = {
|
|
20
|
+
getToken: async () => null,
|
|
21
|
+
refresh: async () => null,
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** A fixed token. For tests and scripts. */
|
|
25
|
+
export function staticToken(token: string): TokenProvider {
|
|
26
|
+
return { getToken: async () => token, refresh: async () => null }
|
|
27
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Frontend settings: the ONLY place that reads `import.meta.env`.
|
|
3
|
+
* Values come from `.env*` files at build time (Vite inlines them), so they are public: no secrets.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export type ApiMode = 'http' | 'fake'
|
|
7
|
+
|
|
8
|
+
function apiMode(value: string | undefined): ApiMode {
|
|
9
|
+
if (value === 'http' || value === 'fake') return value
|
|
10
|
+
// No silent default: a typo in VITE_API_MODE must not ship a fake API to production.
|
|
11
|
+
throw new Error(`VITE_API_MODE must be "http" or "fake", got ${JSON.stringify(value)}`)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const CONFIG = {
|
|
15
|
+
appName: '{{app_name}}',
|
|
16
|
+
apiMode: apiMode(import.meta.env.VITE_API_MODE),
|
|
17
|
+
apiUrl: import.meta.env.VITE_API_URL ?? '/api',
|
|
18
|
+
} as const
|