@insmind/cli 1.9.0 → 2.0.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.
Files changed (69) hide show
  1. package/dist/bin/insmind-cli.js +32 -25
  2. package/dist/bin/task-worker.js +4 -1
  3. package/dist/src/analytics/device.js +2 -2
  4. package/dist/src/bootstrap/create-cli.js +10 -8
  5. package/dist/src/bootstrap/create-runtime.js +29 -23
  6. package/dist/src/bootstrap/run-task-worker.js +7 -2
  7. package/dist/src/bootstrap/validators.js +15 -6
  8. package/dist/src/cli/action-binding.js +39 -0
  9. package/dist/src/cli/agent-commands.js +8 -12
  10. package/dist/src/cli/dam-commands.js +6 -5
  11. package/dist/src/cli/editor-commands.js +10 -5
  12. package/dist/src/cli/errors.js +60 -12
  13. package/dist/src/cli/host-input.js +34 -0
  14. package/dist/src/cli/model-commands.js +4 -3
  15. package/dist/src/cli/observed-errors.js +3 -1
  16. package/dist/src/cli/tool-commands.js +7 -9
  17. package/dist/src/contracts/creation-input.js +20 -0
  18. package/dist/src/features/agent/creative-agent-adapter.js +37 -11
  19. package/dist/src/features/agent/creative-protocol.js +21 -19
  20. package/dist/src/features/agent/creative-stream.js +54 -6
  21. package/dist/src/features/agent/result-reader.js +3 -1
  22. package/dist/src/features/agent/use-cases.js +6 -31
  23. package/dist/src/features/auth/access-policy.js +1 -3
  24. package/dist/src/features/auth/credential-store.js +6 -10
  25. package/dist/src/features/auth/sso-service.js +28 -10
  26. package/dist/src/features/auth/state.js +6 -0
  27. package/dist/src/features/auth/use-cases.js +91 -32
  28. package/dist/src/features/credits/use-cases.js +1 -1
  29. package/dist/src/features/dam/asset-projection.js +10 -1
  30. package/dist/src/features/dam/dam-api-adapter.js +30 -15
  31. package/dist/src/features/dam/file-downloader.js +2 -1
  32. package/dist/src/features/dam/input.js +23 -0
  33. package/dist/src/features/dam/use-cases.js +39 -29
  34. package/dist/src/features/editor/bridge-client.js +1 -1
  35. package/dist/src/features/editor/use-cases.js +6 -8
  36. package/dist/src/features/org/use-cases.js +3 -3
  37. package/dist/src/features/skill/installer.js +24 -22
  38. package/dist/src/features/task/store.js +31 -17
  39. package/dist/src/features/task/task-background.js +67 -19
  40. package/dist/src/features/task/use-cases.js +131 -88
  41. package/dist/src/features/tool/canvas-media.js +82 -27
  42. package/dist/src/features/tool/canvas-models.js +21 -4
  43. package/dist/src/features/tool/canvas-tool-adapter.js +29 -20
  44. package/dist/src/features/tool/canvas-video.js +2 -4
  45. package/dist/src/features/tool/dynamic-schema.js +32 -63
  46. package/dist/src/features/tool/matting-billing.js +38 -26
  47. package/dist/src/features/tool/mns-catalog-adapter.js +9 -2
  48. package/dist/src/features/tool/scene-catalog-adapter.js +0 -1
  49. package/dist/src/features/tool/tool-api-adapter.js +19 -16
  50. package/dist/src/features/tool/use-cases.js +24 -35
  51. package/dist/src/platform/file-lock.js +58 -15
  52. package/dist/src/platform/input-uri.js +105 -0
  53. package/dist/src/platform/json-input.js +1 -1
  54. package/dist/src/platform/local-json-file.js +7 -4
  55. package/dist/src/platform/remote-error-evidence.js +23 -1
  56. package/dist/src/platform/safe-upload-file.js +24 -4
  57. package/dist/src/platform/schema-issues.js +18 -0
  58. package/dist/src/platform/signed-http-transport.js +95 -37
  59. package/dist/src/platform/text-output.js +55 -13
  60. package/dist/src/telemetry/failure-summary.js +53 -2
  61. package/dist/src/telemetry/host-diagnostics.js +95 -0
  62. package/dist/src/telemetry/invocation.js +107 -23
  63. package/dist/src/telemetry/process-errors.js +38 -4
  64. package/dist/src/telemetry/sls-sink.js +71 -26
  65. package/package.json +4 -4
  66. package/skills/insmind-cli/SKILL.md +1 -0
  67. package/skills/insmind-cli/references/editor.md +1 -1
  68. package/skills/insmind-cli/references/generation-constraints.md +3 -1
  69. package/skills/insmind-cli/references/tool.md +2 -3
