@knapsack/renderer-react 4.69.14--canary.4821.246c5f4.0 → 4.69.15--canary.4433.ca0920f.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,76 @@ 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
+ }
824
847
  const meta = {
825
848
  demo,
826
849
  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
- },
850
+ neededImports: imports,
840
851
  demoWrapperProps: {
841
- patternId,
842
- templateId,
843
- demo
852
+ pattern,
853
+ template,
854
+ demo,
855
+ patternsUsed: imports.flatMap((imp) => {
856
+ if (imp.type === "pattern-template") {
857
+ return [
858
+ {
859
+ patternId: imp.patternId,
860
+ templateId: imp.templateId
861
+ }
862
+ ];
863
+ }
864
+ if (imp.type === "pattern-template-demo") {
865
+ return [
866
+ {
867
+ patternId: imp.patternId,
868
+ templateId: imp.templateId,
869
+ demoId: imp.demoId
870
+ }
871
+ ];
872
+ }
873
+ return [];
874
+ })
844
875
  }
845
876
  };
846
877
  let code = `
847
878
  window.knapsack = window.knapsack || {};
848
- window.knapsack.getDemoApp = ({ ${[...importMap.keys()].join(", ")} }) => {
879
+ window.knapsack.getDemoApp = ({ ${imports.map((i) => i.importInfo.name).join(", ")} }) => {
849
880
  ${demoApp}
850
881
  return ${demoAppName}
851
882
  }
@@ -867,7 +898,7 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
867
898
  <script type="application/javascript">${code}</script>
868
899
  <div id="render-root" class="knapsack-pattern-direct-parent" data-dev-note="Knapsack React Template Wrapper"></div>
869
900
  ${this.assets.map((asset) => `<script src="${asset}"></script>`).join("\n")}
870
- ${import_renderer_webpack_base.RendererWebpackBase.createHtmlTagsForAssetPaths({
901
+ ${this.createHtmlTagsForAssetPaths({
871
902
  assets: this.getWebpackAssetPaths(),
872
903
  // 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
904
  scriptTagsAreAsync: false
@@ -911,12 +942,9 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
911
942
  await (0, import_sleep_promise.default)(waitTime);
912
943
  }
913
944
  }
914
- const [templateFileContents, { usage, importMap }] = await Promise.all([
945
+ const [templateFileContents, { usage, imports }] = await Promise.all([
915
946
  (0, import_file_utils3.readFile)(templateDemoPath),
916
- this.getUsageAndImports({
917
- ...opt,
918
- importMap: /* @__PURE__ */ new Map()
919
- })
947
+ this.getUsageAndImports(opt)
920
948
  ]);
921
949
  const demoApp = await getDemoAppUsage({
922
950
  children: usage
@@ -924,18 +952,15 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
924
952
  const results = await this.prepClientRenderResults({
925
953
  usage: templateFileContents,
926
954
  demoApp,
927
- renderOptions: opt,
928
- importMap
955
+ imports,
956
+ renderOptions: opt
929
957
  });
930
958
  return results;
931
959
  }
932
960
  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
961
+ const { usage, imports } = await this.getUsageAndImports(opt);
962
+ const { code: importCode } = this.createJsImportCodeBlock({
963
+ imports
939
964
  });
940
965
  const [demoAppUsage, demoApp] = await Promise.all([
941
966
  getDemoAppUsage({
@@ -950,40 +975,32 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
950
975
  return this.prepClientRenderResults({
951
976
  demoApp,
952
977
  usage: demoAppUsage,
953
- renderOptions: opt,
954
- importMap
978
+ imports,
979
+ renderOptions: opt
955
980
  });
956
981
  }
957
982
  }, "render");
958
983
  getUsageAndImports = /* @__PURE__ */ __name(async ({
959
- patternId,
960
- templateId,
961
- demo,
962
- state,
963
- importMap
984
+ pattern,
985
+ template,
986
+ patternManifest,
987
+ demo
964
988
  }) => {
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
- }
989
+ if (demo?.type && demo.type === "data") {
979
990
  const {
980
991
  data: { props, slots, slotsOptionsComputed }
981
992
  } = demo;
982
- const { name: templateName } = await this.addUniqueValueToImportMap({
983
- importMap,
984
- path: template.path,
985
- alias: template.alias || "default"
993
+ const importInfo = this.getJsImport({
994
+ patternId: pattern.id,
995
+ templateId: template.id
986
996
  });
997
+ if (!importInfo) {
998
+ throw new Error(
999
+ `Could not find import for pattern-template: ${pattern.id}-${template.id}`
1000
+ );
1001
+ }
1002
+ const { type, name: templateName } = importInfo.importInfo;
1003
+ const importInfos = [importInfo];
987
1004
  const children = [];
988
1005
  const extraProps = [];
989
1006
  if (slots) {
@@ -993,7 +1010,6 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
993
1010
  const slotItems = slots[slotName];
994
1011
  const slotItemsUsages = await Promise.all(
995
1012
  slotItems.filter((slotItem) => {
996
- if (!slotItem) return false;
997
1013
  if (slotItem.type !== "text") {
998
1014
  if (!slotItem.patternId) return false;
999
1015
  if (!slotItem.templateId) return false;
@@ -1009,39 +1025,31 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
1009
1025
  }
1010
1026
  return slotItem.text;
1011
1027
  }
1028
+ const slotPattern = patternManifest.getPattern(
1029
+ slotItem.patternId
1030
+ );
1031
+ const slotTemplate = slotPattern.templates.find(
1032
+ (t) => t.id === slotItem.templateId
1033
+ );
1012
1034
  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"
1035
+ const { usage: usage2, imports } = await this.getUsageAndImports({
1036
+ pattern: slotPattern,
1037
+ template: slotTemplate,
1038
+ patternManifest
1023
1039
  });
1024
- return templateRefImport.name;
1040
+ importInfos.push(...imports);
1041
+ return usage2;
1025
1042
  }
1026
1043
  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
1044
+ const { usage: usage2, imports } = await this.getUsageAndImports({
1045
+ pattern: slotPattern,
1046
+ template: slotTemplate,
1047
+ demo: slotItem.demo || this.patterns.demosById[slotItem.demoId],
1048
+ patternManifest
1041
1049
  });
1050
+ importInfos.push(...imports);
1042
1051
  return usage2;
1043
1052
  }
1044
- const _exhaustiveCheck2 = slotItem;
1045
1053
  throw new Error(
1046
1054
  `Unknown slot item: ${JSON.stringify(slotItem)}`
1047
1055
  );
@@ -1100,25 +1108,50 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
1100
1108
  });
1101
1109
  return {
1102
1110
  usage,
1103
- importMap
1111
+ imports: importInfos
1104
1112
  };
1105
1113
  }
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"
1114
+ if (demo?.type && demo.type === "template") {
1115
+ const importInfo = this.getJsImport({
1116
+ patternId: pattern.id,
1117
+ templateId: template.id,
1118
+ demoId: demo.id
1112
1119
  });
1120
+ if (!importInfo) {
1121
+ throw new Error(
1122
+ `Could not find import for pattern-template-demo: ${pattern.id}-${template.id}-${demo.id}`
1123
+ );
1124
+ }
1125
+ const { type, name: templateName } = importInfo.importInfo;
1113
1126
  const usage = await getUsage({ templateName });
1114
1127
  return {
1115
1128
  usage,
1116
- importMap
1129
+ imports: [importInfo]
1130
+ };
1131
+ }
1132
+ if (!demo) {
1133
+ const importInfo = this.getJsImport({
1134
+ patternId: pattern.id,
1135
+ templateId: template.id
1136
+ });
1137
+ if (!importInfo) {
1138
+ throw new Error(
1139
+ `Could not find import for pattern-template: ${pattern.id}-${template.id}`
1140
+ );
1141
+ }
1142
+ const { type, name: templateName } = importInfo.importInfo;
1143
+ return {
1144
+ /**
1145
+ * 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`
1146
+ * @see {KsSlotInfo['isTemplateReference']}
1147
+ * @see {SlottedTemplate}
1148
+ */
1149
+ usage: templateName,
1150
+ imports: [importInfo]
1117
1151
  };
