diff --git a/package.json b/package.json index d8c8efb..3a534d0 100644 --- a/package.json +++ b/package.json @@ -49,17 +49,17 @@ "verify": "node ./scripts/check-architecture.mts && knip && vp check . && vp run skills:lint && vp run smoke:pack && vp test run --coverage" }, "dependencies": { - "@effect/platform-node": "4.1.2", - "@effect/platform-node-shared": "4.1.2", + "@effect/platform-node": "4.1.4", + "@effect/platform-node-shared": "4.1.4", "@sentry/core": "10.78.0", "cli-table3": "^0.6.5", - "effect": "4.1.2", + "effect": "4.1.4", "i18next": "^26.7.2" }, "devDependencies": { - "@effect/vitest": "4.1.2", + "@effect/vitest": "4.1.4", "@oxlint/plugins": "1.91.0", - "@putdotio/sdk": "15.0.1", + "@putdotio/sdk": "16.0.1", "@types/node": "^26.1.0", "@uinaf/oxlint-plugin-no-comments": "1.1.0", "@uinaf/skillcheck": "1.7.7", @@ -78,6 +78,6 @@ }, "packageManager": "pnpm@12.18.0", "inlinedDependencies": { - "@putdotio/sdk": "15.0.1" + "@putdotio/sdk": "16.0.1" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 44dd9d3..7ab2ba5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -174,18 +174,18 @@ catalogs: overrides: vite: npm:@voidzero-dev/vite-plus-core@1.5.0 vitest: 5.1.0 - '@putdotio/sdk>effect': 4.1.2 + '@putdotio/sdk>effect': 4.1.4 importers: .: dependencies: '@effect/platform-node': - specifier: 4.1.2 - version: 4.1.2(effect@4.1.2)(redis@6.2.1(@opentelemetry/api@1.9.1)) + specifier: 4.1.4 + version: 4.1.4(effect@4.1.4)(redis@6.2.1(@opentelemetry/api@1.9.1)) '@effect/platform-node-shared': - specifier: 4.1.2 - version: 4.1.2(effect@4.1.2) + specifier: 4.1.4 + version: 4.1.4(effect@4.1.4) '@sentry/core': specifier: 10.78.0 version: 10.78.0 @@ -193,21 +193,21 @@ importers: specifier: ^0.6.5 version: 0.6.5 effect: - specifier: 4.1.2 - version: 4.1.2 + specifier: 4.1.4 + version: 4.1.4 i18next: specifier: ^26.7.2 version: 26.7.2(typescript@7.0.2) devDependencies: '@effect/vitest': - specifier: 4.1.2 - version: 4.1.2(effect@4.1.2)(vitest@5.1.0) + specifier: 4.1.4 + version: 4.1.4(effect@4.1.4)(vitest@5.1.0) '@oxlint/plugins': specifier: 1.91.0 version: 1.91.0 '@putdotio/sdk': - specifier: 15.0.1 - version: 15.0.1 + specifier: 16.0.1 + version: 16.0.1 '@types/node': specifier: ^26.1.0 version: 26.6.6 @@ -283,23 +283,23 @@ packages: resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==} engines: {node: '>=0.1.90'} - '@effect/platform-node-shared@4.1.2': - resolution: {integrity: sha512-wSwl9A/G1hcVvF8nLI+YfB3EyOIDvWS6+lsTZBkmgDnPBL7m8YWZF+1HD+mdEsb52SUGfukip46Q3gRwSdk3QA==} + '@effect/platform-node-shared@4.1.4': + resolution: {integrity: sha512-DWdfphHGOFJNj/mYadgpT3jIm8aRXDcPrQiGXFBH4p2H4XmA7iYMrPsI8NxVgZ7kNX0q1+FGJZJama0tINHRAg==} engines: {node: '>=22.19.0'} peerDependencies: - effect: ^4.1.2 + effect: ^4.1.4 - '@effect/platform-node@4.1.2': - resolution: {integrity: sha512-ye0UjxORdd5Qu3paZ1LljgGOALWHt7muP9VTpjUSCNfcesiB/Hm7wPJIvZeu4gnwpTe5BtEnO1VHngWqjJp8mA==} + '@effect/platform-node@4.1.4': + resolution: {integrity: sha512-h7QExTPq/RfYtHP/8tMlgfBvqYsuJKhxfkU6w0+NaF/ihqQ8Y3GH9t28ltupQjoqMM7P6W5gy8rOji7F0qVrmg==} engines: {node: '>=22.19.0'} peerDependencies: - effect: ^4.1.2 + effect: ^4.1.4 redis: '>=5.1.0 <7.0.0' - '@effect/vitest@4.1.2': - resolution: {integrity: sha512-JJPwAHkJHxvM/woW9mMW/khjasAHcmwWdOMAgMy16rfqsxcVhFDnrRsvN9VI2+kMv8zDCCyBE2q1n5hzZlfE0w==} + '@effect/vitest@4.1.4': + resolution: {integrity: sha512-AKpZ6zKihCRhY7hDbiQ2yp/krw+afIkxDRjFMwwzMiyhd0iYk0WaHa9J6GGC7TUF/C7HP2dZyMVq5xC0Qm/2/g==} peerDependencies: - effect: ^4.1.2 + effect: ^4.1.4 vitest: 5.1.0 '@emnapi/core@1.11.2': @@ -1004,8 +1004,8 @@ packages: '@polka/url@1.0.0-next.29': resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==} - '@putdotio/sdk@15.0.1': - resolution: {integrity: sha512-4grTI4VdJ+KdhcCmbsoEYvnikg2tXvbQlr8nBIweXcBEBq5DPm1WKd1zn5jav0icknfaL9/iBI+Qtu00xJgQBQ==} + '@putdotio/sdk@16.0.1': + resolution: {integrity: sha512-t8BscAmDugV6IadPwcdK8nXOlmiCgo58t9PDEDwinB6Wntgb6xVOfc48xe3Kek75PPZDI+PQoUpGweL77kDz4w==} engines: {node: '>=24.19.0'} '@redis/bloom@6.2.1': @@ -1516,8 +1516,8 @@ packages: dom-accessibility-api@0.5.16: resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==} - effect@4.1.2: - resolution: {integrity: sha512-d3Oah1WyKxFLFh19yWheS5IXIVaITzxZ71JkE1rkUozq/6EcJSU5nPk5bF2QrSygZ3SQoiNQB8TsxFriyMeMaQ==} + effect@4.1.4: + resolution: {integrity: sha512-Tgrv/9FN+TZYyOn8XSli+fVqAfwDrDAkiX5Uu9vztINb675VTQdhD0gWI5Kzvhlh9QqzjZvw72iugqw5pwoghQ==} emoji-regex@8.0.0: resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} @@ -1865,8 +1865,8 @@ packages: undici-types@8.9.0: resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==} - undici@8.12.3: - resolution: {integrity: sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==} + undici@8.12.4: + resolution: {integrity: sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA==} engines: {node: '>=22.19.0'} vite-plus@1.5.0: @@ -1990,28 +1990,28 @@ snapshots: '@colors/colors@1.5.0': optional: true - '@effect/platform-node-shared@4.1.2(effect@4.1.2)': + '@effect/platform-node-shared@4.1.4(effect@4.1.4)': dependencies: '@types/ws': 8.18.2 - effect: 4.1.2 + effect: 4.1.4 ws: 8.22.1 transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/platform-node@4.1.2(effect@4.1.2)(redis@6.2.1(@opentelemetry/api@1.9.1))': + '@effect/platform-node@4.1.4(effect@4.1.4)(redis@6.2.1(@opentelemetry/api@1.9.1))': dependencies: - '@effect/platform-node-shared': 4.1.2(effect@4.1.2) - effect: 4.1.2 + '@effect/platform-node-shared': 4.1.4(effect@4.1.4) + effect: 4.1.4 redis: 6.2.1(@opentelemetry/api@1.9.1) - undici: 8.12.3 + undici: 8.12.4 transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/vitest@4.1.2(effect@4.1.2)(vitest@5.1.0)': + '@effect/vitest@4.1.4(effect@4.1.4)(vitest@5.1.0)': dependencies: - effect: 4.1.2 + effect: 4.1.4 vitest: 5.1.0(@opentelemetry/api@1.9.1)(@types/node@26.6.6)(@vitest/browser-preview@5.1.0)(@vitest/coverage-v8@5.1.0)(@vitest/ui@5.1.0)(@voidzero-dev/vite-plus-core@1.5.0(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(tsx@4.23.12)(typescript@7.0.2)(yaml@2.9.1)) '@emnapi/core@1.11.2': @@ -2387,9 +2387,9 @@ snapshots: '@polka/url@1.0.0-next.29': {} - '@putdotio/sdk@15.0.1': + '@putdotio/sdk@16.0.1': dependencies: - effect: 4.1.2 + effect: 4.1.4 '@redis/bloom@6.2.1(@redis/client@6.2.1(@opentelemetry/api@1.9.1))': dependencies: @@ -2732,7 +2732,7 @@ snapshots: dom-accessibility-api@0.5.16: {} - effect@4.1.2: {} + effect@4.1.4: {} emoji-regex@8.0.0: {} @@ -3130,7 +3130,7 @@ snapshots: undici-types@8.9.0: {} - undici@8.12.3: {} + undici@8.12.4: {} vite-plus@1.5.0(@opentelemetry/api@1.9.1)(@types/node@26.6.6)(@vitest/coverage-v8@5.1.0)(@vitest/ui@5.1.0)(esbuild@0.28.2)(jiti@2.7.0)(playwright@1.62.1)(tsx@4.23.12)(typescript@7.0.2)(yaml@2.9.1): dependencies: diff --git a/skills/putio-cli/references/guardrails.md b/skills/putio-cli/references/guardrails.md index f1cc1ee..97b8b60 100644 --- a/skills/putio-cli/references/guardrails.md +++ b/skills/putio-cli/references/guardrails.md @@ -14,6 +14,11 @@ copies the HTTP status into `statusCode` when the body is malformed, so matching and `errorType` matching the operation's known missing-file type. Unknown, empty, or unrelated types do not qualify; neither does prose. +Title `Unexpected response from put.io` means a successful response broke the +API contract: malformed, not JSON, or missing a requested field, which +`error.details` names as `["missing field", ""]`. Retry once, then report +it. Title `Invalid request` means the input was rejected before any request. + If a command fails: 1. Re-run with structured output. diff --git a/skills/putio-cli/references/writes.md b/skills/putio-cli/references/writes.md index 820ed3b..37a5e42 100644 --- a/skills/putio-cli/references/writes.md +++ b/skills/putio-cli/references/writes.md @@ -29,4 +29,5 @@ Rules: - Take required keys from `describe`; never guess names. - Treat every `sdk call` operation as potentially mutating and inspect its dry-run before `--execute`. - `sdk call` args are the SDK function's positional parameters and must match its input schema. A mismatch fails with title `Invalid SDK arguments` before any request; `error.details` names the `operation` and the schema `issue` with its path. +- Bulk selections (`downloadLinks.create`, `sharing.clone`, `sharing.shareFiles`, `zips.create`) need `ids` or a `cursor`; `zips.create` names them `file_ids`. - `files upload` sends to `PUTIO_CLI_UPLOAD_BASE_URL`, or upload.put.io with the default API base. With a custom `PUTIO_CLI_API_BASE_URL` and no upload base, it fails before sending anything; set both together. diff --git a/src/command-paths.test.ts b/src/command-paths.test.ts index b7bdde3..8d2c52f 100644 --- a/src/command-paths.test.ts +++ b/src/command-paths.test.ts @@ -193,7 +193,10 @@ const routeReads = (api: FixtureApi) => { "GET /v2/files/search", ok({ cursor: null, files: [file(2, "movie.mkv", { file_type: "VIDEO", size: 42 })], total: 1 }), ); - api.route("GET /v2/transfers/list", ok({ cursor: null, transfers: [transfer(7, "ubuntu.iso")] })); + api.route( + "GET /v2/transfers/list", + ok({ cursor: null, total: 1, transfers: [transfer(7, "ubuntu.iso")] }), + ); api.route("GET /v2/transfers/7", ok({ transfer: transfer(7, "ubuntu.iso", "COMPLETED") })); }; @@ -612,6 +615,33 @@ describe("reads", () => { ]); }); + it("names the missing field when a transfers page omits its total", async () => { + api.route("GET /v2/transfers/list", ok({ cursor: null, transfers: [] })); + + const run = await putio("transfers", "list", "--output", "json"); + + expect(run.exitCode).toBe(1); + expect(run.stdout).toBe(""); + expect(stderrJson(run).error).toMatchObject({ + details: [["missing field", "total"]], + message: "put.io returned data the CLI did not expect.", + title: "Unexpected response from put.io", + }); + }); + + it("reports a successful response that is not JSON as an unexpected response", async () => { + api.route("GET /v2/files/list", () => ({ body: "", contentType: "text/html" })); + + const run = await putio("files", "list", "--output", "json"); + + expect(run.exitCode).toBe(1); + expect(run.stdout).toBe(""); + expect(stderrJson(run).error).toMatchObject({ + message: "put.io returned data the CLI did not expect.", + title: "Unexpected response from put.io", + }); + }); + it.each([ ["json", (run: CliRun) => stdoutJson(run)], ["ndjson", (run: CliRun) => stdoutLines(run)[0]], @@ -687,7 +717,7 @@ describe("pagination", () => { { args: ["transfers", "list"], continuePath: "/v2/transfers/list/continue", - first: { path: "GET /v2/transfers/list", page: {} }, + first: { path: "GET /v2/transfers/list", page: { total: 3 } }, itemKey: "transfers", items: [transfer(7, "ubuntu.iso"), transfer(8, "fedora.iso"), transfer(9, "debian.iso")], }, @@ -1262,6 +1292,20 @@ describe("sdk call", () => { ], ["--dry-run", "missing argument", "transfers.get", "[]", "Missing key at [0]"], ["--dry-run", "argument for a nullary operation", "zips.list", "[1]", /at \[0\]/], + ["--dry-run", "no selection", "downloadLinks.create", "[{}]", /Missing key/], + ["--dry-run", "no selection", "sharing.clone", '[{"parentId":0}]', /Missing key/], + [ + "--dry-run", + "no selection", + "sharing.shareFiles", + '[{"target":{"type":"everyone"}}]', + /Missing key/, + ], + ["--dry-run", "no selection", "zips.create", '[{"exclude_ids":[1]}]', /Missing key/], + ["--dry-run", "empty ids", "downloadLinks.create", '[{"ids":[]}]', /length of at least 1/], + ["--dry-run", "non-positive id", "sharing.clone", '[{"ids":[0]}]', /greater than 0/], + ["--dry-run", "empty cursor", "zips.create", '[{"cursor":""}]', /length of at least 1/], + ["--dry-run", "negative parent", "sharing.clone", '[{"ids":[1],"parentId":-1}]', /parentId/], ])("rejects %s args with %s before any request", async (mode, _label, operation, args, issue) => { const run = await putio( "sdk", diff --git a/src/commands/download-links.ts b/src/commands/download-links.ts index 17c29d8..07be290 100644 --- a/src/commands/download-links.ts +++ b/src/commands/download-links.ts @@ -1,5 +1,5 @@ import { Command } from "effect/cli"; -import { DownloadLinksCreateInputSchema } from "@putdotio/sdk"; +import { DownloadLinksCreateInputSchema, type FilesBulkSelection } from "@putdotio/sdk"; import { Data, Effect, Option, Predicate, Schema } from "effect"; import { @@ -54,20 +54,23 @@ export type DownloadLinksCreateInput = Schema.Schema.Type | string | undefined) => value === undefined || Predicate.isString(value) ? [] : value; -export const resolveDownloadLinksCreateInput = (input: DownloadLinksCreateInput) => { - const normalized = { - cursor: input.cursor, - excludeIds: toOptionalIds(selectionIds(input.excludeIds)), - ids: toOptionalIds(selectionIds(input.ids)), - }; - - if (!normalized.cursor && !normalized.ids) { - throw new DownloadLinksCommandError({ - message: "Provide at least one --id or a --cursor to create download links.", - }); +export const resolveDownloadLinksCreateInput = ( + input: DownloadLinksCreateInput, +): FilesBulkSelection => { + const excludeIds = toOptionalIds(selectionIds(input.excludeIds)); + const ids = toOptionalIds(selectionIds(input.ids)); + + if (ids !== undefined) { + return { cursor: input.cursor, excludeIds, ids }; + } + + if (input.cursor) { + return { cursor: input.cursor, excludeIds, ids }; } - return normalized; + throw new DownloadLinksCommandError({ + message: "Provide at least one --id or a --cursor to create download links.", + }); }; const downloadLinksCreate = Command.make( diff --git a/src/commands/files.ts b/src/commands/files.ts index b8e2fef..d907832 100644 --- a/src/commands/files.ts +++ b/src/commands/files.ts @@ -116,17 +116,17 @@ const NonBlankStringSchema = Schema.String.check( ), ); -const NonEmptyIdsSchema = Schema.Array(Schema.Number).check(Schema.isNonEmpty()); +const NonEmptyIdsSchema = Schema.Array(Schema.Finite).check(Schema.isNonEmpty()); const PositiveIntegerSchema = Schema.Int.check(Schema.isGreaterThan(0)); const NonNegativeIntegerSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); const FilesMkdirInputSchema = Schema.Struct({ name: NonBlankStringSchema, - parent_id: Schema.optional(Schema.Number), + parent_id: Schema.optional(Schema.Finite), }); const FilesRenameInputSchema = Schema.Struct({ - file_id: Schema.Number, + file_id: Schema.Finite, name: NonBlankStringSchema, }); @@ -137,7 +137,7 @@ const FilesDeleteInputSchema = Schema.Struct({ const FilesMoveInputSchema = Schema.Struct({ ids: NonEmptyIdsSchema, - parent_id: Schema.Number, + parent_id: Schema.Finite, }); const FilesUploadInputSchema = Schema.Struct({ diff --git a/src/commands/transfers.ts b/src/commands/transfers.ts index bf7c940..461348e 100644 --- a/src/commands/transfers.ts +++ b/src/commands/transfers.ts @@ -57,7 +57,7 @@ const optionalTransferIdOption = optionalTransferIdConfig.option; const WATCH_TERMINAL_STATUSES = ["COMPLETED", "ERROR", "SEEDING"] as const; -const NonEmptyIdsSchema = Schema.Array(Schema.Number).check(Schema.isNonEmpty()); +const NonEmptyIdsSchema = Schema.Array(Schema.Finite).check(Schema.isNonEmpty()); const TransfersAddInputSchema = Schema.Array(TransferAddInputSchema).check(Schema.isNonEmpty()); @@ -66,7 +66,7 @@ const TransfersCancelInputSchema = Schema.Struct({ }); const TransfersSingleIdInputSchema = Schema.Struct({ - id: Schema.Number, + id: Schema.Finite, }); const TransfersCleanInputSchema = Schema.Struct({ diff --git a/src/i18n/catalog/en.ts b/src/i18n/catalog/en.ts index 265a4d2..526133d 100644 --- a/src/i18n/catalog/en.ts +++ b/src/i18n/catalog/en.ts @@ -125,6 +125,12 @@ export const en = { title: "Permission denied", message: "You don't have permission to do that.", }, + contract: { + title: "Unexpected response from put.io", + message: "put.io returned data the CLI did not expect.", + retryHint: "Retry the command once in case the response was transient.", + reportHint: "If it keeps happening, report it with the command and output.", + }, config: { title: "Configuration error", message: "The CLI configuration is invalid or incomplete.", @@ -208,10 +214,10 @@ export const en = { }, }, validation: { - title: "Unexpected response from put.io", - message: "put.io returned data the CLI did not expect.", - retryHint: "Retry the command once in case the response was transient.", - reportHint: "If it keeps happening, report it with the command and output.", + title: "Invalid request", + message: "The request input was rejected before it was sent.", + checkHint: "Check the flag values or JSON input and try again.", + describeHint: "Run `putio describe` to see what the command accepts.", }, terminal: { tryThis: "Try this", diff --git a/src/internal/localize-error.test.ts b/src/internal/localize-error.test.ts index f8d4bd1..c837e3a 100644 --- a/src/internal/localize-error.test.ts +++ b/src/internal/localize-error.test.ts @@ -1,4 +1,6 @@ import { + PutioConfigurationError, + PutioContractError, PutioOperationError, PutioRateLimitError, PutioTransportError, @@ -118,7 +120,7 @@ describe("localizeCliError", () => { it("localizes files operation errors with file-specific copy", () => { const localized = localizeCliError( - operationError("files", "list", { + operationError("files", "query", { errorMessage: "file lost", errorType: "FILE_LOST", status: 410, @@ -165,7 +167,7 @@ describe("localizeCliError", () => { it.each([ [ "localizes file-not-reachable errors", - operationError("files", "list", { + operationError("files", "query", { errorMessage: "file not reachable", errorType: "FILE_NOT_REACHABLE", status: 503, @@ -229,6 +231,24 @@ describe("localizeCliError", () => { "That transfer request is not valid", "Review the transfer id or input and try again.", ], + [ + "localizes transfer continuation bad requests", + operationError("transfers", "continue", { + errorMessage: "bad request", + status: 400, + }), + "That transfer request is not valid", + "Review the transfer id or input and try again.", + ], + [ + "localizes search continuation not-found errors", + operationError("files", "continueSearch", { + errorMessage: "not found", + status: 404, + }), + "File not found", + "The file you requested is not available.", + ], [ "localizes concurrent download-links limits", operationError("downloadLinks", "create", { @@ -323,10 +343,68 @@ describe("localizeCliError", () => { new PutioValidationError({ cause: new Error("bad payload") }), ); + expect(localized.message).toBe("Invalid request"); + expect(localized.recoverySuggestion.description).toBe( + "The request input was rejected before it was sent.", + ); + expect(localized.meta).toEqual({ + hints: [ + "Check the flag values or JSON input and try again.", + "Run `putio describe` to see what the command accepts.", + ], + }); + }); + + it("localizes a response that lacks a requested field", () => { + const localized = localizeCliError(new PutioContractError({ missingField: "total" })); + + expect(localized.message).toBe("Unexpected response from put.io"); + expect(localized.recoverySuggestion.description).toBe( + "put.io returned data the CLI did not expect.", + ); + expect(localized.meta).toEqual({ + details: [["missing field", "total"]], + hints: [ + "Retry the command once in case the response was transient.", + "If it keeps happening, report it with the command and output.", + ], + }); + }); + + it("localizes a response that is not valid JSON", () => { + const localized = localizeCliError( + new PutioContractError({ + cause: new SyntaxError("The HTTP response body is not valid JSON"), + }), + ); + expect(localized.message).toBe("Unexpected response from put.io"); expect(localized.recoverySuggestion.description).toBe( "put.io returned data the CLI did not expect.", ); + expect(localized.meta).toEqual({ + details: undefined, + hints: [ + "Retry the command once in case the response was transient.", + "If it keeps happening, report it with the command and output.", + ], + }); + }); + + it("localizes SDK configuration errors", () => { + const localized = localizeCliError( + new PutioConfigurationError({ + cause: "SDK request headers must be valid HTTP header values", + }), + ); + + expect(localized.message).toBe("Configuration error"); + expect(localized.meta).toEqual({ + hints: [ + "Check the relevant `PUTIO_CLI_*` environment variables and try again.", + "If you use a persisted config file, verify that its JSON is valid.", + ], + }); }); it("localizes rate-limit errors without retry metadata", () => { diff --git a/src/internal/localizers/files.ts b/src/internal/localizers/files.ts index 1a51241..32d7dc3 100644 --- a/src/internal/localizers/files.ts +++ b/src/internal/localizers/files.ts @@ -2,7 +2,15 @@ import { translate } from "../../i18n/index.js"; import { createOperationLocalizer, hasOperationErrorType, hasOperationStatus } from "./helpers.js"; -const fileOperations = ["list", "continue", "get", "search", "createFolder", "rename"] as const; +const fileOperations = [ + "query", + "continue", + "get", + "search", + "continueSearch", + "createFolder", + "rename", +] as const; export const cliFilesErrorLocalizers = [ createOperationLocalizer( diff --git a/src/internal/localizers/shared.ts b/src/internal/localizers/shared.ts index a19666b..5164a1e 100644 --- a/src/internal/localizers/shared.ts +++ b/src/internal/localizers/shared.ts @@ -175,13 +175,39 @@ const validationLocalizer: MatchConditionLocalizer = { }, meta: { hints: [ - translate("cli.error.validation.retryHint"), - translate("cli.error.validation.reportHint"), + translate("cli.error.validation.checkHint"), + translate("cli.error.validation.describeHint"), ], }, }), }; +const contractLocalizer: MatchConditionLocalizer = { + kind: "match_condition", + match: (error) => isPlainRecord(error) && Predicate.isTagged(error, "PutioContractError"), + localize: (error) => { + const missingField = + isPlainRecord(error) && "missingField" in error && isNonEmptyString(error.missingField) + ? error.missingField + : undefined; + + return { + message: translate("cli.error.contract.title"), + recoverySuggestion: { + type: "instruction", + description: translate("cli.error.contract.message"), + }, + meta: { + details: missingField ? ([["missing field", missingField]] as const) : undefined, + hints: [ + translate("cli.error.contract.retryHint"), + translate("cli.error.contract.reportHint"), + ], + }, + }; + }, +}; + const sdkArgumentsLocalizer: MatchConditionLocalizer = { kind: "match_condition", match: (error) => isPlainRecord(error) && Predicate.isTagged(error, "CliSdkArgumentsError"), @@ -233,7 +259,10 @@ const authFlowLocalizer: MatchConditionLocalizer = { const configLocalizer: MatchConditionLocalizer = { kind: "match_condition", - match: (error) => isPlainRecord(error) && Predicate.isTagged(error, "CliConfigError"), + match: (error) => + isPlainRecord(error) && + (Predicate.isTagged(error, "CliConfigError") || + Predicate.isTagged(error, "PutioConfigurationError")), localize: (error) => ({ message: translate("cli.error.config.title"), recoverySuggestion: { @@ -263,6 +292,7 @@ export const cliSharedErrorLocalizers = [ forbiddenLocalizer, transportLocalizer, validationLocalizer, + contractLocalizer, sdkArgumentsLocalizer, authFlowLocalizer, configLocalizer, diff --git a/src/internal/localizers/transfers.ts b/src/internal/localizers/transfers.ts index d1d76b1..b5b4c26 100644 --- a/src/internal/localizers/transfers.ts +++ b/src/internal/localizers/transfers.ts @@ -50,7 +50,8 @@ export const cliTransfersErrorLocalizers = [ }), ), createOperationLocalizer( - (error) => hasOperationStatus(error, "transfers", ["list", "add", "addMany", "retry"], 400), + (error) => + hasOperationStatus(error, "transfers", ["list", "continue", "add", "addMany", "retry"], 400), () => ({ message: translate("cli.error.transfers.badRequest.title"), recoverySuggestion: { diff --git a/src/internal/sdk-operation-args.ts b/src/internal/sdk-operation-args.ts index 971a1a4..a487fd6 100644 --- a/src/internal/sdk-operation-args.ts +++ b/src/internal/sdk-operation-args.ts @@ -3,7 +3,6 @@ import { AccountConfirmationSchema, AccountInfoQuerySchema, CreateAppSpecificPasswordInputSchema, - DownloadLinksCreateInputSchema, EventsListQuerySchema, FileCopyInputSchema, FileGetChildInputSchema, @@ -21,7 +20,6 @@ import { PublicShareListQuerySchema, RssFeedParamsSchema, SaveAccountSettingsPayloadSchema, - SharingCloneInputSchema, SharingShareInputSchema, SharingUnshareInputSchema, TransferAddInputSchema, @@ -99,6 +97,12 @@ const Id = Schema.Int; const Ids = Schema.Array(Schema.Int); const PerPageQuery = Schema.Struct({ per_page: Schema.optionalKey(Schema.Int) }); +const SelectionIds = Schema.Array(Schema.Int.check(Schema.isGreaterThan(0))).check( + Schema.isMinLength(1), +); + +const SelectionCursor = Schema.String.check(Schema.isMinLength(1)); + const none = Schema.Tuple([]); const byId = Schema.Tuple([Id]); const byText = Schema.Tuple([Schema.String]); @@ -109,15 +113,15 @@ const bulkSelection = (extra: Extra) = Schema.Union([ Schema.Struct({ ...extra, - cursor: Schema.String, + cursor: SelectionCursor, excludeIds: Schema.optionalKey(Ids), - ids: Schema.optionalKey(Ids), + ids: Schema.optionalKey(SelectionIds), }), Schema.Struct({ ...extra, - cursor: Schema.optionalKey(Schema.String), + cursor: Schema.optionalKey(SelectionCursor), excludeIds: Schema.optionalKey(Ids), - ids: Ids, + ids: SelectionIds, }), ]); @@ -147,7 +151,7 @@ const TrashBulkInputSchema = Schema.Union([ Schema.Struct({ file_ids: Ids, useCursor: Schema.optionalKey(Schema.Literal(false)) }), ]); -const QueryValueSchema = Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null]); +const QueryValueSchema = Schema.Union([Schema.String, Schema.Finite, Schema.Boolean, Schema.Null]); const sdkOperationArgsSchemas = defineArgsSchemas({ "account.appSpecificPasswords.create": Schema.Tuple([CreateAppSpecificPasswordInputSchema]), @@ -162,7 +166,7 @@ const sdkOperationArgsSchemas = defineArgsSchemas({ ]), "account.listSubtitleLanguages": none, "account.saveSettings": Schema.Tuple([SaveAccountSettingsPayloadSchema]), - "downloadLinks.create": Schema.Tuple([Schema.optionalKey(DownloadLinksCreateInputSchema)]), + "downloadLinks.create": Schema.Tuple([FilesBulkSelectionSchema]), "downloadLinks.get": byId, "events.clear": none, "events.delete": byId, @@ -256,7 +260,7 @@ const sdkOperationArgsSchemas = defineArgsSchemas({ "files.resetStartFrom": byId, "files.search": Schema.Tuple([FilesSearchQuerySchema]), "files.setSort": Schema.Tuple([FileSetSortInputSchema]), - "files.setStartFrom": Schema.Tuple([Schema.Struct({ file_id: Id, time: Schema.Number })]), + "files.setStartFrom": Schema.Tuple([Schema.Struct({ file_id: Id, time: Schema.Finite })]), "files.setWatchStatus": Schema.Tuple([bulkSelection({ watched: Schema.Boolean })]), "files.touch": Schema.Tuple([FileTouchInputSchema]), "friendInvites.create": none, @@ -346,7 +350,11 @@ const sdkOperationArgsSchemas = defineArgsSchemas({ "rss.retryAll": byId, "rss.retryItem": Schema.Tuple([Id, Id]), "rss.update": Schema.Tuple([Id, RssFeedParamsSchema]), - "sharing.clone": Schema.Tuple([Schema.optionalKey(SharingCloneInputSchema)]), + "sharing.clone": Schema.Tuple([ + bulkSelection({ + parentId: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), + }), + ]), "sharing.getCloneInfo": byId, "sharing.getSharedWith": byId, "sharing.listSharedFiles": none, @@ -357,7 +365,9 @@ const sdkOperationArgsSchemas = defineArgsSchemas({ "sharing.publicShares.create": byId, "sharing.publicShares.delete": byId, "sharing.publicShares.list": none, - "sharing.shareFiles": Schema.Tuple([SharingShareInputSchema]), + "sharing.shareFiles": Schema.Tuple([ + bulkSelection({ target: SharingShareInputSchema.fields.target }), + ]), "sharing.unshare": Schema.Tuple([SharingUnshareInputSchema]), "transfers.add": Schema.Tuple([TransferAddInputSchema]), "transfers.addMany": Schema.Tuple([Schema.Array(TransferAddInputSchema)]), @@ -382,11 +392,18 @@ const sdkOperationArgsSchemas = defineArgsSchemas({ "tunnel.listRoutes": none, "zips.cancel": byId, "zips.create": Schema.Tuple([ - Schema.Struct({ - cursor: Schema.optionalKey(Schema.String), - exclude_ids: Schema.optionalKey(Ids), - file_ids: Schema.optionalKey(Ids), - }), + Schema.Union([ + Schema.Struct({ + cursor: SelectionCursor, + exclude_ids: Schema.optionalKey(Ids), + file_ids: Schema.optionalKey(SelectionIds), + }), + Schema.Struct({ + cursor: Schema.optionalKey(SelectionCursor), + exclude_ids: Schema.optionalKey(Ids), + file_ids: SelectionIds, + }), + ]), ]), "zips.get": byId, "zips.list": none,