@@ -12,7 +12,6 @@ export class AuthExpiredError extends Error {
12
12
  this.name = "AuthExpiredError";
13
13
  }
14
14
  }
15
- const REFRESH_WINDOW_MS = 5 * 60 * 1000;
16
15
  const organizationRefreshes = new Map();
17
16
  export function createAccessPolicies(dependencies) {
18
17
  async function readValidState(signal) {
@@ -102,8 +101,7 @@ export function createAccessPolicies(dependencies) {
102
101
  };
103
102
  }
104
103
  function bindingNeedsRefresh(organization, now) {
105
- return organization.bindExpiresAt === undefined
106
- || Date.parse(organization.bindExpiresAt) <= now.getTime() + REFRESH_WINDOW_MS;
104
+ return organization.bindExpiresAt !== undefined && Date.parse(organization.bindExpiresAt) <= now.getTime();
107
105
  }
108
106
  function sameOrganization(current, expected) {
109
107
  return current?.credential.accessKey === expected.credential.accessKey
@@ -1,11 +1,12 @@
1
1
  import { homedir } from "node:os";
2
2
  import { join } from "node:path";
3
3
  import { createLocalJsonFile } from "../../platform/local-json-file.js";
4
- import { AuthStateInvalidError, parseStoredAuthState } from "./state.js";
4
+ import { AuthStateInvalidError, AuthStateUnavailableError, parseStoredAuthState } from "./state.js";
5
5
  export function createLocalCredentialStore(options = {}) {
6
6
  const file = options.file ?? createLocalJsonFile({
7
7
  directory: join(options.homeDirectory ?? homedir(), options.stateDirectory ?? ".gd"),
8
- filename: "credentials.json"
8
+ filename: "credentials.json",
9
+ role: "credentials"
9
10
  });
10
11
  return {
11
12
  async read() {
@@ -28,7 +29,7 @@ export function createLocalCredentialStore(options = {}) {
28
29
  catch (cause) {
29
30
  if (cause instanceof AuthStateInvalidError)
30
31
  throw cause;
31
- throw invalidState(cause);
32
+ throw new AuthStateUnavailableError({ cause });
32
33
  }
33
34
  },
34
35
  async write(state) {
@@ -39,7 +40,7 @@ export function createLocalCredentialStore(options = {}) {
39
40
  catch (cause) {
40
41
  if (cause instanceof AuthStateInvalidError)
41
42
  throw cause;
42
- throw invalidState(cause);
43
+ throw new AuthStateUnavailableError({ cause });
43
44
  }
44
45
  },
45
46
  async remove() {
@@ -47,7 +48,7 @@ export function createLocalCredentialStore(options = {}) {
47
48
  await file.remove();
48
49
  }
49
50
  catch (cause) {
50
- throw invalidState(cause);
51
+ throw new AuthStateUnavailableError({ cause });
51
52
  }
52
53
  }
53
54
  };
@@ -55,8 +56,3 @@ export function createLocalCredentialStore(options = {}) {
55
56
  function serialize(state) {
56
57
  return `${JSON.stringify(state, null, 2)}\n`;
57
58
  }
58
- function invalidState(cause) {
59
- return new AuthStateInvalidError({
60
- cause, reason: "local_io"
61
- });
62
- }
@@ -35,6 +35,15 @@ export function createSsoService(options) {
35
35
  if (!baseUrl.pathname.endsWith("/"))
36
36
  baseUrl.pathname += "/";
37
37
  const requests = new WeakMap();
38
+ const requestStartedAt = new WeakMap();
39
+ function responseDiagnostics(response) {
40
+ const requestId = ["x-request-id", "x-gd-request-id", "request-id"].map(key => response.headers.get(key))
41
+ .find((value) => value !== null && /^[A-Za-z0-9_.:-]{1,128}$/u.test(value));
42
+ const startedAt = requestStartedAt.get(response);
43
+ return { requestTimeoutMs: options.timeoutMs ?? 30_000,
44
+ ...(startedAt === undefined ? {} : { requestDurationMs: Math.max(0, Date.now() - startedAt) }),
45
+ ...(requestId ? { requestId } : {}) };
46
+ }
38
47
  async function responseError(response, networkError) {
39
48
  let evidence = {};
40
49
  if (!response.ok && !response.bodyUsed) {
@@ -51,16 +60,16 @@ export function createSsoService(options) {
51
60
  ...remoteErrorEvidence({ request: requests.get(response),
52
61
  ...(evidence.remoteBody === undefined ? {} : { response: evidence.remoteBody }),
53
62
  ...(networkError === undefined ? {} : { network: networkFailure(networkError) }) })
54
- }, networkError);
63
+ }, networkError, responseDiagnostics(response));
55
64
  }
56
65
  function invalidFields(response, phase, fields) {
57
- return new SsoRequestError(response.status, { diagnosticReason: "SSO_RESPONSE_FIELDS_MISSING" }, undefined, { ssoPhase: phase, ssoInvalidFields: Object.entries(fields).filter(([, valid]) => !valid).map(([key]) => key).join(",") });
66
+ return new SsoRequestError(response.status, { diagnosticReason: "SSO_RESPONSE_FIELDS_MISSING" }, undefined, { ...responseDiagnostics(response), ssoPhase: phase, ssoInvalidFields: Object.entries(fields).filter(([, valid]) => !valid).map(([key]) => key).join(",") });
58
67
  }
59
68
  async function responseRecord(response) {
60
69
  if (!response.ok) {
61
- // OAuth pending/slow_down are normal token polling responses.
70
+ // OAuth polling states can use HTTP 400 as well as HTTP 200.
62
71
  const body = await response.clone().json().catch(() => undefined);
63
- if (isRecord(body) && ["authorization_pending", "slow_down"].includes(String(body.error).toLowerCase()))
72
+ if (isRecord(body) && ["authorization_pending", "slow_down", "expired_token"].includes(String(body.error).toLowerCase()))
64
73
  return body;
65
74
  throw await responseError(response);
66
75
  }
@@ -78,22 +87,27 @@ export function createSsoService(options) {
78
87
  signal.throwIfAborted();
79
88
  const url = new URL(relativeUrl, baseUrl);
80
89
  const requestInfo = { method, path: url.pathname };
90
+ const startedAt = Date.now();
91
+ const timeoutMs = options.timeoutMs ?? 30_000;
92
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
81
93
  try {
82
94
  const response = await options.fetch(url, {
83
95
  method,
84
96
  headers: { Accept: "application/json", ...(options.traceparent ? { traceparent: options.traceparent() } : {}) },
85
97
  signal: AbortSignal.any([
86
98
  signal,
87
- AbortSignal.timeout(options.timeoutMs ?? 30_000)
99
+ timeoutSignal
88
100
  ])
89
101
  });
90
102
  requests.set(response, requestInfo);
103
+ requestStartedAt.set(response, startedAt);
91
104
  return response;
92
105
  }
93
106
  catch (error) {
94
107
  if (isInterruption(error, signal))
95
108
  throw signal.reason;
96
- throw new SsoRequestError(undefined, remoteErrorEvidence({ request: requestInfo, network: networkFailure(error) }), error);
109
+ throw new SsoRequestError(undefined, remoteErrorEvidence({ request: requestInfo, network: networkFailure(error) }), error, { requestTimeoutMs: timeoutMs, requestDurationMs: Math.max(0, Date.now() - startedAt),
110
+ abortSource: timeoutSignal.aborted ? "request_timeout" : "none" });
97
111
  }
98
112
  }
99
113
  return {
@@ -108,11 +122,11 @@ export function createSsoService(options) {
108
122
  const deviceCode = nonEmptyString(body.device_code);
109
123
  const expiresInSeconds = positiveNumber(body.expires_in);
110
124
  const intervalSeconds = positiveNumber(body.interval);
111
- if (!authorizeCode || !deviceCode || !expiresInSeconds || !intervalSeconds) {
125
+ if (!authorizeCode || !deviceCode || !intervalSeconds) {
112
126
  throw invalidFields(response, "authorize", { authorize_code: authorizeCode, device_code: deviceCode,
113
- expires_in: expiresInSeconds, interval: intervalSeconds });
127
+ interval: intervalSeconds });
114
128
  }
115
- return { authorizeCode, deviceCode, expiresInSeconds, intervalSeconds };
129
+ return { authorizeCode, deviceCode, ...(expiresInSeconds ? { expiresInSeconds } : {}), intervalSeconds };
116
130
  },
117
131
  async pollDeviceToken(deviceCode, signal) {
118
132
  const query = new URLSearchParams({
@@ -126,6 +140,8 @@ export function createSsoService(options) {
126
140
  return { status: "pending" };
127
141
  if (error === "slow_down")
128
142
  return { status: "slow_down" };
143
+ if (error === "expired_token")
144
+ return { status: "expired", httpStatus: response.status };
129
145
  if (!response.ok)
130
146
  throw await responseError(response);
131
147
  const accessKey = nonEmptyString(body.ak);
@@ -238,7 +254,9 @@ function positiveNumber(value) {
238
254
  }
239
255
  function dateString(value) {
240
256
  const text = nonEmptyString(value);
241
- return text && !Number.isNaN(Date.parse(text)) ? text : undefined;
257
+ if (!text || !Number.isFinite(Date.parse(text)))
258
+ return undefined;
259
+ return /^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/iu.test(text) ? text : new Date(text).toISOString();
242
260
  }
243
261
  function identifier(value) {
244
262
  if (typeof value === "number" && Number.isFinite(value))
@@ -6,6 +6,12 @@ export class AuthStateInvalidError extends Error {
6
6
  this.reason = options?.reason ?? "invalid_data";
7
7
  }
8
8
  }
9
+ export class AuthStateUnavailableError extends Error {
10
+ constructor(options) {
11
+ super("无法访问本地登录状态,登录有效性未知。", options);
12
+ this.name = "AuthStateUnavailableError";
13
+ }
14
+ }
9
15
  export function parseStoredAuthState(value) {
10
16
  try {
11
17
  if (!isRecord(value))
@@ -1,8 +1,13 @@
1
1
  import { isInterruption } from "../../platform/interruption.js";
2
2
  import { requireUserIdentity, UserIdentityMissingError } from "./state.js";
3
+ const AUTHORIZATION_WAIT_TIMEOUT_MS = 10 * 60 * 1000;
3
4
  export class DeviceAuthorizationExpiredError extends Error {
4
- constructor(commandName = "gd-cli") {
5
+ expirationSource;
6
+ httpStatus;
7
+ constructor(commandName = "gd-cli", expirationSource = "cli_timeout", httpStatus) {
5
8
  super(`Authorization expired. Run ${commandName} auth login again.`);
9
+ this.expirationSource = expirationSource;
10
+ this.httpStatus = httpStatus;
6
11
  this.name = "DeviceAuthorizationExpiredError";
7
12
  }
8
13
  }
@@ -78,44 +83,98 @@ export function createAuthUseCases(dependencies) {
78
83
  organizationSelected: existing.organization !== undefined
79
84
  };
80
85
  }
86
+ const authorizationStartedAt = dependencies.now().getTime();
87
+ const deadline = authorizationStartedAt + AUTHORIZATION_WAIT_TIMEOUT_MS;
88
+ const deadlineController = new AbortController();
89
+ const authorizationSignal = AbortSignal.any([input.signal, deadlineController.signal]);
90
+ const deadlineTimer = setTimeout(() => deadlineController.abort(new DeviceAuthorizationExpiredError(dependencies.commandName)), AUTHORIZATION_WAIT_TIMEOUT_MS);
91
+ const withinAuthorization = (run) => {
92
+ if (dependencies.now().getTime() >= deadline)
93
+ return Promise.reject(new DeviceAuthorizationExpiredError(dependencies.commandName));
94
+ if (authorizationSignal.aborted)
95
+ return Promise.reject(authorizationSignal.reason);
96
+ return new Promise((resolve, reject) => {
97
+ const abort = () => reject(authorizationSignal.reason);
98
+ authorizationSignal.addEventListener("abort", abort, { once: true });
99
+ Promise.resolve().then(() => { authorizationSignal.throwIfAborted(); return run(); }).then(result => {
100
+ if (dependencies.now().getTime() > deadline)
101
+ reject(new DeviceAuthorizationExpiredError(dependencies.commandName));
102
+ else
103
+ resolve(result);
104
+ }, reject).finally(() => authorizationSignal.removeEventListener("abort", abort));
105
+ });
106
+ };
107
+ let pollCount = 0;
108
+ dependencies.telemetry.annotate({ auth_started_at_ms: authorizationStartedAt,
109
+ auth_wait_timeout_ms: AUTHORIZATION_WAIT_TIMEOUT_MS, auth_deadline_at_ms: deadline });
110
+ const recordResult = (result) => {
111
+ clearTimeout(deadlineTimer);
112
+ dependencies.telemetry.annotate({ auth_result: result,
113
+ auth_elapsed_ms: Math.max(0, dependencies.now().getTime() - authorizationStartedAt), auth_poll_count: pollCount });
114
+ };
115
+ const recordFailure = (cause) => {
116
+ recordResult(isInterruption(cause, input.signal) ? "interrupted"
117
+ : cause instanceof DeviceAuthorizationExpiredError ? cause.expirationSource : "failed");
118
+ throw cause;
119
+ };
81
120
  const authorization = await dependencies.telemetry.stage("authorize", async () => {
82
- const authorization = await dependencies.sso.startDeviceAuthorization(input.signal);
83
- const authorizationUrl = new URL("/cli/device-authorization", dependencies.authPageOrigin);
84
- authorizationUrl.searchParams.set("code", authorization.authorizeCode);
85
- await input.interaction.showAuthorization(authorizationUrl);
86
- if (!input.noBrowser) {
87
- try {
88
- await dependencies.telemetry.stage("browser", () => input.interaction.openBrowser(authorizationUrl));
89
- }
90
- catch (cause) {
91
- if (isInterruption(cause, input.signal))
92
- throw input.signal.reason;
93
- if (input.requireBrowser)
94
- throw new BrowserOpenError(cause);
95
- input.interaction.warn(insmind
96
- ? "Could not open the browser. Open the authorization URL manually."
97
- : "无法自动打开浏览器,请手动访问授权链接。");
121
+ try {
122
+ const authorization = await withinAuthorization(() => dependencies.sso.startDeviceAuthorization(authorizationSignal));
123
+ if (authorization.expiresInSeconds !== undefined)
124
+ dependencies.telemetry.annotate({ auth_server_expires_in_s: authorization.expiresInSeconds });
125
+ const authorizationUrl = new URL("/cli/device-authorization", dependencies.authPageOrigin);
126
+ authorizationUrl.searchParams.set("code", authorization.authorizeCode);
127
+ await withinAuthorization(() => input.interaction.showAuthorization(authorizationUrl));
128
+ if (!input.noBrowser) {
129
+ try {
130
+ await dependencies.telemetry.stage("browser", () => withinAuthorization(() => input.interaction.openBrowser(authorizationUrl)));
131
+ }
132
+ catch (cause) {
133
+ if (isInterruption(cause, input.signal))
134
+ throw input.signal.reason;
135
+ if (cause instanceof DeviceAuthorizationExpiredError)
136
+ throw cause;
137
+ if (input.requireBrowser)
138
+ throw new BrowserOpenError(cause);
139
+ input.interaction.warn(insmind
140
+ ? "Could not open the browser. Open the authorization URL manually."
141
+ : "无法自动打开浏览器,请手动访问授权链接。");
142
+ }
98
143
  }
144
+ return authorization;
145
+ }
146
+ catch (cause) {
147
+ return recordFailure(cause);
99
148
  }
100
- return authorization;
101
149
  });
102
- const deadline = dependencies.now().getTime() + authorization.expiresInSeconds * 1000;
103
150
  let interval = authorization.intervalSeconds * 1000;
104
151
  const token = await dependencies.telemetry.stage("wait", async () => {
105
- while (true) {
106
- if (dependencies.now().getTime() + interval > deadline) {
107
- throw new DeviceAuthorizationExpiredError(dependencies.commandName);
152
+ try {
153
+ while (dependencies.now().getTime() < deadline) {
154
+ const remaining = deadline - dependencies.now().getTime();
155
+ await withinAuthorization(() => dependencies.sleep(Math.min(interval, remaining), authorizationSignal));
156
+ input.signal.throwIfAborted();
157
+ // Wait through the deadline without polling faster than the server permits.
158
+ if (remaining < interval || dependencies.now().getTime() >= deadline)
159
+ break;
160
+ pollCount += 1;
161
+ const result = await withinAuthorization(() => dependencies.sso.pollDeviceToken(authorization.deviceCode, authorizationSignal));
162
+ if (result.status === "pending")
163
+ continue;
164
+ if (result.status === "slow_down") {
165
+ interval += 5_000;
166
+ continue;
167
+ }
168
+ if (result.status === "expired") {
169
+ throw new DeviceAuthorizationExpiredError(dependencies.commandName, "server_expired", result.httpStatus);
170
+ }
171
+ recordResult("authorized");
172
+ return result;
108
173
  }
109
- await dependencies.sleep(interval, input.signal);
110
- input.signal.throwIfAborted();
111
- const result = await dependencies.sso.pollDeviceToken(authorization.deviceCode, input.signal);
112
- if (result.status === "pending")
113
- continue;
114
- if (result.status === "slow_down") {
115
- interval += 5_000;
116
- continue;
117
- }
118
- return result;
174
+ throw new DeviceAuthorizationExpiredError(dependencies.commandName);
175
+ }
176
+ catch (cause) {
177
+ return recordFailure(cause);
119
178
  }
120
179
  });
121
180
  let state = {
@@ -37,7 +37,7 @@ function findCreditsRecord(value) {
37
37
  }
38
38
  if (!isRecord(value))
39
39
  throw new RemoteProtocolError();
40
- const candidates = [value.GAODOU, value.data, isRecord(value.data) ? value.data.GAODOU : undefined];
40
+ const candidates = [value.GAODOU, isRecord(value.data) ? value.data.GAODOU : undefined, value.data];
41
41
  const record = candidates.find(isRecord);
42
42
  if (!record)
43
43
  throw new RemoteProtocolError();
@@ -1,5 +1,10 @@
1
1
  import { isSensitiveKey } from "../../platform/redact.js";
2
2
  import { parseSafeRemoteAssetUrl } from "../../platform/url-safety.js";
3
+ const sourcePresence = new WeakMap();
4
+ /** Internal presence evidence survives public URL safety filtering without exposing the URL. */
5
+ export function damAssetSourcePresent(asset) {
6
+ return sourcePresence.get(asset) ?? (typeof asset.url === "string" && asset.url.trim() !== "");
7
+ }
3
8
  const publicAssetTypes = new Set([
4
9
  "image",
5
10
  "video",
@@ -230,7 +235,7 @@ export function projectDamAssetDetail(value, fallback) {
230
235
  const asset = normalizeAsset(value, fallback);
231
236
  if (asset === undefined)
232
237
  return undefined;
233
- return compact({
238
+ const result = compact({
234
239
  asset_id: asset.asset_id,
235
240
  title: asset.title,
236
241
  description: asset.description,
@@ -251,6 +256,10 @@ export function projectDamAssetDetail(value, fallback) {
251
256
  created_at: asset.created_at,
252
257
  updated_at: asset.updated_at
253
258
  });
259
+ const item = findAssetRecord(value);
260
+ const origin = record(item?.origin_info) ?? record(item?.originInfo);
261
+ sourcePresence.set(result, [origin?.url, item?.origin_url, item?.url].some(value => nonblank(value) !== undefined));
262
+ return result;
254
263
  }
255
264
  export function projectDamAssetSummary(value) {
256
265
  const asset = normalizeAsset(value);
@@ -2,6 +2,7 @@ import { RemoteRequestError } from "../../platform/signed-http-transport.js";
2
2
  import { RemoteProtocolError } from "../../platform/remote-protocol.js";
3
3
  import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
4
4
  import { projectDamAssetDetail, projectDamAssetSummary } from "./asset-projection.js";
5
+ import { normalizeDamAssetId } from "./input.js";
5
6
  export class DamAssetNotFoundError extends Error {
6
7
  constructor() {
7
8
  super("DAM 素材不存在。");
@@ -9,9 +10,13 @@ export class DamAssetNotFoundError extends Error {
9
10
  }
10
11
  }
11
12
  export class DamAssetNotDownloadableError extends Error {
13
+ diagnosticSummary;
14
+ status;
12
15
  diagnosticReason = "ASSET_DOWNLOAD_URL_MISSING";
13
- constructor() {
16
+ constructor(diagnosticSummary = {}, status) {
14
17
  super("该 DAM 素材当前不可下载。");
18
+ this.diagnosticSummary = diagnosticSummary;
19
+ this.status = status;
15
20
  this.name = "DamAssetNotDownloadableError";
16
21
  }
17
22
  }
@@ -128,13 +133,17 @@ function tagRows(value) {
128
133
  }];
129
134
  });
130
135
  }
131
- function downloadUrls(value) {
136
+ function downloadUrls(value, headers, status) {
132
137
  if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
133
138
  throw new RemoteProtocolError();
134
139
  }
135
140
  const urls = value.filter((item) => (typeof item === "string" && item.trim() !== ""));
136
- if (urls.length === 0)
137
- throw new DamAssetNotDownloadableError();
141
+ if (urls.length === 0) {
142
+ const requestId = ["x-request-id", "x-gd-request-id", "request-id"]
143
+ .map(name => headers.get(name)).find((value) => value !== null && /^[A-Za-z0-9._:-]{1,128}$/u.test(value));
144
+ throw new DamAssetNotDownloadableError({ downloadPhase: "url_lookup", downloadUrlCount: 0,
145
+ ...(requestId === undefined ? {} : { requestId }) }, status);
146
+ }
138
147
  for (const value of urls) {
139
148
  try {
140
149
  const url = parseSafeRemoteAssetUrl(value);
@@ -346,7 +355,7 @@ function requestContext(input) {
346
355
  function recycleBody(input) {
347
356
  return {
348
357
  repository_id: input.repositoryId,
349
- file_ids: [input.assetId],
358
+ file_ids: [normalizeDamAssetId(input.assetId)],
350
359
  folder_ids: []
351
360
  };
352
361
  }
@@ -418,12 +427,13 @@ export function createDamApiAdapter(dependencies) {
418
427
  return { repository_id: input.repositoryId, tags: tagRows(response) };
419
428
  },
420
429
  async getDownloadUrls(input) {
421
- const response = await dependencies.transport.getJson({
422
- path: `/dam/asset/files/download/${encodeURIComponent(input.assetId)}/url-list`,
430
+ const assetId = normalizeDamAssetId(input.assetId);
431
+ const response = await dependencies.transport.getJsonResponse({
432
+ path: `/dam/asset/files/download/${encodeURIComponent(assetId)}/url-list`,
423
433
  query: { repository_id: input.repositoryId },
424
434
  ...requestContext(input)
425
435
  });
426
- return downloadUrls(response);
436
+ return downloadUrls(response.body, response.headers, response.status);
427
437
  },
428
438
  async getFolder(input) {
429
439
  let response;
@@ -443,12 +453,13 @@ export function createDamApiAdapter(dependencies) {
443
453
  return folderDetail(response);
444
454
  },
445
455
  async renameEntry(input) {
456
+ const entryId = input.kind === "asset" ? normalizeDamAssetId(input.entryId, "entry_id") : input.entryId;
446
457
  await dependencies.transport.putJson({
447
458
  path: input.kind === "asset"
448
- ? `/dam/asset/${encodeURIComponent(input.entryId)}/rename`
459
+ ? `/dam/asset/${encodeURIComponent(entryId)}/rename`
449
460
  : `/dam/folders/${encodeURIComponent(input.entryId)}/rename`,
450
461
  body: {
451
- id: input.entryId,
462
+ id: entryId,
452
463
  repository_id: input.repositoryId,
453
464
  title: input.title
454
465
  },
@@ -458,11 +469,12 @@ export function createDamApiAdapter(dependencies) {
458
469
  async submitEntryOperation(input) {
459
470
  assertSingleOperationInput(input);
460
471
  const asset = input.kind === "asset";
472
+ const entryId = asset ? normalizeDamAssetId(input.entryId, "entry_id") : input.entryId;
461
473
  const body = asset
462
474
  ? {
463
475
  source_infos: [{
464
476
  source_repository_id: input.sourceRepositoryId,
465
- content_ids: [input.entryId]
477
+ content_ids: [entryId]
466
478
  }],
467
479
  target_folder_id: input.targetFolderId,
468
480
  target_repository_id: input.targetRepositoryId,
@@ -500,10 +512,11 @@ export function createDamApiAdapter(dependencies) {
500
512
  return operationChildren(response);
501
513
  },
502
514
  async getAsset(input) {
515
+ const assetId = normalizeDamAssetId(input.assetId);
503
516
  let response;
504
517
  try {
505
518
  response = await dependencies.transport.getJson({
506
- path: `/dam/asset/${encodeURIComponent(input.assetId)}`,
519
+ path: `/dam/asset/${encodeURIComponent(assetId)}`,
507
520
  ...requestContext(input)
508
521
  });
509
522
  }
@@ -513,7 +526,7 @@ export function createDamApiAdapter(dependencies) {
513
526
  }
514
527
  throw error;
515
528
  }
516
- const asset = projectDamAssetDetail(response, input.assetId);
529
+ const asset = projectDamAssetDetail(response, assetId);
517
530
  if (asset === undefined)
518
531
  throw new RemoteRequestError();
519
532
  return asset;
@@ -527,9 +540,10 @@ export function createDamApiAdapter(dependencies) {
527
540
  return assetId(response);
528
541
  },
529
542
  async createMaterial(input) {
543
+ const body = { ...input.body, asset_info: { ...input.body.asset_info, id: normalizeDamAssetId(input.body.asset_info.id) } };
530
544
  const response = await dependencies.transport.postJson({
531
545
  path: "/dam/asset/createMaterial",
532
- body: input.body,
546
+ body,
533
547
  ...requestContext(input)
534
548
  });
535
549
  const asset = projectDamAssetDetail(response, input.fallback);
@@ -538,9 +552,10 @@ export function createDamApiAdapter(dependencies) {
538
552
  return asset;
539
553
  },
540
554
  async getBatchStatus(input) {
555
+ const assetId = normalizeDamAssetId(input.assetId);
541
556
  const response = await dependencies.transport.getJson({
542
557
  path: "/dam/asset/batch-status",
543
- query: { ids: input.assetId },
558
+ query: { ids: assetId },
544
559
  ...requestContext(input)
545
560
  });
546
561
  return projectDamAssetDetail(response, input.fallback) ?? null;
@@ -98,7 +98,8 @@ function withIndex(filename, index, total) {
98
98
  return filename;
99
99
  const extension = extname(filename);
100
100
  const stem = extension === "" ? filename : filename.slice(0, -extension.length);
101
- return truncateFilename(`${stem}-${index + 1}${extension}`);
101
+ const suffix = `-${index + 1}${extension}`;
102
+ return stem.slice(0, maximumFilenameLength - suffix.length) + suffix;
102
103
  }
103
104
  async function fetchDownload(initial, fetch, signal) {
104
105
  let url = safeDownloadUrl(initial);
@@ -0,0 +1,23 @@
1
+ export class DamInputError extends Error {
2
+ reason;
3
+ field;
4
+ diagnosticSummary;
5
+ constructor(reason = "invalid_value", field) {
6
+ super("DAM 输入不可用。");
7
+ this.reason = reason;
8
+ this.field = field;
9
+ this.name = "DamInputError";
10
+ this.diagnosticSummary = { inputReason: reason, ...(field ? { inputField: `/${field}` } : {}) };
11
+ }
12
+ }
13
+ /** Only machine identifiers tolerate pasted line endings; filenames and text do not. */
14
+ export function normalizeDamAssetId(value, field = "asset_id") {
15
+ if (typeof value !== "string")
16
+ throw new DamInputError("id_required_not_url", field);
17
+ const id = value.replace(/^[ \r\n]+|[ \r\n]+$/gu, "");
18
+ if (/[\u0000-\u001f\u007f-\u009f]/u.test(id))
19
+ throw new DamInputError("identifier_control_character", field);
20
+ if (id.trim() === "" || /^https?:\/\//iu.test(id))
21
+ throw new DamInputError("id_required_not_url", field);
22
+ return id;
23
+ }