@instantdb/react 0.22.89 → 0.22.90-experimental.drewh-ssr.20286580593.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/commonjs/index.d.ts +2 -2
  2. package/dist/commonjs/index.d.ts.map +1 -1
  3. package/dist/commonjs/index.js +2 -1
  4. package/dist/commonjs/index.js.map +1 -1
  5. package/dist/commonjs/next-ssr/HydrationStreamProvider.d.ts +66 -0
  6. package/dist/commonjs/next-ssr/HydrationStreamProvider.d.ts.map +1 -0
  7. package/dist/commonjs/next-ssr/HydrationStreamProvider.js +135 -0
  8. package/dist/commonjs/next-ssr/HydrationStreamProvider.js.map +1 -0
  9. package/dist/commonjs/next-ssr/htmlescape.d.ts +3 -0
  10. package/dist/commonjs/next-ssr/htmlescape.d.ts.map +1 -0
  11. package/dist/commonjs/next-ssr/htmlescape.js +25 -0
  12. package/dist/commonjs/next-ssr/htmlescape.js.map +1 -0
  13. package/dist/commonjs/next-ssr/index.d.ts +50 -0
  14. package/dist/commonjs/next-ssr/index.d.ts.map +1 -0
  15. package/dist/commonjs/next-ssr/index.js +158 -0
  16. package/dist/commonjs/next-ssr/index.js.map +1 -0
  17. package/dist/esm/index.d.ts +2 -2
  18. package/dist/esm/index.d.ts.map +1 -1
  19. package/dist/esm/index.js +2 -2
  20. package/dist/esm/index.js.map +1 -1
  21. package/dist/esm/next-ssr/HydrationStreamProvider.d.ts +66 -0
  22. package/dist/esm/next-ssr/HydrationStreamProvider.d.ts.map +1 -0
  23. package/dist/esm/next-ssr/HydrationStreamProvider.js +98 -0
  24. package/dist/esm/next-ssr/HydrationStreamProvider.js.map +1 -0
  25. package/dist/esm/next-ssr/htmlescape.d.ts +3 -0
  26. package/dist/esm/next-ssr/htmlescape.d.ts.map +1 -0
  27. package/dist/esm/next-ssr/htmlescape.js +21 -0
  28. package/dist/esm/next-ssr/htmlescape.js.map +1 -0
  29. package/dist/esm/next-ssr/index.d.ts +50 -0
  30. package/dist/esm/next-ssr/index.d.ts.map +1 -0
  31. package/dist/esm/next-ssr/index.js +148 -0
  32. package/dist/esm/next-ssr/index.js.map +1 -0
  33. package/dist/standalone/index.js +2078 -1961
  34. package/dist/standalone/index.umd.cjs +14 -14
  35. package/package.json +18 -6
  36. package/src/index.ts +2 -0
  37. package/src/next-ssr/HydrationStreamProvider.tsx +193 -0
  38. package/src/next-ssr/htmlescape.ts +24 -0
  39. package/src/next-ssr/index.tsx +264 -0
  40. package/tsconfig.json +1 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@instantdb/react",
3
- "version": "0.22.89",
3
+ "version": "0.22.90-experimental.drewh-ssr.20286580593.1",
4
4
  "description": "Instant DB for React",
5
5
  "homepage": "https://github.com/instantdb/instant/tree/main/client/packages/react",
6
6
  "repository": {
@@ -24,6 +24,16 @@
24
24
  "types": "./dist/commonjs/index.d.ts",
25
25
  "default": "./dist/commonjs/index.js"
26
26
  }
27
+ },
28
+ "./nextjs": {
29
+ "import": {
30
+ "types": "./dist/esm/next-ssr/index.d.ts",
31
+ "default": "./dist/esm/next-ssr/index.js"
32
+ },
33
+ "require": {
34
+ "types": "./dist/commonjs/next-ssr/index.d.ts",
35
+ "default": "./dist/commonjs/next-ssr/index.js"
36
+ }
27
37
  }
28
38
  },
