@stewardhq/sdk 0.1.0-rc.0 → 0.3.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/dist/index.js CHANGED
@@ -1,62 +1,8 @@
1
- import { A as CodeSchema, B as IntervalSchema, C as BillingProfileSchema, D as API_VERSION, E as SubscriptionSummarySchema, F as EntitlementsSchema, I as ErrorCategorySchema, L as ErrorResponseSchema, M as DateTimeSchema, N as ERROR_CATEGORIES, O as ActorRefSchema, P as EntitlementValueSchema, R as ExternalRefSchema, S as BillingProfileKindSchema, T as SubscriptionStatusSchema, V as MetadataSchema, _ as AccountScheduledChangeSchema, a as EVENT_TYPES, b as AccountSubscriptionStateSchema, c as PING_EVENT_TYPE, d as ACCOUNT_INCLUDES, f as AccessStateSchema, g as AccountProfileStateSchema, h as AccountOpenCheckoutSchema, i as EVENT_DETAIL_SCHEMAS, j as CurrencySchema, k as AmountMinorSchema, l as PingSchema, m as AccountDunningStateSchema, n as ApiVersionSchema, o as EventIdSchema, p as AccountDeleteResponseSchema, r as BillingEventSchema, s as LEGACY_EVENT_TYPES, t as AnyBillingEventSchema, u as isEventType, v as AccountSchema, w as EntitlementSnapshotSchema, x as AccountUpsertInputSchema, y as AccountStateSchema, z as IdSchema } from "./_chunks/events.js";
2
- import { $ as HEADER_SDK, $t as FeatureTypeSchema, A as webhookEndpointUrlProblem, At as MAX_CHECKOUT_CONSENT_DOCS, B as AccountDetailSchema, Bt as ReturnOriginSchema, C as WebhookEndpointListSchema, Ct as CheckoutConsentInputSchema, D as WebhookLastDeliverySchema, Dt as CheckoutSessionSchema, E as WebhookEndpointStatusSchema, Et as CheckoutSessionCreatedSchema, F as PlanSetWarningSchema, Ft as BrandingSchema, G as DeliverySchema, Gt as applySettingsPatch, H as BillingProfileResponseSchema, Ht as SettingsLocaleSchema, I as ResyncResultSchema, It as DEFAULT_CHECKOUT_TTL_MINUTES, J as GrantCreateResponseSchema, Jt as AccountsRefreshResultSchema, K as EventListSchema, Kt as isReturnUrlAllowed, L as ERROR_CODES, Lt as DEFAULT_PORTAL_TTL_MINUTES, M as PlanSetInputSchema, Mt as checkoutRedirectUrl, N as PlanSetModeSchema, Nt as isLegacyCheckoutInput, O as WebhookSecretSchema, Ot as CheckoutStatusSchema, P as PlanSetResponseSchema, Pt as BrandingPatchSchema, Q as HEADER_REQUEST_ID, Qt as FeatureDefSchema, R as errorCodeSpec, Rt as ProductSettingsPatchSchema, S as WebhookEndpointCreateInputSchema, St as CHECKOUT_ERRORS, T as WebhookEndpointSchema, Tt as CheckoutSessionCreateInputSchema, U as CancelSubscriptionResponseSchema, Ut as TtlMinutesSchema, V as AccountUpsertResponseSchema, Vt as SETTINGS_LOCALES, W as CheckoutSessionResponseSchema, Wt as WebUrlSchema, X as HEADER_API_VERSION, Xt as CatalogSyncInputSchema, Y as HEADER_ACTOR_REF, Yt as CatalogSchema, Z as HEADER_IDEMPOTENCY_KEY, Zt as CatalogSyncResultSchema, _ as hostedReadinessOf, _t as StatsSchema, a as DOCTOR_SEVERITIES, at as InvoiceSchema, b as WEBHOOK_ENDPOINT_STATUSES, bt as PortalSessionCreateInputSchema, c as DoctorHostedSchema, ct as MANUAL_INVOICE_MAX_AMOUNT_MINOR, d as DoctorSettingsSchema, dt as manualInvoiceTotals, en as PlanDefSchema, et as InvoiceIssueResponseSchema, f as DoctorSeveritySchema, ft as splitInclusiveTax, g as endpointDiagnosisOf, gt as PaymentSchema, h as buildDoctorReport, ht as GrantSchema, i as DOCTOR_REQUIRED_LEGAL_LINKS, it as InvoiceLineSchema, j as PLAN_SET_MODES, jt as ProviderPayloadSchema, k as generateWebhookSecret, kt as ConsentSchema, l as DoctorProviderSchema, lt as ManualInvoiceInputSchema, m as DoctorWarningSchema, mt as GrantCreateInputSchema, n as DOCTOR_PROVIDER_ENVIRONMENTS, nn as PriceSchema, nt as ManualInvoiceResponseSchema, o as DoctorCatalogSchema, ot as InvoiceStatusSchema, p as DoctorUnsellablePriceSchema, pt as CancelSubscriptionInputSchema, q as EventRecordSchema, qt as returnOriginsOf, r as DOCTOR_REQUIRED_BRANDING, rt as InvoiceIssueInputSchema, s as DoctorEndpointSchema, st as InvoiceVoidInputSchema, t as DOCTOR_PENDING_BACKLOG_MS, tn as PriceDefSchema, tt as InvoiceVoidResponseSchema, u as DoctorReportSchema, ut as ManualInvoiceLineInputSchema, v as DEFAULT_ENDPOINT_EVENT_TYPES, vt as SubscriptionSchema, w as WebhookEndpointRotateInputSchema, wt as CheckoutPrefillSchema, x as WEBHOOK_SECRET_PREFIX, xt as PortalSessionSchema, y as EventTypeSchema, yt as PORTAL_SESSION_ERRORS, z as isKnownErrorCode, zt as ProductSettingsSchema } from "./_chunks/src.js";
1
+ import { $ as CurrencySchema, A as EMAIL_LOCALES, B as NotificationEmailsSchema, C as BillingProfileKindSchema, D as SubscriptionSummarySchema, E as SubscriptionStatusSchema, F as EmailSettingsPatchSchema, G as emailTemplateOf, H as billingPageUrl, I as EmailSettingsSchema, J as uniqueEmails, K as emailTemplateSettings, L as EmailTemplateSchema, M as EMAIL_TEMPLATE_BY_EVENT, N as EmailExtraTextSchema, O as BILLING_PATH_PLACEHOLDERS, P as EmailSenderSchema, Q as CodeSchema, R as EmailTemplateSettingsSchema, S as AccountUpsertInputSchema, T as EntitlementSnapshotSchema, U as emailLocaleOf, V as applyEmailSettingsPatch, W as emailRecipients, X as ActorRefSchema, Y as API_VERSION, Z as AmountMinorSchema, _ as AccountProfileStateSchema, a as EVENT_TYPES, at as ErrorResponseSchema, b as AccountStateSchema, c as PING_EVENT_TYPE, ct as IntervalSchema, d as ACCOUNT_INCLUDES, et as DateTimeSchema, f as AccessStateSchema, g as AccountOpenCheckoutSchema, h as AccountLocaleSchema, i as EVENT_DETAIL_SCHEMAS, it as ErrorCategorySchema, j as EMAIL_TEMPLATES, k as BillingPathSchema, l as PingSchema, lt as MetadataSchema, m as AccountDunningStateSchema, n as ApiVersionSchema, nt as EntitlementValueSchema, o as EventIdSchema, ot as ExternalRefSchema, p as AccountDeleteResponseSchema, q as isEmailRelevant, r as BillingEventSchema, rt as EntitlementsSchema, s as LEGACY_EVENT_TYPES, st as IdSchema, t as AnyBillingEventSchema, tt as ERROR_CATEGORIES, u as isEventType, v as AccountScheduledChangeSchema, w as BillingProfileSchema, x as AccountSubscriptionStateSchema, y as AccountSchema, z as MAX_NOTIFICATION_EMAILS } from "./_chunks/events.js";
2
+ import { $ as InvoiceVoidResponseSchema, $t as PriceSchema, A as WebhookSecretSchema, At as checkoutRedirectUrl, B as errorCodeSpec, Bt as TtlMinutesSchema, C as WEBHOOK_SECRET_PREFIX, Ct as CheckoutSessionCreateInputSchema, D as WebhookEndpointSchema, Dt as ConsentSchema, E as WebhookEndpointRotateInputSchema, Et as CheckoutStatusSchema, F as PlanSetModeSchema, Ft as ProductSettingsPatchSchema, G as CheckoutSessionResponseSchema, Gt as AccountsRefreshResultSchema, H as AccountDetailSchema, Ht as applySettingsPatch, I as PlanSetResponseSchema, It as ProductSettingsSchema, J as HEADER_API_VERSION, Jt as CatalogSyncResultSchema, K as GrantCreateResponseSchema, Kt as CatalogSchema, L as PlanSetWarningSchema, Lt as ReturnOriginSchema, M as webhookEndpointUrlProblem, Mt as BrandingSchema, N as PLAN_SET_MODES, Nt as DEFAULT_CHECKOUT_TTL_MINUTES, O as WebhookEndpointStatusSchema, Ot as MAX_CHECKOUT_CONSENT_DOCS, P as PlanSetInputSchema, Pt as DEFAULT_PORTAL_TTL_MINUTES, Q as InvoiceIssueResponseSchema, Qt as PriceDefSchema, R as ResyncResultSchema, Rt as SETTINGS_LOCALES, S as WEBHOOK_ENDPOINT_STATUSES, St as CheckoutPrefillSchema, T as WebhookEndpointListSchema, Tt as CheckoutSessionSchema, U as AccountUpsertResponseSchema, Ut as isReturnUrlAllowed, V as isKnownErrorCode, Vt as WebUrlSchema, W as CancelSubscriptionResponseSchema, Wt as returnOriginsOf, X as HEADER_REQUEST_ID, Xt as FeatureTypeSchema, Y as HEADER_IDEMPOTENCY_KEY, Yt as FeatureDefSchema, Z as HEADER_SDK, Zt as PlanDefSchema, _ as emailReadinessOf, _t as PORTAL_SESSION_ERRORS, a as DOCTOR_SEVERITIES, at as InvoiceVoidInputSchema, b as DEFAULT_ENDPOINT_EVENT_TYPES, bt as CHECKOUT_ERRORS, c as DoctorEndpointSchema, ct as ManualInvoiceLineInputSchema, d as DoctorReportSchema, dt as CancelSubscriptionInputSchema, et as ManualInvoiceResponseSchema, f as DoctorSettingsSchema, ft as GrantCreateInputSchema, g as buildDoctorReport, gt as SubscriptionSchema, h as DoctorWarningSchema, ht as StatsSchema, i as DOCTOR_REQUIRED_LEGAL_LINKS, it as InvoiceStatusSchema, j as generateWebhookSecret, jt as BrandingPatchSchema, k as WebhookLastDeliverySchema, kt as ProviderPayloadSchema, l as DoctorHostedSchema, lt as manualInvoiceTotals, m as DoctorUnsellablePriceSchema, mt as PaymentSchema, n as DOCTOR_PROVIDER_ENVIRONMENTS, nt as InvoiceLineSchema, o as DoctorCatalogSchema, ot as MANUAL_INVOICE_MAX_AMOUNT_MINOR, p as DoctorSeveritySchema, pt as GrantSchema, q as HEADER_ACTOR_REF, qt as CatalogSyncInputSchema, r as DOCTOR_REQUIRED_BRANDING, rt as InvoiceSchema, s as DoctorEmailsSchema, st as ManualInvoiceInputSchema, t as DOCTOR_PENDING_BACKLOG_MS, tt as InvoiceIssueInputSchema, u as DoctorProviderSchema, ut as splitInclusiveTax, v as endpointDiagnosisOf, vt as PortalSessionCreateInputSchema, w as WebhookEndpointCreateInputSchema, wt as CheckoutSessionCreatedSchema, x as EventTypeSchema, xt as CheckoutConsentInputSchema, y as hostedReadinessOf, yt as PortalSessionSchema, z as ERROR_CODES, zt as SettingsLocaleSchema } from "./_chunks/src.js";
3
3
  import { a as isGrantActive, i as LIVE_SUBSCRIPTION_STATUSES, n as isValidTckn, o as isLiveSubscriptionStatus, r as isValidVkn, s as resolveEntitlements, t as isE164 } from "./_chunks/validators.js";
