@zenky/storefront-vue 0.10.8 → 0.10.9

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 (73) hide show
  1. package/README.md +4 -18
  2. package/dist/cart/index.d.ts +167 -160
  3. package/dist/cart/index.js +7 -7
  4. package/dist/catalog/index.d.ts +18 -21
  5. package/dist/catalog/index.js +2 -2
  6. package/dist/{chunk-RO25KNM5.js → chunk-2Y6QTHXI.js} +2 -2
  7. package/dist/chunk-2Y6QTHXI.js.map +1 -0
  8. package/dist/{chunk-5YD4AIY2.js → chunk-46FNHMWC.js} +4 -4
  9. package/dist/chunk-46FNHMWC.js.map +1 -0
  10. package/dist/{chunk-Z3IW4ODZ.js → chunk-6QCFHSLX.js} +2 -2
  11. package/dist/chunk-6QCFHSLX.js.map +1 -0
  12. package/dist/{chunk-2SMSLZ6G.js → chunk-AVES4WJZ.js} +15 -11
  13. package/dist/chunk-AVES4WJZ.js.map +1 -0
  14. package/dist/{chunk-4IFPVEO7.js → chunk-BUNI6MGH.js} +3 -3
  15. package/dist/chunk-BUNI6MGH.js.map +1 -0
  16. package/dist/{chunk-PTMSPB34.js → chunk-FXKG5TFQ.js} +3 -3
  17. package/dist/chunk-FXKG5TFQ.js.map +1 -0
  18. package/dist/{chunk-MOG6UMFM.js → chunk-GILJFP55.js} +2 -2
  19. package/dist/chunk-GILJFP55.js.map +1 -0
  20. package/dist/{chunk-2CI4RW7V.js → chunk-GLQXTMVW.js} +2 -2
  21. package/dist/{chunk-2CI4RW7V.js.map → chunk-GLQXTMVW.js.map} +1 -1
  22. package/dist/{chunk-MZ66ARDL.js → chunk-GXDTRTUT.js} +2 -2
  23. package/dist/chunk-GXDTRTUT.js.map +1 -0
  24. package/dist/{chunk-E3G7NGCH.js → chunk-KFCO46RB.js} +2 -2
  25. package/dist/{chunk-E3G7NGCH.js.map → chunk-KFCO46RB.js.map} +1 -1
  26. package/dist/{chunk-VFMVQR6Y.js → chunk-QZ3S3NN3.js} +5 -3
  27. package/dist/chunk-QZ3S3NN3.js.map +1 -0
  28. package/dist/{chunk-3FDM6T7F.js → chunk-RF4ML3Q3.js} +8 -6
  29. package/dist/chunk-RF4ML3Q3.js.map +1 -0
  30. package/dist/{chunk-NG7RUIWW.js → chunk-RK5CGOM7.js} +2 -2
  31. package/dist/chunk-RK5CGOM7.js.map +1 -0
  32. package/dist/{chunk-Z247QRDJ.js → chunk-XULHV6SS.js} +3 -3
  33. package/dist/chunk-XULHV6SS.js.map +1 -0
  34. package/dist/index.d.ts +3 -3
  35. package/dist/index.js +14 -14
  36. package/dist/money/index.d.ts +8 -8
  37. package/dist/money/index.js +1 -1
  38. package/dist/order/index.d.ts +3 -3
  39. package/dist/order/index.js.map +1 -1
  40. package/dist/pagination/index.d.ts +29 -37
  41. package/dist/pagination/index.js.map +1 -1
  42. package/dist/ports/index.d.ts +23 -22
  43. package/dist/ports/index.js +1 -1
  44. package/dist/products/index.d.ts +6 -7
  45. package/dist/products/index.js +3 -3
  46. package/dist/promotions/index.d.ts +5 -5
  47. package/dist/promotions/index.js +3 -3
  48. package/dist/seo/index.d.ts +14 -12
  49. package/dist/seo/index.js +5 -5
  50. package/dist/seo/index.js.map +1 -1
  51. package/dist/snippets/index.js +1 -1
  52. package/dist/stores/index.d.ts +4 -5
  53. package/dist/stores/index.js +4 -4
  54. package/dist/theme/index.d.ts +3 -3
  55. package/dist/theme/index.js +1 -1
  56. package/dist/utils/index.d.ts +16 -16
  57. package/dist/utils/index.js +1 -1
  58. package/docs/architecture.md +84 -0
  59. package/docs/consumer-setup.md +13 -54
  60. package/docs/ports.md +12 -13
  61. package/package.json +1 -1
  62. package/dist/chunk-2SMSLZ6G.js.map +0 -1
  63. package/dist/chunk-3FDM6T7F.js.map +0 -1
  64. package/dist/chunk-4IFPVEO7.js.map +0 -1
  65. package/dist/chunk-5YD4AIY2.js.map +0 -1
  66. package/dist/chunk-MOG6UMFM.js.map +0 -1
  67. package/dist/chunk-MZ66ARDL.js.map +0 -1
  68. package/dist/chunk-NG7RUIWW.js.map +0 -1
  69. package/dist/chunk-PTMSPB34.js.map +0 -1
  70. package/dist/chunk-RO25KNM5.js.map +0 -1
  71. package/dist/chunk-VFMVQR6Y.js.map +0 -1
  72. package/dist/chunk-Z247QRDJ.js.map +0 -1
  73. package/dist/chunk-Z3IW4ODZ.js.map +0 -1
