@backstage/plugin-app-backend 0.3.20 → 0.3.23-next.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.
- package/CHANGELOG.md +76 -0
- package/dist/index.cjs.js +137 -4
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +12 -0
- package/migrations/20211229105307_init.js +48 -0
- package/package.json +14 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,81 @@
|
|
|
1
1
|
# @backstage/plugin-app-backend
|
|
2
2
|
|
|
3
|
+
## 0.3.23-next.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies
|
|
8
|
+
- @backstage/backend-common@0.10.6-next.0
|
|
9
|
+
|
|
10
|
+
## 0.3.22
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- f685e1398f: Loading of app configurations now reference the `@deprecated` construct from
|
|
15
|
+
JSDoc to determine if a property in-use has been deprecated. Users are notified
|
|
16
|
+
of deprecated keys in the format:
|
|
17
|
+
|
|
18
|
+
```txt
|
|
19
|
+
The configuration key 'catalog.processors.githubOrg' of app-config.yaml is deprecated and may be removed soon. Configure a GitHub integration instead.
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
When the `withDeprecatedKeys` option is set to `true` in the `process` method
|
|
23
|
+
of `loadConfigSchema`, the user will be notified that deprecated keys have been
|
|
24
|
+
identified in their app configuration.
|
|
25
|
+
|
|
26
|
+
The `backend-common` and `plugin-app-backend` packages have been updated to set
|
|
27
|
+
`withDeprecatedKeys` to true so that users are notified of deprecated settings
|
|
28
|
+
by default.
|
|
29
|
+
|
|
30
|
+
- eb00e8af14: Updated the cache control headers for static assets to instruct clients to cache them for 14 days.
|
|
31
|
+
- eb00e8af14: Added a new asset cache that stores static assets from previous deployments in the database. This fixes an issue where users have old browser tabs open and try to lazy-load static assets that no longer exist in the latest version.
|
|
32
|
+
|
|
33
|
+
The asset cache is enabled by passing the `database` option to `createRouter`.
|
|
34
|
+
|
|
35
|
+
- Updated dependencies
|
|
36
|
+
- @backstage/backend-common@0.10.4
|
|
37
|
+
- @backstage/config@0.1.13
|
|
38
|
+
- @backstage/config-loader@0.9.3
|
|
39
|
+
|
|
40
|
+
## 0.3.22-next.0
|
|
41
|
+
|
|
42
|
+
### Patch Changes
|
|
43
|
+
|
|
44
|
+
- f685e1398f: Loading of app configurations now reference the `@deprecated` construct from
|
|
45
|
+
JSDoc to determine if a property in-use has been deprecated. Users are notified
|
|
46
|
+
of deprecated keys in the format:
|
|
47
|
+
|
|
48
|
+
```txt
|
|
49
|
+
The configuration key 'catalog.processors.githubOrg' of app-config.yaml is deprecated and may be removed soon. Configure a GitHub integration instead.
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
When the `withDeprecatedKeys` option is set to `true` in the `process` method
|
|
53
|
+
of `loadConfigSchema`, the user will be notified that deprecated keys have been
|
|
54
|
+
identified in their app configuration.
|
|
55
|
+
|
|
56
|
+
The `backend-common` and `plugin-app-backend` packages have been updated to set
|
|
57
|
+
`withDeprecatedKeys` to true so that users are notified of deprecated settings
|
|
58
|
+
by default.
|
|
59
|
+
|
|
60
|
+
- eb00e8af14: Updated the cache control headers for static assets to instruct clients to cache them for 14 days.
|
|
61
|
+
- eb00e8af14: Added a new asset cache that stores static assets from previous deployments in the database. This fixes an issue where users have old browser tabs open and try to lazy-load static assets that no longer exist in the latest version.
|
|
62
|
+
|
|
63
|
+
The asset cache is enabled by passing the `database` option to `createRouter`.
|
|
64
|
+
|
|
65
|
+
- Updated dependencies
|
|
66
|
+
- @backstage/backend-common@0.10.4-next.0
|
|
67
|
+
- @backstage/config@0.1.13-next.0
|
|
68
|
+
- @backstage/config-loader@0.9.3-next.0
|
|
69
|
+
|
|
70
|
+
## 0.3.21
|
|
71
|
+
|
|
72
|
+
### Patch Changes
|
|
73
|
+
|
|
74
|
+
- 9d9cfc1b8a: Set `X-Frame-Options: deny` rather than the default `sameorigin` for all content served by the `app-backend`.`
|
|
75
|
+
- Updated dependencies
|
|
76
|
+
- @backstage/backend-common@0.10.1
|
|
77
|
+
- @backstage/config-loader@0.9.1
|
|
78
|
+
|
|
3
79
|
## 0.3.20
|
|
4
80
|
|
|
5
81
|
### Patch Changes
|
package/dist/index.cjs.js
CHANGED
|
@@ -3,17 +3,24 @@
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
5
|
var backendCommon = require('@backstage/backend-common');
|
|
6
|
+
var helmet = require('helmet');
|
|
6
7
|
var express = require('express');
|
|
7
8
|
var Router = require('express-promise-router');
|
|
8
9
|
var fs = require('fs-extra');
|
|
9
10
|
var path = require('path');
|
|
10
11
|
var configLoader = require('@backstage/config-loader');
|
|
12
|
+
var luxon = require('luxon');
|
|
13
|
+
var partition = require('lodash/partition');
|
|
14
|
+
var globby = require('globby');
|
|
11
15
|
|
|
12
16
|
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
|
|
13
17
|
|
|
18
|
+
var helmet__default = /*#__PURE__*/_interopDefaultLegacy(helmet);
|
|
14
19
|
var express__default = /*#__PURE__*/_interopDefaultLegacy(express);
|
|
15
20
|
var Router__default = /*#__PURE__*/_interopDefaultLegacy(Router);
|
|
16
21
|
var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
|
|
22
|
+
var partition__default = /*#__PURE__*/_interopDefaultLegacy(partition);
|
|
23
|
+
var globby__default = /*#__PURE__*/_interopDefaultLegacy(globby);
|
|
17
24
|
|
|
18
25
|
async function injectConfig(options) {
|
|
19
26
|
const { staticDir, logger, appConfigs } = options;
|
|
@@ -46,7 +53,7 @@ async function readConfigs(options) {
|
|
|
46
53
|
const serializedSchema = await fs__default["default"].readJson(schemaPath);
|
|
47
54
|
try {
|
|
48
55
|
const schema = await configLoader.loadConfigSchema({ serialized: serializedSchema });
|
|
49
|
-
const frontendConfigs = await schema.process([{ data: config.get(), context: "app" }], { visibility: ["frontend"] });
|
|
56
|
+
const frontendConfigs = await schema.process([{ data: config.get(), context: "app" }], { visibility: ["frontend"], withDeprecatedKeys: true });
|
|
50
57
|
appConfigs.push(...frontendConfigs);
|
|
51
58
|
} catch (error) {
|
|
52
59
|
throw new Error(`Invalid app bundle schema. If this error is unexpected you need to run \`yarn build\` in the app. If that doesn't help you should make sure your config schema is correct and rebuild the app bundle again. Caused by the following schema error, ${error}`);
|
|
@@ -55,6 +62,117 @@ async function readConfigs(options) {
|
|
|
55
62
|
return appConfigs;
|
|
56
63
|
}
|
|
57
64
|
|
|
65
|
+
var __accessCheck = (obj, member, msg) => {
|
|
66
|
+
if (!member.has(obj))
|
|
67
|
+
throw TypeError("Cannot " + msg);
|
|
68
|
+
};
|
|
69
|
+
var __privateGet = (obj, member, getter) => {
|
|
70
|
+
__accessCheck(obj, member, "read from private field");
|
|
71
|
+
return getter ? getter.call(obj) : member.get(obj);
|
|
72
|
+
};
|
|
73
|
+
var __privateAdd = (obj, member, value) => {
|
|
74
|
+
if (member.has(obj))
|
|
75
|
+
throw TypeError("Cannot add the same private member more than once");
|
|
76
|
+
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
77
|
+
};
|
|
78
|
+
var __privateSet = (obj, member, value, setter) => {
|
|
79
|
+
__accessCheck(obj, member, "write to private field");
|
|
80
|
+
setter ? setter.call(obj, value) : member.set(obj, value);
|
|
81
|
+
return value;
|
|
82
|
+
};
|
|
83
|
+
var _db, _logger;
|
|
84
|
+
const migrationsDir = backendCommon.resolvePackagePath("@backstage/plugin-app-backend", "migrations");
|
|
85
|
+
const _StaticAssetsStore = class {
|
|
86
|
+
constructor(options) {
|
|
87
|
+
__privateAdd(this, _db, void 0);
|
|
88
|
+
__privateAdd(this, _logger, void 0);
|
|
89
|
+
__privateSet(this, _db, options.database);
|
|
90
|
+
__privateSet(this, _logger, options.logger);
|
|
91
|
+
}
|
|
92
|
+
static async create(options) {
|
|
93
|
+
await options.database.migrate.latest({
|
|
94
|
+
directory: migrationsDir
|
|
95
|
+
});
|
|
96
|
+
return new _StaticAssetsStore(options);
|
|
97
|
+
}
|
|
98
|
+
async storeAssets(assets) {
|
|
99
|
+
const existingRows = await __privateGet(this, _db).call(this, "static_assets_cache").whereIn("path", assets.map((a) => a.path));
|
|
100
|
+
const existingAssetPaths = new Set(existingRows.map((r) => r.path));
|
|
101
|
+
const [modified, added] = partition__default["default"](assets, (asset) => existingAssetPaths.has(asset.path));
|
|
102
|
+
__privateGet(this, _logger).info(`Storing ${modified.length} updated assets and ${added.length} new assets`);
|
|
103
|
+
await __privateGet(this, _db).call(this, "static_assets_cache").update({
|
|
104
|
+
last_modified_at: __privateGet(this, _db).fn.now()
|
|
105
|
+
}).whereIn("path", modified.map((a) => a.path));
|
|
106
|
+
for (const asset of added) {
|
|
107
|
+
await __privateGet(this, _db).call(this, "static_assets_cache").insert({
|
|
108
|
+
path: asset.path,
|
|
109
|
+
content: await asset.content()
|
|
110
|
+
}).onConflict("path").ignore();
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
async getAsset(path) {
|
|
114
|
+
const [row] = await __privateGet(this, _db).call(this, "static_assets_cache").where({
|
|
115
|
+
path
|
|
116
|
+
});
|
|
117
|
+
if (!row) {
|
|
118
|
+
return void 0;
|
|
119
|
+
}
|
|
120
|
+
return {
|
|
121
|
+
path: row.path,
|
|
122
|
+
content: row.content,
|
|
123
|
+
lastModifiedAt: typeof row.last_modified_at === "string" ? luxon.DateTime.fromSQL(row.last_modified_at, { zone: "UTC" }).toJSDate() : row.last_modified_at
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
async trimAssets(options) {
|
|
127
|
+
const { maxAgeSeconds } = options;
|
|
128
|
+
await __privateGet(this, _db).call(this, "static_assets_cache").where("last_modified_at", "<=", __privateGet(this, _db).client.config.client === "sqlite3" ? __privateGet(this, _db).raw(`datetime('now', ?)`, [`-${maxAgeSeconds} seconds`]) : __privateGet(this, _db).raw(`now() + interval '${-maxAgeSeconds} seconds'`)).delete();
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
let StaticAssetsStore = _StaticAssetsStore;
|
|
132
|
+
_db = new WeakMap();
|
|
133
|
+
_logger = new WeakMap();
|
|
134
|
+
|
|
135
|
+
async function findStaticAssets(staticDir) {
|
|
136
|
+
const assetPaths = await globby__default["default"]("**/*", {
|
|
137
|
+
ignore: ["**/*.map"],
|
|
138
|
+
cwd: staticDir,
|
|
139
|
+
dot: true
|
|
140
|
+
});
|
|
141
|
+
return assetPaths.map((path) => ({
|
|
142
|
+
path,
|
|
143
|
+
content: async () => fs__default["default"].readFile(backendCommon.resolveSafeChildPath(staticDir, path))
|
|
144
|
+
}));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const CACHE_CONTROL_NO_CACHE = "no-store, max-age=0";
|
|
148
|
+
const CACHE_CONTROL_MAX_CACHE = "public, max-age=1209600";
|
|
149
|
+
|
|
150
|
+
function createStaticAssetMiddleware(store) {
|
|
151
|
+
return (req, res, next) => {
|
|
152
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
153
|
+
next();
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
Promise.resolve((async () => {
|
|
157
|
+
const path$1 = req.path.startsWith("/") ? req.path.slice(1) : req.path;
|
|
158
|
+
const asset = await store.getAsset(path$1);
|
|
159
|
+
if (!asset) {
|
|
160
|
+
next();
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
const ext = path.extname(asset.path);
|
|
164
|
+
if (ext) {
|
|
165
|
+
res.type(ext);
|
|
166
|
+
} else {
|
|
167
|
+
res.type("bin");
|
|
168
|
+
}
|
|
169
|
+
res.setHeader("Cache-Control", CACHE_CONTROL_MAX_CACHE);
|
|
170
|
+
res.setHeader("Last-Modified", asset.lastModifiedAt.toUTCString());
|
|
171
|
+
res.send(asset.content);
|
|
172
|
+
})()).catch(next);
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
58
176
|
async function createRouter(options) {
|
|
59
177
|
const { config, logger, appPackageName, staticFallbackHandler } = options;
|
|
60
178
|
const appDistDir = backendCommon.resolvePackagePath(appPackageName, "dist");
|
|
@@ -73,8 +191,23 @@ async function createRouter(options) {
|
|
|
73
191
|
await injectConfig({ appConfigs, logger, staticDir });
|
|
74
192
|
}
|
|
75
193
|
const router = Router__default["default"]();
|
|
194
|
+
router.use(helmet__default["default"].frameguard({ action: "deny" }));
|
|
76
195
|
const staticRouter = Router__default["default"]();
|
|
77
|
-
staticRouter.use(express__default["default"].static(path.resolve(appDistDir, "static")
|
|
196
|
+
staticRouter.use(express__default["default"].static(path.resolve(appDistDir, "static"), {
|
|
197
|
+
setHeaders: (res) => {
|
|
198
|
+
res.setHeader("Cache-Control", CACHE_CONTROL_MAX_CACHE);
|
|
199
|
+
}
|
|
200
|
+
}));
|
|
201
|
+
if (options.database) {
|
|
202
|
+
const store = await StaticAssetsStore.create({
|
|
203
|
+
logger,
|
|
204
|
+
database: await options.database.getClient()
|
|
205
|
+
});
|
|
206
|
+
const assets = await findStaticAssets(staticDir);
|
|
207
|
+
await store.storeAssets(assets);
|
|
208
|
+
await store.trimAssets({ maxAgeSeconds: 60 * 60 * 24 * 7 });
|
|
209
|
+
staticRouter.use(createStaticAssetMiddleware(store));
|
|
210
|
+
}
|
|
78
211
|
if (staticFallbackHandler) {
|
|
79
212
|
staticRouter.use(staticFallbackHandler);
|
|
80
213
|
}
|
|
@@ -83,14 +216,14 @@ async function createRouter(options) {
|
|
|
83
216
|
router.use(express__default["default"].static(appDistDir, {
|
|
84
217
|
setHeaders: (res, path) => {
|
|
85
218
|
if (express__default["default"].static.mime.lookup(path) === "text/html") {
|
|
86
|
-
res.setHeader("Cache-Control",
|
|
219
|
+
res.setHeader("Cache-Control", CACHE_CONTROL_NO_CACHE);
|
|
87
220
|
}
|
|
88
221
|
}
|
|
89
222
|
}));
|
|
90
223
|
router.get("/*", (_req, res) => {
|
|
91
224
|
res.sendFile(path.resolve(appDistDir, "index.html"), {
|
|
92
225
|
headers: {
|
|
93
|
-
"cache-control":
|
|
226
|
+
"cache-control": CACHE_CONTROL_NO_CACHE
|
|
94
227
|
}
|
|
95
228
|
});
|
|
96
229
|
});
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/lib/config.ts","../src/service/router.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport { resolve as resolvePath } from 'path';\nimport { Logger } from 'winston';\nimport { AppConfig, Config } from '@backstage/config';\nimport { JsonObject } from '@backstage/types';\nimport { loadConfigSchema, readEnvConfig } from '@backstage/config-loader';\n\ntype InjectOptions = {\n appConfigs: AppConfig[];\n // Directory of the static JS files to search for file to inject\n staticDir: string;\n logger: Logger;\n};\n\n/**\n * Injects configs into the app bundle, replacing any existing injected config.\n */\nexport async function injectConfig(options: InjectOptions) {\n const { staticDir, logger, appConfigs } = options;\n\n const files = await fs.readdir(staticDir);\n const jsFiles = files.filter(file => file.endsWith('.js'));\n\n const escapedData = JSON.stringify(appConfigs).replace(/(\"|'|\\\\)/g, '\\\\$1');\n const injected = `/*__APP_INJECTED_CONFIG_MARKER__*/\"${escapedData}\"/*__INJECTED_END__*/`;\n\n for (const jsFile of jsFiles) {\n const path = resolvePath(staticDir, jsFile);\n\n const content = await fs.readFile(path, 'utf8');\n if (content.includes('__APP_INJECTED_RUNTIME_CONFIG__')) {\n logger.info(`Injecting env config into ${jsFile}`);\n\n const newContent = content.replace(\n '\"__APP_INJECTED_RUNTIME_CONFIG__\"',\n injected,\n );\n await fs.writeFile(path, newContent, 'utf8');\n return;\n } else if (content.includes('__APP_INJECTED_CONFIG_MARKER__')) {\n logger.info(`Replacing injected env config in ${jsFile}`);\n\n const newContent = content.replace(\n /\\/\\*__APP_INJECTED_CONFIG_MARKER__\\*\\/.*\\/\\*__INJECTED_END__\\*\\//,\n injected,\n );\n await fs.writeFile(path, newContent, 'utf8');\n return;\n }\n }\n logger.info('Env config not injected');\n}\n\ntype ReadOptions = {\n env: { [name: string]: string | undefined };\n appDistDir: string;\n config: Config;\n};\n\n/**\n * Read config from environment and process the backend config using the\n * schema that is embedded in the frontend build.\n */\nexport async function readConfigs(options: ReadOptions): Promise<AppConfig[]> {\n const { env, appDistDir, config } = options;\n\n const appConfigs = readEnvConfig(env);\n\n const schemaPath = resolvePath(appDistDir, '.config-schema.json');\n if (await fs.pathExists(schemaPath)) {\n const serializedSchema = await fs.readJson(schemaPath);\n\n try {\n const schema = await loadConfigSchema({ serialized: serializedSchema });\n\n const frontendConfigs = await schema.process(\n [{ data: config.get() as JsonObject, context: 'app' }],\n { visibility: ['frontend'] },\n );\n appConfigs.push(...frontendConfigs);\n } catch (error) {\n throw new Error(\n 'Invalid app bundle schema. If this error is unexpected you need to run `yarn build` in the app. ' +\n `If that doesn't help you should make sure your config schema is correct and rebuild the app bundle again. ` +\n `Caused by the following schema error, ${error}`,\n );\n }\n }\n\n return appConfigs;\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { notFoundHandler, resolvePackagePath } from '@backstage/backend-common';\nimport { Config } from '@backstage/config';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport fs from 'fs-extra';\nimport { resolve as resolvePath } from 'path';\nimport { Logger } from 'winston';\nimport { injectConfig, readConfigs } from '../lib/config';\n\n// express uses mime v1 while we only have types for mime v2\ntype Mime = { lookup(arg0: string): string };\n\nexport interface RouterOptions {\n config: Config;\n logger: Logger;\n\n /**\n * The name of the app package that content should be served from. The same app package should be\n * added as a dependency to the backend package in order for it to be accessible at runtime.\n *\n * In a typical setup with a single app package this would be set to 'app'.\n */\n appPackageName: string;\n\n /**\n * A request handler to handle requests for static content that are not present in the app bundle.\n *\n * This can be used to avoid issues with clients on older deployment versions trying to access lazy\n * loaded content that is no longer present. Typically the requests would fall back to a long-term\n * object store where all recently deployed versions of the app are present.\n */\n staticFallbackHandler?: express.Handler;\n\n /**\n * Disables the configuration injection. This can be useful if you're running in an environment\n * with a read-only filesystem, or for some other reason don't want configuration to be injected.\n *\n * Note that this will cause the configuration used when building the app bundle to be used, unless\n * a separate configuration loading strategy is set up.\n *\n * This also disables configuration injection though `APP_CONFIG_` environment variables.\n */\n disableConfigInjection?: boolean;\n}\n\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const { config, logger, appPackageName, staticFallbackHandler } = options;\n\n const appDistDir = resolvePackagePath(appPackageName, 'dist');\n const staticDir = resolvePath(appDistDir, 'static');\n\n if (!(await fs.pathExists(staticDir))) {\n logger.warn(\n `Can't serve static app content from ${staticDir}, directory doesn't exist`,\n );\n\n return Router();\n }\n\n logger.info(`Serving static app content from ${appDistDir}`);\n\n if (!options.disableConfigInjection) {\n const appConfigs = await readConfigs({\n config,\n appDistDir,\n env: process.env,\n });\n\n await injectConfig({ appConfigs, logger, staticDir });\n }\n\n const router = Router();\n\n // Use a separate router for static content so that a fallback can be provided by backend\n const staticRouter = Router();\n staticRouter.use(express.static(resolvePath(appDistDir, 'static')));\n if (staticFallbackHandler) {\n staticRouter.use(staticFallbackHandler);\n }\n staticRouter.use(notFoundHandler());\n\n router.use('/static', staticRouter);\n router.use(\n express.static(appDistDir, {\n setHeaders: (res, path) => {\n // The Cache-Control header instructs the browser to not cache html files since it might\n // link to static assets from recently deployed versions.\n if (\n (express.static.mime as unknown as Mime).lookup(path) === 'text/html'\n ) {\n res.setHeader('Cache-Control', 'no-store, max-age=0');\n }\n },\n }),\n );\n router.get('/*', (_req, res) => {\n res.sendFile(resolvePath(appDistDir, 'index.html'), {\n headers: {\n // The Cache-Control header instructs the browser to not cache the index.html since it might\n // link to static assets from recently deployed versions.\n 'cache-control': 'no-store, max-age=0',\n },\n });\n });\n\n return router;\n}\n"],"names":["fs","path","resolvePath","readEnvConfig","loadConfigSchema","resolvePackagePath","Router","express","notFoundHandler"],"mappings":";;;;;;;;;;;;;;;;;4BAiCmC,SAAwB;AACzD,QAAM,EAAE,WAAW,QAAQ,eAAe;AAE1C,QAAM,QAAQ,MAAMA,uBAAG,QAAQ;AAC/B,QAAM,UAAU,MAAM,OAAO,UAAQ,KAAK,SAAS;AAEnD,QAAM,cAAc,KAAK,UAAU,YAAY,QAAQ,aAAa;AACpE,QAAM,WAAW,sCAAsC;AAEvD,aAAW,UAAU,SAAS;AAC5B,UAAMC,SAAOC,aAAY,WAAW;AAEpC,UAAM,UAAU,MAAMF,uBAAG,SAASC,QAAM;AACxC,QAAI,QAAQ,SAAS,oCAAoC;AACvD,aAAO,KAAK,6BAA6B;AAEzC,YAAM,aAAa,QAAQ,QACzB,qCACA;AAEF,YAAMD,uBAAG,UAAUC,QAAM,YAAY;AACrC;AAAA,eACS,QAAQ,SAAS,mCAAmC;AAC7D,aAAO,KAAK,oCAAoC;AAEhD,YAAM,aAAa,QAAQ,QACzB,oEACA;AAEF,YAAMD,uBAAG,UAAUC,QAAM,YAAY;AACrC;AAAA;AAAA;AAGJ,SAAO,KAAK;AAAA;2BAaoB,SAA4C;AAC5E,QAAM,EAAE,KAAK,YAAY,WAAW;AAEpC,QAAM,aAAaE,2B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MAClD,SAAS;AAAA,QAGP,iBAAiB;AAAA;AAAA;AAAA;AAKvB,SAAO;AAAA;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/lib/config.ts","../src/lib/assets/StaticAssetsStore.ts","../src/lib/assets/findStaticAssets.ts","../src/lib/headers.ts","../src/lib/assets/createStaticAssetMiddleware.ts","../src/service/router.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport { resolve as resolvePath } from 'path';\nimport { Logger } from 'winston';\nimport { AppConfig, Config } from '@backstage/config';\nimport { JsonObject } from '@backstage/types';\nimport { loadConfigSchema, readEnvConfig } from '@backstage/config-loader';\n\ntype InjectOptions = {\n appConfigs: AppConfig[];\n // Directory of the static JS files to search for file to inject\n staticDir: string;\n logger: Logger;\n};\n\n/**\n * Injects configs into the app bundle, replacing any existing injected config.\n */\nexport async function injectConfig(options: InjectOptions) {\n const { staticDir, logger, appConfigs } = options;\n\n const files = await fs.readdir(staticDir);\n const jsFiles = files.filter(file => file.endsWith('.js'));\n\n const escapedData = JSON.stringify(appConfigs).replace(/(\"|'|\\\\)/g, '\\\\$1');\n const injected = `/*__APP_INJECTED_CONFIG_MARKER__*/\"${escapedData}\"/*__INJECTED_END__*/`;\n\n for (const jsFile of jsFiles) {\n const path = resolvePath(staticDir, jsFile);\n\n const content = await fs.readFile(path, 'utf8');\n if (content.includes('__APP_INJECTED_RUNTIME_CONFIG__')) {\n logger.info(`Injecting env config into ${jsFile}`);\n\n const newContent = content.replace(\n '\"__APP_INJECTED_RUNTIME_CONFIG__\"',\n injected,\n );\n await fs.writeFile(path, newContent, 'utf8');\n return;\n } else if (content.includes('__APP_INJECTED_CONFIG_MARKER__')) {\n logger.info(`Replacing injected env config in ${jsFile}`);\n\n const newContent = content.replace(\n /\\/\\*__APP_INJECTED_CONFIG_MARKER__\\*\\/.*\\/\\*__INJECTED_END__\\*\\//,\n injected,\n );\n await fs.writeFile(path, newContent, 'utf8');\n return;\n }\n }\n logger.info('Env config not injected');\n}\n\ntype ReadOptions = {\n env: { [name: string]: string | undefined };\n appDistDir: string;\n config: Config;\n};\n\n/**\n * Read config from environment and process the backend config using the\n * schema that is embedded in the frontend build.\n */\nexport async function readConfigs(options: ReadOptions): Promise<AppConfig[]> {\n const { env, appDistDir, config } = options;\n\n const appConfigs = readEnvConfig(env);\n\n const schemaPath = resolvePath(appDistDir, '.config-schema.json');\n if (await fs.pathExists(schemaPath)) {\n const serializedSchema = await fs.readJson(schemaPath);\n\n try {\n const schema = await loadConfigSchema({ serialized: serializedSchema });\n\n const frontendConfigs = await schema.process(\n [{ data: config.get() as JsonObject, context: 'app' }],\n { visibility: ['frontend'], withDeprecatedKeys: true },\n );\n appConfigs.push(...frontendConfigs);\n } catch (error) {\n throw new Error(\n 'Invalid app bundle schema. If this error is unexpected you need to run `yarn build` in the app. ' +\n `If that doesn't help you should make sure your config schema is correct and rebuild the app bundle again. ` +\n `Caused by the following schema error, ${error}`,\n );\n }\n }\n\n return appConfigs;\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { resolvePackagePath } from '@backstage/backend-common';\nimport { Knex } from 'knex';\nimport { Logger } from 'winston';\nimport { DateTime } from 'luxon';\nimport partition from 'lodash/partition';\nimport { StaticAsset, StaticAssetInput, StaticAssetProvider } from './types';\n\nconst migrationsDir = resolvePackagePath(\n '@backstage/plugin-app-backend',\n 'migrations',\n);\n\ninterface StaticAssetRow {\n path: string;\n content: Buffer;\n last_modified_at: Date;\n}\n\n/** @internal */\nexport interface StaticAssetsStoreOptions {\n database: Knex;\n logger: Logger;\n}\n\n/**\n * A storage for static assets that are assumed to be immutable.\n *\n * @internal\n */\nexport class StaticAssetsStore implements StaticAssetProvider {\n #db: Knex;\n #logger: Logger;\n\n static async create(options: StaticAssetsStoreOptions) {\n await options.database.migrate.latest({\n directory: migrationsDir,\n });\n return new StaticAssetsStore(options);\n }\n\n private constructor(options: StaticAssetsStoreOptions) {\n this.#db = options.database;\n this.#logger = options.logger;\n }\n\n /**\n * Store the provided assets.\n *\n * If an asset for a given path already exists the modification time will be\n * updated, but the contents will not.\n */\n async storeAssets(assets: StaticAssetInput[]) {\n const existingRows = await this.#db<StaticAssetRow>(\n 'static_assets_cache',\n ).whereIn(\n 'path',\n assets.map(a => a.path),\n );\n const existingAssetPaths = new Set(existingRows.map(r => r.path));\n\n const [modified, added] = partition(assets, asset =>\n existingAssetPaths.has(asset.path),\n );\n\n this.#logger.info(\n `Storing ${modified.length} updated assets and ${added.length} new assets`,\n );\n\n await this.#db('static_assets_cache')\n .update({\n last_modified_at: this.#db.fn.now(),\n })\n .whereIn(\n 'path',\n modified.map(a => a.path),\n );\n\n for (const asset of added) {\n // We ignore conflicts with other nodes, it doesn't matter if someone else\n // added the same asset just before us.\n await this.#db('static_assets_cache')\n .insert({\n path: asset.path,\n content: await asset.content(),\n })\n .onConflict('path')\n .ignore();\n }\n }\n\n /**\n * Retrieve an asset from the store with the given path.\n */\n async getAsset(path: string): Promise<StaticAsset | undefined> {\n const [row] = await this.#db<StaticAssetRow>('static_assets_cache').where({\n path,\n });\n if (!row) {\n return undefined;\n }\n return {\n path: row.path,\n content: row.content,\n lastModifiedAt:\n typeof row.last_modified_at === 'string'\n ? DateTime.fromSQL(row.last_modified_at, { zone: 'UTC' }).toJSDate()\n : row.last_modified_at,\n };\n }\n\n /**\n * Delete any assets from the store whose modification time is older than the max age.\n */\n async trimAssets(options: { maxAgeSeconds: number }) {\n const { maxAgeSeconds } = options;\n await this.#db<StaticAssetRow>('static_assets_cache')\n .where(\n 'last_modified_at',\n '<=',\n this.#db.client.config.client === 'sqlite3'\n ? this.#db.raw(`datetime('now', ?)`, [`-${maxAgeSeconds} seconds`])\n : this.#db.raw(`now() + interval '${-maxAgeSeconds} seconds'`),\n )\n .delete();\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fs from 'fs-extra';\nimport globby from 'globby';\nimport { StaticAssetInput } from './types';\nimport { resolveSafeChildPath } from '@backstage/backend-common';\n\n/**\n * Finds all static assets within a directory\n *\n * @internal\n */\nexport async function findStaticAssets(\n staticDir: string,\n): Promise<StaticAssetInput[]> {\n const assetPaths = await globby('**/*', {\n ignore: ['**/*.map'], // Ignore source maps since they're quite large\n cwd: staticDir,\n dot: true,\n });\n\n return assetPaths.map(path => ({\n path,\n content: async () => fs.readFile(resolveSafeChildPath(staticDir, path)),\n }));\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const CACHE_CONTROL_NO_CACHE = 'no-store, max-age=0';\nexport const CACHE_CONTROL_MAX_CACHE = 'public, max-age=1209600'; // 14 days\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { extname } from 'path';\nimport { RequestHandler } from 'express';\nimport { StaticAssetProvider } from './types';\nimport { CACHE_CONTROL_MAX_CACHE } from '../headers';\n\n/**\n * Creates a middleware that serves static assets from a static asset provider\n *\n * @internal\n */\nexport function createStaticAssetMiddleware(\n store: StaticAssetProvider,\n): RequestHandler {\n return (req, res, next) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n next();\n return;\n }\n\n // Let's not assume we're in promise-router\n Promise.resolve(\n (async () => {\n // Drop leading slashes from the incoming path\n const path = req.path.startsWith('/') ? req.path.slice(1) : req.path;\n\n const asset = await store.getAsset(path);\n if (!asset) {\n next();\n return;\n }\n\n // Set the Content-Type header, falling back to octet-stream\n const ext = extname(asset.path);\n if (ext) {\n res.type(ext);\n } else {\n res.type('bin');\n }\n\n // Same as our express.static override\n res.setHeader('Cache-Control', CACHE_CONTROL_MAX_CACHE);\n res.setHeader('Last-Modified', asset.lastModifiedAt.toUTCString());\n\n res.send(asset.content);\n })(),\n ).catch(next);\n };\n}\n","/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n notFoundHandler,\n PluginDatabaseManager,\n resolvePackagePath,\n} from '@backstage/backend-common';\nimport { Config } from '@backstage/config';\nimport helmet from 'helmet';\nimport express from 'express';\nimport Router from 'express-promise-router';\nimport fs from 'fs-extra';\nimport { resolve as resolvePath } from 'path';\nimport { Logger } from 'winston';\nimport { injectConfig, readConfigs } from '../lib/config';\nimport {\n StaticAssetsStore,\n findStaticAssets,\n createStaticAssetMiddleware,\n} from '../lib/assets';\nimport {\n CACHE_CONTROL_MAX_CACHE,\n CACHE_CONTROL_NO_CACHE,\n} from '../lib/headers';\n\n// express uses mime v1 while we only have types for mime v2\ntype Mime = { lookup(arg0: string): string };\n\nexport interface RouterOptions {\n config: Config;\n logger: Logger;\n\n /**\n * If a database is provided it will be used to cache previously deployed static assets.\n *\n * This is a built-in alternative to using a `staticFallbackHandler`.\n */\n database?: PluginDatabaseManager;\n\n /**\n * The name of the app package that content should be served from. The same app package should be\n * added as a dependency to the backend package in order for it to be accessible at runtime.\n *\n * In a typical setup with a single app package this would be set to 'app'.\n */\n appPackageName: string;\n\n /**\n * A request handler to handle requests for static content that are not present in the app bundle.\n *\n * This can be used to avoid issues with clients on older deployment versions trying to access lazy\n * loaded content that is no longer present. Typically the requests would fall back to a long-term\n * object store where all recently deployed versions of the app are present.\n *\n * Another option is to provide a `database` that will take care of storing the static assets instead.\n *\n * If both `database` and `staticFallbackHandler` are provided, the `database` will attempt to serve\n * static assets first, and if they are not found, the `staticFallbackHandler` will be called.\n */\n staticFallbackHandler?: express.Handler;\n\n /**\n * Disables the configuration injection. This can be useful if you're running in an environment\n * with a read-only filesystem, or for some other reason don't want configuration to be injected.\n *\n * Note that this will cause the configuration used when building the app bundle to be used, unless\n * a separate configuration loading strategy is set up.\n *\n * This also disables configuration injection though `APP_CONFIG_` environment variables.\n */\n disableConfigInjection?: boolean;\n}\n\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const { config, logger, appPackageName, staticFallbackHandler } = options;\n\n const appDistDir = resolvePackagePath(appPackageName, 'dist');\n const staticDir = resolvePath(appDistDir, 'static');\n\n if (!(await fs.pathExists(staticDir))) {\n logger.warn(\n `Can't serve static app content from ${staticDir}, directory doesn't exist`,\n );\n\n return Router();\n }\n\n logger.info(`Serving static app content from ${appDistDir}`);\n\n if (!options.disableConfigInjection) {\n const appConfigs = await readConfigs({\n config,\n appDistDir,\n env: process.env,\n });\n\n await injectConfig({ appConfigs, logger, staticDir });\n }\n\n const router = Router();\n\n router.use(helmet.frameguard({ action: 'deny' }));\n\n // Use a separate router for static content so that a fallback can be provided by backend\n const staticRouter = Router();\n staticRouter.use(\n express.static(resolvePath(appDistDir, 'static'), {\n setHeaders: res => {\n res.setHeader('Cache-Control', CACHE_CONTROL_MAX_CACHE);\n },\n }),\n );\n\n if (options.database) {\n const store = await StaticAssetsStore.create({\n logger,\n database: await options.database.getClient(),\n });\n\n const assets = await findStaticAssets(staticDir);\n await store.storeAssets(assets);\n // Remove any assets that are older than 7 days\n await store.trimAssets({ maxAgeSeconds: 60 * 60 * 24 * 7 });\n\n staticRouter.use(createStaticAssetMiddleware(store));\n }\n\n if (staticFallbackHandler) {\n staticRouter.use(staticFallbackHandler);\n }\n staticRouter.use(notFoundHandler());\n\n router.use('/static', staticRouter);\n router.use(\n express.static(appDistDir, {\n setHeaders: (res, path) => {\n // The Cache-Control header instructs the browser to not cache html files since it might\n // link to static assets from recently deployed versions.\n if (\n (express.static.mime as unknown as Mime).lookup(path) === 'text/html'\n ) {\n res.setHeader('Cache-Control', CACHE_CONTROL_NO_CACHE);\n }\n },\n }),\n );\n router.get('/*', (_req, res) => {\n res.sendFile(resolvePath(appDistDir, 'index.html'), {\n headers: {\n // The Cache-Control header instructs the browser to not cache the index.html since it might\n // link to static assets from recently deployed versions.\n 'cache-control': CACHE_CONTROL_NO_CACHE,\n },\n });\n });\n\n return router;\n}\n"],"names":["fs","path","resolvePath","readEnvConfig","loadConfigSchema","resolvePackagePath","partition","DateTime","globby","resolveSafeChildPath","extname","Router","helmet","express","notFoundHandler"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;4BAiCmC,SAAwB;AACzD,QAAM,EAAE,WAAW,QAAQ,eAAe;AAE1C,QAAM,QAAQ,MAAMA,uBAAG,QAAQ;AAC/B,QAAM,UAAU,MAAM,OAAO,UAAQ,KAAK,SAAS;AAEnD,QAAM,cAAc,KAAK,UAAU,YAAY,QAAQ,aAAa;AACpE,QAAM,WAAW,sCAAsC;AAEvD,aAAW,UAAU,SAAS;AAC5B,UAAMC,SAAOC,aAAY,WAAW;AAEpC,UAAM,UAAU,MAAMF,uBAAG,SAASC,QAAM;AACxC,QAAI,QAAQ,SAAS,oCAAoC;AACvD,aAAO,KAAK,6BAA6B;AAEzC,YAAM,aAAa,QAAQ,QACzB,qCACA;AAEF,YAAMD,uBAAG,UAAUC,QAAM,YAAY;AACrC;AAAA,eACS,QAAQ,SAAS,mCAAmC;AAC7D,aAAO,KAAK,oCAAoC;AAEhD,YAAM,aAAa,QAAQ,QACzB,oEACA;AAEF,YAAMD,uBAAG,UAAUC,QAAM,YAAY;AACrC;AAAA;AAAA;AAGJ,SAAO,KAAK;AAAA;2BAaoB,SAA4C;AAC5E,QAAM,EAAE,KAAK,YAAY,WAAW;AAEpC,QAAM,aAAaE,2BAAc;AAEjC,QAAM,aAAaD,aAAY,YAAY;AAC3C,MAAI,MAAMF,uBAAG,WAAW,aAAa;AACnC,UAAM,mBAAmB,MAAMA,uBAAG,SAAS;AAE3C,QAAI;AACF,YAAM,SAAS,MAAMI,8BAAiB,EAAE,YAAY;AAEpD,YAAM,kBAAkB,MAAM,OAAO,QACnC,CAAC,EAAE,MAAM,OAAO,OAAqB,SAAS,UAC9C,EAAE,YAA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
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PluginDatabaseManager } from '@backstage/backend-common';
|
|
1
2
|
import { Config } from '@backstage/config';
|
|
2
3
|
import express from 'express';
|
|
3
4
|
import { Logger } from 'winston';
|
|
@@ -5,6 +6,12 @@ import { Logger } from 'winston';
|
|
|
5
6
|
interface RouterOptions {
|
|
6
7
|
config: Config;
|
|
7
8
|
logger: Logger;
|
|
9
|
+
/**
|
|
10
|
+
* If a database is provided it will be used to cache previously deployed static assets.
|
|
11
|
+
*
|
|
12
|
+
* This is a built-in alternative to using a `staticFallbackHandler`.
|
|
13
|
+
*/
|
|
14
|
+
database?: PluginDatabaseManager;
|
|
8
15
|
/**
|
|
9
16
|
* The name of the app package that content should be served from. The same app package should be
|
|
10
17
|
* added as a dependency to the backend package in order for it to be accessible at runtime.
|
|
@@ -18,6 +25,11 @@ interface RouterOptions {
|
|
|
18
25
|
* This can be used to avoid issues with clients on older deployment versions trying to access lazy
|
|
19
26
|
* loaded content that is no longer present. Typically the requests would fall back to a long-term
|
|
20
27
|
* object store where all recently deployed versions of the app are present.
|
|
28
|
+
*
|
|
29
|
+
* Another option is to provide a `database` that will take care of storing the static assets instead.
|
|
30
|
+
*
|
|
31
|
+
* If both `database` and `staticFallbackHandler` are provided, the `database` will attempt to serve
|
|
32
|
+
* static assets first, and if they are not found, the `staticFallbackHandler` will be called.
|
|
21
33
|
*/
|
|
22
34
|
staticFallbackHandler?: express.Handler;
|
|
23
35
|
/**
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Copyright 2021 The Backstage Authors
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
// @ts-check
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {import('knex').Knex} knex
|
|
21
|
+
*/
|
|
22
|
+
exports.up = async function up(knex) {
|
|
23
|
+
return knex.schema.createTable('static_assets_cache', table => {
|
|
24
|
+
table.comment(
|
|
25
|
+
'A cache of static assets that where previously deployed and may still be lazy-loaded by clients',
|
|
26
|
+
);
|
|
27
|
+
table.text('path').primary().notNullable().comment('The path of the file');
|
|
28
|
+
table
|
|
29
|
+
.dateTime('last_modified_at')
|
|
30
|
+
.defaultTo(knex.fn.now())
|
|
31
|
+
.notNullable()
|
|
32
|
+
.comment(
|
|
33
|
+
'Timestamp of when the asset was most recently seen in a deployment',
|
|
34
|
+
);
|
|
35
|
+
table.binary('content').notNullable().comment('The asset content');
|
|
36
|
+
table.index('last_modified_at', 'static_asset_cache_last_modified_at_idx');
|
|
37
|
+
});
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @param {import('knex').Knex} knex
|
|
42
|
+
*/
|
|
43
|
+
exports.down = async function down(knex) {
|
|
44
|
+
await knex.schema.alterTable('static_assets_cache', table => {
|
|
45
|
+
table.dropIndex([], 'static_asset_cache_last_modified_at_idx');
|
|
46
|
+
});
|
|
47
|
+
await knex.schema.dropTable('static_assets_cache');
|
|
48
|
+
};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/plugin-app-backend",
|
|
3
3
|
"description": "A Backstage backend plugin that serves the Backstage frontend app",
|
|
4
|
-
"version": "0.3.
|
|
4
|
+
"version": "0.3.23-next.0",
|
|
5
5
|
"main": "dist/index.cjs.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
7
7
|
"license": "Apache-2.0",
|
|
@@ -30,27 +30,35 @@
|
|
|
30
30
|
"clean": "backstage-cli clean"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@backstage/backend-common": "^0.10.0",
|
|
34
|
-
"@backstage/config": "^0.1.
|
|
35
|
-
"@backstage/config-loader": "^0.9.
|
|
33
|
+
"@backstage/backend-common": "^0.10.6-next.0",
|
|
34
|
+
"@backstage/config": "^0.1.13",
|
|
35
|
+
"@backstage/config-loader": "^0.9.3",
|
|
36
36
|
"@backstage/types": "^0.1.1",
|
|
37
37
|
"@types/express": "^4.17.6",
|
|
38
38
|
"express": "^4.17.1",
|
|
39
39
|
"express-promise-router": "^4.1.0",
|
|
40
40
|
"fs-extra": "9.1.0",
|
|
41
|
+
"globby": "^11.0.0",
|
|
42
|
+
"helmet": "^4.0.0",
|
|
43
|
+
"knex": "^0.95.1",
|
|
44
|
+
"lodash": "^4.17.21",
|
|
45
|
+
"luxon": "^2.0.2",
|
|
41
46
|
"winston": "^3.2.1",
|
|
42
47
|
"yn": "^4.0.0"
|
|
43
48
|
},
|
|
44
49
|
"devDependencies": {
|
|
45
|
-
"@backstage/
|
|
50
|
+
"@backstage/backend-test-utils": "^0.1.16-next.1",
|
|
51
|
+
"@backstage/cli": "^0.13.1-next.1",
|
|
46
52
|
"@backstage/types": "^0.1.1",
|
|
47
53
|
"@types/supertest": "^2.0.8",
|
|
54
|
+
"mock-fs": "^5.1.0",
|
|
48
55
|
"msw": "^0.35.0",
|
|
49
56
|
"supertest": "^6.1.3"
|
|
50
57
|
},
|
|
51
58
|
"files": [
|
|
52
59
|
"dist",
|
|
60
|
+
"migrations/**/*.{js,d.ts}",
|
|
53
61
|
"static"
|
|
54
62
|
],
|
|
55
|
-
"gitHead": "
|
|
63
|
+
"gitHead": "d6da97a1edeb21fcefc682d91916987ba9f3d89a"
|
|
56
64
|
}
|