@backstage/plugin-app-backend 0.4.0 → 0.4.1
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 +6 -0
- package/dist/service/router.cjs.js +10 -1
- package/dist/service/router.cjs.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -160,7 +160,15 @@ async function createEntryPointRouter({
|
|
|
160
160
|
}
|
|
161
161
|
staticRouter.use(backendCommon.notFoundHandler());
|
|
162
162
|
router.use("/static", staticRouter);
|
|
163
|
-
|
|
163
|
+
const rootRouter = Router__default.default();
|
|
164
|
+
rootRouter.use((req, _res, next) => {
|
|
165
|
+
if (req.url === "/" || req.url === "/index.html") {
|
|
166
|
+
next("router");
|
|
167
|
+
} else {
|
|
168
|
+
next();
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
rootRouter.use(
|
|
164
172
|
express__default.default.static(rootDir, {
|
|
165
173
|
setHeaders: (res, path) => {
|
|
166
174
|
if (express__default.default.static.mime.lookup(path) === "text/html") {
|
|
@@ -169,6 +177,7 @@ async function createEntryPointRouter({
|
|
|
169
177
|
}
|
|
170
178
|
})
|
|
171
179
|
);
|
|
180
|
+
router.use(rootRouter);
|
|
172
181
|
router.get("/*", (_req, res) => {
|
|
173
182
|
if (injectResult?.indexHtmlContent) {
|
|
174
183
|
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.cjs.js","sources":["../../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 { notFoundHandler } from '@backstage/backend-common';\nimport {\n DatabaseService,\n resolvePackagePath,\n RootConfigService,\n} from '@backstage/backend-plugin-api';\nimport { AppConfig } 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 {\n createStaticAssetMiddleware,\n findStaticAssets,\n StaticAssetsStore,\n} from '../lib/assets';\nimport {\n CACHE_CONTROL_MAX_CACHE,\n CACHE_CONTROL_NO_CACHE,\n CACHE_CONTROL_REVALIDATE_CACHE,\n} from '../lib/headers';\nimport { ConfigSchema } from '@backstage/config-loader';\nimport {\n AuthService,\n HttpAuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport { AuthenticationError, InputError } from '@backstage/errors';\nimport { injectConfig, readFrontendConfig } from '../lib/config';\n\n// express uses mime v1 while we only have types for mime v2\ntype Mime = { lookup(arg0: string): string };\n\n/**\n * @public\n * @deprecated Please migrate to the new backend system as this will be removed in the future.\n */\nexport interface RouterOptions {\n config: RootConfigService;\n logger: LoggerService;\n auth?: AuthService;\n httpAuth?: HttpAuthService;\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?: DatabaseService;\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 /**\n *\n * Provides a ConfigSchema.\n *\n */\n schema?: ConfigSchema;\n}\n\n/**\n * @public\n * @deprecated Please migrate to the new backend system as this will be removed in the future.\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const {\n config,\n logger,\n appPackageName,\n staticFallbackHandler,\n auth,\n httpAuth,\n schema,\n } = options;\n\n const disableConfigInjection =\n options.disableConfigInjection ??\n config.getOptionalBoolean('app.disableConfigInjection');\n const disableStaticFallbackCache = config.getOptionalBoolean(\n 'app.disableStaticFallbackCache',\n );\n\n const appDistDir = resolvePackagePath(appPackageName, 'dist');\n const staticDir = resolvePath(appDistDir, 'static');\n\n if (!(await fs.pathExists(staticDir))) {\n if (process.env.NODE_ENV === 'production') {\n logger.error(\n `Can't serve static app content from ${staticDir}, directory doesn't exist`,\n );\n }\n\n return Router();\n }\n\n logger.info(`Serving static app content from ${appDistDir}`);\n\n const appConfigs = disableConfigInjection\n ? undefined\n : await readFrontendConfig({\n config,\n appDistDir,\n env: process.env,\n schema,\n });\n\n const assetStore =\n options.database && !disableStaticFallbackCache\n ? await StaticAssetsStore.create({\n logger,\n database: options.database,\n })\n : undefined;\n\n const router = Router();\n\n router.use(helmet.frameguard({ action: 'deny' }));\n\n const publicDistDir = resolvePath(appDistDir, 'public');\n\n const enablePublicEntryPoint =\n (await fs.pathExists(publicDistDir)) && auth && httpAuth;\n\n if (enablePublicEntryPoint && auth && httpAuth) {\n logger.info(\n `App is running in protected mode, serving public content from ${publicDistDir}`,\n );\n\n const publicRouter = Router();\n\n publicRouter.use(async (req, res, next) => {\n try {\n const credentials = await httpAuth.credentials(req, {\n allow: ['user', 'service', 'none'],\n allowLimitedAccess: true,\n });\n\n if (credentials.principal.type === 'none') {\n next();\n } else {\n next('router');\n }\n } catch {\n // If we fail to authenticate, make sure the session cookie is cleared\n // and continue as unauthenticated. If the user is logged in they will\n // immediately be redirected back to the protected app via the POST.\n await httpAuth.issueUserCookie(res, {\n credentials: await auth.getNoneCredentials(),\n });\n next();\n }\n });\n\n publicRouter.post(\n '*',\n express.urlencoded({ extended: true }),\n async (req, res, next) => {\n if (req.body.type === 'sign-in') {\n const credentials = await auth.authenticate(req.body.token);\n\n if (!auth.isPrincipal(credentials, 'user')) {\n throw new AuthenticationError('Invalid token, not a user');\n }\n\n await httpAuth.issueUserCookie(res, {\n credentials,\n });\n\n // Resume as if it was a GET request towards the outer protected router, serving index.html\n req.method = 'GET';\n next('router');\n } else {\n throw new InputError(\n 'Invalid POST request to app-backend wildcard endpoint',\n );\n }\n },\n );\n\n publicRouter.use(\n await createEntryPointRouter({\n logger: logger.child({ entry: 'public' }),\n rootDir: publicDistDir,\n assetStore: assetStore?.withNamespace('public'),\n appConfigs, // TODO(Rugvip): We should not be including the full config here\n }),\n );\n\n router.use(publicRouter);\n }\n\n router.use(\n await createEntryPointRouter({\n logger: logger.child({ entry: 'main' }),\n rootDir: appDistDir,\n assetStore,\n staticFallbackHandler,\n appConfigs,\n }),\n );\n\n return router;\n}\n\nasync function createEntryPointRouter({\n logger,\n rootDir,\n assetStore,\n staticFallbackHandler,\n appConfigs,\n}: {\n logger: LoggerService;\n rootDir: string;\n assetStore?: StaticAssetsStore;\n staticFallbackHandler?: express.Handler;\n appConfigs?: AppConfig[];\n}) {\n const staticDir = resolvePath(rootDir, 'static');\n\n const injectResult =\n appConfigs &&\n (await injectConfig({ appConfigs, logger, rootDir, staticDir }));\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(\n express.static(staticDir, {\n setHeaders: (res, path) => {\n if (injectResult?.injectedPath === path) {\n res.setHeader('Cache-Control', CACHE_CONTROL_REVALIDATE_CACHE);\n } else {\n res.setHeader('Cache-Control', CACHE_CONTROL_MAX_CACHE);\n }\n },\n }),\n );\n\n if (assetStore) {\n const assets = await findStaticAssets(staticDir);\n await assetStore.storeAssets(assets);\n // Remove any assets that are older than 7 days\n await assetStore.trimAssets({ maxAgeSeconds: 60 * 60 * 24 * 7 });\n\n staticRouter.use(createStaticAssetMiddleware(assetStore));\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(rootDir, {\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\n router.get('/*', (_req, res) => {\n if (injectResult?.indexHtmlContent) {\n res.setHeader('Content-Type', 'text/html; charset=utf-8');\n res.setHeader('Cache-Control', CACHE_CONTROL_NO_CACHE);\n res.send(injectResult.indexHtmlContent);\n } else {\n res.sendFile(resolvePath(rootDir, '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\n return router;\n}\n"],"names":["resolvePackagePath","resolvePath","fs","Router","readFrontendConfig","StaticAssetsStore","helmet","express","AuthenticationError","InputError","injectConfig","CACHE_CONTROL_REVALIDATE_CACHE","CACHE_CONTROL_MAX_CACHE","findStaticAssets","createStaticAssetMiddleware","notFoundHandler","CACHE_CONTROL_NO_CACHE"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAgHA,eAAsB,aACpB,OACyB,EAAA;AACzB,EAAM,MAAA;AAAA,IACJ,MAAA;AAAA,IACA,MAAA;AAAA,IACA,cAAA;AAAA,IACA,qBAAA;AAAA,IACA,IAAA;AAAA,IACA,QAAA;A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A;AAAA;AACvD;AACF,KACD;AAAA,GACH;AAEA,EAAA,MAAA,CAAO,GAAI,CAAA,IAAA,EAAM,CAAC,IAAA,EAAM,GAAQ,KAAA;AAC9B,IAAA,IAAI,cAAc,gBAAkB,EAAA;AAClC,MAAI,GAAA,CAAA,SAAA,CAAU,gBAAgB,0BAA0B,CAAA;AACxD,MAAI,GAAA,CAAA,SAAA,CAAU,iBAAiBA,8BAAsB,CAAA;AACrD,MAAI,GAAA,CAAA,IAAA,CAAK,aAAa,gBAAgB,CAAA;AAAA,KACjC,MAAA;AACL,MAAA,GAAA,CAAI,QAAS,CAAAf,YAAA,CAAY,OAAS,EAAA,YAAY,CAAG,EAAA;AAAA,QAC/C,OAAS,EAAA;AAAA;AAAA;AAAA,UAGP,eAAiB,EAAAe;AAAA;AACnB,OACD,CAAA;AAAA;AACH,GACD,CAAA;AAED,EAAO,OAAA,MAAA;AACT;;;;"}
|
|
1
|
+
{"version":3,"file":"router.cjs.js","sources":["../../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 { notFoundHandler } from '@backstage/backend-common';\nimport {\n DatabaseService,\n resolvePackagePath,\n RootConfigService,\n} from '@backstage/backend-plugin-api';\nimport { AppConfig } 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 {\n createStaticAssetMiddleware,\n findStaticAssets,\n StaticAssetsStore,\n} from '../lib/assets';\nimport {\n CACHE_CONTROL_MAX_CACHE,\n CACHE_CONTROL_NO_CACHE,\n CACHE_CONTROL_REVALIDATE_CACHE,\n} from '../lib/headers';\nimport { ConfigSchema } from '@backstage/config-loader';\nimport {\n AuthService,\n HttpAuthService,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport { AuthenticationError, InputError } from '@backstage/errors';\nimport { injectConfig, readFrontendConfig } from '../lib/config';\n\n// express uses mime v1 while we only have types for mime v2\ntype Mime = { lookup(arg0: string): string };\n\n/**\n * @public\n * @deprecated Please migrate to the new backend system as this will be removed in the future.\n */\nexport interface RouterOptions {\n config: RootConfigService;\n logger: LoggerService;\n auth?: AuthService;\n httpAuth?: HttpAuthService;\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?: DatabaseService;\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 /**\n *\n * Provides a ConfigSchema.\n *\n */\n schema?: ConfigSchema;\n}\n\n/**\n * @public\n * @deprecated Please migrate to the new backend system as this will be removed in the future.\n */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const {\n config,\n logger,\n appPackageName,\n staticFallbackHandler,\n auth,\n httpAuth,\n schema,\n } = options;\n\n const disableConfigInjection =\n options.disableConfigInjection ??\n config.getOptionalBoolean('app.disableConfigInjection');\n const disableStaticFallbackCache = config.getOptionalBoolean(\n 'app.disableStaticFallbackCache',\n );\n\n const appDistDir = resolvePackagePath(appPackageName, 'dist');\n const staticDir = resolvePath(appDistDir, 'static');\n\n if (!(await fs.pathExists(staticDir))) {\n if (process.env.NODE_ENV === 'production') {\n logger.error(\n `Can't serve static app content from ${staticDir}, directory doesn't exist`,\n );\n }\n\n return Router();\n }\n\n logger.info(`Serving static app content from ${appDistDir}`);\n\n const appConfigs = disableConfigInjection\n ? undefined\n : await readFrontendConfig({\n config,\n appDistDir,\n env: process.env,\n schema,\n });\n\n const assetStore =\n options.database && !disableStaticFallbackCache\n ? await StaticAssetsStore.create({\n logger,\n database: options.database,\n })\n : undefined;\n\n const router = Router();\n\n router.use(helmet.frameguard({ action: 'deny' }));\n\n const publicDistDir = resolvePath(appDistDir, 'public');\n\n const enablePublicEntryPoint =\n (await fs.pathExists(publicDistDir)) && auth && httpAuth;\n\n if (enablePublicEntryPoint && auth && httpAuth) {\n logger.info(\n `App is running in protected mode, serving public content from ${publicDistDir}`,\n );\n\n const publicRouter = Router();\n\n publicRouter.use(async (req, res, next) => {\n try {\n const credentials = await httpAuth.credentials(req, {\n allow: ['user', 'service', 'none'],\n allowLimitedAccess: true,\n });\n\n if (credentials.principal.type === 'none') {\n next();\n } else {\n next('router');\n }\n } catch {\n // If we fail to authenticate, make sure the session cookie is cleared\n // and continue as unauthenticated. If the user is logged in they will\n // immediately be redirected back to the protected app via the POST.\n await httpAuth.issueUserCookie(res, {\n credentials: await auth.getNoneCredentials(),\n });\n next();\n }\n });\n\n publicRouter.post(\n '*',\n express.urlencoded({ extended: true }),\n async (req, res, next) => {\n if (req.body.type === 'sign-in') {\n const credentials = await auth.authenticate(req.body.token);\n\n if (!auth.isPrincipal(credentials, 'user')) {\n throw new AuthenticationError('Invalid token, not a user');\n }\n\n await httpAuth.issueUserCookie(res, {\n credentials,\n });\n\n // Resume as if it was a GET request towards the outer protected router, serving index.html\n req.method = 'GET';\n next('router');\n } else {\n throw new InputError(\n 'Invalid POST request to app-backend wildcard endpoint',\n );\n }\n },\n );\n\n publicRouter.use(\n await createEntryPointRouter({\n logger: logger.child({ entry: 'public' }),\n rootDir: publicDistDir,\n assetStore: assetStore?.withNamespace('public'),\n appConfigs, // TODO(Rugvip): We should not be including the full config here\n }),\n );\n\n router.use(publicRouter);\n }\n\n router.use(\n await createEntryPointRouter({\n logger: logger.child({ entry: 'main' }),\n rootDir: appDistDir,\n assetStore,\n staticFallbackHandler,\n appConfigs,\n }),\n );\n\n return router;\n}\n\nasync function createEntryPointRouter({\n logger,\n rootDir,\n assetStore,\n staticFallbackHandler,\n appConfigs,\n}: {\n logger: LoggerService;\n rootDir: string;\n assetStore?: StaticAssetsStore;\n staticFallbackHandler?: express.Handler;\n appConfigs?: AppConfig[];\n}) {\n const staticDir = resolvePath(rootDir, 'static');\n\n const injectResult =\n appConfigs &&\n (await injectConfig({ appConfigs, logger, rootDir, staticDir }));\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(\n express.static(staticDir, {\n setHeaders: (res, path) => {\n if (injectResult?.injectedPath === path) {\n res.setHeader('Cache-Control', CACHE_CONTROL_REVALIDATE_CACHE);\n } else {\n res.setHeader('Cache-Control', CACHE_CONTROL_MAX_CACHE);\n }\n },\n }),\n );\n\n if (assetStore) {\n const assets = await findStaticAssets(staticDir);\n await assetStore.storeAssets(assets);\n // Remove any assets that are older than 7 days\n await assetStore.trimAssets({ maxAgeSeconds: 60 * 60 * 24 * 7 });\n\n staticRouter.use(createStaticAssetMiddleware(assetStore));\n }\n\n if (staticFallbackHandler) {\n staticRouter.use(staticFallbackHandler);\n }\n staticRouter.use(notFoundHandler());\n\n router.use('/static', staticRouter);\n\n const rootRouter = Router();\n rootRouter.use((req, _res, next) => {\n // Make sure / and /index.html are handled by the HTML5 route below\n if (req.url === '/' || req.url === '/index.html') {\n next('router');\n } else {\n next();\n }\n });\n rootRouter.use(\n express.static(rootDir, {\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.use(rootRouter);\n\n // HTML5 routing\n router.get('/*', (_req, res) => {\n if (injectResult?.indexHtmlContent) {\n res.setHeader('Content-Type', 'text/html; charset=utf-8');\n res.setHeader('Cache-Control', CACHE_CONTROL_NO_CACHE);\n res.send(injectResult.indexHtmlContent);\n } else {\n res.sendFile(resolvePath(rootDir, '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\n return router;\n}\n"],"names":["resolvePackagePath","resolvePath","fs","Router","readFrontendConfig","StaticAssetsStore","helmet","express","AuthenticationError","InputError","injectConfig","CACHE_CONTROL_REVALIDATE_CACHE","CACHE_CONTROL_MAX_CACHE","findStaticAssets","createStaticAssetMiddleware","notFoundHandler","CACHE_CONTROL_NO_CACHE"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAgHA,eAAsB,aACpB,OACyB,EAAA;AACzB,EAAM,MAAA;AAAA,IACJ,MAAA;AAAA,IACA,MAAA;AAAA,IACA,cAAA;AAAA,IACA,qBAAA;AAAA,IACA,IAAA;AAAA,IACA,QAAA;AAAA,IACA;AAAA,GACE,GAAA,OAAA;AAEJ,EAAA,MAAM,sBACJ,GAAA,OAAA,CAAQ,sBACR,IAAA,MAAA,CAAO,mBAAmB,4BAA4B,CAAA;AACxD,EAAA,MAAM,6BAA6B,MAAO,CAAA,kBAAA;AAAA,IACxC;AAAA,G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CAAA,IAAA,CAAyB,MAAO,CAAA,IAAI,MAAM,WAC1D,EAAA;AACA,UAAI,GAAA,CAAA,SAAA,CAAU,iBAAiBS,8BAAsB,CAAA;AAAA;AACvD;AACF,KACD;AAAA,GACH;AACA,EAAA,MAAA,CAAO,IAAI,UAAU,CAAA;AAGrB,EAAA,MAAA,CAAO,GAAI,CAAA,IAAA,EAAM,CAAC,IAAA,EAAM,GAAQ,KAAA;AAC9B,IAAA,IAAI,cAAc,gBAAkB,EAAA;AAClC,MAAI,GAAA,CAAA,SAAA,CAAU,gBAAgB,0BAA0B,CAAA;AACxD,MAAI,GAAA,CAAA,SAAA,CAAU,iBAAiBA,8BAAsB,CAAA;AACrD,MAAI,GAAA,CAAA,IAAA,CAAK,aAAa,gBAAgB,CAAA;AAAA,KACjC,MAAA;AACL,MAAA,GAAA,CAAI,QAAS,CAAAf,YAAA,CAAY,OAAS,EAAA,YAAY,CAAG,EAAA;AAAA,QAC/C,OAAS,EAAA;AAAA;AAAA;AAAA,UAGP,eAAiB,EAAAe;AAAA;AACnB,OACD,CAAA;AAAA;AACH,GACD,CAAA;AAED,EAAO,OAAA,MAAA;AACT;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/plugin-app-backend",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "A Backstage backend plugin that serves the Backstage frontend app",
|
|
5
5
|
"backstage": {
|
|
6
6
|
"role": "backend-plugin",
|
|
@@ -90,7 +90,7 @@
|
|
|
90
90
|
"@backstage/backend-app-api": "^1.0.2",
|
|
91
91
|
"@backstage/backend-defaults": "^0.5.3",
|
|
92
92
|
"@backstage/backend-test-utils": "^1.1.0",
|
|
93
|
-
"@backstage/cli": "^0.29.
|
|
93
|
+
"@backstage/cli": "^0.29.1",
|
|
94
94
|
"@backstage/types": "^1.2.0",
|
|
95
95
|
"@types/supertest": "^2.0.8",
|
|
96
96
|
"node-fetch": "^2.7.0",
|