@secondlayer/sdk 10.4.2 → 10.5.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/index.d.ts CHANGED
@@ -39,6 +39,31 @@ interface SecondLayerOptions {
39
39
  * retry policy instead of stalling a walk or consume loop forever. `0`
40
40
  * disables the timeout. */
41
41
  requestTimeoutMs?: number;
42
+ /** Where GET responses carrying an `ETag` are kept, so a repeat read sends
43
+ * `If-None-Match` and a finalized page comes back as a free `304`.
44
+ * Defaults to an in-memory store of the last 64 pages. Pass your own to
45
+ * keep it across processes (a file, a KV), or `false` to turn it off. */
46
+ etagCache?: EtagCache | false;
47
+ }
48
+ /** One cached GET response: its validator and the body it validated. */
49
+ type EtagEntry = {
50
+ etag: string;
51
+ body: string;
52
+ };
53
+ /** Storage for `etagCache`. Keys are full request URLs. Either method may be
54
+ * async, so a disk or KV store works as well as a Map. */
55
+ interface EtagCache {
56
+ get(key: string): EtagEntry | undefined | Promise<EtagEntry | undefined>;
57
+ set(key: string, entry: EtagEntry): void | Promise<void>;
58
+ }
59
+ /** Bounded in-memory `EtagCache`. Evicts the least recently used page, so a
60
+ * long walk can't hold more than `limit` page bodies. */
61
+ declare class MemoryEtagCache implements EtagCache {
62
+ private readonly limit;
63
+ private entries;
64
+ constructor(limit?: number);
65
+ get(key: string): EtagEntry | undefined;
66
+ set(key: string, entry: EtagEntry): void;
42
67
  }
43
68
  /** Default per-request budget. Long enough for a 1000-row filtered page on a
44
69
  * cold cache, short enough that a half-open connection surfaces as a retry. */
