@feedbackrelay/web 0.0.0-stage → 0.1.1

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/AGENTS.md ADDED
@@ -0,0 +1,77 @@
1
+ # Web agent guide
2
+
3
+ Read the host instructions and [README.md](README.md). Keep the host's UI/framework.
4
+
5
+ ## Integrate
6
+
7
+ Use Node.js 26/npm for this checkout's build and packaging commands; Node is a development tool, not a device/browser requirement.
8
+
9
+ Install @feedbackrelay/web@0.1.1 from npm. Contributors can use the local archive steps in README.md to test source changes. `createRelayClient` requires appId/teamId/relayId/publishableKey; optional settings include baseUrl, app release, context, screenshot restriction, private selectors, local uploadLimits and replay. `send(input, options?)` returns a receipt Promise. Imports stay SSR-safe; sends need a browser. Core source/API floors are Chrome/Edge 93+, Firefox 92+ and Safari/iOS Safari 15.4+ (Object.hasOwn); do not claim old-browser certification or add polyfills. Plain HTML needs no JavaScript SDK.
10
+
11
+ Browser FormData/File/Blob uploads real files. Empty files count; never remove caller parts silently. Snapshot without mutating the form. Native HTML uses hidden _relay_key; enhanced forms remove reserved fields before SDK send. No script is required for plain HTML, which returns JSON and adds no SDK diagnostics/capture.
12
+
13
+ ## Errors, objects and retry
14
+
15
+ With an existing client, keep retry state in its owner:
16
+
17
+ ```ts
18
+ import { RelaySendError } from '@feedbackrelay/web';
19
+ let failed: { input: unknown; submissionId: string } | undefined;
20
+ async function report(input: unknown, submissionId?: string) {
21
+ failed = undefined;
22
+ try { return await relay.send(input, { submissionId }); }
23
+ catch (error) {
24
+ if (error instanceof RelaySendError) failed = { input, submissionId: error.submissionId };
25
+ throw error;
26
+ }
27
+ }
28
+ ```
29
+
30
+ Call `report(caughtError)` inside existing error handling; catch reporting failure without replacing app recovery. Do not stringify errors. `report({ screen: 'Checkout' })` sends exact JSON; cycles are handled automatically. A manual Retry copies/checks failed, then calls `report(saved.input, saved.submissionId)` and handles its rejection. New occurrences omit the ID. Canceling cannot retract accepted data; the service must deduplicate IDs.
31
+
32
+ ## Lifetime and changes
33
+
34
+ Use AbortSignal for one send and destroy for final cleanup. Preserve lazy DOM capture, password/private/iframe exclusions and the live page. data-relay-private/privateSelectors control masking; no screen sharing.
35
+
36
+ Edit src/index.ts, data.ts, payload.ts, delivery.ts, metadata.ts or capture.ts as appropriate. Keep types and README examples aligned. Run typecheck, unit and package checks; capture/transport changes also need serial browser checks from the README. Verify the installed archive and preserve third-party notices. Report unavailable browsers honestly.
37
+
38
+ ## Local collection preview
39
+
40
+ Use optional per-send `onCollected(json, png)` for local inspection before ticket/upload/event requests. Emit it once after collection/file preparation/PNG and validation. JSON remains `{submission, formData?}` with ordered text/file descriptors, no binary/SDK URI/key; explicit caller data/context remain. Supply the actual selected PNG separately, absent when no capture or replay is configured. Reuse capture, never recapture or change transport. Web uses `(json: string, png?: Blob)`; the immutable captured Blob can be retained. The host owns/revokes object URLs. Do not await returned Promises; contain rejections.
41
+
42
+ Contain observer errors and recheck cancellation afterward. No observer means no extra preview serialization/copy. Supply it again for retries. The host owns local data/image UI and cleanup; no server echo or receipt is needed for a preview. Optional video uses recorder.preview separately, not this callback.
43
+
44
+ ## Failure isolation
45
+
46
+ Keep ignored send promises internally handled without changing await/catch rejection; do not create a second rejected promise or install global error listeners. Host-created chains/tasks still need their own catch. Invalid setup validation remains explicit. Add no error UI, console logging, automatic retries or blanket suppression of host errors.
47
+
48
+ ## Contract and safety rules
49
+
50
+ - Bind `teamId`/`relayId` at creation. Use one client per destination, at most four active sends per client. When replacing a client, clear its owner's saved retry state.
51
+ - `send` preserves ordinary JSON. Errors, cycles and other non-JSON values get a size-limited diagnostic summary. Valid JSON over a byte/depth/node limit must fail, never silently truncate. No diagnostic flag, converter or extra send method.
52
+ - Do not fetch settings. POST directly to `/v1/sdk/teams/{teamId}/relays/{relayId}` with `X-Relay-Key`. Use the actual body type: JSON envelope is `application/json`; form data is multipart with a generated boundary. Each file part has its own MIME type.
53
+ - Preserve form order/repeats/binary. Reject caller `_relay_` names; append `_relay_metadata` JSON with `kind: data` and no `data` member. Captured screenshots use their separate `/uploads` flow.
54
+ - Local uploadLimits defaults to 10 files/3 MiB each/total. An override must provide all three nonnegative safe integers. Any zero disables file parts. Validate before capture/network; the service independently enforces policy.
55
+ - Keep the README's resource bounds: JSON/context 64 KiB each, metadata 128 KiB, diagnostics 32 KiB, multipart 1,000 caller parts/64 KiB names+text and screenshot 8 MiB/5-second capture budget. These are separate from file policy.
56
+ - Context replaces rather than merges and is copied per send. Cancel old-user work before clearing identity context. Global capture restrictions win over per-send enabling.
57
+ - Only diagnostic summaries redact common credential keys. Exact JSON, context, fields/files and screenshots are not automatically redacted. Keep app error recovery separate from reporting failure.
58
+
59
+ The app owns all UI and file selection. Add no UI, global error interception, gestures, permissions or runtime dependency. Keep replay opt-in and isolated from the core. Preserve required resources/notices. The SDK uses the [Apache License 2.0](LICENSE). Include the license and preserve third-party notices when distributing it. Do not publish unless requested.
60
+
61
+ ## Optional replay
62
+
63
+ Keep automatic-rate behavior and threshold changes aligned with the [automatic FPS rules](https://github.com/apal21/relay-sdk/blob/main/sdk/CONTRACT.md#automatic-fps-rules). Do not claim identical iOS/Android/web policies or equate the selected target with measured throughput.
64
+
65
+ Use `import { createReplayRecorder } from '@feedbackrelay/web/replay'`, then pass `replay: createReplayRecorder({ fps: 'auto' })` at client initialization. Reuse one recorder for clients with the same base URL/team/app. FPS is auto 1–5 or fixed 1–10; invalid values fall back to auto. No backend configuration request, hosted form or HTML recording exists.
66
+
67
+ Replay additionally needs Chrome/Edge 94+, desktop Firefox 130+ or Safari/iOS Safari 16.4+, HTTPS/localhost and an available H.264 encoder. Firefox Android replay is unsupported. These API floors are not runtime certification. Replay uses privacy-filtered canvas frames directly with WebCodecs H.264 and the restricted MP4 writer. It replaces PNG even when unsupported. Keep the ten-second/keyframe-aware/2 MiB ring, 720-pixel edge, 500 kbit/s target, 8 MiB retained budget, four 60-second leases and one 30-second upload job. Drop work rather than queue captures. Close frames/encoders and pause on hidden/pagehide; pageshow resumes with fresh history. No gestures/vitals are uploaded.
68
+
69
+ Core communicates through small opaque attach/freeze/accepted/cancel/detach hooks. It catches media-hook failures, preserves its receipt and does not import encoders. Freeze retains samples; event-associated mux/upload follows durable acceptance in a deferred worker. Explicit local preview can mux before a send and never uploads. Ordinary send failure retains the same lease for retry; explicit abort/detach/clear/destroy/expiry cancels it. A stale retry never captures new history. Local screenshot false restricts replay too.
70
+
71
+ The optional recorder's `preview()` exports local history without send/HTTP. It returns a Promise of either `{video: Blob,width,height,durationMs,startedBeforeEventMs,endedBeforeEventMs,release()}` or `{omitted,release()}`. Keep at most one pending/held preview using the existing worker/lease/byte limits. The host owns its player and object URL; revoke/drop old URLs/Blob references on replacement/clear/unload. SDK release cannot revoke a handed-out Blob. Keep the player private from later capture. Never create a fake receipt or require a server read for playback.
72
+
73
+ Read-only recorder.currentFPS:number|undefined is the selected adaptive/fixed target, not measured throughput. Return undefined when inactive/hidden/unavailable/destroyed; add no SDK timer or uploaded field.
74
+
75
+ Post media separately to `/replays` using protocolVersion 1 and the accepted submissionId, with video descriptor or omission reason. Only pending status plus a valid upload ticket permits storage upload. Never send the publishable key to storage. Complete with `{}` at `/replays/{id}/complete`. An initial ready/omitted/failed/expired handshake needs no upload. Completion succeeds only with the ticket's matching id and status ready; other completion replies are media failures retained for explicit retry within the original lease. Preserve bounded response reads and independent cancellation.
76
+
77
+ Call recorder.clear explicitly at identity changes after canceling old-user work. Context updates alone must not erase shared history. Client destruction detaches only that owner; recorder.destroy is terminal. Union attached private selectors and clear old frame history when stricter. Keep imports SSR-safe and ordinary sends working without encoder support. Verify actual trimmed MP4 playback in other browsers, variable timing, privacy, retries, memory bounds and package subpath imports. Run all checks serially.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,332 @@
1
- # Temporary Holding Version
1
+ # Relay for web
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Send your own form values, JSON or diagnostics from a browser. The SDK is framework-neutral and displays no UI. Imports are safe during server rendering; sending requires a browser document.
4
+
5
+ For a plain HTML form, skip package installation and use [the HTML example](#plain-html-without-javascript). It needs no script. Use the JavaScript SDK below when you need app metadata, diagnostics or optional screenshots.
6
+
7
+ ## Before you start
8
+
9
+ You need a compatible API URL, team ID, relay ID and publishable key. The default URL is `https://api.feedbackrelay.app`; this repository does not deploy that production backend or create credentials. Set `baseUrl` for another compatible service.
10
+
11
+ A client always sends to its configured team/relay. Reuse it for repeated sends; create another client for another destination. Up to four sends can run at once per client.
12
+
13
+ ## 1. Install
14
+
15
+ Use Node.js 26/npm for this checkout's build tools. Core API floors are Chrome/Edge 93+, Firefox 92+, and Safari/iOS Safari 15.4+; these follow [Object.hasOwn support](https://github.com/mdn/browser-compat-data/blob/main/javascript/builtins/Object.json). The browser also needs ES modules, fetch, FormData, Blob, AbortController and Web Crypto. No polyfills or UI framework are bundled. These are source/API floors, not old-browser runtime certification; plain HTML needs no SDK or JavaScript.
16
+
17
+ From your app folder, install the SDK:
18
+
19
+ ```sh
20
+ npm install @feedbackrelay/web@0.1.1
21
+ ```
22
+
23
+ ## 2. Create a client and send
24
+
25
+ ```ts
26
+ import { createRelayClient, RelaySendError } from '@feedbackrelay/web';
27
+
28
+ const relay = createRelayClient({
29
+ appId: 'com.example.app',
30
+ teamId: 'your-team-id',
31
+ relayId: 'your-relay-id',
32
+ publishableKey: 'your-publishable-key',
33
+ // baseUrl: 'https://your-compatible-api.example.com',
34
+ });
35
+
36
+ async function sendMessage(message: string): Promise<void> {
37
+ try {
38
+ const receipt = await relay.send({ message, rating: 3 });
39
+ // Show success after the receipt arrives.
40
+ } catch (error) {
41
+ if (error instanceof RelaySendError) {
42
+ // Show failure; retain error.submissionId for explicit retry.
43
+ }
44
+ }
45
+ }
46
+ ```
47
+
48
+ Call `void sendMessage(message)` from your Submit handler. Without replay, creating the client makes no request or listeners. `appId` is a stable source label, such as `my-website`; it is not an authentication check. Optional `appVersion`, `appBuild` and `context` add metadata. `screenshot: false` is a global privacy restriction; leave it enabled only when your app should allow capture.
49
+
50
+ ## 3. Send forms, errors and files
51
+
52
+ Use your own form, or the HTML example below with id contact. `new FormData(form)` preserves text, repeated fields and selected files as real multipart. Text fields stay strings; use JSON when values should be numbers or booleans. Remove reserved `_relay_` fields before passing an existing HTML form to the SDK; the SDK rejects caller fields with this prefix:
53
+
54
+ ```ts
55
+ const form = document.querySelector<HTMLFormElement>('#contact');
56
+ if (!form) throw new Error('Contact form is missing.');
57
+ form.addEventListener('submit', event => {
58
+ event.preventDefault();
59
+ const values = new FormData(form);
60
+ for (const name of [...values.keys()]) {
61
+ if (name.startsWith('_relay_')) values.delete(name);
62
+ }
63
+ void relay.send(values).then(
64
+ receipt => { /* Show success. */ },
65
+ error => { /* Show failure; keep values for manual retry. */ },
66
+ );
67
+ });
68
+ ```
69
+
70
+ Send an Error directly from your existing error handler. Do not stringify it or replace the app's own error recovery:
71
+
72
+ ```ts
73
+ try {
74
+ // Your app action.
75
+ } catch (appError) {
76
+ try { await relay.send(appError); }
77
+ catch (sendError) { /* Reporting failed; keep normal app recovery. */ }
78
+ }
79
+
80
+ const details: Record<string, unknown> = { screen: 'Checkout' };
81
+ details.self = details;
82
+ await relay.send(details);
83
+ ```
84
+
85
+ Diagnostic input preserves available Error name/message/stack/cause/code and own data, plus dates, maps/sets, bigint and binary length. Ordinary getters and custom `toJSON`/`toString` are skipped; proxies/error formatters can still run host code. For exact application data, use plain JSON with `send` instead.
86
+
87
+ A File or Blob can be sent directly, or added to FormData:
88
+
89
+ ```ts
90
+ const attachment = new Blob(['Example notes'], { type: 'text/plain' });
91
+ const values = new FormData();
92
+ values.append('tag', 'one');
93
+ values.append('tag', 'two');
94
+ values.append('attachment', attachment, 'note.txt');
95
+ await relay.send(values);
96
+ // Or: await relay.send(attachment); // Field name: file.
97
+ ```
98
+
99
+ The SDK snapshots entries without changing your FormData. File/Blob bytes are immutable and are not read into JSON/base64. `_relay_metadata` is added internally; your caller fields may not start `_relay_`. Screenshot upload remains separate from these attachments. Empty file parts count too, including an unselected file input's empty part; remove it in your host only if you intend to omit it.
100
+
101
+ ## 4. Retry, cancel and clean up
102
+
103
+ Keep failed input in your app state. An explicit retry passes that same input and `error.submissionId`; a new submission omits the option:
104
+
105
+ ```ts
106
+ const input = { message: 'Checkout did not respond' };
107
+ let retryId: string | undefined;
108
+ try { await relay.send(input); }
109
+ catch (error) {
110
+ if (error instanceof RelaySendError) retryId = error.submissionId;
111
+ }
112
+ async function retryLastFailure(): Promise<void> {
113
+ if (!retryId) return;
114
+ await relay.send(input, { submissionId: retryId });
115
+ retryId = undefined;
116
+ }
117
+ ```
118
+
119
+ Call `retryLastFailure()` only from your Retry action and handle its rejection in the UI. File retries also require the original files to remain readable. The SDK does not call it automatically.
120
+
121
+ ```ts
122
+ const controller = new AbortController();
123
+ const pending = relay.send({ message: 'Example' }, {
124
+ signal: controller.signal,
125
+ context: { screen: 'Checkout' },
126
+ screenshot: false,
127
+ });
128
+ controller.abort();
129
+ try { await pending; } catch (error) { /* Canceled or already accepted. */ }
130
+ relay.destroy(); // Terminal; cancel sends and release this client.
131
+ ```
132
+
133
+ Retry only on the same client/relay with the saved input/files and ID; a new occurrence gets a new ID. Clear saved retries when replacing the client. A server may have accepted a request before cancellation or a lost response, so it must return the original receipt for that ID.
134
+
135
+ ## Inspect collected data
136
+
137
+ The optional observer supplies collected JSON and the actual captured PNG Blob before delivery. Your app can display that Blob without recapturing or reading a server response:
138
+
139
+ ```ts
140
+ let collectedJSON: string | undefined;
141
+ let screenshotURL: string | undefined;
142
+ function clearScreenshot(image: HTMLImageElement): void {
143
+ image.removeAttribute('src');
144
+ if (screenshotURL) URL.revokeObjectURL(screenshotURL);
145
+ screenshotURL = undefined;
146
+ }
147
+ async function sendWithPreview(input: unknown, image: HTMLImageElement): Promise<void> {
148
+ try {
149
+ const receipt = await relay.send(input, {
150
+ onCollected: (json, png) => {
151
+ collectedJSON = json;
152
+ clearScreenshot(image);
153
+ if (png) image.src = screenshotURL = URL.createObjectURL(png);
154
+ },
155
+ });
156
+ // Show acceptance separately from the local preview.
157
+ } catch (error) { /* Keep the preview; delivery may have failed. */ }
158
+ }
159
+ ```
160
+
161
+ Pass your own `<img alt="Captured app screen" data-relay-private>` element, and clear its URL when replacing/closing it or leaving the page. The Blob is immutable and remains usable after the callback. It is absent when capture is disabled/failed or replay replaces PNG. Video uses the recorder's preview API instead.
162
+
163
+ The first argument is JSON `{ submission, formData? }` with normalized data/metadata and PNG/file descriptors, not binary bytes, SDK keys or internal URIs. Explicit input/context remain. The callback runs once after collection/validation and before delivery; throws/rejected Promises are contained and not awaited. No observer means no preview serialization or UI. A local preview is not a receipt. See the [snapshot reference](https://github.com/apal21/relay-sdk/blob/main/sdk/CONTRACT.md#local-collection-observer).
164
+
165
+ ## Failure behavior
166
+
167
+ For quiet background reporting, use `void relay.send(error)`. The SDK observes an ignored send promise internally without showing UI or logging a failure. The original promise still rejects: use try/catch when awaiting it, and catch failures in any promise chain you create. Invalid client configuration or context updates still throw synchronously; handle those in your setup/action code. Plain HTML actions still navigate to the HTTP response; use the enhanced form for an in-page result.
168
+
169
+ ## Context
170
+
171
+ Use `relay.setContext({ screen: 'Checkout' })` to replace stored context, or `relay.clearContext()` to empty it. The per-send `context` option replaces it for one send. Context must be valid JSON; invalid values leave the previous context unchanged. Values are copied when sending; later changes affect future sends. Cancel old-user sends before clearing identity context on logout.
172
+
173
+ ## Plain HTML without JavaScript
174
+
175
+ No npm package, JavaScript or script tag is needed. Add a normal form using the relay URL as its action. Your browser navigates to a JSON receipt/error; there is no redirect or hosted success UI.
176
+
177
+ A deployed compatible service must support this HTML contract. This repository does not deploy the production Relay backend. Replace the example address/IDs/key with values for your service.
178
+
179
+ ```html
180
+ <form id="contact" method="post" enctype="multipart/form-data" action="https://api.feedbackrelay.app/v1/sdk/teams/YOUR_TEAM/relays/YOUR_RELAY">
181
+ <input type="hidden" name="_relay_key" value="YOUR_PUBLISHABLE_KEY">
182
+ <label>Email <input name="email" type="email" required></label>
183
+ <label>Message <textarea name="message" required></textarea></label>
184
+ <label>Attachment <input name="attachment" type="file"></label>
185
+ <button type="submit">Send</button>
186
+ </form>
187
+ ```
188
+
189
+ URL-encoded fields and real multipart file parts are supported. Add `enctype="multipart/form-data"` and a named file input for attachments. Repeated names are preserved; no SDK diagnostics or screenshot are added. Empty file parts count toward backend limits; do not render a file input when uploads are disabled. `_relay_` names are reserved. Native HTML resubmission creates a new occurrence; it does not have the SDK's explicit retry ID.
190
+
191
+ ## Optional video replay
192
+
193
+ Import replay separately; apps that do not import it do not need its encoder or MP4 writer:
194
+
195
+ ```ts
196
+ import { createRelayClient } from '@feedbackrelay/web';
197
+ import { createReplayRecorder } from '@feedbackrelay/web/replay';
198
+
199
+ const replay = createReplayRecorder({ fps: 'auto' });
200
+ const relay = createRelayClient({
201
+ appId: 'com.example.app', teamId: 'your-team', relayId: 'your-relay',
202
+ publishableKey: 'your-key', replay,
203
+ });
204
+ await relay.send({ message: 'Checkout failed' });
205
+ ```
206
+
207
+ The recorder keeps up to the last ten seconds in memory while the page is visible. `fps` defaults to `auto` (1–5 requested captures/second); a whole number from 1–10 requests a fixed rate. Invalid values fall back to auto. Busy pages can capture fewer frames. Only one recorder can run per page; share it between clients using the same backend URL, team and app. Different relay IDs are allowed.
208
+
209
+ Read `const selectedFPS = replay.currentFPS` for the current adaptive/fixed capture target. It is undefined while inactive, hidden, unavailable or destroyed, and does not measure rendered/encoded/delivered FPS. The getter adds no SDK timer or uploaded data; your app controls label refreshes.
210
+
211
+ **Automatic FPS:** Auto uses smoothed elapsed capture work and a 50 ms-per-second target, without CPU/RAM/battery reads. A cost over 25 ms cannot qualify for 2 FPS; three qualifying checks are needed per increase. Slow rendering can postpone checks. See the [complete web rules](https://github.com/apal21/relay-sdk/blob/main/sdk/CONTRACT.md#automatic-fps-rules).
212
+
213
+ Replay replaces the per-event PNG, including when video is unavailable. `screenshot: false` at initialization or on a send also prohibits that client's replay attachment. Password, private-selector and iframe exclusions apply to replay frames. Attached clients' private selectors are combined; stricter selectors clear previous frame history.
214
+
215
+ The main event returns its normal receipt first. One background worker then creates a silent H.264 MP4 and uses `/replays`, a binary upload ticket, and `/replays/{id}/complete`. Replay failure never turns an accepted event into failure. Capture/encoder omissions are reported best effort; failed media delivery can remain pending or unknown without an extra omission request. No media-completion callback or receipt field is added. Plain HTML posts never record.
216
+
217
+ The recorder uses WebCodecs when available: Chrome/Edge 94+, desktop Firefox 130+, and Safari/iOS Safari 16.4+ are API floors. HTTPS (or localhost), a working H.264 encoder and valid output are required. Firefox Android lacks the required encoder; codec availability also varies by device. Unsupported or failed recording leaves ordinary sends working. These version floors are not a guarantee that every device can encode. Cross-origin assets, video, canvas and unsupported CSS have the same limits as screenshots.
218
+
219
+ The window can be shorter after startup, a keyframe boundary, backgrounding, resize or capture failure. Video is capped at a 720-pixel longest edge and targets 500 kbit/s; actual output varies. The encoded ring is limited to 2 MiB, retained encoded data to 8 MiB and four leases, each expiring after 60 seconds. Browser rendering and encoder buffers use additional memory. Actual peak RAM and CPU overhead have not been benchmarked. Upload jobs have a 30-second budget. No audio, gestures or device-vitals timeline is collected. The automatic rate controller uses local capture timing only.
220
+
221
+ An ordinary event or media-delivery failure retains the same clip until its original 60-second expiry for an explicit same-ID retry. There is no automatic retry. Cancellation, client destruction or expiry releases it. A retry after expiry does not attach a newer recording to the old event. `relay.destroy()` detaches that client; it does not destroy a shared recorder.
222
+
223
+ At an account change, cancel old-user sends, call `replay.clear()` and update context. Context changes alone do not clear shared history. `replay.destroy()` stops recording and cancels retained/background replay work permanently. Neither operation retracts data already accepted by the service. Call these methods from your app's existing lifecycle; the SDK adds no error handlers or UI.
224
+
225
+ ### Play a local preview
226
+
227
+ After attaching an enabled recorder and allowing a few seconds of foreground history, call `preview()` from your own Preview action. It does not send an event or contact the Relay service:
228
+
229
+ ```ts
230
+ let previewURL: string | undefined;
231
+ async function showReplayPreview(player: HTMLVideoElement): Promise<void> {
232
+ clearReplayPreview(player);
233
+ const clip = await replay.preview();
234
+ try {
235
+ if ('omitted' in clip) return; // Show clip.omitted in your UI.
236
+ previewURL = URL.createObjectURL(clip.video);
237
+ player.src = previewURL;
238
+ player.controls = true;
239
+ } finally { clip.release(); }
240
+ }
241
+ function clearReplayPreview(player: HTMLVideoElement): void {
242
+ player.pause();
243
+ player.removeAttribute('src');
244
+ player.load();
245
+ if (previewURL) URL.revokeObjectURL(previewURL);
246
+ previewURL = undefined;
247
+ }
248
+ ```
249
+
250
+ Here `replay` is the recorder above; `player` is your own `<video muted playsinline data-relay-private>` element. Handle `showReplayPreview` errors in your action. A successful result has `video` (Blob; byte size is `video.size`), `width`, `height`, `durationMs`, `startedBeforeEventMs`, `endedBeforeEventMs` and `release()`; an unavailable result has `omitted` and `release()`. Keep only one preview. It shares the existing worker/budgets and expires after 60 seconds. Releasing SDK retention does not revoke an object URL you created; clear it when replacing/closing playback or leaving the page. `clear`/`destroy` discard SDK history, not your handed-out Blob references, which remain outside SDK retention budgets. This is local playback, not an upload result. Existing page-asset rendering limitations still apply.
251
+
252
+ ## Screenshot privacy
253
+
254
+ Web lazily loads html2canvas only when local capture is enabled. It approximates the visible viewport and may miss unsupported CSS, cross-origin assets, video or canvas. It never requests screen sharing.
255
+
256
+ Mark sensitive regions with `data-relay-private`, or configure `privateSelectors: ['.account-details']`. Password inputs and all iframe content are excluded. Exclusions also cover open shadow roots; a private slot omits its owning component. Rendering uses a clone and leaves the live page unchanged, though existing page assets may be fetched. Masking is an aid, not a guarantee that every secret is excluded.
257
+
258
+ Capture failure or an expired capture budget sends without an image. Drawing cannot always be interrupted; late images are ignored. A PNG upload failure fails the send. For `screenshot-too-large`, your UI can offer a retry with capture disabled and the same submission ID.
259
+
260
+ Browser details include viewport, language, screen/input preferences and coarse hardware/network hints where exposed. Native OS/model, battery and available RAM are not collected by the web SDK. Display battery as Unavailable on web; the SDK does not request a separate battery API. No persistent device ID, location, clipboard, logs or disk scan is collected. See the [field reference](https://github.com/apal21/relay-sdk/blob/main/sdk/CONTRACT.md#device-information-and-units) for exact readings and units.
261
+
262
+ ## Service configuration
263
+
264
+ HTTP Content-Type follows the request body: strings, JSON and automatic diagnostics travel inside a JSON envelope as `application/json`. FormData uses `multipart/form-data` with a boundary added by the SDK or transport. File parts keep their own MIME type, such as `text/plain` or `image/png`. Do not override the multipart header yourself.
265
+
266
+ Each send posts directly to `/v1/sdk/teams/{teamId}/relays/{relayId}`, with `X-Relay-Key`. The SDK does not fetch settings. The service must validate keys, relay state, received bytes and quotas.
267
+
268
+ `uploadLimits` is an optional local precheck:
269
+
270
+ ```ts
271
+ const relay = createRelayClient({
272
+ appId: 'com.example.app', teamId: 'your-team', relayId: 'your-relay',
273
+ publishableKey: 'your-key',
274
+ uploadLimits: { maxFiles: 2, maxFileBytes: 1048576, maxTotalFileBytes: 2097152 },
275
+ });
276
+ ```
277
+
278
+ Omitting the object uses 10 files, 3 MiB each and 3 MiB combined. Supply all three nonnegative whole numbers to change them. Any zero disables file parts, including empty files. Client checks are not abuse protection; the service must enforce its own limits.
279
+
280
+ The send result is a receipt with `id`, `submissionId` and `receivedAt` (Swift spells the second field `submissionID`). The [API reference](https://github.com/apal21/relay-sdk/blob/main/sdk/CONTRACT.md) defines the full server contract.
281
+
282
+ ## Limits and data handling
283
+
284
+ | Resource | Limit |
285
+ | --- | --- |
286
+ | JSON data / context | 64 KiB each; 32 levels and 10,000 values |
287
+ | Diagnostic summary | 32 KiB; 8 levels, 500 nodes, 50 entries/container, 8 KiB strings; best-effort 25 ms inspection budget |
288
+ | Final JSON or multipart metadata | 128 KiB |
289
+ | Multipart structure | 1,000 caller parts; 64 KiB field names/text |
290
+ | Field name / filename / MIME | 128 / 255 / 127 UTF-8 bytes |
291
+ | Screenshot | 8 MiB; five-second capture budget, late images ignored |
292
+
293
+ Sizes use encoded UTF-8 bytes; KiB/MiB use 1,024-byte units. These resource limits are separate from local file prechecks and service-enforced quotas. Custom objects can run app code during inspection; the time budget cannot forcibly stop that code.
294
+
295
+ Only diagnostic summaries redact common credential keys. Exact JSON, form fields/files and context are not redacted. Secrets inside strings, stacks or screenshots are not detected. Send only data your app intends to share.
296
+
297
+ Publishable keys identify submission scope, not app authenticity. The service must enforce access, size and rate limits. Licensed under the [Apache License 2.0](LICENSE). Third-party components retain their own licenses.
298
+
299
+ After a receipt, cancelling the completed send does not stop its separate media job. Destroy that client to cancel its media, or clear the recorder to discard all retained history and media.
300
+
301
+ ## Contributor development
302
+
303
+ The npm installation above is all an app needs. To test SDK source changes locally, build an archive from a repository checkout:
304
+
305
+ ```sh
306
+ cd "/path/to/relay-sdk/sdk/web"
307
+ npm ci
308
+ npm pack
309
+ ```
310
+
311
+ Install the generated archive in a separate app:
312
+
313
+ ```sh
314
+ cd "/path/to/your-web-app"
315
+ npm install "/path/to/relay-sdk/sdk/web/feedbackrelay-web-0.1.1.tgz"
316
+ ```
317
+
318
+ Replace the paths with your folders. Repack and reinstall after source changes. `npm pack` does not publish anything.
319
+
320
+ ### Checks
321
+
322
+ From this SDK folder:
323
+
324
+ ```sh
325
+ npm run typecheck
326
+ npm test
327
+ npm run test:package
328
+ npx playwright install chromium firefox webkit
329
+ npm run test:browser -- --workers=1
330
+ ```
331
+
332
+ Run checks serially. The package check verifies included files and importing without browser globals (server rendering). Browser checks require installed browser runtimes. The optional renderer and its notices ship; tests, declarations and documentation are not executed as app runtime code. See [AGENTS.md](AGENTS.md) for agent integration rules and [verification](https://github.com/apal21/relay-sdk/blob/main/sdk/VALIDATION.md) for recorded limits.