@nordsym/apiclaw 2.2.0 → 2.2.1

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.
Files changed (176) hide show
  1. package/README.md +15 -2
  2. package/dist/bin-http.js +0 -0
  3. package/dist/bin.bundled.js +79288 -0
  4. package/dist/gateway-client.d.ts.map +1 -1
  5. package/dist/gateway-client.js +24 -2
  6. package/dist/gateway-client.js.map +1 -1
  7. package/dist/index.bundled.js +61263 -0
  8. package/dist/index.js +2 -2
  9. package/dist/index.js.map +1 -1
  10. package/package.json +7 -2
  11. package/.claude/settings.local.json +0 -13
  12. package/.env.prod +0 -1
  13. package/apiclaw-README.md +0 -494
  14. package/convex/_generated/api.d.ts +0 -145
  15. package/convex/_generated/api.js +0 -23
  16. package/convex/_generated/dataModel.d.ts +0 -60
  17. package/convex/_generated/server.d.ts +0 -143
  18. package/convex/_generated/server.js +0 -93
  19. package/convex/_listWorkspaces.ts +0 -13
  20. package/convex/adminActivate.ts +0 -53
  21. package/convex/adminStats.ts +0 -306
  22. package/convex/agents.ts +0 -939
  23. package/convex/analytics.ts +0 -187
  24. package/convex/apiKeys.ts +0 -220
  25. package/convex/backfillAnalytics.ts +0 -272
  26. package/convex/backfillSearchLogs.ts +0 -35
  27. package/convex/billing.ts +0 -834
  28. package/convex/capabilities.ts +0 -157
  29. package/convex/chains.ts +0 -1318
  30. package/convex/credits.ts +0 -211
  31. package/convex/crons.ts +0 -65
  32. package/convex/debugFilestackLogs.ts +0 -16
  33. package/convex/debugGetToken.ts +0 -18
  34. package/convex/directCall.ts +0 -713
  35. package/convex/earnProgress.ts +0 -753
  36. package/convex/email.ts +0 -329
  37. package/convex/feedback.ts +0 -265
  38. package/convex/funnel.ts +0 -431
  39. package/convex/guards.ts +0 -174
  40. package/convex/http.ts +0 -3756
  41. package/convex/inbound.ts +0 -32
  42. package/convex/logs.ts +0 -701
  43. package/convex/migrateFilestack.ts +0 -81
  44. package/convex/migratePartnersProd.ts +0 -174
  45. package/convex/migratePratham.ts +0 -126
  46. package/convex/migrateProviderWorkspaces.ts +0 -175
  47. package/convex/mou.ts +0 -91
  48. package/convex/nurture.ts +0 -355
  49. package/convex/providerKeys.ts +0 -289
  50. package/convex/providers.ts +0 -1135
  51. package/convex/purchases.ts +0 -183
  52. package/convex/ratelimit.ts +0 -104
  53. package/convex/schema.ts +0 -926
  54. package/convex/searchLogs.ts +0 -265
  55. package/convex/seedAPILayerAPIs.ts +0 -191
  56. package/convex/seedDirectCallConfigs.ts +0 -336
  57. package/convex/seedPratham.ts +0 -149
  58. package/convex/spendAlerts.ts +0 -442
  59. package/convex/stripeActions.ts +0 -607
  60. package/convex/teams.ts +0 -243
  61. package/convex/telemetry.ts +0 -81
  62. package/convex/tsconfig.json +0 -25
  63. package/convex/updateAPIStatus.ts +0 -44
  64. package/convex/usage.ts +0 -260
  65. package/convex/usageReports.ts +0 -357
  66. package/convex/waitlist.ts +0 -55
  67. package/convex/webhooks.ts +0 -494
  68. package/convex/workspaceSettings.ts +0 -143
  69. package/convex/workspaces.ts +0 -1331
  70. package/convex.json +0 -3
  71. package/direct-test.mjs +0 -51
  72. package/email-templates/filestack-provider-outreach.html +0 -162
  73. package/email-templates/partnership-template.html +0 -116
  74. package/email-templates/pratham-draft-preview.txt +0 -57
  75. package/email-templates/pratham-partnership-draft.html +0 -141
  76. package/reports/APIClaw-Session-Report-2026-04-05.pdf +0 -0
  77. package/reports/pipeline/PIPELINE-REPORT.json +0 -153
  78. package/reports/pipeline/acquire_apisguru.json +0 -17
  79. package/reports/pipeline/capabilities.json +0 -38
  80. package/reports/pipeline/discover_azure_recursive.json +0 -1551
  81. package/reports/pipeline/discover_github.json +0 -25
  82. package/reports/pipeline/discover_github_repos.json +0 -49
  83. package/reports/pipeline/discover_swaggerhub.json +0 -24
  84. package/reports/pipeline/discover_well_known.json +0 -23
  85. package/reports/pipeline/fetch_specs.json +0 -19
  86. package/reports/pipeline/generate_providers.json +0 -14
  87. package/reports/pipeline/match_registry.json +0 -11
  88. package/reports/pipeline/parse_specs.json +0 -17
  89. package/reports/pipeline/promote_candidates.json +0 -34
  90. package/reports/pipeline/validate.json +0 -30
  91. package/reports/pipeline/validate_smoke_details.json +0 -3835
  92. package/reports/session-report-2026-04-05.html +0 -433
  93. package/seed-apis-direct.mjs +0 -106
  94. package/src/access-control.ts +0 -174
  95. package/src/adapters/base.ts +0 -364
  96. package/src/adapters/claude-desktop.ts +0 -41
  97. package/src/adapters/cline.ts +0 -88
  98. package/src/adapters/continue.ts +0 -91
  99. package/src/adapters/cursor.ts +0 -43
  100. package/src/adapters/custom.ts +0 -188
  101. package/src/adapters/detect.ts +0 -202
  102. package/src/adapters/index.ts +0 -47
  103. package/src/adapters/windsurf.ts +0 -44
  104. package/src/bin-http.ts +0 -45
  105. package/src/bin.ts +0 -34
  106. package/src/capability-router.ts +0 -331
  107. package/src/chainExecutor.ts +0 -730
  108. package/src/chainResolver.test.ts +0 -246
  109. package/src/chainResolver.ts +0 -658
  110. package/src/cli/commands/demo.ts +0 -109
  111. package/src/cli/commands/doctor.ts +0 -435
  112. package/src/cli/commands/index.ts +0 -9
  113. package/src/cli/commands/login.ts +0 -203
  114. package/src/cli/commands/mcp-install.ts +0 -373
  115. package/src/cli/commands/restore.ts +0 -333
  116. package/src/cli/commands/setup.ts +0 -297
  117. package/src/cli/commands/uninstall.ts +0 -240
  118. package/src/cli/index.ts +0 -148
  119. package/src/cli.ts +0 -370
  120. package/src/confirmation.ts +0 -296
  121. package/src/credentials.ts +0 -455
  122. package/src/credits.ts +0 -329
  123. package/src/crypto.ts +0 -75
  124. package/src/discovery.ts +0 -568
  125. package/src/enterprise/env.ts +0 -156
  126. package/src/enterprise/index.ts +0 -7
  127. package/src/enterprise/script-generator.ts +0 -481
  128. package/src/execute-dynamic.ts +0 -617
  129. package/src/execute.ts +0 -2386
  130. package/src/funnel-client.ts +0 -168
  131. package/src/funnel.test.ts +0 -187
  132. package/src/gateway-client.ts +0 -192
  133. package/src/hivr-whitelist.ts +0 -110
  134. package/src/http-api.ts +0 -286
  135. package/src/http-server-minimal.ts +0 -154
  136. package/src/index.ts +0 -2702
  137. package/src/intelligent-gateway.ts +0 -339
  138. package/src/mcp-analytics.ts +0 -156
  139. package/src/metered.ts +0 -149
  140. package/src/open-apis-generated.ts +0 -157
  141. package/src/open-apis.ts +0 -558
  142. package/src/postinstall.ts +0 -40
  143. package/src/product-whitelist.ts +0 -246
  144. package/src/proxy.ts +0 -36
  145. package/src/registration-guard.ts +0 -117
  146. package/src/session.ts +0 -129
  147. package/src/stripe.ts +0 -497
  148. package/src/telemetry.ts +0 -71
  149. package/src/test.ts +0 -135
  150. package/src/types/convex-api.d.ts +0 -20
  151. package/src/types/convex-api.ts +0 -21
  152. package/src/types.ts +0 -109
  153. package/src/ui/colors.ts +0 -219
  154. package/src/ui/errors.ts +0 -394
  155. package/src/ui/index.ts +0 -17
  156. package/src/ui/prompts.ts +0 -390
  157. package/src/ui/spinner.ts +0 -325
  158. package/src/utils/backup.ts +0 -224
  159. package/src/utils/config.ts +0 -318
  160. package/src/utils/os.ts +0 -124
  161. package/src/utils/paths.ts +0 -203
  162. package/src/webhook.ts +0 -107
  163. package/test-10-working.cjs +0 -97
  164. package/test-14-final.cjs +0 -96
  165. package/test-actual-handlers.ts +0 -92
  166. package/test-apilayer-all-14.ts +0 -249
  167. package/test-apilayer-fixed.ts +0 -248
  168. package/test-direct-endpoints.ts +0 -174
  169. package/test-exact-endpoints.ts +0 -144
  170. package/test-final.ts +0 -83
  171. package/test-full-routing.ts +0 -100
  172. package/test-handlers-correct.ts +0 -217
  173. package/test-numverify-key.ts +0 -41
  174. package/test-via-handlers.ts +0 -92
  175. package/test-worldnews.mjs +0 -26
  176. package/tsconfig.json +0 -20
