@knapsack/renderer-react 4.69.13--canary.4739.37477c8.0 → 4.69.13--canary.4821.022ca72.0

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.js CHANGED
@@ -727,6 +727,7 @@ 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");
730
731
  var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer_webpack_base.RendererWebpackBase {
731
732
  static {
732
733
  __name(this, "KnapsackReactRenderer");
@@ -746,22 +747,29 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
746
747
  } = {}) {
747
748
  super({
748
749
  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
- ]
755
+ ],
756
+ codeSrcs: [demoWrapperPath, errorCatcherPath]
756
757
  });
757
758
  this.language = "jsx";
758
759
  this.assets = [];
759
- this.demoWrapperPath = demoWrapperPath;
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
+ );
760
769
  this.disableReactStrictMode = disableReactStrictMode;
761
770
  this.creators = [createReactPattern];
762
771
  }
763
- init = /* @__PURE__ */ __name(async (opt) => {
764
- await super.init(opt);
772
+ init = /* @__PURE__ */ __name(async () => {
765
773
  this.assets = await copyReactAssets(this.outputDir, this.publicPath);
766
774
  if (!await (0, import_file_utils3.exists)(this.demoWrapperPath)) {
767
775
  throw new Error(
@@ -807,80 +815,37 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
807
815
  };
808
816
  return config;
809
817
  }, "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");
832
818
  async prepClientRenderResults({
833
819
  usage,
834
820
  demoApp,
835
- imports: xImports,
836
- renderOptions: { pattern, template, demo }
821
+ importMap,
822
+ renderOptions: { demo, state, patternId, templateId }
837
823
  }) {
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);
848
824
  const meta = {
849
825
  demo,
850
- moduleImports: (0, import_utils3.groupBy)(importInfos, (importInfo) => importInfo.path),
851
- patternId: pattern.id,
852
- templateId: template.id,
853
- imports,
854
826
  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
+ },
855
840
  demoWrapperProps: {
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
- })
841
+ patternId,
842
+ templateId,
843
+ demo
879
844
  }
880
845
  };
