Sign In

@clocknext/sdk

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@clocknext/sdk - npm Package Compare versions

Comparing version
0.4.0
to
0.5.0
+44
-18
dist/index.cjs

@@ -232,3 +232,3 @@ 'use strict';

// src/http.ts
var SDK_VERSION = "0.4.0" ;
var SDK_VERSION = "0.5.0" ;
var Transport = class {

@@ -343,5 +343,5 @@ constructor(cfg) {

}
/** Create a credit type. `POST /api/v1/credits`. */
/** Create a credit type; returns the created credit. `POST /api/v1/credits`. */
async create(input) {
await this.transport.request({
const res = await this.transport.request({
method: "POST",

@@ -351,2 +351,3 @@ path: "/api/v1/credits",

});
return res.credit;
}

@@ -361,5 +362,5 @@ /** Fetch one credit type with usage stats. `GET /api/v1/credits/:id`. */

}
/** Update a credit type's definition. `PATCH /api/v1/credits/:id`. */
/** Update a credit type's definition; returns the updated credit. `PATCH /api/v1/credits/:id`. */
async update(id, input) {
await this.transport.request({
const res = await this.transport.request({
method: "PATCH",

@@ -369,2 +370,3 @@ path: `/api/v1/credits/${encodeURIComponent(id)}`,

});
return res.credit;
}

@@ -449,8 +451,8 @@ /** Activate or deactivate a credit type. */

}
/** A customer's usage history. `GET /api/v1/customers/:id/usage`. */
/** A customer's usage history. `GET /api/v1/usage?customerId=`. */
async usage(id, params = {}) {
const res = await this.transport.request({
method: "GET",
path: `/api/v1/customers/${encodeURIComponent(id)}/usage`,
query: { limit: params.limit }
path: `/api/v1/usage`,
query: { customerId: id, limit: params.limit }
});

@@ -466,2 +468,33 @@ return { customer: res.customer, totals: res.totals, logs: res.logs };

}
/**
* One credit balance for a customer, matched by `creditId` or `creditName`;
* `null` when the customer has no plan or no matching credit. Convenience
* over `balances()` + `Array.find` — it fetches the FULL balances under the
* hood (there is no server-side scoped read), so prefer `balances()` when you
* need several rows from the same customer.
*/
async creditBalance(customerId, match) {
const { credits } = await this.balances(customerId);
return credits.find(
(c) => match.creditId != null && c.creditId === match.creditId || match.creditName != null && c.creditName === match.creditName
) ?? null;
}
/** One outcome balance for a customer, matched by `outcomeId` or
* `outcomeName`; `null` when absent. See {@link creditBalance} for the
* fetch-then-filter caveat. */
async outcomeBalance(customerId, match) {
const { outcomes } = await this.balances(customerId);
return outcomes.find(
(o) => match.outcomeId != null && o.outcomeId === match.outcomeId || match.outcomeName != null && o.outcomeName === match.outcomeName
) ?? null;
}
/** One unit balance for a customer, matched by `unitId` or `unitName`;
* `null` when absent. See {@link creditBalance} for the fetch-then-filter
* caveat. */
async unitBalance(customerId, match) {
const { units } = await this.balances(customerId);
return units.find(
(u) => match.unitId != null && u.unitId === match.unitId || match.unitName != null && u.unitName === match.unitName
) ?? null;
}
/** The customer's current plan. `GET …/:id/plan`. */

@@ -474,10 +507,2 @@ plan(id) {

}
/** Revenue / cost / profit / margin over a window. `GET …/:id/revenue`. */
revenue(id, params = {}) {
return this.transport.request({
method: "GET",
path: `/api/v1/customers/${encodeURIComponent(id)}/revenue`,
query: { range: params.range }
});
}
// --- Members -------------------------------------------------------------

@@ -648,5 +673,5 @@ /** List a customer's members. `GET …/:id/members`. */

}
/** Activate or deactivate an outcome type. */
/** Activate or deactivate an outcome type; returns the updated outcome. */
async setActive(id, isActive) {
await this.transport.request({
const res = await this.transport.request({
method: "PATCH",

@@ -656,2 +681,3 @@ path: `/api/v1/outcomes/${encodeURIComponent(id)}`,

});
return res.outcome;
}

@@ -658,0 +684,0 @@ /** Delete an outcome type. */

@@ -106,2 +106,14 @@ /**

}
/** The customer's remaining balance for the dimension a signal metered, AFTER
* the signal was applied — update an on-screen meter straight from the record
* response. Populated on recorded (inline / `{ wait: true }`) signals; `null`
* on dry runs and on read-back. */
interface UsageBalance {
dimension: "credit" | "outcome" | "wallet";
/** Post-signal remaining. `null` when the meter is uncapped — an ARREAR
* (pay-as-you-go) credit or outcome has no fixed allowance. */
remaining: number | null;
/** The credit / outcome name; `null` for the wallet. */
name: string | null;
}
interface SerializedUsageLog {

@@ -125,2 +137,5 @@ id: string;

outcome: SerializedOutcomeAttribution | null;
/** Post-signal balance for the metered dimension. Null on dry runs and
* read-back. */
balance: UsageBalance | null;
createdAt: string;

@@ -203,6 +218,42 @@ }

}
type RevenueRange = "30d" | "6m" | "1y" | "all";
/** Loosely typed insight payloads (revenue/balances/plan) — server shapes the
* detail; we surface the whole envelope minus the `ok` flag. */
type CustomerBalances = {
/** One credit type's running balance for a customer (an element of
* `customers.balances().credits`). */
interface CreditBalance {
creditId: string;
/** The credit's stable agent key — the same key used to record usage and to
* adjust this balance. */
agentKey: string;
creditName: string;
granted: number;
used: number;
remaining: number;
}
/** One outcome's running balance for a customer. Unlike a credit balance it
* has no `used`, and it carries the outcome's ordered step list. */
interface OutcomeBalance {
outcomeId: string;
outcomeName: string;
granted: number;
remaining: number;
/** Each step's `agentKey` is what `signals.outcome()` and the outcome adjust
* API use to address this outcome (outcomes have no key of their own). */
steps: {
id: string;
name: string;
agentKey: string;
}[];
}
/** One unit's advance allowance for a customer. No `used` field. */
interface UnitBalance {
unitId: string;
/** The unit's stable agent key — the same key used to record usage and to
* adjust this balance. */
agentKey: string;
unitName: string;
granted: number;
remaining: number;
}
/** Wallet / credit / outcome / unit balances for a customer's active plan
* (`customers.balances()`). */
interface CustomerBalances {
customerId: string;

@@ -217,19 +268,30 @@ currency: {

} | null;
credits: unknown[];
outcomes: unknown[];
units: unknown[];
};
type CustomerPlan = {
customerId: string;
currency: {
code: string;
rateUsd: number;
credits: CreditBalance[];
outcomes: OutcomeBalance[];
units: UnitBalance[];
}
/** The customer's active plan (the `plan` field of `customers.plan()`);
* `null` when the customer is unsubscribed. */
interface CustomerPlanDetails {
purchaseId: string;
planId: string | null;
planName: string;
planType: PlanType;
planKind: PlanKind;
seatScope: "CUSTOMER" | "MEMBER" | null;
billingCycle: BillingCycle;
cost: number;
status: "SCHEDULED" | "ACTIVE";
billingDate: string;
spendingLimit: number | null;
spentThisCycle: number | null;
meters: {
wallet: boolean;
credit: boolean;
outcome: boolean;
unit: boolean;
};
plan: Record<string, unknown> | null;
};
type CustomerRevenue = {
}
interface CustomerPlan {
customerId: string;
range: RevenueRange;
window: unknown;
bucket: unknown;
currency: {

@@ -239,9 +301,4 @@ code: string;

};
revenue: number;
cost: number;
profit: number;
grossMargin: number;
deltas: Record<string, unknown>;
trend: unknown[];
};
plan: CustomerPlanDetails | null;
}
interface PortalTokenInput {

@@ -362,2 +419,4 @@ customerId: string;

cost: number;
/** Signed adjustment applied to the plan's headline price (default 0). */
priceAdjustment: number;
currencyCode: string;

@@ -373,2 +432,3 @@ isActive: boolean;

invoiceCount: number;
openInvoiceCount: number;
stats: {

@@ -396,2 +456,3 @@ totalInvoiced: number;

customerName: string;
customerLogoUrl: string | null;
planId: string | null;

@@ -408,5 +469,8 @@ planName: string;

billingDate: string;
nextBillingDate: string;
status: PurchaseStatus;
voidAfterMinutes: number;
autoPayment: boolean;
autoPaymentPauseReason: string | null;
notes: string | null;
createdAt: string;

@@ -429,3 +493,6 @@ }

name: string;
logoUrl: string | null;
};
voidAfterMinutes: number;
notes: string | null;
autoPayment: boolean;

@@ -625,17 +692,24 @@ autoPaymentPauseReason: string | null;

}
/** Grant (positive) or claw back (negative) a credit balance. `delta` must be a non-zero whole number. */
/** Grant (positive) or claw back (negative) a credit balance. `delta` must be a
* non-zero whole number. The credit is addressed by its stable `agentKey`. */
interface CreditAdjustInput {
creditId: string;
/** The credit's stable agent key (the same key used to record usage). */
agentKey: string;
delta: number;
notes?: string;
}
/** Grant/claw an outcome balance. `delta` is a non-zero whole number; floored at 0. */
/** Grant/claw an outcome balance. `delta` is a non-zero whole number; floored at
* 0. The outcome is addressed by a STEP's `agentKey` (outcomes have no key of
* their own). */
interface OutcomeAdjustInput {
outcomeId: string;
/** An outcome step's stable agent key — identifies the parent outcome. */
agentKey: string;
delta: number;
notes?: string;
}
/** Grant/claw a unit balance. `delta` is non-zero (fractional allowed); floored at 0. */
/** Grant/claw a unit balance. `delta` is non-zero (fractional allowed); floored
* at 0. The unit is addressed by its stable `agentKey`. */
interface UnitAdjustInput {
unitId: string;
/** The unit's stable agent key (the same key used to record usage). */
agentKey: string;
delta: number;

@@ -654,2 +728,39 @@ notes?: string;

}
/** One point on a cost-over-time analytics series. */
interface CostPoint {
/** UTC day, `YYYY-MM-DD`. */
dateIso: string;
/** Short display label, e.g. "Jun 24". */
label: string;
/** Average cost that day, or `null` on days with no usage. */
cost: number | null;
reqs: number;
}
/** Summary stats across a cost-over-time series. */
interface CostStats {
activeDays: number;
avgCost: number | null;
peakCost: number | null;
troughCost: number | null;
deviationPct: number | null;
}
/** Cost-over-time analytics for a credit (`credits.get().analytics`). */
interface CreditAnalytics {
basePrice: number;
pricePerCredit: number;
marginPercent: number;
points: CostPoint[];
stats: CostStats;
}
/** Cost-over-time analytics for an outcome (`outcomes.get().analytics`).
* Each point adds `completions` (workflows finished that day). */
interface OutcomeAnalytics {
basePrice: number;
pricePerOutcome: number;
marginPercent: number;
points: (CostPoint & {
completions: number;
})[];
stats: CostStats;
}
interface Credit {

@@ -679,4 +790,3 @@ id: string;

};
/** Cost-over-time analytics; shape is server-defined. */
analytics: Record<string, unknown>;
analytics: CreditAnalytics;
}

@@ -730,3 +840,3 @@ interface CreateCreditInput {

};
analytics: Record<string, unknown>;
analytics: OutcomeAnalytics;
}

@@ -759,2 +869,5 @@ interface CreateOutcomeInput {

id: string;
/** Stable per-org report key — what `signals.unit({ agentKey })` sends.
* The ONLY identifier accepted when reporting unit consumption. */
agentKey: string;
name: string;

@@ -767,6 +880,19 @@ description: string | null;

createdAt: string;
createdByName: string | null;
}
/** `units.get()` — adds linked-customer sample plus stats. */
/** One row in a unit's linked-customer sample (`units.get().customers`). */
interface UnitCustomerRow {
customerId: string;
name: string;
legalName: string | null;
slug: string;
logoUrl: string | null;
granted: number;
used: number;
remaining: number;
currentlyMetered: boolean;
}
/** `units.get()` — adds linked-customer sample plus stats.
* `createdByName` is inherited from `Unit`. */
interface UnitDetail extends Unit {
createdByName: string | null;
stats: {

@@ -779,3 +905,3 @@ planCount: number;

/** First page (≤10) of customers currently metered on this unit. */
customers: Record<string, unknown>[];
customers: UnitCustomerRow[];
}

@@ -822,2 +948,18 @@ /** Flat per-event pricing — a single `flatPrice` (defaults to 0), no tiers. */

}
/** One serialized unit-consumption event — the result of `signals.unit()` and
* each element of `UnitUsageList.events`. */
interface SerializedUnitUsage {
id: string;
customerId: string;
/** Display name of the unit. */
unit: string;
/** The unit's stable agent key; `null` if the unit was deleted. */
agentKey: string | null;
billingMode: BillingMode;
/** Remaining ADVANCE allowance after this event; `null` for ARREAR. */
remaining: number | null;
customerCost: number;
member: string | null;
createdAt: string;
}
interface UnitUsageRow {

@@ -838,3 +980,3 @@ unit: string;

units: UnitUsageRow[];
events: unknown[];
events: SerializedUnitUsage[];
}

@@ -981,8 +1123,8 @@ type ThresholdKind = "CREDIT" | "OUTCOME" | "WALLET";

}): Promise<Credit[]>;
/** Create a credit type. `POST /api/v1/credits`. */
create(input: CreateCreditInput): Promise<void>;
/** Create a credit type; returns the created credit. `POST /api/v1/credits`. */
create(input: CreateCreditInput): Promise<Credit>;
/** Fetch one credit type with usage stats. `GET /api/v1/credits/:id`. */
get(id: string): Promise<CreditDetail>;
/** Update a credit type's definition. `PATCH /api/v1/credits/:id`. */
update(id: string, input: UpdateCreditInput): Promise<void>;
/** Update a credit type's definition; returns the updated credit. `PATCH /api/v1/credits/:id`. */
update(id: string, input: UpdateCreditInput): Promise<Credit>;
/** Activate or deactivate a credit type. */

