@lark-apaas/coding-template-nestjs-react-fullstack 0.1.72-alpha.20261123065914 → 0.1.72-alpha.20261124145149

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-apaas/coding-template-nestjs-react-fullstack",
3
- "version": "0.1.72-alpha.20261123065914",
3
+ "version": "0.1.72-alpha.20261124145149",
4
4
  "description": "NestJS + React fullstack template for miaoda coding",
5
5
  "type": "module",
6
6
  "files": [
@@ -1568,16 +1568,6 @@
1568
1568
  "styled-jsx": ">=5.0.0"
1569
1569
  }
1570
1570
  },
1571
- "node_modules/@lark-apaas/client-toolkit/node_modules/clsx": {
1572
- "version": "2.0.1",
1573
- "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.0.1.tgz",
1574
- "integrity": "sha512-PrYqtepbSWwrFmtHX0IHv3zUEbWn1psIqaIZyjB3b9wEGpRAkpyeKbCCCkCXJYiHZPjK7jckJvf2sEB/8VKPgQ==",
1575
- "dev": true,
1576
- "license": "MIT",
1577
- "engines": {
1578
- "node": ">=6"
1579
- }
1580
- },
1581
1571
  "node_modules/@lark-apaas/client-toolkit/node_modules/crypto-js": {
1582
1572
  "version": "3.1.9-1",
1583
1573
  "resolved": "https://registry.npmmirror.com/crypto-js/-/crypto-js-3.1.9-1.tgz",
@@ -1585,20 +1575,6 @@
1585
1575
  "dev": true,
1586
1576
  "license": "MIT"
1587
1577
  },
1588
- "node_modules/@lark-apaas/client-toolkit/node_modules/tailwind-merge": {
1589
- "version": "2.0.0",
1590
- "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.0.0.tgz",
1591
- "integrity": "sha512-WO8qghn9yhsldLSg80au+3/gY9E4hFxIvQ3qOmlpXnqpDKoMruKfi/56BbbMg6fHTQJ9QD3cc79PoWqlaQE4rw==",
1592
- "dev": true,
1593
- "license": "MIT",
1594
- "dependencies": {
1595
- "@babel/runtime": "^7.23.1"
1596
- },
1597
- "funding": {
1598
- "type": "github",
1599
- "url": "https://github.com/sponsors/dcastil"
1600
- }
1601
- },
1602
1578
  "node_modules/@lark-apaas/coding-preset-vite-react": {
1603
1579
  "version": "1.0.33",
1604
1580
  "resolved": "https://registry.npmmirror.com/@lark-apaas/coding-preset-vite-react/-/coding-preset-vite-react-1.0.33.tgz",
@@ -1652,17 +1628,6 @@
1652
1628
  "dev": true,
1653
1629
  "license": "MIT"
1654
1630
  },
1655
- "node_modules/@lark-apaas/coding-preset-vite-react/node_modules/tailwind-merge": {
1656
- "version": "2.6.2",
1657
- "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.2.tgz",
1658
- "integrity": "sha512-o2TX9QB8K2cfaJYgMwv96uAUQK5SqpRJHD2vGDK5nyF/tk9PQTZFpwgsDsySQjlIbYdZ6ZDkk5W+bSuWSe92AA==",
1659
- "dev": true,
1660
- "license": "MIT",
1661
- "funding": {
1662
- "type": "github",
1663
- "url": "https://github.com/sponsors/dcastil"
1664
- }
1665
- },
1666
1631
  "node_modules/@lark-apaas/dataloom": {
1667
1632
  "version": "0.1.6",
1668
1633
  "resolved": "https://registry.npmmirror.com/@lark-apaas/dataloom/-/dataloom-0.1.6.tgz",
@@ -1790,30 +1755,6 @@
1790
1755
  "react": ">=16.8.0"
1791
1756
  }
1792
1757
  },
