react-cosmos 5.7.2 → 6.0.0-alpha.0

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 (246) hide show
  1. package/bin/cosmos-export.js +4 -3
  2. package/bin/cosmos-native.js +4 -3
  3. package/bin/cosmos.js +5 -4
  4. package/config.schema.json +14 -4
  5. package/dist/index.d.ts +0 -6
  6. package/dist/index.js +0 -70
  7. package/dist/jest.d.ts +7 -0
  8. package/dist/jest.js +7 -0
  9. package/dist/{config → server/cosmosConfig}/createCosmosConfig.d.ts +1 -1
  10. package/dist/server/cosmosConfig/createCosmosConfig.js +84 -0
  11. package/dist/server/cosmosConfig/detectCosmosConfig.d.ts +2 -0
  12. package/dist/server/cosmosConfig/detectCosmosConfig.js +38 -0
  13. package/dist/{config → server/cosmosConfig}/getCosmosConfigAtPath.d.ts +1 -1
  14. package/dist/server/cosmosConfig/getCosmosConfigAtPath.js +12 -0
  15. package/dist/server/cosmosConfig/shared.d.ts +2 -0
  16. package/dist/server/cosmosConfig/shared.js +7 -0
  17. package/dist/{config/shared.d.ts → server/cosmosConfig/types.d.ts} +5 -5
  18. package/dist/server/cosmosPlugin/findCosmosPluginConfigs.d.ts +8 -0
  19. package/dist/server/cosmosPlugin/findCosmosPluginConfigs.js +14 -0
  20. package/dist/server/cosmosPlugin/pluginConfigs.d.ts +8 -0
  21. package/dist/server/cosmosPlugin/pluginConfigs.js +16 -0
  22. package/dist/server/cosmosPlugin/readCosmosPluginConfig.d.ts +8 -0
  23. package/dist/server/cosmosPlugin/readCosmosPluginConfig.js +31 -0
  24. package/dist/server/cosmosPlugin/types.d.ts +21 -0
  25. package/dist/server/devServer/corePlugins/httpProxy.d.ts +2 -0
  26. package/dist/server/devServer/corePlugins/httpProxy.js +18 -0
  27. package/dist/server/devServer/corePlugins/openFile.d.ts +2 -0
  28. package/dist/server/devServer/corePlugins/openFile.js +53 -0
  29. package/dist/server/devServer/corePlugins/pluginEndpoint.d.ts +2 -0
  30. package/dist/server/devServer/corePlugins/pluginEndpoint.js +17 -0
  31. package/dist/server/devServer/corePlugins/userDepsFile.d.ts +2 -0
  32. package/dist/server/devServer/corePlugins/userDepsFile.js +37 -0
  33. package/dist/server/devServer/expressApp.d.ts +5 -0
  34. package/dist/server/devServer/expressApp.js +21 -0
  35. package/dist/server/devServer/httpServer.d.ts +12 -0
  36. package/dist/server/devServer/httpServer.js +42 -0
  37. package/dist/{devServer → server/devServer}/messageHandler.d.ts +2 -2
  38. package/dist/server/devServer/messageHandler.js +29 -0
  39. package/dist/server/devServer/startDevServer.d.ts +2 -0
  40. package/dist/server/devServer/startDevServer.js +91 -0
  41. package/dist/server/export/generateExport.d.ts +1 -0
  42. package/dist/server/export/generateExport.js +97 -0
  43. package/dist/server/getFixtures/getFixtures.d.ts +14 -0
  44. package/dist/server/getFixtures/getFixtures.js +63 -0
  45. package/dist/server/shared/logPluginInfo.d.ts +2 -0
  46. package/dist/server/shared/logPluginInfo.js +8 -0
  47. package/dist/server/shared/playgroundHtml.d.ts +6 -0
  48. package/dist/server/shared/playgroundHtml.js +85 -0
  49. package/dist/server/shared/playgroundUrl.d.ts +2 -0
  50. package/dist/server/shared/playgroundUrl.js +6 -0
  51. package/dist/server/shared/requirePluginModule.d.ts +2 -0
  52. package/dist/server/shared/requirePluginModule.js +10 -0
  53. package/dist/server/shared/resolveUrlPath.d.ts +1 -0
  54. package/dist/server/shared/resolveUrlPath.js +12 -0
  55. package/dist/server/shared/staticPath.d.ts +1 -0
  56. package/dist/server/shared/staticPath.js +4 -0
  57. package/dist/{shared/static.d.ts → server/shared/staticServer.d.ts} +0 -1
  58. package/dist/server/shared/staticServer.js +12 -0
  59. package/dist/{shared → server}/static/index.html +1 -1
  60. package/dist/server/testHelpers/cwd.d.ts +1 -0
  61. package/dist/server/testHelpers/cwd.js +4 -0
  62. package/dist/server/testHelpers/mockConsole.d.ts +5 -0
  63. package/dist/server/testHelpers/mockConsole.js +11 -0
  64. package/dist/server/testHelpers/mockEsmRequire.js +13 -0
  65. package/dist/server/testHelpers/mockEsmResolve.d.ts +1 -0
  66. package/dist/server/testHelpers/mockEsmResolve.js +13 -0
  67. package/dist/server/testHelpers/mockEsmStaticPath.d.ts +1 -0
  68. package/dist/server/testHelpers/mockEsmStaticPath.js +7 -0
  69. package/dist/server/testHelpers/mockFetch.d.ts +2 -0
  70. package/dist/server/testHelpers/mockFetch.js +7 -0
  71. package/dist/server/testHelpers/mockFs.d.ts +5 -0
  72. package/dist/server/testHelpers/mockFs.js +64 -0
  73. package/dist/server/testHelpers/mockYargs.d.ts +2 -0
  74. package/dist/server/testHelpers/mockYargs.js +21 -0
  75. package/dist/{userDeps → server/userDeps}/findUserModulePaths.d.ts +2 -2
  76. package/dist/server/userDeps/findUserModulePaths.js +20 -0
  77. package/dist/server/userDeps/fixtureWatcher.d.ts +3 -0
  78. package/dist/server/userDeps/fixtureWatcher.js +20 -0
  79. package/dist/{userDeps → server/userDeps}/generateUserDepsModule.d.ts +3 -3
  80. package/dist/server/userDeps/generateUserDepsModule.js +18 -0
  81. package/dist/{userDeps → server/userDeps}/getUserModules.d.ts +3 -3
  82. package/dist/server/userDeps/getUserModules.js +25 -0
  83. package/dist/{userDeps → server/userDeps}/shared.d.ts +1 -1
  84. package/dist/server/userDeps/shared.js +20 -0
  85. package/dist/{userDeps → server/userDeps}/userDepsTemplate.d.ts +2 -2
  86. package/dist/server/userDeps/userDepsTemplate.js +49 -0
  87. package/dist/server/utils/cli.js +4 -0
  88. package/dist/server/utils/fs.d.ts +4 -0
  89. package/dist/server/utils/fs.js +24 -0
  90. package/dist/server/utils/isNodeError.d.ts +2 -0
  91. package/dist/server/utils/isNodeError.js +3 -0
  92. package/dist/server/utils/requireModule.d.ts +2 -0
  93. package/dist/server/utils/requireModule.js +13 -0
  94. package/dist/server/utils/requireSilent.d.ts +1 -0
  95. package/dist/server/utils/requireSilent.js +11 -0
  96. package/dist/server/utils/resolve.d.ts +2 -0
  97. package/dist/server/utils/resolve.js +14 -0
  98. package/dist/server/utils/resolveLoose.d.ts +1 -0
  99. package/dist/server/utils/resolveLoose.js +12 -0
  100. package/dist/server/utils/resolveSilent.d.ts +2 -0
  101. package/dist/server/utils/resolveSilent.js +22 -0
  102. package/dist/server/utils/slash.d.ts +1 -0
  103. package/dist/server/utils/slash.js +5 -0
  104. package/dist/server.d.ts +20 -0
  105. package/dist/server.js +20 -0
  106. package/index.d.ts +1 -1
  107. package/index.js +1 -2
  108. package/jest.d.ts +1 -0
  109. package/jest.js +1 -0
  110. package/package.json +17 -28
  111. package/server.d.ts +1 -0
  112. package/server.js +1 -0
  113. package/dist/config/createCosmosConfig.js +0 -133
  114. package/dist/config/detectCosmosConfig.d.ts +0 -2
  115. package/dist/config/detectCosmosConfig.js +0 -57
  116. package/dist/config/getCosmosConfigAtPath.js +0 -28
  117. package/dist/config/resolveModule.d.ts +0 -1
  118. package/dist/config/resolveModule.js +0 -20
  119. package/dist/config/shared.js +0 -17
  120. package/dist/devServer/app.d.ts +0 -5
  121. package/dist/devServer/app.js +0 -51
  122. package/dist/devServer/httpServer.d.ts +0 -11
  123. package/dist/devServer/httpServer.js +0 -183
  124. package/dist/devServer/messageHandler.js +0 -42
  125. package/dist/devServer/startDevServer.d.ts +0 -18
  126. package/dist/devServer/startDevServer.js +0 -209
  127. package/dist/dom/DomFixtureLoader.d.ts +0 -9
  128. package/dist/dom/DomFixtureLoader.js +0 -38
  129. package/dist/dom/ErrorCatch.d.ts +0 -15
  130. package/dist/dom/ErrorCatch.js +0 -117
  131. package/dist/dom/container.d.ts +0 -1
  132. package/dist/dom/container.js +0 -32
  133. package/dist/dom/globalErrorHandler.js +0 -14
  134. package/dist/dom/index.d.ts +0 -13
  135. package/dist/dom/index.js +0 -47
  136. package/dist/dom/renderMessage.d.ts +0 -4
  137. package/dist/dom/renderMessage.js +0 -30
  138. package/dist/dom/rendererConnect.d.ts +0 -1
  139. package/dist/dom/rendererConnect.js +0 -18
  140. package/dist/dom/rendererId.d.ts +0 -1
  141. package/dist/dom/rendererId.js +0 -26
  142. package/dist/dom/selectedFixtureId.d.ts +0 -2
  143. package/dist/dom/selectedFixtureId.js +0 -41
  144. package/dist/dom/shared.d.ts +0 -1
  145. package/dist/dom/shared.js +0 -14
  146. package/dist/export/generateExport.d.ts +0 -6
  147. package/dist/export/generateExport.js +0 -137
  148. package/dist/fixture.d.ts +0 -1
  149. package/dist/fixture.js +0 -31
  150. package/dist/generateWebExport.d.ts +0 -1
  151. package/dist/generateWebExport.js +0 -37
  152. package/dist/getFixtureUrls.d.ts +0 -8
  153. package/dist/getFixtureUrls.js +0 -97
  154. package/dist/getFixtures.d.ts +0 -13
  155. package/dist/getFixtures.js +0 -89
  156. package/dist/getFixtures2.d.ts +0 -14
  157. package/dist/getFixtures2.js +0 -117
  158. package/dist/native/NativeFixtureLoader.d.ts +0 -12
  159. package/dist/native/NativeFixtureLoader.js +0 -67
  160. package/dist/native/index.d.ts +0 -1
  161. package/dist/native/index.js +0 -25
  162. package/dist/plugins/httpProxy.d.ts +0 -2
  163. package/dist/plugins/httpProxy.js +0 -31
  164. package/dist/plugins/openFile.d.ts +0 -2
  165. package/dist/plugins/openFile.js +0 -87
  166. package/dist/plugins/userDepsFile.d.ts +0 -2
  167. package/dist/plugins/userDepsFile.js +0 -166
  168. package/dist/plugins/webpack/client/errorOverlay/index.d.ts +0 -1
  169. package/dist/plugins/webpack/client/errorOverlay/index.js +0 -16
  170. package/dist/plugins/webpack/client/errorOverlay/reactErrorOverlay.d.ts +0 -2
  171. package/dist/plugins/webpack/client/errorOverlay/reactErrorOverlay.js +0 -63
  172. package/dist/plugins/webpack/client/hmrErrorHandler.js +0 -16
  173. package/dist/plugins/webpack/client/index.d.ts +0 -6
  174. package/dist/plugins/webpack/client/index.js +0 -43
  175. package/dist/plugins/webpack/client/reactDevtoolsHook.d.ts +0 -0
  176. package/dist/plugins/webpack/client/reactDevtoolsHook.js +0 -19
  177. package/dist/plugins/webpack/client/userDeps.d.ts +0 -5
  178. package/dist/plugins/webpack/client/userDeps.js +0 -15
  179. package/dist/plugins/webpack/cosmosConfig/dom.d.ts +0 -6
  180. package/dist/plugins/webpack/cosmosConfig/dom.js +0 -19
  181. package/dist/plugins/webpack/cosmosConfig/webpack.d.ts +0 -10
  182. package/dist/plugins/webpack/cosmosConfig/webpack.js +0 -95
  183. package/dist/plugins/webpack/devServer.d.ts +0 -2
  184. package/dist/plugins/webpack/devServer.js +0 -168
  185. package/dist/plugins/webpack/export.d.ts +0 -2
  186. package/dist/plugins/webpack/export.js +0 -139
  187. package/dist/plugins/webpack/index.d.ts +0 -2
  188. package/dist/plugins/webpack/index.js +0 -21
  189. package/dist/plugins/webpack/shared.d.ts +0 -2
  190. package/dist/plugins/webpack/shared.js +0 -22
  191. package/dist/plugins/webpack/webpackConfig/getDefaultWebpackConfig.d.ts +0 -2
  192. package/dist/plugins/webpack/webpackConfig/getDefaultWebpackConfig.js +0 -152
  193. package/dist/plugins/webpack/webpackConfig/getDevWebpackConfig.d.ts +0 -3
  194. package/dist/plugins/webpack/webpackConfig/getDevWebpackConfig.js +0 -146
  195. package/dist/plugins/webpack/webpackConfig/getExportWebpackConfig.d.ts +0 -3
  196. package/dist/plugins/webpack/webpackConfig/getExportWebpackConfig.js +0 -111
  197. package/dist/plugins/webpack/webpackConfig/getUserWebpackConfig.d.ts +0 -3
  198. package/dist/plugins/webpack/webpackConfig/getUserWebpackConfig.js +0 -136
  199. package/dist/plugins/webpack/webpackConfig/getWebpackConfigModule.d.ts +0 -2
  200. package/dist/plugins/webpack/webpackConfig/getWebpackConfigModule.js +0 -45
  201. package/dist/plugins/webpack/webpackConfig/getWebpackConfigResolve.d.ts +0 -4
  202. package/dist/plugins/webpack/webpackConfig/getWebpackConfigResolve.js +0 -107
  203. package/dist/plugins/webpack/webpackConfig/getWebpackNodeEnv.d.ts +0 -1
  204. package/dist/plugins/webpack/webpackConfig/getWebpackNodeEnv.js +0 -12
  205. package/dist/plugins/webpack/webpackConfig/htmlPlugin.d.ts +0 -16
  206. package/dist/plugins/webpack/webpackConfig/htmlPlugin.js +0 -80
  207. package/dist/plugins/webpack/webpackConfig/plugins.d.ts +0 -5
  208. package/dist/plugins/webpack/webpackConfig/plugins.js +0 -37
  209. package/dist/plugins/webpack/webpackConfig/resolveWebpackClientPath.d.ts +0 -1
  210. package/dist/plugins/webpack/webpackConfig/resolveWebpackClientPath.js +0 -10
  211. package/dist/plugins/webpack/webpackConfig/userDepsLoader.js +0 -36
  212. package/dist/shared/cli.js +0 -14
  213. package/dist/shared/fs.d.ts +0 -4
  214. package/dist/shared/fs.js +0 -37
  215. package/dist/shared/playgroundHtml.d.ts +0 -6
  216. package/dist/shared/playgroundHtml.js +0 -116
  217. package/dist/shared/pluginConfigs.d.ts +0 -2
  218. package/dist/shared/pluginConfigs.js +0 -15
  219. package/dist/shared/rendererConfig.d.ts +0 -6
  220. package/dist/shared/rendererConfig.js +0 -5
  221. package/dist/shared/static.js +0 -30
  222. package/dist/shared/types.d.ts +0 -1
  223. package/dist/shared/types.js +0 -5
  224. package/dist/shared/utils.d.ts +0 -5
  225. package/dist/shared/utils.js +0 -22
  226. package/dist/startNativeServer.d.ts +0 -1
  227. package/dist/startNativeServer.js +0 -39
  228. package/dist/startWebServer.d.ts +0 -1
  229. package/dist/startWebServer.js +0 -43
  230. package/dist/userDeps/findUserModulePaths.js +0 -45
  231. package/dist/userDeps/generateUserDepsModule.js +0 -37
  232. package/dist/userDeps/getUserModules.js +0 -45
  233. package/dist/userDeps/shared.js +0 -32
  234. package/dist/userDeps/userDepsTemplate.js +0 -52
  235. package/dom.d.ts +0 -1
  236. package/dom.js +0 -2
  237. package/fixture.d.ts +0 -1
  238. package/fixture.js +0 -2
  239. package/native.d.ts +0 -1
  240. package/native.js +0 -2
  241. package/yarn-error.log +0 -13450
  242. /package/dist/{dom/globalErrorHandler.d.ts → server/cosmosConfig/types.js} +0 -0
  243. /package/dist/{plugins/webpack/client/hmrErrorHandler.d.ts → server/cosmosPlugin/types.js} +0 -0
  244. /package/dist/{shared → server}/static/favicon.ico +0 -0
  245. /package/dist/{plugins/webpack/webpackConfig/userDepsLoader.d.ts → server/testHelpers/mockEsmRequire.d.ts} +0 -0
  246. /package/dist/{shared → server/utils}/cli.d.ts +0 -0
