@fidscript/instant-solidjs 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.
Files changed (43) hide show
  1. package/.tshy/build.json +8 -0
  2. package/.tshy/commonjs.json +16 -0
  3. package/.tshy/esm.json +15 -0
  4. package/dist/commonjs/InstantSolidDatabase.d.ts +185 -0
  5. package/dist/commonjs/InstantSolidDatabase.d.ts.map +1 -0
  6. package/dist/commonjs/InstantSolidDatabase.js +329 -0
  7. package/dist/commonjs/InstantSolidDatabase.js.map +1 -0
  8. package/dist/commonjs/InstantSolidRoom.d.ts +97 -0
  9. package/dist/commonjs/InstantSolidRoom.d.ts.map +1 -0
  10. package/dist/commonjs/InstantSolidRoom.js +209 -0
  11. package/dist/commonjs/InstantSolidRoom.js.map +1 -0
  12. package/dist/commonjs/index.d.ts +6 -0
  13. package/dist/commonjs/index.d.ts.map +1 -0
  14. package/dist/commonjs/index.js +23 -0
  15. package/dist/commonjs/index.js.map +1 -0
  16. package/dist/commonjs/package.json +3 -0
  17. package/dist/commonjs/version.d.ts +3 -0
  18. package/dist/commonjs/version.d.ts.map +1 -0
  19. package/dist/commonjs/version.js +5 -0
  20. package/dist/commonjs/version.js.map +1 -0
  21. package/dist/esm/InstantSolidDatabase.d.ts +185 -0
  22. package/dist/esm/InstantSolidDatabase.d.ts.map +1 -0
  23. package/dist/esm/InstantSolidDatabase.js +321 -0
  24. package/dist/esm/InstantSolidDatabase.js.map +1 -0
  25. package/dist/esm/InstantSolidRoom.d.ts +97 -0
  26. package/dist/esm/InstantSolidRoom.d.ts.map +1 -0
  27. package/dist/esm/InstantSolidRoom.js +200 -0
  28. package/dist/esm/InstantSolidRoom.js.map +1 -0
  29. package/dist/esm/index.d.ts +6 -0
  30. package/dist/esm/index.d.ts.map +1 -0
  31. package/dist/esm/index.js +18 -0
  32. package/dist/esm/index.js.map +1 -0
  33. package/dist/esm/package.json +3 -0
  34. package/dist/esm/version.d.ts +3 -0
  35. package/dist/esm/version.d.ts.map +1 -0
  36. package/dist/esm/version.js +3 -0
  37. package/dist/esm/version.js.map +1 -0
  38. package/package.json +47 -0
  39. package/src/InstantSolidDatabase.ts +463 -0
  40. package/src/InstantSolidRoom.ts +330 -0
  41. package/src/index.ts +204 -0
  42. package/src/version.ts +2 -0
  43. package/tsconfig.json +45 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InstantSolidRoom.js","sourceRoot":"","sources":["../../src/InstantSolidRoom.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AA6B7E,MAAM,CAAC,MAAM,0BAA0B,GAAG,KAAK,CAAC;AAEhD,SAAS;AACT,SAAS;AAET;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,cAAc,CAK5B,IAAiD,EACjD,KAAgB,EAChB,OAGQ;IAER,YAAY,CAAC,GAAG,EAAE;QAChB,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,cAAc,CAC7C,IAAI,CAAC,IAAI,EACT,IAAI,CAAC,EAAE,EACP,KAAK,EACL,CAAC,KAAU,EAAE,IAAS,EAAE,EAAE;YACxB,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QACvB,CAAC,CACF,CAAC;QAEF,SAAS,CAAC,KAAK,CAAC,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,eAAe,CAK7B,IAAiD,EACjD,KAAgB;IAEhB,YAAY,CAAC,GAAG,EAAE;QAChB,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAc,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC;QACxE,SAAS,CAAC,KAAK,CAAC,CAAC;IACnB,CAAC,CAAC,CAAC;IAEH,OAAO,CAAC,IAA+C,EA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AAC;IACnB,CAAC,CAAC,CAAC;IAEH,MAAM,SAAS,GAAG,CAAC,CAAgB,EAAE,EAAE;QACrC,MAAM,OAAO,GAAG,IAAI,EAAE,WAAW,IAAI,CAAC,CAAC,GAAG,KAAK,OAAO,CAAC;QACvD,MAAM,QAAQ,GAAG,CAAC,OAAO,CAAC;QAC1B,SAAS,CAAC,QAAQ,CAAC,CAAC;IACtB,CAAC,CAAC;IAEF,MAAM,MAAM,GAAG,GAAG,EAAE;QAClB,SAAS,CAAC,KAAK,CAAC,CAAC;IACnB,CAAC,CAAC;IAEF,OAAO;QACL,MAAM;QACN,SAAS;QACT,UAAU,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE;KAClC,CAAC;AACJ,CAAC;AAED,iBAAiB;AACjB,kBAAkB;AAElB,MAAM,CAAC,MAAM,KAAK,GAAG;IACnB,cAAc;IACd,eAAe;IACf,WAAW;IACX,eAAe;IACf,kBAAkB;CACnB,CAAC;AAEF,eAAe;AACf,QAAQ;AAER,MAAM,OAAO,gBAAgB;IAK3B,IAAI,CAAuC;IAC3C,IAAI,CAAW;IACf,EAAE,CAAS;IAEX,YACE,IAA0C,EAC1C,IAAc,EACd,EAAU;QAEV,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;IACf,CAAC;CACF","sourcesContent":["import {\n type PresenceOpts,\n type PresenceResponse,\n type RoomSchemaShape,\n InstantCoreDatabase,\n InstantSchemaDef,\n} from '@fidscript/instant-sdk';\n\nimport { createSignal, createEffect, onCleanup, createMemo } from 'solid-js';\nimport type { Accessor } from 'solid-js';\n\n// ------\n// Types\n\nexport type PresenceHandle<\n PresenceShape,\n Keys extends keyof PresenceShape,\n> = PresenceResponse<PresenceShape, Keys> & {\n publishPresence: (data: Partial<PresenceShape>) => void;\n};\n\nexport type TypingIndicatorOpts = {\n timeout?: number | null;\n stopOnEnter?: boolean;\n // Perf opt - `active` will always be an empty array\n writeOnly?: boolean;\n};\n\nexport type TypingIndicatorHandle<PresenceShape> = {\n active: Accessor<PresenceShape[]>;\n setActive(active: boolean): void;\n inputProps: {\n onKeyDown: (e: KeyboardEvent) => void;\n onBlur: () => void;\n };\n};\n\nexport const defaultActivityStopTimeout = 1_000;\n\n// ------\n// Topics\n\n/**\n * Listen for broadcasted events given a room and topic.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const room = db.room('chats', roomId);\n * db.rooms.useTopicEffect(room, 'emoji', (message, peer) => {\n * console.log(peer.name, 'sent', message);\n * });\n * // ...\n * }\n */\nexport function useTopicEffect<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n TopicType extends keyof RoomSchema[RoomType]['topics'],\n>(\n room: InstantSolidRoom<any, RoomSchema, RoomType>,\n topic: TopicType,\n onEvent: (\n event: RoomSchema[RoomType]['topics'][TopicType],\n peer: RoomSchema[RoomType]['presence'],\n ) => any,\n): void {\n createEffect(() => {\n const unsub = room.core._reactor.subscribeTopic(\n room.type,\n room.id,\n topic,\n (event: any, peer: any) => {\n onEvent(event, peer);\n },\n );\n\n onCleanup(unsub);\n });\n}\n\n/**\n * Broadcast an event to a room.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const room = db.room('chat', roomId);\n * const publishTopic = db.rooms.usePublishTopic(room, \"emoji\");\n *\n * return (\n * <button onClick={() => publishTopic({ emoji: \"🔥\" })}>Send emoji</button>\n * );\n * }\n *\n */\nexport function usePublishTopic<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n TopicType extends keyof RoomSchema[RoomType]['topics'],\n>(\n room: InstantSolidRoom<any, RoomSchema, RoomType>,\n topic: TopicType,\n): (data: RoomSchema[RoomType]['topics'][TopicType]) => void {\n createEffect(() => {\n const unsub = room.core._reactor.joinRoom(room.type as string, room.id);\n onCleanup(unsub);\n });\n\n return (data: RoomSchema[RoomType]['topics'][TopicType]) => {\n room.core._reactor.publishTopic({\n roomType: room.type,\n roomId: room.id,\n topic,\n data,\n });\n };\n}\n\n// ---------\n// Presence\n\n/**\n * Listen for peer's presence data in a room, and publish the current user's presence.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const presence = db.rooms.usePresence(room, { keys: [\"name\", \"avatar\"] });\n * // presence().peers, presence().isLoading, presence().publishPresence\n * }\n */\nexport function usePresence<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n Keys extends keyof RoomSchema[RoomType]['presence'],\n>(\n room: InstantSolidRoom<any, RoomSchema, RoomType>,\n opts: PresenceOpts<RoomSchema[RoomType]['presence'], Keys> = {},\n): Accessor<PresenceHandle<RoomSchema[RoomType]['presence'], Keys>> {\n const [state, setState] = createSignal<\n PresenceResponse<RoomSchema[RoomType]['presence'], Keys>\n >(\n (room.core._reactor.getPresence(room.type, room.id, opts) ?? {\n peers: {},\n isLoading: true,\n }) as PresenceResponse<RoomSchema[RoomType]['presence'], Keys>,\n );\n\n createEffect(() => {\n const unsub = room.core._reactor.subscribePresence(\n room.type,\n room.id,\n opts,\n (data: any) => {\n setState(data);\n },\n );\n\n onCleanup(unsub);\n });\n\n const publishPresence = (data: Partial<RoomSchema[RoomType]['presence']>) => {\n room.core._reactor.publishPresence(room.type, room.id, data);\n };\n\n return createMemo(() => ({\n ...state(),\n publishPresence,\n }));\n}\n\n/**\n * Publishes presence data to a room\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId, nickname }) {\n * const room = db.room('chat', roomId);\n * db.rooms.useSyncPresence(room, { nickname });\n * }\n */\nexport function useSyncPresence<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n>(\n room: InstantSolidRoom<any, RoomSchema, RoomType>,\n data: Partial<RoomSchema[RoomType]['presence']>,\n deps?: any[],\n): void {\n createEffect(() => {\n const unsub = room.core._reactor.joinRoom(\n room.type as string,\n room.id,\n data,\n );\n onCleanup(unsub);\n });\n\n createEffect(() => {\n // Track deps if provided, otherwise track serialized data\n if (deps) {\n deps.forEach((d) => (typeof d === 'function' ? d() : d));\n } else {\n JSON.stringify(data);\n }\n room.core._reactor.publishPresence(room.type, room.id, data);\n });\n}\n\n// -----------------\n// Typing Indicator\n\n/**\n * Manage typing indicator state\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const room = db.room('chat', roomId);\n * const typing = db.rooms.useTypingIndicator(room, \"chat-input\");\n * // typing.active(), typing.setActive(bool), typing.inputProps\n * }\n */\nexport function useTypingIndicator<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n>(\n room: InstantSolidRoom<any, RoomSchema, RoomType>,\n inputName: string,\n opts: TypingIndicatorOpts = {},\n): TypingIndicatorHandle<RoomSchema[RoomType]['presence']> {\n let timeoutId: ReturnType<typeof setTimeout> | null = null;\n\n const presence = rooms.usePresence(room, {\n keys: [inputName] as (keyof RoomSchema[RoomType]['presence'])[],\n });\n\n const active = createMemo(() => {\n if (opts?.writeOnly) return [];\n // Access presence to track it\n presence();\n const presenceSnapshot = room.core._reactor.getPresence(room.type, room.id);\n return Object.values(presenceSnapshot?.peers ?? {}).filter(\n (p: any) => p[inputName] === true,\n );\n });\n\n const setActive = (isActive: boolean) => {\n room.core._reactor.publishPresence(room.type, room.id, {\n [inputName]: isActive ? true : null,\n } as Partial<RoomSchema[RoomType]['presence']>);\n\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n\n if (!isActive) return;\n\n if (opts?.timeout === null || opts?.timeout === 0) return;\n\n timeoutId = setTimeout(() => {\n room.core._reactor.publishPresence(room.type, room.id, {\n [inputName]: null,\n } as Partial<RoomSchema[RoomType]['presence']>);\n }, opts?.timeout ?? defaultActivityStopTimeout);\n };\n\n onCleanup(() => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n timeoutId = null;\n }\n\n // Ensure we don't leave a sticky typing state behind on unmount,\n // even when opts.timeout is null/0 (i.e. no auto-timeout).\n setActive(false);\n });\n\n const onKeyDown = (e: KeyboardEvent) => {\n const isEnter = opts?.stopOnEnter && e.key === 'Enter';\n const isActive = !isEnter;\n setActive(isActive);\n };\n\n const onBlur = () => {\n setActive(false);\n };\n\n return {\n active,\n setActive,\n inputProps: { onKeyDown, onBlur },\n };\n}\n\n// --------------\n// Hooks namespace\n\nexport const rooms = {\n useTopicEffect,\n usePublishTopic,\n usePresence,\n useSyncPresence,\n useTypingIndicator,\n};\n\n// ------------\n// Class\n\nexport class InstantSolidRoom<\n Schema extends InstantSchemaDef<any, any, any>,\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n> {\n core: InstantCoreDatabase<Schema, boolean>;\n type: RoomType;\n id: string;\n\n constructor(\n core: InstantCoreDatabase<Schema, boolean>,\n type: RoomType,\n id: string,\n ) {\n this.core = core;\n this.type = type;\n this.id = id;\n }\n}\n"]}