1793
- "node_modules/@lark-apaas/miaoda-inspector/node_modules/clsx": {
1794
- "version": "2.0.1",
1795
- "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.0.1.tgz",
1796
- "integrity": "sha512-PrYqtepbSWwrFmtHX0IHv3zUEbWn1psIqaIZyjB3b9wEGpRAkpyeKbCCCkCXJYiHZPjK7jckJvf2sEB/8VKPgQ==",
1797
- "dev": true,
1798
- "license": "MIT",
1799
- "engines": {
1800
- "node": ">=6"
1801
- }
1802
- },
1803
- "node_modules/@lark-apaas/miaoda-inspector/node_modules/tailwind-merge": {
1804
- "version": "2.0.0",
1805
- "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.0.0.tgz",
1806
- "integrity": "sha512-WO8qghn9yhsldLSg80au+3/gY9E4hFxIvQ3qOmlpXnqpDKoMruKfi/56BbbMg6fHTQJ9QD3cc79PoWqlaQE4rw==",
1807
- "dev": true,
1808
- "license": "MIT",
1809
- "dependencies": {
1810
- "@babel/runtime": "^7.23.1"
1811
- },
1812
- "funding": {
1813
- "type": "github",
1814
- "url": "https://github.com/sponsors/dcastil"
1815
- }
1816
- },
1817
1758
  "node_modules/@lark-apaas/nestjs-authnpaas": {
1818
1759
  "version": "1.0.11",
1819
1760
  "resolved": "https://registry.npmmirror.com/@lark-apaas/nestjs-authnpaas/-/nestjs-authnpaas-1.0.11.tgz",
@@ -21015,17 +20956,6 @@
21015
20956
  "tailwindcss": "*"
21016
20957
  }
21017
20958
  },
21018
- "node_modules/tailwind-variants/node_modules/tailwind-merge": {
21019
- "version": "2.5.4",
21020
- "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.5.4.tgz",
21021
- "integrity": "sha512-0q8cfZHMu9nuYP/b5Shb7Y7Sh1B7Nnl5GqNr1U+n2p6+mybvRtayrQ+0042Z5byvTA8ihjlP8Odo8/VnHbZu4Q==",
21022
- "dev": true,
21023
- "license": "MIT",
21024
- "funding": {
21025
- "type": "github",
21026
- "url": "https://github.com/sponsors/dcastil"
21027
- }
21028
- },
21029
20959
  "node_modules/tailwindcss": {
21030
20960
  "version": "4.3.3",
21031
20961
  "resolved": "https://registry.npmmirror.com/tailwindcss/-/tailwindcss-4.3.3.tgz",
@@ -136,6 +136,14 @@
136
136
  "vite": "^8",
137
137
  "zod": "^4.3.6"
138
138
  },
