@zappie/foundations 0.28.1 → 0.28.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/account/index.js +0 -1
  3. package/dist/account/zappie-account.js +0 -1
  4. package/dist/attribution/powered-by-zappie.js +0 -1
  5. package/dist/bag/index.d.ts +4 -0
  6. package/dist/bag/index.js +0 -1
  7. package/dist/bag/param.js +0 -1
  8. package/dist/bag/server.js +0 -1
  9. package/dist/branch-finder/index.d.ts +2 -0
  10. package/dist/branch-finder/index.js +0 -1
  11. package/dist/branch-list/index.d.ts +4 -0
  12. package/dist/branch-list/index.js +0 -1
  13. package/dist/branch-list/nearest.js +0 -1
  14. package/dist/branch-list/offers.js +0 -1
  15. package/dist/branch-map/colors.js +0 -1
  16. package/dist/branch-map/delivery-map.js +0 -1
  17. package/dist/branch-map/delivery-runtime.js +0 -1
  18. package/dist/branch-map/fit.js +0 -1
  19. package/dist/branch-map/geometry.js +0 -1
  20. package/dist/branch-map/index.js +0 -1
  21. package/dist/branch-map/loader.js +0 -1
  22. package/dist/branch-map/markers.js +0 -1
  23. package/dist/branch-map/runtime.js +0 -1
  24. package/dist/branch-map/use-map-runtime.js +0 -1
  25. package/dist/branch-switch/index.d.ts +20 -0
  26. package/dist/branch-switch/index.js +0 -1
  27. package/dist/cart/index.js +0 -1
  28. package/dist/checkout/attempt.js +0 -1
  29. package/dist/checkout/contact.js +0 -1
  30. package/dist/checkout/index.d.ts +108 -22
  31. package/dist/checkout/index.js +0 -1
  32. package/dist/checkout/markers.js +0 -1
  33. package/dist/checkout/offers.js +0 -1
  34. package/dist/checkout/pay-after-sign-in.js +0 -1
  35. package/dist/checkout/sign-in.js +0 -1
  36. package/dist/checkout/status.js +0 -1
  37. package/dist/checkout/timing.js +0 -1
  38. package/dist/checkout/use-checkout-flow.js +1 -2
  39. package/dist/{core-Cd-_zlQx.d.ts → core-Dd6qKwNT.d.ts} +4 -0
  40. package/dist/{countries-BLeLfxnY.d.ts → countries-B4B4-e2j.d.ts} +9 -1
  41. package/dist/deferred/index.js +0 -1
  42. package/dist/deferred/retry.js +0 -1
  43. package/dist/fulfilment/address-picker.js +0 -1
  44. package/dist/fulfilment/branch-picker.js +0 -1
  45. package/dist/fulfilment/schedule.js +0 -1
  46. package/dist/fulfilment/switch.js +0 -1
  47. package/dist/fulfilment/window.js +1 -2
  48. package/dist/hours/index.d.ts +16 -0
  49. package/dist/hours/index.js +0 -1
  50. package/dist/{index-B1mCF3ft.d.ts → index-iwUrGm5U.d.ts} +3 -0
  51. package/dist/index.d.ts +82 -8
  52. package/dist/index.js +0 -1
  53. package/dist/internal/combobox.js +0 -1
  54. package/dist/internal/data-attrs.js +0 -1
  55. package/dist/internal/ids.js +0 -1
  56. package/dist/internal/labelled-control.js +0 -1
  57. package/dist/internal/slot.js +0 -1
  58. package/dist/internal/use-controllable-state.js +0 -1
  59. package/dist/item-form/index.js +0 -1
  60. package/dist/item-form/option-group.js +0 -1
  61. package/dist/item-form/options.js +0 -1
  62. package/dist/item-form/quantity.js +0 -1
  63. package/dist/item-form/root.js +0 -1
  64. package/dist/item-sheet/index.d.ts +1 -0
  65. package/dist/item-sheet/index.js +0 -1
  66. package/dist/loyalty/index.d.ts +4 -0
  67. package/dist/loyalty/index.js +0 -1
  68. package/dist/media/image.js +0 -1
  69. package/dist/money.js +0 -1
  70. package/dist/next.js +0 -1
  71. package/dist/{offers-fDZ0bZ0i.d.ts → offers-BVmFttDd.d.ts} +7 -1
  72. package/dist/order/index.d.ts +36 -1
  73. package/dist/order/index.js +0 -1
  74. package/dist/order/model.js +0 -1
  75. package/dist/order/use-customer-order.js +0 -1
  76. package/dist/otp/input.js +0 -1
  77. package/dist/overlay/deferred-host.js +0 -1
  78. package/dist/overlay/drag-to-close.js +0 -1
  79. package/dist/overlay/drag.js +0 -1
  80. package/dist/overlay/engine.js +0 -1
  81. package/dist/overlay/history.js +0 -1
  82. package/dist/overlay/load.js +0 -1
  83. package/dist/overlay/react.js +0 -1
  84. package/dist/payment/methods.js +0 -1
  85. package/dist/phone/combobox.js +0 -1
  86. package/dist/phone/core.js +0 -1
  87. package/dist/phone/countries.d.ts +1 -1
  88. package/dist/phone/countries.js +0 -1
  89. package/dist/phone/country-data.js +0 -1
  90. package/dist/phone/index.d.ts +5 -2
  91. package/dist/phone/index.js +0 -1
  92. package/dist/phone/load.js +0 -1
  93. package/dist/phone/picker.js +0 -1
  94. package/dist/phone/use-phone-field.js +0 -1
  95. package/dist/rich-text/banners.js +0 -1
  96. package/dist/rich-text/browser.js +0 -1
  97. package/dist/rich-text/core.js +0 -1
  98. package/dist/rich-text/index.d.ts +1 -1
  99. package/dist/rich-text/index.js +0 -1
  100. package/dist/rich-text/string.js +0 -1
  101. package/dist/schedule/index.d.ts +1 -1
  102. package/dist/schedule/index.js +0 -1
  103. package/dist/search/engine.js +0 -1
  104. package/dist/search/index.js +0 -1
  105. package/dist/site/at-table.js +0 -1
  106. package/dist/site/category-spy.js +0 -1
  107. package/dist/site/closed.js +0 -1
  108. package/dist/site/customer/checkout-return.js +0 -1
  109. package/dist/site/customer/gate.js +0 -1
  110. package/dist/site/customer/index.d.ts +9 -1
  111. package/dist/site/customer/index.js +0 -1
  112. package/dist/site/index.d.ts +1 -1
  113. package/dist/site/index.js +0 -1
  114. package/dist/site/page-views.js +0 -1
  115. package/dist/site/server/closed.js +0 -1
  116. package/dist/site/server/context.js +0 -1
  117. package/dist/site/server/document.js +0 -1
  118. package/dist/site/server/index.d.ts +12 -3
  119. package/dist/site/server/index.js +0 -1
  120. package/dist/site/title.js +0 -1
  121. package/dist/status/contact.js +0 -1
  122. package/dist/status/hours.js +1 -2
  123. package/dist/status/open-status.js +0 -1
  124. package/dist/{title-CgphFqNB.d.ts → title-uNmu5FUl.d.ts} +2 -0
  125. package/dist/version.js +1 -2
  126. package/dist/{window-BtvnXLww.d.ts → window-ClzBXJAe.d.ts} +6 -0
  127. package/package.json +4 -4
  128. package/dist/account/index.js.map +0 -6
  129. package/dist/account/zappie-account.js.map +0 -6
  130. package/dist/attribution/powered-by-zappie.js.map +0 -6
  131. package/dist/bag/index.js.map +0 -6
  132. package/dist/bag/param.js.map +0 -6
  133. package/dist/bag/server.js.map +0 -6
  134. package/dist/branch-finder/index.js.map +0 -6
  135. package/dist/branch-list/index.js.map +0 -6
  136. package/dist/branch-list/nearest.js.map +0 -6
  137. package/dist/branch-list/offers.js.map +0 -6
  138. package/dist/branch-map/colors.js.map +0 -6
  139. package/dist/branch-map/delivery-map.js.map +0 -6
  140. package/dist/branch-map/delivery-runtime.js.map +0 -6
  141. package/dist/branch-map/fit.js.map +0 -6
  142. package/dist/branch-map/geometry.js.map +0 -6
  143. package/dist/branch-map/index.js.map +0 -6
  144. package/dist/branch-map/loader.js.map +0 -6
  145. package/dist/branch-map/markers.js.map +0 -6
  146. package/dist/branch-map/runtime.js.map +0 -6
  147. package/dist/branch-map/use-map-runtime.js.map +0 -6
  148. package/dist/branch-switch/index.js.map +0 -6
  149. package/dist/cart/index.js.map +0 -6
  150. package/dist/checkout/attempt.js.map +0 -6
  151. package/dist/checkout/contact.js.map +0 -6
  152. package/dist/checkout/index.js.map +0 -6
  153. package/dist/checkout/markers.js.map +0 -6
  154. package/dist/checkout/offers.js.map +0 -6
  155. package/dist/checkout/pay-after-sign-in.js.map +0 -6
  156. package/dist/checkout/sign-in.js.map +0 -6
  157. package/dist/checkout/status.js.map +0 -6
  158. package/dist/checkout/timing.js.map +0 -6
  159. package/dist/checkout/use-checkout-flow.js.map +0 -6
  160. package/dist/deferred/index.js.map +0 -6
  161. package/dist/deferred/retry.js.map +0 -6
  162. package/dist/fulfilment/address-picker.js.map +0 -6
  163. package/dist/fulfilment/branch-picker.js.map +0 -6
  164. package/dist/fulfilment/schedule.js.map +0 -6
  165. package/dist/fulfilment/switch.js.map +0 -6
  166. package/dist/fulfilment/window.js.map +0 -6
  167. package/dist/hours/index.js.map +0 -6
  168. package/dist/index.js.map +0 -6
  169. package/dist/internal/combobox.js.map +0 -6
  170. package/dist/internal/data-attrs.js.map +0 -6
  171. package/dist/internal/ids.js.map +0 -6
  172. package/dist/internal/labelled-control.js.map +0 -6
  173. package/dist/internal/slot.js.map +0 -6
  174. package/dist/internal/use-controllable-state.js.map +0 -6
  175. package/dist/item-form/index.js.map +0 -6
  176. package/dist/item-form/option-group.js.map +0 -6
  177. package/dist/item-form/options.js.map +0 -6
  178. package/dist/item-form/quantity.js.map +0 -6
  179. package/dist/item-form/root.js.map +0 -6
  180. package/dist/item-sheet/index.js.map +0 -6
  181. package/dist/loyalty/index.js.map +0 -6
  182. package/dist/media/image.js.map +0 -6
  183. package/dist/money.js.map +0 -6
  184. package/dist/next.js.map +0 -6
  185. package/dist/order/index.js.map +0 -6
  186. package/dist/order/model.js.map +0 -6
  187. package/dist/order/use-customer-order.js.map +0 -6
  188. package/dist/otp/input.js.map +0 -6
  189. package/dist/overlay/deferred-host.js.map +0 -6
  190. package/dist/overlay/drag-to-close.js.map +0 -6
  191. package/dist/overlay/drag.js.map +0 -6
  192. package/dist/overlay/engine.js.map +0 -6
  193. package/dist/overlay/history.js.map +0 -6
  194. package/dist/overlay/load.js.map +0 -6
  195. package/dist/overlay/react.js.map +0 -6
  196. package/dist/payment/methods.js.map +0 -6
  197. package/dist/phone/combobox.js.map +0 -6
  198. package/dist/phone/core.js.map +0 -6
  199. package/dist/phone/countries.js.map +0 -6
  200. package/dist/phone/country-data.js.map +0 -6
  201. package/dist/phone/index.js.map +0 -6
  202. package/dist/phone/load.js.map +0 -6
  203. package/dist/phone/picker.js.map +0 -6
  204. package/dist/phone/use-phone-field.js.map +0 -6
  205. package/dist/rich-text/banners.js.map +0 -6
  206. package/dist/rich-text/browser.js.map +0 -6
  207. package/dist/rich-text/core.js.map +0 -6
  208. package/dist/rich-text/index.js.map +0 -6
  209. package/dist/rich-text/string.js.map +0 -6
  210. package/dist/schedule/index.js.map +0 -6
  211. package/dist/search/engine.js.map +0 -6
  212. package/dist/search/index.js.map +0 -6
  213. package/dist/site/at-table.js.map +0 -6
  214. package/dist/site/category-spy.js.map +0 -6
  215. package/dist/site/closed.js.map +0 -6
  216. package/dist/site/customer/checkout-return.js.map +0 -6
  217. package/dist/site/customer/gate.js.map +0 -6
  218. package/dist/site/customer/index.js.map +0 -6
  219. package/dist/site/index.js.map +0 -6
  220. package/dist/site/page-views.js.map +0 -6
  221. package/dist/site/server/closed.js.map +0 -6
  222. package/dist/site/server/context.js.map +0 -6
  223. package/dist/site/server/document.js.map +0 -6
  224. package/dist/site/server/index.js.map +0 -6
  225. package/dist/site/title.js.map +0 -6
  226. package/dist/status/contact.js.map +0 -6
  227. package/dist/status/hours.js.map +0 -6
  228. package/dist/status/open-status.js.map +0 -6
  229. package/dist/version.js.map +0 -6
