diff --git a/CHANGELOG.md b/CHANGELOG.md index ad9b6c2..160580f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,67 @@ releases, other ways of signing in. So a hook that prompts a person should still check that the session is gone before it prompts. +- **`client.lists` rows are translated like any other row.** The + endpoint sends every value as a string, and alpha.12 passed that on: + a status's `Order` was `"115"` from `client.lists` and `115` from + `client.query`. Now a number is a number, a Boolean a Boolean and a + relation a Ref or `null`, by the list type's schema (spec 000 §2: one + shape for a row on every read). A multi-value relation can no longer + be selected (it never arrived in a readable form); a date is still + refused. Migration: drop a `Number(row.Order)` or a comparison with + `"True"`; a sort on `Order` now sorts numbers. +- **`/wire`'s `validValues` takes `sort` as one attribute name**, not a + list: the endpoint sorts by one attribute, ascending, and ignores + without an error a name the list type does not have. Migration: + `sort: "Order"` in place of `sort: ["Order"]`. + +### Fixed + +- **What `client.lists` documents was wrong in three places**, now + corrected in the README, the doc comments and the module headers, and + each proved against an instance: + - A team's own values replace the scheme's for **any** list the team + owns values of, not for Status only. alpha.12 said "for Status + only", which was true of the fixture and not of the rule. + - "The project's scheme decides" holds for work items, issues, + requests, goals, strategic themes, retrospectives, environments, + regression tests and regression plans. For members, budgets, + projects, iterations, change sets, attachments and build runs every + active value is valid, with no scheme involved. + - The team step exists only on an instance with team workspaces + enabled. + - What a write enforces is narrower than alpha.12 implied, and is now + stated and tested: only the Status of a story or defect, and only + against its team. Any other list value, an inactive status and a + status outside the scheme are accepted. Moving a story or defect to + another project or team clears a status that is not valid there, + without a failure, unless the same write sets one. A team's + workflow rules can still refuse a status the list offers. This is + what one release does, not a contract: the product has added + enforcement over time, so follow the list and do not rely on a + value outside it being accepted. +- **An empty answer could be the server giving up.** When the server + cannot work out its rule for lack of context it answers no values and + no error. `client.lists` always sends the project; for a new + regression suite, whose rule goes through its regression plan, it now + refuses the call without `context: { RegressionPlan }` instead of + answering `[]`. +- **A list type is told from its own definition.** alpha.12 walked up + the type's ancestors (`StoryStatus`, then `Status`) to reach `List`, + which cost a type load and made a test serving captured meta.v1 types + serve `Status` too. Each inherited attribute already names the + ancestor that defines it, so the list type's own definition is + enough; nothing above it is loaded. (alpha.12's notes also named + `List` among the types loaded; it never was.) + +### Added + +- `client.lists`: `context` on the type-and-scope form (any attribute + of the asset to be), and `team: null` on the asset form (as if the + asset were on no team). +- The requests for several attributes, and the type loads before them, + go out together instead of one after another, as on every other read. + ### Changed - **A write the member has no right to make is said so, to a person, on diff --git a/README.md b/README.md index 3e7b87b..eda12fc 100644 --- a/README.md +++ b/README.md @@ -143,11 +143,16 @@ const done = await client.lists.value({ asset: "Story:1077", attribute: "Status" 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. +- **What decides: the team's own values first, then the asset type's rule.** If the asset is on a team (or you name one) and that team owns values of the list, those are the answer, for any list: a team that owns statuses is offered its statuses, one that owned priorities its priorities. `{ asset }` alone applies that, so there is nothing to switch on; `team: null` asks as if the asset were on no team. This first step exists only on an instance with team workspaces enabled. Otherwise the asset type's own rule applies: for work items, issues, requests, goals, strategic themes, retrospectives, environments, regression tests and regression plans, the active values selected in the project's scheme; for members, budgets, projects, iterations, change sets, attachments and build runs, every active value, with no scheme involved. +- **An inactive value is left out**, "no value" is never an entry, and the order is the values' `Order`. +- **Resolve before you write: the server checks very little.** On a write, one thing is enforced: the Status of a story or defect against its team. A status owned by a team is refused on a work item that is not on that team, and a status owned by no team is refused on a work item whose team has statuses of its own (`Violation'PrimaryWorkitemCannotHaveInvalidStatus`). Nothing else was checked on the release this was proved against: a status the project's scheme does not select, an inactive status, and any Priority, Source, Category or other list value from anywhere were all accepted. Do not build on that leniency. The product has added enforcement release by release and may refuse tomorrow what it accepts today; the list is the rule to follow, and this lookup is how to follow it. +- **A move can clear a status.** When a story or defect changes project or team and the same write does not set a Status, a status that is not valid in the new place (not among the new team's own, or else not selected in the new project's scheme) is set to empty, with no failure reported. Read the Status back after a move if you show it. +- **Valid is not the same as allowed.** A team can restrict which status may follow which, and which roles may make the change; a value `client.lists` offers can still be refused by such a workflow rule when written. - **`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`; a test that serves captured meta.v1 types must serve that whole chain, and the error names the type it could not load when one is missing); 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. +- **Only lists.** The server's endpoint takes no page and would answer every member, team or iteration it considers valid, so for `Owners`, `Team`, `Timebox` and any relation that is not to a list type, `client.lists` throws a `UsageError` before sending anything. Read those with `client.query({ from: "Member", filter, page })`, bounded like every other read. +- **Values are rows like any other.** `select` takes attributes of the value itself (`Order`, `RollupState`, `Team`): a number is a number, a Boolean a Boolean, a relation a Ref or `null`. Not a path, not a multi-value relation, and not a date, which the endpoint writes in the server's culture format. +- **An empty list means no value is valid, and the SDK keeps it meaning that.** The server answers "no values" also when it cannot work the rule out for lack of context, so the SDK always sends the project, and for a type whose rule needs more it asks you for it: `context: { RegressionPlan: "RegressionPlan:7" }` for a new regression suite. `context` takes any attribute of the asset to be. +- **Costs.** One request per attribute, sent together. Nothing is cached, because an administrator can change a scheme or a team's values at any time; the schema is cached as for every read, and telling a list from another relation needs the list type's own definition and nothing above it. - `client.fields.describe(type, scope).lists` says which of a form's attributes are list-typed and to which list type each points. ### Reference diff --git a/src/services/lists.ts b/src/services/lists.ts index 7f8e6fe..c4fe81a 100644 --- a/src/services/lists.ts +++ b/src/services/lists.ts @@ -3,8 +3,8 @@ * 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. + * team's own values and the asset type's rule for its lists (for work + * items, the scope's scheme); 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 @@ -13,30 +13,58 @@ * 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. + * Values are translated by the schema like any other row: the endpoint + * sends every value as a string, and a number, a Boolean and a relation + * come out as they do from `client.query` (spec 000 section 2). A date + * cannot be: the endpoint writes it in the server's culture format. */ 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 { scalar } from "../wire/assetApi"; 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. */ +/** + * 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 }; + | { + asset: Oid; + /** Answer as if the asset were on this team; `null` as if on no team (the asset's own team's values are then not considered). */ + team?: Oid | null; + } + | { + type: AssetTypeToken; + scope: Oid; + /** The team the new asset will be on. */ + team?: Oid; + /** + * More of the asset to be, for a type whose rule for its lists + * needs it: `{ RegressionPlan: "RegressionPlan:7" }` for a + * RegressionSuite. An attribute name to an OID or a plain value. + */ + context?: Readonly>; + }; -/** A valid value: the list entry's identity and name, and whatever else was selected. Values are as rest-1 sends them. */ +/** + * A valid value: the list entry's identity and name, and whatever else was + * selected, translated as on any read (a number is a number, a relation a + * Ref or null). + */ 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. */ + /** List-typed attributes of the asset's type, by bare name. One request each, sent together. */ attributes: readonly string[]; - /** More attributes of each value (`Order`, `RollupState`). `Name` is always returned. Not a date, and not a path through a relation. */ + /** + * More attributes of each value (`Order`, `RollupState`). `Name` is + * always returned. Not a date, not a multi-value relation and not a path + * through a relation. + */ select?: readonly string[]; }; @@ -57,22 +85,19 @@ export type ValueInput = ListTarget & { 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. + * Is `type` a list type? Told from its own definition, with no walk up to + * its ancestors: a type that descends from List has attributes it + * inherited from List (`Name`, `Order`, …), and each inherited attribute + * names the ancestor that defines it. That holds for every list type in + * the product's metamodel, the statuses two levels below List and an + * instance's custom dropdowns included, and for no other type. A type + * that cannot be loaded is an error of its own, not "not a list". */ 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; + if (type === "List") return true; + const loaded = await schema.load(type); + if (!loaded) throw new ApiError(`could not load the asset type ${type} to tell whether it is a list type`, 404, "NOT_FOUND", { type }); + return Object.values(loaded.Attributes).some((definition) => typeof definition.Base === "string" && definition.Base.startsWith("List.")); } /** @@ -87,13 +112,29 @@ export async function listTypeOf(schema: Schema, type: AssetTypeToken, attribute 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 { +/** + * Types whose rule for their lists needs more than a scope, and what it + * needs. Asked for a new asset without it, the server answers no values + * and no error, which would read as "nothing is valid here". (The product + * gives a regression suite no list attribute of its own; this matters for + * a custom dropdown added to one.) + */ +const NEEDS: Readonly> = { RegressionSuite: "RegressionPlan" }; + +/** Everything checked before anything is sent: the target, each attribute's list type, what may be selected. Answers each attribute's list type. */ +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); + const needed = NEEDS[type]; + if (!("asset" in target) && needed && !target.context?.[needed]) { + throw new UsageError(`${what}: the valid values of a new ${type} depend on its ${needed}. Give it as context: { ${needed}: "" }; without it the server answers no values and no error`); + } + // The type loads go out together, as for any read; the checks then run in the order the attributes were named. + const listTypes = await Promise.all(attributes.map((attribute) => listTypeOf(schema, type, attribute))); + const out = new Map(); + for (const [i, attribute] of attributes.entries()) { + const listType = listTypes[i]; if (listType === undefined) throw new UsageError(`${what}: ${type} has no attribute ${attribute}`); if (listType === null) { const related = schema.attribute(type, attribute)?.RelatedAsset; @@ -101,36 +142,51 @@ async function checked(schema: Schema, target: ListTarget, attributes: readonly ? `${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`); } + if (select?.length) await schema.load(listType); 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`); + if (selected.AttributeType === "Relation" && selected.IsMultivalue) throw new UsageError(`${what}: ${listType}.${path} is a multi-value relation, which this endpoint does not return in a form that can be read. Read it with client.query`); } + out.set(attribute, listType); } + return out; } -const paramsOf = (target: ListTarget, select: readonly string[] | undefined): validValues.ValidValuesParams => ({ select: ["Name", ...(select ?? []).filter((s) => s !== "Name")], sort: ["Order"], team: target.team }); +/** A row as the endpoint sent it (every value a string) in the model's shape, by the list type's schema. */ +function translated(row: ListValue, schema: Schema, listType: AssetTypeToken): ListValue { + const out: Record = { _oid: row._oid }; + for (const [key, value] of Object.entries(row)) { + if (key === "_oid") continue; + const definition = schema.attribute(listType, key); + if (definition?.AttributeType === "Relation") out[key] = typeof value === "string" && value && value !== "NULL" ? { _oid: momentless(value as Oid) } : null; + else out[key] = definition ? scalar(value, definition.AttributeType) : value; + } + return out as ListValue; +} -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)); +const paramsOf = (target: ListTarget, select: readonly string[] | undefined): validValues.ValidValuesParams => ({ select: ["Name", ...(select ?? []).filter((s) => s !== "Name")], sort: "Order", team: target.team, ...("asset" in target ? {} : { context: target.context }) }); + +async function read(transport: Transport, schema: Schema, target: ListTarget, attribute: string, listType: AssetTypeToken, select: readonly string[] | undefined): Promise { + const rows = "asset" in target + ? await validValues.forAsset(transport, target.asset, attribute, paramsOf(target, select)) + : await validValues.forNew(transport, target.type, attribute, target.scope, paramsOf(target, select)); + return rows.map((row) => translated(row, schema, listType)); +} /** * 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. + * which is a real answer). One request per attribute, sent together. */ 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 listTypes = await checked(schema, input, input.attributes, input.select, "lists.values"); + const answers = await Promise.all(input.attributes.map((attribute) => read(transport, schema, input, attribute, listTypes.get(attribute)!, input.select))); + return Object.fromEntries(input.attributes.map((attribute, i) => [attribute, answers[i]!])); } - const fold = (text: string): string => text.trim().toLocaleLowerCase(); const named = (rows: readonly ListValue[]): string => rows.map((r) => r.Name).join(", "); @@ -142,15 +198,18 @@ const named = (rows: readonly ListValue[]): string => rows.map((r) => r.Name).jo * 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). + * write the server checks one thing, the Status of a story or defect + * against its team (a team's status on a work item not on that team, or + * a status no team owns on a work item whose team has its own, is the + * command failure `Violation'PrimaryWorkitemCannotHaveInvalidStatus`). + * A status the scope's scheme does not select, an inactive one, and any + * other list value from anywhere are accepted. The team's own values are + * offered only on an instance that has team workspaces enabled. */ export async function value(transport: Transport, schema: Schema, input: ValueInput): Promise { - await checked(schema, input, [input.attribute], input.select, "lists.value"); + const listTypes = 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 all = await read(transport, schema, input, input.attribute, listTypes.get(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); diff --git a/src/wire/assetApi.ts b/src/wire/assetApi.ts index a2594ea..0140dc4 100644 --- a/src/wire/assetApi.ts +++ b/src/wire/assetApi.ts @@ -150,7 +150,7 @@ function translate(value: unknown, resolution: PathResolution, lookup: Attribute } /** A scalar as the model carries it, from the string the endpoint sent. A value that does not parse is left as sent. */ -function scalar(value: unknown, type: AttributeType): unknown { +export function scalar(value: unknown, type: AttributeType): unknown { if (value == null) return null; switch (type) { case "Numeric": diff --git a/src/wire/validValues.ts b/src/wire/validValues.ts index 55451ab..2e59efb 100644 --- a/src/wire/validValues.ts +++ b/src/wire/validValues.ts @@ -13,17 +13,43 @@ * 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 + * Both take `sel` (a comma list of the related type's attributes; + * without it the server returns Name and ID) and `sort`: ONE attribute + * name, ascending. A `sort` the related type has no attribute for is + * ignored without a word and the type's default order is used (for a + * list type that is Order). A base type is accepted * (`PrimaryWorkitem.Status`); an attribute the type does not have is a - * bare 400. + * bare 400. With no `context` at all the server assumes the system + * scope. The context may carry any attribute of the type, not only + * Scope and Team (`Scope=Scope:5,RegressionPlan=RegressionPlan:7`): the + * server sets them on an asset it makes up and asks what would be valid + * for that. * - * 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. + * What the answer means, for a relation to a list type (Status, + * Priority, …). Two rules are tried in order, and the first that finds + * anything is the answer: + * 1. The team's own values. When the asset is on a team (or `teamoid` + * / a Team in the context names one) and that team owns values of + * the related list type that are not closed, those are the answer, + * whatever the list: a team that owns statuses gets its statuses, + * and one that owned priorities would get its priorities. This rule + * exists only where the instance has team workspaces enabled. + * `teamoid=NULL` on the asset form skips it. + * 2. The asset type's own rule for its list attributes. For work + * items, issues, requests, goals, strategic themes, retrospectives, + * environments, regression tests and regression plans: the active + * values selected in the scope's Scheme. For a regression suite: the + * same, through its regression plan. For members, budgets, scopes, + * iterations, change sets, attachments and build runs: every active + * value, with no scheme involved. + * An inactive value is left out and there is no "none" entry. + * + * AN EMPTY ANSWER CAN BE A FAILURE. When the second rule cannot be worked + * out (the context lacks something it needs: no scope, or a regression + * suite with no regression plan) the server answers 200 with no values, + * not an error. A caller that leaves out part of the context cannot tell + * that from "nothing is valid here"; the service above refuses the cases + * it knows of before sending. * 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. @@ -36,10 +62,13 @@ * 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. + * Every value arrives as a string, whatever its type: a number as "115", + * a Boolean as "True", a relation as its OID token ("NULL" when empty), + * and a date in the server's culture format, which cannot be read back + * reliably. This module returns them as sent; the service translates them + * by the schema and refuses a date. */ -import { ApiError } from "../core/errors"; +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"; @@ -50,17 +79,23 @@ 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; + /** One attribute of the related type to sort by, ascending. One the type lacks is ignored by the server without an error. */ + sort?: string; + /** + * A team to answer for: the asset's own is used when it has one and this + * is not given. `null` on the asset form says "as if on no team" (the + * team's own values are then not considered). + */ + team?: Oid | null; + /** forNew only: more attributes of the asset to be, by name, for types whose rule needs them (a regression suite's RegressionPlan). */ + context?: Readonly>; } 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("&"); + const query = [...extra, params.select?.length ? `sel=${list(params.select)}` : "", params.sort ? `sort=${encodeURIComponent(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" }); @@ -73,12 +108,14 @@ async function read(transport: Transport, path: string, extra /** 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)}` : ""}`; + for (const [key, value] of Object.entries(params.context ?? {})) if (!/^[A-Za-z]\w*$/.test(key) || /[,=&#?\s]/.test(value)) throw new UsageError(`api/ValidValues context: ${key} must be an attribute name and its value free of commas, equals signs and spaces`); + const terms = { Scope: momentless(scope), ...(params.team ? { Team: momentless(params.team) } : {}), ...params.context }; + const context = Object.entries(terms).map(([key, value]) => `${key}=${value}`).join(","); 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); + return read(transport, `/api/ValidValues/${encodeURIComponent(type!)}/${encodeURIComponent(id!)}/${encodeURIComponent(attribute)}`, params.team === null ? ["teamoid=NULL"] : params.team ? [`teamoid=${momentless(params.team)}`] : [], params); } diff --git a/test/integration/lists.test.ts b/test/integration/lists.test.ts index c669a7a..8a153c8 100644 --- a/test/integration/lists.test.ts +++ b/test/integration/lists.test.ts @@ -40,7 +40,7 @@ describeInstance("valid values (live)", () => { 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({ team: { AssetType: "Team", Name: n("team with a process") }, plainTeam: { AssetType: "Team", Name: n("team without") }, priorityTeam: { AssetType: "Team", Name: n("team that owns a priority") }, 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"]!] }, @@ -49,13 +49,15 @@ describeInstance("valid values (live)", () => { 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") } + otherPriority: { AssetType: "WorkitemPriority", Name: named("otherPriority", "priority in no scheme") }, + teamPriority: { AssetType: "WorkitemPriority", Name: named("teamPriority", "priority owned by a team"), Team: o["priorityTeam"]! } }); 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"]! } + onPlainTeam: { AssetType: "Story", Name: n("story on the plain team"), Scope: o["scope"]!, Team: o["plainTeam"]! }, + onPriorityTeam: { AssetType: "Story", Name: n("story on the team that owns a priority"), Scope: o["scope"]!, Team: o["priorityTeam"]! } }); }, 120_000); @@ -88,9 +90,11 @@ describeInstance("valid values (live)", () => { 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. + // The endpoint sends every value as a string; the row has a number as a number, like any read. + expect(typeof forAsset.Status![0]!.Order).toBe("number"); + const asRead = await client.query<{ _oid: string; Order: unknown }>({ from: "StoryStatus" as never, select: ["Order"], filter: ["ID=$oid"], with: { $oid: forAsset.Status![0]!._oid }, page: { size: 1, start: 0 } }); + expect(forAsset.Status![0]!.Order).toBe(asRead[0]!.Order); + // This team owns statuses and no priority, so its statuses replace the scheme's and 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"]); @@ -99,6 +103,29 @@ describeInstance("valid values (live)", () => { expect(names((await client.lists.values({ asset: o["onPlainTeam"]!, attributes: ["Status"] })).Status!)).toEqual([label["inScheme"]!]); }); + it("the team's own values replace the scheme's for ANY list, not only Status: a team that owns a priority is offered that, and its Status still comes from the scheme; team: null asks as if on no team", async () => { + const offered = await client.lists.values({ asset: o["onPriorityTeam"]!, attributes: ["Priority", "Status"], select: ["Team"] }); + expect(offered.Priority).toEqual([{ _oid: o["teamPriority"]!, Name: label["teamPriority"]!, Team: { _oid: o["priorityTeam"]! } }]); + // A relation that is empty is null, as on any read. + expect(offered.Status).toEqual([{ _oid: o["inScheme"]!, Name: label["inScheme"]!, Team: null }]); + // As if on no team: the scheme's priority. + expect(names((await client.lists.values({ asset: o["onPriorityTeam"]!, team: null, attributes: ["Priority"] })).Priority!)).toEqual([label["priority"]!]); + expect(names((await client.lists.values({ asset: o["onTeam"]!, team: null, attributes: ["Status"] })).Status!)).toEqual([label["inScheme"]!]); + // And the owning team's priority is offered to nobody else. + expect(names((await client.lists.values({ asset: o["noTeam"]!, attributes: ["Priority"] })).Priority!)).toEqual([label["priority"]!]); + }); + + it("an empty answer can be the server giving up, not 'nothing is valid': with no scope in the context the endpoint answers 200 and no values", async () => { + // Why the service always sends a scope, and refuses a type whose rule needs more than that without it. + const empty = await t.request<{ total: number; Assets: unknown[] }>({ method: "GET", path: "/api/ValidValues/Story.Status/?context=&sel=Name", headers: { accept: "application/json" }, responseType: "json" }); + expect(empty).toMatchObject({ total: 0, Assets: [] }); + // Control: the same request with the scope has the value. + expect((await client.lists.values({ type: "Story", scope: o["scope"]!, attributes: ["Status"] })).Status).toHaveLength(1); + // A sort the list type has no attribute for is ignored without an error: the default order comes back. + const ignored = await t.request<{ Assets: { id: string }[] }>({ method: "GET", path: `/api/ValidValues/Story/${o["onTeam"]!.split(":")[1]}/Status?sel=Name&sort=Nmae`, headers: { accept: "application/json" }, responseType: "json" }); + expect(ignored.Assets.map((a) => a.id)).toEqual([o["teamFirst"]!, o["teamSecond"]!]); + }); + 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"]!]); @@ -132,6 +159,40 @@ describeInstance("valid values (live)", () => { await client.send([{ from: o["noTeam"]!, update: { Status: null } }], { throwOnFailure: true }); }); + // What the server accepts here is what it accepted when this was written, not a promise: the product has added enforcement + // over time. If a release starts refusing one of the "accepted" cases, that is the server getting stricter, not a fault in + // the SDK: change the expectation and the README's "Resolve before you write" with it. + it("on a write, only a story's or defect's Status is checked, and only against the team: any other list value is accepted wherever it comes from", async () => { + const set = async (story: string, update: Record) => { const done = await client.send([{ from: story, update }]); return done.failures.length ? done.failures[0]!.message : "accepted"; }; + // Priority, three ways the list says are not valid: the scheme's on a story whose team owns a priority, a team's on a story on no team, one in no scheme. + expect(await set(o["onPriorityTeam"]!, { Priority: o["priority"]! })).toBe("accepted"); + expect(await set(o["noTeam"]!, { Priority: o["teamPriority"]! })).toBe("accepted"); + expect(await set(o["noTeam"]!, { Priority: o["otherPriority"]! })).toBe("accepted"); + // Status against the team, both ways round: a team's status on a story not on that team, and a global one on a story whose team has its own. + expect(await set(o["noTeam"]!, { Status: o["teamFirst"]! })).toBe("Violation'PrimaryWorkitemCannotHaveInvalidStatus"); + expect(await set(o["onPlainTeam"]!, { Status: o["teamFirst"]! })).toBe("Violation'PrimaryWorkitemCannotHaveInvalidStatus"); + expect(await set(o["onTeam"]!, { Status: o["notInScheme"]! })).toBe("Violation'PrimaryWorkitemCannotHaveInvalidStatus"); + // An inactive status of the story's own team is not offered, and is accepted. + expect(await set(o["onTeam"]!, { Status: o["teamInactive"]! })).toBe("accepted"); + await client.send([{ from: o["onTeam"]!, update: { Status: null } }, { from: o["noTeam"]!, update: { Priority: null } }, { from: o["onPriorityTeam"]!, update: { Priority: null } }], { throwOnFailure: true }); + }); + + it("a status that stops being valid when a story moves is cleared without a word: the scheme is applied on a move, not on setting a status", async () => { + const status = async (story: string) => (await client.get<{ _oid: string; Status: { _oid: string } | null }>(story, ["Status"]))!.Status?._oid ?? null; + // On no team, with a status the scheme does not select (accepted, as above). + await client.send([{ from: o["noTeam"]!, update: { Status: o["notInScheme"]! } }], { throwOnFailure: true }); + expect(await status(o["noTeam"]!)).toBe(o["notInScheme"]!); + // Moved onto a team (one that owns no status): the write succeeds, and the status is gone. + const moved = await client.send([{ from: o["noTeam"]!, update: { Team: o["plainTeam"]! } }]); + expect(moved).toMatchObject({ modified: [o["noTeam"]!], failures: [] }); + expect(await status(o["noTeam"]!)).toBeNull(); + // Control: a status the scheme selects survives the same kind of move. + await client.send([{ from: o["noTeam"]!, update: { Status: o["inScheme"]! } }], { throwOnFailure: true }); + await client.send([{ from: o["noTeam"]!, update: { Team: null } }], { throwOnFailure: true }); + expect(await status(o["noTeam"]!)).toBe(o["inScheme"]!); + 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. diff --git a/test/unit/lists.test.ts b/test/unit/lists.test.ts index 400bef6..222d408 100644 --- a/test/unit/lists.test.ts +++ b/test/unit/lists.test.ts @@ -29,7 +29,7 @@ const client = (t: Transport) => new AgilityApiClient({ baseUrl: "https://x" }, 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" }); + 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" }]); @@ -47,7 +47,7 @@ describe("validValues wire", () => { 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. + // A 404 from the endpoint is thrown as it is, never read as an empty list. await expect(forNew(fake(() => { throw new ApiError("Not Found", 404); }), "Story", "Status", "Scope:5")).rejects.toMatchObject({ status: 404 }); }); }); @@ -57,7 +57,8 @@ describe("client.lists", () => { 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" }]); + // The endpoint sends every value as a string; the row has them as any read has them: Order (a Rank) is a number. + 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); @@ -119,16 +120,61 @@ describe("client.lists", () => { 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. + it("a list type is told from its own definition: nothing above it is loaded, so a schema with Story and StoryStatus alone is enough (a chat-bot and a CLI consumer finding)", async () => { 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" }); + const only = (keep: (name: string) => boolean) => new FakeAgilityClient({ metamodel: { AssetTypes: Object.fromEntries(Object.entries(whole.AssetTypes).filter(([name]) => keep(name))) as MetamodelDocument["AssetTypes"] } }); + // StoryStatus sits two levels below List (through Status); neither ancestor is needed or asked for. + const lean = only((name) => name === "Story" || name === "StoryStatus").onValues({ Status: [{ _oid: "StoryStatus:135", Name: "Done", Order: "117" }] }); + expect(await lean.lists.values({ asset: "Story:1", attributes: ["Status"], select: ["Order"] })).toEqual({ Status: [{ _oid: "StoryStatus:135", Name: "Done", Order: 117 }] }); + expect(lean.schema.loaded.sort()).toEqual(["Story", "StoryStatus"]); + // Every type under List in the metamodel is recognised by that mark, and no other type is. + const base = (name: string): string | undefined => whole.AssetTypes[name]?.Base?.nameref; + const underList = (name: string): boolean => { for (let t: string | undefined = name, i = 0; t && i < 20; t = base(t), i += 1) if (t === "List") return true; return false; }; + const marked = (name: string) => Object.values(whole.AssetTypes[name]!.Attributes).some((a) => a.Base?.tokenref.startsWith("List.")); + for (const name of Object.keys(whole.AssetTypes)) if (name !== "List") expect([name, marked(name)]).toEqual([name, underList(name)]); + // The list type itself missing is said as that, never as "not a list" with advice to use another read. + const error = await only((name) => name !== "StoryStatus").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 StoryStatus to tell whether it 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 () => { + it("values come out as on any read: a number, a Boolean, a relation as a Ref or null; a multi-value relation cannot be selected", async () => { + // As the endpoint sends them: every value a string, an empty relation as "NULL". + const doc = { _type: "Assets", total: 2, pageSize: 2147483647, pageStart: 0, Assets: [ + { _type: "Asset", href: "", id: "StoryStatus:135", Attributes: { Name: { _type: "Attribute", name: "Name", value: "Done" }, Order: { _type: "Attribute", name: "Order", value: "117" }, Inactive: { _type: "Attribute", name: "Inactive", value: "False" }, RollupState: { _type: "Attribute", name: "RollupState", value: "Closed" }, Team: { _type: "Attribute", name: "Team", value: "Team:9" } } }, + { _type: "Asset", href: "", id: "StoryStatus:136", Attributes: { Name: { _type: "Attribute", name: "Name", value: "Held" }, Order: { _type: "Attribute", name: "Order", value: "118" }, Inactive: { _type: "Attribute", name: "Inactive", value: "True" }, RollupState: { _type: "Attribute", name: "RollupState", value: "Active" }, Team: { _type: "Attribute", name: "Team", value: "NULL" } } } + ] }; + const answer = await client(fake(() => doc)).lists.values({ asset: "Story:1", attributes: ["Status"], select: ["Order", "Inactive", "RollupState", "Team"] }); + expect(answer.Status).toEqual([ + { _oid: "StoryStatus:135", Name: "Done", Order: 117, Inactive: false, RollupState: "Closed", Team: { _oid: "Team:9" } }, + { _oid: "StoryStatus:136", Name: "Held", Order: 118, Inactive: true, RollupState: "Active", Team: null } + ]); + await expect(client(fake(() => doc)).lists.values({ asset: "Story:1", attributes: ["Status"], select: ["SelectedInSchemes"] })).rejects.toMatchObject({ kind: "usage", message: expect.stringContaining("multi-value relation") }); + }); + + it("the requests for several attributes go out together, like the type loads; the context can carry more of the asset to be, and a type whose rule needs it is refused without it", async () => { + let open = 0, most = 0; + const slow: Transport & { calls: RequestOptions[] } = fake(() => all); + const inner = slow.request; + slow.request = (async (o: RequestOptions) => { open += 1; most = Math.max(most, open); await new Promise((r) => setTimeout(r, 5)); open -= 1; return inner(o); }) as Transport["request"]; + const answer = await client(slow).lists.values({ asset: "Story:1077", attributes: ["Status", "Priority", "Source"] }); + expect(Object.keys(answer)).toEqual(["Status", "Priority", "Source"]); + expect(most).toBe(3); + // More context: a regression suite's valid values depend on its plan. Without it the server answers nothing and no error, so the service says so first. + // (The product gives a regression suite no list attribute; a custom dropdown on one is the case. The fake has it as scripted.) + const suites = new FakeAgilityClient().onValues({ Custom_Tier: [{ _oid: "Custom_Tier:1", Name: "Gold" }] }); + await expect(suites.lists.values({ type: "RegressionSuite", scope: "Scope:5", attributes: ["Custom_Tier"] })).rejects.toMatchObject({ kind: "usage", message: expect.stringContaining('context: { RegressionPlan: "" }') }); + expect(suites.valuesAsked).toHaveLength(0); + expect(await suites.lists.values({ type: "RegressionSuite", scope: "Scope:5", context: { RegressionPlan: "RegressionPlan:7" }, attributes: ["Custom_Tier"] })).toEqual({ Custom_Tier: [{ _oid: "Custom_Tier:1", Name: "Gold" }] }); + expect(suites.requests.at(-1)!.path).toBe("/api/ValidValues/RegressionSuite.Custom_Tier/?context=Scope=Scope:5,RegressionPlan=RegressionPlan:7&sel=Name&sort=Order"); + const t = fake(() => ({ ...all, total: 0, Assets: [] })); + await expect(client(t).lists.values({ type: "Story", scope: "Scope:5", context: { "Bad Key": "x" }, attributes: ["Status"] })).rejects.toMatchObject({ kind: "usage" }); + // team: null on an asset says "as if on no team": the team's own values are not considered. + await client(t).lists.values({ asset: "Story:1077", team: null, attributes: ["Status"] }); + expect(t.calls.at(-1)!.path).toBe("/api/ValidValues/Story/1077/Status?teamoid=NULL&sel=Name&sort=Order"); + }); + + it("a failure is never an empty list: an error from the endpoint is thrown", 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 });