@kne/fastify-app-manager 0.1.33 → 0.1.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/libs/controllers/link.js +2 -1
- package/libs/models/app.js +8 -4
- package/libs/services/app.js +70 -32
- package/libs/services/bootstrap.js +31 -0
- package/libs/services/link.js +30 -2
- package/libs/utils/remoteIcon.js +142 -0
- package/package.json +1 -1
- package/sql/host-upgrade-app-soft-delete-unique.sql +41 -0
package/README.md
CHANGED
|
@@ -207,6 +207,7 @@ await fastify.listen({ port: 3000 });
|
|
|
207
207
|
| `getOpenApiToken` | function | 否 | `null` | `async app => accessToken`,签发读取子应用 `/open-api.json` 的服务令牌;未配置时 `GET .../app/open-api` 返回 400。接 OIDC 时传 `appOidc.getOpenApiToken` |
|
|
208
208
|
| `issueUserAccessToken` | function | 否 | `null` | `async ({ app, userId, tenantId }) => accessToken`,以登录用户身份签发子应用令牌;未配置时 `POST .../app/open-api/token` 返回 400。接 OIDC 时传 `appOidc.issueUserAccessToken` |
|
|
209
209
|
| `resolveVersionFile` | function | 否 | `null` | `async ({ fileId, name, version, request }) => Buffer`,版本上传传 `fileId`(而非 multipart 文件)时调用,返回 zip 内容;未配置时传 `fileId` 返回 400。版本记录保存 `fileId`;这类版本只在当前部署时常驻磁盘,部署非当前版本或启动时当前版本目录缺失会再次调用以重建 |
|
|
210
|
+
| `saveIconFile` | function | 否 | `null` | `async ({ buffer, filename, mimetype }) => fileId`,凭 installKey 关联外部应用(`POST .../app/link/import`)且未传 `icon` 时,平台从远程应用站点抓取 favicon / manifest 图标,经此回调存入宿主文件系统并返回文件 id,写入应用 `icon`。未配置则不抓取;抓取或保存失败只记告警,不阻断关联 |
|
|
210
211
|
| `defaultAppDb` | object | 否 | `appsRoot/_shared/apps-data.sqlite` | 托管应用默认库(须与宿主主库分离) |
|
|
211
212
|
| `dbQueryMaxRows` | number | 否 | `500` | 只读 query SQL 最大返回行数 |
|
|
212
213
|
| `pm2Defaults` | object | 否 | 见下表 | 全局 PM2 默认;可被应用 `pm2Config` 覆盖 |
|
|
@@ -920,7 +921,7 @@ data: {"name":"demo","ts":1791456608533,...}
|
|
|
920
921
|
| 方法签名 | 说明 |
|
|
921
922
|
|----------|------|
|
|
922
923
|
| `onReady()` | `ensureSchema` 后连接 PM2、挂 log bus、启动日志切分与负载采样定时器,并 **setImmediate** 异步执行 `recoverOnStartup`,以及一次 `rotateLogs` 与一次 `sampleLoad`(不阻塞父应用 ready) |
|
|
923
|
-
| `ensureSchema()` | 宿主 `sync()` 不给已有表加列:为老库补齐后续新增列/可空约束(含 `app.kind`、`appVersion.fileId|migrationFiles|envSchema`、`appOpenApiRecord.searchText`,并把 `port/rootPath/pm2Name`
|
|
924
|
+
| `ensureSchema()` | 宿主 `sync()` 不给已有表加列:为老库补齐后续新增列/可空约束(含 `app.kind`、`appVersion.fileId|migrationFiles|envSchema`、`appOpenApiRecord.searchText`,并把 `port/rootPath/pm2Name` 改为可空);postgres 下将 `name/domain/pm2_name` 唯一约束改为 `WHERE deleted_at IS NULL` 部分唯一索引(软删后可同名重建),可重复执行;插件 `after` 与 `onReady` 都会调用。离线补齐见包内 `sql/host-upgrade-linked-kind.sql`、`sql/host-upgrade-app-soft-delete-unique.sql` |
|
|
924
925
|
| `recoverOnStartup()` | 两路并行:部署目录完好的应用立即 `reconcile`;目录缺失的应用逐个 `restoreArtifact`(需重装依赖,较慢),每补完一个即单独 `syncStatus` 并按需拉起;补不回且原为 `running`/`deploying` 的标记 `error`;两路结束后 `pruneAllVersionArtifacts`。返回 `{ reconciled, restored, pruned }` |
|
|
925
926
|
| `onClose()` | 停止切分与采样定时器并等待进行中的任务,断开 bus / PM2(由插件 `onClose` 调用) |
|
|
926
927
|
| `rotateLogs({ now? })` | 立即执行一轮切分 + 压缩 + 保留清理;返回本轮切分的 `[{ name, stream, fileName, reason }]`,`reason` 为 `size` / `daily` |
|
package/libs/controllers/link.js
CHANGED
|
@@ -21,7 +21,8 @@ module.exports = fp(async (fastify, options) => {
|
|
|
21
21
|
properties: {
|
|
22
22
|
installKey: { type: 'string', description: '远程一次性安装密钥(base64url JSON)' },
|
|
23
23
|
name: { type: 'string', description: '可选覆盖应用 slug;默认取 key 内 appName' },
|
|
24
|
-
label: { type: 'string', description: '可选覆盖显示名' }
|
|
24
|
+
label: { type: 'string', description: '可选覆盖显示名' },
|
|
25
|
+
icon: { type: 'string', description: '可选应用图标(文件 id);未传时从远程应用站点抓取 favicon/manifest 图标并经 saveIconFile 保存,抓取失败则不设置图标' }
|
|
25
26
|
}
|
|
26
27
|
},
|
|
27
28
|
response: success('导入后的应用', obj({ name: str('应用 name'), kind: str('managed|linked'), status: str('状态') }))
|
package/libs/models/app.js
CHANGED
|
@@ -5,7 +5,6 @@ module.exports = ({ DataTypes }) => {
|
|
|
5
5
|
name: {
|
|
6
6
|
type: DataTypes.STRING,
|
|
7
7
|
allowNull: false,
|
|
8
|
-
unique: true,
|
|
9
8
|
comment: '应用 slug / appId'
|
|
10
9
|
},
|
|
11
10
|
label: {
|
|
@@ -22,7 +21,6 @@ module.exports = ({ DataTypes }) => {
|
|
|
22
21
|
domain: {
|
|
23
22
|
type: DataTypes.STRING,
|
|
24
23
|
allowNull: true,
|
|
25
|
-
unique: true,
|
|
26
24
|
comment: '绑定域名 Host;linked 必须为空'
|
|
27
25
|
},
|
|
28
26
|
icon: {
|
|
@@ -77,7 +75,6 @@ module.exports = ({ DataTypes }) => {
|
|
|
77
75
|
pm2Name: {
|
|
78
76
|
type: DataTypes.STRING,
|
|
79
77
|
allowNull: true,
|
|
80
|
-
unique: true,
|
|
81
78
|
comment: 'PM2 进程名;linked 可空'
|
|
82
79
|
},
|
|
83
80
|
message: {
|
|
@@ -88,7 +85,14 @@ module.exports = ({ DataTypes }) => {
|
|
|
88
85
|
},
|
|
89
86
|
options: {
|
|
90
87
|
comment: '托管应用',
|
|
91
|
-
indexes: [
|
|
88
|
+
indexes: [
|
|
89
|
+
{ fields: ['status'] },
|
|
90
|
+
{ fields: ['kind'] },
|
|
91
|
+
// 软删行不占唯一键:删除后可同名重建(须配合 ensureSchema / 迁移丢掉旧的 *_key)
|
|
92
|
+
{ name: 'app_name_active_uk', unique: true, fields: ['name'], where: { deleted_at: null } },
|
|
93
|
+
{ name: 'app_domain_active_uk', unique: true, fields: ['domain'], where: { deleted_at: null } },
|
|
94
|
+
{ name: 'app_pm2_name_active_uk', unique: true, fields: ['pm2_name'], where: { deleted_at: null } }
|
|
95
|
+
]
|
|
92
96
|
}
|
|
93
97
|
};
|
|
94
98
|
};
|
package/libs/services/app.js
CHANGED
|
@@ -64,16 +64,46 @@ module.exports = fp(async (fastify, options) => {
|
|
|
64
64
|
}
|
|
65
65
|
return category.code ? { code: category.code, name: category.name || category.code } : null;
|
|
66
66
|
};
|
|
67
|
+
/**
|
|
68
|
+
* 入口 path 一律相对应用根入库。
|
|
69
|
+
* 详情/中心列表若曾把绝对 url 写回 options.entries,或出现 /http://… 脏数据,这里剥成 pathname,避免与 baseUrl 重复拼接。
|
|
70
|
+
*/
|
|
71
|
+
const toRelativeEntryPath = raw => {
|
|
72
|
+
let path = String(raw || '').trim();
|
|
73
|
+
if (!path) {
|
|
74
|
+
return '';
|
|
75
|
+
}
|
|
76
|
+
for (let i = 0; i < 8; i += 1) {
|
|
77
|
+
if (/^https?:\/\//i.test(path)) {
|
|
78
|
+
try {
|
|
79
|
+
const u = new URL(path);
|
|
80
|
+
path = `${u.pathname || '/'}${u.search || ''}${u.hash || ''}` || '/';
|
|
81
|
+
continue;
|
|
82
|
+
} catch (e) {
|
|
83
|
+
return '';
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (/^\/https?:\/\//i.test(path)) {
|
|
87
|
+
path = path.slice(1);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
if (!path.startsWith('/')) {
|
|
93
|
+
path = `/${path}`;
|
|
94
|
+
}
|
|
95
|
+
return path;
|
|
96
|
+
};
|
|
97
|
+
|
|
67
98
|
// 应用入口:label + 相对应用根的 path;去空、补前导 /、按 path 去重;showInCenter 未设置视为开放给前台
|
|
68
99
|
const normalizeEntries = entries => {
|
|
69
100
|
const seen = new Set();
|
|
70
101
|
return (Array.isArray(entries) ? entries : []).reduce((result, item) => {
|
|
71
102
|
const label = String(item?.label || '').trim();
|
|
72
|
-
const
|
|
73
|
-
if (!label || !
|
|
103
|
+
const entryPath = toRelativeEntryPath(item?.path);
|
|
104
|
+
if (!label || !entryPath) {
|
|
74
105
|
return result;
|
|
75
106
|
}
|
|
76
|
-
const entryPath = rawPath.startsWith('/') ? rawPath : `/${rawPath}`;
|
|
77
107
|
if (!seen.has(entryPath)) {
|
|
78
108
|
seen.add(entryPath);
|
|
79
109
|
result.push({ label, path: entryPath, showInCenter: item?.showInCenter !== false });
|
|
@@ -98,9 +128,10 @@ module.exports = fp(async (fastify, options) => {
|
|
|
98
128
|
const remote = linked ? linkedBaseUrl(appLike) : null;
|
|
99
129
|
const base = remote || mountPrefix(appLike.name);
|
|
100
130
|
return normalizeEntries(appLike.options?.entries).map(entry => {
|
|
101
|
-
|
|
102
|
-
const
|
|
103
|
-
|
|
131
|
+
// path 始终相对,仅 url 拼绝对;linked 若把 path 改成绝对再经 save 回写会与 baseUrl 叠成 http://host/http://host/...
|
|
132
|
+
const pathPart = entry.path;
|
|
133
|
+
const url = `${String(base).replace(/\/+$/, '')}${pathPart}`;
|
|
134
|
+
return Object.assign({}, entry, { path: pathPart, url });
|
|
104
135
|
});
|
|
105
136
|
};
|
|
106
137
|
|
|
@@ -185,22 +216,30 @@ module.exports = fp(async (fastify, options) => {
|
|
|
185
216
|
normalizedOptions.homePath = '/';
|
|
186
217
|
}
|
|
187
218
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
219
|
+
let app;
|
|
220
|
+
try {
|
|
221
|
+
app = await models.app.create({
|
|
222
|
+
name,
|
|
223
|
+
label,
|
|
224
|
+
kind: KIND_MANAGED,
|
|
225
|
+
domain: domain || null,
|
|
226
|
+
icon: icon || null,
|
|
227
|
+
description: description || null,
|
|
228
|
+
env: omitSystemEnv(env, options.systemEnvKeys),
|
|
229
|
+
pm2Config: pm2Config || {},
|
|
230
|
+
options: normalizedOptions,
|
|
231
|
+
port,
|
|
232
|
+
status: 'idle',
|
|
233
|
+
rootPath,
|
|
234
|
+
pm2Name: createPm2Name(options.hostName, name),
|
|
235
|
+
message: null
|
|
236
|
+
});
|
|
237
|
+
} catch (e) {
|
|
238
|
+
if (e.name === 'SequelizeUniqueConstraintError') {
|
|
239
|
+
httpError(409, `app ${name} already exists`);
|
|
240
|
+
}
|
|
241
|
+
throw e;
|
|
242
|
+
}
|
|
204
243
|
return toPublicApp(app);
|
|
205
244
|
};
|
|
206
245
|
|
|
@@ -298,15 +337,7 @@ module.exports = fp(async (fastify, options) => {
|
|
|
298
337
|
const linked = isLinked(app);
|
|
299
338
|
const base = linked ? linkedBaseUrl(app) : null;
|
|
300
339
|
const pathUrl = linked && base ? `${base}/` : `${mountPrefix(app.name)}/`;
|
|
301
|
-
const entries = resolveEntries(app)
|
|
302
|
-
.filter(entry => entry.showInCenter)
|
|
303
|
-
.map(entry =>
|
|
304
|
-
linked && base
|
|
305
|
-
? Object.assign({}, entry, {
|
|
306
|
-
path: entry.path.startsWith('http') ? entry.path : `${base}${entry.path.startsWith('/') ? '' : '/'}${entry.path}`
|
|
307
|
-
})
|
|
308
|
-
: entry
|
|
309
|
-
);
|
|
340
|
+
const entries = resolveEntries(app).filter(entry => entry.showInCenter);
|
|
310
341
|
return {
|
|
311
342
|
name: app.name,
|
|
312
343
|
label: app.label,
|
|
@@ -1068,7 +1099,14 @@ module.exports = fp(async (fastify, options) => {
|
|
|
1068
1099
|
/** 只做 fs 检查:返回当前版本目录(artifactPath/server)缺失的应用 */
|
|
1069
1100
|
const listMissingArtifacts = async () => {
|
|
1070
1101
|
const { Op } = fastify.sequelize.Sequelize;
|
|
1071
|
-
|
|
1102
|
+
// 恢复按创建顺序排队:不指定 order 时顺序取决于库的查询计划/索引,改索引后会变
|
|
1103
|
+
const apps = await models.app.findAll({
|
|
1104
|
+
where: { currentVersionId: { [Op.ne]: null } },
|
|
1105
|
+
order: [
|
|
1106
|
+
['createdAt', 'ASC'],
|
|
1107
|
+
['id', 'ASC']
|
|
1108
|
+
]
|
|
1109
|
+
});
|
|
1072
1110
|
const missing = [];
|
|
1073
1111
|
for (const app of apps) {
|
|
1074
1112
|
if (isLinked(app)) {
|
|
@@ -87,6 +87,37 @@ module.exports = fp(async (fastify, options) => {
|
|
|
87
87
|
await queryInterface.addIndex(table, [kindAttr.field], { name: indexName });
|
|
88
88
|
}
|
|
89
89
|
}
|
|
90
|
+
|
|
91
|
+
// 软删不占唯一键:去掉字段级 UNIQUE 约束,改为 WHERE deleted_at IS NULL 的部分唯一索引。
|
|
92
|
+
// sequelize sync 不会 DROP 旧 *_key;须在此幂等迁移(仅 postgres;MySQL 不支持部分索引)。
|
|
93
|
+
const dialect = models.app.sequelize.getDialect();
|
|
94
|
+
if (dialect === 'postgres') {
|
|
95
|
+
const qi = models.app.sequelize.getQueryInterface();
|
|
96
|
+
const quoted = `"${String(tableName).replace(/"/g, '""')}"`;
|
|
97
|
+
for (const col of ['name', 'domain', 'pm2_name']) {
|
|
98
|
+
await models.app.sequelize.query(`ALTER TABLE ${quoted} DROP CONSTRAINT IF EXISTS "${tableName}_${col}_key"`);
|
|
99
|
+
}
|
|
100
|
+
// 顺带去掉旧的非唯一 domain 索引(若仍存在)
|
|
101
|
+
await models.app.sequelize.query(`DROP INDEX IF EXISTS "${tableName}_domain"`);
|
|
102
|
+
|
|
103
|
+
const activeIndexes = [
|
|
104
|
+
{ name: `${tableName}_name_active_uk`, fields: ['name'] },
|
|
105
|
+
{ name: `${tableName}_domain_active_uk`, fields: ['domain'] },
|
|
106
|
+
{ name: `${tableName}_pm2_name_active_uk`, fields: ['pm2_name'] }
|
|
107
|
+
];
|
|
108
|
+
const indexes = await qi.showIndex(table);
|
|
109
|
+
for (const item of activeIndexes) {
|
|
110
|
+
const exists = (indexes || []).some(row => row.name === item.name);
|
|
111
|
+
if (exists) {
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
await qi.addIndex(table, item.fields, {
|
|
115
|
+
name: item.name,
|
|
116
|
+
unique: true,
|
|
117
|
+
where: { deleted_at: null }
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
}
|
|
90
121
|
};
|
|
91
122
|
|
|
92
123
|
const onReady = async () => {
|
package/libs/services/link.js
CHANGED
|
@@ -2,6 +2,7 @@ const fp = require('fastify-plugin');
|
|
|
2
2
|
const { KIND_LINKED, isLinked, linkedBaseUrl, linkedApiBaseUrl } = require('../utils/appKind');
|
|
3
3
|
const { mergeAppPermissionTree } = require('../utils/permissionSnapshot');
|
|
4
4
|
const { createProxyAuditStore } = require('../utils/proxyAudit');
|
|
5
|
+
const { discoverRemoteIcon } = require('../utils/remoteIcon');
|
|
5
6
|
const { SYSTEM_ENV_KEYS, DB_CONNECTION_KEYS, DB_DEDICATED_KEY } = require('../utils/env');
|
|
6
7
|
|
|
7
8
|
const NAME_RE = /^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/;
|
|
@@ -200,10 +201,36 @@ module.exports = fp(async (fastify, options) => {
|
|
|
200
201
|
return name;
|
|
201
202
|
};
|
|
202
203
|
|
|
204
|
+
/**
|
|
205
|
+
* 图标优先级:用户上传(文件 id)> 远程 manifest 给的 icon > 从远程前端站点抓取并经宿主 saveIconFile 存入文件系统。
|
|
206
|
+
* 抓取/保存失败只记告警,不阻断关联。
|
|
207
|
+
*/
|
|
208
|
+
const resolveLinkedIcon = async ({ icon, manifestIcon, baseUrl }) => {
|
|
209
|
+
if (icon) {
|
|
210
|
+
return icon;
|
|
211
|
+
}
|
|
212
|
+
if (manifestIcon) {
|
|
213
|
+
return manifestIcon;
|
|
214
|
+
}
|
|
215
|
+
if (typeof options.saveIconFile !== 'function') {
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
try {
|
|
219
|
+
const found = await discoverRemoteIcon({ baseUrl, timeoutMs: options.linkIconTimeoutMs });
|
|
220
|
+
if (!found) {
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
return (await options.saveIconFile(found)) || null;
|
|
224
|
+
} catch (e) {
|
|
225
|
+
fastify.log.warn({ err: e, baseUrl }, 'linked app icon fetch/save failed');
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
|
|
203
230
|
/**
|
|
204
231
|
* 凭 installKey 导入外部应用:redeem → 建 linked 记录 → OIDC → activate
|
|
205
232
|
*/
|
|
206
|
-
const importByInstallKey = async ({ installKey, name: overrideName, label: overrideLabel } = {}) => {
|
|
233
|
+
const importByInstallKey = async ({ installKey, name: overrideName, label: overrideLabel, icon: overrideIcon } = {}) => {
|
|
207
234
|
if (!installKey) {
|
|
208
235
|
httpError(400, 'installKey 必填');
|
|
209
236
|
}
|
|
@@ -250,13 +277,14 @@ module.exports = fp(async (fastify, options) => {
|
|
|
250
277
|
const manifest = redeemed.data || {};
|
|
251
278
|
const label = overrideLabel || manifest.label || key.appLabel || name;
|
|
252
279
|
const entries = Array.isArray(manifest.entries) ? manifest.entries : [{ label: '首页', path: '/', showInCenter: true }];
|
|
280
|
+
const icon = await resolveLinkedIcon({ icon: overrideIcon, manifestIcon: manifest.icon, baseUrl });
|
|
253
281
|
|
|
254
282
|
const app = await models.app.create({
|
|
255
283
|
name,
|
|
256
284
|
label,
|
|
257
285
|
kind: KIND_LINKED,
|
|
258
286
|
domain: null,
|
|
259
|
-
icon
|
|
287
|
+
icon,
|
|
260
288
|
description: manifest.description || null,
|
|
261
289
|
env: {},
|
|
262
290
|
pm2Config: {},
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
const MAX_ICON_BYTES = 1024 * 1024;
|
|
2
|
+
const MAX_CANDIDATES = 6;
|
|
3
|
+
|
|
4
|
+
const MIME_EXT = {
|
|
5
|
+
'image/png': 'png',
|
|
6
|
+
'image/jpeg': 'jpg',
|
|
7
|
+
'image/gif': 'gif',
|
|
8
|
+
'image/webp': 'webp',
|
|
9
|
+
'image/svg+xml': 'svg',
|
|
10
|
+
'image/x-icon': 'ico',
|
|
11
|
+
'image/vnd.microsoft.icon': 'ico'
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
const attrOf = (tag, name) => {
|
|
15
|
+
const match = tag.match(new RegExp(`\\s${name}\\s*=\\s*("([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i'));
|
|
16
|
+
return match ? (match[2] ?? match[3] ?? match[4]) : null;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** sizes="192x192" / "48x48 96x96" 取最大边;any / 缺省按 0 */
|
|
20
|
+
const sizeOf = sizes => {
|
|
21
|
+
const values = String(sizes || '')
|
|
22
|
+
.split(/\s+/)
|
|
23
|
+
.map(item => parseInt(item.split('x')[0], 10))
|
|
24
|
+
.filter(Number.isFinite);
|
|
25
|
+
return values.length ? Math.max(...values) : 0;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const bySizeDesc = (a, b) => b.size - a.size;
|
|
29
|
+
|
|
30
|
+
/** 从首页 HTML 解析 <link rel=icon|apple-touch-icon|manifest>,已按优先级排序 */
|
|
31
|
+
const parseHtmlIcons = (html, pageUrl) => {
|
|
32
|
+
const icons = [];
|
|
33
|
+
let manifestUrl = null;
|
|
34
|
+
for (const tag of String(html || '').match(/<link\b[^>]*>/gi) || []) {
|
|
35
|
+
const rel = String(attrOf(tag, 'rel') || '').toLowerCase();
|
|
36
|
+
const href = attrOf(tag, 'href');
|
|
37
|
+
if (!href) {
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
let url;
|
|
41
|
+
try {
|
|
42
|
+
url = new URL(href, pageUrl).href;
|
|
43
|
+
} catch (e) {
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (/\bmanifest\b/.test(rel)) {
|
|
47
|
+
manifestUrl = url;
|
|
48
|
+
} else if (/\bapple-touch-icon(-precomposed)?\b/.test(rel)) {
|
|
49
|
+
icons.push({ url, size: sizeOf(attrOf(tag, 'sizes')), touch: true });
|
|
50
|
+
} else if (/\bicon\b/.test(rel)) {
|
|
51
|
+
icons.push({ url, size: sizeOf(attrOf(tag, 'sizes')), touch: false });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const touch = icons.filter(item => item.touch).sort(bySizeDesc);
|
|
55
|
+
const normal = icons.filter(item => !item.touch).sort(bySizeDesc);
|
|
56
|
+
return { icons: [...touch, ...normal].map(item => item.url), manifestUrl };
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const parseManifestIcons = (manifest, manifestUrl) =>
|
|
60
|
+
(Array.isArray(manifest?.icons) ? manifest.icons : [])
|
|
61
|
+
.filter(item => item && item.src)
|
|
62
|
+
.map(item => {
|
|
63
|
+
try {
|
|
64
|
+
return { url: new URL(item.src, manifestUrl).href, size: sizeOf(item.sizes) };
|
|
65
|
+
} catch (e) {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
})
|
|
69
|
+
.filter(Boolean)
|
|
70
|
+
.sort(bySizeDesc)
|
|
71
|
+
.map(item => item.url);
|
|
72
|
+
|
|
73
|
+
const filenameOf = (url, mimetype) => {
|
|
74
|
+
const base = decodeURIComponent(new URL(url).pathname.split('/').pop() || '');
|
|
75
|
+
if (/\.[a-z0-9]{2,5}$/i.test(base)) {
|
|
76
|
+
return base;
|
|
77
|
+
}
|
|
78
|
+
return `icon.${MIME_EXT[mimetype] || 'png'}`;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 从远程应用前端站点获取图标:首页 <link rel=icon/apple-touch-icon> → web manifest icons → /favicon.ico
|
|
83
|
+
* 只接受 image/* 且不超过 1MB 的响应(SPA 对未知路径回落 HTML 的会被丢弃)。
|
|
84
|
+
* 失败返回 null,不抛错。
|
|
85
|
+
*/
|
|
86
|
+
const discoverRemoteIcon = async ({ baseUrl, timeoutMs = 5000, fetchImpl = fetch } = {}) => {
|
|
87
|
+
const base = String(baseUrl || '').replace(/\/+$/, '');
|
|
88
|
+
if (!/^https?:\/\//i.test(base)) {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
const request = async (url, accept) => {
|
|
92
|
+
const response = await fetchImpl(url, { headers: { accept }, signal: AbortSignal.timeout(timeoutMs) });
|
|
93
|
+
return response.ok ? response : null;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const candidates = [];
|
|
97
|
+
const pageUrl = `${base}/`;
|
|
98
|
+
try {
|
|
99
|
+
const page = await request(pageUrl, 'text/html');
|
|
100
|
+
if (page) {
|
|
101
|
+
const { icons, manifestUrl } = parseHtmlIcons(await page.text(), pageUrl);
|
|
102
|
+
candidates.push(...icons);
|
|
103
|
+
if (manifestUrl) {
|
|
104
|
+
try {
|
|
105
|
+
const manifestRes = await request(manifestUrl, 'application/manifest+json,application/json');
|
|
106
|
+
candidates.push(...parseManifestIcons(manifestRes ? await manifestRes.json() : null, manifestUrl));
|
|
107
|
+
} catch (e) {
|
|
108
|
+
// manifest 取不到不影响后续候选
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
} catch (e) {
|
|
113
|
+
// 首页取不到,退回 /favicon.ico
|
|
114
|
+
}
|
|
115
|
+
candidates.push(`${base}/favicon.ico`);
|
|
116
|
+
|
|
117
|
+
for (const url of [...new Set(candidates)].slice(0, MAX_CANDIDATES)) {
|
|
118
|
+
try {
|
|
119
|
+
const response = await request(url, 'image/*');
|
|
120
|
+
if (!response) {
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
const mimetype = String(response.headers.get('content-type') || '')
|
|
124
|
+
.split(';')[0]
|
|
125
|
+
.trim()
|
|
126
|
+
.toLowerCase();
|
|
127
|
+
if (!mimetype.startsWith('image/')) {
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
const buffer = Buffer.from(await response.arrayBuffer());
|
|
131
|
+
if (!buffer.length || buffer.length > MAX_ICON_BYTES) {
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
return { buffer, mimetype, filename: filenameOf(url, mimetype) };
|
|
135
|
+
} catch (e) {
|
|
136
|
+
// 换下一个候选
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
module.exports = { discoverRemoteIcon, parseHtmlIcons, parseManifestIcons };
|
package/package.json
CHANGED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
-- 宿主库升级脚本(可选):软删行不再占用 name/domain/pm2_name 唯一键。
|
|
2
|
+
-- 默认表前缀 t_app_manager_;若宿主传了 dbTableNamePrefix / DB_TABLE_PREFIX,请改表名。
|
|
3
|
+
-- 幂等。仅 PostgreSQL(部分唯一索引)。对应 @kne/fastify-app-manager libs/models/app.js
|
|
4
|
+
-- 也可由 bootstrap.ensureSchema 在启动时自动执行。
|
|
5
|
+
|
|
6
|
+
DO $$
|
|
7
|
+
BEGIN
|
|
8
|
+
IF EXISTS (
|
|
9
|
+
SELECT 1 FROM information_schema.tables
|
|
10
|
+
WHERE table_schema = 'public' AND table_name = 't_app_manager_app'
|
|
11
|
+
) THEN
|
|
12
|
+
ALTER TABLE t_app_manager_app DROP CONSTRAINT IF EXISTS t_app_manager_app_name_key;
|
|
13
|
+
ALTER TABLE t_app_manager_app DROP CONSTRAINT IF EXISTS t_app_manager_app_domain_key;
|
|
14
|
+
ALTER TABLE t_app_manager_app DROP CONSTRAINT IF EXISTS t_app_manager_app_pm2_name_key;
|
|
15
|
+
DROP INDEX IF EXISTS t_app_manager_app_domain;
|
|
16
|
+
|
|
17
|
+
IF NOT EXISTS (
|
|
18
|
+
SELECT 1 FROM pg_indexes
|
|
19
|
+
WHERE schemaname = 'public' AND indexname = 't_app_manager_app_name_active_uk'
|
|
20
|
+
) THEN
|
|
21
|
+
CREATE UNIQUE INDEX t_app_manager_app_name_active_uk
|
|
22
|
+
ON t_app_manager_app (name) WHERE deleted_at IS NULL;
|
|
23
|
+
END IF;
|
|
24
|
+
|
|
25
|
+
IF NOT EXISTS (
|
|
26
|
+
SELECT 1 FROM pg_indexes
|
|
27
|
+
WHERE schemaname = 'public' AND indexname = 't_app_manager_app_domain_active_uk'
|
|
28
|
+
) THEN
|
|
29
|
+
CREATE UNIQUE INDEX t_app_manager_app_domain_active_uk
|
|
30
|
+
ON t_app_manager_app (domain) WHERE deleted_at IS NULL;
|
|
31
|
+
END IF;
|
|
32
|
+
|
|
33
|
+
IF NOT EXISTS (
|
|
34
|
+
SELECT 1 FROM pg_indexes
|
|
35
|
+
WHERE schemaname = 'public' AND indexname = 't_app_manager_app_pm2_name_active_uk'
|
|
36
|
+
) THEN
|
|
37
|
+
CREATE UNIQUE INDEX t_app_manager_app_pm2_name_active_uk
|
|
38
|
+
ON t_app_manager_app (pm2_name) WHERE deleted_at IS NULL;
|
|
39
|
+
END IF;
|
|
40
|
+
END IF;
|
|
41
|
+
END $$;
|