All files Transloadit.ts

84.45% Statements 364/431
74.68% Branches 292/391
86.66% Functions 78/90
85.35% Lines 344/403

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789                                                                                                                                                                                                                                                                                                                                                                                                42x 42x                         42x                       42x         24x 23x     42x 1x 1x           42x 10x 10x 1x   9x     42x 70x   44x 34x 34x     10x 10x     10x 10x       42x 69x 43x       42x 64x 64x 43x     64x 64x                                                                                                                                                                                                                                     154x 2x         175x       11x 11x     11x           317x           5x                                                                                                                                                                               697x             812x 812x   3x 812x   2x 2x 1x         697x       697x 697x   697x 1x     696x 686x 1x     685x 1x       694x 697x 697x 697x 697x 697x 697x 697x 697x 697x     697x   697x               1x         85x         47x             11x         5x               6x 6x 6x           4x 4x 4x       1x       3x             221x 221x           207x 207x 207x 2x   199x               5x 5x 5x 1x   2x           2x 2x     2x 1x     1x               2x 2x         1x 1x             1x       1x                                               60x     60x           60x 1x   59x   60x     60x 60x   60x   29x       59x 28x         8x             59x   59x     59x               59x   59x   58x   58x                   53x 53x   58x 31x                 31x 2x       51x 58x   8x         8x           8x 8x     59x       60x                                                                                                                                                                             1x           1x               1x       1x                                   11x   11x   11x 11x       11x   11x 11x 2x 2x   11x 7x 1x 1x     11x 11x 7x 6x 5x 5x     11x   11x     8x 8x 8x                   11x 2x               11x 10x 10x     11x 11x 8x 6x 8x 6x 6x     11x 11x   11x 6x   6x                     6x 5x 5x         10x       10x     10x 11x   1x           1x             1x 1x                             46x       46x 109x         46x   110x 1x       109x       109x 109x       109x                     42x     67x 67x         67x 67x 2x       65x 65x 64x 64x       1x 1x     65x           1x         1x 1x                             4x 3x 3x           3x   3x           3x 3x                           4x         4x 4x                           1x                               237x                 236x                   236x   236x           236x             236x                           142x                             152x             149x   149x 1x 1x         148x 148x                       1x                                   1x                           1x                         2x                             1x                                       16x                             4x                           15x               3x               2x 2x                   34x                             4x                               12x           8x 8x               3x           2x 2x             30x         25x 25x                     2x 2x                   798x     798x 798x   798x             7x     7x               802x     802x           126x 126x     126x 115x 115x 115x     126x   126x 56x 56x       126x 115x             688x   688x 688x 23x 23x     665x   665x         801x 801x 2x   801x 773x   801x 776x   801x 775x     801x         772x 772x 772x                                                     810x     810x 810x 810x               810x 687x     810x       810x     812x 125x 125x     812x                                 812x 812x 812x     768x                   768x   43x   43x 29x 29x       29x   29x   29x                     29x         29x               29x 2x 2x     2x 2x     27x           14x            
import type { Readable } from 'node:stream'
 
import type {
  CompileAssemblyInstructionsOptions,
  CompileAssemblyInstructionsResult,
} from '@transloadit/utils'
import type { SignatureAlgorithm } from '@transloadit/utils/node'
import type {
  BeforeRedirectHook,
  Delays,
  Headers,
  OptionsOfJSONResponseBody,
  RetryOptions,
} from 'got'
import type { Input as IntoStreamInput } from 'into-stream'
 
import type { TransloaditErrorResponseBody } from './ApiError.ts'
import type {
  AssemblyIndex,
  AssemblyIndexItem,
  AssemblyStatus,
} from './alphalib/types/assemblyStatus.ts'
import type {
  GetStoredAssetOptions,
  ListStoredAssetsOptions,
  MoveStoredAssetOptions,
  StoredAsset,
  StoredAssetsPage,
} from './alphalib/types/storageAsset.ts'
import type {
  BaseResponse,
  BillResponse,
  CreateAssemblyParams,
  CreateTemplateCredentialParams,
  CreateTemplateParams,
  EditTemplateParams,
  ListAssembliesParams,
  ListedTemplate,
  ListTemplateCredentialsParams,
  ListTemplatesParams,
  OptionalAuthParams,
  PaginationListWithCount,
  ReplayAssemblyNotificationParams,
  ReplayAssemblyNotificationResponse,
  ReplayAssemblyParams,
  ReplayAssemblyResponse,
  TemplateCredentialResponse,
  TemplateCredentialsResponse,
  TemplateResponse,
} from './apiTypes.ts'
import type { BearerTokenResponse, MintBearerTokenOptions } from './bearerToken.ts'
import type {
  LintAssemblyInstructionsInput,
  LintAssemblyInstructionsResult,
} from './lintAssemblyInstructions.ts'
import type {
  GetStoredImageReceiptOptions,
  StoredImageReceipt,
  StoreImageOptions,
} from './storageImage.ts'
import type {
  StoragePublicPrefixDeclared,
  StoragePublicPrefixes,
  StoragePublicPrefixRevoked,
} from './storagePublicPrefixes.ts'
import type {
  GetStoredAssemblyResultsOptions,
  StoredAssemblyResult,
  StoredAssetUrlOptions,
} from './storageResults.ts'
import type { Stream, UploadBehavior } from './tus.ts'
 
import * as assert from 'node:assert'
import { randomUUID } from 'node:crypto'
import { constants, createReadStream } from 'node:fs'
import { access, stat } from 'node:fs/promises'
import { basename } from 'node:path'
import { setTimeout as delay } from 'node:timers/promises'
 
import { compileAssemblyInstructionsFromPrompt } from '@transloadit/utils'
import { getSignedSmartCdnUrl, signParamsSync } from '@transloadit/utils/node'
import debug from 'debug'
import FormData from 'form-data'
import got, { HTTPError, RequestError } from 'got'
import intoStream from 'into-stream'
import { isReadableStream, isStream } from 'is-stream'
import pMap from 'p-map'
import { z } from 'zod'
 
import packageJson from '../package.json' with { type: 'json' }
import { ApiError } from './ApiError.ts'
import { assemblyIndexSchema, assemblyStatusSchema } from './alphalib/types/assemblyStatus.ts'
import {
  damAssetFoundResponseSchema,
  damAssetGetOptionsSchema,
  damAssetMoveOptionsSchema,
  damAssetsListedResponseSchema,
  damAssetsListOptionsSchema,
  damIdSchema,
  storedAssetSchema,
} from './alphalib/types/storageAsset.ts'
import { zodParseWithContext } from './alphalib/zodParseWithContext.ts'
import { mintBearerTokenWithCredentials } from './bearerToken.ts'
import InconsistentResponseError from './InconsistentResponseError.ts'
import { lintAssemblyInstructions as lintAssemblyInstructionsInternal } from './lintAssemblyInstructions.ts'
import PaginationStream from './PaginationStream.ts'
import PollingTimeoutError from './PollingTimeoutError.ts'
import { getStoredImageReceipt, storeImage } from './storageImage.ts'
import {
  normalizeStoragePublicPrefix,
  storagePublicPrefixDeclaredSchema,
  storagePublicPrefixesSchema,
  storagePublicPrefixRevokedSchema,
} from './storagePublicPrefixes.ts'
import { getStoredAssemblyResults, getStoredAssetUrl } from './storageResults.ts'
import { sendTusRequest } from './tus.ts'
 
export type {
  CompileAssemblyInstructionsAttempt,
  CompileAssemblyInstructionsClient,
  CompileAssemblyInstructionsLintIssue,
  CompileAssemblyInstructionsMessage,
  CompileAssemblyInstructionsResult,
} from '@transloadit/utils'
 