@@ -72,6 +97,7 @@ declare abstract class BaseClient {
72
97
  protected origin: "cli" | "mcp" | "session";
73
98
  protected fetchImpl: FetchLike;
74
99
  protected requestTimeoutMs: number;
100
+ protected etagCache: EtagCache | null;
75
101
  constructor(options?: Partial<SecondLayerOptions>);
76
102
  static authHeaders(apiKey?: string): Record<string, string>;
77
103
  protected request<T>(method: string, path: string, body?: unknown, opts?: RequestOptions): Promise<T>;
@@ -88,7 +114,7 @@ declare abstract class BaseClient {
88
114
  /** Issue the HTTP request and map non-2xx statuses onto the error family.
89
115
  * `signal` is the combined caller-plus-timeout signal from `request*`;
90
116
  * subclasses that stream a body call this directly and read it themselves. */
91
- protected fetchResponse(method: string, path: string, body?: unknown, signal?: AbortSignal): Promise<Response>;
117
+ protected fetchResponse(method: string, path: string, body?: unknown, signal?: AbortSignal, extraHeaders?: Record<string, string>): Promise<Response>;
92
118
  }
93
119
  interface SubgraphSource {
94
120
  name: string;
@@ -647,8 +673,9 @@ type SinkTx<S> = S extends ConsumerSink<infer Tx> ? Tx : never;
647
673
  type WithSinkTx<TTx> = [TTx] extends [never] ? unknown : {
648
674
  tx: TTx;
649
675
  };
650
- import { StreamsEvent, StreamsEventType } from "@secondlayer/shared/streams-rows";
651
- import { StreamsEventPayload } from "@secondlayer/shared/streams-rows";
676
+ import { VmEventType } from "@secondlayer/shared";
677
+ import { StreamsEvent, StreamsEventType, StreamsWireEvent, VmStreamsEvent } from "@secondlayer/shared/streams-rows";
678
+ import { StreamsWireEvent as StreamsWireEvent2, StreamsEventPayload } from "@secondlayer/shared/streams-rows";
652
679
  type StreamsTip = {
653
680
  block_height: number;
654
681
  block_hash: string;
@@ -744,9 +771,11 @@ type StreamsEventsListParams = {
744
771
  cursor?: string | null;
745
772
  fromHeight?: number;
746
773
  toHeight?: number;
747
- types?: readonly StreamsEventType[];
774
+ /** `vm` reads ordinal. Omit for Streams 1.0. */
775
+ clock?: "classic" | "vm";
776
+ types?: readonly (StreamsEventType | VmEventType)[];
748
777
  /** Event types to exclude (applied after `types`). */
749
- notTypes?: readonly StreamsEventType[];
778
+ notTypes?: readonly (StreamsEventType | VmEventType)[];
750
779
  contractId?: StreamsFilterValue;
751
780
  sender?: StreamsFilterValue;
752
781
  recipient?: StreamsFilterValue;
@@ -1138,11 +1167,26 @@ type StreamsClient = {
1138
1167
  }): AsyncIterableIterator<StreamsBatch<StreamsEventOfTypes<T>>>;
1139
1168
  consume(params?: StreamsConsumeParams): AsyncIterableIterator<StreamsBatch>;
1140
1169
  events: {
1141
- /** Narrowing overload, matching `consume`. */
1142
- list<const T extends readonly StreamsEventType[]>(params: StreamsEventsListParams & {
1170
+ /** `clock: "vm"` pages carry vm rows only (a parallel vocabulary,
1171
+ * `event_index` = `ordinal`). Never `StreamsEvent`. */
1172
+ list(params: StreamsEventsListParams & {
1173
+ clock: "vm";
1174
+ }): Promise<StreamsEventsEnvelope<VmStreamsEvent>>;
1175
+ /** Narrowing overload, matching `consume`. Classic clock only —
1176
+ * `clock: "vm"` is overload 1, and a general `StreamsEventsListParams`
1177
+ * variable (clock unresolved) is the wire-union fallback. */
1178
+ list<const T extends readonly StreamsEventType[]>(params: Omit<StreamsEventsListParams, "clock" | "types" | "notTypes"> & {
1143
1179
  types: T;
1180
+ notTypes?: readonly StreamsEventType[];
1181
+ clock?: "classic";
1144
1182
  }): Promise<StreamsEventsEnvelope<StreamsEventOfTypes<T>>>;
1145
- list(params?: StreamsEventsListParams): Promise<StreamsEventsEnvelope>;
1183
+ list(params?: Omit<StreamsEventsListParams, "clock" | "types" | "notTypes"> & {
1184
+ types?: readonly StreamsEventType[];
1185
+ notTypes?: readonly StreamsEventType[];
1186
+ clock?: "classic";
1187
+ }): Promise<StreamsEventsEnvelope>;
1188
+ /** Unresolved `clock` on a general params variable: the wire union. */
1189
+ list(params: StreamsEventsListParams): Promise<StreamsEventsEnvelope<StreamsWireEvent>>;
1146
1190
  byTxId(txId: string): Promise<StreamsEventsListEnvelope>;
1147
1191
  /**
1148
1192
  * Pull pages from Streams and call `onBatch` after each page.
@@ -1552,8 +1596,38 @@ type IndexPrint = IndexEventBase & {
1552
1596
  raw_value: string | null;
1553
1597
  };
1554
1598
  };
1599
+ type IndexNestedContractCall = IndexEventBase & {
1600
+ event_type: "nested_contract_call";
1601
+ sender: string | null;
1602
+ caller: string;
1603
+ function_name: string;
1604
+ function_args: unknown;
1605
+ raw_result: string | null;
1606
+ };
1607
+ type IndexVarSet = IndexEventBase & {
1608
+ event_type: "var_set";
1609
+ var_name: string;
1610
+ raw_value: string;
1611
+ };
1612
+ type IndexMapSet = IndexEventBase & {
1613
+ event_type: "map_set";
1614
+ map: string;
1615
+ raw_key: string;
1616
+ raw_value: string;
1617
+ };
1618
+ type IndexMapInsert = IndexEventBase & {
1619
+ event_type: "map_insert";
1620
+ map: string;
1621
+ raw_key: string;
1622
+ raw_value: string;
1623
+ };
1624
+ type IndexMapDelete = IndexEventBase & {
1625
+ event_type: "map_delete";
1626
+ map: string;
1627
+ raw_key: string;
1628
+ };
1555
1629
  /** Decoded chain event, discriminated by `event_type`. */
1556
- type IndexEvent = IndexFtTransfer | IndexNftTransfer | IndexStxTransfer | IndexStxMint | IndexStxBurn | IndexStxLock | IndexFtMint | IndexFtBurn | IndexNftMint | IndexNftBurn | IndexPrint;
1630
+ type IndexEvent = IndexFtTransfer | IndexNftTransfer | IndexStxTransfer | IndexStxMint | IndexStxBurn | IndexStxLock | IndexFtMint | IndexFtBurn | IndexNftMint | IndexNftBurn | IndexPrint | IndexNestedContractCall | IndexVarSet | IndexMapSet | IndexMapInsert | IndexMapDelete;
1557
1631
  type IndexEventType = IndexEvent["event_type"];
1558
1632
  /** Fields every read returns regardless of `fields` — the consume contract
1559
1633
  * (`cursor`, `block_height`) plus the union discriminant. */
@@ -1578,8 +1652,7 @@ type IndexEventOf<T extends IndexEventType> = Extract<IndexEvent, {
1578
1652
  event_type: T;
1579
1653
  }>;
1580
1654
  type EventsListParams<T extends IndexEventType = IndexEventType> = {
1581
- /** Required. One of the decoded event types. Passing a literal narrows the
1582
- * rows every surface hands back to that event's own shape. */
1655
+ /** Decoded types or VM types (`nested_contract_call`, `map_set`, …). */
1583
1656
  eventType: T;
1584
1657
  cursor?: string | null;
1585
1658
  fromCursor?: string | null;
@@ -1590,6 +1663,12 @@ type EventsListParams<T extends IndexEventType = IndexEventType> = {
1590
1663
  assetIdentifier?: string;
1591
1664
  sender?: string;
1592
1665
  recipient?: string;
1666
+ functionName?: string;
1667
+ caller?: string;
1668
+ map?: string;
1669
+ varName?: string;
1670
+ /** Restrict to one transaction. */
1671
+ txId?: string;
1593
1672
  fromHeight?: number;
1594
1673
  toHeight?: number;
1595
1674
  /** Restrict to contracts conforming to a trait/standard (e.g. "sip-010").
@@ -3136,4 +3215,4 @@ declare function verifySecondlayerSignature(rawBody: string, headers: WebhookHea
3136
3215
  declare function decodeChainWebhook(rawBody: string): ChainWebhookDelivery;
3137
3216
  import { RewardSet as RewardSet2 } from "@secondlayer/shared/node/consensus";
3138
3217
  import { decodeClarityValue, toJsonSafe } from "@secondlayer/shared/streams-rows";
3139
- export { verifyWebhookSignature, verifyTransactionProof, verify as verifyStandardWebhooksHeaders, verifySecondlayerSignature, trigger, toJsonSafe, shutdownSignal, resolveBaseUrl, resolveApiKey, resolveAccountKey, parseRetryAfter, isStxTransfer, isStxMint, isStxLock, isStxBurn, isPrint, isNftTransfer, isNftMint, isNftBurn, isFtTransfer, isFtMint, isFtBurn, getSubgraph, fetchRewardSet, decodeStxTransfer, decodeStxMint, decodeStxLock, decodeStxBurn, decodePrint, decodeNftTransfer, decodeNftMint, decodeNftBurn, decodeFtTransfer, decodeFtMint, decodeFtBurn, decodeClarityValue, decodeChainWebhook, decode, createStreamsClient, createArchiveClient, contextField, consumerHealth, consumeIndexFeed, WithSinkTx, Webhooks, WebhookTestResult2 as WebhookTestResult, WebhookSummary2 as WebhookSummary, WebhookStatus, WebhookRuntime, WebhookKind, WebhookHeaderInput, WebhookFormat, WebhookDetail2 as WebhookDetail, WalkOptions, ValidationError, UpdateWebhookRequest2 as UpdateWebhookRequest, TransactionsWalkParams, TransactionsListParams, TransactionsEnvelope, TransactionProofVerifyResult, TransactionProof, TransactionEnvelope, Subgraphs, SubgraphSpecOptions3 as SubgraphSpecOptions, SubgraphSpecFormat2 as SubgraphSpecFormat, SubgraphOperationStatus, SubgraphAgentSchema3 as SubgraphAgentSchema, StreamsTip, StreamsSubscription, StreamsSignatureError, StreamsServerError, StreamsReorgsListParams, StreamsReorgsListEnvelope, StreamsReorgContext, StreamsReorg, StreamsEventsSubscribeParams, StreamsEventsStreamParams, StreamsEventsListParams, StreamsEventsListEnvelope, StreamsEventsEnvelope, StreamsEventsConsumeResult, StreamsEventsConsumeParams, StreamsEventType, StreamsEventPayload, StreamsEvent, StreamsDumpsManifest, StreamsDumps, StreamsDumpFile, StreamsConsumeParams, StreamsClient, StreamsCanonicalBlock, StreamsBatchContext, StreamsBatch, StandardWebhooksHeaders2 as StandardWebhooksHeaders, StackingWalkParams, StackingListParams, StackingEnvelope, SinkTx, SecondLayerOptions, SecondLayerErrorOptions, SecondLayerError, SecondLayerArchive, SecondLayer, SbtcWithdrawalsWalkParams, SbtcWithdrawalsListParams, SbtcWithdrawalsEnvelope, SbtcWithdrawalSweptConfirmedEvent, SbtcWithdrawalStatus, SbtcWithdrawalEvent, SbtcWithdrawalEnvelope, SbtcSummaryEnvelope, SbtcResource, SbtcEventsWalkParams, SbtcEventsListParams, SbtcEventsEnvelope, SbtcEventsConsumeParams, SbtcEventTopic2 as SbtcEventTopic, SbtcDepositsWalkParams, SbtcDepositsListParams, SbtcDepositsEnvelope, SbtcDepositsConsumeParams, SbtcDepositEvent, SbtcDepositEnvelope, RotateSecretResponse2 as RotateSecretResponse, RewardSet2 as RewardSet, RequestOptions, ReplayResult2 as ReplayResult, RateLimitError, PublicStatus2 as PublicStatus, PrintSchemaResponse, PoxResource, PoxCyclesWalkParams, PoxCyclesListParams, PoxCyclesEnvelope, PoxCycleEnvelope, Pox5Resource, Pox5EventsWalkParams, Pox5EventsListParams, Pox5EventsEnvelope, NftTransfersWalkParams, NftTransfersResource, NftTransfersListParams, NftTransfersEnvelope, NftTransferPayload2 as NftTransferPayload, NftTransferEvent, NftTransfer, MempoolWalkParams, MempoolTransactionEnvelope, MempoolListParams, MempoolEnvelope, LoadedArchive, LOCAL_API_URL, InsufficientArchiveCreditsError, InstanceStatus, InstanceState, InstanceIssue, InstanceDiagnosis3 as InstanceDiagnosis, InstanceClient, IndexTransaction, IndexTip, IndexStxTransfer, IndexStxMint, IndexStxLock, IndexStxBurn, IndexStackingAction, IndexSbtcWithdrawalPhase, IndexSbtcWithdrawalDetail, IndexSbtcWithdrawal, IndexSbtcSummary, IndexSbtcEvent, IndexSbtcDepositDetail, IndexSbtcDeposit, IndexReorg, IndexPrint, IndexPoxFunctionCount, IndexPoxCycle, IndexPox5EventTopic, IndexPox5Event, IndexPostCondition, IndexNftTransfer, IndexNftMint, IndexNftBurn, IndexMempoolTransaction, IndexFtTransfer, IndexFtMint, IndexFtBurn, IndexFeedItem, IndexFeedFetcher, IndexFeedEnvelope, IndexEventsResource, IndexEventTypeFilters, IndexEventType, IndexEventOf, IndexEventFields, IndexEvent, IndexDiscovery, IndexContractCall, IndexConsumeOptions, IndexCanonicalBlock, IndexBlock, IndexAlwaysFields, Index, INSTANCE_TOKEN_ENV, INDEX_MAX_PAGE_SIZE, FtTransfersWalkParams, FtTransfersResource, FtTransfersListParams, FtTransfersEnvelope, FtTransferPayload2 as FtTransferPayload, FtTransferEvent, FtTransfer, FetchLike2 as FetchLike, EventsWalkParams, EventsListParams, EventsEnvelope, EventsConsumeParams, DeliveryRow2 as DeliveryRow, DecodedStxTransferPayload, DecodedStxTransfer, DecodedStxMintPayload, DecodedStxMint, DecodedStxLockPayload, DecodedStxLock, DecodedStxBurnPayload, DecodedStxBurn, DecodedPrintValue, DecodedPrintPayload, DecodedPrint, DecodedNftTransferPayload, DecodedNftTransfer, DecodedNftMintPayload, DecodedNftMint, DecodedNftBurnPayload, DecodedNftBurn, DecodedFtTransferPayload, DecodedFtTransfer, DecodedFtMintPayload, DecodedFtMint, DecodedFtBurnPayload, DecodedFtBurn, DecodedEventRow, DecodedEventColumns, DeadRow2 as DeadRow, DEFAULT_REQUEST_TIMEOUT_MS, Cursor, CreateWebhookResponse2 as CreateWebhookResponse, CreateWebhookRequest2 as CreateWebhookRequest, CreateArchiveClientOptions, ContractsListParams, ContractsEnvelope, Contracts, ContractSummary, ContractConformance, ContractCallsWalkParams, ContractCallsListParams, ContractCallsEnvelope, ContractCallsConsumeParams, ContextSnapshot, ContextFieldError, ContextField, ContextAccount, ConsumerSink, ConsumerHealth, ConsumerBatchContext, ChainWebhookEnvelope, ChainWebhookDelivery2 as ChainWebhookDelivery, ChainTxLevelEvent, ChainTriggerType, ChainTrigger, ChainTestDelivery, ChainStxTransferData, ChainStxMintData, ChainStxLockData, ChainStxBurnData, ChainReorgRollbackEnvelope, ChainReorgRollbackDelivery, ChainReorgOrphanedEntry, ChainPrintEventData, ChainNftTransferData, ChainNftMintData, ChainNftBurnData, ChainFtTransferData, ChainFtMintData, ChainFtBurnData, ChainEventEnvelope, ChainApplyEnvelopeOf, ChainApplyEnvelope, ChainApplyDeliveryOf, CanonicalWalkParams, CanonicalListParams, CanonicalEnvelope, BlocksWalkParams, BlocksListParams, BlocksEnvelope, BlockEnvelope, AuthError, ArchiveVerifyResult, ArchiveVerifyRangeStatus, ArchiveVerifyInput, ArchiveStatus, ArchiveSignatureError, ArchiveQuote, ArchivePartition, ArchiveManifest, ArchiveLoadOptions, ArchiveGateNotConfiguredError, ArchiveFlow, ArchiveFetchResult, ArchiveFetchItem, ArchiveDataset, ArchiveCreditsBalance, ArchiveClient, ArchiveAuthError, ApiError, ActiveSubgraphOperation, ACCOUNT_KEY_ENV };
3218
+ export { verifyWebhookSignature, verifyTransactionProof, verify as verifyStandardWebhooksHeaders, verifySecondlayerSignature, trigger, toJsonSafe, shutdownSignal, resolveBaseUrl, resolveApiKey, resolveAccountKey, parseRetryAfter, isStxTransfer, isStxMint, isStxLock, isStxBurn, isPrint, isNftTransfer, isNftMint, isNftBurn, isFtTransfer, isFtMint, isFtBurn, getSubgraph, fetchRewardSet, decodeStxTransfer, decodeStxMint, decodeStxLock, decodeStxBurn, decodePrint, decodeNftTransfer, decodeNftMint, decodeNftBurn, decodeFtTransfer, decodeFtMint, decodeFtBurn, decodeClarityValue, decodeChainWebhook, decode, createStreamsClient, createArchiveClient, contextField, consumerHealth, consumeIndexFeed, WithSinkTx, Webhooks, WebhookTestResult2 as WebhookTestResult, WebhookSummary2 as WebhookSummary, WebhookStatus, WebhookRuntime, WebhookKind, WebhookHeaderInput, WebhookFormat, WebhookDetail2 as WebhookDetail, WalkOptions, VmStreamsEvent, ValidationError, UpdateWebhookRequest2 as UpdateWebhookRequest, TransactionsWalkParams, TransactionsListParams, TransactionsEnvelope, TransactionProofVerifyResult, TransactionProof, TransactionEnvelope, Subgraphs, SubgraphSpecOptions3 as SubgraphSpecOptions, SubgraphSpecFormat2 as SubgraphSpecFormat, SubgraphOperationStatus, SubgraphAgentSchema3 as SubgraphAgentSchema, StreamsWireEvent2 as StreamsWireEvent, StreamsTip, StreamsSubscription, StreamsSignatureError, StreamsServerError, StreamsReorgsListParams, StreamsReorgsListEnvelope, StreamsReorgContext, StreamsReorg, StreamsEventsSubscribeParams, StreamsEventsStreamParams, StreamsEventsListParams, StreamsEventsListEnvelope, StreamsEventsEnvelope, StreamsEventsConsumeResult, StreamsEventsConsumeParams, StreamsEventType, StreamsEventPayload, StreamsEvent, StreamsDumpsManifest, StreamsDumps, StreamsDumpFile, StreamsConsumeParams, StreamsClient, StreamsCanonicalBlock, StreamsBatchContext, StreamsBatch, StandardWebhooksHeaders2 as StandardWebhooksHeaders, StackingWalkParams, StackingListParams, StackingEnvelope, SinkTx, SecondLayerOptions, SecondLayerErrorOptions, SecondLayerError, SecondLayerArchive, SecondLayer, SbtcWithdrawalsWalkParams, SbtcWithdrawalsListParams, SbtcWithdrawalsEnvelope, SbtcWithdrawalSweptConfirmedEvent, SbtcWithdrawalStatus, SbtcWithdrawalEvent, SbtcWithdrawalEnvelope, SbtcSummaryEnvelope, SbtcResource, SbtcEventsWalkParams, SbtcEventsListParams, SbtcEventsEnvelope, SbtcEventsConsumeParams, SbtcEventTopic2 as SbtcEventTopic, SbtcDepositsWalkParams, SbtcDepositsListParams, SbtcDepositsEnvelope, SbtcDepositsConsumeParams, SbtcDepositEvent, SbtcDepositEnvelope, RotateSecretResponse2 as RotateSecretResponse, RewardSet2 as RewardSet, RequestOptions, ReplayResult2 as ReplayResult, RateLimitError, PublicStatus2 as PublicStatus, PrintSchemaResponse, PoxResource, PoxCyclesWalkParams, PoxCyclesListParams, PoxCyclesEnvelope, PoxCycleEnvelope, Pox5Resource, Pox5EventsWalkParams, Pox5EventsListParams, Pox5EventsEnvelope, NftTransfersWalkParams, NftTransfersResource, NftTransfersListParams, NftTransfersEnvelope, NftTransferPayload2 as NftTransferPayload, NftTransferEvent, NftTransfer, MempoolWalkParams, MempoolTransactionEnvelope, MempoolListParams, MempoolEnvelope, MemoryEtagCache, LoadedArchive, LOCAL_API_URL, InsufficientArchiveCreditsError, InstanceStatus, InstanceState, InstanceIssue, InstanceDiagnosis3 as InstanceDiagnosis, InstanceClient, IndexVarSet, IndexTransaction, IndexTip, IndexStxTransfer, IndexStxMint, IndexStxLock, IndexStxBurn, IndexStackingAction, IndexSbtcWithdrawalPhase, IndexSbtcWithdrawalDetail, IndexSbtcWithdrawal, IndexSbtcSummary, IndexSbtcEvent, IndexSbtcDepositDetail, IndexSbtcDeposit, IndexReorg, IndexPrint, IndexPoxFunctionCount, IndexPoxCycle, IndexPox5EventTopic, IndexPox5Event, IndexPostCondition, IndexNftTransfer, IndexNftMint, IndexNftBurn, IndexNestedContractCall, IndexMempoolTransaction, IndexMapSet, IndexMapInsert, IndexMapDelete, IndexFtTransfer, IndexFtMint, IndexFtBurn, IndexFeedItem, IndexFeedFetcher, IndexFeedEnvelope, IndexEventsResource, IndexEventTypeFilters, IndexEventType, IndexEventOf, IndexEventFields, IndexEvent, IndexDiscovery, IndexContractCall, IndexConsumeOptions, IndexCanonicalBlock, IndexBlock, IndexAlwaysFields, Index, INSTANCE_TOKEN_ENV, INDEX_MAX_PAGE_SIZE, FtTransfersWalkParams, FtTransfersResource, FtTransfersListParams, FtTransfersEnvelope, FtTransferPayload2 as FtTransferPayload, FtTransferEvent, FtTransfer, FetchLike2 as FetchLike, EventsWalkParams, EventsListParams, EventsEnvelope, EventsConsumeParams, EtagEntry, EtagCache, DeliveryRow2 as DeliveryRow, DecodedStxTransferPayload, DecodedStxTransfer, DecodedStxMintPayload, DecodedStxMint, DecodedStxLockPayload, DecodedStxLock, DecodedStxBurnPayload, DecodedStxBurn, DecodedPrintValue, DecodedPrintPayload, DecodedPrint, DecodedNftTransferPayload, DecodedNftTransfer, DecodedNftMintPayload, DecodedNftMint, DecodedNftBurnPayload, DecodedNftBurn, DecodedFtTransferPayload, DecodedFtTransfer, DecodedFtMintPayload, DecodedFtMint, DecodedFtBurnPayload, DecodedFtBurn, DecodedEventRow, DecodedEventColumns, DeadRow2 as DeadRow, DEFAULT_REQUEST_TIMEOUT_MS, Cursor, CreateWebhookResponse2 as CreateWebhookResponse, CreateWebhookRequest2 as CreateWebhookRequest, CreateArchiveClientOptions, ContractsListParams, ContractsEnvelope, Contracts, ContractSummary, ContractConformance, ContractCallsWalkParams, ContractCallsListParams, ContractCallsEnvelope, ContractCallsConsumeParams, ContextSnapshot, ContextFieldError, ContextField, ContextAccount, ConsumerSink, ConsumerHealth, ConsumerBatchContext, ChainWebhookEnvelope, ChainWebhookDelivery2 as ChainWebhookDelivery, ChainTxLevelEvent, ChainTriggerType, ChainTrigger, ChainTestDelivery, ChainStxTransferData, ChainStxMintData, ChainStxLockData, ChainStxBurnData, ChainReorgRollbackEnvelope, ChainReorgRollbackDelivery, ChainReorgOrphanedEntry, ChainPrintEventData, ChainNftTransferData, ChainNftMintData, ChainNftBurnData, ChainFtTransferData, ChainFtMintData, ChainFtBurnData, ChainEventEnvelope, ChainApplyEnvelopeOf, ChainApplyEnvelope, ChainApplyDeliveryOf, CanonicalWalkParams, CanonicalListParams, CanonicalEnvelope, BlocksWalkParams, BlocksListParams, BlocksEnvelope, BlockEnvelope, AuthError, ArchiveVerifyResult, ArchiveVerifyRangeStatus, ArchiveVerifyInput, ArchiveStatus, ArchiveSignatureError, ArchiveQuote, ArchivePartition, ArchiveManifest, ArchiveLoadOptions, ArchiveGateNotConfiguredError, ArchiveFlow, ArchiveFetchResult, ArchiveFetchItem, ArchiveDataset, ArchiveCreditsBalance, ArchiveClient, ArchiveAuthError, ApiError, ActiveSubgraphOperation, ACCOUNT_KEY_ENV };
package/dist/index.js CHANGED
@@ -156,6 +156,30 @@ function parseRetryAfter(value) {
156
156
  }
157
157
 
158
158
  // src/base.ts
159
+ class MemoryEtagCache {
160
+ limit;
161
+ entries = new Map;
162
+ constructor(limit = 64) {
163
+ this.limit = limit;
164
+ }
165
+ get(key) {
166
+ const entry = this.entries.get(key);
167
+ if (entry) {
168
+ this.entries.delete(key);
169
+ this.entries.set(key, entry);
170
+ }
171
+ return entry;
172
+ }
173
+ set(key, entry) {
174
+ this.entries.delete(key);
175
+ this.entries.set(key, entry);
176
+ if (this.entries.size > this.limit) {
177
+ const oldest = this.entries.keys().next().value;
178
+ if (oldest !== undefined)
179
+ this.entries.delete(oldest);
180
+ }
181
+ }
182
+ }
159
183
  var DEFAULT_REQUEST_TIMEOUT_MS = 30000;
160
184
  function abortError() {
161
185
  return new DOMException("This operation was aborted", "AbortError");
@@ -266,12 +290,14 @@ class BaseClient {
266
290
  origin;
267
291
  fetchImpl;
268
292
  requestTimeoutMs;
293
+ etagCache;
269
294
  constructor(options = {}) {
270
295
  this.baseUrl = resolveBaseUrl(options.baseUrl);
271
296
  this.apiKey = resolveApiKey(options.apiKey);
272
297
  this.origin = options.origin ?? "cli";
273
298
  this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
274
299
  this.fetchImpl = options.fetchImpl ?? ((...args) => fetch(...args));
300
+ this.etagCache = options.etagCache === false ? null : options.etagCache ?? new MemoryEtagCache;
275
301
  }
276
302
  static authHeaders(apiKey) {
277
303
  const headers = {
@@ -284,11 +310,25 @@ class BaseClient {
284
310
  }
285
311
  async request(method, path, body, opts = {}) {
286
312
  return this.withRequestBudget(opts.signal, async (signal) => {
287
- const response = await this.fetchResponse(method, path, body, signal);
313
+ const cacheKey = method === "GET" && this.etagCache ? `${this.baseUrl}${path}` : null;
314
+ const cached = cacheKey ? await this.etagCache?.get(cacheKey) : undefined;
315
+ const response = await this.fetchResponse(method, path, body, signal, cached ? { "If-None-Match": cached.etag } : undefined);
288
316
  if (response.status === 204) {
289
317
  return;
290
318
  }
291
- return await raceAbort(response.json(), signal);
319
+ if (response.status === 304) {
320
+ if (!cached) {
321
+ throw new ApiError(304, "Not Modified without a cached copy");
322
+ }
323
+ return JSON.parse(cached.body);
324
+ }
325
+ const etag = cacheKey ? response.headers.get("ETag") : null;
326
+ if (!cacheKey || !etag) {
327
+ return await raceAbort(response.json(), signal);
328
+ }
329
+ const text = await raceAbort(response.text(), signal);
330
+ await this.etagCache?.set(cacheKey, { etag, body: text });
331
+ return JSON.parse(text);
292
332
  });
293
333
  }
294
334
  async requestOrNull(method, path, body, opts = {}) {
@@ -331,9 +371,12 @@ class BaseClient {
331
371
  callerSignal?.removeEventListener("abort", forward);
332
372
  }
333
373
  }
334
- async fetchResponse(method, path, body, signal) {
374
+ async fetchResponse(method, path, body, signal, extraHeaders) {
335
375
  const url = `${this.baseUrl}${path}`;
336
- const headers = BaseClient.authHeaders(this.apiKey);
376
+ const headers = {
377
+ ...BaseClient.authHeaders(this.apiKey),
378
+ ...extraHeaders
379
+ };
337
380
  headers["x-sl-origin"] = this.origin;
338
381
  let serializedBody;
339
382
  if (body !== undefined && body !== null) {
@@ -358,6 +401,8 @@ class BaseClient {
358
401
  throw err;
359
402
  throw new ApiError(0, `Cannot reach API at ${this.baseUrl}. Check your connection or try again.`, undefined, undefined, { retryable: true, cause: err instanceof Error ? err : undefined });
360
403
  }
404
+ if (response.status === 304)
405
+ return response;
361
406
  if (!response.ok) {
362
407
  const errorBody = signal ? await raceAbort(response.text(), signal) : await response.text();
363
408
  const envelope = parseErrorEnvelope(errorBody);
@@ -1806,6 +1851,11 @@ class Index extends BaseClient {
1806
1851
  asset_identifier: params.assetIdentifier,
1807
1852
  sender: params.sender,
1808
1853
  recipient: params.recipient,
1854
+ function_name: params.functionName,
1855
+ caller: params.caller,
1856
+ map: params.map,
1857
+ var_name: params.varName,
1858
+ tx_id: params.txId,
1809
1859
  trait: params.trait,
1810
1860
  tx_context: params.txContext ? "true" : undefined
1811
1861
  })}`, undefined, { signal: params.signal });
@@ -2318,6 +2368,7 @@ function createStreamsClient(options) {
2318
2368
  asset_identifier: params.assetIdentifier,
2319
2369
  types: params.types,
2320
2370
  not_types: params.notTypes,
2371
+ clock: params.clock === "vm" ? "vm" : undefined,
2321
2372
  filters: encodeFilters(params.filters)
2322
2373
  })}`);
2323
2374
  }
@@ -2912,6 +2963,7 @@ export {
2912
2963
  SecondLayerError,
2913
2964
  SecondLayer,
2914
2965
  RateLimitError,
2966
+ MemoryEtagCache,
2915
2967
  LOCAL_API_URL,
2916
2968
  InsufficientArchiveCreditsError,
2917
2969
  Index,
@@ -2928,5 +2980,5 @@ export {
2928
2980
  ACCOUNT_KEY_ENV
2929
2981
  };
2930
2982
 
2931
- //# debugId=139DE2F111FF826D64756E2164756E21
2983
+ //# debugId=0B87C7F2FE748A2E64756E2164756E21
2932
2984
  //# sourceMappingURL=index.js.map