@celljs/serve-static 3.8.0 → 4.0.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 (47) hide show
  1. package/cell.yml +2 -2
  2. package/esm/node/embedded-assets.d.ts +20 -0
  3. package/esm/node/embedded-assets.js +70 -0
  4. package/esm/node/embedded-assets.js.map +1 -0
  5. package/esm/node/index.d.ts +2 -0
  6. package/esm/node/index.js +3 -0
  7. package/esm/node/index.js.map +1 -0
  8. package/esm/node/module.d.ts +3 -0
  9. package/esm/node/module.js +4 -0
  10. package/esm/node/module.js.map +1 -0
  11. package/esm/node/serve-static-middleware.d.ts +19 -0
  12. package/esm/node/serve-static-middleware.js +90 -0
  13. package/esm/node/serve-static-middleware.js.map +1 -0
  14. package/esm/node/serve-static.d.ts +3 -0
  15. package/esm/node/serve-static.js +89 -0
  16. package/esm/node/serve-static.js.map +1 -0
  17. package/esm/node/type.d.ts +15 -0
  18. package/esm/node/type.js +2 -0
  19. package/esm/node/type.js.map +1 -0
  20. package/esm/package.json +3 -0
  21. package/lib/node/embedded-assets.d.ts +21 -0
  22. package/lib/node/embedded-assets.d.ts.map +1 -0
  23. package/lib/node/embedded-assets.js +76 -0
  24. package/lib/node/embedded-assets.js.map +1 -0
  25. package/lib/node/embedded-assets.spec.d.ts +2 -0
  26. package/lib/node/embedded-assets.spec.d.ts.map +1 -0
  27. package/lib/node/embedded-assets.spec.js +60 -0
  28. package/lib/node/embedded-assets.spec.js.map +1 -0
  29. package/lib/node/index.d.ts +1 -0
  30. package/lib/node/index.d.ts.map +1 -1
  31. package/lib/node/index.js +1 -0
  32. package/lib/node/index.js.map +1 -1
  33. package/lib/node/serve-static-middleware.d.ts +5 -0
  34. package/lib/node/serve-static-middleware.d.ts.map +1 -1
  35. package/lib/node/serve-static-middleware.js +8 -2
  36. package/lib/node/serve-static-middleware.js.map +1 -1
  37. package/package.json +35 -9
  38. package/src/node/embedded-assets.spec.ts +67 -0
  39. package/src/node/embedded-assets.ts +76 -0
  40. package/src/node/index.ts +1 -0
  41. package/src/node/serve-static-middleware.ts +14 -3
  42. package/cell-remote.yml +0 -3
  43. package/lib/hooks/webpack.d.ts +0 -4
  44. package/lib/hooks/webpack.d.ts.map +0 -1
  45. package/lib/hooks/webpack.js +0 -17
  46. package/lib/hooks/webpack.js.map +0 -1
  47. package/src/hooks/webpack.ts +0 -15
package/cell.yml CHANGED
@@ -1,8 +1,8 @@
1
1
  cell:
2
2
  serve-static:
3
3
  spa: true
4
- root: ${frontendProjectDistPath}
4
+ root: ${paths.public}
5
5
  options:
6
6
  maxAge: 31536000000
7
7
  # htmlMaxAge: 31536000000
