@generaltranslation/api 0.0.0 → 0.0.2

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/dist/index.mjs ADDED
@@ -0,0 +1,1192 @@
1
+ //#region src/generated/sdk.gen.ts
2
+ /**
3
+ * Create a Project
4
+ *
5
+ * Create a Project in the Organization associated with an Organization API key. The key must have the `org:projects:create` permission. Project keys cannot use this endpoint. Enabling CDN delivery also requires `project:write`.
6
+ */
7
+ const createProject = (options) => options.client.post({
8
+ security: [{
9
+ scheme: "bearer",
10
+ type: "http"
11
+ }],
12
+ url: "/v2/projects",
13
+ ...options,
14
+ headers: {
15
+ "Content-Type": "application/json",
16
+ ...options.headers
17
+ }
18
+ });
19
+ /**
20
+ * Upload source files
21
+ *
22
+ * Upload one or more source files to the project. Max 100 files per request.
23
+ */
24
+ const uploadSourceFiles = (options) => options.client.post({
25
+ security: [{
26
+ scheme: "bearer",
27
+ type: "http"
28
+ }],
29
+ url: "/v2/project/files/upload-files",
30
+ ...options,
31
+ headers: {
32
+ "Content-Type": "application/json",
33
+ ...options.headers
34
+ }
35
+ });
36
+ /**
37
+ * Upload translated files
38
+ *
39
+ * Upload translated files linked to their source files. Max 100 files per request.
40
+ */
41
+ const uploadTranslations = (options) => options.client.post({
42
+ security: [{
43
+ scheme: "bearer",
44
+ type: "http"
45
+ }],
46
+ url: "/v2/project/files/upload-translations",
47
+ ...options,
48
+ headers: {
49
+ "Content-Type": "application/json",
50
+ ...options.headers
51
+ }
52
+ });
53
+ /**
54
+ * Upload Project assets
55
+ *
56
+ * Upload OpenType or TrueType fonts through a Project and make them available to Lottie translation workflows across its Organization. Each font is keyed by a normalized identity derived from its family, weight, and italic style (from the supplied `family` and `style`, or from the font metadata and file name). Re-uploading the same identity overwrites the existing asset, so complete retries after a `500` response are safe.
57
+ */
58
+ const uploadAssets = (options) => options.client.post({
59
+ security: [{
60
+ scheme: "bearer",
61
+ type: "http"
62
+ }],
63
+ url: "/v2/project/assets",
64
+ ...options,
65
+ headers: {
66
+ "Content-Type": "application/json",
67
+ ...options.headers
68
+ }
69
+ });
70
+ /**
71
+ * Submit translation diffs
72
+ *
73
+ * Overwrite translations with user-provided localized content.
74
+ */
75
+ const submitUserEditDiffs = (options) => options.client.post({
76
+ security: [{
77
+ scheme: "bearer",
78
+ type: "http"
79
+ }],
80
+ url: "/v2/project/files/diffs",
81
+ ...options,
82
+ headers: {
83
+ "Content-Type": "application/json",
84
+ ...options.headers
85
+ }
86
+ });
87
+ /**
88
+ * Check if context generation is needed
89
+ *
90
+ * Check whether the Project needs translation context generated. This deprecated endpoint is retained for backward compatibility and is no longer called by current clients.
91
+ *
92
+ * @deprecated
93
+ */
94
+ const shouldGenerateProjectContext = (options) => options.client.get({
95
+ security: [{
96
+ scheme: "bearer",
97
+ type: "http"
98
+ }],
99
+ url: "/v2/project/setup/should-generate",
100
+ ...options
101
+ });
102
+ /**
103
+ * Generate translation context
104
+ *
105
+ * Generate glossaries and translation instructions for the project.
106
+ */
107
+ const generateProjectContext = (options) => options.client.post({
108
+ security: [{
109
+ scheme: "bearer",
110
+ type: "http"
111
+ }],
112
+ url: "/v2/project/setup/generate",
113
+ ...options,
114
+ headers: {
115
+ "Content-Type": "application/json",
116
+ ...options.headers
117
+ }
118
+ });
119
+ /**
120
+ * Get context generation job status
121
+ *
122
+ * Track a context generation job. This deprecated endpoint is retained for backward compatibility; new integrations should use `POST /v2/project/jobs/info`.
123
+ *
124
+ * @deprecated
125
+ */
126
+ const getProjectContextGenerationStatus = (options) => options.client.get({
127
+ security: [{
128
+ scheme: "bearer",
129
+ type: "http"
130
+ }],
131
+ url: "/v2/project/setup/status/{jobId}",
132
+ ...options
133
+ });
134
+ /**
135
+ * Queue files for translation
136
+ *
137
+ * Enqueue uploaded source files for background translation. Max 100 files per request. The response shape depends on the requested `gt-api-version`.
138
+ */
139
+ const enqueueFileTranslations = (options) => options.client.post({
140
+ security: [{
141
+ scheme: "bearer",
142
+ type: "http"
143
+ }],
144
+ url: "/v2/project/translations/enqueue",
145
+ ...options,
146
+ headers: {
147
+ "Content-Type": "application/json",
148
+ ...options.headers
149
+ }
150
+ });
151
+ /**
152
+ * Publish or unpublish files
153
+ *
154
+ * Publish or unpublish translated files to the CDN. Requires CDN to be enabled.
155
+ */
156
+ const publishFiles = (options) => options.client.post({
157
+ security: [{
158
+ scheme: "bearer",
159
+ type: "http"
160
+ }],
161
+ url: "/v2/project/files/publish",
162
+ ...options,
163
+ headers: {
164
+ "Content-Type": "application/json",
165
+ ...options.headers
166
+ }
167
+ });
168
+ /**
169
+ * Download a single file
170
+ *
171
+ * Download a single source or translated file. This deprecated endpoint is retained for backward compatibility; new integrations should use `POST /v2/project/files/download`.
172
+ *
173
+ * @deprecated
174
+ */
175
+ const downloadFile = (options) => options.client.get({
176
+ security: [{
177
+ scheme: "bearer",
178
+ type: "http"
179
+ }],
180
+ url: "/v2/project/files/download/{fileId}",
181
+ ...options
182
+ });
183
+ /**
184
+ * Download multiple files
185
+ *
186
+ * Download up to 100 source or translated files in one request.
187
+ */
188
+ const downloadFiles = (options) => options.client.post({
189
+ security: [{
190
+ scheme: "bearer",
191
+ type: "http"
192
+ }],
193
+ url: "/v2/project/files/download",
194
+ ...options,
195
+ headers: {
196
+ "Content-Type": "application/json",
197
+ ...options.headers
198
+ }
199
+ });
200
+ /**
201
+ * Get branch information
202
+ *
203
+ * Return the Project's default branch and any branches requested by name.
204
+ */
205
+ const getBranchInfo = (options) => options.client.post({
206
+ security: [{
207
+ scheme: "bearer",
208
+ type: "http"
209
+ }],
210
+ url: "/v2/project/branches/info",
211
+ ...options,
212
+ headers: {
213
+ "Content-Type": "application/json",
214
+ ...options.headers
215
+ }
216
+ });
217
+ /**
218
+ * Create a branch
219
+ *
220
+ * Create a new branch, or rename and confirm the default branch.
221
+ */
222
+ const createBranch = (options) => options.client.post({
223
+ security: [{
224
+ scheme: "bearer",
225
+ type: "http"
226
+ }],
227
+ url: "/v2/project/branches/create",
228
+ ...options,
229
+ headers: {
230
+ "Content-Type": "application/json",
231
+ ...options.headers
232
+ }
233
+ });
234
+ /**
235
+ * Create or update a tag
236
+ *
237
+ * Create or upsert a tag that points at a set of file versions.
238
+ */
239
+ const createTag = (options) => options.client.post({
240
+ security: [{
241
+ scheme: "bearer",
242
+ type: "http"
243
+ }],
244
+ url: "/v2/project/tags/create",
245
+ ...options,
246
+ headers: {
247
+ "Content-Type": "application/json",
248
+ ...options.headers
249
+ }
250
+ });
251
+ /**
252
+ * Get Project information
253
+ *
254
+ * Read the authenticated Project's name, Organization ID, locale settings, and auto-approval setting.
255
+ */
256
+ const getProjectInfo = (options) => options.client.get({
257
+ security: [{
258
+ scheme: "bearer",
259
+ type: "http"
260
+ }],
261
+ url: "/v2/project/info/{projectId}",
262
+ ...options
263
+ });
264
+ /**
265
+ * Update Project information
266
+ *
267
+ * Update the Project's default locale or CDN delivery setting.
268
+ */
269
+ const updateProjectInfo = (options) => options.client.post({
270
+ security: [{
271
+ scheme: "bearer",
272
+ type: "http"
273
+ }],
274
+ url: "/v2/project/info/{projectId}",
275
+ ...options,
276
+ headers: {
277
+ "Content-Type": "application/json",
278
+ ...options.headers
279
+ }
280
+ });
281
+ /**
282
+ * Get translation job status
283
+ *
284
+ * Return normalized status information for one or more queued translation or context generation jobs.
285
+ */
286
+ const getTranslationJobInfo = (options) => options.client.post({
287
+ security: [{
288
+ scheme: "bearer",
289
+ type: "http"
290
+ }],
291
+ url: "/v2/project/jobs/info",
292
+ ...options,
293
+ headers: {
294
+ "Content-Type": "application/json",
295
+ ...options.headers
296
+ }
297
+ });
298
+ /**
299
+ * Translate content at runtime
300
+ *
301
+ * Translate one or more strings or structured content entries with caching and memoization. Development API keys are accepted for this endpoint.
302
+ */
303
+ const translate = (options) => options.client.post({
304
+ security: [{
305
+ scheme: "bearer",
306
+ type: "http"
307
+ }],
308
+ url: "/v2/translate",
309
+ ...options,
310
+ headers: {
311
+ "Content-Type": "application/json",
312
+ ...options.headers
313
+ }
314
+ });
315
+ /**
316
+ * Get file metadata
317
+ *
318
+ * Get detailed metadata for specific source and translated files.
319
+ */
320
+ const getFileInfo = (options) => options.client.post({
321
+ security: [{
322
+ scheme: "bearer",
323
+ type: "http"
324
+ }],
325
+ url: "/v2/project/files/info",
326
+ ...options,
327
+ headers: {
328
+ "Content-Type": "application/json",
329
+ ...options.headers
330
+ }
331
+ });
332
+ /**
333
+ * Get translation status for a file
334
+ *
335
+ * Return translation progress and availability by locale for one source file, along with its source metadata.
336
+ */
337
+ const getTranslationStatus = (options) => options.client.get({
338
+ security: [{
339
+ scheme: "bearer",
340
+ type: "http"
341
+ }],
342
+ url: "/v2/project/translations/files/status/{fileId}",
343
+ ...options
344
+ });
345
+ /**
346
+ * Move or rename files
347
+ *
348
+ * Clone source files and their translations under new file IDs.
349
+ */
350
+ const processFileMoves = (options) => options.client.post({
351
+ security: [{
352
+ scheme: "bearer",
353
+ type: "http"
354
+ }],
355
+ url: "/v2/project/files/moves",
356
+ ...options,
357
+ headers: {
358
+ "Content-Type": "application/json",
359
+ ...options.headers
360
+ }
361
+ });
362
+ /**
363
+ * Find orphaned files
364
+ *
365
+ * Return files on a branch that are not present in the provided file ID list.
366
+ */
367
+ const getOrphanedFiles = (options) => options.client.post({
368
+ security: [{
369
+ scheme: "bearer",
370
+ type: "http"
371
+ }],
372
+ url: "/v2/project/files/orphaned",
373
+ ...options,
374
+ headers: {
375
+ "Content-Type": "application/json",
376
+ ...options.headers
377
+ }
378
+ });
379
+ /**
380
+ * Create a CLI wizard session
381
+ *
382
+ * Create a temporary session for CLI browser authentication.
383
+ */
384
+ const createCliWizardSession = (options) => options.client.post({
385
+ url: "/cli/wizard/session",
386
+ ...options,
387
+ headers: {
388
+ "Content-Type": "application/json",
389
+ ...options.headers
390
+ }
391
+ });
392
+ /**
393
+ * Delete a CLI wizard session
394
+ *
395
+ * Delete a completed or abandoned CLI wizard session.
396
+ */
397
+ const deleteCliWizardSession = (options) => options.client.delete({
398
+ url: "/cli/wizard/{sessionId}",
399
+ ...options
400
+ });
401
+ /**
402
+ * Get a CLI wizard session
403
+ *
404
+ * Get credentials for a completed CLI wizard session or its current waiting status.
405
+ */
406
+ const getCliWizardSession = (options) => options.client.get({
407
+ url: "/cli/wizard/{sessionId}",
408
+ ...options
409
+ });
410
+ //#endregion
411
+ //#region src/wrappers/transport.ts
412
+ const MAX_RETRIES = 3;
413
+ const INITIAL_DELAY_MS = 500;
414
+ const RATE_LIMIT_RETRY_DELAY_MS = 6e4;
415
+ const IDEMPOTENT_METHODS = new Set([
416
+ "GET",
417
+ "HEAD",
418
+ "OPTIONS",
419
+ "PUT",
420
+ "DELETE"
421
+ ]);
422
+ const DEFAULT_TIMEOUT_MS = 6e4;
423
+ function createTimeoutFetch({ fetch: fetchImplementation = globalThis.fetch, timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
424
+ return async (input, init) => {
425
+ const request = new Request(input, init);
426
+ const controller = new AbortController();
427
+ const forwardAbort = () => controller.abort(request.signal.reason);
428
+ if (request.signal.aborted) forwardAbort();
429
+ else request.signal.addEventListener("abort", forwardAbort, { once: true });
430
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
431
+ try {
432
+ return await fetchImplementation(new Request(request, { signal: controller.signal }));
433
+ } catch (error) {
434
+ if (controller.signal.aborted && !request.signal.aborted) throw new Error(`Request timed out after ${timeoutMs}ms`);
435
+ throw error;
436
+ } finally {
437
+ clearTimeout(timeoutId);
438
+ request.signal.removeEventListener("abort", forwardAbort);
439
+ }
440
+ };
441
+ }
442
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
443
+ function parseDelayMs(value) {
444
+ if (!value) return void 0;
445
+ const seconds = Number(value.split(",")[0].split(";")[0].trim());
446
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1e3 : void 0;
447
+ }
448
+ function parseRetryAfter(value) {
449
+ const delayMs = parseDelayMs(value);
450
+ if (delayMs !== void 0) return delayMs;
451
+ if (!value) return void 0;
452
+ const retryDate = Date.parse(value);
453
+ return Number.isNaN(retryDate) ? void 0 : Math.max(retryDate - Date.now(), 0);
454
+ }
455
+ function retryDelay(response, attempt, retryPolicy) {
456
+ if (response?.status === 429) return parseRetryAfter(response.headers.get("Retry-After")) ?? parseDelayMs(response.headers.get("RateLimit-Reset")) ?? RATE_LIMIT_RETRY_DELAY_MS;
457
+ return INITIAL_DELAY_MS * (retryPolicy === "linear" ? attempt + 1 : 2 ** attempt);
458
+ }
459
+ function createRetryingFetch({ fetch: fetchImplementation = globalThis.fetch, retryPolicy = "exponential" } = {}) {
460
+ return async (input, init) => {
461
+ const request = new Request(input, init);
462
+ const maxRetries = retryPolicy === "none" ? 0 : MAX_RETRIES;
463
+ const isIdempotent = IDEMPOTENT_METHODS.has(request.method);
464
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
465
+ let response;
466
+ try {
467
+ response = await fetchImplementation(request.clone());
468
+ } catch (error) {
469
+ if (request.signal.aborted || attempt === maxRetries || !isIdempotent) throw error;
470
+ }
471
+ if (response && response.status !== 429 && (response.status < 500 || !isIdempotent)) return response;
472
+ if (response && attempt === maxRetries) return response;
473
+ if (request.signal.aborted) {
474
+ if (response) return response;
475
+ throw request.signal.reason;
476
+ }
477
+ response?.body?.cancel();
478
+ await sleep(retryDelay(response, attempt, retryPolicy));
479
+ }
480
+ throw new Error("Max retries exceeded");
481
+ };
482
+ }
483
+ //#endregion
484
+ //#region src/wrappers/awaitJobs.ts
485
+ const DEFAULT_POLLING_INTERVAL_SECONDS = 5;
486
+ const DEFAULT_TIMEOUT_SECONDS = 600;
487
+ async function awaitJobs(client, jobIds, options = {}) {
488
+ return pollJobs(jobIds, async (pendingJobIds, signal) => {
489
+ return (await getTranslationJobInfo({
490
+ body: { jobIds: pendingJobIds },
491
+ client,
492
+ signal,
493
+ throwOnError: true
494
+ })).data;
495
+ }, options);
496
+ }
497
+ async function pollJobs(jobIds, getJobStatuses, options = {}) {
498
+ if (jobIds.length === 0) return {
499
+ complete: true,
500
+ jobs: []
501
+ };
502
+ const pollingInterval = (options.pollingIntervalSeconds ?? DEFAULT_POLLING_INTERVAL_SECONDS) * 1e3;
503
+ const timeout = (options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) * 1e3;
504
+ const deadline = Date.now() + timeout;
505
+ const finalStatuses = new Map(jobIds.map((jobId) => [jobId, {
506
+ jobId,
507
+ status: "unknown"
508
+ }]));
509
+ const pendingJobIds = new Set(jobIds);
510
+ while (pendingJobIds.size > 0 && Date.now() < deadline) {
511
+ let statuses;
512
+ try {
513
+ statuses = await getJobStatuses([...pendingJobIds], AbortSignal.timeout(Math.min(deadline - Date.now(), DEFAULT_TIMEOUT_MS)));
514
+ } catch (error) {
515
+ if (Date.now() >= deadline) break;
516
+ throw error;
517
+ }
518
+ if (Date.now() >= deadline) break;
519
+ const returnedJobIds = new Set(statuses.map(({ jobId }) => jobId));
520
+ for (const job of statuses) {
521
+ finalStatuses.set(job.jobId, job);
522
+ if (job.status === "completed" || job.status === "failed" || job.status === "unknown") pendingJobIds.delete(job.jobId);
523
+ }
524
+ for (const jobId of pendingJobIds) if (!returnedJobIds.has(jobId)) {
525
+ finalStatuses.set(jobId, {
526
+ jobId,
527
+ status: "unknown"
528
+ });
529
+ pendingJobIds.delete(jobId);
530
+ }
531
+ if (pendingJobIds.size > 0) await new Promise((resolve) => setTimeout(resolve, Math.min(pollingInterval, deadline - Date.now())));
532
+ }
533
+ return {
534
+ complete: pendingJobIds.size === 0,
535
+ jobs: [...finalStatuses.values()]
536
+ };
537
+ }
538
+ //#endregion
539
+ //#region src/wrappers/base64.ts
540
+ function encodeBase64(data) {
541
+ if (typeof Buffer !== "undefined") return Buffer.from(data, "utf-8").toString("base64");
542
+ const bytes = new TextEncoder().encode(data);
543
+ let binary = "";
544
+ for (const byte of bytes) binary += String.fromCharCode(byte);
545
+ return btoa(binary);
546
+ }
547
+ function decodeBase64(base64) {
548
+ if (typeof Buffer !== "undefined") return Buffer.from(base64, "base64").toString("utf-8");
549
+ const bytes = Uint8Array.from(atob(base64), (character) => character.charCodeAt(0));
550
+ return new TextDecoder().decode(bytes);
551
+ }
552
+ function encodeFileContent(content, fileFormat) {
553
+ return fileFormat === "LOTTIE" ? content : encodeBase64(content);
554
+ }
555
+ function decodeFileContent(content, fileFormat) {
556
+ return fileFormat === "LOTTIE" ? content : decodeBase64(content);
557
+ }
558
+ //#endregion
559
+ //#region src/wrappers/batch.ts
560
+ const DEFAULT_BATCH_SIZE = 100;
561
+ function createBatches(items, batchSize = 100) {
562
+ const batches = [];
563
+ for (let index = 0; index < items.length; index += batchSize) batches.push(items.slice(index, index + batchSize));
564
+ return batches;
565
+ }
566
+ async function processBatches(items, processBatch, { batchSize = 100, parallel = true } = {}) {
567
+ const batches = createBatches(items, batchSize);
568
+ if (parallel) return (await Promise.all(batches.map(processBatch))).flat();
569
+ const results = [];
570
+ for (const batch of batches) results.push(await processBatch(batch));
571
+ return results.flat();
572
+ }
573
+ //#endregion
574
+ //#region src/generated/core/bodySerializer.gen.ts
575
+ const jsonBodySerializer = { bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value) };
576
+ //#endregion
577
+ //#region src/generated/core/serverSentEvents.gen.ts
578
+ const createSseClient = ({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) => {
579
+ let lastEventId;
580
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
581
+ const createStream = async function* () {
582
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
583
+ let attempt = 0;
584
+ const signal = options.signal ?? new AbortController().signal;
585
+ while (true) {
586
+ if (signal.aborted) break;
587
+ attempt++;
588
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
589
+ if (lastEventId !== void 0) headers.set("Last-Event-ID", lastEventId);
590
+ try {
591
+ const requestInit = {
592
+ redirect: "follow",
593
+ ...options,
594
+ body: options.serializedBody,
595
+ headers,
596
+ signal
597
+ };
598
+ let request = new Request(url, requestInit);
599
+ if (onRequest) request = await onRequest(url, requestInit);
600
+ const response = await (options.fetch ?? globalThis.fetch)(request);
601
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
602
+ if (!response.body) throw new Error("No body in SSE response");
603
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
604
+ let buffer = "";
605
+ const abortHandler = () => {
606
+ try {
607
+ reader.cancel();
608
+ } catch {}
609
+ };
610
+ signal.addEventListener("abort", abortHandler);
611
+ try {
612
+ while (true) {
613
+ const { done, value } = await reader.read();
614
+ if (done) break;
615
+ buffer += value;
616
+ const chunks = buffer.split("\n\n");
617
+ buffer = chunks.pop() ?? "";
618
+ for (const chunk of chunks) {
619
+ const lines = chunk.split("\n");
620
+ const dataLines = [];
621
+ let eventName;
622
+ for (const line of lines) if (line.startsWith("data:")) dataLines.push(line.replace(/^data:\s*/, ""));
623
+ else if (line.startsWith("event:")) eventName = line.replace(/^event:\s*/, "");
624
+ else if (line.startsWith("id:")) lastEventId = line.replace(/^id:\s*/, "");
625
+ else if (line.startsWith("retry:")) {
626
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
627
+ if (!Number.isNaN(parsed)) retryDelay = parsed;
628
+ }
629
+ let data;
630
+ let parsedJson = false;
631
+ if (dataLines.length) {
632
+ const rawData = dataLines.join("\n");
633
+ try {
634
+ data = JSON.parse(rawData);
635
+ parsedJson = true;
636
+ } catch {
637
+ data = rawData;
638
+ }
639
+ }
640
+ if (parsedJson) {
641
+ if (responseValidator) await responseValidator(data);
642
+ if (responseTransformer) data = await responseTransformer(data);
643
+ }
644
+ onSseEvent?.({
645
+ data,
646
+ event: eventName,
647
+ id: lastEventId,
648
+ retry: retryDelay
649
+ });
650
+ if (dataLines.length) yield data;
651
+ }
652
+ }
653
+ } finally {
654
+ signal.removeEventListener("abort", abortHandler);
655
+ reader.releaseLock();
656
+ }
657
+ break;
658
+ } catch (error) {
659
+ onSseError?.(error);
660
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) break;
661
+ await sleep(Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4));
662
+ }
663
+ }
664
+ };
665
+ return { stream: createStream() };
666
+ };
667
+ //#endregion
668
+ //#region src/generated/core/pathSerializer.gen.ts
669
+ const separatorArrayExplode = (style) => {
670
+ switch (style) {
671
+ case "label": return ".";
672
+ case "matrix": return ";";
673
+ case "simple": return ",";
674
+ default: return "&";
675
+ }
676
+ };
677
+ const separatorArrayNoExplode = (style) => {
678
+ switch (style) {
679
+ case "form": return ",";
680
+ case "pipeDelimited": return "|";
681
+ case "spaceDelimited": return "%20";
682
+ default: return ",";
683
+ }
684
+ };
685
+ const separatorObjectExplode = (style) => {
686
+ switch (style) {
687
+ case "label": return ".";
688
+ case "matrix": return ";";
689
+ case "simple": return ",";
690
+ default: return "&";
691
+ }
692
+ };
693
+ const serializeArrayParam = ({ allowReserved, explode, name, style, value }) => {
694
+ if (!explode) {
695
+ const joinedValues = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
696
+ switch (style) {
697
+ case "label": return `.${joinedValues}`;
698
+ case "matrix": return `;${name}=${joinedValues}`;
699
+ case "simple": return joinedValues;
700
+ default: return `${name}=${joinedValues}`;
701
+ }
702
+ }
703
+ const separator = separatorArrayExplode(style);
704
+ const joinedValues = value.map((v) => {
705
+ if (style === "label" || style === "simple") return allowReserved ? v : encodeURIComponent(v);
706
+ return serializePrimitiveParam({
707
+ allowReserved,
708
+ name,
709
+ value: v
710
+ });
711
+ }).join(separator);
712
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
713
+ };
714
+ const serializePrimitiveParam = ({ allowReserved, name, value }) => {
715
+ if (value === void 0 || value === null) return "";
716
+ if (typeof value === "object") throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
717
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
718
+ };
719
+ const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly }) => {
720
+ if (value instanceof Date) return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
721
+ if (style !== "deepObject" && !explode) {
722
+ let values = [];
723
+ Object.entries(value).forEach(([key, v]) => {
724
+ values = [
725
+ ...values,
726
+ key,
727
+ allowReserved ? v : encodeURIComponent(v)
728
+ ];
729
+ });
730
+ const joinedValues = values.join(",");
731
+ switch (style) {
732
+ case "form": return `${name}=${joinedValues}`;
733
+ case "label": return `.${joinedValues}`;
734
+ case "matrix": return `;${name}=${joinedValues}`;
735
+ default: return joinedValues;
736
+ }
737
+ }
738
+ const separator = separatorObjectExplode(style);
739
+ const joinedValues = Object.entries(value).map(([key, v]) => serializePrimitiveParam({
740
+ allowReserved,
741
+ name: style === "deepObject" ? `${name}[${key}]` : key,
742
+ value: v
743
+ })).join(separator);
744
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
745
+ };
746
+ //#endregion
747
+ //#region src/generated/core/utils.gen.ts
748
+ const PATH_PARAM_RE = /\{[^{}]+\}/g;
749
+ const defaultPathSerializer = ({ path, url: _url }) => {
750
+ let url = _url;
751
+ const matches = _url.match(PATH_PARAM_RE);
752
+ if (matches) for (const match of matches) {
753
+ let explode = false;
754
+ let name = match.substring(1, match.length - 1);
755
+ let style = "simple";
756
+ if (name.endsWith("*")) {
757
+ explode = true;
758
+ name = name.substring(0, name.length - 1);
759
+ }
760
+ if (name.startsWith(".")) {
761
+ name = name.substring(1);
762
+ style = "label";
763
+ } else if (name.startsWith(";")) {
764
+ name = name.substring(1);
765
+ style = "matrix";
766
+ }
767
+ const value = path[name];
768
+ if (value === void 0 || value === null) continue;
769
+ if (Array.isArray(value)) {
770
+ url = url.replace(match, serializeArrayParam({
771
+ explode,
772
+ name,
773
+ style,
774
+ value
775
+ }));
776
+ continue;
777
+ }
778
+ if (typeof value === "object") {
779
+ url = url.replace(match, serializeObjectParam({
780
+ explode,
781
+ name,
782
+ style,
783
+ value,
784
+ valueOnly: true
785
+ }));
786
+ continue;
787
+ }
788
+ if (style === "matrix") {
789
+ url = url.replace(match, `;${serializePrimitiveParam({
790
+ name,
791
+ value
792
+ })}`);
793
+ continue;
794
+ }
795
+ const replaceValue = encodeURIComponent(style === "label" ? `.${value}` : value);
796
+ url = url.replace(match, replaceValue);
797
+ }
798
+ return url;
799
+ };
800
+ const getUrl = ({ baseUrl, path, query, querySerializer, url: _url }) => {
801
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
802
+ let url = (baseUrl ?? "") + pathUrl;
803
+ if (path) url = defaultPathSerializer({
804
+ path,
805
+ url
806
+ });
807
+ let search = query ? querySerializer(query) : "";
808
+ if (search.startsWith("?")) search = search.substring(1);
809
+ if (search) url += `?${search}`;
810
+ return url;
811
+ };
812
+ function getValidRequestBody(options) {
813
+ const hasBody = options.body !== void 0;
814
+ if (hasBody && options.bodySerializer) {
815
+ if ("serializedBody" in options) return options.serializedBody !== void 0 && options.serializedBody !== "" ? options.serializedBody : null;
816
+ return options.body !== "" ? options.body : null;
817
+ }
818
+ if (hasBody) return options.body;
819
+ }
820
+ //#endregion
821
+ //#region src/generated/core/auth.gen.ts
822
+ const getAuthToken = async (auth, callback) => {
823
+ const token = typeof callback === "function" ? await callback(auth) : callback;
824
+ if (!token) return;
825
+ if (auth.scheme === "bearer") return `Bearer ${token}`;
826
+ if (auth.scheme === "basic") return `Basic ${btoa(token)}`;
827
+ return token;
828
+ };
829
+ //#endregion
830
+ //#region src/generated/client/utils.gen.ts
831
+ const createQuerySerializer = ({ parameters = {}, ...args } = {}) => {
832
+ const querySerializer = (queryParams) => {
833
+ const search = [];
834
+ if (queryParams && typeof queryParams === "object") for (const name in queryParams) {
835
+ const value = queryParams[name];
836
+ if (value === void 0 || value === null) continue;
837
+ const options = parameters[name] || args;
838
+ if (Array.isArray(value)) {
839
+ const serializedArray = serializeArrayParam({
840
+ allowReserved: options.allowReserved,
841
+ explode: true,
842
+ name,
843
+ style: "form",
844
+ value,
845
+ ...options.array
846
+ });
847
+ if (serializedArray) search.push(serializedArray);
848
+ } else if (typeof value === "object") {
849
+ const serializedObject = serializeObjectParam({
850
+ allowReserved: options.allowReserved,
851
+ explode: true,
852
+ name,
853
+ style: "deepObject",
854
+ value,
855
+ ...options.object
856
+ });
857
+ if (serializedObject) search.push(serializedObject);
858
+ } else {
859
+ const serializedPrimitive = serializePrimitiveParam({
860
+ allowReserved: options.allowReserved,
861
+ name,
862
+ value
863
+ });
864
+ if (serializedPrimitive) search.push(serializedPrimitive);
865
+ }
866
+ }
867
+ return search.join("&");
868
+ };
869
+ return querySerializer;
870
+ };
871
+ /**
872
+ * Infers parseAs value from provided Content-Type header.
873
+ */
874
+ const getParseAs = (contentType) => {
875
+ if (!contentType) return "stream";
876
+ const cleanContent = contentType.split(";")[0]?.trim();
877
+ if (!cleanContent) return;
878
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) return "json";
879
+ if (cleanContent === "multipart/form-data") return "formData";
880
+ if ([
881
+ "application/",
882
+ "audio/",
883
+ "image/",
884
+ "video/"
885
+ ].some((type) => cleanContent.startsWith(type))) return "blob";
886
+ if (cleanContent.startsWith("text/")) return "text";
887
+ };
888
+ const checkForExistence = (options, name) => {
889
+ if (!name) return false;
890
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) return true;
891
+ return false;
892
+ };
893
+ const setAuthParams = async ({ security, ...options }) => {
894
+ for (const auth of security) {
895
+ if (checkForExistence(options, auth.name)) continue;
896
+ const token = await getAuthToken(auth, options.auth);
897
+ if (!token) continue;
898
+ const name = auth.name ?? "Authorization";
899
+ switch (auth.in) {
900
+ case "query":
901
+ if (!options.query) options.query = {};
902
+ options.query[name] = token;
903
+ break;
904
+ case "cookie":
905
+ options.headers.append("Cookie", `${name}=${token}`);
906
+ break;
907
+ default:
908
+ options.headers.set(name, token);
909
+ break;
910
+ }
911
+ }
912
+ };
913
+ const buildUrl = (options) => getUrl({
914
+ baseUrl: options.baseUrl,
915
+ path: options.path,
916
+ query: options.query,
917
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
918
+ url: options.url
919
+ });
920
+ const mergeConfigs = (a, b) => {
921
+ const config = {
922
+ ...a,
923
+ ...b
924
+ };
925
+ if (config.baseUrl?.endsWith("/")) config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
926
+ config.headers = mergeHeaders(a.headers, b.headers);
927
+ return config;
928
+ };
929
+ const headersEntries = (headers) => {
930
+ const entries = [];
931
+ headers.forEach((value, key) => {
932
+ entries.push([key, value]);
933
+ });
934
+ return entries;
935
+ };
936
+ const mergeHeaders = (...headers) => {
937
+ const mergedHeaders = new Headers();
938
+ for (const header of headers) {
939
+ if (!header) continue;
940
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
941
+ for (const [key, value] of iterator) if (value === null) mergedHeaders.delete(key);
942
+ else if (Array.isArray(value)) for (const v of value) mergedHeaders.append(key, v);
943
+ else if (value !== void 0) mergedHeaders.set(key, typeof value === "object" ? JSON.stringify(value) : value);
944
+ }
945
+ return mergedHeaders;
946
+ };
947
+ var Interceptors = class {
948
+ fns = [];
949
+ clear() {
950
+ this.fns = [];
951
+ }
952
+ eject(id) {
953
+ const index = this.getInterceptorIndex(id);
954
+ if (this.fns[index]) this.fns[index] = null;
955
+ }
956
+ exists(id) {
957
+ const index = this.getInterceptorIndex(id);
958
+ return Boolean(this.fns[index]);
959
+ }
960
+ getInterceptorIndex(id) {
961
+ if (typeof id === "number") return this.fns[id] ? id : -1;
962
+ return this.fns.indexOf(id);
963
+ }
964
+ update(id, fn) {
965
+ const index = this.getInterceptorIndex(id);
966
+ if (this.fns[index]) {
967
+ this.fns[index] = fn;
968
+ return id;
969
+ }
970
+ return false;
971
+ }
972
+ use(fn) {
973
+ this.fns.push(fn);
974
+ return this.fns.length - 1;
975
+ }
976
+ };
977
+ const createInterceptors = () => ({
978
+ error: new Interceptors(),
979
+ request: new Interceptors(),
980
+ response: new Interceptors()
981
+ });
982
+ const defaultQuerySerializer = createQuerySerializer({
983
+ allowReserved: false,
984
+ array: {
985
+ explode: true,
986
+ style: "form"
987
+ },
988
+ object: {
989
+ explode: true,
990
+ style: "deepObject"
991
+ }
992
+ });
993
+ const defaultHeaders = { "Content-Type": "application/json" };
994
+ const createConfig = (override = {}) => ({
995
+ ...jsonBodySerializer,
996
+ headers: defaultHeaders,
997
+ parseAs: "auto",
998
+ querySerializer: defaultQuerySerializer,
999
+ ...override
1000
+ });
1001
+ //#endregion
1002
+ //#region src/generated/client/client.gen.ts
1003
+ const createClient = (config = {}) => {
1004
+ let _config = mergeConfigs(createConfig(), config);
1005
+ const getConfig = () => ({ ..._config });
1006
+ const setConfig = (config) => {
1007
+ _config = mergeConfigs(_config, config);
1008
+ return getConfig();
1009
+ };
1010
+ const interceptors = createInterceptors();
1011
+ const beforeRequest = async (options) => {
1012
+ const opts = {
1013
+ ..._config,
1014
+ ...options,
1015
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
1016
+ headers: mergeHeaders(_config.headers, options.headers),
1017
+ serializedBody: void 0
1018
+ };
1019
+ if (opts.security) await setAuthParams({
1020
+ ...opts,
1021
+ security: opts.security
1022
+ });
1023
+ if (opts.requestValidator) await opts.requestValidator(opts);
1024
+ if (opts.body !== void 0 && opts.bodySerializer) opts.serializedBody = opts.bodySerializer(opts.body);
1025
+ if (opts.body === void 0 || opts.serializedBody === "") opts.headers.delete("Content-Type");
1026
+ return {
1027
+ opts,
1028
+ url: buildUrl(opts)
1029
+ };
1030
+ };
1031
+ const request = async (options) => {
1032
+ const { opts, url } = await beforeRequest(options);
1033
+ const requestInit = {
1034
+ redirect: "follow",
1035
+ ...opts,
1036
+ body: getValidRequestBody(opts)
1037
+ };
1038
+ let request = new Request(url, requestInit);
1039
+ for (const fn of interceptors.request.fns) if (fn) request = await fn(request, opts);
1040
+ const _fetch = opts.fetch;
1041
+ let response;
1042
+ try {
1043
+ response = await _fetch(request);
1044
+ } catch (error) {
1045
+ let finalError = error;
1046
+ for (const fn of interceptors.error.fns) if (fn) finalError = await fn(error, void 0, request, opts);
1047
+ finalError = finalError || {};
1048
+ if (opts.throwOnError) throw finalError;
1049
+ return opts.responseStyle === "data" ? void 0 : {
1050
+ error: finalError,
1051
+ request,
1052
+ response: void 0
1053
+ };
1054
+ }
1055
+ for (const fn of interceptors.response.fns) if (fn) response = await fn(response, request, opts);
1056
+ const result = {
1057
+ request,
1058
+ response
1059
+ };
1060
+ if (response.ok) {
1061
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
1062
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
1063
+ let emptyData;
1064
+ switch (parseAs) {
1065
+ case "arrayBuffer":
1066
+ case "blob":
1067
+ case "text":
1068
+ emptyData = await response[parseAs]();
1069
+ break;
1070
+ case "formData":
1071
+ emptyData = new FormData();
1072
+ break;
1073
+ case "stream":
1074
+ emptyData = response.body;
1075
+ break;
1076
+ default:
1077
+ emptyData = {};
1078
+ break;
1079
+ }
1080
+ return opts.responseStyle === "data" ? emptyData : {
1081
+ data: emptyData,
1082
+ ...result
1083
+ };
1084
+ }
1085
+ let data;
1086
+ switch (parseAs) {
1087
+ case "arrayBuffer":
1088
+ case "blob":
1089
+ case "formData":
1090
+ case "json":
1091
+ case "text":
1092
+ data = await response[parseAs]();
1093
+ break;
1094
+ case "stream": return opts.responseStyle === "data" ? response.body : {
1095
+ data: response.body,
1096
+ ...result
1097
+ };
1098
+ }
1099
+ if (parseAs === "json") {
1100
+ if (opts.responseValidator) await opts.responseValidator(data);
1101
+ if (opts.responseTransformer) data = await opts.responseTransformer(data);
1102
+ }
1103
+ return opts.responseStyle === "data" ? data : {
1104
+ data,
1105
+ ...result
1106
+ };
1107
+ }
1108
+ const textError = await response.text();
1109
+ let jsonError;
1110
+ try {
1111
+ jsonError = JSON.parse(textError);
1112
+ } catch {}
1113
+ const error = jsonError ?? textError;
1114
+ let finalError = error;
1115
+ for (const fn of interceptors.error.fns) if (fn) finalError = await fn(error, response, request, opts);
1116
+ finalError = finalError || {};
1117
+ if (opts.throwOnError) throw finalError;
1118
+ return opts.responseStyle === "data" ? void 0 : {
1119
+ error: finalError,
1120
+ ...result
1121
+ };
1122
+ };
1123
+ const makeMethodFn = (method) => (options) => request({
1124
+ ...options,
1125
+ method
1126
+ });
1127
+ const makeSseFn = (method) => async (options) => {
1128
+ const { opts, url } = await beforeRequest(options);
1129
+ return createSseClient({
1130
+ ...opts,
1131
+ body: opts.body,
1132
+ headers: opts.headers,
1133
+ method,
1134
+ onRequest: async (url, init) => {
1135
+ let request = new Request(url, init);
1136
+ for (const fn of interceptors.request.fns) if (fn) request = await fn(request, opts);
1137
+ return request;
1138
+ },
1139
+ url
1140
+ });
1141
+ };
1142
+ return {
1143
+ buildUrl,
1144
+ connect: makeMethodFn("CONNECT"),
1145
+ delete: makeMethodFn("DELETE"),
1146
+ get: makeMethodFn("GET"),
1147
+ getConfig,
1148
+ head: makeMethodFn("HEAD"),
1149
+ interceptors,
1150
+ options: makeMethodFn("OPTIONS"),
1151
+ patch: makeMethodFn("PATCH"),
1152
+ post: makeMethodFn("POST"),
1153
+ put: makeMethodFn("PUT"),
1154
+ request,
1155
+ setConfig,
1156
+ sse: {
1157
+ connect: makeSseFn("CONNECT"),
1158
+ delete: makeSseFn("DELETE"),
1159
+ get: makeSseFn("GET"),
1160
+ head: makeSseFn("HEAD"),
1161
+ options: makeSseFn("OPTIONS"),
1162
+ patch: makeSseFn("PATCH"),
1163
+ post: makeSseFn("POST"),
1164
+ put: makeSseFn("PUT"),
1165
+ trace: makeSseFn("TRACE")
1166
+ },
1167
+ trace: makeMethodFn("TRACE")
1168
+ };
1169
+ };
1170
+ //#endregion
1171
+ //#region src/wrappers/client.ts
1172
+ const API_VERSION = "2026-03-06.v1";
1173
+ function createApiClient(config) {
1174
+ const headers = new Headers({ "gt-api-version": config.apiVersion ?? "2026-03-06.v1" });
1175
+ if (config.apiKey) headers.set("Authorization", `Bearer ${config.apiKey}`);
1176
+ if (config.projectId) headers.set("gt-project-id", config.projectId);
1177
+ return createClient({
1178
+ baseUrl: config.baseUrl,
1179
+ fetch: createRetryingFetch({
1180
+ fetch: createTimeoutFetch({
1181
+ fetch: config.fetch,
1182
+ timeoutMs: config.timeoutMs
1183
+ }),
1184
+ retryPolicy: config.retryPolicy
1185
+ }),
1186
+ headers
1187
+ });
1188
+ }
1189
+ //#endregion
1190
+ export { API_VERSION, DEFAULT_BATCH_SIZE, awaitJobs, createApiClient, createBranch, createCliWizardSession, createProject, createTag, decodeBase64, decodeFileContent, deleteCliWizardSession, downloadFile, downloadFiles, encodeBase64, encodeFileContent, enqueueFileTranslations, generateProjectContext, getBranchInfo, getCliWizardSession, getFileInfo, getOrphanedFiles, getProjectContextGenerationStatus, getProjectInfo, getTranslationJobInfo, getTranslationStatus, processBatches, processFileMoves, publishFiles, shouldGenerateProjectContext, submitUserEditDiffs, translate, updateProjectInfo, uploadAssets, uploadSourceFiles, uploadTranslations };
1191
+
1192
+ //# sourceMappingURL=index.mjs.map