@@ -996,5 +1138,5 @@ setActive(id: string, isActive: boolean): Promise<Credit>;

* The `customers` resource — full CRUD over the org's customers plus the
* read-only insight endpoints (usage / balances / plan / revenue). Every call
* is scoped to the API key's organisation server-side; a customer in another
* org resolves as a NotFoundError.
* read-only insight endpoints (usage / balances / plan). Every call is scoped
* to the API key's organisation server-side; a customer in another org
* resolves as a NotFoundError.
*/

@@ -1026,3 +1168,3 @@ declare class Customers {

delete(id: string): Promise<void>;
/** A customer's usage history. `GET /api/v1/customers/:id/usage`. */
/** A customer's usage history. `GET /api/v1/usage?customerId=`. */
usage(id: string, params?: {

@@ -1033,8 +1175,29 @@ limit?: number;

balances(id: string): Promise<CustomerBalances>;
/**
* One credit balance for a customer, matched by `creditId` or `creditName`;
* `null` when the customer has no plan or no matching credit. Convenience
* over `balances()` + `Array.find` — it fetches the FULL balances under the
* hood (there is no server-side scoped read), so prefer `balances()` when you
* need several rows from the same customer.
*/
creditBalance(customerId: string, match: {
creditId?: string;
creditName?: string;
}): Promise<CreditBalance | null>;
/** One outcome balance for a customer, matched by `outcomeId` or
* `outcomeName`; `null` when absent. See {@link creditBalance} for the
* fetch-then-filter caveat. */
outcomeBalance(customerId: string, match: {
outcomeId?: string;
outcomeName?: string;
}): Promise<OutcomeBalance | null>;
/** One unit balance for a customer, matched by `unitId` or `unitName`;
* `null` when absent. See {@link creditBalance} for the fetch-then-filter
* caveat. */
unitBalance(customerId: string, match: {
unitId?: string;
unitName?: string;
}): Promise<UnitBalance | null>;
/** The customer's current plan. `GET …/:id/plan`. */
plan(id: string): Promise<CustomerPlan>;
/** Revenue / cost / profit / margin over a window. `GET …/:id/revenue`. */
revenue(id: string, params?: {
range?: RevenueRange;
}): Promise<CustomerRevenue>;
/** List a customer's members. `GET …/:id/members`. */

@@ -1113,4 +1276,4 @@ listMembers(id: string): Promise<Member[]>;

update(id: string, input: UpdateOutcomeInput): Promise<Outcome>;
/** Activate or deactivate an outcome type. */
setActive(id: string, isActive: boolean): Promise<void>;
/** Activate or deactivate an outcome type; returns the updated outcome. */
setActive(id: string, isActive: boolean): Promise<Outcome>;
/** Delete an outcome type. */

@@ -1290,3 +1453,3 @@ delete(id: string): Promise<void>;

unit(input: UnitInput): Promise<{
unitUsage: Record<string, unknown>;
unitUsage: SerializedUnitUsage;
}>;

@@ -1458,2 +1621,2 @@ /** A customer's unit balances + recent unit events. `GET /api/v1/units`. */

export { type AddMemberInput, AllowanceError, type ApiCustomer, AuthError, type BillingCycle, type BillingMode, ClockNext, type ClockNextConfig, ClockNextError, type ComponentType, ConflictError, type CreateCreditInput, type CreateCustomerInput, type CreateOutcomeInput, type CreatePlanInput, type CreatePurchaseInput, type CreateUnitInput, type Credit, type CreditAdjustInput, type CreditComponentInput, type CreditDetail, type CreditInput, type CreditSignal, type CustomerBalances, type CustomerList, type CustomerPlan, type CustomerProfileInput, type CustomerRevenue, type DropReason, type FetchLike, type FlatComponentInput, type FlatUnitInput, type Invoice, type InvoiceDetail, type InvoiceLineItem, type InvoiceListRow, type InvoiceParty, type InvoicePlanSnapshot, type InvoiceStatus, type Logger, type Member, type MemberRole, type Model, type ModelBundleEntry, NetworkError, NotFoundError, type Outcome, type OutcomeAdjustInput, type OutcomeComponentInput, type OutcomeDetail, type OutcomeInput, type OutcomeSignal, type OutcomeStepInput, type PayLink, type PaymentDetail, type PaymentRow, type Plan, type PlanComponent, type PlanComponentInput, type PlanDetail, PlanError, type PlanKind, type PlanRef, type PlanType, type PortalToken, type PortalTokenInput, type Purchase, type PurchaseDetail, type PurchaseStatus, RateLimitError, type RevenueRange, type SerializedOutcomeAttribution, type SerializedRuleApplication, type SerializedUsageLog, ServerError, type Signal, type SignalStatus, type SignalType, type ThresholdKind, type TieredUnitInput, type Tokens, type TrackResult, type Unit, type UnitAdjustInput, type UnitComponentInput, type UnitDetail, type UnitInput, type UnitPricingType, type UnitTier, type UnitTierInput, type UnitUsageList, type UnitUsageRow, type UpdateCreditInput, type UpdateMemberInput, type UpdateOutcomeInput, type UpdatePlanInput, type UpdateUnitInput, type UpsertWebhookInput, type UsageList, ValidationError, type WalletComponentInput, type WalletEntryInput, type WalletInput, type WalletList, type WalletSignal, type WalletTransaction, type WalletTransactionType, type Webhook, type WorkspaceIdentity, signalToWire };
export { type AddMemberInput, AllowanceError, type ApiCustomer, AuthError, type BillingCycle, type BillingMode, ClockNext, type ClockNextConfig, ClockNextError, type ComponentType, ConflictError, type CostPoint, type CostStats, type CreateCreditInput, type CreateCustomerInput, type CreateOutcomeInput, type CreatePlanInput, type CreatePurchaseInput, type CreateUnitInput, type Credit, type CreditAdjustInput, type CreditAnalytics, type CreditBalance, type CreditComponentInput, type CreditDetail, type CreditInput, type CreditSignal, type CustomerBalances, type CustomerList, type CustomerPlan, type CustomerPlanDetails, type CustomerProfileInput, type DropReason, type FetchLike, type FlatComponentInput, type FlatUnitInput, type Invoice, type InvoiceDetail, type InvoiceLineItem, type InvoiceListRow, type InvoiceParty, type InvoicePlanSnapshot, type InvoiceStatus, type Logger, type Member, type MemberRole, type Model, type ModelBundleEntry, NetworkError, NotFoundError, type Outcome, type OutcomeAdjustInput, type OutcomeAnalytics, type OutcomeBalance, type OutcomeComponentInput, type OutcomeDetail, type OutcomeInput, type OutcomeSignal, type OutcomeStepInput, type PayLink, type PaymentDetail, type PaymentRow, type Plan, type PlanComponent, type PlanComponentInput, type PlanDetail, PlanError, type PlanKind, type PlanRef, type PlanType, type PortalToken, type PortalTokenInput, type Purchase, type PurchaseDetail, type PurchaseStatus, RateLimitError, type SerializedOutcomeAttribution, type SerializedRuleApplication, type SerializedUnitUsage, type SerializedUsageLog, ServerError, type Signal, type SignalStatus, type SignalType, type ThresholdKind, type TieredUnitInput, type Tokens, type TrackResult, type Unit, type UnitAdjustInput, type UnitBalance, type UnitComponentInput, type UnitCustomerRow, type UnitDetail, type UnitInput, type UnitPricingType, type UnitTier, type UnitTierInput, type UnitUsageList, type UnitUsageRow, type UpdateCreditInput, type UpdateMemberInput, type UpdateOutcomeInput, type UpdatePlanInput, type UpdateUnitInput, type UpsertWebhookInput, type UsageBalance, type UsageList, ValidationError, type WalletComponentInput, type WalletEntryInput, type WalletInput, type WalletList, type WalletSignal, type WalletTransaction, type WalletTransactionType, type Webhook, type WorkspaceIdentity, signalToWire };

@@ -106,2 +106,14 @@ /**

}
/** The customer's remaining balance for the dimension a signal metered, AFTER
* the signal was applied — update an on-screen meter straight from the record
* response. Populated on recorded (inline / `{ wait: true }`) signals; `null`
* on dry runs and on read-back. */
interface UsageBalance {
dimension: "credit" | "outcome" | "wallet";
/** Post-signal remaining. `null` when the meter is uncapped — an ARREAR
* (pay-as-you-go) credit or outcome has no fixed allowance. */
remaining: number | null;
/** The credit / outcome name; `null` for the wallet. */
name: string | null;
}
interface SerializedUsageLog {

@@ -125,2 +137,5 @@ id: string;

outcome: SerializedOutcomeAttribution | null;
/** Post-signal balance for the metered dimension. Null on dry runs and
* read-back. */
balance: UsageBalance | null;
createdAt: string;

@@ -203,6 +218,42 @@ }

}
type RevenueRange = "30d" | "6m" | "1y" | "all";
/** Loosely typed insight payloads (revenue/balances/plan) — server shapes the
* detail; we surface the whole envelope minus the `ok` flag. */
type CustomerBalances = {
/** One credit type's running balance for a customer (an element of
* `customers.balances().credits`). */
interface CreditBalance {
creditId: string;
/** The credit's stable agent key — the same key used to record usage and to
* adjust this balance. */
agentKey: string;
creditName: string;
granted: number;
used: number;
remaining: number;
}
/** One outcome's running balance for a customer. Unlike a credit balance it
* has no `used`, and it carries the outcome's ordered step list. */
interface OutcomeBalance {
outcomeId: string;
outcomeName: string;
granted: number;
remaining: number;
/** Each step's `agentKey` is what `signals.outcome()` and the outcome adjust
* API use to address this outcome (outcomes have no key of their own). */
steps: {
id: string;
name: string;
agentKey: string;
}[];
}
/** One unit's advance allowance for a customer. No `used` field. */
interface UnitBalance {
unitId: string;
/** The unit's stable agent key — the same key used to record usage and to
* adjust this balance. */
agentKey: string;
unitName: string;
granted: number;
remaining: number;
}
/** Wallet / credit / outcome / unit balances for a customer's active plan
* (`customers.balances()`). */
interface CustomerBalances {
customerId: string;

@@ -217,19 +268,30 @@ currency: {

} | null;
credits: unknown[];
outcomes: unknown[];
units: unknown[];
};
type CustomerPlan = {
customerId: string;
currency: {
code: string;
rateUsd: number;
credits: CreditBalance[];
outcomes: OutcomeBalance[];
units: UnitBalance[];
}
/** The customer's active plan (the `plan` field of `customers.plan()`);
* `null` when the customer is unsubscribed. */
interface CustomerPlanDetails {
purchaseId: string;
planId: string | null;
planName: string;
planType: PlanType;
planKind: PlanKind;
seatScope: "CUSTOMER" | "MEMBER" | null;
billingCycle: BillingCycle;
cost: number;
status: "SCHEDULED" | "ACTIVE";
billingDate: string;
spendingLimit: number | null;
spentThisCycle: number | null;
meters: {
wallet: boolean;
credit: boolean;
outcome: boolean;
unit: boolean;
};
plan: Record<string, unknown> | null;
};
type CustomerRevenue = {
}
interface CustomerPlan {
customerId: string;
range: RevenueRange;
window: unknown;
bucket: unknown;
currency: {

@@ -239,9 +301,4 @@ code: string;

};
revenue: number;
cost: number;
profit: number;
grossMargin: number;
deltas: Record<string, unknown>;
trend: unknown[];
};
plan: CustomerPlanDetails | null;
}
interface PortalTokenInput {

@@ -362,2 +419,4 @@ customerId: string;

cost: number;
/** Signed adjustment applied to the plan's headline price (default 0). */
priceAdjustment: number;
currencyCode: string;

@@ -373,2 +432,3 @@ isActive: boolean;

invoiceCount: number;
openInvoiceCount: number;
stats: {

@@ -396,2 +456,3 @@ totalInvoiced: number;

customerName: string;
customerLogoUrl: string | null;
planId: string | null;

@@ -408,5 +469,8 @@ planName: string;

billingDate: string;
nextBillingDate: string;
status: PurchaseStatus;
voidAfterMinutes: number;
autoPayment: boolean;
autoPaymentPauseReason: string | null;
notes: string | null;
createdAt: string;

@@ -429,3 +493,6 @@ }

name: string;
logoUrl: string | null;
};
voidAfterMinutes: number;
notes: string | null;
autoPayment: boolean;

@@ -625,17 +692,24 @@ autoPaymentPauseReason: string | null;

}
/** Grant (positive) or claw back (negative) a credit balance. `delta` must be a non-zero whole number. */
/** Grant (positive) or claw back (negative) a credit balance. `delta` must be a
* non-zero whole number. The credit is addressed by its stable `agentKey`. */
interface CreditAdjustInput {
creditId: string;
/** The credit's stable agent key (the same key used to record usage). */
agentKey: string;
delta: number;
notes?: string;
}
/** Grant/claw an outcome balance. `delta` is a non-zero whole number; floored at 0. */
/** Grant/claw an outcome balance. `delta` is a non-zero whole number; floored at
* 0. The outcome is addressed by a STEP's `agentKey` (outcomes have no key of
* their own). */
interface OutcomeAdjustInput {
outcomeId: string;
/** An outcome step's stable agent key — identifies the parent outcome. */
agentKey: string;
delta: number;
notes?: string;
}
/** Grant/claw a unit balance. `delta` is non-zero (fractional allowed); floored at 0. */
/** Grant/claw a unit balance. `delta` is non-zero (fractional allowed); floored
* at 0. The unit is addressed by its stable `agentKey`. */
interface UnitAdjustInput {
unitId: string;
/** The unit's stable agent key (the same key used to record usage). */
agentKey: string;
delta: number;

@@ -654,2 +728,39 @@ notes?: string;

}
/** One point on a cost-over-time analytics series. */
interface CostPoint {
/** UTC day, `YYYY-MM-DD`. */
dateIso: string;
/** Short display label, e.g. "Jun 24". */
label: string;
/** Average cost that day, or `null` on days with no usage. */
cost: number | null;
reqs: number;
}
/** Summary stats across a cost-over-time series. */
interface CostStats {
activeDays: number;
avgCost: number | null;
peakCost: number | null;
troughCost: number | null;
deviationPct: number | null;
}
/** Cost-over-time analytics for a credit (`credits.get().analytics`). */
interface CreditAnalytics {
basePrice: number;
pricePerCredit: number;
marginPercent: number;
points: CostPoint[];
stats: CostStats;
}
/** Cost-over-time analytics for an outcome (`outcomes.get().analytics`).
* Each point adds `completions` (workflows finished that day). */
interface OutcomeAnalytics {
basePrice: number;
pricePerOutcome: number;
marginPercent: number;
points: (CostPoint & {
completions: number;
})[];
stats: CostStats;
}
interface Credit {

@@ -679,4 +790,3 @@ id: string;

};
/** Cost-over-time analytics; shape is server-defined. */
analytics: Record<string, unknown>;
analytics: CreditAnalytics;
}

@@ -730,3 +840,3 @@ interface CreateCreditInput {

};
analytics: Record<string, unknown>;
analytics: OutcomeAnalytics;
}

