@knapsack/renderer-react 4.69.9--canary.4739.282ee28.0 → 4.69.9--canary.4768.997c53b.0

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.mjs CHANGED
@@ -16,21 +16,25 @@ var __dirname = /* @__PURE__ */ getDirname();
16
16
 
17
17
  // src/renderer-react.ts
18
18
  import sleep from "sleep-promise";
19
- import { KnapsackRendererWebpackBase } from "@knapsack/renderer-webpack-base";
20
- import { pascalCase, isFirstLetterCapital } from "@knapsack/utils";
21
- import { knapsackEvents, log as log2, KnapsackRendererBase } from "@knapsack/app";
22
19
  import {
23
- isSlottedText,
24
- isSlottedTemplateReference,
25
- isSlottedTemplateDemo,
20
+ RendererWebpackBase
21
+ } from "@knapsack/renderer-webpack-base";
22
+ import { pascalCase, isFirstLetterCapital, groupBy } from "@knapsack/utils";
23
+ import { knapsackEvents, log as log2 } from "@knapsack/app";
24
+ import {
25
+ babelCodeForBrowser,
26
+ createSlotOptionsHtmlTags
27
+ } from "@knapsack/app/renderers";
28
+ import {
26
29
  rendererIds
27
30
  } from "@knapsack/types";
28
31
  import {
29
- exists,
32
+ exists as fileExists,
30
33
  findUpPkgJson,
31
34
  getJsExportNames as getJsExportNames2,
32
35
  readFile as readFile2,
33
- formatCode as formatCode2
36
+ formatCode as formatCode2,
37
+ resolvePath as resolvePath2
34
38
  } from "@knapsack/file-utils";
35
39
  import { join, relative, parse } from "path";
36
40
 
