@0dotxyz/p0-ts-sdk 2.2.0-alpha.2 → 2.2.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vendor.js CHANGED
@@ -1,4 +1,4 @@
1
- import { PublicKey, TransactionInstruction, SYSVAR_RENT_PUBKEY, SystemProgram, STAKE_CONFIG_ID, Transaction, LAMPORTS_PER_SOL, StakeProgram, SYSVAR_CLOCK_PUBKEY } from '@solana/web3.js';
1
+ import { PublicKey, TransactionInstruction, SYSVAR_RENT_PUBKEY, SystemProgram, STAKE_CONFIG_ID, Transaction, LAMPORTS_PER_SOL, StakeProgram, SYSVAR_CLOCK_PUBKEY, AddressLookupTableAccount } from '@solana/web3.js';
2
2
  import 'bignumber.js';
3
3
  import { deserialize } from 'borsh';
4
4
  import BN2, { BN } from 'bn.js';
@@ -9,6 +9,7 @@ import { BorshCoder, BorshAccountsCoder, Program } from '@coral-xyz/anchor';
9
9
  import * as borsh from '@coral-xyz/borsh';
10
10
  import { struct as struct$1, bool as bool$1, publicKey as publicKey$1, array, u64 as u64$1, u8 as u8$1, u32 as u32$1, u128 } from '@coral-xyz/borsh';
11
11
  import Decimal3 from 'decimal.js';
12
+ import WebSocket from 'ws';
12
13
 
13
14
  // src/vendor/pyth_legacy/readBig.ts
14
15
  var ERR_BUFFER_OUT_OF_BOUNDS = () => new Error("Attempt to access memory outside buffer bounds");
@@ -485,36 +486,12 @@ function createMemoInstruction(memo, signerPubkeys) {
485
486
  });
486
487
  }
487
488
  var TokenInstruction = /* @__PURE__ */ ((TokenInstruction2) => {
488
- TokenInstruction2[TokenInstruction2["Approve"] = 4] = "Approve";
489
489
  TokenInstruction2[TokenInstruction2["InitializeAccount"] = 1] = "InitializeAccount";
490
490
  TokenInstruction2[TokenInstruction2["TransferChecked"] = 12] = "TransferChecked";
491
491
  TokenInstruction2[TokenInstruction2["CloseAccount"] = 9] = "CloseAccount";
492
492
  TokenInstruction2[TokenInstruction2["SyncNative"] = 17] = "SyncNative";
493
493
  return TokenInstruction2;
494
494
  })(TokenInstruction || {});
495
- var approveInstructionData = struct([
496
- u8("instruction"),
497
- u64("amount")
498
- ]);
499
- function createApproveInstruction(account, delegate, owner, amount, multiSigners = [], programId = TOKEN_PROGRAM_ID) {
500
- const keys = addSigners(
501
- [
502
- { pubkey: account, isSigner: false, isWritable: true },
503
- { pubkey: delegate, isSigner: false, isWritable: false }
504
- ],
505
- owner,
506
- multiSigners
507
- );
508
- const data = Buffer$1.alloc(approveInstructionData.span);
509
- approveInstructionData.encode(
510
- {
511
- instruction: 4 /* Approve */,
512
- amount: BigInt(amount)
513
- },
514
- data
515
- );
516
- return new TransactionInstruction({ keys, programId, data });
517
- }
518
495
  var initializeAccountInstructionData = struct([
519
496
  u8("instruction")
520
497
  ]);
@@ -29162,6 +29139,1774 @@ function makeUpdateJupLendRate({ lendingState }) {
29162
29139
  );
29163
29140
  }
29164
29141
 
