@wefunder/sdk 0.1.0-beta.1 → 0.1.0-beta.11

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/dist/index.cjs CHANGED
@@ -25,29 +25,852 @@ __export(index_exports, {
25
25
  DEFAULT_AUTHORIZE_BASE_URL: () => DEFAULT_AUTHORIZE_BASE_URL,
26
26
  DEFAULT_OAUTH_BASE_URL: () => DEFAULT_OAUTH_BASE_URL,
27
27
  DEFAULT_TOKEN_BASE_URL: () => DEFAULT_TOKEN_BASE_URL,
28
- DELIVERY_ID_HEADER: () => DELIVERY_ID_HEADER,
29
- EVENT_HEADER: () => EVENT_HEADER,
28
+ DEFAULT_TOLERANCE_SECONDS: () => DEFAULT_TOLERANCE_SECONDS,
29
+ LEGACY_DELIVERY_ID_HEADER: () => LEGACY_DELIVERY_ID_HEADER,
30
+ LEGACY_EVENT_HEADER: () => LEGACY_EVENT_HEADER,
31
+ LEGACY_SIGNATURE_HEADER: () => LEGACY_SIGNATURE_HEADER,
32
+ LEGACY_TIMESTAMP_HEADER: () => LEGACY_TIMESTAMP_HEADER,
30
33
  REQUEST_ID_HEADER: () => REQUEST_ID_HEADER,
34
+ SANDBOX_AUTHORIZE_BASE_URL: () => SANDBOX_AUTHORIZE_BASE_URL,
31
35
  SIGNATURE_HEADER: () => SIGNATURE_HEADER,
32
- TIMESTAMP_HEADER: () => TIMESTAMP_HEADER,
36
+ TokenManager: () => TokenManager,
37
+ WebhookSignatureError: () => WebhookSignatureError,
33
38
  Wefunder: () => Wefunder,
34
39
  WefunderAuthError: () => WefunderAuthError,
35
40
  WefunderError: () => WefunderError,
41
+ WefunderTokenPersistenceError: () => WefunderTokenPersistenceError,
42
+ checkWebhookSignature: () => checkWebhookSignature,
36
43
  clientCredentialsGrant: () => clientCredentialsGrant,
37
44
  collect: () => collect,
45
+ computeWebhookSignature: () => computeWebhookSignature,
38
46
  constructEvent: () => constructEvent,
47
+ constructEventFromRequest: () => constructEventFromRequest,
39
48
  createAuthorizationUrl: () => createAuthorizationUrl,
49
+ dispatchWebhook: () => dispatchWebhook,
40
50
  exchangeCode: () => exchangeCode,
41
51
  generatePkce: () => generatePkce,
42
52
  modeForToken: () => modeForToken,
43
53
  paginate: () => paginate,
54
+ parseSignatureHeader: () => parseSignatureHeader,
44
55
  refreshToken: () => refreshToken,
56
+ signWebhook: () => signWebhook,
45
57
  verifyWebhook: () => verifyWebhook
46
58
  });
47
59
  module.exports = __toCommonJS(index_exports);
48
60
 
