@open-dy/ai_coding_sdk 1.0.18 → 1.0.20

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.
@@ -14,7 +14,7 @@ function sleep(ms) {
14
14
  class AIPlatformLLMClient {
15
15
  constructor(options = {}) {
16
16
  this.appEnv = (0, core_1.getAIPlatformAppEnv)();
17
- this.accessToken = options.accessToken;
17
+ this.accessToken = options.accessToken ?? options.delegateToken;
18
18
  this.timeoutMs = options.timeoutMs ?? core_1.AI_PLATFORM_DEFAULT_REQUEST_TIMEOUT_MS;
19
19
  this.imageTimeoutMs = options.imageTimeoutMs ?? core_1.AI_PLATFORM_DEFAULT_IMAGE_TIMEOUT_MS;
20
20
  this.streamTimeoutMs = options.streamTimeoutMs ?? core_1.AI_PLATFORM_DEFAULT_STREAM_TIMEOUT_MS;
@@ -1,5 +1,7 @@
1
1
  import type { AIPlatformCallOptions, AIPlatformEvent, AIPlatformLLMClientOptions, AIPlatformOpenAPIResponse } from './types';
2
2
  export type AIPlatformAppEnv = 'DEV' | 'PROD';
3
+ export type AIPlatformRuntimeEnv = 'INNER_SANDBOX' | 'CLOUD_DEV' | 'CLOUD_PROD';
4
+ export declare function getAIPlatformRuntimeEnv(): AIPlatformRuntimeEnv;
3
5
  export declare function getAIPlatformAppEnv(): AIPlatformAppEnv;
4
6
  export declare function getAIPlatformGatewayOrigin(appEnv?: AIPlatformAppEnv): string;
5
7
  export declare function createAIPlatformClientOptions(options?: AIPlatformCallOptions): AIPlatformLLMClientOptions;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AI_PLATFORM_DEFAULT_STREAM_TIMEOUT_MS = exports.AI_PLATFORM_DEFAULT_IMAGE_TIMEOUT_MS = exports.AI_PLATFORM_DEFAULT_REQUEST_TIMEOUT_MS = void 0;
4
+ exports.getAIPlatformRuntimeEnv = getAIPlatformRuntimeEnv;
4
5
  exports.getAIPlatformAppEnv = getAIPlatformAppEnv;
5
6
  exports.getAIPlatformGatewayOrigin = getAIPlatformGatewayOrigin;
6
7
  exports.createAIPlatformClientOptions = createAIPlatformClientOptions;
@@ -14,11 +15,25 @@ const CLOUD_CALL_DOMAIN_MAP = {
14
15
  const DEFAULT_REQUEST_TIMEOUT_MS = 60000;
15
16
  const DEFAULT_IMAGE_TIMEOUT_MS = 120000;
16
17
  const DEFAULT_STREAM_TIMEOUT_MS = 120000;
17
- function isDevEnvironment() {
18
- return process.env.APP_ENV === 'DEV';
18
+ function getCloudEnv() {
19
+ const cloudEnv = process.env.CLOUD_ENV?.trim();
20
+ return cloudEnv ? cloudEnv : undefined;
21
+ }
22
+ function isInnerSandboxEnvironment() {
23
+ return process.env.APP_ENV === 'DEV' && !getCloudEnv();
24
+ }
25
+ function getAIPlatformRuntimeEnv() {
26
+ const cloudEnv = getCloudEnv();
27
+ if (isInnerSandboxEnvironment()) {
28
+ return 'INNER_SANDBOX';
29
+ }
30
+ if (cloudEnv === 'DEV') {
31
+ return 'CLOUD_DEV';
32
+ }
33
+ return 'CLOUD_PROD';
19
34
  }
20
35
  function getAIPlatformAppEnv() {
21
- return isDevEnvironment() ? 'DEV' : 'PROD';
36
+ return isInnerSandboxEnvironment() ? 'DEV' : 'PROD';
22
37
  }
23
38
  function getAIPlatformGatewayOrigin(appEnv = getAIPlatformAppEnv()) {
24
39
  if (appEnv === 'DEV') {
@@ -33,7 +48,7 @@ function createAIPlatformClientOptions(options) {
33
48
  ...(options?.logid ? { 'x-tt-logid': options.logid } : {}),
34
49
  };
35
50
  return {
36
- accessToken: options?.accessToken,
51
+ accessToken: options?.accessToken ?? options?.delegateToken,
37
52
  timeoutMs: options?.timeoutMs,
38
53
  defaultHeaders,
39
54
  };
@@ -1,3 +1,4 @@
1
1
  export { AIPlatformLLMClient, generate, generateImage, generateVideo, queryVideoTask, streamGenerate, waitVideoTask } from './client';
2
- export { AI_PLATFORM_DEFAULT_IMAGE_TIMEOUT_MS, AI_PLATFORM_DEFAULT_REQUEST_TIMEOUT_MS, AI_PLATFORM_DEFAULT_STREAM_TIMEOUT_MS, createAIPlatformClientOptions, getAIPlatformAppEnv, getAIPlatformGatewayOrigin, parseSSEStream, postAIPlatformJSON, streamAIPlatform } from './core';
2
+ export { AI_PLATFORM_DEFAULT_IMAGE_TIMEOUT_MS, AI_PLATFORM_DEFAULT_REQUEST_TIMEOUT_MS, AI_PLATFORM_DEFAULT_STREAM_TIMEOUT_MS, createAIPlatformClientOptions, getAIPlatformAppEnv, getAIPlatformGatewayOrigin, getAIPlatformRuntimeEnv, parseSSEStream, postAIPlatformJSON, streamAIPlatform } from './core';
3
+ export type { AIPlatformRuntimeEnv } from './core';
3
4
  export type { AIPlatformCallOptions, AIPlatformEvent, AIPlatformLLMClientOptions, AIPlatformMessageEventPayload, AIPlatformOpenAPIResponse, AIPlatformUsage, ContentPart, GenerateImageRequest, GenerateImageResponseData, GenerateMessage, GenerateModelParams, GenerateRequest, GenerateResponseData, GenerateVideoRequest, GenerateVideoResponseData, Message, ModelParams, QueryVideoTaskRequest, QueryVideoTaskResponseData, Role, StreamGenerateRequest, ToolCall } from './types';
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.streamAIPlatform = exports.postAIPlatformJSON = exports.parseSSEStream = exports.getAIPlatformGatewayOrigin = exports.getAIPlatformAppEnv = exports.createAIPlatformClientOptions = exports.AI_PLATFORM_DEFAULT_STREAM_TIMEOUT_MS = exports.AI_PLATFORM_DEFAULT_REQUEST_TIMEOUT_MS = exports.AI_PLATFORM_DEFAULT_IMAGE_TIMEOUT_MS = exports.waitVideoTask = exports.streamGenerate = exports.queryVideoTask = exports.generateVideo = exports.generateImage = exports.generate = exports.AIPlatformLLMClient = void 0;
3
+ exports.streamAIPlatform = exports.postAIPlatformJSON = exports.parseSSEStream = exports.getAIPlatformRuntimeEnv = exports.getAIPlatformGatewayOrigin = exports.getAIPlatformAppEnv = exports.createAIPlatformClientOptions = exports.AI_PLATFORM_DEFAULT_STREAM_TIMEOUT_MS = exports.AI_PLATFORM_DEFAULT_REQUEST_TIMEOUT_MS = exports.AI_PLATFORM_DEFAULT_IMAGE_TIMEOUT_MS = exports.waitVideoTask = exports.streamGenerate = exports.queryVideoTask = exports.generateVideo = exports.generateImage = exports.generate = exports.AIPlatformLLMClient = void 0;
4
4
  var client_1 = require("./client");
5
5
  Object.defineProperty(exports, "AIPlatformLLMClient", { enumerable: true, get: function () { return client_1.AIPlatformLLMClient; } });
6
6
  Object.defineProperty(exports, "generate", { enumerable: true, get: function () { return client_1.generate; } });
@@ -16,6 +16,7 @@ Object.defineProperty(exports, "AI_PLATFORM_DEFAULT_STREAM_TIMEOUT_MS", { enumer
16
16
  Object.defineProperty(exports, "createAIPlatformClientOptions", { enumerable: true, get: function () { return core_1.createAIPlatformClientOptions; } });
17
17
  Object.defineProperty(exports, "getAIPlatformAppEnv", { enumerable: true, get: function () { return core_1.getAIPlatformAppEnv; } });
18
18
  Object.defineProperty(exports, "getAIPlatformGatewayOrigin", { enumerable: true, get: function () { return core_1.getAIPlatformGatewayOrigin; } });
19
+ Object.defineProperty(exports, "getAIPlatformRuntimeEnv", { enumerable: true, get: function () { return core_1.getAIPlatformRuntimeEnv; } });
19
20
  Object.defineProperty(exports, "parseSSEStream", { enumerable: true, get: function () { return core_1.parseSSEStream; } });
20
21
  Object.defineProperty(exports, "postAIPlatformJSON", { enumerable: true, get: function () { return core_1.postAIPlatformJSON; } });
21
22
  Object.defineProperty(exports, "streamAIPlatform", { enumerable: true, get: function () { return core_1.streamAIPlatform; } });
@@ -280,6 +280,12 @@ export interface QueryVideoTaskResponseData {
280
280
  }
281
281
  export interface AIPlatformLLMClientOptions {
282
282
  accessToken?: string;
283
+ /**
284
+ * `accessToken` 的兼容别名。
285
+ *
286
+ * @deprecated 请改用 `accessToken`。
287
+ */
288
+ delegateToken?: string;
283
289
  timeoutMs?: number;
284
290
  imageTimeoutMs?: number;
285
291
  streamTimeoutMs?: number;
@@ -288,6 +294,12 @@ export interface AIPlatformLLMClientOptions {
288
294
  }
289
295
  export interface AIPlatformCallOptions {
290
296
  accessToken?: string;
297
+ /**
298
+ * `accessToken` 的兼容别名。
299
+ *
300
+ * @deprecated 请改用 `accessToken`。
301
+ */
302
+ delegateToken?: string;
291
303
  logid?: string;
292
304
  timeoutMs?: number;
293
305
  defaultHeaders?: Record<string, string>;
@@ -4,6 +4,8 @@ export interface UserHashMobileParams {
4
4
  open_id: string;
5
5
  }
6
6
  export interface UserHashMobileResponse {
7
+ /** 单向哈希加密后的手机号(实际接口返回字段) */
8
+ hash_mobile?: string;
7
9
  /** 单向哈希加密后的手机号 */
8
10
  mobile_hash?: string;
9
11
  }
@@ -13,11 +13,20 @@ const core_1 = require("../core");
13
13
  * @remarks 返回的是经过单向哈希处理的手机号,无法还原为明文。
14
14
  */
15
15
  async function getUserHashMobile(params, options) {
16
- return (0, core_1.callOpenAPI)({
16
+ const response = await (0, core_1.callOpenAPI)({
17
17
  path: '/api/douyin/v1/user/get_user_hash_mobile/',
18
18
  method: 'GET',
19
19
  queryParams: params,
20
20
  domain: 'open.douyin.com',
21
21
  requiresUserAuth: true,
22
22
  }, options);
23
+ const hashMobile = response.data?.hash_mobile ?? response.data?.mobile_hash;
24
+ if (hashMobile) {
25
+ response.data = {
26
+ ...response.data,
27
+ hash_mobile: hashMobile,
28
+ mobile_hash: hashMobile,
29
+ };
30
+ }
31
+ return response;
23
32
  }
@@ -61,6 +61,37 @@ function maskHeaders(headers) {
61
61
  ...(headers['access-token'] ? { 'access-token': '***' } : {}),
62
62
  };
63
63
  }
64
+ function isRecord(value) {
65
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
66
+ }
67
+ function getNumericValue(value) {
68
+ if (typeof value === 'number' && Number.isFinite(value)) {
69
+ return value;
70
+ }
71
+ if (typeof value === 'string' && value.trim() !== '') {
72
+ const parsed = Number(value);
73
+ if (Number.isFinite(parsed)) {
74
+ return parsed;
75
+ }
76
+ }
77
+ return undefined;
78
+ }
79
+ function getStringValue(value) {
80
+ return typeof value === 'string' ? value : undefined;
81
+ }
82
+ function stripLegacyDataMeta(value) {
83
+ if (!isRecord(value)) {
84
+ return value;
85
+ }
86
+ const { error_code: _errorCode, description: _description, ...rest } = value;
87
+ return rest;
88
+ }
89
+ function buildOpenAPIErrorMessage(errMsg, errNo, logId, subErrMsg, subErrNo) {
90
+ const subErrorSuffix = subErrNo && subErrNo !== 0
91
+ ? `, sub_error: ${subErrMsg || 'N/A'} (${subErrNo})`
92
+ : '';
93
+ return `OpenAPI Error: ${errMsg || 'Unknown error'} (${errNo})${subErrorSuffix}, x-tt-logid: ${logId}`;
94
+ }
64
95
  async function callOpenAPI(params, options) {
65
96
  const { path, method = 'GET', queryParams, body, domain = 'open.douyin.com', requiresUserAuth, } = params;
66
97
  const accessToken = options?.accessToken ?? options?.delegateToken;
@@ -91,19 +122,67 @@ async function callOpenAPI(params, options) {
91
122
  if (!response.ok) {
92
123
  throw new Error(`HTTP Error: ${response.status} ${response.statusText}, x-tt-logid: ${response.headers.get('x-tt-logid') || 'N/A'}`);
93
124
  }
94
- if (!rawData ||
95
- typeof rawData !== 'object' ||
96
- !("err_no" in rawData) ||
97
- !("err_msg" in rawData)) {
125
+ if (!isRecord(rawData)) {
98
126
  throw new Error(`Invalid OpenAPI response, x-tt-logid: ${response.headers.get('x-tt-logid') || 'N/A'}`);
99
127
  }
100
128
  const dataAny = rawData;
101
- if (typeof dataAny.err_no === 'number' && dataAny.err_no !== 0) {
102
- throw new Error(`OpenAPI Error: ${String(dataAny.err_msg)} (${String(dataAny.err_no)}), x-tt-logid: ${response.headers.get('x-tt-logid') || 'N/A'}`);
129
+ const responseLogId = response.headers.get('x-tt-logid') || 'N/A';
130
+ const topLevelLogId = getStringValue(dataAny.log_id);
131
+ const dataPayload = dataAny.data;
132
+ const payloadRecord = isRecord(dataPayload) ? dataPayload : undefined;
133
+ const topErrNo = getNumericValue(dataAny.err_no);
134
+ const topErrMsg = getStringValue(dataAny.err_msg);
135
+ const payloadErrNo = getNumericValue(payloadRecord?.error_code);
136
+ const payloadErrMsg = getStringValue(payloadRecord?.description);
137
+ const extraRecord = isRecord(dataAny.extra) ? dataAny.extra : undefined;
138
+ const extraErrNo = getNumericValue(extraRecord?.error_code);
139
+ const extraErrMsg = getStringValue(extraRecord?.description);
140
+ const payloadExtraRecord = payloadRecord && isRecord(payloadRecord.extra) ? payloadRecord.extra : undefined;
141
+ const payloadExtraErrNo = getNumericValue(payloadExtraRecord?.error_code);
142
+ const payloadExtraErrMsg = getStringValue(payloadExtraRecord?.description);
143
+ const payloadExtraSubErrNo = getNumericValue(payloadExtraRecord?.sub_error_code);
144
+ const payloadExtraSubErrMsg = getStringValue(payloadExtraRecord?.sub_description);
145
+ const logId = response.headers.get('x-tt-logid')
146
+ || getStringValue(extraRecord?.logid)
147
+ || getStringValue(payloadRecord?.log_id)
148
+ || topLevelLogId
149
+ || responseLogId;
150
+ // 兼容两类返回协议:
151
+ // 1. 标准协议:顶层 err_no / err_msg / data
152
+ // 2. 授权类老协议:data.error_code / description + extra
153
+ if (topErrNo === undefined &&
154
+ topErrMsg === undefined &&
155
+ payloadErrNo === undefined &&
156
+ extraErrNo === undefined) {
157
+ throw new Error(`Invalid OpenAPI response, x-tt-logid: ${logId}`);
158
+ }
159
+ if (topErrNo !== undefined && topErrNo !== 0) {
160
+ throw new Error(buildOpenAPIErrorMessage(topErrMsg, topErrNo, logId));
161
+ }
162
+ if (payloadExtraErrNo !== undefined && payloadExtraErrNo !== 0) {
163
+ throw new Error(buildOpenAPIErrorMessage(payloadExtraErrMsg, payloadExtraErrNo, logId, payloadExtraSubErrMsg, payloadExtraSubErrNo));
164
+ }
165
+ if (topErrNo === undefined) {
166
+ const normalizedErrNo = payloadErrNo ?? extraErrNo ?? 0;
167
+ const normalizedErrMsg = payloadErrMsg ?? extraErrMsg ?? '';
168
+ if (normalizedErrNo !== 0) {
169
+ throw new Error(buildOpenAPIErrorMessage(normalizedErrMsg, normalizedErrNo, logId));
170
+ }
171
+ const normalized = {
172
+ err_no: normalizedErrNo,
173
+ err_msg: normalizedErrMsg,
174
+ data: stripLegacyDataMeta((dataPayload ?? {})),
175
+ };
176
+ console.log('[OpenAPI] Response:', JSON.stringify(normalized).slice(0, 500));
177
+ return normalized;
103
178
  }
104
179
  const normalized = (() => {
105
180
  if (dataAny.data !== undefined) {
106
- return dataAny;
181
+ return {
182
+ err_no: topErrNo,
183
+ err_msg: topErrMsg ?? '',
184
+ data: stripLegacyDataMeta(dataAny.data),
185
+ };
107
186
  }
108
187
  const { err_no, err_msg, ...rest } = dataAny;
109
188
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-dy/ai_coding_sdk",
3
- "version": "1.0.18",
3
+ "version": "1.0.20",
4
4
  "description": "AI Coding SDK — 抖音开放平台 OpenAPI 客户端与工具集",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",