4
- import { n as createBillingClient, r as parseRetryAfter, t as createSteward } from "./_chunks/steward.js";
4
+ import { t as createSteward } from "./_chunks/steward.js";
5
5
  import { a as StewardNetworkError, i as StewardError, n as StewardConfigError, r as StewardContractError, t as StewardApiError } from "./_chunks/errors.js";
6
- import { n as localeOf } from "./_chunks/locale.js";
7
- //#region src/catalog-cache.ts
8
- function createCatalogCache(steward, options = {}) {
9
- const ttlMs = options.ttlMs ?? 6e4;
10
- if (!Number.isFinite(ttlMs) || ttlMs < 0) throw new StewardConfigError({ message: `createCatalogCache: ttlMs negatif olmayan sayı olmalı: ${ttlMs}` });
11
- const logger = options.logger ?? console;
12
- let entry = null;
13
- let inflight = null;
14
- async function refresh() {
15
- const previous = entry;
16
- try {
17
- const read = await steward.catalog.read(previous?.etag ? { etag: previous.etag } : {});
18
- let next;
19
- if (!read.notModified) next = {
20
- catalog: read.catalog,
21
- etag: read.etag,
22
- fetchedAt: Date.now()
23
- };
24
- else if (previous !== null) next = {
25
- ...previous,
26
- etag: read.etag,
27
- fetchedAt: Date.now()
28
- };
29
- else throw new StewardContractError({ httpStatus: 304 });
30
- entry = next;
31
- return next.catalog;
32
- } catch (error) {
33
- if (previous === null) throw error;
34
- const { code, requestId } = typeof error === "object" && error !== null ? error : {};
35
- logger.warn("steward katalogu tazelenemedi; bayat değer kullanılıyor", {
36
- code: typeof code === "string" ? code : null,
37
- requestId: typeof requestId === "string" ? requestId : null,
38
- ageMs: Date.now() - previous.fetchedAt
39
- });
40
- return previous.catalog;
41
- }
42
- }
43
- return {
44
- get() {
45
- if (entry !== null && Date.now() - entry.fetchedAt < ttlMs) return Promise.resolve(entry.catalog);
46
- inflight ??= refresh().finally(() => {
47
- inflight = null;
48
- });
49
- return inflight;
50
- },
51
- invalidate() {
52
- if (entry !== null) entry = {
53
- ...entry,
54
- fetchedAt: Number.NEGATIVE_INFINITY
55
- };
56
- }
57
- };
58
- }
59
- //#endregion
60
6
  //#region src/state-cache.ts
61
7
  const MANY_CONCURRENCY = 8;
62
8
  const FAILURE_BACKOFF_MS = 5e3;
@@ -410,148 +356,6 @@ function httpStatusFor(err, options = {}) {
410
356
  };
411
357
  }
412
358
  //#endregion