29
39
  "tshy": {
@@ -33,7 +43,8 @@
33
43
  "project": "./tsconfig.json",
34
44
  "exports": {
35
45
  "./package.json": "./package.json",
36
- ".": "./src/index.ts"
46
+ ".": "./src/index.ts",
47
+ "./nextjs": "./src/next-ssr/index.tsx"
37
48
  }
38
49
  },
39
50
  "devDependencies": {
@@ -46,6 +57,7 @@
46
57
  "npm-run-all": "^4.1.5",
47
58
  "tshy": "^3.0.2",
48
59
  "typescript": "^5.9.3",
60
+ "next": "^15.5.6",
49
61
  "vite": "^5.2.0",
50
62
  "vitest": "^0.21.0"
51
63
  },
@@ -54,15 +66,15 @@
54
66
  },
55
67
  "dependencies": {
56
68
  "eventsource": "^4.0.0",
57
- "@instantdb/core": "0.22.89",
58
- "@instantdb/react-common": "0.22.89",
59
- "@instantdb/version": "0.22.89"
69
+ "@instantdb/core": "0.22.90-experimental.drewh-ssr.20286580593.1",
70
+ "@instantdb/version": "0.22.90-experimental.drewh-ssr.20286580593.1",
71
+ "@instantdb/react-common": "0.22.90-experimental.drewh-ssr.20286580593.1"
60
72
  },
