@revenium/anthropic 1.0.3 → 1.0.4

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.
@@ -0,0 +1,322 @@
1
+ /**
2
+ * Revenium Anthropic Middleware - TypeScript-First Basic Usage Example
3
+ *
4
+ * This example demonstrates TypeScript-first patterns with all initialization methods:
5
+ * • Auto-initialization with module augmentation (TypeScript-native usageMetadata)
6
+ * • Explicit initialization with type-safe error handling
7
+ * • Manual configuration with full type control and validation
8
+ * • Interface validation using the `satisfies` operator
9
+ * • Comprehensive type safety throughout
10
+ *
11
+ * Features TypeScript patterns like:
12
+ * - Module augmentation for native usageMetadata support
13
+ * - Type-safe configuration with validation
14
+ * - Strongly typed metadata with satisfies operator
15
+ * - Generic functions with type constraints
16
+ * - Comprehensive error handling with typed responses
17
+ */
18
+
19
+ // Load environment variables from .env file
20
+ import "dotenv/config";
21
+
22
+ // Import for module augmentation - enables native usageMetadata support
23
+ import "@revenium/anthropic";
24
+ import Anthropic from "@anthropic-ai/sdk";
25
+
26
+ // Import types for full TypeScript support
27
+ import type {
28
+ UsageMetadata,
29
+ ReveniumConfig,
30
+ ConfigValidationResult,
31
+ MiddlewareStatus,
32
+ } from "@revenium/anthropic";
33
+
34
+ async function demonstrateBasicUsage() {
35
+ console.log("Revenium Anthropic Middleware - Basic Usage Examples\n");
36
+
37
+ // =============================================================================
38
+ // OPTION A: Auto-Initialization (Simplest - Recommended for Most Projects)
39
+ // =============================================================================
40
+ console.log("Option A: Auto-Initialization (Simplest)");
41
+ console.log(
42
+ "Just import the middleware - it auto-configures from environment variables\n"
43
+ );
44
+
45
+ // Simply import the middleware - auto-initialization happens automatically
46
+ await import("@revenium/anthropic");
47
+
48
+ const anthropic = new Anthropic();
49
+
50
+ try {
51
+ // Example 1: Basic request without metadata (still tracked automatically)
52
+ console.log("Example 1: Basic request without metadata...");
53
+ const basicResponse = await anthropic.messages.create({
54
+ model: "claude-sonnet-4-20250514",
55
+ max_tokens: 50,
56
+ messages: [
57
+ { role: "user", content: "What is the capital of France? Be concise." },
58
+ ],
59
+ // No metadata - still tracked automatically
60
+ });
61
+
62
+ console.log(
63
+ "Response:",
64
+ basicResponse.content[0].type === "text"
65
+ ? basicResponse.content[0].text
66
+ : "Non-text response"
67
+ );
68
+ console.log(
69
+ ` Tokens: ${basicResponse.usage?.input_tokens} input + ${basicResponse.usage?.output_tokens} output\n`
70
+ );
71
+
72
+ // Example 2: Request with rich metadata for enhanced tracking
73
+ console.log("Example 2: Request with rich metadata...");
74
+ const metadataResponse = await anthropic.messages.create({
75
+ model: "claude-sonnet-4-20250514",
76
+ max_tokens: 80,
77
+ messages: [
78
+ { role: "user", content: "Explain quantum computing in one sentence." },
79
+ ],
80
+ // Add rich metadata for enhanced analytics and billing
81
+ usageMetadata: {
82
+ subscriber: {
83
+ id: "user-456",
84
+ email: "user@demo-org.com",
85
+ credential: {
86
+ name: "demo-api-key",
87
+ value: "demo-key-123",
88
+ },
89
+ },
90
+ organizationId: "demo-org-123",
91
+ productId: "ai-assistant-v2",
92
+ taskType: "educational-query",
93
+ agent: "anthropic-basic-demo",
94
+ traceId: "session-" + Date.now(),
95
+ },
96
+ });
97
+
98
+ console.log(
99
+ "Response:",
100
+ metadataResponse.content[0].type === "text"
101
+ ? metadataResponse.content[0].text
102
+ : "Non-text response"
103
+ );
104
+ console.log(
105
+ ` Tokens: ${metadataResponse.usage?.input_tokens} input + ${metadataResponse.usage?.output_tokens} output\n`
106
+ );
107
+
108
+ // Wait a moment for async tracking to complete
109
+ console.log("Waiting for tracking to complete...");
110
+ await new Promise((resolve) => setTimeout(resolve, 2000));
111
+
112
+ console.log(
113
+ "✓ Auto-initialization: Both requests completed and tracking attempted\n"
114
+ );
115
+ } catch (error) {
116
+ console.error("Error: Auto-initialization failed:", error);
117
+ console.log("Falling back to explicit initialization...\n");
118
+
119
+ // =============================================================================
120
+ // OPTION B: Explicit Initialization (Better Error Control)
121
+ // =============================================================================
122
+ await demonstrateExplicitInitialization();
123
+ }
124
+ }
125
+
126
+ async function demonstrateExplicitInitialization() {
127
+ console.log("Option B: Explicit Initialization (Better Error Control)");
128
+ console.log(
129
+ "Call initialize() explicitly for clear error feedback and better control\n"
130
+ );
131
+
132
+ try {
133
+ // Import initialization functions
134
+ const { initialize, getStatus } = await import("@revenium/anthropic");
135
+
136
+ // Explicitly initialize with clear error feedback
137
+ initialize();
138
+ console.log("✓ Explicit initialization successful!");
139
+
140
+ // Check status after initialization
141
+ const status = getStatus();
142
+ console.log("Middleware status:", {
143
+ initialized: status.initialized,
144
+ patched: status.patched,
145
+ hasConfig: status.hasConfig,
146
+ });
147
+
148
+ // Now use Anthropic with guaranteed tracking
149
+ const anthropic = new Anthropic();
150
+ const response = await anthropic.messages.create({
151
+ model: "claude-sonnet-4-20250514",
152
+ max_tokens: 60,
153
+ messages: [
154
+ {
155
+ role: "user",
156
+ content: "What are the benefits of explicit initialization?",
157
+ },
158
+ ],
159
+ usageMetadata: {
160
+ subscriber: {
161
+ id: "explicit-user-789",
162
+ // email and credential are optional
163
+ },
164
+ organizationId: "explicit-demo",
165
+ taskType: "explicit-initialization-example",
166
+ },
167
+ });
168
+
169
+ console.log(
170
+ "Response:",
171
+ response.content[0].type === "text"
172
+ ? response.content[0].text
173
+ : "Non-text response"
174
+ );
175
+ console.log(
176
+ "✓ Explicit initialization: Request tracked with guaranteed configuration!\n"
177
+ );
178
+ } catch (error) {
179
+ console.error("Explicit initialization failed:", (error as Error).message);
180
+ console.log("Falling back to manual configuration...\n");
181
+
182
+ // =============================================================================
183
+ // OPTION C: Manual Configuration (Full Control)
184
+ // =============================================================================
185
+ await demonstrateManualConfiguration();
186
+ }
187
+ }
188
+
189
+ async function demonstrateManualConfiguration() {
190
+ console.log("Option C: Manual Configuration (Full Control)");
191
+
192
+ try {
193
+ // Import configuration function
194
+ const { configure, getConfig } = await import("@revenium/anthropic");
195
+
196
+ // Manual configuration with all options
197
+ configure({
198
+ // Required: Revenium API configuration
199
+ reveniumApiKey:
200
+ process.env.REVENIUM_METERING_API_KEY || "hak_your_api_key_here",
201
+ reveniumBaseUrl:
202
+ process.env.REVENIUM_METERING_BASE_URL ||
203
+ "https://api.revenium.io/meter",
204
+
205
+ // Optional: Anthropic API key (can also be set in Anthropic client)
206
+ anthropicApiKey: process.env.ANTHROPIC_API_KEY,
207
+
208
+ // Optional: Performance and reliability settings
209
+ apiTimeout: 8000, // 8 second timeout (default: 5000)
210
+ maxRetries: 5, // 5 retry attempts (default: 3)
211
+ failSilent: false, // Throw errors instead of silent failure (default: true)
212
+ });
213
+
214
+ console.log("Success: Manual configuration completed!");
215
+
216
+ // Verify configuration
217
+ const config = getConfig();
218
+ console.log("Configuration:", {
219
+ hasReveniumKey: !!config?.reveniumApiKey,
220
+ baseUrl: config?.reveniumBaseUrl,
221
+ timeout: config?.apiTimeout,
222
+ maxRetries: config?.maxRetries,
223
+ });
224
+
225
+ // Use Anthropic with custom configuration
226
+ const anthropic = new Anthropic({
227
+ apiKey: process.env.ANTHROPIC_API_KEY || "sk-ant-your_anthropic_key_here",
228
+ });
229
+
230
+ const response = await anthropic.messages.create({
231
+ model: "claude-sonnet-4-20250514",
232
+ max_tokens: 80,
233
+ messages: [
234
+ {
235
+ role: "user",
236
+ content:
237
+ "What are the advantages of manual configuration in enterprise software?",
238
+ },
239
+ ],
240
+ // Enterprise-grade metadata
241
+ usageMetadata: {
242
+ subscriber: {
243
+ id: "manual-config-user",
244
+ email: "enterprise@corp.com",
245
+ credential: {
246
+ name: "enterprise-api-key",
247
+ value: "ent-key-456",
248
+ },
249
+ },
250
+ organizationId: "enterprise-corp",
251
+ productId: "enterprise-ai-platform",
252
+ taskType: "manual-configuration-demo",
253
+ agent: "anthropic-enterprise-v1",
254
+ responseQualityScore: 0.98,
255
+ },
256
+ });
257
+
258
+ console.log(
259
+ "Response:",
260
+ response.content[0].type === "text"
261
+ ? response.content[0].text
262
+ : "Non-text response"
263
+ );
264
+ console.log(
265
+ "Success: Manual configuration - Request tracked with custom enterprise settings!\n"
266
+ );
267
+ } catch (error) {
268
+ console.error(
269
+ "Error: Manual configuration failed:",
270
+ (error as Error).message
271
+ );
272
+ throw error;
273
+ }
274
+ }
275
+
276
+ // Environment validation
277
+ function checkEnvironment() {
278
+ const required = ["REVENIUM_METERING_API_KEY", "ANTHROPIC_API_KEY"];
279
+ const missing = required.filter((key) => !process.env[key]);
280
+
281
+ if (missing.length > 0) {
282
+ console.error("Error: Missing required environment variables:");
283
+ missing.forEach((key) => console.error(` ${key}`));
284
+ console.error("\nSet them in a .env file in the project root:");
285
+ console.error(" REVENIUM_METERING_API_KEY=hak_your_api_key");
286
+ console.error(" ANTHROPIC_API_KEY=sk-ant-your_anthropic_key");
287
+ console.error("\nOptional (uses defaults if not set):");
288
+ console.error(
289
+ " REVENIUM_METERING_BASE_URL=https://api.revenium.io/meter"
290
+ );
291
+ console.error(" REVENIUM_DEBUG=true # For detailed logging");
292
+ process.exit(1);
293
+ }
294
+ }
295
+
296
+ // Run the example
297
+ if (require.main === module) {
298
+ checkEnvironment();
299
+
300
+ demonstrateBasicUsage()
301
+ .then(() => {
302
+ console.log("✓ Basic usage examples completed successfully!");
303
+ console.log("\nSummary of initialization methods:");
304
+ console.log(" • Auto-initialization: Simplest - just import and go");
305
+ console.log(
306
+ " • Explicit initialization: Better error control and debugging"
307
+ );
308
+ console.log(
309
+ " • Manual configuration: Full control for enterprise applications"
310
+ );
311
+ console.log(
312
+ "\n✓ All requests automatically tracked to Revenium with rich metadata support"
313
+ );
314
+ console.log(
315
+ "\nTo see detailed tracking logs, set REVENIUM_DEBUG=true in .env file"
316
+ );
317
+ })
318
+ .catch((error) => {
319
+ console.error("\nError: Basic usage examples failed:", error);
320
+ process.exit(1);
321
+ });
322
+ }
package/package.json CHANGED
@@ -1,82 +1,84 @@
1
- {
2
- "name": "@revenium/anthropic",
3
- "version": "1.0.3",
4
- "description": "Transparent TypeScript middleware for automatic Revenium usage tracking with Anthropic Claude AI",
5
- "main": "dist/cjs/index.js",
6
- "module": "dist/esm/index.js",
7
- "types": "dist/types/index.d.ts",
8
- "exports": {
9
- ".": {
10
- "import": {
11
- "types": "./dist/types/index.d.ts",
12
- "default": "./dist/esm/index.js"
13
- },
14
- "require": {
15
- "types": "./dist/types/index.d.ts",
16
- "default": "./dist/cjs/index.js"
17
- }
18
- }
19
- },
20
- "scripts": {
21
- "build": "npm run build:cjs && npm run build:esm && npm run build:types && npm run fix-esm",
22
- "build:cjs": "tsc -p tsconfig.json",
23
- "build:esm": "tsc -p tsconfig.esm.json",
24
- "build:types": "tsc -p tsconfig.types.json",
25
- "fix-esm": "node scripts/fix-esm-imports.js",
26
- "dev": "tsc --watch",
27
- "test": "npm run build && echo 'Build successful - no automated tests configured'",
28
- "example": "npm run build && tsx examples/basic-usage.ts",
29
- "example:basic": "npm run build && tsx examples/basic-usage.ts",
30
- "example:advanced": "npm run build && tsx examples/advanced-features.ts",
31
- "clean": "rimraf dist",
32
- "prepublishOnly": "npm run clean && npm run build"
33
- },
34
- "keywords": [
35
- "anthropic",
36
- "claude",
37
- "revenium",
38
- "middleware",
39
- "typescript",
40
- "nodejs",
41
- "usage-tracking",
42
- "metering",
43
- "ai"
44
- ],
45
- "author": "Revenium",
46
- "license": "MIT",
47
- "repository": {
48
- "type": "git",
49
- "url": "git+https://github.com/revenium/revenium-middleware-anthropic-node.git"
50
- },
51
- "homepage": "https://github.com/revenium/revenium-middleware-anthropic-node#readme",
52
- "bugs": {
53
- "url": "https://github.com/revenium/revenium-middleware-anthropic-node/issues"
54
- },
55
- "dependencies": {
56
- "node-fetch": "^3.3.2"
57
- },
58
- "peerDependencies": {
59
- "@anthropic-ai/sdk": ">=0.24.0"
60
- },
61
- "devDependencies": {
62
- "@anthropic-ai/sdk": "^0.55.1",
63
- "@types/node": "^20.0.0",
64
- "@types/node-fetch": "^2.6.12",
65
- "dotenv": "^16.5.0",
66
- "rimraf": "^6.0.1",
67
- "ts-node": "^10.9.2",
68
- "tsx": "^4.20.3",
69
- "typescript": "^5.8.3"
70
- },
71
- "files": [
72
- "dist/cjs/**/*.js",
73
- "dist/esm/**/*.js",
74
- "dist/types/**/*.d.ts",
75
- "README.md",
76
- "LICENSE"
77
- ],
78
- "sideEffects": false,
79
- "engines": {
80
- "node": ">=16.0.0"
81
- }
82
- }
1
+ {
2
+ "name": "@revenium/anthropic",
3
+ "version": "1.0.4",
4
+ "description": "Transparent TypeScript middleware for automatic Revenium usage tracking with Anthropic Claude AI",
5
+ "main": "dist/cjs/index.js",
6
+ "module": "dist/esm/index.js",
7
+ "types": "dist/types/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": {
11
+ "types": "./dist/types/index.d.ts",
12
+ "default": "./dist/esm/index.js"
13
+ },
14
+ "require": {
15
+ "types": "./dist/types/index.d.ts",
16
+ "default": "./dist/cjs/index.js"
17
+ }
18
+ }
19
+ },
20
+ "scripts": {
21
+ "build": "npm run build:cjs && npm run build:esm && npm run build:types && npm run fix-esm",
22
+ "build:cjs": "tsc -p tsconfig.json",
23
+ "build:esm": "tsc -p tsconfig.esm.json",
24
+ "build:types": "tsc -p tsconfig.types.json",
25
+ "fix-esm": "node scripts/fix-esm-imports.js",
26
+ "dev": "tsc --watch",
27
+ "test": "npm run build && echo 'Build successful - no automated tests configured'",
28
+ "example": "npm run build && tsx examples/basic-usage.ts",
29
+ "example:basic": "npm run build && tsx examples/basic-usage.ts",
30
+ "example:advanced": "npm run build && tsx examples/advanced-features.ts",
31
+ "clean": "rimraf dist",
32
+ "prepublishOnly": "npm run clean && npm run build"
33
+ },
34
+ "keywords": [
35
+ "anthropic",
36
+ "claude",
37
+ "revenium",
38
+ "middleware",
39
+ "typescript",
40
+ "nodejs",
41
+ "usage-tracking",
42
+ "metering",
43
+ "ai"
44
+ ],
45
+ "author": "Revenium",
46
+ "license": "MIT",
47
+ "repository": {
48
+ "type": "git",
49
+ "url": "git+https://github.com/revenium/revenium-middleware-anthropic-node.git"
50
+ },
51
+ "homepage": "https://github.com/revenium/revenium-middleware-anthropic-node#readme",
52
+ "bugs": {
53
+ "url": "https://github.com/revenium/revenium-middleware-anthropic-node/issues"
54
+ },
55
+ "dependencies": {
56
+ "node-fetch": "^3.3.2"
57
+ },
58
+ "peerDependencies": {
59
+ "@anthropic-ai/sdk": ">=0.24.0"
60
+ },
61
+ "devDependencies": {
62
+ "@anthropic-ai/sdk": "^0.55.1",
63
+ "@types/node": "^20.0.0",
64
+ "@types/node-fetch": "^2.6.12",
65
+ "dotenv": "^16.5.0",
66
+ "rimraf": "^6.0.1",
67
+ "ts-node": "^10.9.2",
68
+ "tsx": "^4.20.3",
69
+ "typescript": "^5.8.3"
70
+ },
71
+ "files": [
72
+ "dist/cjs/**/*.js",
73
+ "dist/esm/**/*.js",
74
+ "dist/types/**/*.d.ts",
75
+ "examples/**/*",
76
+ "README.md",
77
+ "CHANGELOG.md",
78
+ "LICENSE"
79
+ ],
80
+ "sideEffects": false,
81
+ "engines": {
82
+ "node": ">=16.0.0"
83
+ }
84
+ }