@knapsack/renderer-react 4.69.9--canary.4768.997c53b.0 → 4.69.9--canary.011c229.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_qww7lehrx3uuw4jfw345astxp4/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.5__@swc+core@1.3.57_@swc+helpers_qewjfurrjspcqzwdqcz2r3oykm/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");
@@ -16,10 +16,8 @@ var __dirname = /* @__PURE__ */ getDirname();
16
16
 
17
17
  // src/renderer-react.ts
18
18
  import sleep from "sleep-promise";
19
- import {
20
- RendererWebpackBase
21
- } from "@knapsack/renderer-webpack-base";
22
- import { pascalCase, isFirstLetterCapital, groupBy } from "@knapsack/utils";
19
+ import { RendererWebpackBase } from "@knapsack/renderer-webpack-base";
20
+ import { pascalCase, isFirstLetterCapital } from "@knapsack/utils";
23
21
  import { knapsackEvents, log as log2 } from "@knapsack/app";
24
22
  import {
25
23
  babelCodeForBrowser,
@@ -65,14 +63,13 @@ function renderUsageTemplate({
65
63
  `;
66
64
  }
67
65
  __name(renderUsageTemplate, "renderUsageTemplate");
68
- var demoAppName = "DemoApp";
69
66
  function renderDemoAppTemplate({
70
- imports = "",
67
+ imports,
71
68
  children
72
69
  }) {
73
70
  return `${imports}
74
71
 
75
- function ${demoAppName}() {
72
+ function DemoApp() {
76
73
  return (
77
74
  ${children}
78
75
  )
@@ -131,14 +128,12 @@ async function getUsage(data) {
131
128
  __name(getUsage, "getUsage");
132
129
  async function getDemoAppUsage({
133
130
  children,
134
- imports,
135
- format
131
+ imports
136
132
  }) {
137
133
  const code = renderDemoAppTemplate({
138
134
  children,
139
135
  imports
140
136
  });
141
- if (!format) return code;
142
137
  return formatCode({
143
138
  contents: code,
144
139
  path: "x.tsx"
@@ -728,9 +723,6 @@ var createReactPattern = createCreator({
728
723
  }, "getTasks")
729
724
  });
730
725
 
731
- // src/types.ts
732
- var rendererMetaScriptTagId = "ks-react-meta";
733
-
734
726
  // src/renderer-react.ts
735
727
  var { pkg } = findUpPkgJson(__dirname);
736
728
  log2.setupUpdateNotifier({ ...pkg, name: pkg.name, version: pkg.version });
@@ -755,11 +747,7 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends RendererWebpack
755
747
  id,
756
748
  extension: ".jsx",
757
749
  language: "jsx",
758
- webpackConfig,
759
- extraScripts: [
760
- // this is the code in `./client/init.mts`
761
- "@knapsack/renderer-react/client"
762
- ]
750
+ webpackConfig
763
751
  });
764
752
  this.language = "jsx";
765
753
  this.assets = [];
@@ -842,82 +830,167 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends RendererWebpack
842
830
  imports: xImports,
843
831
  renderOptions: { pattern, template, demo }
844
832
  }) {
845
- const extraImports = this.getJsImports().filter(
846
- (imp) => imp.type === "extra"
833
+ const extraImportNames = this.getJsImports().flatMap(
834
+ (imp) => imp.type === "extra" ? [imp.importInfo.name] : []
847
835
  );
848
- const { imports, isDeclaredVarsUnique, nameCollisions } = this.makeKsJsImportsUnique({ imports: [...xImports, ...extraImports] });
836
+ const { imports, isDeclaredVarsUnique, nameCollisions } = this.makeKsJsImportsUnique({ imports: xImports });
849
837
  if (!isDeclaredVarsUnique) {
850
838
  log2.error(`${nameCollisions.join(", ")} are declared multiple times`, {
851
839
  imports
852
840
  });
853
841
  }
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
- ];
842
+ const importNames = [
843
+ ...imports.map(({ importInfo: { name } }) => name),
844
+ ...extraImportNames
845
+ ];
846
+ const patternsUsed = imports.flatMap((imp) => {
847
+ if (imp.type === "pattern-template") {
848
+ return [
849
+ {
850
+ patternId: imp.patternId,
851
+ templateId: imp.templateId
874
852
  }
875
- if (imp.type === "pattern-template-demo") {
876
- return [
877
- {
878
- patternId: imp.patternId,
879
- templateId: imp.templateId,
880
- demoId: imp.demoId
881
- }
882
- ];
853
+ ];
854
+ }
855
+ if (imp.type === "pattern-template-demo") {
856
+ return [
857
+ {
858
+ patternId: imp.patternId,
859
+ templateId: imp.templateId,
860
+ demoId: imp.demoId
883
861
  }
884
- return [];
885
- })
862
+ ];
886
863
  }
864
+ return [];
865
+ });
866
+ const demoWrapperProps = {
867
+ patternsUsed,
868
+ pattern,
869
+ template,
870
+ demo
887
871
  };
872
+ const demoWrapperCode = await getUsage({
873
+ templateName: "DemoWrapper",
874
+ props: demoWrapperProps,
875
+ children: `<DemoApp />`
876
+ // extraProps,
877
+ });
878
+ async function renderReact({
879
+ patterns,
880
+ theExtraImportNames,
881
+ ksGlobal
882
+ }) {
883
+ if (!ksGlobal) {
884
+ throw new Error('"window.knapsack" is null');
885
+ }
886
+ const components = await ksGlobal.getAllImports({
887
+ patterns,
888
+ extras: theExtraImportNames.map((name) => ({ name }))
889
+ });
890
+ return components;
891
+ }
892
+ __name(renderReact, "renderReact");
888
893
  let code = `
889
- window.knapsack = window.knapsack || {};
890
- window.knapsack.getDemoApp = ({ ${imports.map((i) => i.importInfo.name).join(", ")} }) => {
891
- ${demoApp}
892
- return ${demoAppName}
894
+
895
+ ${renderReact.toString()}
896
+ ${renderReact.name}({
897
+ ksGlobal: window.knapsack,
898
+ patterns: ${JSON.stringify(patternsUsed)},
899
+ theExtraImportNames: ${JSON.stringify(extraImportNames)},
900
+ }).then((components) => {
901
+ const { ${importNames.join(", ")} } = components;
902
+ const root = document.getElementById('render-root');
903
+
904
+ ${demoApp}
905
+
906
+ const reactDomVersion = parseInt(ReactDOM.version.split('.')[0], 10);
907
+
908
+ const ReactRendererResult = () => {
909
+ if (reactDomVersion < 17 || ${this.disableReactStrictMode}){
910
+ return (
911
+ <ErrorCatcher>
912
+ ${demoWrapperCode}
913
+ </ErrorCatcher>
914
+ )
893
915
  }
916
+
917
+ return (
918
+ <React.StrictMode>
919
+ <ErrorCatcher>
920
+ ${demoWrapperCode}
921
+ </ErrorCatcher>
922
+ </React.StrictMode>
923
+ )
924
+ };
925
+
926
+
927
+ if (reactDomVersion > 17){
928
+ ReactDOM.createRoot(root).render(
929
+ <ReactRendererResult />
930
+ )
931
+ } else {
932
+ ReactDOM.render(
933
+ <ReactRendererResult />,
934
+ root
935
+ );
936
+ }
937
+ }).catch((err) => {
938
+ console.error(err);
939
+ const root = document.getElementById('render-root');
940
+ // Create a new <div> element to contain the error message
941
+ const errorMsgDiv = document.createElement('div');
942
+ // Insert the new <div> element before the existing element
943
+ root.parentNode.insertBefore(errorMsgDiv, root);
944
+ // add error message so users can see it
945
+ errorMsgDiv.innerHTML = '<h1>Component Error</h1><p>' + err.message + '</p>';
946
+ });
894
947
  `;
948
+ let codeHadError = false;
895
949
  let errorHtmlMsg = "";
896
950
  try {
897
- code = await babelCodeForBrowser({ code });
951
+ code = await babelCodeForBrowser({
952
+ code
953
+ });
898
954
  } catch (e) {
955
+ codeHadError = true;
899
956
  console.log(code);
900
957
  console.log("---original code before babel error ^---");
901
958
  console.trace(e.message);
902
959
  code = `console.error(${JSON.stringify(e.message)});`;
903
960
  errorHtmlMsg = `<pre><code>${e.message}</code></pre>`;
904
961
  }
962
+ if (!codeHadError) {
963
+ try {
964
+ code = await formatCode2({
965
+ contents: code,
966
+ path: "x.tsx"
967
+ // doing this to set format language
968
+ });
969
+ } catch (e) {
970
+ codeHadError = true;
971
+ console.log(code);
972
+ console.log("---original code before prettier error ^---");
973
+ console.trace(e.message);
974
+ code = `console.error(${JSON.stringify(e.message)});`;
975
+ errorHtmlMsg = `<pre><code>${e.message}</code></pre>`;
976
+ }
977
+ }
905
978
  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>
911
979
  ${this.assets.map((asset) => `<script src="${asset}"></script>`).join("\n")}
980
+
912
981
  ${this.createHtmlTagsForAssetPaths({
913
982
  assets: this.getWebpackAssetPaths(),
914
983
  // 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
915
984
  scriptTagsAreAsync: false
916
985
  })}
917
- ${errorHtmlMsg}
986
+
987
+ <div id="render-root" class="knapsack-pattern-direct-parent" data-dev-note="Knapsack React Template Wrapper"></div>
988
+ <script type="application/javascript">${code}</script>
989
+ ${errorHtmlMsg}
990
+
918
991
  `;
919
992
  return {
920
- ok: !errorHtmlMsg,
993
+ ok: !codeHadError,
921
994
  html: await formatCode2({
922
995
  contents: html,
923
996
  path: "x.html"
@@ -978,8 +1051,7 @@ var KnapsackReactRenderer = class _KnapsackReactRenderer extends RendererWebpack
978
1051
  const [demoAppUsage, demoApp] = await Promise.all([
979
1052
  getDemoAppUsage({
980
1053
  children: usage,
981
- imports: importCode,
982
- format: true
1054
+ imports: importCode
983
1055
  }),
984
1056
  getDemoAppUsage({
985
1057
  children: usage