@faasjs/vite 8.0.0-beta.3 → 8.0.0-beta.4

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/README.md CHANGED
@@ -25,6 +25,8 @@ export default defineConfig({
25
25
  })
26
26
  ```
27
27
 
28
+ The plugin starts an in-process FaasJS server during Vite development.
29
+
28
30
  ## Options
29
31
 
30
32
  See [ViteFaasJsServerOptions](type-aliases/ViteFaasJsServerOptions.md) for more options.
package/dist/index.cjs CHANGED
@@ -1,26 +1,38 @@
1
1
  'use strict';
2
2
 
3
- var child_process = require('child_process');
4
- var http = require('http');
3
+ var path = require('path');
5
4
  var logger = require('@faasjs/logger');
5
+ var server = require('@faasjs/server');
6
6
 
7
7
  // src/index.ts
8
+ function normalizeBase(base) {
9
+ const normalized = base.startsWith("/") ? base : `/${base}`;
10
+ if (normalized === "/") return "/";
11
+ return normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
12
+ }
13
+ function stripBase(url, base) {
14
+ if (base === "/") return url;
15
+ const queryIndex = url.indexOf("?");
16
+ const pathname = queryIndex >= 0 ? url.slice(0, queryIndex) : url;
17
+ const search = queryIndex >= 0 ? url.slice(queryIndex) : "";
18
+ if (pathname === base) return `/${search}`;
19
+ if (pathname.startsWith(`${base}/`))
20
+ return `${pathname.slice(base.length)}${search}`;
21
+ return url;
22
+ }
8
23
  function viteFaasJsServer(options = {}) {
9
24
  let config;
10
- let childProcess = null;
25
+ let server$1 = null;
11
26
  const logger$1 = new logger.Logger("FaasJs:Vite");
12
27
  return {
13
28
  name: "vite:faasjs",
14
29
  enforce: "pre",
15
30
  configResolved(resolvedConfig) {
16
31
  const root = options.root || resolvedConfig.root;
17
- const base = options.base || resolvedConfig.base;
18
- const port = options.port || 3e3;
32
+ const base = normalizeBase(options.base || resolvedConfig.base);
19
33
  config = {
20
34
  root,
21
- base,
22
- port,
23
- command: options.command || `npm exec faas dev -- -p ${port} -r ${root}${base} -v`
35
+ base
24
36
  };
25
37
  },
26
38
  configureServer: async ({ middlewares }) => {
@@ -29,87 +41,33 @@ function viteFaasJsServer(options = {}) {
29
41
  return;
30
42
  }
31
43
  if (!config) throw new Error("viteFaasJsServer: config is not resolved");
32
- if (childProcess) {
33
- childProcess.kill();
34
- childProcess = null;
35
- }
36
- childProcess = child_process.spawn(config.command, {
37
- stdio: "pipe",
38
- shell: true
39
- });
40
- childProcess.stdout.on("data", (data) => logger$1.raw(data.toString().trim()));
41
- childProcess.stderr.on("data", (data) => logger$1.raw(data.toString().trim()));
44
+ server$1 = new server.Server(path.join(config.root, "src"));
42
45
  middlewares.use(async (req, res, next) => {
43
- if (!req.url || req.method !== "POST") return next();
46
+ if (!req.url || req.method !== "POST" || !server$1) return next();
47
+ const originalUrl = req.url;
48
+ const strippedUrl = stripBase(req.url, config.base);
49
+ req.url = strippedUrl;
44
50
  try {
45
- const targetUrl = `http://localhost:${config.port}${req.url.replace(config.base, "/")}`;
46
- let body = null;
47
- const chunks = [];
48
- for await (const chunk of req) {
49
- chunks.push(chunk);
50
- }
51
- body = Buffer.concat(chunks).toString();
52
- try {
53
- if (body) body = JSON.parse(body);
54
- } catch (e) {
55
- logger$1.error("Failed to parse JSON:", e);
56
- }
57
- const headers = {};
58
- for (const [key, value] of Object.entries(req.headers))
59
- if (!["host", "connection"].includes(key)) headers[key] = value;
60
- return new Promise((resolve) => {
61
- logger$1.debug(`Request ${targetUrl}`);
62
- try {
63
- const proxyReq = http.request(
64
- targetUrl,
65
- {
66
- method: "POST",
67
- headers
68
- },
69
- (proxyRes) => {
70
- res.statusCode = proxyRes.statusCode || 200;
71
- for (const key of Object.keys(proxyRes.headers)) {
72
- const value = proxyRes.headers[key];
73
- if (value) res.setHeader(key, value);
74
- }
75
- proxyRes.pipe(res);
76
- }
77
- );
78
- if (body) {
79
- proxyReq.write(JSON.stringify(body));
80
- }
81
- proxyReq.on("error", (err) => {
82
- logger$1.error(err);
83
- next();
84
- resolve();
85
- });
86
- proxyReq.end();
87
- } catch (err) {
88
- logger$1.error(err);
89
- if (!res.headersSent) {
90
- res.writeHead(500, { "Content-Type": "application/json" });
91
- res.write(
92
- JSON.stringify({
93
- error: { message: "Internal Server Error" }
94
- })
95
- );
96
- res.end();
97
- }
98
- next();
99
- resolve();
100
- }
51
+ logger$1.debug(`Request ${req.url}`);
52
+ await server$1.handle(req, res, {
53
+ requestedAt: Date.now()
101
54
  });
102
55
  } catch (error) {
103
56
  logger$1.error(error);
104
- return next();
57
+ if (!res.headersSent && !res.writableEnded) {
58
+ res.writeHead(500, { "Content-Type": "application/json" });
59
+ res.write(
60
+ JSON.stringify({
61
+ error: { message: "Internal Server Error" }
62
+ })
63
+ );
64
+ res.end();
65
+ }
66
+ } finally {
67
+ req.url = originalUrl;
105
68
  }
69
+ if (!res.writableEnded) next();
106
70
  });
