@instantdb/core 0.22.97 → 0.22.98-experimental.drewh-ts-target.20762041587.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.
- package/dist/commonjs/Connection.js +50 -51
- package/dist/commonjs/Connection.js.map +1 -1
- package/dist/commonjs/InMemoryStorage.js +13 -32
- package/dist/commonjs/InMemoryStorage.js.map +1 -1
- package/dist/commonjs/IndexedDBStorage.js +193 -217
- package/dist/commonjs/IndexedDBStorage.js.map +1 -1
- package/dist/commonjs/InstantError.js +1 -0
- package/dist/commonjs/InstantError.js.map +1 -1
- package/dist/commonjs/Reactor.js +566 -610
- package/dist/commonjs/Reactor.js.map +1 -1
- package/dist/commonjs/StorageAPI.js +51 -70
- package/dist/commonjs/StorageAPI.js.map +1 -1
- package/dist/commonjs/SyncTable.js +68 -81
- package/dist/commonjs/SyncTable.js.map +1 -1
- package/dist/commonjs/WindowNetworkListener.js +2 -13
- package/dist/commonjs/WindowNetworkListener.js.map +1 -1
- package/dist/commonjs/__types__/fieldsTypeTest.js +8 -16
- package/dist/commonjs/__types__/fieldsTypeTest.js.map +1 -1
- package/dist/commonjs/__types__/useDatesTypeTest.js +3 -6
- package/dist/commonjs/__types__/useDatesTypeTest.js.map +1 -1
- package/dist/commonjs/authAPI.js +62 -79
- package/dist/commonjs/authAPI.js.map +1 -1
- package/dist/commonjs/createRouteHandler.js +5 -15
- package/dist/commonjs/createRouteHandler.js.map +1 -1
- package/dist/commonjs/datalog.js +1 -1
- package/dist/commonjs/datalog.js.map +1 -1
- package/dist/commonjs/devtool.js +26 -8
- package/dist/commonjs/devtool.js.map +1 -1
- package/dist/commonjs/framework.d.ts.map +1 -1
- package/dist/commonjs/framework.js +142 -152
- package/dist/commonjs/framework.js.map +1 -1
- package/dist/commonjs/index.js +204 -190
- package/dist/commonjs/index.js.map +1 -1
- package/dist/commonjs/instaml.js +44 -30
- package/dist/commonjs/instaml.js.map +1 -1
- package/dist/commonjs/instaql.js +25 -33
- package/dist/commonjs/instaql.js.map +1 -1
- package/dist/commonjs/parseSchemaFromJSON.js +6 -7
- package/dist/commonjs/parseSchemaFromJSON.js.map +1 -1
- package/dist/commonjs/presence.js +7 -8
- package/dist/commonjs/presence.js.map +1 -1
- package/dist/commonjs/queryValidation.js +1 -2
- package/dist/commonjs/queryValidation.js.map +1 -1
- package/dist/commonjs/schema.js +8 -6
- package/dist/commonjs/schema.js.map +1 -1
- package/dist/commonjs/schemaTypes.js +22 -3
- package/dist/commonjs/schemaTypes.js.map +1 -1
- package/dist/commonjs/store.js +29 -38
- package/dist/commonjs/store.js.map +1 -1
- package/dist/commonjs/transactionValidation.js +1 -2
- package/dist/commonjs/transactionValidation.js.map +1 -1
- package/dist/commonjs/utils/Deferred.js +3 -0
- package/dist/commonjs/utils/Deferred.js.map +1 -1
- package/dist/commonjs/utils/PersistedObject.js +216 -233
- package/dist/commonjs/utils/PersistedObject.js.map +1 -1
- package/dist/commonjs/utils/fetch.js +9 -19
- package/dist/commonjs/utils/fetch.js.map +1 -1
- package/dist/commonjs/utils/linkIndex.js +2 -4
- package/dist/commonjs/utils/linkIndex.js.map +1 -1
- package/dist/commonjs/utils/object.js +1 -1
- package/dist/commonjs/utils/object.js.map +1 -1
- package/dist/esm/Connection.js +50 -51
- package/dist/esm/Connection.js.map +1 -1
- package/dist/esm/InMemoryStorage.js +13 -32
- package/dist/esm/InMemoryStorage.js.map +1 -1
- package/dist/esm/IndexedDBStorage.js +193 -217
- package/dist/esm/IndexedDBStorage.js.map +1 -1
- package/dist/esm/InstantError.js +1 -0
- package/dist/esm/InstantError.js.map +1 -1
- package/dist/esm/Reactor.js +566 -610
- package/dist/esm/Reactor.js.map +1 -1
- package/dist/esm/StorageAPI.js +51 -70
- package/dist/esm/StorageAPI.js.map +1 -1
- package/dist/esm/SyncTable.js +68 -81
- package/dist/esm/SyncTable.js.map +1 -1
- package/dist/esm/WindowNetworkListener.js +2 -13
- package/dist/esm/WindowNetworkListener.js.map +1 -1
- package/dist/esm/__types__/fieldsTypeTest.js +8 -16
- package/dist/esm/__types__/fieldsTypeTest.js.map +1 -1
- package/dist/esm/__types__/useDatesTypeTest.js +3 -6
- package/dist/esm/__types__/useDatesTypeTest.js.map +1 -1
- package/dist/esm/authAPI.js +62 -79
- package/dist/esm/authAPI.js.map +1 -1
- package/dist/esm/createRouteHandler.js +5 -15
- package/dist/esm/createRouteHandler.js.map +1 -1
- package/dist/esm/datalog.js +1 -1
- package/dist/esm/datalog.js.map +1 -1
- package/dist/esm/devtool.js +26 -8
- package/dist/esm/devtool.js.map +1 -1
- package/dist/esm/framework.d.ts.map +1 -1
- package/dist/esm/framework.js +142 -152
- package/dist/esm/framework.js.map +1 -1
- package/dist/esm/index.js +204 -190
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/instaml.js +44 -30
- package/dist/esm/instaml.js.map +1 -1
- package/dist/esm/instaql.js +25 -33
- package/dist/esm/instaql.js.map +1 -1
- package/dist/esm/parseSchemaFromJSON.js +6 -7
- package/dist/esm/parseSchemaFromJSON.js.map +1 -1
- package/dist/esm/presence.js +7 -8
- package/dist/esm/presence.js.map +1 -1
- package/dist/esm/queryValidation.js +1 -2
- package/dist/esm/queryValidation.js.map +1 -1
- package/dist/esm/schema.js +8 -6
- package/dist/esm/schema.js.map +1 -1
- package/dist/esm/schemaTypes.js +22 -3
- package/dist/esm/schemaTypes.js.map +1 -1
- package/dist/esm/store.js +29 -38
- package/dist/esm/store.js.map +1 -1
- package/dist/esm/transactionValidation.js +1 -2
- package/dist/esm/transactionValidation.js.map +1 -1
- package/dist/esm/utils/Deferred.js +3 -0
- package/dist/esm/utils/Deferred.js.map +1 -1
- package/dist/esm/utils/PersistedObject.js +216 -233
- package/dist/esm/utils/PersistedObject.js.map +1 -1
- package/dist/esm/utils/fetch.js +9 -19
- package/dist/esm/utils/fetch.js.map +1 -1
- package/dist/esm/utils/linkIndex.js +2 -4
- package/dist/esm/utils/linkIndex.js.map +1 -1
- package/dist/esm/utils/object.js +1 -1
- package/dist/esm/utils/object.js.map +1 -1
- package/dist/standalone/index.js +2610 -2367
- package/dist/standalone/index.umd.cjs +3 -3
- package/package.json +2 -2
- package/src/framework.ts +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;;AAq4BE,oBAAI;AAqBJ,kCAAW;AA15Bb,8DAAmC;AACnC,6CAOsB;AAg4BpB,mFAt4BA,eAAE,OAs4BA;AACF,uFAt4BA,mBAAM,OAs4BA;AACN,uFAt4BA,mBAAM,OAs4BA;AAeN,uFAp5BA,mBAAM,OAo5BA;AAh5BR,sEAA2C;AAk5BzC,mBAl5BK,qBAAQ,CAk5BL;AAj5BV,0DAA+B;AA63B7B,aA73BK,eAAE,CA63BL;AA53BJ,gFAAqD;AAk5BnD,2BAl5BK,6BAAgB,CAk5BL;AAj5BlB,+CAAgD;AAg5B9C,6FAh5BO,uBAAY,OAg5BP;AA/4Bd,0FAA+D;AAi5B7D,gCAj5BK,kCAAqB,CAi5BL;AAh5BvB,2CAAgC;AAw4B9B,kFAx4BO,aAAC,OAw4BP;AAv4BH,6CAA6C;AAC7C,8DAAmC;AAk5BjC,kBAl5BK,oBAAO,CAk5BL;AAj5BT,6DAA2E;AA03BzE,8FA13BO,kCAAa,OA03BP;AACb,qGA33BsB,yCAAoB,OA23BtB;AA13BtB,yEAGoC;AAw3BlC,qGA13BA,+CAAoB,OA03BA;AAEpB,2GA33BA,qDAA0B,OA23BA;AAx3B5B,mEAGoC;AAy/BlC,iGA3/BA,qCAAgB,OA2/BA;AAx/BlB,mEAAoE;AA0/BlE,0GA1/BO,iDAAyB,OA0/BP;AAz/B3B,qEAA+D;AAk3B7D,oGAl3BO,4CAAmB,OAk3BP;AAlyBrB,iDAAuE;AAoyBrE,gGApyBO,8BAAe,OAoyBP;AAzxBjB,+CAAsE;AA4xBpE,gGA5xBO,0BAAe,OA4xBP;AA3xBjB,u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ransactionChunk,\n} from './instatx.js';\nimport weakHash from './utils/weakHash.js';\nimport id from './utils/id.ts';\nimport IndexedDBStorage from './IndexedDBStorage.ts';\nimport { coerceToDate } from './utils/dates.js';\nimport WindowNetworkListener from './WindowNetworkListener.js';\nimport { i } from './schema.js';\nimport { createDevtool } from './devtool.js';\nimport version from './version.ts';\nimport { validateQuery, QueryValidationError } from './queryValidation.ts';\nimport {\n validateTransactions,\n TransactionValidationError,\n} from './transactionValidation.ts';\n\nimport {\n StorageInterface,\n type StorageInterfaceStoreName,\n} from './utils/PersistedObject.ts';\nimport { createInstantRouteHandler } from './createRouteHandler.ts';\nimport { parseSchemaFromJSON } from './parseSchemaFromJSON.ts';\n\nimport type {\n PresenceOpts,\n PresenceResponse,\n PresenceSlice,\n RoomSchemaShape,\n} from './presence.ts';\nimport type {\n DevtoolConfig,\n IDatabase,\n IInstantDatabase,\n StrictDevtoolConfig,\n} from './coreTypes.ts';\nimport type {\n Query,\n QueryResponse,\n InstaQLResponse,\n PageInfoResponse,\n Exactly,\n InstantObject,\n InstaQLParams,\n InstaQLOptions,\n InstaQLQueryParams,\n InstaQLEntity,\n InstaQLEntitySubquery,\n InstaQLResult,\n InstaQLFields,\n ValidQuery,\n} from './queryTypes.ts';\nimport type { PresencePeer } from './presenceTypes.ts';\nimport type {\n AuthState,\n User,\n AuthResult,\n ConnectionStatus,\n} from './clientTypes.ts';\nimport type {\n InstantQuery,\n InstantQueryResult,\n InstantSchema,\n InstantEntity,\n InstantSchemaDatabase,\n} from './helperTypes.ts';\nimport type {\n InstantDBAttr,\n InstantDBAttrOnDelete,\n InstantDBCheckedDataType,\n InstantDBIdent,\n InstantDBInferredType,\n} from './attrTypes.ts';\nimport type {\n AttrsDefs,\n CardinalityKind,\n DataAttrDef,\n EntitiesDef,\n EntitiesWithLinks,\n EntityDef,\n RoomsDef,\n InstantSchemaDef,\n InstantGraph,\n LinkAttrDef,\n LinkDef,\n LinksDef,\n PresenceOf,\n ResolveAttrs,\n RoomsOf,\n TopicsOf,\n TopicOf,\n ValueTypes,\n InstantUnknownSchema,\n InstantUnknownSchemaDef,\n BackwardsCompatibleSchema,\n UpdateParams,\n LinkParams,\n CreateParams,\n RuleParams,\n} from './schemaTypes.ts';\nimport type { InstantRules } from './rulesTypes.ts';\nimport type { UploadFileResponse, DeleteFileResponse } from './StorageAPI.ts';\nimport { FrameworkClient, type FrameworkConfig } from './framework.ts';\n\nimport type {\n ExchangeCodeForTokenParams,\n SendMagicCodeParams,\n SendMagicCodeResponse,\n SignInWithIdTokenParams,\n VerifyMagicCodeParams,\n VerifyResponse,\n} from './authAPI.ts';\n\nimport { InstantAPIError, type InstantIssue } from './utils/fetch.js';\nimport { InstantError } from './InstantError.ts';\nimport { EventSourceType } from './Connection.ts';\nimport { CallbackEventType as SyncTableCallbackEventType } from './SyncTable.ts';\nimport type {\n SyncTableCallback,\n CallbackEvent as SyncTableCallbackEvent,\n InitialSyncBatch as SyncTableInitialSyncBatch,\n InitialSyncComplete as SyncTableInitialSyncComplete,\n SyncTransaction as SyncTableSyncTransaction,\n LoadFromStorage as SyncTableLoadFromStorage,\n SetupError as SyncTableSetupError,\n} from './SyncTable.ts';\n\nconst defaultOpenDevtool = true;\n\n// types\n\ntype ExactlyOne<T> = {\n [K in keyof T]: Pick<T, K> & Partial<Record<Exclude<keyof T, K>, never>>;\n}[keyof T];\n\nexport type Config = {\n appId: string;\n websocketURI?: string;\n apiURI?: string;\n devtool?: boolean | DevtoolConfig;\n verbose?: boolean;\n queryCacheLimit?: number;\n useDateObjects: boolean;\n disableValidation?: boolean;\n};\n\nexport type InstantConfig<\n S extends InstantSchemaDef<any, any, any>,\n UseDates extends boolean = false,\n> = {\n appId: string;\n schema?: S;\n websocketURI?: string;\n firstPartyPath?: string;\n apiURI?: string;\n devtool?: boolean | DevtoolConfig;\n verbose?: boolean;\n queryCacheLimit?: number;\n useDateObjects: UseDates;\n disableValidation?: boolean;\n};\n\nexport type ConfigWithSchema<S extends InstantGraph<any, any>> = Config & {\n schema: S;\n};\n\nexport type TransactionResult = {\n status: 'synced' | 'enqueued';\n clientId: string;\n};\n\nexport type PublishTopic<TopicsByKey> = <Key extends keyof TopicsByKey>(\n topic: Key,\n data: TopicsByKey[Key],\n) => void;\n\nexport type SubscribeTopic<PresenceShape, TopicsByKey> = <\n Key extends keyof TopicsByKey,\n>(\n topic: Key,\n onEvent: (event: TopicsByKey[Key], peer: PresenceShape) => void,\n) => () => void;\n\nexport type GetPresence<PresenceShape> = <Keys extends keyof PresenceShape>(\n opts: PresenceOpts<PresenceShape, Keys>,\n) => PresenceResponse<PresenceShape, Keys> | null;\n\nexport type SubscribePresence<PresenceShape> = <\n Keys extends keyof PresenceShape,\n>(\n opts: PresenceOpts<PresenceShape, Keys>,\n onChange: (slice: PresenceResponse<PresenceShape, Keys>) => void,\n) => () => void;\n\nexport type RoomHandle<PresenceShape, TopicsByKey> = {\n leaveRoom: () => void;\n publishTopic: PublishTopic<TopicsByKey>;\n subscribeTopic: SubscribeTopic<PresenceShape, TopicsByKey>;\n publishPresence: (data: Partial<PresenceShape>) => void;\n getPresence: GetPresence<PresenceShape>;\n subscribePresence: SubscribePresence<PresenceShape>;\n};\n\ntype AuthToken = string;\n\ntype SubscriptionState<Q, Schema, WithCardinalityInference extends boolean> =\n | { error: { message: string }; data: undefined; pageInfo: undefined }\n | {\n error: undefined;\n data: QueryResponse<Q, Schema, WithCardinalityInference>;\n pageInfo: PageInfoResponse<Q>;\n };\n\ntype InstaQLSubscriptionState<Schema, Q, UseDates extends boolean> =\n | { error: { message: string }; data: undefined; pageInfo: undefined }\n | {\n error: undefined;\n data: InstaQLResponse<Schema, Q, UseDates>;\n pageInfo: PageInfoResponse<Q>;\n };\n\ntype LifecycleSubscriptionState<\n Q,\n Schema,\n WithCardinalityInference extends boolean,\n> = SubscriptionState<Q, Schema, WithCardinalityInference> & {\n isLoading: boolean;\n};\n\ntype InstaQLLifecycleState<Schema, Q, UseDates extends boolean = false> =\n | (InstaQLSubscriptionState<Schema, Q, UseDates> & {\n isLoading: boolean;\n })\n | {\n isLoading: true;\n data: undefined;\n pageInfo: undefined;\n error: undefined;\n };\n\ntype UnsubscribeFn = () => void;\n\n// consts\n\nconst defaultConfig = {\n apiURI: 'https://api.instantdb.com',\n websocketURI: 'wss://api.instantdb.com/runtime/session',\n};\n\n// hmr\nfunction initSchemaHashStore(): WeakMap<any, string> {\n globalThis.__instantDbSchemaHashStore =\n globalThis.__instantDbSchemaHashStore ?? new WeakMap<any, string>();\n return globalThis.__instantDbSchemaHashStore;\n}\n\nfunction initGlobalInstantCoreStore(): Record<string, any> {\n globalThis.__instantDbStore = globalThis.__instantDbStore ?? {};\n return globalThis.__instantDbStore;\n}\n\nfunction reactorKey(config: InstantConfig<any, boolean>): string {\n // @ts-expect-error\n const adminToken = config.__adminToken;\n return (\n config.appId +\n '_' +\n (config.websocketURI || 'default_ws_uri') +\n '_' +\n (config.apiURI || 'default_api_uri') +\n '_' +\n (adminToken || 'client_only') +\n '_' +\n config.useDateObjects\n );\n}\n\nconst globalInstantCoreStore = initGlobalInstantCoreStore();\nconst schemaHashStore = initSchemaHashStore();\n\ntype SignoutOpts = {\n invalidateToken?: boolean;\n};\n\n/**\n * Functions to log users in and out.\n *\n * @see https://instantdb.com/docs/auth\n */\nclass Auth {\n constructor(private db: Reactor) {}\n\n /**\n * Sends a magic code to the user's email address.\n *\n * Once you send the magic code, see {@link auth.signInWithMagicCode} to let the\n * user verify.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * db.auth.sendMagicCode({email: \"example@gmail.com\"})\n * .catch((err) => console.error(err.body?.message))\n */\n sendMagicCode = (\n params: SendMagicCodeParams,\n ): Promise<SendMagicCodeResponse> => {\n return this.db.sendMagicCode(params);\n };\n\n /**\n * Verify a magic code that was sent to the user's email address.\n *\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * db.auth.signInWithMagicCode({email: \"example@gmail.com\", code: \"123456\"})\n * .catch((err) => console.error(err.body?.message))\n */\n signInWithMagicCode = (\n params: VerifyMagicCodeParams,\n ): Promise<VerifyResponse> => {\n return this.db.signInWithMagicCode(params);\n };\n\n /**\n * Sign in a user with a refresh token\n *\n * @see https://instantdb.com/docs/backend#frontend-auth-sign-in-with-token\n *\n * @example\n * // Get the token from your backend\n * const token = await fetch('/signin', ...);\n * //Sign in\n * db.auth.signInWithToken(token);\n */\n signInWithToken = (token: AuthToken): Promise<VerifyResponse> => {\n return this.db.signInWithCustomToken(token);\n };\n\n /**\n * Sign in as guest, creating a new user without email\n *\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * db.auth.signInAsGuest();\n */\n signInAsGuest = (): Promise<VerifyResponse> => {\n return this.db.signInAsGuest();\n };\n\n /**\n * Create an authorization url to sign in with an external provider.\n *\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * // Get the authorization url from your backend\n * const url = db.auth.createAuthorizationUrl({\n * clientName: \"google\",\n * redirectURL: window.location.href,\n * });\n *\n * // Put it in a sign in link\n * <a href={url}>Log in with Google</a>\n */\n createAuthorizationURL = (params: {\n clientName: string;\n redirectURL: string;\n }): string => {\n return this.db.createAuthorizationURL(params);\n };\n\n /**\n * Sign in with the id_token from an external provider like Google\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * db.auth\n * .signInWithIdToken({\n * // Token from external service\n * idToken: id_token,\n * // The name you gave the client when you registered it with Instant\n * clientName: \"google\",\n * // The nonce, if any, that you used when you initiated the auth flow\n * // with the external service.\n * nonce: your_nonce\n * })\n * .catch((err) => console.error(err.body?.message));\n *\n */\n signInWithIdToken = (\n params: SignInWithIdTokenParams,\n ): Promise<VerifyResponse> => {\n return this.db.signInWithIdToken(params);\n };\n\n /**\n * Sign in with the id_token from an external provider like Google\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * db.auth\n * .exchangeOAuthCode({\n * // code received in redirect from OAuth callback\n * code: code\n * // The PKCE code_verifier, if any, that you used when you\n * // initiated the auth flow\n * codeVerifier: your_code_verifier\n * })\n * .catch((err) => console.error(err.body?.message));\n *\n */\n exchangeOAuthCode = (params: ExchangeCodeForTokenParams) => {\n return this.db.exchangeCodeForToken(params);\n };\n\n /**\n * OpenID Discovery path for use with tools like\n * expo-auth-session that use auto-discovery of\n * OAuth parameters.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const discovery = useAutoDiscovery(\n * db.auth.issuerURI()\n * );\n */\n issuerURI = (): string => {\n return this.db.issuerURI();\n };\n\n /**\n * Sign out the current user\n */\n signOut = (opts: SignoutOpts = { invalidateToken: true }): Promise<void> => {\n return this.db.signOut(opts);\n };\n}\n\ntype FileOpts = {\n contentType?: string;\n contentDisposition?: string;\n fileSize?: number; // Required for streaming uploads\n};\n\n/**\n * Functions to manage file storage.\n */\nclass Storage {\n constructor(private db: Reactor) {}\n\n /**\n * Uploads file at the provided path.\n *\n * @see https://instantdb.com/docs/storage\n * @example\n * const [file] = e.target.files; // result of file input\n * const data = await db.storage.uploadFile('photos/demo.png', file);\n */\n uploadFile = (\n path: string,\n file: File | Blob,\n opts: FileOpts = {},\n ): Promise<UploadFileResponse> => {\n return this.db.uploadFile(path, file, opts);\n };\n\n /**\n * Deletes a file by path name.\n *\n * @see https://instantdb.com/docs/storage\n * @example\n * await db.storage.delete('photos/demo.png');\n */\n delete = (pathname: string) => {\n return this.db.deleteFile(pathname);\n };\n\n // Deprecated Storage API (Jan 2025)\n // ---------------------------------\n\n /**\n * @deprecated. Use `db.storage.uploadFile` instead\n * remove in the future.\n */\n upload = (pathname: string, file: File) => {\n return this.db.upload(pathname, file);\n };\n\n /**\n * @deprecated Use `db.storage.uploadFile` instead\n */\n put = this.upload;\n\n /**\n * @deprecated. getDownloadUrl will be removed in the future.\n * Use `useQuery` instead to query and fetch for valid urls\n *\n * db.useQuery({\n * $files: {\n * $: {\n * where: {\n * path: \"moop.png\"\n * }\n * }\n * }\n * })\n */\n getDownloadUrl = (pathname: string) => {\n return this.db.getDownloadUrl(pathname);\n };\n}\n\n// util\n\nfunction coerceQuery(o: any) {\n // stringify and parse to remove undefined values\n return JSON.parse(JSON.stringify(o));\n}\n\nclass InstantCoreDatabase<\n Schema extends InstantSchemaDef<any, any, any>,\n UseDates extends boolean = false,\n> implements IInstantDatabase<Schema>\n{\n public _reactor: Reactor<RoomsOf<Schema>>;\n public auth: Auth;\n public storage: Storage;\n\n public tx = txInit<Schema>();\n\n constructor(reactor: Reactor<RoomsOf<Schema>>) {\n this._reactor = reactor;\n this.auth = new Auth(this._reactor);\n this.storage = new Storage(this._reactor);\n }\n\n /**\n * Use this to write data! You can create, update, delete, and link objects\n *\n * @see https://instantdb.com/docs/instaml\n *\n * @example\n * // Create a new object in the `goals` namespace\n * const goalId = id();\n * db.transact(db.tx.goals[goalId].update({title: \"Get fit\"}))\n *\n * // Update the title\n * db.transact(db.tx.goals[goalId].update({title: \"Get super fit\"}))\n *\n * // Delete it\n * db.transact(db.tx.goals[goalId].delete())\n *\n * // Or create an association:\n * todoId = id();\n * db.transact([\n * db.tx.todos[todoId].update({ title: 'Go on a run' }),\n * db.tx.goals[goalId].link({todos: todoId}),\n * ])\n */\n transact(\n chunks: TransactionChunk<any, any> | TransactionChunk<any, any>[],\n ): Promise<TransactionResult> {\n return this._reactor.pushTx(chunks);\n }\n\n getLocalId(name: string): Promise<string> {\n return this._reactor.getLocalId(name);\n }\n\n /**\n * Use this to query your data!\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n * // listen to all goals\n * db.subscribeQuery({ goals: {} }, (resp) => {\n * console.log(resp.data.goals)\n * })\n *\n * // goals where the title is \"Get Fit\"\n * db.subscribeQuery(\n * { goals: { $: { where: { title: \"Get Fit\" } } } },\n * (resp) => {\n * console.log(resp.data.goals)\n * }\n * )\n *\n * // all goals, _alongside_ their todos\n * db.subscribeQuery({ goals: { todos: {} } }, (resp) => {\n * console.log(resp.data.goals)\n * });\n */\n subscribeQuery<\n Q extends ValidQuery<Q, Schema>,\n UseDatesLocal extends boolean = UseDates,\n >(\n query: Q,\n cb: (resp: InstaQLSubscriptionState<Schema, Q, UseDatesLocal>) => void,\n opts?: InstaQLOptions,\n ) {\n return this._reactor.subscribeQuery(query, cb, opts);\n }\n\n /**\n * Listen for the logged in state. This is useful\n * for deciding when to show a login screen.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const unsub = db.subscribeAuth((auth) => {\n * if (auth.user) {\n * console.log('logged in as', auth.user.email)\n * } else {\n * console.log('logged out')\n * }\n * })\n */\n subscribeAuth(cb: (auth: AuthResult) => void): UnsubscribeFn {\n return this._reactor.subscribeAuth(cb);\n }\n\n /**\n * One time query for the logged in state. This is useful\n * for scenarios where you want to know the current auth\n * state without subscribing to changes.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const user = await db.getAuth();\n * console.log('logged in as', user.email)\n */\n getAuth(): Promise<User | null> {\n return this._reactor.getAuth();\n }\n\n /**\n * Listen for connection status changes to Instant. This is useful\n * for building things like connectivity indicators\n *\n * @see https://www.instantdb.com/docs/patterns#connection-status\n * @example\n * const unsub = db.subscribeConnectionStatus((status) => {\n * const connectionState =\n * status === 'connecting' || status === 'opened'\n * ? 'authenticating'\n * : status === 'authenticated'\n * ? 'connected'\n * : status === 'closed'\n * ? 'closed'\n * : status === 'errored'\n * ? 'errored'\n * : 'unexpected state';\n *\n * console.log('Connection status:', connectionState);\n * });\n */\n subscribeConnectionStatus(\n cb: (status: ConnectionStatus) => void,\n ): UnsubscribeFn {\n return this._reactor.subscribeConnectionStatus(cb);\n }\n\n /**\n * Join a room to publish and subscribe to topics and presence.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * // init\n * const db = init();\n * const room = db.joinRoom(roomType, roomId);\n * // usage\n * const unsubscribeTopic = room.subscribeTopic(\"foo\", console.log);\n * const unsubscribePresence = room.subscribePresence({}, console.log);\n * room.publishTopic(\"hello\", { message: \"hello world!\" });\n * room.publishPresence({ name: \"joe\" });\n * // later\n * unsubscribePresence();\n * unsubscribeTopic();\n * room.leaveRoom();\n */\n joinRoom<RoomType extends keyof RoomsOf<Schema>>(\n roomType: RoomType = '_defaultRoomType' as RoomType,\n roomId: string = '_defaultRoomId',\n opts?: {\n initialPresence?: Partial<PresenceOf<Schema, RoomType>>;\n },\n ): RoomHandle<PresenceOf<Schema, RoomType>, TopicsOf<Schema, RoomType>> {\n const leaveRoom = this._reactor.joinRoom(roomId, opts?.initialPresence);\n\n return {\n leaveRoom,\n subscribeTopic: (topic, onEvent) =>\n this._reactor.subscribeTopic(roomId, topic, onEvent),\n subscribePresence: (opts, onChange) =>\n this._reactor.subscribePresence(roomType, roomId, opts, onChange),\n publishTopic: (topic, data) =>\n this._reactor.publishTopic({ roomType, roomId, topic, data }),\n publishPresence: (data) =>\n this._reactor.publishPresence(roomType, roomId, data),\n getPresence: (opts) => this._reactor.getPresence(roomType, roomId, opts),\n };\n }\n\n shutdown() {\n delete globalInstantCoreStore[reactorKey(this._reactor.config)];\n this._reactor.shutdown();\n }\n\n /**\n * Use this for one-off queries.\n * Returns local data if available, otherwise fetches from the server.\n * Because we want to avoid stale data, this method will throw an error\n * if the user is offline or there is no active connection to the server.\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n *\n * const resp = await db.queryOnce({ goals: {} });\n * console.log(resp.data.goals)\n */\n queryOnce<Q extends ValidQuery<Q, Schema>>(\n query: Q,\n opts?: InstaQLOptions,\n ): Promise<{\n data: InstaQLResponse<Schema, Q, UseDates>;\n pageInfo: PageInfoResponse<Q>;\n }> {\n return this._reactor.queryOnce(query, opts);\n }\n\n /**\n * @deprecated This is an experimental function that is not yet ready for production use.\n * Use this function to sync an entire namespace.\n * It has many limitations that will be removed in the future:\n * 1. Must be used with an admin token\n * 2. Does not support permissions\n * 3. Does not support where clauses\n * 4. Does not support links\n * It also does not support multiple top-level namespaces. For example,\n * {posts: {}, users: {}} is invalid. Only `posts` or `users` is allowed, but not both.\n */\n _syncTableExperimental<Q extends ValidQuery<Q, Schema>>(\n query: ExactlyOne<Q>,\n cb: SyncTableCallback<Schema, Q, UseDates>,\n ): (\n opts?: { keepSubscription: boolean | null | undefined } | null | undefined,\n ) => void {\n return this._reactor.subscribeTable(query, cb);\n }\n}\n\nfunction schemaHash(schema?: InstantSchemaDef<any, any, any>): string {\n if (!schema) {\n return '0';\n }\n\n const fromStore = schemaHashStore.get(schema);\n if (fromStore) {\n return fromStore;\n }\n const hash = weakHash(schema);\n schemaHashStore.set(schema, hash);\n return hash;\n}\n\nfunction schemaChanged(\n existingClient: InstantCoreDatabase<any, boolean>,\n newSchema?: InstantSchemaDef<any, any, any>,\n): boolean {\n return (\n schemaHash(existingClient._reactor.config.schema) !== schemaHash(newSchema)\n );\n}\n\n/**\n *\n * The first step: init your application!\n *\n * Visit https://instantdb.com/dash to get your `appId` :)\n *\n * @example\n * import { init } from \"@instantdb/core\"\n *\n * const db = init({ appId: \"my-app-id\" })\n *\n * // You can also provide a schema for type safety and editor autocomplete!\n *\n * import { init } from \"@instantdb/core\"\n * import schema from \"\"../instant.schema.ts\";\n *\n * const db = init({ appId: \"my-app-id\", schema })\n *\n * // To learn more: https://instantdb.com/docs/modeling-data\n */\nfunction init<\n Schema extends InstantSchemaDef<any, any, any> = InstantUnknownSchema,\n UseDates extends boolean = false,\n>(\n // Allows config with missing `useDateObjects`, but keeps `UseDates`\n // as a non-nullable in the InstantConfig type.\n config: Omit<InstantConfig<Schema, UseDates>, 'useDateObjects'> & {\n useDateObjects?: UseDates;\n },\n Storage?: any,\n NetworkListener?: any,\n versions?: { [key: string]: string },\n EventSourceImpl?: any,\n): InstantCoreDatabase<Schema, UseDates> {\n const configStrict = {\n ...config,\n appId: config.appId?.trim(),\n useDateObjects: (config.useDateObjects ?? false) as UseDates,\n };\n const existingClient = globalInstantCoreStore[\n reactorKey(configStrict)\n ] as InstantCoreDatabase<any, UseDates>;\n\n if (existingClient) {\n if (schemaChanged(existingClient, configStrict.schema)) {\n existingClient._reactor.updateSchema(configStrict.schema);\n }\n return existingClient;\n }\n\n const reactor = new Reactor<RoomsOf<Schema>>(\n {\n ...defaultConfig,\n ...configStrict,\n cardinalityInference: configStrict.schema ? true : false,\n },\n Storage || IndexedDBStorage,\n NetworkListener || WindowNetworkListener,\n { ...(versions || {}), '@instantdb/core': version },\n EventSourceImpl,\n );\n\n const client = new InstantCoreDatabase<any, UseDates>(reactor);\n globalInstantCoreStore[reactorKey(configStrict)] = client;\n\n handleDevtool(configStrict.appId, configStrict.devtool);\n\n return client;\n}\n\nfunction handleDevtool(\n appId: string,\n devtool: boolean | DevtoolConfig | null | undefined,\n) {\n if (\n typeof window === 'undefined' ||\n typeof window.location === 'undefined' ||\n typeof document === 'undefined'\n ) {\n return;\n }\n\n if (typeof devtool === 'boolean' && !devtool) {\n return;\n }\n\n const config: StrictDevtoolConfig = {\n position: 'bottom-right' as const,\n allowedHosts: ['localhost'],\n ...(typeof devtool === 'object' ? devtool : {}),\n };\n\n if (!config.allowedHosts.includes(window.location.hostname)) {\n return;\n }\n\n createDevtool(appId, config);\n}\n\n/**\n * @deprecated\n * `init_experimental` is deprecated. You can replace it with `init`.\n *\n * @example\n *\n * // Before\n * import { init_experimental } from \"@instantdb/core\"\n * const db = init_experimental({ ... });\n *\n * // After\n * import { init } from \"@instantdb/core\"\n * const db = init({ ... });\n */\nconst init_experimental = init;\n\nexport {\n // bada bing bada boom\n init,\n init_experimental,\n id,\n tx,\n txInit,\n lookup,\n validateQuery,\n QueryValidationError,\n validateTransactions,\n parseSchemaFromJSON,\n TransactionValidationError,\n FrameworkClient,\n\n // error\n InstantAPIError,\n\n // cli\n i,\n\n // util\n getOps,\n coerceQuery,\n weakHash,\n coerceToDate,\n IndexedDBStorage,\n WindowNetworkListener,\n InstantCoreDatabase,\n Auth,\n Storage,\n version,\n InstantError,\n\n // sync table enums\n SyncTableCallbackEventType,\n\n // og types\n type IDatabase,\n type RoomSchemaShape,\n type Query,\n type QueryResponse,\n type InstaQLResponse,\n type PageInfoResponse,\n type InstantObject,\n type Exactly,\n type TransactionChunk,\n type AuthState,\n type ConnectionStatus,\n type User,\n type AuthToken,\n type TxChunk,\n type SubscriptionState,\n type InstaQLSubscriptionState,\n type LifecycleSubscriptionState,\n type InstaQLLifecycleState,\n\n // presence types\n type PresenceOpts,\n type PresenceSlice,\n type PresenceResponse,\n type PresencePeer,\n\n // new query types\n type InstaQLParams,\n type ValidQuery,\n type InstaQLOptions,\n type InstaQLQueryParams,\n type InstantQuery,\n type InstantQueryResult,\n type InstantSchema,\n type InstantEntity,\n type InstantSchemaDatabase,\n type InstaQLFields,\n\n // schema types\n type AttrsDefs,\n type CardinalityKind,\n type DataAttrDef,\n type EntitiesDef,\n type InstantUnknownSchemaDef,\n type EntitiesWithLinks,\n type EntityDef,\n type RoomsDef,\n type InstantGraph,\n type LinkAttrDef,\n type LinkDef,\n type LinksDef,\n type ResolveAttrs,\n type ValueTypes,\n type RoomsOf,\n type PresenceOf,\n type TopicsOf,\n type TopicOf,\n type InstaQLEntity,\n type InstaQLResult,\n type InstaQLEntitySubquery,\n type InstantSchemaDef,\n type InstantUnknownSchema,\n type IInstantDatabase,\n type BackwardsCompatibleSchema,\n type InstantRules,\n type UpdateParams,\n type LinkParams,\n type CreateParams,\n type RuleParams,\n\n // attr types\n type InstantDBAttr,\n type InstantDBAttrOnDelete,\n type InstantDBCheckedDataType,\n type InstantDBIdent,\n type InstantDBInferredType,\n\n // auth types\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 // SSE\n type EventSourceType,\n type FrameworkConfig,\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 // error types\n type InstantIssue,\n\n // storage (e.g. indexeddb) interface\n StorageInterface,\n type StorageInterfaceStoreName,\n createInstantR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,QAAQ,IAAI,EAAE,CAAC,EAAE,iBAAiB,EAAE,oBAAO,EAAE,EACnD,eAAe,CAChB,CAAC;IAEF,MAAM,MAAM,GAAG,IAAI,mBAAmB,CAAgB,OAAO,CAAC,CAAC;IAC/D,sBAAsB,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC,GAAG,MAAM,CAAC;IAE1D,aAAa,CAAC,YAAY,CAAC,KAAK,EAAE,YAAY,CAAC,OAAO,CAAC,CAAC;IAExD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,aAAa,CACpB,KAAa,EACb,OAAmD;IAEnD,IACE,OAAO,MAAM,KAAK,WAAW;QAC7B,OAAO,MAAM,CAAC,QAAQ,KAAK,WAAW;QACtC,OAAO,QAAQ,KAAK,WAAW,EAC/B,CAAC;QACD,OAAO;IACT,CAAC;IAED,IAAI,OAAO,OAAO,KAAK,SAAS,IAAI,CAAC,OAAO,EAAE,CAAC;QAC7C,OAAO;IACT,CAAC;IAED,MAAM,MAAM,GAAwB;QAClC,QAAQ,EAAE,cAAuB;QACjC,YAAY,EAAE,CAAC,WAAW,CAAC;QAC3B,GAAG,CAAC,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;KAChD,CAAC;IAEF,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC5D,OAAO;IACT,CAAC;IAED,IAAA,0BAAa,EAAC,KAAK,EAAE,MAAM,CAAC,CAAC;AAC/B,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAK7B,8CAAiB","sourcesContent":["import Reactor from './Reactor.js';\nimport {\n tx,\n txInit,\n lookup,\n getOps,\n type TxChunk,\n type TransactionChunk,\n} from './instatx.js';\nimport weakHash from './utils/weakHash.js';\nimport id from './utils/id.ts';\nimport IndexedDBStorage from './IndexedDBStorage.ts';\nimport { coerceToDate } from './utils/dates.js';\nimport WindowNetworkListener from './WindowNetworkListener.js';\nimport { i } from './schema.js';\nimport { createDevtool } from './devtool.js';\nimport version from './version.ts';\nimport { validateQuery, QueryValidationError } from './queryValidation.ts';\nimport {\n validateTransactions,\n TransactionValidationError,\n} from './transactionValidation.ts';\n\nimport {\n StorageInterface,\n type StorageInterfaceStoreName,\n} from './utils/PersistedObject.ts';\nimport { createInstantRouteHandler } from './createRouteHandler.ts';\nimport { parseSchemaFromJSON } from './parseSchemaFromJSON.ts';\n\nimport type {\n PresenceOpts,\n PresenceResponse,\n PresenceSlice,\n RoomSchemaShape,\n} from './presence.ts';\nimport type {\n DevtoolConfig,\n IDatabase,\n IInstantDatabase,\n StrictDevtoolConfig,\n} from './coreTypes.ts';\nimport type {\n Query,\n QueryResponse,\n InstaQLResponse,\n PageInfoResponse,\n Exactly,\n InstantObject,\n InstaQLParams,\n InstaQLOptions,\n InstaQLQueryParams,\n InstaQLEntity,\n InstaQLEntitySubquery,\n InstaQLResult,\n InstaQLFields,\n ValidQuery,\n} from './queryTypes.ts';\nimport type { PresencePeer } from './presenceTypes.ts';\nimport type {\n AuthState,\n User,\n AuthResult,\n ConnectionStatus,\n} from './clientTypes.ts';\nimport type {\n InstantQuery,\n InstantQueryResult,\n InstantSchema,\n InstantEntity,\n InstantSchemaDatabase,\n} from './helperTypes.ts';\nimport type {\n InstantDBAttr,\n InstantDBAttrOnDelete,\n InstantDBCheckedDataType,\n InstantDBIdent,\n InstantDBInferredType,\n} from './attrTypes.ts';\nimport type {\n AttrsDefs,\n CardinalityKind,\n DataAttrDef,\n EntitiesDef,\n EntitiesWithLinks,\n EntityDef,\n RoomsDef,\n InstantSchemaDef,\n InstantGraph,\n LinkAttrDef,\n LinkDef,\n LinksDef,\n PresenceOf,\n ResolveAttrs,\n RoomsOf,\n TopicsOf,\n TopicOf,\n ValueTypes,\n InstantUnknownSchema,\n InstantUnknownSchemaDef,\n BackwardsCompatibleSchema,\n UpdateParams,\n LinkParams,\n CreateParams,\n RuleParams,\n} from './schemaTypes.ts';\nimport type { InstantRules } from './rulesTypes.ts';\nimport type { UploadFileResponse, DeleteFileResponse } from './StorageAPI.ts';\nimport { FrameworkClient, type FrameworkConfig } from './framework.ts';\n\nimport type {\n ExchangeCodeForTokenParams,\n SendMagicCodeParams,\n SendMagicCodeResponse,\n SignInWithIdTokenParams,\n VerifyMagicCodeParams,\n VerifyResponse,\n} from './authAPI.ts';\n\nimport { InstantAPIError, type InstantIssue } from './utils/fetch.js';\nimport { InstantError } from './InstantError.ts';\nimport { EventSourceType } from './Connection.ts';\nimport { CallbackEventType as SyncTableCallbackEventType } from './SyncTable.ts';\nimport type {\n SyncTableCallback,\n CallbackEvent as SyncTableCallbackEvent,\n InitialSyncBatch as SyncTableInitialSyncBatch,\n InitialSyncComplete as SyncTableInitialSyncComplete,\n SyncTransaction as SyncTableSyncTransaction,\n LoadFromStorage as SyncTableLoadFromStorage,\n SetupError as SyncTableSetupError,\n} from './SyncTable.ts';\n\nconst defaultOpenDevtool = true;\n\n// types\n\ntype ExactlyOne<T> = {\n [K in keyof T]: Pick<T, K> & Partial<Record<Exclude<keyof T, K>, never>>;\n}[keyof T];\n\nexport type Config = {\n appId: string;\n websocketURI?: string;\n apiURI?: string;\n devtool?: boolean | DevtoolConfig;\n verbose?: boolean;\n queryCacheLimit?: number;\n useDateObjects: boolean;\n disableValidation?: boolean;\n};\n\nexport type InstantConfig<\n S extends InstantSchemaDef<any, any, any>,\n UseDates extends boolean = false,\n> = {\n appId: string;\n schema?: S;\n websocketURI?: string;\n firstPartyPath?: string;\n apiURI?: string;\n devtool?: boolean | DevtoolConfig;\n verbose?: boolean;\n queryCacheLimit?: number;\n useDateObjects: UseDates;\n disableValidation?: boolean;\n};\n\nexport type ConfigWithSchema<S extends InstantGraph<any, any>> = Config & {\n schema: S;\n};\n\nexport type TransactionResult = {\n status: 'synced' | 'enqueued';\n clientId: string;\n};\n\nexport type PublishTopic<TopicsByKey> = <Key extends keyof TopicsByKey>(\n topic: Key,\n data: TopicsByKey[Key],\n) => void;\n\nexport type SubscribeTopic<PresenceShape, TopicsByKey> = <\n Key extends keyof TopicsByKey,\n>(\n topic: Key,\n onEvent: (event: TopicsByKey[Key], peer: PresenceShape) => void,\n) => () => void;\n\nexport type GetPresence<PresenceShape> = <Keys extends keyof PresenceShape>(\n opts: PresenceOpts<PresenceShape, Keys>,\n) => PresenceResponse<PresenceShape, Keys> | null;\n\nexport type SubscribePresence<PresenceShape> = <\n Keys extends keyof PresenceShape,\n>(\n opts: PresenceOpts<PresenceShape, Keys>,\n onChange: (slice: PresenceResponse<PresenceShape, Keys>) => void,\n) => () => void;\n\nexport type RoomHandle<PresenceShape, TopicsByKey> = {\n leaveRoom: () => void;\n publishTopic: PublishTopic<TopicsByKey>;\n subscribeTopic: SubscribeTopic<PresenceShape, TopicsByKey>;\n publishPresence: (data: Partial<PresenceShape>) => void;\n getPresence: GetPresence<PresenceShape>;\n subscribePresence: SubscribePresence<PresenceShape>;\n};\n\ntype AuthToken = string;\n\ntype SubscriptionState<Q, Schema, WithCardinalityInference extends boolean> =\n | { error: { message: string }; data: undefined; pageInfo: undefined }\n | {\n error: undefined;\n data: QueryResponse<Q, Schema, WithCardinalityInference>;\n pageInfo: PageInfoResponse<Q>;\n };\n\ntype InstaQLSubscriptionState<Schema, Q, UseDates extends boolean> =\n | { error: { message: string }; data: undefined; pageInfo: undefined }\n | {\n error: undefined;\n data: InstaQLResponse<Schema, Q, UseDates>;\n pageInfo: PageInfoResponse<Q>;\n };\n\ntype LifecycleSubscriptionState<\n Q,\n Schema,\n WithCardinalityInference extends boolean,\n> = SubscriptionState<Q, Schema, WithCardinalityInference> & {\n isLoading: boolean;\n};\n\ntype InstaQLLifecycleState<Schema, Q, UseDates extends boolean = false> =\n | (InstaQLSubscriptionState<Schema, Q, UseDates> & {\n isLoading: boolean;\n })\n | {\n isLoading: true;\n data: undefined;\n pageInfo: undefined;\n error: undefined;\n };\n\ntype UnsubscribeFn = () => void;\n\n// consts\n\nconst defaultConfig = {\n apiURI: 'https://api.instantdb.com',\n websocketURI: 'wss://api.instantdb.com/runtime/session',\n};\n\n// hmr\nfunction initSchemaHashStore(): WeakMap<any, string> {\n globalThis.__instantDbSchemaHashStore =\n globalThis.__instantDbSchemaHashStore ?? new WeakMap<any, string>();\n return globalThis.__instantDbSchemaHashStore;\n}\n\nfunction initGlobalInstantCoreStore(): Record<string, any> {\n globalThis.__instantDbStore = globalThis.__instantDbStore ?? {};\n return globalThis.__instantDbStore;\n}\n\nfunction reactorKey(config: InstantConfig<any, boolean>): string {\n // @ts-expect-error\n const adminToken = config.__adminToken;\n return (\n config.appId +\n '_' +\n (config.websocketURI || 'default_ws_uri') +\n '_' +\n (config.apiURI || 'default_api_uri') +\n '_' +\n (adminToken || 'client_only') +\n '_' +\n config.useDateObjects\n );\n}\n\nconst globalInstantCoreStore = initGlobalInstantCoreStore();\nconst schemaHashStore = initSchemaHashStore();\n\ntype SignoutOpts = {\n invalidateToken?: boolean;\n};\n\n/**\n * Functions to log users in and out.\n *\n * @see https://instantdb.com/docs/auth\n */\nclass Auth {\n constructor(private db: Reactor) {}\n\n /**\n * Sends a magic code to the user's email address.\n *\n * Once you send the magic code, see {@link auth.signInWithMagicCode} to let the\n * user verify.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * db.auth.sendMagicCode({email: \"example@gmail.com\"})\n * .catch((err) => console.error(err.body?.message))\n */\n sendMagicCode = (\n params: SendMagicCodeParams,\n ): Promise<SendMagicCodeResponse> => {\n return this.db.sendMagicCode(params);\n };\n\n /**\n * Verify a magic code that was sent to the user's email address.\n *\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * db.auth.signInWithMagicCode({email: \"example@gmail.com\", code: \"123456\"})\n * .catch((err) => console.error(err.body?.message))\n */\n signInWithMagicCode = (\n params: VerifyMagicCodeParams,\n ): Promise<VerifyResponse> => {\n return this.db.signInWithMagicCode(params);\n };\n\n /**\n * Sign in a user with a refresh token\n *\n * @see https://instantdb.com/docs/backend#frontend-auth-sign-in-with-token\n *\n * @example\n * // Get the token from your backend\n * const token = await fetch('/signin', ...);\n * //Sign in\n * db.auth.signInWithToken(token);\n */\n signInWithToken = (token: AuthToken): Promise<VerifyResponse> => {\n return this.db.signInWithCustomToken(token);\n };\n\n /**\n * Sign in as guest, creating a new user without email\n *\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * db.auth.signInAsGuest();\n */\n signInAsGuest = (): Promise<VerifyResponse> => {\n return this.db.signInAsGuest();\n };\n\n /**\n * Create an authorization url to sign in with an external provider.\n *\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * // Get the authorization url from your backend\n * const url = db.auth.createAuthorizationUrl({\n * clientName: \"google\",\n * redirectURL: window.location.href,\n * });\n *\n * // Put it in a sign in link\n * <a href={url}>Log in with Google</a>\n */\n createAuthorizationURL = (params: {\n clientName: string;\n redirectURL: string;\n }): string => {\n return this.db.createAuthorizationURL(params);\n };\n\n /**\n * Sign in with the id_token from an external provider like Google\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * db.auth\n * .signInWithIdToken({\n * // Token from external service\n * idToken: id_token,\n * // The name you gave the client when you registered it with Instant\n * clientName: \"google\",\n * // The nonce, if any, that you used when you initiated the auth flow\n * // with the external service.\n * nonce: your_nonce\n * })\n * .catch((err) => console.error(err.body?.message));\n *\n */\n signInWithIdToken = (\n params: SignInWithIdTokenParams,\n ): Promise<VerifyResponse> => {\n return this.db.signInWithIdToken(params);\n };\n\n /**\n * Sign in with the id_token from an external provider like Google\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * db.auth\n * .exchangeOAuthCode({\n * // code received in redirect from OAuth callback\n * code: code\n * // The PKCE code_verifier, if any, that you used when you\n * // initiated the auth flow\n * codeVerifier: your_code_verifier\n * })\n * .catch((err) => console.error(err.body?.message));\n *\n */\n exchangeOAuthCode = (params: ExchangeCodeForTokenParams) => {\n return this.db.exchangeCodeForToken(params);\n };\n\n /**\n * OpenID Discovery path for use with tools like\n * expo-auth-session that use auto-discovery of\n * OAuth parameters.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const discovery = useAutoDiscovery(\n * db.auth.issuerURI()\n * );\n */\n issuerURI = (): string => {\n return this.db.issuerURI();\n };\n\n /**\n * Sign out the current user\n */\n signOut = (opts: SignoutOpts = { invalidateToken: true }): Promise<void> => {\n return this.db.signOut(opts);\n };\n}\n\ntype FileOpts = {\n contentType?: string;\n contentDisposition?: string;\n fileSize?: number; // Required for streaming uploads\n};\n\n/**\n * Functions to manage file storage.\n */\nclass Storage {\n constructor(private db: Reactor) {}\n\n /**\n * Uploads file at the provided path.\n *\n * @see https://instantdb.com/docs/storage\n * @example\n * const [file] = e.target.files; // result of file input\n * const data = await db.storage.uploadFile('photos/demo.png', file);\n */\n uploadFile = (\n path: string,\n file: File | Blob,\n opts: FileOpts = {},\n ): Promise<UploadFileResponse> => {\n return this.db.uploadFile(path, file, opts);\n };\n\n /**\n * Deletes a file by path name.\n *\n * @see https://instantdb.com/docs/storage\n * @example\n * await db.storage.delete('photos/demo.png');\n */\n delete = (pathname: string) => {\n return this.db.deleteFile(pathname);\n };\n\n // Deprecated Storage API (Jan 2025)\n // ---------------------------------\n\n /**\n * @deprecated. Use `db.storage.uploadFile` instead\n * remove in the future.\n */\n upload = (pathname: string, file: File) => {\n return this.db.upload(pathname, file);\n };\n\n /**\n * @deprecated Use `db.storage.uploadFile` instead\n */\n put = this.upload;\n\n /**\n * @deprecated. getDownloadUrl will be removed in the future.\n * Use `useQuery` instead to query and fetch for valid urls\n *\n * db.useQuery({\n * $files: {\n * $: {\n * where: {\n * path: \"moop.png\"\n * }\n * }\n * }\n * })\n */\n getDownloadUrl = (pathname: string) => {\n return this.db.getDownloadUrl(pathname);\n };\n}\n\n// util\n\nfunction coerceQuery(o: any) {\n // stringify and parse to remove undefined values\n return JSON.parse(JSON.stringify(o));\n}\n\nclass InstantCoreDatabase<\n Schema extends InstantSchemaDef<any, any, any>,\n UseDates extends boolean = false,\n> implements IInstantDatabase<Schema>\n{\n public _reactor: Reactor<RoomsOf<Schema>>;\n public auth: Auth;\n public storage: Storage;\n\n public tx = txInit<Schema>();\n\n constructor(reactor: Reactor<RoomsOf<Schema>>) {\n this._reactor = reactor;\n this.auth = new Auth(this._reactor);\n this.storage = new Storage(this._reactor);\n }\n\n /**\n * Use this to write data! You can create, update, delete, and link objects\n *\n * @see https://instantdb.com/docs/instaml\n *\n * @example\n * // Create a new object in the `goals` namespace\n * const goalId = id();\n * db.transact(db.tx.goals[goalId].update({title: \"Get fit\"}))\n *\n * // Update the title\n * db.transact(db.tx.goals[goalId].update({title: \"Get super fit\"}))\n *\n * // Delete it\n * db.transact(db.tx.goals[goalId].delete())\n *\n * // Or create an association:\n * todoId = id();\n * db.transact([\n * db.tx.todos[todoId].update({ title: 'Go on a run' }),\n * db.tx.goals[goalId].link({todos: todoId}),\n * ])\n */\n transact(\n chunks: TransactionChunk<any, any> | TransactionChunk<any, any>[],\n ): Promise<TransactionResult> {\n return this._reactor.pushTx(chunks);\n }\n\n getLocalId(name: string): Promise<string> {\n return this._reactor.getLocalId(name);\n }\n\n /**\n * Use this to query your data!\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n * // listen to all goals\n * db.subscribeQuery({ goals: {} }, (resp) => {\n * console.log(resp.data.goals)\n * })\n *\n * // goals where the title is \"Get Fit\"\n * db.subscribeQuery(\n * { goals: { $: { where: { title: \"Get Fit\" } } } },\n * (resp) => {\n * console.log(resp.data.goals)\n * }\n * )\n *\n * // all goals, _alongside_ their todos\n * db.subscribeQuery({ goals: { todos: {} } }, (resp) => {\n * console.log(resp.data.goals)\n * });\n */\n subscribeQuery<\n Q extends ValidQuery<Q, Schema>,\n UseDatesLocal extends boolean = UseDates,\n >(\n query: Q,\n cb: (resp: InstaQLSubscriptionState<Schema, Q, UseDatesLocal>) => void,\n opts?: InstaQLOptions,\n ) {\n return this._reactor.subscribeQuery(query, cb, opts);\n }\n\n /**\n * Listen for the logged in state. This is useful\n * for deciding when to show a login screen.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const unsub = db.subscribeAuth((auth) => {\n * if (auth.user) {\n * console.log('logged in as', auth.user.email)\n * } else {\n * console.log('logged out')\n * }\n * })\n */\n subscribeAuth(cb: (auth: AuthResult) => void): UnsubscribeFn {\n return this._reactor.subscribeAuth(cb);\n }\n\n /**\n * One time query for the logged in state. This is useful\n * for scenarios where you want to know the current auth\n * state without subscribing to changes.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const user = await db.getAuth();\n * console.log('logged in as', user.email)\n */\n getAuth(): Promise<User | null> {\n return this._reactor.getAuth();\n }\n\n /**\n * Listen for connection status changes to Instant. This is useful\n * for building things like connectivity indicators\n *\n * @see https://www.instantdb.com/docs/patterns#connection-status\n * @example\n * const unsub = db.subscribeConnectionStatus((status) => {\n * const connectionState =\n * status === 'connecting' || status === 'opened'\n * ? 'authenticating'\n * : status === 'authenticated'\n * ? 'connected'\n * : status === 'closed'\n * ? 'closed'\n * : status === 'errored'\n * ? 'errored'\n * : 'unexpected state';\n *\n * console.log('Connection status:', connectionState);\n * });\n */\n subscribeConnectionStatus(\n cb: (status: ConnectionStatus) => void,\n ): UnsubscribeFn {\n return this._reactor.subscribeConnectionStatus(cb);\n }\n\n /**\n * Join a room to publish and subscribe to topics and presence.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * // init\n * const db = init();\n * const room = db.joinRoom(roomType, roomId);\n * // usage\n * const unsubscribeTopic = room.subscribeTopic(\"foo\", console.log);\n * const unsubscribePresence = room.subscribePresence({}, console.log);\n * room.publishTopic(\"hello\", { message: \"hello world!\" });\n * room.publishPresence({ name: \"joe\" });\n * // later\n * unsubscribePresence();\n * unsubscribeTopic();\n * room.leaveRoom();\n */\n joinRoom<RoomType extends keyof RoomsOf<Schema>>(\n roomType: RoomType = '_defaultRoomType' as RoomType,\n roomId: string = '_defaultRoomId',\n opts?: {\n initialPresence?: Partial<PresenceOf<Schema, RoomType>>;\n },\n ): RoomHandle<PresenceOf<Schema, RoomType>, TopicsOf<Schema, RoomType>> {\n const leaveRoom = this._reactor.joinRoom(roomId, opts?.initialPresence);\n\n return {\n leaveRoom,\n subscribeTopic: (topic, onEvent) =>\n this._reactor.subscribeTopic(roomId, topic, onEvent),\n subscribePresence: (opts, onChange) =>\n this._reactor.subscribePresence(roomType, roomId, opts, onChange),\n publishTopic: (topic, data) =>\n this._reactor.publishTopic({ roomType, roomId, topic, data }),\n publishPresence: (data) =>\n this._reactor.publishPresence(roomType, roomId, data),\n getPresence: (opts) => this._reactor.getPresence(roomType, roomId, opts),\n };\n }\n\n shutdown() {\n delete globalInstantCoreStore[reactorKey(this._reactor.config)];\n this._reactor.shutdown();\n }\n\n /**\n * Use this for one-off queries.\n * Returns local data if available, otherwise fetches from the server.\n * Because we want to avoid stale data, this method will throw an error\n * if the user is offline or there is no active connection to the server.\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n *\n * const resp = await db.queryOnce({ goals: {} });\n * console.log(resp.data.goals)\n */\n queryOnce<Q extends ValidQuery<Q, Schema>>(\n query: Q,\n opts?: InstaQLOptions,\n ): Promise<{\n data: InstaQLResponse<Schema, Q, UseDates>;\n pageInfo: PageInfoResponse<Q>;\n }> {\n return this._reactor.queryOnce(query, opts);\n }\n\n /**\n * @deprecated This is an experimental function that is not yet ready for production use.\n * Use this function to sync an entire namespace.\n * It has many limitations that will be removed in the future:\n * 1. Must be used with an admin token\n * 2. Does not support permissions\n * 3. Does not support where clauses\n * 4. Does not support links\n * It also does not support multiple top-level namespaces. For example,\n * {posts: {}, users: {}} is invalid. Only `posts` or `users` is allowed, but not both.\n */\n _syncTableExperimental<Q extends ValidQuery<Q, Schema>>(\n query: ExactlyOne<Q>,\n cb: SyncTableCallback<Schema, Q, UseDates>,\n ): (\n opts?: { keepSubscription: boolean | null | undefined } | null | undefined,\n ) => void {\n return this._reactor.subscribeTable(query, cb);\n }\n}\n\nfunction schemaHash(schema?: InstantSchemaDef<any, any, any>): string {\n if (!schema) {\n return '0';\n }\n\n const fromStore = schemaHashStore.get(schema);\n if (fromStore) {\n return fromStore;\n }\n const hash = weakHash(schema);\n schemaHashStore.set(schema, hash);\n return hash;\n}\n\nfunction schemaChanged(\n existingClient: InstantCoreDatabase<any, boolean>,\n newSchema?: InstantSchemaDef<any, any, any>,\n): boolean {\n return (\n schemaHash(existingClient._reactor.config.schema) !== schemaHash(newSchema)\n );\n}\n\n/**\n *\n * The first step: init your application!\n *\n * Visit https://instantdb.com/dash to get your `appId` :)\n *\n * @example\n * import { init } from \"@instantdb/core\"\n *\n * const db = init({ appId: \"my-app-id\" })\n *\n * // You can also provide a schema for type safety and editor autocomplete!\n *\n * import { init } from \"@instantdb/core\"\n * import schema from \"\"../instant.schema.ts\";\n *\n * const db = init({ appId: \"my-app-id\", schema })\n *\n * // To learn more: https://instantdb.com/docs/modeling-data\n */\nfunction init<\n Schema extends InstantSchemaDef<any, any, any> = InstantUnknownSchema,\n UseDates extends boolean = false,\n>(\n // Allows config with missing `useDateObjects`, but keeps `UseDates`\n // as a non-nullable in the InstantConfig type.\n config: Omit<InstantConfig<Schema, UseDates>, 'useDateObjects'> & {\n useDateObjects?: UseDates;\n },\n Storage?: any,\n NetworkListener?: any,\n versions?: { [key: string]: string },\n EventSourceImpl?: any,\n): InstantCoreDatabase<Schema, UseDates> {\n const configStrict = {\n ...config,\n appId: config.appId?.trim(),\n useDateObjects: (config.useDateObjects ?? false) as UseDates,\n };\n const existingClient = globalInstantCoreStore[\n reactorKey(configStrict)\n ] as InstantCoreDatabase<any, UseDates>;\n\n if (existingClient) {\n if (schemaChanged(existingClient, configStrict.schema)) {\n existingClient._reactor.updateSchema(configStrict.schema);\n }\n return existingClient;\n }\n\n const reactor = new Reactor<RoomsOf<Schema>>(\n {\n ...defaultConfig,\n ...configStrict,\n cardinalityInference: configStrict.schema ? true : false,\n },\n Storage || IndexedDBStorage,\n NetworkListener || WindowNetworkListener,\n { ...(versions || {}), '@instantdb/core': version },\n EventSourceImpl,\n );\n\n const client = new InstantCoreDatabase<any, UseDates>(reactor);\n globalInstantCoreStore[reactorKey(configStrict)] = client;\n\n handleDevtool(configStrict.appId, configStrict.devtool);\n\n return client;\n}\n\nfunction handleDevtool(\n appId: string,\n devtool: boolean | DevtoolConfig | null | undefined,\n) {\n if (\n typeof window === 'undefined' ||\n typeof window.location === 'undefined' ||\n typeof document === 'undefined'\n ) {\n return;\n }\n\n if (typeof devtool === 'boolean' && !devtool) {\n return;\n }\n\n const config: StrictDevtoolConfig = {\n position: 'bottom-right' as const,\n allowedHosts: ['localhost'],\n ...(typeof devtool === 'object' ? devtool : {}),\n };\n\n if (!config.allowedHosts.includes(window.location.hostname)) {\n return;\n }\n\n createDevtool(appId, config);\n}\n\n/**\n * @deprecated\n * `init_experimental` is deprecated. You can replace it with `init`.\n *\n * @example\n *\n * // Before\n * import { init_experimental } from \"@instantdb/core\"\n * const db = init_experimental({ ... });\n *\n * // After\n * import { init } from \"@instantdb/core\"\n * const db = init({ ... });\n */\nconst init_experimental = init;\n\nexport {\n // bada bing bada boom\n init,\n init_experimental,\n id,\n tx,\n txInit,\n lookup,\n validateQuery,\n QueryValidationError,\n validateTransactions,\n parseSchemaFromJSON,\n TransactionValidationError,\n FrameworkClient,\n\n // error\n InstantAPIError,\n\n // cli\n i,\n\n // util\n getOps,\n coerceQuery,\n weakHash,\n coerceToDate,\n IndexedDBStorage,\n WindowNetworkListener,\n InstantCoreDatabase,\n Auth,\n Storage,\n version,\n InstantError,\n\n // sync table enums\n SyncTableCallbackEventType,\n\n // og types\n type IDatabase,\n type RoomSchemaShape,\n type Query,\n type QueryResponse,\n type InstaQLResponse,\n type PageInfoResponse,\n type InstantObject,\n type Exactly,\n type TransactionChunk,\n type AuthState,\n type ConnectionStatus,\n type User,\n type AuthToken,\n type TxChunk,\n type SubscriptionState,\n type InstaQLSubscriptionState,\n type LifecycleSubscriptionState,\n type InstaQLLifecycleState,\n\n // presence types\n type PresenceOpts,\n type PresenceSlice,\n type PresenceResponse,\n type PresencePeer,\n\n // new query types\n type InstaQLParams,\n type ValidQuery,\n type InstaQLOptions,\n type InstaQLQueryParams,\n type InstantQuery,\n type InstantQueryResult,\n type InstantSchema,\n type InstantEntity,\n type InstantSchemaDatabase,\n type InstaQLFields,\n\n // schema types\n type AttrsDefs,\n type CardinalityKind,\n type DataAttrDef,\n type EntitiesDef,\n type InstantUnknownSchemaDef,\n type EntitiesWithLinks,\n type EntityDef,\n type RoomsDef,\n type InstantGraph,\n type LinkAttrDef,\n type LinkDef,\n type LinksDef,\n type ResolveAttrs,\n type ValueTypes,\n type RoomsOf,\n type PresenceOf,\n type TopicsOf,\n type TopicOf,\n type InstaQLEntity,\n type InstaQLResult,\n type InstaQLEntitySubquery,\n type InstantSchemaDef,\n type InstantUnknownSchema,\n type IInstantDatabase,\n type BackwardsCompatibleSchema,\n type InstantRules,\n type UpdateParams,\n type LinkParams,\n type CreateParams,\n type RuleParams,\n\n // attr types\n type InstantDBAttr,\n type InstantDBAttrOnDelete,\n type InstantDBCheckedDataType,\n type InstantDBIdent,\n type InstantDBInferredType,\n\n // auth types\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 // SSE\n type EventSourceType,\n type FrameworkConfig,\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 // error types\n type InstantIssue,\n\n // storage (e.g. indexeddb) interface\n StorageInterface,\n type StorageInterfaceStoreName,\n createInstantRouteHandler,\n};\n"]}
|
package/dist/commonjs/instaml.js
CHANGED
|
@@ -97,7 +97,6 @@ function extractLookup(attrs, etype, eid) {
|
|
|
97
97
|
return [attr.id, value];
|
|
98
98
|
}
|
|
99
99
|
function withIdAttrForLookup(attrs, etype, eidA, txSteps) {
|
|
100
|
-
var _b;
|
|
101
100
|
const lookup = extractLookup(attrs, etype, eidA);
|
|
102
101
|
if (!Array.isArray(lookup)) {
|
|
103
102
|
return txSteps;
|
|
@@ -105,7 +104,7 @@ function withIdAttrForLookup(attrs, etype, eidA, txSteps) {
|
|
|
105
104
|
const idTuple = [
|
|
106
105
|
'add-triple',
|
|
107
106
|
lookup,
|
|
108
|
-
(
|
|
107
|
+
(0, store_ts_1.getAttrByFwdIdentName)(attrs, etype, 'id')?.id,
|
|
109
108
|
lookup,
|
|
110
109
|
];
|
|
111
110
|
return [idTuple].concat(txSteps);
|
|
@@ -130,7 +129,7 @@ function expandLink({ attrsStore }, [etype, eidA, obj]) {
|
|
|
130
129
|
// Uses `!` because if we get here, we should have created the attr if it doesn't
|
|
131
130
|
// already exist
|
|
132
131
|
extractLookup(attrsStore, revAttr['forward-identity'][1], eidB),
|
|
133
|
-
revAttr
|
|
132
|
+
revAttr?.id,
|
|
134
133
|
extractLookup(attrsStore, etype, eidA),
|
|
135
134
|
];
|
|
136
135
|
return txStep;
|
|
@@ -167,12 +166,11 @@ function expandUnlink({ attrsStore }, [etype, eidA, obj]) {
|
|
|
167
166
|
return withIdAttrForLookup(attrsStore, etype, eidA, retractTriples);
|
|
168
167
|
}
|
|
169
168
|
function checkEntityExists(stores, attrsStore, etype, eid) {
|
|
170
|
-
var _b;
|
|
171
169
|
if (Array.isArray(eid)) {
|
|
172
170
|
// lookup ref
|
|
173
171
|
const [entity_a, entity_v] = eid;
|
|
174
172
|
for (const store of stores || []) {
|
|
175
|
-
const ev = store
|
|
173
|
+
const ev = store?.aev.get(entity_a);
|
|
176
174
|
if (ev) {
|
|
177
175
|
// This would be a lot more efficient with a ave index
|
|
178
176
|
for (const [_e, _a, v] of (0, store_ts_1.allMapValues)(ev, 2)) {
|
|
@@ -186,10 +184,10 @@ function checkEntityExists(stores, attrsStore, etype, eid) {
|
|
|
186
184
|
else {
|
|
187
185
|
// eid
|
|
188
186
|
for (const store of stores || []) {
|
|
189
|
-
const av = store
|
|
187
|
+
const av = store?.eav.get(eid);
|
|
190
188
|
if (av) {
|
|
191
189
|
for (const attr_id of av.keys()) {
|
|
192
|
-
if (
|
|
190
|
+
if (attrsStore.getAttr(attr_id)?.['forward-identity'][1] == etype) {
|
|
193
191
|
return true;
|
|
194
192
|
}
|
|
195
193
|
}
|
|
@@ -199,9 +197,9 @@ function checkEntityExists(stores, attrsStore, etype, eid) {
|
|
|
199
197
|
return false;
|
|
200
198
|
}
|
|
201
199
|
function convertOpts({ stores, attrsStore }, [etype, eid, obj_, opts]) {
|
|
202
|
-
return
|
|
200
|
+
return opts?.upsert === false
|
|
203
201
|
? { mode: 'update' }
|
|
204
|
-
:
|
|
202
|
+
: opts?.upsert === true
|
|
205
203
|
? null
|
|
206
204
|
: checkEntityExists(stores, attrsStore, etype, eid)
|
|
207
205
|
? { mode: 'update' }
|
|
@@ -288,7 +286,7 @@ function removeIdFromArgs(step) {
|
|
|
288
286
|
if (!obj) {
|
|
289
287
|
return step;
|
|
290
288
|
}
|
|
291
|
-
const newObj =
|
|
289
|
+
const newObj = { ...obj };
|
|
292
290
|
delete newObj.id;
|
|
293
291
|
return [op, etype, eid, newObj, ...(opts ? [opts] : [])];
|
|
294
292
|
}
|
|
@@ -327,15 +325,14 @@ function checkedDataTypeOfValueType(valueType) {
|
|
|
327
325
|
}
|
|
328
326
|
}
|
|
329
327
|
function objectPropsFromSchema(schema, etype, label) {
|
|
330
|
-
|
|
331
|
-
const attr = (_c = (_b = schema.entities[etype]) === null || _b === void 0 ? void 0 : _b.attrs) === null || _c === void 0 ? void 0 : _c[label];
|
|
328
|
+
const attr = schema.entities[etype]?.attrs?.[label];
|
|
332
329
|
if (label === 'id')
|
|
333
330
|
return null;
|
|
334
331
|
if (!attr) {
|
|
335
332
|
throw new Error(`${etype}.${label} does not exist in your schema`);
|
|
336
333
|
}
|
|
337
|
-
const { unique, indexed } = attr
|
|
338
|
-
const checkedDataType = checkedDataTypeOfValueType(attr
|
|
334
|
+
const { unique, indexed } = attr?.config;
|
|
335
|
+
const checkedDataType = checkedDataTypeOfValueType(attr?.valueType);
|
|
339
336
|
return {
|
|
340
337
|
'index?': indexed,
|
|
341
338
|
'unique?': unique,
|
|
@@ -349,7 +346,17 @@ function createObjectAttr(schema, etype, label, props) {
|
|
|
349
346
|
const attrId = (0, id_ts_1.default)();
|
|
350
347
|
const fwdIdentId = (0, id_ts_1.default)();
|
|
351
348
|
const fwdIdent = [fwdIdentId, etype, label];
|
|
352
|
-
return
|
|
349
|
+
return {
|
|
350
|
+
id: attrId,
|
|
351
|
+
'forward-identity': fwdIdent,
|
|
352
|
+
'value-type': 'blob',
|
|
353
|
+
cardinality: 'one',
|
|
354
|
+
'unique?': false,
|
|
355
|
+
'index?': false,
|
|
356
|
+
isUnsynced: true,
|
|
357
|
+
...(schemaObjectProps || {}),
|
|
358
|
+
...(props || {}),
|
|
359
|
+
};
|
|
353
360
|
}
|
|
354
361
|
function findSchemaLink(schema, etype, label) {
|
|
355
362
|
const links = Object.values(schema.links);
|
|
@@ -381,13 +388,21 @@ function createRefAttr(schema, etype, label, props) {
|
|
|
381
388
|
const attrId = (0, id_ts_1.default)();
|
|
382
389
|
const fwdIdent = [(0, id_ts_1.default)(), etype, label];
|
|
383
390
|
const revIdent = [(0, id_ts_1.default)(), label, etype];
|
|
384
|
-
return
|
|
391
|
+
return {
|
|
392
|
+
id: attrId,
|
|
385
393
|
// @ts-ignore: ts thinks it's any[]
|
|
386
|
-
'forward-identity': fwdIdent,
|
|
394
|
+
'forward-identity': fwdIdent,
|
|
387
395
|
// @ts-ignore: ts thinks it's any[]
|
|
388
|
-
'reverse-identity': revIdent,
|
|
396
|
+
'reverse-identity': revIdent,
|
|
397
|
+
'value-type': 'ref',
|
|
389
398
|
// @ts-ignore: ts thinks it's type string
|
|
390
|
-
cardinality: 'many',
|
|
399
|
+
cardinality: 'many',
|
|
400
|
+
'unique?': false,
|
|
401
|
+
'index?': false,
|
|
402
|
+
isUnsynced: true,
|
|
403
|
+
...(schemaRefProps || {}),
|
|
404
|
+
...(props || {}),
|
|
405
|
+
};
|
|
391
406
|
}
|
|
392
407
|
// Actions that have an object, e.g. not delete
|
|
393
408
|
const OBJ_ACTIONS = new Set(['create', 'update', 'merge', 'link', 'unlink']);
|
|
@@ -403,7 +418,10 @@ const SUPPORTS_LOOKUP_ACTIONS = new Set([
|
|
|
403
418
|
'ruleParams',
|
|
404
419
|
]);
|
|
405
420
|
const lookupProps = { 'unique?': true, 'index?': true };
|
|
406
|
-
const refLookupProps =
|
|
421
|
+
const refLookupProps = {
|
|
422
|
+
...lookupProps,
|
|
423
|
+
cardinality: 'one',
|
|
424
|
+
};
|
|
407
425
|
function lookupPairsOfOp(op) {
|
|
408
426
|
const res = [];
|
|
409
427
|
const [action, etype, eid, obj] = op;
|
|
@@ -432,7 +450,6 @@ function lookupPairsOfOp(op) {
|
|
|
432
450
|
return res;
|
|
433
451
|
}
|
|
434
452
|
function createMissingAttrs({ attrsStore, schema }, ops) {
|
|
435
|
-
var _b, _c;
|
|
436
453
|
const addedIds = new Set();
|
|
437
454
|
const localAttrs = [];
|
|
438
455
|
const addOps = [];
|
|
@@ -443,11 +460,8 @@ function createMissingAttrs({ attrsStore, schema }, ops) {
|
|
|
443
460
|
}
|
|
444
461
|
function attrByRevIdent(etype, label) {
|
|
445
462
|
return ((0, store_ts_1.getAttrByReverseIdentName)(attrsStore, etype, label) ||
|
|
446
|
-
localAttrs.find((x) =>
|
|
447
|
-
|
|
448
|
-
return ((_b = x['reverse-identity']) === null || _b === void 0 ? void 0 : _b[1]) === etype &&
|
|
449
|
-
((_c = x['reverse-identity']) === null || _c === void 0 ? void 0 : _c[2]) === label;
|
|
450
|
-
}));
|
|
463
|
+
localAttrs.find((x) => x['reverse-identity']?.[1] === etype &&
|
|
464
|
+
x['reverse-identity']?.[2] === label));
|
|
451
465
|
}
|
|
452
466
|
function addAttr(attr) {
|
|
453
467
|
localAttrs.push(attr);
|
|
@@ -497,8 +511,8 @@ function createMissingAttrs({ attrsStore, schema }, ops) {
|
|
|
497
511
|
const revAttr = attrByRevIdent(etype, linkLabel);
|
|
498
512
|
addUnsynced(fwdAttr);
|
|
499
513
|
addUnsynced(revAttr);
|
|
500
|
-
const linkEtype =
|
|
501
|
-
|
|
514
|
+
const linkEtype = fwdAttr?.['reverse-identity']?.[1] ||
|
|
515
|
+
revAttr?.['forward-identity']?.[1] ||
|
|
502
516
|
linkLabel;
|
|
503
517
|
if (isRefLookupIdentLocal(linkEtype, identName)) {
|
|
504
518
|
addForRef(linkEtype, extractRefLookupFwdName(identName));
|
|
@@ -551,7 +565,7 @@ function createMissingAttrs({ attrsStore, schema }, ops) {
|
|
|
551
565
|
}
|
|
552
566
|
}
|
|
553
567
|
if (localAttrs.length) {
|
|
554
|
-
const nextAttrs =
|
|
568
|
+
const nextAttrs = { ...attrsStore.attrs };
|
|
555
569
|
for (const attr of localAttrs) {
|
|
556
570
|
nextAttrs[attr.id] = attr;
|
|
557
571
|
}
|
|
@@ -563,7 +577,7 @@ function transform(ctx, inputChunks) {
|
|
|
563
577
|
const chunks = Array.isArray(inputChunks) ? inputChunks : [inputChunks];
|
|
564
578
|
const ops = chunks.flatMap((tx) => (0, instatx_ts_1.getOps)(tx));
|
|
565
579
|
const [newAttrs, addAttrTxSteps] = createMissingAttrs(ctx, ops);
|
|
566
|
-
const newCtx =
|
|
580
|
+
const newCtx = { ...ctx, attrsStore: newAttrs };
|
|
567
581
|
const txSteps = ops.flatMap((op) => toTxSteps(newCtx, op));
|
|
568
582
|
return [...addAttrTxSteps, ...txSteps];
|
|
569
583
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instaml.js","sourceRoot":"","sources":["../../src/instaml.ts"],"names":[],"mappings":";;;;;AA2BA,kCA4BC;AA2oBD,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G,CAAC,CAAC;IAChE,MAAM,MAAM,mCAAQ,GAAG,KAAE,UAAU,EAAE,QAAQ,GAAE,CAAC;IAChD,MAAM,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,SAAS,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC;IAC3D,OAAO,CAAC,GAAG,cAAc,EAAE,GAAG,OAAO,CAAC,CAAC;AACzC,CAAC","sourcesContent":["import {\n allMapValues,\n AttrsStore,\n AttrsStoreClass,\n getAttrByFwdIdentName,\n getAttrByReverseIdentName,\n Store,\n} from './store.ts';\nimport { getOps, isLookup, parseLookup } from './instatx.ts';\nimport { immutableRemoveUndefined } from './utils/object.js';\nimport { coerceToDate } from './utils/dates.ts';\nimport uuid from './utils/id.ts';\nimport {\n EntitiesWithLinks,\n IContainEntitiesAndLinks,\n LinkDef,\n} from './schemaTypes.ts';\nimport { InstantDBAttr, InstantDBIdent } from './attrTypes.ts';\n\nexport type AttrMapping = {\n attrIdMap: Record<string, string>;\n refSwapAttrIds: Set<string>;\n};\n\ntype TXStep = any[];\n\n// Rewrites optimistic attrs with the attrs we get back from the server.\nexport function rewriteStep(attrMapping: AttrMapping, txStep: TXStep): TXStep {\n const { attrIdMap, refSwapAttrIds } = attrMapping;\n const rewritten: TXStep = [];\n for (const part of txStep) {\n const newValue = attrIdMap[part];\n\n if (newValue) {\n // Rewrites attr id\n rewritten.push(newValue);\n } else if (Array.isArray(part) && part.length == 2 && attrIdMap[part[0]]) {\n // Rewrites attr id in lookups\n const [aid, value] = part;\n rewritten.push([attrIdMap[aid], value]);\n } else {\n rewritten.push(part);\n }\n }\n const [action] = txStep;\n if (\n (action === 'add-triple' || action === 'retract-triple') &&\n refSwapAttrIds.has(txStep[2])\n ) {\n // Reverse links if the optimistic link attr is backwards\n const tmp = rewritten[1];\n rewritten[1] = rewritten[3];\n rewritten[3] = tmp;\n }\n return rewritten;\n}\n\nfunction explodeLookupRef(eid) {\n if (Array.isArray(eid)) {\n return eid;\n }\n const entries = Object.entries(eid);\n if (entries.length !== 1) {\n throw new Error(\n 'lookup must be an object with a single unique attr and value.',\n );\n }\n return entries[0];\n}\n\nfunction isRefLookupIdent(attrs: AttrsStore, etype: string, identName: string) {\n return (\n identName.indexOf('.') !== -1 &&\n // attr names can have `.` in them, so use the attr we find with a `.`\n // before assuming it's a ref lookup.\n !getAttrByFwdIdentName(attrs, etype, identName)\n );\n}\n\nfunction extractRefLookupFwdName(identName) {\n const [fwdName, idIdent, ...rest] = identName.split('.');\n if (rest.length > 0 || idIdent !== 'id') {\n throw new Error(`${identName} is not a valid lookup attribute.`);\n }\n\n return fwdName;\n}\n\nfunction lookupIdentToAttr(\n attrs: AttrsStore,\n etype: string,\n identName: string,\n) {\n if (!isRefLookupIdent(attrs, etype, identName)) {\n return getAttrByFwdIdentName(attrs, etype, identName);\n }\n\n const fwdName = extractRefLookupFwdName(identName);\n\n const refAttr =\n getAttrByFwdIdentName(attrs, etype, fwdName) ||\n getAttrByReverseIdentName(attrs, etype, fwdName);\n if (refAttr && refAttr['value-type'] !== 'ref') {\n throw new Error(`${identName} does not reference a valid link attribute.`);\n }\n return refAttr;\n}\n\n// Returns [attr, value] for the eid if the eid is a lookup.\n// If it's a regular eid, returns null\nfunction lookupPairOfEid(eid) {\n if (typeof eid === 'string' && !isLookup(eid)) {\n return null;\n }\n return typeof eid === 'string' && isLookup(eid)\n ? parseLookup(eid)\n : explodeLookupRef(eid);\n}\n\nfunction extractLookup(attrs: AttrsStore, etype: string, eid: string) {\n const lookupPair = lookupPairOfEid(eid);\n\n if (lookupPair === null) {\n return eid;\n }\n\n const [identName, value] = lookupPair;\n const attr = lookupIdentToAttr(attrs, etype, identName);\n if (!attr || !attr['unique?']) {\n throw new Error(`${identName} is not a unique attribute.`);\n }\n return [attr.id, value];\n}\n\nfunction withIdAttrForLookup(\n attrs: AttrsStore,\n etype: string,\n eidA: string,\n txSteps: TXStep[],\n) {\n const lookup = extractLookup(attrs, etype, eidA);\n if (!Array.isArray(lookup)) {\n return txSteps;\n }\n const idTuple = [\n 'add-triple',\n lookup,\n getAttrByFwdIdentName(attrs, etype, 'id')?.id,\n lookup,\n ];\n return [idTuple].concat(txSteps);\n}\n\nfunction expandLink({ attrsStore }: Ctx, [etype, eidA, obj]) {\n const addTriples = Object.entries(obj).flatMap(([label, eidOrEids]) => {\n const eids = Array.isArray(eidOrEids) ? eidOrEids : [eidOrEids];\n const fwdAttr = getAttrByFwdIdentName(attrsStore, etype, label);\n const revAttr = getAttrByReverseIdentName(attrsStore, etype, label);\n return eids.map((eidB) => {\n const txStep = fwdAttr\n ? [\n 'add-triple',\n extractLookup(attrsStore, etype, eidA),\n fwdAttr.id,\n // Uses `!` because if we get here, we should have created the attr if it doesn't\n // already exist\n extractLookup(attrsStore, fwdAttr['reverse-identity']![1], eidB),\n ]\n : [\n 'add-triple',\n // Uses `!` because if we get here, we should have created the attr if it doesn't\n // already exist\n extractLookup(attrsStore, revAttr!['forward-identity']![1], eidB),\n revAttr?.id,\n extractLookup(attrsStore, etype, eidA),\n ];\n return txStep;\n });\n });\n return withIdAttrForLookup(attrsStore, etype, eidA, addTriples);\n}\n\nfunction expandUnlink({ attrsStore }: Ctx, [etype, eidA, obj]) {\n const retractTriples = Object.entries(obj).flatMap(([label, eidOrEids]) => {\n const eids = Array.isArray(eidOrEids) ? eidOrEids : [eidOrEids];\n const fwdAttr = getAttrByFwdIdentName(attrsStore, etype, label);\n const revAttr = getAttrByReverseIdentName(attrsStore, etype, label);\n return eids.map((eidB) => {\n const txStep = fwdAttr\n ? [\n 'retract-triple',\n extractLookup(attrsStore, etype, eidA),\n fwdAttr.id,\n // Uses `!` because if we get here, we should have created the attr if it doesn't\n // already exist\n extractLookup(attrsStore, fwdAttr!['reverse-identity']![1], eidB),\n ]\n : [\n 'retract-triple',\n // Uses `!` because if we get here, we should have created the attr if it doesn't\n // already exist\n extractLookup(attrsStore, revAttr!['forward-identity'][1], eidB),\n revAttr!.id,\n extractLookup(attrsStore, etype, eidA),\n ];\n return txStep;\n });\n });\n return withIdAttrForLookup(attrsStore, etype, eidA, retractTriples);\n}\n\nfunction checkEntityExists(\n stores: (Store | undefined)[] | undefined,\n attrsStore: AttrsStore,\n etype: string,\n eid: string,\n) {\n if (Array.isArray(eid)) {\n // lookup ref\n const [entity_a, entity_v] = eid;\n for (const store of stores || []) {\n const ev = store?.aev.get(entity_a);\n if (ev) {\n // This would be a lot more efficient with a ave index\n for (const [_e, _a, v] of allMapValues(ev, 2)) {\n if (v === entity_v) {\n return true;\n }\n }\n }\n }\n } else {\n // eid\n for (const store of stores || []) {\n const av = store?.eav.get(eid);\n if (av) {\n for (const attr_id of av.keys()) {\n if (attrsStore.getAttr(attr_id)?.['forward-identity'][1] == etype) {\n return true;\n }\n }\n }\n }\n }\n return false;\n}\n\ntype Ctx = {\n stores?: (Store | undefined)[];\n attrsStore: AttrsStore;\n schema?: Schema;\n useDateObjects?: boolean | null;\n};\n\nfunction convertOpts({ stores, attrsStore }: Ctx, [etype, eid, obj_, opts]) {\n return opts?.upsert === false\n ? { mode: 'update' }\n : opts?.upsert === true\n ? null\n : checkEntityExists(stores, attrsStore, etype, eid)\n ? { mode: 'update' }\n : null; // auto mode chooses between update and upsert, not update and create, just in case\n}\n\nfunction expandCreate(ctx: Ctx, step) {\n const { attrsStore } = ctx;\n const [etype, eid, obj_, opts] = step;\n const obj = immutableRemoveUndefined(obj_);\n const lookup = extractLookup(attrsStore, etype, eid);\n // id first so that we don't clobber updates on the lookup field\n const attrTuples = [['id', lookup]]\n .concat(Object.entries(obj))\n .map(([identName, value]: [string, any]) => {\n // Uses `!` because we should have optimistically created the attr if it doesn't exist\n const attr = getAttrByFwdIdentName(attrsStore, etype, identName)!;\n\n if (attr['checked-data-type'] === 'date' && ctx.useDateObjects) {\n value = coerceToDate(value);\n }\n\n return ['add-triple', lookup, attr.id, value, { mode: 'create' }];\n });\n return attrTuples;\n}\n\nfunction expandUpdate(ctx: Ctx, step) {\n const { attrsStore } = ctx;\n const [etype, eid, obj_, opts] = step;\n const obj = immutableRemoveUndefined(obj_);\n const lookup = extractLookup(attrsStore, etype, eid);\n const serverOpts = convertOpts(ctx, [etype, lookup, obj_, opts]);\n // id first so that we don't clobber updates on the lookup field\n const attrTuples = [['id', lookup]]\n .concat(Object.entries(obj))\n .map(([identName, value]: [string, any]) => {\n const attr = getAttrByFwdIdentName(attrsStore, etype, identName)!;\n\n if (attr['checked-data-type'] === 'date' && ctx.useDateObjects) {\n value = coerceToDate(value);\n }\n\n return [\n 'add-triple',\n lookup,\n attr.id,\n value,\n ...(serverOpts ? [serverOpts] : []),\n ];\n });\n return attrTuples;\n}\n\nfunction expandDelete({ attrsStore }: Ctx, [etype, eid]) {\n const lookup = extractLookup(attrsStore, etype, eid);\n return [['delete-entity', lookup, etype]];\n}\n\nfunction expandDeepMerge(ctx: Ctx, step) {\n const { attrsStore } = ctx;\n const [etype, eid, obj_, opts] = step;\n const obj = immutableRemoveUndefined(obj_);\n const lookup = extractLookup(attrsStore, etype, eid);\n const serverOpts = convertOpts(ctx, [etype, lookup, obj_, opts]);\n const attrTuples = Object.entries(obj).map(([identName, value]) => {\n const attr = getAttrByFwdIdentName(attrsStore, etype, identName)!;\n return [\n 'deep-merge-triple',\n lookup,\n attr.id,\n value,\n ...(serverOpts ? [serverOpts] : []),\n ];\n });\n\n const idTuple = [\n 'add-triple',\n lookup,\n getAttrByFwdIdentName(attrsStore, etype, 'id')!.id,\n lookup,\n ...(serverOpts ? [serverOpts] : []),\n ];\n\n // id first so that we don't clobber updates on the lookup field\n return [idTuple].concat(attrTuples);\n}\n\nfunction expandRuleParams({ attrsStore }: Ctx, [etype, eid, ruleParams]) {\n const lookup = extractLookup(attrsStore, etype, eid);\n return [['rule-params', lookup, etype, ruleParams]];\n}\n\nfunction removeIdFromArgs(step) {\n const [op, etype, eid, obj, opts] = step;\n if (!obj) {\n return step;\n }\n const newObj = { ...obj };\n delete newObj.id;\n return [op, etype, eid, newObj, ...(opts ? [opts] : [])];\n}\n\nfunction toTxSteps(ctx: Ctx, step) {\n const [action, ...args] = removeIdFromArgs(step);\n switch (action) {\n case 'merge':\n return expandDeepMerge(ctx, args);\n case 'create':\n return expandCreate(ctx, args);\n case 'update':\n return expandUpdate(ctx, args);\n case 'link':\n return expandLink(ctx, args);\n case 'unlink':\n return expandUnlink(ctx, args);\n case 'delete':\n return expandDelete(ctx, args);\n case 'ruleParams':\n return expandRuleParams(ctx, args);\n default:\n throw new Error(`unsupported action ${action}`);\n }\n}\n\n// ---------\n// transform\n\nfunction checkedDataTypeOfValueType(valueType) {\n switch (valueType) {\n case 'string':\n case 'date':\n case 'boolean':\n case 'number':\n return valueType;\n default:\n return undefined;\n }\n}\n\nfunction objectPropsFromSchema(schema, etype, label) {\n const attr = schema.entities[etype]?.attrs?.[label];\n if (label === 'id') return null;\n if (!attr) {\n throw new Error(`${etype}.${label} does not exist in your schema`);\n }\n const { unique, indexed } = attr?.config;\n const checkedDataType = checkedDataTypeOfValueType(attr?.valueType);\n\n return {\n 'index?': indexed,\n 'unique?': unique,\n 'checked-data-type': checkedDataType,\n };\n}\n\nfunction createObjectAttr(schema, etype, label, props) {\n const schemaObjectProps = schema\n ? objectPropsFromSchema(schema, etype, label)\n : null;\n const attrId = uuid();\n const fwdIdentId = uuid();\n const fwdIdent = [fwdIdentId, etype, label];\n return {\n id: attrId,\n 'forward-identity': fwdIdent,\n 'value-type': 'blob',\n cardinality: 'one',\n 'unique?': false,\n 'index?': false,\n isUnsynced: true,\n ...(schemaObjectProps || {}),\n ...(props || {}),\n };\n}\n\ntype Link = LinkDef<any, any, any, any, any, any, any>;\ntype Schema = IContainEntitiesAndLinks<any, any>;\n\nfunction findSchemaLink(schema: Schema, etype, label): Link | undefined {\n const links: Link[] = Object.values(schema.links);\n const found = links.find((x: Link) => {\n return (\n (x.forward.on === etype && x.forward.label === label) ||\n (x.reverse.on === etype && x.reverse.label === label)\n );\n });\n return found;\n}\n\nfunction refPropsFromSchema(schema: Schema, etype, label) {\n const found = findSchemaLink(schema, etype, label);\n if (!found) {\n throw new Error(`Couldn't find the link ${etype}.${label} in your schema`);\n }\n const { forward, reverse } = found;\n return {\n 'forward-identity': [uuid(), forward.on, forward.label],\n 'reverse-identity': [uuid(), reverse.on, reverse.label],\n cardinality: forward.has === 'one' ? 'one' : 'many',\n 'unique?': reverse.has === 'one',\n 'on-delete': forward.onDelete,\n 'on-delete-reverse': reverse.onDelete,\n };\n}\n\nfunction createRefAttr(\n schema: Schema | undefined,\n etype: string,\n label: string,\n props?: Partial<InstantDBAttr> | undefined,\n): InstantDBAttr {\n const schemaRefProps = schema\n ? refPropsFromSchema(schema, etype, label)\n : null;\n const attrId = uuid();\n const fwdIdent: InstantDBIdent = [uuid(), etype, label];\n const revIdent: InstantDBIdent = [uuid(), label, etype];\n return {\n id: attrId,\n // @ts-ignore: ts thinks it's any[]\n 'forward-identity': fwdIdent,\n // @ts-ignore: ts thinks it's any[]\n 'reverse-identity': revIdent,\n 'value-type': 'ref',\n // @ts-ignore: ts thinks it's type string\n cardinality: 'many',\n 'unique?': false,\n 'index?': false,\n isUnsynced: true,\n ...(schemaRefProps || {}),\n ...(props || {}),\n };\n}\n\n// Actions that have an object, e.g. not delete\nconst OBJ_ACTIONS = new Set(['create', 'update', 'merge', 'link', 'unlink']);\nconst REF_ACTIONS = new Set(['link', 'unlink']);\nconst UPDATE_ACTIONS = new Set(['create', 'update', 'merge']);\nconst SUPPORTS_LOOKUP_ACTIONS = new Set([\n 'link',\n 'unlink',\n 'create',\n 'update',\n 'merge',\n 'delete',\n 'ruleParams',\n]);\n\nconst lookupProps: Partial<InstantDBAttr> = { 'unique?': true, 'index?': true };\nconst refLookupProps: Partial<InstantDBAttr> = {\n ...lookupProps,\n cardinality: 'one',\n};\n\nfunction lookupPairsOfOp(op) {\n const res: { etype: string; lookupPair: any; linkLabel?: string }[] = [];\n const [action, etype, eid, obj] = op;\n if (!SUPPORTS_LOOKUP_ACTIONS.has(action)) {\n return res;\n }\n\n const eidLookupPair = lookupPairOfEid(eid);\n if (eidLookupPair) {\n res.push({ etype: etype, lookupPair: eidLookupPair });\n }\n if (action === 'link') {\n for (const [label, eidOrEids] of Object.entries(obj)) {\n const eids = Array.isArray(eidOrEids) ? eidOrEids : [eidOrEids];\n for (const linkEid of eids) {\n const linkEidLookupPair = lookupPairOfEid(linkEid);\n if (linkEidLookupPair) {\n res.push({\n etype: etype,\n lookupPair: linkEidLookupPair,\n linkLabel: label,\n });\n }\n }\n }\n }\n return res;\n}\n\nfunction createMissingAttrs(\n { attrsStore, schema }: Ctx,\n ops,\n): [AttrsStore, TXStep[]] {\n const addedIds = new Set();\n const localAttrs: InstantDBAttr[] = [];\n const addOps: TXStep[] = [];\n\n function attrByFwdIdent(etype, label): InstantDBAttr | undefined {\n return (\n getAttrByFwdIdentName(attrsStore, etype, label) ||\n localAttrs.find(\n (x) =>\n x['forward-identity'][1] === etype &&\n x['forward-identity'][2] === label,\n )\n );\n }\n\n function attrByRevIdent(etype, label): InstantDBAttr | undefined {\n return (\n getAttrByReverseIdentName(attrsStore, etype, label) ||\n localAttrs.find(\n (x) =>\n x['reverse-identity']?.[1] === etype &&\n x['reverse-identity']?.[2] === label,\n )\n );\n }\n\n function addAttr(attr: InstantDBAttr) {\n localAttrs.push(attr);\n addOps.push(['add-attr', attr]);\n addedIds.add(attr.id);\n }\n function addUnsynced(\n attr:\n | (InstantDBAttr & { isUnsynced?: boolean })\n | InstantDBAttr\n | undefined,\n ) {\n if (\n attr &&\n 'isUnsynced' in attr &&\n attr.isUnsynced &&\n !addedIds.has(attr.id)\n ) {\n localAttrs.push(attr);\n addOps.push(['add-attr', attr]);\n addedIds.add(attr.id);\n }\n }\n\n function isRefLookupIdentLocal(etype: string, identName: string) {\n return (\n identName.indexOf('.') !== -1 &&\n // attr names can have `.` in them, so use the attr we find with a `.`\n // before assuming it's a ref lookup.\n !attrByFwdIdent(etype, identName)\n );\n }\n\n // Adds attrs needed for a ref lookup\n function addForRef(etype, label) {\n const fwdAttr = attrByFwdIdent(etype, label);\n const revAttr = attrByRevIdent(etype, label);\n addUnsynced(fwdAttr);\n addUnsynced(revAttr);\n if (!fwdAttr && !revAttr) {\n addAttr(createRefAttr(schema, etype, label, refLookupProps));\n }\n }\n\n // Create attrs for lookups if we need to\n // Do these first because otherwise we might add a non-unique attr\n // before we get to it\n for (const op of ops) {\n for (const { etype, lookupPair, linkLabel } of lookupPairsOfOp(op)) {\n const identName = lookupPair[0];\n // We got a link eid that's a lookup, linkLabel is the label of the ident,\n // e.g. `posts` in `link({posts: postIds})`\n if (linkLabel) {\n // Add our ref attr, e.g. users.posts\n addForRef(etype, linkLabel);\n\n // Figure out the link etype so we can make sure we have the attrs\n // for the link lookup\n const fwdAttr = attrByFwdIdent(etype, linkLabel);\n const revAttr = attrByRevIdent(etype, linkLabel);\n addUnsynced(fwdAttr);\n addUnsynced(revAttr);\n const linkEtype =\n fwdAttr?.['reverse-identity']?.[1] ||\n revAttr?.['forward-identity']?.[1] ||\n linkLabel;\n if (isRefLookupIdentLocal(linkEtype, identName)) {\n addForRef(linkEtype, extractRefLookupFwdName(identName));\n } else {\n const attr = attrByFwdIdent(linkEtype, identName);\n if (!attr) {\n addAttr(\n createObjectAttr(schema, linkEtype, identName, lookupProps),\n );\n }\n addUnsynced(attr);\n }\n } else if (isRefLookupIdentLocal(etype, identName)) {\n addForRef(etype, extractRefLookupFwdName(identName));\n } else {\n const attr = attrByFwdIdent(etype, identName);\n if (!attr) {\n addAttr(createObjectAttr(schema, etype, identName, lookupProps));\n }\n addUnsynced(attr);\n }\n }\n }\n\n // Create object and ref attrs\n for (const op of ops) {\n const [action, etype, eid, obj] = op;\n if (OBJ_ACTIONS.has(action)) {\n const idAttr = attrByFwdIdent(etype, 'id');\n addUnsynced(idAttr);\n if (!idAttr) {\n addAttr(createObjectAttr(schema, etype, 'id', { 'unique?': true }));\n }\n\n for (const label of Object.keys(obj)) {\n const fwdAttr = attrByFwdIdent(etype, label);\n addUnsynced(fwdAttr);\n if (UPDATE_ACTIONS.has(action)) {\n if (!fwdAttr) {\n addAttr(\n createObjectAttr(\n schema,\n etype,\n label,\n label === 'id' ? { 'unique?': true } : null,\n ),\n );\n }\n }\n if (REF_ACTIONS.has(action)) {\n const revAttr = attrByRevIdent(etype, label);\n if (!fwdAttr && !revAttr) {\n addAttr(createRefAttr(schema, etype, label));\n }\n addUnsynced(revAttr);\n }\n }\n }\n }\n\n if (localAttrs.length) {\n const nextAttrs = { ...attrsStore.attrs };\n for (const attr of localAttrs) {\n nextAttrs[attr.id] = attr;\n }\n return [new AttrsStoreClass(nextAttrs, attrsStore.linkIndex), addOps];\n }\n return [attrsStore, addOps];\n}\n\nexport function transform(ctx: Ctx, inputChunks) {\n const chunks = Array.isArray(inputChunks) ? inputChunks : [inputChunks];\n const ops = chunks.flatMap((tx) => getOps(tx));\n const [newAttrs, addAttrTxSteps] = createMissingAttrs(ctx, ops);\n const newCtx = { ...ctx, attrsStore: newAttrs };\n const txSteps = ops.flatMap((op) => toTxSteps(newCtx, op));\n return [...addAttrTxSteps, ...txSteps];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"instaml.js","sourceRoot":"","sources":["../../src/instaml.ts"],"names":[],"mappings":";;;;;AA2BA,kCA4BC;AA2oBD,8BAOC;AAzsBD,yCAOoB;AACpB,6CAA6D;AAC7D,iDAA6D;AAC7D,+CAAgD;AAChD,0DAAiC;AAejC,wEAAwE;AACxE,SAAgB,WAAW,CAAC,WAAwB,EAAE,MAAc;IAClE,MAAM,EAAE,SAAS,EAAE,cAAc,EAAE,GAAG,WAAW,CAAC;IAClD,MAAM,SAAS,GAAW,EAAE,CAAC;IAC7B,KAAK,MAAM,IAAI,IAAI,MAAM,EAAE,CAAC;QAC1B,MAAM,QAAQ,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;QAEjC,IAAI,QAAQ,EAAE,CAAC;YACb,mBAAmB;YACnB,SAAS,CAAC,IAAI,CAAC,QAA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AE,CAAC,GAAG,IAAI,CAAC;QAC5B,CAAC;QACD,OAAO,CAAC,IAAI,0BAAe,CAAC,SAAS,EAAE,UAAU,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC,CAAC;IACxE,CAAC;IACD,OAAO,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;AAC9B,CAAC;AAED,SAAgB,SAAS,CAAC,GAAQ,EAAE,WAAW;IAC7C,MAAM,MAAM,GAAG,KAAK,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC;IACxE,MAAM,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,IAAA,mBAAM,EAAC,EAAE,CAAC,CAAC,CAAC;IAC/C,MAAM,CAAC,QAAQ,EAAE,cAAc,CAAC,GAAG,kBAAkB,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IAChE,MAAM,MAAM,GAAG,EAAE,GAAG,GAAG,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC;IAChD,MAAM,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,SAAS,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC;IAC3D,OAAO,CAAC,GAAG,cAAc,EAAE,GAAG,OAAO,CAAC,CAAC;AACzC,CAAC","sourcesContent":["import {\n allMapValues,\n AttrsStore,\n AttrsStoreClass,\n getAttrByFwdIdentName,\n getAttrByReverseIdentName,\n Store,\n} from './store.ts';\nimport { getOps, isLookup, parseLookup } from './instatx.ts';\nimport { immutableRemoveUndefined } from './utils/object.js';\nimport { coerceToDate } from './utils/dates.ts';\nimport uuid from './utils/id.ts';\nimport {\n EntitiesWithLinks,\n IContainEntitiesAndLinks,\n LinkDef,\n} from './schemaTypes.ts';\nimport { InstantDBAttr, InstantDBIdent } from './attrTypes.ts';\n\nexport type AttrMapping = {\n attrIdMap: Record<string, string>;\n refSwapAttrIds: Set<string>;\n};\n\ntype TXStep = any[];\n\n// Rewrites optimistic attrs with the attrs we get back from the server.\nexport function rewriteStep(attrMapping: AttrMapping, txStep: TXStep): TXStep {\n const { attrIdMap, refSwapAttrIds } = attrMapping;\n const rewritten: TXStep = [];\n for (const part of txStep) {\n const newValue = attrIdMap[part];\n\n if (newValue) {\n // Rewrites attr id\n rewritten.push(newValue);\n } else if (Array.isArray(part) && part.length == 2 && attrIdMap[part[0]]) {\n // Rewrites attr id in lookups\n const [aid, value] = part;\n rewritten.push([attrIdMap[aid], value]);\n } else {\n rewritten.push(part);\n }\n }\n const [action] = txStep;\n if (\n (action === 'add-triple' || action === 'retract-triple') &&\n refSwapAttrIds.has(txStep[2])\n ) {\n // Reverse links if the optimistic link attr is backwards\n const tmp = rewritten[1];\n rewritten[1] = rewritten[3];\n rewritten[3] = tmp;\n }\n return rewritten;\n}\n\nfunction explodeLookupRef(eid) {\n if (Array.isArray(eid)) {\n return eid;\n }\n const entries = Object.entries(eid);\n if (entries.length !== 1) {\n throw new Error(\n 'lookup must be an object with a single unique attr and value.',\n );\n }\n return entries[0];\n}\n\nfunction isRefLookupIdent(attrs: AttrsStore, etype: string, identName: string) {\n return (\n identName.indexOf('.') !== -1 &&\n // attr names can have `.` in them, so use the attr we find with a `.`\n // before assuming it's a ref lookup.\n !getAttrByFwdIdentName(attrs, etype, identName)\n );\n}\n\nfunction extractRefLookupFwdName(identName) {\n const [fwdName, idIdent, ...rest] = identName.split('.');\n if (rest.length > 0 || idIdent !== 'id') {\n throw new Error(`${identName} is not a valid lookup attribute.`);\n }\n\n return fwdName;\n}\n\nfunction lookupIdentToAttr(\n attrs: AttrsStore,\n etype: string,\n identName: string,\n) {\n if (!isRefLookupIdent(attrs, etype, identName)) {\n return getAttrByFwdIdentName(attrs, etype, identName);\n }\n\n const fwdName = extractRefLookupFwdName(identName);\n\n const refAttr =\n getAttrByFwdIdentName(attrs, etype, fwdName) ||\n getAttrByReverseIdentName(attrs, etype, fwdName);\n if (refAttr && refAttr['value-type'] !== 'ref') {\n throw new Error(`${identName} does not reference a valid link attribute.`);\n }\n return refAttr;\n}\n\n// Returns [attr, value] for the eid if the eid is a lookup.\n// If it's a regular eid, returns null\nfunction lookupPairOfEid(eid) {\n if (typeof eid === 'string' && !isLookup(eid)) {\n return null;\n }\n return typeof eid === 'string' && isLookup(eid)\n ? parseLookup(eid)\n : explodeLookupRef(eid);\n}\n\nfunction extractLookup(attrs: AttrsStore, etype: string, eid: string) {\n const lookupPair = lookupPairOfEid(eid);\n\n if (lookupPair === null) {\n return eid;\n }\n\n const [identName, value] = lookupPair;\n const attr = lookupIdentToAttr(attrs, etype, identName);\n if (!attr || !attr['unique?']) {\n throw new Error(`${identName} is not a unique attribute.`);\n }\n return [attr.id, value];\n}\n\nfunction withIdAttrForLookup(\n attrs: AttrsStore,\n etype: string,\n eidA: string,\n txSteps: TXStep[],\n) {\n const lookup = extractLookup(attrs, etype, eidA);\n if (!Array.isArray(lookup)) {\n return txSteps;\n }\n const idTuple = [\n 'add-triple',\n lookup,\n getAttrByFwdIdentName(attrs, etype, 'id')?.id,\n lookup,\n ];\n return [idTuple].concat(txSteps);\n}\n\nfunction expandLink({ attrsStore }: Ctx, [etype, eidA, obj]) {\n const addTriples = Object.entries(obj).flatMap(([label, eidOrEids]) => {\n const eids = Array.isArray(eidOrEids) ? eidOrEids : [eidOrEids];\n const fwdAttr = getAttrByFwdIdentName(attrsStore, etype, label);\n const revAttr = getAttrByReverseIdentName(attrsStore, etype, label);\n return eids.map((eidB) => {\n const txStep = fwdAttr\n ? [\n 'add-triple',\n extractLookup(attrsStore, etype, eidA),\n fwdAttr.id,\n // Uses `!` because if we get here, we should have created the attr if it doesn't\n // already exist\n extractLookup(attrsStore, fwdAttr['reverse-identity']![1], eidB),\n ]\n : [\n 'add-triple',\n // Uses `!` because if we get here, we should have created the attr if it doesn't\n // already exist\n extractLookup(attrsStore, revAttr!['forward-identity']![1], eidB),\n revAttr?.id,\n extractLookup(attrsStore, etype, eidA),\n ];\n return txStep;\n });\n });\n return withIdAttrForLookup(attrsStore, etype, eidA, addTriples);\n}\n\nfunction expandUnlink({ attrsStore }: Ctx, [etype, eidA, obj]) {\n const retractTriples = Object.entries(obj).flatMap(([label, eidOrEids]) => {\n const eids = Array.isArray(eidOrEids) ? eidOrEids : [eidOrEids];\n const fwdAttr = getAttrByFwdIdentName(attrsStore, etype, label);\n const revAttr = getAttrByReverseIdentName(attrsStore, etype, label);\n return eids.map((eidB) => {\n const txStep = fwdAttr\n ? [\n 'retract-triple',\n extractLookup(attrsStore, etype, eidA),\n fwdAttr.id,\n // Uses `!` because if we get here, we should have created the attr if it doesn't\n // already exist\n extractLookup(attrsStore, fwdAttr!['reverse-identity']![1], eidB),\n ]\n : [\n 'retract-triple',\n // Uses `!` because if we get here, we should have created the attr if it doesn't\n // already exist\n extractLookup(attrsStore, revAttr!['forward-identity'][1], eidB),\n revAttr!.id,\n extractLookup(attrsStore, etype, eidA),\n ];\n return txStep;\n });\n });\n return withIdAttrForLookup(attrsStore, etype, eidA, retractTriples);\n}\n\nfunction checkEntityExists(\n stores: (Store | undefined)[] | undefined,\n attrsStore: AttrsStore,\n etype: string,\n eid: string,\n) {\n if (Array.isArray(eid)) {\n // lookup ref\n const [entity_a, entity_v] = eid;\n for (const store of stores || []) {\n const ev = store?.aev.get(entity_a);\n if (ev) {\n // This would be a lot more efficient with a ave index\n for (const [_e, _a, v] of allMapValues(ev, 2)) {\n if (v === entity_v) {\n return true;\n }\n }\n }\n }\n } else {\n // eid\n for (const store of stores || []) {\n const av = store?.eav.get(eid);\n if (av) {\n for (const attr_id of av.keys()) {\n if (attrsStore.getAttr(attr_id)?.['forward-identity'][1] == etype) {\n return true;\n }\n }\n }\n }\n }\n return false;\n}\n\ntype Ctx = {\n stores?: (Store | undefined)[];\n attrsStore: AttrsStore;\n schema?: Schema;\n useDateObjects?: boolean | null;\n};\n\nfunction convertOpts({ stores, attrsStore }: Ctx, [etype, eid, obj_, opts]) {\n return opts?.upsert === false\n ? { mode: 'update' }\n : opts?.upsert === true\n ? null\n : checkEntityExists(stores, attrsStore, etype, eid)\n ? { mode: 'update' }\n : null; // auto mode chooses between update and upsert, not update and create, just in case\n}\n\nfunction expandCreate(ctx: Ctx, step) {\n const { attrsStore } = ctx;\n const [etype, eid, obj_, opts] = step;\n const obj = immutableRemoveUndefined(obj_);\n const lookup = extractLookup(attrsStore, etype, eid);\n // id first so that we don't clobber updates on the lookup field\n const attrTuples = [['id', lookup]]\n .concat(Object.entries(obj))\n .map(([identName, value]: [string, any]) => {\n // Uses `!` because we should have optimistically created the attr if it doesn't exist\n const attr = getAttrByFwdIdentName(attrsStore, etype, identName)!;\n\n if (attr['checked-data-type'] === 'date' && ctx.useDateObjects) {\n value = coerceToDate(value);\n }\n\n return ['add-triple', lookup, attr.id, value, { mode: 'create' }];\n });\n return attrTuples;\n}\n\nfunction expandUpdate(ctx: Ctx, step) {\n const { attrsStore } = ctx;\n const [etype, eid, obj_, opts] = step;\n const obj = immutableRemoveUndefined(obj_);\n const lookup = extractLookup(attrsStore, etype, eid);\n const serverOpts = convertOpts(ctx, [etype, lookup, obj_, opts]);\n // id first so that we don't clobber updates on the lookup field\n const attrTuples = [['id', lookup]]\n .concat(Object.entries(obj))\n .map(([identName, value]: [string, any]) => {\n const attr = getAttrByFwdIdentName(attrsStore, etype, identName)!;\n\n if (attr['checked-data-type'] === 'date' && ctx.useDateObjects) {\n value = coerceToDate(value);\n }\n\n return [\n 'add-triple',\n lookup,\n attr.id,\n value,\n ...(serverOpts ? [serverOpts] : []),\n ];\n });\n return attrTuples;\n}\n\nfunction expandDelete({ attrsStore }: Ctx, [etype, eid]) {\n const lookup = extractLookup(attrsStore, etype, eid);\n return [['delete-entity', lookup, etype]];\n}\n\nfunction expandDeepMerge(ctx: Ctx, step) {\n const { attrsStore } = ctx;\n const [etype, eid, obj_, opts] = step;\n const obj = immutableRemoveUndefined(obj_);\n const lookup = extractLookup(attrsStore, etype, eid);\n const serverOpts = convertOpts(ctx, [etype, lookup, obj_, opts]);\n const attrTuples = Object.entries(obj).map(([identName, value]) => {\n const attr = getAttrByFwdIdentName(attrsStore, etype, identName)!;\n return [\n 'deep-merge-triple',\n lookup,\n attr.id,\n value,\n ...(serverOpts ? [serverOpts] : []),\n ];\n });\n\n const idTuple = [\n 'add-triple',\n lookup,\n getAttrByFwdIdentName(attrsStore, etype, 'id')!.id,\n lookup,\n ...(serverOpts ? [serverOpts] : []),\n ];\n\n // id first so that we don't clobber updates on the lookup field\n return [idTuple].concat(attrTuples);\n}\n\nfunction expandRuleParams({ attrsStore }: Ctx, [etype, eid, ruleParams]) {\n const lookup = extractLookup(attrsStore, etype, eid);\n return [['rule-params', lookup, etype, ruleParams]];\n}\n\nfunction removeIdFromArgs(step) {\n const [op, etype, eid, obj, opts] = step;\n if (!obj) {\n return step;\n }\n const newObj = { ...obj };\n delete newObj.id;\n return [op, etype, eid, newObj, ...(opts ? [opts] : [])];\n}\n\nfunction toTxSteps(ctx: Ctx, step) {\n const [action, ...args] = removeIdFromArgs(step);\n switch (action) {\n case 'merge':\n return expandDeepMerge(ctx, args);\n case 'create':\n return expandCreate(ctx, args);\n case 'update':\n return expandUpdate(ctx, args);\n case 'link':\n return expandLink(ctx, args);\n case 'unlink':\n return expandUnlink(ctx, args);\n case 'delete':\n return expandDelete(ctx, args);\n case 'ruleParams':\n return expandRuleParams(ctx, args);\n default:\n throw new Error(`unsupported action ${action}`);\n }\n}\n\n// ---------\n// transform\n\nfunction checkedDataTypeOfValueType(valueType) {\n switch (valueType) {\n case 'string':\n case 'date':\n case 'boolean':\n case 'number':\n return valueType;\n default:\n return undefined;\n }\n}\n\nfunction objectPropsFromSchema(schema, etype, label) {\n const attr = schema.entities[etype]?.attrs?.[label];\n if (label === 'id') return null;\n if (!attr) {\n throw new Error(`${etype}.${label} does not exist in your schema`);\n }\n const { unique, indexed } = attr?.config;\n const checkedDataType = checkedDataTypeOfValueType(attr?.valueType);\n\n return {\n 'index?': indexed,\n 'unique?': unique,\n 'checked-data-type': checkedDataType,\n };\n}\n\nfunction createObjectAttr(schema, etype, label, props) {\n const schemaObjectProps = schema\n ? objectPropsFromSchema(schema, etype, label)\n : null;\n const attrId = uuid();\n const fwdIdentId = uuid();\n const fwdIdent = [fwdIdentId, etype, label];\n return {\n id: attrId,\n 'forward-identity': fwdIdent,\n 'value-type': 'blob',\n cardinality: 'one',\n 'unique?': false,\n 'index?': false,\n isUnsynced: true,\n ...(schemaObjectProps || {}),\n ...(props || {}),\n };\n}\n\ntype Link = LinkDef<any, any, any, any, any, any, any>;\ntype Schema = IContainEntitiesAndLinks<any, any>;\n\nfunction findSchemaLink(schema: Schema, etype, label): Link | undefined {\n const links: Link[] = Object.values(schema.links);\n const found = links.find((x: Link) => {\n return (\n (x.forward.on === etype && x.forward.label === label) ||\n (x.reverse.on === etype && x.reverse.label === label)\n );\n });\n return found;\n}\n\nfunction refPropsFromSchema(schema: Schema, etype, label) {\n const found = findSchemaLink(schema, etype, label);\n if (!found) {\n throw new Error(`Couldn't find the link ${etype}.${label} in your schema`);\n }\n const { forward, reverse } = found;\n return {\n 'forward-identity': [uuid(), forward.on, forward.label],\n 'reverse-identity': [uuid(), reverse.on, reverse.label],\n cardinality: forward.has === 'one' ? 'one' : 'many',\n 'unique?': reverse.has === 'one',\n 'on-delete': forward.onDelete,\n 'on-delete-reverse': reverse.onDelete,\n };\n}\n\nfunction createRefAttr(\n schema: Schema | undefined,\n etype: string,\n label: string,\n props?: Partial<InstantDBAttr> | undefined,\n): InstantDBAttr {\n const schemaRefProps = schema\n ? refPropsFromSchema(schema, etype, label)\n : null;\n const attrId = uuid();\n const fwdIdent: InstantDBIdent = [uuid(), etype, label];\n const revIdent: InstantDBIdent = [uuid(), label, etype];\n return {\n id: attrId,\n // @ts-ignore: ts thinks it's any[]\n 'forward-identity': fwdIdent,\n // @ts-ignore: ts thinks it's any[]\n 'reverse-identity': revIdent,\n 'value-type': 'ref',\n // @ts-ignore: ts thinks it's type string\n cardinality: 'many',\n 'unique?': false,\n 'index?': false,\n isUnsynced: true,\n ...(schemaRefProps || {}),\n ...(props || {}),\n };\n}\n\n// Actions that have an object, e.g. not delete\nconst OBJ_ACTIONS = new Set(['create', 'update', 'merge', 'link', 'unlink']);\nconst REF_ACTIONS = new Set(['link', 'unlink']);\nconst UPDATE_ACTIONS = new Set(['create', 'update', 'merge']);\nconst SUPPORTS_LOOKUP_ACTIONS = new Set([\n 'link',\n 'unlink',\n 'create',\n 'update',\n 'merge',\n 'delete',\n 'ruleParams',\n]);\n\nconst lookupProps: Partial<InstantDBAttr> = { 'unique?': true, 'index?': true };\nconst refLookupProps: Partial<InstantDBAttr> = {\n ...lookupProps,\n cardinality: 'one',\n};\n\nfunction lookupPairsOfOp(op) {\n const res: { etype: string; lookupPair: any; linkLabel?: string }[] = [];\n const [action, etype, eid, obj] = op;\n if (!SUPPORTS_LOOKUP_ACTIONS.has(action)) {\n return res;\n }\n\n const eidLookupPair = lookupPairOfEid(eid);\n if (eidLookupPair) {\n res.push({ etype: etype, lookupPair: eidLookupPair });\n }\n if (action === 'link') {\n for (const [label, eidOrEids] of Object.entries(obj)) {\n const eids = Array.isArray(eidOrEids) ? eidOrEids : [eidOrEids];\n for (const linkEid of eids) {\n const linkEidLookupPair = lookupPairOfEid(linkEid);\n if (linkEidLookupPair) {\n res.push({\n etype: etype,\n lookupPair: linkEidLookupPair,\n linkLabel: label,\n });\n }\n }\n }\n }\n return res;\n}\n\nfunction createMissingAttrs(\n { attrsStore, schema }: Ctx,\n ops,\n): [AttrsStore, TXStep[]] {\n const addedIds = new Set();\n const localAttrs: InstantDBAttr[] = [];\n const addOps: TXStep[] = [];\n\n function attrByFwdIdent(etype, label): InstantDBAttr | undefined {\n return (\n getAttrByFwdIdentName(attrsStore, etype, label) ||\n localAttrs.find(\n (x) =>\n x['forward-identity'][1] === etype &&\n x['forward-identity'][2] === label,\n )\n );\n }\n\n function attrByRevIdent(etype, label): InstantDBAttr | undefined {\n return (\n getAttrByReverseIdentName(attrsStore, etype, label) ||\n localAttrs.find(\n (x) =>\n x['reverse-identity']?.[1] === etype &&\n x['reverse-identity']?.[2] === label,\n )\n );\n }\n\n function addAttr(attr: InstantDBAttr) {\n localAttrs.push(attr);\n addOps.push(['add-attr', attr]);\n addedIds.add(attr.id);\n }\n function addUnsynced(\n attr:\n | (InstantDBAttr & { isUnsynced?: boolean })\n | InstantDBAttr\n | undefined,\n ) {\n if (\n attr &&\n 'isUnsynced' in attr &&\n attr.isUnsynced &&\n !addedIds.has(attr.id)\n ) {\n localAttrs.push(attr);\n addOps.push(['add-attr', attr]);\n addedIds.add(attr.id);\n }\n }\n\n function isRefLookupIdentLocal(etype: string, identName: string) {\n return (\n identName.indexOf('.') !== -1 &&\n // attr names can have `.` in them, so use the attr we find with a `.`\n // before assuming it's a ref lookup.\n !attrByFwdIdent(etype, identName)\n );\n }\n\n // Adds attrs needed for a ref lookup\n function addForRef(etype, label) {\n const fwdAttr = attrByFwdIdent(etype, label);\n const revAttr = attrByRevIdent(etype, label);\n addUnsynced(fwdAttr);\n addUnsynced(revAttr);\n if (!fwdAttr && !revAttr) {\n addAttr(createRefAttr(schema, etype, label, refLookupProps));\n }\n }\n\n // Create attrs for lookups if we need to\n // Do these first because otherwise we might add a non-unique attr\n // before we get to it\n for (const op of ops) {\n for (const { etype, lookupPair, linkLabel } of lookupPairsOfOp(op)) {\n const identName = lookupPair[0];\n // We got a link eid that's a lookup, linkLabel is the label of the ident,\n // e.g. `posts` in `link({posts: postIds})`\n if (linkLabel) {\n // Add our ref attr, e.g. users.posts\n addForRef(etype, linkLabel);\n\n // Figure out the link etype so we can make sure we have the attrs\n // for the link lookup\n const fwdAttr = attrByFwdIdent(etype, linkLabel);\n const revAttr = attrByRevIdent(etype, linkLabel);\n addUnsynced(fwdAttr);\n addUnsynced(revAttr);\n const linkEtype =\n fwdAttr?.['reverse-identity']?.[1] ||\n revAttr?.['forward-identity']?.[1] ||\n linkLabel;\n if (isRefLookupIdentLocal(linkEtype, identName)) {\n addForRef(linkEtype, extractRefLookupFwdName(identName));\n } else {\n const attr = attrByFwdIdent(linkEtype, identName);\n if (!attr) {\n addAttr(\n createObjectAttr(schema, linkEtype, identName, lookupProps),\n );\n }\n addUnsynced(attr);\n }\n } else if (isRefLookupIdentLocal(etype, identName)) {\n addForRef(etype, extractRefLookupFwdName(identName));\n } else {\n const attr = attrByFwdIdent(etype, identName);\n if (!attr) {\n addAttr(createObjectAttr(schema, etype, identName, lookupProps));\n }\n addUnsynced(attr);\n }\n }\n }\n\n // Create object and ref attrs\n for (const op of ops) {\n const [action, etype, eid, obj] = op;\n if (OBJ_ACTIONS.has(action)) {\n const idAttr = attrByFwdIdent(etype, 'id');\n addUnsynced(idAttr);\n if (!idAttr) {\n addAttr(createObjectAttr(schema, etype, 'id', { 'unique?': true }));\n }\n\n for (const label of Object.keys(obj)) {\n const fwdAttr = attrByFwdIdent(etype, label);\n addUnsynced(fwdAttr);\n if (UPDATE_ACTIONS.has(action)) {\n if (!fwdAttr) {\n addAttr(\n createObjectAttr(\n schema,\n etype,\n label,\n label === 'id' ? { 'unique?': true } : null,\n ),\n );\n }\n }\n if (REF_ACTIONS.has(action)) {\n const revAttr = attrByRevIdent(etype, label);\n if (!fwdAttr && !revAttr) {\n addAttr(createRefAttr(schema, etype, label));\n }\n addUnsynced(revAttr);\n }\n }\n }\n }\n\n if (localAttrs.length) {\n const nextAttrs = { ...attrsStore.attrs };\n for (const attr of localAttrs) {\n nextAttrs[attr.id] = attr;\n }\n return [new AttrsStoreClass(nextAttrs, attrsStore.linkIndex), addOps];\n }\n return [attrsStore, addOps];\n}\n\nexport function transform(ctx: Ctx, inputChunks) {\n const chunks = Array.isArray(inputChunks) ? inputChunks : [inputChunks];\n const ops = chunks.flatMap((tx) => getOps(tx));\n const [newAttrs, addAttrTxSteps] = createMissingAttrs(ctx, ops);\n const newCtx = { ...ctx, attrsStore: newAttrs };\n const txSteps = ops.flatMap((op) => toTxSteps(newCtx, op));\n return [...addAttrTxSteps, ...txSteps];\n}\n"]}
|