@spondo/margin 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,77 @@
1
- # Temporary Holding Version
1
+ # @spondo/margin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Node client for [Spondo Margin](https://margin.getspondo.com). Use it to send usage events, see what each customer's AI calls cost you, and manage customers and products. What they paid comes from your Stripe, which you connect in the dashboard.
4
+
5
+ ```bash
6
+ npm install @spondo/margin
7
+ ```
8
+
9
+ It runs anywhere `fetch` does: Node 20 or later, Bun, Deno and edge runtimes. Tracing needs Node.
10
+
11
+ ## Events
12
+
13
+ An event is one thing your product did for a customer. It gets a cost (the traces under it), and its event name and the numbers in its `data` are what value rules count.
14
+
15
+ ```ts
16
+ import { Spondo } from "@spondo/margin";
17
+
18
+ const spondo = new Spondo(); // reads SPONDO_API_KEY
19
+
20
+ await spondo.events.send({
21
+ eventName: "document_uploaded",
22
+ customer: { externalCustomerId: account.id },
23
+ attribution: { externalProductId: "documind" },
24
+ data: { pages: doc.pages },
25
+ idempotencyKey: doc.id, // a retry with the same key is stored once
26
+ });
27
+ ```
28
+
29
+ `send` takes one event or an array of them.
30
+
31
+ ## Cost tracing
32
+
33
+ Tracing puts the cost of each customer's AI calls on them. It also gives you a cost for each event.
34
+
35
+ Install the OpenTelemetry packages it uses (the 3.x line):
36
+
37
+ ```bash
38
+ npm install @opentelemetry/api @opentelemetry/sdk-trace @opentelemetry/context-async-hooks @opentelemetry/exporter-trace-otlp-http
39
+ ```
40
+
41
+ Then wrap each unit of work in `trace()`:
42
+
43
+ ```ts
44
+ import { initTracing, trace, event } from "@spondo/margin/tracing";
45
+
46
+ initTracing(); // once, at startup
47
+
48
+ await trace({ externalCustomerId: account.id, externalProductId: "documind" }, async () => {
49
+ const summary = await anthropic.messages.create({ ... }); // priced from its tokens
50
+ await event("document_uploaded", { pages: doc.pages }); // carries this trace's cost
51
+ });
52
+ ```
53
+
54
+ LLM calls are priced from the `gen_ai.*` token counts on their spans. Register an OpenTelemetry instrumentation for your LLM client as you normally would: OpenLLMetry, OpenInference, and the Vercel AI SDK's `@ai-sdk/otel` all set those attributes. A span with no token counts can give its own cost in US dollars as `meter.cost`. In serverless functions, `await flush()` before returning.
55
+
56
+ ## The rest of the API
57
+
58
+ ```ts
59
+ // stripeCustomerId: their customer in your Stripe, so their payments count as their revenue
60
+ const customer = await spondo.customers.create({ name: "Acme", externalId: "acme", stripeCustomerId: "cus_…" });
61
+ await spondo.customers.get({ externalId: "acme" }); // or by Spondo Margin's id: "cus_…"
62
+ ```
63
+
64
+ The client also covers:
65
+ - `customers`, `products` and `events`
66
+ - any other `/api/v1` call, through `spondo.request(method, path, { query, body, headers })`; `headers` adds to the client's own
67
+
68
+ A failed call throws a `SpondoError`, which carries `status`, `code` and `message`. A rate-limited call (429) is retried twice, after the wait the server asks for.
69
+
70
+ ## Options
71
+
72
+ | Option | Default |
73
+ |---|---|
74
+ | `apiKey` | `SPONDO_API_KEY` |
75
+ | `baseUrl` | `SPONDO_BASE_URL`, then `https://margin.getspondo.com` |
76
+ | `maxRetries` | `2` |
77
+ | `fetch` | `globalThis.fetch` |
@@ -0,0 +1,156 @@
1
+ export declare const DEFAULT_BASE_URL = "https://margin.getspondo.com";
2
+ export type Json = Record<string, unknown>;
3
+ export type Query = Record<string, string | number | boolean | null | undefined>;
4
+ /** A record by its Spondo Margin id (`cus_…`, `prod_…`), or by your own id for it. */
5
+ export type Ref = string | {
6
+ externalId: string;
7
+ };
8
+ export type ListQuery = {
9
+ limit?: number;
10
+ offset?: number;
11
+ };
12
+ export type Page<T> = {
13
+ data: T[];
14
+ pagination: {
15
+ limit: number;
16
+ offset: number;
17
+ total: number;
18
+ hasMore: boolean;
19
+ };
20
+ };
21
+ /** A record this client doesn't type in full yet: its id, and the rest as JSON. */
22
+ export type Resource = {
23
+ id: string;
24
+ } & Json;
25
+ export type ClientOptions = {
26
+ /** A key from Developers → API keys. Default: the SPONDO_API_KEY environment variable. */
27
+ apiKey?: string;
28
+ /** Default: SPONDO_BASE_URL, else https://margin.getspondo.com. */
29
+ baseUrl?: string;
30
+ /** How many times a rate-limited call (429) is retried, after the wait the server asks for. Default 2. */
31
+ maxRetries?: number;
32
+ fetch?: typeof fetch;
33
+ };
34
+ export type CustomerRef = {
35
+ customerId: string;
36
+ } | {
37
+ externalCustomerId: string;
38
+ };
39
+ export type EventInput = {
40
+ /** What happened, e.g. `document_uploaded`. Cost per outcome and value are worked out by it. */
41
+ eventName: string;
42
+ customer: CustomerRef;
43
+ attribution?: {
44
+ productId: string;
45
+ } | {
46
+ externalProductId: string;
47
+ };
48
+ /** Anything to keep with the event; value rules can count its numbers. `trace_id` links the cost traced under it. */
49
+ data?: Json;
50
+ /** ISO 8601; default now. */
51
+ timestamp?: string;
52
+ /** An event sent twice with the same key is stored once. */
53
+ idempotencyKey?: string;
54
+ };
55
+ export type EventsResult = {
56
+ ingested: number;
57
+ duplicates: number;
58
+ failed: number;
59
+ };
60
+ export type EventRecord = {
61
+ id: string;
62
+ name: string;
63
+ customerId: string | null;
64
+ externalCustomerId: string | null;
65
+ productId: string | null;
66
+ externalProductId: string | null;
67
+ traceId: string | null;
68
+ data: Json | null;
69
+ createdAt: string;
70
+ };
71
+ export type CustomerInput = {
72
+ name: string;
73
+ externalId?: string;
74
+ email?: string;
75
+ phone?: string;
76
+ website?: string;
77
+ /** Their customer in your Stripe (`cus_…`), whose payments are their revenue. */
78
+ stripeCustomerId?: string | null;
79
+ metadata?: Json;
80
+ };
81
+ export type Customer = {
82
+ id: string;
83
+ name: string;
84
+ email: string;
85
+ phone: string;
86
+ website: string;
87
+ externalId: string | null;
88
+ stripeCustomerId: string | null;
89
+ status: "active" | "churned";
90
+ churnDate: string | null;
91
+ metadata: Json | null;
92
+ createdAt: string;
93
+ updatedAt: string | null;
94
+ };
95
+ export declare class SpondoError extends Error {
96
+ readonly status: number;
97
+ readonly code: string;
98
+ /** Seconds to wait before trying again, on a 429. */
99
+ readonly retryAfter: number | null;
100
+ constructor(status: number, code: string, message: string, retryAfter?: number | null);
101
+ }
102
+ export declare class Spondo {
103
+ #private;
104
+ readonly apiKey: string;
105
+ readonly baseUrl: string;
106
+ constructor(o?: ClientOptions);
107
+ /** Any /api/v1 call: `path` without the prefix, e.g. `/customers/cus_123/aliases`. `headers` can't replace the client's own. */
108
+ request<T = Json>(method: string, path: string, { query, body, headers }?: {
109
+ query?: Query;
110
+ body?: unknown;
111
+ headers?: Record<string, string>;
112
+ }): Promise<T>;
113
+ readonly events: {
114
+ /** One event or a batch. Retrying with the same idempotency keys is safe. */
115
+ send: (events: EventInput | EventInput[]) => Promise<EventsResult>;
116
+ list: (q?: ListQuery & {
117
+ customerId?: string;
118
+ externalCustomerId?: string;
119
+ productId?: string;
120
+ externalProductId?: string;
121
+ eventName?: string;
122
+ createdAtFrom?: string;
123
+ createdAtTo?: string;
124
+ }) => Promise<Page<EventRecord>>;
125
+ get: (id: string) => Promise<EventRecord>;
126
+ };
127
+ readonly customers: {
128
+ create: (body: CustomerInput) => Promise<Customer>;
129
+ list: (q?: ListQuery) => Promise<Page<Customer>>;
130
+ get: (ref: Ref) => Promise<Customer>;
131
+ /** `churnDate`: when they left (ISO 8601), or null if they're back. */
132
+ update: (ref: Ref, body: Partial<CustomerInput> & {
133
+ churnDate?: string | null;
134
+ }) => Promise<Customer>;
135
+ delete: (ref: Ref) => Promise<void>;
136
+ };
137
+ readonly products: {
138
+ /** `externalId`: your id for it, which events and traces name. `stripeProductId`: its product in your Stripe (`prod_…`). */
139
+ create: (body: {
140
+ name: string;
141
+ externalId?: string;
142
+ description?: string;
143
+ stripeProductId?: string;
144
+ } & Json) => Promise<Resource>;
145
+ list: (q?: ListQuery & {
146
+ name?: string;
147
+ }) => Promise<Page<Resource>>;
148
+ get: (ref: Ref) => Promise<Resource>;
149
+ update: (ref: Ref, body: {
150
+ name?: string;
151
+ externalId?: string | null;
152
+ description?: string | null;
153
+ stripeProductId?: string | null;
154
+ } & Json) => Promise<Resource>;
155
+ };
156
+ }
package/dist/index.js ADDED
@@ -0,0 +1,86 @@
1
+ // @spondo/margin: the client for Spondo Margin's API. A method for each call most apps make, and request() for the
2
+ // rest of /api/v1. Runs wherever fetch does (Node 20+, Bun, Deno, edge runtimes). Cost tracing: @spondo/margin/tracing.
3
+ export const DEFAULT_BASE_URL = "https://margin.getspondo.com";
4
+ export class SpondoError extends Error {
5
+ status;
6
+ code;
7
+ /** Seconds to wait before trying again, on a 429. */
8
+ retryAfter;
9
+ constructor(status, code, message, retryAfter = null) {
10
+ super(message);
11
+ this.name = "SpondoError";
12
+ this.status = status;
13
+ this.code = code;
14
+ this.retryAfter = retryAfter;
15
+ }
16
+ }
17
+ const env = (k) => globalThis.process?.env?.[k];
18
+ const at = (ref) => (typeof ref === "string" ? encodeURIComponent(ref) : `external/${encodeURIComponent(ref.externalId)}`);
19
+ export class Spondo {
20
+ apiKey;
21
+ baseUrl;
22
+ #retries;
23
+ #fetch;
24
+ constructor(o = {}) {
25
+ const key = o.apiKey ?? env("SPONDO_API_KEY");
26
+ if (!key)
27
+ throw new Error("Spondo: pass { apiKey } or set SPONDO_API_KEY");
28
+ this.apiKey = key;
29
+ this.baseUrl = (o.baseUrl ?? env("SPONDO_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/u, "");
30
+ this.#retries = o.maxRetries ?? 2;
31
+ this.#fetch = o.fetch ?? globalThis.fetch;
32
+ }
33
+ /** Any /api/v1 call: `path` without the prefix, e.g. `/customers/cus_123/aliases`. `headers` can't replace the client's own. */
34
+ async request(method, path, { query, body, headers } = {}) {
35
+ const url = new URL(`${this.baseUrl}/api/v1${path}`);
36
+ for (const [k, v] of Object.entries(query ?? {}))
37
+ if (v != null)
38
+ url.searchParams.set(k, String(v));
39
+ const h = new Headers(headers);
40
+ h.set("authorization", `Bearer ${this.apiKey}`);
41
+ if (body !== undefined)
42
+ h.set("content-type", "application/json");
43
+ for (let attempt = 0;; attempt++) {
44
+ const res = await this.#fetch(url, {
45
+ method,
46
+ headers: h,
47
+ body: body === undefined ? undefined : JSON.stringify(body),
48
+ });
49
+ const text = await res.text();
50
+ if (res.ok)
51
+ return (text ? JSON.parse(text) : undefined);
52
+ const wait = res.status === 429 ? Number(res.headers.get("retry-after") ?? 1) || 0 : null;
53
+ if (wait !== null && attempt < this.#retries) {
54
+ await new Promise((ok) => setTimeout(ok, wait * 1000));
55
+ continue;
56
+ }
57
+ let e = {};
58
+ try {
59
+ e = JSON.parse(text);
60
+ }
61
+ catch { }
62
+ throw new SpondoError(res.status, e.code ?? "HTTP_ERROR", e.details ?? e.error ?? (text || res.statusText), wait);
63
+ }
64
+ }
65
+ events = {
66
+ /** One event or a batch. Retrying with the same idempotency keys is safe. */
67
+ send: (events) => this.request("POST", "/events/bulk", { body: { events: Array.isArray(events) ? events : [events] } }),
68
+ list: (q = {}) => this.request("GET", "/events", { query: q }),
69
+ get: (id) => this.request("GET", `/events/${encodeURIComponent(id)}`),
70
+ };
71
+ customers = {
72
+ create: (body) => this.request("POST", "/customers", { body }),
73
+ list: (q = {}) => this.request("GET", "/customers", { query: q }),
74
+ get: (ref) => this.request("GET", `/customers/${at(ref)}`),
75
+ /** `churnDate`: when they left (ISO 8601), or null if they're back. */
76
+ update: (ref, body) => this.request("PUT", `/customers/${at(ref)}`, { body }),
77
+ delete: (ref) => this.request("DELETE", `/customers/${at(ref)}`),
78
+ };
79
+ products = {
80
+ /** `externalId`: your id for it, which events and traces name. `stripeProductId`: its product in your Stripe (`prod_…`). */
81
+ create: (body) => this.request("POST", "/products", { body }),
82
+ list: (q = {}) => this.request("GET", "/products", { query: q }),
83
+ get: (ref) => this.request("GET", `/products/${at(ref)}`),
84
+ update: (ref, body) => this.request("PUT", `/products/${at(ref)}`, { body }),
85
+ };
86
+ }
@@ -0,0 +1,20 @@
1
+ import { TracerProvider } from "@opentelemetry/sdk-trace";
2
+ import type { ClientOptions, EventsResult, Json } from "./index.ts";
3
+ export type TraceTags = {
4
+ externalCustomerId: string;
5
+ externalProductId?: string;
6
+ };
7
+ /**
8
+ * Start sending spans; call once at startup. Takes the client's options (apiKey, baseUrl). It registers the global
9
+ * tracer provider and, unless the app already has one, Node's async context manager, which keeps trace()'s customer
10
+ * across awaits.
11
+ */
12
+ export declare function initTracing(options?: ClientOptions): TracerProvider;
13
+ /** Run `fn` as one unit of work for a customer: the AI calls in it are costed to them. */
14
+ export declare function trace<T>(tags: TraceTags, fn: () => T | Promise<T>): Promise<T>;
15
+ /** Inside trace(): an event for its customer and product that carries the trace's cost. */
16
+ export declare function event(eventName: string, data?: Json, options?: {
17
+ idempotencyKey?: string;
18
+ }): Promise<EventsResult>;
19
+ /** Send the spans waiting in the batch now: before a serverless function returns, or the process exits. */
20
+ export declare const flush: () => Promise<void>;
@@ -0,0 +1,69 @@
1
+ // @spondo/margin/tracing: what each customer's AI calls cost you. Spans go to Spondo Margin's OpenTelemetry collector
2
+ // (<baseUrl>/v1/traces). Every span started inside trace() carries its customer and product, and an event() sent inside
3
+ // it carries that trace's cost, so you see cost per event. LLM calls are priced from their gen_ai.* token counts, so
4
+ // register an OpenTelemetry instrumentation for your LLM client as usual (OpenLLMetry, OpenInference, or the Vercel AI
5
+ // SDK's telemetry); spans that state their own cost set `meter.cost` (USD).
6
+ import { SpanStatusCode, context, createContextKey, trace as otel } from "@opentelemetry/api";
7
+ import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
8
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
9
+ import { BatchSpanProcessor, TracerProvider } from "@opentelemetry/sdk-trace";
10
+ import { Spondo } from "./index.js";
11
+ const TAGS = createContextKey("@spondo/margin tags");
12
+ const tags = (ctx = context.active()) => ctx.getValue(TAGS);
13
+ /** Copies the enclosing trace()'s customer and product onto each span as it starts. */
14
+ const tagger = {
15
+ onStart(span, ctx) {
16
+ const t = tags(ctx);
17
+ if (t)
18
+ span.setAttributes({ "meter.customer_id": t.externalCustomerId, ...(t.externalProductId && { "meter.product_id": t.externalProductId }) });
19
+ },
20
+ onEnd() { },
21
+ forceFlush: async () => { },
22
+ shutdown: async () => { },
23
+ };
24
+ let provider;
25
+ let client;
26
+ /**
27
+ * Start sending spans; call once at startup. Takes the client's options (apiKey, baseUrl). It registers the global
28
+ * tracer provider and, unless the app already has one, Node's async context manager, which keeps trace()'s customer
29
+ * across awaits.
30
+ */
31
+ export function initTracing(options = {}) {
32
+ client = new Spondo(options);
33
+ const exporter = new OTLPTraceExporter({ url: `${client.baseUrl}/v1/traces`, headers: { authorization: `Bearer ${client.apiKey}` } });
34
+ provider = new TracerProvider({ spanProcessors: [tagger, new BatchSpanProcessor({ exporter })] });
35
+ context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable());
36
+ otel.setGlobalTracerProvider(provider);
37
+ return provider;
38
+ }
39
+ /** Run `fn` as one unit of work for a customer: the AI calls in it are costed to them. */
40
+ export function trace(tags, fn) {
41
+ return context.with(context.active().setValue(TAGS, tags), () => otel.getTracer("@spondo/margin").startActiveSpan("spondo.trace", async (span) => {
42
+ try {
43
+ return await fn();
44
+ }
45
+ catch (e) {
46
+ span.recordException(e);
47
+ span.setStatus({ code: SpanStatusCode.ERROR });
48
+ throw e;
49
+ }
50
+ finally {
51
+ span.end();
52
+ }
53
+ }));
54
+ }
55
+ /** Inside trace(): an event for its customer and product that carries the trace's cost. */
56
+ export function event(eventName, data = {}, options = {}) {
57
+ const t = tags();
58
+ if (!client || !t)
59
+ throw new Error("event() runs inside trace(), after initTracing()");
60
+ return client.events.send({
61
+ eventName,
62
+ customer: { externalCustomerId: t.externalCustomerId },
63
+ ...(t.externalProductId && { attribution: { externalProductId: t.externalProductId } }),
64
+ data: { ...data, trace_id: otel.getActiveSpan()?.spanContext().traceId },
65
+ idempotencyKey: options.idempotencyKey,
66
+ });
67
+ }
68
+ /** Send the spans waiting in the batch now: before a serverless function returns, or the process exits. */
69
+ export const flush = () => provider?.forceFlush() ?? Promise.resolve();
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@spondo/margin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.0",
4
+ "description": "The client for Spondo Margin: send usage events, trace what each customer's AI calls cost, and manage customers and products.",
5
+ "homepage": "https://margin.getspondo.com",
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "./tracing": {
14
+ "types": "./dist/tracing.d.ts",
15
+ "default": "./dist/tracing.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "scripts": {
25
+ "build": "tsc",
26
+ "prepublishOnly": "npm run build"
27
+ },
28
+ "peerDependencies": {
29
+ "@opentelemetry/api": "^1.10.0",
30
+ "@opentelemetry/context-async-hooks": "^3.0.0",
31
+ "@opentelemetry/exporter-trace-otlp-http": ">=0.300.0",
32
+ "@opentelemetry/sdk-trace": "^3.0.0"
33
+ },
34
+ "peerDependenciesMeta": {
35
+ "@opentelemetry/api": {
36
+ "optional": true
37
+ },
38
+ "@opentelemetry/context-async-hooks": {
39
+ "optional": true
40
+ },
41
+ "@opentelemetry/exporter-trace-otlp-http": {
42
+ "optional": true
43
+ },
44
+ "@opentelemetry/sdk-trace": {
45
+ "optional": true
46
+ }
47
+ },
48
+ "devDependencies": {
49
+ "@opentelemetry/api": "^1.10.0",
50
+ "@opentelemetry/context-async-hooks": "^3.1.0",
51
+ "@opentelemetry/exporter-trace-otlp-http": "^0.301.0",
52
+ "@opentelemetry/sdk-trace": "^3.1.0",
53
+ "@types/node": "^26.6.6",
54
+ "typescript": "^7.0.2"
55
+ }
56
+ }