107
- },
108
- closeBundle() {
109
- if (childProcess) {
110
- childProcess.kill();
111
- childProcess = null;
112
- }
113
71
  }
114
72
  };
115
73
  }
package/dist/index.d.ts CHANGED
@@ -1,15 +1,11 @@
1
1
  import { Plugin } from 'vite';
2
2
 
3
3
  type ViteFaasJsServerOptions = {
4
- /** faas server root path, default is vite's root */
4
+ /** faas project root path, default is vite's root */
5
5
  root: string;
6
6
  /** faas server base path, default is vite's base */
7
7
  base: string;
8
- /** faas server port, 3000 as default */
9
- port: number;
10
- /** custom command to run the faas server */
11
- command: string;
12
8
  };
13
- declare function viteFaasJsServer(options?: Partial<ViteFaasJsServerOptions>): Plugin;
9
+ declare function viteFaasJsServer(options?: Partial<ViteFaasJsServerOptions> & Record<string, unknown>): Plugin;
14
10
 
15
11
  export { type ViteFaasJsServerOptions, viteFaasJsServer };
package/dist/index.mjs CHANGED
@@ -1,24 +1,36 @@
1
- import { spawn } from 'child_process';
2
- import { request } from 'http';
1
+ import { join } from 'path';
3
2
  import { Logger } from '@faasjs/logger';
3
+ import { Server } from '@faasjs/server';
4
4
 
5
5
  // src/index.ts
