@dr.pogodin/react-utils 1.47.0-alpha.1 → 1.47.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/build/development/client/getInj.js.map +1 -1
  2. package/build/development/client/index.js.map +1 -1
  3. package/build/development/client/init.js.map +1 -1
  4. package/build/development/index.js +3 -4
  5. package/build/development/index.js.map +1 -1
  6. package/build/development/server/server.js +11 -10
  7. package/build/development/server/server.js.map +1 -1
  8. package/build/development/shared/utils/config.js +5 -6
  9. package/build/development/shared/utils/config.js.map +1 -1
  10. package/build/development/shared/utils/splitComponent.js +18 -22
  11. package/build/development/shared/utils/splitComponent.js.map +1 -1
  12. package/build/production/client/getInj.js.map +1 -1
  13. package/build/production/client/index.js.map +1 -1
  14. package/build/production/client/init.js.map +1 -1
  15. package/build/production/index.js +2 -3
  16. package/build/production/index.js.map +1 -1
  17. package/build/production/server/server.js +2 -4
  18. package/build/production/server/server.js.map +1 -1
  19. package/build/production/shared/utils/config.js +3 -5
  20. package/build/production/shared/utils/config.js.map +1 -1
  21. package/build/production/shared/utils/splitComponent.js +6 -17
  22. package/build/production/shared/utils/splitComponent.js.map +1 -1
  23. package/build/types-code/index.d.ts +2 -2
  24. package/build/web/client/getInj.js +9 -16
  25. package/build/web/client/getInj.js.map +1 -1
  26. package/build/web/client/index.js +14 -21
  27. package/build/web/client/index.js.map +1 -1
  28. package/build/web/client/init.js +2 -4
  29. package/build/web/client/init.js.map +1 -1
  30. package/build/web/index.js +2 -4
  31. package/build/web/index.js.map +1 -1
  32. package/build/web/server/server.js +10 -8
  33. package/build/web/server/server.js.map +1 -1
  34. package/build/web/shared/utils/config.js +4 -6
  35. package/build/web/shared/utils/config.js.map +1 -1
  36. package/build/web/shared/utils/splitComponent.js +17 -20
  37. package/build/web/shared/utils/splitComponent.js.map +1 -1
  38. package/config/jest/default.js +7 -2
  39. package/package.json +9 -8
  40. package/src/index.ts +3 -7
  41. package/src/server/server.ts +10 -10
  42. package/src/shared/utils/config.ts +5 -10
  43. package/src/shared/utils/splitComponent.tsx +17 -20
  44. package/node-entry.js +0 -15