881
846
  let code = `
882
847
  window.knapsack = window.knapsack || {};
883
- window.knapsack.getDemoApp = ({ ${imports.map((i) => i.importInfo.name).join(", ")} }) => {
848
+ window.knapsack.getDemoApp = ({ ${[...importMap.keys()].join(", ")} }) => {
884
849
  ${demoApp}
885
850
  return ${demoAppName}
886
851
  }
@@ -902,7 +867,7 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
902
867
  <script type="application/javascript">${code}</script>
903
868
  <div id="render-root" class="knapsack-pattern-direct-parent" data-dev-note="Knapsack React Template Wrapper"></div>
904
869
  ${this.assets.map((asset) => `<script src="${asset}"></script>`).join("\n")}
905
- ${this.createHtmlTagsForAssetPaths({
870
+ ${import_renderer_webpack_base.RendererWebpackBase.createHtmlTagsForAssetPaths({
906
871
  assets: this.getWebpackAssetPaths(),
907
872
  // 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
908
873
  scriptTagsAreAsync: false
@@ -927,11 +892,9 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
927
892
  let attempt = 0;
928
893
  while (true) {
929
894
  try {
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
- });
895
+ const { absolutePath, exists } = await this.resolvePath(
896
+ opt.demo.templateInfo.path
897
+ );
935
898
  if (!exists) {
936
899
  throw new Error(
937
900
  `Template demo file does not exist: ${absolutePath}`
@@ -948,9 +911,12 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
948
911
  await (0, import_sleep_promise.default)(waitTime);
949
912
  }
950
913
  }
951
- const [templateFileContents, { usage, imports }] = await Promise.all([
914
+ const [templateFileContents, { usage, importMap }] = await Promise.all([
952
915
  (0, import_file_utils3.readFile)(templateDemoPath),
953
- this.getUsageAndImports(opt)
916
+ this.getUsageAndImports({
917
+ ...opt,
918
+ importMap: /* @__PURE__ */ new Map()
919
+ })
954
920
  ]);
955
921
  const demoApp = await getDemoAppUsage({
956
922
  children: usage
@@ -958,15 +924,18 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
958
924
  const results = await this.prepClientRenderResults({
959
925
  usage: templateFileContents,
960
926
  demoApp,
961
- imports,
962
- renderOptions: opt
927
+ renderOptions: opt,
928
+ importMap
963
929
  });
964
930
  return results;
965
931
  }
966
932
  if (opt.demo?.type === "data") {
967
- const { usage, imports } = await this.getUsageAndImports(opt);
968
- const { code: importCode } = this.createJsImportCodeBlock({
969
- imports
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
970
939
  });
971
940
  const [demoAppUsage, demoApp] = await Promise.all([
972
941
  getDemoAppUsage({
@@ -981,32 +950,40 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
981
950
  return this.prepClientRenderResults({
982
951
  demoApp,
983
952
  usage: demoAppUsage,
984
- imports,
985
- renderOptions: opt
953
+ renderOptions: opt,
954
+ importMap
986
955
  });
987
956
  }
988
957
  }, "render");
989
958
  getUsageAndImports = /* @__PURE__ */ __name(async ({
990
- pattern,
991
- template,
992
- patternManifest,
993
- demo
959
+ patternId,
960
+ templateId,
961
+ demo,
962
+ state,
963
+ importMap
994
964
  }) => {
995
- if (demo?.type && demo.type === "data") {
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
+ }
996
979
  const {
997
980
  data: { props, slots, slotsOptionsComputed }
998
981
  } = demo;
999
- const importInfo = this.getJsImport({
1000
- patternId: pattern.id,
1001
- templateId: template.id
982
+ const { name: templateName } = await this.addUniqueValueToImportMap({
983
+ importMap,
984
+ path: template.path,
985
+ alias: template.alias || "default"
1002
986
  });
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];
1010
987
  const children = [];
1011
988
  const extraProps = [];
1012
989
  if (slots) {
@@ -1016,6 +993,7 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
1016
993
  const slotItems = slots[slotName];
1017
994
  const slotItemsUsages = await Promise.all(
1018
995
  slotItems.filter((slotItem) => {
996
+ if (!slotItem) return false;
1019
997
  if (slotItem.type !== "text") {
1020
998
  if (!slotItem.patternId) return false;
1021
999
  if (!slotItem.templateId) return false;
@@ -1031,31 +1009,39 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
1031
1009
  }
1032
1010
  return slotItem.text;
1033
1011
  }
1034
- const slotPattern = patternManifest.getPattern(
1035
- slotItem.patternId
1036
- );
1037
- const slotTemplate = slotPattern.templates.find(
1038
- (t) => t.id === slotItem.templateId
1039
- );
1040
1012
  if (slotItem.type === "template-reference") {
1041
- const { usage: usage2, imports } = await this.getUsageAndImports({
1042
- pattern: slotPattern,
1043
- template: slotTemplate,
1044
- patternManifest
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"
1045
1023
  });
1046
- importInfos.push(...imports);
1047
- return usage2;
1024
+ return templateRefImport.name;
1048
1025
  }
1049
1026
  if (slotItem.type === "template-demo") {
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
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
1055
1041
  });
1056
- importInfos.push(...imports);
1057
1042
  return usage2;
1058
1043
  }
1044
+ const _exhaustiveCheck2 = slotItem;
1059
1045
  throw new Error(
1060
1046
  `Unknown slot item: ${JSON.stringify(slotItem)}`
1061
1047
  );
@@ -1114,50 +1100,25 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
1114
1100
  });
1115
1101
  return {
1116
1102
  usage,
1117
- imports: importInfos
1103
+ importMap
1118
1104
  };
1119
1105
  }
1120
- if (demo?.type && demo.type === "template") {
1121
- const importInfo = this.getJsImport({
1122
- patternId: pattern.id,
1123
- templateId: template.id,
1124
- demoId: demo.id
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"
1125
1112
  });
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;
1132
1113
  const usage = await getUsage({ templateName });
1133
1114
  return {
1134
1115
  usage,
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]
1116
+ importMap
1157
1117
  };
1158
1118
  }
1119
+ const _exhaustiveCheck = demo;
1159
1120
  throw new Error(
1160
- `Unhandled demo type for ${pattern.id}-${template.id}: ${JSON.stringify(
1121
+ `Unhandled demo type for ${patternId}-${templateId}: ${JSON.stringify(
1161
1122
  demo
1162
1123
  )}`
1163
1124
  );
@@ -1180,8 +1141,8 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
1180
1141
  }
1181
1142
  return spec;
1182
1143
  }, "inferSpec");
1183
- watch = /* @__PURE__ */ __name(async (opt) => {
1184
- super.watch(opt);
1144
+ watch = /* @__PURE__ */ __name(async () => {
1145
+ super.watch();
1185
1146
  import_app2.knapsackEvents.onPatternTemplateChanged(() => {
1186
1147
  clearInferSpecCache();
1187
1148
  });
@@ -1259,21 +1220,34 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
1259
1220
  ];
1260
1221
  }, "alterTemplateMetaFiles");
1261
1222
  getTemplateSuggestions = /* @__PURE__ */ __name(async ({
1262
- newPath
1223
+ newPath,
1224
+ state
1263
1225
  }) => {
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
- });
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);
1275
1245
  const allPaths = [
1276
- .../* @__PURE__ */ new Set([newPath, ...usedSuggestions.map(({ path: path2 }) => path2)])
1246
+ .../* @__PURE__ */ new Set([
1247
+ newPath,
1248
+ ...Object.keys(this.pkgPathAliases || {}),
1249
+ ...codeSrcs
1250
+ ])
1277
1251
  ];
1278
1252
  const allSuggestions = await Promise.all(
1279
1253
  allPaths.map(async (path2) => {
@@ -1281,7 +1255,7 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends import_renderer
1281
1255
  try {
1282
1256
  const { exports: exports2, errorMsg } = await (0, import_file_utils3.getJsExportNames)({
1283
1257
  path: path2,
1284
- resolveFromDir: dataDir,
1258
+ resolveFromDir: this.dataDir,
1285
1259
  pkgPathAliases: this.pkgPathAliases
1286
1260
  });
1287
1261
  if (errorMsg) {