29165
- export { ACCOUNT_SIZE, ACCOUNT_TYPE_SIZE, ASSOCIATED_TOKEN_PROGRAM_ID, AccountLayout, AccountState, AccountType, CorpAction, DEFAULT_RECENT_SLOT_DURATION_MS, DRIFT_IDL, DRIFT_PROGRAM_ID, DriftSpotBalanceType, ExtensionType, FARMS_PROGRAM_ID, JUP_EXCHANGE_PRICES_PRECISION, JUP_LEND_IDL, JUP_LEND_PROGRAM_ID, JUP_LIQUIDITY_PROGRAM_ID, JUP_MAX_REWARDS_RATE, JUP_REWARDS_PROGRAM_ID, JUP_SECONDS_PER_YEAR, KFARMS_IDL, KLEND_ACCOUNT_CODER, KLEND_IDL, KLEND_PROGRAM_ID, LENGTH_SIZE, MAX_SLOT_DIFFERENCE, MEMO_PROGRAM_ID, MINT_SIZE, MULTISIG_SIZE, MintLayout, MultisigLayout, NATIVE_MINT, ONE, ONE_HUNDRED_PCT_IN_BPS, ONE_YEAR, PERCENTAGE_PRECISION, PERCENTAGE_PRECISION_EXP, PriceStatus, PriceType, REFRESH_OBLIGATION_DISCRIMINATOR, SEED_BASE_REFERRER_STATE, SEED_BASE_REFERRER_TOKEN_STATE, SEED_BASE_SHORT_URL, SEED_BASE_USER_METADATA, SEED_DRIFT_SIGNER, SEED_DRIFT_STATE, SEED_FEE_RECEIVER, SEED_F_TOKEN_MINT, SEED_LENDING, SEED_LENDING_ADMIN, SEED_LENDING_MARKET_AUTH, SEED_LENDING_REWARDS_RATE_MODEL, SEED_LIQUIDITY, SEED_RATE_MODEL, SEED_RESERVE, SEED_RESERVE_COLL_MINT, SEED_RESERVE_COLL_SUPPLY, SEED_RESERVE_LIQ_SUPPLY, SEED_SPOT_MARKET, SEED_SPOT_MARKET_VAULT, SEED_USER, SEED_USER_CLAIM, SEED_USER_STATE, SEED_USER_STATS, SEED_USER_SUPPLY_POSITION, SLOTS_PER_DAY, SLOTS_PER_HOUR, SLOTS_PER_MINUTE, SLOTS_PER_SECOND, SLOTS_PER_YEAR, SPOT_MARKET_RATE_PRECISION, SPOT_MARKET_RATE_PRECISION_EXP, SPOT_MARKET_UTILIZATION_PRECISION, SPOT_MARKET_UTILIZATION_PRECISION_EXP, SWITCHBOARD_ONDEMANDE_PRICE_PRECISION, SinglePoolInstruction, SplAccountType, SpotBalanceType, TEN, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID, TYPE_SIZE, TokenAccountNotFoundError, TokenError, TokenInstruction, TokenInvalidAccountError, TokenInvalidAccountOwnerError, TokenInvalidAccountSizeError, TokenInvalidInstructionDataError, TokenInvalidInstructionKeysError, TokenInvalidInstructionProgramError, TokenInvalidInstructionTypeError, TokenInvalidMintError, TokenInvalidOwnerError, TokenOwnerOffCurveError, TokenUnsupportedInstructionError, ZERO, addSigners, approveInstructionData, calculateAPYFromAPR, calculateDriftBorrowAPR, calculateDriftBorrowAPY, calculateDriftBorrowRate, calculateDriftDepositRate, calculateDriftInterestRate, calculateDriftLendingAPR, calculateDriftLendingAPY, calculateDriftUtilization, calculateJupLendBorrowRate, calculateJupLendLiquiditySupplyRate, calculateJupLendNewExchangePrice, calculateJupLendRewardsRate, calculateJupLendRewardsRateForExchangePrice, calculateJupLendSupplyAPY, calculateJupLendSupplyRate, calculateJupLendTotalAssets, calculateKaminoEstimatedBorrowRate, calculateKaminoEstimatedSupplyRate, calculateKaminoSupplyAPY, calculateRewardApy, calculateSlotAdjustmentFactor, calculateUtilizationRatio, closeAccountInstructionData, createAccountIx, createApproveInstruction, createAssociatedTokenAccountIdempotentInstruction, createAssociatedTokenAccountInstruction, createCloseAccountInstruction, createInitializeAccountInstruction, createMemoInstruction, createPoolOnrampIx, createSyncNativeInstruction, createTransferCheckedInstruction, decodeDriftSpotMarketData, decodeDriftStateData, decodeDriftUserData, decodeDriftUserStatsData, decodeFarmDataRaw, decodeJupLendingRewardsRateModelData, decodeJupLendingStateData, decodeJupRateModelData, decodeJupTokenReserveData, decodeKlendObligationData, decodeKlendReserveData, decodeSwitchboardPullFeedData, deriveBaseObligation, deriveDriftSigner, deriveDriftSpotMarket, deriveDriftSpotMarketVault, deriveDriftState, deriveDriftUser, deriveDriftUserStats, deriveFeeReceiver, deriveJupLendClaimAccount, deriveJupLendFTokenMint, deriveJupLendLending, deriveJupLendLendingAdmin, deriveJupLendLendingPdas, deriveJupLendLendingRewardsRateModel, deriveJupLendLiquidity, deriveJupLendLiquiditySupplyPositionPda, deriveJupLendLiquidityVaultAta, deriveJupLendRateModel, deriveJupLendTokenReserve, deriveLendingMarketAuthority, deriveObligation, deriveReferrerState, deriveReferrerTokenState, deriveReserveCollateralMint, deriveReserveCollateralSupply, deriveReserveLiquiditySupply, deriveShortUrl, deriveUserMetadata, deriveUserState, driftRewardsRawToDto, driftSpotMarketRawToDto, driftStateRawToDto, driftUserRawToDto, driftUserStatsRawToDto, dtoToDriftRewardsRaw, dtoToDriftSpotMarketRaw, dtoToDriftStateRaw, dtoToDriftUserRaw, dtoToDriftUserStatsRaw, dtoToFarmRaw, dtoToJupLendingRewardsRateModelRaw, dtoToJupLendingStateRaw, dtoToJupRateModelRaw, dtoToJupTokenReserveRaw, dtoToObligationRaw, dtoToReserveRaw, farmRawToDto, findMplMetadataAddress, findPoolAddress, findPoolMintAddress, findPoolMintAddressByVoteAccount, findPoolMintAuthorityAddress, findPoolMplAuthorityAddress, findPoolOnRampAddress, findPoolStakeAddress, findPoolStakeAuthorityAddress, generateDriftReserveCurve, generateJupLendSupplyCurve, generateKaminoReserveCurve, getAccount, getAccountLen, getAllDerivedDriftAccounts, getAllDerivedJupLendAccounts, getAllDerivedKaminoAccounts, getAllRequiredMarkets, getAssociatedTokenAddressSync, getDriftRewards, getDriftTokenAmount, getFixedHostInterestRate, getJupLendRewards, getKaminoBorrowRate, getKaminoTotalSupply, getMinimumBalanceForRentExemptAccount, getMinimumBalanceForRentExemptAccountWithExtensions, getMint, getMultipleAccounts, getProtocolTakeRatePct, getReserveRewardsApy, getRewardPerTimeUnitSecond, getStakeAccount, getSwitchboardProgram, initializeAccountInstructionData, initializeStakedPoolIxs, initializeStakedPoolTx, interpolateLinear, isSpotBalanceTypeVariant, jupLendingRewardsRateModelRawToDto, jupLendingStateRawToDto, jupRateModelRawToDto, jupTokenReserveRawToDto, layout, makeRefreshObligationIx, makeRefreshReservesBatchIx, makeRefreshingIxs, makeUpdateJupLendRate, makeUpdateJupLendRateIx, makeUpdateSpotMarketCumulativeInterestIx, makeUpdateSpotMarketIx, obligationRawToDto, parsePriceData, parsePriceInfo2 as parsePriceInfo, replenishPoolIx, reserveRawToDto, scaledSupplies, slotAdjustmentFactor, switchboardAccountCoder, syncNativeInstructionData, transferCheckedInstructionData, truncateBorrowCurve, unpackAccount };
29142
+ // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/utils/utf8.mjs
29143
+ function utf8Count(str) {
29144
+ const strLength = str.length;
29145
+ let byteLength = 0;
29146
+ let pos = 0;
29147
+ while (pos < strLength) {
29148
+ let value = str.charCodeAt(pos++);
29149
+ if ((value & 4294967168) === 0) {
29150
+ byteLength++;
29151
+ continue;
29152
+ } else if ((value & 4294965248) === 0) {
29153
+ byteLength += 2;
29154
+ } else {
29155
+ if (value >= 55296 && value <= 56319) {
29156
+ if (pos < strLength) {
29157
+ const extra = str.charCodeAt(pos);
29158
+ if ((extra & 64512) === 56320) {
29159
+ ++pos;
29160
+ value = ((value & 1023) << 10) + (extra & 1023) + 65536;
29161
+ }
29162
+ }
29163
+ }
29164
+ if ((value & 4294901760) === 0) {
29165
+ byteLength += 3;
29166
+ } else {
29167
+ byteLength += 4;
29168
+ }
29169
+ }
29170
+ }
29171
+ return byteLength;
29172
+ }
29173
+ function utf8EncodeJs(str, output, outputOffset) {
29174
+ const strLength = str.length;
29175
+ let offset = outputOffset;
29176
+ let pos = 0;
29177
+ while (pos < strLength) {
29178
+ let value = str.charCodeAt(pos++);
29179
+ if ((value & 4294967168) === 0) {
29180
+ output[offset++] = value;
29181
+ continue;
29182
+ } else if ((value & 4294965248) === 0) {
29183
+ output[offset++] = value >> 6 & 31 | 192;
29184
+ } else {
29185
+ if (value >= 55296 && value <= 56319) {
29186
+ if (pos < strLength) {
29187
+ const extra = str.charCodeAt(pos);
29188
+ if ((extra & 64512) === 56320) {
29189
+ ++pos;
29190
+ value = ((value & 1023) << 10) + (extra & 1023) + 65536;
29191
+ }
29192
+ }
29193
+ }
29194
+ if ((value & 4294901760) === 0) {
29195
+ output[offset++] = value >> 12 & 15 | 224;
29196
+ output[offset++] = value >> 6 & 63 | 128;
29197
+ } else {
29198
+ output[offset++] = value >> 18 & 7 | 240;
29199
+ output[offset++] = value >> 12 & 63 | 128;
29200
+ output[offset++] = value >> 6 & 63 | 128;
29201
+ }
29202
+ }
29203
+ output[offset++] = value & 63 | 128;
29204
+ }
29205
+ }
29206
+ var sharedTextEncoder = new TextEncoder();
29207
+ var TEXT_ENCODER_THRESHOLD = 50;
29208
+ function utf8EncodeTE(str, output, outputOffset) {
29209
+ sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));
29210
+ }
29211
+ function utf8Encode(str, output, outputOffset) {
29212
+ if (str.length > TEXT_ENCODER_THRESHOLD) {
29213
+ utf8EncodeTE(str, output, outputOffset);
29214
+ } else {
29215
+ utf8EncodeJs(str, output, outputOffset);
29216
+ }
29217
+ }
29218
+ var CHUNK_SIZE = 4096;
29219
+ function utf8DecodeJs(bytes, inputOffset, byteLength) {
29220
+ let offset = inputOffset;
29221
+ const end = offset + byteLength;
29222
+ const units = [];
29223
+ let result = "";
29224
+ while (offset < end) {
29225
+ const byte1 = bytes[offset++];
29226
+ if ((byte1 & 128) === 0) {
29227
+ units.push(byte1);
29228
+ } else if ((byte1 & 224) === 192) {
29229
+ const byte2 = bytes[offset++] & 63;
29230
+ units.push((byte1 & 31) << 6 | byte2);
29231
+ } else if ((byte1 & 240) === 224) {
29232
+ const byte2 = bytes[offset++] & 63;
29233
+ const byte3 = bytes[offset++] & 63;
29234
+ units.push((byte1 & 31) << 12 | byte2 << 6 | byte3);
29235
+ } else if ((byte1 & 248) === 240) {
29236
+ const byte2 = bytes[offset++] & 63;
29237
+ const byte3 = bytes[offset++] & 63;
29238
+ const byte4 = bytes[offset++] & 63;
29239
+ let unit = (byte1 & 7) << 18 | byte2 << 12 | byte3 << 6 | byte4;
29240
+ if (unit > 65535) {
29241
+ unit -= 65536;
29242
+ units.push(unit >>> 10 & 1023 | 55296);
29243
+ unit = 56320 | unit & 1023;
29244
+ }
29245
+ units.push(unit);
29246
+ } else {
29247
+ units.push(byte1);
29248
+ }
29249
+ if (units.length >= CHUNK_SIZE) {
29250
+ result += String.fromCharCode(...units);
29251
+ units.length = 0;
29252
+ }
29253
+ }
29254
+ if (units.length > 0) {
29255
+ result += String.fromCharCode(...units);
29256
+ }
29257
+ return result;
29258
+ }
29259
+ var sharedTextDecoder = new TextDecoder();
29260
+ var TEXT_DECODER_THRESHOLD = 200;
29261
+ function utf8DecodeTD(bytes, inputOffset, byteLength) {
29262
+ const stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);
29263
+ return sharedTextDecoder.decode(stringBytes);
29264
+ }
29265
+ function utf8Decode(bytes, inputOffset, byteLength) {
29266
+ if (byteLength > TEXT_DECODER_THRESHOLD) {
29267
+ return utf8DecodeTD(bytes, inputOffset, byteLength);
29268
+ } else {
29269
+ return utf8DecodeJs(bytes, inputOffset, byteLength);
29270
+ }
29271
+ }
29272
+
29273
+ // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/ExtData.mjs
29274
+ var ExtData = class {
29275
+ type;
29276
+ data;
29277
+ constructor(type, data) {
29278
+ this.type = type;
29279
+ this.data = data;
29280
+ }
29281
+ };
29282
+
29283
+ // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/DecodeError.mjs
29284
+ var DecodeError = class _DecodeError extends Error {
29285
+ constructor(message) {
29286
+ super(message);
29287
+ const proto = Object.create(_DecodeError.prototype);
29288
+ Object.setPrototypeOf(this, proto);
29289
+ Object.defineProperty(this, "name", {
29290
+ configurable: true,
29291
+ enumerable: false,
29292
+ value: _DecodeError.name
29293
+ });
29294
+ }
29295
+ };
29296
+
29297
+ // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/utils/int.mjs
29298
+ var UINT32_MAX = 4294967295;
29299
+ function setUint64(view, offset, value) {
29300
+ const high = value / 4294967296;
29301
+ const low = value;
29302
+ view.setUint32(offset, high);
29303
+ view.setUint32(offset + 4, low);
29304
+ }
29305
+ function setInt64(view, offset, value) {
29306
+ const high = Math.floor(value / 4294967296);
29307
+ const low = value;
29308
+ view.setUint32(offset, high);
29309
+ view.setUint32(offset + 4, low);
29310
+ }
29311
+ function getInt64(view, offset) {
29312
+ const high = view.getInt32(offset);
29313
+ const low = view.getUint32(offset + 4);
29314
+ return high * 4294967296 + low;
29315
+ }
29316
+ function getUint64(view, offset) {
29317
+ const high = view.getUint32(offset);
29318
+ const low = view.getUint32(offset + 4);
29319
+ return high * 4294967296 + low;
29320
+ }
29321
+
29322
+ // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/timestamp.mjs
29323
+ var EXT_TIMESTAMP = -1;
29324
+ var TIMESTAMP32_MAX_SEC = 4294967296 - 1;
29325
+ var TIMESTAMP64_MAX_SEC = 17179869184 - 1;
29326
+ function encodeTimeSpecToTimestamp({ sec, nsec }) {
29327
+ if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {
29328
+ if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {
29329
+ const rv = new Uint8Array(4);
29330
+ const view = new DataView(rv.buffer);
29331
+ view.setUint32(0, sec);
29332
+ return rv;
29333
+ } else {
29334
+ const secHigh = sec / 4294967296;
29335
+ const secLow = sec & 4294967295;
29336
+ const rv = new Uint8Array(8);
29337
+ const view = new DataView(rv.buffer);
29338
+ view.setUint32(0, nsec << 2 | secHigh & 3);
29339
+ view.setUint32(4, secLow);
29340
+ return rv;
29341
+ }
29342
+ } else {
29343
+ const rv = new Uint8Array(12);
29344
+ const view = new DataView(rv.buffer);
29345
+ view.setUint32(0, nsec);
29346
+ setInt64(view, 4, sec);
29347
+ return rv;
29348
+ }
29349
+ }
29350
+ function encodeDateToTimeSpec(date) {
29351
+ const msec = date.getTime();
29352
+ const sec = Math.floor(msec / 1e3);
29353
+ const nsec = (msec - sec * 1e3) * 1e6;
29354
+ const nsecInSec = Math.floor(nsec / 1e9);
29355
+ return {
29356
+ sec: sec + nsecInSec,
29357
+ nsec: nsec - nsecInSec * 1e9
29358
+ };
29359
+ }
29360
+ function encodeTimestampExtension(object) {
29361
+ if (object instanceof Date) {
29362
+ const timeSpec = encodeDateToTimeSpec(object);
29363
+ return encodeTimeSpecToTimestamp(timeSpec);
29364
+ } else {
29365
+ return null;
29366
+ }
29367
+ }
29368
+ function decodeTimestampToTimeSpec(data) {
29369
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
29370
+ switch (data.byteLength) {
29371
+ case 4: {
29372
+ const sec = view.getUint32(0);
29373
+ const nsec = 0;
29374
+ return { sec, nsec };
29375
+ }
29376
+ case 8: {
29377
+ const nsec30AndSecHigh2 = view.getUint32(0);
29378
+ const secLow32 = view.getUint32(4);
29379
+ const sec = (nsec30AndSecHigh2 & 3) * 4294967296 + secLow32;
29380
+ const nsec = nsec30AndSecHigh2 >>> 2;
29381
+ return { sec, nsec };
29382
+ }
29383
+ case 12: {
29384
+ const sec = getInt64(view, 4);
29385
+ const nsec = view.getUint32(0);
29386
+ return { sec, nsec };
29387
+ }
29388
+ default:
29389
+ throw new DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${data.length}`);
29390
+ }
29391
+ }
29392
+ function decodeTimestampExtension(data) {
29393
+ const timeSpec = decodeTimestampToTimeSpec(data);
29394
+ return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);
29395
+ }
29396
+ var timestampExtension = {
29397
+ type: EXT_TIMESTAMP,
29398
+ encode: encodeTimestampExtension,
29399
+ decode: decodeTimestampExtension
29400
+ };
29401
+
29402
+ // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/ExtensionCodec.mjs
29403
+ var ExtensionCodec = class _ExtensionCodec {
29404
+ static defaultCodec = new _ExtensionCodec();
29405
+ // ensures ExtensionCodecType<X> matches ExtensionCodec<X>
29406
+ // this will make type errors a lot more clear
29407
+ // eslint-disable-next-line @typescript-eslint/naming-convention
29408
+ __brand;
29409
+ // built-in extensions
29410
+ builtInEncoders = [];
29411
+ builtInDecoders = [];
29412
+ // custom extensions
29413
+ encoders = [];
29414
+ decoders = [];
29415
+ constructor() {
29416
+ this.register(timestampExtension);
29417
+ }
29418
+ register({ type, encode, decode }) {
29419
+ if (type >= 0) {
29420
+ this.encoders[type] = encode;
29421
+ this.decoders[type] = decode;
29422
+ } else {
29423
+ const index = -1 - type;
29424
+ this.builtInEncoders[index] = encode;
29425
+ this.builtInDecoders[index] = decode;
29426
+ }
29427
+ }
29428
+ tryToEncode(object, context) {
29429
+ for (let i = 0; i < this.builtInEncoders.length; i++) {
29430
+ const encodeExt = this.builtInEncoders[i];
29431
+ if (encodeExt != null) {
29432
+ const data = encodeExt(object, context);
29433
+ if (data != null) {
29434
+ const type = -1 - i;
29435
+ return new ExtData(type, data);
29436
+ }
29437
+ }
29438
+ }
29439
+ for (let i = 0; i < this.encoders.length; i++) {
29440
+ const encodeExt = this.encoders[i];
29441
+ if (encodeExt != null) {
29442
+ const data = encodeExt(object, context);
29443
+ if (data != null) {
29444
+ const type = i;
29445
+ return new ExtData(type, data);
29446
+ }
29447
+ }
29448
+ }
29449
+ if (object instanceof ExtData) {
29450
+ return object;
29451
+ }
29452
+ return null;
29453
+ }
29454
+ decode(data, type, context) {
29455
+ const decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];
29456
+ if (decodeExt) {
29457
+ return decodeExt(data, type, context);
29458
+ } else {
29459
+ return new ExtData(type, data);
29460
+ }
29461
+ }
29462
+ };
29463
+
29464
+ // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/utils/typedArrays.mjs
29465
+ function isArrayBufferLike(buffer) {
29466
+ return buffer instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && buffer instanceof SharedArrayBuffer;
29467
+ }
29468
+ function ensureUint8Array(buffer) {
29469
+ if (buffer instanceof Uint8Array) {
29470
+ return buffer;
29471
+ } else if (ArrayBuffer.isView(buffer)) {
29472
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
29473
+ } else if (isArrayBufferLike(buffer)) {
29474
+ return new Uint8Array(buffer);
29475
+ } else {
29476
+ return Uint8Array.from(buffer);
29477
+ }
29478
+ }
29479
+
29480
+ // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/Encoder.mjs
29481
+ var DEFAULT_MAX_DEPTH = 100;
29482
+ var DEFAULT_INITIAL_BUFFER_SIZE = 2048;
29483
+ var Encoder = class _Encoder {
29484
+ extensionCodec;
29485
+ context;
29486
+ useBigInt64;
29487
+ maxDepth;
29488
+ initialBufferSize;
29489
+ sortKeys;
29490
+ forceFloat32;
29491
+ ignoreUndefined;
29492
+ forceIntegerToFloat;
29493
+ pos;
29494
+ view;
29495
+ bytes;
29496
+ entered = false;
29497
+ constructor(options) {
29498
+ this.extensionCodec = options?.extensionCodec ?? ExtensionCodec.defaultCodec;
29499
+ this.context = options?.context;
29500
+ this.useBigInt64 = options?.useBigInt64 ?? false;
29501
+ this.maxDepth = options?.maxDepth ?? DEFAULT_MAX_DEPTH;
29502
+ this.initialBufferSize = options?.initialBufferSize ?? DEFAULT_INITIAL_BUFFER_SIZE;
29503
+ this.sortKeys = options?.sortKeys ?? false;
29504
+ this.forceFloat32 = options?.forceFloat32 ?? false;
29505
+ this.ignoreUndefined = options?.ignoreUndefined ?? false;
29506
+ this.forceIntegerToFloat = options?.forceIntegerToFloat ?? false;
29507
+ this.pos = 0;
29508
+ this.view = new DataView(new ArrayBuffer(this.initialBufferSize));
29509
+ this.bytes = new Uint8Array(this.view.buffer);
29510
+ }
29511
+ clone() {
29512
+ return new _Encoder({
29513
+ extensionCodec: this.extensionCodec,
29514
+ context: this.context,
29515
+ useBigInt64: this.useBigInt64,
29516
+ maxDepth: this.maxDepth,
29517
+ initialBufferSize: this.initialBufferSize,
29518
+ sortKeys: this.sortKeys,
29519
+ forceFloat32: this.forceFloat32,
29520
+ ignoreUndefined: this.ignoreUndefined,
29521
+ forceIntegerToFloat: this.forceIntegerToFloat
29522
+ });
29523
+ }
29524
+ reinitializeState() {
29525
+ this.pos = 0;
29526
+ }
29527
+ /**
29528
+ * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.
29529
+ *
29530
+ * @returns Encodes the object and returns a shared reference the encoder's internal buffer.
29531
+ */
29532
+ encodeSharedRef(object) {
29533
+ if (this.entered) {
29534
+ const instance = this.clone();
29535
+ return instance.encodeSharedRef(object);
29536
+ }
29537
+ try {
29538
+ this.entered = true;
29539
+ this.reinitializeState();
29540
+ this.doEncode(object, 1);
29541
+ return this.bytes.subarray(0, this.pos);
29542
+ } finally {
29543
+ this.entered = false;
29544
+ }
29545
+ }
29546
+ /**
29547
+ * @returns Encodes the object and returns a copy of the encoder's internal buffer.
29548
+ */
29549
+ encode(object) {
29550
+ if (this.entered) {
29551
+ const instance = this.clone();
29552
+ return instance.encode(object);
29553
+ }
29554
+ try {
29555
+ this.entered = true;
29556
+ this.reinitializeState();
29557
+ this.doEncode(object, 1);
29558
+ return this.bytes.slice(0, this.pos);
29559
+ } finally {
29560
+ this.entered = false;
29561
+ }
29562
+ }
29563
+ doEncode(object, depth) {
29564
+ if (depth > this.maxDepth) {
29565
+ throw new Error(`Too deep objects in depth ${depth}`);
29566
+ }
29567
+ if (object == null) {
29568
+ this.encodeNil();
29569
+ } else if (typeof object === "boolean") {
29570
+ this.encodeBoolean(object);
29571
+ } else if (typeof object === "number") {
29572
+ if (!this.forceIntegerToFloat) {
29573
+ this.encodeNumber(object);
29574
+ } else {
29575
+ this.encodeNumberAsFloat(object);
29576
+ }
29577
+ } else if (typeof object === "string") {
29578
+ this.encodeString(object);
29579
+ } else if (this.useBigInt64 && typeof object === "bigint") {
29580
+ this.encodeBigInt64(object);
29581
+ } else {
29582
+ this.encodeObject(object, depth);
29583
+ }
29584
+ }
29585
+ ensureBufferSizeToWrite(sizeToWrite) {
29586
+ const requiredSize = this.pos + sizeToWrite;
29587
+ if (this.view.byteLength < requiredSize) {
29588
+ this.resizeBuffer(requiredSize * 2);
29589
+ }
29590
+ }
29591
+ resizeBuffer(newSize) {
29592
+ const newBuffer = new ArrayBuffer(newSize);
29593
+ const newBytes = new Uint8Array(newBuffer);
29594
+ const newView = new DataView(newBuffer);
29595
+ newBytes.set(this.bytes);
29596
+ this.view = newView;
29597
+ this.bytes = newBytes;
29598
+ }
29599
+ encodeNil() {
29600
+ this.writeU8(192);
29601
+ }
29602
+ encodeBoolean(object) {
29603
+ if (object === false) {
29604
+ this.writeU8(194);
29605
+ } else {
29606
+ this.writeU8(195);
29607
+ }
29608
+ }
29609
+ encodeNumber(object) {
29610
+ if (!this.forceIntegerToFloat && Number.isSafeInteger(object)) {
29611
+ if (object >= 0) {
29612
+ if (object < 128) {
29613
+ this.writeU8(object);
29614
+ } else if (object < 256) {
29615
+ this.writeU8(204);
29616
+ this.writeU8(object);
29617
+ } else if (object < 65536) {
29618
+ this.writeU8(205);
29619
+ this.writeU16(object);
29620
+ } else if (object < 4294967296) {
29621
+ this.writeU8(206);
29622
+ this.writeU32(object);
29623
+ } else if (!this.useBigInt64) {
29624
+ this.writeU8(207);
29625
+ this.writeU64(object);
29626
+ } else {
29627
+ this.encodeNumberAsFloat(object);
29628
+ }
29629
+ } else {
29630
+ if (object >= -32) {
29631
+ this.writeU8(224 | object + 32);
29632
+ } else if (object >= -128) {
29633
+ this.writeU8(208);
29634
+ this.writeI8(object);
29635
+ } else if (object >= -32768) {
29636
+ this.writeU8(209);
29637
+ this.writeI16(object);
29638
+ } else if (object >= -2147483648) {
29639
+ this.writeU8(210);
29640
+ this.writeI32(object);
29641
+ } else if (!this.useBigInt64) {
29642
+ this.writeU8(211);
29643
+ this.writeI64(object);
29644
+ } else {
29645
+ this.encodeNumberAsFloat(object);
29646
+ }
29647
+ }
29648
+ } else {
29649
+ this.encodeNumberAsFloat(object);
29650
+ }
29651
+ }
29652
+ encodeNumberAsFloat(object) {
29653
+ if (this.forceFloat32) {
29654
+ this.writeU8(202);
29655
+ this.writeF32(object);
29656
+ } else {
29657
+ this.writeU8(203);
29658
+ this.writeF64(object);
29659
+ }
29660
+ }
29661
+ encodeBigInt64(object) {
29662
+ if (object >= BigInt(0)) {
29663
+ this.writeU8(207);
29664
+ this.writeBigUint64(object);
29665
+ } else {
29666
+ this.writeU8(211);
29667
+ this.writeBigInt64(object);
29668
+ }
29669
+ }
29670
+ writeStringHeader(byteLength) {
29671
+ if (byteLength < 32) {
29672
+ this.writeU8(160 + byteLength);
29673
+ } else if (byteLength < 256) {
29674
+ this.writeU8(217);
29675
+ this.writeU8(byteLength);
29676
+ } else if (byteLength < 65536) {
29677
+ this.writeU8(218);
29678
+ this.writeU16(byteLength);
29679
+ } else if (byteLength < 4294967296) {
29680
+ this.writeU8(219);
29681
+ this.writeU32(byteLength);
29682
+ } else {
29683
+ throw new Error(`Too long string: ${byteLength} bytes in UTF-8`);
29684
+ }
29685
+ }
29686
+ encodeString(object) {
29687
+ const maxHeaderSize = 1 + 4;
29688
+ const byteLength = utf8Count(object);
29689
+ this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
29690
+ this.writeStringHeader(byteLength);
29691
+ utf8Encode(object, this.bytes, this.pos);
29692
+ this.pos += byteLength;
29693
+ }
29694
+ encodeObject(object, depth) {
29695
+ const ext = this.extensionCodec.tryToEncode(object, this.context);
29696
+ if (ext != null) {
29697
+ this.encodeExtension(ext);
29698
+ } else if (Array.isArray(object)) {
29699
+ this.encodeArray(object, depth);
29700
+ } else if (ArrayBuffer.isView(object)) {
29701
+ this.encodeBinary(object);
29702
+ } else if (typeof object === "object") {
29703
+ this.encodeMap(object, depth);
29704
+ } else {
29705
+ throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(object)}`);
29706
+ }
29707
+ }
29708
+ encodeBinary(object) {
29709
+ const size = object.byteLength;
29710
+ if (size < 256) {
29711
+ this.writeU8(196);
29712
+ this.writeU8(size);
29713
+ } else if (size < 65536) {
29714
+ this.writeU8(197);
29715
+ this.writeU16(size);
29716
+ } else if (size < 4294967296) {
29717
+ this.writeU8(198);
29718
+ this.writeU32(size);
29719
+ } else {
29720
+ throw new Error(`Too large binary: ${size}`);
29721
+ }
29722
+ const bytes = ensureUint8Array(object);
29723
+ this.writeU8a(bytes);
29724
+ }
29725
+ encodeArray(object, depth) {
29726
+ const size = object.length;
29727
+ if (size < 16) {
29728
+ this.writeU8(144 + size);
29729
+ } else if (size < 65536) {
29730
+ this.writeU8(220);
29731
+ this.writeU16(size);
29732
+ } else if (size < 4294967296) {
29733
+ this.writeU8(221);
29734
+ this.writeU32(size);
29735
+ } else {
29736
+ throw new Error(`Too large array: ${size}`);
29737
+ }
29738
+ for (const item of object) {
29739
+ this.doEncode(item, depth + 1);
29740
+ }
29741
+ }
29742
+ countWithoutUndefined(object, keys) {
29743
+ let count = 0;
29744
+ for (const key of keys) {
29745
+ if (object[key] !== void 0) {
29746
+ count++;
29747
+ }
29748
+ }
29749
+ return count;
29750
+ }
29751
+ encodeMap(object, depth) {
29752
+ const keys = Object.keys(object);
29753
+ if (this.sortKeys) {
29754
+ keys.sort();
29755
+ }
29756
+ const size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;
29757
+ if (size < 16) {
29758
+ this.writeU8(128 + size);
29759
+ } else if (size < 65536) {
29760
+ this.writeU8(222);
29761
+ this.writeU16(size);
29762
+ } else if (size < 4294967296) {
29763
+ this.writeU8(223);
29764
+ this.writeU32(size);
29765
+ } else {
29766
+ throw new Error(`Too large map object: ${size}`);
29767
+ }
29768
+ for (const key of keys) {
29769
+ const value = object[key];
29770
+ if (!(this.ignoreUndefined && value === void 0)) {
29771
+ this.encodeString(key);
29772
+ this.doEncode(value, depth + 1);
29773
+ }
29774
+ }
29775
+ }
29776
+ encodeExtension(ext) {
29777
+ if (typeof ext.data === "function") {
29778
+ const data = ext.data(this.pos + 6);
29779
+ const size2 = data.length;
29780
+ if (size2 >= 4294967296) {
29781
+ throw new Error(`Too large extension object: ${size2}`);
29782
+ }
29783
+ this.writeU8(201);
29784
+ this.writeU32(size2);
29785
+ this.writeI8(ext.type);
29786
+ this.writeU8a(data);
29787
+ return;
29788
+ }
29789
+ const size = ext.data.length;
29790
+ if (size === 1) {
29791
+ this.writeU8(212);
29792
+ } else if (size === 2) {
29793
+ this.writeU8(213);
29794
+ } else if (size === 4) {
29795
+ this.writeU8(214);
29796
+ } else if (size === 8) {
29797
+ this.writeU8(215);
29798
+ } else if (size === 16) {
29799
+ this.writeU8(216);
29800
+ } else if (size < 256) {
29801
+ this.writeU8(199);
29802
+ this.writeU8(size);
29803
+ } else if (size < 65536) {
29804
+ this.writeU8(200);
29805
+ this.writeU16(size);
29806
+ } else if (size < 4294967296) {
29807
+ this.writeU8(201);
29808
+ this.writeU32(size);
29809
+ } else {
29810
+ throw new Error(`Too large extension object: ${size}`);
29811
+ }
29812
+ this.writeI8(ext.type);
29813
+ this.writeU8a(ext.data);
29814
+ }
29815
+ writeU8(value) {
29816
+ this.ensureBufferSizeToWrite(1);
29817
+ this.view.setUint8(this.pos, value);
29818
+ this.pos++;
29819
+ }
29820
+ writeU8a(values) {
29821
+ const size = values.length;
29822
+ this.ensureBufferSizeToWrite(size);
29823
+ this.bytes.set(values, this.pos);
29824
+ this.pos += size;
29825
+ }
29826
+ writeI8(value) {
29827
+ this.ensureBufferSizeToWrite(1);
29828
+ this.view.setInt8(this.pos, value);
29829
+ this.pos++;
29830
+ }
29831
+ writeU16(value) {
29832
+ this.ensureBufferSizeToWrite(2);
29833
+ this.view.setUint16(this.pos, value);
29834
+ this.pos += 2;
29835
+ }
29836
+ writeI16(value) {
29837
+ this.ensureBufferSizeToWrite(2);
29838
+ this.view.setInt16(this.pos, value);
29839
+ this.pos += 2;
29840
+ }
29841
+ writeU32(value) {
29842
+ this.ensureBufferSizeToWrite(4);
29843
+ this.view.setUint32(this.pos, value);
29844
+ this.pos += 4;
29845
+ }
29846
+ writeI32(value) {
29847
+ this.ensureBufferSizeToWrite(4);
29848
+ this.view.setInt32(this.pos, value);
29849
+ this.pos += 4;
29850
+ }
29851
+ writeF32(value) {
29852
+ this.ensureBufferSizeToWrite(4);
29853
+ this.view.setFloat32(this.pos, value);
29854
+ this.pos += 4;
29855
+ }
29856
+ writeF64(value) {
29857
+ this.ensureBufferSizeToWrite(8);
29858
+ this.view.setFloat64(this.pos, value);
29859
+ this.pos += 8;
29860
+ }
29861
+ writeU64(value) {
29862
+ this.ensureBufferSizeToWrite(8);
29863
+ setUint64(this.view, this.pos, value);
29864
+ this.pos += 8;
29865
+ }
29866
+ writeI64(value) {
29867
+ this.ensureBufferSizeToWrite(8);
29868
+ setInt64(this.view, this.pos, value);
29869
+ this.pos += 8;
29870
+ }
29871
+ writeBigUint64(value) {
29872
+ this.ensureBufferSizeToWrite(8);
29873
+ this.view.setBigUint64(this.pos, value);
29874
+ this.pos += 8;
29875
+ }
29876
+ writeBigInt64(value) {
29877
+ this.ensureBufferSizeToWrite(8);
29878
+ this.view.setBigInt64(this.pos, value);
29879
+ this.pos += 8;
29880
+ }
29881
+ };
29882
+
29883
+ // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/utils/prettyByte.mjs
29884
+ function prettyByte(byte) {
29885
+ return `${byte < 0 ? "-" : ""}0x${Math.abs(byte).toString(16).padStart(2, "0")}`;
29886
+ }
29887
+
29888
+ // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/CachedKeyDecoder.mjs
29889
+ var DEFAULT_MAX_KEY_LENGTH = 16;
29890
+ var DEFAULT_MAX_LENGTH_PER_KEY = 16;
29891
+ var CachedKeyDecoder = class {
29892
+ hit = 0;
29893
+ miss = 0;
29894
+ caches;
29895
+ maxKeyLength;
29896
+ maxLengthPerKey;
29897
+ constructor(maxKeyLength = DEFAULT_MAX_KEY_LENGTH, maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY) {
29898
+ this.maxKeyLength = maxKeyLength;
29899
+ this.maxLengthPerKey = maxLengthPerKey;
29900
+ this.caches = [];
29901
+ for (let i = 0; i < this.maxKeyLength; i++) {
29902
+ this.caches.push([]);
29903
+ }
29904
+ }
29905
+ canBeCached(byteLength) {
29906
+ return byteLength > 0 && byteLength <= this.maxKeyLength;
29907
+ }
29908
+ find(bytes, inputOffset, byteLength) {
29909
+ const records = this.caches[byteLength - 1];
29910
+ FIND_CHUNK: for (const record of records) {
29911
+ const recordBytes = record.bytes;
29912
+ for (let j = 0; j < byteLength; j++) {
29913
+ if (recordBytes[j] !== bytes[inputOffset + j]) {
29914
+ continue FIND_CHUNK;
29915
+ }
29916
+ }
29917
+ return record.str;
29918
+ }
29919
+ return null;
29920
+ }
29921
+ store(bytes, value) {
29922
+ const records = this.caches[bytes.length - 1];
29923
+ const record = { bytes, str: value };
29924
+ if (records.length >= this.maxLengthPerKey) {
29925
+ records[Math.random() * records.length | 0] = record;
29926
+ } else {
29927
+ records.push(record);
29928
+ }
29929
+ }
29930
+ decode(bytes, inputOffset, byteLength) {
29931
+ const cachedValue = this.find(bytes, inputOffset, byteLength);
29932
+ if (cachedValue != null) {
29933
+ this.hit++;
29934
+ return cachedValue;
29935
+ }
29936
+ this.miss++;
29937
+ const str = utf8DecodeJs(bytes, inputOffset, byteLength);
29938
+ const slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);
29939
+ this.store(slicedCopyOfBytes, str);
29940
+ return str;
29941
+ }
29942
+ };
29943
+
29944
+ // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/Decoder.mjs
29945
+ var STATE_ARRAY = "array";
29946
+ var STATE_MAP_KEY = "map_key";
29947
+ var STATE_MAP_VALUE = "map_value";
29948
+ var mapKeyConverter = (key) => {
29949
+ if (typeof key === "string" || typeof key === "number") {
29950
+ return key;
29951
+ }
29952
+ throw new DecodeError("The type of key must be string or number but " + typeof key);
29953
+ };
29954
+ var StackPool = class {
29955
+ stack = [];
29956
+ stackHeadPosition = -1;
29957
+ get length() {
29958
+ return this.stackHeadPosition + 1;
29959
+ }
29960
+ top() {
29961
+ return this.stack[this.stackHeadPosition];
29962
+ }
29963
+ pushArrayState(size) {
29964
+ const state = this.getUninitializedStateFromPool();
29965
+ state.type = STATE_ARRAY;
29966
+ state.position = 0;
29967
+ state.size = size;
29968
+ state.array = new Array(size);
29969
+ }
29970
+ pushMapState(size) {
29971
+ const state = this.getUninitializedStateFromPool();
29972
+ state.type = STATE_MAP_KEY;
29973
+ state.readCount = 0;
29974
+ state.size = size;
29975
+ state.map = {};
29976
+ }
29977
+ getUninitializedStateFromPool() {
29978
+ this.stackHeadPosition++;
29979
+ if (this.stackHeadPosition === this.stack.length) {
29980
+ const partialState = {
29981
+ type: void 0,
29982
+ size: 0,
29983
+ array: void 0,
29984
+ position: 0,
29985
+ readCount: 0,
29986
+ map: void 0,
29987
+ key: null
29988
+ };
29989
+ this.stack.push(partialState);
29990
+ }
29991
+ return this.stack[this.stackHeadPosition];
29992
+ }
29993
+ release(state) {
29994
+ const topStackState = this.stack[this.stackHeadPosition];
29995
+ if (topStackState !== state) {
29996
+ throw new Error("Invalid stack state. Released state is not on top of the stack.");
29997
+ }
29998
+ if (state.type === STATE_ARRAY) {
29999
+ const partialState = state;
30000
+ partialState.size = 0;
30001
+ partialState.array = void 0;
30002
+ partialState.position = 0;
30003
+ partialState.type = void 0;
30004
+ }
30005
+ if (state.type === STATE_MAP_KEY || state.type === STATE_MAP_VALUE) {
30006
+ const partialState = state;
30007
+ partialState.size = 0;
30008
+ partialState.map = void 0;
30009
+ partialState.readCount = 0;
30010
+ partialState.type = void 0;
30011
+ }
30012
+ this.stackHeadPosition--;
30013
+ }
30014
+ reset() {
30015
+ this.stack.length = 0;
30016
+ this.stackHeadPosition = -1;
30017
+ }
30018
+ };
30019
+ var HEAD_BYTE_REQUIRED = -1;
30020
+ var EMPTY_VIEW = new DataView(new ArrayBuffer(0));
30021
+ var EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);
30022
+ try {
30023
+ EMPTY_VIEW.getInt8(0);
30024
+ } catch (e) {
30025
+ if (!(e instanceof RangeError)) {
30026
+ throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access");
30027
+ }
30028
+ }
30029
+ var MORE_DATA = new RangeError("Insufficient data");
30030
+ var sharedCachedKeyDecoder = new CachedKeyDecoder();
30031
+ var Decoder = class _Decoder {
30032
+ extensionCodec;
30033
+ context;
30034
+ useBigInt64;
30035
+ rawStrings;
30036
+ maxStrLength;
30037
+ maxBinLength;
30038
+ maxArrayLength;
30039
+ maxMapLength;
30040
+ maxExtLength;
30041
+ keyDecoder;
30042
+ mapKeyConverter;
30043
+ totalPos = 0;
30044
+ pos = 0;
30045
+ view = EMPTY_VIEW;
30046
+ bytes = EMPTY_BYTES;
30047
+ headByte = HEAD_BYTE_REQUIRED;
30048
+ stack = new StackPool();
30049
+ entered = false;
30050
+ constructor(options) {
30051
+ this.extensionCodec = options?.extensionCodec ?? ExtensionCodec.defaultCodec;
30052
+ this.context = options?.context;
30053
+ this.useBigInt64 = options?.useBigInt64 ?? false;
30054
+ this.rawStrings = options?.rawStrings ?? false;
30055
+ this.maxStrLength = options?.maxStrLength ?? UINT32_MAX;
30056
+ this.maxBinLength = options?.maxBinLength ?? UINT32_MAX;
30057
+ this.maxArrayLength = options?.maxArrayLength ?? UINT32_MAX;
30058
+ this.maxMapLength = options?.maxMapLength ?? UINT32_MAX;
30059
+ this.maxExtLength = options?.maxExtLength ?? UINT32_MAX;
30060
+ this.keyDecoder = options?.keyDecoder !== void 0 ? options.keyDecoder : sharedCachedKeyDecoder;
30061
+ this.mapKeyConverter = options?.mapKeyConverter ?? mapKeyConverter;
30062
+ }
30063
+ clone() {
30064
+ return new _Decoder({
30065
+ extensionCodec: this.extensionCodec,
30066
+ context: this.context,
30067
+ useBigInt64: this.useBigInt64,
30068
+ rawStrings: this.rawStrings,
30069
+ maxStrLength: this.maxStrLength,
30070
+ maxBinLength: this.maxBinLength,
30071
+ maxArrayLength: this.maxArrayLength,
30072
+ maxMapLength: this.maxMapLength,
30073
+ maxExtLength: this.maxExtLength,
30074
+ keyDecoder: this.keyDecoder
30075
+ });
30076
+ }
30077
+ reinitializeState() {
30078
+ this.totalPos = 0;
30079
+ this.headByte = HEAD_BYTE_REQUIRED;
30080
+ this.stack.reset();
30081
+ }
30082
+ setBuffer(buffer) {
30083
+ const bytes = ensureUint8Array(buffer);
30084
+ this.bytes = bytes;
30085
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
30086
+ this.pos = 0;
30087
+ }
30088
+ appendBuffer(buffer) {
30089
+ if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {
30090
+ this.setBuffer(buffer);
30091
+ } else {
30092
+ const remainingData = this.bytes.subarray(this.pos);
30093
+ const newData = ensureUint8Array(buffer);
30094
+ const newBuffer = new Uint8Array(remainingData.length + newData.length);
30095
+ newBuffer.set(remainingData);
30096
+ newBuffer.set(newData, remainingData.length);
30097
+ this.setBuffer(newBuffer);
30098
+ }
30099
+ }
30100
+ hasRemaining(size) {
30101
+ return this.view.byteLength - this.pos >= size;
30102
+ }
30103
+ createExtraByteError(posToShow) {
30104
+ const { view, pos } = this;
30105
+ return new RangeError(`Extra ${view.byteLength - pos} of ${view.byteLength} byte(s) found at buffer[${posToShow}]`);
30106
+ }
30107
+ /**
30108
+ * @throws {@link DecodeError}
30109
+ * @throws {@link RangeError}
30110
+ */
30111
+ decode(buffer) {
30112
+ if (this.entered) {
30113
+ const instance = this.clone();
30114
+ return instance.decode(buffer);
30115
+ }
30116
+ try {
30117
+ this.entered = true;
30118
+ this.reinitializeState();
30119
+ this.setBuffer(buffer);
30120
+ const object = this.doDecodeSync();
30121
+ if (this.hasRemaining(1)) {
30122
+ throw this.createExtraByteError(this.pos);
30123
+ }
30124
+ return object;
30125
+ } finally {
30126
+ this.entered = false;
30127
+ }
30128
+ }
30129
+ *decodeMulti(buffer) {
30130
+ if (this.entered) {
30131
+ const instance = this.clone();
30132
+ yield* instance.decodeMulti(buffer);
30133
+ return;
30134
+ }
30135
+ try {
30136
+ this.entered = true;
30137
+ this.reinitializeState();
30138
+ this.setBuffer(buffer);
30139
+ while (this.hasRemaining(1)) {
30140
+ yield this.doDecodeSync();
30141
+ }
30142
+ } finally {
30143
+ this.entered = false;
30144
+ }
30145
+ }
30146
+ async decodeAsync(stream) {
30147
+ if (this.entered) {
30148
+ const instance = this.clone();
30149
+ return instance.decodeAsync(stream);
30150
+ }
30151
+ try {
30152
+ this.entered = true;
30153
+ let decoded = false;
30154
+ let object;
30155
+ for await (const buffer of stream) {
30156
+ if (decoded) {
30157
+ this.entered = false;
30158
+ throw this.createExtraByteError(this.totalPos);
30159
+ }
30160
+ this.appendBuffer(buffer);
30161
+ try {
30162
+ object = this.doDecodeSync();
30163
+ decoded = true;
30164
+ } catch (e) {
30165
+ if (!(e instanceof RangeError)) {
30166
+ throw e;
30167
+ }
30168
+ }
30169
+ this.totalPos += this.pos;
30170
+ }
30171
+ if (decoded) {
30172
+ if (this.hasRemaining(1)) {
30173
+ throw this.createExtraByteError(this.totalPos);
30174
+ }
30175
+ return object;
30176
+ }
30177
+ const { headByte, pos, totalPos } = this;
30178
+ throw new RangeError(`Insufficient data in parsing ${prettyByte(headByte)} at ${totalPos} (${pos} in the current buffer)`);
30179
+ } finally {
30180
+ this.entered = false;
30181
+ }
30182
+ }
30183
+ decodeArrayStream(stream) {
30184
+ return this.decodeMultiAsync(stream, true);
30185
+ }
30186
+ decodeStream(stream) {
30187
+ return this.decodeMultiAsync(stream, false);
30188
+ }
30189
+ async *decodeMultiAsync(stream, isArray) {
30190
+ if (this.entered) {
30191
+ const instance = this.clone();
30192
+ yield* instance.decodeMultiAsync(stream, isArray);
30193
+ return;
30194
+ }
30195
+ try {
30196
+ this.entered = true;
30197
+ let isArrayHeaderRequired = isArray;
30198
+ let arrayItemsLeft = -1;
30199
+ for await (const buffer of stream) {
30200
+ if (isArray && arrayItemsLeft === 0) {
30201
+ throw this.createExtraByteError(this.totalPos);
30202
+ }
30203
+ this.appendBuffer(buffer);
30204
+ if (isArrayHeaderRequired) {
30205
+ arrayItemsLeft = this.readArraySize();
30206
+ isArrayHeaderRequired = false;
30207
+ this.complete();
30208
+ }
30209
+ try {
30210
+ while (true) {
30211
+ yield this.doDecodeSync();
30212
+ if (--arrayItemsLeft === 0) {
30213
+ break;
30214
+ }
30215
+ }
30216
+ } catch (e) {
30217
+ if (!(e instanceof RangeError)) {
30218
+ throw e;
30219
+ }
30220
+ }
30221
+ this.totalPos += this.pos;
30222
+ }
30223
+ } finally {
30224
+ this.entered = false;
30225
+ }
30226
+ }
30227
+ doDecodeSync() {
30228
+ DECODE: while (true) {
30229
+ const headByte = this.readHeadByte();
30230
+ let object;
30231
+ if (headByte >= 224) {
30232
+ object = headByte - 256;
30233
+ } else if (headByte < 192) {
30234
+ if (headByte < 128) {
30235
+ object = headByte;
30236
+ } else if (headByte < 144) {
30237
+ const size = headByte - 128;
30238
+ if (size !== 0) {
30239
+ this.pushMapState(size);
30240
+ this.complete();
30241
+ continue DECODE;
30242
+ } else {
30243
+ object = {};
30244
+ }
30245
+ } else if (headByte < 160) {
30246
+ const size = headByte - 144;
30247
+ if (size !== 0) {
30248
+ this.pushArrayState(size);
30249
+ this.complete();
30250
+ continue DECODE;
30251
+ } else {
30252
+ object = [];
30253
+ }
30254
+ } else {
30255
+ const byteLength = headByte - 160;
30256
+ object = this.decodeString(byteLength, 0);
30257
+ }
30258
+ } else if (headByte === 192) {
30259
+ object = null;
30260
+ } else if (headByte === 194) {
30261
+ object = false;
30262
+ } else if (headByte === 195) {
30263
+ object = true;
30264
+ } else if (headByte === 202) {
30265
+ object = this.readF32();
30266
+ } else if (headByte === 203) {
30267
+ object = this.readF64();
30268
+ } else if (headByte === 204) {
30269
+ object = this.readU8();
30270
+ } else if (headByte === 205) {
30271
+ object = this.readU16();
30272
+ } else if (headByte === 206) {
30273
+ object = this.readU32();
30274
+ } else if (headByte === 207) {
30275
+ if (this.useBigInt64) {
30276
+ object = this.readU64AsBigInt();
30277
+ } else {
30278
+ object = this.readU64();
30279
+ }
30280
+ } else if (headByte === 208) {
30281
+ object = this.readI8();
30282
+ } else if (headByte === 209) {
30283
+ object = this.readI16();
30284
+ } else if (headByte === 210) {
30285
+ object = this.readI32();
30286
+ } else if (headByte === 211) {
30287
+ if (this.useBigInt64) {
30288
+ object = this.readI64AsBigInt();
30289
+ } else {
30290
+ object = this.readI64();
30291
+ }
30292
+ } else if (headByte === 217) {
30293
+ const byteLength = this.lookU8();
30294
+ object = this.decodeString(byteLength, 1);
30295
+ } else if (headByte === 218) {
30296
+ const byteLength = this.lookU16();
30297
+ object = this.decodeString(byteLength, 2);
30298
+ } else if (headByte === 219) {
30299
+ const byteLength = this.lookU32();
30300
+ object = this.decodeString(byteLength, 4);
30301
+ } else if (headByte === 220) {
30302
+ const size = this.readU16();
30303
+ if (size !== 0) {
30304
+ this.pushArrayState(size);
30305
+ this.complete();
30306
+ continue DECODE;
30307
+ } else {
30308
+ object = [];
30309
+ }
30310
+ } else if (headByte === 221) {
30311
+ const size = this.readU32();
30312
+ if (size !== 0) {
30313
+ this.pushArrayState(size);
30314
+ this.complete();
30315
+ continue DECODE;
30316
+ } else {
30317
+ object = [];
30318
+ }
30319
+ } else if (headByte === 222) {
30320
+ const size = this.readU16();
30321
+ if (size !== 0) {
30322
+ this.pushMapState(size);
30323
+ this.complete();
30324
+ continue DECODE;
30325
+ } else {
30326
+ object = {};
30327
+ }
30328
+ } else if (headByte === 223) {
30329
+ const size = this.readU32();
30330
+ if (size !== 0) {
30331
+ this.pushMapState(size);
30332
+ this.complete();
30333
+ continue DECODE;
30334
+ } else {
30335
+ object = {};
30336
+ }
30337
+ } else if (headByte === 196) {
30338
+ const size = this.lookU8();
30339
+ object = this.decodeBinary(size, 1);
30340
+ } else if (headByte === 197) {
30341
+ const size = this.lookU16();
30342
+ object = this.decodeBinary(size, 2);
30343
+ } else if (headByte === 198) {
30344
+ const size = this.lookU32();
30345
+ object = this.decodeBinary(size, 4);
30346
+ } else if (headByte === 212) {
30347
+ object = this.decodeExtension(1, 0);
30348
+ } else if (headByte === 213) {
30349
+ object = this.decodeExtension(2, 0);
30350
+ } else if (headByte === 214) {
30351
+ object = this.decodeExtension(4, 0);
30352
+ } else if (headByte === 215) {
30353
+ object = this.decodeExtension(8, 0);
30354
+ } else if (headByte === 216) {
30355
+ object = this.decodeExtension(16, 0);
30356
+ } else if (headByte === 199) {
30357
+ const size = this.lookU8();
30358
+ object = this.decodeExtension(size, 1);
30359
+ } else if (headByte === 200) {
30360
+ const size = this.lookU16();
30361
+ object = this.decodeExtension(size, 2);
30362
+ } else if (headByte === 201) {
30363
+ const size = this.lookU32();
30364
+ object = this.decodeExtension(size, 4);
30365
+ } else {
30366
+ throw new DecodeError(`Unrecognized type byte: ${prettyByte(headByte)}`);
30367
+ }
30368
+ this.complete();
30369
+ const stack = this.stack;
30370
+ while (stack.length > 0) {
30371
+ const state = stack.top();
30372
+ if (state.type === STATE_ARRAY) {
30373
+ state.array[state.position] = object;
30374
+ state.position++;
30375
+ if (state.position === state.size) {
30376
+ object = state.array;
30377
+ stack.release(state);
30378
+ } else {
30379
+ continue DECODE;
30380
+ }
30381
+ } else if (state.type === STATE_MAP_KEY) {
30382
+ if (object === "__proto__") {
30383
+ throw new DecodeError("The key __proto__ is not allowed");
30384
+ }
30385
+ state.key = this.mapKeyConverter(object);
30386
+ state.type = STATE_MAP_VALUE;
30387
+ continue DECODE;
30388
+ } else {
30389
+ state.map[state.key] = object;
30390
+ state.readCount++;
30391
+ if (state.readCount === state.size) {
30392
+ object = state.map;
30393
+ stack.release(state);
30394
+ } else {
30395
+ state.key = null;
30396
+ state.type = STATE_MAP_KEY;
30397
+ continue DECODE;
30398
+ }
30399
+ }
30400
+ }
30401
+ return object;
30402
+ }
30403
+ }
30404
+ readHeadByte() {
30405
+ if (this.headByte === HEAD_BYTE_REQUIRED) {
30406
+ this.headByte = this.readU8();
30407
+ }
30408
+ return this.headByte;
30409
+ }
30410
+ complete() {
30411
+ this.headByte = HEAD_BYTE_REQUIRED;
30412
+ }
30413
+ readArraySize() {
30414
+ const headByte = this.readHeadByte();
30415
+ switch (headByte) {
30416
+ case 220:
30417
+ return this.readU16();
30418
+ case 221:
30419
+ return this.readU32();
30420
+ default: {
30421
+ if (headByte < 160) {
30422
+ return headByte - 144;
30423
+ } else {
30424
+ throw new DecodeError(`Unrecognized array type byte: ${prettyByte(headByte)}`);
30425
+ }
30426
+ }
30427
+ }
30428
+ }
30429
+ pushMapState(size) {
30430
+ if (size > this.maxMapLength) {
30431
+ throw new DecodeError(`Max length exceeded: map length (${size}) > maxMapLengthLength (${this.maxMapLength})`);
30432
+ }
30433
+ this.stack.pushMapState(size);
30434
+ }
30435
+ pushArrayState(size) {
30436
+ if (size > this.maxArrayLength) {
30437
+ throw new DecodeError(`Max length exceeded: array length (${size}) > maxArrayLength (${this.maxArrayLength})`);
30438
+ }
30439
+ this.stack.pushArrayState(size);
30440
+ }
30441
+ decodeString(byteLength, headerOffset) {
30442
+ if (!this.rawStrings || this.stateIsMapKey()) {
30443
+ return this.decodeUtf8String(byteLength, headerOffset);
30444
+ }
30445
+ return this.decodeBinary(byteLength, headerOffset);
30446
+ }
30447
+ /**
30448
+ * @throws {@link RangeError}
30449
+ */
30450
+ decodeUtf8String(byteLength, headerOffset) {
30451
+ if (byteLength > this.maxStrLength) {
30452
+ throw new DecodeError(`Max length exceeded: UTF-8 byte length (${byteLength}) > maxStrLength (${this.maxStrLength})`);
30453
+ }
30454
+ if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {
30455
+ throw MORE_DATA;
30456
+ }
30457
+ const offset = this.pos + headerOffset;
30458
+ let object;
30459
+ if (this.stateIsMapKey() && this.keyDecoder?.canBeCached(byteLength)) {
30460
+ object = this.keyDecoder.decode(this.bytes, offset, byteLength);
30461
+ } else {
30462
+ object = utf8Decode(this.bytes, offset, byteLength);
30463
+ }
30464
+ this.pos += headerOffset + byteLength;
30465
+ return object;
30466
+ }
30467
+ stateIsMapKey() {
30468
+ if (this.stack.length > 0) {
30469
+ const state = this.stack.top();
30470
+ return state.type === STATE_MAP_KEY;
30471
+ }
30472
+ return false;
30473
+ }
30474
+ /**
30475
+ * @throws {@link RangeError}
30476
+ */
30477
+ decodeBinary(byteLength, headOffset) {
30478
+ if (byteLength > this.maxBinLength) {
30479
+ throw new DecodeError(`Max length exceeded: bin length (${byteLength}) > maxBinLength (${this.maxBinLength})`);
30480
+ }
30481
+ if (!this.hasRemaining(byteLength + headOffset)) {
30482
+ throw MORE_DATA;
30483
+ }
30484
+ const offset = this.pos + headOffset;
30485
+ const object = this.bytes.subarray(offset, offset + byteLength);
30486
+ this.pos += headOffset + byteLength;
30487
+ return object;
30488
+ }
30489
+ decodeExtension(size, headOffset) {
30490
+ if (size > this.maxExtLength) {
30491
+ throw new DecodeError(`Max length exceeded: ext length (${size}) > maxExtLength (${this.maxExtLength})`);
30492
+ }
30493
+ const extType = this.view.getInt8(this.pos + headOffset);
30494
+ const data = this.decodeBinary(
30495
+ size,
30496
+ headOffset + 1
30497
+ /* extType */
30498
+ );
30499
+ return this.extensionCodec.decode(data, extType, this.context);
30500
+ }
30501
+ lookU8() {
30502
+ return this.view.getUint8(this.pos);
30503
+ }
30504
+ lookU16() {
30505
+ return this.view.getUint16(this.pos);
30506
+ }
30507
+ lookU32() {
30508
+ return this.view.getUint32(this.pos);
30509
+ }
30510
+ readU8() {
30511
+ const value = this.view.getUint8(this.pos);
30512
+ this.pos++;
30513
+ return value;
30514
+ }
30515
+ readI8() {
30516
+ const value = this.view.getInt8(this.pos);
30517
+ this.pos++;
30518
+ return value;
30519
+ }
30520
+ readU16() {
30521
+ const value = this.view.getUint16(this.pos);
30522
+ this.pos += 2;
30523
+ return value;
30524
+ }
30525
+ readI16() {
30526
+ const value = this.view.getInt16(this.pos);
30527
+ this.pos += 2;
30528
+ return value;
30529
+ }
30530
+ readU32() {
30531
+ const value = this.view.getUint32(this.pos);
30532
+ this.pos += 4;
30533
+ return value;
30534
+ }
30535
+ readI32() {
30536
+ const value = this.view.getInt32(this.pos);
30537
+ this.pos += 4;
30538
+ return value;
30539
+ }
30540
+ readU64() {
30541
+ const value = getUint64(this.view, this.pos);
30542
+ this.pos += 8;
30543
+ return value;
30544
+ }
30545
+ readI64() {
30546
+ const value = getInt64(this.view, this.pos);
30547
+ this.pos += 8;
30548
+ return value;
30549
+ }
30550
+ readU64AsBigInt() {
30551
+ const value = this.view.getBigUint64(this.pos);
30552
+ this.pos += 8;
30553
+ return value;
30554
+ }
30555
+ readI64AsBigInt() {
30556
+ const value = this.view.getBigInt64(this.pos);
30557
+ this.pos += 8;
30558
+ return value;
30559
+ }
30560
+ readF32() {
30561
+ const value = this.view.getFloat32(this.pos);
30562
+ this.pos += 4;
30563
+ return value;
30564
+ }
30565
+ readF64() {
30566
+ const value = this.view.getFloat64(this.pos);
30567
+ this.pos += 8;
30568
+ return value;
30569
+ }
30570
+ };
30571
+
30572
+ // src/vendor/titan/client.ts
30573
+ var SUBPROTOCOL = "v1.api.titan.ag";
30574
+ var UINT64_MAX = (1n << 64n) - 1n;
30575
+ function toBigInt(value) {
30576
+ if (typeof value === "bigint") {
30577
+ if (value < 0n || value > UINT64_MAX) {
30578
+ throw new RangeError(`Amount out of uint64 range: ${value}`);
30579
+ }
30580
+ return value;
30581
+ }
30582
+ if (!Number.isInteger(value)) {
30583
+ throw new TypeError(`Amount must be a whole number, got ${value}`);
30584
+ }
30585
+ if (value < 0) {
30586
+ throw new RangeError(`Amount must be non-negative, got ${value}`);
30587
+ }
30588
+ return BigInt(value);
30589
+ }
30590
+ var ConnectionClosed = class _ConnectionClosed extends Error {
30591
+ code;
30592
+ reason;
30593
+ constructor(code, reason) {
30594
+ super(`Client WebSocket closed with code ${code}: ${reason}`);
30595
+ this.name = "ConnectionClosed";
30596
+ Object.setPrototypeOf(this, _ConnectionClosed.prototype);
30597
+ this.code = code;
30598
+ this.reason = reason;
30599
+ }
30600
+ };
30601
+ var ErrorResponse = class _ErrorResponse extends Error {
30602
+ response;
30603
+ constructor(response) {
30604
+ super(`Request ${response.requestId} failed with code ${response.code}: ${response.message}`);
30605
+ this.name = "ErrorResponse";
30606
+ Object.setPrototypeOf(this, _ErrorResponse.prototype);
30607
+ this.response = response;
30608
+ }
30609
+ };
30610
+ var StreamError = class _StreamError extends Error {
30611
+ streamId;
30612
+ errorCode;
30613
+ errorMessage;
30614
+ constructor(packet) {
30615
+ const code = packet.errorCode ?? 0;
30616
+ const message = packet.errorMessage ?? "";
30617
+ super(`Stream ${packet.id} ended with error code ${code}: ${message}`);
30618
+ this.name = "StreamError";
30619
+ Object.setPrototypeOf(this, _StreamError.prototype);
30620
+ this.streamId = packet.id;
30621
+ this.errorCode = code;
30622
+ this.errorMessage = message;
30623
+ }
30624
+ };
30625
+ var encoder = new Encoder({ useBigInt64: true });
30626
+ var decoder = new Decoder({ useBigInt64: true });
30627
+ var V1Client = class _V1Client {
30628
+ socket;
30629
+ nextId = 0;
30630
+ _closed = false;
30631
+ _closing = false;
30632
+ pending = /* @__PURE__ */ new Map();
30633
+ streams = /* @__PURE__ */ new Map();
30634
+ streamStopping = /* @__PURE__ */ new Map();
30635
+ closeListeners = [];
30636
+ // --- Static connect ---
30637
+ static connect(url) {
30638
+ return new Promise((resolve, reject) => {
30639
+ const ws = new WebSocket(url, [SUBPROTOCOL]);
30640
+ ws.binaryType = "arraybuffer";
30641
+ ws.on("open", () => {
30642
+ resolve(new _V1Client(ws));
30643
+ });
30644
+ ws.on("error", (err) => {
30645
+ reject(err);
30646
+ });
30647
+ });
30648
+ }
30649
+ // --- Constructor ---
30650
+ constructor(socket) {
30651
+ this.socket = socket;
30652
+ this.socket.on("message", (data) => {
30653
+ this.handleMessage(data);
30654
+ });
30655
+ this.socket.on("close", (code, reason) => {
30656
+ this.handleClose(code, reason.toString());
30657
+ });
30658
+ this.socket.on("error", (err) => {
30659
+ this.handleError(err);
30660
+ });
30661
+ }
30662
+ nextRequestId() {
30663
+ return this.nextId++;
30664
+ }
30665
+ // --- Public API ---
30666
+ get closed() {
30667
+ return this._closed;
30668
+ }
30669
+ close() {
30670
+ if (this._closed) return Promise.resolve();
30671
+ return new Promise((resolve, reject) => {
30672
+ this.closeListeners.push({ resolve, reject });
30673
+ if (!this._closing) {
30674
+ this._closing = true;
30675
+ this.socket.close();
30676
+ }
30677
+ });
30678
+ }
30679
+ newSwapQuoteStream(params) {
30680
+ const requestId = this.nextRequestId();
30681
+ const promise = new Promise(
30682
+ (resolve, reject) => {
30683
+ this.pending.set(requestId, {
30684
+ resolve,
30685
+ reject,
30686
+ kind: "NewSwapQuoteStream"
30687
+ });
30688
+ }
30689
+ );
30690
+ const normalized = {
30691
+ ...params,
30692
+ swap: { ...params.swap, amount: toBigInt(params.swap.amount) }
30693
+ };
30694
+ const message = {
30695
+ id: requestId,
30696
+ data: { NewSwapQuoteStream: normalized }
30697
+ };
30698
+ this.send(message);
30699
+ return promise;
30700
+ }
30701
+ stopStream(streamId) {
30702
+ const requestId = this.nextRequestId();
30703
+ const promise = new Promise((resolve, reject) => {
30704
+ this.pending.set(requestId, {
30705
+ resolve,
30706
+ reject,
30707
+ kind: "StopStream"
30708
+ });
30709
+ });
30710
+ const message = {
30711
+ id: requestId,
30712
+ data: { StopStream: { id: streamId } }
30713
+ };
30714
+ this.send(message);
30715
+ return promise;
30716
+ }
30717
+ // --- Send ---
30718
+ send(message) {
30719
+ try {
30720
+ const encoded = encoder.encode(message);
30721
+ this.socket.send(encoded);
30722
+ } catch (err) {
30723
+ const req = this.pending.get(message.id);
30724
+ if (req) {
30725
+ this.pending.delete(message.id);
30726
+ req.reject(err);
30727
+ }
30728
+ }
30729
+ }
30730
+ // --- Message handling ---
30731
+ handleMessage(raw) {
30732
+ let buf;
30733
+ if (raw instanceof ArrayBuffer) {
30734
+ buf = new Uint8Array(raw);
30735
+ } else if (Buffer.isBuffer(raw)) {
30736
+ buf = new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);
30737
+ } else if (Array.isArray(raw)) {
30738
+ buf = new Uint8Array(Buffer.concat(raw));
30739
+ } else {
30740
+ return;
30741
+ }
30742
+ let message;
30743
+ try {
30744
+ message = decoder.decode(buf);
30745
+ } catch {
30746
+ this.socket.close(3002, "failed to decode message");
30747
+ return;
30748
+ }
30749
+ if ("Response" in message) {
30750
+ this.handleResponse(message.Response);
30751
+ } else if ("Error" in message) {
30752
+ this.handleResponseError(message.Error);
30753
+ } else if ("StreamData" in message) {
30754
+ this.handleStreamData(message.StreamData);
30755
+ } else if ("StreamEnd" in message) {
30756
+ this.handleStreamEnd(message.StreamEnd);
30757
+ }
30758
+ }
30759
+ handleResponse(msg) {
30760
+ const req = this.pending.get(msg.requestId);
30761
+ if (!req) return;
30762
+ this.pending.delete(msg.requestId);
30763
+ if ("NewSwapQuoteStream" in msg.data && req.kind === "NewSwapQuoteStream") {
30764
+ const streamInfo = msg.stream;
30765
+ if (!streamInfo) {
30766
+ req.reject(new Error("No stream associated with NewSwapQuoteStream response"));
30767
+ return;
30768
+ }
30769
+ const stream = new ReadableStream({
30770
+ start: (controller) => {
30771
+ this.streams.set(streamInfo.id, controller);
30772
+ },
30773
+ cancel: () => {
30774
+ return this.cancelStream(streamInfo.id);
30775
+ }
30776
+ });
30777
+ const result = {
30778
+ response: msg.data.NewSwapQuoteStream,
30779
+ stream,
30780
+ streamId: streamInfo.id
30781
+ };
30782
+ req.resolve(result);
30783
+ } else if ("StreamStopped" in msg.data && req.kind === "StopStream") {
30784
+ req.resolve(msg.data.StreamStopped);
30785
+ } else {
30786
+ req.reject(new Error(`Unexpected response type for ${req.kind}`));
30787
+ }
30788
+ }
30789
+ handleResponseError(error) {
30790
+ const req = this.pending.get(error.requestId);
30791
+ if (!req) return;
30792
+ this.pending.delete(error.requestId);
30793
+ req.reject(new ErrorResponse(error));
30794
+ }
30795
+ handleStreamData(packet) {
30796
+ const controller = this.streams.get(packet.id);
30797
+ if (!controller) return;
30798
+ if (packet.payload.SwapQuotes !== void 0) {
30799
+ controller.enqueue(packet.payload.SwapQuotes);
30800
+ }
30801
+ }
30802
+ handleStreamEnd(packet) {
30803
+ const controller = this.streams.get(packet.id);
30804
+ if (!controller) return;
30805
+ this.streams.delete(packet.id);
30806
+ this.streamStopping.delete(packet.id);
30807
+ if (packet.errorCode !== void 0) {
30808
+ controller.error(new StreamError(packet));
30809
+ } else {
30810
+ controller.close();
30811
+ }
30812
+ }
30813
+ async cancelStream(streamId) {
30814
+ if (this.streamStopping.get(streamId) || !this.streams.has(streamId)) return;
30815
+ this.streamStopping.set(streamId, true);
30816
+ await this.stopStream(streamId);
30817
+ }
30818
+ // --- Connection lifecycle ---
30819
+ rejectAll(error) {
30820
+ for (const req of this.pending.values()) {
30821
+ req.reject(error);
30822
+ }
30823
+ this.pending.clear();
30824
+ for (const controller of this.streams.values()) {
30825
+ controller.error(error);
30826
+ }
30827
+ this.streams.clear();
30828
+ this.streamStopping.clear();
30829
+ }
30830
+ handleClose(code, reason) {
30831
+ this._closed = true;
30832
+ this.rejectAll(new ConnectionClosed(code, reason));
30833
+ for (const listener of this.closeListeners) {
30834
+ listener.resolve();
30835
+ }
30836
+ this.closeListeners = [];
30837
+ }
30838
+ handleError(err) {
30839
+ this.rejectAll(err);
30840
+ this.socket.close(3002);
30841
+ }
30842
+ };
30843
+
30844
+ // src/vendor/titan/types.ts
30845
+ var SwapMode = /* @__PURE__ */ ((SwapMode2) => {
30846
+ SwapMode2["ExactIn"] = "ExactIn";
30847
+ SwapMode2["ExactOut"] = "ExactOut";
30848
+ return SwapMode2;
30849
+ })(SwapMode || {});
30850
+ var SwapVersion = /* @__PURE__ */ ((SwapVersion2) => {
30851
+ SwapVersion2[SwapVersion2["V2"] = 2] = "V2";
30852
+ SwapVersion2[SwapVersion2["V3"] = 3] = "V3";
30853
+ return SwapVersion2;
30854
+ })(SwapVersion || {});
30855
+ function deserializeSerializedInstruction(ix) {
30856
+ return new TransactionInstruction({
30857
+ programId: new PublicKey(Buffer.from(ix.p, "base64")),
30858
+ keys: ix.a.map((account) => ({
30859
+ pubkey: new PublicKey(Buffer.from(account.p, "base64")),
30860
+ isSigner: account.s,
30861
+ isWritable: account.w
30862
+ })),
30863
+ data: Buffer.from(ix.d, "base64")
30864
+ });
30865
+ }
30866
+ function selectBestRoute(quotes, swapMode) {
30867
+ const routes = Object.values(quotes);
30868
+ if (routes.length === 0) return null;
30869
+ return routes.reduce((best, route) => {
30870
+ if (swapMode === "ExactIn") {
30871
+ return route.outAmount > best.outAmount ? route : best;
30872
+ } else {
30873
+ return route.inAmount < best.inAmount ? route : best;
30874
+ }
30875
+ });
30876
+ }
30877
+ function buildSwapQuoteResult(route, swapMode) {
30878
+ const slippageBps = route.slippageBps;
30879
+ let otherAmountThreshold;
30880
+ if (swapMode === "ExactIn") {
30881
+ otherAmountThreshold = String(Math.floor(route.outAmount * (1 - slippageBps / 1e4)));
30882
+ } else {
30883
+ otherAmountThreshold = String(Math.ceil(route.inAmount * (1 + slippageBps / 1e4)));
30884
+ }
30885
+ return {
30886
+ inAmount: String(route.inAmount),
30887
+ outAmount: String(route.outAmount),
30888
+ otherAmountThreshold,
30889
+ slippageBps,
30890
+ platformFee: route.platformFee ? {
30891
+ amount: String(route.platformFee.amount),
30892
+ feeBps: route.platformFee.fee_bps
30893
+ } : void 0,
30894
+ contextSlot: route.contextSlot,
30895
+ timeTaken: route.timeTaken
30896
+ };
30897
+ }
30898
+ async function resolveLookupTables(connection, lutPubkeys) {
30899
+ if (lutPubkeys.length === 0) return [];
30900
+ const lutAccountsRaw = await connection.getMultipleAccountsInfo(lutPubkeys);
30901
+ return lutAccountsRaw.map((accountInfo, index) => {
30902
+ if (!accountInfo) return null;
30903
+ return new AddressLookupTableAccount({
30904
+ key: lutPubkeys[index],
30905
+ state: AddressLookupTableAccount.deserialize(accountInfo.data)
30906
+ });
30907
+ }).filter((account) => account !== null);
30908
+ }
30909
+
30910
+ export { ACCOUNT_SIZE, ACCOUNT_TYPE_SIZE, ASSOCIATED_TOKEN_PROGRAM_ID, AccountLayout, AccountState, AccountType, ConnectionClosed, CorpAction, DEFAULT_RECENT_SLOT_DURATION_MS, DRIFT_IDL, DRIFT_PROGRAM_ID, DriftSpotBalanceType, ErrorResponse, ExtensionType, FARMS_PROGRAM_ID, JUP_EXCHANGE_PRICES_PRECISION, JUP_LEND_IDL, JUP_LEND_PROGRAM_ID, JUP_LIQUIDITY_PROGRAM_ID, JUP_MAX_REWARDS_RATE, JUP_REWARDS_PROGRAM_ID, JUP_SECONDS_PER_YEAR, KFARMS_IDL, KLEND_ACCOUNT_CODER, KLEND_IDL, KLEND_PROGRAM_ID, LENGTH_SIZE, MAX_SLOT_DIFFERENCE, MEMO_PROGRAM_ID, MINT_SIZE, MULTISIG_SIZE, MintLayout, MultisigLayout, NATIVE_MINT, ONE, ONE_HUNDRED_PCT_IN_BPS, ONE_YEAR, PERCENTAGE_PRECISION, PERCENTAGE_PRECISION_EXP, PriceStatus, PriceType, REFRESH_OBLIGATION_DISCRIMINATOR, SEED_BASE_REFERRER_STATE, SEED_BASE_REFERRER_TOKEN_STATE, SEED_BASE_SHORT_URL, SEED_BASE_USER_METADATA, SEED_DRIFT_SIGNER, SEED_DRIFT_STATE, SEED_FEE_RECEIVER, SEED_F_TOKEN_MINT, SEED_LENDING, SEED_LENDING_ADMIN, SEED_LENDING_MARKET_AUTH, SEED_LENDING_REWARDS_RATE_MODEL, SEED_LIQUIDITY, SEED_RATE_MODEL, SEED_RESERVE, SEED_RESERVE_COLL_MINT, SEED_RESERVE_COLL_SUPPLY, SEED_RESERVE_LIQ_SUPPLY, SEED_SPOT_MARKET, SEED_SPOT_MARKET_VAULT, SEED_USER, SEED_USER_CLAIM, SEED_USER_STATE, SEED_USER_STATS, SEED_USER_SUPPLY_POSITION, SLOTS_PER_DAY, SLOTS_PER_HOUR, SLOTS_PER_MINUTE, SLOTS_PER_SECOND, SLOTS_PER_YEAR, SPOT_MARKET_RATE_PRECISION, SPOT_MARKET_RATE_PRECISION_EXP, SPOT_MARKET_UTILIZATION_PRECISION, SPOT_MARKET_UTILIZATION_PRECISION_EXP, SWITCHBOARD_ONDEMANDE_PRICE_PRECISION, SinglePoolInstruction, SplAccountType, SpotBalanceType, StreamError, SwapMode, SwapVersion, TEN, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID, TYPE_SIZE, TokenAccountNotFoundError, TokenError, TokenInstruction, TokenInvalidAccountError, TokenInvalidAccountOwnerError, TokenInvalidAccountSizeError, TokenInvalidInstructionDataError, TokenInvalidInstructionKeysError, TokenInvalidInstructionProgramError, TokenInvalidInstructionTypeError, TokenInvalidMintError, TokenInvalidOwnerError, TokenOwnerOffCurveError, TokenUnsupportedInstructionError, V1Client, ZERO, addSigners, buildSwapQuoteResult, calculateAPYFromAPR, calculateDriftBorrowAPR, calculateDriftBorrowAPY, calculateDriftBorrowRate, calculateDriftDepositRate, calculateDriftInterestRate, calculateDriftLendingAPR, calculateDriftLendingAPY, calculateDriftUtilization, calculateJupLendBorrowRate, calculateJupLendLiquiditySupplyRate, calculateJupLendNewExchangePrice, calculateJupLendRewardsRate, calculateJupLendRewardsRateForExchangePrice, calculateJupLendSupplyAPY, calculateJupLendSupplyRate, calculateJupLendTotalAssets, calculateKaminoEstimatedBorrowRate, calculateKaminoEstimatedSupplyRate, calculateKaminoSupplyAPY, calculateRewardApy, calculateSlotAdjustmentFactor, calculateUtilizationRatio, closeAccountInstructionData, createAccountIx, createAssociatedTokenAccountIdempotentInstruction, createAssociatedTokenAccountInstruction, createCloseAccountInstruction, createInitializeAccountInstruction, createMemoInstruction, createPoolOnrampIx, createSyncNativeInstruction, createTransferCheckedInstruction, decodeDriftSpotMarketData, decodeDriftStateData, decodeDriftUserData, decodeDriftUserStatsData, decodeFarmDataRaw, decodeJupLendingRewardsRateModelData, decodeJupLendingStateData, decodeJupRateModelData, decodeJupTokenReserveData, decodeKlendObligationData, decodeKlendReserveData, decodeSwitchboardPullFeedData, deriveBaseObligation, deriveDriftSigner, deriveDriftSpotMarket, deriveDriftSpotMarketVault, deriveDriftState, deriveDriftUser, deriveDriftUserStats, deriveFeeReceiver, deriveJupLendClaimAccount, deriveJupLendFTokenMint, deriveJupLendLending, deriveJupLendLendingAdmin, deriveJupLendLendingPdas, deriveJupLendLendingRewardsRateModel, deriveJupLendLiquidity, deriveJupLendLiquiditySupplyPositionPda, deriveJupLendLiquidityVaultAta, deriveJupLendRateModel, deriveJupLendTokenReserve, deriveLendingMarketAuthority, deriveObligation, deriveReferrerState, deriveReferrerTokenState, deriveReserveCollateralMint, deriveReserveCollateralSupply, deriveReserveLiquiditySupply, deriveShortUrl, deriveUserMetadata, deriveUserState, deserializeSerializedInstruction, driftRewardsRawToDto, driftSpotMarketRawToDto, driftStateRawToDto, driftUserRawToDto, driftUserStatsRawToDto, dtoToDriftRewardsRaw, dtoToDriftSpotMarketRaw, dtoToDriftStateRaw, dtoToDriftUserRaw, dtoToDriftUserStatsRaw, dtoToFarmRaw, dtoToJupLendingRewardsRateModelRaw, dtoToJupLendingStateRaw, dtoToJupRateModelRaw, dtoToJupTokenReserveRaw, dtoToObligationRaw, dtoToReserveRaw, farmRawToDto, findMplMetadataAddress, findPoolAddress, findPoolMintAddress, findPoolMintAddressByVoteAccount, findPoolMintAuthorityAddress, findPoolMplAuthorityAddress, findPoolOnRampAddress, findPoolStakeAddress, findPoolStakeAuthorityAddress, generateDriftReserveCurve, generateJupLendSupplyCurve, generateKaminoReserveCurve, getAccount, getAccountLen, getAllDerivedDriftAccounts, getAllDerivedJupLendAccounts, getAllDerivedKaminoAccounts, getAllRequiredMarkets, getAssociatedTokenAddressSync, getDriftRewards, getDriftTokenAmount, getFixedHostInterestRate, getJupLendRewards, getKaminoBorrowRate, getKaminoTotalSupply, getMinimumBalanceForRentExemptAccount, getMinimumBalanceForRentExemptAccountWithExtensions, getMint, getMultipleAccounts, getProtocolTakeRatePct, getReserveRewardsApy, getRewardPerTimeUnitSecond, getStakeAccount, getSwitchboardProgram, initializeAccountInstructionData, initializeStakedPoolIxs, initializeStakedPoolTx, interpolateLinear, isSpotBalanceTypeVariant, jupLendingRewardsRateModelRawToDto, jupLendingStateRawToDto, jupRateModelRawToDto, jupTokenReserveRawToDto, layout, makeRefreshObligationIx, makeRefreshReservesBatchIx, makeRefreshingIxs, makeUpdateJupLendRate, makeUpdateJupLendRateIx, makeUpdateSpotMarketCumulativeInterestIx, makeUpdateSpotMarketIx, obligationRawToDto, parsePriceData, parsePriceInfo2 as parsePriceInfo, replenishPoolIx, reserveRawToDto, resolveLookupTables, scaledSupplies, selectBestRoute, slotAdjustmentFactor, switchboardAccountCoder, syncNativeInstructionData, transferCheckedInstructionData, truncateBorrowCurve, unpackAccount };
29166
30911
  //# sourceMappingURL=vendor.js.map
29167
30912
  //# sourceMappingURL=vendor.js.map