1118
1152
  }
1119
- const _exhaustiveCheck = demo;
1120
1153
  throw new Error(
1121
- `Unhandled demo type for ${patternId}-${templateId}: ${JSON.stringify(
1154
+ `Unhandled demo type for ${pattern.id}-${template.id}: ${JSON.stringify(
1122
1155
  demo
1123
1156
  )}`
1124
1157
  );
@@ -1141,8 +1174,8 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
1141
1174
  }
1142
1175
  return spec;
1143
1176
  }, "inferSpec");
1144
- watch = /* @__PURE__ */ __name(async () => {
1145
- super.watch();
1177
+ watch = /* @__PURE__ */ __name(async (opt) => {
1178
+ super.watch(opt);
1146
1179
  import_app2.knapsackEvents.onPatternTemplateChanged(() => {
1147
1180
  clearInferSpecCache();
1148
1181
  });
@@ -1220,34 +1253,21 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
1220
1253
  ];
1221
1254
  }, "alterTemplateMetaFiles");
1222
1255
  getTemplateSuggestions = /* @__PURE__ */ __name(async ({
1223
- newPath,
1224
- state
1256
+ newPath
1225
1257
  }) => {
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
- );
1242
- const codeSrcs = new Set(this.getCodeSrcs());
1243
- codeSrcs.delete(this.demoWrapperPath);
1244
- codeSrcs.delete(errorCatcherPath);
1258
+ const { data: dataDir } = this.patterns.userConfig;
1259
+ const { allTemplateDemos, allTemplates } = this.getMyTemplates();
1260
+ const usedSuggestions = [
1261
+ ...allTemplateDemos,
1262
+ ...allTemplates
1263
+ ].map(({ path: path2, alias }) => {
1264
+ return {
1265
+ path: path2,
1266
+ alias: alias || "default"
1267
+ };
1268
+ });
1245
1269
  const allPaths = [
1246
- .../* @__PURE__ */ new Set([
1247
- newPath,
1248
- ...Object.keys(this.pkgPathAliases || {}),
1249
- ...codeSrcs
1250
- ])
1270
+ .../* @__PURE__ */ new Set([newPath, ...usedSuggestions.map(({ path: path2 }) => path2)])
1251
1271
  ];
1252
1272
  const allSuggestions = await Promise.all(
1253
1273
  allPaths.map(async (path2) => {
@@ -1255,7 +1275,7 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
1255
1275
  try {
1256
1276
  const { exports: exports2, errorMsg } = await (0, import_file_utils3.getJsExportNames)({
1257
1277
  path: path2,
1258
- resolveFromDir: this.dataDir,
1278
+ resolveFromDir: dataDir,
1259
1279
  pkgPathAliases: this.pkgPathAliases
1260
1280
  });
1261
1281
  if (errorMsg) {