@knapsack/renderer-react 4.69.12--canary.4821.8709676.0 → 4.69.12--canary.4739.f046133.0

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.js CHANGED
@@ -727,7 +727,6 @@ var rendererMetaScriptTagId = "ks-react-meta";
727
727
  // src/renderer-react.ts
728
728
  var { pkg } = (0, import_file_utils3.findUpPkgJson)(__dirname);
729
729
  import_app2.log.setupUpdateNotifier({ ...pkg, name: pkg.name, version: pkg.version });
730
- var errorCatcherPath = (0, import_path2.join)(__dirname, "./error-catcher.mjs");
731
730
  var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer_webpack_base.RendererWebpackBase {
732
731
  static {
733
732
  __name(this, "KnapsackReactRenderer");
@@ -747,29 +746,22 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
747
746
  } = {}) {
748
747
  super({
749
748
  id,
749
+ extension: ".jsx",
750
750
  language: "jsx",
751
751
  webpackConfig,
752
752
  extraScripts: [
753
753
  // this is the code in `./client/init.mts`
754
754
  "@knapsack/renderer-react/client"
755
- ],
756
- codeSrcs: [demoWrapperPath, errorCatcherPath]
755
+ ]
757
756
  });
758
757
  this.language = "jsx";
759
758
  this.assets = [];
760
- this.demoWrapperPath = (0, import_path2.isAbsolute)(demoWrapperPath) ? demoWrapperPath : this.resolvePathSync({
761
- path: demoWrapperPath,
762
- resolveFromDir: this.userConfigDir
763
- }).absolutePath;
764
- (0, import_file_utils3.assertFileExists)(
765
- this.demoWrapperPath,
766
- `Could not find demo wrapper at: "${this.demoWrapperPath}"
767
- Please adjust setting in "knapsack.config.js" or pass a different path when creating the React Renderer.`
768
- );
759
+ this.demoWrapperPath = demoWrapperPath;
769
760
  this.disableReactStrictMode = disableReactStrictMode;
770
761
  this.creators = [createReactPattern];
771
762
  }
