@simpleapps-com/augur-hooks 2.2.5 → 2.2.7

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/EXPORTS.md CHANGED
@@ -33,8 +33,10 @@ Version: 2.0.21
33
33
  | `SearchSuggestionsResponse` | value | |
34
34
  | `executeBatchQuery` | function | |
35
35
  | `getCartPricingQueryOptions` | function | |
36
+ | `getRegisteredQueryAction` | function | Returns the registered query action function or null |
36
37
  | `getStockKey` | value | |
37
38
  | `getStockOptions` | value | |
39
+ | `registerQueryAction` | function | Registers a query action function for auto-detection by the provider and hooks |
38
40
  | `useAugurApi` | function | |
39
41
  | `useAugurApiOptional` | value | |
40
42
  | `useAugurAuth` | value | |
@@ -1,3 +1,12 @@
1
+ // src/query-action-registry.ts
2
+ var _queryAction = null;
3
+ function registerQueryAction(fn) {
4
+ _queryAction = fn;
5
+ }
6
+ function getRegisteredQueryAction() {
7
+ return _queryAction;
8
+ }
9
+
1
10
  // src/queries/cache-helper.ts
2
11
  import { stableStringify } from "@simpleapps-com/augur-core";
3
12
  function fnv1a(str) {
@@ -125,11 +134,11 @@ function getCartPricingQueryOptions(api, cartLines, customerId, cache) {
125
134
  }
126
135
 
127
136
  export {
137
+ registerQueryAction,
138
+ getRegisteredQueryAction,
128
139
  getStockKey,
129
140
  getStockOptions,
130
141
  executeBatchQuery,
131
- getItemPriceKey,
132
- getItemPriceOptions,
133
142
  getCartPricingQueryOptions
134
143
  };
135
- //# sourceMappingURL=chunk-F6GEN6PI.js.map
144
+ //# sourceMappingURL=chunk-7XCI5EZQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/query-action-registry.ts","../src/queries/cache-helper.ts","../src/queries/stock.ts","../src/queries/batch-query.ts","../src/queries/cart-pricing.ts"],"sourcesContent":["/**\n * Lightweight registry for a query action function.\n *\n * augur-server/hooks.ts registers its queryAction as a side effect when\n * imported. augur-hooks consumers (useCartPricing, useStock, the provider)\n * read from this registry to route data through server actions automatically.\n *\n * No circular dependency: augur-server depends on augur-hooks and writes here.\n * augur-hooks reads from its own module.\n */\n\ntype QueryActionFn = (methodPath: string, ...args: unknown[]) => Promise<unknown>;\n\nlet _queryAction: QueryActionFn | null = null;\n\n/** Register a query action function (called by augur-server/hooks.ts on import). */\nexport function registerQueryAction(fn: QueryActionFn): void {\n _queryAction = fn;\n}\n\n/** Returns the registered query action, or null if none registered. */\nexport function getRegisteredQueryAction(): QueryActionFn | null {\n return _queryAction;\n}\n\n/** Clears the registered query action. Used in tests only. @internal */\nexport function clearRegisteredQueryAction(): void {\n _queryAction = null;\n}\n","import type { CacheProvider, CacheTierConfig } from \"../types\";\nimport { stableStringify } from \"@simpleapps-com/augur-core\";\n\n/**\n * FNV-1a 32-bit hash. Fast, cross-platform (no Node crypto needed).\n */\nfunction fnv1a(str: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < str.length; i++) {\n h ^= str.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16).padStart(8, \"0\");\n}\n\n/**\n * Wraps an async function with optional Redis caching.\n *\n * - When `provider` and `tier.redis` are both set, checks Redis before\n * calling `fn`, then caches the result on miss.\n * - When either is missing, calls `fn` directly (no-op passthrough).\n *\n * @param provider Redis-compatible get/set + prefix. Undefined = skip Redis.\n * @param tier Cache tier config. Undefined or missing `redis` = skip Redis.\n * @param methodPath Dot-separated SDK method path (used as cache key segment).\n * @param fn The async function to cache (typically the SDK call).\n * @param keyArgs Values to hash for the cache key (e.g. query params).\n */\nexport async function withCache<T>(\n provider: CacheProvider | undefined,\n tier: CacheTierConfig | undefined,\n methodPath: string,\n fn: () => Promise<T>,\n ...keyArgs: unknown[]\n): Promise<T> {\n const redisTtl = tier?.redis;\n if (!provider || !redisTtl) return fn();\n\n const key = `${provider.prefix}sdk:${methodPath}:${fnv1a(stableStringify(keyArgs))}`;\n\n try {\n const cached = await provider.get(key);\n if (cached != null) return JSON.parse(cached) as T;\n } catch {\n /* Redis read error — fall through to SDK call */\n }\n\n const result = await fn();\n\n try {\n provider.set(key, JSON.stringify(result), redisTtl).catch(() => {});\n } catch {\n /* Non-serializable or write error — skip caching */\n }\n\n return result;\n}\n","import type { TStock } from \"@simpleapps-com/augur-utils\";\nimport type { AugurApiClient } from \"../provider\";\nimport type { CacheConfig } from \"../types\";\nimport { withCache } from \"./cache-helper\";\n\nexport const getStockKey = (invMastUid: number | string) => {\n return [\"stock\", invMastUid] as const;\n};\n\n/** @deprecated Use createServerQueryProxy() from augur-server/hooks instead. */\nexport const getStockOptions = (\n api: AugurApiClient,\n invMastUid: number | string,\n cache?: CacheConfig,\n) => {\n const tier = cache?.semiStatic;\n return {\n queryKey: getStockKey(invMastUid),\n queryFn: async (): Promise<TStock> => {\n const edgeCache = tier?.edgeCache;\n return withCache(\n cache?.provider,\n tier,\n \"items.invMast.stock.get\",\n async () => {\n const response = await api.items.invMast.stock.get(Number(invMastUid), {\n ...(edgeCache != null ? { edgeCache } : {}),\n });\n const stockData = response.data?.stockData ?? [];\n const companySummary = response.data?.companySummary ?? {};\n return { stockData, companySummary } as TStock;\n },\n invMastUid,\n );\n },\n staleTime: tier?.staleTime,\n gcTime: tier?.gcTime,\n };\n};\n","import type { QueryClient } from \"@tanstack/react-query\";\n\nexport interface BatchQueryConfig<TParam, TData> {\n params: TParam[];\n queryClient: QueryClient;\n /** Build individual cache key for a single param. */\n getItemKey: (param: TParam) => readonly unknown[];\n /** Build the string key for the result Record from a param. */\n getResultKey: (param: TParam) => string;\n /** Fetch only uncached items, return keyed Record. */\n fetchItems: (uncached: TParam[]) => Promise<Record<string, TData>>;\n /** Extract individual cache key from a fetched result entry (for seeding). */\n getSeedKey: (resultKey: string, data: TData) => readonly unknown[];\n}\n\n/**\n * Generic batch query executor.\n *\n * 1. Checks queryClient cache for each param\n * 2. Fetches only uncached items in a single batch call\n * 3. Seeds individual cache entries from the response\n * 4. Returns merged cached + fetched record\n */\nexport async function executeBatchQuery<TParam, TData>(\n config: BatchQueryConfig<TParam, TData>,\n): Promise<Record<string, TData>> {\n const { params, queryClient, getItemKey, getResultKey, fetchItems, getSeedKey } = config;\n\n if (params.length === 0) {\n return {};\n }\n\n const cached: Record<string, TData> = {};\n const uncached: TParam[] = [];\n\n for (const param of params) {\n const existing = queryClient.getQueryData<TData>(getItemKey(param));\n if (existing !== undefined) {\n cached[getResultKey(param)] = existing;\n } else {\n uncached.push(param);\n }\n }\n\n if (uncached.length === 0) {\n return cached;\n }\n\n const fetched = await fetchItems(uncached);\n\n for (const [key, data] of Object.entries(fetched)) {\n queryClient.setQueryData(getSeedKey(key, data as TData), data);\n }\n\n return { ...cached, ...fetched };\n}\n","import type { TPriceData } from \"@simpleapps-com/augur-utils\";\nimport type { AugurApiClient } from \"../provider\";\nimport type { CacheConfig } from \"../types\";\nimport { withCache } from \"./cache-helper\";\n\n/**\n * Generates a consistent query key for item price queries.\n * Used internally by useCartPricing and getCartPricingQueryOptions.\n */\nexport const getItemPriceKey = (\n itemId: string | undefined,\n customerId: string | number | undefined,\n quantity: number = 1,\n) => {\n return [\"price\", itemId?.toUpperCase() || \"\", customerId, quantity] as const;\n};\n\n/**\n * Query options for item price. Accepts the SDK instance so it works\n * in both client (via provider) and server (via direct construction).\n * Used internally by useCartPricing and getCartPricingQueryOptions.\n *\n * @deprecated Use createServerQueryProxy() from augur-server/hooks instead.\n */\nexport const getItemPriceOptions = (\n api: AugurApiClient,\n itemId: string | undefined,\n customerId: string | number | undefined,\n quantity: number = 1,\n cache?: CacheConfig,\n) => {\n const tier = cache?.semiStatic;\n return {\n queryKey: getItemPriceKey(itemId, customerId, quantity),\n queryFn: async (): Promise<TPriceData> => {\n const edgeCache = tier?.edgeCache;\n return withCache(\n cache?.provider,\n tier,\n \"pricing.priceEngine.get\",\n async () => {\n const response = await api.pricing.priceEngine.get({\n itemId: itemId?.toUpperCase() || \"\",\n customerId: Number(customerId),\n quantity,\n ...(edgeCache != null ? { edgeCache } : {}),\n });\n return response.data;\n },\n itemId,\n customerId,\n quantity,\n );\n },\n staleTime: tier?.staleTime,\n gcTime: tier?.gcTime,\n refetchOnReconnect: true,\n refetchOnWindowFocus: false,\n meta: { persist: true },\n };\n};\n\n/**\n * Get cart pricing query options for prefetching or parent components.\n *\n * @deprecated Use createServerQueryProxy() from augur-server/hooks instead.\n */\nexport function getCartPricingQueryOptions(\n api: AugurApiClient,\n cartLines: Array<{ itemId: string; quantity: number }>,\n customerId: string | number | undefined,\n cache?: CacheConfig,\n) {\n return cartLines.map((line) => ({\n ...getItemPriceOptions(api, line.itemId, customerId, line.quantity, cache),\n enabled: !!customerId && !!line.itemId,\n }));\n}\n"],"mappings":";AAaA,IAAI,eAAqC;AAGlC,SAAS,oBAAoB,IAAyB;AAC3D,iBAAe;AACjB;AAGO,SAAS,2BAAiD;AAC/D,SAAO;AACT;;;ACtBA,SAAS,uBAAuB;AAKhC,SAAS,MAAM,KAAqB;AAClC,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,SAAK,IAAI,WAAW,CAAC;AACrB,QAAI,KAAK,KAAK,GAAG,QAAU;AAAA,EAC7B;AACA,UAAQ,MAAM,GAAG,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AAC/C;AAeA,eAAsB,UACpB,UACA,MACA,YACA,OACG,SACS;AACZ,QAAM,WAAW,MAAM;AACvB,MAAI,CAAC,YAAY,CAAC,SAAU,QAAO,GAAG;AAEtC,QAAM,MAAM,GAAG,SAAS,MAAM,OAAO,UAAU,IAAI,MAAM,gBAAgB,OAAO,CAAC,CAAC;AAElF,MAAI;AACF,UAAM,SAAS,MAAM,SAAS,IAAI,GAAG;AACrC,QAAI,UAAU,KAAM,QAAO,KAAK,MAAM,MAAM;AAAA,EAC9C,QAAQ;AAAA,EAER;AAEA,QAAM,SAAS,MAAM,GAAG;AAExB,MAAI;AACF,aAAS,IAAI,KAAK,KAAK,UAAU,MAAM,GAAG,QAAQ,EAAE,MAAM,MAA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1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/queries/cache-helper.ts
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/query-action-registry.ts
2
+ var _queryAction = null;
3
+ function registerQueryAction(fn) {
4
+ _queryAction = fn;
5
+ }
6
+ function getRegisteredQueryAction() {
7
+ return _queryAction;
8
+ }
9
+
10
+ // src/queries/cache-helper.ts
2
11
  var _augurcore = require('@simpleapps-com/augur-core');
3
12
  function fnv1a(str) {
4
13
  let h = 2166136261;
@@ -131,5 +140,5 @@ function getCartPricingQueryOptions(api, cartLines, customerId, cache) {
131
140
 
132
141
 
133
142
 
134
- exports.getStockKey = getStockKey; exports.getStockOptions = getStockOptions; exports.executeBatchQuery = executeBatchQuery; exports.getItemPriceKey = getItemPriceKey; exports.getItemPriceOptions = getItemPriceOptions; exports.getCartPricingQueryOptions = getCartPricingQueryOptions;
135
- //# sourceMappingURL=chunk-SP2RWD73.cjs.map
143
+ exports.registerQueryAction = registerQueryAction; exports.getRegisteredQueryAction = getRegisteredQueryAction; exports.getStockKey = getStockKey; exports.getStockOptions = getStockOptions; exports.executeBatchQuery = executeBatchQuery; exports.getCartPricingQueryOptions = getCartPricingQueryOptions;
144
+ //# sourceMappingURL=chunk-U5PEVN24.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/augur-packages/augur-packages/packages/augur-hooks/dist/chunk-U5PEVN24.cjs","../src/query-action-registry.ts","../src/queries/cache-helper.ts","../src/queries/stock.ts","../src/queries/batch-query.ts","../src/queries/cart-pricing.ts"],"names":[],"mappings":"AAAA;ACaA,IAAI,aAAA,EAAqC,IAAA;AAGlC,SAAS,mBAAA,CAAoB,EAAA,EAAyB;AAC3D,EAAA,aAAA,EAAe,EAAA;AACjB;AAGO,SAAS,wBAAA,CAAA,EAAiD;AAC/D,EAAA,OAAO,YAAA;AACT;ADfA;AACA;AERA,uDAAgC;AAKhC,SAAS,KAAA,CAAM,GAAA,EAAqB;AAClC,EAAA,IAAI,EAAA,EAAI,UAAA;AACR,EAAA,IAAA,CAAA,IAAS,EAAA,EAAI,CAAA,EAAG,EAAA,EAAI,GAAA,CAAI,MAAA,EAAQ,CAAA,EAAA,EAAK;AACnC,IAAA,EAAA,GAAK,GAAA,CAAI,UAAA,CAAW,CAAC,CAAA;AACrB,IAAA,EAAA,EAAI,IAAA,CAAK,IAAA,CAAK,CAAA,EAAG,QAAU,CAAA;AAAA,EAC7B;AACA,EAAA,OAAA,CAAQ,EAAA,IAAM,CAAA,CAAA,CAAG,QAAA,CAAS,EAAE,CAAA,CAAE,QAAA,CAAS,CAAA,EAAG,GAAG,CAAA;AAC/C;AAeA,MAAA,SAAsB,SAAA,CACpB,QAAA,EACA,IAAA,EACA,UAAA,EACA,EAAA,EAAA,GACG,OAAA,EACS;AACZ,EAAA,MAAM,SAAA,kBAAW,IAAA,2BAAM,OAAA;AACvB,EAAA,GAAA,CAAI,CAAC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J;ALyDe;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/augur-packages/augur-packages/packages/augur-hooks/dist/chunk-U5PEVN24.cjs","sourcesContent":[null,"/**\n * Lightweight registry for a query action function.\n *\n * augur-server/hooks.ts registers its queryAction as a side effect when\n * imported. augur-hooks consumers (useCartPricing, useStock, the provider)\n * read from this registry to route data through server actions automatically.\n *\n * No circular dependency: augur-server depends on augur-hooks and writes here.\n * augur-hooks reads from its own module.\n */\n\ntype QueryActionFn = (methodPath: string, ...args: unknown[]) => Promise<unknown>;\n\nlet _queryAction: QueryActionFn | null = null;\n\n/** Register a query action function (called by augur-server/hooks.ts on import). */\nexport function registerQueryAction(fn: QueryActionFn): void {\n _queryAction = fn;\n}\n\n/** Returns the registered query action, or null if none registered. */\nexport function getRegisteredQueryAction(): QueryActionFn | null {\n return _queryAction;\n}\n\n/** Clears the registered query action. Used in tests only. @internal */\nexport function clearRegisteredQueryAction(): void {\n _queryAction = null;\n}\n","import type { CacheProvider, CacheTierConfig } from \"../types\";\nimport { stableStringify } from \"@simpleapps-com/augur-core\";\n\n/**\n * FNV-1a 32-bit hash. Fast, cross-platform (no Node crypto needed).\n */\nfunction fnv1a(str: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < str.length; i++) {\n h ^= str.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16).padStart(8, \"0\");\n}\n\n/**\n * Wraps an async function with optional Redis caching.\n *\n * - When `provider` and `tier.redis` are both set, checks Redis before\n * calling `fn`, then caches the result on miss.\n * - When either is missing, calls `fn` directly (no-op passthrough).\n *\n * @param provider Redis-compatible get/set + prefix. Undefined = skip Redis.\n * @param tier Cache tier config. Undefined or missing `redis` = skip Redis.\n * @param methodPath Dot-separated SDK method path (used as cache key segment).\n * @param fn The async function to cache (typically the SDK call).\n * @param keyArgs Values to hash for the cache key (e.g. query params).\n */\nexport async function withCache<T>(\n provider: CacheProvider | undefined,\n tier: CacheTierConfig | undefined,\n methodPath: string,\n fn: () => Promise<T>,\n ...keyArgs: unknown[]\n): Promise<T> {\n const redisTtl = tier?.redis;\n if (!provider || !redisTtl) return fn();\n\n const key = `${provider.prefix}sdk:${methodPath}:${fnv1a(stableStringify(keyArgs))}`;\n\n try {\n const cached = await provider.get(key);\n if (cached != null) return JSON.parse(cached) as T;\n } catch {\n /* Redis read error — fall through to SDK call */\n }\n\n const result = await fn();\n\n try {\n provider.set(key, JSON.stringify(result), redisTtl).catch(() => {});\n } catch {\n /* Non-serializable or write error — skip caching */\n }\n\n return result;\n}\n","import type { TStock } from \"@simpleapps-com/augur-utils\";\nimport type { AugurApiClient } from \"../provider\";\nimport type { CacheConfig } from \"../types\";\nimport { withCache } from \"./cache-helper\";\n\nexport const getStockKey = (invMastUid: number | string) => {\n return [\"stock\", invMastUid] as const;\n};\n\n/** @deprecated Use createServerQueryProxy() from augur-server/hooks instead. */\nexport const getStockOptions = (\n api: AugurApiClient,\n invMastUid: number | string,\n cache?: CacheConfig,\n) => {\n const tier = cache?.semiStatic;\n return {\n queryKey: getStockKey(invMastUid),\n queryFn: async (): Promise<TStock> => {\n const edgeCache = tier?.edgeCache;\n return withCache(\n cache?.provider,\n tier,\n \"items.invMast.stock.get\",\n async () => {\n const response = await api.items.invMast.stock.get(Number(invMastUid), {\n ...(edgeCache != null ? { edgeCache } : {}),\n });\n const stockData = response.data?.stockData ?? [];\n const companySummary = response.data?.companySummary ?? {};\n return { stockData, companySummary } as TStock;\n },\n invMastUid,\n );\n },\n staleTime: tier?.staleTime,\n gcTime: tier?.gcTime,\n };\n};\n","import type { QueryClient } from \"@tanstack/react-query\";\n\nexport interface BatchQueryConfig<TParam, TData> {\n params: TParam[];\n queryClient: QueryClient;\n /** Build individual cache key for a single param. */\n getItemKey: (param: TParam) => readonly unknown[];\n /** Build the string key for the result Record from a param. */\n getResultKey: (param: TParam) => string;\n /** Fetch only uncached items, return keyed Record. */\n fetchItems: (uncached: TParam[]) => Promise<Record<string, TData>>;\n /** Extract individual cache key from a fetched result entry (for seeding). */\n getSeedKey: (resultKey: string, data: TData) => readonly unknown[];\n}\n\n/**\n * Generic batch query executor.\n *\n * 1. Checks queryClient cache for each param\n * 2. Fetches only uncached items in a single batch call\n * 3. Seeds individual cache entries from the response\n * 4. Returns merged cached + fetched record\n */\nexport async function executeBatchQuery<TParam, TData>(\n config: BatchQueryConfig<TParam, TData>,\n): Promise<Record<string, TData>> {\n const { params, queryClient, getItemKey, getResultKey, fetchItems, getSeedKey } = config;\n\n if (params.length === 0) {\n return {};\n }\n\n const cached: Record<string, TData> = {};\n const uncached: TParam[] = [];\n\n for (const param of params) {\n const existing = queryClient.getQueryData<TData>(getItemKey(param));\n if (existing !== undefined) {\n cached[getResultKey(param)] = existing;\n } else {\n uncached.push(param);\n }\n }\n\n if (uncached.length === 0) {\n return cached;\n }\n\n const fetched = await fetchItems(uncached);\n\n for (const [key, data] of Object.entries(fetched)) {\n queryClient.setQueryData(getSeedKey(key, data as TData), data);\n }\n\n return { ...cached, ...fetched };\n}\n","import type { TPriceData } from \"@simpleapps-com/augur-utils\";\nimport type { AugurApiClient } from \"../provider\";\nimport type { CacheConfig } from \"../types\";\nimport { withCache } from \"./cache-helper\";\n\n/**\n * Generates a consistent query key for item price queries.\n * Used internally by useCartPricing and getCartPricingQueryOptions.\n */\nexport const getItemPriceKey = (\n itemId: string | undefined,\n customerId: string | number | undefined,\n quantity: number = 1,\n) => {\n return [\"price\", itemId?.toUpperCase() || \"\", customerId, quantity] as const;\n};\n\n/**\n * Query options for item price. Accepts the SDK instance so it works\n * in both client (via provider) and server (via direct construction).\n * Used internally by useCartPricing and getCartPricingQueryOptions.\n *\n * @deprecated Use createServerQueryProxy() from augur-server/hooks instead.\n */\nexport const getItemPriceOptions = (\n api: AugurApiClient,\n itemId: string | undefined,\n customerId: string | number | undefined,\n quantity: number = 1,\n cache?: CacheConfig,\n) => {\n const tier = cache?.semiStatic;\n return {\n queryKey: getItemPriceKey(itemId, customerId, quantity),\n queryFn: async (): Promise<TPriceData> => {\n const edgeCache = tier?.edgeCache;\n return withCache(\n cache?.provider,\n tier,\n \"pricing.priceEngine.get\",\n async () => {\n const response = await api.pricing.priceEngine.get({\n itemId: itemId?.toUpperCase() || \"\",\n customerId: Number(customerId),\n quantity,\n ...(edgeCache != null ? { edgeCache } : {}),\n });\n return response.data;\n },\n itemId,\n customerId,\n quantity,\n );\n },\n staleTime: tier?.staleTime,\n gcTime: tier?.gcTime,\n refetchOnReconnect: true,\n refetchOnWindowFocus: false,\n meta: { persist: true },\n };\n};\n\n/**\n * Get cart pricing query options for prefetching or parent components.\n *\n * @deprecated Use createServerQueryProxy() from augur-server/hooks instead.\n */\nexport function getCartPricingQueryOptions(\n api: AugurApiClient,\n cartLines: Array<{ itemId: string; quantity: number }>,\n customerId: string | number | undefined,\n cache?: CacheConfig,\n) {\n return cartLines.map((line) => ({\n ...getItemPriceOptions(api, line.itemId, customerId, line.quantity, cache),\n enabled: !!customerId && !!line.itemId,\n }));\n}\n"]}
package/dist/index.cjs CHANGED
@@ -5,10 +5,14 @@
5
5
 
6
6
 
7
7
 
8
- var _chunkSP2RWD73cjs = require('./chunk-SP2RWD73.cjs');
8
+ var _chunkU5PEVN24cjs = require('./chunk-U5PEVN24.cjs');
9
9
 
10
10
  // src/provider.tsx
11
11
  var _react = require('react');
12
+
13
+
14
+
15
+
12
16
  var _augurcore = require('@simpleapps-com/augur-core');
13
17
  var _jsxruntime = require('react/jsx-runtime');
14
18
  var AugurApiContext = _react.createContext.call(void 0, null);
@@ -18,12 +22,12 @@ var AugurOptionsContext = _react.createContext.call(void 0, null);
18
22
  var AugurSiteContext = _react.createContext.call(void 0, void 0);
19
23
  function AugurHooksProvider({ api, auth, cache, site, children }) {
20
24
  const proxyConfig = cache ? { cache: { static: cache.static, semiStatic: cache.semiStatic } } : void 0;
21
- const options = _react.useMemo.call(void 0,
22
- // eslint-disable-next-line @typescript-eslint/no-deprecated -- backward compat for sites not yet using createServerQueryProxy
23
- () => api ? _augurcore.createOptionsProxy.call(void 0, api, proxyConfig) : _augurcore.createKeysOnlyProxy.call(void 0, proxyConfig),
24
- // eslint-disable-next-line react-hooks/exhaustive-deps
25
- [api]
26
- );
25
+ const options = _react.useMemo.call(void 0, () => {
26
+ if (api) return _augurcore.createOptionsProxy.call(void 0, api, proxyConfig);
27
+ const registeredAction = _chunkU5PEVN24cjs.getRegisteredQueryAction.call(void 0, );
28
+ if (registeredAction) return _augurcore.createQueryActionProxy.call(void 0, registeredAction, proxyConfig);
29
+ return _augurcore.createKeysOnlyProxy.call(void 0, proxyConfig);
30
+ }, [api]);
27
31
  return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, AugurApiContext.Provider, { value: _nullishCoalesce(api, () => ( null)), children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, AugurAuthReactContext.Provider, { value: auth, children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, AugurCacheContext.Provider, { value: cache, children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, AugurSiteContext.Provider, { value: site, children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, AugurOptionsContext.Provider, { value: options, children }) }) }) }) });