61
73
  "scripts": {
62
74
  "test": "vitest",
63
75
  "test:types": "tsc -p tsconfig.test.json --noEmit",
64
76
  "test:ci": "pnpm run test:types",
65
- "check-exports": "attw --pack .",
77
+ "check-exports": "attw --profile node16 --pack .",
66
78
  "dev": "tsc --watch --preserveWatchOutput -p tsconfig.dev.json",
67
79
  "clean": "rm -rf dist",
68
80
  "build:tshy": "tshy",
package/src/index.ts CHANGED
@@ -83,6 +83,7 @@ import {
83
83
  type SyncTableSyncTransaction,
84
84
  type SyncTableLoadFromStorage,
85
85
  type SyncTableSetupError,
86
+ createInstantRouteHandler,
86
87
  } from '@instantdb/core';
87
88
 
88
89
  import { InstantReactAbstractDatabase } from '@instantdb/react-common';
@@ -96,6 +97,7 @@ export {
96
97
  lookup,
97
98
  init,
98
99
  init_experimental,
100
+ createInstantRouteHandler,
99
101
  InstantReactWebDatabase,
100
102
  Cursors,
101
103
  i,
@@ -0,0 +1,193 @@
1
+ 'use client';
2
+ export const isServer = typeof window === 'undefined' || 'Deno' in globalThis;
3
+
4
+ import { useServerInsertedHTML } from 'next/navigation.js';
5
+
6
+ import * as React from 'react';
7
+ import { htmlEscapeJsonString } from './htmlescape.js';
8
+
9
+ const serializedSymbol = Symbol('serialized');
10
+
11
+ interface DataTransformer {
12
+ serialize: (object: any) => any;
13
+ deserialize: (object: any) => any;
14
+ }
15
+
16
+ type Serialized<TData> = unknown & {
17
+ [serializedSymbol]: TData;
18
+ };
19
+
20
+ interface TypedDataTransformer<TData> {
21
+ serialize: (obj: TData) => Serialized<TData>;
22
+ deserialize: (obj: Serialized<TData>) => TData;
23
+ }
24
+
25
+ interface HydrationStreamContext<TShape> {
26
+ id: string;
27
+ stream: {
28
+ /**
29
+ * **Server method**
30
+ * Push a new entry to the stream
31
+ * Will be ignored on the client
32
+ */
33
+ push: (...shape: Array<TShape>) => void;
34
+ };
35
+ }
36
+
37
+ export interface HydrationStreamProviderProps<TShape> {
38
+ children: React.ReactNode;
39
+ /**
40
+ * Optional transformer to serialize/deserialize the data
41
+ * Example devalue, superjson et al
42
+ */
43
+ transformer?: DataTransformer;
44
+ /**
45
+ * **Client method**
46
+ * Called in the browser when new entries are received
47
+ */
48
+ onEntries: (entries: Array<TShape>) => void;
49
+ /**
50
+ * **Server method**
51
+ * onFlush is called on the server when the cache is flushed
52
+ */
53
+ onFlush?: () => Array<TShape>;
54
+ /**
55
+ * A nonce that'll allow the inline script to be executed when Content Security Policy is enforced
56
+ */
57
+ nonce?: string;
58
+ }
59
+
60
+ export function createHydrationStreamProvider<TShape>() {
61
+ const context = React.createContext<HydrationStreamContext<TShape>>(
62
+ null as any,
63
+ );
64
+ /**
65
+
66
+ * 1. (Happens on server): `useServerInsertedHTML()` is called **on the server** whenever a `Suspense`-boundary completes
67
+ * - This means that we might have some new entries in the cache that needs to be flushed
68
+ * - We pass these to the client by inserting a `<script>`-tag where we do `window[id].push(serializedVersionOfCache)`
69
+ * 2. (Happens in browser) In `useEffect()`:
70
+ * - We check if `window[id]` is set to an array and call `push()` on all the entries which will call `onEntries()` with the new entries
71
+ * - We replace `window[id]` with a `push()`-method that will be called whenever new entries are received
72
+ **/
73
+ function UseClientHydrationStreamProvider(props: {
74
+ children: React.ReactNode;
75
+ /**
76
+ * Optional transformer to serialize/deserialize the data
77
+ * Example devalue, superjson et al
78
+ */
79
+ transformer?: DataTransformer;
80
+ /**
81
+ * **Client method**
82
+ * Called in the browser when new entries are received
83
+ */
84
+ onEntries: (entries: Array<TShape>) => void;
85
+ /**
86
+ * **Server method**
87
+ * onFlush is called on the server when the cache is flushed
88
+ */
89
+ onFlush?: () => Array<TShape>;
90
+ /**
91
+ * A nonce that'll allow the inline script to be executed when Content Security Policy is enforced
92
+ */
93
+ nonce?: string;
94
+ }) {
95
+ // unique id for the cache provider
96
+ const id = `__RQ${React.useId()}`;
97
+ const idJSON = htmlEscapeJsonString(JSON.stringify(id));
98
+
99
+ const [transformer] = React.useState(
100
+ () =>
101
+ (props.transformer ?? {
102
+ // noop
103
+ serialize: (obj: any) => obj,
104
+ deserialize: (obj: any) => obj,
105
+ }) as unknown as TypedDataTransformer<TShape>,
106
+ );
107
+
108
+ // <server stuff>
109
+ const [stream] = React.useState<Array<TShape>>(() => {
110
+ if (!isServer) {
111
+ return {
112
+ push() {
113
+ // no-op on the client
114
+ },
115
+ } as unknown as Array<TShape>;
116
+ }
117
+ return [];
118
+ });
119
+ const count = React.useRef(0);
120
+ useServerInsertedHTML(() => {
121
+ // This only happens on the server
122
+ stream.push(...(props.onFlush?.() ?? []));
123
+
124
+ if (!stream.length) {
125
+ return null;
126
+ }
127
+ // console.log(`pushing ${stream.length} entries`)
128
+ const serializedCacheArgs = stream
129
+ .map((entry) => transformer.serialize(entry))
130
+ .map((entry) => JSON.stringify(entry))
131
+ .join(',');
132
+
133
+ // Flush stream
134
+ // eslint-disable-next-line react-hooks/immutability
135
+ stream.length = 0;
136
+
137
+ const html: Array<string> = [
138
+ `window[${idJSON}] = window[${idJSON}] || [];`,
139
+ `window[${idJSON}].push(${htmlEscapeJsonString(serializedCacheArgs)});`,
140
+ ];
141
+ return (
142
+ <script
143
+ key={count.current++}
144
+ nonce={props.nonce}
145
+ dangerouslySetInnerHTML={{
146
+ __html: html.join(''),
147
+ }}
148
+ />
149
+ );
150
+ });
151
+ // </server stuff>
152
+
153
+ // <client stuff>
154
+ // Setup and run the onEntries handler on the client only, but do it during
155
+ // the initial render so children have access to the data immediately
156
+ // This is important to avoid the client suspending during the initial render
157
+ // if the data has not yet been hydrated.
158
+ if (!isServer) {
159
+ const win = window as any;
160
+ if (!win[id]?.initialized) {
161
+ // Client: consume cache:
162
+ const onEntries = (...serializedEntries: Array<Serialized<TShape>>) => {
163
+ const entries = serializedEntries.map((serialized) =>
164
+ transformer.deserialize(serialized),
165
+ );
166
+ props.onEntries(entries);
167
+ };
168
+
169
+ const winStream: Array<Serialized<TShape>> = win[id] ?? [];
170
+
171
+ onEntries(...winStream);
172
+
173
+ // eslint-disable-next-line react-hooks/immutability
174
+ win[id] = {
175
+ initialized: true,
176
+ push: onEntries,
177
+ };
178
+ }
179
+ }
180
+ // </client stuff>
181
+
182
+ return (
183
+ <context.Provider value={{ stream, id }}>
184
+ {props.children}
185
+ </context.Provider>
186
+ );
187
+ }
188
+
189
+ return {
190
+ Provider: UseClientHydrationStreamProvider,
191
+ context,
192
+ };
193
+ }
@@ -0,0 +1,24 @@
1
+ // --------------------------------------------------------------------------------
2
+ //
3
+ // copied from
4
+ // https://github.com/vercel/next.js/blob/6bc07792a4462a4bf921a72ab30dc4ab2c4e1bda/packages/next/src/server/htmlescape.ts
5
+ // License: https://github.com/vercel/next.js/blob/6bc07792a4462a4bf921a72ab30dc4ab2c4e1bda/packages/next/license.md
6
+ //
7
+ // --------------------------------------------------------------------------------
8
+
9
+ // This utility is based on https://github.com/zertosh/htmlescape
10
+ // License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
11
+
12
+ const ESCAPE_LOOKUP: Record<string, string> = {
13
+ '&': '\\u0026',
14
+ '>': '\\u003e',
15
+ '<': '\\u003c',
16
+ '\u2028': '\\u2028',
17
+ '\u2029': '\\u2029',
18
+ };
19
+
20
+ export const ESCAPE_REGEX = /[&><\u2028\u2029]/g;
21
+
22
+ export function htmlEscapeJsonString(str: string): string {
23
+ return str.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]!);
24
+ }
@@ -0,0 +1,264 @@
1
+ 'use client';
2
+ import {
3
+ AuthState,
4
+ FrameworkClient,
5
+ InstantConfig,
6
+ InstantSchemaDef,
7
+ InstantUnknownSchema,
8
+ InstaQLResponse,
9
+ PageInfoResponse,
10
+ RuleParams,
11
+ User,
12
+ ValidQuery,
13
+ } from '@instantdb/core';
14
+ import { createContext, useContext, useRef, useState } from 'react';
15
+ import {
16
+ createHydrationStreamProvider,
17
+ isServer,
18
+ } from './HydrationStreamProvider.tsx';
19
+ import version from '../version.ts';
20
+
21
+ import InstantReactWebDatabase from '../InstantReactWebDatabase.ts';
22
+ import { InstantReactAbstractDatabase } from '@instantdb/react-common';
23
+
24
+ type InstantSuspenseProviderProps<
25
+ Schema extends InstantSchemaDef<any, any, any>,
26
+ > = {
27
+ nonce?: string;
28
+ children: React.ReactNode;
29
+ db?: InstantReactWebDatabase<Schema, any>;
30
+ config?: Omit<InstantConfig<any, any>, 'schema'> & {
31
+ schema: string;
32
+ };
33
+ user?: User | null;
34
+ };
35
+
36
+ const stream = createHydrationStreamProvider<any>();
37
+
38
+ type SuspenseQueryContextValue = {
39
+ useSuspenseQuery: (query: any, opts?: SuspenseQueryOpts) => any;
40
+ ssrUser: User | null | undefined;
41
+ };
42
+
43
+ const SuspsenseQueryContext = createContext<SuspenseQueryContextValue | null>(
44
+ null,
45
+ );
46
+
47
+ // Creates a typed useSuspense hook
48
+ export const createUseSuspenseQuery = <
49
+ Schema extends InstantSchemaDef<any, any, any>,
50
+ UseDates extends boolean,
51
+ >(
52
+ _db: InstantReactWebDatabase<Schema, UseDates>,
53
+ ): (<Q extends ValidQuery<Q, Schema>>(
54
+ q: Q,
55
+ opts?: {
56
+ ruleParams: RuleParams;
57
+ },
58
+ ) => {
59
+ data: InstaQLResponse<Schema, Q, NonNullable<UseDates>>;
60
+ pageInfo?: PageInfoResponse<Q>;
61
+ }) => {
62
+ return <Q extends ValidQuery<Q, Schema>>(q: any, opts: any) => {
63
+ const ctx = useContext(SuspsenseQueryContext);
64
+ if (!ctx) {
65
+ throw new Error(
66
+ 'useSuspenseQuery must be used within a SuspenseQueryProvider',
67
+ );
68
+ }
69
+ return ctx.useSuspenseQuery(q, opts) as any;
70
+ };
71
+ };
72
+
73
+ type SuspenseQueryOpts = {
74
+ ruleParams: RuleParams;
75
+ };
76
+
77
+ export const InstantSuspenseProvider = (
78
+ props: InstantSuspenseProviderProps<any>,
79
+ ) => {
80
+ const clientRef = useRef<FrameworkClient | null>(null);
81
+
82
+ if (!props.db) {
83
+ throw new Error(
84
+ 'Must provide either a db or config to InstantSuspenseProvider',
85
+ );
86
+ }
87
+
88
+ const db = useRef<InstantReactAbstractDatabase<any, any>>(props.db);
89
+
90
+ const [trackedKeys] = useState(() => new Set<string>());
91
+
92
+ if (!clientRef.current) {
93
+ if (props.user && !props.user.refresh_token) {
94
+ throw new Error(
95
+ 'User must have a refresh_token field. Recieved: ' +
96
+ JSON.stringify(props.user, null, 2),
97
+ );
98
+ }
99
+ clientRef.current = new FrameworkClient({
100
+ token: props.user?.refresh_token,
101
+ db: db.current.core,
102
+ });
103
+ }
104
+
105
+ if (isServer) {
106
+ clientRef.current.subscribe((result) => {
107
+ const { queryHash } = result;
108
+ trackedKeys.add(queryHash);
109
+ });
110
+ }
111
+
112
+ const useSuspenseQuery = (query: any, opts: SuspenseQueryOpts) => {
113
+ const nonSuspenseResult = db.current.useQuery(query, {
114
+ ...opts,
115
+ });
116
+
117
+ if (nonSuspenseResult.data) {
118
+ return {
119
+ data: nonSuspenseResult.data,
120
+ pageInfo: nonSuspenseResult.pageInfo,
121
+ };
122
+ }
123
+
124
+ // should never happen (typeguard)
125
+ if (!clientRef.current) {
126
+ throw new Error('Client ref not set up');
127
+ }
128
+
129
+ let entry = clientRef.current.getExistingResultForQuery(query, {
130
+ ruleParams: opts?.ruleParams,
131
+ });
132
+
133
+ if (!entry) {
134
+ entry = clientRef.current!.query(query, opts);
135
+ }
136
+
137
+ if (entry.status === 'pending') {
138
+ throw entry.promise;
139
+ }
140
+
141
+ if (entry.status === 'error') {
142
+ throw entry.error;
143
+ }
144
+
145
+ if (entry.status === 'success') {
146
+ const data = entry.data;
147
+ const result = clientRef.current.completeIsomorphic(
148
+ query,
149
+ data.triples,
150
+ data.attrs,
151
+ data.pageInfo,
152
+ );
153
+
154
+ return result;
155
+ }
156
+ };
157
+
158
+ return (
159
+ <SuspsenseQueryContext.Provider
160
+ value={{ useSuspenseQuery, ssrUser: props.user }}
161
+ >
162
+ <stream.Provider
163
+ nonce={props.nonce}
164
+ onFlush={() => {
165
+ const toSend: { queryKey: string; value: any }[] = [];
166
+ for (const [key, value] of clientRef.current!.resultMap.entries()) {
167
+ if (trackedKeys.has(key) && value.status === 'success') {
168
+ toSend.push({
169
+ queryKey: key,
170
+ value: value.data,
171
+ });
172
+ }
173
+ }
174
+
175
+ trackedKeys.clear();
176
+ return toSend;
177
+ }}
178
+ onEntries={(entries) => {
179
+ entries.forEach((entry) => {
180
+ clientRef.current!.addQueryResult(entry.queryKey, entry.value);
181
+ });
182
+ }}
183
+ >
184
+ {props.children}
185
+ </stream.Provider>
186
+ </SuspsenseQueryContext.Provider>
187
+ );
188
+ };
189
+
190
+ /**
191
+ *
192
+ * The first step: init your application!
193
+ *
194
+ * Visit https://instantdb.com/dash to get your `appId` :)
195
+ *
196
+ * @example
197
+ * import { init } from "@instantdb/react"
198
+ *
199
+ * const db = init({ appId: "my-app-id" })
200
+ *
201
+ * // You can also provide a schema for type safety and editor autocomplete!
202
+ *
203
+ * import { init } from "@instantdb/react"
204
+ * import schema from ""../instant.schema.ts";
205
+ *
206
+ * const db = init({ appId: "my-app-id", schema })
207
+ *
208
+ * // To learn more: https://instantdb.com/docs/modeling-data
209
+ */
210
+ export function init<
211
+ Schema extends InstantSchemaDef<any, any, any> = InstantUnknownSchema,
212
+ UseDates extends boolean = false,
213
+ >(
214
+ config: InstantConfig<Schema, UseDates>,
215
+ ): InstantNextDatabase<Schema, UseDates> {
216
+ return new InstantNextDatabase<Schema, UseDates>(config, {
217
+ '@instantdb/react': version,
218
+ });
219
+ }
220
+
221
+ export class InstantNextDatabase<
222
+ Schema extends InstantSchemaDef<any, any, any>,
223
+ UseDates extends boolean,
224
+ > extends InstantReactWebDatabase<Schema, UseDates> {
225
+ public useSuspenseQuery = <Q extends ValidQuery<Q, Schema>>(
226
+ q: Q,
227
+ opts?: {
228
+ ruleParams: RuleParams;
229
+ },
230
+ ): {
231
+ data: InstaQLResponse<Schema, Q, NonNullable<UseDates>>;
232
+ pageInfo?: PageInfoResponse<Q>;
233
+ } => {
234
+ const ctx = useContext(SuspsenseQueryContext);
235
+ if (!ctx) {
236
+ throw new Error(
237
+ 'useSuspenseQuery must be used within a SuspenseQueryProvider',
238
+ );
239
+ }
240
+ return ctx.useSuspenseQuery(q, opts) as any;
241
+ };
242
+
243
+ useAuth = (): AuthState => {
244
+ const ctx = useContext(SuspsenseQueryContext);
245
+ const realAuthResult = this._useAuth();
246
+ if (!ctx) {
247
+ return realAuthResult;
248
+ }
249
+
250
+ const { ssrUser } = ctx;
251
+ if (ssrUser === undefined) {
252
+ return realAuthResult;
253
+ }
254
+ if (realAuthResult.isLoading) {
255
+ return {
256
+ error: undefined,
257
+ isLoading: false,
258
+ user: ssrUser ?? undefined, // null -> undefined for the response
259
+ };
260
+ }
261
+
262
+ return realAuthResult;
263
+ };
264
+ }
package/tsconfig.json CHANGED
@@ -3,6 +3,7 @@
3
3
  "include": ["src"],
4
4
  "exclude": ["node_modules", "dist", "src/__types__"],
5
5
  "compilerOptions": {
6
+ "skipLibCheck": true,
6
7
  "outDir": "dist/tsc",
7
8
  "rewriteRelativeImportExtensions": true,
8
9
  "rootDir": "src",