@buffcore/sdk 0.0.0-stage → 0.8.39
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 +202 -0
- package/NOTICE +4 -0
- package/README.md +8 -2
- package/dist/api-error.d.ts +18 -0
- package/dist/api-error.js +30 -0
- package/dist/client-destination.d.ts +7 -0
- package/dist/client-destination.js +62 -0
- package/dist/client.d.ts +110 -0
- package/dist/client.js +175 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/leaks.d.ts +8 -0
- package/dist/leaks.js +21 -0
- package/dist/network.d.ts +11 -0
- package/dist/network.js +15 -0
- package/dist/react.d.ts +11 -0
- package/dist/react.js +29 -0
- package/dist/realtime-outbox.d.ts +12 -0
- package/dist/realtime-outbox.js +60 -0
- package/dist/realtime-types.d.ts +91 -0
- package/dist/realtime-types.js +0 -0
- package/dist/realtime.d.ts +6 -0
- package/dist/realtime.js +266 -0
- package/dist/tracker.d.ts +27 -0
- package/dist/tracker.js +41 -0
- package/package.json +49 -3
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/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @buffcore/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Typed client built from BuffCore route schemas, with auth, the event tracker, React hooks and live sessions.
|
|
4
|
+
|
|
5
|
+
Part of [BuffApe](https://github.com/buffape/buffape), the open-source way to build a product with AI agents. Start one with `npm create @buffcore@latest my-app`.
|
|
6
|
+
|
|
7
|
+
## License
|
|
8
|
+
|
|
9
|
+
Apache-2.0. Copyright © 2026 BuffApe. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ApiError } from '@buffcore/contracts';
|
|
2
|
+
/** A failed API call, in the one error shape. Show `text(t)`. */
|
|
3
|
+
export declare class ApiCallError extends Error implements ApiError {
|
|
4
|
+
name: string;
|
|
5
|
+
readonly status: number;
|
|
6
|
+
readonly code: string;
|
|
7
|
+
readonly messageKey: string;
|
|
8
|
+
readonly details?: Record<string, unknown>;
|
|
9
|
+
readonly requestId?: string;
|
|
10
|
+
/** Whether `message` is the server's sentence (it is the code otherwise). */
|
|
11
|
+
private readonly told;
|
|
12
|
+
constructor(status: number, body: Partial<ApiError>);
|
|
13
|
+
/**
|
|
14
|
+
* The error in the reader's words: `t(messageKey)` when the client's catalogs have the key (`t`
|
|
15
|
+
* gives the key back when they don't), else the sentence the server sent in the same language.
|
|
16
|
+
*/
|
|
17
|
+
text(t: (key: string, values?: Record<string, unknown>) => string): string;
|
|
18
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** A failed API call, in the one error shape. Show `text(t)`. */
|
|
2
|
+
export class ApiCallError extends Error {
|
|
3
|
+
name = 'ApiCallError';
|
|
4
|
+
status;
|
|
5
|
+
code;
|
|
6
|
+
messageKey;
|
|
7
|
+
details;
|
|
8
|
+
requestId;
|
|
9
|
+
/** Whether `message` is the server's sentence (it is the code otherwise). */
|
|
10
|
+
told;
|
|
11
|
+
constructor(status, body) {
|
|
12
|
+
super(body.message ?? body.code ?? `http_${status}`);
|
|
13
|
+
this.status = status;
|
|
14
|
+
this.code = body.code ?? 'internal';
|
|
15
|
+
this.messageKey = body.messageKey ?? 'core.errors.internal';
|
|
16
|
+
this.told = Boolean(body.message);
|
|
17
|
+
if (body.details)
|
|
18
|
+
this.details = body.details;
|
|
19
|
+
if (body.requestId)
|
|
20
|
+
this.requestId = body.requestId;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The error in the reader's words: `t(messageKey)` when the client's catalogs have the key (`t`
|
|
24
|
+
* gives the key back when they don't), else the sentence the server sent in the same language.
|
|
25
|
+
*/
|
|
26
|
+
text(t) {
|
|
27
|
+
const own = t(this.messageKey, this.details);
|
|
28
|
+
return own === this.messageKey && this.told ? this.message : own;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ClientOptions, DeviceHeaders } from './client.ts';
|
|
2
|
+
/** Resolve the URL before signing it and keep the account header on the API origin. */
|
|
3
|
+
export declare function clientDestination(options: ClientOptions): {
|
|
4
|
+
headers: (json: boolean, device: DeviceHeaders | null) => Promise<Record<string, string>>;
|
|
5
|
+
resolve: (path: string) => URL;
|
|
6
|
+
send: (url: URL, init: RequestInit, unscoped: boolean) => Promise<Response>;
|
|
7
|
+
};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { ACCOUNT_HEADER } from '@buffcore/contracts';
|
|
2
|
+
import { DEVICE_HEADER, PROFILE_HEADER } from '@buffcore/contracts/devices';
|
|
3
|
+
const UNSCOPED_PATH = /^\/(?:health|v1\/(?:auth|sign-up|sign-in|devices?|legal|errors|events|maintenance))(?:\/|$)/;
|
|
4
|
+
const prefixOf = (url) => url.pathname.replace(/\/+$/, '');
|
|
5
|
+
function under(url, base) {
|
|
6
|
+
const prefix = prefixOf(base);
|
|
7
|
+
return (url.origin === base.origin && (url.pathname === prefix || url.pathname.startsWith(`${prefix}/`)));
|
|
8
|
+
}
|
|
9
|
+
/** Resolve the URL before signing it and keep the account header on the API origin. */
|
|
10
|
+
export function clientDestination(options) {
|
|
11
|
+
const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
12
|
+
const browser = globalThis;
|
|
13
|
+
const apiUrl = () => new URL(options.baseUrl, browser.location?.href);
|
|
14
|
+
async function headers(json, device) {
|
|
15
|
+
const h = { ...options.headers };
|
|
16
|
+
if (json)
|
|
17
|
+
h['content-type'] = 'application/json';
|
|
18
|
+
const language = options.getLocale?.();
|
|
19
|
+
if (language)
|
|
20
|
+
h['accept-language'] = language;
|
|
21
|
+
const screen = options.getScreen?.();
|
|
22
|
+
if (screen)
|
|
23
|
+
h['x-ape-screen'] = screen;
|
|
24
|
+
if (device) {
|
|
25
|
+
h[DEVICE_HEADER] = device.secret;
|
|
26
|
+
if (device.profileId)
|
|
27
|
+
h[PROFILE_HEADER] = device.profileId;
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
const token = await options.getToken?.();
|
|
31
|
+
if (token)
|
|
32
|
+
h.authorization = `Bearer ${token}`;
|
|
33
|
+
}
|
|
34
|
+
return h;
|
|
35
|
+
}
|
|
36
|
+
function resolve(path) {
|
|
37
|
+
const api = apiUrl();
|
|
38
|
+
const relative = path.startsWith('/') && !path.startsWith('//') ? path.slice(1) : path;
|
|
39
|
+
const url = new URL(relative, `${api.origin}${prefixOf(api)}/`);
|
|
40
|
+
if (!under(url, api) && !options.services?.some((service) => under(url, new URL(service)))) {
|
|
41
|
+
throw new Error(`Not the API or one of the product's services: ${path}`);
|
|
42
|
+
}
|
|
43
|
+
return url;
|
|
44
|
+
}
|
|
45
|
+
function send(url, init, unscoped) {
|
|
46
|
+
const api = apiUrl();
|
|
47
|
+
const pathname = under(url, api) ? url.pathname.slice(prefixOf(api).length) : url.pathname;
|
|
48
|
+
const headers = new Headers(init.headers);
|
|
49
|
+
const account = options.accountId ?? headers.get(ACCOUNT_HEADER);
|
|
50
|
+
headers.delete(ACCOUNT_HEADER);
|
|
51
|
+
if (account !== null &&
|
|
52
|
+
!unscoped &&
|
|
53
|
+
url.origin === api.origin &&
|
|
54
|
+
!UNSCOPED_PATH.test(pathname)) {
|
|
55
|
+
headers.set(ACCOUNT_HEADER, account);
|
|
56
|
+
// Fetch may forward custom headers across redirects. Stop before the next request.
|
|
57
|
+
init = { ...init, redirect: 'error' };
|
|
58
|
+
}
|
|
59
|
+
return doFetch(url.href, { ...init, headers: Object.fromEntries(headers) });
|
|
60
|
+
}
|
|
61
|
+
return { headers, resolve, send };
|
|
62
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { type RouteDef, type RouteInput, type RouteOutput } from '@buffcore/contracts';
|
|
2
|
+
export { ApiCallError } from './api-error.ts';
|
|
3
|
+
export interface ClientOptions {
|
|
4
|
+
/** The API's base URL, e.g. http://localhost:4300. */
|
|
5
|
+
baseUrl: string;
|
|
6
|
+
/** Native apps: the session token from secure storage, sent as a bearer token. The web uses cookies. */
|
|
7
|
+
getToken?: () => string | null | undefined | Promise<string | null | undefined>;
|
|
8
|
+
/** The account this member client acts for. Omit to use the server's default. */
|
|
9
|
+
accountId?: string;
|
|
10
|
+
/** The reader's language, sent as Accept-Language. */
|
|
11
|
+
getLocale?: () => string;
|
|
12
|
+
/** The admin screen a call comes from, for the audit log. */
|
|
13
|
+
getScreen?: () => string | undefined;
|
|
14
|
+
/** Extra headers on every call, e.g. the embedded preview's `x-ape-preview` token. */
|
|
15
|
+
headers?: Readonly<Record<string, string>>;
|
|
16
|
+
/**
|
|
17
|
+
* A device in profile mode (v0.5): its grant and the profile picked, or nothing in member mode.
|
|
18
|
+
* While it answers a grant, every call carries `x-ape-device` (and `x-ape-profile` once a
|
|
19
|
+
* profile is picked) and never the member's session: no bearer token, and no cookie.
|
|
20
|
+
*/
|
|
21
|
+
getDevice?: () => DeviceHeaders | null | undefined | Promise<DeviceHeaders | null | undefined>;
|
|
22
|
+
/**
|
|
23
|
+
* A call made with a grant was refused for the device's sake: `device_unknown` (the device was
|
|
24
|
+
* removed), `profile_not_on_device` and `consent_required` (the profile can't use it now), or
|
|
25
|
+
* `profile_paused` (v0.6: the Owner paused the profile). Given the grant the call carried, so an
|
|
26
|
+
* older grant's answer can be told apart.
|
|
27
|
+
*/
|
|
28
|
+
onDeviceRefused?: (code: DeviceRefusal, sent: DeviceHeaders) => void;
|
|
29
|
+
/** The product's own services beside the API (v0.7.2): `fetch` signs calls to them, as to the API. */
|
|
30
|
+
services?: readonly string[];
|
|
31
|
+
fetch?: typeof fetch;
|
|
32
|
+
}
|
|
33
|
+
/** What a device in profile mode sends: its grant's secret, and the profile it acts as. */
|
|
34
|
+
export interface DeviceHeaders {
|
|
35
|
+
secret: string;
|
|
36
|
+
profileId?: string | undefined;
|
|
37
|
+
}
|
|
38
|
+
declare const DEVICE_REFUSALS: readonly ['device_unknown', 'profile_not_on_device', 'consent_required', 'profile_paused'];
|
|
39
|
+
export type DeviceRefusal = (typeof DEVICE_REFUSALS)[number];
|
|
40
|
+
/** A UUIDv7 made on the client, so retries never create duplicates. */
|
|
41
|
+
export declare function uuidv7(now?: number): string;
|
|
42
|
+
export type Client = ReturnType<typeof clientFor> & {
|
|
43
|
+
/** A client with the same credentials and a fixed acting account. */
|
|
44
|
+
withAccount(accountId: string): Client;
|
|
45
|
+
};
|
|
46
|
+
/** The typed API client: `await api.call(getMe, {})`. Writes get an idempotency key automatically. */
|
|
47
|
+
export declare function createClient(options: ClientOptions): Client;
|
|
48
|
+
declare function clientFor(options: ClientOptions): {
|
|
49
|
+
/** The API's base URL (a live session's socket opens on the same host). */
|
|
50
|
+
baseUrl: string;
|
|
51
|
+
/** The reader's language the client sends now (`getLocale`), if any. */
|
|
52
|
+
locale: () => string | undefined;
|
|
53
|
+
/** The acting account used for calls and query keys. */
|
|
54
|
+
accountId: string | undefined;
|
|
55
|
+
call<R extends RouteDef>(route: R, input: RouteInput<R>, opts?: {
|
|
56
|
+
idempotencyKey?: string;
|
|
57
|
+
}): Promise<RouteOutput<R>>;
|
|
58
|
+
/** Sign-in, two-step sign-in and email codes (the sign-in library's endpoints). */
|
|
59
|
+
auth: {
|
|
60
|
+
signIn: (email: string, password: string) => Promise<{
|
|
61
|
+
twoFactorRedirect?: boolean;
|
|
62
|
+
token?: string;
|
|
63
|
+
}>;
|
|
64
|
+
verifyTotp: (code: string, trustDevice?: boolean) => Promise<{
|
|
65
|
+
token?: string;
|
|
66
|
+
}>;
|
|
67
|
+
verifyBackupCode: (code: string) => Promise<{
|
|
68
|
+
token?: string;
|
|
69
|
+
}>;
|
|
70
|
+
enableTwoFactor: (password: string) => Promise<{
|
|
71
|
+
totpURI: string;
|
|
72
|
+
backupCodes: string[];
|
|
73
|
+
}>;
|
|
74
|
+
verifyEmail: (email: string, otp: string) => Promise<unknown>;
|
|
75
|
+
sendEmailCode: (email: string) => Promise<unknown>;
|
|
76
|
+
/** Email a sign-in code (products that offer `email-code`). Says nothing about unknown emails. */
|
|
77
|
+
sendSignInCode: (email: string) => Promise<unknown>;
|
|
78
|
+
signInWithCode: (email: string, otp: string) => Promise<{
|
|
79
|
+
token?: string;
|
|
80
|
+
}>;
|
|
81
|
+
/** Email a reset code. Same answer for any address; 429 TOO_MANY_CODES after 3 an hour. */
|
|
82
|
+
requestPasswordReset: (email: string) => Promise<unknown>;
|
|
83
|
+
/** Set a new password with the emailed code. Signs nobody in and ends every session. */
|
|
84
|
+
resetPassword: (email: string, otp: string, password: string) => Promise<unknown>;
|
|
85
|
+
signOut: () => Promise<unknown>;
|
|
86
|
+
/** The consent page (`mcp-server`): a registered MCP client's name, for anyone signed in. */
|
|
87
|
+
oauthClient: (clientId: string) => Promise<{
|
|
88
|
+
client_id: string;
|
|
89
|
+
client_name?: string;
|
|
90
|
+
}>;
|
|
91
|
+
/**
|
|
92
|
+
* The consent page's answer, with the signed request it was opened with (its query): where
|
|
93
|
+
* to send the person next. 403 `NOT_AN_OPERATOR` unless an operator freshly signed in; a
|
|
94
|
+
* members' client's `accountId` is the account it acts in (403 `NOT_A_MEMBER` if not theirs).
|
|
95
|
+
*/
|
|
96
|
+
oauthConsent: (accept: boolean, oauthQuery: string, accountId?: string) => Promise<{
|
|
97
|
+
url: string;
|
|
98
|
+
}>;
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* A file the API sends instead of JSON (e.g. a ready export's ZIP at a path with its params
|
|
102
|
+
* filled), signed in as every call is. A refusal throws the one error shape.
|
|
103
|
+
*/
|
|
104
|
+
download(path: string): Promise<Blob>;
|
|
105
|
+
/** A plain `fetch` to the API or one of `services`, signed in as `call` is; elsewhere it throws. */
|
|
106
|
+
fetch(url: string, init?: RequestInit): Promise<Response>;
|
|
107
|
+
/** Report an uncaught error. Never throws. */
|
|
108
|
+
reportError(source: 'admin' | 'web' | 'ios' | 'android', error: unknown, where?: string, release?: string): Promise<void>;
|
|
109
|
+
request: <T>(method: string, path: string, body?: unknown, extra?: Record<string, string>, publicRoute?: boolean) => Promise<T>;
|
|
110
|
+
};
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { fillPath, } from '@buffcore/contracts';
|
|
2
|
+
import { ApiCallError } from './api-error.js';
|
|
3
|
+
import { clientDestination } from './client-destination.js';
|
|
4
|
+
export { ApiCallError } from './api-error.js';
|
|
5
|
+
const DEVICE_REFUSALS = [
|
|
6
|
+
'device_unknown',
|
|
7
|
+
'profile_not_on_device',
|
|
8
|
+
'consent_required',
|
|
9
|
+
'profile_paused',
|
|
10
|
+
];
|
|
11
|
+
const isRefusal = (code) => DEVICE_REFUSALS.includes(code);
|
|
12
|
+
const random = () => {
|
|
13
|
+
const bytes = new Uint8Array(16);
|
|
14
|
+
globalThis.crypto.getRandomValues(bytes);
|
|
15
|
+
return bytes;
|
|
16
|
+
};
|
|
17
|
+
/** A UUIDv7 made on the client, so retries never create duplicates. */
|
|
18
|
+
export function uuidv7(now = Date.now()) {
|
|
19
|
+
const b = random();
|
|
20
|
+
for (let i = 0; i < 6; i++)
|
|
21
|
+
b[i] = Math.floor(now / 2 ** (8 * (5 - i))) & 0xff;
|
|
22
|
+
b[6] = 0x70 | (b[6] & 0x0f);
|
|
23
|
+
b[8] = 0x80 | (b[8] & 0x3f);
|
|
24
|
+
const hex = [...b].map((x) => x.toString(16).padStart(2, '0')).join('');
|
|
25
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
26
|
+
}
|
|
27
|
+
function queryString(query) {
|
|
28
|
+
if (!query)
|
|
29
|
+
return '';
|
|
30
|
+
const params = new URLSearchParams();
|
|
31
|
+
for (const [key, value] of Object.entries(query))
|
|
32
|
+
if (value !== undefined && value !== null)
|
|
33
|
+
params.set(key, String(value));
|
|
34
|
+
const text = params.toString();
|
|
35
|
+
return text ? `?${text}` : '';
|
|
36
|
+
}
|
|
37
|
+
/** The typed API client: `await api.call(getMe, {})`. Writes get an idempotency key automatically. */
|
|
38
|
+
export function createClient(options) {
|
|
39
|
+
return {
|
|
40
|
+
...clientFor(options),
|
|
41
|
+
withAccount: (accountId) => createClient({ ...options, accountId }),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function clientFor(options) {
|
|
45
|
+
const { headers, resolve, send } = clientDestination(options);
|
|
46
|
+
const locale = () => options.getLocale?.();
|
|
47
|
+
const { accountId } = options;
|
|
48
|
+
async function request(method, path, body, extra = {}, publicRoute = false) {
|
|
49
|
+
const url = resolve(path);
|
|
50
|
+
const device = (await options.getDevice?.()) ?? null;
|
|
51
|
+
const res = await send(url, {
|
|
52
|
+
method,
|
|
53
|
+
// In profile mode the member's cookie stays home: the grant alone says who is calling.
|
|
54
|
+
credentials: device ? 'omit' : 'include',
|
|
55
|
+
headers: { ...(await headers(body !== undefined, device)), ...extra },
|
|
56
|
+
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
|
57
|
+
}, publicRoute || device !== null);
|
|
58
|
+
const text = await res.text();
|
|
59
|
+
const data = text ? JSON.parse(text) : null;
|
|
60
|
+
if (!res.ok) {
|
|
61
|
+
const error = new ApiCallError(res.status, (data ?? {}));
|
|
62
|
+
if (device && isRefusal(error.code))
|
|
63
|
+
options.onDeviceRefused?.(error.code, device);
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
return data;
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
/** The API's base URL (a live session's socket opens on the same host). */
|
|
70
|
+
baseUrl: options.baseUrl,
|
|
71
|
+
/** The reader's language the client sends now (`getLocale`), if any. */
|
|
72
|
+
locale,
|
|
73
|
+
/** The acting account used for calls and query keys. */
|
|
74
|
+
accountId,
|
|
75
|
+
async call(route, input, opts = {}) {
|
|
76
|
+
const path = fillPath(route.path, input.params) +
|
|
77
|
+
queryString(input.query);
|
|
78
|
+
const extra = route.method === 'GET' ? {} : { 'idempotency-key': opts.idempotencyKey ?? uuidv7() };
|
|
79
|
+
return request(route.method, path, input.body, extra, route.access === 'public');
|
|
80
|
+
},
|
|
81
|
+
/** Sign-in, two-step sign-in and email codes (the sign-in library's endpoints). */
|
|
82
|
+
auth: {
|
|
83
|
+
signIn: (email, password) => request('POST', '/v1/auth/sign-in/email', {
|
|
84
|
+
email,
|
|
85
|
+
password,
|
|
86
|
+
}),
|
|
87
|
+
verifyTotp: (code, trustDevice = false) => request('POST', '/v1/auth/two-factor/verify-totp', {
|
|
88
|
+
code,
|
|
89
|
+
trustDevice,
|
|
90
|
+
}),
|
|
91
|
+
verifyBackupCode: (code) => request('POST', '/v1/auth/two-factor/verify-backup-code', { code }),
|
|
92
|
+
enableTwoFactor: (password) => request('POST', '/v1/auth/two-factor/enable', {
|
|
93
|
+
password,
|
|
94
|
+
}),
|
|
95
|
+
verifyEmail: (email, otp) => request('POST', '/v1/auth/email-otp/verify-email', { email, otp }),
|
|
96
|
+
sendEmailCode: (email) => request('POST', '/v1/auth/email-otp/send-verification-otp', {
|
|
97
|
+
email,
|
|
98
|
+
type: 'email-verification',
|
|
99
|
+
}),
|
|
100
|
+
/** Email a sign-in code (products that offer `email-code`). Says nothing about unknown emails. */
|
|
101
|
+
sendSignInCode: (email) => request('POST', '/v1/auth/email-otp/send-verification-otp', {
|
|
102
|
+
email,
|
|
103
|
+
type: 'sign-in',
|
|
104
|
+
}),
|
|
105
|
+
signInWithCode: (email, otp) => request('POST', '/v1/auth/sign-in/email-otp', { email, otp }),
|
|
106
|
+
/** Email a reset code. Same answer for any address; 429 TOO_MANY_CODES after 3 an hour. */
|
|
107
|
+
requestPasswordReset: (email) => request('POST', '/v1/auth/email-otp/request-password-reset', { email }),
|
|
108
|
+
/** Set a new password with the emailed code. Signs nobody in and ends every session. */
|
|
109
|
+
resetPassword: (email, otp, password) => request('POST', '/v1/auth/email-otp/reset-password', { email, otp, password }),
|
|
110
|
+
signOut: () => request('POST', '/v1/auth/sign-out', {}),
|
|
111
|
+
/** The consent page (`mcp-server`): a registered MCP client's name, for anyone signed in. */
|
|
112
|
+
oauthClient: (clientId) => request('GET', `/v1/auth/oauth2/public-client${queryString({ client_id: clientId })}`),
|
|
113
|
+
/**
|
|
114
|
+
* The consent page's answer, with the signed request it was opened with (its query): where
|
|
115
|
+
* to send the person next. 403 `NOT_AN_OPERATOR` unless an operator freshly signed in; a
|
|
116
|
+
* members' client's `accountId` is the account it acts in (403 `NOT_A_MEMBER` if not theirs).
|
|
117
|
+
*/
|
|
118
|
+
oauthConsent: (accept, oauthQuery, accountId) => request('POST', '/v1/auth/oauth2/consent', {
|
|
119
|
+
accept,
|
|
120
|
+
oauth_query: oauthQuery,
|
|
121
|
+
...(accountId ? { account_id: accountId } : {}),
|
|
122
|
+
}),
|
|
123
|
+
},
|
|
124
|
+
/**
|
|
125
|
+
* A file the API sends instead of JSON (e.g. a ready export's ZIP at a path with its params
|
|
126
|
+
* filled), signed in as every call is. A refusal throws the one error shape.
|
|
127
|
+
*/
|
|
128
|
+
async download(path) {
|
|
129
|
+
const url = resolve(path);
|
|
130
|
+
const device = (await options.getDevice?.()) ?? null;
|
|
131
|
+
const res = await send(url, {
|
|
132
|
+
method: 'GET',
|
|
133
|
+
credentials: device ? 'omit' : 'include',
|
|
134
|
+
headers: await headers(false, device),
|
|
135
|
+
}, device !== null);
|
|
136
|
+
if (res.ok)
|
|
137
|
+
return res.blob();
|
|
138
|
+
const text = await res.text();
|
|
139
|
+
let body = {};
|
|
140
|
+
try {
|
|
141
|
+
body = text ? JSON.parse(text) : {};
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
// Not the one error shape (e.g. a proxy's page): the status says enough.
|
|
145
|
+
}
|
|
146
|
+
throw new ApiCallError(res.status, body);
|
|
147
|
+
},
|
|
148
|
+
/** A plain `fetch` to the API or one of `services`, signed in as `call` is; elsewhere it throws. */
|
|
149
|
+
async fetch(url, init = {}) {
|
|
150
|
+
const target = resolve(url);
|
|
151
|
+
const device = (await options.getDevice?.()) ?? null;
|
|
152
|
+
const merged = new Headers(init.headers);
|
|
153
|
+
for (const [name, value] of Object.entries(await headers(false, device)))
|
|
154
|
+
merged.set(name, value);
|
|
155
|
+
return send(target, {
|
|
156
|
+
...init,
|
|
157
|
+
credentials: device ? 'omit' : 'include',
|
|
158
|
+
headers: Object.fromEntries(merged),
|
|
159
|
+
}, device !== null);
|
|
160
|
+
},
|
|
161
|
+
/** Report an uncaught error. Never throws. */
|
|
162
|
+
async reportError(source, error, where, release) {
|
|
163
|
+
const e = error instanceof Error ? error : new Error(String(error));
|
|
164
|
+
await request('POST', '/v1/errors', {
|
|
165
|
+
source,
|
|
166
|
+
type: e.name.slice(0, 100),
|
|
167
|
+
message: e.message.slice(0, 1000),
|
|
168
|
+
...(e.stack ? { stack: e.stack.slice(0, 16_000) } : {}),
|
|
169
|
+
...(where ? { where: where.slice(0, 200) } : {}),
|
|
170
|
+
...(release ? { release } : {}),
|
|
171
|
+
}).catch(() => undefined);
|
|
172
|
+
},
|
|
173
|
+
request,
|
|
174
|
+
};
|
|
175
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { ApiCallError, type Client, type ClientOptions, createClient, uuidv7 } from './client.ts';
|
|
2
|
+
export { isPasswordLeaked } from './leaks.ts';
|
|
3
|
+
export { startLiveSession } from './realtime.ts';
|
|
4
|
+
export type { LiveClosed, LiveOutbox, LiveOutboxMessage, LiveSession, LiveSessionOptions, LiveSocket, LiveSocketClass, LiveState, } from './realtime-types.ts';
|
|
5
|
+
export { createTracker, type TrackerOptions } from './tracker.ts';
|
package/dist/index.js
ADDED
package/dist/leaks.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Client } from './client.ts';
|
|
2
|
+
/**
|
|
3
|
+
* Whether a new password has shown up in known leaks, by k-anonymity: only the first 5 characters
|
|
4
|
+
* of its SHA-1 go to the API (`GET /v1/sign-in/leaks/:prefix`), and the rest is matched here, so
|
|
5
|
+
* the password stays on the device. Any failure answers false: the check never stops anyone (the
|
|
6
|
+
* server still refuses a leaked one when the product's mode is `refuse`).
|
|
7
|
+
*/
|
|
8
|
+
export declare function isPasswordLeaked(client: Client, password: string): Promise<boolean>;
|