@viu/emporix-sdk 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -234,6 +234,160 @@ declare function createServerStorage(jar: ServerCookieJar): EmporixStorage;
234
234
  */
235
235
  declare function serverAuth(storage: EmporixStorage): AuthContext;
236
236
 
237
+ /**
238
+ * The browser session-storage backends: memory, localStorage, sessionStorage,
239
+ * document.cookie.
240
+ *
241
+ * The contract and the framework-free backends live in `./session-storage`;
242
+ * these are the ones that need browser globals. They were in
243
+ * `@viu/emporix-sdk-react` until `@viu/emporix-sdk-angular` needed them too —
244
+ * `localStorage` is not a React API, and duplicating a storage backend per
245
+ * binding means two of them writing subtly different values under the same key.
246
+ *
247
+ * Every export is a named factory and the package sets `sideEffects: false`, so
248
+ * a Node consumer that imports none of them bundles none of them. That is
249
+ * asserted by `scripts/check-treeshake.mjs`.
250
+ */
251
+
252
+ /**
253
+ * The three methods these backends use from a Web `Storage`.
254
+ *
255
+ * Declared locally on purpose. This package compiles with `lib: ["ES2022"]` and
256
+ * no `"DOM"` — that is the invariant which keeps the SDK runnable on Node, edge
257
+ * runtimes and workers, and adding DOM to the lib to satisfy this one file would
258
+ * switch that compile-time guard off for all ~60 services. So every browser
259
+ * global below is reached through a narrowed `globalThis` instead of an ambient
260
+ * declaration, which is also the pattern the localStorage and sessionStorage
261
+ * availability checks already used before this code moved here.
262
+ */
263
+ interface WebStorageLike {
264
+ getItem(key: string): string | null;
265
+ setItem(key: string, value: string): void;
266
+ removeItem(key: string): void;
267
+ }
268
+ /**
269
+ * Internal: create a swallow-on-throw listener set used by all the storage
270
+ * backends for `subscribeAll`. Centralizes the try/catch wrapper so a buggy
271
+ * telemetry handler never breaks a storage write.
272
+ */
273
+ declare function createListenerSet<T>(): {
274
+ add(l: (value: T) => void): () => void;
275
+ notify(value: T): void;
276
+ };
277
+ /** In-memory token store. Default, SSR-safe, no persistence. */
278
+ declare function createMemoryStorage(opts?: {
279
+ initial?: string;
280
+ }): EmporixStorage;
281
+ /**
282
+ * Internal: build an {@link EmporixStorage} backed by any Web `Storage`
283
+ * instance (`localStorage` or `sessionStorage`). Both share the identical
284
+ * `getItem`/`setItem`/`removeItem` surface, so the 8-key wiring lives here once.
285
+ * Callers own the availability check + memory fallback before delegating.
286
+ */
287
+ declare function fromWebStorage(storage: WebStorageLike, opts?: {
288
+ key?: string;
289
+ }): EmporixStorage;
290
+ /**
291
+ * Browser `localStorage`-backed store: persistent and shared across tabs.
292
+ * Falls back to memory on the server (or when localStorage is unavailable).
293
+ */
294
+ declare function createLocalStorage(opts?: {
295
+ key?: string;
296
+ }): EmporixStorage;
297
+ /** @deprecated Use {@link createLocalStorage}. Kept for backward compatibility. */
298
+ declare const createLocalStorageStorage: typeof createLocalStorage;
299
+ /**
300
+ * Browser `sessionStorage`-backed store: per-tab persistence that survives a
301
+ * reload but is cleared when the tab closes and is not shared across tabs.
302
+ * Falls back to memory on the server (or when sessionStorage is unavailable).
303
+ */
304
+ declare function createSessionStorage(opts?: {
305
+ key?: string;
306
+ }): EmporixStorage;
307
+ /**
308
+ * Cookie-backed store. `Secure` defaults to on for https origins; override
309
+ * with `secure: false` only for non-https dev setups. Consumer must still pick
310
+ * an appropriate `sameSite` for CSRF safety.
311
+ */
312
+ declare function createCookieStorage(opts?: {
313
+ name?: string;
314
+ secure?: boolean;
315
+ sameSite?: "lax" | "strict" | "none";
316
+ }): EmporixStorage;
317
+
318
+ /**
319
+ * The cache-key shape every framework binding shares.
320
+ *
321
+ * Shape: `["emporix", resource, ...args, { tenant, authKind, siteCode?, language? }]`
322
+ *
323
+ * It lives in the core SDK for the same reason {@link STORAGE_KEYS} does: it is
324
+ * not a React concern. `@viu/emporix-sdk-react` and `@viu/emporix-sdk-angular`
325
+ * must produce byte-identical keys or the two bindings, the docs and the
326
+ * devtools all describe different caches. One definition is the only way that
327
+ * holds — a copy per binding would agree on the day it was written and nowhere
328
+ * after.
329
+ *
330
+ * The trailing meta object groups the discriminators that differentiate cache
331
+ * entries across tenants, auth-kinds and (where applicable) active sites.
332
+ * `siteCode` is included only when explicitly passed — non-site-aware reads
333
+ * pass `undefined` and the field is dropped.
334
+ */
335
+ declare function emporixKey<TArgs extends readonly unknown[]>(resource: string, args: TArgs, context: {
336
+ tenant: string;
337
+ authKind: string;
338
+ siteCode?: string | null;
339
+ language?: string | null;
340
+ }): readonly ["emporix", string, ...TArgs, Record<string, unknown>];
341
+ /** Which site discriminators go into the query key's meta object. */
342
+ type SiteFields = "full" | "language" | "none";
343
+ /**
344
+ * Builds the site portion of a query key's meta object. Shared by every read
345
+ * path — React's `useEmporixQuery`, its `prefetchEmporix`, and Angular's
346
+ * `emporixQueryOptions` — so none of them can disagree about which
347
+ * discriminators a resource carries. Key parity is structural, not tested.
348
+ *
349
+ * Note `null` is preserved rather than dropped: an unbound site is a distinct
350
+ * cache identity from a bound one, and {@link emporixKey} only omits a field
351
+ * when it is `undefined`.
352
+ */
353
+ declare function siteMeta(site: SiteFields, siteCode: string | null, language: string | null): {
354
+ siteCode?: string | null;
355
+ language?: string | null;
356
+ };
357
+
358
+ /**
359
+ * In-memory customer-session store, keyed by storage instance.
360
+ *
361
+ * Moved out of the React bindings: it is a subscribe/snapshot store over
362
+ * {@link EmporixStorage} with no framework API in it. React consumes it through
363
+ * `useSyncExternalStore`, Angular through a `signal` — the store itself does not
364
+ * know or care, which is exactly why it does not belong in either binding.
365
+ */
366
+
367
+ /**
368
+ * The three session tokens the customer session tracks. `token` is mirrored
369
+ * from persistent storage; `refreshToken` and `saasToken` are in-memory only
370
+ * (deliberately never persisted).
371
+ */
372
+ interface CustomerSessionState {
373
+ token: string | null;
374
+ refreshToken: string | null;
375
+ saasToken: string | null;
376
+ }
377
+ interface CustomerSessionStore {
378
+ getSnapshot: () => CustomerSessionState;
379
+ setState: (next: CustomerSessionState | ((prev: CustomerSessionState) => CustomerSessionState)) => void;
380
+ subscribe: (listener: () => void) => () => void;
381
+ }
382
+ /**
383
+ * Shared in-memory store for the customer session, keyed by the storage
384
+ * instance. Every consumer reads and writes the same store, so a login in one
385
+ * place (the auth form) is visible in another (the checkout page) — without
386
+ * this, the in-memory `saasToken` lived in a single component's local state and
387
+ * customer checkout would 401 elsewhere.
388
+ */
389
+ declare function getCustomerSessionStore(storage: EmporixStorage): CustomerSessionStore;
390
+
237
391
  /**
238
392
  * Address
239
393
  *
@@ -11930,4 +12084,4 @@ declare function productIdFromYrn(yrn: string | undefined): string;
11930
12084
  */
11931
12085
  declare function productYrn(tenant: string, productId: string): string;
11932
12086
 