@@ -759,2 +869,5 @@ interface CreateOutcomeInput {

id: string;
/** Stable per-org report key — what `signals.unit({ agentKey })` sends.
* The ONLY identifier accepted when reporting unit consumption. */
agentKey: string;
name: string;

@@ -767,6 +880,19 @@ description: string | null;

createdAt: string;
createdByName: string | null;
}
/** `units.get()` — adds linked-customer sample plus stats. */
/** One row in a unit's linked-customer sample (`units.get().customers`). */
interface UnitCustomerRow {
customerId: string;
name: string;
legalName: string | null;
slug: string;
logoUrl: string | null;
granted: number;
used: number;
remaining: number;
currentlyMetered: boolean;
}
/** `units.get()` — adds linked-customer sample plus stats.
* `createdByName` is inherited from `Unit`. */
interface UnitDetail extends Unit {
createdByName: string | null;
stats: {

@@ -779,3 +905,3 @@ planCount: number;

/** First page (≤10) of customers currently metered on this unit. */
customers: Record<string, unknown>[];
customers: UnitCustomerRow[];
}

@@ -822,2 +948,18 @@ /** Flat per-event pricing — a single `flatPrice` (defaults to 0), no tiers. */

}
/** One serialized unit-consumption event — the result of `signals.unit()` and
* each element of `UnitUsageList.events`. */
interface SerializedUnitUsage {
id: string;
customerId: string;
/** Display name of the unit. */
unit: string;
/** The unit's stable agent key; `null` if the unit was deleted. */
agentKey: string | null;
billingMode: BillingMode;
/** Remaining ADVANCE allowance after this event; `null` for ARREAR. */
remaining: number | null;
customerCost: number;
member: string | null;
createdAt: string;
}
interface UnitUsageRow {

@@ -838,3 +980,3 @@ unit: string;

units: UnitUsageRow[];
events: unknown[];
events: SerializedUnitUsage[];
}

