@hexclave/js 1.0.29 → 1.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/dist/esm/lib/hexclave-app/apps/implementations/common.js +1 -1
  2. package/dist/esm/lib/hexclave-app/apps/implementations/server-app-impl.d.ts +14 -0
  3. package/dist/esm/lib/hexclave-app/apps/implementations/server-app-impl.d.ts.map +1 -1
  4. package/dist/esm/lib/hexclave-app/apps/implementations/server-app-impl.js +20 -12
  5. package/dist/esm/lib/hexclave-app/apps/implementations/server-app-impl.js.map +1 -1
  6. package/dist/esm/lib/hexclave-app/apps/implementations/session-replay.d.ts.map +1 -1
  7. package/dist/esm/lib/hexclave-app/apps/implementations/session-replay.js +8 -1
  8. package/dist/esm/lib/hexclave-app/apps/implementations/session-replay.js.map +1 -1
  9. package/dist/esm/lib/hexclave-app/apps/interfaces/server-app.d.ts +13 -0
  10. package/dist/esm/lib/hexclave-app/apps/interfaces/server-app.d.ts.map +1 -1
  11. package/dist/esm/lib/hexclave-app/apps/interfaces/server-app.js.map +1 -1
  12. package/dist/lib/hexclave-app/apps/implementations/common.js +1 -1
  13. package/dist/lib/hexclave-app/apps/implementations/server-app-impl.d.ts +14 -0
  14. package/dist/lib/hexclave-app/apps/implementations/server-app-impl.d.ts.map +1 -1
  15. package/dist/lib/hexclave-app/apps/implementations/server-app-impl.js +20 -12
  16. package/dist/lib/hexclave-app/apps/implementations/server-app-impl.js.map +1 -1
  17. package/dist/lib/hexclave-app/apps/implementations/session-replay.d.ts.map +1 -1
  18. package/dist/lib/hexclave-app/apps/implementations/session-replay.js +8 -1
  19. package/dist/lib/hexclave-app/apps/implementations/session-replay.js.map +1 -1
  20. package/dist/lib/hexclave-app/apps/interfaces/server-app.d.ts +13 -0
  21. package/dist/lib/hexclave-app/apps/interfaces/server-app.d.ts.map +1 -1
  22. package/dist/lib/hexclave-app/apps/interfaces/server-app.js.map +1 -1
  23. package/package.json +2 -2
  24. package/src/lib/hexclave-app/apps/implementations/server-app-impl.ts +24 -12
  25. package/src/lib/hexclave-app/apps/implementations/session-replay.ts +16 -1
  26. package/src/lib/hexclave-app/apps/interfaces/server-app.ts +5 -0