139
+ "overrides": {
140
+ "dayjs": "^1.11.15",
141
+ "clsx": "^2.1.1",
142
+ "tailwind-merge": "^3.5.0",
143
+ "zod": "^4.3.6",
144
+ "echarts": "^6.1.0",
145
+ "stylelint": "^17.3.0"
146
+ },
139
147
  "engines": {
140
148
  "node": ">=22.0.0",
141
149
  "npm": ">=10.0.0"
@@ -0,0 +1,577 @@
1
+ import { HttpStatus, Logger } from '@nestjs/common';
2
+ import * as lark from '@larksuiteoapi/node-sdk';
3
+ import { Buffer } from 'node:buffer';
4
+ import { createWriteStream } from 'node:fs';
5
+ import { Readable } from 'node:stream';
6
+ import { pipeline } from 'node:stream/promises';
7
+ import { ResponseCode } from './constants/api_response_code';
8
+ import { BusinessException } from './interfaces/exception.interface';
9
+
10
+ export interface LarkCallContext {
11
+ /** Use the actual SDK operation, e.g. minutes.v1.minuteTranscript.get. */
12
+ operation: string;
13
+ /** Original document/Wiki/Minutes URL, not a temporary download URL. */
14
+ resourceUrl?: string;
15
+ /** Necessary scopes for this operation, when already known. */
16
+ requiredScopes?: readonly string[];
17
+ }
18
+
19
+ export interface LarkJsonResult {
20
+ code?: number;
21
+ msg?: string;
22
+ request_id?: string;
23
+ error?: { log_id?: string; permission_violations?: unknown };
24
+ }
25
+
26
+ export interface LarkFileResult {
27
+ headers: unknown;
28
+ writeFile(filePath: string): Promise<unknown>;
29
+ getReadableStream(): Readable;
30
+ }
31
+
32
+ export type LarkFailureKind =
33
+ | 'scope_missing'
34
+ | 'resource_permission'
35
+ | 'not_found'
36
+ | 'deleted'
37
+ | 'not_ready'
38
+ | 'rate_limited'
39
+ | 'configuration'
40
+ | 'invalid_request'
41
+ | 'upstream'
42
+ | 'file_processing';
43
+
44
+ interface FailureDetails {
45
+ provider: 'lark_openapi';
46
+ operation: string;
47
+ kind: LarkFailureKind;
48
+ larkCode?: number;
49
+ larkHttpStatus?: number;
50
+ nativeMessage?: string;
51
+ requestId?: string;
52
+ }
53
+
54
+ /** Preserves the template's error.code / error.message / error.details contract. */
55
+ export class LarkOpenApiException extends BusinessException {
56
+ public readonly kind: LarkFailureKind;
57
+ public readonly larkCode?: number;
58
+ public readonly larkHttpStatus?: number;
59
+ public readonly requestId?: string;
60
+
61
+ constructor(
62
+ code: ResponseCode,
63
+ message: string,
64
+ httpStatus: HttpStatus,
65
+ details: FailureDetails,
66
+ ) {
67
+ super(code, message, httpStatus, JSON.stringify(details));
68
+ this.name = 'LarkOpenApiException';
69
+ this.kind = details.kind;
70
+ this.larkCode = details.larkCode;
71
+ this.larkHttpStatus = details.larkHttpStatus;
72
+ this.requestId = details.requestId;
73
+ }
74
+ }
75
+
76
+ let cachedClient:
77
+ | {
78
+ appId: string;
79
+ appSecret: string;
80
+ domain: lark.Domain | string;
81
+ client: lark.Client;
82
+ }
83
+ | undefined;
84
+
85
+ const logger = new Logger('LarkOpenAPI');
86
+
87
+ function record(value: unknown): Record<string, unknown> | undefined {
88
+ return typeof value === 'object' && value !== null
89
+ ? (value as Record<string, unknown>)
90
+ : undefined;
91
+ }
92
+
93
+ function configurationError(message: string): LarkOpenApiException {
94
+ return new LarkOpenApiException(
95
+ ResponseCode.SERVICE_UNAVAILABLE,
96
+ message,
97
+ HttpStatus.SERVICE_UNAVAILABLE,
98
+ {
99
+ provider: 'lark_openapi',
100
+ operation: 'client.initialize',
101
+ kind: 'configuration',
102
+ },
103
+ );
104
+ }
105
+
106
+ export function getLarkSdkDomain(): lark.Domain | string {
107
+ const environment =
108
+ process.env.FORCE_FRAMEWORK_ENVIRONMENT?.trim().toLowerCase();
109
+ if (environment === 'boe') return 'https://open.feishu-boe.cn';
110
+ if (environment === 'pre' || environment === 'online')
111
+ return lark.Domain.Feishu;
112
+ throw configurationError(
113
+ '飞书集成部署环境尚未就绪,请应用开发者核对平台环境配置。',
114
+ );
115
+ }
116
+
117
+ /** Call inside a business method. Importing this file never initializes credentials. */
118
+ export function getLarkClient(): lark.Client {
119
+ const domain = getLarkSdkDomain();
120
+ const appId = process.env.LARK_APP_ID;
121
+ const appSecret = process.env.LARK_APP_SECRET;
122
+ if (!appId || !appSecret) {
123
+ throw configurationError(
124
+ '飞书集成配置尚未就绪,请核对应用绑定与环境同步。',
125
+ );
126
+ }
127
+ if (
128
+ cachedClient?.appId === appId &&
129
+ cachedClient.appSecret === appSecret &&
130
+ cachedClient.domain === domain
131
+ ) {
132
+ return cachedClient.client;
133
+ }
134
+ const client = new lark.Client({
135
+ appId,
136
+ appSecret,
137
+ appType: lark.AppType.SelfBuild,
138
+ domain,
139
+ // SDK error formatting can include request configuration. Emit safe diagnostics below.
140
+ logger: { trace() {}, debug() {}, info() {}, warn() {}, error() {} },
141
+ });
142
+ cachedClient = { appId, appSecret, domain, client };
143
+ return client;
144
+ }
145
+
146
+ function header(headers: unknown, key: string): string | undefined {
147
+ const value = record(headers)?.[key];
148
+ return typeof value === 'string' && value.length <= 200 ? value : undefined;
149
+ }
150
+
151
+ function nativeCode(body: unknown): number | undefined {
152
+ const value = record(body)?.code;
153
+ if (typeof value === 'number' && Number.isSafeInteger(value)) return value;
154
+ if (typeof value === 'string' && /^\d{1,10}$/.test(value))
155
+ return Number(value);
156
+ return undefined;
157
+ }
158
+
159
+ function nativeMessage(body: unknown): string | undefined {
160
+ const value = record(body)?.msg;
161
+ if (typeof value !== 'string' || value.length > 64 * 1024) return undefined;
162
+ let text = value;
163
+ const secret = process.env.LARK_APP_SECRET;
164
+ if (secret) text = text.split(secret).join('[redacted]');
165
+ text = text
166
+ .replace(/Bearer\s+[A-Za-z0-9._~+\/-]+/gi, 'Bearer [redacted]')
167
+ .replace(
168
+ /\b(app_secret|access_token|tenant_access_token|user_access_token)\b(["']?\s*[:=]\s*["']?)[^"',\s}]+/gi,
169
+ '$1$2[redacted]',
170
+ )
171
+ .replace(/[\u0000-\u001f\u007f]/g, ' ')
172
+ .trim();
173
+ return text ? text.slice(0, 500) : undefined;
174
+ }
175
+
176
+ /** Emits one bounded completion record, without SDK objects or business content. */
177
+ function logCall(params: {
178
+ context: LarkCallContext;
179
+ startedAt: number;
180
+ resultType: 'json' | 'file';
181
+ phase: 'request' | 'consume';
182
+ outcome: 'success' | 'failure';
183
+ error?: unknown;
184
+ cause?: unknown;
185
+ requestId?: string;
186
+ }): void {
187
+ const error = params.error;
188
+ const failure = error instanceof LarkOpenApiException ? error : undefined;
189
+ const transportCode = record(params.cause ?? error)?.code;
190
+ const details = {
191
+ provider: 'lark_openapi',
192
+ operation: /^[a-zA-Z][a-zA-Z0-9_.]{0,159}$/.test(params.context.operation)
193
+ ? params.context.operation
194
+ : 'unknown',
195
+ resultType: params.resultType,
196
+ phase: params.phase,
197
+ outcome: params.outcome,
198
+ durationMs: Math.max(0, Date.now() - params.startedAt),
199
+ kind: failure?.kind,
200
+ larkCode:
201
+ failure?.larkCode ??
202
+ (params.outcome === 'success' && params.resultType === 'json'
203
+ ? 0
204
+ : undefined),
205
+ larkHttpStatus: failure?.larkHttpStatus,
206
+ requestId: failure?.requestId ?? params.requestId,
207
+ transportCode:
208
+ typeof transportCode === 'string' &&
209
+ /^(ETIMEDOUT|ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ECONNABORTED|ERR_CANCELED)$/.test(
210
+ transportCode,
211
+ )
212
+ ? transportCode
213
+ : undefined,
214
+ };
215
+ // Logging must not turn a completed call into a failure or replace its error.
216
+ try {
217
+ const message = JSON.stringify(details);
218
+ if (params.outcome === 'success') logger.log(message);
219
+ else logger.warn(message);
220
+ } catch {
221
+ // The caller's result remains authoritative when a log sink is unavailable.
222
+ }
223
+ }
224
+
225
+ function parseJson(text: string): unknown {
226
+ try {
227
+ return JSON.parse(text);
228
+ } catch {
229
+ return undefined;
230
+ }
231
+ }
232
+
233
+ /** Limits apply only to error bodies; successful transcript streams are not truncated. */
234
+ async function errorBody(value: unknown): Promise<unknown> {
235
+ const limit = 64 * 1024;
236
+ if (typeof value === 'string') {
237
+ return Buffer.byteLength(value) <= limit ? parseJson(value) : undefined;
238
+ }
239
+ if (Buffer.isBuffer(value)) {
240
+ return value.length <= limit
241
+ ? parseJson(value.toString('utf8'))
242
+ : undefined;
243
+ }
244
+ if (!(value instanceof Readable)) return record(value);
245
+ return new Promise((resolve) => {
246
+ const chunks: Buffer[] = [];
247
+ let bytes = 0;
248
+ let finished = false;
249
+ const finish = (body: unknown, destroy = false): void => {
250
+ if (finished) return;
251
+ finished = true;
252
+ clearTimeout(timer);
253
+ value.removeListener('data', onData);
254
+ value.removeListener('end', onEnd);
255
+ value.removeListener('error', onError);
256
+ value.removeListener('close', onClose);
257
+ if (destroy) value.destroy();
258
+ resolve(body);
259
+ };
260
+ const onData = (chunk: unknown): void => {
261
+ if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string')
262
+ return finish(undefined, true);
263
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
264
+ bytes += buffer.length;
265
+ if (bytes > limit) return finish(undefined, true);
266
+ chunks.push(buffer);
267
+ };
268
+ const onEnd = (): void =>
269
+ finish(parseJson(Buffer.concat(chunks).toString('utf8')));
270
+ const onError = (): void => finish(undefined, true);
271
+ const onClose = (): void => finish(undefined);
272
+ const timer = setTimeout(() => finish(undefined, true), 5000);
273
+ value.on('data', onData);
274
+ value.once('end', onEnd);
275
+ value.once('error', onError);
276
+ value.once('close', onClose);
277
+ });
278
+ }
279
+
280
+ function resourceLink(context: LarkCallContext): string {
281
+ if (!context.resourceUrl) return '';
282
+ try {
283
+ const url = new URL(context.resourceUrl);
284
+ if (
285
+ !['https:', 'http:'].includes(url.protocol) ||
286
+ url.username ||
287
+ url.password
288
+ )
289
+ return '';
290
+ const href = url.href.replace(/[()<>]/g, (character: string) =>
291
+ encodeURIComponent(character),
292
+ );
293
+ const label = context.operation.startsWith('minutes.')
294
+ ? '打开妙记'
295
+ : context.operation.startsWith('wiki.')
296
+ ? '打开知识库节点'
297
+ : '打开文档';
298
+ return ` [${label}](${href})`;
299
+ } catch {
300
+ return '';
301
+ }
302
+ }
303
+
304
+ function scopeLink(body: unknown, context: LarkCallContext): string {
305
+ const violations = record(record(body)?.error)?.permission_violations;
306
+ if (!Array.isArray(violations)) return '';
307
+ const scopes = [
308
+ ...new Set(
309
+ violations.flatMap((item: unknown): string[] => {
310
+ const violation = record(item);
311
+ return violation?.type === 'action_scope_required' &&
312
+ typeof violation.subject === 'string' &&
313
+ /^[a-zA-Z0-9_:.-]+$/.test(violation.subject)
314
+ ? [violation.subject]
315
+ : [];
316
+ }),
317
+ ),
318
+ ];
319
+ if (!scopes.length) return '';
320
+ const message = record(body)?.msg;
321
+ const anyOf = typeof message === 'string' && /one of|任一/i.test(message);
322
+ const known = context.requiredScopes?.filter((scope: string) =>
323
+ scopes.includes(scope),
324
+ );
325
+ const preferred =
326
+ context.operation === 'minutes.v1.minuteTranscript.get'
327
+ ? 'minutes:minutes.transcript:export'
328
+ : context.operation === 'minutes.v1.minute.get'
329
+ ? 'minutes:minutes.basic:read'
330
+ : context.operation.startsWith('docx.')
331
+ ? 'docx:document:readonly'
332
+ : context.operation === 'wiki.v2.space.getNode'
333
+ ? 'wiki:wiki:readonly'
334
+ : undefined;
335
+ const selected = anyOf
336
+ ? [
337
+ (preferred && scopes.includes(preferred) ? preferred : undefined) ??
338
+ known?.[0] ??
339
+ scopes.find((scope: string) =>
340
+ /:readonly$|\.basic:read$/.test(scope),
341
+ ) ??
342
+ scopes[0],
343
+ ]
344
+ : scopes;
345
+ const appId = process.env.LARK_APP_ID;
346
+ if (!appId || !/^cli_[a-zA-Z0-9]+$/.test(appId)) return '';
347
+ const domain = getLarkSdkDomain();
348
+ const base = typeof domain === 'string' ? domain : 'https://open.feishu.cn';
349
+ return ` 请[申请飞书应用权限](${base}/app/${appId}/auth?q=${encodeURIComponent(selected.join(','))}&op_from=openapi),权限审批及发布生效后重试。`;
350
+ }
351
+
352
+ function failure(
353
+ context: LarkCallContext,
354
+ body?: unknown,
355
+ httpStatus?: number,
356
+ headers?: unknown,
357
+ kindOverride?: LarkFailureKind,
358
+ ): LarkOpenApiException {
359
+ const code = nativeCode(body);
360
+ const originalMessage = nativeMessage(body);
361
+ const error = record(record(body)?.error);
362
+ const id =
363
+ record(body)?.request_id ?? error?.log_id ?? header(headers, 'x-tt-logid');
364
+ const requestId = typeof id === 'string' && id.length <= 200 ? id : undefined;
365
+ let kind: LarkFailureKind = kindOverride ?? 'upstream';
366
+ let responseCode = ResponseCode.BAD_GATEWAY;
367
+ let status = HttpStatus.BAD_GATEWAY;
368
+ let message = '飞书调用失败,请应用开发者根据诊断信息排查。';
369
+ if (kindOverride === 'file_processing') {
370
+ responseCode = ResponseCode.INTERNAL_ERROR;
371
+ status = HttpStatus.INTERNAL_SERVER_ERROR;
372
+ message = '飞书文件读取或保存失败,请应用开发者排查文件处理过程。';
373
+ } else if (code === 99991672) {
374
+ kind = 'scope_missing';
375
+ responseCode = ResponseCode.FORBIDDEN;
376
+ status = HttpStatus.FORBIDDEN;
377
+ message =
378
+ '当前绑定飞书应用缺少本次调用所需的 API 权限。请该应用管理员处理权限配置。' +
379
+ scopeLink(body, context);
380
+ } else if (code === 1770032 || code === 131006 || code === 2091005) {
381
+ kind = 'resource_permission';
382
+ responseCode = ResponseCode.FORBIDDEN;
383
+ status = HttpStatus.FORBIDDEN;
384
+ if (code === 1770032) {
385
+ message =
386
+ '当前绑定飞书应用没有这份文档的阅读权限。请文档拥有者或管理者通过右上角“…”→“…更多”→“添加文档应用”为该应用授权。';
387
+ } else if (code === 131006) {
388
+ message =
389
+ '当前绑定飞书应用没有该知识库节点或空间的访问权限。请知识库管理员或节点管理者为该应用授权所需节点范围。';
390
+ } else if (context.operation === 'minutes.v1.minuteTranscript.get') {
391
+ message =
392
+ '当前绑定飞书应用无法导出这篇妙记的文字记录。请妙记拥有者或管理者确认资源访问范围与导出权限。';
393
+ } else if (context.operation === 'minutes.v1.minute.get') {
394
+ message =
395
+ '当前绑定飞书应用无法读取这篇妙记的基本信息。请妙记拥有者或管理者确认资源阅读权限。';
396
+ } else {
397
+ message =
398
+ '当前绑定飞书应用无权执行本次妙记操作。请妙记拥有者或管理者确认资源与操作权限。';
399
+ }
400
+ message += resourceLink(context);
401
+ } else if ([1770002, 131005, 2091002].includes(code ?? -1)) {
402
+ kind = 'not_found';
403
+ responseCode = ResponseCode.NOT_FOUND;
404
+ status = HttpStatus.NOT_FOUND;
405
+ message =
406
+ '无法找到指定飞书资源,请检查原始链接、资源标识及实际访问范围。' +
407
+ resourceLink(context);
408
+ } else if (code === 1770003 || code === 2091004) {
409
+ kind = 'deleted';
410
+ responseCode = ResponseCode.NOT_FOUND;
411
+ status = HttpStatus.NOT_FOUND;
412
+ message = '指定飞书资源已被删除,请确认原始资源。' + resourceLink(context);
413
+ } else if (code === 2091003) {
414
+ kind = 'not_ready';
415
+ responseCode = ResponseCode.CONFLICT;
416
+ status = HttpStatus.CONFLICT;
417
+ message =
418
+ '妙记文字记录尚未就绪,请等待转写完成后重试。' + resourceLink(context);
419
+ } else if (code === 99991400 || httpStatus === 429) {
420
+ kind = 'rate_limited';
421
+ responseCode = ResponseCode.TOO_MANY_REQUESTS;
422
+ status = HttpStatus.TOO_MANY_REQUESTS;
423
+ message = '飞书请求达到频率限制,请稍后重试。';
424
+ } else if (code === 10014 || code === 99991671) {
425
+ kind = 'configuration';
426
+ responseCode = ResponseCode.SERVICE_UNAVAILABLE;
427
+ status = HttpStatus.SERVICE_UNAVAILABLE;
428
+ message = '飞书调用身份配置未生效,请应用开发者核对绑定与平台环境。';
429
+ } else if (code === 2091001) {
430
+ kind = 'invalid_request';
431
+ responseCode = ResponseCode.BAD_REQUEST;
432
+ status = HttpStatus.BAD_REQUEST;
433
+ message = '飞书请求参数有误,请应用开发者核对资源标识与本次操作的参数。';
434
+ } else if (httpStatus === 400) {
435
+ responseCode = ResponseCode.BAD_REQUEST;
436
+ status = HttpStatus.BAD_REQUEST;
437
+ message = '飞书拒绝本次请求,请根据返回原因处理。';
438
+ }
439
+ if (originalMessage) {
440
+ const plainMessage = originalMessage.replace(/[\\`*_\[\]()<>]/g, '\\$&');
441
+ message += ` 飞书返回:${plainMessage}`;
442
+ }
443
+ const details: FailureDetails = {
444
+ provider: 'lark_openapi',
445
+ operation: context.operation,
446
+ kind,
447
+ larkCode: code,
448
+ larkHttpStatus: httpStatus,
449
+ nativeMessage: originalMessage,
450
+ requestId,
451
+ };
452
+ // Never serialize the original SDK error, credentials, request config or transcript.
453
+ return new LarkOpenApiException(responseCode, message, status, details);
454
+ }
455
+
456
+ async function requestFailure(
457
+ error: unknown,
458
+ context: LarkCallContext,
459
+ ): Promise<LarkOpenApiException> {
460
+ const response = record(record(error)?.response);
461
+ const body = await errorBody(response?.data ?? error);
462
+ const status =
463
+ typeof response?.status === 'number' ? response.status : undefined;
464
+ return failure(context, body, status, response?.headers);
465
+ }
466
+
467
+ /** Checks the JSON business code as well as rejected HTTP requests; never retries writes. */
468
+ export async function callLarkJson<T extends LarkJsonResult>(
469
+ context: LarkCallContext,
470
+ request: (client: lark.Client) => Promise<T>,
471
+ ): Promise<T> {
472
+ const startedAt = Date.now();
473
+ try {
474
+ const result = await request(getLarkClient());
475
+ if (result?.code !== 0) throw failure(context, result);
476
+ const requestId =
477
+ header(result, 'request_id') ?? header(result.error, 'log_id');
478
+ logCall({
479
+ context,
480
+ startedAt,
481
+ resultType: 'json',
482
+ phase: 'request',
483
+ outcome: 'success',
484
+ requestId,
485
+ });
486
+ return result;
487
+ } catch (error: unknown) {
488
+ const normalized =
489
+ error instanceof BusinessException
490
+ ? error
491
+ : await requestFailure(error, context);
492
+ logCall({
493
+ context,
494
+ startedAt,
495
+ resultType: 'json',
496
+ phase: 'request',
497
+ outcome: 'failure',
498
+ error: normalized,
499
+ cause: error,
500
+ });
501
+ throw normalized;
502
+ }
503
+ }
504
+
505
+ /** Consume the successful download once; local consumption errors are not resource permissions. */
506
+ export async function callLarkFile<T>(
507
+ context: LarkCallContext,
508
+ request: (client: lark.Client) => Promise<LarkFileResult>,
509
+ consume: (file: LarkFileResult) => Promise<T>,
510
+ ): Promise<T> {
511
+ const startedAt = Date.now();
512
+ let phase: 'request' | 'consume' = 'request';
513
+ let file: LarkFileResult;
514
+ try {
515
+ file = await request(getLarkClient());
516
+ if (
517
+ typeof file?.getReadableStream !== 'function' ||
518
+ typeof file.writeFile !== 'function'
519
+ ) {
520
+ throw failure(context, file);
521
+ }
522
+ if (header(file.headers, 'content-type')?.includes('application/json')) {
523
+ throw failure(
524
+ context,
525
+ await errorBody(file.getReadableStream()),
526
+ 200,
527
+ file.headers,
528
+ );
529
+ }
530
+ phase = 'consume';
531
+ // Application validation/database errors retain their contract in this phase.
532
+ const result = await consume({
533
+ headers: file.headers,
534
+ getReadableStream: () => file.getReadableStream(),
535
+ // Only this file I/O boundary converts source-stream and destination-file failures.
536
+ writeFile: async (filePath: string) => {
537
+ try {
538
+ await pipeline(file.getReadableStream(), createWriteStream(filePath));
539
+ return filePath;
540
+ } catch (error: unknown) {
541
+ if (error instanceof BusinessException) throw error;
542
+ throw failure(
543
+ context,
544
+ undefined,
545
+ undefined,
546
+ file.headers,
547
+ 'file_processing',
548
+ );
549
+ }
550
+ },
551
+ });
552
+ logCall({
553
+ context,
554
+ startedAt,
555
+ resultType: 'file',
556
+ phase,
557
+ outcome: 'success',
558
+ requestId: header(file.headers, 'x-tt-logid'),
559
+ });
560
+ return result;
561
+ } catch (error: unknown) {
562
+ const normalized =
563
+ phase === 'request' && !(error instanceof BusinessException)
564
+ ? await requestFailure(error, context)
565
+ : error;
566
+ logCall({
567
+ context,
568
+ startedAt,
569
+ resultType: 'file',
570
+ phase,
571
+ outcome: 'failure',
572
+ error: normalized,
573
+ cause: error,
574
+ });
575
+ throw normalized;
576
+ }
577
+ }