@@ -981,8 +1123,8 @@ type ThresholdKind = "CREDIT" | "OUTCOME" | "WALLET";

}): Promise<Credit[]>;
/** Create a credit type. `POST /api/v1/credits`. */
create(input: CreateCreditInput): Promise<void>;
/** Create a credit type; returns the created credit. `POST /api/v1/credits`. */
create(input: CreateCreditInput): Promise<Credit>;
/** Fetch one credit type with usage stats. `GET /api/v1/credits/:id`. */
get(id: string): Promise<CreditDetail>;
/** Update a credit type's definition. `PATCH /api/v1/credits/:id`. */
update(id: string, input: UpdateCreditInput): Promise<void>;
/** Update a credit type's definition; returns the updated credit. `PATCH /api/v1/credits/:id`. */
update(id: string, input: UpdateCreditInput): Promise<Credit>;
/** Activate or deactivate a credit type. */

@@ -996,5 +1138,5 @@ setActive(id: string, isActive: boolean): Promise<Credit>;

* The `customers` resource — full CRUD over the org's customers plus the
* read-only insight endpoints (usage / balances / plan / revenue). Every call
* is scoped to the API key's organisation server-side; a customer in another
* org resolves as a NotFoundError.
* read-only insight endpoints (usage / balances / plan). Every call is scoped
* to the API key's organisation server-side; a customer in another org
* resolves as a NotFoundError.
*/