8
- immutable: true
8
+ immutable: true
@@ -0,0 +1,20 @@
1
+ import type { ServeStaticOption } from './type.js';
2
+ /** A frontend file inside a server bundle built with `cell build --single`. */
3
+ export interface EmbeddedAsset {
4
+ /** Base64 of the content. */
5
+ body: string;
6
+ etag: string;
7
+ }
8
+ /**
9
+ * Frontend files that a `cell build --single` bundle registers before the application starts, by URL
10
+ * path (`/index.html`, `/assets/index-abc.js`). When they are there, they are served from memory
11
+ * instead of `cell.serve-static.root`.
12
+ */
13
+ export declare namespace EmbeddedAssets {
14
+ const KEY: unique symbol;
15
+ function get(): Map<string, EmbeddedAsset> | undefined;
16
+ /** The counterpart of `serveStatic`: same options, same `next()` when a file is not there. */
17
+ function serve(assets: Map<string, EmbeddedAsset>, opts: ServeStaticOption & {
18
+ maxAge?: number;
19
+ }): (req: any, res: any, next: (err?: unknown) => void) => void;
20
+ }
@@ -0,0 +1,70 @@
1
+ import send from 'send';
2
+ /**
3
+ * Frontend files that a `cell build --single` bundle registers before the application starts, by URL
4
+ * path (`/index.html`, `/assets/index-abc.js`). When they are there, they are served from memory
5
+ * instead of `cell.serve-static.root`.
6
+ */
7
+ export var EmbeddedAssets;
8
+ (function (EmbeddedAssets) {
9
+ EmbeddedAssets.KEY = Symbol.for('@celljs/serve-static/assets');
10
+ const decoded = new Map();
11
+ function get() {
12
+ return globalThis[EmbeddedAssets.KEY];
13
+ }
14
+ EmbeddedAssets.get = get;
15
+ function content(path, asset) {
16
+ let body = decoded.get(path);
17
+ if (!body) {
18
+ body = Buffer.from(asset.body, 'base64');
19
+ decoded.set(path, body);
20
+ }
21
+ return body;
22
+ }
23
+ /** The counterpart of `serveStatic`: same options, same `next()` when a file is not there. */
24
+ function serve(assets, opts) {
25
+ return (req, res, next) => {
26
+ var _a;
27
+ var _b, _c;
28
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
29
+ next();
30
+ return;
31
+ }
32
+ let path;
33
+ try {
34
+ path = decodeURIComponent(new URL(req.url.replace(opts.baseHref, '/'), 'http://localhost').pathname);
35
+ }
36
+ catch (_d) {
37
+ next();
38
+ return;
39
+ }
40
+ if (path.endsWith('/')) {
41
+ path += 'index.html';
42
+ }
43
+ const asset = assets.get(path);
44
+ if (!asset) {
45
+ next();
46
+ return;
47
+ }
48
+ const type = send.mime.lookup(path);
49
+ const charset = send.mime.charsets.lookup(type);
50
+ res.setHeader('Content-Type', charset ? `${type}; charset=${charset}` : type);
51
+ res.setHeader('ETag', asset.etag);
52
+ if (opts.cacheControl !== false) {
53
+ const maxAge = Math.floor(Math.min(Math.max(0, Number((_c = (_b = opts.maxAge) !== null && _b !== void 0 ? _b : opts.maxage) !== null && _c !== void 0 ? _c : 0)), 31536000000) / 1000);
54
+ res.setHeader('Cache-Control', `public, max-age=${maxAge}${opts.immutable ? ', immutable' : ''}`);
55
+ }
56
+ (_a = opts.setHeaders) === null || _a === void 0 ? void 0 : _a.call(opts, res, path, undefined);
57
+ if (req.headers['if-none-match'] === asset.etag) {
58
+ res.statusCode = 304;
59
+ res.end();
60
+ return;
61
+ }
62
+ const body = content(path, asset);
63
+ res.statusCode = 200;
64
+ res.setHeader('Content-Length', body.length);
65
+ res.end(req.method === 'HEAD' ? undefined : body);
66
+ };
67
+ }
68
+ EmbeddedAssets.serve = serve;
69
+ })(EmbeddedAssets || (EmbeddedAssets = {}));
70
+ //# sourceMappingURL=embedded-assets.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"embedded-assets.js","sourceRoot":"","sources":["../../src/node/embedded-assets.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AAUxB;;;;GAIG;AACH,MAAM,KAAW,cAAc,CA4D9B;AA5DD,WAAiB,cAAc;IACd,kBAAG,GAAG,MAAM,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAE7D,MAAM,OAAO,GAAG,IAAI,GAAG,EAAkB,CAAC;IAE1C,SAAgB,GAAG;QACf,OAAQ,UAAqE,CAAC,kBAAG,CAAC,CAAC;IACvF,CAAC;IAFe,eAAA,GAAG,MAElB,CAAA;IAED,SAAS,OAAO,CAAC,IAAY,EAAE,KAAoB;QAC/C,IAAI,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC7B,IAAI,CAAC,IAAI,EAAE,CAAC;YACR,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;YACzC,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,IAAI,CAAC;IAChB,CAAC;IAED,8FAA8F;IAC9F,SAAgB,KAAK,CAAC,MAAkC,EAAE,IAA6C;QACnG,OAAO,CAAC,GAAQ,EAAE,GAAQ,EAAE,IAA6B,EAAE,EAAE;;;YACzD,IAAI,GAAG,CAAC,MAAM,KAAK,KAAK,IAAI,GAAG,CAAC,MAAM,KAAK,MAAM,EAAE,CAAC;gBAChD,IAAI,EAAE,CAAC;gBACP,OAAO;YACX,CAAC;YACD,IAAI,IAAY,CAAC;YACjB,IAAI,CAAC;gBACD,IAAI,GAAG,kBAAkB,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,EAAE,kBAA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,GAAG,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;YACxC,IAAI,GAAG,CAAC,OAAO,CAAC,eAAe,CAAC,KAAK,KAAK,CAAC,IAAI,EAAE,CAAC;gBAC9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC;gBACrB,GAAG,CAAC,GAAG,EAAE,CAAC;gBACV,OAAO;YACX,CAAC;YACD,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YAClC,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC;YACrB,GAAG,CAAC,SAAS,CAAC,gBAAgB,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;YAC7C,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QACtD,CAAC,CAAC;IACN,CAAC;IAxCe,eAAA,KAAK,QAwCpB,CAAA;AACL,CAAC,EA5DgB,cAAc,KAAd,cAAc,QA4D9B"}
@@ -0,0 +1,2 @@
1
+ export * from './serve-static-middleware.js';
2
+ export * from './embedded-assets.js';
@@ -0,0 +1,3 @@
1
+ export * from './serve-static-middleware.js';
2
+ export * from './embedded-assets.js';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":"AACA,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC"}
@@ -0,0 +1,3 @@
1
+ import './index.js';
2
+ declare const _default: import("inversify").interfaces.ContainerModule;
3
+ export default _default;
@@ -0,0 +1,4 @@
1
+ import { autoBind } from '@celljs/core';
2
+ import './index.js';
3
+ export default autoBind();
4
+ //# sourceMappingURL=module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"module.js","sourceRoot":"","sources":["../../src/node/module.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,SAAS,CAAC;AAEjB,eAAe,QAAQ,EAAE,CAAC"}
@@ -0,0 +1,19 @@
1
+ import { Middleware, Context, RequestMatcher } from '@celljs/web/lib/node';
2
+ export declare class ServeStaticMiddleware implements Middleware {
3
+ protected config: {
4
+ spa: boolean;
5
+ root: string;
6
+ path: string;
7
+ apiPath: string;
8
+ options: any;
9
+ };
10
+ protected path: string;
11
+ protected readonly requestMatcher: RequestMatcher;
12
+ /**
13
+ * Whether there is a frontend to serve: embedded in the bundle (`--single`) or on disk. On
14
+ * Cloudflare Workers the platform serves the frontend and the worker has no copy.
15
+ */
16
+ protected hasFrontend?: boolean;
17
+ handle(ctx: Context, next: () => Promise<void>): Promise<void>;
18
+ priority: number;
19
+ }
@@ -0,0 +1,90 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { Middleware, RequestMatcher, HTTP_MIDDLEWARE_PRIORITY } from '@celljs/web/lib/node';
11
+ import { serveStatic, mime } from './serve-static.js';
12
+ import { EmbeddedAssets } from './embedded-assets.js';
13
+ import { Value, Component, Autowired } from '@celljs/core';
14
+ import { HttpMethod, MediaType, HttpHeaders } from '@celljs/http';
15
+ import { SERVER_PATH } from '@celljs/web';
16
+ import { existsSync } from 'fs';
17
+ let ServeStaticMiddleware = class ServeStaticMiddleware {
18
+ constructor() {
19
+ this.priority = HTTP_MIDDLEWARE_PRIORITY + 500;
20
+ }
21
+ async handle(ctx, next) {
22
+ var _a;
23
+ this.config.options.baseHref = this.path;
24
+ const method = ctx.request.method;
25
+ (_a = this.hasFrontend) !== null && _a !== void 0 ? _a : (this.hasFrontend = !!EmbeddedAssets.get() || existsSync(this.config.root));
26
+ if (!this.hasFrontend || !(method === HttpMethod.GET || method === HttpMethod.HEAD) || ctx.request.query['static'] === 'skip') {
27
+ await next();
28
+ return;
29
+ }
30
+ if (this.config.apiPath && await this.requestMatcher.match(this.config.apiPath)) {
31
+ await next();
32
+ return;
33
+ }
34
+ if (this.config.path && !await this.requestMatcher.match(this.config.path)) {
35
+ await next();
36
+ return;
37
+ }
38
+ const executor = (resolve, reject) => {
39
+ const opts = this.config.options;
40
+ if (!opts.setHeaders) {
41
+ opts.setHeaders = (res, path) => {
42
+ if (opts.headers) {
43
+ Object.keys(opts.headers).forEach(key => res.setHeader(key, opts.headers[key]));
44
+ }
45
+ if (mime.lookup(path) === MediaType.TEXT_HTML) {
46
+ // Custom Cache-Control for HTML files
47
+ res.setHeader(HttpHeaders.CACHE_CONTROL, `public, max-age=${opts.htmlMaxAge / 1000}`);
48
+ }
49
+ };
50
+ }
51
+ const embedded = EmbeddedAssets.get();
52
+ const serve = embedded ? EmbeddedAssets.serve(embedded, this.config.options) : serveStatic(this.config.root, this.config.options);
53
+ serve(ctx.request, ctx.response, ((err) => {
54
+ const url = ctx.request.url;
55
+ if (url !== '/index.html') {
56
+ if (!this.config.spa) {
57
+ next().then(resolve).catch(reject);
58
+ return;
59
+ }
60
+ ctx.request.url = '/index.html';
61
+ executor(resolve, reject);
62
+ }
63
+ else if (err) {
64
+ reject(err);
65
+ }
66
+ else {
67
+ next().then(resolve).catch(reject);
68
+ }
69
+ }));
70
+ };
71
+ return new Promise(executor);
72
+ }
73
+ };
74
+ __decorate([
75
+ Value('cell["serve-static"]'),
76
+ __metadata("design:type", Object)
77
+ ], ServeStaticMiddleware.prototype, "config", void 0);
78
+ __decorate([
79
+ Value(SERVER_PATH),
80
+ __metadata("design:type", String)
81
+ ], ServeStaticMiddleware.prototype, "path", void 0);
82
+ __decorate([
83
+ Autowired(RequestMatcher),
84
+ __metadata("design:type", Object)
85
+ ], ServeStaticMiddleware.prototype, "requestMatcher", void 0);
86
+ ServeStaticMiddleware = __decorate([
87
+ Component(Middleware)
88
+ ], ServeStaticMiddleware);
89
+ export { ServeStaticMiddleware };
90
+ //# sourceMappingURL=serve-static-middleware.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serve-static-middleware.js","sourceRoot":"","sources":["../../src/node/serve-static-middleware.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,UAAU,EAAW,cAAc,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AACrG,OAAO,EAAC,WAAW,EAAE,IAAI,EAAC,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAClE,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAEzB,IAAM,qBAAqB,GAA3B,MAAM,qBAAqB;IAA3B;QAwEH,aAAQ,GAAG,wBAAwB,GAAG,GAAG,CAAC;IAE9C,CAAC;IAzDG,KAAK,CAAC,MAAM,CAAC,GAAY,EAAE,IAAyB;;QAChD,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC;QACzC,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC;QAClC,MAAA,IAAI,CAAC,WAAW,oCAAhB,IAAI,CAAC,WAAW,GAAK,CAAC,CAAC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AAC;QACf,CAAC,CAAC;QAEF,OAAO,IAAI,OAAO,CAAC,QAAQ,CAAC,CAAC;IACjC,CAAC;CAGJ,CAAA;AAvEa;IADT,KAAK,CAAC,sBAAsB,CAAC;;qDAC+D;AAGnF;IADT,KAAK,CAAC,WAAW,CAAC;;mDACI;AAGJ;IADlB,SAAS,CAAC,cAAc,CAAC;;6DACwB;AATzC,qBAAqB;IADjC,SAAS,CAAC,UAAU,CAAC;GACT,qBAAqB,CA0EjC"}
@@ -0,0 +1,3 @@
1
+ import type { ServeStaticOption } from './type.js';
2
+ export declare const serveStatic: (root: string, opts: ServeStaticOption) => (req: any, res: any, next: Function) => any;
3
+ export declare const mime: typeof import("mime");
@@ -0,0 +1,89 @@
1
+ import send from 'send';
2
+ import { resolve } from 'path';
3
+ /* eslint-disable @typescript-eslint/ban-ts-comment */
4
+ export const serveStatic = (root, opts) => {
5
+ const { fallthrough = true, baseHref, setHeaders, redirect } = opts;
6
+ const onDirectory = redirect ?
7
+ createRedirectDirectoryListener :
8
+ createNotFoundDirectoryListener;
9
+ opts.root = resolve(root);
10
+ return (req, res, next) => {
11
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
12
+ if (fallthrough) {
13
+ return next();
14
+ }
15
+ // method not allowed
16
+ res.statusCode = 405;
17
+ res.setHeader('Allow', 'GET, HEAD');
18
+ res.setHeader('Content-Length', '0');
19
+ res.end();
20
+ next();
21
+ return;
22
+ }
23
+ let forwardError = !fallthrough;
24
+ const url = new URL(`${req.url.replace(baseHref, '/')}`, `http://${req.headers.host}`);
25
+ const stream = send(req, url.pathname, opts);
26
+ stream.on('directory', onDirectory(url));
27
+ if (setHeaders) {
28
+ stream.on('headers', setHeaders);
29
+ }
30
+ if (fallthrough) {
31
+ stream.on('file', function onFile() {
32
+ // once file is determined, always forward error
33
+ forwardError = true;
34
+ });
35
+ }
36
+ // forward errors
37
+ stream.on('error', function error(err) {
38
+ if (forwardError || !(err.statusCode < 500)) {
39
+ next(err);
40
+ return;
41
+ }
42
+ next();
43
+ });
44
+ // pipe
45
+ stream.pipe(res);
46
+ };
47
+ function createNotFoundDirectoryListener() {
48
+ return function notFound() {
49
+ // @ts-ignore
50
+ this.error(404);
51
+ };
52
+ }
53
+ function createRedirectDirectoryListener(url) {
54
+ return (res) => {
55
+ // @ts-ignore
56
+ if (this.hasTrailingSlash()) {
57
+ // @ts-ignore
58
+ this.error(404);
59
+ return;
60
+ }
61
+ // reformat the URL
62
+ const loc = encodeURI(url.href);
63
+ const doc = createHtmlDocument('Redirecting', 'Redirecting to <a href="' + loc + '">' +
64
+ loc + '</a>');
65
+ // send redirect response
66
+ res.statusCode = 301;
67
+ res.setHeader('Content-Type', 'text/html; charset=UTF-8');
68
+ res.setHeader('Content-Length', Buffer.byteLength(doc));
69
+ res.setHeader('Content-Security-Policy', 'default-src \'none\'');
70
+ res.setHeader('X-Content-Type-Options', 'nosniff');
71
+ res.setHeader('Location', loc);
72
+ res.end(doc);
73
+ };
74
+ }
75
+ function createHtmlDocument(title, body) {
76
+ return '<!DOCTYPE html>\n' +
77
+ '<html lang="en">\n' +
78
+ '<head>\n' +
79
+ '<meta charset="utf-8">\n' +
80
+ '<title>' + title + '</title>\n' +
81
+ '</head>\n' +
82
+ '<body>\n' +
83
+ '<pre>' + body + '</pre>\n' +
84
+ '</body>\n' +
85
+ '</html>\n';
86
+ }
87
+ };
88
+ export const mime = send.mime;
89
+ //# sourceMappingURL=serve-static.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serve-static.js","sourceRoot":"","sources":["../../src/node/serve-static.ts"],"names":[],"mappings":"AACA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,sDAAsD;AAEtD,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,IAAY,EAAE,IAAuB,EAAE,EAAE;IAEjE,MAAM,EAAE,WAAW,GAAG,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,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,yBAAyB,EAAE,sBAAsB,CAAC,CAAC;YACjE,GAAG,CAAC,SAAS,CAAC,wBAAwB,EAAE,SAAS,CAAC,CAAC;YACnD,GAAG,CAAC,SAAS,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;YAC/B,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACjB,CAAC,CAAC;IACN,CAAC;IAED,SAAS,kBAAkB,CAAC,KAAa,EAAE,IAAY;QACnD,OAAO,mBAAmB;YACtB,oBAAoB;YACpB,UAAU;YACV,0BAA0B;YAC1B,SAAS,GAAG,KAAK,GAAG,YAAY;YAChC,WAAW;YACX,UAAU;YACV,OAAO,GAAG,IAAI,GAAG,UAAU;YAC3B,WAAW;YACX,WAAW,CAAC;IACpB,CAAC;AAEL,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC"}
@@ -0,0 +1,15 @@
1
+ export interface ServeStaticOption {
2
+ fallthrough?: boolean;
3
+ maxage?: number;
4
+ setHeaders?: (res: any, path: string, stat: any) => void;
5
+ redirect?: boolean;
6
+ extensions?: false | Array<string>;
7
+ dotfiles?: 'allow' | 'deny' | 'ignore';
8
+ acceptRanges?: any;
9
+ cacheControl?: any;
10
+ immutable?: boolean;
11
+ index?: any;
12
+ lastModified?: any;
13
+ baseHref: string;
14
+ root: string;
15
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type.js","sourceRoot":"","sources":["../../src/node/type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,21 @@
1
+ import type { ServeStaticOption } from './type';
2
+ /** A frontend file inside a server bundle built with `cell build --single`. */
3
+ export interface EmbeddedAsset {
4
+ /** Base64 of the content. */
5
+ body: string;
6
+ etag: string;
7
+ }
8
+ /**
9
+ * Frontend files that a `cell build --single` bundle registers before the application starts, by URL
10
+ * path (`/index.html`, `/assets/index-abc.js`). When they are there, they are served from memory
11
+ * instead of `cell.serve-static.root`.
12
+ */
13
+ export declare namespace EmbeddedAssets {
14
+ const KEY: unique symbol;
15
+ function get(): Map<string, EmbeddedAsset> | undefined;
16
+ /** The counterpart of `serveStatic`: same options, same `next()` when a file is not there. */
17
+ function serve(assets: Map<string, EmbeddedAsset>, opts: ServeStaticOption & {
18
+ maxAge?: number;
19
+ }): (req: any, res: any, next: (err?: unknown) => void) => void;
20
+ }
21
+ //# sourceMappingURL=embedded-assets.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"embedded-assets.d.ts","sourceRoot":"","sources":["../../src/node/embedded-assets.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,QAAQ,CAAC;AAEhD,+EAA+E;AAC/E,MAAM,WAAW,aAAa;IAC1B,6BAA6B;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CAChB;AAED;;;;GAIG;AACH,yBAAiB,cAAc,CAAC;IACrB,MAAM,GAAG,eAA4C,CAAC;IAI7D,SAAgB,GAAG,IAAI,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,GAAG,SAAS,CAE5D;IAWD,8FAA8F;IAC9F,SAAgB,KAAK,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,EAAE,IAAI,EAAE,iBAAiB,GAAG;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,SACtF,GAAG,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO,KAAK,IAAI,UAuC5D;CACJ"}
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.EmbeddedAssets = void 0;
7
+ const send_1 = __importDefault(require("send"));
8
+ /**
9
+ * Frontend files that a `cell build --single` bundle registers before the application starts, by URL
10
+ * path (`/index.html`, `/assets/index-abc.js`). When they are there, they are served from memory
11
+ * instead of `cell.serve-static.root`.
12
+ */
13
+ var EmbeddedAssets;
14
+ (function (EmbeddedAssets) {
15
+ EmbeddedAssets.KEY = Symbol.for('@celljs/serve-static/assets');
16
+ const decoded = new Map();
17
+ function get() {
18
+ return globalThis[EmbeddedAssets.KEY];
19
+ }
20
+ EmbeddedAssets.get = get;
21
+ function content(path, asset) {
22
+ let body = decoded.get(path);
23
+ if (!body) {
24
+ body = Buffer.from(asset.body, 'base64');
25
+ decoded.set(path, body);
26
+ }
27
+ return body;
28
+ }
29
+ /** The counterpart of `serveStatic`: same options, same `next()` when a file is not there. */
30
+ function serve(assets, opts) {
31
+ return (req, res, next) => {
32
+ var _a;
33
+ var _b, _c;
34
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
35
+ next();
36
+ return;
37
+ }
38
+ let path;
39
+ try {
40
+ path = decodeURIComponent(new URL(req.url.replace(opts.baseHref, '/'), 'http://localhost').pathname);
41
+ }
42
+ catch (_d) {
43
+ next();
44
+ return;
45
+ }
46
+ if (path.endsWith('/')) {
47
+ path += 'index.html';
48
+ }
49
+ const asset = assets.get(path);
50
+ if (!asset) {
51
+ next();
52
+ return;
53
+ }
54
+ const type = send_1.default.mime.lookup(path);
55
+ const charset = send_1.default.mime.charsets.lookup(type);
56
+ res.setHeader('Content-Type', charset ? `${type}; charset=${charset}` : type);
57
+ res.setHeader('ETag', asset.etag);
58
+ if (opts.cacheControl !== false) {
59
+ const maxAge = Math.floor(Math.min(Math.max(0, Number((_c = (_b = opts.maxAge) !== null && _b !== void 0 ? _b : opts.maxage) !== null && _c !== void 0 ? _c : 0)), 31536000000) / 1000);
60
+ res.setHeader('Cache-Control', `public, max-age=${maxAge}${opts.immutable ? ', immutable' : ''}`);
61
+ }
62
+ (_a = opts.setHeaders) === null || _a === void 0 ? void 0 : _a.call(opts, res, path, undefined);
63
+ if (req.headers['if-none-match'] === asset.etag) {
64
+ res.statusCode = 304;
65
+ res.end();
66
+ return;
67
+ }
68
+ const body = content(path, asset);
69
+ res.statusCode = 200;
70
+ res.setHeader('Content-Length', body.length);
71
+ res.end(req.method === 'HEAD' ? undefined : body);
72
+ };
73
+ }
74
+ EmbeddedAssets.serve = serve;
75
+ })(EmbeddedAssets || (exports.EmbeddedAssets = EmbeddedAssets = {}));
76
+ //# sourceMappingURL=embedded-assets.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"embedded-assets.js","sourceRoot":"","sources":["../../src/node/embedded-assets.ts"],"names":[],"mappings":";;;;;;AAAA,gDAAwB;AAUxB;;;;GAIG;AACH,IAAiB,cAAc,CA4D9B;AA5DD,WAAiB,cAAc;IACd,kBAAG,GAAG,MAAM,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAE7D,MAAM,OAAO,GAAG,IAAI,GAAG,EAAkB,CAAC;IAE1C,SAAgB,GAAG;QACf,OAAQ,UAAqE,CAAC,kBAAG,CAAC,CAAC;IACvF,CAAC;IAFe,eAAA,GAAG,MAElB,CAAA;IAED,SAAS,OAAO,CAAC,IAAY,EAAE,KAAoB;QAC/C,IAAI,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC7B,IAAI,CAAC,IAAI,EAAE,CAAC;YACR,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;YACzC,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,IAAI,CAAC;IAChB,CAAC;IAED,8FAA8F;IAC9F,SAAgB,KAAK,CAAC,MAAkC,EAAE,IAA6C;QACnG,OAAO,CAAC,GAAQ,EAAE,GAAQ,EAAE,IAA6B,EAAE,EAAE;;;YACzD,IAAI,GAAG,CAAC,MAAM,KAAK,KAAK,IAAI,GAAG,CAAC,MA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,EAAE,WAAW,CAAC,GAAG,IAAI,CAAC,CAAC;gBAC9G,GAAG,CAAC,SAAS,CAAC,eAAe,EAAE,mBAAmB,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YACtG,CAAC;YACD,MAAA,IAAI,CAAC,UAAU,+CAAf,IAAI,EAAc,GAAG,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;YACxC,IAAI,GAAG,CAAC,OAAO,CAAC,eAAe,CAAC,KAAK,KAAK,CAAC,IAAI,EAAE,CAAC;gBAC9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC;gBACrB,GAAG,CAAC,GAAG,EAAE,CAAC;gBACV,OAAO;YACX,CAAC;YACD,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;YAClC,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC;YACrB,GAAG,CAAC,SAAS,CAAC,gBAAgB,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;YAC7C,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QACtD,CAAC,CAAC;IACN,CAAC;IAxCe,eAAA,KAAK,QAwCpB,CAAA;AACL,CAAC,EA5DgB,cAAc,aAAd,cAAc,GAAd,cAAc,QA4D9B"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=embedded-assets.spec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"embedded-assets.spec.d.ts","sourceRoot":"","sources":["../../src/node/embedded-assets.spec.ts"],"names":[],"mappings":""}
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const bun_test_1 = require("bun:test");
4
+ const chai_1 = require("chai");
5
+ const embedded_assets_1 = require("./embedded-assets");
6
+ function request(url, opts = {}, method = 'GET', headers = {}) {
7
+ const assets = new Map([
8
+ ['/index.html', { body: Buffer.from('<html></html>').toString('base64'), etag: '"a"' }],
9
+ ['/assets/app.js', { body: Buffer.from('run()').toString('base64'), etag: '"b"' }],
10
+ ]);
11
+ const sent = { headers: {}, next: false };
12
+ const res = {
13
+ statusCode: 0,
14
+ setHeader: (name, value) => {
15
+ sent.headers[name.toLowerCase()] = value;
16
+ },
17
+ end: (body) => {
18
+ sent.status = res.statusCode;
19
+ sent.body = body;
20
+ },
21
+ };
22
+ embedded_assets_1.EmbeddedAssets.serve(assets, { baseHref: '/', root: '', ...opts })({ url, method, headers }, res, () => {
23
+ sent.next = true;
24
+ });
25
+ return sent;
26
+ }
27
+ (0, bun_test_1.describe)('EmbeddedAssets', () => {
28
+ (0, bun_test_1.it)('serves files from memory with type, length, ETag and cache headers', () => {
29
+ var _a, _b;
30
+ const js = request('/assets/app.js', { maxAge: 31536000000, immutable: true });
31
+ (0, chai_1.expect)(js.status).to.equal(200);
32
+ (0, chai_1.expect)((_a = js.body) === null || _a === void 0 ? void 0 : _a.toString()).to.equal('run()');
33
+ (0, chai_1.expect)(js.headers).to.include({
34
+ 'content-type': 'application/javascript; charset=UTF-8',
35
+ 'content-length': 5,
36
+ etag: '"b"',
37
+ 'cache-control': 'public, max-age=31536000, immutable',
38
+ });
39
+ (0, chai_1.expect)((_b = request('/').body) === null || _b === void 0 ? void 0 : _b.toString()).to.equal('<html></html>');
40
+ (0, chai_1.expect)(request('/index.html').headers['content-type']).to.equal('text/html; charset=UTF-8');
41
+ });
42
+ (0, bun_test_1.it)('answers HEAD without a body and If-None-Match with 304', () => {
43
+ const head = request('/assets/app.js', {}, 'HEAD');
44
+ (0, chai_1.expect)(head.status).to.equal(200);
45
+ (0, chai_1.expect)(head.body).to.equal(undefined);
46
+ (0, chai_1.expect)(request('/assets/app.js', {}, 'GET', { 'if-none-match': '"b"' }).status).to.equal(304);
47
+ });
48
+ (0, bun_test_1.it)('passes on what it does not have, other methods and the base href', () => {
49
+ var _a;
50
+ (0, chai_1.expect)(request('/missing.js').next).to.equal(true);
51
+ (0, chai_1.expect)(request('/assets/app.js', {}, 'POST').next).to.equal(true);
52
+ (0, chai_1.expect)((_a = request('/app/assets/app.js', { baseHref: '/app/' }).body) === null || _a === void 0 ? void 0 : _a.toString()).to.equal('run()');
53
+ (0, chai_1.expect)(request('/%E0%A4%A').next).to.equal(true);
54
+ });
55
+ (0, bun_test_1.it)('is found under a global symbol shared with the build', () => {
56
+ (0, chai_1.expect)(embedded_assets_1.EmbeddedAssets.KEY).to.equal(Symbol.for('@celljs/serve-static/assets'));
57
+ (0, chai_1.expect)(embedded_assets_1.EmbeddedAssets.get()).to.equal(undefined);
58
+ });
59
+ });
60
+ //# sourceMappingURL=embedded-assets.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"embedded-assets.spec.js","sourceRoot":"","sources":["../../src/node/embedded-assets.spec.ts"],"names":[],"mappings":";;AAAA,uCAAwC;AACxC,+BAA8B;AAC9B,uDAAmD;AASnD,SAAS,OAAO,CAAC,GAAW,EAAE,IAAI,GAA4B,EAAE,EAAE,MAAM,GAAG,KAAK,EAAE,OAAO,GAA2B,EAAE;IAClH,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC;QACnB,CAAC,aAAa,EAAE,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;QACvF,CAAC,gBAAgB,EAAE,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;KACrF,CAAC,CAAC;IACH,MAAM,IAAI,GAAS,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;IAChD,MAAM,GAAG,GAAG;QACR,UAAU,EAA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E,OAAO,EAAE,CAAC,CAAC,IAAI,0CAAE,QAAQ,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAChG,IAAA,aAAM,EAAC,OAAO,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACrD,CAAC,CAAC,CAAC;IAEH,IAAA,aAAE,EAAC,sDAAsD,EAAE,GAAG,EAAE;QAC5D,IAAA,aAAM,EAAC,gCAAc,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC,CAAC;QAC/E,IAAA,aAAM,EAAC,gCAAc,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;IACrD,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC"}
@@ -1,2 +1,3 @@
1
1
  export * from './serve-static-middleware';