export type { AssemblyStatus } from './alphalib/types/assemblyStatus.ts'
export type {
  GetStoredAssetOptions,
  ListStoredAssetsOptions,
  MoveStoredAssetOptions,
  StoredAsset,
  StoredAssetsPage,
} from './alphalib/types/storageAsset.ts'
export type {
  Base64Strategy,
  InputFile,
  PrepareInputFilesOptions,
  PrepareInputFilesResult,
  UploadInput,
  UrlStrategy,
} from './inputFiles.ts'
export type { LintAssemblyInstructionsResult, LintFatalLevel } from './lintAssemblyInstructions.ts'
export type {
  RobotHelp,
  RobotHelpOptions,
  RobotListItem,
  RobotListOptions,
  RobotListResult,
  RobotParamHelp,
} from './robots.ts'
export type {
  GetStoredImageReceiptOptions,
  StoredImageExpectation,
  StoredImageReceipt,
  StoreImageOptions,
} from './storageImage.ts'
export type {
  StoragePublicPrefixDeclared,
  StoragePublicPrefixes,
  StoragePublicPrefixRevoked,
} from './storagePublicPrefixes.ts'
export type {
  GetStoredAssemblyResultsOptions,
  StoredAssemblyResult,
  StoredAssetUrlOptions,
} from './storageResults.ts'
 
export {
  buildCompileAssemblyInstructionsSystemPrompt,
  CompileAssemblyInstructionsError,
  parseCompileAssemblyInstructionsResponse,
} from '@transloadit/utils'
// See https://github.com/sindresorhus/got/tree/v11.8.6?tab=readme-ov-file#errors
// Expose relevant errors
export {
  HTTPError,
  MaxRedirectsError,
  ParseError,
  ReadError,
  RequestError,
  TimeoutError,
  UploadError,
} from 'got'
 
export { extractFieldNamesFromTemplate } from './alphalib/stepParsing.ts'
// Builtin templates replace the legacy golden template helpers.
export { mergeTemplateContent } from './alphalib/templateMerge.ts'
export * from './apiTypes.ts'
export { prepareInputFiles } from './inputFiles.ts'
export { getRobotHelp, isKnownRobot, listRobots } from './robots.ts'
export { ApiError, InconsistentResponseError }
 
const log = debug('transloadit')
const logWarn = debug('transloadit:warn')
 
export interface UploadProgress {
  uploadedBytes?: number | undefined
  totalBytes?: number | undefined
}
 
export type { UploadBehavior }
 
export type AssemblyStatusWithUploadUrls = AssemblyStatus & {
  upload_urls?: Record<string, string>
}
 
const { version } = packageJson
 
export type AssemblyProgress = (assembly: AssemblyStatus) => void
 
type UploadDescriptor = {
  label: string
  filename: string
  size?: number
  path?: string
  value?: Readable | IntoStreamInput
}
 
const getUploadKey = (
  fieldname: string | null | undefined,
  filename: string | null | undefined,
  size: number | null | undefined,
): string | null => {
  if (!fieldname || !filename || size == null) return null
  return JSON.stringify([fieldname, filename, size])
}
 
const getSizeFromValue = (value: Readable | IntoStreamInput): number | undefined => {
  Iif (typeof value === 'string') return Buffer.byteLength(value)
  Eif (Buffer.isBuffer(value)) return value.length
  if (value instanceof ArrayBuffer) return value.byteLength
  if (ArrayBuffer.isView(value)) return value.byteLength
  return undefined
}
 
const toReadableUpload = (label: string, value: Readable | IntoStreamInput): Readable => {
  const readable = isReadableStream(value)
  if (!readable && isStream(value)) {
    throw new Error(`Upload named "${label}" is not a Readable stream`)
  }
  return readable ? value : intoStream(value)
}
 
const buildStreamsMap = (descriptors: UploadDescriptor[]): Record<string, Stream> =>
  Object.fromEntries(
    descriptors.map((descriptor) => {
      if (descriptor.path) {
        const stream = createReadStream(descriptor.path)
        return [descriptor.label, { stream, path: descriptor.path }]
      }
 
      const value = descriptor.value
      Iif (value == null) {
        throw new Error(`Upload named "${descriptor.label}" has no data`)
      }
      const stream = toReadableUpload(descriptor.label, value)
      return [descriptor.label, { stream }]
    }),
  )
 
const pauseStreams = (streamsMap: Record<string, Stream>): void => {
  for (const { stream } of Object.values(streamsMap)) {
    stream.pause()
  }
}
 
const createStreamErrorPromise = (streamsMap: Record<string, Stream>): Promise<never> => {
  const promise = new Promise<never>((_resolve, reject) => {
    for (const { stream } of Object.values(streamsMap)) {
      stream.on('error', reject)
    }
  })
  promise.catch(() => {})
  return promise
}
 
interface AssemblyUploadOptions {
  files?: {
    [name: string]: string
  }
  uploads?: {
    [name: string]: Readable | IntoStreamInput
  }
  uploadBehavior?: UploadBehavior
  waitForCompletion?: boolean
  chunkSize?: number
  uploadConcurrency?: number
  timeout?: number
  onUploadProgress?: (uploadProgress: UploadProgress) => void
  onAssemblyProgress?: AssemblyProgress
  /**
   * Optional AbortSignal to cancel the upload and any follow-up polling.
   * When aborted, any in-flight HTTP requests and TUS uploads will be cancelled.
   */
  signal?: AbortSignal
}
 
export interface CreateAssemblyOptions extends AssemblyUploadOptions {
  params?: CreateAssemblyParams
  assemblyId?: string
  /**
   * Expected number of tus uploads when files will be uploaded separately.
   */
  expectedUploads?: number
  /**
   * Called once API2 has accepted the creation request, before uploads and polling. Callers that
   * must not create an Assembly twice use it to tell later failures apart from rejected creation.
   */
  onAssemblyCreated?: (assembly: AssemblyStatus) => void
}
 
export interface ResumeAssemblyUploadsOptions extends AssemblyUploadOptions {
  assemblyUrl: string
}
 
export interface AwaitAssemblyCompletionOptions {
  onAssemblyProgress?: AssemblyProgress
  timeout?: number
  interval?: number
  startTimeMs?: number
  /**
   * Optional assembly URL to poll instead of the configured client endpoint.
   * Useful when resuming an Assembly created on a different host/region.
   */
  assemblyUrl?: string
  /**
   * Optional AbortSignal to cancel polling.
   * When aborted, the polling loop will stop and throw an AbortError.
   */
  signal?: AbortSignal
  /**
   * Optional callback invoked before each poll iteration.
   * Return `false` to stop polling early and return the current assembly status.
   * Useful for watch mode where a newer job may supersede the current one.
   */
  onPoll?: () => boolean | undefined
}
 
export interface LintAssemblyInstructionsOptions
  extends Omit<LintAssemblyInstructionsInput, 'template'> {
  /**
   * Template ID to merge with the provided instructions before linting.
   */
  templateId?: string
}
 
export interface SmartCDNUrlOptions {
  /**
   * Workspace slug
   */
  workspace: string
  /**
   * Template slug or template ID
   */
  template: string
  /**
   * Input value that is provided as `${fields.input}` in the template
   */
  input: string
  /**
   * Additional parameters for the URL query string
   */
  urlParams?: Record<string, boolean | number | string | (boolean | number | string)[]>
  /**
   * Expiration timestamp of the signature in milliseconds since UNIX epoch.
   * Defaults to 1 hour from now.
   */
  expiresAt?: number
}
 
export type CompileAssemblyInstructionsFromPromptOptions = Omit<
  CompileAssemblyInstructionsOptions,
  'client'
> & {
  timeout?: number
}
 
