jazz-tools 0.18.19 → 0.18.21
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/.svelte-kit/__package__/Provider.svelte +61 -53
- package/.svelte-kit/__package__/Provider.svelte.d.ts.map +1 -1
- package/.turbo/turbo-build.log +60 -62
- package/CHANGELOG.md +25 -0
- package/dist/browser/index.js +2 -2
- package/dist/browser/index.js.map +1 -1
- package/dist/chunk-BOMSRY5H.js +26 -0
- package/dist/chunk-BOMSRY5H.js.map +1 -0
- package/dist/{chunk-RN3Y24WX.js → chunk-D5L6ES2M.js} +51 -6
- package/dist/chunk-D5L6ES2M.js.map +1 -0
- package/dist/chunk-PZ5AY32C.js +10 -0
- package/dist/chunk-PZ5AY32C.js.map +1 -0
- package/dist/index.js +6 -1
- package/dist/index.js.map +1 -1
- package/dist/react/ssr.d.ts +1 -3
- package/dist/react/ssr.d.ts.map +1 -1
- package/dist/react/ssr.js +3 -1
- package/dist/react/ssr.js.map +1 -1
- package/dist/react-core/hooks.d.ts.map +1 -1
- package/dist/react-core/index.js +2 -2
- package/dist/react-core/index.js.map +1 -1
- package/dist/svelte/Provider.svelte +61 -53
- package/dist/svelte/Provider.svelte.d.ts.map +1 -1
- package/dist/testing.js +2 -1
- package/dist/testing.js.map +1 -1
- package/dist/tools/coValues/coList.d.ts.map +1 -1
- package/dist/tools/coValues/coPlainText.d.ts.map +1 -1
- package/dist/tools/exports.d.ts +1 -0
- package/dist/tools/exports.d.ts.map +1 -1
- package/dist/tools/implementation/zodSchema/runtimeConverters/schemaFieldToCoFieldDef.d.ts +1 -1
- package/dist/tools/implementation/zodSchema/runtimeConverters/schemaFieldToCoFieldDef.d.ts.map +1 -1
- package/dist/tools/implementation/zodSchema/typeConverters/TypeOfZodSchema.d.ts +1 -1
- package/dist/tools/implementation/zodSchema/typeConverters/TypeOfZodSchema.d.ts.map +1 -1
- package/dist/tools/implementation/zodSchema/zodReExport.d.ts +1 -1
- package/dist/tools/implementation/zodSchema/zodReExport.d.ts.map +1 -1
- package/dist/tools/ssr/index.d.ts +2 -0
- package/dist/tools/ssr/index.d.ts.map +1 -0
- package/dist/tools/ssr/ssr.d.ts +4 -0
- package/dist/tools/ssr/ssr.d.ts.map +1 -0
- package/dist/tools/ssr.js +8 -0
- package/dist/tools/ssr.js.map +1 -0
- package/package.json +15 -10
- package/src/browser/auth/PasskeyAuth.ts +2 -2
- package/src/react/ssr.ts +2 -23
- package/src/react-core/hooks.ts +3 -2
- package/src/react-core/tests/useInboxSender.test.ts +37 -3
- package/src/svelte/Provider.svelte +61 -53
- package/src/tools/coValues/coList.ts +11 -0
- package/src/tools/coValues/coPlainText.ts +9 -0
- package/src/tools/exports.ts +2 -0
- package/src/tools/implementation/zodSchema/runtimeConverters/schemaFieldToCoFieldDef.ts +47 -2
- package/src/tools/implementation/zodSchema/typeConverters/TypeOfZodSchema.ts +9 -4
- package/src/tools/implementation/zodSchema/zodReExport.ts +1 -0
- package/src/tools/ssr/index.ts +1 -0
- package/src/tools/ssr/ssr.ts +23 -0
- package/src/tools/tests/coList.test.ts +34 -0
- package/src/tools/tests/coPlainText.test.ts +25 -1
- package/src/tools/tests/zod.test.ts +131 -0
- package/tsup.config.ts +2 -7
- package/dist/chunk-RN3Y24WX.js.map +0 -1
- package/jazz-tools-0.18.6.tgz +0 -0
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/index.js
CHANGED
@@ -37,7 +37,11 @@ import {
|
|
37
37
|
randomSessionProvider,
|
38
38
|
subscribeToCoValue,
|
39
39
|
zodReExport_exports
|
40
|
-
} from "./chunk-
|
40
|
+
} from "./chunk-D5L6ES2M.js";
|
41
|
+
import {
|
42
|
+
createSSRJazzAgent
|
43
|
+
} from "./chunk-BOMSRY5H.js";
|
44
|
+
import "./chunk-PZ5AY32C.js";
|
41
45
|
|
42
46
|
// src/tools/auth/clerk/index.ts
|
43
47
|
import {
|
@@ -871,6 +875,7 @@ export {
|
|
871
875
|
createJazzContext,
|
872
876
|
createJazzContextForNewAccount,
|
873
877
|
createJazzContextFromExistingCredentials,
|
878
|
+
createSSRJazzAgent,
|
874
879
|
experimental_defineRequest,
|
875
880
|
exportCoValue,
|
876
881
|
importContentPieces,
|
package/dist/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../src/tools/auth/clerk/index.ts","../src/tools/auth/clerk/getClerkUsername.ts","../src/tools/auth/clerk/types.ts","../src/tools/auth/DemoAuth.ts","../src/tools/auth/PassphraseAuth.ts","../src/tools/implementation/invites.ts","../src/tools/coValues/request.ts","../src/tools/index.ts"],"sourcesContent":["import {\n Account,\n AuthCredentials,\n AuthSecretStorage,\n AuthenticateAccountFunction,\n} from \"jazz-tools\";\nimport { getClerkUsername } from \"./getClerkUsername.js\";\nimport {\n ClerkCredentials,\n MinimalClerkClient,\n isClerkAuthStateEqual,\n isClerkCredentials,\n} from \"./types.js\";\n\nexport type { MinimalClerkClient };\nexport { isClerkCredentials };\n\nexport class JazzClerkAuth {\n constructor(\n private authenticate: AuthenticateAccountFunction,\n private logOut: () => Promise<void> | void,\n private authSecretStorage: AuthSecretStorage,\n ) {}\n\n /**\n * Loads the Jazz auth data from the Clerk user and sets it in the auth secret storage.\n */\n static loadClerkAuthData(\n credentials: ClerkCredentials,\n storage: AuthSecretStorage,\n ) {\n return storage.set({\n accountID: credentials.jazzAccountID,\n accountSecret: credentials.jazzAccountSecret,\n secretSeed: credentials.jazzAccountSeed\n ? Uint8Array.from(credentials.jazzAccountSeed)\n : undefined,\n provider: \"clerk\",\n });\n }\n\n static async initializeAuth(clerk: MinimalClerkClient) {\n const secretStorage = new AuthSecretStorage();\n\n if (!isClerkCredentials(clerk.user?.unsafeMetadata)) {\n return;\n }\n\n await JazzClerkAuth.loadClerkAuthData(\n clerk.user.unsafeMetadata,\n secretStorage,\n );\n }\n\n private isFirstCall = true;\n\n registerListener(clerkClient: MinimalClerkClient) {\n let previousUser: MinimalClerkClient[\"user\"] | null =\n clerkClient.user ?? null;\n\n // Need to use addListener because the clerk user object is not updated when the user logs in\n return clerkClient.addListener((event) => {\n const user = (event as Pick<MinimalClerkClient, \"user\">).user ?? null;\n\n if (!isClerkAuthStateEqual(previousUser, user) || this.isFirstCall) {\n this.onClerkUserChange({ user });\n previousUser = user;\n this.isFirstCall = false;\n }\n });\n }\n\n onClerkUserChange = async (clerkClient: Pick<MinimalClerkClient, \"user\">) => {\n const isAuthenticated = this.authSecretStorage.isAuthenticated;\n\n // LogOut is driven by Clerk. The framework adapters will need to pass `logOutReplacement` to the `JazzProvider`\n // to make the logOut work correctly.\n if (!clerkClient.user) {\n if (isAuthenticated) {\n this.authSecretStorage.clear();\n await this.logOut();\n }\n return;\n }\n\n if (isAuthenticated) return;\n\n const clerkCredentials = clerkClient.user\n .unsafeMetadata as ClerkCredentials;\n\n if (!clerkCredentials.jazzAccountID) {\n await this.signIn(clerkClient);\n } else {\n await this.logIn(clerkClient);\n }\n };\n\n logIn = async (clerkClient: Pick<MinimalClerkClient, \"user\">) => {\n if (!clerkClient.user) {\n throw new Error(\"Not signed in on Clerk\");\n }\n\n const clerkCredentials = clerkClient.user.unsafeMetadata;\n if (!isClerkCredentials(clerkCredentials)) {\n throw new Error(\"No credentials found on Clerk\");\n }\n\n const credentials = {\n accountID: clerkCredentials.jazzAccountID,\n accountSecret: clerkCredentials.jazzAccountSecret,\n secretSeed: clerkCredentials.jazzAccountSeed\n ? Uint8Array.from(clerkCredentials.jazzAccountSeed)\n : undefined,\n provider: \"clerk\",\n } satisfies AuthCredentials;\n\n await this.authenticate(credentials);\n\n await JazzClerkAuth.loadClerkAuthData(\n {\n jazzAccountID: credentials.accountID,\n jazzAccountSecret: credentials.accountSecret,\n jazzAccountSeed: clerkCredentials.jazzAccountSeed,\n },\n this.authSecretStorage,\n );\n };\n\n signIn = async (clerkClient: Pick<MinimalClerkClient, \"user\">) => {\n const credentials = await this.authSecretStorage.get();\n\n if (!credentials) {\n throw new Error(\"No credentials found\");\n }\n\n const jazzAccountSeed = credentials.secretSeed\n ? Array.from(credentials.secretSeed)\n : undefined;\n\n await clerkClient.user?.update({\n unsafeMetadata: {\n jazzAccountID: credentials.accountID,\n jazzAccountSecret: credentials.accountSecret,\n jazzAccountSeed,\n } satisfies ClerkCredentials,\n });\n\n const currentAccount = await Account.getMe().$jazz.ensureLoaded({\n resolve: {\n profile: true,\n },\n });\n\n const username = getClerkUsername(clerkClient);\n\n if (username) {\n currentAccount.profile.$jazz.set(\"name\", username);\n }\n\n await JazzClerkAuth.loadClerkAuthData(\n {\n jazzAccountID: credentials.accountID,\n jazzAccountSecret: credentials.accountSecret,\n jazzAccountSeed,\n },\n this.authSecretStorage,\n );\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace BrowserClerkAuth {\n export interface Driver {\n onError: (error: string | Error) => void;\n }\n}\n","import type { MinimalClerkClient } from \"./types.js\";\n\nexport function getClerkUsername(\n clerkClient: Pick<MinimalClerkClient, \"user\">,\n) {\n if (!clerkClient.user) {\n return null;\n }\n\n if (clerkClient.user.fullName) {\n return clerkClient.user.fullName;\n }\n\n if (clerkClient.user.firstName) {\n if (clerkClient.user.lastName) {\n return `${clerkClient.user.firstName} ${clerkClient.user.lastName}`;\n }\n\n return clerkClient.user.firstName;\n }\n\n if (clerkClient.user.username) {\n return clerkClient.user.username;\n }\n\n if (clerkClient.user.primaryEmailAddress?.emailAddress) {\n const emailUsername =\n clerkClient.user.primaryEmailAddress.emailAddress.split(\"@\")[0];\n\n if (emailUsername) {\n return emailUsername;\n }\n }\n\n return clerkClient.user.id;\n}\n","import { AgentSecret } from \"cojson\";\nimport { Account, ID } from \"jazz-tools\";\n\nexport type MinimalClerkClient = {\n user:\n | {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n unsafeMetadata: Record<string, any>;\n fullName: string | null;\n username: string | null;\n firstName: string | null;\n lastName: string | null;\n id: string;\n primaryEmailAddress: {\n emailAddress: string | null;\n } | null;\n update: (args: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n unsafeMetadata: Record<string, any>;\n }) => Promise<unknown>;\n }\n | null\n | undefined;\n signOut: () => Promise<void>;\n addListener: (listener: (data: unknown) => void) => void;\n};\n\nexport type ClerkCredentials = {\n jazzAccountID: ID<Account>;\n jazzAccountSecret: AgentSecret;\n jazzAccountSeed?: number[];\n};\n\n/**\n * Checks if the Clerk user metadata contains the necessary credentials for Jazz auth.\n * **Note**: It does not validate the credentials, only checks if the necessary fields are present in the metadata object.\n */\nexport function isClerkCredentials(\n data: NonNullable<MinimalClerkClient[\"user\"]>[\"unsafeMetadata\"] | undefined,\n): data is ClerkCredentials {\n return !!data && \"jazzAccountID\" in data && \"jazzAccountSecret\" in data;\n}\n\nexport function isClerkAuthStateEqual(\n previousUser: MinimalClerkClient[\"user\"] | null | undefined,\n newUser: MinimalClerkClient[\"user\"] | null | undefined,\n) {\n if (Boolean(previousUser) !== Boolean(newUser)) {\n return false;\n }\n\n const previousCredentials = isClerkCredentials(previousUser?.unsafeMetadata);\n const newCredentials = isClerkCredentials(newUser?.unsafeMetadata);\n\n return previousCredentials === newCredentials;\n}\n","import { AgentSecret } from \"cojson\";\nimport { Account, ID } from \"../internal.js\";\nimport { AuthenticateAccountFunction } from \"../types.js\";\nimport { AuthSecretStorage } from \"./AuthSecretStorage.js\";\nimport { KvStore, KvStoreContext } from \"./KvStoreContext.js\";\n\ntype StorageData = {\n accountID: ID<Account>;\n accountSecret: AgentSecret;\n secretSeed?: number[];\n};\n\n/**\n * `DemoAuth` provides a `JazzAuth` object for demo authentication.\n *\n * Demo authentication is useful for quickly testing your app, as it allows you to create new accounts and log in as existing ones.\n *\n * ```\n * import { DemoAuth } from \"jazz-tools\";\n *\n * const auth = new DemoAuth(jazzContext.authenticate, new AuthSecretStorage());\n * ```\n *\n * @category Auth Providers\n */\nexport class DemoAuth {\n constructor(\n private authenticate: AuthenticateAccountFunction,\n private authSecretStorage: AuthSecretStorage,\n ) {}\n\n logIn = async (username: string) => {\n const existingUsers = await this.getExisitingUsersWithData();\n const storageData = existingUsers[username];\n\n if (!storageData?.accountID) {\n throw new Error(\"User not found\");\n }\n\n await this.authenticate({\n accountID: storageData.accountID,\n accountSecret: storageData.accountSecret,\n });\n\n await this.authSecretStorage.set({\n accountID: storageData.accountID,\n accountSecret: storageData.accountSecret,\n secretSeed: storageData.secretSeed\n ? new Uint8Array(storageData.secretSeed)\n : undefined,\n provider: \"demo\",\n });\n };\n\n signUp = async (username: string) => {\n const existingUsers = await this.getExistingUsers();\n if (existingUsers.includes(username)) {\n throw new Error(\"User already registered\");\n }\n\n const credentials = await this.authSecretStorage.get();\n\n if (!credentials) {\n throw new Error(\"No credentials found\");\n }\n\n const currentAccount = await Account.getMe().$jazz.ensureLoaded({\n resolve: {\n profile: true,\n },\n });\n\n currentAccount.profile.$jazz.set(\"name\", username);\n\n await this.authSecretStorage.set({\n accountID: credentials.accountID,\n accountSecret: credentials.accountSecret,\n secretSeed: credentials.secretSeed\n ? new Uint8Array(credentials.secretSeed)\n : undefined,\n provider: \"demo\",\n });\n\n await this.addToExistingUsers(username, {\n accountID: credentials.accountID,\n accountSecret: credentials.accountSecret,\n secretSeed: credentials.secretSeed\n ? Array.from(credentials.secretSeed)\n : undefined,\n });\n };\n\n private async addToExistingUsers(username: string, data: StorageData) {\n const existingUsers = await this.getExisitingUsersWithData();\n\n if (existingUsers[username]) {\n return;\n }\n\n existingUsers[username] = data;\n\n const kvStore = KvStoreContext.getInstance().getStorage();\n await kvStore.set(\"demo-auth-users\", JSON.stringify(existingUsers));\n }\n\n private async getExisitingUsersWithData() {\n const kvStore = KvStoreContext.getInstance().getStorage();\n await migrateExistingUsers(kvStore);\n\n const existingUsers = await kvStore.get(\"demo-auth-users\");\n return existingUsers ? JSON.parse(existingUsers) : {};\n }\n\n getExistingUsers = async () => {\n return Object.keys(await this.getExisitingUsersWithData());\n };\n}\n\nexport function encodeUsername(username: string) {\n return btoa(username)\n .replace(/=/g, \"-\")\n .replace(/\\+/g, \"_\")\n .replace(/\\//g, \".\");\n}\n\nasync function getStorageVersion(kvStore: KvStore) {\n try {\n const version = await kvStore.get(\"demo-auth-storage-version\");\n return version ? parseInt(version) : 1;\n } catch (error) {\n return 1;\n }\n}\n\nasync function setStorageVersion(kvStore: KvStore, version: number) {\n await kvStore.set(\"demo-auth-storage-version\", version.toString());\n}\n\nasync function getExistingUsersList(kvStore: KvStore) {\n const existingUsers = await kvStore.get(\"demo-auth-existing-users\");\n return existingUsers ? existingUsers.split(\",\") : [];\n}\n\n/**\n * Migrates existing users keys to work with any storage.\n */\nasync function migrateExistingUsers(kvStore: KvStore) {\n if ((await getStorageVersion(kvStore)) < 2) {\n const existingUsers = await getExistingUsersList(kvStore);\n\n for (const username of existingUsers) {\n const legacyKey = `demo-auth-existing-users-${username}`;\n const storageData = await kvStore.get(legacyKey);\n if (storageData) {\n await kvStore.set(\n `demo-auth-existing-users-${encodeUsername(username)}`,\n storageData,\n );\n await kvStore.delete(legacyKey);\n }\n }\n\n await setStorageVersion(kvStore, 2);\n }\n\n if ((await getStorageVersion(kvStore)) < 3) {\n const existingUsersList = await getExistingUsersList(kvStore);\n\n const existingUsers: Record<string, StorageData> = {};\n const keysToDelete: string[] = [\"demo-auth-existing-users\"];\n\n for (const username of existingUsersList) {\n const key = `demo-auth-existing-users-${encodeUsername(username)}`;\n const storageData = await kvStore.get(key);\n if (storageData) {\n existingUsers[username] = JSON.parse(storageData);\n keysToDelete.push(key);\n }\n }\n\n await kvStore.set(\"demo-auth-users\", JSON.stringify(existingUsers));\n\n for (const key of keysToDelete) {\n await kvStore.delete(key);\n }\n\n await setStorageVersion(kvStore, 3);\n }\n}\n","import * as bip39 from \"@scure/bip39\";\nimport { entropyToMnemonic } from \"@scure/bip39\";\nimport { CryptoProvider, cojsonInternals } from \"cojson\";\nimport type { ID } from \"../internal.js\";\nimport { Account } from \"../internal.js\";\nimport type {\n AuthenticateAccountFunction,\n RegisterAccountFunction,\n} from \"../types.js\";\nimport { AuthSecretStorage } from \"./AuthSecretStorage.js\";\n\n/**\n * `PassphraseAuth` provides a `JazzAuth` object for passphrase authentication.\n *\n * ```ts\n * import { PassphraseAuth } from \"jazz-tools\";\n *\n * const auth = new PassphraseAuth(crypto, jazzContext.authenticate, new AuthSecretStorage(), wordlist);\n * ```\n *\n * @category Auth Providers\n */\nexport class PassphraseAuth {\n passphrase: string = \"\";\n\n constructor(\n private crypto: CryptoProvider,\n private authenticate: AuthenticateAccountFunction,\n private register: RegisterAccountFunction,\n private authSecretStorage: AuthSecretStorage,\n public wordlist: string[],\n ) {}\n\n logIn = async (passphrase: string) => {\n const { crypto, authenticate } = this;\n\n let secretSeed;\n\n try {\n secretSeed = bip39.mnemonicToEntropy(passphrase, this.wordlist);\n } catch (e) {\n throw new Error(\"Invalid passphrase\");\n }\n\n const accountSecret = crypto.agentSecretFromSecretSeed(secretSeed);\n\n const accountID = cojsonInternals.idforHeader(\n cojsonInternals.accountHeaderForInitialAgentSecret(accountSecret, crypto),\n crypto,\n ) as ID<Account>;\n\n await authenticate({\n accountID,\n accountSecret,\n });\n\n await this.authSecretStorage.set({\n accountID,\n secretSeed,\n accountSecret,\n provider: \"passphrase\",\n });\n\n this.passphrase = passphrase;\n this.notify();\n };\n\n signUp = async (name?: string) => {\n const credentials = await this.authSecretStorage.get();\n\n if (!credentials || !credentials.secretSeed) {\n throw new Error(\"No credentials found\");\n }\n\n const passphrase = entropyToMnemonic(credentials.secretSeed, this.wordlist);\n\n await this.authSecretStorage.set({\n accountID: credentials.accountID,\n secretSeed: credentials.secretSeed,\n accountSecret: credentials.accountSecret,\n provider: \"passphrase\",\n });\n\n if (name?.trim()) {\n const currentAccount = await Account.getMe().$jazz.ensureLoaded({\n resolve: {\n profile: true,\n },\n });\n\n currentAccount.profile.$jazz.set(\"name\", name);\n }\n\n return passphrase;\n };\n\n registerNewAccount = async (passphrase: string, name: string) => {\n const secretSeed = bip39.mnemonicToEntropy(passphrase, this.wordlist);\n const accountSecret = this.crypto.agentSecretFromSecretSeed(secretSeed);\n const accountID = await this.register(accountSecret, { name });\n\n await this.authSecretStorage.set({\n accountID,\n secretSeed,\n accountSecret,\n provider: \"passphrase\",\n });\n\n return accountID;\n };\n\n getCurrentAccountPassphrase = async () => {\n const credentials = await this.authSecretStorage.get();\n\n if (!credentials || !credentials.secretSeed) {\n throw new Error(\"No credentials found\");\n }\n\n return entropyToMnemonic(credentials.secretSeed, this.wordlist);\n };\n\n generateRandomPassphrase = () => {\n return entropyToMnemonic(this.crypto.newRandomSecretSeed(), this.wordlist);\n };\n\n loadCurrentAccountPassphrase = async () => {\n const passphrase = await this.getCurrentAccountPassphrase();\n this.passphrase = passphrase;\n this.notify();\n };\n\n listeners = new Set<() => void>();\n subscribe = (callback: () => void) => {\n this.listeners.add(callback);\n\n return () => {\n this.listeners.delete(callback);\n };\n };\n\n notify() {\n for (const listener of this.listeners) {\n listener();\n }\n }\n}\n","import { type InviteSecret, cojsonInternals } from \"cojson\";\nimport { Account } from \"../coValues/account.js\";\nimport type {\n CoValue,\n CoValueClass,\n CoValueClassOrSchema,\n ID,\n} from \"../internal.js\";\n\n/** @category Invite Links */\nexport function createInviteLink<C extends CoValue>(\n value: C,\n role: \"reader\" | \"writer\" | \"admin\" | \"writeOnly\",\n baseURL: string,\n valueHint?: string,\n): string {\n const coValueCore = value.$jazz.raw.core;\n let currentCoValue = coValueCore;\n\n while (currentCoValue.verified.header.ruleset.type === \"ownedByGroup\") {\n currentCoValue = currentCoValue.getGroup().core;\n }\n\n const { ruleset, meta } = currentCoValue.verified.header;\n\n if (ruleset.type !== \"group\" || meta?.type === \"account\") {\n throw new Error(\"Can't create invite link for object without group\");\n }\n\n const group = cojsonInternals.expectGroup(currentCoValue.getCurrentContent());\n const inviteSecret = group.createInvite(role);\n\n return `${baseURL}#/invite/${valueHint ? valueHint + \"/\" : \"\"}${\n value.$jazz.id\n }/${inviteSecret}`;\n}\n\n/** @category Invite Links */\nexport function parseInviteLink(inviteURL: string):\n | {\n valueID: string;\n valueHint?: string;\n inviteSecret: InviteSecret;\n }\n | undefined {\n const url = new URL(inviteURL);\n const parts = url.hash.split(\"/\");\n\n let valueHint: string | undefined;\n let valueID: string | undefined;\n let inviteSecret: InviteSecret | undefined;\n\n if (parts[0] === \"#\" && parts[1] === \"invite\") {\n if (parts.length === 5) {\n valueHint = parts[2];\n valueID = parts[3];\n inviteSecret = parts[4] as InviteSecret;\n } else if (parts.length === 4) {\n valueID = parts[2];\n inviteSecret = parts[3] as InviteSecret;\n }\n\n if (!valueID || !inviteSecret) {\n return undefined;\n }\n return { valueID, inviteSecret, valueHint };\n }\n}\n\n/** @category Invite Links */\nexport function consumeInviteLink<S extends CoValueClassOrSchema>({\n inviteURL,\n as = Account.getMe(),\n forValueHint,\n invitedObjectSchema,\n}: {\n inviteURL: string;\n as?: Account;\n forValueHint?: string;\n invitedObjectSchema: S;\n}): Promise<\n | {\n valueID: string;\n valueHint?: string;\n inviteSecret: InviteSecret;\n }\n | undefined\n> {\n return new Promise((resolve, reject) => {\n const result = parseInviteLink(inviteURL);\n\n if (result && result.valueHint === forValueHint) {\n as.acceptInvite(result.valueID, result.inviteSecret, invitedObjectSchema)\n .then(() => {\n resolve(result);\n })\n .catch(reject);\n } else {\n resolve(undefined);\n }\n });\n}\n","import {\n CoValueCore,\n CojsonInternalTypes,\n CryptoProvider,\n RawAccount,\n RawCoMap,\n cojsonInternals,\n} from \"cojson\";\nimport z from \"zod/v4\";\nimport {\n AnyZodOrCoValueSchema,\n CoMap,\n CoMapSchema,\n CoMapSchemaInit,\n CoValueClass,\n CoreCoMapSchema,\n Group,\n Loaded,\n ResolveQuery,\n ResolveQueryStrict,\n Simplify,\n coMapDefiner,\n coValueClassFromCoValueClassOrSchema,\n exportCoValue,\n importContentPieces,\n loadCoValue,\n} from \"../internal.js\";\nimport { isCoValueId } from \"../lib/id.js\";\nimport { Account } from \"./account.js\";\n\ntype MessageShape = Record<string, AnyZodOrCoValueSchema>;\n\ntype RequestSchemaDefinition<\n S extends MessageShape,\n R extends ResolveQuery<CoMapSchema<S>> = true,\n> =\n | S\n | {\n schema: S;\n resolve?: R;\n };\n\n/**\n * Configuration options for defining HTTP request/response schemas in Jazz.\n *\n * This interface defines the structure for creating typed HTTP routes with\n * request and response validation using CoMap schemas.\n *\n * @template RequestShape - The shape of the request message schema (must extend MessageShape)\n * @template RequestResolve - The resolve query type for the request CoMap schema\n * @template ResponseShape - The shape of the response message schema (must extend MessageShape)\n * @template ResponseResolve - The resolve query type for the response CoMap schema\n */\ninterface RequestOptions<\n RequestShape extends MessageShape,\n RequestResolve extends ResolveQuery<CoMapSchema<RequestShape>>,\n ResponseShape extends MessageShape,\n ResponseResolve extends ResolveQuery<CoMapSchema<ResponseShape>>,\n> {\n /**\n * The URL endpoint for the HTTP route.\n * This is used by the client to send requests to the server.\n */\n url: string;\n\n /**\n * The id of the worker Account or Group.\n */\n workerId: string;\n\n /**\n * Schema definition for the request payload.\n * Can be either a direct schema object or an object with schema and optional resolve properties.\n * The schema defines the structure and validation rules for incoming requests.\n */\n request: RequestSchemaDefinition<\n RequestShape,\n ResolveQueryStrict<CoMapSchema<RequestShape>, RequestResolve>\n >;\n\n /**\n * Schema definition for the response payload.\n * Can be either a direct schema object or an object with schema and optional resolve properties.\n * The schema defines the structure and validation rules for outgoing responses.\n */\n response: RequestSchemaDefinition<\n ResponseShape,\n ResolveQueryStrict<CoMapSchema<ResponseShape>, ResponseResolve>\n >;\n}\n\ntype AsNullablePayload<T extends MessageShape> = T extends Record<string, never>\n ? undefined\n : never;\ntype MessageValuePayload<T extends MessageShape> =\n | Simplify<CoMapSchemaInit<T>>\n | AsNullablePayload<T>;\n\nfunction createMessageEnvelope<S extends MessageShape>(\n schema: CoreCoMapSchema,\n value: MessageValuePayload<S>,\n owner: Account,\n sharedWith: Account | Group,\n type: \"request\" | \"response\",\n): Loaded<CoMapSchema<S>> {\n const group = Group.create({ owner });\n\n if (type === \"request\") {\n group.addMember(sharedWith, \"writer\");\n } else {\n group.addMember(sharedWith, \"reader\");\n }\n\n // @ts-expect-error - CoreCoMapSchema doesn't have static methods\n return schema.create(value ?? {}, group);\n}\n\n/**\n * Function that exports the input CoValue in a serializable format and prepares the information\n * required for the other side to safely verify the identity of the sender.\n */\nasync function serializeMessagePayload({\n type,\n schema,\n resolve,\n value,\n owner,\n target,\n}: {\n // Skipping type validation here to avoid excessive type complexity that affects the typecheck performance\n type: \"request\" | \"response\";\n schema: CoreCoMapSchema;\n resolve: any;\n value: any;\n owner: Account;\n target: Account | Group;\n}) {\n const me = owner ?? Account.getMe();\n const node = me.$jazz.localNode;\n const crypto = node.crypto;\n\n const agent = node.getCurrentAgent();\n const signerID = agent.currentSignerID();\n const signerSecret = agent.currentSignerSecret();\n\n const envelope = createMessageEnvelope(schema, value, me, target, type);\n\n const contentPieces =\n (await exportCoValue(schema, envelope.$jazz.id, {\n resolve,\n loadAs: me,\n bestEffortResolution: true,\n })) ?? [];\n\n const createdAt = Date.now();\n\n const signPayload = crypto.secureHash({\n contentPieces,\n id: envelope.$jazz.id,\n createdAt,\n signerID,\n });\n\n const authToken = crypto.sign(signerSecret, signPayload);\n\n return {\n contentPieces,\n id: envelope.$jazz.id,\n createdAt,\n authToken,\n signerID,\n };\n}\n\nconst requestSchema = z.object({\n contentPieces: z.array(z.json()),\n id: z.custom<`co_z${string}`>(isCoValueId),\n createdAt: z.number(),\n authToken: z.custom<`signature_z${string}`>(\n (value) => typeof value === \"string\" && value.startsWith(\"signature_z\"),\n ),\n signerID: z.custom<`signer_z${string}`>(\n (value) => typeof value === \"string\" && value.startsWith(\"signer_z\"),\n ),\n});\n\n/**\n * Function that parses the message payload, verifies the identity of the sender and loads the data.\n *\n * @returns The data from the message.\n */\nasync function handleMessagePayload({\n type,\n schema,\n resolve,\n request,\n loadAs,\n}: {\n type: \"request\" | \"response\";\n // Skipping type validation here to avoid excessive type complexity that affects the typecheck performance\n schema: CoreCoMapSchema;\n resolve: any;\n request: unknown;\n loadAs: Account;\n}) {\n const node = loadAs.$jazz.localNode;\n const crypto = node.crypto;\n\n const requestParsed = requestSchema.safeParse(request);\n\n if (!requestParsed.success) {\n throw new JazzRequestError(\n \"Request payload is not valid\",\n 400,\n requestParsed.error,\n );\n }\n\n const requestData = requestParsed.data;\n\n if (type === \"request\") {\n const core = await node.loadCoValueCore(requestData.id, undefined, true);\n\n // Check if the message has already been handled to prevent replay attacks\n if (core.isAvailable()) {\n const content = core.getCurrentContent() as RawCoMap;\n\n if (content.get(\"$handled\") === loadAs.$jazz.id) {\n throw new JazzRequestError(\"Request payload is already handled\", 400);\n }\n }\n\n // Check if the message is expired as extra protection\n if (requestData.createdAt + 1000 * 60 < Date.now()) {\n throw new JazzRequestError(\"Authentication token is expired\", 401);\n }\n }\n\n // Verify the signature of the message to prevent tampering\n const signPayload = crypto.secureHash({\n contentPieces: requestData.contentPieces,\n id: requestData.id,\n createdAt: requestData.createdAt,\n signerID: requestData.signerID,\n });\n\n if (\n !safeVerifySignature(\n crypto,\n signPayload,\n requestData.signerID,\n requestData.authToken,\n )\n ) {\n throw new JazzRequestError(\"Invalid signature\", 401);\n }\n\n let contentPieces =\n requestData.contentPieces as CojsonInternalTypes.NewContentMessage[];\n\n if (type === \"request\") {\n const coValueContent = contentPieces.find(\n (piece) => piece.id === requestData.id,\n );\n\n if (coValueContent && coValueContent.header) {\n const validValues = cojsonInternals.getDependedOnCoValues(\n coValueContent.header,\n coValueContent,\n );\n validValues.add(requestData.id);\n contentPieces = contentPieces.filter((piece) =>\n validValues.has(piece.id),\n );\n } else {\n contentPieces = [];\n }\n }\n\n importContentPieces(contentPieces, loadAs);\n\n const coValue = await node.loadCoValueCore(requestData.id);\n const accountId = getCoValueCreatorAccountId(coValue);\n\n const madeBy = await Account.load(accountId, {\n loadAs,\n });\n\n if (!madeBy) {\n throw new JazzRequestError(\"Creator account not found\", 400);\n }\n\n const coSchema = coValueClassFromCoValueClassOrSchema(\n schema,\n ) as CoValueClass<CoMap>;\n const value = await loadCoValue<CoMap, true>(coSchema, requestData.id, {\n resolve,\n loadAs,\n });\n\n if (!value) {\n throw new JazzRequestError(\"Value not found\", 400);\n }\n\n if (type === \"request\") {\n value.$jazz.raw.set(\"$handled\", loadAs.$jazz.id);\n }\n\n return {\n value: value as unknown,\n madeBy,\n };\n}\n\nfunction parseSchemaAndResolve<\n S extends MessageShape,\n R extends ResolveQuery<CoMapSchema<S>>,\n>(options: RequestSchemaDefinition<S, R>) {\n if (\"schema\" in options) {\n return {\n // Using a type cast to reduce the type complexity\n schema: coMapDefiner(options.schema) as CoreCoMapSchema,\n resolve: options.resolve as any,\n };\n }\n\n return {\n schema: coMapDefiner(options) as CoreCoMapSchema,\n resolve: true as any,\n };\n}\n\nexport class HttpRoute<\n RequestShape extends MessageShape = z.core.$ZodLooseShape,\n RequestResolve extends ResolveQuery<CoMapSchema<RequestShape>> = any,\n ResponseShape extends MessageShape = z.core.$ZodLooseShape,\n ResponseResolve extends ResolveQuery<CoMapSchema<ResponseShape>> = any,\n> {\n private requestDefinition: {\n schema: CoreCoMapSchema;\n resolve: any;\n };\n private responseDefinition: {\n schema: CoreCoMapSchema;\n resolve: any;\n };\n private url: string;\n private workerId: string;\n\n constructor(\n params: RequestOptions<\n RequestShape,\n RequestResolve,\n ResponseShape,\n ResponseResolve\n >,\n ) {\n this.requestDefinition = parseSchemaAndResolve(params.request);\n this.responseDefinition = parseSchemaAndResolve(params.response);\n this.url = params.url;\n this.workerId = params.workerId;\n\n if (params.workerId === undefined) {\n throw new TypeError(\"Worker ID is required\");\n }\n }\n\n async send(\n values: MessageValuePayload<RequestShape>,\n options?: { owner?: Account },\n ): Promise<Loaded<CoMapSchema<ResponseShape>, ResponseResolve>> {\n const as = options?.owner ?? Account.getMe();\n\n const target = await loadWorkerAccountOrGroup(this.workerId, as);\n if (!target) {\n throw new JazzRequestError(\"Worker account not found\", 400);\n }\n\n const response = await fetch(this.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(\n await serializeMessagePayload({\n type: \"request\",\n schema: this.requestDefinition.schema,\n resolve: true, // export only the envelope\n value: values,\n owner: as,\n target,\n }),\n ),\n });\n\n if (!response.ok) {\n if (response.headers.has(\"X-Jazz-Request-Error\")) {\n const error = await response.json();\n throw new JazzRequestError(error.message, error.code, error.details);\n }\n\n throw new JazzRequestError(\"Request failed\", response.status);\n }\n\n const responseBody = await response.json();\n\n const responseParsed = z\n .object({\n type: z.literal(\"success\"),\n payload: z.any(),\n })\n .safeParse(responseBody);\n\n if (!responseParsed.success) {\n throw new JazzRequestError(\n \"Response payload is not valid\",\n 400,\n responseParsed.error,\n );\n }\n\n const data = await handleMessagePayload({\n type: \"response\",\n schema: this.responseDefinition.schema,\n resolve: this.responseDefinition.resolve,\n request: responseParsed.data.payload,\n loadAs: as,\n });\n\n return data.value as Loaded<CoMapSchema<ResponseShape>, ResponseResolve>;\n }\n\n handle = async (\n request: Request,\n as: Account,\n callback: (\n value: Loaded<CoMapSchema<RequestShape>, RequestResolve>,\n madeBy: Account,\n ) =>\n | Promise<MessageValuePayload<ResponseShape>>\n | MessageValuePayload<ResponseShape>,\n ): Promise<Response> => {\n try {\n const response = await this.executeHandleRequest(request, as, callback);\n return response;\n } catch (error) {\n // Serialize the error to make it possible to handle it on the client side\n if (isJazzRequestError(error)) {\n return new Response(JSON.stringify(error.toJSON()), {\n status: error.code,\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Jazz-Request-Error\": \"true\",\n },\n });\n }\n\n throw error;\n }\n };\n\n executeHandleRequest = async (\n request: Request,\n as: Account,\n callback: (\n value: Loaded<CoMapSchema<RequestShape>, RequestResolve>,\n madeBy: Account,\n ) =>\n | Promise<MessageValuePayload<ResponseShape>>\n | MessageValuePayload<ResponseShape>,\n ): Promise<Response> => {\n const node = as.$jazz.localNode;\n const body = await request.json();\n const data = await handleMessagePayload({\n type: \"request\",\n schema: this.requestDefinition.schema,\n resolve: this.requestDefinition.resolve,\n request: body,\n loadAs: as,\n });\n\n const tracking = node.syncManager.trackDirtyCoValues();\n\n const responseValue = await callback(\n data.value as Loaded<CoMapSchema<RequestShape>, RequestResolve>,\n data.madeBy,\n );\n\n const responsePayload = await serializeMessagePayload({\n type: \"response\",\n schema: this.responseDefinition.schema,\n resolve: this.responseDefinition.resolve,\n value: responseValue,\n owner: as,\n target: data.madeBy,\n });\n\n const responseBody = JSON.stringify({\n type: \"success\",\n payload: responsePayload,\n });\n\n // TODO: Detect the defer support from the environment\n await Promise.all(\n Array.from(tracking.done(), (id) => node.syncManager.waitForSync(id)),\n );\n\n return new Response(responseBody, {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n };\n\n get requestSchema(): CoMapSchema<RequestShape> {\n return this.requestDefinition.schema as CoMapSchema<RequestShape>;\n }\n\n get responseSchema() {\n return this.responseDefinition.schema as CoMapSchema<ResponseShape>;\n }\n}\n\n/**\n * Define a request route.\n *\n * @param params - The parameters for the request route.\n * @returns The request route.\n *\n * @see {@link https://jazz.tools/docs/react/server-side/http-requests}\n */\nexport function experimental_defineRequest<\n RequestShape extends MessageShape,\n RequestResolve extends ResolveQuery<CoMapSchema<RequestShape>>,\n ResponseShape extends MessageShape,\n ResponseResolve extends ResolveQuery<CoMapSchema<ResponseShape>>,\n>(\n params: RequestOptions<\n RequestShape,\n RequestResolve,\n ResponseShape,\n ResponseResolve\n >,\n) {\n return new HttpRoute(params);\n}\n\nfunction getCoValueCreatorAccountId(coValue: CoValueCore) {\n if (!coValue.isAvailable()) {\n throw new Error(\"Unable to load the request payload\");\n }\n\n const creatorSessionId = coValue.getValidSortedTransactions().at(0)\n ?.txID.sessionID;\n\n if (!creatorSessionId) {\n throw new JazzRequestError(\n \"Request payload is not valid, creator session ID not found\",\n 400,\n );\n }\n\n const accountId =\n cojsonInternals.accountOrAgentIDfromSessionID(creatorSessionId);\n\n if (!isCoValueId(accountId)) {\n throw new JazzRequestError(\n \"Request payload is not valid, the creator is not a valid account\",\n 400,\n );\n }\n\n return accountId;\n}\n\nexport class JazzRequestError {\n public readonly isJazzRequestError = true;\n\n constructor(\n public readonly message: string,\n public readonly code: number,\n public readonly details?: unknown,\n ) {}\n\n toJSON() {\n return { message: this.message, code: this.code, details: this.details };\n }\n}\n\nexport function isJazzRequestError(error: unknown): error is JazzRequestError {\n return (\n error instanceof JazzRequestError ||\n (typeof error === \"object\" &&\n error !== null &&\n \"isJazzRequestError\" in error &&\n Boolean(error.isJazzRequestError))\n );\n}\n\nfunction safeVerifySignature(\n crypto: CryptoProvider,\n signPayload: `hash_z${string}`,\n signerID: `signer_z${string}`,\n authToken: `signature_z${string}`,\n) {\n try {\n return crypto.verify(authToken, signPayload, signerID);\n } catch (error) {\n return false;\n }\n}\n\nasync function loadWorkerAccountOrGroup(id: string, loadAs: Account) {\n const node = loadAs.$jazz.localNode;\n const coValue = await node.loadCoValueCore(id as `co_z${string}`);\n\n if (!coValue.isAvailable()) {\n return null;\n }\n\n const content = coValue.getCurrentContent();\n\n if (content instanceof RawAccount) {\n return Account.load(content.id, {\n loadAs,\n });\n }\n\n return Group.load(content.id, {\n loadAs,\n });\n}\n","export * from \"./exports.js\";\n\nexport {\n cojsonInternals,\n logger,\n LogLevel,\n} from \"cojson\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE,WAAAA;AAAA,EAEA,qBAAAC;AAAA,OAEK;;;ACHA,SAAS,iBACd,aACA;AACA,MAAI,CAAC,YAAY,MAAM;AACrB,WAAO;AAAA,EACT;AAEA,MAAI,YAAY,KAAK,UAAU;AAC7B,WAAO,YAAY,KAAK;AAAA,EAC1B;AAEA,MAAI,YAAY,KAAK,WAAW;AAC9B,QAAI,YAAY,KAAK,UAAU;AAC7B,aAAO,GAAG,YAAY,KAAK,SAAS,IAAI,YAAY,KAAK,QAAQ;AAAA,IACnE;AAEA,WAAO,YAAY,KAAK;AAAA,EAC1B;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,IACF;AAAA,EACF;AAEA,QAAM,YACJA,iBAAgB,8BAA8B,gBAAgB;AAEhE,MAAI,CAAC,YAAY,SAAS,GAAG;AAC3B,UAAM,IAAI;AAAA,MACR;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEO,IAAM,mBAAN,MAAuB;AAAA,EAG5B,YACkB,SACA,MACA,SAChB;AAHgB;AACA;AACA;AALlB,SAAgB,qBAAqB;AAAA,EAMlC;AAAA,EAEH,SAAS;AACP,WAAO,EAAE,SAAS,KAAK,SAAS,MAAM,KAAK,MAAM,SAAS,KAAK,QAAQ;AAAA,EACzE;AACF;AAEO,SAAS,mBAAmB,OAA2C;AAC5E,SACE,iBAAiB,oBAChB,OAAO,UAAU,YAChB,UAAU,QACV,wBAAwB,SACxB,QAAQ,MAAM,kBAAkB;AAEtC;AAEA,SAAS,oBACP,QACA,aACA,UACA,WACA;AACA,MAAI;AACF,WAAO,OAAO,OAAO,WAAW,aAAa,QAAQ;AAAA,EACvD,SAAS,OAAO;AACd,WAAO;AAAA,EACT;AACF;AAEA,eAAe,yBAAyB,IAAY,QAAiB;AACnE,QAAM,OAAO,OAAO,MAAM;AAC1B,QAAM,UAAU,MAAM,KAAK,gBAAgB,EAAqB;AAEhE,MAAI,CAAC,QAAQ,YAAY,GAAG;AAC1B,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,QAAQ,kBAAkB;AAE1C,MAAI,mBAAmB,YAAY;AACjC,WAAO,QAAQ,KAAK,QAAQ,IAAI;AAAA,MAC9B;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO,MAAM,KAAK,QAAQ,IAAI;AAAA,IAC5B;AAAA,EACF,CAAC;AACH;;;ACtnBA;AAAA,EACE,mBAAAC;AAAA,EACA;AAAA,EACA;AAAA,OACK;","names":["Account","AuthSecretStorage","Account","AuthSecretStorage","cojsonInternals","cojsonInternals","cojsonInternals","cojsonInternals","cojsonInternals"]}
|
1
|
+
{"version":3,"sources":["../src/tools/auth/clerk/index.ts","../src/tools/auth/clerk/getClerkUsername.ts","../src/tools/auth/clerk/types.ts","../src/tools/auth/DemoAuth.ts","../src/tools/auth/PassphraseAuth.ts","../src/tools/implementation/invites.ts","../src/tools/coValues/request.ts","../src/tools/index.ts"],"sourcesContent":["import {\n Account,\n AuthCredentials,\n AuthSecretStorage,\n AuthenticateAccountFunction,\n} from \"jazz-tools\";\nimport { getClerkUsername } from \"./getClerkUsername.js\";\nimport {\n ClerkCredentials,\n MinimalClerkClient,\n isClerkAuthStateEqual,\n isClerkCredentials,\n} from \"./types.js\";\n\nexport type { MinimalClerkClient };\nexport { isClerkCredentials };\n\nexport class JazzClerkAuth {\n constructor(\n private authenticate: AuthenticateAccountFunction,\n private logOut: () => Promise<void> | void,\n private authSecretStorage: AuthSecretStorage,\n ) {}\n\n /**\n * Loads the Jazz auth data from the Clerk user and sets it in the auth secret storage.\n */\n static loadClerkAuthData(\n credentials: ClerkCredentials,\n storage: AuthSecretStorage,\n ) {\n return storage.set({\n accountID: credentials.jazzAccountID,\n accountSecret: credentials.jazzAccountSecret,\n secretSeed: credentials.jazzAccountSeed\n ? Uint8Array.from(credentials.jazzAccountSeed)\n : undefined,\n provider: \"clerk\",\n });\n }\n\n static async initializeAuth(clerk: MinimalClerkClient) {\n const secretStorage = new AuthSecretStorage();\n\n if (!isClerkCredentials(clerk.user?.unsafeMetadata)) {\n return;\n }\n\n await JazzClerkAuth.loadClerkAuthData(\n clerk.user.unsafeMetadata,\n secretStorage,\n );\n }\n\n private isFirstCall = true;\n\n registerListener(clerkClient: MinimalClerkClient) {\n let previousUser: MinimalClerkClient[\"user\"] | null =\n clerkClient.user ?? null;\n\n // Need to use addListener because the clerk user object is not updated when the user logs in\n return clerkClient.addListener((event) => {\n const user = (event as Pick<MinimalClerkClient, \"user\">).user ?? null;\n\n if (!isClerkAuthStateEqual(previousUser, user) || this.isFirstCall) {\n this.onClerkUserChange({ user });\n previousUser = user;\n this.isFirstCall = false;\n }\n });\n }\n\n onClerkUserChange = async (clerkClient: Pick<MinimalClerkClient, \"user\">) => {\n const isAuthenticated = this.authSecretStorage.isAuthenticated;\n\n // LogOut is driven by Clerk. The framework adapters will need to pass `logOutReplacement` to the `JazzProvider`\n // to make the logOut work correctly.\n if (!clerkClient.user) {\n if (isAuthenticated) {\n this.authSecretStorage.clear();\n await this.logOut();\n }\n return;\n }\n\n if (isAuthenticated) return;\n\n const clerkCredentials = clerkClient.user\n .unsafeMetadata as ClerkCredentials;\n\n if (!clerkCredentials.jazzAccountID) {\n await this.signIn(clerkClient);\n } else {\n await this.logIn(clerkClient);\n }\n };\n\n logIn = async (clerkClient: Pick<MinimalClerkClient, \"user\">) => {\n if (!clerkClient.user) {\n throw new Error(\"Not signed in on Clerk\");\n }\n\n const clerkCredentials = clerkClient.user.unsafeMetadata;\n if (!isClerkCredentials(clerkCredentials)) {\n throw new Error(\"No credentials found on Clerk\");\n }\n\n const credentials = {\n accountID: clerkCredentials.jazzAccountID,\n accountSecret: clerkCredentials.jazzAccountSecret,\n secretSeed: clerkCredentials.jazzAccountSeed\n ? Uint8Array.from(clerkCredentials.jazzAccountSeed)\n : undefined,\n provider: \"clerk\",\n } satisfies AuthCredentials;\n\n await this.authenticate(credentials);\n\n await JazzClerkAuth.loadClerkAuthData(\n {\n jazzAccountID: credentials.accountID,\n jazzAccountSecret: credentials.accountSecret,\n jazzAccountSeed: clerkCredentials.jazzAccountSeed,\n },\n this.authSecretStorage,\n );\n };\n\n signIn = async (clerkClient: Pick<MinimalClerkClient, \"user\">) => {\n const credentials = await this.authSecretStorage.get();\n\n if (!credentials) {\n throw new Error(\"No credentials found\");\n }\n\n const jazzAccountSeed = credentials.secretSeed\n ? Array.from(credentials.secretSeed)\n : undefined;\n\n await clerkClient.user?.update({\n unsafeMetadata: {\n jazzAccountID: credentials.accountID,\n jazzAccountSecret: credentials.accountSecret,\n jazzAccountSeed,\n } satisfies ClerkCredentials,\n });\n\n const currentAccount = await Account.getMe().$jazz.ensureLoaded({\n resolve: {\n profile: true,\n },\n });\n\n const username = getClerkUsername(clerkClient);\n\n if (username) {\n currentAccount.profile.$jazz.set(\"name\", username);\n }\n\n await JazzClerkAuth.loadClerkAuthData(\n {\n jazzAccountID: credentials.accountID,\n jazzAccountSecret: credentials.accountSecret,\n jazzAccountSeed,\n },\n this.authSecretStorage,\n );\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace BrowserClerkAuth {\n export interface Driver {\n onError: (error: string | Error) => void;\n }\n}\n","import type { MinimalClerkClient } from \"./types.js\";\n\nexport function getClerkUsername(\n clerkClient: Pick<MinimalClerkClient, \"user\">,\n) {\n if (!clerkClient.user) {\n return null;\n }\n\n if (clerkClient.user.fullName) {\n return clerkClient.user.fullName;\n }\n\n if (clerkClient.user.firstName) {\n if (clerkClient.user.lastName) {\n return `${clerkClient.user.firstName} ${clerkClient.user.lastName}`;\n }\n\n return clerkClient.user.firstName;\n }\n\n if (clerkClient.user.username) {\n return clerkClient.user.username;\n }\n\n if (clerkClient.user.primaryEmailAddress?.emailAddress) {\n const emailUsername =\n clerkClient.user.primaryEmailAddress.emailAddress.split(\"@\")[0];\n\n if (emailUsername) {\n return emailUsername;\n }\n }\n\n return clerkClient.user.id;\n}\n","import { AgentSecret } from \"cojson\";\nimport { Account, ID } from \"jazz-tools\";\n\nexport type MinimalClerkClient = {\n user:\n | {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n unsafeMetadata: Record<string, any>;\n fullName: string | null;\n username: string | null;\n firstName: string | null;\n lastName: string | null;\n id: string;\n primaryEmailAddress: {\n emailAddress: string | null;\n } | null;\n update: (args: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n unsafeMetadata: Record<string, any>;\n }) => Promise<unknown>;\n }\n | null\n | undefined;\n signOut: () => Promise<void>;\n addListener: (listener: (data: unknown) => void) => void;\n};\n\nexport type ClerkCredentials = {\n jazzAccountID: ID<Account>;\n jazzAccountSecret: AgentSecret;\n jazzAccountSeed?: number[];\n};\n\n/**\n * Checks if the Clerk user metadata contains the necessary credentials for Jazz auth.\n * **Note**: It does not validate the credentials, only checks if the necessary fields are present in the metadata object.\n */\nexport function isClerkCredentials(\n data: NonNullable<MinimalClerkClient[\"user\"]>[\"unsafeMetadata\"] | undefined,\n): data is ClerkCredentials {\n return !!data && \"jazzAccountID\" in data && \"jazzAccountSecret\" in data;\n}\n\nexport function isClerkAuthStateEqual(\n previousUser: MinimalClerkClient[\"user\"] | null | undefined,\n newUser: MinimalClerkClient[\"user\"] | null | undefined,\n) {\n if (Boolean(previousUser) !== Boolean(newUser)) {\n return false;\n }\n\n const previousCredentials = isClerkCredentials(previousUser?.unsafeMetadata);\n const newCredentials = isClerkCredentials(newUser?.unsafeMetadata);\n\n return previousCredentials === newCredentials;\n}\n","import { AgentSecret } from \"cojson\";\nimport { Account, ID } from \"../internal.js\";\nimport { AuthenticateAccountFunction } from \"../types.js\";\nimport { AuthSecretStorage } from \"./AuthSecretStorage.js\";\nimport { KvStore, KvStoreContext } from \"./KvStoreContext.js\";\n\ntype StorageData = {\n accountID: ID<Account>;\n accountSecret: AgentSecret;\n secretSeed?: number[];\n};\n\n/**\n * `DemoAuth` provides a `JazzAuth` object for demo authentication.\n *\n * Demo authentication is useful for quickly testing your app, as it allows you to create new accounts and log in as existing ones.\n *\n * ```\n * import { DemoAuth } from \"jazz-tools\";\n *\n * const auth = new DemoAuth(jazzContext.authenticate, new AuthSecretStorage());\n * ```\n *\n * @category Auth Providers\n */\nexport class DemoAuth {\n constructor(\n private authenticate: AuthenticateAccountFunction,\n private authSecretStorage: AuthSecretStorage,\n ) {}\n\n logIn = async (username: string) => {\n const existingUsers = await this.getExisitingUsersWithData();\n const storageData = existingUsers[username];\n\n if (!storageData?.accountID) {\n throw new Error(\"User not found\");\n }\n\n await this.authenticate({\n accountID: storageData.accountID,\n accountSecret: storageData.accountSecret,\n });\n\n await this.authSecretStorage.set({\n accountID: storageData.accountID,\n accountSecret: storageData.accountSecret,\n secretSeed: storageData.secretSeed\n ? new Uint8Array(storageData.secretSeed)\n : undefined,\n provider: \"demo\",\n });\n };\n\n signUp = async (username: string) => {\n const existingUsers = await this.getExistingUsers();\n if (existingUsers.includes(username)) {\n throw new Error(\"User already registered\");\n }\n\n const credentials = await this.authSecretStorage.get();\n\n if (!credentials) {\n throw new Error(\"No credentials found\");\n }\n\n const currentAccount = await Account.getMe().$jazz.ensureLoaded({\n resolve: {\n profile: true,\n },\n });\n\n currentAccount.profile.$jazz.set(\"name\", username);\n\n await this.authSecretStorage.set({\n accountID: credentials.accountID,\n accountSecret: credentials.accountSecret,\n secretSeed: credentials.secretSeed\n ? new Uint8Array(credentials.secretSeed)\n : undefined,\n provider: \"demo\",\n });\n\n await this.addToExistingUsers(username, {\n accountID: credentials.accountID,\n accountSecret: credentials.accountSecret,\n secretSeed: credentials.secretSeed\n ? Array.from(credentials.secretSeed)\n : undefined,\n });\n };\n\n private async addToExistingUsers(username: string, data: StorageData) {\n const existingUsers = await this.getExisitingUsersWithData();\n\n if (existingUsers[username]) {\n return;\n }\n\n existingUsers[username] = data;\n\n const kvStore = KvStoreContext.getInstance().getStorage();\n await kvStore.set(\"demo-auth-users\", JSON.stringify(existingUsers));\n }\n\n private async getExisitingUsersWithData() {\n const kvStore = KvStoreContext.getInstance().getStorage();\n await migrateExistingUsers(kvStore);\n\n const existingUsers = await kvStore.get(\"demo-auth-users\");\n return existingUsers ? JSON.parse(existingUsers) : {};\n }\n\n getExistingUsers = async () => {\n return Object.keys(await this.getExisitingUsersWithData());\n };\n}\n\nexport function encodeUsername(username: string) {\n return btoa(username)\n .replace(/=/g, \"-\")\n .replace(/\\+/g, \"_\")\n .replace(/\\//g, \".\");\n}\n\nasync function getStorageVersion(kvStore: KvStore) {\n try {\n const version = await kvStore.get(\"demo-auth-storage-version\");\n return version ? parseInt(version) : 1;\n } catch (error) {\n return 1;\n }\n}\n\nasync function setStorageVersion(kvStore: KvStore, version: number) {\n await kvStore.set(\"demo-auth-storage-version\", version.toString());\n}\n\nasync function getExistingUsersList(kvStore: KvStore) {\n const existingUsers = await kvStore.get(\"demo-auth-existing-users\");\n return existingUsers ? existingUsers.split(\",\") : [];\n}\n\n/**\n * Migrates existing users keys to work with any storage.\n */\nasync function migrateExistingUsers(kvStore: KvStore) {\n if ((await getStorageVersion(kvStore)) < 2) {\n const existingUsers = await getExistingUsersList(kvStore);\n\n for (const username of existingUsers) {\n const legacyKey = `demo-auth-existing-users-${username}`;\n const storageData = await kvStore.get(legacyKey);\n if (storageData) {\n await kvStore.set(\n `demo-auth-existing-users-${encodeUsername(username)}`,\n storageData,\n );\n await kvStore.delete(legacyKey);\n }\n }\n\n await setStorageVersion(kvStore, 2);\n }\n\n if ((await getStorageVersion(kvStore)) < 3) {\n const existingUsersList = await getExistingUsersList(kvStore);\n\n const existingUsers: Record<string, StorageData> = {};\n const keysToDelete: string[] = [\"demo-auth-existing-users\"];\n\n for (const username of existingUsersList) {\n const key = `demo-auth-existing-users-${encodeUsername(username)}`;\n const storageData = await kvStore.get(key);\n if (storageData) {\n existingUsers[username] = JSON.parse(storageData);\n keysToDelete.push(key);\n }\n }\n\n await kvStore.set(\"demo-auth-users\", JSON.stringify(existingUsers));\n\n for (const key of keysToDelete) {\n await kvStore.delete(key);\n }\n\n await setStorageVersion(kvStore, 3);\n }\n}\n","import * as bip39 from \"@scure/bip39\";\nimport { entropyToMnemonic } from \"@scure/bip39\";\nimport { CryptoProvider, cojsonInternals } from \"cojson\";\nimport type { ID } from \"../internal.js\";\nimport { Account } from \"../internal.js\";\nimport type {\n AuthenticateAccountFunction,\n RegisterAccountFunction,\n} from \"../types.js\";\nimport { AuthSecretStorage } from \"./AuthSecretStorage.js\";\n\n/**\n * `PassphraseAuth` provides a `JazzAuth` object for passphrase authentication.\n *\n * ```ts\n * import { PassphraseAuth } from \"jazz-tools\";\n *\n * const auth = new PassphraseAuth(crypto, jazzContext.authenticate, new AuthSecretStorage(), wordlist);\n * ```\n *\n * @category Auth Providers\n */\nexport class PassphraseAuth {\n passphrase: string = \"\";\n\n constructor(\n private crypto: CryptoProvider,\n private authenticate: AuthenticateAccountFunction,\n private register: RegisterAccountFunction,\n private authSecretStorage: AuthSecretStorage,\n public wordlist: string[],\n ) {}\n\n logIn = async (passphrase: string) => {\n const { crypto, authenticate } = this;\n\n let secretSeed;\n\n try {\n secretSeed = bip39.mnemonicToEntropy(passphrase, this.wordlist);\n } catch (e) {\n throw new Error(\"Invalid passphrase\");\n }\n\n const accountSecret = crypto.agentSecretFromSecretSeed(secretSeed);\n\n const accountID = cojsonInternals.idforHeader(\n cojsonInternals.accountHeaderForInitialAgentSecret(accountSecret, crypto),\n crypto,\n ) as ID<Account>;\n\n await authenticate({\n accountID,\n accountSecret,\n });\n\n await this.authSecretStorage.set({\n accountID,\n secretSeed,\n accountSecret,\n provider: \"passphrase\",\n });\n\n this.passphrase = passphrase;\n this.notify();\n };\n\n signUp = async (name?: string) => {\n const credentials = await this.authSecretStorage.get();\n\n if (!credentials || !credentials.secretSeed) {\n throw new Error(\"No credentials found\");\n }\n\n const passphrase = entropyToMnemonic(credentials.secretSeed, this.wordlist);\n\n await this.authSecretStorage.set({\n accountID: credentials.accountID,\n secretSeed: credentials.secretSeed,\n accountSecret: credentials.accountSecret,\n provider: \"passphrase\",\n });\n\n if (name?.trim()) {\n const currentAccount = await Account.getMe().$jazz.ensureLoaded({\n resolve: {\n profile: true,\n },\n });\n\n currentAccount.profile.$jazz.set(\"name\", name);\n }\n\n return passphrase;\n };\n\n registerNewAccount = async (passphrase: string, name: string) => {\n const secretSeed = bip39.mnemonicToEntropy(passphrase, this.wordlist);\n const accountSecret = this.crypto.agentSecretFromSecretSeed(secretSeed);\n const accountID = await this.register(accountSecret, { name });\n\n await this.authSecretStorage.set({\n accountID,\n secretSeed,\n accountSecret,\n provider: \"passphrase\",\n });\n\n return accountID;\n };\n\n getCurrentAccountPassphrase = async () => {\n const credentials = await this.authSecretStorage.get();\n\n if (!credentials || !credentials.secretSeed) {\n throw new Error(\"No credentials found\");\n }\n\n return entropyToMnemonic(credentials.secretSeed, this.wordlist);\n };\n\n generateRandomPassphrase = () => {\n return entropyToMnemonic(this.crypto.newRandomSecretSeed(), this.wordlist);\n };\n\n loadCurrentAccountPassphrase = async () => {\n const passphrase = await this.getCurrentAccountPassphrase();\n this.passphrase = passphrase;\n this.notify();\n };\n\n listeners = new Set<() => void>();\n subscribe = (callback: () => void) => {\n this.listeners.add(callback);\n\n return () => {\n this.listeners.delete(callback);\n };\n };\n\n notify() {\n for (const listener of this.listeners) {\n listener();\n }\n }\n}\n","import { type InviteSecret, cojsonInternals } from \"cojson\";\nimport { Account } from \"../coValues/account.js\";\nimport type {\n CoValue,\n CoValueClass,\n CoValueClassOrSchema,\n ID,\n} from \"../internal.js\";\n\n/** @category Invite Links */\nexport function createInviteLink<C extends CoValue>(\n value: C,\n role: \"reader\" | \"writer\" | \"admin\" | \"writeOnly\",\n baseURL: string,\n valueHint?: string,\n): string {\n const coValueCore = value.$jazz.raw.core;\n let currentCoValue = coValueCore;\n\n while (currentCoValue.verified.header.ruleset.type === \"ownedByGroup\") {\n currentCoValue = currentCoValue.getGroup().core;\n }\n\n const { ruleset, meta } = currentCoValue.verified.header;\n\n if (ruleset.type !== \"group\" || meta?.type === \"account\") {\n throw new Error(\"Can't create invite link for object without group\");\n }\n\n const group = cojsonInternals.expectGroup(currentCoValue.getCurrentContent());\n const inviteSecret = group.createInvite(role);\n\n return `${baseURL}#/invite/${valueHint ? valueHint + \"/\" : \"\"}${\n value.$jazz.id\n }/${inviteSecret}`;\n}\n\n/** @category Invite Links */\nexport function parseInviteLink(inviteURL: string):\n | {\n valueID: string;\n valueHint?: string;\n inviteSecret: InviteSecret;\n }\n | undefined {\n const url = new URL(inviteURL);\n const parts = url.hash.split(\"/\");\n\n let valueHint: string | undefined;\n let valueID: string | undefined;\n let inviteSecret: InviteSecret | undefined;\n\n if (parts[0] === \"#\" && parts[1] === \"invite\") {\n if (parts.length === 5) {\n valueHint = parts[2];\n valueID = parts[3];\n inviteSecret = parts[4] as InviteSecret;\n } else if (parts.length === 4) {\n valueID = parts[2];\n inviteSecret = parts[3] as InviteSecret;\n }\n\n if (!valueID || !inviteSecret) {\n return undefined;\n }\n return { valueID, inviteSecret, valueHint };\n }\n}\n\n/** @category Invite Links */\nexport function consumeInviteLink<S extends CoValueClassOrSchema>({\n inviteURL,\n as = Account.getMe(),\n forValueHint,\n invitedObjectSchema,\n}: {\n inviteURL: string;\n as?: Account;\n forValueHint?: string;\n invitedObjectSchema: S;\n}): Promise<\n | {\n valueID: string;\n valueHint?: string;\n inviteSecret: InviteSecret;\n }\n | undefined\n> {\n return new Promise((resolve, reject) => {\n const result = parseInviteLink(inviteURL);\n\n if (result && result.valueHint === forValueHint) {\n as.acceptInvite(result.valueID, result.inviteSecret, invitedObjectSchema)\n .then(() => {\n resolve(result);\n })\n .catch(reject);\n } else {\n resolve(undefined);\n }\n });\n}\n","import {\n CoValueCore,\n CojsonInternalTypes,\n CryptoProvider,\n RawAccount,\n RawCoMap,\n cojsonInternals,\n} from \"cojson\";\nimport z from \"zod/v4\";\nimport {\n AnyZodOrCoValueSchema,\n CoMap,\n CoMapSchema,\n CoMapSchemaInit,\n CoValueClass,\n CoreCoMapSchema,\n Group,\n Loaded,\n ResolveQuery,\n ResolveQueryStrict,\n Simplify,\n coMapDefiner,\n coValueClassFromCoValueClassOrSchema,\n exportCoValue,\n importContentPieces,\n loadCoValue,\n} from \"../internal.js\";\nimport { isCoValueId } from \"../lib/id.js\";\nimport { Account } from \"./account.js\";\n\ntype MessageShape = Record<string, AnyZodOrCoValueSchema>;\n\ntype RequestSchemaDefinition<\n S extends MessageShape,\n R extends ResolveQuery<CoMapSchema<S>> = true,\n> =\n | S\n | {\n schema: S;\n resolve?: R;\n };\n\n/**\n * Configuration options for defining HTTP request/response schemas in Jazz.\n *\n * This interface defines the structure for creating typed HTTP routes with\n * request and response validation using CoMap schemas.\n *\n * @template RequestShape - The shape of the request message schema (must extend MessageShape)\n * @template RequestResolve - The resolve query type for the request CoMap schema\n * @template ResponseShape - The shape of the response message schema (must extend MessageShape)\n * @template ResponseResolve - The resolve query type for the response CoMap schema\n */\ninterface RequestOptions<\n RequestShape extends MessageShape,\n RequestResolve extends ResolveQuery<CoMapSchema<RequestShape>>,\n ResponseShape extends MessageShape,\n ResponseResolve extends ResolveQuery<CoMapSchema<ResponseShape>>,\n> {\n /**\n * The URL endpoint for the HTTP route.\n * This is used by the client to send requests to the server.\n */\n url: string;\n\n /**\n * The id of the worker Account or Group.\n */\n workerId: string;\n\n /**\n * Schema definition for the request payload.\n * Can be either a direct schema object or an object with schema and optional resolve properties.\n * The schema defines the structure and validation rules for incoming requests.\n */\n request: RequestSchemaDefinition<\n RequestShape,\n ResolveQueryStrict<CoMapSchema<RequestShape>, RequestResolve>\n >;\n\n /**\n * Schema definition for the response payload.\n * Can be either a direct schema object or an object with schema and optional resolve properties.\n * The schema defines the structure and validation rules for outgoing responses.\n */\n response: RequestSchemaDefinition<\n ResponseShape,\n ResolveQueryStrict<CoMapSchema<ResponseShape>, ResponseResolve>\n >;\n}\n\ntype AsNullablePayload<T extends MessageShape> = T extends Record<string, never>\n ? undefined\n : never;\ntype MessageValuePayload<T extends MessageShape> =\n | Simplify<CoMapSchemaInit<T>>\n | AsNullablePayload<T>;\n\nfunction createMessageEnvelope<S extends MessageShape>(\n schema: CoreCoMapSchema,\n value: MessageValuePayload<S>,\n owner: Account,\n sharedWith: Account | Group,\n type: \"request\" | \"response\",\n): Loaded<CoMapSchema<S>> {\n const group = Group.create({ owner });\n\n if (type === \"request\") {\n group.addMember(sharedWith, \"writer\");\n } else {\n group.addMember(sharedWith, \"reader\");\n }\n\n // @ts-expect-error - CoreCoMapSchema doesn't have static methods\n return schema.create(value ?? {}, group);\n}\n\n/**\n * Function that exports the input CoValue in a serializable format and prepares the information\n * required for the other side to safely verify the identity of the sender.\n */\nasync function serializeMessagePayload({\n type,\n schema,\n resolve,\n value,\n owner,\n target,\n}: {\n // Skipping type validation here to avoid excessive type complexity that affects the typecheck performance\n type: \"request\" | \"response\";\n schema: CoreCoMapSchema;\n resolve: any;\n value: any;\n owner: Account;\n target: Account | Group;\n}) {\n const me = owner ?? Account.getMe();\n const node = me.$jazz.localNode;\n const crypto = node.crypto;\n\n const agent = node.getCurrentAgent();\n const signerID = agent.currentSignerID();\n const signerSecret = agent.currentSignerSecret();\n\n const envelope = createMessageEnvelope(schema, value, me, target, type);\n\n const contentPieces =\n (await exportCoValue(schema, envelope.$jazz.id, {\n resolve,\n loadAs: me,\n bestEffortResolution: true,\n })) ?? [];\n\n const createdAt = Date.now();\n\n const signPayload = crypto.secureHash({\n contentPieces,\n id: envelope.$jazz.id,\n createdAt,\n signerID,\n });\n\n const authToken = crypto.sign(signerSecret, signPayload);\n\n return {\n contentPieces,\n id: envelope.$jazz.id,\n createdAt,\n authToken,\n signerID,\n };\n}\n\nconst requestSchema = z.object({\n contentPieces: z.array(z.json()),\n id: z.custom<`co_z${string}`>(isCoValueId),\n createdAt: z.number(),\n authToken: z.custom<`signature_z${string}`>(\n (value) => typeof value === \"string\" && value.startsWith(\"signature_z\"),\n ),\n signerID: z.custom<`signer_z${string}`>(\n (value) => typeof value === \"string\" && value.startsWith(\"signer_z\"),\n ),\n});\n\n/**\n * Function that parses the message payload, verifies the identity of the sender and loads the data.\n *\n * @returns The data from the message.\n */\nasync function handleMessagePayload({\n type,\n schema,\n resolve,\n request,\n loadAs,\n}: {\n type: \"request\" | \"response\";\n // Skipping type validation here to avoid excessive type complexity that affects the typecheck performance\n schema: CoreCoMapSchema;\n resolve: any;\n request: unknown;\n loadAs: Account;\n}) {\n const node = loadAs.$jazz.localNode;\n const crypto = node.crypto;\n\n const requestParsed = requestSchema.safeParse(request);\n\n if (!requestParsed.success) {\n throw new JazzRequestError(\n \"Request payload is not valid\",\n 400,\n requestParsed.error,\n );\n }\n\n const requestData = requestParsed.data;\n\n if (type === \"request\") {\n const core = await node.loadCoValueCore(requestData.id, undefined, true);\n\n // Check if the message has already been handled to prevent replay attacks\n if (core.isAvailable()) {\n const content = core.getCurrentContent() as RawCoMap;\n\n if (content.get(\"$handled\") === loadAs.$jazz.id) {\n throw new JazzRequestError(\"Request payload is already handled\", 400);\n }\n }\n\n // Check if the message is expired as extra protection\n if (requestData.createdAt + 1000 * 60 < Date.now()) {\n throw new JazzRequestError(\"Authentication token is expired\", 401);\n }\n }\n\n // Verify the signature of the message to prevent tampering\n const signPayload = crypto.secureHash({\n contentPieces: requestData.contentPieces,\n id: requestData.id,\n createdAt: requestData.createdAt,\n signerID: requestData.signerID,\n });\n\n if (\n !safeVerifySignature(\n crypto,\n signPayload,\n requestData.signerID,\n requestData.authToken,\n )\n ) {\n throw new JazzRequestError(\"Invalid signature\", 401);\n }\n\n let contentPieces =\n requestData.contentPieces as CojsonInternalTypes.NewContentMessage[];\n\n if (type === \"request\") {\n const coValueContent = contentPieces.find(\n (piece) => piece.id === requestData.id,\n );\n\n if (coValueContent && coValueContent.header) {\n const validValues = cojsonInternals.getDependedOnCoValues(\n coValueContent.header,\n coValueContent,\n );\n validValues.add(requestData.id);\n contentPieces = contentPieces.filter((piece) =>\n validValues.has(piece.id),\n );\n } else {\n contentPieces = [];\n }\n }\n\n importContentPieces(contentPieces, loadAs);\n\n const coValue = await node.loadCoValueCore(requestData.id);\n const accountId = getCoValueCreatorAccountId(coValue);\n\n const madeBy = await Account.load(accountId, {\n loadAs,\n });\n\n if (!madeBy) {\n throw new JazzRequestError(\"Creator account not found\", 400);\n }\n\n const coSchema = coValueClassFromCoValueClassOrSchema(\n schema,\n ) as CoValueClass<CoMap>;\n const value = await loadCoValue<CoMap, true>(coSchema, requestData.id, {\n resolve,\n loadAs,\n });\n\n if (!value) {\n throw new JazzRequestError(\"Value not found\", 400);\n }\n\n if (type === \"request\") {\n value.$jazz.raw.set(\"$handled\", loadAs.$jazz.id);\n }\n\n return {\n value: value as unknown,\n madeBy,\n };\n}\n\nfunction parseSchemaAndResolve<\n S extends MessageShape,\n R extends ResolveQuery<CoMapSchema<S>>,\n>(options: RequestSchemaDefinition<S, R>) {\n if (\"schema\" in options) {\n return {\n // Using a type cast to reduce the type complexity\n schema: coMapDefiner(options.schema) as CoreCoMapSchema,\n resolve: options.resolve as any,\n };\n }\n\n return {\n schema: coMapDefiner(options) as CoreCoMapSchema,\n resolve: true as any,\n };\n}\n\nexport class HttpRoute<\n RequestShape extends MessageShape = z.core.$ZodLooseShape,\n RequestResolve extends ResolveQuery<CoMapSchema<RequestShape>> = any,\n ResponseShape extends MessageShape = z.core.$ZodLooseShape,\n ResponseResolve extends ResolveQuery<CoMapSchema<ResponseShape>> = any,\n> {\n private requestDefinition: {\n schema: CoreCoMapSchema;\n resolve: any;\n };\n private responseDefinition: {\n schema: CoreCoMapSchema;\n resolve: any;\n };\n private url: string;\n private workerId: string;\n\n constructor(\n params: RequestOptions<\n RequestShape,\n RequestResolve,\n ResponseShape,\n ResponseResolve\n >,\n ) {\n this.requestDefinition = parseSchemaAndResolve(params.request);\n this.responseDefinition = parseSchemaAndResolve(params.response);\n this.url = params.url;\n this.workerId = params.workerId;\n\n if (params.workerId === undefined) {\n throw new TypeError(\"Worker ID is required\");\n }\n }\n\n async send(\n values: MessageValuePayload<RequestShape>,\n options?: { owner?: Account },\n ): Promise<Loaded<CoMapSchema<ResponseShape>, ResponseResolve>> {\n const as = options?.owner ?? Account.getMe();\n\n const target = await loadWorkerAccountOrGroup(this.workerId, as);\n if (!target) {\n throw new JazzRequestError(\"Worker account not found\", 400);\n }\n\n const response = await fetch(this.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(\n await serializeMessagePayload({\n type: \"request\",\n schema: this.requestDefinition.schema,\n resolve: true, // export only the envelope\n value: values,\n owner: as,\n target,\n }),\n ),\n });\n\n if (!response.ok) {\n if (response.headers.has(\"X-Jazz-Request-Error\")) {\n const error = await response.json();\n throw new JazzRequestError(error.message, error.code, error.details);\n }\n\n throw new JazzRequestError(\"Request failed\", response.status);\n }\n\n const responseBody = await response.json();\n\n const responseParsed = z\n .object({\n type: z.literal(\"success\"),\n payload: z.any(),\n })\n .safeParse(responseBody);\n\n if (!responseParsed.success) {\n throw new JazzRequestError(\n \"Response payload is not valid\",\n 400,\n responseParsed.error,\n );\n }\n\n const data = await handleMessagePayload({\n type: \"response\",\n schema: this.responseDefinition.schema,\n resolve: this.responseDefinition.resolve,\n request: responseParsed.data.payload,\n loadAs: as,\n });\n\n return data.value as Loaded<CoMapSchema<ResponseShape>, ResponseResolve>;\n }\n\n handle = async (\n request: Request,\n as: Account,\n callback: (\n value: Loaded<CoMapSchema<RequestShape>, RequestResolve>,\n madeBy: Account,\n ) =>\n | Promise<MessageValuePayload<ResponseShape>>\n | MessageValuePayload<ResponseShape>,\n ): Promise<Response> => {\n try {\n const response = await this.executeHandleRequest(request, as, callback);\n return response;\n } catch (error) {\n // Serialize the error to make it possible to handle it on the client side\n if (isJazzRequestError(error)) {\n return new Response(JSON.stringify(error.toJSON()), {\n status: error.code,\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-Jazz-Request-Error\": \"true\",\n },\n });\n }\n\n throw error;\n }\n };\n\n executeHandleRequest = async (\n request: Request,\n as: Account,\n callback: (\n value: Loaded<CoMapSchema<RequestShape>, RequestResolve>,\n madeBy: Account,\n ) =>\n | Promise<MessageValuePayload<ResponseShape>>\n | MessageValuePayload<ResponseShape>,\n ): Promise<Response> => {\n const node = as.$jazz.localNode;\n const body = await request.json();\n const data = await handleMessagePayload({\n type: \"request\",\n schema: this.requestDefinition.schema,\n resolve: this.requestDefinition.resolve,\n request: body,\n loadAs: as,\n });\n\n const tracking = node.syncManager.trackDirtyCoValues();\n\n const responseValue = await callback(\n data.value as Loaded<CoMapSchema<RequestShape>, RequestResolve>,\n data.madeBy,\n );\n\n const responsePayload = await serializeMessagePayload({\n type: \"response\",\n schema: this.responseDefinition.schema,\n resolve: this.responseDefinition.resolve,\n value: responseValue,\n owner: as,\n target: data.madeBy,\n });\n\n const responseBody = JSON.stringify({\n type: \"success\",\n payload: responsePayload,\n });\n\n // TODO: Detect the defer support from the environment\n await Promise.all(\n Array.from(tracking.done(), (id) => node.syncManager.waitForSync(id)),\n );\n\n return new Response(responseBody, {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n };\n\n get requestSchema(): CoMapSchema<RequestShape> {\n return this.requestDefinition.schema as CoMapSchema<RequestShape>;\n }\n\n get responseSchema() {\n return this.responseDefinition.schema as CoMapSchema<ResponseShape>;\n }\n}\n\n/**\n * Define a request route.\n *\n * @param params - The parameters for the request route.\n * @returns The request route.\n *\n * @see {@link https://jazz.tools/docs/react/server-side/http-requests}\n */\nexport function experimental_defineRequest<\n RequestShape extends MessageShape,\n RequestResolve extends ResolveQuery<CoMapSchema<RequestShape>>,\n ResponseShape extends MessageShape,\n ResponseResolve extends ResolveQuery<CoMapSchema<ResponseShape>>,\n>(\n params: RequestOptions<\n RequestShape,\n RequestResolve,\n ResponseShape,\n ResponseResolve\n >,\n) {\n return new HttpRoute(params);\n}\n\nfunction getCoValueCreatorAccountId(coValue: CoValueCore) {\n if (!coValue.isAvailable()) {\n throw new Error(\"Unable to load the request payload\");\n }\n\n const creatorSessionId = coValue.getValidSortedTransactions().at(0)\n ?.txID.sessionID;\n\n if (!creatorSessionId) {\n throw new JazzRequestError(\n \"Request payload is not valid, creator session ID not found\",\n 400,\n );\n }\n\n const accountId =\n cojsonInternals.accountOrAgentIDfromSessionID(creatorSessionId);\n\n if (!isCoValueId(accountId)) {\n throw new JazzRequestError(\n \"Request payload is not valid, the creator is not a valid account\",\n 400,\n );\n }\n\n return accountId;\n}\n\nexport class JazzRequestError {\n public readonly isJazzRequestError = true;\n\n constructor(\n public readonly message: string,\n public readonly code: number,\n public readonly details?: unknown,\n ) {}\n\n toJSON() {\n return { message: this.message, code: this.code, details: this.details };\n }\n}\n\nexport function isJazzRequestError(error: unknown): error is JazzRequestError {\n return (\n error instanceof JazzRequestError ||\n (typeof error === \"object\" &&\n error !== null &&\n \"isJazzRequestError\" in error &&\n Boolean(error.isJazzRequestError))\n );\n}\n\nfunction safeVerifySignature(\n crypto: CryptoProvider,\n signPayload: `hash_z${string}`,\n signerID: `signer_z${string}`,\n authToken: `signature_z${string}`,\n) {\n try {\n return crypto.verify(authToken, signPayload, signerID);\n } catch (error) {\n return false;\n }\n}\n\nasync function loadWorkerAccountOrGroup(id: string, loadAs: Account) {\n const node = loadAs.$jazz.localNode;\n const coValue = await node.loadCoValueCore(id as `co_z${string}`);\n\n if (!coValue.isAvailable()) {\n return null;\n }\n\n const content = coValue.getCurrentContent();\n\n if (content instanceof RawAccount) {\n return Account.load(content.id, {\n loadAs,\n });\n }\n\n return Group.load(content.id, {\n loadAs,\n });\n}\n","export * from \"./exports.js\";\n\nexport {\n cojsonInternals,\n logger,\n LogLevel,\n} from \"cojson\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE,WAAAA;AAAA,EAEA,qBAAAC;AAAA,OAEK;;;ACHA,SAAS,iBACd,aACA;AACA,MAAI,CAAC,YAAY,MAAM;AACrB,WAAO;AAAA,EACT;AAEA,MAAI,YAAY,KAAK,UAAU;AAC7B,WAAO,YAAY,KAAK;AAAA,EAC1B;AAEA,MAAI,YAAY,KAAK,WAAW;AAC9B,QAAI,YAAY,KAAK,UAAU;AAC7B,aAAO,GAAG,YAAY,KAAK,SAAS,IAAI,YAAY,KAAK,QAAQ;AAAA,IACnE;AAEA,WAAO,YAAY,KAAK;AAAA,EAC1B;AAEA,MAAI,YAAY,KAAK,UAAU;AAC7B,WAAO,YAAY,KAAK;AAAA,EAC1B;AAEA,MAAI,YAAY,KAAK,qBAAqB,cAAc;AACtD,UAAM,gBACJ,YAAY,KAAK,oBAAoB,aAAa,MAAM,GAAG,EAAE,CAAC;AAEhE,QAAI,eAAe;AACjB,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO,YAAY,KAAK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A;AALlB,SAAgB,qBAAqB;AAAA,EAMlC;AAAA,EAEH,SAAS;AACP,WAAO,EAAE,SAAS,KAAK,SAAS,MAAM,KAAK,MAAM,SAAS,KAAK,QAAQ;AAAA,EACzE;AACF;AAEO,SAAS,mBAAmB,OAA2C;AAC5E,SACE,iBAAiB,oBAChB,OAAO,UAAU,YAChB,UAAU,QACV,wBAAwB,SACxB,QAAQ,MAAM,kBAAkB;AAEtC;AAEA,SAAS,oBACP,QACA,aACA,UACA,WACA;AACA,MAAI;AACF,WAAO,OAAO,OAAO,WAAW,aAAa,QAAQ;AAAA,EACvD,SAAS,OAAO;AACd,WAAO;AAAA,EACT;AACF;AAEA,eAAe,yBAAyB,IAAY,QAAiB;AACnE,QAAM,OAAO,OAAO,MAAM;AAC1B,QAAM,UAAU,MAAM,KAAK,gBAAgB,EAAqB;AAEhE,MAAI,CAAC,QAAQ,YAAY,GAAG;AAC1B,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,QAAQ,kBAAkB;AAE1C,MAAI,mBAAmB,YAAY;AACjC,WAAO,QAAQ,KAAK,QAAQ,IAAI;AAAA,MAC9B;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO,MAAM,KAAK,QAAQ,IAAI;AAAA,IAC5B;AAAA,EACF,CAAC;AACH;;;ACtnBA;AAAA,EACE,mBAAAC;AAAA,EACA;AAAA,EACA;AAAA,OACK;","names":["Account","AuthSecretStorage","Account","AuthSecretStorage","cojsonInternals","cojsonInternals","cojsonInternals","cojsonInternals","cojsonInternals"]}
|
package/dist/react/ssr.d.ts
CHANGED
package/dist/react/ssr.d.ts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"ssr.d.ts","sourceRoot":"","sources":["../../src/react/ssr.ts"],"names":[],"mappings":"
|
1
|
+
{"version":3,"file":"ssr.d.ts","sourceRoot":"","sources":["../../src/react/ssr.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC"}
|
package/dist/react/ssr.js
CHANGED
package/dist/react/ssr.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../src/
|
1
|
+
{"version":3,"sources":["../../src/tools/ssr/ssr.ts"],"sourcesContent":["import { WebSocketPeerWithReconnection } from \"cojson-transport-ws\";\nimport { PureJSCrypto } from \"cojson/dist/crypto/PureJSCrypto\";\nimport { createAnonymousJazzContext } from \"jazz-tools\";\n\nexport function createSSRJazzAgent(opts: { peer: string }) {\n const ssrNode = createAnonymousJazzContext({\n crypto: new PureJSCrypto(),\n peersToLoadFrom: [],\n });\n\n const wsPeer = new WebSocketPeerWithReconnection({\n peer: opts.peer,\n reconnectionTimeout: 100,\n addPeer: (peer) => {\n ssrNode.agent.node.syncManager.addPeer(peer);\n },\n removePeer: () => {},\n });\n\n wsPeer.enable();\n\n return ssrNode.agent;\n}\n"],"mappings":";;;AAAA,SAAS,qCAAqC;AAC9C,SAAS,oBAAoB;AAC7B,SAAS,kCAAkC;AAEpC,SAAS,mBAAmB,MAAwB;AACzD,QAAM,UAAU,2BAA2B;AAAA,IACzC,QAAQ,IAAI,aAAa;AAAA,IACzB,iBAAiB,CAAC;AAAA,EACpB,CAAC;AAED,QAAM,SAAS,IAAI,8BAA8B;AAAA,IAC/C,MAAM,KAAK;AAAA,IACX,qBAAqB;AAAA,IACrB,SAAS,CAAC,SAAS;AACjB,cAAQ,MAAM,KAAK,YAAY,QAAQ,IAAI;AAAA,IAC7C;AAAA,IACA,YAAY,MAAM;AAAA,IAAC;AAAA,EACrB,CAAC;AAED,SAAO,OAAO;AAEd,SAAO,QAAQ;AACjB;","names":[]}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../../src/react-core/hooks.ts"],"names":[],"mappings":"AAQA,OAAO,EACL,OAAO,EACP,YAAY,EACZ,kBAAkB,EAClB,gBAAgB,EAChB,OAAO,EACP,oBAAoB,EAIpB,kBAAkB,EAClB,eAAe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E,eAAe,EAAE,CAAC,EAAE,eAAe,KAAK,OAAO,CAAC;IACjE;;;;;;;;;;;;;;OAcG;IACH,eAAe,CAAC,EAAE,gBAAgB,CAAC;CACpC,GACA,eAAe,CAsBjB;AAED,wBAAgB,2BAA2B,CACzC,CAAC,SAAS,OAAO,EACjB,CAAC,SAAS,OAAO,GAAG,SAAS,EAC7B,YAAY,EAAE,MAAM,GAAG,SAAS,aAad,CAAC,qDAuBpB;AAED;;;;;;;;GAQG;AACH,wBAAgB,uBAAuB,YAetC"}
|
package/dist/react-core/index.js
CHANGED
@@ -270,14 +270,14 @@ function experimental_useInboxSender(inboxOwnerID) {
|
|
270
270
|
inboxRef.current = inbox2;
|
271
271
|
}
|
272
272
|
let inbox = await inboxRef.current;
|
273
|
-
if (inbox.owner.id !== inboxOwnerID) {
|
273
|
+
if (inbox.owner.id !== inboxOwnerID || inbox.currentAccount !== me) {
|
274
274
|
const req = InboxSender.load(inboxOwnerID, me);
|
275
275
|
inboxRef.current = req;
|
276
276
|
inbox = await req;
|
277
277
|
}
|
278
278
|
return inbox.sendMessage(message);
|
279
279
|
},
|
280
|
-
[inboxOwnerID]
|
280
|
+
[inboxOwnerID, me.$jazz.id]
|
281
281
|
);
|
282
282
|
return sendMessage;
|
283
283
|
}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../src/react-core/hooks.ts","../../src/react-core/utils.ts","../../src/react-core/auth/DemoAuth.tsx","../../src/react-core/auth/PassphraseAuth.tsx"],"sourcesContent":["import { useSyncExternalStoreWithSelector } from \"use-sync-external-store/shim/with-selector\";\nimport React, {\n useCallback,\n useContext,\n useRef,\n useSyncExternalStore,\n} from \"react\";\n\nimport {\n Account,\n AccountClass,\n AnonymousJazzAgent,\n AnyAccountSchema,\n CoValue,\n CoValueClassOrSchema,\n Group,\n InboxSender,\n InstanceOfSchema,\n JazzContextManager,\n JazzContextType,\n Loaded,\n ResolveQuery,\n ResolveQueryStrict,\n SubscriptionScope,\n coValueClassFromCoValueClassOrSchema,\n type BranchDefinition,\n} from \"jazz-tools\";\nimport { JazzContext, JazzContextManagerContext } from \"./provider.js\";\nimport { getCurrentAccountFromContextManager } from \"./utils.js\";\n\nexport function useJazzContext<Acc extends Account>() {\n const value = useContext(JazzContext) as JazzContextType<Acc>;\n\n if (!value) {\n throw new Error(\n \"You need to set up a JazzProvider on top of your app to use this hook.\",\n );\n }\n\n return value;\n}\n\nexport function useJazzContextManager<Acc extends Account>() {\n const value = useContext(JazzContextManagerContext) as JazzContextManager<\n Acc,\n {}\n >;\n\n if (!value) {\n throw new Error(\n \"You need to set up a JazzProvider on top of your app to use this hook.\",\n );\n }\n\n return value;\n}\n\nexport function useAuthSecretStorage() {\n const value = useContext(JazzContextManagerContext);\n\n if (!value) {\n throw new Error(\n \"You need to set up a JazzProvider on top of your app to use this useAuthSecretStorage.\",\n );\n }\n\n return value.getAuthSecretStorage();\n}\n\nexport function useIsAuthenticated() {\n const authSecretStorage = useAuthSecretStorage();\n\n return useSyncExternalStore(\n useCallback(\n (callback) => {\n return authSecretStorage.onUpdate(callback);\n },\n [authSecretStorage],\n ),\n () => authSecretStorage.isAuthenticated,\n () => authSecretStorage.isAuthenticated,\n );\n}\n\nfunction useCoValueSubscription<\n S extends CoValueClassOrSchema,\n const R extends ResolveQuery<S>,\n>(\n Schema: S,\n id: string | undefined | null,\n options?: {\n resolve?: ResolveQueryStrict<S, R>;\n unstable_branch?: BranchDefinition;\n },\n) {\n const contextManager = useJazzContextManager();\n\n const createSubscription = () => {\n if (!id) {\n return {\n subscription: null,\n contextManager,\n id,\n Schema,\n };\n }\n\n if (options?.unstable_branch?.owner === null) {\n return {\n subscription: null,\n contextManager,\n id,\n Schema,\n };\n }\n\n const node = contextManager.getCurrentValue()!.node;\n const subscription = new SubscriptionScope<any>(\n node,\n options?.resolve ?? true,\n id,\n {\n ref: coValueClassFromCoValueClassOrSchema(Schema),\n optional: true,\n },\n false,\n false,\n options?.unstable_branch,\n );\n\n return {\n subscription,\n contextManager,\n id,\n Schema,\n branchName: options?.unstable_branch?.name,\n branchOwnerId: options?.unstable_branch?.owner?.$jazz.id,\n };\n };\n\n const [subscription, setSubscription] = React.useState(createSubscription);\n\n const branchName = options?.unstable_branch?.name;\n const branchOwnerId = options?.unstable_branch?.owner?.$jazz.id;\n\n React.useLayoutEffect(() => {\n if (\n subscription.contextManager !== contextManager ||\n subscription.id !== id ||\n subscription.Schema !== Schema ||\n subscription.branchName !== branchName ||\n subscription.branchOwnerId !== branchOwnerId\n ) {\n subscription.subscription?.destroy();\n setSubscription(createSubscription());\n }\n\n return contextManager.subscribe(() => {\n subscription.subscription?.destroy();\n setSubscription(createSubscription());\n });\n }, [Schema, id, contextManager, branchName, branchOwnerId]);\n\n return subscription.subscription;\n}\n\n/**\n * React hook for subscribing to CoValues and handling loading states.\n *\n * This hook provides a convenient way to subscribe to CoValues and automatically\n * handles the subscription lifecycle (subscribe on mount, unsubscribe on unmount).\n * It also supports deep loading of nested CoValues through resolve queries.\n *\n * @returns The loaded CoValue, or `undefined` if loading, or `null` if not found/not accessible\n *\n * @example\n * ```tsx\n * // Deep loading with resolve queries\n * const Project = co.map({\n * name: z.string(),\n * tasks: co.list(Task),\n * owner: TeamMember,\n * });\n *\n * function ProjectView({ projectId }: { projectId: string }) {\n * const project = useCoState(Project, projectId, {\n * resolve: {\n * tasks: { $each: true },\n * owner: true,\n * },\n * });\n *\n * if (!project) {\n * return project === null\n * ? \"Project not found or not accessible\"\n * : \"Loading project...\";\n * }\n *\n * return (\n * <div>\n * <h1>{project.name}</h1>\n * <p>Owner: {project.owner.name}</p>\n * <ul>\n * {project.tasks.map((task) => (\n * <li key={task.id}>{task.title}</li>\n * ))}\n * </ul>\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Using with optional references and error handling\n * const Task = co.map({\n * title: z.string(),\n * assignee: co.optional(TeamMember),\n * subtasks: co.list(Task),\n * });\n *\n * function TaskDetail({ taskId }: { taskId: string }) {\n * const task = useCoState(Task, taskId, {\n * resolve: {\n * assignee: true,\n * subtasks: { $each: { $onError: null } },\n * },\n * });\n *\n * if (!task) {\n * return task === null\n * ? \"Task not found or not accessible\"\n * : \"Loading task...\";\n * }\n *\n * return (\n * <div>\n * <h2>{task.title}</h2>\n * {task.assignee && <p>Assigned to: {task.assignee.name}</p>}\n * <ul>\n * {task.subtasks.map((subtask, index) => (\n * subtask ? <li key={subtask.id}>{subtask.title}</li> : <li key={index}>Inaccessible subtask</li>\n * ))}\n * </ul>\n * </div>\n * );\n * }\n * ```\n *\n * For more examples, see the [subscription and deep loading](https://jazz.tools/docs/react/using-covalues/subscription-and-loading) documentation.\n */\nexport function useCoState<\n S extends CoValueClassOrSchema,\n const R extends ResolveQuery<S> = true,\n>(\n /** The CoValue schema or class constructor */\n Schema: S,\n /** The ID of the CoValue to subscribe to. If `undefined`, returns `null` */\n id: string | undefined,\n /** Optional configuration for the subscription */\n options?: {\n /** Resolve query to specify which nested CoValues to load */\n resolve?: ResolveQueryStrict<S, R>;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n },\n): Loaded<S, R> | undefined | null {\n const subscription = useCoValueSubscription(Schema, id, options);\n\n const value = React.useSyncExternalStore<Loaded<S, R> | undefined | null>(\n React.useCallback(\n (callback) => {\n if (!subscription) {\n return () => {};\n }\n\n return subscription.subscribe(callback);\n },\n [subscription],\n ),\n () => (subscription ? subscription.getCurrentValue() : null),\n () => (subscription ? subscription.getCurrentValue() : null),\n );\n\n return value;\n}\n\n/**\n * React hook for subscribing to CoValues with selective data extraction and custom equality checking.\n *\n * This hook extends `useCoState` by allowing you to select only specific parts of the CoValue data\n * through a selector function, which helps reduce unnecessary re-renders by narrowing down the\n * returned data. Additionally, you can provide a custom equality function to further optimize\n * performance by controlling when the component should re-render based on the selected data.\n *\n * The hook automatically handles the subscription lifecycle and supports deep loading of nested\n * CoValues through resolve queries, just like `useCoState`.\n *\n * @returns The result of the selector function applied to the loaded CoValue data\n *\n * @example\n * ```tsx\n * // Select only specific fields to reduce re-renders\n * const Project = co.map({\n * name: z.string(),\n * description: z.string(),\n * tasks: co.list(Task),\n * lastModified: z.date(),\n * });\n *\n * function ProjectTitle({ projectId }: { projectId: string }) {\n * // Only re-render when the project name changes, not other fields\n * const projectName = useCoStateWithSelector(\n * Project,\n * projectId,\n * {\n * select: (project) => project?.name ?? \"Loading...\",\n * }\n * );\n *\n * return <h1>{projectName}</h1>;\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Use custom equality function for complex data structures\n * const TaskList = co.list(Task);\n *\n * function TaskCount({ listId }: { listId: string }) {\n * const taskStats = useCoStateWithSelector(\n * TaskList,\n * listId,\n * {\n * resolve: { $each: true },\n * select: (tasks) => {\n * if (!tasks) return { total: 0, completed: 0 };\n * return {\n * total: tasks.length,\n * completed: tasks.filter(task => task.completed).length,\n * };\n * },\n * // Custom equality to prevent re-renders when stats haven't changed\n * equalityFn: (a, b) => a.total === b.total && a.completed === b.completed,\n * }\n * );\n *\n * return (\n * <div>\n * {taskStats.completed} of {taskStats.total} tasks completed\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Combine with deep loading and complex selectors\n * const Team = co.map({\n * name: z.string(),\n * members: co.list(TeamMember),\n * projects: co.list(Project),\n * });\n *\n * function TeamSummary({ teamId }: { teamId: string }) {\n * const summary = useCoStateWithSelector(\n * Team,\n * teamId,\n * {\n * resolve: {\n * members: { $each: true },\n * projects: { $each: { tasks: { $each: true } } },\n * },\n * select: (team) => {\n * if (!team) return null;\n *\n * const totalTasks = team.projects.reduce(\n * (sum, project) => sum + project.tasks.length,\n * 0\n * );\n *\n * return {\n * teamName: team.name,\n * memberCount: team.members.length,\n * projectCount: team.projects.length,\n * totalTasks,\n * };\n * },\n * }\n * );\n *\n * if (!summary) return <div>Loading team summary...</div>;\n *\n * return (\n * <div>\n * <h2>{summary.teamName}</h2>\n * <p>{summary.memberCount} members</p>\n * <p>{summary.projectCount} projects</p>\n * <p>{summary.totalTasks} total tasks</p>\n * </div>\n * );\n * }\n * ```\n *\n * For more examples, see the [subscription and deep loading](https://jazz.tools/docs/react/using-covalues/subscription-and-loading) documentation.\n */\nexport function useCoStateWithSelector<\n S extends CoValueClassOrSchema,\n TSelectorReturn,\n const R extends ResolveQuery<S> = true,\n>(\n /** The CoValue schema or class constructor */\n Schema: S,\n /** The ID of the CoValue to subscribe to. If `undefined`, returns the result of selector called with `null` */\n id: string | undefined,\n /** Optional configuration for the subscription */\n options: {\n /** Resolve query to specify which nested CoValues to load */\n resolve?: ResolveQueryStrict<S, R>;\n /** Select which value to return */\n select: (value: Loaded<S, R> | undefined | null) => TSelectorReturn;\n /** Equality function to determine if the selected value has changed, defaults to `Object.is` */\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n },\n): TSelectorReturn {\n const subscription = useCoValueSubscription(Schema, id, options);\n\n return useSyncExternalStoreWithSelector<\n Loaded<S, R> | undefined | null,\n TSelectorReturn\n >(\n React.useCallback(\n (callback) => {\n if (!subscription) {\n return () => {};\n }\n\n return subscription.subscribe(callback);\n },\n [subscription],\n ),\n () => (subscription ? subscription.getCurrentValue() : null),\n () => (subscription ? subscription.getCurrentValue() : null),\n options.select,\n options.equalityFn ?? Object.is,\n );\n}\n\nfunction useAccountSubscription<\n S extends AccountClass<Account> | AnyAccountSchema,\n const R extends ResolveQuery<S>,\n>(\n Schema: S,\n options?: {\n resolve?: ResolveQueryStrict<S, R>;\n unstable_branch?: BranchDefinition;\n },\n) {\n const contextManager = useJazzContextManager();\n\n const createSubscription = () => {\n const agent = getCurrentAccountFromContextManager(contextManager);\n\n if (agent.$type$ === \"Anonymous\") {\n return {\n subscription: null,\n contextManager,\n agent,\n };\n }\n\n // We don't need type validation here, since it's mostly to help users on public API\n const resolve: any = options?.resolve ?? true;\n\n const node = contextManager.getCurrentValue()!.node;\n const subscription = new SubscriptionScope<any>(\n node,\n resolve,\n agent.$jazz.id,\n {\n ref: coValueClassFromCoValueClassOrSchema(Schema),\n optional: true,\n },\n false,\n false,\n options?.unstable_branch,\n );\n\n return {\n subscription,\n contextManager,\n Schema,\n branchName: options?.unstable_branch?.name,\n branchOwnerId: options?.unstable_branch?.owner?.$jazz.id,\n };\n };\n\n const [subscription, setSubscription] = React.useState(createSubscription);\n\n const branchName = options?.unstable_branch?.name;\n const branchOwnerId = options?.unstable_branch?.owner?.$jazz.id;\n\n React.useLayoutEffect(() => {\n if (\n subscription.contextManager !== contextManager ||\n subscription.Schema !== Schema ||\n subscription.branchName !== options?.unstable_branch?.name ||\n subscription.branchOwnerId !== options?.unstable_branch?.owner?.$jazz.id\n ) {\n subscription.subscription?.destroy();\n setSubscription(createSubscription());\n }\n\n return contextManager.subscribe(() => {\n subscription.subscription?.destroy();\n setSubscription(createSubscription());\n });\n }, [Schema, contextManager, branchName, branchOwnerId]);\n\n return subscription.subscription;\n}\n\n/**\n * React hook for accessing the current user's account and authentication state.\n * \n * This hook provides access to the current user's account profile and root data,\n * along with authentication utilities. It automatically handles subscription to\n * the user's account data and provides a logout function.\n * \n * @returns An object containing:\n * - `me`: The loaded account data, or `undefined` if loading, or `null` if not authenticated\n * - `agent`: The current agent (anonymous or authenticated user). Can be used as `loadAs` parameter for load and subscribe methods.\n * - `logOut`: Function to log out the current user\n\n * @example\n * ```tsx\n * // Deep loading with resolve queries\n * function ProjectListWithDetails() {\n * const { me } = useAccount(MyAppAccount, {\n * resolve: {\n * profile: true,\n * root: {\n * myProjects: {\n * $each: {\n * tasks: true,\n * },\n * },\n * },\n * },\n * });\n * \n * if (!me) {\n * return me === null\n * ? <div>Failed to load your projects</div>\n * : <div>Loading...</div>;\n * }\n * \n * return (\n * <div>\n * <h1>{me.profile.name}'s projects</h1>\n * <ul>\n * {me.root.myProjects.map((project) => (\n * <li key={project.id}>\n * {project.name} ({project.tasks.length} tasks)\n * </li>\n * ))}\n * </ul>\n * </div>\n * );\n * }\n * ```\n * \n */\nexport function useAccount<\n A extends AccountClass<Account> | AnyAccountSchema,\n R extends ResolveQuery<A> = true,\n>(\n /** The account schema to use. Defaults to the base Account schema */\n AccountSchema: A = Account as unknown as A,\n /** Optional configuration for the subscription */\n options?: {\n /** Resolve query to specify which nested CoValues to load from the account */\n resolve?: ResolveQueryStrict<A, R>;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n },\n): {\n me: Loaded<A, R> | undefined | null;\n agent: AnonymousJazzAgent | Loaded<A, true>;\n logOut: () => void;\n} {\n const contextManager = useJazzContextManager<InstanceOfSchema<A>>();\n const subscription = useAccountSubscription(AccountSchema, options);\n\n const agent = getCurrentAccountFromContextManager(contextManager);\n\n const value = React.useSyncExternalStore<Loaded<A, R> | undefined | null>(\n React.useCallback(\n (callback) => {\n if (!subscription) {\n return () => {};\n }\n\n return subscription.subscribe(callback);\n },\n [subscription],\n ),\n () => (subscription ? subscription.getCurrentValue() : null),\n () => (subscription ? subscription.getCurrentValue() : null),\n );\n\n return {\n me: value,\n agent,\n logOut: contextManager.logOut,\n };\n}\n\n/**\n * React hook for accessing the current user's account with selective data extraction and custom equality checking.\n *\n * This hook extends `useAccount` by allowing you to select only specific parts of the account data\n * through a selector function, which helps reduce unnecessary re-renders by narrowing down the\n * returned data. Additionally, you can provide a custom equality function to further optimize\n * performance by controlling when the component should re-render based on the selected data.\n *\n * The hook automatically handles the subscription lifecycle and supports deep loading of nested\n * CoValues through resolve queries, just like `useAccount`.\n *\n * @returns The result of the selector function applied to the loaded account data\n *\n * @example\n * ```tsx\n * // Select only specific fields to reduce re-renders\n * const MyAppAccount = co.account({\n * profile: co.profile(),\n * root: co.map({\n * name: z.string(),\n * email: z.string(),\n * lastLogin: z.date(),\n * }),\n * });\n *\n * function UserProfile({ accountId }: { accountId: string }) {\n * // Only re-render when the profile name changes, not other fields\n * const profileName = useAccountWithSelector(\n * MyAppAccount,\n * {\n * resolve: {\n * profile: true,\n * root: true,\n * },\n * select: (account) => account?.profile?.name ?? \"Loading...\",\n * }\n * );\n *\n * return <h1>{profileName}</h1>;\n * }\n * ```\n *\n * For more examples, see the [subscription and deep loading](https://jazz.tools/docs/react/using-covalues/subscription-and-loading) documentation.\n */\nexport function useAccountWithSelector<\n A extends AccountClass<Account> | AnyAccountSchema,\n TSelectorReturn,\n R extends ResolveQuery<A> = true,\n>(\n /** The account schema to use. Defaults to the base Account schema */\n AccountSchema: A = Account as unknown as A,\n /** Configuration for the subscription and selection */\n options: {\n /** Resolve query to specify which nested CoValues to load from the account */\n resolve?: ResolveQueryStrict<A, R>;\n /** Select which value to return from the account data */\n select: (account: Loaded<A, R> | undefined | null) => TSelectorReturn;\n /** Equality function to determine if the selected value has changed, defaults to `Object.is` */\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n },\n): TSelectorReturn {\n const subscription = useAccountSubscription(AccountSchema, options);\n\n return useSyncExternalStoreWithSelector<\n Loaded<A, R> | undefined | null,\n TSelectorReturn\n >(\n React.useCallback(\n (callback) => {\n if (!subscription) {\n return () => {};\n }\n\n return subscription.subscribe(callback);\n },\n [subscription],\n ),\n () => (subscription ? subscription.getCurrentValue() : null),\n () => (subscription ? subscription.getCurrentValue() : null),\n options.select,\n options.equalityFn ?? Object.is,\n );\n}\n\nexport function experimental_useInboxSender<\n I extends CoValue,\n O extends CoValue | undefined,\n>(inboxOwnerID: string | undefined) {\n const context = useJazzContext();\n\n if (!(\"me\" in context)) {\n throw new Error(\n \"useInboxSender can't be used in a JazzProvider with auth === 'guest'.\",\n );\n }\n\n const me = context.me;\n const inboxRef = useRef<Promise<InboxSender<I, O>> | undefined>(undefined);\n\n const sendMessage = useCallback(\n async (message: I) => {\n if (!inboxOwnerID) throw new Error(\"Inbox owner ID is required\");\n\n if (!inboxRef.current) {\n const inbox = InboxSender.load<I, O>(inboxOwnerID, me);\n inboxRef.current = inbox;\n }\n\n let inbox = await inboxRef.current;\n\n if (inbox.owner.id !== inboxOwnerID) {\n const req = InboxSender.load<I, O>(inboxOwnerID, me);\n inboxRef.current = req;\n inbox = await req;\n }\n\n return inbox.sendMessage(message);\n },\n [inboxOwnerID],\n );\n\n return sendMessage;\n}\n\n/**\n * Hook that returns the current connection status to the Jazz sync server.\n *\n * @returns `true` when connected to the server, `false` when disconnected\n *\n * @remarks\n * On connection drop, this hook will return `false` only when Jazz detects the disconnection\n * after 5 seconds of not receiving a ping from the server.\n */\nexport function useSyncConnectionStatus() {\n const context = useJazzContext();\n\n const connected = useSyncExternalStore(\n useCallback(\n (callback) => {\n return context.addConnectionListener(callback);\n },\n [context],\n ),\n () => context.connected(),\n () => context.connected(),\n );\n\n return connected;\n}\n","import { Account, JazzContextManager } from \"jazz-tools\";\n\nexport function getCurrentAccountFromContextManager<Acc extends Account>(\n contextManager: JazzContextManager<Acc, any>,\n) {\n const context = contextManager.getCurrentValue();\n\n if (!context) {\n throw new Error(\"No context found\");\n }\n\n return \"me\" in context ? context.me : context.guest;\n}\n\nexport function subscribeToContextManager<Acc extends Account>(\n contextManager: JazzContextManager<Acc, any>,\n callback: () => () => void,\n) {\n let unsub = () => {};\n\n const handler = () => {\n unsub();\n unsub = callback();\n };\n\n handler();\n return contextManager.subscribe(handler);\n}\n","import { DemoAuth } from \"jazz-tools\";\nimport { useEffect, useMemo, useState } from \"react\";\nimport { useAuthSecretStorage, useJazzContext } from \"../hooks.js\";\nimport { useIsAuthenticated } from \"../hooks.js\";\n\n/**\n * `useDemoAuth` is a hook that provides a `JazzAuth` object for demo authentication.\n *\n *\n * ```ts\n * const { state, logIn, signUp, existingUsers } = useDemoAuth();\n * ```\n *\n * @category Auth Providers\n */\nexport function useDemoAuth() {\n const context = useJazzContext();\n const authSecretStorage = useAuthSecretStorage();\n\n if (\"guest\" in context) {\n throw new Error(\"Demo auth is not supported in guest mode\");\n }\n\n const authMethod = useMemo(() => {\n return new DemoAuth(context.authenticate, authSecretStorage);\n }, []);\n\n const isAuthenticated = useIsAuthenticated();\n const [existingUsers, setExistingUsers] = useState<string[]>([]);\n\n useEffect(() => {\n authMethod.getExistingUsers().then(setExistingUsers);\n }, [authMethod]);\n\n function handleSignUp(username: string) {\n return authMethod.signUp(username).then(() => {\n setExistingUsers(existingUsers.concat([username]));\n });\n }\n\n return {\n state: isAuthenticated ? \"signedIn\" : \"anonymous\",\n logIn: authMethod.logIn,\n signUp: handleSignUp,\n existingUsers,\n } as const;\n}\n","import { PassphraseAuth } from \"jazz-tools\";\nimport { useCallback, useMemo, useSyncExternalStore } from \"react\";\nimport { useAuthSecretStorage, useJazzContext } from \"../hooks.js\";\nimport { useIsAuthenticated } from \"../hooks.js\";\n\n/**\n * `usePassphraseAuth` hook provides a `JazzAuth` object for passphrase authentication.\n *\n * @example\n * ```ts\n * const auth = usePassphraseAuth({ appName, appHostname, wordlist });\n * ```\n *\n * @category Auth Providers\n */\nexport function usePassphraseAuth({ wordlist }: { wordlist: string[] }) {\n const context = useJazzContext();\n const authSecretStorage = useAuthSecretStorage();\n\n if (\"guest\" in context) {\n throw new Error(\"Passphrase auth is not supported in guest mode\");\n }\n\n const authMethod = useMemo(() => {\n return new PassphraseAuth(\n context.node.crypto,\n context.authenticate,\n context.register,\n authSecretStorage,\n wordlist,\n );\n }, [wordlist]);\n\n const passphrase = useSyncExternalStore(\n useCallback(\n (callback) => {\n authMethod.loadCurrentAccountPassphrase();\n return authMethod.subscribe(callback);\n },\n [authMethod],\n ),\n () => authMethod.passphrase,\n );\n\n const isAuthenticated = useIsAuthenticated();\n return {\n state: isAuthenticated ? \"signedIn\" : \"anonymous\",\n logIn: authMethod.logIn,\n signUp: authMethod.signUp,\n registerNewAccount: authMethod.registerNewAccount,\n generateRandomPassphrase: authMethod.generateRandomPassphrase,\n passphrase,\n } as const;\n}\n"],"mappings":";;;;;;;AAAA,SAAS,wCAAwC;AACjD,OAAO;AAAA,EACL;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EAOA;AAAA,EAOA;AAAA,EACA;AAAA,OAEK;;;ACxBA,SAAS,oCACd,gBACA;AACA,QAAM,UAAU,eAAe,gB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ACnB;AAEA,QAAM,kBAAkB,mBAAmB;AAC3C,SAAO;AAAA,IACL,OAAO,kBAAkB,aAAa;AAAA,IACtC,OAAO,WAAW;AAAA,IAClB,QAAQ,WAAW;AAAA,IACnB,oBAAoB,WAAW;AAAA,IAC/B,0BAA0B,WAAW;AAAA,IACrC;AAAA,EACF;AACF;","names":["subscription","inbox","useCallback","useMemo","useSyncExternalStore","useMemo","useSyncExternalStore","useCallback"]}
|
1
|
+
{"version":3,"sources":["../../src/react-core/hooks.ts","../../src/react-core/utils.ts","../../src/react-core/auth/DemoAuth.tsx","../../src/react-core/auth/PassphraseAuth.tsx"],"sourcesContent":["import { useSyncExternalStoreWithSelector } from \"use-sync-external-store/shim/with-selector\";\nimport React, {\n useCallback,\n useContext,\n useRef,\n useSyncExternalStore,\n} from \"react\";\n\nimport {\n Account,\n AccountClass,\n AnonymousJazzAgent,\n AnyAccountSchema,\n CoValue,\n CoValueClassOrSchema,\n Group,\n InboxSender,\n InstanceOfSchema,\n JazzContextManager,\n JazzContextType,\n Loaded,\n ResolveQuery,\n ResolveQueryStrict,\n SubscriptionScope,\n coValueClassFromCoValueClassOrSchema,\n type BranchDefinition,\n} from \"jazz-tools\";\nimport { JazzContext, JazzContextManagerContext } from \"./provider.js\";\nimport { getCurrentAccountFromContextManager } from \"./utils.js\";\n\nexport function useJazzContext<Acc extends Account>() {\n const value = useContext(JazzContext) as JazzContextType<Acc>;\n\n if (!value) {\n throw new Error(\n \"You need to set up a JazzProvider on top of your app to use this hook.\",\n );\n }\n\n return value;\n}\n\nexport function useJazzContextManager<Acc extends Account>() {\n const value = useContext(JazzContextManagerContext) as JazzContextManager<\n Acc,\n {}\n >;\n\n if (!value) {\n throw new Error(\n \"You need to set up a JazzProvider on top of your app to use this hook.\",\n );\n }\n\n return value;\n}\n\nexport function useAuthSecretStorage() {\n const value = useContext(JazzContextManagerContext);\n\n if (!value) {\n throw new Error(\n \"You need to set up a JazzProvider on top of your app to use this useAuthSecretStorage.\",\n );\n }\n\n return value.getAuthSecretStorage();\n}\n\nexport function useIsAuthenticated() {\n const authSecretStorage = useAuthSecretStorage();\n\n return useSyncExternalStore(\n useCallback(\n (callback) => {\n return authSecretStorage.onUpdate(callback);\n },\n [authSecretStorage],\n ),\n () => authSecretStorage.isAuthenticated,\n () => authSecretStorage.isAuthenticated,\n );\n}\n\nfunction useCoValueSubscription<\n S extends CoValueClassOrSchema,\n const R extends ResolveQuery<S>,\n>(\n Schema: S,\n id: string | undefined | null,\n options?: {\n resolve?: ResolveQueryStrict<S, R>;\n unstable_branch?: BranchDefinition;\n },\n) {\n const contextManager = useJazzContextManager();\n\n const createSubscription = () => {\n if (!id) {\n return {\n subscription: null,\n contextManager,\n id,\n Schema,\n };\n }\n\n if (options?.unstable_branch?.owner === null) {\n return {\n subscription: null,\n contextManager,\n id,\n Schema,\n };\n }\n\n const node = contextManager.getCurrentValue()!.node;\n const subscription = new SubscriptionScope<any>(\n node,\n options?.resolve ?? true,\n id,\n {\n ref: coValueClassFromCoValueClassOrSchema(Schema),\n optional: true,\n },\n false,\n false,\n options?.unstable_branch,\n );\n\n return {\n subscription,\n contextManager,\n id,\n Schema,\n branchName: options?.unstable_branch?.name,\n branchOwnerId: options?.unstable_branch?.owner?.$jazz.id,\n };\n };\n\n const [subscription, setSubscription] = React.useState(createSubscription);\n\n const branchName = options?.unstable_branch?.name;\n const branchOwnerId = options?.unstable_branch?.owner?.$jazz.id;\n\n React.useLayoutEffect(() => {\n if (\n subscription.contextManager !== contextManager ||\n subscription.id !== id ||\n subscription.Schema !== Schema ||\n subscription.branchName !== branchName ||\n subscription.branchOwnerId !== branchOwnerId\n ) {\n subscription.subscription?.destroy();\n setSubscription(createSubscription());\n }\n\n return contextManager.subscribe(() => {\n subscription.subscription?.destroy();\n setSubscription(createSubscription());\n });\n }, [Schema, id, contextManager, branchName, branchOwnerId]);\n\n return subscription.subscription;\n}\n\n/**\n * React hook for subscribing to CoValues and handling loading states.\n *\n * This hook provides a convenient way to subscribe to CoValues and automatically\n * handles the subscription lifecycle (subscribe on mount, unsubscribe on unmount).\n * It also supports deep loading of nested CoValues through resolve queries.\n *\n * @returns The loaded CoValue, or `undefined` if loading, or `null` if not found/not accessible\n *\n * @example\n * ```tsx\n * // Deep loading with resolve queries\n * const Project = co.map({\n * name: z.string(),\n * tasks: co.list(Task),\n * owner: TeamMember,\n * });\n *\n * function ProjectView({ projectId }: { projectId: string }) {\n * const project = useCoState(Project, projectId, {\n * resolve: {\n * tasks: { $each: true },\n * owner: true,\n * },\n * });\n *\n * if (!project) {\n * return project === null\n * ? \"Project not found or not accessible\"\n * : \"Loading project...\";\n * }\n *\n * return (\n * <div>\n * <h1>{project.name}</h1>\n * <p>Owner: {project.owner.name}</p>\n * <ul>\n * {project.tasks.map((task) => (\n * <li key={task.id}>{task.title}</li>\n * ))}\n * </ul>\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Using with optional references and error handling\n * const Task = co.map({\n * title: z.string(),\n * assignee: co.optional(TeamMember),\n * subtasks: co.list(Task),\n * });\n *\n * function TaskDetail({ taskId }: { taskId: string }) {\n * const task = useCoState(Task, taskId, {\n * resolve: {\n * assignee: true,\n * subtasks: { $each: { $onError: null } },\n * },\n * });\n *\n * if (!task) {\n * return task === null\n * ? \"Task not found or not accessible\"\n * : \"Loading task...\";\n * }\n *\n * return (\n * <div>\n * <h2>{task.title}</h2>\n * {task.assignee && <p>Assigned to: {task.assignee.name}</p>}\n * <ul>\n * {task.subtasks.map((subtask, index) => (\n * subtask ? <li key={subtask.id}>{subtask.title}</li> : <li key={index}>Inaccessible subtask</li>\n * ))}\n * </ul>\n * </div>\n * );\n * }\n * ```\n *\n * For more examples, see the [subscription and deep loading](https://jazz.tools/docs/react/using-covalues/subscription-and-loading) documentation.\n */\nexport function useCoState<\n S extends CoValueClassOrSchema,\n const R extends ResolveQuery<S> = true,\n>(\n /** The CoValue schema or class constructor */\n Schema: S,\n /** The ID of the CoValue to subscribe to. If `undefined`, returns `null` */\n id: string | undefined,\n /** Optional configuration for the subscription */\n options?: {\n /** Resolve query to specify which nested CoValues to load */\n resolve?: ResolveQueryStrict<S, R>;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n },\n): Loaded<S, R> | undefined | null {\n const subscription = useCoValueSubscription(Schema, id, options);\n\n const value = React.useSyncExternalStore<Loaded<S, R> | undefined | null>(\n React.useCallback(\n (callback) => {\n if (!subscription) {\n return () => {};\n }\n\n return subscription.subscribe(callback);\n },\n [subscription],\n ),\n () => (subscription ? subscription.getCurrentValue() : null),\n () => (subscription ? subscription.getCurrentValue() : null),\n );\n\n return value;\n}\n\n/**\n * React hook for subscribing to CoValues with selective data extraction and custom equality checking.\n *\n * This hook extends `useCoState` by allowing you to select only specific parts of the CoValue data\n * through a selector function, which helps reduce unnecessary re-renders by narrowing down the\n * returned data. Additionally, you can provide a custom equality function to further optimize\n * performance by controlling when the component should re-render based on the selected data.\n *\n * The hook automatically handles the subscription lifecycle and supports deep loading of nested\n * CoValues through resolve queries, just like `useCoState`.\n *\n * @returns The result of the selector function applied to the loaded CoValue data\n *\n * @example\n * ```tsx\n * // Select only specific fields to reduce re-renders\n * const Project = co.map({\n * name: z.string(),\n * description: z.string(),\n * tasks: co.list(Task),\n * lastModified: z.date(),\n * });\n *\n * function ProjectTitle({ projectId }: { projectId: string }) {\n * // Only re-render when the project name changes, not other fields\n * const projectName = useCoStateWithSelector(\n * Project,\n * projectId,\n * {\n * select: (project) => project?.name ?? \"Loading...\",\n * }\n * );\n *\n * return <h1>{projectName}</h1>;\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Use custom equality function for complex data structures\n * const TaskList = co.list(Task);\n *\n * function TaskCount({ listId }: { listId: string }) {\n * const taskStats = useCoStateWithSelector(\n * TaskList,\n * listId,\n * {\n * resolve: { $each: true },\n * select: (tasks) => {\n * if (!tasks) return { total: 0, completed: 0 };\n * return {\n * total: tasks.length,\n * completed: tasks.filter(task => task.completed).length,\n * };\n * },\n * // Custom equality to prevent re-renders when stats haven't changed\n * equalityFn: (a, b) => a.total === b.total && a.completed === b.completed,\n * }\n * );\n *\n * return (\n * <div>\n * {taskStats.completed} of {taskStats.total} tasks completed\n * </div>\n * );\n * }\n * ```\n *\n * @example\n * ```tsx\n * // Combine with deep loading and complex selectors\n * const Team = co.map({\n * name: z.string(),\n * members: co.list(TeamMember),\n * projects: co.list(Project),\n * });\n *\n * function TeamSummary({ teamId }: { teamId: string }) {\n * const summary = useCoStateWithSelector(\n * Team,\n * teamId,\n * {\n * resolve: {\n * members: { $each: true },\n * projects: { $each: { tasks: { $each: true } } },\n * },\n * select: (team) => {\n * if (!team) return null;\n *\n * const totalTasks = team.projects.reduce(\n * (sum, project) => sum + project.tasks.length,\n * 0\n * );\n *\n * return {\n * teamName: team.name,\n * memberCount: team.members.length,\n * projectCount: team.projects.length,\n * totalTasks,\n * };\n * },\n * }\n * );\n *\n * if (!summary) return <div>Loading team summary...</div>;\n *\n * return (\n * <div>\n * <h2>{summary.teamName}</h2>\n * <p>{summary.memberCount} members</p>\n * <p>{summary.projectCount} projects</p>\n * <p>{summary.totalTasks} total tasks</p>\n * </div>\n * );\n * }\n * ```\n *\n * For more examples, see the [subscription and deep loading](https://jazz.tools/docs/react/using-covalues/subscription-and-loading) documentation.\n */\nexport function useCoStateWithSelector<\n S extends CoValueClassOrSchema,\n TSelectorReturn,\n const R extends ResolveQuery<S> = true,\n>(\n /** The CoValue schema or class constructor */\n Schema: S,\n /** The ID of the CoValue to subscribe to. If `undefined`, returns the result of selector called with `null` */\n id: string | undefined,\n /** Optional configuration for the subscription */\n options: {\n /** Resolve query to specify which nested CoValues to load */\n resolve?: ResolveQueryStrict<S, R>;\n /** Select which value to return */\n select: (value: Loaded<S, R> | undefined | null) => TSelectorReturn;\n /** Equality function to determine if the selected value has changed, defaults to `Object.is` */\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n },\n): TSelectorReturn {\n const subscription = useCoValueSubscription(Schema, id, options);\n\n return useSyncExternalStoreWithSelector<\n Loaded<S, R> | undefined | null,\n TSelectorReturn\n >(\n React.useCallback(\n (callback) => {\n if (!subscription) {\n return () => {};\n }\n\n return subscription.subscribe(callback);\n },\n [subscription],\n ),\n () => (subscription ? subscription.getCurrentValue() : null),\n () => (subscription ? subscription.getCurrentValue() : null),\n options.select,\n options.equalityFn ?? Object.is,\n );\n}\n\nfunction useAccountSubscription<\n S extends AccountClass<Account> | AnyAccountSchema,\n const R extends ResolveQuery<S>,\n>(\n Schema: S,\n options?: {\n resolve?: ResolveQueryStrict<S, R>;\n unstable_branch?: BranchDefinition;\n },\n) {\n const contextManager = useJazzContextManager();\n\n const createSubscription = () => {\n const agent = getCurrentAccountFromContextManager(contextManager);\n\n if (agent.$type$ === \"Anonymous\") {\n return {\n subscription: null,\n contextManager,\n agent,\n };\n }\n\n // We don't need type validation here, since it's mostly to help users on public API\n const resolve: any = options?.resolve ?? true;\n\n const node = contextManager.getCurrentValue()!.node;\n const subscription = new SubscriptionScope<any>(\n node,\n resolve,\n agent.$jazz.id,\n {\n ref: coValueClassFromCoValueClassOrSchema(Schema),\n optional: true,\n },\n false,\n false,\n options?.unstable_branch,\n );\n\n return {\n subscription,\n contextManager,\n Schema,\n branchName: options?.unstable_branch?.name,\n branchOwnerId: options?.unstable_branch?.owner?.$jazz.id,\n };\n };\n\n const [subscription, setSubscription] = React.useState(createSubscription);\n\n const branchName = options?.unstable_branch?.name;\n const branchOwnerId = options?.unstable_branch?.owner?.$jazz.id;\n\n React.useLayoutEffect(() => {\n if (\n subscription.contextManager !== contextManager ||\n subscription.Schema !== Schema ||\n subscription.branchName !== options?.unstable_branch?.name ||\n subscription.branchOwnerId !== options?.unstable_branch?.owner?.$jazz.id\n ) {\n subscription.subscription?.destroy();\n setSubscription(createSubscription());\n }\n\n return contextManager.subscribe(() => {\n subscription.subscription?.destroy();\n setSubscription(createSubscription());\n });\n }, [Schema, contextManager, branchName, branchOwnerId]);\n\n return subscription.subscription;\n}\n\n/**\n * React hook for accessing the current user's account and authentication state.\n * \n * This hook provides access to the current user's account profile and root data,\n * along with authentication utilities. It automatically handles subscription to\n * the user's account data and provides a logout function.\n * \n * @returns An object containing:\n * - `me`: The loaded account data, or `undefined` if loading, or `null` if not authenticated\n * - `agent`: The current agent (anonymous or authenticated user). Can be used as `loadAs` parameter for load and subscribe methods.\n * - `logOut`: Function to log out the current user\n\n * @example\n * ```tsx\n * // Deep loading with resolve queries\n * function ProjectListWithDetails() {\n * const { me } = useAccount(MyAppAccount, {\n * resolve: {\n * profile: true,\n * root: {\n * myProjects: {\n * $each: {\n * tasks: true,\n * },\n * },\n * },\n * },\n * });\n * \n * if (!me) {\n * return me === null\n * ? <div>Failed to load your projects</div>\n * : <div>Loading...</div>;\n * }\n * \n * return (\n * <div>\n * <h1>{me.profile.name}'s projects</h1>\n * <ul>\n * {me.root.myProjects.map((project) => (\n * <li key={project.id}>\n * {project.name} ({project.tasks.length} tasks)\n * </li>\n * ))}\n * </ul>\n * </div>\n * );\n * }\n * ```\n * \n */\nexport function useAccount<\n A extends AccountClass<Account> | AnyAccountSchema,\n R extends ResolveQuery<A> = true,\n>(\n /** The account schema to use. Defaults to the base Account schema */\n AccountSchema: A = Account as unknown as A,\n /** Optional configuration for the subscription */\n options?: {\n /** Resolve query to specify which nested CoValues to load from the account */\n resolve?: ResolveQueryStrict<A, R>;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n },\n): {\n me: Loaded<A, R> | undefined | null;\n agent: AnonymousJazzAgent | Loaded<A, true>;\n logOut: () => void;\n} {\n const contextManager = useJazzContextManager<InstanceOfSchema<A>>();\n const subscription = useAccountSubscription(AccountSchema, options);\n\n const agent = getCurrentAccountFromContextManager(contextManager);\n\n const value = React.useSyncExternalStore<Loaded<A, R> | undefined | null>(\n React.useCallback(\n (callback) => {\n if (!subscription) {\n return () => {};\n }\n\n return subscription.subscribe(callback);\n },\n [subscription],\n ),\n () => (subscription ? subscription.getCurrentValue() : null),\n () => (subscription ? subscription.getCurrentValue() : null),\n );\n\n return {\n me: value,\n agent,\n logOut: contextManager.logOut,\n };\n}\n\n/**\n * React hook for accessing the current user's account with selective data extraction and custom equality checking.\n *\n * This hook extends `useAccount` by allowing you to select only specific parts of the account data\n * through a selector function, which helps reduce unnecessary re-renders by narrowing down the\n * returned data. Additionally, you can provide a custom equality function to further optimize\n * performance by controlling when the component should re-render based on the selected data.\n *\n * The hook automatically handles the subscription lifecycle and supports deep loading of nested\n * CoValues through resolve queries, just like `useAccount`.\n *\n * @returns The result of the selector function applied to the loaded account data\n *\n * @example\n * ```tsx\n * // Select only specific fields to reduce re-renders\n * const MyAppAccount = co.account({\n * profile: co.profile(),\n * root: co.map({\n * name: z.string(),\n * email: z.string(),\n * lastLogin: z.date(),\n * }),\n * });\n *\n * function UserProfile({ accountId }: { accountId: string }) {\n * // Only re-render when the profile name changes, not other fields\n * const profileName = useAccountWithSelector(\n * MyAppAccount,\n * {\n * resolve: {\n * profile: true,\n * root: true,\n * },\n * select: (account) => account?.profile?.name ?? \"Loading...\",\n * }\n * );\n *\n * return <h1>{profileName}</h1>;\n * }\n * ```\n *\n * For more examples, see the [subscription and deep loading](https://jazz.tools/docs/react/using-covalues/subscription-and-loading) documentation.\n */\nexport function useAccountWithSelector<\n A extends AccountClass<Account> | AnyAccountSchema,\n TSelectorReturn,\n R extends ResolveQuery<A> = true,\n>(\n /** The account schema to use. Defaults to the base Account schema */\n AccountSchema: A = Account as unknown as A,\n /** Configuration for the subscription and selection */\n options: {\n /** Resolve query to specify which nested CoValues to load from the account */\n resolve?: ResolveQueryStrict<A, R>;\n /** Select which value to return from the account data */\n select: (account: Loaded<A, R> | undefined | null) => TSelectorReturn;\n /** Equality function to determine if the selected value has changed, defaults to `Object.is` */\n equalityFn?: (a: TSelectorReturn, b: TSelectorReturn) => boolean;\n /**\n * Create or load a branch for isolated editing.\n *\n * Branching lets you take a snapshot of the current state and start modifying it without affecting the canonical/shared version.\n * It's a fork of your data graph: the same schema, but with diverging values.\n *\n * The checkout of the branch is applied on all the resolved values.\n *\n * @param name - A unique name for the branch. This identifies the branch\n * and can be used to switch between different branches of the same CoValue.\n * @param owner - The owner of the branch. Determines who can access and modify\n * the branch. If not provided, the branch is owned by the current user.\n *\n * For more info see the [branching](https://jazz.tools/docs/react/using-covalues/version-control) documentation.\n */\n unstable_branch?: BranchDefinition;\n },\n): TSelectorReturn {\n const subscription = useAccountSubscription(AccountSchema, options);\n\n return useSyncExternalStoreWithSelector<\n Loaded<A, R> | undefined | null,\n TSelectorReturn\n >(\n React.useCallback(\n (callback) => {\n if (!subscription) {\n return () => {};\n }\n\n return subscription.subscribe(callback);\n },\n [subscription],\n ),\n () => (subscription ? subscription.getCurrentValue() : null),\n () => (subscription ? subscription.getCurrentValue() : null),\n options.select,\n options.equalityFn ?? Object.is,\n );\n}\n\nexport function experimental_useInboxSender<\n I extends CoValue,\n O extends CoValue | undefined,\n>(inboxOwnerID: string | undefined) {\n const context = useJazzContext();\n\n if (!(\"me\" in context)) {\n throw new Error(\n \"useInboxSender can't be used in a JazzProvider with auth === 'guest'.\",\n );\n }\n\n const me = context.me;\n const inboxRef = useRef<Promise<InboxSender<I, O>> | undefined>(undefined);\n\n const sendMessage = useCallback(\n async (message: I) => {\n if (!inboxOwnerID) throw new Error(\"Inbox owner ID is required\");\n\n if (!inboxRef.current) {\n const inbox = InboxSender.load<I, O>(inboxOwnerID, me);\n inboxRef.current = inbox;\n }\n\n let inbox = await inboxRef.current;\n\n // Regenerate the InboxSender if the inbox owner or current account changes\n if (inbox.owner.id !== inboxOwnerID || inbox.currentAccount !== me) {\n const req = InboxSender.load<I, O>(inboxOwnerID, me);\n inboxRef.current = req;\n inbox = await req;\n }\n\n return inbox.sendMessage(message);\n },\n [inboxOwnerID, me.$jazz.id],\n );\n\n return sendMessage;\n}\n\n/**\n * Hook that returns the current connection status to the Jazz sync server.\n *\n * @returns `true` when connected to the server, `false` when disconnected\n *\n * @remarks\n * On connection drop, this hook will return `false` only when Jazz detects the disconnection\n * after 5 seconds of not receiving a ping from the server.\n */\nexport function useSyncConnectionStatus() {\n const context = useJazzContext();\n\n const connected = useSyncExternalStore(\n useCallback(\n (callback) => {\n return context.addConnectionListener(callback);\n },\n [context],\n ),\n () => context.connected(),\n () => context.connected(),\n );\n\n return connected;\n}\n","import { Account, JazzContextManager } from \"jazz-tools\";\n\nexport function getCurrentAccountFromContextManager<Acc extends Account>(\n contextManager: JazzContextManager<Acc, any>,\n) {\n const context = contextManager.getCurrentValue();\n\n if (!context) {\n throw new Error(\"No context found\");\n }\n\n return \"me\" in context ? context.me : context.guest;\n}\n\nexport function subscribeToContextManager<Acc extends Account>(\n contextManager: JazzContextManager<Acc, any>,\n callback: () => () => void,\n) {\n let unsub = () => {};\n\n const handler = () => {\n unsub();\n unsub = callback();\n };\n\n handler();\n return contextManager.subscribe(handler);\n}\n","import { DemoAuth } from \"jazz-tools\";\nimport { useEffect, useMemo, useState } from \"react\";\nimport { useAuthSecretStorage, useJazzContext } from \"../hooks.js\";\nimport { useIsAuthenticated } from \"../hooks.js\";\n\n/**\n * `useDemoAuth` is a hook that provides a `JazzAuth` object for demo authentication.\n *\n *\n * ```ts\n * const { state, logIn, signUp, existingUsers } = useDemoAuth();\n * ```\n *\n * @category Auth Providers\n */\nexport function useDemoAuth() {\n const context = useJazzContext();\n const authSecretStorage = useAuthSecretStorage();\n\n if (\"guest\" in context) {\n throw new Error(\"Demo auth is not supported in guest mode\");\n }\n\n const authMethod = useMemo(() => {\n return new DemoAuth(context.authenticate, authSecretStorage);\n }, []);\n\n const isAuthenticated = useIsAuthenticated();\n const [existingUsers, setExistingUsers] = useState<string[]>([]);\n\n useEffect(() => {\n authMethod.getExistingUsers().then(setExistingUsers);\n }, [authMethod]);\n\n function handleSignUp(username: string) {\n return authMethod.signUp(username).then(() => {\n setExistingUsers(existingUsers.concat([username]));\n });\n }\n\n return {\n state: isAuthenticated ? \"signedIn\" : \"anonymous\",\n logIn: authMethod.logIn,\n signUp: handleSignUp,\n existingUsers,\n } as const;\n}\n","import { PassphraseAuth } from \"jazz-tools\";\nimport { useCallback, useMemo, useSyncExternalStore } from \"react\";\nimport { useAuthSecretStorage, useJazzContext } from \"../hooks.js\";\nimport { useIsAuthenticated } from \"../hooks.js\";\n\n/**\n * `usePassphraseAuth` hook provides a `JazzAuth` object for passphrase authentication.\n *\n * @example\n * ```ts\n * const auth = usePassphraseAuth({ appName, appHostname, wordlist });\n * ```\n *\n * @category Auth Providers\n */\nexport function usePassphraseAuth({ wordlist }: { wordlist: string[] }) {\n const context = useJazzContext();\n const authSecretStorage = useAuthSecretStorage();\n\n if (\"guest\" in context) {\n throw new Error(\"Passphrase auth is not supported in guest mode\");\n }\n\n const authMethod = useMemo(() => {\n return new PassphraseAuth(\n context.node.crypto,\n context.authenticate,\n context.register,\n authSecretStorage,\n wordlist,\n );\n }, [wordlist]);\n\n const passphrase = useSyncExternalStore(\n useCallback(\n (callback) => {\n authMethod.loadCurrentAccountPassphrase();\n return authMethod.subscribe(callback);\n },\n [authMethod],\n ),\n () => authMethod.passphrase,\n );\n\n const isAuthenticated = useIsAuthenticated();\n return {\n state: isAuthenticated ? \"signedIn\" : \"anonymous\",\n logIn: authMethod.logIn,\n signUp: authMethod.signUp,\n registerNewAccount: authMethod.registerNewAccount,\n generateRandomPassphrase: authMethod.generateRandomPassphrase,\n passphrase,\n } as const;\n}\n"],"mappings":";;;;;;;AAAA,SAAS,wCAAwC;AACjD,OAAO;AAAA,EACL;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EAOA;AAAA,EAOA;AAAA,EACA;AAAA,OAEK;;;ACxBA,SAAS,oCACd,gBACA;AACA,QAAM,UAAU,eAAe,gBAAgB;AAE/C,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,MAAM,kBAAkB;AAAA,EACpC;AAEA,SAAO,QAAQ,UAAU,QAAQ,KAAK,QAAQ;AAChD;;;ADkBO,SAAS,iBAAsC;AACpD,QAAM,QAAQ,WAAW,WAAW;AAEpC,MAAI,CAAC,OAAO;AACV,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEO,SAAS,wBAA6C;AAC3D,QAAM,QAAQ,WAAW,yBAAyB;AAKlD,MAAI,CAAC,OAAO;AACV,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAEO,SAAS,uBAAuB;AACrC,QAAM,QAAQ,WAAW,yBAAyB;A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