@data-fair/dev-server 2.0.0 → 2.0.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.
package/package.json CHANGED
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "name": "@data-fair/dev-server",
3
- "version": "2.0.0",
3
+ "version": "2.0.2",
4
4
  "description": "A development server for optimal development experience of data-fair applications.",
5
- "main": "src/index.ts",
5
+ "main": "src/index.js",
6
6
  "bin": {
7
- "df-dev-server": "src/index.ts"
7
+ "df-dev-server": "src/index.js"
8
8
  },
9
9
  "type": "module",
10
10
  "scripts": {
11
- "dev": "NODE_ENV=development node --watch src/index.ts",
11
+ "build": "tsc",
12
+ "dev": "NODE_ENV=development node --watch src/index.js",
12
13
  "dev-test-app-minimal": "http-server test-apps/minimal --port=3000 --cors --silent",
13
14
  "dev-test-app-vue3": "cd test-apps/vue3 && npm run dev",
14
15
  "dev-zellij": "zellij --layout .zellij.kdl",
15
- "prepublishOnly": "npm run lint && npm run check-types && npm -w ui run build",
16
+ "prepublishOnly": "npm run lint && npm run build &&npm -w ui run build",
16
17
  "lint": "eslint . && npm -w ui run lint",
17
18
  "lint-fix": "eslint --fix . && npm -w ui run lint-fix",
18
- "check-types": "tsc && npm -w ui run check-types",
19
19
  "build-types": "df-build-types ."
20
20
  },