49
- // src/client.ts
50
- var import_client_fetch2 = require("@hey-api/client-fetch");
61
+ // src/generated/core/bodySerializer.gen.ts
62
+ var jsonBodySerializer = {
63
+ bodySerializer: (body) => JSON.stringify(
64
+ body,
65
+ (_key, value) => typeof value === "bigint" ? value.toString() : value
66
+ )
67
+ };
68
+
69
+ // src/generated/core/params.gen.ts
70
+ var extraPrefixesMap = {
71
+ $body_: "body",
72
+ $headers_: "headers",
73
+ $path_: "path",
74
+ $query_: "query"
75
+ };
76
+ var extraPrefixes = Object.entries(extraPrefixesMap);
77
+
78
+ // src/generated/core/serverSentEvents.gen.ts
79
+ function createSseClient({
80
+ onRequest,
81
+ onSseError,
82
+ onSseEvent,
83
+ responseTransformer,
84
+ responseValidator,
85
+ sseDefaultRetryDelay,
86
+ sseMaxRetryAttempts,
87
+ sseMaxRetryDelay,
88
+ sseSleepFn,
89
+ url,
90
+ ...options
91
+ }) {
92
+ let lastEventId;
93
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
94
+ const createStream = async function* () {
95
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
96
+ let attempt = 0;
97
+ const signal = options.signal ?? new AbortController().signal;
98
+ while (true) {
99
+ if (signal.aborted) break;
100
+ attempt++;
101
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
102
+ if (lastEventId !== void 0) {
103
+ headers.set("Last-Event-ID", lastEventId);
104
+ }
105
+ try {
106
+ const requestInit = {
107
+ redirect: "follow",
108
+ ...options,
109
+ body: options.serializedBody,
110
+ headers,
111
+ signal
112
+ };
113
+ let request = new Request(url, requestInit);
114
+ if (onRequest) {
115
+ request = await onRequest(url, requestInit);
116
+ }
117
+ const _fetch = options.fetch ?? globalThis.fetch;
118
+ const response = await _fetch(request);
119
+ if (!response.ok)
120
+ throw new Error(
121
+ `SSE failed: ${response.status} ${response.statusText}`
122
+ );
123
+ if (!response.body) throw new Error("No body in SSE response");
124
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
125
+ let buffer = "";
126
+ const abortHandler = () => {
127
+ try {
128
+ reader.cancel();
129
+ } catch {
130
+ }
131
+ };
132
+ signal.addEventListener("abort", abortHandler);
133
+ try {
134
+ while (true) {
135
+ const { done, value } = await reader.read();
136
+ if (done) break;
137
+ buffer += value;
138
+ buffer = buffer.replace(/\r\n?/g, "\n");
139
+ const chunks = buffer.split("\n\n");
140
+ buffer = chunks.pop() ?? "";
141
+ for (const chunk of chunks) {
142
+ const lines = chunk.split("\n");
143
+ const dataLines = [];
144
+ let eventName;
145
+ for (const line of lines) {
146
+ if (line.startsWith("data:")) {
147
+ dataLines.push(line.replace(/^data:\s*/, ""));
148
+ } else if (line.startsWith("event:")) {
149
+ eventName = line.replace(/^event:\s*/, "");
150
+ } else if (line.startsWith("id:")) {
151
+ lastEventId = line.replace(/^id:\s*/, "");
152
+ } else if (line.startsWith("retry:")) {
153
+ const parsed = Number.parseInt(
154
+ line.replace(/^retry:\s*/, ""),
155
+ 10
156
+ );
157
+ if (!Number.isNaN(parsed)) {
158
+ retryDelay = parsed;
159
+ }
160
+ }
161
+ }
162
+ let data;
163
+ let parsedJson = false;
164
+ if (dataLines.length) {
165
+ const rawData = dataLines.join("\n");
166
+ try {
167
+ data = JSON.parse(rawData);
168
+ parsedJson = true;
169
+ } catch {
170
+ data = rawData;
171
+ }
172
+ }
173
+ if (parsedJson) {
174
+ if (responseValidator) {
175
+ await responseValidator(data);
176
+ }
177
+ if (responseTransformer) {
178
+ data = await responseTransformer(data);
179
+ }
180
+ }
181
+ onSseEvent?.({
182
+ data,
183
+ event: eventName,
184
+ id: lastEventId,
185
+ retry: retryDelay
186
+ });
187
+ if (dataLines.length) {
188
+ yield data;
189
+ }
190
+ }
191
+ }
192
+ } finally {
193
+ signal.removeEventListener("abort", abortHandler);
194
+ reader.releaseLock();
195
+ }
196
+ break;
197
+ } catch (error) {
198
+ onSseError?.(error);
199
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
200
+ break;
201
+ }
202
+ const backoff = Math.min(
203
+ retryDelay * 2 ** (attempt - 1),
204
+ sseMaxRetryDelay ?? 3e4
205
+ );
206
+ await sleep(backoff);
207
+ }
208
+ }
209
+ };
210
+ const stream = createStream();
211
+ return { stream };
212
+ }
213
+
214
+ // src/generated/core/pathSerializer.gen.ts
215
+ var separatorArrayExplode = (style) => {
216
+ switch (style) {
217
+ case "label":
218
+ return ".";
219
+ case "matrix":
220
+ return ";";
221
+ case "simple":
222
+ return ",";
223
+ default:
224
+ return "&";
225
+ }
226
+ };
227
+ var separatorArrayNoExplode = (style) => {
228
+ switch (style) {
229
+ case "form":
230
+ return ",";
231
+ case "pipeDelimited":
232
+ return "|";
233
+ case "spaceDelimited":
234
+ return "%20";
235
+ default:
236
+ return ",";
237
+ }
238
+ };
239
+ var separatorObjectExplode = (style) => {
240
+ switch (style) {
241
+ case "label":
242
+ return ".";
243
+ case "matrix":
244
+ return ";";
245
+ case "simple":
246
+ return ",";
247
+ default:
248
+ return "&";
249
+ }
250
+ };
251
+ var serializeArrayParam = ({
252
+ allowReserved,
253
+ explode,
254
+ name,
255
+ style,
256
+ value
257
+ }) => {
258
+ if (!explode) {
259
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
260
+ switch (style) {
261
+ case "label":
262
+ return `.${joinedValues2}`;
263
+ case "matrix":
264
+ return `;${name}=${joinedValues2}`;
265
+ case "simple":
266
+ return joinedValues2;
267
+ default:
268
+ return `${name}=${joinedValues2}`;
269
+ }
270
+ }
271
+ const separator = separatorArrayExplode(style);
272
+ const joinedValues = value.map((v) => {
273
+ if (style === "label" || style === "simple") {
274
+ return allowReserved ? v : encodeURIComponent(v);
275
+ }
276
+ return serializePrimitiveParam({
277
+ allowReserved,
278
+ name,
279
+ value: v
280
+ });
281
+ }).join(separator);
282
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
283
+ };
284
+ var serializePrimitiveParam = ({
285
+ allowReserved,
286
+ name,
287
+ value
288
+ }) => {
289
+ if (value === void 0 || value === null) {
290
+ return "";
291
+ }
292
+ if (typeof value === "object") {
293
+ throw new Error(
294
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
295
+ );
296
+ }
297
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
298
+ };
299
+ var serializeObjectParam = ({
300
+ allowReserved,
301
+ explode,
302
+ name,
303
+ style,
304
+ value,
305
+ valueOnly
306
+ }) => {
307
+ if (value instanceof Date) {
308
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
309
+ }
310
+ if (style !== "deepObject" && !explode) {
311
+ let values = [];
312
+ Object.entries(value).forEach(([key, v]) => {
313
+ values = [
314
+ ...values,
315
+ key,
316
+ allowReserved ? v : encodeURIComponent(v)
317
+ ];
318
+ });
319
+ const joinedValues2 = values.join(",");
320
+ switch (style) {
321
+ case "form":
322
+ return `${name}=${joinedValues2}`;
323
+ case "label":
324
+ return `.${joinedValues2}`;
325
+ case "matrix":
326
+ return `;${name}=${joinedValues2}`;
327
+ default:
328
+ return joinedValues2;
329
+ }
330
+ }
331
+ const separator = separatorObjectExplode(style);
332
+ const joinedValues = Object.entries(value).map(
333
+ ([key, v]) => serializePrimitiveParam({
334
+ allowReserved,
335
+ name: style === "deepObject" ? `${name}[${key}]` : key,
336
+ value: v
337
+ })
338
+ ).join(separator);
339
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
340
+ };
341
+
342
+ // src/generated/core/utils.gen.ts
343
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
344
+ var defaultPathSerializer = ({
345
+ path,
346
+ url: _url
347
+ }) => {
348
+ let url = _url;
349
+ const matches = _url.match(PATH_PARAM_RE);
350
+ if (matches) {
351
+ for (const match of matches) {
352
+ let explode = false;
353
+ let name = match.substring(1, match.length - 1);
354
+ let style = "simple";
355
+ if (name.endsWith("*")) {
356
+ explode = true;
357
+ name = name.substring(0, name.length - 1);
358
+ }
359
+ if (name.startsWith(".")) {
360
+ name = name.substring(1);
361
+ style = "label";
362
+ } else if (name.startsWith(";")) {
363
+ name = name.substring(1);
364
+ style = "matrix";
365
+ }
366
+ const value = path[name];
367
+ if (value === void 0 || value === null) {
368
+ continue;
369
+ }
370
+ if (Array.isArray(value)) {
371
+ url = url.replace(
372
+ match,
373
+ serializeArrayParam({ explode, name, style, value })
374
+ );
375
+ continue;
376
+ }
377
+ if (typeof value === "object") {
378
+ url = url.replace(
379
+ match,
380
+ serializeObjectParam({
381
+ explode,
382
+ name,
383
+ style,
384
+ value,
385
+ valueOnly: true
386
+ })
387
+ );
388
+ continue;
389
+ }
390
+ if (style === "matrix") {
391
+ url = url.replace(
392
+ match,
393
+ `;${serializePrimitiveParam({
394
+ name,
395
+ value
396
+ })}`
397
+ );
398
+ continue;
399
+ }
400
+ const replaceValue = encodeURIComponent(
401
+ style === "label" ? `.${value}` : value
402
+ );
403
+ url = url.replace(match, replaceValue);
404
+ }
405
+ }
406
+ return url;
407
+ };
408
+ var getUrl = ({
409
+ baseUrl,
410
+ path,
411
+ query,
412
+ querySerializer,
413
+ url: _url
414
+ }) => {
415
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
416
+ let url = (baseUrl ?? "") + pathUrl;
417
+ if (path) {
418
+ url = defaultPathSerializer({ path, url });
419
+ }
420
+ let search = query ? querySerializer(query) : "";
421
+ if (search.startsWith("?")) {
422
+ search = search.substring(1);
423
+ }
424
+ if (search) {
425
+ url += `?${search}`;
426
+ }
427
+ return url;
428
+ };
429
+ function getValidRequestBody(options) {
430
+ const hasBody = options.body !== void 0;
431
+ const isSerializedBody = hasBody && options.bodySerializer;
432
+ if (isSerializedBody) {
433
+ if ("serializedBody" in options) {
434
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
435
+ return hasSerializedBody ? options.serializedBody : null;
436
+ }
437
+ return options.body !== "" ? options.body : null;
438
+ }
439
+ if (hasBody) {
440
+ return options.body;
441
+ }
442
+ return void 0;
443
+ }
444
+
445
+ // src/generated/core/auth.gen.ts
446
+ var getAuthToken = async (auth, callback) => {
447
+ const token = typeof callback === "function" ? await callback(auth) : callback;
448
+ if (!token) {
449
+ return;
450
+ }
451
+ if (auth.scheme === "bearer") {
452
+ return `Bearer ${token}`;
453
+ }
454
+ if (auth.scheme === "basic") {
455
+ return `Basic ${btoa(token)}`;
456
+ }
457
+ return token;
458
+ };
459
+
460
+ // src/generated/client/utils.gen.ts
461
+ var createQuerySerializer = ({
462
+ parameters = {},
463
+ ...args
464
+ } = {}) => {
465
+ const querySerializer = (queryParams) => {
466
+ const search = [];
467
+ if (queryParams && typeof queryParams === "object") {
468
+ for (const name in queryParams) {
469
+ const value = queryParams[name];
470
+ if (value === void 0 || value === null) {
471
+ continue;
472
+ }
473
+ const options = parameters[name] || args;
474
+ if (Array.isArray(value)) {
475
+ const serializedArray = serializeArrayParam({
476
+ allowReserved: options.allowReserved,
477
+ explode: true,
478
+ name,
479
+ style: "form",
480
+ value,
481
+ ...options.array
482
+ });
483
+ if (serializedArray) search.push(serializedArray);
484
+ } else if (typeof value === "object") {
485
+ const serializedObject = serializeObjectParam({
486
+ allowReserved: options.allowReserved,
487
+ explode: true,
488
+ name,
489
+ style: "deepObject",
490
+ value,
491
+ ...options.object
492
+ });
493
+ if (serializedObject) search.push(serializedObject);
494
+ } else {
495
+ const serializedPrimitive = serializePrimitiveParam({
496
+ allowReserved: options.allowReserved,
497
+ name,
498
+ value
499
+ });
500
+ if (serializedPrimitive) search.push(serializedPrimitive);
501
+ }
502
+ }
503
+ }
504
+ return search.join("&");
505
+ };
506
+ return querySerializer;
507
+ };
508
+ var getParseAs = (contentType) => {
509
+ if (!contentType) {
510
+ return "stream";
511
+ }
512
+ const cleanContent = contentType.split(";")[0]?.trim();
513
+ if (!cleanContent) {
514
+ return;
515
+ }
516
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
517
+ return "json";
518
+ }
519
+ if (cleanContent === "multipart/form-data") {
520
+ return "formData";
521
+ }
522
+ if (["application/", "audio/", "image/", "video/"].some(
523
+ (type) => cleanContent.startsWith(type)
524
+ )) {
525
+ return "blob";
526
+ }
527
+ if (cleanContent.startsWith("text/")) {
528
+ return "text";
529
+ }
530
+ return;
531
+ };
532
+ var checkForExistence = (options, name) => {
533
+ if (!name) {
534
+ return false;
535
+ }
536
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
537
+ return true;
538
+ }
539
+ return false;
540
+ };
541
+ async function setAuthParams(options) {
542
+ for (const auth of options.security ?? []) {
543
+ if (checkForExistence(options, auth.name)) {
544
+ continue;
545
+ }
546
+ const token = await getAuthToken(auth, options.auth);
547
+ if (!token) {
548
+ continue;
549
+ }
550
+ const name = auth.name ?? "Authorization";
551
+ switch (auth.in) {
552
+ case "query":
553
+ if (!options.query) {
554
+ options.query = {};
555
+ }
556
+ options.query[name] = token;
557
+ break;
558
+ case "cookie":
559
+ options.headers.append("Cookie", `${name}=${token}`);
560
+ break;
561
+ case "header":
562
+ default:
563
+ options.headers.set(name, token);
564
+ break;
565
+ }
566
+ }
567
+ }
568
+ var buildUrl = (options) => getUrl({
569
+ baseUrl: options.baseUrl,
570
+ path: options.path,
571
+ query: options.query,
572
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
573
+ url: options.url
574
+ });
575
+ var mergeConfigs = (a, b) => {
576
+ const config = { ...a, ...b };
577
+ if (config.baseUrl?.endsWith("/")) {
578
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
579
+ }
580
+ config.headers = mergeHeaders(a.headers, b.headers);
581
+ return config;
582
+ };
583
+ var headersEntries = (headers) => {
584
+ const entries = [];
585
+ headers.forEach((value, key) => {
586
+ entries.push([key, value]);
587
+ });
588
+ return entries;
589
+ };
590
+ var mergeHeaders = (...headers) => {
591
+ const mergedHeaders = new Headers();
592
+ for (const header of headers) {
593
+ if (!header) {
594
+ continue;
595
+ }
596
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
597
+ for (const [key, value] of iterator) {
598
+ if (value === null) {
599
+ mergedHeaders.delete(key);
600
+ } else if (Array.isArray(value)) {
601
+ for (const v of value) {
602
+ mergedHeaders.append(key, v);
603
+ }
604
+ } else if (value !== void 0) {
605
+ mergedHeaders.set(
606
+ key,
607
+ typeof value === "object" ? JSON.stringify(value) : value
608
+ );
609
+ }
610
+ }
611
+ }
612
+ return mergedHeaders;
613
+ };
614
+ var Interceptors = class {
615
+ fns = [];
616
+ clear() {
617
+ this.fns = [];
618
+ }
619
+ eject(id) {
620
+ const index = this.getInterceptorIndex(id);
621
+ if (this.fns[index]) {
622
+ this.fns[index] = null;
623
+ }
624
+ }
625
+ exists(id) {
626
+ const index = this.getInterceptorIndex(id);
627
+ return Boolean(this.fns[index]);
628
+ }
629
+ getInterceptorIndex(id) {
630
+ if (typeof id === "number") {
631
+ return this.fns[id] ? id : -1;
632
+ }
633
+ return this.fns.indexOf(id);
634
+ }
635
+ update(id, fn) {
636
+ const index = this.getInterceptorIndex(id);
637
+ if (this.fns[index]) {
638
+ this.fns[index] = fn;
639
+ return id;
640
+ }
641
+ return false;
642
+ }
643
+ use(fn) {
644
+ this.fns.push(fn);
645
+ return this.fns.length - 1;
646
+ }
647
+ };
648
+ var createInterceptors = () => ({
649
+ error: new Interceptors(),
650
+ request: new Interceptors(),
651
+ response: new Interceptors()
652
+ });
653
+ var defaultQuerySerializer = createQuerySerializer({
654
+ allowReserved: false,
655
+ array: {
656
+ explode: true,
657
+ style: "form"
658
+ },
659
+ object: {
660
+ explode: true,
661
+ style: "deepObject"
662
+ }
663
+ });
664
+ var defaultHeaders = {
665
+ "Content-Type": "application/json"
666
+ };
667
+ var createConfig = (override = {}) => ({
668
+ ...jsonBodySerializer,
669
+ headers: defaultHeaders,
670
+ parseAs: "auto",
671
+ querySerializer: defaultQuerySerializer,
672
+ ...override
673
+ });
674
+
675
+ // src/generated/client/client.gen.ts
676
+ var createClient = (config = {}) => {
677
+ let _config = mergeConfigs(createConfig(), config);
678
+ const getConfig = () => ({ ..._config });
679
+ const setConfig = (config2) => {
680
+ _config = mergeConfigs(_config, config2);
681
+ return getConfig();
682
+ };
683
+ const interceptors = createInterceptors();
684
+ const beforeRequest = async (options) => {
685
+ const opts = {
686
+ ..._config,
687
+ ...options,
688
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
689
+ headers: mergeHeaders(_config.headers, options.headers),
690
+ serializedBody: void 0
691
+ };
692
+ if (opts.security) {
693
+ await setAuthParams(opts);
694
+ }
695
+ if (opts.requestValidator) {
696
+ await opts.requestValidator(opts);
697
+ }
698
+ if (opts.body !== void 0 && opts.bodySerializer) {
699
+ opts.serializedBody = opts.bodySerializer(opts.body);
700
+ }
701
+ if (opts.body === void 0 || opts.serializedBody === "") {
702
+ opts.headers.delete("Content-Type");
703
+ }
704
+ const resolvedOpts = opts;
705
+ const url = buildUrl(resolvedOpts);
706
+ return { opts: resolvedOpts, url };
707
+ };
708
+ const request = async (options) => {
709
+ const throwOnError = options.throwOnError ?? _config.throwOnError;
710
+ const responseStyle = options.responseStyle ?? _config.responseStyle;
711
+ let request2;
712
+ let response;
713
+ try {
714
+ const { opts, url } = await beforeRequest(options);
715
+ const requestInit = {
716
+ redirect: "follow",
717
+ ...opts,
718
+ body: getValidRequestBody(opts)
719
+ };
720
+ request2 = new Request(url, requestInit);
721
+ for (const fn of interceptors.request.fns) {
722
+ if (fn) {
723
+ request2 = await fn(request2, opts);
724
+ }
725
+ }
726
+ const _fetch = opts.fetch;
727
+ response = await _fetch(request2);
728
+ for (const fn of interceptors.response.fns) {
729
+ if (fn) {
730
+ response = await fn(response, request2, opts);
731
+ }
732
+ }
733
+ const result = {
734
+ request: request2,
735
+ response
736
+ };
737
+ if (response.ok) {
738
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
739
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
740
+ let emptyData;
741
+ switch (parseAs) {
742
+ case "arrayBuffer":
743
+ case "blob":
744
+ case "text":
745
+ emptyData = await response[parseAs]();
746
+ break;
747
+ case "formData":
748
+ emptyData = new FormData();
749
+ break;
750
+ case "stream":
751
+ emptyData = response.body;
752
+ break;
753
+ case "json":
754
+ default:
755
+ emptyData = {};
756
+ break;
757
+ }
758
+ return opts.responseStyle === "data" ? emptyData : {
759
+ data: emptyData,
760
+ ...result
761
+ };
762
+ }
763
+ let data;
764
+ switch (parseAs) {
765
+ case "arrayBuffer":
766
+ case "blob":
767
+ case "formData":
768
+ case "text":
769
+ data = await response[parseAs]();
770
+ break;
771
+ case "json": {
772
+ const text = await response.text();
773
+ data = text ? JSON.parse(text) : {};
774
+ break;
775
+ }
776
+ case "stream":
777
+ return opts.responseStyle === "data" ? response.body : {
778
+ data: response.body,
779
+ ...result
780
+ };
781
+ }
782
+ if (parseAs === "json") {
783
+ if (opts.responseValidator) {
784
+ await opts.responseValidator(data);
785
+ }
786
+ if (opts.responseTransformer) {
787
+ data = await opts.responseTransformer(data);
788
+ }
789
+ }
790
+ return opts.responseStyle === "data" ? data : {
791
+ data,
792
+ ...result
793
+ };
794
+ }
795
+ const textError = await response.text();
796
+ let jsonError;
797
+ try {
798
+ jsonError = JSON.parse(textError);
799
+ } catch {
800
+ }
801
+ throw jsonError ?? textError;
802
+ } catch (error) {
803
+ let finalError = error;
804
+ for (const fn of interceptors.error.fns) {
805
+ if (fn) {
806
+ finalError = await fn(
807
+ finalError,
808
+ response,
809
+ request2,
810
+ options
811
+ );
812
+ }
813
+ }
814
+ finalError = finalError || {};
815
+ if (throwOnError) {
816
+ throw finalError;
817
+ }
818
+ return responseStyle === "data" ? void 0 : {
819
+ error: finalError,
820
+ request: request2,
821
+ response
822
+ };
823
+ }
824
+ };
825
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
826
+ const makeSseFn = (method) => async (options) => {
827
+ const { opts, url } = await beforeRequest(options);
828
+ return createSseClient({
829
+ ...opts,
830
+ body: opts.body,
831
+ method,
832
+ onRequest: async (url2, init) => {
833
+ let request2 = new Request(url2, init);
834
+ for (const fn of interceptors.request.fns) {
835
+ if (fn) {
836
+ request2 = await fn(request2, opts);
837
+ }
838
+ }
839
+ return request2;
840
+ },
841
+ serializedBody: getValidRequestBody(opts),
842
+ url
843
+ });
844
+ };
845
+ const _buildUrl = (options) => buildUrl({ ..._config, ...options });
846
+ return {
847
+ buildUrl: _buildUrl,
848
+ connect: makeMethodFn("CONNECT"),
849
+ delete: makeMethodFn("DELETE"),
850
+ get: makeMethodFn("GET"),
851
+ getConfig,
852
+ head: makeMethodFn("HEAD"),
853
+ interceptors,
854
+ options: makeMethodFn("OPTIONS"),
855
+ patch: makeMethodFn("PATCH"),
856
+ post: makeMethodFn("POST"),
857
+ put: makeMethodFn("PUT"),
858
+ request,
859
+ setConfig,
860
+ sse: {
861
+ connect: makeSseFn("CONNECT"),
862
+ delete: makeSseFn("DELETE"),
863
+ get: makeSseFn("GET"),
864
+ head: makeSseFn("HEAD"),
865
+ options: makeSseFn("OPTIONS"),
866
+ patch: makeSseFn("PATCH"),
867
+ post: makeSseFn("POST"),
868
+ put: makeSseFn("PUT"),
869
+ trace: makeSseFn("TRACE")
870
+ },
871
+ trace: makeMethodFn("TRACE")
872
+ };
873
+ };
51
874
 