2
+ export * from './embedded-assets';
2
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":"AACA,cAAc,2BAA2B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":"AACA,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC"}
package/lib/node/index.js CHANGED
@@ -15,4 +15,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./serve-static-middleware"), exports);
18
+ __exportStar(require("./embedded-assets"), exports);
18
19
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AACA,4DAA0C"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AACA,4DAA0C;AAC1C,oDAAkC"}
@@ -9,6 +9,11 @@ export declare class ServeStaticMiddleware implements Middleware {
9
9
  };
10
10
  protected path: string;
11
11
  protected readonly requestMatcher: RequestMatcher;
12
+ /**
13
+ * Whether there is a frontend to serve: embedded in the bundle (`--single`) or on disk. On
14
+ * Cloudflare Workers the platform serves the frontend and the worker has no copy.
15
+ */
16
+ protected hasFrontend?: boolean;
12
17
  handle(ctx: Context, next: () => Promise<void>): Promise<void>;
13
18
  priority: number;
14
19
  }
@@ -1 +1 @@
1
- {"version":3,"file":"serve-static-middleware.d.ts","sourceRoot":"","sources":["../../src/node/serve-static-middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,cAAc,EAA4B,MAAM,sBAAsB,CAAC;AAMrG,qBACa,qBAAsB,YAAW,UAAU;IAGpD,SAAS,CAAC,MAAM,EAAE;QAAE,GAAG,EAAE,OAAO,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,GAAG,CAAA;KAAC,CAAC;IAG7F,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;IAGvB,SAAS,CAAC,QAAQ,CAAC,cAAc,EAAE,cAAc,CAAC;IAE5C,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAmDnE;IACD,QAAQ,SAAkC;CAE7C"}
1
+ {"version":3,"file":"serve-static-middleware.d.ts","sourceRoot":"","sources":["../../src/node/serve-static-middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,cAAc,EAA4B,MAAM,sBAAsB,CAAC;AAQrG,qBACa,qBAAsB,YAAW,UAAU;IAGpD,SAAS,CAAC,MAAM,EAAE;QAAE,GAAG,EAAE,OAAO,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,GAAG,CAAA;KAAC,CAAC;IAG7F,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;IAGvB,SAAS,CAAC,QAAQ,CAAC,cAAc,EAAE,cAAc,CAAC;IAElD;;;OAGG;IACH,SAAS,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC;IAE1B,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAsDnE;IACD,QAAQ,SAAkC;CAE7C"}
@@ -12,17 +12,21 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.ServeStaticMiddleware = void 0;
13
13
  const node_1 = require("@celljs/web/lib/node");
14
14
  const serve_static_1 = require("./serve-static");
15
+ const embedded_assets_1 = require("./embedded-assets");
15
16
  const core_1 = require("@celljs/core");
16
17
  const http_1 = require("@celljs/http");
17
18
  const web_1 = require("@celljs/web");
19
+ const fs_1 = require("fs");
18
20
  let ServeStaticMiddleware = class ServeStaticMiddleware {
19
21
  constructor() {
20
22
  this.priority = node_1.HTTP_MIDDLEWARE_PRIORITY + 500;
21
23
  }
22
24
  async handle(ctx, next) {
25
+ var _a;
23
26
  this.config.options.baseHref = this.path;
24
27
  const method = ctx.request.method;
25
- if (!(method === http_1.HttpMethod.GET || method === http_1.HttpMethod.HEAD) || ctx.request.query['static'] === 'skip') {
28
+ (_a = this.hasFrontend) !== null && _a !== void 0 ? _a : (this.hasFrontend = !!embedded_assets_1.EmbeddedAssets.get() || (0, fs_1.existsSync)(this.config.root));
29
+ if (!this.hasFrontend || !(method === http_1.HttpMethod.GET || method === http_1.HttpMethod.HEAD) || ctx.request.query['static'] === 'skip') {
26
30
  await next();
27
31
  return;
28
32
  }
@@ -47,7 +51,9 @@ let ServeStaticMiddleware = class ServeStaticMiddleware {
47
51
  }
48
52
  };
49
53
  }
50
- (0, serve_static_1.serveStatic)(this.config.root, this.config.options)(ctx.request, ctx.response, ((err) => {
54
+ const embedded = embedded_assets_1.EmbeddedAssets.get();
55
+ const serve = embedded ? embedded_assets_1.EmbeddedAssets.serve(embedded, this.config.options) : (0, serve_static_1.serveStatic)(this.config.root, this.config.options);
56
+ serve(ctx.request, ctx.response, ((err) => {
51
57
  const url = ctx.request.url;
52
58
  if (url !== '/index.html') {
53
59
  if (!this.config.spa) {
@@ -1 +1 @@
1
- {"version":3,"file":"serve-static-middleware.js","sourceRoot":"","sources":["../../src/node/serve-static-middleware.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,+CAAqG;AACrG,iDAAiD;AACjD,uCAA2D;AAC3D,uCAAkE;AAClE,qCAA0C;AAGnC,IAAM,qBAAqB,GAA3B,MAAM,qBAAqB;IAA3B;QA+DH,aAAQ,GAAG,+BAAwB,GAAG,GAAG,CAAC;IAE9C,CAAC;IAtDG,KAAK,CAAC,MAAM,CAAC,GAAY,EAAE,IAAyB;QAChD,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC;QACzC,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC;QAElC,IAAI,CAAC,CAAC,MAAM,KAAK,iBAAU,CAAC,GAAG,IAAI,MAAM,KAAK,iBAAU,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,MAAM,EAAE,CAAC;YACvG,MAAM,IAAI,EAAE,CAAC;YACb,OAAO;QACX,CAAC;QAED,IAAI,IAAI,CAAC,MAAM,CAAC,OAAO,IAAI,MAAM,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC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C,OAAO,EAAE,MAAM,CAAC,CAAC;gBAC9B,CAAC;qBAAM,IAAI,GAAG,EAAE,CAAC;oBACb,MAAM,CAAC,GAAG,CAAC,CAAC;gBAChB,CAAC;qBAAM,CAAC;oBACJ,IAAI,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;gBACvC,CAAC;YACL,CAAC,CAAQ,CAAC,CAAC;QACf,CAAC,CAAC;QAEF,OAAO,IAAI,OAAO,CAAC,QAAQ,CAAC,CAAC;IACjC,CAAC;CAGJ,CAAA;;AAvEa;IADT,IAAA,YAAK,EAAC,sBAAsB,CAAC;;qDAC+D;AAGnF;IADT,IAAA,YAAK,EAAC,iBAAW,CAAC;;mDACI;AAGJ;IADlB,IAAA,gBAAS,EAAC,qBAAc,CAAC;;6DACwB;gCATzC,qBAAqB;IADjC,IAAA,gBAAS,EAAC,iBAAU,CAAC;GACT,qBAAqB,CA0EjC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/serve-static",
3
- "version": "3.8.0",
3
+ "version": "4.0.0",
4
4
  "description": "",
5
5
  "keywords": [
6
6
  "cell-component"
@@ -18,28 +18,54 @@
18
18
  "typings": "lib/node/index.d.ts",
19
19
  "files": [
20
20
  "lib",
21
+ "esm",
21
22
  "src",
22
- "cell.yml",
23
- "cell-remote.yml"
23
+ "cell.yml"
24
24
  ],
25
25
  "scripts": {
26
- "build": "tsc -b",
27
- "clean": "rm -rf lib *.tsbuildinfo",
26
+ "build": "tsc -b && bun ../../scripts/build-esm.ts",
27
+ "clean": "rm -rf lib esm *.tsbuildinfo",
28
28
  "test": "bun test --preload reflect-metadata ./lib",
29
29
  "watch": "tsc -b -w --preserveWatchOutput"
30
30
  },
31
31
  "dependencies": {
32
- "@celljs/core": "3.8.0",
33
- "@celljs/http": "3.8.0",
34
- "@celljs/web": "3.8.0",
32
+ "@celljs/core": "4.0.0",
33
+ "@celljs/http": "4.0.0",
34
+ "@celljs/web": "4.0.0",
35
35
  "send": "^0.17.1",
36
36
  "tslib": "^2.8.0"
37
37
  },
38
38
  "devDependencies": {
39
- "@celljs/cli-service": "3.8.0",
40
39
  "@types/send": "^0.17.0"
41
40
  },
42
41
  "publishConfig": {
43
42
  "access": "public"
43
+ },
44
+ "exports": {
45
+ ".": {
46
+ "import": "./esm/node/index.js",
47
+ "default": "./lib/node/index.js"
48
+ },
49
+ "./package.json": "./package.json",
50
+ "./lib/node": {
51
+ "import": "./esm/node/index.js",
52
+ "default": "./lib/node/index.js"
53
+ },
54
+ "./lib/*.js": {
55
+ "import": "./esm/*.js",
56
+ "default": "./lib/*.js"
57
+ },
58
+ "./lib/*": {
59
+ "import": "./esm/*.js",
60
+ "default": "./lib/*.js"
61
+ },
62
+ "./*": "./*"
63
+ },
64
+ "cell": {
65
+ "modules": {
66
+ "backend": [
67
+ "lib/node/module"
68
+ ]
69
+ }
44
70
  }
45
71
  }
@@ -0,0 +1,67 @@
1
+ import { describe, it } from 'bun:test';
2
+ import { expect } from 'chai';
3
+ import { EmbeddedAssets } from './embedded-assets';
4
+
5
+ interface Sent {
6
+ status?: number;
7
+ headers: Record<string, unknown>;
8
+ body?: Buffer;
9
+ next: boolean;
10
+ }
11
+
12
+ function request(url: string, opts: Record<string, unknown> = {}, method = 'GET', headers: Record<string, string> = {}): Sent {
13
+ const assets = new Map([
14
+ ['/index.html', { body: Buffer.from('<html></html>').toString('base64'), etag: '"a"' }],
15
+ ['/assets/app.js', { body: Buffer.from('run()').toString('base64'), etag: '"b"' }],
16
+ ]);
17
+ const sent: Sent = { headers: {}, next: false };
18
+ const res = {
19
+ statusCode: 0,
20
+ setHeader: (name: string, value: unknown) => {
21
+ sent.headers[name.toLowerCase()] = value;
22
+ },
23
+ end: (body?: Buffer) => {
24
+ sent.status = res.statusCode;
25
+ sent.body = body;
26
+ },
27
+ };
28
+ EmbeddedAssets.serve(assets, { baseHref: '/', root: '', ...opts })({ url, method, headers }, res, () => {
29
+ sent.next = true;
30
+ });
31
+ return sent;
32
+ }
33
+
34
+ describe('EmbeddedAssets', () => {
35
+ it('serves files from memory with type, length, ETag and cache headers', () => {
36
+ const js = request('/assets/app.js', { maxAge: 31536000000, immutable: true });
37
+ expect(js.status).to.equal(200);
38
+ expect(js.body?.toString()).to.equal('run()');
39
+ expect(js.headers).to.include({
40
+ 'content-type': 'application/javascript; charset=UTF-8',
41
+ 'content-length': 5,
42
+ etag: '"b"',
43
+ 'cache-control': 'public, max-age=31536000, immutable',
44
+ });
45
+ expect(request('/').body?.toString()).to.equal('<html></html>');
46
+ expect(request('/index.html').headers['content-type']).to.equal('text/html; charset=UTF-8');
47
+ });
48
+
49
+ it('answers HEAD without a body and If-None-Match with 304', () => {
50
+ const head = request('/assets/app.js', {}, 'HEAD');
51
+ expect(head.status).to.equal(200);
52
+ expect(head.body).to.equal(undefined);
53
+ expect(request('/assets/app.js', {}, 'GET', { 'if-none-match': '"b"' }).status).to.equal(304);
54
+ });
55
+
56
+ it('passes on what it does not have, other methods and the base href', () => {
57
+ expect(request('/missing.js').next).to.equal(true);
58
+ expect(request('/assets/app.js', {}, 'POST').next).to.equal(true);
59
+ expect(request('/app/assets/app.js', { baseHref: '/app/' }).body?.toString()).to.equal('run()');
60
+ expect(request('/%E0%A4%A').next).to.equal(true);
61
+ });
62
+
63
+ it('is found under a global symbol shared with the build', () => {
64
+ expect(EmbeddedAssets.KEY).to.equal(Symbol.for('@celljs/serve-static/assets'));
65
+ expect(EmbeddedAssets.get()).to.equal(undefined);
66
+ });
67
+ });
@@ -0,0 +1,76 @@
1
+ import send from 'send';
2
+ import type { ServeStaticOption } from './type';
3
+
4
+ /** A frontend file inside a server bundle built with `cell build --single`. */
5
+ export interface EmbeddedAsset {
6
+ /** Base64 of the content. */
7
+ body: string;
8
+ etag: string;
9
+ }
10
+
11
+ /**
12
+ * Frontend files that a `cell build --single` bundle registers before the application starts, by URL
13
+ * path (`/index.html`, `/assets/index-abc.js`). When they are there, they are served from memory
14
+ * instead of `cell.serve-static.root`.
15
+ */
16
+ export namespace EmbeddedAssets {
17
+ export const KEY = Symbol.for('@celljs/serve-static/assets');
18
+
19
+ const decoded = new Map<string, Buffer>();
20
+
21
+ export function get(): Map<string, EmbeddedAsset> | undefined {
22
+ return (globalThis as Record<symbol, Map<string, EmbeddedAsset> | undefined>)[KEY];
23
+ }
24
+
25
+ function content(path: string, asset: EmbeddedAsset): Buffer {
26
+ let body = decoded.get(path);
27
+ if (!body) {
28
+ body = Buffer.from(asset.body, 'base64');
29
+ decoded.set(path, body);
30
+ }
31
+ return body;
32
+ }
33
+
34
+ /** The counterpart of `serveStatic`: same options, same `next()` when a file is not there. */
35
+ export function serve(assets: Map<string, EmbeddedAsset>, opts: ServeStaticOption & { maxAge?: number }) {
36
+ return (req: any, res: any, next: (err?: unknown) => void) => {
37
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
38
+ next();
39
+ return;
40
+ }
41
+ let path: string;
42
+ try {
43
+ path = decodeURIComponent(new URL(req.url.replace(opts.baseHref, '/'), 'http://localhost').pathname);
44
+ } catch {
45
+ next();
46
+ return;
47
+ }
48
+ if (path.endsWith('/')) {
49
+ path += 'index.html';
50
+ }
51
+ const asset = assets.get(path);
52
+ if (!asset) {
53
+ next();
54
+ return;
55
+ }
56
+ const type = (send.mime as any).lookup(path) as string;
57
+ const charset = (send.mime as any).charsets.lookup(type) as string | undefined;
58
+ res.setHeader('Content-Type', charset ? `${type}; charset=${charset}` : type);
59
+ res.setHeader('ETag', asset.etag);
60
+ if (opts.cacheControl !== false) {
61
+ const maxAge = Math.floor(Math.min(Math.max(0, Number(opts.maxAge ?? opts.maxage ?? 0)), 31536000000) / 1000);
62
+ res.setHeader('Cache-Control', `public, max-age=${maxAge}${opts.immutable ? ', immutable' : ''}`);
63
+ }
64
+ opts.setHeaders?.(res, path, undefined);
65
+ if (req.headers['if-none-match'] === asset.etag) {
66
+ res.statusCode = 304;
67
+ res.end();
68
+ return;
69
+ }
70
+ const body = content(path, asset);
71
+ res.statusCode = 200;
72
+ res.setHeader('Content-Length', body.length);
73
+ res.end(req.method === 'HEAD' ? undefined : body);
74
+ };
75
+ }
76
+ }
package/src/node/index.ts CHANGED
@@ -1,2 +1,3 @@
1
1
 
2
2
  export * from './serve-static-middleware';
3
+ export * from './embedded-assets';
@@ -1,9 +1,11 @@
1
1
  import { Middleware, Context, RequestMatcher, HTTP_MIDDLEWARE_PRIORITY } from '@celljs/web/lib/node';
2
2
  import {serveStatic, mime} from './serve-static';
3
+ import { EmbeddedAssets } from './embedded-assets';
3
4
  import { Value, Component, Autowired } from '@celljs/core';
4
5
  import { HttpMethod, MediaType, HttpHeaders } from '@celljs/http';
5
6
  import { SERVER_PATH } from '@celljs/web';
6
7
  import { OutgoingMessage } from 'http';
8
+ import { existsSync } from 'fs';
7
9
  @Component(Middleware)
8
10
  export class ServeStaticMiddleware implements Middleware {
9
11
 
@@ -16,11 +18,18 @@ export class ServeStaticMiddleware implements Middleware {
16
18
  @Autowired(RequestMatcher)
17
19
  protected readonly requestMatcher: RequestMatcher;
18
20
 
21
+ /**
22
+ * Whether there is a frontend to serve: embedded in the bundle (`--single`) or on disk. On
23
+ * Cloudflare Workers the platform serves the frontend and the worker has no copy.
24
+ */
25
+ protected hasFrontend?: boolean;
26
+
19
27
  async handle(ctx: Context, next: () => Promise<void>): Promise<void> {
20
28
  this.config.options.baseHref = this.path;
21
29
  const method = ctx.request.method;
30
+ this.hasFrontend ??= !!EmbeddedAssets.get() || existsSync(this.config.root);
22
31
 
23
- if (!(method === HttpMethod.GET || method === HttpMethod.HEAD) || ctx.request.query['static'] === 'skip') {
32
+ if (!this.hasFrontend || !(method === HttpMethod.GET || method === HttpMethod.HEAD) || ctx.request.query['static'] === 'skip') {
24
33
  await next();
25
34
  return;
26
35
  }
@@ -49,7 +58,9 @@ export class ServeStaticMiddleware implements Middleware {
49
58
  };
50
59
  }
51
60
 
52
- serveStatic(this.config.root, this.config.options)(ctx.request as any, ctx.response as any, ((err: any) => {
61
+ const embedded = EmbeddedAssets.get();
62
+ const serve = embedded ? EmbeddedAssets.serve(embedded, this.config.options) : serveStatic(this.config.root, this.config.options);
63
+ serve(ctx.request as any, ctx.response as any, ((err: any) => {
53
64
  const url = ctx.request.url;
54
65
  if (url !== '/index.html') {
55
66
  if (!this.config.spa) {
@@ -70,4 +81,4 @@ export class ServeStaticMiddleware implements Middleware {
70
81
  }
71
82
  priority = HTTP_MIDDLEWARE_PRIORITY + 500;
72
83
 
73
- }
84
+ }
package/cell-remote.yml DELETED
@@ -1,3 +0,0 @@
1
- cell:
2
- serve-static:
3
- root: frontend
@@ -1,4 +0,0 @@
1
- import { WebpackContext } from '@celljs/cli-service';
2
- export default _default;
3
- declare function _default(context: WebpackContext): Promise<void>;
4
- //# sourceMappingURL=webpack.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"webpack.d.ts","sourceRoot":"","sources":["../../src/hooks/webpack.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAwB,MAAM,qBAAqB,CAAC;;0BAErD,OAAO,EAAE,cAAc"}
@@ -1,17 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const cli_service_1 = require("@celljs/cli-service");
4
- exports.default = async (context) => {
5
- const { dev, configurations } = context;
6
- const config = cli_service_1.ConfigurationContext.getFrontendConfiguration(configurations);
7
- if (dev && config) {
8
- config
9
- .devServer
10
- .merge({
11
- devMiddleware: {
12
- writeToDisk: true
13
- }
14
- });
15
- }
16
- };
17
- //# sourceMappingURL=webpack.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"webpack.js","sourceRoot":"","sources":["../../src/hooks/webpack.ts"],"names":[],"mappings":";;AAAA,qDAA2E;kBAE5D,KAAK,EAAE,OAAuB,EAAE,EAAE;IAC7C,MAAM,EAAE,GAAG,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC;IACxC,MAAM,MAAM,GAAG,kCAAoB,CAAC,wBAAwB,CAAC,cAAc,CAAC,CAAC;IAC7E,IAAI,GAAG,IAAI,MAAM,EAAE,CAAC;QAChB,MAAM;aACD,SAAS;aACT,KAAK,CAAC;YACH,aAAa,EAAE;gBACX,WAAW,EAAE,IAAI;aACpB;SACJ,CAAC,CAAC;IACX,CAAC;AACL,CAAC"}
@@ -1,15 +0,0 @@
1
- import { WebpackContext, ConfigurationContext } from '@celljs/cli-service';
2
-
3
- export default async (context: WebpackContext) => {
4
- const { dev, configurations } = context;
5
- const config = ConfigurationContext.getFrontendConfiguration(configurations);
6
- if (dev && config) {
7
- config
8
- .devServer
9
- .merge({
10
- devMiddleware: {
11
- writeToDisk: true
12
- }
13
- });
14
- }
15
- };