@@ -1026,3 +1168,3 @@ declare class Customers {

delete(id: string): Promise<void>;
/** A customer's usage history. `GET /api/v1/customers/:id/usage`. */
/** A customer's usage history. `GET /api/v1/usage?customerId=`. */
usage(id: string, params?: {

@@ -1033,8 +1175,29 @@ limit?: number;

balances(id: string): Promise<CustomerBalances>;
/**
* One credit balance for a customer, matched by `creditId` or `creditName`;
* `null` when the customer has no plan or no matching credit. Convenience
* over `balances()` + `Array.find` — it fetches the FULL balances under the
* hood (there is no server-side scoped read), so prefer `balances()` when you
* need several rows from the same customer.
*/
creditBalance(customerId: string, match: {
creditId?: string;
creditName?: string;
}): Promise<CreditBalance | null>;
/** One outcome balance for a customer, matched by `outcomeId` or
* `outcomeName`; `null` when absent. See {@link creditBalance} for the
* fetch-then-filter caveat. */
outcomeBalance(customerId: string, match: {
outcomeId?: string;
outcomeName?: string;
}): Promise<OutcomeBalance | null>;
/** One unit balance for a customer, matched by `unitId` or `unitName`;
* `null` when absent. See {@link creditBalance} for the fetch-then-filter
* caveat. */
unitBalance(customerId: string, match: {
unitId?: string;
unitName?: string;
}): Promise<UnitBalance | null>;
/** The customer's current plan. `GET …/:id/plan`. */
plan(id: string): Promise<CustomerPlan>;
/** Revenue / cost / profit / margin over a window. `GET …/:id/revenue`. */
revenue(id: string, params?: {
range?: RevenueRange;
}): Promise<CustomerRevenue>;
/** List a customer's members. `GET …/:id/members`. */

@@ -1113,4 +1276,4 @@ listMembers(id: string): Promise<Member[]>;

update(id: string, input: UpdateOutcomeInput): Promise<Outcome>;
/** Activate or deactivate an outcome type. */
setActive(id: string, isActive: boolean): Promise<void>;
/** Activate or deactivate an outcome type; returns the updated outcome. */
setActive(id: string, isActive: boolean): Promise<Outcome>;
/** Delete an outcome type. */

@@ -1290,3 +1453,3 @@ delete(id: string): Promise<void>;

unit(input: UnitInput): Promise<{
unitUsage: Record<string, unknown>;
unitUsage: SerializedUnitUsage;
}>;

@@ -1458,2 +1621,2 @@ /** A customer's unit balances + recent unit events. `GET /api/v1/units`. */

export { type AddMemberInput, AllowanceError, type ApiCustomer, AuthError, type BillingCycle, type BillingMode, ClockNext, type ClockNextConfig, ClockNextError, type ComponentType, ConflictError, type CreateCreditInput, type CreateCustomerInput, type CreateOutcomeInput, type CreatePlanInput, type CreatePurchaseInput, type CreateUnitInput, type Credit, type CreditAdjustInput, type CreditComponentInput, type CreditDetail, type CreditInput, type CreditSignal, type CustomerBalances, type CustomerList, type CustomerPlan, type CustomerProfileInput, type CustomerRevenue, type DropReason, type FetchLike, type FlatComponentInput, type FlatUnitInput, type Invoice, type InvoiceDetail, type InvoiceLineItem, type InvoiceListRow, type InvoiceParty, type InvoicePlanSnapshot, type InvoiceStatus, type Logger, type Member, type MemberRole, type Model, type ModelBundleEntry, NetworkError, NotFoundError, type Outcome, type OutcomeAdjustInput, type OutcomeComponentInput, type OutcomeDetail, type OutcomeInput, type OutcomeSignal, type OutcomeStepInput, type PayLink, type PaymentDetail, type PaymentRow, type Plan, type PlanComponent, type PlanComponentInput, type PlanDetail, PlanError, type PlanKind, type PlanRef, type PlanType, type PortalToken, type PortalTokenInput, type Purchase, type PurchaseDetail, type PurchaseStatus, RateLimitError, type RevenueRange, type SerializedOutcomeAttribution, type SerializedRuleApplication, type SerializedUsageLog, ServerError, type Signal, type SignalStatus, type SignalType, type ThresholdKind, type TieredUnitInput, type Tokens, type TrackResult, type Unit, type UnitAdjustInput, type UnitComponentInput, type UnitDetail, type UnitInput, type UnitPricingType, type UnitTier, type UnitTierInput, type UnitUsageList, type UnitUsageRow, type UpdateCreditInput, type UpdateMemberInput, type UpdateOutcomeInput, type UpdatePlanInput, type UpdateUnitInput, type UpsertWebhookInput, type UsageList, ValidationError, type WalletComponentInput, type WalletEntryInput, type WalletInput, type WalletList, type WalletSignal, type WalletTransaction, type WalletTransactionType, type Webhook, type WorkspaceIdentity, signalToWire };
export { type AddMemberInput, AllowanceError, type ApiCustomer, AuthError, type BillingCycle, type BillingMode, ClockNext, type ClockNextConfig, ClockNextError, type ComponentType, ConflictError, type CostPoint, type CostStats, type CreateCreditInput, type CreateCustomerInput, type CreateOutcomeInput, type CreatePlanInput, type CreatePurchaseInput, type CreateUnitInput, type Credit, type CreditAdjustInput, type CreditAnalytics, type CreditBalance, type CreditComponentInput, type CreditDetail, type CreditInput, type CreditSignal, type CustomerBalances, type CustomerList, type CustomerPlan, type CustomerPlanDetails, type CustomerProfileInput, type DropReason, type FetchLike, type FlatComponentInput, type FlatUnitInput, type Invoice, type InvoiceDetail, type InvoiceLineItem, type InvoiceListRow, type InvoiceParty, type InvoicePlanSnapshot, type InvoiceStatus, type Logger, type Member, type MemberRole, type Model, type ModelBundleEntry, NetworkError, NotFoundError, type Outcome, type OutcomeAdjustInput, type OutcomeAnalytics, type OutcomeBalance, type OutcomeComponentInput, type OutcomeDetail, type OutcomeInput, type OutcomeSignal, type OutcomeStepInput, type PayLink, type PaymentDetail, type PaymentRow, type Plan, type PlanComponent, type PlanComponentInput, type PlanDetail, PlanError, type PlanKind, type PlanRef, type PlanType, type PortalToken, type PortalTokenInput, type Purchase, type PurchaseDetail, type PurchaseStatus, RateLimitError, type SerializedOutcomeAttribution, type SerializedRuleApplication, type SerializedUnitUsage, type SerializedUsageLog, ServerError, type Signal, type SignalStatus, type SignalType, type ThresholdKind, type TieredUnitInput, type Tokens, type TrackResult, type Unit, type UnitAdjustInput, type UnitBalance, type UnitComponentInput, type UnitCustomerRow, type UnitDetail, type UnitInput, type UnitPricingType, type UnitTier, type UnitTierInput, type UnitUsageList, type UnitUsageRow, type UpdateCreditInput, type UpdateMemberInput, type UpdateOutcomeInput, type UpdatePlanInput, type UpdateUnitInput, type UpsertWebhookInput, type UsageBalance, type UsageList, ValidationError, type WalletComponentInput, type WalletEntryInput, type WalletInput, type WalletList, type WalletSignal, type WalletTransaction, type WalletTransactionType, type Webhook, type WorkspaceIdentity, signalToWire };

@@ -230,3 +230,3 @@ // src/config.ts

// src/http.ts
var SDK_VERSION = "0.4.0" ;
var SDK_VERSION = "0.5.0" ;
var Transport = class {

@@ -341,5 +341,5 @@ constructor(cfg) {

}
/** Create a credit type. `POST /api/v1/credits`. */
/** Create a credit type; returns the created credit. `POST /api/v1/credits`. */
async create(input) {
await this.transport.request({
const res = await this.transport.request({
method: "POST",

@@ -349,2 +349,3 @@ path: "/api/v1/credits",

});
return res.credit;
}

@@ -359,5 +360,5 @@ /** Fetch one credit type with usage stats. `GET /api/v1/credits/:id`. */

}
/** Update a credit type's definition. `PATCH /api/v1/credits/:id`. */
/** Update a credit type's definition; returns the updated credit. `PATCH /api/v1/credits/:id`. */
async update(id, input) {
await this.transport.request({
const res = await this.transport.request({
method: "PATCH",

@@ -367,2 +368,3 @@ path: `/api/v1/credits/${encodeURIComponent(id)}`,

});
return res.credit;
}

@@ -447,8 +449,8 @@ /** Activate or deactivate a credit type. */

}
/** A customer's usage history. `GET /api/v1/customers/:id/usage`. */
/** A customer's usage history. `GET /api/v1/usage?customerId=`. */
async usage(id, params = {}) {
const res = await this.transport.request({
method: "GET",
path: `/api/v1/customers/${encodeURIComponent(id)}/usage`,
query: { limit: params.limit }
path: `/api/v1/usage`,
query: { customerId: id, limit: params.limit }
});

@@ -464,2 +466,33 @@ return { customer: res.customer, totals: res.totals, logs: res.logs };

}
/**
* One credit balance for a customer, matched by `creditId` or `creditName`;
* `null` when the customer has no plan or no matching credit. Convenience
* over `balances()` + `Array.find` — it fetches the FULL balances under the
* hood (there is no server-side scoped read), so prefer `balances()` when you
* need several rows from the same customer.
*/
async creditBalance(customerId, match) {
const { credits } = await this.balances(customerId);
return credits.find(
(c) => match.creditId != null && c.creditId === match.creditId || match.creditName != null && c.creditName === match.creditName
) ?? null;
}
/** One outcome balance for a customer, matched by `outcomeId` or
* `outcomeName`; `null` when absent. See {@link creditBalance} for the
* fetch-then-filter caveat. */
async outcomeBalance(customerId, match) {
const { outcomes } = await this.balances(customerId);
return outcomes.find(
(o) => match.outcomeId != null && o.outcomeId === match.outcomeId || match.outcomeName != null && o.outcomeName === match.outcomeName
) ?? null;
}
/** One unit balance for a customer, matched by `unitId` or `unitName`;
* `null` when absent. See {@link creditBalance} for the fetch-then-filter
* caveat. */
async unitBalance(customerId, match) {
const { units } = await this.balances(customerId);
return units.find(
(u) => match.unitId != null && u.unitId === match.unitId || match.unitName != null && u.unitName === match.unitName
) ?? null;
}
/** The customer's current plan. `GET …/:id/plan`. */

@@ -472,10 +505,2 @@ plan(id) {

}
/** Revenue / cost / profit / margin over a window. `GET …/:id/revenue`. */
revenue(id, params = {}) {
return this.transport.request({
method: "GET",
path: `/api/v1/customers/${encodeURIComponent(id)}/revenue`,
query: { range: params.range }
});
}
// --- Members -------------------------------------------------------------

@@ -646,5 +671,5 @@ /** List a customer's members. `GET …/:id/members`. */

}
/** Activate or deactivate an outcome type. */
/** Activate or deactivate an outcome type; returns the updated outcome. */
async setActive(id, isActive) {
await this.transport.request({
const res = await this.transport.request({
method: "PATCH",

@@ -654,2 +679,3 @@ path: `/api/v1/outcomes/${encodeURIComponent(id)}`,

});
return res.outcome;
}

@@ -656,0 +682,0 @@ /** Delete an outcome type. */

{
"name": "@clocknext/sdk",
"version": "0.4.0",
"version": "0.5.0",
"description": "Official ClockNext SDK — record usage signals and manage plans, purchases, invoices, customers, and billing from your backend.",

@@ -12,5 +12,10 @@ "license": "MIT",

".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs"
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}

@@ -35,3 +40,4 @@ },

"test:watch": "vitest",
"prepublishOnly": "npm run build"
"lint:pkg": "publint --strict && attw --pack",
"prepublishOnly": "npm run build && npm run lint:pkg"
},

@@ -47,3 +53,5 @@ "keywords": [

"devDependencies": {
"@arethetypeswrong/cli": "^0.18.5",
"@types/node": "^20.14.0",
"publint": "^0.3.22",
"tsup": "^8.3.0",

@@ -50,0 +58,0 @@ "typescript": "^5.6.0",

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display