@kne/fastify-app-manager 0.1.35 → 0.1.37
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 -2
- package/libs/models/app.js +8 -4
- package/libs/services/app.js +70 -32
- package/libs/services/bootstrap.js +31 -0
- package/libs/utils/remoteIcon.js +99 -39
- package/package.json +1 -1
- package/sql/host-upgrade-app-soft-delete-unique.sql +41 -0
package/README.md
CHANGED
|
@@ -207,7 +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`
|
|
210
|
+
| `saveIconFile` | function | 否 | `null` | `async ({ buffer, filename, mimetype }) => fileId`,凭 installKey 关联外部应用(`POST .../app/link/import`)且未传 `icon` 时,平台从远程应用站点收集 favicon / apple-touch-icon / manifest 图标,按真实像素取最大的一张,经此回调存入宿主文件系统并返回文件 id,写入应用 `icon`。未配置则不抓取;抓取或保存失败只记告警,不阻断关联 |
|
|
211
211
|
| `defaultAppDb` | object | 否 | `appsRoot/_shared/apps-data.sqlite` | 托管应用默认库(须与宿主主库分离) |
|
|
212
212
|
| `dbQueryMaxRows` | number | 否 | `500` | 只读 query SQL 最大返回行数 |
|
|
213
213
|
| `pm2Defaults` | object | 否 | 见下表 | 全局 PM2 默认;可被应用 `pm2Config` 覆盖 |
|
|
@@ -921,7 +921,7 @@ data: {"name":"demo","ts":1791456608533,...}
|
|
|
921
921
|
| 方法签名 | 说明 |
|
|
922
922
|
|----------|------|
|
|
923
923
|
| `onReady()` | `ensureSchema` 后连接 PM2、挂 log bus、启动日志切分与负载采样定时器,并 **setImmediate** 异步执行 `recoverOnStartup`,以及一次 `rotateLogs` 与一次 `sampleLoad`(不阻塞父应用 ready) |
|
|
924
|
-
| `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` |
|
|
925
925
|
| `recoverOnStartup()` | 两路并行:部署目录完好的应用立即 `reconcile`;目录缺失的应用逐个 `restoreArtifact`(需重装依赖,较慢),每补完一个即单独 `syncStatus` 并按需拉起;补不回且原为 `running`/`deploying` 的标记 `error`;两路结束后 `pruneAllVersionArtifacts`。返回 `{ reconciled, restored, pruned }` |
|
|
926
926
|
| `onClose()` | 停止切分与采样定时器并等待进行中的任务,断开 bus / PM2(由插件 `onClose` 调用) |
|
|
927
927
|
| `rotateLogs({ now? })` | 立即执行一轮切分 + 压缩 + 保留清理;返回本轮切分的 `[{ name, stream, fileName, reason }]`,`reason` 为 `size` / `daily` |
|
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/utils/remoteIcon.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
const MAX_ICON_BYTES = 1024 * 1024;
|
|
2
|
-
const MAX_CANDIDATES =
|
|
2
|
+
const MAX_CANDIDATES = 8;
|
|
3
|
+
// SVG 没有固有像素尺寸,按一个中等值参与比较:有更大的位图时用位图,否则矢量图也比一张很小的位图好
|
|
4
|
+
const SVG_NOMINAL_SIZE = 256;
|
|
3
5
|
|
|
4
6
|
const MIME_EXT = {
|
|
5
7
|
'image/png': 'png',
|
|
@@ -25,11 +27,10 @@ const sizeOf = sizes => {
|
|
|
25
27
|
return values.length ? Math.max(...values) : 0;
|
|
26
28
|
};
|
|
27
29
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
/** 从首页 HTML 解析 <link rel=icon|apple-touch-icon|manifest>,已按优先级排序 */
|
|
30
|
+
/** 从首页 HTML 解析 <link rel=icon|apple-touch-icon|manifest>,返回候选 [{ url, size }] 与 manifest 地址 */
|
|
31
31
|
const parseHtmlIcons = (html, pageUrl) => {
|
|
32
|
-
const
|
|
32
|
+
const touch = [];
|
|
33
|
+
const normal = [];
|
|
33
34
|
let manifestUrl = null;
|
|
34
35
|
for (const tag of String(html || '').match(/<link\b[^>]*>/gi) || []) {
|
|
35
36
|
const rel = String(attrOf(tag, 'rel') || '').toLowerCase();
|
|
@@ -46,29 +47,80 @@ const parseHtmlIcons = (html, pageUrl) => {
|
|
|
46
47
|
if (/\bmanifest\b/.test(rel)) {
|
|
47
48
|
manifestUrl = url;
|
|
48
49
|
} else if (/\bapple-touch-icon(-precomposed)?\b/.test(rel)) {
|
|
49
|
-
|
|
50
|
+
touch.push({ url, size: sizeOf(attrOf(tag, 'sizes')) });
|
|
50
51
|
} else if (/\bicon\b/.test(rel)) {
|
|
51
|
-
|
|
52
|
+
normal.push({ url, size: sizeOf(attrOf(tag, 'sizes')) });
|
|
52
53
|
}
|
|
53
54
|
}
|
|
54
|
-
|
|
55
|
-
const normal = icons.filter(item => !item.touch).sort(bySizeDesc);
|
|
56
|
-
return { icons: [...touch, ...normal].map(item => item.url), manifestUrl };
|
|
55
|
+
return { icons: [...touch, ...normal], manifestUrl };
|
|
57
56
|
};
|
|
58
57
|
|
|
58
|
+
/** manifest icons → 候选 [{ url, size, maskable }];maskable 图带安全边距,同尺寸时排在普通图之后 */
|
|
59
59
|
const parseManifestIcons = (manifest, manifestUrl) =>
|
|
60
60
|
(Array.isArray(manifest?.icons) ? manifest.icons : [])
|
|
61
61
|
.filter(item => item && item.src)
|
|
62
62
|
.map(item => {
|
|
63
63
|
try {
|
|
64
|
-
|
|
64
|
+
const purposes = String(item.purpose || 'any')
|
|
65
|
+
.toLowerCase()
|
|
66
|
+
.split(/\s+/);
|
|
67
|
+
return { url: new URL(item.src, manifestUrl).href, size: sizeOf(item.sizes), maskable: purposes.includes('maskable') && !purposes.includes('any') };
|
|
65
68
|
} catch (e) {
|
|
66
69
|
return null;
|
|
67
70
|
}
|
|
68
71
|
})
|
|
69
|
-
.filter(Boolean)
|
|
70
|
-
|
|
71
|
-
|
|
72
|
+
.filter(Boolean);
|
|
73
|
+
|
|
74
|
+
/** 读图片头得到真实像素最大边;认不出或没有固有尺寸时返回 0 */
|
|
75
|
+
const imageSize = (buffer, mimetype) => {
|
|
76
|
+
const b = buffer;
|
|
77
|
+
try {
|
|
78
|
+
if (b.length >= 24 && b.readUInt32BE(0) === 0x89504e47 && b.toString('ascii', 12, 16) === 'IHDR') {
|
|
79
|
+
return Math.max(b.readUInt32BE(16), b.readUInt32BE(20));
|
|
80
|
+
}
|
|
81
|
+
if (b.length >= 6 && b.readUInt16LE(0) === 0 && b.readUInt16LE(2) === 1) {
|
|
82
|
+
let max = 0;
|
|
83
|
+
for (let i = 0; i < b.readUInt16LE(4) && 6 + i * 16 + 2 <= b.length; i += 1) {
|
|
84
|
+
max = Math.max(max, b[6 + i * 16] || 256, b[7 + i * 16] || 256);
|
|
85
|
+
}
|
|
86
|
+
return max;
|
|
87
|
+
}
|
|
88
|
+
if (b.length >= 10 && b.toString('ascii', 0, 4) === 'GIF8') {
|
|
89
|
+
return Math.max(b.readUInt16LE(6), b.readUInt16LE(8));
|
|
90
|
+
}
|
|
91
|
+
if (b.length >= 4 && b[0] === 0xff && b[1] === 0xd8) {
|
|
92
|
+
let offset = 2;
|
|
93
|
+
while (offset + 9 < b.length) {
|
|
94
|
+
if (b[offset] !== 0xff) {
|
|
95
|
+
offset += 1;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const marker = b[offset + 1];
|
|
99
|
+
if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
|
|
100
|
+
return Math.max(b.readUInt16BE(offset + 5), b.readUInt16BE(offset + 7));
|
|
101
|
+
}
|
|
102
|
+
offset += 2 + b.readUInt16BE(offset + 2);
|
|
103
|
+
}
|
|
104
|
+
return 0;
|
|
105
|
+
}
|
|
106
|
+
if (b.length >= 30 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') {
|
|
107
|
+
const type = b.toString('ascii', 12, 16);
|
|
108
|
+
if (type === 'VP8X') {
|
|
109
|
+
return Math.max(1 + b.readUIntLE(24, 3), 1 + b.readUIntLE(27, 3));
|
|
110
|
+
}
|
|
111
|
+
if (type === 'VP8L') {
|
|
112
|
+
const bits = b.readUInt32LE(21);
|
|
113
|
+
return Math.max((bits & 0x3fff) + 1, ((bits >> 14) & 0x3fff) + 1);
|
|
114
|
+
}
|
|
115
|
+
if (type === 'VP8 ') {
|
|
116
|
+
return Math.max(b.readUInt16LE(26) & 0x3fff, b.readUInt16LE(28) & 0x3fff);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
} catch (e) {
|
|
120
|
+
return 0;
|
|
121
|
+
}
|
|
122
|
+
return mimetype === 'image/svg+xml' ? SVG_NOMINAL_SIZE : 0;
|
|
123
|
+
};
|
|
72
124
|
|
|
73
125
|
const filenameOf = (url, mimetype) => {
|
|
74
126
|
const base = decodeURIComponent(new URL(url).pathname.split('/').pop() || '');
|
|
@@ -79,7 +131,8 @@ const filenameOf = (url, mimetype) => {
|
|
|
79
131
|
};
|
|
80
132
|
|
|
81
133
|
/**
|
|
82
|
-
* 从远程应用前端站点获取图标:首页 <link rel=icon/apple-touch-icon
|
|
134
|
+
* 从远程应用前端站点获取图标:首页 <link rel=icon/apple-touch-icon>、web manifest icons、/favicon.ico 全部作为候选,
|
|
135
|
+
* 逐个下载后读真实像素尺寸,取最大的一张(站点没声明 sizes 也能比出大小);尺寸相同按 touch > icon > manifest > favicon.ico,普通图优先于 maskable。
|
|
83
136
|
* 只接受 image/* 且不超过 1MB 的响应(SPA 对未知路径回落 HTML 的会被丢弃)。
|
|
84
137
|
* 失败返回 null,不抛错。
|
|
85
138
|
*/
|
|
@@ -112,31 +165,38 @@ const discoverRemoteIcon = async ({ baseUrl, timeoutMs = 5000, fetchImpl = fetch
|
|
|
112
165
|
} catch (e) {
|
|
113
166
|
// 首页取不到,退回 /favicon.ico
|
|
114
167
|
}
|
|
115
|
-
candidates.push(`${base}/favicon.ico
|
|
168
|
+
candidates.push({ url: `${base}/favicon.ico`, size: 0 });
|
|
116
169
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
.
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
170
|
+
const unique = [...new Map(candidates.map(item => [item.url, item])).values()].slice(0, MAX_CANDIDATES);
|
|
171
|
+
const fetched = await Promise.all(
|
|
172
|
+
unique.map(async (item, order) => {
|
|
173
|
+
try {
|
|
174
|
+
const response = await request(item.url, 'image/*');
|
|
175
|
+
if (!response) {
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
const mimetype = String(response.headers.get('content-type') || '')
|
|
179
|
+
.split(';')[0]
|
|
180
|
+
.trim()
|
|
181
|
+
.toLowerCase();
|
|
182
|
+
if (!mimetype.startsWith('image/')) {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
const buffer = Buffer.from(await response.arrayBuffer());
|
|
186
|
+
if (!buffer.length || buffer.length > MAX_ICON_BYTES) {
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
// 真实尺寸优先;读不出时退回站点声明的 sizes
|
|
190
|
+
const pixels = imageSize(buffer, mimetype) || item.size;
|
|
191
|
+
return { buffer, mimetype, filename: filenameOf(item.url, mimetype), pixels, maskable: !!item.maskable, order };
|
|
192
|
+
} catch (e) {
|
|
193
|
+
return null;
|
|
133
194
|
}
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
}
|
|
139
|
-
return null;
|
|
195
|
+
})
|
|
196
|
+
);
|
|
197
|
+
|
|
198
|
+
const best = fetched.filter(Boolean).sort((a, b) => b.pixels - a.pixels || Number(a.maskable) - Number(b.maskable) || a.order - b.order)[0];
|
|
199
|
+
return best ? { buffer: best.buffer, mimetype: best.mimetype, filename: best.filename } : null;
|
|
140
200
|
};
|
|
141
201
|
|
|
142
|
-
module.exports = { discoverRemoteIcon, parseHtmlIcons, parseManifestIcons };
|
|
202
|
+
module.exports = { discoverRemoteIcon, parseHtmlIcons, parseManifestIcons, imageSize };
|
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 $$;
|