@mainsoft/agent-cms 0.10.1 → 0.11.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 +21 -0
- package/README.md +98 -2
- package/TODO.md +6 -6
- package/UPGRADE-0.11.md +43 -0
- package/dist/agent.d.cts +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +7 -7
- package/dist/bin.js +236 -23
- package/dist/{chunk-IU2SMWAM.js → chunk-42PW3HQ3.js} +15 -1
- package/dist/{chunk-6PB4ZCHH.js → chunk-CIMW73L3.js} +58 -1
- package/dist/{chunk-7Y6TU2UA.js → chunk-HY4ED7LT.js} +2 -2
- package/dist/{chunk-DSJETZT4.js → chunk-I3DF6DMI.js} +15 -10
- package/dist/{chunk-KAO3Z3CF.js → chunk-I5UHTAAW.js} +3 -1
- package/dist/{chunk-7SCYDG2G.js → chunk-J25IKU7C.js} +164 -28
- package/dist/{chunk-BFVBHIHV.js → chunk-J5DW3RFQ.js} +4 -1
- package/dist/{chunk-7WJIIJCI.js → chunk-LELPCGDX.js} +8 -5
- package/dist/{chunk-QMPSOLLH.js → chunk-NO6S7KOL.js} +1 -1
- package/dist/{chunk-ZCUJ4MPT.js → chunk-OLHLSSTD.js} +3 -3
- package/dist/{chunk-3OPKTBEI.js → chunk-SV3ZA6XP.js} +1 -1
- package/dist/{chunk-PEQY4N73.js → chunk-TKKTEGHL.js} +1 -0
- package/dist/{chunk-PGV2QPIL.js → chunk-WWG7XDIZ.js} +2 -0
- package/dist/cli.cjs +236 -23
- package/dist/cli.d.cts +2 -2
- package/dist/cli.d.ts +2 -2
- package/dist/cli.js +18 -16
- package/dist/client.cjs +4 -1
- package/dist/client.d.cts +14 -2
- package/dist/client.d.ts +14 -2
- package/dist/client.js +1 -1
- package/dist/{cms-pqJyowu1.d.ts → cms-A9tmLmTP.d.ts} +100 -5
- package/dist/{cms-C_vkAxYV.d.cts → cms-CaB81PPX.d.cts} +100 -5
- package/dist/config.d.cts +1 -1
- package/dist/config.d.ts +1 -1
- package/dist/{drizzle-repo-DWLD0rWe.d.ts → drizzle-repo-BXV-hFkE.d.ts} +1 -1
- package/dist/{drizzle-repo-CviH3EX7.d.cts → drizzle-repo-CblPVYnK.d.cts} +1 -1
- package/dist/errors.cjs +4 -0
- package/dist/errors.d.cts +3 -1
- package/dist/errors.d.ts +3 -1
- package/dist/errors.js +2 -2
- package/dist/frontmatter.d.cts +1 -1
- package/dist/frontmatter.d.ts +1 -1
- package/dist/http.cjs +32 -12
- package/dist/http.d.cts +18 -4
- package/dist/http.d.ts +18 -4
- package/dist/http.js +30 -20
- package/dist/image-sharp.cjs +104 -0
- package/dist/image-sharp.d.cts +47 -0
- package/dist/image-sharp.d.ts +47 -0
- package/dist/image-sharp.js +70 -0
- package/dist/index.cjs +244 -27
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +21 -21
- package/dist/mcp.cjs +9 -4
- package/dist/mcp.d.cts +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +11 -11
- package/dist/messages/en.cjs +2 -0
- package/dist/messages/en.js +1 -1
- package/dist/messages/ko.cjs +2 -0
- package/dist/messages/ko.js +2 -0
- package/dist/registry/cms-doc-editor.json +6 -1
- package/dist/registry/cms-lib.json +2 -2
- package/dist/registry/cms-media-picker.json +2 -2
- package/dist/registry/cms-media.json +1 -1
- package/dist/registry/registry.json +4 -0
- package/dist/storage-vercel-blob.cjs +199 -0
- package/dist/storage-vercel-blob.d.cts +98 -0
- package/dist/storage-vercel-blob.d.ts +98 -0
- package/dist/storage-vercel-blob.js +165 -0
- package/dist/storage.cjs +63 -3
- package/dist/storage.d.cts +27 -2
- package/dist/storage.d.ts +27 -2
- package/dist/storage.js +9 -3
- package/dist/tables.cjs +15 -1
- package/dist/tables.d.cts +154 -1
- package/dist/tables.d.ts +154 -1
- package/dist/tables.js +2 -2
- package/dist/tools.cjs +8 -3
- package/dist/tools.d.cts +1 -1
- package/dist/tools.d.ts +1 -1
- package/dist/tools.js +9 -9
- package/dist/types.cjs +5 -0
- package/dist/types.d.cts +6 -1
- package/dist/types.d.ts +6 -1
- package/dist/types.js +3 -3
- package/package.json +36 -2
package/dist/frontmatter.d.cts
CHANGED
package/dist/frontmatter.d.ts
CHANGED
package/dist/http.cjs
CHANGED
|
@@ -24,6 +24,7 @@ __export(http_exports, {
|
|
|
24
24
|
errorResponse: () => errorResponse,
|
|
25
25
|
json: () => json,
|
|
26
26
|
resolveActor: () => resolveActor,
|
|
27
|
+
sameSite: () => sameSite,
|
|
27
28
|
versionFromIfMatch: () => versionFromIfMatch
|
|
28
29
|
});
|
|
29
30
|
module.exports = __toCommonJS(http_exports);
|
|
@@ -173,6 +174,8 @@ var en = {
|
|
|
173
174
|
import_blocked: "That address cannot be fetched",
|
|
174
175
|
import_failed: "Could not fetch the file ({reason})",
|
|
175
176
|
asset_rejected: "This file did not pass the check",
|
|
177
|
+
asset_replace_type: "A file can only be replaced by one of the same type ({mime})",
|
|
178
|
+
unknown_image_size: "There is no image size named \u201C{size}\u201D",
|
|
176
179
|
asset_missing: "The file {id} does not exist",
|
|
177
180
|
asset_wrong_kind: "The file {id} is not a kind this field takes",
|
|
178
181
|
asset_alt_missing: "The image on line {line} has no alt text",
|
|
@@ -262,6 +265,8 @@ var ERROR_CODES = {
|
|
|
262
265
|
import_blocked: "invalid",
|
|
263
266
|
import_failed: "invalid",
|
|
264
267
|
asset_rejected: "invalid",
|
|
268
|
+
asset_replace_type: "invalid",
|
|
269
|
+
unknown_image_size: "not_found",
|
|
265
270
|
asset_missing: "invalid",
|
|
266
271
|
asset_wrong_kind: "invalid",
|
|
267
272
|
asset_alt_missing: "invalid",
|
|
@@ -886,9 +891,14 @@ var CMS_TOOLS = [
|
|
|
886
891
|
{
|
|
887
892
|
name: "update_asset",
|
|
888
893
|
media: "write",
|
|
889
|
-
description: "Change a file's alt text or
|
|
890
|
-
input: import_zod.z.object({
|
|
891
|
-
|
|
894
|
+
description: "Change a file's alt text, tags or focal point. Documents that use the file without their own alt text show the new one.",
|
|
895
|
+
input: import_zod.z.object({
|
|
896
|
+
id: assetId,
|
|
897
|
+
alt: import_zod.z.string().optional(),
|
|
898
|
+
tags: import_zod.z.array(import_zod.z.string()).optional(),
|
|
899
|
+
focal: import_zod.z.object({ x: import_zod.z.number().min(0).max(1), y: import_zod.z.number().min(0).max(1) }).nullable().optional().describe("Images: the point that stays in view when the picture is cropped, from the left and from the top (0..1). null clears it.")
|
|
900
|
+
}),
|
|
901
|
+
run: async (cms, actor, a) => assetOut(await cms.assets.update(actor, a.id, { alt: a.alt, tags: a.tags, focal: a.focal }))
|
|
892
902
|
},
|
|
893
903
|
{
|
|
894
904
|
name: "move_asset",
|
|
@@ -957,7 +967,7 @@ async function runTool(cms, actor, name, args = {}, opts = {}) {
|
|
|
957
967
|
}
|
|
958
968
|
|
|
959
969
|
// src/version.ts
|
|
960
|
-
var VERSION = "0.
|
|
970
|
+
var VERSION = "0.11.0";
|
|
961
971
|
|
|
962
972
|
// src/mcp.ts
|
|
963
973
|
var ANONYMOUS_READ_TOOLS = ["list_collections", "search_documents", "read_for_answer", "list_documents", "get_document"];
|
|
@@ -1204,7 +1214,17 @@ function errorResponse(err, cms) {
|
|
|
1204
1214
|
return json({ error: "internal", kind: "internal", message: formatMessage(core?.messages, "internal"), params: {} }, 500);
|
|
1205
1215
|
}
|
|
1206
1216
|
var MAX_BODY_BYTES2 = 512 * 1024;
|
|
1207
|
-
|
|
1217
|
+
function sameSite(req, trusted = []) {
|
|
1218
|
+
const origin = req.headers.get("origin");
|
|
1219
|
+
const from = origin ? safeHost(origin) : null;
|
|
1220
|
+
if (from && trusted.some((o) => safeHost(o) === from || o === from)) return true;
|
|
1221
|
+
if (req.headers.get("sec-fetch-site") === "cross-site") return false;
|
|
1222
|
+
if (!origin) return true;
|
|
1223
|
+
if (!from) return false;
|
|
1224
|
+
const own = [safeHost(req.url), req.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || null, req.headers.get("host")];
|
|
1225
|
+
return own.some((h) => !!h && h.toLowerCase() === from.toLowerCase());
|
|
1226
|
+
}
|
|
1227
|
+
async function resolveActor(cms, req, resolveUser, trustedOrigins) {
|
|
1208
1228
|
const core = coreOf(cms);
|
|
1209
1229
|
const raw = keyFromHeader(req.headers.get("authorization"));
|
|
1210
1230
|
if (raw) {
|
|
@@ -1215,9 +1235,7 @@ async function resolveActor(cms, req, resolveUser) {
|
|
|
1215
1235
|
if (/\bsgk_/.test(req.headers.get("authorization") ?? "")) throw new CmsError("invalid_key", {}, { messages: core.messages });
|
|
1216
1236
|
const user = await resolveUser(req);
|
|
1217
1237
|
if (user && !["GET", "HEAD"].includes(req.method.toUpperCase())) {
|
|
1218
|
-
|
|
1219
|
-
const origin = req.headers.get("origin");
|
|
1220
|
-
if (site === "cross-site" || origin && new URL(req.url).host !== safeHost(origin)) throw new CmsError("cross_site", {}, { messages: core.messages });
|
|
1238
|
+
if (!sameSite(req, trustedOrigins)) throw new CmsError("cross_site", {}, { messages: core.messages });
|
|
1221
1239
|
}
|
|
1222
1240
|
if (!user) return { kind: "anonymous" };
|
|
1223
1241
|
const { agent: _agent, ...person } = user;
|
|
@@ -1277,7 +1295,7 @@ function createCmsHandler(opts) {
|
|
|
1277
1295
|
return json(await core.runScheduled());
|
|
1278
1296
|
}
|
|
1279
1297
|
const client = req.headers.get("x-agent-cms-client");
|
|
1280
|
-
const who = await resolveActor(core, req, opts.resolveUser);
|
|
1298
|
+
const who = await resolveActor(core, req, opts.resolveUser, opts.trustedOrigins);
|
|
1281
1299
|
const actor = { ...who, via: seg[0] === "mcp" ? client === "cli" ? "cli" : "mcp" : client === "cli" ? "cli" : "rest" };
|
|
1282
1300
|
const q = url.searchParams;
|
|
1283
1301
|
const expected = (fromBody) => versionFromIfMatch(req.headers.get("if-match")) ?? fromBody;
|
|
@@ -1375,7 +1393,7 @@ function createCmsHandler(opts) {
|
|
|
1375
1393
|
}
|
|
1376
1394
|
}
|
|
1377
1395
|
if (seg[0] === "files" && seg[1] && seg.length <= 3 && (m === "GET" || m === "HEAD")) {
|
|
1378
|
-
const to = await core.assets.open(actor, seg[1], { thumb: q.get("thumb") === "1", download: q.get("download") === "1" });
|
|
1396
|
+
const to = await core.assets.open(actor, seg[1], { thumb: q.get("thumb") === "1", download: q.get("download") === "1", size: q.get("size") });
|
|
1379
1397
|
return new Response(null, { status: 302, headers: { location: to.url, "cache-control": to.visibility === "public" && q.get("download") !== "1" ? "public, max-age=300" : "private, no-store" } });
|
|
1380
1398
|
}
|
|
1381
1399
|
if (seg[0] === "stores" && seg[1] && seg[2] === "files") {
|
|
@@ -1425,7 +1443,8 @@ function createCmsHandler(opts) {
|
|
|
1425
1443
|
store: import_zod2.z.string().nullable().optional(),
|
|
1426
1444
|
alt: import_zod2.z.string().max(500).optional(),
|
|
1427
1445
|
tags,
|
|
1428
|
-
field: import_zod2.z.object({ collection: import_zod2.z.string(), path: import_zod2.z.string() }).nullable().optional()
|
|
1446
|
+
field: import_zod2.z.object({ collection: import_zod2.z.string(), path: import_zod2.z.string() }).nullable().optional(),
|
|
1447
|
+
replace: import_zod2.z.string().max(40).nullable().optional()
|
|
1429
1448
|
})
|
|
1430
1449
|
);
|
|
1431
1450
|
return json(await assets.requestUpload(actor, b), 201);
|
|
@@ -1448,7 +1467,7 @@ function createCmsHandler(opts) {
|
|
|
1448
1467
|
const id = seg[1];
|
|
1449
1468
|
if (id && !id.startsWith("_") && id !== "uploads") {
|
|
1450
1469
|
if (seg.length === 2 && m === "GET") return json({ asset: await assets.get(actor, id) });
|
|
1451
|
-
if (seg.length === 2 && m === "PATCH") return json({ asset: await assets.update(actor, id, await body(req, import_zod2.z.object({ alt: import_zod2.z.string().max(500).optional(), tags }))) });
|
|
1470
|
+
if (seg.length === 2 && m === "PATCH") return json({ asset: await assets.update(actor, id, await body(req, import_zod2.z.object({ alt: import_zod2.z.string().max(500).optional(), tags, focal: import_zod2.z.object({ x: import_zod2.z.number().min(0).max(1), y: import_zod2.z.number().min(0).max(1) }).nullable().optional() }))) });
|
|
1452
1471
|
if (seg.length === 2 && m === "DELETE") {
|
|
1453
1472
|
await assets.remove(actor, id, { confirm: q.get("confirm") === "1" });
|
|
1454
1473
|
return json({ ok: true });
|
|
@@ -1647,5 +1666,6 @@ function createCmsHandler(opts) {
|
|
|
1647
1666
|
errorResponse,
|
|
1648
1667
|
json,
|
|
1649
1668
|
resolveActor,
|
|
1669
|
+
sameSite,
|
|
1650
1670
|
versionFromIfMatch
|
|
1651
1671
|
});
|
package/dist/http.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as CmsLike } from './cms-
|
|
1
|
+
import { C as CmsLike } from './cms-CaB81PPX.cjs';
|
|
2
2
|
import { McpOptions } from './mcp.cjs';
|
|
3
3
|
import { Actor } from './types.cjs';
|
|
4
4
|
import './storage.cjs';
|
|
@@ -64,7 +64,7 @@ import '@modelcontextprotocol/sdk/server/index.js';
|
|
|
64
64
|
* POST /assets/:id/move {folder?, name?}
|
|
65
65
|
* POST /assets/:id/thumb body: a WebP, JPEG or PNG up to 512KB
|
|
66
66
|
* DELETE /assets/:id 409 asset_in_use with the documents; ?confirm=1 deletes anyway
|
|
67
|
-
* GET /files/:id/:name redirect to the file (?thumb=1, ?download=1); private files need a session or key
|
|
67
|
+
* GET /files/:id/:name redirect to the file (?thumb=1, ?download=1, ?size=<name>); private files need a session or key
|
|
68
68
|
*
|
|
69
69
|
* File manager (the bucket as it is, also files the CMS did not upload):
|
|
70
70
|
*
|
|
@@ -107,6 +107,12 @@ interface CmsHandlerOptions {
|
|
|
107
107
|
basePath?: string;
|
|
108
108
|
/** Refuse PATCH and DELETE of a document without If-Match / expectedVersion (428). Default false. */
|
|
109
109
|
requireIfMatch?: boolean;
|
|
110
|
+
/**
|
|
111
|
+
* Other addresses whose pages may write with a person's session, e.g.
|
|
112
|
+
* `["https://admin.example.com"]`. The app's own address needs no entry:
|
|
113
|
+
* it is read from the request (`Host`, `X-Forwarded-Host`).
|
|
114
|
+
*/
|
|
115
|
+
trustedOrigins?: readonly string[];
|
|
110
116
|
/**
|
|
111
117
|
* MCP options. `anonymous: "read"` lets requests without a key use the MCP
|
|
112
118
|
* endpoint with read tools only (published documents of collections anyone
|
|
@@ -116,9 +122,17 @@ interface CmsHandlerOptions {
|
|
|
116
122
|
}
|
|
117
123
|
declare function json(data: unknown, status?: number, headers?: Record<string, string>): Response;
|
|
118
124
|
declare function errorResponse(err: unknown, cms?: CmsLike): Response;
|
|
119
|
-
|
|
125
|
+
/**
|
|
126
|
+
* Is this write from a page of the app itself? Browsers put the page's
|
|
127
|
+
* address in `Origin`; a page elsewhere cannot change it, nor `Host`, nor
|
|
128
|
+
* add `X-Forwarded-Host`. Behind a proxy (and under `next start`) `req.url`
|
|
129
|
+
* holds the address the server listens on, not the one people open, so the
|
|
130
|
+
* address is also read from those two headers.
|
|
131
|
+
*/
|
|
132
|
+
declare function sameSite(req: Request, trusted?: readonly string[]): boolean;
|
|
133
|
+
declare function resolveActor(cms: CmsLike, req: Request, resolveUser: CmsHandlerOptions["resolveUser"], trustedOrigins?: readonly string[]): Promise<Actor>;
|
|
120
134
|
/** `If-Match: "v12"` (or W/"v12", or 12) → 12. */
|
|
121
135
|
declare function versionFromIfMatch(h: string | null): number | undefined;
|
|
122
136
|
declare function createCmsHandler(opts: CmsHandlerOptions): (req: Request) => Promise<Response>;
|
|
123
137
|
|
|
124
|
-
export { type CmsHandlerOptions, createCmsHandler, errorResponse, json, resolveActor, versionFromIfMatch };
|
|
138
|
+
export { type CmsHandlerOptions, createCmsHandler, errorResponse, json, resolveActor, sameSite, versionFromIfMatch };
|
package/dist/http.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as CmsLike } from './cms-
|
|
1
|
+
import { C as CmsLike } from './cms-A9tmLmTP.js';
|
|
2
2
|
import { McpOptions } from './mcp.js';
|
|
3
3
|
import { Actor } from './types.js';
|
|
4
4
|
import './storage.js';
|
|
@@ -64,7 +64,7 @@ import '@modelcontextprotocol/sdk/server/index.js';
|
|
|
64
64
|
* POST /assets/:id/move {folder?, name?}
|
|
65
65
|
* POST /assets/:id/thumb body: a WebP, JPEG or PNG up to 512KB
|
|
66
66
|
* DELETE /assets/:id 409 asset_in_use with the documents; ?confirm=1 deletes anyway
|
|
67
|
-
* GET /files/:id/:name redirect to the file (?thumb=1, ?download=1); private files need a session or key
|
|
67
|
+
* GET /files/:id/:name redirect to the file (?thumb=1, ?download=1, ?size=<name>); private files need a session or key
|
|
68
68
|
*
|
|
69
69
|
* File manager (the bucket as it is, also files the CMS did not upload):
|
|
70
70
|
*
|
|
@@ -107,6 +107,12 @@ interface CmsHandlerOptions {
|
|
|
107
107
|
basePath?: string;
|
|
108
108
|
/** Refuse PATCH and DELETE of a document without If-Match / expectedVersion (428). Default false. */
|
|
109
109
|
requireIfMatch?: boolean;
|
|
110
|
+
/**
|
|
111
|
+
* Other addresses whose pages may write with a person's session, e.g.
|
|
112
|
+
* `["https://admin.example.com"]`. The app's own address needs no entry:
|
|
113
|
+
* it is read from the request (`Host`, `X-Forwarded-Host`).
|
|
114
|
+
*/
|
|
115
|
+
trustedOrigins?: readonly string[];
|
|
110
116
|
/**
|
|
111
117
|
* MCP options. `anonymous: "read"` lets requests without a key use the MCP
|
|
112
118
|
* endpoint with read tools only (published documents of collections anyone
|
|
@@ -116,9 +122,17 @@ interface CmsHandlerOptions {
|
|
|
116
122
|
}
|
|
117
123
|
declare function json(data: unknown, status?: number, headers?: Record<string, string>): Response;
|
|
118
124
|
declare function errorResponse(err: unknown, cms?: CmsLike): Response;
|
|
119
|
-
|
|
125
|
+
/**
|
|
126
|
+
* Is this write from a page of the app itself? Browsers put the page's
|
|
127
|
+
* address in `Origin`; a page elsewhere cannot change it, nor `Host`, nor
|
|
128
|
+
* add `X-Forwarded-Host`. Behind a proxy (and under `next start`) `req.url`
|
|
129
|
+
* holds the address the server listens on, not the one people open, so the
|
|
130
|
+
* address is also read from those two headers.
|
|
131
|
+
*/
|
|
132
|
+
declare function sameSite(req: Request, trusted?: readonly string[]): boolean;
|
|
133
|
+
declare function resolveActor(cms: CmsLike, req: Request, resolveUser: CmsHandlerOptions["resolveUser"], trustedOrigins?: readonly string[]): Promise<Actor>;
|
|
120
134
|
/** `If-Match: "v12"` (or W/"v12", or 12) → 12. */
|
|
121
135
|
declare function versionFromIfMatch(h: string | null): number | undefined;
|
|
122
136
|
declare function createCmsHandler(opts: CmsHandlerOptions): (req: Request) => Promise<Response>;
|
|
123
137
|
|
|
124
|
-
export { type CmsHandlerOptions, createCmsHandler, errorResponse, json, resolveActor, versionFromIfMatch };
|
|
138
|
+
export { type CmsHandlerOptions, createCmsHandler, errorResponse, json, resolveActor, sameSite, versionFromIfMatch };
|
package/dist/http.js
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
1
1
|
import {
|
|
2
2
|
handleMcp,
|
|
3
3
|
toJsonSchema
|
|
4
|
-
} from "./chunk-
|
|
5
|
-
import "./chunk-
|
|
6
|
-
import "./chunk-
|
|
7
|
-
import "./chunk-
|
|
8
|
-
import "./chunk-7Y6TU2UA.js";
|
|
4
|
+
} from "./chunk-OLHLSSTD.js";
|
|
5
|
+
import "./chunk-NO6S7KOL.js";
|
|
6
|
+
import "./chunk-I3DF6DMI.js";
|
|
7
|
+
import "./chunk-HY4ED7LT.js";
|
|
9
8
|
import {
|
|
10
9
|
BULK_ACTIONS,
|
|
11
10
|
PREVIEW_TTLS,
|
|
12
11
|
coreOf,
|
|
13
12
|
keyFromHeader
|
|
14
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-J25IKU7C.js";
|
|
15
14
|
import "./chunk-MA6VKJ3F.js";
|
|
16
15
|
import {
|
|
17
16
|
ASSET_KINDS,
|
|
18
17
|
DOC_STATUSES,
|
|
19
18
|
KEY_SCOPES
|
|
20
|
-
} from "./chunk-
|
|
21
|
-
import "./chunk-3OPKTBEI.js";
|
|
22
|
-
import "./chunk-AKN7SUXU.js";
|
|
19
|
+
} from "./chunk-TKKTEGHL.js";
|
|
23
20
|
import {
|
|
24
21
|
CmsError,
|
|
25
22
|
formatMessage,
|
|
26
23
|
isCmsError
|
|
27
|
-
} from "./chunk-
|
|
28
|
-
import "./chunk-
|
|
29
|
-
import "./chunk-
|
|
24
|
+
} from "./chunk-I5UHTAAW.js";
|
|
25
|
+
import "./chunk-WWG7XDIZ.js";
|
|
26
|
+
import "./chunk-SV3ZA6XP.js";
|
|
27
|
+
import "./chunk-AKN7SUXU.js";
|
|
28
|
+
import "./chunk-J5DW3RFQ.js";
|
|
29
|
+
import "./chunk-CIMW73L3.js";
|
|
30
30
|
import "./chunk-2NTK7H4W.js";
|
|
31
31
|
|
|
32
32
|
// src/http.ts
|
|
@@ -65,7 +65,17 @@ function errorResponse(err, cms) {
|
|
|
65
65
|
return json({ error: "internal", kind: "internal", message: formatMessage(core?.messages, "internal"), params: {} }, 500);
|
|
66
66
|
}
|
|
67
67
|
var MAX_BODY_BYTES = 512 * 1024;
|
|
68
|
-
|
|
68
|
+
function sameSite(req, trusted = []) {
|
|
69
|
+
const origin = req.headers.get("origin");
|
|
70
|
+
const from = origin ? safeHost(origin) : null;
|
|
71
|
+
if (from && trusted.some((o) => safeHost(o) === from || o === from)) return true;
|
|
72
|
+
if (req.headers.get("sec-fetch-site") === "cross-site") return false;
|
|
73
|
+
if (!origin) return true;
|
|
74
|
+
if (!from) return false;
|
|
75
|
+
const own = [safeHost(req.url), req.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || null, req.headers.get("host")];
|
|
76
|
+
return own.some((h) => !!h && h.toLowerCase() === from.toLowerCase());
|
|
77
|
+
}
|
|
78
|
+
async function resolveActor(cms, req, resolveUser, trustedOrigins) {
|
|
69
79
|
const core = coreOf(cms);
|
|
70
80
|
const raw = keyFromHeader(req.headers.get("authorization"));
|
|
71
81
|
if (raw) {
|
|
@@ -76,9 +86,7 @@ async function resolveActor(cms, req, resolveUser) {
|
|
|
76
86
|
if (/\bsgk_/.test(req.headers.get("authorization") ?? "")) throw new CmsError("invalid_key", {}, { messages: core.messages });
|
|
77
87
|
const user = await resolveUser(req);
|
|
78
88
|
if (user && !["GET", "HEAD"].includes(req.method.toUpperCase())) {
|
|
79
|
-
|
|
80
|
-
const origin = req.headers.get("origin");
|
|
81
|
-
if (site === "cross-site" || origin && new URL(req.url).host !== safeHost(origin)) throw new CmsError("cross_site", {}, { messages: core.messages });
|
|
89
|
+
if (!sameSite(req, trustedOrigins)) throw new CmsError("cross_site", {}, { messages: core.messages });
|
|
82
90
|
}
|
|
83
91
|
if (!user) return { kind: "anonymous" };
|
|
84
92
|
const { agent: _agent, ...person } = user;
|
|
@@ -138,7 +146,7 @@ function createCmsHandler(opts) {
|
|
|
138
146
|
return json(await core.runScheduled());
|
|
139
147
|
}
|
|
140
148
|
const client = req.headers.get("x-agent-cms-client");
|
|
141
|
-
const who = await resolveActor(core, req, opts.resolveUser);
|
|
149
|
+
const who = await resolveActor(core, req, opts.resolveUser, opts.trustedOrigins);
|
|
142
150
|
const actor = { ...who, via: seg[0] === "mcp" ? client === "cli" ? "cli" : "mcp" : client === "cli" ? "cli" : "rest" };
|
|
143
151
|
const q = url.searchParams;
|
|
144
152
|
const expected = (fromBody) => versionFromIfMatch(req.headers.get("if-match")) ?? fromBody;
|
|
@@ -236,7 +244,7 @@ function createCmsHandler(opts) {
|
|
|
236
244
|
}
|
|
237
245
|
}
|
|
238
246
|
if (seg[0] === "files" && seg[1] && seg.length <= 3 && (m === "GET" || m === "HEAD")) {
|
|
239
|
-
const to = await core.assets.open(actor, seg[1], { thumb: q.get("thumb") === "1", download: q.get("download") === "1" });
|
|
247
|
+
const to = await core.assets.open(actor, seg[1], { thumb: q.get("thumb") === "1", download: q.get("download") === "1", size: q.get("size") });
|
|
240
248
|
return new Response(null, { status: 302, headers: { location: to.url, "cache-control": to.visibility === "public" && q.get("download") !== "1" ? "public, max-age=300" : "private, no-store" } });
|
|
241
249
|
}
|
|
242
250
|
if (seg[0] === "stores" && seg[1] && seg[2] === "files") {
|
|
@@ -286,7 +294,8 @@ function createCmsHandler(opts) {
|
|
|
286
294
|
store: z.string().nullable().optional(),
|
|
287
295
|
alt: z.string().max(500).optional(),
|
|
288
296
|
tags,
|
|
289
|
-
field: z.object({ collection: z.string(), path: z.string() }).nullable().optional()
|
|
297
|
+
field: z.object({ collection: z.string(), path: z.string() }).nullable().optional(),
|
|
298
|
+
replace: z.string().max(40).nullable().optional()
|
|
290
299
|
})
|
|
291
300
|
);
|
|
292
301
|
return json(await assets.requestUpload(actor, b), 201);
|
|
@@ -309,7 +318,7 @@ function createCmsHandler(opts) {
|
|
|
309
318
|
const id = seg[1];
|
|
310
319
|
if (id && !id.startsWith("_") && id !== "uploads") {
|
|
311
320
|
if (seg.length === 2 && m === "GET") return json({ asset: await assets.get(actor, id) });
|
|
312
|
-
if (seg.length === 2 && m === "PATCH") return json({ asset: await assets.update(actor, id, await body(req, z.object({ alt: z.string().max(500).optional(), tags }))) });
|
|
321
|
+
if (seg.length === 2 && m === "PATCH") return json({ asset: await assets.update(actor, id, await body(req, z.object({ alt: z.string().max(500).optional(), tags, focal: z.object({ x: z.number().min(0).max(1), y: z.number().min(0).max(1) }).nullable().optional() }))) });
|
|
313
322
|
if (seg.length === 2 && m === "DELETE") {
|
|
314
323
|
await assets.remove(actor, id, { confirm: q.get("confirm") === "1" });
|
|
315
324
|
return json({ ok: true });
|
|
@@ -507,5 +516,6 @@ export {
|
|
|
507
516
|
errorResponse,
|
|
508
517
|
json,
|
|
509
518
|
resolveActor,
|
|
519
|
+
sameSite,
|
|
510
520
|
versionFromIfMatch
|
|
511
521
|
};
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/image-sharp.ts
|
|
31
|
+
var image_sharp_exports = {};
|
|
32
|
+
__export(image_sharp_exports, {
|
|
33
|
+
MAX_IMAGE_SIDE: () => MAX_IMAGE_SIDE,
|
|
34
|
+
sharpTransforms: () => sharpTransforms
|
|
35
|
+
});
|
|
36
|
+
module.exports = __toCommonJS(image_sharp_exports);
|
|
37
|
+
var MAX_IMAGE_SIDE = 4096;
|
|
38
|
+
var FORMATS = ["webp", "avif", "jpeg", "png"];
|
|
39
|
+
var clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
|
|
40
|
+
function sharpTransforms(o) {
|
|
41
|
+
const g = globalThis;
|
|
42
|
+
if (typeof g.EdgeRuntime === "string" || g.process?.env?.NEXT_RUNTIME === "edge" || !g.process?.versions?.node) {
|
|
43
|
+
throw new Error('agent-cms: sharpTransforms() needs the Node.js runtime (sharp does not run on the Edge runtime). Move the CMS route to Node (`export const runtime = "nodejs"`) or leave `media.transforms` out there.');
|
|
44
|
+
}
|
|
45
|
+
const format = o.formats?.[0] ?? "webp";
|
|
46
|
+
for (const f of [format, ...o.formats ?? []]) if (!FORMATS.includes(f)) throw new Error(`agent-cms: sharpTransforms: unknown format "${f}" (use ${FORMATS.join(", ")})`);
|
|
47
|
+
const side = (name, which, v) => {
|
|
48
|
+
if (v === void 0) return;
|
|
49
|
+
if (!Number.isInteger(v) || v < 1 || v > MAX_IMAGE_SIDE) throw new Error(`agent-cms: sharpTransforms: size "${name}" has ${which} ${String(v)}; use a whole number from 1 to ${MAX_IMAGE_SIDE}`);
|
|
50
|
+
};
|
|
51
|
+
for (const [name, p] of Object.entries(o.presets)) {
|
|
52
|
+
if (!/^[a-z0-9][a-z0-9_-]{0,31}$/.test(name)) throw new Error(`agent-cms: sharpTransforms: "${name}" is not a size name (lowercase letters, digits, - and _)`);
|
|
53
|
+
side(name, "width", p.width);
|
|
54
|
+
side(name, "height", p.height);
|
|
55
|
+
if (!p.width && !p.height) throw new Error(`agent-cms: sharpTransforms: size "${name}" needs a width or a height`);
|
|
56
|
+
if (p.fit === "cover" && !(p.width && p.height)) throw new Error(`agent-cms: sharpTransforms: size "${name}" uses fit "cover", which needs both a width and a height`);
|
|
57
|
+
if (p.format && !FORMATS.includes(p.format)) throw new Error(`agent-cms: sharpTransforms: size "${name}" has the unknown format "${p.format}"`);
|
|
58
|
+
if (p.quality !== void 0 && !(p.quality >= 1 && p.quality <= 100)) throw new Error(`agent-cms: sharpTransforms: size "${name}" has quality ${p.quality}; use 1 to 100`);
|
|
59
|
+
}
|
|
60
|
+
const limitInputPixels = o.maxInputPixels ?? 1e8;
|
|
61
|
+
let lib = null;
|
|
62
|
+
const load = () => lib ??= import("sharp").then(
|
|
63
|
+
(m) => m.default ?? m,
|
|
64
|
+
(e) => {
|
|
65
|
+
lib = null;
|
|
66
|
+
throw new Error(`agent-cms: sharpTransforms() could not load "sharp" (npm install sharp): ${e instanceof Error ? e.message : String(e)}`);
|
|
67
|
+
}
|
|
68
|
+
);
|
|
69
|
+
return {
|
|
70
|
+
presets: { ...o.presets },
|
|
71
|
+
format,
|
|
72
|
+
maxInputBytes: o.maxInputBytes,
|
|
73
|
+
concurrency: o.concurrency,
|
|
74
|
+
timeoutMs: o.timeoutMs,
|
|
75
|
+
async make(bytes, job) {
|
|
76
|
+
const sharp = await load();
|
|
77
|
+
const meta = await sharp(bytes, { limitInputPixels }).metadata();
|
|
78
|
+
const turned = (meta.orientation ?? 1) >= 5;
|
|
79
|
+
const w = (turned ? meta.height : meta.width) ?? 0;
|
|
80
|
+
const h = (turned ? meta.width : meta.height) ?? 0;
|
|
81
|
+
if (!w || !h) throw new Error("not a picture sharp can read");
|
|
82
|
+
let img = sharp(bytes, { limitInputPixels }).rotate();
|
|
83
|
+
if (job.fit === "cover" && job.width && job.height) {
|
|
84
|
+
const k = Math.min(1, w / job.width, h / job.height);
|
|
85
|
+
const W = Math.max(1, Math.round(job.width * k));
|
|
86
|
+
const H = Math.max(1, Math.round(job.height * k));
|
|
87
|
+
const scale = Math.max(W / w, H / h);
|
|
88
|
+
const rw = Math.max(W, Math.round(w * scale));
|
|
89
|
+
const rh = Math.max(H, Math.round(h * scale));
|
|
90
|
+
const f = job.focal ?? { x: 0.5, y: 0.5 };
|
|
91
|
+
img = img.resize(rw, rh, { fit: "fill" }).extract({ left: clamp(Math.round(f.x * rw - W / 2), 0, rw - W), top: clamp(Math.round(f.y * rh - H / 2), 0, rh - H), width: W, height: H });
|
|
92
|
+
} else {
|
|
93
|
+
img = img.resize({ width: job.width ?? void 0, height: job.height ?? void 0, fit: "inside", withoutEnlargement: true });
|
|
94
|
+
}
|
|
95
|
+
const { data, info } = await img.toFormat(job.format, job.quality ? { quality: job.quality } : {}).toBuffer({ resolveWithObject: true });
|
|
96
|
+
return { bytes: new Uint8Array(data.buffer, data.byteOffset, data.byteLength), width: info.width, height: info.height };
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
101
|
+
0 && (module.exports = {
|
|
102
|
+
MAX_IMAGE_SIDE,
|
|
103
|
+
sharpTransforms
|
|
104
|
+
});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { I as ImagePreset, a as ImageFormat, b as ImageTransforms } from './cms-CaB81PPX.cjs';
|
|
2
|
+
import './storage.cjs';
|
|
3
|
+
import './types.cjs';
|
|
4
|
+
import 'zod';
|
|
5
|
+
import './errors.cjs';
|
|
6
|
+
import './markdown.cjs';
|
|
7
|
+
import './diff.cjs';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Image sizes made with sharp (`npm install sharp`). Node only.
|
|
11
|
+
*
|
|
12
|
+
* import { sharpTransforms } from "@mainsoft/agent-cms/image-sharp";
|
|
13
|
+
*
|
|
14
|
+
* createCms({
|
|
15
|
+
* media: {
|
|
16
|
+
* stores: { ... },
|
|
17
|
+
* transforms: sharpTransforms({
|
|
18
|
+
* presets: { thumb: { width: 480 }, card: { width: 800, height: 450, fit: "cover" }, full: { width: 1600 } },
|
|
19
|
+
* }),
|
|
20
|
+
* },
|
|
21
|
+
* });
|
|
22
|
+
*
|
|
23
|
+
* Only the sizes named here exist: `/api/cms/files/<id>/<name>?size=card`.
|
|
24
|
+
* Nobody can ask for an arbitrary width, so nobody can fill the store with
|
|
25
|
+
* copies. A size is made the first time it is asked for and kept in the
|
|
26
|
+
* store under `_cms/derived/`.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** No size may be wider or taller than this. */
|
|
30
|
+
declare const MAX_IMAGE_SIDE = 4096;
|
|
31
|
+
interface SharpTransformsOptions {
|
|
32
|
+
/** Name → size. Names are lowercase letters, digits, `-` and `_`. */
|
|
33
|
+
presets: Record<string, ImagePreset>;
|
|
34
|
+
/** The first one is the format of sizes that do not name their own. Default `["webp"]`. */
|
|
35
|
+
formats?: readonly ImageFormat[];
|
|
36
|
+
/** Originals above this many bytes are served as they are. Default 40MB. */
|
|
37
|
+
maxInputBytes?: number;
|
|
38
|
+
/** Originals with more pixels than this are served as they are. Default 100 million. */
|
|
39
|
+
maxInputPixels?: number;
|
|
40
|
+
/** Copies made at the same time. Default 4. */
|
|
41
|
+
concurrency?: number;
|
|
42
|
+
/** A request waits this long for a copy, then gets the original. Default 10000. */
|
|
43
|
+
timeoutMs?: number;
|
|
44
|
+
}
|
|
45
|
+
declare function sharpTransforms(o: SharpTransformsOptions): ImageTransforms;
|
|
46
|
+
|
|
47
|
+
export { MAX_IMAGE_SIDE, type SharpTransformsOptions, sharpTransforms };
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { I as ImagePreset, a as ImageFormat, b as ImageTransforms } from './cms-A9tmLmTP.js';
|
|
2
|
+
import './storage.js';
|
|
3
|
+
import './types.js';
|
|
4
|
+
import 'zod';
|
|
5
|
+
import './errors.js';
|
|
6
|
+
import './markdown.js';
|
|
7
|
+
import './diff.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Image sizes made with sharp (`npm install sharp`). Node only.
|
|
11
|
+
*
|
|
12
|
+
* import { sharpTransforms } from "@mainsoft/agent-cms/image-sharp";
|
|
13
|
+
*
|
|
14
|
+
* createCms({
|
|
15
|
+
* media: {
|
|
16
|
+
* stores: { ... },
|
|
17
|
+
* transforms: sharpTransforms({
|
|
18
|
+
* presets: { thumb: { width: 480 }, card: { width: 800, height: 450, fit: "cover" }, full: { width: 1600 } },
|
|
19
|
+
* }),
|
|
20
|
+
* },
|
|
21
|
+
* });
|
|
22
|
+
*
|
|
23
|
+
* Only the sizes named here exist: `/api/cms/files/<id>/<name>?size=card`.
|
|
24
|
+
* Nobody can ask for an arbitrary width, so nobody can fill the store with
|
|
25
|
+
* copies. A size is made the first time it is asked for and kept in the
|
|
26
|
+
* store under `_cms/derived/`.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** No size may be wider or taller than this. */
|
|
30
|
+
declare const MAX_IMAGE_SIDE = 4096;
|
|
31
|
+
interface SharpTransformsOptions {
|
|
32
|
+
/** Name → size. Names are lowercase letters, digits, `-` and `_`. */
|
|
33
|
+
presets: Record<string, ImagePreset>;
|
|
34
|
+
/** The first one is the format of sizes that do not name their own. Default `["webp"]`. */
|
|
35
|
+
formats?: readonly ImageFormat[];
|
|
36
|
+
/** Originals above this many bytes are served as they are. Default 40MB. */
|
|
37
|
+
maxInputBytes?: number;
|
|
38
|
+
/** Originals with more pixels than this are served as they are. Default 100 million. */
|
|
39
|
+
maxInputPixels?: number;
|
|
40
|
+
/** Copies made at the same time. Default 4. */
|
|
41
|
+
concurrency?: number;
|
|
42
|
+
/** A request waits this long for a copy, then gets the original. Default 10000. */
|
|
43
|
+
timeoutMs?: number;
|
|
44
|
+
}
|
|
45
|
+
declare function sharpTransforms(o: SharpTransformsOptions): ImageTransforms;
|
|
46
|
+
|
|
47
|
+
export { MAX_IMAGE_SIDE, type SharpTransformsOptions, sharpTransforms };
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import "./chunk-2NTK7H4W.js";
|
|
2
|
+
|
|
3
|
+
// src/image-sharp.ts
|
|
4
|
+
var MAX_IMAGE_SIDE = 4096;
|
|
5
|
+
var FORMATS = ["webp", "avif", "jpeg", "png"];
|
|
6
|
+
var clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
|
|
7
|
+
function sharpTransforms(o) {
|
|
8
|
+
const g = globalThis;
|
|
9
|
+
if (typeof g.EdgeRuntime === "string" || g.process?.env?.NEXT_RUNTIME === "edge" || !g.process?.versions?.node) {
|
|
10
|
+
throw new Error('agent-cms: sharpTransforms() needs the Node.js runtime (sharp does not run on the Edge runtime). Move the CMS route to Node (`export const runtime = "nodejs"`) or leave `media.transforms` out there.');
|
|
11
|
+
}
|
|
12
|
+
const format = o.formats?.[0] ?? "webp";
|
|
13
|
+
for (const f of [format, ...o.formats ?? []]) if (!FORMATS.includes(f)) throw new Error(`agent-cms: sharpTransforms: unknown format "${f}" (use ${FORMATS.join(", ")})`);
|
|
14
|
+
const side = (name, which, v) => {
|
|
15
|
+
if (v === void 0) return;
|
|
16
|
+
if (!Number.isInteger(v) || v < 1 || v > MAX_IMAGE_SIDE) throw new Error(`agent-cms: sharpTransforms: size "${name}" has ${which} ${String(v)}; use a whole number from 1 to ${MAX_IMAGE_SIDE}`);
|
|
17
|
+
};
|
|
18
|
+
for (const [name, p] of Object.entries(o.presets)) {
|
|
19
|
+
if (!/^[a-z0-9][a-z0-9_-]{0,31}$/.test(name)) throw new Error(`agent-cms: sharpTransforms: "${name}" is not a size name (lowercase letters, digits, - and _)`);
|
|
20
|
+
side(name, "width", p.width);
|
|
21
|
+
side(name, "height", p.height);
|
|
22
|
+
if (!p.width && !p.height) throw new Error(`agent-cms: sharpTransforms: size "${name}" needs a width or a height`);
|
|
23
|
+
if (p.fit === "cover" && !(p.width && p.height)) throw new Error(`agent-cms: sharpTransforms: size "${name}" uses fit "cover", which needs both a width and a height`);
|
|
24
|
+
if (p.format && !FORMATS.includes(p.format)) throw new Error(`agent-cms: sharpTransforms: size "${name}" has the unknown format "${p.format}"`);
|
|
25
|
+
if (p.quality !== void 0 && !(p.quality >= 1 && p.quality <= 100)) throw new Error(`agent-cms: sharpTransforms: size "${name}" has quality ${p.quality}; use 1 to 100`);
|
|
26
|
+
}
|
|
27
|
+
const limitInputPixels = o.maxInputPixels ?? 1e8;
|
|
28
|
+
let lib = null;
|
|
29
|
+
const load = () => lib ??= import("sharp").then(
|
|
30
|
+
(m) => m.default ?? m,
|
|
31
|
+
(e) => {
|
|
32
|
+
lib = null;
|
|
33
|
+
throw new Error(`agent-cms: sharpTransforms() could not load "sharp" (npm install sharp): ${e instanceof Error ? e.message : String(e)}`);
|
|
34
|
+
}
|
|
35
|
+
);
|
|
36
|
+
return {
|
|
37
|
+
presets: { ...o.presets },
|
|
38
|
+
format,
|
|
39
|
+
maxInputBytes: o.maxInputBytes,
|
|
40
|
+
concurrency: o.concurrency,
|
|
41
|
+
timeoutMs: o.timeoutMs,
|
|
42
|
+
async make(bytes, job) {
|
|
43
|
+
const sharp = await load();
|
|
44
|
+
const meta = await sharp(bytes, { limitInputPixels }).metadata();
|
|
45
|
+
const turned = (meta.orientation ?? 1) >= 5;
|
|
46
|
+
const w = (turned ? meta.height : meta.width) ?? 0;
|
|
47
|
+
const h = (turned ? meta.width : meta.height) ?? 0;
|
|
48
|
+
if (!w || !h) throw new Error("not a picture sharp can read");
|
|
49
|
+
let img = sharp(bytes, { limitInputPixels }).rotate();
|
|
50
|
+
if (job.fit === "cover" && job.width && job.height) {
|
|
51
|
+
const k = Math.min(1, w / job.width, h / job.height);
|
|
52
|
+
const W = Math.max(1, Math.round(job.width * k));
|
|
53
|
+
const H = Math.max(1, Math.round(job.height * k));
|
|
54
|
+
const scale = Math.max(W / w, H / h);
|
|
55
|
+
const rw = Math.max(W, Math.round(w * scale));
|
|
56
|
+
const rh = Math.max(H, Math.round(h * scale));
|
|
57
|
+
const f = job.focal ?? { x: 0.5, y: 0.5 };
|
|
58
|
+
img = img.resize(rw, rh, { fit: "fill" }).extract({ left: clamp(Math.round(f.x * rw - W / 2), 0, rw - W), top: clamp(Math.round(f.y * rh - H / 2), 0, rh - H), width: W, height: H });
|
|
59
|
+
} else {
|
|
60
|
+
img = img.resize({ width: job.width ?? void 0, height: job.height ?? void 0, fit: "inside", withoutEnlargement: true });
|
|
61
|
+
}
|
|
62
|
+
const { data, info } = await img.toFormat(job.format, job.quality ? { quality: job.quality } : {}).toBuffer({ resolveWithObject: true });
|
|
63
|
+
return { bytes: new Uint8Array(data.buffer, data.byteOffset, data.byteLength), width: info.width, height: info.height };
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
export {
|
|
68
|
+
MAX_IMAGE_SIDE,
|
|
69
|
+
sharpTransforms
|
|
70
|
+
};
|