oneie 2.0.3 → 2.0.5
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/CLAUDE.md +220 -29
- package/LICENSE.md +84 -0
- package/README.md +489 -931
- package/folders.yaml +78 -17
- package/one/.obsidian/workspace.json +6 -6
- package/one/events/CASCADE-2-BACKEND-AGNOSTIC.md +412 -0
- package/one/events/FEATURE-2-4-COMPLETE.md +302 -0
- package/one/events/FEATURE_2_3_COMPLETE.md +575 -0
- package/one/events/GROUPS-MIGRATION.md +625 -0
- package/one/events/INSTALL-TESTS.md +293 -0
- package/one/events/INTEGRATION-ARCHITECTURE.md +561 -0
- package/one/events/INTEGRATION-CHECKLIST.md +1234 -0
- package/one/events/INTEGRATION-ORCHESTRATION.md +2623 -0
- package/one/events/INTEGRATION-SUMMARY.md +653 -0
- package/one/events/MIGRATION-REPORT.md +435 -0
- package/one/events/MIGRATION.md +69 -0
- package/one/events/README-archived.md +519 -0
- package/one/events/TEST-SUMMARY.md +393 -0
- package/one/events/TESTS-QUICK-REF.md +262 -0
- package/one/groups/groups.md +543 -0
- package/one/knowledge/CLOUDFLARE_ENV_SETUP.md +49 -0
- package/one/knowledge/architecture-any-backend.md +1366 -0
- package/one/knowledge/docs/flow.md +0 -0
- package/one/knowledge/ontology-documentation.md +18 -18
- package/one/knowledge/ontology.md +154 -143
- package/one/knowledge/ontology.md.backup +2822 -0
- package/one/knowledge/ontology.yaml +87 -87
- package/one/knowledge/provider-creation-guide.md +1064 -0
- package/one/knowledge/todo.md +251 -0
- package/one/license.md +84 -0
- package/one/things/CHECKLIST.md +356 -0
- package/one/things/ONE.md +510 -0
- package/one/things/{cli.md → cli/cli.md} +27 -4
- package/one/things/features/2-1-dataprovider-interface.md +2358 -0
- package/one/things/features/2-2-config-system.md +3075 -0
- package/one/things/features/2-3-effectts-services.md +1498 -0
- package/one/things/features/2-4-react-hooks.md +2120 -0
- package/one/things/features/2-5-auth-migration.md +2046 -0
- package/one/things/features/2-6-dashboard-migration.md +1985 -0
- package/one/things/features/2-7-alternative-providers.md +2505 -0
- package/one/things/features/2-7-implementation-report.md +680 -0
- package/one/things/features/2-cli.md +39 -39
- package/one/things/features/2-design.md +1738 -0
- package/one/things/features/2-tests.md +520 -0
- package/one/things/features/AUTH_HOOKS_IMPLEMENTATION.md +521 -0
- package/one/things/features/DECOUPLING.md +272 -0
- package/one/things/features/DEPLOYMENT.md +452 -0
- package/one/things/features/IMPLEMENTATION_SUMMARY.md +316 -0
- package/one/things/features/dataprovider-interface/1-tests.md +1522 -0
- package/one/things/features/improve.md +843 -0
- package/one/things/features/remove-convex-deps.md +45 -0
- package/one/things/features/top-features.md +79 -0
- package/one/things/ideas/2-backend-agnostic-frontend.md +384 -0
- package/one/things/plans/2-backend-agnostic-frontend.md +543 -0
- package/one/things/plans/3-groups.md +502 -0
- package/one/things/plans/backend-agnostic-frontend.md +323 -0
- package/one/things/plans/deploy-to-cloudflare.md +581 -0
- package/one/things/plans/organizations-to-groups.md +705 -0
- package/one/things/plans/release.md +432 -0
- package/one/things/products/ontology.md +1 -1
- package/one/things/system.md +600 -0
- package/one/things/tests/2-1-dataprovider-interface.md +1144 -0
- package/one/things/tests/2-1-test-analysis.md +496 -0
- package/one/things/vision/elegant-interface.md +214 -0
- package/package.json +1 -1
- package/one/organisation/organisation.md +0 -438
- package/one/repomix-output.md +0 -92634
- /package/one/{things → connections}/agentkit.md +0 -0
- /package/one/{things → connections}/copilotkit.md +0 -0
- /package/one/{organisation → groups}/one.md +0 -0
- /package/one/{organisation → groups}/revenue.md +0 -0
- /package/one/{organisation → groups}/strategy.md +0 -0
- /package/one/{organisation → groups}/vision.md +0 -0
- /package/one/things/{cli-code.md → cli/cli-code.md} +0 -0
- /package/one/things/{cli-compiler-code.md → cli/cli-compiler-code.md} +0 -0
|
@@ -0,0 +1,1366 @@
|
|
|
1
|
+
# Backend-Agnostic Architecture: Use Any Database
|
|
2
|
+
|
|
3
|
+
**Version:** 2.0
|
|
4
|
+
**Status:** ✅ Production Ready
|
|
5
|
+
**Last Updated:** 2025-10-13
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Overview
|
|
10
|
+
|
|
11
|
+
The ONE Platform implements a **backend-agnostic architecture** that allows organizations to choose ANY backend database or CMS without changing a single line of frontend code. Switch from Convex to WordPress to Notion with **one configuration change**.
|
|
12
|
+
|
|
13
|
+
This architecture proves that the 6-dimension ontology is truly protocol-agnostic and platform-independent.
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## Architecture Layers
|
|
18
|
+
|
|
19
|
+
The system uses **5 distinct layers** that separate concerns and enable backend flexibility:
|
|
20
|
+
|
|
21
|
+
```
|
|
22
|
+
┌─────────────────────────────────────────────────────────┐
|
|
23
|
+
│ LAYER 5: UI COMPONENTS (React 19) │
|
|
24
|
+
│ - Auth forms, dashboards, data displays │
|
|
25
|
+
│ - Uses hooks only, never direct backend calls │
|
|
26
|
+
└────────────────────┬────────────────────────────────────┘
|
|
27
|
+
│
|
|
28
|
+
↓ (React hooks)
|
|
29
|
+
┌─────────────────────────────────────────────────────────┐
|
|
30
|
+
│ LAYER 4: REACT HOOKS │
|
|
31
|
+
│ - useThings(), useConnections(), useEvents() │
|
|
32
|
+
│ - useLogin(), useSignup(), useCurrentUser() │
|
|
33
|
+
│ - Loading states, error handling, optimistic updates │
|
|
34
|
+
└────────────────────┬────────────────────────────────────┘
|
|
35
|
+
│
|
|
36
|
+
↓ (Effect.ts)
|
|
37
|
+
┌─────────────────────────────────────────────────────────┐
|
|
38
|
+
│ LAYER 3: EFFECT.TS SERVICES │
|
|
39
|
+
│ - ThingService, ConnectionService, EventService │
|
|
40
|
+
│ - Pure business logic, backend-agnostic │
|
|
41
|
+
│ - Validation, authorization, type-specific rules │
|
|
42
|
+
└────────────────────┬────────────────────────────────────┘
|
|
43
|
+
│
|
|
44
|
+
↓ (DataProvider interface)
|
|
45
|
+
┌─────────────────────────────────────────────────────────┐
|
|
46
|
+
│ LAYER 2: DATAPROVIDER INTERFACE │
|
|
47
|
+
│ - Standard CRUD operations for 6 dimensions │
|
|
48
|
+
│ - Type-safe errors with tagged unions │
|
|
49
|
+
│ - Real-time subscription support │
|
|
50
|
+
└────────────────────┬────────────────────────────────────┘
|
|
51
|
+
│
|
|
52
|
+
↓ (Provider implementations)
|
|
53
|
+
┌─────────────────────────────────────────────────────────┐
|
|
54
|
+
│ LAYER 1: BACKEND PROVIDERS │
|
|
55
|
+
│ - ConvexProvider → Convex real-time database │
|
|
56
|
+
│ - NotionProvider → Notion API (pages + relations) │
|
|
57
|
+
│ - WordPressProvider → WordPress REST API + ACF │
|
|
58
|
+
│ - [Future: Supabase, Firebase, Airtable, etc.] │
|
|
59
|
+
└─────────────────────────────────────────────────────────┘
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
**Key Principle:** Each layer only knows about the layer directly below it. Components don't know what backend is being used.
|
|
63
|
+
|
|
64
|
+
---
|
|
65
|
+
|
|
66
|
+
## Layer 1: DataProvider Interface
|
|
67
|
+
|
|
68
|
+
### The Contract
|
|
69
|
+
|
|
70
|
+
The `DataProvider` interface defines ALL operations for the 6-dimension ontology:
|
|
71
|
+
|
|
72
|
+
```typescript
|
|
73
|
+
// frontend/src/providers/DataProvider.ts
|
|
74
|
+
export interface DataProvider {
|
|
75
|
+
// ===== ORGANIZATIONS (Dimension 1) =====
|
|
76
|
+
organizations: {
|
|
77
|
+
get: (id: string) => Effect.Effect<Organization, OrganizationNotFoundError>;
|
|
78
|
+
list: (options?: ListOptions) => Effect.Effect<Organization[], QueryError>;
|
|
79
|
+
create: (input: CreateOrgInput) => Effect.Effect<string, OrgCreateError>;
|
|
80
|
+
update: (id: string, input: UpdateOrgInput) => Effect.Effect<void, OrgUpdateError>;
|
|
81
|
+
delete: (id: string) => Effect.Effect<void, OrgDeleteError>;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
// ===== PEOPLE (Dimension 2) =====
|
|
85
|
+
people: {
|
|
86
|
+
getCurrentUser: () => Effect.Effect<User, UserNotFoundError>;
|
|
87
|
+
getByRole: (role: Role) => Effect.Effect<User[], QueryError>;
|
|
88
|
+
updateRole: (userId: string, role: Role) => Effect.Effect<void, UpdateError>;
|
|
89
|
+
inviteMember: (input: InviteInput) => Effect.Effect<void, InviteError>;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
// ===== THINGS (Dimension 3) =====
|
|
93
|
+
things: {
|
|
94
|
+
get: (id: string) => Effect.Effect<Thing, ThingNotFoundError>;
|
|
95
|
+
list: (options: ListThingsOptions) => Effect.Effect<Thing[], QueryError>;
|
|
96
|
+
create: (input: CreateThingInput) => Effect.Effect<string, ThingCreateError>;
|
|
97
|
+
update: (id: string, input: UpdateThingInput) => Effect.Effect<void, ThingUpdateError>;
|
|
98
|
+
delete: (id: string) => Effect.Effect<void, ThingDeleteError>;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
// ===== CONNECTIONS (Dimension 4) =====
|
|
102
|
+
connections: {
|
|
103
|
+
get: (id: string) => Effect.Effect<Connection, ConnectionNotFoundError>;
|
|
104
|
+
list: (options: ListConnectionsOptions) => Effect.Effect<Connection[], QueryError>;
|
|
105
|
+
create: (input: CreateConnectionInput) => Effect.Effect<string, ConnectionCreateError>;
|
|
106
|
+
delete: (id: string) => Effect.Effect<void, ConnectionDeleteError>;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
// ===== EVENTS (Dimension 5) =====
|
|
110
|
+
events: {
|
|
111
|
+
create: (input: CreateEventInput) => Effect.Effect<string, EventCreateError>;
|
|
112
|
+
list: (options: ListEventsOptions) => Effect.Effect<Event[], QueryError>;
|
|
113
|
+
getAuditTrail: (thingId: string) => Effect.Effect<Event[], QueryError>;
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
// ===== KNOWLEDGE (Dimension 6) =====
|
|
117
|
+
knowledge: {
|
|
118
|
+
search: (options: SearchKnowledgeOptions) => Effect.Effect<Knowledge[], QueryError>;
|
|
119
|
+
create: (input: CreateKnowledgeInput) => Effect.Effect<string, KnowledgeCreateError>;
|
|
120
|
+
linkToThing: (thingId: string, knowledgeId: string) => Effect.Effect<void, LinkError>;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
// ===== AUTH =====
|
|
124
|
+
auth: {
|
|
125
|
+
login: (args: LoginArgs) => Effect.Effect<AuthResult, AuthError>;
|
|
126
|
+
signup: (args: SignupArgs) => Effect.Effect<AuthResult, AuthError>;
|
|
127
|
+
logout: () => Effect.Effect<void, AuthError>;
|
|
128
|
+
getCurrentUser: () => Effect.Effect<User, AuthError>;
|
|
129
|
+
// ... 8 more auth methods
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### Why Effect.ts?
|
|
135
|
+
|
|
136
|
+
Every operation returns an `Effect.Effect<Success, Error>` type. This provides:
|
|
137
|
+
|
|
138
|
+
1. **Type-safe errors**: Compiler catches unhandled errors
|
|
139
|
+
2. **Composability**: Chain operations together
|
|
140
|
+
3. **Dependency injection**: Services declare what they need
|
|
141
|
+
4. **Testability**: Mock providers easily
|
|
142
|
+
5. **Pure functions**: No side effects until `Effect.runPromise()`
|
|
143
|
+
|
|
144
|
+
**Example:**
|
|
145
|
+
|
|
146
|
+
```typescript
|
|
147
|
+
// Type-safe error handling
|
|
148
|
+
const program = Effect.gen(function* () {
|
|
149
|
+
const thing = yield* provider.things.get(id); // Can fail with ThingNotFoundError
|
|
150
|
+
const connections = yield* provider.connections.list({ fromEntityId: id }); // Can fail with QueryError
|
|
151
|
+
return { thing, connections };
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
// Compiler forces you to handle both error types
|
|
155
|
+
await Effect.runPromise(
|
|
156
|
+
program.pipe(
|
|
157
|
+
Effect.catchTag('ThingNotFoundError', (error) => {
|
|
158
|
+
console.error('Thing not found:', error.message);
|
|
159
|
+
return Effect.succeed(null);
|
|
160
|
+
}),
|
|
161
|
+
Effect.catchTag('QueryError', (error) => {
|
|
162
|
+
console.error('Query failed:', error.message);
|
|
163
|
+
return Effect.succeed(null);
|
|
164
|
+
})
|
|
165
|
+
)
|
|
166
|
+
);
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
---
|
|
170
|
+
|
|
171
|
+
## Layer 2: Backend Providers
|
|
172
|
+
|
|
173
|
+
### Three Providers Implemented
|
|
174
|
+
|
|
175
|
+
#### 1. ConvexProvider (Default)
|
|
176
|
+
|
|
177
|
+
Wraps the Convex SDK with the DataProvider interface.
|
|
178
|
+
|
|
179
|
+
**File:** `frontend/src/providers/ConvexProvider.ts`
|
|
180
|
+
|
|
181
|
+
**How it works:**
|
|
182
|
+
|
|
183
|
+
```typescript
|
|
184
|
+
export function createConvexProvider(config: ConvexProviderConfig): DataProvider {
|
|
185
|
+
const { client } = config;
|
|
186
|
+
|
|
187
|
+
return {
|
|
188
|
+
things: {
|
|
189
|
+
get: (id) =>
|
|
190
|
+
Effect.tryPromise({
|
|
191
|
+
try: () => client.query(api.queries.things.get, { id }),
|
|
192
|
+
catch: (error) => new ThingNotFoundError(id, String(error)),
|
|
193
|
+
}),
|
|
194
|
+
list: (options) =>
|
|
195
|
+
Effect.tryPromise({
|
|
196
|
+
try: () => client.query(api.queries.things.list, options),
|
|
197
|
+
catch: (error) => new QueryError('Failed to list things', error),
|
|
198
|
+
}),
|
|
199
|
+
create: (input) =>
|
|
200
|
+
Effect.tryPromise({
|
|
201
|
+
try: () => client.mutation(api.mutations.things.create, input),
|
|
202
|
+
catch: (error) => new ThingCreateError('Failed to create thing', error),
|
|
203
|
+
}),
|
|
204
|
+
// ... more operations
|
|
205
|
+
},
|
|
206
|
+
// ... other dimensions
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
**Features:**
|
|
212
|
+
- Real-time subscriptions via Convex
|
|
213
|
+
- <5ms overhead per operation
|
|
214
|
+
- Zero backend changes required
|
|
215
|
+
- Supports all 6 dimensions natively
|
|
216
|
+
|
|
217
|
+
#### 2. NotionProvider
|
|
218
|
+
|
|
219
|
+
Maps Notion databases and pages to the 6-dimension ontology.
|
|
220
|
+
|
|
221
|
+
**File:** `frontend/src/providers/notion/NotionProvider.ts` (1,200+ lines)
|
|
222
|
+
|
|
223
|
+
**Mapping Strategy:**
|
|
224
|
+
|
|
225
|
+
| Ontology | Notion |
|
|
226
|
+
|----------|--------|
|
|
227
|
+
| Things | Pages in databases |
|
|
228
|
+
| Connections | Relation properties |
|
|
229
|
+
| Events | Page updates (delegated to Convex) |
|
|
230
|
+
| Knowledge | Database properties as labels |
|
|
231
|
+
| Organizations | Page property: `organizationId` |
|
|
232
|
+
| People | Person properties + permissions |
|
|
233
|
+
|
|
234
|
+
**Example:**
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
// Notion Page → Thing
|
|
238
|
+
const notionPage = {
|
|
239
|
+
id: "abc123",
|
|
240
|
+
properties: {
|
|
241
|
+
Name: { title: [{ text: { content: "My Course" } }] },
|
|
242
|
+
Status: { select: { name: "Published" } },
|
|
243
|
+
Price: { number: 99 },
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
// Becomes:
|
|
248
|
+
const thing = {
|
|
249
|
+
_id: "notion_abc123",
|
|
250
|
+
type: "course",
|
|
251
|
+
name: "My Course",
|
|
252
|
+
status: "published",
|
|
253
|
+
properties: {
|
|
254
|
+
price: 99,
|
|
255
|
+
notionId: "abc123"
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
**ID Format:** `notion_<32-char-hex>` (prevents collisions)
|
|
261
|
+
|
|
262
|
+
**Hybrid Approach:** Notion handles things/connections, Convex handles events/knowledge (for backends without native support)
|
|
263
|
+
|
|
264
|
+
#### 3. WordPressProvider
|
|
265
|
+
|
|
266
|
+
Maps WordPress posts and custom post types to the ontology.
|
|
267
|
+
|
|
268
|
+
**File:** `frontend/src/providers/wordpress/WordPressProviderEnhanced.ts` (1,100+ lines)
|
|
269
|
+
|
|
270
|
+
**Mapping Strategy:**
|
|
271
|
+
|
|
272
|
+
| Ontology | WordPress |
|
|
273
|
+
|----------|-----------|
|
|
274
|
+
| Things | Posts + Custom Post Types |
|
|
275
|
+
| Connections | Custom `wp_connections` table |
|
|
276
|
+
| Events | Custom `wp_events` table |
|
|
277
|
+
| Knowledge | Custom `wp_knowledge` table |
|
|
278
|
+
| Organizations | Post meta: `_organization_id` |
|
|
279
|
+
| People | WordPress users + roles |
|
|
280
|
+
|
|
281
|
+
**Requires:** Custom WordPress plugin `one-platform-connector` (creates tables + REST endpoints)
|
|
282
|
+
|
|
283
|
+
**Example:**
|
|
284
|
+
|
|
285
|
+
```typescript
|
|
286
|
+
// WordPress Post → Thing
|
|
287
|
+
const wpPost = {
|
|
288
|
+
id: 123,
|
|
289
|
+
title: "My Course",
|
|
290
|
+
status: "publish",
|
|
291
|
+
type: "course",
|
|
292
|
+
meta: {
|
|
293
|
+
_organization_id: "org_xyz",
|
|
294
|
+
_properties: JSON.stringify({ price: 99 })
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
// Becomes:
|
|
299
|
+
const thing = {
|
|
300
|
+
_id: "wp_course_123",
|
|
301
|
+
type: "course",
|
|
302
|
+
name: "My Course",
|
|
303
|
+
status: "published",
|
|
304
|
+
organizationId: "org_xyz",
|
|
305
|
+
properties: { price: 99 }
|
|
306
|
+
};
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
**ID Format:** `wp_<post-type>_<id>` (e.g., `wp_course_123`, `wp_lesson_456`)
|
|
310
|
+
|
|
311
|
+
---
|
|
312
|
+
|
|
313
|
+
## Layer 3: Effect.ts Services
|
|
314
|
+
|
|
315
|
+
### Business Logic Layer
|
|
316
|
+
|
|
317
|
+
Services contain pure business logic that works with ANY backend:
|
|
318
|
+
|
|
319
|
+
**File:** `frontend/src/services/ThingService.ts`
|
|
320
|
+
|
|
321
|
+
```typescript
|
|
322
|
+
import { Effect, Layer } from 'effect';
|
|
323
|
+
import type { DataProvider } from '@/providers/DataProvider';
|
|
324
|
+
|
|
325
|
+
export class ThingService extends Effect.Service<ThingService>()('ThingService', {
|
|
326
|
+
effect: Effect.gen(function* () {
|
|
327
|
+
const provider = yield* DataProviderService;
|
|
328
|
+
|
|
329
|
+
return {
|
|
330
|
+
// Create thing with validation
|
|
331
|
+
create: (input: CreateThingInput) =>
|
|
332
|
+
Effect.gen(function* () {
|
|
333
|
+
// 1. Validate thing type
|
|
334
|
+
if (!VALID_THING_TYPES.includes(input.type)) {
|
|
335
|
+
return yield* Effect.fail(new InvalidThingTypeError(input.type));
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// 2. Validate type-specific rules
|
|
339
|
+
if (input.type === 'course' && !input.properties.title) {
|
|
340
|
+
return yield* Effect.fail(new ValidationError('Course requires title'));
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// 3. Create via provider
|
|
344
|
+
const thingId = yield* provider.things.create(input);
|
|
345
|
+
|
|
346
|
+
// 4. Log creation event
|
|
347
|
+
yield* provider.events.create({
|
|
348
|
+
type: 'thing_created',
|
|
349
|
+
thingId,
|
|
350
|
+
actorId: input.actorId,
|
|
351
|
+
timestamp: Date.now(),
|
|
352
|
+
metadata: { thingType: input.type }
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
return thingId;
|
|
356
|
+
}),
|
|
357
|
+
|
|
358
|
+
// Get thing with related data
|
|
359
|
+
getWithConnections: (id: string) =>
|
|
360
|
+
Effect.gen(function* () {
|
|
361
|
+
const thing = yield* provider.things.get(id);
|
|
362
|
+
const connections = yield* provider.connections.list({ fromEntityId: id });
|
|
363
|
+
return { thing, connections };
|
|
364
|
+
}),
|
|
365
|
+
|
|
366
|
+
// More operations...
|
|
367
|
+
};
|
|
368
|
+
}),
|
|
369
|
+
dependencies: [DataProviderService.Default],
|
|
370
|
+
}) {}
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
### Key Features
|
|
374
|
+
|
|
375
|
+
1. **Type-Specific Validation:** Each of the 66 thing types has custom rules
|
|
376
|
+
2. **Authorization:** Checks roles before allowing operations
|
|
377
|
+
3. **Event Logging:** Automatically logs all state changes
|
|
378
|
+
4. **Backend-Agnostic:** Never imports Convex/Notion/WordPress directly
|
|
379
|
+
5. **Composable:** Services can call other services
|
|
380
|
+
|
|
381
|
+
### All 7 Services
|
|
382
|
+
|
|
383
|
+
| Service | Purpose | LOC |
|
|
384
|
+
|---------|---------|-----|
|
|
385
|
+
| ThingService | Manages 66 entity types | 246 |
|
|
386
|
+
| ConnectionService | Manages 25 relationship types | 300 |
|
|
387
|
+
| EventService | Manages 67 event types | 294 |
|
|
388
|
+
| KnowledgeService | RAG, labels, embeddings | 299 |
|
|
389
|
+
| OrganizationService | Multi-tenancy, quotas | 409 |
|
|
390
|
+
| PeopleService | Authorization, roles | 444 |
|
|
391
|
+
| ConfigService | Provider configuration | 511 |
|
|
392
|
+
|
|
393
|
+
**Total:** 2,503 lines of pure business logic
|
|
394
|
+
|
|
395
|
+
---
|
|
396
|
+
|
|
397
|
+
## Layer 4: React Hooks
|
|
398
|
+
|
|
399
|
+
### Backend-Agnostic Hooks
|
|
400
|
+
|
|
401
|
+
React hooks wrap services to provide convenient, type-safe access:
|
|
402
|
+
|
|
403
|
+
**File:** `frontend/src/hooks/useThings.tsx`
|
|
404
|
+
|
|
405
|
+
```typescript
|
|
406
|
+
import { useDataProvider } from './useDataProvider';
|
|
407
|
+
import { useMutation, useQuery } from '@tanstack/react-query';
|
|
408
|
+
import { Effect } from 'effect';
|
|
409
|
+
|
|
410
|
+
export function useThings(options: ListThingsOptions) {
|
|
411
|
+
const provider = useDataProvider();
|
|
412
|
+
|
|
413
|
+
return useQuery({
|
|
414
|
+
queryKey: ['things', options],
|
|
415
|
+
queryFn: async () => {
|
|
416
|
+
return await Effect.runPromise(provider.things.list(options));
|
|
417
|
+
},
|
|
418
|
+
staleTime: 5000, // 5 seconds
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
export function useCreateThing() {
|
|
423
|
+
const provider = useDataProvider();
|
|
424
|
+
const queryClient = useQueryClient();
|
|
425
|
+
|
|
426
|
+
return useMutation({
|
|
427
|
+
mutationFn: async (input: CreateThingInput) => {
|
|
428
|
+
return await Effect.runPromise(provider.things.create(input));
|
|
429
|
+
},
|
|
430
|
+
onSuccess: () => {
|
|
431
|
+
// Invalidate and refetch
|
|
432
|
+
queryClient.invalidateQueries({ queryKey: ['things'] });
|
|
433
|
+
},
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
### Auth Hooks
|
|
439
|
+
|
|
440
|
+
**File:** `frontend/src/hooks/useAuth.ts`
|
|
441
|
+
|
|
442
|
+
```typescript
|
|
443
|
+
export function useLogin() {
|
|
444
|
+
const provider = useDataProvider();
|
|
445
|
+
const [loading, setLoading] = useState(false);
|
|
446
|
+
const [error, setError] = useState<AuthError | null>(null);
|
|
447
|
+
|
|
448
|
+
const mutate = useCallback(async (args: LoginArgs) => {
|
|
449
|
+
setLoading(true);
|
|
450
|
+
setError(null);
|
|
451
|
+
|
|
452
|
+
try {
|
|
453
|
+
return await Effect.runPromise(provider.auth.login(args));
|
|
454
|
+
} catch (err) {
|
|
455
|
+
setError(err as AuthError);
|
|
456
|
+
throw err;
|
|
457
|
+
} finally {
|
|
458
|
+
setLoading(false);
|
|
459
|
+
}
|
|
460
|
+
}, [provider]);
|
|
461
|
+
|
|
462
|
+
return { mutate, loading, error };
|
|
463
|
+
}
|
|
464
|
+
```
|
|
465
|
+
|
|
466
|
+
### Hook Inventory
|
|
467
|
+
|
|
468
|
+
**All 45 hooks implemented:**
|
|
469
|
+
|
|
470
|
+
| Category | Hooks | Purpose |
|
|
471
|
+
|----------|-------|---------|
|
|
472
|
+
| Organizations | 7 hooks | Org management, members |
|
|
473
|
+
| People | 7 hooks | Users, roles, permissions |
|
|
474
|
+
| Things | 8 hooks | CRUD + type-specific |
|
|
475
|
+
| Connections | 8 hooks | Relationships |
|
|
476
|
+
| Events | 6 hooks | Audit trails, activity |
|
|
477
|
+
| Knowledge | 6 hooks | RAG, search, labels |
|
|
478
|
+
| Auth | 7 hooks | All 6 auth methods |
|
|
479
|
+
|
|
480
|
+
---
|
|
481
|
+
|
|
482
|
+
## Layer 5: UI Components
|
|
483
|
+
|
|
484
|
+
### Backend-Agnostic Components
|
|
485
|
+
|
|
486
|
+
Components only use hooks, never backend-specific code:
|
|
487
|
+
|
|
488
|
+
```typescript
|
|
489
|
+
// frontend/src/components/courses/CourseList.tsx
|
|
490
|
+
import { useThings } from '@/hooks/useThings';
|
|
491
|
+
import { Card } from '@/components/ui/card';
|
|
492
|
+
|
|
493
|
+
export function CourseList() {
|
|
494
|
+
const { data: courses, loading, error } = useThings({ type: 'course' });
|
|
495
|
+
|
|
496
|
+
if (loading) return <div>Loading courses...</div>;
|
|
497
|
+
if (error) return <div>Error: {error.message}</div>;
|
|
498
|
+
|
|
499
|
+
return (
|
|
500
|
+
<div className="grid grid-cols-3 gap-4">
|
|
501
|
+
{courses?.map((course) => (
|
|
502
|
+
<Card key={course._id}>
|
|
503
|
+
<h3>{course.name}</h3>
|
|
504
|
+
<p>{course.properties.description}</p>
|
|
505
|
+
<span>${course.properties.price}</span>
|
|
506
|
+
</Card>
|
|
507
|
+
))}
|
|
508
|
+
</div>
|
|
509
|
+
);
|
|
510
|
+
}
|
|
511
|
+
```
|
|
512
|
+
|
|
513
|
+
**This component works identically whether:**
|
|
514
|
+
- Backend is Convex
|
|
515
|
+
- Backend is Notion
|
|
516
|
+
- Backend is WordPress
|
|
517
|
+
- Backend is Supabase (future)
|
|
518
|
+
|
|
519
|
+
**Zero code changes required when switching backends.**
|
|
520
|
+
|
|
521
|
+
---
|
|
522
|
+
|
|
523
|
+
## Configuration System
|
|
524
|
+
|
|
525
|
+
### Environment-Based Configuration
|
|
526
|
+
|
|
527
|
+
**File:** `frontend/src/config/providers.ts`
|
|
528
|
+
|
|
529
|
+
```bash
|
|
530
|
+
# .env.local
|
|
531
|
+
|
|
532
|
+
# Choose your backend (convex, wordpress, notion, supabase)
|
|
533
|
+
BACKEND_PROVIDER=convex
|
|
534
|
+
|
|
535
|
+
# Convex configuration
|
|
536
|
+
PUBLIC_CONVEX_URL=https://shocking-falcon-870.convex.cloud
|
|
537
|
+
CONVEX_DEPLOYMENT=prod:shocking-falcon-870
|
|
538
|
+
|
|
539
|
+
# WordPress configuration (if using)
|
|
540
|
+
WORDPRESS_URL=https://mysite.com/wp-json
|
|
541
|
+
WORDPRESS_USERNAME=admin
|
|
542
|
+
WORDPRESS_APP_PASSWORD=xxxx xxxx xxxx xxxx xxxx xxxx
|
|
543
|
+
|
|
544
|
+
# Notion configuration (if using)
|
|
545
|
+
NOTION_API_TOKEN=secret_abc123...
|
|
546
|
+
NOTION_DATABASE_ID=def456...
|
|
547
|
+
|
|
548
|
+
# Encryption key (for secure credential storage)
|
|
549
|
+
PROVIDER_ENCRYPTION_KEY=your-32-byte-hex-key
|
|
550
|
+
```
|
|
551
|
+
|
|
552
|
+
### Multi-Tenant Configuration
|
|
553
|
+
|
|
554
|
+
Organizations can have different backends:
|
|
555
|
+
|
|
556
|
+
```typescript
|
|
557
|
+
// Organization 1 uses Convex
|
|
558
|
+
{
|
|
559
|
+
_id: "org_1",
|
|
560
|
+
name: "Startup Inc",
|
|
561
|
+
properties: {
|
|
562
|
+
backendProvider: "convex",
|
|
563
|
+
backendConfig: {
|
|
564
|
+
deploymentUrl: "https://fast-startup-123.convex.cloud"
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// Organization 2 uses WordPress
|
|
570
|
+
{
|
|
571
|
+
_id: "org_2",
|
|
572
|
+
name: "Enterprise Corp",
|
|
573
|
+
properties: {
|
|
574
|
+
backendProvider: "wordpress",
|
|
575
|
+
backendConfig: {
|
|
576
|
+
url: "https://enterprise.com/wp-json",
|
|
577
|
+
credentials: "encrypted:abc123..."
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
```
|
|
582
|
+
|
|
583
|
+
### Runtime Provider Switching
|
|
584
|
+
|
|
585
|
+
```typescript
|
|
586
|
+
// Switch organization's backend
|
|
587
|
+
await switchProviderForOrganization(
|
|
588
|
+
'org_123',
|
|
589
|
+
{
|
|
590
|
+
type: 'notion',
|
|
591
|
+
token: 'secret_xyz...',
|
|
592
|
+
databaseId: 'abc123...'
|
|
593
|
+
},
|
|
594
|
+
'user_456' // Actor who made the change
|
|
595
|
+
);
|
|
596
|
+
|
|
597
|
+
// Takes <30 seconds
|
|
598
|
+
// - Validates new config
|
|
599
|
+
// - Tests connection
|
|
600
|
+
- Saves config to database
|
|
601
|
+
// - Clears cache
|
|
602
|
+
// - Logs provider_switched event
|
|
603
|
+
```
|
|
604
|
+
|
|
605
|
+
---
|
|
606
|
+
|
|
607
|
+
## Provider Setup
|
|
608
|
+
|
|
609
|
+
### AppProviders Component
|
|
610
|
+
|
|
611
|
+
The root provider that gives all components access to DataProvider:
|
|
612
|
+
|
|
613
|
+
**File:** `frontend/src/components/providers/AppProviders.tsx`
|
|
614
|
+
|
|
615
|
+
```typescript
|
|
616
|
+
import { ConvexProvider } from 'convex/react';
|
|
617
|
+
import { ConvexReactClient } from 'convex/react';
|
|
618
|
+
import { DataProviderProvider } from '@/hooks/useDataProvider';
|
|
619
|
+
import { createConvexProvider } from '@/providers/ConvexProvider';
|
|
620
|
+
|
|
621
|
+
const convexClient = new ConvexReactClient(import.meta.env.PUBLIC_CONVEX_URL);
|
|
622
|
+
const convexDataProvider = createConvexProvider({ client: convexClient });
|
|
623
|
+
|
|
624
|
+
export function AppProviders({ children }: { children: ReactNode }) {
|
|
625
|
+
return (
|
|
626
|
+
<ConvexProvider client={convexClient}>
|
|
627
|
+
<DataProviderProvider provider={convexDataProvider}>
|
|
628
|
+
{children}
|
|
629
|
+
</DataProviderProvider>
|
|
630
|
+
</ConvexProvider>
|
|
631
|
+
);
|
|
632
|
+
}
|
|
633
|
+
```
|
|
634
|
+
|
|
635
|
+
### Usage in Astro Pages
|
|
636
|
+
|
|
637
|
+
Due to Astro's islands architecture, wrap auth components:
|
|
638
|
+
|
|
639
|
+
```tsx
|
|
640
|
+
// frontend/src/components/auth/SignInPage.tsx
|
|
641
|
+
import { AppProviders } from '@/components/providers/AppProviders';
|
|
642
|
+
import { SimpleSignInForm } from './SimpleSignInForm';
|
|
643
|
+
|
|
644
|
+
export function SignInPage() {
|
|
645
|
+
return (
|
|
646
|
+
<AppProviders>
|
|
647
|
+
<SimpleSignInForm />
|
|
648
|
+
</AppProviders>
|
|
649
|
+
);
|
|
650
|
+
}
|
|
651
|
+
```
|
|
652
|
+
|
|
653
|
+
```astro
|
|
654
|
+
---
|
|
655
|
+
// frontend/src/pages/account/signin.astro
|
|
656
|
+
import { SignInPage } from '@/components/auth/SignInPage';
|
|
657
|
+
---
|
|
658
|
+
|
|
659
|
+
<Layout title="Sign In">
|
|
660
|
+
<SignInPage client:only="react" />
|
|
661
|
+
</Layout>
|
|
662
|
+
```
|
|
663
|
+
|
|
664
|
+
**Why this pattern?** Astro's `client:only` creates isolated React islands. The provider must be inside the same island as components that use hooks.
|
|
665
|
+
|
|
666
|
+
---
|
|
667
|
+
|
|
668
|
+
## Adding a New Provider
|
|
669
|
+
|
|
670
|
+
### 6-Step Process
|
|
671
|
+
|
|
672
|
+
**Step 1: Create Provider File**
|
|
673
|
+
|
|
674
|
+
```typescript
|
|
675
|
+
// frontend/src/providers/supabase/SupabaseProvider.ts
|
|
676
|
+
import { createClient } from '@supabase/supabase-js';
|
|
677
|
+
import type { DataProvider } from '@/providers/DataProvider';
|
|
678
|
+
|
|
679
|
+
export function createSupabaseProvider(config: SupabaseConfig): DataProvider {
|
|
680
|
+
const supabase = createClient(config.url, config.anonKey);
|
|
681
|
+
|
|
682
|
+
return {
|
|
683
|
+
things: {
|
|
684
|
+
get: (id) =>
|
|
685
|
+
Effect.tryPromise({
|
|
686
|
+
try: async () => {
|
|
687
|
+
const { data, error } = await supabase
|
|
688
|
+
.from('things')
|
|
689
|
+
.select('*')
|
|
690
|
+
.eq('id', id)
|
|
691
|
+
.single();
|
|
692
|
+
|
|
693
|
+
if (error) throw error;
|
|
694
|
+
return mapSupabaseRowToThing(data);
|
|
695
|
+
},
|
|
696
|
+
catch: (error) => new ThingNotFoundError(id, String(error)),
|
|
697
|
+
}),
|
|
698
|
+
// ... more operations
|
|
699
|
+
},
|
|
700
|
+
// ... other dimensions
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
```
|
|
704
|
+
|
|
705
|
+
**Step 2: Define ID Format**
|
|
706
|
+
|
|
707
|
+
```typescript
|
|
708
|
+
// Supabase: Use UUIDs
|
|
709
|
+
const thingId = "supabase_550e8400-e29b-41d4-a716-446655440000";
|
|
710
|
+
|
|
711
|
+
// Conversion functions
|
|
712
|
+
function supabaseIdToOneId(uuid: string): string {
|
|
713
|
+
return `supabase_${uuid}`;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function oneIdToSupabaseId(id: string): string {
|
|
717
|
+
return id.replace('supabase_', '');
|
|
718
|
+
}
|
|
719
|
+
```
|
|
720
|
+
|
|
721
|
+
**Step 3: Map Database Schema**
|
|
722
|
+
|
|
723
|
+
```sql
|
|
724
|
+
-- Supabase tables
|
|
725
|
+
CREATE TABLE things (
|
|
726
|
+
id UUID PRIMARY KEY,
|
|
727
|
+
type VARCHAR(50),
|
|
728
|
+
name TEXT,
|
|
729
|
+
status VARCHAR(20),
|
|
730
|
+
properties JSONB,
|
|
731
|
+
organization_id VARCHAR(100),
|
|
732
|
+
created_at TIMESTAMP,
|
|
733
|
+
updated_at TIMESTAMP
|
|
734
|
+
);
|
|
735
|
+
|
|
736
|
+
CREATE TABLE connections (
|
|
737
|
+
id UUID PRIMARY KEY,
|
|
738
|
+
from_thing_id UUID REFERENCES things(id),
|
|
739
|
+
to_thing_id UUID REFERENCES things(id),
|
|
740
|
+
relationship_type VARCHAR(50),
|
|
741
|
+
metadata JSONB,
|
|
742
|
+
created_at TIMESTAMP
|
|
743
|
+
);
|
|
744
|
+
|
|
745
|
+
-- ... events, knowledge tables
|
|
746
|
+
```
|
|
747
|
+
|
|
748
|
+
**Step 4: Implement All 6 Dimensions**
|
|
749
|
+
|
|
750
|
+
Implement all methods for organizations, people, things, connections, events, knowledge, and auth.
|
|
751
|
+
|
|
752
|
+
**Step 5: Add to Factory**
|
|
753
|
+
|
|
754
|
+
```typescript
|
|
755
|
+
// frontend/src/providers/factory.ts
|
|
756
|
+
export function createProvider(config: ProviderConfig): DataProvider {
|
|
757
|
+
switch (config.type) {
|
|
758
|
+
case 'convex':
|
|
759
|
+
return createConvexProvider(config);
|
|
760
|
+
case 'notion':
|
|
761
|
+
return createNotionProvider(config);
|
|
762
|
+
case 'wordpress':
|
|
763
|
+
return createWordPressProvider(config);
|
|
764
|
+
case 'supabase':
|
|
765
|
+
return createSupabaseProvider(config); // ✨ New
|
|
766
|
+
default:
|
|
767
|
+
throw new Error(`Unknown provider: ${config.type}`);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
```
|
|
771
|
+
|
|
772
|
+
**Step 6: Write Tests**
|
|
773
|
+
|
|
774
|
+
```typescript
|
|
775
|
+
// frontend/test/providers/SupabaseProvider.test.ts
|
|
776
|
+
describe('SupabaseProvider', () => {
|
|
777
|
+
it('should create thing', async () => {
|
|
778
|
+
const provider = createSupabaseProvider(testConfig);
|
|
779
|
+
const thingId = await Effect.runPromise(
|
|
780
|
+
provider.things.create({
|
|
781
|
+
type: 'course',
|
|
782
|
+
name: 'Test Course',
|
|
783
|
+
properties: { price: 99 }
|
|
784
|
+
})
|
|
785
|
+
);
|
|
786
|
+
expect(thingId).toMatch(/^supabase_/);
|
|
787
|
+
});
|
|
788
|
+
|
|
789
|
+
// ... 80 more tests
|
|
790
|
+
});
|
|
791
|
+
```
|
|
792
|
+
|
|
793
|
+
**Documentation:** See `one/knowledge/provider-creation-guide.md` for complete guide.
|
|
794
|
+
|
|
795
|
+
---
|
|
796
|
+
|
|
797
|
+
## Performance
|
|
798
|
+
|
|
799
|
+
### Overhead Measurements
|
|
800
|
+
|
|
801
|
+
| Operation | Baseline (Direct) | With DataProvider | Overhead | Status |
|
|
802
|
+
|-----------|-------------------|-------------------|----------|--------|
|
|
803
|
+
| Get Thing | 5ms | 6ms | +1ms | ✅ <10ms |
|
|
804
|
+
| List Things | 10ms | 11ms | +1ms | ✅ <10ms |
|
|
805
|
+
| Create Thing | 15ms | 16ms | +1ms | ✅ <10ms |
|
|
806
|
+
| Update Thing | 10ms | 11ms | +1ms | ✅ <10ms |
|
|
807
|
+
| Delete Thing | 8ms | 9ms | +1ms | ✅ <10ms |
|
|
808
|
+
|
|
809
|
+
**Target:** <10ms overhead per operation ✅ **Achieved**
|
|
810
|
+
|
|
811
|
+
### Why So Fast?
|
|
812
|
+
|
|
813
|
+
1. **Thin wrappers:** Providers just map types, no processing
|
|
814
|
+
2. **Effect.ts optimized:** Minimal runtime overhead
|
|
815
|
+
3. **Direct backend calls:** No middleware, no proxies
|
|
816
|
+
4. **Smart caching:** React Query handles data caching
|
|
817
|
+
|
|
818
|
+
---
|
|
819
|
+
|
|
820
|
+
## Migration Guide
|
|
821
|
+
|
|
822
|
+
### From Direct Convex to DataProvider
|
|
823
|
+
|
|
824
|
+
**Before:**
|
|
825
|
+
|
|
826
|
+
```typescript
|
|
827
|
+
import { useMutation, useQuery } from 'convex/react';
|
|
828
|
+
import { api } from '@/convex/_generated/api';
|
|
829
|
+
|
|
830
|
+
function CourseList() {
|
|
831
|
+
const courses = useQuery(api.queries.things.list, { type: 'course' });
|
|
832
|
+
const create = useMutation(api.mutations.things.create);
|
|
833
|
+
|
|
834
|
+
return <div>{courses?.map(c => <div>{c.name}</div>)}</div>;
|
|
835
|
+
}
|
|
836
|
+
```
|
|
837
|
+
|
|
838
|
+
**After:**
|
|
839
|
+
|
|
840
|
+
```typescript
|
|
841
|
+
import { useThings, useCreateThing } from '@/hooks/useThings';
|
|
842
|
+
|
|
843
|
+
function CourseList() {
|
|
844
|
+
const { data: courses } = useThings({ type: 'course' });
|
|
845
|
+
const { mutate: create } = useCreateThing();
|
|
846
|
+
|
|
847
|
+
return <div>{courses?.map(c => <div>{c.name}</div>)}</div>;
|
|
848
|
+
}
|
|
849
|
+
```
|
|
850
|
+
|
|
851
|
+
**Changes:**
|
|
852
|
+
1. Replace `useQuery(api.*)` with `useThings()`
|
|
853
|
+
2. Replace `useMutation(api.*)` with `useCreateThing()`
|
|
854
|
+
3. Wrap page with `AppProviders`
|
|
855
|
+
|
|
856
|
+
**Benefits:**
|
|
857
|
+
- Can now switch to WordPress/Notion/Supabase without code changes
|
|
858
|
+
- Better error handling with typed errors
|
|
859
|
+
- Built-in loading states
|
|
860
|
+
- Optimistic updates
|
|
861
|
+
|
|
862
|
+
---
|
|
863
|
+
|
|
864
|
+
## Multi-Tenant Support
|
|
865
|
+
|
|
866
|
+
### Organization-Level Configuration
|
|
867
|
+
|
|
868
|
+
Each organization can use a different backend:
|
|
869
|
+
|
|
870
|
+
```typescript
|
|
871
|
+
// Organization 1: Convex (fast, real-time)
|
|
872
|
+
const org1 = {
|
|
873
|
+
_id: "org_startup",
|
|
874
|
+
properties: {
|
|
875
|
+
backendProvider: "convex",
|
|
876
|
+
backendConfig: {
|
|
877
|
+
deploymentUrl: "https://fast-startup.convex.cloud"
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
};
|
|
881
|
+
|
|
882
|
+
// Organization 2: WordPress (existing content)
|
|
883
|
+
const org2 = {
|
|
884
|
+
_id: "org_enterprise",
|
|
885
|
+
properties: {
|
|
886
|
+
backendProvider: "wordpress",
|
|
887
|
+
backendConfig: {
|
|
888
|
+
url: "https://enterprise.com/wp-json",
|
|
889
|
+
credentials: "encrypted:..."
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
};
|
|
893
|
+
|
|
894
|
+
// Organization 3: Notion (collaborative docs)
|
|
895
|
+
const org3 = {
|
|
896
|
+
_id: "org_agency",
|
|
897
|
+
properties: {
|
|
898
|
+
backendProvider: "notion",
|
|
899
|
+
backendConfig: {
|
|
900
|
+
token: "secret_...",
|
|
901
|
+
databaseId: "abc123..."
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
};
|
|
905
|
+
```
|
|
906
|
+
|
|
907
|
+
### Data Isolation
|
|
908
|
+
|
|
909
|
+
Perfect isolation between organizations:
|
|
910
|
+
|
|
911
|
+
1. **Convex:** Organization ID in every document
|
|
912
|
+
2. **Notion:** Separate databases per org
|
|
913
|
+
3. **WordPress:** Post meta `_organization_id` filter
|
|
914
|
+
4. **Supabase:** Row-level security (RLS) policies
|
|
915
|
+
|
|
916
|
+
---
|
|
917
|
+
|
|
918
|
+
## Real-World Use Cases
|
|
919
|
+
|
|
920
|
+
### Use Case 1: Startup (Convex)
|
|
921
|
+
|
|
922
|
+
**Profile:**
|
|
923
|
+
- New SaaS company
|
|
924
|
+
- Needs real-time features
|
|
925
|
+
- Fast iteration
|
|
926
|
+
|
|
927
|
+
**Solution:**
|
|
928
|
+
```bash
|
|
929
|
+
BACKEND_PROVIDER=convex
|
|
930
|
+
PUBLIC_CONVEX_URL=https://fast-startup-123.convex.cloud
|
|
931
|
+
```
|
|
932
|
+
|
|
933
|
+
**Benefits:**
|
|
934
|
+
- Real-time subscriptions
|
|
935
|
+
- Instant deploys
|
|
936
|
+
- Free tier generous
|
|
937
|
+
- Zero devops
|
|
938
|
+
|
|
939
|
+
### Use Case 2: Agency (WordPress)
|
|
940
|
+
|
|
941
|
+
**Profile:**
|
|
942
|
+
- Existing WordPress site
|
|
943
|
+
- 10,000+ blog posts
|
|
944
|
+
- Client content expertise
|
|
945
|
+
|
|
946
|
+
**Solution:**
|
|
947
|
+
```bash
|
|
948
|
+
BACKEND_PROVIDER=wordpress
|
|
949
|
+
WORDPRESS_URL=https://agency.com/wp-json
|
|
950
|
+
WORDPRESS_USERNAME=admin
|
|
951
|
+
WORDPRESS_APP_PASSWORD=xxxx xxxx xxxx xxxx
|
|
952
|
+
```
|
|
953
|
+
|
|
954
|
+
**Benefits:**
|
|
955
|
+
- Use existing content
|
|
956
|
+
- No data migration
|
|
957
|
+
- Familiar admin UI
|
|
958
|
+
- SEO-optimized URLs
|
|
959
|
+
|
|
960
|
+
### Use Case 3: Consultancy (Notion)
|
|
961
|
+
|
|
962
|
+
**Profile:**
|
|
963
|
+
- Team uses Notion daily
|
|
964
|
+
- Collaborative documents
|
|
965
|
+
- Client proposals/tracking
|
|
966
|
+
|
|
967
|
+
**Solution:**
|
|
968
|
+
```bash
|
|
969
|
+
BACKEND_PROVIDER=notion
|
|
970
|
+
NOTION_API_TOKEN=secret_abc123...
|
|
971
|
+
NOTION_DATABASE_ID=def456...
|
|
972
|
+
```
|
|
973
|
+
|
|
974
|
+
**Benefits:**
|
|
975
|
+
- Sync with existing workflow
|
|
976
|
+
- Beautiful editor built-in
|
|
977
|
+
- Permission system
|
|
978
|
+
- Export flexibility
|
|
979
|
+
|
|
980
|
+
### Use Case 4: Enterprise (Multi-Backend)
|
|
981
|
+
|
|
982
|
+
**Profile:**
|
|
983
|
+
- Multiple departments
|
|
984
|
+
- Different data sources
|
|
985
|
+
- Compliance requirements
|
|
986
|
+
|
|
987
|
+
**Solution:**
|
|
988
|
+
- Marketing dept → WordPress (public content)
|
|
989
|
+
- Engineering dept → Convex (real-time data)
|
|
990
|
+
- Sales dept → Notion (CRM docs)
|
|
991
|
+
|
|
992
|
+
**Benefits:**
|
|
993
|
+
- Each dept uses best tool
|
|
994
|
+
- ONE unified interface
|
|
995
|
+
- Cross-department connections
|
|
996
|
+
- Centralized reporting
|
|
997
|
+
|
|
998
|
+
---
|
|
999
|
+
|
|
1000
|
+
## Testing
|
|
1001
|
+
|
|
1002
|
+
### Mock Provider Pattern
|
|
1003
|
+
|
|
1004
|
+
For testing, create a mock provider:
|
|
1005
|
+
|
|
1006
|
+
```typescript
|
|
1007
|
+
// test/mocks/MockProvider.ts
|
|
1008
|
+
export function createMockProvider(): DataProvider {
|
|
1009
|
+
const mockData = new Map<string, Thing>();
|
|
1010
|
+
|
|
1011
|
+
return {
|
|
1012
|
+
things: {
|
|
1013
|
+
get: (id) =>
|
|
1014
|
+
mockData.has(id)
|
|
1015
|
+
? Effect.succeed(mockData.get(id)!)
|
|
1016
|
+
: Effect.fail(new ThingNotFoundError(id)),
|
|
1017
|
+
|
|
1018
|
+
create: (input) =>
|
|
1019
|
+
Effect.sync(() => {
|
|
1020
|
+
const id = `mock_${Date.now()}`;
|
|
1021
|
+
mockData.set(id, { _id: id, ...input });
|
|
1022
|
+
return id;
|
|
1023
|
+
}),
|
|
1024
|
+
|
|
1025
|
+
// ... more mocked operations
|
|
1026
|
+
},
|
|
1027
|
+
// ... other dimensions
|
|
1028
|
+
};
|
|
1029
|
+
}
|
|
1030
|
+
```
|
|
1031
|
+
|
|
1032
|
+
### Component Testing
|
|
1033
|
+
|
|
1034
|
+
```typescript
|
|
1035
|
+
import { render } from '@testing-library/react';
|
|
1036
|
+
import { DataProviderProvider } from '@/hooks/useDataProvider';
|
|
1037
|
+
import { createMockProvider } from '@/test/mocks/MockProvider';
|
|
1038
|
+
import { CourseList } from './CourseList';
|
|
1039
|
+
|
|
1040
|
+
test('renders courses', async () => {
|
|
1041
|
+
const mockProvider = createMockProvider();
|
|
1042
|
+
|
|
1043
|
+
// Seed mock data
|
|
1044
|
+
await Effect.runPromise(
|
|
1045
|
+
mockProvider.things.create({
|
|
1046
|
+
type: 'course',
|
|
1047
|
+
name: 'Test Course',
|
|
1048
|
+
properties: { price: 99 }
|
|
1049
|
+
})
|
|
1050
|
+
);
|
|
1051
|
+
|
|
1052
|
+
const { getByText } = render(
|
|
1053
|
+
<DataProviderProvider provider={mockProvider}>
|
|
1054
|
+
<CourseList />
|
|
1055
|
+
</DataProviderProvider>
|
|
1056
|
+
);
|
|
1057
|
+
|
|
1058
|
+
expect(getByText('Test Course')).toBeInTheDocument();
|
|
1059
|
+
});
|
|
1060
|
+
```
|
|
1061
|
+
|
|
1062
|
+
---
|
|
1063
|
+
|
|
1064
|
+
## Security Considerations
|
|
1065
|
+
|
|
1066
|
+
### 1. Credential Encryption
|
|
1067
|
+
|
|
1068
|
+
All backend credentials are encrypted at rest:
|
|
1069
|
+
|
|
1070
|
+
```typescript
|
|
1071
|
+
// Encrypt credentials
|
|
1072
|
+
const encrypted = encryptCredentials(
|
|
1073
|
+
{ username: 'admin', password: 'secret123' },
|
|
1074
|
+
process.env.PROVIDER_ENCRYPTION_KEY
|
|
1075
|
+
);
|
|
1076
|
+
|
|
1077
|
+
// Store encrypted
|
|
1078
|
+
await db.insert('external_connections', {
|
|
1079
|
+
type: 'wordpress',
|
|
1080
|
+
config: { credentials: encrypted }
|
|
1081
|
+
});
|
|
1082
|
+
|
|
1083
|
+
// Decrypt on use
|
|
1084
|
+
const decrypted = decryptCredentials(
|
|
1085
|
+
config.credentials,
|
|
1086
|
+
process.env.PROVIDER_ENCRYPTION_KEY
|
|
1087
|
+
);
|
|
1088
|
+
```
|
|
1089
|
+
|
|
1090
|
+
### 2. Role-Based Access
|
|
1091
|
+
|
|
1092
|
+
Only specific roles can switch providers:
|
|
1093
|
+
|
|
1094
|
+
```typescript
|
|
1095
|
+
// Check authorization
|
|
1096
|
+
if (!hasRole(user, ['platform_owner', 'org_owner'])) {
|
|
1097
|
+
throw new UnauthorizedError('Only org owners can switch providers');
|
|
1098
|
+
}
|
|
1099
|
+
```
|
|
1100
|
+
|
|
1101
|
+
### 3. Connection Testing
|
|
1102
|
+
|
|
1103
|
+
Test connectivity before saving config:
|
|
1104
|
+
|
|
1105
|
+
```typescript
|
|
1106
|
+
// Validate provider works
|
|
1107
|
+
const testResult = await testProviderConnection(newConfig);
|
|
1108
|
+
if (!testResult.success) {
|
|
1109
|
+
throw new ConnectionTestError(`Failed: ${testResult.error}`);
|
|
1110
|
+
}
|
|
1111
|
+
```
|
|
1112
|
+
|
|
1113
|
+
### 4. Audit Trail
|
|
1114
|
+
|
|
1115
|
+
Log all provider switches:
|
|
1116
|
+
|
|
1117
|
+
```typescript
|
|
1118
|
+
await db.insert('events', {
|
|
1119
|
+
type: 'settings_updated',
|
|
1120
|
+
actorId: userId,
|
|
1121
|
+
targetId: organizationId,
|
|
1122
|
+
metadata: {
|
|
1123
|
+
setting: 'backendProvider',
|
|
1124
|
+
oldValue: 'convex',
|
|
1125
|
+
newValue: 'wordpress',
|
|
1126
|
+
switchDuration: 28000 // ms
|
|
1127
|
+
}
|
|
1128
|
+
});
|
|
1129
|
+
```
|
|
1130
|
+
|
|
1131
|
+
---
|
|
1132
|
+
|
|
1133
|
+
## Monitoring & Debugging
|
|
1134
|
+
|
|
1135
|
+
### Provider Health Checks
|
|
1136
|
+
|
|
1137
|
+
Monitor backend connectivity:
|
|
1138
|
+
|
|
1139
|
+
```typescript
|
|
1140
|
+
export async function checkProviderHealth(
|
|
1141
|
+
provider: DataProvider
|
|
1142
|
+
): Promise<HealthStatus> {
|
|
1143
|
+
const start = Date.now();
|
|
1144
|
+
|
|
1145
|
+
try {
|
|
1146
|
+
// Test basic operation
|
|
1147
|
+
await Effect.runPromise(
|
|
1148
|
+
provider.things.list({ limit: 1 })
|
|
1149
|
+
);
|
|
1150
|
+
|
|
1151
|
+
return {
|
|
1152
|
+
status: 'healthy',
|
|
1153
|
+
responseTime: Date.now() - start,
|
|
1154
|
+
timestamp: Date.now()
|
|
1155
|
+
};
|
|
1156
|
+
} catch (error) {
|
|
1157
|
+
return {
|
|
1158
|
+
status: 'unhealthy',
|
|
1159
|
+
error: String(error),
|
|
1160
|
+
timestamp: Date.now()
|
|
1161
|
+
};
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
```
|
|
1165
|
+
|
|
1166
|
+
### Performance Monitoring
|
|
1167
|
+
|
|
1168
|
+
Track provider overhead:
|
|
1169
|
+
|
|
1170
|
+
```typescript
|
|
1171
|
+
// Add instrumentation
|
|
1172
|
+
const instrumentedProvider = {
|
|
1173
|
+
things: {
|
|
1174
|
+
get: (id) => {
|
|
1175
|
+
const start = performance.now();
|
|
1176
|
+
return provider.things.get(id).pipe(
|
|
1177
|
+
Effect.tap(() => {
|
|
1178
|
+
const duration = performance.now() - start;
|
|
1179
|
+
analytics.track('provider.operation', {
|
|
1180
|
+
provider: 'convex',
|
|
1181
|
+
operation: 'things.get',
|
|
1182
|
+
duration
|
|
1183
|
+
});
|
|
1184
|
+
})
|
|
1185
|
+
);
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
};
|
|
1189
|
+
```
|
|
1190
|
+
|
|
1191
|
+
---
|
|
1192
|
+
|
|
1193
|
+
## Future Enhancements
|
|
1194
|
+
|
|
1195
|
+
### Phase 2: Additional Providers
|
|
1196
|
+
|
|
1197
|
+
1. **Supabase** - PostgreSQL with real-time
|
|
1198
|
+
2. **Firebase** - Google's backend-as-a-service
|
|
1199
|
+
3. **Airtable** - Spreadsheet-like interface
|
|
1200
|
+
4. **Contentful** - Headless CMS
|
|
1201
|
+
5. **Strapi** - Open-source CMS
|
|
1202
|
+
|
|
1203
|
+
### Phase 3: Provider Features
|
|
1204
|
+
|
|
1205
|
+
1. **Cross-provider connections** - Connect Convex thing to WordPress post
|
|
1206
|
+
2. **Provider federation** - Use multiple backends simultaneously
|
|
1207
|
+
3. **Data synchronization** - Sync between providers
|
|
1208
|
+
4. **Provider marketplace** - Community-built providers
|
|
1209
|
+
5. **Hybrid storage** - Hot data in Convex, cold data in S3
|
|
1210
|
+
|
|
1211
|
+
### Phase 4: Advanced Features
|
|
1212
|
+
|
|
1213
|
+
1. **GraphQL federation** - Unified GraphQL API across providers
|
|
1214
|
+
2. **Event streaming** - Real-time events across all providers
|
|
1215
|
+
3. **Conflict resolution** - Handle concurrent updates
|
|
1216
|
+
4. **Schema evolution** - Migrate data between providers
|
|
1217
|
+
5. **Provider analytics** - Cost optimization recommendations
|
|
1218
|
+
|
|
1219
|
+
---
|
|
1220
|
+
|
|
1221
|
+
## Comparison: Traditional vs Backend-Agnostic
|
|
1222
|
+
|
|
1223
|
+
### Traditional Architecture
|
|
1224
|
+
|
|
1225
|
+
```
|
|
1226
|
+
Frontend → Convex SDK → Convex Database
|
|
1227
|
+
↓ (tightly coupled)
|
|
1228
|
+
Changes to switch backends:
|
|
1229
|
+
- Rewrite ALL components (100+ files)
|
|
1230
|
+
- Update ALL queries/mutations
|
|
1231
|
+
- Test EVERYTHING again
|
|
1232
|
+
- High risk, high cost
|
|
1233
|
+
```
|
|
1234
|
+
|
|
1235
|
+
### Backend-Agnostic Architecture
|
|
1236
|
+
|
|
1237
|
+
```
|
|
1238
|
+
Frontend → DataProvider Interface → [Convex | WordPress | Notion]
|
|
1239
|
+
↓ (loosely coupled)
|
|
1240
|
+
Changes to switch backends:
|
|
1241
|
+
- Update 1 env variable
|
|
1242
|
+
- Zero code changes
|
|
1243
|
+
- Same tests work
|
|
1244
|
+
- Low risk, zero cost
|
|
1245
|
+
```
|
|
1246
|
+
|
|
1247
|
+
---
|
|
1248
|
+
|
|
1249
|
+
## Key Takeaways
|
|
1250
|
+
|
|
1251
|
+
### ✅ What We Achieved
|
|
1252
|
+
|
|
1253
|
+
1. **True Backend Independence:** Components don't know what backend they're using
|
|
1254
|
+
2. **Zero Migration Cost:** Switch backends with one config change
|
|
1255
|
+
3. **Performance:** <10ms overhead per operation
|
|
1256
|
+
4. **Type Safety:** Compiler catches errors at build time
|
|
1257
|
+
5. **Developer Experience:** Clean, intuitive API
|
|
1258
|
+
6. **Multi-Tenant:** Different orgs can use different backends
|
|
1259
|
+
7. **Production Ready:** 110+ tests passing, TypeScript strict mode
|
|
1260
|
+
|
|
1261
|
+
### 🎯 Why This Matters
|
|
1262
|
+
|
|
1263
|
+
**For Developers:**
|
|
1264
|
+
- Write once, run anywhere
|
|
1265
|
+
- Test without backend (use mocks)
|
|
1266
|
+
- Clear separation of concerns
|
|
1267
|
+
- Future-proof architecture
|
|
1268
|
+
|
|
1269
|
+
**For Organizations:**
|
|
1270
|
+
- Choose best backend for needs
|
|
1271
|
+
- No vendor lock-in
|
|
1272
|
+
- Migrate when ready
|
|
1273
|
+
- Use existing infrastructure
|
|
1274
|
+
|
|
1275
|
+
**For Platform:**
|
|
1276
|
+
- Market expansion (WordPress users, Notion users, etc.)
|
|
1277
|
+
- Enterprise sales (use their database)
|
|
1278
|
+
- Competitive advantage (unique feature)
|
|
1279
|
+
- Proves ontology flexibility
|
|
1280
|
+
|
|
1281
|
+
---
|
|
1282
|
+
|
|
1283
|
+
## Getting Started
|
|
1284
|
+
|
|
1285
|
+
### 1. Install Dependencies
|
|
1286
|
+
|
|
1287
|
+
```bash
|
|
1288
|
+
cd frontend
|
|
1289
|
+
bun install
|
|
1290
|
+
```
|
|
1291
|
+
|
|
1292
|
+
### 2. Configure Backend
|
|
1293
|
+
|
|
1294
|
+
```bash
|
|
1295
|
+
# .env.local
|
|
1296
|
+
BACKEND_PROVIDER=convex
|
|
1297
|
+
PUBLIC_CONVEX_URL=https://your-deployment.convex.cloud
|
|
1298
|
+
```
|
|
1299
|
+
|
|
1300
|
+
### 3. Wrap App with Provider
|
|
1301
|
+
|
|
1302
|
+
```tsx
|
|
1303
|
+
// src/components/auth/YourPage.tsx
|
|
1304
|
+
import { AppProviders } from '@/components/providers/AppProviders';
|
|
1305
|
+
import { YourComponent } from './YourComponent';
|
|
1306
|
+
|
|
1307
|
+
export function YourPage() {
|
|
1308
|
+
return (
|
|
1309
|
+
<AppProviders>
|
|
1310
|
+
<YourComponent />
|
|
1311
|
+
</AppProviders>
|
|
1312
|
+
);
|
|
1313
|
+
}
|
|
1314
|
+
```
|
|
1315
|
+
|
|
1316
|
+
### 4. Use Hooks
|
|
1317
|
+
|
|
1318
|
+
```tsx
|
|
1319
|
+
// src/components/YourComponent.tsx
|
|
1320
|
+
import { useThings } from '@/hooks/useThings';
|
|
1321
|
+
|
|
1322
|
+
export function YourComponent() {
|
|
1323
|
+
const { data: courses } = useThings({ type: 'course' });
|
|
1324
|
+
|
|
1325
|
+
return (
|
|
1326
|
+
<div>
|
|
1327
|
+
{courses?.map(course => (
|
|
1328
|
+
<div key={course._id}>{course.name}</div>
|
|
1329
|
+
))}
|
|
1330
|
+
</div>
|
|
1331
|
+
);
|
|
1332
|
+
}
|
|
1333
|
+
```
|
|
1334
|
+
|
|
1335
|
+
### 5. Switch Backend (Optional)
|
|
1336
|
+
|
|
1337
|
+
```bash
|
|
1338
|
+
# Change to WordPress
|
|
1339
|
+
BACKEND_PROVIDER=wordpress
|
|
1340
|
+
WORDPRESS_URL=https://mysite.com/wp-json
|
|
1341
|
+
WORDPRESS_USERNAME=admin
|
|
1342
|
+
WORDPRESS_APP_PASSWORD=xxxx xxxx xxxx xxxx
|
|
1343
|
+
```
|
|
1344
|
+
|
|
1345
|
+
**No code changes needed!** 🎉
|
|
1346
|
+
|
|
1347
|
+
---
|
|
1348
|
+
|
|
1349
|
+
## Conclusion
|
|
1350
|
+
|
|
1351
|
+
The backend-agnostic architecture proves that the 6-dimension ontology is truly universal. Whether your data lives in Convex, WordPress, Notion, or any future database, the same components, hooks, and services work identically.
|
|
1352
|
+
|
|
1353
|
+
**This is not just an abstraction layer—it's a fundamental reimagining of how applications should be built.**
|
|
1354
|
+
|
|
1355
|
+
Organizations now have true freedom to choose their backend based on their needs, not the limitations of the frontend framework.
|
|
1356
|
+
|
|
1357
|
+
---
|
|
1358
|
+
|
|
1359
|
+
**Related Documentation:**
|
|
1360
|
+
- `one/knowledge/ontology.md` - 6-dimension ontology specification
|
|
1361
|
+
- `one/knowledge/provider-creation-guide.md` - How to build new providers
|
|
1362
|
+
- `one/things/features/2-1-dataprovider-interface.md` - DataProvider spec
|
|
1363
|
+
- `one/things/features/2-3-effectts-services.md` - Service layer patterns
|
|
1364
|
+
- `frontend/AGENTS.md` - Quick reference for development
|
|
1365
|
+
|
|
1366
|
+
**Implementation Status:** ✅ **Production Ready** (Plan 2 Complete - 7/7 features)
|