11933
- export { type AddedPoints, type AdminCustomer, type AdminCustomerAddress, type AdminCustomerAddressInput, type AdminCustomerAddressList, type AdminCustomerAddressUpdate, type AdminCustomerCreated, type AdminCustomerImport, type AdminCustomerImportAccount, type AdminCustomerImportResult, type AdminCustomerInput, type AdminCustomerLegacyAuth, type AdminCustomerList, type AdminCustomerPatch, type AdminCustomerSearchQuery, type AdminCustomerUpdate, type AdminPasswordMigrationRetention, type AdminPasswordMigrationRetentionInput, type Agent, type AgentAnalytics, type AgentExecutions, type AgentFromTemplate, type AgentInput, type AgentPatchOp, type AgentRequestLog, type AgentSearchQuery, type AgentSessionLog, type AgentTemplate, type AgenticPatchOp, type AgentsExport, type AgentsExportRequest, type AgentsImport, type AgentsImportRequest, AiService, type AnalyticsQuery, type Approval, type ApprovalCreated, type ApprovalDecision, type ApprovalInput, type ApprovalList, type ApprovalPatch, type ApprovalPermittedInput, type ApprovalPermittedResult, ApprovalService, type ApprovalUsersQuery, type ApprovalUsersResult, type Assignee, type Attachment, type AttachmentOptions, AuthContext, AvailabilityService, type BatchNextIdEntry, type Brand, type BrandInput, type BrandList, BrandService, type BrandUpdate, type BulkInstanceResult, type BulkPatchInstanceItem, CartService, type Catalog, type CatalogCreated, type CatalogInput, type CatalogList, type CatalogPatch, CatalogService, type CatalogUpdate, CategoryService, type CgRelation, type CgRelationList, type ChatRequest, type ChatResponse, type ChatStreamOptions, CheckoutService, ClientConfigService, type ClientConfiguration, ClientContext, CloudFunctionsService, type CommerceEvents, CompaniesService, type CompletionMessage, type CompletionRequest, type CompletionResponse, type Configuration$1 as Configuration, type ConfigurationDraft, ContactsService, type Conversation, type ConversationSearchQuery, type ConversionFactorInput, type ConversionFactorResult, type ConvertUnitInput, type ConvertUnitResult, type CookieIo, type Country, type CountryList, CountryService, type CountryUpdate, type Coupon$1 as Coupon, type CouponCreated, type CouponInput, type CouponList, CouponService, type CouponUpdate, type Created, type Currency, type CurrencyCreated, type CurrencyInput, type CurrencyList, CurrencyService, type CurrencyUpdate, type CustomEntity, type CustomEntityDraft, type CustomInstance, type CustomInstanceDraft, CustomerAdminService, CustomerGroupsService, CustomerService, type CustomerSummaryBatch, CustomerTokenRefresher, type DeleteAgentOptions, type DeleteConfigOptions, type DeliveryCreated, type DeliveryCycleInput, type DeliverySlot, type DeliverySlotList, type DeliveryTime$1 as DeliveryTime, type DeliveryTimeInput, type DeliveryTimeList, type DeliveryTimeUpdate, type DeliveryWindow$2 as DeliveryWindow, type DeliveryWindowList, type DeliveryWindowValidation, EmporixAuthError, EmporixClient, EmporixConfig, type EmporixCore, EmporixError, EmporixForbiddenError, EmporixInsufficientScopeError, EmporixNetworkError, EmporixNotFoundError, EmporixServerError, type EmporixStorage, type EmporixStorageKey, EmporixTimeoutError, EmporixValidationError, type ExchangeRate, type ExchangeRateCreated, type ExchangeRateInput, type ExchangeRateList, type ExchangeRateUpdate, type ExecutionsQuery, type Fee$1 as Fee, type FeeDraft, FeeService, type FindSiteInput, type GetOptions, type IamAccessControl, type IamAccessControlCreated, type IamAccessControlUpsert, type IamGroup, type IamGroupCreate, type IamGroupCreated, AssignmentCreateRequest as IamGroupMemberAssignment, type IamGroupMemberCreated, type IamGroupMemberInput, type IamGroupUpdate, type IamScope, type IamScopeCreated, type IamScopeUpsert, IamService, type IamUser, type IamUserCreate, type IamUserCreated, type IamUserDetail, type IamUserScopes, type IamUserUpdate, type ImportCancelResult, type ImportConfig, type ImportErrorRecord, type ImportPage, type ImportPageOptions, type ImportRecordOutcome, type ImportRun, type ImportRunDetail, type ImportRunEvent, type ImportRunInput, type ImportRunMode, type ImportRunStatus, type ImportRunStream, type ImportSchedule, ImportService, type ImportStream, type ImportedRecord, type IndexConfig, type IndexConfigCreated, type IndexPublicConfig, IndexingService, type InstanceSearchBody, type InvoiceJob, type InvoiceJobCreated, type InvoiceJobDraft, InvoiceService, type InvokeCloudFunctionOptions, type ItemFee, type ItemFeeDraft, type ItemFeeSearch, type ItemFeeSearchByProductId, type ItemFeeSearchByProductIds, type Job, type JobIdResponse, type Label, type LabelInput, type LabelList, LabelService, type LabelUpdate, type ListConfigOptions, type ListCustomEntitiesOptions, type ListFeesQuery, type ListInstancesQuery, type ListQuery, type ListQuoteReasonsQuery, type ListQuotesQuery, type ListReindexJobsOptions, type ListSchemaReferencesQuery, type ListSchemasQuery, LocationsService, LogLevel, type McpServer, type McpServerInput, MediaService, type MetadataFilter, type MinimumFee, type MutateOptions, type NewPointsEntry, type NextIdCommandRequest, type NextIdOptions, type NextIdResponse, type NextIdsBatchRequest, type NextIdsBatchResponse, type OAuthConfig, type OAuthInput, type OrderCycleList, type OrderEntryEventCreate, type OrderStatusChange, OrdersService, type PackagingProductsChange, type PackingEvent, type PackingEventList, PaginatedItems, PaymentGatewayService, type PersistedAnonymousSession, type PickOrder, type PickOrderList, type PickPackAck, PickPackService, type PointsSummary, PriceService, ProductService, type ProviderModels, QueryFor, type Quote, type QuoteCreated, type QuoteDraft, type QuoteHistory, type QuoteInput, type QuoteReason, type QuoteReasonCreated, type QuoteReasonDraft, type QuoteReasonUpdate, type QuoteResult, QuoteService, type QuoteSlotInput, type QuoteUpdate, RagIndexerService, type RagType, type RecalculationJob, type RecalculationJobCreated, type RecalculationJobInput, type RedeemCouponResult, type RedeemMyPointsInput, type RedeemOption, type RedeemOptionList, type RedeemedPoints, type Redemption, type RedemptionCreated, type RedemptionInput, type ReferralCoupon, type Region, type RegionList, type ReindexEntityType, type ReindexInput, type ReindexJob, type ReindexJobInput, type ReindexJobStatus, ResolvedConfig, type ResourceCreated, type Return, type ReturnCreated, type ReturnInput, type ReturnList, type ReturnPatch, type ReturnUpdate, ReturnsService, RewardPointsService, STORAGE_KEYS, SalesOrdersService, type Schema, type SchemaAttribute, type SchemaDraft, type SchemaExport, type SchemaImportInput, type SchemaInstanceBulkCreateItem, type SchemaInstanceBulkUpsertItem, type SchemaReference, type SchemaReferenceCreated, type SchemaReferenceInput, type SchemaReferenceUpdateInput, SchemaService, type SchemaTypeName, type SchemaUpdate, type SearchImportedRecordsOptions, type SearchInstancesQuery, type SearchQuery, type SearchStreamRecordsOptions, SegmentService, type SequenceSchema, type SequenceSchemaCreate, SequentialIdService, type ServerCookieJar, type ServiceClass, ServiceName, type SessionAttributeInput, type SessionContext, type SessionContextPatch, SessionContextService, type SetItemFeesOptions, type ShippingFee, type ShippingGroup, type ShippingGroupList, type ShippingMethod, type ShippingMethodList, type ShippingPatch, ShippingService, type ShoppingList, type ShoppingListDraft, type ShoppingListItem, ShoppingListService, type Site$1 as Site, type SiteCreated, type SiteInput, type SiteList, type SiteMixin, type SiteMixinCreated, type SiteMixins, SiteService, StoredAnonymousSession, type TaxCalculationInput, type TaxCalculationRequest, type TaxCalculationResult, type TaxClass, type TaxConfig, type TaxConfigCreated, type TaxCreation as TaxConfigInput, type TaxUpdate as TaxConfigUpdate, type TaxLocation, TaxService, TenantConfigService, type TextRequest, type TextResponse, type Token, type TokenInput, TokenProvider, type TokenStorage, type Tool, type ToolInput, type Unit, type UnitCreated, UnitHandlingService, type UnitInput, type UnitUpdate, type Vendor, type VendorCreated, type VendorInput, type VendorList, type VendorLocation, type VendorLocationInput, type VendorLocationList, type VendorLocationUpdate, type VendorSearchQuery, VendorService, type VendorUpdate, type WebhookConfig, type WebhookConfigCreated, type WebhookConfigDraft, type WebhookConfigPatch, type WebhookDashboardAccess, WebhookService, type WebhookStatistics, type WebhookStatisticsQuery, type WebhookSubscription, type WebhookSubscriptionUpdateItem, type WebhookSubscriptionUpdateResultItem, type Zone, type ZoneList, approvalStatusPatch, createCookieBackedStorage, createCore, createEmporixClient, createServerStorage, errorFromResponse, parseAnonymousSession, pickFee, productIdFromYrn, productYrn, resolveZone, serverAuth };
12087
+ export { type AddedPoints, type AdminCustomer, type AdminCustomerAddress, type AdminCustomerAddressInput, type AdminCustomerAddressList, type AdminCustomerAddressUpdate, type AdminCustomerCreated, type AdminCustomerImport, type AdminCustomerImportAccount, type AdminCustomerImportResult, type AdminCustomerInput, type AdminCustomerLegacyAuth, type AdminCustomerList, type AdminCustomerPatch, type AdminCustomerSearchQuery, type AdminCustomerUpdate, type AdminPasswordMigrationRetention, type AdminPasswordMigrationRetentionInput, type Agent, type AgentAnalytics, type AgentExecutions, type AgentFromTemplate, type AgentInput, type AgentPatchOp, type AgentRequestLog, type AgentSearchQuery, type AgentSessionLog, type AgentTemplate, type AgenticPatchOp, type AgentsExport, type AgentsExportRequest, type AgentsImport, type AgentsImportRequest, AiService, type AnalyticsQuery, type Approval, type ApprovalCreated, type ApprovalDecision, type ApprovalInput, type ApprovalList, type ApprovalPatch, type ApprovalPermittedInput, type ApprovalPermittedResult, ApprovalService, type ApprovalUsersQuery, type ApprovalUsersResult, type Assignee, type Attachment, type AttachmentOptions, AuthContext, AvailabilityService, type BatchNextIdEntry, type Brand, type BrandInput, type BrandList, BrandService, type BrandUpdate, type BulkInstanceResult, type BulkPatchInstanceItem, CartService, type Catalog, type CatalogCreated, type CatalogInput, type CatalogList, type CatalogPatch, CatalogService, type CatalogUpdate, CategoryService, type CgRelation, type CgRelationList, type ChatRequest, type ChatResponse, type ChatStreamOptions, CheckoutService, ClientConfigService, type ClientConfiguration, ClientContext, CloudFunctionsService, type CommerceEvents, CompaniesService, type CompletionMessage, type CompletionRequest, type CompletionResponse, type Configuration$1 as Configuration, type ConfigurationDraft, ContactsService, type Conversation, type ConversationSearchQuery, type ConversionFactorInput, type ConversionFactorResult, type ConvertUnitInput, type ConvertUnitResult, type CookieIo, type Country, type CountryList, CountryService, type CountryUpdate, type Coupon$1 as Coupon, type CouponCreated, type CouponInput, type CouponList, CouponService, type CouponUpdate, type Created, type Currency, type CurrencyCreated, type CurrencyInput, type CurrencyList, CurrencyService, type CurrencyUpdate, type CustomEntity, type CustomEntityDraft, type CustomInstance, type CustomInstanceDraft, CustomerAdminService, CustomerGroupsService, CustomerService, type CustomerSessionState, type CustomerSessionStore, type CustomerSummaryBatch, CustomerTokenRefresher, type DeleteAgentOptions, type DeleteConfigOptions, type DeliveryCreated, type DeliveryCycleInput, type DeliverySlot, type DeliverySlotList, type DeliveryTime$1 as DeliveryTime, type DeliveryTimeInput, type DeliveryTimeList, type DeliveryTimeUpdate, type DeliveryWindow$2 as DeliveryWindow, type DeliveryWindowList, type DeliveryWindowValidation, EmporixAuthError, EmporixClient, EmporixConfig, type EmporixCore, EmporixError, EmporixForbiddenError, EmporixInsufficientScopeError, EmporixNetworkError, EmporixNotFoundError, EmporixServerError, type EmporixStorage, type EmporixStorageKey, EmporixTimeoutError, EmporixValidationError, type ExchangeRate, type ExchangeRateCreated, type ExchangeRateInput, type ExchangeRateList, type ExchangeRateUpdate, type ExecutionsQuery, type Fee$1 as Fee, type FeeDraft, FeeService, type FindSiteInput, type GetOptions, type IamAccessControl, type IamAccessControlCreated, type IamAccessControlUpsert, type IamGroup, type IamGroupCreate, type IamGroupCreated, AssignmentCreateRequest as IamGroupMemberAssignment, type IamGroupMemberCreated, type IamGroupMemberInput, type IamGroupUpdate, type IamScope, type IamScopeCreated, type IamScopeUpsert, IamService, type IamUser, type IamUserCreate, type IamUserCreated, type IamUserDetail, type IamUserScopes, type IamUserUpdate, type ImportCancelResult, type ImportConfig, type ImportErrorRecord, type ImportPage, type ImportPageOptions, type ImportRecordOutcome, type ImportRun, type ImportRunDetail, type ImportRunEvent, type ImportRunInput, type ImportRunMode, type ImportRunStatus, type ImportRunStream, type ImportSchedule, ImportService, type ImportStream, type ImportedRecord, type IndexConfig, type IndexConfigCreated, type IndexPublicConfig, IndexingService, type InstanceSearchBody, type InvoiceJob, type InvoiceJobCreated, type InvoiceJobDraft, InvoiceService, type InvokeCloudFunctionOptions, type ItemFee, type ItemFeeDraft, type ItemFeeSearch, type ItemFeeSearchByProductId, type ItemFeeSearchByProductIds, type Job, type JobIdResponse, type Label, type LabelInput, type LabelList, LabelService, type LabelUpdate, type ListConfigOptions, type ListCustomEntitiesOptions, type ListFeesQuery, type ListInstancesQuery, type ListQuery, type ListQuoteReasonsQuery, type ListQuotesQuery, type ListReindexJobsOptions, type ListSchemaReferencesQuery, type ListSchemasQuery, LocationsService, LogLevel, type McpServer, type McpServerInput, MediaService, type MetadataFilter, type MinimumFee, type MutateOptions, type NewPointsEntry, type NextIdCommandRequest, type NextIdOptions, type NextIdResponse, type NextIdsBatchRequest, type NextIdsBatchResponse, type OAuthConfig, type OAuthInput, type OrderCycleList, type OrderEntryEventCreate, type OrderStatusChange, OrdersService, type PackagingProductsChange, type PackingEvent, type PackingEventList, PaginatedItems, PaymentGatewayService, type PersistedAnonymousSession, type PickOrder, type PickOrderList, type PickPackAck, PickPackService, type PointsSummary, PriceService, ProductService, type ProviderModels, QueryFor, type Quote, type QuoteCreated, type QuoteDraft, type QuoteHistory, type QuoteInput, type QuoteReason, type QuoteReasonCreated, type QuoteReasonDraft, type QuoteReasonUpdate, type QuoteResult, QuoteService, type QuoteSlotInput, type QuoteUpdate, RagIndexerService, type RagType, type RecalculationJob, type RecalculationJobCreated, type RecalculationJobInput, type RedeemCouponResult, type RedeemMyPointsInput, type RedeemOption, type RedeemOptionList, type RedeemedPoints, type Redemption, type RedemptionCreated, type RedemptionInput, type ReferralCoupon, type Region, type RegionList, type ReindexEntityType, type ReindexInput, type ReindexJob, type ReindexJobInput, type ReindexJobStatus, ResolvedConfig, type ResourceCreated, type Return, type ReturnCreated, type ReturnInput, type ReturnList, type ReturnPatch, type ReturnUpdate, ReturnsService, RewardPointsService, STORAGE_KEYS, SalesOrdersService, type Schema, type SchemaAttribute, type SchemaDraft, type SchemaExport, type SchemaImportInput, type SchemaInstanceBulkCreateItem, type SchemaInstanceBulkUpsertItem, type SchemaReference, type SchemaReferenceCreated, type SchemaReferenceInput, type SchemaReferenceUpdateInput, SchemaService, type SchemaTypeName, type SchemaUpdate, type SearchImportedRecordsOptions, type SearchInstancesQuery, type SearchQuery, type SearchStreamRecordsOptions, SegmentService, type SequenceSchema, type SequenceSchemaCreate, SequentialIdService, type ServerCookieJar, type ServiceClass, ServiceName, type SessionAttributeInput, type SessionContext, type SessionContextPatch, SessionContextService, type SetItemFeesOptions, type ShippingFee, type ShippingGroup, type ShippingGroupList, type ShippingMethod, type ShippingMethodList, type ShippingPatch, ShippingService, type ShoppingList, type ShoppingListDraft, type ShoppingListItem, ShoppingListService, type Site$1 as Site, type SiteCreated, type SiteFields, type SiteInput, type SiteList, type SiteMixin, type SiteMixinCreated, type SiteMixins, SiteService, StoredAnonymousSession, type TaxCalculationInput, type TaxCalculationRequest, type TaxCalculationResult, type TaxClass, type TaxConfig, type TaxConfigCreated, type TaxCreation as TaxConfigInput, type TaxUpdate as TaxConfigUpdate, type TaxLocation, TaxService, TenantConfigService, type TextRequest, type TextResponse, type Token, type TokenInput, TokenProvider, type TokenStorage, type Tool, type ToolInput, type Unit, type UnitCreated, UnitHandlingService, type UnitInput, type UnitUpdate, type Vendor, type VendorCreated, type VendorInput, type VendorList, type VendorLocation, type VendorLocationInput, type VendorLocationList, type VendorLocationUpdate, type VendorSearchQuery, VendorService, type VendorUpdate, type WebhookConfig, type WebhookConfigCreated, type WebhookConfigDraft, type WebhookConfigPatch, type WebhookDashboardAccess, WebhookService, type WebhookStatistics, type WebhookStatisticsQuery, type WebhookSubscription, type WebhookSubscriptionUpdateItem, type WebhookSubscriptionUpdateResultItem, type Zone, type ZoneList, approvalStatusPatch, createCookieBackedStorage, createCookieStorage, createCore, createEmporixClient, createListenerSet, createLocalStorage, createLocalStorageStorage, createMemoryStorage, createServerStorage, createSessionStorage, emporixKey, errorFromResponse, fromWebStorage, getCustomerSessionStore, parseAnonymousSession, pickFee, productIdFromYrn, productYrn, resolveZone, serverAuth, siteMeta };
package/dist/index.d.ts CHANGED
@@ -234,6 +234,160 @@ declare function createServerStorage(jar: ServerCookieJar): EmporixStorage;
234
234
  */
