diff --git a/docs/api-client-reference.md b/docs/api-client-reference.md index c2d3150..af2df07 100644 --- a/docs/api-client-reference.md +++ b/docs/api-client-reference.md @@ -8,21 +8,38 @@ - [Projects](#projects) - [projects.list](#projectslistrequest-config) - [projects.first](#projectsfirstrequest-config) + - [projects.create](#projectscreaterequest-config) +- [Organizations](#organizations) + - [organizations.getUsage](#organizationsgetusagerequest-config) + - [organizations.search](#organizationssearchrequest-config) + - [organizations.getCreditSummary](#organizationsgetcreditsummaryrequest-config) + - [organizations.listCreditTransactions](#organizationslistcredittransactionsrequest-config) + - [organizations.listCreditTransactionsPage](#organizationslistcredittransactionspagerequest-config) + - [organizations.listCreditTopups](#organizationslistcredittopupsrequest-config) - [Files](#files) - [files.list](#fileslistrequest-config) - [files.first](#filesfirstrequest-config) - [files.listKeys](#fileslistkeysrequest-config) - [files.listKeysPage](#fileslistkeyspagerequest-config) - [files.getContents](#filesgetcontentsrequest-config) + - [files.listPublished](#fileslistpublishedrequest-config) - [Keys](#keys) - [keys.update](#keysupdaterequest-config) - [keys.delete](#keysdeleterequest-config) - [keys.deprecate](#keysdeprecaterequest-config) - [keys.submitTranslation](#keyssubmittranslationrequest-config) + - [keys.getDetails](#keysgetdetailsrequest-config) + - [keys.editSource](#keyseditsourcerequest-config) + - [keys.reviewTranslation](#keysreviewtranslationrequest-config) - [keys.setTags](#keyssettagsrequest-config) - [keys.setMetadata](#keyssetmetadatarequest-config) - [keys.rename](#keysrenamerequest-config) - [keys.setPriority](#keyssetpriorityrequest-config) +- [Comments](#comments) + - [comments.list](#commentslistrequest-config) + - [comments.create](#commentscreaterequest-config) + - [comments.update](#commentsupdaterequest-config) + - [comments.delete](#commentsdeleterequest-config) - [Suggestions](#suggestions) - [suggestions.tm](#suggestionstmrequest-config) - [suggestions.mt](#suggestionsmtrequest-config) @@ -35,6 +52,41 @@ - [export.json](#exportjsonrequest-config) - [Formats](#formats) - [formats.list](#formatslistconfig) +- [Languages](#languages) + - [languages.add](#languagesaddrequest-config) + - [languages.hide](#languageshiderequest-config) + - [languages.enable](#languagesenablerequest-config) + - [languages.disable](#languagesdisablerequest-config) + - [languages.delete](#languagesdeleterequest-config) + - [languages.copy](#languagescopyrequest-config) + - [languages.replace](#languagesreplacerequest-config) + - [languages.setFallback](#languagessetfallbackrequest-config) + - [languages.listKeys](#languageslistkeysrequest-config) + - [languages.listKeysPage](#languageslistkeyspagerequest-config) + - [languages.listPlurals](#languageslistpluralsrequest-config) +- [Styleguides](#styleguides) + - [styleguides.list](#styleguideslistrequest-config) +- [CDN](#cdn) + - [cdn.list](#cdnlistrequest-config) +- [Branches](#branches) + - [branches.list](#brancheslistrequest-config) + - [branches.create](#branchescreaterequest-config) + - [branches.rename](#branchesrenamerequest-config) + - [branches.delete](#branchesdeleterequest-config) + - [branches.setMain](#branchessetmainrequest-config) + - [branches.separate](#branchesseparaterequest-config) + - [branches.analyzeMerge](#branchesanalyzemergerequest-config) + - [branches.merge](#branchesmergerequest-config) + - [branches.getOperation](#branchesgetoperationrequest-config) +- [Links](#links) + - [links.list](#linkslistrequest-config) + - [links.listPage](#linkslistpagerequest-config) + - [links.create](#linkscreaterequest-config) + - [links.delete](#linksdeleterequest-config) +- [Segmentation](#segmentation) + - [segmentation.getParent](#segmentationgetparentrequest-config) +- [Tags](#tags) + - [tags.list](#tagslistrequest-config) - [Screenshots](#screenshots) - [screenshots.list](#screenshotslistrequest-config) - [screenshots.listTags](#screenshotslisttagsrequest-config) @@ -46,12 +98,13 @@ - [glossary.list](#glossarylistrequest-config) - [glossary.find](#glossaryfindrequest-config) - [glossary.create](#glossarycreaterequest-config) + - [glossary.createMany](#glossarycreatemanyrequest-config) - [glossary.update](#glossaryupdaterequest-config) - [glossary.delete](#glossarydeleterequest-config) - [Webhooks](#webhooks) - [webhooks.list](#webhookslistrequest-config) - [webhooks.update](#webhooksupdaterequest-config) - - [webhooks.getSecret](#webhooksgetSecretrequest-config) + - [webhooks.getSecret](#webhooksgetsecretrequest-config) ## Setup @@ -195,6 +248,216 @@ const project = await api.projects.first({ }); ``` +### projects.create(request[, config]) + +Create a [project](../src/types/project.ts) in the organization of the token. Needs an organization +token. + +Rejected when the organization already has 50 projects, the name is blank or longer than 64 +characters, the description is longer than 1000 characters, the source language is unknown, or the +slug is invalid or already taken. Without `slug`, one is generated from the name. + +See: [Localazy API Docs](https://localazy.com/docs/api/projects#create-project) + +| Arguments | Type | +| ----------------- | ---------------------------------------------------------------- | +| request | [`ProjectCreateRequest`](../src/types/project-create-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| --------------------------------------------------------------------------- | +| [`Promise`](../src/types/project-create-response.ts) | + +```javascript +const { projectId } = await api.projects.create({ + name: 'My Application', + sourceLanguage: 'en', // default 'en' + type: 'public', // default 'restricted' + tone: 'informal', // default 'not_specified' +}); +``` + +## Organizations + +The organization endpoints need an organization token. `organization` is the organization's ID or +slug; a project's organization ID is `Project.orgId`. + +Quota and credits belong to the billing (top-level) organization. When `organization` is a team, the +usage and credit methods return the parent's data, and `organizationId` in the response names it. + +Credit amounts are decimal strings, not numbers; parse them with a decimal type to keep the +precision. The credit methods take a period: `from` is inclusive, `to` exclusive, each an ISO 8601 +date (`2026-11-01`, midnight UTC), date-time, or `Date`. `from` defaults to `to` minus 30 days, and +`to` defaults to (and is capped at) now minus 60 seconds. A period may be at most 366 days long. The +response gives the period the server used: for an incremental sync, pass its `to` as the next `from`. + +### organizations.getUsage(request[, config]) + +Get the source key quota usage and the credit balance of an organization. `keys.remaining` is not +clamped: it goes negative when the organization is over its quota. + +See: [Localazy API Docs](https://localazy.com/docs/api/organization-usage#get-usage) + +| Arguments | Type | +| ----------------- | ------------------------------------------------------------------------ | +| request | [`OrganizationUsageRequest`](../src/types/organization-usage-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ------------------------------------------------------------------ | +| [`Promise`](../src/types/organization-usage.ts) | + +```javascript +const { keys, credits } = await api.organizations.getUsage({ + organization: 'organization-id', // or slug +}); +``` + +### organizations.search(request[, config]) + +Full-text search in the keys, comments and translations of all projects of an organization. One key +can give several results: one for its name, one for its comment and one per matching language. + +Needs organization search in the plan, and a top-level organization; otherwise the call fails with +`search_not_available`. Returns at most 2000 results with no paging; narrow the search with a longer +`term` or the filters. Projects the token's user can't read give no results and no error. Changes +show in the results up to about an hour after the project is published. + +See: [Localazy API Docs](https://localazy.com/docs/api/organization-search#search) + +| Arguments | Type | +| ----------------- | -------------------------------------------------------------------------- | +| request | [`OrganizationSearchRequest`](../src/types/organization-search-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ------------------------------------------------------------------------------------- | +| [`Promise`](../src/types/organization-search-response.ts) | + +```javascript +const { results, projects } = await api.organizations.search({ + organization: 'organization-id', + term: 'cart', + projects: ['project-id'], // or Project objects; optional + match: ['key', 'translation'], // optional, all kinds by default + langs: ['de', 'cs'], // optional, filters translation matches only +}); +``` + +### organizations.getCreditSummary(request[, config]) + +Get the credit consumption of an organization in a period, the credits topped up in it and the +current balance, optionally grouped. `spent` excludes `system` costs (trial credit reclaim, negative +balance cover), which are reported as `adjusted`; the balance change in the period is +`toppedUp - spent - adjusted`. + +`groupBy` defaults to `['day']`; an empty list gives the totals only. Use `day` or `month`, not +both. Groups have no paging. + +See: [Localazy API Docs](https://localazy.com/docs/api/organization-credits#get-credit-summary) + +| Arguments | Type | +| ----------------- | ---------------------------------------------------------------- | +| request | [`CreditSummaryRequest`](../src/types/credit-summary-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| --------------------------------------------------------------------------- | +| [`Promise`](../src/types/credit-summary-response.ts) | + +```javascript +const { spent, groups } = await api.organizations.getCreditSummary({ + organization: 'organization-id', + from: '2026-11-01', + to: '2026-12-01', + groupBy: ['day', 'category'], +}); +``` + +### organizations.listCreditTransactions(request[, config]) + +List all credit costs of an organization in a period, one row per charge, in time order. Every +machine or AI translation of a key into one language is one row, so a long period can hold a very +large number of rows; this method fetches every page. + +See: [Localazy API Docs](https://localazy.com/docs/api/organization-credits#list-credit-transactions) + +| Arguments | Type | +| ----------------- | ----------------------------------------------------------------------------------- | +| request | [`CreditTransactionsListRequest`](../src/types/credit-transactions-list-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| -------------------------------------------------------------------- | +| [`Promise`](../src/types/credit-transactions.ts) | + +```javascript +const { to, transactions } = await api.organizations.listCreditTransactions({ + organization: 'organization-id', + from: lastSync, // the `to` of the previous sync +}); +``` + +### organizations.listCreditTransactionsPage(request[, config]) + +List credit costs of an organization in a period. Result is paginated: `limit` sets the page size (1 +to 10000, default 1000). Request the next page with `next` and the same `to` as the first page; when +`to` was omitted, pass the `to` of the first response, since the default moves with the clock. + +See: [Localazy API Docs](https://localazy.com/docs/api/organization-credits#list-credit-transactions) + +| Arguments | Type | +| ----------------- | ----------------------------------------------------------------------------------- | +| request | [`CreditTransactionsListRequest`](../src/types/credit-transactions-list-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| --------------------------------------------------------------------------------------- | +| [`Promise`](../src/types/credit-transactions-paginated.ts) | + +```javascript +const first = await api.organizations.listCreditTransactionsPage({ + organization: 'organization-id', + from: '2026-11-01', +}); +const transactions = [...first.transactions]; +let page = first; + +while (page.next) { + page = await api.organizations.listCreditTransactionsPage({ + organization: 'organization-id', + to: first.to, + next: page.next, + }); + transactions.push(...page.transactions); +} +``` + +### organizations.listCreditTopups(request[, config]) + +List the credits added to an organization in a period, in time order, with no paging. `type` is +`plan` (refill of the plan allowance; `amount` is what the refill added and can be 0 or negative), +`extra` (purchase, bonus) or `balance_cover` (cover of a negative balance, booked together with an +equal `adjusted` cost). + +See: [Localazy API Docs](https://localazy.com/docs/api/organization-credits#list-credit-topups) + +| Arguments | Type | +| ----------------- | ----------------------------------------------------------------------- | +| request | [`CreditTopupsListRequest`](../src/types/credit-topups-list-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ------------------------------------------------------------------------- | +| [`Promise`](../src/types/credit-topups-response.ts) | + +```javascript +const { topups } = await api.organizations.listCreditTopups({ + organization: 'organization-id', + from: '2026-10-01', +}); +``` + ## Files ### files.list(request[, config]) @@ -323,6 +586,34 @@ const blob = await api.files.getContents({ }); ``` +### files.listPublished(request[, config]) + +List when the project's current content (`latest`, always first, tag ID `_e0`) and each release tag +were last published; `publishedAt` is `null` for a tag never published. Use it to check cheaply for new +content: keep `publishedAt` and download only when it changed. It changes on every publish, even when +the files didn't, and a publish can come up to 5 minutes after a change. + +See: [Localazy API Docs](https://localazy.com/docs/api/files#list-publish-times) + +| Arguments | Type | +| ----------------- | ---------------------------------------------------------------- | +| request | [`PublishedListRequest`](../src/types/published-list-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | Type | +| ---------------------------- | :---------------------------------------------------- | +| `Promise` | [`PublishedRecord`](../src/types/published-record.ts) | + +```javascript +const [latest] = await api.files.listPublished({ + project: 'project-id', // or Project object +}); + +if (latest.publishedAt !== previousPublishedAt) { + // download the files +} +``` + ## Keys ### keys.update(request[, config]) @@ -440,6 +731,106 @@ await api.keys.submitTranslation({ }); ``` +### keys.getDetails(request[, config]) + +Get everything Localazy knows about [keys](../src/types/key.ts) in one language: file, tags, +priority, developer comment and context note, source text, current translation with its state, the +version waiting for review, and the comments in that language. + +Pass 1 to 100 keys per call; a larger set is rejected rather than truncated. Keys the project lacks +(`not_found`) or that are segmented as a whole (`segmented_key`) are reported in `errors` and do not +fail the request. Use `translation.review.versionId` to address a version. + +See: [Localazy API Docs](https://localazy.com/docs/api/source-keys#get-key-details) + +| Arguments | Type | +| ----------------- | ---------------------------------------------------------- | +| request | [`KeyDetailsRequest`](../src/types/key-details-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| --------------------------------------------------------------------- | +| [`Promise`](../src/types/key-details-response.ts) | + +```javascript +const { keys, errors } = await api.keys.getDetails({ + project: 'project-id', // or Project object + keys: ['key-id-1', 'key-id-2'], // or Key objects + lang: 'cs', +}); +``` + +### keys.editSource(request[, config]) + +Write a new source text for a [key](../src/types/key.ts). `value` follows the same rules as in +`keys.submitTranslation()`, including the `@`-prefixed plural form. + +The text becomes current immediately only for callers allowed to auto-approve their own versions +(manager, owner); for others it waits for a review. When it becomes current and differs, the key's +translations get the `sourceChanged` state; pass `sourceChanged: false` for a change such as a typo +fix. Segmented keys and their segments are rejected. + +**Check `result` on the response.** `false` with a `message` means the project was momentarily +locked or the value was not stored; it does not reject the promise. + +See: [Localazy API Docs](https://localazy.com/docs/api/source-keys#edit-source-text) + +| Arguments | Type | +| ----------------- | ----------------------------------------------------------------- | +| request | [`KeyEditSourceRequest`](../src/types/key-edit-source-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ----------------------------------------------------------------------------------- | +| [`Promise`](../src/types/submit-translation-response.ts) | + +```javascript +const { result, versionId } = await api.keys.editSource({ + project: 'project-id', // or Project object + key: 'key-id', // or Key object + value: 'Save changes', + sourceChanged: false, +}); +``` + +### keys.reviewTranslation(request[, config]) + +Approve or reject one version of a [key](../src/types/key.ts) in one language, which may be the +source language. + +`approve` makes the version current and rejects the other versions waiting for review; approving the +already-current version confirms it. `reject` rejects the version; the current version cannot be +rejected (`current_version_cannot_be_rejected`). Get `versionId` from +`translation.review.versionId` of `keys.getDetails()`. + +**Check `result` on the response.** `false` means the project was momentarily locked; retry. + +See: [Localazy API Docs](https://localazy.com/docs/api/source-keys#review-a-translation) + +| Arguments | Type | +| ----------------- | ------------------------------------------------------------------------------- | +| request | [`KeyReviewTranslationRequest`](../src/types/key-review-translation-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ----------------------------------------------------------------------------------- | +| [`Promise`](../src/types/review-translation-response.ts) | + +```javascript +const [detail] = (await api.keys.getDetails({ project, keys: ['key-id'], lang: 'cs' })).keys; +const versionId = detail?.translation.review?.versionId; + +if (versionId) { + await api.keys.reviewTranslation({ + project: 'project-id', // or Project object + key: 'key-id', // or Key object + lang: 'cs', + versionId, + action: 'approve', + }); +} +``` + ### keys.setTags(request[, config]) Add and/or remove tags on [keys](../src/types/key.ts). @@ -583,6 +974,113 @@ const { result } = await api.keys.setPriority({ }); ``` +## Comments + +### comments.list(request[, config]) + +List the discussion of a [key](../src/types/key.ts) in one language, newest first. Deleted comments +are left out, and reading does not mark comments as read. `keys.getDetails()` returns the same +comments for up to 100 keys at once. + +See: [Localazy API Docs](https://localazy.com/docs/api/source-keys#list-comments-of-a-key) + +| Arguments | Type | +| ----------------- | ------------------------------------------------------------ | +| request | [`CommentListRequest`](../src/types/comment-list-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ------------------------------------------------------ | +| [`Promise`](../src/types/key-comment.ts) | + +```javascript +const comments = await api.comments.list({ + project: 'project-id', // or Project object + key: 'key-id', // or Key object + lang: 'cs', +}); +``` + +### comments.create(request[, config]) + +Add a comment to the discussion of a [key](../src/types/key.ts) in one language, authored by the +token's user. It behaves like a comment written in Localazy: unread for the other users, +notifications and e-mails are sent, and the `comment_added` webhook fires. `text` must have 1 to 2000 +characters and not be only white space. + +See: [Localazy API Docs](https://localazy.com/docs/api/source-keys#add-a-comment) + +| Arguments | Type | +| ----------------- | ---------------------------------------------------------------- | +| request | [`CommentCreateRequest`](../src/types/comment-create-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | Type | +| ----------------- | :---------- | +| `Promise` | Comment id. | + +```javascript +const id = await api.comments.create({ + project: 'project-id', // or Project object + key: 'key-id', // or Key object + lang: 'cs', + text: "Is 'kus' better here?", +}); +``` + +### comments.update(request[, config]) + +Replace the text of a comment. Only its author may: a comment of another user fails with `401`, even +for a manager or owner. A comment that is deleted or not on this key and language fails with `404`. +No notification or webhook is sent. + +See: [Localazy API Docs](https://localazy.com/docs/api/source-keys#edit-a-comment) + +| Arguments | Type | +| ----------------- | ---------------------------------------------------------------- | +| request | [`CommentUpdateRequest`](../src/types/comment-update-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| --------------- | +| `Promise` | + +```javascript +await api.comments.update({ + project: 'project-id', // or Project object + key: 'key-id', // or Key object + lang: 'cs', + comment: 'comment-id', // or KeyComment object + text: "Is 'kusy' better here?", +}); +``` + +### comments.delete(request[, config]) + +Delete a comment. Only its author may: a comment of another user fails with `401`, even for a +manager or owner. A comment that is already deleted or not on this key and language fails with +`404`. + +See: [Localazy API Docs](https://localazy.com/docs/api/source-keys#delete-a-comment) + +| Arguments | Type | +| ----------------- | ---------------------------------------------------------------- | +| request | [`CommentDeleteRequest`](../src/types/comment-delete-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| --------------- | +| `Promise` | + +```javascript +await api.comments.delete({ + project: 'project-id', // or Project object + key: 'key-id', // or Key object + lang: 'cs', + comment: 'comment-id', // or KeyComment object +}); +``` + ## Suggestions Per-key translation suggestions. Every response shares the same envelope: @@ -883,86 +1381,872 @@ See: [Localazy API Docs](https://localazy.com/docs/api/import#list-available-fil const formats = await api.formats.list(); ``` -## Screenshots +## Languages -### screenshots.list(request[, config]) +Languages are passed as a locale code (`pt_BR`; `pt-BR` works too) or Localazy's numeric language id +(`112`), except in `languages.listKeys`, which takes locale codes only. An unknown region falls back +to the plain language (`pt-XX` resolves to `pt`); every response +echoes the resolved `code`. The project's source language can't be hidden, enabled, disabled, deleted, +copied onto or replaced. Read the languages back with `projects.list({ languages: true })`, adding +`hidden_languages: true` to also list hidden ones. -List all [screenshots](../src/types/screenshot.ts) in the project. +### languages.add(request[, config]) -See: [Localazy API Docs](https://localazy.com/docs/api/screenshot-management#list-screenshots) +Add target languages to the project. They are added empty: nothing is translated and no publish is +triggered. A hidden language comes back with its previous translations, published. -| Arguments | Type | -| ----------------- | -------------------------------------------------------------------- | -| request | [`ScreenshotsListRequest`](../src/types/screenshots-list-request.ts) | -| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | +Up to 100 languages per call. One that can't be resolved rejects the whole request; after that the +languages are added one by one, so a failure part-way can leave the earlier ones added. Repeating the +call is safe. -| Returns | Type | -| ----------------------- | :----------------------------------------- | -| `Promise` | [`Screenshot`](../src/types/screenshot.ts) | +See: [Localazy API Docs](https://localazy.com/docs/api/project-languages#add-languages) + +| Arguments | Type | +| ----------------- | ------------------------------------------------------------------ | +| request | [`LanguagesBatchRequest`](../src/types/languages-batch-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ----------------------------------------------------------------------- | +| [`Promise`](../src/types/language-add-response.ts) | + +Each language gets its `state`: `created`, `restored` (it was hidden) or `unchanged` (already listed). ```javascript -const screenshots = await api.screenshots.list({ +import { Locales } from '@localazy/api-client'; + +const { languages } = await api.languages.add({ project: 'project-id', // or Project object + languages: [Locales.BRAZILIAN_PORTUGUESE, 'cs'], }); ``` -### screenshots.listTags(request[, config]) +### languages.hide(request[, config]) -List all [screenshots tags](../src/types/screenshot-tag.ts) in the project. +Hide languages: they leave the project (not listed, translated or published) but keep their +translations, which come back when the language is added again. To remove the translations too, use +[`languages.delete`](#languagesdeleterequest-config). -See: [Localazy API Docs](https://localazy.com/docs/api/screenshot-management#list-screenshots-tags) +Up to 100 languages per call, all of which must be in the project; otherwise nothing changes. -| Arguments | Type | -| ----------------- | ----------------------------------------------------------------------------- | -| request | [`ScreenshotsListTagsRequest`](../src/types/screenshots-list-tags-request.ts) | -| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | +See: [Localazy API Docs](https://localazy.com/docs/api/project-languages#hide-languages) -| Returns | Type | -| -------------------------- | :------------------------------------------------ | -| `Promise` | [`ScreenshotTag`](../src/types/screenshot-tag.ts) | +| Arguments | Type | +| ----------------- | ------------------------------------------------------------------ | +| request | [`LanguagesBatchRequest`](../src/types/languages-batch-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ------------------------------------------------------------------------- | +| [`Promise`](../src/types/language-hide-response.ts) | + +Each language gets its `state`: `hidden`, or `unchanged` when it already was. ```javascript -const tags = await api.screenshots.listTags({ +await api.languages.hide({ project: 'project-id', // or Project object + languages: ['cs'], }); ``` -### screenshots.create(request[, config]) +### languages.enable(request[, config]) -Create [screenshot](../src/types/screenshot.ts). +Include languages when the project is published (the `published` flag of +[`Language`](../src/types/language.ts)). This doesn't change whether a language is in the project. +Adding a hidden language back also enables it. -See: [Localazy API Docs](https://localazy.com/docs/api/screenshot-management#create-a-new-screenshot) +Up to 100 languages per call, all of which must be in the project; otherwise nothing changes. -| Arguments | Type | -| ----------------- | ---------------------------------------------------------------------- | -| request | [`ScreenshotCreateRequest`](../src/types/screenshot-create-request.ts) | -| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | +See: [Localazy API Docs](https://localazy.com/docs/api/project-languages#enable-and-disable-publishing) -| Returns | Type | -| ----------------- | :------------- | -| `Promise` | Screenshot id. | +| Arguments | Type | +| ----------------- | ------------------------------------------------------------------ | +| request | [`LanguagesBatchRequest`](../src/types/languages-batch-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ----------------------------------------------------------------------------- | +| [`Promise`](../src/types/language-enable-response.ts) | + +Each language gets its `state`: `enabled`, or `unchanged` when it already was. ```javascript -const id = await api.screenshots.create({ +await api.languages.enable({ project: 'project-id', // or Project object - encodedData: 'data:image/jpg;base64,...', + languages: ['cs'], }); ``` -### screenshots.updateImageData(request[, config]) +### languages.disable(request[, config]) -Update the image data of [screenshot](../src/types/screenshot.ts). +Leave languages out when the project is published. They stay in the project and translatable, but +their "new strings to translate" and "new translations to review" e-mails stop. -See: [Localazy API Docs](https://localazy.com/docs/api/screenshot-management#update-the-image-of-an-existing-screenshot) +Up to 100 languages per call, all of which must be in the project; otherwise nothing changes. -| Arguments | Type | -| ----------------- | ------------------------------------------------------------------------------------------ | -| request | [`ScreenshotUpdateImageDataRequest`](../src/types/screenshot-update-image-data-request.ts) | -| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | +See: [Localazy API Docs](https://localazy.com/docs/api/project-languages#enable-and-disable-publishing) -| Returns | -| --------------- | -| `Promise` | +| Arguments | Type | +| ----------------- | ------------------------------------------------------------------ | +| request | [`LanguagesBatchRequest`](../src/types/languages-batch-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ------------------------------------------------------------------------------- | +| [`Promise`](../src/types/language-disable-response.ts) | + +Each language gets its `state`: `disabled`, or `unchanged` when it already was. + +```javascript +await api.languages.disable({ + project: 'project-id', // or Project object + languages: ['cs'], +}); +``` + +### languages.delete(request[, config]) + +Permanently delete a language **and all of its translations**, comments and style guide. There is no +undo. To keep the translations, use [`languages.hide`](#languageshiderequest-config). + +It runs while the request is open, so expect a slow response on a large project. It fails with `409` +while another delete, copy or replace runs in the project, or while another language falls back to +this one. + +See: [Localazy API Docs](https://localazy.com/docs/api/project-languages#delete-a-language) + +| Arguments | Type | +| ----------------- | ------------------------------------------------------------------ | +| request | [`LanguageDeleteRequest`](../src/types/language-delete-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ---------------------------------------------------------- | +| [`Promise`](../src/types/boolean-result.ts) | + +```javascript +await api.languages.delete({ + project: 'project-id', // or Project object + lang: 'cs', +}); +``` + +### languages.copy(request[, config]) + +Add a language pre-filled with a snapshot of the translations of another one, for example `pt_BR` into +`pt_PT`. The copy is always published and independent of the original afterwards. + +`from` must be in the project and not hidden; `to` must not be in the project, unless it is hidden: +then its kept translations are destroyed first, and stay destroyed if the copy then fails (it can fail +with `500` on very large projects). It fails with `409` while another delete, copy or replace runs in +the project. + +See: [Localazy API Docs](https://localazy.com/docs/api/project-languages#copy-a-language) + +| Arguments | Type | +| ----------------- | -------------------------------------------------------------- | +| request | [`LanguageCopyRequest`](../src/types/language-copy-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ------------------------------------------------------------------------- | +| [`Promise`](../src/types/language-copy-response.ts) | + +```javascript +const { language } = await api.languages.copy({ + project: 'project-id', // or Project object + from: 'pt_BR', + to: 'pt_PT', +}); +``` + +### languages.replace(request[, config]) + +Move all translations of `language` to `replaceWith`, for example `de` to `de_AT`. `language` stops +existing; `replaceWith` takes over its state, publish flag and fallbacks included. + +`language` must be in the project and not hidden; `replaceWith` must not be in the project, unless it +is hidden: then its kept translations are destroyed first. It fails with `409` while another delete, +copy or replace runs in the project, or when the move would make a cycle of fallback languages. + +See: [Localazy API Docs](https://localazy.com/docs/api/project-languages#replace-a-language) + +| Arguments | Type | +| ----------------- | -------------------------------------------------------------------- | +| request | [`LanguageReplaceRequest`](../src/types/language-replace-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ---------------------------------------------------------- | +| [`Promise`](../src/types/boolean-result.ts) | + +```javascript +await api.languages.replace({ + project: 'project-id', // or Project object + language: 'de', + replaceWith: 'de_AT', +}); +``` + +### languages.setFallback(request[, config]) + +Set the fallback language of a language, or remove it with `fallback: null`. Output files take the text +of a key untranslated in `lang` from its fallback; key listings and the editor never do. Fallbacks +chain, and each chain ends at the source language. A change publishes the project again. + +The fallback must be a language of the project (hidden or unpublished ones too), not `lang` itself, and +must not make a cycle. Setting one fails with `unpaid` when the organization lacks the feature; +removing one always works. + +See: [Localazy API Docs](https://localazy.com/docs/api/project-languages#set-a-fallback-language) + +| Arguments | Type | +| ----------------- | ----------------------------------------------------------------------------- | +| request | [`LanguageSetFallbackRequest`](../src/types/language-set-fallback-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ---------------------------------------------------------- | +| [`Promise`](../src/types/boolean-result.ts) | + +```javascript +await api.languages.setFallback({ + project: 'project-id', // or Project object + lang: 'pt_PT', + fallback: 'pt_BR', // or null to remove it +}); +``` + +### languages.listKeys(request[, config]) + +List all [keys](../src/types/language-key.ts) of **all files** of the project with their values in one +language. It takes the same options as `files.listKeys`, plus `unapproved` and `resolve_duplicities`; +each key also has the ID of its `file`. + +See: [Localazy API Docs](https://localazy.com/docs/api/files#list-keys-of-all-files) + +| Arguments | Type | +| ----------------- | ----------------------------------------------------------------------- | +| request | [`LanguageListKeysRequest`](../src/types/language-list-keys-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | Type | +| ------------------------ | :-------------------------------------------- | +| `Promise` | [`LanguageKey`](../src/types/language-key.ts) | + +```javascript +import { Locales } from '@localazy/api-client'; + +const keys = await api.languages.listKeys({ + project: 'project-id', // or Project object + lang: Locales.CZECH, +}); +``` + +### languages.listKeysPage(request[, config]) + +List one page of [keys](../src/types/language-key.ts) of all files of the project with their values in +one language. `files` describes, by file ID, the files of the keys on the page; one file can continue +on the next page. + +See: [Localazy API Docs](https://localazy.com/docs/api/files#list-keys-of-all-files) + +| Arguments | Type | +| ----------------- | ----------------------------------------------------------------------- | +| request | [`LanguageListKeysRequest`](../src/types/language-list-keys-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| --------------------------------------------------------------------------- | +| [`Promise`](../src/types/language-keys-paginated.ts) | + +```javascript +import { Locales } from '@localazy/api-client'; + +const keys = []; +let next; + +do { + const page = await api.languages.listKeysPage({ + project: 'project-id', // or Project object + lang: Locales.CZECH, + limit: 10000, + next, + }); + keys.push(...page.keys); + next = page.next; +} while (next); +``` + +### languages.listPlurals(request[, config]) + +Get the plural rules the project defines in place of the standard ones, and the plural forms each +project language uses as a result: which forms a plural value needs in each language. The source +language is first. + +See: [Localazy API Docs](https://localazy.com/docs/api/project-styleguides-plurals#get-plurals) + +| Arguments | Type | +| ----------------- | ------------------------------------------------------------ | +| request | [`PluralsListRequest`](../src/types/plurals-list-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| --------------------------------------------- | +| [`Promise`](../src/types/plurals.ts) | + +```javascript +const { languages } = await api.languages.listPlurals({ + project: 'project-id', // or Project object +}); +const czechForms = languages.find(({ lang }) => lang === 'cs')?.forms; // ['one', 'few', 'other'] +``` + +## Styleguides + +### styleguides.list(request[, config]) + +Get the project's style guides: `general` for all languages (absent when unset) and `languages`, one per +language code. Empty or blank style guides count as unset. This API cannot change style guides. + +See: [Localazy API Docs](https://localazy.com/docs/api/project-styleguides-plurals#get-style-guides) + +| Arguments | Type | +| ----------------- | -------------------------------------------------------------------- | +| request | [`StyleguidesListRequest`](../src/types/styleguides-list-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ----------------------------------------------------- | +| [`Promise`](../src/types/styleguides.ts) | + +```javascript +const { general, languages } = await api.styleguides.list({ + project: 'project-id', // or Project object +}); +``` + +## CDN + +### cdn.list(request[, config]) + +List the URLs of the CDN metadata files (`.v2.json`) of `latest` and of each published release tag. +When the CDN is disabled for the project, `enabled` is `false` and the list is empty. + +See: [Localazy API Docs](https://localazy.com/docs/api/cdn#list-metadata-files) + +| Arguments | Type | +| ----------------- | ---------------------------------------------------- | +| request | [`CdnListRequest`](../src/types/cdn-list-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ------------------------------------------------------ | +| [`Promise`](../src/types/cdn-metadata.ts) | + +```javascript +const { enabled, metadataUrls } = await api.cdn.list({ + project: 'project-id', // or Project object +}); +``` + +## Branches + +A branch is a copy of a project that is changed and translated independently and then merged into +another branch. Each branch is a project of its own, with its own `projectId`, tokens and members; +the first one is the main branch, named `main`. In these methods `project` can be any branch of the +project, and the other branches are addressed by name (or by a [`Branch`](../src/types/branch.ts) +object). To read or change the content of a branch, pass its `projectId` as `project` to the other +namespaces. + +Branching is a feature of the organization's plan; without it every method rejects with `400` +(`unpaid`). + +### branches.list(request[, config]) + +List all [branches](../src/types/branch.ts) of the project: `main` first, then the others by name. +The result is the same whichever branch `project` addresses. + +See: [Localazy API Docs](https://localazy.com/docs/api/branching#list-branches) + +| Arguments | Type | +| ----------------- | ---------------------------------------------------------- | +| request | [`BranchListRequest`](../src/types/branch-list-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | Type | +| ------------------- | :--------------------------------- | +| `Promise` | [`Branch`](../src/types/branch.ts) | + +```javascript +const branches = await api.branches.list({ + project: 'project-id', // or Project object +}); +``` + +### branches.create(request[, config]) + +Create a branch as a full copy of `source` (default: the branch `project` addresses), or with +`empty: true` a copy of its settings only. `name` has 2 to 32 characters from `a-z`, `0-9`, `_`, `-` +and `.`, and cannot start with `_` or `-`; `main` is reserved. A project can have 20 branches, and a +project that uses segmentation cannot have any. + +The copy runs in the background and resolves with an operation ID. Poll +[`branches.getOperation()`](#branchesgetoperationrequest-config) until the status is `done` (the +branch then appears in `branches.list()`) or `error`. + +See: [Localazy API Docs](https://localazy.com/docs/api/branching#create-a-branch) + +| Arguments | Type | +| ----------------- | -------------------------------------------------------------- | +| request | [`BranchCreateRequest`](../src/types/branch-create-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | Description | +| ----------------- | :------------ | +| `Promise` | Operation ID. | + +```javascript +const operation = await api.branches.create({ + project: 'project-id', // or Project object + name: 'release-2', + source: 'main', // optional, or Branch object +}); +``` + +### branches.rename(request[, config]) + +Rename a branch. Its `projectId` stays; its slug ends with `!`. The main branch cannot be +renamed; use `branches.setMain()` instead. + +See: [Localazy API Docs](https://localazy.com/docs/api/branching#rename-a-branch) + +| Arguments | Type | +| ----------------- | -------------------------------------------------------------- | +| request | [`BranchRenameRequest`](../src/types/branch-rename-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| --------------- | +| `Promise` | + +```javascript +await api.branches.rename({ + project: 'project-id', // or Project object + branch: 'release-2', // or Branch object + name: 'release-3', +}); +``` + +### branches.delete(request[, config]) + +Delete a branch: its project is archived with all its content. Rejected for the main branch, a +branch that other branches were made from, the source of linked keys, a branch whose glossary or +translation memory other projects use, and while duplicity resolution runs for it. + +See: [Localazy API Docs](https://localazy.com/docs/api/branching#delete-a-branch) + +| Arguments | Type | +| ----------------- | -------------------------------------------------------------- | +| request | [`BranchDeleteRequest`](../src/types/branch-delete-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| --------------- | +| `Promise` | + +```javascript +await api.branches.delete({ + project: 'project-id', // or Project object + branch: 'release-2', // or Branch object +}); +``` + +### branches.setMain(request[, config]) + +Make `branch` the main branch. No content moves: `branch` takes the name `main` and the old main +slug, and the old main branch takes `name`. Every `projectId` stays, so a branch token keeps +addressing the same content although the name of its branch may change. + +See: [Localazy API Docs](https://localazy.com/docs/api/branching#set-the-main-branch) + +| Arguments | Type | +| ----------------- | ----------------------------------------------------------------- | +| request | [`BranchSetMainRequest`](../src/types/branch-set-main-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| --------------- | +| `Promise` | + +```javascript +await api.branches.setMain({ + project: 'project-id', // or Project object + branch: 'release-2', // or Branch object + name: 'legacy', // new name of the former main branch +}); +``` + +### branches.separate(request[, config]) + +Turn a branch into an independent project. It keeps its `projectId` and content, loses the +`!` slug suffix, disappears from `branches.list()` and can no longer be merged with the +project's branches. Branches made from it move to its own source. The main branch cannot be +separated. + +See: [Localazy API Docs](https://localazy.com/docs/api/branching#separate-a-branch) + +| Arguments | Type | +| ----------------- | ------------------------------------------------------------------ | +| request | [`BranchSeparateRequest`](../src/types/branch-separate-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| --------------- | +| `Promise` | + +```javascript +await api.branches.separate({ + project: 'project-id', // or Project object + branch: 'release-2', // or Branch object +}); +``` + +### branches.analyzeMerge(request[, config]) + +Report what `branches.merge()` with the same request would do, changing nothing. Keys are matched +by file and key name. A translation that differs between the branches is handled by `strategy` +(default `skip`; see [`BranchMergeStrategy`](../src/types/branch-merge-strategy.ts)); one the +strategy does not resolve is a conflict and is never merged. `details` adds the lists of conflicts +and/or failures, which have no length limit. + +The analysis is synchronous and reads every current translation of both branches, so it can take a +long time on a large project. It fails with `409` while another analysis or merge, including one +started in Localazy or the CLI, runs on the target branch, or on the source branch with the `target` +and `time-bidi` strategies. + +See: [Localazy API Docs](https://localazy.com/docs/api/branching#analyze-a-merge) + +| Arguments | Type | +| ----------------- | --------------------------------------------------------------------------- | +| request | [`BranchAnalyzeMergeRequest`](../src/types/branch-analyze-merge-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| ----------------------------------------------------------------------- | +| [`Promise`](../src/types/branch-merge-analysis.ts) | + +```javascript +const analysis = await api.branches.analyzeMerge({ + project: 'project-id', // or Project object + branch: 'release-2', // source branch, or Branch object + target: 'main', // or Branch object + strategy: 'reference', + details: ['conflicts'], +}); +``` + +### branches.merge(request[, config]) + +Merge `branch` into `target`. Takes the same request as `branches.analyzeMerge()` (without +`details`); run the analysis first, because a merge cannot be reverted and the `target` and +`time-bidi` strategies also write back to the source branch. + +The merge runs in the background and resolves with an operation ID. Poll +[`branches.getOperation()`](#branchesgetoperationrequest-config) until the status is `done` (with the +merge counts) or `error`. + +See: [Localazy API Docs](https://localazy.com/docs/api/branching#merge-branches) + +| Arguments | Type | +| ----------------- | ------------------------------------------------------------ | +| request | [`BranchMergeRequest`](../src/types/branch-merge-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | Description | +| ----------------- | :------------ | +| `Promise` | Operation ID. | + +```javascript +const operation = await api.branches.merge({ + project: 'project-id', // or Project object + branch: 'release-2', // source branch, or Branch object + target: 'main', // or Branch object + strategy: 'reference', +}); +``` + +### branches.getOperation(request[, config]) + +Get the status of an operation started by `branches.create()` or `branches.merge()`. Poll while +`status` is `scheduled` or `in_progress`; `done` and `error` are final. A merge that is `done` also +carries its counts. An ID that is unknown, older than 48 hours or started by another project +resolves with status `invalid_id`; only a malformed ID rejects. + +See: [Localazy API Docs](https://localazy.com/docs/api/branching#check-the-status-of-an-operation) + +| Arguments | Type | +| ----------------- | --------------------------------------------------------------------------- | +| request | [`BranchGetOperationRequest`](../src/types/branch-get-operation-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| --------------------------------------------------------------------------- | +| [`Promise`](../src/types/branch-operation-status.ts) | + +```javascript +const operation = await api.branches.merge({ project, branch: 'release-2', target: 'main' }); + +let status = await api.branches.getOperation({ project, operation }); +while (status.status === 'scheduled' || status.status === 'in_progress') { + await new Promise((resolve) => setTimeout(resolve, 2000)); + status = await api.branches.getOperation({ project, operation }); +} +``` + +## Links + +### links.list(request[, config]) + +List all [key links](../src/types/link.ts) in the project, following the `next` cursor until the last page. + +See: [Localazy API Docs](https://localazy.com/docs/api/duplicities#list-links) + +| Arguments | Type | +| ----------------- | ------------------------------------------------------ | +| request | [`LinkListRequest`](../src/types/link-list-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | Type | +| ----------------- | :----------------------------- | +| `Promise` | [`Link`](../src/types/link.ts) | + +```javascript +const links = await api.links.list({ + project: 'project-id', // or Project object +}); +``` + +### links.listPage(request[, config]) + +List [key links](../src/types/link.ts) in the project. Result is paginated. + +See: [Localazy API Docs](https://localazy.com/docs/api/duplicities#list-links) + +| Arguments | Type | +| ----------------- | ------------------------------------------------------ | +| request | [`LinkListRequest`](../src/types/link-list-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | Type | +| ------------------------- | :-------------------------------------------------- | +| `Promise` | [`LinksPaginated`](../src/types/links-paginated.ts) | + +```javascript +const links = []; +let pageResult = { links: [], next: '' }; + +do { + pageResult = await api.links.listPage({ + project: 'project-id', // or Project object + next: pageResult.next, + }); + links.push(...pageResult.links); +} while (pageResult.next); +``` + +### links.create(request[, config]) + +Link a [key](../src/types/key.ts) to a target key in the same project or another one. The linked key +becomes hidden and publishes the target's content while the link exists. + +Links are honoured during publishing only on the Business plan and above; on other plans they are +stored but ignored. A segmented key as a whole cannot be linked on either side (its individual +segments can), and a key or target that does not exist rejects with `unauthorized`. + +See: [Localazy API Docs](https://localazy.com/docs/api/duplicities#create-links) + +| Arguments | Type | +| ----------------- | ---------------------------------------------------------- | +| request | [`LinkCreateRequest`](../src/types/link-create-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| --------------- | +| `Promise` | + +```javascript +await api.links.create({ + project: 'project-id', // or Project object + key: 'key-id', // or Key object; the key that becomes linked + linkedKey: 'target-key-id', // or Key object + linkedProject: 'target-project', // optional, defaults to `project` +}); +``` + +### links.delete(request[, config]) + +Remove the link of a [key](../src/types/key.ts). A segmented key as a whole is rejected. + +See: [Localazy API Docs](https://localazy.com/docs/api/duplicities#remove-links) + +| Arguments | Type | +| ----------------- | ---------------------------------------------------------- | +| request | [`LinkDeleteRequest`](../src/types/link-delete-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| --------------- | +| `Promise` | + +```javascript +await api.links.delete({ + project: 'project-id', // or Project object + key: 'key-id', // or Key object +}); +``` + +## Segmentation + +### segmentation.getParent(request[, config]) + +Get a text-segmentation [parent](../src/types/segmentation-parent.ts): the key a set of segments +reassembles into, with its segment ids and the whole text in `lang`. Use it to turn the `segParentId` +of a segment back into its key. + +`parent` accepts either the parent id (`segParentId`) or the parent handle (the id of a segmented key +in the default mode of `files.listKeys()`); a deprecated parent is addressable only by its parent id. +An unknown id, a parent of another project and a project without segmentation all reject with +`unauthorized`; a malformed ID rejects with `invalid_id`. `lang` must be a locale code; an unknown +one rejects with `unknown_lang`. + +| Arguments | Type | +| ----------------- | --------------------------------------------------------------------------------- | +| request | [`SegmentationGetParentRequest`](../src/types/segmentation-get-parent-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | Type | +| ----------------------------- | :---------------------------------------------------------- | +| `Promise` | [`SegmentationParent`](../src/types/segmentation-parent.ts) | + +`value` is absent for a deprecated parent, whose `segments` are empty. Each segment contributes its +translation when it has one and its source text otherwise, so a partly translated key comes back mixed. + +```javascript +import { Locales } from '@localazy/api-client'; + +const parent = await api.segmentation.getParent({ + project: 'project-id', // or Project object + parent: 'seg-parent-id', // or the parent handle / Key object + lang: Locales.BRAZILIAN_PORTUGUESE, +}); +``` + +## Tags + +### tags.list(request[, config]) + +List all [tags](../src/types/project-tag.ts) that keys of the project can have: the tags Localazy +defines for each project (`builtIn`) first, then the project's own. Not paginated. Screenshot tags are +separate, see `screenshots.listTags()`. + +See: [Localazy API Docs](https://localazy.com/docs/api/source-keys#list-tags-of-a-project) + +| Arguments | Type | +| ----------------- | ------------------------------------------------------------------- | +| request | [`ProjectTagListRequest`](../src/types/project-tag-list-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | Type | +| ----------------------- | :------------------------------------------ | +| `Promise` | [`ProjectTag`](../src/types/project-tag.ts) | + +```javascript +const tags = await api.tags.list({ + project: 'project-id', // or Project object +}); +``` + +## Screenshots + +### screenshots.list(request[, config]) + +List all [screenshots](../src/types/screenshot.ts) in the project. + +See: [Localazy API Docs](https://localazy.com/docs/api/screenshot-management#list-screenshots) + +| Arguments | Type | +| ----------------- | -------------------------------------------------------------------- | +| request | [`ScreenshotsListRequest`](../src/types/screenshots-list-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | Type | +| ----------------------- | :----------------------------------------- | +| `Promise` | [`Screenshot`](../src/types/screenshot.ts) | + +```javascript +const screenshots = await api.screenshots.list({ + project: 'project-id', // or Project object +}); +``` + +### screenshots.listTags(request[, config]) + +List all [screenshots tags](../src/types/screenshot-tag.ts) in the project. + +See: [Localazy API Docs](https://localazy.com/docs/api/screenshot-management#list-screenshots-tags) + +| Arguments | Type | +| ----------------- | ----------------------------------------------------------------------------- | +| request | [`ScreenshotsListTagsRequest`](../src/types/screenshots-list-tags-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | Type | +| -------------------------- | :------------------------------------------------ | +| `Promise` | [`ScreenshotTag`](../src/types/screenshot-tag.ts) | + +```javascript +const tags = await api.screenshots.listTags({ + project: 'project-id', // or Project object +}); +``` + +### screenshots.create(request[, config]) + +Create [screenshot](../src/types/screenshot.ts). + +See: [Localazy API Docs](https://localazy.com/docs/api/screenshot-management#create-a-new-screenshot) + +| Arguments | Type | +| ----------------- | ---------------------------------------------------------------------- | +| request | [`ScreenshotCreateRequest`](../src/types/screenshot-create-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | Type | +| ----------------- | :------------- | +| `Promise` | Screenshot id. | + +```javascript +const id = await api.screenshots.create({ + project: 'project-id', // or Project object + encodedData: 'data:image/jpg;base64,...', +}); +``` + +### screenshots.updateImageData(request[, config]) + +Update the image data of [screenshot](../src/types/screenshot.ts). + +See: [Localazy API Docs](https://localazy.com/docs/api/screenshot-management#update-the-image-of-an-existing-screenshot) + +| Arguments | Type | +| ----------------- | ------------------------------------------------------------------------------------------ | +| request | [`ScreenshotUpdateImageDataRequest`](../src/types/screenshot-update-image-data-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| --------------- | +| `Promise` | ```javascript await api.screenshots.updateImageData({ @@ -1090,6 +2374,44 @@ const id = await api.glossary.create({ }); ``` +### glossary.createMany(request[, config]) + +Create several [glossary records](../src/types/glossary-record.ts) in one request. + +Unlike `glossary.create()`, a duplicate of an existing term is merged into it instead of being +refused: its translations and the options it sets are applied to that term. Terms are duplicates +when their trimmed source-language text and `exactMatch` match; case matters only when both are +case-sensitive. An option left out keeps the existing value on merge and takes the default on a new +term. The response lists each item, by its source-language text, as `created`, `updated` or +`skipped`. The whole batch is rejected if the created terms would exceed the 1000-term project +limit. + +| Arguments | Type | +| ----------------- | --------------------------------------------------------------------------- | +| request | [`GlossaryCreateManyRequest`](../src/types/glossary-create-many-request.ts) | +| config `optional` | [`RequestConfig`](../src/types/request-config.ts) | + +| Returns | +| -------------------------------------------------------------------------------------- | +| [`Promise`](../src/types/glossary-create-many-response.ts) | + +```javascript +import { Locales } from '@localazy/api-client'; + +const { created, updated, skipped } = await api.glossary.createMany({ + project: 'project-id', // or Project object + terms: [ + { term: [{ lang: Locales.ENGLISH, term: 'Save' }], description: 'UI action' }, + { + term: [ + { lang: Locales.ENGLISH, term: 'Monitor' }, + { lang: Locales.CZECH, term: 'Monitor' }, + ], + }, + ], +}); +``` + ### glossary.update(request[, config]) Update [glossary record](../src/types/glossary-record.ts) specified by `id`. diff --git a/src/api/api-client.ts b/src/api/api-client.ts index ef5f3b1..3a27333 100644 --- a/src/api/api-client.ts +++ b/src/api/api-client.ts @@ -9,6 +9,15 @@ import { ApiProjects } from '@/api/methods/api-projects.js'; import { ApiScreenshots } from '@/api/methods/api-screenshots.js'; import { ApiSuggestions } from '@/api/methods/api-suggestions.js'; import { ApiWebhooks } from '@/api/methods/api-webhooks.js'; +import { ApiOrganizations } from '@/api/methods/api-organizations.js'; +import { ApiLanguages } from '@/api/methods/api-languages.js'; +import { ApiBranches } from '@/api/methods/api-branches.js'; +import { ApiComments } from '@/api/methods/api-comments.js'; +import { ApiLinks } from '@/api/methods/api-links.js'; +import { ApiSegmentation } from '@/api/methods/api-segmentation.js'; +import { ApiTags } from '@/api/methods/api-tags.js'; +import { ApiStyleguides } from '@/api/methods/api-styleguides.js'; +import { ApiCdn } from '@/api/methods/api-cdn.js'; import { FetchHttpAdapter } from '@/http/fetch-http-adapter.js'; import type { IHttpAdapter } from '@/http/i-http-adapter.js'; import type { ApiClientOptions } from '@/types/api-client-options.js'; @@ -38,6 +47,24 @@ export class ApiClient { public suggestions: ApiSuggestions; + public organizations: ApiOrganizations; + + public languages: ApiLanguages; + + public branches: ApiBranches; + + public comments: ApiComments; + + public links: ApiLinks; + + public segmentation: ApiSegmentation; + + public tags: ApiTags; + + public styleguides: ApiStyleguides; + + public cdn: ApiCdn; + constructor(options: ApiClientOptions) { this.client = new FetchHttpAdapter(options); @@ -52,5 +79,14 @@ export class ApiClient { this.webhooks = new ApiWebhooks(this); this.screenshots = new ApiScreenshots(this); this.suggestions = new ApiSuggestions(this); + this.organizations = new ApiOrganizations(this); + this.languages = new ApiLanguages(this); + this.branches = new ApiBranches(this); + this.comments = new ApiComments(this); + this.links = new ApiLinks(this); + this.segmentation = new ApiSegmentation(this); + this.tags = new ApiTags(this); + this.styleguides = new ApiStyleguides(this); + this.cdn = new ApiCdn(this); } } diff --git a/src/api/methods/api-branches.ts b/src/api/methods/api-branches.ts new file mode 100644 index 0000000..c314e4b --- /dev/null +++ b/src/api/methods/api-branches.ts @@ -0,0 +1,252 @@ +import { ApiBase } from '@/api/methods/api-base.js'; +import type { Branch } from '@/types/branch.js'; +import type { BranchAnalyzeMergeRequest } from '@/types/branch-analyze-merge-request.js'; +import type { BranchCreateRequest } from '@/types/branch-create-request.js'; +import type { BranchDeleteRequest } from '@/types/branch-delete-request.js'; +import type { BranchGetOperationRequest } from '@/types/branch-get-operation-request.js'; +import type { BranchListRequest } from '@/types/branch-list-request.js'; +import type { BranchMergeAnalysis } from '@/types/branch-merge-analysis.js'; +import type { BranchMergeRequest } from '@/types/branch-merge-request.js'; +import type { BranchOperationStatus } from '@/types/branch-operation-status.js'; +import type { BranchRenameRequest } from '@/types/branch-rename-request.js'; +import type { BranchSeparateRequest } from '@/types/branch-separate-request.js'; +import type { BranchSetMainRequest } from '@/types/branch-set-main-request.js'; +import type { RequestConfig } from '@/types/request-config.js'; + +/** + * Branching is a plan feature; without it every method rejects with `400` (`unpaid`). Branches other + * than the one `project` addresses are referred to by name, and `project` may be any branch. + */ +export class ApiBranches extends ApiBase { + /** + * List all {@link Branch branches} of the project: `main` first, then the others by name. The + * result is the same whichever branch `project` addresses, and includes branches the caller is + * not a member of. + * + * @param request Branch list request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/branching#list-branches Localazy API Docs} + */ + public async list(request: BranchListRequest, config?: RequestConfig): Promise { + const { project }: BranchListRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const response: { branches: Branch[] } = (await this.api.client.get( + `/projects/${projectId}/branches`, + config, + )) as { branches: Branch[] }; + + return response.branches; + } + + /** + * Create a branch as a copy of `source`, or of its settings only with `empty: true`. + * + * The copy runs in the background: poll the returned operation ID with `getOperation()` until it + * is `done` or `error`. + * + * @param request Branch create request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/branching#create-a-branch Localazy API Docs} + */ + public async create(request: BranchCreateRequest, config?: RequestConfig): Promise { + const { project, source, ...data }: BranchCreateRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const response: { result: string } = (await this.api.client.post( + `/projects/${projectId}/branches`, + source === undefined ? data : { ...data, source: ApiBranches.getName(source, 'source') }, + config, + )) as { result: string }; + + return response.result; + } + + /** + * Rename a branch. Its `projectId` stays; its slug ends with `!`. The main branch cannot + * be renamed; use `setMain()` instead. + * + * @param request Branch rename request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/branching#rename-a-branch Localazy API Docs} + */ + public async rename(request: BranchRenameRequest, config?: RequestConfig): Promise { + const { project, branch, name }: BranchRenameRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const branchName: string = ApiBranches.getName(branch, 'branch'); + + await this.api.client.put( + `/projects/${projectId}/branches/${encodeURIComponent(branchName)}`, + { name }, + config, + ); + } + + /** + * Delete a branch: its project is archived with all its content. + * + * Rejected with `400` for the main branch, a branch other branches were made from, the source of + * linked keys, a branch whose glossary or translation memory other projects use, or while + * duplicity resolution runs for it. + * + * @param request Branch delete request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/branching#delete-a-branch Localazy API Docs} + */ + public async delete(request: BranchDeleteRequest, config?: RequestConfig): Promise { + const { project, branch }: BranchDeleteRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const branchName: string = ApiBranches.getName(branch, 'branch'); + + await this.api.client.delete( + `/projects/${projectId}/branches/${encodeURIComponent(branchName)}`, + config, + ); + } + + /** + * Make `branch` the main branch. No content moves: `branch` takes the name `main` and the old main + * slug, and the old main branch takes `name`. Every `projectId` stays, so a branch token keeps + * addressing the same content even though its branch name may change. + * + * @param request Branch set main request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/branching#set-the-main-branch Localazy API Docs} + */ + public async setMain(request: BranchSetMainRequest, config?: RequestConfig): Promise { + const { project, branch, name }: BranchSetMainRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const branchName: string = ApiBranches.getName(branch, 'branch'); + + await this.api.client.post( + `/projects/${projectId}/branches/${encodeURIComponent(branchName)}/main`, + { name }, + config, + ); + } + + /** + * Turn a branch into an independent project. It keeps its `projectId` and content, loses the + * `!` slug suffix, leaves `list()`, and can no longer be merged with the project's branches. + * Branches made from it are re-parented to its own source. The main branch cannot be separated. + * + * @param request Branch separate request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/branching#separate-a-branch Localazy API Docs} + */ + public async separate(request: BranchSeparateRequest, config?: RequestConfig): Promise { + const { project, branch }: BranchSeparateRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const branchName: string = ApiBranches.getName(branch, 'branch'); + + await this.api.client.post( + `/projects/${projectId}/branches/${encodeURIComponent(branchName)}/separate`, + undefined, + config, + ); + } + + /** + * Report what `merge()` with the same request would do, changing nothing. It answers only when the + * analysis finishes, which can take long on a large project, and fails with `409` while another + * analysis or merge runs on one of the branches it uses. + * + * @param request Branch analyze merge request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/branching#analyze-a-merge Localazy API Docs} + */ + public async analyzeMerge( + request: BranchAnalyzeMergeRequest, + config?: RequestConfig, + ): Promise { + const { project, branch, ...data }: BranchAnalyzeMergeRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const branchName: string = ApiBranches.getName(branch, 'branch'); + + return (await this.api.client.post( + `/projects/${projectId}/branches/${encodeURIComponent(branchName)}/analysis`, + ApiBranches.mergeBody(data), + config, + )) as BranchMergeAnalysis; + } + + /** + * Merge `branch` into `target`. Run `analyzeMerge()` with the same request first: a merge cannot + * be reverted, and the `target` and `time-bidi` strategies also write back to the source branch. + * + * The merge runs in the background. The returned operation ID goes to `getOperation()`; poll it + * until the status is `done` (with the merge counts) or `error`. It fails with `409` while + * another analysis or merge runs on one of the branches it uses. + * + * @param request Branch merge request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/branching#merge-branches Localazy API Docs} + */ + public async merge(request: BranchMergeRequest, config?: RequestConfig): Promise { + const { project, branch, ...data }: BranchMergeRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const branchName: string = ApiBranches.getName(branch, 'branch'); + const response: { result: string } = (await this.api.client.post( + `/projects/${projectId}/branches/${encodeURIComponent(branchName)}/merge`, + ApiBranches.mergeBody(data), + config, + )) as { result: string }; + + return response.result; + } + + /** + * Get the status of an operation started by `create()` or `merge()`. Poll while the status is + * `scheduled` or `in_progress`. An unknown, expired (after 48 hours) or foreign ID resolves with + * status `invalid_id`; only a malformed ID rejects. + * + * @param request Branch get operation request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/branching#check-the-status-of-an-operation Localazy API Docs} + */ + public async getOperation( + request: BranchGetOperationRequest, + config?: RequestConfig, + ): Promise { + const { project, operation }: BranchGetOperationRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + if (!operation) { + throw new Error('Invalid operation ID.'); + } + + return (await this.api.client.get( + `/projects/${projectId}/branches/operations/${encodeURIComponent(operation)}`, + config, + )) as BranchOperationStatus; + } + + protected static getName(val: string | Pick, prop: string): string { + const name: string = typeof val === 'string' ? val : val.name || ''; + + // `.` and `..` are dot-segments: URL resolution would drop them and hit another endpoint. + if (!name || name === '.' || name === '..') { + throw new Error(`Invalid ${prop} name.`); + } + + return name; + } + + protected static mergeBody( + data: Omit, + ): Record { + const { target, keys, ...options } = data; + + return { + ...options, + target: ApiBranches.getName(target, 'target'), + ...(keys === undefined ? {} : { keys: ApiBase.getIds(keys, 'key') }), + }; + } +} diff --git a/src/api/methods/api-cdn.ts b/src/api/methods/api-cdn.ts new file mode 100644 index 0000000..e5ff491 --- /dev/null +++ b/src/api/methods/api-cdn.ts @@ -0,0 +1,21 @@ +import { ApiBase } from '@/api/methods/api-base.js'; +import type { CdnListRequest } from '@/types/cdn-list-request.js'; +import type { CdnMetadata } from '@/types/cdn-metadata.js'; +import type { RequestConfig } from '@/types/request-config.js'; + +export class ApiCdn extends ApiBase { + /** + * List the CDN metadata file URLs of `latest` and of each published release tag. When the CDN is + * disabled for the project, `enabled` is `false` and the list is empty. + * + * @param request CDN list request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/cdn#list-metadata-files Localazy API Docs} + */ + public async list(request: CdnListRequest, config?: RequestConfig): Promise { + const projectId: string = ApiBase.getId(request.project, 'project'); + + return (await this.api.client.get(`/projects/${projectId}/cdn`, config)) as CdnMetadata; + } +} diff --git a/src/api/methods/api-comments.ts b/src/api/methods/api-comments.ts new file mode 100644 index 0000000..f8282ce --- /dev/null +++ b/src/api/methods/api-comments.ts @@ -0,0 +1,94 @@ +import { ApiBase } from '@/api/methods/api-base.js'; +import type { CommentCreateRequest } from '@/types/comment-create-request.js'; +import type { CommentDeleteRequest } from '@/types/comment-delete-request.js'; +import type { CommentListRequest } from '@/types/comment-list-request.js'; +import type { CommentUpdateRequest } from '@/types/comment-update-request.js'; +import type { KeyComment } from '@/types/key-comment.js'; +import type { RequestConfig } from '@/types/request-config.js'; + +export class ApiComments extends ApiBase { + /** + * List the discussion of a {@link Key key} in one language, newest first. Deleted comments are + * left out, and reading does not mark comments as read. `keys.getDetails()` returns the same + * comments for up to 100 keys at once. + * + * @param request Comment list request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/source-keys#list-comments-of-a-key Localazy API Docs} + */ + public async list(request: CommentListRequest, config?: RequestConfig): Promise { + const response: { comments: KeyComment[] } = (await this.api.client.get( + ApiComments.commentsUrl(request), + config, + )) as { comments: KeyComment[] }; + + return response.comments; + } + + /** + * Add a comment to the discussion of a {@link Key key} in one language, authored by the token's + * user. It behaves like a comment written in Localazy: unread for the other users, notifications + * and e-mails are sent, and the `comment_added` webhook fires. + * + * @param request Comment create request config. + * @param config Request config. + * @returns ID of the new comment. + * + * @see {@link https://localazy.com/docs/api/source-keys#add-a-comment Localazy API Docs} + */ + public async create(request: CommentCreateRequest, config?: RequestConfig): Promise { + const response: { result: string } = (await this.api.client.post( + ApiComments.commentsUrl(request), + { text: request.text }, + config, + )) as { result: string }; + + return response.result; + } + + /** + * Replace the text of a comment. Only its author may: a comment of another user fails with `401`, + * even for a manager or owner. A comment that is deleted or not on this key and language fails + * with `404`. No notification or webhook is sent. + * + * @param request Comment update request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/source-keys#edit-a-comment Localazy API Docs} + */ + public async update(request: CommentUpdateRequest, config?: RequestConfig): Promise { + const commentId: string = ApiBase.getId(request.comment, 'comment'); + + await this.api.client.put( + `${ApiComments.commentsUrl(request)}/${commentId}`, + { text: request.text }, + config, + ); + } + + /** + * Delete a comment. Only its author may: a comment of another user fails with `401`, even for a + * manager or owner. A comment that is already deleted or not on this key and language fails with + * `404`. + * + * @param request Comment delete request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/source-keys#delete-a-comment Localazy API Docs} + */ + public async delete(request: CommentDeleteRequest, config?: RequestConfig): Promise { + const commentId: string = ApiBase.getId(request.comment, 'comment'); + + await this.api.client.delete(`${ApiComments.commentsUrl(request)}/${commentId}`, config); + } + + protected static commentsUrl(request: CommentListRequest): string { + const { project, key, lang }: CommentListRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const keyId: string = ApiBase.getId(key, 'key'); + const locale: string = encodeURIComponent(ApiBase.requireLang(lang, 'lang')); + + return `/projects/${projectId}/keys/${keyId}/comments/${locale}`; + } +} diff --git a/src/api/methods/api-files.ts b/src/api/methods/api-files.ts index 59b6079..1e2d44e 100644 --- a/src/api/methods/api-files.ts +++ b/src/api/methods/api-files.ts @@ -9,6 +9,8 @@ import type { File } from '@/types/file.js'; import type { FilesListRequest } from '@/types/files-list-request.js'; import type { Key } from '@/types/key.js'; import type { KeysPaginated } from '@/types/keys-paginated.js'; +import type { PublishedListRequest } from '@/types/published-list-request.js'; +import type { PublishedRecord } from '@/types/published-record.js'; import type { RequestConfig } from '@/types/request-config.js'; import type { Blob } from 'node:buffer'; @@ -147,4 +149,26 @@ export class ApiFiles extends ApiBase { responseType: 'blob', })) as Blob; } + + /** + * List when the project's current content (`latest`, always first) and each release tag were last + * published. Use it to check cheaply for new content: download only when `publishedAt` changed + * since the previous call. A publish can come up to 5 minutes after a change. + * + * @param request Published list request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/files#list-publish-times Localazy API Docs} + */ + public async listPublished( + request: PublishedListRequest, + config?: RequestConfig, + ): Promise { + const projectId: string = ApiBase.getId(request.project, 'project'); + + return (await this.api.client.get( + `/projects/${projectId}/published`, + config, + )) as PublishedRecord[]; + } } diff --git a/src/api/methods/api-glossary.ts b/src/api/methods/api-glossary.ts index 8e766d5..a5c9d21 100644 --- a/src/api/methods/api-glossary.ts +++ b/src/api/methods/api-glossary.ts @@ -1,4 +1,6 @@ import { ApiBase } from '@/api/methods/api-base.js'; +import type { GlossaryCreateManyRequest } from '@/types/glossary-create-many-request.js'; +import type { GlossaryCreateManyResponse } from '@/types/glossary-create-many-response.js'; import type { GlossaryCreateRequest } from '@/types/glossary-create-request.js'; import type { GlossaryDeleteRequest } from '@/types/glossary-delete-request.js'; import type { GlossaryFindRequest } from '@/types/glossary-find-request.js'; @@ -70,6 +72,32 @@ export class ApiGlossary extends ApiBase { return response.result; } + /** + * Create several {@link GlossaryRecord glossary records} in one request. + * + * Unlike `create()`, a duplicate of an existing term is merged into it instead of being refused. + * The whole batch is rejected if it would exceed the 1000-term project limit. + * + * @param request Glossary create many request config. + * @param config Request config. + */ + public async createMany( + request: GlossaryCreateManyRequest, + config?: RequestConfig, + ): Promise { + const { project, terms }: GlossaryCreateManyRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + if (!Array.isArray(terms)) { + throw new TypeError('Invalid glossary term list: an array is required.'); + } + + return (await this.api.client.post( + `/projects/${projectId}/glossary/batch`, + terms, + config, + )) as GlossaryCreateManyResponse; + } + /** * Update {@link GlossaryRecord glossary record} specified by `id`. * diff --git a/src/api/methods/api-keys.ts b/src/api/methods/api-keys.ts index 0f5c88a..3407848 100644 --- a/src/api/methods/api-keys.ts +++ b/src/api/methods/api-keys.ts @@ -1,6 +1,11 @@ import { ApiBase } from '@/api/methods/api-base.js'; import type { KeyDeleteRequest } from '@/types/key-delete-request.js'; import type { KeyDeprecateRequest } from '@/types/key-deprecate-request.js'; +import type { KeyDetailsRequest } from '@/types/key-details-request.js'; +import type { KeyDetailsResponse } from '@/types/key-details-response.js'; +import type { KeyEditSourceRequest } from '@/types/key-edit-source-request.js'; +import type { KeyReviewTranslationRequest } from '@/types/key-review-translation-request.js'; +import type { ReviewTranslationResponse } from '@/types/review-translation-response.js'; import type { KeyRenameRequest } from '@/types/key-rename-request.js'; import type { KeyRenameResponse } from '@/types/key-rename-response.js'; import type { KeySetMetadataRequest } from '@/types/key-set-metadata-request.js'; @@ -117,6 +122,92 @@ export class ApiKeys extends ApiBase { )) as SubmitTranslationResponse; } + /** + * Get the details of {@link Key keys} in one language, 1 to 100 keys per call. Keys that can't be + * read are reported in `errors` and don't fail the request. + * + * @param request Key details request config. + * @param config Request config. Its `params` are preserved; `ids` is merged over them. + * + * @see {@link https://localazy.com/docs/api/source-keys#get-key-details Localazy API Docs} + */ + public async getDetails( + request: KeyDetailsRequest, + config?: RequestConfig, + ): Promise { + const { project, keys, lang }: KeyDetailsRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const ids: string = ApiBase.getIds(keys, 'key').join(','); + const locale: string = encodeURIComponent(ApiBase.requireLang(lang, 'lang')); + + return (await this.api.client.get(`/projects/${projectId}/keys/details/${locale}`, { + ...config, + params: { ...config?.params, ids }, + })) as KeyDetailsResponse; + } + + /** + * Write a new source text for a {@link Key key}. + * + * The text becomes current immediately only for callers allowed to auto-approve their own + * versions (manager, owner); for others it waits for a review. `value` follows the same rules as + * in `submitTranslation()`. Segmented keys and their segments are rejected. + * + * **Check `result` on the response**: `false` with a `message` means the project was momentarily + * locked or the value was not stored, and does not reject the promise. + * + * @param request Key edit source request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/source-keys#edit-source-text Localazy API Docs} + */ + public async editSource( + request: KeyEditSourceRequest, + config?: RequestConfig, + ): Promise { + const { project, key, value, sourceChanged }: KeyEditSourceRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const keyId: string = ApiBase.getId(key, 'key'); + + return (await this.api.client.post( + `/projects/${projectId}/keys/${keyId}/source`, + { value: normalizeTranslationValue(value), sourceChanged }, + config, + )) as SubmitTranslationResponse; + } + + /** + * Approve or reject one version of a {@link Key key} in one language. + * + * Approving makes the version current and rejects the other versions waiting for review; + * approving the already-current version confirms it. The current version cannot be rejected + * (`current_version_cannot_be_rejected`). Approving one's own version needs the + * `project.translations.approve.own` permission. + * + * **Check `result` on the response**: `false` means the project was momentarily locked; retry. + * + * @param request Key review translation request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/source-keys#review-a-translation Localazy API Docs} + */ + public async reviewTranslation( + request: KeyReviewTranslationRequest, + config?: RequestConfig, + ): Promise { + const { project, key, lang, versionId, action, sourceChanged }: KeyReviewTranslationRequest = + request; + const projectId: string = ApiBase.getId(project, 'project'); + const keyId: string = ApiBase.getId(key, 'key'); + const locale: string = encodeURIComponent(ApiBase.requireLang(lang, 'lang')); + + return (await this.api.client.post( + `/projects/${projectId}/keys/${keyId}/translations/${locale}/review`, + { versionId, action, sourceChanged }, + config, + )) as ReviewTranslationResponse; + } + /** * Add and/or remove tags on {@link Key keys}. * diff --git a/src/api/methods/api-languages.ts b/src/api/methods/api-languages.ts new file mode 100644 index 0000000..1d4acd2 --- /dev/null +++ b/src/api/methods/api-languages.ts @@ -0,0 +1,284 @@ +import { ApiBase } from '@/api/methods/api-base.js'; +import type { BooleanResult } from '@/types/boolean-result.js'; +import type { LanguageAddResponse } from '@/types/language-add-response.js'; +import type { LanguageCopyRequest } from '@/types/language-copy-request.js'; +import type { LanguageCopyResponse } from '@/types/language-copy-response.js'; +import type { LanguageDeleteRequest } from '@/types/language-delete-request.js'; +import type { LanguageDisableResponse } from '@/types/language-disable-response.js'; +import type { LanguageEnableResponse } from '@/types/language-enable-response.js'; +import type { LanguageHideResponse } from '@/types/language-hide-response.js'; +import type { LanguageKey } from '@/types/language-key.js'; +import type { LanguageKeysPaginated } from '@/types/language-keys-paginated.js'; +import type { LanguageListKeysRequest } from '@/types/language-list-keys-request.js'; +import type { LanguageReplaceRequest } from '@/types/language-replace-request.js'; +import type { LanguageSetFallbackRequest } from '@/types/language-set-fallback-request.js'; +import type { LanguagesBatchRequest } from '@/types/languages-batch-request.js'; +import type { Plurals } from '@/types/plurals.js'; +import type { PluralsListRequest } from '@/types/plurals-list-request.js'; +import type { RequestConfig } from '@/types/request-config.js'; + +export class ApiLanguages extends ApiBase { + /** + * Add target languages to the project. They are added empty: nothing is translated and no publish + * is triggered. A hidden language comes back with its translations, as `restored`. + * + * Only resolving the languages is all-or-nothing; a failure part-way through adding them can leave + * the earlier ones added. Repeating the call is safe. + * + * @param request Languages batch request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/project-languages#add-languages Localazy API Docs} + */ + public async add( + request: LanguagesBatchRequest, + config?: RequestConfig, + ): Promise { + return (await this.postBatch('', request, config)) as LanguageAddResponse; + } + + /** + * Hide languages: they leave the project but keep their translations, which come back when the + * language is added again. Use {@link ApiLanguages.delete} to remove the translations too. + * + * @param request Languages batch request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/project-languages#hide-languages Localazy API Docs} + */ + public async hide( + request: LanguagesBatchRequest, + config?: RequestConfig, + ): Promise { + return (await this.postBatch('/hide', request, config)) as LanguageHideResponse; + } + + /** + * Include languages when the project is published. Adding a hidden language back also enables it. + * + * @param request Languages batch request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/project-languages#enable-and-disable-publishing + * | Localazy API Docs} + */ + public async enable( + request: LanguagesBatchRequest, + config?: RequestConfig, + ): Promise { + return (await this.postBatch('/enable', request, config)) as LanguageEnableResponse; + } + + /** + * Leave languages out when the project is published. They stay in the project and translatable, + * but their "new strings" and "to review" e-mails stop. + * + * @param request Languages batch request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/project-languages#enable-and-disable-publishing + * | Localazy API Docs} + */ + public async disable( + request: LanguagesBatchRequest, + config?: RequestConfig, + ): Promise { + return (await this.postBatch('/disable', request, config)) as LanguageDisableResponse; + } + + /** + * Permanently delete a language **and all of its translations**; there is no undo. Use + * {@link ApiLanguages.hide} to keep the translations. + * + * Runs while the request is open, so it is slow on large projects. Fails with `409` while another + * delete, copy or replace runs in the project, or while another language falls back to this one. + * + * @param request Language delete request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/project-languages#delete-a-language Localazy API Docs} + */ + public async delete( + request: LanguageDeleteRequest, + config?: RequestConfig, + ): Promise { + const { project, lang }: LanguageDeleteRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const locale: string = encodeURIComponent(ApiBase.requireLang(lang, 'lang')); + + return (await this.api.client.delete( + `/projects/${projectId}/languages/${locale}`, + config, + )) as BooleanResult; + } + + /** + * Add a language pre-filled with a snapshot of another one's translations, e.g. `pt_BR` into + * `pt_PT`. + * + * If `to` is hidden, its kept translations are destroyed first and stay destroyed even when the + * copy then fails. + * + * @param request Language copy request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/project-languages#copy-a-language Localazy API Docs} + */ + public async copy( + request: LanguageCopyRequest, + config?: RequestConfig, + ): Promise { + const { project, from, to }: LanguageCopyRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + + return (await this.api.client.post( + `/projects/${projectId}/languages/copy`, + { from: ApiBase.requireLang(from, 'from'), to: ApiBase.requireLang(to, 'to') }, + config, + )) as LanguageCopyResponse; + } + + /** + * Move all translations of `language` to `replaceWith`, e.g. `de` to `de_AT`. `language` stops + * existing and `replaceWith` takes over its state, publish flag and fallbacks included. + * + * Fails with `409` while another delete, copy or replace runs in the project, or when the move + * would make a cycle of fallback languages. + * + * @param request Language replace request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/project-languages#replace-a-language Localazy API Docs} + */ + public async replace( + request: LanguageReplaceRequest, + config?: RequestConfig, + ): Promise { + const { project, language, replaceWith }: LanguageReplaceRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + + return (await this.api.client.post( + `/projects/${projectId}/languages/replace`, + { + language: ApiBase.requireLang(language, 'language'), + replaceWith: ApiBase.requireLang(replaceWith, 'replaceWith'), + }, + config, + )) as BooleanResult; + } + + /** + * Set or remove (`fallback: null`) the fallback language of a language. Fallbacks chain and end at + * the source language, apply only to file outputs, and each change publishes the project again. + * + * Setting one fails with `unpaid` when the organization lacks the feature; removing always works. + * + * @param request Language set fallback request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/project-languages#set-a-fallback-language + * | Localazy API Docs} + */ + public async setFallback( + request: LanguageSetFallbackRequest, + config?: RequestConfig, + ): Promise { + const { project, lang, fallback }: LanguageSetFallbackRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const locale: string = encodeURIComponent(ApiBase.requireLang(lang, 'lang')); + + return (await this.api.client.put( + `/projects/${projectId}/languages/${locale}/fallback`, + { fallback: fallback === null ? null : ApiBase.requireLang(fallback, 'fallback') }, + config, + )) as BooleanResult; + } + + /** + * List all {@link LanguageKey keys} of all files of the project with their values in one language. + * Each key has its `file`; use {@link ApiLanguages.listKeysPage} to also get the file descriptions. + * + * @param request Language list keys request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/files#list-keys-of-all-files Localazy API Docs} + */ + public async listKeys( + request: LanguageListKeysRequest, + config?: RequestConfig, + ): Promise { + const keys: LanguageKey[] = []; + let next: string | undefined = request.next; + + do { + const page: LanguageKeysPaginated = await this.listKeysPage({ ...request, next }, config); + keys.push(...page.keys); + next = page.next; + } while (next); + + return keys; + } + + /** + * List one page of {@link LanguageKey keys} of all files of the project with their values in one + * language. `files` describes the files of the keys on the page. + * + * @param request Language list keys request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/files#list-keys-of-all-files Localazy API Docs} + */ + public async listKeysPage( + request: LanguageListKeysRequest, + config?: RequestConfig, + ): Promise { + const { project, lang, ...query }: LanguageListKeysRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const locale: string = encodeURIComponent(ApiBase.requireLang(lang, 'lang')); + const params: Record = { ...config?.params }; + for (const [name, value] of Object.entries(query)) { + if (value !== undefined && value !== '') { + params[name] = String(value); + } + } + + return (await this.api.client.get( + `/projects/${projectId}/languages/${locale}/keys`, + Object.keys(params).length > 0 ? { ...config, params } : config, + )) as LanguageKeysPaginated; + } + + /** + * Get the plural rules the project defines and the plural forms each project language uses as a + * result, i.e. which forms a plural value needs in each language. + * + * @param request Plurals list request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/project-styleguides-plurals#get-plurals + * | Localazy API Docs} + */ + public async listPlurals(request: PluralsListRequest, config?: RequestConfig): Promise { + const projectId: string = ApiBase.getId(request.project, 'project'); + + return (await this.api.client.get(`/projects/${projectId}/plurals`, config)) as Plurals; + } + + protected async postBatch( + path: string, + request: LanguagesBatchRequest, + config?: RequestConfig, + ): Promise { + const { project, languages }: LanguagesBatchRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + if (!Array.isArray(languages)) { + throw new TypeError('Invalid language list: an array is required.'); + } + + return this.api.client.post( + `/projects/${projectId}/languages${path}`, + { languages: languages.map((lang) => ApiBase.requireLang(lang, 'lang')) }, + config, + ); + } +} diff --git a/src/api/methods/api-links.ts b/src/api/methods/api-links.ts new file mode 100644 index 0000000..011d44f --- /dev/null +++ b/src/api/methods/api-links.ts @@ -0,0 +1,101 @@ +import { ApiBase } from '@/api/methods/api-base.js'; +import type { Link } from '@/types/link.js'; +import type { LinkCreateRequest } from '@/types/link-create-request.js'; +import type { LinkDeleteRequest } from '@/types/link-delete-request.js'; +import type { LinkListRequest } from '@/types/link-list-request.js'; +import type { LinksPaginated } from '@/types/links-paginated.js'; +import type { RequestConfig } from '@/types/request-config.js'; + +export class ApiLinks extends ApiBase { + /** + * List all {@link Link key links} in the project. + * + * @param request Link list request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/duplicities#list-links Localazy API Docs} + */ + public async list(request: LinkListRequest, config?: RequestConfig): Promise { + const links: Link[] = []; + let next: string | undefined = request.next; + + do { + const page: LinksPaginated = await this.listPage({ ...request, next }, config); + links.push(...page.links); + next = page.next; + } while (next); + + return links; + } + + /** + * List {@link Link key links} in the project. Result is paginated. + * + * @param request Link list request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/duplicities#list-links Localazy API Docs} + */ + public async listPage(request: LinkListRequest, config?: RequestConfig): Promise { + const { project, limit, next }: LinkListRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const params: Record = { ...config?.params }; + + if (limit !== undefined) { + params.limit = String(limit); + } + if (next) { + params.next = next; + } + + return (await this.api.client.get( + `/projects/${projectId}/links`, + Object.keys(params).length > 0 ? { ...config, params } : config, + )) as LinksPaginated; + } + + /** + * Link a {@link Key key} to a target key, in the same project or another one. The linked key + * becomes hidden and publishes the target's content while the link exists. + * + * Links are honoured during publishing only on the Business plan and above; on other plans they + * are stored but ignored. A segmented key as a whole cannot be linked on either side (its + * individual segments can), and a key or target that does not exist rejects with `unauthorized`; an unknown `linkedProject` + * rejects with `project_not_found`. + * + * @param request Link create request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/duplicities#create-links Localazy API Docs} + */ + public async create(request: LinkCreateRequest, config?: RequestConfig): Promise { + const { project, key, linkedKey, linkedProject }: LinkCreateRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const keyId: string = ApiBase.getId(key, 'key'); + const data: { keyId: string; project?: string } = { + keyId: ApiBase.getId(linkedKey, 'linked key'), + }; + + if (linkedProject !== undefined) { + data.project = ApiBase.getId(linkedProject, 'linked project'); + } + + await this.api.client.post(`/projects/${projectId}/links/${keyId}`, data, config); + } + + /** + * Remove the link of a {@link Key key}. A segmented key as a whole is rejected. + * + * @param request Link delete request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/duplicities#remove-links Localazy API Docs} + */ + public async delete(request: LinkDeleteRequest, config?: RequestConfig): Promise { + const { project, key }: LinkDeleteRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const keyId: string = ApiBase.getId(key, 'key'); + + await this.api.client.delete(`/projects/${projectId}/links/${keyId}`, config); + } +} diff --git a/src/api/methods/api-organizations.ts b/src/api/methods/api-organizations.ts new file mode 100644 index 0000000..9ce3cca --- /dev/null +++ b/src/api/methods/api-organizations.ts @@ -0,0 +1,210 @@ +import { ApiBase } from '@/api/methods/api-base.js'; +import type { CreditSummaryRequest } from '@/types/credit-summary-request.js'; +import type { CreditSummaryResponse } from '@/types/credit-summary-response.js'; +import type { CreditTopupsListRequest } from '@/types/credit-topups-list-request.js'; +import type { CreditTopupsResponse } from '@/types/credit-topups-response.js'; +import type { CreditTransactionsListRequest } from '@/types/credit-transactions-list-request.js'; +import type { CreditTransactionsPaginated } from '@/types/credit-transactions-paginated.js'; +import type { CreditTransaction, CreditTransactions } from '@/types/credit-transactions.js'; +import type { OrganizationSearchRequest } from '@/types/organization-search-request.js'; +import type { OrganizationSearchResponse } from '@/types/organization-search-response.js'; +import type { OrganizationUsage } from '@/types/organization-usage.js'; +import type { OrganizationUsageRequest } from '@/types/organization-usage-request.js'; +import type { RequestConfig } from '@/types/request-config.js'; + +export class ApiOrganizations extends ApiBase { + /** + * Get the source key quota usage and the credit balance of an organization. + * + * For a team (sub-organization) the figures are those of its parent billing organization, whose + * ID is in `organizationId`. `keys.remaining` goes negative when the organization is over its quota. + * + * @param request Organization usage request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/organization-usage#get-usage Localazy API Docs} + */ + public async getUsage( + request: OrganizationUsageRequest, + config?: RequestConfig, + ): Promise { + const orgId: string = ApiBase.getId(request.organization, 'organization'); + + return (await this.api.client.get( + `/organizations/${orgId}/usage`, + config, + )) as OrganizationUsage; + } + + /** + * Full-text search in the keys, comments and translations of all projects of an organization. + * + * Needs organization search in the plan, and a top-level organization: otherwise the call fails + * with `search_not_available`. Returns at most 2000 results with no paging; projects the token's + * user cannot read give no results and no error. The index lags behind changes by up to about an + * hour. + * + * @param request Organization search request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/organization-search#search Localazy API Docs} + */ + public async search( + request: OrganizationSearchRequest, + config?: RequestConfig, + ): Promise { + const { + organization, + term, + projects, + excludeProjects, + match, + langs, + }: OrganizationSearchRequest = request; + const orgId: string = ApiBase.getId(organization, 'organization'); + if (projects?.length === 0) { + throw new Error('Invalid project list: the server reads an empty list as all projects.'); + } + const params: Record = ApiOrganizations.params(config, { + term, + projects: projects && ApiBase.getIds(projects, 'project'), + excludeProjects: excludeProjects && ApiBase.getIds(excludeProjects, 'project'), + match, + langs, + }); + + return (await this.api.client.get(`/organizations/${orgId}/search`, { + ...config, + params, + })) as OrganizationSearchResponse; + } + + /** + * Get the credit consumption of an organization in a period, the credits topped up in it, and the + * current balance, optionally grouped. + * + * `spent` excludes `system` costs, which are reported as `adjusted`. Credits belong to the billing + * organization: for a team, the parent's data is returned. + * + * @param request Credit summary request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/organization-credits#get-credit-summary Localazy API Docs} + */ + public async getCreditSummary( + request: CreditSummaryRequest, + config?: RequestConfig, + ): Promise { + const { organization, ...rest }: CreditSummaryRequest = request; + const orgId: string = ApiBase.getId(organization, 'organization'); + + return (await this.api.client.get(`/organizations/${orgId}/credits/summary`, { + ...config, + params: ApiOrganizations.params(config, rest), + })) as CreditSummaryResponse; + } + + /** + * List all credit costs of an organization in a period, one row per charge, in time order. + * Fetches every page; a long period can hold a very large number of rows. + * + * The `to` of the first page is reused for the following ones, so the pages cover one period. + * + * @param request Credit transactions list request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/organization-credits#list-credit-transactions Localazy API Docs} + */ + public async listCreditTransactions( + request: CreditTransactionsListRequest, + config?: RequestConfig, + ): Promise { + const first: CreditTransactionsPaginated = await this.listCreditTransactionsPage( + { ...request, next: undefined }, + config, + ); + const transactions: CreditTransaction[] = [...first.transactions]; + let page: CreditTransactionsPaginated = first; + + while (page.next) { + page = await this.listCreditTransactionsPage( + { ...request, to: first.to, next: page.next }, + config, + ); + transactions.push(...page.transactions); + } + + return { organizationId: first.organizationId, from: first.from, to: first.to, transactions }; + } + + /** + * List credit costs of an organization in a period, one row per charge, in time order. Result is + * paginated. + * + * Request the next page with `next` and the same `to` as the first page; when `to` was omitted, + * pass the `to` of the first response, since the default moves with the clock. + * + * @param request Credit transactions list request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/organization-credits#list-credit-transactions Localazy API Docs} + */ + public async listCreditTransactionsPage( + request: CreditTransactionsListRequest, + config?: RequestConfig, + ): Promise { + const { organization, ...rest }: CreditTransactionsListRequest = request; + const orgId: string = ApiBase.getId(organization, 'organization'); + + return (await this.api.client.get(`/organizations/${orgId}/credits/transactions`, { + ...config, + params: ApiOrganizations.params(config, rest), + })) as CreditTransactionsPaginated; + } + + /** + * List the credits added to an organization in a period, in time order, with no paging. + * + * @param request Credit topups list request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/organization-credits#list-credit-topups Localazy API Docs} + */ + public async listCreditTopups( + request: CreditTopupsListRequest, + config?: RequestConfig, + ): Promise { + const { organization, ...rest }: CreditTopupsListRequest = request; + const orgId: string = ApiBase.getId(organization, 'organization'); + + return (await this.api.client.get(`/organizations/${orgId}/credits/topups`, { + ...config, + params: ApiOrganizations.params(config, rest), + })) as CreditTopupsResponse; + } + + /** + * An empty list is sent only for `groupBy`, where it means "totals only"; the other list params + * treat it as no filter, so it is left out. + */ + private static params( + config: RequestConfig | undefined, + values: Record, + ): Record { + const params: Record = { ...config?.params }; + + for (const [name, value] of Object.entries(values)) { + if (Array.isArray(value)) { + if (value.length > 0 || name === 'groupBy') { + params[name] = value.join(','); + } + } else if (value instanceof Date) { + params[name] = value.toISOString(); + } else if (value !== undefined) { + params[name] = String(value); + } + } + + return params; + } +} diff --git a/src/api/methods/api-projects.ts b/src/api/methods/api-projects.ts index bfa41ad..8d39854 100644 --- a/src/api/methods/api-projects.ts +++ b/src/api/methods/api-projects.ts @@ -1,5 +1,7 @@ import { ApiBase } from '@/api/methods/api-base.js'; import type { Project } from '@/types/project.js'; +import type { ProjectCreateRequest } from '@/types/project-create-request.js'; +import type { ProjectCreateResponse } from '@/types/project-create-response.js'; import type { ProjectsListRequest } from '@/types/projects-list-request.js'; import type { RequestConfig } from '@/types/request-config.js'; @@ -34,4 +36,22 @@ export class ApiProjects extends ApiBase { throw new Error('Project not found.'); } + + /** + * Create a {@link Project project} in the organization of the token. Needs an organization token. + * + * Rejected when the organization already has 50 projects, or the name, description, source + * language or slug is invalid; a slug already in use is rejected too. + * + * @param request Project create request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/projects#create-project Localazy API Docs} + */ + public async create( + request: ProjectCreateRequest, + config?: RequestConfig, + ): Promise { + return (await this.api.client.post('/projects', request, config)) as ProjectCreateResponse; + } } diff --git a/src/api/methods/api-segmentation.ts b/src/api/methods/api-segmentation.ts new file mode 100644 index 0000000..7827c27 --- /dev/null +++ b/src/api/methods/api-segmentation.ts @@ -0,0 +1,33 @@ +import { ApiBase } from '@/api/methods/api-base.js'; +import type { RequestConfig } from '@/types/request-config.js'; +import type { SegmentationGetParentRequest } from '@/types/segmentation-get-parent-request.js'; +import type { SegmentationParent } from '@/types/segmentation-parent.js'; + +export class ApiSegmentation extends ApiBase { + /** + * Get a text-segmentation {@link SegmentationParent parent}: the key a set of segments reassembles + * into, with its segment IDs and the whole text in `lang`. Turns the `segParentId` of a segment + * back into its key. + * + * An unknown ID, a parent of another project and a project without segmentation all reject with + * `unauthorized`; a malformed ID rejects with `invalid_id` and an unknown `lang` with + * `unknown_lang`. + * + * @param request Segmentation get parent request config. + * @param config Request config. + */ + public async getParent( + request: SegmentationGetParentRequest, + config?: RequestConfig, + ): Promise { + const { project, parent, lang }: SegmentationGetParentRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + const parentId: string = ApiBase.getId(parent, 'parent'); + const locale: string = encodeURIComponent(ApiBase.requireLang(lang, 'lang')); + + return (await this.api.client.get( + `/projects/${projectId}/segmentation/parents/${parentId}/${locale}`, + config, + )) as SegmentationParent; + } +} diff --git a/src/api/methods/api-styleguides.ts b/src/api/methods/api-styleguides.ts new file mode 100644 index 0000000..898eb3e --- /dev/null +++ b/src/api/methods/api-styleguides.ts @@ -0,0 +1,22 @@ +import { ApiBase } from '@/api/methods/api-base.js'; +import type { RequestConfig } from '@/types/request-config.js'; +import type { Styleguides } from '@/types/styleguides.js'; +import type { StyleguidesListRequest } from '@/types/styleguides-list-request.js'; + +export class ApiStyleguides extends ApiBase { + /** + * Get the project's style guides: the general one and one per language. Empty or blank style + * guides count as not set. This API cannot change them. + * + * @param request Styleguides list request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/project-styleguides-plurals#get-style-guides + * | Localazy API Docs} + */ + public async list(request: StyleguidesListRequest, config?: RequestConfig): Promise { + const projectId: string = ApiBase.getId(request.project, 'project'); + + return (await this.api.client.get(`/projects/${projectId}/styleguides`, config)) as Styleguides; + } +} diff --git a/src/api/methods/api-tags.ts b/src/api/methods/api-tags.ts new file mode 100644 index 0000000..b0b91ff --- /dev/null +++ b/src/api/methods/api-tags.ts @@ -0,0 +1,22 @@ +import { ApiBase } from '@/api/methods/api-base.js'; +import type { ProjectTag } from '@/types/project-tag.js'; +import type { ProjectTagListRequest } from '@/types/project-tag-list-request.js'; +import type { RequestConfig } from '@/types/request-config.js'; + +export class ApiTags extends ApiBase { + /** + * List all {@link ProjectTag tags} that keys of the project can have: the built-in tags first, + * then the project's own. Not paginated. Screenshot tags are separate, see `screenshots.listTags()`. + * + * @param request Project tag list request config. + * @param config Request config. + * + * @see {@link https://localazy.com/docs/api/source-keys#list-tags-of-a-project Localazy API Docs} + */ + public async list(request: ProjectTagListRequest, config?: RequestConfig): Promise { + const { project }: ProjectTagListRequest = request; + const projectId: string = ApiBase.getId(project, 'project'); + + return (await this.api.client.get(`/projects/${projectId}/tags`, config)) as ProjectTag[]; + } +} diff --git a/src/enums/user-role.ts b/src/enums/user-role.ts index 204c29d..050ee02 100644 --- a/src/enums/user-role.ts +++ b/src/enums/user-role.ts @@ -5,5 +5,14 @@ export enum UserRole { REVIEWER = 'reviewer', MANAGER = 'manager', OWNER = 'owner', + VIEWER = 'viewer', + MEMBER = 'member', + /** + * A custom role of the organization; `Project.customRole` names it. + */ + CUSTOM = 'custom', + /** + * @deprecated The API never returns this role. + */ DEVELOPER = 'developer', } diff --git a/src/main.ts b/src/main.ts index c0cacbc..a11ab1c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -16,15 +16,24 @@ export * from '@/api/api-client.js'; export * from '@/api/methods/api-ai.js'; export * from '@/api/methods/api-base.js'; +export * from '@/api/methods/api-branches.js'; +export * from '@/api/methods/api-cdn.js'; +export * from '@/api/methods/api-comments.js'; export * from '@/api/methods/api-export.js'; export * from '@/api/methods/api-files.js'; export * from '@/api/methods/api-formats.js'; export * from '@/api/methods/api-glossary.js'; export * from '@/api/methods/api-import.js'; export * from '@/api/methods/api-keys.js'; +export * from '@/api/methods/api-languages.js'; +export * from '@/api/methods/api-links.js'; +export * from '@/api/methods/api-organizations.js'; export * from '@/api/methods/api-projects.js'; export * from '@/api/methods/api-screenshots.js'; +export * from '@/api/methods/api-segmentation.js'; +export * from '@/api/methods/api-styleguides.js'; export * from '@/api/methods/api-suggestions.js'; +export * from '@/api/methods/api-tags.js'; export * from '@/api/methods/api-webhooks.js'; export * from '@/enums/i18n-deprecate.js'; export * from '@/enums/key-priority.js'; @@ -45,6 +54,34 @@ export * from '@/types/ai-translate-response-item.js'; export * from '@/types/ai-translate-response.js'; export * from '@/types/api-client-options.js'; export * from '@/types/boolean-result.js'; +export * from '@/types/branch-analyze-merge-request.js'; +export * from '@/types/branch-create-request.js'; +export * from '@/types/branch-delete-request.js'; +export * from '@/types/branch-get-operation-request.js'; +export * from '@/types/branch-list-request.js'; +export * from '@/types/branch-merge-analysis.js'; +export * from '@/types/branch-merge-detail.js'; +export * from '@/types/branch-merge-request.js'; +export * from '@/types/branch-merge-strategy.js'; +export * from '@/types/branch-operation-status.js'; +export * from '@/types/branch-rename-request.js'; +export * from '@/types/branch-separate-request.js'; +export * from '@/types/branch-set-main-request.js'; +export * from '@/types/branch.js'; +export * from '@/types/cdn-list-request.js'; +export * from '@/types/cdn-metadata.js'; +export * from '@/types/comment-create-request.js'; +export * from '@/types/comment-delete-request.js'; +export * from '@/types/comment-list-request.js'; +export * from '@/types/comment-update-request.js'; +export * from '@/types/credit-balance.js'; +export * from '@/types/credit-summary-request.js'; +export * from '@/types/credit-summary-response.js'; +export * from '@/types/credit-topups-list-request.js'; +export * from '@/types/credit-topups-response.js'; +export * from '@/types/credit-transactions-list-request.js'; +export * from '@/types/credit-transactions-paginated.js'; +export * from '@/types/credit-transactions.js'; export * from '@/types/export-json-request.js'; export * from '@/types/file-get-contents-request.js'; export * from '@/types/file-list-keys-request.js'; @@ -56,6 +93,8 @@ export * from '@/types/format-key-transformer-meta.js'; export * from '@/types/format-plural-meta-required-param.js'; export * from '@/types/format-plural-meta.js'; export * from '@/types/format.js'; +export * from '@/types/glossary-create-many-request.js'; +export * from '@/types/glossary-create-many-response.js'; export * from '@/types/glossary-create-request.js'; export * from '@/types/glossary-delete-request.js'; export * from '@/types/glossary-find-request.js'; @@ -73,31 +112,71 @@ export * from '@/types/import-i18n-options.js'; export * from '@/types/import-json-request.js'; export * from '@/types/import-progress-request.js'; export * from '@/types/json.js'; +export * from '@/types/key-comment.js'; export * from '@/types/key-delete-request.js'; export * from '@/types/key-deprecate-request.js'; +export * from '@/types/key-details-request.js'; +export * from '@/types/key-details-response.js'; +export * from '@/types/key-edit-source-request.js'; export * from '@/types/key-priority.js'; export * from '@/types/key-rename-request.js'; export * from '@/types/key-rename-response.js'; +export * from '@/types/key-review-translation-request.js'; export * from '@/types/key-set-metadata-request.js'; export * from '@/types/key-set-metadata-response.js'; export * from '@/types/key-set-priority-request.js'; export * from '@/types/key-set-tags-request.js'; +export * from '@/types/key-state.js'; export * from '@/types/key-submit-translation-request.js'; export * from '@/types/key-update-request.js'; export * from '@/types/key-value.js'; export * from '@/types/key.js'; export * from '@/types/keys-paginated.js'; +export * from '@/types/language-add-response.js'; +export * from '@/types/language-batch-response.js'; +export * from '@/types/language-copy-request.js'; +export * from '@/types/language-copy-response.js'; +export * from '@/types/language-delete-request.js'; +export * from '@/types/language-disable-response.js'; +export * from '@/types/language-enable-response.js'; +export * from '@/types/language-hide-response.js'; +export * from '@/types/language-key.js'; +export * from '@/types/language-keys-paginated.js'; +export * from '@/types/language-list-keys-request.js'; +export * from '@/types/language-ref.js'; +export * from '@/types/language-replace-request.js'; +export * from '@/types/language-set-fallback-request.js'; export * from '@/types/language.js'; +export * from '@/types/languages-batch-request.js'; +export * from '@/types/link-create-request.js'; +export * from '@/types/link-delete-request.js'; +export * from '@/types/link-list-request.js'; +export * from '@/types/link.js'; +export * from '@/types/links-paginated.js'; export * from '@/types/localazy-ai-engine-name.js'; export * from '@/types/locales-keys.js'; export * from '@/types/mt-suggestion.js'; export * from '@/types/mt-suggestions-response.js'; +export * from '@/types/organization-search-request.js'; +export * from '@/types/organization-search-response.js'; +export * from '@/types/organization-usage-request.js'; +export * from '@/types/organization-usage.js'; export * from '@/types/organization.js'; export * from '@/types/plural-class.js'; export * from '@/types/plural-marker.js'; +export * from '@/types/plurals-list-request.js'; +export * from '@/types/plurals.js'; +export * from '@/types/project-create-request.js'; +export * from '@/types/project-create-response.js'; +export * from '@/types/project-custom-role.js'; +export * from '@/types/project-tag-list-request.js'; +export * from '@/types/project-tag.js'; export * from '@/types/project.js'; export * from '@/types/projects-list-request.js'; +export * from '@/types/published-list-request.js'; +export * from '@/types/published-record.js'; export * from '@/types/request-config.js'; +export * from '@/types/review-translation-response.js'; export * from '@/types/screenshot-create-request.js'; export * from '@/types/screenshot-delete-request.js'; export * from '@/types/screenshot-metadata.js'; @@ -108,6 +187,10 @@ export * from '@/types/screenshot-update-request.js'; export * from '@/types/screenshot.js'; export * from '@/types/screenshots-list-request.js'; export * from '@/types/screenshots-list-tags-request.js'; +export * from '@/types/segmentation-get-parent-request.js'; +export * from '@/types/segmentation-parent.js'; +export * from '@/types/styleguides-list-request.js'; +export * from '@/types/styleguides.js'; export * from '@/types/submit-translation-response.js'; export * from '@/types/suggestions-request.js'; export * from '@/types/tm-suggestion.js'; diff --git a/src/types/branch-analyze-merge-request.ts b/src/types/branch-analyze-merge-request.ts new file mode 100644 index 0000000..2c32856 --- /dev/null +++ b/src/types/branch-analyze-merge-request.ts @@ -0,0 +1,10 @@ +import type { BranchMergeDetail } from '@/types/branch-merge-detail.js'; +import type { BranchMergeRequest } from '@/types/branch-merge-request.js'; + +export type BranchAnalyzeMergeRequest = BranchMergeRequest & { + /** + * Lists to include besides the counts. They have no length limit, so a large project can give a + * large response. + */ + details?: BranchMergeDetail[]; +}; diff --git a/src/types/branch-create-request.ts b/src/types/branch-create-request.ts new file mode 100644 index 0000000..5a726d0 --- /dev/null +++ b/src/types/branch-create-request.ts @@ -0,0 +1,26 @@ +import type { Branch } from '@/types/branch.js'; +import type { Project } from '@/types/project.js'; + +export type BranchCreateRequest = { + /** + * Project object or Project ID of any branch of the project. + */ + project: Project | string; + + /** + * Name of the new branch: 2 to 32 characters from `a-z`, `0-9`, `_`, `-` and `.`, not starting + * with `_` or `-`. `main` is reserved. + */ + name: string; + + /** + * Branch to copy, by name or as a Branch object. Defaults to the branch that `project` addresses. + */ + source?: Branch | Pick | string; + + /** + * `true` copies only the settings of the source branch, without its keys and translations. + * Defaults to `false`: a full copy. + */ + empty?: boolean; +}; diff --git a/src/types/branch-delete-request.ts b/src/types/branch-delete-request.ts new file mode 100644 index 0000000..351dfb9 --- /dev/null +++ b/src/types/branch-delete-request.ts @@ -0,0 +1,14 @@ +import type { Branch } from '@/types/branch.js'; +import type { Project } from '@/types/project.js'; + +export type BranchDeleteRequest = { + /** + * Project object or Project ID of any branch of the project, including the one being deleted. + */ + project: Project | string; + + /** + * Branch to delete, by name or as a Branch object. + */ + branch: Branch | Pick | string; +}; diff --git a/src/types/branch-get-operation-request.ts b/src/types/branch-get-operation-request.ts new file mode 100644 index 0000000..2f7a833 --- /dev/null +++ b/src/types/branch-get-operation-request.ts @@ -0,0 +1,13 @@ +import type { Project } from '@/types/project.js'; + +export type BranchGetOperationRequest = { + /** + * Project object or Project ID of any branch of the project that started the operation. + */ + project: Project | string; + + /** + * Operation ID returned by `branches.create()` or `branches.merge()`. + */ + operation: string; +}; diff --git a/src/types/branch-list-request.ts b/src/types/branch-list-request.ts new file mode 100644 index 0000000..ae9f9fb --- /dev/null +++ b/src/types/branch-list-request.ts @@ -0,0 +1,8 @@ +import type { Project } from '@/types/project.js'; + +export type BranchListRequest = { + /** + * Project object or Project ID of the main branch or of any other branch. + */ + project: Project | string; +}; diff --git a/src/types/branch-merge-analysis.ts b/src/types/branch-merge-analysis.ts new file mode 100644 index 0000000..f01d0cd --- /dev/null +++ b/src/types/branch-merge-analysis.ts @@ -0,0 +1,157 @@ +export type BranchMergeLanguageChanges = { + /** + * Locale code. + */ + lang: string; + + /** + * Translations of keys the target branch does not have; the merge creates these keys. + */ + newKeys: number; + + /** + * Translations of existing target keys that have no translation in this language there. + */ + newTranslations: number; + + /** + * Translations the merge replaces in the target branch. + */ + updated: number; + + /** + * Translations that are equal in both branches. + */ + equal: number; + + /** + * Differing translations the strategy did not resolve; the merge leaves them unchanged. + */ + conflicts: number; + + /** + * Translations the merge cannot apply, e.g. a plural value for a key that is not plural in the + * target branch. + */ + failures: number; + + /** + * Conflicts resolved with the source value. + */ + resolvedFromSource: number; + + /** + * Conflicts resolved with the target value, which the merge writes back to the source branch. + */ + resolvedFromTarget: number; +}; + +export type BranchMergeConflict = { + /** + * Locale code. + */ + lang: string; + + /** + * File display name. + */ + file: string; + + /** + * Key name as a list of segments. + */ + key: string[]; + + /** + * Key ID in the source branch. + */ + sourceKeyId: string; + + /** + * Key ID in the target branch. + */ + targetKeyId: string; + + /** + * Shortened preview of the source value: a string is cut after 240 characters; an array or plural + * value gives one `item: text` line per item, each cut after 80 characters. Absent when there is + * no value. Read the full value through `keys` endpoints of the branch project. + */ + sourceValue?: string; + + /** + * Preview of the target value, in the same form as `sourceValue`. + */ + targetValue?: string; +}; + +export type BranchMergeFailure = { + /** + * Locale code. + */ + lang: string; + + /** + * File display name. + */ + file: string; + + /** + * Key name as a list of segments. + */ + key: string[]; + + /** + * Key ID in the source branch. + */ + sourceKeyId: string; + + /** + * Key ID in the target branch. + */ + targetKeyId: string; + + /** + * Cause, as an English sentence. + */ + reason: string; + + /** + * `true` when the target has no translation in this language and the value clashes with the + * target key's source-language value; `false` when it clashes with the target translation. + */ + againstSourceLanguage: boolean; +}; + +export type BranchMergeAnalysis = { + /** + * Counts per language that has at least one processed translation, ordered by locale code. + */ + languages: BranchMergeLanguageChanges[]; + + /** + * Display names of files the merge creates in the target branch. + */ + newFiles: string[]; + + /** + * Locale codes of languages the merge adds to the target branch. + */ + newLanguages: string[]; + + /** + * Keys the merge deprecates in the target branch. Always `0` without `deprecateMissing` and + * `mergeDeprecations`. + */ + deprecatedKeys: number; + + /** + * Present only when `details` includes `conflicts`. + */ + conflicts?: BranchMergeConflict[]; + + /** + * Present only when `details` includes `failures`. + */ + failures?: BranchMergeFailure[]; +}; diff --git a/src/types/branch-merge-detail.ts b/src/types/branch-merge-detail.ts new file mode 100644 index 0000000..96cf1b6 --- /dev/null +++ b/src/types/branch-merge-detail.ts @@ -0,0 +1,4 @@ +/** + * Optional list a merge analysis includes: `conflicts` or `failures`. The counts are always present. + */ +export type BranchMergeDetail = 'conflicts' | 'failures'; diff --git a/src/types/branch-merge-request.ts b/src/types/branch-merge-request.ts new file mode 100644 index 0000000..68dd62b --- /dev/null +++ b/src/types/branch-merge-request.ts @@ -0,0 +1,85 @@ +import type { Branch } from '@/types/branch.js'; +import type { BranchMergeStrategy } from '@/types/branch-merge-strategy.js'; +import type { Key } from '@/types/key.js'; +import type { Project } from '@/types/project.js'; + +export type BranchMergeRequest = { + /** + * Project object or Project ID of any branch of the project. + */ + project: Project | string; + + /** + * Source branch, the one that gives the changes, by name or as a Branch object. + */ + branch: Branch | Pick | string; + + /** + * Target branch, the one that receives the changes. Must differ from `branch`. + */ + target: Branch | Pick | string; + + /** + * Defaults to `skip`. + */ + strategy?: BranchMergeStrategy; + + /** + * Languages to process, as locale codes (`pt_BR`) or numeric language IDs. Defaults to all + * languages of the source branch that are not hidden. Must not be empty. + */ + languages?: string[]; + + /** + * Keys of the source branch to process. IDs that are not keys of the source branch are ignored. + * Defaults to all keys. Must not be empty. + */ + keys?: (Key | Pick | string)[]; + + /** + * Create files the target branch does not have. Defaults to `true`; with `false`, translations + * that need a new file are left out. + */ + createFiles?: boolean; + + /** + * Add languages the target branch does not have. Defaults to `true`; with `false`, translations + * that need a new language are left out. + */ + createLanguages?: boolean; + + /** + * Create keys the target branch does not have. Defaults to `true`. + */ + createKeys?: boolean; + + /** + * Leave alone every key and language that already has a translation in the target branch. + * Defaults to `false`. + */ + skipExisting?: boolean; + + /** + * Process only differing translations; add no keys and no translations. Defaults to `false`. + */ + conflictsOnly?: boolean; + + /** + * Deprecate target keys that the source branch does not have. Applies only when the source + * language is processed, and cannot be combined with `keys`. Defaults to `false`. + */ + deprecateMissing?: boolean; + + /** + * Deprecate target keys that are deprecated in the source branch; keys only in the target stay + * active. Applies only when the source language is processed and, with `keys`, only to those keys. + * Defaults to `false`. + */ + mergeDeprecations?: boolean; + + /** + * Count the conflicts the strategy did not resolve. Defaults to `true`; `false` leaves them out of + * the counts and of the conflict list. + */ + reportConflicts?: boolean; +}; diff --git a/src/types/branch-merge-strategy.ts b/src/types/branch-merge-strategy.ts new file mode 100644 index 0000000..944a136 --- /dev/null +++ b/src/types/branch-merge-strategy.ts @@ -0,0 +1,11 @@ +/** + * How a merge handles a translation that differs between the two branches: + * - `skip`: every difference is a conflict and stays as it is. + * - `reference`: updates the target when it still has the value the source started from; + * otherwise a conflict. + * - `time`: the source value wins when it is newer; otherwise a conflict. + * - `time-bidi`: as `time`, and a newer target value is written back to the source branch. + * - `source`: the source value always wins. + * - `target`: the target value always wins and is written back to the source branch. + */ +export type BranchMergeStrategy = 'skip' | 'reference' | 'time' | 'time-bidi' | 'source' | 'target'; diff --git a/src/types/branch-operation-status.ts b/src/types/branch-operation-status.ts new file mode 100644 index 0000000..330db60 --- /dev/null +++ b/src/types/branch-operation-status.ts @@ -0,0 +1,47 @@ +/** + * State of a branch operation: + * - `scheduled`, `in_progress`: still running; poll again. + * - `done`: finished. + * - `error`: stopped on an internal error; a merge may have been applied in part. + * - `invalid_id`: the ID is unknown, expired (statuses are kept for 48 hours), or not an operation + * this project started through the API. + */ +export type BranchOperationState = 'scheduled' | 'in_progress' | 'done' | 'error' | 'invalid_id'; + +/** + * The merge counts are present only for a merge that is `done`. + */ +export type BranchOperationStatus = { + status: BranchOperationState; + + /** + * New keys, new translations and updated translations in the target branch, excluding resolved + * conflicts. + */ + changes?: number; + + /** + * Conflicts the strategy resolved with the source or the target value. + */ + resolved?: number; + + /** + * Conflicts the merge left unresolved. List them with `branches.analyzeMerge()`. + */ + conflicts?: number; + + /** + * Translations the merge could not apply. + */ + failures?: number; + + /** + * Files the merge created in the target branch. + */ + newFiles?: number; + + /** + * Languages the merge added to the target branch. + */ + newLanguages?: number; +}; diff --git a/src/types/branch-rename-request.ts b/src/types/branch-rename-request.ts new file mode 100644 index 0000000..09c7a58 --- /dev/null +++ b/src/types/branch-rename-request.ts @@ -0,0 +1,19 @@ +import type { Branch } from '@/types/branch.js'; +import type { Project } from '@/types/project.js'; + +export type BranchRenameRequest = { + /** + * Project object or Project ID of any branch of the project. + */ + project: Project | string; + + /** + * Branch to rename, by name or as a Branch object. The main branch cannot be renamed. + */ + branch: Branch | Pick | string; + + /** + * New name, with the same rules as the name of a new branch. + */ + name: string; +}; diff --git a/src/types/branch-separate-request.ts b/src/types/branch-separate-request.ts new file mode 100644 index 0000000..fc8fe02 --- /dev/null +++ b/src/types/branch-separate-request.ts @@ -0,0 +1,14 @@ +import type { Branch } from '@/types/branch.js'; +import type { Project } from '@/types/project.js'; + +export type BranchSeparateRequest = { + /** + * Project object or Project ID of any branch of the project. + */ + project: Project | string; + + /** + * Branch to turn into an independent project, by name or as a Branch object. + */ + branch: Branch | Pick | string; +}; diff --git a/src/types/branch-set-main-request.ts b/src/types/branch-set-main-request.ts new file mode 100644 index 0000000..889bcd6 --- /dev/null +++ b/src/types/branch-set-main-request.ts @@ -0,0 +1,19 @@ +import type { Branch } from '@/types/branch.js'; +import type { Project } from '@/types/project.js'; + +export type BranchSetMainRequest = { + /** + * Project object or Project ID of any branch of the project. + */ + project: Project | string; + + /** + * Branch that becomes `main`, by name or as a Branch object. + */ + branch: Branch | Pick | string; + + /** + * New name of the branch that is `main` now, with the same rules as the name of a new branch. + */ + name: string; +}; diff --git a/src/types/branch.ts b/src/types/branch.ts new file mode 100644 index 0000000..1ee77f7 --- /dev/null +++ b/src/types/branch.ts @@ -0,0 +1,31 @@ +/** + * One branch of a project. Each branch is a project of its own, with its own ID, tokens and members. + */ +export type Branch = { + /** + * Branch name. The main branch is always `main`; the other branch endpoints address branches by + * this name. + */ + name: string; + + /** + * ID of the project that holds the content of the branch. Pass it as `project` to the other + * endpoints to read or change keys, translations and files of the branch. + */ + projectId: string; + + /** + * Slug of the branch project, e.g. `mobile-app!release-2`. + */ + slug: string; + + /** + * `true` for the main branch. + */ + main: boolean; + + /** + * Name of the branch this branch was made from. Absent for the main branch. + */ + source?: string; +}; diff --git a/src/types/cdn-list-request.ts b/src/types/cdn-list-request.ts new file mode 100644 index 0000000..ec16701 --- /dev/null +++ b/src/types/cdn-list-request.ts @@ -0,0 +1,8 @@ +import type { Project } from '@/types/project.js'; + +export type CdnListRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; +}; diff --git a/src/types/cdn-metadata.ts b/src/types/cdn-metadata.ts new file mode 100644 index 0000000..a848046 --- /dev/null +++ b/src/types/cdn-metadata.ts @@ -0,0 +1,28 @@ +export type CdnTagMetadata = { + /** + * Release tag ID; `_e0` for `latest`. + */ + tagId: string; + + /** + * Release tag name. + */ + tagName: string; + + /** + * Public `delivery.localazy.com` URL of the tag's `.v2.json` metadata file. + */ + metadataUrl: string; +}; + +export type CdnMetadata = { + /** + * Whether the CDN is enabled for the project. When `false`, `metadataUrls` is empty. + */ + enabled: boolean; + + /** + * One entry per published release tag, plus `latest`. + */ + metadataUrls: CdnTagMetadata[]; +}; diff --git a/src/types/comment-create-request.ts b/src/types/comment-create-request.ts new file mode 100644 index 0000000..379b354 --- /dev/null +++ b/src/types/comment-create-request.ts @@ -0,0 +1,26 @@ +import type { Key } from '@/types/key.js'; +import type { Project } from '@/types/project.js'; +import type { Locales } from '@localazy/languages'; + +export type CommentCreateRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * Key object or Key ID. + */ + key: Key | string; + + /** + * The language of the discussion, as a locale code (e.g. `pt_BR`) or Localazy's numeric language + * id (e.g. `112`). It may be the source language, but must be a language of the project. + */ + lang: `${Locales}` | number; + + /** + * 1 to 2000 characters, not only white space. Stored as sent. + */ + text: string; +}; diff --git a/src/types/comment-delete-request.ts b/src/types/comment-delete-request.ts new file mode 100644 index 0000000..b396a1f --- /dev/null +++ b/src/types/comment-delete-request.ts @@ -0,0 +1,26 @@ +import type { KeyComment } from '@/types/key-comment.js'; +import type { Key } from '@/types/key.js'; +import type { Project } from '@/types/project.js'; +import type { Locales } from '@localazy/languages'; + +export type CommentDeleteRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * Key object or Key ID; must be the key of the comment. + */ + key: Key | string; + + /** + * The language of the comment, as a locale code or Localazy's numeric language id. + */ + lang: `${Locales}` | number; + + /** + * Comment object or Comment ID. + */ + comment: KeyComment | string; +}; diff --git a/src/types/comment-list-request.ts b/src/types/comment-list-request.ts new file mode 100644 index 0000000..f2219b8 --- /dev/null +++ b/src/types/comment-list-request.ts @@ -0,0 +1,21 @@ +import type { Key } from '@/types/key.js'; +import type { Project } from '@/types/project.js'; +import type { Locales } from '@localazy/languages'; + +export type CommentListRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * Key object or Key ID. + */ + key: Key | string; + + /** + * The language of the discussion, as a locale code (e.g. `pt_BR`) or Localazy's numeric language + * id (e.g. `112`). It may be the source language. + */ + lang: `${Locales}` | number; +}; diff --git a/src/types/comment-update-request.ts b/src/types/comment-update-request.ts new file mode 100644 index 0000000..4fe3851 --- /dev/null +++ b/src/types/comment-update-request.ts @@ -0,0 +1,31 @@ +import type { KeyComment } from '@/types/key-comment.js'; +import type { Key } from '@/types/key.js'; +import type { Project } from '@/types/project.js'; +import type { Locales } from '@localazy/languages'; + +export type CommentUpdateRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * Key object or Key ID; must be the key of the comment. + */ + key: Key | string; + + /** + * The language of the comment, as a locale code or Localazy's numeric language id. + */ + lang: `${Locales}` | number; + + /** + * Comment object or Comment ID. + */ + comment: KeyComment | string; + + /** + * The new text: 1 to 2000 characters, not only white space. + */ + text: string; +}; diff --git a/src/types/credit-balance.ts b/src/types/credit-balance.ts new file mode 100644 index 0000000..4595dbf --- /dev/null +++ b/src/types/credit-balance.ts @@ -0,0 +1,25 @@ +/** + * Credit balance of a billing organization. All values are decimal strings; parse them with a + * decimal type, not `parseFloat`, to keep the precision. + */ +export type CreditBalance = { + /** + * Current credit balance. + */ + balance: string; + + /** + * The allowance granted by the most recent plan refill. Not a cap on the total credits. + */ + limit: string; + + /** + * Credits spent from that allowance since the refill. + */ + limitSince: string; + + /** + * What is left of the allowance: `limit` minus `limitSince`, never negative. + */ + limitRemaining: string; +}; diff --git a/src/types/credit-summary-request.ts b/src/types/credit-summary-request.ts new file mode 100644 index 0000000..ec45a58 --- /dev/null +++ b/src/types/credit-summary-request.ts @@ -0,0 +1,37 @@ +/** + * A key to group credit consumption by. `user` yields `userId` or `automationId`; `language` yields + * `fromLanguage` and `toLanguage`. + */ +export type CreditGroupBy = + | 'day' + | 'month' + | 'project' + | 'user' + | 'action' + | 'category' + | 'source' + | 'language'; + +export type CreditSummaryRequest = { + /** + * Organization ID or slug. + */ + organization: string; + + /** + * Start of the period (inclusive): an ISO 8601 date (`2026-11-01`, midnight UTC) or date-time. + * Default: `to` minus 30 days. The period may be at most 366 days long. + */ + from?: string | Date; + + /** + * End of the period (exclusive), same format as `from`. Default and maximum: now minus 60 seconds. + */ + to?: string | Date; + + /** + * Group keys, each at most once, and not both `day` and `month`. Groups by `day` when omitted; + * an empty list gives the totals only. + */ + groupBy?: CreditGroupBy[]; +}; diff --git a/src/types/credit-summary-response.ts b/src/types/credit-summary-response.ts new file mode 100644 index 0000000..c01aeda --- /dev/null +++ b/src/types/credit-summary-response.ts @@ -0,0 +1,100 @@ +import type { CreditBalance } from '@/types/credit-balance.js'; +import type { CreditCategory, CreditSource } from '@/types/credit-transactions.js'; + +/** + * Consumption of one group. Only the keys requested in `groupBy` are present, and a key without a + * value (e.g. `projectId` of a `system` cost) is omitted. + */ +export type CreditSummaryGroup = { + /** + * UTC day, `YYYY-MM-DD`. + */ + day?: string; + + /** + * UTC month, `YYYY-MM`. + */ + month?: string; + + projectId?: string; + + userId?: string; + + automationId?: string; + + action?: string; + + category?: CreditCategory; + + source?: CreditSource; + + fromLanguage?: string; + + toLanguage?: string; + + /** + * Credits spent in the group, excluding category `system` (decimal string). + */ + spent: string; + + /** + * Costs of category `system` in the group (decimal string). + */ + adjusted: string; + + volume: number; + + transactions: number; +}; + +export type CreditSummaryResponse = { + /** + * The billing organization of the data. For a team, its parent organization. + */ + organizationId: string; + + /** + * Start of the period the server used, ISO 8601 UTC. + */ + from: string; + + /** + * End of the period the server used, ISO 8601 UTC. + */ + to: string; + + /** + * Current balance, independent of the period. + */ + balance: CreditBalance; + + /** + * Credits spent in the period, excluding category `system`; the figure to monitor (decimal string). + */ + spent: string; + + /** + * Costs of category `system`: trial credit reclaim and negative balance cover (decimal string). + */ + adjusted: string; + + /** + * Credits added in the period. The balance change is `toppedUp - spent - adjusted` (decimal string). + */ + toppedUp: string; + + /** + * Number of cost rows in the period. + */ + transactions: number; + + /** + * Sum of the volumes in the period. + */ + volume: number; + + /** + * Groups sorted by the keys in `groupBy` order. Empty when `groupBy` is empty. + */ + groups: CreditSummaryGroup[]; +}; diff --git a/src/types/credit-topups-list-request.ts b/src/types/credit-topups-list-request.ts new file mode 100644 index 0000000..30acd26 --- /dev/null +++ b/src/types/credit-topups-list-request.ts @@ -0,0 +1,17 @@ +export type CreditTopupsListRequest = { + /** + * Organization ID or slug. + */ + organization: string; + + /** + * Start of the period (inclusive): an ISO 8601 date (`2026-11-01`, midnight UTC) or date-time. + * Default: `to` minus 30 days. The period may be at most 366 days long. + */ + from?: string | Date; + + /** + * End of the period (exclusive), same format as `from`. Default and maximum: now minus 60 seconds. + */ + to?: string | Date; +}; diff --git a/src/types/credit-topups-response.ts b/src/types/credit-topups-response.ts new file mode 100644 index 0000000..d8863ac --- /dev/null +++ b/src/types/credit-topups-response.ts @@ -0,0 +1,50 @@ +/** + * Kind of a credit topup: + * - `plan`: refill of the plan allowance. + * - `extra`: credits outside the plan (purchase, bonus). + * - `balance_cover`: cover of a negative balance at a plan refill, booked together with an equal + * `adjusted` cost, so the pair leaves the balance unchanged. + */ +export type CreditTopupType = 'plan' | 'extra' | 'balance_cover'; + +export type CreditTopup = { + /** + * Time of the topup, ISO 8601 UTC. + */ + ts: string; + + type: CreditTopupType; + + /** + * Credits added (decimal string). For `plan` this is the part the refill added: 0 when nothing was + * spent since the last refill, negative after a move to a smaller plan. + */ + amount: string; + + /** + * The plan allowance (decimal string). Only for `plan`. + */ + limit?: string; +}; + +export type CreditTopupsResponse = { + /** + * The billing organization of the data. For a team, its parent organization. + */ + organizationId: string; + + /** + * Start of the period the server used, ISO 8601 UTC. + */ + from: string; + + /** + * End of the period the server used, ISO 8601 UTC. + */ + to: string; + + /** + * Topups in time order, with no paging. + */ + topups: CreditTopup[]; +}; diff --git a/src/types/credit-transactions-list-request.ts b/src/types/credit-transactions-list-request.ts new file mode 100644 index 0000000..eb5adc8 --- /dev/null +++ b/src/types/credit-transactions-list-request.ts @@ -0,0 +1,28 @@ +export type CreditTransactionsListRequest = { + /** + * Organization ID or slug. + */ + organization: string; + + /** + * Start of the period (inclusive): an ISO 8601 date (`2026-11-01`, midnight UTC) or date-time. + * Default: `to` minus 30 days. The period may be at most 366 days long. Ignored with `next`. + */ + from?: string | Date; + + /** + * End of the period (exclusive), same format as `from`. Default and maximum: now minus 60 seconds. + * Pass the same value with `next` as with the first page. + */ + to?: string | Date; + + /** + * Page size, 1 to 10000. Default 1000. + */ + limit?: number; + + /** + * The `next` value of the previous page. + */ + next?: string; +}; diff --git a/src/types/credit-transactions-paginated.ts b/src/types/credit-transactions-paginated.ts new file mode 100644 index 0000000..6b033b4 --- /dev/null +++ b/src/types/credit-transactions-paginated.ts @@ -0,0 +1,8 @@ +import type { CreditTransactions } from '@/types/credit-transactions.js'; + +export type CreditTransactionsPaginated = CreditTransactions & { + /** + * Cursor of the next page. Not present on the last page. + */ + next?: string; +}; diff --git a/src/types/credit-transactions.ts b/src/types/credit-transactions.ts new file mode 100644 index 0000000..1125768 --- /dev/null +++ b/src/types/credit-transactions.ts @@ -0,0 +1,84 @@ +/** + * Kind of a credit cost. `system` covers balance adjustments (trial credit reclaim, negative balance + * cover). `unknown` stands for a value newer than the API documentation. + */ +export type CreditCategory = 'mt' | 'ai' | 'clt' | 'system' | 'none' | 'unknown'; + +/** + * What started a credit cost. `unknown` stands for a value newer than the API documentation. + */ +export type CreditSource = + | 'batch' + | 'automations' + | 'clt' + | 'system' + | 'suggestions' + | 'api' + | 'none' + | 'unknown'; + +export type CreditTransaction = { + /** + * Time of the charge, ISO 8601 UTC with up to 6 fraction digits. + */ + ts: string; + + /** + * Cost in credits (decimal string). + */ + amount: string; + + /** + * Volume of the charge, usually the number of words. + */ + volume: number; + + category: CreditCategory; + + /** + * The engine or service, e.g. `localazyAi`, `deepl`, `clt_translate` or `balance`. + */ + action: string; + + source: CreditSource; + + projectId?: string; + + keyId?: string; + + fromLanguage?: string; + + toLanguage?: string; + + /** + * Present when a user started the charge. + */ + userId?: string; + + /** + * Present when an automation started the charge. + */ + automationId?: string; +}; + +export type CreditTransactions = { + /** + * The billing organization of the data. For a team, its parent organization. + */ + organizationId: string; + + /** + * Start of the period the server used, ISO 8601 UTC. + */ + from: string; + + /** + * End of the period the server used, ISO 8601 UTC. Pass it as `from` of the next incremental sync. + */ + to: string; + + /** + * One row per charge, in time order. + */ + transactions: CreditTransaction[]; +}; diff --git a/src/types/file.ts b/src/types/file.ts index 494eaab..1f092fa 100644 --- a/src/types/file.ts +++ b/src/types/file.ts @@ -24,10 +24,15 @@ export type File = { */ module?: string; + /** + * The library the file belongs to. Optional and only available if provided. + */ + library?: string; + /** * A list of associated product flavors. Optional and only available if provided. */ - productFlavors?: string; + productFlavors?: string[]; /** * A build type the file is associated with. Optional and only available if provided. diff --git a/src/types/glossary-create-many-request.ts b/src/types/glossary-create-many-request.ts new file mode 100644 index 0000000..8530800 --- /dev/null +++ b/src/types/glossary-create-many-request.ts @@ -0,0 +1,42 @@ +import type { GlossaryRecordTerm } from '@/types/glossary-record-term.js'; +import type { Project } from '@/types/project.js'; + +/** + * One term of a batch. An omitted option keeps the existing value when the item merges into an + * existing term, and takes the server default when a new term is created. + */ +export type GlossaryCreateManyItem = { + /** + * The term and its translations. Include the source language: it identifies duplicates. + */ + term: GlossaryRecordTerm[]; + + /** + * Defaults to `''` for a new term. + */ + description?: string; + + /** + * Defaults to `true` for a new term. + */ + translateTerm?: boolean; + + /** + * Defaults to `false` for a new term; when omitted, duplicates are matched case-insensitively. + */ + caseSensitive?: boolean; + + /** + * Defaults to `true` for a new term; when omitted, an existing term with either value matches. + */ + exactMatch?: boolean; +}; + +export type GlossaryCreateManyRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + terms: GlossaryCreateManyItem[]; +}; diff --git a/src/types/glossary-create-many-response.ts b/src/types/glossary-create-many-response.ts new file mode 100644 index 0000000..79a26a2 --- /dev/null +++ b/src/types/glossary-create-many-response.ts @@ -0,0 +1,25 @@ +/** + * What a batch did with each item. Each list names items by their source-language text, in request + * order. + */ +export type GlossaryCreateManyResponse = { + /** + * Always `true`; a batch that cannot be applied is rejected instead. + */ + result: boolean; + + /** + * Items created as new terms. + */ + created: string[]; + + /** + * Items merged into an existing term that they changed. + */ + updated: string[]; + + /** + * Items that changed nothing or repeated an earlier item of the batch. + */ + skipped: string[]; +}; diff --git a/src/types/key-comment.ts b/src/types/key-comment.ts new file mode 100644 index 0000000..944465b --- /dev/null +++ b/src/types/key-comment.ts @@ -0,0 +1,23 @@ +export type KeyComment = { + /** + * Comment ID. + */ + id: string; + + /** + * ID of the user that wrote the comment. + */ + userId: string; + + text: string; + + /** + * `true` when the author changed the comment after writing it. + */ + edited: boolean; + + /** + * Time of the last change, ISO 8601 in UTC. + */ + updatedAt: string; +}; diff --git a/src/types/key-details-request.ts b/src/types/key-details-request.ts new file mode 100644 index 0000000..db27f50 --- /dev/null +++ b/src/types/key-details-request.ts @@ -0,0 +1,22 @@ +import type { Key } from '@/types/key.js'; +import type { Project } from '@/types/project.js'; +import type { Locales } from '@localazy/languages'; + +export type KeyDetailsRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * Keys to read, 1 to 100 per call. A cluster-qualified ID (`keyId:clusterKeyId`) is accepted; the + * cluster part is ignored. + */ + keys: (Key | Pick | string)[]; + + /** + * The language of the translation, as a locale code (e.g. `pt_BR`) or Localazy's numeric language + * id (e.g. `112`). For the source language, `translation` describes the source text. + */ + lang: `${Locales}` | number; +}; diff --git a/src/types/key-details-response.ts b/src/types/key-details-response.ts new file mode 100644 index 0000000..cf594b2 --- /dev/null +++ b/src/types/key-details-response.ts @@ -0,0 +1,166 @@ +import type { File } from '@/types/file.js'; +import type { KeyComment } from '@/types/key-comment.js'; +import type { KeyPriority } from '@/types/key-priority.js'; +import type { KeyState } from '@/types/key-state.js'; +import type { KeyValue } from '@/types/key-value.js'; +import type { ProjectTag } from '@/types/project-tag.js'; + +/** + * The current source text of a key. + */ +export type KeyDetailSource = { + /** + * Locale code of the source language. + */ + lang: string; + + /** + * A string, an array of strings, or for a plural key an object keyed by `@`-prefixed plural class. + */ + value: KeyValue; + + /** + * Plural classes the source language uses in the project. Only for a plural key. + */ + pluralForms?: string[]; +}; + +/** + * A version of a key that waits for a review. + */ +export type KeyDetailReview = { + /** + * Version ID; pass it to `keys.reviewTranslation()`. + */ + versionId: string; + + /** + * `null` when the stored value can't be read. + */ + value: KeyValue | null; + + /** + * ID of the user that wrote the version. + */ + userId: string; +}; + +/** + * A key in the requested language. `value` and `authorId` describe the current (approved) + * version and are absent when the language has none. + */ +export type KeyDetailTranslation = { + /** + * Locale code of the requested language. + */ + lang: string; + + value?: KeyValue; + + /** + * Plural classes the requested language uses in the project. Only for a plural key. + */ + pluralForms?: string[]; + + /** + * ID of the user that wrote the current version. + */ + authorId?: string; + + state: KeyState; + + /** + * The newest version that waits for a review; absent when none does. + */ + review?: KeyDetailReview; +}; + +export type KeyDetail = { + /** + * Key ID. + */ + id: string; + + /** + * The key's path as a list of segments. + */ + key: string[]; + + /** + * Shape of the key's values. Absent when the key has no value at all. + */ + type?: 'string' | 'array' | 'plural'; + + /** + * The file that holds the key. + */ + file?: File; + + deprecated: boolean; + + hidden: boolean; + + /** + * Maximum length of a translation, or `-1` for no limit. + */ + limit: number; + + /** + * The developer comment that came with the key from the import; `''` when there is none. + */ + comment: string; + + /** + * The note written for the key in Localazy (what `keys.update()` sets as `comment`); `''` when + * there is none. + */ + contextNote: string; + + priority: KeyPriority; + + /** + * Tags of the key, the priority tag included. + */ + tags: Omit[]; + + /** + * Absent when the key has no source text. + */ + source?: KeyDetailSource; + + translation: KeyDetailTranslation; + + /** + * Discussion of the key in the requested language, newest first. Reading it does not mark the + * comments as read. + */ + comments: KeyComment[]; +}; + +/** + * Why a requested key has no details: + * - `not_found`: the project has no such key (also a deleted key or one of another project). + * - `segmented_key`: the ID is a segmented key as a whole; request its segments instead. + */ +export type KeyDetailErrorCode = 'not_found' | 'segmented_key'; + +export type KeyDetailError = { + /** + * Key ID as requested. + */ + id: string; + + error: KeyDetailErrorCode; +}; + +export type KeyDetailsResponse = { + /** + * Details of the requested keys that the project has, in request order. + */ + keys: KeyDetail[]; + + /** + * One entry per requested key that has no entry in `keys`. + */ + errors: KeyDetailError[]; +}; diff --git a/src/types/key-edit-source-request.ts b/src/types/key-edit-source-request.ts new file mode 100644 index 0000000..e5565a1 --- /dev/null +++ b/src/types/key-edit-source-request.ts @@ -0,0 +1,27 @@ +import type { Key } from '@/types/key.js'; +import type { Project } from '@/types/project.js'; +import type { TranslationValue } from '@/types/translation-value.js'; + +export type KeyEditSourceRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * Key object or Key ID. + */ + key: Key | string; + + /** + * The new source text. Its shape must match the key's form, as for `keys.submitTranslation()`; + * a plural value needs an entry for each plural class of the source language. + */ + value: TranslationValue; + + /** + * Whether translations get the `sourceChanged` state when the new text becomes current and + * differs. Defaults to `true`; pass `false` for a change that doesn't affect meaning, like a typo. + */ + sourceChanged?: boolean; +}; diff --git a/src/types/key-review-translation-request.ts b/src/types/key-review-translation-request.ts new file mode 100644 index 0000000..397dd09 --- /dev/null +++ b/src/types/key-review-translation-request.ts @@ -0,0 +1,42 @@ +import type { Key } from '@/types/key.js'; +import type { Project } from '@/types/project.js'; +import type { Locales } from '@localazy/languages'; + +/** + * - `approve`: the version becomes current, and the other versions that wait for a review are + * rejected. + * - `reject`: the version is rejected. The current version cannot be rejected. + */ +export type KeyReviewAction = 'approve' | 'reject'; + +export type KeyReviewTranslationRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * Key object or Key ID. + */ + key: Key | string; + + /** + * The language of the version, as a locale code (e.g. `pt_BR`) or Localazy's numeric language id + * (e.g. `112`). It may be the source language. + */ + lang: `${Locales}` | number; + + /** + * ID of a version of this key in `lang`, e.g. `translation.review.versionId` of + * `keys.getDetails()`. + */ + versionId: string; + + action: KeyReviewAction; + + /** + * Only for approving a source-language version that changes the source text: whether the + * translations get the `sourceChanged` state. Defaults to `true`. + */ + sourceChanged?: boolean; +}; diff --git a/src/types/key-state.ts b/src/types/key-state.ts new file mode 100644 index 0000000..180ad91 --- /dev/null +++ b/src/types/key-state.ts @@ -0,0 +1,24 @@ +/** + * The state of a key in one language, as four independent flags. + */ +export type KeyState = { + /** + * An approved version exists, or a version waits for a review. + */ + translated: boolean; + + /** + * A version waits for a review. + */ + needReview: boolean; + + /** + * The source text changed after the translation was made. + */ + sourceChanged: boolean; + + /** + * A reviewer marked the translation as needing improvement. + */ + needImprovement: boolean; +}; diff --git a/src/types/key-update-request.ts b/src/types/key-update-request.ts index 0e12045..80b51fb 100644 --- a/src/types/key-update-request.ts +++ b/src/types/key-update-request.ts @@ -19,12 +19,13 @@ export type KeyUpdateRequest = { deprecated?: number; /** - * Set to true to mark the key as hidden on Localazy. + * Set to true to mark the key as hidden on Localazy. A key linked to another key stays hidden. */ hidden?: boolean; /** - * Provide custom comment for translators. + * The context note for translators, reported as `contextNote` by `keys.getDetails()`. The + * developer comment that came with the key from the import is not changed. */ comment?: string; diff --git a/src/types/language-add-response.ts b/src/types/language-add-response.ts new file mode 100644 index 0000000..e3d4c5e --- /dev/null +++ b/src/types/language-add-response.ts @@ -0,0 +1,12 @@ +import type { LanguageBatchResponse } from '@/types/language-batch-response.js'; + +/** + * What adding did with a language: + * - `created`: the language was not in the project and was added empty. + * - `restored`: the language was hidden and is listed again with its previous translations, and + * published even if it was disabled before it was hidden. + * - `unchanged`: the language was already listed; nothing was touched. + */ +export type LanguageAddState = 'created' | 'restored' | 'unchanged'; + +export type LanguageAddResponse = LanguageBatchResponse; diff --git a/src/types/language-batch-response.ts b/src/types/language-batch-response.ts new file mode 100644 index 0000000..4b4e3fa --- /dev/null +++ b/src/types/language-batch-response.ts @@ -0,0 +1,26 @@ +export type LanguageBatchResult = { + /** + * Numeric ID of the resolved language. + */ + id: number; + + /** + * Locale code the request resolved to. Compare it with what you sent: an unknown region falls back + * to the plain language. + */ + code: string; + + state: TState; +}; + +export type LanguageBatchResponse = { + /** + * Always `true`; a request that cannot be applied is rejected instead. + */ + result: boolean; + + /** + * One entry per distinct resolved language, in the order of the request. + */ + languages: LanguageBatchResult[]; +}; diff --git a/src/types/language-copy-request.ts b/src/types/language-copy-request.ts new file mode 100644 index 0000000..7f54276 --- /dev/null +++ b/src/types/language-copy-request.ts @@ -0,0 +1,20 @@ +import type { LanguageRef } from '@/types/language-ref.js'; +import type { Project } from '@/types/project.js'; + +export type LanguageCopyRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * The language to copy. It must be in the project and not hidden. + */ + from: LanguageRef; + + /** + * The language to create. It must not be in the project, unless it is hidden: then the + * translations it kept are destroyed before the copy. + */ + to: LanguageRef; +}; diff --git a/src/types/language-copy-response.ts b/src/types/language-copy-response.ts new file mode 100644 index 0000000..be7aa40 --- /dev/null +++ b/src/types/language-copy-response.ts @@ -0,0 +1,26 @@ +export type LanguageCopyResponse = { + /** + * Always `true`; a request that cannot be applied is rejected instead. + */ + result: boolean; + + /** + * The language the copy created. + */ + language: { + /** + * Numeric ID of the resolved language. + */ + id: number; + + /** + * Locale code the request resolved to. + */ + code: string; + + /** + * Always `created`. + */ + state: 'created'; + }; +}; diff --git a/src/types/language-delete-request.ts b/src/types/language-delete-request.ts new file mode 100644 index 0000000..6873aff --- /dev/null +++ b/src/types/language-delete-request.ts @@ -0,0 +1,14 @@ +import type { LanguageRef } from '@/types/language-ref.js'; +import type { Project } from '@/types/project.js'; + +export type LanguageDeleteRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * The language to delete together with all of its translations. + */ + lang: LanguageRef; +}; diff --git a/src/types/language-disable-response.ts b/src/types/language-disable-response.ts new file mode 100644 index 0000000..a85c725 --- /dev/null +++ b/src/types/language-disable-response.ts @@ -0,0 +1,10 @@ +import type { LanguageBatchResponse } from '@/types/language-batch-response.js'; + +/** + * What disabling did with a language: + * - `disabled`: the language was included in publishing and is now left out. + * - `unchanged`: the language was already left out. + */ +export type LanguageDisableState = 'disabled' | 'unchanged'; + +export type LanguageDisableResponse = LanguageBatchResponse; diff --git a/src/types/language-enable-response.ts b/src/types/language-enable-response.ts new file mode 100644 index 0000000..fabd89d --- /dev/null +++ b/src/types/language-enable-response.ts @@ -0,0 +1,10 @@ +import type { LanguageBatchResponse } from '@/types/language-batch-response.js'; + +/** + * What enabling did with a language: + * - `enabled`: the language was left out of publishing and is now included. + * - `unchanged`: the language was already included. + */ +export type LanguageEnableState = 'enabled' | 'unchanged'; + +export type LanguageEnableResponse = LanguageBatchResponse; diff --git a/src/types/language-hide-response.ts b/src/types/language-hide-response.ts new file mode 100644 index 0000000..1c086f2 --- /dev/null +++ b/src/types/language-hide-response.ts @@ -0,0 +1,10 @@ +import type { LanguageBatchResponse } from '@/types/language-batch-response.js'; + +/** + * What hiding did with a language: + * - `hidden`: the language was listed and is not any more; its translations are kept. + * - `unchanged`: the language was already hidden. + */ +export type LanguageHideState = 'hidden' | 'unchanged'; + +export type LanguageHideResponse = LanguageBatchResponse; diff --git a/src/types/language-key.ts b/src/types/language-key.ts new file mode 100644 index 0000000..6101269 --- /dev/null +++ b/src/types/language-key.ts @@ -0,0 +1,8 @@ +import type { Key } from '@/types/key.js'; + +export type LanguageKey = Key & { + /** + * ID of the file that holds the key; a key of `files` in the page. + */ + file?: string; +}; diff --git a/src/types/language-keys-paginated.ts b/src/types/language-keys-paginated.ts new file mode 100644 index 0000000..be1bb9c --- /dev/null +++ b/src/types/language-keys-paginated.ts @@ -0,0 +1,16 @@ +import type { File } from '@/types/file.js'; +import type { LanguageKey } from '@/types/language-key.js'; + +export type LanguageKeysPaginated = { + keys: LanguageKey[]; + + /** + * Paging cursor. Absent on the last page. + */ + next?: string; + + /** + * The files of the keys on this page, by file ID. A file can continue on the next page. + */ + files: Record; +}; diff --git a/src/types/language-list-keys-request.ts b/src/types/language-list-keys-request.ts new file mode 100644 index 0000000..c4b2d0b --- /dev/null +++ b/src/types/language-list-keys-request.ts @@ -0,0 +1,57 @@ +import type { Locales } from '@localazy/languages'; +import type { Project } from '@/types/project.js'; + +export type LanguageListKeysRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * The language of the values, as a locale code; unlike the other language endpoints, this one + * does not resolve numeric language ids. + */ + lang: `${Locales}` | (string & Record); + + /** + * Also return deprecated keys, alongside the active ones. + */ + deprecated?: boolean; + + /** + * Number of keys per page, from 1 to 10000. Default 1000. + */ + limit?: number; + + /** + * Paging cursor from the previous page's `next`. + */ + next?: string; + + /** + * Also return `comment`, `hidden`, `deprecated` and `limit` of each key. + */ + extra_info?: boolean; + + /** + * Also return the custom `metadata` of each key. + */ + metadata?: boolean; + + /** + * Also return the `event` of each key, a marker of its last change in `lang`. + */ + event?: boolean; + + /** + * For a key with no approved value in `lang`, return its newest translation waiting for review + * instead of an empty value. + */ + unapproved?: boolean; + + /** + * Return a linked duplicate key's own value instead of its canonical key's translation when + * `false`. Default `true`. + */ + resolve_duplicities?: boolean; +}; diff --git a/src/types/language-ref.ts b/src/types/language-ref.ts new file mode 100644 index 0000000..11f00d4 --- /dev/null +++ b/src/types/language-ref.ts @@ -0,0 +1,7 @@ +import type { Locales } from '@localazy/languages'; + +/** + * A language as a locale code (`pt_BR`; `pt-BR` is accepted too) or Localazy's numeric language id + * (`112`). An unknown region falls back to the plain language, so `pt-XX` resolves to `pt`. + */ +export type LanguageRef = `${Locales}` | (string & Record) | number; diff --git a/src/types/language-replace-request.ts b/src/types/language-replace-request.ts new file mode 100644 index 0000000..a16bcb0 --- /dev/null +++ b/src/types/language-replace-request.ts @@ -0,0 +1,21 @@ +import type { LanguageRef } from '@/types/language-ref.js'; +import type { Project } from '@/types/project.js'; + +export type LanguageReplaceRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * The language to replace. It must be in the project, not hidden and not the source language. + * **It stops existing**: its translations move to `replaceWith`. + */ + language: LanguageRef; + + /** + * The language to move the translations to. It must not be in the project, unless it is hidden: + * then the translations it kept are destroyed first. + */ + replaceWith: LanguageRef; +}; diff --git a/src/types/language-set-fallback-request.ts b/src/types/language-set-fallback-request.ts new file mode 100644 index 0000000..c0eb793 --- /dev/null +++ b/src/types/language-set-fallback-request.ts @@ -0,0 +1,20 @@ +import type { LanguageRef } from '@/types/language-ref.js'; +import type { Project } from '@/types/project.js'; + +export type LanguageSetFallbackRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * The language to set the fallback for. + */ + lang: LanguageRef; + + /** + * The fallback language: a language of the project (hidden or unpublished ones too), not `lang` + * itself and not one that would make a cycle. `null` removes the fallback. + */ + fallback: LanguageRef | null; +}; diff --git a/src/types/language.ts b/src/types/language.ts index 7c7d48d..6eedc04 100644 --- a/src/types/language.ts +++ b/src/types/language.ts @@ -9,6 +9,11 @@ export type Language = { */ code: string; + /** + * BCP 47 locale tag. + */ + tag: string; + /** * English name of the language / locale. */ @@ -43,4 +48,26 @@ export type Language = { * Number of keys in the need review state. */ needImprovement: number; + + /** + * Hidden languages are not listed in the project, but keep their translations, which come back + * when the language is added again. Listed only with `hidden_languages: true`. + */ + hidden: boolean; + + /** + * The negation of `hidden`; prefer `hidden`. + */ + enabled: boolean; + + /** + * Whether publishing includes the language. + */ + published: boolean; + + /** + * Code of the language that supplies texts for keys untranslated in this one, or `null`. Applies + * only to file outputs (publish, CDN, downloads), never to key listings. + */ + fallback: string | null; }; diff --git a/src/types/languages-batch-request.ts b/src/types/languages-batch-request.ts new file mode 100644 index 0000000..18b9f64 --- /dev/null +++ b/src/types/languages-batch-request.ts @@ -0,0 +1,16 @@ +import type { LanguageRef } from '@/types/language-ref.js'; +import type { Project } from '@/types/project.js'; + +export type LanguagesBatchRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * Up to 100 languages. If one of them can't be resolved (or, except when adding, isn't in the + * project or is the source language), the whole request is rejected and nothing changes. + * Entries that resolve to the same language collapse into one. + */ + languages: LanguageRef[]; +}; diff --git a/src/types/link-create-request.ts b/src/types/link-create-request.ts new file mode 100644 index 0000000..8ecb80e --- /dev/null +++ b/src/types/link-create-request.ts @@ -0,0 +1,25 @@ +import type { Key } from '@/types/key.js'; +import type { Project } from '@/types/project.js'; + +export type LinkCreateRequest = { + /** + * Project object or Project ID of the key to link. + */ + project: Project | string; + + /** + * Key object or Key ID of the key to link. It becomes hidden and publishes the content of + * `linkedKey` while the link exists. + */ + key: Key | string; + + /** + * Key object or Key ID of the target key. + */ + linkedKey: Key | string; + + /** + * Project object, Project ID or slug of the target key's project. Defaults to `project`. + */ + linkedProject?: Project | string; +}; diff --git a/src/types/link-delete-request.ts b/src/types/link-delete-request.ts new file mode 100644 index 0000000..159f5fa --- /dev/null +++ b/src/types/link-delete-request.ts @@ -0,0 +1,14 @@ +import type { Key } from '@/types/key.js'; +import type { Project } from '@/types/project.js'; + +export type LinkDeleteRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * Key object or Key ID of the linked key whose link is removed. + */ + key: Key | string; +}; diff --git a/src/types/link-list-request.ts b/src/types/link-list-request.ts new file mode 100644 index 0000000..4a57147 --- /dev/null +++ b/src/types/link-list-request.ts @@ -0,0 +1,19 @@ +import type { Project } from '@/types/project.js'; + +export type LinkListRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * Number of links to be returned in a single call. Values outside the token's key-export limit + * (1000 by default) fall back to that limit. + */ + limit?: number; + + /** + * Used for paging long lists. + */ + next?: string; +}; diff --git a/src/types/link.ts b/src/types/link.ts new file mode 100644 index 0000000..2f08851 --- /dev/null +++ b/src/types/link.ts @@ -0,0 +1,16 @@ +export type Link = { + /** + * ID of the linked key in this project; publishing takes its content from `linkedKeyId`. + */ + keyId: string; + + /** + * ID of the project the target key belongs to. + */ + linkedProjectId: string; + + /** + * ID of the target key. + */ + linkedKeyId: string; +}; diff --git a/src/types/links-paginated.ts b/src/types/links-paginated.ts new file mode 100644 index 0000000..db601da --- /dev/null +++ b/src/types/links-paginated.ts @@ -0,0 +1,10 @@ +import type { Link } from '@/types/link.js'; + +export type LinksPaginated = { + links: Link[]; + + /** + * Next is the paging key. The field is not contained if there are no more pages. + */ + next?: string; +}; diff --git a/src/types/organization-search-request.ts b/src/types/organization-search-request.ts new file mode 100644 index 0000000..fc9349b --- /dev/null +++ b/src/types/organization-search-request.ts @@ -0,0 +1,44 @@ +import type { Project } from '@/types/project.js'; + +/** + * What a search result matched: + * - `key`: the name of the key. + * - `comment`: the comment from the import or the context note of the key. + * - `translation`: the value of the key in one language, the source language included. + */ +export type OrganizationSearchMatch = 'key' | 'comment' | 'translation'; + +export type OrganizationSearchRequest = { + /** + * ID or slug of a top-level organization; teams can't be searched. + */ + organization: string; + + /** + * Text to search for, 2 to 4096 characters. Full-text: every word must match, and only the first + * 10 words are used. + */ + term: string; + + /** + * Search only in these projects, 1 to 1000. An empty list is rejected, since the server would read + * it as all projects. + */ + projects?: (Project | string)[]; + + /** + * Do not search in these projects. At most 1000. + */ + excludeProjects?: (Project | string)[]; + + /** + * Kinds of matches to return. All of them when omitted. + */ + match?: OrganizationSearchMatch[]; + + /** + * Return `translation` matches only in these languages; `key` and `comment` matches are not + * filtered. Needs `translation` in `match` when `match` is given. + */ + langs?: string[]; +}; diff --git a/src/types/organization-search-response.ts b/src/types/organization-search-response.ts new file mode 100644 index 0000000..2ed2c83 --- /dev/null +++ b/src/types/organization-search-response.ts @@ -0,0 +1,67 @@ +import type { PrefixedPluralValue } from '@/types/plural-class.js'; +import type { OrganizationSearchMatch } from '@/types/organization-search-request.js'; + +export type OrganizationSearchResult = { + projectId: string; + + keyId: string; + + /** + * The key's name as a list of segments, as `key` of `files.listKeys()`. + */ + key: string[]; + + /** + * Path and name of the file that holds the key, for display. + */ + file: string; + + match: OrganizationSearchMatch; + + /** + * Language of `value`: the translation's language for a `translation` match, the project's source + * language otherwise. + */ + lang: string; + + /** + * Current value in `lang`, shaped by the key's form; plural forms carry the `@` prefix. An empty + * string when the key has no value in `lang`, `null` when the stored value can't be read. + */ + value: string | string[] | PrefixedPluralValue | null; + + /** + * Developer comment from the import, or an empty string. + */ + comment: string; + + /** + * Note written for the key in Localazy, or an empty string. + */ + contextNote: string; + + /** + * Whether the key is hidden from translators. + */ + hidden: boolean; +}; + +export type OrganizationSearchProject = { + id: string; + + name: string; + + slug: string; +}; + +export type OrganizationSearchResponse = { + /** + * At most 2000 matches, with no paging. Matches containing the full term come first. + */ + results: OrganizationSearchResult[]; + + /** + * The projects that have at least one match. + */ + projects: OrganizationSearchProject[]; +}; diff --git a/src/types/organization-usage-request.ts b/src/types/organization-usage-request.ts new file mode 100644 index 0000000..097565b --- /dev/null +++ b/src/types/organization-usage-request.ts @@ -0,0 +1,6 @@ +export type OrganizationUsageRequest = { + /** + * Organization ID or slug. A project's organization ID is `Project.orgId`. + */ + organization: string; +}; diff --git a/src/types/organization-usage.ts b/src/types/organization-usage.ts new file mode 100644 index 0000000..21d9960 --- /dev/null +++ b/src/types/organization-usage.ts @@ -0,0 +1,29 @@ +import type { CreditBalance } from '@/types/credit-balance.js'; + +export type OrganizationKeysUsage = { + /** + * Source keys counted against the quota. + */ + used: number; + + /** + * Source key quota, including active temporary increases. + */ + limit: number; + + /** + * `limit` minus `used`. Negative when the organization is over its quota. + */ + remaining: number; +}; + +export type OrganizationUsage = { + /** + * The billing organization the figures belong to. For a team, this is its parent organization. + */ + organizationId: string; + + keys: OrganizationKeysUsage; + + credits: CreditBalance; +}; diff --git a/src/types/plurals-list-request.ts b/src/types/plurals-list-request.ts new file mode 100644 index 0000000..8b9dce1 --- /dev/null +++ b/src/types/plurals-list-request.ts @@ -0,0 +1,8 @@ +import type { Project } from '@/types/project.js'; + +export type PluralsListRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; +}; diff --git a/src/types/plurals.ts b/src/types/plurals.ts new file mode 100644 index 0000000..ae8f5a2 --- /dev/null +++ b/src/types/plurals.ts @@ -0,0 +1,66 @@ +import type { PluralClass } from '@/types/plural-class.js'; + +export type PluralRule = { + /** + * Language code of the rule, e.g. `fr` or `fr_CA`. + */ + language: string; + + /** + * `true` when the rule applies to this locale only; `false` when it applies to all variants of the + * language. + */ + exact: boolean; + + /** + * The forms as stored in the rule; not validated against the CLDR classes. + */ + forms: string[]; +}; + +export type PluralSamples = { + /** + * Example integers in CLDR notation, e.g. `2~4`. + */ + integer?: string; + + /** + * Example decimals in CLDR notation. + */ + decimal?: string; +}; + +export type PluralLanguageForms = { + /** + * Language code, as in `Language.code`. + */ + lang: string; + + /** + * The plural forms the language uses in the project, ordered `zero`, `one`, `two`, `few`, `many`, + * `other`. + */ + forms: PluralClass[]; + + /** + * `true` when a rule of the project gives the forms instead of CLDR. + */ + override: boolean; + + /** + * Example numbers for each form. Absent when `override` is `true`. + */ + samples?: Partial>; +}; + +export type Plurals = { + /** + * Plural rules the project defines in place of the standard ones. Empty when none. + */ + rules: PluralRule[]; + + /** + * One entry per project language; the source language is first. + */ + languages: PluralLanguageForms[]; +}; diff --git a/src/types/project-create-request.ts b/src/types/project-create-request.ts new file mode 100644 index 0000000..016ae6f --- /dev/null +++ b/src/types/project-create-request.ts @@ -0,0 +1,41 @@ +import type { ProjectTone } from '@/enums/project-tone.js'; +import type { ProjectType } from '@/enums/project-type.js'; +import type { Locales } from '@localazy/languages'; + +export type ProjectCreateRequest = { + /** + * Project name, 1 to 64 characters and not blank. + */ + name: string; + + /** + * Project slug. Generated from the name when omitted. + */ + slug?: string; + + /** + * Source language of the project as a locale code; numeric language ids are not accepted. + * Default `en`. + */ + sourceLanguage?: `${Locales}`; + + /** + * Project visibility. Default `restricted`. + */ + type?: `${ProjectType}`; + + /** + * Preferred translation tone. Default `not_specified`. + */ + tone?: `${ProjectTone}`; + + /** + * Project description, at most 1000 characters. + */ + description?: string; + + /** + * Whether Localazy ShareTM is enabled for the project. Default `true`. + */ + useShareTm?: boolean; +}; diff --git a/src/types/project-create-response.ts b/src/types/project-create-response.ts new file mode 100644 index 0000000..bb4d145 --- /dev/null +++ b/src/types/project-create-response.ts @@ -0,0 +1,6 @@ +export type ProjectCreateResponse = { + /** + * ID of the created project. + */ + projectId: string; +}; diff --git a/src/types/project-custom-role.ts b/src/types/project-custom-role.ts new file mode 100644 index 0000000..e14c859 --- /dev/null +++ b/src/types/project-custom-role.ts @@ -0,0 +1,16 @@ +export type ProjectCustomRole = { + /** + * Number of the custom role, 1000 or higher. + */ + number: number; + + /** + * Key of the custom role; `null` when the organization no longer defines it. + */ + key: string | null; + + /** + * Current name of the custom role; `null` when the organization no longer defines it. + */ + name: string | null; +}; diff --git a/src/types/project-tag-list-request.ts b/src/types/project-tag-list-request.ts new file mode 100644 index 0000000..db32b7c --- /dev/null +++ b/src/types/project-tag-list-request.ts @@ -0,0 +1,8 @@ +import type { Project } from '@/types/project.js'; + +export type ProjectTagListRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; +}; diff --git a/src/types/project-tag.ts b/src/types/project-tag.ts new file mode 100644 index 0000000..fd92cfa --- /dev/null +++ b/src/types/project-tag.ts @@ -0,0 +1,25 @@ +/** + * - `generic`: a normal tag. + * - `file`: a tag that also defines an additional output file for the keys that have it. + */ +export type ProjectTagType = 'generic' | 'file'; + +export type ProjectTag = { + /** + * Tag ID, as reported in the tags of a key. + */ + id: string; + + /** + * Tag name; keys are tagged by name with `keys.setTags()`. + */ + name: string; + + type: ProjectTagType; + + /** + * `true` for a tag that Localazy defines for each project: the four priority tags and the tags it + * sets on translations (such as `Translated by MT`). + */ + builtIn: boolean; +}; diff --git a/src/types/project.ts b/src/types/project.ts index fa0789b..89eee82 100644 --- a/src/types/project.ts +++ b/src/types/project.ts @@ -3,6 +3,7 @@ import type { ProjectType } from '@/enums/project-type.js'; import type { UserRole } from '@/enums/user-role.js'; import type { Language } from '@/types/language.js'; import type { Organization } from '@/types/organization.js'; +import type { ProjectCustomRole } from '@/types/project-custom-role.js'; export type Project = { /** @@ -55,6 +56,11 @@ export type Project = { */ role: `${UserRole}`; + /** + * The custom role of the current user; present only when `role` is `custom`. + */ + customRole?: ProjectCustomRole; + /** * The identifier of the source language of the project. */ @@ -64,10 +70,10 @@ export type Project = { * List of enabled features and available source keys. * Only available if the organization query parameter is set to true. */ - organization: Organization; + organization?: Organization; /** * List of all languages and their current state. Only available if the languages query parameter is set to true. */ - languages: Language[]; + languages?: Language[]; }; diff --git a/src/types/projects-list-request.ts b/src/types/projects-list-request.ts index 8d1aba6..9e8b20d 100644 --- a/src/types/projects-list-request.ts +++ b/src/types/projects-list-request.ts @@ -8,4 +8,9 @@ export type ProjectsListRequest = { * Include languages in the output. */ languages?: boolean; + + /** + * Also include hidden languages in `languages`. Implies `languages: true`. + */ + hidden_languages?: boolean; }; diff --git a/src/types/published-list-request.ts b/src/types/published-list-request.ts new file mode 100644 index 0000000..95e96a6 --- /dev/null +++ b/src/types/published-list-request.ts @@ -0,0 +1,8 @@ +import type { Project } from '@/types/project.js'; + +export type PublishedListRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; +}; diff --git a/src/types/published-record.ts b/src/types/published-record.ts new file mode 100644 index 0000000..2437745 --- /dev/null +++ b/src/types/published-record.ts @@ -0,0 +1,18 @@ +export type PublishedRecord = { + /** + * Release tag ID, to pass as `tag` to the file download. Always `_e0` for `latest`. + */ + tagId: string; + + /** + * Release tag name; `latest` for the project's current content. + */ + name: string; + + /** + * Time of the last publish, ISO 8601 in UTC with up to 6 fraction digits; `null` when never + * published. It changes on every publish, even when the files did not, so compare it with the + * previous value, not with your clock. + */ + publishedAt: string | null; +}; diff --git a/src/types/review-translation-response.ts b/src/types/review-translation-response.ts new file mode 100644 index 0000000..8bc5570 --- /dev/null +++ b/src/types/review-translation-response.ts @@ -0,0 +1,12 @@ +export type ReviewTranslationResponse = { + /** + * `true` when the review was applied; `false` when the project is momentarily locked (see + * `message`) and the call should be retried. + */ + result: boolean; + + /** + * The reason when `result` is `false`. + */ + message?: string; +}; diff --git a/src/types/segmentation-get-parent-request.ts b/src/types/segmentation-get-parent-request.ts new file mode 100644 index 0000000..26f77d6 --- /dev/null +++ b/src/types/segmentation-get-parent-request.ts @@ -0,0 +1,23 @@ +import type { Key } from '@/types/key.js'; +import type { Project } from '@/types/project.js'; +import type { Locales } from '@localazy/languages'; + +export type SegmentationGetParentRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; + + /** + * The parent ID (`segParentId` of a segment) or the parent handle (the ID of a segmented key in + * the default mode of `files.listKeys()`). A deprecated parent is addressable only by its parent + * ID. + */ + parent: Key | string; + + /** + * Language to reassemble the text in, as a locale code (e.g. `pt_BR`); numeric language ids are + * not accepted. + */ + lang: `${Locales}`; +}; diff --git a/src/types/segmentation-parent.ts b/src/types/segmentation-parent.ts new file mode 100644 index 0000000..5603531 --- /dev/null +++ b/src/types/segmentation-parent.ts @@ -0,0 +1,64 @@ +export type SegmentationSegment = { + /** + * The segment's own key ID, as `files.listKeys()` reports it with `segments=true`; the ID to + * address when writing a single segment. + */ + id: string; + + /** + * Zero-based position of the segment within its parent. + */ + segIndex: number; +}; + +export type SegmentationParent = { + /** + * Parent ID, as reported by `segParentId` on each of its segments. + */ + id: string; + + /** + * The ID `files.listKeys()` reports the whole key under in its default mode; accepted for tags, + * screenshots, priority and deprecation. + */ + handle: string; + + /** + * The key's path as a list of segments, shaped like `key` of `files.listKeys()`. + */ + key: string[]; + + /** + * File ID. + */ + file: string; + + /** + * `-1` if the parent is active; any other value means it is deprecated, in which case `segments` + * is empty and `value` is absent. + */ + deprecated: number; + + /** + * `true` when the split comes from explicit `` markers in the source rather than from + * the configured strategy. + */ + explicit: boolean; + + /** + * The key's text with one placeholder per segment. The placeholder format is internal to + * segmentation and may change. + */ + template: string; + + /** + * The whole text in the requested language. Each segment contributes its translation when it has + * one and its source text otherwise, so a partly translated key comes back mixed. + */ + value?: string; + + /** + * Segments ascending by `segIndex`. + */ + segments: SegmentationSegment[]; +}; diff --git a/src/types/styleguides-list-request.ts b/src/types/styleguides-list-request.ts new file mode 100644 index 0000000..63d1084 --- /dev/null +++ b/src/types/styleguides-list-request.ts @@ -0,0 +1,8 @@ +import type { Project } from '@/types/project.js'; + +export type StyleguidesListRequest = { + /** + * Project object or Project ID. + */ + project: Project | string; +}; diff --git a/src/types/styleguides.ts b/src/types/styleguides.ts new file mode 100644 index 0000000..e4767c1 --- /dev/null +++ b/src/types/styleguides.ts @@ -0,0 +1,11 @@ +export type Styleguides = { + /** + * The style guide for all languages. Absent when the project has none. + */ + general?: string; + + /** + * Style guides by language code. Languages without one are absent. + */ + languages: Record; +}; diff --git a/src/types/submit-translation-response.ts b/src/types/submit-translation-response.ts index 8c94e71..d014b83 100644 --- a/src/types/submit-translation-response.ts +++ b/src/types/submit-translation-response.ts @@ -1,16 +1,17 @@ export type SubmitTranslationResponse = { /** - * Whether the translation was accepted. + * `true` when the value was stored or matched an existing version; `false` when the request was + * understood but not applied (see `message`). */ result: boolean; /** - * Identifier of the version created for the submitted translation. + * ID of the stored (or matched) version. Present only when `result` is `true`. */ versionId?: string; /** - * Additional detail about the outcome. + * The reason when `result` is `false`. */ message?: string; }; diff --git a/tests/fixtures/full-project/languageKeys.json b/tests/fixtures/full-project/languageKeys.json new file mode 100644 index 0000000..08adb70 --- /dev/null +++ b/tests/fixtures/full-project/languageKeys.json @@ -0,0 +1,23 @@ +{ + "keys": [ + { + "id": "_a0000000000000000001", + "key": ["home", "title"], + "value": "Vítejte zpět", + "vid": 845123154101354564, + "file": "_e000000000001" + }, + { + "id": "_a0000000000000000002", + "key": ["cart", "item_count"], + "value": { "@one": "1 položka", "@few": "%d položky", "@other": "%d položek" }, + "vid": 845123154101354565, + "file": "_e000000000002" + } + ], + "files": { + "_e000000000001": { "id": "_e000000000001", "name": "home.json", "type": "json" }, + "_e000000000002": { "id": "_e000000000002", "name": "cart.json", "type": "json" } + }, + "next": "e4f7a2c1d5" +} diff --git a/tests/fixtures/full-project/languageKeysLastPage.json b/tests/fixtures/full-project/languageKeysLastPage.json new file mode 100644 index 0000000..1d5e3d6 --- /dev/null +++ b/tests/fixtures/full-project/languageKeysLastPage.json @@ -0,0 +1,14 @@ +{ + "keys": [ + { + "id": "_a0000000000000000003", + "key": ["cart", "empty"], + "value": "Košík je prázdný", + "vid": 845123154101354566, + "file": "_e000000000002" + } + ], + "files": { + "_e000000000002": { "id": "_e000000000002", "name": "cart.json", "type": "json" } + } +} diff --git a/tests/fixtures/full-project/projectsOrgsLangs.json b/tests/fixtures/full-project/projectsOrgsLangs.json index 5a7a5ba..15052dd 100644 --- a/tests/fixtures/full-project/projectsOrgsLangs.json +++ b/tests/fixtures/full-project/projectsOrgsLangs.json @@ -35,8 +35,10 @@ "translated": 6, "sourceChanged": 0, "needImprovement": 0, + "hidden": false, "enabled": true, - "published": true + "published": true, + "fallback": null } ], "sourceLanguage": 85 diff --git a/tests/specs/branches.spec.ts b/tests/specs/branches.spec.ts new file mode 100644 index 0000000..311382e --- /dev/null +++ b/tests/specs/branches.spec.ts @@ -0,0 +1,234 @@ +import type { + ApiClient, + Branch, + BranchMergeAnalysis, + BranchOperationStatus, + Project, +} from '@/main.js'; +import { fullProject } from '@tests/fixtures/index.js'; +import { fetchMock, getApiClient, getToken } from '@tests/support/index.js'; +import type { MockInstance } from 'vitest'; +import { beforeEach, describe, expect, test, vi } from 'vitest'; + +const baseUrl = 'https://api.localazy.com/projects/_a0000000000000000001/branches'; + +const headers = { + Accept: 'application/json', + Authorization: `Bearer ${getToken()}`, + 'Content-Type': 'application/json', +}; + +const branches: Branch[] = [ + { name: 'main', projectId: '_a0000000000000000001', slug: 'mobile-app', main: true }, + { + name: 'release-2', + projectId: '_a0000000000000000002', + slug: 'mobile-app!release-2', + main: false, + source: 'main', + }, +]; + +const analysis: BranchMergeAnalysis = { + languages: [ + { + lang: 'cs', + newKeys: 0, + newTranslations: 12, + updated: 0, + equal: 480, + conflicts: 1, + failures: 0, + resolvedFromSource: 0, + resolvedFromTarget: 0, + }, + ], + newFiles: ['checkout.json'], + newLanguages: [], + deprecatedKeys: 0, + conflicts: [ + { + lang: 'cs', + file: 'strings.json', + key: ['cart', 'title'], + sourceKeyId: '_a0000000000000000001', + targetKeyId: '_a0000000000000000002', + sourceValue: 'Košík', + targetValue: 'Nákupní košík', + }, + ], +}; + +const mergeStatus: BranchOperationStatus = { + status: 'done', + changes: 15, + resolved: 0, + conflicts: 1, + failures: 0, + newFiles: 1, + newLanguages: 0, +}; + +describe('Branches', (): void => { + let api: ApiClient; + let project: Project; + + beforeEach(async (): Promise => { + fullProject.mockResponses(); + + fetchMock.get(baseUrl, { branches }); + fetchMock.post(baseUrl, { result: '_a0000000000000000099' }); + fetchMock.put(`${baseUrl}/release-2`, { result: true }); + fetchMock.delete(`${baseUrl}/release-2`, { result: true }); + fetchMock.post(`${baseUrl}/release-2/main`, { result: true }); + fetchMock.post(`${baseUrl}/release-2/separate`, { result: true }); + fetchMock.post(`${baseUrl}/release-2/analysis`, analysis); + fetchMock.post(`${baseUrl}/release-2/merge`, { result: '_a0000000000000000098' }); + fetchMock.get(`${baseUrl}/operations/_a0000000000000000098`, mergeStatus); + + api = getApiClient(); + project = await api.projects.first(); + }); + + test('api.branches.list', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const result: Branch[] = await api.branches.list({ project }); + + expect(spy).toHaveBeenCalledWith(baseUrl, { headers, method: 'GET' }); + expect(result).toEqual(branches); + }); + + test('api.branches.create', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const result: string = await api.branches.create({ + project, + name: 'release-3', + source: branches[1], + empty: true, + }); + + expect(spy).toHaveBeenCalledWith(baseUrl, { + body: '{"name":"release-3","empty":true,"source":"release-2"}', + headers, + method: 'POST', + }); + expect(result).toBe('_a0000000000000000099'); + }); + + test('api.branches.create without source', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.branches.create({ project: '_a0000000000000000001', name: 'release-3' }); + + expect(spy).toHaveBeenCalledWith( + baseUrl, + expect.objectContaining({ body: '{"name":"release-3"}' }), + ); + }); + + test('api.branches.rename', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.branches.rename({ project, branch: 'release-2', name: 'release-3' }); + + expect(spy).toHaveBeenCalledWith(`${baseUrl}/release-2`, { + body: '{"name":"release-3"}', + headers, + method: 'PUT', + }); + }); + + test('api.branches.delete', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.branches.delete({ project, branch: { name: 'release-2' } }); + + expect(spy).toHaveBeenCalledWith(`${baseUrl}/release-2`, { headers, method: 'DELETE' }); + }); + + test('api.branches.setMain', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.branches.setMain({ project, branch: 'release-2', name: 'legacy' }); + + expect(spy).toHaveBeenCalledWith(`${baseUrl}/release-2/main`, { + body: '{"name":"legacy"}', + headers, + method: 'POST', + }); + }); + + test('api.branches.separate', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.branches.separate({ project, branch: 'release-2' }); + + expect(spy).toHaveBeenCalledWith(`${baseUrl}/release-2/separate`, { headers, method: 'POST' }); + }); + + test('api.branches.analyzeMerge', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const result: BranchMergeAnalysis = await api.branches.analyzeMerge({ + project, + branch: 'release-2', + target: branches[0], + strategy: 'reference', + languages: ['cs'], + keys: [{ id: '_a0000000000000000001' }, '_a0000000000000000002'], + details: ['conflicts'], + }); + + expect(spy).toHaveBeenCalledWith(`${baseUrl}/release-2/analysis`, { + body: '{"strategy":"reference","languages":["cs"],"details":["conflicts"],"target":"main","keys":["_a0000000000000000001","_a0000000000000000002"]}', + headers, + method: 'POST', + }); + expect(result).toEqual(analysis); + }); + + test('api.branches.merge', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const result: string = await api.branches.merge({ + project, + branch: 'release-2', + target: 'main', + deprecateMissing: true, + }); + + expect(spy).toHaveBeenCalledWith(`${baseUrl}/release-2/merge`, { + body: '{"deprecateMissing":true,"target":"main"}', + headers, + method: 'POST', + }); + expect(result).toBe('_a0000000000000000098'); + }); + + test('api.branches.getOperation', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const result: BranchOperationStatus = await api.branches.getOperation({ + project, + operation: '_a0000000000000000098', + }); + + expect(spy).toHaveBeenCalledWith(`${baseUrl}/operations/_a0000000000000000098`, { + headers, + method: 'GET', + }); + expect(result).toEqual(mergeStatus); + }); + + test('api.branches rejects a dot-segment branch name', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await expect(api.branches.delete({ project, branch: '..' })).rejects.toThrow( + 'Invalid branch name.', + ); + await expect(api.branches.rename({ project, branch: '.', name: 'x1' })).rejects.toThrow( + 'Invalid branch name.', + ); + expect(spy).not.toHaveBeenCalled(); + }); + + test('api.branches rejects a missing branch name', async (): Promise => { + await expect(api.branches.delete({ project, branch: '' })).rejects.toThrow( + 'Invalid branch name.', + ); + await expect( + api.branches.merge({ project, branch: 'release-2', target: { name: '' } }), + ).rejects.toThrow('Invalid target name.'); + }); +}); diff --git a/tests/specs/comments.spec.ts b/tests/specs/comments.spec.ts new file mode 100644 index 0000000..821e291 --- /dev/null +++ b/tests/specs/comments.spec.ts @@ -0,0 +1,117 @@ +import type { ApiClient, KeyComment, Project } from '@/main.js'; +import { Locales } from '@/main.js'; +import { fullProject } from '@tests/fixtures/index.js'; +import { fetchMock, getApiClient, getToken } from '@tests/support/index.js'; +import type { MockInstance } from 'vitest'; +import { beforeEach, describe, expect, test, vi } from 'vitest'; + +const commentsUrl: string = + 'https://api.localazy.com/projects/_a0000000000000000001/keys/_a0000000000000000001/comments'; + +const comment: KeyComment = { + id: '_c000000000000000001', + userId: '_u000000000000000001', + text: "Is 'kus' better here?", + edited: false, + updatedAt: '2026-11-12T09:41:00Z', +}; + +const jsonInit = (method: string, body?: string): RequestInit => ({ + ...(body === undefined ? {} : { body }), + headers: { + Accept: 'application/json', + Authorization: `Bearer ${getToken()}`, + 'Content-Type': 'application/json', + }, + method, +}); + +describe('Comments', (): void => { + let api: ApiClient; + let project: Project; + + beforeEach(async (): Promise => { + fullProject.mockResponses(); + fetchMock.get(`${commentsUrl}/zh%23Hans`, { comments: [comment] }); + fetchMock.post(`${commentsUrl}/cs`, { result: '_c000000000000000002' }); + fetchMock.put(`${commentsUrl}/cs/_c000000000000000001`, { result: true }); + fetchMock.delete(`${commentsUrl}/cs/_c000000000000000001`, { result: true }); + fetchMock.delete(`${commentsUrl}/cs/_c000000000000000009`, { + status: 404, + body: { success: false, code: 404, error: 'not_found' }, + }); + + api = getApiClient(); + project = await api.projects.first(); + }); + + test('api.comments.list', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const comments: KeyComment[] = await api.comments.list({ + project, + key: '_a0000000000000000001', + lang: 'zh#Hans', + }); + + expect(comments).toEqual([comment]); + expect(spy).toHaveBeenCalledWith(`${commentsUrl}/zh%23Hans`, jsonInit('GET')); + }); + + test('api.comments.create', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const id: string = await api.comments.create({ + project, + key: '_a0000000000000000001', + lang: Locales.CZECH, + text: 'Yes.', + }); + + expect(id).toBe('_c000000000000000002'); + expect(spy).toHaveBeenCalledWith(`${commentsUrl}/cs`, jsonInit('POST', '{"text":"Yes."}')); + }); + + test('api.comments.update', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.comments.update({ + project, + key: '_a0000000000000000001', + lang: Locales.CZECH, + comment, + text: "Is 'kusy' better here?", + }); + + expect(spy).toHaveBeenCalledWith( + `${commentsUrl}/cs/_c000000000000000001`, + jsonInit('PUT', '{"text":"Is \'kusy\' better here?"}'), + ); + }); + + test('api.comments.delete', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.comments.delete({ + project, + key: '_a0000000000000000001', + lang: Locales.CZECH, + comment: '_c000000000000000001', + }); + + expect(spy).toHaveBeenCalledWith(`${commentsUrl}/cs/_c000000000000000001`, jsonInit('DELETE')); + }); + + test('api.comments.delete rejects a missing comment', async (): Promise => { + await expect( + api.comments.delete({ + project, + key: '_a0000000000000000001', + lang: Locales.CZECH, + comment: '_c000000000000000009', + }), + ).rejects.toThrow('Request failed with status code 404: not_found'); + }); + + test('api.comments rejects an empty comment id', async (): Promise => { + await expect( + api.comments.delete({ project, key: '_a0000000000000000001', lang: 'cs', comment: '' }), + ).rejects.toThrow('Invalid comment ID.'); + }); +}); diff --git a/tests/specs/glossary-batch.spec.ts b/tests/specs/glossary-batch.spec.ts new file mode 100644 index 0000000..96b6d23 --- /dev/null +++ b/tests/specs/glossary-batch.spec.ts @@ -0,0 +1,67 @@ +import type { ApiClient, GlossaryCreateManyResponse, Project } from '@/main.js'; +import { fullProject } from '@tests/fixtures/index.js'; +import { fetchMock, getApiClient, getToken } from '@tests/support/index.js'; +import type { MockInstance } from 'vitest'; +import { beforeEach, describe, expect, test, vi } from 'vitest'; + +const batchUrl: string = 'https://api.localazy.com/projects/_a0000000000000000001/glossary/batch'; + +describe('Glossary batch', (): void => { + let api: ApiClient; + let project: Project; + + beforeEach(async (): Promise => { + fullProject.mockResponses(); + fetchMock.post(batchUrl, { + result: true, + created: ['Save'], + updated: ['Monitor'], + skipped: [], + }); + + api = getApiClient(); + project = await api.projects.first(); + }); + + test('api.glossary.createMany', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const response: GlossaryCreateManyResponse = await api.glossary.createMany({ + project, + terms: [ + { term: [{ lang: 'en', term: 'Save' }], description: 'UI action' }, + { + term: [ + { lang: 'en', term: 'Monitor' }, + { lang: 'cs', term: 'Monitor' }, + ], + caseSensitive: true, + }, + ], + }); + + expect(response).toEqual({ + result: true, + created: ['Save'], + updated: ['Monitor'], + skipped: [], + }); + expect(spy).toHaveBeenCalledWith(batchUrl, { + body: + '[{"term":[{"lang":"en","term":"Save"}],"description":"UI action"},' + + '{"term":[{"lang":"en","term":"Monitor"},{"lang":"cs","term":"Monitor"}],"caseSensitive":true}]', + headers: { + Accept: 'application/json', + Authorization: `Bearer ${getToken()}`, + 'Content-Type': 'application/json', + }, + method: 'POST', + }); + }); + + test('api.glossary.createMany rejects a missing term list', async (): Promise => { + await expect( + // @ts-expect-error terms must be an array + api.glossary.createMany({ project, terms: undefined }), + ).rejects.toThrow(TypeError); + }); +}); diff --git a/tests/specs/keys-details.spec.ts b/tests/specs/keys-details.spec.ts new file mode 100644 index 0000000..74f6dd9 --- /dev/null +++ b/tests/specs/keys-details.spec.ts @@ -0,0 +1,191 @@ +import type { + ApiClient, + KeyDetailsResponse, + Project, + ReviewTranslationResponse, + SubmitTranslationResponse, +} from '@/main.js'; +import { Locales } from '@/main.js'; +import { fullProject } from '@tests/fixtures/index.js'; +import { assertNotNull } from '@tests/support/assert-not-null.js'; +import { fetchMock, getApiClient, getToken } from '@tests/support/index.js'; +import type { MockInstance } from 'vitest'; +import { beforeEach, describe, expect, test, vi } from 'vitest'; + +const baseUrl: string = 'https://api.localazy.com/projects/_a0000000000000000001/keys'; + +const details: KeyDetailsResponse = { + keys: [ + { + id: '_a0000000000000000001', + key: ['cart', 'item_count'], + type: 'plural', + file: { id: '_e000000000001', name: 'en.json', type: 'json' }, + deprecated: false, + hidden: false, + limit: -1, + comment: 'Shown in the cart header.', + contextNote: 'Number of items, not products.', + priority: 'high', + tags: [{ id: '_e40', name: 'High priority', builtIn: true }], + source: { + lang: 'en', + value: { '@one': '%d item', '@other': '%d items' }, + pluralForms: ['one', 'other'], + }, + translation: { + lang: 'cs', + state: { translated: true, needReview: true, sourceChanged: false, needImprovement: false }, + review: { + versionId: '_v000000000000000002', + value: { '@one': '%d kus', '@few': '%d kusy', '@other': '%d kusů' }, + userId: '_u000000000000000001', + }, + }, + comments: [ + { + id: '_c000000000000000001', + userId: '_u000000000000000001', + text: "Is 'kus' better here?", + edited: false, + updatedAt: '2026-11-12T09:41:00Z', + }, + ], + }, + ], + errors: [{ id: '_a0000000000000000002', error: 'not_found' }], +}; + +const jsonInit = (method: string, body?: string): RequestInit => ({ + ...(body === undefined ? {} : { body }), + headers: { + Accept: 'application/json', + Authorization: `Bearer ${getToken()}`, + 'Content-Type': 'application/json', + }, + method, +}); + +describe('Keys details, source and review', (): void => { + let api: ApiClient; + let project: Project; + + beforeEach(async (): Promise => { + fullProject.mockResponses(); + fetchMock.get( + `${baseUrl}/details/zh%23Hans?ids=_a0000000000000000001%2C_a0000000000000000002`, + details, + ); + fetchMock.post(`${baseUrl}/_a0000000000000000001/source`, { + result: true, + versionId: '_v000000000000000003', + }); + fetchMock.post(`${baseUrl}/_a0000000000000000001/translations/cs/review`, { result: true }); + fetchMock.post(`${baseUrl}/_a0000000000000000001/translations/zh%23Hans/review`, { + result: false, + message: 'The project is temporarily locked; please retry.', + }); + + api = getApiClient(); + project = await api.projects.first(); + }); + + test('api.keys.getDetails', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const response: KeyDetailsResponse = await api.keys.getDetails({ + project, + keys: [{ id: '_a0000000000000000001' }, '_a0000000000000000002'], + lang: 'zh#Hans', + }); + + const key = assertNotNull(response.keys[0]); + expect(key.translation.review?.versionId).toBe('_v000000000000000002'); + expect(key.comments[0]?.text).toBe("Is 'kus' better here?"); + expect(response.errors).toEqual([{ id: '_a0000000000000000002', error: 'not_found' }]); + expect(spy).toHaveBeenCalledWith( + `${baseUrl}/details/zh%23Hans?ids=_a0000000000000000001%2C_a0000000000000000002`, + jsonInit('GET'), + ); + }); + + test('api.keys.getDetails keeps caller params', async (): Promise => { + fetchMock.get(`${baseUrl}/details/cs?extra=1&ids=_a0000000000000000001`, details); + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.keys.getDetails( + { project, keys: ['_a0000000000000000001'], lang: Locales.CZECH }, + { params: { extra: '1', ids: 'ignored' } }, + ); + + expect(spy).toHaveBeenCalledWith( + `${baseUrl}/details/cs?extra=1&ids=_a0000000000000000001`, + expect.objectContaining({ method: 'GET' }), + ); + }); + + test('api.keys.getDetails rejects a missing key list or language', async (): Promise => { + await expect( + // @ts-expect-error keys must be an array + api.keys.getDetails({ project, keys: '_a0000000000000000001', lang: Locales.CZECH }), + ).rejects.toThrow(TypeError); + await expect( + // @ts-expect-error lang is required + api.keys.getDetails({ project, keys: ['_a0000000000000000001'], lang: undefined }), + ).rejects.toThrow('Invalid lang language.'); + }); + + test('api.keys.editSource', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const response: SubmitTranslationResponse = await api.keys.editSource({ + project, + key: '_a0000000000000000001', + value: { '@one': '%d item', '@other': '%d items' }, + sourceChanged: false, + }); + + expect(response).toEqual({ result: true, versionId: '_v000000000000000003' }); + expect(spy).toHaveBeenCalledWith( + `${baseUrl}/_a0000000000000000001/source`, + jsonInit('POST', '{"value":{"one":"%d item","other":"%d items"},"sourceChanged":false}'), + ); + }); + + test('api.keys.editSource omits sourceChanged when not given', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.keys.editSource({ project, key: '_a0000000000000000001', value: 'Save changes' }); + + expect(spy).toHaveBeenCalledWith( + `${baseUrl}/_a0000000000000000001/source`, + jsonInit('POST', '{"value":"Save changes"}'), + ); + }); + + test('api.keys.reviewTranslation', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const response: ReviewTranslationResponse = await api.keys.reviewTranslation({ + project, + key: '_a0000000000000000001', + lang: Locales.CZECH, + versionId: '_v000000000000000002', + action: 'approve', + }); + + expect(response).toEqual({ result: true }); + expect(spy).toHaveBeenCalledWith( + `${baseUrl}/_a0000000000000000001/translations/cs/review`, + jsonInit('POST', '{"versionId":"_v000000000000000002","action":"approve"}'), + ); + }); + + test('api.keys.reviewTranslation surfaces result false', async (): Promise => { + const response: ReviewTranslationResponse = await api.keys.reviewTranslation({ + project, + key: '_a0000000000000000001', + lang: 'zh#Hans', + versionId: '_v000000000000000002', + action: 'reject', + }); + + expect(response.result).toBe(false); + expect(response.message).toBe('The project is temporarily locked; please retry.'); + }); +}); diff --git a/tests/specs/languages.spec.ts b/tests/specs/languages.spec.ts new file mode 100644 index 0000000..d92bb99 --- /dev/null +++ b/tests/specs/languages.spec.ts @@ -0,0 +1,317 @@ +import type { + ApiClient, + BooleanResult, + CdnMetadata, + LanguageAddResponse, + LanguageCopyResponse, + LanguageKey, + LanguageKeysPaginated, + Plurals, + Project, + PublishedRecord, + Styleguides, +} from '@/main.js'; +import { Locales } from '@/main.js'; +import { fullProject } from '@tests/fixtures/index.js'; +import languageKeys from '@tests/fixtures/full-project/languageKeys.json' with { type: 'json' }; +import languageKeysLastPage from '@tests/fixtures/full-project/languageKeysLastPage.json' with { type: 'json' }; +import { fetchMock, getApiClient, getToken } from '@tests/support/index.js'; +import type { MockInstance } from 'vitest'; +import { beforeEach, describe, expect, test, vi } from 'vitest'; + +const baseUrl: string = 'https://api.localazy.com/projects/_a0000000000000000001'; + +const requestInit = (method: string, body?: string): RequestInit => ({ + ...(body === undefined ? {} : { body }), + headers: { + Accept: 'application/json', + Authorization: `Bearer ${getToken()}`, + 'Content-Type': 'application/json', + }, + method, +}); + +describe('Languages', (): void => { + let api: ApiClient; + let project: Project; + + beforeEach(async (): Promise => { + fullProject.mockResponses(); + + api = getApiClient(); + project = await api.projects.first(); + }); + + test('api.languages.add', async (): Promise => { + const response: LanguageAddResponse = { + result: true, + languages: [ + { id: 1065, code: 'pt_BR', state: 'created' }, + { id: 60, code: 'cs', state: 'restored' }, + ], + }; + fetchMock.post(`${baseUrl}/languages`, response); + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + + const result: LanguageAddResponse = await api.languages.add({ + project, + languages: [Locales.BRAZILIAN_PORTUGUESE, 60], + }); + + expect(result).toEqual(response); + expect(spy).toHaveBeenCalledWith( + `${baseUrl}/languages`, + requestInit('POST', '{"languages":["pt_BR","60"]}'), + ); + }); + + test.each([ + ['hide', 'hidden'], + ['enable', 'enabled'], + ['disable', 'disabled'], + ] as const)('api.languages.%s', async (method, state): Promise => { + const response = { result: true, languages: [{ id: 60, code: 'cs', state }] }; + fetchMock.post(`https://api.localazy.com/projects/test-project/languages/${method}`, response); + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + + const result = await api.languages[method]({ project: 'test-project', languages: ['cs'] }); + + expect(result).toEqual(response); + expect(spy).toHaveBeenCalledWith( + `https://api.localazy.com/projects/test-project/languages/${method}`, + requestInit('POST', '{"languages":["cs"]}'), + ); + }); + + test('api.languages.hide rejects a non-array', async (): Promise => { + await expect( + // @ts-expect-error languages must be an array + api.languages.hide({ project, languages: 'cs' }), + ).rejects.toThrow('Invalid language list'); + }); + + test('api.languages.delete', async (): Promise => { + fetchMock.delete(`${baseUrl}/languages/zh%23Hans`, { result: true }); + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + + const result: BooleanResult = await api.languages.delete({ project, lang: 'zh#Hans' }); + + expect(result.result).toBe(true); + expect(spy).toHaveBeenCalledWith(`${baseUrl}/languages/zh%23Hans`, requestInit('DELETE')); + }); + + test('api.languages.delete requires a language', async (): Promise => { + await expect(api.languages.delete({ project, lang: '' })).rejects.toThrow( + 'Invalid lang language.', + ); + }); + + test('api.languages.copy', async (): Promise => { + const response: LanguageCopyResponse = { + result: true, + language: { id: 1064, code: 'pt_PT', state: 'created' }, + }; + fetchMock.post(`${baseUrl}/languages/copy`, response); + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + + const result: LanguageCopyResponse = await api.languages.copy({ + project, + from: Locales.BRAZILIAN_PORTUGUESE, + to: 'pt_PT', + }); + + expect(result).toEqual(response); + expect(spy).toHaveBeenCalledWith( + `${baseUrl}/languages/copy`, + requestInit('POST', '{"from":"pt_BR","to":"pt_PT"}'), + ); + }); + + test('api.languages.replace', async (): Promise => { + fetchMock.post(`${baseUrl}/languages/replace`, { result: true }); + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + + const result: BooleanResult = await api.languages.replace({ + project, + language: 'de', + replaceWith: 'de_AT', + }); + + expect(result.result).toBe(true); + expect(spy).toHaveBeenCalledWith( + `${baseUrl}/languages/replace`, + requestInit('POST', '{"language":"de","replaceWith":"de_AT"}'), + ); + }); + + test('api.languages.setFallback', async (): Promise => { + fetchMock.put(`${baseUrl}/languages/pt_PT/fallback`, { result: true }); + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + + const result: BooleanResult = await api.languages.setFallback({ + project, + lang: 'pt_PT', + fallback: Locales.BRAZILIAN_PORTUGUESE, + }); + + expect(result.result).toBe(true); + expect(spy).toHaveBeenCalledWith( + `${baseUrl}/languages/pt_PT/fallback`, + requestInit('PUT', '{"fallback":"pt_BR"}'), + ); + }); + + test('api.languages.setFallback removes the fallback', async (): Promise => { + fetchMock.put(`${baseUrl}/languages/pt_PT/fallback`, { result: true }); + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + + await api.languages.setFallback({ project, lang: 'pt_PT', fallback: null }); + + expect(spy).toHaveBeenCalledWith( + `${baseUrl}/languages/pt_PT/fallback`, + requestInit('PUT', '{"fallback":null}'), + ); + }); + + test('api.languages.listKeysPage', async (): Promise => { + const url: string = `${baseUrl}/languages/cs/keys?limit=2&extra_info=true&resolve_duplicities=false`; + fetchMock.get(url, languageKeys); + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + + const page: LanguageKeysPaginated = await api.languages.listKeysPage({ + project, + lang: Locales.CZECH, + limit: 2, + extra_info: true, + resolve_duplicities: false, + deprecated: undefined, + }); + + expect(spy).toHaveBeenCalledWith(url, requestInit('GET')); + expect(page.next).toBe('e4f7a2c1d5'); + expect(page.keys[1]?.file).toBe('_e000000000002'); + expect(Object.values(page.files).map((file) => file.name)).toEqual(['home.json', 'cart.json']); + }); + + test('api.languages.listKeysPage keeps the params of the config', async (): Promise => { + const url: string = `${baseUrl}/languages/cs/keys?trace=1&limit=2`; + fetchMock.get(url, languageKeys); + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + + await api.languages.listKeysPage( + { project, lang: Locales.CZECH, limit: 2 }, + { params: { trace: '1' } }, + ); + + expect(spy).toHaveBeenCalledWith(url, requestInit('GET')); + }); + + test('api.languages.listKeys walks all pages', async (): Promise => { + fetchMock.get(`${baseUrl}/languages/cs/keys`, languageKeys); + fetchMock.get(`${baseUrl}/languages/cs/keys?next=e4f7a2c1d5`, languageKeysLastPage); + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + + const keys: LanguageKey[] = await api.languages.listKeys({ project, lang: Locales.CZECH }); + + expect(keys.map((key) => key.id)).toEqual([ + '_a0000000000000000001', + '_a0000000000000000002', + '_a0000000000000000003', + ]); + expect(spy).toHaveBeenCalledTimes(2); + expect(spy).toHaveBeenLastCalledWith( + `${baseUrl}/languages/cs/keys?next=e4f7a2c1d5`, + requestInit('GET'), + ); + }); + + test('api.files.listPublished', async (): Promise => { + const response: PublishedRecord[] = [ + { tagId: '_e0', name: 'latest', publishedAt: '2026-11-13T02:15:00.123456Z' }, + { tagId: '_e845123154101354999', name: 'beta', publishedAt: null }, + ]; + fetchMock.get(`${baseUrl}/published`, response); + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + + const result: PublishedRecord[] = await api.files.listPublished({ project }); + + expect(result).toEqual(response); + expect(spy).toHaveBeenCalledWith(`${baseUrl}/published`, requestInit('GET')); + }); + + test('api.languages.listPlurals', async (): Promise => { + const response: Plurals = { + rules: [{ language: 'fr', exact: false, forms: ['zero', 'one', 'other'] }], + languages: [ + { + lang: 'cs', + forms: ['one', 'few', 'other'], + override: false, + samples: { one: { integer: '1' }, few: { integer: '2~4' } }, + }, + { lang: 'fr_CA', forms: ['zero', 'one', 'other'], override: true }, + ], + }; + fetchMock.get(`${baseUrl}/plurals`, response); + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + + const result: Plurals = await api.languages.listPlurals({ project }); + + expect(result).toEqual(response); + expect(spy).toHaveBeenCalledWith(`${baseUrl}/plurals`, requestInit('GET')); + }); + + test('api.projects.list with hidden languages', async (): Promise => { + fetchMock.get('https://api.localazy.com/projects?hidden_languages=true', []); + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + + await api.projects.list({ hidden_languages: true }); + + expect(spy).toHaveBeenCalledWith( + 'https://api.localazy.com/projects?hidden_languages=true', + requestInit('GET'), + ); + }); +}); + +describe('Styleguides', (): void => { + test('api.styleguides.list', async (): Promise => { + fullProject.mockResponses(); + const api: ApiClient = getApiClient(); + const response: Styleguides = { + general: 'Use a friendly tone.', + languages: { cs: 'Tykej uživateli.' }, + }; + fetchMock.get(`${baseUrl}/styleguides`, response); + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + + const result: Styleguides = await api.styleguides.list({ project: '_a0000000000000000001' }); + + expect(result).toEqual(response); + expect(spy).toHaveBeenCalledWith(`${baseUrl}/styleguides`, requestInit('GET')); + }); +}); + +describe('CDN', (): void => { + test('api.cdn.list', async (): Promise => { + fullProject.mockResponses(); + const api: ApiClient = getApiClient(); + const response: CdnMetadata = { + enabled: true, + metadataUrls: [ + { + tagId: '_e0', + tagName: 'latest', + metadataUrl: 'https://delivery.localazy.com/_a64584490296431065702cd54241/_e0.v2.json', + }, + ], + }; + fetchMock.get(`${baseUrl}/cdn`, response); + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + + const result: CdnMetadata = await api.cdn.list({ project: '_a0000000000000000001' }); + + expect(result).toEqual(response); + expect(spy).toHaveBeenCalledWith(`${baseUrl}/cdn`, requestInit('GET')); + }); +}); diff --git a/tests/specs/links.spec.ts b/tests/specs/links.spec.ts new file mode 100644 index 0000000..e289353 --- /dev/null +++ b/tests/specs/links.spec.ts @@ -0,0 +1,136 @@ +import type { ApiClient, Link, Project } from '@/main.js'; +import { fullProject } from '@tests/fixtures/index.js'; +import { fetchMock, getApiClient, getApiUrl, getToken } from '@tests/support/index.js'; +import type { MockInstance } from 'vitest'; +import { beforeEach, describe, expect, test, vi } from 'vitest'; + +const linksUrl: string = `${getApiUrl()}/projects/_a0000000000000000001/links`; + +const firstLink: Link = { + keyId: '_a0000000000000000001', + linkedProjectId: '_a0000000000000000001', + linkedKeyId: '_a0000000000000000002', +}; + +const secondLink: Link = { + keyId: '_a0000000000000000003', + linkedProjectId: '_a0000000000000000009', + linkedKeyId: '_a0000000000000000004', +}; + +describe('Links', (): void => { + let api: ApiClient; + let project: Project; + + beforeEach(async (): Promise => { + fullProject.mockResponses(); + fetchMock.get(`${linksUrl}?next=page2`, { links: [secondLink] }); + fetchMock.get(`begin:${linksUrl}`, { links: [firstLink], next: 'page2' }); + fetchMock.post(`begin:${linksUrl}/`, { result: true }); + fetchMock.delete(`begin:${linksUrl}/`, { result: true }); + + api = getApiClient(); + project = await api.projects.first(); + }); + + test('api.links.list follows the cursor', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const links: Link[] = await api.links.list({ project }); + + expect(links).toEqual([firstLink, secondLink]); + expect(spy).toHaveBeenNthCalledWith(1, linksUrl, expect.objectContaining({ method: 'GET' })); + expect(spy).toHaveBeenNthCalledWith( + 2, + `${linksUrl}?next=page2`, + expect.objectContaining({ method: 'GET' }), + ); + }); + + test('api.links.list resumes from a cursor', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const links: Link[] = await api.links.list({ project, next: 'page2' }); + + expect(links).toEqual([secondLink]); + expect(spy).toHaveBeenCalledTimes(1); + expect(spy).toHaveBeenCalledWith( + `${linksUrl}?next=page2`, + expect.objectContaining({ method: 'GET' }), + ); + }); + + test('api.links.listPage keeps the params of the config', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.links.listPage({ project, limit: 50 }, { params: { trace: '1' } }); + + expect(spy).toHaveBeenCalledWith( + `${linksUrl}?trace=1&limit=50`, + expect.objectContaining({ method: 'GET' }), + ); + }); + + test('api.links.listPage', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const page = await api.links.listPage({ project: '_a0000000000000000001', limit: 50 }); + + expect(page).toEqual({ links: [firstLink], next: 'page2' }); + expect(spy).toHaveBeenCalledWith(`${linksUrl}?limit=50`, { + headers: { + Accept: 'application/json', + Authorization: `Bearer ${getToken()}`, + 'Content-Type': 'application/json', + }, + method: 'GET', + }); + }); + + test('api.links.create', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.links.create({ + project, + key: { id: '_a0000000000000000001' } as never, + linkedKey: '_a0000000000000000002', + }); + + expect(spy).toHaveBeenCalledWith(`${linksUrl}/_a0000000000000000001`, { + body: '{"keyId":"_a0000000000000000002"}', + headers: { + Accept: 'application/json', + Authorization: `Bearer ${getToken()}`, + 'Content-Type': 'application/json', + }, + method: 'POST', + }); + }); + + test('api.links.create across projects', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.links.create({ + project, + key: '_a0000000000000000001', + linkedKey: '_a0000000000000000004', + linkedProject: 'other-project', + }); + + expect(spy).toHaveBeenCalledWith( + `${linksUrl}/_a0000000000000000001`, + expect.objectContaining({ + body: '{"keyId":"_a0000000000000000004","project":"other-project"}', + method: 'POST', + }), + ); + }); + + test('api.links.delete', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.links.delete({ project, key: '_a0000000000000000001' }); + + expect(spy).toHaveBeenCalledWith(`${linksUrl}/_a0000000000000000001`, { + headers: { + Accept: 'application/json', + Authorization: `Bearer ${getToken()}`, + 'Content-Type': 'application/json', + }, + method: 'DELETE', + }); + }); +}); diff --git a/tests/specs/organizations.spec.ts b/tests/specs/organizations.spec.ts new file mode 100644 index 0000000..6261ee1 --- /dev/null +++ b/tests/specs/organizations.spec.ts @@ -0,0 +1,295 @@ +import type { + ApiClient, + CreditSummaryResponse, + CreditTopupsResponse, + CreditTransactions, + CreditTransactionsPaginated, + OrganizationSearchResponse, + OrganizationUsage, + Project, +} from '@/main.js'; +import { fullProject } from '@tests/fixtures/index.js'; +import { fetchMock, getApiClient, getToken } from '@tests/support/index.js'; +import type { MockInstance } from 'vitest'; +import { beforeEach, describe, expect, test, vi } from 'vitest'; + +const orgUrl: string = 'https://api.localazy.com/organizations/_a0000000000000000001'; +const orgId: string = '_a0000000000000000001'; + +const usage: OrganizationUsage = { + organizationId: orgId, + keys: { used: 52000, limit: 50000, remaining: -2000 }, + credits: { balance: '128.50', limit: '100', limitSince: '42.75', limitRemaining: '57.25' }, +}; + +const searchResponse: OrganizationSearchResponse = { + results: [ + { + projectId: '_a0000000000000000001', + keyId: '_a0000000000000000002', + key: ['cart', 'items'], + file: 'locales/en.json', + match: 'translation', + lang: 'de', + value: { '@one': '1 Artikel', '@other': '%d Artikel' }, + comment: '', + contextNote: 'Keep it short.', + hidden: false, + }, + ], + projects: [{ id: '_a0000000000000000001', name: 'Mobile App', slug: 'mobile-app' }], +}; + +const summary: CreditSummaryResponse = { + organizationId: orgId, + from: '2026-11-01T00:00:00Z', + to: '2026-11-03T00:00:00Z', + balance: { + balance: '812.4375', + limit: '1000', + limitSince: '187.5625', + limitRemaining: '812.4375', + }, + spent: '187.5625', + adjusted: '0', + toppedUp: '1000', + transactions: 4160, + volume: 96250, + groups: [ + { + day: '2026-11-01', + category: 'ai', + spent: '92.25', + adjusted: '0', + volume: 92250, + transactions: 4120, + }, + { + day: '2026-11-01', + category: 'clt', + spent: '60', + adjusted: '0', + volume: 4000, + transactions: 40, + }, + ], +}; + +const transactionsPage1: CreditTransactionsPaginated = { + organizationId: orgId, + from: '2026-11-01T00:00:00Z', + to: '2026-11-18T09:41:00Z', + transactions: [ + { + ts: '2026-11-01T07:12:44.120533Z', + amount: '0.0125', + volume: 25, + category: 'ai', + action: 'localazyAi', + source: 'automations', + projectId: '_a0000000000000000001', + keyId: '_a0000000000000000002', + fromLanguage: 'en', + toLanguage: 'de', + automationId: '_a0000000000000000003', + }, + ], + next: 'djE6MTc2MTk4MTMwMjAwNDQxMDox', +}; + +const transactionsPage2: CreditTransactionsPaginated = { + organizationId: orgId, + from: '2026-11-01T07:12:44.120533Z', + to: '2026-11-18T09:41:00Z', + transactions: [ + { + ts: '2026-11-01T07:15:02.00441Z', + amount: '1.5', + volume: 150, + category: 'clt', + action: 'clt_translate', + source: 'clt', + userId: '_a0000000000000000004', + }, + ], +}; + +const topups: CreditTopupsResponse = { + organizationId: orgId, + from: '2026-10-01T00:00:00Z', + to: '2026-11-18T09:41:00Z', + topups: [ + { ts: '2026-10-01T00:00:03.112Z', type: 'plan', amount: '640.5', limit: '1000' }, + { ts: '2026-10-14T13:20:11.9Z', type: 'extra', amount: '500' }, + ], +}; + +const expectedRequest = { + headers: { + Accept: 'application/json', + Authorization: `Bearer ${getToken()}`, + 'Content-Type': 'application/json', + }, + method: 'GET', +}; + +describe('Organizations', (): void => { + let api: ApiClient; + let project: Project; + + beforeEach(async (): Promise => { + fullProject.mockResponses(); + fetchMock.get(`${orgUrl}/usage`, usage); + fetchMock.get(`begin:${orgUrl}/search?`, searchResponse); + fetchMock.get(`begin:${orgUrl}/credits/summary`, summary); + fetchMock.get( + `${orgUrl}/credits/transactions?to=2026-11-18T09%3A41%3A00Z&next=djE6MTc2MTk4MTMwMjAwNDQxMDox`, + transactionsPage2, + ); + fetchMock.get(`begin:${orgUrl}/credits/transactions`, transactionsPage1); + fetchMock.get(`begin:${orgUrl}/credits/topups`, topups); + + api = getApiClient(); + project = await api.projects.first(); + }); + + test('api.organizations.getUsage', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const response: OrganizationUsage = await api.organizations.getUsage({ organization: orgId }); + + expect(response).toEqual(usage); + expect(spy).toHaveBeenCalledWith(`${orgUrl}/usage`, expectedRequest); + }); + + test('api.organizations.getUsage rejects an empty organization', async (): Promise => { + await expect(api.organizations.getUsage({ organization: '' })).rejects.toThrow( + 'Invalid organization ID.', + ); + }); + + test('api.organizations.search', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const response: OrganizationSearchResponse = await api.organizations.search({ + organization: orgId, + term: 'cart', + projects: [project, '_a0000000000000000009'], + excludeProjects: ['_a0000000000000000008'], + match: ['key', 'translation'], + langs: ['de', 'zh#Hans'], + }); + + expect(response).toEqual(searchResponse); + expect(spy).toHaveBeenCalledWith( + `${orgUrl}/search?term=cart&projects=_a0000000000000000001%2C_a0000000000000000009&excludeProjects=_a0000000000000000008&match=key%2Ctranslation&langs=de%2Czh%23Hans`, + expectedRequest, + ); + }); + + test('api.organizations.search with only a term', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.organizations.search({ organization: orgId, term: 'cart' }); + + expect(spy).toHaveBeenCalledWith(`${orgUrl}/search?term=cart`, expectedRequest); + }); + + test('api.organizations.search rejects an empty project list', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await expect( + api.organizations.search({ organization: orgId, term: 'cart', projects: [] }), + ).rejects.toThrow('Invalid project list'); + expect(spy).not.toHaveBeenCalled(); + }); + + test('api.organizations.search leaves out empty filters', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.organizations.search({ + organization: orgId, + term: 'cart', + excludeProjects: [], + match: [], + langs: [], + }); + + expect(spy).toHaveBeenCalledWith(`${orgUrl}/search?term=cart`, expectedRequest); + }); + + test('api.organizations.search keeps the params of the config', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.organizations.search( + { organization: orgId, term: 'cart' }, + { params: { trace: '1' } }, + ); + + expect(spy).toHaveBeenCalledWith(`${orgUrl}/search?trace=1&term=cart`, expectedRequest); + }); + + test('api.organizations.getCreditSummary', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const response: CreditSummaryResponse = await api.organizations.getCreditSummary({ + organization: orgId, + from: '2026-11-01', + to: new Date('2026-11-03T00:00:00Z'), + groupBy: ['day', 'category'], + }); + + expect(response).toEqual(summary); + expect(spy).toHaveBeenCalledWith( + `${orgUrl}/credits/summary?from=2026-11-01&to=2026-11-03T00%3A00%3A00.000Z&groupBy=day%2Ccategory`, + expectedRequest, + ); + }); + + test('api.organizations.getCreditSummary sends an empty groupBy for totals only', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.organizations.getCreditSummary({ organization: orgId, groupBy: [] }); + + expect(spy).toHaveBeenCalledWith(`${orgUrl}/credits/summary?groupBy=`, expectedRequest); + }); + + test('api.organizations.listCreditTransactionsPage', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const response: CreditTransactionsPaginated = + await api.organizations.listCreditTransactionsPage({ + organization: orgId, + from: '2026-11-01', + limit: 1, + }); + + expect(response).toEqual(transactionsPage1); + expect(spy).toHaveBeenCalledWith( + `${orgUrl}/credits/transactions?from=2026-11-01&limit=1`, + expectedRequest, + ); + }); + + test('api.organizations.listCreditTransactions pins `to` across pages', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const response: CreditTransactions = await api.organizations.listCreditTransactions({ + organization: orgId, + }); + + expect(response).toEqual({ + organizationId: orgId, + from: '2026-11-01T00:00:00Z', + to: '2026-11-18T09:41:00Z', + transactions: [...transactionsPage1.transactions, ...transactionsPage2.transactions], + }); + expect(spy).toHaveBeenNthCalledWith(1, `${orgUrl}/credits/transactions?`, expectedRequest); + expect(spy).toHaveBeenNthCalledWith( + 2, + `${orgUrl}/credits/transactions?to=2026-11-18T09%3A41%3A00Z&next=djE6MTc2MTk4MTMwMjAwNDQxMDox`, + expectedRequest, + ); + }); + + test('api.organizations.listCreditTopups', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const response: CreditTopupsResponse = await api.organizations.listCreditTopups({ + organization: orgId, + from: '2026-10-01', + }); + + expect(response).toEqual(topups); + expect(spy).toHaveBeenCalledWith(`${orgUrl}/credits/topups?from=2026-10-01`, expectedRequest); + }); +}); diff --git a/tests/specs/projects-create.spec.ts b/tests/specs/projects-create.spec.ts new file mode 100644 index 0000000..17e10ad --- /dev/null +++ b/tests/specs/projects-create.spec.ts @@ -0,0 +1,52 @@ +import type { ApiClient, ProjectCreateRequest, ProjectCreateResponse } from '@/main.js'; +import { ProjectTone, ProjectType } from '@/main.js'; +import { fullProject } from '@tests/fixtures/index.js'; +import { fetchMock, getApiClient, getToken } from '@tests/support/index.js'; +import type { MockInstance } from 'vitest'; +import { beforeEach, describe, expect, test, vi } from 'vitest'; + +describe('Projects create', (): void => { + let api: ApiClient; + + beforeEach((): void => { + fullProject.mockResponses(); + fetchMock.post('https://api.localazy.com/projects', { projectId: '_a6458449029643106570' }); + + api = getApiClient(); + }); + + test('api.projects.create', async (): Promise => { + const request: ProjectCreateRequest = { + name: 'My Application', + slug: 'my-application', + sourceLanguage: 'en', + type: ProjectType.PUBLIC, + tone: ProjectTone.INFORMAL, + description: 'Mobile app localization.', + useShareTm: false, + }; + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const response: ProjectCreateResponse = await api.projects.create(request); + + expect(response).toEqual({ projectId: '_a6458449029643106570' }); + expect(spy).toHaveBeenCalledWith('https://api.localazy.com/projects', { + body: '{"name":"My Application","slug":"my-application","sourceLanguage":"en","type":"public","tone":"informal","description":"Mobile app localization.","useShareTm":false}', + headers: { + Accept: 'application/json', + Authorization: `Bearer ${getToken()}`, + 'Content-Type': 'application/json', + }, + method: 'POST', + }); + }); + + test('api.projects.create with only a name', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.projects.create({ name: 'My Application' }); + + expect(spy).toHaveBeenCalledWith( + 'https://api.localazy.com/projects', + expect.objectContaining({ body: '{"name":"My Application"}', method: 'POST' }), + ); + }); +}); diff --git a/tests/specs/segmentation.spec.ts b/tests/specs/segmentation.spec.ts new file mode 100644 index 0000000..9666fa4 --- /dev/null +++ b/tests/specs/segmentation.spec.ts @@ -0,0 +1,75 @@ +import type { ApiClient, Project, SegmentationParent } from '@/main.js'; +import { Locales } from '@/main.js'; +import { fullProject } from '@tests/fixtures/index.js'; +import { fetchMock, getApiClient, getApiUrl, getToken } from '@tests/support/index.js'; +import type { MockInstance } from 'vitest'; +import { beforeEach, describe, expect, test, vi } from 'vitest'; + +const parentsUrl: string = `${getApiUrl()}/projects/_a0000000000000000001/segmentation/parents`; + +const parent: SegmentationParent = { + id: '_e845123154101354564', + handle: '_b1c2d3e4f5061708', + key: ['home', 'intro'], + file: '_e845123154101354500', + deprecated: -1, + explicit: false, + template: '{{__llsg:a1b2c3}}\n\n{{__llsg:d4e5f6}}', + value: 'Primeiro parágrafo.\n\nSecond paragraph.', + segments: [ + { id: '_e845123154101354565', segIndex: 0 }, + { id: '_e845123154101354566', segIndex: 1 }, + ], +}; + +describe('Segmentation', (): void => { + let api: ApiClient; + let project: Project; + + beforeEach(async (): Promise => { + fullProject.mockResponses(); + fetchMock.get(`begin:${parentsUrl}/`, parent); + + api = getApiClient(); + project = await api.projects.first(); + }); + + test('api.segmentation.getParent', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const result: SegmentationParent = await api.segmentation.getParent({ + project, + parent: '_e845123154101354564', + lang: Locales.BRAZILIAN_PORTUGUESE, + }); + + expect(result).toEqual(parent); + expect(spy).toHaveBeenCalledWith(`${parentsUrl}/_e845123154101354564/pt_BR`, { + headers: { + Accept: 'application/json', + Authorization: `Bearer ${getToken()}`, + 'Content-Type': 'application/json', + }, + method: 'GET', + }); + }); + + test('api.segmentation.getParent escapes the language', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + await api.segmentation.getParent({ + project, + parent: { id: '_b1c2d3e4f5061708' } as never, + lang: 'zh#Hans', + }); + + expect(spy).toHaveBeenCalledWith( + `${parentsUrl}/_b1c2d3e4f5061708/zh%23Hans`, + expect.anything(), + ); + }); + + test('api.segmentation.getParent rejects a missing language', async (): Promise => { + await expect( + api.segmentation.getParent({ project, parent: '_b1c2d3e4f5061708', lang: '' as never }), + ).rejects.toThrow('Invalid lang language.'); + }); +}); diff --git a/tests/specs/tags.spec.ts b/tests/specs/tags.spec.ts new file mode 100644 index 0000000..87ce572 --- /dev/null +++ b/tests/specs/tags.spec.ts @@ -0,0 +1,40 @@ +import type { ApiClient, Project, ProjectTag } from '@/main.js'; +import { fullProject } from '@tests/fixtures/index.js'; +import { fetchMock, getApiClient, getApiUrl, getToken } from '@tests/support/index.js'; +import type { MockInstance } from 'vitest'; +import { beforeEach, describe, expect, test, vi } from 'vitest'; + +const tagsUrl: string = `${getApiUrl()}/projects/_a0000000000000000001/tags`; + +const tags: ProjectTag[] = [ + { id: '_e40', name: 'High priority', type: 'generic', builtIn: true }, + { id: '_e845123154101354564', name: 'android-extra', type: 'file', builtIn: false }, +]; + +describe('Tags', (): void => { + let api: ApiClient; + let project: Project; + + beforeEach(async (): Promise => { + fullProject.mockResponses(); + fetchMock.get(tagsUrl, tags); + + api = getApiClient(); + project = await api.projects.first(); + }); + + test('api.tags.list', async (): Promise => { + const spy: MockInstance = vi.spyOn(globalThis, 'fetch'); + const result: ProjectTag[] = await api.tags.list({ project }); + + expect(result).toEqual(tags); + expect(spy).toHaveBeenCalledWith(tagsUrl, { + headers: { + Accept: 'application/json', + Authorization: `Bearer ${getToken()}`, + 'Content-Type': 'application/json', + }, + method: 'GET', + }); + }); +});