stitchkit 0.123.1 → 0.123.3
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/CHANGELOG.md +35 -0
- package/dist/browser/client-bound.d.ts +19 -0
- package/dist/browser/client-bound.d.ts.map +1 -0
- package/dist/browser/client-url.d.ts +2 -0
- package/dist/browser/client-url.d.ts.map +1 -1
- package/dist/browser/client.d.ts +20 -10
- package/dist/browser/client.d.ts.map +1 -1
- package/dist/contract/client-types.d.ts +13 -8
- package/dist/contract/client-types.d.ts.map +1 -1
- package/dist/entrypoints/http.js +1 -1
- package/dist/entrypoints/index.js +1 -1
- package/dist/entrypoints/remote.js +1 -1
- package/dist/entrypoints/server.js +3 -3
- package/dist/entrypoints/telegram/voice.d.ts +2 -0
- package/dist/entrypoints/telegram/voice.d.ts.map +1 -0
- package/dist/entrypoints/telegram/voice.js +18 -0
- package/dist/entrypoints/telegram.d.ts +1 -0
- package/dist/entrypoints/telegram.d.ts.map +1 -1
- package/dist/entrypoints/telegram.js +43 -0
- package/dist/entrypoints/testing.js +1 -1
- package/dist/entrypoints/tracking/performance.js +3 -3
- package/dist/index-0jdempdr.js +69 -0
- package/dist/{index-mdyhr36s.js → index-zbzagr9k.js} +127 -61
- package/dist/telegram/voice-waveform-pcm.d.ts +21 -0
- package/dist/telegram/voice-waveform-pcm.d.ts.map +1 -0
- package/dist/telegram/voice-waveform.d.ts +67 -0
- package/dist/telegram/voice-waveform.d.ts.map +1 -0
- package/llms/stitchkit.2.txt +36 -174
- package/llms/stitchkit.3.txt +186 -0
- package/llms/stitchkit.txt +6 -3
- package/llms/telegram-voice.txt +29 -0
- package/llms/telegram.2.txt +71 -0
- package/llms/telegram.txt +51 -59
- package/llms-full.txt +101 -2
- package/llms.txt +4 -3
- package/package.json +5 -1
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
# stitchkit — stitchkit docs slice, part 3 of 3
|
|
2
|
+
|
|
3
|
+
> Generated from the `docs/` tree by `bun run gen:llms`. The index of all slices is
|
|
4
|
+
> `llms.txt` in this package.
|
|
5
|
+
|
|
6
|
+
Parts of this slice:
|
|
7
|
+
- `llms/stitchkit.txt`: Guide: Getting started (docs/guide/getting-started.md) · Guide: Typed client (docs/guide/client.md)
|
|
8
|
+
- `llms/stitchkit.2.txt`: Guide: Typed client (docs/guide/client.md)
|
|
9
|
+
- `llms/stitchkit.3.txt`: API reference: `stitchkit` (docs/api/reference.md)
|
|
10
|
+
|
|
11
|
+
Also read:
|
|
12
|
+
- see `llms/contract.txt` for the Contracts guide
|
|
13
|
+
- see `llms/server.txt` for the Realtime guide
|
|
14
|
+
- see `llms/server.txt` for the Auth & errors guide
|
|
15
|
+
|
|
16
|
+
==============================================================================
|
|
17
|
+
# API reference: `stitchkit` (docs/api/reference.md)
|
|
18
|
+
==============================================================================
|
|
19
|
+
|
|
20
|
+
## `stitchkit`
|
|
21
|
+
|
|
22
|
+
The browser-and-server entrypoint. Re-exports everything from
|
|
23
|
+
[`stitchkit/contract`](#stitchkitcontract), plus the client and browser realtime.
|
|
24
|
+
|
|
25
|
+
### Client
|
|
26
|
+
|
|
27
|
+
| Export | Kind | Summary |
|
|
28
|
+
|--------|------|---------|
|
|
29
|
+
| `createClient` | function | build a typed client from a contract — [guide](../guide/client.md#createclient) |
|
|
30
|
+
| `createClients` | function | build one exact typed client per contract from a registry; accepts the same scoped config and transports as `createClient` |
|
|
31
|
+
| `createScopedClients` | function | build one registry routed by contract scope; arrays compose contracts into one namespace |
|
|
32
|
+
| `createScopedUrlBuilders` | function | build one URL registry routed by contract scope; arrays compose contracts into one namespace |
|
|
33
|
+
| `ScopeClientConfigs` | _type_ | per-scope routing configuration consumed by scoped clients and URL builders |
|
|
34
|
+
| `ScopedClientRegistry` | _type_ | exact composed registry returned by `createScopedClients` |
|
|
35
|
+
| `ScopedUrlBuilderRegistry` | _type_ | exact composed registry returned by `createScopedUrlBuilders` |
|
|
36
|
+
| `ClientRegistryValue` | _type_ | one contract or a contract array composing one client namespace |
|
|
37
|
+
| `ClientContract` | _type_ | HTTP-client-compatible contract value used by scoped registries |
|
|
38
|
+
| `RegistryScope` | _type_ | contract-scope union inferred from a scoped client registry value |
|
|
39
|
+
| `createUrlBuilder` | function | build synchronous browser-native URLs for all HTTP endpoints; body methods accept URL-bound args only — [guide](../guide/client.md#contract-url-builders) |
|
|
40
|
+
| `createUrlBuilders` | function | build one exact URL builder per contract in a registry |
|
|
41
|
+
| `readContractIdentity` | function | read the server's contract fingerprint in one call and return it beside the client's own — [guide](../guide/client.md#which-contract-does-the-server-speak) |
|
|
42
|
+
| `ContractIdentity` | _type_ | `{ client, server }` fingerprints; `server` is `undefined` when the server answers no identity |
|
|
43
|
+
| `UrlBuilderConfig` | _type_ | explicit `{ baseUrl }` source for a URL builder |
|
|
44
|
+
| `ClientConfig` | _type_ | config for `createClient`'s bare-fetch mode (2nd arg, no `HttpClient`) |
|
|
45
|
+
| `ClientFetch` | _type_ | injectable Fetch-compatible transport used by framework and application-owned adapters |
|
|
46
|
+
| `ClientRequestOptions` | _type_ | per-call `{ signal?, onUploadProgress? }` passed through an endpoint callable's `.withOptions(...)`; caller abort is distinct from timeout — [guide](../guide/client.md#per-call-cancellation) |
|
|
47
|
+
| `UploadProgress` | _type_ | `{ sentBytes, totalBytes, attempt }` heard by `onUploadProgress`: bytes of the encoded body handed to the network, first `0`, last `totalBytes`, counted again on each transport retry — [guide](../guide/client.md#upload-progress) |
|
|
48
|
+
| `uploadInChunks` | function | send a file larger than one request as `init` → parts → `finalize` through three calls the app owns; client-minted id, repeats of a part on a failure that may pass, `finalize` never repeated, cancel checked between parts, progress in file bytes — [guide](../guide/client.md#chunked-uploads) |
|
|
49
|
+
| `ChunkedUploadConfig` / `ChunkedUploadStart` / `ChunkedUploadPart` / `ChunkedUploadProgress` | _type_ | the driver's file, part size, retries and three calls; what `init` declares; one part; progress `{ sentBytes, totalBytes, index, chunkCount, attempt }` |
|
|
50
|
+
| `ChunkSource` | _type_ | what the driver reads a file through — `size` and `slice(start, end)`; a `Blob` is one, so is a platform file that is not (an Expo `File`), and a part's `bytes` is what its `slice` returns |
|
|
51
|
+
| `ContractClientConfig` | _type_ | per-tenant / resource-scoped client config — dynamic `pathPrefix` + `stripPrefixKeys`, and `bound` arguments given once for every call ([guide](../guide/client.md#contractclientconfig--per-tenant--resource-scoped-clients)) |
|
|
52
|
+
| `contractEndpointMatchers` | function | compile exact pathname matchers for selected HTTP contract operations and expected-401 policy |
|
|
53
|
+
| `PathPrefixArgs` | _type_ | required string-valued keys exposed to a typed dynamic `pathPrefix` callback |
|
|
54
|
+
| `createHttpClient` | function | the Ky-based HTTP transport; on Next.js SSR its first attempt stays request-memoizable while every retry is a distinct transport attempt — [guide](../guide/client.md#createhttpclient) |
|
|
55
|
+
| `ApiError` | class | a non-2xx or client failure, with `code` / `status` / `details` / `hint`, optional readonly `traceId` from `x-request-id`, and standard `cause` preserving an injected transport failure |
|
|
56
|
+
| `zodIssues` | function | a `ZodError` → structured `{ path, code, message }[]` — the exact projection a `VALIDATION_ERROR` carries in `ApiError.details.issues`, so a caller renders one shape. Also on `stitchkit/server`; same name, one definition |
|
|
57
|
+
| `ZodIssueSummary` | _type_ | one structured validation issue (`{ path, code, message }`) — the element type of `details.issues`. Also on `stitchkit/server` |
|
|
58
|
+
| `formatZodError` | function | a `ZodError` → a readable, field-summarised string. Also on `stitchkit/server` |
|
|
59
|
+
| `HttpClient` | _type_ | the transport interface `createClient` builds on |
|
|
60
|
+
| `ConfiguredHttpClient` | _type_ | a framework-created `HttpClient` carrying its readonly `baseUrl` for URL builders |
|
|
61
|
+
| `HttpClientConfig` | _type_ | config for `createHttpClient`; retry `limit` counts retries after the initial attempt (default 2 = at most 3 GET attempts), with `statusCodes: []` by default; `fetch` installs an explicit transport and is mutually exclusive with the legacy Bun-only `unix` option — [details](../guide/client.md#createhttpclient) |
|
|
62
|
+
| `UnauthorizedMatcher` | _type_ | exact `(pathname) => boolean` policy accepted by `suppressUnauthorizedFor` |
|
|
63
|
+
| `RequestOptions` | _type_ | per-call options — params, timeout, response type, `onUploadProgress` |
|
|
64
|
+
| `HeaderProvider` | _type_ | static or per-request headers |
|
|
65
|
+
| `ApiEvent` | _type_ | a client event — `unauthorized` / `network_error` / `logout` |
|
|
66
|
+
| `ApiEventListener` | _type_ | an `ApiEvent` handler |
|
|
67
|
+
|
|
68
|
+
### Realtime (client) & streaming
|
|
69
|
+
|
|
70
|
+
| Export | Kind | Summary |
|
|
71
|
+
|--------|------|---------|
|
|
72
|
+
| `createSocketIOClient` | function | low-level typed Socket.IO transport primitive — [guide](../guide/realtime.md#low-level-transport) |
|
|
73
|
+
| `defineRealtimeContract` | function | Zod-first shared Socket.IO event contract — [guide](../guide/realtime.md#zod-first-event-contract) |
|
|
74
|
+
| `createRealtimeClient` | function | inferred, runtime-validated Socket.IO client — [guide](../guide/realtime.md#client--createrealtimeclient) |
|
|
75
|
+
| `bindRealtimeClient` | function | bind contract validation and typed acknowledgements to an existing Stitchkit client transport without owning its lifecycle |
|
|
76
|
+
| `createLiveStateController` | function | keep typed application state current across one source-owned snapshot/event generation with finite pre-snapshot buffering, generation fencing and explicit resync — [guide](../guide/realtime.md#snapshot--event-state-synchronization) |
|
|
77
|
+
| `LiveStateController` | _type_ | renderer-neutral `start` / `resync` / `getSnapshot` / `subscribe` / `close` handle |
|
|
78
|
+
| `LiveStateControllerConfig` | _type_ | typed source, reducer, explicit event/byte bounds, event sizing and isolated error hooks |
|
|
79
|
+
| `LiveStateControllerSnapshot` / `LiveStateControllerStatus` | _types_ | current value plus phase, generation, buffer and application/duplicate/gap/refusal counters |
|
|
80
|
+
| `LiveStateControllerStatusSchema` | schema | strict runtime validation for controller status metadata |
|
|
81
|
+
| `LiveStatePhaseSchema` / `LiveStatePhase` | schema / _type_ | `idle`, `opening`, `live`, `resync-required`, `unavailable` or `closed` |
|
|
82
|
+
| `LiveStateStopReasonSchema` / `LiveStateStopReason` | schema / _type_ | explicit gap, overflow, source loss, controller failure and bounded `controller-capacity` reasons |
|
|
83
|
+
| `LiveStateEventDecision` | _type_ | provider-owned reducer result: applied state, duplicate or gap |
|
|
84
|
+
| `LiveStateSource` / `LiveStateSourceOpenInput` / `LiveStateSourceOpenResult` | _types_ | host binding for one continuous snapshot/event boundary; transport retry and cursor semantics remain host-owned |
|
|
85
|
+
| `LiveStateControllerError` / `LiveStateSubscriberError` | _types_ | isolated observer failure payloads that do not change source or subscriber truth |
|
|
86
|
+
| `createRetainedTopics` | function | retained last-value store for sticky events — [guide](../guide/realtime.md#sticky-events) |
|
|
87
|
+
| `parseSSE` | function | parse SSE from a `Response`, a web stream or an async byte iterable into an async generator — [guide](../guide/client.md#sse) |
|
|
88
|
+
| `parseNDJSON` | function | parse bounded fatal-UTF-8 NDJSON from a `Response`, a `ReadableStream<Uint8Array>` or an `AsyncIterable<Uint8Array>` (a child's stdout); blank keep-alives are skipped, `finalLine: 'require-newline'` makes the delimiter mandatory and `signal` cancels the source — [guide](../guide/client.md#any-byte-source) |
|
|
89
|
+
| `createNDJSONDecoder` / `NDJSONDecoder` | function / _type_ | the same bounded NDJSON reading driven by `push(chunk)` / `end()`, for a socket `data` callback |
|
|
90
|
+
| `readBoundedBody` / `BoundedBodyOptions` | function / _type_ | the whole body of a `ReadableStream<Uint8Array>` or async byte iterable as bytes, never reading past `maxBytes` plus one chunk; `limitError(observedBytes)` and `abortError(reason)` choose the two errors, the source is cancelled on both, a `null` body is empty — [guide](../guide/client.md#reading-a-body-up-to-a-byte-limit) |
|
|
91
|
+
| `StreamByteSource` | _type_ | `Response \| ReadableStream<Uint8Array> \| AsyncIterable<Uint8Array>`, what the NDJSON and SSE readers accept |
|
|
92
|
+
| `StreamLineLimitError` / `StreamTruncatedLineError` | class | a line past `maxLineBytes` (`limitBytes`, `lineBytes`; a `RangeError`) and a source ended inside a line under `require-newline` (`lineBytes`; a `SyntaxError`) |
|
|
93
|
+
| `resumableIterator` | function | re-open a long-lived stream from the last delivered cursor, with jittered backoff, a caller-owned terminal item and prompt abort — [guide](../guide/client.md#resumable-streams) |
|
|
94
|
+
| `createBackoff` | function | exponential backoff with subtractive jitter as a value: `next()` / `reset()` |
|
|
95
|
+
| `contractFingerprint` | function | synchronous digest of the operations HTTP carries, whole and per `prefix.key` — [guide](../guide/client.md#which-contract-does-the-server-speak) |
|
|
96
|
+
| `ContractFingerprintSchema` / `ContractFingerprint` | schema / _type_ | `{ fingerprint, operations }` — one digest for the set and one per operation |
|
|
97
|
+
| `contractIdentityContract` | contract | the operation a server answers its fingerprint with; mount it with `withContractIdentity` |
|
|
98
|
+
| `ContractStreamFrameSchema` / `ContractStreamFrame` | schema / _type_ | default on-the-wire `data` / safe `error` / `end` envelope of a contract-first stream |
|
|
99
|
+
| `ContractStreamFraming` / `ContractStreamCompletion` | _types_ | opt-in item-vs-envelope framing and terminal-vs-stream-end completion policies |
|
|
100
|
+
| `StreamFinalLinePolicy` | _type_ | permissive or newline-required final NDJSON line policy |
|
|
101
|
+
| `DEFAULT_CONTRACT_STREAM_FRAME_BYTES` | const | default maximum encoded contract-stream frame: 256 KiB |
|
|
102
|
+
| `SocketIOClient` | _type_ | low-level client handle; `emit` reports disconnected drops and `emitWithAck` exposes the native Promise primitive used by validated `request()` |
|
|
103
|
+
| `SocketIOClientPeerLoaders` | _type_ | inject `socket.io-client` so a bundler can put it in a self-contained artifact |
|
|
104
|
+
| `SocketIOClientConfig` | _type_ | config for `createSocketIOClient` (incl. `retain`, `onConnectError`, `onDroppedEmit`) |
|
|
105
|
+
| `SocketEventMap` | _type_ | the shape of an event map |
|
|
106
|
+
| `RealtimeClient` | _type_ | validated client inferred from a realtime contract |
|
|
107
|
+
| `RealtimeClientOptions` | _type_ | transport options plus rejected-event and metadata-only acknowledged-request phase hooks for `createRealtimeClient` |
|
|
108
|
+
| `BoundRealtimeClient` | _type_ | validated non-owning `on`/`emit`/`request` client with no `connect`/`disconnect` |
|
|
109
|
+
| `RealtimeClientTransport` | _type_ | minimal existing transport capability accepted by `bindRealtimeClient` |
|
|
110
|
+
| `BindRealtimeClientOptions` | _type_ | rejection/logger options for a bound existing transport |
|
|
111
|
+
| `RealtimeAcknowledgedEvent` | _type_ | event-name union restricted to definitions with an `ack` schema |
|
|
112
|
+
| `RealtimeAcknowledgement` | _type_ | validated acknowledgement output inferred from an event definition |
|
|
113
|
+
| `RealtimeRequestArguments` | _type_ | request arguments inferred from an acknowledged event tuple |
|
|
114
|
+
| `RealtimeRequestOptions` | _type_ | finite positive native acknowledgement `timeoutMs` plus an optional invocation-scoped `onPhase` observer |
|
|
115
|
+
| `RealtimeRequestPhaseSchema` / `RealtimeRequestPhase` | schema / _type_ | closed `engine-handoff` / `engine-ack-received` / `settled` / `timeout` / `disconnected` lifecycle |
|
|
116
|
+
| `RealtimeRequestPhaseEventSchema` / `RealtimeRequestPhaseEvent` | schema / _type_ | strict metadata-only `{ requestId, event, phase, elapsedMs }` observation |
|
|
117
|
+
| `RealtimeRequestPhaseHook` | _type_ | isolated sync/async observer accepted globally by `RealtimeClientOptions.onRequestPhase` or per invocation by `RealtimeRequestOptions.onPhase` |
|
|
118
|
+
| `RealtimeRequestTimeoutError` | class | stable `REALTIME_REQUEST_TIMEOUT` rejection |
|
|
119
|
+
| `RealtimeRequestDisconnectedError` | class | stable `REALTIME_REQUEST_DISCONNECTED` rejection, including an immediate disconnected call |
|
|
120
|
+
| `RealtimeRequestInvalidAcknowledgementError` | class | invalid ack was reported through `onRejected` and the request rejected |
|
|
121
|
+
| `RealtimeRequestRejectedError` | class | the peer refused the frame against its own contract and said so — `reason`, `issues` — instead of leaving the sender to time out ([ADR 0106](../decisions/0106-a-refused-frame-answers-its-sender.md)) |
|
|
122
|
+
| `REALTIME_REJECTION_KEY` | const | the reserved acknowledgement key a refusal travels under |
|
|
123
|
+
| `RealtimeRejectionEnvelope` | _type_ | the wire shape of a refusal |
|
|
124
|
+
| `RealtimeRejectionReport` | _type_ | what the sender is told: event, reason, message, issues |
|
|
125
|
+
| `RealtimeRejectionIssue` | _type_ | one refused field, already flattened (`path: '0.v'`) |
|
|
126
|
+
| `asRealtimeRejection` | function | recognise a refusal in an acknowledgement value, validating it |
|
|
127
|
+
| `RealtimeContract` | _type_ | shared server-to-client and client-to-server event registries |
|
|
128
|
+
| `RealtimeEventRegistry` | _type_ | string-keyed registry of event definitions |
|
|
129
|
+
| `RealtimeEventDefinition` | _type_ | one tuple-shaped event and optional acknowledgement schema |
|
|
130
|
+
| `RealtimeEventArguments` | _type_ | tuple inferred from an event definition |
|
|
131
|
+
| `RealtimeEmitArguments` | _type_ | emit arguments including an inferred acknowledgement callback |
|
|
132
|
+
| `RealtimeEventHandler` | _type_ | handler inferred from an event definition |
|
|
133
|
+
| `InferRealtimeEventMap` | _type_ | inferred Socket.IO-compatible event map |
|
|
134
|
+
| `RealtimeRejectDirection` / `RealtimeRejectPhase` / `RealtimeRejectReason` / `RealtimeRejectFault` | _types_ | canonical inferred rejection direction, validation phase, reason and fault classification |
|
|
135
|
+
| `RealtimeRejectedEvent` | _type_ | structured rejected event with event, direction, phase, reason and fault |
|
|
136
|
+
| `RealtimeRejectedEventHook` | _type_ | sync/async observer for structured realtime rejections |
|
|
137
|
+
| `ValidatedRealtimeSocket` | _type_ | runtime-validating `on`/`emit` surface inferred from registries; `emit` returns "accepted by the transport" (`false` only for a client-side disconnected drop) |
|
|
138
|
+
| `RetainedTopics` | _type_ | the `createRetainedTopics` handle |
|
|
139
|
+
| `ParseSSEOptions` | _type_ | options for `parseSSE` |
|
|
140
|
+
| `ParseNDJSONOptions` | _type_ | options for `parseNDJSON` |
|
|
141
|
+
| `BackoffPolicySchema` / `BackoffPolicy` | schema / _type_ | `minDelayMs`, `maxDelayMs` and a `0`–`1` jitter fraction; a ceiling below the floor is refused |
|
|
142
|
+
| `Backoff` | _type_ | the backoff handle returned by `createBackoff` |
|
|
143
|
+
| `ResumableIteratorConfig` | _type_ | caller-owned `open` / `advance` / `isTerminal`, retry policy, abort signal and `onAttempt` observer |
|
|
144
|
+
| `ResumableAttempt` | _type_ | attempt number, the delay about to be waited and the error that caused it |
|
|
145
|
+
|
|
146
|
+
### Trace (client)
|
|
147
|
+
|
|
148
|
+
Browser-safe W3C trace helpers — the same functions as on
|
|
149
|
+
[`stitchkit/observability`](#stitchkitobservability), re-exported so a client
|
|
150
|
+
can emit / propagate a `traceparent` (see `HttpClientConfig.trace`).
|
|
151
|
+
|
|
152
|
+
| Export | Kind | Summary |
|
|
153
|
+
|--------|------|---------|
|
|
154
|
+
| `createTraceContext` | function | a fresh root trace |
|
|
155
|
+
| `formatTraceparent` | function | render a `traceparent` header value |
|
|
156
|
+
| `parseTraceparent` | function | parse a `traceparent` header |
|
|
157
|
+
| `childSpan` | function | a child span of a parent trace |
|
|
158
|
+
| `TraceContext` | _type_ | `{ traceId, spanId, parentSpanId?, tracestate?, baggage? }` |
|
|
159
|
+
|
|
160
|
+
---
|
|
161
|
+
|
|
162
|
+
### Session lifetime and credential coordination
|
|
163
|
+
|
|
164
|
+
`createSessionScope` (`stitchkit`) returns the generic `SessionScope`: `replace(context)`
|
|
165
|
+
creates a new login lifetime (including same-account relogin), `capture()` returns
|
|
166
|
+
its `SessionOperation<T>`, `clear()` invalidates it, `stop()` permanently closes
|
|
167
|
+
the host, and `owns(operation)` answers whether an operation is this scope's current
|
|
168
|
+
one — `current()` alone cannot tell an operation of another scope. Operations expose `id`, `generation`, `context`, `signal`, `current()` and
|
|
169
|
+
`assertCurrent()`. `run(callback)` checks both success and failure across an await;
|
|
170
|
+
`deliver(callback)` admits a synchronous final send/state change or returns false.
|
|
171
|
+
`bindFetch(fetch, headers?)` guards every attempt and scopes its abort signal. Wrap
|
|
172
|
+
the complete client call in `run` too: headers are not the response body boundary.
|
|
173
|
+
Expired work throws `SessionExpiredError`, not a refresh instruction; when the work
|
|
174
|
+
itself failed, that failure is its `cause`.
|
|
175
|
+
|
|
176
|
+
`createSessionCredentials` accepts `SessionCredentialsConfig`:
|
|
177
|
+
`scope`, `refresh(credentials, signal)`, `storage.write(session, credentials)`,
|
|
178
|
+
`storage.clear()`, `maxPendingWrites` (128), `refreshTimeoutMs` (30000, at most one
|
|
179
|
+
hour) and `storageTimeoutMs` (30000, at most one hour): a storage call past it
|
|
180
|
+
rejects and frees the queue, so `logout()` still clears; when the late call settles,
|
|
181
|
+
storage is written again from memory, or cleared when nobody is logged in. `SessionCredentials` provides `login`, `logout`, `read(operation)` and
|
|
182
|
+
`refresh(operation)`. Concurrent refresh calls in one generation share the same
|
|
183
|
+
promise. Logout invalidates memory before its returned persistence promise settles.
|
|
184
|
+
Storage errors and queue-capacity refusals reject; callers must handle them. All
|
|
185
|
+
writes must pass through the same instance. There is no cross-process/tab lock,
|
|
186
|
+
provider error classifier or automatic retry of arbitrary application callbacks.
|
package/llms/stitchkit.txt
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# stitchkit — stitchkit docs slice, part 1 of
|
|
1
|
+
# stitchkit — stitchkit docs slice, part 1 of 3
|
|
2
2
|
|
|
3
3
|
> Generated from the `docs/` tree by `bun run gen:llms`. The index of all slices is
|
|
4
4
|
> `llms.txt` in this package.
|
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
|
|
7
7
|
Parts of this slice:
|
|
8
8
|
- `llms/stitchkit.txt`: Guide: Getting started (docs/guide/getting-started.md) · Guide: Typed client (docs/guide/client.md)
|
|
9
|
-
- `llms/stitchkit.2.txt`: Guide: Typed client (docs/guide/client.md)
|
|
9
|
+
- `llms/stitchkit.2.txt`: Guide: Typed client (docs/guide/client.md)
|
|
10
|
+
- `llms/stitchkit.3.txt`: API reference: `stitchkit` (docs/api/reference.md)
|
|
10
11
|
|
|
11
12
|
Also read:
|
|
12
13
|
- see `llms/contract.txt` for the Contracts guide
|
|
@@ -77,9 +78,10 @@ own, recorded as an ADR.
|
|
|
77
78
|
| `stitchkit/process/owner-loss` | bundled server entry (Bun, POSIX) | evolving | narrow bootstrap that keeps the process runner lazy while carrying its owner-loss guard in a single-file bundle |
|
|
78
79
|
| `stitchkit/files/packaging` | build time (Bun or Node) | evolving | installed native asset graph, integrity, Bun packaging plugin and the artifact loader check; a client bundled into one self-contained, hashed and verified file; no runtime install policy |
|
|
79
80
|
| `stitchkit/files` | server (Bun or Node) | stable | peer-free managed local-file boundary |
|
|
80
|
-
| `stitchkit/telegram` | server (Bun or Node) | evolving | peer-free Telegram platform primitives — Mini App `initData` verification, send-failure classification, one outbound budget per bot token with weighted albums and per-chat 429 pauses, resumable broadcasts, the operator channel with dedupe, a Bot API transport that separates a request that never left from an unknown outcome, local Bot API files, webhook ownership and durable webhook update intake |
|
|
81
|
+
| `stitchkit/telegram` | server (Bun or Node) | evolving | peer-free Telegram platform primitives — Mini App `initData` verification, send-failure classification, one outbound budget per bot token with weighted albums and per-chat 429 pauses, resumable broadcasts, the operator channel with dedupe, a Bot API transport that separates a request that never left from an unknown outcome, local Bot API files, the waveform of a voice message read from its PCM, webhook ownership and durable webhook update intake |
|
|
81
82
|
| `stitchkit/telegram/grammy` | server (Bun or Node) | evolving | the token's outbound budget as one grammY client transformer — a 429 that comes back as a response pauses its chat, and a cancelled wait is a request that never left |
|
|
82
83
|
| `stitchkit/telegram/html` | browser and server | evolving | Telegram's HTML as a tree — clean any markup to what Telegram accepts, cut long text into valid parts by what the reader sees, check markup before it is sent |
|
|
84
|
+
| `stitchkit/telegram/voice` | browser and server | evolving | the waveform of a voice message as one format — packed for `sendVoice` the way Telegram Desktop scales it, unpacked to draw it, a `getMe` read of whether the server takes it |
|
|
83
85
|
| `stitchkit/telegram/screens` | server (Bun or Node) | evolving | a bot's menus as declared screens over grammY — typed paths, actions and input, message reconciliation, state in any `StorageAdapter`, a test chat |
|
|
84
86
|
| `stitchkit/tracking` | browser **and** server | evolving | visitor-tracking mechanics — `createTrackingClient`, the tab-shared outbox, the page-leave beacon, attribution, the contract factory; no event vocabulary, no React |
|
|
85
87
|
| `stitchkit/tracking/contract` | browser **and** server | evolving | the wire shapes — the contract factory, event and visit schemas, the performance sample and its trust threshold; brings `zod` |
|
|
@@ -236,6 +238,7 @@ map — feature → packages:
|
|
|
236
238
|
| grammY lifecycle adapters (`stitchkit/application/grammy`) | `grammy` |
|
|
237
239
|
| Telegram platform primitives (`stitchkit/telegram`) | — (peer-free) |
|
|
238
240
|
| Telegram message markup (`stitchkit/telegram/html`) | — (peer-free) |
|
|
241
|
+
| Telegram voice waveforms (`stitchkit/telegram/voice`) | — (peer-free) |
|
|
239
242
|
| Telegram grammY client transformer (`stitchkit/telegram/grammy`) | `grammy` (types only; the bot brings it) |
|
|
240
243
|
| Telegram screens (`stitchkit/telegram/screens`) | `grammy` (types only; the bot brings it) |
|
|
241
244
|
| OpenTelemetry gauges (`stitchkit/application/opentelemetry`) | `@opentelemetry/api` |
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# stitchkit/telegram/voice — stitchkit docs slice
|
|
2
|
+
|
|
3
|
+
> Generated from the `docs/` tree by `bun run gen:llms`. The index of all slices is
|
|
4
|
+
> `llms.txt` in this package.
|
|
5
|
+
|
|
6
|
+
Contains: API reference: `stitchkit/telegram/voice` (docs/api/reference.md)
|
|
7
|
+
|
|
8
|
+
Also read:
|
|
9
|
+
- see `llms/telegram.txt` for the Telegram bots guide
|
|
10
|
+
|
|
11
|
+
==============================================================================
|
|
12
|
+
# API reference: `stitchkit/telegram/voice` (docs/api/reference.md)
|
|
13
|
+
==============================================================================
|
|
14
|
+
|
|
15
|
+
## `stitchkit/telegram/voice`
|
|
16
|
+
|
|
17
|
+
The waveform of a voice message — the bars under its play button — as one format for the server
|
|
18
|
+
that packs it and the page that draws it. No peer, no file, no network. →
|
|
19
|
+
[guide](../guide/telegram.md#voice-waveforms)
|
|
20
|
+
|
|
21
|
+
| Export | Kind | Summary |
|
|
22
|
+
|--------|------|---------|
|
|
23
|
+
| `packTelegramVoiceWaveform` | function | the 100 loudest absolute samples of 100 equal parts (`0`–`32768`) into the base64 of 63 bytes `sendVoice` takes: 5-bit levels packed little-endian, scaled like Telegram Desktop by 1.8 × the mean peak, never below a floor of 2500, so silence stays zero and a quiet recording stays low |
|
|
24
|
+
| `unpackTelegramVoiceWaveform` | function | the levels of a waveform, `0`–`31`, one per 5 bits: 100 from a packed one, as many as it holds from one Telegram drew |
|
|
25
|
+
| `readTelegramVoiceWaveformSupport` / `TelegramVoiceWaveformSupport` | function / _type_ | from a `getMe` result of any shape: `supported` only when the server declares `supports_voice_waveform` and `voice_waveform_version` 1; `version` as declared, `null` when none (the public Bot API) |
|
|
26
|
+
| `TelegramVoiceWaveformError` / `TelegramVoiceWaveformRefusal` | class / _type_ | `peak-count` / `peak-value` / `malformed` / `empty-pcm` / `truncated-pcm` |
|
|
27
|
+
| `TELEGRAM_VOICE_WAVEFORM_SAMPLES` / `TELEGRAM_VOICE_WAVEFORM_MAX_LEVEL` / `TELEGRAM_VOICE_WAVEFORM_VERSION` | constant | 100 parts, levels up to 31, field version 1 |
|
|
28
|
+
|
|
29
|
+
---
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# stitchkit/telegram — stitchkit docs slice, part 2 of 2
|
|
2
|
+
|
|
3
|
+
> Generated from the `docs/` tree by `bun run gen:llms`. The index of all slices is
|
|
4
|
+
> `llms.txt` in this package.
|
|
5
|
+
|
|
6
|
+
Parts of this slice:
|
|
7
|
+
- `llms/telegram.txt`: Guide: Telegram bots (docs/guide/telegram.md)
|
|
8
|
+
- `llms/telegram.2.txt`: API reference: `stitchkit/telegram` (docs/api/reference.md)
|
|
9
|
+
|
|
10
|
+
Also read:
|
|
11
|
+
- see `llms/telegram-screens.txt` for the Telegram screens guide
|
|
12
|
+
|
|
13
|
+
==============================================================================
|
|
14
|
+
# API reference: `stitchkit/telegram` (docs/api/reference.md)
|
|
15
|
+
==============================================================================
|
|
16
|
+
|
|
17
|
+
## `stitchkit/telegram`
|
|
18
|
+
|
|
19
|
+
Peer-free server-only Telegram platform primitives — the Bot API's own
|
|
20
|
+
protocols and the jobs every bot rewrote around them. Importing this resolves no
|
|
21
|
+
bot library; `stitchkit/application/grammy` remains the lifecycle adapter for an
|
|
22
|
+
injected grammY bot. → ADR 0143, ADR 0201, ADR 0274 — [guide](../guide/telegram.md)
|
|
23
|
+
|
|
24
|
+
| Export | Kind | Summary |
|
|
25
|
+
|--------|------|---------|
|
|
26
|
+
| `verifyTelegramInitData` | function | verify a Mini App `initData` signature against the bot token in constant time, before reading anything out of it |
|
|
27
|
+
| `VerifyTelegramInitDataOptions` | _type_ | raw `initData`, bot token, optional `maxAgeSeconds` bound and injected clock |
|
|
28
|
+
| `TelegramInitDataVerification` | _type_ | `{ valid: true, data }` or a refusal carrying its reason |
|
|
29
|
+
| `TelegramInitData` | _type_ | verified `user`/`receiver` as `TelegramUser`, `authDate`, `ageSeconds`, `queryId`, `startParam`, `chatType`, `chatInstance` and every signed pair in `raw` |
|
|
30
|
+
| `parseTelegramUser` / `TelegramUser` | function / _type_ | Telegram's `snake_case` user — grammY's `ctx.from`, a Bot API `User`, a Mini App `user` — as the one camelCase record initData returns too; `undefined` when it is not a user |
|
|
31
|
+
| `TelegramInitDataRefusal` | _type_ | `missing-hash` / `signature-mismatch` / `malformed` / `expired` — an expired string is not a forged one |
|
|
32
|
+
| `classifyTelegramSendFailure` | function | name a refused Bot API send and separate "retry this send" from "stop addressing this recipient" |
|
|
33
|
+
| `TelegramSendFailure` | _type_ | reason, `status`, Telegram-stated `retryAfterSeconds`, `retryable`, `recipientUnreachable` and which evidence produced the answer |
|
|
34
|
+
| `createTelegramBotTransport` / `TelegramBotTransportOptions` | function / _type_ | a `fetch` for the Bot API senders that connects before it writes, so a failure before the first byte is `TelegramNotDispatchedError`; connection attempt and budget, answer timeout and size, injectable resolver and socket factory — [guide](../guide/telegram.md#a-transport-that-knows-whether-a-request-left) |
|
|
35
|
+
| `TelegramFetch` / `TelegramBotTransportOpen` / `TelegramBotTransportResolve` / `TelegramBotTransportSocket` | _types_ | the `(url, init) => Promise<Response>` the senders take; the transport's socket factory, resolver and the structural socket it needs (a Node `net.Socket` or `tls.TLSSocket` fits) |
|
|
36
|
+
| `TelegramNotDispatchedError` / `TelegramNotDispatchedStage` | class / _type_ | a request that provably never left (`lookup`, `connect` or `request`), so repeating it cannot duplicate a message |
|
|
37
|
+
| `TelegramSendFailureReason` / `TELEGRAM_SEND_FAILURE_REASONS` | _type_ / constant | `blocked-by-user` / `user-deactivated` / `chat-not-found` / `not-started` / `bot-to-bot-disabled` / `rate-limited` / `message-invalid` / `server-error` / `not-dispatched` / `unknown`, and the same as a list; a `Record<TelegramSendFailureReason, …>` over them fails to compile when a reason is added |
|
|
38
|
+
| `telegramOutboundBudget` / `TelegramOutboundBudget` / `TelegramOutboundBudgetConfig` / `TelegramOutboundBudgetStats` / `TelegramOutboundCallOptions` / `TelegramOutboundChatOptions` / `TelegramOutboundLane` | function / _type_ | one token-wide outbound budget: one object per token in the process, strict 24 messages/s by default, weighted albums and multi-message copies, an `interactive` lane granted before `bulk`, `run(method, payload, signal, send, { lane, maxWaitMs })` as the transformer adapter (a 429 on a send pauses its `chat_id` whether `send` throws it or resolves with the Bot API's `{ ok: false, … }` body, and refusals from `tokenPauseChats` chats pause the token), `pause`/`pauseAfter` for 429, `waitUntilResumed` for non-send retries and `stats`; it paces and never retries, and no public value carries the token |
|
|
39
|
+
| `runTelegramBroadcast` | function | a resumable broadcast by `name` under a state `directory`: audience and journal durably recorded, pacing at `ratePerSecond` (25), exact retry delays within the finite declared budget, injected classifier, uncertain send outcomes never replayed, `dryRun`, one fenced runner per name |
|
|
40
|
+
| `TelegramBroadcastConfig` / `TelegramBroadcastSend` / `TelegramBroadcastReport` / `TelegramBroadcastRunOutcome` / `TelegramBroadcastOutcome` / `TelegramBroadcastRecipient` | _type_ | `name`, `directory`, `recipients()`, `send({ recipient, attempt })`, `maxAttempts`, `signal`, `onProgress`; counts `delivered` / `unreachable` / `failed` / `uncertain` / `pending` and `finished` / `stopped` / `halted` / `dry-run` |
|
|
41
|
+
| `TelegramBroadcastFailureSchema` / `TelegramBroadcastFailure` | schema / _type_ | injected `classify` answers retry-after/transient/permanent/ambiguous; exact provider delay is bounded by `maxRetryDelayMs` without shortening, unknown outcome remains uncertain and is never replayed |
|
|
42
|
+
| `telegramBroadcastSender` / `TelegramBroadcastSenderConfig` / `TelegramBroadcastMessage` | function / _type_ | the standard `send`: `sendMessage` with a text or `copyMessage` of a prepared message, through the Bot API |
|
|
43
|
+
| `createTelegramOperatorChannel` | function | the operator chat, apart from the journal: `post(text, topic?)` returns at once and never throws; paced sends into forum topics, 429 honoured, oldest dropped on overflow, `drain(signal)` and `close()` for the way down |
|
|
44
|
+
| `TelegramOperatorChannelConfig` / `TelegramOperatorChannel` / `TelegramOperatorMessage` / `TelegramOperatorDrop` / `TelegramChatId` | _type_ | `chatId`, `topics`, `send`, `maxQueued`, `minIntervalMs`, `maxAttempts`, `onDropped`, `sensitivePatterns` and `sensitiveValues` (a bot token is always masked), `dedupe`; a drop is `overflow` / `refused` / `attempts` / `closed` / `repeated` / `over-budget` with its classification |
|
|
45
|
+
| `createTelegramOperatorDedupe` / `TelegramOperatorDedupeVerdict` | function / _type_ | the channel's dedupe window alone, for a sender with its own bot and retry: `(text, topic?)` → `{ send: true, text }` with the held-back counts, or `{ send: false, reason: 'repeated' \| 'over-budget' }` |
|
|
46
|
+
| `TelegramOperatorDedupe` | _type_ | `windowMs` (10 min): one message per `fingerprint` per window, the next one sent carries `repeatedLine(count)`; `maxPerWindow` (20) across fingerprints, the overflow counted onto the next one sent with `overBudgetLine(count)`; `now` |
|
|
47
|
+
| `telegramOperatorSender` / `TelegramOperatorSenderConfig` | function / _type_ | the standard `send`: `sendMessage` into the chat and topic, plain text unless `parseMode`; with `'HTML'` the markup is cleaned and cut by what it shows, so the channel's cut never leaves a tag open |
|
|
48
|
+
| `createTelegramLocalFiles` | function | files the local Bot API server wrote under `<root>/<token>/`: `resolve(file_path)` and `remove(file_path)` only inside the bot's directory, judged on real paths so a link is judged by where it leads; `check()` for readiness. Recommended root variable: `BOT_API_FILES_ROOT` |
|
|
49
|
+
| `TelegramLocalFilesConfig` / `TelegramLocalFiles` / `TelegramLocalFilesCheck` / `TelegramLocalFileError` / `TelegramLocalFileRefusal` | _type_ / class | `root`, `token`; refusals `root-not-absolute` / `bot-directory-unavailable` / `outside-bot-directory` / `missing` / `not-a-file`, never carrying the path or the token |
|
|
50
|
+
| `readTelegramVoiceWaveform` / `ReadTelegramVoiceWaveformOptions` | function / _type_ | the packed waveform `sendVoice` takes, from a mono 16-bit little-endian PCM side copy of the recording, read in chunks; `signal` stops it between chunks; an empty or cut file is refused with `TelegramVoiceWaveformError` (`stitchkit/telegram/voice`), never named in it — [guide](../guide/telegram.md#voice-waveforms) |
|
|
51
|
+
| `callTelegramBotApi` / `TelegramBotApiCall` / `TelegramBotApiError` | function / _type_ / class | one Bot API method over `fetch`; a refusal keeps `error_code`, `description` and `parameters` for the classifier, and no error names the URL |
|
|
52
|
+
| `TELEGRAM_BOT_TOKEN_PATTERN` / `redactTelegramBotToken` | constant / function | the secret half of a bot token — the bot's id before the colon is not matched; `redact` and every logger on it mask it already, `redactTelegramBotToken(text)` masks every token in a string to `123456:[redacted]` |
|
|
53
|
+
| `claimTelegramWebhook` | function | set the webhook only where it already points here, or by naming the host it is taken from; confirm Telegram holds it; pending updates kept unless `dropPendingUpdates` |
|
|
54
|
+
| `ClaimTelegramWebhookConfig` / `TelegramWebhookConfig` / `TelegramWebhookClaim` | _type_ | `token`, `url`, `secret`, `apiRoot`, `fetch`, `signal`; `takeoverFrom` (a host, or `'none'`), `allowedUpdates`, `maxConnections`, `dropPendingUpdates`; the claim's tagged `url`, `takenFrom`, `pendingUpdates` |
|
|
55
|
+
| `TelegramWebhookClaimError` / `TelegramWebhookRefusal` / `TELEGRAM_WEBHOOK_NONE` | class / _type_ / constant | `owned-elsewhere` / `other-secret` / `not-confirmed` with `ownerHost` — a host, never a path; `'none'` names no webhook |
|
|
56
|
+
| `telegramWebhookUrl` | function | the address with an `owner` tag derived from the secret: equal for one secret, different for another, the path untouched |
|
|
57
|
+
| `checkTelegramWebhook` / `TelegramWebhookState` | function / _type_ | whether the webhook still points here: `owned`, `ownerHost`, `pendingUpdates`, Telegram's `lastError` |
|
|
58
|
+
| `receiveTelegramWebhook` / `ReceiveTelegramWebhookOptions` / `TelegramUpdateAcceptance` | function / _type_ | one webhook `Request`: 403 without the secret (compared in constant time), 405 for another method, 400 for no update, 200 once `accept` recorded it |
|
|
59
|
+
| `createTelegramUpdateIntake` | function | webhook updates recorded before Telegram is answered and handled after: chat order kept, other chats alongside up to `maxConcurrent`, a renewed lease and immutable fence per attempt, a sweep that takes over what a restart or a dead process left, retries, `maxAttempts`, optional recoverable exhaustion delivery, finished updates remembered `retainMs` to refuse repeats; at least once |
|
|
60
|
+
| `TelegramUpdateIntakeConfig` / `TelegramUpdateAttemptIntakeConfig` / `TelegramUpdateIntakeOptions` / `TelegramUpdateIntake` / `TelegramUpdateEnvelope` / `TelegramUpdateFailure` / `TelegramUpdateStoreStep` | _type_ | `store`, unchanged `handle(update)` or attempt-aware `handleAttempt(update, context)` (a grammY `BotError` is unwrapped), shared `retry`, `maxAttempts` (5), `leaseMs` (120 000), `pendingGraceMs` (60 000), `sweepEveryMs` (30 000), `retainMs` (24 h), `maxConcurrent` (32), `onFailure`, durable `handleExhaustion`, `onExhaustionFailure`, `onStoreError`, `now`; `accept(body)`, `start()`, `sweep()`, `idle()`, `close()` |
|
|
61
|
+
| `TelegramUpdateAttemptContext` / `TelegramUpdateAttemptIdentity` / `TelegramUpdateOwnershipLostError` | _type_ / class | immutable `{ updateId, attempt, claimId }` fence plus `ownerLost`; the persisted opaque claim token prevents a stale capability from matching after prune/re-add, while a store check in the consumer's DB transaction fences a domain write |
|
|
62
|
+
| `TelegramUpdateExhaustion` / `TelegramUpdateExhaustionFailure` / `StoredTelegramUpdateExhaustion` / `TelegramUpdateExhaustionQuery` | _type_ | a terminal update/attempt/error retained in the update store until `handleExhaustion` resolves; ordered `{ limit, afterUpdateId? }` pages prevent a failing first batch from starving later rows; delivery failures are observational and leave it due |
|
|
63
|
+
| `TelegramUpdateStore` / `StoredTelegramUpdate` / `TelegramUpdateState` / `TelegramUpdateSettlement` / `TelegramUpdateClaimOptions` / `TelegramUpdateDueQuery` | _type_ | the base store an intake runs on: `add`, `claim`, `renew`, `settle`, `due`, `prune`, each atomic on one record — a claim takes `pending`, a due `failed` or a lapsed `processing`; renew and settle only by the attempt holding it; `due` returns one page and continues strictly after `afterUpdateId` |
|
|
64
|
+
| `TelegramUpdateFencedStore` / `TelegramUpdateDurableStore` | _type_ | reference-store capabilities: `claimOwned` creates and returns the persisted identity, `renewOwned`, `owns(identity, at)` and `settleOwned(identity, settlement)` act only on that exact unexpired claim; `exhaust`, `dueExhaustions`, `acknowledgeExhaustion` keep a final consumer obligation in the same row until exact acknowledgement |
|
|
65
|
+
| `memoryTelegramUpdateStore` | function | the store in this process's memory — tests, or a bot that accepts losing unhandled updates to a restart |
|
|
66
|
+
| `sqliteTelegramUpdateStore` / `SqliteTelegramUpdateStoreConfig` / `TelegramSqliteDatabase` | function / _type_ | the store in SQLite over the handle the application opened — `bun:sqlite` `Database` or `node:sqlite` `DatabaseSync`; `table` (default `telegram_updates`) created when missing |
|
|
67
|
+
| `postgresTelegramUpdateStore` / `PostgresTelegramUpdateStoreConfig` / `TelegramPostgresQuery` | function / _type_ | the store in Postgres over the client the application holds, as one `query(text, parameters)` returning rows — Bun `sql.unsafe`, Prisma `$queryRawUnsafe`, `pg` `pool.query`; each rule one conditional statement; `table`, `createTable` (default `true`) |
|
|
68
|
+
| `postgresTelegramUpdateStoreSchema` | function | the table, idempotent `claim_id` upgrade and index as a statement for a migration, safe to run twice; required before fenced methods when `createTable: false`, while legacy base methods remain compatible with the prior table |
|
|
69
|
+
| `checkTelegramUpdateStore` | function | put any store through every rule, each on a fresh store from `make`, concurrent claims included; resolves with the violations, empty when it keeps them |
|
|
70
|
+
|
|
71
|
+
---
|
package/llms/telegram.txt
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
-
# stitchkit/telegram — stitchkit docs slice
|
|
1
|
+
# stitchkit/telegram — stitchkit docs slice, part 1 of 2
|
|
2
2
|
|
|
3
3
|
> Generated from the `docs/` tree by `bun run gen:llms`. The index of all slices is
|
|
4
4
|
> `llms.txt` in this package.
|
|
5
|
+
> Continues in `llms/telegram.2.txt`.
|
|
5
6
|
|
|
6
|
-
|
|
7
|
+
Parts of this slice:
|
|
8
|
+
- `llms/telegram.txt`: Guide: Telegram bots (docs/guide/telegram.md)
|
|
9
|
+
- `llms/telegram.2.txt`: API reference: `stitchkit/telegram` (docs/api/reference.md)
|
|
7
10
|
|
|
8
11
|
Also read:
|
|
9
12
|
- see `llms/telegram-screens.txt` for the Telegram screens guide
|
|
@@ -30,6 +33,7 @@ way: [ADR 0201](../decisions/0201-a-telegram-bot-is-assembled-from-primitives.md
|
|
|
30
33
|
| the operator's chat: product events, apart from the journal | `createTelegramOperatorChannel` |
|
|
31
34
|
| a broadcast that survives crashes, deploys and Ctrl-C | `runTelegramBroadcast` |
|
|
32
35
|
| a file the local Bot API server wrote to disk | `createTelegramLocalFiles` |
|
|
36
|
+
| the waveform of a voice message: packed for `sendVoice`, drawn in a page | `readTelegramVoiceWaveform`, `stitchkit/telegram/voice` — [below](#voice-waveforms) |
|
|
33
37
|
| why a send was refused | `classifyTelegramSendFailure` — [auth and errors](auth-and-errors.md#telegram-mini-apps) |
|
|
34
38
|
| Mini App `initData` | `verifyTelegramInitData` — [auth and errors](auth-and-errors.md#telegram-mini-apps) |
|
|
35
39
|
| one Bot API call without a bot library | `callTelegramBotApi` |
|
|
@@ -621,61 +625,49 @@ answers whether the directory is there to read and delete from; a resource that
|
|
|
621
625
|
throws on `{ ready: false }` in `start` keeps the bot from answering before it
|
|
622
626
|
can read its media.
|
|
623
627
|
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
628
|
+
## Voice waveforms
|
|
629
|
+
|
|
630
|
+
A voice message carries its waveform: the bars under the play button, 100
|
|
631
|
+
levels of 5 bits. The public Bot API takes no waveform in `sendVoice`, so
|
|
632
|
+
Telegram draws its own. A local Bot API server that takes one says so in
|
|
633
|
+
`getMe` with `supports_voice_waveform: true` and `voice_waveform_version: 1`.
|
|
634
|
+
|
|
635
|
+
The waveform is computed from a decoded side copy of the recording. The file
|
|
636
|
+
being sent stays byte for byte what it was:
|
|
637
|
+
|
|
638
|
+
```ts
|
|
639
|
+
import { readTelegramVoiceWaveform } from 'stitchkit/telegram'
|
|
640
|
+
import { readTelegramVoiceWaveformSupport } from 'stitchkit/telegram/voice'
|
|
641
|
+
|
|
642
|
+
// ffmpeg -nostdin -i voice.ogg -map 0:a:0 -ac 1 -ar 8000 -f s16le wave.pcm
|
|
643
|
+
const waveform = await readTelegramVoiceWaveform(pcmPath, { signal })
|
|
644
|
+
|
|
645
|
+
if (!readTelegramVoiceWaveformSupport(await bot.api.getMe()).supported) {
|
|
646
|
+
throw new Error('this Bot API server draws its own waveform')
|
|
647
|
+
}
|
|
648
|
+
const options = { duration, waveform } satisfies Parameters<typeof bot.api.sendVoice>[2] & {
|
|
649
|
+
waveform: string
|
|
650
|
+
}
|
|
651
|
+
await bot.api.sendVoice(chatId, new InputFile(oggPath), options)
|
|
652
|
+
```
|
|
627
653
|
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
| `TelegramSendFailureReason` / `TELEGRAM_SEND_FAILURE_REASONS` | _type_ / constant | `blocked-by-user` / `user-deactivated` / `chat-not-found` / `not-started` / `bot-to-bot-disabled` / `rate-limited` / `message-invalid` / `server-error` / `not-dispatched` / `unknown`, and the same as a list; a `Record<TelegramSendFailureReason, …>` over them fails to compile when a reason is added |
|
|
649
|
-
| `telegramOutboundBudget` / `TelegramOutboundBudget` / `TelegramOutboundBudgetConfig` / `TelegramOutboundBudgetStats` / `TelegramOutboundCallOptions` / `TelegramOutboundChatOptions` / `TelegramOutboundLane` | function / _type_ | one token-wide outbound budget: one object per token in the process, strict 24 messages/s by default, weighted albums and multi-message copies, an `interactive` lane granted before `bulk`, `run(method, payload, signal, send, { lane, maxWaitMs })` as the transformer adapter (a 429 on a send pauses its `chat_id` whether `send` throws it or resolves with the Bot API's `{ ok: false, … }` body, and refusals from `tokenPauseChats` chats pause the token), `pause`/`pauseAfter` for 429, `waitUntilResumed` for non-send retries and `stats`; it paces and never retries, and no public value carries the token |
|
|
650
|
-
| `runTelegramBroadcast` | function | a resumable broadcast by `name` under a state `directory`: audience and journal durably recorded, pacing at `ratePerSecond` (25), exact retry delays within the finite declared budget, injected classifier, uncertain send outcomes never replayed, `dryRun`, one fenced runner per name |
|
|
651
|
-
| `TelegramBroadcastConfig` / `TelegramBroadcastSend` / `TelegramBroadcastReport` / `TelegramBroadcastRunOutcome` / `TelegramBroadcastOutcome` / `TelegramBroadcastRecipient` | _type_ | `name`, `directory`, `recipients()`, `send({ recipient, attempt })`, `maxAttempts`, `signal`, `onProgress`; counts `delivered` / `unreachable` / `failed` / `uncertain` / `pending` and `finished` / `stopped` / `halted` / `dry-run` |
|
|
652
|
-
| `TelegramBroadcastFailureSchema` / `TelegramBroadcastFailure` | schema / _type_ | injected `classify` answers retry-after/transient/permanent/ambiguous; exact provider delay is bounded by `maxRetryDelayMs` without shortening, unknown outcome remains uncertain and is never replayed |
|
|
653
|
-
| `telegramBroadcastSender` / `TelegramBroadcastSenderConfig` / `TelegramBroadcastMessage` | function / _type_ | the standard `send`: `sendMessage` with a text or `copyMessage` of a prepared message, through the Bot API |
|
|
654
|
-
| `createTelegramOperatorChannel` | function | the operator chat, apart from the journal: `post(text, topic?)` returns at once and never throws; paced sends into forum topics, 429 honoured, oldest dropped on overflow, `drain(signal)` and `close()` for the way down |
|
|
655
|
-
| `TelegramOperatorChannelConfig` / `TelegramOperatorChannel` / `TelegramOperatorMessage` / `TelegramOperatorDrop` / `TelegramChatId` | _type_ | `chatId`, `topics`, `send`, `maxQueued`, `minIntervalMs`, `maxAttempts`, `onDropped`, `sensitivePatterns` and `sensitiveValues` (a bot token is always masked), `dedupe`; a drop is `overflow` / `refused` / `attempts` / `closed` / `repeated` / `over-budget` with its classification |
|
|
656
|
-
| `createTelegramOperatorDedupe` / `TelegramOperatorDedupeVerdict` | function / _type_ | the channel's dedupe window alone, for a sender with its own bot and retry: `(text, topic?)` → `{ send: true, text }` with the held-back counts, or `{ send: false, reason: 'repeated' \| 'over-budget' }` |
|
|
657
|
-
| `TelegramOperatorDedupe` | _type_ | `windowMs` (10 min): one message per `fingerprint` per window, the next one sent carries `repeatedLine(count)`; `maxPerWindow` (20) across fingerprints, the overflow counted onto the next one sent with `overBudgetLine(count)`; `now` |
|
|
658
|
-
| `telegramOperatorSender` / `TelegramOperatorSenderConfig` | function / _type_ | the standard `send`: `sendMessage` into the chat and topic, plain text unless `parseMode`; with `'HTML'` the markup is cleaned and cut by what it shows, so the channel's cut never leaves a tag open |
|
|
659
|
-
| `createTelegramLocalFiles` | function | files the local Bot API server wrote under `<root>/<token>/`: `resolve(file_path)` and `remove(file_path)` only inside the bot's directory, judged on real paths so a link is judged by where it leads; `check()` for readiness. Recommended root variable: `BOT_API_FILES_ROOT` |
|
|
660
|
-
| `TelegramLocalFilesConfig` / `TelegramLocalFiles` / `TelegramLocalFilesCheck` / `TelegramLocalFileError` / `TelegramLocalFileRefusal` | _type_ / class | `root`, `token`; refusals `root-not-absolute` / `bot-directory-unavailable` / `outside-bot-directory` / `missing` / `not-a-file`, never carrying the path or the token |
|
|
661
|
-
| `callTelegramBotApi` / `TelegramBotApiCall` / `TelegramBotApiError` | function / _type_ / class | one Bot API method over `fetch`; a refusal keeps `error_code`, `description` and `parameters` for the classifier, and no error names the URL |
|
|
662
|
-
| `TELEGRAM_BOT_TOKEN_PATTERN` / `redactTelegramBotToken` | constant / function | the secret half of a bot token — the bot's id before the colon is not matched; `redact` and every logger on it mask it already, `redactTelegramBotToken(text)` masks every token in a string to `123456:[redacted]` |
|
|
663
|
-
| `claimTelegramWebhook` | function | set the webhook only where it already points here, or by naming the host it is taken from; confirm Telegram holds it; pending updates kept unless `dropPendingUpdates` |
|
|
664
|
-
| `ClaimTelegramWebhookConfig` / `TelegramWebhookConfig` / `TelegramWebhookClaim` | _type_ | `token`, `url`, `secret`, `apiRoot`, `fetch`, `signal`; `takeoverFrom` (a host, or `'none'`), `allowedUpdates`, `maxConnections`, `dropPendingUpdates`; the claim's tagged `url`, `takenFrom`, `pendingUpdates` |
|
|
665
|
-
| `TelegramWebhookClaimError` / `TelegramWebhookRefusal` / `TELEGRAM_WEBHOOK_NONE` | class / _type_ / constant | `owned-elsewhere` / `other-secret` / `not-confirmed` with `ownerHost` — a host, never a path; `'none'` names no webhook |
|
|
666
|
-
| `telegramWebhookUrl` | function | the address with an `owner` tag derived from the secret: equal for one secret, different for another, the path untouched |
|
|
667
|
-
| `checkTelegramWebhook` / `TelegramWebhookState` | function / _type_ | whether the webhook still points here: `owned`, `ownerHost`, `pendingUpdates`, Telegram's `lastError` |
|
|
668
|
-
| `receiveTelegramWebhook` / `ReceiveTelegramWebhookOptions` / `TelegramUpdateAcceptance` | function / _type_ | one webhook `Request`: 403 without the secret (compared in constant time), 405 for another method, 400 for no update, 200 once `accept` recorded it |
|
|
669
|
-
| `createTelegramUpdateIntake` | function | webhook updates recorded before Telegram is answered and handled after: chat order kept, other chats alongside up to `maxConcurrent`, a renewed lease and immutable fence per attempt, a sweep that takes over what a restart or a dead process left, retries, `maxAttempts`, optional recoverable exhaustion delivery, finished updates remembered `retainMs` to refuse repeats; at least once |
|
|
670
|
-
| `TelegramUpdateIntakeConfig` / `TelegramUpdateAttemptIntakeConfig` / `TelegramUpdateIntakeOptions` / `TelegramUpdateIntake` / `TelegramUpdateEnvelope` / `TelegramUpdateFailure` / `TelegramUpdateStoreStep` | _type_ | `store`, unchanged `handle(update)` or attempt-aware `handleAttempt(update, context)` (a grammY `BotError` is unwrapped), shared `retry`, `maxAttempts` (5), `leaseMs` (120 000), `pendingGraceMs` (60 000), `sweepEveryMs` (30 000), `retainMs` (24 h), `maxConcurrent` (32), `onFailure`, durable `handleExhaustion`, `onExhaustionFailure`, `onStoreError`, `now`; `accept(body)`, `start()`, `sweep()`, `idle()`, `close()` |
|
|
671
|
-
| `TelegramUpdateAttemptContext` / `TelegramUpdateAttemptIdentity` / `TelegramUpdateOwnershipLostError` | _type_ / class | immutable `{ updateId, attempt, claimId }` fence plus `ownerLost`; the persisted opaque claim token prevents a stale capability from matching after prune/re-add, while a store check in the consumer's DB transaction fences a domain write |
|
|
672
|
-
| `TelegramUpdateExhaustion` / `TelegramUpdateExhaustionFailure` / `StoredTelegramUpdateExhaustion` / `TelegramUpdateExhaustionQuery` | _type_ | a terminal update/attempt/error retained in the update store until `handleExhaustion` resolves; ordered `{ limit, afterUpdateId? }` pages prevent a failing first batch from starving later rows; delivery failures are observational and leave it due |
|
|
673
|
-
| `TelegramUpdateStore` / `StoredTelegramUpdate` / `TelegramUpdateState` / `TelegramUpdateSettlement` / `TelegramUpdateClaimOptions` / `TelegramUpdateDueQuery` | _type_ | the base store an intake runs on: `add`, `claim`, `renew`, `settle`, `due`, `prune`, each atomic on one record — a claim takes `pending`, a due `failed` or a lapsed `processing`; renew and settle only by the attempt holding it; `due` returns one page and continues strictly after `afterUpdateId` |
|
|
674
|
-
| `TelegramUpdateFencedStore` / `TelegramUpdateDurableStore` | _type_ | reference-store capabilities: `claimOwned` creates and returns the persisted identity, `renewOwned`, `owns(identity, at)` and `settleOwned(identity, settlement)` act only on that exact unexpired claim; `exhaust`, `dueExhaustions`, `acknowledgeExhaustion` keep a final consumer obligation in the same row until exact acknowledgement |
|
|
675
|
-
| `memoryTelegramUpdateStore` | function | the store in this process's memory — tests, or a bot that accepts losing unhandled updates to a restart |
|
|
676
|
-
| `sqliteTelegramUpdateStore` / `SqliteTelegramUpdateStoreConfig` / `TelegramSqliteDatabase` | function / _type_ | the store in SQLite over the handle the application opened — `bun:sqlite` `Database` or `node:sqlite` `DatabaseSync`; `table` (default `telegram_updates`) created when missing |
|
|
677
|
-
| `postgresTelegramUpdateStore` / `PostgresTelegramUpdateStoreConfig` / `TelegramPostgresQuery` | function / _type_ | the store in Postgres over the client the application holds, as one `query(text, parameters)` returning rows — Bun `sql.unsafe`, Prisma `$queryRawUnsafe`, `pg` `pool.query`; each rule one conditional statement; `table`, `createTable` (default `true`) |
|
|
678
|
-
| `postgresTelegramUpdateStoreSchema` | function | the table, idempotent `claim_id` upgrade and index as a statement for a migration, safe to run twice; required before fenced methods when `createTable: false`, while legacy base methods remain compatible with the prior table |
|
|
679
|
-
| `checkTelegramUpdateStore` | function | put any store through every rule, each on a fresh store from `make`, concurrent claims included; resolves with the violations, empty when it keeps them |
|
|
680
|
-
|
|
681
|
-
---
|
|
654
|
+
The levels follow Telegram Desktop. Each of the 100 parts keeps its loudest
|
|
655
|
+
sample, and the scale is 1.8 times the mean of those peaks, never below 2500
|
|
656
|
+
of 16-bit PCM. A loud passage does not flatten the quiet ones to nothing, and
|
|
657
|
+
a quiet recording is not stretched to look loud. Silence stays at zero. The
|
|
658
|
+
PCM is read in chunks, so a long recording is never held in memory; at 8 kHz,
|
|
659
|
+
six hours of audio is under 350 MB of PCM. A file with no sample or one cut
|
|
660
|
+
inside a sample is refused with `TelegramVoiceWaveformError` (`empty-pcm`,
|
|
661
|
+
`truncated-pcm`), and the waveform is never made up.
|
|
662
|
+
|
|
663
|
+
Whether a server that does not declare support still gets the voice is the
|
|
664
|
+
bot's decision. It can refuse to send, or send without the field and let
|
|
665
|
+
Telegram draw the bars. `readTelegramVoiceWaveformSupport` reads any answer:
|
|
666
|
+
`supported` means version 1, and `version` is what the server declared, or
|
|
667
|
+
`null` when it declared nothing.
|
|
668
|
+
|
|
669
|
+
`stitchkit/telegram/voice` has no peer and touches no file, so a page drawing
|
|
670
|
+
the bars reads the same format: `unpackTelegramVoiceWaveform(waveform)` gives
|
|
671
|
+
the levels `0`–`31`, 100 for a waveform packed here and as many as it holds
|
|
672
|
+
for one Telegram drew itself. `packTelegramVoiceWaveform(peaks)` packs 100
|
|
673
|
+
peaks already found by other means.
|