235
235
  declare function serverAuth(storage: EmporixStorage): AuthContext;
236
236
 
237
+ /**
238
+ * The browser session-storage backends: memory, localStorage, sessionStorage,
239
+ * document.cookie.
240
+ *
241
+ * The contract and the framework-free backends live in `./session-storage`;
242
+ * these are the ones that need browser globals. They were in
243
+ * `@viu/emporix-sdk-react` until `@viu/emporix-sdk-angular` needed them too —
244
+ * `localStorage` is not a React API, and duplicating a storage backend per
245
+ * binding means two of them writing subtly different values under the same key.
246
+ *
247
+ * Every export is a named factory and the package sets `sideEffects: false`, so
248
+ * a Node consumer that imports none of them bundles none of them. That is
249
+ * asserted by `scripts/check-treeshake.mjs`.
250
+ */
251
+
252
+ /**
253
+ * The three methods these backends use from a Web `Storage`.
254
+ *
255
+ * Declared locally on purpose. This package compiles with `lib: ["ES2022"]` and
256
+ * no `"DOM"` — that is the invariant which keeps the SDK runnable on Node, edge
257
+ * runtimes and workers, and adding DOM to the lib to satisfy this one file would
258
+ * switch that compile-time guard off for all ~60 services. So every browser
259
+ * global below is reached through a narrowed `globalThis` instead of an ambient
260
+ * declaration, which is also the pattern the localStorage and sessionStorage
261
+ * availability checks already used before this code moved here.
262
+ */
263
+ interface WebStorageLike {
264
+ getItem(key: string): string | null;
265
+ setItem(key: string, value: string): void;
266
+ removeItem(key: string): void;
267
+ }
268
+ /**
269
+ * Internal: create a swallow-on-throw listener set used by all the storage
270
+ * backends for `subscribeAll`. Centralizes the try/catch wrapper so a buggy
271
+ * telemetry handler never breaks a storage write.
272
+ */
273
+ declare function createListenerSet<T>(): {
274
+ add(l: (value: T) => void): () => void;
275
+ notify(value: T): void;
276
+ };
277
+ /** In-memory token store. Default, SSR-safe, no persistence. */
278
+ declare function createMemoryStorage(opts?: {
279
+ initial?: string;
280
+ }): EmporixStorage;
281
+ /**
282
+ * Internal: build an {@link EmporixStorage} backed by any Web `Storage`
283
+ * instance (`localStorage` or `sessionStorage`). Both share the identical
284
+ * `getItem`/`setItem`/`removeItem` surface, so the 8-key wiring lives here once.
285
+ * Callers own the availability check + memory fallback before delegating.
286
+ */
287
+ declare function fromWebStorage(storage: WebStorageLike, opts?: {
288
+ key?: string;
289
+ }): EmporixStorage;
290
+ /**
291
+ * Browser `localStorage`-backed store: persistent and shared across tabs.
292
+ * Falls back to memory on the server (or when localStorage is unavailable).
293
+ */
294
+ declare function createLocalStorage(opts?: {
295
+ key?: string;
296
+ }): EmporixStorage;
297
+ /** @deprecated Use {@link createLocalStorage}. Kept for backward compatibility. */
298
+ declare const createLocalStorageStorage: typeof createLocalStorage;
299
+ /**
300
+ * Browser `sessionStorage`-backed store: per-tab persistence that survives a
301
+ * reload but is cleared when the tab closes and is not shared across tabs.
302
+ * Falls back to memory on the server (or when sessionStorage is unavailable).
303
+ */
304
+ declare function createSessionStorage(opts?: {
305
+ key?: string;
306
+ }): EmporixStorage;
307
+ /**
308
+ * Cookie-backed store. `Secure` defaults to on for https origins; override
309
+ * with `secure: false` only for non-https dev setups. Consumer must still pick
310
+ * an appropriate `sameSite` for CSRF safety.
311
+ */
312
+ declare function createCookieStorage(opts?: {
313
+ name?: string;
314
+ secure?: boolean;
315
+ sameSite?: "lax" | "strict" | "none";
316
+ }): EmporixStorage;
317
+
318
+ /**
319
+ * The cache-key shape every framework binding shares.
320
+ *
321
+ * Shape: `["emporix", resource, ...args, { tenant, authKind, siteCode?, language? }]`
322
+ *
323
+ * It lives in the core SDK for the same reason {@link STORAGE_KEYS} does: it is
324
+ * not a React concern. `@viu/emporix-sdk-react` and `@viu/emporix-sdk-angular`
325
+ * must produce byte-identical keys or the two bindings, the docs and the
326
+ * devtools all describe different caches. One definition is the only way that
327
+ * holds — a copy per binding would agree on the day it was written and nowhere
328
+ * after.
329
+ *
330
+ * The trailing meta object groups the discriminators that differentiate cache
331
+ * entries across tenants, auth-kinds and (where applicable) active sites.
332
+ * `siteCode` is included only when explicitly passed — non-site-aware reads
333
+ * pass `undefined` and the field is dropped.
334
+ */
335
+ declare function emporixKey<TArgs extends readonly unknown[]>(resource: string, args: TArgs, context: {
336
+ tenant: string;
337
+ authKind: string;
338
+ siteCode?: string | null;
339
+ language?: string | null;
340
+ }): readonly ["emporix", string, ...TArgs, Record<string, unknown>];
341
+ /** Which site discriminators go into the query key's meta object. */
342
+ type SiteFields = "full" | "language" | "none";
343
+ /**
344
+ * Builds the site portion of a query key's meta object. Shared by every read
345
+ * path — React's `useEmporixQuery`, its `prefetchEmporix`, and Angular's
346
+ * `emporixQueryOptions` — so none of them can disagree about which
347
+ * discriminators a resource carries. Key parity is structural, not tested.
348
+ *
349
+ * Note `null` is preserved rather than dropped: an unbound site is a distinct
350
+ * cache identity from a bound one, and {@link emporixKey} only omits a field
351
+ * when it is `undefined`.
352
+ */
353
+ declare function siteMeta(site: SiteFields, siteCode: string | null, language: string | null): {
354
+ siteCode?: string | null;
355
+ language?: string | null;
356
+ };
357
+
358
+ /**
359
+ * In-memory customer-session store, keyed by storage instance.
360
+ *
361
+ * Moved out of the React bindings: it is a subscribe/snapshot store over
362
+ * {@link EmporixStorage} with no framework API in it. React consumes it through
363
+ * `useSyncExternalStore`, Angular through a `signal` — the store itself does not
364
+ * know or care, which is exactly why it does not belong in either binding.
365
+ */
366
+
367
+ /**
368
+ * The three session tokens the customer session tracks. `token` is mirrored
369
+ * from persistent storage; `refreshToken` and `saasToken` are in-memory only
370
+ * (deliberately never persisted).
371
+ */
372
+ interface CustomerSessionState {
373
+ token: string | null;
374
+ refreshToken: string | null;
375
+ saasToken: string | null;
376
+ }
377
+ interface CustomerSessionStore {
378
+ getSnapshot: () => CustomerSessionState;
379
+ setState: (next: CustomerSessionState | ((prev: CustomerSessionState) => CustomerSessionState)) => void;
380
+ subscribe: (listener: () => void) => () => void;
381
+ }
382
+ /**
383
+ * Shared in-memory store for the customer session, keyed by the storage
384
+ * instance. Every consumer reads and writes the same store, so a login in one
385
+ * place (the auth form) is visible in another (the checkout page) — without
386
+ * this, the in-memory `saasToken` lived in a single component's local state and
387
+ * customer checkout would 401 elsewhere.
388
+ */
389
+ declare function getCustomerSessionStore(storage: EmporixStorage): CustomerSessionStore;
390
+
237
391
  /**
238
392
  * Address
239
393
  *
@@ -11930,4 +12084,4 @@ declare function productIdFromYrn(yrn: string | undefined): string;
11930
12084
  */
