@plasmicapp/data-sources 0.1.209 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -49,13 +49,6 @@ import * as React3 from "react";
49
49
  // src/utils.ts
50
50
  function noopFn() {
51
51
  }
52
- function swallow(f) {
53
- try {
54
- return f();
55
- } catch (e) {
56
- return void 0;
57
- }
58
- }
59
52
  function pick(obj, ...keys) {
60
53
  const res = {};
61
54
  for (const key of keys) {
@@ -394,16 +387,29 @@ var StatefulQueryResult = class {
394
387
  }
395
388
  };
396
389
  function safeExec(tryData, ifUndefined, ifError) {
390
+ const result = safeExecResult(tryData);
391
+ if ("promise" in result) {
392
+ return ifUndefined(result.promise);
393
+ } else if ("error" in result) {
394
+ return ifError(result.error);
395
+ } else {
396
+ return result.data;
397
+ }
398
+ }
399
+ function safeExecResult(tryData) {
397
400
  try {
398
- return tryData();
401
+ return { data: tryData() };
399
402
  } catch (err) {
400
403
  if (isPlasmicUndefinedDataErrorPromise(err)) {
401
- return ifUndefined(err);
404
+ return { promise: err };
402
405
  } else {
403
- return ifError(err);
406
+ return { error: err };
404
407
  }
405
408
  }
406
409
  }
410
+ function assertUnexpectedNodeType(x) {
411
+ throw new Error(`Unexpected node type: ${x}`);
412
+ }
407
413
  function resolveParams(params) {
408
414
  return safeExec(
409
415
  () => ({
@@ -484,6 +490,19 @@ var SyncPromise = class {
484
490
  );
485
491
  }
486
492
  };
493
+ function shallowEqualRecords(a, b) {
494
+ if (Object.is(a, b)) {
495
+ return true;
496
+ }
497
+ const aKeys = Object.keys(a);
498
+ const bKeys = Object.keys(b);
499
+ if (aKeys.length !== bKeys.length) {
500
+ return false;
501
+ }
502
+ return aKeys.every(
503
+ (key) => Object.prototype.hasOwnProperty.call(b, key) && Object.is(a[key], b[key])
504
+ );
505
+ }
487
506
  var SettablePromise = class {
488
507
  constructor() {
489
508
  this.promise = new Promise((resolve, reject) => {
@@ -579,7 +598,31 @@ function sortObjectsDeep(value, visitedObjects) {
579
598
 
580
599
  // src/serverQueries/client.ts
581
600
  var GLOBAL_CACHE = /* @__PURE__ */ new Map();
582
- function usePlasmicQueries($queries, queries) {
601
+ function usePlasmicQueries(tree, $props, $ctx, $state) {
602
+ const stableProps = useShallowStableRecord($props);
603
+ const stableCtx = useShallowStableRecord($ctx);
604
+ const $stateRef = React3.useRef($state != null ? $state : {});
605
+ $stateRef.current = $state != null ? $state : {};
606
+ const $queries = React3.useMemo(
607
+ () => createDollarQueries(Object.keys(tree.queries)),
608
+ [tree]
609
+ );
610
+ const queries = React3.useMemo(() => {
611
+ return mapRecords(
612
+ (_name, q) => ({
613
+ id: q.id,
614
+ fn: q.fn,
615
+ execParams: () => q.args({
616
+ $q: $queries,
617
+ $props: stableProps,
618
+ $ctx: stableCtx,
619
+ $state: $stateRef.current,
620
+ $scopedItemVars: {}
621
+ })
622
+ }),
623
+ tree.queries
624
+ );
625
+ }, [$queries, stableCtx, stableProps, tree]);
583
626
  const wrappedQueries = React3.useMemo(() => wrapQueries(queries), [queries]);
584
627
  const $queryStates = $queries;
585
628
  const { fallback: prefetchedCache, cache: swrCache } = usePlasmicDataConfig2();
@@ -646,13 +689,14 @@ function usePlasmicQueries($queries, queries) {
646
689
  },
647
690
  [wrappedQueries, $queryStates, settledCount]
648
691
  );
649
- return mapRecords(
692
+ mapRecords(
650
693
  (_queryName, $query, query) => {
651
- return usePlasmicQuery($query, query, settledCount);
694
+ usePlasmicQuery($query, query, settledCount);
652
695
  },
653
696
  $queryStates,
654
697
  wrappedQueries
655
698
  );
699
+ return $queries;
656
700
  }
657
701
  function wrapQueries(queries) {
658
702
  return mapRecords((_queryName, query) => {
@@ -777,24 +821,261 @@ function usePlasmicQuery($query, query, settledCount) {
777
821
  }
778
822
  return result;
779
823
  }
824
+ function useShallowStableRecord(value) {
825
+ const ref = React3.useRef(value);
826
+ if (!shallowEqualRecords(ref.current, value)) {
827
+ ref.current = value;
828
+ }
829
+ return ref.current;
830
+ }
780
831
 
781
832
  // src/serverQueries/server.ts
782
- function executePlasmicQueries($queries, queries) {
783
- return __async(this, null, function* () {
784
- const doneQueryResults = yield Promise.all(
785
- mapRecordEntries(
786
- (_queryName, $query, query) => {
787
- return executePlasmicQuery($query, query);
788
- },
789
- $queries,
790
- queries
791
- )
833
+ var ROOT_COMPONENT_KEY_PATH = "root";
834
+ function appendKeyPath(currentKeyPath, currentInput) {
835
+ return currentKeyPath ? `${currentKeyPath}/${currentInput}` : currentInput;
836
+ }
837
+ function executeQueryTree(rootNode, options, queriesByComponent) {
838
+ const { $props, $ctx } = options;
839
+ const initialContext = {
840
+ $props,
841
+ $ctx,
842
+ $state: {},
843
+ $q: {},
844
+ $scopedItemVars: {}
845
+ };
846
+ return executeComponentNode(rootNode, {
847
+ context: initialContext,
848
+ parentKeyPath: "",
849
+ childIndex: 0,
850
+ queriesByComponent
851
+ });
852
+ }
853
+ function executeNode(node, params) {
854
+ const p = { node, params, type: node.type };
855
+ switch (p.type) {
856
+ case "component":
857
+ return executeComponentNode(p.node, p.params);
858
+ case "codeComponent":
859
+ return executeCodeComponentNode(p.node, p.params);
860
+ case "dataProvider":
861
+ return executeDataProviderNode(p.node, p.params);
862
+ case "visibility":
863
+ return executeVisibilityNode(p.node, p.params);
864
+ case "repeated":
865
+ return executeRepeatedNode(p.node, p.params);
866
+ default:
867
+ assertUnexpectedNodeType(p);
868
+ }
869
+ }
870
+ function executeComponentNode(node, params) {
871
+ const {
872
+ context: parentContext,
873
+ parentKeyPath,
874
+ childIndex,
875
+ queriesByComponent
876
+ } = params;
877
+ const isRoot = parentKeyPath === "";
878
+ let componentKeyPath;
879
+ let evaluatedProps;
880
+ if (isRoot) {
881
+ componentKeyPath = ROOT_COMPONENT_KEY_PATH;
882
+ evaluatedProps = parentContext.$props;
883
+ } else {
884
+ componentKeyPath = appendKeyPath(parentKeyPath, `c${childIndex}`);
885
+ evaluatedProps = {};
886
+ for (const [propName, propFn] of Object.entries(node.propsContext)) {
887
+ const result = safeExecResult(() => propFn(parentContext));
888
+ if (!("data" in result)) {
889
+ return [];
890
+ }
891
+ evaluatedProps[propName] = result.data;
892
+ }
893
+ }
894
+ let componentQueries = queriesByComponent.get(componentKeyPath);
895
+ if (!componentQueries) {
896
+ componentQueries = {};
897
+ queriesByComponent.set(componentKeyPath, componentQueries);
898
+ }
899
+ const componentContext = {
900
+ $props: evaluatedProps,
901
+ $ctx: parentContext.$ctx,
902
+ $state: parentContext.$state,
903
+ $q: componentQueries,
904
+ $scopedItemVars: parentContext.$scopedItemVars
905
+ };
906
+ const discovered = [];
907
+ for (const [queryName, query] of Object.entries(node.queries)) {
908
+ if (componentQueries[queryName]) {
909
+ continue;
910
+ }
911
+ const $query = new StatefulQueryResult();
912
+ componentQueries[queryName] = $query;
913
+ const capturedContext = componentContext;
914
+ const capturedArgsFn = query.args;
915
+ const plasmicQuery = {
916
+ id: query.id,
917
+ fn: query.fn,
918
+ execParams: () => capturedArgsFn(capturedContext)
919
+ };
920
+ discovered.push({ $query, query: plasmicQuery });
921
+ }
922
+ node.children.forEach((child, idx) => {
923
+ discovered.push(
924
+ ...executeNode(child, {
925
+ context: componentContext,
926
+ parentKeyPath: componentKeyPath,
927
+ childIndex: idx,
928
+ queriesByComponent
929
+ })
792
930
  );
793
- return Object.fromEntries(
794
- Object.values(doneQueryResults).map(($query) => [$query.key, $query.data])
931
+ });
932
+ return discovered;
933
+ }
934
+ function executeCodeComponentNode(node, params) {
935
+ if (node.serverRenderingConfig === false) {
936
+ return [];
937
+ }
938
+ const { context, parentKeyPath, childIndex, queriesByComponent } = params;
939
+ const nodeKeyPath = appendKeyPath(parentKeyPath, `cc${childIndex}`);
940
+ const evaluatedProps = {};
941
+ for (const [propName, propFn] of Object.entries(node.propsContext)) {
942
+ const result = safeExecResult(() => propFn(context));
943
+ if ("data" in result) {
944
+ evaluatedProps[propName] = result.data;
945
+ } else {
946
+ return [];
947
+ }
948
+ }
949
+ const childContext = {
950
+ $props: evaluatedProps,
951
+ $ctx: context.$ctx,
952
+ $state: context.$state,
953
+ $q: context.$q,
954
+ $scopedItemVars: context.$scopedItemVars
955
+ };
956
+ return node.children.flatMap(
957
+ (child, idx) => executeNode(child, {
958
+ context: childContext,
959
+ parentKeyPath: nodeKeyPath,
960
+ childIndex: idx,
961
+ queriesByComponent
962
+ })
963
+ );
964
+ }
965
+ function executeDataProviderNode(node, params) {
966
+ const { context, parentKeyPath, childIndex, queriesByComponent } = params;
967
+ const nodeKeyPath = appendKeyPath(parentKeyPath, `dp${childIndex}`);
968
+ const dataResult = safeExecResult(() => node.data(context));
969
+ if (!("data" in dataResult)) {
970
+ return [];
971
+ }
972
+ const childContext = {
973
+ $props: context.$props,
974
+ $ctx: __spreadProps(__spreadValues({}, context.$ctx), {
975
+ [node.name]: dataResult.data
976
+ }),
977
+ $state: context.$state,
978
+ $q: context.$q,
979
+ $scopedItemVars: context.$scopedItemVars
980
+ };
981
+ return node.children.flatMap(
982
+ (child, idx) => executeNode(child, {
983
+ context: childContext,
984
+ parentKeyPath: nodeKeyPath,
985
+ childIndex: idx,
986
+ queriesByComponent
987
+ })
988
+ );
989
+ }
990
+ function executeVisibilityNode(node, params) {
991
+ const { context, parentKeyPath, childIndex, queriesByComponent } = params;
992
+ const nodeKeyPath = appendKeyPath(parentKeyPath, `v${childIndex}`);
993
+ const visibilityResult = safeExecResult(() => node.visibilityExpr(context));
994
+ if (!("data" in visibilityResult) || !visibilityResult.data) {
995
+ return [];
996
+ }
997
+ return node.children.flatMap(
998
+ (child, idx) => executeNode(child, {
999
+ context,
1000
+ parentKeyPath: nodeKeyPath,
1001
+ childIndex: idx,
1002
+ queriesByComponent
1003
+ })
1004
+ );
1005
+ }
1006
+ function executeRepeatedNode(node, params) {
1007
+ const { context, parentKeyPath, childIndex, queriesByComponent } = params;
1008
+ const nodeKeyPath = appendKeyPath(parentKeyPath, `r${childIndex}`);
1009
+ const collectionResult = safeExecResult(() => node.collectionExpr(context));
1010
+ if (!("data" in collectionResult) || !Array.isArray(collectionResult.data)) {
1011
+ return [];
1012
+ }
1013
+ return collectionResult.data.flatMap((item, index) => {
1014
+ const itemContext = {
1015
+ $props: context.$props,
1016
+ $ctx: context.$ctx,
1017
+ $state: context.$state,
1018
+ $q: context.$q,
1019
+ $scopedItemVars: __spreadProps(__spreadValues({}, context.$scopedItemVars), {
1020
+ [node.itemName]: item,
1021
+ [node.indexName]: index
1022
+ })
1023
+ };
1024
+ const itemKeyPath = appendKeyPath(nodeKeyPath, `i${index}`);
1025
+ return node.children.flatMap(
1026
+ (child, idx) => executeNode(child, {
1027
+ context: itemContext,
1028
+ parentKeyPath: itemKeyPath,
1029
+ childIndex: idx,
1030
+ queriesByComponent
1031
+ })
795
1032
  );
796
1033
  });
797
1034
  }
1035
+ function executePlasmicQueries(rootNode, options) {
1036
+ return __async(this, null, function* () {
1037
+ const queriesByComponent = /* @__PURE__ */ new Map();
1038
+ const discoveredQueries = [];
1039
+ while (true) {
1040
+ const newQueries = executeQueryTree(rootNode, options, queriesByComponent);
1041
+ if (newQueries.length === 0) {
1042
+ break;
1043
+ }
1044
+ discoveredQueries.push(...newQueries);
1045
+ yield Promise.all(
1046
+ newQueries.map(
1047
+ (d) => executePlasmicQuery(d.$query, d.query).catch(() => {
1048
+ })
1049
+ )
1050
+ );
1051
+ }
1052
+ const cache = {};
1053
+ for (const d of discoveredQueries) {
1054
+ if ("data" in d.$query.current) {
1055
+ cache[d.$query.current.key] = d.$query.current.data;
1056
+ }
1057
+ }
1058
+ const queries = {};
1059
+ const rootQueries = queriesByComponent.get(ROOT_COMPONENT_KEY_PATH);
1060
+ if (rootQueries) {
1061
+ for (const [name, $query] of Object.entries(rootQueries)) {
1062
+ if ("data" in $query.current) {
1063
+ queries[name] = {
1064
+ key: $query.key,
1065
+ data: $query.current.data,
1066
+ isLoading: false
1067
+ };
1068
+ }
1069
+ }
1070
+ }
1071
+ for (const d of discoveredQueries) {
1072
+ if ("error" in d.$query.current) {
1073
+ throw d.$query.current.error;
1074
+ }
1075
+ }
1076
+ return { cache, queries };
1077
+ });
1078
+ }
798
1079
  function executePlasmicQuery($query, query) {
799
1080
  return __async(this, null, function* () {
800
1081
  if ($query.current.state === "loading" || $query.current.state === "done") {
@@ -1212,44 +1493,6 @@ function deriveFieldConfigs(specifiedFieldsPartial, schema, makeDefaultConfig) {
1212
1493
  ];
1213
1494
  return { mergedFields, minimalFullLengthFields };
1214
1495
  }
1215
-
1216
- // src/hooks/useDependencyAwareQuery.tsx
1217
- import React6 from "react";
1218
- function usePrevious(value) {
1219
- const prevValue = React6.useRef(void 0);
1220
- React6.useEffect(() => {
1221
- prevValue.current = value;
1222
- return () => {
1223
- prevValue.current = void 0;
1224
- };
1225
- });
1226
- return prevValue.current;
1227
- }
1228
- function useDependencyAwareQuery({
1229
- $queries,
1230
- getDataOp,
1231
- setDollarQueries,
1232
- name,
1233
- pageIndex,
1234
- pageSize
1235
- }) {
1236
- const data = usePlasmicDataOp(swallow(getDataOp), __spreadValues({}, !!pageIndex && !!pageSize && {
1237
- paginate: { pageIndex, pageSize }
1238
- }));
1239
- const finalName = name != null ? name : "data";
1240
- const prevName = usePrevious(finalName);
1241
- React6.useEffect(() => {
1242
- if (!(finalName in $queries) || $queries[finalName] !== data) {
1243
- const $queries2 = __spreadProps(__spreadValues({}, $queries), {
1244
- [finalName]: data
1245
- });
1246
- if (prevName && finalName !== prevName && prevName in $queries) {
1247
- delete $queries2[prevName];
1248
- }
1249
- setDollarQueries($queries2);
1250
- }
1251
- }, [finalName, prevName, data, $queries, setDollarQueries]);
1252
- }
1253
1496
  export {
1254
1497
  Fetcher,
1255
1498
  FetcherMeta,
@@ -1259,11 +1502,9 @@ export {
1259
1502
  makeCacheKey,
1260
1503
  makeQueryCacheKey,
1261
1504
  normalizeData,
1262
- createDollarQueries as unstable_createDollarQueries,
1263
1505
  executePlasmicQueries as unstable_executePlasmicQueries,
1264
1506
  usePlasmicQueries as unstable_usePlasmicQueries,
1265
1507
  wrapDollarQueriesForMetadata as unstable_wrapDollarQueriesForMetadata,
1266
- useDependencyAwareQuery,
1267
1508
  useNormalizedData,
1268
1509
  usePlasmicDataConfig4 as usePlasmicDataConfig,
1269
1510
  usePlasmicDataMutationOp,