@@ -1 +1 @@
1
- {"version":3,"file":"getInj.js","names":["_forge","_interopRequireDefault","require","_buildInfo","inj","metaElement","document","querySelector","remove","data","default","util","decode64","content","key","getBuildInfo","d","cipher","createDecipher","start","iv","slice","length","update","createBuffer","finish","decodeUtf8","output","eval","window","REACT_UTILS_INJECTION","getInj"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\n// Note: this way, only required part of \"node-forge\": AES, and some utils,\n// is bundled into client-side code.\nimport forge from 'node-forge/lib/forge';\n\n// eslint-disable-next-line import/no-unassigned-import\nimport 'node-forge/lib/aes';\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\n// Safeguard is needed here, because the server-side version of Docusaurus docs\n// is compiled (at least now) with settings suggesting it is a client-side\n// environment, but there is no document.\nlet inj: InjT = {};\n\nconst metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\nif (metaElement) {\n metaElement.remove();\n let data = forge.util.decode64(metaElement.content);\n\n const { key } = getBuildInfo();\n const d = forge.cipher.createDecipher('AES-CBC', key);\n d.start({ iv: data.slice(0, key.length) });\n d.update(forge.util.createBuffer(data.slice(key.length)));\n d.finish();\n\n data = forge.util.decodeUtf8(d.output.data);\n\n // TODO: Double-check, if there is a safer alternative to parse it?\n // eslint-disable-next-line no-eval\n inj = eval(`(${data})`) as InjT;\n} else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n inj = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n} else {\n // Otherwise, a bunch of dependent stuff will easily fail in non-standard\n // environments, where no client-side initialization is performed. Like tests,\n // Docusaurus examples, etc.\n inj = {};\n}\n\nexport default function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C,qBAAqB,EAAE;EACxE1B,GAAG,GAAGyB,MAAM,CAACC,qBAAqB;EAClC,OAAOD,MAAM,CAACC,qBAAqB;AACrC,CAAC,MAAM;EACL;EACA;EACA;EACA1B,GAAG,GAAG,CAAC,CAAC;AACV;AAEe,SAAS2B,MAAMA,CAAA,EAAS;EACrC,OAAO3B,GAAG;AACZ","ignoreList":[]}
1
+ {"version":3,"file":"getInj.js","names":["_forge","_interopRequireDefault","require","_buildInfo","inj","metaElement","document","querySelector","remove","data","forge","util","decode64","content","key","getBuildInfo","d","cipher","createDecipher","start","iv","slice","length","update","createBuffer","finish","decodeUtf8","output","eval","window","REACT_UTILS_INJECTION","getInj"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\n// Note: this way, only required part of \"node-forge\": AES, and some utils,\n// is bundled into client-side code.\nimport forge from 'node-forge/lib/forge';\n\n// eslint-disable-next-line import/no-unassigned-import\nimport 'node-forge/lib/aes';\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\n// Safeguard is needed here, because the server-side version of Docusaurus docs\n// is compiled (at least now) with settings suggesting it is a client-side\n// environment, but there is no document.\nlet inj: InjT = {};\n\nconst metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\nif (metaElement) {\n metaElement.remove();\n let data = forge.util.decode64(metaElement.content);\n\n const { key } = getBuildInfo();\n const d = forge.cipher.createDecipher('AES-CBC', key);\n d.start({ iv: data.slice(0, key.length) });\n d.update(forge.util.createBuffer(data.slice(key.length)));\n d.finish();\n\n data = forge.util.decodeUtf8(d.output.data);\n\n // TODO: Double-check, if there is a safer alternative to parse it?\n // eslint-disable-next-line no-eval\n inj = eval(`(${data})`) as InjT;\n} else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n inj = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n} else {\n // Otherwise, a bunch of dependent stuff will easily fail in non-standard\n // environments, where no client-side initialization is performed. Like tests,\n // Docusaurus examples, etc.\n inj = {};\n}\n\nexport default function getInj(): InjT {\n return inj;\n}\n"],"mappings":";;;;;;;AAMA,IAAAA,MAAA,GAAAC,sBAAA,CAAAC,OAAA;AAGAA,OAAA;AAIA,IAAAC,UAAA,GAAAD,OAAA;AAbA;;AAEA;;AAEA;AACA;;AAGA;;AAOA;AACA;AACA;AACA,IAAIE,GAAS,GAAG,CAAC,CAAC;AAElB,MAAMC,WAAmC,GAAG,OAAOC,QAAQ,KAAK,WAAW,GACvE,IAAI,GAAGA,QAAQ,CAACC,aAAa,CAAC,2BAA2B,CAAC;AAE9D,IAAIF,WAAW,EAAE;EACfA,WAAW,CAACG,MAAM,CAAC,CAAC;EACpB,IAAIC,IAAI,GAAGC,cAAK,CAACC,IAAI,CAACC,QAAQ,CAACP,WAAW,CAACQ,OAAO,CAAC;EAEnD,MAAM;IAAEC;EAAI,CAAC,GAAG,IAAAC,uBAAY,EAAC,CAAC;EAC9B,MAAMC,CAAC,GAAGN,cAAK,CAACO,MAAM,CAACC,cAAc,CAAC,SAAS,EAAEJ,GAAG,CAAC;EACrDE,CAAC,CAACG,KAAK,CAAC;IAAEC,EAAE,EAAEX,IAAI,CAACY,KAAK,CAAC,CAAC,EAAEP,GAAG,CAACQ,MAAM;EAAE,CAAC,CAAC;EAC1CN,CAAC,CAACO,MAAM,CAACb,cAAK,CAACC,IAAI,CAACa,YAAY,CAACf,IAAI,CAACY,KAAK,CAACP,GAAG,CAACQ,MAAM,CAAC,CAAC,CAAC;EACzDN,CAAC,CAACS,MAAM,CAAC,CAAC;EAEVhB,IAAI,GAAGC,cAAK,CAACC,IAAI,CAACe,UAAU,CAACV,CAAC,CAACW,MAAM,CAAClB,IAAI,CAAC;;EAE3C;EACA;EACAL,GAAG,GAAGwB,IAAI,CAAC,IAAInB,IAAI,GAAG,CAAS;AACjC,CAAC,MAAM,IAAI,OAAOoB,MAAM,KAAK,WAAW,IAAIA,MAAM,CAACC,qBAAqB,EAAE;EACxE1B,GAAG,GAAGyB,MAAM,CAACC,qBAAqB;EAClC,OAAOD,MAAM,CAACC,qBAAqB;AACrC,CAAC,MAAM;EACL;EACA;EACA;EACA1B,GAAG,GAAG,CAAC,CAAC;AACV;AAEe,SAAS2B,MAAMA,CAAA,EAAS;EACrC,OAAO3B,GAAG;AACZ","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_client","require","_reactHelmet","_reactRouter","_reactGlobalState","_getInj","_interopRequireDefault","_jsxRuntime","Launch","Application","options","container","document","getElementById","Error","scene","jsx","GlobalStateProvider","initialState","default","ISTATE","children","BrowserRouter","HelmetProvider","dontHydrate","root","createRoot","render","hydrateRoot"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport type { ComponentType } from 'react';\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { BrowserRouter } from 'react-router';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: unknown;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport default function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n): void {\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={getInj().ISTATE ?? options.initialState}>\n <BrowserRouter>\n <HelmetProvider>\n <Application />\n </HelmetProvider>\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":";;;;;;;AAIA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,YAAA,GAAAD,OAAA;AACA,IAAAE,YAAA,GAAAF,OAAA;AAEA,IAAAG,iBAAA,GAAAH,OAAA;AAEA,IAAAI,OAAA,GAAAC,sBAAA,CAAAL,OAAA;AAA8B,IAAAM,WAAA,GAAAN,OAAA;AAV9B;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACe,SAASO,MAAMA,CAC5BC,WAA0B,EAC1BC,OAAiB,GAAG,CAAC,CAAC,EAChB;EACN,MAAMC,SAAS,GAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC;EACvD,IAAI,CAACF,SAAS,EAAE,MAAMG,KAAK,CAAC,wCAAwC,CAAC;EACrE,MAAMC,KAAK,gBACT,IAAAR,WAAA,CAAAS,GAAA,EAACZ,iBAAA,CAAAa,mBAAmB;IAACC,YAAY,EAAE,IAAAb,OAAA,CAAAc,OAAM,EAAC,CAAC,CAACC,MAAM,IAAIV,OAAO,CAACQ,YAAa;IAAAG,QAAA,eACzE,IAAAd,WAAA,CAAAS,GAAA,EAACb,YAAA,CAAAmB,aAAa;MAAAD,QAAA,eACZ,IAAAd,WAAA,CAAAS,GAAA,EAACd,YAAA,CAAAqB,cAAc;QAAAF,QAAA,eACb,IAAAd,WAAA,CAAAS,GAAA,EAACP,WAAW,IAAE;MAAC,CACD;IAAC,CACJ;EAAC,CACG,CACtB;EAED,IAAIC,OAAO,CAACc,WAAW,EAAE;IACvB,MAAMC,IAAI,GAAG,IAAAzB,OAAA,CAAA0B,UAAU,EAACf,SAAS,CAAC;IAClCc,IAAI,CAACE,MAAM,CAACZ,KAAK,CAAC;EACpB,CAAC,MAAM,IAAAf,OAAA,CAAA4B,WAAW,EAACjB,SAAS,EAAEI,KAAK,CAAC;AACtC","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_client","require","_reactHelmet","_reactRouter","_reactGlobalState","_getInj","_interopRequireDefault","_jsxRuntime","Launch","Application","options","container","document","getElementById","Error","scene","_jsx","GlobalStateProvider","initialState","getInj","ISTATE","children","BrowserRouter","HelmetProvider","dontHydrate","root","createRoot","render","hydrateRoot"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport type { ComponentType } from 'react';\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { BrowserRouter } from 'react-router';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: unknown;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport default function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n): void {\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={getInj().ISTATE ?? options.initialState}>\n <BrowserRouter>\n <HelmetProvider>\n <Application />\n </HelmetProvider>\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":";;;;;;;AAIA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,YAAA,GAAAD,OAAA;AACA,IAAAE,YAAA,GAAAF,OAAA;AAEA,IAAAG,iBAAA,GAAAH,OAAA;AAEA,IAAAI,OAAA,GAAAC,sBAAA,CAAAL,OAAA;AAA8B,IAAAM,WAAA,GAAAN,OAAA;AAV9B;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACe,SAASO,MAAMA,CAC5BC,WAA0B,EAC1BC,OAAiB,GAAG,CAAC,CAAC,EAChB;EACN,MAAMC,SAAS,GAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC;EACvD,IAAI,CAACF,SAAS,EAAE,MAAMG,KAAK,CAAC,wCAAwC,CAAC;EACrE,MAAMC,KAAK,gBACT,IAAAC,eAAA,EAACC,qCAAmB;IAACC,YAAY,EAAE,IAAAC,eAAM,EAAC,CAAC,CAACC,MAAM,IAAIV,OAAO,CAACQ,YAAa;IAAAG,QAAA,eACzE,IAAAL,eAAA,EAACM,0BAAa;MAAAD,QAAA,eACZ,IAAAL,eAAA,EAACO,2BAAc;QAAAF,QAAA,eACb,IAAAL,eAAA,EAACP,WAAW,IAAE;MAAC,CACD;IAAC,CACJ;EAAC,CACG,CACtB;EAED,IAAIC,OAAO,CAACc,WAAW,EAAE;IACvB,MAAMC,IAAI,GAAG,IAAAC,kBAAU,EAACf,SAAS,CAAC;IAClCc,IAAI,CAACE,MAAM,CAACZ,KAAK,CAAC;EACpB,CAAC,MAAM,IAAAa,mBAAW,EAACjB,SAAS,EAAEI,KAAK,CAAC;AACtC","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"init.js","names":["_buildInfo","require","buildInfo","getBuildInfo","process","env","NODE_ENV","console","warn","window","__DEV_BUILD_INFO__","BUILD_INFO","useServiceWorker","navigator","addEventListener","reg","serviceWorker","register","log","err"],"sources":["../../../src/client/init.ts"],"sourcesContent":["/**\n * Initialization of client-side environment.\n */\n\n/* global window */\n\nimport { type BuildInfoT, getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nconst buildInfo = getBuildInfo();\n\n// TODO: Should be moved into buildInfo module?\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n __DEV_BUILD_INFO__: BuildInfoT | undefined;\n }\n}\n\ndeclare const BUILD_INFO: BuildInfoT | undefined;\n\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.warn('Dev mode: \"BUILD_INFO\" attached to the global \"window\"');\n\n // eslint-disable-next-line no-underscore-dangle\n window.__DEV_BUILD_INFO__ = BUILD_INFO;\n}\n\n/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */\nconst { useServiceWorker } = buildInfo;\nif (useServiceWorker) {\n const { navigator } = window;\n if ('serviceWorker' in navigator) {\n window.addEventListener('load', () => {\n void (async () => {\n try {\n // Note: no matter the \"publicPath\", we want to serve the service worker\n // from the web app root, to allow it control any and all pages of the\n // web app (otherwise, it will be restricted to the scope of its path).\n // The server takes it into account.\n const reg = await navigator\n .serviceWorker.register('/__service-worker.js');\n // eslint-disable-next-line no-console\n console.log('SW registered:', reg);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.log('SW registration failed:', err);\n }\n })();\n });\n }\n}\n"],"mappings":";;AAMA,IAAAA,UAAA,GAAAC,OAAA;AANA;AACA;AACA;;AAEA;;AAIA,MAAMC,SAAS,GAAG,IAAAF,UAAA,CAAAG,YAAY,EAAC,CAAC;;AAEhC;;AAUA,IAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;EACzC;EACAC,OAAO,CAACC,IAAI,CAAC,wDAAwD,CAAC;;EAEtE;EACAC,MAAM,CAACC,kBAAkB,GAAGC,UAAU;AACxC;;AAEA;AACA,MAAM;EAAEC;AAAiB,CAAC,GAAGV,SAAS;AACtC,IAAIU,gBAAgB,EAAE;EACpB,MAAM;IAAEC;EAAU,CAAC,GAAGJ,MAAM;EAC5B,IAAI,eAAe,IAAII,SAAS,EAAE;IAChCJ,MAAM,CAACK,gBAAgB,CAAC,MAAM,EAAE,MAAM;MACpC,KAAK,CAAC,YAAY;QAChB,IAAI;UACF;UACA;UACA;UACA;UACA,MAAMC,GAAG,GAAG,MAAMF,SAAS,CACxBG,aAAa,CAACC,QAAQ,CAAC,sBAAsB,CAAC;UACjD;UACAV,OAAO,CAACW,GAAG,CAAC,gBAAgB,EAAEH,GAAG,CAAC;QACpC,CAAC,CAAC,OAAOI,GAAG,EAAE;UACZ;UACAZ,OAAO,CAACW,GAAG,CAAC,yBAAyB,EAAEC,GAAG,CAAC;QAC7C;MACF,CAAC,EAAE,CAAC;IACN,CAAC,CAAC;EACJ;AACF","ignoreList":[]}
1
+ {"version":3,"file":"init.js","names":["_buildInfo","require","buildInfo","getBuildInfo","process","env","NODE_ENV","console","warn","window","__DEV_BUILD_INFO__","BUILD_INFO","useServiceWorker","navigator","addEventListener","reg","serviceWorker","register","log","err"],"sources":["../../../src/client/init.ts"],"sourcesContent":["/**\n * Initialization of client-side environment.\n */\n\n/* global window */\n\nimport { type BuildInfoT, getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nconst buildInfo = getBuildInfo();\n\n// TODO: Should be moved into buildInfo module?\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n __DEV_BUILD_INFO__: BuildInfoT | undefined;\n }\n}\n\ndeclare const BUILD_INFO: BuildInfoT | undefined;\n\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.warn('Dev mode: \"BUILD_INFO\" attached to the global \"window\"');\n\n // eslint-disable-next-line no-underscore-dangle\n window.__DEV_BUILD_INFO__ = BUILD_INFO;\n}\n\n/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */\nconst { useServiceWorker } = buildInfo;\nif (useServiceWorker) {\n const { navigator } = window;\n if ('serviceWorker' in navigator) {\n window.addEventListener('load', () => {\n void (async () => {\n try {\n // Note: no matter the \"publicPath\", we want to serve the service worker\n // from the web app root, to allow it control any and all pages of the\n // web app (otherwise, it will be restricted to the scope of its path).\n // The server takes it into account.\n const reg = await navigator\n .serviceWorker.register('/__service-worker.js');\n // eslint-disable-next-line no-console\n console.log('SW registered:', reg);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.log('SW registration failed:', err);\n }\n })();\n });\n }\n}\n"],"mappings":";;AAMA,IAAAA,UAAA,GAAAC,OAAA;AANA;AACA;AACA;;AAEA;;AAIA,MAAMC,SAAS,GAAG,IAAAC,uBAAY,EAAC,CAAC;;AAEhC;;AAUA,IAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;EACzC;EACAC,OAAO,CAACC,IAAI,CAAC,wDAAwD,CAAC;;EAEtE;EACAC,MAAM,CAACC,kBAAkB,GAAGC,UAAU;AACxC;;AAEA;AACA,MAAM;EAAEC;AAAiB,CAAC,GAAGV,SAAS;AACtC,IAAIU,gBAAgB,EAAE;EACpB,MAAM;IAAEC;EAAU,CAAC,GAAGJ,MAAM;EAC5B,IAAI,eAAe,IAAII,SAAS,EAAE;IAChCJ,MAAM,CAACK,gBAAgB,CAAC,MAAM,EAAE,MAAM;MACpC,KAAK,CAAC,YAAY;QAChB,IAAI;UACF;UACA;UACA;UACA;UACA,MAAMC,GAAG,GAAG,MAAMF,SAAS,CACxBG,aAAa,CAACC,QAAQ,CAAC,sBAAsB,CAAC;UACjD;UACAV,OAAO,CAACW,GAAG,CAAC,gBAAgB,EAAEH,GAAG,CAAC;QACpC,CAAC,CAAC,OAAOI,GAAG,EAAE;UACZ;UACAZ,OAAO,CAACW,GAAG,CAAC,yBAAyB,EAAEC,GAAG,CAAC;QAC7C;MACF,CAAC,EAAE,CAAC;IACN,CAAC,CAAC;EACJ;AACF","ignoreList":[]}
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
 
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
3
4
  Object.defineProperty(exports, "__esModule", {
4
5
  value: true
5
6
  });
@@ -156,6 +157,7 @@ Object.defineProperty(exports, "withRetries", {
156
157
  return _utils.withRetries;
157
158
  }
158
159
  });
160
+ var _client = _interopRequireDefault(require("./client"));
159
161
  var _utils = require("./shared/utils");
160
162
  var _reactGlobalState = require("@dr.pogodin/react-global-state");
161
163
  var _components = require("./shared/components");
@@ -184,8 +186,5 @@ if (global.REACT_UTILS_LIBRARY_LOADED) {
184
186
  let dirname = require('url').pathToFileURL(__filename).toString();
185
187
  dirname = dirname.slice(5, dirname.lastIndexOf('/'));
186
188
  const server = exports.server = _utils.webpack.requireWeak("./server", dirname);
187
- const client = exports.client = server ? undefined
188
-
189
- // eslint-disable-next-line @typescript-eslint/no-require-imports
190
- : require("./client").default;
189
+ const client = exports.client = server ? undefined : _client.default;
191
190
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_utils","require","_reactGlobalState","_components","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","global","REACT_UTILS_LIBRARY_LOADED","Error","dirname","pathToFileURL","__filename","toString","slice","lastIndexOf","server","webpack","requireWeak","client","undefined","default"],"sources":["../../src/index.ts"],"sourcesContent":["import 'styles/global.scss';\n\nimport { webpack } from 'utils';\n\nimport type * as ClientM from './client';\nimport type * as ServerFactoryM from './server';\n\n// It is a safeguard against multiple instances / versions of the library\n// being loaded into environment by mistake (e.g. because of different\n// packages pinning down different exact versions of the lib, thus preventing\n// a proper dedupe and using a single common library version).\nif (global.REACT_UTILS_LIBRARY_LOADED) {\n throw Error('React utils library is already loaded');\n} else global.REACT_UTILS_LIBRARY_LOADED = true;\n\n// TODO: This is a rapid workaround to get rid of __dirname. I guess, later\n// we'll re-implement requireWeak() to accept import.meta.url directly, and\n// this workaround won't be needed.\nlet dirname = import.meta.url;\ndirname = dirname.slice(5, dirname.lastIndexOf('/'));\n\nconst server = webpack.requireWeak<typeof ServerFactoryM>('./server', dirname);\n\nconst client = server\n ? undefined\n\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n : (require('./client') as typeof ClientM).default;\n\nexport {\n type AsyncCollectionT,\n type AsyncCollectionLoaderT,\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type ForceT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateResT,\n type ValueOrInitializerT,\n getGlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n withGlobalStateType,\n} from '@dr.pogodin/react-global-state';\n\nexport * from 'components';\n\nexport {\n type BeforeRenderResT,\n type BeforeRenderT,\n type ConfigT,\n type ServerSsrContext,\n type ServerT,\n} from './server';\n\nexport {\n assertEmptyObject,\n config,\n Barrier,\n Cached,\n Emitter,\n isomorphy,\n getSsrContext,\n type Listener,\n type ObjectKey,\n Semaphore,\n splitComponent,\n type Theme,\n themed,\n Theme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M,GAAAhB,OAAA,CAAAgB,MAAA,GAAGH,MAAM,GACjBI;;AAEF;AAAA,EACG5B,OAAO,WAAW,CAAC,CAAoB6B,OAAO","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_client","_interopRequireDefault","require","_utils","_reactGlobalState","_components","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","global","REACT_UTILS_LIBRARY_LOADED","Error","dirname","pathToFileURL","__filename","toString","slice","lastIndexOf","server","webpack","requireWeak","client","undefined","clientModule"],"sources":["../../src/index.ts"],"sourcesContent":["import 'styles/global.scss';\n\nimport clientModule from './client';\nimport { webpack } from './shared/utils';\n\nimport type * as ServerFactoryM from './server';\n\n// It is a safeguard against multiple instances / versions of the library\n// being loaded into environment by mistake (e.g. because of different\n// packages pinning down different exact versions of the lib, thus preventing\n// a proper dedupe and using a single common library version).\nif (global.REACT_UTILS_LIBRARY_LOADED) {\n throw Error('React utils library is already loaded');\n} else global.REACT_UTILS_LIBRARY_LOADED = true;\n\n// TODO: This is a rapid workaround to get rid of __dirname. I guess, later\n// we'll re-implement requireWeak() to accept import.meta.url directly, and\n// this workaround won't be needed.\nlet dirname = import.meta.url;\ndirname = dirname.slice(5, dirname.lastIndexOf('/'));\n\nconst server = webpack.requireWeak<typeof ServerFactoryM>('./server', dirname);\n\nconst client = server ? undefined : clientModule;\n\nexport {\n type AsyncCollectionT,\n type AsyncCollectionLoaderT,\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type ForceT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateResT,\n type ValueOrInitializerT,\n getGlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n withGlobalStateType,\n} from '@dr.pogodin/react-global-state';\n\nexport * from 'components';\n\nexport {\n type BeforeRenderResT,\n type BeforeRenderT,\n type ConfigT,\n type ServerSsrContext,\n type ServerT,\n} from './server';\n\nexport {\n assertEmptyObject,\n config,\n Barrier,\n Cached,\n Emitter,\n isomorphy,\n getSsrContext,\n type Listener,\n type ObjectKey,\n Semaphore,\n splitComponent,\n type Theme,\n themed,\n ThemeProvider,\n time,\n webpack,\n withRetries,\n} from 'utils';\n\nexport { client, server };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,IAAAA,OAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,MAAA,GAAAD,OAAA;AAsBA,IAAAE,iBAAA,GAAAF,OAAA;AAmBA,IAAAG,WAAA,GAAAH,OAAA;AAAAI,MAAA,CAAAC,IAAA,CAAAF,WAAA,EAAAG,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,EAAAJ,GAAA;EAAA,IAAAA,GAAA,IAAAK,OAAA,IAAAA,OAAA,CAAAL,GAAA,MAAAJ,WAAA,CAAAI,GAAA;EAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,EAAAL,GAAA;IAAAO,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAZ,WAAA,CAAAI,GAAA;IAAA;EAAA;AAAA;AArCA;AACA;AACA;AACA;AACA,IAAIS,MAAM,CAACC,0BAA0B,EAAE;EACrC,MAAMC,KAAK,CAAC,uCAAuC,CAAC;AACtD,CAAC,MAAMF,MAAM,CAACC,0BAA0B,GAAG,IAAI;;AAE/C;AACA;AACA;AACA,IAAIE,OAAO,GAAAnB,OAAA,QAAAoB,aAAA,CAAAC,UAAA,EAAAC,QAAA,EAAkB;AAC7BH,OAAO,GAAGA,OAAO,CAACI,KAAK,CAAC,CAAC,EAAEJ,OAAO,CAACK,WAAW,CAAC,GAAG,CAAC,CAAC;AAEpD,MAAMC,MAAM,GAAAb,OAAA,CAAAa,MAAA,GAAGC,cAAO,CAACC,WAAW,aAAoCR,OAAO,CAAC;AAE9E,MAAMS,MAAM,GAAAhB,OAAA,CAAAgB,MAAA,GAAGH,MAAM,GAAGI,SAAS,GAAGC,eAAY","ignoreList":[]}
@@ -22,10 +22,9 @@ var _requestIp = _interopRequireDefault(require("request-ip"));
22
22
  var _uuid = require("uuid");
23
23
  var _renderer = _interopRequireDefault(require("./renderer"));
24
24
  var _errors = require("./utils/errors");
25
- /**
25
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } /**
26
26
  * Creation of standard ExpressJS server for ReactJS apps.
27
27
  */
28
-
29
28
  // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
30
29
 
31
30
  /**
@@ -172,15 +171,17 @@ async function factory(webpackConfig, options) {
172
171
  href: `${(0, _nodeUrl.pathToFileURL)(process.cwd()).href}${_nodePath.sep}`
173
172
  };
174
173
  }
175
-
176
- /* eslint-disable @typescript-eslint/no-require-imports */
177
- const webpack = require('webpack');
178
-
179
- // TODO: Figure out the exact type for options, don't wanna waste time on it
180
- // right now.
181
- const webpackDevMiddleware = require('webpack-dev-middleware');
182
- const webpackHotMiddleware = require('webpack-hot-middleware');
174
+ const {
175
+ webpack
176
+ } = await Promise.resolve().then(() => _interopRequireWildcard(require(/* webpackChunkName: "server-side-code" */'webpack')));
177
+ const {
178
+ default: webpackDevMiddleware
179
+ } = await Promise.resolve().then(() => _interopRequireWildcard(require(/* webpackChunkName: "server-side-code" */'webpack-dev-middleware')));
180
+ const {
181
+ default: webpackHotMiddleware
182
+ } = await Promise.resolve().then(() => _interopRequireWildcard(require(/* webpackChunkName: "server-side-code" */'webpack-hot-middleware')));
183
183
  const compiler = webpack(webpackConfig);
184
+ if (!compiler) throw Error('Internal error');
184
185
  server.use(webpackDevMiddleware(compiler, {
185
186
  publicPath,
186
187
  serverSideRender: true
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":["_nodePath","require","_nodeUrl","_cloneDeep","_interopRequireDefault","_mapValues","_pick","_compression","_cookieParser","_csurf","_express","_serveFavicon","_helmet","_morgan","_requestIp","_uuid","_renderer","_errors","defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","cookieSignatureSecret","requestIp","mw","csrf","cookie","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","getErrorForCode","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport cloneDeep from 'lodash/cloneDeep';\nimport mapValues from 'lodash/mapValues';\nimport pick from 'lodash/pick';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\n\nimport express, {\n type Express,\n type NextFunction,\n type RequestHandler,\n type Request,\n type Response,\n} from 'express';\n\nimport favicon from 'serve-favicon';\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport type { Compiler, Configuration } from 'webpack';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT = Exclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => boolean | Promise<boolean>;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cookieSignatureSecret?: string;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser(options.cookieSignatureSecret));\n server.use(requestIp.mw());\n\n server.use(csrf({ cookie: true }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n /* eslint-disable @typescript-eslint/no-require-imports */\n const webpack = require('webpack') as (ops: Configuration) => Compiler;\n\n // TODO: Figure out the exact type for options, don't wanna waste time on it\n // right now.\n const webpackDevMiddleware = require('webpack-dev-middleware') as\n (c: Compiler, ops: unknown) => RequestHandler;\n\n const webpackHotMiddleware = require('webpack-hot-middleware') as\n (c: Compiler) => RequestHandler;\n\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":";;;;;;;;AAIA,IAAAA,SAAA,GAAAC,OAAA;AACA,IAAAC,QAAA,GAAAD,OAAA;AAEA,IAAAE,UAAA,GAAAC,sBAAA,CAAAH,OAAA;AACA,IAAAI,UAAA,GAAAD,sBAAA,CAAAH,OAAA;AACA,IAAAK,KAAA,GAAAF,sBAAA,CAAAH,OAAA;AAEA,IAAAM,YAAA,GAAAH,sBAAA,CAAAH,OAAA;AACA,IAAAO,aAAA,GAAAJ,sBAAA,CAAAH,OAAA;AACA,IAAAQ,MAAA,GAAAL,sBAAA,CAAAH,OAAA;AAEA,IAAAS,QAAA,GAAAN,sBAAA,CAAAH,OAAA;AAQA,IAAAU,aAAA,GAAAP,sBAAA,CAAAH,OAAA;AACA,IAAAW,OAAA,GAAAR,sBAAA,CAAAH,OAAA;AACA,IAAAY,OAAA,GAAAT,sBAAA,CAAAH,OAAA;AACA,IAAAa,UAAA,GAAAV,sBAAA,CAAAH,OAAA;AACA,IAAAc,KAAA,GAAAd,OAAA;AAIA,IAAAe,SAAA,GAAAZ,sBAAA,CAAAH,OAAA;AAKA,IAAAgB,OAAA,GAAAhB,OAAA;AApCA;AACA;AACA;;AA2CA;;AAMA;AACA;AACA;AACA;AACA,MAAMiB,kBAAkB,GAAG;EACzBC,UAAU,EAAE,IAAAC,kBAAS,EACnBC,eAAM,CAACC,qBAAqB,CAACC,oBAAoB,CAAC,CAAC;EAEnD;EACA;EACA;EACA;EACCC,KAAK,IAAMA,KAAK,CAAcC,MAAM,CAAEC,IAAY,IAAKA,IAAI,KAAK,QAAQ,CAC3E;AACF,CAAC;AACDR,kBAAkB,CAACC,UAAU,CAAC,WAAW,CAAC,GAAG,CAC3C,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,IAAAyD,gBAAQ,EAACC,cAAM,CAACC,SAAS,EAAEC,aAAK,CAACD,SAAS,CAAC,CAAC;EACnD,CAAC,CAAC;EAEF,IAAIE,6BAA6B;EACjC,IAAI5E,OAAO,CAAC6E,oBAAoB,EAAE;IAChCD,6BAA6B,GAAG,MAAM5E,OAAO,CAAC6E,oBAAoB,CAACtE,MAAM,CAAC;EAC5E;;EAEA;EACA,IAAI,CAACqE,6BAA6B,EAAE;IAClC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACArE,MAAM,CAACK,GAAG,CAAC,CACTkE,KAEC,EACDjE,GAAY,EACZC,GAAa,EACbC,IAAkB,KACf;MACH;MACA;MACA,IAAID,GAAG,CAACiE,WAAW,EAAE;QACnBhE,IAAI,CAAC+D,KAAK,CAAC;QACX;MACF;MAEA,MAAME,MAAM,GAAGF,KAAK,CAACE,MAAM,IAAIL,aAAK,CAACM,qBAAqB;MAC1D,MAAMC,UAAU,GAAGF,MAAM,IAAKL,aAAK,CAACM,qBAAgC;;MAEpE;MACAjF,OAAO,CAACU,MAAM,CAAEyE,GAAG,CAACD,UAAU,GAAG,OAAO,GAAG,OAAO,EAAEJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC;MAErE,IAAIC,OAAO,GAAGP,KAAK,CAACO,OAAO,IAAI,IAAAC,uBAAe,EAACN,MAAM,CAAC;MACtD,IAAIE,UAAU,IAAInB,OAAO,CAACwB,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;QACvDH,OAAO,GAAGZ,cAAM,CAACQ,qBAAqB;MACxC;MAEAnE,GAAG,CAACkE,MAAM,CAACA,MAAM,CAAC,CAAC9C,IAAI,CAACmD,OAAO,CAAC;IAClC,CAAC,CAAC;EACJ;EAEA,OAAO9E,MAAM;AACf","ignoreList":[]}
1
+ {"version":3,"file":"server.js","names":["_nodePath","require","_nodeUrl","_cloneDeep","_interopRequireDefault","_mapValues","_pick","_compression","_cookieParser","_csurf","_express","_serveFavicon","_helmet","_morgan","_requestIp","_uuid","_renderer","_errors","_interopRequireWildcard","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","cookieSignatureSecret","requestIp","mw","csrf","cookie","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","static","path","setHeaders","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","Promise","resolve","then","webpackDevMiddleware","webpackHotMiddleware","compiler","Error","serverSideRender","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","getErrorForCode","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport cloneDeep from 'lodash/cloneDeep';\nimport mapValues from 'lodash/mapValues';\nimport pick from 'lodash/pick';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\n\nimport express, {\n type Express,\n type NextFunction,\n type Request,\n type Response,\n} from 'express';\n\nimport favicon from 'serve-favicon';\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport type { Configuration } from 'webpack';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT = Exclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => boolean | Promise<boolean>;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cookieSignatureSecret?: string;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser(options.cookieSignatureSecret));\n server.use(requestIp.mw());\n\n server.use(csrf({ cookie: true }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n const { webpack } = await import(/* webpackChunkName: \"server-side-code\" */ 'webpack');\n\n const { default: webpackDevMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-dev-middleware'\n );\n\n const { default: webpackHotMiddleware } = await import(\n /* webpackChunkName: \"server-side-code\" */ 'webpack-hot-middleware'\n );\n\n const compiler = webpack(webpackConfig);\n if (!compiler) throw Error('Internal error');\n\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":";;;;;;;;AAIA,IAAAA,SAAA,GAAAC,OAAA;AACA,IAAAC,QAAA,GAAAD,OAAA;AAEA,IAAAE,UAAA,GAAAC,sBAAA,CAAAH,OAAA;AACA,IAAAI,UAAA,GAAAD,sBAAA,CAAAH,OAAA;AACA,IAAAK,KAA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CAAC,CACToE,KAEC,EACDnE,GAAY,EACZC,GAAa,EACbC,IAAkB,KACf;MACH;MACA;MACA,IAAID,GAAG,CAACmE,WAAW,EAAE;QACnBlE,IAAI,CAACiE,KAAK,CAAC;QACX;MACF;MAEA,MAAME,MAAM,GAAGF,KAAK,CAACE,MAAM,IAAIL,aAAK,CAACM,qBAAqB;MAC1D,MAAMC,UAAU,GAAGF,MAAM,IAAKL,aAAK,CAACM,qBAAgC;;MAEpE;MACAnF,OAAO,CAACU,MAAM,CAAE2E,GAAG,CAACD,UAAU,GAAG,OAAO,GAAG,OAAO,EAAEJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC;MAErE,IAAIC,OAAO,GAAGP,KAAK,CAACO,OAAO,IAAI,IAAAC,uBAAe,EAACN,MAAM,CAAC;MACtD,IAAIE,UAAU,IAAIvB,OAAO,CAAC4B,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;QACvDH,OAAO,GAAGZ,cAAM,CAACQ,qBAAqB;MACxC;MAEArE,GAAG,CAACoE,MAAM,CAACA,MAAM,CAAC,CAAChD,IAAI,CAACqD,OAAO,CAAC;IAClC,CAAC,CAAC;EACJ;EAEA,OAAOhF,MAAM;AACf","ignoreList":[]}
@@ -1,26 +1,25 @@
1
1
  "use strict";
2
2
 
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
3
4
  Object.defineProperty(exports, "__esModule", {
4
5
  value: true
5
6
  });
6
7
  exports.default = void 0;
8
+ var _cookie = require("cookie");
9
+ var _getInj = _interopRequireDefault(require("../../client/getInj"));
7
10
  var _environmentCheck = require("./isomorphy/environment-check");
8
11
  var _webpack = require("./webpack");
9
12
  /* global document */
10
13
 
11
14
  // TODO: The internal type casting is somewhat messed up here,
12
15
  // to be corrected later.
13
- const config = (_environmentCheck.IS_CLIENT_SIDE
14
- // eslint-disable-next-line @typescript-eslint/no-require-imports
15
- ? require("../../client/getInj").default().CONFIG : (0, _webpack.requireWeak)('config')) ?? {};
16
+ const config = (_environmentCheck.IS_CLIENT_SIDE ? (0, _getInj.default)().CONFIG : (0, _webpack.requireWeak)('config')) ?? {};
16
17
 
17
18
  // The safeguard for "document" is necessary because in non-Node environments,
18
19
  // like React Native, IS_CLIENT_SIDE is "true", however "document" and a bunch
19
20
  // of other browser-world features are not available.
20
21
  if (_environmentCheck.IS_CLIENT_SIDE && typeof document !== 'undefined') {
21
- // eslint-disable-next-line @typescript-eslint/no-require-imports
22
- const cookie = require('cookie');
23
- config.CSRF = cookie.parse(document.cookie).csrfToken;
22
+ config.CSRF = (0, _cookie.parse)(document.cookie).csrfToken;
24
23
  }
25
24
  var _default = exports.default = config;
26
25
  //# sourceMappingURL=config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","names":["_environmentCheck","require","_webpack","config","IS_CLIENT_SIDE","default","CONFIG","requireWeak","document","cookie","CSRF","parse","csrfToken","_default","exports"],"sources":["../../../../src/shared/utils/config.ts"],"sourcesContent":["/* global document */\n\nimport type CookieM from 'cookie';\n\nimport { IS_CLIENT_SIDE } from './isomorphy/environment-check';\nimport { requireWeak } from './webpack';\n\n// TODO: The internal type casting is somewhat messed up here,\n// to be corrected later.\nconst config: Record<string, unknown> = (\n IS_CLIENT_SIDE\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n ? (require('client/getInj') as {\n default: () => Record<string, unknown>;\n }).default().CONFIG\n : requireWeak('config')\n) as (Record<string, unknown> | undefined) ?? ({} as Record<string, unknown>);\n\n// The safeguard for \"document\" is necessary because in non-Node environments,\n// like React Native, IS_CLIENT_SIDE is \"true\", however \"document\" and a bunch\n// of other browser-world features are not available.\nif (IS_CLIENT_SIDE && typeof document !== 'undefined') {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const cookie = require('cookie') as typeof CookieM;\n config.CSRF = cookie.parse(document.cookie).csrfToken;\n}\n\nexport default config;\n"],"mappings":";;;;;;AAIA,IAAAA,iBAAA,GAAAC,OAAA;AACA,IAAAC,QAAA,GAAAD,OAAA;AALA;;AAOA;AACA;AACA,MAAME,MAA+B,GAAG,CACtCC;AACE;AAAA,EACGH,OAAO,sBAAgB,CAAC,CAExBI,OAAO,CAAC,CAAC,CAACC,MAAM,GACjB,IAAAC,oBAAW,EAAC,QAAQ,CAAC,KACoB,CAAC,CAA6B;;AAE7E;AACA;AACA;AACA,IAAIH,gCAAc,IAAI,OAAOI,QAAQ,KAAK,WAAW,EAAE;EACrD;EACA,MAAMC,MAAM,GAAGR,OAAO,CAAC,QAAQ,CAAmB;EAClDE,MAAM,CAACO,IAAI,GAAGD,MAAM,CAACE,KAAK,CAACH,QAAQ,CAACC,MAAM,CAAC,CAACG,SAAS;AACvD;AAAA,IAAAC,QAAA,GAAAC,OAAA,CAAAT,OAAA,GAEeF,MAAM","ignoreList":[]}
1
+ {"version":3,"file":"config.js","names":["_cookie","require","_getInj","_interopRequireDefault","_environmentCheck","_webpack","config","IS_CLIENT_SIDE","clientGetInj","CONFIG","requireWeak","document","CSRF","parse","cookie","csrfToken","_default","exports","default"],"sources":["../../../../src/shared/utils/config.ts"],"sourcesContent":["/* global document */\n\nimport { parse } from 'cookie';\n\nimport clientGetInj from '../../client/getInj';\n\nimport { IS_CLIENT_SIDE } from './isomorphy/environment-check';\nimport { requireWeak } from './webpack';\n\n// TODO: The internal type casting is somewhat messed up here,\n// to be corrected later.\nconst config: Record<string, unknown> = (\n IS_CLIENT_SIDE ? clientGetInj().CONFIG : requireWeak('config')\n) as (Record<string, unknown> | undefined) ?? ({} as Record<string, unknown>);\n\n// The safeguard for \"document\" is necessary because in non-Node environments,\n// like React Native, IS_CLIENT_SIDE is \"true\", however \"document\" and a bunch\n// of other browser-world features are not available.\nif (IS_CLIENT_SIDE && typeof document !== 'undefined') {\n config.CSRF = parse(document.cookie).csrfToken;\n}\n\nexport default config;\n"],"mappings":";;;;;;;AAEA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,OAAA,GAAAC,sBAAA,CAAAF,OAAA;AAEA,IAAAG,iBAAA,GAAAH,OAAA;AACA,IAAAI,QAAA,GAAAJ,OAAA;AAPA;;AASA;AACA;AACA,MAAMK,MAA+B,GAAG,CACtCC,gCAAc,GAAG,IAAAC,eAAY,EAAC,CAAC,CAACC,MAAM,GAAG,IAAAC,oBAAW,EAAC,QAAQ,CAAC,KACjB,CAAC,CAA6B;;AAE7E;AACA;AACA;AACA,IAAIH,gCAAc,IAAI,OAAOI,QAAQ,KAAK,WAAW,EAAE;EACrDL,MAAM,CAACM,IAAI,GAAG,IAAAC,aAAK,EAACF,QAAQ,CAACG,MAAM,CAAC,CAACC,SAAS;AAChD;AAAA,IAAAC,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEeZ,MAAM","ignoreList":[]}
@@ -11,25 +11,15 @@ var _jsUtils = require("@dr.pogodin/js-utils");
11
11
  var _globalState = require("./globalState");
12
12
  var _isomorphy = require("./isomorphy");
13
13
  var _jsxRuntime = require("react/jsx-runtime");
14
- /* global document */
15
-
16
- // Note: At the client side we can get chunk groups immediately when loading
17
- // the module; at the server-side we only can get them within React render flow.
18
- // Thus, we set and use the following variable at the client-side, and then when
19
- // needed on the server side, we'll fetch it differently.
20
-
21
- let clientChunkGroups;
22
- if (_isomorphy.IS_CLIENT_SIDE) {
23
- // TODO: Rewrite to avoid these overrides of ESLint rules.
24
- /* eslint-disable @typescript-eslint/no-unsafe-assignment,
25
- @typescript-eslint/no-require-imports,
26
- @typescript-eslint/no-unsafe-call,
27
- @typescript-eslint/no-unsafe-member-access */
28
- clientChunkGroups = require("../../client/getInj").default().CHUNK_GROUPS ?? {};
29
- /* eslint-enable @typescript-eslint/no-unsafe-assignment,
30
- @typescript-eslint/no-require-imports,
31
- @typescript-eslint/no-unsafe-call,
32
- @typescript-eslint/no-unsafe-member-access */
14
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } /* global document */
15
+ function getClientChunkGroups() {
16
+ if (!_isomorphy.IS_CLIENT_SIDE) return undefined;
17
+ return (async () => {
18
+ const {
19
+ default: getInj
20
+ } = await Promise.resolve().then(() => _interopRequireWildcard(require(/* webpackChunkName: "react-utils-client-side-code" */"../../client/getInj")));
21
+ return getInj().CHUNK_GROUPS ?? {};
22
+ })();
33
23
  }
34
24
  const refCounts = {};
35
25
  function getPublicPath() {
@@ -159,14 +149,18 @@ function splitComponent({
159
149
  getComponent,
160
150
  placeholder
161
151
  }) {
162
- // On the client side we can check right away if the chunk name is known.
163
- if (_isomorphy.IS_CLIENT_SIDE) assertChunkName(chunkName, clientChunkGroups);
164
-
165
152
  // The correct usage of splitComponent() assumes a single call per chunk.
166
153
  if (usedChunkNames.has(chunkName)) {
167
154
  throw Error(`Repeated splitComponent() call for the chunk "${chunkName}"`);
168
155
  } else usedChunkNames.add(chunkName);
169
156
  const LazyComponent = /*#__PURE__*/(0, _react.lazy)(async () => {
157
+ const clientChunkGroups = await getClientChunkGroups();
158
+
159
+ // On the client side we can check right away if the chunk name is known.
160
+ if (_isomorphy.IS_CLIENT_SIDE) {
161
+ if (!clientChunkGroups) throw Error('Internal error');
162
+ assertChunkName(chunkName, clientChunkGroups);
163
+ }
170
164
  const resolved = await getComponent();
171
165
  const Component = 'default' in resolved ? resolved.default : resolved;
172
166
 
@@ -174,6 +168,7 @@ function splitComponent({
174
168
  // the component (the lazy load function is executed by React one at
175
169
  // the frist mount).
176
170
  if (_isomorphy.IS_CLIENT_SIDE) {
171
+ if (!clientChunkGroups) throw Error('Internal error');
177
172
  await bookStyleSheets(chunkName, clientChunkGroups, false);
178
173
  }
179
174
  const Wrapper = ({
@@ -195,6 +190,7 @@ function splitComponent({
195
190
  // This takes care about stylesheets management every time an instance of
196
191
  // this component is mounted / unmounted.
197
192
  (0, _react.useInsertionEffect)(() => {
193
+ if (!clientChunkGroups) throw Error('Internal error');
198
194
  void bookStyleSheets(chunkName, clientChunkGroups, true);
199
195
  return () => {
200
196
  freeStyleSheets(chunkName, clientChunkGroups);
@@ -1 +1 @@
1
- {"version":3,"file":"splitComponent.js","names":["_react","require","_jsUtils","_globalState","_isomorphy","_jsxRuntime","clientChunkGroups","IS_CLIENT_SIDE","default","CHUNK_GROUPS","refCounts","getPublicPath","getBuildInfo","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","Barrier","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","resolved","Component","Wrapper","children","ref","rest","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","_jsx","CodeSplit","Suspense","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\n// Note: At the client side we can get chunk groups immediately when loading\n// the module; at the server-side we only can get them within React render flow.\n// Thus, we set and use the following variable at the client-side, and then when\n// needed on the server side, we'll fetch it differently.\nlet clientChunkGroups: ChunkGroupsT;\n\nif (IS_CLIENT_SIDE) {\n // TODO: Rewrite to avoid these overrides of ESLint rules.\n /* eslint-disable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n clientChunkGroups = require('client/getInj').default().CHUNK_GROUPS ?? {};\n /* eslint-enable @typescript-eslint/no-unsafe-assignment,\n @typescript-eslint/no-require-imports,\n @typescript-eslint/no-unsafe-call,\n @typescript-eslint/no-unsafe-member-access */\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends { children?: ReactNode; ref?: RefObject<unknown> },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) assertChunkName(chunkName, clientChunkGroups);\n\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense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BAAiB,EAAE,IAAI,CAAC;QACxD,OAAO,MAAM;UACXiD,eAAe,CAACb,SAAS,EAAEpC,iBAAiB,CAAC;QAC/C,CAAC;MACH,CAAC,EAAE,EAAE,CAAC;MAEN,oBACE,IAAAqE,eAAA,EAACV;MACC;MAAA;QAAA,GACKI,IAAI;QACTD,GAAG,EAAEA,GAAI;QAAAD,QAAA,EAERA;MAAQ,CACA,CAAC;IAEhB,CAAC;IAED,OAAO;MAAE3D,OAAO,EAAE0D;IAAQ,CAAC;EAC7B,CAAC,CAAC;EAEF,MAAMU,SAAmD,GAAGA,CAAC;IAC3DT,QAAQ;IACR,GAAGE;EACY,CAAC,kBAChB,IAAAM,eAAA,EAACE,eAAQ;IAACC,QAAQ,EAAEjB,WAAY;IAAAM,QAAA,eAC9B,IAAAQ,eAAA,EAACb;IACC;IAAA;MAAA,GACIO,IAAI;MAAAF,QAAA,EAEPA;IAAQ,CACI;EAAC,CACR,CACX;EAED,OAAOS,SAAS;AAClB","ignoreList":[]}
1
+ {"version":3,"file":"splitComponent.js","names":["_react","require","_jsUtils","_globalState","_isomorphy","_jsxRuntime","_interopRequireWildcard","e","t","WeakMap","r","n","__esModule","o","i","f","__proto__","default","has","get","set","hasOwnProperty","call","Object","defineProperty","getOwnPropertyDescriptor","getClientChunkGroups","IS_CLIENT_SIDE","undefined","getInj","Promise","resolve","then","CHUNK_GROUPS","refCounts","getPublicPath","getBuildInfo","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","link","querySelector","createElement","setAttribute","head","appendChild","Barrier","addEventListener","Error","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","asset","endsWith","promise","push","length","allSettled","freeStyleSheets","pathRefCount","remove","usedChunkNames","splitComponent","getComponent","placeholder","LazyComponent","lazy","clientChunkGroups","resolved","Component","Wrapper","children","ref","rest","IS_SERVER_SIDE","chunks","getSsrContext","includes","useInsertionEffect","_jsx","CodeSplit","Suspense","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\nfunction getClientChunkGroups(): Promise<ChunkGroupsT> | undefined {\n if (!IS_CLIENT_SIDE) return undefined;\n\n return (async () => {\n const { default: getInj } = await import(/* webpackChunkName: \"react-utils-client-side-code\" */ '../../client/getInj');\n return getInj().CHUNK_GROUPS ?? {};\n })();\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\nconst usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends { children?: ReactNode; ref?: RefObject<unknown> },\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\n throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const clientChunkGroups = await getClientChunkGroups();\n\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n assertChunkName(chunkName, clientChunkGroups);\n }\n\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n if (!clientChunkGroups) throw Error('Internal error');\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":";;;;;;;;AAEA,IAAAA,MAAA,GAAAC,OAAA;AAUA,IAAAC,QAAA,GAAAD,OAAA;AAEA,IAAAE,YAAA,GAAAF,OAAA;AAEA,IAAAG,UAAA,GAAAH,OAAA;AAIqB,IAAAI,WAAA,GAAAJ,OAAA;AAAA,SAAAK,wBAAAC,CAAA,EAAAC,CAAA,6BAAAC,OAAA,MAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAH,uBAAA,YAAAA,CAAAC,CAAA,EAAAC,CAAA,SAAAA,CAAA,IAAAD,CAAA,IAAAA,CAAA,CAAAK,UAAA,SAAAL,CAAA,MAAAM,CAAA,EAAAC,CAAA,EAAAC,CAAA,KAAAC,SAAA,QAAAC,OAAA,EAAAV,CAAA,iBAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,SAAAQ,CAAA,MAAAF,CAAA,GAAAL,CAAA,GAAAG,CAAA,GAAAD,CAAA,QAAAG,CAAA,CAAAK,GAAA,CAAAX,CAAA,UAAAM,CAAA,CAAAM,GAAA,CAAAZ,CAAA,GAAAM,CAAA,CAAAO,GAAA,CAAAb,CAAA,EAAAQ,CAAA,gBAAAP,CAAA,IAAAD,CAAA,gBAAAC,CAAA,OAAAa,cAAA,CAAAC,IAAA,CAAAf,CAAA,EAAAC,CAAA,OAAAM,CAAA,IAAAD,CAAA,GAAAU,MAAA,CAAAC,cAAA,KAAAD,MAAA,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,IAAIC,yBAAc,EAAE;QAClB,MAAM;UAAE1B,WAAW;UAAE2B;QAAO,CAAC,GAAG,IAAAC,0BAAa,EAAC,CAAE;QAChD9B,eAAe,CAACC,SAAS,EAAEC,WAAW,CAAC;QACvC,IAAI,CAAC2B,MAAM,CAACE,QAAQ,CAAC9B,SAAS,CAAC,EAAE4B,MAAM,CAACpB,IAAI,CAACR,SAAS,CAAC;MACzD;;MAEA;MACA;MACA,IAAA+B,yBAAkB,EAAC,MAAM;QACvB,IAAI,CAACX,iBAAiB,EAAE,MAAM5B,KAAK,CAAC,gBAAgB,CAAC;QACrD,KAAKU,eAAe,CAACF,SAAS,EAAEoB,iBAAiB,EAAE,IAAI,CAAC;QACxD,OAAO,MAAM;UACXT,eAAe,CAACX,SAAS,EAAEoB,iBAAiB,CAAC;QAC/C,CAAC;MACH,CAAC,EAAE,EAAE,CAAC;MAEN,oBACE,IAAAY,eAAA,EAACV;MACC;MAAA;QAAA,GACKI,IAAI;QACTD,GAAG,EAAEA,GAAI;QAAAD,QAAA,EAERA;MAAQ,CACA,CAAC;IAEhB,CAAC;IAED,OAAO;MAAEvE,OAAO,EAAEsE;IAAQ,CAAC;EAC7B,CAAC,CAAC;EAEF,MAAMU,SAAmD,GAAGA,CAAC;IAC3DT,QAAQ;IACR,GAAGE;EACY,CAAC,kBAChB,IAAAM,eAAA,EAACE,eAAQ;IAACC,QAAQ,EAAElB,WAAY;IAAAO,QAAA,eAC9B,IAAAQ,eAAA,EAACd;IACC;IAAA;MAAA,GACIQ,IAAI;MAAAF,QAAA,EAEPA;IAAQ,CACI;EAAC,CACR,CACX;EAED,OAAOS,SAAS;AAClB","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"getInj.js","names":["_forge","_interopRequireDefault","require","_buildInfo","inj","metaElement","document","querySelector","remove","data","default","util","decode64","content","key","getBuildInfo","d","cipher","createDecipher","start","iv","slice","length","update","createBuffer","finish","decodeUtf8","output","eval","window","REACT_UTILS_INJECTION","getInj"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\n// Note: this way, only required part of \"node-forge\": AES, and some utils,\n// is bundled into client-side code.\nimport forge from 'node-forge/lib/forge';\n\n// eslint-disable-next-line import/no-unassigned-import\nimport 'node-forge/lib/aes';\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\n// Safeguard is needed here, because the server-side version of Docusaurus docs\n// is compiled (at least now) with settings suggesting it is a client-side\n// environment, but there is no document.\nlet inj: InjT = {};\n\nconst metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\nif (metaElement) {\n metaElement.remove();\n let data = forge.util.decode64(metaElement.content);\n\n const { key } = getBuildInfo();\n const d = forge.cipher.createDecipher('AES-CBC', key);\n d.start({ iv: data.slice(0, key.length) });\n d.update(forge.util.createBuffer(data.slice(key.length)));\n d.finish();\n\n data = forge.util.decodeUtf8(d.output.data);\n\n // TODO: Double-check, if there is a safer alternative to parse it?\n // eslint-disable-next-line no-eval\n inj = eval(`(${data})`) as InjT;\n} else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n inj = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n} else {\n // Otherwise, a bunch of dependent stuff will easily fail in non-standard\n // environments, where no client-side initialization is performed. Like tests,\n // Docusaurus examples, etc.\n inj = {};\n}\n\nexport default function getInj(): InjT {\n return inj;\n}\n"],"mappings":"gLAMA,IAAAA,MAAA,CAAAC,sBAAA,CAAAC,OAAA,0BAGAA,OAAA,uBAIA,IAAAC,UAAA,CAAAD,OAAA,wCAbA;AAEA,qBAEA;AACA;AAGA;AAOA;AACA;AACA;AACA,GAAI,CAAAE,GAAS,CAAG,CAAC,CAAC,CAElB,KAAM,CAAAC,WAAmC,CAAG,MAAO,CAAAC,QAAQ,GAAK,WAAW,CACvE,IAAI,CAAG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","_buildInfo","inj","metaElement","document","querySelector","remove","data","forge","util","decode64","content","key","getBuildInfo","d","cipher","createDecipher","start","iv","slice","length","update","createBuffer","finish","decodeUtf8","output","eval","window","REACT_UTILS_INJECTION","getInj"],"sources":["../../../src/client/getInj.ts"],"sourcesContent":["// Encapsulates retrieval of server-side data injection into HTML template.\n\n/* global document */\n\n// Note: this way, only required part of \"node-forge\": AES, and some utils,\n// is bundled into client-side code.\nimport forge from 'node-forge/lib/forge';\n\n// eslint-disable-next-line import/no-unassigned-import\nimport 'node-forge/lib/aes';\n\nimport type { InjT } from 'utils/globalState';\n\nimport { getBuildInfo } from 'utils/isomorphy/buildInfo';\n\n// Safeguard is needed here, because the server-side version of Docusaurus docs\n// is compiled (at least now) with settings suggesting it is a client-side\n// environment, but there is no document.\nlet inj: InjT = {};\n\nconst metaElement: HTMLMetaElement | null = typeof document === 'undefined'\n ? null : document.querySelector('meta[itemprop=\"drpruinj\"]');\n\nif (metaElement) {\n metaElement.remove();\n let data = forge.util.decode64(metaElement.content);\n\n const { key } = getBuildInfo();\n const d = forge.cipher.createDecipher('AES-CBC', key);\n d.start({ iv: data.slice(0, key.length) });\n d.update(forge.util.createBuffer(data.slice(key.length)));\n d.finish();\n\n data = forge.util.decodeUtf8(d.output.data);\n\n // TODO: Double-check, if there is a safer alternative to parse it?\n // eslint-disable-next-line no-eval\n inj = eval(`(${data})`) as InjT;\n} else if (typeof window !== 'undefined' && window.REACT_UTILS_INJECTION) {\n inj = window.REACT_UTILS_INJECTION;\n delete window.REACT_UTILS_INJECTION;\n} else {\n // Otherwise, a bunch of dependent stuff will easily fail in non-standard\n // environments, where no client-side initialization is performed. Like tests,\n // Docusaurus examples, etc.\n inj = {};\n}\n\nexport default function getInj(): InjT {\n return inj;\n}\n"],"mappings":"gLAMA,IAAAA,MAAA,CAAAC,sBAAA,CAAAC,OAAA,0BAGAA,OAAA,uBAIA,IAAAC,UAAA,CAAAD,OAAA,wCAbA;AAEA,qBAEA;AACA;AAGA;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,CAAA3B,GACT","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_client","require","_reactHelmet","_reactRouter","_reactGlobalState","_getInj","_interopRequireDefault","_jsxRuntime","Launch","Application","options","container","document","getElementById","Error","scene","jsx","GlobalStateProvider","initialState","default","ISTATE","children","BrowserRouter","HelmetProvider","dontHydrate","root","createRoot","render","hydrateRoot"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport type { ComponentType } from 'react';\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { BrowserRouter } from 'react-router';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: unknown;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport default function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n): void {\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={getInj().ISTATE ?? options.initialState}>\n <BrowserRouter>\n <HelmetProvider>\n <Application />\n </HelmetProvider>\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":"gLAIA,IAAAA,OAAA,CAAAC,OAAA,qBACA,IAAAC,YAAA,CAAAD,OAAA,6BACA,IAAAE,YAAA,CAAAF,OAAA,iBAEA,IAAAG,iBAAA,CAAAH,OAAA,mCAEA,IAAAI,OAAA,CAAAC,sBAAA,CAAAL,OAAA,cAA8B,IAAAM,WAAA,CAAAN,OAAA,sBAV9B;AACA,qBAgBA;AACA;AACA;AACA;AACA,GACe,QAAS,CAAAO,MAAMA,CAC5BC,WAA0B,CAC1BC,OAAiB,CAAG,CAAC,CAAC,CAChB,CACN,KAAM,CAAAC,SAAS,CAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC,CACvD,GAAI,CAACF,SAAS,CAAE,KAAM,CAAAG,KAAK,CAAC,wCAAwC,CAAC,CACrE,KAAM,CAAAC,KAAK,cACT,GAAAR,WAAA,CAAAS,GAAA,EAACZ,iBAAA,CAAAa,mBAAmB,EAACC,YAAY,CAAE,GAAAb,OAAA,CAAAc,OAAM,EAAC,CAAC,CAACC,MAAM,EAAIV,OAAO,CAACQ,YAAa,CAAAG,QAAA,cACzE,GAAAd,WAAA,CAAAS,GAAA,EAACb,YAAA,CAAAmB,aAAa,EAAAD,QAAA,cACZ,GAAAd,WAAA,CAAAS,GAAA,EAACd,YAAA,CAAAqB,cAAc,EAAAF,QAAA,cACb,GAAAd,WAAA,CAAAS,GAAA,EAACP,WAAW,GAAE,CAAC,CACD,CAAC,CACJ,CAAC,CACG,CACtB,CAED,GAAIC,OAAO,CAACc,WAAW,CAAE,CACvB,KAAM,CAAAC,IAAI,CAAG,GAAAzB,OAAA,CAAA0B,UAAU,EAACf,SAAS,CAAC,CAClCc,IAAI,CAACE,MAAM,CAACZ,KAAK,CACnB,CAAC,IAAM,GAAAf,OAAA,CAAA4B,WAAW,EAACjB,SAAS,CAAEI,KAAK,CACrC","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_client","require","_reactHelmet","_reactRouter","_reactGlobalState","_getInj","_interopRequireDefault","_jsxRuntime","Launch","Application","options","container","document","getElementById","Error","scene","_jsx","GlobalStateProvider","initialState","getInj","ISTATE","children","BrowserRouter","HelmetProvider","dontHydrate","root","createRoot","render","hydrateRoot"],"sources":["../../../src/client/index.tsx"],"sourcesContent":["// Initialization of client-side code.\n/* global document */\n\nimport type { ComponentType } from 'react';\nimport { createRoot, hydrateRoot } from 'react-dom/client';\nimport { HelmetProvider } from '@dr.pogodin/react-helmet';\nimport { BrowserRouter } from 'react-router';\n\nimport { GlobalStateProvider } from '@dr.pogodin/react-global-state';\n\nimport getInj from './getInj';\n\ntype OptionsT = {\n dontHydrate?: boolean;\n initialState?: unknown;\n};\n\n/**\n * Prepares and launches the app at client side.\n * @param Application Root application component\n * @param [options={}] Optional. Additional settings.\n */\nexport default function Launch(\n Application: ComponentType,\n options: OptionsT = {},\n): void {\n const container = document.getElementById('react-view');\n if (!container) throw Error('Failed to find container for React app');\n const scene = (\n <GlobalStateProvider initialState={getInj().ISTATE ?? options.initialState}>\n <BrowserRouter>\n <HelmetProvider>\n <Application />\n </HelmetProvider>\n </BrowserRouter>\n </GlobalStateProvider>\n );\n\n if (options.dontHydrate) {\n const root = createRoot(container);\n root.render(scene);\n } else hydrateRoot(container, scene);\n}\n"],"mappings":"gLAIA,IAAAA,OAAA,CAAAC,OAAA,qBACA,IAAAC,YAAA,CAAAD,OAAA,6BACA,IAAAE,YAAA,CAAAF,OAAA,iBAEA,IAAAG,iBAAA,CAAAH,OAAA,mCAEA,IAAAI,OAAA,CAAAC,sBAAA,CAAAL,OAAA,cAA8B,IAAAM,WAAA,CAAAN,OAAA,sBAV9B;AACA,qBAgBA;AACA;AACA;AACA;AACA,GACe,QAAS,CAAAO,MAAMA,CAC5BC,WAA0B,CAC1BC,OAAiB,CAAG,CAAC,CAAC,CAChB,CACN,KAAM,CAAAC,SAAS,CAAGC,QAAQ,CAACC,cAAc,CAAC,YAAY,CAAC,CACvD,GAAI,CAACF,SAAS,CAAE,KAAM,CAAAG,KAAK,CAAC,wCAAwC,CAAC,CACrE,KAAM,CAAAC,KAAK,cACT,GAAAC,eAAA,EAACC,qCAAmB,EAACC,YAAY,CAAE,GAAAC,eAAM,EAAC,CAAC,CAACC,MAAM,EAAIV,OAAO,CAACQ,YAAa,CAAAG,QAAA,cACzE,GAAAL,eAAA,EAACM,0BAAa,EAAAD,QAAA,cACZ,GAAAL,eAAA,EAACO,2BAAc,EAAAF,QAAA,cACb,GAAAL,eAAA,EAACP,WAAW,GAAE,CAAC,CACD,CAAC,CACJ,CAAC,CACG,CACtB,CAED,GAAIC,OAAO,CAACc,WAAW,CAAE,CACvB,KAAM,CAAAC,IAAI,CAAG,GAAAC,kBAAU,EAACf,SAAS,CAAC,CAClCc,IAAI,CAACE,MAAM,CAACZ,KAAK,CACnB,CAAC,IAAM,GAAAa,mBAAW,EAACjB,SAAS,CAAEI,KAAK,CACrC","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"init.js","names":["_buildInfo","require","buildInfo","getBuildInfo","process","env","NODE_ENV","console","warn","window","__DEV_BUILD_INFO__","BUILD_INFO","useServiceWorker","navigator","addEventListener","reg","serviceWorker","register","log","err"],"sources":["../../../src/client/init.ts"],"sourcesContent":["/**\n * Initialization of client-side environment.\n */\n\n/* global window */\n\nimport { type BuildInfoT, getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nconst buildInfo = getBuildInfo();\n\n// TODO: Should be moved into buildInfo module?\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n __DEV_BUILD_INFO__: BuildInfoT | undefined;\n }\n}\n\ndeclare const BUILD_INFO: BuildInfoT | undefined;\n\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.warn('Dev mode: \"BUILD_INFO\" attached to the global \"window\"');\n\n // eslint-disable-next-line no-underscore-dangle\n window.__DEV_BUILD_INFO__ = BUILD_INFO;\n}\n\n/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */\nconst { useServiceWorker } = buildInfo;\nif (useServiceWorker) {\n const { navigator } = window;\n if ('serviceWorker' in navigator) {\n window.addEventListener('load', () => {\n void (async () => {\n try {\n // Note: no matter the \"publicPath\", we want to serve the service worker\n // from the web app root, to allow it control any and all pages of the\n // web app (otherwise, it will be restricted to the scope of its path).\n // The server takes it into account.\n const reg = await navigator\n .serviceWorker.register('/__service-worker.js');\n // eslint-disable-next-line no-console\n console.log('SW registered:', reg);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.log('SW registration failed:', err);\n }\n })();\n });\n }\n}\n"],"mappings":"aAMA,IAAAA,UAAA,CAAAC,OAAA,wCANA;AACA;AACA,GAEA,mBAIA,KAAM,CAAAC,SAAS,CAAG,GAAAF,UAAA,CAAAG,YAAY,EAAC,CAAC,CAEhC;AAUA,GAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACzC;AACAC,OAAO,CAACC,IAAI,CAAC,4DAAwD,CAAC,CAEtE;AACAC,MAAM,CAACC,kBAAkB,CAAGC,UAC9B,CAEA,yEACA,KAAM,CAAEC,gBAAiB,CAAC,CAAGV,SAAS,CACtC,GAAIU,gBAAgB,CAAE,CACpB,KAAM,CAAEC,SAAU,CAAC,CAAGJ,MAAM,CAC5B,GAAI,eAAe,EAAI,CAAAI,SAAS,CAAE,CAChCJ,MAAM,CAACK,gBAAgB,CAAC,MAAM,CAAE,IAAM,CACpC,IAAK,CAAC,SAAY,CAChB,GAAI,CACF;AACA;AACA;AACA;AACA,KAAM,CAAAC,GAAG,CAAG,KAAM,CAAAF,SAAS,CACxBG,aAAa,CAACC,QAAQ,CAAC,sBAAsB,CAAC,CACjD;AACAV,OAAO,CAACW,GAAG,CAAC,gBAAgB,CAAEH,GAAG,CACnC,CAAE,MAAOI,GAAG,CAAE,CACZ;AACAZ,OAAO,CAACW,GAAG,CAAC,yBAAyB,CAAEC,GAAG,CAC5C,CACF,CAAC,EAAE,CACL,CAAC,CACH,CACF","ignoreList":[]}
1
+ {"version":3,"file":"init.js","names":["_buildInfo","require","buildInfo","getBuildInfo","process","env","NODE_ENV","console","warn","window","__DEV_BUILD_INFO__","BUILD_INFO","useServiceWorker","navigator","addEventListener","reg","serviceWorker","register","log","err"],"sources":["../../../src/client/init.ts"],"sourcesContent":["/**\n * Initialization of client-side environment.\n */\n\n/* global window */\n\nimport { type BuildInfoT, getBuildInfo } from 'utils/isomorphy/buildInfo';\n\nconst buildInfo = getBuildInfo();\n\n// TODO: Should be moved into buildInfo module?\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n __DEV_BUILD_INFO__: BuildInfoT | undefined;\n }\n}\n\ndeclare const BUILD_INFO: BuildInfoT | undefined;\n\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line no-console\n console.warn('Dev mode: \"BUILD_INFO\" attached to the global \"window\"');\n\n // eslint-disable-next-line no-underscore-dangle\n window.__DEV_BUILD_INFO__ = BUILD_INFO;\n}\n\n/* TODO: A proper logger should be moved to `@dr.pogodin/react-utils`. */\nconst { useServiceWorker } = buildInfo;\nif (useServiceWorker) {\n const { navigator } = window;\n if ('serviceWorker' in navigator) {\n window.addEventListener('load', () => {\n void (async () => {\n try {\n // Note: no matter the \"publicPath\", we want to serve the service worker\n // from the web app root, to allow it control any and all pages of the\n // web app (otherwise, it will be restricted to the scope of its path).\n // The server takes it into account.\n const reg = await navigator\n .serviceWorker.register('/__service-worker.js');\n // eslint-disable-next-line no-console\n console.log('SW registered:', reg);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.log('SW registration failed:', err);\n }\n })();\n });\n }\n}\n"],"mappings":"aAMA,IAAAA,UAAA,CAAAC,OAAA,wCANA;AACA;AACA,GAEA,mBAIA,KAAM,CAAAC,SAAS,CAAG,GAAAC,uBAAY,EAAC,CAAC,CAEhC;AAUA,GAAIC,OAAO,CAACC,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACzC;AACAC,OAAO,CAACC,IAAI,CAAC,4DAAwD,CAAC,CAEtE;AACAC,MAAM,CAACC,kBAAkB,CAAGC,UAC9B,CAEA,yEACA,KAAM,CAAEC,gBAAiB,CAAC,CAAGV,SAAS,CACtC,GAAIU,gBAAgB,CAAE,CACpB,KAAM,CAAEC,SAAU,CAAC,CAAGJ,MAAM,CAC5B,GAAI,eAAe,EAAI,CAAAI,SAAS,CAAE,CAChCJ,MAAM,CAACK,gBAAgB,CAAC,MAAM,CAAE,IAAM,CACpC,IAAK,CAAC,SAAY,CAChB,GAAI,CACF;AACA;AACA;AACA;AACA,KAAM,CAAAC,GAAG,CAAG,KAAM,CAAAF,SAAS,CACxBG,aAAa,CAACC,QAAQ,CAAC,sBAAsB,CAAC,CACjD;AACAV,OAAO,CAACW,GAAG,CAAC,gBAAgB,CAAEH,GAAG,CACnC,CAAE,MAAOI,GAAG,CAAE,CACZ;AACAZ,OAAO,CAACW,GAAG,CAAC,yBAAyB,CAAEC,GAAG,CAC5C,CACF,CAAC,EAAE,CACL,CAAC,CACH,CACF","ignoreList":[]}
@@ -1,10 +1,9 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});var _exportNames={client:true,server:true,assertEmptyObject:true,config:true,Barrier:true,Cached:true,Emitter:true,isomorphy:true,getSsrContext:true,Semaphore:true,splitComponent:true,themed:true,ThemeProvider:true,time:true,webpack:true,withRetries:true,getGlobalState:true,GlobalStateProvider:true,newAsyncDataEnvelope:true,useAsyncCollection:true,useAsyncData:true,useGlobalState:true,withGlobalStateType:true};Object.defineProperty(exports,"Barrier",{enumerable:true,get:function(){return _utils.Barrier}});Object.defineProperty(exports,"Cached",{enumerable:true,get:function(){return _utils.Cached}});Object.defineProperty(exports,"Emitter",{enumerable:true,get:function(){return _utils.Emitter}});Object.defineProperty(exports,"GlobalStateProvider",{enumerable:true,get:function(){return _reactGlobalState.GlobalStateProvider}});Object.defineProperty(exports,"Semaphore",{enumerable:true,get:function(){return _utils.Semaphore}});Object.defineProperty(exports,"ThemeProvider",{enumerable:true,get:function(){return _utils.ThemeProvider}});Object.defineProperty(exports,"assertEmptyObject",{enumerable:true,get:function(){return _utils.assertEmptyObject}});exports.client=void 0;Object.defineProperty(exports,"config",{enumerable:true,get:function(){return _utils.config}});Object.defineProperty(exports,"getGlobalState",{enumerable:true,get:function(){return _reactGlobalState.getGlobalState}});Object.defineProperty(exports,"getSsrContext",{enumerable:true,get:function(){return _utils.getSsrContext}});Object.defineProperty(exports,"isomorphy",{enumerable:true,get:function(){return _utils.isomorphy}});Object.defineProperty(exports,"newAsyncDataEnvelope",{enumerable:true,get:function(){return _reactGlobalState.newAsyncDataEnvelope}});exports.server=void 0;Object.defineProperty(exports,"splitComponent",{enumerable:true,get:function(){return _utils.splitComponent}});Object.defineProperty(exports,"themed",{enumerable:true,get:function(){return _utils.themed}});Object.defineProperty(exports,"time",{enumerable:true,get:function(){return _utils.time}});Object.defineProperty(exports,"useAsyncCollection",{enumerable:true,get:function(){return _reactGlobalState.useAsyncCollection}});Object.defineProperty(exports,"useAsyncData",{enumerable:true,get:function(){return _reactGlobalState.useAsyncData}});Object.defineProperty(exports,"useGlobalState",{enumerable:true,get:function(){return _reactGlobalState.useGlobalState}});Object.defineProperty(exports,"webpack",{enumerable:true,get:function(){return _utils.webpack}});Object.defineProperty(exports,"withGlobalStateType",{enumerable:true,get:function(){return _reactGlobalState.withGlobalStateType}});Object.defineProperty(exports,"withRetries",{enumerable:true,get:function(){return _utils.withRetries}});var _utils=require("./shared/utils");var _reactGlobalState=require("@dr.pogodin/react-global-state");var _components=require("./shared/components");Object.keys(_components).forEach(function(key){if(key==="default"||key==="__esModule")return;if(Object.prototype.hasOwnProperty.call(_exportNames,key))return;if(key in exports&&exports[key]===_components[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _components[key]}})});// It is a safeguard against multiple instances / versions of the library
1
+ "use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});var _exportNames={client:true,server:true,assertEmptyObject:true,config:true,Barrier:true,Cached:true,Emitter:true,isomorphy:true,getSsrContext:true,Semaphore:true,splitComponent:true,themed:true,ThemeProvider:true,time:true,webpack:true,withRetries:true,getGlobalState:true,GlobalStateProvider:true,newAsyncDataEnvelope:true,useAsyncCollection:true,useAsyncData:true,useGlobalState:true,withGlobalStateType:true};Object.defineProperty(exports,"Barrier",{enumerable:true,get:function(){return _utils.Barrier}});Object.defineProperty(exports,"Cached",{enumerable:true,get:function(){return _utils.Cached}});Object.defineProperty(exports,"Emitter",{enumerable:true,get:function(){return _utils.Emitter}});Object.defineProperty(exports,"GlobalStateProvider",{enumerable:true,get:function(){return _reactGlobalState.GlobalStateProvider}});Object.defineProperty(exports,"Semaphore",{enumerable:true,get:function(){return _utils.Semaphore}});Object.defineProperty(exports,"ThemeProvider",{enumerable:true,get:function(){return _utils.ThemeProvider}});Object.defineProperty(exports,"assertEmptyObject",{enumerable:true,get:function(){return _utils.assertEmptyObject}});exports.client=void 0;Object.defineProperty(exports,"config",{enumerable:true,get:function(){return _utils.config}});Object.defineProperty(exports,"getGlobalState",{enumerable:true,get:function(){return _reactGlobalState.getGlobalState}});Object.defineProperty(exports,"getSsrContext",{enumerable:true,get:function(){return _utils.getSsrContext}});Object.defineProperty(exports,"isomorphy",{enumerable:true,get:function(){return _utils.isomorphy}});Object.defineProperty(exports,"newAsyncDataEnvelope",{enumerable:true,get:function(){return _reactGlobalState.newAsyncDataEnvelope}});exports.server=void 0;Object.defineProperty(exports,"splitComponent",{enumerable:true,get:function(){return _utils.splitComponent}});Object.defineProperty(exports,"themed",{enumerable:true,get:function(){return _utils.themed}});Object.defineProperty(exports,"time",{enumerable:true,get:function(){return _utils.time}});Object.defineProperty(exports,"useAsyncCollection",{enumerable:true,get:function(){return _reactGlobalState.useAsyncCollection}});Object.defineProperty(exports,"useAsyncData",{enumerable:true,get:function(){return _reactGlobalState.useAsyncData}});Object.defineProperty(exports,"useGlobalState",{enumerable:true,get:function(){return _reactGlobalState.useGlobalState}});Object.defineProperty(exports,"webpack",{enumerable:true,get:function(){return _utils.webpack}});Object.defineProperty(exports,"withGlobalStateType",{enumerable:true,get:function(){return _reactGlobalState.withGlobalStateType}});Object.defineProperty(exports,"withRetries",{enumerable:true,get:function(){return _utils.withRetries}});var _client=_interopRequireDefault(require("./client"));var _utils=require("./shared/utils");var _reactGlobalState=require("@dr.pogodin/react-global-state");var _components=require("./shared/components");Object.keys(_components).forEach(function(key){if(key==="default"||key==="__esModule")return;if(Object.prototype.hasOwnProperty.call(_exportNames,key))return;if(key in exports&&exports[key]===_components[key])return;Object.defineProperty(exports,key,{enumerable:true,get:function(){return _components[key]}})});// It is a safeguard against multiple instances / versions of the library
2
2
  // being loaded into environment by mistake (e.g. because of different
3
3
  // packages pinning down different exact versions of the lib, thus preventing
4
4
  // a proper dedupe and using a single common library version).
5
5
  if(global.REACT_UTILS_LIBRARY_LOADED){throw Error("React utils library is already loaded")}else global.REACT_UTILS_LIBRARY_LOADED=true;// TODO: This is a rapid workaround to get rid of __dirname. I guess, later
6
6
  // we'll re-implement requireWeak() to accept import.meta.url directly, and
7
7
  // this workaround won't be needed.
8
- let dirname=require("url").pathToFileURL(__filename).toString();dirname=dirname.slice(5,dirname.lastIndexOf("/"));const server=exports.server=_utils.webpack.requireWeak("./server",dirname);const client=exports.client=server?undefined// eslint-disable-next-line @typescript-eslint/no-require-imports
9
- :require("./client").default;
8
+ let dirname=require("url").pathToFileURL(__filename).toString();dirname=dirname.slice(5,dirname.lastIndexOf("/"));const server=exports.server=_utils.webpack.requireWeak("./server",dirname);const client=exports.client=server?undefined:_client.default;
10
9
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_utils","require","_reactGlobalState","_components","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","global","REACT_UTILS_LIBRARY_LOADED","Error","dirname","pathToFileURL","__filename","toString","slice","lastIndexOf","server","webpack","requireWeak","client","undefined","default"],"sources":["../../src/index.ts"],"sourcesContent":["import 'styles/global.scss';\n\nimport { webpack } from 'utils';\n\nimport type * as ClientM from './client';\nimport type * as ServerFactoryM from './server';\n\n// It is a safeguard against multiple instances / versions of the library\n// being loaded into environment by mistake (e.g. because of different\n// packages pinning down different exact versions of the lib, thus preventing\n// a proper dedupe and using a single common library version).\nif (global.REACT_UTILS_LIBRARY_LOADED) {\n throw Error('React utils library is already loaded');\n} else global.REACT_UTILS_LIBRARY_LOADED = true;\n\n// TODO: This is a rapid workaround to get rid of __dirname. I guess, later\n// we'll re-implement requireWeak() to accept import.meta.url directly, and\n// this workaround won't be needed.\nlet dirname = import.meta.url;\ndirname = dirname.slice(5, dirname.lastIndexOf('/'));\n\nconst server = webpack.requireWeak<typeof ServerFactoryM>('./server', dirname);\n\nconst client = server\n ? undefined\n\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n : (require('./client') as typeof ClientM).default;\n\nexport {\n type AsyncCollectionT,\n type AsyncCollectionLoaderT,\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type ForceT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateResT,\n type ValueOrInitializerT,\n getGlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n withGlobalStateType,\n} from '@dr.pogodin/react-global-state';\n\nexport * from 'components';\n\nexport {\n type BeforeRenderResT,\n type BeforeRenderT,\n type ConfigT,\n type ServerSsrContext,\n type ServerT,\n} from './server';\n\nexport {\n assertEmptyObject,\n config,\n Barrier,\n Cached,\n Emitter,\n isomorphy,\n getSsrContext,\n type Listener,\n type ObjectKey,\n Semaphore,\n splitComponent,\n type Theme,\n themed,\n ThemeProvider,\n time,\n webpack,\n withRetries,\n} from 'utils';\n\nexport { client, server };\n"],"mappings":"sxFAEA,IAAAA,MAAA,CAAAC,OAAA,mBA2BA,IAAAC,iBAAA,CAAAD,OAAA,mCAmBA,IAAAE,WAAA,CAAAF,OAAA,wBAAAG,MAAA,CAAAC,IAAA,CAAAF,WAAA,EAAAG,OAAA,UAAAC,GAAA,KAAAA,GAAA,cAAAA,GAAA,0BAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,CAAAJ,GAAA,YAAAA,GAAA,IAAAK,OAAA,EAAAA,OAAA,CAAAL,GAAA,IAAAJ,WAAA,CAAAI,GAAA,SAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,CAAAL,GAAA,EAAAO,UAAA,MAAAC,GAAA,SAAAA,CAAA,SAAAZ,WAAA,CAAAI,GAAA,OAzCA;AACA;AACA;AACA;AACA,GAAIS,MAAM,CAACC,0BAA0B,CAAE,CACrC,KAAM,CAAAC,KAAK,CAAC,uCAAuC,CACrD,CAAC,IAAM,CAAAF,MAAM,CAACC,0BAA0B,CAAG,IAAI,CAE/C;AACA;AACA;AACA,GAAI,CAAAE,OAAO,CAAAlB,OAAA,QAAAmB,aAAA,CAAAC,UAAA,EAAAC,QAAA,EAAkB,CAC7BH,OAAO,CAAGA,OAAO,CAACI,KAAK,CAAC,CAAC,CAAEJ,OAAO,CAACK,WAAW,CAAC,GAAG,CAAC,CAAC,CAEpD,KAAM,CAAAC,MAAM,CAAAb,OAAA,CAAAa,MAAA,CAAGC,cAAO,CAACC,WAAW,YAAoCR,OAAO,CAAC,CAE9E,KAAM,CAAAS,MAAM,CAAAhB,OAAA,CAAAgB,MAAA,CAAGH,MAAM,CACjBI,SAEF;AAAA,CACG5B,OAAO,WAAW,CAAC,CAAoB6B,OAAO","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_client","_interopRequireDefault","require","_utils","_reactGlobalState","_components","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","global","REACT_UTILS_LIBRARY_LOADED","Error","dirname","pathToFileURL","__filename","toString","slice","lastIndexOf","server","webpack","requireWeak","client","undefined","clientModule"],"sources":["../../src/index.ts"],"sourcesContent":["import 'styles/global.scss';\n\nimport clientModule from './client';\nimport { webpack } from './shared/utils';\n\nimport type * as ServerFactoryM from './server';\n\n// It is a safeguard against multiple instances / versions of the library\n// being loaded into environment by mistake (e.g. because of different\n// packages pinning down different exact versions of the lib, thus preventing\n// a proper dedupe and using a single common library version).\nif (global.REACT_UTILS_LIBRARY_LOADED) {\n throw Error('React utils library is already loaded');\n} else global.REACT_UTILS_LIBRARY_LOADED = true;\n\n// TODO: This is a rapid workaround to get rid of __dirname. I guess, later\n// we'll re-implement requireWeak() to accept import.meta.url directly, and\n// this workaround won't be needed.\nlet dirname = import.meta.url;\ndirname = dirname.slice(5, dirname.lastIndexOf('/'));\n\nconst server = webpack.requireWeak<typeof ServerFactoryM>('./server', dirname);\n\nconst client = server ? undefined : clientModule;\n\nexport {\n type AsyncCollectionT,\n type AsyncCollectionLoaderT,\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type ForceT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateResT,\n type ValueOrInitializerT,\n getGlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n withGlobalStateType,\n} from '@dr.pogodin/react-global-state';\n\nexport * from 'components';\n\nexport {\n type BeforeRenderResT,\n type BeforeRenderT,\n type ConfigT,\n type ServerSsrContext,\n type ServerT,\n} from './server';\n\nexport {\n assertEmptyObject,\n config,\n Barrier,\n Cached,\n Emitter,\n isomorphy,\n getSsrContext,\n type Listener,\n type ObjectKey,\n Semaphore,\n splitComponent,\n type Theme,\n themed,\n ThemeProvider,\n time,\n webpack,\n withRetries,\n} from 'utils';\n\nexport { client, server };\n"],"mappings":"y2FAEA,IAAAA,OAAA,CAAAC,sBAAA,CAAAC,OAAA,cACA,IAAAC,MAAA,CAAAD,OAAA,mBAsBA,IAAAE,iBAAA,CAAAF,OAAA,mCAmBA,IAAAG,WAAA,CAAAH,OAAA,wBAAAI,MAAA,CAAAC,IAAA,CAAAF,WAAA,EAAAG,OAAA,UAAAC,GAAA,KAAAA,GAAA,cAAAA,GAAA,0BAAAH,MAAA,CAAAI,SAAA,CAAAC,cAAA,CAAAC,IAAA,CAAAC,YAAA,CAAAJ,GAAA,YAAAA,GAAA,IAAAK,OAAA,EAAAA,OAAA,CAAAL,GAAA,IAAAJ,WAAA,CAAAI,GAAA,SAAAH,MAAA,CAAAS,cAAA,CAAAD,OAAA,CAAAL,GAAA,EAAAO,UAAA,MAAAC,GAAA,SAAAA,CAAA,SAAAZ,WAAA,CAAAI,GAAA,OArCA;AACA;AACA;AACA;AACA,GAAIS,MAAM,CAACC,0BAA0B,CAAE,CACrC,KAAM,CAAAC,KAAK,CAAC,uCAAuC,CACrD,CAAC,IAAM,CAAAF,MAAM,CAACC,0BAA0B,CAAG,IAAI,CAE/C;AACA;AACA;AACA,GAAI,CAAAE,OAAO,CAAAnB,OAAA,QAAAoB,aAAA,CAAAC,UAAA,EAAAC,QAAA,EAAkB,CAC7BH,OAAO,CAAGA,OAAO,CAACI,KAAK,CAAC,CAAC,CAAEJ,OAAO,CAACK,WAAW,CAAC,GAAG,CAAC,CAAC,CAEpD,KAAM,CAAAC,MAAM,CAAAb,OAAA,CAAAa,MAAA,CAAGC,cAAO,CAACC,WAAW,YAAoCR,OAAO,CAAC,CAE9E,KAAM,CAAAS,MAAM,CAAAhB,OAAA,CAAAgB,MAAA,CAAGH,MAAM,CAAGI,SAAS,CAAGC,eAAY","ignoreList":[]}