@@ -0,0 +1,37 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+ import { startFixtureWatcher } from '../../userDeps/fixtureWatcher.js';
4
+ import { getPlaygroundUrl } from '../../shared/playgroundUrl.js';
5
+ import { generateUserDepsModule } from '../../userDeps/generateUserDepsModule.js';
6
+ import { getCliArgs } from '../../utils/cli.js';
7
+ export async function userDepsFileDevServerPlugin(args) {
8
+ if (!shouldGenerateUserDepsFile(args.platformType))
9
+ return;
10
+ const { cosmosConfig } = args;
11
+ await generateUserDepsFile(cosmosConfig);
12
+ const watcher = await startFixtureWatcher(cosmosConfig, 'all', () => {
13
+ generateUserDepsFile(cosmosConfig);
14
+ });
15
+ return () => {
16
+ watcher.close();
17
+ };
18
+ }
19
+ function shouldGenerateUserDepsFile(platformType) {
20
+ return (platformType === 'native' ||
21
+ // CLI support for --external-userdeps flag (useful with react-native-web)
22
+ Boolean(getCliArgs().externalUserdeps));
23
+ }
24
+ async function generateUserDepsFile(cosmosConfig) {
25
+ const { userDepsFilePath } = cosmosConfig;
26
+ const rendererConfig = {
27
+ playgroundUrl: getPlaygroundUrl(cosmosConfig),
28
+ };
29
+ const userDepsModule = generateUserDepsModule({
30
+ cosmosConfig,
31
+ rendererConfig,
32
+ relativeToDir: path.dirname(userDepsFilePath),
33
+ });
34
+ await fs.writeFile(userDepsFilePath, userDepsModule, 'utf8');
35
+ const relUserDepsFilePath = path.relative(process.cwd(), userDepsFilePath);
36
+ console.log(`[Cosmos] Generated ${relUserDepsFilePath}`);
37
+ }
@@ -0,0 +1,5 @@
1
+ import express from 'express';
2
+ import { CosmosPluginConfig } from 'react-cosmos-core';
3
+ import { CosmosConfig } from '../cosmosConfig/types.js';
4
+ import { PlatformType } from '../cosmosPlugin/types.js';
5
+ export declare function createExpressApp(platformType: PlatformType, cosmosConfig: CosmosConfig, pluginConfigs: CosmosPluginConfig[]): Promise<express.Express>;
@@ -0,0 +1,21 @@
1
+ import express from 'express';
2
+ import { getDevPlaygroundHtml } from '../shared/playgroundHtml.js';
3
+ import { getStaticPath } from '../shared/staticPath.js';
4
+ import { resolve } from '../utils/resolve.js';
5
+ export async function createExpressApp(platformType, cosmosConfig, pluginConfigs) {
6
+ const app = express();
7
+ const playgroundHtml = await getDevPlaygroundHtml(platformType, cosmosConfig, pluginConfigs);
8
+ app.get('/', (req, res) => {
9
+ res.send(playgroundHtml);
10
+ });
11
+ app.get('/playground.bundle.js', (req, res) => {
12
+ res.sendFile(resolve('react-cosmos-ui/dist/playground.bundle.js'));
13
+ });
14
+ app.get('/playground.bundle.js.map', (req, res) => {
15
+ res.sendFile(resolve('react-cosmos-ui/dist/playground.bundle.js.map'));
16
+ });
17
+ app.get('/_cosmos.ico', (req, res) => {
18
+ res.sendFile(getStaticPath('favicon.ico'));
19
+ });
20
+ return app;
21
+ }
@@ -0,0 +1,12 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import http from 'http';
4
+ import https from 'https';
5
+ import { CosmosConfig } from '../cosmosConfig/types.js';
6
+ type RequestListener = (request: http.IncomingMessage, response: http.ServerResponse) => void;
7
+ export declare function createHttpServer(cosmosConfig: CosmosConfig, requestListener: RequestListener): Promise<{
8
+ server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse> | https.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
9
+ start: () => Promise<void>;
10
+ stop: () => Promise<void>;
11
+ }>;
12
+ export {};
@@ -0,0 +1,42 @@
1
+ import fs from 'fs';
2
+ import http from 'http';
3
+ import https from 'https';
4
+ import pem from 'pem';
5
+ import { getPlaygroundUrl } from '../shared/playgroundUrl.js';
6
+ export async function createHttpServer(cosmosConfig, requestListener) {
7
+ const { port, hostname, https: httpsEnabled } = cosmosConfig;
8
+ const server = httpsEnabled
9
+ ? https.createServer(await getHttpsOpts(cosmosConfig), requestListener)
10
+ : http.createServer(requestListener);
11
+ async function start() {
12
+ await new Promise(resolve => {
13
+ if (hostname === null) {
14
+ server.listen(port, resolve);
15
+ }
16
+ else {
17
+ server.listen(port, hostname, resolve);
18
+ }
19
+ });
20
+ console.log(`[Cosmos] See you at ${getPlaygroundUrl(cosmosConfig)}`);
21
+ }
22
+ async function stop() {
23
+ await new Promise(resolve => server.close(resolve));
24
+ }
25
+ return { server, start, stop };
26
+ }
27
+ async function getHttpsOpts(cosmosConfig) {
28
+ const { httpsOptions } = cosmosConfig;
29
+ if (httpsOptions)
30
+ return {
31
+ key: fs.readFileSync(httpsOptions.keyPath, 'utf8'),
32
+ cert: fs.readFileSync(httpsOptions.certPath, 'utf8'),
33
+ };
34
+ console.log('[Cosmos] Generating HTTPS certificate');
35
+ return await new Promise((resolve, reject) => {
36
+ pem.createCertificate({ days: 1000, selfSigned: true }, (err, keys) => {
37
+ if (err)
38
+ return reject(err);
39
+ return resolve({ key: keys.serviceKey, cert: keys.certificate });
40
+ });
41
+ });
42
+ }
@@ -1,7 +1,7 @@
1
1
  /// <reference types="node" />