11931
12085
  declare function productYrn(tenant: string, productId: string): string;
11932
12086
 
11933
- export { type AddedPoints, type AdminCustomer, type AdminCustomerAddress, type AdminCustomerAddressInput, type AdminCustomerAddressList, type AdminCustomerAddressUpdate, type AdminCustomerCreated, type AdminCustomerImport, type AdminCustomerImportAccount, type AdminCustomerImportResult, type AdminCustomerInput, type AdminCustomerLegacyAuth, type AdminCustomerList, type AdminCustomerPatch, type AdminCustomerSearchQuery, type AdminCustomerUpdate, type AdminPasswordMigrationRetention, type AdminPasswordMigrationRetentionInput, type Agent, type AgentAnalytics, type AgentExecutions, type AgentFromTemplate, type AgentInput, type AgentPatchOp, type AgentRequestLog, type AgentSearchQuery, type AgentSessionLog, type AgentTemplate, type AgenticPatchOp, type AgentsExport, type AgentsExportRequest, type AgentsImport, type AgentsImportRequest, AiService, type AnalyticsQuery, type Approval, type ApprovalCreated, type ApprovalDecision, type ApprovalInput, type ApprovalList, type ApprovalPatch, type ApprovalPermittedInput, type ApprovalPermittedResult, ApprovalService, type ApprovalUsersQuery, type ApprovalUsersResult, type Assignee, type Attachment, type AttachmentOptions, AuthContext, AvailabilityService, type BatchNextIdEntry, type Brand, type BrandInput, type BrandList, BrandService, type BrandUpdate, type BulkInstanceResult, type BulkPatchInstanceItem, CartService, type Catalog, type CatalogCreated, type CatalogInput, type CatalogList, type CatalogPatch, CatalogService, type CatalogUpdate, CategoryService, type CgRelation, type CgRelationList, type ChatRequest, type ChatResponse, type ChatStreamOptions, CheckoutService, ClientConfigService, type ClientConfiguration, ClientContext, CloudFunctionsService, type CommerceEvents, CompaniesService, type CompletionMessage, type CompletionRequest, type CompletionResponse, type Configuration$1 as Configuration, type ConfigurationDraft, ContactsService, type Conversation, type ConversationSearchQuery, type ConversionFactorInput, type ConversionFactorResult, type ConvertUnitInput, type ConvertUnitResult, type CookieIo, type Country, type CountryList, CountryService, type CountryUpdate, type Coupon$1 as Coupon, type CouponCreated, type CouponInput, type CouponList, CouponService, type CouponUpdate, type Created, type Currency, type CurrencyCreated, type CurrencyInput, type CurrencyList, CurrencyService, type CurrencyUpdate, type CustomEntity, type CustomEntityDraft, type CustomInstance, type CustomInstanceDraft, CustomerAdminService, CustomerGroupsService, CustomerService, type CustomerSummaryBatch, CustomerTokenRefresher, type DeleteAgentOptions, type DeleteConfigOptions, type DeliveryCreated, type DeliveryCycleInput, type DeliverySlot, type DeliverySlotList, type DeliveryTime$1 as DeliveryTime, type DeliveryTimeInput, type DeliveryTimeList, type DeliveryTimeUpdate, type DeliveryWindow$2 as DeliveryWindow, type DeliveryWindowList, type DeliveryWindowValidation, EmporixAuthError, EmporixClient, EmporixConfig, type EmporixCore, EmporixError, EmporixForbiddenError, EmporixInsufficientScopeError, EmporixNetworkError, EmporixNotFoundError, EmporixServerError, type EmporixStorage, type EmporixStorageKey, EmporixTimeoutError, EmporixValidationError, type ExchangeRate, type ExchangeRateCreated, type ExchangeRateInput, type ExchangeRateList, type ExchangeRateUpdate, type ExecutionsQuery, type Fee$1 as Fee, type FeeDraft, FeeService, type FindSiteInput, type GetOptions, type IamAccessControl, type IamAccessControlCreated, type IamAccessControlUpsert, type IamGroup, type IamGroupCreate, type IamGroupCreated, AssignmentCreateRequest as IamGroupMemberAssignment, type IamGroupMemberCreated, type IamGroupMemberInput, type IamGroupUpdate, type IamScope, type IamScopeCreated, type IamScopeUpsert, IamService, type IamUser, type IamUserCreate, type IamUserCreated, type IamUserDetail, type IamUserScopes, type IamUserUpdate, type ImportCancelResult, type ImportConfig, type ImportErrorRecord, type ImportPage, type ImportPageOptions, type ImportRecordOutcome, type ImportRun, type ImportRunDetail, type ImportRunEvent, type ImportRunInput, type ImportRunMode, type ImportRunStatus, type ImportRunStream, type ImportSchedule, ImportService, type ImportStream, type ImportedRecord, type IndexConfig, type IndexConfigCreated, type IndexPublicConfig, IndexingService, type InstanceSearchBody, type InvoiceJob, type InvoiceJobCreated, type InvoiceJobDraft, InvoiceService, type InvokeCloudFunctionOptions, type ItemFee, type ItemFeeDraft, type ItemFeeSearch, type ItemFeeSearchByProductId, type ItemFeeSearchByProductIds, type Job, type JobIdResponse, type Label, type LabelInput, type LabelList, LabelService, type LabelUpdate, type ListConfigOptions, type ListCustomEntitiesOptions, type ListFeesQuery, type ListInstancesQuery, type ListQuery, type ListQuoteReasonsQuery, type ListQuotesQuery, type ListReindexJobsOptions, type ListSchemaReferencesQuery, type ListSchemasQuery, LocationsService, LogLevel, type McpServer, type McpServerInput, MediaService, type MetadataFilter, type MinimumFee, type MutateOptions, type NewPointsEntry, type NextIdCommandRequest, type NextIdOptions, type NextIdResponse, type NextIdsBatchRequest, type NextIdsBatchResponse, type OAuthConfig, type OAuthInput, type OrderCycleList, type OrderEntryEventCreate, type OrderStatusChange, OrdersService, type PackagingProductsChange, type PackingEvent, type PackingEventList, PaginatedItems, PaymentGatewayService, type PersistedAnonymousSession, type PickOrder, type PickOrderList, type PickPackAck, PickPackService, type PointsSummary, PriceService, ProductService, type ProviderModels, QueryFor, type Quote, type QuoteCreated, type QuoteDraft, type QuoteHistory, type QuoteInput, type QuoteReason, type QuoteReasonCreated, type QuoteReasonDraft, type QuoteReasonUpdate, type QuoteResult, QuoteService, type QuoteSlotInput, type QuoteUpdate, RagIndexerService, type RagType, type RecalculationJob, type RecalculationJobCreated, type RecalculationJobInput, type RedeemCouponResult, type RedeemMyPointsInput, type RedeemOption, type RedeemOptionList, type RedeemedPoints, type Redemption, type RedemptionCreated, type RedemptionInput, type ReferralCoupon, type Region, type RegionList, type ReindexEntityType, type ReindexInput, type ReindexJob, type ReindexJobInput, type ReindexJobStatus, ResolvedConfig, type ResourceCreated, type Return, type ReturnCreated, type ReturnInput, type ReturnList, type ReturnPatch, type ReturnUpdate, ReturnsService, RewardPointsService, STORAGE_KEYS, SalesOrdersService, type Schema, type SchemaAttribute, type SchemaDraft, type SchemaExport, type SchemaImportInput, type SchemaInstanceBulkCreateItem, type SchemaInstanceBulkUpsertItem, type SchemaReference, type SchemaReferenceCreated, type SchemaReferenceInput, type SchemaReferenceUpdateInput, SchemaService, type SchemaTypeName, type SchemaUpdate, type SearchImportedRecordsOptions, type SearchInstancesQuery, type SearchQuery, type SearchStreamRecordsOptions, SegmentService, type SequenceSchema, type SequenceSchemaCreate, SequentialIdService, type ServerCookieJar, type ServiceClass, ServiceName, type SessionAttributeInput, type SessionContext, type SessionContextPatch, SessionContextService, type SetItemFeesOptions, type ShippingFee, type ShippingGroup, type ShippingGroupList, type ShippingMethod, type ShippingMethodList, type ShippingPatch, ShippingService, type ShoppingList, type ShoppingListDraft, type ShoppingListItem, ShoppingListService, type Site$1 as Site, type SiteCreated, type SiteInput, type SiteList, type SiteMixin, type SiteMixinCreated, type SiteMixins, SiteService, StoredAnonymousSession, type TaxCalculationInput, type TaxCalculationRequest, type TaxCalculationResult, type TaxClass, type TaxConfig, type TaxConfigCreated, type TaxCreation as TaxConfigInput, type TaxUpdate as TaxConfigUpdate, type TaxLocation, TaxService, TenantConfigService, type TextRequest, type TextResponse, type Token, type TokenInput, TokenProvider, type TokenStorage, type Tool, type ToolInput, type Unit, type UnitCreated, UnitHandlingService, type UnitInput, type UnitUpdate, type Vendor, type VendorCreated, type VendorInput, type VendorList, type VendorLocation, type VendorLocationInput, type VendorLocationList, type VendorLocationUpdate, type VendorSearchQuery, VendorService, type VendorUpdate, type WebhookConfig, type WebhookConfigCreated, type WebhookConfigDraft, type WebhookConfigPatch, type WebhookDashboardAccess, WebhookService, type WebhookStatistics, type WebhookStatisticsQuery, type WebhookSubscription, type WebhookSubscriptionUpdateItem, type WebhookSubscriptionUpdateResultItem, type Zone, type ZoneList, approvalStatusPatch, createCookieBackedStorage, createCore, createEmporixClient, createServerStorage, errorFromResponse, parseAnonymousSession, pickFee, productIdFromYrn, productYrn, resolveZone, serverAuth };
12087
+ export { type AddedPoints, type AdminCustomer, type AdminCustomerAddress, type AdminCustomerAddressInput, type AdminCustomerAddressList, type AdminCustomerAddressUpdate, type AdminCustomerCreated, type AdminCustomerImport, type AdminCustomerImportAccount, type AdminCustomerImportResult, type AdminCustomerInput, type AdminCustomerLegacyAuth, type AdminCustomerList, type AdminCustomerPatch, type AdminCustomerSearchQuery, type AdminCustomerUpdate, type AdminPasswordMigrationRetention, type AdminPasswordMigrationRetentionInput, type Agent, type AgentAnalytics, type AgentExecutions, type AgentFromTemplate, type AgentInput, type AgentPatchOp, type AgentRequestLog, type AgentSearchQuery, type AgentSessionLog, type AgentTemplate, type AgenticPatchOp, type AgentsExport, type AgentsExportRequest, type AgentsImport, type AgentsImportRequest, AiService, type AnalyticsQuery, type Approval, type ApprovalCreated, type ApprovalDecision, type ApprovalInput, type ApprovalList, type ApprovalPatch, type ApprovalPermittedInput, type ApprovalPermittedResult, ApprovalService, type ApprovalUsersQuery, type ApprovalUsersResult, type Assignee, type Attachment, type AttachmentOptions, AuthContext, AvailabilityService, type BatchNextIdEntry, type Brand, type BrandInput, type BrandList, BrandService, type BrandUpdate, type BulkInstanceResult, type BulkPatchInstanceItem, CartService, type Catalog, type CatalogCreated, type CatalogInput, type CatalogList, type CatalogPatch, CatalogService, type CatalogUpdate, CategoryService, type CgRelation, type CgRelationList, type ChatRequest, type ChatResponse, type ChatStreamOptions, CheckoutService, ClientConfigService, type ClientConfiguration, ClientContext, CloudFunctionsService, type CommerceEvents, CompaniesService, type CompletionMessage, type CompletionRequest, type CompletionResponse, type Configuration$1 as Configuration, type ConfigurationDraft, ContactsService, type Conversation, type ConversationSearchQuery, type ConversionFactorInput, type ConversionFactorResult, type ConvertUnitInput, type ConvertUnitResult, type CookieIo, type Country, type CountryList, CountryService, type CountryUpdate, type Coupon$1 as Coupon, type CouponCreated, type CouponInput, type CouponList, CouponService, type CouponUpdate, type Created, type Currency, type CurrencyCreated, type CurrencyInput, type CurrencyList, CurrencyService, type CurrencyUpdate, type CustomEntity, type CustomEntityDraft, type CustomInstance, type CustomInstanceDraft, CustomerAdminService, CustomerGroupsService, CustomerService, type CustomerSessionState, type CustomerSessionStore, type CustomerSummaryBatch, CustomerTokenRefresher, type DeleteAgentOptions, type DeleteConfigOptions, type DeliveryCreated, type DeliveryCycleInput, type DeliverySlot, type DeliverySlotList, type DeliveryTime$1 as DeliveryTime, type DeliveryTimeInput, type DeliveryTimeList, type DeliveryTimeUpdate, type DeliveryWindow$2 as DeliveryWindow, type DeliveryWindowList, type DeliveryWindowValidation, EmporixAuthError, EmporixClient, EmporixConfig, type EmporixCore, EmporixError, EmporixForbiddenError, EmporixInsufficientScopeError, EmporixNetworkError, EmporixNotFoundError, EmporixServerError, type EmporixStorage, type EmporixStorageKey, EmporixTimeoutError, EmporixValidationError, type ExchangeRate, type ExchangeRateCreated, type ExchangeRateInput, type ExchangeRateList, type ExchangeRateUpdate, type ExecutionsQuery, type Fee$1 as Fee, type FeeDraft, FeeService, type FindSiteInput, type GetOptions, type IamAccessControl, type IamAccessControlCreated, type IamAccessControlUpsert, type IamGroup, type IamGroupCreate, type IamGroupCreated, AssignmentCreateRequest as IamGroupMemberAssignment, type IamGroupMemberCreated, type IamGroupMemberInput, type IamGroupUpdate, type IamScope, type IamScopeCreated, type IamScopeUpsert, IamService, type IamUser, type IamUserCreate, type IamUserCreated, type IamUserDetail, type IamUserScopes, type IamUserUpdate, type ImportCancelResult, type ImportConfig, type ImportErrorRecord, type ImportPage, type ImportPageOptions, type ImportRecordOutcome, type ImportRun, type ImportRunDetail, type ImportRunEvent, type ImportRunInput, type ImportRunMode, type ImportRunStatus, type ImportRunStream, type ImportSchedule, ImportService, type ImportStream, type ImportedRecord, type IndexConfig, type IndexConfigCreated, type IndexPublicConfig, IndexingService, type InstanceSearchBody, type InvoiceJob, type InvoiceJobCreated, type InvoiceJobDraft, InvoiceService, type InvokeCloudFunctionOptions, type ItemFee, type ItemFeeDraft, type ItemFeeSearch, type ItemFeeSearchByProductId, type ItemFeeSearchByProductIds, type Job, type JobIdResponse, type Label, type LabelInput, type LabelList, LabelService, type LabelUpdate, type ListConfigOptions, type ListCustomEntitiesOptions, type ListFeesQuery, type ListInstancesQuery, type ListQuery, type ListQuoteReasonsQuery, type ListQuotesQuery, type ListReindexJobsOptions, type ListSchemaReferencesQuery, type ListSchemasQuery, LocationsService, LogLevel, type McpServer, type McpServerInput, MediaService, type MetadataFilter, type MinimumFee, type MutateOptions, type NewPointsEntry, type NextIdCommandRequest, type NextIdOptions, type NextIdResponse, type NextIdsBatchRequest, type NextIdsBatchResponse, type OAuthConfig, type OAuthInput, type OrderCycleList, type OrderEntryEventCreate, type OrderStatusChange, OrdersService, type PackagingProductsChange, type PackingEvent, type PackingEventList, PaginatedItems, PaymentGatewayService, type PersistedAnonymousSession, type PickOrder, type PickOrderList, type PickPackAck, PickPackService, type PointsSummary, PriceService, ProductService, type ProviderModels, QueryFor, type Quote, type QuoteCreated, type QuoteDraft, type QuoteHistory, type QuoteInput, type QuoteReason, type QuoteReasonCreated, type QuoteReasonDraft, type QuoteReasonUpdate, type QuoteResult, QuoteService, type QuoteSlotInput, type QuoteUpdate, RagIndexerService, type RagType, type RecalculationJob, type RecalculationJobCreated, type RecalculationJobInput, type RedeemCouponResult, type RedeemMyPointsInput, type RedeemOption, type RedeemOptionList, type RedeemedPoints, type Redemption, type RedemptionCreated, type RedemptionInput, type ReferralCoupon, type Region, type RegionList, type ReindexEntityType, type ReindexInput, type ReindexJob, type ReindexJobInput, type ReindexJobStatus, ResolvedConfig, type ResourceCreated, type Return, type ReturnCreated, type ReturnInput, type ReturnList, type ReturnPatch, type ReturnUpdate, ReturnsService, RewardPointsService, STORAGE_KEYS, SalesOrdersService, type Schema, type SchemaAttribute, type SchemaDraft, type SchemaExport, type SchemaImportInput, type SchemaInstanceBulkCreateItem, type SchemaInstanceBulkUpsertItem, type SchemaReference, type SchemaReferenceCreated, type SchemaReferenceInput, type SchemaReferenceUpdateInput, SchemaService, type SchemaTypeName, type SchemaUpdate, type SearchImportedRecordsOptions, type SearchInstancesQuery, type SearchQuery, type SearchStreamRecordsOptions, SegmentService, type SequenceSchema, type SequenceSchemaCreate, SequentialIdService, type ServerCookieJar, type ServiceClass, ServiceName, type SessionAttributeInput, type SessionContext, type SessionContextPatch, SessionContextService, type SetItemFeesOptions, type ShippingFee, type ShippingGroup, type ShippingGroupList, type ShippingMethod, type ShippingMethodList, type ShippingPatch, ShippingService, type ShoppingList, type ShoppingListDraft, type ShoppingListItem, ShoppingListService, type Site$1 as Site, type SiteCreated, type SiteFields, type SiteInput, type SiteList, type SiteMixin, type SiteMixinCreated, type SiteMixins, SiteService, StoredAnonymousSession, type TaxCalculationInput, type TaxCalculationRequest, type TaxCalculationResult, type TaxClass, type TaxConfig, type TaxConfigCreated, type TaxCreation as TaxConfigInput, type TaxUpdate as TaxConfigUpdate, type TaxLocation, TaxService, TenantConfigService, type TextRequest, type TextResponse, type Token, type TokenInput, TokenProvider, type TokenStorage, type Tool, type ToolInput, type Unit, type UnitCreated, UnitHandlingService, type UnitInput, type UnitUpdate, type Vendor, type VendorCreated, type VendorInput, type VendorList, type VendorLocation, type VendorLocationInput, type VendorLocationList, type VendorLocationUpdate, type VendorSearchQuery, VendorService, type VendorUpdate, type WebhookConfig, type WebhookConfigCreated, type WebhookConfigDraft, type WebhookConfigPatch, type WebhookDashboardAccess, WebhookService, type WebhookStatistics, type WebhookStatisticsQuery, type WebhookSubscription, type WebhookSubscriptionUpdateItem, type WebhookSubscriptionUpdateResultItem, type Zone, type ZoneList, approvalStatusPatch, createCookieBackedStorage, createCookieStorage, createCore, createEmporixClient, createListenerSet, createLocalStorage, createLocalStorageStorage, createMemoryStorage, createServerStorage, createSessionStorage, emporixKey, errorFromResponse, fromWebStorage, getCustomerSessionStore, parseAnonymousSession, pickFee, productIdFromYrn, productYrn, resolveZone, serverAuth, siteMeta };
package/dist/index.js CHANGED
@@ -382,6 +382,249 @@ function serverAuth(storage) {
382
382
  return token !== null ? auth.customer(token) : auth.anonymous();
383
383
  }
