-
-
Notifications
You must be signed in to change notification settings - Fork 236
Expand file tree
/
Copy pathtypes.ts
More file actions
171 lines (159 loc) · 5.33 KB
/
Copy pathtypes.ts
File metadata and controls
171 lines (159 loc) · 5.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/**
* Options accepted by the {@link HookError} constructor.
*/
export interface HookErrorOptions {
/** Root cause object forwarded from the underlying API (typically a {@link SensitiveInfoError}). */
readonly cause?: unknown
/** Identifier describing the hook operation that failed (for example, `useSecretItem.fetch`). */
readonly operation?: string | undefined
/** Human-friendly hint rendered alongside the message in dev-tools / error overlays. */
readonly hint?: string | undefined
}
/**
* Error wrapper surfaced by the public hooks.
*
* Carries the original native error in `cause` plus extra UI-friendly context (`operation`,
* `hint`) so consumers can build rich error states without unwrapping the underlying
* {@link SensitiveInfoError}.
*
* @example
* ```tsx
* const { error } = useSecret('token', { service: 'auth' })
* if (error) console.warn(`[${error.operation}] ${error.message} — ${error.hint}`)
* ```
*/
export class HookError extends Error {
/** Identifier of the hook operation that failed (e.g. `useSecret.save`). */
readonly operation?: string | undefined
/** UI-facing remediation hint (e.g. `'Ask the user to retry biometrics.'`). */
readonly hint?: string | undefined
/**
* @param message - Human-readable description of the failure.
* @param options - Additional metadata; see {@link HookErrorOptions}.
*/
constructor(
message: string,
{ cause, operation, hint }: HookErrorOptions = {}
) {
super(message)
this.name = 'HookError'
this.operation = operation
this.hint = hint
// Assign `cause` directly instead of passing it to `super()` so this
// compiles cleanly under TS configs whose `lib` predates ES2022 (where
// the second `Error` constructor argument was introduced).
if (cause !== undefined) {
;(this as { cause?: unknown }).cause = cause
}
}
}
/**
* Canonical async state contract returned by most hooks.
*
* @typeParam T - Shape of the resolved value (e.g. `string`, {@link SensitiveInfoItem}).
*/
export interface AsyncState<T> {
/** Most recent successful value, or `null` while loading or after an error. */
readonly data: T | null
/** Most recent failure, or `null` when the last operation succeeded. */
readonly error: HookError | null
/** `true` during the initial fetch (no `data` yet). Use this to render skeletons. */
readonly isLoading: boolean
/** `true` while a refetch / mutation is in flight (with stale `data` still present). */
readonly isPending: boolean
}
/**
* Async state contract used by operations that do not emit data (e.g. `clearService`).
*/
export interface VoidAsyncState {
/** Most recent failure, or `null` when the last operation succeeded. */
readonly error: HookError | null
/** `true` during the initial fetch. */
readonly isLoading: boolean
/** `true` while a refetch / mutation is in flight. */
readonly isPending: boolean
}
/**
* Successful outcome of a hook mutation helper. Use the `success` discriminant to narrow.
*/
export interface HookSuccessResult {
/** Always `true`. Discriminant for {@link HookMutationResult}. */
readonly success: true
/** Always `undefined` on success — present so the union narrows cleanly. */
readonly error?: undefined
}
/**
* Failure outcome of a hook mutation helper. Use the `success` discriminant to narrow.
*/
export interface HookFailureResult {
/** Always `false`. Discriminant for {@link HookMutationResult}. */
readonly success: false
/** {@link HookError} describing the failure. */
readonly error: HookError
}
/**
* Discriminated union returned by hook mutation helpers (`saveSecret`, `clearAll`, …).
*
* Mutations never throw — they always resolve with this union so component code can branch with
* a simple `if (!result.success)` check.
*
* @example
* ```tsx
* const result = await saveSecret(value)
* if (!result.success) showToast(result.error.message)
* ```
*/
export type HookMutationResult = HookSuccessResult | HookFailureResult
/**
* Factory used to initialise {@link AsyncState} values.
*
* @typeParam T - Shape of the eventual data payload.
* @returns A frozen initial state with `isLoading: true` and no data/error.
*
* @example
* ```ts
* const [state, setState] = useState(() => createInitialAsyncState<string>())
* ```
*/
export function createInitialAsyncState<T>(): AsyncState<T> {
return {
data: null,
error: null,
isLoading: true,
isPending: false,
}
}
/**
* Factory used to initialise {@link VoidAsyncState} values.
*
* @returns Initial state with `isLoading: false` and no error — mutations idle by default.
*
* @example
* ```ts
* const [state, setState] = useState(() => createInitialVoidState())
* ```
*/
export function createInitialVoidState(): VoidAsyncState {
return {
error: null,
isLoading: false,
isPending: false,
}
}
/**
* Helper used to return a canonical success result from mutation helpers.
*
* @returns `{ success: true }` — narrows {@link HookMutationResult} to {@link HookSuccessResult}.
*/
export function createHookSuccessResult(): HookSuccessResult {
return { success: true }
}
/**
* Helper used to return a canonical failure result from mutation helpers.
*
* @param error - The {@link HookError} that caused the failure.
* @returns `{ success: false, error }` — narrows to {@link HookFailureResult}.
*/
export function createHookFailureResult(error: HookError): HookFailureResult {
return { success: false, error }
}