@@ -0,0 +1,6 @@
1
+ import { id, tx, lookup, i, InstantAPIError, SyncTableCallbackEventType, type QueryResponse, type InstantQuery, type InstantQueryResult, type InstantSchema, type InstantObject, type InstantEntity, type InstantSchemaDatabase, type InstantUnknownSchemaDef, type IInstantDatabase, type User, type AuthState, type Query, type Config, type InstaQLParams, type ConnectionStatus, type ValidQuery, type PresencePeer, type AttrsDefs, type CardinalityKind, type DataAttrDef, type EntitiesDef, type EntitiesWithLinks, type EntityDef, type InstantGraph, type InstantConfig, type LinkAttrDef, type LinkDef, type LinksDef, type ResolveAttrs, type ValueTypes, type InstaQLEntity, type InstaQLFields, type InstaQLResult, type InstaQLEntitySubquery, type RoomsOf, type RoomsDef, type PresenceOf, type TopicsOf, type TopicOf, type RoomHandle, type TransactionChunk, type InstantUnknownSchema, type InstantSchemaDef, type BackwardsCompatibleSchema, type InstantRules, type UpdateParams, type LinkParams, type CreateParams, type CheckMagicCodeParams, type CheckMagicCodeResponse, type ExchangeCodeForTokenParams, type SendMagicCodeParams, type SendMagicCodeResponse, type SignInWithIdTokenParams, type VerifyMagicCodeParams, type VerifyResponse, type FileOpts, type UploadFileResponse, type DeleteFileResponse, type SyncTableCallback, type SyncTableCallbackEvent, type SyncTableInitialSyncBatch, type SyncTableInitialSyncComplete, type SyncTableSyncTransaction, type SyncTableLoadFromStorage, type SyncTableSetupError, StoreInterface, createInstantRouteHandler, type InstantRouteHandlerPayloadByType, type InstantRouteHandlerType, type InstantRouteHandlerBody, type StoreInterfaceStoreName, type Logger } from '@fidscript/instant-sdk';
2
+ import { InstantSolidDatabase } from './InstantSolidDatabase.js';
3
+ import { init } from './InstantSolidDatabase.js';
4
+ import { InstantSolidRoom } from './InstantSolidRoom.js';
5
+ export { id, tx, lookup, init, InstantSolidDatabase, InstantSolidRoom, i, InstantAPIError, SyncTableCallbackEventType, type Config, type InstantConfig, type InstantUnknownSchemaDef, type Query, type QueryResponse, type InstantObject, type User, type AuthState, type ConnectionStatus, type InstantQuery, type InstantQueryResult, type InstantSchema, type InstantEntity, type InstantSchemaDatabase, type IInstantDatabase, type InstaQLParams, type ValidQuery, type InstaQLFields, type PresencePeer, type AttrsDefs, type CardinalityKind, type DataAttrDef, type EntitiesDef, type EntitiesWithLinks, type EntityDef, type InstantGraph, type LinkAttrDef, type LinkDef, type LinksDef, type ResolveAttrs, type ValueTypes, type InstaQLEntity, type InstaQLResult, type InstaQLEntitySubquery, type RoomsOf, type RoomsDef, type TransactionChunk, type PresenceOf, type TopicsOf, type TopicOf, type RoomHandle, type InstantUnknownSchema, type InstantSchemaDef, type BackwardsCompatibleSchema, type InstantRules, type UpdateParams, type LinkParams, type CreateParams, type CheckMagicCodeParams, type CheckMagicCodeResponse, type ExchangeCodeForTokenParams, type SendMagicCodeParams, type SendMagicCodeResponse, type SignInWithIdTokenParams, type VerifyMagicCodeParams, type VerifyResponse, type FileOpts, type UploadFileResponse, type DeleteFileResponse, StoreInterface, type StoreInterfaceStoreName, type SyncTableCallback, type SyncTableCallbackEvent, type SyncTableInitialSyncBatch, type SyncTableInitialSyncComplete, type SyncTableSyncTransaction, type SyncTableLoadFromStorage, type SyncTableSetupError, createInstantRouteHandler, type InstantRouteHandlerPayloadByType, type InstantRouteHandlerType, type InstantRouteHandlerBody, type Logger, };
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,EAAE,EACF,EAAE,EACF,MAAM,EACN,CAAC,EAGD,eAAe,EAGf,0BAA0B,EAG1B,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,qBAAqB,EAC1B,KAAK,uBAAuB,EAC5B,KAAK,gBAAgB,EACrB,KAAK,IAAI,EACT,KAAK,SAAS,EACd,KAAK,KAAK,EACV,KAAK,MAAM,EACX,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,KAAK,UAAU,EAGf,KAAK,YAAY,EAGjB,KAAK,SAAS,EACd,KAAK,eAAe,EACpB,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,iBAAiB,EACtB,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,OAAO,EACZ,KAAK,QAAQ,EACb,KAAK,YAAY,EACjB,KAAK,UAAU,EACf,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,qBAAqB,EAC1B,KAAK,OAAO,EACZ,KAAK,QAAQ,EACb,KAAK,UAAU,EACf,KAAK,QAAQ,EACb,KAAK,OAAO,EACZ,KAAK,UAAU,EACf,KAAK,gBAAgB,EACrB,KAAK,oBAAoB,EACzB,KAAK,gBAAgB,EACrB,KAAK,yBAAyB,EAC9B,KAAK,YAAY,EACjB,KAAK,YAAY,EAC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Ae,EACpB,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,iBAAiB,EACtB,KAAK,SAAS,EACd,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,OAAO,EACZ,KAAK,QAAQ,EACb,KAAK,YAAY,EACjB,KAAK,UAAU,EACf,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,qBAAqB,EAC1B,KAAK,OAAO,EACZ,KAAK,QAAQ,EACb,KAAK,gBAAgB,EACrB,KAAK,UAAU,EACf,KAAK,QAAQ,EACb,KAAK,OAAO,EACZ,KAAK,UAAU,EACf,KAAK,oBAAoB,EACzB,KAAK,gBAAgB,EACrB,KAAK,yBAAyB,EAC9B,KAAK,YAAY,EACjB,KAAK,YAAY,EACjB,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,oBAAoB,EACzB,KAAK,sBAAsB,EAC3B,KAAK,0BAA0B,EAC/B,KAAK,mBAAmB,EACxB,KAAK,qBAAqB,EAC1B,KAAK,uBAAuB,EAC5B,KAAK,qBAAqB,EAC1B,KAAK,cAAc,EAGnB,KAAK,QAAQ,EACb,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EAGvB,cAAc,EACd,KAAK,uBAAuB,EAG5B,KAAK,iBAAiB,EACtB,KAAK,sBAAsB,EAC3B,KAAK,yBAAyB,EAC9B,KAAK,4BAA4B,EACjC,KAAK,wBAAwB,EAC7B,KAAK,wBAAwB,EAC7B,KAAK,mBAAmB,EAGxB,yBAAyB,EACzB,KAAK,gCAAgC,EACrC,KAAK,uBAAuB,EAC5B,KAAK,uBAAuB,EAG5B,KAAK,MAAM,GACZ,CAAC"}
@@ -0,0 +1,18 @@
1
+ import { id, tx, lookup, i,
2
+ // error
3
+ InstantAPIError,
4
+ // sync table enums
5
+ SyncTableCallbackEventType, StoreInterface, createInstantRouteHandler, } from '@fidscript/instant-sdk';
6
+ import { InstantSolidDatabase } from './InstantSolidDatabase.js';
7
+ import { init } from './InstantSolidDatabase.js';
8
+ import { InstantSolidRoom } from './InstantSolidRoom.js';
9
+ export { id, tx, lookup, init, InstantSolidDatabase, InstantSolidRoom, i,
10
+ // error
11
+ InstantAPIError,
12
+ // sync table enums
13
+ SyncTableCallbackEventType,
14
+ // custom store
15
+ StoreInterface,
16
+ // Server helper
17
+ createInstantRouteHandler, };
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,EAAE,EACF,EAAE,EACF,MAAM,EACN,CAAC;AAED,QAAQ;AACR,eAAe;AAEf,mBAAmB;AACnB,0BAA0B,EA6E1B,cAAc,EACd,yBAAyB,GAM1B,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAAE,IAAI,EAAE,MAAM,2BAA2B,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD,OAAO,EACL,EAAE,EACF,EAAE,EACF,MAAM,EACN,IAAI,EACJ,oBAAoB,EACpB,gBAAgB,EAChB,CAAC;AAED,QAAQ;AACR,eAAe;AAEf,mBAAmB;AACnB,0BAA0B;AAqE1B,eAAe;AACf,cAAc;AAYd,gBAAgB;AAChB,yBAAyB,GAO1B,CAAC","sourcesContent":["import {\n id,\n tx,\n lookup,\n i,\n\n // error\n InstantAPIError,\n\n // sync table enums\n SyncTableCallbackEventType,\n\n // types\n type QueryResponse,\n type InstantQuery,\n type InstantQueryResult,\n type InstantSchema,\n type InstantObject,\n type InstantEntity,\n type InstantSchemaDatabase,\n type InstantUnknownSchemaDef,\n type IInstantDatabase,\n type User,\n type AuthState,\n type Query,\n type Config,\n type InstaQLParams,\n type ConnectionStatus,\n type ValidQuery,\n\n // presence types\n type PresencePeer,\n\n // schema types\n type AttrsDefs,\n type CardinalityKind,\n type DataAttrDef,\n type EntitiesDef,\n type EntitiesWithLinks,\n type EntityDef,\n type InstantGraph,\n type InstantConfig,\n type LinkAttrDef,\n type LinkDef,\n type LinksDef,\n type ResolveAttrs,\n type ValueTypes,\n type InstaQLEntity,\n type InstaQLFields,\n type InstaQLResult,\n type InstaQLEntitySubquery,\n type RoomsOf,\n type RoomsDef,\n type PresenceOf,\n type TopicsOf,\n type TopicOf,\n type RoomHandle,\n type TransactionChunk,\n type InstantUnknownSchema,\n type InstantSchemaDef,\n type BackwardsCompatibleSchema,\n type InstantRules,\n type UpdateParams,\n type LinkParams,\n type CreateParams,\n type CheckMagicCodeParams,\n type CheckMagicCodeResponse,\n type ExchangeCodeForTokenParams,\n type SendMagicCodeParams,\n type SendMagicCodeResponse,\n type SignInWithIdTokenParams,\n type VerifyMagicCodeParams,\n type VerifyResponse,\n\n // storage types\n type FileOpts,\n type UploadFileResponse,\n type DeleteFileResponse,\n\n // sync table types\n type SyncTableCallback,\n type SyncTableCallbackEvent,\n type SyncTableInitialSyncBatch,\n type SyncTableInitialSyncComplete,\n type SyncTableSyncTransaction,\n type SyncTableLoadFromStorage,\n type SyncTableSetupError,\n StoreInterface,\n createInstantRouteHandler,\n type InstantRouteHandlerPayloadByType,\n type InstantRouteHandlerType,\n type InstantRouteHandlerBody,\n type StoreInterfaceStoreName,\n type Logger,\n} from '@fidscript/instant-sdk';\n\nimport { InstantSolidDatabase } from './InstantSolidDatabase.js';\nimport { init } from './InstantSolidDatabase.js';\nimport { InstantSolidRoom } from './InstantSolidRoom.js';\n\nexport {\n id,\n tx,\n lookup,\n init,\n InstantSolidDatabase,\n InstantSolidRoom,\n i,\n\n // error\n InstantAPIError,\n\n // sync table enums\n SyncTableCallbackEventType,\n\n // types\n type Config,\n type InstantConfig,\n type InstantUnknownSchemaDef,\n type Query,\n type QueryResponse,\n type InstantObject,\n type User,\n type AuthState,\n type ConnectionStatus,\n type InstantQuery,\n type InstantQueryResult,\n type InstantSchema,\n type InstantEntity,\n type InstantSchemaDatabase,\n type IInstantDatabase,\n type InstaQLParams,\n type ValidQuery,\n type InstaQLFields,\n\n // presence types\n type PresencePeer,\n\n // schema types\n type AttrsDefs,\n type CardinalityKind,\n type DataAttrDef,\n type EntitiesDef,\n type EntitiesWithLinks,\n type EntityDef,\n type InstantGraph,\n type LinkAttrDef,\n type LinkDef,\n type LinksDef,\n type ResolveAttrs,\n type ValueTypes,\n type InstaQLEntity,\n type InstaQLResult,\n type InstaQLEntitySubquery,\n type RoomsOf,\n type RoomsDef,\n type TransactionChunk,\n type PresenceOf,\n type TopicsOf,\n type TopicOf,\n type RoomHandle,\n type InstantUnknownSchema,\n type InstantSchemaDef,\n type BackwardsCompatibleSchema,\n type InstantRules,\n type UpdateParams,\n type LinkParams,\n type CreateParams,\n type CheckMagicCodeParams,\n type CheckMagicCodeResponse,\n type ExchangeCodeForTokenParams,\n type SendMagicCodeParams,\n type SendMagicCodeResponse,\n type SignInWithIdTokenParams,\n type VerifyMagicCodeParams,\n type VerifyResponse,\n\n // storage types\n type FileOpts,\n type UploadFileResponse,\n type DeleteFileResponse,\n\n // custom store\n StoreInterface,\n type StoreInterfaceStoreName,\n\n // sync table types\n type SyncTableCallback,\n type SyncTableCallbackEvent,\n type SyncTableInitialSyncBatch,\n type SyncTableInitialSyncComplete,\n type SyncTableSyncTransaction,\n type SyncTableLoadFromStorage,\n type SyncTableSetupError,\n\n // Server helper\n createInstantRouteHandler,\n type InstantRouteHandlerPayloadByType,\n type InstantRouteHandlerType,\n type InstantRouteHandlerBody,\n\n // logger\n type Logger,\n};\n"]}
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,3 @@
1
+ declare const version = "0.1.0";
2
+ export default version;
3
+ //# sourceMappingURL=version.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,QAAA,MAAM,OAAO,UAAU,CAAC;AACxB,eAAe,OAAO,CAAC"}
@@ -0,0 +1,3 @@
1
+ const version = '0.1.0';
2
+ export default version;
3
+ //# sourceMappingURL=version.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,GAAG,OAAO,CAAC;AACxB,eAAe,OAAO,CAAC","sourcesContent":["const version = '0.1.0';\nexport default version;\n"]}
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@fidscript/instant-solidjs",
3
+ "type": "module",
4
+ "version": "0.1.0",
5
+ "description": "FIDScript self-hosted InstantDB SolidJS SDK",
6
+ "license": "Apache-2.0",
7
+ "exports": {
8
+ "./package.json": "./package.json",
9
+ ".": {
10
+ "import": {
11
+ "types": "./dist/esm/index.d.ts",
12
+ "default": "./dist/esm/index.js"
13
+ },
14
+ "require": {
15
+ "types": "./dist/commonjs/index.d.ts",
16
+ "default": "./dist/commonjs/index.js"
17
+ }
18
+ }
19
+ },
20
+ "tshy": {
21
+ "selfLink": false,
22
+ "main": true,
23
+ "module": true,
24
+ "project": "./tsconfig.json",
25
+ "exports": {
26
+ "./package.json": "./package.json",
27
+ ".": "./src/index.ts"
28
+ }
29
+ },
30
+ "main": "./dist/commonjs/index.js",
31
+ "types": "./dist/commonjs/index.d.ts",
32
+ "module": "./dist/esm/index.js",
33
+ "scripts": {
34
+ "build": "rm -rf dist .tshy-build; tshy",
35
+ "check": "tsc --noEmit"
36
+ },
37
+ "devDependencies": {
38
+ "tshy": "^3.0.2",
39
+ "typescript": "^5.0.0"
40
+ },
41
+ "peerDependencies": {
42
+ "solid-js": ">=1.0.0"
43
+ },
44
+ "dependencies": {
45
+ "@fidscript/instant-sdk": "^0.1.1"
46
+ }
47
+ }
@@ -0,0 +1,463 @@
1
+ import {
2
+ // types
3
+ type AuthState,
4
+ type User,
5
+ type ConnectionStatus,
6
+ type TransactionChunk,
7
+ type RoomSchemaShape,
8
+ type InstaQLOptions,
9
+ type InstantConfig,
10
+ type PageInfoResponse,
11
+ type InstaQLLifecycleState,
12
+ type InstaQLResponse,
13
+ type InfiniteQuerySubscription,
14
+ type ValidQuery,
15
+ // classes
16
+ Auth,
17
+ Storage,
18
+ Streams,
19
+ txInit,
20
+ InstantCoreDatabase,
21
+ init as core_init,
22
+ coerceQuery,
23
+ getInfiniteQueryInitialSnapshot,
24
+ InstantSchemaDef,
25
+ RoomsOf,
26
+ InstantError,
27
+ IInstantDatabase,
28
+ } from '@fidscript/instant-sdk';
29
+
30
+ import { createSignal, createEffect, onCleanup, createMemo } from 'solid-js';
31
+ import type { Accessor } from 'solid-js';
32
+
33
+ import { InstantSolidRoom, rooms } from './InstantSolidRoom.js';
34
+ import version from './version.js';
35
+
36
+ const defaultState = {
37
+ isLoading: true,
38
+ data: undefined,
39
+ pageInfo: undefined,
40
+ error: undefined,
41
+ } as const;
42
+
43
+ export type InfiniteQueryState<
44
+ Schema extends InstantSchemaDef<any, any, any>,
45
+ Q extends ValidQuery<Q, Schema>,
46
+ UseDates extends boolean,
47
+ > = {
48
+ isLoading: boolean;
49
+ error: { message: string } | undefined;
50
+ data: InstaQLResponse<Schema, Q, UseDates> | undefined;
51
+ canLoadNextPage: boolean;
52
+ loadNextPage: () => void;
53
+ };
54
+
55
+ const defaultAuthState: AuthState = {
56
+ isLoading: true,
57
+ user: undefined,
58
+ error: undefined,
59
+ };
60
+
61
+ function stateForResult(result: any) {
62
+ return {
63
+ isLoading: !Boolean(result),
64
+ data: undefined,
65
+ pageInfo: undefined,
66
+ error: undefined,
67
+ ...(result ? result : {}),
68
+ };
69
+ }
70
+
71
+ export class InstantSolidDatabase<
72
+ Schema extends InstantSchemaDef<any, any, any>,
73
+ UseDates extends boolean = false,
74
+ Rooms extends RoomSchemaShape = RoomsOf<Schema>,
75
+ > implements IInstantDatabase<Schema>
76
+ {
77
+ public tx = txInit<Schema>();
78
+
79
+ public auth: Auth;
80
+ public storage: Storage;
81
+ public streams: Streams;
82
+ public core: InstantCoreDatabase<Schema, UseDates>;
83
+
84
+ constructor(core: InstantCoreDatabase<Schema, UseDates>) {
85
+ this.core = core;
86
+ this.auth = this.core.auth;
87
+ this.storage = this.core.storage;
88
+ this.streams = this.core.streams;
89
+ }
90
+
91
+ /**
92
+ * Returns a unique ID for a given `name`. It's stored in local storage,
93
+ * so you will get the same ID across sessions.
94
+ *
95
+ * @example
96
+ * const deviceId = await db.getLocalId('device');
97
+ */
98
+ getLocalId = (name: string): Promise<string> => {
99
+ return this.core.getLocalId(name);
100
+ };
101
+
102
+ /**
103
+ * Use this to write data! You can create, update, delete, and link objects
104
+ *
105
+ * @see https://instantdb.com/docs/instaml
106
+ *
107
+ * @example
108
+ * const goalId = id();
109
+ * db.transact(db.tx.goals[goalId].update({title: "Get fit"}))
110
+ */
111
+ transact = (
112
+ chunks: TransactionChunk<any, any> | TransactionChunk<any, any>[],
113
+ ) => {
114
+ return this.core.transact(chunks);
115
+ };
116
+
117
+ /**
118
+ * One time query for the logged in state.
119
+ *
120
+ * @see https://instantdb.com/docs/auth
121
+ * @example
122
+ * const user = await db.getAuth();
123
+ * console.log('logged in as', user.email)
124
+ */
125
+ getAuth(): Promise<User | null> {
126
+ return this.core.getAuth();
127
+ }
128
+
129
+ /**
130
+ * Use this for one-off queries.
131
+ * Returns local data if available, otherwise fetches from the server.
132
+ *
133
+ * @see https://instantdb.com/docs/instaql
134
+ *
135
+ * @example
136
+ * const resp = await db.queryOnce({ goals: {} });
137
+ * console.log(resp.data.goals)
138
+ */
139
+ queryOnce = <Q extends ValidQuery<Q, Schema>>(
140
+ query: Q,
141
+ opts?: InstaQLOptions,
142
+ ): Promise<{
143
+ data: InstaQLResponse<Schema, Q, UseDates>;
144
+ pageInfo: PageInfoResponse<Q>;
145
+ }> => {
146
+ return this.core.queryOnce(query, opts);
147
+ };
148
+
149
+ // -----------
150
+ // Solid reactive hooks
151
+
152
+ /**
153
+ * Use this to query your data!
154
+ *
155
+ * @see https://instantdb.com/docs/instaql
156
+ *
157
+ * @example
158
+ * const state = db.useQuery({ goals: {} });
159
+ * // state().isLoading, state().error, state().data
160
+ */
161
+ useQuery = <Q extends ValidQuery<Q, Schema>>(
162
+ query: (() => null | Q) | null | Q,
163
+ opts?: InstaQLOptions,
164
+ ): Accessor<InstaQLLifecycleState<Schema, Q, UseDates>> => {
165
+ const [state, setState] = createSignal<
166
+ InstaQLLifecycleState<Schema, Q, UseDates>
167
+ >(defaultState as InstaQLLifecycleState<Schema, Q, UseDates>);
168
+
169
+ createEffect(() => {
170
+ const resolvedQuery = typeof query === 'function' ? query() : query;
171
+
172
+ if (!resolvedQuery) {
173
+ setState(
174
+ () => defaultState as InstaQLLifecycleState<Schema, Q, UseDates>,
175
+ );
176
+ return;
177
+ }
178
+
179
+ let q = resolvedQuery;
180
+ if (opts && 'ruleParams' in opts) {
181
+ q = { $$ruleParams: (opts as any)['ruleParams'], ...q };
182
+ }
183
+
184
+ const coerced = coerceQuery(q);
185
+ const prev = this.core._reactor.getPreviousResult(coerced);
186
+ if (prev) {
187
+ setState(
188
+ () =>
189
+ stateForResult(prev) as InstaQLLifecycleState<Schema, Q, UseDates>,
190
+ );
191
+ }
192
+
193
+ const unsub = this.core.subscribeQuery<Q, UseDates>(coerced, (result) => {
194
+ setState(
195
+ () =>
196
+ Object.assign(
197
+ {
198
+ isLoading: false,
199
+ data: undefined,
200
+ pageInfo: undefined,
201
+ error: undefined,
202
+ },
203
+ result,
204
+ ) as InstaQLLifecycleState<Schema, Q, UseDates>,
205
+ );
206
+ });
207
+
208
+ onCleanup(unsub);
209
+ });
210
+
211
+ return state;
212
+ };
213
+
214
+ /**
215
+ * Subscribe to a query and incrementally load more items.
216
+ *
217
+ * Only one top level namespace in the query is allowed.
218
+ *
219
+ * @see https://instantdb.com/docs/instaql
220
+ *
221
+ * @example
222
+ * const state = db.useInfiniteQuery({
223
+ * posts: {
224
+ * $: {
225
+ * limit: 20,
226
+ * order: { createdAt: 'desc' },
227
+ * },
228
+ * },
229
+ * });
230
+ * // state().data, state().isLoading, state().error,
231
+ * // state().canLoadNextPage, state().loadNextPage()
232
+ */
233
+ useInfiniteQuery = <Q extends ValidQuery<Q, Schema>>(
234
+ query: (() => null | Q) | null | Q,
235
+ opts?: InstaQLOptions,
236
+ ): Accessor<InfiniteQueryState<Schema, Q, UseDates>> => {
237
+ let sub: InfiniteQuerySubscription | null = null;
238
+ const loadNextPage = () => sub?.loadNextPage();
239
+
240
+ const [state, setState] = createSignal<
241
+ InfiniteQueryState<Schema, Q, UseDates>
242
+ >({
243
+ isLoading: true,
244
+ error: undefined,
245
+ data: undefined,
246
+ canLoadNextPage: false,
247
+ loadNextPage,
248
+ });
249
+
250
+ createEffect(() => {
251
+ const resolvedQuery = typeof query === 'function' ? query() : query;
252
+
253
+ if (!resolvedQuery) {
254
+ sub = null;
255
+ setState(() => ({
256
+ isLoading: true,
257
+ error: undefined,
258
+ data: undefined,
259
+ canLoadNextPage: false,
260
+ loadNextPage,
261
+ }));
262
+ return;
263
+ }
264
+
265
+ const snapshot = getInfiniteQueryInitialSnapshot<Schema, Q, UseDates>(
266
+ this.core,
267
+ resolvedQuery,
268
+ opts,
269
+ );
270
+ setState(() => ({
271
+ ...snapshot,
272
+ isLoading: !snapshot.data && !snapshot.error,
273
+ loadNextPage,
274
+ }));
275
+
276
+ sub = this.core.subscribeInfiniteQuery<Q>(
277
+ resolvedQuery,
278
+ (resp) => {
279
+ setState(() => ({
280
+ ...resp,
281
+ isLoading: false,
282
+ loadNextPage,
283
+ }));
284
+ },
285
+ opts,
286
+ );
287
+
288
+ onCleanup(() => {
289
+ sub?.unsubscribe();
290
+ sub = null;
291
+ });
292
+ });
293
+
294
+ return state;
295
+ };
296
+
297
+ /**
298
+ * Listen for the logged in state. This is useful
299
+ * for deciding when to show a login screen.
300
+ *
301
+ * @see https://instantdb.com/docs/auth
302
+ * @example
303
+ * function App() {
304
+ * const auth = db.useAuth();
305
+ * // auth().isLoading, auth().user, auth().error
306
+ * }
307
+ */
308
+ useAuth = (): Accessor<AuthState> => {
309
+ const [state, setState] = createSignal<AuthState>(
310
+ this.core._reactor._currentUserCached ?? defaultAuthState,
311
+ );
312
+
313
+ createEffect(() => {
314
+ const unsub = this.core.subscribeAuth((auth) => {
315
+ setState({ isLoading: false, ...auth });
316
+ });
317
+
318
+ onCleanup(unsub);
319
+ });
320
+
321
+ return state;
322
+ };
323
+
324
+ /**
325
+ * Subscribe to the currently logged in user.
326
+ * If the user is not logged in, this will throw an Error.
327
+ *
328
+ * @see https://instantdb.com/docs/auth
329
+ * @example
330
+ * function UserDisplay() {
331
+ * const user = db.useUser();
332
+ * return <div>Logged in as: {user().email}</div>
333
+ * }
334
+ */
335
+ useUser = (): Accessor<User> => {
336
+ const auth = this.useAuth();
337
+ return createMemo(() => {
338
+ const { user } = auth();
339
+ if (!user) {
340
+ throw new InstantError(
341
+ 'useUser must be used within an auth-protected route',
342
+ );
343
+ }
344
+ return user;
345
+ });
346
+ };
347
+
348
+ /**
349
+ * Listen for connection status changes to Instant.
350
+ *
351
+ * @see https://www.instantdb.com/docs/patterns#connection-status
352
+ * @example
353
+ * function App() {
354
+ * const status = db.useConnectionStatus();
355
+ * return <div>Connection state: {status()}</div>
356
+ * }
357
+ */
358
+ useConnectionStatus = (): Accessor<ConnectionStatus> => {
359
+ const [status, setStatus] = createSignal<ConnectionStatus>(
360
+ this.core._reactor.status as ConnectionStatus,
361
+ );
362
+
363
+ createEffect(() => {
364
+ const unsub = this.core.subscribeConnectionStatus((newStatus) => {
365
+ setStatus(() => newStatus);
366
+ });
367
+
368
+ onCleanup(unsub);
369
+ });
370
+
371
+ return status;
372
+ };
373
+
374
+ /**
375
+ * A hook that returns a unique ID for a given `name`. localIds are
376
+ * stored in local storage, so you will get the same ID across sessions.
377
+ *
378
+ * Initially returns `null`, and then loads the localId.
379
+ *
380
+ * @example
381
+ * const deviceId = db.useLocalId('device');
382
+ * // deviceId() is null initially, then the ID string
383
+ */
384
+ useLocalId = (name: string): Accessor<string | null> => {
385
+ const [localId, setLocalId] = createSignal<string | null>(null);
386
+
387
+ createEffect(() => {
388
+ let mounted = true;
389
+ this.getLocalId(name).then((id) => {
390
+ if (mounted) {
391
+ setLocalId(() => id);
392
+ }
393
+ });
394
+ onCleanup(() => {
395
+ mounted = false;
396
+ });
397
+ });
398
+
399
+ return localId;
400
+ };
401
+
402
+ /**
403
+ * Obtain a handle to a room, which allows you to listen to topics and presence data
404
+ *
405
+ * @see https://instantdb.com/docs/presence-and-topics
406
+ *
407
+ * @example
408
+ * const room = db.room('chat', roomId);
409
+ * const presence = db.rooms.usePresence(room);
410
+ */
411
+ room<RoomType extends keyof Rooms>(
412
+ type: RoomType = '_defaultRoomType' as RoomType,
413
+ id: string = '_defaultRoomId',
414
+ ) {
415
+ return new InstantSolidRoom<Schema, Rooms, RoomType>(this.core, type, id);
416
+ }
417
+
418
+ /**
419
+ * Hooks for working with rooms
420
+ *
421
+ * @see https://instantdb.com/docs/presence-and-topics
422
+ *
423
+ * @example
424
+ * const room = db.room('chat', roomId);
425
+ * const presence = db.rooms.usePresence(room);
426
+ * const publish = db.rooms.usePublishTopic(room, 'emoji');
427
+ */
428
+ rooms = rooms;
429
+ }
430
+
431
+ // -----------
432
+ // init
433
+
434
+ /**
435
+ * The first step: init your application!
436
+ *
437
+ * Visit https://instantdb.com/dash to get your `appId` :)
438
+ *
439
+ * @example
440
+ * import { init } from "@instantdb/solidjs"
441
+ *
442
+ * const db = init({ appId: "my-app-id" })
443
+ *
444
+ * // You can also provide a schema for type safety and editor autocomplete!
445
+ *
446
+ * import { init } from "@instantdb/solidjs"
447
+ * import schema from "../instant.schema.ts";
448
+ *
449
+ * const db = init({ appId: "my-app-id", schema })
450
+ */
451
+ export function init<
452
+ Schema extends InstantSchemaDef<any, any, any>,
453
+ UseDates extends boolean = false,
454
+ >(
455
+ config: Omit<InstantConfig<Schema, UseDates>, 'useDateObjects'> & {
456
+ useDateObjects?: UseDates;
457
+ },
458
+ ): InstantSolidDatabase<Schema, UseDates> {
459
+ const coreDb = core_init<Schema, UseDates>(config, undefined, undefined, {
460
+ '@instantdb/solidjs': version,
461
+ });
462
+ return new InstantSolidDatabase<Schema, UseDates>(coreDb);
463
+ }