export type Fields = Record<string, string | number>
 
// A special promise that lets the user immediately get the assembly ID (synchronously before the request is sent)
interface CreateAssemblyPromise extends Promise<AssemblyStatusWithUploadUrls> {
  assemblyId: string
}
 
// Not sure if this is still a problem with the API, but throw a special error type so the user can retry if needed
function checkAssemblyUrls(
  result: AssemblyStatus,
): asserts result is AssemblyStatus & { assembly_url: string; assembly_ssl_url: string } {
  if (result.assembly_url == null || result.assembly_ssl_url == null) {
    throw new InconsistentResponseError('Server returned an incomplete assembly response (no URL)')
  }
}
 
function getHrTimeMs(): number {
  return Number(process.hrtime.bigint() / 1000000n)
}
 
function getAssemblyIdFromUrl(assemblyUrl: string): string {
  const match = assemblyUrl.match(/\/assemblies\/([^/?#]+)/)
  Iif (!match) {
    throw new Error(`Invalid assembly URL: ${assemblyUrl}`)
  }
  return match[1] ?? ''
}
 
function checkResult<T>(result: T | { error: string }): asserts result is T {
  // In case server returned a successful HTTP status code, but an `error` in the JSON object
  // This happens sometimes, for example when createAssembly with an invalid file (IMPORT_FILE_ERROR)
  if (
    typeof result === 'object' &&
    result !== null &&
    'error' in result &&
    typeof result.error === 'string'
  ) {
    throw new ApiError({ body: result }) // in this case there is no `cause` because we don't have an HTTPError
  }
}
 
function getResultBilledChargeUsd(result: unknown): number | undefined {
  if (typeof result !== 'object' || result === null || Array.isArray(result)) {
    return undefined
  }
 
  if (!('meta' in result)) {
    return undefined
  }
 
  const { meta } = result
  if (typeof meta !== 'object' || meta === null || Array.isArray(meta)) {
    return undefined
  }
 
  if (!('billed_charge_usd' in meta)) {
    return undefined
  }
 
  const { billed_charge_usd: billedChargeUsd } = meta
  return typeof billedChargeUsd === 'number' ? billedChargeUsd : undefined
}
 
async function fetchJson(url: string): Promise<unknown> {
  const response = await fetch(url)
  if (!response.ok) {
    throw new Error(`Failed to fetch AI response: ${response.status} ${response.statusText}`)
  }
 
  return await response.json()
}
 
type AuthKeySecret = {
  authKey: string
  authSecret: string
  authToken?: undefined
}
 
type AuthToken = {
  authToken: string
  authKey?: string
  authSecret?: string
}
 
type BaseOptions = {
  /** Use signatureAlgorithm: 'sha256' for new combined Smart CDN/Assembly keys; legacy default: sha384. */
  signatureAlgorithm?: SignatureAlgorithm
  endpoint?: string
  maxRetries?: number
  timeout?: number
  gotRetry?: Partial<RetryOptions>
  /** Follow API redirects. Disable when requests originate from untrusted callers. Defaults to true. */
  followRedirects?: boolean
  validateResponses?: boolean
  clientName?: string
  /**
   * Fixed headers sent with every API request, for trusted relays such as the Transloadit-hosted
   * MCP service that must identify itself to API2 next to a forwarded bearer token.
   */
  extraHeaders?: Record<string, string>
}
 
export type Options = BaseOptions & (AuthKeySecret | AuthToken)
 
export class Transloadit {
  #signatureAlgorithm: SignatureAlgorithm
  #followRedirects: boolean
  private _authKey: string
 
  private _authSecret: string
 
  private _authToken: string | null
 
  private _endpoint: string
 
  private _maxRetries: number
 
  private _defaultTimeout: number
 
  private _gotRetry: Partial<RetryOptions>
 
  private _clientName: string
 
  #extraHeaders: Record<string, string>
 
  private _lastUsedAssemblyUrl = ''
 
  /**
   * got drops `Authorization` and cookies when a redirect changes origin, but not custom headers,
   * so `extraHeaders` (such as a relay's shared secret) are removed the same way.
   */
  #dropExtraHeadersOffOrigin(requestUrl: string): BeforeRedirectHook[] {
    const names = Object.keys(this.#extraHeaders).map((name) => name.toLowerCase())
    if (names.length === 0) return []
    // An unparseable request URL counts as a different origin, which drops the headers.
    const requestOrigin = URL.canParse(requestUrl) ? new URL(requestUrl).origin : undefined
    return [
      (redirectOptions) => {
        const redirectUrl = redirectOptions.url
        if (requestOrigin && redirectUrl && new URL(redirectUrl).origin === requestOrigin) return
        for (const name of names) delete redirectOptions.headers[name]
      },
    ]
  }
 
  private _validateResponses = false
 
  /** Create a client; new combined keys require signatureAlgorithm: 'sha256' explicitly. */
  constructor(opts: Options) {
    const rawToken = typeof opts?.authToken === 'string' ? opts.authToken.trim() : ''
    const hasToken = rawToken.length > 0
 
    if (opts.endpoint?.endsWith('/')) {
      throw new Error('Trailing slash in endpoint is not allowed')
    }
 
    if (!hasToken) {
      if (opts?.authKey == null) {
        throw new Error('Please provide an authKey')
      }
 
      if (opts.authSecret == null) {
        throw new Error('Please provide an authSecret')
      }
    }
 
    this._authKey = opts.authKey ?? ''
    this._authSecret = opts.authSecret ?? ''
    this.#signatureAlgorithm = opts.signatureAlgorithm ?? 'sha384'
    this._authToken = hasToken ? rawToken : null
    this.#followRedirects = opts.followRedirects ?? true
    this._endpoint = opts.endpoint || 'https://api2.transloadit.com'
    this._maxRetries = opts.maxRetries != null ? opts.maxRetries : 5
    this._defaultTimeout = opts.timeout != null ? opts.timeout : 60000
    this._clientName = opts.clientName?.trim() || `node-sdk:${version}`
    this.#extraHeaders = { ...opts.extraHeaders }
 
    // Passed on to got https://github.com/sindresorhus/got/blob/main/documentation/7-retry.md
    this._gotRetry = opts.gotRetry != null ? opts.gotRetry : { limit: 0 }
 
    if (opts.validateResponses != null) this._validateResponses = opts.validateResponses
  }
 
  getLastUsedAssemblyUrl(): string {
    return this._lastUsedAssemblyUrl
  }
 
  setDefaultTimeout(timeout: number): void {
    this._defaultTimeout = timeout
  }
 
  /** Stores one local original at an explicit path and returns its verified image metadata. */
  storeImage(filePath: string, options: StoreImageOptions): Promise<StoredImageReceipt> {
    return storeImage(this, filePath, options)
  }
 
  /** Reconstructs a verified receipt from authoritative Assembly status and trusted upload facts. */
  getStoredImageReceipt(options: GetStoredImageReceiptOptions): Promise<StoredImageReceipt> {
    return getStoredImageReceipt(this, options)
  }
 
  /** Verifies a completed batch's retained media and preserves result/input provenance. */
  getStoredAssemblyResults(
    options: GetStoredAssemblyResultsOptions,
  ): Promise<StoredAssemblyResult[]> {
    return getStoredAssemblyResults(this, options)
  }
 
  /** Signs exact original bytes after your app authorizes the asset. Use a 307 for fresh request-time authorization. */
  getStoredAssetUrl(asset: StoredAsset, options?: StoredAssetUrlOptions): string {
    return getStoredAssetUrl(this, asset, options)
  }
 
  /** Reads a live asset's current version, or the exact retained version when version_id is set. */
  async getStoredAsset(
    assetId: string,
    options: GetStoredAssetOptions & { signal?: AbortSignal } = {},
  ): Promise<StoredAsset> {
    const id = damIdSchema.parse(assetId)
    const params = damAssetGetOptionsSchema.parse(options)
    const result = await this._remoteJson<unknown, OptionalAuthParams & GetStoredAssetOptions>({
      urlSuffix: `/dam/assets/${id}`,
      method: 'get',
      params,
      signal: options.signal,
    })
    checkResult(result)
    const { asset } = damAssetFoundResponseSchema.parse(result)
    if (
      asset.asset_id !== id ||
      (params.version_id !== undefined && asset.version_id !== params.version_id)
    ) {
      throw new InconsistentResponseError(
        'The response did not match the requested Storage reference',
      )
    }
    return asset
  }
 
  /** Reads one bounded catalog page without S3 credentials or a HEAD request per object. */
  async listStoredAssets(
    options: ListStoredAssetsOptions & { signal?: AbortSignal } = {},
  ): Promise<StoredAssetsPage> {
    const params = damAssetsListOptionsSchema.parse(options)
    const result = await this._remoteJson<unknown, OptionalAuthParams & ListStoredAssetsOptions>({
      urlSuffix: '/dam/assets',
      method: 'get',
      params,
      signal: options.signal,
    })
    checkResult(result)
    const page = damAssetsListedResponseSchema.parse(result)
    if (page.assets.some((asset) => asset.workspace !== page.workspace)) {
      throw new InconsistentResponseError('Storage catalog page contains a different Workspace')
    }
    return page
  }
 
  /** Moves or renames an asset natively, preserving asset and version identities. */
  async moveStoredAsset(
    assetId: string,
    options: MoveStoredAssetOptions & { signal?: AbortSignal },
  ): Promise<StoredAsset> {
    const id = damIdSchema.parse(assetId)
    const params = damAssetMoveOptionsSchema.parse(options)
    if (params.filename === undefined && params.destination_folder_id === undefined) {
      throw new TypeError('Provide filename or destination_folder_id for a Storage move')
    }
    const result = await this._remoteJson<unknown, OptionalAuthParams & MoveStoredAssetOptions>({
      urlSuffix: `/dam/assets/${id}`,
      method: 'patch',
      params,
      signal: options.signal,
    })
    checkResult(result)
    const { asset } = z
      .object({ ok: z.literal('DAM_ASSET_MOVED'), asset: storedAssetSchema })
      .parse(result)
    if (asset.asset_id !== id)
      throw new InconsistentResponseError(
        'The response did not match the requested Storage reference',
      )
    return asset
  }
 
  /** Soft-deletes an asset by identity, making retained versions unavailable for new reads. */
  async deleteStoredAsset(
    assetId: string,
    options: { signal?: AbortSignal } = {},
  ): Promise<{ asset_id: string; deleted_at: string }> {
    const id = damIdSchema.parse(assetId)
    const result = await this._remoteJson<unknown, OptionalAuthParams>({
      urlSuffix: `/dam/assets/${id}`,
      method: 'delete',
      signal: options.signal,
    })
    checkResult(result)
    const receipt = z
      .object({
        ok: z.literal('DAM_ASSET_DELETED'),
        asset_id: damIdSchema,
        deleted_at: z.string().datetime(),
      })
      .parse(result)
    Iif (receipt.asset_id !== id)
      throw new InconsistentResponseError(
        'The response did not match the requested Storage reference',
      )
    return { asset_id: receipt.asset_id, deleted_at: receipt.deleted_at }
  }
 
  /**
   * Create an Assembly
   *
   * @param opts assembly options
   */
  createAssembly(opts: CreateAssemblyOptions = {}): CreateAssemblyPromise {
    const {
      params = {},
      waitForCompletion = false,
      chunkSize: requestedChunkSize = Number.POSITIVE_INFINITY,
      uploadConcurrency = 10,
      timeout = 24 * 60 * 60 * 1000, // 1 day
      onUploadProgress = () => {},
      onAssemblyProgress = () => {},
      files = {},
      uploads = {},
      assemblyId,
      expectedUploads,
      onAssemblyCreated,
      signal,
      uploadBehavior = 'await',
    } = opts
 
    // Keep track of how long the request took
    const startTimeMs = getHrTimeMs()
 
    // Undocumented feature to allow specifying a custom assembly id from the client
    // Not recommended for general use due to security. E.g if the user doesn't provide a cryptographically
    // secure ID, then anyone could access the assembly.
    let effectiveAssemblyId: string
    if (assemblyId != null) {
      effectiveAssemblyId = assemblyId
    } else {
      effectiveAssemblyId = randomUUID().replace(/-/g, '')
    }
    const urlSuffix = `/assemblies/${effectiveAssemblyId}`
 
    // We want to be able to return the promise immediately with custom data
    const promise = (async () => {
      this._lastUsedAssemblyUrl = `${this._endpoint}${urlSuffix}`
 
      await pMap(
        Object.entries(files),
        async ([, path]) => access(path, constants.F_OK | constants.R_OK),
        { concurrency: 5 },
      )
 
      const descriptors: UploadDescriptor[] = [
        ...Object.entries(files).map(([label, path]) => ({
          label,
          path,
          filename: basename(path),
        })),
        ...Object.entries(uploads).map(([label, value]) => ({
          label,
          filename: label,
          value,
        })),
      ]
 
      const allStreamsMap = buildStreamsMap(descriptors)
 
      const allStreams = Object.values(allStreamsMap)
 
      // Pause all streams
      pauseStreams(allStreamsMap)
 
      // If any stream emits error, we want to handle this and exit with error.
      // This promise races against createAssemblyAndUpload() below via Promise.race().
      // When createAssemblyAndUpload wins the race, this promise becomes "orphaned" -
      // it's no longer awaited, but stream error handlers remain attached.
      // The no-op catch prevents Node's unhandled rejection warning if a stream
      // errors after the race is already won.
      const streamErrorPromise = createStreamErrorPromise(allStreamsMap)
 
      const createAssemblyAndUpload = async () => {
        const totalExpectedUploads =
          expectedUploads == null ? allStreams.length : Math.max(expectedUploads, allStreams.length)
 
        const result: AssemblyStatusWithUploadUrls = await this._remoteJson({
          urlSuffix,
          method: 'post',
          timeout: { request: timeout },
          params,
          fields: {
            tus_num_expected_upload_files: totalExpectedUploads,
          },
          signal,
        })
        checkResult(result)
        onAssemblyCreated?.(result)
 
        if (Object.keys(allStreamsMap).length > 0) {
          const { uploadUrls } = await sendTusRequest({
            streamsMap: allStreamsMap,
            assembly: result,
            onProgress: onUploadProgress,
            requestedChunkSize,
            uploadConcurrency,
            signal,
            uploadBehavior,
          })
          if (uploadBehavior !== 'await' && Object.keys(uploadUrls).length > 0) {
            result.upload_urls = uploadUrls
          }
        }
 
        const shouldWaitForCompletion = waitForCompletion && uploadBehavior === 'await'
        if (!shouldWaitForCompletion) return result
 
        Iif (result.assembly_id == null) {
          throw new InconsistentResponseError(
            'Server returned an assembly response without an assembly_id after creation',
          )
        }
        const awaitResult = await this.awaitAssemblyCompletion(result.assembly_id, {
          timeout,
          onAssemblyProgress,
          startTimeMs,
          signal,
        })
        checkResult(awaitResult)
        return awaitResult
      }
 
      return Promise.race([createAssemblyAndUpload(), streamErrorPromise])
    })()
 
    // This allows the user to use or log the assemblyId even before it has been created for easier debugging
    return Object.assign(promise, { assemblyId: effectiveAssemblyId })
  }
 
  /**
   * Lint Assembly Instructions locally.
   *
   * If a templateId is provided, the template content is merged with the instructions,
   * just like the API. When a template sets `allow_steps_override=false`, providing
   * `steps` will throw a TEMPLATE_DENIES_STEPS_OVERRIDE error.
   *
   * The `assemblyInstructions` input may be a JSON string, a full instructions object,
   * or a steps-only object (missing the `steps` property).
   */
  async lintAssemblyInstructions(
    options: LintAssemblyInstructionsOptions,
  ): Promise<LintAssemblyInstructionsResult> {
    const { templateId, ...rest } = options
    if (!templateId) {
      return await lintAssemblyInstructionsInternal(rest)
    }
 
    const template = await this.getTemplate(templateId)
    return await lintAssemblyInstructionsInternal({
      ...rest,
      template: template.content,
    })
  }
 
  /**
   * Compile a natural-language prompt into validated Assembly Instructions.
   *
   * This creates a zero-upload /ai/chat Assembly, validates the structured response,
   * and lints the generated instructions locally before returning them.
   */
  async compileAssemblyInstructionsFromPrompt(
    options: CompileAssemblyInstructionsFromPromptOptions,
  ): Promise<CompileAssemblyInstructionsResult> {
    const timeout = options.timeout ?? 5 * 60 * 1000
 
    return await compileAssemblyInstructionsFromPrompt({
      ...options,
      mcpServerUrl: options.mcpServerUrl ?? `${this._endpoint}/mcp`,
      client: {
        runAssemblyInstructionsCompiler: async ({ aiStep }) => {
          const assembly = await this.createAssembly({
            params: {
              steps: {
                ai: aiStep,
              },
            },
            waitForCompletion: true,
            expectedUploads: 0,
            timeout,
          })
 
          const result = assembly.results?.ai?.[0]
          const resultUrl = result?.url
          if (!resultUrl) {
            throw new Error('No AI response in Assembly results.')
          }
 
          return {
            response: await fetchJson(resultUrl),
            assemblyUrl: assembly.assembly_ssl_url ?? assembly.assembly_url ?? undefined,
            billedChargeUsd: getResultBilledChargeUsd(result),
            usageBytes: assembly.bytes_usage ?? undefined,
          }
        },
        lintAssemblyInstructions: async (instructionsJson) => {
          const lintResult = await this.lintAssemblyInstructions({
            assemblyInstructions: instructionsJson,
          })
          return lintResult.issues
        },
      },
    })
  }
 
  /**
   * Mint a short-lived bearer token via POST /token.
   *
   * This uses HTTP Basic Auth (authKey + authSecret) and can optionally request a narrowed scope.
   * If `scope` is omitted, the token inherits the auth key's scope.
   */
  async mintBearerToken(
    options: Omit<MintBearerTokenOptions, 'endpoint'> & { endpoint?: string } = {},
  ): Promise<BearerTokenResponse> {
    Iif (this._authToken) {
      throw new Error(
        'Cannot mint bearer tokens when using authToken authentication. Provide authKey + authSecret instead.',
      )
    }
 
    const result = await mintBearerTokenWithCredentials(
      { authKey: this._authKey, authSecret: this._authSecret },
      {
        ...options,
        endpoint: options.endpoint ?? this._endpoint,
      },
    )
 
    Iif (!result.ok) {
      throw new Error(result.error)
    }
 
    return result.data
  }
 
  async resumeAssemblyUploads(
    opts: ResumeAssemblyUploadsOptions,
  ): Promise<AssemblyStatusWithUploadUrls> {
    const {
      assemblyUrl,
      files = {},
      uploads = {},
      chunkSize: requestedChunkSize = Number.POSITIVE_INFINITY,
      uploadConcurrency = 10,
      timeout = 24 * 60 * 60 * 1000, // 1 day
      waitForCompletion = false,
      onUploadProgress = () => {},
      onAssemblyProgress = () => {},
      signal,
      uploadBehavior = 'await',
    } = opts
 
    const startTimeMs = getHrTimeMs()
 
    getAssemblyIdFromUrl(assemblyUrl)
    const assembly: AssemblyStatusWithUploadUrls = await this._fetchAssemblyStatus({
      url: assemblyUrl,
      signal,
    })
    const statusUrl = assembly.assembly_ssl_url ?? assembly.assembly_url ?? assemblyUrl
 
    const finishedKeys = new Set<string>()
    for (const upload of assembly.uploads ?? []) {
      const key = getUploadKey(upload.field ?? null, upload.basename ?? null, upload.size)
      Eif (key) finishedKeys.add(key)
    }
    for (const upload of assembly.tus_uploads ?? []) {
      if (!upload.finished) continue
      const key = getUploadKey(upload.fieldname, upload.filename, upload.size)
      Eif (key) finishedKeys.add(key)
    }
 
    const resumeUrls = new Map<string, string>()
    for (const upload of assembly.tus_uploads ?? []) {
      if (upload.finished) continue
      if (!upload.upload_url) continue
      const key = getUploadKey(upload.fieldname, upload.filename, upload.size)
      Eif (key) resumeUrls.set(key, upload.upload_url)
    }
 
    const descriptors: UploadDescriptor[] = []
 
    await pMap(
      Object.entries(files),
      async ([label, path]) => {
        await access(path, constants.F_OK | constants.R_OK)
        const info = await stat(path)
        descriptors.push({
          label,
          path,
          filename: basename(path),
          size: info.size,
        })
      },
      { concurrency: 5 },
    )
 
    for (const [label, value] of Object.entries(uploads)) {
      descriptors.push({
        label,
        filename: label,
        size: isReadableStream(value) ? undefined : getSizeFromValue(value),
        value,
      })
    }
 
    const descriptorsToUpload = descriptors.filter((descriptor) => {
      const key = getUploadKey(descriptor.label, descriptor.filename, descriptor.size ?? null)
      return key ? !finishedKeys.has(key) : true
    })
 
    const uploadUrlsByLabel: Record<string, string> = {}
    for (const descriptor of descriptorsToUpload) {
      if (!descriptor.path) continue
      const key = getUploadKey(descriptor.label, descriptor.filename, descriptor.size ?? null)
      Iif (!key) continue
      const uploadUrl = resumeUrls.get(key)
      if (uploadUrl) uploadUrlsByLabel[descriptor.label] = uploadUrl
    }
 
    const streamsMap = buildStreamsMap(descriptorsToUpload)
    pauseStreams(streamsMap)
 
    if (Object.keys(streamsMap).length > 0) {
      const streamErrorPromise = createStreamErrorPromise(streamsMap)
 
      const uploadPromise = sendTusRequest({
        streamsMap,
        assembly,
        requestedChunkSize,
        uploadConcurrency,
        onProgress: onUploadProgress,
        signal,
        uploadUrls: uploadUrlsByLabel,
        uploadBehavior,
      })
 
      await Promise.race([uploadPromise, streamErrorPromise])
      const { uploadUrls } = await uploadPromise
      Iif (uploadBehavior !== 'await' && Object.keys(uploadUrls).length > 0) {
        assembly.upload_urls = uploadUrls
      }
    }
 
    const latestAssembly: AssemblyStatusWithUploadUrls = await this._fetchAssemblyStatus({
      url: statusUrl,
      signal,
    })
    Iif (uploadBehavior !== 'await' && assembly.upload_urls) {
      latestAssembly.upload_urls = assembly.upload_urls
    }
    const shouldWaitForCompletion = waitForCompletion && uploadBehavior === 'await'
    if (!shouldWaitForCompletion) return latestAssembly
 
    Iif (latestAssembly.assembly_id == null) {
      throw new InconsistentResponseError(
        'Server returned an assembly response without an assembly_id after resuming uploads',
      )
    }
 
    const awaitResult = await this.awaitAssemblyCompletion(latestAssembly.assembly_id, {
      timeout,
      onAssemblyProgress,
      startTimeMs,
      assemblyUrl: statusUrl,
      signal,
    })
    checkResult(awaitResult)
    return awaitResult
  }
 
  async awaitAssemblyCompletion(
    assemblyId: string,
    {
      onAssemblyProgress = () => {},
      timeout,
      startTimeMs = getHrTimeMs(),
      interval = 1000,
      assemblyUrl,
      signal,
      onPoll,
    }: AwaitAssemblyCompletionOptions = {},
  ): Promise<AssemblyStatus> {
    assert.ok(assemblyId)
 
    let lastResult: AssemblyStatus | undefined
 
    const fetchAssemblyStatus = (): Promise<AssemblyStatus> => {
      return assemblyUrl
        ? this._fetchAssemblyStatus({ url: assemblyUrl, signal })
        : this.getAssembly(assemblyId, { signal })
    }
 
    while (true) {
      // Check if caller wants to stop polling early
      if (onPoll?.() === false && lastResult) {
        return lastResult
      }
 
      // Check if aborted before making the request
      Iif (signal?.aborted) {
        throw signal.reason ?? new DOMException('Aborted', 'AbortError')
      }
 
      const result = await fetchAssemblyStatus()
      lastResult = result
 
      // If 'ok' is not in result, it implies a terminal state (e.g., error, completed, canceled).
      // If 'ok' is present, then we check if it's one of the non-terminal polling states.
      if (
        !('ok' in result) ||
        (result.ok !== 'ASSEMBLY_UPLOADING' &&
          result.ok !== 'ASSEMBLY_EXECUTING' &&
          // ASSEMBLY_REPLAYING is not a valid 'ok' status for polling, it means it's done replaying.
          // The API does not seem to have an ASSEMBLY_REPLAYING status in the typical polling loop.
          // It's usually a final status from the replay endpoint.
          // For polling, we only care about UPLOADING and EXECUTING.
          // If a replay operation puts it into a pollable state, that state would be EXECUTING.
          result.ok !== 'ASSEMBLY_REPLAYING') // This line might need review based on actual API behavior for replayed assembly polling
      ) {
        return result // Done!
      }
 
      try {
        onAssemblyProgress(result)
      } catch (err) {
        log('Caught onAssemblyProgress error', err)
      }
 
      const nowMs = getHrTimeMs()
      if (timeout != null && nowMs - startTimeMs >= timeout) {
        throw new PollingTimeoutError('Polling timed out')
      }
 
      // Make the sleep abortable, ensuring listener cleanup to prevent memory leaks
      await new Promise<void>((resolve, reject) => {
        const timeoutId = setTimeout(() => {
          signal?.removeEventListener('abort', onAbort)
          resolve()
        }, interval)
 
        function onAbort() {
          clearTimeout(timeoutId)
          reject(signal?.reason ?? new DOMException('Aborted', 'AbortError'))
        }
 
        signal?.addEventListener('abort', onAbort, { once: true })
      })
    }
  }
 
  maybeThrowInconsistentResponseError(message: string) {
    const err = new InconsistentResponseError(message)
 
    // @TODO, once our schemas have matured, we should remove the option and always throw the error here.
    // But as it stands, schemas are new, and we can't easily update all customer's node-sdks,
    // so there will be a long tail of throws if we enable this now.
    Eif (this._validateResponses) {
      throw err
    }
 
    console.error(
      `---\nPlease report this error to Transloadit (support@transloadit.com). We are working on better schemas for our API and this looks like something we do not cover yet: \n\n${err}\nThank you in advance!\n---\n`,
    )
  }
 
  /**
   * Cancel the assembly
   *
   * @param assemblyId assembly ID
   * @returns after the assembly is deleted
   */
  async cancelAssembly(assemblyId: string): Promise<AssemblyStatus> {
    const assembly = await this.getAssembly(assemblyId)
    checkAssemblyUrls(assembly)
    const rawResult = await this._remoteJson<Record<string, unknown>, OptionalAuthParams>({
      url: assembly.assembly_ssl_url,
      isTrustedUrl: true,
      method: 'delete',
    })
 
    const parsedResult = zodParseWithContext(assemblyStatusSchema, rawResult)
 
    Iif (!parsedResult.success) {
      this.maybeThrowInconsistentResponseError(
        `The API responded with data that does not match the expected schema while cancelling Assembly: ${assemblyId}.\n${parsedResult.humanReadable}`,
      )
    }
 
    checkAssemblyUrls(rawResult as AssemblyStatus)
    return rawResult as AssemblyStatus
  }
 
  /**
   * Replay an Assembly
   *
   * @param assemblyId of the assembly to replay
   * @param optional params
   * @returns after the replay is started
   */
  async replayAssembly(
    assemblyId: string,
    params: ReplayAssemblyParams = {},
  ): Promise<ReplayAssemblyResponse> {
    const result: ReplayAssemblyResponse = await this._remoteJson({
      urlSuffix: `/assemblies/${assemblyId}/replay`,
      method: 'post',
      ...(Object.keys(params).length > 0 && { params }),
    })
    checkResult(result)
    return result
  }
 
  /**
   * Replay an Assembly notification
   *
   * @param assemblyId of the assembly whose notification to replay
   * @param optional params
   * @returns after the replay is started
   */
  async replayAssemblyNotification(
    assemblyId: string,
    params: ReplayAssemblyNotificationParams = {},
  ): Promise<ReplayAssemblyNotificationResponse> {
    return await this._remoteJson({
      urlSuffix: `/assembly_notifications/${assemblyId}/replay`,
      method: 'post',
      ...(Object.keys(params).length > 0 && { params }),
    })
  }
 
  /**
   * List all assemblies
   *
   * @param params optional request options
   * @returns list of Assemblies
   */
  async listAssemblies(
    params?: ListAssembliesParams,
  ): Promise<PaginationListWithCount<AssemblyIndexItem>> {
    const rawResponse = await this._remoteJson<
      PaginationListWithCount<Record<string, unknown>>,
      ListAssembliesParams
    >({
      urlSuffix: '/assemblies',
      method: 'get',
      params: params || {},
    })
 
    Iif (
      rawResponse == null ||
      typeof rawResponse !== 'object' ||
      !Array.isArray(rawResponse.items)
    ) {
      throw new InconsistentResponseError(
        'API response for listAssemblies is malformed or missing items array',
      )
    }
 
    const parsedResult = zodParseWithContext(assemblyIndexSchema, rawResponse.items)
 
    Iif (!parsedResult.success) {
      this.maybeThrowInconsistentResponseError(
        `API response for listAssemblies contained items that do not match the expected schema.\n${parsedResult.humanReadable}`,
      )
    }
 
    return {
      items: rawResponse.items as AssemblyIndex,
      count: rawResponse.count,
    }
  }
 
  streamAssemblies(params: ListAssembliesParams): Readable {
    return new PaginationStream(async (page) => this.listAssemblies({ ...params, page }))
  }
 
  /**
   * Get an Assembly
   *
   * @param assemblyId the Assembly Id
   * @param options optional request options
   * @returns the retrieved Assembly
   */
  async getAssembly(
    assemblyId: string,
    options?: { signal?: AbortSignal },
  ): Promise<AssemblyStatus> {
    return await this._fetchAssemblyStatus({
      assemblyId,
      signal: options?.signal,
    })
  }
 
  private async _fetchAssemblyStatus({
    assemblyId,
    url,
    signal,
  }: {
    assemblyId?: string
    url?: string
    signal?: AbortSignal
  }): Promise<AssemblyStatus> {
    const rawResult = await this._remoteJson<Record<string, unknown>, OptionalAuthParams>({
      url,
      urlSuffix: url ? undefined : `/assemblies/${assemblyId}`,
      isTrustedUrl: Boolean(url),
      signal,
    })
 
    const parsedResult = zodParseWithContext(assemblyStatusSchema, rawResult)
 
    if (!parsedResult.success) {
      const label = assemblyId ?? url ?? 'unknown'
      this.maybeThrowInconsistentResponseError(
        `The API responded with data that does not match the expected schema while getting Assembly: ${label}.\n${parsedResult.humanReadable}`,
      )
    }
 
    checkAssemblyUrls(rawResult as AssemblyStatus)
    return rawResult as AssemblyStatus
  }
 
  /**
   * Create a Credential
   *
   * @param params optional request options
   * @returns when the Credential is created
   */
  async createTemplateCredential(
    params: CreateTemplateCredentialParams,
  ): Promise<TemplateCredentialResponse> {
    return await this._remoteJson({
      urlSuffix: '/template_credentials',
      method: 'post',
      params: params || {},
    })
  }
 
  /**
   * Edit a Credential
   *
   * @param credentialId the Credential ID
   * @param params optional request options
   * @returns when the Credential is edited
   */
  async editTemplateCredential(
    credentialId: string,
    params: CreateTemplateCredentialParams,
  ): Promise<TemplateCredentialResponse> {
    return await this._remoteJson({
      urlSuffix: `/template_credentials/${credentialId}`,
      method: 'put',
      params: params || {},
    })
  }
 
  /**
   * Delete a Credential
   *
   * @param credentialId the Credential ID
   * @returns when the Credential is deleted
   */
  async deleteTemplateCredential(credentialId: string): Promise<BaseResponse> {
    return await this._remoteJson({
      urlSuffix: `/template_credentials/${credentialId}`,
      method: 'delete',
    })
  }
 
  /**
   * Get a Credential
   *
   * @param credentialId the Credential ID
   * @returns when the Credential is retrieved
   */
  async getTemplateCredential(credentialId: string): Promise<TemplateCredentialResponse> {
    return await this._remoteJson({
      urlSuffix: `/template_credentials/${credentialId}`,
      method: 'get',
    })
  }
 
  /**
   * List all TemplateCredentials
   *
   * @param params optional request options
   * @returns the list of templates
   */
  async listTemplateCredentials(
    params?: ListTemplateCredentialsParams,
  ): Promise<TemplateCredentialsResponse> {
    return await this._remoteJson({
      urlSuffix: '/template_credentials',
      method: 'get',
      params: params || {},
    })
  }
 
  streamTemplateCredentials(params: ListTemplateCredentialsParams) {
    return new PaginationStream(async (page) => ({
      items: (await this.listTemplateCredentials({ ...params, page })).credentials,
    }))
  }
 
  /**
   * Create an Assembly Template
   *
   * @param params optional request options
   * @returns when the template is created
   */
  async createTemplate(params: CreateTemplateParams): Promise<TemplateResponse> {
    return await this._remoteJson({
      urlSuffix: '/templates',
      method: 'post',
      params: params || {},
    })
  }
 
  /**
   * Edit an Assembly Template
   *
   * @param templateId the template ID
   * @param params optional request options
   * @returns when the template is edited
   */
  async editTemplate(templateId: string, params: EditTemplateParams): Promise<TemplateResponse> {
    return await this._remoteJson({
      urlSuffix: `/templates/${templateId}`,
      method: 'put',
      params: params || {},
    })
  }
 
  /**
   * Delete an Assembly Template
   *
   * @param templateId the template ID
   * @returns when the template is deleted
   */
  async deleteTemplate(templateId: string): Promise<BaseResponse> {
    return await this._remoteJson({
      urlSuffix: `/templates/${templateId}`,
      method: 'delete',
    })
  }
 
  /** Revoke the signing Auth Key itself, without granting access to other workspace keys. */
  async revokeOwnAuthKey(): Promise<void> {
    const result = await this._remoteJson<
      unknown,
      OptionalAuthParams & { action: 'revoke_auth_key' }
    >({
      urlSuffix: '/auth_keys/self',
      method: 'delete',
      params: { action: 'revoke_auth_key' },
    })
    checkResult(result)
    z.object({ ok: z.literal('AUTH_KEY_DELETED') }).parse(result)
  }
 
  /**
   * Get an Assembly Template
   *
   * @param templateId the template ID
   * @returns when the template is retrieved
   */
  async getTemplate(templateId: string): Promise<TemplateResponse> {
    return await this._remoteJson({
      urlSuffix: `/templates/${templateId}`,
      method: 'get',
    })
  }
 
  /**
   * List all Assembly Templates
   *
   * @param params optional request options
   * @returns the list of templates
   */
  async listTemplates(
    params?: ListTemplatesParams,
  ): Promise<PaginationListWithCount<ListedTemplate>> {
    return await this._remoteJson({
      urlSuffix: '/templates',
      method: 'get',
      params: params || {},
    })
  }
 
  streamTemplates(params?: ListTemplatesParams): PaginationStream<ListedTemplate> {
    return new PaginationStream(async (page) => this.listTemplates({ ...params, page }))
  }
 
  /** Declare a directory public for unsigned Storage Built-ins. Requires dam:write scope. */
  async publishStoragePrefix(
    prefix: string,
    options?: { signal?: AbortSignal },
  ): Promise<StoragePublicPrefixDeclared> {
    const result = await this._remoteJson<unknown, OptionalAuthParams & { prefix: string }>({
      urlSuffix: '/storage/public_prefixes',
      method: 'post',
      params: { prefix: normalizeStoragePublicPrefix(prefix) },
      signal: options?.signal,
    })
    checkResult(result)
    return storagePublicPrefixDeclaredSchema.parse(result)
  }
 
  /** Revoke origin access to a public directory; cached or downloaded bytes cannot be recalled. */
  async unpublishStoragePrefix(
    prefix: string,
    options?: { signal?: AbortSignal },
  ): Promise<StoragePublicPrefixRevoked> {
    const result = await this._remoteJson<unknown, OptionalAuthParams & { prefix: string }>({
      urlSuffix: '/storage/public_prefixes',
      method: 'delete',
      params: { prefix: normalizeStoragePublicPrefix(prefix) },
      signal: options?.signal,
    })
    checkResult(result)
    return storagePublicPrefixRevokedSchema.parse(result)
  }
 
  /** List the workspace's explicitly public directories through the ordinary signed API. */
  async listPublicStoragePrefixes(options?: {
    signal?: AbortSignal
  }): Promise<StoragePublicPrefixes> {
    const result = await this._remoteJson({
      urlSuffix: '/storage/public_prefixes',
      method: 'get',
      signal: options?.signal,
    })
    checkResult(result)
    return storagePublicPrefixesSchema.parse(result)
  }
 
  /**
   * Get account Billing details for a specific month
   *
   * @param month the date for the required billing in the format yyyy-mm
   * @returns with billing data
   * @see https://transloadit.com/docs/api/bill-date-get/
   */
  async getBill(month: string): Promise<BillResponse> {
    assert.ok(month, 'month is required')
    return await this._remoteJson({
      urlSuffix: `/bill/${month}`,
      method: 'get',
    })
  }
 
  calcSignature(
    params: OptionalAuthParams,
    algorithm?: string,
  ): { signature: string; params: string } {
    Iif (!this._authKey || !this._authSecret) {
      throw new Error('Cannot sign params without authKey and authSecret.')
    }
    const jsonParams = this._prepareParams(params)
    const signature = this._calcSignature(jsonParams, algorithm)
 
    return { signature, params: jsonParams }
  }
 
  /**
   * Construct a signed Smart CDN URL. See https://transloadit.com/docs/topics/signature-authentication/#smart-cdn.
   */
  getSignedSmartCDNUrl(opts: SmartCDNUrlOptions): string {
    Iif (!this._authKey || !this._authSecret) {
      throw new Error('authKey and authSecret are required to sign Smart CDN URLs.')
    }
    return getSignedSmartCdnUrl({
      ...opts,
      authKey: this._authKey,
      authSecret: this._authSecret,
    })
  }
 
  private _calcSignature(toSign: string, algorithm: string = this.#signatureAlgorithm): string {
    Iif (!this._authSecret) {
      throw new Error('Cannot sign params without authSecret.')
    }
    return signParamsSync(toSign, this._authSecret, algorithm)
  }
 
  // Sets the multipart/form-data for POST, PUT and DELETE requests, including
  // the streams, the signed params, and any additional fields.
  private _appendForm(form: FormData, params: OptionalAuthParams, fields?: Fields): void {
    const shouldSign = Boolean(this._authKey && this._authSecret)
    let jsonParams = JSON.stringify(params ?? {})
    let signature: string | undefined
 
    if (shouldSign) {
      const sigData = this.calcSignature(params)
      jsonParams = sigData.params
      signature = sigData.signature
    }
 
    form.append('params', jsonParams)
 
    if (fields != null) {
      for (const [key, val] of Object.entries(fields)) {
        form.append(key, val)
      }
    }
 
    if (signature) {
      form.append('signature', signature)
    }
  }
 
  // Implements HTTP GET query params, handling the case where the url already
  // has params.
  private _appendParamsToUrl(url: string, params: OptionalAuthParams): string {
    const prefix = url.indexOf('?') === -1 ? '?' : '&'
 
    const shouldSign = Boolean(this._authKey && this._authSecret)
    if (!shouldSign) {
      const jsonParams = JSON.stringify(params ?? {})
      return `${url}${prefix}params=${encodeURIComponent(jsonParams)}`
    }
 
    const { signature, params: jsonParams } = this.calcSignature(params)
 
    return `${url}${prefix}signature=${signature}&params=${encodeURIComponent(jsonParams)}`
  }
 
  // Responsible for including auth parameters in all requests
  private _prepareParams(paramsIn?: OptionalAuthParams): string {
    let params = paramsIn
    if (params == null) {
      params = {}
    }
    if (params.auth == null) {
      params.auth = {}
    }
    if (params.auth.key == null) {
      params.auth.key = this._authKey
    }
    if (params.auth.expires == null) {
      params.auth.expires = this._getExpiresDate()
    }
 
    return JSON.stringify(params)
  }
 
  // We want to mock this method
  private _getExpiresDate(): string {
    const expiresDate = new Date()
    expiresDate.setDate(expiresDate.getDate() + 1)
    return expiresDate.toISOString()
  }
 
  // Responsible for making API calls. Automatically sends streams with any POST,
  // PUT or DELETE requests. Automatically adds signature parameters to all
  // requests. Also automatically parses the JSON response.
  private async _remoteJson<TRet, TParams extends OptionalAuthParams>(opts: {
    urlSuffix?: string
    url?: string
    isTrustedUrl?: boolean
    timeout?: Delays
    method?: 'delete' | 'get' | 'patch' | 'post' | 'put'
    params?: TParams
    fields?: Fields
    headers?: Headers
    signal?: AbortSignal
  }): Promise<TRet> {
    const {
      urlSuffix,
      url: urlInput,
      isTrustedUrl = false,
      timeout = { request: this._defaultTimeout },
      method = 'get',
      params = {},
      fields,
      headers,
      signal,
    } = opts
 
    // Allow providing either a `urlSuffix` or a full `url`
    Iif (!urlSuffix && !urlInput) throw new Error('No URL provided')
    let url = urlInput || `${this._endpoint}${urlSuffix}`
    Iif (urlInput && !isTrustedUrl) {
      const allowed = new URL(this._endpoint)
      const candidate = new URL(urlInput)
      if (allowed.origin !== candidate.origin) {
        throw new Error(`Untrusted URL: ${candidate.origin}`)
      }
    }
 
    if (method === 'get') {
      url = this._appendParamsToUrl(url, params)
    }
 
    log('Sending request', method, url)
 
    // todo use got.retry instead because we are no longer using FormData (which is a stream and can only be used once)
    // https://github.com/sindresorhus/got/issues/1282
    for (let retryCount = 0; ; retryCount++) {
      let form: FormData | undefined
 
      if (method === 'post' || method === 'patch' || method === 'put' || method === 'delete') {
        form = new FormData()
        this._appendForm(form, params, fields)
      }
 
      const requestOpts: OptionsOfJSONResponseBody = {
        followRedirect: this.#followRedirects,
        retry: this._gotRetry,
        body: form,
        timeout,
        headers: {
          'Transloadit-Client': this._clientName,
          'User-Agent': undefined, // Remove got's user-agent
          ...(this._authToken ? { Authorization: `Bearer ${this._authToken}` } : {}),
          ...this.#extraHeaders,
          ...headers,
        },
        hooks: { beforeRedirect: this.#dropExtraHeadersOffOrigin(url) },
        responseType: 'json',
        signal,
      }
 
      try {
        const request = got[method]<TRet>(url, requestOpts)
        const { body, statusCode } = await request
        // redirect_url responses can contain a valid Assembly, but an empty redirect cannot
        // fulfill an API request. Keep its Location unfollowed without reporting empty success.
        Iif (
          !this.#followRedirects &&
          statusCode >= 300 &&
          statusCode < 400 &&
          (body === null || typeof body !== 'object')
        ) {
          throw new InconsistentResponseError(
            'The API returned a redirect without a JSON object while redirects are disabled.',
          )
        }
        return body
      } catch (err) {
        Iif (!(err instanceof RequestError)) throw err
 
        if (err instanceof HTTPError) {
          const { statusCode, body } = err.response
          logWarn('HTTP error', statusCode, body)
 
          // check whether we should retry
          // https://transloadit.com/blog/2012/04/introducing-rate-limiting/
          const retryAfterHeader = err.response?.headers?.['retry-after']
          const retryAfterSeconds =
            typeof retryAfterHeader === 'string' ? Number(retryAfterHeader) : undefined
          const retryInFromInfo =
            typeof body === 'object' &&
            body != null &&
            'info' in body &&
            typeof body.info === 'object' &&
            body.info != null &&
            'retryIn' in body.info &&
            typeof body.info.retryIn === 'number' &&
            body.info.retryIn > 0
              ? body.info.retryIn
              : undefined
          const retryInSec =
            retryInFromInfo ??
            (typeof retryAfterSeconds === 'number' && retryAfterSeconds > 0
              ? retryAfterSeconds
              : undefined)
          const shouldRetry =
            retryCount < this._maxRetries && // 413 taken from https://transloadit.com/blog/2012/04/introducing-rate-limiting/
            // todo can 413 be removed?
            ((statusCode === 413 &&
              body &&
              typeof body === 'object' &&
              body.error === 'RATE_LIMIT_REACHED') ||
              statusCode === 429)
 
          if (shouldRetry) {
            const retryDelaySec = retryInSec ?? 1
            logWarn(
              `Rate limit reached, retrying request in approximately ${retryDelaySec} seconds.`,
            )
            const retryInMs = 1000 * (retryDelaySec * (1 + 0.1 * Math.random()))
            await delay(retryInMs)
            // Retry
          } else {
            throw new ApiError({
              cause: err,
              body: err.response?.body as TransloaditErrorResponseBody | undefined,
            }) // todo don't assert type
          }
        } else {
          throw err
        }
      }
    }
  }
}