metergraph 0.5.0 → 0.6.2

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/dist/session.js CHANGED
@@ -1,5 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SessionManager = exports.MAX_BACKOFF_MS = exports.REFRESH_MARGIN_MS = exports.DEFAULT_TTL_MS = exports.DEFAULT_TIMEOUT_MS = void 0;
1
4
  /**
2
- * Repository-aware ingest protocol v2: app-token -> session-token exchange.
5
+ * SDK 0.4+ repository-aware ingestion: app-token -> session-token exchange.
3
6
  *
4
7
  * The app token is sent only on POST /v1/ingest/sessions. The resulting
5
8
  * session token is cached in memory and reused until it's within
@@ -10,30 +13,30 @@
10
13
  * mode is fail-open: getToken() resolves to undefined and callers drop that
11
14
  * batch rather than ever sending the app token to /v1/ingest.
12
15
  */
13
- import { FailureLogger } from "./failure-log.js";
14
- export const DEFAULT_TIMEOUT_MS = 3_000;
15
- export const DEFAULT_TTL_MS = 300_000;
16
- export const REFRESH_MARGIN_MS = 30_000;
17
- export const MAX_BACKOFF_MS = 60_000;
16
+ const failure_log_js_1 = require("./failure-log.js");
17
+ exports.DEFAULT_TIMEOUT_MS = 3_000;
18
+ exports.DEFAULT_TTL_MS = 300_000;
19
+ exports.REFRESH_MARGIN_MS = 30_000;
20
+ exports.MAX_BACKOFF_MS = 60_000;
18
21
  function parseExpiresAt(value) {
19
22
  if (typeof value !== "string")
20
23
  return undefined;
21
24
  const parsed = Date.parse(value);
22
25
  return Number.isNaN(parsed) ? undefined : parsed;
23
26
  }