772
- init = /* @__PURE__ */ __name(async () => {
763
+ init = /* @__PURE__ */ __name(async (opt) => {
764
+ await super.init(opt);
773
765
  this.assets = await copyReactAssets(this.outputDir, this.publicPath);
774
766
  if (!await (0, import_file_utils3.exists)(this.demoWrapperPath)) {
775
767
  throw new Error(
@@ -815,37 +807,80 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
815
807
  };
816
808
  return config;
817
809
  }, "createWebpackConfig");
810
+ getJsImports = /* @__PURE__ */ __name(() => {
811
+ const imports = super.getJsImports();
812
+ imports.push(
813
+ {
814
+ type: "extra",
815
+ importInfo: {
816
+ type: "default",
817
+ path: this.demoWrapperPath,
818
+ name: "DemoWrapper"
819
+ }
820
+ },
821
+ {
822
+ type: "extra",
823
+ importInfo: {
824
+ type: "default",
825
+ path: (0, import_path2.join)(__dirname, "./error-catcher.mjs"),
826
+ name: "ErrorCatcher"
827
+ }
828
+ }
829
+ );
830
+ return imports;
831
+ }, "getJsImports");
818
832
  async prepClientRenderResults({
819
833
  usage,
820
834
  demoApp,
821
- importMap,
822
- renderOptions: { demo, state, patternId, templateId }
835
+ imports: xImports,
836
+ renderOptions: { pattern, template, demo }
823
837
  }) {
838
+ const extraImports = this.getJsImports().filter(
839
+ (imp) => imp.type === "extra"
840
+ );
841
+ const { imports, isDeclaredVarsUnique, nameCollisions } = this.makeKsJsImportsUnique({ imports: [...xImports, ...extraImports] });
842
+ if (!isDeclaredVarsUnique) {
843
+ import_app2.log.error(`${nameCollisions.join(", ")} are declared multiple times`, {
844
+ imports
845
+ });
846
+ }
847
+ const importInfos = imports.map(({ importInfo }) => importInfo);
824
848
  const meta = {
825
849
  demo,
850
+ moduleImports: (0, import_utils3.groupBy)(importInfos, (importInfo) => importInfo.path),
851
+ patternId: pattern.id,
852
+ templateId: template.id,
853
+ imports,
826
854
  disableReactStrictMode: this.disableReactStrictMode,
827
- neededImportsByPath: (0, import_renderer_webpack_base.convertImportMapToNeededImportsByPath)(importMap),
828
- extraImports: {
829
- DemoWrapper: {
830
- type: "default",
831
- path: this.demoWrapperPath,
832
- name: "DemoWrapper"
833
- },
834
- ErrorCatcher: {
835
- type: "default",
836
- path: errorCatcherPath,
837
- name: "ErrorCatcher"
838
- }
839
- },
840
855
  demoWrapperProps: {
841
- patternId,
842
- templateId,
843
- demo
856
+ pattern,
857
+ template,
858
+ demo,
859
+ patternsUsed: imports.flatMap((imp) => {
860
+ if (imp.type === "pattern-template") {
861
+ return [
862
+ {
863
+ patternId: imp.patternId,
864
+ templateId: imp.templateId
865
+ }
866
+ ];
867
+ }
868
+ if (imp.type === "pattern-template-demo") {
869
+ return [
870
+ {
871
+ patternId: imp.patternId,
872
+ templateId: imp.templateId,
873
+ demoId: imp.demoId
874
+ }
875
+ ];
876
+ }
877
+ return [];
878
+ })
844
879
  }
845
880
  };
846
881
  let code = `
847
882
  window.knapsack = window.knapsack || {};
848
- window.knapsack.getDemoApp = ({ ${[...importMap.keys()].join(", ")} }) => {
883
+ window.knapsack.getDemoApp = ({ ${imports.map((i) => i.importInfo.name).join(", ")} }) => {
849
884
  ${demoApp}
850
885
  return ${demoAppName}
851
886
  }
@@ -867,7 +902,7 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
867
902
  <script type="application/javascript">${code}</script>
868
903
  <div id="render-root" class="knapsack-pattern-direct-parent" data-dev-note="Knapsack React Template Wrapper"></div>
869
904
  ${this.assets.map((asset) => `<script src="${asset}"></script>`).join("\n")}
870
- ${import_renderer_webpack_base.RendererWebpackBase.createHtmlTagsForAssetPaths({
905
+ ${this.createHtmlTagsForAssetPaths({
871
906
  assets: this.getWebpackAssetPaths(),
872
907
  // we need the scripts to finish adding methods to the global knapsack object synchronously before the client-side code runs that is in the <script> tag below
873
908
  scriptTagsAreAsync: false
@@ -892,9 +927,11 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
892
927
  let attempt = 0;
893
928
  while (true) {
894
929
  try {
895
- const { absolutePath, exists } = await this.resolvePath(
896
- opt.demo.templateInfo.path
897
- );
930
+ const { absolutePath, exists } = await (0, import_file_utils3.resolvePath)({
931
+ path: opt.demo.templateInfo.path,
932
+ pkgPathAliases: this.pkgPathAliases,
933
+ resolveFromDir: this.dataDir
934
+ });
898
935
  if (!exists) {
899
936
  throw new Error(
900
937
  `Template demo file does not exist: ${absolutePath}`
@@ -911,12 +948,9 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
911
948
  await (0, import_sleep_promise.default)(waitTime);
912
949
  }
913
950
  }
914
- const [templateFileContents, { usage, importMap }] = await Promise.all([
951
+ const [templateFileContents, { usage, imports }] = await Promise.all([
915
952
  (0, import_file_utils3.readFile)(templateDemoPath),
916
- this.getUsageAndImports({
917
- ...opt,
918
- importMap: /* @__PURE__ */ new Map()
919
- })
953
+ this.getUsageAndImports(opt)
920
954
  ]);
921
955
  const demoApp = await getDemoAppUsage({
922
956
  children: usage
@@ -924,18 +958,15 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
924
958
  const results = await this.prepClientRenderResults({
925
959
  usage: templateFileContents,
926
960
  demoApp,
927
- renderOptions: opt,
928
- importMap
961
+ imports,
962
+ renderOptions: opt
929
963
  });
930
964
  return results;
931
965
  }
932
966
  if (opt.demo?.type === "data") {
933
- const { usage, importMap } = await this.getUsageAndImports({
934
- ...opt,
935
- importMap: /* @__PURE__ */ new Map()
936
- });
937
- const importCode = import_renderer_webpack_base.RendererWebpackBase.createJsImportCodeBlock({
938
- importMap
967
+ const { usage, imports } = await this.getUsageAndImports(opt);
968
+ const { code: importCode } = this.createJsImportCodeBlock({
969
+ imports
939
970
  });
940
971
  const [demoAppUsage, demoApp] = await Promise.all([
941
972
  getDemoAppUsage({
@@ -950,40 +981,32 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
950
981
  return this.prepClientRenderResults({
951
982
  demoApp,
952
983
  usage: demoAppUsage,
953
- renderOptions: opt,
954
- importMap
984
+ imports,
985
+ renderOptions: opt
955
986
  });
956
987
  }
957
988
  }, "render");
958
989
  getUsageAndImports = /* @__PURE__ */ __name(async ({
959
- patternId,
960
- templateId,
961
- demo,
962
- state,
963
- importMap
990
+ pattern,
991
+ template,
992
+ patternManifest,
993
+ demo
964
994
  }) => {
965
- if (!demo) {
966
- throw new Error(
967
- `No demo provided while rendering ${patternId} ${templateId}`
968
- );
969
- }
970
- const pattern = state.patterns[patternId];
971
- if (!pattern) {
972
- throw new Error(`Could not find pattern: ${patternId}`);
973
- }
974
- if (demo.type === "data") {
975
- const template = pattern.templates.find((t) => t.id === templateId);
976
- if (!template) {
977
- throw new Error(`Could not find template: ${templateId}`);
978
- }
995
+ if (demo?.type && demo.type === "data") {
979
996
  const {
980
997
  data: { props, slots, slotsOptionsComputed }
981
998
  } = demo;
982
- const { name: templateName } = await this.addUniqueValueToImportMap({
983
- importMap,
984
- path: template.path,
985
- alias: template.alias || "default"
999
+ const importInfo = this.getJsImport({
1000
+ patternId: pattern.id,
1001
+ templateId: template.id
986
1002
  });
1003
+ if (!importInfo) {
1004
+ throw new Error(
1005
+ `Could not find import for pattern-template: ${pattern.id}-${template.id}`
1006
+ );
1007
+ }
1008
+ const { type, name: templateName } = importInfo.importInfo;
1009
+ const importInfos = [importInfo];
987
1010
  const children = [];
988
1011
  const extraProps = [];
989
1012
  if (slots) {
@@ -993,7 +1016,6 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
993
1016
  const slotItems = slots[slotName];
994
1017
  const slotItemsUsages = await Promise.all(
995
1018
  slotItems.filter((slotItem) => {
996
- if (!slotItem) return false;
997
1019
  if (slotItem.type !== "text") {
998
1020
  if (!slotItem.patternId) return false;
999
1021
  if (!slotItem.templateId) return false;
@@ -1009,39 +1031,31 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
1009
1031
  }
1010
1032
  return slotItem.text;
1011
1033
  }
1034
+ const slotPattern = patternManifest.getPattern(
1035
+ slotItem.patternId
1036
+ );
1037
+ const slotTemplate = slotPattern.templates.find(
1038
+ (t) => t.id === slotItem.templateId
1039
+ );
1012
1040
  if (slotItem.type === "template-reference") {
1013
- const slottedTemplate = state.patterns[slotItem.patternId]?.templates.find((t) => t.id === slotItem.templateId);
1014
- if (!slottedTemplate) {
1015
- throw new Error(
1016
- `Could not find slotted template: ${slotItem.patternId} ${slotItem.templateId}`
1017
- );
1018
- }
1019
- const templateRefImport = await this.addUniqueValueToImportMap({
1020
- importMap,
1021
- path: slottedTemplate.path,
1022
- alias: slottedTemplate.alias || "default"
1041
+ const { usage: usage2, imports } = await this.getUsageAndImports({
1042
+ pattern: slotPattern,
1043
+ template: slotTemplate,
1044
+ patternManifest
1023
1045
  });
1024
- return templateRefImport.name;
1046
+ importInfos.push(...imports);
1047
+ return usage2;
1025
1048
  }
1026
1049
  if (slotItem.type === "template-demo") {
1027
- const thisDemo = slotItem.demo;
1028
- if (!thisDemo) {
1029
- throw new Error(
1030
- `Could not find slotted template demo ${JSON.stringify(
1031
- slotItem
1032
- )}`
1033
- );
1034
- }
1035
- const { usage: usage2 } = await this.getUsageAndImports({
1036
- patternId: thisDemo.patternId,
1037
- templateId: thisDemo.templateId,
1038
- demo: thisDemo,
1039
- state,
1040
- importMap
1050
+ const { usage: usage2, imports } = await this.getUsageAndImports({
1051
+ pattern: slotPattern,
1052
+ template: slotTemplate,
1053
+ demo: slotItem.demo || this.patterns.demosById[slotItem.demoId],
1054
+ patternManifest
1041
1055
  });
1056
+ importInfos.push(...imports);
1042
1057
  return usage2;
1043
1058
  }
1044
- const _exhaustiveCheck2 = slotItem;
1045
1059
  throw new Error(
1046
1060
  `Unknown slot item: ${JSON.stringify(slotItem)}`
1047
1061
  );
@@ -1100,25 +1114,50 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
1100
1114
  });
1101
1115
  return {
1102
1116
  usage,
1103
- importMap
1117
+ imports: importInfos
1104
1118
  };
1105
1119
  }
1106
- if (demo.type === "template") {
1107
- const { templateInfo } = demo;
1108
- const { name: templateName } = await this.addUniqueValueToImportMap({
1109
- importMap,
1110
- path: templateInfo.path,
1111
- alias: templateInfo.alias || "default"
1120
+ if (demo?.type && demo.type === "template") {
1121
+ const importInfo = this.getJsImport({
1122
+ patternId: pattern.id,
1123
+ templateId: template.id,
1124
+ demoId: demo.id
1112
1125
  });
1126
+ if (!importInfo) {
1127
+ throw new Error(
1128
+ `Could not find import for pattern-template-demo: ${pattern.id}-${template.id}-${demo.id}`
1129
+ );
1130
+ }
1131
+ const { type, name: templateName } = importInfo.importInfo;
1113
1132
  const usage = await getUsage({ templateName });
1114
1133
  return {
1115
1134
  usage,
1116
- importMap
1135
+ imports: [importInfo]
1136
+ };
1137
+ }
1138
+ if (!demo) {
1139
+ const importInfo = this.getJsImport({
1140
+ patternId: pattern.id,
1141
+ templateId: template.id
1142
+ });
1143
+ if (!importInfo) {
1144
+ throw new Error(
1145
+ `Could not find import for pattern-template: ${pattern.id}-${template.id}`
1146
+ );
1147
+ }
1148
+ const { type, name: templateName } = importInfo.importInfo;
1149
+ return {
1150
+ /**
1151
+ * i.e. Given a React Component, `Button`, normally this would be `<Button>` with a demo, but since there is none this will just be a reference to it: `Button`
1152
+ * @see {KsSlotInfo['isTemplateReference']}
1153
+ * @see {SlottedTemplate}
1154
+ */
1155
+ usage: templateName,
1156
+ imports: [importInfo]
1117
1157
  };
1118
1158
  }
1119
- const _exhaustiveCheck = demo;
1120
1159
  throw new Error(
1121
- `Unhandled demo type for ${patternId}-${templateId}: ${JSON.stringify(
1160
+ `Unhandled demo type for ${pattern.id}-${template.id}: ${JSON.stringify(
1122
1161
  demo
1123
1162
  )}`
1124
1163
  );
@@ -1141,8 +1180,8 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
1141
1180
  }
1142
1181
  return spec;
1143
1182
  }, "inferSpec");
1144
- watch = /* @__PURE__ */ __name(async () => {
1145
- super.watch();
1183
+ watch = /* @__PURE__ */ __name(async (opt) => {
1184
+ super.watch(opt);
1146
1185
  import_app2.knapsackEvents.onPatternTemplateChanged(() => {
1147
1186
  clearInferSpecCache();
1148
1187
  });
@@ -1220,31 +1259,21 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
1220
1259
  ];
1221
1260
  }, "alterTemplateMetaFiles");
1222
1261
  getTemplateSuggestions = /* @__PURE__ */ __name(async ({
1223
- newPath,
1224
- state
1262
+ newPath
1225
1263
  }) => {
1226
- const usedSuggestions = Object.values(state.patterns).reduce(
1227
- (acc, { templateDemos, templates }) => {
1228
- templates.forEach(({ path: path2, alias, templateLanguageId }) => {
1229
- if (templateLanguageId !== this.id) return;
1230
- acc.push({ path: path2, alias });
1231
- });
1232
- templateDemos.forEach(
1233
- ({ templateInfo: { path: path2, alias }, templateLanguageId }) => {
1234
- if (templateLanguageId !== this.id) return;
1235
- acc.push({ path: path2, alias });
1236
- }
1237
- );
1238
- return acc;
1239
- },
1240
- []
1241
- );
1264
+ const { data: dataDir } = this.patterns.userConfig;
1265
+ const { allTemplateDemos, allTemplates } = this.getMyTemplates();
1266
+ const usedSuggestions = [
1267
+ ...allTemplateDemos,
1268
+ ...allTemplates
1269
+ ].map(({ path: path2, alias }) => {
1270
+ return {
1271
+ path: path2,
1272
+ alias: alias || "default"
1273
+ };
1274
+ });
1242
1275
  const allPaths = [
1243
- .../* @__PURE__ */ new Set([
1244
- newPath,
1245
- ...Object.keys(this.pkgPathAliases || {}),
1246
- ...this.getCodeSrcs()
1247
- ])
1276
+ .../* @__PURE__ */ new Set([newPath, ...usedSuggestions.map(({ path: path2 }) => path2)])
1248
1277
  ];
1249
1278
  const allSuggestions = await Promise.all(
1250
1279
  allPaths.map(async (path2) => {
@@ -1252,7 +1281,7 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
1252
1281
  try {
1253
1282
  const { exports: exports2, errorMsg } = await (0, import_file_utils3.getJsExportNames)({
1254
1283
  path: path2,
1255
- resolveFromDir: this.dataDir,
1284
+ resolveFromDir: dataDir,
1256
1285
  pkgPathAliases: this.pkgPathAliases
1257
1286
  });
1258
1287
  if (errorMsg) {