6
+ function normalizeBase(base) {
7
+ const normalized = base.startsWith("/") ? base : `/${base}`;
8
+ if (normalized === "/") return "/";
9
+ return normalized.endsWith("/") ? normalized.slice(0, -1) : normalized;
10
+ }
11
+ function stripBase(url, base) {
12
+ if (base === "/") return url;
13
+ const queryIndex = url.indexOf("?");
14
+ const pathname = queryIndex >= 0 ? url.slice(0, queryIndex) : url;
15
+ const search = queryIndex >= 0 ? url.slice(queryIndex) : "";
16
+ if (pathname === base) return `/${search}`;
17
+ if (pathname.startsWith(`${base}/`))
18
+ return `${pathname.slice(base.length)}${search}`;
19
+ return url;
20
+ }
6
21
  function viteFaasJsServer(options = {}) {
7
22
  let config;
8
- let childProcess = null;
23
+ let server = null;
9
24
  const logger = new Logger("FaasJs:Vite");
10
25
  return {
11
26
  name: "vite:faasjs",
12
27
  enforce: "pre",
13
28
  configResolved(resolvedConfig) {
14
29
  const root = options.root || resolvedConfig.root;
15
- const base = options.base || resolvedConfig.base;
16
- const port = options.port || 3e3;
30
+ const base = normalizeBase(options.base || resolvedConfig.base);
17
31
  config = {
18
32
  root,
19
- base,
20
- port,
21
- command: options.command || `npm exec faas dev -- -p ${port} -r ${root}${base} -v`
33
+ base
22
34
  };
23
35
  },
24
36
  configureServer: async ({ middlewares }) => {
@@ -27,87 +39,33 @@ function viteFaasJsServer(options = {}) {
27
39
  return;
28
40
  }
29
41
  if (!config) throw new Error("viteFaasJsServer: config is not resolved");
30
- if (childProcess) {
31
- childProcess.kill();
32
- childProcess = null;
33
- }
34
- childProcess = spawn(config.command, {
35
- stdio: "pipe",
36
- shell: true
37
- });
38
- childProcess.stdout.on("data", (data) => logger.raw(data.toString().trim()));
39
- childProcess.stderr.on("data", (data) => logger.raw(data.toString().trim()));
42
+ server = new Server(join(config.root, "src"));
40
43
  middlewares.use(async (req, res, next) => {
41
- if (!req.url || req.method !== "POST") return next();
44
+ if (!req.url || req.method !== "POST" || !server) return next();
45
+ const originalUrl = req.url;
46
+ const strippedUrl = stripBase(req.url, config.base);
47
+ req.url = strippedUrl;
42
48
  try {
43
- const targetUrl = `http://localhost:${config.port}${req.url.replace(config.base, "/")}`;
44
- let body = null;
45
- const chunks = [];
46
- for await (const chunk of req) {
47
- chunks.push(chunk);
48
- }
49
- body = Buffer.concat(chunks).toString();
50
- try {
51
- if (body) body = JSON.parse(body);
52
- } catch (e) {
53
- logger.error("Failed to parse JSON:", e);
54
- }
55
- const headers = {};
56
- for (const [key, value] of Object.entries(req.headers))
57
- if (!["host", "connection"].includes(key)) headers[key] = value;
58
- return new Promise((resolve) => {
59
- logger.debug(`Request ${targetUrl}`);
60
- try {
61
- const proxyReq = request(
62
- targetUrl,
63
- {
64
- method: "POST",
65
- headers
66
- },
67
- (proxyRes) => {
68
- res.statusCode = proxyRes.statusCode || 200;
69
- for (const key of Object.keys(proxyRes.headers)) {
70
- const value = proxyRes.headers[key];
71
- if (value) res.setHeader(key, value);
72
- }
73
- proxyRes.pipe(res);
74
- }
75
- );
76
- if (body) {
77
- proxyReq.write(JSON.stringify(body));
78
- }
79
- proxyReq.on("error", (err) => {
80
- logger.error(err);
81
- next();
82
- resolve();
83
- });
84
- proxyReq.end();
85
- } catch (err) {
86
- logger.error(err);
87
- if (!res.headersSent) {
88
- res.writeHead(500, { "Content-Type": "application/json" });
89
- res.write(
90
- JSON.stringify({
91
- error: { message: "Internal Server Error" }
92
- })
93
- );
94
- res.end();
95
- }
96
- next();
97
- resolve();
98
- }
49
+ logger.debug(`Request ${req.url}`);
50
+ await server.handle(req, res, {
51
+ requestedAt: Date.now()
99
52
  });
100
53
  } catch (error) {
101
54
  logger.error(error);
102
- return next();
55
+ if (!res.headersSent && !res.writableEnded) {
56
+ res.writeHead(500, { "Content-Type": "application/json" });
57
+ res.write(
58
+ JSON.stringify({
59
+ error: { message: "Internal Server Error" }
60
+ })
61
+ );
62
+ res.end();
63
+ }
64
+ } finally {
65
+ req.url = originalUrl;
103
66
  }
67
+ if (!res.writableEnded) next();
104
68
  });
105
- },
106
- closeBundle() {
107
- if (childProcess) {
108
- childProcess.kill();
109
- childProcess = null;
110
- }
111
69
  }
112
70
  };
113
71
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@faasjs/vite",
3
- "version": "v8.0.0-beta.3",
3
+ "version": "v8.0.0-beta.4",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -30,11 +30,11 @@
30
30
  "dist"
31
31
  ],
32
32
  "peerDependencies": {
33
- "@faasjs/cli": ">=v8.0.0-beta.3",
33
+ "@faasjs/server": ">=v8.0.0-beta.4",
34
34
  "vite": "*"
35
35
  },
36
36
  "devDependencies": {
37
- "@faasjs/cli": ">=v8.0.0-beta.3",
37
+ "@faasjs/server": ">=v8.0.0-beta.4",
38
38
  "vite": "*"
39
39
  },
40
40
  "engines": {