413
- //#region src/messages.ts
414
- /** SDK'nın kendisinin ürettiği kodlar (yanıt yok ya da istek hiç gönderilmedi). */
415
- const CLIENT_ERROR_CODES = [
416
- "network_error",
417
- "timeout",
418
- "invalid_response",
419
- "config_error"
420
- ];
421
- const STEWARD_ERROR_CODES = Object.freeze([...Object.keys(ERROR_CODES), ...CLIENT_ERROR_CODES]);
422
- const TR_CONFIG = "Ödeme sistemi yapılandırmasında bir sorun var. Lütfen destekle iletişime geçin.";
423
- const TR_RETRY = "İstek işlenemedi. Lütfen tekrar deneyin.";
424
- const TR_LATER = "Ödeme sistemi şu anda kullanılamıyor. Lütfen biraz sonra tekrar deneyin.";
425
- const EN_CONFIG = "There is a problem with the billing configuration. Please contact support.";
426
- const EN_RETRY = "The request could not be processed. Please try again.";
427
- const errorMessages = {
428
- tr: {
429
- unauthorized: TR_CONFIG,
430
- forbidden: TR_CONFIG,
431
- invalid_actor_ref: TR_RETRY,
432
- actor_ref_required: TR_RETRY,
433
- idempotency_key_required: TR_RETRY,
434
- invalid_idempotency_key: TR_RETRY,
435
- idempotency_key_reused: "Bu istek daha önce farklı bilgilerle gönderildi. Sayfayı yenileyip tekrar deneyin.",
436
- request_in_progress: "Aynı işlem şu anda sürüyor. Birkaç saniye sonra tekrar deneyin.",
437
- invalid_json: TR_RETRY,
438
- invalid_request: "Gönderilen bilgiler geçersiz. Lütfen kontrol edip tekrar deneyin.",
439
- invalid_account_ref: "Hesap bilgisi geçersiz.",
440
- invalid_include: TR_RETRY,
441
- invalid_cursor: TR_RETRY,
442
- invalid_limit: TR_RETRY,
443
- not_found: "Kayıt bulunamadı.",
444
- account_not_found: "Faturalandırma hesabı bulunamadı.",
445
- account_deleted: "Faturalandırma hesabı silinmiş.",
446
- subscription_active: "Hesabın etkin bir aboneliği var; önce aboneliği iptal edin.",
447
- checkout_in_progress: "Hesapta süren bir ödeme işlemi var. Lütfen daha sonra tekrar deneyin.",
448
- checkout_session_not_found: "Ödeme oturumu bulunamadı.",
449
- subscription_not_found: "Abonelik bulunamadı.",
450
- invoice_not_found: "Fatura bulunamadı.",
451
- document_not_found: "Fatura belgesi bulunamadı.",
452
- grant_not_found: "Tanımlı plan hakkı bulunamadı.",
453
- event_not_found: "Kayıt bulunamadı.",
454
- webhook_endpoint_not_found: "Kayıt bulunamadı.",
455
- plan_not_found: "Plan bulunamadı.",
456
- catalog_not_configured: "Planlar henüz tanımlanmadı. Lütfen daha sonra tekrar deneyin.",
457
- already_subscribed: "Bu hesabın zaten etkin bir aboneliği var.",
458
- plan_not_sellable: "Bu plan satın alınamıyor.",
459
- return_url_not_allowed: TR_CONFIG,
460
- provider_not_configured: "Şu anda ödeme alınamıyor. Lütfen daha sonra tekrar deneyin.",
461
- provider_error: "Ödeme sağlayıcısında bir sorun oluştu. Lütfen biraz sonra tekrar deneyin.",
462
- already_canceled: "Abonelik zaten iptal edilmiş.",
463
- subscription_plan_higher: "Hesabın etkin aboneliği bu plandan daha yüksek bir planda.",
464
- override_type_mismatch: "Hak değeri, özelliğin türüyle uyuşmuyor.",
465
- invalid_window: "Bitiş tarihi başlangıçtan sonra olmalı.",
466
- plan_missing_feature: "Katalogdaki bir plan, özelliklerden birine değer vermiyor.",
467
- already_issued: "Bu fatura zaten kesilmiş.",
468
- number_taken: "Bu fatura numarası başka bir faturada kullanılıyor.",
469
- invalid_document: "Fatura belgesi geçersiz: en fazla 5 MB PDF yükleyin.",
470
- billing_profile_required: "Fatura için önce hesabın fatura bilgileri girilmeli.",
471
- invoice_not_voidable: "Bu fatura zaten iptal edilmiş.",
472
- invoice_has_payment: "Ödemesi alınmış fatura iptal edilemez; iade süreci gerekir.",
473
- internal_error: "Ödeme sisteminde beklenmeyen bir hata oluştu. Lütfen daha sonra tekrar deneyin.",
474
- database_unavailable: TR_LATER,
475
- unknown_provider: TR_CONFIG,
476
- bad_signature: TR_CONFIG,
477
- invalid_payload: TR_RETRY,
478
- stale_event: TR_RETRY,
479
- not_configured: "Şu anda ödeme alınamıyor. Lütfen daha sonra tekrar deneyin.",
480
- unknown_subscription: "Abonelik bulunamadı.",
481
- network_error: "Ödeme sistemine ulaşılamadı. Lütfen biraz sonra tekrar deneyin.",
482
- timeout: "Ödeme sistemi zamanında yanıt vermedi. Lütfen biraz sonra tekrar deneyin.",
483
- rate_limited: "Şu anda çok fazla istek var. Lütfen birkaç saniye sonra tekrar deneyin.",
484
- invalid_response: "Ödeme sisteminden beklenmeyen bir yanıt alındı. Lütfen daha sonra tekrar deneyin.",
485
- config_error: TR_CONFIG,
486
- fallback: "Bir hata oluştu. Lütfen daha sonra tekrar deneyin."
487
- },
488
- en: {
489
- unauthorized: EN_CONFIG,
490
- forbidden: EN_CONFIG,
491
- invalid_actor_ref: EN_RETRY,
492
- actor_ref_required: EN_RETRY,
493
- idempotency_key_required: EN_RETRY,
494
- invalid_idempotency_key: EN_RETRY,
495
- idempotency_key_reused: "This request was already sent with different details. Refresh the page and try again.",
496
- request_in_progress: "The same operation is already in progress. Try again in a few seconds.",
497
- invalid_json: EN_RETRY,
498
- invalid_request: "Some of the details are invalid. Please check them and try again.",
499
- invalid_account_ref: "The account reference is invalid.",
500
- invalid_include: EN_RETRY,
501
- invalid_cursor: EN_RETRY,
502
- invalid_limit: EN_RETRY,
503
- not_found: "Not found.",
504
- account_not_found: "Billing account not found.",
505
- account_deleted: "The billing account has been deleted.",
506
- subscription_active: "The account has an active subscription; cancel it first.",
507
- checkout_in_progress: "A payment is in progress for this account. Please try again later.",
508
- checkout_session_not_found: "Checkout session not found.",
509
- subscription_not_found: "Subscription not found.",
510
- invoice_not_found: "Invoice not found.",
511
- document_not_found: "Invoice document not found.",
512
- grant_not_found: "Plan grant not found.",
513
- event_not_found: "Not found.",
514
- webhook_endpoint_not_found: "Not found.",
515
- plan_not_found: "Plan not found.",
516
- catalog_not_configured: "Plans are not set up yet. Please try again later.",
517
- already_subscribed: "This account already has an active subscription.",
518
- plan_not_sellable: "This plan cannot be purchased.",
519
- return_url_not_allowed: EN_CONFIG,
520
- provider_not_configured: "Payments are unavailable right now. Please try again later.",
521
- provider_error: "The payment provider ran into a problem. Please try again shortly.",
522
- already_canceled: "The subscription is already canceled.",
523
- subscription_plan_higher: "The account's active subscription is on a higher plan than this one.",
524
- override_type_mismatch: "The entitlement value does not match the feature type.",
525
- invalid_window: "The end date must be after the start date.",
526
- plan_missing_feature: "A plan in the catalog is missing a value for one of the features.",
527
- already_issued: "This invoice has already been issued.",
528
- number_taken: "This invoice number is already used by another invoice.",
529
- invalid_document: "Invalid invoice document: upload a PDF of at most 5 MB.",
530
- billing_profile_required: "Enter the account's billing details before creating an invoice.",
531
- invoice_not_voidable: "This invoice is already void.",
532
- invoice_has_payment: "A paid invoice cannot be voided; it requires a refund.",
533
- internal_error: "Billing ran into an unexpected error. Please try again later.",
534
- database_unavailable: "Billing is temporarily unavailable. Please try again shortly.",
535
- unknown_provider: EN_CONFIG,
536
- bad_signature: EN_CONFIG,
537
- invalid_payload: EN_RETRY,
538
- stale_event: EN_RETRY,
539
- not_configured: "Payments are unavailable right now. Please try again later.",
540
- unknown_subscription: "Subscription not found.",
541
- network_error: "Could not reach billing. Please try again shortly.",
542
- timeout: "Billing did not respond in time. Please try again shortly.",
543
- rate_limited: "Too many requests right now. Please try again in a few seconds.",
544
- invalid_response: "Billing returned an unexpected response. Please try again later.",
545
- config_error: EN_CONFIG,
546
- fallback: "Something went wrong. Please try again later."
547
- }
548
- };
549
- /** Kullanıcıya gösterilecek metin (`tr`, `tr-TR` → tr; diğer diller → en); tanınmayan kodda genel metin. */
550
- function messageFor(code, locale) {
551
- const messages = errorMessages[localeOf(locale)];
552
- return Object.hasOwn(messages, code) ? messages[code] : messages.fallback;
553
- }
554
- //#endregion
555
359
  //#region src/catalog.ts
