@plasmicapp/data-sources 0.1.117 → 0.1.120
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/data-sources.cjs.development.js +79 -59
- package/dist/data-sources.cjs.development.js.map +1 -1
- package/dist/data-sources.cjs.production.min.js +1 -1
- package/dist/data-sources.cjs.production.min.js.map +1 -1
- package/dist/data-sources.esm.js +79 -59
- package/dist/data-sources.esm.js.map +1 -1
- package/dist/hooks/usePlasmicDataOp.d.ts +1 -0
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"data-sources.cjs.production.min.js","sources":["../src/executor.tsx","../src/hooks/usePlasmicDataOp.tsx","../src/utils.ts","../src/helpers.ts","../src/components/Fetcher.tsx","../src/hooks/useDependencyAwareQuery.tsx"],"sourcesContent":["import { PlasmicDataSourceContextValue } from '@plasmicapp/data-sources-context';\nimport fetch from '@plasmicapp/isomorphic-unfetch';\nimport { wrapLoadingFetcher } from '@plasmicapp/query';\nimport stringify from 'fast-stringify';\nimport { ManyRowsResult, Pagination, SingleRowResult } from './types';\n\nconst DEFAULT_HOST = 'https://data.plasmic.app';\n\nexport interface DataOp {\n sourceId: string;\n opId: string;\n userArgs?: Record<string, any>;\n cacheKey?: string;\n invalidatedKeys?: string[] | null;\n roleId?: string | null;\n}\n\ninterface ExecuteOpts {\n userAuthToken?: string;\n user?: PlasmicDataSourceContextValue['user'];\n paginate?: Pagination;\n}\n\nconst UNAUTHORIZED_MESSAGE =\n 'You do not have permission to perform this operation. Login to get access or contact the app owner to get access.';\n\nexport async function executePlasmicDataOp<\n T extends SingleRowResult | ManyRowsResult\n>(op: DataOp, opts?: ExecuteOpts) {\n const func = getConfig(\n '__PLASMIC_EXECUTE_DATA_OP',\n _executePlasmicDataOp\n ) as typeof _executePlasmicDataOp;\n const res = await wrapLoadingFetcher(func)(op, opts);\n return res as T;\n}\n\nasync function _executePlasmicDataOp<\n T extends SingleRowResult | ManyRowsResult\n>(op: DataOp, opts?: ExecuteOpts) {\n if (op.roleId) {\n if (!opts?.user || !opts.user.roleIds.includes(op.roleId)) {\n console.error(UNAUTHORIZED_MESSAGE);\n throw new Error(UNAUTHORIZED_MESSAGE);\n }\n }\n\n const host = getConfig('__PLASMIC_DATA_HOST', DEFAULT_HOST);\n\n const url = `${host}/api/v1/server-data/sources/${op.sourceId}/execute`;\n const resp = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(opts?.userAuthToken && {\n 'x-plasmic-data-user-auth-token': opts.userAuthToken,\n }),\n },\n body: stringify({\n opId: op.opId,\n userArgs: op.userArgs ?? {},\n paginate: opts?.paginate,\n }),\n });\n if (resp.status !== 200) {\n const text = await resp.text();\n throw new Error(text);\n }\n return (await resp.json()) as T;\n}\n\nfunction getConfig<T>(key: string, defaultValue: T) {\n if (typeof globalThis === 'undefined') {\n return defaultValue;\n } else {\n return (globalThis as any)[key] ?? defaultValue;\n }\n}\n","import { usePlasmicDataSourceContext } from '@plasmicapp/data-sources-context';\n// eslint-disable-next-line no-restricted-imports\nimport * as ph from '@plasmicapp/host';\nimport {\n useMutablePlasmicQueryData,\n usePlasmicDataConfig,\n} from '@plasmicapp/query';\nimport React from 'react';\nimport { DataOp, executePlasmicDataOp } from '../executor';\nimport { ManyRowsResult, Pagination, SingleRowResult } from '../types';\nimport { pick } from '../utils';\n\nexport function makeCacheKey(\n dataOp: DataOp,\n opts?: { paginate?: Pagination; userAuthToken?: string | null }\n) {\n const queryDependencies = JSON.stringify({\n sourceId: dataOp.sourceId,\n opId: dataOp.opId,\n args: dataOp.userArgs,\n userAuthToken: opts?.userAuthToken,\n paginate: opts?.paginate,\n });\n return dataOp.cacheKey\n ? `${dataOp.cacheKey}${queryDependencies}`\n : queryDependencies;\n}\n\nconst enableLoadingBoundaryKey = 'plasmicInternalEnableLoadingBoundary';\n\nfunction mkUndefinedDataProxy(\n promiseRef: { fetchingPromise: Promise<any> | undefined },\n fetchAndUpdateCache: (() => Promise<any>) | undefined\n) {\n return new Proxy(\n {},\n {\n get: (_target, prop) => {\n if (prop === 'isPlasmicUndefinedDataProxy') {\n return true;\n }\n\n if (!fetchAndUpdateCache) {\n // There's no key so no fetch to kick off yet; when computing key,\n // we encountered some thrown exception (that's not an undefined data promise),\n // and so we can't fetch yet. This might be dependent on a $state or $prop value\n // that's currently undefined, etc. We will act like an undefined data object,\n // and trigger the usual fallback behavior\n return undefined;\n }\n\n const promise =\n // existing fetch\n promiseRef.fetchingPromise ||\n // No existing fetch, so kick off a fetch\n fetchAndUpdateCache();\n (promise as any).plasmicType = 'PlasmicUndefinedDataError';\n (promise as any).message = `Cannot read property ${String(\n prop\n )} - data is still loading`;\n throw promise;\n },\n }\n ) as any;\n}\n\ninterface PlasmicUndefinedDataErrorPromise extends Promise<any> {\n plasmicType: 'PlasmicUndefinedDataError';\n message: string;\n}\n\nfunction isPlasmicUndefinedDataErrorPromise(\n x: any\n): x is PlasmicUndefinedDataErrorPromise {\n return (\n !!x &&\n typeof x === 'object' &&\n (x as any).plasmicType === 'PlasmicUndefinedDataError'\n );\n}\n\nconst reactMajorVersion = +React.version.split('.')[0];\n\ntype ResolvableDataOp =\n | DataOp\n | undefined\n | null\n | (() => DataOp | undefined | null);\n\n/**\n * This returns either:\n * * DataOp to perform\n * * undefined/null, if no data op can be performed\n * * PlasmicUndefinedDataErrorPromise, if when trying to evaluate the DataOp to perform,\n * we encounter a PlasmicUndefinedDataErrorPromise, so this operation cannot be\n * performed until that promise is resolved.\n */\nfunction resolveDataOp(dataOp: ResolvableDataOp) {\n if (typeof dataOp === 'function') {\n try {\n return dataOp();\n } catch (err) {\n if (isPlasmicUndefinedDataErrorPromise(err)) {\n return err;\n }\n return null;\n }\n } else {\n return dataOp;\n }\n}\n\n/**\n * Fetches can be kicked off two ways -- normally, by useSWR(), or by some\n * expression accessing the `$queries.*` proxy when not ready yet. We need\n * a global cache for proxy-invoked caches, so that different components\n * with the same key can share the same fetch.\n *\n * The life cycle for this cache is short -- only the duration of a\n * proxy-invoked fetch, and once the fetch is done. That's because we really\n * just want SWR to be managing the cache, not us! Once the data is in SWR,\n * we will use SWR for getting data.\n */\nconst PRE_FETCHES = new Map<string, Promise<any>>();\n\nexport function usePlasmicDataOp<\n T extends SingleRowResult | ManyRowsResult,\n E = any\n>(\n dataOp: ResolvableDataOp,\n opts?: {\n paginate?: Pagination;\n noUndefinedDataProxy?: boolean;\n }\n): Partial<T> & {\n error?: E;\n isLoading?: boolean;\n} {\n const resolvedDataOp = resolveDataOp(dataOp);\n const ctx = usePlasmicDataSourceContext();\n const enableLoadingBoundary = !!ph.useDataEnv?.()?.[enableLoadingBoundaryKey];\n const { mutate, cache } = usePlasmicDataConfig();\n // Cannot perform this operation\n const isNullDataOp = !resolvedDataOp;\n // This operation depends on another data query to resolve first\n const isWaitingOnDependentQuery =\n isPlasmicUndefinedDataErrorPromise(resolvedDataOp);\n const key =\n !resolvedDataOp || isPlasmicUndefinedDataErrorPromise(resolvedDataOp)\n ? null\n : makeCacheKey(resolvedDataOp, {\n paginate: opts?.paginate,\n userAuthToken: ctx?.userAuthToken,\n });\n const fetchingData = React.useMemo(\n () => ({\n fetchingPromise: undefined as Promise<T> | undefined,\n }),\n [key]\n );\n const fetcher = React.useMemo(\n () => () => {\n // If we are in this function, that means SWR cache missed.\n if (!key) {\n throw new Error(`Fetcher should never be called without a proper key`);\n }\n\n // dataOp is guaranteed to be a DataOp, and not an undefined promise or null\n\n if (fetchingData.fetchingPromise) {\n // Fetch is already underway from this hook\n return fetchingData.fetchingPromise;\n }\n\n if (key && PRE_FETCHES.has(key)) {\n // Some other usePlasmicDataOp() hook elsewhere has already\n // started this fetch as well; re-use it here.\n const existing = PRE_FETCHES.get(key) as Promise<T>;\n fetchingData.fetchingPromise = existing;\n return existing;\n }\n\n // Else we really need to kick off this fetch now...\n const fetcherFn = () =>\n executePlasmicDataOp<T>(resolvedDataOp as DataOp, {\n userAuthToken: ctx?.userAuthToken || undefined,\n user: ctx?.user,\n paginate: opts?.paginate,\n });\n const fetcherPromise = fetcherFn();\n fetchingData.fetchingPromise = fetcherPromise;\n if (key) {\n PRE_FETCHES.set(key, fetcherPromise);\n // Once we have a result, we rely on swr to perform the caching,\n // so remove from our cache as quickly as possible.\n fetcherPromise.then(\n () => {\n PRE_FETCHES.delete(key);\n },\n () => {\n PRE_FETCHES.delete(key);\n }\n );\n }\n return fetcherPromise;\n },\n [key, fetchingData]\n );\n\n const dependentKeyDataErrorPromise = isPlasmicUndefinedDataErrorPromise(\n resolvedDataOp\n )\n ? resolvedDataOp\n : undefined;\n const fetchAndUpdateCache = React.useMemo(() => {\n if (!key && !dependentKeyDataErrorPromise) {\n // If there's no key, and no data query we're waiting for, then there's\n // no way to perform a fetch\n return undefined;\n }\n return () => {\n // This function is called when the undefined data proxy is invoked.\n // USUALLY, this means the data is not available in SWR yet, and\n // we need to kick off a fetch.\n\n if (fetchingData.fetchingPromise) {\n // No need to update cache as the exist promise call site will do it\n return fetchingData.fetchingPromise;\n }\n\n if (dependentKeyDataErrorPromise) {\n // We can't actually fetch yet, because we couldn't even evaluate the dataOp\n // to fetch for, because we depend on unfetched data. Once _that_\n // dataOp we depend on is finished, then we can try again. So we\n // will throw and wait for _that_ promise to be resolved instead.\n return dependentKeyDataErrorPromise;\n }\n\n if (!key) {\n throw new Error(`Expected key to be non-null`);\n }\n\n // SOMETIMES, SWR actually _does_ have the cache, but we still end up\n // here. That's because of how we update $queries, which takes two\n // cycles; each time we render, we build a `new$Queries`, and\n // `set$Queries(new$Queries)`. So once the data is ready, at the\n // first render, we will have data in `new$Queries` but not `$queries`,\n // but we will still finish rendering that pass, which means any `$queries`\n // access will still end up here. So we look into the SWR cache and\n // return any data that's here.\n const cached = cache.get(key);\n if (cached) {\n return Promise.resolve(cached);\n }\n const cachedError = cache.get(`$swr$${key}`);\n if (cachedError) {\n return Promise.reject(cachedError.error);\n }\n\n // Now, upon this proxy.get() miss, we want to kick off the fetch. We can't\n // wait for useSWR() to kick off the fetch, because upon data miss we are\n // throwing a promise, and useSWR() won't kick off the fetch till the effect,\n // so it will never get a chance to fetch. Instead, we fetch, and then we\n // put the fetched data into the SWR cache, so that next time useSWR() is called,\n // it will just find it in the cache.\n //\n // However, we don't want to fetch SYNCHRONOUSLY RIGHT NOW, becase we are in\n // the rendering phase (presumably, we're here because some component is trying\n // to read fetched data while rendering). Doing a fetch right now would invoke\n // the fetcher, which is wrapped by @plasmicapp/query to tracking loading state,\n // and upon loading state toggled to true, it will fire loading event listeners,\n // and for example, our antd's <GlobalLoadingIndicator /> will listen to this\n // event and immediately ask antd to show the loading indicator, which mutates\n // antd component's state. It is NOT LEGAL to call setState() on some other\n // component's state during rendering phase!\n //\n // We therefore will delay kicking off the fetch by a tick, so that we will safely\n // start the fetch outside of React rendering phase.\n const fetcherPromise = new Promise((resolve, reject) => {\n setTimeout(() => {\n fetcher().then(resolve, reject);\n }, 1);\n });\n fetcherPromise\n .then((data) => {\n // Insert the fetched data into the SWR cache\n mutate(key, data);\n })\n .catch((err) => {\n // Cache the error here to avoid infinite loop\n const keyInfo = key ? '$swr$' + key : '';\n cache.set(keyInfo, { ...(cache.get(keyInfo) ?? {}), error: err });\n });\n return fetcherPromise;\n };\n }, [fetcher, fetchingData, cache, key, dependentKeyDataErrorPromise]);\n const res = useMutablePlasmicQueryData<T, E>(key, fetcher, {\n shouldRetryOnError: false,\n\n // If revalidateIfStale is true, then if there's a cache entry with a key,\n // but no mounted hook with that key yet, and when the hook mounts with the key,\n // swr will revalidate. This may be reasonable behavior, but for us, this\n // happens all the time -- we prepopulate the cache with proxy-invoked fetch,\n // sometimes before swr had a chance to run the effect. So we turn off\n // revalidateIfStale here, and just let the user manage invalidation.\n revalidateIfStale: false,\n });\n const { data, error, isLoading } = res;\n if (fetchingData.fetchingPromise != null && data !== undefined) {\n // Clear the fetching promise as the actual data is now used (so\n // revalidation is possible)\n fetchingData.fetchingPromise = undefined;\n }\n return React.useMemo(() => {\n const result = {\n ...(data ?? ({} as Partial<T>)),\n ...pick(res, 'isLoading', 'error'),\n };\n if (\n !opts?.noUndefinedDataProxy &&\n reactMajorVersion >= 18 &&\n enableLoadingBoundary &&\n (isLoading || isNullDataOp || isWaitingOnDependentQuery) &&\n result.data === undefined &&\n result.schema === undefined &&\n result.error === undefined\n ) {\n result.data = mkUndefinedDataProxy(fetchingData, fetchAndUpdateCache);\n result.schema = mkUndefinedDataProxy(fetchingData, fetchAndUpdateCache);\n }\n return result;\n }, [\n isNullDataOp,\n isWaitingOnDependentQuery,\n data,\n error,\n isLoading,\n opts?.noUndefinedDataProxy,\n enableLoadingBoundary,\n fetchingData,\n fetchAndUpdateCache,\n ]);\n}\n\nexport function usePlasmicDataMutationOp<\n T extends SingleRowResult | ManyRowsResult\n>(dataOp: ResolvableDataOp) {\n const ctx = usePlasmicDataSourceContext();\n const userToken = ctx?.userAuthToken;\n\n const getRealDataOp = React.useCallback(async () => {\n const tryGetRealDataOp = async (): Promise<DataOp | null> => {\n const resolved = resolveDataOp(dataOp);\n if (!resolved) {\n return null;\n } else if (isPlasmicUndefinedDataErrorPromise(resolved)) {\n // If calling the dataOp function resulted in a data fetch,\n // then we wait for the data fetch to finish and try\n // again\n await resolved;\n return tryGetRealDataOp();\n } else {\n return resolved;\n }\n };\n return await tryGetRealDataOp();\n }, [dataOp]);\n\n return React.useCallback(async () => {\n const { sourceId, opId, userArgs } = (await getRealDataOp()) ?? {};\n\n if (!sourceId || !opId) {\n return undefined;\n }\n\n return executePlasmicDataOp<T>(\n { sourceId, opId, userArgs },\n {\n userAuthToken: userToken || undefined,\n user: ctx?.user,\n }\n );\n }, [getRealDataOp, userToken]);\n}\n","export function swallow<T>(f: () => T): T | undefined {\n try {\n return f();\n } catch {\n return undefined;\n }\n}\n\nexport function pick<T extends object, K extends keyof T>(\n obj: T,\n ...keys: K[]\n): Pick<T, K> {\n const res: any = {};\n for (const key of keys) {\n if (key in obj) {\n res[key] = obj[key as keyof T];\n }\n }\n return res;\n}\n\ntype ReactElt = {\n children: ReactElt | ReactElt[];\n props: {\n children: ReactElt | ReactElt[];\n [prop: string]: any;\n } | null;\n type: React.ComponentType<any> | null;\n key: string | null;\n} | null;\n\nexport function traverseReactEltTree(\n children: React.ReactNode,\n callback: (elt: ReactElt) => void\n) {\n const rec = (elts: ReactElt | ReactElt[] | null) => {\n (Array.isArray(elts) ? elts : [elts]).forEach((elt) => {\n if (elt) {\n callback(elt);\n if (elt.children) {\n rec(elt.children);\n }\n if (elt.props?.children && elt.props.children !== elt.children) {\n rec(elt.props.children);\n }\n }\n });\n };\n rec(children as any);\n}\n\nexport function asArray<T>(x: T[] | T | undefined | null) {\n if (Array.isArray(x)) {\n return x;\n } else if (x == null) {\n return [];\n } else {\n return [x];\n }\n}\n\nexport function ensureNumber(x: number | string): number {\n return x as number;\n}\n\nexport function ensure<T>(x: T | null | undefined): T {\n if (x === null || x === undefined) {\n throw new Error('Expected non-null or non-undefined value');\n }\n return x;\n}\n\nexport function isOneOf<T, U extends T>(elem: T, arr: readonly U[]): elem is U {\n return arr.includes(elem as any);\n}\n\nexport function maybe<T, U>(\n x: T | undefined | null,\n f: (y: T) => U\n): U | undefined {\n if (x === undefined || x === null) return undefined;\n return f(x);\n}\n\nexport function isLikeImage(value: unknown) {\n return typeof value === 'string'\n ? value.match(/\\.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff)$/i)\n : false;\n}\n\nexport function ensureArray<T>(xs: T | T[]): T[] {\n return Array.isArray(xs) ? xs : [xs];\n}\n\nexport const tuple = <T extends any[]>(...args: T): T => args;\n\nexport interface HasId {\n id: string;\n}\n\nexport function mkIdMap<T extends HasId>(xs: ReadonlyArray<T>): Map<string, T> {\n return new Map(xs.map((x) => tuple(x.id, x) as [string, T]));\n}\n\nexport const mkShortId = () => `${Math.random()}`;\n\nexport function withoutNils<T>(xs: Array<T | undefined | null>): T[] {\n return xs.filter((x): x is T => x != null);\n}\n\nexport type Falsey = null | undefined | false | '' | 0 | 0n;\nexport type Truthy<T> = T extends Falsey ? never : T;\n\nexport function withoutFalsey<T>(xs: Array<T | Falsey>): T[] {\n return xs.filter((x): x is T => !!x);\n}\n","import {\n ManyRowsResult,\n TableFieldSchema,\n TableFieldType,\n TableSchema,\n} from './types';\nimport { mkIdMap, withoutNils } from './utils';\n\nexport type QueryResult = Partial<ManyRowsResult<any>> & {\n error?: any;\n isLoading?: boolean;\n};\n\nexport interface NormalizedData {\n data: Record<string, unknown>[];\n schema?: TableSchema;\n}\n\nexport function normalizeData(rawData: unknown): NormalizedData | undefined {\n if (!rawData) {\n return undefined;\n }\n\n const dataArray = tryGetDataArray(rawData);\n if (!dataArray) {\n return undefined;\n }\n const schema = (rawData as any).schema ?? tryGetSchema(dataArray);\n if (!schema) {\n return undefined;\n }\n return { data: dataArray, schema };\n}\n\nfunction tryGetDataArray(rawData: unknown): any[] | undefined {\n if (rawData == null || typeof rawData !== 'object') {\n return undefined;\n }\n\n if (Array.isArray(rawData)) {\n if (isArrayOfObjects(rawData)) {\n return rawData;\n } else {\n // TODO: array of primitives? Maybe we can wrap this?\n return undefined;\n }\n }\n\n if (rawData == null) {\n return undefined;\n }\n\n if ('data' in rawData && typeof (rawData as any).data === 'object') {\n if (\n Array.isArray((rawData as any).data) &&\n isArrayOfObjects((rawData as any).data)\n ) {\n return (rawData as any).data;\n } else if ((rawData as any).data != null) {\n return [(rawData as any).data];\n } else {\n return undefined;\n }\n }\n if ('isLoading' in rawData || 'error' in rawData) {\n return undefined;\n }\n\n // Maybe a singleton record?\n return [rawData];\n}\n\nfunction isArrayOfObjects(arr: unknown[]) {\n return arr.every((x) => typeof x === 'object' && !Array.isArray(x));\n}\n\nfunction tryGetSchema(data: any[]): TableSchema | undefined {\n const fieldMap: Record<string, TableFieldType> = {};\n data.forEach((entry: any) => {\n if (entry && typeof entry === 'object') {\n Array.from(Object.entries(entry)).forEach(([k, v]) => {\n const inferredType: TableFieldType =\n typeof v === 'string'\n ? 'string'\n : typeof v === 'boolean'\n ? 'boolean'\n : typeof v === 'number'\n ? 'number'\n : 'unknown';\n if (fieldMap[k] && fieldMap[k] !== inferredType) {\n fieldMap[k] = 'unknown';\n } else {\n fieldMap[k] = inferredType;\n }\n });\n }\n });\n return {\n id: 'inferred',\n fields: Object.entries(fieldMap).map(([f, t]) => ({\n id: f,\n type: t,\n readOnly: false,\n })),\n };\n}\n\nexport type BaseFieldConfig = {\n key?: string;\n fieldId?: string;\n};\n\nconst mkShortId = () => `${Math.random()}`;\n\nexport function deriveFieldConfigs<T extends BaseFieldConfig>(\n specifiedFieldsPartial: Partial<T>[],\n schema: TableSchema | undefined,\n makeDefaultConfig: (field: TableFieldSchema | undefined) => T\n): {\n mergedFields: T[];\n minimalFullLengthFields: Partial<T>[];\n} {\n const schemaFields = schema?.fields ?? [];\n const fieldById = mkIdMap(schemaFields);\n const specifiedFieldIds = new Set(\n withoutNils(specifiedFieldsPartial.map((f) => f.fieldId))\n );\n const keptSpecifiedFields = specifiedFieldsPartial.flatMap((f): T[] => {\n if (!f.fieldId) {\n return [\n { key: mkShortId(), ...makeDefaultConfig(undefined), ...f },\n ] as T[];\n }\n const field = fieldById.get(f.fieldId as string);\n\n // Drop configs with fieldIds no longer in the data.\n if (!field) {\n return [];\n }\n\n return [\n {\n key: mkShortId(),\n ...makeDefaultConfig(field),\n ...f,\n },\n ] as T[];\n });\n const newVirtualFields = schemaFields\n .filter((f) => !specifiedFieldIds.has(f.id))\n .map(\n (f): T => ({\n key: mkShortId(),\n ...makeDefaultConfig(f),\n })\n );\n const mergedFields = [...keptSpecifiedFields, ...newVirtualFields];\n const minimalFullLengthFields: Partial<T>[] = [\n ...specifiedFieldsPartial,\n ...newVirtualFields.map((f) => ({ key: f.key, fieldId: f.fieldId })),\n ] as Partial<T>[];\n return { mergedFields, minimalFullLengthFields };\n}\n","import { ComponentMeta } from '@plasmicapp/host';\nimport React from 'react';\nimport { DataOp } from '../executor';\nimport { usePlasmicDataOp } from '../hooks/usePlasmicDataOp';\n\nexport interface DataOpConfig {\n name?: string;\n pageIndex?: number;\n pageSize?: number;\n}\n\nexport interface FetcherProps extends DataOpConfig {\n dataOp?: DataOp;\n children?: ($queries: Record<string, any>) => React.ReactElement | null;\n queries?: Record<string, any>;\n}\n\nexport function Fetcher(props: FetcherProps): React.ReactElement | null {\n const { dataOp, children, name, pageIndex, pageSize } = props;\n const data = usePlasmicDataOp(dataOp, {\n ...(!!pageIndex &&\n !!pageSize && {\n paginate: { pageIndex, pageSize },\n }),\n });\n\n const $queries = React.useMemo(\n () => ({ ...props.queries, [name ?? 'data']: data }),\n [props.queries, name, data]\n );\n\n return children?.($queries) ?? null;\n}\n\nexport const FetcherMeta: ComponentMeta<FetcherProps> = {\n name: 'plasmic-data-source-fetcher',\n displayName: 'Data Fetcher',\n props: {\n dataOp: {\n type: 'dataSourceOp' as any,\n displayName: 'Data',\n },\n name: {\n type: 'string',\n displayName: 'Variable name',\n },\n children: {\n type: 'slot',\n renderPropParams: ['$queries'],\n },\n pageSize: {\n type: 'number',\n advanced: true,\n displayName: 'Page size',\n description: 'Only fetch in batches of this size; for pagination',\n },\n pageIndex: {\n type: 'number',\n advanced: true,\n displayName: 'Page index',\n description: '0-based index of the paginated page to fetch',\n },\n },\n importPath: '@plasmicapp/react-web/lib/data-sources',\n importName: 'Fetcher',\n alwaysAutoName: true,\n styleSections: false,\n};\n","import React from 'react';\nimport { DataOpConfig } from '../components/Fetcher';\nimport { DataOp } from '../executor';\nimport { swallow } from '../utils';\nimport { usePlasmicDataOp } from './usePlasmicDataOp';\n\nfunction usePrevious<T>(value: T | undefined): T | undefined {\n const prevValue = React.useRef<T | undefined>(undefined);\n\n React.useEffect(() => {\n prevValue.current = value;\n\n return () => {\n prevValue.current = undefined;\n };\n });\n\n return prevValue.current;\n}\n\nexport interface DependencyAwareQueryConfig extends DataOpConfig {\n $queries: Record<string, any>;\n setDollarQueries: ($queries: Record<string, any>) => void;\n getDataOp: () => DataOp;\n}\n\n/**\n * @deprecated Prefer using `usePlasmicDataOp` directly instead.\n */\nexport function useDependencyAwareQuery({\n $queries,\n getDataOp,\n setDollarQueries,\n name,\n pageIndex,\n pageSize,\n}: DependencyAwareQueryConfig) {\n const data = usePlasmicDataOp(swallow(getDataOp), {\n ...(!!pageIndex &&\n !!pageSize && {\n paginate: { pageIndex, pageSize },\n }),\n });\n const finalName = name ?? 'data';\n const prevName = usePrevious(finalName);\n React.useEffect(() => {\n if (!(finalName in $queries) || $queries[finalName] !== data) {\n const $queries2 = {\n ...$queries,\n [finalName]: data,\n };\n if (prevName && finalName !== prevName && prevName in $queries) {\n delete $queries2[prevName];\n }\n setDollarQueries($queries2);\n }\n }, [finalName, prevName, data, $queries, setDollarQueries]);\n}\n"],"names":["UNAUTHORIZED_MESSAGE","executePlasmicDataOp","_x","_x2","_executePlasmicDataOp2","_asyncToGenerator","_regeneratorRuntime","mark","_callee","op","opts","func","wrap","_context","prev","next","getConfig","_executePlasmicDataOp","wrapLoadingFetcher","abrupt","sent","stop","apply","arguments","_x3","_x4","_executePlasmicDataOp3","_callee2","_op$userArgs","host","url","resp","_context2","roleId","user","roleIds","includes","console","error","Error","sourceId","fetch","method","headers","_extends","Content-Type","userAuthToken","x-plasmic-data-user-auth-token","body","stringify","opId","userArgs","paginate","status","text","json","key","defaultValue","globalThis","_globalThis$key","makeCacheKey","dataOp","queryDependencies","JSON","args","cacheKey","mkUndefinedDataProxy","promiseRef","fetchAndUpdateCache","Proxy","get","_target","prop","promise","fetchingPromise","plasmicType","message","String","isPlasmicUndefinedDataErrorPromise","x","reactMajorVersion","React","version","split","resolveDataOp","err","PRE_FETCHES","Map","usePlasmicDataOp","resolvedDataOp","ctx","usePlasmicDataSourceContext","enableLoadingBoundary","ph","_ph$useDataEnv","_usePlasmicDataConfig","usePlasmicDataConfig","mutate","cache","isNullDataOp","isWaitingOnDependentQuery","fetchingData","useMemo","undefined","fetcher","has","existing","fetcherPromise","set","then","dependentKeyDataErrorPromise","cached","Promise","resolve","cachedError","reject","setTimeout","data","keyInfo","_cache$get","res","useMutablePlasmicQueryData","shouldRetryOnError","revalidateIfStale","isLoading","result","obj","_len","length","keys","Array","_key","_i","_keys","pick","noUndefinedDataProxy","schema","isArrayOfObjects","arr","every","isArray","mkShortId","Math","random","props","children","name","pageIndex","pageSize","$queries","_extends2","queries","_children","displayName","type","renderPropParams","advanced","description","importPath","importName","alwaysAutoName","styleSections","specifiedFieldsPartial","makeDefaultConfig","schemaFields","_schema$fields","fields","fieldById","map","_len2","_key2","tuple","id","specifiedFieldIds","Set","f","fieldId","filter","keptSpecifiedFields","flatMap","field","newVirtualFields","mergedFields","concat","minimalFullLengthFields","rawData","dataArray","tryGetDataArray","fieldMap","_rawData$schema","forEach","entry","from","Object","entries","_ref","k","v","inferredType","_ref2","readOnly","value","prevValue","setDollarQueries","_unused","swallow","getDataOp","finalName","prevName","useRef","useEffect","current","$queries2","userToken","getRealDataOp","useCallback","tryGetRealDataOp","resolved","_callee3","_yield$getRealDataOp","_ref4","_context3","t0","t1"],"mappings":"4uOAMA,IAiBMA,EACJ,6HAEoBC,EAAoBC,EAAAC,GAAA,OAAAC,EAAAA,GAAAC,EAAAC,IAAAC,MAAnC,SAAAC,EAELC,EAAYC,GAAkB,IAAAC,EAAA,OAAAL,IAAAM,eAAAC,GAAA,cAAAA,EAAAC,KAAAD,EAAAE,MAAA,OAIG,OAH3BJ,EAAOK,EACX,4BACAC,GAC+BJ,EAAAE,OACfG,qBAAmBP,EAAnBO,CAAyBT,EAAIC,GAAK,OAA3C,OAAAG,EAAAM,gBAAAN,EAAAO,MACM,OAAA,UAAA,OAAAP,EAAAQ,UAAAb,QAChBc,WAAAC,WAAA,SAEcN,EAAqBO,EAAAC,GAAA,OAAAC,EAAAA,GAAArB,EAAAC,IAAAC,MAApC,SAAAoB,EAEElB,EAAYC,GAAkB,IAAAkB,EAAAC,EAAAC,EAAAC,EAAA,OAAAzB,IAAAM,eAAAoB,GAAA,cAAAA,EAAAlB,KAAAkB,EAAAjB,MAAA,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gBAElBsM,GAAQ,QAAA,UAAA,OAAA5M,EAAAQ,UAAAb,QAElBc,WAAAC,YAAAS,EAAAjB,OACYyM,IAAkB,OAAA,OAAAxL,EAAAb,gBAAAa,EAAAZ,MAAA,OAAA,UAAA,OAAAY,EAAAX,UAAAM,OAC9B,CAACkC,IAEJ,OAAOoB,EAAMsI,YAAWlN,EAAAC,IAAAC,MAAC,SAAAmN,IAAA,IAAAC,EAAAC,EAAApL,EAAAU,EAAAC,EAAA,OAAA7C,IAAAM,eAAAiN,GAAA,cAAAA,EAAA/M,KAAA+M,EAAA9M,MAAA,OAAA,OAAA8M,EAAA9M,OACqBuM,IAAe,OAAA,GAAAO,EAAAC,GAAAH,EAAAE,EAAAzM,WAAAyM,EAAAC,IAAAD,EAAA9M,OAAA,MAAA8M,EAAAE,GAAAJ,EAAAE,EAAA9M,OAAA,MAAA,OAAA8M,EAAAE,GAAK,GAAE,OAAlC,GAAd7K,GAAgD0K,EAAAC,EAAAE,IAAhD7K,KAAMC,EAAQyK,EAARzK,UAAhBX,EAAQoL,EAARpL,WAEUU,GAAI2K,EAAA9M,QAAA,MAAA,OAAA8M,EAAA1M,qBACboF,GAAS,QAAA,OAAAsH,EAAA1M,gBAGXlB,EACL,CAAEuC,SAAAA,EAAUU,KAAAA,EAAMC,SAAAA,GAClB,CACEL,cAAeuK,QAAa9G,EAC5BrE,WAAMwD,SAAAA,EAAKxD,QAEd,QAAA,UAAA,OAAA2L,EAAAxM,UAAAqM,OACA,CAACJ,EAAeD"}
|
|
1
|
+
{"version":3,"file":"data-sources.cjs.production.min.js","sources":["../src/executor.tsx","../src/hooks/usePlasmicDataOp.tsx","../src/utils.ts","../src/helpers.ts","../src/components/Fetcher.tsx","../src/hooks/useDependencyAwareQuery.tsx"],"sourcesContent":["import { PlasmicDataSourceContextValue } from '@plasmicapp/data-sources-context';\nimport fetch from '@plasmicapp/isomorphic-unfetch';\nimport { wrapLoadingFetcher } from '@plasmicapp/query';\nimport stringify from 'fast-stringify';\nimport { ManyRowsResult, Pagination, SingleRowResult } from './types';\n\nconst DEFAULT_HOST = 'https://data.plasmic.app';\n\nexport interface DataOp {\n sourceId: string;\n opId: string;\n userArgs?: Record<string, any>;\n cacheKey?: string;\n invalidatedKeys?: string[] | null;\n roleId?: string | null;\n}\n\ninterface ExecuteOpts {\n userAuthToken?: string;\n user?: PlasmicDataSourceContextValue['user'];\n paginate?: Pagination;\n}\n\nconst UNAUTHORIZED_MESSAGE =\n 'You do not have permission to perform this operation. Login to get access or contact the app owner to get access.';\n\nexport async function executePlasmicDataOp<\n T extends SingleRowResult | ManyRowsResult\n>(op: DataOp, opts?: ExecuteOpts) {\n const func = getConfig(\n '__PLASMIC_EXECUTE_DATA_OP',\n _executePlasmicDataOp\n ) as typeof _executePlasmicDataOp;\n const res = await wrapLoadingFetcher(func)(op, opts);\n return res as T;\n}\n\nasync function _executePlasmicDataOp<\n T extends SingleRowResult | ManyRowsResult\n>(op: DataOp, opts?: ExecuteOpts) {\n if (op.roleId) {\n if (!opts?.user || !opts.user.roleIds.includes(op.roleId)) {\n console.error(UNAUTHORIZED_MESSAGE);\n throw new Error(UNAUTHORIZED_MESSAGE);\n }\n }\n\n const host = getConfig('__PLASMIC_DATA_HOST', DEFAULT_HOST);\n\n const url = `${host}/api/v1/server-data/sources/${op.sourceId}/execute`;\n const resp = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(opts?.userAuthToken && {\n 'x-plasmic-data-user-auth-token': opts.userAuthToken,\n }),\n },\n body: stringify({\n opId: op.opId,\n userArgs: op.userArgs ?? {},\n paginate: opts?.paginate,\n }),\n });\n if (resp.status !== 200) {\n const text = await resp.text();\n throw new Error(text);\n }\n return (await resp.json()) as T;\n}\n\nfunction getConfig<T>(key: string, defaultValue: T) {\n if (typeof globalThis === 'undefined') {\n return defaultValue;\n } else {\n return (globalThis as any)[key] ?? defaultValue;\n }\n}\n","import { usePlasmicDataSourceContext } from '@plasmicapp/data-sources-context';\n// eslint-disable-next-line no-restricted-imports\nimport * as ph from '@plasmicapp/host';\nimport {\n useMutablePlasmicQueryData,\n usePlasmicDataConfig,\n} from '@plasmicapp/query';\nimport React from 'react';\nimport { DataOp, executePlasmicDataOp } from '../executor';\nimport { ManyRowsResult, Pagination, SingleRowResult } from '../types';\nimport { pick } from '../utils';\n\nexport function makeCacheKey(\n dataOp: DataOp,\n opts?: { paginate?: Pagination; userAuthToken?: string | null }\n) {\n const queryDependencies = JSON.stringify({\n sourceId: dataOp.sourceId,\n opId: dataOp.opId,\n args: dataOp.userArgs,\n userAuthToken: opts?.userAuthToken,\n paginate: opts?.paginate,\n });\n return dataOp.cacheKey\n ? `${dataOp.cacheKey}${queryDependencies}`\n : queryDependencies;\n}\n\nexport function usePlasmicInvalidate() {\n const { cache, fallback, mutate } = usePlasmicDataConfig();\n return async (invalidatedKeys: string[] | null | undefined) => {\n const getKeysToInvalidate = () => {\n if (!invalidatedKeys) {\n return [];\n }\n const allKeys = Array.from(\n new Set([\n ...(cache as any).keys(),\n ...(fallback ? Object.keys(fallback) : []),\n ])\n ).filter((key): key is string => typeof key === 'string');\n if (invalidatedKeys.includes('plasmic_refresh_all')) {\n return allKeys;\n }\n return allKeys.filter((key) =>\n invalidatedKeys.some((k) => key.includes(`.$.${k}.$.`))\n );\n };\n\n const keys = getKeysToInvalidate();\n if (keys.length === 0) {\n return;\n }\n\n return await Promise.all(keys.map((key) => mutate(key)));\n };\n}\n\nconst enableLoadingBoundaryKey = 'plasmicInternalEnableLoadingBoundary';\n\nfunction mkUndefinedDataProxy(\n promiseRef: { fetchingPromise: Promise<any> | undefined },\n fetchAndUpdateCache: (() => Promise<any>) | undefined\n) {\n let fetchAndUpdatePromise: Promise<any> | undefined = undefined;\n\n return new Proxy(\n {},\n {\n get: (_target, prop) => {\n if (prop === 'isPlasmicUndefinedDataProxy') {\n return true;\n }\n\n if (!fetchAndUpdateCache) {\n // There's no key so no fetch to kick off yet; when computing key,\n // we encountered some thrown exception (that's not an undefined data promise),\n // and so we can't fetch yet. This might be dependent on a $state or $prop value\n // that's currently undefined, etc. We will act like an undefined data object,\n // and trigger the usual fallback behavior\n return undefined;\n }\n\n const doFetchAndUpdate = () => {\n // We hold onto the promise last returned by fetchAndUpdateCache()\n // and keep reusing it until it is resolved. The reason is that the\n // Promise thrown here will be used as a dependency for memoized\n // fetchAndUpdateCache, which is a dependency on the memoized returned value\n // from usePlasmicDataOp(). If we have a fetch that's taking a long time,\n // we want to make sure that our memoized returned value is stable,\n // so that we don't keep calling setDollarQueries() (otherwise, for each\n // render, we find an unstable result, and call setDollarQueries(),\n // resulting in an infinite loop while fetch is happening).\n if (!fetchAndUpdatePromise) {\n fetchAndUpdatePromise = fetchAndUpdateCache().finally(() => {\n fetchAndUpdatePromise = undefined;\n });\n }\n return fetchAndUpdatePromise;\n };\n\n const promise =\n // existing fetch\n promiseRef.fetchingPromise ||\n // No existing fetch, so kick off a fetch\n doFetchAndUpdate();\n (promise as any).plasmicType = 'PlasmicUndefinedDataError';\n (promise as any).message = `Cannot read property ${String(\n prop\n )} - data is still loading`;\n throw promise;\n },\n }\n ) as any;\n}\n\ninterface PlasmicUndefinedDataErrorPromise extends Promise<any> {\n plasmicType: 'PlasmicUndefinedDataError';\n message: string;\n}\n\nfunction isPlasmicUndefinedDataErrorPromise(\n x: any\n): x is PlasmicUndefinedDataErrorPromise {\n return (\n !!x &&\n typeof x === 'object' &&\n (x as any).plasmicType === 'PlasmicUndefinedDataError'\n );\n}\n\nconst reactMajorVersion = +React.version.split('.')[0];\n\ntype ResolvableDataOp =\n | DataOp\n | undefined\n | null\n | (() => DataOp | undefined | null);\n\n/**\n * This returns either:\n * * DataOp to perform\n * * undefined/null, if no data op can be performed\n * * PlasmicUndefinedDataErrorPromise, if when trying to evaluate the DataOp to perform,\n * we encounter a PlasmicUndefinedDataErrorPromise, so this operation cannot be\n * performed until that promise is resolved.\n */\nfunction resolveDataOp(dataOp: ResolvableDataOp) {\n if (typeof dataOp === 'function') {\n try {\n return dataOp();\n } catch (err) {\n if (isPlasmicUndefinedDataErrorPromise(err)) {\n return err;\n }\n return null;\n }\n } else {\n return dataOp;\n }\n}\n\n/**\n * Fetches can be kicked off two ways -- normally, by useSWR(), or by some\n * expression accessing the `$queries.*` proxy when not ready yet. We need\n * a global cache for proxy-invoked caches, so that different components\n * with the same key can share the same fetch.\n *\n * The life cycle for this cache is short -- only the duration of a\n * proxy-invoked fetch, and once the fetch is done. That's because we really\n * just want SWR to be managing the cache, not us! Once the data is in SWR,\n * we will use SWR for getting data.\n */\nconst PRE_FETCHES = new Map<string, Promise<any>>();\n\nexport function usePlasmicDataOp<\n T extends SingleRowResult | ManyRowsResult,\n E = any\n>(\n dataOp: ResolvableDataOp,\n opts?: {\n paginate?: Pagination;\n noUndefinedDataProxy?: boolean;\n }\n): Partial<T> & {\n error?: E;\n isLoading?: boolean;\n} {\n const resolvedDataOp = resolveDataOp(dataOp);\n const ctx = usePlasmicDataSourceContext();\n const enableLoadingBoundary = !!ph.useDataEnv?.()?.[enableLoadingBoundaryKey];\n const { mutate, cache } = usePlasmicDataConfig();\n // Cannot perform this operation\n const isNullDataOp = !resolvedDataOp;\n // This operation depends on another data query to resolve first\n const isWaitingOnDependentQuery =\n isPlasmicUndefinedDataErrorPromise(resolvedDataOp);\n const key =\n !resolvedDataOp || isPlasmicUndefinedDataErrorPromise(resolvedDataOp)\n ? null\n : makeCacheKey(resolvedDataOp, {\n paginate: opts?.paginate,\n userAuthToken: ctx?.userAuthToken,\n });\n const fetchingData = React.useMemo(\n () => ({\n fetchingPromise: undefined as Promise<T> | undefined,\n }),\n [key]\n );\n const fetcher = React.useMemo(\n () => () => {\n // If we are in this function, that means SWR cache missed.\n if (!key) {\n throw new Error(`Fetcher should never be called without a proper key`);\n }\n\n // dataOp is guaranteed to be a DataOp, and not an undefined promise or null\n\n if (fetchingData.fetchingPromise) {\n // Fetch is already underway from this hook\n return fetchingData.fetchingPromise;\n }\n\n if (key && PRE_FETCHES.has(key)) {\n // Some other usePlasmicDataOp() hook elsewhere has already\n // started this fetch as well; re-use it here.\n const existing = PRE_FETCHES.get(key) as Promise<T>;\n fetchingData.fetchingPromise = existing;\n return existing;\n }\n\n // Else we really need to kick off this fetch now...\n const fetcherFn = () =>\n executePlasmicDataOp<T>(resolvedDataOp as DataOp, {\n userAuthToken: ctx?.userAuthToken || undefined,\n user: ctx?.user,\n paginate: opts?.paginate,\n });\n const fetcherPromise = fetcherFn();\n fetchingData.fetchingPromise = fetcherPromise;\n if (key) {\n PRE_FETCHES.set(key, fetcherPromise);\n // Once we have a result, we rely on swr to perform the caching,\n // so remove from our cache as quickly as possible.\n fetcherPromise.then(\n () => {\n PRE_FETCHES.delete(key);\n },\n () => {\n PRE_FETCHES.delete(key);\n }\n );\n }\n return fetcherPromise;\n },\n [key, fetchingData]\n );\n\n const dependentKeyDataErrorPromise = isPlasmicUndefinedDataErrorPromise(\n resolvedDataOp\n )\n ? resolvedDataOp\n : undefined;\n const fetchAndUpdateCache = React.useMemo(() => {\n if (!key && !dependentKeyDataErrorPromise) {\n // If there's no key, and no data query we're waiting for, then there's\n // no way to perform a fetch\n return undefined;\n }\n return () => {\n // This function is called when the undefined data proxy is invoked.\n // USUALLY, this means the data is not available in SWR yet, and\n // we need to kick off a fetch.\n\n if (fetchingData.fetchingPromise) {\n // No need to update cache as the exist promise call site will do it\n return fetchingData.fetchingPromise;\n }\n\n if (dependentKeyDataErrorPromise) {\n // We can't actually fetch yet, because we couldn't even evaluate the dataOp\n // to fetch for, because we depend on unfetched data. Once _that_\n // dataOp we depend on is finished, then we can try again. So we\n // will throw and wait for _that_ promise to be resolved instead.\n return dependentKeyDataErrorPromise;\n }\n\n if (!key) {\n throw new Error(`Expected key to be non-null`);\n }\n\n // SOMETIMES, SWR actually _does_ have the cache, but we still end up\n // here. That's because of how we update $queries, which takes two\n // cycles; each time we render, we build a `new$Queries`, and\n // `set$Queries(new$Queries)`. So once the data is ready, at the\n // first render, we will have data in `new$Queries` but not `$queries`,\n // but we will still finish rendering that pass, which means any `$queries`\n // access will still end up here. So we look into the SWR cache and\n // return any data that's here.\n const cached = cache.get(key);\n if (cached) {\n return Promise.resolve(cached);\n }\n const cachedError = cache.get(`$swr$${key}`);\n if (cachedError) {\n return Promise.reject(cachedError.error);\n }\n\n // Now, upon this proxy.get() miss, we want to kick off the fetch. We can't\n // wait for useSWR() to kick off the fetch, because upon data miss we are\n // throwing a promise, and useSWR() won't kick off the fetch till the effect,\n // so it will never get a chance to fetch. Instead, we fetch, and then we\n // put the fetched data into the SWR cache, so that next time useSWR() is called,\n // it will just find it in the cache.\n //\n // However, we don't want to fetch SYNCHRONOUSLY RIGHT NOW, becase we are in\n // the rendering phase (presumably, we're here because some component is trying\n // to read fetched data while rendering). Doing a fetch right now would invoke\n // the fetcher, which is wrapped by @plasmicapp/query to tracking loading state,\n // and upon loading state toggled to true, it will fire loading event listeners,\n // and for example, our antd's <GlobalLoadingIndicator /> will listen to this\n // event and immediately ask antd to show the loading indicator, which mutates\n // antd component's state. It is NOT LEGAL to call setState() on some other\n // component's state during rendering phase!\n //\n // We therefore will delay kicking off the fetch by a tick, so that we will safely\n // start the fetch outside of React rendering phase.\n const fetcherPromise = new Promise((resolve, reject) => {\n setTimeout(() => {\n fetcher().then(resolve, reject);\n }, 1);\n });\n fetcherPromise\n .then((data) => {\n // Insert the fetched data into the SWR cache\n mutate(key, data);\n })\n .catch((err) => {\n // Cache the error here to avoid infinite loop\n const keyInfo = key ? '$swr$' + key : '';\n cache.set(keyInfo, { ...(cache.get(keyInfo) ?? {}), error: err });\n });\n return fetcherPromise;\n };\n }, [fetcher, fetchingData, cache, key, dependentKeyDataErrorPromise]);\n const res = useMutablePlasmicQueryData<T, E>(key, fetcher, {\n shouldRetryOnError: false,\n\n // If revalidateIfStale is true, then if there's a cache entry with a key,\n // but no mounted hook with that key yet, and when the hook mounts with the key,\n // swr will revalidate. This may be reasonable behavior, but for us, this\n // happens all the time -- we prepopulate the cache with proxy-invoked fetch,\n // sometimes before swr had a chance to run the effect. So we turn off\n // revalidateIfStale here, and just let the user manage invalidation.\n // TODO: even so, we don't do this for now, as fallback data\n // does not get inserted into the cache with\n // `revalidateIfStale: false`, so we cannot invalidate them.\n // Will fix with usePlasmicDataInvalidate()\n // revalidateIfStale: false,\n });\n const { data, error, isLoading } = res;\n if (fetchingData.fetchingPromise != null && data !== undefined) {\n // Clear the fetching promise as the actual data is now used (so\n // revalidation is possible)\n fetchingData.fetchingPromise = undefined;\n }\n return React.useMemo(() => {\n const result = {\n ...(data ?? ({} as Partial<T>)),\n ...pick(res, 'isLoading', 'error'),\n };\n if (\n !opts?.noUndefinedDataProxy &&\n reactMajorVersion >= 18 &&\n enableLoadingBoundary &&\n (isLoading || isNullDataOp || isWaitingOnDependentQuery) &&\n result.data === undefined &&\n result.schema === undefined &&\n result.error === undefined\n ) {\n result.data = mkUndefinedDataProxy(fetchingData, fetchAndUpdateCache);\n result.schema = mkUndefinedDataProxy(fetchingData, fetchAndUpdateCache);\n }\n return result;\n }, [\n isNullDataOp,\n isWaitingOnDependentQuery,\n data,\n error,\n isLoading,\n opts?.noUndefinedDataProxy,\n enableLoadingBoundary,\n fetchingData,\n fetchAndUpdateCache,\n ]);\n}\n\nexport function usePlasmicDataMutationOp<\n T extends SingleRowResult | ManyRowsResult\n>(dataOp: ResolvableDataOp) {\n const ctx = usePlasmicDataSourceContext();\n const userToken = ctx?.userAuthToken;\n\n const getRealDataOp = React.useCallback(async () => {\n const tryGetRealDataOp = async (): Promise<DataOp | null> => {\n const resolved = resolveDataOp(dataOp);\n if (!resolved) {\n return null;\n } else if (isPlasmicUndefinedDataErrorPromise(resolved)) {\n // If calling the dataOp function resulted in a data fetch,\n // then we wait for the data fetch to finish and try\n // again\n await resolved;\n return tryGetRealDataOp();\n } else {\n return resolved;\n }\n };\n return await tryGetRealDataOp();\n }, [dataOp]);\n\n return React.useCallback(async () => {\n const { sourceId, opId, userArgs } = (await getRealDataOp()) ?? {};\n\n if (!sourceId || !opId) {\n return undefined;\n }\n\n return executePlasmicDataOp<T>(\n { sourceId, opId, userArgs },\n {\n userAuthToken: userToken || undefined,\n user: ctx?.user,\n }\n );\n }, [getRealDataOp, userToken]);\n}\n","export function swallow<T>(f: () => T): T | undefined {\n try {\n return f();\n } catch {\n return undefined;\n }\n}\n\nexport function pick<T extends object, K extends keyof T>(\n obj: T,\n ...keys: K[]\n): Pick<T, K> {\n const res: any = {};\n for (const key of keys) {\n if (key in obj) {\n res[key] = obj[key as keyof T];\n }\n }\n return res;\n}\n\ntype ReactElt = {\n children: ReactElt | ReactElt[];\n props: {\n children: ReactElt | ReactElt[];\n [prop: string]: any;\n } | null;\n type: React.ComponentType<any> | null;\n key: string | null;\n} | null;\n\nexport function traverseReactEltTree(\n children: React.ReactNode,\n callback: (elt: ReactElt) => void\n) {\n const rec = (elts: ReactElt | ReactElt[] | null) => {\n (Array.isArray(elts) ? elts : [elts]).forEach((elt) => {\n if (elt) {\n callback(elt);\n if (elt.children) {\n rec(elt.children);\n }\n if (elt.props?.children && elt.props.children !== elt.children) {\n rec(elt.props.children);\n }\n }\n });\n };\n rec(children as any);\n}\n\nexport function asArray<T>(x: T[] | T | undefined | null) {\n if (Array.isArray(x)) {\n return x;\n } else if (x == null) {\n return [];\n } else {\n return [x];\n }\n}\n\nexport function ensureNumber(x: number | string): number {\n return x as number;\n}\n\nexport function ensure<T>(x: T | null | undefined): T {\n if (x === null || x === undefined) {\n throw new Error('Expected non-null or non-undefined value');\n }\n return x;\n}\n\nexport function isOneOf<T, U extends T>(elem: T, arr: readonly U[]): elem is U {\n return arr.includes(elem as any);\n}\n\nexport function maybe<T, U>(\n x: T | undefined | null,\n f: (y: T) => U\n): U | undefined {\n if (x === undefined || x === null) return undefined;\n return f(x);\n}\n\nexport function isLikeImage(value: unknown) {\n return typeof value === 'string'\n ? value.match(/\\.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff)$/i)\n : false;\n}\n\nexport function ensureArray<T>(xs: T | T[]): T[] {\n return Array.isArray(xs) ? xs : [xs];\n}\n\nexport const tuple = <T extends any[]>(...args: T): T => args;\n\nexport interface HasId {\n id: string;\n}\n\nexport function mkIdMap<T extends HasId>(xs: ReadonlyArray<T>): Map<string, T> {\n return new Map(xs.map((x) => tuple(x.id, x) as [string, T]));\n}\n\nexport const mkShortId = () => `${Math.random()}`;\n\nexport function withoutNils<T>(xs: Array<T | undefined | null>): T[] {\n return xs.filter((x): x is T => x != null);\n}\n\nexport type Falsey = null | undefined | false | '' | 0 | 0n;\nexport type Truthy<T> = T extends Falsey ? never : T;\n\nexport function withoutFalsey<T>(xs: Array<T | Falsey>): T[] {\n return xs.filter((x): x is T => !!x);\n}\n","import {\n ManyRowsResult,\n TableFieldSchema,\n TableFieldType,\n TableSchema,\n} from './types';\nimport { mkIdMap, withoutNils } from './utils';\n\nexport type QueryResult = Partial<ManyRowsResult<any>> & {\n error?: any;\n isLoading?: boolean;\n};\n\nexport interface NormalizedData {\n data: Record<string, unknown>[];\n schema?: TableSchema;\n}\n\nexport function normalizeData(rawData: unknown): NormalizedData | undefined {\n if (!rawData) {\n return undefined;\n }\n\n const dataArray = tryGetDataArray(rawData);\n if (!dataArray) {\n return undefined;\n }\n const schema = (rawData as any).schema ?? tryGetSchema(dataArray);\n if (!schema) {\n return undefined;\n }\n return { data: dataArray, schema };\n}\n\nfunction tryGetDataArray(rawData: unknown): any[] | undefined {\n if (rawData == null || typeof rawData !== 'object') {\n return undefined;\n }\n\n if (Array.isArray(rawData)) {\n if (isArrayOfObjects(rawData)) {\n return rawData;\n } else {\n // TODO: array of primitives? Maybe we can wrap this?\n return undefined;\n }\n }\n\n if (rawData == null) {\n return undefined;\n }\n\n if ('data' in rawData && typeof (rawData as any).data === 'object') {\n if (\n Array.isArray((rawData as any).data) &&\n isArrayOfObjects((rawData as any).data)\n ) {\n return (rawData as any).data;\n } else if ((rawData as any).data != null) {\n return [(rawData as any).data];\n } else {\n return undefined;\n }\n }\n if ('isLoading' in rawData || 'error' in rawData) {\n return undefined;\n }\n\n // Maybe a singleton record?\n return [rawData];\n}\n\nfunction isArrayOfObjects(arr: unknown[]) {\n return arr.every((x) => typeof x === 'object' && !Array.isArray(x));\n}\n\nfunction tryGetSchema(data: any[]): TableSchema | undefined {\n const fieldMap: Record<string, TableFieldType> = {};\n data.forEach((entry: any) => {\n if (entry && typeof entry === 'object') {\n Array.from(Object.entries(entry)).forEach(([k, v]) => {\n const inferredType: TableFieldType =\n typeof v === 'string'\n ? 'string'\n : typeof v === 'boolean'\n ? 'boolean'\n : typeof v === 'number'\n ? 'number'\n : 'unknown';\n if (fieldMap[k] && fieldMap[k] !== inferredType) {\n fieldMap[k] = 'unknown';\n } else {\n fieldMap[k] = inferredType;\n }\n });\n }\n });\n return {\n id: 'inferred',\n fields: Object.entries(fieldMap).map(([f, t]) => ({\n id: f,\n type: t,\n readOnly: false,\n })),\n };\n}\n\nexport type BaseFieldConfig = {\n key?: string;\n fieldId?: string;\n};\n\nconst mkShortId = () => `${Math.random()}`;\n\nexport function deriveFieldConfigs<T extends BaseFieldConfig>(\n specifiedFieldsPartial: Partial<T>[],\n schema: TableSchema | undefined,\n makeDefaultConfig: (field: TableFieldSchema | undefined) => T\n): {\n mergedFields: T[];\n minimalFullLengthFields: Partial<T>[];\n} {\n const schemaFields = schema?.fields ?? [];\n const fieldById = mkIdMap(schemaFields);\n const specifiedFieldIds = new Set(\n withoutNils(specifiedFieldsPartial.map((f) => f.fieldId))\n );\n const keptSpecifiedFields = specifiedFieldsPartial.flatMap((f): T[] => {\n if (!f.fieldId) {\n return [\n { key: mkShortId(), ...makeDefaultConfig(undefined), ...f },\n ] as T[];\n }\n const field = fieldById.get(f.fieldId as string);\n\n // Drop configs with fieldIds no longer in the data.\n if (!field) {\n return [];\n }\n\n return [\n {\n key: mkShortId(),\n ...makeDefaultConfig(field),\n ...f,\n },\n ] as T[];\n });\n const newVirtualFields = schemaFields\n .filter((f) => !specifiedFieldIds.has(f.id))\n .map(\n (f): T => ({\n key: mkShortId(),\n ...makeDefaultConfig(f),\n })\n );\n const mergedFields = [...keptSpecifiedFields, ...newVirtualFields];\n const minimalFullLengthFields: Partial<T>[] = [\n ...specifiedFieldsPartial,\n ...newVirtualFields.map((f) => ({ key: f.key, fieldId: f.fieldId })),\n ] as Partial<T>[];\n return { mergedFields, minimalFullLengthFields };\n}\n","import { ComponentMeta } from '@plasmicapp/host';\nimport React from 'react';\nimport { DataOp } from '../executor';\nimport { usePlasmicDataOp } from '../hooks/usePlasmicDataOp';\n\nexport interface DataOpConfig {\n name?: string;\n pageIndex?: number;\n pageSize?: number;\n}\n\nexport interface FetcherProps extends DataOpConfig {\n dataOp?: DataOp;\n children?: ($queries: Record<string, any>) => React.ReactElement | null;\n queries?: Record<string, any>;\n}\n\nexport function Fetcher(props: FetcherProps): React.ReactElement | null {\n const { dataOp, children, name, pageIndex, pageSize } = props;\n const data = usePlasmicDataOp(dataOp, {\n ...(!!pageIndex &&\n !!pageSize && {\n paginate: { pageIndex, pageSize },\n }),\n });\n\n const $queries = React.useMemo(\n () => ({ ...props.queries, [name ?? 'data']: data }),\n [props.queries, name, data]\n );\n\n return children?.($queries) ?? null;\n}\n\nexport const FetcherMeta: ComponentMeta<FetcherProps> = {\n name: 'plasmic-data-source-fetcher',\n displayName: 'Data Fetcher',\n props: {\n dataOp: {\n type: 'dataSourceOp' as any,\n displayName: 'Data',\n },\n name: {\n type: 'string',\n displayName: 'Variable name',\n },\n children: {\n type: 'slot',\n renderPropParams: ['$queries'],\n },\n pageSize: {\n type: 'number',\n advanced: true,\n displayName: 'Page size',\n description: 'Only fetch in batches of this size; for pagination',\n },\n pageIndex: {\n type: 'number',\n advanced: true,\n displayName: 'Page index',\n description: '0-based index of the paginated page to fetch',\n },\n },\n importPath: '@plasmicapp/react-web/lib/data-sources',\n importName: 'Fetcher',\n alwaysAutoName: true,\n styleSections: false,\n};\n","import React from 'react';\nimport { DataOpConfig } from '../components/Fetcher';\nimport { DataOp } from '../executor';\nimport { swallow } from '../utils';\nimport { usePlasmicDataOp } from './usePlasmicDataOp';\n\nfunction usePrevious<T>(value: T | undefined): T | undefined {\n const prevValue = React.useRef<T | undefined>(undefined);\n\n React.useEffect(() => {\n prevValue.current = value;\n\n return () => {\n prevValue.current = undefined;\n };\n });\n\n return prevValue.current;\n}\n\nexport interface DependencyAwareQueryConfig extends DataOpConfig {\n $queries: Record<string, any>;\n setDollarQueries: ($queries: Record<string, any>) => void;\n getDataOp: () => DataOp;\n}\n\n/**\n * @deprecated Prefer using `usePlasmicDataOp` directly instead.\n */\nexport function useDependencyAwareQuery({\n $queries,\n getDataOp,\n setDollarQueries,\n name,\n pageIndex,\n pageSize,\n}: DependencyAwareQueryConfig) {\n const data = usePlasmicDataOp(swallow(getDataOp), {\n ...(!!pageIndex &&\n !!pageSize && {\n paginate: { pageIndex, pageSize },\n }),\n });\n const finalName = name ?? 'data';\n const prevName = usePrevious(finalName);\n React.useEffect(() => {\n if (!(finalName in $queries) || $queries[finalName] !== data) {\n const $queries2 = {\n ...$queries,\n [finalName]: data,\n };\n if (prevName && finalName !== prevName && prevName in $queries) {\n delete $queries2[prevName];\n }\n setDollarQueries($queries2);\n }\n }, [finalName, prevName, data, $queries, setDollarQueries]);\n}\n"],"names":["UNAUTHORIZED_MESSAGE","executePlasmicDataOp","_x","_x2","_executePlasmicDataOp2","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee","op","opts","func","wrap","_context","prev","next","getConfig","_executePlasmicDataOp","wrapLoadingFetcher","abrupt","sent","stop","_x3","_x4","_executePlasmicDataOp3","_callee2","_op$userArgs","host","url","resp","_context2","roleId","user","roleIds","includes","console","error","Error","sourceId","fetch","method","headers","_extends","Content-Type","userAuthToken","x-plasmic-data-user-auth-token","body","stringify","opId","userArgs","paginate","status","text","json","key","defaultValue","globalThis","_globalThis$key","makeCacheKey","dataOp","queryDependencies","JSON","args","cacheKey","mkUndefinedDataProxy","promiseRef","fetchAndUpdateCache","fetchAndUpdatePromise","undefined","Proxy","get","_target","prop","promise","fetchingPromise","plasmicType","message","String","isPlasmicUndefinedDataErrorPromise","x","reactMajorVersion","React","version","split","resolveDataOp","err","PRE_FETCHES","Map","usePlasmicDataOp","resolvedDataOp","ctx","usePlasmicDataSourceContext","enableLoadingBoundary","ph","_ph$useDataEnv","_usePlasmicDataConfig2","usePlasmicDataConfig","mutate","cache","isNullDataOp","isWaitingOnDependentQuery","fetchingData","useMemo","fetcher","has","existing","fetcherPromise","set","then","dependentKeyDataErrorPromise","cached","Promise","resolve","cachedError","reject","setTimeout","data","keyInfo","_cache$get","res","useMutablePlasmicQueryData","shouldRetryOnError","isLoading","result","obj","_len","length","keys","Array","_key","_i","_keys","pick","noUndefinedDataProxy","schema","isArrayOfObjects","arr","every","isArray","mkShortId","Math","random","props","children","name","pageIndex","pageSize","$queries","_extends2","queries","_children","displayName","type","renderPropParams","advanced","description","importPath","importName","alwaysAutoName","styleSections","specifiedFieldsPartial","makeDefaultConfig","schemaFields","_schema$fields","fields","fieldById","map","_len2","_key2","tuple","id","specifiedFieldIds","Set","f","fieldId","filter","keptSpecifiedFields","flatMap","field","newVirtualFields","mergedFields","concat","minimalFullLengthFields","rawData","dataArray","tryGetDataArray","fieldMap","_rawData$schema","forEach","entry","from","Object","entries","_ref","k","v","inferredType","_ref2","readOnly","value","prevValue","setDollarQueries","_unused","swallow","getDataOp","finalName","prevName","useRef","useEffect","current","$queries2","userToken","getRealDataOp","useCallback","_callee3","tryGetRealDataOp","_context3","_ref3","resolved","_callee4","_yield$getRealDataOp","_ref5","_context4","t0","t1"],"mappings":"wuOAMA,IAiBMA,EACJ,6HAEoBC,EAAoBC,EAAAC,GAAA,OAAAC,EAAAC,WAAAC,WASzC,SAAAF,IAAA,OAAAA,EAAAG,EAAAC,IAAAC,MATM,SAAAC,EAELC,EAAYC,GAAkB,IAAAC,EAAA,OAAAL,IAAAM,eAAAC,GAAA,cAAAA,EAAAC,KAAAD,EAAAE,MAAA,OAIG,OAH3BJ,E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uC,SAAAA,EAAUU,KAAAA,EAAMC,SAAAA,GAClB,CACEL,cAAeuK,QAAa/I,EAC5BpC,WAAM0D,SAAAA,EAAK1D,QAEd,QAAA,UAAA,OAAA8L,EAAAzM,UAAAsM,OACA,CAACP,EAAeD"}
|
package/dist/data-sources.esm.js
CHANGED
|
@@ -352,11 +352,13 @@ function _extends() {
|
|
|
352
352
|
return _extends.apply(this, arguments);
|
|
353
353
|
}
|
|
354
354
|
|
|
355
|
-
var _executePlasmicDataOp2, _executePlasmicDataOp3;
|
|
356
355
|
var DEFAULT_HOST = 'https://data.plasmic.app';
|
|
357
356
|
var UNAUTHORIZED_MESSAGE = 'You do not have permission to perform this operation. Login to get access or contact the app owner to get access.';
|
|
358
357
|
function executePlasmicDataOp(_x, _x2) {
|
|
359
|
-
return
|
|
358
|
+
return _executePlasmicDataOp2.apply(this, arguments);
|
|
359
|
+
}
|
|
360
|
+
function _executePlasmicDataOp2() {
|
|
361
|
+
_executePlasmicDataOp2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(op, opts) {
|
|
360
362
|
var func, res;
|
|
361
363
|
return _regeneratorRuntime().wrap(function _callee$(_context) {
|
|
362
364
|
while (1) switch (_context.prev = _context.next) {
|
|
@@ -372,10 +374,14 @@ function executePlasmicDataOp(_x, _x2) {
|
|
|
372
374
|
return _context.stop();
|
|
373
375
|
}
|
|
374
376
|
}, _callee);
|
|
375
|
-
}))
|
|
377
|
+
}));
|
|
378
|
+
return _executePlasmicDataOp2.apply(this, arguments);
|
|
376
379
|
}
|
|
377
380
|
function _executePlasmicDataOp(_x3, _x4) {
|
|
378
|
-
return
|
|
381
|
+
return _executePlasmicDataOp3.apply(this, arguments);
|
|
382
|
+
}
|
|
383
|
+
function _executePlasmicDataOp3() {
|
|
384
|
+
_executePlasmicDataOp3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(op, opts) {
|
|
379
385
|
var _op$userArgs;
|
|
380
386
|
var host, url, resp, text;
|
|
381
387
|
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
|
|
@@ -429,7 +435,8 @@ function _executePlasmicDataOp(_x3, _x4) {
|
|
|
429
435
|
return _context2.stop();
|
|
430
436
|
}
|
|
431
437
|
}, _callee2);
|
|
432
|
-
}))
|
|
438
|
+
}));
|
|
439
|
+
return _executePlasmicDataOp3.apply(this, arguments);
|
|
433
440
|
}
|
|
434
441
|
function getConfig(key, defaultValue) {
|
|
435
442
|
if (typeof globalThis === 'undefined') {
|
|
@@ -489,6 +496,7 @@ function makeCacheKey(dataOp, opts) {
|
|
|
489
496
|
}
|
|
490
497
|
var enableLoadingBoundaryKey = 'plasmicInternalEnableLoadingBoundary';
|
|
491
498
|
function mkUndefinedDataProxy(promiseRef, fetchAndUpdateCache) {
|
|
499
|
+
var fetchAndUpdatePromise = undefined;
|
|
492
500
|
return new Proxy({}, {
|
|
493
501
|
get: function get(_target, prop) {
|
|
494
502
|
if (prop === 'isPlasmicUndefinedDataProxy') {
|
|
@@ -502,11 +510,28 @@ function mkUndefinedDataProxy(promiseRef, fetchAndUpdateCache) {
|
|
|
502
510
|
// and trigger the usual fallback behavior
|
|
503
511
|
return undefined;
|
|
504
512
|
}
|
|
513
|
+
var doFetchAndUpdate = function doFetchAndUpdate() {
|
|
514
|
+
// We hold onto the promise last returned by fetchAndUpdateCache()
|
|
515
|
+
// and keep reusing it until it is resolved. The reason is that the
|
|
516
|
+
// Promise thrown here will be used as a dependency for memoized
|
|
517
|
+
// fetchAndUpdateCache, which is a dependency on the memoized returned value
|
|
518
|
+
// from usePlasmicDataOp(). If we have a fetch that's taking a long time,
|
|
519
|
+
// we want to make sure that our memoized returned value is stable,
|
|
520
|
+
// so that we don't keep calling setDollarQueries() (otherwise, for each
|
|
521
|
+
// render, we find an unstable result, and call setDollarQueries(),
|
|
522
|
+
// resulting in an infinite loop while fetch is happening).
|
|
523
|
+
if (!fetchAndUpdatePromise) {
|
|
524
|
+
fetchAndUpdatePromise = fetchAndUpdateCache()["finally"](function () {
|
|
525
|
+
fetchAndUpdatePromise = undefined;
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
return fetchAndUpdatePromise;
|
|
529
|
+
};
|
|
505
530
|
var promise =
|
|
506
531
|
// existing fetch
|
|
507
532
|
promiseRef.fetchingPromise ||
|
|
508
533
|
// No existing fetch, so kick off a fetch
|
|
509
|
-
|
|
534
|
+
doFetchAndUpdate();
|
|
510
535
|
promise.plasmicType = 'PlasmicUndefinedDataError';
|
|
511
536
|
promise.message = "Cannot read property " + String(prop) + " - data is still loading";
|
|
512
537
|
throw promise;
|
|
@@ -556,9 +581,9 @@ function usePlasmicDataOp(dataOp, opts) {
|
|
|
556
581
|
var resolvedDataOp = resolveDataOp(dataOp);
|
|
557
582
|
var ctx = usePlasmicDataSourceContext();
|
|
558
583
|
var enableLoadingBoundary = !!(useDataEnv != null && (_ph$useDataEnv = useDataEnv()) != null && _ph$useDataEnv[enableLoadingBoundaryKey]);
|
|
559
|
-
var
|
|
560
|
-
mutate =
|
|
561
|
-
cache =
|
|
584
|
+
var _usePlasmicDataConfig2 = usePlasmicDataConfig(),
|
|
585
|
+
mutate = _usePlasmicDataConfig2.mutate,
|
|
586
|
+
cache = _usePlasmicDataConfig2.cache;
|
|
562
587
|
// Cannot perform this operation
|
|
563
588
|
var isNullDataOp = !resolvedDataOp;
|
|
564
589
|
// This operation depends on another data query to resolve first
|
|
@@ -693,14 +718,7 @@ function usePlasmicDataOp(dataOp, opts) {
|
|
|
693
718
|
};
|
|
694
719
|
}, [fetcher, fetchingData, cache, key, dependentKeyDataErrorPromise]);
|
|
695
720
|
var res = useMutablePlasmicQueryData(key, fetcher, {
|
|
696
|
-
shouldRetryOnError: false
|
|
697
|
-
// If revalidateIfStale is true, then if there's a cache entry with a key,
|
|
698
|
-
// but no mounted hook with that key yet, and when the hook mounts with the key,
|
|
699
|
-
// swr will revalidate. This may be reasonable behavior, but for us, this
|
|
700
|
-
// happens all the time -- we prepopulate the cache with proxy-invoked fetch,
|
|
701
|
-
// sometimes before swr had a chance to run the effect. So we turn off
|
|
702
|
-
// revalidateIfStale here, and just let the user manage invalidation.
|
|
703
|
-
revalidateIfStale: false
|
|
721
|
+
shouldRetryOnError: false
|
|
704
722
|
});
|
|
705
723
|
var data = res.data,
|
|
706
724
|
error = res.error,
|
|
@@ -722,83 +740,85 @@ function usePlasmicDataOp(dataOp, opts) {
|
|
|
722
740
|
function usePlasmicDataMutationOp(dataOp) {
|
|
723
741
|
var ctx = usePlasmicDataSourceContext();
|
|
724
742
|
var userToken = ctx == null ? void 0 : ctx.userAuthToken;
|
|
725
|
-
var getRealDataOp = React.useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function
|
|
726
|
-
var _ref2;
|
|
743
|
+
var getRealDataOp = React.useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
|
|
727
744
|
var tryGetRealDataOp;
|
|
728
|
-
return _regeneratorRuntime().wrap(function
|
|
729
|
-
while (1) switch (
|
|
745
|
+
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
|
|
746
|
+
while (1) switch (_context3.prev = _context3.next) {
|
|
730
747
|
case 0:
|
|
731
|
-
tryGetRealDataOp = function
|
|
732
|
-
|
|
748
|
+
tryGetRealDataOp = /*#__PURE__*/function () {
|
|
749
|
+
var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
|
|
733
750
|
var resolved;
|
|
734
|
-
return _regeneratorRuntime().wrap(function
|
|
735
|
-
while (1) switch (
|
|
751
|
+
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
|
|
752
|
+
while (1) switch (_context2.prev = _context2.next) {
|
|
736
753
|
case 0:
|
|
737
754
|
resolved = resolveDataOp(dataOp);
|
|
738
755
|
if (resolved) {
|
|
739
|
-
|
|
756
|
+
_context2.next = 5;
|
|
740
757
|
break;
|
|
741
758
|
}
|
|
742
|
-
return
|
|
759
|
+
return _context2.abrupt("return", null);
|
|
743
760
|
case 5:
|
|
744
761
|
if (!isPlasmicUndefinedDataErrorPromise(resolved)) {
|
|
745
|
-
|
|
762
|
+
_context2.next = 11;
|
|
746
763
|
break;
|
|
747
764
|
}
|
|
748
|
-
|
|
765
|
+
_context2.next = 8;
|
|
749
766
|
return resolved;
|
|
750
767
|
case 8:
|
|
751
|
-
return
|
|
768
|
+
return _context2.abrupt("return", tryGetRealDataOp());
|
|
752
769
|
case 11:
|
|
753
|
-
return
|
|
770
|
+
return _context2.abrupt("return", resolved);
|
|
754
771
|
case 12:
|
|
755
772
|
case "end":
|
|
756
|
-
return
|
|
773
|
+
return _context2.stop();
|
|
757
774
|
}
|
|
758
|
-
},
|
|
759
|
-
}))
|
|
760
|
-
|
|
761
|
-
|
|
775
|
+
}, _callee2);
|
|
776
|
+
}));
|
|
777
|
+
return function tryGetRealDataOp() {
|
|
778
|
+
return _ref3.apply(this, arguments);
|
|
779
|
+
};
|
|
780
|
+
}();
|
|
781
|
+
_context3.next = 3;
|
|
762
782
|
return tryGetRealDataOp();
|
|
763
783
|
case 3:
|
|
764
|
-
return
|
|
784
|
+
return _context3.abrupt("return", _context3.sent);
|
|
765
785
|
case 4:
|
|
766
786
|
case "end":
|
|
767
|
-
return
|
|
787
|
+
return _context3.stop();
|
|
768
788
|
}
|
|
769
|
-
},
|
|
789
|
+
}, _callee3);
|
|
770
790
|
})), [dataOp]);
|
|
771
|
-
return React.useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function
|
|
791
|
+
return React.useCallback( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
|
|
772
792
|
var _yield$getRealDataOp;
|
|
773
|
-
var
|
|
774
|
-
return _regeneratorRuntime().wrap(function
|
|
775
|
-
while (1) switch (
|
|
793
|
+
var _ref5, sourceId, opId, userArgs;
|
|
794
|
+
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
|
|
795
|
+
while (1) switch (_context4.prev = _context4.next) {
|
|
776
796
|
case 0:
|
|
777
|
-
|
|
797
|
+
_context4.next = 2;
|
|
778
798
|
return getRealDataOp();
|
|
779
799
|
case 2:
|
|
780
|
-
|
|
781
|
-
if (!(
|
|
782
|
-
|
|
800
|
+
_context4.t0 = _yield$getRealDataOp = _context4.sent;
|
|
801
|
+
if (!(_context4.t0 != null)) {
|
|
802
|
+
_context4.next = 7;
|
|
783
803
|
break;
|
|
784
804
|
}
|
|
785
|
-
|
|
786
|
-
|
|
805
|
+
_context4.t1 = _yield$getRealDataOp;
|
|
806
|
+
_context4.next = 8;
|
|
787
807
|
break;
|
|
788
808
|
case 7:
|
|
789
|
-
|
|
809
|
+
_context4.t1 = {};
|
|
790
810
|
case 8:
|
|
791
|
-
|
|
792
|
-
sourceId =
|
|
793
|
-
opId =
|
|
794
|
-
userArgs =
|
|
811
|
+
_ref5 = _context4.t1;
|
|
812
|
+
sourceId = _ref5.sourceId;
|
|
813
|
+
opId = _ref5.opId;
|
|
814
|
+
userArgs = _ref5.userArgs;
|
|
795
815
|
if (!(!sourceId || !opId)) {
|
|
796
|
-
|
|
816
|
+
_context4.next = 14;
|
|
797
817
|
break;
|
|
798
818
|
}
|
|
799
|
-
return
|
|
819
|
+
return _context4.abrupt("return", undefined);
|
|
800
820
|
case 14:
|
|
801
|
-
return
|
|
821
|
+
return _context4.abrupt("return", executePlasmicDataOp({
|
|
802
822
|
sourceId: sourceId,
|
|
803
823
|
opId: opId,
|
|
804
824
|
userArgs: userArgs
|
|
@@ -808,9 +828,9 @@ function usePlasmicDataMutationOp(dataOp) {
|
|
|
808
828
|
}));
|
|
809
829
|
case 15:
|
|
810
830
|
case "end":
|
|
811
|
-
return
|
|
831
|
+
return _context4.stop();
|
|
812
832
|
}
|
|
813
|
-
},
|
|
833
|
+
}, _callee4);
|
|
814
834
|
})), [getRealDataOp, userToken]);
|
|
815
835
|
}
|
|
816
836
|
|