21
21
  "workspaces": [
@@ -58,6 +58,7 @@
58
58
  "cors": "^2.8.5",
59
59
  "debug": "^4.4.1",
60
60
  "dotenv": "^17.0.0",
61
+ "escape-string-regexp": "^5.0.0",
61
62
  "express": "^5.1.0",
62
63
  "http-proxy-middleware": "^3.0.5",
63
64
  "parse5": "^7.3.0",
package/src/app.js ADDED
@@ -0,0 +1,273 @@
1
+ // Express app for TaxMan own API and UI
2
+ import config from './config.js';
3
+ import uiConfig from './ui-config.js';
4
+ import { WebSocket, WebSocketServer } from 'ws';
5
+ import { createServer } from 'node:http';
6
+ import express from 'express';
7
+ import cors from 'cors';
8
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
9
+ import debugModule from 'debug';
10
+ import { createProxyMiddleware, fixRequestBody } from 'http-proxy-middleware';
11
+ import * as parse5 from 'parse5';
12
+ import chalk from 'chalk';
13
+ import { isElementNode, createTextNode, createElement } from '@parse5/tools';
14
+ import escapeStringRegexp from 'escape-string-regexp';
15
+ import eventPromise from '@data-fair/lib-utils/event-promise.js';
16
+ import { createSpaMiddleware } from '@data-fair/lib-express/serve-spa.js';
17
+ import { resolve } from 'node:path';
18
+ const debug = debugModule('df-dev-server');
19
+ const app = express();
20
+ const server = createServer(app);
21
+ // web socket server, used both by dev-server UI (opened on / path)
22
+ // and by application (opened on /data-fair), in this case we transmit all messages to and from data-fair
23
+ const wss = new WebSocketServer({ noServer: true });
24
+ let devServerWS;
25
+ let dataFairWS;
26
+ server.on('upgrade', function upgrade(req, socket, head) {
27
+ wss.handleUpgrade(req, socket, head, (ws) => {
28
+ if (req.url === '/data-fair') {
29
+ if (dataFairWS)
30
+ dataFairWS.terminate();
31
+ dataFairWS = ws;
32
+ ws.on('message', (data) => {
33
+ if (dataFairOutputWS) {
34
+ const message = JSON.parse(data);
35
+ if (message.type === 'subscribe')
36
+ message.apiKey = config.dataFair.apiKey;
37
+ dataFairOutputWS.send(JSON.stringify(message));
38
+ }
39
+ });
40
+ }
41
+ else {
42
+ if (devServerWS)
43
+ devServerWS.terminate();
44
+ devServerWS = ws;
45
+ }
46
+ wss.emit('connection', ws, req);
47
+ });
48
+ });
49
+ const dfWsUrl = config.dataFair.url.replace('http://', 'ws://').replace('https://', 'wss://') + '/';
50
+ const dataFairOutputWS = new WebSocket(dfWsUrl);
51
+ dataFairOutputWS.on('open', () => dataFairOutputWS.send('connect to external websocket server ' + dfWsUrl));
52
+ dataFairOutputWS.on('message', (data) => { if (dataFairWS)
53
+ dataFairWS.send(data.toString()); });
54
+ dataFairOutputWS.on('error', (err) => console.error('failed to connect to external websocket server', dfWsUrl, err));
55
+ app.use(cors());
56
+ app.use(express.json());
57
+ // very basic CRUD of config
58
+ app.get('/config', (req, res, next) => {
59
+ const devConfig = existsSync('.dev-config.json') ? JSON.parse(readFileSync('.dev-config.json', 'utf8')) : {};
60
+ debug('read dev config', devConfig);
61
+ res.send(devConfig);
62
+ });
63
+ app.put('/config', (req, res, next) => {
64
+ debug('save dev config', req.body);
65
+ writeFileSync('.dev-config.json', JSON.stringify(req.body, null, 2));
66
+ res.send(req.body);
67
+ });
68
+ app.post('/config/error', (req, res) => {
69
+ console.log('Application sent an error', req.body);
70
+ if (devServerWS)
71
+ devServerWS.send(JSON.stringify({ type: 'app-error', data: req.body }));
72
+ else
73
+ console.error('no dev-server websocket open to send error to');
74
+ res.send();
75
+ });
76
+ // re-expose the application performing similar modifications to the body as data-fair
77
+ const appUrl = new URL(config.app.url);
78
+ const appPrefix = appUrl.pathname === '/' ? '' : appUrl.pathname;
79
+ app.use('/app', createProxyMiddleware({
80
+ target: appUrl.origin,
81
+ secure: false,
82
+ changeOrigin: true,
83
+ selfHandleResponse: true, // so that the onProxyRes takes care of sending the response
84
+ on: {
85
+ proxyReq(proxyReq, req, res) {
86
+ proxyReq.path = appPrefix + proxyReq.path;
87
+ proxyReq.setHeader('Accept-Encoding', 'identity'); // disable compression
88
+ },
89
+ proxyRes(proxyRes, req, res) {
90
+ const configuration = existsSync('.dev-config.json') ? JSON.parse(readFileSync('.dev-config.json', 'utf8')) : {};
91
+ // console.log('inject config', configuration)
92
+ const dataBuffers = [];
93
+ proxyRes.on('data', (data) => { dataBuffers.push(data); });
94
+ proxyRes.on('end', async () => {
95
+ try {
96
+ let output = Buffer.concat(dataBuffers).toString();
97
+ if (output.includes('%APPLICATION%')) {
98
+ const filledBody = output.replace(/%APPLICATION%/g, JSON.stringify({
99
+ id: 'dev-application',
100
+ title: 'Dev application',
101
+ configuration,
102
+ exposedUrl: `http://localhost:${config.port}/app`,
103
+ href: `http://localhost:${config.port}/config`,
104
+ apiUrl: `http://localhost:${config.port}/data-fair/api/v1`,
105
+ wsUrl: `ws://localhost:${config.port}/data-fair`,
106
+ owner: config.dataFair && config.dataFair.owner
107
+ }));
108
+ const document = parse5.parse(filledBody);
109
+ const html = document.childNodes.filter(isElementNode).find(c => c.tagName === 'html');
110
+ if (!html)
111
+ throw new Error('HTML structure is broken, expect html, head and body elements');
112
+ const headNode = html.childNodes.filter(isElementNode).find(c => c.tagName === 'head');
113
+ const bodyNode = html.childNodes.filter(isElementNode).find(c => c.tagName === 'body');
114
+ if (!headNode || !bodyNode)
115
+ throw new Error('HTML structure is broken, expect html, head and body elements');
116
+ // add a script to simulate instrumentation by capture service
117
+ // @ts-ignore
118
+ const query = req.query;
119
+ if (query.thumbnail === 'true') {
120
+ const script = createElement('script', { type: 'text/javascript' });
121
+ script.childNodes.push(createTextNode(`
122
+ console.log('[capture] Simulate a screenshot capture context')
123
+ var triggerCalled = false
124
+ window.triggerCapture = function (animationSupported) {
125
+ triggerCalled = true
126
+ console.log('[capture] triggerCapture called')
127
+ if (animationSupported) {
128
+ console.log('[capture] this application supports animated screenshots')
129
+ var i = 0
130
+ const interval = setInterval(function () {
131
+ i++
132
+ if (i === 1800) {
133
+ console.error('[capture] stop after the maximum number of frames was attained')
134
+ clearInterval(interval)
135
+ }
136
+ var stopped = window.animateCaptureFrame()
137
+ if (stopped) {
138
+ console.log('[capture] animation was stopped after ' + i + ' frames')
139
+ clearInterval(interval)
140
+ }
141
+ }, 67)
142
+ return true
143
+ } else {
144
+ console.log('[capture] this application does not support animated screenshots')
145
+ }
146
+ }
147
+ setTimeout(function() {
148
+ if (!triggerCalled) {
149
+ console.error('[capture] triggerCapture was not called after a 5s wait')
150
+ }
151
+ }, 5000)
152
+ `));
153
+ headNode.childNodes.push(script);
154
+ }
155
+ const meta = {};
156
+ for (const node of headNode.childNodes.filter(isElementNode)) {
157
+ if (node.tagName === 'meta') {
158
+ const name = node.attrs.find(a => a.name === 'name')?.value;
159
+ const content = node.attrs.find(a => a.name === 'content')?.value;
160
+ if (name !== undefined && content !== undefined)
161
+ meta[name] = content;
162
+ }
163
+ }
164
+ if (meta['df:sync-state'] === 'true' || meta['df:overflow'] === 'true') {
165
+ bodyNode.childNodes.push(createElement('script', {
166
+ type: 'text/javascript',
167
+ src: 'https://cdn.jsdelivr.net/npm/@data-fair/frame@0.12/dist/v-iframe-compat/d-frame-content.min.js'
168
+ }));
169
+ }
170
+ output = parse5.serialize(document);
171
+ // proxyRes.headers['content-length'] = output.length
172
+ delete proxyRes.headers['content-length'];
173
+ delete proxyRes.headers['last-modified'];
174
+ delete proxyRes.headers['max-age'];
175
+ delete proxyRes.headers.etag;
176
+ proxyRes.headers['cache-control'] = 'no-cache';
177
+ }
178
+ res.writeHead(proxyRes.statusCode ?? 200, proxyRes.headers);
179
+ res.end(output);
180
+ }
181
+ catch (err) {
182
+ console.error(err);
183
+ res.writeHead(500);
184
+ res.end(err.message);
185
+ }
186
+ });
187
+ }
188
+ }
189
+ }));
190
+ for (const proxyPath of config.app.proxyPaths) {
191
+ app.use(proxyPath, createProxyMiddleware({
192
+ target: appUrl.origin,
193
+ secure: false,
194
+ changeOrigin: true,
195
+ ws: true
196
+ }));
197
+ }
198
+ // re-expose a data-fair instance to access datasets, etc.
199
+ const dfUrl = new URL(config.dataFair.url);
200
+ app.use('/data-fair', createProxyMiddleware({
201
+ target: dfUrl.origin,
202
+ secure: false,
203
+ changeOrigin: true,
204
+ selfHandleResponse: true, // so that the onProxyRes takes care of sending the response
205
+ on: {
206
+ proxyReq(proxyReq, req, res) {
207
+ proxyReq.path = '/data-fair' + proxyReq.path;
208
+ // no gzip so that we can process the content
209
+ proxyReq.setHeader('accept-encoding', 'identity');
210
+ // authentication through api key only
211
+ proxyReq.setHeader('cookie', '');
212
+ if (config.dataFair.apiKey)
213
+ proxyReq.setHeader('x-apiKey', config.dataFair.apiKey);
214
+ // body was already parsed by body-parser and no longer available as a stream
215
+ fixRequestBody(proxyReq, req);
216
+ },
217
+ proxyRes(proxyRes, req, res) {
218
+ // console.log('DF RES', proxyRes)
219
+ if (proxyRes.headers['content-type'] && proxyRes.headers['content-type'].startsWith('application/json')) {
220
+ let body = '';
221
+ proxyRes.on('data', (data) => { body += data.toString(); });
222
+ proxyRes.on('end', () => {
223
+ const output = body.replace(new RegExp(escapeStringRegexp(config.dataFair.url), 'g'), 'http://localhost:5888/data-fair');
224
+ // proxyRes.headers['content-length'] = output.length
225
+ delete proxyRes.headers['content-length'];
226
+ res.writeHead(proxyRes.statusCode ?? 200, proxyRes.headers);
227
+ // make all references to data-fair url point to local proxy
228
+ res.end(output);
229
+ });
230
+ }
231
+ else {
232
+ res.writeHead(proxyRes.statusCode ?? 200, proxyRes.headers);
233
+ proxyRes.pipe(res);
234
+ }
235
+ }
236
+ }
237
+ }));
238
+ // also re-expose the simple-directory instance matching data-fair
239
+ app.use('/simple-directory', createProxyMiddleware({
240
+ target: dfUrl.origin,
241
+ secure: false,
242
+ changeOrigin: true,
243
+ on: {
244
+ proxyReq(proxyReq, req, res) {
245
+ proxyReq.path = '/simple-directory' + proxyReq.path;
246
+ }
247
+ }
248
+ }));
249
+ if (config.serveUi) {
250
+ app.use(await createSpaMiddleware(resolve(import.meta.dirname, '../ui/dist'), uiConfig));
251
+ }
252
+ else {
253
+ app.use('/', createProxyMiddleware({
254
+ target: 'http://localhost:6220',
255
+ secure: false
256
+ }));
257
+ }
258
+ // Run app and return it in a promise
259
+ export const run = async () => {
260
+ server.listen(config.port);
261
+ await eventPromise(server, 'listening');
262
+ console.log(chalk.bold.blue('\nDataFair dev server available on ') + chalk.underline.bold.blue(`http://localhost:${config.port}`));
263
+ return server;
264
+ };
265
+ export const stop = async () => {
266
+ if (devServerWS)
267
+ devServerWS.terminate();
268
+ if (dataFairWS)
269
+ dataFairWS.terminate();
270
+ server.close();
271
+ await eventPromise(server, 'close');
272
+ await app.get('client').close();
273
+ };
package/src/app.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // Express app for TaxMan own API and UI
2
2
 
3
- import config from './config.ts'
4
- import uiConfig from './ui-config.ts'
3
+ import config from './config.js'
4
+ import uiConfig from './ui-config.js'
5
5
  import { WebSocket, WebSocketServer } from 'ws'
6
6
  import { createServer } from 'node:http'
7
7
  import express from 'express'
package/src/config.js ADDED
@@ -0,0 +1,7 @@
1
+ import { assertValid } from '../config/type/index.js';
2
+ import config from 'config';
3
+ // we reload the config instead of using the singleton from the config module for testing purposes
4
+ // @ts-ignore
5
+ const devServerConfig = process.env.NODE_ENV === 'test' ? config.util.loadFileConfigs(process.env.NODE_CONFIG_DIR, { skipConfigSources: true }) : config;
6
+ assertValid(devServerConfig, { lang: 'en', name: 'config', internal: true });
7
+ export default devServerConfig;
package/src/index.js ADDED
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env node
2
+ import 'dotenv/config';
3
+ import path from 'node:path';
4
+ process.env.NODE_CONFIG_DIR = path.join(import.meta.dirname, '../config');
5
+ const app = await import('./app.js');
6
+ app.run().then(app => {
7
+ // nothing to do
8
+ }, error => {
9
+ console.error('Failure in dev server process', error);
10
+ process.exit(-1);
11
+ });
12
+ process.on('SIGTERM', function onSigterm() {
13
+ console.info('Received SIGTERM signal, shutdown gracefully...');
14
+ app.stop().then(() => {
15
+ console.log('shutting down now');
16
+ process.exit();
17
+ }, err => {
18
+ console.error('Failure while stopping service', err);
19
+ process.exit(-1);
20
+ });
21
+ });
package/src/index.ts CHANGED
@@ -4,7 +4,7 @@ import 'dotenv/config'
4
4
  import path from 'node:path'
5
5
 
6
6
  process.env.NODE_CONFIG_DIR = path.join(import.meta.dirname, '../config')
7
- const app = await import('./app.ts')
7
+ const app = await import('./app.js')
8
8
 
9
9
  app.run().then(app => {
10
10
  // nothing to do
@@ -0,0 +1,3 @@
1
+ import config from './config.js';
2
+ export const uiConfig = { dataFair: config.dataFair };
3
+ export default uiConfig;
package/src/ui-config.ts CHANGED
@@ -1,4 +1,4 @@
1
- import config from './config.ts'
1
+ import config from './config.js'
2
2
 
3
3
  export const uiConfig = { dataFair: config.dataFair }
4
4