@live-state/sync 0.0.1-alpha.1 → 0.0.1-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/dist/chunk-EK7ODJWE.js +1 -0
- package/dist/chunk-NIWX45UD.js +1 -0
- package/dist/client.d.ts +3 -283
- package/dist/client.js +1 -1
- package/dist/fetch-client.d.ts +17 -0
- package/dist/fetch-client.js +1 -0
- package/dist/index-NDRWVwih.d.ts +343 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +209 -2
- package/dist/index.d.ts +209 -2
- package/dist/index.js +1 -1
- package/dist/server.cjs +2 -1
- package/dist/server.d.cts +186 -52
- package/dist/server.d.ts +186 -52
- package/dist/server.js +2 -1
- package/package.json +22 -15
- package/dist/index-sSVirsfN.d.cts +0 -458
- package/dist/index-sSVirsfN.d.ts +0 -458
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Pedro Costa
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var g=Object.create;var f=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var i=Object.getOwnPropertyNames;var j=Object.getPrototypeOf,k=Object.prototype.hasOwnProperty;var m=(b,a)=>()=>(a||b((a={exports:{}}).exports,a),a.exports);var l=(b,a,c,e)=>{if(a&&typeof a=="object"||typeof a=="function")for(let d of i(a))!k.call(b,d)&&d!==c&&f(b,d,{get:()=>a[d],enumerable:!(e=h(a,d))||e.enumerable});return b};var n=(b,a,c)=>(c=b!=null?g(j(b)):{},l(a||!b||!b.__esModule?f(c,"default",{value:b,enumerable:true}):c,b));export{m as a,n as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var R="0123456789ABCDEFGHJKMNPQRSTVWXYZ";var c;(function(e){e.Base32IncorrectEncoding="B32_ENC_INVALID",e.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",e.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",e.EncodeTimeNegative="ENC_TIME_NEG",e.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",e.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",e.PRNGDetectFailure="PRNG_DETECT",e.ULIDInvalid="ULID_INVALID",e.Unexpected="UNEXPECTED",e.UUIDInvalid="UUID_INVALID";})(c||(c={}));var l=class extends Error{constructor(t,n){super(`${n} (${t})`),this.name="ULIDError",this.code=t;}};function L(e){let t=Math.floor(e()*32);return t===32&&(t=31),R.charAt(t)}function I(e){let t=M(),n=t&&(t.crypto||t.msCrypto)||null;if(typeof(n==null?void 0:n.getRandomValues)=="function")return ()=>{let i=new Uint8Array(1);return n.getRandomValues(i),i[0]/255};if(typeof(n==null?void 0:n.randomBytes)=="function")return ()=>n.randomBytes(1).readUInt8()/255;throw new l(c.PRNGDetectFailure,"Failed to find a reliable PRNG")}function M(){return A()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}function E(e,t){let n="";for(;e>0;e--)n=L(t)+n;return n}function _(e,t=10){if(isNaN(e))throw new l(c.EncodeTimeValueMalformed,`Time must be a number: ${e}`);if(e>0xffffffffffff)throw new l(c.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${0xffffffffffff}: ${e}`);if(e<0)throw new l(c.EncodeTimeNegative,`Time must be positive: ${e}`);if(Number.isInteger(e)===false)throw new l(c.EncodeTimeValueMalformed,`Time must be an integer: ${e}`);let n,i="";for(let a=t;a>0;a--)n=e%32,i=R.charAt(n)+i,e=(e-n)/32;return i}function A(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function x(e,t){let n=I(),i=Date.now();return _(i,10)+E(16,n)}var S=()=>x().toLowerCase(),j=(e,t)=>typeof e=="function"?e(t):e;var b=e=>{if(e)return Array.isArray(e.value)?e.value.map(t=>b(t)):typeof e.value!="object"?e.value:Object.fromEntries(Object.entries(e.value).map(([t,n])=>[t,b(n)]))};var w=(e,t,n=[])=>new Proxy(e,{get:(i,a)=>{var y,h;if(a==="__isProxy__")return true;let r=(y=t.get)==null?void 0:y.call(t,i,[...n,a]);if(r!==void 0)return r;let o=i,s=a;return (h=o[s])!=null&&h.__isProxy__||(o[s]=w(typeof o[s]=="object"?o[s]:function(){},t,[...n,a])),o[s]},apply:(i,a,r)=>{var o;return (o=t.apply)==null?void 0:o.call(t,i,n,r)}});export{S as a,j as b,b as c,w as d};
|
package/dist/client.d.ts
CHANGED
|
@@ -1,283 +1,3 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
type MutationType = "set";
|
|
5
|
-
declare abstract class LiveType<Value = any, Meta extends LiveTypeMeta = LiveTypeMeta, EncodeInput = Partial<Value> | Value, DecodeInput = {
|
|
6
|
-
value: Value;
|
|
7
|
-
_meta: keyof Meta extends never ? never : Meta;
|
|
8
|
-
}> {
|
|
9
|
-
readonly _value: Value;
|
|
10
|
-
readonly _meta: Meta;
|
|
11
|
-
readonly _encodeInput: EncodeInput;
|
|
12
|
-
readonly _decodeInput: DecodeInput;
|
|
13
|
-
abstract encodeMutation(mutationType: MutationType, input: EncodeInput, timestamp: string): DecodeInput;
|
|
14
|
-
/**
|
|
15
|
-
* Merges the materialized shape with the encoded mutation
|
|
16
|
-
* @param mutationType The type of mutation
|
|
17
|
-
* @param encodedMutation The encoded mutation
|
|
18
|
-
* @param materializedShape The materialized shape
|
|
19
|
-
* @returns A tuple of the new materialized shape and the accepted diff
|
|
20
|
-
*/
|
|
21
|
-
abstract mergeMutation(mutationType: MutationType, encodedMutation: DecodeInput, materializedShape?: MaterializedLiveType<LiveType<Value, Meta>>): [MaterializedLiveType<LiveType<Value, Meta>>, DecodeInput | null];
|
|
22
|
-
}
|
|
23
|
-
type LiveTypeAny = LiveType<any, LiveTypeMeta, any, any>;
|
|
24
|
-
type InferLiveType<T extends LiveTypeAny> = T["_value"] extends Record<string, LiveTypeAny> ? {
|
|
25
|
-
[K in keyof T["_value"]]: InferLiveType<T["_value"][K]>;
|
|
26
|
-
} : T["_value"];
|
|
27
|
-
type InferIndex<T extends LiveTypeAny> = string;
|
|
28
|
-
|
|
29
|
-
declare class OptionalLiveType<T extends LiveTypeAny> extends LiveType<T["_value"] | undefined, T["_meta"], T["_encodeInput"], T["_decodeInput"]> {
|
|
30
|
-
encodeMutation(mutationType: MutationType, input: T["_value"] | undefined, timestamp: string): string;
|
|
31
|
-
mergeMutation(mutationType: MutationType, encodedMutation: T["_decodeInput"], materializedShape?: MaterializedLiveType<LiveType<T["_value"] | undefined, T["_meta"], T["_value"] | Partial<T["_value"] | undefined>, T["_decodeInput"]>> | undefined): [
|
|
32
|
-
MaterializedLiveType<LiveType<T["_value"] | undefined, T["_meta"], T["_value"] | Partial<T["_value"] | undefined>, T["_decodeInput"]>>,
|
|
33
|
-
T["_decodeInput"] | null
|
|
34
|
-
];
|
|
35
|
-
}
|
|
36
|
-
type LiveAtomicTypeMeta = {
|
|
37
|
-
timestamp: string;
|
|
38
|
-
} & LiveTypeMeta;
|
|
39
|
-
declare abstract class LiveAtomicType<Value = any, Meta extends LiveAtomicTypeMeta = LiveAtomicTypeMeta, EncodeInput = Partial<Value> | Value> extends LiveType<Value, Meta, EncodeInput> {
|
|
40
|
-
constructor();
|
|
41
|
-
optional(): OptionalLiveType<this>;
|
|
42
|
-
}
|
|
43
|
-
declare class LiveString extends LiveAtomicType<string> {
|
|
44
|
-
encodeMutation(mutationType: MutationType, input: Partial<string>, timestamp: string): {
|
|
45
|
-
value: string;
|
|
46
|
-
_meta: {
|
|
47
|
-
timestamp: string;
|
|
48
|
-
};
|
|
49
|
-
};
|
|
50
|
-
mergeMutation(mutationType: MutationType, encodedMutation: {
|
|
51
|
-
value: string;
|
|
52
|
-
_meta: {
|
|
53
|
-
timestamp: string;
|
|
54
|
-
};
|
|
55
|
-
}, materializedShape?: MaterializedLiveType<LiveString>): [
|
|
56
|
-
MaterializedLiveType<LiveString>,
|
|
57
|
-
{
|
|
58
|
-
value: string;
|
|
59
|
-
_meta: {
|
|
60
|
-
timestamp: string;
|
|
61
|
-
};
|
|
62
|
-
} | null
|
|
63
|
-
];
|
|
64
|
-
static create(): LiveString;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
type InferLiveObjectWithoutRelations<T extends LiveObjectAny> = {
|
|
68
|
-
[K in keyof T["fields"]]: InferLiveType<T["fields"][K]>;
|
|
69
|
-
};
|
|
70
|
-
type InferLiveObject<T extends LiveObjectAny> = InferLiveObjectWithoutRelations<T> & {
|
|
71
|
-
[K in keyof T["relations"]]: T["relations"][K]["type"] extends "one" ? InferLiveObject<T["relations"][K]["entity"]> : InferLiveObject<T["relations"][K]["entity"]>[];
|
|
72
|
-
};
|
|
73
|
-
type InferRelationalColumns<T extends Record<string, RelationAny>> = {
|
|
74
|
-
[K in keyof T as T[K] extends Relation<any, any, any, infer ColumnName, any, any> ? ColumnName extends string ? ColumnName : never : never]: T[K]["type"] extends "one" ? T[K] extends Relation<infer Entity, any, any, any, any, any> ? T[K]["required"] extends true ? InferIndex<Entity> : InferIndex<Entity> | undefined : never : never;
|
|
75
|
-
};
|
|
76
|
-
type InferLiveObjectWithRelationalIds<T extends LiveObjectAny> = keyof T["relations"] extends string ? InferLiveObjectWithoutRelations<T> & InferRelationalColumns<T["relations"]> : InferLiveObjectWithoutRelations<T>;
|
|
77
|
-
type LiveObjectMutationInput<TSchema extends LiveObjectAny> = InferLiveObjectWithRelationalIds<TSchema>;
|
|
78
|
-
declare class LiveObject<TName extends string, TSchema extends Record<string, LiveTypeAny>, TRelations extends Record<string, RelationAny>> extends LiveType<TSchema, LiveTypeMeta, LiveObjectMutationInput<any>, Record<string, MaterializedLiveType<LiveTypeAny>>> {
|
|
79
|
-
readonly name: TName;
|
|
80
|
-
readonly fields: TSchema;
|
|
81
|
-
readonly relations: TRelations;
|
|
82
|
-
constructor(name: TName, fields: TSchema, relations?: TRelations);
|
|
83
|
-
encodeMutation(_mutationType: MutationType, input: LiveObjectMutationInput<this>, timestamp: string): Record<string, any>;
|
|
84
|
-
mergeMutation(mutationType: MutationType, encodedMutations: Record<string, MaterializedLiveType<LiveTypeAny>>, materializedShape?: MaterializedLiveType<this> | undefined): [MaterializedLiveType<this>, Record<string, any> | null];
|
|
85
|
-
setRelations<TRelations extends Record<string, RelationAny>>(relations: TRelations): LiveObject<this["name"], this["fields"], TRelations>;
|
|
86
|
-
static create<TName extends string, TSchema extends Record<string, LiveTypeAny>>(name: TName, schema: TSchema): LiveObject<TName, TSchema, never>;
|
|
87
|
-
}
|
|
88
|
-
type LiveObjectAny = LiveObject<string, Record<string, LiveTypeAny>, any>;
|
|
89
|
-
declare class Relation<TEntity extends LiveObjectAny, TSourceEntity extends LiveObjectAny, TType extends "one" | "many", TRelationalColumn extends keyof TSourceEntity["fields"], TForeignColumn extends keyof TEntity["fields"], TRequired extends boolean> extends LiveType<InferIndex<TEntity>, {
|
|
90
|
-
timestamp: string;
|
|
91
|
-
} & LiveTypeMeta> {
|
|
92
|
-
readonly entity: TEntity;
|
|
93
|
-
readonly type: TType;
|
|
94
|
-
readonly required: TRequired;
|
|
95
|
-
readonly relationalColumn?: TRelationalColumn;
|
|
96
|
-
readonly foreignColumn?: TForeignColumn;
|
|
97
|
-
readonly sourceEntity: TSourceEntity;
|
|
98
|
-
private constructor();
|
|
99
|
-
encodeMutation(mutationType: MutationType, input: string, timestamp: string): {
|
|
100
|
-
value: string;
|
|
101
|
-
_meta: {
|
|
102
|
-
timestamp: string;
|
|
103
|
-
};
|
|
104
|
-
};
|
|
105
|
-
mergeMutation(mutationType: MutationType, encodedMutation: {
|
|
106
|
-
value: string;
|
|
107
|
-
_meta: {
|
|
108
|
-
timestamp: string;
|
|
109
|
-
};
|
|
110
|
-
}, materializedShape?: MaterializedLiveType<LiveString> | undefined): [
|
|
111
|
-
MaterializedLiveType<LiveString>,
|
|
112
|
-
{
|
|
113
|
-
value: string;
|
|
114
|
-
_meta: {
|
|
115
|
-
timestamp: string;
|
|
116
|
-
};
|
|
117
|
-
} | null
|
|
118
|
-
];
|
|
119
|
-
static createOneFactory<TOriginEntity extends LiveObjectAny>(): <TEntity extends LiveObjectAny, TColumn extends keyof TOriginEntity["fields"], TRequired extends boolean = false>(entity: TEntity, column: TColumn, required?: TRequired) => Relation<TEntity, TOriginEntity, "one", TColumn, never, TRequired>;
|
|
120
|
-
static createManyFactory<TOriginEntity extends LiveObjectAny>(): <TEntity extends LiveObjectAny, TColumn extends keyof TEntity["fields"], TRequired extends boolean = false>(entity: TEntity, foreignColumn: TColumn, required?: TRequired) => Relation<TEntity, TOriginEntity, "many", never, TColumn, TRequired>;
|
|
121
|
-
}
|
|
122
|
-
type RelationAny = Relation<LiveObjectAny, LiveObjectAny, any, any, any, any>;
|
|
123
|
-
type MaterializedLiveType<T extends LiveTypeAny> = keyof T["_meta"] extends never ? {
|
|
124
|
-
value: T["_value"] extends Record<string, LiveTypeAny> ? {
|
|
125
|
-
[K in keyof T["_value"]]: MaterializedLiveType<T["_value"][K]>;
|
|
126
|
-
} : T["_value"];
|
|
127
|
-
} : {
|
|
128
|
-
value: T["_value"] extends Record<string, LiveTypeAny> ? {
|
|
129
|
-
[K in keyof T["_value"]]: MaterializedLiveType<T["_value"][K]>;
|
|
130
|
-
} : T["_value"];
|
|
131
|
-
_meta: T["_meta"];
|
|
132
|
-
};
|
|
133
|
-
type MaterializedLiveObject<T extends LiveObjectAny> = MaterializedLiveType<T> & {
|
|
134
|
-
[K in keyof T["relations"]]: InferIndex<T["relations"][K]["entity"]>;
|
|
135
|
-
};
|
|
136
|
-
type ExtractObjectValues<T> = T[keyof T];
|
|
137
|
-
type RelationsDecl<TObjectName extends string = string, TRelations extends Record<string, RelationAny> = Record<string, RelationAny>> = {
|
|
138
|
-
$type: "relations";
|
|
139
|
-
objectName: TObjectName;
|
|
140
|
-
relations: TRelations;
|
|
141
|
-
};
|
|
142
|
-
type ParseRelationsFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
|
|
143
|
-
[K in keyof TRawSchema]: TRawSchema[K] extends RelationsDecl<infer TObjectName_, any> ? TObjectName_ extends TObjectName ? {
|
|
144
|
-
[K2 in keyof TRawSchema[K]["relations"]]: Relation<ParseObjectFromSchema<TRawSchema, TRawSchema[K]["relations"][K2]["entity"]["name"]>, TRawSchema[K]["relations"][K2]["sourceEntity"], TRawSchema[K]["relations"][K2]["type"], Exclude<TRawSchema[K]["relations"][K2]["relationalColumn"], undefined>, Exclude<TRawSchema[K]["relations"][K2]["foreignColumn"], undefined>, TRawSchema[K]["relations"][K2]["required"]>;
|
|
145
|
-
} : never : never;
|
|
146
|
-
}>;
|
|
147
|
-
type ParseObjectFromSchema<TRawSchema extends RawSchema, TObjectName extends string> = ExtractObjectValues<{
|
|
148
|
-
[K in keyof TRawSchema]: TRawSchema[K] extends LiveObjectAny ? TRawSchema[K]["name"] extends TObjectName ? LiveObject<TRawSchema[K]["name"], TRawSchema[K]["fields"], ParseRelationsFromSchema<TRawSchema, TRawSchema[K]["name"]>> : never : never;
|
|
149
|
-
}>;
|
|
150
|
-
type RawSchema = Record<string, LiveObjectAny | RelationsDecl>;
|
|
151
|
-
type Schema<TRawSchema extends RawSchema> = {
|
|
152
|
-
[K in keyof TRawSchema as TRawSchema[K] extends LiveObjectAny ? TRawSchema[K]["name"] : never]: TRawSchema[K] extends LiveObjectAny ? ParseObjectFromSchema<TRawSchema, TRawSchema[K]["name"]> : never;
|
|
153
|
-
};
|
|
154
|
-
|
|
155
|
-
declare abstract class Storage {
|
|
156
|
-
abstract updateSchema(opts: Schema<any>): Promise<void>;
|
|
157
|
-
abstract findById<T extends LiveObjectAny>(resourceName: string, id: string): Promise<MaterializedLiveType<T> | undefined>;
|
|
158
|
-
abstract find<T extends LiveObjectAny>(resourceName: string, where?: Record<string, any>): Promise<Record<string, MaterializedLiveType<T>>>;
|
|
159
|
-
abstract upsert<T extends LiveObjectAny>(resourceName: string, resourceId: string, value: MaterializedLiveType<T>): Promise<MaterializedLiveType<T>>;
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
type RequestBase = {
|
|
163
|
-
resourceName: string;
|
|
164
|
-
context: Record<string, any>;
|
|
165
|
-
where?: Record<string, any>;
|
|
166
|
-
};
|
|
167
|
-
type FindRequest = RequestBase & {
|
|
168
|
-
type: "FIND";
|
|
169
|
-
};
|
|
170
|
-
type SetRequest = RequestBase & {
|
|
171
|
-
type: "SET";
|
|
172
|
-
resourceId: string;
|
|
173
|
-
payload: Record<string, any>;
|
|
174
|
-
};
|
|
175
|
-
type Request = FindRequest | SetRequest;
|
|
176
|
-
type RouteRecord = Record<string, Route<LiveObjectAny>>;
|
|
177
|
-
declare class Router<TSchema extends Schema<any>, TRoutes extends RouteRecord> {
|
|
178
|
-
readonly routes: TRoutes;
|
|
179
|
-
private constructor();
|
|
180
|
-
static create<TSchema extends Schema<any>, TRoutes extends RouteRecord>(opts: {
|
|
181
|
-
routes: TRoutes;
|
|
182
|
-
}): Router<TSchema, TRoutes>;
|
|
183
|
-
}
|
|
184
|
-
type AnyRouter = Router<Schema<any>, RouteRecord>;
|
|
185
|
-
type RouteResult<TShape extends LiveObjectAny> = {
|
|
186
|
-
data: MaterializedLiveType<TShape> | Record<string, MaterializedLiveType<TShape>>;
|
|
187
|
-
acceptedValues: Record<string, any> | null;
|
|
188
|
-
};
|
|
189
|
-
declare class Route<TShape extends LiveObjectAny> {
|
|
190
|
-
readonly shape: TShape;
|
|
191
|
-
constructor(shape: TShape);
|
|
192
|
-
private handleFind;
|
|
193
|
-
private handleSet;
|
|
194
|
-
handleRequest(opts: {
|
|
195
|
-
req: Request;
|
|
196
|
-
db: Storage;
|
|
197
|
-
}): Promise<RouteResult<TShape>>;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
type Simplify<T> = T extends Record<string, any> ? {
|
|
201
|
-
[K in keyof T]: Simplify<T[K]>;
|
|
202
|
-
} : T;
|
|
203
|
-
|
|
204
|
-
type Observable<T> = {
|
|
205
|
-
[K in keyof T]: Observable<T[K]>;
|
|
206
|
-
} & {
|
|
207
|
-
get: () => T;
|
|
208
|
-
subscribe: (callback: (value: T) => void) => () => void;
|
|
209
|
-
subscribeToRemote: () => () => void;
|
|
210
|
-
};
|
|
211
|
-
|
|
212
|
-
type WebSocketClientEventMap = WebSocketEventMap & {
|
|
213
|
-
connectionChange: {
|
|
214
|
-
open: boolean;
|
|
215
|
-
};
|
|
216
|
-
};
|
|
217
|
-
declare class WebSocketClient {
|
|
218
|
-
private ws;
|
|
219
|
-
private url;
|
|
220
|
-
private autoConnect;
|
|
221
|
-
private autoReconnect;
|
|
222
|
-
private reconnectTimeout;
|
|
223
|
-
private reconnectLimit?;
|
|
224
|
-
private reconnectAttempts;
|
|
225
|
-
private eventListeners;
|
|
226
|
-
private reconnectTimer;
|
|
227
|
-
private intentionallyDisconnected;
|
|
228
|
-
constructor(options: {
|
|
229
|
-
url: string;
|
|
230
|
-
autoConnect?: boolean;
|
|
231
|
-
autoReconnect?: boolean;
|
|
232
|
-
reconnectTimeout?: number;
|
|
233
|
-
reconnectLimit?: number;
|
|
234
|
-
});
|
|
235
|
-
connected(): boolean;
|
|
236
|
-
connect(): void;
|
|
237
|
-
disconnect(): void;
|
|
238
|
-
addEventListener<K extends keyof WebSocketClientEventMap>(event: K, callback: (event: WebSocketClientEventMap[K]) => void): void;
|
|
239
|
-
removeEventListener<K extends keyof WebSocketClientEventMap>(event: K, callback: (event: WebSocketClientEventMap[K]) => void): void;
|
|
240
|
-
send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void;
|
|
241
|
-
private handleOpen;
|
|
242
|
-
private handleClose;
|
|
243
|
-
private handleError;
|
|
244
|
-
private handleMessage;
|
|
245
|
-
private scheduleReconnect;
|
|
246
|
-
private dispatchEvent;
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
declare const useLiveQuery: <T extends Observable<U>, U>(observable: T, opts?: {
|
|
250
|
-
subscribeToRemote?: boolean;
|
|
251
|
-
}) => ReturnType<T["get"]>;
|
|
252
|
-
declare const SubscriptionProvider: ({ children, client, }: {
|
|
253
|
-
children: React.ReactNode;
|
|
254
|
-
client: Client<AnyRouter>["client"];
|
|
255
|
-
}) => react_jsx_runtime.JSX.Element;
|
|
256
|
-
|
|
257
|
-
type RawObjPool<TRouter extends AnyRouter> = Record<keyof TRouter["routes"], Record<string, MaterializedLiveObject<TRouter["routes"][keyof TRouter["routes"]]["shape"]>> | undefined>;
|
|
258
|
-
type ClientState<TRouter extends AnyRouter> = {
|
|
259
|
-
[K in keyof TRouter["routes"]]: Record<InferIndex<TRouter["routes"][K]["shape"]>, InferLiveObject<TRouter["routes"][K]["shape"]>> | undefined;
|
|
260
|
-
};
|
|
261
|
-
type Client<TRouter extends AnyRouter> = {
|
|
262
|
-
/**
|
|
263
|
-
* @internal
|
|
264
|
-
*/
|
|
265
|
-
_router: TRouter;
|
|
266
|
-
client: {
|
|
267
|
-
ws: WebSocketClient;
|
|
268
|
-
subscribeToRemote: (resourceType?: string[]) => () => void;
|
|
269
|
-
};
|
|
270
|
-
store: Observable<ClientState<TRouter>> & {
|
|
271
|
-
[K in keyof TRouter["routes"]]: {
|
|
272
|
-
insert: (input: Simplify<LiveObjectMutationInput<TRouter["routes"][K]["shape"]>>["value"]) => void;
|
|
273
|
-
update: (id: string, value: Omit<Simplify<LiveObjectMutationInput<TRouter["routes"][K]["shape"]>>["value"], "id">) => void;
|
|
274
|
-
};
|
|
275
|
-
};
|
|
276
|
-
};
|
|
277
|
-
type ClientOptions = {
|
|
278
|
-
url: string;
|
|
279
|
-
schema: Schema<any>;
|
|
280
|
-
};
|
|
281
|
-
declare const createClient: <TRouter extends AnyRouter>(opts: ClientOptions) => Client<TRouter>;
|
|
282
|
-
|
|
283
|
-
export { type Client, type ClientOptions, type ClientState, type RawObjPool, SubscriptionProvider, createClient, useLiveQuery };
|
|
1
|
+
import 'zod';
|
|
2
|
+
export { c as Client, C as ClientOptions, b as ClientState, O as ObservableClientState, R as RawObjPool, e as SubscriptionProvider, d as createClient, u as useLiveQuery } from './index-NDRWVwih.js';
|
|
3
|
+
import 'react/jsx-runtime';
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import {nanoid}from'nanoid';import {z}from'zod';import {useState,useEffect}from'react';import {jsx,Fragment}from'react/jsx-runtime';var v=z.string().nanoid(),K=z.object({_id:v,type:z.literal("SUBSCRIBE"),resource:z.string()}),k=z.object({_id:v,type:z.literal("SYNC"),lastSyncedAt:z.string().optional(),resources:z.string().array().optional()}),I=z.record(z.object({value:z.string().or(z.number()).or(z.boolean()).or(z.date()),_meta:z.object({timestamp:z.string().optional()}).optional()})).superRefine((o,e)=>{o.id&&e.addIssue({code:z.ZodIssueCode.custom,message:"Payload cannot have an id"});}),A=z.object({_id:v,type:z.literal("MUTATE"),resource:z.string(),resourceId:z.string(),payload:I});z.union([K,A,k]);var P=z.object({_id:v,type:z.literal("SYNC"),resource:z.string(),data:z.record(I)}),N=z.object({_id:v,type:z.literal("REJECT"),resource:z.string()}),C=z.union([A,P,N]);var b=o=>Array.isArray(o.value)?o.value.map(e=>b(e)):typeof o.value!="object"?o.value:Object.fromEntries(Object.entries(o.value).map(([e,t])=>[e,b(t)]));var R=class{nodes;constructor(){this.nodes=new Map;}createNode(e,t,n){if(this.nodes.has(e))throw new Error(`Node with id ${e} already exists`);let i={id:e,type:t,referencedBy:new Map(n.map(r=>[r,new Set])),references:new Map,subscriptions:new Set};return this.nodes.set(e,i),i}getNode(e){return this.nodes.get(e)}hasNode(e){return this.nodes.has(e)}createLink(e,t,n){let i=this.nodes.get(e),r=this.nodes.get(t);if(!i)throw new Error(`Source node with id ${e} does not exist`);if(!r)throw new Error(`Target node with id ${t} does not exist`);i.references.set(n,t);let s=r.referencedBy.get(n);s&&s instanceof Set?s.add(e):r.referencedBy.set(n,e),this.notifySubscribers(t);}removeLink(e,t){let n=this.nodes.get(e);if(!n)throw new Error(`Node with id ${e} does not exist`);let i=n.references.get(t);if(!i)return;n.references.delete(t);let r=this.nodes.get(i);if(!r)return;let s=r.referencedBy.get(t);s&&(s instanceof Set?s.delete(e):r.referencedBy.delete(t),this.notifySubscribers(i)),this.notifySubscribers(e);}subscribe(e,t){let n=this.nodes.get(e);if(!n)throw new Error(`Node with id ${e} does not exist`);return n.subscriptions.add(t),()=>{n.subscriptions.delete(t);}}removeNode(e){let t=this.nodes.get(e);t&&(Array.from(t.referencedBy.entries()).forEach(([n,i])=>{(i instanceof Set?Array.from(i.values()):[i]).forEach(s=>{let c=this.nodes.get(s);!c||!c.references.get(n)||(c.references.delete(n),this.notifySubscribers(s));});}),this.nodes.delete(e));}updateNode(e,t){let n=this.nodes.get(e);if(!n)throw new Error(`Node with id ${e} does not exist`);t(n),this.notifySubscribers(e);}notifySubscribers(e){let t=this.nodes.get(e);t&&Array.from(t.subscriptions).forEach(n=>{try{n(e);}catch(i){console.error(`Error in node subscription for node ${e}:`,i);}});}getAllNodes(){return Array.from(this.nodes.values())}};var x=(o,e,t=[])=>new Proxy(o,{get:(n,i)=>{var l,p;if(i==="__isProxy__")return true;let r=(l=e.get)==null?void 0:l.call(e,n,[...t,i]);if(r!==void 0)return r;let s=n,c=i;return (p=s[c])!=null&&p.__isProxy__||(s[c]=x(typeof s[c]=="object"?s[c]:Object.create(null),e,[...t,i])),s[c]}});var M=class{ws=null;url;autoConnect;autoReconnect;reconnectTimeout;reconnectLimit;reconnectAttempts=0;eventListeners=new Map;reconnectTimer=null;intentionallyDisconnected=false;constructor(e){this.url=e.url,this.autoConnect=e.autoConnect??false,this.autoReconnect=e.autoReconnect??false,this.reconnectTimeout=e.reconnectTimeout??5e3,this.reconnectLimit=e.reconnectLimit,this.autoConnect&&this.connect();}connected(){var e;return ((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN}connect(){this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING)||(this.intentionallyDisconnected=false,this.ws=new WebSocket(this.url),this.ws.addEventListener("open",this.handleOpen.bind(this)),this.ws.addEventListener("close",this.handleClose.bind(this)),this.ws.addEventListener("error",this.handleError.bind(this)),this.ws.addEventListener("message",this.handleMessage.bind(this)));}disconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.intentionallyDisconnected=true,this.ws&&(this.ws.close(),this.ws=null);}addEventListener(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t);}removeEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.get(e).delete(t);}send(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN)this.ws.send(e);else throw new Error("WebSocket is not open")}handleOpen(e){this.reconnectAttempts=0,this.dispatchEvent("open",e),this.dispatchEvent("connectionChange",{open:true});}handleClose(e){this.dispatchEvent("close",e),this.dispatchEvent("connectionChange",{open:false}),this.autoReconnect&&!this.intentionallyDisconnected&&this.scheduleReconnect();}handleError(e){this.dispatchEvent("error",e);}handleMessage(e){this.dispatchEvent("message",e);}scheduleReconnect(){this.reconnectLimit&&this.reconnectAttempts>=this.reconnectLimit||(this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect();},this.reconnectTimeout));}dispatchEvent(e,t){this.eventListeners.has(e)&&this.eventListeners.get(e).forEach(n=>{n(t);});}};var pe=(o,e)=>{let[t,n]=useState(()=>o.get());return useEffect(()=>{if(e!=null&&e.subscribeToRemote)return o.subscribeToRemote()},[e==null?void 0:e.subscribeToRemote]),useEffect(()=>o.subscribe(()=>{let i=o.get();n(i);}),[]),t},ye=({children:o,client:e})=>(useEffect(()=>{e.subscribeToRemote();},[]),jsx(Fragment,{children:o}));var _=class{_router;url;ws;schema;rawObjPool={};optimisticMutationStack={};optimisticObjGraph=new R;optimisticRawObjPool={};resourceTypeSubscriptions={};routeSubscriptions={};constructor(e){this.url=e.url,this.schema=e.schema,this.ws=new M({url:e.url,autoConnect:true,autoReconnect:true,reconnectTimeout:5e3}),this.ws.addEventListener("message",t=>{this.handleServerMessage(t.data);}),this.ws.addEventListener("connectionChange",t=>{t.open&&(this.sendWsMessage({_id:nanoid(),type:"SYNC"}),Object.entries(this.routeSubscriptions).forEach(([n,i])=>{i>0&&this.sendWsMessage({_id:nanoid(),type:"SUBSCRIBE",resource:n});}),Object.values(this.optimisticMutationStack).forEach(n=>{n.forEach(i=>this.sendWsMessage(i));}));});}get(e){if(e.length===0)throw new Error("Path must not be empty");if(e.length===1)return Object.fromEntries(Object.entries(this.optimisticRawObjPool[e[0]]??{}).map(([n,i])=>[n,b(i)]));let t=this.getFullObject(e[0],e[1]);if(!t)throw new Error("Object of type "+e[0]+" not found with id "+e[1]);return b(t)}handleServerMessage(e){try{console.log("Message received from the server:",e);let t=C.parse(JSON.parse(e));if(console.log("Parsed message:",t),t.type==="MUTATE"){let{resource:n}=t;try{this.addMutation(n,t);}catch(i){console.error("Error parsing mutation from the server:",i);}}else if(t.type==="SYNC"){let{resource:n,data:i}=t;console.log("Syncing resource:",i,t),Object.entries(i).forEach(([r,s])=>{this.addMutation(n,{_id:r,type:"MUTATE",resource:n,resourceId:r,payload:s});});}else t.type;}catch(t){console.error("Error parsing message from the server:",t);}}subscribeToRemote(e){return this.routeSubscriptions[e]=(this.routeSubscriptions[e]??0)+1,this.sendWsMessage({_id:nanoid(),type:"SUBSCRIBE",resource:e}),()=>{this.routeSubscriptions[e]-=1,this.routeSubscriptions[e];}}subscribeToSlice(e,t){if(e.length===1)return this.resourceTypeSubscriptions[e[0]]||(this.resourceTypeSubscriptions[e[0]]=new Set),this.resourceTypeSubscriptions[e[0]].add(t),()=>{this.resourceTypeSubscriptions[e[0]].delete(t);};if(e.length===2){if(!this.optimisticObjGraph.getNode(e[1]))throw new Error("Node not found");return this.optimisticObjGraph.subscribe(e[1],t)}throw new Error("Not implemented")}mutate(e,t,n){let i={_id:nanoid(),type:"MUTATE",resource:e,payload:this.schema[e].encodeMutation("set",n,new Date().toISOString()),resourceId:t};this.addMutation(e,i,true),this.sendWsMessage(i);}sendWsMessage(e){this.ws&&this.ws.connected()&&this.ws.send(JSON.stringify(e));}addMutation(e,t,n=false){var c,l,p,f;let i=this.schema[e];if(console.log("Adding mutation",t),!i)throw new Error("Schema not found");n?(this.optimisticMutationStack[e]||(this.optimisticMutationStack[e]=[]),this.optimisticMutationStack[e].push(t)):this.optimisticMutationStack[e]&&(this.optimisticMutationStack[e]=this.optimisticMutationStack[e].filter(u=>u._id!==t._id)),this.optimisticObjGraph.getNode(t.resourceId)||this.optimisticObjGraph.createNode(t.resourceId,e,Object.values(i.relations).flatMap(u=>u.type==="many"?[u.foreignColumn]:[]));let r=((c=this.optimisticRawObjPool[e])==null?void 0:c[t.resourceId])??((l=this.rawObjPool[e])==null?void 0:l[t.resourceId]);n||(this.rawObjPool[e]??={},this.rawObjPool[e][t.resourceId]={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}}),this.optimisticRawObjPool[e]??={};let s=(this.optimisticMutationStack[e]??[]).reduce((u,d)=>d.resourceId!==d.resourceId?u:this.schema[e].mergeMutation("set",d.payload,u)[0],(p=this.rawObjPool[e])==null?void 0:p[t.resourceId]);if(s&&(this.optimisticRawObjPool[e][t.resourceId]={value:{...s.value,id:{value:t.resourceId}}}),Object.keys(i.relations).length>0){let u=Object.fromEntries(Object.entries(i.relations).flatMap(([d,T])=>T.type==="one"?[[T.relationalColumn,d]]:[]));Object.entries(t.payload).forEach(([d,T])=>{if(!u[d])return;let[,y]=i.relations[u[d]].mergeMutation("set",T,r==null?void 0:r.value[d]);y&&this.optimisticObjGraph.createLink(t.resourceId,y.value,d);});}(f=this.resourceTypeSubscriptions[e])==null||f.forEach(u=>u()),this.optimisticObjGraph.notifySubscribers(t.resourceId);}getFullObject(e,t){var r;let n=this.optimisticObjGraph.getNode(t);if(!n)return;let i=(r=this.optimisticRawObjPool[e])==null?void 0:r[t];if(i)return {value:{...i.value,...Object.fromEntries(Array.from(n.referencedBy.entries()).map(([s,c])=>{var T;let l=c instanceof Set,p=l?Array.from(c.values()).flatMap(y=>{let h=this.optimisticObjGraph.getNode(y);return h?[h]:[]}):this.optimisticObjGraph.getNode(c);if(!p)return [s,void 0];let[f,u]=Object.entries(this.schema[e].relations).find(y=>y[1].relationalColumn===s||y[1].foreignColumn===s)??[],d=u==null?void 0:u.entity.name;return !d||!u?[s,l?[]:void 0]:[f,{value:l?p.map(y=>{var h;return (h=this.optimisticRawObjPool[d])==null?void 0:h[y.id]}):(T=this.optimisticRawObjPool[d])==null?void 0:T[p.id]}]}))}}}},Ke=o=>{let e=new _(o);return {_router:e._router,client:{ws:e.ws,subscribeToRemote:t=>{let n=[];for(let i of t??Object.keys(e.schema))n.push(e.subscribeToRemote(i));return ()=>{n.forEach(i=>i());}}},store:x({},{get:(t,n)=>{let i=n.slice(0,-1),r=n[n.length-1];if(r==="get")return ()=>e.get(i);if(r==="subscribe")return s=>e.subscribeToSlice(i,s);if(r==="subscribeToRemote")return e.subscribeToRemote.bind(e,i[0]);if(i.length===1){if(r==="insert")return s=>{let{id:c,...l}=s;e.mutate(i[0],c,l);};if(r==="update")return (s,c)=>{e.mutate(i[0],s,c);}}}})}};export{ye as SubscriptionProvider,Ke as createClient,pe as useLiveQuery};
|
|
1
|
+
import {d,a,c,b as b$1}from'./chunk-NIWX45UD.js';import {z as z$1}from'zod';import {stringify}from'qs';import {useState,useEffect}from'react';import {jsx,Fragment}from'react/jsx-runtime';z$1.object({type:z$1.literal("QUERY"),resource:z$1.string(),where:z$1.record(z$1.any()).optional(),include:z$1.record(z$1.any()).optional()});var T=z$1.record(z$1.object({value:z$1.string().or(z$1.number()).or(z$1.boolean()).or(z$1.date()),_meta:z$1.object({timestamp:z$1.string().optional()}).optional()})).superRefine((l,e)=>{l.id&&e.addIssue({code:z$1.ZodIssueCode.custom,message:"Payload cannot have an id"});}),x=z$1.object({id:z$1.string().optional(),type:z$1.literal("MUTATE"),resource:z$1.string()}),R=x.extend({procedure:z$1.string(),payload:z$1.any().optional()}),O=x.extend({resourceId:z$1.string(),payload:T});z$1.union([R,O]);var b=z$1.string(),k=z$1.object({id:b,type:z$1.literal("SUBSCRIBE"),resource:z$1.string()}),G=z$1.object({id:b,type:z$1.literal("SYNC"),lastSyncedAt:z$1.string().optional(),resources:z$1.string().array().optional(),where:z$1.record(z$1.any()).optional()}),A=O.extend({id:b}),W=R.extend({id:b}),K=z$1.union([W,A]);z$1.union([k,G,K]);var z=z$1.object({id:b,type:z$1.literal("SYNC"),resource:z$1.string(),data:z$1.record(T)}),I=z$1.object({id:b,type:z$1.literal("REJECT"),resource:z$1.string(),message:z$1.string().optional()}),B=z$1.object({id:b,type:z$1.literal("REPLY"),data:z$1.any()}),P=z$1.union([z,I,B,A]);var S=class{nodes;constructor(){this.nodes=new Map;}createNode(e,t,i){if(this.nodes.has(e))throw new Error(`Node with id ${e} already exists`);let r={id:e,type:t,referencedBy:new Map(i.map(s=>[s,new Set])),references:new Map,subscriptions:new Set};return this.nodes.set(e,r),r}getNode(e){return this.nodes.get(e)}hasNode(e){return this.nodes.has(e)}createLink(e,t,i){let r=this.nodes.get(e),s=this.nodes.get(t);if(!r)throw new Error(`Source node with id ${e} does not exist`);if(!s)throw new Error(`Target node with id ${t} does not exist`);r.references.set(i,t);let n=s.referencedBy.get(i);n&&n instanceof Set?n.add(e):s.referencedBy.set(i,e),this.notifySubscribers(t);}removeLink(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);let r=i.references.get(t);if(!r)return;i.references.delete(t);let s=this.nodes.get(r);if(!s)return;let n=s.referencedBy.get(t);n&&(n instanceof Set?n.delete(e):s.referencedBy.delete(t),this.notifySubscribers(r)),this.notifySubscribers(e);}subscribe(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);return i.subscriptions.add(t),()=>{i.subscriptions.delete(t);}}removeNode(e){let t=this.nodes.get(e);t&&(Array.from(t.referencedBy.entries()).forEach(([i,r])=>{(r instanceof Set?Array.from(r.values()):[r]).forEach(n=>{let d=this.nodes.get(n);!d||!d.references.get(i)||(d.references.delete(i),this.notifySubscribers(n));});}),this.nodes.delete(e));}updateNode(e,t){let i=this.nodes.get(e);if(!i)throw new Error(`Node with id ${e} does not exist`);t(i),this.notifySubscribers(e);}notifySubscribers(e){let t=this.nodes.get(e);t&&Array.from(t.subscriptions).forEach(i=>{try{i(e);}catch(r){console.error(`Error in node subscription for node ${e}:`,r);}});}getAllNodes(){return Array.from(this.nodes.values())}};var M=class{ws=null;url;autoConnect;autoReconnect;reconnectTimeout;reconnectLimit;reconnectAttempts=0;eventListeners=new Map;reconnectTimer=null;intentionallyDisconnected=false;credentials;constructor(e){this.url=e.url,this.autoConnect=e.autoConnect??false,this.autoReconnect=e.autoReconnect??false,this.reconnectTimeout=e.reconnectTimeout??5e3,this.reconnectLimit=e.reconnectLimit,this.credentials=e.credentials,this.autoConnect&&this.connect();}connected(){var e;return ((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN}async connect(){if(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;this.intentionallyDisconnected=false;let e=await b$1(this.credentials);this.ws=new WebSocket(this.url+(e?`?${stringify(e)}`:"")),this.ws.addEventListener("open",this.handleOpen.bind(this)),this.ws.addEventListener("close",this.handleClose.bind(this)),this.ws.addEventListener("error",this.handleError.bind(this)),this.ws.addEventListener("message",this.handleMessage.bind(this));}disconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.intentionallyDisconnected=true,this.ws&&(this.ws.close(),this.ws=null);}addEventListener(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t);}removeEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.get(e).delete(t);}send(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN)this.ws.send(e);else throw new Error("WebSocket is not open")}handleOpen(e){this.reconnectAttempts=0,this.dispatchEvent("open",e),this.dispatchEvent("connectionChange",{open:true});}handleClose(e){this.dispatchEvent("close",e),this.dispatchEvent("connectionChange",{open:false}),this.autoReconnect&&!this.intentionallyDisconnected&&this.scheduleReconnect();}handleError(e){this.dispatchEvent("error",e);}handleMessage(e){this.dispatchEvent("message",e);}scheduleReconnect(){this.reconnectLimit&&this.reconnectAttempts>=this.reconnectLimit||(this.reconnectAttempts++,this.reconnectTimer=setTimeout(()=>{this.connect();},this.reconnectTimeout));}dispatchEvent(e,t){this.eventListeners.has(e)&&this.eventListeners.get(e).forEach(i=>{i(t);});}};var re=(l,e)=>{let[t,i]=useState(()=>l.get());return useEffect(()=>{if(e!=null&&e.subscribeToRemote)return l.subscribeToRemote()},[e==null?void 0:e.subscribeToRemote]),useEffect(()=>l.subscribe(()=>{let r=l.get();i(r);}),[]),t},se=({children:l,client:e})=>(useEffect(()=>{e.subscribeToRemote();},[]),jsx(Fragment,{children:l}));var j=class{url;ws;schema;rawObjPool={};optimisticMutationStack={};optimisticObjGraph=new S;optimisticRawObjPool={};resourceTypeSubscriptions={};routeSubscriptions={};replyHandlers={};constructor(e){this.url=e.url,this.schema=e.schema,this.ws=new M({url:e.url,autoConnect:true,autoReconnect:true,reconnectTimeout:5e3,credentials:e.credentials}),this.ws.addEventListener("message",t=>{this.handleServerMessage(t.data);}),this.ws.addEventListener("connectionChange",t=>{t.open&&(this.sendWsMessage({id:a(),type:"SYNC"}),Object.entries(this.routeSubscriptions).forEach(([i,r])=>{r>0&&this.sendWsMessage({id:a(),type:"SUBSCRIBE",resource:i});}),Object.values(this.optimisticMutationStack).forEach(i=>{i.forEach(r=>this.sendWsMessage(r));}));});}get(e){if(e.length===0)throw new Error("Path must not be empty");if(e.length===1)return Object.fromEntries(Object.entries(this.optimisticRawObjPool[e[0]]??{}).map(([i,r])=>[i,c(r)]));let t=this.getFullObject(e[0],e[1]);if(!t)throw new Error("Object of type "+e[0]+" not found with id "+e[1]);return c(t)}handleServerMessage(e){try{console.log("Message received from the server:",e);let t=P.parse(JSON.parse(e));if(console.log("Parsed message:",t),t.type==="MUTATE"){let{resource:i}=t;try{this.addMutation(i,t);}catch(r){console.error("Error parsing mutation from the server:",r);}}else if(t.type==="SYNC"){let{resource:i,data:r}=t;console.log("Syncing resource:",r,t),Object.entries(r).forEach(([s,n])=>{this.addMutation(i,{id:s,type:"MUTATE",resource:i,resourceId:s,payload:n});});}else if(t.type!=="REJECT"){if(t.type==="REPLY"){let{id:i,data:r}=t;if(!this.replyHandlers[i])return;clearTimeout(this.replyHandlers[i].timeoutHandle),this.replyHandlers[i].handler(r);}}}catch(t){console.error("Error parsing message from the server:",t);}}subscribeToRemote(e){return this.routeSubscriptions[e]=(this.routeSubscriptions[e]??0)+1,this.sendWsMessage({id:a(),type:"SUBSCRIBE",resource:e}),()=>{this.routeSubscriptions[e]-=1,this.routeSubscriptions[e];}}subscribeToSlice(e,t){if(e.length===1)return this.resourceTypeSubscriptions[e[0]]||(this.resourceTypeSubscriptions[e[0]]=new Set),this.resourceTypeSubscriptions[e[0]].add(t),()=>{this.resourceTypeSubscriptions[e[0]].delete(t);};if(e.length===2){if(!this.optimisticObjGraph.getNode(e[1]))throw new Error("Node not found");return this.optimisticObjGraph.subscribe(e[1],t)}throw new Error("Not implemented")}mutate(e,t,i){let r={id:a(),type:"MUTATE",resource:e,payload:this.schema[e].encodeMutation("set",i,new Date().toISOString()),resourceId:t};this.addMutation(e,r,true),this.sendWsMessage(r);}genericMutate(e,t,i){if(!this.ws||!this.ws.connected())throw new Error("WebSocket not connected");let r={id:a(),type:"MUTATE",resource:e,procedure:t,payload:i};return this.sendWsMessage(r),new Promise((s,n)=>{this.replyHandlers[r.id]={timeoutHandle:setTimeout(()=>{delete this.replyHandlers[r.id],n(new Error("Reply timeout"));},5e3),handler:d=>{delete this.replyHandlers[r.id],s(d);}};})}sendWsMessage(e){this.ws&&this.ws.connected()&&this.ws.send(JSON.stringify(e));}addMutation(e,t,i=false){var d,p,g,v;let r=this.schema[e];if(console.log("Adding mutation",t),!r)throw new Error("Schema not found");i?(this.optimisticMutationStack[e]||(this.optimisticMutationStack[e]=[]),this.optimisticMutationStack[e].push(t)):this.optimisticMutationStack[e]&&(this.optimisticMutationStack[e]=this.optimisticMutationStack[e].filter(a=>a.id!==t.id)),this.optimisticObjGraph.getNode(t.resourceId)||this.optimisticObjGraph.createNode(t.resourceId,e,Object.values(r.relations).flatMap(a=>a.type==="many"?[a.foreignColumn]:[]));let s=((d=this.optimisticRawObjPool[e])==null?void 0:d[t.resourceId])??((p=this.rawObjPool[e])==null?void 0:p[t.resourceId]);i||(this.rawObjPool[e]??={},this.rawObjPool[e][t.resourceId]={value:{...this.schema[e].mergeMutation("set",t.payload,this.rawObjPool[e][t.resourceId])[0].value,id:{value:t.resourceId}}}),this.optimisticRawObjPool[e]??={};let n=(this.optimisticMutationStack[e]??[]).reduce((a,u)=>u.resourceId!==u.resourceId?a:this.schema[e].mergeMutation("set",u.payload,a)[0],(g=this.rawObjPool[e])==null?void 0:g[t.resourceId]);if(n&&(this.optimisticRawObjPool[e][t.resourceId]={value:{...n.value,id:{value:t.resourceId}}}),Object.keys(r.relations).length>0){let a=Object.fromEntries(Object.entries(r.relations).flatMap(([u,f])=>f.type==="one"?[[f.relationalColumn,u]]:[]));Object.entries(t.payload).forEach(([u,f])=>{if(!a[u])return;let[,h]=r.relations[a[u]].mergeMutation("set",f,s==null?void 0:s.value[u]);h&&this.optimisticObjGraph.createLink(t.resourceId,h.value,u);});}(v=this.resourceTypeSubscriptions[e])==null||v.forEach(a=>a()),this.optimisticObjGraph.notifySubscribers(t.resourceId);}getFullObject(e,t){var s;let i=this.optimisticObjGraph.getNode(t);if(!i)return;let r=(s=this.optimisticRawObjPool[e])==null?void 0:s[t];if(r)return {value:{...r.value,...Object.fromEntries(Array.from(i.referencedBy.entries()).map(([n,d])=>{var f;let p=d instanceof Set,g=p?Array.from(d.values()).flatMap(h=>{let m=this.optimisticObjGraph.getNode(h);return m?[m]:[]}):this.optimisticObjGraph.getNode(d);if(!g)return [n,void 0];let[v,a]=Object.entries(this.schema[e].relations).find(h=>h[1].relationalColumn===n||h[1].foreignColumn===n)??[],u=a==null?void 0:a.entity.name;return !u||!a?[n,p?[]:void 0]:[v,{value:p?g.map(h=>{var m;return (m=this.optimisticRawObjPool[u])==null?void 0:m[h.id]}):(f=this.optimisticRawObjPool[u])==null?void 0:f[g.id]}]}))}}}},Ce=l=>{let e=new j(l);return {client:{ws:e.ws,subscribeToRemote:t=>{let i=[];for(let r of t??Object.keys(e.schema))i.push(e.subscribeToRemote(r));return ()=>{i.forEach(r=>r());}}},store:d(()=>{},{apply:(t,i,r)=>{let s=i.slice(0,-1),n=i[i.length-1];if(n==="get")return e.get(s);if(n==="subscribe")return e.subscribeToSlice(s,r[0]);if(n==="subscribeToRemote")return e.subscribeToRemote(s[0]);if(n==="insert"){let{id:d,...p}=r[0];return e.mutate(s[0],d,p)}if(n==="update"){let[d,p]=r;return e.mutate(s[0],d,p)}return e.genericMutate(s[0],n,r[0])}})}};export{se as SubscriptionProvider,Ce as createClient,re as useLiveQuery};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { A as AnyRouter, C as ClientOptions, L as LiveObjectAny, W as WhereClause, S as Simplify, I as InferLiveObject, a as LiveObjectMutationInput } from './index-NDRWVwih.js';
|
|
2
|
+
import 'zod';
|
|
3
|
+
import 'react/jsx-runtime';
|
|
4
|
+
|
|
5
|
+
type GetOptions<T extends LiveObjectAny> = {
|
|
6
|
+
headers?: Record<string, string>;
|
|
7
|
+
where?: WhereClause<T>;
|
|
8
|
+
};
|
|
9
|
+
type FetchClient<TRouter extends AnyRouter> = {
|
|
10
|
+
[K in keyof TRouter["routes"]]: {
|
|
11
|
+
get: (opts?: GetOptions<TRouter["routes"][K]["_resourceSchema"]>) => Promise<Simplify<InferLiveObject<TRouter["routes"][K]["_resourceSchema"]>>>;
|
|
12
|
+
upsert: (input: Simplify<LiveObjectMutationInput<TRouter["routes"][K]["_resourceSchema"]>>) => Promise<void>;
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
declare const createClient: <TRouter extends AnyRouter>(opts: ClientOptions) => FetchClient<TRouter>;
|
|
16
|
+
|
|
17
|
+
export { createClient };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import {d,b,c}from'./chunk-NIWX45UD.js';import {stringify}from'qs';var S=t=>d(()=>{},{apply:async(h,c$1,o)=>{if(c$1.length>2)throw new Error("Trying to access invalid property");let[n,i]=c$1,s=await b(t.credentials)??{};if(i==="get"){let e=o[0],r={};return e!=null&&e.where&&(r.where=e.where),fetch(`${t.url}/${n}${Object.keys(r).length>0?`?${stringify(r)}`:""}`,{headers:s}).then(async y=>Object.fromEntries(Object.entries(await y.json()??{}).map(([m,l])=>[m,c(l)])))}if(i==="upsert"){let{id:e,...r}=o[0];return fetch(`${t.url}/${n}/set`,{method:"POST",headers:{...s,"Content-Type":"application/json"},body:JSON.stringify({resourceId:e,payload:t.schema[n].encodeMutation("set",r,new Date().toISOString())})})}return fetch(`${t.url}/${n}/${i}`,{method:"POST",headers:{...s,"Content-Type":"application/json"},body:JSON.stringify(o[0])})}});export{S as createClient};
|