@putdotio/sdk 9.0.1 → 9.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/dist/index.js CHANGED
@@ -1,167 +1,6 @@
1
- import { FetchHttpClient, Headers, HttpClient, HttpClientRequest, HttpClientResponse } from "@effect/platform";
2
- import { Context, Data, Effect, Layer, ManagedRuntime, Option, Schema } from "effect";
3
- //#region src/core/errors.ts
4
- const PutioErrorEnvelopeSchema = Schema.Struct({
5
- error_message: Schema.optional(Schema.String),
6
- error_type: Schema.optional(Schema.String),
7
- status_code: Schema.optional(Schema.Number.pipe(Schema.int())),
8
- details: Schema.optional(Schema.Unknown)
9
- });
10
- const isKnownContractMatch = (contract, error) => {
11
- if (contract.errorType !== void 0) return error.body.error_type === contract.errorType;
12
- if (contract.statusCode !== void 0) return error.status === contract.statusCode;
13
- return false;
14
- };
15
- const isMatchableApiError = (error) => error._tag === "PutioApiError" || error._tag === "PutioAuthError";
16
- function toOperationReason(contract) {
17
- if (contract.errorType !== void 0) return {
18
- kind: "error_type",
19
- errorType: contract.errorType
20
- };
21
- return {
22
- kind: "status_code",
23
- statusCode: contract.statusCode
24
- };
25
- }
26
- var PutioTransportError = class extends Data.TaggedError("PutioTransportError") {};
27
- var PutioConfigurationError = class extends Data.TaggedError("PutioConfigurationError") {};
28
- var PutioValidationError = class extends Data.TaggedError("PutioValidationError") {};
29
- var PutioApiError = class extends Data.TaggedError("PutioApiError") {};
30
- var PutioAuthError = class extends Data.TaggedError("PutioAuthError") {};
31
- var PutioRateLimitError = class extends Data.TaggedError("PutioRateLimitError") {};
32
- var PutioOperationError = class extends Data.TaggedError("PutioOperationError") {};
33
- const definePutioOperationErrorSpec = (spec) => spec;
34
- const decodePutioErrorEnvelope = Schema.decodeUnknown(PutioErrorEnvelopeSchema);
35
- const fallbackPutioErrorEnvelope = (status) => ({
36
- error_message: `put.io API request failed with status ${status}`,
37
- status_code: status
38
- });
39
- const responseRateLimitHeaders = (headers) => ({
40
- action: Option.getOrUndefined(Headers.get(headers, "x-ratelimit-action")),
41
- id: Option.getOrUndefined(Headers.get(headers, "x-ratelimit-id")),
42
- limit: Option.getOrUndefined(Headers.get(headers, "x-ratelimit-limit")),
43
- remaining: Option.getOrUndefined(Headers.get(headers, "x-ratelimit-remaining")),
44
- retryAfter: Option.getOrUndefined(Headers.get(headers, "retry-after")),
45
- reset: Option.getOrUndefined(Headers.get(headers, "x-ratelimit-reset"))
46
- });
47
- const mapDecodeErrorToValidationError = (cause) => new PutioValidationError({ cause });
48
- const mapConfigurationError = (cause) => new PutioConfigurationError({ cause });
49
- const mapTransportError = (cause) => new PutioTransportError({ cause });
50
- const makeResponseError = (status, headers, body) => {
51
- if (status === 429) return new PutioRateLimitError({
52
- status,
53
- body,
54
- ...responseRateLimitHeaders(headers)
55
- });
56
- if (status === 401 || status === 403) return new PutioAuthError({
57
- status,
58
- body
59
- });
60
- return new PutioApiError({
61
- status,
62
- body
63
- });
64
- };
65
- const parseErrorBody = (status, json) => decodePutioErrorEnvelope(json).pipe(Effect.orElseSucceed(() => fallbackPutioErrorEnvelope(status)));
66
- function withOperationErrors(effectOrSpec, maybeSpec) {
67
- if (maybeSpec === void 0) {
68
- const spec = effectOrSpec;
69
- return (effect) => withOperationErrors(effect, spec);
70
- }
71
- const effect = effectOrSpec;
72
- const spec = maybeSpec;
73
- return effect.pipe(Effect.mapError((error) => {
74
- if (!isMatchableApiError(error)) return error;
75
- const contract = spec.knownErrors.find((candidate) => isKnownContractMatch(candidate, error));
76
- if (!contract) return error;
77
- return new PutioOperationError({
78
- body: error.body,
79
- contract,
80
- domain: spec.domain,
81
- operation: spec.operation,
82
- reason: toOperationReason(contract),
83
- status: error.status
84
- });
85
- }));
86
- }
87
- //#endregion
88
- //#region src/core/defaults.ts
89
- const DEFAULT_PUTIO_API_BASE_URL = "https://api.put.io";
90
- const DEFAULT_PUTIO_UPLOAD_BASE_URL = "https://upload.put.io";
91
- const DEFAULT_PUTIO_WEB_APP_URL = "https://app.put.io";
92
- //#endregion
93
- //#region src/core/http.ts
94
- var PutioSdkConfig = class extends Context.Tag("PutioSdkConfig")() {};
95
- const makePutioSdkConfig = (config) => ({
96
- accessToken: config.accessToken,
97
- baseUrl: config.baseUrl ?? "https://api.put.io",
98
- uploadBaseUrl: config.uploadBaseUrl ?? "https://upload.put.io",
99
- webAppUrl: config.webAppUrl ?? "https://app.put.io"
100
- });
101
- const makePutioSdkLayer = (config) => Layer.succeed(PutioSdkConfig, makePutioSdkConfig(config));
102
- const buildPutioUrl = (baseUrl, path, query) => {
103
- const url = new URL(path, baseUrl);
104
- if (query) {
105
- for (const [key, value] of Object.entries(query)) if (value !== void 0 && value !== null) url.searchParams.set(key, String(value));
106
- }
107
- return url.toString();
108
- };
109
- const OkResponseSchema = Schema.Struct({ status: Schema.Literal("OK") });
110
- const isSuccessStatus = (status) => status >= 200 && status < 300;
111
- const decodeSuccessJson = (schema, response) => HttpClientResponse.schemaBodyJson(schema)(response).pipe(Effect.mapError(mapDecodeErrorToValidationError));
112
- const decodeFailure = (response, headers) => response.json.pipe(Effect.flatMap((json) => parseErrorBody(response.status, json)), Effect.orElseSucceed(() => fallbackPutioErrorEnvelope(response.status)), Effect.map((body) => makeResponseError(response.status, headers, body)));
113
- const toBasicAuthorization = (username, password) => {
114
- if (typeof globalThis.btoa === "function") return `Basic ${globalThis.btoa(`${username}:${password}`)}`;
115
- throw mapConfigurationError("This runtime does not provide btoa(), so Basic auth cannot be encoded safely");
116
- };
117
- const resolveAuthorization = (config, auth) => {
118
- const resolvedAuth = auth ?? { type: "config-token" };
119
- switch (resolvedAuth.type) {
120
- case "none": return Effect.succeed(void 0);
121
- case "token": return Effect.succeed(`Token ${resolvedAuth.token}`);
122
- case "basic": return Effect.try({
123
- try: () => toBasicAuthorization(resolvedAuth.username, resolvedAuth.password),
124
- catch: mapConfigurationError
125
- });
126
- case "config-token":
127
- if (!config.accessToken) return Effect.fail(mapConfigurationError("This endpoint requires an access token, but PutioSdkConfig.accessToken is missing"));
128
- return Effect.succeed(`Token ${config.accessToken}`);
129
- }
130
- };
131
- const normalizeFormValue = (value) => {
132
- if (value === null || value === void 0) return "";
133
- if (typeof value === "string") return value;
134
- if (typeof value === "number" || typeof value === "boolean") return String(value);
135
- return JSON.stringify(value);
136
- };
137
- const withBody = (request, body) => {
138
- switch (body.type) {
139
- case "none": return Effect.succeed(request);
140
- case "json": return HttpClientRequest.bodyJson(request, body.value).pipe(Effect.mapError(mapDecodeErrorToValidationError));
141
- case "form": return Effect.succeed(HttpClientRequest.bodyUrlParams(request, Object.fromEntries(Object.entries(body.value).flatMap(([key, value]) => value === void 0 ? [] : [[key, normalizeFormValue(value)]]))));
142
- case "form-data": return Effect.succeed(HttpClientRequest.bodyFormData(request, body.value));
143
- }
144
- };
145
- const makeRequest = (url, options, authorization) => Effect.gen(function* () {
146
- const headers = authorization ? Headers.set(Headers.fromInput(options.headers), "authorization", authorization) : Headers.fromInput(options.headers);
147
- const body = options.body ?? { type: "none" };
148
- return yield* withBody(HttpClientRequest.make(options.method)(url, {
149
- acceptJson: true,
150
- headers
151
- }), body);
152
- });
153
- const executeRequest = (options) => Effect.gen(function* () {
154
- const config = yield* PutioSdkConfig;
155
- const authorization = yield* resolveAuthorization(config, options.auth);
156
- const request = yield* makeRequest(buildPutioUrl(options.baseUrl ?? config.baseUrl ?? "https://api.put.io", options.path, options.query), options, authorization);
157
- return yield* HttpClient.execute(request).pipe(Effect.mapError(mapTransportError));
158
- });
159
- const requestJson = (schema, options) => executeRequest(options).pipe(Effect.flatMap((response) => isSuccessStatus(response.status) ? decodeSuccessJson(schema, response) : decodeFailure(response, response.headers).pipe(Effect.flatMap(Effect.fail))));
160
- const selectJsonField = (field) => (effect) => effect.pipe(Effect.map((value) => value[field]));
161
- const selectJsonFields = (...fields) => (effect) => effect.pipe(Effect.map((value) => Object.fromEntries(fields.map((field) => [field, value[field]]))));
162
- const requestArrayBuffer = (options) => executeRequest(options).pipe(Effect.flatMap((response) => isSuccessStatus(response.status) ? response.arrayBuffer.pipe(Effect.mapError(mapTransportError), Effect.map((buffer) => new Uint8Array(buffer))) : decodeFailure(response, response.headers).pipe(Effect.flatMap(Effect.fail))));
163
- const requestVoid = (options) => executeRequest(options).pipe(Effect.flatMap((response) => isSuccessStatus(response.status) ? Effect.void : decodeFailure(response, response.headers).pipe(Effect.flatMap(Effect.fail))));
164
- //#endregion
1
+ import { A as mapTransportError, C as PutioValidationError, D as makeResponseError, E as fallbackPutioErrorEnvelope, M as responseRateLimitHeaders, N as withOperationErrors, O as mapConfigurationError, S as PutioTransportError, T as definePutioOperationErrorSpec, _ as PutioAuthError, a as buildPutioUrl, b as PutioOperationError, c as requestArrayBuffer, d as selectJsonField, f as selectJsonFields, g as PutioApiError, h as DEFAULT_PUTIO_WEB_APP_URL, i as PutioSdkConfig, j as parseErrorBody, k as mapDecodeErrorToValidationError, l as requestJson, m as DEFAULT_PUTIO_UPLOAD_BASE_URL, n as toCursorSelectionForm, o as makePutioSdkConfig, p as DEFAULT_PUTIO_API_BASE_URL, r as OkResponseSchema, s as makePutioSdkLayer, t as joinCsv, u as requestVoid, v as PutioConfigurationError, w as decodePutioErrorEnvelope, x as PutioRateLimitError, y as PutioErrorEnvelopeSchema } from "./forms-DM_sjuyz.js";
2
+ import { FetchHttpClient } from "@effect/platform";
3
+ import { Effect, Layer, ManagedRuntime, Schema } from "effect";
165
4
  //#region src/domains/account.ts
166
5
  const RequestedFlag$1 = Schema.Literal(1);
167
6
  const AccountDiskSchema = Schema.Struct({
@@ -1197,17 +1036,6 @@ const deleteConfigKey = (key) => requestJson(OkResponseSchema, {
1197
1036
  path: `/v2/config/${key}`
1198
1037
  });
1199
1038
  //#endregion
1200
- //#region src/core/forms.ts
1201
- const joinCsv = (values) => values && values.length > 0 ? values.join(",") : void 0;
1202
- const toCursorSelectionForm = (selection, idsFieldName) => {
1203
- const resolvedIdsFieldName = idsFieldName ?? "file_ids";
1204
- return {
1205
- cursor: selection.cursor,
1206
- exclude_ids: joinCsv(selection.excludeIds),
1207
- [resolvedIdsFieldName]: joinCsv(selection.ids)
1208
- };
1209
- };
1210
- //#endregion
1211
1039
  //#region src/domains/download-links.ts
1212
1040
  const DownloadLinksStatusSchema = Schema.Literal("NEW", "PROCESSING", "DONE", "ERROR");
1213
1041
  const DownloadLinksCreateInputSchema = Schema.Struct({