@onebuffalolabs/herd-sync 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 One Buffalo Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,108 @@
1
- # Temporary Holding Version
1
+ # @onebuffalolabs/herd-sync
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Core local-first state and database synchronization engine for HerdSync. Provides dynamic client-side PouchDB initialization, reactive React hooks, bi-directional CouchDB synchronization, and pluggable conflict resolution.
4
+
5
+ ---
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pnpm add @onebuffalolabs/herd-sync
11
+
12
+ ```
13
+
14
+ ### Static Next.js Configuration (`output: 'export'`)
15
+
16
+ When using HerdSync inside static Next.js applications, configure `next.config.mjs` to transpile the package and stub node-specific server fallbacks:
17
+
18
+ ```javascript
19
+ /** @type {import('next').NextConfig} */
20
+ const nextConfig = {
21
+ output: "export",
22
+ transpilePackages: ["@onebuffalolabs/herd-sync"],
23
+ images: {
24
+ unoptimized: true
25
+ },
26
+ webpack: (config, { isServer }) => {
27
+ if (isServer) {
28
+ config.resolve.fallback = {
29
+ ...config.resolve.fallback,
30
+ events: false,
31
+ buffer: false,
32
+ stream: false
33
+ };
34
+ }
35
+ return config;
36
+ }
37
+ };
38
+
39
+ export default nextConfig;
40
+ ```
41
+
42
+ ---
43
+
44
+ ## Components & Hooks
45
+
46
+ ### `HerdSyncProvider`
47
+
48
+ Initializes the browser database and orchestrates background replication tasks.
49
+
50
+ ```tsx
51
+ import { HerdSyncProvider } from "@onebuffalolabs/herd-sync";
52
+
53
+ <HerdSyncProvider
54
+ live="{true}"
55
+ name="my_local_db"
56
+ remoteUrl="[https://couchdb.example.com/my_remote_db](https://couchdb.example.com/my_remote_db)"
57
+ retry="{true}"
58
+ >
59
+ {children}
60
+ </HerdSyncProvider>;
61
+ ```
62
+
63
+ ### `useHerdDoc(id, initialDoc?)`
64
+
65
+ Binds a single document to reactive React state. Subscribes to live local and remote database changes automatically.
66
+
67
+ ```tsx
68
+ const { doc, loading, error, save, remove } = useHerdDoc<TaskDoc>("task_123", {
69
+ title: "Default Title",
70
+ completed: false
71
+ });
72
+ ```
73
+
74
+ - `doc`: Current document object (`T | null`).
75
+ - `loading`: `true` while the document is initially being resolved from local storage.
76
+ - `error`: Non-null if an IndexedDB read/write failure occurs.
77
+ - `save(patch)`: Persists updates, generates an updated ISO `updatedAt` timestamp, and writes the current `_rev`.
78
+ - `remove()`: Marks the document as deleted and purges it locally.
79
+
80
+ ### Conflict Resolution
81
+
82
+ Resolve divergent PouchDB revision branches using `resolveDocConflicts` with built-in strategies (`resolveLWW`, `createArrayMergeResolver`) or custom domain handlers:
83
+
84
+ ```typescript
85
+ import { resolveDocConflicts, resolveLWW } from "@onebuffalolabs/herd-sync";
86
+
87
+ await resolveDocConflicts(db, "task_123", {
88
+ resolver: resolveLWW
89
+ });
90
+ ```
91
+
92
+ ---
93
+
94
+ ## Document Requirements
95
+
96
+ All documents must adhere to `HerdDoc`:
97
+
98
+ ```typescript
99
+ export interface HerdDoc {
100
+ _id: string;
101
+ _rev?: string;
102
+ _deleted?: boolean;
103
+ updatedAt?: string;
104
+ [key: string]: unknown;
105
+ }
106
+ ```
107
+
108
+ > **Important:** Do not prefix custom fields with leading underscores (e.g., use `updatedAt`, not `_updatedAt`). CouchDB reserves leading underscores for database metadata.
@@ -0,0 +1,153 @@
1
+ import React from 'react';
2
+
3
+ /**
4
+ * Shape of the dynamic PouchDB constructor function.
5
+ */
6
+ type PouchDBCtor<T extends HerdDoc> = new (name?: string, options?: PouchDB.Configuration.DatabaseConfiguration) => PouchDB.Database<T>;
7
+ /**
8
+ * Lifecycle connection state for the sync adapter.
9
+ */
10
+ type SyncConnectionState = "uninitialized" | "idle" | "connecting" | "connected" | "syncing" | "paused" | "error" | "denied";
11
+ /**
12
+ * Base document shape managed by HerdSync.
13
+ */
14
+ interface HerdDoc {
15
+ _id: string;
16
+ _rev?: string;
17
+ _deleted?: boolean;
18
+ updatedAt?: string;
19
+ [key: string]: unknown;
20
+ }
21
+ /**
22
+ * Authentication parameters for connecting to a remote CouchDB or Cloudant instance.
23
+ */
24
+ interface RemoteAuthConfig {
25
+ username?: string;
26
+ password?: string;
27
+ bearerToken?: string;
28
+ }
29
+ /**
30
+ * Configuration options for initializing the CouchDB synchronization adapter.
31
+ */
32
+ interface CouchDBAdapterOptions {
33
+ remoteUrl?: string;
34
+ auth?: RemoteAuthConfig;
35
+ live?: boolean;
36
+ retry?: boolean;
37
+ backOffMultiplier?: number;
38
+ initialBackOffMs?: number;
39
+ maxBackOffMs?: number;
40
+ }
41
+ /**
42
+ * Live status payload emitted during synchronization events.
43
+ */
44
+ interface HerdSyncStatus {
45
+ state: SyncConnectionState;
46
+ lastSyncedAt: string | null;
47
+ pendingPushes: number;
48
+ error: string | null;
49
+ }
50
+ /**
51
+ * Contract implemented by HerdSync storage adapters.
52
+ */
53
+ interface SyncAdapter {
54
+ start(): void;
55
+ stop(): Promise<void>;
56
+ getStatus(): HerdSyncStatus;
57
+ subscribe(callback: (status: HerdSyncStatus) => void): () => void;
58
+ }
59
+ /**
60
+ * Signature for pluggable conflict resolution functions.
61
+ */
62
+ type ConflictResolver<T extends HerdDoc = HerdDoc> = (localDoc: T, conflictingDoc: T) => T | Promise<T>;
63
+ /**
64
+ * Result report after resolving a document's conflicting revisions.
65
+ */
66
+ interface ConflictResolutionResult<T extends HerdDoc = HerdDoc> {
67
+ resolvedDoc: T;
68
+ purgedRevisions: string[];
69
+ }
70
+ /**
71
+ * Options for configuring the conflict resolution runner.
72
+ */
73
+ interface ConflictResolutionOptions<T extends HerdDoc = HerdDoc> {
74
+ resolver?: ConflictResolver<T>;
75
+ timeoutMs?: number;
76
+ }
77
+
78
+ /**
79
+ * PouchDB-to-CouchDB synchronization adapter supporting bi-directional replication and auto-retry backoff.
80
+ */
81
+ declare class CouchDBAdapter<T extends HerdDoc = HerdDoc> implements SyncAdapter {
82
+ private localDb;
83
+ private remoteDb;
84
+ private syncHandler;
85
+ private options;
86
+ private status;
87
+ private listeners;
88
+ constructor(localDb: PouchDB.Database<T>, options?: CouchDBAdapterOptions);
89
+ getStatus(): HerdSyncStatus;
90
+ subscribe(callback: (status: HerdSyncStatus) => void): () => void;
91
+ private updateStatus;
92
+ start(): Promise<void>;
93
+ stop(): Promise<void>;
94
+ }
95
+
96
+ /**
97
+ * Last-Write-Wins (LWW) conflict strategy.
98
+ * Compares updatedAt timestamps and selects the newest revision.
99
+ * If timestamps match, deterministically compares _rev strings.
100
+ */
101
+ declare function resolveLWW<T extends HerdDoc>(localDoc: T, conflictingDoc: T): T;
102
+ /**
103
+ * Array merge conflict strategy factory.
104
+ * Concatenates and deduplicates array fields specified by arrayKeys while delegating other fields to LWW.
105
+ */
106
+ declare function createArrayMergeResolver<T extends HerdDoc>(arrayKeys: (keyof T)[]): ConflictResolver<T>;
107
+
108
+ /**
109
+ * Inspects a document for divergent revision branches, runs the configured resolver,
110
+ * writes the winning revision, and marks losing branches as deleted.
111
+ */
112
+ declare function resolveDocConflicts<T extends HerdDoc>(db: PouchDB.Database<T>, docId: string, options?: ConflictResolutionOptions<T>): Promise<ConflictResolutionResult<T> | null>;
113
+
114
+ /**
115
+ * React Context value shape for HerdSync.
116
+ */
117
+ interface HerdSyncContextValue<T extends HerdDoc = HerdDoc> {
118
+ db: PouchDB.Database<T> | null;
119
+ status: HerdSyncStatus;
120
+ adapter: CouchDBAdapter<T> | null;
121
+ }
122
+ /**
123
+ * Props for the HerdSyncProvider component.
124
+ */
125
+ interface HerdSyncProviderProps extends CouchDBAdapterOptions {
126
+ name: string;
127
+ children: React.ReactNode;
128
+ }
129
+ /**
130
+ * Top-level provider establishing the local PouchDB instance and remote sync adapter lifecycle.
131
+ */
132
+ declare function HerdSyncProvider<T extends HerdDoc = HerdDoc>({ name, remoteUrl, auth, live, retry, backOffMultiplier, initialBackOffMs, maxBackOffMs, children }: HerdSyncProviderProps): React.JSX.Element;
133
+ /**
134
+ * Hook to access the current database instance and replication status.
135
+ */
136
+ declare function useHerdSync<T extends HerdDoc = HerdDoc>(): HerdSyncContextValue<T>;
137
+
138
+ /**
139
+ * Return signature of the useHerdDoc reactive hook.
140
+ */
141
+ interface UseHerdDocReturn<T extends HerdDoc> {
142
+ doc: T | null;
143
+ loading: boolean;
144
+ error: Error | null;
145
+ save: (patch: Record<string, unknown>) => Promise<T>;
146
+ remove: () => Promise<void>;
147
+ }
148
+ /**
149
+ * Reactive document hook keeping local state synchronized with PouchDB changes.
150
+ */
151
+ declare function useHerdDoc<T extends HerdDoc>(id: string, initialDoc?: Partial<T>): UseHerdDocReturn<T>;
152
+
153
+ export { type ConflictResolutionOptions, type ConflictResolutionResult, type ConflictResolver, CouchDBAdapter, type CouchDBAdapterOptions, type HerdDoc, type HerdSyncContextValue, HerdSyncProvider, type HerdSyncProviderProps, type HerdSyncStatus, type PouchDBCtor, type RemoteAuthConfig, type SyncAdapter, type SyncConnectionState, type UseHerdDocReturn, createArrayMergeResolver, resolveDocConflicts, resolveLWW, useHerdDoc, useHerdSync };
@@ -0,0 +1,153 @@
1
+ import React from 'react';
2
+
3
+ /**
4
+ * Shape of the dynamic PouchDB constructor function.
5
+ */
6
+ type PouchDBCtor<T extends HerdDoc> = new (name?: string, options?: PouchDB.Configuration.DatabaseConfiguration) => PouchDB.Database<T>;
7
+ /**
8
+ * Lifecycle connection state for the sync adapter.
9
+ */
10
+ type SyncConnectionState = "uninitialized" | "idle" | "connecting" | "connected" | "syncing" | "paused" | "error" | "denied";
11
+ /**
12
+ * Base document shape managed by HerdSync.
13
+ */
14
+ interface HerdDoc {
15
+ _id: string;
16
+ _rev?: string;
17
+ _deleted?: boolean;
18
+ updatedAt?: string;
19
+ [key: string]: unknown;
20
+ }
21
+ /**
22
+ * Authentication parameters for connecting to a remote CouchDB or Cloudant instance.
23
+ */
24
+ interface RemoteAuthConfig {
25
+ username?: string;
26
+ password?: string;
27
+ bearerToken?: string;
28
+ }
29
+ /**
30
+ * Configuration options for initializing the CouchDB synchronization adapter.
31
+ */
32
+ interface CouchDBAdapterOptions {
33
+ remoteUrl?: string;
34
+ auth?: RemoteAuthConfig;
35
+ live?: boolean;
36
+ retry?: boolean;
37
+ backOffMultiplier?: number;
38
+ initialBackOffMs?: number;
39
+ maxBackOffMs?: number;
40
+ }
41
+ /**
42
+ * Live status payload emitted during synchronization events.
43
+ */
44
+ interface HerdSyncStatus {
45
+ state: SyncConnectionState;
46
+ lastSyncedAt: string | null;
47
+ pendingPushes: number;
48
+ error: string | null;
49
+ }
50
+ /**
51
+ * Contract implemented by HerdSync storage adapters.
52
+ */
53
+ interface SyncAdapter {
54
+ start(): void;
55
+ stop(): Promise<void>;
56
+ getStatus(): HerdSyncStatus;
57
+ subscribe(callback: (status: HerdSyncStatus) => void): () => void;
58
+ }
59
+ /**
60
+ * Signature for pluggable conflict resolution functions.
61
+ */
62
+ type ConflictResolver<T extends HerdDoc = HerdDoc> = (localDoc: T, conflictingDoc: T) => T | Promise<T>;
63
+ /**
64
+ * Result report after resolving a document's conflicting revisions.
65
+ */
66
+ interface ConflictResolutionResult<T extends HerdDoc = HerdDoc> {
67
+ resolvedDoc: T;
68
+ purgedRevisions: string[];
69
+ }
70
+ /**
71
+ * Options for configuring the conflict resolution runner.
72
+ */
73
+ interface ConflictResolutionOptions<T extends HerdDoc = HerdDoc> {
74
+ resolver?: ConflictResolver<T>;
75
+ timeoutMs?: number;
76
+ }
77
+
78
+ /**
79
+ * PouchDB-to-CouchDB synchronization adapter supporting bi-directional replication and auto-retry backoff.
80
+ */
81
+ declare class CouchDBAdapter<T extends HerdDoc = HerdDoc> implements SyncAdapter {
82
+ private localDb;
83
+ private remoteDb;
84
+ private syncHandler;
85
+ private options;
86
+ private status;
87
+ private listeners;
88
+ constructor(localDb: PouchDB.Database<T>, options?: CouchDBAdapterOptions);
89
+ getStatus(): HerdSyncStatus;
90
+ subscribe(callback: (status: HerdSyncStatus) => void): () => void;
91
+ private updateStatus;
92
+ start(): Promise<void>;
93
+ stop(): Promise<void>;
94
+ }
95
+
96
+ /**
97
+ * Last-Write-Wins (LWW) conflict strategy.
98
+ * Compares updatedAt timestamps and selects the newest revision.
99
+ * If timestamps match, deterministically compares _rev strings.
100
+ */
101
+ declare function resolveLWW<T extends HerdDoc>(localDoc: T, conflictingDoc: T): T;
102
+ /**
103
+ * Array merge conflict strategy factory.
104
+ * Concatenates and deduplicates array fields specified by arrayKeys while delegating other fields to LWW.
105
+ */
106
+ declare function createArrayMergeResolver<T extends HerdDoc>(arrayKeys: (keyof T)[]): ConflictResolver<T>;
107
+
108
+ /**
109
+ * Inspects a document for divergent revision branches, runs the configured resolver,
110
+ * writes the winning revision, and marks losing branches as deleted.
111
+ */
112
+ declare function resolveDocConflicts<T extends HerdDoc>(db: PouchDB.Database<T>, docId: string, options?: ConflictResolutionOptions<T>): Promise<ConflictResolutionResult<T> | null>;
113
+
114
+ /**
115
+ * React Context value shape for HerdSync.
116
+ */
117
+ interface HerdSyncContextValue<T extends HerdDoc = HerdDoc> {
118
+ db: PouchDB.Database<T> | null;
119
+ status: HerdSyncStatus;
120
+ adapter: CouchDBAdapter<T> | null;
121
+ }
122
+ /**
123
+ * Props for the HerdSyncProvider component.
124
+ */
125
+ interface HerdSyncProviderProps extends CouchDBAdapterOptions {
126
+ name: string;
127
+ children: React.ReactNode;
128
+ }
129
+ /**
130
+ * Top-level provider establishing the local PouchDB instance and remote sync adapter lifecycle.
131
+ */
132
+ declare function HerdSyncProvider<T extends HerdDoc = HerdDoc>({ name, remoteUrl, auth, live, retry, backOffMultiplier, initialBackOffMs, maxBackOffMs, children }: HerdSyncProviderProps): React.JSX.Element;
133
+ /**
134
+ * Hook to access the current database instance and replication status.
135
+ */
136
+ declare function useHerdSync<T extends HerdDoc = HerdDoc>(): HerdSyncContextValue<T>;
137
+
138
+ /**
139
+ * Return signature of the useHerdDoc reactive hook.
140
+ */
141
+ interface UseHerdDocReturn<T extends HerdDoc> {
142
+ doc: T | null;
143
+ loading: boolean;
144
+ error: Error | null;
145
+ save: (patch: Record<string, unknown>) => Promise<T>;
146
+ remove: () => Promise<void>;
147
+ }
148
+ /**
149
+ * Reactive document hook keeping local state synchronized with PouchDB changes.
150
+ */
151
+ declare function useHerdDoc<T extends HerdDoc>(id: string, initialDoc?: Partial<T>): UseHerdDocReturn<T>;
152
+
153
+ export { type ConflictResolutionOptions, type ConflictResolutionResult, type ConflictResolver, CouchDBAdapter, type CouchDBAdapterOptions, type HerdDoc, type HerdSyncContextValue, HerdSyncProvider, type HerdSyncProviderProps, type HerdSyncStatus, type PouchDBCtor, type RemoteAuthConfig, type SyncAdapter, type SyncConnectionState, type UseHerdDocReturn, createArrayMergeResolver, resolveDocConflicts, resolveLWW, useHerdDoc, useHerdSync };