oneie 3.6.26 → 3.6.27

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.
@@ -0,0 +1,459 @@
1
+ ---
2
+ title: Performance Optimization Guide
3
+ dimension: knowledge
4
+ category: performance
5
+ tags: optimization, performance, speed, efficiency, lighthouse
6
+ related_dimensions: all
7
+ scope: global
8
+ created: 2025-11-08
9
+ version: 1.0.0
10
+ ai_context: |
11
+ Comprehensive guide to performance optimization in the ONE platform,
12
+ covering Astro islands, code splitting, caching, and database optimization.
13
+ ---
14
+
15
+ # Performance Optimization Guide
16
+
17
+ **Build fast applications that scale.**
18
+
19
+ ---
20
+
21
+ ## Core Performance Principles
22
+
23
+ 1. **Static by default** - Ship HTML, not JavaScript
24
+ 2. **Progressive enhancement** - Add interactivity strategically
25
+ 3. **Lazy loading** - Load what's needed, when it's needed
26
+ 4. **Optimize database queries** - Use indexes, batch operations
27
+ 5. **Edge deployment** - Serve from 330+ locations worldwide
28
+
29
+ ---
30
+
31
+ ## Astro Islands Architecture
32
+
33
+ **Performance principle:** Static HTML by default. Add interactivity strategically.
34
+
35
+ ### Client Directives
36
+
37
+ ```astro
38
+ <!-- Static (no JS) - BEST -->
39
+ <ProductCard product={product} />
40
+
41
+ <!-- Interactive (loads immediately) - Use sparingly -->
42
+ <ShoppingCart client:load />
43
+
44
+ <!-- Deferred (loads when idle) - Good for non-critical -->
45
+ <SearchBox client:idle />
46
+
47
+ <!-- Lazy (loads when visible) - Best for below-fold -->
48
+ <RelatedProducts client:visible />
49
+
50
+ <!-- Client-only (never SSR) - Use for browser APIs -->
51
+ <BrowserWidget client:only="react" />
52
+ ```
53
+
54
+ ### Performance Impact
55
+
56
+ | Directive | Initial JS | TTI Impact | Use Case |
57
+ |-----------|-----------|------------|----------|
58
+ | None (static) | 0KB | None | Default for everything |
59
+ | `client:visible` | Lazy | Minimal | Below-fold content |
60
+ | `client:idle` | Deferred | Low | Non-critical features |
61
+ | `client:load` | Immediate | Medium | Critical interactivity |
62
+ | `client:only` | Immediate | Medium | Browser-only components |
63
+
64
+ **Golden Rule:** Start with no directive. Add `client:*` only when interactivity is required.
65
+
66
+ ---
67
+
68
+ ## Code Splitting
69
+
70
+ ### Dynamic Imports
71
+
72
+ ```typescript
73
+ // Split heavy components
74
+ import { lazy } from 'react';
75
+
76
+ const HeavyChart = lazy(() => import('./HeavyChart'));
77
+ const VideoPlayer = lazy(() => import('./VideoPlayer'));
78
+
79
+ // Use with Suspense
80
+ <Suspense fallback={<Skeleton />}>
81
+ <HeavyChart data={data} />
82
+ </Suspense>
83
+ ```
84
+
85
+ ### Route-Based Splitting
86
+
87
+ ```typescript
88
+ // Astro automatically code-splits by route
89
+ // Each page = separate bundle
90
+
91
+ // pages/index.astro → index.js
92
+ // pages/products/[id].astro → products-[id].js
93
+ // pages/checkout.astro → checkout.js
94
+ ```
95
+
96
+ **Result:** Each page loads only the JS it needs.
97
+
98
+ ---
99
+
100
+ ## Image Optimization
101
+
102
+ ### Astro Image Component
103
+
104
+ ```astro
105
+ ---
106
+ import { Image } from 'astro:assets';
107
+ import hero from '../assets/hero.jpg';
108
+ ---
109
+
110
+ <!-- Optimized with multiple formats -->
111
+ <Image
112
+ src={hero}
113
+ alt="Hero image"
114
+ width={1200}
115
+ height={600}
116
+ loading="lazy"
117
+ format="webp"
118
+ />
119
+ ```
120
+
121
+ ### Performance Gains
122
+
123
+ - Automatic format conversion (WebP, AVIF)
124
+ - Responsive images (`srcset`)
125
+ - Lazy loading by default
126
+ - Automatic width/height (prevents layout shift)
127
+
128
+ ---
129
+
130
+ ## Database Query Optimization
131
+
132
+ ### 1. Use Indexes
133
+
134
+ ```typescript
135
+ // schema.ts
136
+ defineTable({
137
+ groupId: v.id("groups"),
138
+ type: v.string(),
139
+ name: v.string(),
140
+ createdAt: v.number(),
141
+ })
142
+ .index("by_group_type", ["groupId", "type"])
143
+ .index("by_group_created", ["groupId", "createdAt"])
144
+ ```
145
+
146
+ **Query pattern → Index required:**
147
+
148
+ ```typescript
149
+ // Query pattern: list by group + type
150
+ .query("things")
151
+ .withIndex("by_group_type", q =>
152
+ q.eq("groupId", groupId).eq("type", type)
153
+ )
154
+
155
+ // Index required: ["groupId", "type"]
156
+ ```
157
+
158
+ ### 2. Batch Operations
159
+
160
+ ```typescript
161
+ // BAD: N+1 queries
162
+ for (const id of ids) {
163
+ const thing = await ctx.db.get(id); // 100 queries for 100 IDs
164
+ results.push(thing);
165
+ }
166
+
167
+ // GOOD: Single batch operation
168
+ const things = await Promise.all(
169
+ ids.map(id => ctx.db.get(id))
170
+ ); // 1 batch for 100 IDs
171
+ ```
172
+
173
+ ### 3. Use `first()` for Single Items
174
+
175
+ ```typescript
176
+ // BAD: Collect all and take first
177
+ const things = await ctx.db
178
+ .query("things")
179
+ .withIndex("by_group_type", q => q.eq("groupId", groupId))
180
+ .collect();
181
+ const thing = things[0]; // Fetches ALL, uses only 1
182
+
183
+ // GOOD: Use first()
184
+ const thing = await ctx.db
185
+ .query("things")
186
+ .withIndex("by_group_type", q => q.eq("groupId", groupId))
187
+ .first(); // Fetches ONLY 1
188
+ ```
189
+
190
+ ### 4. Pagination
191
+
192
+ ```typescript
193
+ // Paginate large result sets
194
+ export const listPaginated = query({
195
+ args: {
196
+ groupId: v.id("groups"),
197
+ cursor: v.optional(v.string()),
198
+ limit: v.optional(v.number()),
199
+ },
200
+ handler: async (ctx, args) => {
201
+ const limit = args.limit ?? 20;
202
+
203
+ const results = await ctx.db
204
+ .query("things")
205
+ .withIndex("by_group_created", q => q.eq("groupId", args.groupId))
206
+ .order("desc")
207
+ .paginate({
208
+ cursor: args.cursor,
209
+ numItems: limit,
210
+ });
211
+
212
+ return results;
213
+ },
214
+ });
215
+ ```
216
+
217
+ ---
218
+
219
+ ## Caching Strategies
220
+
221
+ ### 1. Edge Caching (Cloudflare)
222
+
223
+ ```astro
224
+ ---
225
+ // pages/api/products.ts
226
+ export const prerender = true; // Static generation
227
+
228
+ // Or dynamic with cache headers
229
+ export async function get() {
230
+ return new Response(JSON.stringify(data), {
231
+ headers: {
232
+ 'Cache-Control': 'public, max-age=3600, s-maxage=86400',
233
+ },
234
+ });
235
+ }
236
+ ---
237
+ ```
238
+
239
+ ### 2. Convex Real-Time Caching
240
+
241
+ ```typescript
242
+ // Convex automatically caches query results
243
+ // Invalidates cache on mutation
244
+
245
+ // queries/products.ts
246
+ export const list = query({
247
+ handler: async (ctx) => {
248
+ // Cached until mutation occurs
249
+ return await ctx.db.query("products").collect();
250
+ },
251
+ });
252
+
253
+ // mutations/products.ts
254
+ export const create = mutation({
255
+ handler: async (ctx, args) => {
256
+ // Mutation invalidates query cache
257
+ return await ctx.db.insert("products", args);
258
+ },
259
+ });
260
+ ```
261
+
262
+ ### 3. Browser Storage
263
+
264
+ ```typescript
265
+ // Cache static data in localStorage
266
+ function getCachedData(key: string) {
267
+ const cached = localStorage.getItem(key);
268
+ if (cached) {
269
+ const { data, timestamp } = JSON.parse(cached);
270
+ if (Date.now() - timestamp < 3600000) { // 1 hour
271
+ return data;
272
+ }
273
+ }
274
+ return null;
275
+ }
276
+
277
+ function setCachedData(key: string, data: any) {
278
+ localStorage.setItem(key, JSON.stringify({
279
+ data,
280
+ timestamp: Date.now(),
281
+ }));
282
+ }
283
+ ```
284
+
285
+ ---
286
+
287
+ ## Bundle Size Optimization
288
+
289
+ ### 1. Tree Shaking
290
+
291
+ ```typescript
292
+ // GOOD: Named imports (tree-shakable)
293
+ import { Button } from '@/components/ui/button';
294
+
295
+ // BAD: Default import (entire package)
296
+ import * as UI from '@/components/ui';
297
+ ```
298
+
299
+ ### 2. Remove Unused Dependencies
300
+
301
+ ```bash
302
+ # Analyze bundle size
303
+ bunx astro build --verbose
304
+
305
+ # Remove unused packages
306
+ bun remove unused-package
307
+ ```
308
+
309
+ ### 3. Use Smaller Alternatives
310
+
311
+ ```typescript
312
+ // Instead of moment.js (67KB)
313
+ import { formatDistance } from 'date-fns'; // 2KB
314
+
315
+ // Instead of lodash (71KB)
316
+ import debounce from 'lodash.debounce'; // 1KB
317
+
318
+ // Instead of axios (15KB)
319
+ fetch('/api/data'); // Native, 0KB
320
+ ```
321
+
322
+ ---
323
+
324
+ ## Lighthouse Optimization Checklist
325
+
326
+ **Target: 90+ score on all metrics**
327
+
328
+ ### Performance (90+)
329
+
330
+ - [ ] Use static HTML by default (no `client:load`)
331
+ - [ ] Optimize images (WebP, lazy loading)
332
+ - [ ] Code split heavy components
333
+ - [ ] Remove unused CSS/JS
334
+ - [ ] Enable edge caching (Cloudflare)
335
+
336
+ ### Accessibility (95+)
337
+
338
+ - [ ] Use semantic HTML (`<header>`, `<nav>`, `<main>`)
339
+ - [ ] Add ARIA labels where needed
340
+ - [ ] Ensure keyboard navigation works
341
+ - [ ] Test with screen readers
342
+ - [ ] Color contrast ratio ≥ 4.5:1
343
+
344
+ ### Best Practices (95+)
345
+
346
+ - [ ] HTTPS everywhere
347
+ - [ ] No console errors
348
+ - [ ] Proper meta tags
349
+ - [ ] Valid robots.txt
350
+ - [ ] Secure headers (CSP, HSTS)
351
+
352
+ ### SEO (95+)
353
+
354
+ - [ ] Meta description on every page
355
+ - [ ] Proper heading hierarchy (H1 → H6)
356
+ - [ ] Alt text on all images
357
+ - [ ] Sitemap.xml generated
358
+ - [ ] Structured data (JSON-LD)
359
+
360
+ ---
361
+
362
+ ## Monitoring Performance
363
+
364
+ ### 1. Lighthouse CI
365
+
366
+ ```bash
367
+ # Run Lighthouse locally
368
+ bunx astro build
369
+ npx lighthouse http://localhost:4321 --view
370
+
371
+ # Target scores:
372
+ # Performance: 90+
373
+ # Accessibility: 95+
374
+ # Best Practices: 95+
375
+ # SEO: 95+
376
+ ```
377
+
378
+ ### 2. Web Vitals
379
+
380
+ ```typescript
381
+ // Track Core Web Vitals
382
+ import { onCLS, onFID, onLCP } from 'web-vitals';
383
+
384
+ onCLS(console.log); // Cumulative Layout Shift
385
+ onFID(console.log); // First Input Delay
386
+ onLCP(console.log); // Largest Contentful Paint
387
+ ```
388
+
389
+ ### 3. Convex Dashboard
390
+
391
+ - Query latency (p50, p95, p99)
392
+ - Function execution time
393
+ - Database read/write operations
394
+ - Real-time active connections
395
+
396
+ **Target metrics:**
397
+ - Query latency p95: < 100ms
398
+ - Function execution: < 500ms
399
+ - Database reads: < 50ms
400
+ - Active connections: Monitor for leaks
401
+
402
+ ---
403
+
404
+ ## Performance Budget
405
+
406
+ **Set limits and enforce them:**
407
+
408
+ | Metric | Budget | Current | Status |
409
+ |--------|--------|---------|--------|
410
+ | Initial JS | < 100KB | 85KB | ✅ |
411
+ | Total Page Weight | < 500KB | 420KB | ✅ |
412
+ | Time to Interactive | < 3s | 2.1s | ✅ |
413
+ | First Contentful Paint | < 1.5s | 1.2s | ✅ |
414
+ | Lighthouse Score | > 90 | 94 | ✅ |
415
+
416
+ **Enforce in CI:**
417
+
418
+ ```bash
419
+ # Fail build if bundle exceeds budget
420
+ bunx astro build
421
+ npx bundlesize
422
+ ```
423
+
424
+ ---
425
+
426
+ ## Quick Wins
427
+
428
+ **Implement these for immediate gains:**
429
+
430
+ 1. **Add `loading="lazy"` to images below fold**
431
+ ```html
432
+ <img src="hero.jpg" loading="lazy" alt="Hero" />
433
+ ```
434
+
435
+ 2. **Use `client:idle` instead of `client:load`**
436
+ ```astro
437
+ <SearchBox client:idle /> <!-- Deferred loading -->
438
+ ```
439
+
440
+ 3. **Enable Cloudflare cache**
441
+ ```astro
442
+ export const prerender = true;
443
+ ```
444
+
445
+ 4. **Add database indexes**
446
+ ```typescript
447
+ .index("by_group_type", ["groupId", "type"])
448
+ ```
449
+
450
+ 5. **Use WebP images**
451
+ ```astro
452
+ <Image format="webp" />
453
+ ```
454
+
455
+ **Result:** 20-30 point Lighthouse score improvement in < 1 hour.
456
+
457
+ ---
458
+
459
+ **Build fast. Stay fast. Monitor always.**