@urupema/forja-sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # @urupema/forja-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ SDK TypeScript da API do Forja do Instituto Urupema, gerado das specs OpenAPI.
4
+
5
+ ```bash
6
+ npm install @urupema/forja-sdk
7
+ ```
8
+
9
+ ```ts
10
+ import { ForjaClient } from '@urupema/forja-sdk';
11
+ ```
12
+
13
+ A CLI [`@urupema/forja`](https://www.npmjs.com/package/@urupema/forja) usa este SDK e cuida do login.
@@ -0,0 +1,441 @@
1
+ type AuthToken = string | undefined;
2
+ interface Auth {
3
+ /**
4
+ * Which part of the request do we use to send the auth?
5
+ *
6
+ * @default 'header'
7
+ */
8
+ in?: 'header' | 'query' | 'cookie';
9
+ /**
10
+ * A unique identifier for the security scheme.
11
+ *
12
+ * Defined only when there are multiple security schemes whose `Auth`
13
+ * shape would otherwise be identical.
14
+ */
15
+ key?: string;
16
+ /**
17
+ * Header or query parameter name.
18
+ *
19
+ * @default 'Authorization'
20
+ */
21
+ name?: string;
22
+ scheme?: 'basic' | 'bearer';
23
+ type: 'apiKey' | 'http';
24
+ }
25
+ interface SerializerOptions<T> {
26
+ /**
27
+ * @default true
28
+ */
29
+ explode: boolean;
30
+ style: T;
31
+ }
32
+ type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
33
+ type ObjectStyle = 'form' | 'deepObject';
34
+ type QuerySerializer = (query: Record<string, unknown>) => string;
35
+ type BodySerializer = (body: unknown) => unknown;
36
+ type QuerySerializerOptionsObject = {
37
+ allowReserved?: boolean;
38
+ array?: Partial<SerializerOptions<ArrayStyle>>;
39
+ object?: Partial<SerializerOptions<ObjectStyle>>;
40
+ };
41
+ type QuerySerializerOptions = QuerySerializerOptionsObject & {
42
+ /**
43
+ * Per-parameter serialization overrides. When provided, these settings
44
+ * override the global array/object settings for specific parameter names.
45
+ */
46
+ parameters?: Record<string, QuerySerializerOptionsObject>;
47
+ };
48
+ type HttpMethod = 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put' | 'trace';
49
+ type Client$1<RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never> = {
50
+ /**
51
+ * Returns the final request URL.
52
+ */
53
+ buildUrl: BuildUrlFn;
54
+ getConfig: () => Config;
55
+ request: RequestFn;
56
+ setConfig: (config: Config) => Config;
57
+ } & { [K in HttpMethod]: MethodFn; } & ([SseFn] extends [never] ? {
58
+ sse?: never;
59
+ } : {
60
+ sse: { [K in HttpMethod]: SseFn; };
61
+ });
62
+ interface Config$1 {
63
+ /**
64
+ * Auth token or a function returning auth token. The resolved value will be
65
+ * added to the request payload as defined by its `security` array.
66
+ */
67
+ auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
68
+ /**
69
+ * A function for serializing request body parameter. By default,
70
+ * {@link JSON.stringify()} will be used.
71
+ */
72
+ bodySerializer?: BodySerializer | null;
73
+ /**
74
+ * An object containing any HTTP headers that you want to pre-populate your
75
+ * `Headers` object with.
76
+ *
77
+ * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
78
+ */
79
+ headers?: RequestInit['headers'] | Record<string, string | number | boolean | (string | number | boolean)[] | null | undefined | unknown>;
80
+ /**
81
+ * The request method.
82
+ *
83
+ * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
84
+ */
85
+ method?: Uppercase<HttpMethod>;
86
+ /**
87
+ * A function for serializing request query parameters. By default, arrays
88
+ * will be exploded in form style, objects will be exploded in deepObject
89
+ * style, and reserved characters are percent-encoded.
90
+ *
91
+ * This method will have no effect if the native `paramsSerializer()` Axios
92
+ * API function is used.
93
+ *
94
+ * {@link https://swagger.io/docs/specification/serialization/#query View examples}
95
+ */
96
+ querySerializer?: QuerySerializer | QuerySerializerOptions;
97
+ /**
98
+ * A function validating request data. This is useful if you want to ensure
99
+ * the request conforms to the desired shape, so it can be safely sent to
100
+ * the server.
101
+ */
102
+ requestValidator?: (data: unknown) => Promise<unknown>;
103
+ /**
104
+ * A function transforming response data before it's returned. This is useful
105
+ * for post-processing data, e.g., converting ISO strings into Date objects.
106
+ */
107
+ responseTransformer?: (data: unknown) => Promise<unknown>;
108
+ /**
109
+ * A function validating response data. This is useful if you want to ensure
110
+ * the response conforms to the desired shape, so it can be safely passed to
111
+ * the transformers and returned to the user.
112
+ */
113
+ responseValidator?: (data: unknown) => Promise<unknown>;
114
+ }
115
+ /**
116
+ * Arbitrary metadata passed through the `meta` request option.
117
+ */
118
+ interface ClientMeta {}
119
+ type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, 'method'> & Pick<Config$1, 'method' | 'responseTransformer' | 'responseValidator'> & {
120
+ /**
121
+ * Fetch API implementation. You can use this option to provide a custom
122
+ * fetch instance.
123
+ *
124
+ * @default globalThis.fetch
125
+ */
126
+ fetch?: typeof fetch;
127
+ /**
128
+ * Implementing clients can call request interceptors inside this hook.
129
+ */
130
+ onRequest?: (url: string, init: RequestInit) => Promise<Request>;
131
+ /**
132
+ * Callback invoked when a network or parsing error occurs during streaming.
133
+ *
134
+ * This option applies only if the endpoint returns a stream of events.
135
+ *
136
+ * @param error The error that occurred.
137
+ */
138
+ onSseError?: (error: unknown) => void;
139
+ /**
140
+ * Callback invoked when an event is streamed from the server.
141
+ *
142
+ * This option applies only if the endpoint returns a stream of events.
143
+ *
144
+ * @param event Event streamed from the server.
145
+ * @returns Nothing (void).
146
+ */
147
+ onSseEvent?: (event: StreamEvent<TData>) => void;
148
+ serializedBody?: RequestInit['body'];
149
+ /**
150
+ * Default retry delay in milliseconds.
151
+ *
152
+ * This option applies only if the endpoint returns a stream of events.
153
+ *
154
+ * @default 3000
155
+ */
156
+ sseDefaultRetryDelay?: number;
157
+ /**
158
+ * Maximum number of retry attempts before giving up.
159
+ */
160
+ sseMaxRetryAttempts?: number;
161
+ /**
162
+ * Maximum retry delay in milliseconds.
163
+ *
164
+ * Applies only when exponential backoff is used.
165
+ *
166
+ * This option applies only if the endpoint returns a stream of events.
167
+ *
168
+ * @default 30000
169
+ */
170
+ sseMaxRetryDelay?: number;
171
+ /**
172
+ * Optional sleep function for retry backoff.
173
+ *
174
+ * Defaults to using `setTimeout`.
175
+ */
176
+ sseSleepFn?: (ms: number) => Promise<void>;
177
+ url: string;
178
+ };
179
+ interface StreamEvent<TData = unknown> {
180
+ data: TData;
181
+ event?: string;
182
+ id?: string;
183
+ retry?: number;
184
+ }
185
+ type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {
186
+ stream: AsyncGenerator<TData extends Record<string, unknown> ? TData[keyof TData] : TData, TReturn, TNext>;
187
+ };
188
+ type ErrInterceptor<Err, Res, Req, Options> = (error: Err,
189
+ /** response may be undefined due to a network error where no response object is produced */
190
+ response: Res | undefined,
191
+ /** request may be undefined, because error may be from building the request object itself */
192
+ request: Req | undefined, options: Options) => Err | Promise<Err>;
193
+ type ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;
194
+ type ResInterceptor<Res, Req, Options> = (response: Res, request: Req, options: Options) => Res | Promise<Res>;
195
+ declare class Interceptors<Interceptor> {
196
+ fns: Array<Interceptor | null>;
197
+ clear(): void;
198
+ eject(id: number | Interceptor): void;
199
+ exists(id: number | Interceptor): boolean;
200
+ getInterceptorIndex(id: number | Interceptor): number;
201
+ update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false;
202
+ use(fn: Interceptor): number;
203
+ }
204
+ interface Middleware<Req, Res, Err, Options> {
205
+ error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;
206
+ request: Interceptors<ReqInterceptor<Req, Options>>;
207
+ response: Interceptors<ResInterceptor<Res, Req, Options>>;
208
+ }
209
+ export declare const createConfig: <T extends ClientOptions$1 = ClientOptions$1>(override?: Config<Omit<ClientOptions$1, keyof T> & T>) => Config<Omit<ClientOptions$1, keyof T> & T>;
210
+ type ResponseStyle = 'data' | 'fields';
211
+ interface Config<T extends ClientOptions$1 = ClientOptions$1> extends Omit<RequestInit, 'body' | 'headers' | 'method'>, Config$1 {
212
+ /**
213
+ * Base URL for all requests made by this client.
214
+ */
215
+ baseUrl?: T['baseUrl'];
216
+ /**
217
+ * Fetch API implementation. You can use this option to provide a custom
218
+ * fetch instance.
219
+ *
220
+ * @default globalThis.fetch
221
+ */
222
+ fetch?: typeof fetch;
223
+ /**
224
+ * Please don't use the Fetch client for Next.js applications. The `next`
225
+ * options won't have any effect.
226
+ *
227
+ * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
228
+ */
229
+ next?: never;
230
+ /**
231
+ * Return the response data parsed in a specified format. By default, `auto`
232
+ * will infer the appropriate method from the `Content-Type` response header.
233
+ * You can override this behavior with any of the {@link Body} methods.
234
+ * Select `stream` if you don't want to parse response data at all.
235
+ *
236
+ * @default 'auto'
237
+ */
238
+ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text';
239
+ /**
240
+ * Should we return only data or multiple fields (data, error, response, etc.)?
241
+ *
242
+ * @default 'fields'
243
+ */
244
+ responseStyle?: ResponseStyle;
245
+ /**
246
+ * Throw an error instead of returning it in the response?
247
+ *
248
+ * @default false
249
+ */
250
+ throwOnError?: T['throwOnError'];
251
+ }
252
+ interface RequestOptions<TData = unknown, TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string> extends Config<{
253
+ responseStyle: TResponseStyle;
254
+ throwOnError: ThrowOnError;
255
+ }>, Pick<ServerSentEventsOptions<TData>, 'onRequest' | 'onSseError' | 'onSseEvent' | 'sseDefaultRetryDelay' | 'sseMaxRetryAttempts' | 'sseMaxRetryDelay'> {
256
+ /**
257
+ * Any body that you want to add to your request.
258
+ *
259
+ * {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
260
+ */
261
+ body?: unknown;
262
+ path?: Record<string, unknown>;
263
+ query?: Record<string, unknown>;
264
+ /**
265
+ * Security mechanism(s) to use for the request.
266
+ */
267
+ security?: ReadonlyArray<Auth>;
268
+ url: Url;
269
+ }
270
+ interface ResolvedRequestOptions<TResponseStyle extends ResponseStyle = 'fields', ThrowOnError extends boolean = boolean, Url extends string = string> extends RequestOptions<unknown, TResponseStyle, ThrowOnError, Url> {
271
+ headers: Headers;
272
+ serializedBody?: string;
273
+ }
274
+ type RequestResult<TData = unknown, TError = unknown, ThrowOnError extends boolean = boolean, TResponseStyle extends ResponseStyle = 'fields'> = ThrowOnError extends true ? Promise<TResponseStyle extends 'data' ? TData extends Record<string, unknown> ? TData[keyof TData] : TData : {
275
+ data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
276
+ request: Request;
277
+ response: Response;
278
+ }> : Promise<TResponseStyle extends 'data' ? (TData extends Record<string, unknown> ? TData[keyof TData] : TData) | undefined : ({
279
+ data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
280
+ error: undefined;
281
+ } | {
282
+ data: undefined;
283
+ error: TError extends Record<string, unknown> ? TError[keyof TError] : TError;
284
+ }) & {
285
+ /** request may be undefined, because error may be from building the request object itself */
286
+ request?: Request;
287
+ /** response may be undefined, because error may be from building the request object itself or from a network error */
288
+ response?: Response;
289
+ }>;
290
+ interface ClientOptions$1 {
291
+ baseUrl?: string;
292
+ responseStyle?: ResponseStyle;
293
+ throwOnError?: boolean;
294
+ }
295
+ type MethodFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields'>(options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'>) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
296
+ type SseFn = <TData = unknown, _TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields'>(options: Omit<RequestOptions<never, TResponseStyle, ThrowOnError>, 'method'>) => Promise<ServerSentEventsResult<TData>>;
297
+ type RequestFn = <TData = unknown, TError = unknown, ThrowOnError extends boolean = false, TResponseStyle extends ResponseStyle = 'fields'>(options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'> & Pick<Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>, 'method'>) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
298
+ type BuildUrlFn = <TData extends {
299
+ body?: unknown;
300
+ path?: Record<string, unknown>;
301
+ query?: Record<string, unknown>;
302
+ url: string;
303
+ }>(options: TData & Options$1<TData>) => string;
304
+ type Client = Client$1<RequestFn, Config, MethodFn, BuildUrlFn, SseFn> & {
305
+ interceptors: Middleware<Request, Response, unknown, ResolvedRequestOptions>;
306
+ };
307
+ interface TDataShape {
308
+ body?: unknown;
309
+ headers?: unknown;
310
+ path?: unknown;
311
+ query?: unknown;
312
+ url: string;
313
+ }
314
+ type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
315
+ type Options$1<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown, TResponseStyle extends ResponseStyle = 'fields'> = OmitKeys<RequestOptions<TResponse, TResponseStyle, ThrowOnError>, 'body' | 'path' | 'query' | 'url'> & ([TData] extends [never] ? unknown : Omit<TData, 'url'>);
316
+ export declare const createClient: (config?: Config) => Client;
317
+ type ClientOptions = {
318
+ baseUrl: 'https://forja.institutourupema.com.br' | (string & {});
319
+ };
320
+ type Me = {
321
+ identity: Identity;
322
+ /**
323
+ * Grupos de que a pessoa participa no Forja.
324
+ */
325
+ groups: Array<GroupMembership>;
326
+ };
327
+ /**
328
+ * A pessoa como o IdP Urupema a conhece: o par (issuer, subject) é a
329
+ * chave dela em todo o Forja.
330
+ *
331
+ */
332
+ type Identity = {
333
+ issuer: string;
334
+ subject: string;
335
+ };
336
+ type GroupMembership = {
337
+ group: GroupId;
338
+ role: Role;
339
+ };
340
+ /**
341
+ * Identificador estável do grupo.
342
+ */
343
+ type GroupId = string;
344
+ type Role = 'member' | 'admin';
345
+ /**
346
+ * Erro no formato RFC 9457.
347
+ */
348
+ type Problem = {
349
+ type: string;
350
+ title: string;
351
+ status: number;
352
+ code: 'unauthenticated' | 'insufficient_scope' | 'not_found' | 'forbidden' | 'internal';
353
+ detail?: string;
354
+ /**
355
+ * O `X-Request-Id` da requisição.
356
+ */
357
+ instance?: string;
358
+ };
359
+ type GetMeData = {
360
+ body?: never;
361
+ path?: never;
362
+ query?: never;
363
+ url: '/api/v1/me';
364
+ };
365
+ type GetMeErrors = {
366
+ /**
367
+ * Token ausente, inválido ou vencido
368
+ * (`https://forja.institutourupema.com.br/problems/unauthenticated`).
369
+ *
370
+ */
371
+ 401: Problem;
372
+ /**
373
+ * O token não tem o escopo `forja`
374
+ * (`https://forja.institutourupema.com.br/problems/insufficient-scope`).
375
+ *
376
+ */
377
+ 403: Problem;
378
+ /**
379
+ * Erro interno (`https://forja.institutourupema.com.br/problems/internal`).
380
+ */
381
+ 500: Problem;
382
+ };
383
+ type GetMeError = GetMeErrors[keyof GetMeErrors];
384
+ type GetMeResponses = {
385
+ /**
386
+ * A pessoa autenticada.
387
+ */
388
+ 200: Me;
389
+ };
390
+ type GetMeResponse = GetMeResponses[keyof GetMeResponses];
391
+ type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options$1<TData, ThrowOnError, TResponse> & {
392
+ /**
393
+ * You can provide a client instance returned by `createClient()` instead of
394
+ * individual options. This might be also useful if you want to implement a
395
+ * custom client.
396
+ */
397
+ client?: Client;
398
+ /**
399
+ * You can pass arbitrary values through the `meta` object. This can be
400
+ * used to access values that aren't defined as part of the SDK function.
401
+ */
402
+ meta?: keyof ClientMeta extends never ? Record<string, unknown> : ClientMeta;
403
+ };
404
+ declare class Identity$1 {
405
+ /**
406
+ * Quem sou eu
407
+ *
408
+ * A identidade da pessoa dona do token e os grupos dela no Forja.
409
+ * Na CLI: `forja get-me`.
410
+ *
411
+ */
412
+ static getMe<ThrowOnError extends boolean = false>(options?: Options<GetMeData, ThrowOnError>): RequestResult<GetMeResponses, GetMeErrors, ThrowOnError>;
413
+ }
414
+ interface ForjaClientOptions {
415
+ /**
416
+ * Base URL of the Forja.
417
+ * @example 'https://forja.institutourupema.com.br'
418
+ */
419
+ baseUrl: string;
420
+ /**
421
+ * The access token, or a function returning one per request (so a caller
422
+ * can refresh it). Sent as `Authorization: Bearer <token>`.
423
+ */
424
+ token?: string | (() => string | Promise<string>);
425
+ /** Extra headers sent on every request. */
426
+ headers?: Record<string, string>;
427
+ }
428
+ /**
429
+ * The Forja API, one property per resource (spec tag):
430
+ *
431
+ * ```ts
432
+ * const forja = new ForjaClient({ baseUrl, token });
433
+ * const { data, error } = await forja.identity.getMe();
434
+ * ```
435
+ */
436
+ export declare class ForjaClient {
437
+ readonly identity: typeof Identity$1;
438
+ readonly client: Client;
439
+ constructor(options: ForjaClientOptions);
440
+ }
441
+ export { type ClientOptions, type ForjaClientOptions, type GetMeData, type GetMeError, type GetMeErrors, type GetMeResponse, type GetMeResponses, type GroupId, type GroupMembership, type Identity, Identity$1 as Identity2, type Me, type Options, type Problem, type Role };
package/dist/index.mjs ADDED
@@ -0,0 +1,655 @@
1
+ // src/generated/core/bodySerializer.gen.ts
2
+ const jsonBodySerializer = { bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value) };
3
+ Object.entries({
4
+ $body_: "body",
5
+ $headers_: "headers",
6
+ $path_: "path",
7
+ $query_: "query"
8
+ });
9
+ // src/generated/core/serverSentEvents.gen.ts
10
+ function createSseClient({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) {
11
+ let lastEventId;
12
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
13
+ const createStream = async function* () {
14
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
15
+ let attempt = 0;
16
+ const signal = options.signal ?? new AbortController().signal;
17
+ while (true) {
18
+ if (signal.aborted) break;
19
+ attempt++;
20
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
21
+ if (lastEventId !== void 0) headers.set("Last-Event-ID", lastEventId);
22
+ try {
23
+ const requestInit = {
24
+ redirect: "follow",
25
+ ...options,
26
+ body: options.serializedBody,
27
+ headers,
28
+ signal
29
+ };
30
+ let request = new Request(url, requestInit);
31
+ if (onRequest) request = await onRequest(url, requestInit);
32
+ const response = await (options.fetch ?? globalThis.fetch)(request);
33
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
34
+ if (!response.body) throw new Error("No body in SSE response");
35
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
36
+ let buffer = "";
37
+ const abortHandler = () => {
38
+ try {
39
+ reader.cancel();
40
+ } catch {}
41
+ };
42
+ signal.addEventListener("abort", abortHandler);
43
+ try {
44
+ while (true) {
45
+ const { done, value } = await reader.read();
46
+ if (done) break;
47
+ buffer += value;
48
+ buffer = buffer.replace(/\r\n?/g, "\n");
49
+ const chunks = buffer.split("\n\n");
50
+ buffer = chunks.pop() ?? "";
51
+ for (const chunk of chunks) {
52
+ const lines = chunk.split("\n");
53
+ const dataLines = [];
54
+ let eventName;
55
+ for (const line of lines) if (line.startsWith("data:")) dataLines.push(line.replace(/^data:\s*/, ""));
56
+ else if (line.startsWith("event:")) eventName = line.replace(/^event:\s*/, "");
57
+ else if (line.startsWith("id:")) lastEventId = line.replace(/^id:\s*/, "");
58
+ else if (line.startsWith("retry:")) {
59
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
60
+ if (!Number.isNaN(parsed)) retryDelay = parsed;
61
+ }
62
+ let data;
63
+ let parsedJson = false;
64
+ if (dataLines.length) {
65
+ const rawData = dataLines.join("\n");
66
+ try {
67
+ data = JSON.parse(rawData);
68
+ parsedJson = true;
69
+ } catch {
70
+ data = rawData;
71
+ }
72
+ }
73
+ if (parsedJson) {
74
+ if (responseValidator) await responseValidator(data);
75
+ if (responseTransformer) data = await responseTransformer(data);
76
+ }
77
+ onSseEvent?.({
78
+ data,
79
+ event: eventName,
80
+ id: lastEventId,
81
+ retry: retryDelay
82
+ });
83
+ if (dataLines.length) yield data;
84
+ }
85
+ }
86
+ } finally {
87
+ signal.removeEventListener("abort", abortHandler);
88
+ reader.releaseLock();
89
+ }
90
+ break;
91
+ } catch (error) {
92
+ onSseError?.(error);
93
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) break;
94
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
95
+ await sleep(backoff);
96
+ }
97
+ }
98
+ };
99
+ return { stream: createStream() };
100
+ }
101
+ // src/generated/core/pathSerializer.gen.ts
102
+ const separatorArrayExplode = (style) => {
103
+ switch (style) {
104
+ case "label": return ".";
105
+ case "matrix": return ";";
106
+ case "simple": return ",";
107
+ default: return "&";
108
+ }
109
+ };
110
+ const separatorArrayNoExplode = (style) => {
111
+ switch (style) {
112
+ case "form": return ",";
113
+ case "pipeDelimited": return "|";
114
+ case "spaceDelimited": return "%20";
115
+ default: return ",";
116
+ }
117
+ };
118
+ const separatorObjectExplode = (style) => {
119
+ switch (style) {
120
+ case "label": return ".";
121
+ case "matrix": return ";";
122
+ case "simple": return ",";
123
+ default: return "&";
124
+ }
125
+ };
126
+ const serializeArrayParam = ({ allowReserved, explode, name, style, value }) => {
127
+ if (!explode) {
128
+ const joinedValues = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
129
+ switch (style) {
130
+ case "label": return `.${joinedValues}`;
131
+ case "matrix": return `;${name}=${joinedValues}`;
132
+ case "simple": return joinedValues;
133
+ default: return `${name}=${joinedValues}`;
134
+ }
135
+ }
136
+ const separator = separatorArrayExplode(style);
137
+ const joinedValues = value.map((v) => {
138
+ if (style === "label" || style === "simple") return allowReserved ? v : encodeURIComponent(v);
139
+ return serializePrimitiveParam({
140
+ allowReserved,
141
+ name,
142
+ value: v
143
+ });
144
+ }).join(separator);
145
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
146
+ };
147
+ const serializePrimitiveParam = ({ allowReserved, name, value }) => {
148
+ if (value === void 0 || value === null) return "";
149
+ if (typeof value === "object") throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");
150
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
151
+ };
152
+ const serializeObjectParam = ({ allowReserved, explode, name, style, value, valueOnly }) => {
153
+ if (value instanceof Date) return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
154
+ if (style !== "deepObject" && !explode) {
155
+ let values = [];
156
+ Object.entries(value).forEach(([key, v]) => {
157
+ values = [
158
+ ...values,
159
+ key,
160
+ allowReserved ? v : encodeURIComponent(v)
161
+ ];
162
+ });
163
+ const joinedValues = values.join(",");
164
+ switch (style) {
165
+ case "form": return `${name}=${joinedValues}`;
166
+ case "label": return `.${joinedValues}`;
167
+ case "matrix": return `;${name}=${joinedValues}`;
168
+ default: return joinedValues;
169
+ }
170
+ }
171
+ const separator = separatorObjectExplode(style);
172
+ const joinedValues = Object.entries(value).map(([key, v]) => serializePrimitiveParam({
173
+ allowReserved,
174
+ name: style === "deepObject" ? `${name}[${key}]` : key,
175
+ value: v
176
+ })).join(separator);
177
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
178
+ };
179
+ // src/generated/core/utils.gen.ts
180
+ const PATH_PARAM_RE = /\{[^{}]+\}/g;
181
+ const defaultPathSerializer = ({ path, url: _url }) => {
182
+ let url = _url;
183
+ const matches = _url.match(PATH_PARAM_RE);
184
+ if (matches) for (const match of matches) {
185
+ let explode = false;
186
+ let name = match.substring(1, match.length - 1);
187
+ let style = "simple";
188
+ if (name.endsWith("*")) {
189
+ explode = true;
190
+ name = name.substring(0, name.length - 1);
191
+ }
192
+ if (name.startsWith(".")) {
193
+ name = name.substring(1);
194
+ style = "label";
195
+ } else if (name.startsWith(";")) {
196
+ name = name.substring(1);
197
+ style = "matrix";
198
+ }
199
+ const value = path[name];
200
+ if (value === void 0 || value === null) continue;
201
+ if (Array.isArray(value)) {
202
+ url = url.replace(match, serializeArrayParam({
203
+ explode,
204
+ name,
205
+ style,
206
+ value
207
+ }));
208
+ continue;
209
+ }
210
+ if (typeof value === "object") {
211
+ url = url.replace(match, serializeObjectParam({
212
+ explode,
213
+ name,
214
+ style,
215
+ value,
216
+ valueOnly: true
217
+ }));
218
+ continue;
219
+ }
220
+ if (style === "matrix") {
221
+ url = url.replace(match, `;${serializePrimitiveParam({
222
+ name,
223
+ value
224
+ })}`);
225
+ continue;
226
+ }
227
+ const replaceValue = encodeURIComponent(style === "label" ? `.${value}` : value);
228
+ url = url.replace(match, replaceValue);
229
+ }
230
+ return url;
231
+ };
232
+ const getUrl = ({ baseUrl, path, query, querySerializer, url: _url }) => {
233
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
234
+ let url = (baseUrl ?? "") + pathUrl;
235
+ if (path) url = defaultPathSerializer({
236
+ path,
237
+ url
238
+ });
239
+ let search = query ? querySerializer(query) : "";
240
+ if (search.startsWith("?")) search = search.substring(1);
241
+ if (search) url += `?${search}`;
242
+ return url;
243
+ };
244
+ function getValidRequestBody(options) {
245
+ const hasBody = options.body !== void 0;
246
+ if (hasBody && options.bodySerializer) {
247
+ if ("serializedBody" in options) return options.serializedBody !== void 0 && options.serializedBody !== "" ? options.serializedBody : null;
248
+ return options.body !== "" ? options.body : null;
249
+ }
250
+ if (hasBody) return options.body;
251
+ }
252
+ // src/generated/core/auth.gen.ts
253
+ const getAuthToken = async (auth, callback) => {
254
+ const token = typeof callback === "function" ? await callback(auth) : callback;
255
+ if (!token) return;
256
+ if (auth.scheme === "bearer") return `Bearer ${token}`;
257
+ if (auth.scheme === "basic") return `Basic ${btoa(token)}`;
258
+ return token;
259
+ };
260
+ // src/generated/client/utils.gen.ts
261
+ const createQuerySerializer = ({ parameters = {}, ...args } = {}) => {
262
+ const querySerializer = (queryParams) => {
263
+ const search = [];
264
+ if (queryParams && typeof queryParams === "object") for (const name in queryParams) {
265
+ const value = queryParams[name];
266
+ if (value === void 0 || value === null) continue;
267
+ const options = parameters[name] || args;
268
+ if (Array.isArray(value)) {
269
+ const serializedArray = serializeArrayParam({
270
+ allowReserved: options.allowReserved,
271
+ explode: true,
272
+ name,
273
+ style: "form",
274
+ value,
275
+ ...options.array
276
+ });
277
+ if (serializedArray) search.push(serializedArray);
278
+ } else if (typeof value === "object") {
279
+ const serializedObject = serializeObjectParam({
280
+ allowReserved: options.allowReserved,
281
+ explode: true,
282
+ name,
283
+ style: "deepObject",
284
+ value,
285
+ ...options.object
286
+ });
287
+ if (serializedObject) search.push(serializedObject);
288
+ } else {
289
+ const serializedPrimitive = serializePrimitiveParam({
290
+ allowReserved: options.allowReserved,
291
+ name,
292
+ value
293
+ });
294
+ if (serializedPrimitive) search.push(serializedPrimitive);
295
+ }
296
+ }
297
+ return search.join("&");
298
+ };
299
+ return querySerializer;
300
+ };
301
+ /**
302
+ * Infers parseAs value from provided Content-Type header.
303
+ */
304
+ const getParseAs = (contentType) => {
305
+ if (!contentType) return "stream";
306
+ const cleanContent = contentType.split(";")[0]?.trim();
307
+ if (!cleanContent) return;
308
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) return "json";
309
+ if (cleanContent === "multipart/form-data") return "formData";
310
+ if ([
311
+ "application/",
312
+ "audio/",
313
+ "image/",
314
+ "video/"
315
+ ].some((type) => cleanContent.startsWith(type))) return "blob";
316
+ if (cleanContent.startsWith("text/")) return "text";
317
+ };
318
+ const checkForExistence = (options, name) => {
319
+ if (!name) return false;
320
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) return true;
321
+ return false;
322
+ };
323
+ async function setAuthParams(options) {
324
+ for (const auth of options.security ?? []) {
325
+ if (checkForExistence(options, auth.name)) continue;
326
+ const token = await getAuthToken(auth, options.auth);
327
+ if (!token) continue;
328
+ const name = auth.name ?? "Authorization";
329
+ switch (auth.in) {
330
+ case "query":
331
+ if (!options.query) options.query = {};
332
+ options.query[name] = token;
333
+ break;
334
+ case "cookie":
335
+ options.headers.append("Cookie", `${name}=${token}`);
336
+ break;
337
+ default: options.headers.set(name, token);
338
+ }
339
+ }
340
+ }
341
+ const buildUrl = (options) => getUrl({
342
+ baseUrl: options.baseUrl,
343
+ path: options.path,
344
+ query: options.query,
345
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
346
+ url: options.url
347
+ });
348
+ const mergeConfigs = (a, b) => {
349
+ const config = {
350
+ ...a,
351
+ ...b
352
+ };
353
+ if (config.baseUrl?.endsWith("/")) config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
354
+ config.headers = mergeHeaders(a.headers, b.headers);
355
+ return config;
356
+ };
357
+ const headersEntries = (headers) => {
358
+ const entries = [];
359
+ headers.forEach((value, key) => {
360
+ entries.push([key, value]);
361
+ });
362
+ return entries;
363
+ };
364
+ const mergeHeaders = (...headers) => {
365
+ const mergedHeaders = new Headers();
366
+ for (const header of headers) {
367
+ if (!header) continue;
368
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
369
+ for (const [key, value] of iterator) if (value === null) mergedHeaders.delete(key);
370
+ else if (Array.isArray(value)) for (const v of value) mergedHeaders.append(key, v);
371
+ else if (value !== void 0) mergedHeaders.set(key, typeof value === "object" ? JSON.stringify(value) : value);
372
+ }
373
+ return mergedHeaders;
374
+ };
375
+ var Interceptors = class {
376
+ fns = [];
377
+ clear() {
378
+ this.fns = [];
379
+ }
380
+ eject(id) {
381
+ const index = this.getInterceptorIndex(id);
382
+ if (this.fns[index]) this.fns[index] = null;
383
+ }
384
+ exists(id) {
385
+ const index = this.getInterceptorIndex(id);
386
+ return Boolean(this.fns[index]);
387
+ }
388
+ getInterceptorIndex(id) {
389
+ if (typeof id === "number") return this.fns[id] ? id : -1;
390
+ return this.fns.indexOf(id);
391
+ }
392
+ update(id, fn) {
393
+ const index = this.getInterceptorIndex(id);
394
+ if (this.fns[index]) {
395
+ this.fns[index] = fn;
396
+ return id;
397
+ }
398
+ return false;
399
+ }
400
+ use(fn) {
401
+ this.fns.push(fn);
402
+ return this.fns.length - 1;
403
+ }
404
+ };
405
+ const createInterceptors = () => ({
406
+ error: new Interceptors(),
407
+ request: new Interceptors(),
408
+ response: new Interceptors()
409
+ });
410
+ const defaultQuerySerializer = createQuerySerializer({
411
+ allowReserved: false,
412
+ array: {
413
+ explode: true,
414
+ style: "form"
415
+ },
416
+ object: {
417
+ explode: true,
418
+ style: "deepObject"
419
+ }
420
+ });
421
+ const defaultHeaders = { "Content-Type": "application/json" };
422
+ const createConfig = (override = {}) => ({
423
+ ...jsonBodySerializer,
424
+ headers: defaultHeaders,
425
+ parseAs: "auto",
426
+ querySerializer: defaultQuerySerializer,
427
+ ...override
428
+ });
429
+ // src/generated/client/client.gen.ts
430
+ const createClient = (config = {}) => {
431
+ let _config = mergeConfigs(createConfig(), config);
432
+ const getConfig = () => ({ ..._config });
433
+ const setConfig = (config) => {
434
+ _config = mergeConfigs(_config, config);
435
+ return getConfig();
436
+ };
437
+ const interceptors = createInterceptors();
438
+ const beforeRequest = async (options) => {
439
+ const opts = {
440
+ ..._config,
441
+ ...options,
442
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
443
+ headers: mergeHeaders(_config.headers, options.headers),
444
+ serializedBody: void 0
445
+ };
446
+ if (opts.security) await setAuthParams(opts);
447
+ if (opts.requestValidator) await opts.requestValidator(opts);
448
+ if (opts.body !== void 0 && opts.bodySerializer) opts.serializedBody = opts.bodySerializer(opts.body);
449
+ if (opts.body === void 0 || opts.serializedBody === "") opts.headers.delete("Content-Type");
450
+ const resolvedOpts = opts;
451
+ return {
452
+ opts: resolvedOpts,
453
+ url: buildUrl(resolvedOpts)
454
+ };
455
+ };
456
+ const request = async (options) => {
457
+ const throwOnError = options.throwOnError ?? _config.throwOnError;
458
+ const responseStyle = options.responseStyle ?? _config.responseStyle;
459
+ let request;
460
+ let response;
461
+ try {
462
+ const { opts, url } = await beforeRequest(options);
463
+ const requestInit = {
464
+ redirect: "follow",
465
+ ...opts,
466
+ body: getValidRequestBody(opts)
467
+ };
468
+ request = new Request(url, requestInit);
469
+ for (const fn of interceptors.request.fns) if (fn) request = await fn(request, opts);
470
+ response = await (0, opts.fetch)(request);
471
+ for (const fn of interceptors.response.fns) if (fn) response = await fn(response, request, opts);
472
+ const result = {
473
+ request,
474
+ response
475
+ };
476
+ if (response.ok) {
477
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
478
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
479
+ let emptyData;
480
+ switch (parseAs) {
481
+ case "arrayBuffer":
482
+ case "blob":
483
+ case "text":
484
+ emptyData = await response[parseAs]();
485
+ break;
486
+ case "formData":
487
+ emptyData = new FormData();
488
+ break;
489
+ case "stream":
490
+ emptyData = response.body;
491
+ break;
492
+ default: emptyData = {};
493
+ }
494
+ return opts.responseStyle === "data" ? emptyData : {
495
+ data: emptyData,
496
+ ...result
497
+ };
498
+ }
499
+ let data;
500
+ switch (parseAs) {
501
+ case "arrayBuffer":
502
+ case "blob":
503
+ case "formData":
504
+ case "text":
505
+ data = await response[parseAs]();
506
+ break;
507
+ case "json": {
508
+ const text = await response.text();
509
+ data = text ? JSON.parse(text) : {};
510
+ break;
511
+ }
512
+ case "stream": return opts.responseStyle === "data" ? response.body : {
513
+ data: response.body,
514
+ ...result
515
+ };
516
+ }
517
+ if (parseAs === "json") {
518
+ if (opts.responseValidator) await opts.responseValidator(data);
519
+ if (opts.responseTransformer) data = await opts.responseTransformer(data);
520
+ }
521
+ return opts.responseStyle === "data" ? data : {
522
+ data,
523
+ ...result
524
+ };
525
+ }
526
+ const textError = await response.text();
527
+ let jsonError;
528
+ try {
529
+ jsonError = JSON.parse(textError);
530
+ } catch {}
531
+ throw jsonError ?? textError;
532
+ } catch (error) {
533
+ let finalError = error;
534
+ for (const fn of interceptors.error.fns) if (fn) finalError = await fn(finalError, response, request, options);
535
+ finalError = finalError || {};
536
+ if (throwOnError) throw finalError;
537
+ return responseStyle === "data" ? void 0 : {
538
+ error: finalError,
539
+ request,
540
+ response
541
+ };
542
+ }
543
+ };
544
+ const makeMethodFn = (method) => (options) => request({
545
+ ...options,
546
+ method
547
+ });
548
+ const makeSseFn = (method) => async (options) => {
549
+ const { opts, url } = await beforeRequest(options);
550
+ return createSseClient({
551
+ ...opts,
552
+ body: opts.body,
553
+ method,
554
+ onRequest: async (url, init) => {
555
+ let request = new Request(url, init);
556
+ for (const fn of interceptors.request.fns) if (fn) request = await fn(request, opts);
557
+ return request;
558
+ },
559
+ serializedBody: getValidRequestBody(opts),
560
+ url
561
+ });
562
+ };
563
+ const _buildUrl = (options) => buildUrl({
564
+ ..._config,
565
+ ...options
566
+ });
567
+ return {
568
+ buildUrl: _buildUrl,
569
+ connect: makeMethodFn("CONNECT"),
570
+ delete: makeMethodFn("DELETE"),
571
+ get: makeMethodFn("GET"),
572
+ getConfig,
573
+ head: makeMethodFn("HEAD"),
574
+ interceptors,
575
+ options: makeMethodFn("OPTIONS"),
576
+ patch: makeMethodFn("PATCH"),
577
+ post: makeMethodFn("POST"),
578
+ put: makeMethodFn("PUT"),
579
+ request,
580
+ setConfig,
581
+ sse: {
582
+ connect: makeSseFn("CONNECT"),
583
+ delete: makeSseFn("DELETE"),
584
+ get: makeSseFn("GET"),
585
+ head: makeSseFn("HEAD"),
586
+ options: makeSseFn("OPTIONS"),
587
+ patch: makeSseFn("PATCH"),
588
+ post: makeSseFn("POST"),
589
+ put: makeSseFn("PUT"),
590
+ trace: makeSseFn("TRACE")
591
+ },
592
+ trace: makeMethodFn("TRACE")
593
+ };
594
+ };
595
+ // src/generated/client.gen.ts
596
+ const client = createClient(createConfig({ baseUrl: "https://forja.institutourupema.com.br" }));
597
+ // src/generated/sdk.gen.ts
598
+ var Identity = class {
599
+ /**
600
+ * Quem sou eu
601
+ *
602
+ * A identidade da pessoa dona do token e os grupos dela no Forja.
603
+ * Na CLI: `forja get-me`.
604
+ *
605
+ */
606
+ static getMe(options) {
607
+ return (options?.client ?? client).get({
608
+ url: "/api/v1/me",
609
+ ...options
610
+ });
611
+ }
612
+ };
613
+ // src/forjaClient.ts
614
+ /**
615
+ * Wraps a static SDK class so its methods are called with `client` already
616
+ * set. The type stays `typeof <Class>`: same signatures, same results.
617
+ */
618
+ const bindResource = (SdkClass, client) => {
619
+ return new Proxy(SdkClass, { get: (target, prop) => {
620
+ const value = target[prop];
621
+ if (typeof value === "function") return (options) => {
622
+ return value({
623
+ ...options,
624
+ client
625
+ });
626
+ };
627
+ return value;
628
+ } });
629
+ };
630
+ /**
631
+ * The Forja API, one property per resource (spec tag):
632
+ *
633
+ * ```ts
634
+ * const forja = new ForjaClient({ baseUrl, token });
635
+ * const { data, error } = await forja.identity.getMe();
636
+ * ```
637
+ */
638
+ var ForjaClient = class {
639
+ identity;
640
+ client;
641
+ constructor(options) {
642
+ this.client = createClient(createConfig({
643
+ baseUrl: options.baseUrl,
644
+ headers: options.headers
645
+ }));
646
+ const { token } = options;
647
+ if (token) this.client.interceptors.request.use(async (request) => {
648
+ const value = typeof token === "function" ? await token() : token;
649
+ request.headers.set("authorization", `Bearer ${value}`);
650
+ return request;
651
+ });
652
+ this.identity = bindResource(Identity, this.client);
653
+ }
654
+ };
655
+ export { ForjaClient, Identity as Identity2, createClient, createConfig };
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@urupema/forja-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "TypeScript SDK for the Forja API, generated from its OpenAPI specs.",
5
+ "type": "module",
6
+ "main": "dist/index.mjs",
7
+ "types": "dist/index.d.mts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.mts",
11
+ "import": "./dist/index.mjs"
12
+ }
13
+ },
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "devDependencies": {
21
+ "@hey-api/openapi-ts": "^0.99.0",
22
+ "@ttoss/openapi-codegen": "^0.10.2",
23
+ "@types/node": "^26.6.11",
24
+ "tsdown": "^0.23.7",
25
+ "tsx": "^4.23.15",
26
+ "typescript": "~6.0.3"
27
+ },
28
+ "license": "UNLICENSED",
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/urupema/forja.git",
32
+ "directory": "packages/sdk"
33
+ },
34
+ "homepage": "https://forja.institutourupema.com.br",
35
+ "engines": {
36
+ "node": ">=24"
37
+ },
38
+ "scripts": {
39
+ "generate": "tsx scripts/generate.ts",
40
+ "build": "tsdown",
41
+ "typecheck": "tsc -p ."
42
+ }
6
43
  }