react-smart-copy 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,218 @@
1
+ //#region src/core/errors.d.ts
2
+ /**
3
+ * Every way a copy can fail, as a closed union.
4
+ *
5
+ * `CopyError.message` is developer-facing (logs, telemetry). For user-facing
6
+ * text use {@link describeCopyError} or map `type` through your own i18n layer.
7
+ */
8
+ export type CopyErrorType =
9
+ /** No Clipboard API (old browser, server, locked-down webview). Not retryable. */
10
+ 'unsupported' |
11
+ /** Page is not served over HTTPS/localhost. Not retryable. */
12
+ 'insecure-context' |
13
+ /** Browser or user blocked the write. Also what Safari reports for a missing user gesture. */
14
+ 'permission-denied' |
15
+ /** The document lost focus mid-copy (Chromium). Retrying after refocus usually works. */
16
+ 'not-focused' |
17
+ /** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */
18
+ 'invalid-payload' |
19
+ /** The browser cannot write this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */
20
+ 'unsupported-format' |
21
+ /** A lazy image source threw, rejected or did not produce a Blob. */
22
+ 'blob-generation-failed' |
23
+ /** `retry()` was called after `maxRetries` was reached. Terminal. */
24
+ 'max-retries-exceeded' |
25
+ /** Anything the platform threw that we could not classify. */
26
+ 'unknown';
27
+ export interface CopyError {
28
+ readonly type: CopyErrorType;
29
+ readonly message: string;
30
+ readonly cause?: unknown;
31
+ }
32
+ export declare function createCopyError(type: CopyErrorType, message: string, cause?: unknown): CopyError;
33
+ /** Whether retrying the same payload could plausibly succeed. */
34
+ export declare function isRetryableError(error: CopyError): boolean;
35
+ /**
36
+ * Branded (not `instanceof`) so failures stay recognisable even when the core
37
+ * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
38
+ */
39
+ declare const COPY_FAILURE_BRAND: unique symbol;
40
+ /** Error thrown by adapters to carry a fully classified {@link CopyError}. */
41
+ export declare class CopyFailure extends Error {
42
+ readonly copyError: CopyError;
43
+ readonly [COPY_FAILURE_BRAND] = true;
44
+ constructor(copyError: CopyError);
45
+ }
46
+ export declare function isCopyFailure(value: unknown): value is CopyFailure;
47
+ /** Classifies anything thrown by the platform or an adapter into a {@link CopyError}. */
48
+ export declare function toCopyError(cause: unknown): CopyError;
49
+ /** Default English, user-facing sentence for an error. Replace for i18n. */
50
+ export declare function describeCopyError(error: CopyError): string;
51
+ //#endregion
52
+ //#region src/core/payload.d.ts
53
+ /** The only image MIME type with reliable cross-browser clipboard write support. */
54
+ export declare const IMAGE_MIME_TYPE = "image/png";
55
+ /**
56
+ * An image as a Blob, a promise of one, or a function producing one.
57
+ * Prefer the function form: it is invoked synchronously inside the user
58
+ * gesture, which Safari requires for async image generation.
59
+ */
60
+ export type BlobSource = Blob | PromiseLike<Blob> | (() => Blob | PromiseLike<Blob>);
61
+ export interface TextPayload {
62
+ readonly kind: 'text';
63
+ readonly value: string;
64
+ }
65
+ export interface HtmlPayload {
66
+ readonly kind: 'html';
67
+ readonly html: string;
68
+ /** Required plain-text fallback for targets that don't understand HTML. */
69
+ readonly text: string;
70
+ }
71
+ export interface ImagePayload {
72
+ readonly kind: 'image';
73
+ readonly blob: BlobSource;
74
+ }
75
+ export interface JsonPayload {
76
+ readonly kind: 'json';
77
+ readonly value: unknown;
78
+ /** `true` = 2-space indent, a number = that indent, falsy = compact. */
79
+ readonly pretty?: boolean | number;
80
+ }
81
+ export interface MultiPayloadItem {
82
+ readonly mimeType: string;
83
+ readonly data: string | Blob;
84
+ }
85
+ export interface MultiPayload {
86
+ readonly kind: 'multi';
87
+ readonly items: readonly MultiPayloadItem[];
88
+ }
89
+ export type CopyPayload = TextPayload | HtmlPayload | ImagePayload | JsonPayload | MultiPayload;
90
+ export type CopyPayloadKind = CopyPayload['kind'];
91
+ /** A payload, or a bare string as shorthand for `{ kind: 'text' }`. */
92
+ export type CopyInput = string | CopyPayload;
93
+ /**
94
+ * What `copy()` accepts. The function form is resolved synchronously at copy
95
+ * time, so it always reads the latest value without re-rendering.
96
+ */
97
+ export type CopySource = CopyInput | (() => CopyInput);
98
+ export declare function normalizePayload(input: CopyInput): CopyPayload;
99
+ export declare function isBlob(value: unknown): value is Blob;
100
+ /**
101
+ * Structural validation. Typed callers can't produce most of these states,
102
+ * but plain-JS callers and runtime data can, so the check is always on.
103
+ */
104
+ export declare function validatePayload(payload: unknown): CopyError | null;
105
+ /** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */
106
+ export declare function serializeJson(payload: JsonPayload): string;
107
+ //#endregion
108
+ //#region src/core/clipboard-adapter.d.ts
109
+ /** Minimal structural view of `navigator.clipboard`, so fakes and polyfills fit. */
110
+ export interface ClipboardLike {
111
+ writeText?(text: string): Promise<void>;
112
+ write?(items: readonly unknown[]): Promise<void>;
113
+ }
114
+ export type ClipboardItemData = Blob | PromiseLike<Blob>;
115
+ export interface ClipboardItemConstructorLike {
116
+ new (items: Record<string, ClipboardItemData>): unknown;
117
+ supports?(type: string): boolean;
118
+ }
119
+ export interface ClipboardEnvironment {
120
+ readonly isSecureContext?: boolean;
121
+ readonly navigator?: {
122
+ readonly clipboard?: ClipboardLike | undefined;
123
+ } | undefined;
124
+ readonly ClipboardItem?: ClipboardItemConstructorLike | undefined;
125
+ }
126
+ /**
127
+ * The only thing the state machine needs. Implement it to target Electron,
128
+ * a native bridge, a test double, or anything else.
129
+ *
130
+ * Contract: start the platform write synchronously (before any `await`) so the
131
+ * browser still sees the user gesture, and reject with a `CopyFailure` when you
132
+ * can classify the error.
133
+ */
134
+ export interface ClipboardAdapter {
135
+ write(payload: CopyPayload): Promise<void>;
136
+ }
137
+ export interface BrowserClipboardAdapterOptions {
138
+ /** Defaults to `window`, read lazily at copy time (SSR-safe). */
139
+ readonly getEnvironment?: () => ClipboardEnvironment | undefined;
140
+ /** When rich HTML copy is unavailable, fall back to its plain text. Default `true`. */
141
+ readonly degradeHtmlToText?: boolean;
142
+ }
143
+ /** The default adapter: async Clipboard API with feature detection and honest errors. */
144
+ export declare function createBrowserClipboardAdapter(options?: BrowserClipboardAdapterOptions): ClipboardAdapter;
145
+ //#endregion
146
+ //#region src/core/copy-machine.d.ts
147
+ export declare const DEFAULT_RESET_AFTER_MS = 2000;
148
+ export declare const DEFAULT_MAX_RETRIES = 3;
149
+ export interface IdleState {
150
+ readonly status: 'idle';
151
+ }
152
+ export interface CopyingState {
153
+ readonly status: 'copying';
154
+ readonly payload: CopyPayload;
155
+ readonly retryCount: number;
156
+ }
157
+ export interface CopiedState {
158
+ readonly status: 'copied';
159
+ readonly payload: CopyPayload;
160
+ /** Epoch ms when the write resolved. */
161
+ readonly at: number;
162
+ }
163
+ export interface ErrorState {
164
+ readonly status: 'error';
165
+ /** `null` when the input itself could not be resolved. */
166
+ readonly payload: CopyPayload | null;
167
+ readonly error: CopyError;
168
+ readonly retryCount: number;
169
+ }
170
+ export type CopyState = IdleState | CopyingState | CopiedState | ErrorState;
171
+ export type CopyStatus = CopyState['status'];
172
+ export type CopyIgnoredReason = 'in-flight' | 'nothing-to-retry' | 'not-retryable';
173
+ /** What `copy()`/`retry()` resolve to. They never reject. */
174
+ export type CopyOutcome = {
175
+ readonly status: 'copied';
176
+ readonly payload: CopyPayload;
177
+ } | {
178
+ readonly status: 'error';
179
+ readonly error: CopyError;
180
+ } | {
181
+ readonly status: 'ignored';
182
+ readonly reason: CopyIgnoredReason;
183
+ };
184
+ export interface CopyMachineOptions {
185
+ /** Defaults to the browser Clipboard API adapter. */
186
+ readonly adapter?: ClipboardAdapter;
187
+ /** Time in `copied` before returning to `idle`. `false`/`Infinity` disables. Default 2000. */
188
+ readonly resetAfterMs?: number | false;
189
+ /** Max `retry()` calls after the first failure. Default 3. */
190
+ readonly maxRetries?: number;
191
+ readonly onCopy?: (payload: CopyPayload) => void;
192
+ readonly onError?: (error: CopyError, payload: CopyPayload | null) => void;
193
+ /** Clock injection for tests and deterministic environments. */
194
+ readonly now?: () => number;
195
+ }
196
+ /** Options object, or a getter so hosts (like React) can supply the latest options. */
197
+ export type CopyMachineOptionsSource = CopyMachineOptions | (() => CopyMachineOptions);
198
+ export interface CopyMachine {
199
+ readonly getSnapshot: () => CopyState;
200
+ readonly subscribe: (listener: () => void) => () => void;
201
+ readonly copy: (source: CopySource) => Promise<CopyOutcome>;
202
+ readonly retry: () => Promise<CopyOutcome>;
203
+ readonly reset: () => void;
204
+ /**
205
+ * Lifecycle hook for hosts. Re-arms a pending auto-reset; the returned
206
+ * cleanup clears timers, drops in-flight results and unsticks `copying`.
207
+ * Safe to call repeatedly (React StrictMode).
208
+ */
209
+ readonly connect: () => () => void;
210
+ }
211
+ export declare const IDLE_STATE: IdleState;
212
+ export declare function resolveMaxRetries(value: number | undefined): number;
213
+ /** Pure helper: can `retry()` do anything from this state? */
214
+ export declare function canRetryState(state: CopyState, maxRetries?: number): boolean;
215
+ /** Framework-agnostic copy state machine. */
216
+ export declare function createCopyMachine(options?: CopyMachineOptionsSource): CopyMachine;
217
+ //#endregion
218
+ //# sourceMappingURL=core.d.cts.map
package/dist/core.d.ts ADDED
@@ -0,0 +1,218 @@
1
+ //#region src/core/errors.d.ts
2
+ /**
3
+ * Every way a copy can fail, as a closed union.
4
+ *
5
+ * `CopyError.message` is developer-facing (logs, telemetry). For user-facing
6
+ * text use {@link describeCopyError} or map `type` through your own i18n layer.
7
+ */
8
+ export type CopyErrorType =
9
+ /** No Clipboard API (old browser, server, locked-down webview). Not retryable. */
10
+ 'unsupported' |
11
+ /** Page is not served over HTTPS/localhost. Not retryable. */
12
+ 'insecure-context' |
13
+ /** Browser or user blocked the write. Also what Safari reports for a missing user gesture. */
14
+ 'permission-denied' |
15
+ /** The document lost focus mid-copy (Chromium). Retrying after refocus usually works. */
16
+ 'not-focused' |
17
+ /** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */
18
+ 'invalid-payload' |
19
+ /** The browser cannot write this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */
20
+ 'unsupported-format' |
21
+ /** A lazy image source threw, rejected or did not produce a Blob. */
22
+ 'blob-generation-failed' |
23
+ /** `retry()` was called after `maxRetries` was reached. Terminal. */
24
+ 'max-retries-exceeded' |
25
+ /** Anything the platform threw that we could not classify. */
26
+ 'unknown';
27
+ export interface CopyError {
28
+ readonly type: CopyErrorType;
29
+ readonly message: string;
30
+ readonly cause?: unknown;
31
+ }
32
+ export declare function createCopyError(type: CopyErrorType, message: string, cause?: unknown): CopyError;
33
+ /** Whether retrying the same payload could plausibly succeed. */
34
+ export declare function isRetryableError(error: CopyError): boolean;
35
+ /**
36
+ * Branded (not `instanceof`) so failures stay recognisable even when the core
37
+ * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
38
+ */
39
+ declare const COPY_FAILURE_BRAND: unique symbol;
40
+ /** Error thrown by adapters to carry a fully classified {@link CopyError}. */
41
+ export declare class CopyFailure extends Error {
42
+ readonly copyError: CopyError;
43
+ readonly [COPY_FAILURE_BRAND] = true;
44
+ constructor(copyError: CopyError);
45
+ }
46
+ export declare function isCopyFailure(value: unknown): value is CopyFailure;
47
+ /** Classifies anything thrown by the platform or an adapter into a {@link CopyError}. */
48
+ export declare function toCopyError(cause: unknown): CopyError;
49
+ /** Default English, user-facing sentence for an error. Replace for i18n. */
50
+ export declare function describeCopyError(error: CopyError): string;
51
+ //#endregion
52
+ //#region src/core/payload.d.ts
53
+ /** The only image MIME type with reliable cross-browser clipboard write support. */
54
+ export declare const IMAGE_MIME_TYPE = "image/png";
55
+ /**
56
+ * An image as a Blob, a promise of one, or a function producing one.
57
+ * Prefer the function form: it is invoked synchronously inside the user
58
+ * gesture, which Safari requires for async image generation.
59
+ */
60
+ export type BlobSource = Blob | PromiseLike<Blob> | (() => Blob | PromiseLike<Blob>);
61
+ export interface TextPayload {
62
+ readonly kind: 'text';
63
+ readonly value: string;
64
+ }
65
+ export interface HtmlPayload {
66
+ readonly kind: 'html';
67
+ readonly html: string;
68
+ /** Required plain-text fallback for targets that don't understand HTML. */
69
+ readonly text: string;
70
+ }
71
+ export interface ImagePayload {
72
+ readonly kind: 'image';
73
+ readonly blob: BlobSource;
74
+ }
75
+ export interface JsonPayload {
76
+ readonly kind: 'json';
77
+ readonly value: unknown;
78
+ /** `true` = 2-space indent, a number = that indent, falsy = compact. */
79
+ readonly pretty?: boolean | number;
80
+ }
81
+ export interface MultiPayloadItem {
82
+ readonly mimeType: string;
83
+ readonly data: string | Blob;
84
+ }
85
+ export interface MultiPayload {
86
+ readonly kind: 'multi';
87
+ readonly items: readonly MultiPayloadItem[];
88
+ }
89
+ export type CopyPayload = TextPayload | HtmlPayload | ImagePayload | JsonPayload | MultiPayload;
90
+ export type CopyPayloadKind = CopyPayload['kind'];
91
+ /** A payload, or a bare string as shorthand for `{ kind: 'text' }`. */
92
+ export type CopyInput = string | CopyPayload;
93
+ /**
94
+ * What `copy()` accepts. The function form is resolved synchronously at copy
95
+ * time, so it always reads the latest value without re-rendering.
96
+ */
97
+ export type CopySource = CopyInput | (() => CopyInput);
98
+ export declare function normalizePayload(input: CopyInput): CopyPayload;
99
+ export declare function isBlob(value: unknown): value is Blob;
100
+ /**
101
+ * Structural validation. Typed callers can't produce most of these states,
102
+ * but plain-JS callers and runtime data can, so the check is always on.
103
+ */
104
+ export declare function validatePayload(payload: unknown): CopyError | null;
105
+ /** Serialises a JSON payload, throwing a classified failure instead of a raw TypeError. */
106
+ export declare function serializeJson(payload: JsonPayload): string;
107
+ //#endregion
108
+ //#region src/core/clipboard-adapter.d.ts
109
+ /** Minimal structural view of `navigator.clipboard`, so fakes and polyfills fit. */
110
+ export interface ClipboardLike {
111
+ writeText?(text: string): Promise<void>;
112
+ write?(items: readonly unknown[]): Promise<void>;
113
+ }
114
+ export type ClipboardItemData = Blob | PromiseLike<Blob>;
115
+ export interface ClipboardItemConstructorLike {
116
+ new (items: Record<string, ClipboardItemData>): unknown;
117
+ supports?(type: string): boolean;
118
+ }
119
+ export interface ClipboardEnvironment {
120
+ readonly isSecureContext?: boolean;
121
+ readonly navigator?: {
122
+ readonly clipboard?: ClipboardLike | undefined;
123
+ } | undefined;
124
+ readonly ClipboardItem?: ClipboardItemConstructorLike | undefined;
125
+ }
126
+ /**
127
+ * The only thing the state machine needs. Implement it to target Electron,
128
+ * a native bridge, a test double, or anything else.
129
+ *
130
+ * Contract: start the platform write synchronously (before any `await`) so the
131
+ * browser still sees the user gesture, and reject with a `CopyFailure` when you
132
+ * can classify the error.
133
+ */
134
+ export interface ClipboardAdapter {
135
+ write(payload: CopyPayload): Promise<void>;
136
+ }
137
+ export interface BrowserClipboardAdapterOptions {
138
+ /** Defaults to `window`, read lazily at copy time (SSR-safe). */
139
+ readonly getEnvironment?: () => ClipboardEnvironment | undefined;
140
+ /** When rich HTML copy is unavailable, fall back to its plain text. Default `true`. */
141
+ readonly degradeHtmlToText?: boolean;
142
+ }
143
+ /** The default adapter: async Clipboard API with feature detection and honest errors. */
144
+ export declare function createBrowserClipboardAdapter(options?: BrowserClipboardAdapterOptions): ClipboardAdapter;
145
+ //#endregion
146
+ //#region src/core/copy-machine.d.ts
147
+ export declare const DEFAULT_RESET_AFTER_MS = 2000;
148
+ export declare const DEFAULT_MAX_RETRIES = 3;
149
+ export interface IdleState {
150
+ readonly status: 'idle';
151
+ }
152
+ export interface CopyingState {
153
+ readonly status: 'copying';
154
+ readonly payload: CopyPayload;
155
+ readonly retryCount: number;
156
+ }
157
+ export interface CopiedState {
158
+ readonly status: 'copied';
159
+ readonly payload: CopyPayload;
160
+ /** Epoch ms when the write resolved. */
161
+ readonly at: number;
162
+ }
163
+ export interface ErrorState {
164
+ readonly status: 'error';
165
+ /** `null` when the input itself could not be resolved. */
166
+ readonly payload: CopyPayload | null;
167
+ readonly error: CopyError;
168
+ readonly retryCount: number;
169
+ }
170
+ export type CopyState = IdleState | CopyingState | CopiedState | ErrorState;
171
+ export type CopyStatus = CopyState['status'];
172
+ export type CopyIgnoredReason = 'in-flight' | 'nothing-to-retry' | 'not-retryable';
173
+ /** What `copy()`/`retry()` resolve to. They never reject. */
174
+ export type CopyOutcome = {
175
+ readonly status: 'copied';
176
+ readonly payload: CopyPayload;
177
+ } | {
178
+ readonly status: 'error';
179
+ readonly error: CopyError;
180
+ } | {
181
+ readonly status: 'ignored';
182
+ readonly reason: CopyIgnoredReason;
183
+ };
184
+ export interface CopyMachineOptions {
185
+ /** Defaults to the browser Clipboard API adapter. */
186
+ readonly adapter?: ClipboardAdapter;
187
+ /** Time in `copied` before returning to `idle`. `false`/`Infinity` disables. Default 2000. */
188
+ readonly resetAfterMs?: number | false;
189
+ /** Max `retry()` calls after the first failure. Default 3. */
190
+ readonly maxRetries?: number;
191
+ readonly onCopy?: (payload: CopyPayload) => void;
192
+ readonly onError?: (error: CopyError, payload: CopyPayload | null) => void;
193
+ /** Clock injection for tests and deterministic environments. */
194
+ readonly now?: () => number;
195
+ }
196
+ /** Options object, or a getter so hosts (like React) can supply the latest options. */
197
+ export type CopyMachineOptionsSource = CopyMachineOptions | (() => CopyMachineOptions);
198
+ export interface CopyMachine {
199
+ readonly getSnapshot: () => CopyState;
200
+ readonly subscribe: (listener: () => void) => () => void;
201
+ readonly copy: (source: CopySource) => Promise<CopyOutcome>;
202
+ readonly retry: () => Promise<CopyOutcome>;
203
+ readonly reset: () => void;
204
+ /**
205
+ * Lifecycle hook for hosts. Re-arms a pending auto-reset; the returned
206
+ * cleanup clears timers, drops in-flight results and unsticks `copying`.
207
+ * Safe to call repeatedly (React StrictMode).
208
+ */
209
+ readonly connect: () => () => void;
210
+ }
211
+ export declare const IDLE_STATE: IdleState;
212
+ export declare function resolveMaxRetries(value: number | undefined): number;
213
+ /** Pure helper: can `retry()` do anything from this state? */
214
+ export declare function canRetryState(state: CopyState, maxRetries?: number): boolean;
215
+ /** Framework-agnostic copy state machine. */
216
+ export declare function createCopyMachine(options?: CopyMachineOptionsSource): CopyMachine;
217
+ //#endregion
218
+ //# sourceMappingURL=core.d.ts.map