@insmind/cli 2.0.0 → 2.1.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/README.md +5 -0
- package/contracts/operations/agent.send/input.schema.json +1 -77
- package/contracts/operations/credits.get/input.schema.json +8 -0
- package/contracts/operations/credits.get/output.schema.json +92 -0
- package/contracts/operations/credits.usage.get/input.schema.json +17 -0
- package/contracts/operations/credits.usage.get/output.schema.json +46 -0
- package/contracts/operations/credits.usage.list/input.schema.json +27 -0
- package/contracts/operations/credits.usage.list/output.schema.json +135 -0
- package/contracts/operations/dam.folder.list/input.schema.json +0 -1
- package/contracts/operations/dam.folder.list/output.schema.json +1 -2
- package/contracts/operations/dam.list/input.schema.json +3 -6
- package/contracts/operations/dam.list/output.schema.json +1 -2
- package/contracts/operations/dam.search/input.schema.json +3 -6
- package/contracts/operations/dam.search/output.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-edit-smart.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-expand-smart.schema.json +1 -2
- package/contracts/operations/tool.call/models/image-layers-smart.schema.json +1 -3
- package/contracts/operations/tool.call/models/video-edit-smart.schema.json +0 -3
- package/contracts/operations/tool.call/ocr-payload.schema.json +4 -5
- package/dist/bin/postinstall.js +22 -6
- package/dist/bin/task-worker.js +2 -2
- package/dist/src/bootstrap/create-cli.js +31 -15
- package/dist/src/bootstrap/create-runtime.js +103 -30
- package/dist/src/bootstrap/run-task-worker.js +6 -2
- package/dist/src/bootstrap/validators.js +4 -1
- package/dist/src/cli/action-binding.js +17 -50
- package/dist/src/cli/agent-commands.js +11 -11
- package/dist/src/cli/auth-commands.js +2 -1
- package/dist/src/cli/creation-help.js +9 -0
- package/dist/src/cli/credits-command.js +127 -16
- package/dist/src/cli/dam-commands.js +10 -14
- package/dist/src/cli/editor-commands.js +7 -5
- package/dist/src/cli/errors.js +81 -22
- package/dist/src/cli/host-input.js +64 -5
- package/dist/src/cli/model-commands.js +9 -3
- package/dist/src/cli/observed-errors.js +7 -3
- package/dist/src/cli/org-commands.js +3 -1
- package/dist/src/cli/presenter.js +4 -0
- package/dist/src/cli/task-commands.js +6 -2
- package/dist/src/cli/tool-commands.js +12 -11
- package/dist/src/cli/update-command.js +24 -1
- package/dist/src/features/agent/creative-agent-adapter.js +6 -2
- package/dist/src/features/agent/creative-protocol.js +8 -29
- package/dist/src/features/agent/resource-authorizer.js +25 -17
- package/dist/src/features/agent/result-reader.js +31 -14
- package/dist/src/features/agent/use-cases.js +6 -31
- package/dist/src/features/credits/amount.js +51 -0
- package/dist/src/features/credits/response.js +11 -0
- package/dist/src/features/credits/use-cases.js +200 -30
- package/dist/src/features/dam/asset-projection.js +3 -6
- package/dist/src/features/dam/dam-api-adapter.js +30 -15
- package/dist/src/features/dam/repository-catalog.js +30 -21
- package/dist/src/features/dam/use-cases.js +12 -7
- package/dist/src/features/editor/bridge-client.js +0 -2
- package/dist/src/features/editor/public-url.js +1 -36
- package/dist/src/features/editor/session.js +3 -2
- package/dist/src/features/editor/use-cases.js +27 -2
- package/dist/src/features/org/org-service.js +10 -1
- package/dist/src/features/org/use-cases.js +18 -4
- package/dist/src/features/task/process-owner.js +54 -0
- package/dist/src/features/task/store.js +37 -10
- package/dist/src/features/task/task-background.js +5 -2
- package/dist/src/features/task/use-cases.js +184 -84
- package/dist/src/features/tool/argument-paths.js +14 -0
- package/dist/src/features/tool/canvas-copy.js +28 -15
- package/dist/src/features/tool/canvas-matting.js +123 -0
- package/dist/src/features/tool/canvas-media.js +100 -52
- package/dist/src/features/tool/canvas-models.js +66 -33
- package/dist/src/features/tool/canvas-pricing.js +12 -0
- package/dist/src/features/tool/canvas-recovery.js +13 -30
- package/dist/src/features/tool/canvas-results.js +79 -87
- package/dist/src/features/tool/canvas-tool-adapter.js +134 -157
- package/dist/src/features/tool/canvas-video.js +44 -37
- package/dist/src/features/tool/dynamic-schema.js +39 -40
- package/dist/src/features/tool/ffprobe-executable.js +21 -0
- package/dist/src/features/tool/mns-catalog-adapter.js +61 -24
- package/dist/src/features/tool/resource-authorizer.js +11 -3
- package/dist/src/features/tool/tool-api-adapter.js +73 -82
- package/dist/src/features/tool/tool-errors.js +25 -0
- package/dist/src/features/tool/tool-output.js +15 -0
- package/dist/src/features/tool/use-cases.js +74 -98
- package/dist/src/features/update/check-schema.js +17 -0
- package/dist/src/features/update/host-receipt.js +30 -0
- package/dist/src/features/update/notice-output.js +30 -0
- package/dist/src/features/update/update-lock.js +80 -0
- package/dist/src/features/update/update-notification.js +129 -240
- package/dist/src/features/update/update-service.js +95 -21
- package/dist/src/platform/media-type.js +46 -0
- package/dist/src/platform/public-url.js +35 -0
- package/dist/src/platform/remote-error-evidence.js +33 -6
- package/dist/src/platform/resource-auth-key.js +35 -1
- package/dist/src/platform/safe-upload-file.js +36 -41
- package/dist/src/platform/signature.js +3 -1
- package/dist/src/platform/signed-http-transport.js +14 -6
- package/dist/src/platform/url-safety.js +6 -1
- package/dist/src/platform/webm-header.js +41 -0
- package/dist/src/telemetry/command-route.js +38 -0
- package/dist/src/telemetry/command-routes.json +1 -0
- package/dist/src/telemetry/failure-summary.js +1 -1
- package/dist/src/telemetry/invocation.js +1 -2
- package/dist/src/telemetry/process-errors.js +17 -33
- package/dist/src/telemetry/sanitize.js +19 -4
- package/dist/src/telemetry/sls-sink.js +8 -0
- package/package.json +4 -4
- package/skills/insmind-cli/SKILL.md +19 -5
- package/skills/insmind-cli/references/agent.md +9 -4
- package/skills/insmind-cli/references/creation.md +3 -1
- package/skills/insmind-cli/references/editor.md +7 -5
- package/skills/insmind-cli/references/errors.md +20 -9
- package/skills/insmind-cli/references/matting.md +3 -5
- package/skills/insmind-cli/references/media-tools.md +10 -4
- package/skills/insmind-cli/references/tool.md +9 -15
- package/skills/insmind-cli/references/update.md +2 -0
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { mediaFilename, mediaTypeFromFilename } from "../../platform/media-type.js";
|
|
1
2
|
import { canvasModelBindings, canvasRemoteControlArguments } from "../tool/canvas-models.js";
|
|
2
|
-
import {
|
|
3
|
+
import { parseHttpAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
|
|
3
4
|
export class AgentInputError extends Error {
|
|
4
5
|
reason;
|
|
5
6
|
field;
|
|
@@ -10,33 +11,6 @@ export class AgentInputError extends Error {
|
|
|
10
11
|
this.name = "AgentInputError";
|
|
11
12
|
}
|
|
12
13
|
}
|
|
13
|
-
const mediaTypes = {
|
|
14
|
-
avif: "image/avif",
|
|
15
|
-
gif: "image/gif",
|
|
16
|
-
heic: "image/heic",
|
|
17
|
-
jpeg: "image/jpeg",
|
|
18
|
-
jpg: "image/jpeg",
|
|
19
|
-
mp4: "video/mp4",
|
|
20
|
-
png: "image/png",
|
|
21
|
-
webp: "image/webp"
|
|
22
|
-
};
|
|
23
|
-
function pathnameFilename(url) {
|
|
24
|
-
const segment = url.pathname.split("/").filter(Boolean).at(-1);
|
|
25
|
-
if (segment === undefined)
|
|
26
|
-
return "creative-media";
|
|
27
|
-
try {
|
|
28
|
-
return decodeURIComponent(segment) || "creative-media";
|
|
29
|
-
}
|
|
30
|
-
catch {
|
|
31
|
-
return segment;
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
function inferMediaType(filename) {
|
|
35
|
-
const extension = filename.split(".").at(-1)?.toLowerCase();
|
|
36
|
-
return extension === undefined || extension === filename.toLowerCase()
|
|
37
|
-
? "application/octet-stream"
|
|
38
|
-
: mediaTypes[extension] ?? "application/octet-stream";
|
|
39
|
-
}
|
|
40
14
|
export function createAgentUseCases(dependencies) {
|
|
41
15
|
async function prepare({ input, access, signal }) {
|
|
42
16
|
signal.throwIfAborted();
|
|
@@ -77,19 +51,20 @@ export function createAgentUseCases(dependencies) {
|
|
|
77
51
|
}
|
|
78
52
|
let url;
|
|
79
53
|
try {
|
|
80
|
-
url =
|
|
54
|
+
url = parseHttpAssetUrl(part.url);
|
|
81
55
|
}
|
|
82
56
|
catch (error) {
|
|
83
57
|
if (error instanceof UrlSafetyError)
|
|
84
58
|
throw new AgentInputError("invalid_asset_url", `/message/parts/${input.message.parts.indexOf(part)}/url`, error);
|
|
85
59
|
throw error;
|
|
86
60
|
}
|
|
87
|
-
const
|
|
61
|
+
const urlFilename = mediaFilename(url);
|
|
62
|
+
const filename = part.filename ?? urlFilename;
|
|
88
63
|
prepared.push({
|
|
89
64
|
kind: "asset",
|
|
90
65
|
asset: {
|
|
91
66
|
url: part.url,
|
|
92
|
-
mediaType: part.mediaType ??
|
|
67
|
+
mediaType: part.mediaType ?? mediaTypeFromFilename(filename) ?? mediaTypeFromFilename(urlFilename) ?? "application/octet-stream",
|
|
93
68
|
filename,
|
|
94
69
|
fromUserUpload: false
|
|
95
70
|
},
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
2
|
+
const maximum = BigInt(Number.MAX_SAFE_INTEGER);
|
|
3
|
+
/** Keep service decimals exact until arithmetic and range checks are complete. */
|
|
4
|
+
export function readCreditAmount(value) {
|
|
5
|
+
if (typeof value !== "number" && typeof value !== "string")
|
|
6
|
+
throw new RemoteProtocolError();
|
|
7
|
+
const text = String(value).trim();
|
|
8
|
+
const match = /^([+-]?)(?:(\d+)(?:\.(\d*))?|\.(\d+))(?:e([+-]?\d+))?$/i.exec(text);
|
|
9
|
+
if (!match)
|
|
10
|
+
throw new RemoteProtocolError();
|
|
11
|
+
const fraction = match[3] ?? match[4] ?? "";
|
|
12
|
+
const digits = `${match[2] ?? ""}${fraction}`.replace(/^0+/, "");
|
|
13
|
+
if (digits === "")
|
|
14
|
+
return { coefficient: 0n, scale: 0 };
|
|
15
|
+
const numeric = Number(text);
|
|
16
|
+
// Reject nonzero underflow before constructing powers for an extreme exponent.
|
|
17
|
+
if (match[1] === "-" || !Number.isFinite(numeric) || numeric === 0 || numeric > Number.MAX_SAFE_INTEGER) {
|
|
18
|
+
throw new RemoteProtocolError();
|
|
19
|
+
}
|
|
20
|
+
let coefficient = BigInt(digits);
|
|
21
|
+
let scale = fraction.length - Number(match[5] ?? 0);
|
|
22
|
+
if (scale < 0) {
|
|
23
|
+
coefficient *= 10n ** BigInt(-scale);
|
|
24
|
+
scale = 0;
|
|
25
|
+
}
|
|
26
|
+
return checked({ coefficient, scale });
|
|
27
|
+
}
|
|
28
|
+
export function sumCreditAmounts(values) {
|
|
29
|
+
const scale = values.reduce((largest, value) => Math.max(largest, value.scale), 0);
|
|
30
|
+
const coefficient = values.reduce((sum, value) => sum + scaled(value, scale), 0n);
|
|
31
|
+
return checked({ coefficient, scale });
|
|
32
|
+
}
|
|
33
|
+
export function availableCreditAmount(total, used) {
|
|
34
|
+
const scale = Math.max(total.scale, used.scale);
|
|
35
|
+
const difference = scaled(total, scale) - scaled(used, scale);
|
|
36
|
+
return { coefficient: difference > 0n ? difference : 0n, scale };
|
|
37
|
+
}
|
|
38
|
+
export function creditAmountNumber(value) {
|
|
39
|
+
const numeric = Number(`${value.coefficient}e-${value.scale}`);
|
|
40
|
+
if (value.coefficient !== 0n && numeric === 0)
|
|
41
|
+
throw new RemoteProtocolError();
|
|
42
|
+
return numeric;
|
|
43
|
+
}
|
|
44
|
+
function scaled(value, scale) {
|
|
45
|
+
return value.coefficient * 10n ** BigInt(scale - value.scale);
|
|
46
|
+
}
|
|
47
|
+
function checked(value) {
|
|
48
|
+
if (value.coefficient > maximum * 10n ** BigInt(value.scale))
|
|
49
|
+
throw new RemoteProtocolError();
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
const amountFields = new Set(["total", "used", "wait", "member_period_limit", "usage"]);
|
|
2
|
+
/** Preserve amount tokens before JSON.parse can round them; other fields keep their JSON types. */
|
|
3
|
+
export function parseCreditsResponse(text) {
|
|
4
|
+
const preserved = text.replace(/("(?:\\.|[^"\\])*")(?:(\s*:\s*)(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?))?/g, (token, key, separator, value) => {
|
|
5
|
+
// Consume every complete string token, including descriptions with escaped quotes.
|
|
6
|
+
if (value === undefined || !amountFields.has(JSON.parse(key)))
|
|
7
|
+
return token;
|
|
8
|
+
return `${key}${separator}${JSON.stringify(value)}`;
|
|
9
|
+
});
|
|
10
|
+
return JSON.parse(preserved);
|
|
11
|
+
}
|
|
@@ -1,39 +1,137 @@
|
|
|
1
|
+
import { withResponseDiagnostics } from "../../platform/signed-http-transport.js";
|
|
1
2
|
import { RemoteProtocolError } from "../../platform/remote-protocol.js";
|
|
3
|
+
import { availableCreditAmount, creditAmountNumber, readCreditAmount, sumCreditAmounts } from "./amount.js";
|
|
4
|
+
import { parseCreditsResponse } from "./response.js";
|
|
5
|
+
export class CreditsPageCursorError extends RemoteProtocolError {
|
|
6
|
+
partialResult;
|
|
7
|
+
constructor(partialResult) {
|
|
8
|
+
super({}, undefined, "CREDITS_NEXT_CURSOR_MISSING");
|
|
9
|
+
this.partialResult = partialResult;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function readableRows(values, project, warning) {
|
|
13
|
+
const kept = [];
|
|
14
|
+
for (const row of values) {
|
|
15
|
+
try {
|
|
16
|
+
kept.push(project(row));
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
if (!(error instanceof RemoteProtocolError))
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
if (kept.length !== values.length) {
|
|
24
|
+
if (!kept.length)
|
|
25
|
+
throw new RemoteProtocolError({}, undefined, "CREDITS_NO_READABLE_ROWS");
|
|
26
|
+
warning?.();
|
|
27
|
+
}
|
|
28
|
+
return kept;
|
|
29
|
+
}
|
|
2
30
|
export function createCreditsUseCases(options) {
|
|
3
31
|
return {
|
|
4
32
|
async get(input) {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
33
|
+
return withResponseDiagnostics(async (onResponse) => {
|
|
34
|
+
const body = await options.transport.getJson({
|
|
35
|
+
path: "/trade/rights-overview",
|
|
36
|
+
query: { goods_type_enums: "GAODOU" },
|
|
37
|
+
...input,
|
|
38
|
+
onResponse,
|
|
39
|
+
sensitiveResponse: true,
|
|
40
|
+
parseJson: parseCreditsResponse
|
|
41
|
+
});
|
|
42
|
+
const rows = findCreditsRecords(body).map(source => {
|
|
43
|
+
const total = readCreditAmount(source.total);
|
|
44
|
+
const used = readCreditAmount(source.used);
|
|
45
|
+
const pending = readCreditAmount(source.wait);
|
|
46
|
+
const identifier = optionalString(source.identifier, options.onPartial);
|
|
47
|
+
const memberPeriodLimit = source.member_period_limit == null ? undefined : amount(source.member_period_limit);
|
|
48
|
+
return { ...(identifier === undefined ? {} : { identifier }), total, used, pending,
|
|
49
|
+
...(memberPeriodLimit === undefined ? {} : { memberPeriodLimit }) };
|
|
50
|
+
});
|
|
51
|
+
const total = sumCreditAmounts(rows.map(row => row.total));
|
|
52
|
+
const used = sumCreditAmounts(rows.map(row => row.used));
|
|
53
|
+
const pending = sumCreditAmounts(rows.map(row => row.pending));
|
|
54
|
+
const balances = rows.map(({ total, used, pending, ...metadata }) => ({
|
|
55
|
+
...metadata, total: creditAmountNumber(total), used: creditAmountNumber(used), pending: creditAmountNumber(pending),
|
|
56
|
+
available: creditAmountNumber(availableCreditAmount(total, used))
|
|
57
|
+
}));
|
|
58
|
+
return {
|
|
59
|
+
credits: { unit: options.billingUnit, total: creditAmountNumber(total), used: creditAmountNumber(used),
|
|
60
|
+
pending: creditAmountNumber(pending), available: creditAmountNumber(availableCreditAmount(total, used)) },
|
|
61
|
+
...(balances.length > 1 || balances.some(row => row.memberPeriodLimit !== undefined) ? { balances } : {})
|
|
62
|
+
};
|
|
63
|
+
});
|
|
64
|
+
},
|
|
65
|
+
async listUsage({ input, ...access }) {
|
|
66
|
+
return withResponseDiagnostics(async (onResponse) => {
|
|
67
|
+
const normalized = normalizeCreditsUsageListInput(input, options.now?.());
|
|
68
|
+
const body = await options.transport.getJson({
|
|
69
|
+
path: "/trade/gaodou-rights/usage-records",
|
|
70
|
+
query: { recordAtGte: normalized.from, recordAtLte: normalized.to, pageSize: String(normalized.limit),
|
|
71
|
+
...(normalized.cursor === undefined ? {} : { cursor: normalized.cursor }) },
|
|
72
|
+
...access,
|
|
73
|
+
onResponse,
|
|
74
|
+
sensitiveResponse: true,
|
|
75
|
+
parseJson: parseCreditsResponse
|
|
76
|
+
});
|
|
77
|
+
if (!isRecord(body) || !Array.isArray(body.items) || typeof body.has_more !== "boolean")
|
|
78
|
+
throw new RemoteProtocolError();
|
|
79
|
+
const page = { unit: options.billingUnit, range: { from: normalized.from, to: normalized.to },
|
|
80
|
+
items: readableRows(body.items, item => readUsageRecord(item, options.onPartial), options.onPartial), hasMore: body.has_more };
|
|
81
|
+
if (!body.has_more)
|
|
82
|
+
return { ...page, nextCursor: null };
|
|
83
|
+
const cursor = body.next_cursor;
|
|
84
|
+
if (typeof cursor !== "string" || !cursor.trim())
|
|
85
|
+
throw new CreditsPageCursorError(page);
|
|
86
|
+
return { ...page, nextCursor: cursor };
|
|
11
87
|
});
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
88
|
+
},
|
|
89
|
+
async getUsage({ input, ...access }) {
|
|
90
|
+
return withResponseDiagnostics(async (onResponse) => {
|
|
91
|
+
const body = await options.transport.getJson({
|
|
92
|
+
path: `/trade/gaodou-rights/usage-records/${encodeURIComponent(input.id)}`,
|
|
93
|
+
...access,
|
|
94
|
+
onResponse,
|
|
95
|
+
sensitiveResponse: true,
|
|
96
|
+
parseJson: parseCreditsResponse
|
|
97
|
+
});
|
|
98
|
+
if (!isRecord(body) || !Array.isArray(body.usage_logs))
|
|
99
|
+
throw new RemoteProtocolError();
|
|
100
|
+
return {
|
|
101
|
+
id: input.id,
|
|
21
102
|
unit: options.billingUnit,
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
103
|
+
breakdown: readableRows(body.usage_logs, value => {
|
|
104
|
+
if (!isRecord(value))
|
|
105
|
+
throw new RemoteProtocolError();
|
|
106
|
+
const usageType = optionalNumber(value.usage_type, options.onPartial);
|
|
107
|
+
const sourceType = optionalString(value.source_type, options.onPartial);
|
|
108
|
+
return { amount: amount(value.usage), ...(usageType === undefined ? {} : { usageType }),
|
|
109
|
+
...(sourceType === undefined ? {} : { sourceType }) };
|
|
110
|
+
}, options.onPartial)
|
|
111
|
+
};
|
|
112
|
+
});
|
|
28
113
|
}
|
|
29
114
|
};
|
|
30
115
|
}
|
|
31
|
-
|
|
116
|
+
/** UTC defaults and timezone conversion are CLI-owned, unlike service business limits. */
|
|
117
|
+
export function normalizeCreditsUsageListInput(input, now = new Date()) {
|
|
118
|
+
const from = input.from === undefined
|
|
119
|
+
? new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString() : timestamp(input.from);
|
|
120
|
+
const to = input.to === undefined
|
|
121
|
+
? new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1) - 1).toISOString() : timestamp(input.to);
|
|
122
|
+
const limit = input.limit ?? 20;
|
|
123
|
+
if (timestampAfter(from, to) || !Number.isSafeInteger(limit) || limit < 1)
|
|
124
|
+
throw new RangeError("Invalid credits time range or page size.");
|
|
125
|
+
if (input.cursor !== undefined && input.cursor.trim() === "")
|
|
126
|
+
throw new RangeError("Empty credits cursor.");
|
|
127
|
+
return { from, to, limit, ...(input.cursor === undefined ? {} : { cursor: input.cursor }) };
|
|
128
|
+
}
|
|
129
|
+
function findCreditsRecords(value) {
|
|
32
130
|
if (Array.isArray(value)) {
|
|
33
|
-
const
|
|
34
|
-
if (!
|
|
131
|
+
const records = value.filter((candidate) => (isRecord(candidate) && candidate.goods_type_enum === "GAODOU"));
|
|
132
|
+
if (!records.length)
|
|
35
133
|
throw new RemoteProtocolError();
|
|
36
|
-
return
|
|
134
|
+
return records;
|
|
37
135
|
}
|
|
38
136
|
if (!isRecord(value))
|
|
39
137
|
throw new RemoteProtocolError();
|
|
@@ -41,13 +139,85 @@ function findCreditsRecord(value) {
|
|
|
41
139
|
const record = candidates.find(isRecord);
|
|
42
140
|
if (!record)
|
|
43
141
|
throw new RemoteProtocolError();
|
|
44
|
-
return record;
|
|
142
|
+
return [record];
|
|
143
|
+
}
|
|
144
|
+
function readUsageRecord(value, warn) {
|
|
145
|
+
if (!isRecord(value))
|
|
146
|
+
throw new RemoteProtocolError();
|
|
147
|
+
let recordedAt;
|
|
148
|
+
try {
|
|
149
|
+
recordedAt = timestamp(requiredString(value.record_at));
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
throw new RemoteProtocolError();
|
|
153
|
+
}
|
|
154
|
+
const recordMode = optionalString(value.record_mode, warn);
|
|
155
|
+
const description = optionalString(value.consume_desc, warn);
|
|
156
|
+
const scene = optionalNumber(value.consume_scene, warn);
|
|
157
|
+
const referenceId = optionalString(value.reference_id, warn);
|
|
158
|
+
const userId = optionalString(value.uc_id, warn);
|
|
159
|
+
const userName = optionalString(value.user_name, warn);
|
|
160
|
+
return {
|
|
161
|
+
id: requiredString(value.record_id), changeType: requiredString(value.change_type),
|
|
162
|
+
amount: amount(value.usage), recordedAt,
|
|
163
|
+
...(recordMode === undefined ? {} : { recordMode }), ...(description === undefined ? {} : { description }),
|
|
164
|
+
...(scene === undefined ? {} : { scene }), ...(referenceId === undefined ? {} : { referenceId }),
|
|
165
|
+
...(userId === undefined && userName === undefined ? {} : { user: {
|
|
166
|
+
...(userId === undefined ? {} : { id: userId }), ...(userName === undefined ? {} : { name: userName })
|
|
167
|
+
} })
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
function amount(value) {
|
|
171
|
+
return creditAmountNumber(readCreditAmount(value));
|
|
45
172
|
}
|
|
46
|
-
function
|
|
47
|
-
if (typeof value !== "
|
|
173
|
+
function requiredString(value) {
|
|
174
|
+
if (typeof value !== "string" || value.trim() === "")
|
|
175
|
+
throw new RemoteProtocolError();
|
|
176
|
+
return value;
|
|
177
|
+
}
|
|
178
|
+
function optionalString(value, warn) {
|
|
179
|
+
if (value == null)
|
|
48
180
|
return undefined;
|
|
49
|
-
|
|
50
|
-
|
|
181
|
+
if (typeof value !== "string") {
|
|
182
|
+
warn?.();
|
|
183
|
+
return undefined;
|
|
184
|
+
}
|
|
185
|
+
return value;
|
|
186
|
+
}
|
|
187
|
+
function optionalNumber(value, warn) {
|
|
188
|
+
if (value == null)
|
|
189
|
+
return undefined;
|
|
190
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
191
|
+
warn?.();
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
return value;
|
|
195
|
+
}
|
|
196
|
+
function timestamp(value) {
|
|
197
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(?:Z|[+-]\d{2}:\d{2})$/i.exec(value);
|
|
198
|
+
const parsed = Date.parse(value);
|
|
199
|
+
if (!match || !Number.isFinite(parsed))
|
|
200
|
+
throw new RangeError("A timestamp with an explicit timezone is required.");
|
|
201
|
+
const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]);
|
|
202
|
+
const monthDays = [31, year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
203
|
+
if (month < 1 || month > 12 || day < 1 || day > monthDays[month - 1] || Number(match[4]) > 23 || Number(match[5]) > 59 || Number(match[6]) > 59) {
|
|
204
|
+
throw new RangeError("Invalid calendar timestamp.");
|
|
205
|
+
}
|
|
206
|
+
const normalized = new Date(parsed).toISOString();
|
|
207
|
+
// Date normalizes the offset but retains only milliseconds; preserve any finer digits.
|
|
208
|
+
return `${normalized.slice(0, -1)}${match[7]?.slice(3) ?? ""}Z`;
|
|
209
|
+
}
|
|
210
|
+
function timestampAfter(from, to) {
|
|
211
|
+
const fromPoint = from.indexOf(".");
|
|
212
|
+
const toPoint = to.indexOf(".");
|
|
213
|
+
const fromSeconds = Date.parse(`${from.slice(0, fromPoint)}Z`);
|
|
214
|
+
const toSeconds = Date.parse(`${to.slice(0, toPoint)}Z`);
|
|
215
|
+
if (fromSeconds !== toSeconds)
|
|
216
|
+
return fromSeconds > toSeconds;
|
|
217
|
+
const fromFraction = from.slice(fromPoint + 1, -1);
|
|
218
|
+
const toFraction = to.slice(toPoint + 1, -1);
|
|
219
|
+
const precision = Math.max(fromFraction.length, toFraction.length);
|
|
220
|
+
return fromFraction.padEnd(precision, "0") > toFraction.padEnd(precision, "0");
|
|
51
221
|
}
|
|
52
222
|
function isRecord(value) {
|
|
53
223
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { filterUrlParameters } from "../../platform/public-url.js";
|
|
2
2
|
import { parseSafeRemoteAssetUrl } from "../../platform/url-safety.js";
|
|
3
3
|
const sourcePresence = new WeakMap();
|
|
4
4
|
/** Internal presence evidence survives public URL safety filtering without exposing the URL. */
|
|
@@ -91,11 +91,8 @@ function safePublicUrl(value) {
|
|
|
91
91
|
return undefined;
|
|
92
92
|
try {
|
|
93
93
|
const url = parseSafeRemoteAssetUrl(raw);
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
url.searchParams.delete(key);
|
|
97
|
-
}
|
|
98
|
-
return url.href;
|
|
94
|
+
const publicUrl = filterUrlParameters(url);
|
|
95
|
+
return publicUrl.href === url.href ? raw : publicUrl.href;
|
|
99
96
|
}
|
|
100
97
|
catch {
|
|
101
98
|
return undefined;
|
|
@@ -45,6 +45,8 @@ function nonblank(value) {
|
|
|
45
45
|
function finiteNumber(value) {
|
|
46
46
|
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
47
47
|
}
|
|
48
|
+
// 2.1.x promises numeric tag/folder counts. An omitted count deliberately remains 0 for compatibility.
|
|
49
|
+
// This exception does not apply to prices, usage, or balances.
|
|
48
50
|
function nonnegativeInteger(value) {
|
|
49
51
|
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : 0;
|
|
50
52
|
}
|
|
@@ -61,10 +63,16 @@ function optionalString(value) {
|
|
|
61
63
|
const projected = String(value);
|
|
62
64
|
return projected.trim() === "" ? undefined : projected;
|
|
63
65
|
}
|
|
64
|
-
function
|
|
66
|
+
function warnSkipped(total, kept, warn) {
|
|
67
|
+
if (total > 0 && !kept)
|
|
68
|
+
throw new RemoteProtocolError({}, undefined, "DAM_NO_READABLE_ROWS");
|
|
69
|
+
if (total > kept)
|
|
70
|
+
warn?.(total - kept);
|
|
71
|
+
}
|
|
72
|
+
function folderRows(value, warn) {
|
|
65
73
|
if (!Array.isArray(value))
|
|
66
74
|
throw new RemoteProtocolError();
|
|
67
|
-
|
|
75
|
+
const result = value.flatMap((candidate) => {
|
|
68
76
|
const item = record(candidate);
|
|
69
77
|
const folderId = nonblank(item?.id);
|
|
70
78
|
const title = nonblank(item?.title);
|
|
@@ -92,6 +100,8 @@ function folderRows(value) {
|
|
|
92
100
|
...(updatedAt === undefined ? {} : { updated_at: updatedAt })
|
|
93
101
|
}];
|
|
94
102
|
});
|
|
103
|
+
warnSkipped(value.length, result.length, warn);
|
|
104
|
+
return result;
|
|
95
105
|
}
|
|
96
106
|
function folderPagination(headers) {
|
|
97
107
|
const raw = headers.get("x-pagination");
|
|
@@ -109,16 +119,16 @@ function folderPagination(headers) {
|
|
|
109
119
|
const pageSize = pagination?.size;
|
|
110
120
|
const total = pagination?.total;
|
|
111
121
|
if (!Number.isInteger(page) || page < 1
|
|
112
|
-
|| !Number.isInteger(pageSize) || pageSize < 1
|
|
122
|
+
|| !Number.isInteger(pageSize) || pageSize < 1
|
|
113
123
|
|| !Number.isInteger(total) || total < 0) {
|
|
114
124
|
throw new RemoteProtocolError();
|
|
115
125
|
}
|
|
116
126
|
return { page: page, pageSize: pageSize, total: total };
|
|
117
127
|
}
|
|
118
|
-
function tagRows(value) {
|
|
128
|
+
function tagRows(value, warn) {
|
|
119
129
|
if (!Array.isArray(value))
|
|
120
130
|
throw new RemoteProtocolError();
|
|
121
|
-
|
|
131
|
+
const result = value.flatMap((candidate) => {
|
|
122
132
|
const item = record(candidate);
|
|
123
133
|
const tagId = nonblank(item?.id);
|
|
124
134
|
const name = nonblank(item?.name);
|
|
@@ -132,6 +142,8 @@ function tagRows(value) {
|
|
|
132
142
|
asset_count: nonnegativeInteger(item?.file_count)
|
|
133
143
|
}];
|
|
134
144
|
});
|
|
145
|
+
warnSkipped(value.length, result.length, warn);
|
|
146
|
+
return result;
|
|
135
147
|
}
|
|
136
148
|
function downloadUrls(value, headers, status) {
|
|
137
149
|
if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
|
|
@@ -321,7 +333,7 @@ function firstValue(response, keys) {
|
|
|
321
333
|
}
|
|
322
334
|
return undefined;
|
|
323
335
|
}
|
|
324
|
-
function searchResult(response, input) {
|
|
336
|
+
function searchResult(response, input, warn, warnPagination) {
|
|
325
337
|
const items = searchItems(response);
|
|
326
338
|
if (items === undefined)
|
|
327
339
|
throw new RemoteRequestError();
|
|
@@ -329,13 +341,16 @@ function searchResult(response, input) {
|
|
|
329
341
|
const asset = projectDamAssetSummary(item);
|
|
330
342
|
return asset === undefined ? [] : [asset];
|
|
331
343
|
});
|
|
344
|
+
warnSkipped(items.length, assets.length, warn);
|
|
332
345
|
const suppliedTotal = finiteNumber(firstValue(response, ["total", "count"]));
|
|
333
|
-
const
|
|
346
|
+
const knownTotal = suppliedTotal !== undefined && suppliedTotal >= 0;
|
|
347
|
+
const total = knownTotal ? suppliedTotal : items.length;
|
|
334
348
|
const suppliedFinish = firstValue(response, ["finish"]);
|
|
335
|
-
const finish = typeof suppliedFinish === "boolean"
|
|
336
|
-
? suppliedFinish
|
|
337
|
-
: items.length >= total;
|
|
338
349
|
const cursor = nonblank(firstValue(response, ["query_id", "cursor"]));
|
|
350
|
+
const finish = typeof suppliedFinish === "boolean" ? suppliedFinish
|
|
351
|
+
: knownTotal ? items.length >= total : cursor === undefined;
|
|
352
|
+
if (!knownTotal || typeof suppliedFinish !== "boolean")
|
|
353
|
+
warnPagination?.();
|
|
339
354
|
return {
|
|
340
355
|
repository_ids: input.repositoryIds,
|
|
341
356
|
page_size: input.pageSize,
|
|
@@ -378,16 +393,16 @@ export function createDamApiAdapter(dependencies) {
|
|
|
378
393
|
...(input.type === undefined
|
|
379
394
|
? {}
|
|
380
395
|
: { content_format_list: contentFormats[input.type] }),
|
|
381
|
-
...(input.assetFormats === undefined
|
|
396
|
+
...(input.assetFormats === undefined
|
|
382
397
|
? {}
|
|
383
398
|
: { format: input.assetFormats }),
|
|
384
|
-
...(input.tagIds === undefined
|
|
399
|
+
...(input.tagIds === undefined
|
|
385
400
|
? {}
|
|
386
401
|
: { tag_ids: input.tagIds })
|
|
387
402
|
},
|
|
388
403
|
...requestContext(input)
|
|
389
404
|
});
|
|
390
|
-
return searchResult(response, input);
|
|
405
|
+
return searchResult(response, input, dependencies.onPartial, dependencies.onPaginationFallback);
|
|
391
406
|
},
|
|
392
407
|
async listFolders(input) {
|
|
393
408
|
const response = await dependencies.transport.getJsonResponse({
|
|
@@ -411,7 +426,7 @@ export function createDamApiAdapter(dependencies) {
|
|
|
411
426
|
page: pagination.page,
|
|
412
427
|
page_size: pagination.pageSize,
|
|
413
428
|
total: pagination.total,
|
|
414
|
-
folders: folderRows(response.body)
|
|
429
|
+
folders: folderRows(response.body, dependencies.onPartial)
|
|
415
430
|
};
|
|
416
431
|
},
|
|
417
432
|
async listTags(input) {
|
|
@@ -424,7 +439,7 @@ export function createDamApiAdapter(dependencies) {
|
|
|
424
439
|
},
|
|
425
440
|
...requestContext(input)
|
|
426
441
|
});
|
|
427
|
-
return { repository_id: input.repositoryId, tags: tagRows(response) };
|
|
442
|
+
return { repository_id: input.repositoryId, tags: tagRows(response, dependencies.onPartial) };
|
|
428
443
|
},
|
|
429
444
|
async getDownloadUrls(input) {
|
|
430
445
|
const assetId = normalizeDamAssetId(input.assetId);
|
|
@@ -77,12 +77,18 @@ function enterpriseRepositories(value) {
|
|
|
77
77
|
}];
|
|
78
78
|
});
|
|
79
79
|
}
|
|
80
|
-
export function normalizeRepositoryCatalog(privateRows, teamRows, enterpriseRows) {
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
80
|
+
export function normalizeRepositoryCatalog(privateRows, teamRows, enterpriseRows, onUnrepresented) {
|
|
81
|
+
const personal = privateRepositories(privateRows), teams = teamRepositories(teamRows), enterprise = enterpriseRepositories(enterpriseRows);
|
|
82
|
+
const groups = [
|
|
83
|
+
["personal", rows(privateRows).filter(row => record(row)?.type !== 8).length, personal.length],
|
|
84
|
+
["team", rows(teamRows).length, teams.length], ["enterprise", rows(enterpriseRows).length, enterprise.length]
|
|
85
85
|
];
|
|
86
|
+
const incomplete = groups.filter(([, total, count]) => total > count);
|
|
87
|
+
const merged = [...personal, ...teams, ...enterprise];
|
|
88
|
+
if (incomplete.length && !merged.length)
|
|
89
|
+
throw new RemoteProtocolError({}, undefined, "DAM_NO_READABLE_REPOSITORIES");
|
|
90
|
+
for (const [source] of incomplete)
|
|
91
|
+
onUnrepresented?.(source);
|
|
86
92
|
const seen = new Set();
|
|
87
93
|
const unique = merged.filter((repository) => {
|
|
88
94
|
if (seen.has(repository.repository_id))
|
|
@@ -91,7 +97,7 @@ export function normalizeRepositoryCatalog(privateRows, teamRows, enterpriseRows
|
|
|
91
97
|
return true;
|
|
92
98
|
});
|
|
93
99
|
const defaultIndex = unique.findIndex((repository) => repository.type === "personal");
|
|
94
|
-
const selectedIndex = defaultIndex === -1 && unique.length > 0 ? 0 : defaultIndex;
|
|
100
|
+
const selectedIndex = defaultIndex === -1 && !incomplete.length && unique.length > 0 ? 0 : defaultIndex;
|
|
95
101
|
return unique.map((repository, index) => ({
|
|
96
102
|
...repository,
|
|
97
103
|
is_default: index === selectedIndex
|
|
@@ -107,21 +113,24 @@ function requestContext(input) {
|
|
|
107
113
|
export function createDamRepositoryCatalog(dependencies) {
|
|
108
114
|
return {
|
|
109
115
|
async list(input) {
|
|
110
|
-
const [
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
116
|
+
const sources = ["/tb-dam/repositories", "/tb-dam/teams", "/dam/org-repositories"];
|
|
117
|
+
const results = await Promise.allSettled(sources.map(async (path) => rows(await dependencies.transport.getJson({
|
|
118
|
+
path, ...requestContext(input)
|
|
119
|
+
}))));
|
|
120
|
+
input.signal.throwIfAborted();
|
|
121
|
+
const failures = results.flatMap((r, i) => r.status === "rejected" ? [{ i, error: r.reason }] : []);
|
|
122
|
+
const [p, t, e] = results.map(r => r.status === "fulfilled" ? r.value : []);
|
|
123
|
+
const repositories = normalizeRepositoryCatalog(p, t, e, dependencies.onPartial);
|
|
124
|
+
if (failures.length && !repositories.length)
|
|
125
|
+
throw failures[0].error;
|
|
126
|
+
for (const failure of failures)
|
|
127
|
+
dependencies.onPartial?.(["personal", "team", "enterprise"][failure.i]);
|
|
128
|
+
if (failures.length && !repositories.some(r => r.type === "personal")) {
|
|
129
|
+
if (!input.allowPartial)
|
|
130
|
+
throw failures[0].error;
|
|
131
|
+
return repositories.map(r => ({ ...r, is_default: false }));
|
|
132
|
+
}
|
|
133
|
+
return repositories;
|
|
125
134
|
}
|
|
126
135
|
};
|
|
127
136
|
}
|