2
2
  import http from 'http';
3
- import { BuildMessage } from 'react-cosmos-shared2/build';
3
+ import { ServerMessage } from 'react-cosmos-core';
4
4
  export declare function createMessageHandler(httpServer: http.Server): {
5
- sendMessage: (msg: BuildMessage) => void;
5
+ sendMessage: (msg: ServerMessage) => void;
6
6
  cleanUp: () => void;
7
7
  };
@@ -0,0 +1,29 @@
1
+ import { serverSocketMessage } from 'react-cosmos-core';
2
+ import WebSocket, { WebSocketServer } from 'ws';
3
+ export function createMessageHandler(httpServer) {
4
+ const wss = new WebSocketServer({ server: httpServer });
5
+ wss.on('connection', ws => {
6
+ // Forward commands between connected clients. Parties involved can be the
7
+ // - The Cosmos UI, which acts as a remote control
8
+ // - The web iframe or the React Native component renderers
9
+ ws.on('message', msg => {
10
+ wss.clients.forEach(client => {
11
+ if (client !== ws && client.readyState === WebSocket.OPEN) {
12
+ client.send(msg.toString());
13
+ }
14
+ });
15
+ });
16
+ });
17
+ function sendMessage(msg) {
18
+ wss.clients.forEach(client => {
19
+ if (client.readyState === WebSocket.OPEN) {
20
+ client.send(JSON.stringify(serverSocketMessage(msg)));
21
+ }
22
+ });
23
+ }
24
+ function cleanUp() {
25
+ wss.clients.forEach(client => client.close());
26
+ wss.close();
27
+ }
28
+ return { sendMessage, cleanUp };
29
+ }
@@ -0,0 +1,2 @@
1
+ import { PlatformType } from '../cosmosPlugin/types.js';
2
+ export declare function startDevServer(platformType: PlatformType): Promise<() => Promise<void>>;
@@ -0,0 +1,91 @@
1
+ import path from 'path';
2
+ import { detectCosmosConfig, detectCosmosConfigPath, } from '../cosmosConfig/detectCosmosConfig.js';
3
+ import { getPluginConfigs } from '../cosmosPlugin/pluginConfigs.js';
4
+ import { logPluginInfo } from '../shared/logPluginInfo.js';
5
+ import { requirePluginModule } from '../shared/requirePluginModule.js';
6
+ import { serveStaticDir } from '../shared/staticServer.js';
7
+ import { httpProxyDevServerPlugin } from './corePlugins/httpProxy.js';
8
+ import openFileDevServerPlugin from './corePlugins/openFile.js';
9
+ import pluginEndpointDevServerPlugin from './corePlugins/pluginEndpoint.js';
10
+ import { userDepsFileDevServerPlugin } from './corePlugins/userDepsFile.js';
11
+ import { createExpressApp } from './expressApp.js';
12
+ import { createHttpServer } from './httpServer.js';
13
+ import { createMessageHandler } from './messageHandler.js';
14
+ const builtInPlugins = [
15
+ userDepsFileDevServerPlugin,
16
+ httpProxyDevServerPlugin,
17
+ openFileDevServerPlugin,
18
+ pluginEndpointDevServerPlugin,
19
+ ];
20
+ export async function startDevServer(platformType) {
21
+ const cosmosConfig = await detectCosmosConfig();
22
+ logCosmosConfigInfo();
23
+ const pluginConfigs = await getPluginConfigs({
24
+ cosmosConfig,
25
+ // Absolute paths are required in dev mode because the dev server could
26
+ // run in a monorepo package that's not the root of the project and plugins
27
+ // could be installed in the root
28
+ relativePaths: false,
29
+ });
30
+ logPluginInfo(pluginConfigs);
31
+ const app = await createExpressApp(platformType, cosmosConfig, pluginConfigs);
32
+ const httpServer = await createHttpServer(cosmosConfig, app);
33
+ const msgHandler = createMessageHandler(httpServer.server);
34
+ const pluginCleanupCallbacks = [];
35
+ async function cleanUp() {
36
+ await Promise.all(pluginCleanupCallbacks.map(cleanup => cleanup()));
37
+ await httpServer.stop();
38
+ msgHandler.cleanUp();
39
+ }
40
+ const userPlugins = await getDevServerPlugins(pluginConfigs, cosmosConfig.rootDir);
41
+ for (const plugin of [...builtInPlugins, ...userPlugins]) {
42
+ try {
43
+ const pluginReturn = await plugin({
44
+ cosmosConfig,
45
+ platformType,
46
+ httpServer: httpServer.server,
47
+ expressApp: app,
48
+ sendMessage: msgHandler.sendMessage,
49
+ });
50
+ if (typeof pluginReturn === 'function') {
51
+ pluginCleanupCallbacks.push(() => {
52
+ try {
53
+ pluginReturn();
54
+ }
55
+ catch (err) {
56
+ // Log when a plugin fails to clean up, but continue to attempt
57
+ // to clean up the remaining plugins
58
+ console.log(`[Cosmos][${plugin.name}] Dev server plugin cleanup failed`);
59
+ console.log(err);
60
+ }
61
+ });
62
+ }
63
+ }
64
+ catch (err) {
65
+ // Abort starting server if a plugin init fails and attempt cleanup of all
66
+ // plugins that have already initialized
67
+ console.log(`[Cosmos][${plugin.name}] Dev server plugin init failed`);
68
+ cleanUp();
69
+ throw err;
70
+ }
71
+ }
72
+ if (cosmosConfig.staticPath) {
73
+ serveStaticDir(app, cosmosConfig.staticPath, cosmosConfig.publicUrl);
74
+ }
75
+ await httpServer.start();
76
+ return cleanUp;
77
+ }
78
+ function logCosmosConfigInfo() {
79
+ const cosmosConfigPath = detectCosmosConfigPath();
80
+ if (!cosmosConfigPath) {
81
+ console.log(`[Cosmos] Using default cosmos config`);
82
+ return;
83
+ }
84
+ const relConfigPath = path.relative(process.cwd(), cosmosConfigPath);
85
+ console.log(`[Cosmos] Using cosmos config found at ${relConfigPath}`);
86
+ }
87
+ async function getDevServerPlugins(pluginConfigs, rootDir) {
88
+ return Promise.all(pluginConfigs
89
+ .filter(pluginConfig => pluginConfig.devServer)
90
+ .map(pluginConfig => requirePluginModule(rootDir, pluginConfig, 'devServer')));
91
+ }
@@ -0,0 +1 @@
1
+ export declare function generateExport(): Promise<void>;
@@ -0,0 +1,97 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+ import { removeLeadingSlash, } from 'react-cosmos-core';
4
+ import { detectCosmosConfig } from '../cosmosConfig/detectCosmosConfig.js';
5
+ import { getPluginConfigs } from '../cosmosPlugin/pluginConfigs.js';
6
+ import { logPluginInfo } from '../shared/logPluginInfo.js';
7
+ import { getExportPlaygroundHtml } from '../shared/playgroundHtml.js';
8
+ import { requirePluginModule } from '../shared/requirePluginModule.js';
9
+ import { getStaticPath } from '../shared/staticPath.js';
10
+ import { resolve } from '../utils/resolve.js';
11
+ const builtInPlugins = [];
12
+ export async function generateExport() {
13
+ const cosmosConfig = await detectCosmosConfig();
14
+ const pluginConfigs = await getPluginConfigs({
15
+ cosmosConfig,
16
+ // Relative paths work in exports because all plugin modules are copied
17
+ // inside the export path
18
+ relativePaths: true,
19
+ });
20
+ logPluginInfo(pluginConfigs);
21
+ // Clear previous export (or other files at export path)
22
+ const { exportPath } = cosmosConfig;
23
+ await fs.rm(exportPath, { recursive: true, force: true });
24
+ // Copy static assets first, so that the built index.html overrides the its
25
+ // template file (in case the static assets are served from the root path)
26
+ await copyStaticAssets(cosmosConfig);
27
+ const userPlugins = await getExportPlugins(pluginConfigs, cosmosConfig.rootDir);
28
+ for (const plugin of [...builtInPlugins, ...userPlugins]) {
29
+ try {
30
+ await plugin({ cosmosConfig });
31
+ }
32
+ catch (err) {
33
+ console.log(`[Cosmos][${plugin.name}] Export plugin failed`);
34
+ throw err;
35
+ }
36
+ }
37
+ await exportPlaygroundFiles(cosmosConfig, pluginConfigs);
38
+ console.log('[Cosmos] Export complete!');
39
+ console.log(`Export path: ${cosmosConfig.exportPath}`);
40
+ }
41
+ async function copyStaticAssets(cosmosConfig) {
42
+ const { staticPath } = cosmosConfig;
43
+ if (!staticPath) {
44
+ return;
45
+ }
46
+ const { exportPath } = cosmosConfig;
47
+ if (exportPath.indexOf(staticPath) !== -1) {
48
+ console.warn(`[Cosmos] Warning: Can't export static path because it contains the export path! (avoiding infinite loop)`);
49
+ console.warn('Public path:', staticPath);
50
+ console.warn('Export path:', exportPath);
51
+ return;
52
+ }
53
+ const staticStat = await fs.stat(staticPath);
54
+ if (!staticStat.isDirectory()) {
55
+ console.log(`[Cosmos] Warning: config.staticPath doesn't point to a valid dir`, staticPath);
56
+ return;
57
+ }
58
+ const { publicUrl } = cosmosConfig;
59
+ const exportStaticPath = path.resolve(exportPath, removeLeadingSlash(publicUrl));
60
+ fs.cp(staticPath, exportStaticPath, { recursive: true });
61
+ }
62
+ async function getExportPlugins(pluginConfigs, rootDir) {
63
+ return Promise.all(pluginConfigs
64
+ .filter(pluginConfig => pluginConfig.export)
65
+ .map(pluginConfig => requirePluginModule(rootDir, pluginConfig, 'export')));
66
+ }
67
+ async function exportPlaygroundFiles(cosmosConfig, pluginConfigs) {
68
+ const { exportPath } = cosmosConfig;
69
+ // Copy UI plugins to export path and embed them in the playground HTML
70
+ // with updated paths
71
+ const uiPlugins = pluginConfigs.filter(isUiPlugin);
72
+ const copiedUiPlugins = await Promise.all(uiPlugins.map(p => exportUiPlugin(cosmosConfig, p)));
73
+ await fs.copyFile(resolve('react-cosmos-ui/dist/playground.bundle.js'), path.resolve(exportPath, 'playground.bundle.js'));
74
+ await fs.copyFile(resolve('react-cosmos-ui/dist/playground.bundle.js.map'), path.resolve(exportPath, 'playground.bundle.js.map'));
75
+ await fs.copyFile(getStaticPath('favicon.ico'), path.resolve(exportPath, '_cosmos.ico'));
76
+ const playgroundHtml = await getExportPlaygroundHtml(cosmosConfig, copiedUiPlugins);
77
+ await fs.writeFile(path.resolve(exportPath, 'index.html'), playgroundHtml);
78
+ }
79
+ async function exportUiPlugin(cosmosConfig, pluginConfig) {
80
+ const { rootDir, exportPath } = cosmosConfig;
81
+ const pluginPath = path.join(exportPath, '_plugin');
82
+ const pluginRootDir = path.resolve(rootDir, pluginConfig.rootDir);
83
+ const srcUiPath = path.resolve(rootDir, pluginConfig.ui);
84
+ const relUiPath = path.relative(pluginRootDir, srcUiPath);
85
+ const pluginDirName = pluginRootDir.split(path.sep).pop();
86
+ const targetUiPath = path.resolve(pluginPath, pluginDirName, relUiPath);
87
+ await fs.mkdir(path.dirname(targetUiPath), { recursive: true });
88
+ await fs.copyFile(srcUiPath, targetUiPath);
89
+ return {
90
+ name: pluginConfig.name,
91
+ rootDir: pluginDirName,
92
+ ui: path.relative(pluginPath, targetUiPath),
93
+ };
94
+ }
95
+ function isUiPlugin(pluginConfig) {
96
+ return Boolean(pluginConfig.ui);
97
+ }
@@ -0,0 +1,14 @@
1
+ import { ReactElement } from 'react';
2
+ import { CosmosConfig } from '../cosmosConfig/types.js';
3
+ export type FixtureApi = {
4
+ absoluteFilePath: string;
5
+ fileName: string;
6
+ getElement: () => ReactElement;
7
+ name: string | null;
8
+ parents: string[];
9
+ playgroundUrl: string;
10
+ relativeFilePath: string;
11
+ rendererUrl: string;
12
+ treePath: string[];
13
+ };
14
+ export declare function getFixtures(cosmosConfig: CosmosConfig): FixtureApi[];
@@ -0,0 +1,63 @@
1
+ import path from 'path';
2
+ import { createFixtureTree, flattenFixtureTree, getDecoratedFixtureElement, getFixtureListFromExports, getSortedDecoratorsForFixturePath, stringifyPlaygroundUrlQuery, stringifyRendererUrlQuery, } from 'react-cosmos-core';
3
+ import { RENDERER_FILENAME } from '../shared/playgroundHtml.js';
4
+ import { resolveUrlPath } from '../shared/resolveUrlPath.js';
5
+ import { getUserModules } from '../userDeps/getUserModules.js';
6
+ export function getFixtures(cosmosConfig) {
7
+ const { fixturesDir, fixtureFileSuffix, rootDir } = cosmosConfig;
8
+ const fixtureInfo = [];
9
+ const { fixtures, decorators } = getUserModules(cosmosConfig);
10
+ const fixtureList = getFixtureListFromExports(fixtures);
11
+ const fixtureTree = createFixtureTree({
12
+ fixtures: fixtureList,
13
+ fixturesDir,
14
+ fixtureFileSuffix,
15
+ });
16
+ const flatFixtureTree = flattenFixtureTree(fixtureTree);
17
+ flatFixtureTree.forEach(({ fileName, fixtureId, name, parents }) => {
18
+ const fixtureExport = fixtures[fixtureId.path];
19
+ const fixture = fixtureId.name === undefined
20
+ ? fixtureExport
21
+ : fixtureExport[fixtureId.name];
22
+ const treePath = [...parents, fileName];
23
+ if (name)
24
+ treePath.push(name);
25
+ fixtureInfo.push({
26
+ absoluteFilePath: path.join(rootDir, fixtureId.path),
27
+ fileName,
28
+ getElement: createFixtureElementGetter(fixture, fixtureId.path, decorators),
29
+ name,
30
+ parents,
31
+ playgroundUrl: getPlaygroundUrl(cosmosConfig, fixtureId),
32
+ relativeFilePath: fixtureId.path,
33
+ rendererUrl: getRendererUrl(cosmosConfig, fixtureId),
34
+ treePath,
35
+ });
36
+ });
37
+ return fixtureInfo;
38
+ }
39
+ function getPlaygroundUrl(cosmosConfig, fixtureId) {
40
+ const host = getPlaygroundHost(cosmosConfig);
41
+ const query = stringifyPlaygroundUrlQuery({ fixtureId });
42
+ return `${host}/?${query}`;
43
+ }
44
+ function getRendererUrl(cosmosConfig, fixtureId) {
45
+ const { publicUrl, rendererUrl } = cosmosConfig;
46
+ const query = stringifyRendererUrlQuery({ _fixtureId: fixtureId });
47
+ if (rendererUrl)
48
+ return `${rendererUrl}?${query}`;
49
+ const host = getPlaygroundHost(cosmosConfig);
50
+ const urlPath = resolveUrlPath(publicUrl, RENDERER_FILENAME);
51
+ return `${host}${urlPath}?${query}`;
52
+ }
53
+ function getPlaygroundHost({ hostname, port, https }) {
54
+ return `${https ? 'https' : 'http'}://${hostname || 'localhost'}:${port}`;
55
+ }
56
+ function createFixtureElementGetter(fixture, fixturePath, decoratorsByPath) {
57
+ const decorators = getSortedDecoratorsForFixturePath(fixturePath, decoratorsByPath);
58
+ return () => getDecoratedFixtureElement(fixture, decorators, {
59
+ fixtureState: {},
60
+ setFixtureState: () => { },
61
+ onErrorReset: () => { },
62
+ });
63
+ }
@@ -0,0 +1,2 @@
1
+ import { CosmosPluginConfig } from 'react-cosmos-core';
2
+ export declare function logPluginInfo(pluginConfigs: CosmosPluginConfig[]): void;
@@ -0,0 +1,8 @@
1
+ export function logPluginInfo(pluginConfigs) {
2
+ const pluginCount = pluginConfigs.length;
3
+ if (pluginCount > 0) {
4
+ const pluginLabel = pluginCount === 1 ? 'plugin' : 'plugins';
5
+ const pluginNames = pluginConfigs.map(p => p.name).join(', ');
6
+ console.log(`[Cosmos] Found ${pluginCount} ${pluginLabel}: ${pluginNames}`);
7
+ }
8
+ }
@@ -0,0 +1,6 @@
1
+ import { CosmosPluginConfig } from 'react-cosmos-core';
2
+ import { CosmosConfig } from '../cosmosConfig/types.js';
3
+ import { PlatformType } from '../cosmosPlugin/types.js';
4
+ export declare const RENDERER_FILENAME = "_renderer.html";
5
+ export declare function getDevPlaygroundHtml(platformType: PlatformType, cosmosConfig: CosmosConfig, pluginConfigs: CosmosPluginConfig[]): Promise<string>;
6
+ export declare function getExportPlaygroundHtml(cosmosConfig: CosmosConfig, pluginConfigs: CosmosPluginConfig[]): Promise<string>;
@@ -0,0 +1,85 @@
1
+ import fs from 'fs';
2
+ import { readFile } from 'fs/promises';
3
+ import path from 'path';
4
+ import { pkgUpSync } from 'pkg-up';
5
+ import { replaceKeys } from 'react-cosmos-core';
6
+ import { resolveUrlPath } from './resolveUrlPath.js';
7
+ import { getStaticPath } from './staticPath.js';
8
+ export const RENDERER_FILENAME = '_renderer.html';
9
+ export async function getDevPlaygroundHtml(platformType, cosmosConfig, pluginConfigs) {
10
+ const { ui } = cosmosConfig;
11
+ return getPlaygroundHtml({
12
+ playgroundConfig: {
13
+ ...ui,
14
+ core: await getDevCoreConfig(platformType, cosmosConfig),
15
+ },
16
+ pluginConfigs,
17
+ });
18
+ }
19
+ export async function getExportPlaygroundHtml(cosmosConfig, pluginConfigs) {
20
+ const { ui } = cosmosConfig;
21
+ return getPlaygroundHtml({
22
+ playgroundConfig: {
23
+ ...ui,
24
+ core: await getExportCoreConfig(cosmosConfig),
25
+ },
26
+ pluginConfigs,
27
+ });
28
+ }
29
+ async function getDevCoreConfig(platformType, cosmosConfig) {
30
+ switch (platformType) {
31
+ case 'native':
32
+ return {
33
+ ...(await getSharedCoreConfig(cosmosConfig)),
34
+ devServerOn: true,
35
+ webRendererUrl: null,
36
+ };
37
+ case 'web':
38
+ return {
39
+ ...(await getSharedCoreConfig(cosmosConfig)),
40
+ devServerOn: true,
41
+ webRendererUrl: cosmosConfig.rendererUrl ||
42
+ resolveUrlPath(cosmosConfig.publicUrl, RENDERER_FILENAME),
43
+ };
44
+ default:
45
+ throw new Error(`Invalid platform type: ${platformType}`);
46
+ }
47
+ }
48
+ async function getExportCoreConfig(cosmosConfig) {
49
+ return {
50
+ ...(await getSharedCoreConfig(cosmosConfig)),
51
+ devServerOn: false,
52
+ webRendererUrl: resolveUrlPath(cosmosConfig.publicUrl, RENDERER_FILENAME),
53
+ };
54
+ }
55
+ async function getSharedCoreConfig(cosmosConfig) {
56
+ const { rootDir, fixturesDir, fixtureFileSuffix } = cosmosConfig;
57
+ return {
58
+ projectId: await getProjectId(rootDir),
59
+ fixturesDir,
60
+ fixtureFileSuffix,
61
+ };
62
+ }
63
+ async function getProjectId(rootDir) {
64
+ const pkgPath = pkgUpSync({ cwd: rootDir });
65
+ if (!pkgPath) {
66
+ return rootDir.split(path.sep).pop();
67
+ }
68
+ try {
69
+ const pkg = JSON.parse(await readFile(pkgPath, 'utf8'));
70
+ return pkg.name || 'new-project';
71
+ }
72
+ catch (err) {
73
+ console.log('Failed to read package.json');
74
+ console.log(err);
75
+ return 'new-project';
76
+ }
77
+ }
78
+ function getPlaygroundHtml(playgroundArgs) {
79
+ return replaceKeys(getPlaygroundHtmlTemplate(), {
80
+ __PLAYGROUND_ARGS: JSON.stringify(playgroundArgs),
81
+ });
82
+ }
83
+ function getPlaygroundHtmlTemplate() {
84
+ return fs.readFileSync(getStaticPath('index.html'), 'utf8');
85
+ }
@@ -0,0 +1,2 @@
1
+ import { CosmosConfig } from '../cosmosConfig/types.js';
2
+ export declare function getPlaygroundUrl(cosmosConfig: CosmosConfig): string;
@@ -0,0 +1,6 @@
1
+ export function getPlaygroundUrl(cosmosConfig) {
2
+ const { hostname, port, https: httpsEnabled } = cosmosConfig;
3
+ const protocol = httpsEnabled ? 'https' : 'http';
4
+ const hostnameDisplay = hostname || 'localhost';
5
+ return `${protocol}://${hostnameDisplay}:${port}`;
6
+ }
@@ -0,0 +1,2 @@
1
+ import { CosmosPluginConfig } from 'react-cosmos-core';
2
+ export declare function requirePluginModule<T>(rootDir: string, pluginConfig: CosmosPluginConfig, configKey: 'ui' | 'devServer' | 'export'): Promise<T>;
@@ -0,0 +1,10 @@
1
+ import path from 'path';
2
+ import { pathToFileURL } from 'url';
3
+ export async function requirePluginModule(rootDir, pluginConfig, configKey) {
4
+ const moduleId = pluginConfig[configKey];
5
+ if (!moduleId) {
6
+ throw new Error(`Module missing in plugin "${pluginConfig.name}": ${configKey}`);
7
+ }
8
+ const esModule = await import(pathToFileURL(path.resolve(rootDir, moduleId)).href);
9
+ return esModule.default;
10
+ }
@@ -0,0 +1 @@
1
+ export declare function resolveUrlPath(base: string, urlPath: string): string;
@@ -0,0 +1,12 @@
1
+ // resolveUrlPath('/', '_renderer.html') => '/_renderer.html'
2
+ // resolveUrlPath('./', '_renderer.html') => '/_renderer.html'
3
+ // resolveUrlPath('http://localhost:5000', '_renderer.html') => 'http://localhost:5000/_renderer.html'
4
+ export function resolveUrlPath(base, urlPath) {
5
+ // The 'resolve://' protocol is only added when base is a relative URL.
6
+ const resolvedUrl = new URL(urlPath, new URL(base, 'resolve://'));
7
+ if (resolvedUrl.protocol === 'resolve:') {
8
+ const { pathname, search, hash } = resolvedUrl;
9
+ return pathname + search + hash;
10
+ }
11
+ return resolvedUrl.toString();
12
+ }
@@ -0,0 +1 @@
1
+ export declare function getStaticPath(relPath: string): string;
@@ -0,0 +1,4 @@
1
+ import { fileURLToPath } from 'url';
2
+ export function getStaticPath(relPath) {
3
+ return fileURLToPath(new URL(`../static/${relPath}`, import.meta.url));
4
+ }
@@ -1,3 +1,2 @@
1
1
  import express from 'express';
