oneie 2.0.1 → 2.0.3
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/AGENTS.md +245 -0
- package/CLAUDE.md +534 -0
- package/README.md +61 -4
- package/one/.obsidian/app.json +1 -0
- package/one/.obsidian/appearance.json +1 -0
- package/one/.obsidian/core-plugins.json +33 -0
- package/one/.obsidian/workspace.json +211 -0
- package/one/connections/a2a.md +551 -0
- package/one/connections/acp.md +761 -0
- package/one/connections/acps.md +731 -0
- package/one/connections/agui.md +767 -0
- package/one/connections/any-backend.md +1702 -0
- package/one/connections/ap2.md +998 -0
- package/one/connections/api-docs.md +1891 -0
- package/one/connections/api.md +2190 -0
- package/one/connections/architecture-diagram.md +94 -0
- package/one/connections/communications.md +449 -0
- package/one/connections/connections.md +339 -0
- package/one/connections/cryptonetworks.md +781 -0
- package/one/connections/documentation.md +1120 -0
- package/one/connections/effect.md +279 -0
- package/one/connections/elizaos.md +1290 -0
- package/one/connections/inference.md +58 -0
- package/one/connections/kyc.md +632 -0
- package/one/connections/mcp.md +842 -0
- package/one/connections/membership.md +1152 -0
- package/one/connections/middleware.md +1067 -0
- package/one/connections/multitenant.md +1341 -0
- package/one/connections/n8n.md +1015 -0
- package/one/connections/patterns.md +89 -0
- package/one/connections/protocols.md +279 -0
- package/one/connections/relationships.md +107 -0
- package/one/connections/schema.md +587 -0
- package/one/connections/service-layer.md +550 -0
- package/one/connections/structure.md +0 -0
- package/one/connections/vectors.md +207 -0
- package/one/connections/wordpress.md +1302 -0
- package/one/connections/workflow-copy.md +905 -0
- package/one/connections/workflow-examples.md +741 -0
- package/one/connections/workflow.md +905 -0
- package/one/connections/workflows/delegation.md +885 -0
- package/one/connections/workflows/frontend.md +1037 -0
- package/one/connections/workflows/strategy.md +903 -0
- package/one/connections/workflows/tasks.md +698 -0
- package/one/connections/x402.md +1249 -0
- package/one/events/events.md +545 -0
- package/one/knowledge/ai-platform.md +305 -0
- package/one/knowledge/architecture-diagram.md +94 -0
- package/one/knowledge/architecture-frontend.md +930 -0
- package/one/knowledge/architecture.md +2077 -0
- package/one/knowledge/crypto.md +960 -0
- package/one/knowledge/dsl.md +1660 -0
- package/one/knowledge/files.md +2471 -0
- package/one/knowledge/frontend.md +1038 -0
- package/one/knowledge/hono.md +2109 -0
- package/one/knowledge/implementation-examples.md +2536 -0
- package/one/knowledge/inference-score.md +159 -0
- package/one/knowledge/knowledge.md +642 -0
- package/one/knowledge/language.md +980 -0
- package/one/knowledge/lessons-learned.md +70 -0
- package/one/knowledge/ontology-6-dimensions.md +0 -0
- package/one/knowledge/ontology-documentation.md +356 -0
- package/one/knowledge/ontology-engineering-specification.md +1292 -0
- package/one/knowledge/ontology-engineering.md +1652 -0
- package/one/knowledge/ontology-frontend-copy-2.md +1492 -0
- package/one/knowledge/ontology-frontend-copy.md +753 -0
- package/one/knowledge/ontology-frontend-specifications.md +2188 -0
- package/one/knowledge/ontology-frontend.md +2427 -0
- package/one/knowledge/ontology-minimal.yaml +299 -0
- package/one/knowledge/ontology.md +2819 -0
- package/one/knowledge/ontology.yaml +1165 -0
- package/one/knowledge/patterns/backend/convex-mutation-pattern.md +100 -0
- package/one/knowledge/patterns/backend/convex-query-pattern.md +88 -0
- package/one/knowledge/patterns/backend/mutation-template.md +231 -0
- package/one/knowledge/patterns/backend/query-template.md +267 -0
- package/one/knowledge/patterns/backend/service-template.md +237 -0
- package/one/knowledge/patterns/design/component-architecture.md +399 -0
- package/one/knowledge/patterns/design/test-driven-design-pattern.md +162 -0
- package/one/knowledge/patterns/design/wireframe-template.md +216 -0
- package/one/knowledge/patterns/frontend/component-template.md +195 -0
- package/one/knowledge/patterns/frontend/form-template.md +276 -0
- package/one/knowledge/patterns/frontend/page-template.md +178 -0
- package/one/knowledge/patterns/frontend/react-component-pattern.md +128 -0
- package/one/knowledge/patterns/test/acceptance-criteria-template.md +378 -0
- package/one/knowledge/patterns/test/technical-test-template.md +544 -0
- package/one/knowledge/patterns/test/test-driven-pattern.md +140 -0
- package/one/knowledge/patterns/test/user-flow-template.md +254 -0
- package/one/knowledge/quality-loop.md +401 -0
- package/one/knowledge/readme.md +131 -0
- package/one/knowledge/rules.md +626 -0
- package/one/knowledge/score.md +67 -0
- package/one/knowledge/specifications.md +855 -0
- package/one/knowledge/tags.md +130 -0
- package/one/organisation/one.md +599 -0
- package/one/organisation/organisation.md +438 -0
- package/one/organisation/revenue.md +673 -0
- package/one/organisation/strategy.md +869 -0
- package/one/organisation/vision.md +98 -0
- package/one/people/anthony-o-connell.md +440 -0
- package/one/people/people.md +567 -0
- package/one/repomix-output.md +92634 -0
- package/one/things/agentkit.md +349 -0
- package/one/things/agents/agent-backend.md +1401 -0
- package/one/things/agents/agent-builder.md +955 -0
- package/one/things/agents/agent-clean.md +709 -0
- package/one/things/agents/agent-clone.md +1341 -0
- package/one/things/agents/agent-designer.md +2177 -0
- package/one/things/agents/agent-director.md +1508 -0
- package/one/things/agents/agent-documenter.md +1049 -0
- package/one/things/agents/agent-frontend.md +1119 -0
- package/one/things/agents/agent-integrator.md +1192 -0
- package/one/things/agents/agent-problem-solver.md +1379 -0
- package/one/things/agents/agent-quality.md +1353 -0
- package/one/things/agents/agent-sales.md +986 -0
- package/one/things/cascade/cascade.yaml +464 -0
- package/one/things/cascade/docs/examples/1-1-agent-prompts/design.md +470 -0
- package/one/things/cascade/docs/examples/1-1-agent-prompts/tests.md +264 -0
- package/one/things/cascade/docs/examples/1-1-agent-prompts.md +486 -0
- package/one/things/cascade/docs/examples/1-2-yaml-orchestrator/design.md +497 -0
- package/one/things/cascade/docs/examples/1-2-yaml-orchestrator/tests.md +227 -0
- package/one/things/cascade/docs/examples/1-2-yaml-orchestrator.md +516 -0
- package/one/things/cascade/docs/examples/1-3-event-coordination/design.md +544 -0
- package/one/things/cascade/docs/examples/1-3-event-coordination/tests.md +223 -0
- package/one/things/cascade/docs/examples/1-3-event-coordination.md +508 -0
- package/one/things/cascade/docs/examples/1-4-knowledge-management/design.md +609 -0
- package/one/things/cascade/docs/examples/1-4-knowledge-management/tests.md +195 -0
- package/one/things/cascade/docs/examples/1-4-knowledge-management.md +577 -0
- package/one/things/cascade/docs/examples/1-5-quality-loops/design.md +797 -0
- package/one/things/cascade/docs/examples/1-5-quality-loops/tests.md +212 -0
- package/one/things/cascade/docs/examples/1-5-quality-loops.md +641 -0
- package/one/things/cascade/docs/examples/1-6-numbering-structure/design.md +610 -0
- package/one/things/cascade/docs/examples/1-6-numbering-structure/tests.md +213 -0
- package/one/things/cascade/docs/examples/1-6-numbering-structure.md +575 -0
- package/one/things/cascade/docs/examples/readme.md +222 -0
- package/one/things/cascade/docs/getting-started.md +515 -0
- package/one/things/cascade/docs/workflow.md +1372 -0
- package/one/things/cascade/readme.md +336 -0
- package/one/things/cascade/templates/feature-template.md +267 -0
- package/one/things/claude/agents/advocacy-activation-manager.md +685 -0
- package/one/things/claude/agents/advocacy-campaign-designer.md +663 -0
- package/one/things/claude/agents/analyst.md +483 -0
- package/one/things/claude/agents/architect.md +480 -0
- package/one/things/claude/agents/brand-identity-specialist.md +513 -0
- package/one/things/claude/agents/bstp-token-strategist.md +667 -0
- package/one/things/claude/agents/builder-repo.md +489 -0
- package/one/things/claude/agents/bullstamp-community-builder.md +574 -0
- package/one/things/claude/agents/bullstamp-marketing-orchestrator.md +506 -0
- package/one/things/claude/agents/bulltilt-platform-growth.md +567 -0
- package/one/things/claude/agents/company-bullstamp-character.md +587 -0
- package/one/things/claude/agents/company-bullstamp-community.md +292 -0
- package/one/things/claude/agents/company-bullstamp-marketing.md +292 -0
- package/one/things/claude/agents/company-bullstamp-token.md +292 -0
- package/one/things/claude/agents/company-bulltilt-growth.md +292 -0
- package/one/things/claude/agents/content-bibliography-formatter.md +381 -0
- package/one/things/claude/agents/content-calendar-planner.md +448 -0
- package/one/things/claude/agents/content-chapter-formatter.md +488 -0
- package/one/things/claude/agents/content-formatter.md +546 -0
- package/one/things/claude/agents/content-hook-specialist.md +462 -0
- package/one/things/claude/agents/content-image-formatter.md +535 -0
- package/one/things/claude/agents/content-introduction-formatter.md +485 -0
- package/one/things/claude/agents/content-multiplication-engine.md +556 -0
- package/one/things/claude/agents/content-playbook-writer.md +448 -0
- package/one/things/claude/agents/content-team-manager.md +622 -0
- package/one/things/claude/agents/content-toc-formatter.md +522 -0
- package/one/things/claude/agents/convex-backend-specialist.md +2561 -0
- package/one/things/claude/agents/core-manager.md +582 -0
- package/one/things/claude/agents/core-master.md +403 -0
- package/one/things/claude/agents/cross-functional-manager.md +471 -0
- package/one/things/claude/agents/crypto-airdrop-strategist.md +602 -0
- package/one/things/claude/agents/crypto-analytics-educator.md +553 -0
- package/one/things/claude/agents/crypto-architecture-specialist.md +466 -0
- package/one/things/claude/agents/crypto-community-analyst.md +298 -0
- package/one/things/claude/agents/crypto-community-psychologist.md +509 -0
- package/one/things/claude/agents/crypto-dex-optimization-expert.md +538 -0
- package/one/things/claude/agents/crypto-dex-optimizer.md +292 -0
- package/one/things/claude/agents/crypto-diamond-formation-specialist.md +513 -0
- package/one/things/claude/agents/crypto-diamond-hands.md +292 -0
- package/one/things/claude/agents/crypto-ecosystem-expansion-manager.md +554 -0
- package/one/things/claude/agents/crypto-engagement-specialist.md +540 -0
- package/one/things/claude/agents/crypto-market-researcher.md +292 -0
- package/one/things/claude/agents/crypto-marketing-orchestrator.md +523 -0
- package/one/things/claude/agents/crypto-network-effect-amplifier.md +569 -0
- package/one/things/claude/agents/crypto-optimization-analyst.md +554 -0
- package/one/things/claude/agents/crypto-strategic-synthesizer.md +517 -0
- package/one/things/claude/agents/crypto-team-manager.md +387 -0
- package/one/things/claude/agents/crypto-token-analyst.md +278 -0
- package/one/things/claude/agents/crypto-viral-content-creator.md +546 -0
- package/one/things/claude/agents/crypto-wallet-identification-expert.md +517 -0
- package/one/things/claude/agents/crypto-wallet-identifier.md +292 -0
- package/one/things/claude/agents/customer-journey-designer.md +481 -0
- package/one/things/claude/agents/customer-success-manager.md +581 -0
- package/one/things/claude/agents/dev.md +413 -0
- package/one/things/claude/agents/documenter.md +546 -0
- package/one/things/claude/agents/elevate-marketing-orchestrator.md +410 -0
- package/one/things/claude/agents/engagement-specialist.md +509 -0
- package/one/things/claude/agents/engineering-architect.md +387 -0
- package/one/things/claude/agents/engineering-business-analyst.md +537 -0
- package/one/things/claude/agents/engineering-developer.md +387 -0
- package/one/things/claude/agents/engineering-director.md +282 -0
- package/one/things/claude/agents/engineering-ingestor.md +649 -0
- package/one/things/claude/agents/engineering-product-manager.md +537 -0
- package/one/things/claude/agents/engineering-product-owner.md +537 -0
- package/one/things/claude/agents/engineering-project-coordinator.md +537 -0
- package/one/things/claude/agents/engineering-quality-assurance.md +393 -0
- package/one/things/claude/agents/engineering-team-manager.md +512 -0
- package/one/things/claude/agents/engineering-user-experience.md +387 -0
- package/one/things/claude/agents/framework-elevate-manager.md +294 -0
- package/one/things/claude/agents/improver.md +763 -0
- package/one/things/claude/agents/intelligence-team-manager.md +385 -0
- package/one/things/claude/agents/lead-capture-expert.md +466 -0
- package/one/things/claude/agents/lead-magnet-creator.md +453 -0
- package/one/things/claude/agents/market-research-analyst.md +412 -0
- package/one/things/claude/agents/marketing-brand-identity.md +314 -0
- package/one/things/claude/agents/marketing-content-hooks.md +450 -0
- package/one/things/claude/agents/marketing-content-multiplier.md +326 -0
- package/one/things/claude/agents/marketing-content-poster.md +361 -0
- package/one/things/claude/agents/marketing-customer-journey.md +326 -0
- package/one/things/claude/agents/marketing-director.md +397 -0
- package/one/things/claude/agents/marketing-engagement.md +326 -0
- package/one/things/claude/agents/marketing-lead-capture.md +326 -0
- package/one/things/claude/agents/marketing-lead-magnet.md +326 -0
- package/one/things/claude/agents/marketing-network-effects.md +326 -0
- package/one/things/claude/agents/marketing-nurture-campaigns.md +326 -0
- package/one/things/claude/agents/marketing-share-optimizer.md +326 -0
- package/one/things/claude/agents/marketing-team-manager.md +446 -0
- package/one/things/claude/agents/marketing-viral-growth.md +201 -0
- package/one/things/claude/agents/mission-commander.md +373 -0
- package/one/things/claude/agents/network-effect-analyst.md +587 -0
- package/one/things/claude/agents/nextjs-15-specialist.md +1547 -0
- package/one/things/claude/agents/npx.md +890 -0
- package/one/things/claude/agents/nurture-campaign-manager.md +531 -0
- package/one/things/claude/agents/one-master.md +355 -0
- package/one/things/claude/agents/one-orchestrator.md +315 -0
- package/one/things/claude/agents/one.md +601 -0
- package/one/things/claude/agents/playbook-generator.md +503 -0
- package/one/things/claude/agents/pm.md +326 -0
- package/one/things/claude/agents/po.md +345 -0
- package/one/things/claude/agents/qa.md +336 -0
- package/one/things/claude/agents/research-foundation-analyst.md +307 -0
- package/one/things/claude/agents/research-intelligence-gatherer.md +408 -0
- package/one/things/claude/agents/research-market-analyst.md +307 -0
- package/one/things/claude/agents/research-team-manager.md +482 -0
- package/one/things/claude/agents/sales-environment-optimizer.md +494 -0
- package/one/things/claude/agents/sales-team-manager.md +400 -0
- package/one/things/claude/agents/sales-upsell-strategist.md +307 -0
- package/one/things/claude/agents/service-advocacy-campaigns.md +307 -0
- package/one/things/claude/agents/service-advocacy-manager.md +307 -0
- package/one/things/claude/agents/service-success-manager.md +307 -0
- package/one/things/claude/agents/service-team-manager.md +400 -0
- package/one/things/claude/agents/shadcn-ui-design-system-specialist.md +2302 -0
- package/one/things/claude/agents/share-optimization-specialist.md +551 -0
- package/one/things/claude/agents/sm.md +327 -0
- package/one/things/claude/agents/story-teller.md +473 -0
- package/one/things/claude/agents/task-master.md +596 -0
- package/one/things/claude/agents/tauri-cross-platform-specialist.md +1827 -0
- package/one/things/claude/agents/tester.md +556 -0
- package/one/things/claude/agents/the-bull-character-manager.md +580 -0
- package/one/things/claude/agents/tools-playbook-generator.md +489 -0
- package/one/things/claude/agents/turbo-repo-builder.md +316 -0
- package/one/things/claude/agents/upsell-strategist.md +480 -0
- package/one/things/claude/agents/ux-expert.md +335 -0
- package/one/things/claude/agents/viral-growth-orchestrator.md +497 -0
- package/one/things/claude/claude-code-hooks-development.json +21 -0
- package/one/things/claude/claude-code-hooks-production.json +21 -0
- package/one/things/claude/claude-code-hooks.json +25 -0
- package/one/things/claude/commands/agent.md +104 -0
- package/one/things/claude/commands/cascade-status.md +128 -0
- package/one/things/claude/commands/ingest.md +290 -0
- package/one/things/claude/commands/ingestor.md +136 -0
- package/one/things/claude/commands/mission.md +83 -0
- package/one/things/claude/commands/npx.md +133 -0
- package/one/things/claude/commands/one.md +440 -0
- package/one/things/claude/commands/quality-check.md +204 -0
- package/one/things/claude/commands/smart-route.md +220 -0
- package/one/things/claude/commands/start.md +121 -0
- package/one/things/claude/commands/story.md +83 -0
- package/one/things/claude/commands/task.md +173 -0
- package/one/things/claude/hook-bypass.json +32 -0
- package/one/things/claude/hooks/agent-hook-config.json +427 -0
- package/one/things/claude/hooks/agent-hook-manager.js +525 -0
- package/one/things/claude/hooks/agent-load-balancer.js +271 -0
- package/one/things/claude/hooks/agent-request-interceptor.js +70 -0
- package/one/things/claude/hooks/build-hook.sh +156 -0
- package/one/things/claude/hooks/cascade-feedback.js +297 -0
- package/one/things/claude/hooks/cascade-integration-hooks.js +648 -0
- package/one/things/claude/hooks/cleanup-hook.sh +201 -0
- package/one/things/claude/hooks/continuous-improvement-monitor.js +510 -0
- package/one/things/claude/hooks/file-organization-engine.js +427 -0
- package/one/things/claude/hooks/file-organization-hook.sh +80 -0
- package/one/things/claude/hooks/file-organization-monitor.js +269 -0
- package/one/things/claude/hooks/format-hook.sh +43 -0
- package/one/things/claude/hooks/hook-bypass.sh +293 -0
- package/one/things/claude/hooks/hook-config-manager.js +202 -0
- package/one/things/claude/hooks/hook-debouncer.sh +62 -0
- package/one/things/claude/hooks/hook-logger.sh +89 -0
- package/one/things/claude/hooks/hook-orchestrator.js +662 -0
- package/one/things/claude/hooks/hook-performance-report.js +120 -0
- package/one/things/claude/hooks/lint-hook.sh +140 -0
- package/one/things/claude/hooks/mcp-cascade-integration.js +816 -0
- package/one/things/claude/hooks/memory-optimizer.js +510 -0
- package/one/things/claude/hooks/notification-hook.sh +204 -0
- package/one/things/claude/hooks/ontology-compliance.js +394 -0
- package/one/things/claude/hooks/ontology-hook-manager.js +316 -0
- package/one/things/claude/hooks/ontology-validation-engine.js +317 -0
- package/one/things/claude/hooks/ontology-validation-hook.sh +86 -0
- package/one/things/claude/hooks/performance-metrics.json +25 -0
- package/one/things/claude/hooks/performance-monitoring-hook.js +422 -0
- package/one/things/claude/hooks/quality-scoring-engine.js +834 -0
- package/one/things/claude/hooks/security-hook.sh +256 -0
- package/one/things/claude/hooks/simple-load-balancer.js +238 -0
- package/one/things/claude/hooks/startup-optimizer.js +625 -0
- package/one/things/claude/hooks/story-scoring-system.js +445 -0
- package/one/things/claude/hooks/story-validation-engine.js +473 -0
- package/one/things/claude/hooks/story-validation-hook-enhanced.sh +210 -0
- package/one/things/claude/hooks/story-validation-hook.sh +145 -0
- package/one/things/claude/hooks/structure-synchronizer.js +194 -0
- package/one/things/claude/hooks/sub-agent-output-validator.js +647 -0
- package/one/things/claude/hooks/sub-agent-validation-hook.js +343 -0
- package/one/things/claude/hooks/test-hook.sh +145 -0
- package/one/things/claude/hooks/test-story-validation.sh +170 -0
- package/one/things/claude/hooks/trinity-validation-system.js +392 -0
- package/one/things/claude/settings-local.json +86 -0
- package/one/things/cli-code.md +652 -0
- package/one/things/cli-compiler-code.md +652 -0
- package/one/things/cli.md +1045 -0
- package/one/things/components/card-shadcn.md +929 -0
- package/one/things/components/card.md +1050 -0
- package/one/things/components.md +1669 -0
- package/one/things/componets.md +4 -0
- package/one/things/copilotkit.md +1559 -0
- package/one/things/creator-diagram.md +166 -0
- package/one/things/examples/children/lemonade-stand.md +366 -0
- package/one/things/examples/enterprise/crm-saas.md +1429 -0
- package/one/things/features/1-1-agent-prompts/design.md +470 -0
- package/one/things/features/1-1-agent-prompts/tests.md +264 -0
- package/one/things/features/1-1-agent-prompts.md +486 -0
- package/one/things/features/1-2-yaml-orchestrator/design.md +497 -0
- package/one/things/features/1-2-yaml-orchestrator/tests.md +227 -0
- package/one/things/features/1-2-yaml-orchestrator.md +516 -0
- package/one/things/features/1-3-event-coordination/design.md +544 -0
- package/one/things/features/1-3-event-coordination/tests.md +223 -0
- package/one/things/features/1-3-event-coordination.md +508 -0
- package/one/things/features/1-4-knowledge-management/design.md +609 -0
- package/one/things/features/1-4-knowledge-management/tests.md +195 -0
- package/one/things/features/1-4-knowledge-management.md +577 -0
- package/one/things/features/1-5-quality-loops/design.md +797 -0
- package/one/things/features/1-5-quality-loops/tests.md +212 -0
- package/one/things/features/1-5-quality-loops.md +641 -0
- package/one/things/features/1-6-numbering-structure/design.md +610 -0
- package/one/things/features/1-6-numbering-structure/tests.md +213 -0
- package/one/things/features/1-6-numbering-structure.md +575 -0
- package/one/things/features/2-cli.md +1235 -0
- package/one/things/features/use-one-backend.md +1180 -0
- package/one/things/ideas/1-create-workflow.md +189 -0
- package/one/things/plans/1-create-workflow-status.md +555 -0
- package/one/things/plans/1-create-workflow.md +713 -0
- package/one/things/plans/app.md +761 -0
- package/one/things/plans/better-auth-any-backend-revised.md +1065 -0
- package/one/things/plans/better-auth-any-backend.md +1852 -0
- package/one/things/plans/better-auth-available-features.md +235 -0
- package/one/things/plans/big-plan.md +38 -0
- package/one/things/plans/convex-better-auth.md +1109 -0
- package/one/things/plans/convex-on-off.md +389 -0
- package/one/things/plans/desktop.md +1121 -0
- package/one/things/plans/effect-components.md +1669 -0
- package/one/things/plans/effect.md +973 -0
- package/one/things/plans/email.md +953 -0
- package/one/things/plans/enhance-auth.md +1669 -0
- package/one/things/plans/install-components.md +198 -0
- package/one/things/plans/landing.md +728 -0
- package/one/things/plans/layout.md +205 -0
- package/one/things/plans/mail-backend.md +1308 -0
- package/one/things/plans/mail.md +2624 -0
- package/one/things/plans/next-features.md +83 -0
- package/one/things/plans/one.md +658 -0
- package/one/things/plans/ontology-6-dimensions.md +2216 -0
- package/one/things/plans/ontology-driven-strategy.md +866 -0
- package/one/things/plans/ontology-ui-approach.md +357 -0
- package/one/things/plans/open-agent.md +785 -0
- package/one/things/plans/performace.md +90 -0
- package/one/things/plans/releases.md +809 -0
- package/one/things/plans/repos.md +76 -0
- package/one/things/plans/separate-copy-2.md +1293 -0
- package/one/things/plans/separate-copy-3.md +2458 -0
- package/one/things/plans/separate-copy.md +1293 -0
- package/one/things/plans/separate.md +1983 -0
- package/one/things/plans/shadcn-integration-summary.md +450 -0
- package/one/things/plans/sidebar.md +172 -0
- package/one/things/plans/small-fixes.md +5 -0
- package/one/things/plans/test-backend-connection.md +476 -0
- package/one/things/plans/workflow-files.md +1196 -0
- package/one/things/plans/workflow.md +1372 -0
- package/one/things/products/cascade-landing-page.md +737 -0
- package/one/things/products/cascade.md +1518 -0
- package/one/things/products/context-engineering.md +1427 -0
- package/one/things/products/onthology.md +0 -0
- package/one/things/products/ontology-ui-shadcn.md +1280 -0
- package/one/things/products/ontology-ui.md +1387 -0
- package/one/things/products/ontology.md +717 -0
- package/one/things/products/sdk.md +557 -0
- package/one/things/promptkit.md +903 -0
- package/one/things/service-providers-new.md +982 -0
- package/one/things/service-providers.md +1092 -0
- package/one/things/things.md +349 -0
- package/one/things/todo.md +1248 -0
- package/package.json +5 -2
|
@@ -0,0 +1,2109 @@
|
|
|
1
|
+
# Hono.md - API Backend Architecture
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
**Hono** is a lightweight, ultrafast web framework that can be used with Convex in two ways:
|
|
6
|
+
|
|
7
|
+
1. **Convex-Native** (Recommended): Hono runs inside Convex as HTTP actions (`convex/http.ts`)
|
|
8
|
+
2. **Separate API**: Hono runs on Cloudflare Workers, calls Convex via `ConvexHttpClient`
|
|
9
|
+
|
|
10
|
+
This document covers **both approaches** with complete implementation guides.
|
|
11
|
+
|
|
12
|
+
### Quick Comparison
|
|
13
|
+
|
|
14
|
+
| Feature | Convex-Native | Separate API |
|
|
15
|
+
|---------|---------------|--------------|
|
|
16
|
+
| **Deployment** | Single (Convex only) | Two (Workers + Convex) |
|
|
17
|
+
| **Access to Convex** | `c.env.runQuery/Mutation` | `ConvexHttpClient` (HTTP) |
|
|
18
|
+
| **Infrastructure** | Minimal | More complex |
|
|
19
|
+
| **Multi-Tenancy** | Limited | Full support |
|
|
20
|
+
| **Team Separation** | Harder | Easier |
|
|
21
|
+
| **API Reusability** | Limited | High (web/mobile/desktop) |
|
|
22
|
+
| **Official Pattern** | ✅ Yes ([Convex Stack](https://stack.convex.dev/hono-with-convex)) | Custom |
|
|
23
|
+
| **Best For** | Single-tenant apps | Multi-tenant platforms |
|
|
24
|
+
|
|
25
|
+
**Key Principle:** Use **Convex for ALL data storage** (including auth), not external databases.
|
|
26
|
+
|
|
27
|
+
**Official Documentation:**
|
|
28
|
+
- [Hono with Convex (Convex Stack)](https://stack.convex.dev/hono-with-convex) - Official pattern
|
|
29
|
+
- [Hono Documentation](https://hono.dev/) - Hono framework docs
|
|
30
|
+
- [convex-helpers](https://stack.convex.dev/convex-helpers) - Helper utilities
|
|
31
|
+
|
|
32
|
+
## Architecture Vision
|
|
33
|
+
|
|
34
|
+
```
|
|
35
|
+
┌─────────────────────────────────────────────────────────┐
|
|
36
|
+
│ ASTRO FRONTEND │
|
|
37
|
+
│ ┌──────────────────────────────────────────────────┐ │
|
|
38
|
+
│ │ Pages, Components, UI (User Customizable) │ │
|
|
39
|
+
│ │ - Vibe code with Convex hooks │ │
|
|
40
|
+
│ │ - shadcn/ui components │ │
|
|
41
|
+
│ │ - Tailwind styling │ │
|
|
42
|
+
│ └────────────────┬─────────────────────────────────┘ │
|
|
43
|
+
└───────────────────┼─────────────────────────────────────┘
|
|
44
|
+
│ HTTP API Calls
|
|
45
|
+
▼
|
|
46
|
+
┌─────────────────────────────────────────────────────────┐
|
|
47
|
+
│ HONO API BACKEND │
|
|
48
|
+
│ ┌──────────────────────────────────────────────────┐ │
|
|
49
|
+
│ │ Routes (Hono) │ │
|
|
50
|
+
│ │ /api/auth/* - Better Auth endpoints │ │
|
|
51
|
+
│ │ /api/tokens/* - Token economy endpoints │ │
|
|
52
|
+
│ │ /api/agents/* - Agent management │ │
|
|
53
|
+
│ │ /api/content/*- Content creation │ │
|
|
54
|
+
│ └────────────────┬─────────────────────────────────┘ │
|
|
55
|
+
│ │ │
|
|
56
|
+
│ ┌────────────────┴─────────────────────────────────┐ │
|
|
57
|
+
│ │ Business Logic (Effect.ts Services) │ │
|
|
58
|
+
│ │ - TokenService, AgentService, etc. │ │
|
|
59
|
+
│ │ - Pure functional logic │ │
|
|
60
|
+
│ │ - Type-safe error handling │ │
|
|
61
|
+
│ └────────────────┬─────────────────────────────────┘ │
|
|
62
|
+
│ │ │
|
|
63
|
+
│ ┌────────────────┴─────────────────────────────────┐ │
|
|
64
|
+
│ │ Data Layer (ConvexHttpClient) │ │
|
|
65
|
+
│ │ - Queries/mutations via HTTP │ │
|
|
66
|
+
│ │ - Better Auth → Convex adapter │ │
|
|
67
|
+
│ └────────────────┬─────────────────────────────────┘ │
|
|
68
|
+
└───────────────────┼─────────────────────────────────────┘
|
|
69
|
+
│
|
|
70
|
+
▼
|
|
71
|
+
┌─────────────────────────────────────────────────────────┐
|
|
72
|
+
│ CONVEX BACKEND │
|
|
73
|
+
│ - 6-dimension ontology (organizations, people, things, connections, events, knowledge)│
|
|
74
|
+
│ - Auth data stored as entities │
|
|
75
|
+
│ - Real-time subscriptions │
|
|
76
|
+
│ - Typed functions │
|
|
77
|
+
└─────────────────────────────────────────────────────────┘
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Technology Stack
|
|
81
|
+
|
|
82
|
+
**Frontend:**
|
|
83
|
+
- Astro 5.14+ (SSR pages)
|
|
84
|
+
- React 19 (interactive components)
|
|
85
|
+
- shadcn/ui (UI components)
|
|
86
|
+
- Tailwind CSS v4 (styling)
|
|
87
|
+
- Effect.ts (client-side error handling)
|
|
88
|
+
|
|
89
|
+
**API Backend:**
|
|
90
|
+
- Hono (routing on Cloudflare Workers)
|
|
91
|
+
- Better Auth (authentication with Convex adapter)
|
|
92
|
+
- Effect.ts (100% business logic coverage - see [effect.md](../connections/effect.md))
|
|
93
|
+
- ConvexHttpClient (data access via Effect.ts wrapper)
|
|
94
|
+
|
|
95
|
+
**Data Backend:**
|
|
96
|
+
- Convex (real-time database)
|
|
97
|
+
- 6-dimension ontology (things, connections, events, knowledge, people, protocols)
|
|
98
|
+
|
|
99
|
+
**Deployment:**
|
|
100
|
+
- Cloudflare Pages (Astro frontend)
|
|
101
|
+
- Cloudflare Workers (Hono API)
|
|
102
|
+
- Convex Cloud (database)
|
|
103
|
+
|
|
104
|
+
**Key Principle:** Effect.ts is used throughout the entire pipeline (frontend → API → services → data) for consistent error handling, composability, and testability. See **[effect.md](../connections/effect.md)** for complete Effect.ts coverage patterns.
|
|
105
|
+
|
|
106
|
+
## Two Deployment Approaches
|
|
107
|
+
|
|
108
|
+
There are **two ways** to use Hono with Convex, each with different trade-offs:
|
|
109
|
+
|
|
110
|
+
### Approach 1: Convex-Native (Recommended for Most Apps)
|
|
111
|
+
|
|
112
|
+
**Pattern:** Hono runs inside Convex as HTTP actions (`convex/http.ts`)
|
|
113
|
+
|
|
114
|
+
**Pros:**
|
|
115
|
+
- ✅ Single deployment (Convex only)
|
|
116
|
+
- ✅ Direct access to Convex functions via `c.env.runQuery/runMutation`
|
|
117
|
+
- ✅ No separate API infrastructure needed
|
|
118
|
+
- ✅ Simpler authentication (uses Convex auth directly)
|
|
119
|
+
- ✅ Official Convex pattern (see [stack.convex.dev/hono-with-convex](https://stack.convex.dev/hono-with-convex))
|
|
120
|
+
|
|
121
|
+
**Cons:**
|
|
122
|
+
- ❌ Less flexible for multi-tenancy
|
|
123
|
+
- ❌ Harder to separate concerns for large teams
|
|
124
|
+
- ❌ Couples API lifecycle to Convex
|
|
125
|
+
|
|
126
|
+
**Best For:**
|
|
127
|
+
- Single-tenant applications
|
|
128
|
+
- Simpler architectures
|
|
129
|
+
- Teams that want to minimize infrastructure
|
|
130
|
+
|
|
131
|
+
**Documentation:** See "Convex-Native Implementation" section below.
|
|
132
|
+
|
|
133
|
+
### Approach 2: Separate API (Cloudflare Workers)
|
|
134
|
+
|
|
135
|
+
**Pattern:** Hono runs on Cloudflare Workers, calls Convex via `ConvexHttpClient`
|
|
136
|
+
|
|
137
|
+
**Pros:**
|
|
138
|
+
- ✅ Complete separation of frontend and backend
|
|
139
|
+
- ✅ Multi-tenancy support (different frontends, shared API)
|
|
140
|
+
- ✅ Independent deployment of API and database
|
|
141
|
+
- ✅ API can be reused across web, mobile, desktop
|
|
142
|
+
- ✅ Better for large teams (frontend/backend specialization)
|
|
143
|
+
|
|
144
|
+
**Cons:**
|
|
145
|
+
- ❌ More infrastructure to manage (Workers + Convex)
|
|
146
|
+
- ❌ HTTP overhead calling Convex
|
|
147
|
+
- ❌ More complex authentication setup
|
|
148
|
+
|
|
149
|
+
**Best For:**
|
|
150
|
+
- Multi-tenant platforms
|
|
151
|
+
- Large teams with frontend/backend separation
|
|
152
|
+
- APIs serving multiple client types
|
|
153
|
+
|
|
154
|
+
**Documentation:** See "Separate API Implementation" section below.
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
## Convex-Native Implementation
|
|
159
|
+
|
|
160
|
+
This approach runs Hono **inside Convex** as HTTP actions, following the official Convex pattern.
|
|
161
|
+
|
|
162
|
+
### Setup
|
|
163
|
+
|
|
164
|
+
**1. Install dependencies:**
|
|
165
|
+
```bash
|
|
166
|
+
npm install hono convex-helpers @hono/zod-validator zod
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
**2. Create `convex/http.ts`:**
|
|
170
|
+
```typescript
|
|
171
|
+
import { Hono } from "hono";
|
|
172
|
+
import { HonoWithConvex, HttpRouterWithHono } from "convex-helpers/server/hono";
|
|
173
|
+
import { ActionCtx } from "./_generated/server";
|
|
174
|
+
import { api } from "./_generated/api";
|
|
175
|
+
import { cors } from "hono/cors";
|
|
176
|
+
import { zValidator } from "@hono/zod-validator";
|
|
177
|
+
import { z } from "zod";
|
|
178
|
+
|
|
179
|
+
// Hono app with Convex context
|
|
180
|
+
const app: HonoWithConvex<ActionCtx> = new Hono();
|
|
181
|
+
|
|
182
|
+
// CORS middleware
|
|
183
|
+
app.use('/api/*', cors({
|
|
184
|
+
origin: ['http://localhost:4321', 'https://your-frontend.pages.dev'],
|
|
185
|
+
credentials: true,
|
|
186
|
+
}));
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* GET /api/tokens/:id
|
|
190
|
+
* Fetch token via Convex query
|
|
191
|
+
*/
|
|
192
|
+
app.get("/api/tokens/:id", async (c) => {
|
|
193
|
+
const tokenId = c.req.param("id");
|
|
194
|
+
|
|
195
|
+
// Direct access to Convex via c.env
|
|
196
|
+
const token = await c.env.runQuery(api.queries.entities.get, {
|
|
197
|
+
id: tokenId
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
if (!token || token.type !== "token") {
|
|
201
|
+
return c.json({ error: "Token not found" }, 404);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return c.json(token);
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* POST /api/tokens/purchase
|
|
209
|
+
* Purchase tokens with validation
|
|
210
|
+
*/
|
|
211
|
+
app.post(
|
|
212
|
+
"/api/tokens/purchase",
|
|
213
|
+
zValidator(
|
|
214
|
+
"json",
|
|
215
|
+
z.object({
|
|
216
|
+
tokenId: z.string(),
|
|
217
|
+
amount: z.number().min(1).max(10000),
|
|
218
|
+
})
|
|
219
|
+
),
|
|
220
|
+
async (c) => {
|
|
221
|
+
const { tokenId, amount } = c.req.valid("json");
|
|
222
|
+
|
|
223
|
+
// Get user from auth (example - implement based on your auth strategy)
|
|
224
|
+
const userId = c.req.header("X-User-Id");
|
|
225
|
+
if (!userId) {
|
|
226
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// Call Convex mutation
|
|
230
|
+
const result = await c.env.runMutation(api.mutations.tokens.purchase, {
|
|
231
|
+
userId,
|
|
232
|
+
tokenId,
|
|
233
|
+
amount,
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
return c.json(result);
|
|
237
|
+
}
|
|
238
|
+
);
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* GET /api/messages/:userId
|
|
242
|
+
* Dynamic route example
|
|
243
|
+
*/
|
|
244
|
+
app.get("/api/messages/:userId{[0-9]+}", async (c) => {
|
|
245
|
+
const userId = c.req.param("userId");
|
|
246
|
+
|
|
247
|
+
const messages = await c.env.runQuery(api.queries.messages.getByAuthor, {
|
|
248
|
+
authorNumber: userId,
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
return c.json(messages);
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
// Export as Convex HTTP router
|
|
255
|
+
export default new HttpRouterWithHono(app);
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
**3. Update `convex.json`:**
|
|
259
|
+
```json
|
|
260
|
+
{
|
|
261
|
+
"functions": "convex/",
|
|
262
|
+
"node": {
|
|
263
|
+
"externalPackages": ["hono"]
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
### Authentication with Convex Auth
|
|
269
|
+
|
|
270
|
+
**Using Convex Auth in Hono routes:**
|
|
271
|
+
|
|
272
|
+
```typescript
|
|
273
|
+
import { getAuthUserId } from "@convex-dev/auth/server";
|
|
274
|
+
|
|
275
|
+
app.post("/api/protected", async (c) => {
|
|
276
|
+
// Get authenticated user ID
|
|
277
|
+
const userId = await getAuthUserId(c.env);
|
|
278
|
+
|
|
279
|
+
if (!userId) {
|
|
280
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Use userId in queries/mutations
|
|
284
|
+
const data = await c.env.runQuery(api.queries.getUserData, { userId });
|
|
285
|
+
|
|
286
|
+
return c.json(data);
|
|
287
|
+
});
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
### Cookie Handling
|
|
291
|
+
|
|
292
|
+
```typescript
|
|
293
|
+
import { setCookie, getCookie } from 'hono/cookie';
|
|
294
|
+
|
|
295
|
+
app.post("/api/session", async (c) => {
|
|
296
|
+
const { token } = await c.req.json();
|
|
297
|
+
|
|
298
|
+
// Set cookie
|
|
299
|
+
setCookie(c, 'session_token', token, {
|
|
300
|
+
httpOnly: true,
|
|
301
|
+
secure: true,
|
|
302
|
+
maxAge: 86400, // 1 day
|
|
303
|
+
sameSite: 'Lax',
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
return c.json({ success: true });
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
app.get("/api/session", async (c) => {
|
|
310
|
+
// Get cookie
|
|
311
|
+
const token = getCookie(c, 'session_token');
|
|
312
|
+
|
|
313
|
+
if (!token) {
|
|
314
|
+
return c.json({ error: "No session" }, 401);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
return c.json({ token });
|
|
318
|
+
});
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
### Error Handling
|
|
322
|
+
|
|
323
|
+
```typescript
|
|
324
|
+
app.onError((err, c) => {
|
|
325
|
+
console.error(`${err}`);
|
|
326
|
+
|
|
327
|
+
// Handle specific error types
|
|
328
|
+
if (err.name === 'ConvexError') {
|
|
329
|
+
return c.json({ error: err.message }, 400);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
return c.json({ error: 'Internal Server Error' }, 500);
|
|
333
|
+
});
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
### Benefits of Convex-Native Approach
|
|
337
|
+
|
|
338
|
+
1. **Direct Function Access**: No HTTP overhead calling Convex
|
|
339
|
+
2. **Shared Type Safety**: Same types for routes and Convex functions
|
|
340
|
+
3. **Simple Deployment**: Single `npx convex deploy`
|
|
341
|
+
4. **Built-in Auth**: Easy integration with Convex Auth
|
|
342
|
+
5. **Environment Variables**: Access via `process.env` in actions
|
|
343
|
+
|
|
344
|
+
### When to Use Convex-Native
|
|
345
|
+
|
|
346
|
+
✅ **Use this approach when:**
|
|
347
|
+
- Building a single-tenant application
|
|
348
|
+
- Want simplest possible deployment
|
|
349
|
+
- Don't need multi-frontend support
|
|
350
|
+
- Team is focused on rapid development
|
|
351
|
+
- Frontend and backend tightly coupled
|
|
352
|
+
|
|
353
|
+
❌ **Don't use when:**
|
|
354
|
+
- Need multi-tenancy (different frontends per org)
|
|
355
|
+
- Want to reuse API across mobile/web/desktop
|
|
356
|
+
- Large team needs frontend/backend separation
|
|
357
|
+
- Need API versioning or complex routing
|
|
358
|
+
|
|
359
|
+
---
|
|
360
|
+
|
|
361
|
+
## Separate API Implementation (Cloudflare Workers)
|
|
362
|
+
|
|
363
|
+
This approach runs Hono on **Cloudflare Workers** separately from Convex, providing maximum flexibility.
|
|
364
|
+
|
|
365
|
+
## Why Hono + Separation?
|
|
366
|
+
|
|
367
|
+
### Problems Solved
|
|
368
|
+
|
|
369
|
+
1. **Frontend Lock-In**: Currently Astro is tightly coupled to backend logic
|
|
370
|
+
2. **Multi-Tenancy**: Organizations can't easily customize their frontend
|
|
371
|
+
3. **Development Speed**: Frontend changes require backend understanding
|
|
372
|
+
4. **API Portability**: Backend logic can't be reused across different frontends
|
|
373
|
+
|
|
374
|
+
### Benefits
|
|
375
|
+
|
|
376
|
+
1. **Rapid Prototyping**: Users can "vibe code" frontend with Convex hooks without touching backend
|
|
377
|
+
2. **Multi-Frontend Support**: Same API serves web, mobile, desktop apps
|
|
378
|
+
3. **Clear Contracts**: API endpoints define clear boundaries
|
|
379
|
+
4. **Independent Deployment**: Deploy frontend and backend separately
|
|
380
|
+
5. **Team Specialization**: Frontend devs work on UI, backend devs work on logic
|
|
381
|
+
6. **Single Database**: All data (including auth) in Convex - no separate database needed
|
|
382
|
+
|
|
383
|
+
## Implementation Pattern
|
|
384
|
+
|
|
385
|
+
### 1. Hono API Backend Structure
|
|
386
|
+
|
|
387
|
+
```
|
|
388
|
+
api/
|
|
389
|
+
├── src/
|
|
390
|
+
│ ├── index.ts # Main Hono app
|
|
391
|
+
│ ├── auth.ts # Better Auth with Convex adapter
|
|
392
|
+
│ ├── routes/
|
|
393
|
+
│ │ ├── auth.ts # /api/auth/* routes
|
|
394
|
+
│ │ ├── tokens.ts # /api/tokens/* routes
|
|
395
|
+
│ │ ├── agents.ts # /api/agents/* routes
|
|
396
|
+
│ │ └── content.ts # /api/content/* routes
|
|
397
|
+
│ ├── services/
|
|
398
|
+
│ │ ├── convex.ts # Convex integration service
|
|
399
|
+
│ │ ├── token.ts # Token business logic (Effect.ts)
|
|
400
|
+
│ │ ├── agent.ts # Agent business logic (Effect.ts)
|
|
401
|
+
│ │ └── content.ts # Content business logic (Effect.ts)
|
|
402
|
+
│ └── middleware/
|
|
403
|
+
│ ├── auth.ts # Auth middleware
|
|
404
|
+
│ └── cors.ts # CORS configuration
|
|
405
|
+
├── convex/ # Shared Convex backend
|
|
406
|
+
│ ├── schema.ts # 6-dimension ontology schema
|
|
407
|
+
│ ├── queries/
|
|
408
|
+
│ │ ├── auth.ts # Auth queries (for Better Auth adapter)
|
|
409
|
+
│ │ ├── entities.ts
|
|
410
|
+
│ │ └── ...
|
|
411
|
+
│ ├── mutations/
|
|
412
|
+
│ │ ├── auth.ts # Auth mutations (for Better Auth adapter)
|
|
413
|
+
│ │ ├── entities.ts
|
|
414
|
+
│ │ └── ...
|
|
415
|
+
│ └── services/ # Shared Effect.ts services
|
|
416
|
+
├── wrangler.toml # Cloudflare Workers config
|
|
417
|
+
└── package.json
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
### 2. Installation
|
|
421
|
+
|
|
422
|
+
```bash
|
|
423
|
+
# Create Hono project
|
|
424
|
+
npm create hono@latest api
|
|
425
|
+
cd api
|
|
426
|
+
|
|
427
|
+
# Install dependencies
|
|
428
|
+
npm install hono
|
|
429
|
+
npm install better-auth
|
|
430
|
+
npm install convex
|
|
431
|
+
npm install effect
|
|
432
|
+
npm install @effect/schema
|
|
433
|
+
|
|
434
|
+
# For development
|
|
435
|
+
npm install -D @cloudflare/workers-types
|
|
436
|
+
npm install -D wrangler
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
### 3. Better Auth with Convex Adapter
|
|
440
|
+
|
|
441
|
+
#### `api/src/auth.ts`
|
|
442
|
+
|
|
443
|
+
```typescript
|
|
444
|
+
import { betterAuth } from 'better-auth';
|
|
445
|
+
import { ConvexHttpClient } from 'convex/browser';
|
|
446
|
+
import { api } from '../../convex/_generated/api';
|
|
447
|
+
|
|
448
|
+
type CloudflareBindings = {
|
|
449
|
+
BETTER_AUTH_URL: string;
|
|
450
|
+
BETTER_AUTH_SECRET: string;
|
|
451
|
+
CONVEX_URL: string;
|
|
452
|
+
GITHUB_CLIENT_ID: string;
|
|
453
|
+
GITHUB_CLIENT_SECRET: string;
|
|
454
|
+
GOOGLE_CLIENT_ID: string;
|
|
455
|
+
GOOGLE_CLIENT_SECRET: string;
|
|
456
|
+
};
|
|
457
|
+
|
|
458
|
+
/**
|
|
459
|
+
* Custom Convex adapter for Better Auth
|
|
460
|
+
* Stores all auth data in Convex entities table
|
|
461
|
+
*/
|
|
462
|
+
function createConvexAdapter(convexUrl: string) {
|
|
463
|
+
const client = new ConvexHttpClient(convexUrl);
|
|
464
|
+
|
|
465
|
+
return {
|
|
466
|
+
// User operations
|
|
467
|
+
async createUser(data: any) {
|
|
468
|
+
return client.mutation(api.mutations.auth.createUser, data);
|
|
469
|
+
},
|
|
470
|
+
async getUser(id: string) {
|
|
471
|
+
return client.query(api.queries.auth.getUser, { id });
|
|
472
|
+
},
|
|
473
|
+
async getUserByEmail(email: string) {
|
|
474
|
+
return client.query(api.queries.auth.getUserByEmail, { email });
|
|
475
|
+
},
|
|
476
|
+
async updateUser(id: string, data: any) {
|
|
477
|
+
return client.mutation(api.mutations.auth.updateUser, { id, data });
|
|
478
|
+
},
|
|
479
|
+
async deleteUser(id: string) {
|
|
480
|
+
return client.mutation(api.mutations.auth.deleteUser, { id });
|
|
481
|
+
},
|
|
482
|
+
|
|
483
|
+
// Session operations
|
|
484
|
+
async createSession(data: any) {
|
|
485
|
+
return client.mutation(api.mutations.auth.createSession, data);
|
|
486
|
+
},
|
|
487
|
+
async getSession(token: string) {
|
|
488
|
+
return client.query(api.queries.auth.getSession, { token });
|
|
489
|
+
},
|
|
490
|
+
async updateSession(token: string, data: any) {
|
|
491
|
+
return client.mutation(api.mutations.auth.updateSession, { token, data });
|
|
492
|
+
},
|
|
493
|
+
async deleteSession(token: string) {
|
|
494
|
+
return client.mutation(api.mutations.auth.deleteSession, { token });
|
|
495
|
+
},
|
|
496
|
+
|
|
497
|
+
// Account operations (OAuth)
|
|
498
|
+
async linkAccount(data: any) {
|
|
499
|
+
return client.mutation(api.mutations.auth.linkAccount, data);
|
|
500
|
+
},
|
|
501
|
+
async unlinkAccount(data: any) {
|
|
502
|
+
return client.mutation(api.mutations.auth.unlinkAccount, data);
|
|
503
|
+
},
|
|
504
|
+
|
|
505
|
+
// Verification tokens
|
|
506
|
+
async createVerificationToken(data: any) {
|
|
507
|
+
return client.mutation(api.mutations.auth.createVerificationToken, data);
|
|
508
|
+
},
|
|
509
|
+
async getVerificationToken(token: string) {
|
|
510
|
+
return client.query(api.queries.auth.getVerificationToken, { token });
|
|
511
|
+
},
|
|
512
|
+
async deleteVerificationToken(token: string) {
|
|
513
|
+
return client.mutation(api.mutations.auth.deleteVerificationToken, { token });
|
|
514
|
+
},
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
export const auth = (env: CloudflareBindings) => {
|
|
519
|
+
return betterAuth({
|
|
520
|
+
database: createConvexAdapter(env.CONVEX_URL),
|
|
521
|
+
baseURL: env.BETTER_AUTH_URL,
|
|
522
|
+
secret: env.BETTER_AUTH_SECRET,
|
|
523
|
+
emailAndPassword: {
|
|
524
|
+
enabled: true,
|
|
525
|
+
requireEmailVerification: true,
|
|
526
|
+
},
|
|
527
|
+
socialProviders: {
|
|
528
|
+
github: {
|
|
529
|
+
clientId: env.GITHUB_CLIENT_ID,
|
|
530
|
+
clientSecret: env.GITHUB_CLIENT_SECRET,
|
|
531
|
+
},
|
|
532
|
+
google: {
|
|
533
|
+
clientId: env.GOOGLE_CLIENT_ID,
|
|
534
|
+
clientSecret: env.GOOGLE_CLIENT_SECRET,
|
|
535
|
+
},
|
|
536
|
+
},
|
|
537
|
+
});
|
|
538
|
+
};
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
### 4. Convex Auth Mutations/Queries
|
|
542
|
+
|
|
543
|
+
#### `convex/mutations/auth.ts`
|
|
544
|
+
|
|
545
|
+
```typescript
|
|
546
|
+
import { v } from 'convex/values';
|
|
547
|
+
import { mutation } from '../_generated/server';
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Auth mutations for Better Auth Convex adapter
|
|
551
|
+
* Stores auth data in entities table following ontology
|
|
552
|
+
*/
|
|
553
|
+
|
|
554
|
+
export const createUser = mutation({
|
|
555
|
+
args: {
|
|
556
|
+
email: v.string(),
|
|
557
|
+
name: v.optional(v.string()),
|
|
558
|
+
image: v.optional(v.string()),
|
|
559
|
+
emailVerified: v.optional(v.boolean()),
|
|
560
|
+
},
|
|
561
|
+
handler: async (ctx, args) => {
|
|
562
|
+
const userId = await ctx.db.insert('entities', {
|
|
563
|
+
type: 'user',
|
|
564
|
+
name: args.name || args.email,
|
|
565
|
+
properties: {
|
|
566
|
+
email: args.email,
|
|
567
|
+
image: args.image,
|
|
568
|
+
emailVerified: args.emailVerified || false,
|
|
569
|
+
role: 'user',
|
|
570
|
+
},
|
|
571
|
+
status: 'active',
|
|
572
|
+
createdAt: Date.now(),
|
|
573
|
+
updatedAt: Date.now(),
|
|
574
|
+
});
|
|
575
|
+
|
|
576
|
+
return { id: userId, ...args };
|
|
577
|
+
},
|
|
578
|
+
});
|
|
579
|
+
|
|
580
|
+
export const updateUser = mutation({
|
|
581
|
+
args: {
|
|
582
|
+
id: v.id('entities'),
|
|
583
|
+
data: v.object({
|
|
584
|
+
email: v.optional(v.string()),
|
|
585
|
+
name: v.optional(v.string()),
|
|
586
|
+
image: v.optional(v.string()),
|
|
587
|
+
emailVerified: v.optional(v.boolean()),
|
|
588
|
+
}),
|
|
589
|
+
},
|
|
590
|
+
handler: async (ctx, args) => {
|
|
591
|
+
const user = await ctx.db.get(args.id);
|
|
592
|
+
if (!user || user.type !== 'user') {
|
|
593
|
+
throw new Error('User not found');
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
await ctx.db.patch(args.id, {
|
|
597
|
+
name: args.data.name || user.name,
|
|
598
|
+
properties: {
|
|
599
|
+
...user.properties,
|
|
600
|
+
...args.data,
|
|
601
|
+
},
|
|
602
|
+
updatedAt: Date.now(),
|
|
603
|
+
});
|
|
604
|
+
|
|
605
|
+
return { id: args.id, ...args.data };
|
|
606
|
+
},
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
export const deleteUser = mutation({
|
|
610
|
+
args: { id: v.id('entities') },
|
|
611
|
+
handler: async (ctx, args) => {
|
|
612
|
+
await ctx.db.delete(args.id);
|
|
613
|
+
return { success: true };
|
|
614
|
+
},
|
|
615
|
+
});
|
|
616
|
+
|
|
617
|
+
export const createSession = mutation({
|
|
618
|
+
args: {
|
|
619
|
+
userId: v.id('entities'),
|
|
620
|
+
token: v.string(),
|
|
621
|
+
expiresAt: v.number(),
|
|
622
|
+
},
|
|
623
|
+
handler: async (ctx, args) => {
|
|
624
|
+
const sessionId = await ctx.db.insert('entities', {
|
|
625
|
+
type: 'session',
|
|
626
|
+
name: `Session for ${args.userId}`,
|
|
627
|
+
properties: {
|
|
628
|
+
userId: args.userId,
|
|
629
|
+
token: args.token,
|
|
630
|
+
expiresAt: args.expiresAt,
|
|
631
|
+
},
|
|
632
|
+
status: 'active',
|
|
633
|
+
createdAt: Date.now(),
|
|
634
|
+
updatedAt: Date.now(),
|
|
635
|
+
});
|
|
636
|
+
|
|
637
|
+
// Create connection: user → session
|
|
638
|
+
await ctx.db.insert('connections', {
|
|
639
|
+
fromEntityId: args.userId,
|
|
640
|
+
toEntityId: sessionId,
|
|
641
|
+
relationshipType: 'has_session',
|
|
642
|
+
createdAt: Date.now(),
|
|
643
|
+
});
|
|
644
|
+
|
|
645
|
+
return { id: sessionId, ...args };
|
|
646
|
+
},
|
|
647
|
+
});
|
|
648
|
+
|
|
649
|
+
export const updateSession = mutation({
|
|
650
|
+
args: {
|
|
651
|
+
token: v.string(),
|
|
652
|
+
data: v.object({
|
|
653
|
+
expiresAt: v.optional(v.number()),
|
|
654
|
+
}),
|
|
655
|
+
},
|
|
656
|
+
handler: async (ctx, args) => {
|
|
657
|
+
const session = await ctx.db
|
|
658
|
+
.query('entities')
|
|
659
|
+
.filter((q) =>
|
|
660
|
+
q.and(
|
|
661
|
+
q.eq(q.field('type'), 'session'),
|
|
662
|
+
q.eq(q.field('properties.token'), args.token)
|
|
663
|
+
)
|
|
664
|
+
)
|
|
665
|
+
.first();
|
|
666
|
+
|
|
667
|
+
if (!session) {
|
|
668
|
+
throw new Error('Session not found');
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
await ctx.db.patch(session._id, {
|
|
672
|
+
properties: {
|
|
673
|
+
...session.properties,
|
|
674
|
+
...args.data,
|
|
675
|
+
},
|
|
676
|
+
updatedAt: Date.now(),
|
|
677
|
+
});
|
|
678
|
+
|
|
679
|
+
return { token: args.token, ...args.data };
|
|
680
|
+
},
|
|
681
|
+
});
|
|
682
|
+
|
|
683
|
+
export const deleteSession = mutation({
|
|
684
|
+
args: { token: v.string() },
|
|
685
|
+
handler: async (ctx, args) => {
|
|
686
|
+
const session = await ctx.db
|
|
687
|
+
.query('entities')
|
|
688
|
+
.filter((q) =>
|
|
689
|
+
q.and(
|
|
690
|
+
q.eq(q.field('type'), 'session'),
|
|
691
|
+
q.eq(q.field('properties.token'), args.token)
|
|
692
|
+
)
|
|
693
|
+
)
|
|
694
|
+
.first();
|
|
695
|
+
|
|
696
|
+
if (session) {
|
|
697
|
+
await ctx.db.delete(session._id);
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
return { success: true };
|
|
701
|
+
},
|
|
702
|
+
});
|
|
703
|
+
|
|
704
|
+
// OAuth account linking
|
|
705
|
+
export const linkAccount = mutation({
|
|
706
|
+
args: {
|
|
707
|
+
userId: v.id('entities'),
|
|
708
|
+
provider: v.string(),
|
|
709
|
+
providerAccountId: v.string(),
|
|
710
|
+
accessToken: v.optional(v.string()),
|
|
711
|
+
refreshToken: v.optional(v.string()),
|
|
712
|
+
},
|
|
713
|
+
handler: async (ctx, args) => {
|
|
714
|
+
const accountId = await ctx.db.insert('entities', {
|
|
715
|
+
type: 'oauth_account',
|
|
716
|
+
name: `${args.provider} account`,
|
|
717
|
+
properties: {
|
|
718
|
+
provider: args.provider,
|
|
719
|
+
providerAccountId: args.providerAccountId,
|
|
720
|
+
accessToken: args.accessToken,
|
|
721
|
+
refreshToken: args.refreshToken,
|
|
722
|
+
},
|
|
723
|
+
status: 'active',
|
|
724
|
+
createdAt: Date.now(),
|
|
725
|
+
updatedAt: Date.now(),
|
|
726
|
+
});
|
|
727
|
+
|
|
728
|
+
// Connection: user → oauth_account
|
|
729
|
+
await ctx.db.insert('connections', {
|
|
730
|
+
fromEntityId: args.userId,
|
|
731
|
+
toEntityId: accountId,
|
|
732
|
+
relationshipType: 'linked_account',
|
|
733
|
+
createdAt: Date.now(),
|
|
734
|
+
});
|
|
735
|
+
|
|
736
|
+
return { id: accountId, ...args };
|
|
737
|
+
},
|
|
738
|
+
});
|
|
739
|
+
|
|
740
|
+
export const unlinkAccount = mutation({
|
|
741
|
+
args: {
|
|
742
|
+
provider: v.string(),
|
|
743
|
+
providerAccountId: v.string(),
|
|
744
|
+
},
|
|
745
|
+
handler: async (ctx, args) => {
|
|
746
|
+
const account = await ctx.db
|
|
747
|
+
.query('entities')
|
|
748
|
+
.filter((q) =>
|
|
749
|
+
q.and(
|
|
750
|
+
q.eq(q.field('type'), 'oauth_account'),
|
|
751
|
+
q.eq(q.field('properties.provider'), args.provider),
|
|
752
|
+
q.eq(q.field('properties.providerAccountId'), args.providerAccountId)
|
|
753
|
+
)
|
|
754
|
+
)
|
|
755
|
+
.first();
|
|
756
|
+
|
|
757
|
+
if (account) {
|
|
758
|
+
await ctx.db.delete(account._id);
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
return { success: true };
|
|
762
|
+
},
|
|
763
|
+
});
|
|
764
|
+
|
|
765
|
+
// Verification tokens
|
|
766
|
+
export const createVerificationToken = mutation({
|
|
767
|
+
args: {
|
|
768
|
+
identifier: v.string(), // email
|
|
769
|
+
token: v.string(),
|
|
770
|
+
expiresAt: v.number(),
|
|
771
|
+
},
|
|
772
|
+
handler: async (ctx, args) => {
|
|
773
|
+
const tokenId = await ctx.db.insert('entities', {
|
|
774
|
+
type: 'verification_token',
|
|
775
|
+
name: `Verification for ${args.identifier}`,
|
|
776
|
+
properties: {
|
|
777
|
+
identifier: args.identifier,
|
|
778
|
+
token: args.token,
|
|
779
|
+
expiresAt: args.expiresAt,
|
|
780
|
+
},
|
|
781
|
+
status: 'active',
|
|
782
|
+
createdAt: Date.now(),
|
|
783
|
+
updatedAt: Date.now(),
|
|
784
|
+
});
|
|
785
|
+
|
|
786
|
+
return { id: tokenId, ...args };
|
|
787
|
+
},
|
|
788
|
+
});
|
|
789
|
+
|
|
790
|
+
export const deleteVerificationToken = mutation({
|
|
791
|
+
args: { token: v.string() },
|
|
792
|
+
handler: async (ctx, args) => {
|
|
793
|
+
const token = await ctx.db
|
|
794
|
+
.query('entities')
|
|
795
|
+
.filter((q) =>
|
|
796
|
+
q.and(
|
|
797
|
+
q.eq(q.field('type'), 'verification_token'),
|
|
798
|
+
q.eq(q.field('properties.token'), args.token)
|
|
799
|
+
)
|
|
800
|
+
)
|
|
801
|
+
.first();
|
|
802
|
+
|
|
803
|
+
if (token) {
|
|
804
|
+
await ctx.db.delete(token._id);
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
return { success: true };
|
|
808
|
+
},
|
|
809
|
+
});
|
|
810
|
+
```
|
|
811
|
+
|
|
812
|
+
#### `convex/queries/auth.ts`
|
|
813
|
+
|
|
814
|
+
```typescript
|
|
815
|
+
import { v } from 'convex/values';
|
|
816
|
+
import { query } from '../_generated/server';
|
|
817
|
+
|
|
818
|
+
/**
|
|
819
|
+
* Auth queries for Better Auth Convex adapter
|
|
820
|
+
*/
|
|
821
|
+
|
|
822
|
+
export const getUser = query({
|
|
823
|
+
args: { id: v.id('entities') },
|
|
824
|
+
handler: async (ctx, args) => {
|
|
825
|
+
const user = await ctx.db.get(args.id);
|
|
826
|
+
if (!user || user.type !== 'user') return null;
|
|
827
|
+
|
|
828
|
+
return {
|
|
829
|
+
id: user._id,
|
|
830
|
+
email: user.properties.email,
|
|
831
|
+
name: user.name,
|
|
832
|
+
image: user.properties.image,
|
|
833
|
+
emailVerified: user.properties.emailVerified,
|
|
834
|
+
};
|
|
835
|
+
},
|
|
836
|
+
});
|
|
837
|
+
|
|
838
|
+
export const getUserByEmail = query({
|
|
839
|
+
args: { email: v.string() },
|
|
840
|
+
handler: async (ctx, args) => {
|
|
841
|
+
const user = await ctx.db
|
|
842
|
+
.query('entities')
|
|
843
|
+
.filter((q) =>
|
|
844
|
+
q.and(
|
|
845
|
+
q.eq(q.field('type'), 'user'),
|
|
846
|
+
q.eq(q.field('properties.email'), args.email)
|
|
847
|
+
)
|
|
848
|
+
)
|
|
849
|
+
.first();
|
|
850
|
+
|
|
851
|
+
if (!user) return null;
|
|
852
|
+
|
|
853
|
+
return {
|
|
854
|
+
id: user._id,
|
|
855
|
+
email: user.properties.email,
|
|
856
|
+
name: user.name,
|
|
857
|
+
image: user.properties.image,
|
|
858
|
+
emailVerified: user.properties.emailVerified,
|
|
859
|
+
};
|
|
860
|
+
},
|
|
861
|
+
});
|
|
862
|
+
|
|
863
|
+
export const getSession = query({
|
|
864
|
+
args: { token: v.string() },
|
|
865
|
+
handler: async (ctx, args) => {
|
|
866
|
+
const session = await ctx.db
|
|
867
|
+
.query('entities')
|
|
868
|
+
.filter((q) =>
|
|
869
|
+
q.and(
|
|
870
|
+
q.eq(q.field('type'), 'session'),
|
|
871
|
+
q.eq(q.field('properties.token'), args.token)
|
|
872
|
+
)
|
|
873
|
+
)
|
|
874
|
+
.first();
|
|
875
|
+
|
|
876
|
+
if (!session) return null;
|
|
877
|
+
|
|
878
|
+
// Check if expired
|
|
879
|
+
if (session.properties.expiresAt < Date.now()) {
|
|
880
|
+
await ctx.db.delete(session._id);
|
|
881
|
+
return null;
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
return {
|
|
885
|
+
id: session._id,
|
|
886
|
+
userId: session.properties.userId,
|
|
887
|
+
token: args.token,
|
|
888
|
+
expiresAt: session.properties.expiresAt,
|
|
889
|
+
};
|
|
890
|
+
},
|
|
891
|
+
});
|
|
892
|
+
|
|
893
|
+
export const getVerificationToken = query({
|
|
894
|
+
args: { token: v.string() },
|
|
895
|
+
handler: async (ctx, args) => {
|
|
896
|
+
const token = await ctx.db
|
|
897
|
+
.query('entities')
|
|
898
|
+
.filter((q) =>
|
|
899
|
+
q.and(
|
|
900
|
+
q.eq(q.field('type'), 'verification_token'),
|
|
901
|
+
q.eq(q.field('properties.token'), args.token)
|
|
902
|
+
)
|
|
903
|
+
)
|
|
904
|
+
.first();
|
|
905
|
+
|
|
906
|
+
if (!token) return null;
|
|
907
|
+
|
|
908
|
+
// Check if expired
|
|
909
|
+
if (token.properties.expiresAt < Date.now()) {
|
|
910
|
+
await ctx.db.delete(token._id);
|
|
911
|
+
return null;
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
return {
|
|
915
|
+
identifier: token.properties.identifier,
|
|
916
|
+
token: args.token,
|
|
917
|
+
expiresAt: token.properties.expiresAt,
|
|
918
|
+
};
|
|
919
|
+
},
|
|
920
|
+
});
|
|
921
|
+
```
|
|
922
|
+
|
|
923
|
+
### 5. Hono Main App
|
|
924
|
+
|
|
925
|
+
#### `api/src/index.ts`
|
|
926
|
+
|
|
927
|
+
```typescript
|
|
928
|
+
import { Hono } from 'hono';
|
|
929
|
+
import { cors } from 'hono/cors';
|
|
930
|
+
import { auth } from './auth';
|
|
931
|
+
import { tokenRoutes } from './routes/tokens';
|
|
932
|
+
import { agentRoutes } from './routes/agents';
|
|
933
|
+
import { contentRoutes } from './routes/content';
|
|
934
|
+
|
|
935
|
+
type CloudflareBindings = {
|
|
936
|
+
BETTER_AUTH_URL: string;
|
|
937
|
+
BETTER_AUTH_SECRET: string;
|
|
938
|
+
CONVEX_URL: string;
|
|
939
|
+
GITHUB_CLIENT_ID: string;
|
|
940
|
+
GITHUB_CLIENT_SECRET: string;
|
|
941
|
+
GOOGLE_CLIENT_ID: string;
|
|
942
|
+
GOOGLE_CLIENT_SECRET: string;
|
|
943
|
+
};
|
|
944
|
+
|
|
945
|
+
const app = new Hono<{ Bindings: CloudflareBindings }>();
|
|
946
|
+
|
|
947
|
+
// CORS for Astro frontend
|
|
948
|
+
app.use('/*', cors({
|
|
949
|
+
origin: ['http://localhost:4321', 'https://your-astro-frontend.pages.dev'],
|
|
950
|
+
credentials: true,
|
|
951
|
+
}));
|
|
952
|
+
|
|
953
|
+
// Better Auth endpoints (handles sign-in, sign-up, OAuth, etc.)
|
|
954
|
+
app.on(['GET', 'POST'], '/api/auth/*', (c) => {
|
|
955
|
+
return auth(c.env).handler(c.req.raw);
|
|
956
|
+
});
|
|
957
|
+
|
|
958
|
+
// Business logic routes
|
|
959
|
+
app.route('/api/tokens', tokenRoutes);
|
|
960
|
+
app.route('/api/agents', agentRoutes);
|
|
961
|
+
app.route('/api/content', contentRoutes);
|
|
962
|
+
|
|
963
|
+
// Health check
|
|
964
|
+
app.get('/health', (c) => c.json({ status: 'ok' }));
|
|
965
|
+
|
|
966
|
+
export default app;
|
|
967
|
+
```
|
|
968
|
+
|
|
969
|
+
### 6. Convex Integration Service (Effect.ts Wrapper)
|
|
970
|
+
|
|
971
|
+
#### `api/src/services/convex.ts`
|
|
972
|
+
|
|
973
|
+
```typescript
|
|
974
|
+
import { Effect, Context, Layer } from 'effect';
|
|
975
|
+
import { ConvexHttpClient } from 'convex/browser';
|
|
976
|
+
import { api } from '../../../convex/_generated/api';
|
|
977
|
+
import type { Id } from '../../../convex/_generated/dataModel';
|
|
978
|
+
|
|
979
|
+
/**
|
|
980
|
+
* Convex Database Error
|
|
981
|
+
*/
|
|
982
|
+
export class ConvexDatabaseError {
|
|
983
|
+
readonly _tag = 'ConvexDatabaseError';
|
|
984
|
+
constructor(readonly operation: string, readonly cause: unknown) {}
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
/**
|
|
988
|
+
* Convex Database Service (Effect.ts wrapper)
|
|
989
|
+
* Provides typed access to Convex functions with Effect error handling
|
|
990
|
+
*
|
|
991
|
+
* See effect.md for complete Effect.ts integration patterns
|
|
992
|
+
*/
|
|
993
|
+
export class ConvexDatabase extends Context.Tag('ConvexDatabase')<
|
|
994
|
+
ConvexDatabase,
|
|
995
|
+
{
|
|
996
|
+
// Generic operations
|
|
997
|
+
query: <T>(name: any, args: any) => Effect.Effect<T, ConvexDatabaseError>;
|
|
998
|
+
mutation: <T>(name: any, args: any) => Effect.Effect<T, ConvexDatabaseError>;
|
|
999
|
+
action: <T>(name: any, args: any) => Effect.Effect<T, ConvexDatabaseError>;
|
|
1000
|
+
|
|
1001
|
+
// Convenience methods for common operations
|
|
1002
|
+
getEntity: (id: Id<'entities'>) => Effect.Effect<any, ConvexDatabaseError>;
|
|
1003
|
+
listEntities: (type: string) => Effect.Effect<any[], ConvexDatabaseError>;
|
|
1004
|
+
}
|
|
1005
|
+
>() {
|
|
1006
|
+
/**
|
|
1007
|
+
* Live implementation (production)
|
|
1008
|
+
*/
|
|
1009
|
+
static readonly Live = Layer.effect(
|
|
1010
|
+
ConvexDatabase,
|
|
1011
|
+
Effect.gen(function* () {
|
|
1012
|
+
// Get Convex URL from environment
|
|
1013
|
+
const convexUrl = yield* Effect.sync(() => process.env.CONVEX_URL);
|
|
1014
|
+
|
|
1015
|
+
if (!convexUrl) {
|
|
1016
|
+
return yield* Effect.fail(
|
|
1017
|
+
new ConvexDatabaseError('init', 'CONVEX_URL not set')
|
|
1018
|
+
);
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
const client = new ConvexHttpClient(convexUrl);
|
|
1022
|
+
|
|
1023
|
+
return {
|
|
1024
|
+
// Generic query/mutation/action
|
|
1025
|
+
query: <T>(name: any, args: any) =>
|
|
1026
|
+
Effect.tryPromise({
|
|
1027
|
+
try: () => client.query(name, args) as Promise<T>,
|
|
1028
|
+
catch: (error) => new ConvexDatabaseError('query', error),
|
|
1029
|
+
}),
|
|
1030
|
+
|
|
1031
|
+
mutation: <T>(name: any, args: any) =>
|
|
1032
|
+
Effect.tryPromise({
|
|
1033
|
+
try: () => client.mutation(name, args) as Promise<T>,
|
|
1034
|
+
catch: (error) => new ConvexDatabaseError('mutation', error),
|
|
1035
|
+
}),
|
|
1036
|
+
|
|
1037
|
+
action: <T>(name: any, args: any) =>
|
|
1038
|
+
Effect.tryPromise({
|
|
1039
|
+
try: () => client.action(name, args) as Promise<T>,
|
|
1040
|
+
catch: (error) => new ConvexDatabaseError('action', error),
|
|
1041
|
+
}),
|
|
1042
|
+
|
|
1043
|
+
// Convenience methods
|
|
1044
|
+
getEntity: (id: Id<'entities'>) =>
|
|
1045
|
+
Effect.tryPromise({
|
|
1046
|
+
try: () => client.query(api.queries.entities.get, { id }),
|
|
1047
|
+
catch: (error) => new ConvexDatabaseError('getEntity', error),
|
|
1048
|
+
}),
|
|
1049
|
+
|
|
1050
|
+
listEntities: (type: string) =>
|
|
1051
|
+
Effect.tryPromise({
|
|
1052
|
+
try: () => client.query(api.queries.entities.list, { type }),
|
|
1053
|
+
catch: (error) => new ConvexDatabaseError('listEntities', error),
|
|
1054
|
+
}),
|
|
1055
|
+
};
|
|
1056
|
+
})
|
|
1057
|
+
);
|
|
1058
|
+
|
|
1059
|
+
/**
|
|
1060
|
+
* Create layer from environment
|
|
1061
|
+
*/
|
|
1062
|
+
static fromEnv = (convexUrl: string) =>
|
|
1063
|
+
Layer.succeed(ConvexDatabase, {
|
|
1064
|
+
query: <T>(name: any, args: any) => {
|
|
1065
|
+
const client = new ConvexHttpClient(convexUrl);
|
|
1066
|
+
return Effect.tryPromise({
|
|
1067
|
+
try: () => client.query(name, args) as Promise<T>,
|
|
1068
|
+
catch: (error) => new ConvexDatabaseError('query', error),
|
|
1069
|
+
});
|
|
1070
|
+
},
|
|
1071
|
+
mutation: <T>(name: any, args: any) => {
|
|
1072
|
+
const client = new ConvexHttpClient(convexUrl);
|
|
1073
|
+
return Effect.tryPromise({
|
|
1074
|
+
try: () => client.mutation(name, args) as Promise<T>,
|
|
1075
|
+
catch: (error) => new ConvexDatabaseError('mutation', error),
|
|
1076
|
+
});
|
|
1077
|
+
},
|
|
1078
|
+
action: <T>(name: any, args: any) => {
|
|
1079
|
+
const client = new ConvexHttpClient(convexUrl);
|
|
1080
|
+
return Effect.tryPromise({
|
|
1081
|
+
try: () => client.action(name, args) as Promise<T>,
|
|
1082
|
+
catch: (error) => new ConvexDatabaseError('action', error),
|
|
1083
|
+
});
|
|
1084
|
+
},
|
|
1085
|
+
getEntity: (id: Id<'entities'>) => {
|
|
1086
|
+
const client = new ConvexHttpClient(convexUrl);
|
|
1087
|
+
return Effect.tryPromise({
|
|
1088
|
+
try: () => client.query(api.queries.entities.get, { id }),
|
|
1089
|
+
catch: (error) => new ConvexDatabaseError('getEntity', error),
|
|
1090
|
+
});
|
|
1091
|
+
},
|
|
1092
|
+
listEntities: (type: string) => {
|
|
1093
|
+
const client = new ConvexHttpClient(convexUrl);
|
|
1094
|
+
return Effect.tryPromise({
|
|
1095
|
+
try: () => client.query(api.queries.entities.list, { type }),
|
|
1096
|
+
catch: (error) => new ConvexDatabaseError('listEntities', error),
|
|
1097
|
+
});
|
|
1098
|
+
},
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
```
|
|
1102
|
+
|
|
1103
|
+
#### `api/src/lib/effect-handler.ts`
|
|
1104
|
+
|
|
1105
|
+
```typescript
|
|
1106
|
+
import { Effect, Exit } from 'effect';
|
|
1107
|
+
import type { Context } from 'hono';
|
|
1108
|
+
|
|
1109
|
+
/**
|
|
1110
|
+
* Run Effect program in Hono route handler
|
|
1111
|
+
* Automatically converts Effect errors to HTTP responses
|
|
1112
|
+
*
|
|
1113
|
+
* See effect.md for complete usage patterns
|
|
1114
|
+
*/
|
|
1115
|
+
export async function runEffectHandler<E, A>(
|
|
1116
|
+
c: Context,
|
|
1117
|
+
program: Effect.Effect<A, E>,
|
|
1118
|
+
errorHandler?: (error: E) => { status: number; body: any }
|
|
1119
|
+
): Promise<Response> {
|
|
1120
|
+
const exit = await Effect.runPromiseExit(program);
|
|
1121
|
+
|
|
1122
|
+
return Exit.match(exit, {
|
|
1123
|
+
onSuccess: (value) => c.json(value),
|
|
1124
|
+
onFailure: (cause) => {
|
|
1125
|
+
// Extract the error
|
|
1126
|
+
const failures = cause.failures;
|
|
1127
|
+
const error = failures.length > 0 ? failures[0] : null;
|
|
1128
|
+
|
|
1129
|
+
// Use custom error handler if provided
|
|
1130
|
+
if (errorHandler && error) {
|
|
1131
|
+
const { status, body } = errorHandler(error as E);
|
|
1132
|
+
return c.json(body, status);
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
// Default error handling based on error tag
|
|
1136
|
+
if (error && typeof error === 'object' && '_tag' in error) {
|
|
1137
|
+
switch ((error as any)._tag) {
|
|
1138
|
+
case 'UnauthorizedError':
|
|
1139
|
+
return c.json({ error: 'Unauthorized' }, 401);
|
|
1140
|
+
case 'NotFoundError':
|
|
1141
|
+
return c.json({ error: 'Not found' }, 404);
|
|
1142
|
+
case 'ValidationError':
|
|
1143
|
+
return c.json({ error: (error as any).message }, 400);
|
|
1144
|
+
case 'QuotaExceededError':
|
|
1145
|
+
return c.json({
|
|
1146
|
+
error: (error as any).message,
|
|
1147
|
+
code: 'QUOTA_EXCEEDED'
|
|
1148
|
+
}, 403);
|
|
1149
|
+
case 'ConvexDatabaseError':
|
|
1150
|
+
return c.json({
|
|
1151
|
+
error: 'Database error',
|
|
1152
|
+
operation: (error as any).operation
|
|
1153
|
+
}, 500);
|
|
1154
|
+
default:
|
|
1155
|
+
return c.json({ error: 'Internal server error' }, 500);
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
return c.json({ error: 'Internal server error' }, 500);
|
|
1160
|
+
},
|
|
1161
|
+
});
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
/**
|
|
1165
|
+
* Hono Context as Effect Service
|
|
1166
|
+
*/
|
|
1167
|
+
import { Context as EffectContext } from 'effect';
|
|
1168
|
+
|
|
1169
|
+
export class HonoContextService extends EffectContext.Tag('HonoContext')<
|
|
1170
|
+
HonoContextService,
|
|
1171
|
+
{
|
|
1172
|
+
req: Context['req'];
|
|
1173
|
+
env: any;
|
|
1174
|
+
orgId?: string;
|
|
1175
|
+
session?: any;
|
|
1176
|
+
}
|
|
1177
|
+
>() {}
|
|
1178
|
+
|
|
1179
|
+
/**
|
|
1180
|
+
* Extract Hono context into Effect layer
|
|
1181
|
+
*/
|
|
1182
|
+
export const createHonoLayer = (c: Context) => {
|
|
1183
|
+
return Layer.succeed(HonoContextService, {
|
|
1184
|
+
req: c.req,
|
|
1185
|
+
env: c.env,
|
|
1186
|
+
orgId: c.get('orgId'),
|
|
1187
|
+
session: c.get('session'),
|
|
1188
|
+
});
|
|
1189
|
+
};
|
|
1190
|
+
```
|
|
1191
|
+
|
|
1192
|
+
### 7. Business Logic with Effect.ts
|
|
1193
|
+
|
|
1194
|
+
#### `api/src/services/token.ts`
|
|
1195
|
+
|
|
1196
|
+
```typescript
|
|
1197
|
+
import { Effect } from 'effect';
|
|
1198
|
+
import { ConvexService } from './convex';
|
|
1199
|
+
|
|
1200
|
+
/**
|
|
1201
|
+
* Token business logic service
|
|
1202
|
+
* Pure Effect.ts service - no side effects
|
|
1203
|
+
*/
|
|
1204
|
+
|
|
1205
|
+
// Tagged errors
|
|
1206
|
+
export class TokenNotFoundError {
|
|
1207
|
+
readonly _tag = 'TokenNotFoundError';
|
|
1208
|
+
constructor(readonly tokenId: string) {}
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
export class InsufficientFundsError {
|
|
1212
|
+
readonly _tag = 'InsufficientFundsError';
|
|
1213
|
+
constructor(readonly required: number, readonly available: number) {}
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
export class TokenService {
|
|
1217
|
+
constructor(private convex: ConvexService) {}
|
|
1218
|
+
|
|
1219
|
+
/**
|
|
1220
|
+
* Purchase tokens with validation
|
|
1221
|
+
*/
|
|
1222
|
+
purchase = (args: {
|
|
1223
|
+
userId: string;
|
|
1224
|
+
tokenId: string;
|
|
1225
|
+
amount: number;
|
|
1226
|
+
}): Effect.Effect<
|
|
1227
|
+
{ success: true; newBalance: number },
|
|
1228
|
+
TokenNotFoundError | InsufficientFundsError
|
|
1229
|
+
> =>
|
|
1230
|
+
Effect.gen(this, function* () {
|
|
1231
|
+
// Validate token exists
|
|
1232
|
+
const token = yield* Effect.promise(() => this.convex.getEntity(args.tokenId));
|
|
1233
|
+
|
|
1234
|
+
if (!token || token.type !== 'token') {
|
|
1235
|
+
return yield* Effect.fail(new TokenNotFoundError(args.tokenId));
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
// Calculate cost
|
|
1239
|
+
const cost = args.amount * token.properties.price;
|
|
1240
|
+
|
|
1241
|
+
// TODO: Verify user has funds (integrate with payment provider)
|
|
1242
|
+
// For now, assume purchase succeeds
|
|
1243
|
+
|
|
1244
|
+
// Execute purchase via Convex
|
|
1245
|
+
const result = yield* Effect.promise(() =>
|
|
1246
|
+
this.convex.purchaseTokens(args.userId, args.tokenId, args.amount)
|
|
1247
|
+
);
|
|
1248
|
+
|
|
1249
|
+
return {
|
|
1250
|
+
success: true as const,
|
|
1251
|
+
newBalance: result.balance,
|
|
1252
|
+
};
|
|
1253
|
+
});
|
|
1254
|
+
|
|
1255
|
+
/**
|
|
1256
|
+
* Get token balance
|
|
1257
|
+
*/
|
|
1258
|
+
getBalance = (args: {
|
|
1259
|
+
userId: string;
|
|
1260
|
+
tokenId: string;
|
|
1261
|
+
}): Effect.Effect<number, TokenNotFoundError> =>
|
|
1262
|
+
Effect.gen(this, function* () {
|
|
1263
|
+
const balance = yield* Effect.promise(() =>
|
|
1264
|
+
this.convex.getTokenBalance(args.userId, args.tokenId)
|
|
1265
|
+
);
|
|
1266
|
+
|
|
1267
|
+
return balance;
|
|
1268
|
+
});
|
|
1269
|
+
}
|
|
1270
|
+
```
|
|
1271
|
+
|
|
1272
|
+
### 8. API Routes with Effect.ts
|
|
1273
|
+
|
|
1274
|
+
#### `api/src/routes/tokens.ts`
|
|
1275
|
+
|
|
1276
|
+
```typescript
|
|
1277
|
+
import { Hono } from 'hono';
|
|
1278
|
+
import { Effect, Layer } from 'effect';
|
|
1279
|
+
import { runEffectHandler, createHonoLayer, HonoContextService } from '../lib/effect-handler';
|
|
1280
|
+
import { ConvexDatabase } from '../services/convex';
|
|
1281
|
+
import { TokenService } from '../../../convex/services/tokens/token';
|
|
1282
|
+
import { AuthService } from '../services/auth';
|
|
1283
|
+
import { StripeProvider } from '../services/providers/stripe';
|
|
1284
|
+
import { auth } from '../auth';
|
|
1285
|
+
|
|
1286
|
+
const app = new Hono();
|
|
1287
|
+
|
|
1288
|
+
/**
|
|
1289
|
+
* GET /api/tokens/:id
|
|
1290
|
+
* Fetch token details
|
|
1291
|
+
*/
|
|
1292
|
+
app.get('/:id', async (c) => {
|
|
1293
|
+
const tokenId = c.req.param('id');
|
|
1294
|
+
|
|
1295
|
+
// Build Effect program
|
|
1296
|
+
const program = Effect.gen(function* () {
|
|
1297
|
+
const db = yield* ConvexDatabase;
|
|
1298
|
+
|
|
1299
|
+
// Get token entity
|
|
1300
|
+
const token = yield* db.getEntity(tokenId);
|
|
1301
|
+
|
|
1302
|
+
if (!token || token.type !== 'token') {
|
|
1303
|
+
return yield* Effect.fail(new NotFoundError('Token not found'));
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
return token;
|
|
1307
|
+
});
|
|
1308
|
+
|
|
1309
|
+
// Create layer with dependencies
|
|
1310
|
+
const layer = ConvexDatabase.fromEnv(c.env.CONVEX_URL);
|
|
1311
|
+
|
|
1312
|
+
// Run Effect program with automatic error handling
|
|
1313
|
+
return runEffectHandler(c, program.pipe(Effect.provide(layer)));
|
|
1314
|
+
});
|
|
1315
|
+
|
|
1316
|
+
/**
|
|
1317
|
+
* POST /api/tokens/purchase
|
|
1318
|
+
* Purchase tokens (complete Effect.ts flow)
|
|
1319
|
+
*/
|
|
1320
|
+
app.post('/purchase', async (c) => {
|
|
1321
|
+
const { tokenId, amount } = await c.req.json();
|
|
1322
|
+
|
|
1323
|
+
// Build Effect program
|
|
1324
|
+
const program = Effect.gen(function* () {
|
|
1325
|
+
// Get dependencies
|
|
1326
|
+
const ctx = yield* HonoContextService;
|
|
1327
|
+
const authService = yield* AuthService;
|
|
1328
|
+
const tokenService = yield* TokenService;
|
|
1329
|
+
|
|
1330
|
+
// Verify authentication
|
|
1331
|
+
const session = yield* authService.getSession(ctx.req.raw.headers);
|
|
1332
|
+
if (!session) {
|
|
1333
|
+
return yield* Effect.fail(new UnauthorizedError());
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
// Check organization membership (if multi-tenant)
|
|
1337
|
+
if (ctx.orgId) {
|
|
1338
|
+
const isMember = yield* authService.checkOrgMembership({
|
|
1339
|
+
userId: session.user.id,
|
|
1340
|
+
orgId: ctx.orgId,
|
|
1341
|
+
});
|
|
1342
|
+
|
|
1343
|
+
if (!isMember) {
|
|
1344
|
+
return yield* Effect.fail(
|
|
1345
|
+
new ForbiddenError('Not a member of this organization')
|
|
1346
|
+
);
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
// Execute token purchase (Effect.ts service)
|
|
1351
|
+
const result = yield* tokenService.purchase({
|
|
1352
|
+
userId: session.user.id,
|
|
1353
|
+
tokenId,
|
|
1354
|
+
amount,
|
|
1355
|
+
orgId: ctx.orgId,
|
|
1356
|
+
});
|
|
1357
|
+
|
|
1358
|
+
// Log success
|
|
1359
|
+
yield* Effect.logInfo('Token purchase completed', {
|
|
1360
|
+
userId: session.user.id,
|
|
1361
|
+
tokenId,
|
|
1362
|
+
amount,
|
|
1363
|
+
newBalance: result.newBalance,
|
|
1364
|
+
});
|
|
1365
|
+
|
|
1366
|
+
return result;
|
|
1367
|
+
});
|
|
1368
|
+
|
|
1369
|
+
// Create layer with all dependencies
|
|
1370
|
+
const layer = Layer.mergeAll(
|
|
1371
|
+
createHonoLayer(c),
|
|
1372
|
+
ConvexDatabase.fromEnv(c.env.CONVEX_URL),
|
|
1373
|
+
StripeProvider.Live,
|
|
1374
|
+
AuthService.Default,
|
|
1375
|
+
TokenService.Default
|
|
1376
|
+
);
|
|
1377
|
+
|
|
1378
|
+
// Run Effect program (errors automatically converted to HTTP responses)
|
|
1379
|
+
return runEffectHandler(c, program.pipe(Effect.provide(layer)));
|
|
1380
|
+
});
|
|
1381
|
+
|
|
1382
|
+
/**
|
|
1383
|
+
* GET /api/tokens/balance/:tokenId
|
|
1384
|
+
* Get user's token balance
|
|
1385
|
+
*/
|
|
1386
|
+
app.get('/balance/:tokenId', async (c) => {
|
|
1387
|
+
const tokenId = c.req.param('tokenId');
|
|
1388
|
+
|
|
1389
|
+
const program = Effect.gen(function* () {
|
|
1390
|
+
const ctx = yield* HonoContextService;
|
|
1391
|
+
const authService = yield* AuthService;
|
|
1392
|
+
const tokenService = yield* TokenService;
|
|
1393
|
+
|
|
1394
|
+
// Verify authentication
|
|
1395
|
+
const session = yield* authService.getSession(ctx.req.raw.headers);
|
|
1396
|
+
if (!session) {
|
|
1397
|
+
return yield* Effect.fail(new UnauthorizedError());
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
// Get balance
|
|
1401
|
+
const balance = yield* tokenService.getBalance({
|
|
1402
|
+
userId: session.user.id,
|
|
1403
|
+
tokenId,
|
|
1404
|
+
orgId: ctx.orgId,
|
|
1405
|
+
});
|
|
1406
|
+
|
|
1407
|
+
return { balance };
|
|
1408
|
+
});
|
|
1409
|
+
|
|
1410
|
+
const layer = Layer.mergeAll(
|
|
1411
|
+
createHonoLayer(c),
|
|
1412
|
+
ConvexDatabase.fromEnv(c.env.CONVEX_URL),
|
|
1413
|
+
AuthService.Default,
|
|
1414
|
+
TokenService.Default
|
|
1415
|
+
);
|
|
1416
|
+
|
|
1417
|
+
return runEffectHandler(c, program.pipe(Effect.provide(layer)));
|
|
1418
|
+
});
|
|
1419
|
+
|
|
1420
|
+
export const tokenRoutes = app;
|
|
1421
|
+
|
|
1422
|
+
/**
|
|
1423
|
+
* Tagged Errors
|
|
1424
|
+
*/
|
|
1425
|
+
class NotFoundError {
|
|
1426
|
+
readonly _tag = 'NotFoundError';
|
|
1427
|
+
constructor(readonly message: string) {}
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
class UnauthorizedError {
|
|
1431
|
+
readonly _tag = 'UnauthorizedError';
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
class ForbiddenError {
|
|
1435
|
+
readonly _tag = 'ForbiddenError';
|
|
1436
|
+
constructor(readonly message: string) {}
|
|
1437
|
+
}
|
|
1438
|
+
```
|
|
1439
|
+
|
|
1440
|
+
**Key Benefits of This Pattern:**
|
|
1441
|
+
|
|
1442
|
+
1. **Type-Safe Error Handling** - All errors are typed with `_tag`
|
|
1443
|
+
2. **Automatic HTTP Conversion** - `runEffectHandler` converts Effect errors to HTTP responses
|
|
1444
|
+
3. **Composable Logic** - Effect programs compose cleanly
|
|
1445
|
+
4. **Testable** - Easy to test with mock layers
|
|
1446
|
+
5. **Observable** - Built-in logging via `Effect.logInfo`
|
|
1447
|
+
|
|
1448
|
+
For complete Effect.ts patterns and examples, see **[effect.md](../connections/effect.md)**.
|
|
1449
|
+
|
|
1450
|
+
### 9. Astro Frontend Integration
|
|
1451
|
+
|
|
1452
|
+
#### `src/lib/api.ts` (API Client)
|
|
1453
|
+
|
|
1454
|
+
```typescript
|
|
1455
|
+
/**
|
|
1456
|
+
* API client for Hono backend
|
|
1457
|
+
* Provides typed methods for all API endpoints
|
|
1458
|
+
*/
|
|
1459
|
+
export class APIClient {
|
|
1460
|
+
private baseURL: string;
|
|
1461
|
+
|
|
1462
|
+
constructor(baseURL: string = import.meta.env.PUBLIC_API_URL) {
|
|
1463
|
+
this.baseURL = baseURL;
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
private async request(
|
|
1467
|
+
path: string,
|
|
1468
|
+
options: RequestInit = {}
|
|
1469
|
+
): Promise<Response> {
|
|
1470
|
+
return fetch(`${this.baseURL}${path}`, {
|
|
1471
|
+
...options,
|
|
1472
|
+
credentials: 'include', // Important for Better Auth cookies
|
|
1473
|
+
headers: {
|
|
1474
|
+
'Content-Type': 'application/json',
|
|
1475
|
+
...options.headers,
|
|
1476
|
+
},
|
|
1477
|
+
});
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
// Auth methods (Better Auth endpoints)
|
|
1481
|
+
async signIn(email: string, password: string) {
|
|
1482
|
+
return this.request('/api/auth/sign-in', {
|
|
1483
|
+
method: 'POST',
|
|
1484
|
+
body: JSON.stringify({ email, password }),
|
|
1485
|
+
});
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
async signUp(email: string, password: string, name: string) {
|
|
1489
|
+
return this.request('/api/auth/sign-up', {
|
|
1490
|
+
method: 'POST',
|
|
1491
|
+
body: JSON.stringify({ email, password, name }),
|
|
1492
|
+
});
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
async signOut() {
|
|
1496
|
+
return this.request('/api/auth/sign-out', { method: 'POST' });
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
async getSession() {
|
|
1500
|
+
const res = await this.request('/api/auth/session');
|
|
1501
|
+
return res.json();
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
// Token methods
|
|
1505
|
+
async getToken(id: string) {
|
|
1506
|
+
const res = await this.request(`/api/tokens/${id}`);
|
|
1507
|
+
return res.json();
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
async purchaseTokens(tokenId: string, amount: number) {
|
|
1511
|
+
const res = await this.request('/api/tokens/purchase', {
|
|
1512
|
+
method: 'POST',
|
|
1513
|
+
body: JSON.stringify({ tokenId, amount }),
|
|
1514
|
+
});
|
|
1515
|
+
return res.json();
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
async getTokenBalance(tokenId: string) {
|
|
1519
|
+
const res = await this.request(`/api/tokens/balance/${tokenId}`);
|
|
1520
|
+
return res.json();
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1523
|
+
// Agent methods
|
|
1524
|
+
async createAgent(config: any) {
|
|
1525
|
+
const res = await this.request('/api/agents', {
|
|
1526
|
+
method: 'POST',
|
|
1527
|
+
body: JSON.stringify(config),
|
|
1528
|
+
});
|
|
1529
|
+
return res.json();
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
async getAgent(id: string) {
|
|
1533
|
+
const res = await this.request(`/api/agents/${id}`);
|
|
1534
|
+
return res.json();
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
// Content methods
|
|
1538
|
+
async createContent(content: any) {
|
|
1539
|
+
const res = await this.request('/api/content', {
|
|
1540
|
+
method: 'POST',
|
|
1541
|
+
body: JSON.stringify(content),
|
|
1542
|
+
});
|
|
1543
|
+
return res.json();
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1546
|
+
async listContent() {
|
|
1547
|
+
const res = await this.request('/api/content');
|
|
1548
|
+
return res.json();
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
export const api = new APIClient();
|
|
1553
|
+
```
|
|
1554
|
+
|
|
1555
|
+
### 10. Dual Integration Pattern (Hono + Convex + Effect.ts)
|
|
1556
|
+
|
|
1557
|
+
#### `src/components/features/tokens/TokenPurchase.tsx`
|
|
1558
|
+
|
|
1559
|
+
```typescript
|
|
1560
|
+
import { useState } from 'react';
|
|
1561
|
+
import { Effect } from 'effect';
|
|
1562
|
+
import { useQuery } from 'convex/react';
|
|
1563
|
+
import { api as convexApi } from '@/convex/_generated/api'; // Convex hooks
|
|
1564
|
+
import { TokenClientService } from '@/lib/effects/token-client';
|
|
1565
|
+
import { ClientLayer } from '@/lib/effects/layers';
|
|
1566
|
+
import { Button } from '@/components/ui/button';
|
|
1567
|
+
import { useToast } from '@/hooks/use-toast';
|
|
1568
|
+
import type { Id } from '@/convex/_generated/dataModel';
|
|
1569
|
+
|
|
1570
|
+
/**
|
|
1571
|
+
* Token purchase component demonstrating triple integration:
|
|
1572
|
+
* 1. Convex hooks for real-time data (live balance updates)
|
|
1573
|
+
* 2. Effect.ts client service for API calls (type-safe errors)
|
|
1574
|
+
* 3. Hono API backend for business logic (auth, validation, payment)
|
|
1575
|
+
*
|
|
1576
|
+
* See effect.md for complete Effect.ts client patterns
|
|
1577
|
+
*/
|
|
1578
|
+
export function TokenPurchase({ tokenId }: { tokenId: Id<'entities'> }) {
|
|
1579
|
+
const { toast } = useToast();
|
|
1580
|
+
const [loading, setLoading] = useState(false);
|
|
1581
|
+
|
|
1582
|
+
// Real-time token data via Convex (live updates!)
|
|
1583
|
+
const token = useQuery(convexApi.queries.tokens.get, { id: tokenId });
|
|
1584
|
+
|
|
1585
|
+
/**
|
|
1586
|
+
* Purchase handler using Effect.ts client service
|
|
1587
|
+
* Provides type-safe error handling and automatic retry
|
|
1588
|
+
*/
|
|
1589
|
+
const handlePurchase = async (amount: number) => {
|
|
1590
|
+
setLoading(true);
|
|
1591
|
+
|
|
1592
|
+
// Build Effect program
|
|
1593
|
+
const program = Effect.gen(function* () {
|
|
1594
|
+
const tokenService = yield* TokenClientService;
|
|
1595
|
+
|
|
1596
|
+
// Purchase tokens (calls Hono API)
|
|
1597
|
+
const result = yield* tokenService.purchase({ tokenId, amount });
|
|
1598
|
+
|
|
1599
|
+
return result;
|
|
1600
|
+
});
|
|
1601
|
+
|
|
1602
|
+
// Run Effect program with error handling
|
|
1603
|
+
const result = await Effect.runPromise(
|
|
1604
|
+
program.pipe(
|
|
1605
|
+
// Provide client dependencies
|
|
1606
|
+
Effect.provide(ClientLayer),
|
|
1607
|
+
|
|
1608
|
+
// Automatic retry on network errors
|
|
1609
|
+
Effect.retry({
|
|
1610
|
+
times: 3,
|
|
1611
|
+
schedule: Effect.Schedule.exponential('1 second'),
|
|
1612
|
+
}),
|
|
1613
|
+
|
|
1614
|
+
// Timeout after 30 seconds
|
|
1615
|
+
Effect.timeout('30 seconds'),
|
|
1616
|
+
|
|
1617
|
+
// Handle success
|
|
1618
|
+
Effect.tap(() =>
|
|
1619
|
+
Effect.sync(() =>
|
|
1620
|
+
toast({
|
|
1621
|
+
title: 'Success!',
|
|
1622
|
+
description: `Purchased ${amount} tokens`,
|
|
1623
|
+
})
|
|
1624
|
+
)
|
|
1625
|
+
),
|
|
1626
|
+
|
|
1627
|
+
// Type-safe error handling
|
|
1628
|
+
Effect.catchTag('UnauthorizedError', () =>
|
|
1629
|
+
Effect.sync(() => {
|
|
1630
|
+
toast({
|
|
1631
|
+
title: 'Unauthorized',
|
|
1632
|
+
description: 'Please sign in to purchase tokens',
|
|
1633
|
+
variant: 'destructive',
|
|
1634
|
+
});
|
|
1635
|
+
window.location.href = '/signin';
|
|
1636
|
+
return { success: false as const };
|
|
1637
|
+
})
|
|
1638
|
+
),
|
|
1639
|
+
|
|
1640
|
+
Effect.catchTag('TokenPurchaseError', (error) =>
|
|
1641
|
+
Effect.sync(() => {
|
|
1642
|
+
toast({
|
|
1643
|
+
title: 'Purchase Failed',
|
|
1644
|
+
description: error.message,
|
|
1645
|
+
variant: 'destructive',
|
|
1646
|
+
});
|
|
1647
|
+
return { success: false as const };
|
|
1648
|
+
})
|
|
1649
|
+
),
|
|
1650
|
+
|
|
1651
|
+
Effect.catchTag('NetworkError', (error) =>
|
|
1652
|
+
Effect.sync(() => {
|
|
1653
|
+
toast({
|
|
1654
|
+
title: 'Network Error',
|
|
1655
|
+
description: 'Please check your connection and try again',
|
|
1656
|
+
variant: 'destructive',
|
|
1657
|
+
});
|
|
1658
|
+
return { success: false as const };
|
|
1659
|
+
})
|
|
1660
|
+
),
|
|
1661
|
+
|
|
1662
|
+
Effect.catchTag('TimeoutException', () =>
|
|
1663
|
+
Effect.sync(() => {
|
|
1664
|
+
toast({
|
|
1665
|
+
title: 'Request Timeout',
|
|
1666
|
+
description: 'Purchase took too long, please try again',
|
|
1667
|
+
variant: 'destructive',
|
|
1668
|
+
});
|
|
1669
|
+
return { success: false as const };
|
|
1670
|
+
})
|
|
1671
|
+
)
|
|
1672
|
+
)
|
|
1673
|
+
);
|
|
1674
|
+
|
|
1675
|
+
setLoading(false);
|
|
1676
|
+
|
|
1677
|
+
// Convex subscription automatically updates balance in real-time!
|
|
1678
|
+
};
|
|
1679
|
+
|
|
1680
|
+
if (!token) return <div>Loading...</div>;
|
|
1681
|
+
|
|
1682
|
+
return (
|
|
1683
|
+
<div className="space-y-4">
|
|
1684
|
+
<h2 className="text-2xl font-bold">{token.name}</h2>
|
|
1685
|
+
<p className="text-muted-foreground">
|
|
1686
|
+
Price: ${token.properties.price}
|
|
1687
|
+
</p>
|
|
1688
|
+
|
|
1689
|
+
{/* Real-time balance via Convex subscription */}
|
|
1690
|
+
<p className="text-sm text-muted-foreground">
|
|
1691
|
+
Your balance: {token.properties.balance || 0} tokens
|
|
1692
|
+
</p>
|
|
1693
|
+
|
|
1694
|
+
<Button onClick={() => handlePurchase(100)} disabled={loading}>
|
|
1695
|
+
{loading ? 'Processing...' : 'Buy 100 Tokens'}
|
|
1696
|
+
</Button>
|
|
1697
|
+
</div>
|
|
1698
|
+
);
|
|
1699
|
+
}
|
|
1700
|
+
```
|
|
1701
|
+
|
|
1702
|
+
**Key Benefits of Triple Integration:**
|
|
1703
|
+
|
|
1704
|
+
1. **Real-Time Data** - Convex hooks provide live subscriptions (balance updates automatically)
|
|
1705
|
+
2. **Type-Safe Errors** - Effect.ts client catches all error types with `catchTag`
|
|
1706
|
+
3. **Automatic Retry** - Effect retries network failures with exponential backoff
|
|
1707
|
+
4. **Timeout Protection** - Effect prevents hanging requests
|
|
1708
|
+
5. **Composable Logic** - Effect programs combine cleanly
|
|
1709
|
+
6. **Better UX** - User sees optimistic updates + error messages
|
|
1710
|
+
|
|
1711
|
+
For complete Effect.ts client patterns, see **[effect.md](../connections/effect.md)**.
|
|
1712
|
+
|
|
1713
|
+
### 11. Environment Variables
|
|
1714
|
+
|
|
1715
|
+
#### Hono API (`.dev.vars` / Cloudflare Workers settings)
|
|
1716
|
+
|
|
1717
|
+
```bash
|
|
1718
|
+
# Better Auth
|
|
1719
|
+
BETTER_AUTH_URL=http://localhost:8787
|
|
1720
|
+
BETTER_AUTH_SECRET=your-secret-key
|
|
1721
|
+
|
|
1722
|
+
# Convex
|
|
1723
|
+
CONVEX_URL=https://xxx.convex.cloud
|
|
1724
|
+
CONVEX_DEPLOY_KEY=xxx
|
|
1725
|
+
|
|
1726
|
+
# OAuth (optional)
|
|
1727
|
+
GITHUB_CLIENT_ID=xxx
|
|
1728
|
+
GITHUB_CLIENT_SECRET=xxx
|
|
1729
|
+
GOOGLE_CLIENT_ID=xxx
|
|
1730
|
+
GOOGLE_CLIENT_SECRET=xxx
|
|
1731
|
+
```
|
|
1732
|
+
|
|
1733
|
+
#### Astro Frontend (`.env`)
|
|
1734
|
+
|
|
1735
|
+
```bash
|
|
1736
|
+
# Public URLs
|
|
1737
|
+
PUBLIC_API_URL=http://localhost:8787
|
|
1738
|
+
PUBLIC_CONVEX_URL=https://xxx.convex.cloud
|
|
1739
|
+
```
|
|
1740
|
+
|
|
1741
|
+
## Development Workflow
|
|
1742
|
+
|
|
1743
|
+
### Terminal Setup
|
|
1744
|
+
|
|
1745
|
+
```bash
|
|
1746
|
+
# Terminal 1: Hono API
|
|
1747
|
+
cd api
|
|
1748
|
+
bun run dev # Runs on localhost:8787
|
|
1749
|
+
|
|
1750
|
+
# Terminal 2: Convex backend
|
|
1751
|
+
npx convex dev # Runs Convex functions locally
|
|
1752
|
+
|
|
1753
|
+
# Terminal 3: Astro frontend
|
|
1754
|
+
cd ..
|
|
1755
|
+
bun run dev # Runs on localhost:4321
|
|
1756
|
+
```
|
|
1757
|
+
|
|
1758
|
+
### "Vibe Code" Workflow
|
|
1759
|
+
|
|
1760
|
+
```
|
|
1761
|
+
1. User designs UI mockup
|
|
1762
|
+
2. User writes React component with Convex hooks
|
|
1763
|
+
3. Component shows real-time data (no backend changes!)
|
|
1764
|
+
4. User deploys frontend to Cloudflare Pages
|
|
1765
|
+
5. Done! ✅
|
|
1766
|
+
```
|
|
1767
|
+
|
|
1768
|
+
**Example: Building a dashboard page**
|
|
1769
|
+
|
|
1770
|
+
```astro
|
|
1771
|
+
---
|
|
1772
|
+
// src/pages/dashboard.astro
|
|
1773
|
+
import CreatorStats from '@/components/dashboard/CreatorStats';
|
|
1774
|
+
---
|
|
1775
|
+
|
|
1776
|
+
<Layout>
|
|
1777
|
+
<div class="container py-8">
|
|
1778
|
+
<h1>Dashboard</h1>
|
|
1779
|
+
|
|
1780
|
+
{/* Real-time stats with Convex hooks - zero backend code! */}
|
|
1781
|
+
<CreatorStats client:load />
|
|
1782
|
+
</div>
|
|
1783
|
+
</Layout>
|
|
1784
|
+
```
|
|
1785
|
+
|
|
1786
|
+
```typescript
|
|
1787
|
+
// src/components/dashboard/CreatorStats.tsx
|
|
1788
|
+
import { useQuery } from 'convex/react';
|
|
1789
|
+
import { api } from '@/convex/_generated/api';
|
|
1790
|
+
|
|
1791
|
+
export function CreatorStats() {
|
|
1792
|
+
// Real-time data - updates automatically!
|
|
1793
|
+
const stats = useQuery(api.queries.dashboard.getStats);
|
|
1794
|
+
|
|
1795
|
+
return (
|
|
1796
|
+
<div className="grid grid-cols-3 gap-4">
|
|
1797
|
+
<Card>
|
|
1798
|
+
<CardTitle>Revenue</CardTitle>
|
|
1799
|
+
<CardContent>${stats?.revenue || 0}</CardContent>
|
|
1800
|
+
</Card>
|
|
1801
|
+
{/* More cards... */}
|
|
1802
|
+
</div>
|
|
1803
|
+
);
|
|
1804
|
+
}
|
|
1805
|
+
```
|
|
1806
|
+
|
|
1807
|
+
## When to Use Hono API vs Convex Direct
|
|
1808
|
+
|
|
1809
|
+
### Use Hono API For:
|
|
1810
|
+
|
|
1811
|
+
- **Authentication**: Login, signup, password reset, OAuth
|
|
1812
|
+
- **Business Logic**: Token purchases, payment processing, complex workflows
|
|
1813
|
+
- **External APIs**: Stripe, Resend, third-party services
|
|
1814
|
+
- **Heavy Computation**: Data aggregation, report generation
|
|
1815
|
+
- **Rate Limiting**: API throttling, abuse prevention
|
|
1816
|
+
- **REST API Contracts**: External integrations, mobile apps
|
|
1817
|
+
|
|
1818
|
+
### Use Convex Direct For:
|
|
1819
|
+
|
|
1820
|
+
- **Real-time Updates**: Live data, subscriptions, WebSocket-like behavior
|
|
1821
|
+
- **Simple Queries**: Fetching entities, connections, events
|
|
1822
|
+
- **Client-Side Logic**: Filtering, sorting, pagination
|
|
1823
|
+
- **Optimistic Updates**: Instant UI feedback
|
|
1824
|
+
- **Dashboard Data**: Live metrics, analytics
|
|
1825
|
+
|
|
1826
|
+
### Example: Token Purchase Flow
|
|
1827
|
+
|
|
1828
|
+
```
|
|
1829
|
+
User clicks "Buy Tokens"
|
|
1830
|
+
↓
|
|
1831
|
+
Component calls Hono API (POST /api/tokens/purchase)
|
|
1832
|
+
↓
|
|
1833
|
+
Hono validates session (Better Auth)
|
|
1834
|
+
↓
|
|
1835
|
+
Effect.ts service processes business logic
|
|
1836
|
+
↓
|
|
1837
|
+
Service calls Convex mutation to update balance
|
|
1838
|
+
↓
|
|
1839
|
+
Convex updates entities table
|
|
1840
|
+
↓
|
|
1841
|
+
Convex real-time subscription pushes update to UI
|
|
1842
|
+
↓
|
|
1843
|
+
Component re-renders with new balance ✅
|
|
1844
|
+
```
|
|
1845
|
+
|
|
1846
|
+
## Deployment
|
|
1847
|
+
|
|
1848
|
+
### Production Architecture
|
|
1849
|
+
|
|
1850
|
+
```
|
|
1851
|
+
┌────────────────────────────────────────┐
|
|
1852
|
+
│ Cloudflare Pages (Astro Frontend) │
|
|
1853
|
+
│ https://oneie.pages.dev │
|
|
1854
|
+
└──────────────┬─────────────────────────┘
|
|
1855
|
+
│ HTTPS
|
|
1856
|
+
▼
|
|
1857
|
+
┌────────────────────────────────────────┐
|
|
1858
|
+
│ Cloudflare Workers (Hono API) │
|
|
1859
|
+
│ https://api.oneieworkers.dev │
|
|
1860
|
+
└──────────────┬─────────────────────────┘
|
|
1861
|
+
│ HTTPS
|
|
1862
|
+
▼
|
|
1863
|
+
┌────────────────────────────────────────┐
|
|
1864
|
+
│ Convex Cloud (Database + Functions) │
|
|
1865
|
+
│ https://xxx.convex.cloud │
|
|
1866
|
+
└────────────────────────────────────────┘
|
|
1867
|
+
```
|
|
1868
|
+
|
|
1869
|
+
### Deploy Commands
|
|
1870
|
+
|
|
1871
|
+
```bash
|
|
1872
|
+
# 1. Deploy Convex functions
|
|
1873
|
+
npx convex deploy
|
|
1874
|
+
|
|
1875
|
+
# 2. Deploy Hono API to Cloudflare Workers
|
|
1876
|
+
cd api
|
|
1877
|
+
wrangler deploy
|
|
1878
|
+
|
|
1879
|
+
# 3. Deploy Astro frontend to Cloudflare Pages
|
|
1880
|
+
cd ..
|
|
1881
|
+
bun run build
|
|
1882
|
+
wrangler pages deploy dist --project-name=one-platform
|
|
1883
|
+
```
|
|
1884
|
+
|
|
1885
|
+
## Migration Strategy
|
|
1886
|
+
|
|
1887
|
+
### Phase 1: Add Hono API (Parallel)
|
|
1888
|
+
|
|
1889
|
+
- Create `api/` directory
|
|
1890
|
+
- Set up Hono with Better Auth + Convex adapter
|
|
1891
|
+
- Keep existing Astro auth working
|
|
1892
|
+
- Deploy Hono API to Workers
|
|
1893
|
+
- Test API endpoints independently
|
|
1894
|
+
|
|
1895
|
+
### Phase 2: Migrate Authentication
|
|
1896
|
+
|
|
1897
|
+
- Update Astro to use Hono API for auth
|
|
1898
|
+
- Migrate Better Auth logic from Astro to Hono
|
|
1899
|
+
- Update all auth-related components
|
|
1900
|
+
- Test session management across both systems
|
|
1901
|
+
|
|
1902
|
+
### Phase 3: Extract Business Logic
|
|
1903
|
+
|
|
1904
|
+
- Move token purchase logic to Hono routes + Effect.ts
|
|
1905
|
+
- Move agent creation to Hono routes + Effect.ts
|
|
1906
|
+
- Move content creation to Hono routes + Effect.ts
|
|
1907
|
+
- Keep Convex for data layer + real-time subscriptions
|
|
1908
|
+
|
|
1909
|
+
### Phase 4: Optimize Frontend
|
|
1910
|
+
|
|
1911
|
+
- Remove server-side business logic from Astro
|
|
1912
|
+
- Use API client for all mutations/actions
|
|
1913
|
+
- Use Convex hooks for real-time data
|
|
1914
|
+
- Deploy as static site to Pages (if desired)
|
|
1915
|
+
|
|
1916
|
+
### Phase 5: Multi-Tenant Support
|
|
1917
|
+
|
|
1918
|
+
- Add org-specific API keys
|
|
1919
|
+
- Enable frontend customization per org
|
|
1920
|
+
- Deploy custom frontends to subdomains
|
|
1921
|
+
- Share same Hono API + Convex backend
|
|
1922
|
+
|
|
1923
|
+
## Integration with 6-Dimension Ontology
|
|
1924
|
+
|
|
1925
|
+
The Hono API fully respects the ontology:
|
|
1926
|
+
|
|
1927
|
+
### Entities
|
|
1928
|
+
|
|
1929
|
+
- Auth data (users, sessions, accounts) stored as entities
|
|
1930
|
+
- All business objects (tokens, agents, content) are entities
|
|
1931
|
+
- Hono routes operate on entities via Convex
|
|
1932
|
+
|
|
1933
|
+
### Connections
|
|
1934
|
+
|
|
1935
|
+
- User → session connections (has_session)
|
|
1936
|
+
- User → OAuth account connections (linked_account)
|
|
1937
|
+
- User → token connections (holds_tokens)
|
|
1938
|
+
- Creator → content connections (authored)
|
|
1939
|
+
|
|
1940
|
+
### Events
|
|
1941
|
+
|
|
1942
|
+
- Every API call logs an event
|
|
1943
|
+
- Auth events: sign_in, sign_up, sign_out
|
|
1944
|
+
- Business events: tokens_purchased, agent_created, content_published
|
|
1945
|
+
- Events enable audit trails and analytics
|
|
1946
|
+
|
|
1947
|
+
### Tags
|
|
1948
|
+
|
|
1949
|
+
- Entities can be tagged via API
|
|
1950
|
+
- Tags enable categorization and filtering
|
|
1951
|
+
- Query entities by tags
|
|
1952
|
+
|
|
1953
|
+
## Benefits Summary
|
|
1954
|
+
|
|
1955
|
+
1. **Single Database**: All data (including auth) in Convex - no external DB needed
|
|
1956
|
+
2. **Type Safety**: End-to-end TypeScript from frontend → Hono → Effect.ts → Convex
|
|
1957
|
+
3. **Real-Time**: Convex subscriptions for live updates
|
|
1958
|
+
4. **Functional**: Pure Effect.ts services with explicit error handling
|
|
1959
|
+
5. **Separation**: API backend vs frontend - deploy independently
|
|
1960
|
+
6. **Multi-Tenant**: Custom frontends sharing backend
|
|
1961
|
+
7. **Vibe Code**: Rapid frontend development with Convex hooks
|
|
1962
|
+
8. **Performance**: Edge SSR on Cloudflare Workers
|
|
1963
|
+
9. **Security**: Better Auth session management
|
|
1964
|
+
10. **Scalability**: Independent scaling of frontend, API, and database
|
|
1965
|
+
|
|
1966
|
+
## Next Steps
|
|
1967
|
+
|
|
1968
|
+
1. Create `api/` directory for Hono backend
|
|
1969
|
+
2. Implement Better Auth with Convex adapter
|
|
1970
|
+
3. Create Convex auth mutations/queries (entities table)
|
|
1971
|
+
4. Set up ConvexService integration layer
|
|
1972
|
+
5. Implement Effect.ts business logic services
|
|
1973
|
+
6. Create Hono API routes
|
|
1974
|
+
7. Build Astro API client (`src/lib/api.ts`)
|
|
1975
|
+
8. Update React components to use dual integration
|
|
1976
|
+
9. Test authentication flow end-to-end
|
|
1977
|
+
10. Deploy to Cloudflare Workers + Pages
|
|
1978
|
+
|
|
1979
|
+
**Result:** A clean, scalable architecture where users can rapidly customize frontends while the platform team maintains a robust, shared backend powered by Convex + Effect.ts.
|
|
1980
|
+
|
|
1981
|
+
---
|
|
1982
|
+
|
|
1983
|
+
## Decision Guide: Which Approach to Use?
|
|
1984
|
+
|
|
1985
|
+
### Choose Convex-Native When:
|
|
1986
|
+
|
|
1987
|
+
✅ **Simple Single-Tenant App**
|
|
1988
|
+
- You're building one application for one organization
|
|
1989
|
+
- Don't need multiple custom frontends
|
|
1990
|
+
- Want fastest development velocity
|
|
1991
|
+
|
|
1992
|
+
✅ **MVP or Prototype**
|
|
1993
|
+
- Need to validate idea quickly
|
|
1994
|
+
- Minimum infrastructure complexity
|
|
1995
|
+
- Can iterate rapidly
|
|
1996
|
+
|
|
1997
|
+
✅ **Small Team**
|
|
1998
|
+
- 1-5 developers
|
|
1999
|
+
- Everyone works on full-stack features
|
|
2000
|
+
- Don't need strict frontend/backend separation
|
|
2001
|
+
|
|
2002
|
+
✅ **Direct Convex Access is Critical**
|
|
2003
|
+
- Need real-time subscriptions in API routes
|
|
2004
|
+
- Want to avoid HTTP overhead
|
|
2005
|
+
- Leveraging Convex-specific features
|
|
2006
|
+
|
|
2007
|
+
**Example Use Cases:**
|
|
2008
|
+
- SaaS dashboard for single company
|
|
2009
|
+
- Internal tools
|
|
2010
|
+
- Rapid prototypes
|
|
2011
|
+
- Blog with custom API endpoints
|
|
2012
|
+
|
|
2013
|
+
### Choose Separate API When:
|
|
2014
|
+
|
|
2015
|
+
✅ **Multi-Tenant Platform**
|
|
2016
|
+
- Different organizations need custom frontends
|
|
2017
|
+
- Shared backend across tenants
|
|
2018
|
+
- White-label solutions
|
|
2019
|
+
|
|
2020
|
+
✅ **Large Team**
|
|
2021
|
+
- 10+ developers
|
|
2022
|
+
- Clear frontend/backend team split
|
|
2023
|
+
- Need independent deployment cycles
|
|
2024
|
+
|
|
2025
|
+
✅ **Multi-Client Architecture**
|
|
2026
|
+
- API serves web, mobile, desktop
|
|
2027
|
+
- Third-party integrations
|
|
2028
|
+
- Public API for external developers
|
|
2029
|
+
|
|
2030
|
+
✅ **Complex Business Logic**
|
|
2031
|
+
- Need Effect.ts services everywhere
|
|
2032
|
+
- External API integrations (Stripe, OpenAI, etc.)
|
|
2033
|
+
- Advanced error handling and retry logic
|
|
2034
|
+
|
|
2035
|
+
**Example Use Cases:**
|
|
2036
|
+
- Creator economy platform (ONE)
|
|
2037
|
+
- E-commerce with mobile app
|
|
2038
|
+
- API-first products
|
|
2039
|
+
- Enterprise SaaS with customization
|
|
2040
|
+
|
|
2041
|
+
### Hybrid Approach (Advanced)
|
|
2042
|
+
|
|
2043
|
+
You can use **both** approaches together:
|
|
2044
|
+
|
|
2045
|
+
```
|
|
2046
|
+
Convex-Native (convex/http.ts):
|
|
2047
|
+
├─ Internal admin endpoints
|
|
2048
|
+
├─ Webhooks from external services
|
|
2049
|
+
└─ Simple read-only APIs
|
|
2050
|
+
|
|
2051
|
+
Separate API (Cloudflare Workers):
|
|
2052
|
+
├─ Public-facing REST API
|
|
2053
|
+
├─ Complex business logic (Effect.ts)
|
|
2054
|
+
└─ Multi-tenant routing
|
|
2055
|
+
```
|
|
2056
|
+
|
|
2057
|
+
**Benefits:**
|
|
2058
|
+
- Simple endpoints stay in Convex (less overhead)
|
|
2059
|
+
- Complex logic in separate API (better separation)
|
|
2060
|
+
- Best of both worlds
|
|
2061
|
+
|
|
2062
|
+
**Trade-offs:**
|
|
2063
|
+
- More complexity to manage
|
|
2064
|
+
- Two deployment processes
|
|
2065
|
+
- Documentation overhead
|
|
2066
|
+
|
|
2067
|
+
### Migration Path
|
|
2068
|
+
|
|
2069
|
+
**Start with Convex-Native → Move to Separate API:**
|
|
2070
|
+
|
|
2071
|
+
1. **Phase 1:** Build MVP with Convex-Native
|
|
2072
|
+
2. **Phase 2:** Extract business logic to Effect.ts services
|
|
2073
|
+
3. **Phase 3:** Move services to separate Hono API on Workers
|
|
2074
|
+
4. **Phase 4:** Keep simple endpoints in Convex, complex in Workers
|
|
2075
|
+
|
|
2076
|
+
**This is the recommended path for most projects.**
|
|
2077
|
+
|
|
2078
|
+
---
|
|
2079
|
+
|
|
2080
|
+
## Summary
|
|
2081
|
+
|
|
2082
|
+
**Convex-Native:**
|
|
2083
|
+
- ✅ Official Convex pattern
|
|
2084
|
+
- ✅ Simplest deployment
|
|
2085
|
+
- ✅ Direct Convex access
|
|
2086
|
+
- ❌ Limited multi-tenancy
|
|
2087
|
+
- ❌ Harder to separate teams
|
|
2088
|
+
|
|
2089
|
+
**Separate API:**
|
|
2090
|
+
- ✅ Multi-tenant support
|
|
2091
|
+
- ✅ Team separation
|
|
2092
|
+
- ✅ API reusability
|
|
2093
|
+
- ❌ More infrastructure
|
|
2094
|
+
- ❌ HTTP overhead to Convex
|
|
2095
|
+
|
|
2096
|
+
**Both approaches use:**
|
|
2097
|
+
- Hono for routing
|
|
2098
|
+
- Convex for data storage (6-dimension ontology)
|
|
2099
|
+
- Effect.ts for business logic (optional but recommended)
|
|
2100
|
+
- Type-safe validation (Zod)
|
|
2101
|
+
- CORS middleware
|
|
2102
|
+
|
|
2103
|
+
**Official Resources:**
|
|
2104
|
+
- [Hono with Convex](https://stack.convex.dev/hono-with-convex) - Convex Stack guide
|
|
2105
|
+
- [convex-helpers](https://stack.convex.dev/convex-helpers) - Helper library
|
|
2106
|
+
- [Hono Documentation](https://hono.dev/) - Hono framework
|
|
2107
|
+
- [Effect.ts Documentation](https://effect.website/) - Functional programming
|
|
2108
|
+
|
|
2109
|
+
Choose the approach that matches your team size, architecture needs, and deployment preferences. When in doubt, **start with Convex-Native** and migrate to Separate API when you need multi-tenancy or team separation.
|