@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.mjs CHANGED
@@ -7,7 +7,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
7
7
  throw Error('Dynamic require of "' + x + '" is not supported');
8
8
  });
9
9
 
10
- // ../../../../node_modules/.pnpm/tsup@8.2.4_@microsoft+api-extractor@7.43.8_@types+node@20.16.5__@swc+core@1.3.57_@swc+helpers_ltnhnypbjniokjoiamajspm464/node_modules/tsup/assets/esm_shims.js
10
+ // ../../../../node_modules/.pnpm/tsup@8.2.4_@microsoft+api-extractor@7.43.8_@types+node@20.16.6__@swc+core@1.3.57_@swc+helpers_iqa4vqpgdlzwuubzthdmdz7nfe/node_modules/tsup/assets/esm_shims.js
11
11
  import { fileURLToPath } from "url";
12
12
  import path from "path";
13
13
  var getFilename = /* @__PURE__ */ __name(() => fileURLToPath(import.meta.url), "getFilename");
@@ -17,10 +17,9 @@ var __dirname = /* @__PURE__ */ getDirname();
17
17
  // src/renderer-react.ts
18
18
  import sleep from "sleep-promise";
19
19
  import {
20
- RendererWebpackBase,
21
- convertImportMapToNeededImportsByPath
20
+ RendererWebpackBase
22
21
  } from "@knapsack/renderer-webpack-base";
23
- import { pascalCase, isFirstLetterCapital } from "@knapsack/utils";
22
+ import { pascalCase, isFirstLetterCapital, groupBy } from "@knapsack/utils";
24
23
  import { knapsackEvents, log as log2 } from "@knapsack/app";
25
24
  import {
26
25
  babelCodeForBrowser,
@@ -35,9 +34,9 @@ import {
35
34
  getJsExportNames as getJsExportNames2,
36
35
  readFile as readFile2,
37
36
  formatCode as formatCode2,
38
- assertFileExists
37
+ resolvePath as resolvePath2
39
38
  } from "@knapsack/file-utils";
40
- import { join, relative, parse, isAbsolute } from "path";
39
+ import { join, relative, parse } from "path";
41
40
 
42
41
  // src/utils.ts
43
42
  import { log } from "@knapsack/app";
@@ -735,7 +734,6 @@ var rendererMetaScriptTagId = "ks-react-meta";
735
734
  // src/renderer-react.ts
736
735
  var { pkg } = findUpPkgJson(__dirname);
737
736
  log2.setupUpdateNotifier({ ...pkg, name: pkg.name, version: pkg.version });
738
- var errorCatcherPath = join(__dirname, "./error-catcher.mjs");
739
737
  var KnapsackReactRenderer = class _KnapsackReactRenderer extends RendererWebpackBase {
740
738
  static {
741
739
  __name(this, "KnapsackReactRenderer");
@@ -755,29 +753,22 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends RendererWebpack
755
753
  } = {}) {
756
754
  super({
757
755
  id,
756
+ extension: ".jsx",
758
757
  language: "jsx",
759
758
  webpackConfig,
760
759
  extraScripts: [
761
760
  // this is the code in `./client/init.mts`
762
761
  "@knapsack/renderer-react/client"
763
- ],
764
- codeSrcs: [demoWrapperPath, errorCatcherPath]
762
+ ]
765
763
  });
766
764
  this.language = "jsx";
767
765
  this.assets = [];
768
- this.demoWrapperPath = isAbsolute(demoWrapperPath) ? demoWrapperPath : this.resolvePathSync({
769
- path: demoWrapperPath,
770
- resolveFromDir: this.userConfigDir
771
- }).absolutePath;
772
- assertFileExists(
773
- this.demoWrapperPath,
774
- `Could not find demo wrapper at: "${this.demoWrapperPath}"
775
- Please adjust setting in "knapsack.config.js" or pass a different path when creating the React Renderer.`
776
- );
766
+ this.demoWrapperPath = demoWrapperPath;
777
767
  this.disableReactStrictMode = disableReactStrictMode;
778
768
  this.creators = [createReactPattern];
779
769
  }
