@osdk/react 0.9.3 → 0.10.0-beta.10
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/AGENTS.md +46 -221
- package/CHANGELOG.md +109 -51
- package/build/browser/new/makeExternalStore.js +61 -0
- package/build/browser/new/makeExternalStore.js.map +1 -1
- package/build/browser/new/useLinks.js +11 -4
- package/build/browser/new/useLinks.js.map +1 -1
- package/build/browser/new/useObjectSet.js +6 -3
- package/build/browser/new/useObjectSet.js.map +1 -1
- package/build/browser/new/useOsdkAction.js +2 -2
- package/build/browser/new/useOsdkAction.js.map +1 -1
- package/build/browser/new/useOsdkAggregation.js +65 -27
- package/build/browser/new/useOsdkAggregation.js.map +1 -1
- package/build/browser/new/useOsdkFunction.js +17 -12
- package/build/browser/new/useOsdkFunction.js.map +1 -1
- package/build/browser/new/useOsdkObject.js +36 -17
- package/build/browser/new/useOsdkObject.js.map +1 -1
- package/build/browser/new/useOsdkObjects.js +28 -19
- package/build/browser/new/useOsdkObjects.js.map +1 -1
- package/build/browser/{intellisense.test.helpers/useOsdkObjectsWithPivot.js → public/experimental/admin.js} +4 -19
- package/build/browser/public/experimental/admin.js.map +1 -0
- package/build/browser/public/experimental.js +0 -3
- package/build/browser/public/experimental.js.map +1 -1
- package/build/browser/useOsdkMetadata.js.map +1 -1
- package/build/cjs/{chunk-V32JHU3O.cjs → chunk-OVBG5VXE.cjs} +3 -8
- package/build/cjs/chunk-OVBG5VXE.cjs.map +1 -0
- package/build/cjs/chunk-SVVMLSKN.cjs +111 -0
- package/build/cjs/chunk-SVVMLSKN.cjs.map +1 -0
- package/build/cjs/index.cjs +4 -4
- package/build/cjs/index.d.cts +1 -1
- package/build/cjs/public/experimental/admin.cjs +146 -0
- package/build/cjs/public/experimental/admin.cjs.map +1 -0
- package/build/cjs/public/experimental/admin.d.cts +118 -0
- package/build/cjs/public/experimental.cjs +217 -478
- package/build/cjs/public/experimental.cjs.map +1 -1
- package/build/cjs/public/experimental.d.cts +88 -127
- package/build/cjs/useOsdkMetadata-BElt3F5s.d.cts +15 -0
- package/build/esm/new/makeExternalStore.js +61 -0
- package/build/esm/new/makeExternalStore.js.map +1 -1
- package/build/esm/new/useLinks.js +11 -4
- package/build/esm/new/useLinks.js.map +1 -1
- package/build/esm/new/useObjectSet.js +6 -3
- package/build/esm/new/useObjectSet.js.map +1 -1
- package/build/esm/new/useOsdkAction.js +2 -2
- package/build/esm/new/useOsdkAction.js.map +1 -1
- package/build/esm/new/useOsdkAggregation.js +65 -27
- package/build/esm/new/useOsdkAggregation.js.map +1 -1
- package/build/esm/new/useOsdkFunction.js +17 -12
- package/build/esm/new/useOsdkFunction.js.map +1 -1
- package/build/esm/new/useOsdkObject.js +36 -17
- package/build/esm/new/useOsdkObject.js.map +1 -1
- package/build/esm/new/useOsdkObjects.js +28 -19
- package/build/esm/new/useOsdkObjects.js.map +1 -1
- package/build/esm/{intellisense.test.helpers/useOsdkObjectsWithPivot.js → public/experimental/admin.js} +4 -19
- package/build/esm/public/experimental/admin.js.map +1 -0
- package/build/esm/public/experimental.js +0 -3
- package/build/esm/public/experimental.js.map +1 -1
- package/build/esm/useOsdkMetadata.js.map +1 -1
- package/build/types/new/makeExternalStore.d.ts +11 -0
- package/build/types/new/makeExternalStore.d.ts.map +1 -1
- package/build/types/new/useLinks.d.ts +19 -0
- package/build/types/new/useLinks.d.ts.map +1 -1
- package/build/types/new/useObjectSet.d.ts +6 -0
- package/build/types/new/useObjectSet.d.ts.map +1 -1
- package/build/types/new/useOsdkAggregation.d.ts +41 -3
- package/build/types/new/useOsdkAggregation.d.ts.map +1 -1
- package/build/types/new/useOsdkFunction.d.ts +11 -5
- package/build/types/new/useOsdkFunction.d.ts.map +1 -1
- package/build/types/new/useOsdkObject.d.ts +12 -1
- package/build/types/new/useOsdkObject.d.ts.map +1 -1
- package/build/types/new/useOsdkObjects.d.ts +10 -0
- package/build/types/new/useOsdkObjects.d.ts.map +1 -1
- package/build/types/public/experimental/admin.d.ts +3 -0
- package/build/types/public/experimental/admin.d.ts.map +1 -0
- package/build/types/public/experimental.d.ts +0 -3
- package/build/types/public/experimental.d.ts.map +1 -1
- package/build/types/useOsdkMetadata.d.ts +5 -4
- package/build/types/useOsdkMetadata.d.ts.map +1 -1
- package/docs/querying-data.md +19 -0
- package/{build/esm/intellisense.test.helpers/useOsdkObjectsWithProperties.js → experimental/admin.d.ts} +1 -18
- package/package.json +29 -8
- package/build/browser/intellisense.test.helpers/useOsdkObjectsWithPivot.js.map +0 -1
- package/build/browser/intellisense.test.helpers/useOsdkObjectsWithProperties.js +0 -34
- package/build/browser/intellisense.test.helpers/useOsdkObjectsWithProperties.js.map +0 -1
- package/build/browser/intellisense.test.helpers/useOsdkObjectsWithRids.js +0 -37
- package/build/browser/intellisense.test.helpers/useOsdkObjectsWithRids.js.map +0 -1
- package/build/browser/intellisense.test.js +0 -172
- package/build/browser/intellisense.test.js.map +0 -1
- package/build/cjs/chunk-V32JHU3O.cjs.map +0 -1
- package/build/cjs/useOsdkMetadata-DFZhnhGZ.d.cts +0 -14
- package/build/esm/intellisense.test.helpers/useOsdkObjectsWithPivot.js.map +0 -1
- package/build/esm/intellisense.test.helpers/useOsdkObjectsWithProperties.js.map +0 -1
- package/build/esm/intellisense.test.helpers/useOsdkObjectsWithRids.js +0 -37
- package/build/esm/intellisense.test.helpers/useOsdkObjectsWithRids.js.map +0 -1
- package/build/esm/intellisense.test.js +0 -172
- package/build/esm/intellisense.test.js.map +0 -1
- package/build/types/intellisense.test.d.ts +0 -1
- package/build/types/intellisense.test.d.ts.map +0 -1
- package/build/types/intellisense.test.helpers/useOsdkObjectsWithPivot.d.ts +0 -1
- package/build/types/intellisense.test.helpers/useOsdkObjectsWithPivot.d.ts.map +0 -1
- package/build/types/intellisense.test.helpers/useOsdkObjectsWithProperties.d.ts +0 -1
- package/build/types/intellisense.test.helpers/useOsdkObjectsWithProperties.d.ts.map +0 -1
- package/build/types/intellisense.test.helpers/useOsdkObjectsWithRids.d.ts +0 -1
- package/build/types/intellisense.test.helpers/useOsdkObjectsWithRids.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLinks.js","names":["React","makeExternalStore","OsdkContext2","emptyArray","Object","freeze","useLinks","objects","linkName","options","observableClient","useContext","enabled","otherOptions","stableWhere","useMemo","where","JSON","stringify","stableOrderBy","orderBy","objectsKey","undefined","arr","Array","isArray","map","obj","$apiName","$primaryKey","join","objectsArray","subscribe","getSnapShot","unsubscribe","observer","observeLinks","pageSize","mode","payload","useSyncExternalStore","links","resolvedList","isLoading","status","isOptimistic","error","fetchMore","hasMore"],"sources":["useLinks.ts"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n LinkedType,\n LinkNames,\n ObjectOrInterfaceDefinition,\n} from \"@osdk/api\";\nimport type { Osdk, PropertyKeys, WhereClause } from \"@osdk/client\";\nimport type { ObserveLinks } from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { makeExternalStore } from \"./makeExternalStore.js\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\nexport interface UseLinksOptions<\n T extends ObjectOrInterfaceDefinition,\n> {\n /**\n * Standard OSDK Where clause for filtering linked objects\n */\n where?: WhereClause<T>;\n\n /**\n * The preferred page size for the links list.\n */\n pageSize?: number;\n\n /** Sorting options for the linked objects */\n orderBy?: {\n [K in PropertyKeys<T>]?: \"asc\" | \"desc\";\n };\n\n /**\n * The mode to use for fetching data.\n * - undefined: Fetch data if not already in cache\n * - \"force\": Always fetch fresh data\n * - \"offline\": Only use cached data, don't make network requests\n */\n mode?: \"force\" | \"offline\";\n\n /**\n * Enable or disable the query.\n *\n * When `false`, the query will not automatically execute. It will still\n * return any cached data, but will not fetch from the server.\n *\n * This is useful for:\n * - Lazy/on-demand queries that should wait for user interaction\n * - Dependent queries that need data from another query first\n * - Conditional queries based on component state\n *\n * @default true\n * @example\n * // Dependent query - wait for employee data\n * const { object: employee } = useOsdkObject(Employee, employeeId);\n * const { links: reports } = useLinks(employee, \"reports\", {\n * enabled: !!employee\n * });\n */\n enabled?: boolean;\n}\n\nexport interface UseLinksResult<\n Q extends ObjectOrInterfaceDefinition,\n> {\n links: Osdk.Instance<Q>[] | undefined;\n isLoading: boolean;\n error: Error | undefined;\n\n /**\n * Refers to whether the links are optimistic or not.\n */\n isOptimistic: boolean;\n\n /**\n * Fetch more linked objects if pagination is supported\n */\n fetchMore: (() => Promise<unknown>) | undefined;\n\n /**\n * Indicates if there are more linked objects available to fetch\n */\n hasMore: boolean;\n}\n\nconst emptyArray = Object.freeze([]);\n\n/**\n * Hook to observe links from an object or array of objects.\n *\n * @param objects The source object(s) to observe links from\n * @param linkName The name of the link to observe\n * @param options Optional configuration for the link query\n * @returns UseLinksResult with links data and metadata\n */\nexport function useLinks<\n T extends ObjectOrInterfaceDefinition,\n L extends LinkNames<T>,\n>(\n objects: Osdk.Instance<T> | Array<Osdk.Instance<T>> | undefined,\n linkName: L,\n options: UseLinksOptions<LinkedType<T, L>> = {},\n): UseLinksResult<LinkedType<T, L>> {\n const { observableClient } = React.useContext(OsdkContext2);\n\n const { enabled = true, ...otherOptions } = options;\n\n const stableWhere = React.useMemo(\n () => otherOptions.where,\n [JSON.stringify(otherOptions.where)],\n );\n\n const stableOrderBy = React.useMemo(\n () => otherOptions.orderBy,\n [JSON.stringify(otherOptions.orderBy)],\n );\n\n const objectsKey = React.useMemo(() => {\n if (objects === undefined) return \"\";\n const arr = Array.isArray(objects) ? objects : [objects];\n return arr.map(obj => `${obj.$apiName}:${obj.$primaryKey}`).join(\",\");\n }, [objects]);\n\n // Convert single object to array for consistent handling\n const objectsArray: ReadonlyArray<Osdk.Instance<T>> = React.useMemo(() => {\n return objects === undefined\n ? emptyArray\n : Array.isArray(objects)\n ? objects\n : [objects];\n }, [objectsKey, objects]);\n\n const { subscribe, getSnapShot } = React.useMemo(\n () => {\n if (!enabled) {\n return makeExternalStore<ObserveLinks.CallbackArgs<T>>(\n () => ({ unsubscribe: () => {} }),\n `links ${linkName} for ${objectsKey} [DISABLED]`,\n );\n }\n return makeExternalStore<ObserveLinks.CallbackArgs<T>>(\n (observer) =>\n observableClient.observeLinks(\n objectsArray,\n linkName,\n {\n linkName,\n where: stableWhere,\n pageSize: otherOptions.pageSize,\n orderBy: stableOrderBy,\n mode: otherOptions.mode,\n },\n observer,\n ),\n `links ${linkName} for ${objectsKey}`,\n );\n },\n [\n enabled,\n observableClient,\n objectsArray,\n objectsKey,\n linkName,\n stableWhere,\n otherOptions.pageSize,\n stableOrderBy,\n otherOptions.mode,\n ],\n );\n\n const payload = React.useSyncExternalStore(\n subscribe,\n getSnapShot,\n );\n\n return {\n links: payload?.resolvedList,\n isLoading: enabled\n ? (payload?.status === \"loading\" || payload?.status === \"init\"\n || !payload)\n : false,\n isOptimistic: payload?.isOptimistic ?? false,\n error: payload?.error,\n fetchMore: payload?.hasMore ? payload?.fetchMore : undefined,\n hasMore: payload?.hasMore ?? false,\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AASA,OAAOA,KAAK,MAAM,OAAO;AACzB,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D,SAASC,YAAY,QAAQ,mBAAmB;AAyEhD,MAAMC,UAAU,GAAGC,MAAM,CAACC,MAAM,CAAC,EAAE,CAAC;;AAEpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,QAAQA,CAItBC,OAA+D,EAC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emptyArray","Object","freeze","emptyMap","Map","useLinks","objects","linkName","options","observableClient","useContext","enabled","otherOptions","stableWhere","useMemo","where","JSON","stringify","stableOrderBy","orderBy","stableSelect","$select","objectsKey","undefined","arr","Array","isArray","map","obj","$apiName","$primaryKey","join","objectsArray","subscribe","getSnapShot","unsubscribe","observer","observeLinks","pageSize","mode","dedupeInterval","dedupeIntervalMs","select","payload","useSyncExternalStore","links","resolvedList","linkedObjectsBySourcePrimaryKey","isLoading","status","isOptimistic","error","fetchMore","hasMore"],"sources":["useLinks.ts"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n LinkedType,\n LinkNames,\n ObjectOrInterfaceDefinition,\n} from \"@osdk/api\";\nimport type { Osdk, PropertyKeys, WhereClause } from \"@osdk/client\";\nimport type { ObserveLinks } from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { makeExternalStore } from \"./makeExternalStore.js\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\nexport interface UseLinksOptions<\n T extends ObjectOrInterfaceDefinition,\n> {\n /**\n * Standard OSDK Where clause for filtering linked objects\n */\n where?: WhereClause<T>;\n\n /**\n * The preferred page size for the links list.\n */\n pageSize?: number;\n\n /** Sorting options for the linked objects */\n orderBy?: {\n [K in PropertyKeys<T>]?: \"asc\" | \"desc\";\n };\n\n /**\n * Restrict which properties are returned for each linked object.\n * When provided, only the specified properties will be fetched,\n * reducing payload sizes for list views.\n */\n $select?: readonly PropertyKeys<T>[];\n\n /**\n * The mode to use for fetching data.\n * - undefined: Fetch data if not already in cache\n * - \"force\": Always fetch fresh data\n * - \"offline\": Only use cached data, don't make network requests\n */\n mode?: \"force\" | \"offline\";\n\n /**\n * The number of milliseconds to wait after the last observed link change.\n *\n * Two uses of `useLinks` with the same parameters will only trigger one\n * network request if the second is within `dedupeIntervalMs`.\n */\n dedupeIntervalMs?: number;\n\n /**\n * Enable or disable the query.\n *\n * When `false`, the query will not automatically execute. It will still\n * return any cached data, but will not fetch from the server.\n *\n * This is useful for:\n * - Lazy/on-demand queries that should wait for user interaction\n * - Dependent queries that need data from another query first\n * - Conditional queries based on component state\n *\n * @default true\n * @example\n * // Dependent query - wait for employee data\n * const { object: employee } = useOsdkObject(Employee, employeeId);\n * const { links: reports } = useLinks(employee, \"reports\", {\n * enabled: !!employee\n * });\n */\n enabled?: boolean;\n}\n\nexport interface UseLinksResult<\n Q extends ObjectOrInterfaceDefinition,\n> {\n links: Osdk.Instance<Q>[] | undefined;\n\n /**\n * Maps each source object's primary key to its linked object instances.\n * Useful when observing links from multiple source objects to determine\n * which source links to which targets.\n */\n linkedObjectsBySourcePrimaryKey: ReadonlyMap<\n string | number,\n ReadonlyArray<Osdk.Instance<Q>>\n >;\n\n isLoading: boolean;\n error: Error | undefined;\n\n /**\n * Refers to whether the links are optimistic or not.\n */\n isOptimistic: boolean;\n\n /**\n * Fetch more linked objects if pagination is supported\n */\n fetchMore: (() => Promise<unknown>) | undefined;\n\n /**\n * Indicates if there are more linked objects available to fetch\n */\n hasMore: boolean;\n}\n\nconst emptyArray = Object.freeze([]);\nconst emptyMap: ReadonlyMap<string | number, ReadonlyArray<never>> = new Map();\n\n/**\n * Hook to observe links from an object or array of objects.\n *\n * @param objects The source object(s) to observe links from\n * @param linkName The name of the link to observe\n * @param options Optional configuration for the link query\n * @returns UseLinksResult with links data and metadata\n */\nexport function useLinks<\n T extends ObjectOrInterfaceDefinition,\n L extends LinkNames<T>,\n>(\n objects: Osdk.Instance<T> | Array<Osdk.Instance<T>> | undefined,\n linkName: L,\n options: UseLinksOptions<LinkedType<T, L>> = {},\n): UseLinksResult<LinkedType<T, L>> {\n const { observableClient } = React.useContext(OsdkContext2);\n\n const { enabled = true, ...otherOptions } = options;\n\n const stableWhere = React.useMemo(\n () => otherOptions.where,\n [JSON.stringify(otherOptions.where)],\n );\n\n const stableOrderBy = React.useMemo(\n () => otherOptions.orderBy,\n [JSON.stringify(otherOptions.orderBy)],\n );\n\n const stableSelect = React.useMemo(\n () => otherOptions.$select,\n [JSON.stringify(otherOptions.$select)],\n );\n\n const objectsKey = React.useMemo(() => {\n if (objects === undefined) return \"\";\n const arr = Array.isArray(objects) ? objects : [objects];\n return arr.map(obj => `${obj.$apiName}:${obj.$primaryKey}`).join(\",\");\n }, [objects]);\n\n // Convert single object to array for consistent handling\n const objectsArray: ReadonlyArray<Osdk.Instance<T>> = React.useMemo(() => {\n return objects === undefined\n ? emptyArray\n : Array.isArray(objects)\n ? objects\n : [objects];\n }, [objectsKey, objects]);\n\n const { subscribe, getSnapShot } = React.useMemo(\n () => {\n if (!enabled) {\n return makeExternalStore<ObserveLinks.CallbackArgs<T>>(\n () => ({ unsubscribe: () => {} }),\n `links ${linkName} for ${objectsKey} [DISABLED]`,\n );\n }\n return makeExternalStore<ObserveLinks.CallbackArgs<T>>(\n (observer) =>\n observableClient.observeLinks(\n objectsArray,\n linkName,\n {\n linkName,\n where: stableWhere,\n pageSize: otherOptions.pageSize,\n orderBy: stableOrderBy,\n mode: otherOptions.mode,\n dedupeInterval: otherOptions.dedupeIntervalMs ?? 2_000,\n ...(stableSelect ? { select: stableSelect } : {}),\n },\n observer,\n ),\n `links ${linkName} for ${objectsKey}`,\n );\n },\n [\n enabled,\n observableClient,\n objectsArray,\n objectsKey,\n linkName,\n stableWhere,\n otherOptions.pageSize,\n stableOrderBy,\n otherOptions.mode,\n otherOptions.dedupeIntervalMs,\n stableSelect,\n ],\n );\n\n const payload = React.useSyncExternalStore(\n subscribe,\n getSnapShot,\n );\n\n return React.useMemo(() => ({\n links: payload?.resolvedList,\n linkedObjectsBySourcePrimaryKey: payload?.linkedObjectsBySourcePrimaryKey\n ?? emptyMap,\n isLoading: enabled\n ? (payload?.status === \"loading\" || payload?.status === \"init\"\n || !payload)\n : false,\n isOptimistic: payload?.isOptimistic ?? false,\n error: payload?.error,\n fetchMore: payload?.hasMore ? payload?.fetchMore : undefined,\n hasMore: payload?.hasMore ?? false,\n }), [payload, enabled]);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AASA,OAAOA,KAAK,MAAM,OAAO;AACzB,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D,SAASC,YAAY,QAAQ,mBAAmB;AAmGhD,MAAMC,UAAU,GAAGC,MAAM,CAACC,MAAM,CAAC,EAAE,CAAC;AACpC,MAAMC,QAA4D,GAAG,IAAIC,GAAG,CAAC,CAAC;;AAE9E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,QAAQA,CAItBC,OAA+D,EAC/DC,QAAW,EACXC,OAA0C,GAAG,CAAC,CAAC,EACb;EAClC,MAAM;IAAEC;EAAiB,CAAC,GAAGZ,KAAK,CAACa,UAAU,CAACX,YAAY,CAAC;EAE3D,MAAM;IAAEY,OAAO,GAAG,IAAI;IAAE,GAAGC;EAAa,CAAC,GAAGJ,OAAO;EAEnD,MAAMK,WAAW,GAAGhB,KAAK,CAACiB,OAAO,CAC/B,MAAMF,YAAY,CAACG,KAAK,EACxB,CAACC,IAAI,CAACC,SAAS,CAACL,YAAY,CAACG,KAAK,CAAC,CACrC,CAAC;EAED,MAAMG,aAAa,GAAGrB,KAAK,CAACiB,OAAO,CACjC,MAAMF,YAAY,CAACO,OAAO,EAC1B,CAACH,IAAI,CAACC,SAAS,CAACL,YAAY,CAACO,OAAO,CAAC,CACvC,CAAC;EAED,MAAMC,YAAY,GAAGvB,KAAK,CAACiB,OAAO,CAChC,MAAMF,YAAY,CAACS,OAAO,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B,IAAI;MACvBC,cAAc,EAAE5B,YAAY,CAAC6B,gBAAgB,IAAI,KAAK;MACtD,IAAIrB,YAAY,GAAG;QAAEsB,MAAM,EAAEtB;MAAa,CAAC,GAAG,CAAC,CAAC;IAClD,CAAC,EACDgB,QACF,CAAC,EACH,SAAS7B,QAAQ,QAAQe,UAAU,EACrC,CAAC;EACH,CAAC,EACD,CACEX,OAAO,EACPF,gBAAgB,EAChBuB,YAAY,EACZV,UAAU,EACVf,QAAQ,EACRM,WAAW,EACXD,YAAY,CAAC0B,QAAQ,EACrBpB,aAAa,EACbN,YAAY,CAAC2B,IAAI,EACjB3B,YAAY,CAAC6B,gBAAgB,EAC7BrB,YAAY,CAEhB,CAAC;EAED,MAAMuB,OAAO,GAAG9C,KAAK,CAAC+C,oBAAoB,CACxCX,SAAS,EACTC,WACF,CAAC;EAED,OAAOrC,KAAK,CAACiB,OAAO,CAAC,OAAO;IAC1B+B,KAAK,EAAEF,OAAO,EAAEG,YAAY;IAC5BC,+BAA+B,EAAEJ,OAAO,EAAEI,+BAA+B,IACpE5C,QAAQ;IACb6C,SAAS,EAAErC,OAAO,GACbgC,OAAO,EAAEM,MAAM,KAAK,SAAS,IAAIN,OAAO,EAAEM,MAAM,KAAK,MAAM,IACzD,CAACN,OAAO,GACX,KAAK;IACTO,YAAY,EAAEP,OAAO,EAAEO,YAAY,IAAI,KAAK;IAC5CC,KAAK,EAAER,OAAO,EAAEQ,KAAK;IACrBC,SAAS,EAAET,OAAO,EAAEU,OAAO,GAAGV,OAAO,EAAES,SAAS,GAAG7B,SAAS;IAC5D8B,OAAO,EAAEV,OAAO,EAAEU,OAAO,IAAI;EAC/B,CAAC,CAAC,EAAE,CAACV,OAAO,EAAEhC,OAAO,CAAC,CAAC;AACzB","ignoreList":[]}
|
|
@@ -18,6 +18,7 @@ import { computeObjectSetCacheKey } from "@osdk/client/unstable-do-not-use";
|
|
|
18
18
|
import React from "react";
|
|
19
19
|
import { makeExternalStore } from "./makeExternalStore.js";
|
|
20
20
|
import { OsdkContext2 } from "./OsdkContext2.js";
|
|
21
|
+
const OBJECT_TYPE_PLACEHOLDER = "$__OBJECT__TYPE__PLACEHOLDER";
|
|
21
22
|
/**
|
|
22
23
|
* React hook for observing and interacting with OSDK object sets.
|
|
23
24
|
*
|
|
@@ -40,7 +41,7 @@ export function useObjectSet(baseObjectSet, options = {}) {
|
|
|
40
41
|
} = options;
|
|
41
42
|
|
|
42
43
|
// Track object type to detect when we switch to a different object type
|
|
43
|
-
const objectTypeKey = baseObjectSet.$objectSetInternals.def.apiName;
|
|
44
|
+
const objectTypeKey = enabled ? baseObjectSet.$objectSetInternals.def.apiName : OBJECT_TYPE_PLACEHOLDER;
|
|
44
45
|
const previousObjectTypeRef = React.useRef(objectTypeKey);
|
|
45
46
|
const previousCompletedPayloadRef = React.useRef();
|
|
46
47
|
const objectTypeChanged = previousObjectTypeRef.current !== objectTypeKey;
|
|
@@ -59,7 +60,8 @@ export function useObjectSet(baseObjectSet, options = {}) {
|
|
|
59
60
|
subtract: otherOptions.subtract,
|
|
60
61
|
pivotTo: otherOptions.pivotTo,
|
|
61
62
|
pageSize: otherOptions.pageSize,
|
|
62
|
-
orderBy: otherOptions.orderBy
|
|
63
|
+
orderBy: otherOptions.orderBy,
|
|
64
|
+
select: otherOptions.$select
|
|
63
65
|
});
|
|
64
66
|
const {
|
|
65
67
|
subscribe,
|
|
@@ -83,7 +85,8 @@ export function useObjectSet(baseObjectSet, options = {}) {
|
|
|
83
85
|
orderBy: otherOptions.orderBy,
|
|
84
86
|
dedupeInterval: otherOptions.dedupeIntervalMs ?? 2_000,
|
|
85
87
|
autoFetchMore: otherOptions.autoFetchMore,
|
|
86
|
-
streamUpdates
|
|
88
|
+
streamUpdates,
|
|
89
|
+
select: otherOptions.$select
|
|
87
90
|
}, observer);
|
|
88
91
|
return subscription;
|
|
89
92
|
}, process.env.NODE_ENV !== "production" ? `objectSet ${stableKey}` : void 0, initialValue);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useObjectSet.js","names":["computeObjectSetCacheKey","React","makeExternalStore","OsdkContext2","useObjectSet","baseObjectSet","options","observableClient","useContext","enabled","streamUpdates","otherOptions","objectTypeKey","$objectSetInternals","def","apiName","previousObjectTypeRef","useRef","previousCompletedPayloadRef","objectTypeChanged","current","undefined","stableKey","where","withProperties","union","intersect","subtract","pivotTo","pageSize","orderBy","subscribe","getSnapShot","useMemo","unsubscribe","process","env","NODE_ENV","initialValue","observer","subscription","observeObjectSet","dedupeInterval","dedupeIntervalMs","autoFetchMore","payload","useSyncExternalStore","isPayloadCompleted","lastLoaded","data","resolvedList","isLoading","error","fetchMore","hasMore","objectSet","totalCount","status"],"sources":["useObjectSet.tsx"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n DerivedProperty,\n LinkNames,\n ObjectOrInterfaceDefinition,\n ObjectSet,\n Osdk,\n PropertyKeys,\n SimplePropertyDef,\n WhereClause,\n} from \"@osdk/api\";\n\nimport {\n computeObjectSetCacheKey,\n type ObserveObjectSetArgs,\n} from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { makeExternalStore, type Snapshot } from \"./makeExternalStore.js\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\nexport interface UseObjectSetOptions<\n Q extends ObjectOrInterfaceDefinition,\n RDPs extends Record<string, SimplePropertyDef> = {},\n> {\n /**\n * Where clause for filtering\n */\n where?: WhereClause<Q, RDPs>;\n\n /**\n * Derived properties to add to the object set\n */\n withProperties?: { [K in keyof RDPs]: DerivedProperty.Creator<Q, RDPs[K]> };\n\n /**\n * Object sets to union with\n */\n union?: ObjectSet<Q>[];\n\n /**\n * Object sets to intersect with\n */\n intersect?: ObjectSet<Q>[];\n\n /**\n * Object sets to subtract from\n */\n subtract?: ObjectSet<Q>[];\n\n /**\n * Link to pivot to (changes the type)\n */\n pivotTo?: LinkNames<Q>;\n\n /**\n * The preferred page size for the list\n */\n pageSize?: number;\n\n /**\n * Sort order for the results\n */\n orderBy?: {\n [K in PropertyKeys<Q>]?: \"asc\" | \"desc\";\n };\n\n /**\n * Minimum time between fetch requests in milliseconds (defaults to 2000ms)\n */\n dedupeIntervalMs?: number;\n\n /**\n * Automatically fetch additional pages on initial load.\n *\n * - `true`: Fetch all available pages automatically\n * - `number`: Fetch pages until at least this many items are loaded\n * - `undefined` (default): Only fetch the first page, user must call fetchMore()\n */\n autoFetchMore?: boolean | number;\n\n /**\n * Enable streaming updates via websocket subscription.\n * When true, the object set will automatically update when matching objects are\n * added, updated, or removed.\n *\n * @default false\n */\n streamUpdates?: boolean;\n\n /**\n * Enable or disable the query.\n *\n * When `false`, the query will not automatically execute. It will still\n * return any cached data, but will not fetch from the server.\n *\n * This is useful for:\n * - Lazy/on-demand queries that should wait for user interaction\n * - Dependent queries that need data from another query first\n * - Conditional queries based on component state\n *\n * @default true\n * @example\n * // Dependent query - wait for filter selection\n * const { data: filteredObjects } = useObjectSet(MyObject.all(), {\n * where: { status: selectedStatus },\n * enabled: !!selectedStatus\n * });\n */\n enabled?: boolean;\n}\n\nexport interface UseObjectSetResult<\n Q extends ObjectOrInterfaceDefinition,\n RDPs extends Record<string, SimplePropertyDef> = {},\n> {\n /**\n * The fetched data with derived properties\n */\n data:\n | Osdk.Instance<Q, \"$allBaseProperties\", PropertyKeys<Q>, RDPs>[]\n | undefined;\n\n /**\n * Whether data is currently being loaded\n */\n isLoading: boolean;\n\n /**\n * Any error that occurred during fetching\n */\n error: Error | undefined;\n\n /**\n * Function to fetch more pages (undefined if no more pages)\n */\n fetchMore: (() => Promise<void>) | undefined;\n\n /**\n * The final ObjectSet after all transformations\n */\n objectSet: ObjectSet<Q, RDPs>;\n\n /**\n * The total count of objects matching the query (if available from the API)\n */\n totalCount?: string;\n}\n\ndeclare const process: {\n env: {\n NODE_ENV: \"development\" | \"production\";\n };\n};\n\n/**\n * React hook for observing and interacting with OSDK object sets.\n *\n * @typeParam Q - The object type definition\n * @typeParam BaseRDPs - Derived properties that already exist on the input ObjectSet\n * @typeParam RDPs - New derived properties to be added via options.withProperties\n *\n * @param baseObjectSet - The ObjectSet to observe (may already have derived properties)\n * @param options - Options for filtering, sorting, and adding new derived properties\n * @returns Object set data with both existing and new derived properties\n */\nexport function useObjectSet<\n Q extends ObjectOrInterfaceDefinition,\n BaseRDPs extends Record<string, SimplePropertyDef> = never,\n RDPs extends Record<string, SimplePropertyDef> = {},\n>(\n baseObjectSet: ObjectSet<Q, BaseRDPs>,\n options: UseObjectSetOptions<Q, RDPs> = {},\n): UseObjectSetResult<Q, RDPs> {\n const { observableClient } = React.useContext(OsdkContext2);\n\n const { enabled = true, streamUpdates, ...otherOptions } = options;\n\n // Track object type to detect when we switch to a different object type\n const objectTypeKey = baseObjectSet.$objectSetInternals.def.apiName;\n const previousObjectTypeRef = React.useRef<string>(objectTypeKey);\n const previousCompletedPayloadRef = React.useRef<\n Snapshot<ObserveObjectSetArgs<Q, RDPs>> | undefined\n >();\n\n const objectTypeChanged = previousObjectTypeRef.current !== objectTypeKey;\n if (objectTypeChanged) {\n previousObjectTypeRef.current = objectTypeKey;\n previousCompletedPayloadRef.current = undefined;\n }\n\n // Compute a stable cache key for the ObjectSet and options\n // dedupeIntervalMs and enabled are excluded as they don't affect the data\n const stableKey = computeObjectSetCacheKey(baseObjectSet, {\n where: otherOptions.where,\n withProperties: otherOptions.withProperties,\n union: otherOptions.union,\n intersect: otherOptions.intersect,\n subtract: otherOptions.subtract,\n pivotTo: otherOptions.pivotTo,\n pageSize: otherOptions.pageSize,\n orderBy: otherOptions.orderBy,\n });\n\n const { subscribe, getSnapShot } = React.useMemo(\n () => {\n if (!enabled) {\n return makeExternalStore<ObserveObjectSetArgs<Q, RDPs>>(\n () => ({ unsubscribe: () => {} }),\n process.env.NODE_ENV !== \"production\"\n ? `objectSet ${stableKey} [DISABLED]`\n : void 0,\n );\n }\n\n const initialValue = objectTypeChanged\n ? undefined\n : previousCompletedPayloadRef.current;\n\n return makeExternalStore<ObserveObjectSetArgs<Q, RDPs>>(\n (observer) => {\n const subscription = observableClient.observeObjectSet(\n baseObjectSet as ObjectSet<Q>,\n {\n where: otherOptions.where,\n withProperties: otherOptions.withProperties,\n union: otherOptions.union,\n intersect: otherOptions.intersect,\n subtract: otherOptions.subtract,\n pivotTo: otherOptions.pivotTo,\n pageSize: otherOptions.pageSize,\n orderBy: otherOptions.orderBy,\n dedupeInterval: otherOptions.dedupeIntervalMs ?? 2_000,\n autoFetchMore: otherOptions.autoFetchMore,\n streamUpdates,\n },\n observer,\n );\n return subscription;\n },\n process.env.NODE_ENV !== \"production\"\n ? `objectSet ${stableKey}`\n : void 0,\n initialValue,\n );\n },\n [enabled, observableClient, stableKey, streamUpdates, objectTypeChanged],\n );\n\n const payload = React.useSyncExternalStore(subscribe, getSnapShot);\n if (payload && isPayloadCompleted(payload)) {\n previousCompletedPayloadRef.current = payload;\n }\n\n return React.useMemo(() => {\n const lastLoaded = isPayloadCompleted(payload)\n ? payload\n : previousCompletedPayloadRef.current;\n return {\n data: lastLoaded?.resolvedList as Osdk.Instance<\n Q,\n \"$allBaseProperties\",\n PropertyKeys<Q>,\n RDPs\n >[],\n isLoading: !isPayloadCompleted(payload),\n error: lastLoaded && \"error\" in lastLoaded ? lastLoaded.error : undefined,\n fetchMore: payload?.hasMore ? payload.fetchMore : undefined,\n objectSet: payload?.objectSet as ObjectSet<Q, RDPs> || baseObjectSet,\n totalCount: lastLoaded?.totalCount,\n };\n }, [payload, baseObjectSet]);\n}\n\nfunction isPayloadCompleted<\n Q extends ObjectOrInterfaceDefinition,\n RDPs extends Record<string, SimplePropertyDef>,\n>(\n payload: Snapshot<ObserveObjectSetArgs<Q, RDPs>>,\n): boolean {\n if (payload != null && \"error\" in payload) {\n return true;\n }\n\n if (payload?.status == null) {\n return false;\n }\n\n switch (payload.status) {\n case \"loaded\":\n case \"error\":\n return true;\n case \"loading\":\n case \"init\":\n return false;\n default:\n payload.status satisfies never;\n return false;\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAaA,SACEA,wBAAwB,QAEnB,kCAAkC;AACzC,OAAOC,KAAK,MAAM,OAAO;AACzB,SAASC,iBAAiB,QAAuB,wBAAwB;AACzE,SAASC,YAAY,QAAQ,mBAAmB;AAwIhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,YAAYA,CAK1BC,aAAqC,EACrCC,OAAqC,GAAG,CAAC,CAAC,EACb;EAC7B,MAAM;IAAEC;EAAiB,CAAC,GAAGN,KAAK,CAACO,UAAU,CAACL,YAAY,CAAC;EAE3D,MAAM;IAAEM,OAAO,GAAG,IAAI;IAAEC,aAAa;IAAE,GAAGC;EAAa,CAAC,GAAGL,OAAO;;EAElE;EACA,MAAMM,aAAa,GAAGP,aAAa,CAACQ,mBAAmB,CAACC,GAAG,CAACC,OAAO;EACnE,MAAMC,qBAAqB,GAAGf,KAAK,CAACgB,MAAM,CAASL,aAAa,CAAC;EACjE,MAAMM,2BAA2B,GAAGjB,KAAK,CAACgB,MAAM,CAE9C,CAAC;EAEH,MAAME,iBAAiB,GAAGH,qBAAqB,CAACI,OAAO,KAAKR,aAAa;EACzE,IAAIO,iBAAiB,EAAE;IACrBH,qBAAqB,CAACI,OAAO,GAAGR,aAAa;IAC7CM,2BAA2B,CAACE,OAAO,GAAGC,SAAS;EACjD;;EAEA;EACA;EACA,MAAMC,SAAS,GAAGtB,wBAAwB,CAACK,aAAa,EAAE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A,OAAO,EAAEY,MAAM,IAAI,IAAI,EAAE;IAC3B,OAAO,KAAK;EACd;EAEA,QAAQZ,OAAO,CAACY,MAAM;IACpB,KAAK,QAAQ;IACb,KAAK,OAAO;MACV,OAAO,IAAI;IACb,KAAK,SAAS;IACd,KAAK,MAAM;MACT,OAAO,KAAK;IACd;MACEZ,OAAO,CAACY,MAAM;MACd,OAAO,KAAK;EAChB;AACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"useObjectSet.js","names":["computeObjectSetCacheKey","React","makeExternalStore","OsdkContext2","OBJECT_TYPE_PLACEHOLDER","useObjectSet","baseObjectSet","options","observableClient","useContext","enabled","streamUpdates","otherOptions","objectTypeKey","$objectSetInternals","def","apiName","previousObjectTypeRef","useRef","previousCompletedPayloadRef","objectTypeChanged","current","undefined","stableKey","where","withProperties","union","intersect","subtract","pivotTo","pageSize","orderBy","select","$select","subscribe","getSnapShot","useMemo","unsubscribe","process","env","NODE_ENV","initialValue","observer","subscription","observeObjectSet","dedupeInterval","dedupeIntervalMs","autoFetchMore","payload","useSyncExternalStore","isPayloadCompleted","lastLoaded","data","resolvedList","isLoading","error","fetchMore","hasMore","objectSet","totalCount","status"],"sources":["useObjectSet.tsx"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n DerivedProperty,\n LinkNames,\n ObjectOrInterfaceDefinition,\n ObjectSet,\n Osdk,\n PropertyKeys,\n SimplePropertyDef,\n WhereClause,\n} from \"@osdk/api\";\n\nimport {\n computeObjectSetCacheKey,\n type ObserveObjectSetArgs,\n} from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { makeExternalStore, type Snapshot } from \"./makeExternalStore.js\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\nexport interface UseObjectSetOptions<\n Q extends ObjectOrInterfaceDefinition,\n RDPs extends Record<string, SimplePropertyDef> = {},\n> {\n /**\n * Where clause for filtering\n */\n where?: WhereClause<Q, RDPs>;\n\n /**\n * Derived properties to add to the object set\n */\n withProperties?: { [K in keyof RDPs]: DerivedProperty.Creator<Q, RDPs[K]> };\n\n /**\n * Object sets to union with\n */\n union?: ObjectSet<Q>[];\n\n /**\n * Object sets to intersect with\n */\n intersect?: ObjectSet<Q>[];\n\n /**\n * Object sets to subtract from\n */\n subtract?: ObjectSet<Q>[];\n\n /**\n * Link to pivot to (changes the type)\n */\n pivotTo?: LinkNames<Q>;\n\n /**\n * The preferred page size for the list\n */\n pageSize?: number;\n\n /**\n * Sort order for the results\n */\n orderBy?: {\n [K in PropertyKeys<Q>]?: \"asc\" | \"desc\";\n };\n\n /**\n * Minimum time between fetch requests in milliseconds (defaults to 2000ms)\n */\n dedupeIntervalMs?: number;\n\n /**\n * Automatically fetch additional pages on initial load.\n *\n * - `true`: Fetch all available pages automatically\n * - `number`: Fetch pages until at least this many items are loaded\n * - `undefined` (default): Only fetch the first page, user must call fetchMore()\n */\n autoFetchMore?: boolean | number;\n\n /**\n * Enable streaming updates via websocket subscription.\n * When true, the object set will automatically update when matching objects are\n * added, updated, or removed.\n *\n * @default false\n */\n streamUpdates?: boolean;\n\n /**\n * Restrict which properties are returned for each object.\n * When provided, only the specified properties will be fetched,\n * reducing payload sizes for list views.\n */\n $select?: readonly PropertyKeys<Q>[];\n\n /**\n * Enable or disable the query.\n *\n * When `false`, the query will not automatically execute. It will still\n * return any cached data, but will not fetch from the server.\n *\n * This is useful for:\n * - Lazy/on-demand queries that should wait for user interaction\n * - Dependent queries that need data from another query first\n * - Conditional queries based on component state\n *\n * @default true\n * @example\n * // Dependent query - wait for filter selection\n * const { data: filteredObjects } = useObjectSet(MyObject.all(), {\n * where: { status: selectedStatus },\n * enabled: !!selectedStatus\n * });\n */\n enabled?: boolean;\n}\n\nexport interface UseObjectSetResult<\n Q extends ObjectOrInterfaceDefinition,\n RDPs extends Record<string, SimplePropertyDef> = {},\n> {\n /**\n * The fetched data with derived properties\n */\n data:\n | Osdk.Instance<Q, \"$allBaseProperties\", PropertyKeys<Q>, RDPs>[]\n | undefined;\n\n /**\n * Whether data is currently being loaded\n */\n isLoading: boolean;\n\n /**\n * Any error that occurred during fetching\n */\n error: Error | undefined;\n\n /**\n * Function to fetch more pages (undefined if no more pages)\n */\n fetchMore: (() => Promise<void>) | undefined;\n\n /**\n * The final ObjectSet after all transformations\n */\n objectSet: ObjectSet<Q, RDPs>;\n\n /**\n * The total count of objects matching the query (if available from the API)\n */\n totalCount?: string;\n}\n\ndeclare const process: {\n env: {\n NODE_ENV: \"development\" | \"production\";\n };\n};\n\nconst OBJECT_TYPE_PLACEHOLDER = \"$__OBJECT__TYPE__PLACEHOLDER\";\n/**\n * React hook for observing and interacting with OSDK object sets.\n *\n * @typeParam Q - The object type definition\n * @typeParam BaseRDPs - Derived properties that already exist on the input ObjectSet\n * @typeParam RDPs - New derived properties to be added via options.withProperties\n *\n * @param baseObjectSet - The ObjectSet to observe (may already have derived properties)\n * @param options - Options for filtering, sorting, and adding new derived properties\n * @returns Object set data with both existing and new derived properties\n */\nexport function useObjectSet<\n Q extends ObjectOrInterfaceDefinition,\n BaseRDPs extends Record<string, SimplePropertyDef> = never,\n RDPs extends Record<string, SimplePropertyDef> = {},\n>(\n baseObjectSet: ObjectSet<Q, BaseRDPs>,\n options: UseObjectSetOptions<Q, RDPs> = {},\n): UseObjectSetResult<Q, RDPs> {\n const { observableClient } = React.useContext(OsdkContext2);\n\n const { enabled = true, streamUpdates, ...otherOptions } = options;\n\n // Track object type to detect when we switch to a different object type\n const objectTypeKey = enabled\n ? baseObjectSet.$objectSetInternals.def.apiName\n : OBJECT_TYPE_PLACEHOLDER;\n\n const previousObjectTypeRef = React.useRef<string>(objectTypeKey);\n const previousCompletedPayloadRef = React.useRef<\n Snapshot<ObserveObjectSetArgs<Q, RDPs>> | undefined\n >();\n\n const objectTypeChanged = previousObjectTypeRef.current !== objectTypeKey;\n if (objectTypeChanged) {\n previousObjectTypeRef.current = objectTypeKey;\n previousCompletedPayloadRef.current = undefined;\n }\n\n // Compute a stable cache key for the ObjectSet and options\n // dedupeIntervalMs and enabled are excluded as they don't affect the data\n const stableKey = computeObjectSetCacheKey(baseObjectSet, {\n where: otherOptions.where,\n withProperties: otherOptions.withProperties,\n union: otherOptions.union,\n intersect: otherOptions.intersect,\n subtract: otherOptions.subtract,\n pivotTo: otherOptions.pivotTo,\n pageSize: otherOptions.pageSize,\n orderBy: otherOptions.orderBy,\n select: otherOptions.$select,\n });\n\n const { subscribe, getSnapShot } = React.useMemo(\n () => {\n if (!enabled) {\n return makeExternalStore<ObserveObjectSetArgs<Q, RDPs>>(\n () => ({ unsubscribe: () => {} }),\n process.env.NODE_ENV !== \"production\"\n ? `objectSet ${stableKey} [DISABLED]`\n : void 0,\n );\n }\n\n const initialValue = objectTypeChanged\n ? undefined\n : previousCompletedPayloadRef.current;\n\n return makeExternalStore<ObserveObjectSetArgs<Q, RDPs>>(\n (observer) => {\n const subscription = observableClient.observeObjectSet(\n baseObjectSet as ObjectSet<Q>,\n {\n where: otherOptions.where,\n withProperties: otherOptions.withProperties,\n union: otherOptions.union,\n intersect: otherOptions.intersect,\n subtract: otherOptions.subtract,\n pivotTo: otherOptions.pivotTo,\n pageSize: otherOptions.pageSize,\n orderBy: otherOptions.orderBy,\n dedupeInterval: otherOptions.dedupeIntervalMs ?? 2_000,\n autoFetchMore: otherOptions.autoFetchMore,\n streamUpdates,\n select: otherOptions.$select,\n },\n observer,\n );\n return subscription;\n },\n process.env.NODE_ENV !== \"production\"\n ? `objectSet ${stableKey}`\n : void 0,\n initialValue,\n );\n },\n [enabled, observableClient, stableKey, streamUpdates, objectTypeChanged],\n );\n\n const payload = React.useSyncExternalStore(subscribe, getSnapShot);\n if (payload && isPayloadCompleted(payload)) {\n previousCompletedPayloadRef.current = payload;\n }\n\n return React.useMemo(() => {\n const lastLoaded = isPayloadCompleted(payload)\n ? payload\n : previousCompletedPayloadRef.current;\n return {\n data: lastLoaded?.resolvedList as Osdk.Instance<\n Q,\n \"$allBaseProperties\",\n PropertyKeys<Q>,\n RDPs\n >[],\n isLoading: !isPayloadCompleted(payload),\n error: lastLoaded && \"error\" in lastLoaded ? lastLoaded.error : undefined,\n fetchMore: payload?.hasMore ? payload.fetchMore : undefined,\n objectSet: payload?.objectSet as ObjectSet<Q, RDPs> || baseObjectSet,\n totalCount: lastLoaded?.totalCount,\n };\n }, [payload, baseObjectSet]);\n}\n\nfunction isPayloadCompleted<\n Q extends ObjectOrInterfaceDefinition,\n RDPs extends Record<string, SimplePropertyDef>,\n>(\n payload: Snapshot<ObserveObjectSetArgs<Q, RDPs>>,\n): boolean {\n if (payload != null && \"error\" in payload) {\n return true;\n }\n\n if (payload?.status == null) {\n return false;\n }\n\n switch (payload.status) {\n case \"loaded\":\n case \"error\":\n return true;\n case \"loading\":\n case \"init\":\n return false;\n default:\n payload.status satisfies never;\n return false;\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAaA,SACEA,wBAAwB,QAEnB,kCAAkC;AACzC,OAAOC,KAAK,MAAM,OAAO;AACzB,SAASC,iBAAiB,QAAuB,wBAAwB;AACzE,SAASC,YAAY,QAAQ,mBAAmB;AA+IhD,MAAMC,uBAAuB,GAAG,8BAA8B;AAC9D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,YAAYA,CAK1BC,aAAqC,EACrCC,OAAqC,GAAG,CAAC,CAAC,EACb;EAC7B,MAAM;IAAEC;EAAiB,CAAC,GAAGP,KAAK,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,CAAC,MAAM;IACzB,MAAMe,UAAU,GAAGD,kBAAkB,CAACF,OAAO,CAAC,GAC1CA,OAAO,GACP7B,2BAA2B,CAACE,OAAO;IACvC,OAAO;MACL+B,IAAI,EAAED,UAAU,EAAEE,YAKf;MACHC,SAAS,EAAE,CAACJ,kBAAkB,CAACF,OAAO,CAAC;MACvCO,KAAK,EAAEJ,UAAU,IAAI,OAAO,IAAIA,UAAU,GAAGA,UAAU,CAACI,KAAK,GAAGjC,SAAS;MACzEkC,SAAS,EAAER,OAAO,EAAES,OAAO,GAAGT,OAAO,CAACQ,SAAS,GAAGlC,SAAS;MAC3DoC,SAAS,EAAEV,OAAO,EAAEU,SAAS,IAA0BpD,aAAa;MACpEqD,UAAU,EAAER,UAAU,EAAEQ;IAC1B,CAAC;EACH,CAAC,EAAE,CAACX,OAAO,EAAE1C,aAAa,CAAC,CAAC;AAC9B;AAEA,SAAS4C,kBAAkBA,CAIzBF,OAAgD,EACvC;EACT,IAAIA,OAAO,IAAI,IAAI,IAAI,OAAO,IAAIA,OAAO,EAAE;IACzC,OAAO,IAAI;EACb;EAEA,IAAIA,OAAO,EAAEY,MAAM,IAAI,IAAI,EAAE;IAC3B,OAAO,KAAK;EACd;EAEA,QAAQZ,OAAO,CAACY,MAAM;IACpB,KAAK,QAAQ;IACb,KAAK,OAAO;MACV,OAAO,IAAI;IACb,KAAK,SAAS;IACd,KAAK,MAAM;MACT,OAAO,KAAK;IACd;MACEZ,OAAO,CAACY,MAAM;MACd,OAAO,KAAK;EAChB;AACF","ignoreList":[]}
|
|
@@ -135,7 +135,7 @@ export function useOsdkAction(actionDef) {
|
|
|
135
135
|
}
|
|
136
136
|
};
|
|
137
137
|
}, []);
|
|
138
|
-
return {
|
|
138
|
+
return React.useMemo(() => ({
|
|
139
139
|
applyAction,
|
|
140
140
|
validateAction,
|
|
141
141
|
error,
|
|
@@ -143,6 +143,6 @@ export function useOsdkAction(actionDef) {
|
|
|
143
143
|
isPending,
|
|
144
144
|
isValidating,
|
|
145
145
|
validationResult
|
|
146
|
-
};
|
|
146
|
+
}), [applyAction, validateAction, error, data, isPending, isValidating, validationResult]);
|
|
147
147
|
}
|
|
148
148
|
//# sourceMappingURL=useOsdkAction.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useOsdkAction.js","names":["ActionValidationError","React","OsdkContext2","useOsdkAction","actionDef","observableClient","useContext","error","setError","useState","data","setData","isPending","setPending","isValidating","setValidating","validationResult","setValidationResult","abortControllerRef","useRef","applyAction","useCallback","hookArgs","current","abort","undefined","Array","isArray","updates","args","map","a","$optimisticUpdate","push","r","optimisticUpdate","ctx","update","e","actionValidation","unknown","validateAction","abortController","AbortController","result","signal","aborted","Error","name","useEffect"],"sources":["useOsdkAction.ts"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n ActionDefinition,\n ActionEditResponse,\n ActionValidationResponse,\n} from \"@osdk/client\";\nimport { ActionValidationError } from \"@osdk/client\";\nimport type {\n ActionSignatureFromDef,\n ObservableClient,\n} from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\ntype ApplyActionParams<Q extends ActionDefinition<any>> =\n & Parameters<ActionSignatureFromDef<Q>[\"applyAction\"]>[0]\n & {\n [K in keyof ObservableClient.ApplyActionOptions as `$${K}`]:\n ObservableClient.ApplyActionOptions[K];\n };\n\nexport interface UseOsdkActionResult<Q extends ActionDefinition<any>> {\n applyAction: (\n args: ApplyActionParams<Q> | Array<ApplyActionParams<Q>>,\n ) => Promise<ActionEditResponse | undefined>;\n\n error:\n | undefined\n | Partial<{\n actionValidation: ActionValidationError;\n unknown: unknown;\n }>;\n data: ActionEditResponse | undefined;\n\n isPending: boolean;\n isValidating: boolean;\n\n /**\n * Validates the action with the provided arguments without executing it.\n * Calling this function again before the previous validation finishes will cancel\n * the first validation and start a new one.\n * @param args The action arguments to validate\n * @returns A promise that resolves to the validation response, or undefined if aborted\n */\n validateAction: (\n args: Parameters<ActionSignatureFromDef<Q>[\"applyAction\"]>[0],\n ) => Promise<ActionValidationResponse | undefined>;\n\n validationResult?: ActionValidationResponse;\n}\n\nexport function useOsdkAction<Q extends ActionDefinition<any>>(\n actionDef: Q,\n): UseOsdkActionResult<Q> {\n const { observableClient } = React.useContext(OsdkContext2);\n const [error, setError] = React.useState<UseOsdkActionResult<Q>[\"error\"]>();\n const [data, setData] = React.useState<ActionEditResponse | undefined>();\n const [isPending, setPending] = React.useState(false);\n const [isValidating, setValidating] = React.useState(false);\n const [validationResult, setValidationResult] = React.useState<\n ActionValidationResponse | undefined\n >();\n const abortControllerRef = React.useRef<AbortController | null>(null);\n\n const applyAction = React.useCallback(async function applyAction(\n hookArgs: ApplyActionParams<Q> | Array<ApplyActionParams<Q>>,\n ) {\n try {\n // If validation is in progress, abort it\n if (isValidating && abortControllerRef.current) {\n abortControllerRef.current.abort();\n setValidating(false);\n }\n\n setPending(true);\n setError(undefined);\n\n if (Array.isArray(hookArgs)) {\n const updates: Array<\n ObservableClient.ApplyActionOptions[\"optimisticUpdate\"]\n > = [];\n const args = hookArgs.map(a => {\n const { $optimisticUpdate, ...args } = a;\n if ($optimisticUpdate) {\n updates.push($optimisticUpdate);\n }\n return args;\n });\n\n const r = await observableClient.applyAction(actionDef, args, {\n optimisticUpdate: (ctx) => {\n for (const update of updates) {\n update?.(ctx);\n }\n },\n });\n setData(r);\n return r;\n } else {\n const { $optimisticUpdate, ...args } = hookArgs;\n\n const r = await observableClient.applyAction(actionDef, args, {\n optimisticUpdate: $optimisticUpdate,\n });\n setData(r);\n return r;\n }\n } catch (e) {\n if (e instanceof ActionValidationError) {\n setError({\n actionValidation: e,\n });\n } else {\n setError({ unknown: e });\n }\n } finally {\n setPending(false);\n }\n }, [observableClient, actionDef, isValidating]);\n\n const validateAction = React.useCallback(async function validateAction(\n args: Parameters<ActionSignatureFromDef<Q>[\"applyAction\"]>[0],\n ): Promise<ActionValidationResponse | undefined> {\n try {\n // Check if action is being applied\n if (isPending) {\n return undefined;\n }\n\n // Abort any existing validation\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n }\n\n // Create new AbortController\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setValidating(true);\n setError(undefined);\n\n const result = await observableClient.validateAction(actionDef, args);\n\n // Check if aborted\n if (abortController.signal.aborted) {\n return undefined;\n }\n\n setValidationResult(result);\n return result;\n } catch (e) {\n // Check if it was aborted\n if (e instanceof Error && e.name === \"AbortError\") {\n return undefined;\n }\n\n if (e instanceof ActionValidationError) {\n setError({\n actionValidation: e,\n });\n } else {\n setError({ unknown: e });\n }\n throw e;\n } finally {\n setValidating(false);\n }\n }, [observableClient, actionDef, isPending]);\n\n // Cleanup on unmount\n React.useEffect(() => {\n return () => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n }\n };\n }, []);\n\n return {\n applyAction,\n validateAction,\n error,\n data,\n isPending,\n isValidating,\n validationResult,\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAOA,SAASA,qBAAqB,QAAQ,cAAc;AAKpD,OAAOC,KAAK,MAAM,OAAO;AACzB,SAASC,YAAY,QAAQ,mBAAmB;AAuChD,OAAO,SAASC,aAAaA,CAC3BC,SAAY,EACY;EACxB,MAAM;IAAEC;EAAiB,CAAC,GAAGJ,KAAK,CAACK,UAAU,CAACJ,YAAY,CAAC;EAC3D,MAAM,CAACK,KAAK,EAAEC,QAAQ,CAA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C,cAAc,CAACrC,SAAS,EAAEyB,IAAI,CAAC;;MAErE;MACA,IAAIa,eAAe,CAACG,MAAM,CAACC,OAAO,EAAE;QAClC,OAAOrB,SAAS;MAClB;MAEAR,mBAAmB,CAAC2B,MAAM,CAAC;MAC3B,OAAOA,MAAM;IACf,CAAC,CAAC,OAAON,CAAC,EAAE;MACV;MACA,IAAIA,CAAC,YAAYS,KAAK,IAAIT,CAAC,CAACU,IAAI,KAAK,YAAY,EAAE;QACjD,OAAOvB,SAAS;MAClB;MAEA,IAAIa,CAAC,YAAYtC,qBAAqB,EAAE;QACtCQ,QAAQ,CAAC;UACP+B,gBAAgB,EAAED;QACpB,CAAC,CAAC;MACJ,CAAC,MAAM;QACL9B,QAAQ,CAAC;UAAEgC,OAAO,EAAEF;QAAE,CAAC,CAAC;MAC1B;MACA,MAAMA,CAAC;IACT,CAAC,SAAS;MACRvB,aAAa,CAAC,KAAK,CAAC;IACtB;EACF,CAAC,EAAE,CAACV,gBAAgB,EAAED,SAAS,EAAEQ,SAAS,CAAC,CAAC;;EAE5C;EACAX,KAAK,CAACgD,SAAS,CAAC,MAAM;IACpB,OAAO,MAAM;MACX,IAAI/B,kBAAkB,CAACK,OAAO,EAAE;QAC9BL,kBAAkB,CAACK,OAAO,CAACC,KAAK,CAAC,CAAC;MACpC;IACF,CAAC;EACH,CAAC,EAAE,EAAE,CAAC;EAEN,OAAO;IACLJ,WAAW;IACXqB,cAAc;IACdlC,KAAK;IACLG,IAAI;IACJE,SAAS;IACTE,YAAY;IACZE;EACF,CAAC;AACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"useOsdkAction.js","names":["ActionValidationError","React","OsdkContext2","useOsdkAction","actionDef","observableClient","useContext","error","setError","useState","data","setData","isPending","setPending","isValidating","setValidating","validationResult","setValidationResult","abortControllerRef","useRef","applyAction","useCallback","hookArgs","current","abort","undefined","Array","isArray","updates","args","map","a","$optimisticUpdate","push","r","optimisticUpdate","ctx","update","e","actionValidation","unknown","validateAction","abortController","AbortController","result","signal","aborted","Error","name","useEffect","useMemo"],"sources":["useOsdkAction.ts"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n ActionDefinition,\n ActionEditResponse,\n ActionValidationResponse,\n} from \"@osdk/client\";\nimport { ActionValidationError } from \"@osdk/client\";\nimport type {\n ActionSignatureFromDef,\n ObservableClient,\n} from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\ntype ApplyActionParams<Q extends ActionDefinition<any>> =\n & Parameters<ActionSignatureFromDef<Q>[\"applyAction\"]>[0]\n & {\n [K in keyof ObservableClient.ApplyActionOptions as `$${K}`]:\n ObservableClient.ApplyActionOptions[K];\n };\n\nexport interface UseOsdkActionResult<Q extends ActionDefinition<any>> {\n applyAction: (\n args: ApplyActionParams<Q> | Array<ApplyActionParams<Q>>,\n ) => Promise<ActionEditResponse | undefined>;\n\n error:\n | undefined\n | Partial<{\n actionValidation: ActionValidationError;\n unknown: unknown;\n }>;\n data: ActionEditResponse | undefined;\n\n isPending: boolean;\n isValidating: boolean;\n\n /**\n * Validates the action with the provided arguments without executing it.\n * Calling this function again before the previous validation finishes will cancel\n * the first validation and start a new one.\n * @param args The action arguments to validate\n * @returns A promise that resolves to the validation response, or undefined if aborted\n */\n validateAction: (\n args: Parameters<ActionSignatureFromDef<Q>[\"applyAction\"]>[0],\n ) => Promise<ActionValidationResponse | undefined>;\n\n validationResult?: ActionValidationResponse;\n}\n\nexport function useOsdkAction<Q extends ActionDefinition<any>>(\n actionDef: Q,\n): UseOsdkActionResult<Q> {\n const { observableClient } = React.useContext(OsdkContext2);\n const [error, setError] = React.useState<UseOsdkActionResult<Q>[\"error\"]>();\n const [data, setData] = React.useState<ActionEditResponse | undefined>();\n const [isPending, setPending] = React.useState(false);\n const [isValidating, setValidating] = React.useState(false);\n const [validationResult, setValidationResult] = React.useState<\n ActionValidationResponse | undefined\n >();\n const abortControllerRef = React.useRef<AbortController | null>(null);\n\n const applyAction = React.useCallback(async function applyAction(\n hookArgs: ApplyActionParams<Q> | Array<ApplyActionParams<Q>>,\n ) {\n try {\n // If validation is in progress, abort it\n if (isValidating && abortControllerRef.current) {\n abortControllerRef.current.abort();\n setValidating(false);\n }\n\n setPending(true);\n setError(undefined);\n\n if (Array.isArray(hookArgs)) {\n const updates: Array<\n ObservableClient.ApplyActionOptions[\"optimisticUpdate\"]\n > = [];\n const args = hookArgs.map(a => {\n const { $optimisticUpdate, ...args } = a;\n if ($optimisticUpdate) {\n updates.push($optimisticUpdate);\n }\n return args;\n });\n\n const r = await observableClient.applyAction(actionDef, args, {\n optimisticUpdate: (ctx) => {\n for (const update of updates) {\n update?.(ctx);\n }\n },\n });\n setData(r);\n return r;\n } else {\n const { $optimisticUpdate, ...args } = hookArgs;\n\n const r = await observableClient.applyAction(actionDef, args, {\n optimisticUpdate: $optimisticUpdate,\n });\n setData(r);\n return r;\n }\n } catch (e) {\n if (e instanceof ActionValidationError) {\n setError({\n actionValidation: e,\n });\n } else {\n setError({ unknown: e });\n }\n } finally {\n setPending(false);\n }\n }, [observableClient, actionDef, isValidating]);\n\n const validateAction = React.useCallback(async function validateAction(\n args: Parameters<ActionSignatureFromDef<Q>[\"applyAction\"]>[0],\n ): Promise<ActionValidationResponse | undefined> {\n try {\n // Check if action is being applied\n if (isPending) {\n return undefined;\n }\n\n // Abort any existing validation\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n }\n\n // Create new AbortController\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n setValidating(true);\n setError(undefined);\n\n const result = await observableClient.validateAction(actionDef, args);\n\n // Check if aborted\n if (abortController.signal.aborted) {\n return undefined;\n }\n\n setValidationResult(result);\n return result;\n } catch (e) {\n // Check if it was aborted\n if (e instanceof Error && e.name === \"AbortError\") {\n return undefined;\n }\n\n if (e instanceof ActionValidationError) {\n setError({\n actionValidation: e,\n });\n } else {\n setError({ unknown: e });\n }\n throw e;\n } finally {\n setValidating(false);\n }\n }, [observableClient, actionDef, isPending]);\n\n // Cleanup on unmount\n React.useEffect(() => {\n return () => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n }\n };\n }, []);\n\n return React.useMemo(() => ({\n applyAction,\n validateAction,\n error,\n data,\n isPending,\n isValidating,\n validationResult,\n }), [\n applyAction,\n validateAction,\n error,\n data,\n isPending,\n isValidating,\n validationResult,\n ]);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAOA,SAASA,qBAAqB,QAAQ,cAAc;AAKpD,OAAOC,KAAK,MAAM,OAAO;AACzB,SAASC,YAAY,QAAQ,mBAAmB;AAuChD,OAAO,SAASC,aAAaA,CAC3BC,SAAY,EACY;EACxB,MAAM;IAAEC;EAAiB,CAAC,GAAGJ,KAAK,CAACK,UAAU,CAACJ,YAAY,CAAC;EAC3D,MAAM,CAACK,KAAK,EAAEC,QAAQ,CAAC,GAAGP,KAAK,CAACQ,QAAQ,CAAkC,CAAC;EAC3E,MAAM,CAACC,IAAI,EAAEC,OAAO,CAAC,GAAGV,KAAK,CAACQ,QAAQ,CAAiC,CAAC;EACxE,MAAM,CAACG,SAAS,EAAEC,UAAU,CAAC,GAAGZ,KAAK,CAACQ,QAAQ,CAAC,KAAK,CAAC;EACrD,MAAM,CAACK,YAAY,EAAEC,aAAa,CAAC,GAAGd,KAAK,CAACQ,QAAQ,CAAC,KAAK,CAAC;EAC3D,MAAM,CAACO,gBAAgB,EAAEC,m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YtC,qBAAqB,EAAE;QACtCQ,QAAQ,CAAC;UACP+B,gBAAgB,EAAED;QACpB,CAAC,CAAC;MACJ,CAAC,MAAM;QACL9B,QAAQ,CAAC;UAAEgC,OAAO,EAAEF;QAAE,CAAC,CAAC;MAC1B;MACA,MAAMA,CAAC;IACT,CAAC,SAAS;MACRvB,aAAa,CAAC,KAAK,CAAC;IACtB;EACF,CAAC,EAAE,CAACV,gBAAgB,EAAED,SAAS,EAAEQ,SAAS,CAAC,CAAC;;EAE5C;EACAX,KAAK,CAACgD,SAAS,CAAC,MAAM;IACpB,OAAO,MAAM;MACX,IAAI/B,kBAAkB,CAACK,OAAO,EAAE;QAC9BL,kBAAkB,CAACK,OAAO,CAACC,KAAK,CAAC,CAAC;MACpC;IACF,CAAC;EACH,CAAC,EAAE,EAAE,CAAC;EAEN,OAAOvB,KAAK,CAACiD,OAAO,CAAC,OAAO;IAC1B9B,WAAW;IACXqB,cAAc;IACdlC,KAAK;IACLG,IAAI;IACJE,SAAS;IACTE,YAAY;IACZE;EACF,CAAC,CAAC,EAAE,CACFI,WAAW,EACXqB,cAAc,EACdlC,KAAK,EACLG,IAAI,EACJE,SAAS,EACTE,YAAY,EACZE,gBAAgB,CACjB,CAAC;AACJ","ignoreList":[]}
|
|
@@ -14,9 +14,12 @@
|
|
|
14
14
|
* limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
+
import { computeObjectSetCacheKey } from "@osdk/client/unstable-do-not-use";
|
|
17
18
|
import React from "react";
|
|
18
|
-
import { makeExternalStore } from "./makeExternalStore.js";
|
|
19
|
+
import { makeExternalStore, makeExternalStoreAsync } from "./makeExternalStore.js";
|
|
19
20
|
import { OsdkContext2 } from "./OsdkContext2.js";
|
|
21
|
+
const EMPTY_WHERE = {};
|
|
22
|
+
|
|
20
23
|
/**
|
|
21
24
|
* React hook for performing aggregations on OSDK object sets.
|
|
22
25
|
*
|
|
@@ -29,6 +32,7 @@ import { OsdkContext2 } from "./OsdkContext2.js";
|
|
|
29
32
|
*
|
|
30
33
|
* @example
|
|
31
34
|
* ```tsx
|
|
35
|
+
* // Basic aggregation without ObjectSet
|
|
32
36
|
* const { data, isLoading, error } = useOsdkAggregation(Employee, {
|
|
33
37
|
* where: { department: "Engineering" },
|
|
34
38
|
* aggregate: {
|
|
@@ -39,45 +43,79 @@ import { OsdkContext2 } from "./OsdkContext2.js";
|
|
|
39
43
|
* }
|
|
40
44
|
* }
|
|
41
45
|
* });
|
|
46
|
+
*
|
|
47
|
+
* // With a pivoted ObjectSet
|
|
48
|
+
* const pivotedSet = useMemo(() => $(Employee).pivotTo("primaryOffice"), []);
|
|
49
|
+
* const { data } = useOsdkAggregation(Office, {
|
|
50
|
+
* objectSet: pivotedSet,
|
|
51
|
+
* aggregate: { $select: { $count: "unordered" } }
|
|
52
|
+
* });
|
|
42
53
|
* ```
|
|
43
54
|
*/
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
55
|
+
|
|
56
|
+
export function useOsdkAggregation(type, options) {
|
|
57
|
+
const {
|
|
58
|
+
where = EMPTY_WHERE,
|
|
59
|
+
withProperties,
|
|
60
|
+
intersectWith,
|
|
61
|
+
aggregate,
|
|
62
|
+
dedupeIntervalMs
|
|
63
|
+
} = options;
|
|
64
|
+
const objectSet = "objectSet" in options ? options.objectSet : undefined;
|
|
50
65
|
const {
|
|
51
66
|
observableClient
|
|
52
67
|
} = React.useContext(OsdkContext2);
|
|
53
|
-
const canonWhere = observableClient.canonicalizeWhereClause(where
|
|
68
|
+
const canonWhere = observableClient.canonicalizeWhereClause(where);
|
|
69
|
+
const stableCanonWhere = React.useMemo(() => canonWhere, [JSON.stringify(canonWhere)]);
|
|
70
|
+
const objectSetRef = React.useRef(objectSet);
|
|
71
|
+
objectSetRef.current = objectSet;
|
|
72
|
+
const objectSetKeyString = objectSet ? computeObjectSetCacheKey(objectSet) : undefined;
|
|
54
73
|
const stableWithProperties = React.useMemo(() => withProperties, [JSON.stringify(withProperties)]);
|
|
55
74
|
const stableAggregate = React.useMemo(() => aggregate, [JSON.stringify(aggregate)]);
|
|
75
|
+
const stableIntersectWith = React.useMemo(() => intersectWith, [JSON.stringify(intersectWith)]);
|
|
56
76
|
const {
|
|
57
77
|
subscribe,
|
|
58
78
|
getSnapShot
|
|
59
|
-
} = React.useMemo(() =>
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
79
|
+
} = React.useMemo(() => {
|
|
80
|
+
if (objectSetKeyString && objectSetRef.current) {
|
|
81
|
+
return makeExternalStoreAsync(observer => observableClient.observeAggregation({
|
|
82
|
+
type: type,
|
|
83
|
+
objectSet: objectSetRef.current,
|
|
84
|
+
where: stableCanonWhere,
|
|
85
|
+
withProperties: stableWithProperties,
|
|
86
|
+
intersectWith: stableIntersectWith,
|
|
87
|
+
aggregate: stableAggregate,
|
|
88
|
+
dedupeInterval: dedupeIntervalMs ?? 2_000
|
|
89
|
+
}, observer), process.env.NODE_ENV !== "production" ? `aggregation ${type.apiName} ${objectSetKeyString} ${JSON.stringify(stableCanonWhere)}` : void 0);
|
|
90
|
+
}
|
|
91
|
+
return makeExternalStore(observer =>
|
|
92
|
+
// eslint-disable-next-line @typescript-eslint/no-deprecated
|
|
93
|
+
observableClient.observeAggregation({
|
|
94
|
+
type: type,
|
|
95
|
+
where: stableCanonWhere,
|
|
96
|
+
withProperties: stableWithProperties,
|
|
97
|
+
intersectWith: stableIntersectWith,
|
|
98
|
+
aggregate: stableAggregate,
|
|
99
|
+
dedupeInterval: dedupeIntervalMs ?? 2_000
|
|
100
|
+
}, observer), process.env.NODE_ENV !== "production" ? `aggregation ${type.apiName} ${JSON.stringify(stableCanonWhere)}` : void 0);
|
|
101
|
+
}, [observableClient, type.apiName, type.type, objectSetKeyString, stableCanonWhere, stableWithProperties, stableIntersectWith, stableAggregate, dedupeIntervalMs]);
|
|
66
102
|
const payload = React.useSyncExternalStore(subscribe, getSnapShot);
|
|
67
|
-
let error;
|
|
68
|
-
if (payload && "error" in payload && payload.error) {
|
|
69
|
-
error = payload.error;
|
|
70
|
-
} else if (payload?.status === "error") {
|
|
71
|
-
error = new Error("Failed to execute aggregation");
|
|
72
|
-
}
|
|
73
103
|
const refetch = React.useCallback(async () => {
|
|
74
104
|
await observableClient.invalidateObjectType(type.apiName);
|
|
75
105
|
}, [observableClient, type.apiName]);
|
|
76
|
-
return {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
106
|
+
return React.useMemo(() => {
|
|
107
|
+
let error;
|
|
108
|
+
if (payload && "error" in payload && payload.error) {
|
|
109
|
+
error = payload.error;
|
|
110
|
+
} else if (payload?.status === "error") {
|
|
111
|
+
error = new Error("Failed to execute aggregation");
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
data: payload?.result,
|
|
115
|
+
isLoading: payload?.status === "loading" || payload?.status === "init" || !payload,
|
|
116
|
+
error,
|
|
117
|
+
refetch
|
|
118
|
+
};
|
|
119
|
+
}, [payload, refetch]);
|
|
82
120
|
}
|
|
83
121
|
//# sourceMappingURL=useOsdkAggregation.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useOsdkAggregation.js","names":["React","makeExternalStore","OsdkContext2","useOsdkAggregation","type","where","withProperties","aggregate","dedupeIntervalMs","observableClient","useContext","canonWhere","canonicalizeWhereClause","stableWithProperties","useMemo","JSON","stringify","stableAggregate","subscribe","getSnapShot","observer","observeAggregation","dedupeInterval","process","env","NODE_ENV","apiName","payload","useSyncExternalStore","error","status","Error","refetch","useCallback","invalidateObjectType","data","result","isLoading"],"sources":["useOsdkAggregation.ts"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n AggregateOpts,\n AggregationsResults,\n DerivedProperty,\n ObjectOrInterfaceDefinition,\n SimplePropertyDef,\n WhereClause,\n} from \"@osdk/api\";\nimport type { ObserveAggregationArgs } from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { makeExternalStore } from \"./makeExternalStore.js\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\nexport interface UseOsdkAggregationOptions<\n T extends ObjectOrInterfaceDefinition,\n A extends AggregateOpts<T>,\n RDPs extends Record<string, SimplePropertyDef> = {},\n> {\n /**\n * Standard OSDK Where clause to filter objects before aggregation\n */\n where?: WhereClause<T, RDPs>;\n\n /**\n * Define derived properties (RDPs) to be computed server-side.\n * The derived properties can be used in the where clause and aggregation groupBy/select.\n */\n withProperties?: { [K in keyof RDPs]: DerivedProperty.Creator<T, RDPs[K]> };\n\n /**\n * Aggregation options including groupBy and select\n */\n aggregate: A;\n\n /**\n * The number of milliseconds to wait after the last observed aggregation change.\n *\n * Two uses of `useOsdkAggregation` with the same parameters will only trigger one\n * network request if the second is within `dedupeIntervalMs`.\n */\n dedupeIntervalMs?: number;\n}\n\nexport interface UseOsdkAggregationResult<\n T extends ObjectOrInterfaceDefinition,\n A extends AggregateOpts<T>,\n> {\n data: AggregationsResults<T, A> | undefined;\n isLoading: boolean;\n error: Error | undefined;\n refetch: () => void;\n}\n\ndeclare const process: {\n env: {\n NODE_ENV: \"development\" | \"production\";\n };\n};\n\n/**\n * React hook for performing aggregations on OSDK object sets.\n *\n * Executes server-side aggregations with groupBy and metric calculations on filtered object sets.\n * Supports runtime derived properties and where clauses.\n *\n * @param type - The object or interface type to aggregate\n * @param options - Aggregation configuration including where clause, aggregation spec, and optional derived properties\n * @returns Object containing aggregation results, loading state, error state, and refetch function\n *\n * @example\n * ```tsx\n * const { data, isLoading, error } = useOsdkAggregation(Employee, {\n * where: { department: \"Engineering\" },\n * aggregate: {\n * groupBy: { department: \"exact\" },\n * select: {\n * avgSalary: { $avg: \"salary\" },\n * count: { $count: {} }\n * }\n * }\n * });\n * ```\n */\nexport function useOsdkAggregation<\n Q extends ObjectOrInterfaceDefinition,\n const A extends AggregateOpts<Q>,\n RDPs extends Record<string, SimplePropertyDef> = {},\n>(\n type: Q,\n {\n where = {},\n withProperties,\n aggregate,\n dedupeIntervalMs,\n }: UseOsdkAggregationOptions<Q, A, RDPs>,\n): UseOsdkAggregationResult<Q, A> {\n const { observableClient } = React.useContext(OsdkContext2);\n\n const canonWhere = observableClient.canonicalizeWhereClause<Q>(where ?? {});\n\n const stableWithProperties = React.useMemo(\n () => withProperties,\n [JSON.stringify(withProperties)],\n );\n\n const stableAggregate = React.useMemo(\n () => aggregate,\n [JSON.stringify(aggregate)],\n );\n\n const { subscribe, getSnapShot } = React.useMemo(\n () =>\n makeExternalStore<ObserveAggregationArgs<Q, A>>(\n (observer) =>\n observableClient.observeAggregation(\n {\n type: type,\n where: canonWhere,\n withProperties: stableWithProperties,\n aggregate: stableAggregate,\n dedupeInterval: dedupeIntervalMs ?? 2_000,\n },\n observer,\n ),\n process.env.NODE_ENV !== \"production\"\n ? `aggregation ${type.apiName} ${JSON.stringify(canonWhere)}`\n : void 0,\n ),\n [\n observableClient,\n type.apiName,\n type.type,\n canonWhere,\n stableWithProperties,\n stableAggregate,\n dedupeIntervalMs,\n ],\n );\n\n const payload = React.useSyncExternalStore(subscribe, getSnapShot);\n\n let error: Error | undefined;\n if (payload && \"error\" in payload && payload.error) {\n error = payload.error;\n } else if (payload?.status === \"error\") {\n error = new Error(\"Failed to execute aggregation\");\n }\n\n const refetch = React.useCallback(async () => {\n await observableClient.invalidateObjectType(type.apiName);\n }, [observableClient, type.apiName]);\n\n return {\n data: payload?.result as AggregationsResults<Q, A> | undefined,\n isLoading: payload?.status === \"loading\" || payload?.status === \"init\"\n || !payload,\n error,\n refetch,\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAWA,OAAOA,KAAK,MAAM,OAAO;AACzB,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D,SAASC,YAAY,QAAQ,mBAAmB;AAgDhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,kBAAkBA,CAKhCC,IAAO,EACP;EACEC,KAAK,GAAG,CAAC,CAAC;EACVC,cAAc;EACdC,SAAS;EACTC;AACqC,CAAC,EACR;EAChC,MAAM;IAAEC;EAAiB,CAAC,GAAGT,KAAK,CAACU,UAAU,CAACR,YAAY,CAAC;EAE3D,MAAMS,UAAU,GAAGF,gBAAgB,CAACG,uBAAuB,CAAIP,KAAK,IAAI,CAAC,CAAC,CAAC;EAE3E,MAAMQ,oBAAoB,GAAGb,KAAK,CAACc,OAAO,CACxC,MAAMR,cAAc,EACpB,CAACS,IAAI,CAACC,SAAS,CAACV,cAAc,CAAC,CACjC,CAAC;EAED,MAAMW,eAAe,GAAGjB,KAAK,CAACc,OAAO,CACnC,MAAMP,SAAS,EACf,CAACQ,IAAI,CAACC,SAAS,CAACT,SAAS,CAAC,CAC5B,CAAC;EAED,MAAM;IAAEW,SAAS;IAAEC;EAAY,CAAC,GAAGnB,KAAK,CAACc,OAAO,CAC9C,MACEb,iBAAiB,CACdmB,QAAQ,IACPX,gBAAgB,CAACY,kBAAkB,CACjC;IACEjB,IAAI,EAAEA,IAAI;IACVC,KAAK,EAAEM,UAAU;IACjBL,cAAc,EAAEO,oBAAoB;IACpCN,SAAS,EAAEU,eAAe;IAC1BK,cAAc,EAAEd,gBAAgB,IAAI;EACtC,CAAC,EACDY,QACF,CAAC,EACHG,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,GACjC,eAAerB,IAAI,CAACsB,OAAO,IAAIX,IAAI,CAACC,SAAS,CAACL,UAAU,CAAC,EAAE,GAC3D,KAAK,CACX,CAAC,EACH,CACEF,gBAAgB,EAChBL,IAAI,CAACsB,OAAO,EACZtB,IAAI,CAACA,IAAI,EACTO,UAAU,EACVE,oBAAoB,EACpBI,eAAe,EACfT,gBAAgB,CAEpB,CAAC;EAED,MAAMmB,OAAO,GAAG3B,KAAK,CAAC4B,oBAAoB,CAACV,SAAS,EAAEC,WAAW,CAAC;EAElE,IAAIU,KAAwB;EAC5B,IAAIF,OAAO,IAAI,OAAO,IAAIA,OAAO,IAAIA,OAAO,CAACE,KAAK,EAAE;IAClDA,KAAK,GAAGF,OAAO,CAACE,KAAK;EACvB,CAAC,MAAM,IAAIF,OAAO,EAAEG,MAAM,KAAK,OAAO,EAAE;IACtCD,KAAK,GAAG,IAAIE,KAAK,CAAC,+BAA+B,CAAC;EACpD;EAEA,MAAMC,OAAO,GAAGhC,KAAK,CAACiC,WAAW,CAAC,YAAY;IAC5C,MAAMxB,gBAAgB,CAACyB,oBAAoB,CAAC9B,IAAI,CAACsB,OAAO,CAAC;EAC3D,CAAC,EAAE,CAACjB,gBAAgB,EAAEL,IAAI,CAACsB,OAAO,CAAC,CAAC;EAEpC,OAAO;IACLS,IAAI,EAAER,OAAO,EAAES,MAA+C;IAC9DC,SAAS,EAAEV,OAAO,EAAEG,MAAM,KAAK,SAAS,IAAIH,OAAO,EAAEG,MAAM,KAAK,MAAM,IACjE,CAACH,OAAO;IACbE,KAAK;IACLG;EACF,CAAC;AACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"useOsdkAggregation.js","names":["computeObjectSetCacheKey","React","makeExternalStore","makeExternalStoreAsync","OsdkContext2","EMPTY_WHERE","useOsdkAggregation","type","options","where","withProperties","intersectWith","aggregate","dedupeIntervalMs","objectSet","undefined","observableClient","useContext","canonWhere","canonicalizeWhereClause","stableCanonWhere","useMemo","JSON","stringify","objectSetRef","useRef","current","objectSetKeyString","stableWithProperties","stableAggregate","stableIntersectWith","subscribe","getSnapShot","observer","observeAggregation","dedupeInterval","process","env","NODE_ENV","apiName","payload","useSyncExternalStore","refetch","useCallback","invalidateObjectType","error","status","Error","data","result","isLoading"],"sources":["useOsdkAggregation.ts"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n AggregateOpts,\n AggregationsResults,\n DerivedProperty,\n ObjectOrInterfaceDefinition,\n ObjectSet,\n SimplePropertyDef,\n WhereClause,\n} from \"@osdk/api\";\nimport type { ObjectTypeDefinition } from \"@osdk/client\";\nimport type { ObserveAggregationArgs } from \"@osdk/client/unstable-do-not-use\";\nimport { computeObjectSetCacheKey } from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport {\n makeExternalStore,\n makeExternalStoreAsync,\n} from \"./makeExternalStore.js\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\ninterface UseOsdkAggregationBaseOptions<\n T extends ObjectOrInterfaceDefinition,\n A extends AggregateOpts<T>,\n RDPs extends Record<string, SimplePropertyDef> = {},\n> {\n /**\n * Standard OSDK Where clause to filter objects before aggregation\n */\n where?: WhereClause<T, RDPs>;\n\n /**\n * Define derived properties (RDPs) to be computed server-side.\n * The derived properties can be used in the where clause and aggregation groupBy/select.\n */\n withProperties?: { [K in keyof RDPs]: DerivedProperty.Creator<T, RDPs[K]> };\n\n /**\n * Intersect the main query with additional filtered object sets.\n * Each entry creates a separate object set with its own where clause,\n * and the final result is the intersection of all sets.\n */\n intersectWith?: Array<{\n where: WhereClause<T, RDPs>;\n }>;\n\n /**\n * Aggregation options including groupBy and select\n */\n aggregate: A;\n\n /**\n * The number of milliseconds to wait after the last observed aggregation change.\n *\n * Two uses of `useOsdkAggregation` with the same parameters will only trigger one\n * network request if the second is within `dedupeIntervalMs`.\n */\n dedupeIntervalMs?: number;\n}\n\nexport interface UseOsdkAggregationOptions<\n T extends ObjectOrInterfaceDefinition,\n A extends AggregateOpts<T>,\n RDPs extends Record<string, SimplePropertyDef> = {},\n> extends UseOsdkAggregationBaseOptions<T, A, RDPs> {}\n\nexport interface UseOsdkAggregationOptionsWithObjectSet<\n T extends ObjectTypeDefinition,\n A extends AggregateOpts<T>,\n RDPs extends Record<string, SimplePropertyDef> = {},\n> extends UseOsdkAggregationBaseOptions<T, A, RDPs> {\n /**\n * The ObjectSet to aggregate on. Enables aggregation on pivoted, filtered, or composed ObjectSets.\n */\n objectSet: ObjectSet<T>;\n}\n\nconst EMPTY_WHERE = {};\n\nexport interface UseOsdkAggregationResult<\n T extends ObjectOrInterfaceDefinition,\n A extends AggregateOpts<T>,\n> {\n data: AggregationsResults<T, A> | undefined;\n isLoading: boolean;\n error: Error | undefined;\n refetch: () => void;\n}\n\ndeclare const process: {\n env: {\n NODE_ENV: \"development\" | \"production\";\n };\n};\n\n/**\n * React hook for performing aggregations on OSDK object sets.\n *\n * Executes server-side aggregations with groupBy and metric calculations on filtered object sets.\n * Supports runtime derived properties and where clauses.\n *\n * @param type - The object or interface type to aggregate\n * @param options - Aggregation configuration including where clause, aggregation spec, and optional derived properties\n * @returns Object containing aggregation results, loading state, error state, and refetch function\n *\n * @example\n * ```tsx\n * // Basic aggregation without ObjectSet\n * const { data, isLoading, error } = useOsdkAggregation(Employee, {\n * where: { department: \"Engineering\" },\n * aggregate: {\n * groupBy: { department: \"exact\" },\n * select: {\n * avgSalary: { $avg: \"salary\" },\n * count: { $count: {} }\n * }\n * }\n * });\n *\n * // With a pivoted ObjectSet\n * const pivotedSet = useMemo(() => $(Employee).pivotTo(\"primaryOffice\"), []);\n * const { data } = useOsdkAggregation(Office, {\n * objectSet: pivotedSet,\n * aggregate: { $select: { $count: \"unordered\" } }\n * });\n * ```\n */\nexport function useOsdkAggregation<\n Q extends ObjectOrInterfaceDefinition,\n const A extends AggregateOpts<Q>,\n RDPs extends Record<string, SimplePropertyDef> = {},\n>(\n type: Q,\n options: UseOsdkAggregationOptions<Q, A, RDPs>,\n): UseOsdkAggregationResult<Q, A>;\nexport function useOsdkAggregation<\n Q extends ObjectTypeDefinition,\n const A extends AggregateOpts<Q>,\n RDPs extends Record<string, SimplePropertyDef> = {},\n>(\n type: Q,\n options: UseOsdkAggregationOptionsWithObjectSet<Q, A, RDPs>,\n): UseOsdkAggregationResult<Q, A>;\nexport function useOsdkAggregation<\n Q extends ObjectTypeDefinition,\n const A extends AggregateOpts<Q>,\n RDPs extends Record<string, SimplePropertyDef> = {},\n>(\n type: Q,\n options:\n | UseOsdkAggregationOptions<Q, A, RDPs>\n | UseOsdkAggregationOptionsWithObjectSet<Q, A, RDPs>,\n): UseOsdkAggregationResult<Q, A> {\n const {\n where = EMPTY_WHERE,\n withProperties,\n intersectWith,\n aggregate,\n dedupeIntervalMs,\n } = options;\n const objectSet = \"objectSet\" in options ? options.objectSet : undefined;\n\n const { observableClient } = React.useContext(OsdkContext2);\n\n const canonWhere = observableClient.canonicalizeWhereClause<Q>(where);\n\n const stableCanonWhere = React.useMemo(\n () => canonWhere,\n [JSON.stringify(canonWhere)],\n );\n\n const objectSetRef = React.useRef(objectSet);\n objectSetRef.current = objectSet;\n\n const objectSetKeyString = objectSet\n ? computeObjectSetCacheKey(objectSet)\n : undefined;\n\n const stableWithProperties = React.useMemo(\n () => withProperties,\n [JSON.stringify(withProperties)],\n );\n\n const stableAggregate = React.useMemo(\n () => aggregate,\n [JSON.stringify(aggregate)],\n );\n\n const stableIntersectWith = React.useMemo(\n () => intersectWith,\n [JSON.stringify(intersectWith)],\n );\n\n const { subscribe, getSnapShot } = React.useMemo(\n () => {\n if (objectSetKeyString && objectSetRef.current) {\n return makeExternalStoreAsync<ObserveAggregationArgs<Q, A>>(\n (observer) =>\n observableClient.observeAggregation(\n {\n type: type,\n objectSet: objectSetRef.current!,\n where: stableCanonWhere,\n withProperties: stableWithProperties,\n intersectWith: stableIntersectWith,\n aggregate: stableAggregate,\n dedupeInterval: dedupeIntervalMs ?? 2_000,\n },\n observer,\n ),\n process.env.NODE_ENV !== \"production\"\n ? `aggregation ${type.apiName} ${objectSetKeyString} ${\n JSON.stringify(stableCanonWhere)\n }`\n : void 0,\n );\n }\n return makeExternalStore<ObserveAggregationArgs<Q, A>>(\n (observer) =>\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n observableClient.observeAggregation(\n {\n type: type,\n where: stableCanonWhere,\n withProperties: stableWithProperties,\n intersectWith: stableIntersectWith,\n aggregate: stableAggregate,\n dedupeInterval: dedupeIntervalMs ?? 2_000,\n },\n observer,\n ),\n process.env.NODE_ENV !== \"production\"\n ? `aggregation ${type.apiName} ${JSON.stringify(stableCanonWhere)}`\n : void 0,\n );\n },\n [\n observableClient,\n type.apiName,\n type.type,\n objectSetKeyString,\n stableCanonWhere,\n stableWithProperties,\n stableIntersectWith,\n stableAggregate,\n dedupeIntervalMs,\n ],\n );\n\n const payload = React.useSyncExternalStore(subscribe, getSnapShot);\n\n const refetch = React.useCallback(async () => {\n await observableClient.invalidateObjectType(type.apiName);\n }, [observableClient, type.apiName]);\n\n return React.useMemo(() => {\n let error: Error | undefined;\n if (payload && \"error\" in payload && payload.error) {\n error = payload.error;\n } else if (payload?.status === \"error\") {\n error = new Error(\"Failed to execute aggregation\");\n }\n\n return {\n data: payload?.result as AggregationsResults<Q, A> | undefined,\n isLoading: payload?.status === \"loading\" || payload?.status === \"init\"\n || !payload,\n error,\n refetch,\n };\n }, [payload, refetch]);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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
16
|
|
|
17
|
+
import { getWireObjectSet } from "@osdk/client/unstable-do-not-use";
|
|
17
18
|
import React from "react";
|
|
18
19
|
import { makeExternalStore } from "./makeExternalStore.js";
|
|
19
20
|
import { OsdkContext2 } from "./OsdkContext2.js";
|
|
@@ -63,10 +64,12 @@ export function useOsdkFunction(queryDef, options = {}) {
|
|
|
63
64
|
} = options;
|
|
64
65
|
const stableParams = React.useMemo(() => params, [JSON.stringify(params)]);
|
|
65
66
|
const stableDependsOn = React.useMemo(() => dependsOn, [JSON.stringify(dependsOn?.map(d => typeof d === "string" ? d : d.apiName))]);
|
|
66
|
-
const stableDependsOnObjects = React.useMemo(() => dependsOnObjects, [JSON.stringify(dependsOnObjects?.map(
|
|
67
|
-
$apiName:
|
|
68
|
-
$primaryKey:
|
|
69
|
-
}
|
|
67
|
+
const stableDependsOnObjects = React.useMemo(() => dependsOnObjects, [JSON.stringify(dependsOnObjects?.map(item => "$apiName" in item ? {
|
|
68
|
+
$apiName: item.$apiName,
|
|
69
|
+
$primaryKey: item.$primaryKey
|
|
70
|
+
} : {
|
|
71
|
+
__objectSet: getWireObjectSet(item)
|
|
72
|
+
}))]);
|
|
70
73
|
|
|
71
74
|
// Record<string, unknown> required as typing is figured out at runtime
|
|
72
75
|
const paramsForApi = stableParams;
|
|
@@ -86,16 +89,18 @@ export function useOsdkFunction(queryDef, options = {}) {
|
|
|
86
89
|
}, observer), process.env.NODE_ENV !== "production" ? `function ${queryDef.apiName} ${JSON.stringify(stableParams)}` : void 0);
|
|
87
90
|
}, [observableClient, queryDef.apiName, queryDef.version, paramsForApi, stableDependsOn, stableDependsOnObjects, dedupeIntervalMs, enabled]);
|
|
88
91
|
const payload = React.useSyncExternalStore(subscribe, getSnapShot);
|
|
89
|
-
const error = payload?.error ?? (payload?.status === "error" ? new Error("Failed to execute function") : undefined);
|
|
90
92
|
const refetch = React.useCallback(() => {
|
|
91
93
|
void observableClient.invalidateFunction(queryDef, paramsForApi);
|
|
92
94
|
}, [observableClient, queryDef, paramsForApi]);
|
|
93
|
-
return {
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
95
|
+
return React.useMemo(() => {
|
|
96
|
+
const error = payload?.error ?? (payload?.status === "error" ? new Error("Failed to execute function") : undefined);
|
|
97
|
+
return {
|
|
98
|
+
data: payload?.result,
|
|
99
|
+
isLoading: payload?.status === "loading",
|
|
100
|
+
error,
|
|
101
|
+
lastUpdated: payload?.lastUpdated ?? 0,
|
|
102
|
+
refetch
|
|
103
|
+
};
|
|
104
|
+
}, [payload, refetch]);
|
|
100
105
|
}
|
|
101
106
|
//# sourceMappingURL=useOsdkFunction.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useOsdkFunction.js","names":["React","makeExternalStore","OsdkContext2","useOsdkFunction","queryDef","options","observableClient","useContext","params","dependsOn","dependsOnObjects","dedupeIntervalMs","enabled","stableParams","useMemo","JSON","stringify","stableDependsOn","map","d","apiName","stableDependsOnObjects","o","$apiName","$primaryKey","paramsForApi","subscribe","getSnapShot","unsubscribe","process","env","NODE_ENV","observer","observeFunction","dedupeInterval","version","payload","useSyncExternalStore","error","status","Error","undefined","refetch","useCallback","invalidateFunction","data","result","isLoading","lastUpdated"],"sources":["useOsdkFunction.ts"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n CompileTimeMetadata,\n ObjectTypeDefinition,\n Osdk,\n QueryDefinition,\n} from \"@osdk/api\";\nimport type {\n ObserveFunctionCallbackArgs,\n QueryParameterType,\n QueryReturnType,\n} from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { makeExternalStore } from \"./makeExternalStore.js\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\nexport interface UseOsdkFunctionOptions<Q extends QueryDefinition<unknown>> {\n /**\n * Parameters to pass to the function.\n * Must include all required parameters; optional parameters can be omitted.\n */\n params?: CompileTimeMetadata<Q>[\"parameters\"] extends Record<string, never>\n ? undefined\n : QueryParameterType<CompileTimeMetadata<Q>[\"parameters\"]>;\n\n /**\n * Object types this function depends on.\n * When actions modify objects of these types, the function will automatically refetch.\n *\n * @example\n * ```tsx\n * // Refetch when any Employee object changes\n * { dependsOn: [Employee] }\n * ```\n */\n dependsOn?: Array<ObjectTypeDefinition | string>;\n\n /**\n * Specific object instances this function depends on.\n * When any of these specific objects change, the function will refetch.\n * More fine-grained than dependsOn for precise invalidation control.\n *\n * @example\n * ```tsx\n * // Refetch when this specific employee changes\n * { dependsOnObjects: [employee] }\n * ```\n */\n dependsOnObjects?: Array<Osdk.Instance<ObjectTypeDefinition>>;\n\n /**\n * The number of milliseconds to dedupe identical function calls.\n * Two calls with the same function and params will share results\n * if the second call is within this interval of the first.\n * @default 2000\n */\n dedupeIntervalMs?: number;\n\n /**\n * Whether to enable the query. When false, the query will not execute.\n * Useful for:\n * - Dependent queries that need to wait for other data\n * - Conditional queries based on component state\n *\n * @default true\n * @example\n * // Dependent query - wait for required data\n * const { data: employee } = useOsdkObject(Employee, employeeId);\n * const { data: report } = useOsdkFunction(getEmployeeReport, {\n * params: { employeeId: employee?.$primaryKey },\n * enabled: !!employee\n * });\n */\n enabled?: boolean;\n}\n\nexport interface UseOsdkFunctionResult<Q extends QueryDefinition<unknown>> {\n /**\n * The function result, or undefined if not yet loaded or on error.\n */\n data: QueryReturnType<CompileTimeMetadata<Q>[\"output\"]> | undefined;\n\n /**\n * True while the function is executing.\n */\n isLoading: boolean;\n\n /**\n * Error if the function execution failed.\n */\n error: Error | undefined;\n\n /**\n * Timestamp (ms since epoch) of when the result was last fetched.\n */\n lastUpdated: number;\n\n /**\n * Manually refetch the function.\n * Useful for \"pull to refresh\" or retry patterns.\n */\n refetch: () => void;\n}\n\ndeclare const process: {\n env: {\n NODE_ENV: \"development\" | \"production\";\n };\n};\n\n/**\n * React hook for executing and observing OSDK functions.\n *\n * Provides automatic caching, deduplication, and reactive updates for function calls.\n * Functions are automatically re-fetched when dependencies change (configured via options).\n *\n * @param queryDef - The QueryDefinition to execute\n * @param options - Configuration options for the function call\n * @returns Object containing result, loading state, error, and refetch function\n *\n * @example Basic usage\n * ```tsx\n * const { data, isLoading, error } = useOsdkFunction(getEmployeeStats, {\n * params: { departmentId: \"engineering\" }\n * });\n * ```\n *\n * @example With dependency tracking\n * ```tsx\n * const { data, refetch } = useOsdkFunction(calculateMetrics, {\n * params: { startDate, endDate },\n * dependsOn: [Employee, Project],\n * });\n * ```\n *\n * @example With specific object dependencies\n * ```tsx\n * const { data } = useOsdkFunction(getEmployeeReport, {\n * params: { employeeId: employee.$primaryKey },\n * dependsOnObjects: [employee],\n * });\n * ```\n */\nexport function useOsdkFunction<Q extends QueryDefinition<unknown>>(\n queryDef: Q,\n options: UseOsdkFunctionOptions<Q> = {},\n): UseOsdkFunctionResult<Q> {\n const { observableClient } = React.useContext(OsdkContext2);\n const {\n params,\n dependsOn,\n dependsOnObjects,\n dedupeIntervalMs,\n enabled = true,\n } = options;\n\n const stableParams = React.useMemo(\n () => params,\n [JSON.stringify(params)],\n );\n const stableDependsOn = React.useMemo(\n () => dependsOn,\n [JSON.stringify(\n dependsOn?.map(d => typeof d === \"string\" ? d : d.apiName),\n )],\n );\n const stableDependsOnObjects = React.useMemo(\n () => dependsOnObjects,\n [JSON.stringify(\n dependsOnObjects?.map(o => ({\n $apiName: o.$apiName,\n $primaryKey: o.$primaryKey,\n })),\n )],\n );\n\n // Record<string, unknown> required as typing is figured out at runtime\n const paramsForApi = stableParams as Record<string, unknown> | undefined;\n\n const { subscribe, getSnapShot } = React.useMemo(\n () => {\n if (!enabled) {\n return makeExternalStore<ObserveFunctionCallbackArgs<Q>>(\n () => ({ unsubscribe: () => {} }),\n process.env.NODE_ENV !== \"production\"\n ? `function ${queryDef.apiName} ${\n JSON.stringify(stableParams)\n } [DISABLED]`\n : void 0,\n );\n }\n return makeExternalStore<ObserveFunctionCallbackArgs<Q>>(\n (observer) =>\n observableClient.observeFunction(\n queryDef,\n paramsForApi,\n {\n dependsOn: stableDependsOn,\n dependsOnObjects: stableDependsOnObjects,\n dedupeInterval: dedupeIntervalMs ?? 2_000,\n },\n observer,\n ),\n process.env.NODE_ENV !== \"production\"\n ? `function ${queryDef.apiName} ${JSON.stringify(stableParams)}`\n : void 0,\n );\n },\n [\n observableClient,\n queryDef.apiName,\n queryDef.version,\n paramsForApi,\n stableDependsOn,\n stableDependsOnObjects,\n dedupeIntervalMs,\n enabled,\n ],\n );\n\n const payload = React.useSyncExternalStore(subscribe, getSnapShot);\n\n const error = payload?.error\n ?? (payload?.status === \"error\"\n ? new Error(\"Failed to execute function\")\n : undefined);\n\n const refetch = React.useCallback(() => {\n void observableClient.invalidateFunction(queryDef, paramsForApi);\n }, [observableClient, queryDef, paramsForApi]);\n\n return {\n data: payload?.result as\n | QueryReturnType<CompileTimeMetadata<Q>[\"output\"]>\n | undefined,\n isLoading: payload?.status === \"loading\",\n error,\n lastUpdated: payload?.lastUpdated ?? 0,\n refetch,\n };\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAaA,OAAOA,KAAK,MAAM,OAAO;AACzB,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D,SAASC,YAAY,QAAQ,mBAAmB;AAgGhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAC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ACF,CAAC;AACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"useOsdkFunction.js","names":["getWireObjectSet","React","makeExternalStore","OsdkContext2","useOsdkFunction","queryDef","options","observableClient","useContext","params","dependsOn","dependsOnObjects","dedupeIntervalMs","enabled","stableParams","useMemo","JSON","stringify","stableDependsOn","map","d","apiName","stableDependsOnObjects","item","$apiName","$primaryKey","__objectSet","paramsForApi","subscribe","getSnapShot","unsubscribe","process","env","NODE_ENV","observer","observeFunction","dedupeInterval","version","payload","useSyncExternalStore","refetch","useCallback","invalidateFunction","error","status","Error","undefined","data","result","isLoading","lastUpdated"],"sources":["useOsdkFunction.ts"],"sourcesContent":["/*\n * Copyright 2025 Palantir Technologies, Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n CompileTimeMetadata,\n ObjectSet,\n ObjectTypeDefinition,\n Osdk,\n QueryDefinition,\n} from \"@osdk/api\";\nimport type {\n ObserveFunctionCallbackArgs,\n QueryParameterType,\n} from \"@osdk/client/unstable-do-not-use\";\nimport { getWireObjectSet } from \"@osdk/client/unstable-do-not-use\";\nimport React from \"react\";\nimport { makeExternalStore } from \"./makeExternalStore.js\";\nimport { OsdkContext2 } from \"./OsdkContext2.js\";\n\nexport interface UseOsdkFunctionOptions<Q extends QueryDefinition<unknown>> {\n /**\n * Parameters to pass to the function.\n * Must include all required parameters; optional parameters can be omitted.\n */\n params?: CompileTimeMetadata<Q>[\"parameters\"] extends Record<string, never>\n ? undefined\n : QueryParameterType<CompileTimeMetadata<Q>[\"parameters\"]>;\n\n /**\n * Object types this function depends on.\n * When actions modify objects of these types, the function will automatically refetch.\n *\n * @example\n * ```tsx\n * // Refetch when any Employee object changes\n * { dependsOn: [Employee] }\n * ```\n */\n dependsOn?: Array<ObjectTypeDefinition | string>;\n\n /**\n * Specific object instances or ObjectSets this function depends on.\n * When any of these specific objects change, the function will refetch.\n * More fine-grained than dependsOn for precise invalidation control.\n *\n * For ObjectSets, the object type is extracted asynchronously and changes\n * to any object of that type will trigger a refetch.\n *\n * @example\n * ```tsx\n * // Refetch when this specific employee changes\n * { dependsOnObjects: [employee] }\n *\n * // Refetch when any object in the ObjectSet's type changes\n * { dependsOnObjects: [employeeObjectSet] }\n * ```\n */\n dependsOnObjects?: Array<\n Osdk.Instance<ObjectTypeDefinition> | ObjectSet<ObjectTypeDefinition>\n >;\n\n /**\n * The number of milliseconds to dedupe identical function calls.\n * Two calls with the same function and params will share results\n * if the second call is within this interval of the first.\n * @default 2000\n */\n dedupeIntervalMs?: number;\n\n /**\n * Whether to enable the query. When false, the query will not execute.\n * Useful for:\n * - Dependent queries that need to wait for other data\n * - Conditional queries based on component state\n *\n * @default true\n * @example\n * // Dependent query - wait for required data\n * const { data: employee } = useOsdkObject(Employee, employeeId);\n * const { data: report } = useOsdkFunction(getEmployeeReport, {\n * params: { employeeId: employee?.$primaryKey },\n * enabled: !!employee\n * });\n */\n enabled?: boolean;\n}\n\nexport interface UseOsdkFunctionResult<Q extends QueryDefinition<unknown>> {\n /**\n * The function result, or undefined if not yet loaded or on error.\n */\n data:\n | (CompileTimeMetadata<Q>[\"signature\"] extends (...args: never[]) => infer R\n ? Awaited<R>\n : never)\n | undefined;\n\n /**\n * True while the function is executing.\n */\n isLoading: boolean;\n\n /**\n * Error if the function execution failed.\n */\n error: Error | undefined;\n\n /**\n * Timestamp (ms since epoch) of when the result was last fetched.\n */\n lastUpdated: number;\n\n /**\n * Manually refetch the function.\n * Useful for \"pull to refresh\" or retry patterns.\n */\n refetch: () => void;\n}\n\ndeclare const process: {\n env: {\n NODE_ENV: \"development\" | \"production\";\n };\n};\n\n/**\n * React hook for executing and observing OSDK functions.\n *\n * Provides automatic caching, deduplication, and reactive updates for function calls.\n * Functions are automatically re-fetched when dependencies change (configured via options).\n *\n * @param queryDef - The QueryDefinition to execute\n * @param options - Configuration options for the function call\n * @returns Object containing result, loading state, error, and refetch function\n *\n * @example Basic usage\n * ```tsx\n * const { data, isLoading, error } = useOsdkFunction(getEmployeeStats, {\n * params: { departmentId: \"engineering\" }\n * });\n * ```\n *\n * @example With dependency tracking\n * ```tsx\n * const { data, refetch } = useOsdkFunction(calculateMetrics, {\n * params: { startDate, endDate },\n * dependsOn: [Employee, Project],\n * });\n * ```\n *\n * @example With specific object dependencies\n * ```tsx\n * const { data } = useOsdkFunction(getEmployeeReport, {\n * params: { employeeId: employee.$primaryKey },\n * dependsOnObjects: [employee],\n * });\n * ```\n */\nexport function useOsdkFunction<Q extends QueryDefinition<unknown>>(\n queryDef: Q,\n options: UseOsdkFunctionOptions<Q> = {},\n): UseOsdkFunctionResult<Q> {\n const { observableClient } = React.useContext(OsdkContext2);\n const {\n params,\n dependsOn,\n dependsOnObjects,\n dedupeIntervalMs,\n enabled = true,\n } = options;\n\n const stableParams = React.useMemo(\n () => params,\n [JSON.stringify(params)],\n );\n const stableDependsOn = React.useMemo(\n () => dependsOn,\n [JSON.stringify(\n dependsOn?.map(d => typeof d === \"string\" ? d : d.apiName),\n )],\n );\n const stableDependsOnObjects = React.useMemo(\n () => dependsOnObjects,\n [JSON.stringify(\n dependsOnObjects?.map(item =>\n \"$apiName\" in item\n ? { $apiName: item.$apiName, $primaryKey: item.$primaryKey }\n : { __objectSet: getWireObjectSet(item) }\n ),\n )],\n );\n\n // Record<string, unknown> required as typing is figured out at runtime\n const paramsForApi = stableParams as Record<string, unknown> | undefined;\n\n const { subscribe, getSnapShot } = React.useMemo(\n () => {\n if (!enabled) {\n return makeExternalStore<ObserveFunctionCallbackArgs<Q>>(\n () => ({ unsubscribe: () => {} }),\n process.env.NODE_ENV !== \"production\"\n ? `function ${queryDef.apiName} ${\n JSON.stringify(stableParams)\n } [DISABLED]`\n : void 0,\n );\n }\n return makeExternalStore<ObserveFunctionCallbackArgs<Q>>(\n (observer) =>\n observableClient.observeFunction(\n queryDef,\n paramsForApi,\n {\n dependsOn: stableDependsOn,\n dependsOnObjects: stableDependsOnObjects,\n dedupeInterval: dedupeIntervalMs ?? 2_000,\n },\n observer,\n ),\n process.env.NODE_ENV !== \"production\"\n ? `function ${queryDef.apiName} ${JSON.stringify(stableParams)}`\n : void 0,\n );\n },\n [\n observableClient,\n queryDef.apiName,\n queryDef.version,\n paramsForApi,\n stableDependsOn,\n stableDependsOnObjects,\n dedupeIntervalMs,\n enabled,\n ],\n );\n\n const payload = React.useSyncExternalStore(subscribe, getSnapShot);\n\n const refetch = React.useCallback(() => {\n void observableClient.invalidateFunction(queryDef, paramsForApi);\n }, [observableClient, queryDef, paramsForApi]);\n\n return React.useMemo(() => {\n const error = payload?.error\n ?? (payload?.status === \"error\"\n ? new Error(\"Failed to execute function\")\n : undefined);\n\n return {\n data: payload?.result as UseOsdkFunctionResult<Q>[\"data\"],\n isLoading: payload?.status === \"loading\",\n error,\n lastUpdated: payload?.lastUpdated ?? 0,\n refetch,\n };\n }, [payload, refetch]);\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAaA,SAASA,gBAAgB,QAAQ,kCAAkC;AACnE,OAAOC,KAAK,MAAM,OAAO;AACzB,SAASC,iBAAiB,QAAQ,wBAAwB;AAC1D,SAASC,YAAY,QAAQ,mBAAmB;AA4GhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,eAAeA,CAC7BC,QAAW,EACXC,OAAkC,GAAG,CAAC,CAAC,EACb;EAC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WAAW,IAAI,CAAC;MACtCV;IACF,CAAC;EACH,CAAC,EAAE,CAACF,OAAO,EAAEE,OAAO,CAAC,CAAC;AACxB","ignoreList":[]}
|
|
@@ -31,6 +31,14 @@ import { OsdkContext2 } from "./OsdkContext2.js";
|
|
|
31
31
|
* @param enabled Enable or disable the query (defaults to true)
|
|
32
32
|
*/
|
|
33
33
|
|
|
34
|
+
/**
|
|
35
|
+
* Loads an object or interface instance by type and primary key with options.
|
|
36
|
+
*
|
|
37
|
+
* @param type The object type or interface definition
|
|
38
|
+
* @param primaryKey The primary key of the object
|
|
39
|
+
* @param options Options including $select and enabled
|
|
40
|
+
*/
|
|
41
|
+
|
|
34
42
|
/*
|
|
35
43
|
Implementation of useOsdkObject
|
|
36
44
|
*/
|
|
@@ -44,12 +52,17 @@ export function useOsdkObject(...args) {
|
|
|
44
52
|
// so we must use type assertions after runtime discrimination
|
|
45
53
|
const isInstanceSignature = "$objectType" in args[0];
|
|
46
54
|
|
|
55
|
+
// Extract options object if provided (3rd arg is an object with $select or enabled)
|
|
56
|
+
const optionsArg = !isInstanceSignature && args[2] != null && typeof args[2] === "object" ? args[2] : undefined;
|
|
57
|
+
|
|
47
58
|
// Extract enabled flag - 2nd param for instance signature, 3rd for type signature
|
|
48
|
-
const enabled = isInstanceSignature ? typeof args[1] === "boolean" ? args[1] : true : typeof args[2] === "boolean" ? args[2] : true;
|
|
59
|
+
const enabled = isInstanceSignature ? typeof args[1] === "boolean" ? args[1] : true : optionsArg ? optionsArg.enabled ?? true : typeof args[2] === "boolean" ? args[2] : true;
|
|
60
|
+
const selectArg = optionsArg?.$select;
|
|
49
61
|
const mode = isInstanceSignature ? "offline" : undefined;
|
|
50
62
|
const typeOrApiName = isInstanceSignature ? args[0].$objectType : args[0];
|
|
51
63
|
const primaryKey = isInstanceSignature ? args[0].$primaryKey : args[1];
|
|
52
64
|
const apiNameString = typeof typeOrApiName === "string" ? typeOrApiName : typeOrApiName.apiName;
|
|
65
|
+
const stableSelect = React.useMemo(() => selectArg, [JSON.stringify(selectArg)]);
|
|
53
66
|
const {
|
|
54
67
|
subscribe,
|
|
55
68
|
getSnapShot
|
|
@@ -60,24 +73,30 @@ export function useOsdkObject(...args) {
|
|
|
60
73
|
}), `object ${apiNameString} ${primaryKey} [DISABLED]`);
|
|
61
74
|
}
|
|
62
75
|
return makeExternalStore(observer => observableClient.observeObject(typeOrApiName, primaryKey, {
|
|
63
|
-
mode
|
|
76
|
+
mode,
|
|
77
|
+
...(stableSelect ? {
|
|
78
|
+
select: stableSelect
|
|
79
|
+
} : {})
|
|
64
80
|
}, observer), `object ${apiNameString} ${primaryKey}`);
|
|
65
|
-
}, [enabled, observableClient, typeOrApiName, apiNameString, primaryKey, mode]);
|
|
81
|
+
}, [enabled, observableClient, typeOrApiName, apiNameString, primaryKey, mode, stableSelect]);
|
|
66
82
|
const payload = React.useSyncExternalStore(subscribe, getSnapShot);
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
error
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
isOptimistic: !!payload?.isOptimistic,
|
|
77
|
-
error,
|
|
78
|
-
forceUpdate: () => {
|
|
79
|
-
throw new Error("not implemented");
|
|
83
|
+
const forceUpdate = React.useCallback(() => {
|
|
84
|
+
throw new Error("not implemented");
|
|
85
|
+
}, []);
|
|
86
|
+
return React.useMemo(() => {
|
|
87
|
+
let error;
|
|
88
|
+
if (payload && "error" in payload && payload.error) {
|
|
89
|
+
error = payload.error;
|
|
90
|
+
} else if (payload?.status === "error") {
|
|
91
|
+
error = new Error("Failed to load object");
|
|
80
92
|
}
|
|
81
|
-
|
|
93
|
+
return {
|
|
94
|
+
object: payload?.object,
|
|
95
|
+
isLoading: enabled ? payload?.status === "loading" || payload?.status === "init" || !payload : false,
|
|
96
|
+
isOptimistic: !!payload?.isOptimistic,
|
|
97
|
+
error,
|
|
98
|
+
forceUpdate
|
|
99
|
+
};
|
|
100
|
+
}, [payload, enabled, forceUpdate]);
|
|
82
101
|
}
|
|
83
102
|
//# sourceMappingURL=useOsdkObject.js.map
|