@@ -61,13 +65,14 @@ function renderUsageTemplate({
61
65
  `;
62
66
  }
63
67
  __name(renderUsageTemplate, "renderUsageTemplate");
68
+ var demoAppName = "DemoApp";
64
69
  function renderDemoAppTemplate({
65
- imports,
70
+ imports = "",
66
71
  children
67
72
  }) {
68
73
  return `${imports}
69
74
 
70
- function DemoApp() {
75
+ function ${demoAppName}() {
71
76
  return (
72
77
  ${children}
73
78
  )
@@ -126,12 +131,14 @@ async function getUsage(data) {
126
131
  __name(getUsage, "getUsage");
127
132
  async function getDemoAppUsage({
128
133
  children,
129
- imports
134
+ imports,
135
+ format
130
136
  }) {
131
137
  const code = renderDemoAppTemplate({
132
138
  children,
133
139
  imports
134
140
  });
141
+ if (!format) return code;
135
142
  return formatCode({
136
143
  contents: code,
137
144
  path: "x.tsx"
@@ -721,11 +728,13 @@ var createReactPattern = createCreator({
721
728
  }, "getTasks")
722
729
  });
723
730
 
731
+ // src/types.ts
732
+ var rendererMetaScriptTagId = "ks-react-meta";
733
+
724
734
  // src/renderer-react.ts
725
735
  var { pkg } = findUpPkgJson(__dirname);
726
736
  log2.setupUpdateNotifier({ ...pkg, name: pkg.name, version: pkg.version });
727
- var { createSlotOptionsHtmlTags } = KnapsackRendererBase;
728
- var KnapsackReactRenderer = class _KnapsackReactRenderer extends KnapsackRendererWebpackBase {
737
+ var KnapsackReactRenderer = class _KnapsackReactRenderer extends RendererWebpackBase {
729
738
  static {
730
739
  __name(this, "KnapsackReactRenderer");
731
740
  }
@@ -734,7 +743,6 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends KnapsackRendere
734
743
  */
735
744
  assets;
736
745
  babelConfig;
737
- creators;
738
746
  demoWrapperPath;
739
747
  disableReactStrictMode;
740
748
  constructor({
@@ -747,7 +755,11 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends KnapsackRendere
747
755
  id,
748
756
  extension: ".jsx",
749
757
  language: "jsx",
750
- webpackConfig
758
+ webpackConfig,
759
+ extraScripts: [
760
+ // this is the code in `./client/init.mts`
761
+ "@knapsack/renderer-react/client"
762
+ ]
751
763
  });
752
764
  this.language = "jsx";
753
765
  this.assets = [];
@@ -755,15 +767,15 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends KnapsackRendere
755
767
  this.disableReactStrictMode = disableReactStrictMode;
756
768
  this.creators = [createReactPattern];
757
769
  }
758
- async init(opt) {
770
+ init = /* @__PURE__ */ __name(async (opt) => {
759
771
  await super.init(opt);
760
772
  this.assets = await copyReactAssets(this.outputDir, this.publicPath);
761
- if (!await exists(this.demoWrapperPath)) {
773
+ if (!await fileExists(this.demoWrapperPath)) {
762
774
  throw new Error(
763
775
  `Could not find demo wrapper at: "${this.demoWrapperPath}"`
764
776
  );
765
777
  }
766
- }
778
+ }, "init");
767
779
  getMeta = /* @__PURE__ */ __name(() => ({
768
780
  id: this.id,
769
781
  title: "React",
@@ -793,18 +805,16 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends KnapsackRendere
793
805
  }
794
806
  }
795
807
  }), "getMeta");
796
- changeCase(str) {
797
- return pascalCase(str);
798
- }
799
- createWebpackConfig() {
808
+ changeCase = /* @__PURE__ */ __name((str) => pascalCase(str), "changeCase");
809
+ createWebpackConfig = /* @__PURE__ */ __name(() => {
800
810
  const config = super.createWebpackConfig();
801
811
  config.externals = {
802
812
  react: "React",
803
813
  "react-dom": "ReactDOM"
804
814
  };
805
815
  return config;
806
- }
807
- getJsImports() {
816
+ }, "createWebpackConfig");
817
+ getJsImports = /* @__PURE__ */ __name(() => {
808
818
  const imports = super.getJsImports();
809
819
  imports.push(
810
820
  {
@@ -825,174 +835,89 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends KnapsackRendere
825
835
  }
826
836
  );
827
837
  return imports;
828
- }
838
+ }, "getJsImports");
829
839
  async prepClientRenderResults({
830
840
  usage,
831
841
  demoApp,
832
842
  imports: xImports,
833
843
  renderOptions: { pattern, template, demo }
834
844
  }) {
835
- const extraImportNames = this.getJsImports().flatMap(
836
- (imp) => imp.type === "extra" ? [imp.importInfo.name] : []
845
+ const extraImports = this.getJsImports().filter(
846
+ (imp) => imp.type === "extra"
837
847
  );
838
- const { imports, isDeclaredVarsUnique, nameCollisions } = this.makeKsJsImportsUnique({ imports: xImports });
848
+ const { imports, isDeclaredVarsUnique, nameCollisions } = this.makeKsJsImportsUnique({ imports: [...xImports, ...extraImports] });
839
849
  if (!isDeclaredVarsUnique) {
840
850
  log2.error(`${nameCollisions.join(", ")} are declared multiple times`, {
841
851
  imports
842
852
  });
843
853
  }
844
- const importNames = [
845
- ...imports.map(({ importInfo: { name } }) => name),
846
- ...extraImportNames
847
- ];
848
- const patternsUsed = imports.flatMap((imp) => {
849
- if (imp.type === "pattern-template") {
850
- return [
851
- {
852
- patternId: imp.patternId,
853
- templateId: imp.templateId
854
+ const importInfos = imports.map(({ importInfo }) => importInfo);
855
+ const meta = {
856
+ demo,
857
+ moduleImports: groupBy(importInfos, (importInfo) => importInfo.path),
858
+ patternId: pattern.id,
859
+ templateId: template.id,
860
+ imports,
861
+ disableReactStrictMode: this.disableReactStrictMode,
862
+ demoWrapperProps: {
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
+ ];
854
874
  }
855
- ];
856
- }
857
- if (imp.type === "pattern-template-demo") {
858
- return [
859
- {
860
- patternId: imp.patternId,
861
- templateId: imp.templateId,
862
- demoId: imp.demoId
875
+ if (imp.type === "pattern-template-demo") {
876
+ return [
877
+ {
878
+ patternId: imp.patternId,
879
+ templateId: imp.templateId,
880
+ demoId: imp.demoId
881
+ }
882
+ ];
863
883
  }
864
- ];
884
+ return [];
885
+ })
865
886
  }
866
- return [];
867
- });
868
- const demoWrapperProps = {
869
- patternsUsed,
870
- pattern,
871
- template,
872
- demo
873
887
  };
874
- const demoWrapperCode = await getUsage({
875
- templateName: "DemoWrapper",
876
- props: demoWrapperProps,
877
- children: `<DemoApp />`
878
- // extraProps,
879
- });
880
- async function renderReact({
881
- patterns,
882
- theExtraImportNames,
883
- ksGlobal
884
- }) {
885
- if (!ksGlobal) {
886
- throw new Error('"window.knapsack" is null');
887
- }
888
- const components = await ksGlobal.getAllImports({
889
- patterns,
890
- extras: theExtraImportNames.map((name) => ({ name }))
891
- });
892
- return components;
893
- }
894
- __name(renderReact, "renderReact");
895
888
  let code = `
896
-
897
- ${renderReact.toString()}
898
- ${renderReact.name}({
899
- ksGlobal: window.knapsack,
900
- patterns: ${JSON.stringify(patternsUsed)},
901
- theExtraImportNames: ${JSON.stringify(extraImportNames)},
902
- }).then((components) => {
903
- const { ${importNames.join(", ")} } = components;
904
- const root = document.getElementById('render-root');
905
-
906
- ${demoApp}
907
-
908
- const reactDomVersion = parseInt(ReactDOM.version.split('.')[0], 10);
909
-
910
- const ReactRendererResult = () => {
911
- if (reactDomVersion < 17 || ${this.disableReactStrictMode}){
912
- return (
913
- <ErrorCatcher>
914
- ${demoWrapperCode}
915
- </ErrorCatcher>
916
- )
889
+ window.knapsack = window.knapsack || {};
890
+ window.knapsack.getDemoApp = ({ ${imports.map((i) => i.importInfo.name).join(", ")} }) => {
891
+ ${demoApp}
892
+ return ${demoAppName}
917
893
  }
918
-
919
- return (
920
- <React.StrictMode>
921
- <ErrorCatcher>
922
- ${demoWrapperCode}
923
- </ErrorCatcher>
924
- </React.StrictMode>
925
- )
926
- };
927
-
928
-
929
- if (reactDomVersion > 17){
930
- ReactDOM.createRoot(root).render(
931
- <ReactRendererResult />
932
- )
933
- } else {
934
- ReactDOM.render(
935
- <ReactRendererResult />,
936
- root
937
- );
938
- }
939
- }).catch((err) => {
940
- console.error(err);
941
- const root = document.getElementById('render-root');
942
- // Create a new <div> element to contain the error message
943
- const errorMsgDiv = document.createElement('div');
944
- // Insert the new <div> element before the existing element
945
- root.parentNode.insertBefore(errorMsgDiv, root);
946
- // add error message so users can see it
947
- errorMsgDiv.innerHTML = '<h1>Component Error</h1><p>' + err.message + '</p>';
948
- });
949
894
  `;
950
- let codeHadError = false;
951
895
  let errorHtmlMsg = "";
952
896
  try {
953
- code = await this.babelCodeForBrowser({
954
- code
955
- });
897
+ code = await babelCodeForBrowser({ code });
956
898
  } catch (e) {
957
- codeHadError = true;
958
899
  console.log(code);
959
900
  console.log("---original code before babel error ^---");
960
901
  console.trace(e.message);
961
902
  code = `console.error(${JSON.stringify(e.message)});`;
962
903
  errorHtmlMsg = `<pre><code>${e.message}</code></pre>`;
963
904
  }
964
- if (!codeHadError) {
965
- try {
966
- code = await formatCode2({
967
- contents: code,
968
- path: "x.tsx"
969
- // doing this to set format language
970
- });
971
- } catch (e) {
972
- codeHadError = true;
973
- console.log(code);
974
- console.log("---original code before prettier error ^---");
975
- console.trace(e.message);
976
- code = `console.error(${JSON.stringify(e.message)});`;
977
- errorHtmlMsg = `<pre><code>${e.message}</code></pre>`;
978
- }
979
- }
980
905
  const html = `
906
+ <script type="application/json" id="${rendererMetaScriptTagId}">${JSON.stringify(
907
+ meta
908
+ )}</script>
909
+ <script type="application/javascript">${code}</script>
910
+ <div id="render-root" class="knapsack-pattern-direct-parent" data-dev-note="Knapsack React Template Wrapper"></div>
981
911
  ${this.assets.map((asset) => `<script src="${asset}"></script>`).join("\n")}
982
-
983
912
  ${this.createHtmlTagsForAssetPaths({
984
913
  assets: this.getWebpackAssetPaths(),
985
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
986
915
  scriptTagsAreAsync: false
987
916
  })}
988
-
989
- <div id="render-root" class="knapsack-pattern-direct-parent" data-dev-note="Knapsack React Template Wrapper"></div>
990
- <script type="application/javascript">${code}</script>
991
- ${errorHtmlMsg}
992
-
917
+ ${errorHtmlMsg}
993
918
  `;
994
919
  return {
995
- ok: !codeHadError,
920
+ ok: !errorHtmlMsg,
996
921
  html: await formatCode2({
997
922
  contents: html,
998
923
  path: "x.html"
@@ -1002,18 +927,24 @@ ${errorHtmlMsg}
1002
927
  templateLanguage: this.language
1003
928
  };
1004
929
  }
1005
- async render(opt) {
1006
- if (_KnapsackReactRenderer.isTemplateDemo(opt.demo)) {
930
+ render = /* @__PURE__ */ __name(async (opt) => {
931
+ if (opt.demo?.type === "template") {
1007
932
  const waits = [5, 10, 20, 50, 100, 1e3, 1e3];
1008
933
  let templateDemoPath;
1009
934
  let attempt = 0;
1010
935
  while (true) {
1011
936
  try {
1012
- templateDemoPath = opt.patternManifest.getTemplateDemoAbsolutePath({
1013
- patternId: opt.pattern.id,
1014
- templateId: opt.template.id,
1015
- demoId: opt.demo.id
937
+ const { absolutePath, exists } = await resolvePath2({
938
+ path: opt.demo.templateInfo.path,
939
+ pkgPathAliases: this.pkgPathAliases,
940
+ resolveFromDir: this.dataDir
1016
941
  });
942
+ if (!exists) {
943
+ throw new Error(
944
+ `Template demo file does not exist: ${absolutePath}`
945
+ );
946
+ }
947
+ templateDemoPath = absolutePath;
1017
948
  break;
1018
949
  } catch (e) {
1019
950
  const waitTime = waits[attempt];
@@ -1039,7 +970,7 @@ ${errorHtmlMsg}
1039
970
  });
1040
971
  return results;
1041
972
  }
1042
- if (_KnapsackReactRenderer.isDataDemo(opt.demo)) {
973
+ if (opt.demo?.type === "data") {
1043
974
  const { usage, imports } = await this.getUsageAndImports(opt);
1044
975
  const { code: importCode } = this.createJsImportCodeBlock({
1045
976
  imports
@@ -1047,7 +978,8 @@ ${errorHtmlMsg}
1047
978
  const [demoAppUsage, demoApp] = await Promise.all([
1048
979
  getDemoAppUsage({
1049
980
  children: usage,
1050
- imports: importCode
981
+ imports: importCode,
982
+ format: true
1051
983
  }),
1052
984
  getDemoAppUsage({
1053
985
  children: usage
@@ -1060,10 +992,14 @@ ${errorHtmlMsg}
1060
992
  renderOptions: opt
1061
993
  });
1062
994
  }
1063
- }
1064
- async getUsageAndImports(opt) {
1065
- const { pattern, template, patternManifest, demo } = opt;
1066
- if (demo?.type && _KnapsackReactRenderer.isDataDemo(demo)) {
995
+ }, "render");
996
+ getUsageAndImports = /* @__PURE__ */ __name(async ({
997
+ pattern,
998
+ template,
999
+ patternManifest,
1000
+ demo
1001
+ }) => {
1002
+ if (demo?.type && demo.type === "data") {
1067
1003
  const {
1068
1004
  data: { props, slots, slotsOptionsComputed }
1069
1005
  } = demo;
@@ -1087,16 +1023,16 @@ ${errorHtmlMsg}
1087
1023
  const slotItems = slots[slotName];
1088
1024
  const slotItemsUsages = await Promise.all(
1089
1025
  slotItems.filter((slotItem) => {
1090
- if (!isSlottedText(slotItem)) {
1026
+ if (slotItem.type !== "text") {
1091
1027
  if (!slotItem.patternId) return false;
1092
1028
  if (!slotItem.templateId) return false;
1093
- if (isSlottedTemplateDemo(slotItem) && !slotItem.demoId) {
1029
+ if (slotItem.type === "template-demo" && !slotItem.demoId) {
1094
1030
  return false;
1095
1031
  }
1096
1032
  }
1097
1033
  return true;
1098
1034
  }).map(async (slotItem) => {
1099
- if (isSlottedText(slotItem)) {
1035
+ if (slotItem.type === "text") {
1100
1036
  if (slotItems.length === 1 && slotName !== "children") {
1101
1037
  return `\`${slotItem.text}\``;
1102
1038
  }
@@ -1108,7 +1044,7 @@ ${errorHtmlMsg}
1108
1044
  const slotTemplate = slotPattern.templates.find(
1109
1045
  (t) => t.id === slotItem.templateId
1110
1046
  );
1111
- if (isSlottedTemplateReference(slotItem)) {
1047
+ if (slotItem.type === "template-reference") {
1112
1048
  const { usage: usage2, imports } = await this.getUsageAndImports({
1113
1049
  pattern: slotPattern,
1114
1050
  template: slotTemplate,
@@ -1117,7 +1053,7 @@ ${errorHtmlMsg}
1117
1053
  importInfos.push(...imports);
1118
1054
  return usage2;
1119
1055
  }
1120
- if (isSlottedTemplateDemo(slotItem)) {
1056
+ if (slotItem.type === "template-demo") {
1121
1057
  const { usage: usage2, imports } = await this.getUsageAndImports({
1122
1058
  pattern: slotPattern,
1123
1059
  template: slotTemplate,
@@ -1188,7 +1124,7 @@ ${errorHtmlMsg}
1188
1124
  imports: importInfos
1189
1125
  };
1190
1126
  }
1191
- if (demo?.type && _KnapsackReactRenderer.isTemplateDemo(demo)) {
1127
+ if (demo?.type && demo.type === "template") {
1192
1128
  const importInfo = this.getJsImport({
1193
1129
  patternId: pattern.id,
1194
1130
  templateId: template.id,
@@ -1232,11 +1168,7 @@ ${errorHtmlMsg}
1232
1168
  demo
1233
1169
  )}`
1234
1170
  );
1235
- }
1236
- async getUsage(opt) {
1237
- const { usage } = await this.getUsageAndImports(opt);
1238
- return usage;
1239
- }
1171
+ }, "getUsageAndImports");
1240
1172
  inferSpec = /* @__PURE__ */ __name(async ({
1241
1173
  template,
1242
1174
  templatePath
@@ -1255,12 +1187,12 @@ ${errorHtmlMsg}
1255
1187
  }
1256
1188
  return spec;
1257
1189
  }, "inferSpec");
1258
- async watch(opt) {
1259
- await super.watch(opt);
1190
+ watch = /* @__PURE__ */ __name(async (opt) => {
1191
+ super.watch(opt);
1260
1192
  knapsackEvents.onPatternTemplateChanged(() => {
1261
1193
  clearInferSpecCache();
1262
1194
  });
1263
- }
1195
+ }, "watch");
1264
1196
  getTemplateMeta = /* @__PURE__ */ __name(async ({
1265
1197
  pattern,
1266
1198
  template
@@ -1303,7 +1235,10 @@ ${errorHtmlMsg}
1303
1235
  }
1304
1236
  return files;
1305
1237
  }, "getTemplateMeta");
1306
- alterTemplateMetaFiles = /* @__PURE__ */ __name(async ({ files, metaDir }) => {
1238
+ alterTemplateMetaFiles = /* @__PURE__ */ __name(async ({
1239
+ files,
1240
+ metaDir
1241
+ }) => {
1307
1242
  const imports = [];
1308
1243
  const ext = ".spec.d.ts";
1309
1244
  files.forEach((file) => {
@@ -1330,9 +1265,9 @@ ${errorHtmlMsg}
1330
1265
  }
1331
1266
  ];
1332
1267
  }, "alterTemplateMetaFiles");
1333
- async getTemplateSuggestions({
1268
+ getTemplateSuggestions = /* @__PURE__ */ __name(async ({
1334
1269
  newPath
1335
- }) {
1270
+ }) => {
1336
1271
  const { data: dataDir } = this.patterns.userConfig;
1337
1272
  const { allTemplateDemos, allTemplates } = this.getMyTemplates();
1338
1273
  const usedSuggestions = [
@@ -1383,7 +1318,7 @@ ${errorHtmlMsg}
1383
1318
  return {
1384
1319
  suggestions
1385
1320
  };
1386
- }
1321
+ }, "getTemplateSuggestions");
1387
1322
  };
1388
1323
  export {
1389
1324
  KnapsackReactRenderer