From bb390c2312f7386a455fb7c1491c52dcd07e18f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20=C5=A0v=C3=A1b=C3=ADk?= Date: Wed, 25 Nov 2026 17:38:14 +0100 Subject: [PATCH 1/5] feat(cms): findings carry cause and params, with cms-schema 0.12.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit cms-schema 0.12.0 gives each finding a cause (which of its rule's causes it is) and typed params (the facts its message is made of), so a client can word findings in any language. `cms validate -o json` and `-o yaml` print them beside the English message and hint, additive to report version 1; the table and `-o text` are unchanged. The module's skipped rule now names its reason as a code, with the sentence in `message`. Report version 1 keeps `quality.skipped[].reason` English and adds `code` and `params`, and the notes on stderr print the sentence, not the code. Signed-off-by: Jan Švábík --- CHANGELOG.md | 8 ++++ README.md | 8 +++- docs/DESIGN.md | 1 + go.mod | 2 +- go.sum | 4 +- internal/cli/cms/validate.go | 37 ++++++++++++++++-- internal/cli/cms/validate_test.go | 39 ++++++++++++++++++- .../cli/testdata/golden/cms-validate.json | 9 +++++ .../cli/testdata/golden/cms-validate.yaml | 8 +++- 9 files changed, 106 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 850b5c8..9e32eb2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ this file collects what users and scripts need to know. ## Unreleased +### New + +- `norcube cms validate -o json` (and `-o yaml`) gives each finding its + `cause`, which of the rule's causes it is, and `params`, the facts its + message is made of, typed (cms-schema 0.12.0). The table, `-o text` + and the English `message` and `hint` are unchanged. A skipped quality + rule keeps its English `reason` and gains `code` and `params`. + ## 0.28.0 (2026-11-25) ### New diff --git a/README.md b/README.md index 8c89201..5ea2f1b 100644 --- a/README.md +++ b/README.md @@ -264,8 +264,12 @@ norcube cms validate ./site --quality --git --strict-quality # in CI - run: norcube cms validate --quality --git --strict-quality ``` -`-o json` prints every finding with its rule id, and with `--quality` a -`quality` summary of what was checked, skipped and guessed. +`-o json` prints every finding with its rule id, its `cause` (which of +the rule's causes it is) and `params` (the facts its message is made of, +typed), and with `--quality` a `quality` summary of what was checked, +skipped and guessed. The English `message` and `hint` stay; a tool that +words findings itself keys on `rule`, `cause` and `params`, as the +module's `report/catalog.json` lists them. ## Documentation diff --git a/docs/DESIGN.md b/docs/DESIGN.md index d3e3e5c..71375aa 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -803,6 +803,7 @@ changelog, and the owner's decisions in the planning sessions of | 2026-11-15 | `cms validate`: a `cms` group whose first command works on a site checkout, offline, with no sign-in. The checks live in the public `github.com/norcubeplatform/cms-schema` module, which the CMS service and the dashboard's fixtures share, so the CLI is a thin wrapper and cannot drift from the editor. `--fail-on` defaults to `error` (unlike `monitor status`, whose default is `none`) because a validator that exits 0 on errors would be useless in CI; findings keep their severity whatever `--fail-on` says. A failed run uses the new code `invalid`, not `unhealthy`: `unhealthy` describes a service's state, `invalid` what the command checked. The report is printed before the error so CI keeps it. The path argument completes directories only | Owner's brief: validate a whole site against every page, locally and in CI, with the rules the editor runs. Rejected: putting the checks in the CLI module (the private backend would then depend on the CLI's releases and dependency graph); a `--strict` flag (the tree already has `--fail-on` for this); naming the command `cms schema validate` (content and links are checked too) | owner | | 2026-11-23 | `cms validate --quality` (cms-schema 0.10.0): the content quality checks run only when asked for, as in the module, because their findings are advice rather than breakage; they are warnings and notices, never errors, and notices never fail a run whatever `--fail-on` says. `--strict-quality` fails on quality warnings alone (unlike `--fail-on warning`, which also fails on correctness warnings). `--git` reads when each file last changed from `git log` with a deadline; it needs `--quality`, and a git failure ends the run with its own code (`usage_error` outside a checkout, `timeout`, `error`) instead of silently skipping the outdated-translation check the person asked for. Quality is a flag, not an `--only` value, so `--only` keeps meaning the correctness checks. A finding about one language of a page that holds every language shows the language after its path in the PATH column (`title.en [en]`); `-o json` has it as `locale` | Owner's brief: run the module's quality checks from the CLI, mirroring `cms-schema-validate`. Rejected: a LOCALE column (mostly empty, and placed after MESSAGE in `-o text`); skipping the outdated check when git fails (the person asked for it) | owner | | 2026-11-25 | `cms validate --git` with cms-schema 0.11.0: an outdated translation is one whose source changed a translatable text since the translation last changed or was marked current, so `--git` hands the module a reader of the source's earlier versions (`gitlog.SourceBases`) instead of file dates. The history is read only when the checks have language versions to judge, under the same deadline; a read failure still ends the run with the same codes, and the deadline or an interrupt decides the code before what git printed (a killed `git rev-parse` reads as "not a repository"). A shallow clone is refused with `usage_error` (cms-schema 0.11.1, `gitlog.ErrShallowHistory`): its oldest commit lists every file as added, so every translation would look current, a silent pass in CI, where `actions/checkout` clones with depth 1 | A date says nothing about what changed: a changed link or a commit in another folder made a translation "outdated". Rejected: reading the history up front to fail early on a site without language versions (twice the git work for a check with nothing to judge) | owner | +| 2026-11-25 | `cms validate` with cms-schema 0.12.0: findings carry `cause` and typed `params` beside the English `message` and `hint`, added to `-o json`/`-o yaml` as the module emits them; the table and `-o text` print `message` as before. The module's skipped rule turned its `reason` from a sentence into a code (with `message`), so report version 1 keeps `quality.skipped[].reason` English and adds `code` and `params` (`qualityReport`), a CLI view of that one list over the module's summary | Owner's brief: findings are codes and parameters, words come from a catalog per client; the CLI stays English (I18N_BACKEND.md 4.3). Rejected: passing the module's `skipped` through (a changed meaning of a version 1 field needs the owner's agreement, 6.4); copying the whole summary into a CLI type (it would drift from the module) | owner | --- diff --git a/go.mod b/go.mod index a479da0..0d3b1fd 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,7 @@ require ( github.com/gofrs/flock v0.13.0 github.com/google/uuid v1.6.0 github.com/jmespath-community/go-jmespath v1.1.1 - github.com/norcubeplatform/cms-schema v0.11.1 + github.com/norcubeplatform/cms-schema v0.12.0 github.com/oapi-codegen/runtime v1.4.0 github.com/pelletier/go-toml/v2 v2.3.1 github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c diff --git a/go.sum b/go.sum index e6e8bfc..73baa14 100644 --- a/go.sum +++ b/go.sum @@ -129,8 +129,8 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= -github.com/norcubeplatform/cms-schema v0.11.1 h1:GWief9ru4UOTNlEjidKZ3LACcKWRDavJwz66l51gu1I= -github.com/norcubeplatform/cms-schema v0.11.1/go.mod h1:fY05NpvoygKgMBZjj3+R6KI1vko9CSJPJKS02n6WRh0= +github.com/norcubeplatform/cms-schema v0.12.0 h1:+rBvgxUQUORYMJloCmmu4MRjC8rsdZNB97mHVSFiymc= +github.com/norcubeplatform/cms-schema v0.12.0/go.mod h1:fY05NpvoygKgMBZjj3+R6KI1vko9CSJPJKS02n6WRh0= github.com/oapi-codegen/runtime v1.4.0 h1:KLOSFOp7UzkbS7Cs1ms6NBEKYr0WmH2wZG0KKbd2er4= github.com/oapi-codegen/runtime v1.4.0/go.mod h1:5sw5fxCDmnOzKNYmkVNF8d34kyUeejJEY8HNT2WaPec= github.com/oasdiff/yaml v0.1.1 h1:6nHx+pn9gBRM6YpBlFZFQGCCd1nuvqOBtTD3KKTgGxY= diff --git a/internal/cli/cms/validate.go b/internal/cli/cms/validate.go index 5e45dde..922df3c 100644 --- a/internal/cli/cms/validate.go +++ b/internal/cli/cms/validate.go @@ -53,7 +53,38 @@ type validateReport struct { Summary validateSummary `json:"summary" yaml:"summary"` // Quality says what the content quality checks looked at, skipped and // assumed; present only with --quality. - Quality *quality.Summary `json:"quality,omitempty" yaml:"quality,omitempty"` + Quality *qualityReport `json:"quality,omitempty" yaml:"quality,omitempty"` +} + +// qualityReport is the module's quality summary as report version 1 +// prints it. Version 1 gave a skipped rule's reason as an English +// sentence; it stays one, and the module's code and params for it are +// added beside it. +type qualityReport struct { + *quality.Summary + Skipped []skippedRule `json:"skipped,omitempty" yaml:"skipped,omitempty"` +} + +// skippedRule is a quality rule the run did not run. +type skippedRule struct { + Rule report.Rule `json:"rule" yaml:"rule"` + // Reason says why in English; Code and Params say it as data + // (quality.SkipReasons). + Reason string `json:"reason" yaml:"reason"` + Code quality.SkipReason `json:"code" yaml:"code"` + Params *report.Params `json:"params,omitempty" yaml:"params,omitempty"` +} + +// newQualityReport is s as report version 1 prints it; nil for nil. +func newQualityReport(s *quality.Summary) *qualityReport { + if s == nil { + return nil + } + q := &qualityReport{Summary: s} + for _, sk := range s.Skipped { + q.Skipped = append(q.Skipped, skippedRule{Rule: sk.Rule, Reason: sk.Message, Code: sk.Reason, Params: sk.Params}) + } + return q } // validateSummary counts what the run looked at and found. @@ -233,7 +264,7 @@ Notices never fail a run. A path that is not a CMS site exits 3.`, Files: res.Files, SchemaFiles: res.SchemaFiles, Errors: res.Errors, Warnings: res.Warnings, Notices: res.Notices, }, - Quality: res.Quality, + Quality: newQualityReport(res.Quality), } if rep.Findings == nil { rep.Findings = []report.Finding{} @@ -347,7 +378,7 @@ func findingPath(f report.Finding) string { // same in "quality"). func printQualityNotes(w io.Writer, s *quality.Summary, withGit bool) { for _, sk := range s.Skipped { - note := sk.Reason + note := sk.Message if sk.Rule == report.RuleQualityTranslationOutdated && !withGit { note += "; pass --git to read the git history" } diff --git a/internal/cli/cms/validate_test.go b/internal/cli/cms/validate_test.go index 0717781..1e0f23e 100644 --- a/internal/cli/cms/validate_test.go +++ b/internal/cli/cms/validate_test.go @@ -3,6 +3,7 @@ package cms import ( "bytes" "context" + "encoding/json" "errors" "fmt" "strings" @@ -106,7 +107,7 @@ func TestValidateGitHistoryReachesQuality(t *testing.T) { if got := outdatedLines(out); len(got) != 0 { t.Fatalf("outdated translations reported without the history:\n%s", out) } - if !strings.Contains(stderr, "skipped quality.translation_outdated") || !strings.Contains(stderr, "--git") { + if !strings.Contains(stderr, "skipped quality.translation_outdated: the history of the content files was not given; pass --git") { t.Errorf("the skipped rule is not explained: %q", stderr) } @@ -211,3 +212,39 @@ func TestFindingPathShowsTheLanguage(t *testing.T) { } } } + +// Report version 1 printed a skipped rule's reason as English: it stays +// English, with the module's code and params beside it, and the rest of +// the module's summary as it is. +func TestQualityReportKeepsSkippedReasonEnglish(t *testing.T) { + s := &quality.Summary{ + Checked: map[report.Rule]int{report.RuleQualityTitleMissing: 2}, + Skipped: []quality.Skipped{{ + Rule: report.RuleQualityImageHeavy, Reason: quality.SkipMediaUnlistable, + Params: &report.Params{Detail: "disk gone"}, Message: "the media files could not be listed: disk gone", + }}, + Drafts: 1, + } + raw, err := json.Marshal(newQualityReport(s)) + if err != nil { + t.Fatal(err) + } + var got map[string]any + if err := json.Unmarshal(raw, &got); err != nil { + t.Fatal(err) + } + skipped, _ := got["skipped"].([]any) + if len(skipped) != 1 { + t.Fatalf("skipped %s", raw) + } + sk := skipped[0].(map[string]any) + if sk["reason"] != "the media files could not be listed: disk gone" || sk["code"] != "media_unlistable" || sk["rule"] != "quality.image_heavy" { + t.Errorf("skipped %v", sk) + } + if got["drafts"] != float64(1) || got["checked"] == nil { + t.Errorf("the module's summary is missing: %s", raw) + } + if newQualityReport(nil) != nil { + t.Error("no summary is no report") + } +} diff --git a/internal/cli/testdata/golden/cms-validate.json b/internal/cli/testdata/golden/cms-validate.json index c1073ae..c37e9f4 100644 --- a/internal/cli/testdata/golden/cms-validate.json +++ b/internal/cli/testdata/golden/cms-validate.json @@ -6,6 +6,12 @@ "file": "src/content/pages/contact.md", "severity": "warning", "rule": "content.extra_keys", + "cause": "not_in_schema", + "params": { + "names": [ + "draft" + ] + }, "message": "keys draft are not in the schema", "hint": "They show in the editor's out-of-schema panel. Add them to the schema or remove them." }, @@ -14,6 +20,9 @@ "path": "link", "severity": "warning", "rule": "links.unresolved_link", + "params": { + "path": "/about/" + }, "message": "links to /about/, which no content file produces", "hint": "If the site serves this route from code, add it to knownPaths in config.yml; otherwise fix the link." } diff --git a/internal/cli/testdata/golden/cms-validate.yaml b/internal/cli/testdata/golden/cms-validate.yaml index abc56a8..0a90817 100644 --- a/internal/cli/testdata/golden/cms-validate.yaml +++ b/internal/cli/testdata/golden/cms-validate.yaml @@ -1,12 +1,18 @@ findings: - - file: src/content/pages/contact.md + - cause: not_in_schema + file: src/content/pages/contact.md hint: They show in the editor's out-of-schema panel. Add them to the schema or remove them. message: keys draft are not in the schema + params: + names: + - draft rule: content.extra_keys severity: warning - file: src/content/pages/index.md hint: If the site serves this route from code, add it to knownPaths in config.yml; otherwise fix the link. message: links to /about/, which no content file produces + params: + path: /about/ path: link rule: links.unresolved_link severity: warning From a4d1de24cdc94c25dd263e2157bd6f1fc3f5a9f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20=C5=A0v=C3=A1b=C3=ADk?= Date: Wed, 25 Nov 2026 17:44:41 +0100 Subject: [PATCH 2/5] feat(langsync): context_file key descriptions and message syntax MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A namespace in .langsync.json can name a context_file, a flat JSON object of key descriptions in the source language. sync sends the descriptions of the source file's keys with the job (contexts); the others are left out with one warning line. A missing or invalid file and a description over 1,000 characters stop the sync before anything is sent; a context_file the language scan would read as a language is refused when the project file is loaded. pull doesn't read it, and init keeps it (and language_aliases) when a namespace is picked again. namespaces create and update take --message-syntax plain|icu, from the generated client's enum; namespaces list shows it. The sync summary words each translation LangSync didn't store (key, language, code and its facts, "and N more"), counts unreviewed translations per language, and names the context file when the server refuses the descriptions. JSON summaries carry failures and unreviewedPerLanguage. The LangSync client is regenerated from the current API (the other services' clients are left as they are). Signed-off-by: Jan Švábík --- CHANGELOG.md | 52 + docs/DESIGN.md | 7 +- internal/api/apierror/apierror.go | 6 + internal/api/apierror/apierror_test.go | 22 + internal/api/langsync/langsync.gen.go | 1146 +++++++++++++---- internal/cli/golden_test.go | 2 +- internal/cli/langsync/errors.go | 14 +- internal/cli/langsync/import.go | 6 +- internal/cli/langsync/init.go | 6 + internal/cli/langsync/mark.go | 12 +- internal/cli/langsync/namespace.go | 97 +- .../cli/langsync/projectcfg/projectcfg.go | 97 ++ .../langsync/projectcfg/projectcfg_test.go | 114 ++ .../projectcfg/translations/flatjson.go | 14 +- internal/cli/langsync/sync.go | 87 +- internal/cli/langsync/sync_contexts.go | 113 ++ internal/cli/langsync/sync_interactive.go | 4 +- internal/cli/langsync/sync_issues.go | 103 +- internal/cli/langsync/sync_poll.go | 2 +- internal/cli/langsync/sync_summary_test.go | 193 +++ internal/cli/langsync/translations.go | 6 +- internal/cli/langsync_sync_test.go | 248 ++++ .../golden/langsync-namespace-list.json | 1 + .../golden/langsync-namespace-list.tsv | 2 +- .../golden/langsync-namespace-list.txt | 4 +- .../golden/langsync-namespace-list.yaml | 1 + specs/langsync.openapi.json | 953 +++++++++++++- 27 files changed, 2989 insertions(+), 323 deletions(-) create mode 100644 internal/cli/langsync/projectcfg/projectcfg_test.go create mode 100644 internal/cli/langsync/sync_contexts.go create mode 100644 internal/cli/langsync/sync_summary_test.go create mode 100644 internal/cli/langsync_sync_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 850b5c8..291ef66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,58 @@ this file collects what users and scripts need to know. ## Unreleased +### New + +- LangSync key descriptions from the project: a namespace in + `.langsync.json` can name a `context_file`, a flat JSON object + `{"key": "what the key is"}` in the source language (a relative path is + resolved like `dir`). `langsync sync` sends the descriptions of the + source file's keys with the job, and the people and the model that + translate a key see it; an empty description clears one. Descriptions + of keys the source file doesn't have are not sent, with one warning + line giving the count. A missing file, invalid JSON, a value that isn't + text and a description longer than 1,000 characters stop the sync + before anything is sent, naming the file (and the key). A + `context_file` that sits directly in the namespace's `dir` with a + `.json` name is refused when the project file is read, because every + such file there is read as a language: keep it in a subdirectory such + as `context/en.json`. `langsync pull` doesn't read it. No new flag. +- `langsync namespaces create` and `update` take `--message-syntax plain|icu`: + what the namespace's strings are. With `icu` LangSync translates ICU + MessageFormat per plural form of each language and checks every + translation and every write before storing it. `namespaces list` shows + it in a SYNTAX column. +- The `langsync sync` summary lists every translation LangSync didn't + store, with the key, the language, the reason (`placeholders_changed`, + `icu_invalid`, `plural_forms`, `tags_changed`, `glossary_term_missing`, + `too_many_variants`, `untranslated`, `model_failed`) and its facts, and + "and N more" for the ones the server didn't list. A "Not reviewed" + block counts per language the translations nobody has marked reviewed. + A refusal of the descriptions (`SYNC_CONTEXTS_INVALID`) names the + context file and the key. + +### Fixes + +- `langsync init` keeps a namespace's `language_aliases` and + `context_file` when the namespace is picked again. + +### Changes for scripts + +- `langsync sync` / `pull` / `init -o json|yaml`: each namespace's summary + has `failures` (the job's entries: `phase`, `opIdx`, `mark`, `error`, + and for a translation not stored `code`, `languageCode`, `offset`, + `argument`, `missing`, `unexpected`; one entry with `dropped` stands for + the entries not listed) and `unreviewedPerLanguage` (`{languageCode: + count}`), both left out when the job has none. `-o text` columns are + unchanged. +- `langsync namespaces list -o json|yaml` has `messageSyntax` (`plain` or + `icu`); `-o text` has it as a new last column. `namespaces create` and + `update -o json` have `messageSyntax` when the command set it. +- A LangSync refusal whose body carries a data object (such as + `TERM_TRANSLATION_INVALID` from `translations set` or `terms add`, or + `TERM_IMPORT_TRANSLATIONS_INVALID` from `terms import`) has it in the + JSON error's `details.data`. + ## 0.28.0 (2026-11-25) ### New diff --git a/docs/DESIGN.md b/docs/DESIGN.md index d3e3e5c..c9514cd 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -803,6 +803,7 @@ changelog, and the owner's decisions in the planning sessions of | 2026-11-15 | `cms validate`: a `cms` group whose first command works on a site checkout, offline, with no sign-in. The checks live in the public `github.com/norcubeplatform/cms-schema` module, which the CMS service and the dashboard's fixtures share, so the CLI is a thin wrapper and cannot drift from the editor. `--fail-on` defaults to `error` (unlike `monitor status`, whose default is `none`) because a validator that exits 0 on errors would be useless in CI; findings keep their severity whatever `--fail-on` says. A failed run uses the new code `invalid`, not `unhealthy`: `unhealthy` describes a service's state, `invalid` what the command checked. The report is printed before the error so CI keeps it. The path argument completes directories only | Owner's brief: validate a whole site against every page, locally and in CI, with the rules the editor runs. Rejected: putting the checks in the CLI module (the private backend would then depend on the CLI's releases and dependency graph); a `--strict` flag (the tree already has `--fail-on` for this); naming the command `cms schema validate` (content and links are checked too) | owner | | 2026-11-23 | `cms validate --quality` (cms-schema 0.10.0): the content quality checks run only when asked for, as in the module, because their findings are advice rather than breakage; they are warnings and notices, never errors, and notices never fail a run whatever `--fail-on` says. `--strict-quality` fails on quality warnings alone (unlike `--fail-on warning`, which also fails on correctness warnings). `--git` reads when each file last changed from `git log` with a deadline; it needs `--quality`, and a git failure ends the run with its own code (`usage_error` outside a checkout, `timeout`, `error`) instead of silently skipping the outdated-translation check the person asked for. Quality is a flag, not an `--only` value, so `--only` keeps meaning the correctness checks. A finding about one language of a page that holds every language shows the language after its path in the PATH column (`title.en [en]`); `-o json` has it as `locale` | Owner's brief: run the module's quality checks from the CLI, mirroring `cms-schema-validate`. Rejected: a LOCALE column (mostly empty, and placed after MESSAGE in `-o text`); skipping the outdated check when git fails (the person asked for it) | owner | | 2026-11-25 | `cms validate --git` with cms-schema 0.11.0: an outdated translation is one whose source changed a translatable text since the translation last changed or was marked current, so `--git` hands the module a reader of the source's earlier versions (`gitlog.SourceBases`) instead of file dates. The history is read only when the checks have language versions to judge, under the same deadline; a read failure still ends the run with the same codes, and the deadline or an interrupt decides the code before what git printed (a killed `git rev-parse` reads as "not a repository"). A shallow clone is refused with `usage_error` (cms-schema 0.11.1, `gitlog.ErrShallowHistory`): its oldest commit lists every file as added, so every translation would look current, a silent pass in CI, where `actions/checkout` clones with depth 1 | A date says nothing about what changed: a changed link or a commit in another folder made a translation "outdated". Rejected: reading the history up front to fail early on a site without language versions (twice the git work for a check with nothing to judge) | owner | +| 2026-11-25 | LangSync key descriptions come from a `context_file` named per namespace in `.langsync.json`, read whenever it is configured (no flag), and only by commands that push (`pull` pushes nothing, so it doesn't read it). A file the language scan would read (`.json` directly in `dir`, by the same rule as `ListLangsInDir`) is refused when the project file is loaded; descriptions of keys the source file lacks are left out with one warning line, because the server refuses them and a renamed key shouldn't stop a sync; the file being unreadable stops it before anything is sent. `--message-syntax` takes its values from the generated client's enum, checked against the spec by a test. The sync summary words each failure code itself and keeps the server's English for codes it doesn't know | The backend's key descriptions and message syntax (owner's i18n plan). Rejected: a `--contexts` flag (a project setting belongs in the project file); sending every description and letting the server refuse (one stale entry would fail the whole namespace) | owner | --- @@ -1045,8 +1046,10 @@ observable contract and will be announced in the changelog. 7; a failed sync job is a plain error rather than `job_failed`; some usage errors exit 1; several local "Cancelled." implementations; direct `os.Stderr` writes; vocabulary mixes "mark" and "term" (`terms add` says - "Add a new mark"). `sync`, `pull`, `init` and the project file code have - no tests yet. Exit-code fixes here are "Changes for scripts". + "Add a new mark"). `sync`, `pull`, `init` and the project file code are + tested only for key descriptions (`context_file`), the summary and + `init` keeping an entry's hand-written fields. Exit-code fixes here are + "Changes for scripts". - **JSON shapes (before 1.0).** Several write commands return ad-hoc maps instead of the API resource; `backup policies list` returns attachments instead of definitions with `--datasource`. diff --git a/internal/api/apierror/apierror.go b/internal/api/apierror/apierror.go index 66428f7..3f9dca9 100644 --- a/internal/api/apierror/apierror.go +++ b/internal/api/apierror/apierror.go @@ -28,6 +28,9 @@ const maxRawBody = 500 type Typed struct { Msg string Type string + // Data is the body's machine-readable data object (a refusal's reason + // and facts), when it has one; it goes to the error's details. + Data any } // Format builds the standard "service METHOD URL: detail" error as a @@ -51,6 +54,9 @@ func Format(service string, resp *http.Response, body []byte, typed ...*Typed) e e.Message = fmt.Sprintf("status %d", e.HTTPStatus) } e.Code = clierr.CodeForStatus(e.HTTPStatus, e.Type) + if t.Data != nil { + e.Details = map[string]any{"data": t.Data} + } return e } } diff --git a/internal/api/apierror/apierror_test.go b/internal/api/apierror/apierror_test.go index 63865bf..b67f375 100644 --- a/internal/api/apierror/apierror_test.go +++ b/internal/api/apierror/apierror_test.go @@ -91,3 +91,25 @@ func TestFormatProblemScopeAndForbidden(t *testing.T) { t.Errorf("text %q", err.Error()) } } + +func TestFormatTypedBodyKeepsItsData(t *testing.T) { + data := map[string]any{"reason": "too_long", "key": "checkout.total", "maxChars": 1000} + err := Format("langsync", respFor("POST", "https://api.test/s", 400), nil, + &Typed{Msg: "contexts invalid", Type: "SYNC_CONTEXTS_INVALID", Data: data}) + var ce *clierr.Error + if !errors.As(err, &ce) { + t.Fatalf("not a clierr.Error: %T", err) + } + d, ok := ce.Details.(map[string]any) + if !ok || d["data"] == nil { + t.Fatalf("details %v", ce.Details) + } + if ce.Code != clierr.CodeValidation { + t.Fatalf("code %q", ce.Code) + } + // Without data there are no details. + _ = errors.As(Format("langsync", respFor("GET", "https://api.test/s", 400), nil, &Typed{Msg: "bad", Type: "X"}), &ce) + if ce.Details != nil { + t.Fatalf("details without data: %v", ce.Details) + } +} diff --git a/internal/api/langsync/langsync.gen.go b/internal/api/langsync/langsync.gen.go index 9251a18..138d437 100644 --- a/internal/api/langsync/langsync.gen.go +++ b/internal/api/langsync/langsync.gen.go @@ -17,30 +17,58 @@ import ( openapi_types "github.com/oapi-codegen/runtime/types" ) +// Defines values for ConstantsAITranslationWorkWindow. +const ( + AITranslationWorkWindowDay ConstantsAITranslationWorkWindow = "day" + AITranslationWorkWindowHour ConstantsAITranslationWorkWindow = "hour" +) + +// Valid indicates whether the value is a known member of the ConstantsAITranslationWorkWindow enum. +func (e ConstantsAITranslationWorkWindow) Valid() bool { + switch e { + case AITranslationWorkWindowDay: + return true + case AITranslationWorkWindowHour: + return true + default: + return false + } +} + // Defines values for ConstantsAuditAction. const ( - AuditActionAPIKeyCreated ConstantsAuditAction = "apikey.created" - AuditActionAPIKeyDeleted ConstantsAuditAction = "apikey.deleted" - AuditActionCustomLanguageCreated ConstantsAuditAction = "custom_language.created" - AuditActionCustomLanguageDeleted ConstantsAuditAction = "custom_language.deleted" - AuditActionCustomPromptCreated ConstantsAuditAction = "custom_prompt.created" - AuditActionCustomPromptDeleted ConstantsAuditAction = "custom_prompt.deleted" - AuditActionCustomPromptUpdated ConstantsAuditAction = "custom_prompt.updated" - AuditActionGlossaryCreated ConstantsAuditAction = "glossary.created" - AuditActionGlossaryItemCreated ConstantsAuditAction = "glossary_item.created" - AuditActionGlossaryItemDeleted ConstantsAuditAction = "glossary_item.deleted" - AuditActionGlossaryItemUpdated ConstantsAuditAction = "glossary_item.updated" - AuditActionGlossaryLanguageAttached ConstantsAuditAction = "glossary.language_attached" - AuditActionMigratorImported ConstantsAuditAction = "migrator.imported" - AuditActionNamespaceCreated ConstantsAuditAction = "namespace.created" - AuditActionNamespaceDeleted ConstantsAuditAction = "namespace.deleted" - AuditActionNamespaceLanguageAdded ConstantsAuditAction = "namespace.language_added" - AuditActionNamespaceLanguageRemoved ConstantsAuditAction = "namespace.language_removed" - AuditActionNamespaceUpdated ConstantsAuditAction = "namespace.updated" - AuditActionSyncJobCompleted ConstantsAuditAction = "sync_job.completed" - AuditActionSyncJobCreated ConstantsAuditAction = "sync_job.created" - AuditActionSyncJobFailed ConstantsAuditAction = "sync_job.failed" - AuditActionTermImportFinished ConstantsAuditAction = "term_import.finished" + AuditActionAPIKeyCreated ConstantsAuditAction = "apikey.created" + AuditActionAPIKeyDeleted ConstantsAuditAction = "apikey.deleted" + AuditActionCustomLanguageCreated ConstantsAuditAction = "custom_language.created" + AuditActionCustomLanguageDeleted ConstantsAuditAction = "custom_language.deleted" + AuditActionCustomPromptCreated ConstantsAuditAction = "custom_prompt.created" + AuditActionCustomPromptDeleted ConstantsAuditAction = "custom_prompt.deleted" + AuditActionCustomPromptUpdated ConstantsAuditAction = "custom_prompt.updated" + AuditActionGlossaryCreated ConstantsAuditAction = "glossary.created" + AuditActionGlossaryItemCreated ConstantsAuditAction = "glossary_item.created" + AuditActionGlossaryItemDeleted ConstantsAuditAction = "glossary_item.deleted" + AuditActionGlossaryItemTranslationAdded ConstantsAuditAction = "glossary_item.translation_added" + AuditActionGlossaryItemUpdated ConstantsAuditAction = "glossary_item.updated" + AuditActionGlossaryLanguageAttached ConstantsAuditAction = "glossary.language_attached" + AuditActionMigratorImported ConstantsAuditAction = "migrator.imported" + AuditActionNamespaceCreated ConstantsAuditAction = "namespace.created" + AuditActionNamespaceDeleted ConstantsAuditAction = "namespace.deleted" + AuditActionNamespaceLanguageAdded ConstantsAuditAction = "namespace.language_added" + AuditActionNamespaceLanguageRemoved ConstantsAuditAction = "namespace.language_removed" + AuditActionNamespaceUpdated ConstantsAuditAction = "namespace.updated" + AuditActionSyncJobCompleted ConstantsAuditAction = "sync_job.completed" + AuditActionSyncJobCreated ConstantsAuditAction = "sync_job.created" + AuditActionSyncJobFailed ConstantsAuditAction = "sync_job.failed" + AuditActionTermCreated ConstantsAuditAction = "term.created" + AuditActionTermDeleted ConstantsAuditAction = "term.deleted" + AuditActionTermImportFinished ConstantsAuditAction = "term_import.finished" + AuditActionTermTranslationUpdated ConstantsAuditAction = "term_translation.updated" + AuditActionTermUpdated ConstantsAuditAction = "term.updated" + AuditActionTranslationMissingRequested ConstantsAuditAction = "translation.missing_requested" + AuditActionTranslationRecommended ConstantsAuditAction = "translation.recommended" + AuditActionTranslationReviewed ConstantsAuditAction = "translation.reviewed" + AuditActionTranslationTextTranslated ConstantsAuditAction = "translation.text_translated" + AuditActionTranslationTextsTranslated ConstantsAuditAction = "translation.texts_translated" ) // Valid indicates whether the value is a known member of the ConstantsAuditAction enum. @@ -66,6 +94,8 @@ func (e ConstantsAuditAction) Valid() bool { return true case AuditActionGlossaryItemDeleted: return true + case AuditActionGlossaryItemTranslationAdded: + return true case AuditActionGlossaryItemUpdated: return true case AuditActionGlossaryLanguageAttached: @@ -88,8 +118,26 @@ func (e ConstantsAuditAction) Valid() bool { return true case AuditActionSyncJobFailed: return true + case AuditActionTermCreated: + return true + case AuditActionTermDeleted: + return true case AuditActionTermImportFinished: return true + case AuditActionTermTranslationUpdated: + return true + case AuditActionTermUpdated: + return true + case AuditActionTranslationMissingRequested: + return true + case AuditActionTranslationRecommended: + return true + case AuditActionTranslationReviewed: + return true + case AuditActionTranslationTextTranslated: + return true + case AuditActionTranslationTextsTranslated: + return true default: return false } @@ -105,6 +153,7 @@ const ( AuditTargetMigrator ConstantsAuditTargetType = "migrator" AuditTargetNamespace ConstantsAuditTargetType = "namespace" AuditTargetSyncJob ConstantsAuditTargetType = "sync_job" + AuditTargetTerm ConstantsAuditTargetType = "term" AuditTargetTermImport ConstantsAuditTargetType = "term_import" ) @@ -127,6 +176,8 @@ func (e ConstantsAuditTargetType) Valid() bool { return true case AuditTargetSyncJob: return true + case AuditTargetTerm: + return true case AuditTargetTermImport: return true default: @@ -179,6 +230,48 @@ func (e ConstantsGlossaryItemType) Valid() bool { } } +// Defines values for ConstantsNamespaceMessageSyntax. +const ( + NamespaceMessageSyntaxICU ConstantsNamespaceMessageSyntax = "icu" + NamespaceMessageSyntaxPlain ConstantsNamespaceMessageSyntax = "plain" +) + +// Valid indicates whether the value is a known member of the ConstantsNamespaceMessageSyntax enum. +func (e ConstantsNamespaceMessageSyntax) Valid() bool { + switch e { + case NamespaceMessageSyntaxICU: + return true + case NamespaceMessageSyntaxPlain: + return true + default: + return false + } +} + +// Defines values for ConstantsSyncContextsProblem. +const ( + SyncContextsProblemNotText ConstantsSyncContextsProblem = "not_text" + SyncContextsProblemTooLong ConstantsSyncContextsProblem = "too_long" + SyncContextsProblemTooMany ConstantsSyncContextsProblem = "too_many" + SyncContextsProblemUnknownKey ConstantsSyncContextsProblem = "unknown_key" +) + +// Valid indicates whether the value is a known member of the ConstantsSyncContextsProblem enum. +func (e ConstantsSyncContextsProblem) Valid() bool { + switch e { + case SyncContextsProblemNotText: + return true + case SyncContextsProblemTooLong: + return true + case SyncContextsProblemTooMany: + return true + case SyncContextsProblemUnknownKey: + return true + default: + return false + } +} + // Defines values for ConstantsTermBulkImportStatus. const ( TermBulkImportStatusCompleted ConstantsTermBulkImportStatus = "completed" @@ -251,6 +344,60 @@ func (e ConstantsTermImportFormat) Valid() bool { } } +// Defines values for ConstantsTermReviewProblem. +const ( + TermReviewProblemNoTerms ConstantsTermReviewProblem = "no_terms" + TermReviewProblemTooManyTerms ConstantsTermReviewProblem = "too_many_terms" +) + +// Valid indicates whether the value is a known member of the ConstantsTermReviewProblem enum. +func (e ConstantsTermReviewProblem) Valid() bool { + switch e { + case TermReviewProblemNoTerms: + return true + case TermReviewProblemTooManyTerms: + return true + default: + return false + } +} + +// Defines values for ConstantsTermTranslationProblem. +const ( + TermTranslationProblemGlossaryTermMissing ConstantsTermTranslationProblem = "glossary_term_missing" + TermTranslationProblemICUInvalid ConstantsTermTranslationProblem = "icu_invalid" + TermTranslationProblemModelFailed ConstantsTermTranslationProblem = "model_failed" + TermTranslationProblemPlaceholdersChanged ConstantsTermTranslationProblem = "placeholders_changed" + TermTranslationProblemPluralForms ConstantsTermTranslationProblem = "plural_forms" + TermTranslationProblemTagsChanged ConstantsTermTranslationProblem = "tags_changed" + TermTranslationProblemTooManyVariants ConstantsTermTranslationProblem = "too_many_variants" + TermTranslationProblemUntranslated ConstantsTermTranslationProblem = "untranslated" +) + +// Valid indicates whether the value is a known member of the ConstantsTermTranslationProblem enum. +func (e ConstantsTermTranslationProblem) Valid() bool { + switch e { + case TermTranslationProblemGlossaryTermMissing: + return true + case TermTranslationProblemICUInvalid: + return true + case TermTranslationProblemModelFailed: + return true + case TermTranslationProblemPlaceholdersChanged: + return true + case TermTranslationProblemPluralForms: + return true + case TermTranslationProblemTagsChanged: + return true + case TermTranslationProblemTooManyVariants: + return true + case TermTranslationProblemUntranslated: + return true + default: + return false + } +} + // Defines values for DtoDTOTermImportStatus. const ( Completed DtoDTOTermImportStatus = "completed" @@ -277,62 +424,71 @@ func (e DtoDTOTermImportStatus) Valid() bool { // Defines values for ResponseType. const ( - ErrBackupCodeInvalid ResponseType = "BACKUP_CODE_INVALID" - ErrColumnCountMismatch ResponseType = "COLUMN_COUNT_MISMATCH" - ErrConflict ResponseType = "CONFLICT" - ErrConnectionAlreadyExists ResponseType = "CONNECTION_ALREADY_EXISTS" - ErrCustomPromptNotShared ResponseType = "CUSTOM_PROMPT_NOT_SHARED" - ErrDuplicate ResponseType = "DUPLICATE" - ErrEmailRequired ResponseType = "EMAIL_REQUIRED" - ErrEmpty ResponseType = "EMPTY" - ErrEmptyValue ResponseType = "EMPTY_VALUE" - ErrForbidden ResponseType = "FORBIDDEN" - ErrImportInvalidFile ResponseType = "IMPORT_INVALID_FILE" - ErrImportUnsupportedFormat ResponseType = "IMPORT_UNSUPPORTED_FORMAT" - ErrInnovationAgencyIDRequired ResponseType = "INNOVATION_AGENCY_ID_REQUIRED" - ErrInsufficientPermissions ResponseType = "INSUFFICIENT_PERMISSIONS" - ErrInsufficientScope ResponseType = "INSUFFICIENT_SCOPE" - ErrInternalServer ResponseType = "INTERNAL_SERVER_ERROR" - ErrInvalidCustomPrompt ResponseType = "INVALID_CUSTOM_PROMPT" - ErrInvalidImportStatus ResponseType = "INVALID_IMPORT_STATUS" - ErrInvalidName ResponseType = "INVALID_NAME" - ErrInvalidOldPassword ResponseType = "INVALID_OLD_PASSWORD" - ErrInvalidRequest ResponseType = "INVALID_REQUEST" - ErrInvalidRole ResponseType = "INVALID_ROLE" - ErrInvalidToken ResponseType = "INVALID_TOKEN" - ErrLanguageNotInNamespace ResponseType = "LANGUAGE_NOT_IN_NAMESPACE" - ErrLoginIntentToken ResponseType = "LOGIN_INTENT_TOKEN" - ErrMissingBackupCode ResponseType = "MISSING_BACKUP_CODE" - ErrMissingNewPassword ResponseType = "MISSING_NEW_PASSWORD" - ErrMissingPermissions ResponseType = "MISSING_PERMISSIONS" - ErrMissingResetPasswordSecret ResponseType = "MISSING_RESET_PASSWORD_SECRET" - ErrNameRequired ResponseType = "NAME_REQUIRED" - ErrNamespaceMissing ResponseType = "NAMESPACE_MISSING" - ErrNewPasswordRequired ResponseType = "NEW_PASSWORD_REQUIRED" - ErrNoConnections ResponseType = "NO_CONNECTIONS" - ErrNoTranslationSource ResponseType = "NO_TRANSLATION_SOURCE" - ErrNotFound ResponseType = "NOT_FOUND" - ErrNotImplemented ResponseType = "NOT_IMPLEMENTED" - ErrOTPInvalid ResponseType = "OTP_INVALID" - ErrOldPasswordRequired ResponseType = "OLD_PASSWORD_REQUIRED" - ErrOrgBlocked ResponseType = "ORG_BLOCKED" - ErrOrganizationMissing ResponseType = "ORGANIZATION_MISSING" - ErrPasswordRequired ResponseType = "PASSWORD_REQUIRED" - ErrPayloadInvalid ResponseType = "INVALID_PAYLOAD" - ErrSecretExpired ResponseType = "SECRET_EXPIRED" - ErrSecretNotFound ResponseType = "SECRET_NOT_FOUND" - ErrSetupRequired ResponseType = "SETUP_REQUIRED" - ErrTermAlreadyExists ResponseType = "TERM_ALREADY_EXISTS" - ErrTermIsRequired ResponseType = "TERM_IS_REQUIRED" - ErrTooManyRequests ResponseType = "TOO_MANY_REQUESTS" - ErrUnauthorized ResponseType = "UNAUTHORIZED" - ErrUserAlreadyExists ResponseType = "USER_ALREADY_EXISTS" - ErrUserNotFound ResponseType = "USER_NOT_FOUND" + ErrAITranslationBudgetExceeded ResponseType = "AI_TRANSLATION_BUDGET_EXCEEDED" + ErrBackupCodeInvalid ResponseType = "BACKUP_CODE_INVALID" + ErrColumnCountMismatch ResponseType = "COLUMN_COUNT_MISMATCH" + ErrConflict ResponseType = "CONFLICT" + ErrConnectionAlreadyExists ResponseType = "CONNECTION_ALREADY_EXISTS" + ErrCustomPromptNotShared ResponseType = "CUSTOM_PROMPT_NOT_SHARED" + ErrDuplicate ResponseType = "DUPLICATE" + ErrEmailRequired ResponseType = "EMAIL_REQUIRED" + ErrEmpty ResponseType = "EMPTY" + ErrEmptyValue ResponseType = "EMPTY_VALUE" + ErrForbidden ResponseType = "FORBIDDEN" + ErrImportInvalidFile ResponseType = "IMPORT_INVALID_FILE" + ErrImportUnsupportedFormat ResponseType = "IMPORT_UNSUPPORTED_FORMAT" + ErrInnovationAgencyIDRequired ResponseType = "INNOVATION_AGENCY_ID_REQUIRED" + ErrInsufficientPermissions ResponseType = "INSUFFICIENT_PERMISSIONS" + ErrInsufficientScope ResponseType = "INSUFFICIENT_SCOPE" + ErrInternalServer ResponseType = "INTERNAL_SERVER_ERROR" + ErrInvalidCustomPrompt ResponseType = "INVALID_CUSTOM_PROMPT" + ErrInvalidImportStatus ResponseType = "INVALID_IMPORT_STATUS" + ErrInvalidMessageSyntax ResponseType = "INVALID_MESSAGE_SYNTAX" + ErrInvalidName ResponseType = "INVALID_NAME" + ErrInvalidOldPassword ResponseType = "INVALID_OLD_PASSWORD" + ErrInvalidRequest ResponseType = "INVALID_REQUEST" + ErrInvalidRole ResponseType = "INVALID_ROLE" + ErrInvalidToken ResponseType = "INVALID_TOKEN" + ErrLanguageNotInNamespace ResponseType = "LANGUAGE_NOT_IN_NAMESPACE" + ErrLoginIntentToken ResponseType = "LOGIN_INTENT_TOKEN" + ErrMissingBackupCode ResponseType = "MISSING_BACKUP_CODE" + ErrMissingNewPassword ResponseType = "MISSING_NEW_PASSWORD" + ErrMissingPermissions ResponseType = "MISSING_PERMISSIONS" + ErrMissingResetPasswordSecret ResponseType = "MISSING_RESET_PASSWORD_SECRET" + ErrNameRequired ResponseType = "NAME_REQUIRED" + ErrNamespaceMissing ResponseType = "NAMESPACE_MISSING" + ErrNewPasswordRequired ResponseType = "NEW_PASSWORD_REQUIRED" + ErrNoConnections ResponseType = "NO_CONNECTIONS" + ErrNoTranslationSource ResponseType = "NO_TRANSLATION_SOURCE" + ErrNotFound ResponseType = "NOT_FOUND" + ErrNotImplemented ResponseType = "NOT_IMPLEMENTED" + ErrOTPInvalid ResponseType = "OTP_INVALID" + ErrOldPasswordRequired ResponseType = "OLD_PASSWORD_REQUIRED" + ErrOrgBlocked ResponseType = "ORG_BLOCKED" + ErrOrganizationMissing ResponseType = "ORGANIZATION_MISSING" + ErrPasswordRequired ResponseType = "PASSWORD_REQUIRED" + ErrPayloadInvalid ResponseType = "INVALID_PAYLOAD" + ErrSecretExpired ResponseType = "SECRET_EXPIRED" + ErrSecretNotFound ResponseType = "SECRET_NOT_FOUND" + ErrSetupRequired ResponseType = "SETUP_REQUIRED" + ErrSyncContextsInvalid ResponseType = "SYNC_CONTEXTS_INVALID" + ErrTermAlreadyExists ResponseType = "TERM_ALREADY_EXISTS" + ErrTermFilterLanguageRequired ResponseType = "TERM_FILTER_LANGUAGE_REQUIRED" + ErrTermImportTranslationsInvalid ResponseType = "TERM_IMPORT_TRANSLATIONS_INVALID" + ErrTermIsRequired ResponseType = "TERM_IS_REQUIRED" + ErrTermReviewInvalid ResponseType = "TERM_REVIEW_INVALID" + ErrTermTranslationInvalid ResponseType = "TERM_TRANSLATION_INVALID" + ErrTooManyRequests ResponseType = "TOO_MANY_REQUESTS" + ErrUnauthorized ResponseType = "UNAUTHORIZED" + ErrUserAlreadyExists ResponseType = "USER_ALREADY_EXISTS" + ErrUserNotFound ResponseType = "USER_NOT_FOUND" ) // Valid indicates whether the value is a known member of the ResponseType enum. func (e ResponseType) Valid() bool { switch e { + case ErrAITranslationBudgetExceeded: + return true case ErrBackupCodeInvalid: return true case ErrColumnCountMismatch: @@ -369,6 +525,8 @@ func (e ResponseType) Valid() bool { return true case ErrInvalidImportStatus: return true + case ErrInvalidMessageSyntax: + return true case ErrInvalidName: return true case ErrInvalidOldPassword: @@ -423,10 +581,20 @@ func (e ResponseType) Valid() bool { return true case ErrSetupRequired: return true + case ErrSyncContextsInvalid: + return true case ErrTermAlreadyExists: return true + case ErrTermFilterLanguageRequired: + return true + case ErrTermImportTranslationsInvalid: + return true case ErrTermIsRequired: return true + case ErrTermReviewInvalid: + return true + case ErrTermTranslationInvalid: + return true case ErrTooManyRequests: return true case ErrUnauthorized: @@ -482,6 +650,9 @@ type AuditPayloadListResponse struct { NextCursorId *string `json:"nextCursorId,omitempty"` } +// ConstantsAITranslationWorkWindow defines model for constants.AITranslationWorkWindow. +type ConstantsAITranslationWorkWindow string + // ConstantsAuditAction defines model for constants.AuditAction. type ConstantsAuditAction string @@ -491,6 +662,12 @@ type ConstantsAuditTargetType string // ConstantsGlossaryItemType defines model for constants.GlossaryItemType. type ConstantsGlossaryItemType string +// ConstantsNamespaceMessageSyntax defines model for constants.NamespaceMessageSyntax. +type ConstantsNamespaceMessageSyntax string + +// ConstantsSyncContextsProblem defines model for constants.SyncContextsProblem. +type ConstantsSyncContextsProblem string + // ConstantsTermBulkImportStatus defines model for constants.TermBulkImportStatus. type ConstantsTermBulkImportStatus string @@ -500,6 +677,18 @@ type ConstantsTermImportCSVColumnSetupType string // ConstantsTermImportFormat defines model for constants.TermImportFormat. type ConstantsTermImportFormat string +// ConstantsTermReviewProblem defines model for constants.TermReviewProblem. +type ConstantsTermReviewProblem string + +// ConstantsTermTranslationProblem defines model for constants.TermTranslationProblem. +type ConstantsTermTranslationProblem string + +// DtoAITranslationBudgetRefusal defines model for dto.AITranslationBudgetRefusal. +type DtoAITranslationBudgetRefusal struct { + RetryAt string `json:"retryAt"` + Window ConstantsAITranslationWorkWindow `json:"window"` +} + // DtoAPIKey defines model for dto.APIKey. type DtoAPIKey struct { CreatedAt string `json:"createdAt"` @@ -554,6 +743,12 @@ type DtoDTOLanguageConnection struct { LanguageId *int `json:"language_id,omitempty"` LanguageName *string `json:"language_name,omitempty"` LanguageShared *bool `json:"language_shared,omitempty"` + + // UnreviewedCount UnreviewedCount is how many of the language's translations have + // text that nobody marked reviewed (POST + // .../translations/{languageId}/review). 0 for the default language, + // whose texts are what the others are translated from. + UnreviewedCount int `json:"unreviewedCount"` } // DtoDTONamespace defines model for dto.DTONamespace. @@ -568,11 +763,16 @@ type DtoDTONamespace struct { DefaultLanguageId *int `json:"defaultLanguageId,omitempty"` Id *string `json:"id,omitempty"` Languages *[]string `json:"languages,omitempty"` - Name *string `json:"name,omitempty"` - OrganizationId *string `json:"organization_id,omitempty"` - Progress *float32 `json:"progress,omitempty"` - TotalTerms *int `json:"total_terms,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` + + // MessageSyntax MessageSyntax is what the namespace's strings are: plain (variables + // kept as they are) or icu (ICU MessageFormat 1, translated per plural + // form and checked before storing). + MessageSyntax ConstantsNamespaceMessageSyntax `json:"messageSyntax"` + Name *string `json:"name,omitempty"` + OrganizationId *string `json:"organization_id,omitempty"` + Progress *float32 `json:"progress,omitempty"` + TotalTerms *int `json:"total_terms,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` } // DtoDTOSyncJob defines model for dto.DTOSyncJob. @@ -618,8 +818,13 @@ type DtoDTOSyncJob struct { Status *string `json:"status,omitempty"` StillUntranslatedCount *int `json:"stillUntranslatedCount,omitempty"` Strategy *string `json:"strategy,omitempty"` - UpdatedCount *int `json:"updatedCount,omitempty"` - WaitForAutotranslate *bool `json:"waitForAutotranslate,omitempty"` + + // UnreviewedPerLanguage UnreviewedPerLanguage counts, per language code, the translations + // with text nobody marked reviewed when the job finished (not the + // job's source language). Set on status='completed'. + UnreviewedPerLanguage *map[string]int `json:"unreviewedPerLanguage,omitempty"` + UpdatedCount *int `json:"updatedCount,omitempty"` + WaitForAutotranslate *bool `json:"waitForAutotranslate,omitempty"` } // DtoDTOSyncJobCreateResponse defines model for dto.DTOSyncJobCreateResponse. @@ -629,10 +834,32 @@ type DtoDTOSyncJobCreateResponse struct { // DtoDTOSyncJobFailure defines model for dto.DTOSyncJobFailure. type DtoDTOSyncJobFailure struct { + Argument *string `json:"argument,omitempty"` + + // Code Code says why a translation was not stored: an automatic + // translation the checks refused (phase autotranslate) or a pushed + // value an ICU namespace refused (phase push). Absent for other + // failures. + Code *ConstantsTermTranslationProblem `json:"code,omitempty"` + + // Dropped Dropped counts the phase's failures not listed (more than 500); set + // on one summary entry. + Dropped *int `json:"dropped,omitempty"` + + // Error Error is English, for logs and older clients; a client words Code. Error *string `json:"error,omitempty"` - Mark *string `json:"mark,omitempty"` - OpIdx *int `json:"opIdx,omitempty"` - Phase *string `json:"phase,omitempty"` + + // LanguageCode LanguageCode is the language of the translation Code is about. + LanguageCode *string `json:"languageCode,omitempty"` + Mark *string `json:"mark,omitempty"` + Missing *[]string `json:"missing,omitempty"` + + // Offset The facts of Code: where an ICU message stops being valid, which + // plural or select, which forms, variables, tags or terms. + Offset *int `json:"offset,omitempty"` + OpIdx *int `json:"opIdx,omitempty"` + Phase *string `json:"phase,omitempty"` + Unexpected *[]string `json:"unexpected,omitempty"` } // DtoDTOSyncJobOp defines model for dto.DTOSyncJobOp. @@ -719,6 +946,83 @@ type DtoLangInfo struct { Id int `json:"id"` } +// DtoMarkReviewedRequest defines model for dto.MarkReviewedRequest. +type DtoMarkReviewedRequest struct { + // TermIds TermIDs are the terms, 1 to 1,000. + TermIds []int `json:"termIds"` +} + +// DtoMarkReviewedResponse defines model for dto.MarkReviewedResponse. +type DtoMarkReviewedResponse struct { + Reviewed int `json:"reviewed"` +} + +// DtoSyncContextsProblem defines model for dto.SyncContextsProblem. +type DtoSyncContextsProblem struct { + // Key Key is the entry it is about (unknown_key, too_long, not_text). + Key *string `json:"key,omitempty"` + + // Max Max is the most entries the request may have (too_many). + Max *int `json:"max,omitempty"` + + // MaxChars MaxChars is the longest a description may be (too_long). + MaxChars *int `json:"maxChars,omitempty"` + Reason ConstantsSyncContextsProblem `json:"reason"` +} + +// DtoTermImportTranslationProblem defines model for dto.TermImportTranslationProblem. +type DtoTermImportTranslationProblem struct { + // Argument Argument is the plural or select whose branches are wrong + // (plural_forms). + Argument *string `json:"argument,omitempty"` + LanguageId int `json:"languageId"` + Mark string `json:"mark"` + + // Missing Missing and Unexpected list the forms, variables, tags or glossary + // terms missing or not allowed. + Missing *[]string `json:"missing,omitempty"` + + // Offset Offset is the character (Unicode code point, from 0) where the + // message stops being valid ICU (icu_invalid). + Offset *int `json:"offset,omitempty"` + Reason ConstantsTermTranslationProblem `json:"reason"` + + // Row Row is the file's row, from 1 (the header is row 1, so the first + // value is row 2). + Row int `json:"row"` + Unexpected *[]string `json:"unexpected,omitempty"` +} + +// DtoTermImportTranslationProblems defines model for dto.TermImportTranslationProblems. +type DtoTermImportTranslationProblems struct { + Problems []DtoTermImportTranslationProblem `json:"problems"` + Total int `json:"total"` +} + +// DtoTermReviewProblem defines model for dto.TermReviewProblem. +type DtoTermReviewProblem struct { + // Max Max is the most terms one request may mark (too_many_terms). + Max *int `json:"max,omitempty"` + Reason ConstantsTermReviewProblem `json:"reason"` +} + +// DtoTermTranslationProblem defines model for dto.TermTranslationProblem. +type DtoTermTranslationProblem struct { + // Argument Argument is the plural or select whose branches are wrong + // (plural_forms). + Argument *string `json:"argument,omitempty"` + + // Missing Missing and Unexpected list the forms, variables, tags or glossary + // terms missing or not allowed. + Missing *[]string `json:"missing,omitempty"` + + // Offset Offset is the character (Unicode code point, from 0) where the + // message stops being valid ICU (icu_invalid). + Offset *int `json:"offset,omitempty"` + Reason ConstantsTermTranslationProblem `json:"reason"` + Unexpected *[]string `json:"unexpected,omitempty"` +} + // DtoTranslationInfo defines model for dto.TranslationInfo. type DtoTranslationInfo struct { // AiGenerated AIGenerated is true while the value is exactly what AI translation @@ -728,8 +1032,12 @@ type DtoTranslationInfo struct { CreatedAt *string `json:"created_at,omitempty"` Lang DtoLangInfo `json:"lang"` LanguageToNamespaceId int `json:"language_to_namespace_id"` - UpdatedAt *string `json:"updated_at,omitempty"` - Value string `json:"value"` + + // ReviewedAt ReviewedAt is when a person marked the current text reviewed; null + // while it is not (a changed text is unreviewed again). + ReviewedAt *string `json:"reviewedAt,omitempty"` + UpdatedAt *string `json:"updated_at,omitempty"` + Value string `json:"value"` } // GlossaryAddTranslationRequest defines model for glossary.addTranslationRequest. @@ -829,8 +1137,12 @@ type NamespacePayloadCreateNamespaceRequest struct { // DefaultLanguageId Preferred new fields — pass exactly one. The CLI/frontend should // emit these going forward. - DefaultLanguageId *int `json:"defaultLanguageId,omitempty"` - Name string `json:"name"` + DefaultLanguageId *int `json:"defaultLanguageId,omitempty"` + + // MessageSyntax MessageSyntax is what the namespace's strings are: plain (the + // default) or icu (ICU MessageFormat 1). + MessageSyntax *ConstantsNamespaceMessageSyntax `json:"messageSyntax,omitempty"` + Name string `json:"name"` } // NamespacePayloadUpdateNamespaceRequest defines model for namespace.payloadUpdateNamespaceRequest. @@ -851,7 +1163,11 @@ type NamespacePayloadUpdateNamespaceRequest struct { // now accepts either int or string via LanguageRef. Prefer the explicit // fields above. DefaultLanguage *TypesLanguageRef `json:"default_language,omitempty"` - Name *string `json:"name,omitempty"` + + // MessageSyntax MessageSyntax sets what the namespace's strings are: plain or icu + // (ICU MessageFormat 1). Omit to keep it. + MessageSyntax *ConstantsNamespaceMessageSyntax `json:"messageSyntax,omitempty"` + Name *string `json:"name,omitempty"` } // PoeditorPOEditorTime defines model for poeditor.POEditorTime. @@ -942,8 +1258,14 @@ type SharedTermImportSetup struct { // SyncjobCreateSyncRequest defines model for syncjob.createSyncRequest. type SyncjobCreateSyncRequest struct { - DefaultLanguageCode *string `json:"defaultLanguageCode,omitempty"` - DryRun *bool `json:"dryRun,omitempty"` + // Contexts Contexts are key descriptions ({key: description}) the push phase + // stores with the terms; an empty description clears one, a key left + // out keeps its own. Each key must be one of the source language's + // keys in this request, each description at most 1,000 characters. + // The model gets them with the key when it translates. + Contexts *map[string]string `json:"contexts,omitempty"` + DefaultLanguageCode *string `json:"defaultLanguageCode,omitempty"` + DryRun *bool `json:"dryRun,omitempty"` // Marks Marks is the legacy default-lang-only shape. Kept for one // release of the CLI; new clients submit MarksPerLanguage. @@ -1140,11 +1462,29 @@ type ListGlossaryItemsParams struct { // ListByNamespaceParams defines parameters for ListByNamespace. type ListByNamespaceParams struct { - Cursor string `form:"cursor" json:"cursor"` - HasAnyUntranslated *bool `form:"hasAnyUntranslated,omitempty" json:"hasAnyUntranslated,omitempty"` - Limit int `form:"limit" json:"limit"` - Search string `form:"search" json:"search"` - UntranslatedLangId *int `form:"untranslatedLangId,omitempty" json:"untranslatedLangId,omitempty"` + // AiGenerated AIGenerated lists only terms whose translation in languageId has + // text that is (true) or is not (false) exactly the AI's. + AiGenerated *bool `form:"aiGenerated,omitempty" json:"aiGenerated,omitempty"` + + // Cursor Cursor is the next value of the page before; empty for the first. + Cursor *string `form:"cursor,omitempty" json:"cursor,omitempty"` + HasAnyUntranslated *bool `form:"hasAnyUntranslated,omitempty" json:"hasAnyUntranslated,omitempty"` + + // LanguageId LanguageID is the language the reviewed and aiGenerated filters + // look at; required with either. + LanguageId *int `form:"languageId,omitempty" json:"languageId,omitempty"` + + // Limit Limit is the page size, 1 to 100; 25 when absent or out of range. + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` + + // Reviewed Reviewed lists only terms whose translation in languageId has text + // and is (true) or is not (false) marked reviewed. + Reviewed *bool `form:"reviewed,omitempty" json:"reviewed,omitempty"` + + // Search Search narrows the list to terms whose key or translations contain + // it; empty lists every term. + Search *string `form:"search,omitempty" json:"search,omitempty"` + UntranslatedLangId *int `form:"untranslatedLangId,omitempty" json:"untranslatedLangId,omitempty"` } // CreateImportMultipartBody defines parameters for CreateImport. @@ -1189,8 +1529,8 @@ type UpdateNamespaceJSONRequestBody = NamespacePayloadUpdateNamespaceRequest // AddLanguageJSONRequestBody defines body for AddLanguage for application/json ContentType. type AddLanguageJSONRequestBody = NamespacePayloadAddLanguageRequest -// PostNamespacesNamespaceNameSyncJSONRequestBody defines body for PostNamespacesNamespaceNameSync for application/json ContentType. -type PostNamespacesNamespaceNameSyncJSONRequestBody = SyncjobCreateSyncRequest +// CreateSyncJobJSONRequestBody defines body for CreateSyncJob for application/json ContentType. +type CreateSyncJobJSONRequestBody = SyncjobCreateSyncRequest // AddTermJSONRequestBody defines body for AddTerm for application/json ContentType. type AddTermJSONRequestBody = TermPayloadAddRequest @@ -1213,14 +1553,17 @@ type RecommendMagicTranslationJSONRequestBody = TermPayloadRecommendMagicTransla // UpdateTermTranslationJSONRequestBody defines body for UpdateTermTranslation for application/json ContentType. type UpdateTermTranslationJSONRequestBody = TermPayloadUpdateTranslationRequest +// MarkTranslationsReviewedJSONRequestBody defines body for MarkTranslationsReviewed for application/json ContentType. +type MarkTranslationsReviewedJSONRequestBody = DtoMarkReviewedRequest + // CreateCustomPromptJSONRequestBody defines body for CreateCustomPrompt for application/json ContentType. type CreateCustomPromptJSONRequestBody = TranslationCreateCustomPromptInput // UpdateCustomPromptJSONRequestBody defines body for UpdateCustomPrompt for application/json ContentType. type UpdateCustomPromptJSONRequestBody = TranslationPatchCustomPromptInput -// PostTranslationsTranslateJSONRequestBody defines body for PostTranslationsTranslate for application/json ContentType. -type PostTranslationsTranslateJSONRequestBody = TranslationTranslateTextBody +// TranslateTextJSONRequestBody defines body for TranslateText for application/json ContentType. +type TranslateTextJSONRequestBody = TranslationTranslateTextBody // RequestEditorFn is the function signature for the RequestEditor callback function type RequestEditorFn func(ctx context.Context, req *http.Request) error @@ -1400,13 +1743,13 @@ type ClientInterface interface { // RemoveLanguage request RemoveLanguage(ctx context.Context, namespaceName string, languageId int, reqEditors ...RequestEditorFn) (*http.Response, error) - // PostNamespacesNamespaceNameSyncWithBody request with any body - PostNamespacesNamespaceNameSyncWithBody(ctx context.Context, namespaceName string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + // CreateSyncJobWithBody request with any body + CreateSyncJobWithBody(ctx context.Context, namespaceName string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - PostNamespacesNamespaceNameSync(ctx context.Context, namespaceName string, body PostNamespacesNamespaceNameSyncJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + CreateSyncJob(ctx context.Context, namespaceName string, body CreateSyncJobJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - // GetNamespacesNamespaceNameSyncJobId request - GetNamespacesNamespaceNameSyncJobId(ctx context.Context, namespaceName string, jobId string, reqEditors ...RequestEditorFn) (*http.Response, error) + // GetSyncJob request + GetSyncJob(ctx context.Context, namespaceName string, jobId string, reqEditors ...RequestEditorFn) (*http.Response, error) // ListByNamespace request ListByNamespace(ctx context.Context, namespaceName string, params *ListByNamespaceParams, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -1453,6 +1796,11 @@ type ClientInterface interface { UpdateTermTranslation(ctx context.Context, namespaceName string, termId int, languageToNamespaceId int, body UpdateTermTranslationJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + // MarkTranslationsReviewedWithBody request with any body + MarkTranslationsReviewedWithBody(ctx context.Context, namespaceName string, languageId int, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + + MarkTranslationsReviewed(ctx context.Context, namespaceName string, languageId int, body MarkTranslationsReviewedJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + // ListCustomPrompts request ListCustomPrompts(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) @@ -1472,10 +1820,10 @@ type ClientInterface interface { UpdateCustomPrompt(ctx context.Context, promptId string, body UpdateCustomPromptJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) - // PostTranslationsTranslateWithBody request with any body - PostTranslationsTranslateWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) + // TranslateTextWithBody request with any body + TranslateTextWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) - PostTranslationsTranslate(ctx context.Context, body PostTranslationsTranslateJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + TranslateText(ctx context.Context, body TranslateTextJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) } func (c *Client) ListAPIKeys(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { @@ -1946,8 +2294,8 @@ func (c *Client) RemoveLanguage(ctx context.Context, namespaceName string, langu return c.Client.Do(req) } -func (c *Client) PostNamespacesNamespaceNameSyncWithBody(ctx context.Context, namespaceName string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewPostNamespacesNamespaceNameSyncRequestWithBody(c.Server, namespaceName, contentType, body) +func (c *Client) CreateSyncJobWithBody(ctx context.Context, namespaceName string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateSyncJobRequestWithBody(c.Server, namespaceName, contentType, body) if err != nil { return nil, err } @@ -1958,8 +2306,8 @@ func (c *Client) PostNamespacesNamespaceNameSyncWithBody(ctx context.Context, na return c.Client.Do(req) } -func (c *Client) PostNamespacesNamespaceNameSync(ctx context.Context, namespaceName string, body PostNamespacesNamespaceNameSyncJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewPostNamespacesNamespaceNameSyncRequest(c.Server, namespaceName, body) +func (c *Client) CreateSyncJob(ctx context.Context, namespaceName string, body CreateSyncJobJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewCreateSyncJobRequest(c.Server, namespaceName, body) if err != nil { return nil, err } @@ -1970,8 +2318,8 @@ func (c *Client) PostNamespacesNamespaceNameSync(ctx context.Context, namespaceN return c.Client.Do(req) } -func (c *Client) GetNamespacesNamespaceNameSyncJobId(ctx context.Context, namespaceName string, jobId string, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewGetNamespacesNamespaceNameSyncJobIdRequest(c.Server, namespaceName, jobId) +func (c *Client) GetSyncJob(ctx context.Context, namespaceName string, jobId string, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetSyncJobRequest(c.Server, namespaceName, jobId) if err != nil { return nil, err } @@ -2186,6 +2534,30 @@ func (c *Client) UpdateTermTranslation(ctx context.Context, namespaceName string return c.Client.Do(req) } +func (c *Client) MarkTranslationsReviewedWithBody(ctx context.Context, namespaceName string, languageId int, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewMarkTranslationsReviewedRequestWithBody(c.Server, namespaceName, languageId, contentType, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + +func (c *Client) MarkTranslationsReviewed(ctx context.Context, namespaceName string, languageId int, body MarkTranslationsReviewedJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewMarkTranslationsReviewedRequest(c.Server, namespaceName, languageId, body) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + func (c *Client) ListCustomPrompts(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { req, err := NewListCustomPromptsRequest(c.Server) if err != nil { @@ -2270,8 +2642,8 @@ func (c *Client) UpdateCustomPrompt(ctx context.Context, promptId string, body U return c.Client.Do(req) } -func (c *Client) PostTranslationsTranslateWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewPostTranslationsTranslateRequestWithBody(c.Server, contentType, body) +func (c *Client) TranslateTextWithBody(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewTranslateTextRequestWithBody(c.Server, contentType, body) if err != nil { return nil, err } @@ -2282,8 +2654,8 @@ func (c *Client) PostTranslationsTranslateWithBody(ctx context.Context, contentT return c.Client.Do(req) } -func (c *Client) PostTranslationsTranslate(ctx context.Context, body PostTranslationsTranslateJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { - req, err := NewPostTranslationsTranslateRequest(c.Server, body) +func (c *Client) TranslateText(ctx context.Context, body TranslateTextJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewTranslateTextRequest(c.Server, body) if err != nil { return nil, err } @@ -3439,19 +3811,19 @@ func NewRemoveLanguageRequest(server string, namespaceName string, languageId in return req, nil } -// NewPostNamespacesNamespaceNameSyncRequest calls the generic PostNamespacesNamespaceNameSync builder with application/json body -func NewPostNamespacesNamespaceNameSyncRequest(server string, namespaceName string, body PostNamespacesNamespaceNameSyncJSONRequestBody) (*http.Request, error) { +// NewCreateSyncJobRequest calls the generic CreateSyncJob builder with application/json body +func NewCreateSyncJobRequest(server string, namespaceName string, body CreateSyncJobJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader buf, err := json.Marshal(body) if err != nil { return nil, err } bodyReader = bytes.NewReader(buf) - return NewPostNamespacesNamespaceNameSyncRequestWithBody(server, namespaceName, "application/json", bodyReader) + return NewCreateSyncJobRequestWithBody(server, namespaceName, "application/json", bodyReader) } -// NewPostNamespacesNamespaceNameSyncRequestWithBody generates requests for PostNamespacesNamespaceNameSync with any type of body -func NewPostNamespacesNamespaceNameSyncRequestWithBody(server string, namespaceName string, contentType string, body io.Reader) (*http.Request, error) { +// NewCreateSyncJobRequestWithBody generates requests for CreateSyncJob with any type of body +func NewCreateSyncJobRequestWithBody(server string, namespaceName string, contentType string, body io.Reader) (*http.Request, error) { var err error var pathParam0 string @@ -3486,8 +3858,8 @@ func NewPostNamespacesNamespaceNameSyncRequestWithBody(server string, namespaceN return req, nil } -// NewGetNamespacesNamespaceNameSyncJobIdRequest generates requests for GetNamespacesNamespaceNameSyncJobId -func NewGetNamespacesNamespaceNameSyncJobIdRequest(server string, namespaceName string, jobId string) (*http.Request, error) { +// NewGetSyncJobRequest generates requests for GetSyncJob +func NewGetSyncJobRequest(server string, namespaceName string, jobId string) (*http.Request, error) { var err error var pathParam0 string @@ -3562,12 +3934,28 @@ func NewListByNamespaceRequest(server string, namespaceName string, params *List // per the OpenAPI spec (e.g. "color=blue,black,brown"). var rawQueryFragments []string - if queryFrag, err := runtime.StyleParamWithOptions("form", true, "cursor", params.Cursor, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { - return nil, err - } else { - for _, qp := range strings.Split(queryFrag, "&") { - rawQueryFragments = append(rawQueryFragments, qp) + if params.AiGenerated != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "aiGenerated", *params.AiGenerated, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Cursor != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "cursor", *params.Cursor, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } } + } if params.HasAnyUntranslated != nil { @@ -3582,20 +3970,52 @@ func NewListByNamespaceRequest(server string, namespaceName string, params *List } - if queryFrag, err := runtime.StyleParamWithOptions("form", true, "limit", params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { - return nil, err - } else { - for _, qp := range strings.Split(queryFrag, "&") { - rawQueryFragments = append(rawQueryFragments, qp) + if params.LanguageId != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "languageId", *params.LanguageId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } } + } - if queryFrag, err := runtime.StyleParamWithOptions("form", true, "search", params.Search, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { - return nil, err - } else { - for _, qp := range strings.Split(queryFrag, "&") { - rawQueryFragments = append(rawQueryFragments, qp) + if params.Limit != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "limit", *params.Limit, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "integer", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Reviewed != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "reviewed", *params.Reviewed, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "boolean", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } + } + + } + + if params.Search != nil { + + if queryFrag, err := runtime.StyleParamWithOptions("form", true, "search", *params.Search, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationQuery, Type: "string", Format: ""}); err != nil { + return nil, err + } else { + for _, qp := range strings.Split(queryFrag, "&") { + rawQueryFragments = append(rawQueryFragments, qp) + } } + } if params.UntranslatedLangId != nil { @@ -4107,6 +4527,60 @@ func NewUpdateTermTranslationRequestWithBody(server string, namespaceName string return req, nil } +// NewMarkTranslationsReviewedRequest calls the generic MarkTranslationsReviewed builder with application/json body +func NewMarkTranslationsReviewedRequest(server string, namespaceName string, languageId int, body MarkTranslationsReviewedJSONRequestBody) (*http.Request, error) { + var bodyReader io.Reader + buf, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(buf) + return NewMarkTranslationsReviewedRequestWithBody(server, namespaceName, languageId, "application/json", bodyReader) +} + +// NewMarkTranslationsReviewedRequestWithBody generates requests for MarkTranslationsReviewed with any type of body +func NewMarkTranslationsReviewedRequestWithBody(server string, namespaceName string, languageId int, contentType string, body io.Reader) (*http.Request, error) { + var err error + + var pathParam0 string + + pathParam0, err = runtime.StyleParamWithOptions("simple", false, "namespaceName", namespaceName, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""}) + if err != nil { + return nil, err + } + + var pathParam1 string + + pathParam1, err = runtime.StyleParamWithOptions("simple", false, "languageId", languageId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "integer", Format: ""}) + if err != nil { + return nil, err + } + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/namespaces/%s/translations/%s/review", pathParam0, pathParam1) + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodPost, queryURL.String(), body) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", contentType) + + return req, nil +} + // NewListCustomPromptsRequest generates requests for ListCustomPrompts func NewListCustomPromptsRequest(server string) (*http.Request, error) { var err error @@ -4289,19 +4763,19 @@ func NewUpdateCustomPromptRequestWithBody(server string, promptId string, conten return req, nil } -// NewPostTranslationsTranslateRequest calls the generic PostTranslationsTranslate builder with application/json body -func NewPostTranslationsTranslateRequest(server string, body PostTranslationsTranslateJSONRequestBody) (*http.Request, error) { +// NewTranslateTextRequest calls the generic TranslateText builder with application/json body +func NewTranslateTextRequest(server string, body TranslateTextJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader buf, err := json.Marshal(body) if err != nil { return nil, err } bodyReader = bytes.NewReader(buf) - return NewPostTranslationsTranslateRequestWithBody(server, "application/json", bodyReader) + return NewTranslateTextRequestWithBody(server, "application/json", bodyReader) } -// NewPostTranslationsTranslateRequestWithBody generates requests for PostTranslationsTranslate with any type of body -func NewPostTranslationsTranslateRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { +// NewTranslateTextRequestWithBody generates requests for TranslateText with any type of body +func NewTranslateTextRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) { var err error serverURL, err := url.Parse(server) @@ -4477,13 +4951,13 @@ type ClientWithResponsesInterface interface { // RemoveLanguageWithResponse request RemoveLanguageWithResponse(ctx context.Context, namespaceName string, languageId int, reqEditors ...RequestEditorFn) (*RemoveLanguageResponse, error) - // PostNamespacesNamespaceNameSyncWithBodyWithResponse request with any body - PostNamespacesNamespaceNameSyncWithBodyWithResponse(ctx context.Context, namespaceName string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostNamespacesNamespaceNameSyncResponse, error) + // CreateSyncJobWithBodyWithResponse request with any body + CreateSyncJobWithBodyWithResponse(ctx context.Context, namespaceName string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateSyncJobResponse, error) - PostNamespacesNamespaceNameSyncWithResponse(ctx context.Context, namespaceName string, body PostNamespacesNamespaceNameSyncJSONRequestBody, reqEditors ...RequestEditorFn) (*PostNamespacesNamespaceNameSyncResponse, error) + CreateSyncJobWithResponse(ctx context.Context, namespaceName string, body CreateSyncJobJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateSyncJobResponse, error) - // GetNamespacesNamespaceNameSyncJobIdWithResponse request - GetNamespacesNamespaceNameSyncJobIdWithResponse(ctx context.Context, namespaceName string, jobId string, reqEditors ...RequestEditorFn) (*GetNamespacesNamespaceNameSyncJobIdResponse, error) + // GetSyncJobWithResponse request + GetSyncJobWithResponse(ctx context.Context, namespaceName string, jobId string, reqEditors ...RequestEditorFn) (*GetSyncJobResponse, error) // ListByNamespaceWithResponse request ListByNamespaceWithResponse(ctx context.Context, namespaceName string, params *ListByNamespaceParams, reqEditors ...RequestEditorFn) (*ListByNamespaceResponse, error) @@ -4530,6 +5004,11 @@ type ClientWithResponsesInterface interface { UpdateTermTranslationWithResponse(ctx context.Context, namespaceName string, termId int, languageToNamespaceId int, body UpdateTermTranslationJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateTermTranslationResponse, error) + // MarkTranslationsReviewedWithBodyWithResponse request with any body + MarkTranslationsReviewedWithBodyWithResponse(ctx context.Context, namespaceName string, languageId int, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*MarkTranslationsReviewedResponse, error) + + MarkTranslationsReviewedWithResponse(ctx context.Context, namespaceName string, languageId int, body MarkTranslationsReviewedJSONRequestBody, reqEditors ...RequestEditorFn) (*MarkTranslationsReviewedResponse, error) + // ListCustomPromptsWithResponse request ListCustomPromptsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ListCustomPromptsResponse, error) @@ -4549,10 +5028,10 @@ type ClientWithResponsesInterface interface { UpdateCustomPromptWithResponse(ctx context.Context, promptId string, body UpdateCustomPromptJSONRequestBody, reqEditors ...RequestEditorFn) (*UpdateCustomPromptResponse, error) - // PostTranslationsTranslateWithBodyWithResponse request with any body - PostTranslationsTranslateWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostTranslationsTranslateResponse, error) + // TranslateTextWithBodyWithResponse request with any body + TranslateTextWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*TranslateTextResponse, error) - PostTranslationsTranslateWithResponse(ctx context.Context, body PostTranslationsTranslateJSONRequestBody, reqEditors ...RequestEditorFn) (*PostTranslationsTranslateResponse, error) + TranslateTextWithResponse(ctx context.Context, body TranslateTextJSONRequestBody, reqEditors ...RequestEditorFn) (*TranslateTextResponse, error) } type ListAPIKeysResponse struct { @@ -5478,19 +5957,23 @@ func (r RemoveLanguageResponse) ContentType() string { return "" } -type PostNamespacesNamespaceNameSyncResponse struct { +type CreateSyncJobResponse struct { Body []byte HTTPResponse *http.Response JSON202 *DtoDTOSyncJobCreateResponse - JSON400 *ResponseAPIError - JSON401 *ResponseAPIError - JSON403 *ResponseAPIError - JSON404 *ResponseAPIError - JSON500 *ResponseAPIError + JSON400 *struct { + Data *DtoSyncContextsProblem `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + JSON401 *ResponseAPIError + JSON403 *ResponseAPIError + JSON404 *ResponseAPIError + JSON500 *ResponseAPIError } // Status returns HTTPResponse.Status -func (r PostNamespacesNamespaceNameSyncResponse) Status() string { +func (r CreateSyncJobResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -5498,7 +5981,7 @@ func (r PostNamespacesNamespaceNameSyncResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r PostNamespacesNamespaceNameSyncResponse) StatusCode() int { +func (r CreateSyncJobResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } @@ -5506,14 +5989,14 @@ func (r PostNamespacesNamespaceNameSyncResponse) StatusCode() int { } // ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers -func (r PostNamespacesNamespaceNameSyncResponse) ContentType() string { +func (r CreateSyncJobResponse) ContentType() string { if r.HTTPResponse != nil { return r.HTTPResponse.Header.Get("Content-Type") } return "" } -type GetNamespacesNamespaceNameSyncJobIdResponse struct { +type GetSyncJobResponse struct { Body []byte HTTPResponse *http.Response JSON200 *DtoDTOSyncJob @@ -5525,7 +6008,7 @@ type GetNamespacesNamespaceNameSyncJobIdResponse struct { } // Status returns HTTPResponse.Status -func (r GetNamespacesNamespaceNameSyncJobIdResponse) Status() string { +func (r GetSyncJobResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -5533,7 +6016,7 @@ func (r GetNamespacesNamespaceNameSyncJobIdResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r GetNamespacesNamespaceNameSyncJobIdResponse) StatusCode() int { +func (r GetSyncJobResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } @@ -5541,7 +6024,7 @@ func (r GetNamespacesNamespaceNameSyncJobIdResponse) StatusCode() int { } // ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers -func (r GetNamespacesNamespaceNameSyncJobIdResponse) ContentType() string { +func (r GetSyncJobResponse) ContentType() string { if r.HTTPResponse != nil { return r.HTTPResponse.Header.Get("Content-Type") } @@ -5591,11 +6074,20 @@ type AddTermResponse struct { Body []byte HTTPResponse *http.Response JSON200 *DtoDTOTerm - JSON400 *ResponseAPIError - JSON401 *ResponseAPIError - JSON403 *ResponseAPIError - JSON404 *ResponseAPIError - JSON500 *ResponseAPIError + JSON400 *struct { + Data *DtoTermTranslationProblem `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + JSON401 *ResponseAPIError + JSON403 *ResponseAPIError + JSON404 *ResponseAPIError + JSON429 *struct { + Data *DtoAITranslationBudgetRefusal `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + JSON500 *ResponseAPIError } // Status returns HTTPResponse.Status @@ -5696,11 +6188,20 @@ type ImportFinishResponse struct { Body []byte HTTPResponse *http.Response JSON200 *TermImportFinishResponse - JSON400 *ResponseAPIError - JSON401 *ResponseAPIError - JSON403 *ResponseAPIError - JSON404 *ResponseAPIError - JSON500 *ResponseAPIError + JSON400 *struct { + Data *DtoTermImportTranslationProblems `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + JSON401 *ResponseAPIError + JSON403 *ResponseAPIError + JSON404 *ResponseAPIError + JSON429 *struct { + Data *DtoAITranslationBudgetRefusal `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + JSON500 *ResponseAPIError } // Status returns HTTPResponse.Status @@ -5735,7 +6236,12 @@ type TranslateMissingTranslationsResponse struct { JSON401 *ResponseAPIError JSON403 *ResponseAPIError JSON404 *ResponseAPIError - JSON500 *ResponseAPIError + JSON429 *struct { + Data *DtoAITranslationBudgetRefusal `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + JSON500 *ResponseAPIError } // Status returns HTTPResponse.Status @@ -5874,7 +6380,12 @@ type RecommendMagicTranslationResponse struct { JSON401 *ResponseAPIError JSON403 *ResponseAPIError JSON404 *ResponseAPIError - JSON500 *ResponseAPIError + JSON429 *struct { + Data *DtoAITranslationBudgetRefusal `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + JSON500 *ResponseAPIError } // Status returns HTTPResponse.Status @@ -5905,11 +6416,15 @@ type UpdateTermTranslationResponse struct { Body []byte HTTPResponse *http.Response JSON200 *DtoDTOTerm - JSON400 *ResponseAPIError - JSON401 *ResponseAPIError - JSON403 *ResponseAPIError - JSON404 *ResponseAPIError - JSON500 *ResponseAPIError + JSON400 *struct { + Data *DtoTermTranslationProblem `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + JSON401 *ResponseAPIError + JSON403 *ResponseAPIError + JSON404 *ResponseAPIError + JSON500 *ResponseAPIError } // Status returns HTTPResponse.Status @@ -5936,6 +6451,45 @@ func (r UpdateTermTranslationResponse) ContentType() string { return "" } +type MarkTranslationsReviewedResponse struct { + Body []byte + HTTPResponse *http.Response + JSON200 *DtoMarkReviewedResponse + JSON400 *struct { + Data *DtoTermReviewProblem `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + JSON401 *ResponseAPIError + JSON403 *ResponseAPIError + JSON404 *ResponseAPIError + JSON500 *ResponseAPIError +} + +// Status returns HTTPResponse.Status +func (r MarkTranslationsReviewedResponse) Status() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Status + } + return http.StatusText(0) +} + +// StatusCode returns HTTPResponse.StatusCode +func (r MarkTranslationsReviewedResponse) StatusCode() int { + if r.HTTPResponse != nil { + return r.HTTPResponse.StatusCode + } + return 0 +} + +// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers +func (r MarkTranslationsReviewedResponse) ContentType() string { + if r.HTTPResponse != nil { + return r.HTTPResponse.Header.Get("Content-Type") + } + return "" +} + type ListCustomPromptsResponse struct { Body []byte HTTPResponse *http.Response @@ -6102,16 +6656,21 @@ func (r UpdateCustomPromptResponse) ContentType() string { return "" } -type PostTranslationsTranslateResponse struct { +type TranslateTextResponse struct { Body []byte HTTPResponse *http.Response JSON200 *TranslationTranslateTextResponse JSON400 *ResponseAPIError - JSON500 *ResponseAPIError + JSON429 *struct { + Data *DtoAITranslationBudgetRefusal `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + JSON500 *ResponseAPIError } // Status returns HTTPResponse.Status -func (r PostTranslationsTranslateResponse) Status() string { +func (r TranslateTextResponse) Status() string { if r.HTTPResponse != nil { return r.HTTPResponse.Status } @@ -6119,7 +6678,7 @@ func (r PostTranslationsTranslateResponse) Status() string { } // StatusCode returns HTTPResponse.StatusCode -func (r PostTranslationsTranslateResponse) StatusCode() int { +func (r TranslateTextResponse) StatusCode() int { if r.HTTPResponse != nil { return r.HTTPResponse.StatusCode } @@ -6127,7 +6686,7 @@ func (r PostTranslationsTranslateResponse) StatusCode() int { } // ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers -func (r PostTranslationsTranslateResponse) ContentType() string { +func (r TranslateTextResponse) ContentType() string { if r.HTTPResponse != nil { return r.HTTPResponse.Header.Get("Content-Type") } @@ -6473,30 +7032,30 @@ func (c *ClientWithResponses) RemoveLanguageWithResponse(ctx context.Context, na return ParseRemoveLanguageResponse(rsp) } -// PostNamespacesNamespaceNameSyncWithBodyWithResponse request with arbitrary body returning *PostNamespacesNamespaceNameSyncResponse -func (c *ClientWithResponses) PostNamespacesNamespaceNameSyncWithBodyWithResponse(ctx context.Context, namespaceName string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostNamespacesNamespaceNameSyncResponse, error) { - rsp, err := c.PostNamespacesNamespaceNameSyncWithBody(ctx, namespaceName, contentType, body, reqEditors...) +// CreateSyncJobWithBodyWithResponse request with arbitrary body returning *CreateSyncJobResponse +func (c *ClientWithResponses) CreateSyncJobWithBodyWithResponse(ctx context.Context, namespaceName string, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*CreateSyncJobResponse, error) { + rsp, err := c.CreateSyncJobWithBody(ctx, namespaceName, contentType, body, reqEditors...) if err != nil { return nil, err } - return ParsePostNamespacesNamespaceNameSyncResponse(rsp) + return ParseCreateSyncJobResponse(rsp) } -func (c *ClientWithResponses) PostNamespacesNamespaceNameSyncWithResponse(ctx context.Context, namespaceName string, body PostNamespacesNamespaceNameSyncJSONRequestBody, reqEditors ...RequestEditorFn) (*PostNamespacesNamespaceNameSyncResponse, error) { - rsp, err := c.PostNamespacesNamespaceNameSync(ctx, namespaceName, body, reqEditors...) +func (c *ClientWithResponses) CreateSyncJobWithResponse(ctx context.Context, namespaceName string, body CreateSyncJobJSONRequestBody, reqEditors ...RequestEditorFn) (*CreateSyncJobResponse, error) { + rsp, err := c.CreateSyncJob(ctx, namespaceName, body, reqEditors...) if err != nil { return nil, err } - return ParsePostNamespacesNamespaceNameSyncResponse(rsp) + return ParseCreateSyncJobResponse(rsp) } -// GetNamespacesNamespaceNameSyncJobIdWithResponse request returning *GetNamespacesNamespaceNameSyncJobIdResponse -func (c *ClientWithResponses) GetNamespacesNamespaceNameSyncJobIdWithResponse(ctx context.Context, namespaceName string, jobId string, reqEditors ...RequestEditorFn) (*GetNamespacesNamespaceNameSyncJobIdResponse, error) { - rsp, err := c.GetNamespacesNamespaceNameSyncJobId(ctx, namespaceName, jobId, reqEditors...) +// GetSyncJobWithResponse request returning *GetSyncJobResponse +func (c *ClientWithResponses) GetSyncJobWithResponse(ctx context.Context, namespaceName string, jobId string, reqEditors ...RequestEditorFn) (*GetSyncJobResponse, error) { + rsp, err := c.GetSyncJob(ctx, namespaceName, jobId, reqEditors...) if err != nil { return nil, err } - return ParseGetNamespacesNamespaceNameSyncJobIdResponse(rsp) + return ParseGetSyncJobResponse(rsp) } // ListByNamespaceWithResponse request returning *ListByNamespaceResponse @@ -6646,6 +7205,23 @@ func (c *ClientWithResponses) UpdateTermTranslationWithResponse(ctx context.Cont return ParseUpdateTermTranslationResponse(rsp) } +// MarkTranslationsReviewedWithBodyWithResponse request with arbitrary body returning *MarkTranslationsReviewedResponse +func (c *ClientWithResponses) MarkTranslationsReviewedWithBodyWithResponse(ctx context.Context, namespaceName string, languageId int, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*MarkTranslationsReviewedResponse, error) { + rsp, err := c.MarkTranslationsReviewedWithBody(ctx, namespaceName, languageId, contentType, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseMarkTranslationsReviewedResponse(rsp) +} + +func (c *ClientWithResponses) MarkTranslationsReviewedWithResponse(ctx context.Context, namespaceName string, languageId int, body MarkTranslationsReviewedJSONRequestBody, reqEditors ...RequestEditorFn) (*MarkTranslationsReviewedResponse, error) { + rsp, err := c.MarkTranslationsReviewed(ctx, namespaceName, languageId, body, reqEditors...) + if err != nil { + return nil, err + } + return ParseMarkTranslationsReviewedResponse(rsp) +} + // ListCustomPromptsWithResponse request returning *ListCustomPromptsResponse func (c *ClientWithResponses) ListCustomPromptsWithResponse(ctx context.Context, reqEditors ...RequestEditorFn) (*ListCustomPromptsResponse, error) { rsp, err := c.ListCustomPrompts(ctx, reqEditors...) @@ -6707,21 +7283,21 @@ func (c *ClientWithResponses) UpdateCustomPromptWithResponse(ctx context.Context return ParseUpdateCustomPromptResponse(rsp) } -// PostTranslationsTranslateWithBodyWithResponse request with arbitrary body returning *PostTranslationsTranslateResponse -func (c *ClientWithResponses) PostTranslationsTranslateWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*PostTranslationsTranslateResponse, error) { - rsp, err := c.PostTranslationsTranslateWithBody(ctx, contentType, body, reqEditors...) +// TranslateTextWithBodyWithResponse request with arbitrary body returning *TranslateTextResponse +func (c *ClientWithResponses) TranslateTextWithBodyWithResponse(ctx context.Context, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*TranslateTextResponse, error) { + rsp, err := c.TranslateTextWithBody(ctx, contentType, body, reqEditors...) if err != nil { return nil, err } - return ParsePostTranslationsTranslateResponse(rsp) + return ParseTranslateTextResponse(rsp) } -func (c *ClientWithResponses) PostTranslationsTranslateWithResponse(ctx context.Context, body PostTranslationsTranslateJSONRequestBody, reqEditors ...RequestEditorFn) (*PostTranslationsTranslateResponse, error) { - rsp, err := c.PostTranslationsTranslate(ctx, body, reqEditors...) +func (c *ClientWithResponses) TranslateTextWithResponse(ctx context.Context, body TranslateTextJSONRequestBody, reqEditors ...RequestEditorFn) (*TranslateTextResponse, error) { + rsp, err := c.TranslateText(ctx, body, reqEditors...) if err != nil { return nil, err } - return ParsePostTranslationsTranslateResponse(rsp) + return ParseTranslateTextResponse(rsp) } // ParseListAPIKeysResponse parses an HTTP response from a ListAPIKeysWithResponse call @@ -8169,15 +8745,15 @@ func ParseRemoveLanguageResponse(rsp *http.Response) (*RemoveLanguageResponse, e return response, nil } -// ParsePostNamespacesNamespaceNameSyncResponse parses an HTTP response from a PostNamespacesNamespaceNameSyncWithResponse call -func ParsePostNamespacesNamespaceNameSyncResponse(rsp *http.Response) (*PostNamespacesNamespaceNameSyncResponse, error) { +// ParseCreateSyncJobResponse parses an HTTP response from a CreateSyncJobWithResponse call +func ParseCreateSyncJobResponse(rsp *http.Response) (*CreateSyncJobResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &PostNamespacesNamespaceNameSyncResponse{ + response := &CreateSyncJobResponse{ Body: bodyBytes, HTTPResponse: rsp, } @@ -8191,7 +8767,11 @@ func ParsePostNamespacesNamespaceNameSyncResponse(rsp *http.Response) (*PostName response.JSON202 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: - var dest ResponseAPIError + var dest struct { + Data *DtoSyncContextsProblem `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -8230,15 +8810,15 @@ func ParsePostNamespacesNamespaceNameSyncResponse(rsp *http.Response) (*PostName return response, nil } -// ParseGetNamespacesNamespaceNameSyncJobIdResponse parses an HTTP response from a GetNamespacesNamespaceNameSyncJobIdWithResponse call -func ParseGetNamespacesNamespaceNameSyncJobIdResponse(rsp *http.Response) (*GetNamespacesNamespaceNameSyncJobIdResponse, error) { +// ParseGetSyncJobResponse parses an HTTP response from a GetSyncJobWithResponse call +func ParseGetSyncJobResponse(rsp *http.Response) (*GetSyncJobResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &GetNamespacesNamespaceNameSyncJobIdResponse{ + response := &GetSyncJobResponse{ Body: bodyBytes, HTTPResponse: rsp, } @@ -8378,7 +8958,11 @@ func ParseAddTermResponse(rsp *http.Response) (*AddTermResponse, error) { response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: - var dest ResponseAPIError + var dest struct { + Data *DtoTermTranslationProblem `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -8405,6 +8989,17 @@ func ParseAddTermResponse(rsp *http.Response) (*AddTermResponse, error) { } response.JSON404 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest struct { + Data *DtoAITranslationBudgetRefusal `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON429 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest ResponseAPIError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -8561,7 +9156,11 @@ func ParseImportFinishResponse(rsp *http.Response) (*ImportFinishResponse, error response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: - var dest ResponseAPIError + var dest struct { + Data *DtoTermImportTranslationProblems `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } @@ -8588,6 +9187,17 @@ func ParseImportFinishResponse(rsp *http.Response) (*ImportFinishResponse, error } response.JSON404 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest struct { + Data *DtoAITranslationBudgetRefusal `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON429 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest ResponseAPIError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -8649,6 +9259,17 @@ func ParseTranslateMissingTranslationsResponse(rsp *http.Response) (*TranslateMi } response.JSON404 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest struct { + Data *DtoAITranslationBudgetRefusal `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON429 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest ResponseAPIError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -8886,6 +9507,17 @@ func ParseRecommendMagicTranslationResponse(rsp *http.Response) (*RecommendMagic } response.JSON404 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest struct { + Data *DtoAITranslationBudgetRefusal `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON429 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest ResponseAPIError if err := json.Unmarshal(bodyBytes, &dest); err != nil { @@ -8920,10 +9552,79 @@ func ParseUpdateTermTranslationResponse(rsp *http.Response) (*UpdateTermTranslat response.JSON200 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest struct { + Data *DtoTermTranslationProblem `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON400 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: var dest ResponseAPIError if err := json.Unmarshal(bodyBytes, &dest); err != nil { return nil, err } + response.JSON401 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403: + var dest ResponseAPIError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON403 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404: + var dest ResponseAPIError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON404 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: + var dest ResponseAPIError + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON500 = &dest + + } + + return response, nil +} + +// ParseMarkTranslationsReviewedResponse parses an HTTP response from a MarkTranslationsReviewedWithResponse call +func ParseMarkTranslationsReviewedResponse(rsp *http.Response) (*MarkTranslationsReviewedResponse, error) { + bodyBytes, err := io.ReadAll(rsp.Body) + defer func() { _ = rsp.Body.Close() }() + if err != nil { + return nil, err + } + + response := &MarkTranslationsReviewedResponse{ + Body: bodyBytes, + HTTPResponse: rsp, + } + + switch { + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200: + var dest DtoMarkReviewedResponse + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON200 = &dest + + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400: + var dest struct { + Data *DtoTermReviewProblem `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } response.JSON400 = &dest case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401: @@ -9201,15 +9902,15 @@ func ParseUpdateCustomPromptResponse(rsp *http.Response) (*UpdateCustomPromptRes return response, nil } -// ParsePostTranslationsTranslateResponse parses an HTTP response from a PostTranslationsTranslateWithResponse call -func ParsePostTranslationsTranslateResponse(rsp *http.Response) (*PostTranslationsTranslateResponse, error) { +// ParseTranslateTextResponse parses an HTTP response from a TranslateTextWithResponse call +func ParseTranslateTextResponse(rsp *http.Response) (*TranslateTextResponse, error) { bodyBytes, err := io.ReadAll(rsp.Body) defer func() { _ = rsp.Body.Close() }() if err != nil { return nil, err } - response := &PostTranslationsTranslateResponse{ + response := &TranslateTextResponse{ Body: bodyBytes, HTTPResponse: rsp, } @@ -9229,6 +9930,17 @@ func ParsePostTranslationsTranslateResponse(rsp *http.Response) (*PostTranslatio } response.JSON400 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 429: + var dest struct { + Data *DtoAITranslationBudgetRefusal `json:"data,omitempty"` + Msg string `json:"msg"` + Type ResponseType `json:"type"` + } + if err := json.Unmarshal(bodyBytes, &dest); err != nil { + return nil, err + } + response.JSON429 = &dest + case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500: var dest ResponseAPIError if err := json.Unmarshal(bodyBytes, &dest); err != nil { diff --git a/internal/cli/golden_test.go b/internal/cli/golden_test.go index 7aef499..7aaf568 100644 --- a/internal/cli/golden_test.go +++ b/internal/cli/golden_test.go @@ -57,7 +57,7 @@ var goldenData = map[string]string{ // #nosec G101 -- API fixtures, no credentia {"id":"att-1","isEnabled":true,"priority":1,"jitterSeconds":60,"createdAt":"2026-01-01T00:00:00Z","nextRunAt":"2026-10-02T02:00:00Z","backupPolicy":{"id":"pol-1","name":"Nightly","cronExpression":"0 2 * * *","retentionDays":30}} ]`, "GET /namespaces": `[ - {"id":"ns-1","name":"web","context":"Marketing site","defaultLanguageId":4,"languages":["en","cs"],"organization_id":"org-1","progress":50,"total_terms":12,"created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-02T00:00:00Z","created_by":"user-1"} + {"id":"ns-1","name":"web","context":"Marketing site","defaultLanguageId":4,"messageSyntax":"plain","languages":["en","cs"],"organization_id":"org-1","progress":50,"total_terms":12,"created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-02T00:00:00Z","created_by":"user-1"} ]`, "GET /languages": `[ {"id":4,"code":"en","name":"English","isCustom":false}, diff --git a/internal/cli/langsync/errors.go b/internal/cli/langsync/errors.go index fd2a63d..090ad51 100644 --- a/internal/cli/langsync/errors.go +++ b/internal/cli/langsync/errors.go @@ -67,7 +67,19 @@ func typedOf(e *langsync.ResponseAPIError) *apierror.Typed { if e == nil { return nil } - return &apierror.Typed{Msg: e.Msg, Type: string(e.Type)} + return &apierror.Typed{Msg: e.Msg, Type: string(e.Type), Data: e.Data} +} + +// refusal is the common error shape of a 400 the generated client types +// per endpoint because its body carries a data object (the reason and +// its facts). The data stays with the error, so -o json shows it under +// details.data. +func refusal[D any](msg string, typ langsync.ResponseType, data *D) *langsync.ResponseAPIError { + e := &langsync.ResponseAPIError{Msg: msg, Type: typ} + if data != nil { + e.Data = data + } + return e } // namespaceAPIError is apiError for a namespace-scoped endpoint: a typed diff --git a/internal/cli/langsync/import.go b/internal/cli/langsync/import.go index 09c7f78..502cdc3 100644 --- a/internal/cli/langsync/import.go +++ b/internal/cli/langsync/import.go @@ -160,8 +160,12 @@ waits for it (and exits 1, code job_failed, when it failed), and return nil, err } if res.JSON200 == nil { + var bad *langsync.ResponseAPIError + if res.JSON400 != nil { + bad = refusal(res.JSON400.Msg, res.JSON400.Type, res.JSON400.Data) + } return nil, namespaceAPIError(c, ns, res.HTTPResponse, res.Body, - res.JSON400, res.JSON401, res.JSON403, res.JSON404, res.JSON500) + bad, res.JSON401, res.JSON403, res.JSON404, res.JSON500) } result.Status = string(res.JSON200.Status) if wait.Wait { diff --git a/internal/cli/langsync/init.go b/internal/cli/langsync/init.go index cd5c6ac..1ab6b74 100644 --- a/internal/cli/langsync/init.go +++ b/internal/cli/langsync/init.go @@ -674,11 +674,17 @@ func buildInitEntries(picked []langsync.DtoDTONamespace, langByID map[int]string } } + // What only a person writes into an entry (the file code aliases + // and the key descriptions file) survives picking the namespace + // again. + prior := existingByName[name] out = append(out, projectcfg.Namespace{ Namespace: name, Dir: dir, Format: projectcfg.FormatFlatJSON, DefaultLocalLanguage: defaultCode, + LanguageAliases: prior.LanguageAliases, + ContextFile: prior.ContextFile, }) } return out, nil diff --git a/internal/cli/langsync/mark.go b/internal/cli/langsync/mark.go index fa70305..8de4d35 100644 --- a/internal/cli/langsync/mark.go +++ b/internal/cli/langsync/mark.go @@ -94,8 +94,12 @@ explicitly or the command errors out before touching the network.`, if isNamespaceForbidden(res.JSON403) || isNamespaceForbidden(res.JSON404) { return namespaceAccessError(c.OrgLabel(), ns) } + var bad *langsync.ResponseAPIError + if res.JSON400 != nil { + bad = refusal(res.JSON400.Msg, res.JSON400.Type, res.JSON400.Data) + } return apiError(res.HTTPResponse, res.Body, - res.JSON400, res.JSON401, res.JSON403, res.JSON404, res.JSON500) + bad, res.JSON401, res.JSON403, res.JSON404, res.JSON500) } msg := fmt.Sprintf("Added mark %q to namespace %q.", mark, ns) @@ -160,9 +164,9 @@ translation carries the same flag as "aiGenerated".`, page, err := cmdutil.Paginate(cmd.Context(), pages, func(ctx context.Context, cursor string, size int) ([]langsync.DtoDTOTerm, string, error) { params := &langsync.ListByNamespaceParams{ - Cursor: cursor, - Limit: size, - Search: search, + Cursor: optional(cursor), + Limit: optional(size), + Search: optional(search), } if cmd.Flags().Changed("has-untranslated") { params.HasAnyUntranslated = &hasUntranslated diff --git a/internal/cli/langsync/namespace.go b/internal/cli/langsync/namespace.go index 5ee121b..9ddfeb4 100644 --- a/internal/cli/langsync/namespace.go +++ b/internal/cli/langsync/namespace.go @@ -63,8 +63,8 @@ func newNamespaceListCmd() *cobra.Command { } return cmdutil.Print(cmd, output.Table[langsync.DtoDTONamespace]{ - Headers: []string{"NAME", "DEFAULT_LANG", "LANGUAGES", "CONTEXT", "ID"}, - MaxWidths: []int{32, 0, 0, 40, 0}, + Headers: []string{"NAME", "DEFAULT_LANG", "LANGUAGES", "CONTEXT", "ID", "SYNTAX"}, + MaxWidths: []int{32, 0, 0, 40, 0, 0}, Rows: func(n langsync.DtoDTONamespace) []string { return []string{ deref(n.Name), @@ -72,6 +72,7 @@ func newNamespaceListCmd() *cobra.Command { languageCount(n.Languages), deref(n.Context), deref(n.Id), + deref(ptrStr(string(n.MessageSyntax))), } }, Items: items, @@ -84,6 +85,7 @@ func newNamespaceCreateCmd() *cobra.Command { var ( defaultLanguage string context string + messageSyntax string ) cmd := &cobra.Command{ Use: "create [name]", @@ -96,12 +98,23 @@ The default language is the source of truth — it's the language users write marks in. It's a language code like "en", "cs", "de"; the backend maps it to an actual language record on creation. +--message-syntax says what the namespace's strings are: ` + messageSyntaxHelp + `. + In an interactive shell, omitting any value pops a prompt; in a script the name positional + --default-language are both required.`, Example: ` norcube langsync namespaces create web --default-language en - norcube langsync namespaces create marketing --default-language cs --context "Marketing site copy"`, + norcube langsync namespaces create marketing --default-language cs --context "Marketing site copy" + norcube langsync namespaces create app --default-language en --message-syntax icu`, Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { + var syntax *langsync.ConstantsNamespaceMessageSyntax + if cmd.Flags().Changed("message-syntax") { + v, err := parseMessageSyntax(messageSyntax) + if err != nil { + return err + } + syntax = &v + } c, err := newLangsyncContext(cmd) if err != nil { return err @@ -134,8 +147,9 @@ the name positional + --default-language are both required.`, // typed: numeric → defaultLanguageId, else → defaultLanguageCode. // The backend resolver does the org-scoped lookup. body := langsync.CreateNamespaceJSONRequestBody{ - Name: name, - Context: context, + Name: name, + Context: context, + MessageSyntax: syntax, } if id, parseErr := strconv.Atoi(strings.TrimSpace(defaultLanguage)); parseErr == nil && id > 0 { body.DefaultLanguageId = &id @@ -154,13 +168,14 @@ the name positional + --default-language are both required.`, } return cmdutil.Print(cmd, output.Done{ Message: fmt.Sprintf("Created namespace %q (default language %q).", name, defaultLanguage), - Value: namespaceResult{Name: name, DefaultLanguage: defaultLanguage, Context: context}, + Value: namespaceResult{Name: name, DefaultLanguage: defaultLanguage, Context: context, MessageSyntax: messageSyntaxOf(syntax)}, Fields: []output.Field{{Value: name}, {Value: defaultLanguage}}, }) }, } cmd.Flags().StringVar(&defaultLanguage, "default-language", "", "Language code that source marks are written in (e.g. en, cs, de)") cmd.Flags().StringVar(&context, "context", "", "Free-form description shown next to the namespace in the picker") + addMessageSyntaxFlag(cmd, &messageSyntax, "What the namespace's strings are: "+messageSyntaxHelp+"; the server's default is "+string(langsync.NamespaceMessageSyntaxPlain)) return cmd } @@ -325,11 +340,12 @@ func newNamespaceUpdateCmd() *cobra.Command { context string defaultLanguage string // accept code OR id; resolve below defaultPrompt string + messageSyntax string ) cmd := &cobra.Command{ Use: "update ", Annotations: cmdutil.Writes(), - Short: "Update a namespace's name, context, default language or default prompt", + Short: "Update a namespace's name, context, default language, default prompt or message syntax", Long: `Partial update of a namespace. Pass only the fields you want to change — omitted flags leave existing values alone. @@ -339,13 +355,26 @@ sending the request (the underlying endpoint wants the id form). --default-prompt sets the custom prompt every automatic translation in the namespace uses unless a run names another (see -` + "`norcube langsync prompts list`" + `); "none" removes it.`, +` + "`norcube langsync prompts list`" + `); "none" removes it. + +--message-syntax says what the namespace's strings are: ` + messageSyntaxHelp + `. +Changing it rewrites nothing: it decides how the next translations and +writes are made and checked.`, Example: ` norcube langsync namespaces update web --rename website norcube langsync namespaces update web --default-language cs norcube langsync namespaces update web --default-prompt 5f0c2a9e-1d2b-4c3d-8e9f-0a1b2c3d4e5f - norcube langsync namespaces update web --default-prompt none`, + norcube langsync namespaces update web --default-prompt none + norcube langsync namespaces update web --message-syntax icu`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { + body := langsync.UpdateNamespaceJSONRequestBody{} + if cmd.Flags().Changed("message-syntax") { + v, err := parseMessageSyntax(messageSyntax) + if err != nil { + return err + } + body.MessageSyntax = &v + } c, err := newLangsyncContext(cmd) if err != nil { return err @@ -355,7 +384,6 @@ the namespace uses unless a run names another (see return fmt.Errorf("namespace name must not be empty") } - body := langsync.UpdateNamespaceJSONRequestBody{} if cmd.Flags().Changed("rename") { body.Name = &rename } @@ -380,8 +408,8 @@ the namespace uses unless a run names another (see } body.DefaultCustomPromptId = &id } - if body.Name == nil && body.Context == nil && body.DefaultLanguageId == nil && body.DefaultLanguageCode == nil && body.DefaultCustomPromptId == nil { - return clierr.Usage(errors.New("nothing to update: pass at least one of --rename, --context, --default-language, --default-prompt")) + if body.Name == nil && body.Context == nil && body.DefaultLanguageId == nil && body.DefaultLanguageCode == nil && body.DefaultCustomPromptId == nil && body.MessageSyntax == nil { + return clierr.Usage(errors.New("nothing to update: pass at least one of --rename, --context, --default-language, --default-prompt, --message-syntax")) } res, err := c.API.UpdateNamespaceWithResponse(cmd.Context(), name, body) @@ -406,6 +434,7 @@ the namespace uses unless a run names another (see updated.DefaultLanguage = defaultLanguage } updated.DefaultPromptID = body.DefaultCustomPromptId + updated.MessageSyntax = messageSyntaxOf(body.MessageSyntax) return cmdutil.Print(cmd, output.Done{ Message: fmt.Sprintf("Updated namespace %q.", name), Value: updated, @@ -417,6 +446,7 @@ the namespace uses unless a run names another (see cmd.Flags().StringVar(&context, "context", "", "New context description") cmd.Flags().StringVar(&defaultLanguage, "default-language", "", "New default language — accepts either the code (e.g. en) or the numeric id; codes are resolved to ids client-side") cmd.Flags().StringVar(&defaultPrompt, "default-prompt", "", `Custom prompt id for the namespace's automatic translations, or "none" to remove it`) + addMessageSyntaxFlag(cmd, &messageSyntax, "What the namespace's strings are: "+messageSyntaxHelp) return cmd } @@ -519,4 +549,47 @@ type namespaceResult struct { // DefaultPromptID is set when the update changed the default prompt; // "" means it was removed. DefaultPromptID *string `json:"defaultPromptId,omitempty" yaml:"defaultPromptId,omitempty"` + // MessageSyntax is set when the command set it. + MessageSyntax string `json:"messageSyntax,omitempty" yaml:"messageSyntax,omitempty"` +} + +// messageSyntaxes are the values of --message-syntax: the API's enum, +// named by the generated client's constants (a test checks the list +// against the spec, so a new value can't be missed). +var messageSyntaxes = []langsync.ConstantsNamespaceMessageSyntax{ + langsync.NamespaceMessageSyntaxPlain, + langsync.NamespaceMessageSyntaxICU, +} + +// messageSyntaxHelp names the values for help text. +var messageSyntaxHelp = string(langsync.NamespaceMessageSyntaxPlain) + " (variables such as {name} or %s are kept as they are) or " + + string(langsync.NamespaceMessageSyntaxICU) + " (ICU MessageFormat, translated per plural form of each language and checked before storing)" + +func addMessageSyntaxFlag(cmd *cobra.Command, value *string, usage string) { + cmd.Flags().StringVar(value, "message-syntax", "", usage) + names := make([]string, len(messageSyntaxes)) + for i, v := range messageSyntaxes { + names[i] = string(v) + } + cmdutil.FlagEnum(cmd, "message-syntax", names...) +} + +// parseMessageSyntax checks a --message-syntax value before any request. +func parseMessageSyntax(s string) (langsync.ConstantsNamespaceMessageSyntax, error) { + v := langsync.ConstantsNamespaceMessageSyntax(strings.ToLower(strings.TrimSpace(s))) + if !v.Valid() { + names := make([]string, len(messageSyntaxes)) + for i, m := range messageSyntaxes { + names[i] = string(m) + } + return "", clierr.Usage(fmt.Errorf("invalid --message-syntax %q (must be %s)", s, strings.Join(names, "|"))) + } + return v, nil +} + +func messageSyntaxOf(p *langsync.ConstantsNamespaceMessageSyntax) string { + if p == nil { + return "" + } + return string(*p) } diff --git a/internal/cli/langsync/projectcfg/projectcfg.go b/internal/cli/langsync/projectcfg/projectcfg.go index 0780b2c..27d90a2 100644 --- a/internal/cli/langsync/projectcfg/projectcfg.go +++ b/internal/cli/langsync/projectcfg/projectcfg.go @@ -17,7 +17,11 @@ import ( "fmt" "os" "path/filepath" + "sort" "strings" + "unicode/utf8" + + "github.com/norcubeplatform/cli/internal/cli/langsync/projectcfg/translations" ) // Filename is the canonical name we read and write. The CLI does not @@ -107,8 +111,22 @@ type Namespace struct { // Pure separator differences (cs_cz ↔ cs-CZ) get an automatic // silent alias so the file's local spelling is preserved. LanguageAliases map[string]string `json:"language_aliases,omitempty"` + // ContextFile is an optional flat JSON object {key: description} in + // the source language: what each key is, for the people and the + // model that translate it. Sync sends the descriptions of the source + // file's keys with the job. A relative path is resolved like Dir. It + // must not sit directly in Dir with a .json name, because every such + // file there is read as a language (a subdirectory such as + // "context/en.json" is fine). + ContextFile string `json:"context_file,omitempty"` } +// MaxContextChars is the longest key description LangSync stores, in +// Unicode code points. The server refuses a longer one too +// (SYNC_CONTEXTS_INVALID, reason too_long); checking it here names the +// key before anything is sent. +const MaxContextChars = 1000 + // Find walks up from start (inclusive) looking for a .langsync.json // file. Returns its absolute path. Mirrors how git, npm, and similar // tools find their root marker. @@ -155,9 +173,45 @@ func Load(path string) (*File, error) { if err := f.Validate(); err != nil { return nil, fmt.Errorf("%s: %w", path, err) } + if err := f.checkContextFiles(path); err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } return &f, nil } +// checkContextFiles refuses a context_file that the language scan would +// also read as a language: a ".json" directly in the namespace's +// dir. Sync would otherwise push its descriptions as translations of a +// language called . +func (f *File) checkContextFiles(configPath string) error { + for i, ns := range f.Namespaces { + if ns.ContextFile == "" { + continue + } + file := f.ResolveContextFile(configPath, ns) + if !translations.IsLangFileName(filepath.Base(file)) { + continue + } + if sameDir(filepath.Dir(file), f.ResolveDir(configPath, ns)) { + return fmt.Errorf("namespaces[%d] (%q): context_file %s is in the namespace's dir, where every *.json file is read as a language; move it to a subdirectory (for example %s)", + i, ns.Namespace, file, filepath.Join(filepath.Dir(file), "context", filepath.Base(file))) + } + } + return nil +} + +// sameDir reports whether a and b are the same directory: the same +// cleaned path, or, when both exist, the same directory on disk (a +// symlink, or another letter case on a case-insensitive file system). +func sameDir(a, b string) bool { + if a == b { + return true + } + ai, errA := os.Stat(a) + bi, errB := os.Stat(b) + return errA == nil && errB == nil && os.SameFile(ai, bi) +} + // Save writes the config atomically (tmp file + rename) with stable // two-space indentation, the same format `init` emits. func Save(path string, f *File) error { @@ -234,6 +288,9 @@ func (f *File) Validate() error { if strings.TrimSpace(ns.DefaultLocalLanguage) == "" { return fmt.Errorf("namespaces[%d] (%q): default_local_language must not be empty", i, ns.Namespace) } + if ns.ContextFile != "" && strings.TrimSpace(ns.ContextFile) == "" { + return fmt.Errorf("namespaces[%d] (%q): context_file must not be blank (leave it out for no key descriptions)", i, ns.Namespace) + } } return nil } @@ -249,6 +306,46 @@ func (f *File) ResolveDir(configPath string, ns Namespace) string { return filepath.Clean(filepath.Join(filepath.Dir(configPath), ns.Dir)) } +// ResolveContextFile returns the absolute path of ns.ContextFile, anchored +// like ResolveDir; "" when the namespace has none. +func (f *File) ResolveContextFile(configPath string, ns Namespace) string { + if ns.ContextFile == "" { + return "" + } + if filepath.IsAbs(ns.ContextFile) { + return filepath.Clean(ns.ContextFile) + } + return filepath.Clean(filepath.Join(filepath.Dir(configPath), ns.ContextFile)) +} + +// ReadContexts reads a context file: a flat JSON object of key +// descriptions. A missing file, a value that is not a string and a +// description longer than MaxContextChars are errors naming the file +// (and the key); an empty description is kept, because it clears the +// key's description on the server. +func ReadContexts(path string) (map[string]string, error) { + contexts, err := translations.ReadFlatJSON(path) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("context_file %s does not exist (create it, or remove context_file from %s)", path, Filename) + } + return nil, fmt.Errorf("context_file: %w", err) + } + // Report the first key in a stable order, so a rerun names the same. + keys := make([]string, 0, len(contexts)) + for k, v := range contexts { + if utf8.RuneCountInString(v) > MaxContextChars { + keys = append(keys, k) + } + } + if len(keys) > 0 { + sort.Strings(keys) + return nil, fmt.Errorf("context_file %s: the description of key %q is %d characters long; the most is %d", + path, keys[0], utf8.RuneCountInString(contexts[keys[0]]), MaxContextChars) + } + return contexts, nil +} + // FindNamespace returns the namespace entry by name (case-sensitive) // and a bool for found-ness, mirroring the standard library idiom. func (f *File) FindNamespace(name string) (Namespace, bool) { diff --git a/internal/cli/langsync/projectcfg/projectcfg_test.go b/internal/cli/langsync/projectcfg/projectcfg_test.go new file mode 100644 index 0000000..a5c40b4 --- /dev/null +++ b/internal/cli/langsync/projectcfg/projectcfg_test.go @@ -0,0 +1,114 @@ +package projectcfg + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// writeProject writes a .langsync.json with one namespace whose dir is +// "locales" and whose context_file is contextFile, and returns its path. +func writeProject(t *testing.T, contextFile string) string { + t.Helper() + root := t.TempDir() + if err := os.MkdirAll(filepath.Join(root, "locales", "context"), 0o750); err != nil { + t.Fatal(err) + } + cfg := `{"version":1,"namespaces":[{"namespace":"web","dir":"locales","format":"flat-json","default_local_language":"en","context_file":` + + quote(contextFile) + `}]}` + path := filepath.Join(root, Filename) + if err := os.WriteFile(path, []byte(cfg), 0o600); err != nil { + t.Fatal(err) + } + return path +} + +func quote(s string) string { return `"` + strings.ReplaceAll(s, `\`, `\\`) + `"` } + +func TestLoadRefusesAContextFileTheLanguageScanWouldRead(t *testing.T) { + path := writeProject(t, "locales/context.json") + _, err := Load(path) + want := filepath.Join(filepath.Dir(path), "locales", "context.json") + if err == nil || !strings.Contains(err.Error(), "context_file "+want) || !strings.Contains(err.Error(), "read as a language") { + t.Fatalf("got %v, want a refusal naming %s", err, want) + } + + // The same directory reached another way is still the same directory. + root := filepath.Dir(path) + if err := os.Symlink(filepath.Join(root, "locales"), filepath.Join(root, "alias")); err != nil { + t.Skipf("symlinks: %v", err) + } + cfg := `{"version":1,"namespaces":[{"namespace":"web","dir":"locales","format":"flat-json","default_local_language":"en","context_file":"alias/en-context.json"}]}` + if err := os.WriteFile(path, []byte(cfg), 0o600); err != nil { + t.Fatal(err) + } + if _, err := Load(path); err == nil || !strings.Contains(err.Error(), "alias") { + t.Fatalf("a symlinked dir should be refused too, got %v", err) + } +} + +func TestLoadAcceptsContextFilesTheScanSkips(t *testing.T) { + for _, cf := range []string{"locales/context/en.json", "locales/.context.json", "locales/context.txt", "docs/keys.json"} { + path := writeProject(t, cf) + f, err := Load(path) + if err != nil { + t.Fatalf("%s: %v", cf, err) + } + want := filepath.Join(filepath.Dir(path), filepath.FromSlash(cf)) + if got := f.ResolveContextFile(path, f.Namespaces[0]); got != want { + t.Fatalf("%s resolved to %s, want %s", cf, got, want) + } + } +} + +func TestLoadRefusesABlankContextFile(t *testing.T) { + if _, err := Load(writeProject(t, " ")); err == nil || !strings.Contains(err.Error(), "context_file must not be blank") { + t.Fatalf("got %v", err) + } +} + +func TestReadContexts(t *testing.T) { + dir := t.TempDir() + write := func(name, body string) string { + p := filepath.Join(dir, name) + if err := os.WriteFile(p, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + return p + } + + missing := filepath.Join(dir, "nope.json") + if _, err := ReadContexts(missing); err == nil || !strings.Contains(err.Error(), missing) || !strings.Contains(err.Error(), "does not exist") { + t.Fatalf("missing file: %v", err) + } + + for name, body := range map[string]string{ + "broken.json": `{"a": `, + "number.json": `{"a": 1}`, + "nested.json": `{"a": {"b": "c"}}`, + "array.json": `["a"]`, + "list-val.json": `{"a": [1]}`, + } { + p := write(name, body) + if _, err := ReadContexts(p); err == nil || !strings.Contains(err.Error(), p) { + t.Fatalf("%s: got %v, want an error naming the file", name, err) + } + } + + // 1,000 code points is the most, counted as characters, not bytes. + atLimit := strings.Repeat("č", MaxContextChars) + tooLong := strings.Repeat("a", MaxContextChars+1) + p := write("ok.json", `{"title": "`+atLimit+`", "cleared": ""}`) + got, err := ReadContexts(p) + if err != nil { + t.Fatalf("at the limit: %v", err) + } + if got["title"] != atLimit || got["cleared"] != "" || len(got) != 2 { + t.Fatalf("read %v", got) + } + p = write("long.json", `{"ok": "fine", "checkout.total": "`+tooLong+`"}`) + if _, err := ReadContexts(p); err == nil || !strings.Contains(err.Error(), `"checkout.total"`) || !strings.Contains(err.Error(), p) { + t.Fatalf("too long: %v", err) + } +} diff --git a/internal/cli/langsync/projectcfg/translations/flatjson.go b/internal/cli/langsync/projectcfg/translations/flatjson.go index e502f4f..e8f6921 100644 --- a/internal/cli/langsync/projectcfg/translations/flatjson.go +++ b/internal/cli/langsync/projectcfg/translations/flatjson.go @@ -121,6 +121,15 @@ func WriteFlatJSON(path string, data map[string]string) error { return os.Rename(tmpName, path) } +// IsLangFileName reports whether a file of this name, directly in a +// namespace's directory, is read as a language by ListLangsInDir: a +// ".json" that is not a dotfile. Anything else that must live next +// to the language files (the key descriptions of a context file) is +// checked against it. +func IsLangFileName(name string) bool { + return !strings.HasPrefix(name, ".") && LangCodeFromFileName(name) != "" +} + // ListLangsInDir scans dir for files matching the flat-json convention // and returns the discovered language codes (basename minus ".json"), // sorted, plus the absolute paths in matching order. @@ -139,13 +148,10 @@ func ListLangsInDir(dir string) (codes []string, paths []string, err error) { type entry struct{ code, path string } var hits []entry for _, e := range entries { - if e.IsDir() || strings.HasPrefix(e.Name(), ".") { + if e.IsDir() || !IsLangFileName(e.Name()) { continue } code := LangCodeFromFileName(e.Name()) - if code == "" { - continue - } hits = append(hits, entry{code: code, path: filepath.Join(dir, e.Name())}) } sort.Slice(hits, func(i, j int) bool { return hits[i].code < hits[j].code }) diff --git a/internal/cli/langsync/sync.go b/internal/cli/langsync/sync.go index 0c81c96..b43fa35 100644 --- a/internal/cli/langsync/sync.go +++ b/internal/cli/langsync/sync.go @@ -74,7 +74,19 @@ Flags: when a term's source-language value has changed, empty its existing non-source-language translations so the server re-translates them via the LLM - (default off: stale translations stay as-is)`, + (default off: stale translations stay as-is) + +Key descriptions: a namespace whose .langsync.json entry has +"context_file" (a flat JSON object {"key": "what the key is"} in the +source language, outside the language files' directory or in a +subdirectory of it) sends the descriptions of the source file's keys +with the job; the people and the model that translate a key see it. +Descriptions of keys the source file doesn't have are not sent (one +warning says how many); an empty description clears a key's. + +After the run, the Issues block lists every translation LangSync didn't +store, with the key, language and reason, and "Not reviewed" counts the +translations per language nobody has marked reviewed yet.`, Example: ` norcube langsync sync norcube langsync sync --dry-run norcube langsync sync -n ytracker-backend @@ -149,6 +161,10 @@ type syncOptions struct { // vs the new source). Opt-in to avoid blasting hand-curated // translations on a casual sync. retranslateOnSourceChange bool + + // contexts are the key descriptions from each namespace's + // context_file, keyed by namespace (see loadSyncContexts). + contexts map[string]map[string]string } // runParallelSync is the shared entry point for both `sync` and the @@ -169,6 +185,15 @@ func runParallelSync(cmd *cobra.Command, c *langsyncContext, cfg *projectcfg.Fil // the user almost certainly wants to fix the situation before // committing to the sync. if opts.strategy != strategyServer { + // Key descriptions are read before anything is sent: a context + // file that can't be used stops the run instead of half of it. + // The server strategy pushes nothing, descriptions included, so + // pull doesn't read them. + contexts, err := loadSyncContexts(cmd.ErrOrStderr(), cfg, configPath, targets) + if err != nil { + return nil, err + } + opts.contexts = contexts if err := preflightAttachLanguages(cmd.Context(), c, cfg, configPath, targets); err != nil { return nil, err } @@ -215,6 +240,21 @@ func runParallelSync(cmd *cobra.Command, c *langsyncContext, cfg *projectcfg.Fil } } + var unreviewed []string + for _, r := range results { + if r.err == nil && r.finalJob != nil && r.finalJob.UnreviewedPerLanguage != nil { + if line := unreviewedLine(r.namespace, *r.finalJob.UnreviewedPerLanguage); line != "" { + unreviewed = append(unreviewed, line) + } + } + } + if len(unreviewed) > 0 { + d.PrintHeading("Not reviewed") + for _, line := range unreviewed { + d.PrintNote(line) + } + } + if opts.dryRun { d.PrintHeading("Dry run — nothing was changed") } @@ -256,6 +296,11 @@ type syncSummary struct { StillUntranslated int `json:"stillUntranslated" yaml:"stillUntranslated"` FilesWritten int `json:"filesWritten" yaml:"filesWritten"` Error string `json:"error,omitempty" yaml:"error,omitempty"` + // UnreviewedPerLanguage and Failures are the job's own fields: per + // language code, the translations nobody marked reviewed, and the + // keys and ops that failed (with the code of a refused translation). + UnreviewedPerLanguage map[string]int `json:"unreviewedPerLanguage,omitempty" yaml:"unreviewedPerLanguage,omitempty"` + Failures []langsync.DtoDTOSyncJobFailure `json:"failures,omitempty" yaml:"failures,omitempty"` } // summarizeSync turns the per-namespace results into summaries. @@ -277,6 +322,14 @@ func summarizeSync(results []syncResult) []syncSummary { if r.err != nil { row.Status, row.Error = "failed", r.err.Error() } + if j := r.finalJob; j != nil { + if j.UnreviewedPerLanguage != nil { + row.UnreviewedPerLanguage = *j.UnreviewedPerLanguage + } + if j.Failures != nil { + row.Failures = *j.Failures + } + } rows = append(rows, row) } return rows @@ -510,7 +563,15 @@ func submitSyncJob(ctx context.Context, c *langsyncContext, ns projectcfg.Namesp // server and the source-override lookup fails with "isn't // attached". defaultCode := serverLangCode(ns.DefaultLocalLanguage, ns.LanguageAliases) + // Only descriptions of keys this request pushes in the source + // language: the server refuses any other (loadSyncContexts already + // filtered and warned; this keeps the rule where the body is built). + var contexts *map[string]string + if kept, _ := sourceContexts(opts.contexts[ns.Namespace], marksPerLang[defaultCode]); len(kept) > 0 { + contexts = &kept + } body := langsync.SyncjobCreateSyncRequest{ + Contexts: contexts, DefaultLanguageCode: ptrStr(defaultCode), DryRun: ptrBool(opts.dryRun), MarksPerLanguage: &mpl, @@ -519,7 +580,7 @@ func submitSyncJob(ctx context.Context, c *langsyncContext, ns projectcfg.Namesp WaitForAutotranslate: ptrBool(opts.wait), RetranslateOnSourceChange: ptrBool(opts.retranslateOnSourceChange), } - res, err := c.API.PostNamespacesNamespaceNameSyncWithResponse(ctx, ns.Namespace, body) + res, err := c.API.CreateSyncJobWithResponse(ctx, ns.Namespace, body) if err != nil { return "", err } @@ -527,8 +588,16 @@ func submitSyncJob(ctx context.Context, c *langsyncContext, ns projectcfg.Namesp if isNamespaceForbidden(res.JSON403) || isNamespaceForbidden(res.JSON404) { return "", namespaceAccessError(c.OrgLabel(), ns.Namespace) } - return "", apiError(res.HTTPResponse, res.Body, - res.JSON400, res.JSON401, res.JSON403, res.JSON404, res.JSON500) + var bad *langsync.ResponseAPIError + if res.JSON400 != nil { + bad = refusal(res.JSON400.Msg, res.JSON400.Type, res.JSON400.Data) + } + err := apiError(res.HTTPResponse, res.Body, + bad, res.JSON401, res.JSON403, res.JSON404, res.JSON500) + if res.JSON400 != nil && res.JSON400.Type == langsync.ErrSyncContextsInvalid { + return "", syncContextsError(err, ns.ContextFile, res.JSON400.Data) + } + return "", err } if res.JSON202.Id == nil || *res.JSON202.Id == "" { return "", fmt.Errorf("backend returned a 202 with no job id") @@ -636,3 +705,13 @@ func relPath(configPath, target string) string { func ptrStr(s string) *string { return &s } func ptrBool(b bool) *bool { return &b } + +// optional is a pointer to v, or nil for the zero value, for the +// generated client's optional query parameters (left out when nil). +func optional[T comparable](v T) *T { + var zero T + if v == zero { + return nil + } + return &v +} diff --git a/internal/cli/langsync/sync_contexts.go b/internal/cli/langsync/sync_contexts.go new file mode 100644 index 0000000..c820f3b --- /dev/null +++ b/internal/cli/langsync/sync_contexts.go @@ -0,0 +1,113 @@ +package langsync + +import ( + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + + "github.com/norcubeplatform/cli/internal/api/langsync" + "github.com/norcubeplatform/cli/internal/cli/langsync/projectcfg" + "github.com/norcubeplatform/cli/internal/cli/langsync/projectcfg/translations" + "github.com/norcubeplatform/cli/internal/clierr" +) + +// loadSyncContexts reads the context file of every target that has one, +// before anything is sent, and keeps the descriptions of the source +// file's keys: LangSync refuses a description of a key the request +// doesn't push. Descriptions left out that way are counted in one +// warning line per namespace on w. A context file that can't be read is +// an error, because the person configured it and expects it to be sent. +// The result is keyed by namespace; namespaces without descriptions are +// absent. +func loadSyncContexts(w io.Writer, cfg *projectcfg.File, configPath string, targets []projectcfg.Namespace) (map[string]map[string]string, error) { + out := map[string]map[string]string{} + for _, ns := range targets { + path := cfg.ResolveContextFile(configPath, ns) + if path == "" { + continue + } + contexts, err := projectcfg.ReadContexts(path) + if err != nil { + return nil, fmt.Errorf("[%s] %w", ns.Namespace, err) + } + sourcePath := filepath.Join(cfg.ResolveDir(configPath, ns), translations.LangFileName(ns.DefaultLocalLanguage)) + source, err := translations.ReadFlatJSON(sourcePath) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("[%s] %w", ns.Namespace, err) + } + kept, dropped := sourceContexts(contexts, source) + if dropped > 0 { + fmt.Fprintf(w, "[%s] warning: %d %s in %s %s that %s doesn't have; not sent\n", + ns.Namespace, dropped, plural(dropped, "description", "descriptions"), relPath(configPath, path), + plural(dropped, "is for a key", "are for keys"), translations.LangFileName(ns.DefaultLocalLanguage)) + } + if len(kept) > 0 { + out[ns.Namespace] = kept + } + } + return out, nil +} + +// sourceContexts keeps the descriptions whose key is one of the source +// language's keys and counts the others. +func sourceContexts(contexts, source map[string]string) (kept map[string]string, dropped int) { + kept = make(map[string]string, len(contexts)) + for key, description := range contexts { + if _, ok := source[key]; !ok { + dropped++ + continue + } + kept[key] = description + } + return kept, dropped +} + +// syncContextsError words LangSync's refusal of a sync's key +// descriptions (SYNC_CONTEXTS_INVALID). The error keeps the API's code, +// type and data; only the sentence is the CLI's, naming the context +// file to fix. +func syncContextsError(err error, contextFile string, p *langsync.DtoSyncContextsProblem) error { + var ce *clierr.Error + if p == nil || !errors.As(err, &ce) { + return err + } + key := "" + if p.Key != nil { + key = *p.Key + } + var what string + switch p.Reason { + case langsync.SyncContextsProblemTooMany: + what = "there are more descriptions than source keys" + if p.Max != nil { + what += fmt.Sprintf(" (the most is %d)", *p.Max) + } + case langsync.SyncContextsProblemUnknownKey: + what = fmt.Sprintf("key %q is not one of the source language's keys", key) + case langsync.SyncContextsProblemTooLong: + what = fmt.Sprintf("the description of key %q is too long", key) + if p.MaxChars != nil { + what += fmt.Sprintf(" (the most is %d characters)", *p.MaxChars) + } + case langsync.SyncContextsProblemNotText: + what = fmt.Sprintf("the description of key %q is not text", key) + default: + what = strings.TrimSpace(string(p.Reason) + " " + key) + } + source := "the key descriptions" + if contextFile != "" { + source = "the key descriptions from " + contextFile + } + ce.Message = fmt.Sprintf("LangSync refused %s: %s", source, what) + return ce +} + +func plural(n int, one, many string) string { + if n == 1 { + return one + } + return many +} diff --git a/internal/cli/langsync/sync_interactive.go b/internal/cli/langsync/sync_interactive.go index cfd3a07..6d527e7 100644 --- a/internal/cli/langsync/sync_interactive.go +++ b/internal/cli/langsync/sync_interactive.go @@ -145,8 +145,8 @@ func fetchDefaultLangValues(ctx context.Context, c *langsyncContext, namespace, cursor := "" for { params := &langsync.ListByNamespaceParams{ - Cursor: cursor, - Limit: 200, + Cursor: optional(cursor), + Limit: optional(200), } res, err := c.API.ListByNamespaceWithResponse(ctx, namespace, params) if err != nil { diff --git a/internal/cli/langsync/sync_issues.go b/internal/cli/langsync/sync_issues.go index a20e354..c75a26a 100644 --- a/internal/cli/langsync/sync_issues.go +++ b/internal/cli/langsync/sync_issues.go @@ -5,6 +5,7 @@ import ( "fmt" "path/filepath" "sort" + "strings" "github.com/norcubeplatform/cli/internal/api/langsync" "github.com/norcubeplatform/cli/internal/cli/langsync/projectcfg" @@ -52,15 +53,7 @@ func collectIssues(ctx context.Context, c *langsyncContext, cfg *projectcfg.File // Backend-reported failures from the failures array. if r.finalJob.Failures != nil { for _, f := range *r.finalJob.Failures { - msg := cmdutil.Deref(f.Error) - phase := cmdutil.Deref(f.Phase) - mark := cmdutil.Deref(f.Mark) - prefix := fmt.Sprintf("[%s] %s", r.namespace, phase) - if mark != "" { - lines = append(lines, fmt.Sprintf("%s — %s: %s", prefix, mark, msg)) - } else { - lines = append(lines, fmt.Sprintf("%s — %s", prefix, msg)) - } + lines = append(lines, failureLine(r.namespace, f)) } } @@ -93,6 +86,94 @@ func collectIssues(ctx context.Context, c *langsyncContext, cfg *projectcfg.File return lines } +// failureLine is one entry of the failures array for people. An entry +// with a code (a translation LangSync didn't store because of its text) +// names the key, the language, the code and its facts in words; an entry +// with dropped stands for the failures the server didn't list; any other +// keeps the server's English error. +func failureLine(namespace string, f langsync.DtoDTOSyncJobFailure) string { + prefix := fmt.Sprintf("[%s] %s", namespace, cmdutil.Deref(f.Phase)) + if n := cmdutil.Deref(f.Dropped); n > 0 { + return fmt.Sprintf("%s — and %d more", prefix, n) + } + mark := cmdutil.Deref(f.Mark) + if lang := cmdutil.Deref(f.LanguageCode); lang != "" { + mark = strings.TrimSpace(mark + " [" + lang + "]") + } + what := cmdutil.Deref(f.Error) + if f.Code != nil { + what = describeTranslationProblem(f) + } + if mark != "" { + return fmt.Sprintf("%s — %s: %s", prefix, mark, what) + } + return fmt.Sprintf("%s — %s", prefix, what) +} + +// translationProblemWords say what each code of a refused translation +// means. A code this CLI doesn't know yet is shown with the server's +// English error. +var translationProblemWords = map[langsync.ConstantsTermTranslationProblem]string{ + langsync.TermTranslationProblemPlaceholdersChanged: "the variables or placeholders changed", + langsync.TermTranslationProblemICUInvalid: "not a valid ICU message", + langsync.TermTranslationProblemPluralForms: "the plural forms don't fit the language", + langsync.TermTranslationProblemTagsChanged: "the tags changed", + langsync.TermTranslationProblemGlossaryTermMissing: "a glossary term that stays as it is is missing", + langsync.TermTranslationProblemTooManyVariants: "too many plural and select variants (split the message)", + langsync.TermTranslationProblemUntranslated: "the model answered with the source text", + langsync.TermTranslationProblemModelFailed: "the model failed to translate it", +} + +// describeTranslationProblem is ": ()". +func describeTranslationProblem(f langsync.DtoDTOSyncJobFailure) string { + code := cmdutil.Deref(f.Code) + words, ok := translationProblemWords[code] + if !ok { + words = cmdutil.Deref(f.Error) + } + var facts []string + if f.Argument != nil && *f.Argument != "" { + facts = append(facts, "argument "+*f.Argument) + } + if f.Offset != nil { + facts = append(facts, fmt.Sprintf("at offset %d", *f.Offset)) + } + if f.Missing != nil && len(*f.Missing) > 0 { + facts = append(facts, "missing: "+strings.Join(*f.Missing, ", ")) + } + if f.Unexpected != nil && len(*f.Unexpected) > 0 { + facts = append(facts, "unexpected: "+strings.Join(*f.Unexpected, ", ")) + } + out := strings.TrimSpace(string(code) + ": " + words) + if len(facts) > 0 { + out += " (" + strings.Join(facts, "; ") + ")" + } + return out +} + +// unreviewedLine says how many translations per language nobody has +// marked reviewed, or "" when there are none. +func unreviewedLine(namespace string, counts map[string]int) string { + codes := make([]string, 0, len(counts)) + total := 0 + for code, n := range counts { + if n > 0 { + codes = append(codes, code) + total += n + } + } + if total == 0 { + return "" + } + sort.Strings(codes) + parts := make([]string, len(codes)) + for i, code := range codes { + parts[i] = fmt.Sprintf("%s %d", code, counts[code]) + } + return fmt.Sprintf("[%s] %d %s not reviewed: %s", namespace, total, + plural(total, "translation", "translations"), strings.Join(parts, ", ")) +} + // diagnoseEmptyCells fetches the namespace's still-untranslated // marks and labels each by likely cause. Most common cause: the // mark's source value (in the default language) is blank. @@ -116,8 +197,8 @@ func diagnoseEmptyCells(ctx context.Context, c *langsyncContext, ns projectcfg.N truthy := true for page := 0; page < maxDiagnosePages; page++ { params := &langsync.ListByNamespaceParams{ - Cursor: cursor, - Limit: pageLimit, + Cursor: optional(cursor), + Limit: optional(pageLimit), HasAnyUntranslated: &truthy, } res, err := c.API.ListByNamespaceWithResponse(ctx, ns.Namespace, params) diff --git a/internal/cli/langsync/sync_poll.go b/internal/cli/langsync/sync_poll.go index 06e5019..f4b1f5a 100644 --- a/internal/cli/langsync/sync_poll.go +++ b/internal/cli/langsync/sync_poll.go @@ -60,7 +60,7 @@ func pollSyncJobDashboard(ctx context.Context, c *langsyncContext, d *dashboard, } func fetchSyncJob(ctx context.Context, c *langsyncContext, namespace, jobID string) (*langsync.DtoDTOSyncJob, error) { - res, err := c.API.GetNamespacesNamespaceNameSyncJobIdWithResponse(ctx, namespace, jobID) + res, err := c.API.GetSyncJobWithResponse(ctx, namespace, jobID) if err != nil { return nil, err } diff --git a/internal/cli/langsync/sync_summary_test.go b/internal/cli/langsync/sync_summary_test.go new file mode 100644 index 0000000..72f242e --- /dev/null +++ b/internal/cli/langsync/sync_summary_test.go @@ -0,0 +1,193 @@ +package langsync + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/norcubeplatform/cli/internal/api/langsync" + "github.com/norcubeplatform/cli/internal/cli/langsync/projectcfg" + "github.com/norcubeplatform/cli/internal/clierr" +) + +// specEnum reads an enum of the checked-in LangSync spec, the contract +// the generated client comes from. +func specEnum(t *testing.T, schema string) []string { + t.Helper() + raw, err := os.ReadFile(filepath.Join("..", "..", "..", "specs", "langsync.openapi.json")) + if err != nil { + t.Fatal(err) + } + var spec struct { + Components struct { + Schemas map[string]struct { + Enum []string `json:"enum"` + } `json:"schemas"` + } `json:"components"` + } + if err := json.Unmarshal(raw, &spec); err != nil { + t.Fatal(err) + } + values := spec.Components.Schemas[schema].Enum + if len(values) == 0 { + t.Fatalf("no enum %s in the spec", schema) + } + return values +} + +func TestMessageSyntaxesAreTheAPIs(t *testing.T) { + var got []string + for _, v := range messageSyntaxes { + got = append(got, string(v)) + } + want := specEnum(t, "constants.NamespaceMessageSyntax") + slices.Sort(got) + slices.Sort(want) + if !slices.Equal(got, want) { + t.Fatalf("--message-syntax offers %v, the API has %v", got, want) + } +} + +func TestParseMessageSyntax(t *testing.T) { + for in, want := range map[string]langsync.ConstantsNamespaceMessageSyntax{ + "icu": langsync.NamespaceMessageSyntaxICU, " ICU ": langsync.NamespaceMessageSyntaxICU, "plain": langsync.NamespaceMessageSyntaxPlain, + } { + if got, err := parseMessageSyntax(in); err != nil || got != want { + t.Errorf("%q: got %q, %v", in, got, err) + } + } + for _, in := range []string{"", "icu4j", "mf2"} { + _, err := parseMessageSyntax(in) + var ue *clierr.UsageError + if !errors.As(err, &ue) || !strings.Contains(err.Error(), "plain|icu") { + t.Errorf("%q: got %v, want a usage error naming the values", in, err) + } + } +} + +func TestEveryTranslationProblemHasWords(t *testing.T) { + for _, code := range specEnum(t, "constants.TermTranslationProblem") { + if _, ok := translationProblemWords[langsync.ConstantsTermTranslationProblem(code)]; !ok { + t.Errorf("no words for %s", code) + } + } +} + +func TestFailureLine(t *testing.T) { + str := func(s string) *string { return &s } + num := func(n int) *int { return &n } + list := func(s ...string) *[]string { return &s } + code := func(c langsync.ConstantsTermTranslationProblem) *langsync.ConstantsTermTranslationProblem { return &c } + tests := []struct { + name string + f langsync.DtoDTOSyncJobFailure + want string + }{ + {"plural forms with their facts", + langsync.DtoDTOSyncJobFailure{Phase: str("autotranslate"), Mark: str("cart.items"), LanguageCode: str("cs"), + Code: code(langsync.TermTranslationProblemPluralForms), Argument: str("count"), Missing: list("few", "many"), Error: str("english")}, + "[web] autotranslate — cart.items [cs]: plural_forms: the plural forms don't fit the language (argument count; missing: few, many)"}, + {"placeholders missing and unexpected", + langsync.DtoDTOSyncJobFailure{Phase: str("autotranslate"), Mark: str("hello"), LanguageCode: str("de"), + Code: code(langsync.TermTranslationProblemPlaceholdersChanged), Missing: list("{name}"), Unexpected: list("{nme}")}, + "[web] autotranslate — hello [de]: placeholders_changed: the variables or placeholders changed (missing: {name}; unexpected: {nme})"}, + {"an ICU parse error at an offset, from a push", + langsync.DtoDTOSyncJobFailure{Phase: str("push"), Mark: str("cart.total"), LanguageCode: str("cs"), + Code: code(langsync.TermTranslationProblemICUInvalid), Offset: num(0)}, + "[web] push — cart.total [cs]: icu_invalid: not a valid ICU message (at offset 0)"}, + {"a code without facts", + langsync.DtoDTOSyncJobFailure{Phase: str("autotranslate"), Mark: str("title"), LanguageCode: str("cs"), + Code: code(langsync.TermTranslationProblemUntranslated)}, + "[web] autotranslate — title [cs]: untranslated: the model answered with the source text"}, + {"a code this CLI doesn't know keeps the server's words", + langsync.DtoDTOSyncJobFailure{Phase: str("autotranslate"), Mark: str("title"), LanguageCode: str("cs"), + Code: code("new_reason"), Error: str("something new")}, + "[web] autotranslate — title [cs]: new_reason: something new"}, + {"the entry for failures not listed", + langsync.DtoDTOSyncJobFailure{Phase: str("autotranslate"), Dropped: num(12), Error: str("12 more failures")}, + "[web] autotranslate — and 12 more"}, + {"an entry without a code reads as before", + langsync.DtoDTOSyncJobFailure{Phase: str("push"), Mark: str("x"), Error: str("op failed")}, + "[web] push — x: op failed"}, + {"an entry without a key", + langsync.DtoDTOSyncJobFailure{Phase: str("autotranslate"), Error: str("budget reached")}, + "[web] autotranslate — budget reached"}, + } + for _, tt := range tests { + if got := failureLine("web", tt.f); got != tt.want { + t.Errorf("%s:\n got %s\nwant %s", tt.name, got, tt.want) + } + } +} + +func TestUnreviewedLine(t *testing.T) { + if got := unreviewedLine("web", map[string]int{"de": 3, "cs": 12, "fr": 0}); got != "[web] 15 translations not reviewed: cs 12, de 3" { + t.Fatalf("got %q", got) + } + if got := unreviewedLine("web", map[string]int{"cs": 1}); got != "[web] 1 translation not reviewed: cs 1" { + t.Fatalf("got %q", got) + } + if got := unreviewedLine("web", map[string]int{"cs": 0}); got != "" { + t.Fatalf("all reviewed should print nothing, got %q", got) + } + if got := unreviewedLine("web", nil); got != "" { + t.Fatalf("got %q", got) + } +} + +func TestSourceContexts(t *testing.T) { + kept, dropped := sourceContexts( + map[string]string{"a": "first", "b": "", "gone": "old key"}, + map[string]string{"a": "A", "b": "B", "c": "C"}, + ) + if dropped != 1 || len(kept) != 2 || kept["a"] != "first" || kept["b"] != "" { + t.Fatalf("kept %v dropped %d", kept, dropped) + } + if kept, dropped := sourceContexts(map[string]string{"a": "x"}, nil); len(kept) != 0 || dropped != 1 { + t.Fatalf("no source file: kept %v dropped %d", kept, dropped) + } +} + +func TestSyncContextsErrorNamesTheFileAndKey(t *testing.T) { + str := func(s string) *string { return &s } + num := func(n int) *int { return &n } + base := func() error { + return &clierr.Error{Code: clierr.CodeValidation, Message: "contexts invalid", Type: "SYNC_CONTEXTS_INVALID", HTTPStatus: 400} + } + for _, tc := range []struct { + p langsync.DtoSyncContextsProblem + want string + }{ + {langsync.DtoSyncContextsProblem{Reason: langsync.SyncContextsProblemUnknownKey, Key: str("old.key")}, `key "old.key" is not one of the source language's keys`}, + {langsync.DtoSyncContextsProblem{Reason: langsync.SyncContextsProblemTooLong, Key: str("k"), MaxChars: num(1000)}, `the description of key "k" is too long (the most is 1000 characters)`}, + {langsync.DtoSyncContextsProblem{Reason: langsync.SyncContextsProblemTooMany, Max: num(3)}, "there are more descriptions than source keys (the most is 3)"}, + {langsync.DtoSyncContextsProblem{Reason: langsync.SyncContextsProblemNotText, Key: str("k")}, `the description of key "k" is not text`}, + } { + err := syncContextsError(base(), "messages/context/en.json", &tc.p) + var ce *clierr.Error + if !errors.As(err, &ce) || ce.Code != clierr.CodeValidation || + ce.Message != "LangSync refused the key descriptions from messages/context/en.json: "+tc.want { + t.Errorf("%s: got %v", tc.p.Reason, err) + } + } +} + +func TestInitKeepsWhatAPersonWroteIntoAnEntry(t *testing.T) { + name, langID := "web", 4 + existing := &projectcfg.File{Version: 1, Namespaces: []projectcfg.Namespace{{ + Namespace: "web", Dir: "locales", Format: projectcfg.FormatFlatJSON, DefaultLocalLanguage: "en", + LanguageAliases: map[string]string{"cs_cz": "cs-CZ"}, ContextFile: "messages/context/en.json", + }}} + got, err := buildInitEntries([]langsync.DtoDTONamespace{{Name: &name, DefaultLanguageId: &langID}}, + map[int]string{4: "en"}, existing, "", "") + if err != nil { + t.Fatal(err) + } + if len(got) != 1 || got[0].Dir != "locales" || got[0].ContextFile != "messages/context/en.json" || got[0].LanguageAliases["cs_cz"] != "cs-CZ" { + t.Fatalf("got %+v", got) + } +} diff --git a/internal/cli/langsync/translations.go b/internal/cli/langsync/translations.go index cca70e8..8e6361e 100644 --- a/internal/cli/langsync/translations.go +++ b/internal/cli/langsync/translations.go @@ -108,8 +108,12 @@ func setTranslation(cmd *cobra.Command, c *langsyncContext, ns string, termID in return translationSet{}, err } if !ok2xx(res.HTTPResponse) { + var bad *langsync.ResponseAPIError + if res.JSON400 != nil { + bad = refusal(res.JSON400.Msg, res.JSON400.Type, res.JSON400.Data) + } return translationSet{}, namespaceAPIError(c, ns, res.HTTPResponse, res.Body, - res.JSON400, res.JSON401, res.JSON403, res.JSON404, res.JSON500) + bad, res.JSON401, res.JSON403, res.JSON404, res.JSON500) } return translationSet{ Namespace: ns, TermID: termID, Language: cmdutil.Deref(conn.LanguageCode), diff --git a/internal/cli/langsync_sync_test.go b/internal/cli/langsync_sync_test.go new file mode 100644 index 0000000..d3daaee --- /dev/null +++ b/internal/cli/langsync_sync_test.go @@ -0,0 +1,248 @@ +package cli + +import ( + "encoding/json" + "fmt" + "net/http" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/norcubeplatform/cli/internal/clierr" +) + +// syncProject writes a LangSync project for the namespace "web" (files in +// locales/, en the source language) with the given context_file and +// files (paths relative to the project), and makes it the working +// directory. +func syncProject(t *testing.T, contextFile string, files map[string]string) { + t.Helper() + root := t.TempDir() + ns := map[string]any{"namespace": "web", "dir": "locales", "format": "flat-json", "default_local_language": "en"} + if contextFile != "" { + ns["context_file"] = contextFile + } + cfg, err := json.Marshal(map[string]any{"version": 1, "namespaces": []any{ns}}) + if err != nil { + t.Fatal(err) + } + files[".langsync.json"] = string(cfg) + for name, body := range files { + p := filepath.Join(root, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(p), 0o750); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + } + t.Chdir(root) +} + +// syncJobDone is a completed sync job with a refused translation, the +// entry for failures not listed, and translations nobody reviewed. +const syncJobDone = `{"id":"job-1","status":"completed","createdCount":0,"updatedCount":1, + "resultPerLanguage":{"en":{"cart.items":"{count, plural, one {# item} other {# items}}","title":"Shop"},"cs":{"title":"Obchod"}}, + "unreviewedPerLanguage":{"cs":1,"de":0}, + "failures":[ + {"phase":"autotranslate","mark":"cart.items","languageCode":"cs","code":"plural_forms","argument":"count","missing":["few","many"],"error":"plural forms"}, + {"phase":"autotranslate","dropped":4,"error":"4 more"} + ]}` + +// syncServer answers the sync endpoints and records the job request. +func syncServer(t *testing.T, create http.HandlerFunc) *map[string]any { + t.Helper() + var body map[string]any + if create == nil { + create = func(w http.ResponseWriter, r *http.Request) { + body = jsonBody(t, r) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusAccepted) + fmt.Fprint(w, `{"id":"job-1"}`) + } + } + goldenHandlers(t, map[string]http.HandlerFunc{ + "POST /namespaces/web/sync": create, + "GET /namespaces/web/sync/job-1": func(w http.ResponseWriter, _ *http.Request) { + fmt.Fprint(w, syncJobDone) + }, + }) + return &body +} + +func TestLangSyncSendsTheSourceKeysDescriptions(t *testing.T) { + goldenEnv(t) + body := syncServer(t, nil) + syncProject(t, "messages/context/en.json", map[string]string{ + "locales/en.json": `{"cart.items": "{count, plural, one {# item} other {# items}}", "title": "Shop"}`, + "locales/cs.json": `{"title": "Obchod"}`, + "messages/context/en.json": `{"cart.items": "Items in the cart, under its total", "title": "", "removed.key": "left over"}`, + }) + out, stderr, err := run(t, "langsync", "sync", "-o", "json") + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + + // Only the source file's keys; an empty description clears one. + got, _ := json.Marshal((*body)["contexts"]) + if string(got) != `{"cart.items":"Items in the cart, under its total","title":""}` { + t.Fatalf("contexts sent: %s", got) + } + if want := "[web] warning: 1 description in messages/context/en.json is for a key that en.json doesn't have; not sent"; strings.Count(stderr, want) != 1 { + t.Fatalf("want one warning line %q in:\n%s", want, stderr) + } + + // The summary for people names the key, language, code and facts, + // the failures not listed, and what nobody reviewed. + for _, want := range []string{ + "[web] autotranslate — cart.items [cs]: plural_forms: the plural forms don't fit the language (argument count; missing: few, many)", + "[web] autotranslate — and 4 more", + "▸ Not reviewed", + "[web] 1 translation not reviewed: cs 1", + } { + if !strings.Contains(stderr, want) { + t.Errorf("stderr lacks %q:\n%s", want, stderr) + } + } + + // Scripts get the job's own fields. + var summary []map[string]any + if err := json.Unmarshal([]byte(out), &summary); err != nil || len(summary) != 1 { + t.Fatalf("stdout %s: %v", out, err) + } + failures, _ := json.Marshal(summary[0]["failures"]) + unreviewed, _ := json.Marshal(summary[0]["unreviewedPerLanguage"]) + if !strings.Contains(string(failures), `"code":"plural_forms"`) || !strings.Contains(string(failures), `"dropped":4`) || + string(unreviewed) != `{"cs":1,"de":0}` { + t.Fatalf("summary %s", out) + } +} + +func TestLangSyncWithoutAContextFileSendsNoContexts(t *testing.T) { + goldenEnv(t) + body := syncServer(t, nil) + syncProject(t, "", map[string]string{"locales/en.json": `{"title": "Shop"}`}) + if _, stderr, err := run(t, "langsync", "sync", "-o", "json"); err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if _, ok := (*body)["contexts"]; ok { + t.Fatalf("contexts sent without a context_file: %v", *body) + } +} + +func TestLangSyncRefusesAContextFileItCannotUse(t *testing.T) { + goldenEnv(t) + var posts int32 + syncServer(t, func(w http.ResponseWriter, _ *http.Request) { + atomic.AddInt32(&posts, 1) + w.WriteHeader(http.StatusAccepted) + }) + tooLong := strings.Repeat("x", 1001) + for _, tc := range []struct { + name, contextFile string + files map[string]string + want []string + }{ + {"a missing file", "messages/context/en.json", map[string]string{}, []string{"messages/context/en.json", "does not exist"}}, + {"invalid JSON", "messages/context/en.json", map[string]string{"messages/context/en.json": `{"title": 1}`}, []string{"messages/context/en.json", "decode"}}, + {"a description that is too long", "messages/context/en.json", map[string]string{"messages/context/en.json": `{"title": "` + tooLong + `"}`}, []string{`key "title"`, "the most is 1000"}}, + {"a file the language scan reads", "locales/context.json", map[string]string{"locales/context.json": `{}`}, []string{filepath.Join("locales", "context.json"), "read as a language"}}, + } { + t.Run(tc.name, func(t *testing.T) { + tc.files["locales/en.json"] = `{"title": "Shop"}` + syncProject(t, tc.contextFile, tc.files) + _, stderr, err := run(t, "langsync", "sync") + if err == nil { + t.Fatalf("no error\n%s", stderr) + } + for _, want := range tc.want { + if !strings.Contains(filepath.ToSlash(err.Error()), filepath.ToSlash(want)) { + t.Errorf("error %q lacks %q", err, want) + } + } + }) + } + if posts != 0 { + t.Fatalf("%d sync jobs were submitted", posts) + } +} + +func TestLangSyncWordsARefusalOfTheDescriptions(t *testing.T) { + goldenEnv(t) + syncServer(t, func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, `{"type":"SYNC_CONTEXTS_INVALID","msg":"contexts invalid","data":{"reason":"unknown_key","key":"title"}}`) + }) + syncProject(t, "messages/context/en.json", map[string]string{ + "locales/en.json": `{"title": "Shop"}`, + "messages/context/en.json": `{"title": "The shop's name"}`, + }) + out, _, err := run(t, "langsync", "sync", "-o", "json") + if err == nil { + t.Fatal("want the sync to fail") + } + if !strings.Contains(out, `LangSync refused the key descriptions from messages/context/en.json: key \"title\" is not one of the source language's keys`) { + t.Fatalf("summary %s", out) + } +} + +func TestLangSyncPullDoesNotReadTheContextFile(t *testing.T) { + goldenEnv(t) + body := syncServer(t, nil) + syncProject(t, "messages/context/en.json", map[string]string{"locales/en.json": `{"title": "Shop"}`}) + if _, stderr, err := run(t, "langsync", "pull", "-o", "json"); err != nil { + t.Fatalf("pull pushes nothing, so a missing context file doesn't matter: %v\n%s", err, stderr) + } + if _, ok := (*body)["contexts"]; ok || (*body)["strategy"] != "server" { + t.Fatalf("body %v", *body) + } +} + +func TestLangSyncNamespaceMessageSyntax(t *testing.T) { + goldenEnv(t) + var body map[string]any + record := func(w http.ResponseWriter, r *http.Request) { + body = jsonBody(t, r) + fmt.Fprint(w, `{}`) + } + goldenHandlers(t, map[string]http.HandlerFunc{"POST /namespaces": record, "PATCH /namespaces/web": record}) + + out, stderr, err := run(t, "langsync", "namespaces", "create", "app", "--default-language", "en", "--message-syntax", "icu", "-o", "json") + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if body["messageSyntax"] != "icu" || !strings.Contains(out, `"messageSyntax": "icu"`) { + t.Fatalf("create: body %v out %s", body, out) + } + if _, _, err := run(t, "langsync", "namespaces", "create", "app", "--default-language", "en"); err != nil { + t.Fatal(err) + } + if _, ok := body["messageSyntax"]; ok { + t.Fatalf("without the flag the server decides: %v", body) + } + + out, stderr, err = run(t, "langsync", "namespaces", "update", "web", "--message-syntax", "plain", "-o", "json") + if err != nil { + t.Fatalf("%v\n%s", err, stderr) + } + if body["messageSyntax"] != "plain" || len(body) != 1 || !strings.Contains(out, `"messageSyntax": "plain"`) { + t.Fatalf("update: body %v out %s", body, out) + } + + body = nil + for _, args := range [][]string{ + {"langsync", "namespaces", "create", "app", "--default-language", "en", "--message-syntax", "mf2"}, + {"langsync", "namespaces", "update", "web", "--message-syntax", ""}, + } { + _, _, err := run(t, args...) + if err == nil || Describe(err).ExitCode() != clierr.ExitUsage || !strings.Contains(err.Error(), "plain|icu") { + t.Errorf("%v: want a usage error naming the values, got %v", args, err) + } + } + if body != nil { + t.Fatalf("a request was sent: %v", body) + } +} diff --git a/internal/cli/testdata/golden/langsync-namespace-list.json b/internal/cli/testdata/golden/langsync-namespace-list.json index b3a143a..e0b2d86 100644 --- a/internal/cli/testdata/golden/langsync-namespace-list.json +++ b/internal/cli/testdata/golden/langsync-namespace-list.json @@ -9,6 +9,7 @@ "en", "cs" ], + "messageSyntax": "plain", "name": "web", "organization_id": "org-1", "progress": 50, diff --git a/internal/cli/testdata/golden/langsync-namespace-list.tsv b/internal/cli/testdata/golden/langsync-namespace-list.tsv index 5e7c6e8..8e721e1 100644 --- a/internal/cli/testdata/golden/langsync-namespace-list.tsv +++ b/internal/cli/testdata/golden/langsync-namespace-list.tsv @@ -1 +1 @@ -web 4 2 Marketing site ns-1 +web 4 2 Marketing site ns-1 plain diff --git a/internal/cli/testdata/golden/langsync-namespace-list.txt b/internal/cli/testdata/golden/langsync-namespace-list.txt index 0f14e0d..58593af 100644 --- a/internal/cli/testdata/golden/langsync-namespace-list.txt +++ b/internal/cli/testdata/golden/langsync-namespace-list.txt @@ -1,2 +1,2 @@ -NAME DEFAULT_LANG LANGUAGES CONTEXT ID -web en 2 Marketing site ns-1 +NAME DEFAULT_LANG LANGUAGES CONTEXT ID SYNTAX +web en 2 Marketing site ns-1 plain diff --git a/internal/cli/testdata/golden/langsync-namespace-list.yaml b/internal/cli/testdata/golden/langsync-namespace-list.yaml index 5cb543a..4b46604 100644 --- a/internal/cli/testdata/golden/langsync-namespace-list.yaml +++ b/internal/cli/testdata/golden/langsync-namespace-list.yaml @@ -6,6 +6,7 @@ languages: - en - cs + messageSyntax: plain name: web organization_id: org-1 progress: 50 diff --git a/specs/langsync.openapi.json b/specs/langsync.openapi.json index 8e545e1..2aec33b 100644 --- a/specs/langsync.openapi.json +++ b/specs/langsync.openapi.json @@ -119,6 +119,17 @@ }, "type": "object" }, + "constants.AITranslationWorkWindow": { + "enum": [ + "hour", + "day" + ], + "type": "string", + "x-enum-varnames": [ + "AITranslationWorkWindowHour", + "AITranslationWorkWindowDay" + ] + }, "constants.AuditAction": { "enum": [ "namespace.created", @@ -133,6 +144,7 @@ "glossary_item.created", "glossary_item.updated", "glossary_item.deleted", + "glossary_item.translation_added", "custom_language.created", "custom_language.deleted", "custom_prompt.created", @@ -141,6 +153,15 @@ "sync_job.created", "sync_job.completed", "sync_job.failed", + "term.created", + "term.updated", + "term.deleted", + "term_translation.updated", + "translation.missing_requested", + "translation.recommended", + "translation.text_translated", + "translation.texts_translated", + "translation.reviewed", "term_import.finished", "migrator.imported" ], @@ -158,6 +179,7 @@ "AuditActionGlossaryItemCreated", "AuditActionGlossaryItemUpdated", "AuditActionGlossaryItemDeleted", + "AuditActionGlossaryItemTranslationAdded", "AuditActionCustomLanguageCreated", "AuditActionCustomLanguageDeleted", "AuditActionCustomPromptCreated", @@ -166,6 +188,15 @@ "AuditActionSyncJobCreated", "AuditActionSyncJobCompleted", "AuditActionSyncJobFailed", + "AuditActionTermCreated", + "AuditActionTermUpdated", + "AuditActionTermDeleted", + "AuditActionTermTranslationUpdated", + "AuditActionTranslationMissingRequested", + "AuditActionTranslationRecommended", + "AuditActionTranslationTextTranslated", + "AuditActionTranslationTextsTranslated", + "AuditActionTranslationReviewed", "AuditActionTermImportFinished", "AuditActionMigratorImported" ] @@ -179,6 +210,7 @@ "custom_language", "custom_prompt", "sync_job", + "term", "term_import", "migrator" ], @@ -191,6 +223,7 @@ "AuditTargetCustomLanguage", "AuditTargetCustomPrompt", "AuditTargetSyncJob", + "AuditTargetTerm", "AuditTargetTermImport", "AuditTargetMigrator" ] @@ -224,6 +257,32 @@ "GlossaryItemTypeNotApplicable" ] }, + "constants.NamespaceMessageSyntax": { + "enum": [ + "plain", + "icu" + ], + "type": "string", + "x-enum-varnames": [ + "NamespaceMessageSyntaxPlain", + "NamespaceMessageSyntaxICU" + ] + }, + "constants.SyncContextsProblem": { + "enum": [ + "too_many", + "unknown_key", + "too_long", + "not_text" + ], + "type": "string", + "x-enum-varnames": [ + "SyncContextsProblemTooMany", + "SyncContextsProblemUnknownKey", + "SyncContextsProblemTooLong", + "SyncContextsProblemNotText" + ] + }, "constants.TermBulkImportStatus": { "enum": [ "prechecked", @@ -269,6 +328,63 @@ "TermImportFormatXLS" ] }, + "constants.TermReviewProblem": { + "enum": [ + "no_terms", + "too_many_terms" + ], + "type": "string", + "x-enum-varnames": [ + "TermReviewProblemNoTerms", + "TermReviewProblemTooManyTerms" + ] + }, + "constants.TermTranslationProblem": { + "enum": [ + "placeholders_changed", + "icu_invalid", + "plural_forms", + "tags_changed", + "glossary_term_missing", + "too_many_variants", + "untranslated", + "model_failed" + ], + "type": "string", + "x-enum-varnames": [ + "TermTranslationProblemPlaceholdersChanged", + "TermTranslationProblemICUInvalid", + "TermTranslationProblemPluralForms", + "TermTranslationProblemTagsChanged", + "TermTranslationProblemGlossaryTermMissing", + "TermTranslationProblemTooManyVariants", + "TermTranslationProblemUntranslated", + "TermTranslationProblemModelFailed" + ] + }, + "dto.AITranslationBudgetRefusal": { + "properties": { + "retryAt": { + "type": "string" + }, + "window": { + "allOf": [ + { + "$ref": "#/components/schemas/constants.AITranslationWorkWindow" + } + ], + "enum": [ + "hour", + "day" + ] + } + }, + "required": [ + "retryAt", + "window" + ], + "type": "object" + }, "dto.APIKey": { "properties": { "createdAt": { @@ -394,8 +510,15 @@ }, "language_shared": { "type": "boolean" + }, + "unreviewedCount": { + "description": "UnreviewedCount is how many of the language's translations have\ntext that nobody marked reviewed (POST\n.../translations/{languageId}/review). 0 for the default language,\nwhose texts are what the others are translated from.", + "type": "integer" } }, + "required": [ + "unreviewedCount" + ], "type": "object" }, "dto.DTONamespace": { @@ -425,6 +548,14 @@ }, "type": "array" }, + "messageSyntax": { + "allOf": [ + { + "$ref": "#/components/schemas/constants.NamespaceMessageSyntax" + } + ], + "description": "MessageSyntax is what the namespace's strings are: plain (variables\nkept as they are) or icu (ICU MessageFormat 1, translated per plural\nform and checked before storing)." + }, "name": { "type": "string" }, @@ -441,6 +572,9 @@ "type": "string" } }, + "required": [ + "messageSyntax" + ], "type": "object" }, "dto.DTOSyncJob": { @@ -532,6 +666,13 @@ "strategy": { "type": "string" }, + "unreviewedPerLanguage": { + "additionalProperties": { + "type": "integer" + }, + "description": "UnreviewedPerLanguage counts, per language code, the translations\nwith text nobody marked reviewed when the job finished (not the\njob's source language). Set on status='completed'.", + "type": "object" + }, "updatedCount": { "type": "integer" }, @@ -551,17 +692,53 @@ }, "dto.DTOSyncJobFailure": { "properties": { + "argument": { + "type": "string" + }, + "code": { + "allOf": [ + { + "$ref": "#/components/schemas/constants.TermTranslationProblem" + } + ], + "description": "Code says why a translation was not stored: an automatic\ntranslation the checks refused (phase autotranslate) or a pushed\nvalue an ICU namespace refused (phase push). Absent for other\nfailures." + }, + "dropped": { + "description": "Dropped counts the phase's failures not listed (more than 500); set\non one summary entry.", + "type": "integer" + }, "error": { + "description": "Error is English, for logs and older clients; a client words Code.", + "type": "string" + }, + "languageCode": { + "description": "LanguageCode is the language of the translation Code is about.", "type": "string" }, "mark": { "type": "string" }, + "missing": { + "items": { + "type": "string" + }, + "type": "array" + }, + "offset": { + "description": "The facts of Code: where an ICU message stops being valid, which\nplural or select, which forms, variables, tags or terms.", + "type": "integer" + }, "opIdx": { "type": "integer" }, "phase": { "type": "string" + }, + "unexpected": { + "items": { + "type": "string" + }, + "type": "array" } }, "type": "object" @@ -799,6 +976,165 @@ ], "type": "object" }, + "dto.MarkReviewedRequest": { + "properties": { + "termIds": { + "description": "TermIDs are the terms, 1 to 1,000.", + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "required": [ + "termIds" + ], + "type": "object" + }, + "dto.MarkReviewedResponse": { + "properties": { + "reviewed": { + "type": "integer" + } + }, + "required": [ + "reviewed" + ], + "type": "object" + }, + "dto.SyncContextsProblem": { + "properties": { + "key": { + "description": "Key is the entry it is about (unknown_key, too_long, not_text).", + "type": "string" + }, + "max": { + "description": "Max is the most entries the request may have (too_many).", + "type": "integer" + }, + "maxChars": { + "description": "MaxChars is the longest a description may be (too_long).", + "type": "integer" + }, + "reason": { + "$ref": "#/components/schemas/constants.SyncContextsProblem" + } + }, + "required": [ + "reason" + ], + "type": "object" + }, + "dto.TermImportTranslationProblem": { + "properties": { + "argument": { + "description": "Argument is the plural or select whose branches are wrong\n(plural_forms).", + "type": "string" + }, + "languageId": { + "type": "integer" + }, + "mark": { + "type": "string" + }, + "missing": { + "description": "Missing and Unexpected list the forms, variables, tags or glossary\nterms missing or not allowed.", + "items": { + "type": "string" + }, + "type": "array" + }, + "offset": { + "description": "Offset is the character (Unicode code point, from 0) where the\nmessage stops being valid ICU (icu_invalid).", + "type": "integer" + }, + "reason": { + "$ref": "#/components/schemas/constants.TermTranslationProblem" + }, + "row": { + "description": "Row is the file's row, from 1 (the header is row 1, so the first\nvalue is row 2).", + "type": "integer" + }, + "unexpected": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "languageId", + "mark", + "reason", + "row" + ], + "type": "object" + }, + "dto.TermImportTranslationProblems": { + "properties": { + "problems": { + "items": { + "$ref": "#/components/schemas/dto.TermImportTranslationProblem" + }, + "type": "array" + }, + "total": { + "type": "integer" + } + }, + "required": [ + "problems", + "total" + ], + "type": "object" + }, + "dto.TermReviewProblem": { + "properties": { + "max": { + "description": "Max is the most terms one request may mark (too_many_terms).", + "type": "integer" + }, + "reason": { + "$ref": "#/components/schemas/constants.TermReviewProblem" + } + }, + "required": [ + "reason" + ], + "type": "object" + }, + "dto.TermTranslationProblem": { + "properties": { + "argument": { + "description": "Argument is the plural or select whose branches are wrong\n(plural_forms).", + "type": "string" + }, + "missing": { + "description": "Missing and Unexpected list the forms, variables, tags or glossary\nterms missing or not allowed.", + "items": { + "type": "string" + }, + "type": "array" + }, + "offset": { + "description": "Offset is the character (Unicode code point, from 0) where the\nmessage stops being valid ICU (icu_invalid).", + "type": "integer" + }, + "reason": { + "$ref": "#/components/schemas/constants.TermTranslationProblem" + }, + "unexpected": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "reason" + ], + "type": "object" + }, "dto.TranslationInfo": { "properties": { "aiGenerated": { @@ -814,6 +1150,10 @@ "language_to_namespace_id": { "type": "integer" }, + "reviewedAt": { + "description": "ReviewedAt is when a person marked the current text reviewed; null\nwhile it is not (a changed text is unreviewed again).", + "type": "string" + }, "updated_at": { "type": "string" }, @@ -1040,6 +1380,14 @@ "description": "Preferred new fields — pass exactly one. The CLI/frontend should\nemit these going forward.", "type": "integer" }, + "messageSyntax": { + "allOf": [ + { + "$ref": "#/components/schemas/constants.NamespaceMessageSyntax" + } + ], + "description": "MessageSyntax is what the namespace's strings are: plain (the\ndefault) or icu (ICU MessageFormat 1)." + }, "name": { "type": "string" } @@ -1074,6 +1422,14 @@ ], "description": "Deprecated: kept for one release. Used to be `default_language` (int);\nnow accepts either int or string via LanguageRef. Prefer the explicit\nfields above." }, + "messageSyntax": { + "allOf": [ + { + "$ref": "#/components/schemas/constants.NamespaceMessageSyntax" + } + ], + "description": "MessageSyntax sets what the namespace's strings are: plain or icu\n(ICU MessageFormat 1). Omit to keep it." + }, "name": { "type": "string" } @@ -1185,6 +1541,7 @@ "INSUFFICIENT_SCOPE", "ORG_BLOCKED", "TOO_MANY_REQUESTS", + "AI_TRANSLATION_BUDGET_EXCEEDED", "INSUFFICIENT_PERMISSIONS", "INVALID_PAYLOAD", "EMPTY", @@ -1223,7 +1580,13 @@ "COLUMN_COUNT_MISMATCH", "LANGUAGE_NOT_IN_NAMESPACE", "INVALID_IMPORT_STATUS", - "DUPLICATE" + "DUPLICATE", + "INVALID_MESSAGE_SYNTAX", + "TERM_TRANSLATION_INVALID", + "TERM_IMPORT_TRANSLATIONS_INVALID", + "SYNC_CONTEXTS_INVALID", + "TERM_REVIEW_INVALID", + "TERM_FILTER_LANGUAGE_REQUIRED" ], "type": "string", "x-enum-varnames": [ @@ -1239,6 +1602,7 @@ "ErrInsufficientScope", "ErrOrgBlocked", "ErrTooManyRequests", + "ErrAITranslationBudgetExceeded", "ErrInsufficientPermissions", "ErrPayloadInvalid", "ErrEmpty", @@ -1277,7 +1641,13 @@ "ErrColumnCountMismatch", "ErrLanguageNotInNamespace", "ErrInvalidImportStatus", - "ErrDuplicate" + "ErrDuplicate", + "ErrInvalidMessageSyntax", + "ErrTermTranslationInvalid", + "ErrTermImportTranslationsInvalid", + "ErrSyncContextsInvalid", + "ErrTermReviewInvalid", + "ErrTermFilterLanguageRequired" ] }, "shared.TermBulkImportPrecheckData": { @@ -1369,6 +1739,13 @@ }, "syncjob.createSyncRequest": { "properties": { + "contexts": { + "additionalProperties": { + "type": "string" + }, + "description": "Contexts are key descriptions ({key: description}) the push phase\nstores with the terms; an empty description clears one, a key left\nout keeps its own. Each key must be one of the source language's\nkeys in this request, each description at most 1,000 characters.\nThe model gets them with the key when it translates.", + "type": "object" + }, "defaultLanguageCode": { "type": "string" }, @@ -1770,7 +2147,8 @@ "summary": "List API keys", "tags": [ "API keys" - ] + ], + "x-norcube-never": true }, "post": { "description": "Create API key", @@ -1852,7 +2230,8 @@ "summary": "Create API key", "tags": [ "API keys" - ] + ], + "x-norcube-never": true } }, "/apikeys/{id}": { @@ -1928,7 +2307,8 @@ "summary": "Delete API key", "tags": [ "API keys" - ] + ], + "x-norcube-never": true } }, "/audit-log": { @@ -2053,7 +2433,8 @@ "summary": "List Audit Log", "tags": [ "Audit" - ] + ], + "x-norcube-never": true } }, "/audit-log/actors": { @@ -2098,7 +2479,8 @@ "summary": "List Audit Log Actors", "tags": [ "Audit" - ] + ], + "x-norcube-never": true } }, "/glossary": { @@ -2147,9 +2529,14 @@ "description": "Internal Server Error" } }, - "summary": "Get Glossary", + "summary": "Get the glossary", "tags": [ "Glossary" + ], + "x-norcube-scopes": [ + "langsync.read", + "langsync.write", + "langsync.sync" ] }, "post": { @@ -2212,7 +2599,9 @@ "summary": "Create Glossary", "tags": [ "Glossary" - ] + ], + "x-norcube-risk": "changes settings", + "x-norcube-summary": "Starts the organization's glossary, with the default language {defaultLanguageId}." } }, "/glossary/items": { @@ -2292,9 +2681,14 @@ "description": "Internal Server Error" } }, - "summary": "List Glossary Items", + "summary": "List glossary items", "tags": [ "Glossary" + ], + "x-norcube-scopes": [ + "langsync.read", + "langsync.write", + "langsync.sync" ] }, "post": { @@ -2357,7 +2751,9 @@ "summary": "Create Glossary Item", "tags": [ "Glossary" - ] + ], + "x-norcube-risk": "changes settings", + "x-norcube-summary": "Adds {defaultLanguageValue} to the glossary as a {type}[ ({context})]; translatable: {isTranslatable}." } }, "/glossary/items/{itemId}": { @@ -2420,7 +2816,9 @@ "summary": "Delete Glossary Item", "tags": [ "Glossary" - ] + ], + "x-norcube-risk": "cannot be undone", + "x-norcube-summary": "Deletes the glossary item {itemId} with its translations." }, "get": { "description": "Retrieve a glossary item by ID", @@ -2478,9 +2876,15 @@ "description": "Internal Server Error" } }, - "summary": "Get Glossary Item", + "summary": "Get a glossary item", "tags": [ "Glossary" + ], + "x-norcube-page": "glossary-item", + "x-norcube-scopes": [ + "langsync.read", + "langsync.write", + "langsync.sync" ] } }, @@ -2556,7 +2960,9 @@ "summary": "Add Translation to Glossary Item", "tags": [ "Glossary" - ] + ], + "x-norcube-risk": "changes settings", + "x-norcube-summary": "Translates the glossary item {itemId} into the language {languageId} as {value}." } }, "/glossary/items/{itemId}/translations/{languageId}": { @@ -2640,7 +3046,9 @@ "summary": "Update Glossary Item Translation", "tags": [ "Glossary" - ] + ], + "x-norcube-risk": "changes settings", + "x-norcube-summary": "Changes the translation of the glossary item {itemId} in the language {languageId} to {value}." } }, "/glossary/languages": { @@ -2704,7 +3112,9 @@ "summary": "Attach Language to Glossary", "tags": [ "Glossary" - ] + ], + "x-norcube-risk": "changes settings", + "x-norcube-summary": "Adds the language {languageId} to the glossary." } }, "/languages": { @@ -2746,9 +3156,14 @@ "description": "Internal Server Error" } }, - "summary": "List languages (shared + this org's custom)", + "summary": "List languages", "tags": [ "languages" + ], + "x-norcube-scopes": [ + "langsync.read", + "langsync.write", + "langsync.sync" ] }, "post": { @@ -2821,7 +3236,9 @@ "summary": "Create a custom language", "tags": [ "languages" - ] + ], + "x-norcube-risk": "changes settings", + "x-norcube-summary": "Adds the custom language {name} ({code})." } }, "/languages/{id}": { @@ -2897,7 +3314,9 @@ "summary": "Delete a custom language", "tags": [ "languages" - ] + ], + "x-norcube-risk": "cannot be undone", + "x-norcube-summary": "Deletes the custom language {id}." } }, "/migrators/poeditor/projects": { @@ -2983,7 +3402,8 @@ "summary": "Get projects from POEditor", "tags": [ "Migrator" - ] + ], + "x-norcube-never": true } }, "/migrators/poeditor/start": { @@ -3066,12 +3486,13 @@ "summary": "Migrate terms from POEditor", "tags": [ "Migrator" - ] + ], + "x-norcube-never": true } }, "/namespaces": { "get": { - "description": "List all namespaces", + "description": "Lists the organization's namespaces (translation projects) with their languages, term counts and overall translation progress. For which terms or languages are missing, list the namespace's terms.", "operationId": "listNamespaces", "responses": { "200": { @@ -3138,9 +3559,14 @@ "description": "Internal Server Error" } }, - "summary": "List all namespaces", + "summary": "List namespaces", "tags": [ "Namespace" + ], + "x-norcube-scopes": [ + "langsync.read", + "langsync.write", + "langsync.sync" ] }, "post": { @@ -3223,7 +3649,9 @@ "summary": "Create a namespace", "tags": [ "Namespace" - ] + ], + "x-norcube-risk": "counts toward your plan", + "x-norcube-summary": "Creates the namespace {name}[ with the default language {defaultLanguageCode}][, message syntax {messageSyntax}]: {context}." } }, "/namespaces/{namespaceName}": { @@ -3306,7 +3734,9 @@ "summary": "Delete a namespace", "tags": [ "Namespace" - ] + ], + "x-norcube-risk": "cannot be undone", + "x-norcube-summary": "Deletes the namespace {namespaceName} with all its terms and translations." }, "get": { "description": "Get a namespace by name", @@ -3387,6 +3817,12 @@ "summary": "Get a namespace by name", "tags": [ "Namespace" + ], + "x-norcube-page": "namespace", + "x-norcube-scopes": [ + "langsync.read", + "langsync.write", + "langsync.sync" ] }, "patch": { @@ -3480,7 +3916,9 @@ "summary": "Update a namespace", "tags": [ "Namespace" - ] + ], + "x-norcube-risk": "changes settings", + "x-norcube-summary": "Changes the namespace {namespaceName}[: renames it to {name}, which the CLI's sync settings must follow][, context {context}][, default language {defaultLanguageCode}][, message syntax {messageSyntax}]." } }, "/namespaces/{namespaceName}/languages": { @@ -3563,9 +4001,14 @@ "description": "Internal Server Error" } }, - "summary": "Get languages attached to a namespace", + "summary": "List a namespace's languages", "tags": [ "Namespace" + ], + "x-norcube-scopes": [ + "langsync.read", + "langsync.write", + "langsync.sync" ] }, "post": { @@ -3659,7 +4102,9 @@ "summary": "Add a language to a namespace", "tags": [ "Namespace" - ] + ], + "x-norcube-risk": "changes settings", + "x-norcube-summary": "Adds the language {languageCode|languageId} to {namespaceName}." } }, "/namespaces/{namespaceName}/languages/{languageId}": { @@ -3751,12 +4196,15 @@ "summary": "Remove a language from a namespace", "tags": [ "Namespace" - ] + ], + "x-norcube-risk": "cannot be undone", + "x-norcube-summary": "Removes the language {languageId} from {namespaceName}, with all its translations there." } }, "/namespaces/{namespaceName}/sync": { "post": { "description": "Enqueues a sync job that diffs the submitted default-language marks against the server's state, optionally pushes the diff, triggers autotranslate, and finalises a per-language result. The actual work happens asynchronously; the CLI polls GET .../sync/{id} for progress.", + "operationId": "createSyncJob", "parameters": [ { "description": "Namespace name (URL slug)", @@ -3795,11 +4243,23 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/response.APIError" + "allOf": [ + { + "$ref": "#/components/schemas/response.APIError" + }, + { + "properties": { + "data": { + "$ref": "#/components/schemas/dto.SyncContextsProblem" + } + }, + "type": "object" + } + ] } } }, - "description": "Bad Request" + "description": "SYNC_CONTEXTS_INVALID: contexts name a key the request's source language does not have, are too many, too long or not text; INVALID_REQUEST otherwise" }, "401": { "content": { @@ -3845,12 +4305,14 @@ "summary": "Create a sync job for a namespace", "tags": [ "Namespaces" - ] + ], + "x-norcube-never": true } }, "/namespaces/{namespaceName}/sync/{jobId}": { "get": { "description": "Returns the sync job's progress and (when complete) the per-language result. Clients poll this endpoint until status is one of {completed, planned, failed, cancelled}.", + "operationId": "getSyncJob", "parameters": [ { "description": "Namespace name (URL slug)", @@ -3933,15 +4395,20 @@ "description": "Internal Server Error" } }, - "summary": "Get a sync job's current state", + "summary": "Get a sync job", "tags": [ "Namespaces" + ], + "x-norcube-scopes": [ + "langsync.read", + "langsync.write", + "langsync.sync" ] } }, "/namespaces/{namespaceName}/terms": { "get": { - "description": "Get terms by namespace name", + "description": "Lists every term of a namespace with its translation in each of the namespace's languages; a language with no translation is missing for that term. Use it to see which translations are missing or incomplete, per term and per language.", "operationId": "listByNamespace", "parameters": [ { @@ -3954,9 +4421,17 @@ } }, { + "description": "AIGenerated lists only terms whose translation in languageId has\ntext that is (true) or is not (false) exactly the AI's.", + "in": "query", + "name": "aiGenerated", + "schema": { + "type": "boolean" + } + }, + { + "description": "Cursor is the next value of the page before; empty for the first.", "in": "query", "name": "cursor", - "required": true, "schema": { "type": "string" } @@ -3969,17 +4444,35 @@ } }, { + "description": "LanguageID is the language the reviewed and aiGenerated filters\nlook at; required with either.", + "in": "query", + "name": "languageId", + "schema": { + "type": "integer" + } + }, + { + "description": "Limit is the page size, 1 to 100; 25 when absent or out of range.", "in": "query", "name": "limit", - "required": true, "schema": { + "maximum": 100, + "minimum": 1, "type": "integer" } }, { + "description": "Reviewed lists only terms whose translation in languageId has text\nand is (true) or is not (false) marked reviewed.", + "in": "query", + "name": "reviewed", + "schema": { + "type": "boolean" + } + }, + { + "description": "Search narrows the list to terms whose key or translations contain\nit; empty lists every term.", "in": "query", "name": "search", - "required": true, "schema": { "type": "string" } @@ -4026,7 +4519,7 @@ } } }, - "description": "Bad Request" + "description": "TERM_FILTER_LANGUAGE_REQUIRED: reviewed or aiGenerated without languageId" }, "401": { "content": { @@ -4069,9 +4562,14 @@ "description": "Internal Server Error" } }, - "summary": "Get terms by namespace name", + "summary": "List a namespace's terms", "tags": [ "Terms" + ], + "x-norcube-scopes": [ + "langsync.read", + "langsync.write", + "langsync.sync" ] }, "post": { @@ -4114,11 +4612,23 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/response.APIError" + "allOf": [ + { + "$ref": "#/components/schemas/response.APIError" + }, + { + "properties": { + "data": { + "$ref": "#/components/schemas/dto.TermTranslationProblem" + } + }, + "type": "object" + } + ] } } }, - "description": "Bad Request" + "description": "TERM_TRANSLATION_INVALID: in an ICU namespace, the default language value is not a valid message" }, "401": { "content": { @@ -4150,6 +4660,36 @@ }, "description": "Not Found" }, + "429": { + "content": { + "application/json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/response.APIError" + }, + { + "properties": { + "data": { + "$ref": "#/components/schemas/dto.AITranslationBudgetRefusal" + } + }, + "type": "object" + } + ] + } + } + }, + "description": "AI_TRANSLATION_BUDGET_EXCEEDED: the organization's AI translation limit for the hour or day is reached", + "headers": { + "Retry-After": { + "description": "Seconds until the limit frees up", + "schema": { + "type": "integer" + } + } + } + }, "500": { "content": { "application/json": { @@ -4164,7 +4704,15 @@ "summary": "Add term", "tags": [ "Terms" - ] + ], + "x-norcube-keywords": [ + "translation key", + "new key", + "new string", + "new term" + ], + "x-norcube-risk": "changes settings", + "x-norcube-summary": "Adds the term {mark} to {namespaceName}: {defaultLanguageValue}; translated automatically: {translateAutomatically}." } }, "/namespaces/{namespaceName}/terms/imports": { @@ -4266,7 +4814,8 @@ "summary": "Import creation and precheck", "tags": [ "Terms" - ] + ], + "x-norcube-never": true } }, "/namespaces/{namespaceName}/terms/imports/{importId}": { @@ -4411,11 +4960,23 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/response.APIError" + "allOf": [ + { + "$ref": "#/components/schemas/response.APIError" + }, + { + "properties": { + "data": { + "$ref": "#/components/schemas/dto.TermImportTranslationProblems" + } + }, + "type": "object" + } + ] } } }, - "description": "Bad Request" + "description": "TERM_IMPORT_TRANSLATIONS_INVALID: in an ICU namespace, values of the file are not valid messages (nothing is imported); other codes for the setup" }, "401": { "content": { @@ -4447,6 +5008,36 @@ }, "description": "Not Found" }, + "429": { + "content": { + "application/json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/response.APIError" + }, + { + "properties": { + "data": { + "$ref": "#/components/schemas/dto.AITranslationBudgetRefusal" + } + }, + "type": "object" + } + ] + } + } + }, + "description": "AI_TRANSLATION_BUDGET_EXCEEDED: the organization's AI translation limit for the hour or day is reached", + "headers": { + "Retry-After": { + "description": "Seconds until the limit frees up", + "schema": { + "type": "integer" + } + } + } + }, "500": { "content": { "application/json": { @@ -4461,7 +5052,8 @@ "summary": "Import finish", "tags": [ "Terms" - ] + ], + "x-norcube-never": true } }, "/namespaces/{namespaceName}/terms/translate-missing": { @@ -4541,6 +5133,36 @@ }, "description": "Not Found" }, + "429": { + "content": { + "application/json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/response.APIError" + }, + { + "properties": { + "data": { + "$ref": "#/components/schemas/dto.AITranslationBudgetRefusal" + } + }, + "type": "object" + } + ] + } + } + }, + "description": "AI_TRANSLATION_BUDGET_EXCEEDED: the organization's AI translation limit for the hour or day is reached", + "headers": { + "Retry-After": { + "description": "Seconds until the limit frees up", + "schema": { + "type": "integer" + } + } + } + }, "500": { "content": { "application/json": { @@ -4555,7 +5177,9 @@ "summary": "Translate missing translations", "tags": [ "Terms" - ] + ], + "x-norcube-risk": "costs usage", + "x-norcube-summary": "Translates the missing translations of {namespaceName} with AI[ into {languageIds}]." } }, "/namespaces/{namespaceName}/terms/{termId}": { @@ -4639,7 +5263,9 @@ "summary": "Delete term", "tags": [ "Terms" - ] + ], + "x-norcube-risk": "cannot be undone", + "x-norcube-summary": "Deletes the term {termId} from {namespaceName}, with its translations." }, "get": { "description": "One term of the namespace with its translations in every language of the namespace, in the same shape as an item of the term list.", @@ -4729,6 +5355,11 @@ "summary": "Get a term", "tags": [ "Terms" + ], + "x-norcube-scopes": [ + "langsync.read", + "langsync.write", + "langsync.sync" ] }, "patch": { @@ -4830,7 +5461,9 @@ "summary": "Update term", "tags": [ "Terms" - ] + ], + "x-norcube-risk": "changes settings", + "x-norcube-summary": "Changes the term {termId} in {namespaceName}[: mark {mark}][, context {context}]." } }, "/namespaces/{namespaceName}/terms/{termId}/translations/{languageId}/recommend": { @@ -4928,6 +5561,36 @@ }, "description": "Not Found" }, + "429": { + "content": { + "application/json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/response.APIError" + }, + { + "properties": { + "data": { + "$ref": "#/components/schemas/dto.AITranslationBudgetRefusal" + } + }, + "type": "object" + } + ] + } + } + }, + "description": "AI_TRANSLATION_BUDGET_EXCEEDED: the organization's AI translation limit for the hour or day is reached", + "headers": { + "Retry-After": { + "description": "Seconds until the limit frees up", + "schema": { + "type": "integer" + } + } + } + }, "500": { "content": { "application/json": { @@ -4942,7 +5605,9 @@ "summary": "Recommend magic translation", "tags": [ "Terms" - ] + ], + "x-norcube-risk": "costs usage", + "x-norcube-summary": "Suggests an AI translation of the term {termId} in {namespaceName} into {languageId}; nothing is saved." } }, "/namespaces/{namespaceName}/terms/{termId}/translations/{languageToNamespaceId}": { @@ -5004,11 +5669,23 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/response.APIError" + "allOf": [ + { + "$ref": "#/components/schemas/response.APIError" + }, + { + "properties": { + "data": { + "$ref": "#/components/schemas/dto.TermTranslationProblem" + } + }, + "type": "object" + } + ] } } }, - "description": "Bad Request" + "description": "TERM_TRANSLATION_INVALID: in an ICU namespace, the value is not a valid message or does not hold against the source" }, "401": { "content": { @@ -5054,7 +5731,126 @@ "summary": "Update translation", "tags": [ "Terms" - ] + ], + "x-norcube-risk": "changes settings", + "x-norcube-summary": "Sets the translation of the term {termId} in {namespaceName} to {value}." + } + }, + "/namespaces/{namespaceName}/translations/{languageId}/review": { + "post": { + "description": "Marks the current text of the listed terms' translations in one language reviewed by the person asking. Translations without text, terms of another namespace and translations reviewed already are skipped; reviewed says how many were marked. A translation whose text changes later (an edit, an AI translation, a sync) is unreviewed again.", + "operationId": "markTranslationsReviewed", + "parameters": [ + { + "description": "Namespace name", + "in": "path", + "name": "namespaceName", + "required": true, + "schema": { + "type": "string" + } + }, + { + "description": "Language ID", + "in": "path", + "name": "languageId", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.MarkReviewedRequest" + } + } + }, + "description": "Terms to mark", + "required": true, + "x-originalParamName": "payload" + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/dto.MarkReviewedResponse" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/response.APIError" + }, + { + "properties": { + "data": { + "$ref": "#/components/schemas/dto.TermReviewProblem" + } + }, + "type": "object" + } + ] + } + } + }, + "description": "TERM_REVIEW_INVALID: no terms, or more than 1,000" + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.APIError" + } + } + }, + "description": "Unauthorized" + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.APIError" + } + } + }, + "description": "Forbidden" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.APIError" + } + } + }, + "description": "LANGUAGE_NOT_IN_NAMESPACE" + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/response.APIError" + } + } + }, + "description": "Internal Server Error" + } + }, + "summary": "Mark translations reviewed", + "tags": [ + "Terms" + ], + "x-norcube-never": true } }, "/translations/custom-prompts": { @@ -5096,7 +5892,7 @@ "description": "Internal Server Error" } }, - "summary": "List Custom Prompts", + "summary": "List custom prompts", "tags": [ "CustomPrompts" ] @@ -5161,7 +5957,9 @@ "summary": "Create Custom Prompt", "tags": [ "CustomPrompts" - ] + ], + "x-norcube-risk": "changes settings", + "x-norcube-summary": "Creates the custom prompt {name}[, private: {isPrivate}]." } }, "/translations/custom-prompts/{promptId}": { @@ -5224,7 +6022,9 @@ "summary": "Delete Custom Prompt", "tags": [ "CustomPrompts" - ] + ], + "x-norcube-risk": "cannot be undone", + "x-norcube-summary": "Deletes the custom prompt {promptId}." }, "get": { "description": "One custom prompt of the organization: shared prompts, or a private prompt of the caller.", @@ -5302,7 +6102,7 @@ "description": "Internal Server Error" } }, - "summary": "Get Custom Prompt", + "summary": "Get a custom prompt", "tags": [ "CustomPrompts" ] @@ -5378,12 +6178,15 @@ "summary": "Update Custom Prompt", "tags": [ "CustomPrompts" - ] + ], + "x-norcube-risk": "changes settings", + "x-norcube-summary": "Changes the custom prompt {promptId}[: name {name}][, private: {isPrivate}]." } }, "/translations/translate": { "post": { "description": "Translates text from a source language to a target language.", + "operationId": "translateText", "requestBody": { "content": { "application/json": { @@ -5417,6 +6220,36 @@ }, "description": "Bad Request" }, + "429": { + "content": { + "application/json": { + "schema": { + "allOf": [ + { + "$ref": "#/components/schemas/response.APIError" + }, + { + "properties": { + "data": { + "$ref": "#/components/schemas/dto.AITranslationBudgetRefusal" + } + }, + "type": "object" + } + ] + } + } + }, + "description": "AI_TRANSLATION_BUDGET_EXCEEDED: the organization's AI translation limit for the hour or day is reached", + "headers": { + "Retry-After": { + "description": "Seconds until the limit frees up", + "schema": { + "type": "integer" + } + } + } + }, "500": { "content": { "application/json": { @@ -5431,7 +6264,9 @@ "summary": "Translate Text", "tags": [ "Translation" - ] + ], + "x-norcube-risk": "costs usage", + "x-norcube-summary": "Translates the text {text} with AI; nothing is saved." } } } From 5839864cc1ee9d36628990f8aae0bba03517742a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20=C5=A0v=C3=A1b=C3=ADk?= Date: Thu, 26 Nov 2026 04:49:55 +0100 Subject: [PATCH 3/5] chore(deps): cms-schema 0.12.1, kinds of value as codes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit cms-schema 0.12.1 sends the kinds of value a finding names (params.expected and params.actual) as codes from a closed vocabulary (group_of_fields where 0.12.0 sent "group of fields"), and a localized group's mixed field types in params.type and params.otherType. `cms validate -o json` and `-o yaml` print the params as the module emits them; the table, `-o text` and every English message and hint read as before. Signed-off-by: Jan Švábík --- CHANGELOG.md | 9 ++++++--- go.mod | 2 +- go.sum | 4 ++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e32eb2..bef8082 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,9 +9,12 @@ this file collects what users and scripts need to know. - `norcube cms validate -o json` (and `-o yaml`) gives each finding its `cause`, which of the rule's causes it is, and `params`, the facts its - message is made of, typed (cms-schema 0.12.0). The table, `-o text` - and the English `message` and `hint` are unchanged. A skipped quality - rule keeps its English `reason` and gains `code` and `params`. + message is made of, typed (cms-schema 0.12.1). Kinds of value are codes + (`params.expected` and `params.actual`: `group_of_fields`, + `list_of_references`, `string`…), the vocabulary the module's + `report/catalog.json` lists. The table, `-o text` and the English + `message` and `hint` are unchanged. A skipped quality rule keeps its + English `reason` and gains `code` and `params`. ## 0.28.0 (2026-11-25) diff --git a/go.mod b/go.mod index 0d3b1fd..029a8bf 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,7 @@ require ( github.com/gofrs/flock v0.13.0 github.com/google/uuid v1.6.0 github.com/jmespath-community/go-jmespath v1.1.1 - github.com/norcubeplatform/cms-schema v0.12.0 + github.com/norcubeplatform/cms-schema v0.12.1 github.com/oapi-codegen/runtime v1.4.0 github.com/pelletier/go-toml/v2 v2.3.1 github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c diff --git a/go.sum b/go.sum index 73baa14..481a726 100644 --- a/go.sum +++ b/go.sum @@ -129,8 +129,8 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= -github.com/norcubeplatform/cms-schema v0.12.0 h1:+rBvgxUQUORYMJloCmmu4MRjC8rsdZNB97mHVSFiymc= -github.com/norcubeplatform/cms-schema v0.12.0/go.mod h1:fY05NpvoygKgMBZjj3+R6KI1vko9CSJPJKS02n6WRh0= +github.com/norcubeplatform/cms-schema v0.12.1 h1:eCrNBa6S8XzoD+KJMcLyj4MOR8uir5JTBEV+8rToUQU= +github.com/norcubeplatform/cms-schema v0.12.1/go.mod h1:fY05NpvoygKgMBZjj3+R6KI1vko9CSJPJKS02n6WRh0= github.com/oapi-codegen/runtime v1.4.0 h1:KLOSFOp7UzkbS7Cs1ms6NBEKYr0WmH2wZG0KKbd2er4= github.com/oapi-codegen/runtime v1.4.0/go.mod h1:5sw5fxCDmnOzKNYmkVNF8d34kyUeejJEY8HNT2WaPec= github.com/oasdiff/yaml v0.1.1 h1:6nHx+pn9gBRM6YpBlFZFQGCCd1nuvqOBtTD3KKTgGxY= From f175a06cb0d0b5678db993c84990ef6dd86085b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20=C5=A0v=C3=A1b=C3=ADk?= Date: Thu, 26 Nov 2026 12:44:39 +0100 Subject: [PATCH 4/5] chore(deps): cms-schema 0.12.2, declaration kinds as codes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit cms-schema 0.12.2 names the kind of schema declaration a refused fact looks up as a code (params.declarationKind) instead of an English word in params.kind. nrc cms validate prints findings, not fact refusals, so its output is unchanged. Signed-off-by: Jan Švábík --- CHANGELOG.md | 2 +- go.mod | 2 +- go.sum | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 60943a0..e2e3dac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ this file collects what users and scripts need to know. - `norcube cms validate -o json` (and `-o yaml`) gives each finding its `cause`, which of the rule's causes it is, and `params`, the facts its - message is made of, typed (cms-schema 0.12.1). Kinds of value are codes + message is made of, typed (cms-schema 0.12.2). Kinds of value are codes (`params.expected` and `params.actual`: `group_of_fields`, `list_of_references`, `string`…), the vocabulary the module's `report/catalog.json` lists. The table, `-o text` and the English diff --git a/go.mod b/go.mod index 029a8bf..82db17e 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,7 @@ require ( github.com/gofrs/flock v0.13.0 github.com/google/uuid v1.6.0 github.com/jmespath-community/go-jmespath v1.1.1 - github.com/norcubeplatform/cms-schema v0.12.1 + github.com/norcubeplatform/cms-schema v0.12.2 github.com/oapi-codegen/runtime v1.4.0 github.com/pelletier/go-toml/v2 v2.3.1 github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c diff --git a/go.sum b/go.sum index 481a726..0053244 100644 --- a/go.sum +++ b/go.sum @@ -129,8 +129,8 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc= github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= -github.com/norcubeplatform/cms-schema v0.12.1 h1:eCrNBa6S8XzoD+KJMcLyj4MOR8uir5JTBEV+8rToUQU= -github.com/norcubeplatform/cms-schema v0.12.1/go.mod h1:fY05NpvoygKgMBZjj3+R6KI1vko9CSJPJKS02n6WRh0= +github.com/norcubeplatform/cms-schema v0.12.2 h1:JjU+20g6X5J9faIYkmOfrdCJmWQ53KriH/mFor0uS4Q= +github.com/norcubeplatform/cms-schema v0.12.2/go.mod h1:fY05NpvoygKgMBZjj3+R6KI1vko9CSJPJKS02n6WRh0= github.com/oapi-codegen/runtime v1.4.0 h1:KLOSFOp7UzkbS7Cs1ms6NBEKYr0WmH2wZG0KKbd2er4= github.com/oapi-codegen/runtime v1.4.0/go.mod h1:5sw5fxCDmnOzKNYmkVNF8d34kyUeejJEY8HNT2WaPec= github.com/oasdiff/yaml v0.1.1 h1:6nHx+pn9gBRM6YpBlFZFQGCCd1nuvqOBtTD3KKTgGxY= From eb71a1bad501b169aa4020d71b8181e46c046f41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20=C5=A0v=C3=A1b=C3=ADk?= Date: Thu, 26 Nov 2026 14:55:56 +0100 Subject: [PATCH 5/5] chore: release 0.29.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jan Švábík --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e2e3dac..041409a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ this file collects what users and scripts need to know. ## Unreleased +## 0.29.0 (2026-11-26) + ### New - `norcube cms validate -o json` (and `-o yaml`) gives each finding its