556
360
  const feature = (type, options) => options?.description === void 0 ? { type } : {
557
361
  type,
@@ -714,71 +518,4 @@ function defineCatalog(definition) {
714
518
  });
715
519
  }
716
520
  //#endregion
717
- //#region src/money.ts
718
- function assertInteger(name, value) {
719
- if (!Number.isInteger(value) || value < 0) throw new RangeError(`${name} negatif olmayan tam sayı olmalı: ${value}`);
720
- }
721
- /**
722
- * Vergi dahil fiyatta toplam korunur, matrah kuruşa yuvarlanır ve vergi kalandır;
723
- * vergi hariç fiyatta vergi kuruşa yuvarlanıp üstüne eklenir.
724
- */
725
- function taxBreakdown(price) {
726
- const { amountMinor, taxRateBps } = price;
727
- assertInteger("amountMinor", amountMinor);
728
- assertInteger("taxRateBps", taxRateBps);
729
- if (price.taxInclusive) {
730
- const subtotalMinor = Math.round(amountMinor * 1e4 / (1e4 + taxRateBps));
731
- return {
732
- subtotalMinor,
733
- taxMinor: amountMinor - subtotalMinor,
734
- totalMinor: amountMinor
735
- };
736
- }
737
- const taxMinor = Math.round(amountMinor * taxRateBps / 1e4);
738
- return {
739
- subtotalMinor: amountMinor,
740
- taxMinor,
741
- totalMinor: amountMinor + taxMinor
742
- };
743
- }
744
- const TAX_LABEL = {
745
- tr: {
746
- inclusive: "KDV dahil",
747
- exclusive: "KDV hariç"
748
- },
749
- en: {
750
- inclusive: "VAT included",
751
- exclusive: "VAT excluded"
752
- }
753
- };
754
- /**
755
- * Tutar, para biriminin ondalık hanesiyle (TRY/USD 2, JPY 0): `₺1.250,00`
756
- * (tr), `₺1,250.00` (en). Sembol dar biçimde (`TRY 1,250.00` değil).
757
- */
758
- function formatMoney(amountMinor, currency, locale) {
759
- if (!Number.isInteger(amountMinor)) throw new RangeError(`amountMinor tam sayı olmalı: ${amountMinor}`);
760
- const digits = new Intl.NumberFormat("en", {
761
- style: "currency",
762
- currency
763
- }).resolvedOptions().maximumFractionDigits ?? 2;
764
- return new Intl.NumberFormat(locale, {
765
- style: "currency",
766
- currency,
767
- currencyDisplay: "narrowSymbol",
768
- minimumFractionDigits: digits,
769
- maximumFractionDigits: digits
770
- }).format(amountMinor / 10 ** digits);
771
- }
772
- /**
773
- * Fiyat etiketi: `₺1.250,00 · KDV dahil` (tr), `₺1,250.00 · VAT included` (en).
774
- * Vergi oranı 0 ise vergi ibaresi yazılmaz. Sayı biçimi `locale`'in kendisiyle,
775
- * ibare `tr*` → Türkçe, diğerleri İngilizce.
776
- */
777
- function formatPrice(price, locale) {
778
- const amount = formatMoney(price.amountMinor, price.currency, locale);
779
- if (price.taxRateBps === 0) return amount;
780
- const labels = TAX_LABEL[localeOf(locale)];
781
- return `${amount} · ${price.taxInclusive ? labels.inclusive : labels.exclusive}`;
782
- }
783
- //#endregion
784
- export { ACCOUNT_INCLUDES, API_VERSION, AccessStateSchema, AccountDeleteResponseSchema, AccountDetailSchema, AccountDunningStateSchema, AccountOpenCheckoutSchema, AccountProfileStateSchema, AccountScheduledChangeSchema, AccountSchema, AccountStateSchema, AccountSubscriptionStateSchema, AccountUpsertInputSchema, AccountUpsertResponseSchema, AccountsRefreshResultSchema, ActorRefSchema, AmountMinorSchema, AnyBillingEventSchema, ApiVersionSchema, BillingEventSchema, BillingProfileKindSchema, BillingProfileResponseSchema, BillingProfileSchema, BrandingPatchSchema, BrandingSchema, CHECKOUT_ERRORS, CancelSubscriptionInputSchema, CancelSubscriptionResponseSchema, CatalogSchema, CatalogSyncInputSchema, CatalogSyncResultSchema, CheckoutConsentInputSchema, CheckoutPrefillSchema, CheckoutSessionCreateInputSchema, CheckoutSessionCreatedSchema, CheckoutSessionResponseSchema, CheckoutSessionSchema, CheckoutStatusSchema, CodeSchema, ConsentSchema, CurrencySchema, DEFAULT_CHECKOUT_TTL_MINUTES, DEFAULT_ENDPOINT_EVENT_TYPES, DEFAULT_PORTAL_TTL_MINUTES, DOCTOR_PENDING_BACKLOG_MS, DOCTOR_PROVIDER_ENVIRONMENTS, DOCTOR_REQUIRED_BRANDING, DOCTOR_REQUIRED_LEGAL_LINKS, DOCTOR_SEVERITIES, DateTimeSchema, DeliverySchema, DoctorCatalogSchema, DoctorEndpointSchema, DoctorHostedSchema, DoctorProviderSchema, DoctorReportSchema, DoctorSettingsSchema, DoctorSeveritySchema, DoctorUnsellablePriceSchema, DoctorWarningSchema, ERROR_CATEGORIES, ERROR_CODES, EVENT_DETAIL_SCHEMAS, EVENT_TYPES, EntitlementSnapshotSchema, EntitlementValueSchema, EntitlementsSchema, ErrorCategorySchema, ErrorResponseSchema, EventIdSchema, EventListSchema, EventRecordSchema, EventTypeSchema, ExternalRefSchema, FeatureDefSchema, FeatureTypeSchema, GrantCreateInputSchema, GrantCreateResponseSchema, GrantSchema, HEADER_ACTOR_REF, HEADER_API_VERSION, HEADER_IDEMPOTENCY_KEY, HEADER_REQUEST_ID, HEADER_SDK, IdSchema, IntervalSchema, InvoiceIssueInputSchema, InvoiceIssueResponseSchema, InvoiceLineSchema, InvoiceSchema, InvoiceStatusSchema, InvoiceVoidInputSchema, InvoiceVoidResponseSchema, LEGACY_EVENT_TYPES, LIVE_SUBSCRIPTION_STATUSES, MANUAL_INVOICE_MAX_AMOUNT_MINOR, MAX_CHECKOUT_CONSENT_DOCS, ManualInvoiceInputSchema, ManualInvoiceLineInputSchema, ManualInvoiceResponseSchema, MetadataSchema, PING_EVENT_TYPE, PLAN_SET_MODES, PORTAL_SESSION_ERRORS, PaymentSchema, PingSchema, PlanDefSchema, PlanSetInputSchema, PlanSetModeSchema, PlanSetResponseSchema, PlanSetWarningSchema, PortalSessionCreateInputSchema, PortalSessionSchema, PriceDefSchema, PriceSchema, ProductSettingsPatchSchema, ProductSettingsSchema, ProviderPayloadSchema, ResyncResultSchema, ReturnOriginSchema, SETTINGS_LOCALES, STEWARD_ERROR_CODES, SettingsLocaleSchema, StatsSchema, StewardApiError, StewardConfigError, StewardContractError, StewardError, StewardNetworkError, SubscriptionSchema, SubscriptionStatusSchema, SubscriptionSummarySchema, TtlMinutesSchema, WEBHOOK_ENDPOINT_STATUSES, WEBHOOK_SECRET_PREFIX, WebUrlSchema, WebhookEndpointCreateInputSchema, WebhookEndpointListSchema, WebhookEndpointRotateInputSchema, WebhookEndpointSchema, WebhookEndpointStatusSchema, WebhookLastDeliverySchema, WebhookSecretSchema, applySettingsPatch, buildDoctorReport, checkoutRedirectUrl, createBillingClient, createCatalogCache, createSteward, defineCatalog, endpointDiagnosisOf, errorCodeSpec, errorMessages, flag, formatMoney, formatPrice, generateWebhookSecret, hostedReadinessOf, httpStatusFor, isE164, isEventType, isGrantActive, isKnownErrorCode, isLegacyCheckoutInput, isLiveSubscriptionStatus, isReturnUrlAllowed, isValidTckn, isValidVkn, limit, manualInvoiceTotals, messageFor, parseRetryAfter, resolveEntitlements, returnOriginsOf, splitInclusiveTax, stateCache, taxBreakdown, text, webhookEndpointUrlProblem };
521
+ export { ACCOUNT_INCLUDES, API_VERSION, AccessStateSchema, AccountDeleteResponseSchema, AccountDetailSchema, AccountDunningStateSchema, AccountLocaleSchema, AccountOpenCheckoutSchema, AccountProfileStateSchema, AccountScheduledChangeSchema, AccountSchema, AccountStateSchema, AccountSubscriptionStateSchema, AccountUpsertInputSchema, AccountUpsertResponseSchema, AccountsRefreshResultSchema, ActorRefSchema, AmountMinorSchema, AnyBillingEventSchema, ApiVersionSchema, BILLING_PATH_PLACEHOLDERS, BillingEventSchema, BillingPathSchema, BillingProfileKindSchema, BillingProfileSchema, BrandingPatchSchema, BrandingSchema, CHECKOUT_ERRORS, CancelSubscriptionInputSchema, CancelSubscriptionResponseSchema, CatalogSchema, CatalogSyncInputSchema, CatalogSyncResultSchema, CheckoutConsentInputSchema, CheckoutPrefillSchema, CheckoutSessionCreateInputSchema, CheckoutSessionCreatedSchema, CheckoutSessionResponseSchema, CheckoutSessionSchema, CheckoutStatusSchema, CodeSchema, ConsentSchema, CurrencySchema, DEFAULT_CHECKOUT_TTL_MINUTES, DEFAULT_ENDPOINT_EVENT_TYPES, DEFAULT_PORTAL_TTL_MINUTES, DOCTOR_PENDING_BACKLOG_MS, DOCTOR_PROVIDER_ENVIRONMENTS, DOCTOR_REQUIRED_BRANDING, DOCTOR_REQUIRED_LEGAL_LINKS, DOCTOR_SEVERITIES, DateTimeSchema, DoctorCatalogSchema, DoctorEmailsSchema, DoctorEndpointSchema, DoctorHostedSchema, DoctorProviderSchema, DoctorReportSchema, DoctorSettingsSchema, DoctorSeveritySchema, DoctorUnsellablePriceSchema, DoctorWarningSchema, EMAIL_LOCALES, EMAIL_TEMPLATES, EMAIL_TEMPLATE_BY_EVENT, ERROR_CATEGORIES, ERROR_CODES, EVENT_DETAIL_SCHEMAS, EVENT_TYPES, EmailExtraTextSchema, EmailSenderSchema, EmailSettingsPatchSchema, EmailSettingsSchema, EmailTemplateSchema, EmailTemplateSettingsSchema, EntitlementSnapshotSchema, EntitlementValueSchema, EntitlementsSchema, ErrorCategorySchema, ErrorResponseSchema, EventIdSchema, EventTypeSchema, ExternalRefSchema, FeatureDefSchema, FeatureTypeSchema, GrantCreateInputSchema, GrantCreateResponseSchema, GrantSchema, HEADER_ACTOR_REF, HEADER_API_VERSION, HEADER_IDEMPOTENCY_KEY, HEADER_REQUEST_ID, HEADER_SDK, IdSchema, IntervalSchema, InvoiceIssueInputSchema, InvoiceIssueResponseSchema, InvoiceLineSchema, InvoiceSchema, InvoiceStatusSchema, InvoiceVoidInputSchema, InvoiceVoidResponseSchema, LEGACY_EVENT_TYPES, LIVE_SUBSCRIPTION_STATUSES, MANUAL_INVOICE_MAX_AMOUNT_MINOR, MAX_CHECKOUT_CONSENT_DOCS, MAX_NOTIFICATION_EMAILS, ManualInvoiceInputSchema, ManualInvoiceLineInputSchema, ManualInvoiceResponseSchema, MetadataSchema, NotificationEmailsSchema, PING_EVENT_TYPE, PLAN_SET_MODES, PORTAL_SESSION_ERRORS, PaymentSchema, PingSchema, PlanDefSchema, PlanSetInputSchema, PlanSetModeSchema, PlanSetResponseSchema, PlanSetWarningSchema, PortalSessionCreateInputSchema, PortalSessionSchema, PriceDefSchema, PriceSchema, ProductSettingsPatchSchema, ProductSettingsSchema, ProviderPayloadSchema, ResyncResultSchema, ReturnOriginSchema, SETTINGS_LOCALES, SettingsLocaleSchema, StatsSchema, StewardApiError, StewardConfigError, StewardContractError, StewardError, StewardNetworkError, SubscriptionSchema, SubscriptionStatusSchema, SubscriptionSummarySchema, TtlMinutesSchema, WEBHOOK_ENDPOINT_STATUSES, WEBHOOK_SECRET_PREFIX, WebUrlSchema, WebhookEndpointCreateInputSchema, WebhookEndpointListSchema, WebhookEndpointRotateInputSchema, WebhookEndpointSchema, WebhookEndpointStatusSchema, WebhookLastDeliverySchema, WebhookSecretSchema, applyEmailSettingsPatch, applySettingsPatch, billingPageUrl, buildDoctorReport, checkoutRedirectUrl, createSteward, defineCatalog, emailLocaleOf, emailReadinessOf, emailRecipients, emailTemplateOf, emailTemplateSettings, endpointDiagnosisOf, errorCodeSpec, flag, generateWebhookSecret, hostedReadinessOf, httpStatusFor, isE164, isEmailRelevant, isEventType, isGrantActive, isKnownErrorCode, isLiveSubscriptionStatus, isReturnUrlAllowed, isValidTckn, isValidVkn, limit, manualInvoiceTotals, resolveEntitlements, returnOriginsOf, splitInclusiveTax, stateCache, text, uniqueEmails, webhookEndpointUrlProblem };
package/dist/server.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { Qn as CheckoutPrefill, Un as PortalSession, Wn as PortalSessionCreateInput, ei as Interval, lr as CheckoutStatus, or as CheckoutSessionCreated, qt as CheckoutSessionResponse, rr as CheckoutSessionCreateInput } from "./_chunks/index.js";
2
- import { D as AccountInclude, F as AccountState, V as BillingProfile, a as BillingEvent, f as EventType, n as AnyBillingEvent, o as BillingEventOf } from "./_chunks/events.js";
3
- import { i as MutationOptions } from "./_chunks/steward.js";
1
+ import { Or as CheckoutSessionCreated, Tr as CheckoutSessionCreateInput, bi as Interval, br as CheckoutPrefill, dr as PortalSession, fr as PortalSessionCreateInput, jr as CheckoutStatus, xn as CheckoutSessionResponse } from "./_chunks/index.js";
2
+ import { D as AccountInclude, H as BillingProfile, I as AccountState, a as BillingEvent, f as EventType, n as AnyBillingEvent, o as BillingEventOf } from "./_chunks/events.js";
3
+ import { r as MutationOptions } from "./_chunks/steward.js";
4
4
  import { r as StewardLogger, t as StewardLocale } from "./_chunks/locale.js";