@@ -1,339 +0,0 @@
1
- /**
2
- * APIClaw Intelligent Gateway - Capability Resolver
3
- *
4
- * Routes natural-language intents and capability queries to the best
5
- * matching providers from the 25k+ generated provider registry.
6
- */
7
-
8
- import { createRequire } from 'module';
9
-
10
- const require = createRequire(import.meta.url);
11
-
12
- // ---------------------------------------------------------------------------
13
- // Types
14
- // ---------------------------------------------------------------------------
15
-
16
- interface GeneratedActionParam {
17
- name: string;
18
- in: 'path' | 'query' | 'header' | 'body' | string;
19
- required?: boolean;
20
- type?: string;
21
- }
22
-
23
- interface GeneratedAction {
24
- method: 'GET' | 'POST';
25
- pathTemplate: string;
26
- operationId?: string;
27
- summary?: string;
28
- params?: GeneratedActionParam[];
29
- requiresAuth?: boolean;
30
- capabilities?: string[];
31
- capabilityPrimary?: string;
32
- }
33
-
34
- interface GeneratedProvider {
35
- id: string;
36
- name: string;
37
- description: string;
38
- baseUrl: string;
39
- host: string;
40
- source: string;
41
- sourceUrl: string;
42
- callable: boolean;
43
- matchKind: string;
44
- matchConfidence: number;
45
- actionCount: number;
46
- actions: Record<string, GeneratedAction>;
47
- capabilitySummary?: string[];
48
- }
49
-
50
- interface GeneratedArtifact {
51
- version: number;
52
- generatedAt: number;
53
- providerCount: number;
54
- callableCount: number;
55
- providers: GeneratedProvider[];
56
- }
57
-
58
- // ---------------------------------------------------------------------------
59
- // Public interfaces
60
- // ---------------------------------------------------------------------------
61
-
62
- export interface ResolvedProvider {
63
- providerId: string;
64
- providerName: string;
65
- baseUrl: string;
66
- capability: string;
67
- matchedActions: {
68
- actionId: string;
69
- method: string;
70
- pathTemplate: string;
71
- summary: string;
72
- capabilities: string[];
73
- }[];
74
- score: number;
75
- callable: boolean;
76
- }
77
-
78
- export interface CapabilityInfo {
79
- capability: string;
80
- providerCount: number;
81
- actionCount: number;
82
- }
83
-
84
- export interface VersatileProvider {
85
- providerId: string;
86
- name: string;
87
- capabilities: string[];
88
- actionCount: number;
89
- }
90
-
91
- // ---------------------------------------------------------------------------
92
- // Data loader (cached)
93
- // ---------------------------------------------------------------------------
94
-
95
- let cachedArtifact: GeneratedArtifact | null = null;
96
-
97
- function loadArtifact(): GeneratedArtifact {
98
- if (cachedArtifact) return cachedArtifact;
99
- try {
100
- cachedArtifact = require('./registry/generated-providers.json') as GeneratedArtifact;
101
- } catch {
102
- cachedArtifact = {
103
- version: 1,
104
- generatedAt: 0,
105
- providerCount: 0,
106
- callableCount: 0,
107
- providers: [],
108
- };
109
- }
110
- return cachedArtifact;
111
- }
112
-
113
- // ---------------------------------------------------------------------------
114
- // Keyword matching helpers
115
- // ---------------------------------------------------------------------------
116
-
117
- function containsKeyword(text: string, keyword: string): boolean {
118
- return text.toLowerCase().includes(keyword.toLowerCase());
119
- }
120
-
121
- function countKeywordHits(text: string, keywords: string[]): number {
122
- let hits = 0;
123
- const lower = text.toLowerCase();
124
- for (const kw of keywords) {
125
- if (lower.includes(kw.toLowerCase())) hits++;
126
- }
127
- return hits;
128
- }
129
-
130
- // ---------------------------------------------------------------------------
131
- // resolveCapability
132
- // ---------------------------------------------------------------------------
133
-
134
- export function resolveCapability(
135
- capability: string,
136
- keywords?: string[],
137
- opts?: { limit?: number; callableOnly?: boolean },
138
- ): ResolvedProvider[] {
139
- const limit = opts?.limit ?? 10;
140
- const callableOnly = opts?.callableOnly ?? true;
141
- const artifact = loadArtifact();
142
- const capLower = capability.toLowerCase();
143
- const kws = keywords?.map(k => k.toLowerCase()) ?? [];
144
-
145
- const results: ResolvedProvider[] = [];
146
-
147
- for (const provider of artifact.providers) {
148
- // Filter callable
149
- if (callableOnly && !provider.callable) continue;
150
-
151
- // Capability must be in capabilitySummary
152
- const caps = provider.capabilitySummary ?? [];
153
- if (!caps.some(c => c.toLowerCase() === capLower)) continue;
154
-
155
- // Find matching actions (actions whose capabilities include the requested one)
156
- const matchedActions: ResolvedProvider['matchedActions'] = [];
157
- for (const [actionId, action] of Object.entries(provider.actions)) {
158
- const actionCaps = action.capabilities ?? [];
159
- if (actionCaps.some(c => c.toLowerCase() === capLower)) {
160
- matchedActions.push({
161
- actionId,
162
- method: action.method,
163
- pathTemplate: action.pathTemplate,
164
- summary: action.summary ?? '',
165
- capabilities: actionCaps,
166
- });
167
- }
168
- }
169
-
170
- // Score — rewards relevance density, not raw volume
171
- let rawScore = 0;
172
-
173
- if (kws.length > 0) {
174
- // Keyword hits in provider name + description (strongest signal)
175
- const nameDescText = `${provider.name} ${provider.description}`.toLowerCase();
176
- const nameHits = kws.filter(kw => nameDescText.includes(kw)).length;
177
- rawScore += (nameHits / kws.length) * 0.4; // up to 0.4 for name/desc match
178
-
179
- // Keyword density in MATCHED actions only (not all actions)
180
- if (matchedActions.length > 0) {
181
- const matchedText = matchedActions
182
- .map(a => `${a.summary} ${a.actionId} ${a.pathTemplate}`)
183
- .join(' ')
184
- .toLowerCase();
185
- const actionHits = kws.filter(kw => matchedText.includes(kw)).length;
186
- rawScore += (actionHits / kws.length) * 0.2; // up to 0.2
187
- }
188
- } else {
189
- // No keywords — base capability match
190
- rawScore += 0.3;
191
- }
192
-
193
- // Callable bonus (verified working)
194
- if (provider.callable) rawScore += 0.25;
195
-
196
- // Action richness for this capability (more matched actions = more useful)
197
- const actionRatio = Math.min(matchedActions.length / 5, 1);
198
- rawScore += actionRatio * 0.1;
199
-
200
- // Penalize mock/sandbox servers
201
- const urlLower = provider.baseUrl.toLowerCase();
202
- if (urlLower.includes('virtserver') || urlLower.includes('sandbox') || urlLower.includes('.local')) {
203
- rawScore *= 0.5;
204
- }
205
-
206
- // Normalize to 0-1
207
- const score = Math.min(1, rawScore);
208
-
209
- results.push({
210
- providerId: provider.id,
211
- providerName: provider.name,
212
- baseUrl: provider.baseUrl,
213
- capability,
214
- matchedActions,
215
- score: Math.round(score * 1000) / 1000,
216
- callable: provider.callable,
217
- });
218
- }
219
-
220
- // Sort by score descending
221
- results.sort((a, b) => b.score - a.score);
222
-
223
- return results.slice(0, limit);
224
- }
225
-
226
- // ---------------------------------------------------------------------------
227
- // findProviderForIntent
228
- // ---------------------------------------------------------------------------
229
-
230
- const CAPABILITY_WORDS = new Set([
231
- 'lookup', 'search', 'list', 'convert', 'validate', 'generate',
232
- 'monitor', 'price', 'enrich', 'analyze', 'send', 'compute',
233
- 'stream', 'create', 'update',
234
- ]);
235
-
236
- const STOP_WORDS = new Set([
237
- 'i', 'need', 'to', 'a', 'an', 'the', 'want', 'can', 'you',
238
- 'please', 'me', 'find', 'get', 'do', 'make', 'help', 'with',
239
- 'for', 'from', 'this', 'that',
240
- ]);
241
-
242
- export function findProviderForIntent(intentText: string): ResolvedProvider[] {
243
- const tokens = intentText
244
- .toLowerCase()
245
- .replace(/[^a-z0-9\s]/g, '')
246
- .split(/\s+/)
247
- .filter(t => t.length > 0);
248
-
249
- const capabilities: string[] = [];
250
- const keywords: string[] = [];
251
-
252
- for (const token of tokens) {
253
- if (CAPABILITY_WORDS.has(token)) {
254
- capabilities.push(token);
255
- } else if (!STOP_WORDS.has(token)) {
256
- keywords.push(token);
257
- }
258
- }
259
-
260
- // Default capability if none extracted
261
- if (capabilities.length === 0) {
262
- capabilities.push('search');
263
- }
264
-
265
- // Merge results from all detected capabilities, dedup by providerId
266
- const seen = new Set<string>();
267
- const merged: ResolvedProvider[] = [];
268
-
269
- for (const cap of capabilities) {
270
- const results = resolveCapability(cap, keywords, { limit: 20, callableOnly: false });
271
- for (const r of results) {
272
- if (!seen.has(r.providerId)) {
273
- seen.add(r.providerId);
274
- merged.push(r);
275
- }
276
- }
277
- }
278
-
279
- // Re-sort and limit
280
- merged.sort((a, b) => b.score - a.score);
281
- return merged.slice(0, 10);
282
- }
283
-
284
- // ---------------------------------------------------------------------------
285
- // listCapabilities
286
- // ---------------------------------------------------------------------------
287
-
288
- export function listCapabilities(): CapabilityInfo[] {
289
- const artifact = loadArtifact();
290
- const capMap = new Map<string, { providerCount: number; actionCount: number }>();
291
-
292
- for (const provider of artifact.providers) {
293
- const counted = new Set<string>();
294
- for (const action of Object.values(provider.actions)) {
295
- const actionCaps = action.capabilities ?? [];
296
- for (const cap of actionCaps) {
297
- const entry = capMap.get(cap) ?? { providerCount: 0, actionCount: 0 };
298
- entry.actionCount++;
299
- if (!counted.has(cap)) {
300
- entry.providerCount++;
301
- counted.add(cap);
302
- }
303
- capMap.set(cap, entry);
304
- }
305
- }
306
- }
307
-
308
- const result: CapabilityInfo[] = [];
309
- for (const [capability, stats] of capMap) {
310
- result.push({ capability, ...stats });
311
- }
312
-
313
- result.sort((a, b) => b.actionCount - a.actionCount);
314
- return result;
315
- }
316
-
317
- // ---------------------------------------------------------------------------
318
- // findVersatileProviders
319
- // ---------------------------------------------------------------------------
320
-
321
- export function findVersatileProviders(minCapabilities: number): VersatileProvider[] {
322
- const artifact = loadArtifact();
323
- const results: VersatileProvider[] = [];
324
-
325
- for (const provider of artifact.providers) {
326
- const caps = provider.capabilitySummary ?? [];
327
- if (caps.length >= minCapabilities) {
328
- results.push({
329
- providerId: provider.id,
330
- name: provider.name,
331
- capabilities: caps,
332
- actionCount: provider.actionCount,
333
- });
334
- }
335
- }
336
-
337
- results.sort((a, b) => b.capabilities.length - a.capabilities.length || b.actionCount - a.actionCount);
338
- return results;
339
- }
@@ -1,156 +0,0 @@
1
- /**
2
- * APIClaw Analytics - Track all API usage
3
- * Both Direct Call and Open API calls are logged here
4
- */
5
-
6
- import { appendFileSync, existsSync, mkdirSync } from 'fs';
7
- import { homedir } from 'os';
8
- import { join } from 'path';
9
- import { ConvexHttpClient } from 'convex/browser';
10
- import { api } from './types/convex-api.js';
11
-
12
- export interface APICallLog {
13
- timestamp: string;
14
- provider: string;
15
- action: string;
16
- type: 'direct' | 'open';
17
- userId?: string;
18
- success: boolean;
19
- latencyMs?: number;
20
- error?: string;
21
- metadata?: {
22
- product?: string;
23
- [key: string]: any;
24
- };
25
- }
26
-
27
- // Log directory
28
- const LOG_DIR = join(homedir(), '.apiclaw', 'logs');
29
- const LOG_FILE = join(LOG_DIR, 'api-calls.jsonl');
30
-
31
- // Convex client (lazy init)
32
- let convexClient: ConvexHttpClient | null = null;
33
-
34
- function getConvexClient(): ConvexHttpClient | null {
35
- if (convexClient) return convexClient;
36
-
37
- const convexUrl = process.env.APICLAW_CONVEX_URL || process.env.NEXT_PUBLIC_CONVEX_URL;
38
- if (!convexUrl) return null;
39
-
40
- try {
41
- convexClient = new ConvexHttpClient(convexUrl);
42
- return convexClient;
43
- } catch (e) {
44
- console.error('[APIClaw Analytics] Failed to init Convex client:', e);
45
- return null;
46
- }
47
- }
48
-
49
- // Ensure log directory exists
50
- function ensureLogDir(): void {
51
- if (!existsSync(LOG_DIR)) {
52
- mkdirSync(LOG_DIR, { recursive: true });
53
- }
54
- }
55
-
56
- /**
57
- * Log an API call to local file AND Convex
58
- */
59
- export function logAPICall(log: APICallLog): void {
60
- // 1. Local file (existing behavior)
61
- try {
62
- ensureLogDir();
63
- const line = JSON.stringify(log) + '\n';
64
- appendFileSync(LOG_FILE, line);
65
- } catch (e) {
66
- console.error('[APIClaw Analytics] Failed to log to file:', e);
67
- }
68
-
69
- // 2. Send to Convex (new - includes anonymous usage)
70
- sendToConvex(log).catch(() => {}); // Fire and forget
71
- }
72
-
73
- /**
74
- * Send analytics event to Convex
75
- * Works for both authenticated and anonymous users
76
- */
77
- async function sendToConvex(log: APICallLog): Promise<void> {
78
- const client = getConvexClient();
79
- if (!client) return;
80
-
81
- try {
82
- await client.mutation(api.analytics.log, {
83
- event: 'api_call',
84
- provider: log.provider,
85
- query: log.action, // Store action as query field
86
- identifier: log.userId || 'anonymous',
87
- metadata: {
88
- type: log.type,
89
- success: log.success,
90
- latencyMs: log.latencyMs,
91
- error: log.error,
92
- timestamp: log.timestamp,
93
- ...log.metadata, // Include product and any other metadata
94
- },
95
- });
96
- } catch (e) {
97
- // Silent fail - don't break API calls for logging errors
98
- console.error('[APIClaw Analytics] Failed to send to Convex:', e);
99
- }
100
- }
101
-
102
- /**
103
- * Webhook for real-time analytics (optional)
104
- * Set APICLAW_ANALYTICS_WEBHOOK env var to enable
105
- */
106
- export async function sendToWebhook(log: APICallLog): Promise<void> {
107
- const webhookUrl = process.env.APICLAW_ANALYTICS_WEBHOOK;
108
- if (!webhookUrl) return;
109
-
110
- try {
111
- await fetch(webhookUrl, {
112
- method: 'POST',
113
- headers: { 'Content-Type': 'application/json' },
114
- body: JSON.stringify(log),
115
- });
116
- } catch (e) {
117
- // Silent fail
118
- }
119
- }
120
-
121
- /**
122
- * Track API call with timing
123
- */
124
- export async function trackAPICall<T>(
125
- provider: string,
126
- action: string,
127
- type: 'direct' | 'open',
128
- userId: string | undefined,
129
- fn: () => Promise<T>
130
- ): Promise<T> {
131
- const start = Date.now();
132
- let success = true;
133
- let error: string | undefined;
134
-
135
- try {
136
- return await fn();
137
- } catch (e: any) {
138
- success = false;
139
- error = e.message;
140
- throw e;
141
- } finally {
142
- const log: APICallLog = {
143
- timestamp: new Date().toISOString(),
144
- provider,
145
- action,
146
- type,
147
- userId,
148
- success,
149
- latencyMs: Date.now() - start,
150
- error,
151
- };
152
-
153
- logAPICall(log);
154
- sendToWebhook(log).catch(() => {}); // Fire and forget
155
- }
156
- }
package/src/metered.ts DELETED
@@ -1,149 +0,0 @@
1
- /**
2
- * APIClaw Metered Billing - Pay-per-call execution wrapper
3
- *
4
- * Usage:
5
- * 1. Customer signs up with metered subscription
6
- * 2. Each API call via executeMetered() reports usage to Stripe
7
- * 3. Customer is billed at end of billing period based on usage
8
- */
9
-
10
- import { executeAPICall } from './execute.js';
11
- import { reportUsage, hasActiveMeteredSubscription, METERED_BILLING } from './stripe.js';
12
-
13
- interface MeteredResult {
14
- success: boolean;
15
- provider: string;
16
- action: string;
17
- data?: unknown;
18
- error?: string;
19
- cost?: number;
20
- billing?: {
21
- tracked: boolean;
22
- customerId?: string;
23
- pricePerCall: number;
24
- };
25
- }
26
-
27
- interface MeteredOptions {
28
- /** Stripe customer ID for usage tracking */
29
- customerId?: string;
30
- /** Skip usage reporting (for testing/free tier) */
31
- skipBilling?: boolean;
32
- /** Provider-specific API key (Direct Call mode) */
33
- customerKey?: string;
34
- /** User ID for dynamic providers */
35
- userId?: string;
36
- }
37
-
38
- /**
39
- * Execute an API call with metered billing tracking
40
- *
41
- * If customerId is provided and has active metered subscription,
42
- * usage is reported to Stripe after successful execution.
43
- */
44
- export async function executeMetered(
45
- providerId: string,
46
- action: string,
47
- params: Record<string, unknown>,
48
- options: MeteredOptions = {}
49
- ): Promise<MeteredResult> {
50
- const { customerId, skipBilling, customerKey, userId } = options;
51
-
52
- // Execute the API call
53
- const result = await executeAPICall(
54
- providerId,
55
- action,
56
- params,
57
- userId,
58
- customerKey
59
- );
60
-
61
- // Build response
62
- const response: MeteredResult = {
63
- ...result,
64
- billing: {
65
- tracked: false,
66
- pricePerCall: METERED_BILLING.pricePerCall,
67
- },
68
- };
69
-
70
- // Skip billing if requested or no customer
71
- if (skipBilling || !customerId) {
72
- return response;
73
- }
74
-
75
- // Skip billing for failed calls
76
- if (!result.success) {
77
- return response;
78
- }
79
-
80
- // Check for active metered subscription
81
- const subscription = await hasActiveMeteredSubscription(customerId);
82
- if (!subscription.active) {
83
- console.log(`Customer ${customerId} has no active metered subscription`);
84
- return response;
85
- }
86
-
87
- // Report usage to Stripe meter
88
- const usageReport = await reportUsage(
89
- customerId,
90
- 1,
91
- `${customerId}_${providerId}_${action}_${Date.now()}`
92
- );
93
-
94
- if (usageReport.success) {
95
- response.billing = {
96
- tracked: true,
97
- customerId,
98
- pricePerCall: METERED_BILLING.pricePerCall,
99
- };
100
- } else {
101
- console.error(`Failed to report usage for ${customerId}:`, usageReport.error);
102
- }
103
-
104
- return response;
105
- }
106
-
107
- /**
108
- * Execute multiple API calls in batch with usage tracking
109
- */
110
- export async function executeMeteredBatch(
111
- calls: Array<{
112
- provider: string;
113
- action: string;
114
- params: Record<string, unknown>;
115
- }>,
116
- options: MeteredOptions = {}
117
- ): Promise<MeteredResult[]> {
118
- const results = await Promise.all(
119
- calls.map((call) =>
120
- executeMetered(call.provider, call.action, call.params, options)
121
- )
122
- );
123
-
124
- return results;
125
- }
126
-
127
- /**
128
- * Calculate estimated cost for a number of API calls
129
- */
130
- export function estimateCost(callCount: number): {
131
- calls: number;
132
- pricePerCall: number;
133
- totalCost: number;
134
- currency: string;
135
- } {
136
- return {
137
- calls: callCount,
138
- pricePerCall: METERED_BILLING.pricePerCall,
139
- totalCost: callCount * METERED_BILLING.pricePerCall,
140
- currency: 'USD',
141
- };
142
- }
143
-
144
- /**
145
- * Get metered billing configuration
146
- */
147
- export function getMeteredConfig(): typeof METERED_BILLING {
148
- return METERED_BILLING;
149
- }