28
32
  }
29
33
  function useAugurOptions() {
@@ -175,12 +179,11 @@ function useFormatPrice(optionsOrLocale, legacyCurrency) {
175
179
  var _reactquery = require('@tanstack/react-query');
176
180
  var _augurutils = require('@simpleapps-com/augur-utils');
177
181
  function useStock(invMastUid, options = {}) {
178
- const api = useAugurApiOptional();
179
- const cache = useAugurCache();
180
- const queryOpts = _chunkSP2RWD73cjs.getStockOptions.call(void 0, api, invMastUid, cache);
182
+ const proxy = useAugurOptions();
181
183
  const resolvedQueryFn = options.queryFn;
184
+ const proxyOpts = proxy.items.invMast.stock.get(Number(invMastUid));
182
185
  const query = _reactquery.useQuery.call(void 0, {
183
- ...queryOpts,
186
+ ...proxyOpts,
184
187
  ...resolvedQueryFn ? { queryFn: resolvedQueryFn } : {},
185
188
  enabled: (_nullishCoalesce(options.enabled, () => ( true))) && !!invMastUid,
186
189
  retry: 3,
@@ -188,24 +191,28 @@ function useStock(invMastUid, options = {}) {
188
191
  retryDelay: (attemptIndex) => Math.min(1e3 * 2 ** attemptIndex, 1e4)
189
192
  /* v8 ignore stop */
190
193
  });
194
+ const stockData = _react.useMemo.call(void 0, () => {
195
+ const rawData = query.data;
196
+ if (!rawData) return null;
197
+ const inner = _nullishCoalesce(rawData.data, () => ( rawData));
198
+ const stock = inner;
199
+ return {
200
+ stockData: _nullishCoalesce(stock.stockData, () => ( [])),
201
+ companySummary: _nullishCoalesce(stock.companySummary, () => ( {}))
202
+ };
203
+ }, [query.data]);
191
204
  const resolved = _react.useMemo.call(void 0,
192
205
  () => _augurutils.resolveStock.call(void 0, {
193
- stock: _nullishCoalesce(query.data, () => ( null)),
206
+ stock: stockData,
194
207
  companyKey: options.companyKey,
195
208
  round: options.round,
196
209
  lowStockThreshold: options.lowStockThreshold,
197
210
  showQuantity: options.showQuantity
198
211
  }),
199
- [
200
- query.data,
201
- options.companyKey,
202
- options.round,
203
- options.lowStockThreshold,
204
- options.showQuantity
205
- ]
212
+ [stockData, options.companyKey, options.round, options.lowStockThreshold, options.showQuantity]
206
213
  );
207
214
  return {
208
- stock: _nullishCoalesce(query.data, () => ( null)),
215
+ stock: stockData,
209
216
  resolved,
210
217
  loading: query.isLoading,
211
218
  error: query.error
@@ -664,25 +671,35 @@ function useCartInitialization(session, callbacks) {
664
671
 
665
672
 
666
673
  function useCartPricing(options = {}) {
667
- const api = useAugurApiOptional();
674
+ const proxy = useAugurOptions();
668
675
  const auth = useAugurAuth();
669
- const cache = useAugurCache();
670
676
  const site = useAugurSite();
671
677
  const cartLines = useCartLines();
672
678
  const customerId = _nullishCoalesce(_nullishCoalesce(options.customerId, () => ( _optionalChain([auth, 'optionalAccess', _64 => _64.customerId]))), () => ( _optionalChain([site, 'optionalAccess', _65 => _65.defaults, 'optionalAccess', _66 => _66.customerId])));
673
679
  const priceFn = options.queryFn;
674
680
  const priceQueries = _reactquery.useQueries.call(void 0, {
675
681
  queries: cartLines.map((line) => {
676
- const base = priceFn ? {
677
- queryKey: _chunkSP2RWD73cjs.getItemPriceKey.call(void 0, line.itemId, customerId, line.quantity),
678
- queryFn: () => priceFn(line.itemId, customerId, line.quantity),
682
+ if (priceFn) {
683
+ return {
684
+ queryKey: ["price", _optionalChain([line, 'access', _67 => _67.itemId, 'optionalAccess', _68 => _68.toUpperCase, 'call', _69 => _69()]) || "", customerId, line.quantity],
685
+ queryFn: () => priceFn(line.itemId, customerId, line.quantity),
686
+ refetchOnReconnect: true,
687
+ refetchOnWindowFocus: false,
688
+ meta: { persist: true },
689
+ enabled: !!customerId && !!line.itemId
690
+ };
691
+ }
692
+ const proxyOpts = proxy.pricing.priceEngine.get({
693
+ itemId: _optionalChain([line, 'access', _70 => _70.itemId, 'optionalAccess', _71 => _71.toUpperCase, 'call', _72 => _72()]) || "",
694
+ customerId: Number(customerId),
695
+ quantity: line.quantity
696
+ });
697
+ return {
698
+ ...proxyOpts,
699
+ enabled: !!customerId && !!line.itemId,
679
700
  refetchOnReconnect: true,
680
701
  refetchOnWindowFocus: false,
681
702
  meta: { persist: true }
682
- } : _chunkSP2RWD73cjs.getItemPriceOptions.call(void 0, api, line.itemId, customerId, line.quantity, cache);
683
- return {
684
- ...base,
685
- enabled: !!customerId && !!line.itemId
686
703
  };
687
704
  })
688
705
  });
@@ -690,11 +707,16 @@ function useCartPricing(options = {}) {
690
707
  const map = {};
691
708
  cartLines.forEach((line, index) => {
692
709
  const queryResult = priceQueries[index];
693
- if (_optionalChain([queryResult, 'optionalAccess', _67 => _67.data])) {
694
- const derived = _augurutils.derivePrice.call(void 0, { priceData: queryResult.data, quantity: line.quantity });
710
+ const rawData = _optionalChain([queryResult, 'optionalAccess', _73 => _73.data]);
711
+ if (rawData) {
712
+ const priceData = _nullishCoalesce(rawData.data, () => ( rawData));
713
+ const derived = _augurutils.derivePrice.call(void 0, {
714
+ priceData,
715
+ quantity: line.quantity
716
+ });
695
717
  map[line.itemId.toUpperCase()] = {
696
718
  unitPrice: derived.unitPrice,
697
- priceData: queryResult.data
719
+ priceData
698
720
  };
699
721
  }
700
722
  });
@@ -702,7 +724,7 @@ function useCartPricing(options = {}) {
702
724
  }, [cartLines, priceQueries]);
703
725
  const getUnitPrice = _react.useMemo.call(void 0, () => {
704
726
  return (itemId) => {
705
- return _nullishCoalesce(_optionalChain([prices, 'access', _68 => _68[_optionalChain([itemId, 'optionalAccess', _69 => _69.toUpperCase, 'call', _70 => _70()])], 'optionalAccess', _71 => _71.unitPrice]), () => ( 0));
727
+ return _nullishCoalesce(_optionalChain([prices, 'access', _74 => _74[_optionalChain([itemId, 'optionalAccess', _75 => _75.toUpperCase, 'call', _76 => _76()])], 'optionalAccess', _77 => _77.unitPrice]), () => ( 0));
706
728
  };
707
729
  }, [prices]);
708
730
  const getItemTotal = _react.useMemo.call(void 0, () => {
@@ -712,7 +734,7 @@ function useCartPricing(options = {}) {
712
734
  }, [getUnitPrice]);
713
735
  const subtotal = _react.useMemo.call(void 0, () => {
714
736
  return cartLines.reduce((sum, line) => {
715
- const unitPrice = _nullishCoalesce(_optionalChain([prices, 'access', _72 => _72[line.itemId.toUpperCase()], 'optionalAccess', _73 => _73.unitPrice]), () => ( 0));
737
+ const unitPrice = _nullishCoalesce(_optionalChain([prices, 'access', _78 => _78[line.itemId.toUpperCase()], 'optionalAccess', _79 => _79.unitPrice]), () => ( 0));
716
738
  return sum + unitPrice * line.quantity;
717
739
  }, 0);
718
740
  }, [cartLines, prices]);
@@ -789,7 +811,7 @@ function deserialize(data) {
789
811
 
790
812
  // src/persistence/apply-limits.ts
791
813
  function applyLimits(data, limits) {
792
- const queries = _optionalChain([data, 'access', _74 => _74.clientState, 'optionalAccess', _75 => _75.queries]);
814
+ const queries = _optionalChain([data, 'access', _80 => _80.clientState, 'optionalAccess', _81 => _81.queries]);
793
815
  if (!queries || Object.keys(limits).length === 0) return data;
794
816
  const entries = queries;
795
817
  const unlimited = [];
@@ -890,7 +912,7 @@ function useStorageMonitor(config) {
890
912
  const raw = storage.getItem(key);
891
913
  if (!raw) return;
892
914
  const parsed = JSON.parse(raw);
893
- if (!_optionalChain([parsed, 'access', _76 => _76.clientState, 'optionalAccess', _77 => _77.queries])) return;
915
+ if (!_optionalChain([parsed, 'access', _82 => _82.clientState, 'optionalAccess', _83 => _83.queries])) return;
894
916
  parsed.clientState.queries = parsed.clientState.queries.filter(
895
917
  (q) => {
896
918
  if (!Array.isArray(q.queryKey)) return true;
@@ -917,7 +939,7 @@ function useAugurPersistence(config) {
917
939
  setIsMounted(true);
918
940
  }, []);
919
941
  useStorageMonitor(config);
920
- const isDev = typeof process !== "undefined" && _optionalChain([process, 'access', _78 => _78.env, 'optionalAccess', _79 => _79["NODE_ENV"]]) === "development";
942
+ const isDev = typeof process !== "undefined" && _optionalChain([process, 'access', _84 => _84.env, 'optionalAccess', _85 => _85["NODE_ENV"]]) === "development";
921
943
  const { persistableKeys } = config;
922
944
  const dehydrateOptions = _react.useMemo.call(void 0,
923
945
  () => ({
@@ -967,5 +989,7 @@ function useAugurPersistence(config) {
967
989
 
968
990
 
969
991
 
970
- exports.AugurHooksProvider = AugurHooksProvider; exports.executeBatchQuery = _chunkSP2RWD73cjs.executeBatchQuery; exports.getCartPricingQueryOptions = _chunkSP2RWD73cjs.getCartPricingQueryOptions; exports.getStockKey = _chunkSP2RWD73cjs.getStockKey; exports.getStockOptions = _chunkSP2RWD73cjs.getStockOptions; exports.useAugurApi = useAugurApi; exports.useAugurApiOptional = useAugurApiOptional; exports.useAugurAuth = useAugurAuth; exports.useAugurCache = useAugurCache; exports.useAugurOptions = useAugurOptions; exports.useAugurPersistence = useAugurPersistence; exports.useAugurSite = useAugurSite; exports.useCartActions = useCartActions; exports.useCartHdrUid = useCartHdrUid; exports.useCartInitialization = useCartInitialization; exports.useCartLineCount = useCartLineCount; exports.useCartLines = useCartLines; exports.useCartPricing = useCartPricing; exports.useCartQuantityTotal = useCartQuantityTotal; exports.useCartStore = useCartStore; exports.useClearCart = useClearCart; exports.useDebounce = useDebounce; exports.useFormatPrice = useFormatPrice; exports.useItemFiltersStore = useItemFiltersStore; exports.usePaginationPrefetch = usePaginationPrefetch; exports.usePaymentFlow = usePaymentFlow; exports.useSetCartHdrUid = useSetCartHdrUid; exports.useSetCartLines = useSetCartLines; exports.useStock = useStock;
992
+
993
+
994
+ exports.AugurHooksProvider = AugurHooksProvider; exports.executeBatchQuery = _chunkU5PEVN24cjs.executeBatchQuery; exports.getCartPricingQueryOptions = _chunkU5PEVN24cjs.getCartPricingQueryOptions; exports.getRegisteredQueryAction = _chunkU5PEVN24cjs.getRegisteredQueryAction; exports.getStockKey = _chunkU5PEVN24cjs.getStockKey; exports.getStockOptions = _chunkU5PEVN24cjs.getStockOptions; exports.registerQueryAction = _chunkU5PEVN24cjs.registerQueryAction; exports.useAugurApi = useAugurApi; exports.useAugurApiOptional = useAugurApiOptional; exports.useAugurAuth = useAugurAuth; exports.useAugurCache = useAugurCache; exports.useAugurOptions = useAugurOptions; exports.useAugurPersistence = useAugurPersistence; exports.useAugurSite = useAugurSite; exports.useCartActions = useCartActions; exports.useCartHdrUid = useCartHdrUid; exports.useCartInitialization = useCartInitialization; exports.useCartLineCount = useCartLineCount; exports.useCartLines = useCartLines; exports.useCartPricing = useCartPricing; exports.useCartQuantityTotal = useCartQuantityTotal; exports.useCartStore = useCartStore; exports.useClearCart = useClearCart; exports.useDebounce = useDebounce; exports.useFormatPrice = useFormatPrice; exports.useItemFiltersStore = useItemFiltersStore; exports.usePaginationPrefetch = usePaginationPrefetch; exports.usePaymentFlow = usePaymentFlow; exports.useSetCartHdrUid = useSetCartHdrUid; exports.useSetCartLines = useSetCartLines; exports.useStock = useStock;
971
995
  //# sourceMappingURL=index.cjs.map