5
5
  import { a as HeaderSource, s as VerifyRawFailure } from "./_chunks/webhook-core.js";
6
6
  import "./_chunks/webhook.js";
@@ -29,9 +29,9 @@ type CheckoutOptions = {
29
29
  steward: CheckoutSteward;
30
30
  cache?: CheckoutCache;
31
31
  /**
32
- * Mutlak dönüş adresi; origin'i steward ürün ayarında izinli olmalı (`appUrl` +
33
- * `extraReturnOrigins`). Yer tutucular `{CHECKOUT_ID}` `{STATUS}` `{ACCOUNT_REF}` `{LOCALE}`
34
- * varsa steward yalnızca onları doldurur; yoksa `?session=&status=` ekler.
32
+ * Absolute return URL; its origin must be allowed by the steward product settings (`appUrl` +
33
+ * `extraReturnOrigins`). Steward fills the placeholders `{CHECKOUT_ID}` `{STATUS}` `{ACCOUNT_REF}`
34
+ * `{LOCALE}` if present and never appends query parameters, so a URL without placeholders is used as-is.
35
35
  */
36
36
  successUrl: string;
37
37
  /** Sayfadaki "Vazgeç" hedefi (mutlak); verilmezse steward ayarı `appUrl`. */
package/dist/server.js CHANGED
@@ -1,8 +1,19 @@
1
- import { O as ActorRefSchema, R as ExternalRefSchema, a as EVENT_TYPES, c as PING_EVENT_TYPE, l as PingSchema, r as BillingEventSchema, t as AnyBillingEventSchema, y as AccountStateSchema, z as IdSchema } from "./_chunks/events.js";
1
+ import { X as ActorRefSchema, a as EVENT_TYPES, b as AccountStateSchema, c as PING_EVENT_TYPE, l as PingSchema, ot as ExternalRefSchema, r as BillingEventSchema, st as IdSchema, t as AnyBillingEventSchema } from "./_chunks/events.js";
2
2
  import "./_chunks/src.js";
3
3
  import { n as StewardConfigError, r as StewardContractError, t as StewardApiError } from "./_chunks/errors.js";
4
- import { t as hostedLocaleOf } from "./_chunks/locale.js";
5
4
  import { i as verifyWebhookRaw } from "./_chunks/webhook.js";
5
+ //#region src/locale.ts
6
+ /**
7
+ * Hosted page language (`Checkout`, `CustomerPortal`): the primary subtag of a BCP-47-like tag
8
+ * (`tr`, `tr-TR`, `EN_us` → tr/en). An unsupported or empty value → `undefined`: the caller sends
9
+ * no locale and steward uses the product setting `defaultLocale`.
10
+ */
11
+ function hostedLocaleOf(locale) {
12
+ if (typeof locale !== "string") return void 0;
13
+ const primary = locale.trim().toLowerCase().split(/[-_]/)[0];
14
+ return primary === "tr" || primary === "en" ? primary : void 0;
15
+ }
16
+ //#endregion
6
17
  //#region src/server/checkout.ts
7
18
  function isAbsoluteHttpUrl(value) {
8
19
  if (typeof value !== "string") return false;
package/dist/testing.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { $t as EventRecord, Cr as CatalogSyncInput, Dr as FeatureDef, Ft as ErrorCode, Gn as PortalSessionCreateInputSchema, Gt as CancelSubscriptionResponse, Pn as GrantCreateInputSchema, Qn as CheckoutPrefill, Rn as Stats, Tr as CatalogSyncResult, Un as PortalSession, Ut as BillingProfileResponse, Vt as AccountUpsertResponse, Wr as EntitlementValue, Zt as EventList, ar as CheckoutSessionCreateParsed, cn as InvoiceIssueResponse, dr as Consent, ei as Interval, gn as InvoiceIssueInputSchema, gt as PlanSetInputSchema, jn as CancelSubscriptionInputSchema, mn as Invoice, nr as CheckoutSession, nt as ProductSettingsPatch, or as CheckoutSessionCreated, pr as LegacyCheckoutSessionCreateParsed, qt as CheckoutSessionResponse, tn as GrantCreateResponse, tt as ProductSettings, wr as CatalogSyncInputSchema, wt as ResyncResult, yr as AccountsRefreshResult, yt as PlanSetResponse, zt as AccountDetail } from "./_chunks/index.js";
2
- import { B as AccountUpsertInputSchema, C as AccountDeleteResponse, D as AccountInclude, F as AccountState, V as BillingProfile, a as BillingEvent, f as EventType, o as BillingEventOf, q as SubscriptionStatus, u as EventDetail } from "./_chunks/events.js";
3
- import { a as Steward, c as StewardOptions } from "./_chunks/steward.js";
1
+ import { $n as CancelSubscriptionInputSchema, An as InvoiceIssueResponse, At as EmailTemplate, Cn as GrantCreateResponse, Dr as CheckoutSessionCreateParsed, Gr as CatalogSyncResult, In as Invoice, Kt as PlanSetInputSchema, Nr as Consent, Or as CheckoutSessionCreated, Rn as InvoiceIssueInputSchema, Ur as CatalogSyncInput, Wr as CatalogSyncInputSchema, Yt as PlanSetResponse, _n as AccountUpsertResponse, at as ProductSettingsPatch, bi as Interval, br as CheckoutPrefill, dn as ErrorCode, dr as PortalSession, en as ResyncResult, hn as AccountDetail, it as ProductSettings, nr as GrantCreateInputSchema, or as Stats, pr as PortalSessionCreateInputSchema, qr as FeatureDef, ui as EntitlementValue, wr as CheckoutSession, xn as CheckoutSessionResponse, yn as CancelSubscriptionResponse, zr as AccountsRefreshResult } from "./_chunks/index.js";
2
+ import { C as AccountDeleteResponse, D as AccountInclude, H as BillingProfile, I as AccountState, J as SubscriptionStatus, V as AccountUpsertInputSchema, a as BillingEvent, f as EventType, o as BillingEventOf, u as EventDetail } from "./_chunks/events.js";
3
+ import { i as Steward, s as StewardOptions } from "./_chunks/steward.js";
4
4
  import { z } from "zod";
5
5
  //#endregion
6
6
  //#region src/testing/world.d.ts
@@ -48,6 +48,10 @@ type AccountRow = {
48
48
  /** Yazılan her durum (version sırasıyla); `simulate.deliver({outOfOrder})` eski durumu buradan alır. */
49
49
  history: AccountState[];
50
50
  profile: BillingProfile | null;
51
+ /** Extra billing email recipients (`PUT /v1/accounts/:ref` `notificationEmails`). */
52
+ notificationEmails: string[];
53
+ /** Billing email language set by the product. */
54
+ locale: "tr" | "en" | null;
51
55
  /** KVKK anonimleştirme anı (F4e, `deleteAccount`); doluysa hesap yolunun uçları 410. */
52
56
  deletedAt?: Ms;
53
57
  };
@@ -93,12 +97,11 @@ type SessionRow = {
93
97
  priceId: string;
94
98
  status: CheckoutSession["status"];
95
99
  locale: string;
96
- returnUrl: string;
97
- /** Hosted oturum (F2b): başarı adresi (yer tutucularıyla); eski gövdede null. */
98
- successUrl: string | null;
100
+ /** Success URL (with placeholders, if any). */
101
+ successUrl: string;
99
102
  /** Hosted: "Vazgeç" hedefi; verilmediyse null (dönüş `settings.appUrl`). */
100
103
  cancelUrl: string | null;
101
- /** Hosted: onaylatılacak belgeler (eski gövdede boş). */
104
+ /** Hosted: onaylatılacak belgeler. */
102
105
  consentDocs: {
103
106
  document: string;
104
107
  version: string;
@@ -115,8 +118,6 @@ type SessionRow = {
115
118
  expiresAt: Ms;
116
119
  createdAt: Ms;
117
120
  completedAt: Ms | null;
118
- /** Sahte sağlayıcı formu; hosted oturumda sahte sayfanın `details` adımı olmadığından null. */
119
- providerToken: string | null;
120
121
  };
121
122
  type PaymentRow = {
122
123
  id: string;
@@ -199,13 +200,22 @@ type EventRow = {
199
200
  /** Endpoint yoksa ya da filtresi tipi içermiyorsa null. */
200
201
  delivery: DeliveryRow | null;
201
202
  };
203
+ /** A billing email the fake steward sent (`fake.emails()`). */
204
+ type EmailRow = {
205
+ eventId: string;
206
+ template: EmailTemplate;
207
+ accountRef: string;
208
+ to: string[];
209
+ locale: "tr" | "en";
210
+ sentAt: Ms;
211
+ };
202
212
  type World = {
203
213
  readonly productCode: string;
204
214
  /** Ürün ayarları (`GET/PATCH /v1/admin/settings`; checkout TTL ve dönüş origin'i buradan). */
205
215
  settings: ProductSettings;
206
216
  /**
207
217
  * true: dönüş origin'i ayarlanana kadar (`appUrl`/`extraReturnOrigins` boş ve yamada
208
- * verilmedi) her `returnUrl` kabul — sahtenin kolaylığı; servis ayar ister.
218
+ * verilmedi) every return URL is accepted — a fake convenience; the service requires the setting.
209
219
  */
210
220
  permissiveReturnOrigins: boolean;
211
221
  adminEndpoints: AdminEndpointRow[];
@@ -227,6 +237,7 @@ type World = {
227
237
  invoices: InvoiceRow[];
228
238
  grants: GrantRow[];
229
239
  events: EventRow[];
240
+ emails: EmailRow[];
230
241
  now(): Ms;
231
242
  /** Saati ileri alır (geri almaz). */
232
243
  setNow(ms: Ms): void;
@@ -234,7 +245,7 @@ type World = {
234
245
  id(): string;
235
246
  };
236
247
  declare namespace operations_d_exports {
237
- export { Failure, PORTAL_CANCEL_REASON, PORTAL_INVOICE_LIMIT, PORTAL_RETRY_INTERVAL_MS, PortalActionResult, PortalView, Result, accountDetail, advanceTo, applyRenewalPayment, cancelCheckout, cancelSubscription, checkoutSessionResponse, completeCheckout, createCheckoutSession, createGrant, createHostedCheckoutSession, createPortalSession, customerActorRef, deleteAccount, failCheckout, hostedPageUrl, hostedPortalUrl, issueInvoice, listEvents, livePortalSession, openHostedSession, openPortalSession, portalCancel, portalInvoiceDocument, portalRetryPayment, portalView, putBillingProfile, redeliverEvent, refreshAccounts, resyncAccount, revokeGrant, sessionRow, setPlan, stats, syncCatalog, updatePortalProfile, upsertAccount, validatePortalProfile };
248
+ export { Failure, PORTAL_CANCEL_REASON, PORTAL_INVOICE_LIMIT, PORTAL_RETRY_INTERVAL_MS, PortalActionResult, PortalView, Result, accountDetail, advanceTo, applyRenewalPayment, cancelCheckout, cancelSubscription, checkoutSessionResponse, completeCheckout, createCheckoutSession, createGrant, createPortalSession, customerActorRef, deleteAccount, failCheckout, hostedPageUrl, hostedPortalUrl, issueInvoice, livePortalSession, openHostedSession, openPortalSession, portalCancel, portalInvoiceDocument, portalRetryPayment, portalView, redeliverEvent, refreshAccounts, resyncAccount, revokeGrant, sessionRow, setPlan, stats, syncCatalog, updatePortalProfile, upsertAccount, validatePortalProfile };
238
249
  }
239
250
  type Failure = {
240
251
  ok: false;
@@ -247,9 +258,7 @@ type Result<T> = {
247
258
  } | Failure;
248
259
  type CatalogInput = z.output<typeof CatalogSyncInputSchema>;
249
260
  type UpsertInput = z.output<typeof AccountUpsertInputSchema>;
250
- /** Eski gövde (K16); hosted gövde `HostedCheckoutInput` (http.ts `isLegacyCheckoutInput` ile ayırır). */
251
- type CheckoutInput = LegacyCheckoutSessionCreateParsed;
252
- type HostedCheckoutInput = CheckoutSessionCreateParsed;
261
+ type CheckoutInput = CheckoutSessionCreateParsed;
253
262
  type CancelInput = z.output<typeof CancelSubscriptionInputSchema>;
254
263
  type GrantInput = z.output<typeof GrantCreateInputSchema>;
255
264
  type IssueInput = z.output<typeof InvoiceIssueInputSchema>;
@@ -262,17 +271,15 @@ declare function upsertAccount(w: World, ref: string, input: UpsertInput): {
262
271
  account: AccountUpsertResponse;
263
272
  created: boolean;
264
273
  };
265
- declare function putBillingProfile(w: World, ref: string, profile: BillingProfile): Result<BillingProfileResponse>;
266
274
  declare function accountDetail(w: World, ref: string, include: readonly AccountInclude[]): AccountDetail | null;
267
275
  /** Hosted checkout sayfası (servisin `hostedCheckoutUrl`); sahtede `hosted.ts` sunar. */
268
276
  declare const hostedPageUrl: (baseUrl: string, id: string, pageKey: string) => string;
269
- declare function createCheckoutSession(w: World, baseUrl: string, ref: string, input: CheckoutInput, actorRef: string): Result<CheckoutSessionCreated>;
270
277
  /**
271
- * `createHostedCheckoutSession` (hosted gövde, F2b): sağlayıcıya gidilmez; doğrulama sırası ve
272
- * kodları servisle aynı (hesap, dönüş origin'leri, canlı abonelik, satılabilir fiyat). Hesap
273
- * yoksa `displayName` ile açılır. `url` sahte steward'ın hosted sayfasıdır (`hosted.ts`).
278
+ * `createHostedCheckoutSession` (service): no provider call; validation order and codes match the
279
+ * service (account, return origins, live subscription, sellable price). A missing account is
280
+ * opened with `displayName`. `url` is the fake steward's hosted page (`hosted.ts`).
274
281
  */
275
- declare function createHostedCheckoutSession(w: World, baseUrl: string, ref: string, input: HostedCheckoutInput, actorRef: string): Result<CheckoutSessionCreated>;
282
+ declare function createCheckoutSession(w: World, baseUrl: string, ref: string, input: CheckoutInput, actorRef: string): Result<CheckoutSessionCreated>;
276
283
  declare function checkoutSessionResponse(w: World, id: string): CheckoutSessionResponse | null;
277
284
  declare function sessionRow(w: World, id: string): SessionRow;
278
285
  /** Hosted oturumun sayfası açık mı: anahtar bu oturumun, oturum açık ve süresi geçmemiş (servis `openSession`). */
@@ -304,8 +311,9 @@ declare function setPlan(w: World, ref: string, input: PlanSetInput, actorRef: s
304
311
  declare function resyncAccount(w: World, ref: string): Result<ResyncResult>;
305
312
  /**
306
313
  * `deleteAccount` (`domain/account-deletion.ts`, F4e): önkoşullar sırayla (hesap yok 404,
307
- * silinmiş 410, canlı abonelik, formu açık checkout — sahte steward'da yalnızca eski
308
- * gövdeli oturumun formu vardır) ve hiçbiri tutmazsa değişiklik yok. Sonra anonimleştirme:
314
+ * silinmiş 410, canlı abonelik) ve hiçbiri tutmazsa değişiklik yok. The service's
315
+ * `checkout_in_progress` (open provider form) never happens here: the fake hosted page has no
316
+ * provider form, so open sessions are formless and deletion closes them. Sonra anonimleştirme:
309
317
  * ad/metadata/profil, oturumların ön doldurması/anahtarı ve onay izinin `ipHash`/`userAgent`'ı,
310
318
  * portal oturumları, aktif grant'ler; eski event yüklerinde `displayName`. Faturalar kalır.
311
319
  */
@@ -395,12 +403,8 @@ declare function portalInvoiceDocument(w: World, session: PortalSessionRow, invo
395
403
  bytes: Uint8Array;
396
404
  filename: string;
397
405
  } | null;
398
- declare function listEvents(w: World, query: {
399
- accountRef?: string;
400
- cursor?: string;
401
- limit: number;
402
- }): Result<EventList>;
403
- declare function redeliverEvent(w: World, id: string): EventRecord | null;
406
+ /** Requeues the event's delivery (dead or delivered included); `false` if there is no such event. */
407
+ declare function redeliverEvent(w: World, id: string): boolean;
404
408
  /**
405
409
  * Tahsilat sonucu. Dunning'deki abonelikte AYNI başarısız siparişin yeniden
406
410
  * denemesidir (iyzico retry'ı; servisin `existingPayment` yolu), aksi halde
@@ -445,12 +449,13 @@ type FakeStewardOptions = {
445
449
  /**
446
450
  * Başlangıç ürün ayarları (`PATCH /v1/admin/settings` yamasıyla aynı biçim). Sağlayıcı
447
451
  * her zaman sahte (`provider: "fake"`). Dönüş origin'i (`appUrl`, `extraReturnOrigins`,
448
- * `returnOrigins`) hiç verilmez ve yamalanmazsa her `returnUrl` kabul edilir.
452
+ * `returnOrigins`) is never given or patched, every return URL (`successUrl`, `cancelUrl`,
453
+ * portal `returnUrl`) is accepted.
449
454
  */
450
455
  settings?: ProductSettingsPatch;
451
- /** Checkout `returnUrl` origin listesi = `settings.extraReturnOrigins` (ikisi birlikte verilemez). */
456
+ /** Allowed return origins for checkout and portal = `settings.extraReturnOrigins` (cannot be given together). */
452
457
  returnOrigins?: readonly string[];
453
- /** = `settings.checkoutTtlMinutes`; varsayılan 30 (sahte sağlayıcının formu da 30 dk). */
458
+ /** = `settings.checkoutTtlMinutes`; default 30. */
454
459
  checkoutTtlMinutes?: number;
455
460
  /** Varsayılan servisinki: `dryRun: true` (adımlar sayılır, askı/sonlandırma yok). */
456
461
  dunningPolicy?: FakeDunningPolicy;
@@ -574,6 +579,12 @@ type FakeSimulate = {
574
579
  deliver(type: EventType, options: FakeDeliverOptions): Promise<FakeDelivery[]>;
575
580
  /** Bekleyen (teslim edilmemiş) outbox event'lerini sırayla alıcıya gönderir. */
576
581
  flush(): Promise<FakeDelivery[]>;
582
+ /**
583
+ * Operator redelivery (the service's pod CLI `redeliver-event <product> <eventId>`): the event's
584
+ * delivery is requeued with attempts reset, the next `flush()` sends the same id and body again.
585
+ * Throws for an unknown event id. There is no product HTTP API for this.
586
+ */
587
+ redeliver(eventId: string): void;
577
588
  };
578
589
  type FakeSteward = {
579
590
  readonly baseUrl: string;
@@ -589,11 +600,27 @@ type FakeSteward = {
589
600
  * `webhook` seçeneği (sır, filtre) verilmemişse fırlatır.
590
601
  */
591
602
  connect(handler: FakeWebhookHandler): void;
592
- /** Yayınlanan event'ler, yayın sırasıyla (`GET /v1/events`'in içeriği; eski tiplerde de tam durum). */
603
+ /** Published events in publish order (the outbox; legacy types carry the full state too). */
593
604
  events(ref?: string): readonly BillingEvent[];
605
+ /**
606
+ * Billing emails steward would send (issue #15), in send order. The fake applies the
607
+ * service's rules (template switch, send-time relevance, recipients, locale) immediately
608
+ * when the event is published; skipped emails are not listed. Content is not rendered.
609
+ */
610
+ emails(ref?: string): readonly FakeEmail[];
594
611
  /** Sahte saat. */
595
612
  now(): Date;
596
613
  };
614
+ type FakeEmail = {
615
+ /** Triggering event (`fake.events()`); one email per event. */
616
+ eventId: string;
617
+ template: EmailTemplate;
618
+ accountRef: string;
619
+ /** Billing profile email first, then the account's `notificationEmails`. */
620
+ to: readonly string[];
621
+ locale: "tr" | "en";
622
+ sentAt: string;
623
+ };
597
624
  export declare function createFakeSteward(options?: FakeStewardOptions): FakeSteward;
598
625
  //#endregion
599
626
  //#region src/testing/signed-event.d.ts
@@ -626,4 +653,4 @@ type SignedEvent<T extends EventType = EventType> = {
626
653
  };
627
654
  export declare function signedEvent<T extends EventType>(type: T, overrides?: SignedEventOverrides<T>, options?: SignedEventOptions): SignedEvent<T>;
628
655
  //#endregion
629
- export type { FakeDeliverOptions, FakeDelivery, FakeDunningPolicy, FakeHostedCheckoutResult, FakePortalActionResult, FakeRequest, FakeSimulate, FakeSteward, FakeStewardOptions, FakeWebhookHandler, FakeWebhookOptions, SignedEvent, SignedEventOptions, SignedEventOverrides };
656
+ export type { FakeDeliverOptions, FakeDelivery, FakeDunningPolicy, FakeEmail, FakeHostedCheckoutResult, FakePortalActionResult, FakeRequest, FakeSimulate, FakeSteward, FakeStewardOptions, FakeWebhookHandler, FakeWebhookOptions, SignedEvent, SignedEventOptions, SignedEventOverrides };