@@ -1,9 +1,9 @@
1
- import { ProductModifiersRequest, OrderProductVariant, PaymentMethod, OrderPaymentMethodRequest, OrderAuthenticationMethod, OrderCredentials, Order, OrderCheckoutTotal, OrderSettings, OrderPaymentMethod, OrderDeliveryMethod, InclusionRequest, ZenkyStorefront, SetOrderCustomerRequest, SetOrderDeliveryRequest, OrderPromocode, OrderCheckoutResult, RecaptchaAction, EvaluatedRestriction, Media, Product } from '@zenky/storefront-api';
1
+ import { ProductModifiersRequest, OrderProductVariant, PaymentMethod, OrderPaymentMethodRequest, OrderAuthenticationMethod, OrderCredentials, Order, OrderCheckoutTotal, OrderSettings, OrderPaymentMethod, OrderDeliveryMethod, InclusionRequest, ZenkyStorefront, SetOrderCustomerRequest, SetOrderDeliveryRequest, OrderPromocode, RecommendationsBlock, OrderCheckoutResult, RecaptchaAction, EvaluatedRestriction, Media, Product } from '@zenky/storefront-api';
2
2
  import { ComputedRef, MaybeRefOrGetter, Ref } from 'vue';
3
3
  import { ActivityReporter, Notifier, Result } from '../ports/index.js';
4
4
  import '@zenky/integrations-sdk';
5
5
 