52
875
  // src/http.ts
53
876
  var IDEMPOTENT = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
@@ -69,13 +892,6 @@ function backoffMs(attempt, opts, random) {
69
892
  const jitter = exp * 0.5 * random();
70
893
  return Math.min(exp + jitter, opts.maxDelayMs);
71
894
  }
72
- function withBearer(input, init, token) {
73
- const headers = new Headers(
74
- init?.headers ?? (input instanceof Request ? input.headers : void 0)
75
- );
76
- headers.set("Authorization", `Bearer ${token}`);
77
- return { ...init, headers };
78
- }
79
895
  function createFetch(deps) {
80
896
  const baseFetch = deps.fetch ?? fetch;
81
897
  const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
@@ -89,21 +905,37 @@ function createFetch(deps) {
89
905
  return async function wrappedFetch(input, init) {
90
906
  const method = methodOf(input, init);
91
907
  const idempotent = IDEMPOTENT.has(method);
908
+ const isRequest = input instanceof Request;
92
909
  let refreshed = false;
93
910
  let attempt = 0;
911
+ let retryToken;
912
+ const dispatch = (authToken) => {
913
+ if (isRequest) {
914
+ const fresh = input.clone();
915
+ if (authToken === void 0) return baseFetch(fresh);
916
+ const headers = new Headers(fresh.headers);
917
+ headers.set("Authorization", `Bearer ${authToken}`);
918
+ return baseFetch(new Request(fresh, { headers }));
919
+ }
920
+ const nextInit = authToken === void 0 ? init : (() => {
921
+ const headers = new Headers(init?.headers);
922
+ headers.set("Authorization", `Bearer ${authToken}`);
923
+ return { ...init, headers };
924
+ })();
925
+ return baseFetch(input, nextInit);
926
+ };
94
927
  for (; ; ) {
95
928
  let response;
96
929
  let networkError;
97
930
  try {
98
- response = await baseFetch(input, init);
931
+ response = await dispatch(retryToken);
99
932
  } catch (err) {
100
933
  networkError = err;
101
934
  }
102
- const replayable = !(input instanceof Request && input.bodyUsed);
103
- if (response?.status === 401 && !refreshed && replayable && deps.tokenManager?.canRefresh) {
935
+ if (response?.status === 401 && !refreshed && deps.tokenManager?.canRefresh) {
104
936
  refreshed = true;
105
937
  const next = await deps.tokenManager.refresh();
106
- init = withBearer(input, init, next.accessToken);
938
+ retryToken = next.accessToken;
107
939
  continue;
108
940
  }
109
941
  if (response?.status === 429 && attempt < retry.maxRetries) {
@@ -126,10 +958,11 @@ function createFetch(deps) {
126
958
  // src/oauth.ts
127
959
  var import_node_crypto = require("crypto");
128
960
  var DEFAULT_AUTHORIZE_BASE_URL = "https://wefunder.com/oauth";
129
- var DEFAULT_TOKEN_BASE_URL = "https://wefunder.com/oauth";
961
+ var SANDBOX_AUTHORIZE_BASE_URL = "https://oauth.wefunder-sandbox.com/oauth";
962
+ var DEFAULT_TOKEN_BASE_URL = "https://api.wefunder.com/oauth";
130
963
  var DEFAULT_OAUTH_BASE_URL = DEFAULT_AUTHORIZE_BASE_URL;
131
- function resolveAuthorizeBase(o) {
132
- return o.authorizeBaseUrl ?? o.oauthBaseUrl ?? DEFAULT_AUTHORIZE_BASE_URL;
964
+ function defaultAuthorizeBase(clientId) {
965
+ return clientId.startsWith("pk_test_") ? SANDBOX_AUTHORIZE_BASE_URL : DEFAULT_AUTHORIZE_BASE_URL;
133
966
  }
134
967
  function resolveTokenBase(o) {
135
968
  return o.tokenBaseUrl ?? o.oauthBaseUrl ?? DEFAULT_TOKEN_BASE_URL;
@@ -169,7 +1002,7 @@ function generatePkce() {
169
1002
  return { codeVerifier, codeChallenge, codeChallengeMethod: "S256" };
170
1003
  }
171
1004
  function createAuthorizationUrl(opts) {
172
- const base = resolveAuthorizeBase(opts);
1005
+ const base = opts.authorizeBaseUrl ?? opts.oauthBaseUrl ?? defaultAuthorizeBase(opts.clientId);
173
1006
  const q = new URLSearchParams({
174
1007
  response_type: "code",
175
1008
  client_id: opts.clientId,
@@ -243,6 +1076,20 @@ var WefunderAuthError = class extends WefunderError {
243
1076
  };
244
1077
 
245
1078
  // src/token-manager.ts
1079
+ var WefunderTokenPersistenceError = class extends Error {
1080
+ tokens;
1081
+ constructor(tokens, cause) {
1082
+ super(
1083
+ `Token store failed to save the rotated token set: ${cause instanceof Error ? cause.message : String(cause)}`,
1084
+ { cause }
1085
+ );
1086
+ this.name = "WefunderTokenPersistenceError";
1087
+ this.tokens = tokens;
1088
+ }
1089
+ };
1090
+ function sameTokenSet(a, b) {
1091
+ return a.accessToken === b.accessToken && a.refreshToken === b.refreshToken;
1092
+ }
246
1093
  var TokenManager = class {
247
1094
  #tokens;
248
1095
  #clientId;
@@ -255,6 +1102,7 @@ var TokenManager = class {
255
1102
  #now;
256
1103
  #leeway;
257
1104
  #inflight;
1105
+ #pending;
258
1106
  constructor(opts) {
259
1107
  this.#tokens = opts.tokens;
260
1108
  this.#clientId = opts.clientId;
@@ -267,15 +1115,40 @@ var TokenManager = class {
267
1115
  this.#now = opts.now ?? Date.now;
268
1116
  this.#leeway = opts.expiryLeewayMs ?? 3e4;
269
1117
  }
1118
+ /** The durable, in-use token set. A rotated set that could not be persisted sits in `pendingTokens`. */
270
1119
  get current() {
271
1120
  return this.#tokens;
272
1121
  }
273
1122
  /** True if the manager can recover an expired token (rotate a refresh token or re-mint). */
274
1123
  get canRefresh() {
275
- return Boolean(this.#tokens.refreshToken && this.#clientId || this.#reMint);
1124
+ return Boolean(
1125
+ this.#tokens.refreshToken && this.#clientId || this.#reMint
1126
+ );
1127
+ }
1128
+ /** A rotated set awaiting a successful `store.save` (see `WefunderTokenPersistenceError`). */
1129
+ get pendingTokens() {
1130
+ return this.#pending;
276
1131
  }
277
- /** Returns a valid access token, refreshing proactively if it's expired/near-expiry. */
1132
+ /**
1133
+ * Tell the manager you persisted `tokens` (the set from a `WefunderTokenPersistenceError`)
1134
+ * yourself. Publishes it only if it is still the pending set — a stale acknowledgment (the
1135
+ * manager has since rotated again) is a no-op and returns false, so an older save can never
1136
+ * publish a newer, unsaved set.
1137
+ */
1138
+ async markPersisted(tokens) {
1139
+ const pending = this.#pending;
1140
+ if (!pending || !sameTokenSet(pending, tokens)) return false;
1141
+ this.#pending = void 0;
1142
+ this.#tokens = pending;
1143
+ return true;
1144
+ }
1145
+ /**
1146
+ * Returns a valid access token, refreshing proactively if it's expired/near-expiry. If a
1147
+ * rotated set is pending persistence, the save is retried first — no request uses an
1148
+ * undurable token.
1149
+ */
278
1150
  async getAccessToken() {
1151
+ if (this.#pending) await this.refresh();
279
1152
  const { expiresAt } = this.#tokens;
280
1153
  if (expiresAt !== void 0 && this.#now() >= expiresAt - this.#leeway && this.canRefresh) {
281
1154
  await this.refresh();
@@ -289,6 +1162,14 @@ var TokenManager = class {
289
1162
  */
290
1163
  async refresh() {
291
1164
  if (this.#inflight) return this.#inflight;
1165
+ if (this.#pending) {
1166
+ this.#inflight = this.#publishPending();
1167
+ try {
1168
+ return await this.#inflight;
1169
+ } finally {
1170
+ this.#inflight = void 0;
1171
+ }
1172
+ }
292
1173
  const strategy = this.#recoveryStrategy();
293
1174
  if (!strategy) {
294
1175
  throw new WefunderAuthError(
@@ -296,11 +1177,8 @@ var TokenManager = class {
296
1177
  );
297
1178
  }
298
1179
  this.#inflight = (async () => {
299
- const next = await strategy();
300
- this.#tokens = next;
301
- await this.#store?.save(next);
302
- await this.#onTokenRefresh?.(next);
303
- return next;
1180
+ this.#pending = await strategy();
1181
+ return this.#publishPending();
304
1182
  })();
305
1183
  try {
306
1184
  return await this.#inflight;
@@ -308,6 +1186,22 @@ var TokenManager = class {
308
1186
  this.#inflight = void 0;
309
1187
  }
310
1188
  }
1189
+ // Persist BEFORE publishing: no caller may use the rotated token until it is durable, and a
1190
+ // failed save must not leave the process working in memory but unable to reconnect after a
1191
+ // restart. On failure the set stays pending and WefunderTokenPersistenceError is thrown; the
1192
+ // next call retries the save.
1193
+ async #publishPending() {
1194
+ const tokens = this.#pending;
1195
+ try {
1196
+ await this.#store?.save(tokens);
1197
+ await this.#onTokenRefresh?.(tokens);
1198
+ } catch (err) {
1199
+ throw new WefunderTokenPersistenceError(tokens, err);
1200
+ }
1201
+ this.#pending = void 0;
1202
+ this.#tokens = tokens;
1203
+ return tokens;
1204
+ }
311
1205
  // Pick the recovery strategy: refresh_token rotation, else cc re-mint, else none.
312
1206
  #recoveryStrategy() {
313
1207
  const refreshTokenValue = this.#tokens.refreshToken;
@@ -357,21 +1251,36 @@ var sdk_gen_exports = {};
357
1251
  __export(sdk_gen_exports, {
358
1252
  approveSyndicateMember: () => approveSyndicateMember,
359
1253
  closeSyndicateDeal: () => closeSyndicateDeal,
1254
+ createInstallation: () => createInstallation,
1255
+ createInstallationToken: () => createInstallationToken,
360
1256
  createIntent: () => createIntent,
361
1257
  createPartnerInvite: () => createPartnerInvite,
1258
+ createWebhookEndpoint: () => createWebhookEndpoint,
362
1259
  createWebhookSubscription: () => createWebhookSubscription,
1260
+ deleteWebhookEndpoint: () => deleteWebhookEndpoint,
363
1261
  deleteWebhookSubscription: () => deleteWebhookSubscription,
364
1262
  demoteSyndicateMember: () => demoteSyndicateMember,
365
1263
  exportSyndicateMembersCsv: () => exportSyndicateMembersCsv,
366
1264
  finalizeSyndicateDeal: () => finalizeSyndicateDeal,
1265
+ followCompany: () => followCompany,
367
1266
  getAttributionMe: () => getAttributionMe,
368
1267
  getAttributionStats: () => getAttributionStats,
1268
+ getCompany: () => getCompany,
1269
+ getCompanyDisclosures: () => getCompanyDisclosures,
1270
+ getCompanyPitch: () => getCompanyPitch,
1271
+ getCompanyUpdate: () => getCompanyUpdate,
369
1272
  getCurrentUser: () => getCurrentUser,
1273
+ getInstallation: () => getInstallation,
370
1274
  getIntent: () => getIntent,
1275
+ getInvestment: () => getInvestment,
371
1276
  getOffering: () => getOffering,
1277
+ getOfferingStats: () => getOfferingStats,
1278
+ getPortfolio: () => getPortfolio,
372
1279
  getSyndicate: () => getSyndicate,
373
1280
  getSyndicateDeal: () => getSyndicateDeal,
1281
+ getSyndicatePortfolio: () => getSyndicatePortfolio,
374
1282
  getSyndicateStatistics: () => getSyndicateStatistics,
1283
+ getWebhookEndpoint: () => getWebhookEndpoint,
375
1284
  getWebhookSubscription: () => getWebhookSubscription,
376
1285
  hideSyndicateMember: () => hideSyndicateMember,
377
1286
  inviteSyndicateMember: () => inviteSyndicateMember,
@@ -379,19 +1288,31 @@ __export(sdk_gen_exports, {
379
1288
  listAttributedInvestments: () => listAttributedInvestments,
380
1289
  listAttributionCampaigns: () => listAttributionCampaigns,
381
1290
  listCampaigns: () => listCampaigns,
1291
+ listCompanyInvestmentChanges: () => listCompanyInvestmentChanges,
1292
+ listCompanyQuestions: () => listCompanyQuestions,
1293
+ listCompanyUpdates: () => listCompanyUpdates,
382
1294
  listConnectedApps: () => listConnectedApps,
1295
+ listEligibleInstallTargets: () => listEligibleInstallTargets,
1296
+ listFollowedCompanies: () => listFollowedCompanies,
1297
+ listInstallations: () => listInstallations,
383
1298
  listIntents: () => listIntents,
384
1299
  listInvestments: () => listInvestments,
1300
+ listMyCompanies: () => listMyCompanies,
385
1301
  listOfferings: () => listOfferings,
386
1302
  listPartnerInvites: () => listPartnerInvites,
1303
+ listPortfolioPositions: () => listPortfolioPositions,
387
1304
  listSyndicateDealInvestors: () => listSyndicateDealInvestors,
388
1305
  listSyndicateDeals: () => listSyndicateDeals,
389
1306
  listSyndicateMemberInvestments: () => listSyndicateMemberInvestments,
390
1307
  listSyndicateMembers: () => listSyndicateMembers,
1308
+ listSyndicatePortfolioPositions: () => listSyndicatePortfolioPositions,
391
1309
  listSyndicates: () => listSyndicates,
1310
+ listWebhookEndpoints: () => listWebhookEndpoints,
392
1311
  listWebhookSubscriptions: () => listWebhookSubscriptions,
1312
+ previewIntent: () => previewIntent,
393
1313
  promoteSyndicateMember: () => promoteSyndicateMember,
394
1314
  reactivateWebhookSubscription: () => reactivateWebhookSubscription,
1315
+ reenableWebhookEndpoint: () => reenableWebhookEndpoint,
395
1316
  regenerateWebhookSecret: () => regenerateWebhookSecret,
396
1317
  registerAsPartner: () => registerAsPartner,
397
1318
  removeSyndicateMember: () => removeSyndicateMember,
@@ -399,628 +1320,500 @@ __export(sdk_gen_exports, {
399
1320
  resendSyndicateInvite: () => resendSyndicateInvite,
400
1321
  restoreSyndicateMember: () => restoreSyndicateMember,
401
1322
  revokeConnectedApp: () => revokeConnectedApp,
1323
+ revokeInstallation: () => revokeInstallation,
402
1324
  revokePartnerInvite: () => revokePartnerInvite,
1325
+ rotateWebhookEndpointSecret: () => rotateWebhookEndpointSecret,
1326
+ searchCompanies: () => searchCompanies,
1327
+ testWebhookEndpoint: () => testWebhookEndpoint,
403
1328
  testWebhookSubscription: () => testWebhookSubscription,
1329
+ unfollowCompany: () => unfollowCompany,
404
1330
  updateSyndicate: () => updateSyndicate,
405
- updateSyndicateMember: () => updateSyndicateMember
1331
+ updateSyndicateMember: () => updateSyndicateMember,
1332
+ updateWebhookEndpoint: () => updateWebhookEndpoint
406
1333
  });
407
1334
 
408
1335
  // src/generated/client.gen.ts
409
- var import_client_fetch = require("@hey-api/client-fetch");
410
- var client = (0, import_client_fetch.createClient)((0, import_client_fetch.createConfig)());
1336
+ var client = createClient(
1337
+ createConfig({ baseUrl: "https://api.wefunder.com" })
1338
+ );
411
1339
 
412
1340
  // src/generated/sdk.gen.ts
413
- var listOfferings = (options) => {
414
- return (options?.client ?? client).get({
415
- security: [
416
- {
417
- scheme: "bearer",
418
- type: "http"
419
- }
420
- ],
421
- url: "/explore",
422
- ...options
423
- });
424
- };
425
- var getOffering = (options) => {
426
- return (options.client ?? client).get({
427
- security: [
428
- {
429
- scheme: "bearer",
430
- type: "http"
431
- }
432
- ],
433
- url: "/offerings/{external_id}",
434
- ...options
435
- });
436
- };
437
- var getCurrentUser = (options) => {
438
- return (options?.client ?? client).get({
439
- security: [
440
- {
441
- scheme: "bearer",
442
- type: "http"
443
- }
444
- ],
445
- url: "/users/me",
446
- ...options
447
- });
448
- };
449
- var listInvestments = (options) => {
450
- return (options?.client ?? client).get({
451
- security: [
452
- {
453
- scheme: "bearer",
454
- type: "http"
455
- }
456
- ],
457
- url: "/investments",
458
- ...options
459
- });
460
- };
461
- var listCampaigns = (options) => {
462
- return (options?.client ?? client).get({
463
- security: [
464
- {
465
- scheme: "bearer",
466
- type: "http"
467
- }
468
- ],
469
- url: "/campaigns",
470
- ...options
471
- });
472
- };
473
- var listSyndicates = (options) => {
474
- return (options?.client ?? client).get({
475
- security: [
476
- {
477
- scheme: "bearer",
478
- type: "http"
479
- }
480
- ],
481
- url: "/syndicates",
482
- ...options
483
- });
484
- };
485
- var getSyndicate = (options) => {
486
- return (options.client ?? client).get({
487
- security: [
488
- {
489
- scheme: "bearer",
490
- type: "http"
491
- }
492
- ],
493
- url: "/syndicates/{syndicate_id}",
494
- ...options
495
- });
496
- };
497
- var updateSyndicate = (options) => {
498
- return (options.client ?? client).patch({
499
- security: [
500
- {
501
- scheme: "bearer",
502
- type: "http"
503
- }
504
- ],
505
- url: "/syndicates/{syndicate_id}",
506
- ...options,
507
- headers: {
508
- "Content-Type": "application/json",
509
- ...options?.headers
510
- }
511
- });
512
- };
513
- var listSyndicateMembers = (options) => {
514
- return (options.client ?? client).get({
515
- security: [
516
- {
517
- scheme: "bearer",
518
- type: "http"
519
- }
520
- ],
521
- url: "/syndicates/{syndicate_id}/members",
522
- ...options
523
- });
524
- };
525
- var inviteSyndicateMember = (options) => {
526
- return (options.client ?? client).post({
527
- security: [
528
- {
529
- scheme: "bearer",
530
- type: "http"
531
- }
532
- ],
533
- url: "/syndicates/{syndicate_id}/members/invite",
534
- ...options,
535
- headers: {
536
- "Content-Type": "application/json",
537
- ...options?.headers
538
- }
539
- });
540
- };
541
- var removeSyndicateMember = (options) => {
542
- return (options.client ?? client).delete({
543
- security: [
544
- {
545
- scheme: "bearer",
546
- type: "http"
547
- }
548
- ],
549
- url: "/syndicates/{syndicate_id}/members/{member_id}",
550
- ...options
551
- });
552
- };
553
- var updateSyndicateMember = (options) => {
554
- return (options.client ?? client).patch({
555
- security: [
556
- {
557
- scheme: "bearer",
558
- type: "http"
559
- }
560
- ],
561
- url: "/syndicates/{syndicate_id}/members/{member_id}",
562
- ...options,
563
- headers: {
564
- "Content-Type": "application/json",
565
- ...options?.headers
566
- }
567
- });
568
- };
569
- var approveSyndicateMember = (options) => {
570
- return (options.client ?? client).post({
571
- security: [
572
- {
573
- scheme: "bearer",
574
- type: "http"
575
- }
576
- ],
577
- url: "/syndicates/{syndicate_id}/members/{member_id}/approve",
578
- ...options
579
- });
580
- };
581
- var hideSyndicateMember = (options) => {
582
- return (options.client ?? client).post({
583
- security: [
584
- {
585
- scheme: "bearer",
586
- type: "http"
587
- }
588
- ],
589
- url: "/syndicates/{syndicate_id}/members/{member_id}/hide",
590
- ...options
591
- });
592
- };
593
- var promoteSyndicateMember = (options) => {
594
- return (options.client ?? client).post({
595
- security: [
596
- {
597
- scheme: "bearer",
598
- type: "http"
599
- }
600
- ],
601
- url: "/syndicates/{syndicate_id}/members/{member_id}/promote",
602
- ...options
603
- });
604
- };
605
- var demoteSyndicateMember = (options) => {
606
- return (options.client ?? client).post({
607
- security: [
608
- {
609
- scheme: "bearer",
610
- type: "http"
611
- }
612
- ],
613
- url: "/syndicates/{syndicate_id}/members/{member_id}/demote",
614
- ...options
615
- });
616
- };
617
- var restoreSyndicateMember = (options) => {
618
- return (options.client ?? client).post({
619
- security: [
620
- {
621
- scheme: "bearer",
622
- type: "http"
623
- }
624
- ],
625
- url: "/syndicates/{syndicate_id}/members/{member_id}/restore",
626
- ...options
627
- });
628
- };
629
- var resendSyndicateInvite = (options) => {
630
- return (options.client ?? client).post({
631
- security: [
632
- {
633
- scheme: "bearer",
634
- type: "http"
635
- }
636
- ],
637
- url: "/syndicates/{syndicate_id}/members/{member_id}/resend_invite",
638
- ...options
639
- });
640
- };
641
- var reorderSyndicateMembers = (options) => {
642
- return (options.client ?? client).post({
643
- security: [
644
- {
645
- scheme: "bearer",
646
- type: "http"
647
- }
648
- ],
649
- url: "/syndicates/{syndicate_id}/members/reorder",
650
- ...options,
651
- headers: {
652
- "Content-Type": "application/json",
653
- ...options?.headers
654
- }
655
- });
656
- };
657
- var exportSyndicateMembersCsv = (options) => {
658
- return (options.client ?? client).post({
659
- security: [
660
- {
661
- scheme: "bearer",
662
- type: "http"
663
- }
664
- ],
665
- url: "/syndicates/{syndicate_id}/members/export_csv",
666
- ...options
667
- });
668
- };
669
- var listSyndicateDeals = (options) => {
670
- return (options.client ?? client).get({
671
- security: [
672
- {
673
- scheme: "bearer",
674
- type: "http"
675
- }
676
- ],
677
- url: "/syndicates/{syndicate_id}/deals",
678
- ...options
679
- });
680
- };
681
- var getSyndicateDeal = (options) => {
682
- return (options.client ?? client).get({
683
- security: [
684
- {
685
- scheme: "bearer",
686
- type: "http"
687
- }
688
- ],
689
- url: "/syndicates/{syndicate_id}/deals/{fundraise_id}",
690
- ...options
691
- });
692
- };
693
- var listSyndicateDealInvestors = (options) => {
694
- return (options.client ?? client).get({
695
- security: [
696
- {
697
- scheme: "bearer",
698
- type: "http"
699
- }
700
- ],
701
- url: "/syndicates/{syndicate_id}/deals/{fundraise_id}/investors",
702
- ...options
703
- });
704
- };
705
- var listSyndicateMemberInvestments = (options) => {
706
- return (options.client ?? client).get({
707
- security: [
708
- {
709
- scheme: "bearer",
710
- type: "http"
711
- }
712
- ],
713
- url: "/syndicates/{syndicate_id}/members/{member_id}/investments",
714
- ...options
715
- });
716
- };
717
- var getSyndicateStatistics = (options) => {
718
- return (options.client ?? client).get({
719
- security: [
720
- {
721
- scheme: "bearer",
722
- type: "http"
723
- }
724
- ],
725
- url: "/syndicates/{syndicate_id}/statistics",
726
- ...options
727
- });
728
- };
729
- var closeSyndicateDeal = (options) => {
730
- return (options.client ?? client).post({
731
- security: [
732
- {
733
- scheme: "bearer",
734
- type: "http"
735
- }
736
- ],
737
- url: "/syndicates/{syndicate_id}/deals/{fundraise_id}/close",
738
- ...options
739
- });
740
- };
741
- var finalizeSyndicateDeal = (options) => {
742
- return (options.client ?? client).post({
743
- security: [
744
- {
745
- scheme: "bearer",
746
- type: "http"
747
- }
748
- ],
749
- url: "/syndicates/{syndicate_id}/deals/{fundraise_id}/finalize",
750
- ...options
751
- });
752
- };
753
- var listIntents = (options) => {
754
- return (options?.client ?? client).get({
755
- security: [
756
- {
757
- scheme: "bearer",
758
- type: "http"
759
- }
760
- ],
761
- url: "/intents",
762
- ...options
763
- });
764
- };
765
- var createIntent = (options) => {
766
- return (options.client ?? client).post({
767
- security: [
768
- {
769
- scheme: "bearer",
770
- type: "http"
771
- }
772
- ],
773
- url: "/intents",
774
- ...options,
775
- headers: {
776
- "Content-Type": "application/json",
777
- ...options?.headers
1341
+ var listOfferings = (options) => (options?.client ?? client).get({
1342
+ querySerializer: {
1343
+ parameters: {
1344
+ industry: { array: { explode: false } },
1345
+ business_model: { array: { explode: false } }
778
1346
  }
779
- });
780
- };
781
- var getIntent = (options) => {
782
- return (options.client ?? client).get({
783
- security: [
784
- {
785
- scheme: "bearer",
786
- type: "http"
787
- }
788
- ],
789
- url: "/intents/{intent_id}",
790
- ...options
791
- });
792
- };
793
- var listActivity = (options) => {
794
- return (options?.client ?? client).get({
795
- security: [
796
- {
797
- scheme: "bearer",
798
- type: "http"
799
- }
800
- ],
801
- url: "/activity",
802
- ...options
803
- });
804
- };
805
- var listConnectedApps = (options) => {
806
- return (options?.client ?? client).get({
807
- security: [
808
- {
809
- scheme: "bearer",
810
- type: "http"
811
- }
812
- ],
813
- url: "/connected-apps",
814
- ...options
815
- });
816
- };
817
- var revokeConnectedApp = (options) => {
818
- return (options.client ?? client).delete({
819
- security: [
820
- {
821
- scheme: "bearer",
822
- type: "http"
823
- }
824
- ],
825
- url: "/connected-apps/{app_id}",
826
- ...options
827
- });
828
- };
829
- var getAttributionStats = (options) => {
830
- return (options.client ?? client).get({
831
- security: [
832
- {
833
- scheme: "bearer",
834
- type: "http"
835
- }
836
- ],
837
- url: "/campaigns/{campaign_id}/attribution/stats",
838
- ...options
839
- });
840
- };
841
- var listAttributedInvestments = (options) => {
842
- return (options.client ?? client).get({
843
- security: [
844
- {
845
- scheme: "bearer",
846
- type: "http"
847
- }
848
- ],
849
- url: "/campaigns/{campaign_id}/attribution/investments",
850
- ...options
851
- });
852
- };
853
- var listWebhookSubscriptions = (options) => {
854
- return (options.client ?? client).get({
855
- security: [
856
- {
857
- scheme: "bearer",
858
- type: "http"
859
- }
860
- ],
861
- url: "/campaigns/{campaign_id}/attribution/webhooks",
862
- ...options
863
- });
864
- };
865
- var createWebhookSubscription = (options) => {
866
- return (options.client ?? client).post({
867
- security: [
868
- {
869
- scheme: "bearer",
870
- type: "http"
871
- }
872
- ],
873
- url: "/campaigns/{campaign_id}/attribution/webhooks",
874
- ...options,
875
- headers: {
876
- "Content-Type": "application/json",
877
- ...options?.headers
878
- }
879
- });
880
- };
881
- var deleteWebhookSubscription = (options) => {
882
- return (options.client ?? client).delete({
883
- security: [
884
- {
885
- scheme: "bearer",
886
- type: "http"
887
- }
888
- ],
889
- url: "/campaigns/{campaign_id}/attribution/webhooks/{webhook_id}",
890
- ...options
891
- });
892
- };
893
- var getWebhookSubscription = (options) => {
894
- return (options.client ?? client).get({
895
- security: [
896
- {
897
- scheme: "bearer",
898
- type: "http"
899
- }
900
- ],
901
- url: "/campaigns/{campaign_id}/attribution/webhooks/{webhook_id}",
902
- ...options
903
- });
904
- };
905
- var testWebhookSubscription = (options) => {
906
- return (options.client ?? client).post({
907
- security: [
908
- {
909
- scheme: "bearer",
910
- type: "http"
911
- }
912
- ],
913
- url: "/campaigns/{campaign_id}/attribution/webhooks/{webhook_id}/test",
914
- ...options
915
- });
916
- };
917
- var regenerateWebhookSecret = (options) => {
918
- return (options.client ?? client).post({
919
- security: [
920
- {
921
- scheme: "bearer",
922
- type: "http"
923
- }
924
- ],
925
- url: "/campaigns/{campaign_id}/attribution/webhooks/{webhook_id}/regenerate_secret",
926
- ...options
927
- });
928
- };
929
- var reactivateWebhookSubscription = (options) => {
930
- return (options.client ?? client).post({
931
- security: [
932
- {
933
- scheme: "bearer",
934
- type: "http"
935
- }
936
- ],
937
- url: "/campaigns/{campaign_id}/attribution/webhooks/{webhook_id}/reactivate",
938
- ...options
939
- });
940
- };
941
- var getAttributionMe = (options) => {
942
- return (options?.client ?? client).get({
943
- security: [
944
- {
945
- scheme: "bearer",
946
- type: "http"
947
- }
948
- ],
949
- url: "/attribution/me",
950
- ...options
951
- });
952
- };
953
- var listAttributionCampaigns = (options) => {
954
- return (options?.client ?? client).get({
955
- security: [
956
- {
957
- scheme: "bearer",
958
- type: "http"
959
- }
960
- ],
961
- url: "/attribution/campaigns",
962
- ...options
963
- });
964
- };
965
- var registerAsPartner = (options) => {
966
- return (options.client ?? client).post({
967
- security: [
968
- {
969
- scheme: "bearer",
970
- type: "http"
971
- }
972
- ],
973
- url: "/attribution/partners/register",
974
- ...options,
975
- headers: {
976
- "Content-Type": "application/json",
977
- ...options?.headers
978
- }
979
- });
980
- };
981
- var listPartnerInvites = (options) => {
982
- return (options?.client ?? client).get({
983
- security: [
984
- {
985
- scheme: "bearer",
986
- type: "http"
987
- }
988
- ],
989
- url: "/attribution/invites",
990
- ...options
991
- });
992
- };
993
- var createPartnerInvite = (options) => {
994
- return (options.client ?? client).post({
995
- security: [
996
- {
997
- scheme: "bearer",
998
- type: "http"
999
- }
1000
- ],
1001
- url: "/attribution/invites",
1002
- ...options,
1003
- headers: {
1004
- "Content-Type": "application/json",
1005
- ...options?.headers
1006
- }
1007
- });
1008
- };
1009
- var revokePartnerInvite = (options) => {
1010
- return (options.client ?? client).delete({
1011
- security: [
1012
- {
1013
- scheme: "bearer",
1014
- type: "http"
1015
- }
1016
- ],
1017
- url: "/attribution/invites/{token}",
1018
- ...options
1019
- });
1020
- };
1347
+ },
1348
+ security: [{ scheme: "bearer", type: "http" }],
1349
+ url: "/explore",
1350
+ ...options
1351
+ });
1352
+ var getOffering = (options) => (options.client ?? client).get({
1353
+ security: [{ scheme: "bearer", type: "http" }],
1354
+ url: "/offerings/{external_id}",
1355
+ ...options
1356
+ });
1357
+ var getCompanyDisclosures = (options) => (options.client ?? client).get({
1358
+ querySerializer: {
1359
+ parameters: { sections: { array: { explode: false } } }
1360
+ },
1361
+ security: [{ scheme: "bearer", type: "http" }],
1362
+ url: "/companies/{id}/disclosures",
1363
+ ...options
1364
+ });
1365
+ var getCompanyPitch = (options) => (options.client ?? client).get({
1366
+ querySerializer: {
1367
+ parameters: { sections: { array: { explode: false } } }
1368
+ },
1369
+ security: [{ scheme: "bearer", type: "http" }],
1370
+ url: "/companies/{id}/pitch",
1371
+ ...options
1372
+ });
1373
+ var listCompanyUpdates = (options) => (options.client ?? client).get({
1374
+ security: [{ scheme: "bearer", type: "http" }],
1375
+ url: "/companies/{id}/updates",
1376
+ ...options
1377
+ });
1378
+ var getCompanyUpdate = (options) => (options.client ?? client).get({
1379
+ security: [{ scheme: "bearer", type: "http" }],
1380
+ url: "/companies/{id}/updates/{update_id}",
1381
+ ...options
1382
+ });
1383
+ var listCompanyQuestions = (options) => (options.client ?? client).get({
1384
+ security: [{ scheme: "bearer", type: "http" }],
1385
+ url: "/companies/{id}/questions",
1386
+ ...options
1387
+ });
1388
+ var searchCompanies = (options) => (options.client ?? client).get({
1389
+ security: [{ scheme: "bearer", type: "http" }],
1390
+ url: "/companies/search",
1391
+ ...options
1392
+ });
1393
+ var getCompany = (options) => (options.client ?? client).get({
1394
+ security: [{ scheme: "bearer", type: "http" }],
1395
+ url: "/companies/{id}",
1396
+ ...options
1397
+ });
1398
+ var getCurrentUser = (options) => (options?.client ?? client).get({
1399
+ security: [{ scheme: "bearer", type: "http" }],
1400
+ url: "/users/me",
1401
+ ...options
1402
+ });
1403
+ var listMyCompanies = (options) => (options?.client ?? client).get({
1404
+ security: [{ scheme: "bearer", type: "http" }],
1405
+ url: "/users/me/companies",
1406
+ ...options
1407
+ });
1408
+ var listFollowedCompanies = (options) => (options?.client ?? client).get({
1409
+ security: [{ scheme: "bearer", type: "http" }],
1410
+ url: "/users/me/follows",
1411
+ ...options
1412
+ });
1413
+ var unfollowCompany = (options) => (options.client ?? client).delete({
1414
+ security: [{ scheme: "bearer", type: "http" }],
1415
+ url: "/users/me/follows/{company_id}",
1416
+ ...options
1417
+ });
1418
+ var followCompany = (options) => (options.client ?? client).put({
1419
+ security: [{ scheme: "bearer", type: "http" }],
1420
+ url: "/users/me/follows/{company_id}",
1421
+ ...options
1422
+ });
1423
+ var listInvestments = (options) => (options?.client ?? client).get({
1424
+ security: [{ scheme: "bearer", type: "http" }],
1425
+ url: "/investments",
1426
+ ...options
1427
+ });
1428
+ var getInvestment = (options) => (options.client ?? client).get({
1429
+ security: [{ scheme: "bearer", type: "http" }],
1430
+ url: "/investments/{id}",
1431
+ ...options
1432
+ });
1433
+ var getOfferingStats = (options) => (options.client ?? client).get({
1434
+ security: [{ scheme: "bearer", type: "http" }],
1435
+ url: "/offerings/{offering_id}/stats",
1436
+ ...options
1437
+ });
1438
+ var listCompanyInvestmentChanges = (options) => (options.client ?? client).get({
1439
+ security: [{ scheme: "bearer", type: "http" }],
1440
+ url: "/companies/{company_id}/investments/changes",
1441
+ ...options
1442
+ });
1443
+ var getPortfolio = (options) => (options?.client ?? client).get({
1444
+ security: [{ scheme: "bearer", type: "http" }],
1445
+ url: "/portfolio",
1446
+ ...options
1447
+ });
1448
+ var listPortfolioPositions = (options) => (options?.client ?? client).get({
1449
+ security: [{ scheme: "bearer", type: "http" }],
1450
+ url: "/portfolio/positions",
1451
+ ...options
1452
+ });
1453
+ var listCampaigns = (options) => (options?.client ?? client).get({
1454
+ security: [{ scheme: "bearer", type: "http" }],
1455
+ url: "/campaigns",
1456
+ ...options
1457
+ });
1458
+ var listSyndicates = (options) => (options?.client ?? client).get({
1459
+ security: [{ scheme: "bearer", type: "http" }],
1460
+ url: "/syndicates",
1461
+ ...options
1462
+ });
1463
+ var getSyndicate = (options) => (options.client ?? client).get({
1464
+ security: [{ scheme: "bearer", type: "http" }],
1465
+ url: "/syndicates/{syndicate_id}",
1466
+ ...options
1467
+ });
1468
+ var updateSyndicate = (options) => (options.client ?? client).patch({
1469
+ security: [{ scheme: "bearer", type: "http" }],
1470
+ url: "/syndicates/{syndicate_id}",
1471
+ ...options,
1472
+ headers: {
1473
+ "Content-Type": "application/json",
1474
+ ...options.headers
1475
+ }
1476
+ });
1477
+ var listSyndicateMembers = (options) => (options.client ?? client).get({
1478
+ security: [{ scheme: "bearer", type: "http" }],
1479
+ url: "/syndicates/{syndicate_id}/members",
1480
+ ...options
1481
+ });
1482
+ var inviteSyndicateMember = (options) => (options.client ?? client).post({
1483
+ security: [{ scheme: "bearer", type: "http" }],
1484
+ url: "/syndicates/{syndicate_id}/members/invite",
1485
+ ...options,
1486
+ headers: {
1487
+ "Content-Type": "application/json",
1488
+ ...options.headers
1489
+ }
1490
+ });
1491
+ var removeSyndicateMember = (options) => (options.client ?? client).delete({
1492
+ security: [{ scheme: "bearer", type: "http" }],
1493
+ url: "/syndicates/{syndicate_id}/members/{member_id}",
1494
+ ...options
1495
+ });
1496
+ var updateSyndicateMember = (options) => (options.client ?? client).patch({
1497
+ security: [{ scheme: "bearer", type: "http" }],
1498
+ url: "/syndicates/{syndicate_id}/members/{member_id}",
1499
+ ...options,
1500
+ headers: {
1501
+ "Content-Type": "application/json",
1502
+ ...options.headers
1503
+ }
1504
+ });
1505
+ var approveSyndicateMember = (options) => (options.client ?? client).post({
1506
+ security: [{ scheme: "bearer", type: "http" }],
1507
+ url: "/syndicates/{syndicate_id}/members/{member_id}/approve",
1508
+ ...options
1509
+ });
1510
+ var hideSyndicateMember = (options) => (options.client ?? client).post({
1511
+ security: [{ scheme: "bearer", type: "http" }],
1512
+ url: "/syndicates/{syndicate_id}/members/{member_id}/hide",
1513
+ ...options
1514
+ });
1515
+ var promoteSyndicateMember = (options) => (options.client ?? client).post({
1516
+ security: [{ scheme: "bearer", type: "http" }],
1517
+ url: "/syndicates/{syndicate_id}/members/{member_id}/promote",
1518
+ ...options
1519
+ });
1520
+ var demoteSyndicateMember = (options) => (options.client ?? client).post({
1521
+ security: [{ scheme: "bearer", type: "http" }],
1522
+ url: "/syndicates/{syndicate_id}/members/{member_id}/demote",
1523
+ ...options
1524
+ });
1525
+ var restoreSyndicateMember = (options) => (options.client ?? client).post({
1526
+ security: [{ scheme: "bearer", type: "http" }],
1527
+ url: "/syndicates/{syndicate_id}/members/{member_id}/restore",
1528
+ ...options
1529
+ });
1530
+ var resendSyndicateInvite = (options) => (options.client ?? client).post({
1531
+ security: [{ scheme: "bearer", type: "http" }],
1532
+ url: "/syndicates/{syndicate_id}/members/{member_id}/resend_invite",
1533
+ ...options
1534
+ });
1535
+ var reorderSyndicateMembers = (options) => (options.client ?? client).post({
1536
+ security: [{ scheme: "bearer", type: "http" }],
1537
+ url: "/syndicates/{syndicate_id}/members/reorder",
1538
+ ...options,
1539
+ headers: {
1540
+ "Content-Type": "application/json",
1541
+ ...options.headers
1542
+ }
1543
+ });
1544
+ var exportSyndicateMembersCsv = (options) => (options.client ?? client).post({
1545
+ security: [{ scheme: "bearer", type: "http" }],
1546
+ url: "/syndicates/{syndicate_id}/members/export_csv",
1547
+ ...options
1548
+ });
1549
+ var listSyndicateDeals = (options) => (options.client ?? client).get({
1550
+ security: [{ scheme: "bearer", type: "http" }],
1551
+ url: "/syndicates/{syndicate_id}/deals",
1552
+ ...options
1553
+ });
1554
+ var getSyndicateDeal = (options) => (options.client ?? client).get({
1555
+ security: [{ scheme: "bearer", type: "http" }],
1556
+ url: "/syndicates/{syndicate_id}/deals/{fundraise_id}",
1557
+ ...options
1558
+ });
1559
+ var listSyndicateDealInvestors = (options) => (options.client ?? client).get({
1560
+ security: [{ scheme: "bearer", type: "http" }],
1561
+ url: "/syndicates/{syndicate_id}/deals/{fundraise_id}/investors",
1562
+ ...options
1563
+ });
1564
+ var listSyndicateMemberInvestments = (options) => (options.client ?? client).get({
1565
+ security: [{ scheme: "bearer", type: "http" }],
1566
+ url: "/syndicates/{syndicate_id}/members/{member_id}/investments",
1567
+ ...options
1568
+ });
1569
+ var getSyndicateStatistics = (options) => (options.client ?? client).get({
1570
+ security: [{ scheme: "bearer", type: "http" }],
1571
+ url: "/syndicates/{syndicate_id}/statistics",
1572
+ ...options
1573
+ });
1574
+ var getSyndicatePortfolio = (options) => (options.client ?? client).get({
1575
+ security: [{ scheme: "bearer", type: "http" }],
1576
+ url: "/syndicates/{syndicate_id}/portfolio",
1577
+ ...options
1578
+ });
1579
+ var listSyndicatePortfolioPositions = (options) => (options.client ?? client).get({
1580
+ security: [{ scheme: "bearer", type: "http" }],
1581
+ url: "/syndicates/{syndicate_id}/portfolio/positions",
1582
+ ...options
1583
+ });
1584
+ var closeSyndicateDeal = (options) => (options.client ?? client).post({
1585
+ security: [{ scheme: "bearer", type: "http" }],
1586
+ url: "/syndicates/{syndicate_id}/deals/{fundraise_id}/close",
1587
+ ...options
1588
+ });
1589
+ var finalizeSyndicateDeal = (options) => (options.client ?? client).post({
1590
+ security: [{ scheme: "bearer", type: "http" }],
1591
+ url: "/syndicates/{syndicate_id}/deals/{fundraise_id}/finalize",
1592
+ ...options
1593
+ });
1594
+ var previewIntent = (options) => (options.client ?? client).post({
1595
+ security: [{ scheme: "bearer", type: "http" }],
1596
+ url: "/intents/preview",
1597
+ ...options,
1598
+ headers: {
1599
+ "Content-Type": "application/json",
1600
+ ...options.headers
1601
+ }
1602
+ });
1603
+ var listIntents = (options) => (options?.client ?? client).get({
1604
+ security: [{ scheme: "bearer", type: "http" }],
1605
+ url: "/intents",
1606
+ ...options
1607
+ });
1608
+ var createIntent = (options) => (options.client ?? client).post({
1609
+ security: [{ scheme: "bearer", type: "http" }],
1610
+ url: "/intents",
1611
+ ...options,
1612
+ headers: {
1613
+ "Content-Type": "application/json",
1614
+ ...options.headers
1615
+ }
1616
+ });
1617
+ var getIntent = (options) => (options.client ?? client).get({
1618
+ security: [{ scheme: "bearer", type: "http" }],
1619
+ url: "/intents/{intent_id}",
1620
+ ...options
1621
+ });
1622
+ var listActivity = (options) => (options?.client ?? client).get({
1623
+ security: [{ scheme: "bearer", type: "http" }],
1624
+ url: "/activity",
1625
+ ...options
1626
+ });
1627
+ var listConnectedApps = (options) => (options?.client ?? client).get({
1628
+ security: [{ scheme: "bearer", type: "http" }],
1629
+ url: "/connected-apps",
1630
+ ...options
1631
+ });
1632
+ var revokeConnectedApp = (options) => (options.client ?? client).delete({
1633
+ security: [{ scheme: "bearer", type: "http" }],
1634
+ url: "/connected-apps/{app_id}",
1635
+ ...options
1636
+ });
1637
+ var getAttributionStats = (options) => (options.client ?? client).get({
1638
+ security: [{ scheme: "bearer", type: "http" }],
1639
+ url: "/campaigns/{campaign_id}/attribution/stats",
1640
+ ...options
1641
+ });
1642
+ var listAttributedInvestments = (options) => (options.client ?? client).get({
1643
+ security: [{ scheme: "bearer", type: "http" }],
1644
+ url: "/campaigns/{campaign_id}/attribution/investments",
1645
+ ...options
1646
+ });
1647
+ var listInstallations = (options) => (options?.client ?? client).get({
1648
+ security: [{ scheme: "bearer", type: "http" }],
1649
+ url: "/installations",
1650
+ ...options
1651
+ });
1652
+ var createInstallation = (options) => (options.client ?? client).post({
1653
+ security: [{ scheme: "bearer", type: "http" }],
1654
+ url: "/installations",
1655
+ ...options,
1656
+ headers: {
1657
+ "Content-Type": "application/json",
1658
+ ...options.headers
1659
+ }
1660
+ });
1661
+ var listEligibleInstallTargets = (options) => (options?.client ?? client).get({
1662
+ security: [{ scheme: "bearer", type: "http" }],
1663
+ url: "/installations/eligible",
1664
+ ...options
1665
+ });
1666
+ var revokeInstallation = (options) => (options.client ?? client).delete({
1667
+ security: [{ scheme: "bearer", type: "http" }],
1668
+ url: "/installations/{external_id}",
1669
+ ...options
1670
+ });
1671
+ var getInstallation = (options) => (options.client ?? client).get({
1672
+ security: [{ scheme: "bearer", type: "http" }],
1673
+ url: "/installations/{external_id}",
1674
+ ...options
1675
+ });
1676
+ var createInstallationToken = (options) => (options.client ?? client).post({
1677
+ security: [{ scheme: "bearer", type: "http" }],
1678
+ url: "/installations/{external_id}/tokens",
1679
+ ...options,
1680
+ headers: {
1681
+ "Content-Type": "application/json",
1682
+ ...options.headers
1683
+ }
1684
+ });
1685
+ var listWebhookEndpoints = (options) => (options?.client ?? client).get({
1686
+ security: [{ scheme: "bearer", type: "http" }],
1687
+ url: "/webhook_endpoints",
1688
+ ...options
1689
+ });
1690
+ var createWebhookEndpoint = (options) => (options.client ?? client).post({
1691
+ security: [{ scheme: "bearer", type: "http" }],
1692
+ url: "/webhook_endpoints",
1693
+ ...options,
1694
+ headers: {
1695
+ "Content-Type": "application/json",
1696
+ ...options.headers
1697
+ }
1698
+ });
1699
+ var deleteWebhookEndpoint = (options) => (options.client ?? client).delete({
1700
+ security: [{ scheme: "bearer", type: "http" }],
1701
+ url: "/webhook_endpoints/{external_id}",
1702
+ ...options
1703
+ });
1704
+ var getWebhookEndpoint = (options) => (options.client ?? client).get({
1705
+ security: [{ scheme: "bearer", type: "http" }],
1706
+ url: "/webhook_endpoints/{external_id}",
1707
+ ...options
1708
+ });
1709
+ var updateWebhookEndpoint = (options) => (options.client ?? client).patch({
1710
+ security: [{ scheme: "bearer", type: "http" }],
1711
+ url: "/webhook_endpoints/{external_id}",
1712
+ ...options,
1713
+ headers: {
1714
+ "Content-Type": "application/json",
1715
+ ...options.headers
1716
+ }
1717
+ });
1718
+ var rotateWebhookEndpointSecret = (options) => (options.client ?? client).post({
1719
+ security: [{ scheme: "bearer", type: "http" }],
1720
+ url: "/webhook_endpoints/{external_id}/rotate_secret",
1721
+ ...options
1722
+ });
1723
+ var reenableWebhookEndpoint = (options) => (options.client ?? client).post({
1724
+ security: [{ scheme: "bearer", type: "http" }],
1725
+ url: "/webhook_endpoints/{external_id}/reenable",
1726
+ ...options
1727
+ });
1728
+ var testWebhookEndpoint = (options) => (options.client ?? client).post({
1729
+ security: [{ scheme: "bearer", type: "http" }],
1730
+ url: "/webhook_endpoints/{external_id}/test",
1731
+ ...options,
1732
+ headers: {
1733
+ "Content-Type": "application/json",
1734
+ ...options.headers
1735
+ }
1736
+ });
1737
+ var listWebhookSubscriptions = (options) => (options.client ?? client).get({
1738
+ security: [{ scheme: "bearer", type: "http" }],
1739
+ url: "/campaigns/{campaign_id}/attribution/webhooks",
1740
+ ...options
1741
+ });
1742
+ var createWebhookSubscription = (options) => (options.client ?? client).post({
1743
+ security: [{ scheme: "bearer", type: "http" }],
1744
+ url: "/campaigns/{campaign_id}/attribution/webhooks",
1745
+ ...options,
1746
+ headers: {
1747
+ "Content-Type": "application/json",
1748
+ ...options.headers
1749
+ }
1750
+ });
1751
+ var deleteWebhookSubscription = (options) => (options.client ?? client).delete({
1752
+ security: [{ scheme: "bearer", type: "http" }],
1753
+ url: "/campaigns/{campaign_id}/attribution/webhooks/{webhook_id}",
1754
+ ...options
1755
+ });
1756
+ var getWebhookSubscription = (options) => (options.client ?? client).get({
1757
+ security: [{ scheme: "bearer", type: "http" }],
1758
+ url: "/campaigns/{campaign_id}/attribution/webhooks/{webhook_id}",
1759
+ ...options
1760
+ });
1761
+ var testWebhookSubscription = (options) => (options.client ?? client).post({
1762
+ security: [{ scheme: "bearer", type: "http" }],
1763
+ url: "/campaigns/{campaign_id}/attribution/webhooks/{webhook_id}/test",
1764
+ ...options
1765
+ });
1766
+ var regenerateWebhookSecret = (options) => (options.client ?? client).post({
1767
+ security: [{ scheme: "bearer", type: "http" }],
1768
+ url: "/campaigns/{campaign_id}/attribution/webhooks/{webhook_id}/regenerate_secret",
1769
+ ...options
1770
+ });
1771
+ var reactivateWebhookSubscription = (options) => (options.client ?? client).post({
1772
+ security: [{ scheme: "bearer", type: "http" }],
1773
+ url: "/campaigns/{campaign_id}/attribution/webhooks/{webhook_id}/reactivate",
1774
+ ...options
1775
+ });
1776
+ var getAttributionMe = (options) => (options?.client ?? client).get({
1777
+ security: [{ scheme: "bearer", type: "http" }],
1778
+ url: "/attribution/me",
1779
+ ...options
1780
+ });
1781
+ var listAttributionCampaigns = (options) => (options?.client ?? client).get({
1782
+ security: [{ scheme: "bearer", type: "http" }],
1783
+ url: "/attribution/campaigns",
1784
+ ...options
1785
+ });
1786
+ var registerAsPartner = (options) => (options.client ?? client).post({
1787
+ security: [{ scheme: "bearer", type: "http" }],
1788
+ url: "/attribution/partners/register",
1789
+ ...options,
1790
+ headers: {
1791
+ "Content-Type": "application/json",
1792
+ ...options.headers
1793
+ }
1794
+ });
1795
+ var listPartnerInvites = (options) => (options?.client ?? client).get({
1796
+ security: [{ scheme: "bearer", type: "http" }],
1797
+ url: "/attribution/invites",
1798
+ ...options
1799
+ });
1800
+ var createPartnerInvite = (options) => (options.client ?? client).post({
1801
+ security: [{ scheme: "bearer", type: "http" }],
1802
+ url: "/attribution/invites",
1803
+ ...options,
1804
+ headers: {
1805
+ "Content-Type": "application/json",
1806
+ ...options.headers
1807
+ }
1808
+ });
1809
+ var revokePartnerInvite = (options) => (options.client ?? client).delete({
1810
+ security: [{ scheme: "bearer", type: "http" }],
1811
+ url: "/attribution/invites/{token}",
1812
+ ...options
1813
+ });
1021
1814
 
1022
1815
  // src/client.ts
1023
- var DEFAULT_API_BASE_URL = "https://api.wefunder.com/api/v2";
1816
+ var DEFAULT_API_BASE_URL = "https://api.wefunder.com";
1024
1817
  var DEFAULT_API_VERSION = "2025-01-15";
1025
1818
  function modeForToken(token) {
1026
1819
  if (token.startsWith("at_live_")) return "live";
@@ -1067,7 +1860,7 @@ var Wefunder = class _Wefunder {
1067
1860
  random: opts.random,
1068
1861
  retry: opts.retry
1069
1862
  });
1070
- this.#client = (0, import_client_fetch2.createClient)({
1863
+ this.#client = createClient({
1071
1864
  baseUrl: opts.baseUrl ?? DEFAULT_API_BASE_URL,
1072
1865
  headers: { "Wefunder-Version": opts.apiVersion ?? DEFAULT_API_VERSION },
1073
1866
  auth: () => this.#tokens.getAccessToken(),
@@ -1101,12 +1894,22 @@ var Wefunder = class _Wefunder {
1101
1894
  });
1102
1895
  }
1103
1896
  /** The live token set (e.g. to persist after construction). */
1897
+ /** A rotated set awaiting a successful save (see `WefunderTokenPersistenceError`). */
1898
+ get pendingTokens() {
1899
+ return this.#tokens.pendingTokens;
1900
+ }
1901
+ /** Acknowledge an out-of-band save of `tokens`; false if that set is no longer pending. */
1902
+ markPersisted(tokens) {
1903
+ return this.#tokens.markPersisted(tokens);
1904
+ }
1104
1905
  get tokens() {
1105
1906
  return this.#tokens.current;
1106
1907
  }
1107
1908
  // ---- unwrap: turn the {data,error,response} result into data-or-throw ----
1108
1909
  async #unwrap(p) {
1109
1910
  const { data, error, response } = await p;
1911
+ if (error instanceof WefunderTokenPersistenceError || error instanceof WefunderError)
1912
+ throw error;
1110
1913
  if (response && response.ok && error === void 0) return data;
1111
1914
  const status = response?.status ?? 0;
1112
1915
  const env = error ?? {};
@@ -1115,7 +1918,10 @@ var Wefunder = class _Wefunder {
1115
1918
  type: env.error?.type ?? "api_error",
1116
1919
  message: env.error?.message ?? response?.statusText ?? "Request failed",
1117
1920
  // X-Wf-Request-Id header is primary (present even on non-JSON edge errors).
1118
- requestId: requestIdFrom(response, env.error?.request_id ?? env.request_id),
1921
+ requestId: requestIdFrom(
1922
+ response,
1923
+ env.error?.request_id ?? env.request_id
1924
+ ),
1119
1925
  details: env.error?.details,
1120
1926
  remediation: env.error?.remediation
1121
1927
  });
@@ -1151,17 +1957,59 @@ var Wefunder = class _Wefunder {
1151
1957
  me: () => this.#unwrapData(getCurrentUser({ client: this.#client }))
1152
1958
  };
1153
1959
  offerings = {
1154
- list: this.#page(listOfferings),
1960
+ list: this.#page(
1961
+ listOfferings
1962
+ ),
1155
1963
  all: (query) => paginate((cursor) => this.offerings.list({ ...query, cursor })),
1156
1964
  collect: (query) => collect((cursor) => this.offerings.list({ ...query, cursor })),
1157
1965
  get: (externalId) => this.#unwrapData(
1158
- getOffering({ client: this.#client, path: { external_id: externalId } })
1966
+ getOffering({
1967
+ client: this.#client,
1968
+ path: { external_id: externalId }
1969
+ })
1159
1970
  )
1160
1971
  };
1972
+ /**
1973
+ * Investments (`read:investments`). `list` is a bootstrap listing; pass `updated_since`
1974
+ * or a saved `cursor` for sync mode (`meta.mode === "delta"`). Persist `meta.next_cursor`
1975
+ * from your last page — it is always present — and resume from it next time.
1976
+ */
1161
1977
  investments = {
1162
- list: this.#page(listInvestments),
1163
- all: () => paginate((cursor) => this.investments.list({ cursor })),
1164
- collect: () => collect((cursor) => this.investments.list({ cursor }))
1978
+ list: this.#page(
1979
+ listInvestments
1980
+ ),
1981
+ all: (query) => paginate(
1982
+ (cursor) => this.investments.list({
1983
+ ...query,
1984
+ cursor
1985
+ })
1986
+ ),
1987
+ collect: (query) => collect(
1988
+ (cursor) => this.investments.list({
1989
+ ...query,
1990
+ cursor
1991
+ })
1992
+ ),
1993
+ /** The current record (not the published projection) for one investment (`inv_…`). */
1994
+ get: (id) => this.#unwrapData(
1995
+ getInvestment({ client: this.#client, path: { id } })
1996
+ )
1997
+ };
1998
+ portfolio = {
1999
+ get: (query) => this.#unwrapData(
2000
+ getPortfolio({ client: this.#client, query })
2001
+ ),
2002
+ positions: {
2003
+ list: this.#page(
2004
+ listPortfolioPositions
2005
+ ),
2006
+ all: (query) => paginate(
2007
+ (cursor) => this.portfolio.positions.list({ ...query, cursor })
2008
+ ),
2009
+ collect: (query) => collect(
2010
+ (cursor) => this.portfolio.positions.list({ ...query, cursor })
2011
+ )
2012
+ }
1165
2013
  };
1166
2014
  campaigns = {
1167
2015
  list: this.#page(listCampaigns),
@@ -1169,29 +2017,116 @@ var Wefunder = class _Wefunder {
1169
2017
  collect: () => collect((cursor) => this.campaigns.list({ cursor }))
1170
2018
  };
1171
2019
  syndicates = {
1172
- list: this.#page(listSyndicates),
1173
- all: () => paginate((cursor) => this.syndicates.list({ cursor })),
1174
- get: (id) => this.#unwrapData(getSyndicate({ client: this.#client, path: { id } }))
2020
+ list: this.#page(
2021
+ listSyndicates
2022
+ ),
2023
+ all: (query) => paginate((cursor) => this.syndicates.list({ ...query, cursor })),
2024
+ get: (id) => this.#unwrapData(
2025
+ getSyndicate({ client: this.#client, path: { id } })
2026
+ )
1175
2027
  };
1176
2028
  intents = {
1177
2029
  list: this.#page(listIntents),
1178
- all: () => paginate((cursor) => this.intents.list({ cursor })),
1179
- get: (id) => this.#unwrapData(getIntent({ client: this.#client, path: { id } }))
2030
+ all: (query) => paginate((cursor) => this.intents.list({ ...query, cursor })),
2031
+ get: (id) => this.#unwrapData(
2032
+ getIntent({ client: this.#client, path: { id } })
2033
+ )
1180
2034
  };
1181
2035
  attribution = {
1182
- me: () => this.#unwrapData(getAttributionMe({ client: this.#client }))
2036
+ me: () => this.#unwrapData(
2037
+ getAttributionMe({ client: this.#client })
2038
+ )
2039
+ };
2040
+ /**
2041
+ * Webhook endpoints (`/webhook_endpoints`, scopes `read:webhooks` / `write:webhooks`).
2042
+ * Endpoints belong to your application and are managed through the LIVE API —
2043
+ * create sandbox receivers there with `mode: "test"`; they're mirrored into
2044
+ * sandbox. The signing `secret` is returned ONLY by `create` and `rotateSecret`.
2045
+ * Verify deliveries with `constructEvent` (see the webhooks module).
2046
+ */
2047
+ webhookEndpoints = {
2048
+ /** All of your app's endpoints (secret omitted). `meta.quota` is the per-app limit. */
2049
+ list: () => this.#unwrap(
2050
+ listWebhookEndpoints({ client: this.#client })
2051
+ ),
2052
+ get: (id) => this.#unwrapData(
2053
+ getWebhookEndpoint({
2054
+ client: this.#client,
2055
+ path: { external_id: id }
2056
+ })
2057
+ ),
2058
+ /** Store `attributes.secret` from the result — it is never shown again. */
2059
+ create: (input) => this.#unwrapData(
2060
+ createWebhookEndpoint({ client: this.#client, body: input })
2061
+ ),
2062
+ /** `events` replaces the subscription list wholesale (no merge); omit to leave unchanged. */
2063
+ update: (id, input) => this.#unwrapData(
2064
+ updateWebhookEndpoint({
2065
+ client: this.#client,
2066
+ path: { external_id: id },
2067
+ body: input
2068
+ })
2069
+ ),
2070
+ /** Stops deliveries immediately. Removal is permanent — create a new endpoint to resume. */
2071
+ remove: (id) => this.#unwrapData(
2072
+ deleteWebhookEndpoint({
2073
+ client: this.#client,
2074
+ path: { external_id: id }
2075
+ })
2076
+ ),
2077
+ /**
2078
+ * New secret (shown once). The old one keeps signing for a 24h overlap — deliveries
2079
+ * carry a `v1` for both, and `constructEvent` accepts either.
2080
+ */
2081
+ rotateSecret: (id) => this.#unwrapData(
2082
+ rotateWebhookEndpointSecret({
2083
+ client: this.#client,
2084
+ path: { external_id: id }
2085
+ })
2086
+ ),
2087
+ /** Recover an auto-disabled endpoint after fixing your server. Idempotent. */
2088
+ reenable: (id) => this.#unwrapData(
2089
+ reenableWebhookEndpoint({
2090
+ client: this.#client,
2091
+ path: { external_id: id }
2092
+ })
2093
+ ),
2094
+ /**
2095
+ * POST a real, signed example event at the endpoint (production envelope + signature)
2096
+ * and report the outcome inline. Defaults to the endpoint's first subscribed event.
2097
+ * Doesn't affect delivery health. Rate-limited to 10/min per endpoint.
2098
+ */
2099
+ test: (id, event) => this.#unwrapData(
2100
+ testWebhookEndpoint({
2101
+ client: this.#client,
2102
+ path: { external_id: id },
2103
+ body: event ? { event } : void 0
2104
+ })
2105
+ )
1183
2106
  };
1184
2107
  };
1185
2108
 
1186
2109
  // src/webhooks.ts
1187
2110
  var import_node_crypto2 = require("crypto");
1188
- var SIGNATURE_HEADER = "x-wefunder-signature";
1189
- var TIMESTAMP_HEADER = "x-wefunder-timestamp";
1190
- var EVENT_HEADER = "x-wefunder-event";
1191
- var DELIVERY_ID_HEADER = "x-wefunder-delivery-id";
1192
- function computeSignature(secret, timestamp, payload) {
1193
- const mac = (0, import_node_crypto2.createHmac)("sha256", secret).update(`${timestamp}.${payload}`).digest("hex");
1194
- return `sha256=${mac}`;
2111
+ var SIGNATURE_HEADER = "wefunder-signature";
2112
+ var DEFAULT_TOLERANCE_SECONDS = 300;
2113
+ var LEGACY_SIGNATURE_HEADER = "x-wefunder-signature";
2114
+ var LEGACY_TIMESTAMP_HEADER = "x-wefunder-timestamp";
2115
+ var LEGACY_EVENT_HEADER = "x-wefunder-event";
2116
+ var LEGACY_DELIVERY_ID_HEADER = "x-wefunder-delivery-id";
2117
+ var WebhookSignatureError = class extends Error {
2118
+ reason;
2119
+ constructor(reason, message) {
2120
+ super(message);
2121
+ this.name = "WebhookSignatureError";
2122
+ this.reason = reason;
2123
+ }
2124
+ };
2125
+ function bodyBuffer(payload) {
2126
+ return typeof payload === "string" ? Buffer.from(payload, "utf8") : Buffer.from(payload);
2127
+ }
2128
+ function computeWebhookSignature(secret, timestamp, payload) {
2129
+ return (0, import_node_crypto2.createHmac)("sha256", secret).update(`${timestamp}.`).update(bodyBuffer(payload)).digest("hex");
1195
2130
  }
1196
2131
  function constantTimeEqual(a, b) {
1197
2132
  const ab = Buffer.from(a);
@@ -1199,42 +2134,142 @@ function constantTimeEqual(a, b) {
1199
2134
  if (ab.length !== bb.length) return false;
1200
2135
  return (0, import_node_crypto2.timingSafeEqual)(ab, bb);
1201
2136
  }
2137
+ function parseSignatureHeader(header) {
2138
+ let timestamp;
2139
+ const signatures = [];
2140
+ for (const part of header.split(",")) {
2141
+ const eq = part.indexOf("=");
2142
+ if (eq < 0) continue;
2143
+ const key = part.slice(0, eq).trim();
2144
+ const value = part.slice(eq + 1).trim();
2145
+ if (key === "t") {
2146
+ if (!/^\d+$/.test(value)) return null;
2147
+ timestamp = Number(value);
2148
+ } else if (key === "v1" && value) {
2149
+ signatures.push(value);
2150
+ }
2151
+ }
2152
+ if (timestamp === void 0 || signatures.length === 0) return null;
2153
+ return { timestamp, signatures };
2154
+ }
2155
+ function signWebhook(opts) {
2156
+ const t = opts.timestamp ?? Math.floor(Date.now() / 1e3);
2157
+ const secrets = [opts.secret, ...opts.additionalSecrets ?? []];
2158
+ const entries = secrets.map((s) => `v1=${computeWebhookSignature(s, t, opts.payload)}`);
2159
+ return [`t=${t}`, ...entries].join(",");
2160
+ }
2161
+ function checkWebhookSignature(opts) {
2162
+ const parsed = parseSignatureHeader(opts.header);
2163
+ if (!parsed) return "malformed_header";
2164
+ const tolerance = opts.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;
2165
+ if (tolerance > 0) {
2166
+ const nowSec = (opts.now ?? Date.now)() / 1e3;
2167
+ if (Math.abs(nowSec - parsed.timestamp) > tolerance) return "timestamp_out_of_tolerance";
2168
+ }
2169
+ const expected = computeWebhookSignature(opts.secret, parsed.timestamp, opts.payload);
2170
+ return parsed.signatures.some((sig) => constantTimeEqual(sig, expected)) ? null : "signature_mismatch";
2171
+ }
1202
2172
  function verifyWebhook(opts) {
1203
- const tolerance = opts.toleranceSeconds ?? 300;
1204
- const now = (opts.now ?? Date.now)();
2173
+ if ("header" in opts) return checkWebhookSignature(opts) === null;
2174
+ return verifyLegacyWebhook(opts);
2175
+ }
2176
+ function verifyLegacyWebhook(opts) {
2177
+ const tolerance = opts.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;
1205
2178
  const ts = Number(opts.timestamp);
1206
2179
  if (!Number.isFinite(ts)) return false;
1207
- if (tolerance > 0 && Math.abs(now / 1e3 - ts) > tolerance) return false;
1208
- const expected = computeSignature(opts.secret, opts.timestamp, opts.payload);
2180
+ if (tolerance > 0 && Math.abs((opts.now ?? Date.now)() / 1e3 - ts) > tolerance) return false;
2181
+ const expected = `sha256=${computeWebhookSignature(opts.secret, opts.timestamp, opts.payload)}`;
1209
2182
  return constantTimeEqual(opts.signature, expected);
1210
2183
  }
1211
- function constructEvent(payload, headers, secret, opts) {
1212
- const get = (name) => {
1213
- if (headers instanceof Headers) return headers.get(name) ?? void 0;
1214
- const v = headers[name] ?? headers[name.toLowerCase()];
2184
+ function headerGetter(headers) {
2185
+ if (typeof headers === "string") {
2186
+ return (name) => name === SIGNATURE_HEADER ? headers : void 0;
2187
+ }
2188
+ if (headers instanceof Headers) return (name) => headers.get(name) ?? void 0;
2189
+ return (name) => {
2190
+ let v = headers[name];
2191
+ if (v === void 0) {
2192
+ const hit = Object.keys(headers).find((k) => k.toLowerCase() === name);
2193
+ if (hit) v = headers[hit];
2194
+ }
1215
2195
  return Array.isArray(v) ? v[0] : v;
1216
2196
  };
1217
- const signature = get(SIGNATURE_HEADER);
1218
- const timestamp = get(TIMESTAMP_HEADER);
1219
- if (!signature || !timestamp) {
1220
- throw new Error("Missing X-Wefunder-Signature or X-Wefunder-Timestamp header");
1221
- }
1222
- const ok = verifyWebhook({
1223
- payload,
1224
- signature,
1225
- timestamp,
1226
- secret,
1227
- toleranceSeconds: opts?.toleranceSeconds,
1228
- now: opts?.now
1229
- });
1230
- if (!ok) throw new Error("Webhook signature verification failed");
2197
+ }
2198
+ function constructEvent(payload, headers, secret, opts) {
2199
+ const get = headerGetter(headers);
2200
+ const header = get(SIGNATURE_HEADER);
2201
+ if (!header) {
2202
+ const legacySig = get(LEGACY_SIGNATURE_HEADER);
2203
+ const legacyTs = get(LEGACY_TIMESTAMP_HEADER);
2204
+ if (legacySig && legacyTs) return constructLegacyEvent(payload, get, legacySig, legacyTs, secret, opts);
2205
+ throw new WebhookSignatureError("missing_header", describeFailure("missing_header"));
2206
+ }
2207
+ const failure = checkWebhookSignature({ payload, header, secret, ...opts });
2208
+ if (failure) throw new WebhookSignatureError(failure, describeFailure(failure));
2209
+ const parsed = parseSignatureHeader(header);
2210
+ const env = parseEnvelope(payload);
1231
2211
  return {
1232
- event: get(EVENT_HEADER) ?? "",
1233
- deliveryId: get(DELIVERY_ID_HEADER) ?? "",
1234
- timestamp: Number(timestamp),
1235
- data: JSON.parse(payload)
2212
+ id: String(env.id ?? ""),
2213
+ event: String(env.event ?? ""),
2214
+ created_at: String(env.created_at ?? ""),
2215
+ mode: env.mode === "test" ? "test" : "live",
2216
+ data: env.data,
2217
+ timestamp: parsed.timestamp
1236
2218
  };
1237
2219
  }
2220
+ function constructLegacyEvent(payload, get, signature, timestamp, secret, opts) {
2221
+ if (!verifyLegacyWebhook({ payload, signature, timestamp, secret, ...opts })) {
2222
+ throw new WebhookSignatureError("signature_mismatch", describeFailure("signature_mismatch"));
2223
+ }
2224
+ const env = parseEnvelope(payload);
2225
+ return {
2226
+ id: String(env.id ?? get(LEGACY_DELIVERY_ID_HEADER) ?? ""),
2227
+ event: String(env.event ?? get(LEGACY_EVENT_HEADER) ?? ""),
2228
+ created_at: String(env.created_at ?? ""),
2229
+ mode: env.mode === "test" ? "test" : "live",
2230
+ data: env.data ?? env,
2231
+ timestamp: Number(timestamp)
2232
+ };
2233
+ }
2234
+ function parseEnvelope(payload) {
2235
+ try {
2236
+ const parsed = JSON.parse(bodyBuffer(payload).toString("utf8"));
2237
+ if (parsed === null || typeof parsed !== "object") throw new Error("not an object");
2238
+ return parsed;
2239
+ } catch {
2240
+ throw new WebhookSignatureError("invalid_payload", describeFailure("invalid_payload"));
2241
+ }
2242
+ }
2243
+ function describeFailure(reason) {
2244
+ switch (reason) {
2245
+ case "missing_header":
2246
+ return "Missing Wefunder-Signature header";
2247
+ case "malformed_header":
2248
+ return "Wefunder-Signature header is malformed (expected t=<unix>,v1=<hex>)";
2249
+ case "timestamp_out_of_tolerance":
2250
+ return "Webhook timestamp is outside the replay tolerance";
2251
+ case "signature_mismatch":
2252
+ return "Webhook signature verification failed";
2253
+ case "invalid_payload":
2254
+ return "Webhook body is not a JSON object";
2255
+ }
2256
+ }
2257
+ async function constructEventFromRequest(request, secret, opts) {
2258
+ const payload = await request.text();
2259
+ return constructEvent(payload, request.headers, secret, opts);
2260
+ }
2261
+ async function dispatchWebhook(event, handlers) {
2262
+ const specific = event.event === "default" ? void 0 : handlers[event.event];
2263
+ if (specific) {
2264
+ await specific(event);
2265
+ return true;
2266
+ }
2267
+ if (handlers.default) {
2268
+ await handlers.default(event);
2269
+ return true;
2270
+ }
2271
+ return false;
2272
+ }
1238
2273
  // Annotate the CommonJS export names for ESM import in node:
1239
2274
  0 && (module.exports = {
1240
2275
  DEFAULT_API_BASE_URL,
@@ -1242,23 +2277,35 @@ function constructEvent(payload, headers, secret, opts) {
1242
2277
  DEFAULT_AUTHORIZE_BASE_URL,
1243
2278
  DEFAULT_OAUTH_BASE_URL,
1244
2279
  DEFAULT_TOKEN_BASE_URL,
1245
- DELIVERY_ID_HEADER,
1246
- EVENT_HEADER,
2280
+ DEFAULT_TOLERANCE_SECONDS,
2281
+ LEGACY_DELIVERY_ID_HEADER,
2282
+ LEGACY_EVENT_HEADER,
2283
+ LEGACY_SIGNATURE_HEADER,
2284
+ LEGACY_TIMESTAMP_HEADER,
1247
2285
  REQUEST_ID_HEADER,
2286
+ SANDBOX_AUTHORIZE_BASE_URL,
1248
2287
  SIGNATURE_HEADER,
1249
- TIMESTAMP_HEADER,
2288
+ TokenManager,
2289
+ WebhookSignatureError,
1250
2290
  Wefunder,
1251
2291
  WefunderAuthError,
1252
2292
  WefunderError,
2293
+ WefunderTokenPersistenceError,
2294
+ checkWebhookSignature,
1253
2295
  clientCredentialsGrant,
1254
2296
  collect,
2297
+ computeWebhookSignature,
1255
2298
  constructEvent,
2299
+ constructEventFromRequest,
1256
2300
  createAuthorizationUrl,
2301
+ dispatchWebhook,
1257
2302
  exchangeCode,
1258
2303
  generatePkce,
1259
2304
  modeForToken,
1260
2305
  paginate,
2306
+ parseSignatureHeader,
1261
2307
  refreshToken,
2308
+ signWebhook,
1262
2309
  verifyWebhook
1263
2310
  });
1264
2311
  //# sourceMappingURL=index.cjs.map