24
- export class SessionManager {
27
+ class SessionManager {
25
28
  appToken;
26
29
  repository;
27
30
  sdkVersion;
28
31
  timeoutMs;
29
32
  url;
30
- failureLog = new FailureLogger();
33
+ failureLog = new failure_log_js_1.FailureLogger();
31
34
  token;
32
35
  expiresAt = 0;
33
36
  stopped = false;
34
37
  retryAt = 0;
35
38
  backoffMs = 1_000;
36
- constructor(appToken, baseUrl, repository, sdkVersion, timeoutMs = DEFAULT_TIMEOUT_MS) {
39
+ constructor(appToken, baseUrl, repository, sdkVersion, timeoutMs = exports.DEFAULT_TIMEOUT_MS) {
37
40
  this.appToken = appToken;
38
41
  this.repository = repository;
39
42
  this.sdkVersion = sdkVersion;
@@ -43,7 +46,7 @@ export class SessionManager {
43
46
  async getToken() {
44
47
  if (this.stopped)
45
48
  return undefined;
46
- if (this.token !== undefined && Date.now() < this.expiresAt - REFRESH_MARGIN_MS) {
49
+ if (this.token !== undefined && Date.now() < this.expiresAt - exports.REFRESH_MARGIN_MS) {
47
50
  return this.token;
48
51
  }
49
52
  if (Date.now() < this.retryAt)
@@ -89,7 +92,7 @@ export class SessionManager {
89
92
  this.markFailed();
90
93
  return;
91
94
  }
92
- const expiresAt = parseExpiresAt(doc?.expires_at) ?? Date.now() + DEFAULT_TTL_MS;
95
+ const expiresAt = parseExpiresAt(doc?.expires_at) ?? Date.now() + exports.DEFAULT_TTL_MS;
93
96
  if (!this.stopped) {
94
97
  this.token = token;
95
98
  this.expiresAt = expiresAt;
@@ -104,6 +107,7 @@ export class SessionManager {
104
107
  }
105
108
  markFailed() {
106
109
  this.retryAt = Date.now() + this.backoffMs;
107
- this.backoffMs = Math.min(this.backoffMs * 2, MAX_BACKOFF_MS);
110
+ this.backoffMs = Math.min(this.backoffMs * 2, exports.MAX_BACKOFF_MS);
108
111
  }
109
112
  }
113
+ exports.SessionManager = SessionManager;
package/dist/template.js CHANGED
@@ -1,3 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.scrub = scrub;
4
+ exports.templateHash = templateHash;
1
5
  const sensitive = new Set([
2
6
  "api-key",
3
7
  "api_key",
@@ -15,7 +19,7 @@ const sensitive = new Set([
15
19
  "token",
16
20
  "x-api-key",
17
21
  ]);
18
- export function scrub(value) {
22
+ function scrub(value) {
19
23
  if (Array.isArray(value))
20
24
  return value.map(scrub);
21
25
  if (value && typeof value === "object") {
@@ -52,6 +56,6 @@ function fnv1a(value) {
52
56
  }
53
57
  return hash.toString(16).padStart(16, "0");
54
58
  }
55
- export function templateHash(request) {
59
+ function templateHash(request) {
56
60
  return fnv1a(JSON.stringify(normalized(scrub(request))));
57
61
  }
package/dist/track.js CHANGED
@@ -1,11 +1,14 @@
1
- import { contextSnapshot, runWithContext } from "./context.js";
2
- export function track(nameOrFn, maybeFn) {
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.track = track;
4
+ const context_js_1 = require("./context.js");
5
+ function track(nameOrFn, maybeFn) {
3
6
  const fn = typeof nameOrFn === "string" ? maybeFn : nameOrFn;
4
7
  if (typeof fn !== "function")
5
8
  throw new TypeError("track requires a function");
6
9
  const funcName = typeof nameOrFn === "string" ? nameOrFn : fn.name || "<anonymous>";
7
10
  const wrapped = function (...args) {
8
- return runWithContext({ ...contextSnapshot(), funcName }, () => fn.apply(this, args));
11
+ return (0, context_js_1.runWithContext)({ ...(0, context_js_1.contextSnapshot)(), funcName }, () => fn.apply(this, args));
9
12
  };
10
13
  return wrapped;
11
14
  }
package/dist/transport.js CHANGED
@@ -1,5 +1,8 @@
1
- import { FailureLogger } from "./failure-log.js";
2
- export const MAX_BATCH_BYTES = 512 * 1024;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Transport = exports.MAX_BATCH_BYTES = void 0;
4
+ const failure_log_js_1 = require("./failure-log.js");
5
+ exports.MAX_BATCH_BYTES = 4 * 1024 * 1024;
3
6
  function detectedMode() {
4
7
  const env = typeof process === "undefined" ? {} : process.env;
5
8
  const agent = typeof navigator === "undefined" ? "" : navigator.userAgent;
@@ -13,7 +16,7 @@ async function gzipBody(body) {
13
16
  const source = new Blob([body]).stream();
14
17
  return new Response(source.pipeThrough(new CompressionStream("gzip"))).arrayBuffer();
15
18
  }
16
- export class Transport {
19
+ class Transport {
17
20
  token;
18
21
  baseUrl;
19
22
  queue = [];
@@ -29,7 +32,7 @@ export class Transport {
29
32
  errors = 0;
30
33
  retryAt = 0;
31
34
  backoffMs = 1_000;
32
- failureLog = new FailureLogger();
35
+ failureLog = new failure_log_js_1.FailureLogger();
33
36
  session;
34
37
  constructor(token, baseUrl, options = {}) {
35
38
  this.token = token;
@@ -114,7 +117,7 @@ export class Transport {
114
117
  const raw = encoded.buffer.slice(encoded.byteOffset, encoded.byteOffset + encoded.byteLength);
115
118
  const compressed = raw.byteLength > 32 * 1024;
116
119
  const body = compressed ? await gzipBody(raw) : raw;
117
- if (body.byteLength > MAX_BATCH_BYTES) {
120
+ if (body.byteLength > exports.MAX_BATCH_BYTES) {
118
121
  if (rows.length === 1) {
119
122
  this.dropped += 1;
120
123
  return;
@@ -175,3 +178,4 @@ export class Transport {
175
178
  await this.flush();
176
179
  }
177
180
  }
181
+ exports.Transport = Transport;
package/dist/vercel-ai.js CHANGED
@@ -1,5 +1,8 @@
1
- import { chunkText } from "./capture.js";
2
- import { getCaptureRuntime } from "./wrap.js";
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createVercelAISDKMiddleware = createVercelAISDKMiddleware;
4
+ const capture_js_1 = require("./capture.js");
5
+ const wrap_js_1 = require("./wrap.js");
3
6
  const GATEWAY_PROVIDERS = new Set(["gateway", "vercel", "vercel-ai-gateway"]);
4
7
  function canonicalProvider(provider, modelId) {
5
8
  const raw = String(provider ?? "unknown").trim().toLowerCase();
@@ -82,7 +85,7 @@ function wrapStreamResult(result, capture, state, started) {
82
85
  const observe = (part) => {
83
86
  if (firstOutputAt === undefined && outputChunk(part))
84
87
  firstOutputAt = performance.now();
85
- const delta = chunkText(part);
88
+ const delta = (0, capture_js_1.chunkText)(part);
86
89
  if (delta !== undefined)
87
90
  text += delta;
88
91
  if (["tool-call", "tool-result", "tool-error", "file", "source"].includes(part?.type)) {
@@ -146,7 +149,7 @@ function wrapStreamResult(result, capture, state, started) {
146
149
  });
147
150
  return { ...result, stream };
148
151
  }
149
- export function createVercelAISDKMiddleware(options = {}) {
152
+ function createVercelAISDKMiddleware(options = {}) {
150
153
  if (options.aiSdkVersion === 5 && options.specificationVersion !== undefined) {
151
154
  throw new TypeError("aiSdkVersion and specificationVersion cannot be combined");
152
155
  }
@@ -154,7 +157,7 @@ export function createVercelAISDKMiddleware(options = {}) {
154
157
  return {
155
158
  specificationVersion,
156
159
  async wrapGenerate({ doGenerate, params, model }) {
157
- const capture = getCaptureRuntime();
160
+ const capture = (0, wrap_js_1.getCaptureRuntime)();
158
161
  if (!capture)
159
162
  return await doGenerate();
160
163
  const state = startCapture(capture, "generate", params, model);
@@ -169,7 +172,7 @@ export function createVercelAISDKMiddleware(options = {}) {
169
172
  }
170
173
  },
171
174
  async wrapStream({ doStream, params, model }) {
172
- const capture = getCaptureRuntime();
175
+ const capture = (0, wrap_js_1.getCaptureRuntime)();
173
176
  if (!capture)
174
177
  return await doStream();
175
178
  const started = performance.now();
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "0.5.0";
1
+ export declare const SDK_VERSION = "0.6.2";
package/dist/version.js CHANGED
@@ -1 +1,4 @@
1
- export const SDK_VERSION = "0.5.0";
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SDK_VERSION = void 0;
4
+ exports.SDK_VERSION = "0.6.2";
package/dist/wrap.js CHANGED
@@ -1,5 +1,11 @@
1
- import { chunkText } from "./capture.js";
2
- import { contextSnapshot } from "./context.js";
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.wrapClient = exports.SEAM_TABLES = exports.GOOGLE_SEAMS = exports.ANTHROPIC_SEAMS = exports.OPENAI_SEAMS = void 0;
4
+ exports.setCaptureRuntime = setCaptureRuntime;
5
+ exports.getCaptureRuntime = getCaptureRuntime;
6
+ exports.wrap = wrap;
7
+ const capture_js_1 = require("./capture.js");
8
+ const context_js_1 = require("./context.js");
3
9
  let runtime;
4
10
  const seenBatchItems = new Set();
5
11
  // Tracks which resource *owners* (e.g. a specific chat.completions instance)
@@ -11,11 +17,11 @@ const seenBatchItems = new Set();
11
17
  // same synchronous window are never mistaken for one delegating into the
12
18
  // other.
13
19
  const reentrantOwners = new WeakSet();
14
- export function setCaptureRuntime(value) {
20
+ function setCaptureRuntime(value) {
15
21
  runtime = value;
16
22
  }
17
23
  /** @internal Used by optional framework adapters without adding runtime dependencies. */
18
- export function getCaptureRuntime() {
24
+ function getCaptureRuntime() {
19
25
  return runtime;
20
26
  }
21
27
  function requestFrom(args) {
@@ -163,7 +169,7 @@ function patchOpenAIBatchContent(owner, method) {
163
169
  if (!capture)
164
170
  return original.apply(owner, args);
165
171
  const sourceId = String(args[0] ?? "unknown");
166
- const context = contextSnapshot();
172
+ const context = (0, context_js_1.contextSnapshot)();
167
173
  const stack = new Error().stack;
168
174
  const result = original.apply(owner, args);
169
175
  if (result && typeof result.then === "function") {
@@ -186,7 +192,7 @@ function patchAnthropicBatchResults(owner) {
186
192
  if (!capture)
187
193
  return original.apply(owner, args);
188
194
  const batchId = String(args[0] ?? "unknown");
189
- const context = contextSnapshot();
195
+ const context = (0, context_js_1.contextSnapshot)();
190
196
  const stack = new Error().stack;
191
197
  const result = original.apply(owner, args);
192
198
  if (result && typeof result.then === "function") {
@@ -204,7 +210,7 @@ function streamProxy(stream, state, capture) {
204
210
  const parts = [];
205
211
  const chunks = [];
206
212
  const hasOutput = (chunk) => {
207
- if (chunkText(chunk))
213
+ if ((0, capture_js_1.chunkText)(chunk))
208
214
  return true;
209
215
  const value = chunk;
210
216
  if (Array.isArray(value?.choices)
@@ -228,7 +234,7 @@ function streamProxy(stream, state, capture) {
228
234
  const observe = (chunk) => {
229
235
  last = chunk;
230
236
  chunks.push(chunk);
231
- const text = chunkText(chunk);
237
+ const text = (0, capture_js_1.chunkText)(chunk);
232
238
  if (ttftMs === undefined && hasOutput(chunk)) {
233
239
  ttftMs = Math.round(performance.now() - state.started);
234
240
  }
@@ -382,7 +388,7 @@ function patch(owner, method, provider, endpoint) {
382
388
  owner[method] = wrapped;
383
389
  return true;
384
390
  }
385
- export const OPENAI_SEAMS = [
391
+ exports.OPENAI_SEAMS = [
386
392
  { path: "chat.completions", method: "create", endpoint: "chat.completions" },
387
393
  { path: "chat.completions", method: "parse", endpoint: "chat.completions.parse" },
388
394
  // beta.chat.completions.parse is v4.x-only — removed at the v4->v5
@@ -402,11 +408,11 @@ export const OPENAI_SEAMS = [
402
408
  // beta.chat.completions.parse above is exempted from that check since it
403
409
  // will correctly show as absent there — see the test for details.
404
410
  ];
405
- export const ANTHROPIC_SEAMS = [
411
+ exports.ANTHROPIC_SEAMS = [
406
412
  { path: "messages", method: "create", endpoint: "messages" },
407
413
  { path: "messages", method: "stream", endpoint: "messages.stream" },
408
414
  ];
409
- export const GOOGLE_SEAMS = [
415
+ exports.GOOGLE_SEAMS = [
410
416
  { path: "models", method: "generateContent", endpoint: "models.generate_content" },
411
417
  { path: "models", method: "generateContentStream", endpoint: "models.generate_content.stream" },
412
418
  // Note: unlike the Python google-genai client, the JS/TS @google/genai
@@ -414,10 +420,10 @@ export const GOOGLE_SEAMS = [
414
420
  // installed package — client.aio is undefined; JS methods are already
415
421
  // Promise-based) — do not add aio.models entries here.
416
422
  ];
417
- export const SEAM_TABLES = {
418
- openai: OPENAI_SEAMS,
419
- anthropic: ANTHROPIC_SEAMS,
420
- google: GOOGLE_SEAMS,
423
+ exports.SEAM_TABLES = {
424
+ openai: exports.OPENAI_SEAMS,
425
+ anthropic: exports.ANTHROPIC_SEAMS,
426
+ google: exports.GOOGLE_SEAMS,
421
427
  };
422
428
  function detectProvider(client) {
423
429
  if (client.models?.generateContent)
@@ -437,7 +443,7 @@ function resolveSeam(client, path) {
437
443
  }
438
444
  function applySeams(client, provider) {
439
445
  const patched = [];
440
- for (const seam of SEAM_TABLES[provider] ?? []) {
446
+ for (const seam of exports.SEAM_TABLES[provider] ?? []) {
441
447
  let owner;
442
448
  try {
443
449
  owner = resolveSeam(client, seam.path);
@@ -463,7 +469,7 @@ function applyBatchExtras(client, provider) {
463
469
  }
464
470
  return patched;
465
471
  }
466
- export function wrap(client, provider) {
472
+ function wrap(client, provider) {
467
473
  try {
468
474
  const name = provider ?? detectProvider(client);
469
475
  const patched = applySeams(client, name);
@@ -480,4 +486,4 @@ export function wrap(client, provider) {
480
486
  }
481
487
  return client;
482
488
  }
483
- export const wrapClient = wrap;
489
+ exports.wrapClient = wrap;
package/package.json CHANGED
@@ -1,21 +1,27 @@
1
1
  {
2
2
  "name": "metergraph",
3
- "version": "0.5.0",
3
+ "version": "0.6.2",
4
4
  "description": "Fire-and-forget LLM spend capture for Metergraph",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
+ "module": "./dist/index.mjs",
7
8
  "types": "./dist/index.d.ts",
8
9
  "exports": {
9
10
  ".": {
10
11
  "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js"
12
+ "import": "./dist/index.mjs",
13
+ "require": "./dist/index.js",
14
+ "default": "./dist/index.mjs"
12
15
  }
13
16
  },
14
17
  "files": ["dist", "README.md"],
15
18
  "scripts": {
16
- "build": "tsc -p tsconfig.json",
19
+ "build": "node scripts/prepare-build.mjs && tsc -p tsconfig.json && node scripts/finish-build.mjs",
17
20
  "prepack": "npm run build",
18
- "test": "npm run build && npm run test:types && node --test test/*.test.mjs",
21
+ "prepublishOnly": "npm test && npm run test:package",
22
+ "test": "npm run build && npm run test:types && npm run test:examples && node --test test/*.test.mjs",
23
+ "test:examples": "tsc --noEmit --strict --skipLibCheck --target ES2022 --module NodeNext --moduleResolution NodeNext test/ai-sdk-factories.types.ts",
24
+ "test:package": "npm run build && node --test test/package/packed-package.test.mjs",
19
25
  "test:types": "tsc --noEmit --strict --skipLibCheck --target ES2022 --module NodeNext --moduleResolution NodeNext test/ai-sdk-current.types.ts"
20
26
  },
21
27
  "engines": {
@@ -35,12 +41,15 @@
35
41
  "keywords": ["llm", "observability", "openai", "anthropic", "gemini", "vercel-ai-sdk", "cost-tracking"],
36
42
  "dependencies": {},
37
43
  "devDependencies": {
38
- "ai": "^7.0.55",
44
+ "@ai-sdk/anthropic": "^4.0.39",
45
+ "@ai-sdk/openai": "^4.0.43",
46
+ "@ai-sdk/openai-compatible": "^3.0.31",
47
+ "@anthropic-ai/sdk": "^0.30",
48
+ "@google/genai": "^1",
39
49
  "@types/node": "^24.0.0",
40
- "typescript": "^5.8.0",
50
+ "ai": "^7.0.55",
41
51
  "openai": "^7",
42
- "@anthropic-ai/sdk": "^0.30",
43
- "@google/genai": "^1"
52
+ "typescript": "^5.8.0"
44
53
  },
45
54
  "peerDependencies": {
46
55
  "@anthropic-ai/sdk": ">=0.30",