@@ -1 +1 @@
1
- {"version":3,"file":"server-app-impl.js","names":["_HexclaveClientAppImplIncomplete","Result","KnownErrors","HexclaveServerInterface","HexclaveAssertionError","WebAuthnError","InternalSession"],"sources":["../../../../../src/lib/hexclave-app/apps/implementations/server-app-impl.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY UNLESS YOU ALSO EDIT THE CORRESPONDING FILE IN packages/template\n//===========================================\nimport { WebAuthnError, startRegistration } from \"@simplewebauthn/browser\";\nimport { KnownErrors, HexclaveServerInterface } from \"@hexclave/shared\";\nimport { ContactChannelsCrud } from \"@hexclave/shared/dist/interface/crud/contact-channels\";\nimport { ItemCrud } from \"@hexclave/shared/dist/interface/crud/items\";\nimport { NotificationPreferenceCrud } from \"@hexclave/shared/dist/interface/crud/notification-preferences\";\nimport { OAuthProviderCrud } from \"@hexclave/shared/dist/interface/crud/oauth-providers\";\nimport type { CustomerProductsListResponse } from \"@hexclave/shared/dist/interface/crud/products\";\nimport { TeamApiKeysCrud, UserApiKeysCrud, teamApiKeysCreateOutputSchema, userApiKeysCreateOutputSchema } from \"@hexclave/shared/dist/interface/crud/project-api-keys\";\nimport { ProjectPermissionDefinitionsCrud, ProjectPermissionsCrud } from \"@hexclave/shared/dist/interface/crud/project-permissions\";\nimport { TeamInvitationCrud } from \"@hexclave/shared/dist/interface/crud/team-invitation\";\nimport { TeamMemberProfilesCrud } from \"@hexclave/shared/dist/interface/crud/team-member-profiles\";\nimport { TeamPermissionDefinitionsCrud, TeamPermissionsCrud } from \"@hexclave/shared/dist/interface/crud/team-permissions\";\nimport { TeamsCrud } from \"@hexclave/shared/dist/interface/crud/teams\";\nimport { UsersCrud } from \"@hexclave/shared/dist/interface/crud/users\";\nimport { InternalSession } from \"@hexclave/shared/dist/sessions\";\nimport type { AsyncCache } from \"@hexclave/shared/dist/utils/caches\";\nimport { HexclaveAssertionError, captureError, throwErr } from \"@hexclave/shared/dist/utils/errors\";\nimport { ProviderType } from \"@hexclave/shared/dist/utils/oauth\";\nimport { runAsynchronously } from \"@hexclave/shared/dist/utils/promises\";\nimport { suspend } from \"@hexclave/shared/dist/utils/react\";\nimport { Result } from \"@hexclave/shared/dist/utils/results\";\nimport * as yup from \"yup\";\nimport { constructRedirectUrl } from \"../../../../utils/url\";\nimport { ApiKey, ApiKeyCreationOptions, ApiKeyUpdateOptions, apiKeyCreationOptionsToCrud, apiKeyUpdateOptionsToCrud } from \"../../api-keys\";\nimport { ConvexCtx, GetCurrentUserOptions } from \"../../common\";\nimport { DeprecatedOAuthConnection, OAuthConnection } from \"../../connected-accounts\";\nimport { ServerContactChannel, ServerContactChannelCreateOptions, ServerContactChannelUpdateOptions, serverContactChannelCreateOptionsToCrud, serverContactChannelUpdateOptionsToCrud } from \"../../contact-channels\";\nimport { Customer, CustomerProductsList, CustomerProductsRequestOptions, InlineProduct, ServerItem } from \"../../customers\";\nimport { DataVaultStore } from \"../../data-vault\";\nimport { EmailDeliveryInfo, SendEmailOptions } from \"../../email\";\nimport { NotificationCategory } from \"../../notification-categories\";\nimport { AdminProjectPermissionDefinition, AdminTeamPermission, AdminTeamPermissionDefinition } from \"../../permissions\";\nimport { EditableTeamMemberProfile, ReceivedTeamInvitation, SentTeamInvitation, ServerListTeamsOptions, ServerListUsersOptions, ServerTeam, ServerTeamCreateOptions, ServerTeamUpdateOptions, ServerTeamUser, Team, serverTeamCreateOptionsToCrud, serverTeamUpdateOptionsToCrud } from \"../../teams\";\nimport { ProjectCurrentServerUser, ServerOAuthProvider, ServerUser, ServerUserCreateOptions, ServerUserUpdateOptions, serverUserCreateOptionsToCrud, serverUserUpdateOptionsToCrud, withUserDestructureGuard } from \"../../users\";\nimport { StackServerAppConstructorOptions } from \"../interfaces/server-app\";\nimport { _HexclaveClientAppImplIncomplete } from \"./client-app-impl\";\nimport { clientVersion, createCache, createCacheBySession, getDefaultExtraRequestHeaders, getDefaultProjectId, getDefaultPublishableClientKey, getDefaultSecretServerKey, resolveApiUrls, resolveConstructorOptions } from \"./common\";\n\n\nexport class _HexclaveServerAppImplIncomplete<HasTokenStore extends boolean, ProjectId extends string> extends _HexclaveClientAppImplIncomplete<HasTokenStore, ProjectId> {\n declare protected _interface: HexclaveServerInterface;\n\n // TODO override the client user cache to use the server user cache, so we save some requests\n private readonly _currentServerUserCache = createCacheBySession(async (session) => {\n if (session.isKnownToBeInvalid()) {\n // see comment in _currentUserCache for more details on why we do this\n return null;\n }\n return await this._interface.getServerUserByToken(session);\n });\n private readonly _serverUsersCache = createCache<[\n cursor?: string,\n limit?: number,\n orderBy?: 'signedUpAt' | 'lastActiveAt',\n desc?: boolean,\n query?: string,\n includeRestricted?: boolean,\n includeAnonymous?: boolean,\n onlyAnonymous?: boolean,\n teamId?: string,\n ], UsersCrud['Server']['List']>(async ([cursor, limit, orderBy, desc, query, includeRestricted, includeAnonymous, onlyAnonymous, teamId]) => {\n if (onlyAnonymous && !includeAnonymous) {\n throw new HexclaveAssertionError(\"onlyAnonymous=true requires includeAnonymous=true\");\n }\n if (onlyAnonymous) {\n return await this._interface.listServerUsers({ cursor, limit, orderBy, desc, query, includeRestricted, includeAnonymous: true, onlyAnonymous: true, teamId });\n }\n return await this._interface.listServerUsers({ cursor, limit, orderBy, desc, query, includeRestricted, includeAnonymous, teamId });\n });\n private readonly _serverUserCache = createCache<string[], UsersCrud['Server']['Read'] | null>(async ([userId]) => {\n const user = await this._interface.getServerUserById(userId);\n return Result.or(user, null);\n });\n private readonly _serverTeamsCache = createCache<[\n userId?: string,\n orderBy?: 'createdAt',\n desc?: boolean,\n cursor?: string,\n limit?: number,\n query?: string,\n ], TeamsCrud['Server']['List']>(async ([userId, orderBy, desc, cursor, limit, query]) => {\n return await this._interface.listServerTeamsPaginated({ userId, orderBy, desc, cursor, limit, query });\n });\n\n protected async _refreshTeamMembership(teamId: string, userId: string) {\n await Promise.all([\n this._serverTeamMemberProfilesCache.refresh([teamId]),\n this._serverTeamsCache.refreshWhere(([u]) => u === userId || u === undefined),\n this._serverUsersCache.refreshWhere((key) => key[8] === teamId),\n ]);\n }\n private readonly _serverUserTeamInvitationsCache = createCache<string[], TeamInvitationCrud['Client']['Read'][]>(async ([userId]) => {\n return await this._interface.listServerUserTeamInvitations(userId);\n });\n private readonly _serverTeamUserPermissionsCache = createCache<\n [string, string, boolean],\n TeamPermissionsCrud['Server']['Read'][]\n >(async ([teamId, userId, recursive]) => {\n return await this._interface.listServerTeamPermissions({ teamId, userId, recursive }, null);\n });\n // Bulk variant: one request returning permissions for every member of a\n // team. Used by the dashboard's team-member table to avoid N per-row\n // calls. Keyed without userId so it's a distinct cache entry from the\n // per-user lookup above.\n private readonly _serverAllTeamMemberPermissionsCache = createCache<\n [string, boolean],\n TeamPermissionsCrud['Server']['Read'][]\n >(async ([teamId, recursive]) => {\n return await this._interface.listServerTeamPermissions({ teamId, recursive }, null);\n });\n private readonly _serverUserProjectPermissionsCache = createCache<\n [string, boolean],\n ProjectPermissionsCrud['Server']['Read'][]\n >(async ([userId, recursive]) => {\n return await this._interface.listServerProjectPermissions({ userId, recursive }, null);\n });\n /** @deprecated Used by legacy getConnectedAccount(providerId) — uses old per-provider access token endpoint */\n private readonly _serverUserOAuthConnectionAccessTokensCache = createCache<[string, string, string], { accessToken: string } | null>(\n async ([userId, providerId, scope]) => {\n try {\n const result = await this._interface.createServerProviderAccessToken(userId, providerId, scope || \"\");\n return { accessToken: result.access_token };\n } catch (err) {\n if (!(KnownErrors.OAuthAccessTokenNotAvailable.isInstance(err) || KnownErrors.OAuthConnectionDoesNotHaveRequiredScope.isInstance(err) || KnownErrors.OAuthConnectionNotConnectedToUser.isInstance(err))) {\n throw err;\n }\n }\n return null;\n }\n );\n /** @deprecated Used by legacy getConnectedAccount(providerId) — combines token check + redirect */\n private readonly _serverUserOAuthConnectionCache = createCache<[string, ProviderType, string, boolean], DeprecatedOAuthConnection | null>(\n async ([userId, providerId, scope, redirect]) => {\n return await this._getUserOAuthConnectionCacheFn({\n getUser: async () => Result.orThrow(await this._serverUserCache.getOrWait([userId], \"write-only\")),\n getOrWaitOAuthToken: async () => Result.orThrow(await this._serverUserOAuthConnectionAccessTokensCache.getOrWait([userId, providerId, scope || \"\"] as const, \"write-only\")),\n providerId,\n scope,\n redirect,\n session: null,\n });\n }\n );\n private readonly _serverUserConnectedAccountsCache = createCache<[string], OAuthConnection[]>(\n async ([userId]) => {\n const result = await this._interface.listServerConnectedAccounts(userId);\n return result.items.map((item) => this._createServerOAuthConnectionFromCrudItem(userId, item));\n }\n );\n private readonly _serverUserOAuthConnectionAccessTokensByAccountCache = createCache<[string, string, string, string], { accessToken: string } | null>(\n async ([userId, providerId, providerAccountId, scope]) => {\n try {\n const result = await this._interface.createServerProviderAccessTokenByAccount(userId, providerId, providerAccountId, scope || \"\");\n return { accessToken: result.access_token };\n } catch (err) {\n if (!(KnownErrors.OAuthAccessTokenNotAvailable.isInstance(err) || KnownErrors.OAuthConnectionDoesNotHaveRequiredScope.isInstance(err) || KnownErrors.OAuthConnectionNotConnectedToUser.isInstance(err))) {\n throw err;\n }\n }\n return null;\n }\n );\n private readonly _serverTeamMemberProfilesCache = createCache<[string], TeamMemberProfilesCrud['Server']['Read'][]>(\n async ([teamId]) => {\n return await this._interface.listServerTeamMemberProfiles({ teamId });\n }\n );\n private readonly _serverTeamInvitationsCache = createCache<[string], TeamInvitationCrud['Server']['Read'][]>(\n async ([teamId]) => {\n return await this._interface.listServerTeamInvitations({ teamId });\n }\n );\n private readonly _serverUserTeamProfileCache = createCache<[string, string], TeamMemberProfilesCrud['Client']['Read']>(\n async ([teamId, userId]) => {\n return await this._interface.getServerTeamMemberProfile({ teamId, userId });\n }\n );\n private readonly _serverContactChannelsCache = createCache<[string], ContactChannelsCrud['Server']['Read'][]>(\n async ([userId]) => {\n return await this._interface.listServerContactChannels(userId);\n }\n );\n private readonly _serverNotificationCategoriesCache = createCache<[string], NotificationPreferenceCrud['Server']['Read'][]>(\n async ([userId]) => {\n return await this._interface.listServerNotificationCategories(userId);\n }\n );\n private readonly _serverDataVaultStoreValueCache = createCache<[string, string, string], string | null>(async ([storeId, key, secret]) => {\n return await this._interface.getDataVaultStoreValue(secret, storeId, key);\n });\n\n private readonly _emailDeliveryInfoCache = createCache(async () => {\n return await this._interface.getEmailDeliveryInfo();\n });\n\n private readonly _serverUserApiKeysCache = createCache<[string], UserApiKeysCrud['Server']['Read'][]>(\n async ([userId]) => {\n const result = await this._interface.listProjectApiKeys({\n user_id: userId,\n }, null, \"server\");\n return result as UserApiKeysCrud['Server']['Read'][];\n }\n );\n\n private readonly _serverTeamApiKeysCache = createCache<[string], TeamApiKeysCrud['Server']['Read'][]>(\n async ([teamId]) => {\n const result = await this._interface.listProjectApiKeys({\n team_id: teamId,\n }, null, \"server\");\n return result as TeamApiKeysCrud['Server']['Read'][];\n }\n );\n\n private readonly _convexIdentitySubjectCache = createCache<[ConvexCtx], string | null>(\n async ([ctx]) => {\n const identity = await ctx.auth.getUserIdentity();\n return identity ? identity.subject : null;\n }\n );\n\n private readonly _serverCheckApiKeyCache = createCache<[\"user\" | \"team\", string], UserApiKeysCrud['Server']['Read'] | TeamApiKeysCrud['Server']['Read'] | null>(async ([type, apiKey]) => {\n const result = await this._interface.checkProjectApiKey(\n type,\n apiKey,\n null,\n \"server\",\n );\n return result;\n });\n\n private readonly _serverOAuthProvidersCache = createCache<[string], OAuthProviderCrud['Server']['Read'][]>(\n async ([userId]) => {\n return await this._interface.listServerOAuthProviders({ user_id: userId });\n }\n );\n\n private readonly _serverTeamItemsCache = createCache<[string, string], ItemCrud['Client']['Read']>(\n async ([teamId, itemId]) => {\n return await this._interface.getItem({ teamId, itemId }, null, \"server\");\n }\n );\n\n private readonly _serverUserItemsCache = createCache<[string, string], ItemCrud['Client']['Read']>(\n async ([userId, itemId]) => {\n return await this._interface.getItem({ userId, itemId }, null, \"server\");\n }\n );\n\n private readonly _serverCustomItemsCache = createCache<[string, string], ItemCrud['Client']['Read']>(\n async ([customCustomerId, itemId]) => {\n return await this._interface.getItem({ customCustomerId, itemId }, null, \"server\");\n }\n );\n\n private readonly _serverUserProductsCache = createCache<[string, string | null, number | null], CustomerProductsListResponse>(\n async ([userId, cursor, limit]) => {\n return await this._interface.listProducts({\n customer_type: \"user\",\n customer_id: userId,\n cursor: cursor ?? undefined,\n limit: limit ?? undefined,\n }, null, \"server\");\n }\n );\n\n private readonly _serverTeamProductsCache = createCache<[string, string | null, number | null], CustomerProductsListResponse>(\n async ([teamId, cursor, limit]) => {\n return await this._interface.listProducts({\n customer_type: \"team\",\n customer_id: teamId,\n cursor: cursor ?? undefined,\n limit: limit ?? undefined,\n }, null, \"server\");\n }\n );\n\n private readonly _serverCustomProductsCache = createCache<[string, string | null, number | null], CustomerProductsListResponse>(\n async ([customCustomerId, cursor, limit]) => {\n return await this._interface.listProducts({\n customer_type: \"custom\",\n customer_id: customCustomerId,\n cursor: cursor ?? undefined,\n limit: limit ?? undefined,\n }, null, \"server\");\n }\n );\n\n protected _createServerCustomer(userIdOrTeamId: string, type: \"user\" | \"team\"): Omit<Customer<true>, \"id\"> {\n const app = this;\n const productsCache = type === \"user\" ? app._serverUserProductsCache : app._serverTeamProductsCache;\n const customerOptions = type === \"user\" ? { userId: userIdOrTeamId } : { teamId: userIdOrTeamId };\n return {\n ...this._createCustomer(userIdOrTeamId, type, null),\n async getItem(itemId: string) {\n return await app.getItem({ itemId, ...customerOptions });\n },\n async grantProduct(productOptions: { productId: string, quantity?: number } | { product: InlineProduct, quantity?: number }) {\n if (type === \"user\") {\n if (\"productId\" in productOptions) {\n await app.grantProduct({ userId: userIdOrTeamId, productId: productOptions.productId, quantity: productOptions.quantity });\n } else {\n await app.grantProduct({ userId: userIdOrTeamId, product: productOptions.product, quantity: productOptions.quantity });\n }\n } else {\n if (\"productId\" in productOptions) {\n await app.grantProduct({ teamId: userIdOrTeamId, productId: productOptions.productId, quantity: productOptions.quantity });\n } else {\n await app.grantProduct({ teamId: userIdOrTeamId, product: productOptions.product, quantity: productOptions.quantity });\n }\n }\n await productsCache.refresh([userIdOrTeamId, null, null]);\n },\n async createCheckoutUrl(options: { productId: string, returnUrl?: string } | { product: InlineProduct, returnUrl?: string }) {\n const productIdOrInline = \"productId\" in options ? options.productId : options.product;\n return await app._interface.createCheckoutUrl(type, userIdOrTeamId, productIdOrInline, null, options.returnUrl, \"server\");\n },\n };\n }\n\n private async _updateServerUser(userId: string, update: ServerUserUpdateOptions): Promise<UsersCrud['Server']['Read']> {\n const result = await this._interface.updateServerUser(userId, serverUserUpdateOptionsToCrud(update));\n await this._refreshUsers();\n return result;\n }\n\n protected _serverEditableTeamProfileFromCrud(crud: TeamMemberProfilesCrud['Client']['Read']): EditableTeamMemberProfile {\n const app = this;\n return {\n displayName: crud.display_name,\n profileImageUrl: crud.profile_image_url,\n async update(update: { displayName?: string, profileImageUrl?: string }) {\n await app._interface.updateServerTeamMemberProfile({\n teamId: crud.team_id,\n userId: crud.user_id,\n profile: {\n display_name: update.displayName,\n profile_image_url: update.profileImageUrl,\n },\n });\n await app._serverUserTeamProfileCache.refresh([crud.team_id, crud.user_id]);\n }\n };\n }\n\n protected _serverContactChannelFromCrud(userId: string, crud: ContactChannelsCrud['Server']['Read']): ServerContactChannel {\n const app = this;\n return {\n id: crud.id,\n value: crud.value,\n type: crud.type,\n isVerified: crud.is_verified,\n isPrimary: crud.is_primary,\n usedForAuth: crud.used_for_auth,\n async sendVerificationEmail(options?: { callbackUrl?: string }) {\n await app._interface.sendServerContactChannelVerificationEmail(userId, crud.id, options?.callbackUrl ?? constructRedirectUrl(app._getUrls().emailVerification, \"callbackUrl\"));\n },\n async update(data: ServerContactChannelUpdateOptions) {\n await app._interface.updateServerContactChannel(userId, crud.id, serverContactChannelUpdateOptionsToCrud(data));\n await Promise.all([\n app._serverContactChannelsCache.refresh([userId]),\n app._serverUserCache.refresh([userId])\n ]);\n },\n async delete() {\n await app._interface.deleteServerContactChannel(userId, crud.id);\n await Promise.all([\n app._serverContactChannelsCache.refresh([userId]),\n app._serverUserCache.refresh([userId])\n ]);\n },\n };\n }\n\n protected _serverNotificationCategoryFromCrud(userId: string, crud: NotificationPreferenceCrud['Server']['Read']): NotificationCategory {\n const app = this;\n return {\n id: crud.notification_category_id,\n name: crud.notification_category_name,\n enabled: crud.enabled,\n canDisable: crud.can_disable,\n\n async setEnabled(enabled: boolean) {\n await app._interface.setServerNotificationsEnabled(userId, crud.notification_category_id, enabled);\n await app._serverNotificationCategoriesCache.refresh([userId]);\n },\n };\n }\n\n protected _serverOAuthProviderFromCrud(crud: OAuthProviderCrud['Server']['Read']) {\n const app = this;\n return {\n id: crud.id,\n type: crud.type,\n userId: crud.user_id,\n accountId: crud.account_id,\n email: crud.email,\n allowSignIn: crud.allow_sign_in,\n allowConnectedAccounts: crud.allow_connected_accounts,\n\n async update(data: { accountId?: string, email?: string, allowSignIn?: boolean, allowConnectedAccounts?: boolean }): Promise<Result<void,\n InstanceType<typeof KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn>\n >> {\n try {\n await app._interface.updateServerOAuthProvider(crud.user_id, crud.id, {\n account_id: data.accountId,\n email: data.email,\n allow_sign_in: data.allowSignIn,\n allow_connected_accounts: data.allowConnectedAccounts,\n });\n await Promise.all([\n app._serverOAuthProvidersCache.refresh([crud.user_id]),\n app._serverUserConnectedAccountsCache.refresh([crud.user_id]),\n ]);\n return Result.ok(undefined);\n } catch (error) {\n if (KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn.isInstance(error)) {\n return Result.error(error);\n }\n throw error;\n }\n },\n\n async delete() {\n await app._interface.deleteServerOAuthProvider(crud.user_id, crud.id);\n await Promise.all([\n app._serverOAuthProvidersCache.refresh([crud.user_id]),\n app._serverUserConnectedAccountsCache.refresh([crud.user_id]),\n ]);\n },\n };\n }\n\n constructor(options: StackServerAppConstructorOptions<HasTokenStore, ProjectId>, extraOptions?: { uniqueIdentifier?: string, checkString?: string, interface?: HexclaveServerInterface }) {\n const resolvedOptions = resolveConstructorOptions(options);\n\n const publishableClientKey = resolvedOptions.publishableClientKey ?? getDefaultPublishableClientKey();\n\n super(resolvedOptions, {\n ...extraOptions,\n interface: extraOptions?.interface ?? (() => {\n const apiUrls = resolveApiUrls(resolvedOptions.baseUrl);\n return new HexclaveServerInterface({\n getBaseUrl: () => apiUrls()[0],\n getApiUrls: apiUrls,\n projectId: resolvedOptions.projectId ?? getDefaultProjectId(),\n extraRequestHeaders: resolvedOptions.extraRequestHeaders ?? getDefaultExtraRequestHeaders(),\n clientVersion,\n ...(publishableClientKey != null ? { publishableClientKey } : {}),\n secretServerKey: resolvedOptions.secretServerKey ?? getDefaultSecretServerKey(),\n });\n })(),\n });\n }\n\n\n protected _serverApiKeyFromCrud(crud: TeamApiKeysCrud['Client']['Read']): ApiKey<\"team\">;\n protected _serverApiKeyFromCrud(crud: UserApiKeysCrud['Client']['Read']): ApiKey<\"user\">;\n protected _serverApiKeyFromCrud(crud: yup.InferType<typeof teamApiKeysCreateOutputSchema>): ApiKey<\"team\", true>;\n protected _serverApiKeyFromCrud(crud: yup.InferType<typeof userApiKeysCreateOutputSchema>): ApiKey<\"user\", true>;\n protected _serverApiKeyFromCrud(crud: TeamApiKeysCrud['Client']['Read'] | UserApiKeysCrud['Client']['Read'] | yup.InferType<typeof teamApiKeysCreateOutputSchema> | yup.InferType<typeof userApiKeysCreateOutputSchema>): ApiKey<\"user\" | \"team\", boolean> {\n return {\n ...this._baseApiKeyFromCrud(crud),\n async revoke() {\n await this.update({ revoked: true });\n },\n update: async (options: ApiKeyUpdateOptions) => {\n await this._interface.updateProjectApiKey(\n crud.type === \"team\" ? { team_id: crud.team_id } : { user_id: crud.user_id },\n crud.id,\n await apiKeyUpdateOptionsToCrud(crud.type, options),\n null,\n \"server\");\n if (crud.type === \"team\") {\n await this._serverTeamApiKeysCache.refresh([crud.team_id]);\n } else {\n await this._serverUserApiKeysCache.refresh([crud.user_id]);\n }\n },\n };\n }\n\n protected _createServerOAuthConnectionFromCrudItem(\n userId: string,\n item: { provider: string, provider_account_id: string },\n ): OAuthConnection {\n const app = this;\n const providerId = item.provider;\n const providerAccountId = item.provider_account_id;\n return {\n id: providerId, // deprecated, for backward compat\n provider: providerId,\n providerAccountId,\n async getAccessToken(options?: { scopes?: string[] }) {\n const scopeString = options?.scopes?.join(\" \") ?? \"\";\n const result = Result.orThrow(await app._serverUserOAuthConnectionAccessTokensByAccountCache.getOrWait([userId, providerId, providerAccountId, scopeString], \"write-only\"));\n if (!result) {\n const scopeDetail = scopeString ? `The requested scopes [${scopeString}] are not available on the existing token.` : \"The OAuth refresh token has likely been revoked or expired.\";\n return Result.error(new KnownErrors.OAuthAccessTokenNotAvailable(providerId, `${scopeDetail} The user needs to re-authorize by calling \\`linkConnectedAccount\\` or using \\`getOrLinkConnectedAccount\\`.`));\n }\n return Result.ok(result);\n },\n };\n }\n\n protected _serverUserFromCrud(crud: UsersCrud['Server']['Read']): ServerUser {\n const app = this;\n\n /** @deprecated The string-based overloads are deprecated. Use `getConnectedAccount({ provider, providerAccountId })` for existence check. */\n async function getConnectedAccount(id: ProviderType, options?: { scopes?: string[] }): Promise<DeprecatedOAuthConnection | null>;\n async function getConnectedAccount(id: ProviderType, options: { or: 'redirect', scopes?: string[] }): Promise<DeprecatedOAuthConnection>;\n async function getConnectedAccount(account: { provider: string, providerAccountId: string }): Promise<OAuthConnection | null>;\n async function getConnectedAccount(\n idOrAccount: ProviderType | { provider: string, providerAccountId: string },\n options?: { or?: 'redirect', scopes?: string[] }\n ): Promise<DeprecatedOAuthConnection | OAuthConnection | null> {\n const scopeString = options?.scopes?.join(\" \") ?? \"\";\n\n // Check if it's the new object-based API\n if (typeof idOrAccount === 'object' && 'provider' in idOrAccount && 'providerAccountId' in idOrAccount) {\n const { provider, providerAccountId } = idOrAccount;\n // Check if the account exists in the connected accounts list\n const connectedAccounts = Result.orThrow(await app._serverUserConnectedAccountsCache.getOrWait([crud.id], \"write-only\"));\n const found = connectedAccounts.find(\n a => a.provider === provider && a.providerAccountId === providerAccountId\n );\n if (!found) {\n return null;\n }\n return found;\n }\n\n // Original behavior: by provider ID (returns first match)\n return Result.orThrow(await app._serverUserOAuthConnectionCache.getOrWait([crud.id, idOrAccount, scopeString, options?.or === 'redirect'], \"write-only\"));\n }\n\n\n // Type assertion needed because the new restricted_by_admin fields may not be reflected in TypeScript types yet\n // after schema changes - the runtime values are present after the schema is updated\n const crudWithAdminRestriction = crud as typeof crud & {\n restricted_by_admin: boolean,\n restricted_by_admin_reason: string | null,\n restricted_by_admin_private_details: string | null,\n };\n const serverUser = withUserDestructureGuard({\n ...super._createBaseUser(crud),\n lastActiveAt: new Date(crud.last_active_at_millis),\n serverMetadata: crud.server_metadata,\n restrictedByAdmin: crudWithAdminRestriction.restricted_by_admin,\n restrictedByAdminReason: crudWithAdminRestriction.restricted_by_admin_reason,\n restrictedByAdminPrivateDetails: crudWithAdminRestriction.restricted_by_admin_private_details,\n countryCode: crud.country_code,\n riskScores: {\n signUp: {\n bot: crud.risk_scores.sign_up.bot,\n freeTrialAbuse: crud.risk_scores.sign_up.free_trial_abuse,\n },\n },\n async setPrimaryEmail(email: string | null, options?: { verified?: boolean }) {\n await app._updateServerUser(crud.id, { primaryEmail: email, primaryEmailVerified: options?.verified });\n },\n async grantPermission(scopeOrPermissionId: Team | string, permissionId?: string): Promise<void> {\n if (scopeOrPermissionId && typeof scopeOrPermissionId !== 'string' && permissionId) {\n const scope = scopeOrPermissionId;\n await app._interface.grantServerTeamUserPermission(scope.id, crud.id, permissionId);\n\n for (const recursive of [true, false]) {\n await app._serverTeamUserPermissionsCache.refresh([scope.id, crud.id, recursive]);\n await app._serverAllTeamMemberPermissionsCache.refresh([scope.id, recursive]);\n }\n } else {\n const pId = scopeOrPermissionId as string;\n await app._interface.grantServerProjectPermission(crud.id, pId);\n\n for (const recursive of [true, false]) {\n await app._serverUserProjectPermissionsCache.refresh([crud.id, recursive]);\n }\n }\n },\n async revokePermission(scopeOrPermissionId: Team | string, permissionId?: string): Promise<void> {\n if (scopeOrPermissionId && typeof scopeOrPermissionId !== 'string' && permissionId) {\n const scope = scopeOrPermissionId;\n await app._interface.revokeServerTeamUserPermission(scope.id, crud.id, permissionId);\n\n for (const recursive of [true, false]) {\n await app._serverTeamUserPermissionsCache.refresh([scope.id, crud.id, recursive]);\n await app._serverAllTeamMemberPermissionsCache.refresh([scope.id, recursive]);\n }\n } else {\n const pId = scopeOrPermissionId as string;\n await app._interface.revokeServerProjectPermission(crud.id, pId);\n\n for (const recursive of [true, false]) {\n await app._serverUserProjectPermissionsCache.refresh([crud.id, recursive]);\n }\n }\n },\n async delete() {\n const res = await app._interface.deleteServerUser(crud.id);\n await app._refreshUsers();\n return res;\n },\n async createSession(options: { expiresInMillis?: number, isImpersonation?: boolean }) {\n // TODO this should also refresh the access token when it expires (like InternalSession)\n const tokens = await app._interface.createServerUserSession(crud.id, options.expiresInMillis ?? 1000 * 60 * 60 * 24 * 365, options.isImpersonation ?? false);\n return {\n async getTokens() {\n return tokens;\n },\n };\n },\n\n async getActiveSessions() {\n const sessions = await app._interface.listServerSessions(crud.id);\n return sessions.items.map((session) => app._clientSessionFromCrud(session));\n },\n\n async revokeSession(sessionId: string) {\n await app._interface.deleteServerSession(sessionId);\n },\n async setDisplayName(displayName: string | null) {\n return await this.update({ displayName });\n },\n async setClientMetadata(metadata: Record<string, any>) {\n return await this.update({ clientMetadata: metadata });\n },\n async setClientReadOnlyMetadata(metadata: Record<string, any>) {\n return await this.update({ clientReadOnlyMetadata: metadata });\n },\n async setServerMetadata(metadata: Record<string, any>) {\n return await this.update({ serverMetadata: metadata });\n },\n async setSelectedTeam(team: Team | string | null) {\n return await this.update({ selectedTeamId: typeof team === 'string' ? team : team?.id ?? null });\n },\n getConnectedAccount,\n async listConnectedAccounts() {\n return Result.orThrow(await app._serverUserConnectedAccountsCache.getOrWait([crud.id], \"write-only\"));\n },\n async linkConnectedAccount(): Promise<void> {\n throw new HexclaveAssertionError(\"linkConnectedAccount is not available for server users. OAuth flows must be initiated on the client side.\");\n },\n async getOrLinkConnectedAccount(): Promise<OAuthConnection> {\n throw new HexclaveAssertionError(\"getOrLinkConnectedAccount is not available for server users. OAuth flows must be initiated on the client side.\");\n },\n selectedTeam: crud.selected_team ? app._serverTeamFromCrud(crud.selected_team) : null,\n async getTeam(teamId: string) {\n const teams = await this.listTeams();\n return teams.find((t) => t.id === teamId) ?? null;\n },\n async listTeams(options?: ServerListTeamsOptions): Promise<ServerTeam[] & { nextCursor: string | null }> {\n const result = Result.orThrow(await app._serverTeamsCache.getOrWait([crud.id, options?.orderBy, options?.desc, options?.cursor, options?.limit, options?.query] as const, \"write-only\"));\n const teams: any = result.items.map((t) => app._serverTeamFromCrud(t));\n teams.nextCursor = result.pagination?.next_cursor ?? null;\n return teams as any;\n },\n createTeam: async (data: Omit<ServerTeamCreateOptions, \"creatorUserId\">) => {\n const team = await app._interface.createServerTeam(serverTeamCreateOptionsToCrud({\n creatorUserId: crud.id,\n ...data,\n }));\n await app._serverTeamsCache.refreshWhere(() => true);\n await app._updateServerUser(crud.id, { selectedTeamId: team.id });\n return app._serverTeamFromCrud(team);\n },\n leaveTeam: async (team: Team) => {\n await app._interface.leaveServerTeam({ teamId: team.id, userId: crud.id });\n await app._refreshTeamMembership(team.id, crud.id);\n },\n async listTeamInvitations() {\n const invitations = Result.orThrow(await app._serverUserTeamInvitationsCache.getOrWait([crud.id], \"write-only\"));\n return invitations.map((inv) => app._serverReceivedTeamInvitationFromCrud(crud.id, inv));\n },\n async listPermissions(scopeOrOptions?: Team | { recursive?: boolean }, options?: { recursive?: boolean }): Promise<AdminTeamPermission[]> {\n if (scopeOrOptions && 'id' in scopeOrOptions) {\n const scope = scopeOrOptions;\n const recursive = options?.recursive ?? true;\n const permissions = Result.orThrow(await app._serverTeamUserPermissionsCache.getOrWait([scope.id, crud.id, recursive], \"write-only\"));\n return permissions.map((crud) => app._serverPermissionFromCrud(crud));\n } else {\n const opts = scopeOrOptions;\n const recursive = opts?.recursive ?? true;\n const permissions = Result.orThrow(await app._serverUserProjectPermissionsCache.getOrWait([crud.id, recursive], \"write-only\"));\n return permissions.map((crud) => app._serverPermissionFromCrud(crud));\n }\n },\n async getPermission(scopeOrPermissionId: Team | string, permissionId?: string): Promise<AdminTeamPermission | null> {\n if (scopeOrPermissionId && typeof scopeOrPermissionId !== 'string') {\n const scope = scopeOrPermissionId;\n const permissions = await this.listPermissions(scope);\n return permissions.find((p) => p.id === permissionId) ?? null;\n } else {\n const pid = scopeOrPermissionId;\n const permissions = await this.listPermissions();\n return permissions.find((p) => p.id === pid) ?? null;\n }\n },\n async hasPermission(scopeOrPermissionId: Team | string, permissionId?: string): Promise<boolean> {\n if (scopeOrPermissionId && typeof scopeOrPermissionId !== 'string') {\n const scope = scopeOrPermissionId;\n return (await this.getPermission(scope, permissionId as string)) !== null;\n } else {\n const pid = scopeOrPermissionId;\n return (await this.getPermission(pid)) !== null;\n }\n },\n async update(update: ServerUserUpdateOptions) {\n await app._updateServerUser(crud.id, update);\n },\n async sendVerificationEmail() {\n return await app._checkFeatureSupport(\"sendVerificationEmail() on ServerUser\", {});\n },\n async updatePassword(options: { oldPassword: string, newPassword: string }) {\n const result = await app._interface.updatePassword(options);\n await app._serverUserCache.refresh([crud.id]);\n return result;\n },\n async setPassword(options: { password: string }) {\n const result = await this.update(options);\n await app._serverUserCache.refresh([crud.id]);\n return result;\n },\n async getTeamProfile(team: Team) {\n const result = Result.orThrow(await app._serverUserTeamProfileCache.getOrWait([team.id, crud.id], \"write-only\"));\n return app._serverEditableTeamProfileFromCrud(result);\n },\n async listContactChannels() {\n const result = Result.orThrow(await app._serverContactChannelsCache.getOrWait([crud.id], \"write-only\"));\n return result.map((data) => app._serverContactChannelFromCrud(crud.id, data));\n },\n createContactChannel: async (data: ServerContactChannelCreateOptions) => {\n const contactChannel = await app._interface.createServerContactChannel(serverContactChannelCreateOptionsToCrud(crud.id, data));\n await Promise.all([\n app._serverContactChannelsCache.refresh([crud.id]),\n app._serverUserCache.refresh([crud.id])\n ]);\n return app._serverContactChannelFromCrud(crud.id, contactChannel);\n },\n async listNotificationCategories() {\n const results = Result.orThrow(await app._serverNotificationCategoriesCache.getOrWait([crud.id], \"write-only\"));\n return results.map((category) => app._serverNotificationCategoryFromCrud(crud.id, category));\n },\n async listApiKeys() {\n const result = Result.orThrow(await app._serverUserApiKeysCache.getOrWait([crud.id], \"write-only\"));\n return result.map((apiKey) => app._serverApiKeyFromCrud(apiKey));\n },\n async createApiKey(options: ApiKeyCreationOptions<\"user\">) {\n const result = await app._interface.createProjectApiKey(\n await apiKeyCreationOptionsToCrud(\"user\", crud.id, options),\n null,\n \"server\",\n );\n await app._serverUserApiKeysCache.refresh([crud.id]);\n return app._serverApiKeyFromCrud(result);\n },\n\n async listOAuthProviders() {\n const results = Result.orThrow(await app._serverOAuthProvidersCache.getOrWait([crud.id], \"write-only\"));\n return results.map((oauthCrud) => app._serverOAuthProviderFromCrud(oauthCrud));\n },\n\n async getOAuthProvider(id: string) {\n const providers = await this.listOAuthProviders();\n return providers.find((p) => p.id === id) ?? null;\n },\n async registerPasskey(options?: { hostname?: string }): Promise<Result<undefined, KnownErrors[\"PasskeyRegistrationFailed\"] | KnownErrors[\"PasskeyWebAuthnError\"]>> {\n // TODO remove duplicated code between this and the function in client-app-impl.ts\n const hostname = options?.hostname || (await app._getCurrentUrl())?.hostname;\n if (!hostname) {\n throw new HexclaveAssertionError(\"hostname must be provided if the Stack App does not have a redirect method\");\n }\n\n // Use server interface to initiate passkey registration for this specific user\n const initiationResult = await app._interface.initiateServerPasskeyRegistration(crud.id);\n\n if (initiationResult.status !== \"ok\") {\n return Result.error(new KnownErrors.PasskeyRegistrationFailed(\"Failed to get initiation options for passkey registration\"));\n }\n\n const { options_json, code } = initiationResult.data;\n\n // HACK: Override the rpID to be the actual domain\n if (options_json.rp.id !== \"THIS_VALUE_WILL_BE_REPLACED.example.com\") {\n throw new HexclaveAssertionError(`Expected returned RP ID from server to equal sentinel, but found ${options_json.rp.id}`);\n }\n\n options_json.rp.id = hostname;\n\n let attResp;\n try {\n attResp = await startRegistration({ optionsJSON: options_json });\n } catch (error: any) {\n if (error instanceof WebAuthnError) {\n return Result.error(new KnownErrors.PasskeyWebAuthnError(error.message, error.name));\n } else {\n // This should never happen\n captureError(\"passkey-registration-failed\", error);\n return Result.error(new KnownErrors.PasskeyRegistrationFailed(\"Failed to start passkey registration due to unknown error\"));\n }\n }\n\n // Create a temporary session to complete the registration\n // TODO instead of creating a new session, this should just call the endpoint in a way in which it doesn't require a session\n // (currently this shows up on session history etc... not ideal)\n const { accessToken, refreshToken } = await app._interface.createServerUserSession(crud.id, 60000 * 2, false);\n const tempSession = new InternalSession({\n accessToken,\n refreshToken,\n refreshAccessTokenCallback: async () => null,\n });\n\n const registrationResult = await app._interface.registerPasskey({ credential: attResp, code }, tempSession);\n\n await app._serverUserCache.refresh([crud.id]);\n return registrationResult;\n },\n ...app._createServerCustomer(crud.id, \"user\"),\n } satisfies ServerUser);\n\n return serverUser;\n }\n\n protected _serverTeamUserFromCrud(crud: TeamMemberProfilesCrud[\"Server\"][\"Read\"]): ServerTeamUser {\n const teamUser = withUserDestructureGuard({\n ...this._serverUserFromCrud(crud.user),\n teamProfile: {\n displayName: crud.display_name,\n profileImageUrl: crud.profile_image_url,\n },\n } satisfies ServerTeamUser);\n\n return teamUser;\n }\n\n protected _serverSentTeamInvitationFromCrud(crud: TeamInvitationCrud['Server']['Read']): SentTeamInvitation {\n return {\n id: crud.id,\n recipientEmail: crud.recipient_email,\n expiresAt: new Date(crud.expires_at_millis),\n revoke: async () => {\n await this._interface.revokeServerTeamInvitation(crud.id, crud.team_id);\n await this._serverTeamInvitationsCache.refresh([crud.team_id]);\n },\n };\n }\n\n protected _serverReceivedTeamInvitationFromCrud(userId: string, crud: TeamInvitationCrud['Client']['Read']): ReceivedTeamInvitation {\n const app = this;\n return {\n id: crud.id,\n teamId: crud.team_id,\n teamDisplayName: crud.team_display_name,\n recipientEmail: crud.recipient_email,\n expiresAt: new Date(crud.expires_at_millis),\n accept: async () => {\n await app._interface.acceptServerTeamInvitationById(crud.id, userId);\n await Promise.all([\n app._serverUserTeamInvitationsCache.refresh([userId]),\n app._serverTeamInvitationsCache.refresh([crud.team_id]),\n app._refreshTeamMembership(crud.team_id, userId),\n ]);\n },\n };\n }\n\n protected override _currentUserFromCrud(crud: UsersCrud['Server']['Read'], session: InternalSession): ProjectCurrentServerUser<ProjectId> {\n const currentUser = withUserDestructureGuard({\n ...this._serverUserFromCrud(crud),\n ...this._createAuth(session),\n ...this._isInternalProject() ? this._createInternalUserExtra(session) : {},\n } satisfies ServerUser);\n\n return currentUser as ProjectCurrentServerUser<ProjectId>;\n }\n\n protected _serverTeamFromCrud(crud: TeamsCrud['Server']['Read']): ServerTeam {\n const app = this;\n return {\n id: crud.id,\n displayName: crud.display_name,\n profileImageUrl: crud.profile_image_url,\n createdAt: new Date(crud.created_at_millis),\n clientMetadata: crud.client_metadata,\n clientReadOnlyMetadata: crud.client_read_only_metadata,\n serverMetadata: crud.server_metadata,\n async update(update: Partial<ServerTeamUpdateOptions>) {\n await app._interface.updateServerTeam(crud.id, serverTeamUpdateOptionsToCrud(update));\n await Promise.all([\n app._serverTeamsCache.refreshWhere(() => true),\n app._serverUsersCache.refreshWhere(() => true),\n ]);\n },\n async delete() {\n await app._interface.deleteServerTeam(crud.id);\n await Promise.all([\n app._serverTeamsCache.refreshWhere(() => true),\n app._serverUsersCache.refreshWhere(() => true),\n ]);\n },\n async listUsers() {\n const result = Result.orThrow(await app._serverTeamMemberProfilesCache.getOrWait([crud.id], \"write-only\"));\n return result.map(u => app._serverTeamUserFromCrud(u));\n },\n async addUser(userId) {\n await app._interface.addServerUserToTeam({\n teamId: crud.id,\n userId,\n });\n await app._refreshTeamMembership(crud.id, userId);\n },\n async removeUser(userId) {\n await app._interface.removeServerUserFromTeam({\n teamId: crud.id,\n userId,\n });\n await app._refreshTeamMembership(crud.id, userId);\n },\n async inviteUser(options: { email: string, callbackUrl?: string }) {\n await app._interface.sendServerTeamInvitation({\n teamId: crud.id,\n email: options.email,\n callbackUrl: options.callbackUrl ?? constructRedirectUrl(app._getUrls().teamInvitation, \"callbackUrl\"),\n });\n await app._serverTeamInvitationsCache.refresh([crud.id]);\n },\n async listInvitations() {\n const result = Result.orThrow(await app._serverTeamInvitationsCache.getOrWait([crud.id], \"write-only\"));\n return result.map((crud) => app._serverSentTeamInvitationFromCrud(crud));\n },\n async listApiKeys() {\n const result = Result.orThrow(await app._serverTeamApiKeysCache.getOrWait([crud.id], \"write-only\"));\n return result.map((apiKey) => app._serverApiKeyFromCrud(apiKey));\n },\n async createApiKey(options: ApiKeyCreationOptions<\"team\">) {\n const result = await app._interface.createProjectApiKey(\n await apiKeyCreationOptionsToCrud(\"team\", crud.id, options),\n null,\n \"server\",\n );\n await app._serverTeamApiKeysCache.refresh([crud.id]);\n return app._serverApiKeyFromCrud(result);\n },\n ...app._createServerCustomer(crud.id, \"team\"),\n };\n }\n\n protected _serverItemFromCrud(customer: { type: \"user\" | \"team\" | \"custom\", id: string }, crud: ItemCrud['Client']['Read']): ServerItem {\n const app = this;\n return {\n displayName: crud.display_name,\n quantity: crud.quantity,\n nonNegativeQuantity: Math.max(0, crud.quantity),\n increaseQuantity: async (delta: number) => {\n const updateOptions = customer.type === \"user\"\n ? { itemId: crud.id, userId: customer.id }\n : customer.type === \"team\"\n ? { itemId: crud.id, teamId: customer.id }\n : { itemId: crud.id, customCustomerId: customer.id };\n await app._interface.updateItemQuantity(updateOptions, { delta });\n if (customer.type === \"user\") await app._serverUserItemsCache.refresh([customer.id, crud.id]);\n else if (customer.type === \"team\") await app._serverTeamItemsCache.refresh([customer.id, crud.id]);\n else await app._serverCustomItemsCache.refresh([customer.id, crud.id]);\n },\n decreaseQuantity: async (delta: number) => {\n const updateOptions = customer.type === \"user\"\n ? { itemId: crud.id, userId: customer.id }\n : customer.type === \"team\"\n ? { itemId: crud.id, teamId: customer.id }\n : { itemId: crud.id, customCustomerId: customer.id };\n await app._interface.updateItemQuantity(updateOptions, { delta: -delta, allow_negative: true });\n if (customer.type === \"user\") await app._serverUserItemsCache.refresh([customer.id, crud.id]);\n else if (customer.type === \"team\") await app._serverTeamItemsCache.refresh([customer.id, crud.id]);\n else await app._serverCustomItemsCache.refresh([customer.id, crud.id]);\n },\n tryDecreaseQuantity: async (delta: number) => {\n try {\n const updateOptions = customer.type === \"user\"\n ? { itemId: crud.id, userId: customer.id }\n : customer.type === \"team\"\n ? { itemId: crud.id, teamId: customer.id }\n : { itemId: crud.id, customCustomerId: customer.id };\n await app._interface.updateItemQuantity(updateOptions, { delta: -delta });\n if (customer.type === \"user\") await app._serverUserItemsCache.refresh([customer.id, crud.id]);\n else if (customer.type === \"team\") await app._serverTeamItemsCache.refresh([customer.id, crud.id]);\n else await app._serverCustomItemsCache.refresh([customer.id, crud.id]);\n return true;\n } catch (error) {\n if (error instanceof KnownErrors.ItemQuantityInsufficientAmount) {\n return false;\n }\n throw error;\n }\n },\n };\n }\n\n protected async _getUserApiKey(options: { apiKey: string }): Promise<ApiKey<\"user\"> | null> {\n const crud = Result.orThrow(await this._serverCheckApiKeyCache.getOrWait([\"user\", options.apiKey], \"write-only\")) as UserApiKeysCrud['Server']['Read'] | null;\n return crud ? this._serverApiKeyFromCrud(crud) : null;\n }\n\n protected async _getTeamApiKey(options: { apiKey: string }): Promise<ApiKey<\"team\"> | null> {\n const crud = Result.orThrow(await this._serverCheckApiKeyCache.getOrWait([\"team\", options.apiKey], \"write-only\")) as TeamApiKeysCrud['Server']['Read'] | null;\n return crud ? this._serverApiKeyFromCrud(crud) : null;\n }\n protected async _getUserByApiKey(apiKey: string): Promise<ServerUser | null> {\n const apiKeyObject = await this._getUserApiKey({ apiKey });\n if (apiKeyObject === null) {\n return null;\n }\n return await this.getServerUserById(apiKeyObject.userId);\n }\n\n protected async _getUserByConvex(ctx: ConvexCtx, includeAnonymous: boolean): Promise<ServerUser | null> {\n const identity = await ctx.auth.getUserIdentity();\n if (identity === null) {\n return null;\n }\n const user = await this.getServerUserById(identity.subject);\n if (user?.isAnonymous && !includeAnonymous) {\n return null;\n }\n return user;\n }\n\n protected async _getTeamByApiKey(apiKey: string): Promise<ServerTeam | null> {\n const apiKeyObject = await this._getTeamApiKey({ apiKey });\n if (apiKeyObject === null) {\n return null;\n }\n return await this.getTeam(apiKeyObject.teamId);\n }\n\n async createUser(options: ServerUserCreateOptions): Promise<ServerUser> {\n const crud = await this._interface.createServerUser(serverUserCreateOptionsToCrud(options));\n await this._refreshUsers();\n return this._serverUserFromCrud(crud);\n }\n\n async getUser(options: GetCurrentUserOptions<HasTokenStore> & { or: 'redirect' }): Promise<ProjectCurrentServerUser<ProjectId>>;\n async getUser(options: GetCurrentUserOptions<HasTokenStore> & { or: 'throw' }): Promise<ProjectCurrentServerUser<ProjectId>>;\n async getUser(options: GetCurrentUserOptions<HasTokenStore> & { or: 'anonymous' }): Promise<ProjectCurrentServerUser<ProjectId>>;\n async getUser(options?: GetCurrentUserOptions<HasTokenStore>): Promise<ProjectCurrentServerUser<ProjectId> | null>;\n async getUser(id: string): Promise<ServerUser | null>;\n async getUser(options: { apiKey: string }): Promise<ServerUser | null>;\n async getUser(options: { from: \"convex\", ctx: ConvexCtx, or?: \"return-null\" | \"anonymous\" }): Promise<ServerUser | null>;\n async getUser(options?: string | GetCurrentUserOptions<HasTokenStore> | { apiKey: string } | { from: \"convex\", ctx: ConvexCtx }): Promise<ProjectCurrentServerUser<ProjectId> | ServerUser | null> {\n if (typeof options === \"string\") {\n return await this.getServerUserById(options);\n } else if (typeof options === \"object\" && \"apiKey\" in options) {\n return await this._getUserByApiKey(options.apiKey);\n } else if (typeof options === \"object\" && \"from\" in options && options.from as string === \"convex\") {\n return await this._getUserByConvex(options.ctx, \"or\" in options && options.or === \"anonymous\");\n } else {\n options = options as GetCurrentUserOptions<HasTokenStore> | undefined;\n\n // Validate that includeRestricted: false and or: 'anonymous' are mutually exclusive\n if (options?.or === 'anonymous' && options.includeRestricted === false) {\n throw new Error(\"Cannot use { or: 'anonymous' } with { includeRestricted: false }. Anonymous users implicitly include restricted users.\");\n }\n\n // TODO this code is duplicated from the client app; fix that\n this._ensurePersistentTokenStore(options?.tokenStore);\n const session = await this._getSession(options?.tokenStore);\n let crud = Result.orThrow(await this._currentServerUserCache.getOrWait([session], \"write-only\"));\n const includeAnonymous = options?.or === \"anonymous\" || options?.or === \"anonymous-if-exists[deprecated]\";\n const includeRestricted = options?.includeRestricted === true || includeAnonymous;\n\n if (crud === null || (crud.is_anonymous && !includeAnonymous) || (crud.is_restricted && !includeRestricted)) {\n switch (options?.or) {\n case 'redirect': {\n if (!crud?.is_anonymous && crud?.is_restricted) {\n await this.redirectToOnboarding({ replace: true });\n } else {\n await this.redirectToSignIn({ replace: true });\n }\n // TODO: see client-app-impl. We probably want to `await neverResolve()` here instead of returning null\n break;\n }\n case 'throw': {\n throw new Error(\"User is not signed in but getUser was called with { or: 'throw' }\");\n }\n case 'anonymous': {\n const tokens = await this._signUpAnonymously();\n return await this.getUser({ tokenStore: tokens, or: \"anonymous-if-exists[deprecated]\", includeRestricted: true }) ?? throwErr(\"Something went wrong while signing up anonymously\");\n }\n case undefined:\n case \"anonymous-if-exists[deprecated]\":\n case \"return-null\": {\n return null;\n }\n }\n }\n\n return crud && this._currentUserFromCrud(crud, session);\n }\n }\n\n async getServerUser(): Promise<ProjectCurrentServerUser<ProjectId> | null> {\n console.warn(\"hexclaveServerApp.getServerUser is deprecated; use hexclaveServerApp.getUser instead\");\n return await this.getUser();\n }\n\n async getServerUserById(userId: string): Promise<ServerUser | null> {\n const crud = Result.orThrow(await this._serverUserCache.getOrWait([userId], \"write-only\"));\n return crud && this._serverUserFromCrud(crud);\n }\n\n\n async listUsers(options?: ServerListUsersOptions): Promise<ServerUser[] & { nextCursor: string | null }> {\n const crud = Result.orThrow(await this._serverUsersCache.getOrWait([options?.cursor, options?.limit, options?.orderBy, options?.desc, options?.query, options?.includeRestricted, options?.includeAnonymous, options?.onlyAnonymous, options?.teamId], \"write-only\"));\n const result: any = crud.items.map((j) => this._serverUserFromCrud(j));\n result.nextCursor = crud.pagination?.next_cursor ?? null;\n return result as any;\n }\n\n\n _serverPermissionFromCrud(crud: TeamPermissionsCrud['Server']['Read'] | ProjectPermissionsCrud['Server']['Read']): AdminTeamPermission {\n return {\n id: crud.id,\n };\n }\n\n _serverTeamPermissionDefinitionFromCrud(crud: TeamPermissionDefinitionsCrud['Admin']['Read']): AdminTeamPermissionDefinition {\n return {\n id: crud.id,\n description: crud.description,\n containedPermissionIds: crud.contained_permission_ids,\n };\n }\n\n _serverProjectPermissionDefinitionFromCrud(crud: ProjectPermissionDefinitionsCrud['Admin']['Read']): AdminProjectPermissionDefinition {\n return {\n id: crud.id,\n description: crud.description,\n containedPermissionIds: crud.contained_permission_ids,\n };\n }\n\n async getItem(options: { itemId: string, userId: string } | { itemId: string, teamId: string } | { itemId: string, customCustomerId: string }): Promise<ServerItem> {\n if (\"userId\" in options) {\n const result = Result.orThrow(await this._serverUserItemsCache.getOrWait([options.userId, options.itemId], \"write-only\"));\n return this._serverItemFromCrud({ type: \"user\", id: options.userId }, result);\n } else if (\"teamId\" in options) {\n const result = Result.orThrow(await this._serverTeamItemsCache.getOrWait([options.teamId, options.itemId], \"write-only\"));\n return this._serverItemFromCrud({ type: \"team\", id: options.teamId }, result);\n } else {\n const result = Result.orThrow(await this._serverCustomItemsCache.getOrWait([options.customCustomerId, options.itemId], \"write-only\"));\n return this._serverItemFromCrud({ type: \"custom\", id: options.customCustomerId }, result);\n }\n }\n\n async listProducts(options: CustomerProductsRequestOptions): Promise<CustomerProductsList> {\n if (\"userId\" in options) {\n const response = Result.orThrow(await this._serverUserProductsCache.getOrWait([options.userId, options.cursor ?? null, options.limit ?? null], \"write-only\"));\n return this._customerProductsFromResponse(response);\n } else if (\"teamId\" in options) {\n const response = Result.orThrow(await this._serverTeamProductsCache.getOrWait([options.teamId, options.cursor ?? null, options.limit ?? null], \"write-only\"));\n return this._customerProductsFromResponse(response);\n }\n const response = Result.orThrow(await this._serverCustomProductsCache.getOrWait([options.customCustomerId, options.cursor ?? null, options.limit ?? null], \"write-only\"));\n return this._customerProductsFromResponse(response);\n }\n\n async grantProduct(options: (\n ({ userId: string } | { teamId: string } | { customCustomerId: string }) &\n ({ productId: string } | { product: InlineProduct }) &\n { quantity?: number }\n )): Promise<void> {\n let customerType: \"user\" | \"team\" | \"custom\";\n let customerId: string;\n if (\"userId\" in options) {\n customerType = \"user\";\n customerId = options.userId;\n } else if (\"teamId\" in options) {\n customerType = \"team\";\n customerId = options.teamId;\n } else {\n customerType = \"custom\";\n customerId = options.customCustomerId;\n }\n\n await this._interface.grantProduct({\n customerType,\n customerId,\n productId: \"productId\" in options ? options.productId : undefined,\n product: \"product\" in options ? options.product : undefined,\n quantity: options.quantity,\n });\n\n const cache = customerType === \"user\"\n ? this._serverUserProductsCache\n : customerType === \"team\"\n ? this._serverTeamProductsCache\n : this._serverCustomProductsCache;\n await cache.refresh([customerId, null, null]);\n }\n\n async createTeam(data: ServerTeamCreateOptions): Promise<ServerTeam> {\n const team = await this._interface.createServerTeam(serverTeamCreateOptionsToCrud(data));\n await this._serverTeamsCache.refreshWhere(() => true);\n return this._serverTeamFromCrud(team);\n }\n\n async listTeams(options?: ServerListTeamsOptions): Promise<ServerTeam[] & { nextCursor: string | null }> {\n const crud = Result.orThrow(await this._serverTeamsCache.getOrWait([undefined, options?.orderBy, options?.desc, options?.cursor, options?.limit, options?.query] as const, \"write-only\"));\n const teams: any = crud.items.map((t) => this._serverTeamFromCrud(t));\n teams.nextCursor = crud.pagination?.next_cursor ?? null;\n return teams as any;\n }\n\n\n async listTeamMemberPermissions(teamId: string, options?: { recursive?: boolean }): Promise<{ userId: string, permissionId: string }[]> {\n const recursive = options?.recursive ?? false;\n const rows = Result.orThrow(await this._serverAllTeamMemberPermissionsCache.getOrWait([teamId, recursive] as const, \"write-only\"));\n return rows.map((r) => ({ userId: r.user_id, permissionId: r.id }));\n }\n\n\n async getTeam(options: { apiKey: string }): Promise<ServerTeam | null>;\n async getTeam(teamId: string): Promise<ServerTeam | null>;\n async getTeam(options?: { apiKey: string } | string): Promise<ServerTeam | null> {\n if (typeof options === \"object\" && \"apiKey\" in options) {\n return await this._getTeamByApiKey(options.apiKey);\n } else {\n const teamId = options;\n const teams = await this.listTeams();\n return teams.find((t) => t.id === teamId) ?? null;\n }\n }\n\n\n protected _createServerDataVaultStore(id: string): DataVaultStore {\n const validateOptions = (options: { secret: string }) => {\n if (typeof options.secret !== \"string\") throw new Error(\"secret must be a string, got \" + typeof options.secret);\n };\n return {\n id,\n setValue: async (key, value, options) => {\n validateOptions(options);\n await this._interface.setDataVaultStoreValue(options.secret, id, key, value);\n },\n getValue: async (key, options) => {\n validateOptions(options);\n return Result.orThrow(await this._serverDataVaultStoreValueCache.getOrWait([id, key, options.secret], \"write-only\"));\n },\n };\n }\n\n async getDataVaultStore(id: string): Promise<DataVaultStore> {\n return this._createServerDataVaultStore(id);\n }\n\n\n async sendEmail(options: SendEmailOptions): Promise<void> {\n await this._interface.sendEmail(options);\n await this._emailDeliveryInfoCache.refresh([]);\n }\n\n async getEmailDeliveryStats(): Promise<EmailDeliveryInfo> {\n return Result.orThrow(await this._emailDeliveryInfoCache.getOrWait([], \"write-only\"));\n }\n\n\n async activateEmailCapacityBoost(): Promise<void> {\n await this._interface.activateEmailCapacityBoost();\n // Refresh the cache so UI updates immediately\n await this._emailDeliveryInfoCache.refresh([]);\n }\n\n protected override async _refreshSession(session: InternalSession) {\n await Promise.all([\n super._refreshUser(session),\n this._currentServerUserCache.refresh([session]),\n ]);\n }\n\n protected override async _refreshUsers() {\n await Promise.all([\n super._refreshUsers(),\n this._serverUserCache.refreshWhere(() => true),\n this._serverUsersCache.refreshWhere(() => true),\n this._serverContactChannelsCache.refreshWhere(() => true),\n this._serverOAuthProvidersCache.refreshWhere(() => true),\n this._serverUserConnectedAccountsCache.refreshWhere(() => true),\n ]);\n }\n\n async createOAuthProvider(options: {\n userId: string,\n providerConfigId: string,\n accountId: string,\n email: string,\n allowSignIn: boolean,\n allowConnectedAccounts: boolean,\n }): Promise<Result<ServerOAuthProvider, InstanceType<typeof KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn>>> {\n try {\n const crud = await this._interface.createServerOAuthProvider({\n user_id: options.userId,\n provider_config_id: options.providerConfigId,\n account_id: options.accountId,\n email: options.email,\n allow_sign_in: options.allowSignIn,\n allow_connected_accounts: options.allowConnectedAccounts,\n });\n\n await Promise.all([\n this._serverOAuthProvidersCache.refresh([options.userId]),\n this._serverUserConnectedAccountsCache.refresh([options.userId]),\n ]);\n return Result.ok(this._serverOAuthProviderFromCrud(crud));\n } catch (error) {\n if (KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn.isInstance(error)) {\n return Result.error(error);\n }\n throw error;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2CA,IAAa,mCAAb,cAA+GA,sDAA2D;CA6CxK,MAAgB,uBAAuB,QAAgB,QAAgB;AACrE,QAAM,QAAQ,IAAI;GAChB,KAAK,+BAA+B,QAAQ,CAAC,OAAO,CAAC;GACrD,KAAK,kBAAkB,cAAc,CAAC,OAAO,MAAM,UAAU,MAAM,OAAU;GAC7E,KAAK,kBAAkB,cAAc,QAAQ,IAAI,OAAO,OAAO;GAChE,CAAC;;CAsMJ,AAAU,sBAAsB,gBAAwB,MAAmD;EACzG,MAAM,MAAM;EACZ,MAAM,gBAAgB,SAAS,SAAS,IAAI,2BAA2B,IAAI;EAC3E,MAAM,kBAAkB,SAAS,SAAS,EAAE,QAAQ,gBAAgB,GAAG,EAAE,QAAQ,gBAAgB;AACjG,SAAO;GACL,GAAG,KAAK,gBAAgB,gBAAgB,MAAM,KAAK;GACnD,MAAM,QAAQ,QAAgB;AAC5B,W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,EAC3B,KAAK,wBAAwB,QAAQ,CAAC,QAAQ,CAAC,CAChD,CAAC;;CAGJ,MAAyB,gBAAgB;AACvC,QAAM,QAAQ,IAAI;GAChB,MAAM,eAAe;GACrB,KAAK,iBAAiB,mBAAmB,KAAK;GAC9C,KAAK,kBAAkB,mBAAmB,KAAK;GAC/C,KAAK,4BAA4B,mBAAmB,KAAK;GACzD,KAAK,2BAA2B,mBAAmB,KAAK;GACxD,KAAK,kCAAkC,mBAAmB,KAAK;GAChE,CAAC;;CAGJ,MAAM,oBAAoB,SAO4F;AACpH,MAAI;GACF,MAAM,OAAO,MAAM,KAAK,WAAW,0BAA0B;IAC3D,SAAS,QAAQ;IACjB,oBAAoB,QAAQ;IAC5B,YAAY,QAAQ;IACpB,OAAO,QAAQ;IACf,eAAe,QAAQ;IACvB,0BAA0B,QAAQ;IACnC,CAAC;AAEF,SAAM,QAAQ,IAAI,CAChB,KAAK,2BAA2B,QAAQ,CAAC,QAAQ,OAAO,CAAC,EACzD,KAAK,kCAAkC,QAAQ,CAAC,QAAQ,OAAO,CAAC,CACjE,CAAC;AACF,UAAOA,2CAAO,GAAG,KAAK,6BAA6B,KAAK,CAAC;WAClD,OAAO;AACd,OAAIC,6BAAY,2CAA2C,WAAW,MAAM,CAC1E,QAAOD,2CAAO,MAAM,MAAM;AAE5B,SAAM"}
1
+ {"version":3,"file":"server-app-impl.js","names":["_HexclaveClientAppImplIncomplete","Result","KnownErrors","HexclaveServerInterface","HexclaveAssertionError","WebAuthnError","InternalSession"],"sources":["../../../../../src/lib/hexclave-app/apps/implementations/server-app-impl.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY UNLESS YOU ALSO EDIT THE CORRESPONDING FILE IN packages/template\n//===========================================\nimport { WebAuthnError, startRegistration } from \"@simplewebauthn/browser\";\nimport { KnownErrors, HexclaveServerInterface } from \"@hexclave/shared\";\nimport { ContactChannelsCrud } from \"@hexclave/shared/dist/interface/crud/contact-channels\";\nimport { ItemCrud } from \"@hexclave/shared/dist/interface/crud/items\";\nimport { NotificationPreferenceCrud } from \"@hexclave/shared/dist/interface/crud/notification-preferences\";\nimport { OAuthProviderCrud } from \"@hexclave/shared/dist/interface/crud/oauth-providers\";\nimport type { CustomerProductsListResponse } from \"@hexclave/shared/dist/interface/crud/products\";\nimport { TeamApiKeysCrud, UserApiKeysCrud, teamApiKeysCreateOutputSchema, userApiKeysCreateOutputSchema } from \"@hexclave/shared/dist/interface/crud/project-api-keys\";\nimport { ProjectPermissionDefinitionsCrud, ProjectPermissionsCrud } from \"@hexclave/shared/dist/interface/crud/project-permissions\";\nimport { TeamInvitationCrud } from \"@hexclave/shared/dist/interface/crud/team-invitation\";\nimport { TeamMemberProfilesCrud } from \"@hexclave/shared/dist/interface/crud/team-member-profiles\";\nimport { TeamPermissionDefinitionsCrud, TeamPermissionsCrud } from \"@hexclave/shared/dist/interface/crud/team-permissions\";\nimport { TeamsCrud } from \"@hexclave/shared/dist/interface/crud/teams\";\nimport { UsersCrud } from \"@hexclave/shared/dist/interface/crud/users\";\nimport { InternalSession } from \"@hexclave/shared/dist/sessions\";\nimport type { AsyncCache } from \"@hexclave/shared/dist/utils/caches\";\nimport { HexclaveAssertionError, captureError, throwErr } from \"@hexclave/shared/dist/utils/errors\";\nimport { ProviderType } from \"@hexclave/shared/dist/utils/oauth\";\nimport { runAsynchronously } from \"@hexclave/shared/dist/utils/promises\";\nimport { suspend } from \"@hexclave/shared/dist/utils/react\";\nimport { Result } from \"@hexclave/shared/dist/utils/results\";\nimport * as yup from \"yup\";\nimport { constructRedirectUrl } from \"../../../../utils/url\";\nimport { ApiKey, ApiKeyCreationOptions, ApiKeyUpdateOptions, apiKeyCreationOptionsToCrud, apiKeyUpdateOptionsToCrud } from \"../../api-keys\";\nimport { ConvexCtx, GetCurrentUserOptions } from \"../../common\";\nimport { DeprecatedOAuthConnection, OAuthConnection } from \"../../connected-accounts\";\nimport { ServerContactChannel, ServerContactChannelCreateOptions, ServerContactChannelUpdateOptions, serverContactChannelCreateOptionsToCrud, serverContactChannelUpdateOptionsToCrud } from \"../../contact-channels\";\nimport { Customer, CustomerProductsList, CustomerProductsRequestOptions, InlineProduct, ServerItem } from \"../../customers\";\nimport { DataVaultStore } from \"../../data-vault\";\nimport { EmailDeliveryInfo, SendEmailOptions } from \"../../email\";\nimport { NotificationCategory } from \"../../notification-categories\";\nimport { AdminProjectPermissionDefinition, AdminTeamPermission, AdminTeamPermissionDefinition } from \"../../permissions\";\nimport { EditableTeamMemberProfile, ReceivedTeamInvitation, SentTeamInvitation, ServerListTeamsOptions, ServerListUsersOptions, ServerTeam, ServerTeamCreateOptions, ServerTeamUpdateOptions, ServerTeamUser, Team, serverTeamCreateOptionsToCrud, serverTeamUpdateOptionsToCrud } from \"../../teams\";\nimport { ProjectCurrentServerUser, ServerOAuthProvider, ServerUser, ServerUserCreateOptions, ServerUserUpdateOptions, serverUserCreateOptionsToCrud, serverUserUpdateOptionsToCrud, withUserDestructureGuard } from \"../../users\";\nimport { StackServerAppConstructorOptions } from \"../interfaces/server-app\";\nimport { _HexclaveClientAppImplIncomplete } from \"./client-app-impl\";\nimport { clientVersion, createCache, createCacheBySession, getDefaultExtraRequestHeaders, getDefaultProjectId, getDefaultPublishableClientKey, getDefaultSecretServerKey, resolveApiUrls, resolveConstructorOptions } from \"./common\";\n\n\nexport class _HexclaveServerAppImplIncomplete<HasTokenStore extends boolean, ProjectId extends string> extends _HexclaveClientAppImplIncomplete<HasTokenStore, ProjectId> {\n declare protected _interface: HexclaveServerInterface;\n\n // TODO override the client user cache to use the server user cache, so we save some requests\n private readonly _currentServerUserCache = createCacheBySession(async (session) => {\n if (session.isKnownToBeInvalid()) {\n // see comment in _currentUserCache for more details on why we do this\n return null;\n }\n return await this._interface.getServerUserByToken(session);\n });\n private readonly _serverUsersCache = createCache<[\n cursor?: string,\n limit?: number,\n orderBy?: 'signedUpAt' | 'lastActiveAt',\n desc?: boolean,\n query?: string,\n includeRestricted?: boolean,\n includeAnonymous?: boolean,\n onlyAnonymous?: boolean,\n teamId?: string,\n ], UsersCrud['Server']['List']>(async ([cursor, limit, orderBy, desc, query, includeRestricted, includeAnonymous, onlyAnonymous, teamId]) => {\n if (onlyAnonymous && !includeAnonymous) {\n throw new HexclaveAssertionError(\"onlyAnonymous=true requires includeAnonymous=true\");\n }\n if (onlyAnonymous) {\n return await this._interface.listServerUsers({ cursor, limit, orderBy, desc, query, includeRestricted, includeAnonymous: true, onlyAnonymous: true, teamId });\n }\n return await this._interface.listServerUsers({ cursor, limit, orderBy, desc, query, includeRestricted, includeAnonymous, teamId });\n });\n private readonly _serverUserCache = createCache<string[], UsersCrud['Server']['Read'] | null>(async ([userId]) => {\n const user = await this._interface.getServerUserById(userId);\n return Result.or(user, null);\n });\n private readonly _serverTeamsCache = createCache<[\n userId?: string,\n orderBy?: 'createdAt',\n desc?: boolean,\n cursor?: string,\n limit?: number,\n query?: string,\n ], TeamsCrud['Server']['List']>(async ([userId, orderBy, desc, cursor, limit, query]) => {\n return await this._interface.listServerTeamsPaginated({ userId, orderBy, desc, cursor, limit, query });\n });\n\n protected async _refreshTeamMembership(teamId: string, userId: string) {\n await Promise.all([\n this._serverTeamMemberProfilesCache.refresh([teamId]),\n this._serverTeamsCache.refreshWhere(([u]) => u === userId || u === undefined),\n this._serverUsersCache.refreshWhere((key) => key[8] === teamId),\n ]);\n }\n private readonly _serverUserTeamInvitationsCache = createCache<string[], TeamInvitationCrud['Client']['Read'][]>(async ([userId]) => {\n return await this._interface.listServerUserTeamInvitations(userId);\n });\n private readonly _serverTeamUserPermissionsCache = createCache<\n [string, string, boolean],\n TeamPermissionsCrud['Server']['Read'][]\n >(async ([teamId, userId, recursive]) => {\n return await this._interface.listServerTeamPermissions({ teamId, userId, recursive }, null);\n });\n // Bulk variant: one request returning permissions for every member of a\n // team. Used by the dashboard's team-member table to avoid N per-row\n // calls. Keyed without userId so it's a distinct cache entry from the\n // per-user lookup above.\n private readonly _serverAllTeamMemberPermissionsCache = createCache<\n [string, boolean],\n TeamPermissionsCrud['Server']['Read'][]\n >(async ([teamId, recursive]) => {\n return await this._interface.listServerTeamPermissions({ teamId, recursive }, null);\n });\n private readonly _serverUserProjectPermissionsCache = createCache<\n [string, boolean],\n ProjectPermissionsCrud['Server']['Read'][]\n >(async ([userId, recursive]) => {\n return await this._interface.listServerProjectPermissions({ userId, recursive }, null);\n });\n /** @deprecated Used by legacy getConnectedAccount(providerId) — uses old per-provider access token endpoint */\n private readonly _serverUserOAuthConnectionAccessTokensCache = createCache<[string, string, string], { accessToken: string } | null>(\n async ([userId, providerId, scope]) => {\n try {\n const result = await this._interface.createServerProviderAccessToken(userId, providerId, scope || \"\");\n return { accessToken: result.access_token };\n } catch (err) {\n if (!(KnownErrors.OAuthAccessTokenNotAvailable.isInstance(err) || KnownErrors.OAuthConnectionDoesNotHaveRequiredScope.isInstance(err) || KnownErrors.OAuthConnectionNotConnectedToUser.isInstance(err))) {\n throw err;\n }\n }\n return null;\n }\n );\n /** @deprecated Used by legacy getConnectedAccount(providerId) — combines token check + redirect */\n private readonly _serverUserOAuthConnectionCache = createCache<[string, ProviderType, string, boolean], DeprecatedOAuthConnection | null>(\n async ([userId, providerId, scope, redirect]) => {\n return await this._getUserOAuthConnectionCacheFn({\n getUser: async () => Result.orThrow(await this._serverUserCache.getOrWait([userId], \"write-only\")),\n getOrWaitOAuthToken: async () => Result.orThrow(await this._serverUserOAuthConnectionAccessTokensCache.getOrWait([userId, providerId, scope || \"\"] as const, \"write-only\")),\n providerId,\n scope,\n redirect,\n session: null,\n });\n }\n );\n private readonly _serverUserConnectedAccountsCache = createCache<[string], OAuthConnection[]>(\n async ([userId]) => {\n const result = await this._interface.listServerConnectedAccounts(userId);\n return result.items.map((item) => this._createServerOAuthConnectionFromCrudItem(userId, item));\n }\n );\n private readonly _serverUserOAuthConnectionAccessTokensByAccountCache = createCache<[string, string, string, string], { accessToken: string } | null>(\n async ([userId, providerId, providerAccountId, scope]) => {\n try {\n const result = await this._interface.createServerProviderAccessTokenByAccount(userId, providerId, providerAccountId, scope || \"\");\n return { accessToken: result.access_token };\n } catch (err) {\n if (!(KnownErrors.OAuthAccessTokenNotAvailable.isInstance(err) || KnownErrors.OAuthConnectionDoesNotHaveRequiredScope.isInstance(err) || KnownErrors.OAuthConnectionNotConnectedToUser.isInstance(err))) {\n throw err;\n }\n }\n return null;\n }\n );\n private readonly _serverTeamMemberProfilesCache = createCache<[string], TeamMemberProfilesCrud['Server']['Read'][]>(\n async ([teamId]) => {\n return await this._interface.listServerTeamMemberProfiles({ teamId });\n }\n );\n private readonly _serverTeamInvitationsCache = createCache<[string], TeamInvitationCrud['Server']['Read'][]>(\n async ([teamId]) => {\n return await this._interface.listServerTeamInvitations({ teamId });\n }\n );\n private readonly _serverUserTeamProfileCache = createCache<[string, string], TeamMemberProfilesCrud['Client']['Read']>(\n async ([teamId, userId]) => {\n return await this._interface.getServerTeamMemberProfile({ teamId, userId });\n }\n );\n private readonly _serverContactChannelsCache = createCache<[string], ContactChannelsCrud['Server']['Read'][]>(\n async ([userId]) => {\n return await this._interface.listServerContactChannels(userId);\n }\n );\n private readonly _serverNotificationCategoriesCache = createCache<[string], NotificationPreferenceCrud['Server']['Read'][]>(\n async ([userId]) => {\n return await this._interface.listServerNotificationCategories(userId);\n }\n );\n private readonly _serverDataVaultStoreValueCache = createCache<[string, string, string], string | null>(async ([storeId, key, secret]) => {\n return await this._interface.getDataVaultStoreValue(secret, storeId, key);\n });\n\n private readonly _emailDeliveryInfoCache = createCache(async () => {\n return await this._interface.getEmailDeliveryInfo();\n });\n\n private readonly _serverUserApiKeysCache = createCache<[string], UserApiKeysCrud['Server']['Read'][]>(\n async ([userId]) => {\n const result = await this._interface.listProjectApiKeys({\n user_id: userId,\n }, null, \"server\");\n return result as UserApiKeysCrud['Server']['Read'][];\n }\n );\n\n private readonly _serverTeamApiKeysCache = createCache<[string], TeamApiKeysCrud['Server']['Read'][]>(\n async ([teamId]) => {\n const result = await this._interface.listProjectApiKeys({\n team_id: teamId,\n }, null, \"server\");\n return result as TeamApiKeysCrud['Server']['Read'][];\n }\n );\n\n private readonly _convexIdentitySubjectCache = createCache<[ConvexCtx], string | null>(\n async ([ctx]) => {\n const identity = await ctx.auth.getUserIdentity();\n return identity ? identity.subject : null;\n }\n );\n\n private readonly _serverCheckApiKeyCache = createCache<[\"user\" | \"team\", string], UserApiKeysCrud['Server']['Read'] | TeamApiKeysCrud['Server']['Read'] | null>(async ([type, apiKey]) => {\n const result = await this._interface.checkProjectApiKey(\n type,\n apiKey,\n null,\n \"server\",\n );\n return result;\n });\n\n private readonly _serverOAuthProvidersCache = createCache<[string], OAuthProviderCrud['Server']['Read'][]>(\n async ([userId]) => {\n return await this._interface.listServerOAuthProviders({ user_id: userId });\n }\n );\n\n private readonly _serverTeamItemsCache = createCache<[string, string], ItemCrud['Client']['Read']>(\n async ([teamId, itemId]) => {\n return await this._interface.getItem({ teamId, itemId }, null, \"server\");\n }\n );\n\n private readonly _serverUserItemsCache = createCache<[string, string], ItemCrud['Client']['Read']>(\n async ([userId, itemId]) => {\n return await this._interface.getItem({ userId, itemId }, null, \"server\");\n }\n );\n\n private readonly _serverCustomItemsCache = createCache<[string, string], ItemCrud['Client']['Read']>(\n async ([customCustomerId, itemId]) => {\n return await this._interface.getItem({ customCustomerId, itemId }, null, \"server\");\n }\n );\n\n private readonly _serverUserProductsCache = createCache<[string, string | null, number | null], CustomerProductsListResponse>(\n async ([userId, cursor, limit]) => {\n return await this._interface.listProducts({\n customer_type: \"user\",\n customer_id: userId,\n cursor: cursor ?? undefined,\n limit: limit ?? undefined,\n }, null, \"server\");\n }\n );\n\n private readonly _serverTeamProductsCache = createCache<[string, string | null, number | null], CustomerProductsListResponse>(\n async ([teamId, cursor, limit]) => {\n return await this._interface.listProducts({\n customer_type: \"team\",\n customer_id: teamId,\n cursor: cursor ?? undefined,\n limit: limit ?? undefined,\n }, null, \"server\");\n }\n );\n\n private readonly _serverCustomProductsCache = createCache<[string, string | null, number | null], CustomerProductsListResponse>(\n async ([customCustomerId, cursor, limit]) => {\n return await this._interface.listProducts({\n customer_type: \"custom\",\n customer_id: customCustomerId,\n cursor: cursor ?? undefined,\n limit: limit ?? undefined,\n }, null, \"server\");\n }\n );\n\n protected _createServerCustomer(userIdOrTeamId: string, type: \"user\" | \"team\"): Omit<Customer<true>, \"id\"> {\n const app = this;\n const productsCache = type === \"user\" ? app._serverUserProductsCache : app._serverTeamProductsCache;\n const customerOptions = type === \"user\" ? { userId: userIdOrTeamId } : { teamId: userIdOrTeamId };\n return {\n ...this._createCustomer(userIdOrTeamId, type, null),\n async getItem(itemId: string) {\n return await app.getItem({ itemId, ...customerOptions });\n },\n async grantProduct(productOptions: { productId: string, quantity?: number } | { product: InlineProduct, quantity?: number }) {\n if (type === \"user\") {\n if (\"productId\" in productOptions) {\n await app.grantProduct({ userId: userIdOrTeamId, productId: productOptions.productId, quantity: productOptions.quantity });\n } else {\n await app.grantProduct({ userId: userIdOrTeamId, product: productOptions.product, quantity: productOptions.quantity });\n }\n } else {\n if (\"productId\" in productOptions) {\n await app.grantProduct({ teamId: userIdOrTeamId, productId: productOptions.productId, quantity: productOptions.quantity });\n } else {\n await app.grantProduct({ teamId: userIdOrTeamId, product: productOptions.product, quantity: productOptions.quantity });\n }\n }\n await productsCache.refresh([userIdOrTeamId, null, null]);\n },\n async createCheckoutUrl(options: { productId: string, returnUrl?: string } | { product: InlineProduct, returnUrl?: string }) {\n const productIdOrInline = \"productId\" in options ? options.productId : options.product;\n return await app._interface.createCheckoutUrl(type, userIdOrTeamId, productIdOrInline, null, options.returnUrl, \"server\");\n },\n };\n }\n\n private async _updateServerUser(userId: string, update: ServerUserUpdateOptions): Promise<UsersCrud['Server']['Read']> {\n const result = await this._interface.updateServerUser(userId, serverUserUpdateOptionsToCrud(update));\n await this._refreshUsers();\n return result;\n }\n\n protected _serverEditableTeamProfileFromCrud(crud: TeamMemberProfilesCrud['Client']['Read']): EditableTeamMemberProfile {\n const app = this;\n return {\n displayName: crud.display_name,\n profileImageUrl: crud.profile_image_url,\n async update(update: { displayName?: string, profileImageUrl?: string }) {\n await app._interface.updateServerTeamMemberProfile({\n teamId: crud.team_id,\n userId: crud.user_id,\n profile: {\n display_name: update.displayName,\n profile_image_url: update.profileImageUrl,\n },\n });\n await app._serverUserTeamProfileCache.refresh([crud.team_id, crud.user_id]);\n }\n };\n }\n\n protected _serverContactChannelFromCrud(userId: string, crud: ContactChannelsCrud['Server']['Read']): ServerContactChannel {\n const app = this;\n return {\n id: crud.id,\n value: crud.value,\n type: crud.type,\n isVerified: crud.is_verified,\n isPrimary: crud.is_primary,\n usedForAuth: crud.used_for_auth,\n async sendVerificationEmail(options?: { callbackUrl?: string }) {\n await app._interface.sendServerContactChannelVerificationEmail(userId, crud.id, options?.callbackUrl ?? constructRedirectUrl(app._getUrls().emailVerification, \"callbackUrl\"));\n },\n async update(data: ServerContactChannelUpdateOptions) {\n await app._interface.updateServerContactChannel(userId, crud.id, serverContactChannelUpdateOptionsToCrud(data));\n await Promise.all([\n app._serverContactChannelsCache.refresh([userId]),\n app._serverUserCache.refresh([userId])\n ]);\n },\n async delete() {\n await app._interface.deleteServerContactChannel(userId, crud.id);\n await Promise.all([\n app._serverContactChannelsCache.refresh([userId]),\n app._serverUserCache.refresh([userId])\n ]);\n },\n };\n }\n\n protected _serverNotificationCategoryFromCrud(userId: string, crud: NotificationPreferenceCrud['Server']['Read']): NotificationCategory {\n const app = this;\n return {\n id: crud.notification_category_id,\n name: crud.notification_category_name,\n enabled: crud.enabled,\n canDisable: crud.can_disable,\n\n async setEnabled(enabled: boolean) {\n await app._interface.setServerNotificationsEnabled(userId, crud.notification_category_id, enabled);\n await app._serverNotificationCategoriesCache.refresh([userId]);\n },\n };\n }\n\n protected _serverOAuthProviderFromCrud(crud: OAuthProviderCrud['Server']['Read']) {\n const app = this;\n return {\n id: crud.id,\n type: crud.type,\n userId: crud.user_id,\n accountId: crud.account_id,\n email: crud.email,\n allowSignIn: crud.allow_sign_in,\n allowConnectedAccounts: crud.allow_connected_accounts,\n\n async update(data: { accountId?: string, email?: string, allowSignIn?: boolean, allowConnectedAccounts?: boolean }): Promise<Result<void,\n InstanceType<typeof KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn>\n >> {\n try {\n await app._interface.updateServerOAuthProvider(crud.user_id, crud.id, {\n account_id: data.accountId,\n email: data.email,\n allow_sign_in: data.allowSignIn,\n allow_connected_accounts: data.allowConnectedAccounts,\n });\n await Promise.all([\n app._serverOAuthProvidersCache.refresh([crud.user_id]),\n app._serverUserConnectedAccountsCache.refresh([crud.user_id]),\n ]);\n return Result.ok(undefined);\n } catch (error) {\n if (KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn.isInstance(error)) {\n return Result.error(error);\n }\n throw error;\n }\n },\n\n async delete() {\n await app._interface.deleteServerOAuthProvider(crud.user_id, crud.id);\n await Promise.all([\n app._serverOAuthProvidersCache.refresh([crud.user_id]),\n app._serverUserConnectedAccountsCache.refresh([crud.user_id]),\n ]);\n },\n };\n }\n\n constructor(options: StackServerAppConstructorOptions<HasTokenStore, ProjectId>, extraOptions?: { uniqueIdentifier?: string, checkString?: string, interface?: HexclaveServerInterface }) {\n const resolvedOptions = resolveConstructorOptions(options);\n\n const publishableClientKey = resolvedOptions.publishableClientKey ?? getDefaultPublishableClientKey();\n\n super(resolvedOptions, {\n ...extraOptions,\n interface: extraOptions?.interface ?? (() => {\n const apiUrls = resolveApiUrls(resolvedOptions.baseUrl);\n return new HexclaveServerInterface({\n getBaseUrl: () => apiUrls()[0],\n getApiUrls: apiUrls,\n projectId: resolvedOptions.projectId ?? getDefaultProjectId(),\n extraRequestHeaders: resolvedOptions.extraRequestHeaders ?? getDefaultExtraRequestHeaders(),\n clientVersion,\n ...(publishableClientKey != null ? { publishableClientKey } : {}),\n secretServerKey: resolvedOptions.secretServerKey ?? getDefaultSecretServerKey(),\n });\n })(),\n });\n }\n\n\n protected _serverApiKeyFromCrud(crud: TeamApiKeysCrud['Client']['Read']): ApiKey<\"team\">;\n protected _serverApiKeyFromCrud(crud: UserApiKeysCrud['Client']['Read']): ApiKey<\"user\">;\n protected _serverApiKeyFromCrud(crud: yup.InferType<typeof teamApiKeysCreateOutputSchema>): ApiKey<\"team\", true>;\n protected _serverApiKeyFromCrud(crud: yup.InferType<typeof userApiKeysCreateOutputSchema>): ApiKey<\"user\", true>;\n protected _serverApiKeyFromCrud(crud: TeamApiKeysCrud['Client']['Read'] | UserApiKeysCrud['Client']['Read'] | yup.InferType<typeof teamApiKeysCreateOutputSchema> | yup.InferType<typeof userApiKeysCreateOutputSchema>): ApiKey<\"user\" | \"team\", boolean> {\n return {\n ...this._baseApiKeyFromCrud(crud),\n async revoke() {\n await this.update({ revoked: true });\n },\n update: async (options: ApiKeyUpdateOptions) => {\n await this._interface.updateProjectApiKey(\n crud.type === \"team\" ? { team_id: crud.team_id } : { user_id: crud.user_id },\n crud.id,\n await apiKeyUpdateOptionsToCrud(crud.type, options),\n null,\n \"server\");\n if (crud.type === \"team\") {\n await this._serverTeamApiKeysCache.refresh([crud.team_id]);\n } else {\n await this._serverUserApiKeysCache.refresh([crud.user_id]);\n }\n },\n };\n }\n\n protected _createServerOAuthConnectionFromCrudItem(\n userId: string,\n item: { provider: string, provider_account_id: string },\n ): OAuthConnection {\n const app = this;\n const providerId = item.provider;\n const providerAccountId = item.provider_account_id;\n return {\n id: providerId, // deprecated, for backward compat\n provider: providerId,\n providerAccountId,\n async getAccessToken(options?: { scopes?: string[] }) {\n const scopeString = options?.scopes?.join(\" \") ?? \"\";\n const result = Result.orThrow(await app._serverUserOAuthConnectionAccessTokensByAccountCache.getOrWait([userId, providerId, providerAccountId, scopeString], \"write-only\"));\n if (!result) {\n const scopeDetail = scopeString ? `The requested scopes [${scopeString}] are not available on the existing token.` : \"The OAuth refresh token has likely been revoked or expired.\";\n return Result.error(new KnownErrors.OAuthAccessTokenNotAvailable(providerId, `${scopeDetail} The user needs to re-authorize by calling \\`linkConnectedAccount\\` or using \\`getOrLinkConnectedAccount\\`.`));\n }\n return Result.ok(result);\n },\n };\n }\n\n protected _serverUserFromCrud(crud: UsersCrud['Server']['Read']): ServerUser {\n const app = this;\n\n /** @deprecated The string-based overloads are deprecated. Use `getConnectedAccount({ provider, providerAccountId })` for existence check. */\n async function getConnectedAccount(id: ProviderType, options?: { scopes?: string[] }): Promise<DeprecatedOAuthConnection | null>;\n async function getConnectedAccount(id: ProviderType, options: { or: 'redirect', scopes?: string[] }): Promise<DeprecatedOAuthConnection>;\n async function getConnectedAccount(account: { provider: string, providerAccountId: string }): Promise<OAuthConnection | null>;\n async function getConnectedAccount(\n idOrAccount: ProviderType | { provider: string, providerAccountId: string },\n options?: { or?: 'redirect', scopes?: string[] }\n ): Promise<DeprecatedOAuthConnection | OAuthConnection | null> {\n const scopeString = options?.scopes?.join(\" \") ?? \"\";\n\n // Check if it's the new object-based API\n if (typeof idOrAccount === 'object' && 'provider' in idOrAccount && 'providerAccountId' in idOrAccount) {\n const { provider, providerAccountId } = idOrAccount;\n // Check if the account exists in the connected accounts list\n const connectedAccounts = Result.orThrow(await app._serverUserConnectedAccountsCache.getOrWait([crud.id], \"write-only\"));\n const found = connectedAccounts.find(\n a => a.provider === provider && a.providerAccountId === providerAccountId\n );\n if (!found) {\n return null;\n }\n return found;\n }\n\n // Original behavior: by provider ID (returns first match)\n return Result.orThrow(await app._serverUserOAuthConnectionCache.getOrWait([crud.id, idOrAccount, scopeString, options?.or === 'redirect'], \"write-only\"));\n }\n\n\n // Type assertion needed because the new restricted_by_admin fields may not be reflected in TypeScript types yet\n // after schema changes - the runtime values are present after the schema is updated\n const crudWithAdminRestriction = crud as typeof crud & {\n restricted_by_admin: boolean,\n restricted_by_admin_reason: string | null,\n restricted_by_admin_private_details: string | null,\n };\n const serverUser = withUserDestructureGuard({\n ...super._createBaseUser(crud),\n lastActiveAt: new Date(crud.last_active_at_millis),\n serverMetadata: crud.server_metadata,\n restrictedByAdmin: crudWithAdminRestriction.restricted_by_admin,\n restrictedByAdminReason: crudWithAdminRestriction.restricted_by_admin_reason,\n restrictedByAdminPrivateDetails: crudWithAdminRestriction.restricted_by_admin_private_details,\n countryCode: crud.country_code,\n riskScores: {\n signUp: {\n bot: crud.risk_scores.sign_up.bot,\n freeTrialAbuse: crud.risk_scores.sign_up.free_trial_abuse,\n },\n },\n async setPrimaryEmail(email: string | null, options?: { verified?: boolean }) {\n await app._updateServerUser(crud.id, { primaryEmail: email, primaryEmailVerified: options?.verified });\n },\n async grantPermission(scopeOrPermissionId: Team | string, permissionId?: string): Promise<void> {\n if (scopeOrPermissionId && typeof scopeOrPermissionId !== 'string' && permissionId) {\n const scope = scopeOrPermissionId;\n await app._interface.grantServerTeamUserPermission(scope.id, crud.id, permissionId);\n\n for (const recursive of [true, false]) {\n await app._serverTeamUserPermissionsCache.refresh([scope.id, crud.id, recursive]);\n await app._serverAllTeamMemberPermissionsCache.refresh([scope.id, recursive]);\n }\n } else {\n const pId = scopeOrPermissionId as string;\n await app._interface.grantServerProjectPermission(crud.id, pId);\n\n for (const recursive of [true, false]) {\n await app._serverUserProjectPermissionsCache.refresh([crud.id, recursive]);\n }\n }\n },\n async revokePermission(scopeOrPermissionId: Team | string, permissionId?: string): Promise<void> {\n if (scopeOrPermissionId && typeof scopeOrPermissionId !== 'string' && permissionId) {\n const scope = scopeOrPermissionId;\n await app._interface.revokeServerTeamUserPermission(scope.id, crud.id, permissionId);\n\n for (const recursive of [true, false]) {\n await app._serverTeamUserPermissionsCache.refresh([scope.id, crud.id, recursive]);\n await app._serverAllTeamMemberPermissionsCache.refresh([scope.id, recursive]);\n }\n } else {\n const pId = scopeOrPermissionId as string;\n await app._interface.revokeServerProjectPermission(crud.id, pId);\n\n for (const recursive of [true, false]) {\n await app._serverUserProjectPermissionsCache.refresh([crud.id, recursive]);\n }\n }\n },\n async delete() {\n const res = await app._interface.deleteServerUser(crud.id);\n await app._refreshUsers();\n return res;\n },\n async createSession(options: { expiresInMillis?: number, isImpersonation?: boolean }) {\n // TODO this should also refresh the access token when it expires (like InternalSession)\n const tokens = await app._interface.createServerUserSession(crud.id, options.expiresInMillis ?? 1000 * 60 * 60 * 24 * 365, options.isImpersonation ?? false);\n return {\n async getTokens() {\n return tokens;\n },\n };\n },\n\n async getActiveSessions() {\n const sessions = await app._interface.listServerSessions(crud.id);\n return sessions.items.map((session) => app._clientSessionFromCrud(session));\n },\n\n async revokeSession(sessionId: string) {\n await app._interface.deleteServerSession(sessionId);\n },\n async setDisplayName(displayName: string | null) {\n return await this.update({ displayName });\n },\n async setClientMetadata(metadata: Record<string, any>) {\n return await this.update({ clientMetadata: metadata });\n },\n async setClientReadOnlyMetadata(metadata: Record<string, any>) {\n return await this.update({ clientReadOnlyMetadata: metadata });\n },\n async setServerMetadata(metadata: Record<string, any>) {\n return await this.update({ serverMetadata: metadata });\n },\n async setSelectedTeam(team: Team | string | null) {\n return await this.update({ selectedTeamId: typeof team === 'string' ? team : team?.id ?? null });\n },\n getConnectedAccount,\n async listConnectedAccounts() {\n return Result.orThrow(await app._serverUserConnectedAccountsCache.getOrWait([crud.id], \"write-only\"));\n },\n async linkConnectedAccount(): Promise<void> {\n throw new HexclaveAssertionError(\"linkConnectedAccount is not available for server users. OAuth flows must be initiated on the client side.\");\n },\n async getOrLinkConnectedAccount(): Promise<OAuthConnection> {\n throw new HexclaveAssertionError(\"getOrLinkConnectedAccount is not available for server users. OAuth flows must be initiated on the client side.\");\n },\n selectedTeam: crud.selected_team ? app._serverTeamFromCrud(crud.selected_team) : null,\n async getTeam(teamId: string) {\n const teams = await this.listTeams();\n return teams.find((t) => t.id === teamId) ?? null;\n },\n async listTeams(options?: ServerListTeamsOptions): Promise<ServerTeam[] & { nextCursor: string | null }> {\n const result = Result.orThrow(await app._serverTeamsCache.getOrWait([crud.id, options?.orderBy, options?.desc, options?.cursor, options?.limit, options?.query] as const, \"write-only\"));\n const teams: any = result.items.map((t) => app._serverTeamFromCrud(t));\n teams.nextCursor = result.pagination?.next_cursor ?? null;\n return teams as any;\n },\n createTeam: async (data: Omit<ServerTeamCreateOptions, \"creatorUserId\">) => {\n const team = await app._interface.createServerTeam(serverTeamCreateOptionsToCrud({\n creatorUserId: crud.id,\n ...data,\n }));\n await app._serverTeamsCache.refreshWhere(() => true);\n await app._updateServerUser(crud.id, { selectedTeamId: team.id });\n return app._serverTeamFromCrud(team);\n },\n leaveTeam: async (team: Team) => {\n await app._interface.leaveServerTeam({ teamId: team.id, userId: crud.id });\n await app._refreshTeamMembership(team.id, crud.id);\n },\n async listTeamInvitations() {\n const invitations = Result.orThrow(await app._serverUserTeamInvitationsCache.getOrWait([crud.id], \"write-only\"));\n return invitations.map((inv) => app._serverReceivedTeamInvitationFromCrud(crud.id, inv));\n },\n async listPermissions(scopeOrOptions?: Team | { recursive?: boolean }, options?: { recursive?: boolean }): Promise<AdminTeamPermission[]> {\n if (scopeOrOptions && 'id' in scopeOrOptions) {\n const scope = scopeOrOptions;\n const recursive = options?.recursive ?? true;\n const permissions = Result.orThrow(await app._serverTeamUserPermissionsCache.getOrWait([scope.id, crud.id, recursive], \"write-only\"));\n return permissions.map((crud) => app._serverPermissionFromCrud(crud));\n } else {\n const opts = scopeOrOptions;\n const recursive = opts?.recursive ?? true;\n const permissions = Result.orThrow(await app._serverUserProjectPermissionsCache.getOrWait([crud.id, recursive], \"write-only\"));\n return permissions.map((crud) => app._serverPermissionFromCrud(crud));\n }\n },\n async getPermission(scopeOrPermissionId: Team | string, permissionId?: string): Promise<AdminTeamPermission | null> {\n if (scopeOrPermissionId && typeof scopeOrPermissionId !== 'string') {\n const scope = scopeOrPermissionId;\n const permissions = await this.listPermissions(scope);\n return permissions.find((p) => p.id === permissionId) ?? null;\n } else {\n const pid = scopeOrPermissionId;\n const permissions = await this.listPermissions();\n return permissions.find((p) => p.id === pid) ?? null;\n }\n },\n async hasPermission(scopeOrPermissionId: Team | string, permissionId?: string): Promise<boolean> {\n if (scopeOrPermissionId && typeof scopeOrPermissionId !== 'string') {\n const scope = scopeOrPermissionId;\n return (await this.getPermission(scope, permissionId as string)) !== null;\n } else {\n const pid = scopeOrPermissionId;\n return (await this.getPermission(pid)) !== null;\n }\n },\n async update(update: ServerUserUpdateOptions) {\n await app._updateServerUser(crud.id, update);\n },\n async sendVerificationEmail() {\n return await app._checkFeatureSupport(\"sendVerificationEmail() on ServerUser\", {});\n },\n async updatePassword(options: { oldPassword: string, newPassword: string }) {\n const result = await app._interface.updatePassword(options);\n await app._serverUserCache.refresh([crud.id]);\n return result;\n },\n async setPassword(options: { password: string }) {\n const result = await this.update(options);\n await app._serverUserCache.refresh([crud.id]);\n return result;\n },\n async getTeamProfile(team: Team) {\n const result = Result.orThrow(await app._serverUserTeamProfileCache.getOrWait([team.id, crud.id], \"write-only\"));\n return app._serverEditableTeamProfileFromCrud(result);\n },\n async listContactChannels() {\n const result = Result.orThrow(await app._serverContactChannelsCache.getOrWait([crud.id], \"write-only\"));\n return result.map((data) => app._serverContactChannelFromCrud(crud.id, data));\n },\n createContactChannel: async (data: ServerContactChannelCreateOptions) => {\n const contactChannel = await app._interface.createServerContactChannel(serverContactChannelCreateOptionsToCrud(crud.id, data));\n await Promise.all([\n app._serverContactChannelsCache.refresh([crud.id]),\n app._serverUserCache.refresh([crud.id])\n ]);\n return app._serverContactChannelFromCrud(crud.id, contactChannel);\n },\n async listNotificationCategories() {\n const results = Result.orThrow(await app._serverNotificationCategoriesCache.getOrWait([crud.id], \"write-only\"));\n return results.map((category) => app._serverNotificationCategoryFromCrud(crud.id, category));\n },\n async listApiKeys() {\n const result = Result.orThrow(await app._serverUserApiKeysCache.getOrWait([crud.id], \"write-only\"));\n return result.map((apiKey) => app._serverApiKeyFromCrud(apiKey));\n },\n async createApiKey(options: ApiKeyCreationOptions<\"user\">) {\n const result = await app._interface.createProjectApiKey(\n await apiKeyCreationOptionsToCrud(\"user\", crud.id, options),\n null,\n \"server\",\n );\n await app._serverUserApiKeysCache.refresh([crud.id]);\n return app._serverApiKeyFromCrud(result);\n },\n\n async listOAuthProviders() {\n const results = Result.orThrow(await app._serverOAuthProvidersCache.getOrWait([crud.id], \"write-only\"));\n return results.map((oauthCrud) => app._serverOAuthProviderFromCrud(oauthCrud));\n },\n\n async getOAuthProvider(id: string) {\n const providers = await this.listOAuthProviders();\n return providers.find((p) => p.id === id) ?? null;\n },\n async registerPasskey(options?: { hostname?: string }): Promise<Result<undefined, KnownErrors[\"PasskeyRegistrationFailed\"] | KnownErrors[\"PasskeyWebAuthnError\"]>> {\n // TODO remove duplicated code between this and the function in client-app-impl.ts\n const hostname = options?.hostname || (await app._getCurrentUrl())?.hostname;\n if (!hostname) {\n throw new HexclaveAssertionError(\"hostname must be provided if the Stack App does not have a redirect method\");\n }\n\n // Use server interface to initiate passkey registration for this specific user\n const initiationResult = await app._interface.initiateServerPasskeyRegistration(crud.id);\n\n if (initiationResult.status !== \"ok\") {\n return Result.error(new KnownErrors.PasskeyRegistrationFailed(\"Failed to get initiation options for passkey registration\"));\n }\n\n const { options_json, code } = initiationResult.data;\n\n // HACK: Override the rpID to be the actual domain\n if (options_json.rp.id !== \"THIS_VALUE_WILL_BE_REPLACED.example.com\") {\n throw new HexclaveAssertionError(`Expected returned RP ID from server to equal sentinel, but found ${options_json.rp.id}`);\n }\n\n options_json.rp.id = hostname;\n\n let attResp;\n try {\n attResp = await startRegistration({ optionsJSON: options_json });\n } catch (error: any) {\n if (error instanceof WebAuthnError) {\n return Result.error(new KnownErrors.PasskeyWebAuthnError(error.message, error.name));\n } else {\n // This should never happen\n captureError(\"passkey-registration-failed\", error);\n return Result.error(new KnownErrors.PasskeyRegistrationFailed(\"Failed to start passkey registration due to unknown error\"));\n }\n }\n\n // Create a temporary session to complete the registration\n // TODO instead of creating a new session, this should just call the endpoint in a way in which it doesn't require a session\n // (currently this shows up on session history etc... not ideal)\n const { accessToken, refreshToken } = await app._interface.createServerUserSession(crud.id, 60000 * 2, false);\n const tempSession = new InternalSession({\n accessToken,\n refreshToken,\n refreshAccessTokenCallback: async () => null,\n });\n\n const registrationResult = await app._interface.registerPasskey({ credential: attResp, code }, tempSession);\n\n await app._serverUserCache.refresh([crud.id]);\n return registrationResult;\n },\n ...app._createServerCustomer(crud.id, \"user\"),\n } satisfies ServerUser);\n\n return serverUser;\n }\n\n protected _serverTeamUserFromCrud(crud: TeamMemberProfilesCrud[\"Server\"][\"Read\"]): ServerTeamUser {\n const teamUser = withUserDestructureGuard({\n ...this._serverUserFromCrud(crud.user),\n teamProfile: {\n displayName: crud.display_name,\n profileImageUrl: crud.profile_image_url,\n },\n } satisfies ServerTeamUser);\n\n return teamUser;\n }\n\n protected _serverSentTeamInvitationFromCrud(crud: TeamInvitationCrud['Server']['Read']): SentTeamInvitation {\n return {\n id: crud.id,\n recipientEmail: crud.recipient_email,\n expiresAt: new Date(crud.expires_at_millis),\n revoke: async () => {\n await this._interface.revokeServerTeamInvitation(crud.id, crud.team_id);\n await this._serverTeamInvitationsCache.refresh([crud.team_id]);\n },\n };\n }\n\n protected _serverReceivedTeamInvitationFromCrud(userId: string, crud: TeamInvitationCrud['Client']['Read']): ReceivedTeamInvitation {\n const app = this;\n return {\n id: crud.id,\n teamId: crud.team_id,\n teamDisplayName: crud.team_display_name,\n recipientEmail: crud.recipient_email,\n expiresAt: new Date(crud.expires_at_millis),\n accept: async () => {\n await app._interface.acceptServerTeamInvitationById(crud.id, userId);\n await Promise.all([\n app._serverUserTeamInvitationsCache.refresh([userId]),\n app._serverTeamInvitationsCache.refresh([crud.team_id]),\n app._refreshTeamMembership(crud.team_id, userId),\n ]);\n },\n };\n }\n\n protected override _currentUserFromCrud(crud: UsersCrud['Server']['Read'], session: InternalSession): ProjectCurrentServerUser<ProjectId> {\n const currentUser = withUserDestructureGuard({\n ...this._serverUserFromCrud(crud),\n ...this._createAuth(session),\n ...this._isInternalProject() ? this._createInternalUserExtra(session) : {},\n } satisfies ServerUser);\n\n return currentUser as ProjectCurrentServerUser<ProjectId>;\n }\n\n protected _serverTeamFromCrud(crud: TeamsCrud['Server']['Read']): ServerTeam {\n const app = this;\n return {\n id: crud.id,\n displayName: crud.display_name,\n profileImageUrl: crud.profile_image_url,\n createdAt: new Date(crud.created_at_millis),\n clientMetadata: crud.client_metadata,\n clientReadOnlyMetadata: crud.client_read_only_metadata,\n serverMetadata: crud.server_metadata,\n async update(update: Partial<ServerTeamUpdateOptions>) {\n await app._interface.updateServerTeam(crud.id, serverTeamUpdateOptionsToCrud(update));\n await Promise.all([\n app._serverTeamsCache.refreshWhere(() => true),\n app._serverUsersCache.refreshWhere(() => true),\n ]);\n },\n async delete() {\n await app._interface.deleteServerTeam(crud.id);\n await Promise.all([\n app._serverTeamsCache.refreshWhere(() => true),\n app._serverUsersCache.refreshWhere(() => true),\n ]);\n },\n async listUsers() {\n const result = Result.orThrow(await app._serverTeamMemberProfilesCache.getOrWait([crud.id], \"write-only\"));\n return result.map(u => app._serverTeamUserFromCrud(u));\n },\n async addUser(userId) {\n await app._interface.addServerUserToTeam({\n teamId: crud.id,\n userId,\n });\n await app._refreshTeamMembership(crud.id, userId);\n },\n async removeUser(userId) {\n await app._interface.removeServerUserFromTeam({\n teamId: crud.id,\n userId,\n });\n await app._refreshTeamMembership(crud.id, userId);\n },\n async inviteUser(options: { email: string, callbackUrl?: string }) {\n await app._interface.sendServerTeamInvitation({\n teamId: crud.id,\n email: options.email,\n callbackUrl: options.callbackUrl ?? constructRedirectUrl(app._getUrls().teamInvitation, \"callbackUrl\"),\n });\n await app._serverTeamInvitationsCache.refresh([crud.id]);\n },\n async listInvitations() {\n const result = Result.orThrow(await app._serverTeamInvitationsCache.getOrWait([crud.id], \"write-only\"));\n return result.map((crud) => app._serverSentTeamInvitationFromCrud(crud));\n },\n async listApiKeys() {\n const result = Result.orThrow(await app._serverTeamApiKeysCache.getOrWait([crud.id], \"write-only\"));\n return result.map((apiKey) => app._serverApiKeyFromCrud(apiKey));\n },\n async createApiKey(options: ApiKeyCreationOptions<\"team\">) {\n const result = await app._interface.createProjectApiKey(\n await apiKeyCreationOptionsToCrud(\"team\", crud.id, options),\n null,\n \"server\",\n );\n await app._serverTeamApiKeysCache.refresh([crud.id]);\n return app._serverApiKeyFromCrud(result);\n },\n ...app._createServerCustomer(crud.id, \"team\"),\n };\n }\n\n protected _serverItemFromCrud(customer: { type: \"user\" | \"team\" | \"custom\", id: string }, crud: ItemCrud['Client']['Read']): ServerItem {\n const app = this;\n return {\n displayName: crud.display_name,\n quantity: crud.quantity,\n nonNegativeQuantity: Math.max(0, crud.quantity),\n increaseQuantity: async (delta: number) => {\n const updateOptions = customer.type === \"user\"\n ? { itemId: crud.id, userId: customer.id }\n : customer.type === \"team\"\n ? { itemId: crud.id, teamId: customer.id }\n : { itemId: crud.id, customCustomerId: customer.id };\n await app._interface.updateItemQuantity(updateOptions, { delta });\n if (customer.type === \"user\") await app._serverUserItemsCache.refresh([customer.id, crud.id]);\n else if (customer.type === \"team\") await app._serverTeamItemsCache.refresh([customer.id, crud.id]);\n else await app._serverCustomItemsCache.refresh([customer.id, crud.id]);\n },\n decreaseQuantity: async (delta: number) => {\n const updateOptions = customer.type === \"user\"\n ? { itemId: crud.id, userId: customer.id }\n : customer.type === \"team\"\n ? { itemId: crud.id, teamId: customer.id }\n : { itemId: crud.id, customCustomerId: customer.id };\n await app._interface.updateItemQuantity(updateOptions, { delta: -delta, allow_negative: true });\n if (customer.type === \"user\") await app._serverUserItemsCache.refresh([customer.id, crud.id]);\n else if (customer.type === \"team\") await app._serverTeamItemsCache.refresh([customer.id, crud.id]);\n else await app._serverCustomItemsCache.refresh([customer.id, crud.id]);\n },\n tryDecreaseQuantity: async (delta: number) => {\n try {\n const updateOptions = customer.type === \"user\"\n ? { itemId: crud.id, userId: customer.id }\n : customer.type === \"team\"\n ? { itemId: crud.id, teamId: customer.id }\n : { itemId: crud.id, customCustomerId: customer.id };\n await app._interface.updateItemQuantity(updateOptions, { delta: -delta });\n if (customer.type === \"user\") await app._serverUserItemsCache.refresh([customer.id, crud.id]);\n else if (customer.type === \"team\") await app._serverTeamItemsCache.refresh([customer.id, crud.id]);\n else await app._serverCustomItemsCache.refresh([customer.id, crud.id]);\n return true;\n } catch (error) {\n if (error instanceof KnownErrors.ItemQuantityInsufficientAmount) {\n return false;\n }\n throw error;\n }\n },\n };\n }\n\n protected async _getUserApiKey(options: { apiKey: string }): Promise<ApiKey<\"user\"> | null> {\n const crud = Result.orThrow(await this._serverCheckApiKeyCache.getOrWait([\"user\", options.apiKey], \"write-only\")) as UserApiKeysCrud['Server']['Read'] | null;\n return crud ? this._serverApiKeyFromCrud(crud) : null;\n }\n\n protected async _getTeamApiKey(options: { apiKey: string }): Promise<ApiKey<\"team\"> | null> {\n const crud = Result.orThrow(await this._serverCheckApiKeyCache.getOrWait([\"team\", options.apiKey], \"write-only\")) as TeamApiKeysCrud['Server']['Read'] | null;\n return crud ? this._serverApiKeyFromCrud(crud) : null;\n }\n protected async _getUserByApiKey(apiKey: string): Promise<ServerUser | null> {\n const apiKeyObject = await this._getUserApiKey({ apiKey });\n if (apiKeyObject === null) {\n return null;\n }\n return await this.getServerUserById(apiKeyObject.userId);\n }\n\n protected async _getUserByConvex(ctx: ConvexCtx, includeAnonymous: boolean): Promise<ServerUser | null> {\n const identity = await ctx.auth.getUserIdentity();\n if (identity === null) {\n return null;\n }\n const user = await this.getServerUserById(identity.subject);\n if (user?.isAnonymous && !includeAnonymous) {\n return null;\n }\n return user;\n }\n\n protected async _getTeamByApiKey(apiKey: string): Promise<ServerTeam | null> {\n const apiKeyObject = await this._getTeamApiKey({ apiKey });\n if (apiKeyObject === null) {\n return null;\n }\n return await this.getTeam(apiKeyObject.teamId);\n }\n\n async createUser(options: ServerUserCreateOptions): Promise<ServerUser> {\n const crud = await this._interface.createServerUser(serverUserCreateOptionsToCrud(options));\n await this._refreshUsers();\n return this._serverUserFromCrud(crud);\n }\n\n async getUser(options: GetCurrentUserOptions<HasTokenStore> & { or: 'redirect' }): Promise<ProjectCurrentServerUser<ProjectId>>;\n async getUser(options: GetCurrentUserOptions<HasTokenStore> & { or: 'throw' }): Promise<ProjectCurrentServerUser<ProjectId>>;\n async getUser(options: GetCurrentUserOptions<HasTokenStore> & { or: 'anonymous' }): Promise<ProjectCurrentServerUser<ProjectId>>;\n async getUser(options?: GetCurrentUserOptions<HasTokenStore>): Promise<ProjectCurrentServerUser<ProjectId> | null>;\n async getUser(id: string): Promise<ServerUser | null>;\n async getUser(options: { apiKey: string }): Promise<ServerUser | null>;\n async getUser(options: { from: \"convex\", ctx: ConvexCtx, or?: \"return-null\" | \"anonymous\" }): Promise<ServerUser | null>;\n async getUser(options?: string | GetCurrentUserOptions<HasTokenStore> | { apiKey: string } | { from: \"convex\", ctx: ConvexCtx }): Promise<ProjectCurrentServerUser<ProjectId> | ServerUser | null> {\n if (typeof options === \"string\") {\n return await this.getServerUserById(options);\n } else if (typeof options === \"object\" && \"apiKey\" in options) {\n return await this._getUserByApiKey(options.apiKey);\n } else if (typeof options === \"object\" && \"from\" in options && options.from as string === \"convex\") {\n return await this._getUserByConvex(options.ctx, \"or\" in options && options.or === \"anonymous\");\n } else {\n options = options as GetCurrentUserOptions<HasTokenStore> | undefined;\n\n // Validate that includeRestricted: false and or: 'anonymous' are mutually exclusive\n if (options?.or === 'anonymous' && options.includeRestricted === false) {\n throw new Error(\"Cannot use { or: 'anonymous' } with { includeRestricted: false }. Anonymous users implicitly include restricted users.\");\n }\n\n // TODO this code is duplicated from the client app; fix that\n this._ensurePersistentTokenStore(options?.tokenStore);\n const session = await this._getSession(options?.tokenStore);\n let crud = Result.orThrow(await this._currentServerUserCache.getOrWait([session], \"write-only\"));\n const includeAnonymous = options?.or === \"anonymous\" || options?.or === \"anonymous-if-exists[deprecated]\";\n const includeRestricted = options?.includeRestricted === true || includeAnonymous;\n\n if (crud === null || (crud.is_anonymous && !includeAnonymous) || (crud.is_restricted && !includeRestricted)) {\n switch (options?.or) {\n case 'redirect': {\n if (!crud?.is_anonymous && crud?.is_restricted) {\n await this.redirectToOnboarding({ replace: true });\n } else {\n await this.redirectToSignIn({ replace: true });\n }\n // TODO: see client-app-impl. We probably want to `await neverResolve()` here instead of returning null\n break;\n }\n case 'throw': {\n throw new Error(\"User is not signed in but getUser was called with { or: 'throw' }\");\n }\n case 'anonymous': {\n const tokens = await this._signUpAnonymously();\n return await this.getUser({ tokenStore: tokens, or: \"anonymous-if-exists[deprecated]\", includeRestricted: true }) ?? throwErr(\"Something went wrong while signing up anonymously\");\n }\n case undefined:\n case \"anonymous-if-exists[deprecated]\":\n case \"return-null\": {\n return null;\n }\n }\n }\n\n return crud && this._currentUserFromCrud(crud, session);\n }\n }\n\n async getServerUser(): Promise<ProjectCurrentServerUser<ProjectId> | null> {\n console.warn(\"hexclaveServerApp.getServerUser is deprecated; use hexclaveServerApp.getUser instead\");\n return await this.getUser();\n }\n\n async getServerUserById(userId: string): Promise<ServerUser | null> {\n const crud = Result.orThrow(await this._serverUserCache.getOrWait([userId], \"write-only\"));\n return crud && this._serverUserFromCrud(crud);\n }\n\n\n async listUsers(options?: ServerListUsersOptions): Promise<ServerUser[] & { nextCursor: string | null }> {\n const crud = Result.orThrow(await this._serverUsersCache.getOrWait([options?.cursor, options?.limit, options?.orderBy, options?.desc, options?.query, options?.includeRestricted, options?.includeAnonymous, options?.onlyAnonymous, options?.teamId], \"write-only\"));\n const result: any = crud.items.map((j) => this._serverUserFromCrud(j));\n result.nextCursor = crud.pagination?.next_cursor ?? null;\n return result as any;\n }\n\n\n _serverPermissionFromCrud(crud: TeamPermissionsCrud['Server']['Read'] | ProjectPermissionsCrud['Server']['Read']): AdminTeamPermission {\n return {\n id: crud.id,\n };\n }\n\n _serverTeamPermissionDefinitionFromCrud(crud: TeamPermissionDefinitionsCrud['Admin']['Read']): AdminTeamPermissionDefinition {\n return {\n id: crud.id,\n description: crud.description,\n containedPermissionIds: crud.contained_permission_ids,\n };\n }\n\n _serverProjectPermissionDefinitionFromCrud(crud: ProjectPermissionDefinitionsCrud['Admin']['Read']): AdminProjectPermissionDefinition {\n return {\n id: crud.id,\n description: crud.description,\n containedPermissionIds: crud.contained_permission_ids,\n };\n }\n\n async getItem(options: { itemId: string, userId: string } | { itemId: string, teamId: string } | { itemId: string, customCustomerId: string }): Promise<ServerItem> {\n if (\"userId\" in options) {\n const result = Result.orThrow(await this._serverUserItemsCache.getOrWait([options.userId, options.itemId], \"write-only\"));\n return this._serverItemFromCrud({ type: \"user\", id: options.userId }, result);\n } else if (\"teamId\" in options) {\n const result = Result.orThrow(await this._serverTeamItemsCache.getOrWait([options.teamId, options.itemId], \"write-only\"));\n return this._serverItemFromCrud({ type: \"team\", id: options.teamId }, result);\n } else {\n const result = Result.orThrow(await this._serverCustomItemsCache.getOrWait([options.customCustomerId, options.itemId], \"write-only\"));\n return this._serverItemFromCrud({ type: \"custom\", id: options.customCustomerId }, result);\n }\n }\n\n async listProducts(options: CustomerProductsRequestOptions): Promise<CustomerProductsList> {\n if (\"userId\" in options) {\n const response = Result.orThrow(await this._serverUserProductsCache.getOrWait([options.userId, options.cursor ?? null, options.limit ?? null], \"write-only\"));\n return this._customerProductsFromResponse(response);\n } else if (\"teamId\" in options) {\n const response = Result.orThrow(await this._serverTeamProductsCache.getOrWait([options.teamId, options.cursor ?? null, options.limit ?? null], \"write-only\"));\n return this._customerProductsFromResponse(response);\n }\n const response = Result.orThrow(await this._serverCustomProductsCache.getOrWait([options.customCustomerId, options.cursor ?? null, options.limit ?? null], \"write-only\"));\n return this._customerProductsFromResponse(response);\n }\n\n private _resolveCustomer(\n options: { userId: string } | { teamId: string } | { customCustomerId: string }\n ): { customerType: \"user\" | \"team\" | \"custom\", customerId: string } {\n if (\"userId\" in options) {\n return { customerType: \"user\", customerId: options.userId };\n }\n if (\"teamId\" in options) {\n return { customerType: \"team\", customerId: options.teamId };\n }\n return { customerType: \"custom\", customerId: options.customCustomerId };\n }\n\n async grantProduct(options: (\n ({ userId: string } | { teamId: string } | { customCustomerId: string }) &\n ({ productId: string } | { product: InlineProduct }) &\n { quantity?: number }\n )): Promise<void> {\n const { customerType, customerId } = this._resolveCustomer(options);\n\n await this._interface.grantProduct({\n customerType,\n customerId,\n productId: \"productId\" in options ? options.productId : undefined,\n product: \"product\" in options ? options.product : undefined,\n quantity: options.quantity,\n });\n\n const cache = customerType === \"user\"\n ? this._serverUserProductsCache\n : customerType === \"team\"\n ? this._serverTeamProductsCache\n : this._serverCustomProductsCache;\n await cache.refresh([customerId, null, null]);\n }\n\n async createCheckoutUrl(options: (\n ({ userId: string } | { teamId: string } | { customCustomerId: string }) &\n ({ productId: string } | { product: InlineProduct }) &\n { returnUrl?: string }\n )): Promise<string> {\n const { customerType, customerId } = this._resolveCustomer(options);\n\n const productIdOrInline = \"productId\" in options ? options.productId : options.product;\n return await this._interface.createCheckoutUrl(customerType, customerId, productIdOrInline, null, options.returnUrl, \"server\");\n }\n\n async createTeam(data: ServerTeamCreateOptions): Promise<ServerTeam> {\n const team = await this._interface.createServerTeam(serverTeamCreateOptionsToCrud(data));\n await this._serverTeamsCache.refreshWhere(() => true);\n return this._serverTeamFromCrud(team);\n }\n\n async listTeams(options?: ServerListTeamsOptions): Promise<ServerTeam[] & { nextCursor: string | null }> {\n const crud = Result.orThrow(await this._serverTeamsCache.getOrWait([undefined, options?.orderBy, options?.desc, options?.cursor, options?.limit, options?.query] as const, \"write-only\"));\n const teams: any = crud.items.map((t) => this._serverTeamFromCrud(t));\n teams.nextCursor = crud.pagination?.next_cursor ?? null;\n return teams as any;\n }\n\n\n async listTeamMemberPermissions(teamId: string, options?: { recursive?: boolean }): Promise<{ userId: string, permissionId: string }[]> {\n const recursive = options?.recursive ?? false;\n const rows = Result.orThrow(await this._serverAllTeamMemberPermissionsCache.getOrWait([teamId, recursive] as const, \"write-only\"));\n return rows.map((r) => ({ userId: r.user_id, permissionId: r.id }));\n }\n\n\n async getTeam(options: { apiKey: string }): Promise<ServerTeam | null>;\n async getTeam(teamId: string): Promise<ServerTeam | null>;\n async getTeam(options?: { apiKey: string } | string): Promise<ServerTeam | null> {\n if (typeof options === \"object\" && \"apiKey\" in options) {\n return await this._getTeamByApiKey(options.apiKey);\n } else {\n const teamId = options;\n const teams = await this.listTeams();\n return teams.find((t) => t.id === teamId) ?? null;\n }\n }\n\n\n protected _createServerDataVaultStore(id: string): DataVaultStore {\n const validateOptions = (options: { secret: string }) => {\n if (typeof options.secret !== \"string\") throw new Error(\"secret must be a string, got \" + typeof options.secret);\n };\n return {\n id,\n setValue: async (key, value, options) => {\n validateOptions(options);\n await this._interface.setDataVaultStoreValue(options.secret, id, key, value);\n },\n getValue: async (key, options) => {\n validateOptions(options);\n return Result.orThrow(await this._serverDataVaultStoreValueCache.getOrWait([id, key, options.secret], \"write-only\"));\n },\n };\n }\n\n async getDataVaultStore(id: string): Promise<DataVaultStore> {\n return this._createServerDataVaultStore(id);\n }\n\n\n async sendEmail(options: SendEmailOptions): Promise<void> {\n await this._interface.sendEmail(options);\n await this._emailDeliveryInfoCache.refresh([]);\n }\n\n async getEmailDeliveryStats(): Promise<EmailDeliveryInfo> {\n return Result.orThrow(await this._emailDeliveryInfoCache.getOrWait([], \"write-only\"));\n }\n\n\n async activateEmailCapacityBoost(): Promise<void> {\n await this._interface.activateEmailCapacityBoost();\n // Refresh the cache so UI updates immediately\n await this._emailDeliveryInfoCache.refresh([]);\n }\n\n protected override async _refreshSession(session: InternalSession) {\n await Promise.all([\n super._refreshUser(session),\n this._currentServerUserCache.refresh([session]),\n ]);\n }\n\n protected override async _refreshUsers() {\n await Promise.all([\n super._refreshUsers(),\n this._serverUserCache.refreshWhere(() => true),\n this._serverUsersCache.refreshWhere(() => true),\n this._serverContactChannelsCache.refreshWhere(() => true),\n this._serverOAuthProvidersCache.refreshWhere(() => true),\n this._serverUserConnectedAccountsCache.refreshWhere(() => true),\n ]);\n }\n\n async createOAuthProvider(options: {\n userId: string,\n providerConfigId: string,\n accountId: string,\n email: string,\n allowSignIn: boolean,\n allowConnectedAccounts: boolean,\n }): Promise<Result<ServerOAuthProvider, InstanceType<typeof KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn>>> {\n try {\n const crud = await this._interface.createServerOAuthProvider({\n user_id: options.userId,\n provider_config_id: options.providerConfigId,\n account_id: options.accountId,\n email: options.email,\n allow_sign_in: options.allowSignIn,\n allow_connected_accounts: options.allowConnectedAccounts,\n });\n\n await Promise.all([\n this._serverOAuthProvidersCache.refresh([options.userId]),\n this._serverUserConnectedAccountsCache.refresh([options.userId]),\n ]);\n return Result.ok(this._serverOAuthProviderFromCrud(crud));\n } catch (error) {\n if (KnownErrors.OAuthProviderAccountIdAlreadyUsedForSignIn.isInstance(error)) {\n return Result.error(error);\n }\n throw error;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2CA,IAAa,mCAAb,cAA+GA,sDAA2D;CA6CxK,MAAgB,uBAAuB,QAAgB,QAAgB;AACrE,QAAM,QAAQ,IAAI;GAChB,KAAK,+BAA+B,QAAQ,CAAC,OAAO,CAAC;GACrD,KAAK,kBAAkB,cAAc,CAAC,OAAO,MAAM,UAAU,MAAM,OAAU;GAC7E,KAAK,kBAAkB,cAAc,QAAQ,IAAI,OAAO,OAAO;GAChE,CAAC;;CAsMJ,AAAU,sBAAsB,gBAAwB,MAAmD;EACzG,MAAM,MAAM;EACZ,MAAM,gBAAgB,SAAS,SAAS,IAAI,2BAA2B,IAAI;EAC3E,MAAM,kBAAkB,SAAS,SAAS,EAAE,QAAQ,gBAAgB,GAAG,EAAE,QAAQ,gBAAgB;AACjG,SAAO;GACL,GAAG,KAAK,gBAAgB,gBAAgB,MAAM,KAAK;GACnD,MAAM,QAAQ,QAAgB;AAC5B,WAAO,MAAM,IAAI,QAAQ;KAAE;KAAQ,GAAG;KAAiB,CAAC;;GAE1D,MAAM,aAAa,gBAA0G;AAC3H,QAAI,SAAS,OACX,KAAI,eAAe,eACjB,OAAM,IAAI,aAAa;KAAE,QAAQ;KAAgB,WAAW,eAAe;KAAW,UAAU,eAAe;KAAU,CAAC;QAE1H,OAAM,IA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ACA,cAAA;EAAA,QACA,gBAAA;EAAA,QACA,WAAA;EAAA,QACA,OAAA;EAAA,QACA,WAAA;EAAA,QACA,YAAA;EAAA,QACA,oBAAA;EAAA,QACA,UAAA;EAAA,QACA,YAAA;EAAA,QACA,qBAAA;EAAA,QACA,eAAA;EAAA,QACA,gBAAA;EAAA,iBACS,uBAAA;EAAA,iBACA,WAAA;EAAA,iBAEA,iBAAA;EAAA,iBACA,KAAA;EAAA,iBACA,cAAA;cAEL,IAAA,EAAM,mBAAA,EAAqB,aAAA,EAAe,sBAAA;EA7CQ;;;EAwD9D,KAAA,CAAA;EAYA,IAAA,CAAA;EAWA,WAAA,CAAA;EAAA,QAMQ,gBAAA;EAAA,QASM,MAAA;EAAA,QA4FN,QAAA;EAAA,QAUM,eAAA;EAAA,QAgEN,qBAAA;EAAA,QAeA,KAAA;AAAA"}
@@ -60,6 +60,7 @@ const FLUSH_INTERVAL_MS = 5e3;
60
60
  const MAX_EVENTS_PER_BATCH = 200;
61
61
  const MAX_APPROX_BYTES_PER_BATCH = 512e3;
62
62
  const MAX_FLUSH_PAYLOAD_BYTES = 9e5;
63
+ const textEncoder = new TextEncoder();
63
64
  function safeParseStoredSession(raw) {
64
65
  if (!raw) return null;
65
66
  try {
@@ -186,6 +187,12 @@ var SessionRecorder = class {
186
187
  try {
187
188
  let offset = 0;
188
189
  while (offset < allEvents.length) {
190
+ const firstSize = allSizes[offset] ?? (0, _hexclave_shared_dist_utils_errors.throwErr)("_eventSizes out of sync with _events — this should never happen");
191
+ if (firstSize > MAX_FLUSH_PAYLOAD_BYTES) {
192
+ (0, _hexclave_shared_dist_utils_errors.captureWarning)("SessionRecorder.flush", /* @__PURE__ */ new Error(`Dropping oversized session replay event (${firstSize} bytes > ${MAX_FLUSH_PAYLOAD_BYTES} byte limit); it cannot be sent without a 413.`));
193
+ offset += 1;
194
+ continue;
195
+ }
189
196
  let batchBytes = 0;
190
197
  let batchEnd = offset;
191
198
  for (let i = offset; i < allEvents.length; i++) {
@@ -258,7 +265,7 @@ var SessionRecorder = class {
258
265
  this._takingSnapshot = false;
259
266
  }
260
267
  }
261
- const eventSize = JSON.stringify(event).length;
268
+ const eventSize = textEncoder.encode(JSON.stringify(event)).byteLength;
262
269
  this._events.push(event);
263
270
  this._eventSizes.push(eventSize);
264
271
  this._approxBytes += eventSize;
@@ -1 +1 @@
1
- {"version":3,"file":"session-replay.js","names":["KnownErrors","Result"],"sources":["../../../../../src/lib/hexclave-app/apps/implementations/session-replay.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY UNLESS YOU ALSO EDIT THE CORRESPONDING FILE IN packages/template\n//===========================================\nimport { KnownErrors } from \"@hexclave/shared/dist/known-errors\";\nimport { isBrowserLike } from \"@hexclave/shared/dist/utils/env\";\nimport { captureWarning, throwErr } from \"@hexclave/shared/dist/utils/errors\";\nimport { runAsynchronously } from \"@hexclave/shared/dist/utils/promises\";\nimport { Result } from \"@hexclave/shared/dist/utils/results\";\n\nexport type AnalyticsReplayOptions = {\n /**\n * Whether session replays are enabled.\n *\n * @default true\n */\n enabled?: boolean,\n /**\n * Whether to mask the content of all `<input>` elements.\n *\n * @default true\n */\n maskAllInputs?: boolean,\n /**\n * A CSS class name or RegExp. Elements with a matching class will be blocked\n * (replaced with a placeholder in the recording).\n *\n * @default undefined\n */\n blockClass?: string | RegExp,\n /**\n * A CSS selector string. Elements matching this selector will be blocked\n * (replaced with a placeholder in the recording).\n *\n * @default undefined\n */\n blockSelector?: string,\n};\n\nexport type AnalyticsOptions = {\n /**\n * Whether SDK-managed analytics capture is enabled.\n *\n * @default true\n */\n enabled?: boolean,\n /**\n * Options for session replay recording. Replays are enabled by default;\n * set `enabled: false` to opt out.\n */\n replays?: AnalyticsReplayOptions,\n};\n\nexport function getSessionReplayOptions(analyticsOptions: AnalyticsOptions | undefined): AnalyticsReplayOptions {\n return {\n ...analyticsOptions?.replays,\n enabled: analyticsOptions?.replays?.enabled ?? true,\n };\n}\n\n/**\n * Converts AnalyticsOptions to a JSON-safe representation.\n * RegExp blockClass values are serialized as `{ __regexp, __flags }` objects.\n * The return type is AnalyticsOptions to keep StackClientAppJson simple;\n * the actual runtime value is JSON-safe.\n */\nexport function analyticsOptionsToJson(options: AnalyticsOptions | undefined): AnalyticsOptions | undefined {\n if (!options?.replays?.blockClass) return options;\n const { blockClass, ...rest } = options.replays;\n if (!(blockClass instanceof RegExp)) return options;\n return {\n ...options,\n replays: {\n ...rest,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n blockClass: { __regexp: blockClass.source, __flags: blockClass.flags } as any,\n },\n };\n}\n\n/**\n * Reconstructs AnalyticsOptions from a JSON-deserialized value.\n * Converts `{ __regexp, __flags }` objects back to RegExp instances.\n */\nexport function analyticsOptionsFromJson(json: AnalyticsOptions | undefined): AnalyticsOptions | undefined {\n if (!json?.replays?.blockClass) return json;\n const { blockClass, ...rest } = json.replays;\n if (typeof blockClass === 'object' && '__regexp' in blockClass) {\n const bc = blockClass as unknown as { __regexp: string, __flags: string };\n return {\n ...json,\n replays: {\n ...rest,\n blockClass: new RegExp(bc.__regexp, bc.__flags),\n },\n };\n }\n return json;\n}\n\n// ---------- Recording internals ----------\n\n// Hexclave rebrand: canonical localStorage prefix (colon delimiters preserved).\nconst LOCAL_STORAGE_PREFIX = \"hexclave:session-replay:v1\";\n// Hexclave rebrand: legacy prefix — dual-read only, so a recording session active\n// across an SDK upgrade is not orphaned. Never written.\nconst LEGACY_LOCAL_STORAGE_PREFIX = \"stack:session-replay:v1\";\nconst IDLE_TTL_MS = 3 * 60 * 1000;\n\nconst FLUSH_INTERVAL_MS = 5_000;\nconst MAX_EVENTS_PER_BATCH = 200;\nconst MAX_APPROX_BYTES_PER_BATCH = 512_000;\n// The server rejects payloads > 1MB. Stay well under to account for JSON\n// envelope overhead (browser_session_id, timestamps, wrapper keys, etc.).\nconst MAX_FLUSH_PAYLOAD_BYTES = 900_000;\n\nexport type StoredSession = {\n session_id: string,\n created_at_ms: number,\n last_activity_ms: number,\n};\n\nexport function safeParseStoredSession(raw: string | null): StoredSession | null {\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw);\n if (typeof parsed !== \"object\" || parsed === null) return null;\n if (typeof parsed.session_id !== \"string\") return null;\n if (typeof parsed.created_at_ms !== \"number\") return null;\n if (typeof parsed.last_activity_ms !== \"number\") return null;\n return parsed as StoredSession;\n } catch {\n return null;\n }\n}\n\nexport function makeStorageKey(projectId: string) {\n return `${LOCAL_STORAGE_PREFIX}:${projectId}`;\n}\n\n// Hexclave rebrand: legacy key, dual-read only (never written).\nexport function makeLegacyStorageKey(projectId: string) {\n return `${LEGACY_LOCAL_STORAGE_PREFIX}:${projectId}`;\n}\n\nexport function generateUuid() {\n return crypto.randomUUID();\n}\n\nexport function getOrRotateSession(options: { key: string, legacyKey?: string, nowMs: number }): StoredSession {\n // Hexclave rebrand: prefer the new key; fall back to the legacy key so a\n // recording session active across an SDK upgrade is not orphaned.\n const existing = safeParseStoredSession(localStorage.getItem(options.key))\n ?? (options.legacyKey ? safeParseStoredSession(localStorage.getItem(options.legacyKey)) : null);\n if (existing && options.nowMs - existing.last_activity_ms <= IDLE_TTL_MS) {\n return existing;\n }\n const next: StoredSession = {\n session_id: generateUuid(),\n created_at_ms: options.nowMs,\n last_activity_ms: options.nowMs,\n };\n localStorage.setItem(options.key, JSON.stringify(next));\n return next;\n}\n\nexport type SessionRecorderDeps = {\n projectId: string,\n sendBatch: (body: string, options: { keepalive: boolean }) => Promise<Result<Response, Error>>,\n};\n\nexport function isAnalyticsNotEnabledError(error: unknown): boolean {\n return KnownErrors.AnalyticsNotEnabled.isInstance(error);\n}\n\n/**\n * Whether the error looks like a network failure caused by an ad blocker or\n * similar extension blocking analytics requests. These are expected in\n * production and should be silently ignored rather than logged as warnings.\n */\nexport function isAdBlockerNetworkError(error: unknown): boolean {\n if (error instanceof Error) {\n return error.message.includes(\"Failed to fetch\")\n || error.message.includes(\"NetworkError\")\n || error.message.includes(\"Load failed\")\n || error.message.includes(\"network connection\");\n }\n return false;\n}\n\nexport class SessionRecorder {\n private _started = false;\n private _cancelled = false;\n private _disabled = false;\n private _stopRecording: (() => void) | null = null;\n private _detachListeners: (() => void) | null = null;\n private _flushTimer: ReturnType<typeof setInterval> | null = null;\n private _events: unknown[] = [];\n private _eventSizes: number[] = [];\n private _approxBytes = 0;\n private _lastPersistActivity = 0;\n private _recording = false;\n private _rrwebModule: typeof import(\"rrweb\") | null = null;\n private _lastBrowserSessionId: string | null = null;\n private _takingSnapshot = false;\n private _flushInProgress = false;\n private readonly _sessionReplaySegmentId: string;\n private readonly _storageKey: string;\n // Hexclave rebrand: legacy key used for dual-read fallback only.\n private readonly _legacyStorageKey: string;\n private readonly _deps: SessionRecorderDeps;\n private readonly _replayOptions: AnalyticsReplayOptions;\n\n constructor(deps: SessionRecorderDeps, replayOptions: AnalyticsReplayOptions) {\n this._deps = deps;\n this._replayOptions = replayOptions;\n this._sessionReplaySegmentId = generateUuid();\n this._storageKey = makeStorageKey(deps.projectId);\n this._legacyStorageKey = makeLegacyStorageKey(deps.projectId);\n }\n\n /**\n * Starts recording. Idempotent — calling multiple times is safe.\n */\n start() {\n if (this._started) return;\n if (!isBrowserLike()) return;\n this._started = true;\n\n // Kick off rrweb recording\n runAsynchronously(() => this._startRecording(), { noErrorLogging: true });\n\n // Periodic flush\n this._flushTimer = setInterval(() => this._tick(), FLUSH_INTERVAL_MS);\n }\n\n stop() {\n this._cancelled = true;\n if (this._flushTimer !== null) {\n clearInterval(this._flushTimer);\n this._flushTimer = null;\n }\n // Flush remaining events before cleanup\n runAsynchronously(() => this._flush({ keepalive: true }));\n this._stopCurrentRecording();\n }\n\n clearBuffer() {\n this._events = [];\n this._eventSizes = [];\n this._approxBytes = 0;\n }\n\n private _persistActivity(nowMs: number): StoredSession {\n const stored = getOrRotateSession({ key: this._storageKey, legacyKey: this._legacyStorageKey, nowMs });\n if (nowMs - this._lastPersistActivity < 5_000) return stored;\n this._lastPersistActivity = nowMs;\n const updated: StoredSession = { ...stored, last_activity_ms: nowMs };\n localStorage.setItem(this._storageKey, JSON.stringify(updated));\n return stored;\n }\n\n private async _flush(options: { keepalive: boolean }) {\n if (this._disabled) return;\n if (this._events.length === 0) return;\n // Prevent concurrent in-flight HTTP requests. When a flush is already\n // in-flight, a second batch could race on the server (both call\n // findRecentSessionReplay before either upsert commits) and create\n // duplicate SessionReplay records. Events stay in _events and will be\n // picked up by the next tick or batch-size check.\n if (this._flushInProgress) return;\n\n const nowMs = Date.now();\n const stored = getOrRotateSession({ key: this._storageKey, legacyKey: this._legacyStorageKey, nowMs });\n\n // Capture all buffered events upfront (before any await) so that\n // stop() / _stopCurrentRecording() clearing this._events cannot race\n // with the async send loop below and silently discard overflow batches.\n const allEvents = this._events;\n const allSizes = this._eventSizes;\n this._events = [];\n this._eventSizes = [];\n this._approxBytes = 0;\n\n this._flushInProgress = true;\n try {\n let offset = 0;\n while (offset < allEvents.length) {\n // Build a batch that fits under the server's payload limit.\n // When _flushInProgress blocked earlier flushes, events can accumulate\n // well past MAX_APPROX_BYTES_PER_BATCH; sending them all at once would\n // exceed the server's 1MB body limit (413).\n let batchBytes = 0;\n let batchEnd = offset;\n for (let i = offset; i < allEvents.length; i++) {\n const nextSize = allSizes[i] ?? throwErr(\"_eventSizes out of sync with _events — this should never happen\");\n if (batchBytes + nextSize > MAX_FLUSH_PAYLOAD_BYTES && batchEnd > offset) break;\n batchBytes += nextSize;\n batchEnd = i + 1;\n }\n\n const batchEvents = allEvents.slice(offset, batchEnd);\n offset = batchEnd;\n\n const batchId = generateUuid();\n const payload = {\n browser_session_id: stored.session_id,\n session_replay_segment_id: this._sessionReplaySegmentId,\n batch_id: batchId,\n started_at_ms: stored.created_at_ms,\n sent_at_ms: nowMs,\n events: batchEvents,\n };\n\n const res = await this._deps.sendBatch(\n JSON.stringify(payload),\n { keepalive: options.keepalive },\n );\n\n if (res.status === \"error\") {\n if (isAnalyticsNotEnabledError(res.error)) {\n this._disable();\n return;\n }\n // Ad blockers commonly block analytics endpoints, causing network\n // errors. These are expected and should not pollute the console.\n if (isAdBlockerNetworkError(res.error)) {\n return;\n }\n captureWarning(\"SessionRecorder.flush\", res.error);\n return;\n }\n\n if (!res.data.ok) {\n captureWarning(\"SessionRecorder.flush\", new Error(`SessionRecorder flush failed: ${res.data.status} ${await res.data.text()}`));\n return;\n }\n }\n } finally {\n this._flushInProgress = false;\n }\n }\n\n private _disable() {\n this._disabled = true;\n this.clearBuffer();\n if (this._flushTimer !== null) {\n clearInterval(this._flushTimer);\n this._flushTimer = null;\n }\n this._stopCurrentRecording();\n }\n\n private async _startRecording() {\n if (this._recording || this._cancelled) return;\n\n if (!this._rrwebModule) {\n const rrwebImport = await Result.fromPromise(import(\"rrweb\"));\n if (rrwebImport.status === \"error\") {\n console.warn(\"SessionRecorder: rrweb import failed. Is rrweb installed?\", rrwebImport.error);\n return;\n }\n this._rrwebModule = rrwebImport.data;\n }\n\n // cancelled may change during the await above\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (this._cancelled) return;\n\n this._stopRecording = this._rrwebModule.record({\n emit: (event) => {\n const nowMs = Date.now();\n const stored = this._persistActivity(nowMs);\n\n // Detect session rotation: after 3+ minutes idle, getOrRotateSession\n // creates a new session ID. We need to inject a FullSnapshot so the\n // new server-side SessionReplay record is playable.\n if (this._lastBrowserSessionId === null) {\n this._lastBrowserSessionId = stored.session_id;\n } else if (stored.session_id !== this._lastBrowserSessionId && !this._takingSnapshot) {\n this._lastBrowserSessionId = stored.session_id;\n // Inject a FullSnapshot for the new session (calls emit synchronously)\n this._takingSnapshot = true;\n try {\n this._rrwebModule!.record.takeFullSnapshot();\n } finally {\n this._takingSnapshot = false;\n }\n }\n\n const eventSize = JSON.stringify(event).length;\n this._events.push(event);\n this._eventSizes.push(eventSize);\n this._approxBytes += eventSize;\n if (this._events.length >= MAX_EVENTS_PER_BATCH || this._approxBytes >= MAX_APPROX_BYTES_PER_BATCH) {\n runAsynchronously(() => this._flush({ keepalive: false }));\n }\n },\n maskAllInputs: this._replayOptions.maskAllInputs ?? true,\n ...(this._replayOptions.blockClass !== undefined ? { blockClass: this._replayOptions.blockClass } : {}),\n ...(this._replayOptions.blockSelector !== undefined ? { blockSelector: this._replayOptions.blockSelector } : {}),\n }) ?? null;\n\n this._recording = true;\n\n const onPageHide = () => {\n runAsynchronously(() => this._flush({ keepalive: true }));\n };\n window.addEventListener(\"pagehide\", onPageHide);\n document.addEventListener(\"visibilitychange\", onPageHide);\n this._detachListeners = () => {\n window.removeEventListener(\"pagehide\", onPageHide);\n document.removeEventListener(\"visibilitychange\", onPageHide);\n };\n }\n\n private _stopCurrentRecording() {\n if (this._detachListeners) {\n this._detachListeners();\n this._detachListeners = null;\n }\n if (this._stopRecording) {\n this._stopRecording();\n this._stopRecording = null;\n }\n this._events = [];\n this._eventSizes = [];\n this._approxBytes = 0;\n this._recording = false;\n }\n\n private _tick() {\n if (this._cancelled) return;\n if (this._events.length > 0) {\n runAsynchronously(() => this._flush({ keepalive: false }));\n }\n }\n}\n"],"mappings":";;;;;;;;;AAqDA,SAAgB,wBAAwB,kBAAwE;AAC9G,QAAO;EACL,GAAG,kBAAkB;EACrB,SAAS,kBAAkB,SAAS,WAAW;EAChD;;;;;;;;AASH,SAAgB,uBAAuB,SAAqE;AAC1G,KAAI,CAAC,SAAS,SAAS,WAAY,QAAO;CAC1C,MAAM,EAAE,YAAY,GAAG,SAAS,QAAQ;AACxC,KAAI,EAAE,sBAAsB,QAAS,QAAO;AAC5C,QAAO;EACL,GAAG;EACH,SAAS;GACP,GAAG;GAEH,YAAY;IAAE,UAAU,WAAW;IAAQ,SAAS,WAAW;IAAO;GACvE;EACF;;;;;;AAOH,SAAgB,yBAAyB,MAAkE;AACzG,KAAI,CAAC,MAAM,SAAS,WAAY,QAAO;CACvC,MAAM,EAAE,YAAY,GAAG,SAAS,KAAK;AACrC,KAAI,OAAO,eAAe,YAAY,c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e,YAAY,GAAG,EAAE;GACtG,GAAI,KAAK,eAAe,kBAAkB,SAAY,EAAE,eAAe,KAAK,eAAe,eAAe,GAAG,EAAE;GAChH,CAAC,IAAI;AAEN,OAAK,aAAa;EAElB,MAAM,mBAAmB;AACvB,qEAAwB,KAAK,OAAO,EAAE,WAAW,MAAM,CAAC,CAAC;;AAE3D,SAAO,iBAAiB,YAAY,WAAW;AAC/C,WAAS,iBAAiB,oBAAoB,WAAW;AACzD,OAAK,yBAAyB;AAC5B,UAAO,oBAAoB,YAAY,WAAW;AAClD,YAAS,oBAAoB,oBAAoB,WAAW;;;CAIhE,AAAQ,wBAAwB;AAC9B,MAAI,KAAK,kBAAkB;AACzB,QAAK,kBAAkB;AACvB,QAAK,mBAAmB;;AAE1B,MAAI,KAAK,gBAAgB;AACvB,QAAK,gBAAgB;AACrB,QAAK,iBAAiB;;AAExB,OAAK,UAAU,EAAE;AACjB,OAAK,cAAc,EAAE;AACrB,OAAK,eAAe;AACpB,OAAK,aAAa;;CAGpB,AAAQ,QAAQ;AACd,MAAI,KAAK,WAAY;AACrB,MAAI,KAAK,QAAQ,SAAS,EACxB,mEAAwB,KAAK,OAAO,EAAE,WAAW,OAAO,CAAC,CAAC"}
1
+ {"version":3,"file":"session-replay.js","names":["KnownErrors","Result"],"sources":["../../../../../src/lib/hexclave-app/apps/implementations/session-replay.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY UNLESS YOU ALSO EDIT THE CORRESPONDING FILE IN packages/template\n//===========================================\nimport { KnownErrors } from \"@hexclave/shared/dist/known-errors\";\nimport { isBrowserLike } from \"@hexclave/shared/dist/utils/env\";\nimport { captureWarning, throwErr } from \"@hexclave/shared/dist/utils/errors\";\nimport { runAsynchronously } from \"@hexclave/shared/dist/utils/promises\";\nimport { Result } from \"@hexclave/shared/dist/utils/results\";\n\nexport type AnalyticsReplayOptions = {\n /**\n * Whether session replays are enabled.\n *\n * @default true\n */\n enabled?: boolean,\n /**\n * Whether to mask the content of all `<input>` elements.\n *\n * @default true\n */\n maskAllInputs?: boolean,\n /**\n * A CSS class name or RegExp. Elements with a matching class will be blocked\n * (replaced with a placeholder in the recording).\n *\n * @default undefined\n */\n blockClass?: string | RegExp,\n /**\n * A CSS selector string. Elements matching this selector will be blocked\n * (replaced with a placeholder in the recording).\n *\n * @default undefined\n */\n blockSelector?: string,\n};\n\nexport type AnalyticsOptions = {\n /**\n * Whether SDK-managed analytics capture is enabled.\n *\n * @default true\n */\n enabled?: boolean,\n /**\n * Options for session replay recording. Replays are enabled by default;\n * set `enabled: false` to opt out.\n */\n replays?: AnalyticsReplayOptions,\n};\n\nexport function getSessionReplayOptions(analyticsOptions: AnalyticsOptions | undefined): AnalyticsReplayOptions {\n return {\n ...analyticsOptions?.replays,\n enabled: analyticsOptions?.replays?.enabled ?? true,\n };\n}\n\n/**\n * Converts AnalyticsOptions to a JSON-safe representation.\n * RegExp blockClass values are serialized as `{ __regexp, __flags }` objects.\n * The return type is AnalyticsOptions to keep StackClientAppJson simple;\n * the actual runtime value is JSON-safe.\n */\nexport function analyticsOptionsToJson(options: AnalyticsOptions | undefined): AnalyticsOptions | undefined {\n if (!options?.replays?.blockClass) return options;\n const { blockClass, ...rest } = options.replays;\n if (!(blockClass instanceof RegExp)) return options;\n return {\n ...options,\n replays: {\n ...rest,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n blockClass: { __regexp: blockClass.source, __flags: blockClass.flags } as any,\n },\n };\n}\n\n/**\n * Reconstructs AnalyticsOptions from a JSON-deserialized value.\n * Converts `{ __regexp, __flags }` objects back to RegExp instances.\n */\nexport function analyticsOptionsFromJson(json: AnalyticsOptions | undefined): AnalyticsOptions | undefined {\n if (!json?.replays?.blockClass) return json;\n const { blockClass, ...rest } = json.replays;\n if (typeof blockClass === 'object' && '__regexp' in blockClass) {\n const bc = blockClass as unknown as { __regexp: string, __flags: string };\n return {\n ...json,\n replays: {\n ...rest,\n blockClass: new RegExp(bc.__regexp, bc.__flags),\n },\n };\n }\n return json;\n}\n\n// ---------- Recording internals ----------\n\n// Hexclave rebrand: canonical localStorage prefix (colon delimiters preserved).\nconst LOCAL_STORAGE_PREFIX = \"hexclave:session-replay:v1\";\n// Hexclave rebrand: legacy prefix — dual-read only, so a recording session active\n// across an SDK upgrade is not orphaned. Never written.\nconst LEGACY_LOCAL_STORAGE_PREFIX = \"stack:session-replay:v1\";\nconst IDLE_TTL_MS = 3 * 60 * 1000;\n\nconst FLUSH_INTERVAL_MS = 5_000;\nconst MAX_EVENTS_PER_BATCH = 200;\nconst MAX_APPROX_BYTES_PER_BATCH = 512_000;\n// The server rejects payloads > 1MB. Stay well under to account for JSON\n// envelope overhead (browser_session_id, timestamps, wrapper keys, etc.).\nconst MAX_FLUSH_PAYLOAD_BYTES = 900_000;\n\n// Reused across the emit hot path to avoid per-event allocation.\nconst textEncoder = new TextEncoder();\n\nexport type StoredSession = {\n session_id: string,\n created_at_ms: number,\n last_activity_ms: number,\n};\n\nexport function safeParseStoredSession(raw: string | null): StoredSession | null {\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw);\n if (typeof parsed !== \"object\" || parsed === null) return null;\n if (typeof parsed.session_id !== \"string\") return null;\n if (typeof parsed.created_at_ms !== \"number\") return null;\n if (typeof parsed.last_activity_ms !== \"number\") return null;\n return parsed as StoredSession;\n } catch {\n return null;\n }\n}\n\nexport function makeStorageKey(projectId: string) {\n return `${LOCAL_STORAGE_PREFIX}:${projectId}`;\n}\n\n// Hexclave rebrand: legacy key, dual-read only (never written).\nexport function makeLegacyStorageKey(projectId: string) {\n return `${LEGACY_LOCAL_STORAGE_PREFIX}:${projectId}`;\n}\n\nexport function generateUuid() {\n return crypto.randomUUID();\n}\n\nexport function getOrRotateSession(options: { key: string, legacyKey?: string, nowMs: number }): StoredSession {\n // Hexclave rebrand: prefer the new key; fall back to the legacy key so a\n // recording session active across an SDK upgrade is not orphaned.\n const existing = safeParseStoredSession(localStorage.getItem(options.key))\n ?? (options.legacyKey ? safeParseStoredSession(localStorage.getItem(options.legacyKey)) : null);\n if (existing && options.nowMs - existing.last_activity_ms <= IDLE_TTL_MS) {\n return existing;\n }\n const next: StoredSession = {\n session_id: generateUuid(),\n created_at_ms: options.nowMs,\n last_activity_ms: options.nowMs,\n };\n localStorage.setItem(options.key, JSON.stringify(next));\n return next;\n}\n\nexport type SessionRecorderDeps = {\n projectId: string,\n sendBatch: (body: string, options: { keepalive: boolean }) => Promise<Result<Response, Error>>,\n};\n\nexport function isAnalyticsNotEnabledError(error: unknown): boolean {\n return KnownErrors.AnalyticsNotEnabled.isInstance(error);\n}\n\n/**\n * Whether the error looks like a network failure caused by an ad blocker or\n * similar extension blocking analytics requests. These are expected in\n * production and should be silently ignored rather than logged as warnings.\n */\nexport function isAdBlockerNetworkError(error: unknown): boolean {\n if (error instanceof Error) {\n return error.message.includes(\"Failed to fetch\")\n || error.message.includes(\"NetworkError\")\n || error.message.includes(\"Load failed\")\n || error.message.includes(\"network connection\");\n }\n return false;\n}\n\nexport class SessionRecorder {\n private _started = false;\n private _cancelled = false;\n private _disabled = false;\n private _stopRecording: (() => void) | null = null;\n private _detachListeners: (() => void) | null = null;\n private _flushTimer: ReturnType<typeof setInterval> | null = null;\n private _events: unknown[] = [];\n private _eventSizes: number[] = [];\n private _approxBytes = 0;\n private _lastPersistActivity = 0;\n private _recording = false;\n private _rrwebModule: typeof import(\"rrweb\") | null = null;\n private _lastBrowserSessionId: string | null = null;\n private _takingSnapshot = false;\n private _flushInProgress = false;\n private readonly _sessionReplaySegmentId: string;\n private readonly _storageKey: string;\n // Hexclave rebrand: legacy key used for dual-read fallback only.\n private readonly _legacyStorageKey: string;\n private readonly _deps: SessionRecorderDeps;\n private readonly _replayOptions: AnalyticsReplayOptions;\n\n constructor(deps: SessionRecorderDeps, replayOptions: AnalyticsReplayOptions) {\n this._deps = deps;\n this._replayOptions = replayOptions;\n this._sessionReplaySegmentId = generateUuid();\n this._storageKey = makeStorageKey(deps.projectId);\n this._legacyStorageKey = makeLegacyStorageKey(deps.projectId);\n }\n\n /**\n * Starts recording. Idempotent — calling multiple times is safe.\n */\n start() {\n if (this._started) return;\n if (!isBrowserLike()) return;\n this._started = true;\n\n // Kick off rrweb recording\n runAsynchronously(() => this._startRecording(), { noErrorLogging: true });\n\n // Periodic flush\n this._flushTimer = setInterval(() => this._tick(), FLUSH_INTERVAL_MS);\n }\n\n stop() {\n this._cancelled = true;\n if (this._flushTimer !== null) {\n clearInterval(this._flushTimer);\n this._flushTimer = null;\n }\n // Flush remaining events before cleanup\n runAsynchronously(() => this._flush({ keepalive: true }));\n this._stopCurrentRecording();\n }\n\n clearBuffer() {\n this._events = [];\n this._eventSizes = [];\n this._approxBytes = 0;\n }\n\n private _persistActivity(nowMs: number): StoredSession {\n const stored = getOrRotateSession({ key: this._storageKey, legacyKey: this._legacyStorageKey, nowMs });\n if (nowMs - this._lastPersistActivity < 5_000) return stored;\n this._lastPersistActivity = nowMs;\n const updated: StoredSession = { ...stored, last_activity_ms: nowMs };\n localStorage.setItem(this._storageKey, JSON.stringify(updated));\n return stored;\n }\n\n private async _flush(options: { keepalive: boolean }) {\n if (this._disabled) return;\n if (this._events.length === 0) return;\n // Prevent concurrent in-flight HTTP requests. When a flush is already\n // in-flight, a second batch could race on the server (both call\n // findRecentSessionReplay before either upsert commits) and create\n // duplicate SessionReplay records. Events stay in _events and will be\n // picked up by the next tick or batch-size check.\n if (this._flushInProgress) return;\n\n const nowMs = Date.now();\n const stored = getOrRotateSession({ key: this._storageKey, legacyKey: this._legacyStorageKey, nowMs });\n\n // Capture all buffered events upfront (before any await) so that\n // stop() / _stopCurrentRecording() clearing this._events cannot race\n // with the async send loop below and silently discard overflow batches.\n const allEvents = this._events;\n const allSizes = this._eventSizes;\n this._events = [];\n this._eventSizes = [];\n this._approxBytes = 0;\n\n this._flushInProgress = true;\n try {\n let offset = 0;\n while (offset < allEvents.length) {\n // Build a batch that fits under the server's payload limit.\n // When _flushInProgress blocked earlier flushes, events can accumulate\n // well past MAX_APPROX_BYTES_PER_BATCH; sending them all at once would\n // exceed the server's 1MB body limit (413).\n // A single event over the limit can't be sent (rrweb events aren't splittable); drop it and move on.\n const firstSize = allSizes[offset] ?? throwErr(\"_eventSizes out of sync with _events — this should never happen\");\n if (firstSize > MAX_FLUSH_PAYLOAD_BYTES) {\n captureWarning(\n \"SessionRecorder.flush\",\n new Error(`Dropping oversized session replay event (${firstSize} bytes > ${MAX_FLUSH_PAYLOAD_BYTES} byte limit); it cannot be sent without a 413.`),\n );\n offset += 1;\n continue;\n }\n\n let batchBytes = 0;\n let batchEnd = offset;\n for (let i = offset; i < allEvents.length; i++) {\n const nextSize = allSizes[i] ?? throwErr(\"_eventSizes out of sync with _events — this should never happen\");\n if (batchBytes + nextSize > MAX_FLUSH_PAYLOAD_BYTES && batchEnd > offset) break;\n batchBytes += nextSize;\n batchEnd = i + 1;\n }\n\n const batchEvents = allEvents.slice(offset, batchEnd);\n offset = batchEnd;\n\n const batchId = generateUuid();\n const payload = {\n browser_session_id: stored.session_id,\n session_replay_segment_id: this._sessionReplaySegmentId,\n batch_id: batchId,\n started_at_ms: stored.created_at_ms,\n sent_at_ms: nowMs,\n events: batchEvents,\n };\n\n const res = await this._deps.sendBatch(\n JSON.stringify(payload),\n { keepalive: options.keepalive },\n );\n\n if (res.status === \"error\") {\n if (isAnalyticsNotEnabledError(res.error)) {\n this._disable();\n return;\n }\n // Ad blockers commonly block analytics endpoints, causing network\n // errors. These are expected and should not pollute the console.\n if (isAdBlockerNetworkError(res.error)) {\n return;\n }\n captureWarning(\"SessionRecorder.flush\", res.error);\n return;\n }\n\n if (!res.data.ok) {\n captureWarning(\"SessionRecorder.flush\", new Error(`SessionRecorder flush failed: ${res.data.status} ${await res.data.text()}`));\n return;\n }\n }\n } finally {\n this._flushInProgress = false;\n }\n }\n\n private _disable() {\n this._disabled = true;\n this.clearBuffer();\n if (this._flushTimer !== null) {\n clearInterval(this._flushTimer);\n this._flushTimer = null;\n }\n this._stopCurrentRecording();\n }\n\n private async _startRecording() {\n if (this._recording || this._cancelled) return;\n\n if (!this._rrwebModule) {\n const rrwebImport = await Result.fromPromise(import(\"rrweb\"));\n if (rrwebImport.status === \"error\") {\n console.warn(\"SessionRecorder: rrweb import failed. Is rrweb installed?\", rrwebImport.error);\n return;\n }\n this._rrwebModule = rrwebImport.data;\n }\n\n // cancelled may change during the await above\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (this._cancelled) return;\n\n this._stopRecording = this._rrwebModule.record({\n emit: (event) => {\n const nowMs = Date.now();\n const stored = this._persistActivity(nowMs);\n\n // Detect session rotation: after 3+ minutes idle, getOrRotateSession\n // creates a new session ID. We need to inject a FullSnapshot so the\n // new server-side SessionReplay record is playable.\n if (this._lastBrowserSessionId === null) {\n this._lastBrowserSessionId = stored.session_id;\n } else if (stored.session_id !== this._lastBrowserSessionId && !this._takingSnapshot) {\n this._lastBrowserSessionId = stored.session_id;\n // Inject a FullSnapshot for the new session (calls emit synchronously)\n this._takingSnapshot = true;\n try {\n this._rrwebModule!.record.takeFullSnapshot();\n } finally {\n this._takingSnapshot = false;\n }\n }\n\n // Measure UTF-8 byte length to match the server's byte limit (.length counts UTF-16 units, undercounting multibyte content).\n const eventSize = textEncoder.encode(JSON.stringify(event)).byteLength;\n this._events.push(event);\n this._eventSizes.push(eventSize);\n this._approxBytes += eventSize;\n if (this._events.length >= MAX_EVENTS_PER_BATCH || this._approxBytes >= MAX_APPROX_BYTES_PER_BATCH) {\n runAsynchronously(() => this._flush({ keepalive: false }));\n }\n },\n maskAllInputs: this._replayOptions.maskAllInputs ?? true,\n ...(this._replayOptions.blockClass !== undefined ? { blockClass: this._replayOptions.blockClass } : {}),\n ...(this._replayOptions.blockSelector !== undefined ? { blockSelector: this._replayOptions.blockSelector } : {}),\n }) ?? null;\n\n this._recording = true;\n\n const onPageHide = () => {\n runAsynchronously(() => this._flush({ keepalive: true }));\n };\n window.addEventListener(\"pagehide\", onPageHide);\n document.addEventListener(\"visibilitychange\", onPageHide);\n this._detachListeners = () => {\n window.removeEventListener(\"pagehide\", onPageHide);\n document.removeEventListener(\"visibilitychange\", onPageHide);\n };\n }\n\n private _stopCurrentRecording() {\n if (this._detachListeners) {\n this._detachListeners();\n this._detachListeners = null;\n }\n if (this._stopRecording) {\n this._stopRecording();\n this._stopRecording = null;\n }\n this._events = [];\n this._eventSizes = [];\n this._approxBytes = 0;\n this._recording = false;\n }\n\n private _tick() {\n if (this._cancelled) return;\n if (this._events.length > 0) {\n runAsynchronously(() => this._flush({ keepalive: false }));\n }\n }\n}\n"],"mappings":";;;;;;;;;AAqDA,SAAgB,wBAAwB,kBAAwE;AAC9G,QAAO;EACL,GAAG,kBAAkB;EACrB,SAAS,kBAAkB,SAAS,WAAW;EAChD;;;;;;;;AASH,SAAgB,uBAAuB,SAAqE;AAC1G,KAAI,CAAC,SAAS,SAAS,WAAY,QAAO;CAC1C,MAAM,EAAE,YAAY,GAAG,SAAS,QAAQ;AACxC,KAAI,EAAE,sBAAsB,QAAS,QAAO;AAC5C,QAAO;EACL,GAAG;EACH,SAAS;GACP,GAAG;GAEH,YAAY;IAAE,UAAU,WAAW;IAAQ,SAAS,WAAW;IAAO;GACvE;EACF;;;;;;AAOH,SAAgB,yBAAyB,MAAkE;AACzG,KAAI,CAAC,MAAM,SAAS,WAAY,QAAO;CACvC,MAAM,EAAE,YAAY,GAAG,SAAS,KAAK;AACrC,KAAI,OAAO,eAAe,YAAY,cAAc,YAAY;EAC9D,MAAM,KAAK;AACX,SAAO;GACL,GAAG;GACH,SAAS;IACP,GAAG;IACH,YAAY,IAAI,OAAO,GAAG,UAAU,GAAG,QAAQ;IAChD;GACF;;AAEH,QAAO;;AAMT,MAAM,uBAAuB;AAG7B,MAAM,8BAA8B;AACpC,MAAM,cAAc,MAAS;AAE7B,MAAM,oBAAoB;AAC1B,MAAM,uBAAuB;AAC7B,MAAM,6BAA6B;AAGnC,MAAM,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