@tiendanube/nube-sdk-helper 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1167 @@
1
+ import { NubeBrowserAPIs, NubeComponent, NubeSDKState, UISlot, NubeSDKListenableEvent, EventListenerMap, Nullable, Address, BillingAddress, ShippingAddress, Cart, CartItem, CartValidation, CartValidationFail, CartValidationPending, CartValidationSuccess, ProductDetails, Customer, Payment, Shipping, ShippingOption, Store, Page, AllProductsPage, CategoryPage, CheckoutPage, HomePage, ProductPage, SearchPage, NubeSDK, Checkout, Category, Home } from '@tiendanube/nube-sdk-types';
2
+
3
+ /**
4
+ * @fileoverview Browser APIs access functions for NubeSDK
5
+ *
6
+ * This module provides utility functions to easily access
7
+ * browser APIs through the NubeSDK instance.
8
+ */
9
+
10
+ /**
11
+ * Browser APIs available through NubeSDK.
12
+ *
13
+ * Provides access to browser storage, navigation, and other APIs
14
+ * in a convenient and type-safe way.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * // Use async localStorage
19
+ * await browser.asyncLocalStorage.setItem('key', 'value');
20
+ * const value = await browser.asyncLocalStorage.getItem('key');
21
+ *
22
+ * // Use async sessionStorage
23
+ * await browser.asyncSessionStorage.setItem('session', 'data');
24
+ *
25
+ * // Navigate to a route
26
+ * browser.navigate('/products/123');
27
+ * ```
28
+ *
29
+ * @since 0.1.0
30
+ */
31
+ declare const browser: Readonly<NubeBrowserAPIs>;
32
+ /**
33
+ * Navigates to a specific route within the Nube application.
34
+ *
35
+ * @param route - The route to navigate to, must start with '/'
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * // Navigate to a product page
40
+ * navigate('/products/123');
41
+ *
42
+ * // Navigate to home
43
+ * navigate('/');
44
+ *
45
+ * ```
46
+ *
47
+ * @since 0.1.0
48
+ */
49
+ declare function navigate(route: `/${string}`): void;
50
+ /**
51
+ * Clears the browser APIs cache.
52
+ *
53
+ * This function is useful for testing or when you need to force
54
+ * a fresh instance of the browser APIs to be created.
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * // Clear cache before testing
59
+ * clearBrowserCache();
60
+ *
61
+ * // Next access to browser properties will create a new instance
62
+ * await browser.asyncLocalStorage.setItem('key', 'value');
63
+ * ```
64
+ *
65
+ * @since 0.1.0
66
+ */
67
+ declare function clearBrowserCache(): void;
68
+
69
+ /**
70
+ * Visual variants supported by {@link UIHelper.showToast}.
71
+ *
72
+ * @since 0.1.0
73
+ */
74
+ type ToastVariant = "success" | "error" | "warning" | "info";
75
+ /**
76
+ * A component, list of components, or a render function that derives them from
77
+ * the current state.
78
+ *
79
+ * @since 0.1.0
80
+ */
81
+ type RenderableComponent = NubeComponent | NubeComponent[] | ((state: Readonly<NubeSDKState>) => NubeComponent | NubeComponent[]);
82
+ type UIHelper = {
83
+ showToast: (message: string, variant?: ToastVariant) => void;
84
+ clear: (slot: UISlot) => void;
85
+ render: (slot: UISlot, component: RenderableComponent) => void;
86
+ renderAll: (slots: UISlot[], component: RenderableComponent) => void;
87
+ };
88
+ /**
89
+ * View helpers for NubeSDK.
90
+ *
91
+ * Provides methods to show toasts, clear slots, and render components.
92
+ */
93
+ declare const ui: Readonly<UIHelper>;
94
+
95
+ /**
96
+ * @fileoverview Event subscription helpers for NubeSDK
97
+ *
98
+ * Thin, ergonomic wrappers around `nube.on` that return an unsubscribe
99
+ * function, plus sugar for the very common "show a toast when an event fires"
100
+ * pattern seen across apps.
101
+ */
102
+
103
+ /**
104
+ * Subscribes a listener to a NubeSDK event and returns an unsubscribe function.
105
+ *
106
+ * Equivalent to calling `nube.on(event, listener)`, but the returned function
107
+ * detaches the listener via `nube.off`, so you don't need to hold a reference
108
+ * to both the instance and the listener to clean it up.
109
+ *
110
+ * @param event - The event to listen for
111
+ * @param listener - The listener to register
112
+ * @returns An unsubscribe function
113
+ *
114
+ * @example
115
+ * ```typescript
116
+ * const unsubscribe = onEvent("cart:update", (state) => {
117
+ * console.log("Cart now has", state.cart.items.length, "items");
118
+ * });
119
+ *
120
+ * // Later:
121
+ * unsubscribe();
122
+ * ```
123
+ *
124
+ * @since 0.1.0
125
+ */
126
+ declare function onEvent<T extends NubeSDKListenableEvent>(event: T, listener: EventListenerMap[T]): () => void;
127
+ /**
128
+ * Shows a toast whenever the given event fires.
129
+ *
130
+ * Replaces the repetitive `nube.on("...:success", () => ui.showToast(...))`
131
+ * pattern. The message can be a static string or a function deriving it from
132
+ * the current state.
133
+ *
134
+ * @param event - The event to listen for
135
+ * @param message - The toast message, or a function returning it from state
136
+ * @param variant - Optional toast variant (defaults to the {@link ui.showToast} default)
137
+ * @returns An unsubscribe function
138
+ *
139
+ * @example
140
+ * ```typescript
141
+ * toastOn("cart:add:success", "Product added to cart", "success");
142
+ *
143
+ * toastOn(
144
+ * "cart:update",
145
+ * (state) => `Cart updated: ${state.cart.items.length} items`,
146
+ * );
147
+ * ```
148
+ *
149
+ * @since 0.1.0
150
+ */
151
+ declare function toastOn<T extends NubeSDKListenableEvent>(event: T, message: string | ((state: Readonly<NubeSDKState>) => string), variant?: ToastVariant): () => void;
152
+
153
+ /**
154
+ * @fileoverview Access functions for NubeSDK instance data
155
+ *
156
+ * This module provides utility functions to easily access
157
+ * the SDK instance, current state and application data.
158
+ */
159
+
160
+ /**
161
+ * Gets the current NubeSDK state.
162
+ *
163
+ * @returns The current readonly SDK state
164
+ *
165
+ * @example
166
+ * ```typescript
167
+ * const state = getCurrentState();
168
+ * console.log('Current page:', state.location.page.type);
169
+ * console.log('Page data:', state.location.page.data);
170
+ * ```
171
+ *
172
+ * @since 0.1.0
173
+ */
174
+ declare function getCurrentState(): Readonly<NubeSDKState>;
175
+ /**
176
+ * Gets the current application data.
177
+ *
178
+ * @returns Readonly object containing application ID and script
179
+ *
180
+ * @example
181
+ * ```typescript
182
+ * const appData = getAppData();
183
+ * console.log('Application ID:', appData.id);
184
+ * console.log('Application script:', appData.script);
185
+ * ```
186
+ *
187
+ * @since 0.1.0
188
+ */
189
+ declare function getAppData(): Readonly<{
190
+ id: string;
191
+ script: string;
192
+ }>;
193
+ /**
194
+ * Gets the parsed URL of the application script.
195
+ *
196
+ * @returns The readonly URL instance of the application script
197
+ *
198
+ * @example
199
+ * ```typescript
200
+ * const url = getScriptURL();
201
+ * console.log('Script origin:', url.origin);
202
+ * console.log('Script pathname:', url.pathname);
203
+ * ```
204
+ *
205
+ * @since 0.1.0
206
+ */
207
+ declare function getScriptURL(): Readonly<URL>;
208
+ /**
209
+ * Gets the search parameters of the application script URL.
210
+ *
211
+ * @returns The readonly URLSearchParams instance from the script URL
212
+ *
213
+ * @example
214
+ * ```typescript
215
+ * const params = getScriptSearchParams();
216
+ * for (const [key, value] of params) {
217
+ * console.log(`${key}: ${value}`);
218
+ * }
219
+ * ```
220
+ *
221
+ * @since 0.1.0
222
+ */
223
+ declare function getScriptSearchParams(): Readonly<URLSearchParams>;
224
+ /**
225
+ * Gets a specific search parameter from the application script URL.
226
+ *
227
+ * @param key - The name of the search parameter to retrieve
228
+ * @returns The value of the search parameter, or null if not present
229
+ *
230
+ * @example
231
+ * ```typescript
232
+ * const version = getScriptParam('version');
233
+ * if (version) {
234
+ * console.log('Script version:', version);
235
+ * }
236
+ * ```
237
+ *
238
+ * @since 0.1.0
239
+ */
240
+ declare function getScriptParam(key: string): Nullable<string>;
241
+
242
+ /**
243
+ * @fileoverview Address type guards for NubeSDK (address, shipping & billing).
244
+ */
245
+
246
+ /**
247
+ * Type guard to check if a value is a valid address object
248
+ *
249
+ * @param value - The value to check
250
+ * @returns True if the value is an Address
251
+ *
252
+ * @example
253
+ * ```typescript
254
+ * if (isAddress(data)) {
255
+ * // data is now typed as Address
256
+ * console.log(data.zipcode);
257
+ * console.log(data.city);
258
+ * }
259
+ * ```
260
+ *
261
+ * @since 0.1.0
262
+ */
263
+ declare function isAddress(value: unknown): value is Address;
264
+ /**
265
+ * Type guard to check if a value is a valid shipping address
266
+ *
267
+ * @param value - The value to check
268
+ * @returns True if the value is a ShippingAddress
269
+ *
270
+ * @example
271
+ * ```typescript
272
+ * if (isShippingAddress(data)) {
273
+ * // data is now typed as ShippingAddress
274
+ * console.log(data.zipcode);
275
+ * console.log(data.between_street);
276
+ * }
277
+ * ```
278
+ *
279
+ * @since 0.1.0
280
+ */
281
+ declare function isShippingAddress(value: unknown): value is ShippingAddress;
282
+ /**
283
+ * Type guard to check if a value is a valid billing address
284
+ *
285
+ * @param value - The value to check
286
+ * @returns True if the value is a BillingAddress
287
+ *
288
+ * @example
289
+ * ```typescript
290
+ * if (isBillingAddress(data)) {
291
+ * // data is now typed as BillingAddress
292
+ * console.log(data.zipcode);
293
+ * console.log(data.business_name);
294
+ * }
295
+ * ```
296
+ *
297
+ * @since 0.1.0
298
+ */
299
+ declare function isBillingAddress(value: unknown): value is BillingAddress;
300
+
301
+ /**
302
+ * @fileoverview Cart type guards for NubeSDK.
303
+ */
304
+
305
+ /**
306
+ * Type guard to check if a value is a valid cart object
307
+ *
308
+ * @param value - The value to check
309
+ * @returns True if the value is a Cart
310
+ *
311
+ * @example
312
+ * ```typescript
313
+ * if (isCart(data)) {
314
+ * // data is now typed as Cart
315
+ * console.log(data.id);
316
+ * console.log(data.items.length);
317
+ * }
318
+ * ```
319
+ *
320
+ * @since 0.1.0
321
+ */
322
+ declare function isCart(value: unknown): value is Cart;
323
+ /**
324
+ * Type guard to check if a value is a valid cart item
325
+ *
326
+ * @param value - The value to check
327
+ * @returns True if the value is a CartItem
328
+ *
329
+ * @example
330
+ * ```typescript
331
+ * if (isCartItem(item)) {
332
+ * // item is now typed as CartItem
333
+ * console.log(item.name);
334
+ * console.log(item.price);
335
+ * }
336
+ * ```
337
+ *
338
+ * @since 0.1.0
339
+ */
340
+ declare function isCartItem(value: unknown): value is CartItem;
341
+ /**
342
+ * Type guard to check if a cart validation is successful
343
+ *
344
+ * @param validation - The validation to check
345
+ * @returns True if the validation is successful
346
+ *
347
+ * @example
348
+ * ```typescript
349
+ * if (isCartValidationSuccess(cart.validation)) {
350
+ * // cart.validation is now typed as CartValidationSuccess
351
+ * console.log('Cart is valid');
352
+ * }
353
+ * ```
354
+ *
355
+ * @since 0.1.0
356
+ */
357
+ declare function isCartValidationSuccess(validation: CartValidation): validation is CartValidationSuccess;
358
+ /**
359
+ * Type guard to check if a cart validation is pending
360
+ *
361
+ * @param validation - The validation to check
362
+ * @returns True if the validation is pending
363
+ *
364
+ * @example
365
+ * ```typescript
366
+ * if (isCartValidationPending(cart.validation)) {
367
+ * // cart.validation is now typed as CartValidationPending
368
+ * console.log('Cart validation in progress...');
369
+ * }
370
+ * ```
371
+ *
372
+ * @since 0.1.0
373
+ */
374
+ declare function isCartValidationPending(validation: CartValidation): validation is CartValidationPending;
375
+ /**
376
+ * Type guard to check if a cart validation failed
377
+ *
378
+ * @param validation - The validation to check
379
+ * @returns True if the validation failed
380
+ *
381
+ * @example
382
+ * ```typescript
383
+ * if (isCartValidationFail(cart.validation)) {
384
+ * // cart.validation is now typed as CartValidationFail
385
+ * console.log('Cart validation failed:', cart.validation.reason);
386
+ * }
387
+ * ```
388
+ *
389
+ * @since 0.1.0
390
+ */
391
+ declare function isCartValidationFail(validation: CartValidation): validation is CartValidationFail;
392
+
393
+ /**
394
+ * @fileoverview Component & page-data structure guards for NubeSDK.
395
+ */
396
+
397
+ /**
398
+ * Type guard to check if a value is a valid Nube component
399
+ *
400
+ * @param value - The value to check
401
+ * @returns True if the value is a NubeComponent
402
+ *
403
+ * @example
404
+ * ```typescript
405
+ * if (isNubeComponent(component)) {
406
+ * // component is now typed as NubeComponent
407
+ * console.log(component.type);
408
+ * }
409
+ * ```
410
+ *
411
+ * @since 0.1.0
412
+ */
413
+ declare function isNubeComponent(value: unknown): value is NubeComponent;
414
+ /**
415
+ * Type guard that checks if an object contains a list of products.
416
+ *
417
+ * This function verifies that the provided data is an object with a `products`
418
+ * property that is an array of ProductDetails. Useful for validating page data
419
+ * structures that may contain product lists.
420
+ *
421
+ * @param data - The unknown value to check
422
+ * @returns True if data is an object with a `products` array property, false otherwise
423
+ *
424
+ * @example
425
+ * ```typescript
426
+ * const pageData = { products: [product1, product2] };
427
+ * if (hasProductList(pageData)) {
428
+ * // TypeScript now knows pageData.products exists and is ProductDetails[]
429
+ * pageData.products.forEach(product => console.log(product.id));
430
+ * }
431
+ * ```
432
+ */
433
+ declare function hasProductList(data: unknown): data is {
434
+ products: ProductDetails[];
435
+ };
436
+ /**
437
+ * Type guard that checks if an object contains a list of sections.
438
+ *
439
+ * This function verifies that the provided data is an object with a `sections`
440
+ * property that is an array. Useful for validating page data structures that
441
+ * may contain section-based content.
442
+ *
443
+ * @param data - The unknown value to check
444
+ * @returns True if data is an object with a `sections` array property, false otherwise
445
+ *
446
+ * @example
447
+ * ```typescript
448
+ * const pageData = { sections: [{ type: "featured_products", products: [] }] };
449
+ * if (hasSections(pageData)) {
450
+ * // TypeScript now knows pageData.sections exists and is an array
451
+ * pageData.sections.forEach(section => processSection(section));
452
+ * }
453
+ * ```
454
+ */
455
+ declare function hasSections(data: unknown): data is {
456
+ sections: unknown[];
457
+ };
458
+ /**
459
+ * Type guard that checks if a section item contains products.
460
+ *
461
+ * This function verifies that the provided item is an object with a `products`
462
+ * property that is an array of ProductDetails. Useful for iterating through
463
+ * sections and filtering those that contain product lists.
464
+ *
465
+ * @param item - The unknown value to check (typically a section object)
466
+ * @returns True if item is an object with a `products` array property, false otherwise
467
+ *
468
+ * @example
469
+ * ```typescript
470
+ * const sections = [{ type: "featured_products", products: [product1] }];
471
+ * sections.forEach(section => {
472
+ * if (isSectionWithProducts(section)) {
473
+ * // TypeScript now knows section.products exists and is ProductDetails[]
474
+ * section.products.forEach(product => renderProduct(product));
475
+ * }
476
+ * });
477
+ * ```
478
+ */
479
+ declare function isSectionWithProducts(item: unknown): item is {
480
+ products: ProductDetails[];
481
+ };
482
+ /**
483
+ * Type guard that checks if an object contains a single product (Product Detail Page).
484
+ *
485
+ * This function verifies that the provided data is an object with a `product`
486
+ * property that is a valid ProductDetails object. It performs a minimal integrity
487
+ * check by verifying the product has an `id` property. Useful for validating
488
+ * product detail page data structures.
489
+ *
490
+ * @param data - The unknown value to check
491
+ * @returns True if data is an object with a `product` property containing a valid ProductDetails, false otherwise
492
+ *
493
+ * @example
494
+ * ```typescript
495
+ * const pageData = { product: { id: 1, name: {...}, ... } };
496
+ * if (hasSingleProduct(pageData)) {
497
+ * // TypeScript now knows pageData.product exists and is ProductDetails
498
+ * console.log(pageData.product.id);
499
+ * }
500
+ * ```
501
+ */
502
+ declare function hasSingleProduct(data: unknown): data is {
503
+ product: ProductDetails;
504
+ };
505
+
506
+ /**
507
+ * @fileoverview Domain type guards for NubeSDK (store, customer, payment, shipping).
508
+ */
509
+
510
+ /**
511
+ * Type guard to check if a value is a valid store object
512
+ *
513
+ * @param value - The value to check
514
+ * @returns True if the value is a Store
515
+ *
516
+ * @example
517
+ * ```typescript
518
+ * if (isStore(data)) {
519
+ * // data is now typed as Store
520
+ * console.log(data.name);
521
+ * console.log(data.currency);
522
+ * }
523
+ * ```
524
+ *
525
+ * @since 0.1.0
526
+ */
527
+ declare function isStore(value: unknown): value is Store;
528
+ /**
529
+ * Type guard to check if a value is a valid customer object
530
+ *
531
+ * @param value - The value to check
532
+ * @returns True if the value is a Customer
533
+ *
534
+ * @example
535
+ * ```typescript
536
+ * if (isCustomer(data)) {
537
+ * // data is now typed as Customer
538
+ * console.log(data.contact.email);
539
+ * console.log(data.shipping_address.city);
540
+ * }
541
+ * ```
542
+ *
543
+ * @since 0.1.0
544
+ */
545
+ declare function isCustomer(value: unknown): value is Customer;
546
+ /**
547
+ * Type guard to check if a value is a valid payment object
548
+ *
549
+ * @param value - The value to check
550
+ * @returns True if the value is a Payment
551
+ *
552
+ * @example
553
+ * ```typescript
554
+ * if (isPayment(data)) {
555
+ * // data is now typed as Payment
556
+ * console.log(data.status);
557
+ * console.log(data.selected?.method_name);
558
+ * }
559
+ * ```
560
+ *
561
+ * @since 0.1.0
562
+ */
563
+ declare function isPayment(value: unknown): value is Payment;
564
+ /**
565
+ * Type guard to check if a value is a valid shipping object
566
+ *
567
+ * @param value - The value to check
568
+ * @returns True if the value is a Shipping
569
+ *
570
+ * @example
571
+ * ```typescript
572
+ * if (isShipping(data)) {
573
+ * // data is now typed as Shipping
574
+ * console.log(data.selected);
575
+ * console.log(data.options?.length);
576
+ * }
577
+ * ```
578
+ *
579
+ * @since 0.1.0
580
+ */
581
+ declare function isShipping(value: unknown): value is Shipping;
582
+ /**
583
+ * Type guard to check if a value is a valid shipping option
584
+ *
585
+ * @param value - The value to check
586
+ * @returns True if the value is a ShippingOption
587
+ *
588
+ * @example
589
+ * ```typescript
590
+ * if (isShippingOption(option)) {
591
+ * // option is now typed as ShippingOption
592
+ * console.log(option.name);
593
+ * console.log(option.price);
594
+ * }
595
+ * ```
596
+ *
597
+ * @since 0.1.0
598
+ */
599
+ declare function isShippingOption(value: unknown): value is ShippingOption;
600
+
601
+ /**
602
+ * @fileoverview Page type guards for NubeSDK.
603
+ *
604
+ * Runtime checks that narrow a `Page` to its specific page type.
605
+ */
606
+
607
+ /**
608
+ * Type guard to check if a page is a product page
609
+ *
610
+ * @param page - The page to check
611
+ * @returns True if the page is a ProductPage
612
+ *
613
+ * @example
614
+ * ```typescript
615
+ * if (isProductPage(page)) {
616
+ * // page is now typed as ProductPage
617
+ * console.log(page.data.name);
618
+ * console.log(page.data.variants);
619
+ * }
620
+ * ```
621
+ *
622
+ * @since 0.1.0
623
+ */
624
+ declare function isProductPage(page: Page): page is ProductPage;
625
+ /**
626
+ * Type guard to check if a page is a category page
627
+ *
628
+ * @param page - The page to check
629
+ * @returns True if the page is a CategoryPage
630
+ *
631
+ * @example
632
+ * ```typescript
633
+ * if (isCategoryPage(page)) {
634
+ * // page is now typed as CategoryPage
635
+ * console.log(page.data.name);
636
+ * console.log(page.data.id);
637
+ * }
638
+ * ```
639
+ *
640
+ * @since 0.1.0
641
+ */
642
+ declare function isCategoryPage(page: Page): page is CategoryPage;
643
+ /**
644
+ * Type guard to check if a page is a checkout page
645
+ *
646
+ * @param page - The page to check
647
+ * @returns True if the page is a CheckoutPage
648
+ *
649
+ * @example
650
+ * ```typescript
651
+ * if (isCheckoutPage(page)) {
652
+ * // page is now typed as CheckoutPage
653
+ * console.log(page.data.step);
654
+ * }
655
+ * ```
656
+ *
657
+ * @since 0.1.0
658
+ */
659
+ declare function isCheckoutPage(page: Page): page is CheckoutPage;
660
+ /**
661
+ * Type guard to check if a page is an all products page
662
+ *
663
+ * @param page - The page to check
664
+ * @returns True if the page is an AllProductsPage
665
+ *
666
+ * @example
667
+ * ```typescript
668
+ * if (isAllProductsPage(page)) {
669
+ * // page is now typed as AllProductsPage
670
+ * console.log(page.data.id); // 0
671
+ * console.log(page.data.products);
672
+ * }
673
+ * ```
674
+ *
675
+ * @since 0.1.0
676
+ */
677
+ declare function isAllProductsPage(page: Page): page is AllProductsPage;
678
+ /**
679
+ * Type guard to check if a page is a search page
680
+ *
681
+ * @param page - The page to check
682
+ * @returns True if the page is a SearchPage
683
+ *
684
+ * @example
685
+ * ```typescript
686
+ * if (isSearchPage(page)) {
687
+ * // page is now typed as SearchPage
688
+ * console.log(page.data.q);
689
+ * console.log(page.data.products);
690
+ * }
691
+ * ```
692
+ *
693
+ * @since 0.1.0
694
+ */
695
+ declare function isSearchPage(page: Page): page is SearchPage;
696
+ /**
697
+ * Type guard to check if a page is a home page
698
+ *
699
+ * @param page - The page to check
700
+ * @returns True if the page is a HomePage
701
+ *
702
+ * @example
703
+ * ```typescript
704
+ * if (isHomePage(page)) {
705
+ * // page is now typed as HomePage
706
+ * console.log(page.data?.sections);
707
+ * }
708
+ * ```
709
+ *
710
+ * @since 0.1.0
711
+ */
712
+ declare function isHomePage(page: Page): page is HomePage;
713
+
714
+ /**
715
+ * @fileoverview NubeSDK instance management
716
+ *
717
+ * The NubeSDK runtime passes the SDK instance only as the argument of the
718
+ * app entry point (`App(nube)`); it does not expose it on a global. This module
719
+ * lets an app register that instance once, so every other helper
720
+ * (`getCurrentState`, `ui`, `browser`, `onPage`, selectors, ...) can access it
721
+ * without threading `nube` through every function and component.
722
+ */
723
+
724
+ /**
725
+ * Registers the NubeSDK instance for the current app.
726
+ *
727
+ * Call this once at the very start of your app entry point so the rest of the
728
+ * helper API can access the instance without it being passed around.
729
+ *
730
+ * @param nube - The NubeSDK instance received by your `App(nube)` entry point
731
+ *
732
+ * @example
733
+ * ```typescript
734
+ * import { setNubeInstance, getCurrentState, ui } from "@tiendanube/nube-sdk-helper";
735
+ *
736
+ * export function App(nube: NubeSDK) {
737
+ * setNubeInstance(nube);
738
+ *
739
+ * // No need to pass `nube` around anymore:
740
+ * const state = getCurrentState();
741
+ * ui.showToast("App ready!");
742
+ * }
743
+ * ```
744
+ *
745
+ * @since 0.1.0
746
+ */
747
+ declare function setNubeInstance(nube: Readonly<NubeSDK>): void;
748
+ /**
749
+ * Gets the NubeSDK instance for the current app.
750
+ *
751
+ * Returns the instance registered via {@link setNubeInstance}. If none was
752
+ * registered, it falls back to `self.__SDK_INSTANCE__` (for forward
753
+ * compatibility) and throws a descriptive error if neither is available.
754
+ *
755
+ * @returns The readonly NubeSDK instance
756
+ * @throws If no instance was registered and no global instance exists
757
+ *
758
+ * @example
759
+ * ```typescript
760
+ * const nube = getNubeInstance();
761
+ * nube.on("location:updated", (state) => {
762
+ * console.log("Page updated:", state.location.page);
763
+ * });
764
+ * ```
765
+ *
766
+ * @since 0.1.0
767
+ */
768
+ declare function getNubeInstance(): Readonly<NubeSDK>;
769
+ /**
770
+ * Clears the registered NubeSDK instance.
771
+ *
772
+ * Mainly useful for testing or for tearing down between app reloads.
773
+ *
774
+ * @since 0.1.0
775
+ */
776
+ declare function clearNubeInstance(): void;
777
+
778
+ /**
779
+ * @fileoverview Page matching system for NubeSDK
780
+ *
781
+ * This module provides a type-safe system for handling different page types
782
+ * (product, category, checkout) and their respective data.
783
+ * Includes functions for page matching and event handlers.
784
+ */
785
+
786
+ /**
787
+ * Maps each page type to its specific data payload.
788
+ *
789
+ * @example
790
+ * ```typescript
791
+ * // Product page data
792
+ * const productData: PageDataMap['product'] = {
793
+ * id: '123',
794
+ * name: 'Example Product',
795
+ * price: 29.99
796
+ * };
797
+ *
798
+ * // Category page data
799
+ * const categoryData: PageDataMap['category'] = {
800
+ * id: 'cat-1',
801
+ * name: 'Example Category',
802
+ * products: []
803
+ * };
804
+ * ```
805
+ *
806
+ * @since 0.1.0
807
+ */
808
+ type PageDataMap = {
809
+ product: ProductDetails;
810
+ category: Category;
811
+ checkout: Checkout;
812
+ home: Home;
813
+ };
814
+ /**
815
+ * Typed handler for a given page type.
816
+ *
817
+ * @template T - The page type (product, category, checkout)
818
+ * @param state - Current NubeSDK state
819
+ * @param data - Page-specific data for the given page type
820
+ *
821
+ * @example
822
+ * ```typescript
823
+ * const productHandler: PageHandlerFunction<'product'> = (state, data) => {
824
+ * console.log('Product viewed:', data.name);
825
+ * trackProductView(data.id);
826
+ * };
827
+ *
828
+ * const checkoutHandler: PageHandlerFunction<'checkout'> = (state, data) => {
829
+ * if (data.step === 'success') {
830
+ * trackPurchase(data.orderId);
831
+ * }
832
+ * };
833
+ * ```
834
+ *
835
+ * @since 0.1.0
836
+ */
837
+ type PageHandlerFunction<T extends keyof PageDataMap> = (state: NubeSDKState, data: PageDataMap[T]) => void;
838
+ /**
839
+ * Partial set of handlers where only relevant page types need to be implemented.
840
+ *
841
+ * @example
842
+ * ```typescript
843
+ * const handlers: PageHandlers = {
844
+ * product: (state, data) => trackProductView(data.id),
845
+ * checkout: (state, data) => {
846
+ * if (data.step === 'success') trackPurchase();
847
+ * }
848
+ * // category handler is optional
849
+ * };
850
+ * ```
851
+ *
852
+ * @since 0.1.0
853
+ */
854
+ type PageHandlers = {
855
+ [K in keyof PageDataMap]?: PageHandlerFunction<K>;
856
+ };
857
+ /**
858
+ * Dispatches to the appropriate handler based on the current page type.
859
+ * Type inference guarantees that each handler receives the correct payload.
860
+ *
861
+ * @param state - Current NubeSDK state
862
+ * @param handlers - Handlers mapped by page type
863
+ *
864
+ * @example
865
+ * ```typescript
866
+ * const state = getCurrentState();
867
+ *
868
+ * pageMatch(state, {
869
+ * product: (state, data) => {
870
+ * console.log('Product:', data.name, 'Price:', data.price);
871
+ * },
872
+ * category: (state, data) => {
873
+ * console.log('Category:', data.name, 'Products:', data.products.length);
874
+ * },
875
+ * checkout: (state, data) => {
876
+ * console.log('Checkout step:', data.step);
877
+ * }
878
+ * });
879
+ * ```
880
+ *
881
+ * @since 0.1.0
882
+ */
883
+ declare function pageMatch(state: NubeSDKState, handlers: PageHandlers): void;
884
+ /**
885
+ * Subscribes to navigation changes and invokes handlers that match the current page.
886
+ *
887
+ * Functional pattern that detects the current page type and calls the
888
+ * corresponding handler whenever navigation updates occur.
889
+ *
890
+ * @param handlers - Handlers mapped by page type
891
+ * @returns An unsubscribe function that stops listening for navigation changes
892
+ *
893
+ * @example
894
+ * ```typescript
895
+ * const unsubscribe = onPage({
896
+ * product: (state, data) => trackProductView(data.id),
897
+ * checkout: (state, data) => {
898
+ * if (data.step === 'success') trackPurchase();
899
+ * }
900
+ * });
901
+ *
902
+ * // Later, to stop listening:
903
+ * unsubscribe();
904
+ * ```
905
+ *
906
+ * @since 0.1.0
907
+ */
908
+ declare function onPage(handlers: PageHandlers): () => void;
909
+ /**
910
+ * Union of all possible checkout steps.
911
+ *
912
+ * @since 0.1.0
913
+ */
914
+ type CheckoutStep = Checkout["step"];
915
+ /**
916
+ * Handlers per checkout step (e.g., 'cart', 'payment', 'success').
917
+ * Only the steps you care about need to be provided.
918
+ *
919
+ * @example
920
+ * ```typescript
921
+ * const checkoutHandlers: CheckoutStepHandlers = {
922
+ * cart: (state) => console.log('Cart step'),
923
+ * payment: (state) => console.log('Payment step'),
924
+ * success: (state) => console.log('Success step')
925
+ * };
926
+ * ```
927
+ *
928
+ * @since 0.1.0
929
+ */
930
+ type CheckoutStepHandlers = Partial<Record<CheckoutStep, (state: NubeSDKState) => void>>;
931
+ /**
932
+ * Runs a handler when the checkout is ready and the current step matches.
933
+ *
934
+ * Listens to `checkout:ready` and, if the current page is a checkout,
935
+ * invokes the handler registered for the current `Checkout.step`.
936
+ *
937
+ * @param handlers - Handlers keyed by checkout step
938
+ * @returns An unsubscribe function that stops listening for checkout steps
939
+ *
940
+ * @example
941
+ * ```typescript
942
+ * const unsubscribe = onCheckoutStep({
943
+ * cart: (state) => {
944
+ * console.log('User is in cart step');
945
+ * trackCartView();
946
+ * },
947
+ * success: (state) => {
948
+ * console.log('Purchase completed');
949
+ * trackPurchase();
950
+ * }
951
+ * });
952
+ *
953
+ * // Later, to stop listening:
954
+ * unsubscribe();
955
+ * ```
956
+ *
957
+ * @since 0.1.0
958
+ */
959
+ declare function onCheckoutStep(handlers: CheckoutStepHandlers): () => void;
960
+
961
+ /**
962
+ * @fileoverview Render helpers for NubeSDK
963
+ *
964
+ * This module provides utilities to extract products from state and
965
+ * iterate over them for rendering (e.g., in grid slots).
966
+ */
967
+
968
+ /**
969
+ * Extracts all products from the NubeSDK state, regardless of the page type.
970
+ * Strategy: "Greedy" (Aggressive Collection).
971
+ *
972
+ * This function collects products from multiple sources within the state:
973
+ * - Direct product lists in category, products, and search pages
974
+ * - Products within sections for home, product, category, and products pages
975
+ * - The main product in product detail pages
976
+ *
977
+ * @param state - The current NubeSDK state containing location and page information
978
+ * @returns An array of ProductDetails. Returns an empty array if no products are found
979
+ * or if the page structure doesn't contain products.
980
+ *
981
+ * @example
982
+ * ```typescript
983
+ * const state = nube.getState();
984
+ * const products = getProductsFromState(state);
985
+ * products.forEach(product => console.log(product.id));
986
+ * ```
987
+ */
988
+ declare function getProductsFromState(state: NubeSDKState): ProductDetails[];
989
+ /**
990
+ * Creates a higher-order function that iterates over products in grid slots.
991
+ *
992
+ * This helper abstracts page type checking, product iteration, and automatic key generation.
993
+ * It extracts products from the state, maps them through a render factory function,
994
+ * filters out null/undefined results, and automatically injects unique keys for each component.
995
+ *
996
+ * @param renderFactory - A function that receives a ProductDetails and returns a NubeComponent,
997
+ * null, or undefined. Components returning null/undefined are filtered out.
998
+ * @returns A function that accepts NubeSDKState and returns an array of NubeComponent instances
999
+ * with automatically generated keys using the product ID.
1000
+ *
1001
+ * @example
1002
+ * ```typescript
1003
+ * nube.render(
1004
+ * "product_grid_item_image_bottom_right",
1005
+ * forEachProduct((product) => <MyBadge product={product} />)
1006
+ * );
1007
+ * ```
1008
+ */
1009
+ declare function forEachProduct(renderFactory: (product: ProductDetails) => NubeComponent | null | undefined): (state: NubeSDKState) => NubeComponent[];
1010
+
1011
+ /**
1012
+ * @fileoverview State selectors for NubeSDK
1013
+ *
1014
+ * Small, focused accessors for the most frequently read slices of the SDK
1015
+ * state. Each selector accepts an optional `state`; when omitted it reads the
1016
+ * current state from the registered instance, so apps don't need to repeat
1017
+ * `const state = nube.getState()` everywhere.
1018
+ */
1019
+
1020
+ /**
1021
+ * Gets the current cart.
1022
+ *
1023
+ * @param state - Optional state; defaults to the current SDK state
1024
+ * @returns The cart
1025
+ *
1026
+ * @example
1027
+ * ```typescript
1028
+ * const cart = getCart();
1029
+ * console.log("Items:", cart.items.length);
1030
+ * ```
1031
+ *
1032
+ * @since 0.1.0
1033
+ */
1034
+ declare function getCart(state?: NubeSDKState): Cart;
1035
+ /**
1036
+ * Gets the items currently in the cart.
1037
+ *
1038
+ * @param state - Optional state; defaults to the current SDK state
1039
+ * @returns The list of cart items
1040
+ *
1041
+ * @example
1042
+ * ```typescript
1043
+ * for (const item of getCartItems()) {
1044
+ * console.log(item.name, item.quantity);
1045
+ * }
1046
+ * ```
1047
+ *
1048
+ * @since 0.1.0
1049
+ */
1050
+ declare function getCartItems(state?: NubeSDKState): CartItem[];
1051
+ /**
1052
+ * Gets the type of the current page (e.g. `"home"`, `"product"`, `"checkout"`).
1053
+ *
1054
+ * @param state - Optional state; defaults to the current SDK state
1055
+ * @returns The current page type
1056
+ *
1057
+ * @example
1058
+ * ```typescript
1059
+ * if (getPageType() === "checkout") {
1060
+ * // checkout-specific logic
1061
+ * }
1062
+ * ```
1063
+ *
1064
+ * @since 0.1.0
1065
+ */
1066
+ declare function getPageType(state?: NubeSDKState): Page["type"];
1067
+ /**
1068
+ * Gets the current customer, or `null` when not available on the current page.
1069
+ *
1070
+ * @param state - Optional state; defaults to the current SDK state
1071
+ * @returns The customer or `null`
1072
+ *
1073
+ * @example
1074
+ * ```typescript
1075
+ * const customer = getCustomer();
1076
+ * if (customer) console.log(customer.contact?.email);
1077
+ * ```
1078
+ *
1079
+ * @since 0.1.0
1080
+ */
1081
+ declare function getCustomer(state?: NubeSDKState): Nullable<Customer>;
1082
+
1083
+ /**
1084
+ * @fileoverview General utility functions for NubeSDK
1085
+ *
1086
+ * This module provides general-purpose utility functions including
1087
+ * deep cloning, debouncing, and throttling capabilities.
1088
+ */
1089
+ /**
1090
+ * Deep clones a value.
1091
+ *
1092
+ * Uses the structured clone algorithm when available (it is, in the NubeSDK
1093
+ * Web Worker runtime), which correctly handles `Date`, `Map`, `Set`, typed
1094
+ * arrays and circular references. Falls back to JSON serialization in
1095
+ * environments without `structuredClone` (with the usual JSON limitations:
1096
+ * functions, symbols and `undefined` are dropped).
1097
+ *
1098
+ * @template T - The type of the value to clone
1099
+ * @param obj - The value to deep clone
1100
+ * @returns A deep clone of the input value
1101
+ *
1102
+ * @example
1103
+ * ```typescript
1104
+ * const original = { name: 'John', age: 30, hobbies: ['reading', 'coding'] };
1105
+ * const cloned = deepClone(original);
1106
+ *
1107
+ * cloned.name = 'Jane';
1108
+ * cloned.hobbies.push('gaming');
1109
+ *
1110
+ * console.log(original.name); // 'John' (unchanged)
1111
+ * console.log(original.hobbies); // ['reading', 'coding'] (unchanged)
1112
+ * ```
1113
+ *
1114
+ * @since 0.1.0
1115
+ */
1116
+ declare function deepClone<T>(obj: T): T;
1117
+ /**
1118
+ * Debounces a function call, ensuring it only executes after a specified
1119
+ * delay has passed since the last invocation.
1120
+ *
1121
+ * @template T - The function type
1122
+ * @param func - The function to debounce
1123
+ * @param wait - The number of milliseconds to delay
1124
+ * @returns A debounced version of the function
1125
+ *
1126
+ * @example
1127
+ * ```typescript
1128
+ * const debouncedSearch = debounce((query: string) => {
1129
+ * console.log('Searching for:', query);
1130
+ * // Perform search operation
1131
+ * }, 300);
1132
+ *
1133
+ * // Multiple rapid calls will only execute the last one after 300ms
1134
+ * debouncedSearch('a');
1135
+ * debouncedSearch('ab');
1136
+ * debouncedSearch('abc'); // Only this will execute
1137
+ * ```
1138
+ *
1139
+ * @since 0.1.0
1140
+ */
1141
+ declare function debounce<T extends (...args: never[]) => unknown>(func: T, wait: number): (...args: Parameters<T>) => void;
1142
+ /**
1143
+ * Creates a throttled version of a function that will only execute
1144
+ * at most once per specified time limit.
1145
+ *
1146
+ * @template T - The function type
1147
+ * @param func - The function to throttle
1148
+ * @param limit - The time limit in milliseconds
1149
+ * @returns A throttled version of the function
1150
+ *
1151
+ * @example
1152
+ * ```typescript
1153
+ * const throttledScroll = throttle((event: Event) => {
1154
+ * console.log('Scroll event:', event);
1155
+ * // Handle scroll event
1156
+ * }, 100);
1157
+ *
1158
+ * // Even with rapid scroll events, the function will only execute
1159
+ * // once every 100ms
1160
+ * window.addEventListener('scroll', throttledScroll);
1161
+ * ```
1162
+ *
1163
+ * @since 0.1.0
1164
+ */
1165
+ declare function throttle<T extends (...args: never[]) => unknown>(func: T, limit: number): (...args: Parameters<T>) => void;
1166
+
1167
+ export { type CheckoutStepHandlers, type PageDataMap, type PageHandlerFunction, type PageHandlers, type RenderableComponent, type ToastVariant, type UIHelper, browser, clearBrowserCache, clearNubeInstance, debounce, deepClone, forEachProduct, getAppData, getCart, getCartItems, getCurrentState, getCustomer, getNubeInstance, getPageType, getProductsFromState, getScriptParam, getScriptSearchParams, getScriptURL, hasProductList, hasSections, hasSingleProduct, isAddress, isAllProductsPage, isBillingAddress, isCart, isCartItem, isCartValidationFail, isCartValidationPending, isCartValidationSuccess, isCategoryPage, isCheckoutPage, isCustomer, isHomePage, isNubeComponent, isPayment, isProductPage, isSearchPage, isSectionWithProducts, isShipping, isShippingAddress, isShippingOption, isStore, navigate, onCheckoutStep, onEvent, onPage, pageMatch, setNubeInstance, throttle, toastOn, ui };