@playlive/tiltify-core
    Preparing search index...

    Class Tiltify

    Tiltify v5 REST client. Prefer the tiltify singleton over new Tiltify().

    Index
    ActivateWebhookEndpoint ClearAuthToken CreateOrUpdateWebhookSubscription CurrentBaseURL DeleteWebhookSubscription DisableAuth DisableErrorLogging EnableErrorLogging FindAuctionHouseByCauseSlug FindAuctionHouseByUserSlug FindCampaign FindTeam FindUser GET GET_Array GET_Paginator GetActiveFundraisingEventMilestones GetAllCurrentFundraisingEvents GetAllTeamCampaigns GetAuctionBids GetAuctionBidsWithCursor GetAuctionHouse GetAuctionItem GetAuctionItems GetAuthMode GetAuthModeAsString GetAuthStatus GetAuthToken GetCampaign GetCampaignDonations GetCampaignFitnessGoals GetCause GetCauseCampaigns GetCauseDonations GetCauseDonorLeaderboard GetCurrentEvents GetCurrentRefreshToken GetCurrentToken GetCurrentUser GetDonationMatches GetEventTeamsFitnessDistanceLeaderboard GetEventTeamsFitnessTimeLeaderboard GetEventUserFitnessDistanceLeaderboard GetEventUserFitnessTimeLeaderboard GetEventUserLeaderboard GetFundraiser GetFundraisingEventsSupportingCampaigns GetLeaderboard GetLeaderboardWithCursor GetMaxRetryDuration GetMilestones GetMode GetNextMilestone GetPoll GetPolls GetRewards GetSchedule GetSourceTag GetTargets GetTeam GetTeamCampaign GetTeamCampaigns GetTeamMembers GetTeamSupportingCampaigns GetTeamUserLeaderboard GetTokenExpiration GetUser GetUserAgent GetUserAndTeamCampaigns GetUserCampaigns IsProxyFallbackEnabled OverrideAuthToken OverrideBaseURL PerformRequest RefreshAuthToken SetCauseApiKey SetCauseMode SetCredentials SetLogger SetLogLevel SetMaxRetries SetMaxRetryDuration SetPublicMode SetSourceTag SetTiltifyTimeout SetUserAgent TestClearCredentials TestOverrideTokenExpiration UseClientAuth UseOriginalBaseURL UseProxy UseProxyWithFallback UseUserAuth WaitForSeconds
    • Parameters

      • __namedParameters: {
            maxContentLength?: number;
            maxRedirects?: number;
            maxRetryDurationMs?: number;
            timeout?: number;
        } = {}
        • OptionalmaxContentLength?: number
        • OptionalmaxRedirects?: number
        • OptionalmaxRetryDurationMs?: number

          Optional wall-clock ceiling on total retry duration in ms. Overrides the default 8000ms. Pass 0 to disable and rely on _maxRetries alone.

        • Optionaltimeout?: number

      Returns Tiltify

    • get Instance(): Tiltify

      Returns the singleton instance of the Tiltify client.

      The instance reference is stored on globalThis behind Symbol.for("@playlive/tiltify-core.instance") rather than on a private static field of this class. Consumer bundlers — notably Vite's optimizeDeps in dev — can pre-bundle each subpath export of a downstream package independently and inline tiltify-core into each pre-bundle. That produces two class Tiltify declarations, each with its own _instance slot, and consumer calls like tiltify.UseProxy(...) land on a different instance than the one the fetcher chain eventually reads from — all requests then run against an unconfigured client and, depending on the caller, fail silently.

      Symbol-registry lookup on globalThis collapses those duplicate copies to a single logical instance. Same technique used in @playlive/fundraiser-data/config for its configure() slot; see that module's packageDocumentation block for the fuller story.

      Returns Tiltify

    • Creates or updates a webhook subscription for a given endpoint and event.

      Parameters

      • webhookEndpointID: string
      • eventID: string
      • eventTypes: (
            | "private:direct:auction_bid_amount_updated"
            | "private:direct:donation_updated"
            | "private:direct:fact_updated"
            | "private:indirect:donation_updated"
            | "private:indirect:fact_updated"
            | "public:direct:auction_bid_amount_updated"
            | "public:direct:donation_updated"
            | "public:direct:fact_updated"
            | "public:indirect:donation_updated"
            | "public:indirect:fact_updated"
        )[]

      Returns Promise<TiltifyWebhookSubscription>

    • Disables all library logging (equivalent to SetLogLevel("silent")). Errors are still thrown — only the log sink is silenced.

      Returns void

    • Helper for calling the Tiltify v5 API with optional pagination parameters. Tiltify error responses are returned as data rather than thrown.

      Type Parameters

      • T

      Parameters

      • endpoint: string
      • limit: number | null = 100
      • cursor: string | null = null
      • cursorMode: "before" | "after" = "after"

      Returns Promise<{ data: T; error?: string; metadata: TiltifyMetadata }>

      const { data, metadata } = await tiltify.GET<TiltifyDonation[]>(
      "public/campaigns/my-id/donations",
      50,
      );
    • Auto-paginating wrapper around GET that accumulates all results into a single array.

      Type Parameters

      • T

      Parameters

      • endpoint: string
      • max: number = Number.MAX_VALUE
      • batchLimit: number = 100

      Returns Promise<T[]>

      const donations = await tiltify.GET_Array<TiltifyDonation>(
      "public/campaigns/my-id/donations",
      );
    • A DIY paginator. Calls the provided async callback with each page of data. The callback must return a cursor string to continue paginating, or null to stop.

      Type Parameters

      • T

      Parameters

      • endpoint: string
      • dataCallback: (data: T[], metadata: TiltifyMetadata) => Promise<string | null>
      • limit: number = 100

      Returns Promise<void>

      await tiltify.GET_Paginator<TiltifyDonation>(
      "public/campaigns/my-id/donations",
      async (donations, metadata) => {
      await processBatch(donations);
      return metadata.after ?? null;
      },
      );
    • Get the currently active milestones for a fundraising event by its public id — the same UUID returned by GET /public/fundraising_events/{id} and referenced throughout the Tiltify REST API (/supporting_events, /user_leaderboard, …).

      This is a proxy-only call. Tiltify's public REST API has no milestones endpoint for a fundraising event — milestones exist only for campaigns, team campaigns, personal campaigns, and facts (and /public/facts/:fact_id/milestones 404s for fundraising-event ids). The FE-level list is reachable only through the GraphQL endpoint tiltify.com's own landing pages use, which browsers cannot call from a Play Live surface (CORS + Cloudflare bot-scoring).

      The proxy therefore fills the gap at GET /public/fundraising_events/:fundraising_event_id/milestones, resolving the fact via GraphQL, filtering active === true server-side, and returning a Tiltify REST-shaped { data, metadata } envelope. Requires UseProxy to have been called — there is no direct fallback.

      The proxy scopes this route to St. Jude: a fundraising event owned by any other cause is refused with a 403, since fact ids are global and the route would otherwise act as an open relay for Tiltify's GraphQL gateway.

      Public / unauthenticated route: no Authorization header is sent and the proxy never returns inactive milestones. This method also re-filters active === true client-side as defence-in-depth in case a future proxy version drifts.

      The returned items are field-compatible with the REST TiltifyMilestone from GetMilestones, minus inserted_at / updated_at / legacy_id (the upstream GraphQL fragment does not project those).

      Parameters

      • fundraisingEventID: string

        The fundraising event's public id (UUID).

      Returns Promise<TiltifyFactMilestone[] | null>

      Ordered array of active milestones, or null when no fundraising event matches the id (the proxy answers 404 with Tiltify's own error envelope, matching GetCampaign's not-found convention). An empty array is meaningful and distinct: the event exists but currently has no active milestones.

      HTTP_ERROR on non-2xx, non-404 proxy responses — including the 422 the proxy returns for a malformed (non-UUID) id, and the 403 it returns for a fundraising event that is not a St. Jude event.

      tiltify.UseProxy("prod");
      const active = await tiltify.GetActiveFundraisingEventMilestones(
      "7d3ee5c9-684a-47ae-bb88-ced83b19fa4e",
      );
      if (active === null) {
      // no such fundraising event
      }
    • Gets all current fundraising events at the cause level with optional pagination.

      Parameters

      • limit: number = 100
      • cursor: string | null = null

      Returns Promise<
          {
              data: TiltifyFundraisingEvent[];
              error?: string;
              metadata: TiltifyMetadata;
          },
      >

    • Gets bids for an auction item with pagination metadata.

      Parameters

      • auctionHouseID: string
      • auctionItemID: string
      • limit: number = 100
      • cursor: string | null = null
      • cursorMode: "before" | "after" = "after"

      Returns Promise<
          { data: TiltifyAuctionBid[]; error?: string; metadata: TiltifyMetadata },
      >

    • Gets auction items for a given auction house.

      Parameters

      • auctionHouseID: string
      • Optionaloptions: {
            created_after?: string;
            created_before?: string;
            limit?: number;
            status?: TiltifyAuctionItemStatus;
            updated_after?: string;
            updated_before?: string;
        }

      Returns Promise<TiltifyAuctionItem[]>

    • Fetches an OAuth access token from Tiltify using the client_credentials grant. Only valid in CLIENT auth mode.

      • DISABLED mode → returns null (proxy-handled auth).
      • USER mode → throws (call OverrideAuthToken instead).

      Parameters

      • clientID: string | undefined = undefined

        Falls back to process.env.TILTIFY_CLIENT_ID.

      • clientSecret: string | undefined = undefined

        Falls back to process.env.TILTIFY_SECRET.

      • scope: TiltifyOAuthScope = "cause"

        OAuth scope to request. Defaults to "cause".

      Returns Promise<string | null>

      The bearer token string, or null if auth is disabled.

      On missing credentials, rejected credentials, or wrong mode.

      tiltify.UseClientAuth();
      await tiltify.GetAuthToken(process.env.TILTIFY_CLIENT_ID, process.env.TILTIFY_SECRET);
    • Gets donations for a given campaign with optional date range filters.

      Parameters

      • campaignID: string
      • isTeam: boolean = false
      • count: number = 10
      • completed_before: string | Date | null = null
      • completed_after: string | Date | null = null

      Returns Promise<TiltifyDonation[]>

    • Gets donations for the current cause. Requires cause mode + API key.

      Parameters

      • count: number = 10
      • created_before: string | null = null
      • created_after: string | null = null

      Returns Promise<TiltifyDonation[]>

    • Gets the donor leaderboard for a given cause.

      Parameters

      • causeID: string
      • timeType: "all" | "daily" | "weekly" | "monthly" | "yearly" | "ytd" = "all"
      • max: number = Number.MAX_VALUE

      Returns Promise<TiltifyLeaderboardEntry[]>

    • Gets the top teams by fitness distance for a given fundraising event.

      Parameters

      • fundraisingEventID: string
      • timeType: "all" | "daily" | "weekly" | "monthly" | "yearly" | "ytd" = "all"
      • max: number = 20

      Returns Promise<TiltifyLeaderboardEntry[]>

    • Gets the top teams by fitness time for a given fundraising event.

      Parameters

      • fundraisingEventID: string
      • timeType: "all" | "daily" | "weekly" | "monthly" | "yearly" | "ytd" = "all"
      • max: number = 20

      Returns Promise<TiltifyLeaderboardEntry[]>

    • Gets the top users by fitness distance for a given fundraising event.

      Parameters

      • fundraisingEventID: string
      • timeType: "all" | "daily" | "weekly" | "monthly" | "yearly" | "ytd" = "all"
      • max: number = 20

      Returns Promise<TiltifyLeaderboardEntry[]>

    • Gets the top users by fitness time for a given fundraising event.

      Parameters

      • fundraisingEventID: string
      • timeType: "all" | "daily" | "weekly" | "monthly" | "yearly" | "ytd" = "all"
      • max: number = 20

      Returns Promise<TiltifyLeaderboardEntry[]>

    • Gets the donor leaderboard for a given campaign.

      Parameters

      • campaignID: string
      • timeType: "all" | "daily" | "weekly" | "monthly" | "yearly" | "ytd" = "all"
      • isTeam: boolean = false
      • max: number = Number.MAX_VALUE

      Returns Promise<TiltifyLeaderboardEntry[]>

    • Gets the donor leaderboard for a given campaign, returning the raw paginated response.

      Parameters

      • campaignID: string
      • timeType: "all" | "daily" | "weekly" | "monthly" | "yearly" | "ytd" = "all"
      • isTeam: boolean = false
      • max: number = Number.MAX_VALUE
      • cursor: string | null = null

      Returns Promise<
          {
              data: TiltifyLeaderboardEntry[];
              error?: string;
              metadata: TiltifyMetadata;
          },
      >

    • Gets the next unachieved milestone for a campaign based on amount raised.

      Parameters

      • campaignID: string
      • isTeam: boolean = false
      • amountRaised: number | null = null

      Returns Promise<TiltifyMilestone | null>

    • Gets a single poll by ID for a given campaign.

      Parameters

      • campaignID: string
      • pollID: string
      • isTeam: boolean = false

      Returns Promise<TiltifyPoll | null>

    • Gets the user leaderboard for a given team campaign.

      Parameters

      • campaignID: string
      • timeType: "all" | "daily" | "weekly" | "monthly" | "yearly" | "ytd" = "all"
      • max: number = Number.MAX_VALUE

      Returns Promise<TiltifyLeaderboardEntry[]>

    • Manually sets the current bearer token, its expiration, and (optionally) a refresh token. The canonical way to authenticate in USER auth mode.

      Parameters

      • token: string

        Full Authorization-header value (e.g. "Bearer eyJ...").

      • expiration: number

        Milliseconds timestamp at which the token expires.

      • OptionalrefreshToken: string | null

        OAuth refresh token. Pass undefined to leave any previously stored refresh token in place; pass null to explicitly clear it.

      Returns void

      tiltify.UseUserAuth();
      tiltify.SetCredentials(clientID, clientSecret);
      tiltify.OverrideAuthToken(`Bearer ${accessToken}`, Date.now() + expiresInMs, refreshToken);
    • Type Parameters

      • T

      Parameters

      • endpoint: string
      • method: string = "get"
      • Optionalretry: number
      • scope: TiltifyOAuthScope = "cause"
      • body: string | null = null
      • handleError: boolean = true

      Returns Promise<{ data: T; status: number }>

    • Exchanges the currently stored refresh token for a fresh access token. Only valid in USER auth mode.

      Returns Promise<string | null>

      The new bearer token string, or null if auth is disabled.

      If not in USER mode, no refresh token has been stored, client credentials are missing (direct mode only), or the OAuth server rejects the refresh request.

      tiltify.UseUserAuth();
      tiltify.UseProxy("prod");
      tiltify.OverrideAuthToken(`Bearer ${at}`, exp, refreshToken);
      await tiltify.RefreshAuthToken();
    • Stores the Cause API key sent as Cause-Api-Key on cause-mode requests.

      Parameters

      • apiKey: string

        The Tiltify-issued cause API key.

      Returns void

      tiltify.SetCauseMode();
      tiltify.SetCauseApiKey(process.env.CAUSE_API_KEY);
    • Sets the client ID + secret used for client-credential auth. Takes precedence over TILTIFY_CLIENT_ID / TILTIFY_SECRET env vars.

      Parameters

      • clientId: string

        Tiltify application client ID.

      • clientSecret: string

        Tiltify application client secret.

      Returns void

      tiltify.UseClientAuth();
      tiltify.SetCredentials("my-client-id", "my-client-secret");
      await tiltify.GetAuthToken();
    • Replaces the built-in console.*-based logger with a custom sink — for example to forward logs to Sentry, pino, or any structured logger.

      Parameters

      • fn: LogFn

        A LogFn that handles (level, scope, message, ctx).

      Returns void

      tiltify.SetLogger((level, scope, message, ctx) => {
      myLogger[level]({ scope, ctx }, message);
      });
    • Sets the minimum log level. Anything below the chosen level is dropped. Use "silent" to suppress all logging.

      Parameters

      • level: LogLevel

        One of "debug" | "info" | "warn" | "error" | "silent".

      Returns void

      tiltify.SetLogLevel("debug"); // see everything
      tiltify.SetLogLevel("silent"); // see nothing
    • Sets the maximum retry count for transient failures (default 5).

      PerformRequest retries 401/502/5xx responses and AbortError timeouts up to this many times, with 0.5s backoff between attempts. Each attempt is a fresh fetch() and so produces its own OTEL undici span — lowering this is the right knob for "best effort" Lambdas (e.g. periodic ticks, fire-and-forget snapshots) where a single failed read is cheap and the next invocation will retry anyway, and where the per-attempt OTEL error span volume is unwanted dashboard noise.

      Pass 0 to disable retries entirely.

      Parameters

      • maxRetries: number

      Returns void

    • Sets a wall-clock ceiling on the total time a single PerformRequest (including all retry sleeps) may spend before short-circuiting with the last observed error. Defaults to 0 (disabled) so _maxRetries alone governs retry behavior — opt in from short-timeout callers such as API-Gateway lambdas that would otherwise burn ~15s on a full exponential-backoff chain while their client has already timed out.

      The cap is checked before each retry sleep; a sleep that would push Date.now() past the deadline aborts the retry loop and throws the response's error immediately. Explicit Retry-After headers are still honoured whenever they fit within the remaining budget.

      Pass 0 to disable the cap.

      Parameters

      • ms: number

        Maximum retry budget in milliseconds.

      Returns void

    • Overrides the value sent in the source-tagging header (X-Source by default).

      Parameters

      • source: string

        The source identifier (e.g. an app name or build ID).

      Returns void

    • Overrides the outbound User-Agent header. Useful when a consumer wants Tiltify-side logs (and Cloudflare bot-scoring) to attribute traffic to a specific PLAY LIVE surface instead of the generic library default. The value is sent verbatim on every fetch — token mints, refresh exchanges, and all REST calls.

      Parameters

      • userAgent: string

        A non-empty UA string. Empty / whitespace-only values are ignored so consumers cannot accidentally fall back to Node's bare node default by passing "".

      Returns void

      tiltify.SetUserAgent("playlive-rest-api/1.0 (+https://playlive.experience.stjude.org)");
      
    • Internal

      Test helper: manually overrides the token expiration time.

      Parameters

      • expiration: number

        A Date-compatible milliseconds timestamp.

      Returns void

    • Configures the library to use a Tiltify proxy. Disables direct auth and overrides the base URL. Also clears any leftover bearer token stashed by a previous GetAuthToken / OverrideAuthToken call — the proxy handles auth server-side, and leaving a stale (or cause-scoped) bearer on the singleton would poison downstream requests. USER mode is preserved so consumers driving their own OAuth flow keep their token.

      Parameters

      • envOrURL: string = PROXY_URLS.prod

        Either an env shorthand ("dev" | "qa" | "prod") or an explicit proxy base URL. Defaults to the production St. Jude proxy.

      • Optionalsource: string

        Optional value for the source-tagging header.

      Returns void

      tiltify.UseProxy("https://your-proxy.example.com/api/");
      tiltify.SetPublicMode();
      const campaign = await tiltify.FindCampaign("team", "campaign");
    • Enables proxy mode with an automatic env fallback chain (prod → qa → dev). Transient or server-side failures advance the chain; 4xx responses propagate immediately.

      Parameters

      • Optionalsource: string

        Optional source-tag header value (see UseProxy).

      Returns void

      tiltify.UseProxyWithFallback();
      const user = await tiltify.FindUser("some-user-slug");
    • Switches to user OAuth auth mode.

      In this mode the library does not perform the initial OAuth code-exchange — the consumer is responsible for that step (typically on a server they control) and pushes the resulting bearer token into the client via OverrideAuthToken. If the consumer also supplies a refresh token, the library will transparently exchange it for a fresh access token when the current one expires (see RefreshAuthToken).

      Returns void

      tiltify.UseUserAuth();
      tiltify.UseProxy();
      tiltify.SetCredentials(clientID, clientSecret);
      tiltify.OverrideAuthToken(`Bearer ${accessToken}`, expiresAtMs, refreshToken);
      const me = await tiltify.GetCurrentUser();
    • Waits asynchronously for the given number of seconds. Useful for Tiltify rate-limit handling.

      Parameters

      • seconds: number

        Number of seconds to wait.

      Returns Promise<void>