780
- init = /* @__PURE__ */ __name(async () => {
770
+ init = /* @__PURE__ */ __name(async (opt) => {
771
+ await super.init(opt);
781
772
  this.assets = await copyReactAssets(this.outputDir, this.publicPath);
782
773
  if (!await fileExists(this.demoWrapperPath)) {
783
774
  throw new Error(
@@ -823,37 +814,80 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
823
814
  };
824
815
  return config;
825
816
  }, "createWebpackConfig");
817
+ getJsImports = /* @__PURE__ */ __name(() => {
818
+ const imports = super.getJsImports();
819
+ imports.push(
820
+ {
821
+ type: "extra",
822
+ importInfo: {
823
+ type: "default",
824
+ path: this.demoWrapperPath,
825
+ name: "DemoWrapper"
826
+ }
827
+ },
828
+ {
829
+ type: "extra",
830
+ importInfo: {
831
+ type: "default",
832
+ path: join(__dirname, "./error-catcher.mjs"),
833
+ name: "ErrorCatcher"
834
+ }
835
+ }
836
+ );
837
+ return imports;
838
+ }, "getJsImports");
826
839
  async prepClientRenderResults({
827
840
  usage,
828
841
  demoApp,
829
- importMap,
830
- renderOptions: { demo, state, patternId, templateId }
842
+ imports: xImports,
843
+ renderOptions: { pattern, template, demo }
831
844
  }) {
845
+ const extraImports = this.getJsImports().filter(
846
+ (imp) => imp.type === "extra"
847
+ );
848
+ const { imports, isDeclaredVarsUnique, nameCollisions } = this.makeKsJsImportsUnique({ imports: [...xImports, ...extraImports] });
849
+ if (!isDeclaredVarsUnique) {
850
+ log2.error(`${nameCollisions.join(", ")} are declared multiple times`, {
851
+ imports
852
+ });
853
+ }
854
+ const importInfos = imports.map(({ importInfo }) => importInfo);
832
855
  const meta = {
833
856
  demo,
857
+ moduleImports: groupBy(importInfos, (importInfo) => importInfo.path),
858
+ patternId: pattern.id,
859
+ templateId: template.id,
860
+ imports,
834
861
  disableReactStrictMode: this.disableReactStrictMode,
835
- neededImportsByPath: convertImportMapToNeededImportsByPath(importMap),
836
- extraImports: {
837
- DemoWrapper: {
838
- type: "default",
839
- path: this.demoWrapperPath,
840
- name: "DemoWrapper"
841
- },
842
- ErrorCatcher: {
843
- type: "default",
844
- path: errorCatcherPath,
845
- name: "ErrorCatcher"
846
- }
847
- },
848
862
  demoWrapperProps: {
849
- patternId,
850
- templateId,
851
- demo
863
+ pattern,
864
+ template,
865
+ demo,
866
+ patternsUsed: imports.flatMap((imp) => {
867
+ if (imp.type === "pattern-template") {
868
+ return [
869
+ {
870
+ patternId: imp.patternId,
871
+ templateId: imp.templateId
872
+ }
873
+ ];
874
+ }
875
+ if (imp.type === "pattern-template-demo") {
876
+ return [
877
+ {
878
+ patternId: imp.patternId,
879
+ templateId: imp.templateId,
880
+ demoId: imp.demoId
881
+ }
882
+ ];
883
+ }
884
+ return [];
885
+ })
852
886
  }
853
887
  };
854
888
  let code = `
855
889
  window.knapsack = window.knapsack || {};
856
- window.knapsack.getDemoApp = ({ ${[...importMap.keys()].join(", ")} }) => {
890
+ window.knapsack.getDemoApp = ({ ${imports.map((i) => i.importInfo.name).join(", ")} }) => {
857
891
  ${demoApp}
858
892
  return ${demoAppName}
859
893
  }
@@ -875,7 +909,7 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
875
909
  <script type="application/javascript">${code}</script>
876
910
  <div id="render-root" class="knapsack-pattern-direct-parent" data-dev-note="Knapsack React Template Wrapper"></div>
877
911
  ${this.assets.map((asset) => `<script src="${asset}"></script>`).join("\n")}
878
- ${RendererWebpackBase.createHtmlTagsForAssetPaths({
912
+ ${this.createHtmlTagsForAssetPaths({
879
913
  assets: this.getWebpackAssetPaths(),
880
914
  // 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
881
915
  scriptTagsAreAsync: false
@@ -900,9 +934,11 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
900
934
  let attempt = 0;
901
935
  while (true) {
902
936
  try {
903
- const { absolutePath, exists } = await this.resolvePath(
904
- opt.demo.templateInfo.path
905
- );
937
+ const { absolutePath, exists } = await resolvePath2({
938
+ path: opt.demo.templateInfo.path,
939
+ pkgPathAliases: this.pkgPathAliases,
940
+ resolveFromDir: this.dataDir
941
+ });
906
942
  if (!exists) {
907
943
  throw new Error(
908
944
  `Template demo file does not exist: ${absolutePath}`
@@ -919,12 +955,9 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
919
955
  await sleep(waitTime);
920
956
  }
921
957
  }
922
- const [templateFileContents, { usage, importMap }] = await Promise.all([
958
+ const [templateFileContents, { usage, imports }] = await Promise.all([
923
959
  readFile2(templateDemoPath),
924
- this.getUsageAndImports({
925
- ...opt,
926
- importMap: /* @__PURE__ */ new Map()
927
- })
960
+ this.getUsageAndImports(opt)
928
961
  ]);
929
962
  const demoApp = await getDemoAppUsage({
930
963
  children: usage
@@ -932,18 +965,15 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
932
965
  const results = await this.prepClientRenderResults({
933
966
  usage: templateFileContents,
934
967
  demoApp,
935
- renderOptions: opt,
936
- importMap
968
+ imports,
969
+ renderOptions: opt
937
970
  });
938
971
  return results;
939
972
  }
940
973
  if (opt.demo?.type === "data") {
941
- const { usage, importMap } = await this.getUsageAndImports({
942
- ...opt,
943
- importMap: /* @__PURE__ */ new Map()
944
- });
945
- const importCode = RendererWebpackBase.createJsImportCodeBlock({
946
- importMap
974
+ const { usage, imports } = await this.getUsageAndImports(opt);
975
+ const { code: importCode } = this.createJsImportCodeBlock({
976
+ imports
947
977
  });
948
978
  const [demoAppUsage, demoApp] = await Promise.all([
949
979
  getDemoAppUsage({
@@ -958,40 +988,32 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
958
988
  return this.prepClientRenderResults({
959
989
  demoApp,
960
990
  usage: demoAppUsage,
961
- renderOptions: opt,
962
- importMap
991
+ imports,
992
+ renderOptions: opt
963
993
  });
964
994
  }
965
995
  }, "render");
966
996
  getUsageAndImports = /* @__PURE__ */ __name(async ({
967
- patternId,
968
- templateId,
969
- demo,
970
- state,
971
- importMap
997
+ pattern,
998
+ template,
999
+ patternManifest,
1000
+ demo
972
1001
  }) => {
973
- if (!demo) {
974
- throw new Error(
975
- `No demo provided while rendering ${patternId} ${templateId}`
976
- );
977
- }
978
- const pattern = state.patterns[patternId];
979
- if (!pattern) {
980
- throw new Error(`Could not find pattern: ${patternId}`);
981
- }
982
- if (demo.type === "data") {
983
- const template = pattern.templates.find((t) => t.id === templateId);
984
- if (!template) {
985
- throw new Error(`Could not find template: ${templateId}`);
986
- }
1002
+ if (demo?.type && demo.type === "data") {
987
1003
  const {
988
1004
  data: { props, slots, slotsOptionsComputed }
989
1005
  } = demo;
990
- const { name: templateName } = await this.addUniqueValueToImportMap({
991
- importMap,
992
- path: template.path,
993
- alias: template.alias || "default"
1006
+ const importInfo = this.getJsImport({
1007
+ patternId: pattern.id,
1008
+ templateId: template.id
994
1009
  });
1010
+ if (!importInfo) {
1011
+ throw new Error(
1012
+ `Could not find import for pattern-template: ${pattern.id}-${template.id}`
1013
+ );
1014
+ }
1015
+ const { type, name: templateName } = importInfo.importInfo;
1016
+ const importInfos = [importInfo];
995
1017
  const children = [];
996
1018
  const extraProps = [];
997
1019
  if (slots) {
@@ -1001,7 +1023,6 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
1001
1023
  const slotItems = slots[slotName];
1002
1024
  const slotItemsUsages = await Promise.all(
1003
1025
  slotItems.filter((slotItem) => {
1004
- if (!slotItem) return false;
1005
1026
  if (slotItem.type !== "text") {
1006
1027
  if (!slotItem.patternId) return false;
1007
1028
  if (!slotItem.templateId) return false;
@@ -1017,39 +1038,31 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
1017
1038
  }
1018
1039
  return slotItem.text;
1019
1040
  }
1041
+ const slotPattern = patternManifest.getPattern(
1042
+ slotItem.patternId
1043
+ );
1044
+ const slotTemplate = slotPattern.templates.find(
1045
+ (t) => t.id === slotItem.templateId
1046
+ );
1020
1047
  if (slotItem.type === "template-reference") {
1021
- const slottedTemplate = state.patterns[slotItem.patternId]?.templates.find((t) => t.id === slotItem.templateId);
1022
- if (!slottedTemplate) {
1023
- throw new Error(
1024
- `Could not find slotted template: ${slotItem.patternId} ${slotItem.templateId}`
1025
- );
1026
- }
1027
- const templateRefImport = await this.addUniqueValueToImportMap({
1028
- importMap,
1029
- path: slottedTemplate.path,
1030
- alias: slottedTemplate.alias || "default"
1048
+ const { usage: usage2, imports } = await this.getUsageAndImports({
1049
+ pattern: slotPattern,
1050
+ template: slotTemplate,
1051
+ patternManifest
1031
1052
  });
1032
- return templateRefImport.name;
1053
+ importInfos.push(...imports);
1054
+ return usage2;
1033
1055
  }
1034
1056
  if (slotItem.type === "template-demo") {
1035
- const thisDemo = slotItem.demo;
1036
- if (!thisDemo) {
1037
- throw new Error(
1038
- `Could not find slotted template demo ${JSON.stringify(
1039
- slotItem
1040
- )}`
1041
- );
1042
- }
1043
- const { usage: usage2 } = await this.getUsageAndImports({
1044
- patternId: thisDemo.patternId,
1045
- templateId: thisDemo.templateId,
1046
- demo: thisDemo,
1047
- state,
1048
- importMap
1057
+ const { usage: usage2, imports } = await this.getUsageAndImports({
1058
+ pattern: slotPattern,
1059
+ template: slotTemplate,
1060
+ demo: slotItem.demo || this.patterns.demosById[slotItem.demoId],
1061
+ patternManifest
1049
1062
  });
1063
+ importInfos.push(...imports);
1050
1064
  return usage2;
1051
1065
  }
1052
- const _exhaustiveCheck2 = slotItem;
1053
1066
  throw new Error(
1054
1067
  `Unknown slot item: ${JSON.stringify(slotItem)}`
1055
1068
  );
@@ -1108,25 +1121,50 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
1108
1121
  });
1109
1122
  return {
1110
1123
  usage,
1111
- importMap
1124
+ imports: importInfos
1112
1125
  };
1113
1126
  }
1114
- if (demo.type === "template") {
1115
- const { templateInfo } = demo;
1116
- const { name: templateName } = await this.addUniqueValueToImportMap({
1117
- importMap,
1118
- path: templateInfo.path,
1119
- alias: templateInfo.alias || "default"
1127
+ if (demo?.type && demo.type === "template") {
1128
+ const importInfo = this.getJsImport({
1129
+ patternId: pattern.id,
1130
+ templateId: template.id,
1131
+ demoId: demo.id
1120
1132
  });
1133
+ if (!importInfo) {
1134
+ throw new Error(
1135
+ `Could not find import for pattern-template-demo: ${pattern.id}-${template.id}-${demo.id}`
1136
+ );
1137
+ }
1138
+ const { type, name: templateName } = importInfo.importInfo;
1121
1139
  const usage = await getUsage({ templateName });
1122
1140
  return {
1123
1141
  usage,
1124
- importMap
1142
+ imports: [importInfo]
1143
+ };
1144
+ }
1145
+ if (!demo) {
1146
+ const importInfo = this.getJsImport({
1147
+ patternId: pattern.id,
1148
+ templateId: template.id
1149
+ });
1150
+ if (!importInfo) {
1151
+ throw new Error(
1152
+ `Could not find import for pattern-template: ${pattern.id}-${template.id}`
1153
+ );
1154
+ }
1155
+ const { type, name: templateName } = importInfo.importInfo;
1156
+ return {
1157
+ /**
1158
+ * 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`
1159
+ * @see {KsSlotInfo['isTemplateReference']}
1160
+ * @see {SlottedTemplate}
1161
+ */
1162
+ usage: templateName,
1163
+ imports: [importInfo]
1125
1164
  };
1126
1165
  }
1127
- const _exhaustiveCheck = demo;
1128
1166
  throw new Error(
1129
- `Unhandled demo type for ${patternId}-${templateId}: ${JSON.stringify(
1167
+ `Unhandled demo type for ${pattern.id}-${template.id}: ${JSON.stringify(
1130
1168
  demo
1131
1169
  )}`
1132
1170
  );
@@ -1149,8 +1187,8 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
1149
1187
  }
1150
1188
  return spec;
1151
1189
  }, "inferSpec");
1152
- watch = /* @__PURE__ */ __name(async () => {
1153
- super.watch();
1190
+ watch = /* @__PURE__ */ __name(async (opt) => {
1191
+ super.watch(opt);
1154
1192
  knapsackEvents.onPatternTemplateChanged(() => {
1155
1193
  clearInferSpecCache();
1156
1194
  });
@@ -1228,31 +1266,21 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
1228
1266
  ];
1229
1267
  }, "alterTemplateMetaFiles");
1230
1268
  getTemplateSuggestions = /* @__PURE__ */ __name(async ({
1231
- newPath,
1232
- state
1269
+ newPath
1233
1270
  }) => {
1234
- const usedSuggestions = Object.values(state.patterns).reduce(
1235
- (acc, { templateDemos, templates }) => {
1236
- templates.forEach(({ path: path3, alias, templateLanguageId }) => {
1237
- if (templateLanguageId !== this.id) return;
1238
- acc.push({ path: path3, alias });
1239
- });
1240
- templateDemos.forEach(
1241
- ({ templateInfo: { path: path3, alias }, templateLanguageId }) => {
1242
- if (templateLanguageId !== this.id) return;
1243
- acc.push({ path: path3, alias });
1244
- }
1245
- );
1246
- return acc;
1247
- },
1248
- []
1249
- );
1271
+ const { data: dataDir } = this.patterns.userConfig;
1272
+ const { allTemplateDemos, allTemplates } = this.getMyTemplates();
1273
+ const usedSuggestions = [
1274
+ ...allTemplateDemos,
1275
+ ...allTemplates
1276
+ ].map(({ path: path3, alias }) => {
1277
+ return {
1278
+ path: path3,
1279
+ alias: alias || "default"
1280
+ };
1281
+ });
1250
1282
  const allPaths = [
1251
- .../* @__PURE__ */ new Set([
1252
- newPath,
1253
- ...Object.keys(this.pkgPathAliases || {}),
1254
- ...this.getCodeSrcs()
1255
- ])
1283
+ .../* @__PURE__ */ new Set([newPath, ...usedSuggestions.map(({ path: path3 }) => path3)])
1256
1284
  ];
1257
1285
  const allSuggestions = await Promise.all(
1258
1286
  allPaths.map(async (path3) => {
@@ -1260,7 +1288,7 @@ Please adjust setting in "knapsack.config.js" or pass a different path when crea
1260
1288
  try {
1261
1289
  const { exports, errorMsg } = await getJsExportNames2({
1262
1290
  path: path3,
1263
- resolveFromDir: this.dataDir,
1291
+ resolveFromDir: dataDir,
1264
1292
  pkgPathAliases: this.pkgPathAliases
1265
1293
  });
1266
1294
  if (errorMsg) {