diff --git a/AGENTS.md b/AGENTS.md index 56cf833..a7263fd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,8 +56,9 @@ Four paths, and `package.json`'s `exports` lists no others (spec 000 §5a): A new export goes on the lowest of these that serves it; the root grows only for something a client user writes or reads. On the client, reads are -`client.query` / `queryPage` / `get`, `client.search` across asset types -and `client.deleted`, and writes are `client.send`, +`client.query` / `queryPage` / `get`, `client.search` across asset types, +`client.deleted` and `client.lists` (the values a list-typed attribute may +take), and writes are `client.send`, `client.preview` and `client.sendGuarded` (a guarded write compares each asset's `Moment`; what matched nothing is a conflict, never a success: spec 000 §6). @@ -112,6 +113,46 @@ change, by design: `layers.test.ts` (imports point down the layer table), line.** Until 1.0.0, breaking changes are allowed between alphas and are listed under "Breaking". +## Reference data on the testing instance + +The API-testing instance holds nine assets that are there to stay, so +that a consumer can prove valid values (`client.lists`, api/ValidValues) +and status-by-name against real values. + +A team with its own process and the three statuses it owns, in this +Order: + +| OID | Name | | +|---|---|---| +| `Team:152495` | sdk-reference team | `HasProcess` is true | +| `StoryStatus:152496` | sdk-reference Ready | RollupState Future | +| `StoryStatus:152497` | sdk-reference In Progress | RollupState Active | +| `StoryStatus:152498` | sdk-reference Done | RollupState Closed | + +Five global story statuses with the product's own names, on no team, +selected in the Default Scheme (`Scheme:1000`, which nearly every project +on the instance uses), in this Order: + +| OID | Name | | +|---|---|---| +| `StoryStatus:152567` | Future | RollupState Active | +| `StoryStatus:152568` | In Progress | RollupState Active | +| `StoryStatus:152569` | QA / Test | RollupState Active | +| `StoryStatus:152570` | Done | RollupState Closed | +| `StoryStatus:152571` | Accepted | RollupState Closed | + +A Story created as a fixture in the system project (`Scope:0`) on no team +is offered exactly those five; one with `Team: "Team:152495"` exactly the +three `sdk-reference` ones. + +**Nothing creates, edits, closes, reorders or deletes any of the nine, or +anything named `sdk-reference`, and nothing changes what `Scheme:1000` +selects.** `sdk-reference` marks permanent data; `sdk-integration` marks +what a test creates and deletes in its own run. `deleteFixtures` refuses a +list that contains any of the nine OIDs or any asset whose name starts +with `sdk-reference` (test/integration/referenceData.ts), and no test may +assume the instance has no status, team or other asset of a kind. + ## Pull requests and releases - Branch from `master`, open the pull request against `master`, and say diff --git a/CHANGELOG.md b/CHANGELOG.md index 68ac20b..4ef2bba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,128 @@ # Changelog +## 1.0.0-alpha.12 + +### Breaking + +- **A config object with a key its factory does not know is refused.** + `new AgilityApiClient(config, options)`, `createFetchTransport(config)` + and `new FakeAgilityClient(config)` (the fake this package exports + from `/testing`, not a test double of your own that happens to share + the name) each throw a `UsageError` at + construction when the object has a key that is not one of theirs. The + message names the key or keys, suggests the nearest known key when one + looks like a typo (`"retrys" (did you mean "retries"?)`), lists the + keys the factory takes, and never repeats a value. Until now such a + key was ignored without a word, which a TypeScript caller is told at + compile time and a JavaScript or JSDoc-checked caller never was: a + consumer's `fetchImpl` on the client's config did nothing for several + releases. A key is refused whatever its value, `undefined` included + (the name is the mistake); a known key may still be `undefined`. + Migration: read each `new AgilityApiClient(…)`, + `createFetchTransport(…)` and `new FakeAgilityClient(…)` in your code + and remove or correct any key the README does not list for it. The two + most likely: an option in the wrong object (`transport` and `types` go + in the client's second argument; `onError` is the client's, not the + transport's), and a config object shared between the client and + something else that added its own keys to it (pass the client its own + object). + +### Fixed + +- **A built-in transport handed to a client was wrapped in the resend + and timeout rules a second time**, so a read that failed with a 5xx, + a 429 or a lost connection was sent four times instead of two + (`new AgilityApiClient(config, { transport: createFetchTransport(…) + })`, the way to give the client a `fetch` of your own until now; a + CLI consumer finding, present since alpha.5). The transport + `createFetchTransport` returns now says that it applies both rules + itself, and the client adds neither. Its own `retries` and `timeoutMs` + are then the ones that count: set them on `createFetchTransport`, not + on the client. Migration: nothing, unless you counted on four sends. + A wrapper of your own around the built-in transport is a custom + transport and gets the client's rules around it; make the inner one + with `retries: 0, timeoutMs: 0` to have each rule once. + +### Changed + +- **More is known about `"retry-write"`** (no behaviour change). A + browser-app consumer checked the case that matters most to a browser: + a credential that had been valid and expired. On one product release + an api/asset batch of creates and a rest-1 attribute write were each + answered 401 and not applied, and a query.v1 read got the same 401; + no 403 and no redirect was seen. The doc comment, spec 000 and example + 09 now say so. Still not checked: a 403, other releases, other ways of + signing in. The same check showed that a 401 can carry a body + (`{"error":"Unauthorized"}`, or rest-1's `{"_type":"Error", …}`) or + none; all three are `kind: "auth"`, and `transportConformance` now has + each as a case. + +### Added + +- `fetchImpl` in the client's config: the `fetch` the built-in transport + calls (a proxy-aware one, a recording one in a test), so a caller no + longer has to build the transport to supply it. It was accepted and + silently ignored by a JavaScript caller before. + +- **`client.lists`: the values a list-typed attribute may take, and the + one a name means.** For Status, Priority, Source, Category and any + other relation to a list type, over the server's api/ValidValues, as + the product's own pickers ask it. + - `client.lists.values({ asset, attributes, select? })` for an existing + asset, or `{ type, scope, team?, attributes }` for one not created + yet: a map from attribute to rows `{ _oid, Name, …selected }` in the + list's own order. One request per attribute, one after another; + nothing is cached. + - `client.lists.value({ asset | type+scope, attribute, name, match? })`: + the one value a name means there, matched whole, ignoring case and + surrounding space; `name` may be an OID, which is checked to be among + the valid values; `match: "prefix"` also accepts the start of the + name or of a word in it when no name matches whole. No match is an + `ApiError` coded `NO_SUCH_VALUE`, several is `AMBIGUOUS_VALUE` (both + `kind: "invalid"`), each with the candidates as rows in + `details.values`. + - What decides, proved live on fixtures: the scope's scheme (only the + values selected in it); a team that owns statuses replaces the + scheme's statuses with its own, and `{ asset }` alone applies that; + a team that owns none changes nothing; an inactive value is left + out; there is no "none" entry; a base type (`PrimaryWorkitem`) is + accepted. + - The server enforces less on a write than this list says: it refuses + a status outside a team's process, and accepts one the scope's + scheme does not select. Resolve a name with `lists.value` before + writing it. + - Only relations to a list type. The endpoint takes no page and no + filter and answers any attribute whole, so `Owners`, `Team`, + `Timebox` and the like are a `UsageError` before anything is sent, + naming the bounded read to use (`client.query` on the related type + with a filter and a page). An attribute the type does not have, a + date in `select` (the endpoint writes dates in the server's culture + format) and a path in `select` are refused the same way. + - Telling a list from another relation walks the related type's + ancestors to `List` (for Status: `StoryStatus`, `Status`, `List`), so + a cold schema cache pays up to two more type loads. A type in that + chain that cannot be loaded is an `ApiError` coded `NOT_FOUND` naming + it, never "not a list type" (a test that serves captured meta.v1 + types needs those two as well). + - No fallback: on an instance without the endpoint the call fails as + the server's 404, never as an empty list. From which product release + the endpoint exists is not established here. +- `client.fields.describe(type, scope)` answers `lists` as well: which + of the required, visible and important attributes are list-typed, and + the list type of each (`{ Status: "StoryStatus" }`). A consumer that + compares the whole answer with `toEqual` adds the key. +- `/wire`: `validValues.forAsset` and `validValues.forNew`, the endpoint + as it is, unbounded; its header says what care that needs. `/services`: + `lists`. +- `/testing`: `fake.onValues({ Status: rows })` scripts the valid values + by attribute (rows, a function of what was asked, or an Error), and + `fake.valuesAsked` records each request. Name matching and the two + errors are the client's own on the fake. Without a `metamodel` the + fake does not know what an attribute nobody scripted is and says so + in its own words; to test what the client refuses (`Owners`), give + the fake a metamodel. +- `examples/12-list-values.ts`. + ## 1.0.0-alpha.11 ### Breaking diff --git a/README.md b/README.md index ccfc866..d0c26bc 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,9 @@ npm test | Write with a record and an undo | `client.batch.run(commands, { guard })` then `client.batch.reversible(receipt)` | `guard` has no default. | | Copy an asset, or run an operation for its result | `client.copy(oid)` / `client.operate(oid, op)` | | | Defaults for a new asset | `client.template(type, { ctx })` | Nothing is created. | -| What a form needs | `client.fields.describe(type, scope)` | Required, visible and important attributes. | +| What a form needs | `client.fields.describe(type, scope)` | Required, visible and important attributes, and which of them are list-typed. | +| The values a Status, Priority or other list may take | `client.lists.values({ asset, attributes })` or `{ type, scope, team?, attributes }` | As the project's scheme and the team's process allow. See "List values". | +| The value a name means | `client.lists.value({ asset, attribute, name })` | `{ _oid, Name }` to write; `NO_SUCH_VALUE` with the valid values otherwise. | | Files | `client.attachments.*`, `client.embeddedImages.*` | | | A link for a person | `client.urls.asset(oidOrNumber)` | | | An error, said to a person | `client.explain(error)` | "Project is required.", with the instance's labels. | @@ -124,6 +126,30 @@ A date is spelled one way on every read: `"2026-09-06T13:52:51.903"`, three deci Rows are typed from what you select, against the product's metamodel: a selected key is its value or `null`, never `undefined`. For an attribute your instance has and the generated model does not (a custom field's relation, a product module's attribute), name your own row type at the call: `client.query(q)` needs only `_oid` on `MyRow`. +### List values + +Which values a list-typed attribute may take depends on where the asset is. `client.lists` asks the server, as the product's own pickers do: + +```ts +// For an existing asset: its own project and team apply. +const { Status, Priority } = await client.lists.values({ asset: "Story:1077", attributes: ["Status", "Priority"], select: ["Order"] }); +// → Status: [{ _oid: "StoryStatus:133", Name: "Future", Order: "115" }, …], in the list's own order + +// For one not created yet: say where it will be. +await client.lists.values({ type: "Defect", scope: "Scope:1005", team: "Team:1030", attributes: ["Priority"] }); + +// From a name a person typed (or an OID) to the value to write. +const done = await client.lists.value({ asset: "Story:1077", attribute: "Status", name: "done" }); +await client.send([{ from: "Story:1077", update: { Status: done._oid } }]); +``` + +- **What decides.** The project's scheme: only the values selected in it. A team that has its own process (it owns statuses; `Team.HasProcess`) replaces the scheme's statuses with its own, and `{ asset }` alone applies that, so there is nothing to switch on. A team without a process changes nothing. An inactive value is left out, and "no value" is never an entry. The order is the values' `Order`. +- **Resolve before you write.** A team's process IS enforced on a write: a status outside it is refused, as a command failure `Violation'PrimaryWorkitemCannotHaveInvalidStatus`. A scheme's selection is NOT: a status the project's scheme does not select is accepted, with no violation at all. Nothing but this lookup stops a write from setting a value the project does not use. +- **`lists.value` matches the whole name**, ignoring case and surrounding space. `match: "prefix"` also accepts the start of the name or of a word in it ("prog" finds "In Progress") when no name matches whole. It never picks among several: no match is an `ApiError` coded `NO_SUCH_VALUE`, more than one is `AMBIGUOUS_VALUE`, and both carry the candidates as rows in `error.details.values` (every valid value, or the ones that matched), ready to offer. +- **Only lists.** The server's endpoint takes no page and no filter and would answer every member, team or iteration in the project, so for `Owners`, `Team`, `Timebox` and any relation that is not to a list type, `client.lists` throws a `UsageError` before sending anything. There is no "valid values" call for those: read them with `client.query({ from: "Member", filter, page })`, bounded like every other read. +- **Costs and limits.** One request per attribute, sent one after another, and on a cold schema cache the type loads that tell a list from another relation (for Status: `StoryStatus`, `Status`, `List`); nothing is cached, because an administrator can change a scheme at any time. `select` takes attributes of the value itself (`Order`, `RollupState`), not paths and not dates, and every value arrives as a string. On an instance without the endpoint the call fails as the server's 404; it does not fall back to every value of the list type, which would be a different answer. +- `client.fields.describe(type, scope).lists` says which of a form's attributes are list-typed and to which list type each points. + ### Reference Changes between alphas are in `CHANGELOG.md`, each with its migration line. @@ -148,6 +174,8 @@ Changes between alphas are in `CHANGELOG.md`, each with its migration line. - `createFetchTransport` - configurable HTTP transport: `credentials` for same-origin cookie auth, `onUnauthorized` to re-authenticate on a 401 (resends idempotent requests once), and a per-request `signal`; `client.withSignal(signal)` ties a whole client to one - **Timeouts are the client's business with any transport**: each attempt has `timeoutMs` (default 60000; 0 for none), and at the deadline the request rejects with an `ApiError` coded `TIMEOUT`, whether or not a custom transport lets go of it (the transport is handed a `signal` that fires then; a late answer is discarded). A timed-out write may still have been applied. A custom transport that waits for a person inside `request` (a sign-in prompt before it replays the request) sets `timeoutMs: 0`: the deadline cannot tell a person from a slow network. The built-in transport's `onUnauthorized` hook runs outside the deadline - Every `ApiError` the client lets out says what was asked: `error.request` is `{ method, path, idempotent }` (never the body or headers). `client.explain(error)` uses it: a write that got no answer, or a server failure for one, is explained as "Agility did not confirm the change. It may or may not have been made: check before trying again." with `retrySafe: false`, where a read is `retrySafe: true`, except a read the server itself gave up on (`SERVER_TIMEOUT`), which is `false`: the same request would cost and fail the same. The two questions after a failure are two fields: `retrySafe` (may the same request be sent again as it is?) and `outcome` (is it known whether the change was made?). `outcome` is `"unknown"` for a write that got no confirmation (no answer, a timeout, a 5xx: look before acting), `"notApplied"` where the server answered a refusal before doing the work (a 4xx or a 429 in answer to a write, a conflict, and each failed command in the explanation of a batch, which says nothing of the batch's other commands: those are in the Outcome), and `null` for a read or when the error does not say what was asked. A guarded write (`sendGuarded`) is a write here too: it is never sent again by the client, because a second send of one that landed applies nothing and reports a conflict, which would tell you someone else changed the asset when the change was yours. When one gets no answer (`outcome: "unknown"`), read the asset again: you see your change or you do not, and the guard makes sending it again safe. Decide on `retrySafe`, not on the sentence; it is `null` when the server answered, or when the error carries no stamp (one from a `/wire` function on a bare transport) +- A config key that is not one the factory takes (`new AgilityApiClient`, `createFetchTransport`, `new FakeAgilityClient`) is refused at construction with a `UsageError` naming it, with the nearest known key when it looks like a typo. Nothing is ignored silently, and no value is repeated in the message. +- A `fetch` of your own goes in the client's config (`fetchImpl`). A transport you make yourself with `createFetchTransport` and hand to the client keeps its own `retries` and `timeoutMs` and is not given the client's rules a second time; a wrapper of yours around it is a custom transport and is, so make the inner one with `retries: 0, timeoutMs: 0`. - Resends and failures are the client's business with any transport: an idempotent request (a GET, a read; never a write, guarded or not) is sent once more after a network failure, a 5xx or a 429 (`retries`, default 1, 0 for none; never a plain write, a 401 or a 403, and **never after a timeout**: the client's `TIMEOUT`, a 408, a 504, or the server's own SQL execution timeout, which arrives as an error document and is coded `SERVER_TIMEOUT` (ask for less: a smaller page, fewer selected paths, a tighter filter). A timeout or an abort ends the client's wait and does not stop the work on the server, so a query that timed out may still be running; `pages` and `all` stop at the first one), and `onError(error, request)` in the config is told about each request that finally failed - A custom `Transport` (`new AgilityApiClient(config, { transport })`) decides by itself where requests go; `config.baseUrl` is then used only for the links the client builds (`urls.*`, `embeddedImages.normalize`). `apiErrorFromResponse(status, data)` is the error the fetch transport throws for a refused response, for a custom transport to throw the same - `@versionone/agility-sdk/services` - the services as free functions over a `Transport` (`guard`, `batch`, `resolve`, `schema`, `attachments`, `fields`), for a caller that composes one differently; the client's methods are the same things @@ -174,6 +202,7 @@ expect(fake.sent[0]).toEqual([{ from: "Story:1", execute: "QuickClose" }]); - `onSearch(rows)` answers a search, whether your code calls `fake.search` or builds its own client on `fake.transport`: the fake pages the rows and reports the total, each row comes back with exactly the selected keys, and `fake.searched` is what was asked. Script it before the first search. - `sendGuarded` and `batch.run` work on assets addressed by OID that you scripted a row for: `fake.touch(oid)` is someone else changing the asset (the next write stamped earlier is a conflict), `fake.remove(oid)` is it being deleted. - `resolve.numbers` finds a number among the scripted rows; `localize` answers `onLocalize` labels and echoes any other tag; `fake.transport` can be the transport of a client your code builds itself. +- `onValues({ Status: [{ _oid: "StoryStatus:135", Name: "Done" }] })` scripts the valid values by attribute (rows, a function of what was asked, or an Error). `lists.value`'s matching and its errors are the client's own, and `fake.valuesAsked` records each request: the type, the attribute and the asset or the scope and team. - `onList(type, rows)` answers rest-1's list read the same way (`client.deleted`, and `rest1.list` from `/wire`). `onRequest(path, answer)` answers any other endpoint in its own shape; with `new FakeAgilityClient({ metamodel })` (a meta.v1 document) a response captured from a server reads translated, as it would live. An `Error` as an answer is thrown. - A custom `Transport` has its own suite: `transportConformance(make)` answers the SDK's expectations of a transport as named checks (`for (const c of transportConformance(make)) it(c.name, c.run)`), and the SDK's fetch transport runs the same ones. - The fake evaluates no filter or sort and applies no write. It proves what your code asks and what it does with the answer; what the server answers is for a test against an instance. diff --git a/examples/09-browser-session.ts b/examples/09-browser-session.ts index 8c165ce..a542d2d 100644 --- a/examples/09-browser-session.ts +++ b/examples/09-browser-session.ts @@ -46,10 +46,10 @@ const client = new AgilityApiClient({ // sending it again would apply it twice. "retry-write" resends it // anyway, and is YOUR assertion that on your server a refusal for an // expired session means nothing in the request was executed. It has - // been seen to hold for a missing and for an invalid session on one - // release (a 401 before any command ran); not for a session that - // expired, a 403, or rest-1. Answer it only if you know it holds for - // you; otherwise answer "fail" and let the user retry. + // been seen to hold on one release for a missing, an invalid and an + // expired credential (a 401 before any command ran, on api/asset and + // on a rest-1 write); not for a 403. Answer it only if you know it + // holds for you; otherwise answer "fail" and let the user retry. return "retry-write"; } }); diff --git a/examples/12-list-values.ts b/examples/12-list-values.ts new file mode 100644 index 0000000..85b8fe0 --- /dev/null +++ b/examples/12-list-values.ts @@ -0,0 +1,49 @@ +/** + * List values: which Status or Priority an asset may take, and the one a + * name means, with `client.lists`. Writes nothing. + * + * V1_URL=… V1_ACCESS_TOKEN=… node examples/12-list-values.ts [status name] + */ +import { AgilityApiClient, ApiError, type ListValue } from "@versionone/agility-sdk"; + +const { V1_URL, V1_ACCESS_TOKEN } = process.env; +if (!V1_URL || !V1_ACCESS_TOKEN) throw new Error("set V1_URL and V1_ACCESS_TOKEN"); +const client = new AgilityApiClient({ baseUrl: V1_URL, accessToken: V1_ACCESS_TOKEN }); +const wanted = process.argv[2] ?? "Done"; + +const [story] = await client.query({ from: "Story", select: ["Name", "Number", "Scope"], sort: ["-ChangeDateUTC"], page: { size: 1, start: 0 } }); +if (!story) throw new Error("this instance has no Story to ask about"); + +// What a form for this asset should offer. The project's scheme decides, +// and a team with its own process replaces the scheme's statuses with its +// own: the asset alone says all of that. One request per attribute; each +// value is a row like any other, in the list's own order. +const offered = await client.lists.values({ asset: story._oid, attributes: ["Status", "Priority"], select: ["Order"] }); +for (const [attribute, rows] of Object.entries(offered)) console.log(`${story.Number} ${attribute}: ${rows.map((r) => r.Name).join(", ") || "(no value is valid here)"}`); + +// For an asset that does not exist yet, say where it will be. +const forNew = await client.lists.values({ type: "Defect", scope: story.Scope!._oid, attributes: ["Priority"] }); +console.log(`a new Defect in the same project, Priority: ${forNew.Priority!.map((r) => r.Name).join(", ") || "(none)"}`); + +// From a name a person typed to the value to write. The whole name must +// match, ignoring case; `match: "prefix"` also takes the start of a word. +// Resolve before writing: the server accepts a status the project's scheme +// does not select, so nothing else stops a value the project does not use. +try { + const status = await client.lists.value({ asset: story._oid, attribute: "Status", name: wanted }); + console.log(`"${wanted}" is ${status._oid}; to set it: client.send([{ from: "${story._oid}", update: { Status: "${status._oid}" } }])`); +} catch (error) { + if (!(error instanceof ApiError) || (error.code !== "NO_SUCH_VALUE" && error.code !== "AMBIGUOUS_VALUE")) throw error; + // The candidates are rows, so a caller can offer them as buttons and write the one picked without asking again. + const candidates = (error.details as { values: ListValue[] }).values; + console.log(`${error.code}: ${error.message} (${candidates.length} to offer)`); +} + +// Only a list. The server's endpoint cannot be paged, so for a relation to +// members, teams or iterations the call is refused before anything is +// sent, and says which bounded read to use instead. +try { + await client.lists.values({ asset: story._oid, attributes: ["Owners"] }); +} catch (error) { + console.log(`Owners: ${(error as Error).message.split(". ")[0]}`); +} diff --git a/examples/README.md b/examples/README.md index 60db985..3676e28 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,6 +1,6 @@ # Examples -Eleven short programs, one per task, each runnable as it stands. Read them +Twelve short programs, one per task, each runnable as it stands. Read them in order; each says at the top what it does. | File | Shows | Writes? | @@ -16,6 +16,7 @@ in order; each says at the top what it does. | `09-browser-session.ts` | Cookie auth for a browser app: `credentials`, `onUnauthorized`, and when `"retry-write"` is yours to answer | no instance at all (a stand-in server) | | `10-search.ts` | `client.search` across asset types; `find` on an ordinary read within one family | no | | `11-axios-transport.ts` | A `Transport` over an axios instance, and an axios adapter that lets `transportConformance` stand in for the network | no instance at all | +| `12-list-values.ts` | `client.lists`: the Status and Priority values an asset may take, a name resolved to the value to write, and what is refused | no | ## Running one diff --git a/package-lock.json b/package-lock.json index adeb3cd..18966ad 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.11", + "version": "1.0.0-alpha.12", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.11", + "version": "1.0.0-alpha.12", "license": "MIT", "devDependencies": { "@types/node": "^22.13.10", diff --git a/package.json b/package.json index 9d350d2..3fc91b9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.11", + "version": "1.0.0-alpha.12", "description": "TypeScript SDK for the Digital.ai Agility (VersionOne) API: queries, batches, schema-translated rows, guarded writes, attachments", "keywords": [ "agility", diff --git a/specs/000-layers.md b/specs/000-layers.md index ccb8a14..a1f1901 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -189,10 +189,12 @@ committed files. is its name, and this repository is public); any other hosted URL and anything named V1Production is **refused**. A suite that recycles the app domain (custom fields) runs on local instances only. - Suites bring their own data — a hosted testing instance may be nearly - empty (it had no StoryStatus at all on 2026-11-04) — and fixtures are - named `sdk-integration …` and deleted by exact OID by the suite that made - them. + Suites bring their own data and assume nothing about what else the + instance holds, and fixtures are named `sdk-integration …` and deleted + by exact OID by the suite that made them. The API-testing instance also + holds a little permanent reference data (AGENTS.md lists it by OID): + nothing creates, edits or deletes it, and `deleteFixtures` refuses a + list that contains any of it. The API's real behaviours — silent empties, projection order, full-text index lag, what a preview echoes — are what fakes cannot reproduce; the @@ -235,7 +237,17 @@ another 4xx, never after a timeout (below), and once by default (`retries: 1`); the client's, not one transport's: the built-in fetch transport applies it itself (it can read Retry-After), and the client applies it around a custom Transport (`core/retry`), so a consumer's transport does not -re-implement it and cannot forget it. `retries: 0` turns it off for a +re-implement it and cannot forget it. Each rule is applied once, in one +place: the transport `createFetchTransport` returns declares that it +times its attempts and resends by the rule itself (`governsItself`), and +the client then adds neither, whether it made that transport or was +handed it; every other transport gets both from the client. (The rule +stays inside the built-in transport because only there is the response +at hand, with its Retry-After. Before this was declared, a built-in +transport handed to a client got the rule twice and sent a failed read +four times.) A caller's wrapper around the built-in transport is a +custom transport, and its author gives the inner one `retries: 0, +timeoutMs: 0`. `retries: 0` turns it off for a client. A 401 or 403 is never resent by it. So is the timeout. Each attempt has `timeoutMs` (60 s unless told; 0 for @@ -249,6 +261,13 @@ suite checks; one with a shorter timeout of its own simply rejects first. A timeout says the client stopped waiting, never that the server did not act, which is one more reason a write is not resent. +One endpoint cannot be bounded at all: api/ValidValues takes no page and no +filter, and answers for any attribute. The lists service therefore asks it +only for relations to a list type (one that descends from List), which are +short by nature, and refuses every other attribute before sending, naming +the bounded read to use instead. The wire module says in its header that a +caller using it directly takes that care itself. + **Nothing is resent after a timeout, a read included.** A timeout or an abort ends the client's wait; it does not stop the work on the server. A query that timed out may still be running, and a request that ran out of @@ -276,13 +295,14 @@ and the caller decides. There is one way round that, and it is the consumer's assertion, not the SDK's: a hook that answers "retry-write" has the refused request sent once more, a plain write included, on its own word that on its server such a refusal means nothing in the request -was executed. The premise has been checked once, by a consumer, on one -product release: an api/asset create sent with no session, and one sent -with an invalid session, were each answered 401 with an empty body before -any command ran, and nothing was created. It has not been checked for a -session that was valid and has expired, for a 403, or for rest-1, and the -SDK's own tests (which run where every request is authenticated) check -none of it. So the SDK never assumes it. A guarded write is a write here +was executed. The premise has been checked by a consumer, on one product +release: an api/asset create sent with no session, with an invalid one, +and with a credential that had been valid and expired was each answered +401 before any command ran, and nothing was created; with the expired +credential a rest-1 attribute write was refused the same way and not +applied. It has not been checked for a 403, on other releases, or for +other ways of signing in, and the SDK's own tests (which run where every +request is authenticated) check none of it. So the SDK never assumes it. A guarded write is a write here too: `retryable` is false for it, and "retry-write" is what resumes it. A request sent with `reauthorize: false` skips the hook: it is how a hook asks whether the session is alive without waiting on itself. A caller's abort (`signal`) ends the request as @@ -346,7 +366,8 @@ every `ApiError` has a `kind`: `auth`, `forbidden`, `notFound`, `invalid`, `transient`, `aborted`, `commandFailure`, `conflict`, `protocol`, `usage` or `unknown`. `status` and `code` say what happened; `kind` says what to do. A mistake the SDK catches before any request (an unpaged read, an empty -batch, a bad OID token) is a `UsageError` (`kind: "usage"`, `status: 0`), +batch, a bad OID token, a config object with a key its factory does not +know: named in the message, never with its value) is a `UsageError` (`kind: "usage"`, `status: 0`), never a bare `Error` or `TypeError`. An error raised around another (a batch send that failed, an upload that failed after its create) is a `WrappedError` carrying the cause and the cause's kind, so the branch a diff --git a/src/client.ts b/src/client.ts index 156a036..bcd7c05 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,12 +1,14 @@ -import type { ClientConfig } from "./core/clientConfig"; +import { CLIENT_CONFIG_KEYS, type ClientConfig } from "./core/clientConfig"; +import { keysOf, refuseUnknownKeys } from "./core/knownKeys"; import { ApiError, UsageError } from "./core/errors"; import { createFetchTransport } from "./core/fetchTransport"; -import { DEFAULT_TIMEOUT_MS, withErrorHook, withRequestStamp, withRetry, withTimeout } from "./core/retry"; +import { DEFAULT_TIMEOUT_MS, withErrorHook, withRequestStamp, withRetry, withTimeout, governsItself } from "./core/retry"; import type { Transport } from "./core/transport"; import * as attachments from "./services/attachments"; import * as batch from "./services/batch"; import * as explainService from "./services/explain"; import * as fieldsService from "./services/fields"; +import * as listsService from "./services/lists"; import * as guard from "./services/guard"; import * as resolve from "./services/resolve"; import { Schema, type TypeCache } from "./services/schema"; @@ -69,6 +71,8 @@ export type Me = Pick()({ transport: true, types: true }); + /** Transports a client has already put its resend rule and error hook around. */ const dressed = new WeakSet(); @@ -106,7 +110,13 @@ export class AgilityApiClient { readonly transport: Transport; readonly schema: Schema; + /** + * A key the config or the options do not know is refused here with a + * UsageError naming it: a misspelt option is never ignored silently. + */ constructor(config: ClientConfig, opts: ClientOptions = {}) { + refuseUnknownKeys("the client's config", config, CLIENT_CONFIG_KEYS); + refuseUnknownKeys("the client's options", opts, CLIENT_OPTION_KEYS); // The built-in transport times its attempts and resends idempotent requests itself (it can read Retry-After); a // custom one gets the same two rules from the client. A transport another client of ours already dressed (withSignal) is taken as it is. let transport = opts.transport ?? createFetchTransport({ @@ -118,11 +128,14 @@ export class AgilityApiClient { defaultHeaders: config.defaultHeaders, credentials: config.credentials, onUnauthorized: config.onUnauthorized, - unauthorizedStatuses: config.unauthorizedStatuses + unauthorizedStatuses: config.unauthorizedStatuses, + fetchImpl: config.fetchImpl }); if (!dressed.has(transport)) { - // A custom transport: each attempt under the client's deadline, and the resend rule around that. - if (opts.transport) transport = withRetry(withTimeout(transport, config.timeoutMs ?? DEFAULT_TIMEOUT_MS), config.retries ?? 1); + // A custom transport: each attempt under the client's deadline, and the resend rule around that. The built-in + // transport applies both itself, also when it was made by the caller and handed in: wrapping it again would + // send a failed read four times instead of two. + if (!governsItself(transport)) transport = withRetry(withTimeout(transport, config.timeoutMs ?? DEFAULT_TIMEOUT_MS), config.retries ?? 1); // Every error says what was asked (so an explanation can tell a failed read from a write whose fate is unknown). transport = withRequestStamp(transport); if (config.onError) transport = withErrorHook(transport, config.onError); @@ -363,6 +376,27 @@ export class AgilityApiClient { visibleByAsset: (oid: Oid) => fields.visibleFieldsByAsset(this.transport, oid) }; + /** + * Which values a list-typed attribute (Status, Priority, a custom + * dropdown) may take: for an existing asset (`{ asset }`: its own scope + * and team apply, a team with its own process included) or for one not + * created yet (`{ type, scope, team? }`). The scope's scheme and the + * team's process decide, as in the product's own pickers; the server + * itself enforces less on a write (it accepts a status outside the + * scope's scheme), so resolve a name here before writing it. + * `values` answers a map from attribute to rows `{ _oid, Name }` in the + * list's order, one request per attribute; `value` answers the one + * value a name (or an OID) means there, or throws NO_SUCH_VALUE / + * AMBIGUOUS_VALUE with the candidates as rows in `details.values`. + * Only relations to a list type: the endpoint cannot be paged, so for + * Owners, Team or Timebox use `client.query` on the related type with a + * filter and a page. + */ + readonly lists = { + values: (input: listsService.ValuesInput) => listsService.values(this.transport, this.schema, input), + value: (input: listsService.ValueInput) => listsService.value(this.transport, this.schema, input) + }; + // ---- writes ----------------------------------------------------------------------- /** diff --git a/src/core/clientConfig.ts b/src/core/clientConfig.ts index 35562ad..8f3d78d 100644 --- a/src/core/clientConfig.ts +++ b/src/core/clientConfig.ts @@ -1,7 +1,14 @@ import type { ApiError } from "./errors"; import type { FetchTransportConfig } from "./fetchTransport"; +import { keysOf } from "./knownKeys"; import type { RequestOptions } from "./transport"; +/** + * What a client is built from. A key that is not one of these is refused + * when the client is constructed (a UsageError naming the key, with the + * nearest known one when it looks like a typo): a misspelt option is + * never ignored silently. + */ export interface ClientConfig extends Pick { /** * The instance base URL: "https://agility.example.com/MyInstance". The @@ -17,9 +24,17 @@ export interface ClientConfig extends Pick". */ accessToken?: string; + /** + * The `fetch` the built-in transport calls, when it should not be the + * global one (a proxy-aware fetch, a recording one in a test). Not used + * when the client is given a transport of its own. + */ + fetchImpl?: typeof fetch; /** * How long one attempt may take, in milliseconds, whichever Transport - * the client has. Default 60000. When it has passed, the request + * the client has (one exception: a transport you made yourself with + * `createFetchTransport` and handed in keeps its own `timeoutMs` and + * `retries`, since it applies both rules itself). Default 60000. When it has passed, the request * rejects with an ApiError coded TIMEOUT. It is NOT sent again, a read * included: a timeout (like an abort) ends the client's wait and does * not stop the work on the server, so a query that timed out may still @@ -62,3 +77,6 @@ export interface ClientConfig extends Pick void; } + +/** Every key of ClientConfig. A key added to the type and not here, or here and not in the type, does not compile. */ +export const CLIENT_CONFIG_KEYS = keysOf()({ baseUrl: true, authorization: true, accessToken: true, fetchImpl: true, timeoutMs: true, retries: true, defaultHeaders: true, onError: true, credentials: true, onUnauthorized: true, unauthorizedStatuses: true }); diff --git a/src/core/errors.ts b/src/core/errors.ts index 1203ff0..c0547f9 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -32,6 +32,8 @@ export function kindOf(status: number, code?: string): ErrorKind { case "COMMAND_FAILURE": return "commandFailure"; case "CONFLICT": return "conflict"; case "RECEIPT_VERSION": return "usage"; + case "NO_SUCH_VALUE": + case "AMBIGUOUS_VALUE": case "QUERY_REJECTED": case "TOO_LARGE": return "invalid"; case "NOT_FOUND": return "notFound"; diff --git a/src/core/fetchTransport.ts b/src/core/fetchTransport.ts index 48f5204..b27e562 100644 --- a/src/core/fetchTransport.ts +++ b/src/core/fetchTransport.ts @@ -1,5 +1,6 @@ import { ApiError, apiErrorFromResponse } from "./errors"; -import { DEFAULT_TIMEOUT_MS, deadline, resendable } from "./retry"; +import { keysOf, refuseUnknownKeys } from "./knownKeys"; +import { DEFAULT_TIMEOUT_MS, deadline, declareSelfGoverned, resendable } from "./retry"; import type { RequestBody, RequestOptions, ResponseType, Transport } from "./transport"; /** @@ -79,15 +80,19 @@ export interface FetchTransportConfig { * `unauthorizedStatuses` means nothing in the request was * executed — the sign-in was checked before any command * ran — so sending it again cannot apply anything twice. - * What is known: on one product release, an api/asset - * create sent with no session and one sent with an - * invalid session were each answered 401 with an empty - * body before any command ran, and nothing was created - * (a consumer's check, by an exact-name query afterwards). - * What is not: a session that was valid and has expired, - * a 403, and rest-1. The SDK's own tests run where every + * What is known, from a consumer's checks on one product + * release: an api/asset create sent with no session, + * with an invalid one, and with a credential that had + * been valid and expired was each answered 401 before + * any command ran, and nothing was created (checked by + * an exact-name query afterwards); with the expired + * credential a rest-1 attribute write was refused the + * same way and not applied, and a query.v1 read got the + * same 401. No 403 and no redirect was seen. What is + * not known: a 403, other releases, and other ways of + * signing in. The SDK's own tests run where every * request is authenticated and check none of it, so - * beyond that case it remains your assertion. Answer it + * beyond those cases it remains your assertion. Answer it * only where it holds (a missing or lapsed sign-in; not a * permission problem, which api/asset reports per command * inside a 200). Honoured once per request, like "retry". @@ -171,13 +176,21 @@ function retryDelay(response: { status: number; headers: { get(name: string): st return 150 * (attempt + 1); } +/** Every key of FetchTransportConfig. A key added to the type and not here, or here and not in the type, does not compile. */ +export const FETCH_TRANSPORT_CONFIG_KEYS = keysOf()({ baseUrl: true, authorization: true, accessToken: true, defaultHeaders: true, timeoutMs: true, retries: true, fetchImpl: true, credentials: true, onUnauthorized: true, unauthorizedStatuses: true }); + +/** + * The built-in transport. A config with a key it does not know is refused + * here with a UsageError naming the key: nothing is ignored silently. + */ export function createFetchTransport(config: FetchTransportConfig): Transport { + refuseUnknownKeys("createFetchTransport's config", config, FETCH_TRANSPORT_CONFIG_KEYS); const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS; const retries = Math.max(0, config.retries ?? 1); const authorization = config.authorization ?? (config.accessToken ? `Bearer ${config.accessToken}` : undefined); const unauthorizedStatuses = config.unauthorizedStatuses ?? [401]; - return { + return declareSelfGoverned({ async request(options: RequestOptions): Promise { const url = buildUrl(config.baseUrl, options.path, options.query); const { body, contentType } = encodeBody(options.body, options.contentType); @@ -263,5 +276,5 @@ export function createFetchTransport(config: FetchTransportConfig): Transport { } throw lastError instanceof ApiError ? lastError : new ApiError("Unknown transport error", 0, "UNKNOWN_ERROR", { cause: lastError }); } - }; + }); } diff --git a/src/core/knownKeys.ts b/src/core/knownKeys.ts new file mode 100644 index 0000000..c30e400 --- /dev/null +++ b/src/core/knownKeys.ts @@ -0,0 +1,39 @@ +import { UsageError } from "./errors"; + +/** Edit distance between two short names, for "did you mean". */ +function distance(a: string, b: string): number { + let row = Array.from({ length: b.length + 1 }, (_, j) => j); + for (let i = 1; i <= a.length; i += 1) { + const next = [i]; + for (let j = 1; j <= b.length; j += 1) next[j] = Math.min(next[j - 1]! + 1, row[j]! + 1, row[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1)); + row = next; + } + return row[b.length]!; +} + +/** The known key nearest to a mistyped one, when one is close: the same but for case, or one or two edits away. */ +function nearest(key: string, known: readonly string[]): string | null { + const exact = known.find((k) => k.toLowerCase() === key.toLowerCase()); + if (exact) return exact; + const [best] = known.map((k) => [k, distance(key.toLowerCase(), k.toLowerCase())] as const).filter(([k, d]) => d <= 2 && d < Math.max(k.length, key.length) / 2).sort((x, y) => x[1] - y[1]); + return best ? best[0] : null; +} + +/** + * A config object with a key its factory does not know is a mistake in the + * call, and is refused when the object is handed over: a misspelt or + * misplaced option that is quietly ignored leaves a caller believing it + * was applied. The name is the mistake, so a key is refused whatever its + * value, `undefined` included. The message names the keys and never a + * value: a config holds credentials. + */ +export function refuseUnknownKeys(what: string, config: unknown, known: readonly string[]): void { + if (config === null || typeof config !== "object" || Array.isArray(config)) throw new UsageError(`${what} must be an object`); + const unknown = Object.keys(config).filter((key) => !known.includes(key)); + if (!unknown.length) return; + const said = unknown.map((key) => { const near = nearest(key, known); return near ? `"${key}" (did you mean "${near}"?)` : `"${key}"`; }); + throw new UsageError(`${what}: unknown key${unknown.length > 1 ? "s" : ""} ${said.join(", ")}. It takes: ${known.join(", ")}`, { unknown, known: [...known] }); +} + +/** The names of a config type's keys, as a list that cannot drift from the type: a key missing here or extra here does not compile. */ +export const keysOf = () => >(keys: K & Record, never>): readonly (keyof T & string)[] => Object.keys(keys) as (keyof T & string)[]; diff --git a/src/core/retry.ts b/src/core/retry.ts index f71813b..37be61a 100644 --- a/src/core/retry.ts +++ b/src/core/retry.ts @@ -91,6 +91,17 @@ export function resendable(error: unknown): boolean { return error instanceof ApiError && error.kind === "transient" && error.code !== "TIMEOUT" && error.code !== "SERVER_TIMEOUT" && error.status !== 408 && error.status !== 504; } +const selfGoverned = new WeakSet(); +/** A transport declares that it times its own attempts and applies the resend rule itself. The built-in fetch transport does. */ +export function declareSelfGoverned(transport: T): T { selfGoverned.add(transport); return transport; } +/** + * Does this transport time its attempts and resend by the rule itself? + * Then the client adds neither: a rule applied twice is a request sent + * four times. True only of the very object `createFetchTransport` + * returned; a wrapper around it is a custom transport like any other. + */ +export function governsItself(transport: Transport): boolean { return selfGoverned.has(transport); } + /** * The resend rule, for any Transport: an idempotent request (a GET, or one * the caller marked: a query.v1 read; never a write, guarded or not) @@ -106,7 +117,8 @@ export function resendable(error: unknown): boolean { * rule, so each attempt has its own deadline), so the rule is the client's * and not each transport's to re-implement. The built-in fetch transport * applies the same rule itself (it can also read Retry-After) and is not - * wrapped again. + * wrapped again, whether the client made it or was handed it: the + * transport says so itself (`governsItself`). */ export function withRetry(transport: Transport, retries: number): Transport { const extra = Math.max(0, retries); diff --git a/src/index.ts b/src/index.ts index 5de2f39..f8e963f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -29,6 +29,7 @@ export type { Localizations, LocalizeOptions } from "./wire/loc2"; export type { ConditionalOptions, MetamodelDocument, Tagged } from "./wire/meta"; export type { QueryRejection } from "./wire/queryV1"; export type { FieldsOf } from "./services/fields"; +export type { ListTarget, ListValue, ValueInput, ValuesInput } from "./services/lists"; export { importantName } from "./services/fields"; // The wire modules themselves (assetApi, queryV1, rest1, meta, loc2, attachment, fields, select) and the // endpoints' envelope types are at "@versionone/agility-sdk/wire". diff --git a/src/services/fields.ts b/src/services/fields.ts index 9163dcb..2287278 100644 --- a/src/services/fields.ts +++ b/src/services/fields.ts @@ -16,6 +16,7 @@ import type { AssetTypeToken } from "../types/metamodel"; import { momentless } from "../types/oid"; import * as assetApi from "../wire/assetApi"; import * as fields from "../wire/fields"; +import { listTypeOf } from "./lists"; import type { Schema } from "./schema"; export interface FieldsOf { @@ -31,6 +32,13 @@ export interface FieldsOf { important: string[]; /** Whether the scheme enforces its important fields when an asset is closed. */ requiredAtClose: boolean; + /** + * Which of the attributes above (required, visible or important) are + * list-typed, and the list type each points to: `{ Status: + * "StoryStatus", Priority: "WorkitemPriority" }`. These are the + * attributes `client.lists.values` answers for. + */ + lists: Record; } type SchemeRow = Asset & { Scheme?: (Ref & { ImportantFields?: unknown; IsRequiredAtClose?: unknown }) | null }; @@ -70,6 +78,13 @@ export async function describe(transport: Transport, schema: Schema, type: Asset const scheme = row?.Scheme ?? null; const tokens = Array.isArray(scheme?.ImportantFields) ? scheme.ImportantFields.filter((t): t is string => typeof t === "string") : []; const important = [...new Set(tokens.map((t) => importantName(t, types)).filter((n): n is string => !!n))].sort(); + const lists: Record = {}; + for (const name of [...new Set([...required, ...(visible[type] ?? []), ...important])].sort()) { + // Only a relation can be list-typed; the related type is loaded only for those. + if (definition && schema.attribute(type, name)?.AttributeType !== "Relation") continue; + const listType = await listTypeOf(schema, type, name); + if (listType) lists[name] = listType; + } return { type, scope: scopeOid, @@ -77,6 +92,7 @@ export async function describe(transport: Transport, schema: Schema, type: Asset required, visible: visible[type] ?? [], important, - requiredAtClose: scheme?.IsRequiredAtClose === true + requiredAtClose: scheme?.IsRequiredAtClose === true, + lists }; } diff --git a/src/services/index.ts b/src/services/index.ts index b51287d..ad23da0 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -11,6 +11,7 @@ export * as batch from "./batch"; export * as explain from "./explain"; export * as fields from "./fields"; export * as guard from "./guard"; +export * as lists from "./lists"; export * as resolve from "./resolve"; export * as schema from "./schema"; export * as search from "./search"; diff --git a/src/services/lists.ts b/src/services/lists.ts new file mode 100644 index 0000000..7f8e6fe --- /dev/null +++ b/src/services/lists.ts @@ -0,0 +1,164 @@ +/** + * The lists service: which values a list-typed attribute (Status, + * Priority, Source, Category, a custom dropdown) may take for an asset, + * or for one about to be created in a scope, and the one value a name + * means there. Over api/ValidValues (wire/validValues), which applies the + * scope's scheme and the team's process; what it answers is in that + * module's header. + * + * ONLY RELATIONS TO A LIST TYPE. The endpoint takes no page and no + * filter, and answers for any attribute: asked for a relation to members + * or iterations it returns every one in the scope, unbounded. A list type + * (one that descends from List) is short by nature, so that is all this + * service asks for; anything else is a UsageError naming the read to use + * instead. No read in this SDK is unbounded (spec 000 section 6). + * + * There is no fallback. On an instance without the endpoint the call + * fails as the server's 404; it does not quietly offer every value of the + * list type, which is a different answer. + */ +import { ApiError, UsageError } from "../core/errors"; +import type { Transport } from "../core/transport"; +import type { Asset, Oid } from "../types/asset"; +import type { AssetTypeToken } from "../types/metamodel"; +import { momentless } from "../types/oid"; +import * as validValues from "../wire/validValues"; +import type { Schema } from "./schema"; + +/** Where the values are asked for: an existing asset (its own scope and team apply), or a type in a scope for one not created yet. */ +export type ListTarget = + | { asset: Oid; /** Answer as if the asset were on this team. */ team?: Oid } + | { type: AssetTypeToken; scope: Oid; /** The team the new asset will be on. */ team?: Oid }; + +/** A valid value: the list entry's identity and name, and whatever else was selected. Values are as rest-1 sends them. */ +export type ListValue = Asset & { Name: string } & Record; + +export type ValuesInput = ListTarget & { + /** List-typed attributes of the asset's type, by bare name. One request each, sent one after another. */ + attributes: readonly string[]; + /** More attributes of each value (`Order`, `RollupState`). `Name` is always returned. Not a date, and not a path through a relation. */ + select?: readonly string[]; +}; + +export type ValueInput = ListTarget & { + attribute: string; + /** The value's Name as a person would type it, or its OID. */ + name: string; + /** + * "exact" (the default): the whole Name, ignoring case and surrounding + * space. "prefix": also a Name of which the text begins a word ("prog" + * finds "In Progress"), used only when no Name matches exactly; more + * than one such Name is AMBIGUOUS_VALUE, never a silent choice. + */ + match?: "exact" | "prefix"; + select?: readonly string[]; +}; + +const typeOf = (target: ListTarget): AssetTypeToken => ("asset" in target ? momentless(target.asset).split(":")[0]! : target.type); + +/** + * Does `type` descend from List (or is it List)? By the schema, loading + * ancestors as needed (StoryStatus → Status → List: up to two more type + * loads on a cold cache). A type in the chain that cannot be loaded is an + * error of its own: "not a list" would be a guess, and the advice that + * goes with it would be wrong. + */ +async function isListType(schema: Schema, type: AssetTypeToken): Promise { + const seen = new Set(); + for (let t: AssetTypeToken | undefined = type; t && !seen.has(t); ) { + if (t === "List") return true; + seen.add(t); + const loaded = await schema.load(t); + if (!loaded) throw new ApiError(`could not load the asset type ${t} to tell whether ${type} is a list type`, 404, "NOT_FOUND", { type: t }); + t = loaded.Base; + } + return false; +} + +/** + * The list type an attribute points to, or null when it is not a relation + * to a list type; undefined when the type has no such attribute. + */ +export async function listTypeOf(schema: Schema, type: AssetTypeToken, attribute: string): Promise { + if (!(await schema.load(type))) return undefined; + const definition = schema.attribute(type, attribute); + if (!definition) return undefined; + if (definition.AttributeType !== "Relation" || !definition.RelatedAsset) return null; + return (await isListType(schema, definition.RelatedAsset)) ? definition.RelatedAsset : null; +} + +/** The list type of each attribute, each checked before anything is sent. */ +async function checked(schema: Schema, target: ListTarget, attributes: readonly string[], select: readonly string[] | undefined, what: string): Promise { + const type = typeOf(target); + if ("asset" in target ? !/^[A-Za-z]\w*:\d+(:\d+)?$/.test(target.asset) : !target.type || !target.scope) throw new UsageError(`${what}: give an asset's OID, or a type and a scope`); + if (!attributes.length) throw new UsageError(`${what}: no attribute named`); + for (const attribute of attributes) { + const listType = await listTypeOf(schema, type, attribute); + if (listType === undefined) throw new UsageError(`${what}: ${type} has no attribute ${attribute}`); + if (listType === null) { + const related = schema.attribute(type, attribute)?.RelatedAsset; + throw new UsageError(related + ? `${what}: ${type}.${attribute} points to ${related}, which is not a list type. The server's valid-values endpoint cannot be paged or filtered and would return every ${related} in the scope. Read them with client.query({ from: "${related}", filter, page }) instead` + : `${what}: ${type}.${attribute} is not a relation, so it has no list of valid values`); + } + for (const path of select ?? []) { + if (path.includes(".")) throw new UsageError(`${what}: select takes attributes of the value itself, not a path (${path})`); + await schema.load(listType); + const selected = schema.attribute(listType, path); + if (!selected) throw new UsageError(`${what}: ${listType} has no attribute ${path}`); + if (selected.AttributeType === "Date") throw new UsageError(`${what}: ${listType}.${path} is a date, which this endpoint writes in the server's culture format, not ISO. Read it with client.query`); + } + } +} + +const paramsOf = (target: ListTarget, select: readonly string[] | undefined): validValues.ValidValuesParams => ({ select: ["Name", ...(select ?? []).filter((s) => s !== "Name")], sort: ["Order"], team: target.team }); + +const read = (transport: Transport, target: ListTarget, attribute: string, select: readonly string[] | undefined): Promise => + "asset" in target + ? validValues.forAsset(transport, target.asset, attribute, paramsOf(target, select)) + : validValues.forNew(transport, target.type, attribute, target.scope, paramsOf(target, select)); + +/** + * The values each attribute may take there, in the list's own order: a map + * from attribute name to rows `{ _oid, Name, …selected }`. An attribute + * with no valid value there maps to `[]` (the scope's scheme selects none, + * which is a real answer). One request per attribute, one after another. + */ +export async function values(transport: Transport, schema: Schema, input: ValuesInput): Promise> { + await checked(schema, input, input.attributes, input.select, "lists.values"); + const out: Record = {}; + for (const attribute of input.attributes) out[attribute] = await read(transport, input, attribute, input.select); + return out; +} + +const fold = (text: string): string => text.trim().toLocaleLowerCase(); +const named = (rows: readonly ListValue[]): string => rows.map((r) => r.Name).join(", "); + +/** + * The one valid value a name means there. `name` may be an OID, which is + * then checked to be among the valid values. No such value is an ApiError + * coded NO_SUCH_VALUE; more than one is AMBIGUOUS_VALUE. Both carry + * `details: { attribute, name, values }`, the candidates as rows (all the + * valid values, or the ones that matched), so a caller can offer them. + * + * This is the check to make before writing a name a person gave. On a + * write the server enforces a team's process (a status outside it is the + * command failure `Violation'PrimaryWorkitemCannotHaveInvalidStatus`) and + * does not enforce a scheme's selection (a status the scope's scheme does + * not select is accepted, with no violation). + */ +export async function value(transport: Transport, schema: Schema, input: ValueInput): Promise { + await checked(schema, input, [input.attribute], input.select, "lists.value"); + if (typeof input.name !== "string" || !input.name.trim()) throw new UsageError("lists.value: no name given"); + const all = await read(transport, input, input.attribute, input.select); + const wanted = fold(input.name); + const isOid = /^[A-Za-z]\w*:\d+(:\d+)?$/.test(input.name.trim()); + let found = isOid ? all.filter((r) => r._oid === momentless(input.name.trim() as Oid)) : all.filter((r) => fold(String(r.Name)) === wanted); + if (!found.length && !isOid && input.match === "prefix") found = all.filter((r) => fold(String(r.Name)).split(/\s+/).some((word, i, words) => words.slice(i).join(" ").startsWith(wanted))); + if (found.length === 1) return found[0]!; + const type = typeOf(input); + if (!found.length) { + throw new ApiError(`${type}.${input.attribute} has no value "${input.name.trim()}" here. ${all.length ? `It can be: ${named(all)}.` : "No value is valid here."}`, 0, "NO_SUCH_VALUE", { attribute: input.attribute, name: input.name, values: all }); + } + throw new ApiError(`${type}.${input.attribute}: "${input.name.trim()}" matches more than one value here: ${named(found)}.`, 0, "AMBIGUOUS_VALUE", { attribute: input.attribute, name: input.name, values: found }); +} diff --git a/src/testing/index.ts b/src/testing/index.ts index ec1a508..ef4e77c 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -19,6 +19,8 @@ export { CONFORMANCE_BASE_URL, fetchFrom, transportConformance } from "./transpo export type { ConformanceCheck, ConformanceRequest, ConformanceResponse, ConformanceServer } from "./transportConformance"; import type { ClientConfig } from "../core/clientConfig"; import type { SearchOptions, SearchResult, SearchRow } from "../services/search"; +import * as listsService from "../services/lists"; +import type { ValueInput, ValuesInput } from "../services/lists"; import { ATTRIBUTE_NAMES, CONCRETE_SUBTYPES } from "../types/assets/subtypes"; import { ApiError, UsageError, apiErrorFromResponse } from "../core/errors"; import type { RequestOptions, Transport } from "../core/transport"; @@ -58,10 +60,15 @@ const typeOfFrom = (from: string): string => (isOidToken(from) ? typeOfOid(from) /** What a scripted search answers: rows (the whole result, paged by the fake), a function of the text and options answering one page, or an Error to throw. */ type SearchAnswer = FakeRows | Error | ((text: string, options: SearchOptions) => FakeRows); +/** What `client.lists` asked the fake: the type and attribute, and the asset or the scope (and team) it asked for. */ +export interface ValuesAsked { type: string; attribute: string; asset?: Oid; scope?: Oid; team?: Oid } +type ValuesAnswer = Record readonly FakeRow[])>; type ListMatch = string | ((type: string, params: Record) => boolean); interface Script { searches: SearchAnswer[]; + /** Valid values scripted with onValues, by attribute name; the one scripted last wins. */ + values: ValuesAnswer; /** The options of the search the fake's own client is making right now, for the record. */ searching: SearchOptions | null; lists: { match: ListMatch; answer: FakeRows | Error | ((type: string, params: Record) => FakeRows) }[]; @@ -70,7 +77,7 @@ interface Script { sends: SendAnswer[]; requests: { match: RequestMatch; answer: RequestAnswer }[]; labels: Record; - seen: { requests: RequestOptions[]; asked: QueryBody[]; sent: Command[][]; searched: { text: string; options: SearchOptions }[] }; + seen: { requests: RequestOptions[]; asked: QueryBody[]; sent: Command[][]; searched: { text: string; options: SearchOptions }[]; valuesAsked: ValuesAsked[] }; nextId: number; /** The fake's versions: each asset's moment (1 until something writes it), and the assets that are gone. */ moments: Map; @@ -181,8 +188,11 @@ function answerSend(script: Script, commands: Command[], writes: { body: Command function anyType(script: Script, token: string): unknown { const scripted = script.searches.flatMap((answer) => (Array.isArray(answer) ? answer : answer && typeof answer === "object" && "rows" in answer ? answer.rows : []) as readonly FakeRow[]).flatMap((row) => Object.keys(row)); const root = ["Name", "Description", "AssetType", "AssetState", "ChangeDateUTC", "CreateDateUTC"]; - const names = token === "BaseAsset" ? root : [...new Set([...ATTRIBUTE_NAMES, ...scripted.map((key) => key.split(".")[0]!)])].filter((name) => name !== "_oid"); - const Attributes = Object.fromEntries(names.map((Name) => [`${token}.${Name}`, { _type: "AttributeDefinition", Name, Token: `${token}.${Name}`, DisplayName: Name, AttributeType: "Text", IsReadOnly: false, IsRequired: false, IsMultivalue: false, IsCanned: true, IsCustom: false }])); + // What onValues scripted: its attributes are relations to a list type, and its rows' keys are attributes of that type. + const listed = Object.keys(script.values); + const valueKeys = Object.values(script.values).flatMap((answer) => (Array.isArray(answer) ? (answer as readonly FakeRow[]).flatMap((row) => Object.keys(row)) : [])); + const names = token === "BaseAsset" ? root : [...new Set([...ATTRIBUTE_NAMES, ...scripted.map((key) => key.split(".")[0]!), ...listed, ...valueKeys])].filter((name) => name !== "_oid"); + const Attributes = Object.fromEntries(names.map((Name) => [`${token}.${Name}`, { _type: "AttributeDefinition", Name, Token: `${token}.${Name}`, DisplayName: Name, AttributeType: "Text", IsReadOnly: false, IsRequired: false, IsMultivalue: false, IsCanned: true, IsCustom: false, ...(listed.includes(Name) && token !== "List" ? { AttributeType: "Relation", RelatedAsset: { nameref: "List", href: "/meta.v1/List" } } : {}) }])); // A family the generated table knows (Workitem) is abstract here as on a server, so a search naming it expands to its subtypes. return { _type: "AssetType", Name: token, Token: token, DisplayName: token, Abstract: token === "BaseAsset" || token in CONCRETE_SUBTYPES, ...(token === "BaseAsset" ? {} : { Base: { nameref: "BaseAsset", href: "/meta.v1/BaseAsset" } }), Attributes }; } @@ -199,7 +209,7 @@ function respond(script: Script, request: RequestOptions): unknown { request.onResponse?.({ status: 200, headers: { get: () => null } }); return found; } - if (!raw && request.method === "GET" && request.path.startsWith("/meta.v1/") && script.searches.length && !request.path.slice("/meta.v1/".length).includes("/")) { + if (!raw && request.method === "GET" && request.path.startsWith("/meta.v1/") && (script.searches.length || Object.keys(script.values).length) && !request.path.slice("/meta.v1/".length).includes("/")) { // A search asks the schema which searched type has which attribute. With a search scripted and no metamodel, the fake's // instance has whatever type is asked for, with every attribute a scripted row could carry, so the rows come back as scripted. request.onResponse?.({ status: 200, headers: { get: () => null } }); @@ -216,6 +226,25 @@ function respond(script: Script, request: RequestOptions): unknown { const encoded = request.method === "GET" ? request.path.slice(request.path.indexOf("?") + 1) : String(request.body); return Object.fromEntries((JSON.parse(decodeURIComponent(encoded)) as string[]).map((tag) => [tag, script.labels[tag] ?? tag])); } + if (request.method === "GET" && request.path.startsWith("/api/ValidValues/")) { + // Both forms of the endpoint: ./?context=Scope=…[,Team=…] and //[?teamoid=…]. + const [path, query = ""] = request.path.slice("/api/ValidValues/".length).split("?"); + const params = new Map(query.split("&").filter(Boolean).map((pair) => { const at = pair.indexOf("="); return [pair.slice(0, at), decodeURIComponent(pair.slice(at + 1))] as const; })); + const parts = path!.split("/").filter(Boolean).map(decodeURIComponent); + const context = new Map((params.get("context") ?? "").split(",").filter(Boolean).map((term) => { const at = term.indexOf("="); return [term.slice(0, at), term.slice(at + 1)] as const; })); + const asked: ValuesAsked = parts.length === 3 + ? { type: parts[0]!, attribute: parts[2]!, asset: `${parts[0]}:${parts[1]}`, ...(params.get("teamoid") ? { team: params.get("teamoid")! } : {}) } + : { type: parts[0]!.split(".")[0]!, attribute: parts[0]!.split(".")[1]!, ...(context.get("Scope") ? { scope: context.get("Scope")! } : {}), ...(context.get("Team") ? { team: context.get("Team")! } : {}) }; + script.seen.valuesAsked.push(asked); + const answer = script.values[asked.attribute]; + if (answer === undefined) throw new UsageError(`FakeAgilityClient: no valid values scripted for ${asked.type}.${asked.attribute}; script them with onValues({ ${asked.attribute}: [...] })`); + if (answer instanceof Error) throw answer; + const rows = typeof answer === "function" ? answer(asked) : answer; + // As the endpoint answers: the selected attributes and no others, one the row does not carry as null. + const selected = (params.get("sel") ?? "").split(",").filter(Boolean); + const projected = selected.length ? rows.map((row) => ({ _oid: row._oid, ...Object.fromEntries(selected.map((name) => [name, (row as Record)[name] ?? null])) }) as FakeRow) : rows; + return { _type: "Assets", total: rows.length, pageSize: 2147483647, pageStart: 0, Assets: projected.map(toAssetDocument) }; + } if (request.method === "GET" && request.path.startsWith("/rest-1.v1/Data/") && !request.path.slice("/rest-1.v1/Data/".length).includes("/")) { const type = decodeURIComponent(request.path.slice("/rest-1.v1/Data/".length)); const params = (request.query ?? {}) as Record; @@ -416,10 +445,12 @@ export class FakeAgilityClient extends AgilityApiClient { * client asked (its filter, its sort), read the request in `requests`. */ readonly searched: { text: string; options: SearchOptions }[]; + /** Every request for valid values (`client.lists.values` / `lists.value`), in order: one per attribute asked. */ + readonly valuesAsked: ValuesAsked[]; private readonly script: Script; constructor(config: Partial & FakeOptions = {}) { - const script: Script = { lists: [], metamodel: config.metamodel ?? null, queries: [], sends: [], requests: [], labels: {}, seen: { requests: [], asked: [], sent: [], searched: [] }, searches: [], searching: null, nextId: 1000, moments: new Map(), gone: new Set(), known: new Set() }; + const script: Script = { lists: [], metamodel: config.metamodel ?? null, queries: [], sends: [], requests: [], labels: {}, seen: { requests: [], asked: [], sent: [], searched: [], valuesAsked: [] }, values: {}, searches: [], searching: null, nextId: 1000, moments: new Map(), gone: new Set(), known: new Set() }; const transport: Transport = { // Answers are computed synchronously and delivered as a real response would be: later, and a throw as a rejection. request: async (request: RequestOptions): Promise => { @@ -436,6 +467,7 @@ export class FakeAgilityClient extends AgilityApiClient { this.asked = script.seen.asked; this.sent = script.seen.sent; this.searched = script.seen.searched; + this.valuesAsked = script.seen.valuesAsked; } /** @@ -467,6 +499,46 @@ export class FakeAgilityClient extends AgilityApiClient { return this; } + /** + * Script what `client.lists.values` and `lists.value` answer: for each + * attribute, the valid values as rows in the model's shape (`{ _oid, + * Name, … }`, in the order to return them), a function of what was + * asked (the asset, or the scope and team) answering the rows, or an + * Error to throw. Calls add up by attribute; the answer scripted last + * for an attribute wins. No scheme or team process is evaluated: the + * rows scripted are the valid values. The lookup itself is the client's + * own, so name matching, NO_SUCH_VALUE and AMBIGUOUS_VALUE behave as + * they do live, also for a client built on `fake.transport`. Without a + * `metamodel` the fake's instance treats each scripted attribute as a + * relation to a list type on whatever asset type asks; with one, the + * metamodel decides, as a server's does. What was asked is in + * `valuesAsked`. + */ + onValues(answer: ValuesAnswer): this { + Object.assign(this.script.values, answer); + return this; + } + + /** + * `client.lists` on the fake. Without a metamodel the fake cannot know + * what an attribute nobody scripted is (a list, a relation to members, + * a text), so it says that, rather than refuse in words a server's + * metamodel would not produce. With a metamodel the client's own checks + * run as they do live. + */ + override readonly lists = (() => { + const scripted = (what: string, input: { asset?: string; type?: string }, attributes: readonly string[]) => { + if (this.script.metamodel) return; + const missing = attributes.find((a) => !(a in this.script.values)); + const type = input.asset ? input.asset.split(":")[0] : input.type; + if (missing !== undefined) throw new UsageError(`FakeAgilityClient: no valid values scripted for ${type}.${missing} (${what}); script them with onValues({ ${missing}: [...] }). To test what the client refuses (an attribute that is not a list), give the fake a metamodel: without one it does not know what ${missing} is`); + }; + return { + values: async (input: ValuesInput) => { scripted("lists.values", input, input.attributes ?? []); return listsService.values(this.transport, this.schema, input); }, + value: async (input: ValueInput) => { scripted("lists.value", input, [input.attribute]); return listsService.value(this.transport, this.schema, input); } + }; + })(); + /** * Script what a search answers: rows in the model's shape (a list is * the whole result: the fake pages it and reports its length as the diff --git a/src/testing/transportConformance.ts b/src/testing/transportConformance.ts index 01d8891..d80e00e 100644 --- a/src/testing/transportConformance.ts +++ b/src/testing/transportConformance.ts @@ -160,6 +160,9 @@ export function transportConformance(make: (server: ConformanceServer) => Transp [401, "Unauthorized"], // As api/asset refuses a request with no session: a 401 with nothing in the body. The status alone makes it kind "auth". [401, ""], + // As query.v1 and rest-1 refuse an expired credential: a 401 with a body. Still kind "auth". + [401, { error: "Unauthorized" }], + [401, { _type: "Error", error: "Unauthorized" }], [503, ""] ]; for (const [status, data] of bodies) { diff --git a/src/wire/index.ts b/src/wire/index.ts index 1b507a5..7ddcf56 100644 --- a/src/wire/index.ts +++ b/src/wire/index.ts @@ -11,6 +11,8 @@ export * as queryV1 from "./queryV1"; export * as attachment from "./attachment"; export * as select from "./select"; export * as fields from "./fields"; +export * as validValues from "./validValues"; export type { AssetDocument, AssetsDocument, ReadParams, ReadResult } from "./rest1"; export type { AssetApiResponse, Command, CommandBody, CommandValue, CreateBody, ExecuteBody, QueryBody, UpdateBody, CommandFailure, CommandError, OidTokens, ReadOptions, RowContext, SendOptions } from "./assetApi"; export type { Localizations, LocalizeOptions } from "./loc2"; +export type { ValidValuesParams } from "./validValues"; diff --git a/src/wire/validValues.ts b/src/wire/validValues.ts new file mode 100644 index 0000000..55451ab --- /dev/null +++ b/src/wire/validValues.ts @@ -0,0 +1,84 @@ +/** + * The valid-values wire module: which assets a relation may point to, for + * an asset or for an asset not yet created. One GET endpoint in two + * forms, both answering rest-1's Assets document. What the product's own + * pickers ask. Settled against the API-testing instance (2026-11-26, + * test/integration/lists.test.ts): + * + * api/ValidValues/./?context=Scope=[,Team=] + * For an asset that does not exist yet. The trailing slash is + * required. The context is ONE parameter; a scope and a team are + * joined by a comma (a semicolon, an encoded ampersand or a second + * `context` is a 400). `teamoid` is silently ignored in this form. + * api/ValidValues///[?teamoid=] + * For an existing asset, in its own scope and team. `teamoid` asks + * "and if it were on this team". + * Both take `sel` and `sort` as rest-1 does. A base type is accepted + * (`PrimaryWorkitem.Status`); an attribute the type does not have is a + * bare 400. + * + * What the answer means, for a List relation (Status, Priority, …): + * - the scope's Scheme decides: only the values selected in it; + * - a team that owns values of that list (a team with its own process: + * Team.HasProcess, true exactly when it owns a StoryStatus) replaces + * the scheme's with its own; a team that owns none changes nothing; + * - an inactive value is left out, and there is no "none" entry; + * - the order is the values' Order, which `sort=Order` asks for. + * The server enforces less on a write than this list says: a status + * outside a team's process is refused, but one outside the scope's scheme + * is accepted. The list is what a person should be offered. + * + * THE ENDPOINT CANNOT BE BOUNDED. It takes no page and no filter, and it + * answers for any attribute: a relation to members or iterations returns + * every one in the scope, and an attribute that is no relation at all + * (`Story.Name`) returned every distinct value on the instance. Nothing in + * this module stops that; the service above it (services/lists) asks only + * for relations to List types, which are short by nature. A caller of + * this module takes that care itself. + * + * Values arrive as rest-1 sends them, except that a date is written in + * the server's culture format, not ISO: do not select one. + */ +import { ApiError } from "../core/errors"; +import type { Transport } from "../core/transport"; +import type { Asset, Oid } from "../types/asset"; +import type { AssetTypeToken } from "../types/metamodel"; +import { momentless } from "../types/oid"; +import { rejected } from "./queryV1"; +import { fromAssetDocument, type AssetsDocument } from "./rest1"; + +export interface ValidValuesParams { + /** Attributes of the related asset to return. Without it the server chooses. */ + select?: readonly string[]; + /** Sort terms as rest-1 spells them (`Order`, `-Name`). */ + sort?: readonly string[]; + /** A team to answer for: the asset's own is used when it has one and this is not given. */ + team?: Oid; +} + +const list = (names: readonly string[]): string => names.map(encodeURIComponent).join(","); + +async function read(transport: Transport, path: string, extra: string[], params: ValidValuesParams): Promise { + // Built by hand: the context's `=` and `,` must arrive as they are, and the transport's query map would encode them. + const query = [...extra, params.select?.length ? `sel=${list(params.select)}` : "", params.sort?.length ? `sort=${list(params.sort)}` : ""].filter(Boolean).join("&"); + let doc: AssetsDocument; + try { + doc = await transport.request({ method: "GET", path: query ? `${path}?${query}` : path, headers: { accept: "application/json" }, responseType: "json" }); + } catch (error) { + throw error instanceof ApiError && error.status === 400 ? rejected(error) : error; + } + if (!doc || !Array.isArray(doc.Assets)) throw new ApiError("api/ValidValues did not answer a list of assets", 200, "BAD_RESPONSE", doc); + return doc.Assets.map((a) => fromAssetDocument(a, { select: params.select })); +} + +/** The assets `.` may point to for an asset of that type in `scope` (and on `team`) that does not exist yet. */ +export function forNew(transport: Transport, type: AssetTypeToken, attribute: string, scope: Oid, params: ValidValuesParams = {}): Promise { + const context = `Scope=${momentless(scope)}${params.team ? `,Team=${momentless(params.team)}` : ""}`; + return read(transport, `/api/ValidValues/${encodeURIComponent(type)}.${encodeURIComponent(attribute)}/`, [`context=${context}`], params); +} + +/** The assets an existing asset's `attribute` may point to, in its own scope and team (or on `team`, when given). */ +export function forAsset(transport: Transport, oid: Oid, attribute: string, params: ValidValuesParams = {}): Promise { + const [type, id] = momentless(oid).split(":"); + return read(transport, `/api/ValidValues/${encodeURIComponent(type!)}/${encodeURIComponent(id!)}/${encodeURIComponent(attribute)}`, params.team ? [`teamoid=${momentless(params.team)}`] : [], params); +} diff --git a/test/integration/instance.ts b/test/integration/instance.ts index ca5c560..2353086 100644 --- a/test/integration/instance.ts +++ b/test/integration/instance.ts @@ -10,6 +10,7 @@ import type { Transport } from "../../src/core/transport"; import { CommandFailureError, momentless, send, type AssetApiResponse } from "../../src/wire/assetApi"; import type { Command } from "../../src/types/command"; import { instance, type Instance } from "./instanceConfig"; +import { assertNotReference } from "./referenceData"; export { instance, type Instance }; @@ -33,9 +34,12 @@ export const fixtureName = (what: string): string => `sdk-integration ${what} ${ * if any is still there: a fixture left behind is a failure, not a shrug. * Agility refuses to delete a closed asset, so one that would not delete * is reactivated and deleted again. An asset already gone is fine (the - * server answers a command for it with success). + * server answers a command for it with success). Before anything is + * deleted the names are read: permanent reference data (named + * `sdk-reference …`) in the list stops the whole cleanup with an error. */ export async function deleteFixtures(transport: Transport, oids: readonly string[]): Promise { + await assertNotReference(transport, oids); const left: string[] = []; for (const oid of oids) { const first = await send(transport, [{ from: oid, execute: "Delete" }]); diff --git a/test/integration/lists.test.ts b/test/integration/lists.test.ts new file mode 100644 index 0000000..c669a7a --- /dev/null +++ b/test/integration/lists.test.ts @@ -0,0 +1,179 @@ +import { afterAll, beforeAll, expect, it } from "vitest"; +import { AgilityApiClient } from "../../src/client"; +import type { ApiError } from "../../src/core/errors"; +import { validValues } from "../../src/wire"; +import { deleteFixtures, describeInstance, fixtureName, instance, sendFixtures } from "./instance"; +import { reference, schemeStatuses } from "./referenceData"; + +/** + * Valid values against a real instance: what api/ValidValues answers for a + * list-typed attribute, and client.lists over it. The suite brings a whole + * small world of its own, so every expectation is exact, and touches + * nothing that exists: + * - a Scope under the system project with its own Scheme; + * - two global statuses, one selected in that Scheme and one in none; + * two priorities likewise; + * - a Team that owns three statuses (one of them inactivated), which + * gives it a process of its own, and a Team that owns none; + * - a Story on each team and one on no team. + * Each "these values" has a control beside it that must not appear. All + * of it is deleted by exact OID, dependents first, and the suite fails if + * any of it can still be read. The Scope lives for seconds and no member + * is assigned to it, so nothing can come to reference it as a default + * project; that is not checked. + */ +describeInstance("valid values (live)", () => { + const t = instance!.transport; + const client = new AgilityApiClient({ baseUrl: instance!.url }, { transport: t }); + const created: string[] = []; + const made: Record = {}; + /** A fixture's OID by the key it was made under. */ + const o = new Proxy(made, { get: (target, key) => { const oid = target[String(key)]; if (!oid) throw new Error(`no fixture ${String(key)}`); return oid; } }) as Record & { [key: string]: string }; + const make = async (commands: Record>) => { + const oids = (await sendFixtures(t, Object.values(commands) as never)).assetsCreated!.oidTokens; + Object.keys(commands).forEach((key, i) => { made[key] = oids[i]!; }); + created.push(...oids); + }; + const names = (rows: { Name: string }[]) => rows.map((r) => r.Name); + const n = (what: string) => fixtureName(`values ${what}`); + const label: Record = {}; + const named = (key: string, what: string) => (label[key] = n(what)); + + beforeAll(async () => { + await make({ team: { AssetType: "Team", Name: n("team with a process") }, plainTeam: { AssetType: "Team", Name: n("team without") }, scheme: { AssetType: "Scheme", Name: n("scheme"), IsRequiredAtClose: false } }); + await make({ scope: { AssetType: "Scope", Name: n("scope"), Parent: "Scope:0", Scheme: o["scheme"]!, BeginDate: "2026-01-01" } }); + await make({ + inScheme: { AssetType: "StoryStatus", Name: named("inScheme", "status in scheme"), RollupState: "Active", SelectedInSchemes: [o["scheme"]!] }, + notInScheme: { AssetType: "StoryStatus", Name: named("notInScheme", "status in no scheme"), RollupState: "Active" }, + teamFirst: { AssetType: "StoryStatus", Name: named("teamFirst", "team status first"), RollupState: "Active", Team: o["team"]! }, + teamSecond: { AssetType: "StoryStatus", Name: named("teamSecond", "team status second"), RollupState: "Closed", Team: o["team"]! }, + teamInactive: { AssetType: "StoryStatus", Name: named("teamInactive", "team status inactive"), RollupState: "Active", Team: o["team"]! }, + priority: { AssetType: "WorkitemPriority", Name: named("priority", "priority in scheme"), SelectedInSchemes: [o["scheme"]!] }, + otherPriority: { AssetType: "WorkitemPriority", Name: named("otherPriority", "priority in no scheme") } + }); + await client.send([{ from: o["teamInactive"]!, execute: "Inactivate" }], { throwOnFailure: true }); + await make({ + onTeam: { AssetType: "Story", Name: n("story on the team"), Scope: o["scope"]!, Team: o["team"]! }, + noTeam: { AssetType: "Story", Name: n("story on no team"), Scope: o["scope"]! }, + onPlainTeam: { AssetType: "Story", Name: n("story on the plain team"), Scope: o["scope"]!, Team: o["plainTeam"]! } + }); + }, 120_000); + + afterAll(async () => { + const rank = (oid: string) => ["Story", "StoryStatus", "WorkitemPriority", "Scope", "Scheme", "Team"].indexOf(oid.split(":")[0]!); + await deleteFixtures(t, [...created].sort((a, b) => rank(a) - rank(b))); + // Deleted means unreadable: a Delete that answered success and left the asset would be a leak. + for (const type of new Set(created.map((oid) => oid.split(":")[0]!))) { + const oids = created.filter((oid) => oid.startsWith(`${type}:`)); + const left = await client.query({ from: type, select: ["Name"], filter: ["ID=$oids"], with: { $oids: oids }, page: { size: oids.length, start: 0 } }); + if (left.length) throw new Error(`fixtures left behind: ${left.map((r) => r._oid).join(", ")}`); + } + }, 120_000); + + it("a team that owns a status has a process of its own; one that owns none has not", async () => { + const teams = await client.query<{ _oid: string; HasProcess: unknown }>({ from: "Team" as never, select: ["HasProcess"], filter: ["ID=$oids"], with: { $oids: [o["team"]!, o["plainTeam"]!] }, sort: ["ID"], page: { size: 2, start: 0 } }); + expect(teams.map((r) => [r._oid, String(r.HasProcess).toLowerCase()])).toEqual([[o["team"]!, "true"], [o["plainTeam"]!, "false"]]); + }); + + it("the scope's scheme decides: only the values selected in it, for Status and for Priority alike; a base type is a type", async () => { + const answer = await client.lists.values({ type: "Story", scope: o["scope"]!, attributes: ["Status", "Priority"] }); + expect(answer).toEqual({ Status: [{ _oid: o["inScheme"]!, Name: label["inScheme"]! }], Priority: [{ _oid: o["priority"]!, Name: label["priority"]! }] }); + expect(await client.lists.values({ type: "PrimaryWorkitem", scope: o["scope"]!, attributes: ["Status"] })).toEqual({ Status: [{ _oid: o["inScheme"]!, Name: label["inScheme"]! }] }); + // Control: another scope has none of these. + const system = await client.lists.values({ type: "Story", scope: "Scope:0", attributes: ["Status", "Priority"] }); + for (const rows of Object.values(system)) for (const oid of created) expect(rows.map((r) => r._oid)).not.toContain(oid); + }); + + it("a team with its own process replaces the scheme's statuses with its own, an inactive one left out, in Order; the asset alone says so", async () => { + const forAsset = await client.lists.values({ asset: o["onTeam"]!, attributes: ["Status", "Priority"], select: ["Order"] }); + expect(names(forAsset.Status!)).toEqual([label["teamFirst"]!, label["teamSecond"]!]); + expect(forAsset.Status!.map((r) => Number(r.Order))).toEqual([...forAsset.Status!.map((r) => Number(r.Order))].sort((a, b) => a - b)); + // Every value is a string, a number too. + expect(typeof forAsset.Status![0]!.Order).toBe("string"); + // The team's process is about Status: Priority still comes from the scheme. + expect(names(forAsset.Priority!)).toEqual([label["priority"]!]); + // RollupState is selectable on a status. + expect((await client.lists.values({ asset: o["onTeam"]!, attributes: ["Status"], select: ["RollupState"] })).Status!.map((r) => r.RollupState)).toEqual(["Active", "Closed"]); + // No team, or a team that owns no status: the scheme's. + expect(names((await client.lists.values({ asset: o["noTeam"]!, attributes: ["Status"] })).Status!)).toEqual([label["inScheme"]!]); + expect(names((await client.lists.values({ asset: o["onPlainTeam"]!, attributes: ["Status"] })).Status!)).toEqual([label["inScheme"]!]); + }); + + it("for an asset not created yet the team travels in the context: with a process its statuses, without one the scheme's; and an asset can be asked about as if on a team", async () => { + expect(names((await client.lists.values({ type: "Story", scope: o["scope"]!, team: o["team"]!, attributes: ["Status"] })).Status!)).toEqual([label["teamFirst"]!, label["teamSecond"]!]); + expect(names((await client.lists.values({ type: "Story", scope: o["scope"]!, team: o["plainTeam"]!, attributes: ["Status"] })).Status!)).toEqual([label["inScheme"]!]); + expect(names((await client.lists.values({ type: "Story", scope: o["scope"]!, team: o["team"]!, attributes: ["Priority"] })).Priority!)).toEqual([label["priority"]!]); + expect(names((await client.lists.values({ asset: o["noTeam"]!, team: o["team"]!, attributes: ["Status"] })).Status!)).toEqual([label["teamFirst"]!, label["teamSecond"]!]); + // Why the SDK does not send `teamoid` in the relation form: the server ignores it there and answers the scheme's values. + const ignored = await t.request<{ Assets: { id: string }[] }>({ method: "GET", path: `/api/ValidValues/Story.Status/?context=Scope=${o["scope"]!}&teamoid=${o["team"]!}&sel=Name`, headers: { accept: "application/json" }, responseType: "json" }); + expect(ignored.Assets.map((a) => a.id)).toEqual([o["inScheme"]!]); + }); + + it("value resolves a name there, and says what the valid values are when it is none of them", async () => { + expect(await client.lists.value({ asset: o["onTeam"]!, attribute: "Status", name: ` ${label["teamSecond"]!.toUpperCase()} ` })).toEqual({ _oid: o["teamSecond"]!, Name: label["teamSecond"]! }); + expect(await client.lists.value({ asset: o["onTeam"]!, attribute: "Status", name: o["teamFirst"]! })).toMatchObject({ _oid: o["teamFirst"]! }); + // A status of the scheme is not valid on the team's story; the inactive one is not valid anywhere. + for (const name of [label["inScheme"]!, o["inScheme"]!, label["teamInactive"]!]) { + const error = await client.lists.value({ asset: o["onTeam"]!, attribute: "Status", name }).catch((e: unknown) => e as ApiError); + expect(error).toMatchObject({ code: "NO_SUCH_VALUE", details: { values: [{ _oid: o["teamFirst"]!, Name: label["teamFirst"]! }, { _oid: o["teamSecond"]!, Name: label["teamSecond"]! }] } }); + } + // Both team statuses begin "sdk-integration": a prefix that fits both is ambiguous, never a pick. + await expect(client.lists.value({ asset: o["onTeam"]!, attribute: "Status", name: "sdk-integration", match: "prefix" })).rejects.toMatchObject({ code: "AMBIGUOUS_VALUE" }); + }); + + it("the server enforces the team's process on a write, and not the scope's scheme: the list is what to offer, not what the server will refuse", async () => { + const refused = await client.send([{ from: o["onTeam"]!, update: { Status: o["inScheme"]! } }]); + expect(refused.modified).toEqual([]); + expect(refused.failures[0]!.message).toBe("Violation'PrimaryWorkitemCannotHaveInvalidStatus"); + // A status selected in no scheme, on a story whose team has no process: accepted. + const accepted = await client.send([{ from: o["noTeam"]!, update: { Status: o["notInScheme"]! } }]); + expect(accepted.modified).toEqual([o["noTeam"]!]); + expect(accepted.failures).toEqual([]); + await client.send([{ from: o["noTeam"]!, update: { Status: null } }], { throwOnFailure: true }); + }); + + it("what the service refuses to ask, and why: the endpoint answers any relation whole. The raw module shows it on a relation this suite can bound", async () => { + await expect(client.lists.values({ asset: o["onTeam"]!, attributes: ["Team"] })).rejects.toMatchObject({ kind: "usage" }); + // An attribute the type does not have: the server's answer is a bare 400, so the service says it first. + await expect(validValues.forNew(t, "Story", "Nmae", o["scope"]!)).rejects.toMatchObject({ status: 400 }); + await expect(client.lists.values({ type: "Story", scope: o["scope"]!, attributes: ["Nmae"] })).rejects.toMatchObject({ kind: "usage" }); + // The context takes a scope and a team joined by a comma, and nothing else. + await expect(t.request({ method: "GET", path: `/api/ValidValues/Story.Status/?context=Scope=${o["scope"]!};Team=${o["team"]!}&sel=Name`, headers: { accept: "application/json" }, responseType: "json" })).rejects.toMatchObject({ status: 400 }); + }); + + it("the permanent reference team (AGENTS.md) offers its three statuses, in Order, to a story on it; read only, and skipped where the instance has no such team", async (context) => { + const [team] = await client.query<{ _oid: string; Name: string }>({ from: "Team" as never, select: ["Name"], filter: ["ID=$oid"], with: { $oid: reference.team }, page: { size: 1, start: 0 } }); + if (team?.Name !== "sdk-reference team") return context.skip(); + const offered = await client.lists.values({ type: "Story", scope: o["scope"]!, team: reference.team, attributes: ["Status"], select: ["RollupState"] }); + expect(offered.Status).toEqual([ + { _oid: reference.ready, Name: "sdk-reference Ready", RollupState: "Future" }, + { _oid: reference.inProgress, Name: "sdk-reference In Progress", RollupState: "Active" }, + { _oid: reference.done, Name: "sdk-reference Done", RollupState: "Closed" } + ]); + expect(await client.lists.value({ type: "Story", scope: o["scope"]!, team: reference.team, attribute: "Status", name: "sdk-reference done" })).toMatchObject({ _oid: reference.done }); + // The suite's own team is not offered them, and they are not this suite's to delete. + expect((await client.lists.values({ asset: o["onTeam"]!, attributes: ["Status"] })).Status!.map((r) => r._oid)).not.toContain(reference.done); + expect(created).not.toContain(reference.team); + }); + + it("the permanent statuses selected in the default scheme (AGENTS.md) are what a story in the system project on no team is offered; read only, and skipped where the instance has none", async (context) => { + const present = await client.query({ from: "StoryStatus" as never, select: ["Name"], filter: ["ID=$oids"], with: { $oids: schemeStatuses.map((s) => s._oid) }, page: { size: 5, start: 0 } }); + if (present.length !== schemeStatuses.length) return context.skip(); + // RollupState is what tells a consumer that "Done" closes work. + const offered = await client.lists.values({ type: "Story", scope: "Scope:0", attributes: ["Status"], select: ["RollupState"] }); + expect(offered.Status).toEqual(schemeStatuses.map((s) => ({ ...s }))); + expect(await client.lists.value({ type: "Story", scope: "Scope:0", attribute: "Status", name: "done" })).toEqual({ _oid: "StoryStatus:152570", Name: "Done" }); + // "In Progress" and the reference team's "sdk-reference In Progress" are different lists: each context has its own. + expect(await client.lists.value({ type: "Story", scope: "Scope:0", attribute: "Status", name: "in progress" })).toMatchObject({ _oid: "StoryStatus:152568" }); + await expect(client.lists.value({ type: "Story", scope: "Scope:0", team: reference.team, attribute: "Status", name: "in progress" })).rejects.toMatchObject({ code: "NO_SUCH_VALUE" }); + // The suite's own scope has its own scheme, so it is offered none of them. + expect((await client.lists.values({ asset: o["noTeam"]!, attributes: ["Status"] })).Status!.map((r) => r._oid)).not.toContain("StoryStatus:152570"); + }); + + it("fields.describe says which of a form's attributes are list-typed", async () => { + const described = await client.fields.describe("Story", o["scope"]!); + expect(described.lists).toMatchObject({ Status: "StoryStatus", Priority: "WorkitemPriority" }); + expect(described.lists).not.toHaveProperty("Owners"); + expect(described.lists).not.toHaveProperty("Name"); + }); +}); diff --git a/test/integration/referenceData.ts b/test/integration/referenceData.ts new file mode 100644 index 0000000..e478911 --- /dev/null +++ b/test/integration/referenceData.ts @@ -0,0 +1,61 @@ +/** + * Permanent reference data on the API-testing instance, and the guard that + * keeps the tier's cleanup away from it. Anything whose name starts with + * `sdk-reference` was put there to stay (AGENTS.md, "Reference data on the + * testing instance"): nothing in this repository creates, edits, closes, + * reorders or deletes it. `sdk-integration` is the other prefix: what a + * test creates and deletes within its own run. + * + * Kept free of the test runner and of the instance configuration, so the + * unit tier can test the guard. + */ +import type { Transport } from "../../src/core/transport"; +import { momentless } from "../../src/types/oid"; +import { queries } from "../../src/wire/queryV1"; + +export const REFERENCE_PREFIX = "sdk-reference"; + +/** The reference team with its own process and the three statuses it owns, in Order. */ +export const reference = { + team: "Team:152495", + ready: "StoryStatus:152496", + inProgress: "StoryStatus:152497", + done: "StoryStatus:152498" +} as const; + +/** + * The five global story statuses selected in the Default Scheme, in Order, + * by the product's own names. A name like "Done" cannot be a prefix rule, + * so these are guarded by OID. + */ +export const schemeStatuses = [ + { _oid: "StoryStatus:152567", Name: "Future", RollupState: "Active" }, + { _oid: "StoryStatus:152568", Name: "In Progress", RollupState: "Active" }, + { _oid: "StoryStatus:152569", Name: "QA / Test", RollupState: "Active" }, + { _oid: "StoryStatus:152570", Name: "Done", RollupState: "Closed" }, + { _oid: "StoryStatus:152571", Name: "Accepted", RollupState: "Closed" } +] as const; + +/** Every permanent OID, and the scheme whose selection must not change. */ +export const PERMANENT: ReadonlySet = new Set([...Object.values(reference), ...schemeStatuses.map((s) => s._oid), "Scheme:1000", "Scope:0"]); + +/** + * Throws if any of these assets is reference data: one of the permanent + * OIDs, or anything named `sdk-reference …` as the instance has it now. Called before anything is deleted: an OID that + * reached a cleanup list by mistake must stop the cleanup, not be removed. + * An OID nothing answers for (already deleted) passes. A name that cannot + * be read is a refusal too: not knowing is not permission. + */ +export async function assertNotReference(transport: Transport, oids: readonly string[]): Promise { + // By OID first, with no request: these are permanent whatever they are named now. + const permanent = oids.map((o) => momentless(o)).filter((oid) => PERMANENT.has(oid)); + if (permanent.length) throw new Error(`refusing to delete permanent reference data: ${permanent.join(", ")}. Nothing was deleted.`); + const byType = new Map(); + for (const oid of oids.map((o) => momentless(o))) byType.set(oid.split(":")[0]!, [...(byType.get(oid.split(":")[0]!) ?? []), oid]); + if (!byType.size) return; + // One request for all types: query.v1 answers one result per query. A filter by ID must name one type's OIDs. + const types = [...byType.keys()]; + const results = await queries<{ _oid: string; Name?: unknown }>(transport, types.map((type) => ({ from: type, select: ["Name"], filter: ["ID=$oids"], with: { $oids: byType.get(type)! }, page: { size: byType.get(type)!.length, start: 0 } }))); + const kept = results.flat().filter((row) => typeof row.Name === "string" && row.Name.trim().toLowerCase().startsWith(REFERENCE_PREFIX)); + if (kept.length) throw new Error(`refusing to delete permanent reference data (named ${REFERENCE_PREFIX} …): ${kept.map((row) => `${row._oid} "${String(row.Name)}"`).join(", ")}. Nothing was deleted.`); +} diff --git a/test/unit/fields.test.ts b/test/unit/fields.test.ts index 7cc21ed..c687797 100644 --- a/test/unit/fields.test.ts +++ b/test/unit/fields.test.ts @@ -46,7 +46,7 @@ describe("fields service", () => { const t = fake((o) => (o.path.startsWith("/api/visibleFields") ? visibleAnswer : { requestId: "r", queryResult: { results: [[{ _oid: "Scope:0", Scheme: [{ _oid: "Scheme:1000", ImportantFields: ["Story.Owners", "Defect.Resolution", "Workitem.Estimate"], IsRequiredAtClose: "True" }] }]], resultMetaData: [], count: 1 } })); const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, types: schema().cache }); const f = await client.fields.describe("Story", "Scope:0:7"); - expect(f).toEqual({ type: "Story", scope: "Scope:0", scheme: "Scheme:1000", required: ["Name", "Scope"], visible: visibleAnswer[0]!.fields, important: ["Estimate", "Owners"], requiredAtClose: true }); + expect(f).toEqual({ type: "Story", scope: "Scope:0", scheme: "Scheme:1000", required: ["Name", "Scope"], visible: visibleAnswer[0]!.fields, important: ["Estimate", "Owners"], requiredAtClose: true, lists: { Status: "StoryStatus" } }); const body = (t.calls.find((c) => c.path === "/api/asset")!.body as unknown[])[0]; expect(body).toMatchObject({ from: "Scope", with: { $scope: "Scope:0" }, page: { size: 1, start: 0 } }); }); diff --git a/test/unit/knownKeys.test.ts b/test/unit/knownKeys.test.ts new file mode 100644 index 0000000..7526478 --- /dev/null +++ b/test/unit/knownKeys.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vitest"; +import { AgilityApiClient } from "../../src/client"; +import { CLIENT_CONFIG_KEYS, type ClientConfig } from "../../src/core/clientConfig"; +import { UsageError } from "../../src/core/errors"; +import { FETCH_TRANSPORT_CONFIG_KEYS, createFetchTransport, type FetchTransportConfig } from "../../src/core/fetchTransport"; +import { keysOf, refuseUnknownKeys } from "../../src/core/knownKeys"; +import { TypeCache } from "../../src/services/schema"; +import { FakeAgilityClient } from "../../src/testing"; + +/** + * A config object with a key its factory does not know is refused when it + * is handed over. A JavaScript caller (or one checked by JSDoc, not + * compiled) gets no excess-property error from a compiler, and a misspelt + * or misplaced option that is quietly ignored is how a client ran for + * releases without the `fetch` its author thought it had. + */ +const SECRET = "s3cr3t-token-value"; +const refusal = (make: () => unknown): UsageError => { try { make(); } catch (error) { return error as UsageError; } throw new Error("was not refused"); }; + +describe("unknown config keys", () => { + it("the client refuses a key its config does not know, names it, suggests the nearest known key, and never repeats a value", () => { + const error = refusal(() => new AgilityApiClient({ baseUrl: "https://agility.example.com/I", accessToken: SECRET, retrys: 3, fetchImplementation: fetch } as unknown as ClientConfig)); + expect(error).toBeInstanceOf(UsageError); + expect(error.kind).toBe("usage"); + expect(error.message).toContain(`unknown keys "retrys" (did you mean "retries"?), "fetchImplementation"`); + expect(error.message).toContain("It takes: baseUrl, authorization, accessToken"); + expect(error.details).toMatchObject({ unknown: ["retrys", "fetchImplementation"] }); + expect(JSON.stringify([error.message, error.details])).not.toContain(SECRET); + // The same but for case, and one letter off. + expect(refusal(() => new AgilityApiClient({ baseUrl: "https://x", baseURL: "https://y" } as unknown as ClientConfig)).message).toContain(`"baseURL" (did you mean "baseUrl"?)`); + expect(refusal(() => new AgilityApiClient({ baseUrl: "https://x", timeoutMS: 5 } as unknown as ClientConfig)).message).toContain(`"timeoutMS" (did you mean "timeoutMs"?)`); + expect(refusal(() => new AgilityApiClient({ baseUrl: "https://x", acessToken: SECRET } as unknown as ClientConfig)).message).toContain(`"acessToken" (did you mean "accessToken"?)`); + // Nothing near: named, with no guess. + expect(refusal(() => new AgilityApiClient({ baseUrl: "https://x", proxy: "http://p" } as unknown as ClientConfig)).message).toContain(`unknown key "proxy". It takes:`); + }); + + it("the name is the mistake: an unknown key is refused even when its value is undefined; a known key may be undefined", () => { + expect(refusal(() => new AgilityApiClient({ baseUrl: "https://x", retrys: undefined } as unknown as ClientConfig)).message).toContain(`"retrys"`); + expect(() => new AgilityApiClient({ baseUrl: "https://x", accessToken: undefined, retries: undefined, timeoutMs: undefined, fetchImpl: undefined, onError: undefined })).not.toThrow(); + expect(() => createFetchTransport({ baseUrl: "https://x", authorization: undefined, credentials: undefined })).not.toThrow(); + }); + + it("every documented key is accepted, by the client and by createFetchTransport", () => { + const everyClientKey: Required = { baseUrl: "https://x", authorization: "Basic eA==", accessToken: "t", fetchImpl: fetch, timeoutMs: 1, retries: 0, defaultHeaders: {}, onError: () => {}, credentials: "include", onUnauthorized: () => "fail", unauthorizedStatuses: [401] }; + expect(Object.keys(everyClientKey).sort()).toEqual([...CLIENT_CONFIG_KEYS].sort()); + expect(() => new AgilityApiClient(everyClientKey)).not.toThrow(); + const everyTransportKey: Required = { baseUrl: "https://x", authorization: "Basic eA==", accessToken: "t", defaultHeaders: {}, timeoutMs: 1, retries: 0, fetchImpl: fetch, credentials: "include", onUnauthorized: () => "fail", unauthorizedStatuses: [401] }; + expect(Object.keys(everyTransportKey).sort()).toEqual([...FETCH_TRANSPORT_CONFIG_KEYS].sort()); + expect(() => createFetchTransport(everyTransportKey)).not.toThrow(); + }); + + it("createFetchTransport, the client's options and the fake refuse alike; a client built by withSignal is not refused", () => { + expect(refusal(() => createFetchTransport({ baseUrl: "https://x", accessToken: SECRET, onError: () => {} } as unknown as FetchTransportConfig)).message).toMatch(/^createFetchTransport's config: unknown key "onError"/); + // A key in the wrong object: `transport` belongs in the options, `fetchImpl` in the config. + expect(refusal(() => new AgilityApiClient({ baseUrl: "https://x", transport: {} } as unknown as ClientConfig)).message).toContain(`the client's config: unknown key "transport"`); + expect(refusal(() => new AgilityApiClient({ baseUrl: "https://x" }, { fetchImpl: fetch } as never)).message).toContain(`the client's options: unknown key "fetchImpl"`); + expect(refusal(() => new AgilityApiClient({ baseUrl: "https://x" }, { type: new TypeCache() } as never)).message).toContain(`"type" (did you mean "types"?)`); + // The fake takes the client's keys and `metamodel`. + expect(() => new FakeAgilityClient({ retries: 1, metamodel: { AssetTypes: {} } })).not.toThrow(); + expect(refusal(() => new FakeAgilityClient({ metamodl: { AssetTypes: {} } } as never)).message).toContain(`"metamodl"`); + expect(() => new AgilityApiClient({ baseUrl: "https://x" }).withSignal(new AbortController().signal)).not.toThrow(); + // Not an object at all. + expect(() => new AgilityApiClient(null as never)).toThrow(UsageError); + expect(() => refuseUnknownKeys("a config", [], ["a"])).toThrow(UsageError); + }); + + it("a key list cannot drift from its type: a key left out, or one the type does not have, does not compile", () => { + interface Example { a: string; b?: number } + expect(keysOf()({ a: true, b: true })).toEqual(["a", "b"]); + // @ts-expect-error a key of the type left out of the list + keysOf()({ a: true }); + // @ts-expect-error a key the type does not have + keysOf()({ a: true, b: true, c: true }); + }); +}); diff --git a/test/unit/lists.test.ts b/test/unit/lists.test.ts new file mode 100644 index 0000000..400bef6 --- /dev/null +++ b/test/unit/lists.test.ts @@ -0,0 +1,165 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it, vi } from "vitest"; +import { AgilityApiClient } from "../../src/client"; +import { ApiError, apiErrorFromResponse } from "../../src/core/errors"; +import type { RequestOptions, Transport } from "../../src/core/transport"; +import { Schema } from "../../src/services/schema"; +import { FakeAgilityClient } from "../../src/testing"; +import { toMetamodel, type MetamodelDocument } from "../../src/wire/meta"; +import { forAsset, forNew } from "../../src/wire/validValues"; + +const schema = () => Schema.fromMetamodel(toMetamodel(JSON.parse(readFileSync(join(__dirname, "..", "..", "metamodel.json"), "utf8")) as MetamodelDocument)); +function fake(answer: (o: RequestOptions) => unknown): Transport & { calls: RequestOptions[] } { + const calls: RequestOptions[] = []; + return { request: vi.fn(async (o: RequestOptions) => { calls.push(o); return answer(o); }) as Transport["request"], calls }; +} +// As api/ValidValues answered on the API-testing instance (2026-11-26), identities replaced. Every value is a string; pageSize is the server's "no page". +const entry = (id: number, Name: string, Order: string, RollupState = "Active") => ({ _type: "Asset", href: `~/rest-1.v1/Data/StoryStatus/${id}`, id: `StoryStatus:${id}`, Attributes: { Name: { _type: "Attribute", name: "Name", value: Name }, Order: { _type: "Attribute", name: "Order", value: Order }, RollupState: { _type: "Attribute", name: "RollupState", value: RollupState } } }); +const all = { _type: "Assets", total: 3, pageSize: 2147483647, pageStart: 0, Assets: [entry(133, "Future", "115"), entry(134, "In Progress", "116"), entry(135, "Done", "117", "Closed")] }; +type Doc = typeof all; +/** The document with the attributes the request selected, as the endpoint sends it. */ +const answering = (doc: Doc) => (o: RequestOptions): Doc => { + const sel = /[?&]sel=([^&]*)/.exec(o.path)?.[1]?.split(","); + return { ...doc, Assets: doc.Assets.map((a) => ({ ...a, Attributes: Object.fromEntries(Object.entries(a.Attributes).filter(([name]) => !sel || sel.includes(name))) as typeof a.Attributes })) }; +}; +const statuses = answering(all); +const client = (t: Transport) => new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, types: schema().cache }); + +describe("validValues wire", () => { + it("forNew asks the relation form: a trailing slash, one context joined by a comma, the values as they are", async () => { + const t = fake(statuses); + const rows = await forNew(t, "Story", "Status", "Scope:5:99", { select: ["Name", "Order"], sort: ["Order"], team: "Team:9" }); + expect(t.calls[0]).toMatchObject({ method: "GET", path: "/api/ValidValues/Story.Status/?context=Scope=Scope:5,Team=Team:9&sel=Name,Order&sort=Order" }); + // The keys selected and no others; a value is the string the endpoint sent. + expect(rows).toEqual([{ _oid: "StoryStatus:133", Name: "Future", Order: "115" }, { _oid: "StoryStatus:134", Name: "In Progress", Order: "116" }, { _oid: "StoryStatus:135", Name: "Done", Order: "117" }]); + await forNew(t, "Story", "Status", "Scope:5"); + expect(t.calls[1]!.path).toBe("/api/ValidValues/Story.Status/?context=Scope=Scope:5"); + }); + + it("forAsset asks the asset form, the team as teamoid; a refusal is an error and an answer that is no list is a protocol error", async () => { + const t = fake(statuses); + await forAsset(t, "Story:1077:3", "Status", { select: ["Name"], team: "Team:9" }); + expect(t.calls[0]!.path).toBe("/api/ValidValues/Story/1077/Status?teamoid=Team:9&sel=Name"); + await forAsset(t, "Story:1077", "Status"); + expect(t.calls[1]!.path).toBe("/api/ValidValues/Story/1077/Status"); + // As the endpoint refuses an attribute the type does not have (2026-11-26). + const refusing = fake(() => { throw apiErrorFromResponse(400, { Exceptions: ["Bad Request", "Reference: 00000000-0000-0000-0000-000000000000"] }); }); + await expect(forNew(refusing, "Story", "Nmae", "Scope:5")).rejects.toMatchObject({ status: 400, kind: "invalid" }); + await expect(forNew(fake(() => ({ nope: 1 })), "Story", "Status", "Scope:5")).rejects.toMatchObject({ code: "BAD_RESPONSE" }); + // An instance without the endpoint: its 404, never an empty list. + await expect(forNew(fake(() => { throw new ApiError("Not Found", 404); }), "Story", "Status", "Scope:5")).rejects.toMatchObject({ status: 404 }); + }); +}); + +describe("client.lists", () => { + it("values answers a map from attribute to rows in the list's order, one request per attribute, Name always selected and sorted by Order", async () => { + const t = fake(statuses); + const answer = await client(t).lists.values({ asset: "Story:1077", attributes: ["Status", "Priority"], select: ["Order"] }); + expect(t.calls.map((c) => c.path)).toEqual(["/api/ValidValues/Story/1077/Status?sel=Name,Order&sort=Order", "/api/ValidValues/Story/1077/Priority?sel=Name,Order&sort=Order"]); + expect(answer.Status).toEqual([{ _oid: "StoryStatus:133", Name: "Future", Order: "115" }, { _oid: "StoryStatus:134", Name: "In Progress", Order: "116" }, { _oid: "StoryStatus:135", Name: "Done", Order: "117" }]); + // What is selected must be an attribute of every list asked for: a status has a RollupState, a priority has not. + await expect(client(t).lists.values({ asset: "Story:1077", attributes: ["Status", "Priority"], select: ["RollupState"] })).rejects.toMatchObject({ kind: "usage", message: expect.stringContaining("WorkitemPriority has no attribute RollupState") }); + expect(t.calls).toHaveLength(2); + expect(Object.keys(answer)).toEqual(["Status", "Priority"]); + // For an asset not created yet: the type, the scope and the team it will be on. A base type is a type. + const forNewOne = fake(() => ({ ...all, total: 0, Assets: [] })); + expect(await client(forNewOne).lists.values({ type: "PrimaryWorkitem", scope: "Scope:5", team: "Team:9", attributes: ["Status"] })).toEqual({ Status: [] }); + expect(forNewOne.calls[0]!.path).toBe("/api/ValidValues/PrimaryWorkitem.Status/?context=Scope=Scope:5,Team=Team:9&sel=Name&sort=Order"); + }); + + it("only a relation to a list type is asked for, because the endpoint cannot be bounded; everything else is refused before anything is sent, with the read to use instead", async () => { + const t = fake(statuses); + const lists = client(t).lists; + await expect(lists.values({ asset: "Story:1", attributes: ["Owners"] })).rejects.toMatchObject({ kind: "usage", message: expect.stringMatching(/Story\.Owners points to Member, which is not a list type.*client\.query\(\{ from: "Member", filter, page \}\)/) }); + await expect(lists.values({ type: "Story", scope: "Scope:5", attributes: ["Team"] })).rejects.toMatchObject({ kind: "usage", message: expect.stringContaining('client.query({ from: "Team"') }); + await expect(lists.values({ asset: "Story:1", attributes: ["Timebox"] })).rejects.toMatchObject({ kind: "usage" }); + await expect(lists.values({ asset: "Story:1", attributes: ["Name"] })).rejects.toMatchObject({ kind: "usage", message: expect.stringContaining("Story.Name is not a relation") }); + await expect(lists.values({ asset: "Story:1", attributes: ["Nmae"] })).rejects.toMatchObject({ kind: "usage", message: expect.stringContaining("Story has no attribute Nmae") }); + await expect(lists.values({ asset: "Story:1", attributes: [] })).rejects.toMatchObject({ kind: "usage" }); + await expect(lists.values({ asset: "S-01077" as never, attributes: ["Status"] })).rejects.toMatchObject({ kind: "usage" }); + // One bad attribute among good ones: nothing is sent for any. + await expect(lists.values({ asset: "Story:1", attributes: ["Status", "Owners"] })).rejects.toMatchObject({ kind: "usage" }); + // select: attributes of the value itself, and never a date (the endpoint writes dates in the server's culture format). + await expect(lists.values({ asset: "Story:1", attributes: ["Status"], select: ["ChangeDate"] })).rejects.toMatchObject({ kind: "usage", message: expect.stringContaining("is a date") }); + await expect(lists.values({ asset: "Story:1", attributes: ["Status"], select: ["Team.Name"] })).rejects.toMatchObject({ kind: "usage" }); + await expect(lists.values({ asset: "Story:1", attributes: ["Status"], select: ["Nmae"] })).rejects.toMatchObject({ kind: "usage", message: expect.stringContaining("StoryStatus has no attribute Nmae") }); + expect(t.calls).toHaveLength(0); + }); + + it("value answers the one value a name means there: the whole name, ignoring case and surrounding space; an OID is checked to be among the valid values", async () => { + const t = fake(statuses); + const lists = client(t).lists; + expect(await lists.value({ asset: "Story:1077", attribute: "Status", name: " done " })).toEqual({ _oid: "StoryStatus:135", Name: "Done" }); + expect(await lists.value({ asset: "Story:1077", attribute: "Status", name: "IN PROGRESS", select: ["RollupState"] })).toEqual({ _oid: "StoryStatus:134", Name: "In Progress", RollupState: "Active" }); + expect(await lists.value({ type: "Story", scope: "Scope:5", attribute: "Status", name: "StoryStatus:133:7" })).toMatchObject({ _oid: "StoryStatus:133", Name: "Future" }); + await expect(lists.value({ asset: "Story:1077", attribute: "Status", name: " " })).rejects.toMatchObject({ kind: "usage" }); + }); + + it("no such value is NO_SUCH_VALUE with every valid value as a row; more than one is AMBIGUOUS_VALUE with the ones that matched; a part of a name matches only when asked", async () => { + const twice = { ...all, Assets: [...all.Assets, entry(136, "Done", "118"), entry(137, "In Review", "119"), entry(138, "Progressing", "120")] }; + const lists = client(fake(answering(twice))).lists; + const missing = await lists.value({ asset: "Story:1077", attribute: "Status", name: "Dne" }).catch((e: unknown) => e as ApiError); + expect(missing).toMatchObject({ code: "NO_SUCH_VALUE", kind: "invalid", message: 'Story.Status has no value "Dne" here. It can be: Future, In Progress, Done, Done, In Review, Progressing.' }); + expect((missing.details as { values: unknown[] }).values).toEqual(twice.Assets.map((a) => ({ _oid: a.id, Name: a.Attributes.Name.value }))); + // A valid OID of the list type that is not valid here is no such value either. + await expect(lists.value({ asset: "Story:1077", attribute: "Status", name: "StoryStatus:999" })).rejects.toMatchObject({ code: "NO_SUCH_VALUE" }); + const both = await lists.value({ asset: "Story:1077", attribute: "Status", name: "done" }).catch((e: unknown) => e as ApiError); + expect(both).toMatchObject({ code: "AMBIGUOUS_VALUE", kind: "invalid", details: { attribute: "Status", name: "done", values: [{ _oid: "StoryStatus:135", Name: "Done" }, { _oid: "StoryStatus:136", Name: "Done" }] } }); + // By default a part of a name finds nothing: a wrong status is never picked silently. + await expect(lists.value({ asset: "Story:1077", attribute: "Status", name: "fut" })).rejects.toMatchObject({ code: "NO_SUCH_VALUE" }); + // match "prefix": the text begins the name or a word of it; an exact name still wins; several is ambiguous. + expect(await lists.value({ asset: "Story:1077", attribute: "Status", name: "fut", match: "prefix" })).toMatchObject({ _oid: "StoryStatus:133" }); + expect(await lists.value({ asset: "Story:1077", attribute: "Status", name: "rev", match: "prefix" })).toMatchObject({ _oid: "StoryStatus:137" }); + expect(await lists.value({ asset: "Story:1077", attribute: "Status", name: "future", match: "prefix" })).toMatchObject({ _oid: "StoryStatus:133" }); + await expect(lists.value({ asset: "Story:1077", attribute: "Status", name: "prog", match: "prefix" })).rejects.toMatchObject({ code: "AMBIGUOUS_VALUE", details: { values: [{ _oid: "StoryStatus:134" }, { _oid: "StoryStatus:138" }] } }); + await expect(lists.value({ asset: "Story:1077", attribute: "Status", name: "in", match: "prefix" })).rejects.toMatchObject({ code: "AMBIGUOUS_VALUE" }); + await expect(lists.value({ asset: "Story:1077", attribute: "Status", name: "ogress", match: "prefix" })).rejects.toMatchObject({ code: "NO_SUCH_VALUE" }); + // No value valid there at all: said, not listed. + await expect(client(fake(() => ({ ...all, total: 0, Assets: [] }))).lists.value({ asset: "Story:1", attribute: "Status", name: "Done" })).rejects.toMatchObject({ code: "NO_SUCH_VALUE", message: 'Story.Status has no value "Done" here. No value is valid here.' }); + }); + + it("a type in the chain to List that cannot be loaded is said as that, not as 'not a list' with advice to use another read (a chat-bot consumer finding)", async () => { + // A schema that has Story and StoryStatus and nothing above them, as a test serving captured types may. + const whole = JSON.parse(readFileSync(join(__dirname, "..", "..", "metamodel.json"), "utf8")) as MetamodelDocument; + const partial = new FakeAgilityClient({ metamodel: { AssetTypes: Object.fromEntries(Object.entries(whole.AssetTypes).filter(([name]) => name !== "Status" && name !== "List")) as MetamodelDocument["AssetTypes"] } }); + const error = await partial.lists.values({ asset: "Story:1", attributes: ["Status"] }).catch((e: unknown) => e as ApiError); + expect(error).toMatchObject({ code: "NOT_FOUND", kind: "notFound", message: "could not load the asset type Status to tell whether StoryStatus is a list type" }); + expect(error.message).not.toContain("client.query"); + }); + + it("a failure is never an empty list: the endpoint's error is thrown, also when it is absent from the instance", async () => { + const gone = fake(() => { throw new ApiError("Not Found", 404); }); + await expect(client(gone).lists.values({ asset: "Story:1", attributes: ["Status"] })).rejects.toMatchObject({ status: 404 }); + await expect(client(gone).lists.value({ asset: "Story:1", attribute: "Status", name: "Done" })).rejects.toMatchObject({ status: 404 }); + }); +}); + +describe("FakeAgilityClient.onValues", () => { + it("scripts the valid values by attribute; the lookup is the client's own, and what was asked is recorded", async () => { + const agility = new FakeAgilityClient(); + agility.onValues({ Status: [{ _oid: "StoryStatus:133", Name: "Future" }, { _oid: "StoryStatus:135", Name: "Done", RollupState: "Closed" }] }); + agility.onValues({ Priority: (asked) => (asked.team ? [{ _oid: "WorkitemPriority:140", Name: "High" }] : []) }); + expect(await agility.lists.values({ asset: "Story:1077", attributes: ["Status"], select: ["RollupState"] })).toEqual({ Status: [{ _oid: "StoryStatus:133", Name: "Future", RollupState: null }, { _oid: "StoryStatus:135", Name: "Done", RollupState: "Closed" }] }); + expect(await agility.lists.value({ asset: "Story:1077", attribute: "Status", name: "done" })).toEqual({ _oid: "StoryStatus:135", Name: "Done" }); + await expect(agility.lists.value({ asset: "Story:1077", attribute: "Status", name: "Dne" })).rejects.toMatchObject({ code: "NO_SUCH_VALUE", details: { values: [{ _oid: "StoryStatus:133", Name: "Future" }, { _oid: "StoryStatus:135", Name: "Done" }] } }); + expect(await agility.lists.values({ type: "Defect", scope: "Scope:5", team: "Team:9", attributes: ["Priority"] })).toEqual({ Priority: [{ _oid: "WorkitemPriority:140", Name: "High" }] }); + expect(agility.valuesAsked).toEqual([ + { type: "Story", attribute: "Status", asset: "Story:1077" }, + { type: "Story", attribute: "Status", asset: "Story:1077" }, + { type: "Story", attribute: "Status", asset: "Story:1077" }, + { type: "Defect", attribute: "Priority", scope: "Scope:5", team: "Team:9" } + ]); + // An attribute nothing was scripted for says so, in the fake's own words: without a metamodel it does not know what + // Owners is, and must not refuse in words a server's metamodel would not produce (a CLI consumer finding). + for (const attribute of ["Source", "Owners"]) { + await expect(agility.lists.values({ asset: "Story:1", attributes: [attribute] })).rejects.toMatchObject({ kind: "usage", message: expect.stringMatching(new RegExp(`^FakeAgilityClient: no valid values scripted for Story\\.${attribute}`)) }); + } + await expect(agility.lists.value({ asset: "Story:1", attribute: "Owners", name: "x" })).rejects.toMatchObject({ message: expect.stringContaining("FakeAgilityClient") }); + // With a metamodel the client's own refusal is the one a server's metamodel produces. + const real = new FakeAgilityClient({ metamodel: JSON.parse(readFileSync(join(__dirname, "..", "..", "metamodel.json"), "utf8")) as MetamodelDocument }); + await expect(real.lists.values({ asset: "Story:1", attributes: ["Owners"] })).rejects.toMatchObject({ kind: "usage", message: expect.stringContaining("Story.Owners points to Member, which is not a list type") }); + agility.onValues({ Status: new ApiError("Not Found", 404) }); + await expect(agility.lists.values({ asset: "Story:1", attributes: ["Status"] })).rejects.toMatchObject({ status: 404 }); + }); +}); diff --git a/test/unit/preflight.test.ts b/test/unit/preflight.test.ts index 7dcdec0..982001a 100644 --- a/test/unit/preflight.test.ts +++ b/test/unit/preflight.test.ts @@ -1,3 +1,4 @@ +import { assertNotReference } from "../integration/referenceData"; import { describe, expect, it } from "vitest"; import type { RequestOptions, Transport } from "../../src/core/transport"; import { problemWith } from "../integration/memberCheck"; @@ -42,3 +43,35 @@ describe("the integration tier's preflight", () => { expect(await problemWith(instanceWhere({ seesProject: true, creates: true, deletes: false }))).toMatch(/created Story:900 and cannot delete it/); }); }); + +describe("the guard on permanent reference data", () => { + // query.v1 answers one list per query; here one query per asset type, each filtered by that type's OIDs. + const names: Record = { "Team:77": "sdk-reference team", "StoryStatus:78": "SDK-Reference In Progress", "Story:7": "sdk-integration story", "Team:9": "a team about the sdk-reference data" }; + const answering = (): Transport & { asked: { from: string; with: { $oids: string[] } }[][] } => { + const asked: { from: string; with: { $oids: string[] } }[][] = []; + return { asked, request: (async (o: RequestOptions) => { const body = o.body as { from: string; with: { $oids: string[] } }[]; asked.push(body); return body.map((q) => q.with.$oids.filter((oid) => oid in names).map((oid) => ({ _oid: oid, Name: names[oid] }))); }) as Transport["request"] }; + }; + + it("refuses a cleanup list that holds anything named sdk-reference, by the name the instance has now, and says which", async () => { + const t = answering(); + await expect(assertNotReference(t, ["Story:7", "Team:77:3", "StoryStatus:78"])).rejects.toThrow(/refusing to delete permanent reference data.*Team:77 "sdk-reference team", StoryStatus:78 "SDK-Reference In Progress".*Nothing was deleted/); + // One request, one query per type, each asking only for its own type's OIDs (a mixed ID filter is an error on the server). + expect(t.asked).toHaveLength(1); + expect(t.asked[0]!.map((q) => [q.from, q.with.$oids])).toEqual([["Story", ["Story:7"]], ["Team", ["Team:77"]], ["StoryStatus", ["StoryStatus:78"]]]); + }); + + it("refuses the permanent OIDs before asking anything: the product-named statuses, the reference team, the default scheme", async () => { + for (const oid of ["StoryStatus:152570", "StoryStatus:152567:9", "Team:152495", "Scheme:1000", "Scope:0"]) { + const t = answering(); + await expect(assertNotReference(t, ["Story:7", oid])).rejects.toThrow(/refusing to delete permanent reference data.*Nothing was deleted/); + expect(t.asked).toHaveLength(0); + } + }); + + it("lets through fixtures, assets already gone, and a name that merely mentions the prefix; an unreadable name is a refusal", async () => { + await expect(assertNotReference(answering(), ["Story:7", "Story:404", "Team:9"])).resolves.toBeUndefined(); + await expect(assertNotReference(answering(), [])).resolves.toBeUndefined(); + const failing: Transport = { request: (async () => { throw new Error("down"); }) as Transport["request"] }; + await expect(assertNotReference(failing, ["Story:7"])).rejects.toThrow("down"); + }); +}); diff --git a/test/unit/retry.test.ts b/test/unit/retry.test.ts index 254076f..b92e118 100644 --- a/test/unit/retry.test.ts +++ b/test/unit/retry.test.ts @@ -91,6 +91,70 @@ describe("the resend rule above a custom Transport", () => { expect(t.calls).toHaveLength(2); }); + it("the built-in transport handed to a client is not wrapped again: a failed read is sent twice, not four times (a CLI consumer finding); a wrapper around it is a custom transport", async () => { + const counting = () => { const sent: string[] = []; const fetchImpl = (async (url: string | URL) => { sent.push(new URL(String(url)).pathname); return new Response("down", { status: 503 }); }) as typeof fetch; return { sent, fetchImpl }; }; + // Handed in, as the README shows for a fetch of the caller's own. + const handed = counting(); + await expect(new AgilityApiClient({ baseUrl: "https://x" }, { transport: createFetchTransport({ baseUrl: "https://x", fetchImpl: handed.fetchImpl }) }).query(q)).rejects.toMatchObject({ status: 503, request: { method: "GET", path: "/meta.v1/Story", idempotent: true } }); + expect(handed.sent).toEqual(["/meta.v1/Story", "/meta.v1/Story"]); + // The transport's own `retries` is the one that counts then; the client's config does not add to it. + const off = counting(); + await expect(new AgilityApiClient({ baseUrl: "https://x", retries: 3 }, { transport: createFetchTransport({ baseUrl: "https://x", retries: 0, fetchImpl: off.fetchImpl }) }).query(q)).rejects.toMatchObject({ status: 503 }); + expect(off.sent).toHaveLength(1); + // Made by the client from its config, with a fetch of the caller's: the same two sends, and the fetch is the one given. + const made = counting(); + await expect(new AgilityApiClient({ baseUrl: "https://x", fetchImpl: made.fetchImpl }).query(q)).rejects.toMatchObject({ status: 503 }); + expect(made.sent).toEqual(["/meta.v1/Story", "/meta.v1/Story"]); + // A wrapper of the caller's around the built-in transport is a custom transport: the client's rule goes around it. + // To have one rule only, the wrapped transport is made with retries: 0 and timeoutMs: 0. + const wrapped = counting(); + const inner = createFetchTransport({ baseUrl: "https://x", retries: 0, timeoutMs: 0, fetchImpl: wrapped.fetchImpl }); + await expect(new AgilityApiClient({ baseUrl: "https://x" }, { transport: { request: (o) => inner.request(o) } }).query(q)).rejects.toMatchObject({ status: 503 }); + expect(wrapped.sent).toHaveLength(2); + }); + + it("one rule, once, however the client is built: from its config, on a built-in transport handed in, on a custom transport. Attempts counted for a 502, a lost connection, a 429 with Retry-After and a timeout", async () => { + type Failure = "502" | "lost" | "429" | "timeout"; + /** A fetch that fails every request the given way and counts the requests for the query (not the schema load). */ + const failing = (how: Failure) => { + const state = { sends: 0 }; + const fetchImpl = ((url: string | URL, init?: RequestInit) => { + if (new URL(String(url)).pathname.startsWith("/meta.v1/")) return Promise.resolve(new Response("{}", { status: 404 })); + state.sends += 1; + if (how === "lost") return Promise.reject(new TypeError("fetch failed")); + if (how === "timeout") return new Promise((_, reject) => init!.signal!.addEventListener("abort", () => reject(Object.assign(new Error("aborted"), { name: "AbortError" })))); + return Promise.resolve(new Response("no", { status: Number(how), headers: how === "429" ? { "retry-after": "0" } : {} })); + }) as typeof fetch; + return { state, fetchImpl }; + }; + const base = { baseUrl: "https://x", timeoutMs: 60 }; + const builds: Record AgilityApiClient> = { + "from its config": (fetchImpl) => new AgilityApiClient({ ...base, fetchImpl }), + "a built-in transport handed in": (fetchImpl) => new AgilityApiClient({ baseUrl: "https://x" }, { transport: createFetchTransport({ ...base, fetchImpl }) }), + // A custom transport: plain fetch, errors as the built-in one words them, no rule of its own. + "a custom transport": (fetchImpl) => new AgilityApiClient(base, { transport: { request: async (o) => { + let response: Response; + try { response = await fetchImpl(`https://x${o.path}`, { method: o.method, body: o.body === undefined ? undefined : JSON.stringify(o.body), signal: o.signal }); } + catch (error) { throw new ApiError((error as Error).message, 0, "NETWORK_ERROR"); } + if (!response.ok) throw new ApiError("refused", response.status); + return response.json(); + } } }) + }; + const expected: Record = { "502": { sends: 2, status: 502 }, lost: { sends: 2, code: "NETWORK_ERROR", status: 0 }, "429": { sends: 2, status: 429 }, timeout: { sends: 1, code: "TIMEOUT", status: 0 } }; + for (const [built, make] of Object.entries(builds)) { + for (const how of Object.keys(expected) as Failure[]) { + const { state, fetchImpl } = failing(how); + const started = Date.now(); + const error = await make(fetchImpl).query(q).catch((e: unknown) => e); + const want = expected[how]; + expect(error, `${built}, ${how}`).toMatchObject({ status: want.status, kind: "transient", ...(want.code ? { code: want.code } : {}) }); + expect(state.sends, `${built}, ${how}: attempts`).toBe(want.sends); + // One deadline, not two stacked: a timeout ends at about timeoutMs. + if (how === "timeout") expect(Date.now() - started, `${built}: one deadline`).toBeLessThan(1000); + } + } + }, 30_000); + it("once, not forever; `retries` says how many times, and 0 turns it off", async () => { const down = () => new ApiError("Service Unavailable", 503); const once = custom(down(), down(), [[]]);