@drawbridge/drawbridge-utils 0.0.103 → 0.0.104

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,807 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all2) => {
8
+ for (var name in all2)
9
+ __defProp(target, name, { get: all2[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // lib/pricing.js
30
+ var pricing_exports = {};
31
+ __export(pricing_exports, {
32
+ LOCAL_FLAT_CENTS: () => LOCAL_FLAT_CENTS,
33
+ MARKUP: () => MARKUP,
34
+ PREMIUM_CPM_CENTS: () => PREMIUM_CPM_CENTS,
35
+ PREMIUM_RATE_PER_GB: () => PREMIUM_RATE_PER_GB,
36
+ REUSE_FLAT_CENTS: () => REUSE_FLAT_CENTS,
37
+ STANDARD_CPM_CENTS: () => STANDARD_CPM_CENTS,
38
+ STANDARD_RATE_PER_GB: () => STANDARD_RATE_PER_GB,
39
+ ai: () => ai,
40
+ channels: () => channels,
41
+ conversionRate: () => conversionRate,
42
+ free: () => free,
43
+ plans: () => plans,
44
+ resolvePlan: () => resolvePlan,
45
+ scrape: () => scrape,
46
+ unitAmountDecimal: () => unitAmountDecimal
47
+ });
48
+ module.exports = __toCommonJS(pricing_exports);
49
+
50
+ // lib/features.js
51
+ var page = {
52
+ qrcode: {
53
+ key: "page:qrcode",
54
+ error: "Plan does not include qrcodes",
55
+ feature: "Page qrcode management"
56
+ },
57
+ shortcode: {
58
+ key: "page:shortcode",
59
+ error: "Plan does not include shortcodes",
60
+ feature: "Page shortcode management"
61
+ },
62
+ slug: {
63
+ key: "page:slug",
64
+ error: "Plan does not include url customization",
65
+ feature: "Page slug customization"
66
+ }
67
+ };
68
+ var fields = {
69
+ additional: {
70
+ key: "campaign:fields:additional",
71
+ error: "Plan does not include additional fields",
72
+ feature: "Campaign additional fields"
73
+ },
74
+ lead: {
75
+ key: "campaign:fields:lead",
76
+ error: "Plan does not include lead fields",
77
+ feature: "Campaign lead fields"
78
+ }
79
+ };
80
+ var field = {
81
+ email: {
82
+ key: "campaign:field:email",
83
+ error: "Plan does not include email field",
84
+ feature: "Campaign email field"
85
+ },
86
+ name: {
87
+ key: "campaign:field:name",
88
+ error: "Plan does not include name field",
89
+ feature: "Campaign name field"
90
+ },
91
+ number: {
92
+ key: "campaign:field:number",
93
+ error: "Plan does not include number field",
94
+ feature: "Campaign number field"
95
+ },
96
+ phone: {
97
+ key: "campaign:field:phone",
98
+ error: "Plan does not include phone field",
99
+ feature: "Campaign phone field"
100
+ },
101
+ select: {
102
+ key: "campaign:field:select",
103
+ error: "Plan does not include dropdown field",
104
+ feature: "Campaign dropdown field"
105
+ },
106
+ text: {
107
+ key: "campaign:field:text",
108
+ error: "Plan does not include short text field",
109
+ feature: "Campaign short text field"
110
+ },
111
+ textarea: {
112
+ key: "campaign:field:textarea",
113
+ error: "Plan does not include long text field",
114
+ feature: "Campaign long text field"
115
+ }
116
+ };
117
+ var connection = {
118
+ mailchimp: {
119
+ key: "organization:connection:mailchimp",
120
+ error: "Plan does not include Mailchimp connection",
121
+ feature: "Mailchimp connection"
122
+ },
123
+ sender: {
124
+ key: "organization:connection:sender",
125
+ error: "Plan does not include a verified sending domain",
126
+ feature: "Sending domain connection"
127
+ },
128
+ sendgrid: {
129
+ key: "organization:connection:sendgrid",
130
+ error: "Plan does not include SendGrid connection",
131
+ feature: "SendGrid connection"
132
+ },
133
+ shopify: {
134
+ key: "organization:connection:shopify",
135
+ error: "Plan does not include Shopify connection",
136
+ feature: "Shopify connection"
137
+ },
138
+ twilio: {
139
+ key: "organization:connection:twilio",
140
+ error: "Plan does not include Twilio connection",
141
+ feature: "Twilio connection"
142
+ },
143
+ webhook: {
144
+ key: "organization:connection:webhook",
145
+ error: "Plan does not include Webhook connection",
146
+ feature: "Webhook connection"
147
+ }
148
+ };
149
+ var organization = {
150
+ advertisements: {
151
+ key: "organization:advertisements",
152
+ error: "Your plan does not include advertisements",
153
+ feature: "Organization advertisement management"
154
+ },
155
+ affiliates: {
156
+ key: "organization:affiliates",
157
+ error: "Your plan does not include affiliates",
158
+ feature: "Organization affiliates management"
159
+ },
160
+ analytics: {
161
+ key: "organization:analytics",
162
+ error: "Your plan does not include analytics",
163
+ feature: "Organization analytics management"
164
+ },
165
+ brands: {
166
+ key: "organization:brands",
167
+ error: "Your plan does not include brands",
168
+ feature: "Organization brands management"
169
+ },
170
+ members: {
171
+ key: "organization:members",
172
+ error: "Your plan does not include team members",
173
+ feature: "Organization members management"
174
+ },
175
+ reports: {
176
+ key: "organization:report",
177
+ error: "Plan does not include report generation",
178
+ feature: "Organization report generation"
179
+ },
180
+ subdomain: {
181
+ key: "organization:subdomain",
182
+ error: "Plan does not include subdomain customization",
183
+ feature: "Organization subdomain customization"
184
+ }
185
+ };
186
+
187
+ // index.js
188
+ var import_currency_codes = require("currency-codes");
189
+ var import_nanoid = require("nanoid");
190
+
191
+ // lib/color.js
192
+ var import_tinycolor2 = __toESM(require("tinycolor2"), 1);
193
+ var colorFormatted = (value) => {
194
+ const color = (0, import_tinycolor2.default)(value);
195
+ const attributes = {
196
+ brightness: color.getBrightness(),
197
+ dark: color.isDark(),
198
+ light: color.isLight(),
199
+ luminance: color.getLuminance()
200
+ };
201
+ return {
202
+ attributes,
203
+ hex: color.toHexString(),
204
+ hsl: color.toHsl(),
205
+ hsv: color.toHsv(),
206
+ rgb: color.toRgbString()
207
+ };
208
+ };
209
+ var colorAccessible = (background2) => {
210
+ const white = "#ffffff";
211
+ const black = "#000000";
212
+ return import_tinycolor2.default.isReadable(
213
+ background2,
214
+ white,
215
+ {
216
+ level: "AA",
217
+ size: "normal"
218
+ }
219
+ ) ? white : black;
220
+ };
221
+
222
+ // lib/constants.js
223
+ var font = {
224
+ family: "Roboto Flex",
225
+ transform: "none",
226
+ weight: "regular"
227
+ };
228
+ var background = "#ffffff";
229
+ var style = {
230
+ background: {
231
+ color: colorFormatted(background)
232
+ },
233
+ body: font,
234
+ button: {
235
+ background: {
236
+ color: colorFormatted(background)
237
+ },
238
+ radius: 0,
239
+ text: {
240
+ color: colorFormatted(colorAccessible(background))
241
+ }
242
+ },
243
+ heading: font,
244
+ input: {
245
+ radius: 0
246
+ },
247
+ text: {
248
+ color: colorFormatted(colorAccessible(background))
249
+ }
250
+ };
251
+
252
+ // index.js
253
+ var nanoid = (0, import_nanoid.customAlphabet)("0123456789abcdefghijklmnopqrstuvwxyz", 8);
254
+ var infinite = 1e300;
255
+ var megabyte = 1024 * 1024;
256
+ var gigabyte = megabyte * 1024;
257
+ var currencies = import_currency_codes.data.map((item) => ({
258
+ ...item,
259
+ key: item.currency,
260
+ value: item.code
261
+ }));
262
+
263
+ // lib/plans.js
264
+ var featuresFor = (array = []) => Object.values({
265
+ ...connection,
266
+ ...organization,
267
+ ...fields,
268
+ ...field,
269
+ ...page
270
+ }).reduce(
271
+ (accumulator, { key, error, feature }) => {
272
+ if (array.includes(key)) {
273
+ accumulator.granted[key] = feature;
274
+ } else {
275
+ accumulator.denied[key] = error;
276
+ }
277
+ return accumulator;
278
+ },
279
+ { denied: {}, granted: {} }
280
+ );
281
+ var overage = (actionCents) => ({
282
+ actionCents,
283
+ overages: { actions: String(actionCents) }
284
+ });
285
+ var unitAmountDecimal = (cents) => {
286
+ const value = Number(cents);
287
+ if (cents == null || !Number.isFinite(value)) throw new Error(`Invalid overage rate: ${cents}`);
288
+ return String(value);
289
+ };
290
+ var all = {
291
+ features: (array = []) => featuresFor([
292
+ connection.mailchimp.key,
293
+ connection.sendgrid.key,
294
+ connection.shopify.key,
295
+ connection.twilio.key,
296
+ connection.webhook.key,
297
+ organization.affiliates.key,
298
+ organization.brands.key,
299
+ fields.additional.key,
300
+ fields.lead.key,
301
+ field.email.key,
302
+ field.name.key,
303
+ field.number.key,
304
+ field.phone.key,
305
+ field.select.key,
306
+ field.text.key,
307
+ field.textarea.key,
308
+ page.qrcode.key,
309
+ page.shortcode.key,
310
+ ...array
311
+ ]),
312
+ // `members` and `storage` default to infinite so an unnamed term on a custom
313
+ // plan reads as UNLIMITED rather than absent. Storage used to have no
314
+ // default, so a deal that did not name it resolved to undefined and the
315
+ // organization's usage card simply omitted the row — the same blank field
316
+ // that showed "Unlimited" for members showed nothing at all for storage.
317
+ // Every catalog plan names both, so the defaults only ever apply to a
318
+ // custom plan. `actions` has no default on purpose: an unnamed allowance
319
+ // bills nothing, which is why the availability switch refuses to flip
320
+ // without one.
321
+ limits: ({ actions, members = infinite, storage = infinite }) => ({
322
+ campaign: {
323
+ advertisements: infinite,
324
+ links: infinite,
325
+ fields: infinite,
326
+ pages: infinite
327
+ },
328
+ organization: {
329
+ actions,
330
+ affiliates: infinite,
331
+ brands: infinite,
332
+ campaigns: infinite,
333
+ members,
334
+ storage
335
+ }
336
+ })
337
+ };
338
+ var free = {
339
+ conversion: 3,
340
+ features: all.features(),
341
+ limits: all.limits({
342
+ actions: 200,
343
+ members: 0,
344
+ storage: gigabyte * 5
345
+ }),
346
+ title: "Free"
347
+ };
348
+ var plans = {
349
+ DB00002: {
350
+ // A verified sending domain is a PAID capability: free plans cannot send
351
+ // lead-facing email at all (the send path gates on an active
352
+ // subscription), so granting it there would offer a domain that can
353
+ // never send from.
354
+ features: all.features([connection.sender.key, organization.members.key]),
355
+ limits: all.limits({ actions: 5e3, members: 3, storage: gigabyte * 10 }),
356
+ marketing: {
357
+ description: "Tools to fine-tune campaigns and improve lead quality.",
358
+ features: [],
359
+ limits: [
360
+ ["Actions per month", "5,000"],
361
+ ["Affiliates", "Unlimited"],
362
+ ["Brands", "Unlimited"],
363
+ ["Campaigns", "Unlimited"],
364
+ ["Pages", "Unlimited"],
365
+ ["Members", "3"],
366
+ ["Storage", "10GB"]
367
+ ]
368
+ },
369
+ ...overage(2.5),
370
+ title: "Starter",
371
+ conversion: 2
372
+ },
373
+ DB00003: {
374
+ features: all.features([
375
+ connection.sender.key,
376
+ organization.advertisements.key,
377
+ organization.analytics.key,
378
+ organization.members.key,
379
+ organization.subdomain.key,
380
+ page.slug.key
381
+ ]),
382
+ limits: all.limits({ actions: 15e3, members: 5, storage: gigabyte * 20 }),
383
+ marketing: {
384
+ description: "Expand your reach and grow your lead pipeline.",
385
+ features: [
386
+ "Analytics",
387
+ "Custom subdomain / URLs",
388
+ "Confirmation page ads"
389
+ ],
390
+ limits: [
391
+ ["Actions per month", "15,000"],
392
+ ["Affiliates", "Unlimited"],
393
+ ["Brands", "Unlimited"],
394
+ ["Campaigns", "Unlimited"],
395
+ ["Pages", "Unlimited"],
396
+ ["Members", "5"],
397
+ ["Storage", "20GB"]
398
+ ]
399
+ },
400
+ ...overage(2),
401
+ title: "Pro",
402
+ conversion: 1.5
403
+ },
404
+ DB00004: {
405
+ features: all.features([
406
+ connection.sender.key,
407
+ organization.advertisements.key,
408
+ organization.analytics.key,
409
+ organization.members.key,
410
+ organization.subdomain.key,
411
+ page.slug.key
412
+ ]),
413
+ limits: all.limits({ actions: 4e4, members: 10, storage: gigabyte * 50 }),
414
+ marketing: {
415
+ description: "Accelerate acquisition with more power and flexibility.",
416
+ features: [
417
+ "Analytics",
418
+ "Custom subdomain / URLs",
419
+ "Confirmation page ads"
420
+ ],
421
+ limits: [
422
+ ["Actions per month", "40,000"],
423
+ ["Affiliates", "Unlimited"],
424
+ ["Brands", "Unlimited"],
425
+ ["Campaigns", "Unlimited"],
426
+ ["Pages", "Unlimited"],
427
+ ["Members", "10"],
428
+ ["Storage", "50GB"]
429
+ ]
430
+ },
431
+ ...overage(1.85),
432
+ title: "Premium",
433
+ conversion: 1
434
+ },
435
+ DB00005: {
436
+ features: all.features([
437
+ connection.sender.key,
438
+ organization.advertisements.key,
439
+ organization.analytics.key,
440
+ organization.members.key,
441
+ organization.subdomain.key,
442
+ page.slug.key
443
+ ]),
444
+ limits: all.limits({ actions: 1e5, members: infinite, storage: gigabyte * 100 }),
445
+ marketing: {
446
+ description: "Built for brands focused on results.",
447
+ features: [
448
+ "Analytics",
449
+ "Custom subdomain / URLs",
450
+ "Confirmation page ads"
451
+ ],
452
+ limits: [
453
+ ["Actions per month", "100,000"],
454
+ ["Affiliates", "Unlimited"],
455
+ ["Brands", "Unlimited"],
456
+ ["Campaigns", "Unlimited"],
457
+ ["Pages", "Unlimited"],
458
+ ["Members", "Unlimited"],
459
+ ["Storage", "100GB"]
460
+ ]
461
+ },
462
+ ...overage(1.5),
463
+ title: "Elite",
464
+ conversion: 0.5
465
+ }
466
+ };
467
+ var resolvePlan = (subscription) => {
468
+ var _a, _b;
469
+ const custom = subscription == null ? void 0 : subscription.custom;
470
+ if (!custom) return plans[subscription == null ? void 0 : subscription.plan] ?? free;
471
+ return {
472
+ // Reusing all.features / all.limits is what keeps a custom plan the same
473
+ // SHAPE as a catalog one: the base feature grants every plan carries, the
474
+ // campaign limits that are always infinite, and members defaulting to
475
+ // infinite when a deal does not name it.
476
+ conversion: custom.conversion ?? free.conversion,
477
+ custom: true,
478
+ // A custom plan is a negotiated PAID deal, so it carries the paid-tier
479
+ // baseline whether or not the deal thought to name it. Today that is the
480
+ // sending domain: every catalog paid tier grants it, and a custom plan
481
+ // silently lacking it would be a support ticket, not a pricing decision.
482
+ features: all.features([connection.sender.key, ...((_a = custom.features) == null ? void 0 : _a.granted) || []]),
483
+ limits: all.limits(((_b = custom.limits) == null ? void 0 : _b.organization) || {}),
484
+ // A custom plan stores its overage BARE on `custom.overages` — a different
485
+ // shape from the catalog's nested one. Number() so a deal stored as a string
486
+ // still resolves to cents-per-action; an unnamed overage stays undefined
487
+ // (it bills nothing) rather than becoming NaN.
488
+ actionCents: custom.overages == null ? void 0 : Number(custom.overages),
489
+ overages: { actions: custom.overages },
490
+ title: custom.title || "Custom"
491
+ };
492
+ };
493
+ var conversionRate = (subscription) => {
494
+ var _a;
495
+ return ((_a = resolvePlan(subscription)) == null ? void 0 : _a.conversion) ?? free.conversion;
496
+ };
497
+
498
+ // lib/transactions.js
499
+ var import_drawbridge_telemetry = require("@drawbridge/drawbridge-telemetry");
500
+ var insertTransaction = async ({
501
+ db,
502
+ user,
503
+ type,
504
+ category,
505
+ source,
506
+ amount,
507
+ _id,
508
+ stripeInvoiceId,
509
+ stripeEventId,
510
+ session,
511
+ ...rest
512
+ }) => {
513
+ const trace = (0, import_drawbridge_telemetry.currentTraceId)();
514
+ await db.create({
515
+ authenticated: user,
516
+ collection: "transaction",
517
+ data: {
518
+ ..._id && { _id },
519
+ user: user == null ? void 0 : user.id,
520
+ type,
521
+ category,
522
+ source,
523
+ amount,
524
+ ...trace && { trace },
525
+ ...rest,
526
+ ...stripeInvoiceId && { stripeInvoiceId },
527
+ ...stripeEventId && { stripeEventId }
528
+ },
529
+ ...session && { options: { session } }
530
+ });
531
+ };
532
+ var debit = async ({
533
+ db,
534
+ user,
535
+ amount,
536
+ type,
537
+ category,
538
+ source,
539
+ stripeInvoiceId,
540
+ stripeEventId,
541
+ session,
542
+ ...rest
543
+ }) => {
544
+ if (!Number.isInteger(amount) || amount <= 0) {
545
+ throw new Error(`debit() requires a positive integer amount, got ${amount}`);
546
+ }
547
+ if (!type) {
548
+ throw new Error('debit() requires a type (e.g., "ai")');
549
+ }
550
+ if (!source) {
551
+ throw new Error('debit() requires a source ("system" | "admin" | "user")');
552
+ }
553
+ await insertTransaction({
554
+ db,
555
+ user,
556
+ type,
557
+ category,
558
+ source,
559
+ amount: -amount,
560
+ stripeInvoiceId,
561
+ stripeEventId,
562
+ session,
563
+ ...rest
564
+ });
565
+ };
566
+
567
+ // lib/billing.js
568
+ var import_drawbridge_telemetry2 = require("@drawbridge/drawbridge-telemetry");
569
+ var logger = (0, import_drawbridge_telemetry2.createLogger)();
570
+ var MARKUP = 1.3;
571
+ var cost = {
572
+ // gemini-3.5-flash — verified against Google's pricing page 2026-07-09:
573
+ // $0.15 cached / $1.50 input / $9.00 output per 1M tokens (thinking billed at
574
+ // output). ~3.6x the retired 2.5-flash output rate.
575
+ "gemini-3.5-flash": {
576
+ cached: 15,
577
+ input: 150,
578
+ output: 900
579
+ },
580
+ // gemini-3.5-flash-lite — verified against Google's pricing page 2026-08-20:
581
+ // $0.03 cached / $0.30 input / $2.50 output per 1M tokens (thinking billed at
582
+ // output). A fifth of flash on input, ~a quarter on output. Growth's assistant
583
+ // ranks the feed on this tier — one call per page — so its rows were the
584
+ // unpriced ones until now.
585
+ "gemini-3.5-flash-lite": {
586
+ cached: 3,
587
+ input: 30,
588
+ output: 250
589
+ },
590
+ "gemini-2.5-flash": {
591
+ cached: 3,
592
+ input: 30,
593
+ output: 250
594
+ },
595
+ "gemini-2.5-flash-image": {
596
+ cached: 3,
597
+ input: 30,
598
+ output: 3e3
599
+ },
600
+ // gemini-3-pro-image-preview — verified against Google's pricing page
601
+ // 2026-08-12: $2.00 input / $12.00 text output per 1M, and image output
602
+ // tokens at ~$120/1M (a 1K-2K image is 1120 tokens = $0.134, a 4K image
603
+ // 2000 tokens = $0.24). Encoded the flash-image way: one flat output rate
604
+ // that reproduces the per-image price from the tokens usageMetadata
605
+ // reports. Growth's hero generation runs this model today.
606
+ "gemini-3-pro-image-preview": {
607
+ cached: 20,
608
+ input: 200,
609
+ output: 12e3
610
+ }
611
+ };
612
+ var toolCost = {
613
+ search: 3.5
614
+ };
615
+ var toolPricing = Object.fromEntries(
616
+ Object.entries(toolCost).map(([tool, value]) => [
617
+ tool,
618
+ Math.ceil(value * MARKUP)
619
+ ])
620
+ );
621
+ var pricing = Object.fromEntries(
622
+ Object.entries(cost).map(([model, rates]) => [
623
+ model,
624
+ {
625
+ cached: Math.round(rates.cached * MARKUP),
626
+ input: Math.round(rates.input * MARKUP),
627
+ output: Math.round(rates.output * MARKUP)
628
+ }
629
+ ])
630
+ );
631
+ var sumCents = (rates, tokens) => Math.ceil(
632
+ (Number((tokens == null ? void 0 : tokens.cached) || 0) * rates.cached + Number((tokens == null ? void 0 : tokens.input) || 0) * rates.input + (Number((tokens == null ? void 0 : tokens.output) || 0) + Number((tokens == null ? void 0 : tokens.thinking) || 0)) * rates.output) / 1e6
633
+ );
634
+ var sumToolCents = (table, tools) => Object.entries(tools || {}).reduce(
635
+ (total, [name, used]) => total + (used && table[name] ? table[name] : 0),
636
+ 0
637
+ );
638
+ var priceForRequest = (model, usage, tools) => {
639
+ const rates = pricing[model];
640
+ if (!rates) {
641
+ throw new Error(`Unknown model for pricing: ${model}`);
642
+ }
643
+ return sumCents(rates, usage) + Math.ceil(sumToolCents(toolPricing, tools));
644
+ };
645
+ var costForRequest = (model, usage, tools) => {
646
+ const rates = cost[model];
647
+ if (!rates) {
648
+ throw new Error(`Unknown model for cost: ${model}`);
649
+ }
650
+ return sumCents(rates, usage) + Math.ceil(sumToolCents(toolCost, tools));
651
+ };
652
+ var billRequest = async ({ db, user, model, usage, tools }) => {
653
+ const gross = priceForRequest(model, usage, tools);
654
+ const cogs = costForRequest(model, usage, tools);
655
+ await debit({
656
+ db,
657
+ user,
658
+ amount: gross,
659
+ type: "ai",
660
+ category: "usage",
661
+ source: "user",
662
+ ai: {
663
+ name: "google",
664
+ model,
665
+ tokens: usage,
666
+ tools,
667
+ rates: {
668
+ wholesale: cost[model],
669
+ retail: pricing[model]
670
+ },
671
+ totals: {
672
+ cost: cogs,
673
+ net: gross - cogs,
674
+ gross
675
+ }
676
+ }
677
+ });
678
+ };
679
+ var ai = {
680
+ // The rate tables themselves, in cents per 1,000,000 tokens (`tools` in cents
681
+ // per request). Read-only surface for lib/pricing.js — the fee math above is
682
+ // still the only thing that should compute from them.
683
+ rates: { wholesale: cost, retail: pricing, tools: { wholesale: toolCost, retail: toolPricing } },
684
+ // Retail cents for a request (what the user pays).
685
+ price: priceForRequest,
686
+ // Wholesale cents for a request (what we pay the provider).
687
+ cost: costForRequest,
688
+ // Deferred bill() the caller fires on success, so the debit lands only when
689
+ // the request succeeds and bundles into that request's Sentry trace. No user
690
+ // → a no-op.
691
+ bill: ({ db, user, model, usage, tools }) => (user == null ? void 0 : user.id) ? () => billRequest({ db, user, model, usage, tools }) : () => Promise.resolve()
692
+ };
693
+ var STANDARD_RATE_PER_GB = 8;
694
+ var PREMIUM_RATE_PER_GB = 11;
695
+ var STANDARD_CPM_CENTS = 0.15;
696
+ var PREMIUM_CPM_CENTS = 0.25;
697
+ var PREMIUM_HOSTS = /* @__PURE__ */ new Set();
698
+ var LOCAL_FLAT_CENTS = 1;
699
+ var REUSE_FLAT_CENTS = 1;
700
+ var isPremium = (url) => {
701
+ try {
702
+ return PREMIUM_HOSTS.has(new URL(url).hostname);
703
+ } catch {
704
+ return false;
705
+ }
706
+ };
707
+ var ratePerGB = (url) => isPremium(url) ? PREMIUM_RATE_PER_GB : STANDARD_RATE_PER_GB;
708
+ var cpmCents = (url) => isPremium(url) ? PREMIUM_CPM_CENTS : STANDARD_CPM_CENTS;
709
+ var scrapeFee = ({ provider, bytes, requests, url, cold }) => {
710
+ if (!cold) return REUSE_FLAT_CENTS;
711
+ if (provider === "brightdata") {
712
+ return Math.ceil((bytes || 0) / 1e9 * ratePerGB(url) * 100 * MARKUP);
713
+ }
714
+ if (provider === "brightdata-unlocker") {
715
+ return Math.ceil((requests || 0) * cpmCents(url) * MARKUP);
716
+ }
717
+ return LOCAL_FLAT_CENTS;
718
+ };
719
+ var scrapeBreakdown = ({ provider, bytes, requests, url }) => {
720
+ if (provider === "brightdata") {
721
+ return {
722
+ provider,
723
+ basis: "bytes",
724
+ units: bytes || 0,
725
+ rate: ratePerGB(url),
726
+ rateUnit: "GB",
727
+ cents: scrapeFee({ provider, bytes, url, cold: true })
728
+ };
729
+ }
730
+ if (provider === "brightdata-unlocker") {
731
+ return {
732
+ provider,
733
+ basis: "requests",
734
+ units: requests || 0,
735
+ // cpmCents is cents-per-request; ×10 expresses it as dollars per 1,000.
736
+ rate: cpmCents(url) * 10,
737
+ rateUnit: "1K requests",
738
+ cents: scrapeFee({ provider, requests, url, cold: true })
739
+ };
740
+ }
741
+ return { provider: provider || "local", basis: "local", units: null, rate: null, rateUnit: null, cents: LOCAL_FLAT_CENTS };
742
+ };
743
+ var scrape = {
744
+ // Cents for a scrape given its provider/bytes/cold basis.
745
+ fee: scrapeFee,
746
+ // Itemized cold-fee breakdown (basis/units/rate/cents) for display + the scrape doc.
747
+ breakdown: scrapeBreakdown,
748
+ // Deferred bill(scrapeId) the scrape store's resolve() hands the generation
749
+ // flow. Atomically claims the cold (first-time) fee via the `charged` flag so
750
+ // a BrightData scrape's metered cost is recovered ONCE; later reuses pay the
751
+ // flat rate. Best-effort — a billing hiccup never fails generation.
752
+ bill: ({ controller, user, page: page2, url }) => async (scrapeId) => {
753
+ var _a;
754
+ if (!(user == null ? void 0 : user.id) || !scrapeId) return;
755
+ try {
756
+ const claim = await controller.update({
757
+ collection: "scrape",
758
+ data: { $set: { charged: true } },
759
+ options: { bypassDocumentValidation: true },
760
+ query: { id: scrapeId, charged: { $ne: true } }
761
+ });
762
+ const cents = scrapeFee({
763
+ provider: (_a = page2 == null ? void 0 : page2.provider) == null ? void 0 : _a.name,
764
+ bytes: page2 == null ? void 0 : page2.bytes,
765
+ requests: page2 == null ? void 0 : page2.requests,
766
+ url: (page2 == null ? void 0 : page2.url) || url,
767
+ cold: Boolean(claim == null ? void 0 : claim.value)
768
+ });
769
+ if (cents > 0) await debit({ db: controller, user, amount: cents, type: "ai", category: "usage", source: "user" });
770
+ } catch (error) {
771
+ logger.error(error, { extra: { action: "generation.scrape.bill", scrapeId } });
772
+ }
773
+ }
774
+ };
775
+
776
+ // lib/pricing.js
777
+ var channels = {
778
+ email: {
779
+ actionsPerSend: 1,
780
+ includedInAllowance: true
781
+ },
782
+ sms: {
783
+ // Two actions PER SEGMENT (a long message is several segments), billed from
784
+ // the FIRST segment and never drawn from the plan's included allowance —
785
+ // carrier cost is real from message one, so there is no free tier of it.
786
+ actionsPerSegment: 2,
787
+ includedInAllowance: false
788
+ }
789
+ };
790
+ // Annotate the CommonJS export names for ESM import in node:
791
+ 0 && (module.exports = {
792
+ LOCAL_FLAT_CENTS,
793
+ MARKUP,
794
+ PREMIUM_CPM_CENTS,
795
+ PREMIUM_RATE_PER_GB,
796
+ REUSE_FLAT_CENTS,
797
+ STANDARD_CPM_CENTS,
798
+ STANDARD_RATE_PER_GB,
799
+ ai,
800
+ channels,
801
+ conversionRate,
802
+ free,
803
+ plans,
804
+ resolvePlan,
805
+ scrape,
806
+ unitAmountDecimal
807
+ });