@girardmedia/bootspring 1.2.0 → 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.
Files changed (253) hide show
  1. package/README.md +107 -14
  2. package/bin/bootspring.js +166 -27
  3. package/cli/agent.js +189 -17
  4. package/cli/analyze.js +499 -0
  5. package/cli/audit.js +557 -0
  6. package/cli/auth.js +495 -38
  7. package/cli/billing.js +302 -0
  8. package/cli/build.js +695 -0
  9. package/cli/business.js +109 -26
  10. package/cli/checkpoint-utils.js +168 -0
  11. package/cli/checkpoint.js +639 -0
  12. package/cli/cloud-sync.js +447 -0
  13. package/cli/content.js +198 -0
  14. package/cli/context.js +1 -1
  15. package/cli/deploy.js +543 -0
  16. package/cli/fundraise.js +112 -50
  17. package/cli/github-cmd.js +435 -0
  18. package/cli/health.js +477 -0
  19. package/cli/init.js +84 -13
  20. package/cli/legal.js +107 -95
  21. package/cli/log.js +2 -2
  22. package/cli/loop.js +976 -73
  23. package/cli/manager.js +711 -0
  24. package/cli/metrics.js +480 -0
  25. package/cli/monitor.js +812 -0
  26. package/cli/onboard.js +521 -0
  27. package/cli/orchestrator.js +12 -24
  28. package/cli/prd.js +594 -0
  29. package/cli/preseed-start.js +1483 -0
  30. package/cli/preseed.js +2302 -0
  31. package/cli/project.js +436 -0
  32. package/cli/quality.js +233 -0
  33. package/cli/security.js +913 -0
  34. package/cli/seed.js +1441 -5
  35. package/cli/skill.js +273 -211
  36. package/cli/suggest.js +989 -0
  37. package/cli/switch.js +453 -0
  38. package/cli/visualize.js +527 -0
  39. package/cli/watch.js +769 -0
  40. package/cli/workspace.js +607 -0
  41. package/core/analyze-workflow.js +1134 -0
  42. package/core/api-client.js +535 -22
  43. package/core/audit-workflow.js +1350 -0
  44. package/core/build-orchestrator.js +480 -0
  45. package/core/build-state.js +577 -0
  46. package/core/checkpoint-engine.js +408 -0
  47. package/core/config.js +1109 -26
  48. package/core/context-loader.js +21 -1
  49. package/core/deploy-workflow.js +836 -0
  50. package/core/entitlements.js +93 -22
  51. package/core/github-sync.js +610 -0
  52. package/core/index.js +8 -1
  53. package/core/ingest.js +1111 -0
  54. package/core/metrics-engine.js +768 -0
  55. package/core/onboard-workflow.js +1007 -0
  56. package/core/preseed-workflow.js +934 -0
  57. package/core/preseed.js +1617 -0
  58. package/core/project-context.js +325 -0
  59. package/core/project-state.js +694 -0
  60. package/core/r2-sync.js +583 -0
  61. package/core/scaffold.js +525 -7
  62. package/core/session.js +258 -0
  63. package/core/task-extractor.js +758 -0
  64. package/core/telemetry.js +28 -6
  65. package/core/tier-enforcement.js +737 -0
  66. package/core/utils.js +38 -14
  67. package/generators/questionnaire.js +15 -12
  68. package/generators/sections/ai.js +7 -7
  69. package/generators/sections/content.js +300 -0
  70. package/generators/sections/index.js +3 -0
  71. package/generators/sections/plugins.js +7 -6
  72. package/generators/templates/build-planning.template.js +596 -0
  73. package/generators/templates/content.template.js +819 -0
  74. package/generators/templates/index.js +2 -1
  75. package/hooks/git-autopilot.js +1250 -0
  76. package/hooks/index.js +9 -0
  77. package/intelligence/agent-collab.js +2057 -0
  78. package/intelligence/auto-suggest.js +634 -0
  79. package/intelligence/content-gen.js +1589 -0
  80. package/intelligence/cross-project.js +1647 -0
  81. package/intelligence/index.js +184 -0
  82. package/intelligence/learning/insights.json +517 -7
  83. package/intelligence/learning/pattern-learner.js +1008 -14
  84. package/intelligence/memory/decision-tracker.js +1431 -31
  85. package/intelligence/memory/decisions.jsonl +0 -0
  86. package/intelligence/orchestrator.js +2896 -1
  87. package/intelligence/prd.js +92 -1
  88. package/intelligence/recommendation-weights.json +14 -2
  89. package/intelligence/recommendations.js +463 -9
  90. package/intelligence/workflow-composer.js +1451 -0
  91. package/marketplace/index.d.ts +324 -0
  92. package/marketplace/index.js +1921 -0
  93. package/mcp/contracts/mcp-contract.v1.json +342 -4
  94. package/mcp/registry.js +680 -3
  95. package/mcp/response-formatter.js +23 -0
  96. package/mcp/tools/assist-tool.js +78 -4
  97. package/mcp/tools/autopilot-tool.js +408 -0
  98. package/mcp/tools/content-tool.js +571 -0
  99. package/mcp/tools/dashboard-tool.js +251 -5
  100. package/mcp/tools/mvp-tool.js +344 -0
  101. package/mcp/tools/plugin-tool.js +23 -1
  102. package/mcp/tools/prd-tool.js +579 -0
  103. package/mcp/tools/seed-tool.js +447 -0
  104. package/mcp/tools/skill-tool.js +43 -14
  105. package/mcp/tools/suggest-tool.js +147 -0
  106. package/package.json +15 -6
  107. package/agents/README.md +0 -93
  108. package/agents/ai-integration-expert/context.md +0 -386
  109. package/agents/api-expert/context.md +0 -416
  110. package/agents/architecture-expert/context.md +0 -454
  111. package/agents/auth-expert/context.md +0 -399
  112. package/agents/backend-expert/context.md +0 -483
  113. package/agents/business-strategy-expert/context.md +0 -180
  114. package/agents/code-review-expert/context.md +0 -365
  115. package/agents/competitive-analysis-expert/context.md +0 -239
  116. package/agents/data-modeling-expert/context.md +0 -352
  117. package/agents/database-expert/context.md +0 -250
  118. package/agents/devops-expert/context.md +0 -446
  119. package/agents/email-expert/context.md +0 -379
  120. package/agents/financial-expert/context.md +0 -213
  121. package/agents/frontend-expert/context.md +0 -364
  122. package/agents/fundraising-expert/context.md +0 -257
  123. package/agents/growth-expert/context.md +0 -249
  124. package/agents/index.js +0 -140
  125. package/agents/investor-relations-expert/context.md +0 -266
  126. package/agents/legal-expert/context.md +0 -284
  127. package/agents/marketing-expert/context.md +0 -236
  128. package/agents/monitoring-expert/context.md +0 -362
  129. package/agents/operations-expert/context.md +0 -279
  130. package/agents/partnerships-expert/context.md +0 -286
  131. package/agents/payment-expert/context.md +0 -340
  132. package/agents/performance-expert/context.md +0 -377
  133. package/agents/private-equity-expert/context.md +0 -246
  134. package/agents/railway-expert/context.md +0 -284
  135. package/agents/research-expert/context.md +0 -245
  136. package/agents/sales-expert/context.md +0 -241
  137. package/agents/security-expert/context.md +0 -343
  138. package/agents/testing-expert/context.md +0 -414
  139. package/agents/ui-ux-expert/context.md +0 -448
  140. package/agents/vercel-expert/context.md +0 -426
  141. package/skills/index.js +0 -787
  142. package/skills/patterns/README.md +0 -163
  143. package/skills/patterns/ai/agents.md +0 -281
  144. package/skills/patterns/ai/claude.md +0 -138
  145. package/skills/patterns/ai/embeddings.md +0 -150
  146. package/skills/patterns/ai/rag.md +0 -266
  147. package/skills/patterns/ai/streaming.md +0 -170
  148. package/skills/patterns/ai/structured-output.md +0 -162
  149. package/skills/patterns/ai/tools.md +0 -154
  150. package/skills/patterns/analytics/tracking.md +0 -220
  151. package/skills/patterns/api/errors.md +0 -296
  152. package/skills/patterns/api/graphql.md +0 -440
  153. package/skills/patterns/api/middleware.md +0 -279
  154. package/skills/patterns/api/openapi.md +0 -285
  155. package/skills/patterns/api/rate-limiting.md +0 -231
  156. package/skills/patterns/api/route-handler.md +0 -217
  157. package/skills/patterns/api/server-action.md +0 -249
  158. package/skills/patterns/api/versioning.md +0 -443
  159. package/skills/patterns/api/webhooks.md +0 -247
  160. package/skills/patterns/auth/clerk.md +0 -132
  161. package/skills/patterns/auth/mfa.md +0 -313
  162. package/skills/patterns/auth/nextauth.md +0 -140
  163. package/skills/patterns/auth/oauth.md +0 -237
  164. package/skills/patterns/auth/rbac.md +0 -152
  165. package/skills/patterns/auth/session-management.md +0 -367
  166. package/skills/patterns/auth/session.md +0 -120
  167. package/skills/patterns/database/audit.md +0 -177
  168. package/skills/patterns/database/migrations.md +0 -177
  169. package/skills/patterns/database/pagination.md +0 -230
  170. package/skills/patterns/database/pooling.md +0 -357
  171. package/skills/patterns/database/prisma.md +0 -180
  172. package/skills/patterns/database/relations.md +0 -187
  173. package/skills/patterns/database/seeding.md +0 -246
  174. package/skills/patterns/database/soft-delete.md +0 -153
  175. package/skills/patterns/database/transactions.md +0 -162
  176. package/skills/patterns/deployment/ci-cd.md +0 -231
  177. package/skills/patterns/deployment/docker.md +0 -188
  178. package/skills/patterns/deployment/monitoring.md +0 -387
  179. package/skills/patterns/deployment/vercel.md +0 -160
  180. package/skills/patterns/email/resend.md +0 -143
  181. package/skills/patterns/email/templates.md +0 -245
  182. package/skills/patterns/email/transactional.md +0 -503
  183. package/skills/patterns/email/verification.md +0 -176
  184. package/skills/patterns/files/download.md +0 -243
  185. package/skills/patterns/files/upload.md +0 -239
  186. package/skills/patterns/i18n/nextintl.md +0 -188
  187. package/skills/patterns/logging/structured.md +0 -292
  188. package/skills/patterns/notifications/email-queue.md +0 -248
  189. package/skills/patterns/notifications/push.md +0 -279
  190. package/skills/patterns/payments/checkout.md +0 -303
  191. package/skills/patterns/payments/invoices.md +0 -287
  192. package/skills/patterns/payments/portal.md +0 -245
  193. package/skills/patterns/payments/stripe.md +0 -272
  194. package/skills/patterns/payments/subscriptions.md +0 -300
  195. package/skills/patterns/payments/usage.md +0 -279
  196. package/skills/patterns/performance/caching.md +0 -276
  197. package/skills/patterns/performance/code-splitting.md +0 -233
  198. package/skills/patterns/performance/edge.md +0 -254
  199. package/skills/patterns/performance/isr.md +0 -266
  200. package/skills/patterns/performance/lazy-loading.md +0 -281
  201. package/skills/patterns/realtime/sse.md +0 -327
  202. package/skills/patterns/realtime/websockets.md +0 -336
  203. package/skills/patterns/search/filtering.md +0 -329
  204. package/skills/patterns/search/fulltext.md +0 -260
  205. package/skills/patterns/security/audit-logging.md +0 -444
  206. package/skills/patterns/security/csrf.md +0 -234
  207. package/skills/patterns/security/headers.md +0 -252
  208. package/skills/patterns/security/sanitization.md +0 -258
  209. package/skills/patterns/security/secrets.md +0 -261
  210. package/skills/patterns/security/validation.md +0 -268
  211. package/skills/patterns/security/xss.md +0 -229
  212. package/skills/patterns/seo/metadata.md +0 -252
  213. package/skills/patterns/state/context.md +0 -349
  214. package/skills/patterns/state/react-query.md +0 -313
  215. package/skills/patterns/state/url-state.md +0 -482
  216. package/skills/patterns/state/zustand.md +0 -262
  217. package/skills/patterns/testing/api.md +0 -259
  218. package/skills/patterns/testing/component.md +0 -233
  219. package/skills/patterns/testing/coverage.md +0 -207
  220. package/skills/patterns/testing/fixtures.md +0 -225
  221. package/skills/patterns/testing/integration.md +0 -436
  222. package/skills/patterns/testing/mocking.md +0 -177
  223. package/skills/patterns/testing/playwright.md +0 -162
  224. package/skills/patterns/testing/snapshot.md +0 -175
  225. package/skills/patterns/testing/vitest.md +0 -307
  226. package/skills/patterns/ui/accordions.md +0 -395
  227. package/skills/patterns/ui/cards.md +0 -299
  228. package/skills/patterns/ui/dropdowns.md +0 -476
  229. package/skills/patterns/ui/empty-states.md +0 -320
  230. package/skills/patterns/ui/forms.md +0 -405
  231. package/skills/patterns/ui/inputs.md +0 -319
  232. package/skills/patterns/ui/layouts.md +0 -282
  233. package/skills/patterns/ui/loading.md +0 -291
  234. package/skills/patterns/ui/modals.md +0 -338
  235. package/skills/patterns/ui/navigation.md +0 -374
  236. package/skills/patterns/ui/tables.md +0 -407
  237. package/skills/patterns/ui/toasts.md +0 -300
  238. package/skills/patterns/ui/tooltips.md +0 -396
  239. package/skills/patterns/utils/dates.md +0 -435
  240. package/skills/patterns/utils/errors.md +0 -451
  241. package/skills/patterns/utils/formatting.md +0 -345
  242. package/skills/patterns/utils/validation.md +0 -434
  243. package/templates/bootspring.config.js +0 -83
  244. package/templates/business/business-model-canvas.md +0 -246
  245. package/templates/business/business-plan.md +0 -266
  246. package/templates/business/competitive-analysis.md +0 -312
  247. package/templates/fundraising/data-room-checklist.md +0 -300
  248. package/templates/fundraising/investor-research.md +0 -243
  249. package/templates/fundraising/pitch-deck-outline.md +0 -253
  250. package/templates/legal/gdpr-checklist.md +0 -339
  251. package/templates/legal/privacy-policy.md +0 -285
  252. package/templates/legal/terms-of-service.md +0 -222
  253. package/templates/mcp.json +0 -9
