UNPKG

autumn-js

Version:
963 lines (940 loc) 26.8 kB
import { logger } from "./chunk-WNUBT3GZ.mjs"; // src/utils/encryptUtils.tsx import crypto from "crypto"; // src/sdk/error.ts var AutumnError = class _AutumnError extends Error { message; code; constructor(response) { super(response.message); this.message = response.message; this.code = response.code; } static fromError(error) { return new _AutumnError({ message: error.message || "Unknown error", code: error.code || "unknown_error" }); } toString() { return `${this.message} (code: ${this.code})`; } toJSON() { return { message: this.message, code: this.code }; } }; // src/sdk/general/genMethods.ts var handleCheckout = async ({ instance, params }) => { return instance.post("/checkout", params); }; var handleAttach = async ({ instance, params }) => { return instance.post("/attach", params); }; var handleSetupPayment = async ({ instance, params }) => { return instance.post("/setup_payment", params); }; var handleCancel = async ({ instance, params }) => { return instance.post("/cancel", params); }; var handleTrack = async ({ instance, params }) => { return instance.post("/track", params); }; var handleUsage = async ({ instance, params }) => { return instance.post("/usage", params); }; var handleCheck = async ({ instance, params }) => { return instance.post("/check", params); }; var handleQuery = async ({ instance, params }) => { return instance.post("/query", params); }; // src/libraries/backend/constants.ts var autumnApiUrl = "https://api.useautumn.com/v1"; // src/sdk/utils.ts import queryString from "query-string"; var staticWrapper = (callback, instance, args) => { if (!instance) { instance = new Autumn(); } return callback({ instance, ...args }); }; var buildQueryString = (params) => { if (!params) return ""; return queryString.stringify(params, { skipNull: true, skipEmptyString: true }); }; var buildPathWithQuery = (basePath, params) => { const query = buildQueryString(params); return query ? `${basePath}?${query}` : basePath; }; // src/sdk/customers/cusMethods.ts var customerMethods = (instance) => { return { list: (params) => staticWrapper(listCustomers, instance, { params }), get: (id, params) => staticWrapper(getCustomer, instance, { id, params }), create: (params) => staticWrapper(createCustomer, instance, { params }), update: (id, params) => staticWrapper(updateCustomer, instance, { id, params }), delete: (id, params) => staticWrapper(deleteCustomer, instance, { id, params }), billingPortal: (id, params) => staticWrapper(billingPortal, instance, { id, params }), updateBalances: (id, params) => staticWrapper(updateBalances, instance, { id, params }) }; }; var getExpandStr = (expand) => { if (!expand) { return ""; } return `expand=${expand.join(",")}`; }; var listCustomers = async ({ instance, params }) => { const path = buildPathWithQuery("/customers", params); return instance.get(path); }; var getCustomer = async ({ instance, id, params }) => { if (!id) { return { data: null, error: new AutumnError({ message: "Customer ID is required", code: "CUSTOMER_ID_REQUIRED" }) }; } return instance.get(`/customers/${id}?${getExpandStr(params?.expand)}`); }; var createCustomer = async ({ instance, params }) => { return instance.post(`/customers?${getExpandStr(params?.expand)}`, params); }; var updateCustomer = async ({ instance, id, params }) => { return instance.post(`/customers/${id}`, params); }; var deleteCustomer = async ({ instance, id, params }) => { return instance.delete(`/customers/${id}${params?.delete_in_stripe ? "?delete_in_stripe=true" : ""}`); }; var billingPortal = async ({ instance, id, params }) => { return instance.post(`/customers/${id}/billing_portal`, params); }; var updateBalances = async ({ instance, id, params }) => { return instance.post(`/customers/${id}/balances`, { balances: Array.isArray(params) ? params : [params] }); }; // src/sdk/customers/entities/entMethods.ts var entityMethods = (instance) => { return { get: (customer_id, entity_id, params) => staticWrapper(getEntity, instance, { customer_id, entity_id, params }), create: (customer_id, params) => staticWrapper(createEntity, instance, { customer_id, params }), transfer: (customer_id, params) => staticWrapper(transferProduct, instance, { customer_id, params }), delete: (customer_id, entity_id) => staticWrapper(deleteEntity, instance, { customer_id, entity_id }) }; }; var getExpandStr2 = (expand) => { if (!expand) { return ""; } return `expand=${expand.join(",")}`; }; var getEntity = async ({ instance, customer_id, entity_id, params }) => { return instance.get( `/customers/${customer_id}/entities/${entity_id}?${getExpandStr2( params?.expand )}` ); }; var createEntity = async ({ instance, customer_id, params }) => { return instance.post(`/customers/${customer_id}/entities`, params); }; var deleteEntity = async ({ instance, customer_id, entity_id }) => { return instance.delete(`/customers/${customer_id}/entities/${entity_id}`); }; var transferProduct = async ({ instance, customer_id, params }) => { return instance.post(`/customers/${customer_id}/transfer`, params); }; // src/sdk/products/prodMethods.ts var productMethods = (instance) => { return { get: (id) => staticWrapper(getProduct, instance, { id }), create: (params) => staticWrapper(createProduct, instance, { params }), list: (params) => staticWrapper(listProducts, instance, { params }), delete: (id) => staticWrapper(deleteProduct, instance, { id }) }; }; var listProducts = async ({ instance, params }) => { let path = "/products_beta"; if (params) { const queryParams = new URLSearchParams(); for (const [key, value] of Object.entries(params)) { if (value !== void 0) { queryParams.append(key, String(value)); } } const queryString2 = queryParams.toString(); if (queryString2) { path += `?${queryString2}`; } } return instance.get(path); }; var getProduct = async ({ instance, id }) => { return instance.get(`/products/${id}`); }; var createProduct = async ({ instance, params }) => { return instance.post("/products", params); }; var deleteProduct = async ({ instance, id, params }) => { const path = buildPathWithQuery(`/products/${id}`, params); return instance.delete(path); }; // src/sdk/referrals/referralMethods.ts var referralMethods = (instance) => { return { createCode: (params) => staticWrapper(createReferralCode, instance, { params }), redeemCode: (params) => staticWrapper(redeemReferralCode, instance, { params }) }; }; var createReferralCode = async ({ instance, params }) => { return instance.post("/referrals/code", params); }; var redeemReferralCode = async ({ instance, params }) => { return instance.post("/referrals/redeem", params); }; // src/sdk/response.ts var toContainerResult = async ({ response, logger: logger2, logError = true }) => { if (response.status < 200 || response.status >= 300) { let error; try { error = await response.json(); if (logError) { logger2.error(`[Autumn] ${error.message}`); } } catch (error2) { throw error2; } return { data: null, error: new AutumnError({ message: error.message, code: error.code }), statusCode: response.status }; } try { const data = await response.json(); return { data, error: null, statusCode: response?.status }; } catch (error) { throw error; } }; // src/sdk/features/featureMethods.ts var featureMethods = (instance) => { return { list: () => staticWrapper(listFeatures, instance, {}), get: (id) => staticWrapper(getFeature, instance, { id }) }; }; var listFeatures = async ({ instance, params }) => { let path = "/features"; if (params) { const queryParams = new URLSearchParams(); for (const [key, value] of Object.entries(params)) { if (value !== void 0) { queryParams.append(key, String(value)); } } const queryString2 = queryParams.toString(); if (queryString2) { path += `?${queryString2}`; } } return instance.get(path); }; var getFeature = async ({ instance, id }) => { return instance.get(`/features/${id}`); }; // src/sdk/client.ts var LATEST_API_VERSION = "1.2"; var Autumn = class { secretKey; publishableKey; headers; url; logger = console; constructor(options) { try { this.secretKey = options?.secretKey || process.env.AUTUMN_SECRET_KEY; this.publishableKey = options?.publishableKey || process.env.AUTUMN_PUBLISHABLE_KEY; } catch (error) { } if (!this.secretKey && !this.publishableKey && !options?.headers) { throw new Error("Autumn secret key or publishable key is required"); } this.headers = options?.headers || { Authorization: `Bearer ${this.secretKey || this.publishableKey}`, "Content-Type": "application/json" }; let version = options?.version || LATEST_API_VERSION; this.headers["x-api-version"] = version; this.url = options?.url || autumnApiUrl; this.logger = logger; this.logger.level = options?.logLevel || "info"; } async get(path) { const response = await fetch(`${this.url}${path}`, { headers: this.headers }); return toContainerResult({ response, logger: this.logger }); } async post(path, body) { try { const response = await fetch(`${this.url}${path}`, { method: "POST", headers: this.headers, body: JSON.stringify(body) }); return toContainerResult({ response, logger: this.logger }); } catch (error) { console.error("Error sending request:", error); throw error; } } async delete(path) { const response = await fetch(`${this.url}${path}`, { method: "DELETE", headers: this.headers }); return toContainerResult({ response, logger: this.logger }); } static customers = customerMethods(); static products = productMethods(); static entities = entityMethods(); static referrals = referralMethods(); static features = featureMethods(); customers = customerMethods(this); products = productMethods(this); entities = entityMethods(this); referrals = referralMethods(this); features = featureMethods(this); /** * Initiates a checkout flow for a product purchase. * * The checkout function handles the purchase process for products with pricing. * It determines whether to show a dialog for user input or redirect directly * to Stripe based on the customer's state and product requirements. * * @param params - Checkout parameters including product ID, customer data, and options * @returns Promise resolving to checkout details including pricing, prorations, and URLs * * @example * ```typescript * const result = await autumn.checkout({ * customer_id: "user_123", * product_id: "pro", * success_url: "https://myapp.com/success" * }); * * if (result.url) { * // Redirect to Stripe checkout * window.location.href = result.url; * } * ``` */ async checkout(params) { return handleCheckout({ instance: this, params }); } static checkout = (params) => staticWrapper(handleCheckout, void 0, { params }); static usage = (params) => staticWrapper(handleUsage, void 0, { params }); /** * Attaches a product to a customer, enabling access and handling billing. * * The attach function activates a product for a customer and applies all product items. * When you attach a product: * - The customer gains access to all features in the product * - If the product has prices, the customer will be billed accordingly * - If there's no existing payment method, a checkout URL will be generated * * @param params - Attach parameters including customer ID, product ID, and options * @returns Promise resolving to attachment result with checkout URL if needed * * @example * ```typescript * const result = await autumn.attach({ * customer_id: "user_123", * product_id: "pro", * success_url: "https://myapp.com/success" * }); * * if (result.checkout_url) { * // Payment required - redirect to checkout * window.location.href = result.checkout_url; * } else { * // Product successfully attached * console.log("Access granted:", result.message); * } * ``` */ async attach(params) { return handleAttach({ instance: this, params }); } static attach = (params) => staticWrapper(handleAttach, void 0, { params }); static setupPayment = (params) => staticWrapper(handleSetupPayment, void 0, { params }); /** * Sets up a payment method for a customer. * * This method allows you to set up payment methods for customers without * immediately charging them. Useful for collecting payment information * before product attachment or for updating existing payment methods. * * @param params - Setup payment parameters including customer information * @returns Promise resolving to setup payment result * * @example * ```typescript * const result = await autumn.setupPayment({ * customer_id: "user_123" * }); * ``` */ async setupPayment(params) { return handleSetupPayment({ instance: this, params }); } static cancel = (params) => staticWrapper(handleCancel, void 0, { params }); /** * Cancels a customer's subscription or product attachment. * * This method allows you to cancel a customer's subscription to a specific product. * You can choose to cancel immediately or at the end of the billing cycle. * * @param params - Cancel parameters including customer ID and product ID * @returns Promise resolving to cancellation result * * @example * ```typescript * const result = await autumn.cancel({ * customer_id: "user_123", * product_id: "pro", * cancel_immediately: false // Cancel at end of billing cycle * }); * ``` */ async cancel(params) { return handleCancel({ instance: this, params }); } static check = (params) => staticWrapper(handleCheck, void 0, { params }); /** * Checks if a customer has access to a specific feature. * * This method verifies whether a customer has permission to use a feature * and checks their remaining balance/usage limits. It can be used to gate * features and determine when to show upgrade prompts. * * @param params - Check parameters including customer ID and feature ID * @returns Promise resolving to access check result with allowed status and balance info * * @example * ```typescript * const result = await autumn.check({ * customer_id: "user_123", * feature_id: "messages", * required_balance: 1 * }); * * if (!result.allowed) { * console.log("Feature access denied - upgrade required"); * } * ``` */ async check(params) { return handleCheck({ instance: this, params }); } static track = (params) => staticWrapper(handleTrack, void 0, { params }); /** * Tracks usage events for features or analytics. * * This method records usage events for metered features, updating the customer's * balance and usage statistics. It's typically used server-side to ensure * accurate tracking that cannot be manipulated by users. * * @param params - Track parameters including customer ID, feature ID, and usage value * @returns Promise resolving to tracking result * * @example * ```typescript * const result = await autumn.track({ * customer_id: "user_123", * feature_id: "messages", * value: 1 // Track 1 message sent * }); * ``` */ async track(params) { return handleTrack({ instance: this, params }); } /** * Retrieves usage statistics and analytics for a customer. * * This method fetches detailed usage information for a customer's features, * including current balances, usage history, and analytics data. Useful * for displaying usage dashboards or generating reports. * * @param params - Usage parameters including customer ID and optional filters * @returns Promise resolving to usage statistics and analytics data * * @example * ```typescript * const result = await autumn.usage({ * customer_id: "user_123", * feature_id: "messages" * value: 20 // Usage value * }); * ``` */ async usage(params) { return handleUsage({ instance: this, params }); } static query = (params) => staticWrapper(handleQuery, void 0, { params }); /** * Performs advanced queries on customer data and analytics. * * This method allows you to run complex queries against customer data, * usage patterns, and billing information. Useful for generating reports, * analytics, and custom data insights. * * @param params - Query parameters including customer ID and query specifications * @returns Promise resolving to query results with requested data * * @example * ```typescript * const result = await autumn.query({ * customer_id: "user_123", * feature_id: "messages" // feature id to fetch for query, can also be an array * }); * * ``` */ async query(params) { return handleQuery({ instance: this, params }); } }; // src/sdk/products/prodEnums.ts var ProductItemInterval = /* @__PURE__ */ ((ProductItemInterval2) => { ProductItemInterval2["Minute"] = "minute"; ProductItemInterval2["Hour"] = "hour"; ProductItemInterval2["Day"] = "day"; ProductItemInterval2["Week"] = "week"; ProductItemInterval2["Month"] = "month"; ProductItemInterval2["Quarter"] = "quarter"; ProductItemInterval2["SemiAnnual"] = "semi_annual"; ProductItemInterval2["Year"] = "year"; ProductItemInterval2["Multiple"] = "multiple"; return ProductItemInterval2; })(ProductItemInterval || {}); // src/sdk/customers/cusEnums.ts import { z } from "zod/v4"; var CustomerExpandEnum = z.enum([ "invoices", "rewards", "trials_used", "entities", "referrals", "payment_method" ]); // src/sdk/customers/cusTypes.ts import { z as z2 } from "zod/v4"; var CoreCusFeatureSchema = z2.object({ unlimited: z2.boolean().optional(), interval: z2.enum(ProductItemInterval).optional(), balance: z2.number().nullish(), usage: z2.number().optional(), included_usage: z2.number().optional(), next_reset_at: z2.number().nullish(), overage_allowed: z2.boolean().optional(), usage_limit: z2.number().optional(), rollovers: z2.object({ balance: z2.number(), expires_at: z2.number() }).optional(), breakdown: z2.array( z2.object({ interval: z2.enum(ProductItemInterval), balance: z2.number().optional(), usage: z2.number().optional(), included_usage: z2.number().optional(), next_reset_at: z2.number().optional() }) ).optional(), credit_schema: z2.array( z2.object({ feature_id: z2.string(), credit_amount: z2.number() }) ).optional() }); var CustomerDataSchema = z2.object({ name: z2.string().nullish(), email: z2.string().nullish(), fingerprint: z2.string().nullish() }); var CreateCustomerParamsSchema = z2.object({ id: z2.string().nullish(), email: z2.string().nullish(), name: z2.string().nullish(), fingerprint: z2.string().nullish(), metadata: z2.record(z2.string(), z2.any()).optional(), expand: z2.array(CustomerExpandEnum).optional(), stripe_id: z2.string().nullish() }); var BillingPortalParamsSchema = z2.object({ return_url: z2.string().optional() }); var UpdateBalancesParamsSchema = z2.object({ feature_id: z2.string(), balance: z2.number() }).or( z2.array( z2.object({ feature_id: z2.string(), balance: z2.number() }) ) ); var DeleteCustomerParamsSchema = z2.object({ delete_in_stripe: z2.boolean().optional() }); var ListCustomersParamsSchema = z2.object({ limit: z2.number().optional(), offset: z2.number().optional() }); // src/sdk/general/checkTypes.ts import { z as z3 } from "zod/v4"; var CheckFeatureResultSchema = z3.object({ allowed: z3.boolean(), feature_id: z3.string(), customer_id: z3.string(), entity_id: z3.string().optional(), required_balance: z3.number() }).extend(CoreCusFeatureSchema.shape); // src/sdk/customers/entities/entTypes.ts import { z as z4 } from "zod/v4"; var EntityDataSchema = z4.object({ name: z4.string().optional(), feature_id: z4.string() }); var TransferProductParamsSchema = z4.object({ from_entity_id: z4.string(), to_entity_id: z4.string(), product_id: z4.string() }); // src/sdk/general/genTypes.ts import { z as z5 } from "zod/v4"; var CancelParamsSchema = z5.object({ customer_id: z5.string(), product_id: z5.string(), entity_id: z5.string().optional(), cancel_immediately: z5.boolean().optional() }); var CancelResultSchema = z5.object({ success: z5.boolean(), customer_id: z5.string(), product_id: z5.string() }); var TrackParamsSchema = z5.object({ customer_id: z5.string(), value: z5.number().optional(), feature_id: z5.string().optional(), event_name: z5.string().optional(), entity_id: z5.string().optional(), customer_data: z5.any().optional(), idempotency_key: z5.string().optional(), entity_data: z5.any().optional(), properties: z5.record(z5.string(), z5.any()).optional() }); var TrackResultSchema = z5.object({ id: z5.string(), code: z5.string(), customer_id: z5.string(), feature_id: z5.string().optional(), event_name: z5.string().optional() }); var CheckParamsSchema = z5.object({ customer_id: z5.string(), feature_id: z5.string().optional(), product_id: z5.string().optional(), entity_id: z5.string().optional(), customer_data: z5.any().optional(), required_balance: z5.number().optional(), send_event: z5.boolean().optional(), with_preview: z5.boolean().optional(), entity_data: EntityDataSchema.optional() }); var QueryRangeEnum = z5.enum(["24h", "7d", "30d", "90d", "last_cycle"]); var QueryParamsSchema = z5.object({ customer_id: z5.string(), feature_id: z5.string().or(z5.array(z5.string())), range: QueryRangeEnum.optional() }); // src/sdk/referrals/referralTypes.ts import { z as z6 } from "zod/v4"; var CreateReferralCodeParamsSchema = z6.object({ customer_id: z6.string(), program_id: z6.string() }); var RedeemReferralCodeParamsSchema = z6.object({ code: z6.string(), customer_id: z6.string() }); // src/sdk/general/attachTypes.ts import { z as z7 } from "zod/v4"; var AttachFeatureOptionsSchema = z7.object({ feature_id: z7.string(), quantity: z7.number() }); var AttachParamsSchema = z7.object({ customer_id: z7.string(), product_id: z7.string().optional(), entity_id: z7.string().optional(), options: z7.array(AttachFeatureOptionsSchema).optional(), product_ids: z7.array(z7.string()).optional(), free_trial: z7.boolean().optional(), success_url: z7.string().optional(), metadata: z7.record(z7.string(), z7.string()).optional(), force_checkout: z7.boolean().optional(), customer_data: CustomerDataSchema.optional(), entity_data: z7.any().optional(), checkout_session_params: z7.record(z7.string(), z7.any()).optional(), reward: z7.string().optional(), invoice: z7.boolean().optional() }); var AttachResultSchema = z7.object({ checkout_url: z7.string().optional(), customer_id: z7.string(), product_ids: z7.array(z7.string()), code: z7.string(), message: z7.string(), customer_data: z7.any().optional(), invoice: z7.object({ status: z7.string(), stripe_id: z7.string(), hosted_invoice_url: z7.string().nullable(), total: z7.number(), currency: z7.string() }).optional() }); var CheckoutParamsSchema = z7.object({ customer_id: z7.string(), product_id: z7.string(), product_ids: z7.array(z7.string()).optional(), entity_id: z7.string().optional(), options: z7.array(AttachFeatureOptionsSchema).optional(), force_checkout: z7.boolean().optional(), invoice: z7.boolean().optional(), success_url: z7.string().optional(), customer_data: CustomerDataSchema.optional(), entity_data: z7.any().optional(), checkout_session_params: z7.record(z7.string(), z7.any()).optional(), reward: z7.string().optional() }); // src/sdk/features/featureTypes.ts import { z as z8 } from "zod/v4"; var FeatureType = /* @__PURE__ */ ((FeatureType2) => { FeatureType2["Boolean"] = "boolean"; FeatureType2["SingleUse"] = "single_use"; FeatureType2["ContinuousUse"] = "continuous_use"; FeatureType2["CreditSystem"] = "credit_system"; return FeatureType2; })(FeatureType || {}); var FeatureSchema = z8.object({ id: z8.string(), name: z8.string(), type: z8.enum(FeatureType), display: z8.object({ singular: z8.string(), plural: z8.string() }).nullish(), credit_schema: z8.array( z8.object({ metered_feature_id: z8.string(), credit_cost: z8.number() }) ).nullish(), archived: z8.boolean() }); // src/utils/encryptUtils.tsx var getKey = () => { if (!process.env.AUTUMN_SECRET_KEY) { throw new AutumnError({ message: "Autumn secret key not found in process.env.AUTUMN_SECRET_KEY. Please set it in your .env file.", code: "secret_key_not_found" }); } return crypto.createHash("sha512").update(process.env.AUTUMN_SECRET_KEY).digest("hex").substring(0, 32); }; function encryptData(data) { let key; try { key = getKey(); } catch (error) { throw new AutumnError({ message: `Failed to encrypt customer ID. ${error.message}`, code: "encrypt_customer_id_failed" }); } const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv("aes-256-cbc", key, iv); const encrypted = Buffer.concat([ cipher.update(data, "utf8"), cipher.final() ]); const result = Buffer.concat([iv, encrypted]); return result.toString("base64"); } function decryptData(encryptedData) { const buffer = Buffer.from(encryptedData, "base64"); const iv = buffer.slice(0, 16); const encrypted = buffer.slice(16); const key = getKey(); const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv); const decrypted = Buffer.concat([ decipher.update(encrypted), decipher.final() ]); return decrypted.toString("utf8"); } export { decryptData, encryptData };