6
- /** WebSocket события канала заказа */
6
+ /** WebSocket events for the order channel */
7
7
  declare const ORDER_EVENTS: {
8
8
  readonly PriceRecalculated: "orders.price.recalculated";
9
9
  readonly Reload: "orders.reload";
@@ -14,7 +14,7 @@ declare const ORDER_EVENTS: {
14
14
  readonly RewardsReload: "orders.rewards.reload";
15
15
  };
16
16
 
17
- /** Нормализация строки адреса для сравнения (lowercase, схлопывание запятых/пробелов). */
17
+ /** Normalizes an address string for comparison (lowercase, collapse commas/spaces). */
18
18
  declare function normalizeAddress(value: string | null | undefined): string;
19
19
 
20
20
  interface CartLineKeyParams {
@@ -23,7 +23,7 @@ interface CartLineKeyParams {
23
23
  promotionId?: string;
24
24
  promotionRewardId?: string;
25
25
  }
26
- /** Детерминированный ключ строки корзины: variant + sorted modifiers + promotion. */
26
+ /** Deterministic cart line key: variant + sorted modifiers + promotion. */
27
27
  declare function buildCartLineKey(params: CartLineKeyParams): string;
28
28
  declare function variantLineKey(variant: OrderProductVariant): string;
29
29
 
@@ -35,167 +35,171 @@ interface MainPaymentRequestParams {
35
35
  currency: string;
36
36
  }
37
37
  /**
38
- * Основной (не-бонусный) payment-request из выбранного способа оплаты.
39
- * Единый источник для UI и reconciliation; `bill` конвертируется minor→major здесь.
38
+ * Builds the main (non-bonus) payment request from the selected payment method.
39
+ * Single source of truth for both UI and reconciliation; `bill` is converted
40
+ * minor → major here.
40
41
  */
41
42
  declare function buildMainPaymentRequest(params: MainPaymentRequestParams): OrderPaymentMethodRequest | null;
42
43
 
43
44
  /**
44
- * Утилиты для построения пресетов «с какой суммы приготовить сдачу» (cash bill)
45
- * в минорных единицах валюты (копейки/тыйны/сатанги).
45
+ * Utilities for building "prepare change from this amount" (cash bill) presets,
46
+ * in minor currency units (kopecks/tiyn/satang).
46
47
  *
47
- * UI отображает пресеты как пилюли: «1100 ₽», «1500 ₽», «5000 ₽» и т.п.
48
+ * The UI shows the presets as pills: "1100 ₽", "1500 ₽", "5000 ₽", etc.
48
49
  */
49
50
  /**
50
- * Номиналы банкнот по странам в **мажорных** единицах валюты.
51
- * Набор банкнот зависит от страны (рубли РФ ≠ тенге KZ), а конвертация
52
- * мажор → минор — от валюты (через `majorToMinor`, который сам учитывает
53
- * число дробных знаков по ISO-коду). Поэтому `getCashDenominationsMinor`
54
- * принимает и страну (выбор набора), и валюту (фактор конвертации).
51
+ * Banknote denominations per country, in **major** currency units.
52
+ * The set of banknotes depends on the country (RU rubles ≠ KZ tenge), while
53
+ * the major → minor conversion depends on the currency (via `majorToMinor`,
54
+ * which accounts for the number of decimal digits per ISO code). That's why
55
+ * `getCashDenominationsMinor` takes both a country (to pick the set) and a
56
+ * currency (the conversion factor).
55
57
  */
56
58
  declare const CASH_DENOMINATIONS_MAJOR: Record<string, number[]>;
57
59
  /**
58
- * Шаги округления вверх в **мажорных** единицах: 10 / 50 / 100 / 200 / 500 / 1000.
59
- * Конвертируются в минорные по валюте через `getDefaultRoundStepsMinor` —
60
- * чтобы работать для валют с любым числом дробных знаков, а не только ×100.
60
+ * Round-up steps in **major** units: 10 / 50 / 100 / 200 / 500 / 1000.
61
+ * Converted to minor units per currency via `getDefaultRoundStepsMinor` — so
62
+ * it works for currencies with any number of decimal digits, not just ×100.
61
63
  */
62
64
  declare const DEFAULT_ROUND_STEPS_MAJOR: readonly number[];
63
65
  declare function getDefaultRoundStepsMinor(currency?: string): number[];
64
- /** Номиналы в минорных единицах для страны магазина (с фолбэком на RU). */
65
66
  declare function getCashDenominationsMinor(country: string | null | undefined, currency?: string): number[];
66
67
  interface CashChangePresetsOptions {
67
- /** Сумма заказа в минорных единицах. */
68
68
  totalMinor: number;
69
- /** Номиналы банкнот в минорных единицах (см. `getCashDenominationsMinor`). */
69
+ /** Banknote denominations in minor units (see `getCashDenominationsMinor`). */
70
70
  denominationsMinor: number[];
71
- /** Шаги округления — переопределяй только если знаешь зачем. */
71
+ /** Round-up steps — override this only if you know why. */
72
72
  roundStepsMinor?: readonly number[];
73
73
  }
74
74
  /**
75
- * Строит пресеты сдачи в минорных единицах:
76
- * объединяем округлённые вверх суммы (до 10/50/100/200/500/1000) и все
77
- * банкноты > total, дедупим, сортируем по возрастанию.
75
+ * Builds change presets in minor units: combines round-up sums (to
76
+ * 10/50/100/200/500/1000) with all banknotes > total, dedupes, and sorts
77
+ * ascending.
78
78
  *
79
- * Округления — strict (`total + 1`), чтобы сдача всегда была > 0.
79
+ * Rounding is strict (`total + 1`), so the change is always > 0.
80
80
  *
81
- * Примеры (для RU, total в рублях для краткости):
81
+ * Examples (for RU, total in rubles for brevity):
82
82
  * total = 1080: 1090 / 1100 / 1200 / 1500 / 2000 / 5000 / 10000
83
83
  * total = 1130: 1140 / 1150 / 1200 / 1500 / 2000 / 5000 / 10000
84
84
  * total = 3060: 3070 / 3100 / 3200 / 3500 / 4000 / 5000 / 10000
85
85
  * total = 3982: 3990 / 4000 / 5000 / 10000
86
- * total = 0: все банкноты как есть.
86
+ * total = 0: all banknotes as-is.
87
87
  */
88
88
  declare function buildCashChangePresets({ totalMinor, denominationsMinor, roundStepsMinor, }: CashChangePresetsOptions): number[];
89
89
 
90
90
  /**
91
- * Единый формат логов ошибок для всех cart/checkout-операций + извлечение
92
- * читаемых сообщений из ZenkyError для UI (toast / inline).
91
+ * Common error log format for all cart/checkout operations, plus extraction
92
+ * of readable messages from a ZenkyError for the UI (toast / inline).
93
93
  *
94
- * Контракт ошибок Zenky API (см. `ApiError` в SDK):
94
+ * Zenky API error contract (see `ApiError` in the SDK):
95
95
  * {
96
96
  * err: {
97
- * message: string, // локализованное — "Адрес доставки не указан."
98
- * original_message: string, // англ. оригинал
97
+ * message: string, // localized — "Адрес доставки не указан."
98
+ * original_message: string, // English original
99
99
  * http_code: number,
100
100
  * error_code: string, // 'addresses.not_specified' | 'validation' | etc.
101
- * meta: any, // для validation: { errors: { [field]: string[] } }
101
+ * meta: any, // for validation: { errors: { [field]: string[] } }
102
102
  * }
103
103
  * }
104
104
  *
105
- * Для validation-ошибок (`error_code === 'validation'`) — берём сообщения из
106
- * `meta.errors`, не верхнеуровневое generic сообщение.
105
+ * For validation errors (`error_code === 'validation'`), we take the messages
106
+ * from `meta.errors` instead of the generic top-level message.
107
107
  */
108
108
  interface CartErrorScope {
109
- /** Префикс — operation name (`cart-add` / `delivery` / `promocode-apply` / etc.) */
109
+ /** Prefix — operation name (`cart-add` / `delivery` / `promocode-apply` / etc.) */
110
110
  scope: string;
111
- /** Параметры операции — id'шники, входы, что в данный момент в credentials */
111
+ /** Operation parameters — ids, inputs, whatever is currently in credentials */
112
112
  context?: Record<string, unknown>;
113
113
  }
114
114
  /**
115
- * Залогировать ошибку cart/checkout-операции в едином формате.
116
- * Безопасно для любого `unknown` — не падает на не-ZenkyError ошибках.
115
+ * Logs a cart/checkout operation error in a common format.
116
+ * Safe for any `unknown` value — doesn't throw on non-ZenkyError errors.
117
117
  */
118
118
  declare function logCartError({ scope, context }: CartErrorScope, e: unknown): void;
119
119
  /**
120
- * Достаёт `error_code` бэка (например `addresses.not_specified`).
121
- * Возвращает undefined для не-Zenky ошибок.
120
+ * Extracts the backend `error_code` (e.g. `addresses.not_specified`).
121
+ * Returns undefined for non-Zenky errors.
122
122
  */
123
123
  declare function getCartErrorCode(e: unknown): string | undefined;
124
124
  /**
125
- * Достаёт HTTP-код бэка (например 401 для требующей авторизации операции).
126
- * Возвращает undefined для не-Zenky ошибок.
125
+ * Extracts the backend HTTP code (e.g. 401 for an operation that requires
126
+ * authorization). Returns undefined for non-Zenky errors.
127
127
  */
128
128
  declare function getCartErrorHttpCode(e: unknown): number | undefined;
129
129
  /**
130
- * Достаёт field → [messages] из ZenkyError для валидации.
131
- * Возвращает {} если ошибка не validation или meta.errors пусто.
130
+ * Extracts field → [messages] from a ZenkyError for validation.
131
+ * Returns {} if the error isn't a validation error or meta.errors is empty.
132
132
  */
133
133
  declare function getValidationErrors(e: unknown): Record<string, string[]>;
134
134
  /**
135
- * Вытащить читаемое сообщение для UI (toast / inline).
135
+ * Extracts a readable message for the UI (toast / inline).
136
136
  *
137
- * Приоритет:
138
- * 1. Если validation-ошибка → склеиваем все сообщения из `meta.errors` (по всем полям)
139
- * 2. Иначе — `err.message` (generic от бэка)
140
- * 3. Иначе — `fallback`
137
+ * Priority:
138
+ * 1. If it's a validation error → join all messages from `meta.errors` (across all fields)
139
+ * 2. Otherwise — `err.message` (generic message from the backend)
140
+ * 3. Otherwise — `fallback`
141
141
  */
142
142
  declare function getCartErrorMessage(e: unknown, fallback: string): string;
143
143
 
144
144
  /**
145
- * Race-safe выполнение мутаций корзины.
145
+ * Race-safe execution of cart mutations.
146
146
  *
147
- * Проблема: SDK Zenky не поддерживает AbortSignal — нельзя физически отменить
148
- * запрос на полпути. Если пользователь быстро жмёт `+ → доставка → оплата`,
149
- * ответы могут прийти в произвольном порядке и устаревший ответ перепишет
150
- * свежее состояние (race condition).
147
+ * Problem: the Zenky SDK doesn't support AbortSignal — a request can't actually
148
+ * be canceled halfway through. If the user quickly clicks `+ → delivery →
149
+ * payment`, responses can arrive out of order and a stale response can
150
+ * overwrite fresher state (a race condition).
151
151
  *
152
- * Решение: версионирование per-kind. У каждого вида операции свой счётчик —
153
- * новый вызов инкрементирует его, после await callback проверяет «я ещё актуален?»
154
- * через `isStale()`. Если устарел — side-effect (`cartStore.setOrder`) пропускается.
155
- * HTTP-запрос всё равно завершается на бэке (минорный overhead), но фронт
156
- * игнорирует результат → race гарантированно не пройдёт.
152
+ * Solution: per-kind versioning. Each operation kind has its own counter — a
153
+ * new call increments it, and after the await the callback checks "am I still
154
+ * current?" via `isStale()`. If it's stale, the side effect
155
+ * (`cartStore.setOrder`) is skipped. The HTTP request still completes on the
156
+ * backend (a minor overhead), but the frontend ignores the result, so the race
157
+ * can never land.
157
158
  *
158
- * Дополнительно — debounce per-kind. Быстрые подряд клики «++++» схлопываются
159
- * в один запрос после паузы.
159
+ * Also includes per-kind debounce. Rapid clicks like "++++" collapse into a
160
+ * single request after a pause.
160
161
  *
161
- * Состояние версий общее для composables одного storefront runtime, но изолировано
162
- * между SSR-запросами и отдельными Vue-приложениями.
162
+ * Version state is shared across composables within one storefront runtime,
163
+ * but isolated between SSR requests and separate Vue apps.
163
164
  */
164
165
  /**
165
- * `cart-line-${lineKey}` — динамический ключ строки корзины: add и remove одной
166
- * строки делят kind, т.к. конфликтуют по одному ресурсу.
166
+ * `cart-line-${lineKey}` — dynamic cart line key: add and remove for the same
167
+ * line share a kind, since they contend for the same resource.
167
168
  */
168
169
  type MutationKind = 'delivery' | 'delivery-settle' | 'payment' | 'promocode' | 'bonuses' | 'customer' | 'total' | 'settings' | 'checkout' | `cart-line-${string}`;
169
170
  interface MutationOptions {
170
- /** Уникальный kind — мутации одного kind заменяют друг друга */
171
+ /** Unique kind — mutations of the same kind replace each other */
171
172
  kind: MutationKind;
172
- /** Debounce в мс перед отправкой (0 = без debounce) */
173
+ /** Debounce in ms before sending (0 = no debounce) */
173
174
  debounce?: number;
174
175
  }
175
176
  interface CartMutationComposable {
176
177
  /**
177
- * Запустить мутацию. Внутри callback'а можно делать side-effect только
178
- * если `isStale()` вернул `false` — иначе старый результат затрёт свежий.
178
+ * Run a mutation. Inside the callback, only do the side effect if
179
+ * `isStale()` returns `false` — otherwise a stale result would overwrite a
180
+ * fresher one.
179
181
  *
180
- * Возвращает результат `fn` или `undefined` если был stale.
182
+ * Returns the result of `fn`, or `undefined` if it went stale.
181
183
  *
182
184
  * @example
183
185
  * await run({ kind: 'payment', debounce: 300 }, async (isStale) => {
184
186
  * const order = await sdk.orders.setOrderPayments(...)
185
- * if (isStale()) return // Пришёл новый клик — наш результат устарел
187
+ * if (isStale()) return // A new click came in — our result is stale
186
188
  * cartStore.setOrder(order)
187
189
  * return order
188
190
  * })
189
191
  */
190
192
  run: <T>(options: MutationOptions, fn: (isStale: () => boolean) => Promise<T>) => Promise<T | undefined>;
191
- /** Получить текущую версию kind'а — для тестов / отладки */
193
+ /** Get the current version of a kind — for tests / debugging */
192
194
  getVersion: (kind: MutationKind) => number;
193
195
  /**
194
- * Bump-нуть версии всех kind с указанным префиксом — все in-flight операции,
195
- * матчащие префикс, станут stale и их side-effect'ы будут проигнорированы.
196
+ * Bump the versions of all kinds with the given prefix — every in-flight
197
+ * operation matching the prefix becomes stale and its side effects are
198
+ * ignored.
196
199
  *
197
- * Используется при `clearAndResetCart` / `logout` — отменить все pending
198
- * мутации старого заказа, чтобы поздние ответы не записались в свежий стейт.
200
+ * Used by `clearAndResetCart` / `logout` — to cancel all pending mutations
201
+ * of the old order, so late responses don't get written into the fresh
202
+ * state.
199
203
  */
200
204
  bumpKindsWithPrefix: (prefix: string) => void;
201
205
  }
@@ -208,31 +212,31 @@ interface CartQuantities {
208
212
  declare function useCartQuantities(): CartQuantities;
209
213
 
210
214
  interface CheckoutFlowFlags {
211
- /** Режим из настроек магазина (Disabled / Preauth / Confirmation) */
212
215
  mode: ComputedRef<OrderAuthenticationMethod>;
213
- /** Нужна авторизация перед submit (открывается AuthModal вместо checkoutOrder) */
216
+ /** Auth is required before submit (opens AuthModal instead of checkoutOrder) */
214
217
  needsAuth: ComputedRef<boolean>;
215
- /** Нужно показать CustomerForm в корзине (phone + name) */
218
+ /** CustomerForm (phone + name) must be shown in the cart */
216
219
  needsCustomerForm: ComputedRef<boolean>;
217
220
  }
218
221
  /**
219
- * Определяет поведение чекаута в зависимости от настроек магазина.
222
+ * Determines checkout behavior based on store settings.
220
223
  *
221
- * Матрица:
224
+ * Matrix:
222
225
  * ┌──────────────┬──────────┬──────────────────┐
223
226
  * │ mode │ needsAuth│ needsCustomerForm│
224
227
  * ├──────────────┼──────────┼──────────────────┤
225
228
  * │ Preauth │ true │ false │
226
- * │ Confirmation │ false │ true (гости) │
227
- * │ Disabled │ false │ true (гости) │
229
+ * │ Confirmation │ false │ true (guests) │
230
+ * │ Disabled │ false │ true (guests) │
228
231
  * └──────────────┴──────────┴──────────────────┘
229
232
  *
230
- * Нужна ли SMS-подтверждение — фронт не вычисляет: бэк возвращает
231
- * `confirmation.required` в ответе `checkoutOrder`, и UI реагирует на него.
233
+ * Whether SMS confirmation is needed is not computed on the frontend: the
234
+ * backend returns `confirmation.required` in the `checkoutOrder` response,
235
+ * and the UI reacts to that.
232
236
  *
233
- * Примечание: `needsCustomerForm` сейчас возвращает true для гостей во всех
234
- * режимах кроме Preauth. Для авторизованных клиентов форма не нужна
235
- * (данные автозаполняются через authStore).
237
+ * Note: `needsCustomerForm` currently returns true for guests in every mode
238
+ * except Preauth. Authenticated customers don't need the form (their data is
239
+ * autofilled from authStore).
236
240
  */
237
241
  declare function useCheckoutFlow(): CheckoutFlowFlags;
238
242
 
@@ -249,8 +253,9 @@ interface CartCredentials {
249
253
  isOrderActive: (order: Order) => boolean;
250
254
  }
251
255
  /**
252
- * Управление credentials заказа. Персистенс order-id/token — через порт `storage`
253
- * (ядро не знает про useCookie). Рефы инициализируются из storage, persist пишет в оба.
256
+ * Manages order credentials. Order id/token persistence goes through the `storage`
257
+ * port (the core doesn't know about useCookie). The refs are initialized from
258
+ * storage; persisting writes to both.
254
259
  */
255
260
  declare function useCartCredentials(): CartCredentials;
256
261
 
@@ -262,15 +267,15 @@ interface OrderTotal {
262
267
  declare function useOrderTotal(): OrderTotal;
263
268
 
264
269
  interface OrderSettingsComposable {
265
- /** Полный снепшот настроек — читается из `cartStore.orderSettings` */
270
+ /** Full settings snapshot — read from `cartStore.orderSettings` */
266
271
  settings: ComputedRef<OrderSettings | null>;
267
272
  paymentMethods: ComputedRef<OrderPaymentMethod[]>;
268
273
  deliveryMethods: ComputedRef<OrderDeliveryMethod[]>;
269
274
  loading: Ref<boolean>;
270
275
  /**
271
- * Перезапросить настройки с бэка. Вызывается:
272
- * - при старте (через useCartInitialization)
273
- * - после setOrderDeliveryMethod (набор payment-методов меняется от доставки)
276
+ * Refetches settings from the backend. Called:
277
+ * - on startup (via useCartInitialization)
278
+ * - after setOrderDeliveryMethod (the set of payment methods changes based on delivery)
274
279
  */
275
280
  fetchSettings: () => Promise<void>;
276
281
  }
@@ -282,30 +287,31 @@ interface OrderCredentialsLike {
282
287
  }
283
288
  interface RetryOptions {
284
289
  /**
285
- * ID существующей online-payment транзакции (`order.payments[].id` где
286
- * `is_online === true && status === 'pending'`). Используется как fallback
287
- * если основной retry-эндпоинт вернул ошибку (typically 409
288
- * `order_is_not_submitted` для свежих pending-заказов).
290
+ * ID of an existing online-payment transaction (`order.payments[].id`
291
+ * where `is_online === true && status === 'pending'`). Used as a fallback
292
+ * if the main retry endpoint returns an error (typically 409
293
+ * `order_is_not_submitted` for freshly created pending orders).
289
294
  */
290
295
  transactionId?: string | null;
291
296
  /**
292
- * Куда вернуть юзера после оплаты. По дефолту `window.location.href` —
293
- * на success-странице это правильно (вернёт обратно на success), но
294
- * со страницы заказа `/me/orders/[id]` лучше передать success-URL явно,
295
- * иначе после оплаты юзер останется на странице заказа без `?payment=`
296
- * query и не увидит результат оплаты.
297
+ * Where to send the user back after payment. Defaults to
298
+ * `window.location.href` — correct on the success page (sends back to
299
+ * success), but from the order page `/me/orders/[id]` it's better to pass
300
+ * the success URL explicitly, otherwise after payment the user is left on
301
+ * the order page without the `?payment=` query and never sees the
302
+ * payment result.
297
303
  */
298
304
  currentUrl?: string;
299
305
  }
300
306
  /**
301
- * Повторная попытка онлайн-оплаты заказа.
307
+ * Retries an order's online payment.
302
308
  *
303
- * **Стратегия (двухуровневая)**:
304
- * 1. `sdk.orders.retryOnlinePayment` — официальный retry-эндпоинт (submitted-заказы).
305
- * 2. `getOnlinePaymentRedirect(transactionId)` — fallback для pending-заказов (409
309
+ * **Strategy (two-tier)**:
310
+ * 1. `sdk.orders.retryOnlinePayment` — the official retry endpoint (submitted orders).
311
+ * 2. `getOnlinePaymentRedirect(transactionId)` — fallback for pending orders (409
306
312
  * `order_is_not_submitted`).
307
313
  *
308
- * Возвращает `redirect_url` или `null` если оба способа упали.
314
+ * Returns `redirect_url`, or `null` if both approaches fail.
309
315
  */
310
316
  declare function useOnlinePaymentRetry(): {
311
317
  retry(creds: OrderCredentialsLike, options?: RetryOptions): Promise<string | null>;
@@ -349,7 +355,7 @@ interface BonusesReconciliationDeps {
349
355
  notifier: Notifier;
350
356
  activity?: ActivityReporter;
351
357
  }
352
- /** Headless-синхронизация применённых бонусов после order-change (от server-state + intent). */
358
+ /** Headless sync of applied bonuses after an order change (using server state + intent). */
353
359
  declare function useBonusesReconciliation(deps: BonusesReconciliationDeps): BonusesReconciliation;
354
360
 
355
361
  interface CartRecalculation {
@@ -360,14 +366,16 @@ interface CartRecalculationDeps {
360
366
  activity?: ActivityReporter;
361
367
  }
362
368
  /**
363
- * Orchestration после order-change: total → синхронизация бонусов → промо/min-price.
364
- * Вызывать явно после мутаций заказа; не привязывать к каждому fetchTotal (цикл).
369
+ * Orchestration after an order change: total → bonus sync → promo/min-price.
370
+ * Call this explicitly after order mutations; don't wire it to every fetchTotal
371
+ * call (that would create a cycle).
365
372
  */
366
373
  declare function useCartRecalculation(deps: CartRecalculationDeps): CartRecalculation;
367
374
 
368
375
  /**
369
- * View прикреплённого покупателя для UI. `national` форматируется потребителем
370
- * (нужна app-специфичная маска страны — Nuxt useAppConfig), ядро его не считает.
376
+ * View of the attached customer, for the UI. `national` is formatted by the
377
+ * consumer (it needs an app-specific country mask — Nuxt useAppConfig); the
378
+ * core does not compute it.
371
379
  */
372
380
  interface CachedCustomerView {
373
381
  first_name: string;
@@ -379,9 +387,9 @@ interface CachedCustomerView {
379
387
  };
380
388
  }
381
389
  /**
382
- * Контракт client-local кэша покупателя. Реализация — на стороне потребителя
383
- * (localStorage + app-форматтер телефона), инжектится параметром в
384
- * `useCustomerAttach` / `useCartCustomerAttachment`.
390
+ * Contract for the client-local customer cache. Implemented by the consumer
391
+ * (localStorage + an app-specific phone formatter), injected as a parameter
392
+ * into `useCustomerAttach` / `useCartCustomerAttachment`.
385
393
  */
386
394
  interface AttachedCustomerCache {
387
395
  forOrder: (orderId: MaybeRefOrGetter<string | null | undefined>) => ComputedRef<CachedCustomerView | null>;
@@ -390,50 +398,51 @@ interface AttachedCustomerCache {
390
398
  }
391
399
 
392
400
  interface CustomerAttachComposable {
393
- /** Прикреплён ли покупатель к заказу (есть `order.customer`) */
401
+ /** Whether the customer is attached to the order (there's `order.customer`) */
394
402
  isAttached: ComputedRef<boolean>;
395
403
  /**
396
- * Привязать customer к заказу (phone + имя + опционально фамилия / дата рождения).
397
- * После успешного вызова заказ перечитываем с includes — чтобы `order.customer`
398
- * попал в `cartStore.order` и компоненты могли его увидеть.
404
+ * Attach a customer to the order (phone + name + optional last name / birth date).
405
+ * After a successful call, the order is re-fetched with includes — so that
406
+ * `order.customer` lands in `cartStore.order` and components can see it.
399
407
  *
400
- * Обёрнуто в activity('custom') — блокирует кнопку «Оформить» на время запроса.
408
+ * Wrapped in activity('custom') — blocks the "Checkout" button while the
409
+ * request is in flight.
401
410
  */
402
411
  attach: (request: SetOrderCustomerRequest) => Promise<void>;
403
412
  }
404
413
  /**
405
- * Работа с прикреплением клиента к заказу.
414
+ * Handles attaching a customer to the order.
406
415
  *
407
- * Используется в двух режимах OrderAuthenticationMethod:
408
- * - `Disabled` — гость заполняет phone+name, `attach` до `checkoutOrder`
409
- * - `Confirmation` — гость заполняет phone+name, после `checkoutOrder` придёт SMS
416
+ * Used in two OrderAuthenticationMethod modes:
417
+ * - `Disabled` — the guest fills in phone+name, `attach` runs before `checkoutOrder`
418
+ * - `Confirmation` — the guest fills in phone+name, an SMS arrives after `checkoutOrder`
410
419
  *
411
- * Для `Preauth` обычно не нужно — customer прикрепляется автоматически,
412
- * когда SDK имеет `api_token` клиента (см. `authStore`).
420
+ * Usually not needed for `Preauth` — the customer is attached automatically
421
+ * once the SDK has the client's `api_token` (see `authStore`).
413
422
  *
414
- * @param cache client-local кэш покупателя (реализация потребителя — localStorage).
423
+ * @param cache client-local customer cache (implemented by the consumer — localStorage).
415
424
  */
416
425
  declare function useCustomerAttach(cache: AttachedCustomerCache): CustomerAttachComposable;
417
426
 
418
427
  /**
419
- * Привязывает customer'а авторизованного юзера к текущему заказу.
428
+ * Attaches the authenticated user's customer record to the current order.
420
429
  *
421
- * Срабатывает в двух кейсах:
422
- * 1) Юзер залогинился (auth state изменилась) — `notifyOnPhoneChange = true`,
423
- * в этом сценарии возможно был анонимный customer с другим телефоном —
424
- * показываем тост, если телефон реально изменился.
425
- * 2) У авторизованного юзера появился новый заказ без customer'а
426
- * (например, после очистки корзины и добавления товара) — `notifyOnPhoneChange = false`,
427
- * тост не нужен, это безшумная синхронизация.
430
+ * Runs in two cases:
431
+ * 1) The user logged in (auth state changed) — `notifyOnPhoneChange = true`;
432
+ * there may have been an anonymous customer with a different phone, so we
433
+ * show a toast if the phone actually changed.
434
+ * 2) An authenticated user got a new order with no customer attached
435
+ * (e.g. after clearing the cart and adding a product) — `notifyOnPhoneChange = false`,
436
+ * no toast needed, this is a silent sync.
428
437
  *
429
- * @param cache client-local кэш покупателя (реализация потребителя — localStorage).
438
+ * @param cache client-local customer cache (implemented by the consumer — localStorage).
430
439
  */
431
440
  declare function useCartCustomerAttachment(cache: AttachedCustomerCache): void;
432
441
 
433
442
  interface CartStockWatcher {
434
443
  /**
435
- * Реагирует на смену склада в обновлённом заказе: переключает stock,
436
- * перегружает каталог при смене хэша и валидирует товары корзины.
444
+ * Reacts to a stock change in the updated order: switches the stock,
445
+ * reloads the catalog if the hash changed, and validates the cart items.
437
446
  */
438
447
  handleStockChange: (updatedOrder: Order) => Promise<void>;
439
448
  }
@@ -459,17 +468,16 @@ interface OrderDelivery {
459
468
  declare function useOrderDelivery(deps?: OrderDeliveryDeps): OrderDelivery;
460
469
 
461
470
  interface OrderPromocodeComposable {
462
- /** Применённый к заказу промокод (читается из cartStore.order.promocode) */
471
+ /** Promocode applied to the order (read from cartStore.order.promocode) */
463
472
  applied: ComputedRef<OrderPromocode | null>;
464
473
  isApplied: ComputedRef<boolean>;
465
474
  loading: Ref<boolean>;
466
- /** Сообщение об ошибке (невалидный / просрочен / не подходит к заказу) */
475
+ /** Error message (invalid / expired / doesn't apply to this order) */
467
476
  errorMessage: Ref<string | null>;
468
- /** Применить промокод. Обёрнуто в activity('promocode'). */
477
+ /** Applies the promocode. Wrapped in activity('promocode'). */
469
478
  apply: (code: string) => Promise<void>;
470
- /** Убрать ранее применённый промокод */
471
479
  remove: () => Promise<void>;
472
- /** Сбросить состояние ошибки (например, при редактировании поля) */
480
+ /** Resets the error state (e.g. when the field is being edited) */
473
481
  clearError: () => void;
474
482
  }
475
483
  interface OrderPromocodeDeps {
@@ -489,6 +497,7 @@ interface CartItemRequest {
489
497
  variantLabel?: string;
490
498
  promotionId?: string;
491
499
  promotionRewardId?: string;
500
+ recommendationsBlock?: RecommendationsBlock;
492
501
  }
493
502
  interface CartDependencies {
494
503
  notifier: Notifier;
@@ -504,32 +513,29 @@ interface CartOperations {
504
513
  }
505
514
  declare function useCartOperations(credentials: CartCredentials, initialization: CartInitialization, sdk: ZenkyStorefront, deps: CartDependencies): CartOperations;
506
515
 
507
- /** Провайдер reCAPTCHA-payload (реализация потребителя — Google reCAPTCHA v3). */
516
+ /** reCAPTCHA payload provider (implemented by the consumer app — Google reCAPTCHA v3). */
508
517
  type RecaptchaPayloadProvider = (action: RecaptchaAction) => Promise<{
509
518
  token: string;
510
519
  } | undefined>;
511
520
  interface CheckoutSubmitComposable {
512
- /** Последний результат `checkoutOrder` — нужен для UI (ConfirmationModal / online redirect) */
521
+ /** Last `checkoutOrder` result — needed by the UI (ConfirmationModal / online redirect) */
513
522
  result: Ref<OrderCheckoutResult | null>;
514
- /** Идёт ли сейчас submit */
515
523
  submitting: Ref<boolean>;
516
524
  /**
517
- * Отправить заказ.
518
- * Собирает `OrderCheckoutRequest` из `cartStore` (notes + persons_count).
519
- * Возвращает `OrderCheckoutResult` с флагами confirmation/online_payment.
525
+ * Collects `OrderCheckoutRequest` from `cartStore` (notes + persons_count).
526
+ * Returns `OrderCheckoutResult` with confirmation/online_payment flags.
520
527
  */
521
528
  submit: () => Promise<OrderCheckoutResult | null>;
522
- /** Подтвердить SMS-код (после checkoutOrder с confirmation.required) */
529
+ /** Confirm the SMS code (after checkoutOrder returned confirmation.required) */
523
530
  confirm: (code: string) => Promise<boolean>;
524
- /** Переотправить код (с backoff — должен следить UI) */
531
+ /** Resend the code (with backoff — the UI is responsible for that) */
525
532
  resendCode: () => Promise<boolean>;
526
- /** Отменить pending-заказ (cancelOrder) */
527
533
  cancel: () => Promise<boolean>;
528
534
  }
529
535
  /**
530
- * Финальный submit заказа + SMS-подтверждение.
536
+ * Final order submit + SMS confirmation.
531
537
  *
532
- * @param getRecaptchaPayload провайдер reCAPTCHA-токена (app-специфичен, инжектится).
538
+ * @param getRecaptchaPayload reCAPTCHA token provider (app-specific, injected).
533
539
  */
534
540
  declare function useCheckoutSubmit(getRecaptchaPayload: RecaptchaPayloadProvider): CheckoutSubmitComposable;
535
541
 
@@ -556,7 +562,7 @@ interface StorefrontCart {
556
562
  }
557
563
  declare function useStorefrontCart(): StorefrontCart;
558
564
 
559
- /** Данные товара для показа в модалке гейта (как строка корзины). */
565
+ /** Product data for display in the gate modal (shaped like a cart line). */
560
566
  interface RestrictionGateProduct {
561
567
  name: string;
562
568
  image: Media | null;
@@ -579,9 +585,10 @@ interface RestrictedAddToCart {
579
585
  declare function useRestrictedAddToCart(): RestrictedAddToCart;
580
586
 
581
587
  /**
582
- * Позиции корзины, видимые покупателю: серверное количество с учётом оптимистичной дельты.
583
- * Единый источник для списка, футера и подсветки — иначе блокировка чекаута, поиск
584
- * блокирующей позиции и реальный рендер списка могут разъехаться.
588
+ * Cart lines visible to the customer: server quantity adjusted by the optimistic
589
+ * delta. A single source for the list, footer, and highlighting — otherwise
590
+ * checkout blocking, finding the blocking line, and the actual rendered list
591
+ * could drift apart.
585
592
  */
586
593
  declare function useVisibleCartVariants(): ComputedRef<OrderProductVariant[]>;
587
594