@@ -1,13 +1,15 @@
1
1
  import { CartModule, CheckoutField, CheckoutCustomer as CheckoutCustomer$1, CartIssue, CartState, Money, Branch, Menu, CartLine, CartFulfilment, DeliveryAddress, Quote, CartFix } from '@zappie/sdk';
2
2
  import { CheckoutRequest, CheckoutClient } from '@zappie/sdk/checkout';
3
- import { C as CheckoutMode } from '../offers-fDZ0bZ0i.js';
4
- export { c as checkoutOffers } from '../offers-fDZ0bZ0i.js';
3
+ import { C as CheckoutMode } from '../offers-BVmFttDd.js';
4
+ export { c as checkoutOffers } from '../offers-BVmFttDd.js';
5
5
  import { CustomerClient } from '@zappie/sdk/customer';
6
6
 
7
7
  type Payload = ReturnType<CartModule["toCheckoutPayload"]>;
8
8
  /** One checkout request and the idempotency key it keeps while its payload stays the same. */
9
9
  type CheckoutAttempt = {
10
+ /** The idempotency key to open the session with. A random UUID, kept while the payload, phone and name stay the same. */
10
11
  key: string;
12
+ /** The checkout session request to send, built from the cart's payload, contact and return URLs. */
11
13
  request: CheckoutRequest;
12
14
  };
13
15
  /**
@@ -35,15 +37,27 @@ declare function createCheckoutAttempt(): (input: {
35
37
  * required or optional.
36
38
  */
37
39
  type ContactField = {
40
+ /** The field's key, such as `given_name`, `family_name` or `email`. It keys the shopper's values and problems. */
38
41
  key: string;
42
+ /** The label the business gave the field, to show beside the control. */
39
43
  label: string;
44
+ /**
45
+ * What the field holds, which sets its input type and how it is checked. `text` takes any text.
46
+ * `email` must read as an email address. `tel` must read as a valid phone number.
47
+ * `businessContactFields` gives only `text` and `email`.
48
+ */
40
49
  type: "text" | "email" | "tel";
50
+ /** Whether Pay stays blocked while the field is empty. */
41
51
  required: boolean;
42
52
  };
43
53
  /** What the shopper typed in each contact field, by its key. */
44
54
  type ContactValues = Readonly<Record<string, string>>;
45
55
  /** Why a contact detail stops Pay: it is empty and required, or it doesn't read as valid. */
46
- type ContactProblem = "missing" | "invalid";
56
+ type ContactProblem =
57
+ /** The detail is required and the shopper left it empty. */
58
+ "missing"
59
+ /** The shopper typed something that doesn't read as valid for the field. */
60
+ | "invalid";
47
61
  /**
48
62
  * The number to send: the shopper's own international number, or a local number typed without
49
63
  * its dial code, with any leading 0 dropped.
@@ -66,8 +80,11 @@ declare function fullPhone(typed: string, dialCode?: string): string;
66
80
  declare function contactProblems(fields: readonly ContactField[], values: ContactValues, phone: string, accountPhone?: string, dialCode?: string): Record<string, ContactProblem>;
67
81
  /** What the shopper typed for the person an order is for, when they order for someone else. */
68
82
  type RecipientDraft = {
83
+ /** Whether the shopper switched on ordering for someone else. While off, the name and phone are ignored. */
69
84
  on: boolean;
85
+ /** The other person's name as typed. At most 100 characters once trimmed. */
70
86
  name: string;
87
+ /** The other person's phone as typed. A local number takes the dial code. */
71
88
  phone: string;
72
89
  };
73
90
  /**
@@ -97,11 +114,14 @@ declare function checkoutCustomer(fields: readonly ContactField[], values: Conta
97
114
 
98
115
  /** The attributes that mark an issue's element, so a `fix_issues` step can find it. */
99
116
  type IssueMarker = {
117
+ /** The issue's code. */
100
118
  "data-zappie-issue": string;
119
+ /** The id of the cart line the issue belongs to. Left out when the issue is not about one line. */
101
120
  "data-zappie-issue-line"?: string;
102
121
  };
103
122
  /** The attribute that marks a contact field's control, so a `contact` step can find it. */
104
123
  type FieldMarker = {
124
+ /** `phone` for the phone, else the business field's key. */
105
125
  "data-zappie-field": string;
106
126
  };
107
127
  /**
@@ -131,34 +151,61 @@ declare function fieldMarker(key: string): FieldMarker;
131
151
  */
132
152
  declare function fieldSelector(key: string): string;
133
153
 
134
- /**
135
- * What the one Pay button does now, in precedence order: the first that applies wins.
136
- *
137
- * - `busy`: payment or sign-in is opening. Disabled until the page unloads.
138
- * - `empty`: the cart has no lines. Disabled.
139
- * - `checking`: the cart hasn't hydrated or the session isn't known yet. Disabled.
140
- * - `closed`: the branch takes no order now or ahead. Disabled.
141
- * - `address`, `area`, `time`: enabled. A press asks for that step.
142
- * - `fix_issues`: enabled. A press points at the first blocking issue.
143
- * - `sign_in`: enabled, only when the business requires a customer for this order.
144
- * - `phone`, `contact`: enabled. A press points at the first invalid field.
145
- * - `quoting`: disabled while the total updates.
146
- * - `retry`: enabled. A press asks for the total again.
147
- * - `pay`: enabled. A press opens payment.
148
- */
149
- type CheckoutStatus = "busy" | "empty" | "checking" | "closed" | "address" | "area" | "time" | "fix_issues" | "sign_in" | "phone" | "contact" | "quoting" | "retry" | "pay";
154
+ /** What the one Pay button does now, in precedence order. The first value that applies wins. */
155
+ type CheckoutStatus =
156
+ /** Payment or sign-in is opening. Disabled until the page unloads. */
157
+ "busy"
158
+ /** The cart has no lines. Disabled. */
159
+ | "empty"
160
+ /** The cart hasn't hydrated or the session isn't known yet. Disabled. */
161
+ | "checking"
162
+ /** The branch takes no order now or ahead. Disabled. */
163
+ | "closed"
164
+ /** Enabled. A press asks for the delivery address. */
165
+ | "address"
166
+ /** Enabled. A press asks for the delivery area. */
167
+ | "area"
168
+ /** Enabled. A press asks for a time. */
169
+ | "time"
170
+ /** Enabled. A press points at the first blocking issue. */
171
+ | "fix_issues"
172
+ /** Enabled, only when the business requires a customer for this order. */
173
+ | "sign_in"
174
+ /** Enabled. A press points at the invalid phone. */
175
+ | "phone"
176
+ /** Enabled. A press points at the first invalid contact field. */
177
+ | "contact"
178
+ /** Disabled while the total updates. */
179
+ | "quoting"
180
+ /** Enabled. A press asks for the total again. */
181
+ | "retry"
182
+ /** Enabled. A press opens payment. */
183
+ | "pay";
150
184
  /** Whether the shopper's session has been checked yet, and its answer. */
151
- type CheckoutAuth = "unknown" | "authenticated" | "anonymous";
185
+ type CheckoutAuth =
186
+ /** The session hasn't been checked yet. Pay stays at `checking`. */
187
+ "unknown"
188
+ /** A customer is signed in. */
189
+ | "authenticated"
190
+ /** No customer is signed in. The shopper pays as a guest. */
191
+ | "anonymous";
152
192
  /** What decides the Pay button's status. */