2
- export declare function getStaticPath(relPath: string): string;
3
2
  export declare function serveStaticDir(app: express.Application, staticPath: string, publicUrl: string): void;
@@ -0,0 +1,12 @@
1
+ import express from 'express';
2
+ import path from 'path';
3
+ import { removeLeadingDot } from 'react-cosmos-core';
4
+ export function serveStaticDir(app, staticPath, publicUrl) {
5
+ const relStaticPath = path.relative(process.cwd(), staticPath);
6
+ console.log(`[Cosmos] Serving static files from ${relStaticPath}`);
7
+ app.use(removeLeadingDot(publicUrl), express.static(staticPath, {
8
+ // Ensure Playground index loads instead an index.html found in the
9
+ // static path
10
+ index: false,
11
+ }));
12
+ }
@@ -11,7 +11,7 @@
11
11
  </head>
12
12
  <body>
13
13
  <div id="root"></div>
14
- <script src="_playground.js"></script>
14
+ <script src="playground.bundle.js"></script>
15
15
  <script>
16
16
  mountPlayground(__PLAYGROUND_ARGS);
17
17
  </script>
@@ -0,0 +1 @@
1
+ export declare function getCwdPath(relPath?: string): string;
@@ -0,0 +1,4 @@
1
+ import path from 'path';
2
+ export function getCwdPath(relPath = '.') {
3
+ return path.resolve(process.cwd(), relPath);
4
+ }
@@ -0,0 +1,5 @@
1
+ type ConsoleMockApi = {
2
+ expectLog: (msg: string) => void;
3
+ };
4
+ export declare function mockConsole<R>(cb: (api: ConsoleMockApi) => Promise<R>): Promise<R>;
5
+ export {};