@codenhub/error 0.0.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/LICENSE +201 -0
- package/README.md +346 -0
- package/dist/index.d.ts +53 -0
- package/dist/index.js +2 -0
- package/dist/registries/browser.d.ts +10 -0
- package/dist/registries/browser.js +32 -0
- package/dist/registries/index.d.ts +3 -0
- package/dist/registries/index.js +3 -0
- package/dist/registries/supabase.d.ts +10 -0
- package/dist/registries/supabase.js +32 -0
- package/dist/src-DrlQ39IZ.js +322 -0
- package/dist/types-D6n8W1xw.d.ts +87 -0
- package/package.json +53 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
# @codenhub/error
|
|
2
|
+
|
|
3
|
+
Typed error normalization and result-style control flow for TypeScript apps. The package starts with an empty error registry by default, so consumers opt into known-error mappings explicitly, including ready-made registries for common platform and library errors.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pnpm add @codenhub/error
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
Configure the app-level `AppError.registry` during initialization, then normalize thrown or returned unknown values into a predictable error shape.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { AppError, err, ok, type Result } from "@codenhub/error";
|
|
17
|
+
|
|
18
|
+
AppError.registry.codes.add("invalid_credentials", {
|
|
19
|
+
message: "Invalid email or password.",
|
|
20
|
+
messageKey: "error.auth.invalidCredentials",
|
|
21
|
+
source: "auth",
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const signIn = async (): Promise<Result<string>> => {
|
|
25
|
+
try {
|
|
26
|
+
return ok("user-id");
|
|
27
|
+
} catch (error) {
|
|
28
|
+
return err(error);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const appError = new AppError({ code: "invalid_credentials" });
|
|
33
|
+
|
|
34
|
+
console.log(appError.message, appError.messageKey);
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Ready registries are opt-in. Merge them into an app-owned registry when the app wants those classifications.
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
import { AppError } from "@codenhub/error";
|
|
41
|
+
import { browserErrorRegistry } from "@codenhub/error/registries/browser";
|
|
42
|
+
import { supabaseErrorRegistry } from "@codenhub/error/registries/supabase";
|
|
43
|
+
|
|
44
|
+
AppError.registry.merge(browserErrorRegistry);
|
|
45
|
+
AppError.registry.merge(supabaseErrorRegistry);
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Reference
|
|
49
|
+
|
|
50
|
+
### `@codenhub/error`
|
|
51
|
+
|
|
52
|
+
Primary entrypoint for app-owned registries, error normalization, and result helpers.
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
import {
|
|
56
|
+
AppError,
|
|
57
|
+
DEFAULT_APP_ERROR_MESSAGE,
|
|
58
|
+
createErrorRegistry,
|
|
59
|
+
err,
|
|
60
|
+
ok,
|
|
61
|
+
type AppErrorOptions,
|
|
62
|
+
type AppErrorSource,
|
|
63
|
+
type AppErrorType,
|
|
64
|
+
type Err,
|
|
65
|
+
type ErrorFeedback,
|
|
66
|
+
type ErrorPatternDefinition,
|
|
67
|
+
type ErrorPatternRegistryBucket,
|
|
68
|
+
type ErrorPrefixDefinition,
|
|
69
|
+
type ErrorPrefixRegistryBucket,
|
|
70
|
+
type ErrorRegistry,
|
|
71
|
+
type ErrorRegistryBucket,
|
|
72
|
+
type Ok,
|
|
73
|
+
type Result,
|
|
74
|
+
} from "@codenhub/error";
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Supported import paths:
|
|
78
|
+
|
|
79
|
+
| Path | Description |
|
|
80
|
+
| ------------------------------------- | ------------------------------------------------------- |
|
|
81
|
+
| `@codenhub/error` | Core error normalization, registry, and result helpers. |
|
|
82
|
+
| `@codenhub/error/registries` | Index of opt-in ready registry presets. |
|
|
83
|
+
| `@codenhub/error/registries/browser` | Browser and Web API error mappings. |
|
|
84
|
+
| `@codenhub/error/registries/supabase` | Supabase error mappings. |
|
|
85
|
+
|
|
86
|
+
#### `createErrorRegistry()`
|
|
87
|
+
|
|
88
|
+
Creates an empty isolated registry. This is also available as `AppError.createRegistry()`.
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
function createErrorRegistry(): ErrorRegistry;
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Use isolated registries for tests, request scopes, tenant-specific mappings, or integrations where mappings should not use the app-level `AppError.registry`.
|
|
95
|
+
|
|
96
|
+
#### `DEFAULT_APP_ERROR_MESSAGE`
|
|
97
|
+
|
|
98
|
+
Default fallback message used when an error has no registry match and no `fallbackMessage` was provided.
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
const DEFAULT_APP_ERROR_MESSAGE = "An unexpected error occurred.";
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
#### `ErrorRegistry`
|
|
105
|
+
|
|
106
|
+
Stores deterministic and heuristic mappings used by `AppError`.
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
interface ErrorRegistry {
|
|
110
|
+
codes: ErrorRegistryBucket;
|
|
111
|
+
names: ErrorRegistryBucket;
|
|
112
|
+
messages: ErrorRegistryBucket;
|
|
113
|
+
prefixes: ErrorPrefixRegistryBucket;
|
|
114
|
+
patterns: ErrorPatternRegistryBucket;
|
|
115
|
+
clear(): void;
|
|
116
|
+
merge(registry: ErrorRegistry): void;
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Code, name, exact message, and prefix matches are deterministic known errors. When multiple prefixes match the same message, the longest normalized prefix wins. Pattern matches are heuristic and should be treated as unexpected errors with better user-facing feedback.
|
|
121
|
+
|
|
122
|
+
`AppError.registry` is mutable and starts empty. `createErrorRegistry()` creates another empty registry with the same bucket API.
|
|
123
|
+
|
|
124
|
+
Registry buckets support adding one mapping at a time or a tuple list:
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
interface ErrorRegistryBucket {
|
|
128
|
+
add(identifier: string, feedback: ErrorFeedback): void;
|
|
129
|
+
addList(entries: readonly (readonly [identifier: string, feedback: ErrorFeedback])[]): void;
|
|
130
|
+
clear(): void;
|
|
131
|
+
get(identifier: string): ErrorFeedback | undefined;
|
|
132
|
+
values(): IterableIterator<[string, ErrorFeedback]>;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
interface ErrorPrefixRegistryBucket {
|
|
136
|
+
add(prefix: string, feedback: ErrorFeedback): void;
|
|
137
|
+
addList(entries: readonly (readonly [prefix: string, feedback: ErrorFeedback])[]): void;
|
|
138
|
+
clear(): void;
|
|
139
|
+
values(): readonly ErrorPrefixDefinition[];
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
interface ErrorPatternRegistryBucket {
|
|
143
|
+
add(pattern: RegExp, feedback: ErrorFeedback): void;
|
|
144
|
+
addList(entries: readonly (readonly [pattern: RegExp, feedback: ErrorFeedback])[]): void;
|
|
145
|
+
clear(): void;
|
|
146
|
+
values(): readonly ErrorPatternDefinition[];
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
`values()` returns defensive copies. Pattern buckets clone `RegExp` values so global or sticky regex state does not leak across classifications.
|
|
151
|
+
|
|
152
|
+
`add()` and `addList()` validate entries immediately and throw `TypeError` for invalid input. Exact and prefix identifiers must be non-empty strings after trimming whitespace and trailing sentence punctuation. Exact identifiers are stored and looked up in that normalized form. Feedback must be an object with a non-empty `message`; optional `messageKey` and `source` values must be strings, and optional `retryable` must be a boolean. Pattern buckets only accept `RegExp` patterns.
|
|
153
|
+
|
|
154
|
+
#### `ErrorFeedback`
|
|
155
|
+
|
|
156
|
+
Feedback stored in registry buckets.
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
interface ErrorFeedback {
|
|
160
|
+
message: string;
|
|
161
|
+
messageKey?: string;
|
|
162
|
+
source?: string;
|
|
163
|
+
retryable?: boolean;
|
|
164
|
+
}
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
`message` should be safe to show to users. `messageKey`, `source`, and `retryable` are optional metadata copied onto matched `AppError` instances.
|
|
168
|
+
|
|
169
|
+
#### `ErrorPrefixDefinition` and `ErrorPatternDefinition`
|
|
170
|
+
|
|
171
|
+
Entries returned by `prefixes.values()` and `patterns.values()`.
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
interface ErrorPrefixDefinition extends ErrorFeedback {
|
|
175
|
+
prefix: string;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
interface ErrorPatternDefinition extends ErrorFeedback {
|
|
179
|
+
pattern: RegExp;
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Most consumers only need these when inspecting, copying, or testing registry contents.
|
|
184
|
+
|
|
185
|
+
#### `AppError`
|
|
186
|
+
|
|
187
|
+
Normalizes an unknown value into a predictable error object. By default, it classifies errors with `AppError.registry`.
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
class AppError extends Error {
|
|
191
|
+
static readonly registry: ErrorRegistry;
|
|
192
|
+
|
|
193
|
+
static createRegistry(): ErrorRegistry;
|
|
194
|
+
|
|
195
|
+
readonly type: "known" | "unexpected" | "unknown";
|
|
196
|
+
readonly message: string;
|
|
197
|
+
readonly messageKey: string | null;
|
|
198
|
+
readonly source: string | null;
|
|
199
|
+
readonly originalError: unknown;
|
|
200
|
+
readonly retryable: boolean;
|
|
201
|
+
|
|
202
|
+
constructor(error: unknown, options?: AppErrorOptions);
|
|
203
|
+
}
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
`AppError` does not throw during construction. If no registry mapping matches, it uses `DEFAULT_APP_ERROR_MESSAGE` or `fallbackMessage` and classifies the value as `"unknown"`.
|
|
207
|
+
|
|
208
|
+
#### `AppErrorType` and `AppErrorSource`
|
|
209
|
+
|
|
210
|
+
Reusable property types for consumers that store or pass around normalized error metadata.
|
|
211
|
+
|
|
212
|
+
```ts
|
|
213
|
+
type AppErrorType = "known" | "unexpected" | "unknown";
|
|
214
|
+
type AppErrorSource = string | null;
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
#### `AppErrorOptions`
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
interface AppErrorOptions {
|
|
221
|
+
fallbackMessage?: string;
|
|
222
|
+
registry?: ErrorRegistry;
|
|
223
|
+
}
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
| Option | Type | Default | Description |
|
|
227
|
+
| ----------------- | --------------- | --------------------------- | --------------------------------------------- |
|
|
228
|
+
| `fallbackMessage` | `string` | `DEFAULT_APP_ERROR_MESSAGE` | Message used when no mapping matches. |
|
|
229
|
+
| `registry` | `ErrorRegistry` | `AppError.registry` | Registry used to classify the provided error. |
|
|
230
|
+
|
|
231
|
+
#### `ok()`
|
|
232
|
+
|
|
233
|
+
Creates a successful result.
|
|
234
|
+
|
|
235
|
+
```ts
|
|
236
|
+
function ok<T>(value: T): { ok: true; value: T };
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
The returned shape is also exported as `Ok<T>`.
|
|
240
|
+
|
|
241
|
+
#### `err()`
|
|
242
|
+
|
|
243
|
+
Creates a failed result containing an `AppError`.
|
|
244
|
+
|
|
245
|
+
```ts
|
|
246
|
+
function err(error: unknown, options?: AppErrorOptions): { ok: false; error: AppError };
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
String errors are also used as the fallback message, so `err("Missing user id")` produces that message when no registry entry matches.
|
|
250
|
+
|
|
251
|
+
The returned shape is also exported as `Err`.
|
|
252
|
+
|
|
253
|
+
#### `Result<T>`
|
|
254
|
+
|
|
255
|
+
Represents success or failure without exceptions.
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
type Result<T> = { ok: true; value: T } | { ok: false; error: AppError };
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
### `@codenhub/error/registries`
|
|
262
|
+
|
|
263
|
+
Index entrypoint for ready registry presets.
|
|
264
|
+
|
|
265
|
+
```ts
|
|
266
|
+
import { browserErrorRegistry, supabaseErrorRegistry } from "@codenhub/error/registries";
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
Ready registries are plain `ErrorRegistry` values intended to be merged into `AppError.registry` or another app-owned registry. Importing a preset does not mutate `AppError.registry`.
|
|
270
|
+
|
|
271
|
+
The preset registry objects are mutable like any other `ErrorRegistry`. Treat imported presets as shared read-only inputs and merge them into an app-owned registry before adding app-specific mappings.
|
|
272
|
+
|
|
273
|
+
### `@codenhub/error/registries/browser`
|
|
274
|
+
|
|
275
|
+
Browser and Web API error mappings.
|
|
276
|
+
|
|
277
|
+
```ts
|
|
278
|
+
import { browserErrorRegistry } from "@codenhub/error/registries/browser";
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
Use this preset when normalizing `DOMException`, fetch, storage, abort, permissions, quota, and other browser API errors.
|
|
282
|
+
|
|
283
|
+
Importing this preset does not require `window`, `document`, `DOMException`, or other browser globals to exist.
|
|
284
|
+
|
|
285
|
+
### `@codenhub/error/registries/supabase`
|
|
286
|
+
|
|
287
|
+
Supabase error mappings.
|
|
288
|
+
|
|
289
|
+
```ts
|
|
290
|
+
import { supabaseErrorRegistry } from "@codenhub/error/registries/supabase";
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
Use this preset when normalizing Supabase Auth, PostgREST, Storage, Realtime, and Edge Functions errors.
|
|
294
|
+
|
|
295
|
+
Importing this preset only creates static error mappings. It does not contact Supabase services or require Supabase client packages.
|
|
296
|
+
|
|
297
|
+
## Examples
|
|
298
|
+
|
|
299
|
+
### Isolate Tests
|
|
300
|
+
|
|
301
|
+
```ts
|
|
302
|
+
import { createErrorRegistry, err } from "@codenhub/error";
|
|
303
|
+
|
|
304
|
+
const errors = createErrorRegistry();
|
|
305
|
+
|
|
306
|
+
errors.names.add("AbortError", {
|
|
307
|
+
message: "Request cancelled.",
|
|
308
|
+
source: "browser",
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
const result = err(new DOMException("Aborted", "AbortError"), { registry: errors });
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
### Merge Presets
|
|
315
|
+
|
|
316
|
+
```ts
|
|
317
|
+
import { AppError } from "@codenhub/error";
|
|
318
|
+
import { browserErrorRegistry, supabaseErrorRegistry } from "@codenhub/error/registries";
|
|
319
|
+
|
|
320
|
+
AppError.registry.merge(browserErrorRegistry);
|
|
321
|
+
AppError.registry.merge(supabaseErrorRegistry);
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
### Add Multiple Mappings
|
|
325
|
+
|
|
326
|
+
```ts
|
|
327
|
+
import { AppError } from "@codenhub/error";
|
|
328
|
+
|
|
329
|
+
AppError.registry.codes.addList([
|
|
330
|
+
["invalid_credentials", { message: "Invalid email or password.", source: "auth" }],
|
|
331
|
+
["email_not_confirmed", { message: "Email address is not confirmed.", source: "auth" }],
|
|
332
|
+
]);
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
## Requirements
|
|
336
|
+
|
|
337
|
+
- TypeScript consumers should use `moduleResolution: "bundler"` or another resolver that understands package `exports`.
|
|
338
|
+
- The core API is intended to run in browsers, Node, SSR, workers, and edge runtimes.
|
|
339
|
+
- Browser-specific registry presets may reference browser error names and messages, but importing them must not require browser globals to exist.
|
|
340
|
+
- The package has no runtime dependencies.
|
|
341
|
+
|
|
342
|
+
## Notes
|
|
343
|
+
|
|
344
|
+
- Registries are opt-in by design. Consumers start from a blank registry to avoid hidden global classifications.
|
|
345
|
+
- Registries, including `AppError.registry` and ready registry presets, are currently mutable. Configure shared registries during app initialization and avoid mutating imported presets at runtime. A future version is expected to provide stronger mutation safeguards.
|
|
346
|
+
- Preset registries should prefer stable error codes or names over message matching when a library provides them.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { a as ErrorPatternDefinition, c as ErrorPrefixRegistryBucket, i as ErrorFeedback, l as ErrorRegistry, n as AppErrorSource, o as ErrorPatternRegistryBucket, r as AppErrorType, s as ErrorPrefixDefinition, t as AppErrorOptions, u as ErrorRegistryBucket } from "./types-D6n8W1xw.js";
|
|
2
|
+
|
|
3
|
+
//#region src/app-error.d.ts
|
|
4
|
+
/** Default message used when no registry entry or fallback message can describe an error. */
|
|
5
|
+
declare const DEFAULT_APP_ERROR_MESSAGE = "An unexpected error occurred.";
|
|
6
|
+
/** Error class that normalizes unknown thrown or returned values into a predictable shape. */
|
|
7
|
+
declare class AppError extends Error {
|
|
8
|
+
/** App-level registry used when no registry is passed to the constructor. */
|
|
9
|
+
static readonly registry: ErrorRegistry;
|
|
10
|
+
/** Creates an isolated registry without modifying the app-level registry. */
|
|
11
|
+
static createRegistry(): ErrorRegistry;
|
|
12
|
+
/** Classification assigned after registry lookup and fallback handling. */
|
|
13
|
+
readonly type: AppErrorType;
|
|
14
|
+
/** User-facing message resolved from registry feedback or fallback handling. */
|
|
15
|
+
readonly message: string;
|
|
16
|
+
/** Optional localization key from matched registry feedback. */
|
|
17
|
+
readonly messageKey: string | null;
|
|
18
|
+
/** Optional source label from matched registry feedback. */
|
|
19
|
+
readonly source: AppErrorSource;
|
|
20
|
+
/** Original value passed to the constructor, or the original value from a wrapped `AppError`. */
|
|
21
|
+
readonly originalError: unknown;
|
|
22
|
+
/** Whether retrying the failed operation is likely to help. */
|
|
23
|
+
readonly retryable: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Normalizes an unknown error value. Construction does not throw; unmatched values become `unknown` errors.
|
|
26
|
+
*/
|
|
27
|
+
constructor(error: unknown, options?: AppErrorOptions);
|
|
28
|
+
private static resolve;
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
//#region src/registry.d.ts
|
|
32
|
+
/** Creates an empty, isolated registry for classifying unknown errors. */
|
|
33
|
+
declare const createErrorRegistry: () => ErrorRegistry;
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/result.d.ts
|
|
36
|
+
/** Successful result value returned by `ok()`. */
|
|
37
|
+
type Ok<T> = {
|
|
38
|
+
ok: true;
|
|
39
|
+
value: T;
|
|
40
|
+
};
|
|
41
|
+
/** Failed result value returned by `err()`. */
|
|
42
|
+
type Err = {
|
|
43
|
+
ok: false;
|
|
44
|
+
error: AppError;
|
|
45
|
+
};
|
|
46
|
+
/** Result union for APIs that return success or failure without throwing. */
|
|
47
|
+
type Result<T> = Ok<T> | Err;
|
|
48
|
+
/** Wraps a value in a successful result. */
|
|
49
|
+
declare const ok: <T>(value: T) => Ok<T>;
|
|
50
|
+
/** Normalizes an unknown error value and wraps it in a failed result. */
|
|
51
|
+
declare const err: (error: unknown, options?: AppErrorOptions) => Err;
|
|
52
|
+
//#endregion
|
|
53
|
+
export { AppError, type AppErrorOptions, type AppErrorSource, type AppErrorType, DEFAULT_APP_ERROR_MESSAGE, type Err, type ErrorFeedback, type ErrorPatternDefinition, type ErrorPatternRegistryBucket, type ErrorPrefixDefinition, type ErrorPrefixRegistryBucket, type ErrorRegistry, type ErrorRegistryBucket, type Ok, type Result, createErrorRegistry, err, ok };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { l as ErrorRegistry } from "../types-D6n8W1xw.js";
|
|
2
|
+
|
|
3
|
+
//#region src/registries/browser.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Opt-in mutable registry preset for common browser and Web API errors.
|
|
6
|
+
* Importing this preset does not mutate `AppError.registry` and does not require browser globals.
|
|
7
|
+
*/
|
|
8
|
+
declare const browserErrorRegistry: ErrorRegistry;
|
|
9
|
+
//#endregion
|
|
10
|
+
export { browserErrorRegistry };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { r as AppError } from "../src-DrlQ39IZ.js";
|
|
2
|
+
//#region src/registries/browser.ts
|
|
3
|
+
/**
|
|
4
|
+
* Opt-in mutable registry preset for common browser and Web API errors.
|
|
5
|
+
* Importing this preset does not mutate `AppError.registry` and does not require browser globals.
|
|
6
|
+
*/
|
|
7
|
+
const browserErrorRegistry = AppError.createRegistry();
|
|
8
|
+
browserErrorRegistry.names.addList([
|
|
9
|
+
["AbortError", {
|
|
10
|
+
message: "Request cancelled.",
|
|
11
|
+
messageKey: "error.browser.abort",
|
|
12
|
+
source: "browser"
|
|
13
|
+
}],
|
|
14
|
+
["QuotaExceededError", {
|
|
15
|
+
message: "Browser storage quota exceeded.",
|
|
16
|
+
messageKey: "error.browser.storageQuotaExceeded",
|
|
17
|
+
source: "browser.storage"
|
|
18
|
+
}],
|
|
19
|
+
["NotAllowedError", {
|
|
20
|
+
message: "Permission was denied.",
|
|
21
|
+
messageKey: "error.browser.permissionDenied",
|
|
22
|
+
source: "browser.permissions"
|
|
23
|
+
}]
|
|
24
|
+
]);
|
|
25
|
+
browserErrorRegistry.patterns.addList([[/failed to fetch|networkerror|load failed/i, {
|
|
26
|
+
message: "Network request failed.",
|
|
27
|
+
messageKey: "error.browser.network",
|
|
28
|
+
source: "browser.network",
|
|
29
|
+
retryable: true
|
|
30
|
+
}]]);
|
|
31
|
+
//#endregion
|
|
32
|
+
export { browserErrorRegistry };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { l as ErrorRegistry } from "../types-D6n8W1xw.js";
|
|
2
|
+
|
|
3
|
+
//#region src/registries/supabase.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Opt-in mutable registry preset for common Supabase Auth, database, and function errors.
|
|
6
|
+
* Importing this preset does not mutate `AppError.registry` or contact Supabase services.
|
|
7
|
+
*/
|
|
8
|
+
declare const supabaseErrorRegistry: ErrorRegistry;
|
|
9
|
+
//#endregion
|
|
10
|
+
export { supabaseErrorRegistry };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { r as AppError } from "../src-DrlQ39IZ.js";
|
|
2
|
+
//#region src/registries/supabase.ts
|
|
3
|
+
/**
|
|
4
|
+
* Opt-in mutable registry preset for common Supabase Auth, database, and function errors.
|
|
5
|
+
* Importing this preset does not mutate `AppError.registry` or contact Supabase services.
|
|
6
|
+
*/
|
|
7
|
+
const supabaseErrorRegistry = AppError.createRegistry();
|
|
8
|
+
supabaseErrorRegistry.codes.addList([
|
|
9
|
+
["invalid_credentials", {
|
|
10
|
+
message: "Invalid email or password.",
|
|
11
|
+
messageKey: "error.supabase.auth.invalidCredentials",
|
|
12
|
+
source: "supabase.auth"
|
|
13
|
+
}],
|
|
14
|
+
["email_not_confirmed", {
|
|
15
|
+
message: "Email address is not confirmed.",
|
|
16
|
+
messageKey: "error.supabase.auth.emailNotConfirmed",
|
|
17
|
+
source: "supabase.auth"
|
|
18
|
+
}],
|
|
19
|
+
["23505", {
|
|
20
|
+
message: "A record with this value already exists.",
|
|
21
|
+
messageKey: "error.supabase.database.uniqueViolation",
|
|
22
|
+
source: "supabase.database"
|
|
23
|
+
}]
|
|
24
|
+
]);
|
|
25
|
+
supabaseErrorRegistry.names.add("FunctionsHttpError", {
|
|
26
|
+
message: "Edge Function request failed.",
|
|
27
|
+
messageKey: "error.supabase.functions.http",
|
|
28
|
+
source: "supabase.functions",
|
|
29
|
+
retryable: true
|
|
30
|
+
});
|
|
31
|
+
//#endregion
|
|
32
|
+
export { supabaseErrorRegistry };
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
//#region src/registry.ts
|
|
2
|
+
const ERROR_IDENTIFIER_TRAILING_PUNCTUATION_PATTERN = /[.!?]+$/;
|
|
3
|
+
const normalizeErrorIdentifier = (identifier) => {
|
|
4
|
+
return identifier.trim().replace(ERROR_IDENTIFIER_TRAILING_PUNCTUATION_PATTERN, "");
|
|
5
|
+
};
|
|
6
|
+
const assertNonEmptyIdentifier = (identifier, label) => {
|
|
7
|
+
if (typeof identifier !== "string" || normalizeErrorIdentifier(identifier).length === 0) throw new TypeError(`Error registry ${label} must be a non-empty string.`);
|
|
8
|
+
};
|
|
9
|
+
const assertFeedback = (feedback) => {
|
|
10
|
+
if (typeof feedback !== "object" || feedback === null) throw new TypeError("Error registry feedback must be an object.");
|
|
11
|
+
if (typeof feedback.message !== "string" || feedback.message.trim().length === 0) throw new TypeError("Error registry feedback.message must be a non-empty string.");
|
|
12
|
+
if (feedback.messageKey !== void 0 && typeof feedback.messageKey !== "string") throw new TypeError("Error registry feedback.messageKey must be a string when provided.");
|
|
13
|
+
if (feedback.source !== void 0 && typeof feedback.source !== "string") throw new TypeError("Error registry feedback.source must be a string when provided.");
|
|
14
|
+
if (feedback.retryable !== void 0 && typeof feedback.retryable !== "boolean") throw new TypeError("Error registry feedback.retryable must be a boolean when provided.");
|
|
15
|
+
};
|
|
16
|
+
const cloneFeedback = (feedback) => ({ ...feedback });
|
|
17
|
+
const createFeedbackMapBucket = () => {
|
|
18
|
+
const entries = /* @__PURE__ */ new Map();
|
|
19
|
+
const add = (identifier, feedback) => {
|
|
20
|
+
assertNonEmptyIdentifier(identifier, "identifier");
|
|
21
|
+
assertFeedback(feedback);
|
|
22
|
+
entries.set(normalizeErrorIdentifier(identifier), cloneFeedback(feedback));
|
|
23
|
+
};
|
|
24
|
+
return {
|
|
25
|
+
add,
|
|
26
|
+
addList(errorEntries) {
|
|
27
|
+
for (const [identifier, feedback] of errorEntries) add(identifier, feedback);
|
|
28
|
+
},
|
|
29
|
+
clear() {
|
|
30
|
+
entries.clear();
|
|
31
|
+
},
|
|
32
|
+
get(identifier) {
|
|
33
|
+
const feedback = entries.get(normalizeErrorIdentifier(identifier));
|
|
34
|
+
return feedback === void 0 ? void 0 : cloneFeedback(feedback);
|
|
35
|
+
},
|
|
36
|
+
values() {
|
|
37
|
+
return Array.from(entries.entries(), ([identifier, feedback]) => [identifier, cloneFeedback(feedback)]).values();
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
const createPrefixBucket = () => {
|
|
42
|
+
const entries = [];
|
|
43
|
+
const add = (prefix, feedback) => {
|
|
44
|
+
assertNonEmptyIdentifier(prefix, "prefix");
|
|
45
|
+
assertFeedback(feedback);
|
|
46
|
+
entries.push({
|
|
47
|
+
...cloneFeedback(feedback),
|
|
48
|
+
prefix: normalizeErrorIdentifier(prefix)
|
|
49
|
+
});
|
|
50
|
+
};
|
|
51
|
+
return {
|
|
52
|
+
add,
|
|
53
|
+
addList(errorEntries) {
|
|
54
|
+
for (const [prefix, feedback] of errorEntries) add(prefix, feedback);
|
|
55
|
+
},
|
|
56
|
+
clear() {
|
|
57
|
+
entries.length = 0;
|
|
58
|
+
},
|
|
59
|
+
values() {
|
|
60
|
+
return entries.map((entry) => ({ ...entry }));
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
};
|
|
64
|
+
const createPatternBucket = () => {
|
|
65
|
+
const entries = [];
|
|
66
|
+
const add = (pattern, feedback) => {
|
|
67
|
+
if (!(pattern instanceof RegExp)) throw new TypeError("Error registry pattern must be a RegExp.");
|
|
68
|
+
assertFeedback(feedback);
|
|
69
|
+
entries.push({
|
|
70
|
+
...cloneFeedback(feedback),
|
|
71
|
+
pattern: new RegExp(pattern.source, pattern.flags)
|
|
72
|
+
});
|
|
73
|
+
};
|
|
74
|
+
return {
|
|
75
|
+
add,
|
|
76
|
+
addList(errorEntries) {
|
|
77
|
+
for (const [pattern, feedback] of errorEntries) add(pattern, feedback);
|
|
78
|
+
},
|
|
79
|
+
clear() {
|
|
80
|
+
entries.length = 0;
|
|
81
|
+
},
|
|
82
|
+
values() {
|
|
83
|
+
return entries.map((entry) => ({
|
|
84
|
+
...entry,
|
|
85
|
+
pattern: new RegExp(entry.pattern.source, entry.pattern.flags)
|
|
86
|
+
}));
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
/** Creates an empty, isolated registry for classifying unknown errors. */
|
|
91
|
+
const createErrorRegistry = () => {
|
|
92
|
+
const codes = createFeedbackMapBucket();
|
|
93
|
+
const names = createFeedbackMapBucket();
|
|
94
|
+
const messages = createFeedbackMapBucket();
|
|
95
|
+
const prefixes = createPrefixBucket();
|
|
96
|
+
const patterns = createPatternBucket();
|
|
97
|
+
return {
|
|
98
|
+
codes,
|
|
99
|
+
names,
|
|
100
|
+
messages,
|
|
101
|
+
prefixes,
|
|
102
|
+
patterns,
|
|
103
|
+
clear() {
|
|
104
|
+
codes.clear();
|
|
105
|
+
names.clear();
|
|
106
|
+
messages.clear();
|
|
107
|
+
prefixes.clear();
|
|
108
|
+
patterns.clear();
|
|
109
|
+
},
|
|
110
|
+
merge(sourceRegistry) {
|
|
111
|
+
for (const [identifier, feedback] of sourceRegistry.codes.values()) codes.add(identifier, feedback);
|
|
112
|
+
for (const [identifier, feedback] of sourceRegistry.names.values()) names.add(identifier, feedback);
|
|
113
|
+
for (const [identifier, feedback] of sourceRegistry.messages.values()) messages.add(identifier, feedback);
|
|
114
|
+
for (const { prefix, ...feedback } of sourceRegistry.prefixes.values()) prefixes.add(prefix, feedback);
|
|
115
|
+
for (const { pattern, ...feedback } of sourceRegistry.patterns.values()) patterns.add(pattern, feedback);
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
//#endregion
|
|
120
|
+
//#region src/normalize.ts
|
|
121
|
+
const ERROR_UNWRAP_MAX_DEPTH = 3;
|
|
122
|
+
const ERROR_WRAPPER_FIELD_NAMES = [
|
|
123
|
+
"cause",
|
|
124
|
+
"originalError",
|
|
125
|
+
"error"
|
|
126
|
+
];
|
|
127
|
+
const isRecord = (value) => {
|
|
128
|
+
return typeof value === "object" && value !== null;
|
|
129
|
+
};
|
|
130
|
+
const getRecordField = (source, key) => {
|
|
131
|
+
try {
|
|
132
|
+
return source[key];
|
|
133
|
+
} catch {
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
const getStringField = (source, key) => {
|
|
138
|
+
const value = getRecordField(source, key);
|
|
139
|
+
return typeof value === "string" ? value : null;
|
|
140
|
+
};
|
|
141
|
+
const toKnownClassification = (feedback) => ({
|
|
142
|
+
type: "known",
|
|
143
|
+
message: feedback.message,
|
|
144
|
+
messageKey: feedback.messageKey ?? null,
|
|
145
|
+
source: feedback.source ?? null,
|
|
146
|
+
retryable: feedback.retryable ?? false
|
|
147
|
+
});
|
|
148
|
+
const toUnexpectedClassification = (feedback) => ({
|
|
149
|
+
type: "unexpected",
|
|
150
|
+
message: feedback.message,
|
|
151
|
+
messageKey: feedback.messageKey ?? null,
|
|
152
|
+
source: feedback.source ?? null,
|
|
153
|
+
retryable: feedback.retryable ?? false
|
|
154
|
+
});
|
|
155
|
+
const normalizeError = (error) => {
|
|
156
|
+
if (typeof error === "string") return {
|
|
157
|
+
code: null,
|
|
158
|
+
message: error,
|
|
159
|
+
name: null
|
|
160
|
+
};
|
|
161
|
+
if (!isRecord(error)) return {
|
|
162
|
+
code: null,
|
|
163
|
+
message: null,
|
|
164
|
+
name: null
|
|
165
|
+
};
|
|
166
|
+
return {
|
|
167
|
+
code: getStringField(error, "code"),
|
|
168
|
+
message: getStringField(error, "message"),
|
|
169
|
+
name: getStringField(error, "name")
|
|
170
|
+
};
|
|
171
|
+
};
|
|
172
|
+
const getWrappedErrorCandidates = (error) => {
|
|
173
|
+
if (!isRecord(error)) return [];
|
|
174
|
+
return ERROR_WRAPPER_FIELD_NAMES.map((fieldName) => getRecordField(error, fieldName)).filter((value) => value !== void 0 && value !== null);
|
|
175
|
+
};
|
|
176
|
+
const getErrorCandidates = (error) => {
|
|
177
|
+
const candidates = [];
|
|
178
|
+
const visitedObjects = /* @__PURE__ */ new Set();
|
|
179
|
+
if (isRecord(error)) visitedObjects.add(error);
|
|
180
|
+
const pendingCandidates = [{
|
|
181
|
+
depth: 0,
|
|
182
|
+
value: error
|
|
183
|
+
}];
|
|
184
|
+
for (let index = 0; index < pendingCandidates.length; index += 1) {
|
|
185
|
+
const candidate = pendingCandidates[index];
|
|
186
|
+
candidates.push(candidate.value);
|
|
187
|
+
if (candidate.depth >= ERROR_UNWRAP_MAX_DEPTH) continue;
|
|
188
|
+
for (const wrappedErrorCandidate of getWrappedErrorCandidates(candidate.value)) {
|
|
189
|
+
if (isRecord(wrappedErrorCandidate)) {
|
|
190
|
+
if (visitedObjects.has(wrappedErrorCandidate)) continue;
|
|
191
|
+
visitedObjects.add(wrappedErrorCandidate);
|
|
192
|
+
}
|
|
193
|
+
pendingCandidates.push({
|
|
194
|
+
depth: candidate.depth + 1,
|
|
195
|
+
value: wrappedErrorCandidate
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return candidates;
|
|
200
|
+
};
|
|
201
|
+
const getKnownMessageFeedback = (registry, message) => {
|
|
202
|
+
const normalizedMessage = normalizeErrorIdentifier(message);
|
|
203
|
+
for (const [registeredMessage, feedback] of registry.messages.values()) if (normalizeErrorIdentifier(registeredMessage) === normalizedMessage) return toKnownClassification(feedback);
|
|
204
|
+
const prefixDefinition = registry.prefixes.values().filter((definition) => normalizedMessage.startsWith(definition.prefix)).sort((firstDefinition, secondDefinition) => secondDefinition.prefix.length - firstDefinition.prefix.length)[0];
|
|
205
|
+
if (prefixDefinition === void 0) return null;
|
|
206
|
+
return toKnownClassification(prefixDefinition);
|
|
207
|
+
};
|
|
208
|
+
const resolveDeterministicKnownError = (registry, { code, message, name }) => {
|
|
209
|
+
if (code !== null) {
|
|
210
|
+
const feedback = registry.codes.get(code);
|
|
211
|
+
if (feedback !== void 0) return toKnownClassification(feedback);
|
|
212
|
+
}
|
|
213
|
+
if (name !== null) {
|
|
214
|
+
const feedback = registry.names.get(name);
|
|
215
|
+
if (feedback !== void 0) return toKnownClassification(feedback);
|
|
216
|
+
}
|
|
217
|
+
if (message !== null) {
|
|
218
|
+
const feedback = getKnownMessageFeedback(registry, message);
|
|
219
|
+
if (feedback !== null) return feedback;
|
|
220
|
+
}
|
|
221
|
+
return null;
|
|
222
|
+
};
|
|
223
|
+
const resolveHeuristicUnexpectedError = (registry, { message }) => {
|
|
224
|
+
if (message === null) return null;
|
|
225
|
+
const definition = registry.patterns.values().find((currentDefinition) => {
|
|
226
|
+
return new RegExp(currentDefinition.pattern.source, currentDefinition.pattern.flags).test(message);
|
|
227
|
+
});
|
|
228
|
+
if (definition === void 0) return null;
|
|
229
|
+
return toUnexpectedClassification(definition);
|
|
230
|
+
};
|
|
231
|
+
const classifyErrorCandidate = (registry, error) => {
|
|
232
|
+
const normalizedError = normalizeError(error);
|
|
233
|
+
const knownError = resolveDeterministicKnownError(registry, normalizedError);
|
|
234
|
+
if (knownError !== null) return knownError;
|
|
235
|
+
return resolveHeuristicUnexpectedError(registry, normalizedError);
|
|
236
|
+
};
|
|
237
|
+
//#endregion
|
|
238
|
+
//#region src/app-error.ts
|
|
239
|
+
/** Default message used when no registry entry or fallback message can describe an error. */
|
|
240
|
+
const DEFAULT_APP_ERROR_MESSAGE = "An unexpected error occurred.";
|
|
241
|
+
/** Error class that normalizes unknown thrown or returned values into a predictable shape. */
|
|
242
|
+
var AppError = class AppError extends Error {
|
|
243
|
+
/** App-level registry used when no registry is passed to the constructor. */
|
|
244
|
+
static registry = createErrorRegistry();
|
|
245
|
+
/** Creates an isolated registry without modifying the app-level registry. */
|
|
246
|
+
static createRegistry() {
|
|
247
|
+
return createErrorRegistry();
|
|
248
|
+
}
|
|
249
|
+
/** Classification assigned after registry lookup and fallback handling. */
|
|
250
|
+
type;
|
|
251
|
+
/** Optional localization key from matched registry feedback. */
|
|
252
|
+
messageKey;
|
|
253
|
+
/** Optional source label from matched registry feedback. */
|
|
254
|
+
source;
|
|
255
|
+
/** Original value passed to the constructor, or the original value from a wrapped `AppError`. */
|
|
256
|
+
originalError;
|
|
257
|
+
/** Whether retrying the failed operation is likely to help. */
|
|
258
|
+
retryable;
|
|
259
|
+
/**
|
|
260
|
+
* Normalizes an unknown error value. Construction does not throw; unmatched values become `unknown` errors.
|
|
261
|
+
*/
|
|
262
|
+
constructor(error, options = {}) {
|
|
263
|
+
const resolved = AppError.resolve(error, options);
|
|
264
|
+
super(resolved.message);
|
|
265
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
266
|
+
this.name = "AppError";
|
|
267
|
+
this.type = resolved.type;
|
|
268
|
+
this.messageKey = resolved.messageKey;
|
|
269
|
+
this.source = resolved.source;
|
|
270
|
+
this.originalError = resolved.originalError;
|
|
271
|
+
this.retryable = resolved.retryable;
|
|
272
|
+
}
|
|
273
|
+
static resolve(error, options) {
|
|
274
|
+
if (error instanceof AppError) return {
|
|
275
|
+
type: error.type,
|
|
276
|
+
message: error.message,
|
|
277
|
+
messageKey: error.messageKey,
|
|
278
|
+
source: error.source,
|
|
279
|
+
originalError: error.originalError,
|
|
280
|
+
retryable: error.retryable
|
|
281
|
+
};
|
|
282
|
+
const fallbackMessage = options.fallbackMessage ?? "An unexpected error occurred.";
|
|
283
|
+
const errorCandidates = getErrorCandidates(error);
|
|
284
|
+
const registry = options.registry ?? AppError.registry;
|
|
285
|
+
for (const errorCandidate of errorCandidates) {
|
|
286
|
+
const classification = classifyErrorCandidate(registry, errorCandidate);
|
|
287
|
+
if (classification !== null) return {
|
|
288
|
+
type: classification.type,
|
|
289
|
+
message: classification.message,
|
|
290
|
+
messageKey: classification.messageKey,
|
|
291
|
+
source: classification.source,
|
|
292
|
+
originalError: error,
|
|
293
|
+
retryable: classification.retryable
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
return {
|
|
297
|
+
type: "unknown",
|
|
298
|
+
message: fallbackMessage,
|
|
299
|
+
messageKey: null,
|
|
300
|
+
source: null,
|
|
301
|
+
originalError: error,
|
|
302
|
+
retryable: false
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
//#endregion
|
|
307
|
+
//#region src/result.ts
|
|
308
|
+
/** Wraps a value in a successful result. */
|
|
309
|
+
const ok = (value) => ({
|
|
310
|
+
ok: true,
|
|
311
|
+
value
|
|
312
|
+
});
|
|
313
|
+
/** Normalizes an unknown error value and wraps it in a failed result. */
|
|
314
|
+
const err = (error, options = {}) => ({
|
|
315
|
+
ok: false,
|
|
316
|
+
error: new AppError(error, typeof error === "string" ? {
|
|
317
|
+
fallbackMessage: error,
|
|
318
|
+
...options
|
|
319
|
+
} : options)
|
|
320
|
+
});
|
|
321
|
+
//#endregion
|
|
322
|
+
export { createErrorRegistry as a, DEFAULT_APP_ERROR_MESSAGE as i, ok as n, AppError as r, err as t };
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
//#region src/types.d.ts
|
|
2
|
+
/** Options that control how unknown errors are normalized. */
|
|
3
|
+
interface AppErrorOptions {
|
|
4
|
+
/** Message used when the error cannot be matched by the selected registry. */
|
|
5
|
+
fallbackMessage?: string;
|
|
6
|
+
/** Registry used for classification. Defaults to the app-level `AppError.registry`. */
|
|
7
|
+
registry?: ErrorRegistry;
|
|
8
|
+
}
|
|
9
|
+
/** Classification assigned to a normalized application error. */
|
|
10
|
+
type AppErrorType = "known" | "unexpected" | "unknown";
|
|
11
|
+
/** Optional source label for the system, package, or integration that produced an error. */
|
|
12
|
+
type AppErrorSource = string | null;
|
|
13
|
+
/** Consumer-facing feedback returned when a registry entry matches an error. */
|
|
14
|
+
interface ErrorFeedback {
|
|
15
|
+
/** Safe user-facing message for the matched error. */
|
|
16
|
+
message: string;
|
|
17
|
+
/** Optional localization key for the message. */
|
|
18
|
+
messageKey?: string;
|
|
19
|
+
/** Optional source label, such as `auth`, `browser.network`, or `supabase.database`. */
|
|
20
|
+
source?: string;
|
|
21
|
+
/** Whether retrying the failed operation is likely to help. Defaults to `false`. */
|
|
22
|
+
retryable?: boolean;
|
|
23
|
+
}
|
|
24
|
+
/** Registry bucket for exact string identifiers such as error codes, names, or messages. */
|
|
25
|
+
interface ErrorRegistryBucket {
|
|
26
|
+
/** Adds or replaces feedback for one normalized non-empty identifier, throwing `TypeError` for invalid input. */
|
|
27
|
+
add(identifier: string, feedback: ErrorFeedback): void;
|
|
28
|
+
/** Adds or replaces feedback for multiple normalized identifiers, throwing `TypeError` when any entry is invalid. */
|
|
29
|
+
addList(entries: readonly (readonly [identifier: string, feedback: ErrorFeedback])[]): void;
|
|
30
|
+
/** Removes all entries from this bucket. */
|
|
31
|
+
clear(): void;
|
|
32
|
+
/** Returns a defensive copy of feedback for a normalized identifier when present. */
|
|
33
|
+
get(identifier: string): ErrorFeedback | undefined;
|
|
34
|
+
/** Returns defensive copies of all bucket entries. */
|
|
35
|
+
values(): IterableIterator<[string, ErrorFeedback]>;
|
|
36
|
+
}
|
|
37
|
+
/** Stored prefix mapping returned by prefix registry bucket inspection. */
|
|
38
|
+
interface ErrorPrefixDefinition extends ErrorFeedback {
|
|
39
|
+
/** Message prefix that is matched after trimming trailing sentence punctuation. */
|
|
40
|
+
prefix: string;
|
|
41
|
+
}
|
|
42
|
+
/** Stored pattern mapping returned by pattern registry bucket inspection. */
|
|
43
|
+
interface ErrorPatternDefinition extends ErrorFeedback {
|
|
44
|
+
/** Regular expression used for heuristic message matching. */
|
|
45
|
+
pattern: RegExp;
|
|
46
|
+
}
|
|
47
|
+
/** Registry bucket for known errors matched by longest normalized message prefix. */
|
|
48
|
+
interface ErrorPrefixRegistryBucket {
|
|
49
|
+
/** Adds prefix feedback after normalization, throwing `TypeError` for empty prefixes or invalid feedback. */
|
|
50
|
+
add(prefix: string, feedback: ErrorFeedback): void;
|
|
51
|
+
/** Adds multiple prefix feedback entries, throwing `TypeError` when any entry is invalid. */
|
|
52
|
+
addList(entries: readonly (readonly [prefix: string, feedback: ErrorFeedback])[]): void;
|
|
53
|
+
/** Removes all prefix entries. */
|
|
54
|
+
clear(): void;
|
|
55
|
+
/** Returns defensive copies of all prefix definitions. */
|
|
56
|
+
values(): readonly ErrorPrefixDefinition[];
|
|
57
|
+
}
|
|
58
|
+
/** Registry bucket for unexpected errors matched heuristically by message pattern. */
|
|
59
|
+
interface ErrorPatternRegistryBucket {
|
|
60
|
+
/** Adds pattern feedback, throwing `TypeError` for non-`RegExp` patterns or invalid feedback. */
|
|
61
|
+
add(pattern: RegExp, feedback: ErrorFeedback): void;
|
|
62
|
+
/** Adds multiple pattern feedback entries, throwing `TypeError` when any entry is invalid. */
|
|
63
|
+
addList(entries: readonly (readonly [pattern: RegExp, feedback: ErrorFeedback])[]): void;
|
|
64
|
+
/** Removes all pattern entries. */
|
|
65
|
+
clear(): void;
|
|
66
|
+
/** Returns defensive copies of all pattern definitions. */
|
|
67
|
+
values(): readonly ErrorPatternDefinition[];
|
|
68
|
+
}
|
|
69
|
+
/** Mutable collection of exact and heuristic mappings used to classify unknown errors. */
|
|
70
|
+
interface ErrorRegistry {
|
|
71
|
+
/** Exact error-code mappings, usually from APIs or databases. */
|
|
72
|
+
codes: ErrorRegistryBucket;
|
|
73
|
+
/** Exact error-name mappings, usually from `Error.name` or `DOMException.name`. */
|
|
74
|
+
names: ErrorRegistryBucket;
|
|
75
|
+
/** Exact error-message mappings after light punctuation normalization. */
|
|
76
|
+
messages: ErrorRegistryBucket;
|
|
77
|
+
/** Known-error mappings by normalized message prefix. */
|
|
78
|
+
prefixes: ErrorPrefixRegistryBucket;
|
|
79
|
+
/** Heuristic mappings by message pattern, classified as `unexpected`. */
|
|
80
|
+
patterns: ErrorPatternRegistryBucket;
|
|
81
|
+
/** Removes all mappings from every bucket. */
|
|
82
|
+
clear(): void;
|
|
83
|
+
/** Copies all mappings from another registry into this registry. */
|
|
84
|
+
merge(registry: ErrorRegistry): void;
|
|
85
|
+
}
|
|
86
|
+
//#endregion
|
|
87
|
+
export { ErrorPatternDefinition as a, ErrorPrefixRegistryBucket as c, ErrorFeedback as i, ErrorRegistry as l, AppErrorSource as n, ErrorPatternRegistryBucket as o, AppErrorType as r, ErrorPrefixDefinition as s, AppErrorOptions as t, ErrorRegistryBucket as u };
|
package/package.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@codenhub/error",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"private": false,
|
|
5
|
+
"description": "Typed error normalization, result helpers, and opt-in registry presets for TypeScript apps.",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/codenhub/codenhub.git",
|
|
10
|
+
"directory": "packages/error"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"dist"
|
|
14
|
+
],
|
|
15
|
+
"type": "module",
|
|
16
|
+
"main": "./dist/index.js",
|
|
17
|
+
"module": "./dist/index.js",
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"import": "./dist/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./registries": {
|
|
25
|
+
"types": "./dist/registries/index.d.ts",
|
|
26
|
+
"import": "./dist/registries/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./registries/browser": {
|
|
29
|
+
"types": "./dist/registries/browser.d.ts",
|
|
30
|
+
"import": "./dist/registries/browser.js"
|
|
31
|
+
},
|
|
32
|
+
"./registries/supabase": {
|
|
33
|
+
"types": "./dist/registries/supabase.d.ts",
|
|
34
|
+
"import": "./dist/registries/supabase.js"
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"access": "public"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@vitest/coverage-v8": "4.1.8",
|
|
42
|
+
"tsdown": "^0.22.2",
|
|
43
|
+
"typescript": "^6.0.3",
|
|
44
|
+
"vitest": "^4.0.17"
|
|
45
|
+
},
|
|
46
|
+
"scripts": {
|
|
47
|
+
"build": "tsdown src/index.ts src/registries/index.ts src/registries/browser.ts src/registries/supabase.ts --format esm --dts --clean --no-fixed-extension",
|
|
48
|
+
"test": "vitest run",
|
|
49
|
+
"test:coverage": "vitest run --coverage",
|
|
50
|
+
"test:watch": "vitest",
|
|
51
|
+
"typecheck": "tsc --noEmit"
|
|
52
|
+
}
|
|
53
|
+
}
|