153
193
  type CheckoutStatusInput = {
194
+ /** Payment or sign-in is opening. */
154
195
  busy: boolean;
196
+ /** The cart has loaded from storage. */
155
197
  hydrated: boolean;
198
+ /** How many lines the cart has. */
156
199
  lines: number;
200
+ /** Whether the session is known, and whether a customer is signed in. */
157
201
  auth: CheckoutAuth;
202
+ /** The branch takes no order now or ahead. */
158
203
  closed: boolean;
159
204
  /** Delivery is chosen and the cart has no address for it. */
160
205
  needsAddress: boolean;
206
+ /** The order can't be placed for now and the shopper hasn't chosen a time. */
161
207
  needsTime: boolean;
208
+ /** The cart's state, with its quote and issues. */
162
209
  state: CartState;
163
210
  /** The last quote request for this cart failed. */
164
211
  quoteFailed: boolean;
@@ -293,7 +340,13 @@ type CheckoutAccount = {
293
340
  * A failure the template words: the total couldn't be priced, payment couldn't open, or a
294
341
  * sign-in came back without a session the site can use.
295
342
  */
296
- type CheckoutFlowError = "quote_failed" | "open_failed" | "sign_in_failed";
343
+ type CheckoutFlowError =
344
+ /** The last request for the total failed. Pay offers `retry`. */
345
+ "quote_failed"
346
+ /** Opening payment failed, such as for an in-venue order, which checkout sessions don't take yet. */
347
+ | "open_failed"
348
+ /** The shopper came back from sign-in without a session the site can use. */
349
+ | "sign_in_failed";
297
350
  /** The customer client methods the flow reads. */
298
351
  type CheckoutCustomer = Pick<CustomerClient, "state" | "customer" | "onChange" | "addresses" | "session" | "profile">;
299
352
  /** Where the checkout flow reads its branch and how it leaves the page. */
@@ -352,11 +405,20 @@ type CheckoutContact = {
352
405
  phone: string;
353
406
  /** The phone payment receives, with its dial code, or empty to use the account's. */
354
407
  contactPhone: string;
408
+ /** Sets the phone as typed and keeps it in session storage. */
355
409
  setPhone(phone: string): void;
356
410
  /** The signed-in customer's masked phone, used when the shopper types none. */
357
411
  accountPhone?: string | undefined;
412
+ /** The contact fields to ask beside the phone. Leaves out those in `held`. */
358
413
  fields: readonly ContactField[];
414
+ /** What the shopper typed in each field, by its key. */
359
415
  values: ContactValues;
416
+ /**
417
+ * Sets what the shopper typed in one field and keeps it in session storage.
418
+ *
419
+ * @param key - The field's key.
420
+ * @param value - The value as typed.
421
+ */
360
422
  setField(key: string, value: string): void;
361
423
  /** What stops Pay, by key, with `phone` for the phone. */
362
424
  problems: Readonly<Record<string, ContactProblem>>;
@@ -369,12 +431,16 @@ type CheckoutContact = {
369
431
  recipient?: CheckoutRecipient | undefined;
370
432
  /** The keys whose problem the template shows: blurred fields, and all of them after Pay. */
371
433
  shown: ReadonlySet<string>;
434
+ /** Marks a field's problem as shown, such as when the field loses focus. `phone` for the phone. */
372
435
  show(key: string): void;
373
436
  };
374
437
  /** A checkout field the customer's account already holds. */
375
438
  type HeldContact = {
439
+ /** The checkout field's key, such as `given_name` or `email`. */
376
440
  key: string;
441
+ /** The label the business gave the field. */
377
442
  label: string;
443
+ /** What the account holds for it, trimmed. */
378
444
  value: string;
379
445
  };
380
446
  /**
@@ -385,20 +451,29 @@ type HeldContact = {
385
451
  type CheckoutRecipient = {
386
452
  /** `Deliver to` on a delivery, `Collected by` on a pickup. */
387
453
  label: "Deliver to" | "Collected by";
454
+ /** Whether the shopper is ordering for someone else. */
388
455
  on: boolean;
456
+ /** Turns ordering for someone else on or off, and keeps it in session storage. */
389
457
  setOn(on: boolean): void;
390
458
  /** Their name as typed. Its problem is keyed `recipient_name`. */
391
459
  name: string;
460
+ /** Sets their name as typed, and keeps it in session storage. */
392
461
  setName(name: string): void;
393
462
  /** Their phone as typed. Its problem is keyed `recipient_phone`. */
394
463
  phone: string;
464
+ /** Sets their phone as typed, and keeps it in session storage. */
395
465
  setPhone(phone: string): void;
396
466
  };
397
467
  /** The one Pay button: its status, whether it takes a press, and what a press does. */
398
468
  type CheckoutPay = {
469
+ /** What the button does now. See `CheckoutStatus`. */
399
470
  status: CheckoutStatus;
471
+ /** Whether the button takes a press in this status. */
400
472
  enabled: boolean;
401
- /** Where a `busy` button is going. */
473
+ /**
474
+ * Where a `busy` button is going. `payment` while payment opens. `sign_in` while the shopper
475
+ * leaves to sign in. Undefined in any other status.
476
+ */
402
477
  leavingFor?: "payment" | "sign_in" | undefined;
403
478
  /** The issue `fix_issues` points at. */
404
479
  issue?: CartIssue | undefined;
@@ -417,9 +492,11 @@ type CheckoutFlow = {
417
492
  * `@zappie/sdk/display`.
418
493
  */
419
494
  mode: CheckoutMode;
495
+ /** The modes to offer the shopper, in the order to show them. */
420
496
  offers: readonly CheckoutMode[];
421
497
  /** Chooses how the order arrives. Returns the address step when delivery has no known address. */
422
498
  choose(mode: CheckoutMode): CheckoutIntent | undefined;
499
+ /** The cart's delivery, with its address, area and rider note. Undefined unless delivery is chosen and the cart holds an address. */
423
500
  delivery?: CheckoutDelivery | undefined;
424
501
  /**
425
502
  * Changes the address, area and rider note in one step, and chooses delivery. A new address is
@@ -440,14 +517,19 @@ type CheckoutFlow = {
440
517
  setRegion(regionId: string): CheckoutIntent | undefined;
441
518
  /** Sets the rider note. Returns the address step when there is no address yet. */
442
519
  setNote(note: string): CheckoutIntent | undefined;
520
+ /** The chosen time, as an ISO 8601 instant. Undefined for as soon as possible and for an in-venue order. */
443
521
  scheduledFor?: string | undefined;
444
522
  /** Chooses a time, or now with `null`. */
445
523
  schedule(at: string | null): void;
524
+ /** How the bag can be timed: now, later, or not at all. */
446
525
  timing: CheckoutTiming;
526
+ /** The shopper's contact details and what stops Pay among them. */
447
527
  contact: CheckoutContact;
528
+ /** Whether the session is known yet, and whether a customer is signed in. */
448
529
  auth: CheckoutAuth;
449
530
  /** The signed-in customer, such as for "Signed in as Ada". Undefined for a guest. */
450
531
  account?: CheckoutAccount | undefined;
532
+ /** The cart's latest quote, with its total and issues. Undefined until the cart is priced. */
451
533
  quote?: Quote | undefined;
452
534
  /** Whether the total is being updated. */
453
535
  pricing: boolean;
@@ -463,14 +545,18 @@ type CheckoutFlow = {
463
545
  issues: readonly CartIssue[];
464
546
  /** Applies an issue's fix, or returns the step the template shows for it. */
465
547
  fix(issue: CartIssue, action: CartFix): CheckoutIntent | undefined;
548
+ /** The last failure, for the template to word. Cleared by the next Pay press. */
466
549
  error?: CheckoutFlowError | undefined;
550
+ /** Clears `error`. */
467
551
  clearError(): void;
468
552
  /**
469
553
  * Why a return from "Sign in to pay" stays on the cart. Without one, payment opens by itself.
470
554
  * Word it beside Pay.
471
555
  */
472
556
  notice?: CheckoutNotice | undefined;
557
+ /** Clears `notice`. */
473
558
  clearNotice(): void;
559
+ /** The one Pay button. */
474
560
  pay: CheckoutPay;
475
561
  };
476
562
  /**
@@ -1,2 +1 @@
1
1
  "use client";import{createCheckoutAttempt}from"./attempt.js";import{businessContactFields,checkoutCustomer,contactProblems,fullPhone,recipientProblems}from"./contact.js";import{fieldMarker,fieldSelector,issueMarker,issueSelector}from"./markers.js";import{checkoutOffers}from"./offers.js";import{signInOnce}from"./sign-in.js";import{checkoutStatus,firstIssue,isCheckoutFieldIssue,payEnabled}from"./status.js";import{checkoutTiming,mustSchedule}from"./timing.js";import{useCheckoutFlow}from"./use-checkout-flow.js";export{businessContactFields,checkoutCustomer,checkoutOffers,checkoutStatus,checkoutTiming,contactProblems,createCheckoutAttempt,fieldMarker,fieldSelector,firstIssue,fullPhone,isCheckoutFieldIssue,issueMarker,issueSelector,mustSchedule,payEnabled,recipientProblems,signInOnce,useCheckoutFlow};
2
- //# sourceMappingURL=index.js.map
@@ -1,2 +1 @@
1
1
  var quoted=value=>`"${value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;function issueMarker(issue){const marker={"data-zappie-issue":issue.code};if(issue.lineId){marker["data-zappie-issue-line"]=issue.lineId}return marker}function issueSelector(issue){const code=`[data-zappie-issue=${quoted(issue.code)}]`;return issue.lineId?`${code}[data-zappie-issue-line=${quoted(issue.lineId)}]`:code}function fieldMarker(key){return{"data-zappie-field":key}}function fieldSelector(key){return`[data-zappie-field=${quoted(key)}]`}export{fieldMarker,fieldSelector,issueMarker,issueSelector};
2
- //# sourceMappingURL=markers.js.map
@@ -1,2 +1 @@
1
1
  var MODES=["delivery","pickup","dine_in"];var takes=(branch,mode)=>mode==="dine_in"?branch.fulfilment.dineIn:branch.fulfilment[mode];function checkoutOffers(branch,menu){const listed=menu?.menus?.flatMap(section=>section.fulfilment??[]);return MODES.filter(mode=>takes(branch,mode)&&(!listed||listed.length===0||listed.includes(mode)))}export{checkoutOffers};
2
- //# sourceMappingURL=offers.js.map
@@ -1,2 +1 @@
1
1
  import{money}from"@zappie/sdk";var PAY_PARAM="zappie_pay";var PAY_MS=10*6e4;var UNAVAILABLE=["item_unavailable","item_not_found","option_unavailable"];function payPath(path){const url=new URL(path,"https://pay.invalid");url.searchParams.set(PAY_PARAM,"1");return`${url.pathname}${url.search}${url.hash}`}function cartIdentity(branchId,lines,promoCode){return JSON.stringify([branchId,promoCode,lines.map(({unitPrice:_u,lineSubtotal:_s,addedAt:_a,name:_n,...line})=>line)])}function takePaymentIntent(key){let stored=null;try{stored=sessionStorage.getItem(key);sessionStorage.removeItem(key)}catch{}const[navigation]=performance.getEntriesByType("navigation");const marked=new URL(navigation?.name||location.href,location.href).searchParams.has(PAY_PARAM);const url=new URL(location.href);if(url.searchParams.has(PAY_PARAM)){url.searchParams.delete(PAY_PARAM);history.replaceState(history.state,"",url)}try{const intent=JSON.parse(stored??"null");return intent&&marked&&intent.at<performance.timeOrigin&&Date.now()-intent.at<PAY_MS&&navigation?.type!=="back_forward"?intent:void 0}catch{return void 0}}function paymentNotice(intent,now){if(now.cart!==intent.cart){return{reason:"cart_changed"}}const gone=now.issues.find(issue=>UNAVAILABLE.includes(issue.code));if(gone){return{reason:"unavailable",issue:gone}}if(now.status!=="pay"||!now.total){return{reason:"needs_action",issue:now.issues.find(issue=>issue.severity==="blocking")??now.issues[0]}}const before=intent.total;if(now.total.amountMinor!==before.amountMinor||now.total.currency!==before.currency){return{reason:"total_changed",before:money(before.amountMinor,before.currency),after:now.total}}return void 0}export{cartIdentity,payPath,paymentNotice,takePaymentIntent};
2
- //# sourceMappingURL=pay-after-sign-in.js.map
@@ -1,2 +1 @@
1
1
  var ATTEMPT_KEY="zappie:sign-in";var ATTEMPT_MS=10*6e4;function returnedFromSignIn(path){const attempt=sessionStorage.getItem(ATTEMPT_KEY)??"";const space=attempt.indexOf(" ");const at=Number(attempt.slice(0,space));const[navigation]=performance.getEntriesByType("navigation");return space>0&&attempt.slice(space+1)===path&&at<performance.timeOrigin&&Date.now()-at<ATTEMPT_MS&&navigation?.type!=="back_forward"}function signInOnce(path){try{if(returnedFromSignIn(path)){sessionStorage.removeItem(ATTEMPT_KEY);return false}sessionStorage.setItem(ATTEMPT_KEY,`${Date.now()} ${path}`)}catch{}window.location.assign(`/_zappie/login?return=${encodeURIComponent(path)}`);return true}export{signInOnce};
2
- //# sourceMappingURL=sign-in.js.map
@@ -1,2 +1 @@
1
1
  var ENABLED=new Set(["address","area","time","fix_issues","sign_in","phone","contact","retry","pay"]);function payEnabled(status){return ENABLED.has(status)}function quoteOf(state){return"quote"in state?state.quote:void 0}function firstIssue(state){const issues=state.status==="needs_attention"?state.issues:quoteOf(state)?.issues??[];const cart=issues.filter(issue=>!isCheckoutFieldIssue(issue));return cart.find(issue=>issue.severity==="blocking")??cart[0]}function isCheckoutFieldIssue(issue){return issue.code==="checkout_field_required"||issue.code==="checkout_field_invalid"}function checkoutStatus(input){const{state}=input;if(input.busy){return"busy"}if(input.hydrated&&input.lines===0){return"empty"}if(!input.hydrated||input.auth==="unknown"){return"checking"}if(input.closed){return"closed"}if(input.needsAddress){return"address"}const quote=quoteOf(state);const issues=(state.status==="needs_attention"?state.issues:quote?.issues??[]).filter(issue=>!isCheckoutFieldIssue(issue));const fieldsOnly=quote!==void 0&&quote.issues.some(isCheckoutFieldIssue);if(issues.some(issue=>issue.code==="delivery_region_required")){return"area"}if(input.needsTime){return"time"}if(issues.some(issue=>issue.severity==="blocking")||state.status==="needs_attention"&&issues.length>0||quote&&!fieldsOnly&&(!quote.canCheckout||quote.checkout.reason==="issues")){return"fix_issues"}if(input.signInRequired||quote?.checkout.reason==="customer_required"){return"sign_in"}if(input.contactField!==void 0){return input.contactField==="phone"?"phone":"contact"}if(state.status==="quoting"){return"quoting"}if(input.quoteFailed||state.status==="needs_attention"&&!quote){return"retry"}if(quote){return"pay"}return"quoting"}export{checkoutStatus,firstIssue,isCheckoutFieldIssue,payEnabled};
2
- //# sourceMappingURL=status.js.map
@@ -1,2 +1 @@
1
1
  import{canOrderAhead}from"../status/hours.js";function mustSchedule(menu,lines){const sections=menu?.menus??[];const notice=id=>{const schedule=sections.find(section=>section.id===id)?.schedule;return Boolean(schedule?.preorder&&(schedule.preorderNoticeHours??0)>0)};return lines.some(line=>{const menus=line.menuId?[line.menuId]:sections.filter(section=>section.categoryIds.some(categoryId=>menu?.categories.find(category=>category.id===categoryId)?.itemIds.includes(line.itemId))).map(section=>section.id);return menus.length>0&&menus.every(notice)})}function checkoutTiming(branch,menu,lines,scheduledFor){const ahead=canOrderAhead(branch);const notice=mustSchedule(menu,lines);const canNow=branch.isOpen&&!notice;const closed=!branch.isOpen&&!ahead;const opensAt=branch.isOpen?void 0:branch.closedUntil??branch.nextChangeAt;return{ahead,notice,canNow,closed,needsTime:ahead&&!canNow&&!scheduledFor,...opensAt?{opensAt}:{}}}export{checkoutTiming,mustSchedule};
2
- //# sourceMappingURL=timing.js.map
@@ -1,2 +1 @@
1
- "use client";import{holdsForLater,isHeldQuote}from"@zappie/sdk";import{CheckoutError,createCheckout}from"@zappie/sdk/checkout";import{defaultRegion,prefillFulfilment,rememberAddress,rememberedAddress,watchCheckoutDefaults}from"@zappie/sdk/checkout-defaults";import{createCustomer}from"@zappie/sdk/customer";import{holdPerks}from"@zappie/sdk/loyalty";import{usePendingNavigation}from"@zappie/sdk/navigation/react";import{useCart}from"@zappie/sdk/react";import{redirectToCheckout}from"@zappie/sdk/redirect";import{countEvent,currentSource}from"@zappie/sdk/visits";import{useCallback,useEffect,useMemo,useRef,useState}from"react";import{createCheckoutAttempt}from"./attempt.js";import{businessContactFields,checkoutCustomer,contactProblems,fullPhone,recipientProblems}from"./contact.js";import{fieldSelector,issueSelector}from"./markers.js";import{checkoutOffers}from"./offers.js";import{cartIdentity,paymentNotice,payPath,takePaymentIntent}from"./pay-after-sign-in.js";import{signInOnce}from"./sign-in.js";import{checkoutStatus,firstIssue,isCheckoutFieldIssue,payEnabled}from"./status.js";import{checkoutTiming}from"./timing.js";function readSession(key){try{return window.sessionStorage.getItem(key)}catch{return null}}function writeSession(key,value){try{window.sessionStorage.setItem(key,value)}catch{}}function removeSession(key){try{window.sessionStorage.removeItem(key)}catch{}}var aborted=failure=>failure instanceof Error&&failure.name==="AbortError";var NO_FIELDS=[];var NO_VALUES={};var NO_RECIPIENT={on:false,name:"",phone:""};function profileValues(me){const values={};for(const[key,value]of[["given_name",me.given_name],["family_name",me.family_name],["email",me.email]]){if(value?.trim()){values[key]=value.trim()}}return values}var LISTED_BY_DEFAULT=["delivery","pickup"];var accountOf=person=>person?{name:person.given_name,phone:person.phone_masked}:void 0;function useCheckoutFlow(options){const{branch,menu,contactFields:givenFields=NO_FIELDS,reviewPath="/checkout",dialCode="+234",storageKey="zappie:checkout"}=options;const cart=useCart();const checkout=useMemo(()=>options.checkout??createCheckout(),[options.checkout]);const customer=useMemo(()=>options.customer??createCustomer(),[options.customer]);const owned=options.customer===void 0;const attempt=useMemo(()=>createCheckoutAttempt(),[]);const leaving=usePendingNavigation();const[auth,setAuth]=useState("unknown");const[who,setWho]=useState();const[account,setAccount]=useState();const[profile,setProfile]=useState();const[defaults,setDefaults]=useState();const[phone,setPhoneState]=useState("");const[values,setValues]=useState({});const[recipient,setRecipient]=useState(NO_RECIPIENT);const[shown,setShown]=useState(new Set);const[error,setError]=useState();const[signInRequired,setSignInRequired]=useState(false);const[leavingFor,setLeavingFor]=useState();const[failedKey,setFailedKey]=useState();const[notice,setNotice]=useState();const[defaultsFor,setDefaultsFor]=useState();const payKey=`${storageKey}.pay`;const paying=useRef(void 0);const payRead=useRef(false);useEffect(()=>{if(!payRead.current){payRead.current=true;paying.current=takePaymentIntent(payKey)}},[payKey]);const listed=options.offers??LISTED_BY_DEFAULT;const listedKey=listed.join();const offers=useMemo(()=>{const taken=checkoutOffers(branch,menu);return listed.filter(type=>taken.includes(type))},[branch,menu,listedKey]);const branchId=cart.branchId??branch.id;const fulfilment=cart.fulfilment;const[chosen,setChosen]=useState();const initial=options.initialMode&&offers.includes(options.initialMode)?options.initialMode:offers[0]??"pickup";const mode=chosen??(fulfilment&&offers.includes(fulfilment.type)?fulfilment.type:initial);const asking=options.checkoutFields!==void 0;const storeFieldsKey=asking?JSON.stringify(options.checkoutFields):"";const asked=useMemo(()=>asking?businessContactFields(options.checkoutFields,branchId,mode):givenFields,[asking,storeFieldsKey,branchId,mode,givenFields]);const holds=profile&&profile.of===who?profile.values:NO_VALUES;const held=asked.flatMap(field=>holds[field.key]?[{key:field.key,label:field.label,value:holds[field.key]}]:[]);const heldKey=held.map(entry=>entry.key).join();const contactFields=useMemo(()=>asked.filter(field=>!heldKey.split(",").includes(field.key)),[asked,heldKey]);const[pendingAt,setPendingAt]=useState();const delivery=mode==="delivery"&&fulfilment?.type==="delivery"?fulfilment:void 0;const scheduledFor=mode==="dine_in"?void 0:(fulfilment&&fulfilment.type!=="dine_in"&&fulfilment.type===mode?fulfilment.scheduledFor:void 0)??pendingAt;const latest=useRef(delivery);latest.current=delivery;useEffect(()=>{const ownerKey=`${storageKey}.owner`;const owner=readSession(ownerKey);if(owner&&owner!==who){if(who!==void 0){for(const key of[ownerKey,`${storageKey}.phone`,`${storageKey}.contact`,`${storageKey}.recipient`]){removeSession(key)}}setPhoneState("");setValues({});setRecipient(NO_RECIPIENT);return}if(who){writeSession(ownerKey,who)}setPhoneState(readSession(`${storageKey}.phone`)??"");try{setValues(JSON.parse(readSession(`${storageKey}.contact`)??"{}"))}catch{setValues({})}try{setRecipient({...NO_RECIPIENT,...JSON.parse(readSession(`${storageKey}.recipient`)??"{}")})}catch{setRecipient(NO_RECIPIENT)}},[storageKey,who]);const read=useRef({branch,fulfilment});read.current={branch,fulfilment};useEffect(()=>{const stopDefaults=watchCheckoutDefaults(customer,()=>read.current,next=>{setDefaults(next);setDefaultsFor(customer.state==="authenticated"?customer.customer?.id:customer.state==="anonymous"?null:void 0)});const stopAuth=customer.onChange((state,person)=>{setAuth(state);setAccount(state==="authenticated"?accountOf(person):void 0);setWho(state==="authenticated"?person?.id??void 0:state==="anonymous"?null:void 0)});void customer.session().then(current=>{setAuth(current?"authenticated":"anonymous");setAccount(accountOf(current));setWho(current?.id??null)},()=>{setAuth("anonymous");setAccount(void 0)});return()=>{stopDefaults();stopAuth();if(owned&&"dispose"in customer){customer.dispose()}}},[customer,owned]);const asksAny=asking&&asked.length>0;useEffect(()=>{if(!asksAny||!who){return}let current=true;customer.profile().then(me=>{if(current){setProfile({of:who,values:profileValues(me)})}},()=>void 0);return()=>{current=false}},[asksAny,who,customer]);useEffect(()=>{if(!cart.isHydrated||cart.lines.length===0||mode==="delivery"||fulfilment?.type===mode){return}cart.actions.setFulfilment(mode==="dine_in"?{type:"dine_in",branchId}:{type:"pickup",branchId,...pendingAt?{scheduledFor:pendingAt}:{}})},[branchId,cart.actions,cart.isHydrated,cart.lines.length,fulfilment?.type,mode,pendingAt]);const pendingDelivery=mode==="delivery"&&fulfilment?.type!=="delivery";useEffect(()=>{cart.actions.setPendingFulfilment(pendingDelivery?{type:"delivery",scheduledFor:pendingAt}:null)},[cart.actions,pendingDelivery,pendingAt]);const awaiting=useRef(false);const writeDelivery=useCallback((patch,at=scheduledFor)=>{const current=latest.current;const address=patch.address??current?.address;if(!address?.line1){return false}const regionId=defaultRegion(branch,patch.deliveryRegionId??current?.deliveryRegionId);const next={type:"delivery",branchId,address,...regionId?{deliveryRegionId:regionId}:{},...at?{scheduledFor:at}:{}};latest.current=next;awaiting.current=false;setChosen("delivery");cart.actions.setFulfilment(next);return true},[branch,branchId,cart.actions,scheduledFor]);const prefilled=useRef(void 0);useEffect(()=>{if(!cart.isHydrated||cart.lines.length===0){return}const filled=prefillFulfilment(fulfilment,branch);if(filled&&filled!==fulfilment){cart.actions.setFulfilment(filled);return}if(awaiting.current&&who!==void 0&&mode==="delivery"&&fulfilment?.type!=="delivery"){const known=rememberedAddress({customerId:who})??defaults?.address;if(known){writeDelivery({address:known})}return}const address=defaults?.address;if(mode==="delivery"&&!fulfilment&&address&&prefilled.current!==address){prefilled.current=address;writeDelivery({address})}},[branch,cart.actions,cart.isHydrated,cart.lines.length,defaults?.address,fulfilment,mode,who,writeDelivery]);const quoteKey=JSON.stringify([cart.lines,fulfilment,cart.promoCode]);const quoted=useRef("");useEffect(()=>{if(cart.isHydrated&&cart.lines.length>0&&cart.state.status==="ready"&&quoted.current!==quoteKey){quoted.current=quoteKey;void cart.actions.quote().then(()=>{setFailedKey(void 0);setError(current=>current==="quote_failed"?void 0:current)},failure=>{if(!aborted(failure)){setFailedKey(quoteKey);setError("quote_failed")}})}},[cart.actions,cart.isHydrated,cart.lines.length,cart.state.status,quoteKey]);const timing=checkoutTiming(branch,menu,cart.lines,scheduledFor);const quote="quote"in cart.state?cart.state.quote:void 0;const heldQuote=isHeldQuote(quote);const unquotedTime=Boolean(scheduledFor)&&!quote?.fulfilment?.scheduledFor;const issues=useMemo(()=>{const cartIssues=cart.issues.filter(issue2=>!isCheckoutFieldIssue(issue2));return timing.ahead?unquotedTime?cartIssues.filter(issue2=>!holdsForLater(issue2)):cartIssues:cartIssues.map(issue2=>holdsForLater(issue2)?{...issue2,fixes:issue2.fixes.filter(entry=>entry.action!=="schedule")}:issue2)},[cart.issues,timing.ahead,unquotedTime]);const accountPhone=defaults?.phone.fromAccount?defaults.phone.display:void 0;const forOther=mode!=="dine_in"&&recipient.on;const problems=contactProblems(contactFields,values,phone,accountPhone,dialCode);if(forOther){delete problems.phone;Object.assign(problems,recipientProblems(recipient,dialCode))}const quotedField=cart.issues.map(issue2=>isCheckoutFieldIssue(issue2)?issue2.data?.field:void 0).find(field=>typeof field==="string");const contactField=Object.keys(problems)[0]??quotedField;const sending=asking?checkoutCustomer(contactFields,values):null;const sendingKey=JSON.stringify(sending);useEffect(()=>{if(asking){cart.actions.setCustomer(sending)}},[asking,sendingKey,cart.actions]);const contactPhone=forOther?fullPhone(recipient.phone,dialCode):phone.trim()?fullPhone(phone,dialCode):"";const status=checkoutStatus({busy:leaving.pending,hydrated:cart.isHydrated,lines:cart.lines.length,auth,closed:timing.closed,needsAddress:mode==="delivery"&&!delivery?.address.line1,needsTime:mode!=="dine_in"&&timing.needsTime,state:cart.state,quoteFailed:failedKey===quoteKey,signInRequired,contactField});const shopper=()=>customer.state==="authenticated"?customer.customer?.id??void 0:customer.state==="anonymous"?null:void 0;const choose=type=>{setChosen(type);awaiting.current=false;if(type==="delivery"&&fulfilment?.type!=="delivery"){setPendingAt(scheduledFor);const owner=shopper();const known=(owner===void 0?void 0:rememberedAddress({customerId:owner}))??defaults?.address;if(known){writeDelivery({address:known},scheduledFor);return void 0}awaiting.current=true;return{step:"address"}}return void 0};const setDelivery=(change,{remember=true}={})=>{const base=change.address??latest.current?.address;if(!base?.line1){return{step:"address"}}const typed=change.note??change.address?.instructions??latest.current?.address.instructions;const{instructions:_old,...rest}=base;const note=typed?.trim();writeDelivery({address:note?{...rest,instructions:note}:rest,...change.regionId!==void 0?{deliveryRegionId:change.regionId}:{}});const owner=shopper();if(change.address&&remember&&owner!==void 0){rememberAddress(change.address,void 0,owner)}return void 0};const setAddress=(address,options2={})=>{setDelivery({address},options2)};const setRegion=regionId=>latest.current?setDelivery({regionId}):{step:"address"};const setNote=note=>latest.current?setDelivery({note}):{step:"address"};const schedule=at=>{setPendingAt(at??void 0);if(!fulfilment||fulfilment.type==="dine_in"||fulfilment.type!==mode){return}const{scheduledFor:_old,...rest}=fulfilment;cart.actions.setFulfilment(at?{...rest,scheduledFor:at}:rest)};const fix=(issue2,action)=>{setError(void 0);switch(action.action){case"change_address":return{step:"address"};case"choose_region":return{step:"area"};case"schedule":return{step:"time"};case"switch_fulfilment":{const next=action.types.find(type=>type!==mode&&offers.includes(type))??(mode==="delivery"?"pickup":"delivery");return choose(next)}case"choose_option":case"choose_other_option":{const line=cart.lines.find(entry=>entry.id===issue2.lineId);return line?{step:"item",itemId:line.itemId,lineId:line.id}:void 0}default:cart.actions.applyFix(cart.issues.find(entry=>entry.code===issue2.code&&entry.lineId===issue2.lineId&&entry.message===issue2.message)??issue2,action);return void 0}};const signIn=options.signIn??signInOnce;const leaveToSignIn=()=>{setLeavingFor("sign_in");if(quote){writeSession(payKey,JSON.stringify({at:Date.now(),cart:cartIdentity(branchId,cart.lines,cart.promoCode),total:quote.total}))}if(!signIn(payPath(reviewPath))){removeSession(payKey);leaving.end();setError("sign_in_failed")}};const keepRecipient=change=>setRecipient(current=>{const next={...current,...change};writeSession(`${storageKey}.recipient`,JSON.stringify(next));return next});const redirect=options.redirect??(url=>redirectToCheckout(url,window.top??window));const attribution=options.attribution??currentSource;const openPayment=async()=>{setLeavingFor("payment");try{const prepared=attempt({payload:cart.actions.toCheckoutPayload(),branchId,contactPhone,contactName:forOther?recipient.name:"",returnUrl:`${location.origin}/checkout/return`,cancelUrl:`${location.origin}${reviewPath}`,attribution:attribution()});const session=await checkout.open(prepared.request,prepared.key);holdPerks(prepared.request.perk_redemption_ids,session);redirect(session.url)}catch(failure){if(failure instanceof CheckoutError&&failure.apiCode==="customer_required"){setSignInRequired(true);leaveToSignIn();return}leaving.end();if(failure instanceof CheckoutError&&failure.apiCode==="quote_issues"&&failure.param?.startsWith("customer.")){const key=failure.param.slice("customer.".length);setShown(current=>new Set([...current,key]));void cart.actions.quote({force:true}).catch(()=>void 0);return}setError("open_failed")}};const retry=async()=>{setFailedKey(void 0);try{await cart.actions.quote({force:true});setError(void 0)}catch(failure){if(!aborted(failure)){setFailedKey(quoteKey);setError("quote_failed")}}};const issue=status==="fix_issues"?firstIssue(cart.state):void 0;const activate=async()=>{setError(void 0);setNotice(void 0);switch(status){case"address":return{step:"address"};case"area":return{step:"area"};case"time":return{step:"time"};case"fix_issues":{const target=issue??issues[0];return target?{step:"issue",issue:target,target:issueSelector(target)}:void 0}case"phone":case"contact":setShown(current=>new Set([...current,...Object.keys(problems)]));return contactField?{step:"contact",field:contactField,target:fieldSelector(contactField)}:void 0;case"retry":await retry();return void 0;case"sign_in":countEvent("checkout");await leaving.start(leaveToSignIn);return void 0;case"pay":countEvent("checkout");await leaving.start(openPayment);return void 0;default:return void 0}};useEffect(()=>{const intent=paying.current;if(!intent||auth==="unknown"){return}if(auth==="authenticated"&&status!=="empty"&&(defaultsFor!==who||cart.state.status==="ready"||status==="checking"||status==="quoting"||status==="busy")){return}paying.current=void 0;if(auth==="anonymous"){return}const found=paymentNotice(intent,{cart:cartIdentity(branchId,cart.lines,cart.promoCode),total:quote?.total,status,issues});if(found){setNotice(found);return}countEvent("checkout");void leaving.start(openPayment)});return{mode,offers,choose,delivery,setDelivery,setAddress,setRegion,setNote,scheduledFor,schedule,timing,contact:{phone,contactPhone,setPhone:value=>{setPhoneState(value);writeSession(`${storageKey}.phone`,value)},accountPhone,fields:contactFields,held,values,setField:(key,value)=>{setValues(current=>{const next={...current,[key]:value};writeSession(`${storageKey}.contact`,JSON.stringify(next));return next})},recipient:mode==="dine_in"?void 0:{label:mode==="pickup"?"Collected by":"Deliver to",...recipient,setOn:on=>keepRecipient({on}),setName:name=>keepRecipient({name}),setPhone:value=>keepRecipient({phone:value})},problems,shown,show:key=>setShown(current=>current.has(key)?current:new Set([...current,key]))},auth,account,quote,pricing:cart.state.status==="quoting",held:heldQuote?timing.ahead?"time":"opening":void 0,issues,fix,error,clearError:()=>setError(void 0),notice,clearNotice:()=>setNotice(void 0),pay:{status,enabled:payEnabled(status),leavingFor:status==="busy"?leavingFor:void 0,issue,field:status==="phone"||status==="contact"?contactField:void 0,activate}}}export{useCheckoutFlow};
2
- //# sourceMappingURL=use-checkout-flow.js.map
1
+ "use client";import{holdsForLater,isHeldQuote}from"@zappie/sdk";import{CheckoutError,createCheckout}from"@zappie/sdk/checkout";import{defaultRegion,prefillFulfilment,rememberAddress,rememberedAddress,watchCheckoutDefaults}from"@zappie/sdk/checkout-defaults";import{createCustomer}from"@zappie/sdk/customer";import{holdPerks}from"@zappie/sdk/loyalty";import{usePendingNavigation}from"@zappie/sdk/navigation/react";import{useCart}from"@zappie/sdk/react";import{redirectToCheckout}from"@zappie/sdk/redirect";import{countEvent,currentSource}from"@zappie/sdk/visits";import{useCallback,useEffect,useMemo,useRef,useState}from"react";import{createCheckoutAttempt}from"./attempt.js";import{businessContactFields,checkoutCustomer,contactProblems,fullPhone,recipientProblems}from"./contact.js";import{fieldSelector,issueSelector}from"./markers.js";import{checkoutOffers}from"./offers.js";import{cartIdentity,paymentNotice,payPath,takePaymentIntent}from"./pay-after-sign-in.js";import{signInOnce}from"./sign-in.js";import{checkoutStatus,firstIssue,isCheckoutFieldIssue,payEnabled}from"./status.js";import{checkoutTiming}from"./timing.js";function readSession(key){try{return window.sessionStorage.getItem(key)}catch{return null}}function writeSession(key,value){try{window.sessionStorage.setItem(key,value)}catch{}}function removeSession(key){try{window.sessionStorage.removeItem(key)}catch{}}var aborted=failure=>failure instanceof Error&&failure.name==="AbortError";var NO_FIELDS=[];var NO_VALUES={};var NO_RECIPIENT={on:false,name:"",phone:""};function profileValues(me){const values={};for(const[key,value]of[["given_name",me.given_name],["family_name",me.family_name],["email",me.email]]){if(value?.trim()){values[key]=value.trim()}}return values}var LISTED_BY_DEFAULT=["delivery","pickup"];var accountOf=person=>person?{name:person.given_name,phone:person.phone_masked}:void 0;function useCheckoutFlow(options){const{branch,menu,contactFields:givenFields=NO_FIELDS,reviewPath="/checkout",dialCode="+234",storageKey="zappie:checkout"}=options;const cart=useCart();const checkout=useMemo(()=>options.checkout??createCheckout(),[options.checkout]);const customer=useMemo(()=>options.customer??createCustomer(),[options.customer]);const owned=options.customer===void 0;const attempt=useMemo(()=>createCheckoutAttempt(),[]);const leaving=usePendingNavigation();const[auth,setAuth]=useState("unknown");const[who,setWho]=useState();const[account,setAccount]=useState();const[profile,setProfile]=useState();const[defaults,setDefaults]=useState();const[phone,setPhoneState]=useState("");const[values,setValues]=useState({});const[recipient,setRecipient]=useState(NO_RECIPIENT);const[shown,setShown]=useState(new Set);const[error,setError]=useState();const[signInRequired,setSignInRequired]=useState(false);const[leavingFor,setLeavingFor]=useState();const[failedKey,setFailedKey]=useState();const[notice,setNotice]=useState();const[defaultsFor,setDefaultsFor]=useState();const payKey=`${storageKey}.pay`;const paying=useRef(void 0);const payRead=useRef(false);useEffect(()=>{if(!payRead.current){payRead.current=true;paying.current=takePaymentIntent(payKey)}},[payKey]);const listed=options.offers??LISTED_BY_DEFAULT;const listedKey=listed.join();const offers=useMemo(()=>{const taken=checkoutOffers(branch,menu);return listed.filter(type=>taken.includes(type))},[branch,menu,listedKey]);const branchId=cart.branchId??branch.id;const fulfilment=cart.fulfilment;const[chosen,setChosen]=useState();const initial=options.initialMode&&offers.includes(options.initialMode)?options.initialMode:offers[0]??"pickup";const mode=chosen??(fulfilment&&offers.includes(fulfilment.type)?fulfilment.type:initial);const asking=options.checkoutFields!==void 0;const storeFieldsKey=asking?JSON.stringify(options.checkoutFields):"";const asked=useMemo(()=>asking?businessContactFields(options.checkoutFields,branchId,mode):givenFields,[asking,storeFieldsKey,branchId,mode,givenFields]);const holds=profile&&profile.of===who?profile.values:NO_VALUES;const held=asked.flatMap(field=>holds[field.key]?[{key:field.key,label:field.label,value:holds[field.key]}]:[]);const heldKey=held.map(entry=>entry.key).join();const contactFields=useMemo(()=>asked.filter(field=>!heldKey.split(",").includes(field.key)),[asked,heldKey]);const[pendingAt,setPendingAt]=useState();const delivery=mode==="delivery"&&fulfilment?.type==="delivery"?fulfilment:void 0;const scheduledFor=mode==="dine_in"?void 0:(fulfilment&&fulfilment.type!=="dine_in"&&fulfilment.type===mode?fulfilment.scheduledFor:void 0)??pendingAt;const latest=useRef(delivery);latest.current=delivery;useEffect(()=>{const ownerKey=`${storageKey}.owner`;const owner=readSession(ownerKey);if(owner&&owner!==who){if(who!==void 0){for(const key of[ownerKey,`${storageKey}.phone`,`${storageKey}.contact`,`${storageKey}.recipient`]){removeSession(key)}}setPhoneState("");setValues({});setRecipient(NO_RECIPIENT);return}if(who){writeSession(ownerKey,who)}setPhoneState(readSession(`${storageKey}.phone`)??"");try{setValues(JSON.parse(readSession(`${storageKey}.contact`)??"{}"))}catch{setValues({})}try{setRecipient({...NO_RECIPIENT,...JSON.parse(readSession(`${storageKey}.recipient`)??"{}")})}catch{setRecipient(NO_RECIPIENT)}},[storageKey,who]);const read=useRef({branch,fulfilment});read.current={branch,fulfilment};useEffect(()=>{const stopDefaults=watchCheckoutDefaults(customer,()=>read.current,next=>{setDefaults(next);setDefaultsFor(customer.state==="authenticated"?customer.customer?.id:customer.state==="anonymous"?null:void 0)});const stopAuth=customer.onChange((state,person)=>{setAuth(state);setAccount(state==="authenticated"?accountOf(person):void 0);setWho(state==="authenticated"?person?.id??void 0:state==="anonymous"?null:void 0)});void customer.session().then(current=>{setAuth(current?"authenticated":"anonymous");setAccount(accountOf(current));setWho(current?.id??null)},()=>{setAuth("anonymous");setAccount(void 0)});return()=>{stopDefaults();stopAuth();if(owned&&"dispose"in customer){customer.dispose()}}},[customer,owned]);const asksAny=asking&&asked.length>0;useEffect(()=>{if(!asksAny||!who){return}let current=true;customer.profile().then(me=>{if(current){setProfile({of:who,values:profileValues(me)})}},()=>void 0);return()=>{current=false}},[asksAny,who,customer]);useEffect(()=>{if(!cart.isHydrated||cart.lines.length===0||mode==="delivery"||fulfilment?.type===mode){return}cart.actions.setFulfilment(mode==="dine_in"?{type:"dine_in",branchId}:{type:"pickup",branchId,...pendingAt?{scheduledFor:pendingAt}:{}})},[branchId,cart.actions,cart.isHydrated,cart.lines.length,fulfilment?.type,mode,pendingAt]);const pendingDelivery=mode==="delivery"&&fulfilment?.type!=="delivery";useEffect(()=>{cart.actions.setPendingFulfilment(pendingDelivery?{type:"delivery",scheduledFor:pendingAt}:null)},[cart.actions,pendingDelivery,pendingAt]);const awaiting=useRef(false);const writeDelivery=useCallback((patch,at=scheduledFor)=>{const current=latest.current;const address=patch.address??current?.address;if(!address?.line1){return false}const regionId=defaultRegion(branch,patch.deliveryRegionId??current?.deliveryRegionId);const next={type:"delivery",branchId,address,...regionId?{deliveryRegionId:regionId}:{},...at?{scheduledFor:at}:{}};latest.current=next;awaiting.current=false;setChosen("delivery");cart.actions.setFulfilment(next);return true},[branch,branchId,cart.actions,scheduledFor]);const prefilled=useRef(void 0);useEffect(()=>{if(!cart.isHydrated||cart.lines.length===0){return}const filled=prefillFulfilment(fulfilment,branch);if(filled&&filled!==fulfilment){cart.actions.setFulfilment(filled);return}if(awaiting.current&&who!==void 0&&mode==="delivery"&&fulfilment?.type!=="delivery"){const known=rememberedAddress({customerId:who})??defaults?.address;if(known){writeDelivery({address:known})}return}const address=defaults?.address;if(mode==="delivery"&&!fulfilment&&address&&prefilled.current!==address){prefilled.current=address;writeDelivery({address})}},[branch,cart.actions,cart.isHydrated,cart.lines.length,defaults?.address,fulfilment,mode,who,writeDelivery]);const quoteKey=JSON.stringify([cart.lines,fulfilment,cart.promoCode]);const quoted=useRef("");useEffect(()=>{if(cart.isHydrated&&cart.lines.length>0&&cart.state.status==="ready"&&quoted.current!==quoteKey){quoted.current=quoteKey;void cart.actions.quote().then(()=>{setFailedKey(void 0);setError(current=>current==="quote_failed"?void 0:current)},failure=>{if(!aborted(failure)){setFailedKey(quoteKey);setError("quote_failed")}})}},[cart.actions,cart.isHydrated,cart.lines.length,cart.state.status,quoteKey]);const timing=checkoutTiming(branch,menu,cart.lines,scheduledFor);const quote="quote"in cart.state?cart.state.quote:void 0;const heldQuote=isHeldQuote(quote);const unquotedTime=Boolean(scheduledFor)&&!quote?.fulfilment?.scheduledFor;const issues=useMemo(()=>{const cartIssues=cart.issues.filter(issue2=>!isCheckoutFieldIssue(issue2));return timing.ahead?unquotedTime?cartIssues.filter(issue2=>!holdsForLater(issue2)):cartIssues:cartIssues.map(issue2=>holdsForLater(issue2)?{...issue2,fixes:issue2.fixes.filter(entry=>entry.action!=="schedule")}:issue2)},[cart.issues,timing.ahead,unquotedTime]);const accountPhone=defaults?.phone.fromAccount?defaults.phone.display:void 0;const forOther=mode!=="dine_in"&&recipient.on;const problems=contactProblems(contactFields,values,phone,accountPhone,dialCode);if(forOther){delete problems.phone;Object.assign(problems,recipientProblems(recipient,dialCode))}const quotedField=cart.issues.map(issue2=>isCheckoutFieldIssue(issue2)?issue2.data?.field:void 0).find(field=>typeof field==="string");const contactField=Object.keys(problems)[0]??quotedField;const sending=asking?checkoutCustomer(contactFields,values):null;const sendingKey=JSON.stringify(sending);useEffect(()=>{if(asking){cart.actions.setCustomer(sending)}},[asking,sendingKey,cart.actions]);const contactPhone=forOther?fullPhone(recipient.phone,dialCode):phone.trim()?fullPhone(phone,dialCode):"";const status=checkoutStatus({busy:leaving.pending,hydrated:cart.isHydrated,lines:cart.lines.length,auth,closed:timing.closed,needsAddress:mode==="delivery"&&!delivery?.address.line1,needsTime:mode!=="dine_in"&&timing.needsTime,state:cart.state,quoteFailed:failedKey===quoteKey,signInRequired,contactField});const shopper=()=>customer.state==="authenticated"?customer.customer?.id??void 0:customer.state==="anonymous"?null:void 0;const choose=type=>{setChosen(type);awaiting.current=false;if(type==="delivery"&&fulfilment?.type!=="delivery"){setPendingAt(scheduledFor);const owner=shopper();const known=(owner===void 0?void 0:rememberedAddress({customerId:owner}))??defaults?.address;if(known){writeDelivery({address:known},scheduledFor);return void 0}awaiting.current=true;return{step:"address"}}return void 0};const setDelivery=(change,{remember=true}={})=>{const base=change.address??latest.current?.address;if(!base?.line1){return{step:"address"}}const typed=change.note??change.address?.instructions??latest.current?.address.instructions;const{instructions:_old,...rest}=base;const note=typed?.trim();writeDelivery({address:note?{...rest,instructions:note}:rest,...change.regionId!==void 0?{deliveryRegionId:change.regionId}:{}});const owner=shopper();if(change.address&&remember&&owner!==void 0){rememberAddress(change.address,void 0,owner)}return void 0};const setAddress=(address,options2={})=>{setDelivery({address},options2)};const setRegion=regionId=>latest.current?setDelivery({regionId}):{step:"address"};const setNote=note=>latest.current?setDelivery({note}):{step:"address"};const schedule=at=>{setPendingAt(at??void 0);if(!fulfilment||fulfilment.type==="dine_in"||fulfilment.type!==mode){return}const{scheduledFor:_old,...rest}=fulfilment;cart.actions.setFulfilment(at?{...rest,scheduledFor:at}:rest)};const fix=(issue2,action)=>{setError(void 0);switch(action.action){case"change_address":return{step:"address"};case"choose_region":return{step:"area"};case"schedule":return{step:"time"};case"fill_field":setShown(current=>new Set([...current,action.field]));return{step:"contact",field:action.field,target:fieldSelector(action.field)};case"switch_fulfilment":{const next=action.types.find(type=>type!==mode&&offers.includes(type))??(mode==="delivery"?"pickup":"delivery");return choose(next)}case"choose_option":case"choose_other_option":{const line=cart.lines.find(entry=>entry.id===issue2.lineId);return line?{step:"item",itemId:line.itemId,lineId:line.id}:void 0}default:cart.actions.applyFix(cart.issues.find(entry=>entry.code===issue2.code&&entry.lineId===issue2.lineId&&entry.message===issue2.message)??issue2,action);return void 0}};const signIn=options.signIn??signInOnce;const leaveToSignIn=()=>{setLeavingFor("sign_in");if(quote){writeSession(payKey,JSON.stringify({at:Date.now(),cart:cartIdentity(branchId,cart.lines,cart.promoCode),total:quote.total}))}if(!signIn(payPath(reviewPath))){removeSession(payKey);leaving.end();setError("sign_in_failed")}};const keepRecipient=change=>setRecipient(current=>{const next={...current,...change};writeSession(`${storageKey}.recipient`,JSON.stringify(next));return next});const redirect=options.redirect??(url=>redirectToCheckout(url,window.top??window));const attribution=options.attribution??currentSource;const openPayment=async()=>{setLeavingFor("payment");try{const prepared=attempt({payload:cart.actions.toCheckoutPayload(),branchId,contactPhone,contactName:forOther?recipient.name:"",returnUrl:`${location.origin}/checkout/return`,cancelUrl:`${location.origin}${reviewPath}`,attribution:attribution()});const session=await checkout.open(prepared.request,prepared.key);holdPerks(prepared.request.perk_redemption_ids,session);redirect(session.url)}catch(failure){if(failure instanceof CheckoutError&&failure.apiCode==="customer_required"){setSignInRequired(true);leaveToSignIn();return}leaving.end();if(failure instanceof CheckoutError&&failure.apiCode==="quote_issues"&&failure.param?.startsWith("customer.")){const key=failure.param.slice("customer.".length);setShown(current=>new Set([...current,key]));void cart.actions.quote({force:true}).catch(()=>void 0);return}setError("open_failed")}};const retry=async()=>{setFailedKey(void 0);try{await cart.actions.quote({force:true});setError(void 0)}catch(failure){if(!aborted(failure)){setFailedKey(quoteKey);setError("quote_failed")}}};const issue=status==="fix_issues"?firstIssue(cart.state):void 0;const activate=async()=>{setError(void 0);setNotice(void 0);switch(status){case"address":return{step:"address"};case"area":return{step:"area"};case"time":return{step:"time"};case"fix_issues":{const target=issue??issues[0];return target?{step:"issue",issue:target,target:issueSelector(target)}:void 0}case"phone":case"contact":setShown(current=>new Set([...current,...Object.keys(problems)]));return contactField?{step:"contact",field:contactField,target:fieldSelector(contactField)}:void 0;case"retry":await retry();return void 0;case"sign_in":countEvent("checkout");await leaving.start(leaveToSignIn);return void 0;case"pay":countEvent("checkout");await leaving.start(openPayment);return void 0;default:return void 0}};useEffect(()=>{const intent=paying.current;if(!intent||auth==="unknown"){return}if(auth==="authenticated"&&status!=="empty"&&(defaultsFor!==who||cart.state.status==="ready"||status==="checking"||status==="quoting"||status==="busy")){return}paying.current=void 0;if(auth==="anonymous"){return}const found=paymentNotice(intent,{cart:cartIdentity(branchId,cart.lines,cart.promoCode),total:quote?.total,status,issues});if(found){setNotice(found);return}countEvent("checkout");void leaving.start(openPayment)});return{mode,offers,choose,delivery,setDelivery,setAddress,setRegion,setNote,scheduledFor,schedule,timing,contact:{phone,contactPhone,setPhone:value=>{setPhoneState(value);writeSession(`${storageKey}.phone`,value)},accountPhone,fields:contactFields,held,values,setField:(key,value)=>{setValues(current=>{const next={...current,[key]:value};writeSession(`${storageKey}.contact`,JSON.stringify(next));return next})},recipient:mode==="dine_in"?void 0:{label:mode==="pickup"?"Collected by":"Deliver to",...recipient,setOn:on=>keepRecipient({on}),setName:name=>keepRecipient({name}),setPhone:value=>keepRecipient({phone:value})},problems,shown,show:key=>setShown(current=>current.has(key)?current:new Set([...current,key]))},auth,account,quote,pricing:cart.state.status==="quoting",held:heldQuote?timing.ahead?"time":"opening":void 0,issues,fix,error,clearError:()=>setError(void 0),notice,clearNotice:()=>setNotice(void 0),pay:{status,enabled:payEnabled(status),leavingFor:status==="busy"?leavingFor:void 0,issue,field:status==="phone"||status==="contact"?contactField:void 0,activate}}}export{useCheckoutFlow};
@@ -2,9 +2,13 @@
2
2
  * A parser-neutral rich-text node containing its type, optional tag name, text and children.
3
3
  */
4
4
  type ParsedRichTextNode = {
5
+ /** The node's kind. `text` is text, `comment` and `directive` are dropped, and any other kind is read as an element. */
5
6
  type: string;
7
+ /** The element's tag name, such as `p`, in any case. Left out for text. */
6
8
  name?: string;
9
+ /** The text of a `text` node. */
7
10
  data?: string;
11
+ /** The element's child nodes, in order. */
8
12
  children?: ParsedRichTextNode[];
9
13
  };
10
14
  /**
@@ -21,7 +21,15 @@ type PhoneCountry = {
21
21
  keepsZero?: boolean;
22
22
  };
23
23
  /** The four markets Zappie runs in. */
24
- type PhoneMarketCode = "NG" | "GH" | "KE" | "ZA";
24
+ type PhoneMarketCode =
25
+ /** Nigeria, dial code 234. */
26
+ "NG"
27
+ /** Ghana, dial code 233. */
28
+ | "GH"
29
+ /** Kenya, dial code 254. */
30
+ | "KE"
31
+ /** South Africa, dial code 27. */
32
+ | "ZA";
25
33
  /** An ISO country code. The four markets are spelled out so an editor offers them first. */
26
34
  type PhoneCountryCode = PhoneMarketCode | (string & {});
27
35
  /** What a phone number's digits add up to for its country. */
@@ -1,2 +1 @@
1
1
  "use client";import{Fragment,useEffect,useMemo,useState}from"react";import{OverlayRetry}from"./retry.js";import{jsx}from"react/jsx-runtime";function component(value){if(typeof value==="object"&&value!==null&&"default"in value&&!("$$typeof"in value)){return value.default}return value}var ignore=()=>{};function deferred(load){let loaded;let pending;const waiting=new Set;const preload=()=>{if(loaded){return Promise.resolve(loaded)}if(!pending){const attempt=new Promise(resolve=>resolve(load())).then(component).then(result=>{loaded=result;for(const notify of waiting){notify(result)}return result},error=>{if(pending===attempt){pending=void 0}throw error});attempt.catch(ignore);pending=attempt}return pending};const preloadWhenIdle=(options={})=>{if(typeof window==="undefined"||loaded){return ignore}const start=()=>{preload().catch(ignore)};if(typeof window.requestIdleCallback==="function"){const handle2=window.requestIdleCallback(start,options.timeout===void 0?void 0:{timeout:options.timeout});return()=>window.cancelIdleCallback(handle2)}const handle=window.setTimeout(start,options.timeout??1);return()=>window.clearTimeout(handle)};function DeferredComponent({fallback=null,failed,...props}){const{open}=props;const[ready,setReady]=useState(()=>loaded);const[opened,setOpened]=useState(open);const[failure,setFailure]=useState(false);const[startedOpen]=useState(open);const[retries,setRetries]=useState(0);if(open&&!opened){setOpened(true)}const Loaded=ready??loaded;useEffect(()=>{if(Loaded){return}const notify=value=>setReady(()=>value);waiting.add(notify);return()=>{waiting.delete(notify)}},[Loaded]);useEffect(()=>{if(!open||Loaded){return}let active=true;setFailure(false);preload().then(value=>{if(active){setReady(()=>value)}},()=>{if(active){setFailure(true)}});return()=>{active=false}},[open,Loaded,retries]);if(!(open||opened)){return null}if(!Loaded){if(!open){return null}if(failure==="closed"){return null}if(!failure){return jsx(Fragment,{children:fallback})}const retry=()=>setRetries(count=>count+1);const close=()=>{setFailure("closed");const{onOpenChange,onClose}=props;if(typeof onOpenChange==="function"){onOpenChange(false)}else if(typeof onClose==="function"){onClose()}};return jsx(Fragment,{children:failed?failed(retry,close):jsx(OverlayRetry,{retry,close,focus:!startedOpen})})}return jsx(Loaded,{...props})}DeferredComponent.displayName="Deferred";return{preload,preloadWhenIdle,Component:DeferredComponent}}function useIntentPreload(target){return useMemo(()=>{const start=()=>{target.preload().catch(ignore)};return{onPointerEnter:start,onPointerDown:start,onFocus:start}},[target])}export{deferred,useIntentPreload};
2
- //# sourceMappingURL=index.js.map
@@ -1,2 +1 @@
1
1
  "use client";import{useEffect,useRef}from"react";import{jsx,jsxs}from"react/jsx-runtime";function OverlayRetry({message="This didn't load.",retry,close,focus=true,className}){const button=useRef(null);useEffect(()=>{if(focus){button.current?.focus()}},[focus]);const onKeyDown=event=>{if(event.key==="Escape"){close()}};return jsxs("p",{role:"alert",className,"data-zappie-region":"Retry notice",children:[jsx("span",{children:message})," ",jsx("button",{ref:button,type:"button",onClick:retry,onKeyDown,children:"Try again"})," ",jsx("button",{type:"button",onClick:close,onKeyDown,children:"Close"})]})}export{OverlayRetry};
2
- //# sourceMappingURL=retry.js.map
@@ -1,2 +1 @@
1
1
  "use client";import{createContext,forwardRef,useContext,useEffect,useState}from"react";import{countAnnouncement,useCombobox,withLiveRegion}from"../internal/combobox.js";import{composeRefs,part}from"../internal/slot.js";import{useControllableState}from"../internal/use-controllable-state.js";import{jsx}from"react/jsx-runtime";var Context=/*@__PURE__ */createContext(null);function useAddress(){const ctx=useContext(Context);if(!ctx){throw new Error("Address parts require Address.Picker")}return ctx}function Picker({getSuggestions,onSelect,query,defaultQuery="",onQueryChange,debounceMs=200,announcement=countAnnouncement,...props}){const[value,setValue]=useControllableState({value:query,defaultValue:defaultQuery,onChange:onQueryChange});const[response,setResponse]=useState({query:"",suggestions:[],status:"ready"});const suggestions=response.query===value?response.suggestions:[];const combo=useCombobox(suggestions,suggestion=>{setValue(suggestion.label);onSelect(suggestion)});useEffect(()=>{if(!value.trim()){setResponse({query:value,suggestions:[],status:"ready"});return}let live=true;const abort=new AbortController;setResponse({query:value,suggestions:[],status:"loading"});const timer=setTimeout(()=>{void Promise.resolve().then(()=>getSuggestions(value,abort.signal)).then(items=>{if(live){setResponse({query:value,suggestions:items,status:"ready"})}},error=>{if(live){setResponse({query:value,suggestions:[],status:"error",error})}})},debounceMs);return()=>{live=false;abort.abort();clearTimeout(timer)}},[value,getSuggestions,debounceMs]);const setQuery=next=>{setValue(next);combo.setOpen(true);combo.setActiveIndex(-1)};const state={...combo,query:value,setQuery,suggestions,status:response.status,error:response.error};return jsx(Context.Provider,{value:state,children:part("div",withLiveRegion(props,combo.isOpen&&value.trim()&&response.status==="ready"?announcement(suggestions.length):""),state,{"data-state":response.status==="error"?"invalid":response.status==="loading"?"loading":"valid",onBlur:event=>{if(!event.currentTarget.contains(event.relatedTarget)){combo.setOpen(false)}}})})}var Input=/*@__PURE__ */forwardRef(function Input2(props,ref){const state=useAddress();return part("input",props,state,{...state.inputProps,type:"text",autoComplete:"street-address","data-zappie-address-input":"",value:state.query,onChange:event=>state.setQuery(event.target.value)},ref)});var Suggestions=/*@__PURE__ */forwardRef(function Suggestions2(props,ref){const state=useAddress();return part("div",props,state,{...state.listProps,"aria-busy":state.status==="loading"},composeRefs(ref,node=>{if(node?.id&&node.id!==state.listProps.id){state.setListId(node.id)}}))});var Suggestion=/*@__PURE__ */forwardRef(function Suggestion2({index,...props},ref){const state=useAddress();return part("div",props,state,state.getOptionProps(index),composeRefs(ref,node=>{if(node?.id&&node.id!==state.getOptionProps(index).id){state.registerOption(index,node.id)}}))});var Address={Picker,Input,Suggestions,Suggestion};export{Address};
2
- //# sourceMappingURL=address-picker.js.map
@@ -1,2 +1 @@
1
1
  "use client";import{useCart,useStore}from"@zappie/sdk/react";import{forwardRef,useState}from"react";import{part}from"../internal/slot.js";import{getOpenStatus}from"../status/hours.js";var Picker=/*@__PURE__ */forwardRef(function Picker2({branches,value,onSelect,...props},ref){const cart=useCart();const store=useStore();const[isLoading,setLoading]=useState(false);const[error,setError]=useState();const selected=branches.find(branch=>branch.id===(value??cart.branchId));const select=async branch=>{if(isLoading||branch.id===cart.branchId||!branches.some(candidate=>candidate.id===branch.id)){return}setLoading(true);setError(void 0);try{await cart.actions.moveTo(branch.id);onSelect?.(branch)}catch(failure){setError(failure)}finally{setLoading(false)}};return part("div",props,{branches,selected,select,isLoading,error,isOpenNow:branch=>getOpenStatus(branch,branch.timezone??store.data?.timezone??"UTC").isOpen},{role:"group","aria-busy":isLoading,"data-state":isLoading?"loading":error?"invalid":"valid"},ref)});var Branch={Picker};export{Branch};
2
- //# sourceMappingURL=branch-picker.js.map
@@ -1,2 +1 @@
1
1
  "use client";import{useCart,useMenu,useStore,useZappie}from"@zappie/sdk/react";import{forwardRef,useEffect,useMemo,useState}from"react";import{part}from"../internal/slot.js";import{useControllableState}from"../internal/use-controllable-state.js";var windowModule;var windowLoad;var loadRules=()=>windowLoad??(windowLoad=import("./window.js").catch(()=>import("./window.js")).then(module=>windowModule=module).catch(error=>{windowLoad=void 0;throw error}));var Schedule=/*@__PURE__ */forwardRef(function Schedule2({branch,timezone:suppliedTimezone,value,defaultValue=null,onValueChange,intervalMinutes,maxDays,noticeMinutes,menuIds,...props},ref){const client=useZappie();const store=useStore();const menu=useMenu(branch.id,{metadataOnly:true});const cart=useCart();const ids=(menuIds??cart.lines.map(line=>line.menuId)).join(" ");const[retrying,setRetrying]=useState(false);const[rules,setRules]=useState(windowModule);const[failed,setFailed]=useState(false);useEffect(()=>{if(!rules){loadRules().then(setRules,()=>setFailed(true))}},[]);const menuFailed=!menu.data&&menu.error!==void 0;const status=menu.isLoading||retrying||!rules&&!failed?"loading":menuFailed||failed?"error":"ready";const ready=status==="ready";const timezone=suppliedTimezone??branch.timezone??store.data?.timezone??"UTC";const[now,setNow]=useState(()=>new Date);useEffect(()=>{const timer=setTimeout(()=>setNow(new Date),6e4-Date.now()%6e4);return()=>clearTimeout(timer)},[now]);const[selection,setSelection]=useControllableState({value,defaultValue,onChange:onValueChange});const result=useMemo(()=>rules?.bagWindow(branch,timezone,now,menu.data,ids,{intervalMinutes,maxDays,noticeMinutes}),[rules,branch,timezone,now,menu.data,ids,intervalMinutes,maxDays,noticeMinutes]);const slots=ready&&result?.slots||[];const days=Array.from(new Set(slots.map(slot=>slot.date))).map(date=>({date,slots:slots.filter(slot=>slot.date===date)}));const canAsap=ready&&result.canAsap;const isClosed=ready&&!canAsap&&slots.length===0;const isValid=selection===null?canAsap:slots.some(slot=>slot.value===selection);const retry=()=>{if(failed){location.reload();return}if(retrying||!menuFailed){return}setRetrying(true);void client.menu.get({branch:branch.id,metadataOnly:true}).catch(()=>{}).finally(()=>setRetrying(false))};const setValue=next=>{if(next===null?canAsap:slots.some(slot=>slot.value===next)){setSelection(next)}};return part("div",props,{status,retry,isClosed,blocker:isClosed?result.why():void 0,days,slots,value:selection,setValue,isAsap:selection===null,canAsap,isValid},{role:"group","aria-busy":status==="loading"?true:void 0,"data-status":status,"data-state":isValid?"valid":"invalid","data-invalid":isValid||!ready?void 0:""},ref)});export{Schedule};
2
- //# sourceMappingURL=schedule.js.map
@@ -1,2 +1 @@
1
1
  "use client";import{ZappieError}from"@zappie/sdk";import{useCart,useStore}from"@zappie/sdk/react";import{forwardRef}from"react";import{part}from"../internal/slot.js";import{useControllableState}from"../internal/use-controllable-state.js";var Switch=/*@__PURE__ */forwardRef(function Switch2({value,defaultValue,onValueChange,...props},ref){const cart=useCart();const store=useStore();const[selection,setSelection]=useControllableState({value,defaultValue:defaultValue??cart.fulfilment,onChange:onValueChange});const current=value===void 0&&defaultValue===void 0?cart.fulfilment:selection;const branch=store.data?.branches.find(branch2=>branch2.id===(cart.branchId??current?.branchId))??store.data?.branches.find(branch2=>branch2.isDefault)??store.data?.branches[0];const available=branch?.fulfilment;const options=[];if(available?.pickup){options.push("pickup")}if(available?.delivery){options.push("delivery")}if(available?.dineIn){options.push("dine_in")}const setValue=next=>{if(!options.includes(next.type)||next.branchId!==branch?.id){throw new ZappieError("invalid_request","Select an offered fulfilment mode for this branch")}cart.actions.setFulfilment(next);setSelection(next)};return part("div",props,{options,value:current,setValue},{role:"group"},ref)});var Fulfilment={Switch};export{Fulfilment};
2
- //# sourceMappingURL=switch.js.map
@@ -1,2 +1 @@
1
- import{canOrderAhead,getOpenStatus,localParts,openingIntervals}from"../status/hours.js";var labels=new Map;function grid(branch,timezone,now,menus,step,days,earliest,bookableDays=Infinity){const menuIntervals=menus.flatMap(({schedule})=>schedule?.openingTimes.length?[openingIntervals({...branch,openingTimes:schedule.openingTimes,specialHours:[]},timezone,now,days+1)]:[]);let label=labels.get(timezone);if(!label){label=new Intl.DateTimeFormat("en",{timeZone:timezone,hour:"numeric",minute:"2-digit",timeZoneName:"shortOffset"});labels.set(timezone,label)}const slots=[];const dates=new Set;for(const{start,end}of openingIntervals(branch,timezone,now,days+1)){for(let instant=start+Math.max(0,Math.ceil((earliest-start)/step))*step;instant<end;instant+=step){if(menuIntervals.every(intervals=>intervals.some(interval=>interval.start<=instant&&interval.end>instant))){const at=new Date(instant);const date=localParts(at,timezone).date;if(dates.add(date).size>bookableDays){return slots}slots.push({value:at.toISOString(),date,label:label.format(at)})}}}return slots}function explain(branch,timezone,now,menus,{intervalMinutes=30,maxDays=90,noticeMinutes=0}={},span=0){if(!Number.isInteger(intervalMinutes)||intervalMinutes<1||!Number.isInteger(maxDays)||maxDays<1||maxDays>90||!(noticeMinutes>=0&&noticeMinutes<Infinity)||!Number.isInteger(span)||span<0||span>90){throw new RangeError("Schedule requires a positive interval, 1\u201390 days and a non-negative notice")}const preorders=menus.filter(menu=>menu.schedule?.preorder);const ahead=branch.orderAheadDays;let days=Math.min(maxDays,ahead>0||!preorders.some(menu=>menu.schedule.preorderMaxDays>0)?ahead??14:90);let notice=noticeMinutes;let daysMenu;let noticeMenu;for(const{id,schedule}of preorders){const limit=schedule.preorderMaxDays;if(limit>0&&limit<days){days=limit;daysMenu=id}if(schedule.preorderNoticeHours*60>notice){notice=schedule.preorderNoticeHours*60;noticeMenu=id}}const step=intervalMinutes*6e4;const scheduling=branch.fulfilment.scheduling&&(preorders.length>0||canOrderAhead(branch));const earliest=now.getTime()+notice*6e4;const lead=Math.ceil(notice/1440);const slots=scheduling?grid(branch,timezone,now,menus,step,lead+Math.min(days*7+7,366),earliest,days):[];let why;return{slots,why(date){if(!scheduling){return{reason:"no-scheduling"}}if(!why){const open=list=>grid(branch,timezone,now,list,step,Math.max(span,lead+days,7),-Infinity);const branchOpen=open([]);const menusOpen=menus.map((_,index)=>open(menus.slice(0,index+1)));why=on=>{const at=list=>list.filter(slot=>on?slot.date===on:Date.parse(slot.value)>=now.getTime());const index=menusOpen.findIndex(list=>!at(list).length);return at(slots).length?void 0:!at(branchOpen).length?{reason:"closed"}:index>=0?{reason:"menu-closed",menuId:menus[index].id}:at(menusOpen.at(-1)??branchOpen).every(slot=>slot.value>(slots.at(-1)?.value??"~"))?{reason:"too-far",maxDays:days,menuId:daysMenu}:{reason:"too-soon",noticeHours:notice/60,menuId:noticeMenu}}}return why(date)}}}function bagWindow(branch,timezone,now,menu,ids,options){const sections=menu?.menus?.filter(section=>ids.split(" ").includes(section.id));const menus=sections?.length?sections:menu?.schedule?[menu]:[];return{...explain(branch,timezone,now,menus,options),canAsap:branch.isOpen!==false&&getOpenStatus(branch,timezone,now).isOpen&&menus.every(({schedule})=>!schedule?.preorder&&(!schedule?.openingTimes.length||getOpenStatus({...branch,...schedule},timezone,now).isOpen))}}export{bagWindow,explain};
2
- //# sourceMappingURL=window.js.map
1
+ import{canOrderAhead,getOpenStatus,localParts,openingIntervals}from"../status/hours.js";var labels=new Map;function grid(branch,timezone,now,menus,step,days,earliest,bookableDays=Infinity){const menuIntervals=menus.flatMap(({schedule})=>schedule?.openingTimes.length?[openingIntervals({...branch,openingTimes:schedule.openingTimes,specialHours:[]},timezone,now,days+1)]:[]);let label=labels.get(timezone);if(!label){label=new Intl.DateTimeFormat("en",{timeZone:timezone,hour:"numeric",minute:"2-digit",timeZoneName:"shortOffset"});labels.set(timezone,label)}const slots=[];const dates=new Set;for(const{start,end}of openingIntervals(branch,timezone,now,days+1)){for(let instant=start+Math.max(0,Math.ceil((earliest-start)/step))*step;instant<end;instant+=step){if(menuIntervals.every(intervals=>intervals.some(interval=>interval.start<=instant&&interval.end>instant))){const at=new Date(instant);const date=localParts(at,timezone).date;if(dates.add(date).size>bookableDays){return slots}slots.push({value:at.toISOString(),date,label:label.format(at)})}}}return slots}function explain(branch,timezone,now,menus,{intervalMinutes=30,maxDays=90,noticeMinutes=0}={},span=0){if(!Number.isInteger(intervalMinutes)||intervalMinutes<1||!Number.isInteger(maxDays)||maxDays<1||maxDays>90||!(noticeMinutes>=0&&noticeMinutes<Infinity)||!Number.isInteger(span)||span<0||span>90){throw new RangeError("Schedule requires a positive interval, 1\u201390 days and a non-negative notice")}const preorders=menus.filter(menu=>menu.schedule?.preorder);const ahead=branch.orderAheadDays;let days=Math.min(maxDays,ahead>0||!preorders.some(menu=>menu.schedule.preorderMaxDays>0)?ahead??14:90);let notice=noticeMinutes;let daysMenu;let noticeMenu;for(const{id,schedule}of preorders){const limit=schedule.preorderMaxDays;if(limit>0&&limit<days){days=limit;daysMenu=id}if(schedule.preorderNoticeHours*60>notice){notice=schedule.preorderNoticeHours*60;noticeMenu=id}}const step=intervalMinutes*6e4;const scheduling=branch.fulfilment.scheduling&&(preorders.length>0||canOrderAhead(branch));const earliest=now.getTime()+notice*6e4;const lead=Math.ceil(notice/1440);const slots=scheduling?grid(branch,timezone,now,menus,step,lead+Math.min(days*7+7,366),earliest,days):[];let why;return{slots,why(date){if(!scheduling&&branch.openingTimes.some(t=>!t.disabled)){return{reason:"no-scheduling"}}if(!why){const open=list=>grid(branch,timezone,now,list,step,Math.max(span,lead+days,7),-Infinity);const branchOpen=open([]);const menusOpen=menus.map((_,index)=>open(menus.slice(0,index+1)));why=on=>{const at=list=>list.filter(slot=>on?slot.date===on:Date.parse(slot.value)>=now.getTime());const index=menusOpen.findIndex(list=>!at(list).length);return at(slots).length?void 0:!at(branchOpen).length?{reason:"closed"}:index>=0?{reason:"menu-closed",menuId:menus[index].id}:at(menusOpen.at(-1)??branchOpen).every(slot=>slot.value>(slots.at(-1)?.value??"~"))?{reason:"too-far",maxDays:days,menuId:daysMenu}:{reason:"too-soon",noticeHours:notice/60,menuId:noticeMenu}}}return why(date)}}}function bagWindow(branch,timezone,now,menu,ids,options){const sections=menu?.menus?.filter(section=>ids.split(" ").includes(section.id));const menus=sections?.length?sections:menu?.schedule?[menu]:[];return{...explain(branch,timezone,now,menus,options),canAsap:branch.isOpen!==false&&getOpenStatus(branch,timezone,now).isOpen&&menus.every(({schedule})=>!schedule?.preorder&&(!schedule?.openingTimes.length||getOpenStatus({...branch,...schedule},timezone,now).isOpen))}}export{bagWindow,explain};
@@ -43,9 +43,11 @@ type ClockStyle = {
43
43
  declare function formatClock(time: string, { hour12, padHour, minutes, period, space, roundLastMinute, }?: ClockStyle): string;
44
44
  /** When a closed branch opens next, in its own time zone. */
45
45
  type NextOpening = {
46
+ /** The instant the branch opens. */
46
47
  at: Date;
47
48
  /** Whether that is today or tomorrow in the branch's time zone, or a later day. */
48
49
  day: "today" | "tomorrow" | "later";
50
+ /** The day of the week it opens, in the branch's time zone, Sunday 0 to Saturday 6. */
49
51
  weekday: Weekday;
50
52
  /** The local wall-clock time, HH:mm. */
51
53
  time: string;
@@ -72,15 +74,20 @@ declare function nextOpening(branch: Branch, { from, now, storeTimezone, }?: Hou
72
74
  * The defaults read "Opens at 7 am", "Opens tomorrow at 7 am" and "Opens Thu at 7 am".
73
75
  */
74
76
  type OpeningPhrases = {
77
+ /** For an opening later today. Defaults to "Opens at {time}". */
75
78
  today: string;
79
+ /** For an opening tomorrow. Defaults to "Opens tomorrow at {time}". */
76
80
  tomorrow: string;
81
+ /** For an opening on a later day. Defaults to "Opens {weekday} at {time}". */
77
82
  later: string;
78
83
  };
79
84
  /** How an opening or a status reads. */
80
85
  type LabelOptions = {
86
+ /** How the time reads. Defaults to `formatClock`'s style: "7 am", "7:30 pm". */
81
87
  clock?: ClockStyle | undefined;
82
88
  /** `short` reads "Thu", `long` reads "Thursday". Defaults to `short`. */
83
89
  weekday?: "short" | "long" | undefined;
90
+ /** Your own words for any of the phrases. The ones you leave out keep their defaults. */
84
91
  phrases?: Partial<OpeningPhrases> | undefined;
85
92
  };
86
93
  /** Put an opening into words, as `opensLabel` does. */
@@ -126,6 +133,7 @@ type StatusPhrases = OpeningPhrases & {
126
133
  };
127
134
  /** A branch's state at an instant, worked out from its hours in its own time zone. */
128
135
  type HoursStatus = {
136
+ /** Whether the branch is open at the instant, by its weekly hours, special hours and `closedUntil`. */
129
137
  isOpen: boolean;
130
138
  /** Whether the branch takes orders for later, so a closed branch can still take one. */
131
139
  canOrderAhead: boolean;
@@ -133,11 +141,13 @@ type HoursStatus = {
133
141
  closedForOrders: boolean;
134
142
  /** Open, and closing within `closingSoonMinutes`. */
135
143
  closingSoon: boolean;
144
+ /** The status in words, such as "Open until 10 pm", "Closes at 10 pm", "Opens tomorrow at 7 am" or "Closed". */
136
145
  label: string;
137
146
  /** When it opens next, while it is closed. */
138
147
  next?: NextOpening;
139
148
  /** The next opening or closing found in the hours, for a timer. */
140
149
  nextChange?: Date;
150
+ /** The IANA time zone the hours were read in: the branch's, then the store's, then Africa/Lagos. */
141
151
  timezone: string;
142
152
  };
143
153
  /** Options for `openStatus`. */
@@ -159,8 +169,11 @@ type OpenStatusOptions = HoursOptions & Omit<LabelOptions, "phrases"> & {
159
169
  declare function openStatus(branch: Branch, { now, storeTimezone, closingSoonMinutes, phrases, ...label }?: OpenStatusOptions): HoursStatus;
160
170
  /** One row of a week's hours: a run of days that share their hours. */
161
171
  type HoursRow = {
172
+ /** The days in the run, in the order the week was read, Sunday 0 to Saturday 6. */
162
173
  days: Weekday[];
174
+ /** The run's days in words: one day's name, or the first and last joined by `through`, such as "Monday – Friday". Reads `everyDay` when one row covers the week. */
163
175
  dayLabel: string;
176
+ /** The run's hours in words, such as "8 am – 10 pm". Holds the `closed` label on a run of closed days. */
164
177
  hoursLabel: string;
165
178
  /** Set on a run of closed days, when `closed` names them. */
166
179
  closed?: true;
@@ -179,6 +192,7 @@ type OpeningHoursOptions = {
179
192
  everyDay?: string | undefined;
180
193
  /** Read hours from midnight to 23:5x with this label ("Open all day"). */
181
194
  allDay?: string | undefined;
195
+ /** How each time reads. Defaults to `formatClock`'s style: "7 am", "7:30 pm". */
182
196
  clock?: ClockStyle | undefined;
183
197
  /** Seven day names from Sunday. Defaults to the full English names. */
184
198
  dayNames?: readonly string[] | undefined;
@@ -203,9 +217,11 @@ type OpeningHoursOptions = {
203
217
  declare function openingHours(times: readonly OpeningTime[], options?: OpeningHoursOptions): HoursRow[];
204
218
  /** A branch's hours for a list of branches: its status, today's hours and its week from today. */
205
219
  type BranchHours = {
220
+ /** Whether the branch is open at `now`, and its next change in words. */
206
221
  status: HoursStatus;
207
222
  /** Today's hours in the branch's time zone, with today's special hours. Empty on a closed day. */
208
223
  today: string;
224
+ /** The week's hours grouped into rows, starting today, with today's row marked. */
209
225
  week: HoursRow[];
210
226
  };
211
227
  /** Options for `branchHours`: `hours` reads today's hours and the week, the rest read the status. */