@@ -1,327 +0,0 @@
1
- # Server-Sent Events Patterns
2
-
3
- Patterns for real-time updates with Server-Sent Events.
4
-
5
- ## SSE API Route
6
-
7
- ```typescript
8
- // app/api/events/route.ts
9
- export const dynamic = 'force-dynamic'
10
-
11
- export async function GET(request: Request) {
12
- const encoder = new TextEncoder()
13
-
14
- const stream = new ReadableStream({
15
- async start(controller) {
16
- // Send initial connection message
17
- controller.enqueue(
18
- encoder.encode(`data: ${JSON.stringify({ type: 'connected' })}\n\n`)
19
- )
20
-
21
- // Simulated event source
22
- const interval = setInterval(() => {
23
- const event = {
24
- type: 'update',
25
- data: { timestamp: new Date().toISOString() }
26
- }
27
-
28
- controller.enqueue(
29
- encoder.encode(`data: ${JSON.stringify(event)}\n\n`)
30
- )
31
- }, 5000)
32
-
33
- // Clean up on close
34
- request.signal.addEventListener('abort', () => {
35
- clearInterval(interval)
36
- controller.close()
37
- })
38
- }
39
- })
40
-
41
- return new Response(stream, {
42
- headers: {
43
- 'Content-Type': 'text/event-stream',
44
- 'Cache-Control': 'no-cache',
45
- 'Connection': 'keep-alive'
46
- }
47
- })
48
- }
49
- ```
50
-
51
- ## SSE Client Hook
52
-
53
- ```tsx
54
- // hooks/useEventSource.ts
55
- 'use client'
56
-
57
- import { useEffect, useRef, useState, useCallback } from 'react'
58
-
59
- interface UseEventSourceOptions {
60
- url: string
61
- onMessage?: (event: MessageEvent) => void
62
- onError?: (error: Event) => void
63
- onOpen?: () => void
64
- }
65
-
66
- export function useEventSource({ url, onMessage, onError, onOpen }: UseEventSourceOptions) {
67
- const eventSourceRef = useRef<EventSource | null>(null)
68
- const [isConnected, setIsConnected] = useState(false)
69
-
70
- useEffect(() => {
71
- const eventSource = new EventSource(url)
72
- eventSourceRef.current = eventSource
73
-
74
- eventSource.onopen = () => {
75
- setIsConnected(true)
76
- onOpen?.()
77
- }
78
-
79
- eventSource.onmessage = (event) => {
80
- onMessage?.(event)
81
- }
82
-
83
- eventSource.onerror = (error) => {
84
- setIsConnected(false)
85
- onError?.(error)
86
- }
87
-
88
- return () => {
89
- eventSource.close()
90
- }
91
- }, [url, onMessage, onError, onOpen])
92
-
93
- const close = useCallback(() => {
94
- eventSourceRef.current?.close()
95
- }, [])
96
-
97
- return { isConnected, close }
98
- }
99
- ```
100
-
101
- ## Notification Stream
102
-
103
- ```tsx
104
- // components/NotificationStream.tsx
105
- 'use client'
106
-
107
- import { useState } from 'react'
108
- import { useEventSource } from '@/hooks/useEventSource'
109
-
110
- interface Notification {
111
- id: string
112
- type: string
113
- message: string
114
- timestamp: string
115
- }
116
-
117
- export function NotificationStream({ userId }: { userId: string }) {
118
- const [notifications, setNotifications] = useState<Notification[]>([])
119
-
120
- useEventSource({
121
- url: `/api/notifications/stream?userId=${userId}`,
122
- onMessage: (event) => {
123
- const data = JSON.parse(event.data)
124
-
125
- if (data.type === 'notification') {
126
- setNotifications(prev => [data.notification, ...prev].slice(0, 50))
127
- }
128
- }
129
- })
130
-
131
- return (
132
- <div className="space-y-2">
133
- {notifications.map(notification => (
134
- <div key={notification.id} className="rounded border p-3">
135
- <p>{notification.message}</p>
136
- <span className="text-sm text-gray-500">
137
- {new Date(notification.timestamp).toLocaleTimeString()}
138
- </span>
139
- </div>
140
- ))}
141
- </div>
142
- )
143
- }
144
-
145
- // API route
146
- // app/api/notifications/stream/route.ts
147
- export async function GET(request: Request) {
148
- const { searchParams } = new URL(request.url)
149
- const userId = searchParams.get('userId')
150
-
151
- const encoder = new TextEncoder()
152
-
153
- const stream = new ReadableStream({
154
- async start(controller) {
155
- // Subscribe to notification events
156
- const unsubscribe = subscribeToNotifications(userId!, (notification) => {
157
- controller.enqueue(
158
- encoder.encode(`data: ${JSON.stringify({
159
- type: 'notification',
160
- notification
161
- })}\n\n`)
162
- )
163
- })
164
-
165
- request.signal.addEventListener('abort', () => {
166
- unsubscribe()
167
- controller.close()
168
- })
169
- }
170
- })
171
-
172
- return new Response(stream, {
173
- headers: {
174
- 'Content-Type': 'text/event-stream',
175
- 'Cache-Control': 'no-cache',
176
- 'Connection': 'keep-alive'
177
- }
178
- })
179
- }
180
- ```
181
-
182
- ## Progress Streaming
183
-
184
- ```typescript
185
- // app/api/process/route.ts
186
- export async function POST(request: Request) {
187
- const { taskId } = await request.json()
188
-
189
- const encoder = new TextEncoder()
190
-
191
- const stream = new ReadableStream({
192
- async start(controller) {
193
- // Simulate long-running process with progress updates
194
- const steps = ['Initializing', 'Processing', 'Validating', 'Completing']
195
-
196
- for (let i = 0; i < steps.length; i++) {
197
- // Send progress update
198
- controller.enqueue(
199
- encoder.encode(`data: ${JSON.stringify({
200
- type: 'progress',
201
- step: steps[i],
202
- progress: ((i + 1) / steps.length) * 100
203
- })}\n\n`)
204
- )
205
-
206
- // Simulate work
207
- await new Promise(resolve => setTimeout(resolve, 1000))
208
- }
209
-
210
- // Send completion
211
- controller.enqueue(
212
- encoder.encode(`data: ${JSON.stringify({
213
- type: 'complete',
214
- result: { success: true }
215
- })}\n\n`)
216
- )
217
-
218
- controller.close()
219
- }
220
- })
221
-
222
- return new Response(stream, {
223
- headers: {
224
- 'Content-Type': 'text/event-stream',
225
- 'Cache-Control': 'no-cache'
226
- }
227
- })
228
- }
229
-
230
- // Client component
231
- function ProcessTracker({ taskId }: { taskId: string }) {
232
- const [progress, setProgress] = useState(0)
233
- const [step, setStep] = useState('')
234
- const [isComplete, setIsComplete] = useState(false)
235
-
236
- useEffect(() => {
237
- const eventSource = new EventSource(`/api/process?taskId=${taskId}`)
238
-
239
- eventSource.onmessage = (event) => {
240
- const data = JSON.parse(event.data)
241
-
242
- if (data.type === 'progress') {
243
- setProgress(data.progress)
244
- setStep(data.step)
245
- } else if (data.type === 'complete') {
246
- setIsComplete(true)
247
- eventSource.close()
248
- }
249
- }
250
-
251
- return () => eventSource.close()
252
- }, [taskId])
253
-
254
- return (
255
- <div>
256
- <div className="mb-2">{step}</div>
257
- <div className="h-2 rounded-full bg-gray-200">
258
- <div
259
- className="h-2 rounded-full bg-blue-600 transition-all"
260
- style={{ width: `${progress}%` }}
261
- />
262
- </div>
263
- {isComplete && <p className="mt-2 text-green-600">Complete!</p>}
264
- </div>
265
- )
266
- }
267
- ```
268
-
269
- ## Named Events
270
-
271
- ```typescript
272
- // app/api/events/route.ts
273
- export async function GET(request: Request) {
274
- const encoder = new TextEncoder()
275
-
276
- const stream = new ReadableStream({
277
- async start(controller) {
278
- // Send named events
279
- const sendEvent = (eventName: string, data: any) => {
280
- controller.enqueue(
281
- encoder.encode(`event: ${eventName}\ndata: ${JSON.stringify(data)}\n\n`)
282
- )
283
- }
284
-
285
- sendEvent('user_online', { userId: '123', name: 'John' })
286
- sendEvent('message', { text: 'Hello!' })
287
- sendEvent('notification', { type: 'alert', message: 'New update' })
288
-
289
- // Keep alive
290
- const keepAlive = setInterval(() => {
291
- controller.enqueue(encoder.encode(`: keep-alive\n\n`))
292
- }, 15000)
293
-
294
- request.signal.addEventListener('abort', () => {
295
- clearInterval(keepAlive)
296
- controller.close()
297
- })
298
- }
299
- })
300
-
301
- return new Response(stream, {
302
- headers: { 'Content-Type': 'text/event-stream' }
303
- })
304
- }
305
-
306
- // Client with named events
307
- const eventSource = new EventSource('/api/events')
308
-
309
- eventSource.addEventListener('user_online', (e) => {
310
- console.log('User online:', JSON.parse(e.data))
311
- })
312
-
313
- eventSource.addEventListener('message', (e) => {
314
- console.log('Message:', JSON.parse(e.data))
315
- })
316
-
317
- eventSource.addEventListener('notification', (e) => {
318
- console.log('Notification:', JSON.parse(e.data))
319
- })
320
- ```
321
-
322
- ## When to Use
323
-
324
- - Live updates
325
- - Progress tracking
326
- - Notifications
327
- - Stock prices
@@ -1,336 +0,0 @@
1
- # WebSocket Patterns
2
-
3
- Patterns for real-time communication with WebSockets.
4
-
5
- ## WebSocket Client Hook
6
-
7
- ```tsx
8
- // hooks/useWebSocket.ts
9
- 'use client'
10
-
11
- import { useEffect, useRef, useState, useCallback } from 'react'
12
-
13
- interface UseWebSocketOptions {
14
- url: string
15
- onMessage?: (data: any) => void
16
- onOpen?: () => void
17
- onClose?: () => void
18
- onError?: (error: Event) => void
19
- reconnect?: boolean
20
- reconnectInterval?: number
21
- maxReconnectAttempts?: number
22
- }
23
-
24
- export function useWebSocket({
25
- url,
26
- onMessage,
27
- onOpen,
28
- onClose,
29
- onError,
30
- reconnect = true,
31
- reconnectInterval = 3000,
32
- maxReconnectAttempts = 5
33
- }: UseWebSocketOptions) {
34
- const wsRef = useRef<WebSocket | null>(null)
35
- const reconnectAttemptsRef = useRef(0)
36
- const [isConnected, setIsConnected] = useState(false)
37
-
38
- const connect = useCallback(() => {
39
- try {
40
- wsRef.current = new WebSocket(url)
41
-
42
- wsRef.current.onopen = () => {
43
- setIsConnected(true)
44
- reconnectAttemptsRef.current = 0
45
- onOpen?.()
46
- }
47
-
48
- wsRef.current.onmessage = (event) => {
49
- const data = JSON.parse(event.data)
50
- onMessage?.(data)
51
- }
52
-
53
- wsRef.current.onclose = () => {
54
- setIsConnected(false)
55
- onClose?.()
56
-
57
- if (reconnect && reconnectAttemptsRef.current < maxReconnectAttempts) {
58
- reconnectAttemptsRef.current++
59
- setTimeout(connect, reconnectInterval)
60
- }
61
- }
62
-
63
- wsRef.current.onerror = (error) => {
64
- onError?.(error)
65
- }
66
- } catch (error) {
67
- console.error('WebSocket connection error:', error)
68
- }
69
- }, [url, onMessage, onOpen, onClose, onError, reconnect, reconnectInterval, maxReconnectAttempts])
70
-
71
- useEffect(() => {
72
- connect()
73
-
74
- return () => {
75
- wsRef.current?.close()
76
- }
77
- }, [connect])
78
-
79
- const send = useCallback((data: any) => {
80
- if (wsRef.current?.readyState === WebSocket.OPEN) {
81
- wsRef.current.send(JSON.stringify(data))
82
- }
83
- }, [])
84
-
85
- return { isConnected, send }
86
- }
87
- ```
88
-
89
- ## Chat Application
90
-
91
- ```tsx
92
- // components/Chat.tsx
93
- 'use client'
94
-
95
- import { useState, useEffect, useRef } from 'react'
96
- import { useWebSocket } from '@/hooks/useWebSocket'
97
-
98
- interface Message {
99
- id: string
100
- userId: string
101
- content: string
102
- timestamp: string
103
- }
104
-
105
- export function Chat({ roomId, userId }: { roomId: string; userId: string }) {
106
- const [messages, setMessages] = useState<Message[]>([])
107
- const [input, setInput] = useState('')
108
- const messagesEndRef = useRef<HTMLDivElement>(null)
109
-
110
- const { isConnected, send } = useWebSocket({
111
- url: `${process.env.NEXT_PUBLIC_WS_URL}/chat/${roomId}`,
112
- onMessage: (data) => {
113
- switch (data.type) {
114
- case 'message':
115
- setMessages(prev => [...prev, data.message])
116
- break
117
- case 'history':
118
- setMessages(data.messages)
119
- break
120
- }
121
- }
122
- })
123
-
124
- // Auto-scroll to bottom
125
- useEffect(() => {
126
- messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
127
- }, [messages])
128
-
129
- const handleSend = () => {
130
- if (!input.trim()) return
131
-
132
- send({
133
- type: 'message',
134
- content: input,
135
- userId
136
- })
137
-
138
- setInput('')
139
- }
140
-
141
- return (
142
- <div className="flex h-[500px] flex-col rounded-lg border">
143
- {/* Status */}
144
- <div className="border-b p-2 text-sm">
145
- {isConnected ? (
146
- <span className="text-green-600">Connected</span>
147
- ) : (
148
- <span className="text-red-600">Disconnected</span>
149
- )}
150
- </div>
151
-
152
- {/* Messages */}
153
- <div className="flex-1 overflow-y-auto p-4 space-y-2">
154
- {messages.map(msg => (
155
- <div
156
- key={msg.id}
157
- className={`rounded-lg p-2 ${
158
- msg.userId === userId ? 'ml-auto bg-blue-500 text-white' : 'bg-gray-100'
159
- }`}
160
- >
161
- {msg.content}
162
- </div>
163
- ))}
164
- <div ref={messagesEndRef} />
165
- </div>
166
-
167
- {/* Input */}
168
- <div className="border-t p-2">
169
- <div className="flex gap-2">
170
- <input
171
- value={input}
172
- onChange={(e) => setInput(e.target.value)}
173
- onKeyDown={(e) => e.key === 'Enter' && handleSend()}
174
- placeholder="Type a message..."
175
- className="flex-1 rounded-lg border px-3 py-2"
176
- />
177
- <button
178
- onClick={handleSend}
179
- disabled={!isConnected}
180
- className="rounded-lg bg-blue-500 px-4 py-2 text-white"
181
- >
182
- Send
183
- </button>
184
- </div>
185
- </div>
186
- </div>
187
- )
188
- }
189
- ```
190
-
191
- ## Server-Side WebSocket (Node.js)
192
-
193
- ```typescript
194
- // server/websocket.ts
195
- import { WebSocketServer, WebSocket } from 'ws'
196
-
197
- interface Client {
198
- ws: WebSocket
199
- userId: string
200
- roomId: string
201
- }
202
-
203
- const clients = new Map<string, Client>()
204
-
205
- export function setupWebSocket(server: any) {
206
- const wss = new WebSocketServer({ server, path: '/ws' })
207
-
208
- wss.on('connection', (ws, request) => {
209
- const url = new URL(request.url!, `http://${request.headers.host}`)
210
- const roomId = url.searchParams.get('room')
211
- const userId = url.searchParams.get('user')
212
-
213
- if (!roomId || !userId) {
214
- ws.close(1008, 'Missing room or user')
215
- return
216
- }
217
-
218
- const clientId = `${userId}-${Date.now()}`
219
- clients.set(clientId, { ws, userId, roomId })
220
-
221
- // Send history
222
- ws.send(JSON.stringify({
223
- type: 'history',
224
- messages: getMessageHistory(roomId)
225
- }))
226
-
227
- // Notify room
228
- broadcastToRoom(roomId, {
229
- type: 'user_joined',
230
- userId
231
- }, clientId)
232
-
233
- ws.on('message', (data) => {
234
- try {
235
- const message = JSON.parse(data.toString())
236
-
237
- if (message.type === 'message') {
238
- const savedMessage = saveMessage({
239
- roomId,
240
- userId,
241
- content: message.content
242
- })
243
-
244
- broadcastToRoom(roomId, {
245
- type: 'message',
246
- message: savedMessage
247
- })
248
- }
249
- } catch (error) {
250
- console.error('Message handling error:', error)
251
- }
252
- })
253
-
254
- ws.on('close', () => {
255
- clients.delete(clientId)
256
- broadcastToRoom(roomId, {
257
- type: 'user_left',
258
- userId
259
- })
260
- })
261
- })
262
- }
263
-
264
- function broadcastToRoom(roomId: string, data: any, excludeClient?: string) {
265
- const message = JSON.stringify(data)
266
-
267
- clients.forEach((client, clientId) => {
268
- if (client.roomId === roomId && clientId !== excludeClient) {
269
- if (client.ws.readyState === WebSocket.OPEN) {
270
- client.ws.send(message)
271
- }
272
- }
273
- })
274
- }
275
- ```
276
-
277
- ## Presence System
278
-
279
- ```tsx
280
- // hooks/usePresence.ts
281
- 'use client'
282
-
283
- import { useState, useEffect } from 'react'
284
- import { useWebSocket } from './useWebSocket'
285
-
286
- interface User {
287
- id: string
288
- name: string
289
- status: 'online' | 'away' | 'offline'
290
- }
291
-
292
- export function usePresence(roomId: string, currentUser: User) {
293
- const [users, setUsers] = useState<User[]>([])
294
-
295
- const { send } = useWebSocket({
296
- url: `${process.env.NEXT_PUBLIC_WS_URL}/presence/${roomId}`,
297
- onMessage: (data) => {
298
- switch (data.type) {
299
- case 'presence_update':
300
- setUsers(data.users)
301
- break
302
- case 'user_status':
303
- setUsers(prev =>
304
- prev.map(u => u.id === data.userId ? { ...u, status: data.status } : u)
305
- )
306
- break
307
- }
308
- },
309
- onOpen: () => {
310
- send({ type: 'join', user: currentUser })
311
- }
312
- })
313
-
314
- // Send heartbeat
315
- useEffect(() => {
316
- const interval = setInterval(() => {
317
- send({ type: 'heartbeat' })
318
- }, 30000)
319
-
320
- return () => clearInterval(interval)
321
- }, [send])
322
-
323
- const updateStatus = (status: User['status']) => {
324
- send({ type: 'status', status })
325
- }
326
-
327
- return { users, updateStatus }
328
- }
329
- ```
330
-
331
- ## When to Use
332
-
333
- - Real-time chat
334
- - Live notifications
335
- - Collaborative editing
336
- - Gaming