384
384
 
385
+ // src/core/browser-storage.ts
386
+ var browser = globalThis;
387
+ function createListenerSet() {
388
+ const listeners = /* @__PURE__ */ new Set();
389
+ return {
390
+ add(l) {
391
+ listeners.add(l);
392
+ return () => listeners.delete(l);
393
+ },
394
+ notify(value) {
395
+ for (const l of listeners) {
396
+ try {
397
+ l(value);
398
+ } catch {
399
+ }
400
+ }
401
+ }
402
+ };
403
+ }
404
+ function createMemoryStorage(opts = {}) {
405
+ let token = opts.initial ?? null;
406
+ let cartId = null;
407
+ let anon = null;
408
+ let siteCode = null;
409
+ let language = null;
410
+ let activeLegalEntityId = null;
411
+ let refreshToken = null;
412
+ let saasToken = null;
413
+ const tokenListeners = /* @__PURE__ */ new Set();
414
+ const all = createListenerSet();
415
+ return {
416
+ getCustomerToken: () => token,
417
+ setCustomerToken: (t) => {
418
+ token = t;
419
+ for (const l of tokenListeners) l(token);
420
+ all.notify("customerToken");
421
+ },
422
+ subscribe: (l) => {
423
+ tokenListeners.add(l);
424
+ return () => tokenListeners.delete(l);
425
+ },
426
+ getCartId: () => cartId,
427
+ setCartId: (id) => {
428
+ cartId = id;
429
+ all.notify("cartId");
430
+ },
431
+ getAnonymousSession: () => anon,
432
+ setAnonymousSession: (s) => {
433
+ anon = s;
434
+ all.notify("anonymousSession");
435
+ },
436
+ getSiteCode: () => siteCode,
437
+ setSiteCode: (code) => {
438
+ siteCode = code;
439
+ all.notify("siteCode");
440
+ },
441
+ getLanguage: () => language,
442
+ setLanguage: (l) => {
443
+ language = l;
444
+ all.notify("language");
445
+ },
446
+ getActiveLegalEntityId: () => activeLegalEntityId,
447
+ setActiveLegalEntityId: (id) => {
448
+ activeLegalEntityId = id;
449
+ all.notify("activeLegalEntityId");
450
+ },
451
+ getRefreshToken: () => refreshToken,
452
+ setRefreshToken: (t) => {
453
+ refreshToken = t;
454
+ all.notify("refreshToken");
455
+ },
456
+ getSaasToken: () => saasToken,
457
+ setSaasToken: (t) => {
458
+ saasToken = t;
459
+ all.notify("saasToken");
460
+ },
461
+ subscribeAll: (l) => all.add(l)
462
+ };
463
+ }
464
+ function fromWebStorage(storage, opts = {}) {
465
+ const tokenKey = opts.key ?? STORAGE_KEYS.customerToken;
466
+ const tokenListeners = /* @__PURE__ */ new Set();
467
+ const all = createListenerSet();
468
+ return {
469
+ getCustomerToken: () => storage.getItem(tokenKey),
470
+ setCustomerToken: (t) => {
471
+ if (t === null) storage.removeItem(tokenKey);
472
+ else storage.setItem(tokenKey, t);
473
+ for (const l of tokenListeners) l(t);
474
+ all.notify("customerToken");
475
+ },
476
+ subscribe: (l) => {
477
+ tokenListeners.add(l);
478
+ return () => tokenListeners.delete(l);
479
+ },
480
+ getCartId: () => storage.getItem(STORAGE_KEYS.cartId),
481
+ setCartId: (id) => {
482
+ if (id === null) storage.removeItem(STORAGE_KEYS.cartId);
483
+ else storage.setItem(STORAGE_KEYS.cartId, id);
484
+ all.notify("cartId");
485
+ },
486
+ getAnonymousSession: () => parseAnonymousSession(storage.getItem(STORAGE_KEYS.anonymousSession)),
487
+ setAnonymousSession: (s) => {
488
+ if (s === null) storage.removeItem(STORAGE_KEYS.anonymousSession);
489
+ else
490
+ storage.setItem(
491
+ STORAGE_KEYS.anonymousSession,
492
+ JSON.stringify({ refreshToken: s.refreshToken, sessionId: s.sessionId })
493
+ );
494
+ all.notify("anonymousSession");
495
+ },
496
+ getSiteCode: () => storage.getItem(STORAGE_KEYS.siteCode),
497
+ setSiteCode: (code) => {
498
+ if (code === null) storage.removeItem(STORAGE_KEYS.siteCode);
499
+ else storage.setItem(STORAGE_KEYS.siteCode, code);
500
+ all.notify("siteCode");
501
+ },
502
+ getLanguage: () => storage.getItem(STORAGE_KEYS.language),
503
+ setLanguage: (l) => {
504
+ if (l === null) storage.removeItem(STORAGE_KEYS.language);
505
+ else storage.setItem(STORAGE_KEYS.language, l);
506
+ all.notify("language");
507
+ },
508
+ getActiveLegalEntityId: () => storage.getItem(STORAGE_KEYS.activeLegalEntityId),
509
+ setActiveLegalEntityId: (id) => {
510
+ if (id === null) storage.removeItem(STORAGE_KEYS.activeLegalEntityId);
511
+ else storage.setItem(STORAGE_KEYS.activeLegalEntityId, id);
512
+ all.notify("activeLegalEntityId");
513
+ },
514
+ getRefreshToken: () => storage.getItem(STORAGE_KEYS.refreshToken),
515
+ setRefreshToken: (t) => {
516
+ if (t === null) storage.removeItem(STORAGE_KEYS.refreshToken);
517
+ else storage.setItem(STORAGE_KEYS.refreshToken, t);
518
+ all.notify("refreshToken");
519
+ },
520
+ getSaasToken: () => storage.getItem(STORAGE_KEYS.saasToken),
521
+ setSaasToken: (t) => {
522
+ if (t === null) storage.removeItem(STORAGE_KEYS.saasToken);
523
+ else storage.setItem(STORAGE_KEYS.saasToken, t);
524
+ all.notify("saasToken");
525
+ },
526
+ subscribeAll: (l) => all.add(l)
527
+ };
528
+ }
529
+ function createLocalStorage(opts = {}) {
530
+ const store = browser.localStorage;
531
+ if (store === void 0) {
532
+ console.warn("[emporix] localStorage unavailable; falling back to in-memory storage");
533
+ return createMemoryStorage();
534
+ }
535
+ return fromWebStorage(store, opts);
536
+ }
537
+ var createLocalStorageStorage = createLocalStorage;
538
+ function createSessionStorage(opts = {}) {
539
+ const store = browser.sessionStorage;
540
+ if (store === void 0) {
541
+ console.warn("[emporix] sessionStorage unavailable; falling back to in-memory storage");
542
+ return createMemoryStorage();
543
+ }
544
+ return fromWebStorage(store, opts);
545
+ }
546
+ function createCookieStorage(opts = {}) {
547
+ const sameSite = opts.sameSite ?? "lax";
548
+ const secure = opts.secure ?? browser.location?.protocol === "https:";
549
+ const doc = browser.document;
550
+ if (doc === void 0) {
551
+ console.warn("[emporix] document unavailable; cookie storage falling back to in-memory");
552
+ return createMemoryStorage();
553
+ }
554
+ const attrs = `path=/; SameSite=${sameSite}${secure ? "; Secure" : ""}`;
555
+ const all = createListenerSet();
556
+ const storage = createCookieBackedStorage(
557
+ {
558
+ get: (name) => {
559
+ for (const part of doc.cookie.split("; ")) {
560
+ const [k, ...v] = part.split("=");
561
+ if (k === name) return decodeURIComponent(v.join("=")) || null;
562
+ }
563
+ return null;
564
+ },
565
+ set: (name, value) => {
566
+ doc.cookie = value === null ? `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; ${attrs}` : `${name}=${encodeURIComponent(value)}; ${attrs}`;
567
+ }
568
+ },
569
+ {
570
+ ...opts.name !== void 0 ? { tokenName: opts.name } : {},
571
+ notify: (key) => all.notify(key)
572
+ }
573
+ );
574
+ return { ...storage, subscribeAll: (l) => all.add(l) };
575
+ }
576
+
577
+ // src/core/query-keys.ts
578
+ function emporixKey(resource, args, context) {
579
+ const meta = {
580
+ tenant: context.tenant,
581
+ authKind: context.authKind
582
+ };
583
+ if (context.siteCode !== void 0) {
584
+ meta.siteCode = context.siteCode;
585
+ }
586
+ if (context.language !== void 0) {
587
+ meta.language = context.language;
588
+ }
589
+ return ["emporix", resource, ...args, meta];
590
+ }
591
+ function siteMeta(site, siteCode, language) {
592
+ return site === "full" ? { siteCode, language } : site === "language" ? { language } : {};
593
+ }
594
+
595
+ // src/core/customer-session-store.ts
596
+ var stores = /* @__PURE__ */ new WeakMap();
597
+ function getCustomerSessionStore(storage) {
598
+ const existing = stores.get(storage);
599
+ if (existing) return existing;
600
+ let state = {
601
+ token: storage.getCustomerToken(),
602
+ refreshToken: storage.getRefreshToken(),
603
+ saasToken: storage.getSaasToken?.() ?? null
604
+ };
605
+ const listeners = /* @__PURE__ */ new Set();
606
+ const store = {
607
+ getSnapshot: () => state,
608
+ setState: (next) => {
609
+ const resolved = typeof next === "function" ? next(state) : next;
610
+ if (resolved === state) return;
611
+ state = resolved;
612
+ for (const listener of listeners) listener();
613
+ },
614
+ subscribe: (listener) => {
615
+ listeners.add(listener);
616
+ return () => {
617
+ listeners.delete(listener);
618
+ };
619
+ }
620
+ };
621
+ storage.subscribe?.((t) => {
622
+ store.setState((s) => s.token === t ? s : { ...s, token: t });
623
+ });
624
+ stores.set(storage, store);
625
+ return store;
626
+ }
627
+
385
628
  // src/core/sse.ts
