UNPKG

@whop/api

Version:
1,600 lines (1,554 loc) 76 kB
var __defProp = Object.defineProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; // src/verify-user-token.ts import { importJWK, jwtVerify } from "jose"; var USER_TOKEN_HEADER_NAME = "x-whop-user-token"; var USER_TOKEN_VERIFICATION_KEY = '{"kty":"EC","x":"rz8a8vxvexHC0TLT91g7llOdDOsNuYiGEfic4Qhni-E","y":"zH0QblKYToexd5PEIMGXPVJS9AB5smKrW4S_TbiXrOs","crv":"P-256"}'; function getUserToken(tokenOrHeadersOrRequest) { if (typeof tokenOrHeadersOrRequest === "string") return tokenOrHeadersOrRequest; if (tokenOrHeadersOrRequest instanceof Headers) return tokenOrHeadersOrRequest.get(USER_TOKEN_HEADER_NAME); if (tokenOrHeadersOrRequest instanceof Request) return tokenOrHeadersOrRequest.headers.get(USER_TOKEN_HEADER_NAME); return null; } function makeUserTokenVerifier(options) { return async function verifyUserToken2(tokenOrHeadersOrRequest, overrideOptions) { return await internalVerifyUserToken(tokenOrHeadersOrRequest, { ...options, ...overrideOptions }); }; } function verifyUserToken(tokenOrHeadersOrRequest, overrideOptions) { return internalVerifyUserToken(tokenOrHeadersOrRequest, { ...overrideOptions }); } async function internalVerifyUserToken(tokenOrHeadersOrRequest, options) { try { const tokenString = getUserToken(tokenOrHeadersOrRequest); if (!tokenString) { throw new Error( "Whop user token not found. If you are the app developer, ensure you are developing in the whop.com iframe and have the dev proxy enabled." ); } const jwkString = options.publicKey ?? USER_TOKEN_VERIFICATION_KEY; const key = await importJWK(JSON.parse(jwkString), "ES256").catch(() => { throw new Error("Invalid public key provided to verifyUserToken"); }); const token = await jwtVerify(tokenString, key, { issuer: "urn:whopcom:exp-proxy" }).catch((_e) => { throw new Error("Invalid user token provided to verifyUserToken"); }); if (!(token.payload.sub && token.payload.aud) || Array.isArray(token.payload.aud)) { throw new Error("Invalid user token provided to verifyUserToken"); } if (options.appId && token.payload.aud !== options.appId) throw new Error("Invalid app id provided to verifyUserToken"); return { appId: token.payload.aud, userId: token.payload.sub }; } catch (e) { if (options.dontThrow) { return null; } throw e; } } // src/codegen/proto/index.ts var proto_exports = {}; __export(proto_exports, { bounties_app: () => index_bounties_app_exports, calendar_bookings_app: () => index_calendar_bookings_app_exports, common: () => index_common_exports, content_app: () => index_content_app_exports, content_rewards_app: () => index_content_rewards_app_exports, courses_app: () => index_courses_app_exports, data_platform: () => index_data_platform_exports, events_app: () => index_events_app_exports, experience: () => index_experience_exports, games: () => index_games_exports, google: () => index_google_exports, wheel_app: () => index_wheel_app_exports }); // src/codegen/proto/index.common.ts var index_common_exports = {}; __export(index_common_exports, { AccessPassExperience_UpsellType: () => AccessPassExperience_UpsellType, AccessPass_AccessPassType: () => AccessPass_AccessPassType, AccessPass_Visibility: () => AccessPass_Visibility, AccessType: () => AccessType, ActiveUserBucket_UserBucketType: () => ActiveUserBucket_UserBucketType, AppBuild_Status: () => AppBuild_Status, AppViewType: () => AppViewType, BusinessActivityEvent_EventType: () => BusinessActivityEvent_EventType, ChannelSubscriptionState_DisconnectionReason: () => ChannelSubscriptionState_DisconnectionReason, Channel_Type: () => Channel_Type, ConnectedId_Type: () => ConnectedId_Type, Entry_EntryStatus: () => Entry_EntryStatus, FeedChatFeed_MemberPermissionType: () => FeedChatFeed_MemberPermissionType, FeedDmsFeedMember_DmsFeedMemberStatus: () => FeedDmsFeedMember_DmsFeedMemberStatus, FeedDmsFeedMember_NotificationPreference: () => FeedDmsFeedMember_NotificationPreference, FeedDmsPost_MessageType: () => FeedDmsPost_MessageType, FeedForumFeed_EmailNotificationPreferenceType: () => FeedForumFeed_EmailNotificationPreferenceType, FeedForumFeed_LayoutType: () => FeedForumFeed_LayoutType, FeedForumFeed_MemberPermissionType: () => FeedForumFeed_MemberPermissionType, FeedForumPost_ForumPostType: () => FeedForumPost_ForumPostType, FeedLivestreamFeed_MemberPermissionType: () => FeedLivestreamFeed_MemberPermissionType, FeedReaction_ReactionType: () => FeedReaction_ReactionType, GetTopExperiencesByActiveUsersRequest_AppFilter: () => GetTopExperiencesByActiveUsersRequest_AppFilter, GoFetchNotifications_NotifyingEntityType: () => GoFetchNotifications_NotifyingEntityType, MuxAsset_MuxAssetStatus: () => MuxAsset_MuxAssetStatus, Plan_PlanType: () => Plan_PlanType, Plan_ReleaseMethod: () => Plan_ReleaseMethod, Plan_Visibility: () => Plan_Visibility, Platform: () => Platform, Position_Type: () => Position_Type, PostReactionCount_ReactionType: () => PostReactionCount_ReactionType, ProductSurface_DiscoverSection: () => ProductSurface_DiscoverSection, ProductSurface_FeedTab: () => ProductSurface_FeedTab, ProductSurface_SurfaceType: () => ProductSurface_SurfaceType, ProductSurface_ViewContext: () => ProductSurface_ViewContext, Purchase_ReleaseMethod: () => Purchase_ReleaseMethod, ResourceType: () => ResourceType, UserType: () => UserType, User_PlatformRole: () => User_PlatformRole }); // src/codegen/proto/common/users.ts var UserType = { UNKNOWN_TYPE: "UNKNOWN_TYPE", HUMAN: "HUMAN", SYSTEM: "SYSTEM", AGENT: "AGENT", UNRECOGNIZED: "UNRECOGNIZED" }; var User_PlatformRole = { UNKNOWN_ROLE: "UNKNOWN_ROLE", SUPER_ADMIN: "SUPER_ADMIN", ADMIN: "ADMIN", TRUST_AND_SAFETY_MANAGER: "TRUST_AND_SAFETY_MANAGER", MANAGER: "MANAGER", SUPPORT: "SUPPORT", TESTER: "TESTER", SEO_MANAGER: "SEO_MANAGER", TEMPLATE_USER: "TEMPLATE_USER", MARKETPLACE_MANAGER: "MARKETPLACE_MANAGER", DEVELOPER: "DEVELOPER", FINANCE_MANAGER: "FINANCE_MANAGER", RESOLUTION_CENTER_MANAGER: "RESOLUTION_CENTER_MANAGER", UNRECOGNIZED: "UNRECOGNIZED" }; // src/codegen/proto/common/common.ts var AppViewType = { APP_VIEW_TYPE_UNKNOWN: "APP_VIEW_TYPE_UNKNOWN", APP_VIEW_TYPE_HUB: "APP_VIEW_TYPE_HUB", APP_VIEW_TYPE_DASH: "APP_VIEW_TYPE_DASH", APP_VIEW_TYPE_ANALYTICS: "APP_VIEW_TYPE_ANALYTICS", UNRECOGNIZED: "UNRECOGNIZED" }; var AccessType = { UNKNOWN_ACCESS_TYPE: "UNKNOWN_ACCESS_TYPE", NO_ACCESS: "NO_ACCESS", CUSTOMER: "CUSTOMER", ADMIN: "ADMIN", UNRECOGNIZED: "UNRECOGNIZED" }; var Platform = { UNKNOWN: "UNKNOWN", WEB: "WEB", IOS: "IOS", ANDROID: "ANDROID", UNRECOGNIZED: "UNRECOGNIZED" }; var AppBuild_Status = { STATUS_UNKNOWN: "STATUS_UNKNOWN", STATUS_DRAFT: "STATUS_DRAFT", STATUS_PENDING: "STATUS_PENDING", STATUS_APPROVED: "STATUS_APPROVED", STATUS_REJECTED: "STATUS_REJECTED", UNRECOGNIZED: "UNRECOGNIZED" }; var AccessPass_Visibility = { VISIBILITY_UNKNOWN: "VISIBILITY_UNKNOWN", VISIBLE: "VISIBLE", HIDDEN: "HIDDEN", ARCHIVED: "ARCHIVED", QUICK_LINK: "QUICK_LINK", UNRECOGNIZED: "UNRECOGNIZED" }; var AccessPass_AccessPassType = { ACCESS_PASS_TYPE_UNKNOWN: "ACCESS_PASS_TYPE_UNKNOWN", REGULAR: "REGULAR", APP: "APP", EXPERIENCE_UPSELL: "EXPERIENCE_UPSELL", UNRECOGNIZED: "UNRECOGNIZED" }; var Plan_Visibility = { VISIBILITY_UNKNOWN: "VISIBILITY_UNKNOWN", VISIBLE: "VISIBLE", HIDDEN: "HIDDEN", ARCHIVED: "ARCHIVED", QUICK_LINK: "QUICK_LINK", UNRECOGNIZED: "UNRECOGNIZED" }; var Plan_ReleaseMethod = { RELEASE_METHOD_UNKNOWN: "RELEASE_METHOD_UNKNOWN", BUY_NOW: "BUY_NOW", WAITLIST: "WAITLIST", RAFFLE: "RAFFLE", UNRECOGNIZED: "UNRECOGNIZED" }; var Plan_PlanType = { PLAN_TYPE_UNKNOWN: "PLAN_TYPE_UNKNOWN", RENEWAL: "RENEWAL", ONE_TIME: "ONE_TIME", UNRECOGNIZED: "UNRECOGNIZED" }; var Entry_EntryStatus = { ENTRY_STATUS_UNKNOWN: "ENTRY_STATUS_UNKNOWN", PENDING: "PENDING", APPROVED: "APPROVED", DENIED: "DENIED", UNRECOGNIZED: "UNRECOGNIZED" }; var AccessPassExperience_UpsellType = { UPSELL_TYPE_UNKNOWN: "UPSELL_TYPE_UNKNOWN", BEFORE_CHECKOUT: "BEFORE_CHECKOUT", AFTER_CHECKOUT: "AFTER_CHECKOUT", ONLY_IN_WHOP: "ONLY_IN_WHOP", UNRECOGNIZED: "UNRECOGNIZED" }; var Purchase_ReleaseMethod = { UNKNOWN: "UNKNOWN", BUY_NOW: "BUY_NOW", WAITLIST: "WAITLIST", UNRECOGNIZED: "UNRECOGNIZED" }; var ConnectedId_Type = { UNKNOWN: "UNKNOWN", ANONYMOUS: "ANONYMOUS", USER: "USER", UNRECOGNIZED: "UNRECOGNIZED" }; var Channel_Type = { UNKNOWN: "UNKNOWN", /** EXPERIENCE - / A channel to which all users of an experience are subscribed, only when vieweing that experience in the UI. The ID is the experience.tag (exp_XXXXX) */ EXPERIENCE: "EXPERIENCE", /** NOTIFICATIONS - / Not used right now. */ NOTIFICATIONS: "NOTIFICATIONS", /** DMS - / A channel to which all users in a dms_feed are subscribed. Id is the dms_feed.external_id (feed_XXXXX) */ DMS: "DMS", /** USER - / A channel to which a single user is subscribed. (Id is the user's id) */ USER: "USER", /** EVERYONE - / A single channel to which all connections are subscribed. (Id is empty) */ EVERYONE: "EVERYONE", /** AUTHENTICATED - / A single channel to which all authenticated users are subscribed. (Id is empty) */ AUTHENTICATED: "AUTHENTICATED", /** ANONYMOUS - / A channel that is created for every anonymous connection. The id is 128bits of random data. */ ANONYMOUS: "ANONYMOUS", /** PUBLIC - / A channel type that can be connected to by anyone without authentication. Allows anything after the `public_` prefix. */ PUBLIC: "PUBLIC", /** ACCESS_PASS - / A channel to which all users of an access pass are subscribed. The ID is the access_pass.tag (pass_XXXX or prod_XXXX) */ ACCESS_PASS: "ACCESS_PASS", /** APP - / A channel that is used by an app to broadcast data to all of its websocket connections. It may look like: app_XXX or app_XXX_exp_XXX or app_XXX_custom_suffix */ APP: "APP", /** BOT - / A channel to which all members with valid access to a bot are subscribed. The ID is the bot.id (biz_XXX) */ BOT: "BOT", UNRECOGNIZED: "UNRECOGNIZED" }; var ChannelSubscriptionState_DisconnectionReason = { UNKNOWN: "UNKNOWN", NO_ACCESS: "NO_ACCESS", REQUESTED_DISCONNECT: "REQUESTED_DISCONNECT", UNRECOGNIZED: "UNRECOGNIZED" }; var Position_Type = { UNKNOWN: "UNKNOWN", MOUSE: "MOUSE", PLAYER: "PLAYER", UNRECOGNIZED: "UNRECOGNIZED" }; var BusinessActivityEvent_EventType = { UNKNOWN: "UNKNOWN", MEMBER_JOINED: "MEMBER_JOINED", NEW_PAYMENT: "NEW_PAYMENT", NEW_DISPUTE: "NEW_DISPUTE", MEMBER_CANCELED: "MEMBER_CANCELED", MEMBER_CHURNED: "MEMBER_CHURNED", NEW_MARKETPLACE_SALE: "NEW_MARKETPLACE_SALE", NEW_RESOLUTION_CENTER_CASE: "NEW_RESOLUTION_CENTER_CASE", NEW_REVIEW: "NEW_REVIEW", TEAM_MEMBER_JOINED: "TEAM_MEMBER_JOINED", BANNED_USER: "BANNED_USER", FAILED_PAYMENT: "FAILED_PAYMENT", PAYOUT_REQUESTED: "PAYOUT_REQUESTED", PAYOUT_COMPLETED: "PAYOUT_COMPLETED", PAYOUT_FAILED: "PAYOUT_FAILED", COMPETITION_ALERT: "COMPETITION_ALERT", UNRECOGNIZED: "UNRECOGNIZED" }; // src/codegen/proto/common/feed.ts var FeedDmsPost_MessageType = { UNKNOWN_TYPE: "UNKNOWN_TYPE", REGULAR: "REGULAR", SYSTEM: "SYSTEM", AUTOMATED: "AUTOMATED", UNRECOGNIZED: "UNRECOGNIZED" }; var FeedChatFeed_MemberPermissionType = { UNKNOWN: "UNKNOWN", NONE: "NONE", EVERYONE: "EVERYONE", MEMBERS: "MEMBERS", ADMINS: "ADMINS", PRODUCT_OWNERS: "PRODUCT_OWNERS", UNRECOGNIZED: "UNRECOGNIZED" }; var FeedLivestreamFeed_MemberPermissionType = { UNKNOWN: "UNKNOWN", NONE: "NONE", EVERYONE: "EVERYONE", ADMINS: "ADMINS", PRODUCT_OWNERS: "PRODUCT_OWNERS", UNRECOGNIZED: "UNRECOGNIZED" }; var FeedDmsFeedMember_DmsFeedMemberStatus = { UNKNOWN_STATUS: "UNKNOWN_STATUS", REQUESTED: "REQUESTED", ACCEPTED: "ACCEPTED", REJECTED: "REJECTED", CLOSED: "CLOSED", ARCHIVED: "ARCHIVED", UNRECOGNIZED: "UNRECOGNIZED" }; var FeedDmsFeedMember_NotificationPreference = { UNKNOWN_PREFERENCE: "UNKNOWN_PREFERENCE", ALL: "ALL", MENTIONS: "MENTIONS", NONE: "NONE", UNRECOGNIZED: "UNRECOGNIZED" }; var FeedReaction_ReactionType = { UNKNOWN: "UNKNOWN", LIKE: "LIKE", EMOJI: "EMOJI", VIEW: "VIEW", VOTE: "VOTE", UNRECOGNIZED: "UNRECOGNIZED" }; var FeedForumFeed_MemberPermissionType = { UNKNOWN_PERMISSION: "UNKNOWN_PERMISSION", EVERYONE: "EVERYONE", ADMINS: "ADMINS", UNRECOGNIZED: "UNRECOGNIZED" }; var FeedForumFeed_LayoutType = { UNKNOWN_LAYOUT: "UNKNOWN_LAYOUT", FEED: "FEED", BLOG: "BLOG", UNRECOGNIZED: "UNRECOGNIZED" }; var FeedForumFeed_EmailNotificationPreferenceType = { UNKNOWN_PREFERENCE: "UNKNOWN_PREFERENCE", ALL_ADMIN_POSTS: "ALL_ADMIN_POSTS", ONLY_WEEKLY_SUMMARY: "ONLY_WEEKLY_SUMMARY", NONE: "NONE", UNRECOGNIZED: "UNRECOGNIZED" }; var MuxAsset_MuxAssetStatus = { UNKNOWN: "UNKNOWN", UPLOADING: "UPLOADING", CREATED: "CREATED", READY: "READY", UNRECOGNIZED: "UNRECOGNIZED" }; var PostReactionCount_ReactionType = { UNKNOWN: "UNKNOWN", LIKE: "LIKE", EMOJI: "EMOJI", VIEW: "VIEW", VOTE: "VOTE", UNRECOGNIZED: "UNRECOGNIZED" }; var FeedForumPost_ForumPostType = { UNKNOWN_TYPE: "UNKNOWN_TYPE", REGULAR: "REGULAR", AUTOMATED: "AUTOMATED", UNRECOGNIZED: "UNRECOGNIZED" }; // src/codegen/proto/common/notifications.ts var GoFetchNotifications_NotifyingEntityType = { UNKNOWN: "UNKNOWN", GENERIC: "GENERIC", EXPERIENCE: "EXPERIENCE", COMPANY: "COMPANY", COMPANY_TEAM: "COMPANY_TEAM", ACCESS_PASS: "ACCESS_PASS", UNRECOGNIZED: "UNRECOGNIZED" }; // src/codegen/proto/common/product_surface.ts var ProductSurface_ViewContext = { VIEW_CTX_UNKNOWN: "VIEW_CTX_UNKNOWN", /** VIEW_CTX_WHOP - / The user is viewing from inside a whop view. */ VIEW_CTX_WHOP: "VIEW_CTX_WHOP", /** VIEW_CTX_HOME_FEED - / The user is viewing from the home feed */ VIEW_CTX_HOME_FEED: "VIEW_CTX_HOME_FEED", UNRECOGNIZED: "UNRECOGNIZED" }; var ProductSurface_DiscoverSection = { DISCOVER_UNKNOWN: "DISCOVER_UNKNOWN", DISCOVER_LEADERBOARDS: "DISCOVER_LEADERBOARDS", DISCOVER_FOR_YOU: "DISCOVER_FOR_YOU", DISCOVER_EXPLORE: "DISCOVER_EXPLORE", UNRECOGNIZED: "UNRECOGNIZED" }; var ProductSurface_FeedTab = { FEED_TAB_UNKNOWN: "FEED_TAB_UNKNOWN", FEED_TAB_HOME: "FEED_TAB_HOME", FEED_TAB_EARN: "FEED_TAB_EARN", FEED_TAB_CHAT: "FEED_TAB_CHAT", FEED_TAB_LEARN: "FEED_TAB_LEARN", FEED_TAB_CALENDAR: "FEED_TAB_CALENDAR", FEED_TAB_PLAY: "FEED_TAB_PLAY", FEED_TAB_INTEGRATIONS: "FEED_TAB_INTEGRATIONS", FEED_TAB_TOOLS: "FEED_TAB_TOOLS", UNRECOGNIZED: "UNRECOGNIZED" }; var ProductSurface_SurfaceType = { UNKNOWN: "UNKNOWN", EXPERIENCE: "EXPERIENCE", WHOP: "WHOP", CREATOR_DASHBOARD: "CREATOR_DASHBOARD", AFFILIATE_DASHBOARD: "AFFILIATE_DASHBOARD", DISCOVER: "DISCOVER", HOME_FEED: "HOME_FEED", MESSAGES: "MESSAGES", PROFILE: "PROFILE", NOTIFICATIONS: "NOTIFICATIONS", USER_SETTINGS: "USER_SETTINGS", CHECKOUT: "CHECKOUT", AUTH: "AUTH", OTHER: "OTHER", USER_ONBOARDING: "USER_ONBOARDING", LEADERBOARD: "LEADERBOARD", UNRECOGNIZED: "UNRECOGNIZED" }; var ActiveUserBucket_UserBucketType = { UNKNOWN: "UNKNOWN", EXPERIENCE: "EXPERIENCE", WHOP: "WHOP", STORE_PAGE: "STORE_PAGE", MESSAGES: "MESSAGES", HOME_FEED: "HOME_FEED", DISCOVER: "DISCOVER", BOT: "BOT", UNRECOGNIZED: "UNRECOGNIZED" }; var GetTopExperiencesByActiveUsersRequest_AppFilter = { ALL: "ALL", LIVESTREAMS: "LIVESTREAMS", UNRECOGNIZED: "UNRECOGNIZED" }; // src/codegen/proto/common/websockets.ts var ResourceType = { RESOURCE_UNKNOWN: "RESOURCE_UNKNOWN", RESOURCE_BOT: "RESOURCE_BOT", RESOURCE_ACCESS_PASS: "RESOURCE_ACCESS_PASS", RESOURCE_EXPERIENCE: "RESOURCE_EXPERIENCE", RESOURCE_USER: "RESOURCE_USER", RESOURCE_EXPERIENCE_PREVIEW_CONTENT: "RESOURCE_EXPERIENCE_PREVIEW_CONTENT", RESOURCE_APP: "RESOURCE_APP", RESOURCE_FORUM_FEED: "RESOURCE_FORUM_FEED", RESOURCE_UNIVERSAL_POST: "RESOURCE_UNIVERSAL_POST", UNRECOGNIZED: "UNRECOGNIZED" }; // src/codegen/proto/index.google.ts var index_google_exports = {}; __export(index_google_exports, { protobuf: () => index_google_protobuf_exports }); // src/codegen/proto/index.google.protobuf.ts var index_google_protobuf_exports = {}; __export(index_google_protobuf_exports, { NullValue: () => NullValue }); // src/codegen/proto/google/protobuf/struct.ts var NullValue = { /** NULL_VALUE - Null value. */ NULL_VALUE: "NULL_VALUE", UNRECOGNIZED: "UNRECOGNIZED" }; // src/codegen/proto/index.calendar_bookings_app.ts var index_calendar_bookings_app_exports = {}; // src/codegen/proto/index.bounties_app.ts var index_bounties_app_exports = {}; __export(index_bounties_app_exports, { BountySubmission_BountySubmissionStatus: () => BountySubmission_BountySubmissionStatus, Bounty_BountyRewardUnit: () => Bounty_BountyRewardUnit, Bounty_BountyStatus: () => Bounty_BountyStatus }); // src/codegen/proto/bounties_app/bounties_app.ts var Bounty_BountyStatus = { UNKNOWN_STATUS: "UNKNOWN_STATUS", PUBLISHED: "PUBLISHED", ARCHIVED: "ARCHIVED", UNRECOGNIZED: "UNRECOGNIZED" }; var Bounty_BountyRewardUnit = { UNKNOWN_REWARD_UNIT: "UNKNOWN_REWARD_UNIT", PER_SUBMISSION: "PER_SUBMISSION", PER_VIEW: "PER_VIEW", UNRECOGNIZED: "UNRECOGNIZED" }; var BountySubmission_BountySubmissionStatus = { UNKNOWN_STATUS: "UNKNOWN_STATUS", PENDING: "PENDING", APPROVED: "APPROVED", DENIED: "DENIED", UNRECOGNIZED: "UNRECOGNIZED" }; // src/codegen/proto/index.content_app.ts var index_content_app_exports = {}; // src/codegen/proto/index.content_rewards_app.ts var index_content_rewards_app_exports = {}; __export(index_content_rewards_app_exports, { ContentPlatform: () => ContentPlatform, ContentRewardsCampaign_Category: () => ContentRewardsCampaign_Category, ContentRewardsCampaign_ContentType: () => ContentRewardsCampaign_ContentType, ContentRewardsCampaign_Status: () => ContentRewardsCampaign_Status, ContentRewardsSubmission_Status: () => ContentRewardsSubmission_Status }); // src/codegen/proto/content_rewards_app/content_rewards_app.ts var ContentPlatform = { UNKNOWN_PLATFORM: "UNKNOWN_PLATFORM", INSTAGRAM: "INSTAGRAM", TIKTOK: "TIKTOK", X: "X", YOUTUBE: "YOUTUBE", UNRECOGNIZED: "UNRECOGNIZED" }; var ContentRewardsCampaign_Status = { UNKNOWN: "UNKNOWN", ACTIVE: "ACTIVE", PENDING: "PENDING", EXPIRED: "EXPIRED", ARCHIVED: "ARCHIVED", UNRECOGNIZED: "UNRECOGNIZED" }; var ContentRewardsCampaign_ContentType = { UNKNOWN_CONTENT_TYPE: "UNKNOWN_CONTENT_TYPE", UGC: "UGC", CLIPPING: "CLIPPING", /** @deprecated */ FACELESS: "FACELESS", OTHER_CONTENT_TYPE: "OTHER_CONTENT_TYPE", UNRECOGNIZED: "UNRECOGNIZED" }; var ContentRewardsCampaign_Category = { UNKNOWN_CATEGORY: "UNKNOWN_CATEGORY", /** @deprecated */ CREATOR: "CREATOR", /** @deprecated */ BRAND: "BRAND", /** @deprecated */ INFLUENCER: "INFLUENCER", /** @deprecated */ STREAMER: "STREAMER", /** @deprecated */ MUSICIAN: "MUSICIAN", OTHER: "OTHER", /** @deprecated */ ECOMMERCE: "ECOMMERCE", LOGO: "LOGO", MUSIC: "MUSIC", /** @deprecated */ PODCAST: "PODCAST", /** @deprecated */ SOFTWARE: "SOFTWARE", /** @deprecated */ STREAM: "STREAM", ENTERTAINMENT: "ENTERTAINMENT", PRODUCTS: "PRODUCTS", PERSONAL_BRAND: "PERSONAL_BRAND", UNRECOGNIZED: "UNRECOGNIZED" }; var ContentRewardsSubmission_Status = { UNKNOWN: "UNKNOWN", PENDING: "PENDING", APPROVED: "APPROVED", REJECTED: "REJECTED", FLAGGED: "FLAGGED", UNRECOGNIZED: "UNRECOGNIZED" }; // src/codegen/proto/index.courses_app.ts var index_courses_app_exports = {}; // src/codegen/proto/index.events_app.ts var index_events_app_exports = {}; __export(index_events_app_exports, { Event_LocationType: () => Event_LocationType, Event_RecurringRule: () => Event_RecurringRule }); // src/codegen/proto/events_app/events_app.ts var Event_LocationType = { UNKNOWN_LOCATION_TYPE: "UNKNOWN_LOCATION_TYPE", OFFLINE: "OFFLINE", ONLINE: "ONLINE", ZOOM: "ZOOM", GOOGLE_MEET: "GOOGLE_MEET", UNRECOGNIZED: "UNRECOGNIZED" }; var Event_RecurringRule = { UNKNOWN_RECURRING_RULE: "UNKNOWN_RECURRING_RULE", DAILY: "DAILY", WEEKLY: "WEEKLY", MONTHLY: "MONTHLY", YEARLY: "YEARLY", UNRECOGNIZED: "UNRECOGNIZED" }; // src/codegen/proto/index.wheel_app.ts var index_wheel_app_exports = {}; __export(index_wheel_app_exports, { Spin_SpinStatus: () => Spin_SpinStatus }); // src/codegen/proto/wheel_app/wheel_app.ts var Spin_SpinStatus = { UNKNOWN_SPIN_STATUS: "UNKNOWN_SPIN_STATUS", WON: "WON", LOST: "LOST", UNRECOGNIZED: "UNRECOGNIZED" }; // src/codegen/proto/index.experience.ts var index_experience_exports = {}; // src/codegen/proto/index.games.ts var index_games_exports = {}; __export(index_games_exports, { quizzes: () => index_games_quizzes_exports }); // src/codegen/proto/index.games.quizzes.ts var index_games_quizzes_exports = {}; __export(index_games_quizzes_exports, { HostCommand_StatusCommand: () => HostCommand_StatusCommand, QuizStatus: () => QuizStatus }); // src/codegen/proto/games/quizzes/quizzes.ts var QuizStatus = { UNKNOWN: "UNKNOWN", WAITING_FOR_PLAYERS: "WAITING_FOR_PLAYERS", SHOW_QUESTION: "SHOW_QUESTION", ANSWER_QUESTION: "ANSWER_QUESTION", QUESTION_RESULT: "QUESTION_RESULT", QUESTION_LEADERBOARD: "QUESTION_LEADERBOARD", GAME_RESULT: "GAME_RESULT", UNRECOGNIZED: "UNRECOGNIZED" }; var HostCommand_StatusCommand = { UNKNOWN: "UNKNOWN", /** NEXT - / Move to the next phase of the game. */ NEXT: "NEXT", /** END_GAME - / End the game immediately, skip results screen and destroy the session. */ END_GAME: "END_GAME", /** GO_BACK_TO_LOBBY - / Go back to the lobby, allowing more players to join while the current game is running. Does not reset the leaderboard. */ GO_BACK_TO_LOBBY: "GO_BACK_TO_LOBBY", /** SKIP_TO_END_RESULTS - / Skip the questions and go straight to the end state of the game. Shows the leaderboard. */ SKIP_TO_END_RESULTS: "SKIP_TO_END_RESULTS", UNRECOGNIZED: "UNRECOGNIZED" }; // src/codegen/proto/index.data_platform.ts var index_data_platform_exports = {}; __export(index_data_platform_exports, { DisputeMetric: () => DisputeMetric, LogicalOperator: () => LogicalOperator, PaymentMethod: () => PaymentMethod }); // src/codegen/proto/data_platform/dispute_rates_query.ts var PaymentMethod = { PAYMENT_METHOD_UNSPECIFIED: "PAYMENT_METHOD_UNSPECIFIED", PAYMENT_METHOD_ALL_PAYMENT_METHODS: "PAYMENT_METHOD_ALL_PAYMENT_METHODS", PAYMENT_METHOD_ALL_CARD_AND_FINANCING: "PAYMENT_METHOD_ALL_CARD_AND_FINANCING", PAYMENT_METHOD_ALL_FINANCING: "PAYMENT_METHOD_ALL_FINANCING", PAYMENT_METHOD_SPLITIT: "PAYMENT_METHOD_SPLITIT", PAYMENT_METHOD_SEZZLE: "PAYMENT_METHOD_SEZZLE", PAYMENT_METHOD_AFTERPAY_CLEARPAY: "PAYMENT_METHOD_AFTERPAY_CLEARPAY", PAYMENT_METHOD_ZIP: "PAYMENT_METHOD_ZIP", PAYMENT_METHOD_KLARNA: "PAYMENT_METHOD_KLARNA", PAYMENT_METHOD_AFFIRM: "PAYMENT_METHOD_AFFIRM", UNRECOGNIZED: "UNRECOGNIZED" }; var DisputeMetric = { DISPUTE_METRIC_UNSPECIFIED: "DISPUTE_METRIC_UNSPECIFIED", DISPUTE_RATE: "DISPUTE_RATE", TOTAL_TRANSACTIONS: "TOTAL_TRANSACTIONS", DISPUTED_TRANSACTIONS: "DISPUTED_TRANSACTIONS", UNRECOGNIZED: "UNRECOGNIZED" }; var LogicalOperator = { LOGICAL_OPERATOR_UNSPECIFIED: "LOGICAL_OPERATOR_UNSPECIFIED", AND: "AND", OR: "OR", UNRECOGNIZED: "UNRECOGNIZED" }; // src/webhooks.ts var DEFAULT_SIGNATURE_HEADER_NAME = "x-whop-signature"; function makeWebhookValidator({ webhookSecret, signatureHeaderName }) { const textEncoder = new TextEncoder(); const encodedKey = textEncoder.encode(webhookSecret); const cryptoKeyPromise = crypto.subtle.importKey( "raw", encodedKey, { name: "HMAC", hash: "SHA-256" }, false, ["sign"] ); return async function validateWebhookBody(req) { const body = await req.text(); const header = req.headers.get( signatureHeaderName ?? DEFAULT_SIGNATURE_HEADER_NAME ); if (!header) throw Error("Missing header containing signature."); const [timestampStr, signatureStr] = header.split(","); const [, timestamp] = timestampStr.split("="); const [version, sentSignature] = signatureStr.split("="); const now = Math.round(Date.now() / 1e3); if (Number.isNaN(Number.parseInt(timestamp)) || Math.abs(now - Number.parseInt(timestamp)) > 300) throw Error("Invalid timestamp"); const stringToHash = `${timestamp}.${body}`; const cryptoKey = await cryptoKeyPromise; const signatureBuffer = await crypto.subtle.sign( { name: "HMAC", hash: "SHA-256" }, cryptoKey, textEncoder.encode(stringToHash) ); const signature = buf2hex(signatureBuffer); if (version !== "v1") throw Error("Unsupported version"); if (signature !== sentSignature) throw Error("Signature mismatch"); const parsedBody = JSON.parse(body); if (!isValidWebhook(parsedBody)) throw Error("Invalid webhook payload"); return parsedBody; }; } function buf2hex(buffer) { return [...new Uint8Array(buffer)].map((x) => x.toString(16).padStart(2, "0")).join(""); } function isValidWebhook(webhook) { if (!webhook || typeof webhook !== "object") return false; if (!("api_version" in webhook) || webhook.api_version !== "v5") return false; if (!("action" in webhook) || typeof webhook.action !== "string") return false; if (!("data" in webhook) || typeof webhook.data !== "object" || webhook.data === null) return false; return true; } // src/utils/retry.ts var RetryError = class extends Error { constructor(message, errors, maxRetries) { super(message); this.errors = errors; this.maxRetries = maxRetries; this.name = "RetryError"; } }; async function retry(fn, maxRetries, signal, ...args) { let tries = 0; const errors = []; while (tries < maxRetries) { signal?.throwIfAborted(); try { const res = await fn(...args); return res; } catch (error) { errors.push(error); tries++; } } for (const error of errors) { console.error(error); } throw new RetryError("Failed to retry", errors, maxRetries); } // src/attachments/upload-parts.ts var uploadTasks = []; var workerCount = 0; var maxWorkers = 10; async function uploadWorker(uploadPart) { if (workerCount >= maxWorkers) { return; } workerCount++; while (uploadTasks.length > 0) { const task = uploadTasks.shift(); if (!task) { continue; } try { const etag = await retry(uploadPart, 10, task.task.signal, task.task); task.resolve({ etag, partNumber: task.task.partNumber }); } catch (e) { task.reject(e); } } workerCount--; } function uploadParts(tasks, uploadPart, priority = false) { const promises = tasks.map((task) => { return new Promise( (resolve, reject) => { if (priority) { uploadTasks.unshift({ task, resolve, reject }); } else { uploadTasks.push({ task, resolve, reject }); } } ); }); for (let i = 0; i < Math.min(tasks.length, maxWorkers); i++) { void uploadWorker(uploadPart); } return Promise.all(promises); } // src/utils/sum.ts function sum(...args) { return args.reduce((acc, curr) => acc + curr, 0); } // src/attachments/upload.ts async function handleUpload({ data, ...preparedFile }, { onProgress, signal, uploadPart }) { if (preparedFile.multipart) { const loaded = Array(preparedFile.multipartUploadUrls.length).fill(0); const result = await uploadParts( preparedFile.multipartUploadUrls.map((part, index) => ({ ...part, fullData: data, onProgress: (event) => { loaded[index] = event.loaded; const total = sum(...loaded); onProgress?.(Math.round(total / data.size * 100)); }, signal })), uploadPart ); return result; } await uploadParts( [ { url: preparedFile.uploadUrl, fullData: data, partNumber: 1, headers: preparedFile.headers, onProgress: (event) => { onProgress?.(Math.round(event.loaded / data.size * 100)); }, signal } ], uploadPart, true ); return []; } function getMediaType(data) { switch (true) { case data.type.startsWith("image/"): return "image"; case data.type.startsWith("video/"): return "video"; case data.type.startsWith("audio/"): return "audio"; default: return "other"; } } function makeUploadAttachmentFunction({ uploadPart }) { return async function uploadAttachment(input, { onProgress, signal } = {}) { const preparedAttachment = "record" in input && "file" in input ? await this.prepareAttachmentForUpload(input.file, input.record) : await input; const result = await handleUpload(preparedAttachment, { onProgress, signal, uploadPart }); const mediaType = getMediaType(preparedAttachment.data); if (preparedAttachment.multipart) { await this.attachments.processAttachment({ directUploadId: preparedAttachment.id, mediaType, multipartUploadId: preparedAttachment.multipartUploadId, multipartParts: result }); } else { await this.attachments.processAttachment({ directUploadId: preparedAttachment.id, mediaType }); } const attachment = await this.analyzeAttachment(preparedAttachment.id, { signal }); if (!attachment) { throw new Error("Failed to analyze Attachment"); } return { directUploadId: preparedAttachment.id, record: preparedAttachment.record, attachment }; }; } // src/attachments/analyze.ts async function analyzeAttachment(signedId, opts) { while (!opts?.signal?.aborted) { const attachment = await this.attachments.getAttachment({ id: signedId }, { signal: opts?.signal }).catch(() => null); if (attachment) { return attachment; } } } // src/attachments/common.ts var MULTIPART_UPLOAD_CHUNK_SIZE = 5 * 1024 * 1024; // src/utils/with-awaitable-params.ts var withAwaitableParams = (fn) => { return (...args) => { const casted = args; const hasPromises = casted.some((arg) => arg instanceof Promise); if (hasPromises) { return new Promise((resolve, reject) => { return Promise.all(casted).then((args2) => { return fn(...args2); }).then(resolve).catch(reject); }); } return fn(...args); }; }; // src/utils/b64.ts var encodings = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function b64Raw(arrayBuffer) { let base64 = ""; const bytes = new Uint8Array(arrayBuffer); const byteLength = bytes.byteLength; const byteRemainder = byteLength % 3; const mainLength = byteLength - byteRemainder; let a; let b; let c; let d; let chunk; for (let i = 0; i < mainLength; i = i + 3) { chunk = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2]; a = (chunk & 16515072) >> 18; b = (chunk & 258048) >> 12; c = (chunk & 4032) >> 6; d = chunk & 63; base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]; } if (byteRemainder === 1) { chunk = bytes[mainLength]; a = (chunk & 252) >> 2; b = (chunk & 3) << 4; base64 += `${encodings[a]}${encodings[b]}==`; } else if (byteRemainder === 2) { chunk = bytes[mainLength] << 8 | bytes[mainLength + 1]; a = (chunk & 64512) >> 10; b = (chunk & 1008) >> 4; c = (chunk & 15) << 2; base64 += `${encodings[a]}${encodings[b]}${encodings[c]}=`; } return base64; } var b64 = withAwaitableParams(b64Raw); // src/utils/md5.ts import { md5 as jsMd5 } from "js-md5"; async function md5(stream) { const hasher = jsMd5.create(); await stream.pipeTo( new WritableStream({ write(chunk) { hasher.update(chunk); } }) ); return hasher.arrayBuffer(); } // src/attachments/prepare.ts async function prepareAttachmentForUpload(data, record) { const isMultipart = data.size > MULTIPART_UPLOAD_CHUNK_SIZE; const mediaDirectUpload = await this.attachments.uploadMedia({ byteSizeV2: data.size.toString(), record, filename: data instanceof File ? data.name : crypto.randomUUID(), contentType: data.type, checksum: await b64(md5(data.stream())), multipart: isMultipart }); if (isMultipart) { if (!mediaDirectUpload?.multipartUploadId || !mediaDirectUpload.multipartUploadUrls) { throw new Error("Failed to prepare file"); } return { data, id: mediaDirectUpload.id, multipartUploadUrls: mediaDirectUpload.multipartUploadUrls, multipartUploadId: mediaDirectUpload.multipartUploadId, record, multipart: true }; } if (!mediaDirectUpload?.id || !mediaDirectUpload.uploadUrl) { throw new Error("Failed to prepare file"); } return { data, id: mediaDirectUpload.id, uploadUrl: mediaDirectUpload.uploadUrl, headers: mediaDirectUpload.headers, record, multipart: false }; } // src/attachments/partial-file-sdk-extensions.ts function partialFileSdkExtensions(baseSdk) { const prepareAttachmentForUpload2 = prepareAttachmentForUpload.bind(baseSdk); const analyzeAttachment2 = analyzeAttachment.bind(baseSdk); return { prepareAttachmentForUpload: prepareAttachmentForUpload2, analyzeAttachment: analyzeAttachment2 }; } // src/attachments/file-sdk-extensions.ts function fileSdkExtensions(baseSdk, uploadAttachmentFn) { const partial = partialFileSdkExtensions(baseSdk); const uploadAttachment = uploadAttachmentFn.bind({ ...baseSdk, ...partial }); return { ...partial, uploadAttachment }; } // src/codegen/graphql/client.ts function getSdk(requester) { return { accessPasses: { getAccessPass(variables, options) { return requester( "whop-sdk-ts-client/sha256:daea5c9cf3e5e30ef0fd9eaad8ea852ffdbd0e0088ff3ad05aacb6a761b7c6f9", "getAccessPass", "query", variables, options ).then((res) => res.accessPass); } }, attachments: { getAttachment(variables, options) { return requester( "whop-sdk-ts-client/sha256:07f48fb0c1292fda5a8dd5f54b5d1b637635a87b6012769819ebcf7795a045ba", "getAttachment", "query", variables, options ).then((res) => res.attachment); }, processAttachment(variables, options) { return requester( "whop-sdk-ts-client/sha256:396c5803051b3c9bcedd3ce310505a4f57a6b94bc190e7142e897d9aa5036ece", "processAttachment", "mutation", { input: variables }, options ).then((res) => res.mediaAnalyzeAttachment); }, uploadMedia(variables, options) { return requester( "whop-sdk-ts-client/sha256:a3d06ed16e52126d96aae83cad3400471246f37fc275e4c8f4836c98bf8e9d59", "uploadMedia", "mutation", { input: variables }, options ).then((res) => res.mediaDirectUpload); } }, courses: { createAssessmentQuestion(variables, options) { return requester( "whop-sdk-ts-client/sha256:52902016f3a8cf2b819038945ded34a0caafd80c9a867403ca36451c39f56ac6", "createAssessmentQuestion", "mutation", { input: variables }, options ).then((res) => res.createAssessmentQuestion); }, createChapter(variables, options) { return requester( "whop-sdk-ts-client/sha256:8ebe9533278b00eded622eef765baeebf70fccedcd5d60854f8777812da20311", "createChapter", "mutation", { input: variables }, options ).then((res) => res.createChapter); }, createCourse(variables, options) { return requester( "whop-sdk-ts-client/sha256:41f957dfc0e147131265e62e4b5ae6f743256f6bf7a4e28e042a3469777e9c35", "createCourse", "mutation", { input: variables }, options ).then((res) => res.createCourse); }, createLesson(variables, options) { return requester( "whop-sdk-ts-client/sha256:33069f4d2b756d6a9a2a486d0ac6d91272c9acbd9d3774c15e12d7b39f3df6f4", "createLesson", "mutation", { input: variables }, options ).then((res) => res.createLesson); }, deleteAssessmentQuestionImage(variables, options) { return requester( "whop-sdk-ts-client/sha256:07563fb79b45fd9fbe7ef7d14923014e5f3407dae067d0393b84bd6724970aaa", "deleteAssessmentQuestionImage", "mutation", { input: variables }, options ).then((res) => res.deleteAssessmentQuestionImage); }, deleteChapter(variables, options) { return requester( "whop-sdk-ts-client/sha256:021c10ea5b5f776e229d4c2cd25578b8aec3c869c898c747d4dcb889ddad32b6", "deleteChapter", "mutation", { input: variables }, options ).then((res) => res.deleteChapter); }, deleteLessonAttachment(variables, options) { return requester( "whop-sdk-ts-client/sha256:7af840d8ddbf664a04ec3da2283e9a540f68da24adedbe7a2af9718f1c70f10c", "deleteLessonAttachment", "mutation", { input: variables }, options ).then((res) => res.deleteLessonAttachment); }, deleteLesson(variables, options) { return requester( "whop-sdk-ts-client/sha256:6be8fd89af64aec7db125bac7d67bad8530cc8f5b8ee98c879351acd59aa6fac", "deleteLesson", "mutation", { input: variables }, options ).then((res) => res.deleteLesson); }, getCourse(variables, options) { return requester( "whop-sdk-ts-client/sha256:5e81c304ac7c4c19b2d07ea7c2a32b2fd8998774bf90900a81999b9077b383a1", "getCourse", "query", variables, options ).then((res) => res.course); }, getLesson(variables, options) { return requester( "whop-sdk-ts-client/sha256:372989bc0ffb7ff3c36d1325f1af4115c06205e95378a2e344d91a857e732630", "getLesson", "query", variables, options ).then((res) => res.course); }, getUserLessonInteractions(variables, options) { return requester( "whop-sdk-ts-client/sha256:6b12c8ccabe59b65d8869029d4e4e56ddbeac7256137e5e79012a3e33aa81523", "getUserLessonInteractions", "query", variables, options ).then((res) => res.course); }, listCoursesForCompany(variables, options) { return requester( "whop-sdk-ts-client/sha256:76dd2b0b09b6083392dcce8c1df423cc6e6eb290e58bdd2d830f50ef1a4828b3", "listCoursesForCompany", "query", variables, options ).then((res) => res.company); }, listCoursesForExperience(variables, options) { return requester( "whop-sdk-ts-client/sha256:a579fee2663d841a23be014b234d89eadb097dac387722dfe9d0e87911a7598e", "listCoursesForExperience", "query", variables, options ).then((res) => res.publicExperience); }, markLessonAsCompleted(variables, options) { return requester( "whop-sdk-ts-client/sha256:941178d021bd72247401d347d5dd969036579147777e0a754f5102cddc5074c7", "markLessonAsCompleted", "mutation", { input: variables }, options ).then((res) => res.markLessonAsCompleted); }, moveCourse(variables, options) { return requester( "whop-sdk-ts-client/sha256:ce7d38029113792bf1ff544db18f000732fed4db3ebc766767a367cef5691c2b", "moveCourse", "mutation", { input: variables }, options ).then((res) => res.moveCourse); }, updateChapterOrder(variables, options) { return requester( "whop-sdk-ts-client/sha256:c749c5c4907afd39ab2d3f8c44b3e65c8c9928e0cf06f8687deaa40d144a0df6", "updateChapterOrder", "mutation", { input: variables }, options ).then((res) => res.updateChapterOrder); }, updateChapter(variables, options) { return requester( "whop-sdk-ts-client/sha256:9fda8d867b07c1b31622cb73084523577519ca35822d8ce3938fa2b07efaf6e5", "updateChapter", "mutation", { input: variables }, options ).then((res) => res.updateChapter); }, updateLessonOrder(variables, options) { return requester( "whop-sdk-ts-client/sha256:8ae83382f97b182c08bf5851e3bbed05fd8269856c00b82b5577939c00e39e43", "updateLessonOrder", "mutation", { input: variables }, options ).then((res) => res.updateLessonOrder); }, updateLesson(variables, options) { return requester( "whop-sdk-ts-client/sha256:c872c79e5469f162f4de0f64ed6decc489cc3e05d66781a2f33ae1eef4d762bd", "updateLesson", "mutation", { input: variables }, options ).then((res) => res.updateLesson); } }, experiences: { getExperience(variables, options) { return requester( "whop-sdk-ts-client/sha256:114eb7b7c8403ffbe75a0c74a26ac50b5367e183a16ba64eebf4a43d5466bb4e", "getExperience", "query", variables, options ).then((res) => res.experience); }, listUsersForExperience(variables, options) { return requester( "whop-sdk-ts-client/sha256:85c827d8660dc2a97e8b930e213b83493ae132c00988e0f03e02c5dc99559a5a", "listUsersForExperience", "query", variables, options ).then((res) => res.publicExperience); } }, forums: { listForumPostsFromForum(variables, options) { return requester( "whop-sdk-ts-client/sha256:97a7d797f3a5f6f83bf4628cc7c586d529b90e54c0a8e193493a55b4ad05df46", "listForumPostsFromForum", "query", variables, options ).then((res) => res.feedPosts); } }, messages: { listMessagesFromChat(variables, options) { return requester( "whop-sdk-ts-client/sha256:5fdbf50fe489888e5b0a98e9fe6170584bf47ab38f87d1e0b7fce8f523513894", "listMessagesFromChat", "query", variables, options ).then((res) => res.feedPosts); } }, users: { getCurrentUser(variables, options) { return requester( "whop-sdk-ts-client/sha256:9f7cc9ff353a2778e55b674cfd5737a7dcaff19be9ac13d6f79aabd5d8ef69ff", "getCurrentUser", "query", variables, options ).then((res) => res.viewer); }, getUserLedgerAccount(variables, options) { return requester( "whop-sdk-ts-client/sha256:d7eeaf0a388395edb82220877e72a7fc91d1f06a6d89f1cfa5e56bb400d2aa49", "getUserLedgerAccount", "query", variables, options ).then((res) => res.viewer); }, getUser(variables, options) { return requester( "whop-sdk-ts-client/sha256:d8022374c6b0eb0445781342a14c9bffafd776cee4e282cb76e31af8c017d33e", "getUser", "query", variables, options ).then((res) => res.publicUser); } } }; } // src/sdk/sdk-common.ts var DEFAULT_API_ORIGIN = "https://api.whop.com"; var GQLNetworkError = class extends Error { constructor(e) { const message = e instanceof Error ? e.message : typeof e === "string" ? e : "Unknown network error"; super(message); if (e instanceof Error) this.stack = e.stack; } }; var GQLRequestError = class extends Error { statusCode; constructor(statusCode, message) { super(message); this.statusCode = statusCode; } isUnauthorized() { return this.statusCode === 401; } isForbidden() { return this.statusCode === 403; } isNotFound() { return this.statusCode === 404; } isServerError() { return this.statusCode >= 500; } }; var GQLError = class extends Error { errors; constructor(errors) { super(errors[0].message); this.errors = errors; } }; async function graphqlFetch(url, operationId, operationName, operationType, variables, headersInit = {}) { try { const body = { operationId, operationType, operationName, variables }; const headers = new Headers(headersInit); headers.set("Content-Type", "application/json"); headers.set("Accept", "application/json"); const urlObject = addOperationNameToUrl( url, operationName, operationId, operationType ); const response = await fetch(urlObject, { method: "POST", body: JSON.stringify(body), headers }); if (!response.ok) { const errorMessage = await response.text(); throw new GQLRequestError(response.status, errorMessage); } const data = await response.json(); if (data.errors) { throw new GQLError(data.errors); } return data.data; } catch (e) { throw new GQLNetworkError(e); } } function addOperationNameToUrl(url, name, operationId, operationType) { const urlObject = new URL(url); let pathname = urlObject.pathname; if (pathname.endsWith("/")) { pathname = pathname.slice(0, -1); } pathname += `/${name}`; urlObject.pathname = pathname; const [clientName, opId] = operationId.split("/"); urlObject.searchParams.set("id", opId); urlObject.searchParams.set("client", clientName); urlObject.searchParams.set("type", operationType); return urlObject; } // src/websockets/client.common.ts import { TypedEmitter } from "tiny-typed-emitter"; var WhopWebsocketClientBase = class extends TypedEmitter { websocket = null; failedConnectionAttempts = 0; status = "disconnected"; wantsToBeConnected = false; makeWebsocket() { throw new Error("Not implemented in base class"); } connect() { if (this.websocket) { this.disconnect(); } this.wantsToBeConnected = true; this.setStatus("connecting"); const websocket = this.makeWebsocket(); this.websocket = websocket; websocket.onopen = () => { this.setStatus("connected"); }; websocket.onmessage = (event) => { try { const message = JSON.parse(event.data); this.emit("message", message); if (message.appMessage) { this.emit("appMessage", message.appMessage); } } catch (error) { console.error( "[WhopWebsocketClient] Error parsing message", event.data ); } }; websocket.onerror = (event) => { console.error("[WhopWebsocketClient] Websocket error", event); this.setStatus("disconnected"); }; websocket.onclose = (event) => { this.setStatus("disconnected"); }; return () => { this.disconnect(); }; } disconnect() { if (this.websocket) { this.websocket.onopen = null; this.websocket.onmessage = null; this.websocket.onerror = null; this.websocket.onclose = null; this.websocket.close(); this.websocket = null; } this.wantsToBeConnected = false; } send(message) { if (!this.websocket) { throw new Error("Websocket not connected"); } this.websocket.send(JSON.stringify(message)); } broadcast({ message, target }) { this.send({ broadcastAppMessage: { channel: convertBroadcastTargetToProtoChannel(target), json: message } }); } setStatus(status) { if (status === this.status) return; this.status = status; if (status === "disconnected") { const backoff = this.calculateBackoff(); this.failedConnectionAttempts++; setTimeout(() => { if (this.wantsToBeConnected) { this.connect(); } }, backoff); this.emit("disconnect"); } if (status === "connected") { this.failedConnectionAttempts = 0; this.emit("connect"); } this.emit("connectionStatus", status); } calculateBackoff() { return Math.min(50 * 2 ** this.failedConnectionAttempts, 1e3 * 60); } }; function convertBroadcastTargetToProtoChannel(target) { if (target === "everyone") { return { type: "APP", id: "[app_id]" }; } if ("experienceId" in target) { return { type: "APP", id: `[app_id]_${target.experienceId}` }; } if ("customId" in target) { return { type: "APP", id: `[app_id]_c_${target.customId}` }; } throw new Error("Invalid broadcast target"); } // src/websockets/client.browser.ts var WhopWebsocketClientBrowser = class extends WhopWebsocketClientBase { options; constructor(options) { super(); this.options = options; } makeWebsocket() { const path = "/_whop/ws/v1/websockets/connect"; const searchParams = new URLSearchParams(); addChannelIds(searchParams, "join_experience", this.options.joinExperience); addChannelIds(searchParams, "join_custom", this.options.joinCustom); addChannelIds(searchParams, "join_public", this.options.joinPublic); const url = new URL(path, window.location.origin); url.protocol = url.protocol.replace("http", "ws"); url.search = searchParams.toString(); return new WebSocket(url.toString()); } }; function addChannelIds