386
629
  function parseFrame(frame) {
387
630
  const ev = { data: "" };
@@ -702,7 +945,7 @@ var HttpClient = class {
702
945
  };
703
946
 
704
947
  // package.json
705
- var version = "3.0.0";
948
+ var version = "3.1.0";
706
949
 
707
950
  // src/version.ts
708
951
  var SDK_VERSION = version;
@@ -5002,6 +5245,6 @@ function productYrn(tenant, productId) {
5002
5245
  return `urn:yaas:hybris:product:product:${tenant};${productId}`;
5003
5246
  }
5004
5247
 
5005
- export { AiService, ApprovalService, BrandService, CatalogService, ClientConfigService, CloudFunctionsService, CountryService, CouponService, CurrencyService, CustomerAdminService, DEFAULT_HOST, EmporixClient, FeeService, HttpClient, ImportService, IndexingService, InvoiceService, LEVEL, LabelService, LevelResolver, PickPackService, QuoteService, RagIndexerService, ReturnsService, RewardPointsService, STORAGE_KEYS, SchemaService, SequentialIdService, SessionContextService, ShippingService, ShoppingListService, SiteService, TaxService, TenantConfigService, UnitHandlingService, VendorService, WebhookService, approvalStatusPatch, createConsoleLogger, createCookieBackedStorage, createCore, createEmporixClient, createNoopLogger, createServerStorage, parseAnonymousSession, pickFee, productIdFromYrn, productYrn, redact, resolveZone, serverAuth, validateConfig };
5248
+ export { AiService, ApprovalService, BrandService, CatalogService, ClientConfigService, CloudFunctionsService, CountryService, CouponService, CurrencyService, CustomerAdminService, DEFAULT_HOST, EmporixClient, FeeService, HttpClient, ImportService, IndexingService, InvoiceService, LEVEL, LabelService, LevelResolver, PickPackService, QuoteService, RagIndexerService, ReturnsService, RewardPointsService, STORAGE_KEYS, SchemaService, SequentialIdService, SessionContextService, ShippingService, ShoppingListService, SiteService, TaxService, TenantConfigService, UnitHandlingService, VendorService, WebhookService, approvalStatusPatch, createConsoleLogger, createCookieBackedStorage, createCookieStorage, createCore, createEmporixClient, createListenerSet, createLocalStorage, createLocalStorageStorage, createMemoryStorage, createNoopLogger, createServerStorage, createSessionStorage, emporixKey, fromWebStorage, getCustomerSessionStore, parseAnonymousSession, pickFee, productIdFromYrn, productYrn, redact, resolveZone, serverAuth, siteMeta, validateConfig };
5006
5249
  //# sourceMappingURL=index.js.map
5007
5250
  //# sourceMappingURL=index.js.map