From c5431f3b01aecd959528ce87d2363570004005c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:29:22 +0000 Subject: [PATCH 01/11] Search is client.query with find: documented, proved live, and an empty find is a usage error The README sent text search to rest-1's list; query.v1 honours find and findin across types. A Searching section states the server's matching rules, each with a live test and a control. An empty find answered no rows (the server's answer to a search for nothing); it now throws a UsageError before any request. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 17 ++++- README.md | 30 +++++++- src/client.ts | 14 +++- test/integration/search.test.ts | 129 ++++++++++++++++++++++++++++++++ test/unit/client.test.ts | 11 +++ 5 files changed, 197 insertions(+), 4 deletions(-) create mode 100644 test/integration/search.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index a5dd68c..556e049 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,22 @@ ## Unreleased -Nothing in the package changes. +### Changed + +- **A read with an empty `find` throws a `UsageError`** (`kind: "usage"`, + nothing is sent), on `query`, `queries`, `queryPage`, `pages`, `all` and + `data.list`. It used to answer no rows, because that is what the server + answers to a search for nothing, and no rows read as "nothing matches". + Migration: when the search box is empty, leave `find` out of the query + (or do not send the read). + +### Documented + +- Text search is `client.query` with `find` and `findin`: README, + "Searching", with the server's matching rules, each proved by a live + test. The README's table no longer sends a search to `client.data.list`. + +### Repository - The repository has runnable examples, one per task, in `examples/` (they are not in the published package). They are compiled by diff --git a/README.md b/README.md index 13ec445..1097b37 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,8 @@ npm test | One asset | `client.get(oid, select)` | Null when nothing has that OID. | | Rows and how many there are | `client.queryPage(q)` | `{ rows, total, more }`. | | Everything, page by page | `client.pages(q, { limit })` / `client.all(q, { limit })` | Bounded: default limit 1000. | -| Text search across types, a total, deleted assets | `client.data.list(type, params)` | rest-1: `find` / `findin`, `Story.Number` from `BaseAsset`, `deleted: true`. | +| Text search, one type or many | `client.query({ from, find, findin, … })` | An ordinary read with two more keys; see "Searching" below. `queryPage` adds the total. | +| Deleted assets; one page across unrelated types with each type's Number | `client.data.list(type, params)` | rest-1: `deleted: true`; `Story.Number` selected from `BaseAsset`. | | An asset's past versions | `client.history(oid, params)` | One row per version; `_oid` carries the moment. | | Who am I | `client.me()` | The member the credentials belong to. | | Numbers and OIDs a person typed | `client.resolve.numbers([...])` / `client.resolve.refs([...])` | Answered as rows. One request for numbers of any mix of types. | @@ -68,6 +69,33 @@ Every row follows one rule, whichever call read it: **a relation you select is a A row's identity is `_oid`: it is the key the server sends, underscored so it cannot collide with an attribute (the identity attribute is `ID`). Rows, Refs, resolved assets, attachments and the assets on a receipt all carry it; a record that only mentions an asset (a receipt's `described` entries, a `drifted` entry) says `oid`. +### Searching + +A text search is a read with `find` (the text) and `findin` (the attributes to look in). It composes with `filter`, `sort` and `page`, and `queryPage` answers its total. + +```ts +const hits = await client.query({ + from: "Workitem", // stories, defects, epics, themes, tasks, tests, test sets + select: ["Name", "Number", "AssetType"], + find: "warehouse ship*", + findin: ["Name", "Number"], + page: { size: 25, start: 0 } +}); +``` + +What the server does with the text (each of these is a live test in `test/integration/search.test.ts`): + +- **Every word must match**, in any order, in any letter case. Punctuation separates words. +- **Whole words**, with the server's stemming ("shipping" finds "ship"). Part of a word finds nothing unless it ends in `*`: `integrat*` finds "integration". A leading `*` does not work. +- **A number is text too**: `find: "S-01001", findin: ["Number"]` finds that story, in either case. +- **Always send `findin`.** Without it the attributes searched depend on the type. +- **The text index trails a write by a few seconds.** An asset created a moment ago is found by its Number at once and by its words shortly after; do not search by name for what you just created. +- Closed assets are found; deleted ones are not. +- An attribute `findin` does not know is a refused query (`QUERY_REJECTED`), not an empty result. +- **An empty `find` is a usage error.** The server answers a search for nothing with no rows, which would read as "nothing matches"; leave `find` out to read without searching. + +`from` decides how wide the search is. `Workitem` covers the backlog types and has `Number`. `BaseAsset` is every asset (members, issues, requests, and anything else that carries the words, a notification included), so narrow it with a filter on `AssetType`; it has no `Number` of its own, and query.v1 refuses a type-qualified select such as `Story.Number` there. For one page across unrelated types with their Numbers, either send one typed query per type in a single request with `client.queries([...])`, or use `client.data.list("BaseAsset", { select: ["Name", "Story.Number", "Issue.Number"], … })`, which rest-1 answers with the value under `Number`. + 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`. ### Reference diff --git a/src/client.ts b/src/client.ts index 410da5c..ab631c1 100644 --- a/src/client.ts +++ b/src/client.ts @@ -73,7 +73,14 @@ const dressed = new WeakSet(); /** Every read is bounded: the type says so, and for a caller the type did not reach this says so before any request (not even a schema load) is sent. */ function bounded(qs: readonly assetApi.QueryBody[]): void { - for (const q of qs) if (!q.page) throw new UsageError(`query of ${q.from} without a page: every read must be bounded`); + for (const q of qs) { + if (!q.page) throw new UsageError(`query of ${q.from} without a page: every read must be bounded`); + searchable(String(q.from), q.find); + } +} +/** A text search for nothing: the server answers it with zero rows, which would read as "nothing matches". */ +function searchable(from: string, find: string | undefined): void { + if (find !== undefined && !String(find).trim()) throw new UsageError(`query of ${from} with an empty \`find\`: the server answers a search for nothing with no rows, not all rows; leave \`find\` out to read without searching`); } const ME_SELECT = ["Name", "Username", "Nickname", "Email"]; @@ -291,7 +298,10 @@ export class AgilityApiClient { * everyday read.) */ readonly data = { - list: (type: string, params: rest1.ReadParams) => rest1.list(this.transport, type, params) + list: (type: string, params: rest1.ReadParams): Promise> => { + try { searchable(type, params.find); } catch (error) { return Promise.reject(error); } + return rest1.list(this.transport, type, params); + } }; /** diff --git a/test/integration/search.test.ts b/test/integration/search.test.ts new file mode 100644 index 0000000..e031cfe --- /dev/null +++ b/test/integration/search.test.ts @@ -0,0 +1,129 @@ +import { afterAll, beforeAll, expect, it } from "vitest"; +import { AgilityApiClient } from "../../src/client"; +import { queryV1 } from "../../src/wire"; +import { deleteFixtures, describeInstance, instance } from "./instance"; + +/** + * Text search against a real instance: `find` and `findin` on an ordinary + * read. Brings its own assets, named with a word that exists nowhere else, + * so each expectation has an exact answer and each "it found rows" has a + * control that finds none. What only the server can prove: that query.v1 + * honours `find` across types, how words match, that the text index trails + * a write, what an empty search answers, and where rest-1 is still the + * only way. + */ +describeInstance("search (live)", () => { + const t = instance!.transport; + const client = new AgilityApiClient({ baseUrl: instance!.url }, { transport: t }); + const page = { size: 10, start: 0 }; + // Letters only, so the server's word splitting cannot break it. + const word = `sdkfind${[...Date.now().toString(36)].map((c) => String.fromCharCode(97 + (parseInt(c, 36) % 26))).join("")}`; + const created: string[] = []; + let story = "", defect = "", issue = "", gone = "", storyNumber = "", issueNumber = ""; + const found = async (q: Partial[0]> & { find: string }) => + (await client.query<{ _oid: string }>({ from: "Workitem", select: ["Name"], findin: ["Name"], sort: ["ID"], page, ...q })).map((r) => r._oid); + + beforeAll(async () => { + const made = await client.send([ + { AssetType: "Story", Name: `sdk-integration ${word} warehouse shipping`, Description: `described as ${word}desc`, Scope: "Scope:0" }, + { AssetType: "Defect", Name: `sdk-integration ${word} accounting`, Scope: "Scope:0" }, + { AssetType: "Issue", Name: `sdk-integration ${word} blocker`, Scope: "Scope:0" }, + { AssetType: "Story", Name: `sdk-integration ${word} deleted`, Scope: "Scope:0" } + ], { throwOnFailure: true }); + [story, defect, issue, gone] = made.created as [string, string, string, string]; + created.push(story, defect, issue, gone); + await client.send([{ from: gone, execute: "Delete" }, { from: defect, execute: "QuickClose" }], { throwOnFailure: true }); + storyNumber = String((await client.get(story, ["Number"]))!.Number); + issueNumber = String((await client.get<{ _oid: string; Number: string }>(issue, ["Number"]))!.Number); + // The text index trails a write by a few seconds (measured: found after 4 s, not after 1 s), so wait for it. + for (let i = 0; i < 20 && (await found({ from: "BaseAsset", find: `${word} blocker` })).length === 0; i += 1) await new Promise((r) => setTimeout(r, 1500)); + }, 60_000); + afterAll(() => deleteFixtures(t, created)); + + it("a new asset is found by its Number at once, and by its words only once the text index has caught up", async () => { + const made = await client.send([{ AssetType: "Story", Name: `sdk-integration ${word}fresh`, Scope: "Scope:0" }], { throwOnFailure: true }); + const fresh = made.created[0]!; + created.push(fresh); + const number = String((await client.get(fresh, ["Number"]))!.Number); + expect(await found({ find: number, findin: ["Number"] })).toEqual([fresh]); + // By name it appears within seconds, not necessarily yet: so this only asserts that it does appear. + let seen: string[] = []; + for (let i = 0; i < 20 && !seen.length; i += 1) { await new Promise((r) => setTimeout(r, 1500)); seen = await found({ find: `${word}fresh` }); } + expect(seen).toEqual([fresh]); + }, 60_000); + + it("find on a type finds by a word of the name; a word nothing has finds nothing (the control)", async () => { + expect(await found({ from: "Story", find: word })).toEqual([story]); + expect(await found({ from: "Story", find: `${word}nothing` })).toEqual([]); + }); + + it("from Workitem the rows are of mixed types, each with its Number; BaseAsset reaches types outside Workitem", async () => { + const rows = await client.query({ from: "Workitem", select: ["Name", "Number", "AssetType"], find: word, findin: ["Name"], sort: ["ID"], page }); + expect(rows.map((r) => [r._oid, r.AssetType])).toEqual([[story, "Story"], [defect, "Defect"]]); + expect(rows[0]!.Number).toBe(storyNumber); + // BaseAsset is every asset, so anything else naming the word matches too (an instance that notifies + // someone of each new item has a Message per fixture): narrow by type when that is not wanted. + const all = await client.query({ from: "BaseAsset", select: ["Name", "AssetType"], find: word, findin: ["Name"], filter: ["AssetType=$types"], with: { $types: ["Story", "Defect", "Issue"] }, sort: ["ID"], page }); + expect(all.map((r) => r._oid)).toEqual([story, defect, issue]); + }); + + it("a number is found in Number, in any letter case", async () => { + expect(await found({ find: storyNumber, findin: ["Number"] })).toEqual([story]); + expect(await found({ find: storyNumber.toLowerCase(), findin: ["Number"] })).toEqual([story]); + }); + + it("every word must match, in any order; whole words only, unless the word ends in *", async () => { + expect(await found({ find: `shipping ${word} warehouse` })).toEqual([story]); + expect(await found({ find: `${word} warehouse accounting` })).toEqual([]); + expect(await found({ find: word.toUpperCase() })).toEqual([story, defect]); + // Punctuation separates words, and the server stems them: "ship" finds "shipping". + expect(await found({ find: `${word}-warehouse, shipping!` })).toEqual([story]); + expect(await found({ find: `${word} ship` })).toEqual([story]); + expect(await found({ find: word.slice(0, -2) })).toEqual([]); + expect(await found({ find: `${word.slice(0, -2)}*`, filter: ["ID=$ids"], with: { $ids: [story, defect] } })).toEqual([story, defect]); + }); + + it("findin chooses the attributes searched: a word of the description is found there and not in the name", async () => { + expect(await found({ find: `${word}desc`, findin: ["Description"] })).toEqual([story]); + expect(await found({ find: `${word}desc`, findin: ["Name"] })).toEqual([]); + expect(await found({ find: `${word}desc`, findin: ["Name", "Description"] })).toEqual([story]); + }); + + it("find composes with filter, sort and page; a closed asset is found and a deleted one is not", async () => { + expect((await client.get(defect, ["IsClosed"]))?.IsClosed).toBe(true); + expect(await found({ find: word, filter: ["AssetType='Defect'"] })).toEqual([defect]); + expect(await found({ find: word, sort: ["-ID"], page: { size: 1, start: 0 } })).toEqual([defect]); + expect(await found({ find: word, sort: ["-ID"], page: { size: 1, start: 1 } })).toEqual([story]); + expect(await found({ from: "Story", find: `${word} deleted` })).toEqual([]); + }); + + it("the server answers a search for nothing with no rows and no error, which is why the client refuses one", async () => { + expect(await queryV1.query(t, { from: "Story", select: ["Name"], find: "", findin: ["Name"], page })).toEqual([]); + await expect(client.query({ from: "Story", select: ["Name"], find: " ", findin: ["Name"], page })).rejects.toMatchObject({ kind: "usage", status: 0 }); + }); + + it("an attribute findin does not know is a refused query, not an empty result", async () => { + await expect(found({ find: word, findin: ["NoSuchAttribute"] })).rejects.toMatchObject({ status: 400, code: "QUERY_REJECTED" }); + }); + + it("queryPage answers a search with its total and whether more follow", async () => { + const first = await client.queryPage({ from: "Workitem", select: ["Name"], find: word, findin: ["Name"], sort: ["ID"], page: { size: 1, start: 0 } }); + expect(first).toMatchObject({ total: 2, more: true }); + expect(first.rows.map((r) => r._oid)).toEqual([story]); + const rest = await client.queryPage({ from: "Workitem", select: ["Name"], find: word, findin: ["Name"], sort: ["ID"], page: { size: 5, start: 1 } }); + expect(rest).toMatchObject({ total: 2, more: false }); + expect(rest.rows.map((r) => r._oid)).toEqual([defect]); + }); + + it("what only rest-1's list answers: deleted assets, and one page across every type with each type's Number", async () => { + const deleted = await client.data.list("Story", { find: `${word} deleted`, findin: ["Name"], select: ["Name"], deleted: true, page }); + expect(deleted.rows.map((r) => r._oid.split(":").slice(0, 2).join(":"))).toEqual([gone]); + // query.v1 refuses a type-qualified select on a base type; rest-1 answers it, as `Number`. + const mixed = { from: "BaseAsset", select: ["Name", "Story.Number", "Issue.Number"], find: word, findin: ["Name"], sort: ["ID"], page }; + await expect(client.query<{ _oid: string }>(mixed)).rejects.toMatchObject({ status: 400, code: "QUERY_REJECTED" }); + const numbered = await client.data.list<{ _oid: string; Number?: string }>("BaseAsset", { find: word, findin: ["Name"], select: ["Name", "Story.Number", "Issue.Number"], filter: ["AssetType='Story','Defect','Issue'"], sort: ["ID"], page }); + expect(numbered.rows.map((r) => r._oid)).toEqual([story, defect, issue]); + expect(JSON.stringify(numbered.rows)).toContain(storyNumber); + expect(JSON.stringify(numbered.rows)).toContain(issueNumber); + }); +}); diff --git a/test/unit/client.test.ts b/test/unit/client.test.ts index 95caa2a..b08939c 100644 --- a/test/unit/client.test.ts +++ b/test/unit/client.test.ts @@ -121,6 +121,17 @@ describe("client: reads", () => { await expect(client.all({ from: "Story", select: ["Name"] } as never)).rejects.toBeInstanceOf(UsageError); }); + it("a search for nothing is a usage error on every read, before any request: the server would answer it with no rows", async () => { + const t = fake(() => { throw new Error("nothing may be sent"); }); + const client = new AgilityApiClient({ baseUrl: "https://agility.example.com/I" }, { transport: t }); + const page = { size: 5, start: 0 }; + const empty = { from: "Story", select: ["Name"], find: " ", findin: ["Name"], page }; + for (const read of [() => client.query(empty), () => client.queries([{ from: "Story", page }, empty]), () => client.queryPage(empty), () => client.all(empty), () => client.data.list("Story", { find: "", page })]) { + await expect(read()).rejects.toMatchObject({ kind: "usage", status: 0, message: expect.stringContaining("empty `find`") }); + } + expect(t.calls).toEqual([]); + }); + it("me asks for the member whose IsSelf is true", async () => { const t = fake(() => [[{ _oid: "Member:1000", Name: "SDK Test Account", Username: "sdk-test-account", Nickname: "SDK", Email: "" }]]); const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, types: schema().cache }); From 4a14f979254599800d6b4f307a3b117f708fc221 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:38:08 +0000 Subject: [PATCH 02/11] client.search: text search across asset types, and client.deleted; 1.0.0-alpha.9 One page of mixed rows in one server-side order with the total. types is required; select and findin take plain attribute names and each row has every selected key under that name, null where its type has no such attribute, so nothing type-qualified is written or read. rest-1 answers it today (it alone takes a subtype's attribute from a base type on instances before the release that lets api/asset); the route is not part of the contract. client.deleted reads deleted assets. The fake has onSearch. Spec 000 states the one place a row carries a key its type lacks. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 30 ++++++- README.md | 30 ++++++- examples/10-search.ts | 39 +++++++++ examples/README.md | 3 +- package-lock.json | 4 +- package.json | 2 +- specs/000-layers.md | 13 +++ src/client.ts | 28 ++++++ src/index.ts | 1 + src/services/index.ts | 1 + src/services/search.ts | 149 ++++++++++++++++++++++++++++++++ src/testing/index.ts | 43 +++++++++ test/integration/search.test.ts | 63 +++++++++++++- test/unit/search.test.ts | 129 +++++++++++++++++++++++++++ 14 files changed, 523 insertions(+), 12 deletions(-) create mode 100644 examples/10-search.ts create mode 100644 src/services/search.ts create mode 100644 test/unit/search.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 556e049..9db90de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,25 @@ # Changelog -## Unreleased +## 1.0.0-alpha.9 + +### Added + +- **`client.search(text, { types, select?, findin?, filter?, where?, + with?, sort?, page })`**: text search across asset types, answered as + `{ rows, total, more }`: one page of mixed rows in one server-side + order. `types` is required. `select` and `findin` take plain attribute + names, and each row has every selected key under that name: its value + if the row's type defines the attribute, `null` if not, so a Story and a + Request both have `Number`. Nothing type-qualified is written or read. + A consumer that built this from `client.data.list("BaseAsset", …)` with + one `.Number` select per type replaces it with one call. + (a CLI consumer and a chat-bot consumer.) +- **`client.deleted(type, params)`**: deleted assets of a type, as + `{ rows, total, more }`. +- `FakeAgilityClient.onSearch(rows)` and `fake.searched`, to test code + that searches. +- `@versionone/agility-sdk/services` has `search`. The root exports the + types `SearchOptions`, `SearchResult`, `SearchRow`. ### Changed @@ -13,9 +32,12 @@ ### Documented -- Text search is `client.query` with `find` and `findin`: README, - "Searching", with the server's matching rules, each proved by a live - test. The README's table no longer sends a search to `client.data.list`. +- README, "Searching": a search within one type or family is + `client.query` with `find` and `findin`; across types it is + `client.search`. The server's matching rules are stated (every word, + whole words, stemming, `*`, the few seconds the text index trails a + write), each proved by a live test. The README's table no longer sends + a search to `client.data.list`. ### Repository diff --git a/README.md b/README.md index 1097b37..e8ee618 100644 --- a/README.md +++ b/README.md @@ -49,8 +49,9 @@ npm test | One asset | `client.get(oid, select)` | Null when nothing has that OID. | | Rows and how many there are | `client.queryPage(q)` | `{ rows, total, more }`. | | Everything, page by page | `client.pages(q, { limit })` / `client.all(q, { limit })` | Bounded: default limit 1000. | -| Text search, one type or many | `client.query({ from, find, findin, … })` | An ordinary read with two more keys; see "Searching" below. `queryPage` adds the total. | -| Deleted assets; one page across unrelated types with each type's Number | `client.data.list(type, params)` | rest-1: `deleted: true`; `Story.Number` selected from `BaseAsset`. | +| Text search across asset types | `client.search(text, { types, page })` | One page of mixed rows, one order, `{ rows, total, more }`; `Number` on every row whose type has one. See "Searching". | +| Text search within one type or family | `client.query({ from, find, findin, … })` | An ordinary read with two more keys. `queryPage` adds the total. | +| Deleted assets | `client.deleted(type, params)` | No other read returns one. | | An asset's past versions | `client.history(oid, params)` | One row per version; `_oid` carries the moment. | | Who am I | `client.me()` | The member the credentials belong to. | | Numbers and OIDs a person typed | `client.resolve.numbers([...])` / `client.resolve.refs([...])` | Answered as rows. One request for numbers of any mix of types. | @@ -94,7 +95,29 @@ What the server does with the text (each of these is a live test in `test/integr - An attribute `findin` does not know is a refused query (`QUERY_REJECTED`), not an empty result. - **An empty `find` is a usage error.** The server answers a search for nothing with no rows, which would read as "nothing matches"; leave `find` out to read without searching. -`from` decides how wide the search is. `Workitem` covers the backlog types and has `Number`. `BaseAsset` is every asset (members, issues, requests, and anything else that carries the words, a notification included), so narrow it with a filter on `AssetType`; it has no `Number` of its own, and query.v1 refuses a type-qualified select such as `Story.Number` there. For one page across unrelated types with their Numbers, either send one typed query per type in a single request with `client.queries([...])`, or use `client.data.list("BaseAsset", { select: ["Name", "Story.Number", "Issue.Number"], … })`, which rest-1 answers with the value under `Number`. +`from` decides how wide that read is: one type, or a family (`Workitem` is the backlog types, and has `Number`). It cannot give one page of unrelated types with their own attributes: `BaseAsset` is every asset but has no `Number`, and the query endpoints refuse a subtype's attribute there. That is what `client.search` is for. + +#### Across types: `client.search` + +```ts +const { rows, total, more } = await client.search("warehouse ship*", { + types: ["Story", "Defect", "Epic", "Request", "Issue", "Goal"], // required: there is no default + select: ["Name", "Number", "AssetState", "Scope.Name", "Owners", "Owner"], + filter: ["AssetState!='Closed'"], + sort: ["-ChangeDateUTC"], + page: { size: 25, start: 0 } +}); +// rows[0].Number is "S-01042" for a Story and "R-01011" for a Request +``` + +- **One request, one order across every type, and the total.** The matching rules above apply. +- **`types` is required**: concrete types, at least one. A default would silently leave types out. +- **You name an attribute once, plainly, and each row has that key**: its value if the row's type defines it, `null` if not (`Owners` is null on a Request, `Owner` null on a Story; the SDK does not merge differently named attributes). A name none of the types defines is a usage error that lists the types. +- `select` defaults to `Name`, `Number`, `AssetType`, `AssetState`; `findin` defaults to `Name` and `Number`. +- A relation is a bare `{ _oid }`; ask for a display value as a path (`"Scope.Name"`, `"Owners.Name"`). +- `filter` and `sort` are sent as written. A filter term on an attribute only some types have is type-qualified by you: `"(Workitem.Owners.IsSelf='true'|Request.Owner.IsSelf='true')"`. +- Deleted assets are never found; `client.deleted(type, params)` reads those. +- To find one asset by its exact number, do not search: `client.resolve.numbers(["S-01042"])` is exact and does not wait for the text index. 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`. @@ -141,6 +164,7 @@ expect(fake.sent[0]).toEqual([{ from: "Story:1", execute: "QuickClose" }]); - `onQuery(match, rows)` answers every read (`query`, `get`, `queryPage`, `pages`, …). A list is the whole result: the fake pages it and answers a read by OID with that row. A function gets the query and answers one page. A read nothing was scripted for throws; it never looks like an empty result. - Writes need no script: a create answers a new OID, an update or operation by OID answers that OID. `onSend` scripts anything else, failures included. +- `onSearch(rows)` answers `client.search`: the fake pages the rows, reports the total, and cuts each row to the selected keys; `fake.searched` is what was asked. It sends no request. - `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. - `onList(type, rows)` answers `client.data.list` the same way. `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. diff --git a/examples/10-search.ts b/examples/10-search.ts new file mode 100644 index 0000000..eb5343a --- /dev/null +++ b/examples/10-search.ts @@ -0,0 +1,39 @@ +/** + * Searching: across asset types with `client.search`, and within one + * family of types with `find` on an ordinary read. Writes nothing. + * + * V1_URL=… V1_ACCESS_TOKEN=… node examples/10-search.ts [text] + */ +import { AgilityApiClient } 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 text = process.argv[2] ?? "sample"; + +// One page across unrelated types, in one order, with the total. `types` +// is required: a default would silently leave some out. Each name in +// `select` is written once, plainly, and every row has that key: its value +// if the row's type has the attribute, null if not. +const { rows, total, more } = await client.search(text, { + types: ["Story", "Defect", "Epic", "Request", "Issue", "Goal"], + select: ["Name", "Number", "AssetType", "Scope.Name", "Estimate"], + filter: ["AssetState!='Closed'"], + sort: ["-ChangeDateUTC"], + page: { size: 5, start: 0 } +}); +console.log(`"${text}": ${rows.length} of ${total} open assets${more ? " (more follow)" : ""}`); +for (const row of rows) console.log(` ${row.Number} ${row.AssetType} ${row.Name} [${row["Scope.Name"]}] estimate ${row.Estimate ?? "-"}`); + +// Within one family, a search is a read with two more keys, typed like any +// read. Every word must match; a word matches whole, or by its start with *. +const stories = await client.query({ from: "Story", select: ["Name", "Number"], find: `${text}*`, findin: ["Name"], page: { size: 3, start: 0 } }); +console.log(`stories whose name has a word starting "${text}": ${stories.map((s) => s.Number).join(", ") || "none on this page"}`); + +// A search for nothing is refused before any request: the server would +// answer it with no rows, which would read as "nothing matches". +try { + await client.search(" ", { types: ["Story"], page: { size: 1, start: 0 } }); +} catch (error) { + console.log(`an empty search: ${(error as Error).message.split(":")[0]}`); +} diff --git a/examples/README.md b/examples/README.md index 0bc28d5..8e9b545 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,6 +1,6 @@ # Examples -Nine short programs, one per task, each runnable as it stands. Read them +Ten 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? | @@ -14,6 +14,7 @@ in order; each says at the top what it does. | `07-testing.ts` | `FakeAgilityClient`: test your own code with no instance | no instance at all | | `08-custom-transport.ts` | A `Transport` of your own (a timed wrapper), checked with `transportConformance` | no; a live read only if an instance is set | | `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 | ## Running one diff --git a/package-lock.json b/package-lock.json index edfd662..0ecf49e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.8", + "version": "1.0.0-alpha.9", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.8", + "version": "1.0.0-alpha.9", "license": "MIT", "devDependencies": { "@types/node": "^22.13.10", diff --git a/package.json b/package.json index 89df342..7dcc844 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.8", + "version": "1.0.0-alpha.9", "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 0cd03b8..165def3 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -65,6 +65,19 @@ selected, and keeps a dotted key that has no Ref to fold onto. An integration test reads one asset through all three paths and compares the keys. +One addition, for the one read whose page mixes unrelated types +(`client.search`): **you name an attribute once, plainly, and each row has +that key — its value if the row's type defines the attribute, null if it +does not.** This is the only place a row carries a key its own type lacks. +The caller never writes or reads a type-qualified name (`Story.Number`): +the schema says which of the searched types define `Number`, the service +asks each, and the key is `Number`. A relation on such a row is a bare +`{ _oid }`; a display value is asked for as a path (`"Scope.Name"`). None +of this depends on which endpoint answers the search: rest-1 does today, +because it alone takes a subtype's attribute from a base type on +instances before the release that lets api/asset do it, and the route may +move without the call or its rows changing. + Corollaries: - Envelope types live **inside the wire module that owns them** diff --git a/src/client.ts b/src/client.ts index ab631c1..b48e2b1 100644 --- a/src/client.ts +++ b/src/client.ts @@ -10,6 +10,7 @@ import * as fieldsService from "./services/fields"; import * as guard from "./services/guard"; import * as resolve from "./services/resolve"; import { Schema, type TypeCache } from "./services/schema"; +import * as searchService from "./services/search"; import type { Asset, Oid } from "./types/asset"; import type { Attachment } from "./types/assets/Attachment"; import type { Member } from "./types/assets/Member"; @@ -304,6 +305,33 @@ export class AgilityApiClient { } }; + /** + * Text search across asset types: one page of mixed rows in one order, + * with the total. `types` is required (there is no default set of + * types). `select` and `findin` take plain attribute names: a row has + * each selected key under that name, null where its type has no such + * attribute, so `Number` is simply `row.Number` for a Story and a + * Request alike. To search within one type or one family of types, an + * ordinary read with `find` does it: `client.query({ from, find, … })`. + * + * The text index trails a write by a few seconds: an asset created a + * moment ago is found by its Number at once and by its words shortly + * after. + */ + async search(text: string, options: searchService.SearchOptions): Promise> { + return searchService.search(this.transport, this.schema, text, options); + } + + /** + * Deleted assets of a type: one page, each row's `AssetState` saying + * `"Deleted"`. No other read returns a deleted asset. + */ + async deleted(type: string, params: Omit): Promise> { + searchable(type, params.find); + const { rows, total, more } = await rest1.list(this.transport, type, { ...params, filter: [...(params.filter ?? []), "IsDeleted='true'"], deleted: true, needTotal: params.needTotal ?? true }); + return { rows, total, more }; + } + /** * An asset's history: one row per version, newest paging as asked, each * row's `_oid` carrying its moment (`Story:1234:5678`). `target` is an diff --git a/src/index.ts b/src/index.ts index 6218ee4..5de2f39 100644 --- a/src/index.ts +++ b/src/index.ts @@ -41,6 +41,7 @@ export { AttachmentUploadError, INLINE_LIMIT } from "./services/attachments"; export type { AddOptions as AttachmentAddOptions, AddedAttachment, AttachmentFile, AttachmentInfo, GetOptions as AttachmentGetOptions, ListOptions as AttachmentListOptions, ListedAttachment } from "./services/attachments"; export { fromBase64, toBase64 } from "./wire/attachment"; export type { Explanation } from "./services/explain"; +export type { SearchOptions, SearchResult, SearchRow } from "./services/search"; export { isAssetNumber } from "./services/resolve"; export type { Resolution, ResolvedAsset } from "./services/resolve"; export { ConflictError, GuardedPassError, UnguardableError, unguardable } from "./services/guard"; diff --git a/src/services/index.ts b/src/services/index.ts index 22fdd8e..b51287d 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -13,3 +13,4 @@ export * as fields from "./fields"; export * as guard from "./guard"; export * as resolve from "./resolve"; export * as schema from "./schema"; +export * as search from "./search"; diff --git a/src/services/search.ts b/src/services/search.ts new file mode 100644 index 0000000..5f64b11 --- /dev/null +++ b/src/services/search.ts @@ -0,0 +1,149 @@ +/** + * Text search across asset types: one page of mixed rows, one order, a + * total. + * + * Within one family of types a search is an ordinary read with `find` + * (`client.query({ from: "Story", find, findin, … })`). Across unrelated + * types (a Story, a Request, an Issue, a Goal on one page) the rows need + * attributes their common base type does not define — `Number` first of + * all — and that takes selecting a subtype's attribute from the base type. + * rest-1 answers such a select; query.v1 and api/asset refuse it on + * instances before the release that allows it. So this service asks + * rest-1 today. That is not part of its contract: the call, the rows and + * the total stay as they are when the route moves. + * + * The caller names an attribute once, plainly (`"Number"`, `"Status"`), + * and never writes or reads a type-qualified name: the schema says which + * of the searched types define it, the request asks each of them, and a + * row has the key under its plain name — its value when the row's type + * defines the attribute, null when it does not. + */ +import { UsageError } from "../core/errors"; +import type { Transport } from "../core/transport"; +import type { Asset, Oid } from "../types/asset"; +import * as rest1 from "../wire/rest1"; +import type { Schema } from "./schema"; + +/** The type every searchable asset descends from, and the one a mixed search reads. */ +const ROOT = "BaseAsset"; +export const DEFAULT_SELECT = ["Name", "Number", "AssetType", "AssetState"] as const; +export const DEFAULT_FINDIN = ["Name", "Number"] as const; + +export interface SearchOptions { + /** + * The asset types to search: concrete types (`"Story"`, `"Request"`), + * at least one. There is no default: a default of "work items" would + * silently leave out requests, issues, goals and topics. + */ + types: readonly string[]; + /** + * Attributes for each row, by plain name; a path (`"Scope.Name"`) is + * keyed as written. A row whose type lacks one has null there. Default: + * Name, Number, AssetType, AssetState. + */ + select?: readonly string[]; + /** Attributes to search in, by plain name. Default: Name and Number. Always sent: the server's own default differs by type. */ + findin?: readonly string[]; + /** Filter terms, sent as written. A term on an attribute only some types have is type-qualified by the caller (`"Workitem.Owners.IsSelf='true'"`). */ + filter?: readonly string[]; + /** Equality terms: attribute → value, the value carried as a variable. */ + where?: Readonly>; + /** Variables for `filter`. */ + with?: Readonly>; + /** Sort terms, sent as written (`"-ChangeDateUTC"`): one order across every type. */ + sort?: readonly string[]; + /** Required, like every read. */ + page: { size: number; start: number }; +} + +/** A search row when the caller names no type of its own: `_oid` and the selected keys. */ +export type SearchRow = { _oid: Oid } & Record; + +/** One page of a search: the rows, how many assets match in all, and whether more follow this page. */ +export interface SearchResult { rows: Row[]; total: number | null; more: boolean } + +const quoted = (value: string): string => `'${value.replace(/'/g, "''")}'`; + +/** The types as a set, each loaded and checked: known, concrete, and a descendant of the root. */ +async function checked(schema: Schema, types: readonly string[]): Promise { + if (!Array.isArray(types) || !types.length) throw new UsageError("search needs `types`: the asset types to search, such as [\"Story\", \"Defect\", \"Request\"]; there is no default"); + const unique = [...new Set(types)]; + await Promise.all([ROOT, ...unique].map((t) => schema.load(t))); + for (const token of unique) { + const type = schema.assetType(token); + if (!type) throw new UsageError(`search: there is no asset type "${token}"`); + if (type.Abstract) throw new UsageError(`search: "${token}" is an abstract type; list the concrete types to search, or use client.query with \`find\` to search one family (from: "${token}")`); + let base = type.Base; + while (base && base !== ROOT) base = (await schema.load(base))?.Base; + if (base !== ROOT) throw new UsageError(`search: "${token}" does not descend from ${ROOT} and cannot be searched with other types; use client.query with \`find\` (from: "${token}")`); + } + return unique; +} + +/** + * A plain name as the request spells it: itself when every searched asset + * has it (the root defines it, or one type is searched), otherwise once + * per type that defines it, qualified. A name no type defines is a + * mistake in the call. + */ +function spelled(schema: Schema, types: readonly string[], names: readonly string[], what: string): string[] { + if (types.length === 1) { + for (const name of names) if (!schema.attribute(types[0]!, name.split(".")[0]!)) throw new UsageError(`search: ${what} "${name}" is not an attribute of ${types[0]}`); + return [...names]; + } + return names.flatMap((name) => { + const head = name.split(".")[0]!; + if (schema.attribute(ROOT, head)) return [name]; + const defining = types.filter((t) => schema.attribute(t, head)); + if (!defining.length) throw new UsageError(`search: ${what} "${name}" is not an attribute of any type searched (${types.join(", ")})`); + return defining.map((t) => `${t}.${name}`); + }); +} + +/** A row with exactly the selected keys: null where its type has no such attribute, a relation as bare Refs, nothing unselected. */ +function shaped(row: Asset, select: readonly string[]): Row { + const out: Record = { _oid: row._oid }; + const bare = (value: unknown): unknown => + Array.isArray(value) ? value.map(bare) : value && typeof value === "object" && typeof (value as { _oid?: unknown })._oid === "string" ? { _oid: (value as { _oid: string })._oid } : value; + const sent = row as unknown as Record; + // A selected path's values arrive beside the relation and were folded onto its Refs: read them back from there. + const along = (name: string): unknown => { + const dot = name.indexOf("."); + const target = dot < 0 ? undefined : sent[name.slice(0, dot)]; + const attribute = name.slice(dot + 1); + const of = (ref: unknown): unknown => (ref && typeof ref === "object" ? (ref as Record)[attribute] ?? null : null); + return Array.isArray(target) ? target.map(of) : of(target); + }; + for (const name of select) out[name] = name in sent ? bare(sent[name] ?? null) : along(name); + return out as Row; +} + +/** One page of the assets of `types` whose text matches, as `{ rows, total, more }`. */ +export async function search(transport: Transport, schema: Schema, text: string, options: SearchOptions): Promise> { + if (typeof text !== "string" || !text.trim()) throw new UsageError("search needs text: the server answers a search for nothing with no rows, which would read as \"nothing matches\""); + if (!options?.page) throw new UsageError("search without a page: every read must be bounded"); + const types = await checked(schema, options.types); + const select = [...new Set(options.select ?? DEFAULT_SELECT)]; + const findin = [...new Set(options.findin ?? DEFAULT_FINDIN)]; + if (!findin.length) throw new UsageError("search needs at least one attribute in `findin`"); + const one = types.length === 1; + const filter = [...(options.filter ?? [])]; + const variables: Record = { ...options.with }; + Object.entries(options.where ?? {}).forEach(([attribute, value], i) => { + const name = `$where${i}`; + filter.push(`${attribute}=${name}`); + variables[name] = value; + }); + if (!one) filter.unshift(`AssetType=${types.map(quoted).join(",")}`); + const result = await rest1.list(transport, one ? types[0]! : ROOT, { + find: text, + findin: spelled(schema, types, findin, "findin"), + select: spelled(schema, types, select, "select"), + filter: filter.length ? filter : undefined, + with: Object.keys(variables).length ? variables : undefined, + sort: options.sort ? [...options.sort] : undefined, + page: options.page, + needTotal: true + }); + return { rows: result.rows.map((row) => shaped(row, select)), total: result.total, more: result.more }; +} diff --git a/src/testing/index.ts b/src/testing/index.ts index 4752adc..a144e86 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -18,6 +18,7 @@ import { AgilityApiClient } from "../client"; export { CONFORMANCE_BASE_URL, fetchFrom, transportConformance } from "./transportConformance"; export type { ConformanceCheck, ConformanceRequest, ConformanceResponse, ConformanceServer } from "./transportConformance"; import type { ClientConfig } from "../core/clientConfig"; +import { DEFAULT_SELECT, type SearchOptions, type SearchResult, type SearchRow } from "../services/search"; import { ApiError, UsageError, apiErrorFromResponse } from "../core/errors"; import type { RequestOptions, Transport } from "../core/transport"; import type { Asset, Oid } from "../types/asset"; @@ -343,6 +344,8 @@ function toAssetDocument(row: FakeRow): Record { * simulation with its own answer. A write scoped by a query cannot be * previewed by the fake (it evaluates no filter): script that preview * with `onRequest`. + * - `onSearch(rows)` answers `client.search`: rows in the model's shape, + * paged by the fake, with the total; what was searched is in `searched`. * - `onList(type, rows)` answers `client.data.list` the same way: rows in * the model's shape, a list paged by the fake. * - `onRequest(match, answer)` answers any other request by path, in the @@ -360,6 +363,9 @@ export class FakeAgilityClient extends AgilityApiClient { readonly asked: QueryBody[]; /** Every batch that carried a write, in order, as sent: a Ref is written as its OID token. */ readonly sent: Command[][]; + /** Every search made, in order: its text and options. */ + readonly searched: { text: string; options: SearchOptions }[] = []; + private readonly searches: (FakeRows | Error | ((text: string, options: SearchOptions) => FakeRows))[] = []; private readonly script: Script; constructor(config: Partial & FakeOptions = {}) { @@ -410,6 +416,43 @@ export class FakeAgilityClient extends AgilityApiClient { return this; } + /** + * Script what `client.search` answers: rows in the model's shape (a + * list is the whole result: the fake pages it and reports its length + * as the total), a function of the text and options answering one page, + * or an Error to throw. The answer scripted last wins. No text is + * matched and no filter evaluated; each row is cut to the keys the + * search selected, null where the row has none, as live. + */ + onSearch(answer: FakeRows | Error | ((text: string, options: SearchOptions) => FakeRows)): this { + this.searches.push(answer); + return this; + } + + /** + * `client.search` on the fake: the same refusals before anything is + * asked (no text, no types, no page), then the scripted answer. It sends + * no request, so a test does not depend on which endpoint a search uses. + */ + override async search(text: string, options: SearchOptions): Promise> { + if (typeof text !== "string" || !text.trim()) throw new UsageError("search needs text: the server answers a search for nothing with no rows, which would read as \"nothing matches\""); + if (!options?.page) throw new UsageError("search without a page: every read must be bounded"); + if (!Array.isArray(options.types) || !options.types.length) throw new UsageError("search needs `types`: the asset types to search, such as [\"Story\", \"Defect\", \"Request\"]; there is no default"); + this.searched.push({ text, options }); + const answer = this.searches.at(-1); + if (answer === undefined) throw new UsageError(`FakeAgilityClient: no answer scripted for search(${JSON.stringify(text)}); script one with onSearch`); + if (answer instanceof Error) throw answer; + const answered = typeof answer === "function" ? answer(text, options) : answer; + const whole = Array.isArray(answered) && typeof answer !== "function"; + const all = (Array.isArray(answered) ? answered : (answered as { rows: readonly FakeRow[] }).rows) as readonly FakeRow[]; + const { size, start } = options.page; + const page = whole ? all.slice(start, start + size) : all; + const total = Array.isArray(answered) ? (whole ? all.length : null) : (answered as { total?: number | null }).total ?? null; + const select = [...new Set(options.select ?? DEFAULT_SELECT)]; + const rows = page.map((row) => Object.fromEntries([["_oid", row._oid], ...select.map((name) => [name, (row as Record)[name] ?? null])]) as unknown as Row); + return { rows, total, more: total === null ? rows.length === size : start + rows.length < total }; + } + /** Script labels for `client.localize`: tag → label. A tag nothing scripted answers itself, as loc-2 answers a tag it does not know. */ onLocalize(labels: Record): this { Object.assign(this.script.labels, labels); diff --git a/test/integration/search.test.ts b/test/integration/search.test.ts index e031cfe..53d9619 100644 --- a/test/integration/search.test.ts +++ b/test/integration/search.test.ts @@ -13,7 +13,8 @@ import { deleteFixtures, describeInstance, instance } from "./instance"; * only way. */ describeInstance("search (live)", () => { - const t = instance!.transport; + const requests: { path: string }[] = []; + const t: NonNullable["transport"] = { request: (o) => { requests.push({ path: o.path }); return instance!.transport.request(o); } }; const client = new AgilityApiClient({ baseUrl: instance!.url }, { transport: t }); const page = { size: 10, start: 0 }; // Letters only, so the server's word splitting cannot break it. @@ -126,4 +127,64 @@ describeInstance("search (live)", () => { expect(JSON.stringify(numbered.rows)).toContain(storyNumber); expect(JSON.stringify(numbered.rows)).toContain(issueNumber); }); + + // ---- client.search: the mixed page ---- + const SIXTEEN = ["Story", "Defect", "Task", "Test", "Epic", "Request", "Issue", "Goal", "Theme", "Topic", "TestSet", "RegressionTest", "RegressionSuite", "RegressionPlan", "Roadmap", "StrategicTheme"]; + + it("client.search answers one page across sixteen types in one request: plain keys, null where a type lacks the attribute, a total, one order", async () => { + const before = requests.length; + const hits = await client.search(word, { types: SIXTEEN, select: ["Name", "Number", "AssetType", "Estimate", "Scope", "Scope.Name", "Owners", "Owner"], findin: ["Name", "Description"], sort: ["-ID"], page }); + // One request once the types are loaded (the loads are meta.v1 and cached). + expect(requests.slice(before).filter((r) => !r.path.startsWith("/meta.v1"))).toHaveLength(1); + expect(hits.total).toBe(3); + expect(hits.more).toBe(false); + // One server-side order across types: newest first is the Issue, then the Defect, then the Story. + expect(hits.rows.map((r) => r._oid)).toEqual([issue, defect, story]); + const [i, d, s] = hits.rows; + // The control the design turns on: a type outside Workitem arrives with its Number, under the plain key. + expect(i).toEqual({ _oid: issue, Name: expect.stringContaining(word), Number: issueNumber, AssetType: "Issue", Estimate: null, Scope: { _oid: "Scope:0" }, "Scope.Name": expect.any(String), Owners: null, Owner: null }); + expect(s).toEqual({ _oid: story, Name: expect.stringContaining(word), Number: storyNumber, AssetType: "Story", Estimate: null, Scope: { _oid: "Scope:0" }, "Scope.Name": expect.any(String), Owners: [], Owner: null }); + expect(d).toMatchObject({ _oid: defect, AssetType: "Defect", Number: expect.stringMatching(/^D-/) }); + // Nothing a row did not select, and no type-qualified key anywhere. + expect(Object.keys(s!).some((k) => /^(Story|Workitem|Issue)\./.test(k))).toBe(false); + }); + + it("client.search: the defaults give Name, Number, AssetType and AssetState and search Name and Number; it pages with a total; filter and where compose", async () => { + const byNumber = await client.search(issueNumber, { types: SIXTEEN, page }); + expect(byNumber.rows).toEqual([{ _oid: issue, Name: expect.stringContaining(word), Number: issueNumber, AssetType: "Issue", AssetState: "Active" }]); + const first = await client.search(word, { types: ["Story", "Defect", "Issue"], sort: ["ID"], page: { size: 2, start: 0 } }); + expect([first.rows.map((r) => r._oid), first.total, first.more]).toEqual([[story, defect], 3, true]); + const last = await client.search(word, { types: ["Story", "Defect", "Issue"], sort: ["ID"], page: { size: 2, start: 2 } }); + expect([last.rows.map((r) => r._oid), last.total, last.more]).toEqual([[issue], 3, false]); + // The defect was closed in beforeAll: a filter as written, and a where carried as a variable. + expect((await client.search(word, { types: SIXTEEN, filter: ["AssetState!='Closed'"], sort: ["ID"], page })).rows.map((r) => r._oid)).toEqual([story, issue]); + expect((await client.search(word, { types: SIXTEEN, where: { AssetType: "Defect" }, page })).rows.map((r) => r._oid)).toEqual([defect]); + // A term on an attribute only some types have is type-qualified by the caller, and an OR across two of them works. + expect((await client.search(word, { types: SIXTEEN, filter: ["(Workitem.Number=$n|Issue.Number=$n)"], with: { $n: issueNumber }, page })).rows.map((r) => r._oid)).toEqual([issue]); + }); + + it("client.search with one type reads that type; a notification that names the word is never a row, because only the types asked for are", async () => { + const one = await client.search(word, { types: ["Issue"], select: ["Name", "Number", "Owner"], page }); + expect(one.rows).toEqual([{ _oid: issue, Name: expect.stringContaining(word), Number: issueNumber, Owner: null }]); + expect((await client.search(word, { types: SIXTEEN, findin: ["Name"], page })).rows.every((r) => !r._oid.startsWith("Message:"))).toBe(true); + }); + + it("client.search refuses, before any search is sent: no text, no types, an abstract type, an unknown type, a name no type defines", async () => { + const refused = async (run: () => Promise, message: RegExp) => { + const before = requests.filter((r) => r.path.startsWith("/rest-1.v1")).length; + await expect(run()).rejects.toMatchObject({ kind: "usage", status: 0, message: expect.stringMatching(message) }); + expect(requests.filter((r) => r.path.startsWith("/rest-1.v1")).length).toBe(before); + }; + await refused(() => client.search(" ", { types: ["Story"], page }), /needs text/); + await refused(() => client.search(word, { types: [], page }), /needs `types`/); + await refused(() => client.search(word, { types: ["Workitem"], page }), /abstract type/); + await refused(() => client.search(word, { types: ["NoSuchType"], page }), /no asset type "NoSuchType"/); + await refused(() => client.search(word, { types: ["Story", "Issue"], select: ["Name", "Nmae"], page }), /"Nmae" is not an attribute of any type searched \(Story, Issue\)/); + }); + + it("client.deleted answers deleted assets only, each saying Deleted", async () => { + const both = await client.deleted("Story", { filter: ["ID=$ids"], with: { $ids: [story, gone] }, select: ["Name", "AssetState"], page }); + expect(both.rows.map((r) => [r._oid, r.AssetState])).toEqual([[gone, "Deleted"]]); + expect(both.total).toBe(1); + }); }); diff --git a/test/unit/search.test.ts b/test/unit/search.test.ts new file mode 100644 index 0000000..fc574d7 --- /dev/null +++ b/test/unit/search.test.ts @@ -0,0 +1,129 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { UsageError } from "../../src/core/errors"; +import type { RequestOptions, Transport } from "../../src/core/transport"; +import { Schema } from "../../src/services/schema"; +import { search } from "../../src/services/search"; +import { FakeAgilityClient } from "../../src/testing"; +import { toMetamodel, type MetamodelDocument } from "../../src/wire/meta"; + +/** + * The search service: what it asks rest-1 for, and what it makes of the + * answer. The response below is written in the shape live responses have + * (test/integration/search.test.ts pins that shape against a server): + * rest-1 keys a type-qualified select by the attribute's plain name, + * leaves it out where the type has no such attribute, and adds display + * columns nobody asked for. + */ +const schema = () => Schema.fromMetamodel(toMetamodel(JSON.parse(readFileSync(join(__dirname, "..", "..", "metamodel.json"), "utf8")) as MetamodelDocument)); +const attribute = (name: string, value: unknown) => ({ _type: "Attribute", name, value }); +const relation = (name: string, value: unknown) => ({ _type: "Relation", name, value }); +const ref = (idref: string) => ({ _type: "Asset", href: `/I/rest-1.v1/Data/${idref.replace(":", "/")}`, idref }); +const live = { + _type: "Assets", total: 2, pageSize: 10, pageStart: 0, + Assets: [ + { _type: "Asset", href: "/I/rest-1.v1/Data/Issue/3", id: "Issue:3", Attributes: { + Name: attribute("Name", "Printer blocker"), AssetType: attribute("AssetType", "Issue"), Number: attribute("Number", "I-01043"), + Scope: relation("Scope", ref("Scope:0")), "Scope.Name": attribute("Scope.Name", "System (All Projects)"), + Owner: relation("Owner", null), "Owner.Name": attribute("Owner.Name", null), "Owner.Nickname": attribute("Owner.Nickname", null) } }, + { _type: "Asset", href: "/I/rest-1.v1/Data/Story/1", id: "Story:1", Attributes: { + Name: attribute("Name", "Printer setup"), AssetType: attribute("AssetType", "Story"), Number: attribute("Number", "S-01001"), Estimate: attribute("Estimate", 2), + Scope: relation("Scope", ref("Scope:0")), "Scope.Name": attribute("Scope.Name", "System (All Projects)"), + Owners: relation("Owners", [ref("Member:20"), ref("Member:21")]), "Owners.Name": attribute("Owners.Name", ["Ann", "Bo"]), "Owners.Nickname": attribute("Owners.Nickname", ["a", "b"]) } } + ] +}; +function recording(answer: unknown = live): Transport & { calls: RequestOptions[] } { + const calls: RequestOptions[] = []; + return { calls, request: (async (o: RequestOptions) => { calls.push(o); return answer; }) as Transport["request"] }; +} +const page = { size: 10, start: 0 }; + +describe("search", () => { + it("asks rest-1 once for a mixed page: the root type, each plain name spelled for every type that defines it, the types as a filter, a total", async () => { + const t = recording(); + await search(t, schema(), "printer", { types: ["Story", "Issue", "Story"], select: ["Name", "Number", "Estimate", "Owners", "Owner", "Scope.Name"], filter: ["AssetState!='Closed'"], where: { "Scope.Name": "O'Hare" }, sort: ["-ChangeDateUTC"], page }); + expect(t.calls).toHaveLength(1); + expect(t.calls[0]).toMatchObject({ method: "GET", path: "/rest-1.v1/Data/BaseAsset" }); + expect(t.calls[0]!.query).toEqual({ + find: "printer", + findin: "Name,Story.Number,Issue.Number", + // Name is the root's own; Number is both types'; Estimate and Owners are a Story's, Owner an Issue's; a path is spelled from its first step. + sel: "Name,Story.Number,Issue.Number,Story.Estimate,Story.Owners,Issue.Owner,Story.Scope.Name,Issue.Scope.Name", + where: "AssetType='Story','Issue';AssetState!='Closed';Scope.Name=$where0", + with: "$where0=O'Hare", + sort: "-ChangeDateUTC", + page: "10,0", + needTotal: "true", + deleted: undefined, + asof: undefined + }); + }); + + it("each row has exactly the selected keys under their plain names: null where its type has no such attribute, relations as bare Refs, a path where it was asked for", async () => { + const result = await search(recording(), schema(), "printer", { types: ["Story", "Issue"], select: ["Name", "Number", "Estimate", "Owners", "Owners.Name", "Owner", "Scope", "Scope.Name"], page }); + expect(result).toEqual({ + total: 2, + more: false, + rows: [ + { _oid: "Issue:3", Name: "Printer blocker", Number: "I-01043", Estimate: null, Owners: null, "Owners.Name": null, Owner: null, Scope: { _oid: "Scope:0" }, "Scope.Name": "System (All Projects)" }, + { _oid: "Story:1", Name: "Printer setup", Number: "S-01001", Estimate: 2, Owners: [{ _oid: "Member:20" }, { _oid: "Member:21" }], "Owners.Name": ["Ann", "Bo"], Owner: null, Scope: { _oid: "Scope:0" }, "Scope.Name": "System (All Projects)" } + ] + }); + }); + + it("the defaults select Name, Number, AssetType and AssetState and search Name and Number; one type is read as itself, with plain names", async () => { + const mixed = recording(); + await search(mixed, schema(), "printer", { types: ["Story", "Request"], page }); + expect(mixed.calls[0]!.query).toMatchObject({ sel: "Name,Story.Number,Request.Number,AssetType,AssetState", findin: "Name,Story.Number,Request.Number" }); + const one = recording(); + await search(one, schema(), "printer", { types: ["Request"], select: ["Name", "Number", "Owner"], page }); + expect(one.calls[0]).toMatchObject({ path: "/rest-1.v1/Data/Request", query: { sel: "Name,Number,Owner", findin: "Name,Number", where: undefined } }); + }); + + it("a mistake in the call is a usage error and nothing is sent: no text, no page, no types, an abstract or unknown type, a name no searched type defines (naming the types checked)", async () => { + const t = recording(); + const s = schema(); + const refused = async (run: () => Promise, message: RegExp) => { + const error = await run().then(() => null, (e: unknown) => e); + expect(error).toBeInstanceOf(UsageError); + expect((error as UsageError).message).toMatch(message); + }; + await refused(() => search(t, s, " ", { types: ["Story"], page }), /needs text/); + await refused(() => search(t, s, "x", { types: ["Story"] } as never), /without a page/); + await refused(() => search(t, s, "x", { types: [], page }), /needs `types`/); + await refused(() => search(t, s, "x", { types: ["Workitem"], page }), /"Workitem" is an abstract type/); + await refused(() => search(t, s, "x", { types: ["Sotry"], page }), /no asset type "Sotry"/); + await refused(() => search(t, s, "x", { types: ["Story", "Issue"], select: ["Nmae"], page }), /select "Nmae" is not an attribute of any type searched \(Story, Issue\)/); + await refused(() => search(t, s, "x", { types: ["Story", "Issue"], findin: ["Nmae"], page }), /findin "Nmae"/); + await refused(() => search(t, s, "x", { types: ["Issue"], select: ["Estimate"], page }), /"Estimate" is not an attribute of Issue/); + expect(t.calls).toEqual([]); + }); +}); + +describe("FakeAgilityClient: search", () => { + it("onSearch answers client.search with scripted rows, paged, with the total, each cut to the selected keys; what was searched is recorded and nothing is requested", async () => { + const fake = new FakeAgilityClient().onSearch([ + { _oid: "Story:1", Name: "Printer setup", Number: "S-1", AssetType: "Story", AssetState: "Active", Estimate: 2 }, + { _oid: "Request:2", Name: "Printer request", Number: "R-2", AssetType: "Request", AssetState: "Active" }, + { _oid: "Issue:3", Name: "Printer blocker", Number: "I-3", AssetType: "Issue", AssetState: "Active" } + ]); + const first = await fake.search("printer", { types: ["Story", "Request", "Issue"], select: ["Name", "Number", "Estimate"], page: { size: 2, start: 0 } }); + expect(first).toEqual({ total: 3, more: true, rows: [{ _oid: "Story:1", Name: "Printer setup", Number: "S-1", Estimate: 2 }, { _oid: "Request:2", Name: "Printer request", Number: "R-2", Estimate: null }] }); + const rest = await fake.search("printer", { types: ["Story", "Request", "Issue"], page: { size: 2, start: 2 } }); + expect(rest).toEqual({ total: 3, more: false, rows: [{ _oid: "Issue:3", Name: "Printer blocker", Number: "I-3", AssetType: "Issue", AssetState: "Active" }] }); + expect(fake.searched.map((s) => [s.text, s.options.page.start])).toEqual([["printer", 0], ["printer", 2]]); + expect(fake.requests).toEqual([]); + }); + + it("an unscripted search throws, and so do the mistakes the client refuses; a function answers a page, an Error is thrown", async () => { + const fake = new FakeAgilityClient(); + await expect(fake.search("printer", { types: ["Story"], page })).rejects.toThrow(/no answer scripted for search\("printer"\)/); + await expect(fake.search(" ", { types: ["Story"], page })).rejects.toMatchObject({ kind: "usage" }); + await expect(fake.search("x", { types: [], page })).rejects.toMatchObject({ kind: "usage" }); + fake.onSearch((text, options) => ({ rows: [{ _oid: "Story:9", Name: `${text} in ${options.types.join("+")}` }], total: 41 })); + expect(await fake.search("x", { types: ["Story", "Goal"], select: ["Name"], page: { size: 1, start: 0 } })).toEqual({ rows: [{ _oid: "Story:9", Name: "x in Story+Goal" }], total: 41, more: true }); + fake.onSearch(new Error("down")); + await expect(fake.search("x", { types: ["Story"], page })).rejects.toThrow("down"); + }); +}); From 76b9428a80f1f460c70f963b17f2735ef7522ccd Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:39:11 +0000 Subject: [PATCH 03/11] Deprecate client.data.list: search, deleted and query cover its uses Kept as its own commit so that removing it (now or at 1.0) is one change. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 9 +++++++++ README.md | 4 +++- src/client.ts | 6 ++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9db90de..75714ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,15 @@ Migration: when the search box is empty, leave `find` out of the query (or do not send the read). +### Deprecated + +- **`client.data.list`**: its everyday uses now have named calls. + Migration: a text search across types → `client.search`; deleted assets + → `client.deleted(type, params)`; any other list → `client.query` or + `client.queryPage`. A caller that wants rest-1's list itself imports + `rest1` from `@versionone/agility-sdk/wire` (`rest1.list(client.transport, + type, params)`). + ### Documented - README, "Searching": a search within one type or family is diff --git a/README.md b/README.md index e8ee618..436097b 100644 --- a/README.md +++ b/README.md @@ -136,7 +136,9 @@ Changes between alphas are in `CHANGELOG.md`, each with its migration line. - `copy(oid)` - the Copy operation, answering the copy's OID (api/asset performs it but never says what it made); `operate(oid, op)` is the general form - `fields.describe(type, scope)` - what a form needs: required attributes (meta), the ones the product shows there (`api/visibleFields`, custom fields included), the scheme's important fields and whether they are enforced at close - `urls.asset(oidOrNumber)` / `attachment` / `embeddedImage` - where a browser opens each - - `data.list` / `history` / `template` - rest-1 reads: text search and deleted assets, history, and a new asset's template for a context (`New/?ctx=`); `meta.*` - meta.v1 raw, with conditional reads (`read` / `readType` with `ifNoneMatch`, `etag()`: meta.v1 sends one ETag for the whole schema); `schema` - the translated, cached view, `schema.revalidate()` drops it only when that tag moves; `localize` - loc-2 labels for tags (a violation's `tag` is one) + - `search(text, { types, … })` - text search across asset types, `{ rows, total, more }`; `deleted(type, params)` - deleted assets (see "Searching") + - `history` / `template` - an asset's past versions, and a new asset's template for a context; `data.list` is deprecated (use `search`, `deleted`, `query`) + - `template` reads (`New/?ctx=`); `meta.*` - meta.v1 raw, with conditional reads (`read` / `readType` with `ifNoneMatch`, `etag()`: meta.v1 sends one ETag for the whole schema); `schema` - the translated, cached view, `schema.revalidate()` drops it only when that tag moves; `localize` - loc-2 labels for tags (a violation's `tag` is one) - `normalizeQuery(q)` - a query written with rest-1's spellings (`sel`, a textual `where`, comma-joined lists, a `"size,start"` page) as the `QueryBody` every read takes - Errors: everything thrown is an `ApiError` with a `kind` (`auth`, `forbidden`, `notFound`, `invalid`, `transient`, `aborted`, `commandFailure`, `conflict`, `protocol`, `usage`, `unknown`). A mistake caught before any request is a `UsageError`: `kind: "usage"` means nothing was sent (`status` is 0), so the fix is in the call, not on the server - `TypeCache` - one instance's loaded type definitions, shared by many clients (`new AgilityApiClient(config, { types })`); `TypeCache.fromMetamodel(metamodel)` seeds one so nothing is loaded diff --git a/src/client.ts b/src/client.ts index b48e2b1..e2b7434 100644 --- a/src/client.ts +++ b/src/client.ts @@ -299,6 +299,12 @@ export class AgilityApiClient { * everyday read.) */ readonly data = { + /** + * @deprecated Use `client.search` for text search across types, + * `client.deleted` for deleted assets, and `client.query` / + * `client.queryPage` for everything else. rest-1's list itself stays + * at `@versionone/agility-sdk/wire` (`rest1.list`). + */ list: (type: string, params: rest1.ReadParams): Promise> => { try { searchable(type, params.find); } catch (error) { return Promise.reject(error); } return rest1.list(this.transport, type, params); From 35482fa9ff6b7affa7eb9f60258739729b39d091 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:42:01 +0000 Subject: [PATCH 04/11] Remove client.data.list: search, deleted and query cover its uses client.data goes with it. rest-1's list stays at /wire (rest1.list). The changelog lists it under Breaking with a migration line per use, and the README says why a search's selects are plain while its filters are sent as written. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 45 ++++++++++++++++++--------------- README.md | 6 ++--- src/client.ts | 30 ++-------------------- src/services/search.ts | 7 ++++- src/testing/index.ts | 7 ++--- src/wire/rest1.ts | 4 +-- test/integration/client.test.ts | 9 ++++--- test/integration/search.test.ts | 6 ++--- test/unit/client.test.ts | 11 ++++---- test/unit/rest1.test.ts | 2 +- test/unit/testing.test.ts | 15 ++++++----- 11 files changed, 64 insertions(+), 78 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 75714ec..166811c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,26 @@ ## 1.0.0-alpha.9 +### Breaking + +- **`client.data.list` is removed, and `client.data` with it.** Its uses + have named calls. Migration: + - a text search across asset types → `client.search(text, { types, … })` + (below); + - a search within one type or family, or any other list → + `client.query` / `client.queryPage` (with `find` and `findin` for a + search); + - deleted assets → `client.deleted(type, params)`; + - rest-1's list itself, for a caller that wants the endpoint: + `import { rest1 } from "@versionone/agility-sdk/wire"` and + `rest1.list(client.transport, type, params)`, unchanged. +- **A read with an empty `find` throws a `UsageError`** (`kind: "usage"`, + nothing is sent), on `query`, `queries`, `queryPage`, `pages`, `all` and + `deleted`. It used to answer no rows, because that is what the server + answers to a search for nothing, and no rows read as "nothing matches". + Migration: when the search box is empty, leave `find` out of the query + (or do not send the read). + ### Added - **`client.search(text, { types, select?, findin?, filter?, where?, @@ -10,7 +30,9 @@ order. `types` is required. `select` and `findin` take plain attribute names, and each row has every selected key under that name: its value if the row's type defines the attribute, `null` if not, so a Story and a - Request both have `Number`. Nothing type-qualified is written or read. + Request both have `Number`. Nothing type-qualified is written or read + in a select; `filter` is sent as written and may be type-qualified, + since a condition across types has no plain spelling. A consumer that built this from `client.data.list("BaseAsset", …)` with one `.Number` select per type replaces it with one call. (a CLI consumer and a chat-bot consumer.) @@ -21,32 +43,13 @@ - `@versionone/agility-sdk/services` has `search`. The root exports the types `SearchOptions`, `SearchResult`, `SearchRow`. -### Changed - -- **A read with an empty `find` throws a `UsageError`** (`kind: "usage"`, - nothing is sent), on `query`, `queries`, `queryPage`, `pages`, `all` and - `data.list`. It used to answer no rows, because that is what the server - answers to a search for nothing, and no rows read as "nothing matches". - Migration: when the search box is empty, leave `find` out of the query - (or do not send the read). - -### Deprecated - -- **`client.data.list`**: its everyday uses now have named calls. - Migration: a text search across types → `client.search`; deleted assets - → `client.deleted(type, params)`; any other list → `client.query` or - `client.queryPage`. A caller that wants rest-1's list itself imports - `rest1` from `@versionone/agility-sdk/wire` (`rest1.list(client.transport, - type, params)`). - ### Documented - README, "Searching": a search within one type or family is `client.query` with `find` and `findin`; across types it is `client.search`. The server's matching rules are stated (every word, whole words, stemming, `*`, the few seconds the text index trails a - write), each proved by a live test. The README's table no longer sends - a search to `client.data.list`. + write), each proved by a live test. ### Repository diff --git a/README.md b/README.md index 436097b..642eafe 100644 --- a/README.md +++ b/README.md @@ -115,7 +115,7 @@ const { rows, total, more } = await client.search("warehouse ship*", { - **You name an attribute once, plainly, and each row has that key**: its value if the row's type defines it, `null` if not (`Owners` is null on a Request, `Owner` null on a Story; the SDK does not merge differently named attributes). A name none of the types defines is a usage error that lists the types. - `select` defaults to `Name`, `Number`, `AssetType`, `AssetState`; `findin` defaults to `Name` and `Number`. - A relation is a bare `{ _oid }`; ask for a display value as a path (`"Scope.Name"`, `"Owners.Name"`). -- `filter` and `sort` are sent as written. A filter term on an attribute only some types have is type-qualified by you: `"(Workitem.Owners.IsSelf='true'|Request.Owner.IsSelf='true')"`. +- **Selects are plain; filters are sent as written and may be type-qualified.** A select names a value, and the SDK can ask each type for it. A filter is an expression: a condition across types, such as "owned by me" when work items have `Owners` and requests have `Owner`, has no plain spelling, so you write it: `"(Workitem.Owners.IsSelf='true'|Request.Owner.IsSelf='true')"`. A term on an attribute every searched type shares (`AssetState`, `Scope.Name`) needs no qualifying. `sort` is sent as written too. - Deleted assets are never found; `client.deleted(type, params)` reads those. - To find one asset by its exact number, do not search: `client.resolve.numbers(["S-01042"])` is exact and does not wait for the text index. @@ -137,7 +137,7 @@ Changes between alphas are in `CHANGELOG.md`, each with its migration line. - `fields.describe(type, scope)` - what a form needs: required attributes (meta), the ones the product shows there (`api/visibleFields`, custom fields included), the scheme's important fields and whether they are enforced at close - `urls.asset(oidOrNumber)` / `attachment` / `embeddedImage` - where a browser opens each - `search(text, { types, … })` - text search across asset types, `{ rows, total, more }`; `deleted(type, params)` - deleted assets (see "Searching") - - `history` / `template` - an asset's past versions, and a new asset's template for a context; `data.list` is deprecated (use `search`, `deleted`, `query`) + - `history` / `template` - an asset's past versions, and a new asset's template for a context - `template` reads (`New/?ctx=`); `meta.*` - meta.v1 raw, with conditional reads (`read` / `readType` with `ifNoneMatch`, `etag()`: meta.v1 sends one ETag for the whole schema); `schema` - the translated, cached view, `schema.revalidate()` drops it only when that tag moves; `localize` - loc-2 labels for tags (a violation's `tag` is one) - `normalizeQuery(q)` - a query written with rest-1's spellings (`sel`, a textual `where`, comma-joined lists, a `"size,start"` page) as the `QueryBody` every read takes - Errors: everything thrown is an `ApiError` with a `kind` (`auth`, `forbidden`, `notFound`, `invalid`, `transient`, `aborted`, `commandFailure`, `conflict`, `protocol`, `usage`, `unknown`). A mistake caught before any request is a `UsageError`: `kind: "usage"` means nothing was sent (`status` is 0), so the fix is in the call, not on the server @@ -169,7 +169,7 @@ expect(fake.sent[0]).toEqual([{ from: "Story:1", execute: "QuickClose" }]); - `onSearch(rows)` answers `client.search`: the fake pages the rows, reports the total, and cuts each row to the selected keys; `fake.searched` is what was asked. It sends no request. - `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. -- `onList(type, rows)` answers `client.data.list` the same way. `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. +- `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/src/client.ts b/src/client.ts index e2b7434..6b1b2a4 100644 --- a/src/client.ts +++ b/src/client.ts @@ -97,8 +97,8 @@ const ME_SELECT = ["Name", "Username", "Nickname", "Email"]; * construction, so a request can be resent like a GET — but its shape has * nowhere to put a total; api/asset reports one (`needTotal`) beside the * rows, which is why `queryPage` goes there and `query` does not. rest-1 - * serves what neither does: `data.list` (text search across types, - * deleted assets), `history`, `template`, `operate`. Writes: `send`, + * serves what neither does: `search` (text search across types), + * `deleted`, `history`, `template`, `operate`. Writes: `send`, * `sendGuarded`, `batch.run`, `copy`. Services: `resolve`, * `fields`, `attachments`, `embeddedImages`, `schema`, `localize`, `urls`. */ @@ -285,32 +285,6 @@ export class AgilityApiClient { return explainService.explain(this.transport, error, options); } - /** - * rest-1's list read, for what the other reads cannot do: full-text - * `find` / `findin` across types with one order and a total, a - * type-qualified select from a base type (`Story.Number` on BaseAsset), - * and deleted assets (`deleted: true`). Parameters are spelled as a - * query's (`select`, `filter`), and rows follow the rule every read - * follows: a relation you select is a Ref, a path you select by name is - * at `row[path]`, and nothing arrives that you did not select. For - * everything else use `query` / `queryPage`. (`data` has this one member - * on purpose: it is the cross-type text search until a `client.search` - * exists, and stays here so that nobody needs the wire modules for an - * everyday read.) - */ - readonly data = { - /** - * @deprecated Use `client.search` for text search across types, - * `client.deleted` for deleted assets, and `client.query` / - * `client.queryPage` for everything else. rest-1's list itself stays - * at `@versionone/agility-sdk/wire` (`rest1.list`). - */ - list: (type: string, params: rest1.ReadParams): Promise> => { - try { searchable(type, params.find); } catch (error) { return Promise.reject(error); } - return rest1.list(this.transport, type, params); - } - }; - /** * Text search across asset types: one page of mixed rows in one order, * with the total. `types` is required (there is no default set of diff --git a/src/services/search.ts b/src/services/search.ts index 5f64b11..7f03c24 100644 --- a/src/services/search.ts +++ b/src/services/search.ts @@ -44,7 +44,12 @@ export interface SearchOptions { select?: readonly string[]; /** Attributes to search in, by plain name. Default: Name and Number. Always sent: the server's own default differs by type. */ findin?: readonly string[]; - /** Filter terms, sent as written. A term on an attribute only some types have is type-qualified by the caller (`"Workitem.Owners.IsSelf='true'"`). */ + /** + * Filter terms, sent as written. Unlike a select, a filter is an + * expression, and a condition across types has no plain spelling: a term + * on an attribute only some types have is type-qualified by the caller + * (`"(Workitem.Owners.IsSelf='true'|Request.Owner.IsSelf='true')"`). + */ filter?: readonly string[]; /** Equality terms: attribute → value, the value carried as a variable. */ where?: Readonly>; diff --git a/src/testing/index.ts b/src/testing/index.ts index a144e86..36e2984 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -346,7 +346,8 @@ function toAssetDocument(row: FakeRow): Record { * with `onRequest`. * - `onSearch(rows)` answers `client.search`: rows in the model's shape, * paged by the fake, with the total; what was searched is in `searched`. - * - `onList(type, rows)` answers `client.data.list` the same way: rows in + * - `onList(type, rows)` answers rest-1's list read the same way + * (`client.deleted`, and `rest1.list` from `/wire`): rows in * the model's shape, a list paged by the fake. * - `onRequest(match, answer)` answers any other request by path, in the * endpoint's own shape (attachment bytes, a captured response), and wins @@ -404,8 +405,8 @@ export class FakeAgilityClient extends AgilityApiClient { } /** - * Script `client.data.list` (rest-1's list read: text search, deleted - * assets) for an asset type or a predicate over the type and the query + * Script rest-1's list read (what `client.deleted` asks, and + * `rest1.list` from `/wire`) for an asset type or a predicate over the type and the query * string rest-1 is sent (`find`, `where`, `sel`, `deleted`). Rows are in * the model's shape, as for `onQuery`: a list is the whole result (the * fake pages it and reports its length as the total when asked), a diff --git a/src/wire/rest1.ts b/src/wire/rest1.ts index 212c4ea..97272ee 100644 --- a/src/wire/rest1.ts +++ b/src/wire/rest1.ts @@ -257,7 +257,7 @@ const listOf = (value: string | string[]): string[] => (typeof value === "string * typed as a read takes it (`Query`). Nothing is sent. Saying one * thing twice (`sel` and `select`, a textual `where` and `filter`) is a * UsageError rather than a guess at which was meant, and so is `deleted`: - * a QueryBody cannot ask for deleted assets (`client.data.list` can). + * a QueryBody cannot ask for deleted assets (`client.deleted` reads those). */ export function normalizeQuery(query: LooseQuery & { page: NonNullable }): Query; export function normalizeQuery(query: LooseQuery): QueryBody; @@ -265,7 +265,7 @@ export function normalizeQuery(query: LooseQuery): QueryBody { if (!query || typeof query !== "object" || typeof query.from !== "string" || !query.from) throw new UsageError("a query needs a `from`: an asset type token or an OID token"); const { sel, select, where, filter, sort, findin, page, ...rest } = query; if (sel !== undefined && select !== undefined) throw new UsageError(`query of ${query.from} has both \`sel\` and \`select\`: write one (\`select\`)`); - if ("deleted" in rest) throw new UsageError(`query of ${query.from} asks for \`deleted\`: only rest-1 reads deleted assets — use client.data.list(type, { deleted: true, … })`); + if ("deleted" in rest) throw new UsageError(`query of ${query.from} asks for \`deleted\`: only rest-1 reads deleted assets — use client.deleted(type, params)`); const out: Record = { ...rest }; const chosen = select ?? sel; if (chosen !== undefined) out.select = listOf(chosen as string | string[]).map((entry: string | LooseQuery) => (typeof entry === "string" ? entry : normalizeQuery(entry))); diff --git a/test/integration/client.test.ts b/test/integration/client.test.ts index 89e4517..0b8a569 100644 --- a/test/integration/client.test.ts +++ b/test/integration/client.test.ts @@ -2,6 +2,7 @@ import { expect, it } from "vitest"; import { AgilityApiClient } from "../../src/client"; import type { Story } from "../../src/types/assets/Story"; import { assetStateKind } from "../../src/types/asset"; +import * as rest1 from "../../src/wire/rest1"; import { normalizeQuery } from "../../src/wire/rest1"; import { describeInstance, fixtureName, instance } from "./instance"; @@ -48,7 +49,7 @@ describeInstance("client reads (live)", () => { const keys = ["Name", "Owners", "Owners.Name", "Scope.Name", "_oid"]; const viaQuery = (await client.query({ from: "Story", select, filter: ["ID=$id"], with: { $id: story }, page: { size: 1, start: 0 } }))[0]! as Record; const viaPage = (await client.queryPage({ from: "Story", select, filter: ["ID=$id"], with: { $id: story }, page: { size: 1, start: 0 } })).rows[0]! as Record; - const viaRest = (await client.data.list("Story", { select, filter: [`ID='${story}'`], page: { size: 1, start: 0 } })).rows[0]! as unknown as Record; + const viaRest = (await rest1.list(client.transport, "Story", { select, filter: [`ID='${story}'`], page: { size: 1, start: 0 } })).rows[0]! as unknown as Record; for (const row of [viaQuery, viaPage, viaRest]) { expect(Object.keys(row).sort()).toEqual(keys); expect(row["Owners.Name"]).toEqual([me.Name]); // a parallel array beside the Refs @@ -60,10 +61,10 @@ describeInstance("client reads (live)", () => { expect(viaPage.Owners).toEqual([{ _oid: me._oid }]); expect((viaRest.Owners as { Name: string }[])[0]!.Name).toBe(me.Name); // rest-1 without the dotted path selected: its uninvited columns are on the Ref, not on the row. - const bare = (await client.data.list("Story", { select: ["Name", "Owners"], filter: [`ID='${story}'`], page: { size: 1, start: 0 } })).rows[0]! as unknown as Record; + const bare = (await rest1.list(client.transport, "Story", { select: ["Name", "Owners"], filter: [`ID='${story}'`], page: { size: 1, start: 0 } })).rows[0]! as unknown as Record; expect(Object.keys(bare).sort()).toEqual(["Name", "Owners", "_oid"]); // And a refused rest-1 read is a QUERY_REJECTED with sentences, like query.v1's. - await expect(client.data.list("Story", { filter: ["Nope=1"], page: { size: 1, start: 0 } })).rejects.toMatchObject({ kind: "invalid", code: "QUERY_REJECTED", message: expect.stringMatching(/^Invalid WHERE parameter; /) }); + await expect(rest1.list(client.transport, "Story", { filter: ["Nope=1"], page: { size: 1, start: 0 } })).rejects.toMatchObject({ kind: "invalid", code: "QUERY_REJECTED", message: expect.stringMatching(/^Invalid WHERE parameter; /) }); await expect(client.query({ from: "Story", filter: ["Nope=1"], page: { size: 1, start: 0 } })).rejects.toMatchObject({ kind: "invalid", code: "QUERY_REJECTED" }); } finally { await client.send([{ from: story, execute: "Delete" }]); @@ -131,7 +132,7 @@ describeInstance("client reads (live)", () => { } // Gone from an ordinary read; rest-1's deleted read still shows it, and says Deleted. expect(await client.get(story)).toBeNull(); - const [deleted] = (await client.data.list<{ _oid: string; AssetState: string }>("Story", { select: ["AssetState"], filter: [`ID='${story}'`], deleted: true, page: { size: 1, start: 0 } })).rows; + const [deleted] = (await rest1.list<{ _oid: string; AssetState: string }>(client.transport, "Story", { select: ["AssetState"], filter: [`ID='${story}'`], deleted: true, page: { size: 1, start: 0 } })).rows; expect([deleted?.AssetState, assetStateKind(deleted?.AssetState)]).toEqual(["Deleted", "deleted"]); // A template is state 200, which query.v1 sends as "200" and the model names Template. (None on an empty instance: then nothing is asserted.) const [template] = await client.query<{ _oid: string; AssetState: string }>({ from: "Story", select: ["AssetState"], filter: ["AssetState='200'"], page: { size: 1, start: 0 } }); diff --git a/test/integration/search.test.ts b/test/integration/search.test.ts index 53d9619..e5f3080 100644 --- a/test/integration/search.test.ts +++ b/test/integration/search.test.ts @@ -1,6 +1,6 @@ import { afterAll, beforeAll, expect, it } from "vitest"; import { AgilityApiClient } from "../../src/client"; -import { queryV1 } from "../../src/wire"; +import { queryV1, rest1 } from "../../src/wire"; import { deleteFixtures, describeInstance, instance } from "./instance"; /** @@ -117,12 +117,12 @@ describeInstance("search (live)", () => { }); it("what only rest-1's list answers: deleted assets, and one page across every type with each type's Number", async () => { - const deleted = await client.data.list("Story", { find: `${word} deleted`, findin: ["Name"], select: ["Name"], deleted: true, page }); + const deleted = await rest1.list(client.transport, "Story", { find: `${word} deleted`, findin: ["Name"], select: ["Name"], deleted: true, page }); expect(deleted.rows.map((r) => r._oid.split(":").slice(0, 2).join(":"))).toEqual([gone]); // query.v1 refuses a type-qualified select on a base type; rest-1 answers it, as `Number`. const mixed = { from: "BaseAsset", select: ["Name", "Story.Number", "Issue.Number"], find: word, findin: ["Name"], sort: ["ID"], page }; await expect(client.query<{ _oid: string }>(mixed)).rejects.toMatchObject({ status: 400, code: "QUERY_REJECTED" }); - const numbered = await client.data.list<{ _oid: string; Number?: string }>("BaseAsset", { find: word, findin: ["Name"], select: ["Name", "Story.Number", "Issue.Number"], filter: ["AssetType='Story','Defect','Issue'"], sort: ["ID"], page }); + const numbered = await rest1.list<{ _oid: string; Number?: string }>(client.transport, "BaseAsset", { find: word, findin: ["Name"], select: ["Name", "Story.Number", "Issue.Number"], filter: ["AssetType='Story','Defect','Issue'"], sort: ["ID"], page }); expect(numbered.rows.map((r) => r._oid)).toEqual([story, defect, issue]); expect(JSON.stringify(numbered.rows)).toContain(storyNumber); expect(JSON.stringify(numbered.rows)).toContain(issueNumber); diff --git a/test/unit/client.test.ts b/test/unit/client.test.ts index b08939c..285da46 100644 --- a/test/unit/client.test.ts +++ b/test/unit/client.test.ts @@ -126,7 +126,7 @@ describe("client: reads", () => { const client = new AgilityApiClient({ baseUrl: "https://agility.example.com/I" }, { transport: t }); const page = { size: 5, start: 0 }; const empty = { from: "Story", select: ["Name"], find: " ", findin: ["Name"], page }; - for (const read of [() => client.query(empty), () => client.queries([{ from: "Story", page }, empty]), () => client.queryPage(empty), () => client.all(empty), () => client.data.list("Story", { find: "", page })]) { + for (const read of [() => client.query(empty), () => client.queries([{ from: "Story", page }, empty]), () => client.queryPage(empty), () => client.all(empty), () => client.deleted("Story", { find: "", page })]) { await expect(read()).rejects.toMatchObject({ kind: "usage", status: 0, message: expect.stringContaining("empty `find`") }); } expect(t.calls).toEqual([]); @@ -141,12 +141,13 @@ describe("client: reads", () => { await expect(new AgilityApiClient({ baseUrl: "https://x" }, { transport: fake(() => [[]]), types: schema().cache }).me()).rejects.toMatchObject({ kind: "notFound" }); }); - it("data.list takes a query's spelling (select, filter) and sends rest-1's (sel, where)", async () => { + it("deleted takes a query's spelling (select, filter), sends rest-1's (sel, where), and asks for deleted assets only, with the total", async () => { const t = fake(() => ({ _type: "Assets", pageSize: 2, pageStart: 0, Assets: [] })); const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t }); - await client.data.list("Story", { select: ["Name"], filter: ["AssetState='Closed'"], deleted: true, page: { size: 2, start: 0 } }); - for (const call of t.calls) expect(call).toMatchObject({ method: "GET", path: "/rest-1.v1/Data/Story", query: expect.objectContaining({ sel: "Name", where: "AssetState='Closed'", page: "2,0" }) }); - expect(t.calls[0]!.query).toMatchObject({ deleted: "true" }); + expect(await client.deleted("Story", { select: ["Name"], filter: ["Scope='Scope:0'"], page: { size: 2, start: 0 } })).toEqual({ rows: [], total: null, more: false }); + expect(t.calls).toHaveLength(1); + expect(t.calls[0]).toMatchObject({ method: "GET", path: "/rest-1.v1/Data/Story", query: expect.objectContaining({ sel: "Name", where: "Scope='Scope:0';IsDeleted='true'", page: "2,0", deleted: "true", needTotal: "true" }) }); + expect((client as unknown as { data?: unknown }).data).toBeUndefined(); }); }); diff --git a/test/unit/rest1.test.ts b/test/unit/rest1.test.ts index 93ed4bf..81c60ac 100644 --- a/test/unit/rest1.test.ts +++ b/test/unit/rest1.test.ts @@ -155,7 +155,7 @@ describe("normalizeQuery: a query written with rest-1's spellings", () => { it("saying one thing twice, asking for deleted assets, a bad page or no from is a UsageError: nothing is guessed", () => { expect(() => normalizeQuery({ from: "Story", sel: "Name", select: ["Name"] })).toThrow(/both `sel` and `select`/); expect(() => normalizeQuery({ from: "Story", where: "A='1'", filter: ["B='2'"] })).toThrow(/both a textual `where` and `filter`/); - expect(() => normalizeQuery({ from: "Story", deleted: true })).toThrow(/client\.data\.list/); + expect(() => normalizeQuery({ from: "Story", deleted: true })).toThrow(/client\.deleted/); expect(() => normalizeQuery({ from: "Story", page: "ten" })).toThrow(UsageError); expect(() => normalizeQuery({ sel: "Name" } as never)).toThrow(UsageError); }); diff --git a/test/unit/testing.test.ts b/test/unit/testing.test.ts index 9628779..e206d9c 100644 --- a/test/unit/testing.test.ts +++ b/test/unit/testing.test.ts @@ -7,6 +7,7 @@ import { FakeAgilityClient } from "../../src/testing"; import { ConflictError } from "../../src/services/guard"; import { CommandFailureError } from "../../src/wire/assetApi"; import type { MetamodelDocument } from "../../src/wire/meta"; +import * as rest1 from "../../src/wire/rest1"; /** * The consumer-facing fake: a real client over a transport that answers @@ -98,7 +99,7 @@ describe("FakeAgilityClient", () => { expect(await fake.localize(["Plural'Story"])).toEqual({ "Plural'Story": "Backlog Items" }); fake.onQuery("Attachment", [{ _oid: "Attachment:5", Name: "n", Filename: "f.txt", ContentType: "text/plain" }]); expect((await fake.attachments.get(5)).bytes).toEqual(new Uint8Array([1, 2])); - await expect(fake.data.list("Story", { page: { size: 1, start: 0 } })).rejects.toThrow(/no answer scripted for GET \/rest-1\.v1\/Data\/Story/); + await expect(rest1.list(fake.transport, "Story", { page: { size: 1, start: 0 } })).rejects.toThrow(/no answer scripted for GET \/rest-1\.v1\/Data\/Story/); }); it("a batch that creates and reads back through an alias answers the scripted row of that type under the created OID", async () => { @@ -138,26 +139,26 @@ describe("FakeAgilityClient", () => { expect(fake.requests.map((r) => r.path)).toEqual(["/query.v1"]); // the type load is the client's plumbing, not the test's subject }); - it("onList answers client.data.list from rows in the model's shape: Refs, dotted paths, paging, the total and `more`, and the rows rule", async () => { + it("onList answers rest-1's list read (client.deleted, rest1.list) from rows in the model's shape: Refs, dotted paths, paging, the total and `more`, and the rows rule", async () => { const found = [ { _oid: "Story:1", Name: "Logon", Number: "S-01001", AssetState: "Active", Owners: [{ _oid: "Member:20" }], "Owners.Name": ["Dana"], Status: null }, { _oid: "Defect:9", Name: "Crash on logon", Number: "D-00009", AssetState: "Closed", Owners: [], Status: { _oid: "StoryStatus:5" } }, { _oid: "Story:3", Name: "Logon help", Number: "S-01003", AssetState: "Active", Owners: [], Status: null } ]; const fake = new FakeAgilityClient().onList("BaseAsset", found); - const page = await fake.data.list("BaseAsset", { find: "logon", findin: ["Name"], select: ["Name", "Number", "AssetState", "Owners", "Owners.Name", "Status"], page: { size: 2, start: 0 }, needTotal: true }); + const page = await rest1.list(fake.transport, "BaseAsset", { find: "logon", findin: ["Name"], select: ["Name", "Number", "AssetState", "Owners", "Owners.Name", "Status"], page: { size: 2, start: 0 }, needTotal: true }); // As scripted, read back through the client's own rest-1 translation: so, as live, a selected dotted path is also on its Refs. expect(page.rows).toEqual([{ ...found[0], Owners: [{ _oid: "Member:20", Name: "Dana" }] }, found[1]]); expect(page).toMatchObject({ total: 3, more: true }); - expect((await fake.data.list("BaseAsset", { page: { size: 2, start: 2 }, needTotal: true })).rows).toEqual([found[2]]); + expect((await rest1.list(fake.transport, "BaseAsset", { page: { size: 2, start: 2 }, needTotal: true })).rows).toEqual([found[2]]); // What a scripted Ref carries stays on it, as rest-1's display columns do live, whether or not the dotted path was selected. fake.onList("Story", [{ _oid: "Story:1", Status: { _oid: "StoryStatus:1", Name: "Dev" }, Owners: [{ _oid: "Member:1", Name: "a", Nickname: "A" }, { _oid: "Member:2", Name: "b", Nickname: "B" }] }]); - expect((await fake.data.list("Story", { select: ["Status", "Owners"], page: { size: 1, start: 0 } })).rows).toEqual([{ _oid: "Story:1", Status: { _oid: "StoryStatus:1", Name: "Dev" }, Owners: [{ _oid: "Member:1", Name: "a", Nickname: "A" }, { _oid: "Member:2", Name: "b", Nickname: "B" }] }]); + expect((await rest1.list(fake.transport, "Story", { select: ["Status", "Owners"], page: { size: 1, start: 0 } })).rows).toEqual([{ _oid: "Story:1", Status: { _oid: "StoryStatus:1", Name: "Dev" }, Owners: [{ _oid: "Member:1", Name: "a", Nickname: "A" }, { _oid: "Member:2", Name: "b", Nickname: "B" }] }]); expect(fake.requests[0]).toMatchObject({ method: "GET", path: "/rest-1.v1/Data/BaseAsset", query: { find: "logon", findin: "Name", page: "2,0" } }); // A function sees the type and rest-1's own query string, and answers one page. fake.onList((type, q) => type === "Story" && q.deleted === "true", () => ({ rows: [{ _oid: "Story:7", Name: "gone" }], total: 12 })); - expect(await fake.data.list("Story", { deleted: true, page: { size: 1, start: 0 }, needTotal: true })).toMatchObject({ rows: [{ _oid: "Story:7", Name: "gone" }], total: 12, more: true }); - await expect(fake.data.list("Epic", { page: { size: 1, start: 0 } })).rejects.toThrow(/no answer scripted for GET \/rest-1\.v1\/Data\/Epic/); + expect(await rest1.list(fake.transport, "Story", { deleted: true, page: { size: 1, start: 0 }, needTotal: true })).toMatchObject({ rows: [{ _oid: "Story:7", Name: "gone" }], total: 12, more: true }); + await expect(rest1.list(fake.transport, "Epic", { page: { size: 1, start: 0 } })).rejects.toThrow(/no answer scripted for GET \/rest-1\.v1\/Data\/Epic/); }); it("with a metamodel the fake's instance has those types: a response captured from a server reads translated, for the fake and for a client built on its transport", async () => { From 73ba57e06eff9899d73d57adf5057b9f0fe77692 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:47:27 +0000 Subject: [PATCH 05/11] One rule for a Ref on every read; a family of types in search A Ref is { _oid } on rest-1-backed reads too: the display columns rest-1 sends beside a relation unasked are dropped instead of put on the Ref, and a path the caller selected is at row[path]. The same select now gives the same row whichever endpoint answers (a live test compares all three). client.search accepts a family by its abstract type (types: ["Workitem"]) from a generated table of each abstract type's concrete subtypes; a live test checks the table against the instance. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 16 ++++++++++- README.md | 4 +-- examples/10-search.ts | 2 +- scripts/generate-types.mjs | 19 ++++++++++-- specs/000-layers.md | 18 ++++++------ src/services/search.ts | 51 +++++++++++++++++---------------- src/testing/index.ts | 2 +- src/types/assets/subtypes.ts | 8 ++++++ src/wire/rest1.ts | 37 +++++++++--------------- test/integration/client.test.ts | 12 ++++---- test/integration/rest1.test.ts | 5 ++-- test/integration/search.test.ts | 14 +++++++-- test/unit/rest1.test.ts | 39 +++++++++++-------------- test/unit/search.test.ts | 12 ++++++-- test/unit/testing.test.ts | 8 +++--- 15 files changed, 147 insertions(+), 100 deletions(-) create mode 100644 src/types/assets/subtypes.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 166811c..8b63eaf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,19 @@ - rest-1's list itself, for a caller that wants the endpoint: `import { rest1 } from "@versionone/agility-sdk/wire"` and `rest1.list(client.transport, type, params)`, unchanged. +- **A Ref is `{ _oid }` on every read; rest-1's unasked display columns + are dropped, no longer put on the Ref.** `client.history`, + `client.template`, `client.deleted`, `client.search` and `rest1.list` / + `rest1.get` from `/wire` used to answer `Owners: [{ _oid, Name, + Nickname }]` for a selected relation, because rest-1 sends those columns + beside it; the query endpoints never did, so the same select gave two + rows. Migration: select the path you read (`"Owners.Name"`, + `"Status.Name"`, `"Scope.Name"`) and read it at `row["Owners.Name"]` (an + array parallel to `row.Owners` for a multi-value relation). Nothing + errors if you do not: `ref.Name` is simply undefined, so search your + code for a name read off a relation. A read with no select at all (a + template) keeps every column the server sent, each under its own key + (`template["Scope.Name"]`), and its Refs are bare too. (a CLI consumer.) - **A read with an empty `find` throws a `UsageError`** (`kind: "usage"`, nothing is sent), on `query`, `queries`, `queryPage`, `pages`, `all` and `deleted`. It used to answer no rows, because that is what the server @@ -27,7 +40,8 @@ - **`client.search(text, { types, select?, findin?, filter?, where?, with?, sort?, page })`**: text search across asset types, answered as `{ rows, total, more }`: one page of mixed rows in one server-side - order. `types` is required. `select` and `findin` take plain attribute + order. `types` is required: concrete types, or a family by its + abstract type (`"Workitem"`). `select` and `findin` take plain attribute names, and each row has every selected key under that name: its value if the row's type defines the attribute, `null` if not, so a Story and a Request both have `Number`. Nothing type-qualified is written or read diff --git a/README.md b/README.md index 642eafe..0d76e1d 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ npm test | An error, said to a person | `client.explain(error)` | "Project is required.", with the instance's labels. | | Labels in the instance's words | `client.localize(tags)` | | -Every row follows one rule, whichever call read it: **a relation you select is a Ref (`{ _oid }`); a path you select by name is at `row[path]` (`row["Status.Name"]`); nothing arrives that you did not select.** Select both `Owners` and `Owners.Name` and you get the Refs and, beside them, a parallel array at `"Owners.Name"`. To get attributes on the related rows themselves, use a sub-select: `{ from: "Owners", select: ["Name"] }` gives `row.Owners[i].Name`. (rest-1 also puts the display attributes it sends unasked on the Refs of a relation you selected.) +Every row follows one rule, whichever call read it: **a relation you select is a Ref (`{ _oid }`); a path you select by name is at `row[path]` (`row["Status.Name"]`); nothing arrives that you did not select.** Select both `Owners` and `Owners.Name` and you get the Refs and, beside them, a parallel array at `"Owners.Name"`. To get attributes on the related rows themselves, use a sub-select: `{ from: "Owners", select: ["Name"] }` gives `row.Owners[i].Name`. A row's identity is `_oid`: it is the key the server sends, underscored so it cannot collide with an attribute (the identity attribute is `ID`). Rows, Refs, resolved assets, attachments and the assets on a receipt all carry it; a record that only mentions an asset (a receipt's `described` entries, a `drifted` entry) says `oid`. @@ -111,7 +111,7 @@ const { rows, total, more } = await client.search("warehouse ship*", { ``` - **One request, one order across every type, and the total.** The matching rules above apply. -- **`types` is required**: concrete types, at least one. A default would silently leave types out. +- **`types` is required**, at least one: concrete types, or a family by its abstract type (`"Workitem"` is stories, defects, epics, themes, tasks, tests and test sets; requests, issues and goals are not work items, so name them). A default would silently leave types out. - **You name an attribute once, plainly, and each row has that key**: its value if the row's type defines it, `null` if not (`Owners` is null on a Request, `Owner` null on a Story; the SDK does not merge differently named attributes). A name none of the types defines is a usage error that lists the types. - `select` defaults to `Name`, `Number`, `AssetType`, `AssetState`; `findin` defaults to `Name` and `Number`. - A relation is a bare `{ _oid }`; ask for a display value as a path (`"Scope.Name"`, `"Owners.Name"`). diff --git a/examples/10-search.ts b/examples/10-search.ts index eb5343a..4933da6 100644 --- a/examples/10-search.ts +++ b/examples/10-search.ts @@ -16,7 +16,7 @@ const text = process.argv[2] ?? "sample"; // `select` is written once, plainly, and every row has that key: its value // if the row's type has the attribute, null if not. const { rows, total, more } = await client.search(text, { - types: ["Story", "Defect", "Epic", "Request", "Issue", "Goal"], + types: ["Workitem", "Request", "Issue", "Goal"], // a family by its abstract type, and three types outside it select: ["Name", "Number", "AssetType", "Scope.Name", "Estimate"], filter: ["AssetState!='Closed'"], sort: ["-ChangeDateUTC"], diff --git a/scripts/generate-types.mjs b/scripts/generate-types.mjs index e3b23b2..a7757a2 100644 --- a/scripts/generate-types.mjs +++ b/scripts/generate-types.mjs @@ -14,6 +14,8 @@ * Asset root (src/types/asset.ts). * - src/types/assets/index.ts: every type re-exported, the AssetTypeName * union, and an AssetTypeMap from token to interface. + * - src/types/assets/subtypes.ts: the one generated value, each abstract + * type's concrete subtypes (`Workitem` → Story, Defect, Epic, …). * * What the output is not: * - endpoint-aware. A relation is a Ref (or Ref[]); how api/asset, query.v1 @@ -180,16 +182,29 @@ export function model(metamodel) { `` ].join("\n"); - return { files, index, count: tokens.length, attributes: files.reduce((n, f) => n + f.ownCount, 0) }; + // The one generated VALUE: an abstract type's concrete subtypes, for a caller that names a family ("Workitem") + // where the server wants concrete types. The root is left out: "every asset" is not a family anyone searches. + const families = tokens.filter((t) => types[t].Abstract && baseOf(t) && descendants(t).length); + const subtypes = [ + `// Generated by scripts/generate-types.mjs from metamodel.json (meta.v1 ${metamodel.Version}); do not edit.`, + `/** Each abstract asset type's concrete subtypes, as the product ships them (an instance's own custom types are not here). */`, + `export const CONCRETE_SUBTYPES: Readonly> = {`, + ...families.map((t) => ` ${t}: [${descendants(t).map((n) => JSON.stringify(n)).join(", ")}],`), + `};`, + `` + ].join("\n"); + + return { files, index, subtypes, count: tokens.length, attributes: files.reduce((n, f) => n + f.ownCount, 0) }; } export async function generate(metamodelPath, outDir) { const metamodel = JSON.parse(await readFile(metamodelPath, "utf8")); - const { files, index, count, attributes } = model(metamodel); + const { files, index, subtypes, count, attributes } = model(metamodel); await rm(outDir, { recursive: true, force: true }); await mkdir(outDir, { recursive: true }); await Promise.all(files.map((f) => writeFile(join(outDir, `${f.token}.ts`), f.text))); await writeFile(join(outDir, "index.ts"), index); + await writeFile(join(outDir, "subtypes.ts"), subtypes); return { count, attributes, written: (await readdir(outDir)).length }; } diff --git a/specs/000-layers.md b/specs/000-layers.md index 165def3..bc006a8 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -41,8 +41,7 @@ imports `core` for one reason: a string that is not an OID token is a ## 2. One shape The objects the SDK passes around have **one shape**, wherever they came -from or are going. A relation is a `Ref` (`{ _oid }` plus whatever a select -pulled through) in a create, in an update, and in a query result alike. +from or are going. A relation is a `Ref` (`{ _oid }`, plus what a sub-select asked for) in a create, in an update, and in a query result alike. `AssetState` has one set of values. Whatever an endpoint spells differently — api/asset writing a relation as an OID token, rest-1 wrapping every value in `Attributes` and rendering `AssetState` as a number — is translated in @@ -58,12 +57,15 @@ described update, a drifted entry — says plain `oid`. One rule for a row, on every read path (query.v1, api/asset, rest-1): **a relation you select is a Ref; a path you select by name is at `row[path]`; nothing arrives that you did not select.** A sub-select is -how to ask for attributes on the related rows. rest-1 sends display -columns beside a selected relation unasked; its wire module folds them -onto the Refs and drops their keys from the row unless the path was -selected, and keeps a dotted key that has no Ref to fold onto. An -integration test reads one asset through all three paths and compares -the keys. +how to ask for attributes on the related rows. A Ref is `{ _oid }` and +nothing more unless a sub-select put attributes on it. rest-1 sends +display columns beside a selected relation unasked (`Owners.Name`); its +wire module drops them unless that path was selected, in which case the +value is at `row[path]` like any path. They are never put on the Ref: a +row must not differ by which endpoint answered it. Where a read has no +select at all (a template), the server chose the attributes and every +column it sent stays under its own key. An integration test reads one +asset through all three paths and compares the rows. One addition, for the one read whose page mixes unrelated types (`client.search`): **you name an attribute once, plainly, and each row has diff --git a/src/services/search.ts b/src/services/search.ts index 7f03c24..c6bde2a 100644 --- a/src/services/search.ts +++ b/src/services/search.ts @@ -21,6 +21,7 @@ import { UsageError } from "../core/errors"; import type { Transport } from "../core/transport"; import type { Asset, Oid } from "../types/asset"; +import { CONCRETE_SUBTYPES } from "../types/assets/subtypes"; import * as rest1 from "../wire/rest1"; import type { Schema } from "./schema"; @@ -31,9 +32,10 @@ export const DEFAULT_FINDIN = ["Name", "Number"] as const; export interface SearchOptions { /** - * The asset types to search: concrete types (`"Story"`, `"Request"`), - * at least one. There is no default: a default of "work items" would - * silently leave out requests, issues, goals and topics. + * The asset types to search, at least one: concrete types (`"Story"`, + * `"Request"`), or a family by its abstract type (`"Workitem"` is + * stories, defects, epics, themes, tasks, tests and test sets). There is + * no default: one would silently leave types out. */ types: readonly string[]; /** @@ -69,20 +71,33 @@ export interface SearchResult { rows: Row const quoted = (value: string): string => `'${value.replace(/'/g, "''")}'`; -/** The types as a set, each loaded and checked: known, concrete, and a descendant of the root. */ +/** + * The types as a set of concrete types, each loaded and checked. A family + * named by its abstract type (`"Workitem"`) stands for its concrete + * subtypes as the product ships them; one of those this instance does not + * have is left out, since the caller did not name it. + */ async function checked(schema: Schema, types: readonly string[]): Promise { if (!Array.isArray(types) || !types.length) throw new UsageError("search needs `types`: the asset types to search, such as [\"Story\", \"Defect\", \"Request\"]; there is no default"); - const unique = [...new Set(types)]; - await Promise.all([ROOT, ...unique].map((t) => schema.load(t))); - for (const token of unique) { + const named = [...new Set(types)]; + await Promise.all([ROOT, ...named].map((t) => schema.load(t))); + const concrete = new Set(); + for (const token of named) { const type = schema.assetType(token); if (!type) throw new UsageError(`search: there is no asset type "${token}"`); - if (type.Abstract) throw new UsageError(`search: "${token}" is an abstract type; list the concrete types to search, or use client.query with \`find\` to search one family (from: "${token}")`); - let base = type.Base; + if (!type.Abstract) { concrete.add(token); continue; } + const family = CONCRETE_SUBTYPES[token]; + if (!family) throw new UsageError(`search: "${token}" is an abstract type whose concrete subtypes the SDK does not know; list the concrete types to search`); + const loaded = await Promise.all(family.map((t) => schema.load(t))); + family.forEach((t, i) => { if (loaded[i]) concrete.add(t); }); + } + for (const token of concrete) { + let base = schema.assetType(token)!.Base; while (base && base !== ROOT) base = (await schema.load(base))?.Base; if (base !== ROOT) throw new UsageError(`search: "${token}" does not descend from ${ROOT} and cannot be searched with other types; use client.query with \`find\` (from: "${token}")`); } - return unique; + if (!concrete.size) throw new UsageError(`search: none of the types named (${named.join(", ")}) has a concrete type on this instance`); + return [...concrete]; } /** @@ -105,22 +120,10 @@ function spelled(schema: Schema, types: readonly string[], names: readonly strin }); } -/** A row with exactly the selected keys: null where its type has no such attribute, a relation as bare Refs, nothing unselected. */ +/** A row with exactly the selected keys: null where its type has no such attribute, nothing unselected. */ function shaped(row: Asset, select: readonly string[]): Row { - const out: Record = { _oid: row._oid }; - const bare = (value: unknown): unknown => - Array.isArray(value) ? value.map(bare) : value && typeof value === "object" && typeof (value as { _oid?: unknown })._oid === "string" ? { _oid: (value as { _oid: string })._oid } : value; const sent = row as unknown as Record; - // A selected path's values arrive beside the relation and were folded onto its Refs: read them back from there. - const along = (name: string): unknown => { - const dot = name.indexOf("."); - const target = dot < 0 ? undefined : sent[name.slice(0, dot)]; - const attribute = name.slice(dot + 1); - const of = (ref: unknown): unknown => (ref && typeof ref === "object" ? (ref as Record)[attribute] ?? null : null); - return Array.isArray(target) ? target.map(of) : of(target); - }; - for (const name of select) out[name] = name in sent ? bare(sent[name] ?? null) : along(name); - return out as Row; + return Object.fromEntries([["_oid", row._oid], ...select.map((name) => [name, sent[name] ?? null])]) as Row; } /** One page of the assets of `types` whose text matches, as `{ rows, total, more }`. */ diff --git a/src/testing/index.ts b/src/testing/index.ts index 36e2984..7be9587 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -281,7 +281,7 @@ function toAssetDocument(row: FakeRow): Record { const ref = (r: { _oid: string }) => ({ _type: "Asset", href: "", idref: r._oid }); const Attributes: Record = {}; // What a scripted Ref carries beyond its OID goes out as rest-1 sends a relation's display columns (`Owners.Name`, a - // parallel array for a multi-value relation), so the client folds it back onto the Ref, as it does live. + // parallel array for a multi-value relation), so the client reads it as it does live: at the path, when the path was selected. const columns = (name: string, refs: Record[], many: boolean) => { for (const key of new Set(refs.flatMap((r) => Object.keys(r).filter((k) => k !== "_oid")))) { const path = `${name}.${key}`; diff --git a/src/types/assets/subtypes.ts b/src/types/assets/subtypes.ts new file mode 100644 index 0000000..4088cb6 --- /dev/null +++ b/src/types/assets/subtypes.ts @@ -0,0 +1,8 @@ +// Generated by scripts/generate-types.mjs from metamodel.json (meta.v1 26.3.2.13); do not edit. +/** Each abstract asset type's concrete subtypes, as the product ships them (an instance's own custom types are not here). */ +export const CONCRETE_SUBTYPES: Readonly> = { + Okr: ["KeyResult", "OkrObjective"], + PrimaryWorkitem: ["Defect", "Story", "TestSet"], + Status: ["EpicStatus", "StoryStatus"], + Workitem: ["Defect", "Epic", "Story", "Task", "Test", "TestSet", "Theme"], +}; diff --git a/src/wire/rest1.ts b/src/wire/rest1.ts index 97272ee..34068ae 100644 --- a/src/wire/rest1.ts +++ b/src/wire/rest1.ts @@ -31,7 +31,7 @@ * - AssetState is the NUMBER (the server's AssetState enum); the model wants the name. * - a type-qualified sel (Story.Number on BaseAsset) arrives keyed by its plain name (Number). * - selecting a relation also brings its display columns (Owners.Name, - * Owners.Nickname, Status.Name) uninvited; they are folded onto the Refs. + * Owners.Nickname, Status.Name) uninvited; they are dropped unless selected. * - a page is required by this module: no Data read is unbounded. */ import { ApiError, UsageError } from "../core/errors"; @@ -81,39 +81,30 @@ const toRef = (doc: AssetRefDocument): Ref => ({ _oid: momentless(doc.idref) }); * row's own _oid keeps its moment only on a history read (it is the moment * that identifies the row). * - * rest-1 adds display columns beside a selected relation without being - * asked (Owners.Name, Owners.Nickname). They are folded onto the Refs by - * position, and the row follows the rule every read follows — it has the - * keys that were selected and no others: a dotted key stays only when it - * is in `select` (the caller asked for that path by name), or when it has - * no Ref to fold onto (it is then all there is of that value). + * A Ref is `{ _oid }` and nothing else, as on every read. rest-1 adds + * display columns beside a selected relation without being asked + * (`Owners.Name`, `Owners.Nickname`): they are dropped, because the row + * has the keys that were selected and no others. A path the caller did + * select (`"Owners.Name"`, or type-qualified, `"Story.Owners.Name"`) is at + * `row["Owners.Name"]`. When nothing was selected (a template, a read + * without `select`) the server chose the attributes, and every column it + * sent stays, under its own key. */ export function fromAssetDocument(doc: AssetDocument, { history = false, select }: { history?: boolean; select?: readonly string[] } = {}): Row { const out: Record = { _oid: history ? doc.id : momentless(doc.id) }; - const attrs = doc.Attributes ?? {}; - for (const [key, a] of Object.entries(attrs)) { + // rest-1 keys a type-qualified select (`Story.Scope.Name`) by its plain path (`Scope.Name`). + const selected = (key: string): boolean => !select || select.some((s) => s === key || s.endsWith(`.${key}`)); + for (const [key, a] of Object.entries(doc.Attributes ?? {})) { if (a._type === "Relation") { out[key] = Array.isArray(a.value) ? a.value.map(toRef) : a.value ? toRef(a.value) : null; + } else if (key.includes(".") && !selected(key)) { + continue; // a display column nobody asked for } else if (key === "AssetState" && typeof a.value === "number") { out[key] = assetStateOf(a.value); } else { out[key] = a.value; } } - // Fold "Rel.Attr" columns onto the Ref(s) of a selected relation. - for (const [key, a] of Object.entries(attrs)) { - const dot = key.indexOf("."); - if (dot < 0 || a._type !== "Attribute") continue; - const rel = key.slice(0, dot), attr = key.slice(dot + 1); - if (attr.includes(".")) continue; // deeper paths stay as columns only - const target = out[rel]; - const values = a.value; - let folded = false; - if (Array.isArray(target) && Array.isArray(values)) { target.forEach((ref, i) => { if (ref && typeof ref === "object") (ref as Record)[attr] = values[i]; }); folded = true; } - else if (target && typeof target === "object" && !Array.isArray(target) && !Array.isArray(a.value)) { (target as Record)[attr] = a.value; folded = true; } - // On the Ref now. The dotted key goes unless the caller selected that path by name. - if (folded && !select?.includes(key)) delete out[key]; - } return out as Row; } diff --git a/test/integration/client.test.ts b/test/integration/client.test.ts index 0b8a569..ae81066 100644 --- a/test/integration/client.test.ts +++ b/test/integration/client.test.ts @@ -56,13 +56,13 @@ describeInstance("client reads (live)", () => { expect(typeof row["Scope.Name"]).toBe("string"); // its relation was not selected: the path is still there expect((row.Owners as { _oid: string }[]).map((o) => o._oid)).toEqual([me._oid]); } - // query.v1 and api/asset Refs are bare; rest-1 puts the display attributes it sends on the Ref as well. - expect(viaQuery.Owners).toEqual([{ _oid: me._oid }]); - expect(viaPage.Owners).toEqual([{ _oid: me._oid }]); - expect((viaRest.Owners as { Name: string }[])[0]!.Name).toBe(me.Name); - // rest-1 without the dotted path selected: its uninvited columns are on the Ref, not on the row. + // A Ref is bare on all three: the three rows are the same row. + expect(viaPage).toEqual(viaQuery); + expect(viaRest).toEqual(viaQuery); + expect(viaRest.Owners).toEqual([{ _oid: me._oid }]); + // rest-1 without the dotted path selected: the display columns it sends unasked are nowhere, not on the row and not on the Ref. const bare = (await rest1.list(client.transport, "Story", { select: ["Name", "Owners"], filter: [`ID='${story}'`], page: { size: 1, start: 0 } })).rows[0]! as unknown as Record; - expect(Object.keys(bare).sort()).toEqual(["Name", "Owners", "_oid"]); + expect(bare).toEqual({ _oid: story, Name: viaQuery.Name, Owners: [{ _oid: me._oid }] }); // And a refused rest-1 read is a QUERY_REJECTED with sentences, like query.v1's. await expect(rest1.list(client.transport, "Story", { filter: ["Nope=1"], page: { size: 1, start: 0 } })).rejects.toMatchObject({ kind: "invalid", code: "QUERY_REJECTED", message: expect.stringMatching(/^Invalid WHERE parameter; /) }); await expect(client.query({ from: "Story", filter: ["Nope=1"], page: { size: 1, start: 0 } })).rejects.toMatchObject({ kind: "invalid", code: "QUERY_REJECTED" }); diff --git a/test/integration/rest1.test.ts b/test/integration/rest1.test.ts index 7671e28..609f066 100644 --- a/test/integration/rest1.test.ts +++ b/test/integration/rest1.test.ts @@ -43,11 +43,12 @@ describeInstance("rest1 (live)", () => { it("get reads one asset with its relations as Refs, and history reads the same asset one moment per row", async () => { const { rows: [any] } = await rest1.list(t, "Story", { select: ["Name"], page: { size: 1, start: 0 } }); expect(any).toBeDefined(); - const one = await rest1.get(t, any!._oid, ["Name", "Scope", "Owners", "Super"]); + const one = await rest1.get(t, any!._oid, ["Name", "Scope", "Scope.Name", "Owners", "Super"]); expect(one._oid).toBe(any!._oid); expect(one.Name).toBe(any!.Name); expect(one.Scope).toMatchObject({ _oid: expect.stringMatching(/^Scope:\d+$/) }); - expect(typeof one.Scope?.Name).toBe("string"); // rest-1 adds Scope.Name beside a selected Scope; folded onto the Ref + expect(one.Scope).toEqual({ _oid: one.Scope!._oid }); // a Ref is bare: the columns rest-1 adds beside it are not on it + expect(typeof one["Scope.Name"]).toBe("string"); // the path, selected, is at row[path] const moments = await rest1.history(t, any!._oid, { select: ["Name", "ChangeDate"], page: { size: 3, start: 0 } }); expect(moments.rows.length).toBeGreaterThan(0); for (const m of moments.rows) expect(m._oid).toMatch(new RegExp(`^${any!._oid}:\\d+$`)); diff --git a/test/integration/search.test.ts b/test/integration/search.test.ts index e5f3080..4ba8bd1 100644 --- a/test/integration/search.test.ts +++ b/test/integration/search.test.ts @@ -1,5 +1,6 @@ import { afterAll, beforeAll, expect, it } from "vitest"; import { AgilityApiClient } from "../../src/client"; +import { CONCRETE_SUBTYPES } from "../../src/types/assets/subtypes"; import { queryV1, rest1 } from "../../src/wire"; import { deleteFixtures, describeInstance, instance } from "./instance"; @@ -169,7 +170,16 @@ describeInstance("search (live)", () => { expect((await client.search(word, { types: SIXTEEN, findin: ["Name"], page })).rows.every((r) => !r._oid.startsWith("Message:"))).toBe(true); }); - it("client.search refuses, before any search is sent: no text, no types, an abstract type, an unknown type, a name no type defines", async () => { + it("types: [\"Workitem\"] searches the family: the generated list of its concrete subtypes is what this instance's Workitems are", async () => { + const hits = await client.search(word, { types: ["Workitem"], sort: ["ID"], page }); + expect(hits.rows.map((r) => r._oid)).toEqual([story, defect]); // the Issue is not a Workitem + // The expansion against the server: no Workitem on the instance has a type outside the list (zero rows), and the control inside it finds rows. + const family = CONCRETE_SUBTYPES.Workitem!; + expect(await client.query({ from: "Workitem", select: ["AssetType"], filter: [`AssetType!=${family.map((t) => `'${t}'`).join(",")}`], page: { size: 1, start: 0 } })).toEqual([]); + expect(await client.query({ from: "Workitem", select: ["AssetType"], filter: [`AssetType=${family.map((t) => `'${t}'`).join(",")}`], page: { size: 1, start: 0 } })).toHaveLength(1); + }); + + it("client.search refuses, before any search is sent: no text, no types, the root type, an unknown type, a name no type defines", async () => { const refused = async (run: () => Promise, message: RegExp) => { const before = requests.filter((r) => r.path.startsWith("/rest-1.v1")).length; await expect(run()).rejects.toMatchObject({ kind: "usage", status: 0, message: expect.stringMatching(message) }); @@ -177,7 +187,7 @@ describeInstance("search (live)", () => { }; await refused(() => client.search(" ", { types: ["Story"], page }), /needs text/); await refused(() => client.search(word, { types: [], page }), /needs `types`/); - await refused(() => client.search(word, { types: ["Workitem"], page }), /abstract type/); + await refused(() => client.search(word, { types: ["BaseAsset"], page }), /abstract type/); await refused(() => client.search(word, { types: ["NoSuchType"], page }), /no asset type "NoSuchType"/); await refused(() => client.search(word, { types: ["Story", "Issue"], select: ["Name", "Nmae"], page }), /"Nmae" is not an attribute of any type searched \(Story, Issue\)/); }); diff --git a/test/unit/rest1.test.ts b/test/unit/rest1.test.ts index 81c60ac..d3dd820 100644 --- a/test/unit/rest1.test.ts +++ b/test/unit/rest1.test.ts @@ -27,30 +27,25 @@ const storyDoc: AssetDocument = { }; describe("rest1: translation", () => { - it("turns a rest-1 asset into the model shape: Refs for relations (null when unset), display columns folded onto the Refs, AssetState by name, plain values otherwise", () => { - const row = fromAssetDocument(storyDoc); - expect(row._oid).toBe("Story:2104"); - expect(row.Name).toBe("Legal Check"); - expect(row.Estimate).toBe(2); - expect(row.AssetState).toBe("Closed"); - expect(row.Number).toBe("S-01530"); - expect(row.Super).toBeNull(); - expect(row.Status).toEqual({ _oid: "StoryStatus:137", Name: "Accepted" }); - expect(row.Owners).toEqual([{ _oid: "Member:1035", Name: "Alfred Smith", Nickname: "alfred" }, { _oid: "Member:20", Name: "Betty Builder", Nickname: "betty" }]); - // rest-1 sent those display columns uninvited: they are on the Refs, and the row has no key nobody selected. - expect(Object.keys(row).filter((k) => k.includes("."))).toEqual([]); + it("turns a rest-1 asset into the model shape: bare Refs for relations (null when unset), AssetState by name, plain values otherwise", () => { + const row = fromAssetDocument(storyDoc, { select: ["Name", "Status", "AssetState", "Estimate", "Super", "Owners", "Number"] }); + expect(row).toEqual({ + _oid: "Story:2104", Name: "Legal Check", Estimate: 2, AssetState: "Closed", Number: "S-01530", Super: null, + // A Ref is { _oid } and nothing else: the display columns rest-1 sent beside each relation, unasked, are not on it, + Status: { _oid: "StoryStatus:137" }, + Owners: [{ _oid: "Member:1035" }, { _oid: "Member:20" }] + // and they are not keys of the row either: nothing arrives that was not selected. + }); }); - it("the rows rule on rest-1: a path selected by name keeps its key (a parallel array beside bare-looking Refs for a multi-value relation); one with no Ref to fold onto is kept as sent", () => { - const selected = fromAssetDocument(storyDoc, { select: ["Name", "Owners", "Owners.Name", "Status.Name"] }) as unknown as Record; - expect(selected["Owners.Name"]).toEqual(["Alfred Smith", "Betty Builder"]); - expect(selected["Status.Name"]).toBe("Accepted"); - expect(selected["Owners.Nickname"]).toBeUndefined(); // uninvited: on the Refs only - expect((selected.Owners as { Nickname: string }[]).map((o) => o.Nickname)).toEqual(["alfred", "betty"]); - // A dotted or type-qualified key whose relation is not in the row has nothing to fold onto: it is all there is of the value, so it stays. - const lone: AssetDocument = { _type: "Asset", href: "", id: "Story:1", Attributes: { "Scope.Name": { _type: "Attribute", name: "Scope.Name", value: "Release 1" }, "Story.Number": { _type: "Attribute", name: "Story.Number", value: "S-1" } } }; - expect(fromAssetDocument(lone)).toEqual({ _oid: "Story:1", "Scope.Name": "Release 1", "Story.Number": "S-1" }); - expect(fromAssetDocument(lone, { select: ["Name"] })).toEqual({ _oid: "Story:1", "Scope.Name": "Release 1", "Story.Number": "S-1" }); + it("the rows rule on rest-1: a path selected by name is at row[path] (a parallel array for a multi-value relation), plain or type-qualified; with no select, every column the server chose stays under its own key", () => { + const selected = fromAssetDocument(storyDoc, { select: ["Name", "Owners", "Owners.Name", "PrimaryWorkitem.Status.Name"] }) as unknown as Record; + expect(selected).toEqual({ _oid: "Story:2104", Name: "Legal Check", Owners: [{ _oid: "Member:1035" }, { _oid: "Member:20" }], "Owners.Name": ["Alfred Smith", "Betty Builder"], "Status.Name": "Accepted", Status: { _oid: "StoryStatus:137" }, AssetState: "Closed", Estimate: 2, Super: null, Number: "S-01530" }); + expect(selected["Owners.Nickname"]).toBeUndefined(); // unasked, so absent: not on the row, not on the Refs + // No select (a template, a bare read): the server chose the attributes, so what it sent is the row; Refs are still bare. + const unselected = fromAssetDocument(storyDoc) as unknown as Record; + expect(unselected.Status).toEqual({ _oid: "StoryStatus:137" }); + expect([unselected["Status.Name"], unselected["Owners.Name"], unselected["Owners.Nickname"]]).toEqual(["Accepted", ["Alfred Smith", "Betty Builder"], ["alfred", "betty"]]); }); it("a read rest-1 refuses is a QUERY_REJECTED with the server's sentences, like one query.v1 refuses; a page has `more`", async () => { diff --git a/test/unit/search.test.ts b/test/unit/search.test.ts index fc574d7..5ad4e95 100644 --- a/test/unit/search.test.ts +++ b/test/unit/search.test.ts @@ -81,7 +81,15 @@ describe("search", () => { expect(one.calls[0]).toMatchObject({ path: "/rest-1.v1/Data/Request", query: { sel: "Name,Number,Owner", findin: "Name,Number", where: undefined } }); }); - it("a mistake in the call is a usage error and nothing is sent: no text, no page, no types, an abstract or unknown type, a name no searched type defines (naming the types checked)", async () => { + it("a family named by its abstract type stands for its concrete subtypes, beside any other type, each once", async () => { + const t = recording(); + await search(t, schema(), "printer", { types: ["Workitem", "Story", "Request"], select: ["Name"], page }); + expect(t.calls[0]!.query).toMatchObject({ where: "AssetType='Defect','Epic','Story','Task','Test','TestSet','Theme','Request'" }); + await search(t, schema(), "printer", { types: ["PrimaryWorkitem"], select: ["Number"], findin: ["Name"], page }); + expect(t.calls[1]).toMatchObject({ path: "/rest-1.v1/Data/BaseAsset", query: { where: "AssetType='Defect','Story','TestSet'", sel: "Defect.Number,Story.Number,TestSet.Number" } }); + }); + + it("a mistake in the call is a usage error and nothing is sent: no text, no page, no types, an unknown type or a root that is no family, a name no searched type defines (naming the types checked)", async () => { const t = recording(); const s = schema(); const refused = async (run: () => Promise, message: RegExp) => { @@ -92,7 +100,7 @@ describe("search", () => { await refused(() => search(t, s, " ", { types: ["Story"], page }), /needs text/); await refused(() => search(t, s, "x", { types: ["Story"] } as never), /without a page/); await refused(() => search(t, s, "x", { types: [], page }), /needs `types`/); - await refused(() => search(t, s, "x", { types: ["Workitem"], page }), /"Workitem" is an abstract type/); + await refused(() => search(t, s, "x", { types: ["BaseAsset"], page }), /"BaseAsset" is an abstract type whose concrete subtypes the SDK does not know/); await refused(() => search(t, s, "x", { types: ["Sotry"], page }), /no asset type "Sotry"/); await refused(() => search(t, s, "x", { types: ["Story", "Issue"], select: ["Nmae"], page }), /select "Nmae" is not an attribute of any type searched \(Story, Issue\)/); await refused(() => search(t, s, "x", { types: ["Story", "Issue"], findin: ["Nmae"], page }), /findin "Nmae"/); diff --git a/test/unit/testing.test.ts b/test/unit/testing.test.ts index e206d9c..08cbefe 100644 --- a/test/unit/testing.test.ts +++ b/test/unit/testing.test.ts @@ -147,13 +147,13 @@ describe("FakeAgilityClient", () => { ]; const fake = new FakeAgilityClient().onList("BaseAsset", found); const page = await rest1.list(fake.transport, "BaseAsset", { find: "logon", findin: ["Name"], select: ["Name", "Number", "AssetState", "Owners", "Owners.Name", "Status"], page: { size: 2, start: 0 }, needTotal: true }); - // As scripted, read back through the client's own rest-1 translation: so, as live, a selected dotted path is also on its Refs. - expect(page.rows).toEqual([{ ...found[0], Owners: [{ _oid: "Member:20", Name: "Dana" }] }, found[1]]); + // As scripted, read back through the client's own rest-1 translation: a selected path is at row[path], and a Ref is bare. + expect(page.rows).toEqual([found[0], found[1]]); expect(page).toMatchObject({ total: 3, more: true }); expect((await rest1.list(fake.transport, "BaseAsset", { page: { size: 2, start: 2 }, needTotal: true })).rows).toEqual([found[2]]); - // What a scripted Ref carries stays on it, as rest-1's display columns do live, whether or not the dotted path was selected. + // What a scripted Ref carries beyond its OID goes out as rest-1's display columns do, and is read back as live: at the path when it was selected, nowhere when it was not. fake.onList("Story", [{ _oid: "Story:1", Status: { _oid: "StoryStatus:1", Name: "Dev" }, Owners: [{ _oid: "Member:1", Name: "a", Nickname: "A" }, { _oid: "Member:2", Name: "b", Nickname: "B" }] }]); - expect((await rest1.list(fake.transport, "Story", { select: ["Status", "Owners"], page: { size: 1, start: 0 } })).rows).toEqual([{ _oid: "Story:1", Status: { _oid: "StoryStatus:1", Name: "Dev" }, Owners: [{ _oid: "Member:1", Name: "a", Nickname: "A" }, { _oid: "Member:2", Name: "b", Nickname: "B" }] }]); + expect((await rest1.list(fake.transport, "Story", { select: ["Status", "Owners", "Owners.Name"], page: { size: 1, start: 0 } })).rows).toEqual([{ _oid: "Story:1", Status: { _oid: "StoryStatus:1" }, Owners: [{ _oid: "Member:1" }, { _oid: "Member:2" }], "Owners.Name": ["a", "b"] }]); expect(fake.requests[0]).toMatchObject({ method: "GET", path: "/rest-1.v1/Data/BaseAsset", query: { find: "logon", findin: "Name", page: "2,0" } }); // A function sees the type and rest-1's own query string, and answers one page. fake.onList((type, q) => type === "Story" && q.deleted === "true", () => ({ rows: [{ _oid: "Story:7", Name: "gone" }], total: 12 })); From 3933327fd11e13a90c6defbaccbbe3cb7d6aa77d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:56:40 +0000 Subject: [PATCH 06/11] Search: a column no searched type has is null; one date spelling; the fake answers at its transport A select name none of the searched types defines is left out of the request and null on every row, so one list of columns serves any choice of types; only a name that is no attribute of any asset type is refused (from a generated set of the product's attribute names). A findin name none has is dropped; none left is refused. A date is spelled one way on every read (seven decimals, Z on a UTC attribute): query.v1, api/asset and rest-1 each wrote it differently. The schema says what is a date, so text that looks like one is untouched. onSearch answers at the fake's transport, so a client built on fake.transport searches the same way; the fake's instance has any type a scripted search names. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 20 +++++- README.md | 7 ++- scripts/generate-types.mjs | 12 +++- specs/000-layers.md | 9 ++- src/client.ts | 13 ++-- src/services/search.ts | 51 ++++++++++------ src/testing/index.ts | 104 +++++++++++++++++++++----------- src/types/asset.ts | 17 +++++- src/types/assets/subtypes.ts | 6 ++ src/wire/assetApi.ts | 4 +- src/wire/rest1.ts | 47 +++++++++++---- test/integration/client.test.ts | 18 +++++- test/integration/search.test.ts | 15 ++++- test/unit/client.test.ts | 13 ++-- test/unit/search.test.ts | 67 ++++++++++++++++---- test/unit/translate.test.ts | 4 +- 16 files changed, 306 insertions(+), 101 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b63eaf..ff57209 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,19 @@ code for a name read off a relation. A read with no select at all (a template) keeps every column the server sent, each under its own key (`template["Scope.Name"]`), and its Refs are bare too. (a CLI consumer.) +- **A date has one spelling on every read**: `"2026-09-06T13:52:51.9030000"` + (seven decimals; a `Z` on a UTC attribute). The endpoints differ, and + rows used to carry whichever spelling the endpoint behind the call + used: `query` / `get` answered seven decimals (unchanged), `queryPage` + answered `"…51.903"` with trailing zeros dropped, and `history`, + `template` and the rest-1 reads answered three decimals and a midnight + as the date alone (`"2011-09-20"`). Nothing is cut: seven decimals is + the server's precision. Migration: code that compares date strings from + `queryPage`, `history` or `template` against stored ones, or slices + them by position, should parse them (`new Date(value)`) or expect the + one spelling. `rest1.list` / `get` / `history` / `template` from + `/wire` spell dates this way when given `{ lookup: client.schema }`, + and as rest-1 sent them without. (a CLI consumer.) - **A read with an empty `find` throws a `UsageError`** (`kind: "usage"`, nothing is sent), on `query`, `queries`, `queryPage`, `pages`, `all` and `deleted`. It used to answer no rows, because that is what the server @@ -44,7 +57,9 @@ abstract type (`"Workitem"`). `select` and `findin` take plain attribute names, and each row has every selected key under that name: its value if the row's type defines the attribute, `null` if not, so a Story and a - Request both have `Number`. Nothing type-qualified is written or read + Request both have `Number`, and a name none of the searched types has + is `null` on every row (only a name that is no attribute of anything is + refused). Nothing type-qualified is written or read in a select; `filter` is sent as written and may be type-qualified, since a condition across types has no plain spelling. A consumer that built this from `client.data.list("BaseAsset", …)` with @@ -53,7 +68,8 @@ - **`client.deleted(type, params)`**: deleted assets of a type, as `{ rows, total, more }`. - `FakeAgilityClient.onSearch(rows)` and `fake.searched`, to test code - that searches. + that searches, through the fake or through a client built on + `fake.transport`. - `@versionone/agility-sdk/services` has `search`. The root exports the types `SearchOptions`, `SearchResult`, `SearchRow`. diff --git a/README.md b/README.md index 0d76e1d..04f6daf 100644 --- a/README.md +++ b/README.md @@ -112,13 +112,16 @@ const { rows, total, more } = await client.search("warehouse ship*", { - **One request, one order across every type, and the total.** The matching rules above apply. - **`types` is required**, at least one: concrete types, or a family by its abstract type (`"Workitem"` is stories, defects, epics, themes, tasks, tests and test sets; requests, issues and goals are not work items, so name them). A default would silently leave types out. -- **You name an attribute once, plainly, and each row has that key**: its value if the row's type defines it, `null` if not (`Owners` is null on a Request, `Owner` null on a Story; the SDK does not merge differently named attributes). A name none of the types defines is a usage error that lists the types. +- **You name an attribute once, plainly, and each row has that key**: its value if the row's type defines it, `null` if not (`Owners` is null on a Request, `Owner` null on a Story; the SDK does not merge differently named attributes). That holds when none of the searched types has it too: every row has `null`, so one list of columns serves whatever types a user picks. Only a name that is no attribute of any asset type is a usage error (a misspelling). A `findin` name none of the searched types has is left out; if none is left, the search is refused. - `select` defaults to `Name`, `Number`, `AssetType`, `AssetState`; `findin` defaults to `Name` and `Number`. - A relation is a bare `{ _oid }`; ask for a display value as a path (`"Scope.Name"`, `"Owners.Name"`). - **Selects are plain; filters are sent as written and may be type-qualified.** A select names a value, and the SDK can ask each type for it. A filter is an expression: a condition across types, such as "owned by me" when work items have `Owners` and requests have `Owner`, has no plain spelling, so you write it: `"(Workitem.Owners.IsSelf='true'|Request.Owner.IsSelf='true')"`. A term on an attribute every searched type shares (`AssetState`, `Scope.Name`) needs no qualifying. `sort` is sent as written too. - Deleted assets are never found; `client.deleted(type, params)` reads those. +- The first search loads the schema of each type searched (one request per type, then cached for the client, or shared through a `TypeCache`). A short-lived process that searches once pays that every time: seed the cache (`TypeCache.fromMetamodel`) or keep the client. - To find one asset by its exact number, do not search: `client.resolve.numbers(["S-01042"])` is exact and does not wait for the text index. +A date is spelled one way on every read: `"2026-09-06T13:52:51.9030000"`, seven decimals, with a `Z` on a UTC attribute (`ChangeDateUTC`). The endpoints each write dates differently, and the SDK answers this one spelling whichever of them was asked; `new Date(value)` reads it. + 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`. ### Reference @@ -166,7 +169,7 @@ expect(fake.sent[0]).toEqual([{ from: "Story:1", execute: "QuickClose" }]); - `onQuery(match, rows)` answers every read (`query`, `get`, `queryPage`, `pages`, …). A list is the whole result: the fake pages it and answers a read by OID with that row. A function gets the query and answers one page. A read nothing was scripted for throws; it never looks like an empty result. - Writes need no script: a create answers a new OID, an update or operation by OID answers that OID. `onSend` scripts anything else, failures included. -- `onSearch(rows)` answers `client.search`: the fake pages the rows, reports the total, and cuts each row to the selected keys; `fake.searched` is what was asked. It sends no request. +- `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. - `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. diff --git a/scripts/generate-types.mjs b/scripts/generate-types.mjs index a7757a2..d0e1221 100644 --- a/scripts/generate-types.mjs +++ b/scripts/generate-types.mjs @@ -14,8 +14,9 @@ * Asset root (src/types/asset.ts). * - src/types/assets/index.ts: every type re-exported, the AssetTypeName * union, and an AssetTypeMap from token to interface. - * - src/types/assets/subtypes.ts: the one generated value, each abstract - * type's concrete subtypes (`Workitem` → Story, Defect, Epic, …). + * - src/types/assets/subtypes.ts: the generated values, kept small: each + * abstract type's concrete subtypes (`Workitem` → Story, Defect, Epic, + * …), and the set of every attribute name the product has. * * What the output is not: * - endpoint-aware. A relation is a Ref (or Ref[]); how api/asset, query.v1 @@ -184,6 +185,7 @@ export function model(metamodel) { // The one generated VALUE: an abstract type's concrete subtypes, for a caller that names a family ("Workitem") // where the server wants concrete types. The root is left out: "every asset" is not a family anyone searches. + const attributeNames = [...new Set(tokens.flatMap((t) => Object.values(types[t].Attributes).filter((a) => a.IsCanned !== false && !a.Name.includes(".")).map((a) => a.Name)))].sort(); const families = tokens.filter((t) => types[t].Abstract && baseOf(t) && descendants(t).length); const subtypes = [ `// Generated by scripts/generate-types.mjs from metamodel.json (meta.v1 ${metamodel.Version}); do not edit.`, @@ -191,6 +193,12 @@ export function model(metamodel) { `export const CONCRETE_SUBTYPES: Readonly> = {`, ...families.map((t) => ` ${t}: [${descendants(t).map((n) => JSON.stringify(n)).join(", ")}],`), `};`, + ``, + `/**`, + ` * Every attribute name some asset type of the product has. It tells a name that is merely absent from the types`, + ` * at hand (a Request has no Estimate) from one that is no attribute at all (a misspelling).`, + ` */`, + `export const ATTRIBUTE_NAMES: ReadonlySet = new Set(${JSON.stringify(attributeNames.join(","))}.split(","));`, `` ].join("\n"); diff --git a/specs/000-layers.md b/specs/000-layers.md index bc006a8..e611c29 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -47,6 +47,12 @@ from or are going. A relation is a `Ref` (`{ _oid }`, plus what a sub-select ask in `Attributes` and rendering `AssetState` as a number — is translated in that endpoint's wire module, once, on the way in and on the way out. +A date is one of those spellings. query.v1 writes seven decimals, +api/asset drops trailing zeros, rest-1 writes three and a midnight as the +date alone; the model's `DateString` is `2026-09-06T13:52:51.9030000` +(with `Z` on a UTC attribute), and every read answers it. The schema says +which attribute is a date: text that looks like one is never touched. + A row's identity is `_oid`: the key the server sends for it, underscored so that it can never collide with an attribute (an asset's own identity attribute is `ID`). Every row has it, and so does anything that is a row @@ -70,7 +76,8 @@ asset through all three paths and compares the rows. One addition, for the one read whose page mixes unrelated types (`client.search`): **you name an attribute once, plainly, and each row has that key — its value if the row's type defines the attribute, null if it -does not.** This is the only place a row carries a key its own type lacks. +does not** (so null on every row when none of the searched types has it; +only a name that is no attribute of any type is refused). This is the only place a row carries a key its own type lacks. The caller never writes or reads a type-qualified name (`Story.Number`): the schema says which of the searched types define `Number`, the service asks each, and the key is `Number`. A relation on such a row is a bare diff --git a/src/client.ts b/src/client.ts index 6b1b2a4..7dd0488 100644 --- a/src/client.ts +++ b/src/client.ts @@ -308,7 +308,8 @@ export class AgilityApiClient { */ async deleted(type: string, params: Omit): Promise> { searchable(type, params.find); - const { rows, total, more } = await rest1.list(this.transport, type, { ...params, filter: [...(params.filter ?? []), "IsDeleted='true'"], deleted: true, needTotal: params.needTotal ?? true }); + await this.schema.ensureFor([{ from: type, select: params.select }]); + const { rows, total, more } = await rest1.list(this.transport, type, { ...params, filter: [...(params.filter ?? []), "IsDeleted='true'"], deleted: true, needTotal: params.needTotal ?? true }, { lookup: this.schema }); return { rows, total, more }; } @@ -317,8 +318,9 @@ export class AgilityApiClient { * row's `_oid` carrying its moment (`Story:1234:5678`). `target` is an * OID token, or an asset type for the history of every asset of it. */ - history(target: string, params: rest1.ReadParams): Promise> { - return rest1.history(this.transport, target, params); + async history(target: string, params: rest1.ReadParams): Promise> { + await this.schema.ensureFor([{ from: target.split(":")[0]!, select: params.select }]); + return rest1.history(this.transport, target, params, { lookup: this.schema }); } /** @@ -326,8 +328,9 @@ export class AgilityApiClient { * a context (a Timebox's next name and dates in a schedule's scope, a * Story's carry-over from a Request). Nothing is created. */ - template(type: F, options?: { ctx?: Oid }): Promise>> { - return rest1.template>(this.transport, type, options); + async template(type: F, options?: { ctx?: Oid }): Promise>> { + await this.schema.load(type); + return rest1.template>(this.transport, type, { ...options, lookup: this.schema }); } /** diff --git a/src/services/search.ts b/src/services/search.ts index c6bde2a..8ffea4f 100644 --- a/src/services/search.ts +++ b/src/services/search.ts @@ -21,7 +21,7 @@ import { UsageError } from "../core/errors"; import type { Transport } from "../core/transport"; import type { Asset, Oid } from "../types/asset"; -import { CONCRETE_SUBTYPES } from "../types/assets/subtypes"; +import { ATTRIBUTE_NAMES, CONCRETE_SUBTYPES } from "../types/assets/subtypes"; import * as rest1 from "../wire/rest1"; import type { Schema } from "./schema"; @@ -40,11 +40,17 @@ export interface SearchOptions { types: readonly string[]; /** * Attributes for each row, by plain name; a path (`"Scope.Name"`) is - * keyed as written. A row whose type lacks one has null there. Default: - * Name, Number, AssetType, AssetState. + * keyed as written. A row whose type lacks one has null there, and so + * does every row when none of the searched types has it. Default: Name, + * Number, AssetType, AssetState. */ select?: readonly string[]; - /** Attributes to search in, by plain name. Default: Name and Number. Always sent: the server's own default differs by type. */ + /** + * Attributes to search in, by plain name. Default: Name and Number. + * Always sent: the server's own default differs by type. One that none + * of the searched types has is left out; if none is left, the search is + * refused. + */ findin?: readonly string[]; /** * Filter terms, sent as written. Unlike a select, a filter is an @@ -101,21 +107,24 @@ async function checked(schema: Schema, types: readonly string[]): Promise { const head = name.split(".")[0]!; - if (schema.attribute(ROOT, head)) return [name]; - const defining = types.filter((t) => schema.attribute(t, head)); - if (!defining.length) throw new UsageError(`search: ${what} "${name}" is not an attribute of any type searched (${types.join(", ")})`); + if (one ? schema.attribute(types[0]!, head) : schema.attribute(ROOT, head)) return [name]; + const defining = one ? [] : types.filter((t) => schema.attribute(t, head)); + if (!defining.length && !ATTRIBUTE_NAMES.has(head) && !head.startsWith("Custom_")) throw new UsageError(`search: ${what} "${name}" is not an attribute of any asset type (searched: ${types.join(", ")})`); return defining.map((t) => `${t}.${name}`); }); } @@ -143,15 +152,21 @@ export async function search(transport: T variables[name] = value; }); if (!one) filter.unshift(`AssetType=${types.map(quoted).join(",")}`); + const searchIn = spelled(schema, types, findin, "findin"); + if (!searchIn.length) throw new UsageError(`search: none of the types searched (${types.join(", ")}) has any of the attributes in \`findin\` (${findin.join(", ")}): there is nothing to search in`); + const asked = spelled(schema, types, select, "select"); + // The paths' related types too, so a date at the end of a path is spelled as every read spells it. + await schema.ensureFor(types.map((from) => ({ from, select: select.filter((name) => schema.attribute(from, name.split(".")[0]!)) }))); const result = await rest1.list(transport, one ? types[0]! : ROOT, { find: text, - findin: spelled(schema, types, findin, "findin"), - select: spelled(schema, types, select, "select"), + findin: searchIn, + // Every searched asset has a Name: asked for when nothing selected applies, so the server does not choose the attributes itself. + select: asked.length ? asked : ["Name"], filter: filter.length ? filter : undefined, with: Object.keys(variables).length ? variables : undefined, sort: options.sort ? [...options.sort] : undefined, page: options.page, needTotal: true - }); + }, { lookup: schema }); return { rows: result.rows.map((row) => shaped(row, select)), total: result.total, more: result.more }; } diff --git a/src/testing/index.ts b/src/testing/index.ts index 7be9587..94ceb34 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -18,7 +18,8 @@ import { AgilityApiClient } from "../client"; export { CONFORMANCE_BASE_URL, fetchFrom, transportConformance } from "./transportConformance"; export type { ConformanceCheck, ConformanceRequest, ConformanceResponse, ConformanceServer } from "./transportConformance"; import type { ClientConfig } from "../core/clientConfig"; -import { DEFAULT_SELECT, type SearchOptions, type SearchResult, type SearchRow } from "../services/search"; +import type { SearchOptions, SearchResult, SearchRow } from "../services/search"; +import { ATTRIBUTE_NAMES } from "../types/assets/subtypes"; import { ApiError, UsageError, apiErrorFromResponse } from "../core/errors"; import type { RequestOptions, Transport } from "../core/transport"; import type { Asset, Oid } from "../types/asset"; @@ -55,16 +56,21 @@ const bodyOf = (command: Command): CommandBody => { const isQuery = (body: CommandBody): body is QueryBody => typeof (body as QueryBody).from === "string" && !("update" in body) && !("execute" in body) && !("AssetType" in body); const typeOfFrom = (from: string): string => (isOidToken(from) ? typeOfOid(from) ?? from : 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); type ListMatch = string | ((type: string, params: Record) => boolean); interface Script { + searches: SearchAnswer[]; + /** 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) }[]; metamodel: FakeOptions["metamodel"] | null; queries: { match: QueryMatch; answer: QueryAnswer }[]; sends: SendAnswer[]; requests: { match: RequestMatch; answer: RequestAnswer }[]; labels: Record; - seen: { requests: RequestOptions[]; asked: QueryBody[]; sent: Command[][] }; + seen: { requests: RequestOptions[]; asked: QueryBody[]; sent: Command[][]; searched: { text: string; options: SearchOptions }[] }; nextId: number; /** The fake's versions: each asset's moment (1 until something writes it), and the assets that are gone. */ moments: Map; @@ -171,6 +177,15 @@ function answerSend(script: Script, commands: Command[], writes: { body: Command return out; } +/** A type for the fake's instance to have when a search asks for one: concrete, under BaseAsset, with every attribute the product names and every key a scripted search row carries. */ +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 }])); + return { _type: "AssetType", Name: token, Token: token, DisplayName: token, Abstract: token === "BaseAsset", ...(token === "BaseAsset" ? {} : { Base: { nameref: "BaseAsset", href: "/meta.v1/BaseAsset" } }), Attributes }; +} + function respond(script: Script, request: RequestOptions): unknown { const raw = [...script.requests].reverse().find(({ match }) => (typeof match === "string" ? request.path.startsWith(match) : match instanceof RegExp ? match.test(request.path) : match(request))); // A type nothing scripted is a type the fake's instance does not have, so rows are read as scripted. These @@ -183,6 +198,12 @@ 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("/")) { + // 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 } }); + return anyType(script, decodeURIComponent(request.path.slice("/meta.v1/".length))); + } if (!raw && request.method === "GET" && request.path.startsWith("/meta.v1/")) throw apiErrorFromResponse(404, { error: "Not Found", exceptions: [{ message: `FakeAgilityClient knows no asset type at ${request.path}` }] }); script.seen.requests.push(request); if (raw) { @@ -197,6 +218,21 @@ function respond(script: Script, request: RequestOptions): unknown { 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; + if (params.find !== undefined && script.searches.length) { + // What a search asks today. The options are the fake client's own when it made the search; for a client built on + // the fake's transport they are what the request shows. + const [size, start] = (params.page ?? "").split(",").map(Number) as [number, number]; + const types = type === "BaseAsset" ? [...(/^AssetType=([^;]*)/.exec(params.where ?? "")?.[1] ?? "").matchAll(/'([^']*)'/g)].map((m) => m[1]!) : [type]; + const options: SearchOptions = script.searching ?? { types, page: { size, start } }; + script.seen.searched.push({ text: params.find, options }); + const answer = script.searches.at(-1)!; + if (answer instanceof Error) throw answer; + const answered = typeof answer === "function" ? answer(params.find, options) : answer; + const whole = Array.isArray(answered) && typeof answer !== "function"; + const all = (Array.isArray(answered) ? answered : (answered as { rows: readonly FakeRow[] }).rows) as readonly FakeRow[]; + const total = Array.isArray(answered) ? (whole ? all.length : undefined) : (answered as { total?: number | null }).total ?? undefined; + return { _type: "Assets", total, pageSize: size, pageStart: start, Assets: (whole ? all.slice(start, start + size) : all).map(toAssetDocument) }; + } const hit = [...script.lists].reverse().find(({ match }) => (typeof match === "function" ? match(type, params) : match === type)); if (hit) { if (hit.answer instanceof Error) throw hit.answer; @@ -344,8 +380,10 @@ function toAssetDocument(row: FakeRow): Record { * simulation with its own answer. A write scoped by a query cannot be * previewed by the fake (it evaluates no filter): script that preview * with `onRequest`. - * - `onSearch(rows)` answers `client.search`: rows in the model's shape, - * paged by the fake, with the total; what was searched is in `searched`. + * - `onSearch(rows)` answers a search, from this client or from one built + * on `fake.transport`: rows in the model's shape, paged by the fake, + * with the total; what was searched is in `searched`. Script it before + * the first search. * - `onList(type, rows)` answers rest-1's list read the same way * (`client.deleted`, and `rest1.list` from `/wire`): rows in * the model's shape, a list paged by the fake. @@ -364,13 +402,16 @@ export class FakeAgilityClient extends AgilityApiClient { readonly asked: QueryBody[]; /** Every batch that carried a write, in order, as sent: a Ref is written as its OID token. */ readonly sent: Command[][]; - /** Every search made, in order: its text and options. */ - readonly searched: { text: string; options: SearchOptions }[] = []; - private readonly searches: (FakeRows | Error | ((text: string, options: SearchOptions) => FakeRows))[] = []; + /** + * Every search made, in order: its text and options. A search made by a + * client of your own over `fake.transport` is recorded too, with the + * options the request shows: `types` and `page`. + */ + readonly searched: { text: string; options: SearchOptions }[]; private readonly script: Script; constructor(config: Partial & FakeOptions = {}) { - const script: Script = { lists: [], metamodel: config.metamodel ?? null, queries: [], sends: [], requests: [], labels: {}, seen: { requests: [], asked: [], sent: [] }, 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: [] }, 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 => { @@ -386,6 +427,7 @@ export class FakeAgilityClient extends AgilityApiClient { this.requests = script.seen.requests; this.asked = script.seen.asked; this.sent = script.seen.sent; + this.searched = script.seen.searched; } /** @@ -418,40 +460,32 @@ export class FakeAgilityClient extends AgilityApiClient { } /** - * Script what `client.search` answers: rows in the model's shape (a - * list is the whole result: the fake pages it and reports its length - * as the total), a function of the text and options answering one page, - * or an Error to throw. The answer scripted last wins. No text is - * matched and no filter evaluated; each row is cut to the keys the - * search selected, null where the row has none, as live. + * 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 + * total), a function of the text and options answering one page, or an + * Error to throw. The answer scripted last wins. No text is matched and + * no filter evaluated. The search itself is the client's own, so each + * row comes back with exactly the selected keys, null where the row has + * none, and it works the same for a client your code builds on + * `fake.transport`. Without a `metamodel` the fake's instance has any + * type a search names; script the search before the first one is made. */ - onSearch(answer: FakeRows | Error | ((text: string, options: SearchOptions) => FakeRows)): this { - this.searches.push(answer); + onSearch(answer: SearchAnswer): this { + this.script.searches.push(answer); return this; } /** - * `client.search` on the fake: the same refusals before anything is - * asked (no text, no types, no page), then the scripted answer. It sends - * no request, so a test does not depend on which endpoint a search uses. + * `client.search` on the fake: the client's own search, over the fake's + * transport. A search nothing was scripted for says so, rather than + * failing on the first thing the search happens to ask the instance. */ override async search(text: string, options: SearchOptions): Promise> { - if (typeof text !== "string" || !text.trim()) throw new UsageError("search needs text: the server answers a search for nothing with no rows, which would read as \"nothing matches\""); - if (!options?.page) throw new UsageError("search without a page: every read must be bounded"); - if (!Array.isArray(options.types) || !options.types.length) throw new UsageError("search needs `types`: the asset types to search, such as [\"Story\", \"Defect\", \"Request\"]; there is no default"); - this.searched.push({ text, options }); - const answer = this.searches.at(-1); - if (answer === undefined) throw new UsageError(`FakeAgilityClient: no answer scripted for search(${JSON.stringify(text)}); script one with onSearch`); - if (answer instanceof Error) throw answer; - const answered = typeof answer === "function" ? answer(text, options) : answer; - const whole = Array.isArray(answered) && typeof answer !== "function"; - const all = (Array.isArray(answered) ? answered : (answered as { rows: readonly FakeRow[] }).rows) as readonly FakeRow[]; - const { size, start } = options.page; - const page = whole ? all.slice(start, start + size) : all; - const total = Array.isArray(answered) ? (whole ? all.length : null) : (answered as { total?: number | null }).total ?? null; - const select = [...new Set(options.select ?? DEFAULT_SELECT)]; - const rows = page.map((row) => Object.fromEntries([["_oid", row._oid], ...select.map((name) => [name, (row as Record)[name] ?? null])]) as unknown as Row); - return { rows, total, more: total === null ? rows.length === size : start + rows.length < total }; + if (!this.script.searches.length && !this.script.metamodel && typeof text === "string" && text.trim() && options?.page && options.types?.length) { + throw new UsageError(`FakeAgilityClient: no answer scripted for search(${JSON.stringify(text)}); script one with onSearch`); + } + this.script.searching = options; + try { return await super.search(text, options); } finally { this.script.searching = null; } } /** Script labels for `client.localize`: tag → label. A tag nothing scripted answers itself, as loc-2 answers a tag it does not know. */ diff --git a/src/types/asset.ts b/src/types/asset.ts index 641062a..9f1c0bd 100644 --- a/src/types/asset.ts +++ b/src/types/asset.ts @@ -10,9 +10,24 @@ /** An OID token, momentless: "Story:1234". */ export type Oid = string; -/** An ISO-8601 date-time as the API renders it, e.g. "2026-09-06T13:52:51.903". */ +/** + * A date-time as the model carries it: `"2026-09-06T13:52:51.9030000"`, + * with a `Z` when the attribute is a UTC one (`ChangeDateUTC`). One + * spelling on every read: the endpoints differ (query.v1 sends seven + * decimals, api/asset drops trailing zeros, rest-1 sends three and writes a + * midnight as the date alone), so each read spells the value this way. + * Seven decimals is the server's own precision; nothing is cut. + */ export type DateString = string; +const DATE = /^(\d{4}-\d\d-\d\d)(?:T(\d\d:\d\d:\d\d)(?:\.(\d{1,7}))?)?(Z)?$/; + +/** A date as any endpoint spells it, in the model's one spelling (see DateString). Anything else is answered as given. */ +export function dateString(value: T): T | DateString { + const m = typeof value === "string" ? DATE.exec(value) : null; + return m ? `${m[1]}T${m[2] ?? "00:00:00"}.${(m[3] ?? "").padEnd(7, "0")}${m[4] ?? ""}` : value; +} + /** * An AssetState as the model carries it: the names of the server's AssetState * enum (Future 0, Active 64, Closed 128, Dead 192, diff --git a/src/types/assets/subtypes.ts b/src/types/assets/subtypes.ts index 4088cb6..69df56a 100644 --- a/src/types/assets/subtypes.ts +++ b/src/types/assets/subtypes.ts @@ -6,3 +6,9 @@ export const CONCRETE_SUBTYPES: Readonly> = { Status: ["EpicStatus", "StoryStatus"], Workitem: ["Defect", "Epic", "Story", "Task", "Test", "TestSet", "Theme"], }; + +/** + * Every attribute name some asset type of the product has. It tells a name that is merely absent from the types + * at hand (a Request has no Estimate) from one that is no attribute at all (a misspelling). + */ +export const ATTRIBUTE_NAMES: ReadonlySet = new Set("ACLMask,AccessedAt,Activity,ActualAmount,ActualResults,Actuals,AffectedByDefects,AffectedPrimaryWorkitems,AlignedOkrs,AlignedStrategicThemes,AlignedWorkitems,AllocatedDetailEstimate,AllocatedToDo,AllocationStrategy,Allocations,AllowedRoles,AllowedStatusTransitions,AllowedStatuses,Amount,AmountType,Application,Area,AssessedBusinessValue,Asset,AssetState,AssetType,AssociatedConversations,AssociatedPublications,AttachedImages,Attachments,AttributeDefinition,AttributeToken,AttributeType,AudiencePattern,Author,AuthorEmail,AuthorIsSuspended,AuthorName,AuthoredAt,AuthoredTopics,Avatar,BeginDate,BelongsTo,Benefits,BlendedRate,BlockedEpics,BlockedPrimaryWorkitems,BlockedWorkitemsCount,BlockingIssues,Body,Budget,BudgetAllocation,Budgets,BuildProject,BuildProjects,BuildRuns,Builds,Bundles,By,Calculation,CalendarEvents,CanAddChild,CanAddOfficialComment,CanChangeSchedule,CanConvertToDefect,CanConvertToStory,CanEditCategory,CanEnableAuthor,CanFollow,CanMarkAppropriate,CanMarkApproved,CanMarkAsEnabled,CanMarkAsSuspended,CanMarkCandidate,CanMarkCompleted,CanMarkInappropriate,CanMarkNotPlanned,CanMarkPending,CanMarkPlanned,CanMove,CanSetDefault,CanSuspendAuthor,CanUnfollow,CanUpdate,Capacities,CapacityExcludedMembers,CapacityExcludedTeams,CascadedFrom,CascadedTo,Category,CategoryName,CausedBy,ChangeComment,ChangeDate,ChangeDateUTC,ChangeReason,ChangeSets,ChangedBy,CheckActivate,CheckAssignMemberWithRole,CheckAssignSubsAndMeToScope,CheckAssignToScopeWithRole,CheckBreakdown,CheckClose,CheckConvertToTeam,CheckCopy,CheckCopyAcceptanceTestsFromRegressionSuite,CheckCopyRelationsAndAcceptanceTestsFromRegressionSuite,CheckDeepCopy,CheckGenerateSubEpic,CheckGenerateSubStory,CheckInactivate,CheckInactivateCollaborator,CheckMakeFuture,CheckMakeTemplate,CheckPromote,CheckPromoteCollaborator,CheckQuickClose,CheckQuickSignup,CheckReactivate,CheckReactivateCollaborator,CheckRevoke,CheckSend,CheckShallowCopy,CheckSplit,Children,ChildrenAndDown,ChildrenAndMe,ChildrenMeAndDown,Class,ClassOfService,ClosedBy,ClosedDate,ClosedDateUTC,ClosedEstimate,Code,ColorName,Commitment,Communities,CompleteEstimate,CompletedInBuildRuns,CompletesPrimaryWorkitems,ComplexityRank,Concepts,ContainedExpressions,Content,ContentType,ConversationsHidden,CostOfDelay,CreateComment,CreateDate,CreateDateUTC,CreateReason,CreatedAt,CreatedAtUTC,CreatedBy,CriticalValue,CurrencyType,CurrentValue,Customer,CustomeredStories,CustomeredTasks,CustomeredThemes,Date,Days,DefaultCustomer,DefaultRole,DefaultScope,Defects,DefinedIn,DeliveredOn,DeliveredOnUTC,Deliveries,DeliveryCategory,Dependants,Dependencies,Description,DetailEstimate,DoneDate,DoneDateUTC,DuplicateOf,DuplicatedBy,Duration,EarliestActiveTimebox,EffectiveAssetState,Elapsed,ElicitedBy,Email,EmbeddedImages,EndDate,Environment,Environments,Epics,Estimate,EstimateAmount,EstimatedAllocatedDone,EstimatedDeliveryDateUTC,EstimatedDone,EventDefinition,ExpectedResults,Expression,ExpressionImages,ExpressionSpace,Expressions,ExternalActions,ExternalReference,FacilitatedBy,FacilitatedRetrospectives,Failed,FakeAssetState,Feedback,Filename,FilterByTeam,FilterTerms,FixedInBuild,FlaggedItems,Folder,FollowedCommunities,FollowedSpaces,Followers,Following,Forum,ForumTitle,FoundBy,FoundDefects,FoundInBuild,FoundInBuildRuns,FullName,FullVersion,GeneratedFrom,GeneratedRegressionTests,GeneratedTests,Goal,Goals,Grants,HasProcess,HideVoteCounts,History,Hotness,ID,Idea,Ideas,IdeasRole,IdeasUserCache,IdeasUserID,IdentifiedBy,IdentifiedIn,IdentifiedStories,ImportantFields,InReplyTo,Inactive,InappropriateItems,IncompleteEstimate,InitialValue,Initializer,Inputs,Invocations,InvokedOn,Is,IsActivityStream,IsAppropriate,IsArchived,IsAssetHistory,IsBasic,IsCanned,IsClosed,IsClosedState,IsCollaborator,IsCompleted,IsCustom,IsCustomLabel,IsDead,IsDefault,IsDeletable,IsDeleted,IsFavorite,IsHidden,IsInProgress,IsInactive,IsJoinable,IsKanban,IsLeavable,IsLoginDisabled,IsNotStarted,IsOfficial,IsPrivate,IsProtected,IsPublic,IsRead,IsReadOnly,IsRequired,IsRequiredAtClose,IsRevoked,IsSelf,IsSent,IsSuspended,IsTopic,IsUnarchived,IsUndeletable,IsUnread,Issues,Jeopardy,Key,KeyResults,LastAccessDate,LastActivity,LastActivityUTC,LastVersion,Level,LinkedFrom,LinkedTo,Links,Manager,Mascot,Member,MemberLabels,Members,MentionedInExpressions,Mentions,Message,MessageReceipts,Messages,Milestones,ModifiedBy,ModifyDateUTC,Moment,MorphedFrom,MorphedInto,MostRecentReply,MyLastChangeMoment,Name,NativeValue,NewQuickValuesFilter,NewValidValuesFilter,Nickname,NotRun,NotifyViaEmail,Now,Number,NumberOfComments,NumberOfIdeas,NumberOfVotes,OkrObjective,OkrObjectives,OkrSession,OnInsert,OnMenu,OnUpdate,OpenEstimate,Operation,Order,OriginalEstimate,OwnedApplications,OwnedByScope,OwnedGrants,OwnedIssues,OwnedOkrObjectives,OwnedRegressionPlans,OwnedRegressionSuites,OwnedRegressionTests,OwnedRequests,OwnedScopes,OwnedTimeboxes,OwnedTimesheets,OwnedWorkitems,Owner,Owners,OwnsScheme,PackageReference,PackageRevision,PackageVersion,Page,Parameter,Parent,ParentAndMe,ParentAndUp,ParentMeAndUp,Participants,ParticipatesIn,ParticipatesInConversations,Passed,Password,Payload,Phase,Phone,PlannedBusinessValue,PlannedCompletionBy,PlannedCompletionOf,PlannedEnd,PlannedRelease,PlannedStart,PlanningLevel,PotentialBaseAssetMatch,PrimaryWorkitems,Prior,Priority,PrivilegesMask,ProfileKey,Progress,Prompts,Publications,QuickValuesFilter,RaisedTopics,Receipts,ReceiveEmailNotifications,Received,ReceivedMessages,Recipient,Recipients,Reference,RegressionPlan,RegressionPlans,RegressionSuite,RegressionSuites,RegressionTests,RelatedAssetType,Release,Releases,Replies,RequestedBy,Requests,Resolution,ResolutionReason,RetireComment,RetireDate,RetireDateUTC,RetireReason,RetiredBy,Retrospectives,ReverseIsActivityStream,ReverseIsAssetHistory,ReverseIsBasic,ReverseName,ReverseNewQuickValuesFilter,ReverseNewValidValuesFilter,ReverseQuickValuesFilter,ReverseValidValuesFilter,Reviewer,RightsMask,Risk,RiskReduction,Roadmaps,RollupState,Room,Rooms,SavedViews,Schedule,ScheduledScopes,Scheme,Scope,ScopeLabel,ScopeLabels,Scopes,SecuredAssets,SecurityScope,SelectedInSchemes,SelectedValues,SendConversationEmails,Sent,Setup,SharedAccessWith,SharedOkrObjectives,ShowReportByWorkItemCount,Source,SplitFrom,SplitFromAndMe,SplitFromAndUp,SplitFromMeAndUp,SplitTo,SplitToAndDown,SplitToAndMe,SplitToMeAndDown,SpurredBy,SpurredRequests,StartDate,State,Status,StatusCode,StatusName,Steps,Stories,StrategicTheme,StrategicThemes,Stretch,SubState,Subs,SubsAndDown,SubsAndMe,SubsMeAndDown,Subscriber,SubscribesTo,Subscription,Summary,Super,SuperAndMe,SuperAndUp,SuperMeAndUp,Swag,TaggedWith,Target,TargetDate,TargetEstimate,TargetSwag,TargetSwagPeriod,TargetSwagValue,TargetValue,TargetVelocityPeriod,TargetVelocityValue,TargetedBy,Targets,Tasks,Team,TeamWorkflows,TestRuns,TestSets,TestSuite,Tests,Themes,TimeCriticality,Timebox,TimeboxGap,TimeboxLength,Timeboxes,Title,ToDo,ToStatus,Token,Topic,Topics,TotalChangeSets,TotalCommentFlags,TotalComments,TotalFlags,TotalHours,TotalIdeas,TotalPendingComments,TotalVotes,TotalWorkitems,Trigger,TriggerType,Triggered,TriggeredBy,Type,URL,Unit,UnitOfMeasure,UserAgent,Username,UsesLicense,ValidForAssetType,ValidValuesFilter,Value,ValueStream,VerifiedBy,VerifiedDefects,Version,VersionAffected,VersionTested,Versions,Viewers,WasAnEpic,Weekdays,WelcomeMessage,Workers,Workflow,WorkflowStatusTransitions,WorkflowTransitions,Workitem,Workitems,WorksOn,Wsjf".split(",")); diff --git a/src/wire/assetApi.ts b/src/wire/assetApi.ts index 2c98b47..1727c85 100644 --- a/src/wire/assetApi.ts +++ b/src/wire/assetApi.ts @@ -26,7 +26,7 @@ */ import { ApiError, UsageError } from "../core/errors"; import type { Transport } from "../core/transport"; -import type { Asset, Oid, Ref } from "../types/asset"; +import { dateString, type Asset, type Oid, type Ref } from "../types/asset"; import { parseViolation, type Command, type CommandFailureDetail, type CommandValue, type ExecuteBody, type Outcome, type QueryBody, type UpdateBody } from "../types/command"; import type { AssetTypeToken, AttributeLookup, AttributeTokenRef, AttributeType } from "../types/metamodel"; import { momentless } from "../types/oid"; @@ -157,6 +157,8 @@ function scalar(value: unknown, type: AttributeType): unknown { case "LongInt": case "Rank": // a 32-bit integer sent as a string ("-2000000000"); sorts as a number return toNumber(value); + case "Date": + return dateString(value); case "Boolean": return value === true || value === "True" || value === "true" ? true : value === false || value === "False" || value === "false" ? false : value; default: diff --git a/src/wire/rest1.ts b/src/wire/rest1.ts index 34068ae..62f3098 100644 --- a/src/wire/rest1.ts +++ b/src/wire/rest1.ts @@ -36,10 +36,12 @@ */ import { ApiError, UsageError } from "../core/errors"; import type { Transport } from "../core/transport"; -import { assetStateOf, type Asset, type Oid, type Ref } from "../types/asset"; +import { assetStateOf, dateString, type Asset, type Oid, type Ref } from "../types/asset"; +import type { AttributeLookup } from "../types/metamodel"; import { momentless } from "../types/oid"; import type { Query, QueryBody } from "./assetApi"; import { rejected } from "./queryV1"; +import { resolvePath } from "./select"; export { momentless }; @@ -108,6 +110,29 @@ export function fromAssetDocument(doc: AssetDocument, return out as Row; } +/** + * What a rest-1 read is given beyond its parameters: the schema, so a date + * is spelled as every read spells it. rest-1 sends values already typed + * (a number is a number) except dates, which it writes its own way, and a + * date cannot be told from text by its looks. Without a lookup, or for a + * type it has not loaded, values are as rest-1 sent them. + */ +export interface ReadContext { lookup?: AttributeLookup } + +/** The row's dates in the model's spelling, by the row's own type. */ +function dated(row: Row, lookup: AttributeLookup | undefined): Row { + if (!lookup) return row; + const type = row._oid.split(":")[0]!; + const values = row as unknown as Record; + for (const [key, value] of Object.entries(values)) { + if (key === "_oid" || (typeof value !== "string" && !Array.isArray(value))) continue; + const resolution = resolvePath(lookup, type, key); + if (resolution.kind !== "resolved" || resolution.definition?.AttributeType !== "Date") continue; + values[key] = Array.isArray(value) ? value.map(dateString) : dateString(value); + } + return row; +} + /** The query string rest-1 wants, from the model's parameters. */ export function toQuery(params: ReadParams): Record { return { @@ -129,7 +154,7 @@ export function toQuery(params: ReadParams): Record /** One page of a rest-1 read: the rows, the total when asked for with `needTotal` (null otherwise), and whether more pages follow (as `Page.more`: exact with a total, else whether this page came back full). */ export interface ReadResult { rows: Row[]; total: number | null; more: boolean; pageSize: number; pageStart: number } -async function read(transport: Transport, path: string, params: ReadParams, history: boolean): Promise> { +async function read(transport: Transport, path: string, params: ReadParams, history: boolean, context: ReadContext = {}): Promise> { if (!params.page) throw new UsageError(`rest-1 read of ${path} without a page: every read must be bounded`); let doc: AssetsDocument; try { @@ -138,20 +163,20 @@ async function read(transport: Transport, path: string, param // A read rest-1 refused (a bad filter, an unknown attribute) reads like one query.v1 refused. throw error instanceof ApiError && error.status === 400 ? rejected(error) : error; } - const rows = (doc.Assets ?? []).map((a) => fromAssetDocument(a, { history, select: params.select })); + const rows = (doc.Assets ?? []).map((a) => dated(fromAssetDocument(a, { history, select: params.select }), context.lookup)); const total = typeof doc.total === "number" && doc.total >= 0 ? doc.total : null; return { rows, total, more: total === null ? rows.length === params.page.size : params.page.start + rows.length < total, pageSize: doc.pageSize, pageStart: doc.pageStart }; } /** A bounded list read of a type. */ -export const list = (transport: Transport, type: string, params: ReadParams): Promise> => - read(transport, `/rest-1.v1/Data/${encodeURIComponent(type)}`, params, false); +export const list = (transport: Transport, type: string, params: ReadParams, context?: ReadContext): Promise> => + read(transport, `/rest-1.v1/Data/${encodeURIComponent(type)}`, params, false, context); /** One asset by OID. */ -export async function get(transport: Transport, oid: Oid, select?: string[]): Promise { +export async function get(transport: Transport, oid: Oid, select?: string[], context: ReadContext = {}): Promise { const [type, id] = momentless(oid).split(":"); const doc = await transport.request({ method: "GET", path: `/rest-1.v1/Data/${encodeURIComponent(type!)}/${encodeURIComponent(id!)}`, query: { sel: select?.join(",") }, responseType: "json" }); - return fromAssetDocument(doc, { select }); + return dated(fromAssetDocument(doc, { select }), context.lookup); } /** @@ -185,17 +210,17 @@ export type Template = Partial>; * else exposes. Idempotent, like any GET. Without a context the template * is empty, and an unknown context is echoed back, not refused. */ -export async function template(transport: Transport, type: string, options: { ctx?: Oid } = {}): Promise> { +export async function template(transport: Transport, type: string, options: { ctx?: Oid } & ReadContext = {}): Promise> { const doc = await transport.request({ method: "GET", path: `/rest-1.v1/New/${encodeURIComponent(type)}`, query: { ctx: options.ctx ? momentless(options.ctx) : undefined }, responseType: "json" }); - const { _oid: _ignored, ...values } = fromAssetDocument({ ...doc, id: doc.id || `${type}:0` }); + const { _oid: _ignored, ...values } = dated(fromAssetDocument({ ...doc, id: doc.id || `${type}:0` }), options.lookup); return values as Template; } /** A bounded history read: one row per moment, _oid carrying the moment. */ -export const history = (transport: Transport, target: string, params: ReadParams): Promise> => { +export const history = (transport: Transport, target: string, params: ReadParams, context?: ReadContext): Promise> => { const [type, id] = target.split(":"); const path = id ? `/rest-1.v1/Hist/${encodeURIComponent(type!)}/${encodeURIComponent(id)}` : `/rest-1.v1/Hist/${encodeURIComponent(type!)}`; - return read(transport, path, params, true); + return read(transport, path, params, true, context); }; // ---- rest-1 spellings of a query ----------------------------------------------- diff --git a/test/integration/client.test.ts b/test/integration/client.test.ts index ae81066..a23bdcf 100644 --- a/test/integration/client.test.ts +++ b/test/integration/client.test.ts @@ -45,16 +45,28 @@ describeInstance("client reads (live)", () => { const made = await client.send([{ AssetType: "Story", Name: fixtureName("rows rule"), Scope: { _oid: "Scope:0" }, Owners: [{ _oid: me._oid }] }], { throwOnFailure: true }); const story = made.created[0]!; try { - const select = ["Name", "Owners", "Owners.Name", "Scope.Name"]; - const keys = ["Name", "Owners", "Owners.Name", "Scope.Name", "_oid"]; + const select = ["Name", "Owners", "Owners.Name", "Scope.Name", "ChangeDateUTC", "CreateDate"]; + const keys = ["ChangeDateUTC", "CreateDate", "Name", "Owners", "Owners.Name", "Scope.Name", "_oid"]; const viaQuery = (await client.query({ from: "Story", select, filter: ["ID=$id"], with: { $id: story }, page: { size: 1, start: 0 } }))[0]! as Record; const viaPage = (await client.queryPage({ from: "Story", select, filter: ["ID=$id"], with: { $id: story }, page: { size: 1, start: 0 } })).rows[0]! as Record; - const viaRest = (await rest1.list(client.transport, "Story", { select, filter: [`ID='${story}'`], page: { size: 1, start: 0 } })).rows[0]! as unknown as Record; + const viaRest = (await rest1.list(client.transport, "Story", { select, filter: [`ID='${story}'`], page: { size: 1, start: 0 } }, { lookup: client.schema })).rows[0]! as unknown as Record; + // A day with no time of day (a sprint's begin date), which rest-1 writes as the date alone: the same value through each. + const sprint = { from: "Timebox", select: ["BeginDate"], sort: ["ID"], page: { size: 1, start: 0 } }; + const [byQuery] = await client.query<{ _oid: string; BeginDate: string }>(sprint); + if (byQuery) { + const byPage = (await client.queryPage<{ _oid: string; BeginDate: string }>(sprint)).rows[0]!; + const byRest = (await rest1.list<{ _oid: string; BeginDate: string }>(client.transport, "Timebox", { select: ["BeginDate"], sort: ["ID"], page: { size: 1, start: 0 } }, { lookup: client.schema })).rows[0]!; + expect(byQuery.BeginDate).toMatch(/^\d{4}-\d\d-\d\dT00:00:00\.0000000$/); + expect([byPage, byRest]).toEqual([byQuery, byQuery]); + } for (const row of [viaQuery, viaPage, viaRest]) { expect(Object.keys(row).sort()).toEqual(keys); expect(row["Owners.Name"]).toEqual([me.Name]); // a parallel array beside the Refs expect(typeof row["Scope.Name"]).toBe("string"); // its relation was not selected: the path is still there expect((row.Owners as { _oid: string }[]).map((o) => o._oid)).toEqual([me._oid]); + // The three endpoints write a date three ways (seven decimals, trailing zeros dropped, three decimals): the model has one. + expect(row.ChangeDateUTC).toMatch(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{7}Z$/); + expect(row.CreateDate).toMatch(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{7}$/); } // A Ref is bare on all three: the three rows are the same row. expect(viaPage).toEqual(viaQuery); diff --git a/test/integration/search.test.ts b/test/integration/search.test.ts index 4ba8bd1..f3c48a1 100644 --- a/test/integration/search.test.ts +++ b/test/integration/search.test.ts @@ -179,6 +179,18 @@ describeInstance("search (live)", () => { expect(await client.query({ from: "Workitem", select: ["AssetType"], filter: [`AssetType=${family.map((t) => `'${t}'`).join(",")}`], page: { size: 1, start: 0 } })).toHaveLength(1); }); + it("one list of columns serves any choice of types: a column none of the searched types has is null on every row, not an error (a CLI consumer's find with --type)", async () => { + const columns = ["Name", "Number", "Status.Name", "Owners.Name", "Owner.Name", "Scope.Name", "ChangeDateUTC"]; + // Only stories: a Story has no Owner. + const stories = await client.search(word, { types: ["Story"], select: columns, findin: ["Name", "Description"], page }); + expect(stories.rows).toEqual([{ _oid: story, Name: expect.stringContaining(word), Number: storyNumber, "Status.Name": null, "Owners.Name": [], "Owner.Name": null, "Scope.Name": expect.any(String), ChangeDateUTC: expect.stringMatching(/\.\d{7}Z$/) }]); + // Only issues: no Status, no Owners. + const issues = await client.search(word, { types: ["Issue"], select: columns, page }); + expect(issues.rows).toEqual([{ _oid: issue, Name: expect.stringContaining(word), Number: issueNumber, "Status.Name": null, "Owners.Name": null, "Owner.Name": null, "Scope.Name": expect.any(String), ChangeDateUTC: expect.stringMatching(/\.\d{7}Z$/) }]); + // Goals and topics have neither a Status nor an owner: the search is made (and finds none of the fixtures), where it used to be refused. + expect(await client.search(word, { types: ["Goal", "Topic"], select: columns, findin: ["Name", "Estimate"], page })).toEqual({ rows: [], total: 0, more: false }); + }); + it("client.search refuses, before any search is sent: no text, no types, the root type, an unknown type, a name no type defines", async () => { const refused = async (run: () => Promise, message: RegExp) => { const before = requests.filter((r) => r.path.startsWith("/rest-1.v1")).length; @@ -189,7 +201,8 @@ describeInstance("search (live)", () => { await refused(() => client.search(word, { types: [], page }), /needs `types`/); await refused(() => client.search(word, { types: ["BaseAsset"], page }), /abstract type/); await refused(() => client.search(word, { types: ["NoSuchType"], page }), /no asset type "NoSuchType"/); - await refused(() => client.search(word, { types: ["Story", "Issue"], select: ["Name", "Nmae"], page }), /"Nmae" is not an attribute of any type searched \(Story, Issue\)/); + await refused(() => client.search(word, { types: ["Story", "Issue"], select: ["Name", "Nmae"], page }), /"Nmae" is not an attribute of any asset type/); + await refused(() => client.search(word, { types: ["Goal", "Topic"], findin: ["Estimate"], page }), /nothing to search in/); }); it("client.deleted answers deleted assets only, each saying Deleted", async () => { diff --git a/test/unit/client.test.ts b/test/unit/client.test.ts index 285da46..0e63b24 100644 --- a/test/unit/client.test.ts +++ b/test/unit/client.test.ts @@ -142,11 +142,16 @@ describe("client: reads", () => { }); it("deleted takes a query's spelling (select, filter), sends rest-1's (sel, where), and asks for deleted assets only, with the total", async () => { - const t = fake(() => ({ _type: "Assets", pageSize: 2, pageStart: 0, Assets: [] })); - const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t }); - expect(await client.deleted("Story", { select: ["Name"], filter: ["Scope='Scope:0'"], page: { size: 2, start: 0 } })).toEqual({ rows: [], total: null, more: false }); + // rest-1 writes a date its own way (three decimals; a midnight as the date alone): the client answers the model's spelling. + const gone = { _type: "Asset", href: "", id: "Story:7", Attributes: { Name: { _type: "Attribute", name: "Name", value: "2011-09-20" }, ChangeDate: { _type: "Attribute", name: "ChangeDate", value: "2026-07-13T18:06:14.600" }, CreateDate: { _type: "Attribute", name: "CreateDate", value: "2011-09-20" } } }; + const t = fake(() => ({ _type: "Assets", pageSize: 2, pageStart: 0, Assets: [gone] })); + const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, types: schema().cache }); + expect(await client.deleted("Story", { select: ["Name", "ChangeDate", "CreateDate"], filter: ["Scope='Scope:0'"], page: { size: 2, start: 0 } })).toEqual({ + // The Name is text that happens to look like a date: it is left alone, because the schema says what is a date. + rows: [{ _oid: "Story:7", Name: "2011-09-20", ChangeDate: "2026-07-13T18:06:14.6000000", CreateDate: "2011-09-20T00:00:00.0000000" }], total: null, more: false + }); expect(t.calls).toHaveLength(1); - expect(t.calls[0]).toMatchObject({ method: "GET", path: "/rest-1.v1/Data/Story", query: expect.objectContaining({ sel: "Name", where: "Scope='Scope:0';IsDeleted='true'", page: "2,0", deleted: "true", needTotal: "true" }) }); + expect(t.calls[0]).toMatchObject({ method: "GET", path: "/rest-1.v1/Data/Story", query: expect.objectContaining({ sel: "Name,ChangeDate,CreateDate", where: "Scope='Scope:0';IsDeleted='true'", page: "2,0", deleted: "true", needTotal: "true" }) }); expect((client as unknown as { data?: unknown }).data).toBeUndefined(); }); }); diff --git a/test/unit/search.test.ts b/test/unit/search.test.ts index 5ad4e95..d9be7ac 100644 --- a/test/unit/search.test.ts +++ b/test/unit/search.test.ts @@ -5,6 +5,7 @@ import { UsageError } from "../../src/core/errors"; import type { RequestOptions, Transport } from "../../src/core/transport"; import { Schema } from "../../src/services/schema"; import { search } from "../../src/services/search"; +import { AgilityApiClient } from "../../src/client"; import { FakeAgilityClient } from "../../src/testing"; import { toMetamodel, type MetamodelDocument } from "../../src/wire/meta"; @@ -102,26 +103,66 @@ describe("search", () => { await refused(() => search(t, s, "x", { types: [], page }), /needs `types`/); await refused(() => search(t, s, "x", { types: ["BaseAsset"], page }), /"BaseAsset" is an abstract type whose concrete subtypes the SDK does not know/); await refused(() => search(t, s, "x", { types: ["Sotry"], page }), /no asset type "Sotry"/); - await refused(() => search(t, s, "x", { types: ["Story", "Issue"], select: ["Nmae"], page }), /select "Nmae" is not an attribute of any type searched \(Story, Issue\)/); - await refused(() => search(t, s, "x", { types: ["Story", "Issue"], findin: ["Nmae"], page }), /findin "Nmae"/); - await refused(() => search(t, s, "x", { types: ["Issue"], select: ["Estimate"], page }), /"Estimate" is not an attribute of Issue/); + await refused(() => search(t, s, "x", { types: ["Story", "Issue"], select: ["Nmae"], page }), /select "Nmae" is not an attribute of any asset type \(searched: Story, Issue\)/); + await refused(() => search(t, s, "x", { types: ["Story"], findin: ["Nmae"], page }), /findin "Nmae" is not an attribute of any asset type/); + await refused(() => search(t, s, "x", { types: ["Goal", "Topic"], findin: ["Estimate", "Owners"], page }), /none of the types searched \(Goal, Topic\) has any of the attributes in `findin` \(Estimate, Owners\): there is nothing to search in/); expect(t.calls).toEqual([]); }); + + it("a name none of the searched types has is not a mistake: it is left out of the request and every row has null there, so one list of columns serves any choice of types", async () => { + const columns = ["Name", "Number", "Status.Name", "Owners.Name", "Owner.Name", "Estimate", "Custom_Risk"]; + // One type, which has no Owner and no custom field of that name. + const story = recording({ ...live, Assets: [live.Assets[1]] }); + const one = await search(story, schema(), "printer", { types: ["Story"], select: columns, page }); + expect(story.calls[0]).toMatchObject({ path: "/rest-1.v1/Data/Story", query: { sel: "Name,Number,Status.Name,Owners.Name,Estimate" } }); + expect(one.rows).toEqual([{ _oid: "Story:1", Name: "Printer setup", Number: "S-01001", "Status.Name": null, "Owners.Name": ["Ann", "Bo"], "Owner.Name": null, Estimate: 2, Custom_Risk: null }]); + // Two types with neither a Status nor an owner nor an Estimate: only what they have is asked for; a findin none has is dropped. + const few = recording({ ...live, Assets: [] }); + await search(few, schema(), "printer", { types: ["Goal", "Topic"], select: columns, findin: ["Name", "Estimate"], page }); + expect(few.calls[0]!.query).toMatchObject({ sel: "Name,Goal.Number,Topic.Number", findin: "Name" }); + // Nothing selected applies at all: the search still asks for something of its own, and the rows have the keys. + const none = recording({ ...live, Assets: [{ _type: "Asset", href: "", id: "Goal:4", Attributes: { Name: attribute("Name", "Printing goal") } }] }); + expect((await search(none, schema(), "printer", { types: ["Goal", "Topic"], select: ["Estimate", "Owners"], findin: ["Name"], page })).rows).toEqual([{ _oid: "Goal:4", Estimate: null, Owners: null }]); + expect(none.calls[0]!.query).toMatchObject({ sel: "Name" }); + }); + + it("a date is in the model's one spelling, by the row's own type; text that looks like a date is left alone", async () => { + const dated = recording({ ...live, Assets: [{ _type: "Asset", href: "", id: "Story:1", Attributes: { Name: attribute("Name", "2011-09-20"), ChangeDateUTC: attribute("ChangeDateUTC", "2026-07-13T22:06:14.600Z"), CreateDate: attribute("CreateDate", "2011-09-20") } }] }); + expect((await search(dated, schema(), "printer", { types: ["Story", "Issue"], select: ["Name", "ChangeDateUTC", "CreateDate"], page })).rows).toEqual([{ _oid: "Story:1", Name: "2011-09-20", ChangeDateUTC: "2026-07-13T22:06:14.6000000Z", CreateDate: "2011-09-20T00:00:00.0000000" }]); + }); }); describe("FakeAgilityClient: search", () => { - it("onSearch answers client.search with scripted rows, paged, with the total, each cut to the selected keys; what was searched is recorded and nothing is requested", async () => { - const fake = new FakeAgilityClient().onSearch([ - { _oid: "Story:1", Name: "Printer setup", Number: "S-1", AssetType: "Story", AssetState: "Active", Estimate: 2 }, - { _oid: "Request:2", Name: "Printer request", Number: "R-2", AssetType: "Request", AssetState: "Active" }, - { _oid: "Issue:3", Name: "Printer blocker", Number: "I-3", AssetType: "Issue", AssetState: "Active" } - ]); - const first = await fake.search("printer", { types: ["Story", "Request", "Issue"], select: ["Name", "Number", "Estimate"], page: { size: 2, start: 0 } }); - expect(first).toEqual({ total: 3, more: true, rows: [{ _oid: "Story:1", Name: "Printer setup", Number: "S-1", Estimate: 2 }, { _oid: "Request:2", Name: "Printer request", Number: "R-2", Estimate: null }] }); + const scripted = [ + { _oid: "Story:1", Name: "Printer setup", Number: "S-1", AssetType: "Story", AssetState: "Active", Estimate: 2, Scope: { _oid: "Scope:0", Name: "System" } }, + { _oid: "Request:2", Name: "Printer request", Number: "R-2", AssetType: "Request", AssetState: "Active" }, + { _oid: "Issue:3", Name: "Printer blocker", Number: "I-3", AssetType: "Issue", AssetState: "Active" } + ]; + + it("onSearch answers client.search with scripted rows, paged, with the total, each with exactly the selected keys; what was searched is recorded", async () => { + const fake = new FakeAgilityClient().onSearch(scripted); + const first = await fake.search("printer", { types: ["Story", "Request", "Issue"], select: ["Name", "Number", "Estimate", "Scope", "Scope.Name"], page: { size: 2, start: 0 } }); + expect(first).toEqual({ total: 3, more: true, rows: [ + { _oid: "Story:1", Name: "Printer setup", Number: "S-1", Estimate: 2, Scope: { _oid: "Scope:0" }, "Scope.Name": "System" }, + { _oid: "Request:2", Name: "Printer request", Number: "R-2", Estimate: null, Scope: null, "Scope.Name": null } + ] }); const rest = await fake.search("printer", { types: ["Story", "Request", "Issue"], page: { size: 2, start: 2 } }); expect(rest).toEqual({ total: 3, more: false, rows: [{ _oid: "Issue:3", Name: "Printer blocker", Number: "I-3", AssetType: "Issue", AssetState: "Active" }] }); - expect(fake.searched.map((s) => [s.text, s.options.page.start])).toEqual([["printer", 0], ["printer", 2]]); - expect(fake.requests).toEqual([]); + expect(fake.searched.map((s) => [s.text, s.options.types, s.options.page.start])).toEqual([["printer", ["Story", "Request", "Issue"], 0], ["printer", ["Story", "Request", "Issue"], 2]]); + }); + + it("a client the code under test builds on fake.transport gets the same answer: the search is the client's own, and the fake's instance has the types it names (a chat-bot consumer's pattern)", async () => { + const fake = new FakeAgilityClient().onSearch(scripted); + const own = new AgilityApiClient({ baseUrl: "https://agility.example.com/Fake", retries: 0 }, { transport: fake.transport }); + const found = await own.search("printer queue", { types: ["Story", "Request", "Issue", "Test"], findin: ["Name", "Description"], filter: ["AssetState!='Closed'"], sort: ["-ChangeDateUTC"], page: { size: 2, start: 0 } }); + expect(found).toEqual({ total: 3, more: true, rows: [ + { _oid: "Story:1", Name: "Printer setup", Number: "S-1", AssetType: "Story", AssetState: "Active" }, + { _oid: "Request:2", Name: "Printer request", Number: "R-2", AssetType: "Request", AssetState: "Active" } + ] }); + expect(fake.searched).toEqual([{ text: "printer queue", options: { types: ["Story", "Request", "Issue", "Test"], page: { size: 2, start: 0 } } }]); + // What the code under test typed travels as the search text and nowhere else. + expect(fake.requests).toHaveLength(1); + expect(fake.requests[0]!.query).toMatchObject({ find: "printer queue", where: "AssetType='Story','Request','Issue','Test';AssetState!='Closed'" }); }); it("an unscripted search throws, and so do the mistakes the client refuses; a function answers a page, an Error is thrown", async () => { diff --git a/test/unit/translate.test.ts b/test/unit/translate.test.ts index fa16591..cfdbee0 100644 --- a/test/unit/translate.test.ts +++ b/test/unit/translate.test.ts @@ -52,7 +52,7 @@ describe("translate: a row into the model, by schema", () => { expect((fromWireRow({ _oid: "Story:1", Owners: [{ _oid: "NULL" }, { _oid: "Member:20" }] }, { lookup: schema, type: "Story" }) as unknown as Record).Owners).toEqual([{ _oid: "Member:20" }]); }); - it("numbers become numbers, booleans booleans, a sub-selected single relation one Ref, a bare one stays a Ref, aggregates numbers, dates and states as sent", () => { + it("numbers become numbers, booleans booleans, a sub-selected single relation one Ref, a bare one stays a Ref, aggregates numbers, a date in the model's one spelling, states as sent", () => { const row = fromWireRow(liveRow, { lookup: schema, type: "Story" }); expect(row._oid).toBe("Story:1226"); expect(row.Name).toBe("Ship Order"); @@ -61,7 +61,7 @@ describe("translate: a row into the model, by schema", () => { expect(row.IsDeleted).toBe(false); expect(row.IsClosed).toBe(true); expect(row.AssetState).toBe("Closed"); - expect(row.CreateDate).toBe("2026-06-27T12:28:29.137"); + expect(row.CreateDate).toBe("2026-06-27T12:28:29.1370000"); // sent as "…29.137" by api/asset; every read spells seven decimals expect(row.Order).toBe(-1989738965); // Rank: a 32-bit integer sent as a string, a number in the model expect(row.Status).toEqual({ _oid: "StoryStatus:2191", Name: "Accepted", Order: 3 }); // [x] -> x; the nested row is translated by StoryStatus (Order is Rank there too) expect(row.Super).toEqual({ _oid: "Epic:1185", Name: "Order Entry" }); From e270b591165dc65302688a0e2f05d612f3fa86e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 15:01:40 +0000 Subject: [PATCH 07/11] Subpath types resolve under moduleResolution node10 (typesVersions) TypeScript's node10 resolution ignores exports, so /wire, /services and /testing had runtime entries and no types there. Checked by compiling a consumer file against the packed package under node10, bundler and node16. Also a doc line on what fake.searched records. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 5 +++++ package.json | 7 +++++++ src/testing/index.ts | 3 ++- 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ff57209..a1a2634 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -70,6 +70,11 @@ - `FakeAgilityClient.onSearch(rows)` and `fake.searched`, to test code that searches, through the fake or through a client built on `fake.transport`. +- The subpaths' types resolve under TypeScript's `moduleResolution: + "node"` (node10), which ignores `exports`: `package.json` has a + `typesVersions` entry for `/wire`, `/services` and `/testing`. A + consumer's ambient `declare module` bridge for them can go. + (a browser-app consumer.) - `@versionone/agility-sdk/services` has `search`. The root exports the types `SearchOptions`, `SearchResult`, `SearchRow`. diff --git a/package.json b/package.json index 7dcc844..9935b5f 100644 --- a/package.json +++ b/package.json @@ -59,6 +59,13 @@ }, "./package.json": "./package.json" }, + "typesVersions": { + "*": { + "wire": ["dist/wire.d.ts"], + "services": ["dist/services.d.ts"], + "testing": ["dist/testing.d.ts"] + } + }, "files": [ "dist", "CHANGELOG.md" diff --git a/src/testing/index.ts b/src/testing/index.ts index 94ceb34..25ca77c 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -405,7 +405,8 @@ export class FakeAgilityClient extends AgilityApiClient { /** * Every search made, in order: its text and options. A search made by a * client of your own over `fake.transport` is recorded too, with the - * options the request shows: `types` and `page`. + * options the request shows: `types` and `page`. For what else such a + * client asked (its filter, its sort), read the request in `requests`. */ readonly searched: { text: string; options: SearchOptions }[]; private readonly script: Script; From 9c5b6ab3e6046a5f6f8dabfb9bfa8712a58d7537 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 15:04:04 +0000 Subject: [PATCH 08/11] A test that the types resolve under node10, node16 and bundler; toDate The packaging test installs the built package in a temp directory and compiles a consumer of all four import paths under each resolution (it fails under node10 without typesVersions). toDate reads a DateString without relying on a parser's tolerance for seven decimals, which the standard does not promise; the README no longer says new Date does. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 7 ++-- README.md | 2 +- src/index.ts | 2 +- src/types/asset.ts | 15 ++++++++ test/unit/translate.test.ts | 16 +++++++++ test/unit/typesResolution.test.ts | 57 +++++++++++++++++++++++++++++++ 6 files changed, 95 insertions(+), 4 deletions(-) create mode 100644 test/unit/typesResolution.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index a1a2634..cc37639 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,8 +37,8 @@ as the date alone (`"2011-09-20"`). Nothing is cut: seven decimals is the server's precision. Migration: code that compares date strings from `queryPage`, `history` or `template` against stored ones, or slices - them by position, should parse them (`new Date(value)`) or expect the - one spelling. `rest1.list` / `get` / `history` / `template` from + them by position, should parse them (`toDate(value)`), take the day + with `value.slice(0, 10)`, or expect the one spelling. `rest1.list` / `get` / `history` / `template` from `/wire` spell dates this way when given `{ lookup: client.schema }`, and as rest-1 sent them without. (a CLI consumer.) - **A read with an empty `find` throws a `UsageError`** (`kind: "usage"`, @@ -70,6 +70,9 @@ - `FakeAgilityClient.onSearch(rows)` and `fake.searched`, to test code that searches, through the fake or through a client built on `fake.transport`. +- `toDate(value)` on the root: a `DateString` as a `Date`. The model's + seven decimals are more than the standard promises `new Date` will + parse, so parse with this. (a browser-app consumer.) - The subpaths' types resolve under TypeScript's `moduleResolution: "node"` (node10), which ignores `exports`: `package.json` has a `typesVersions` entry for `/wire`, `/services` and `/testing`. A diff --git a/README.md b/README.md index 04f6daf..da128d1 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ const { rows, total, more } = await client.search("warehouse ship*", { - The first search loads the schema of each type searched (one request per type, then cached for the client, or shared through a `TypeCache`). A short-lived process that searches once pays that every time: seed the cache (`TypeCache.fromMetamodel`) or keep the client. - To find one asset by its exact number, do not search: `client.resolve.numbers(["S-01042"])` is exact and does not wait for the text index. -A date is spelled one way on every read: `"2026-09-06T13:52:51.9030000"`, seven decimals, with a `Z` on a UTC attribute (`ChangeDateUTC`). The endpoints each write dates differently, and the SDK answers this one spelling whichever of them was asked; `new Date(value)` reads it. +A date is spelled one way on every read: `"2026-09-06T13:52:51.9030000"`, seven decimals, with a `Z` on a UTC attribute (`ChangeDateUTC`). The endpoints each write dates differently, and the SDK answers this one spelling whichever of them was asked. To get a `Date`, use `toDate(value)` from the root rather than `new Date(value)`: the standard promises a parser three decimals, not seven. A value without a `Z` is the server's wall-clock time with no zone; for a day (a sprint's `BeginDate`) take `value.slice(0, 10)`. 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`. diff --git a/src/index.ts b/src/index.ts index 5de2f39..2bac67a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,7 +10,7 @@ export type { RequestBody, RequestOptions, ResponseType, Transport } from "./cor // The model: what things are. export type { Asset, AttributeValue, CustomAttributes, DateString, Oid, Ref, AssetStateValue } from "./types/asset"; -export { ASSET_STATE_CODES, assetStateKind, assetStateOf } from "./types/asset"; +export { ASSET_STATE_CODES, assetStateKind, toDate, assetStateOf } from "./types/asset"; export { isOidToken, momentless, parseOid, toOid, typeOfOid } from "./types/oid"; export type { OidParts } from "./types/oid"; export type { AssetType, AttributeDefinition, AttributeLookup, AttributeType, AttributeTokenRef, AssetTypeToken, Metamodel } from "./types/metamodel"; diff --git a/src/types/asset.ts b/src/types/asset.ts index 9f1c0bd..4fee1b2 100644 --- a/src/types/asset.ts +++ b/src/types/asset.ts @@ -22,6 +22,21 @@ export type DateString = string; const DATE = /^(\d{4}-\d\d-\d\d)(?:T(\d\d:\d\d:\d\d)(?:\.(\d{1,7}))?)?(Z)?$/; +/** + * A DateString as a `Date`, or null when the value is null or no date. + * Use this rather than `new Date(value)`: the standard promises a parser + * only three decimals of a second, and what an engine does with seven is + * its own business. A UTC attribute's value (it ends in `Z`) is that + * instant; any other is the server's wall-clock time with no zone, read + * here, as the standard reads a date-time without one, as local time. + */ +export function toDate(value: DateString | null | undefined): Date | null { + const m = typeof value === "string" ? DATE.exec(value) : null; + if (!m) return null; + const date = new Date(`${m[1]}T${m[2] ?? "00:00:00"}.${(m[3] ?? "").padEnd(3, "0").slice(0, 3)}${m[4] ?? ""}`); + return Number.isNaN(date.getTime()) ? null : date; +} + /** A date as any endpoint spells it, in the model's one spelling (see DateString). Anything else is answered as given. */ export function dateString(value: T): T | DateString { const m = typeof value === "string" ? DATE.exec(value) : null; diff --git a/test/unit/translate.test.ts b/test/unit/translate.test.ts index cfdbee0..78d61fb 100644 --- a/test/unit/translate.test.ts +++ b/test/unit/translate.test.ts @@ -4,6 +4,7 @@ import { join } from "node:path"; import { AgilityApiClient } from "../../src/client"; import type { RequestOptions, Transport } from "../../src/core/transport"; import { Schema, TypeCache } from "../../src/services/schema"; +import { dateString, toDate } from "../../src/types/asset"; import type { Story } from "../../src/types/assets/Story"; import { fromWireRow, send, type AssetApiResponse } from "../../src/wire/assetApi"; import { toMetamodel, type MetamodelDocument } from "../../src/wire/meta"; @@ -140,4 +141,19 @@ describe("translate: through send and the client", () => { const { rows: [again] } = await seeded.queryPage({ from: "Story", select: ["Estimate"], page: { size: 1, start: 0 } }); expect(again!.IsClosed).toBe(true); }); + + it("dateString is the model's one spelling of what each endpoint writes; toDate reads it without relying on a parser's tolerance for seven decimals", () => { + // query.v1, api/asset, rest-1, and rest-1's midnight: one value each way. + for (const sent of ["2026-07-13T22:06:14.6000000Z", "2026-07-13T22:06:14.6Z", "2026-07-13T22:06:14.600Z"]) expect(dateString(sent)).toBe("2026-07-13T22:06:14.6000000Z"); + expect(dateString("2011-09-20T00:00:00")).toBe("2011-09-20T00:00:00.0000000"); + expect(dateString("2011-09-20")).toBe("2011-09-20T00:00:00.0000000"); + // Not a date: answered as given. + expect([dateString("soon"), dateString(null), dateString(7), dateString("2011-09-20 or so")]).toEqual(["soon", null, 7, "2011-09-20 or so"]); + // A UTC value is that instant; nothing beyond the millisecond is given to the parser. + expect(toDate("2026-07-13T22:06:14.6001234Z")?.toISOString()).toBe("2026-07-13T22:06:14.600Z"); + // No zone: local wall-clock time, as the standard reads it. + const local = toDate("2011-09-20T08:30:00.0000000")!; + expect([local.getFullYear(), local.getMonth(), local.getDate(), local.getHours(), local.getMinutes()]).toEqual([2011, 8, 20, 8, 30]); + expect([toDate(null), toDate(undefined), toDate("soon"), toDate("2011-13-45T00:00:00.0000000")]).toEqual([null, null, null, null]); + }); }); diff --git a/test/unit/typesResolution.test.ts b/test/unit/typesResolution.test.ts new file mode 100644 index 0000000..db671b3 --- /dev/null +++ b/test/unit/typesResolution.test.ts @@ -0,0 +1,57 @@ +import { cpSync, existsSync, copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import ts from "typescript"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +/** + * A TypeScript consumer finds the types of all four import paths, whatever + * its `moduleResolution`. The older "node" (node10) resolution ignores the + * package's `exports` map, so the subpaths resolve there only through + * `typesVersions`: without it, `@versionone/agility-sdk/testing` runs (the + * bundlers and test runners read `exports`) and does not compile. + * + * Installs the built package (dist/ and the real package.json) under + * node_modules in a temp directory and compiles a consumer file against it. + * It needs the declarations in dist/, which `npm run verify` builds before + * the tests; without them it says so and skips. + */ +const root = join(__dirname, "..", ".."); +const built = ["index", "wire", "services", "testing"].every((entry) => existsSync(join(root, "dist", `${entry}.d.ts`)) && existsSync(join(root, "dist", `${entry}.d.cts`))); +let dir = ""; + +beforeAll(() => { + if (!built) return; + dir = mkdtempSync(join(tmpdir(), "sdk-types-")); + const installed = join(dir, "node_modules", "@versionone", "agility-sdk"); + mkdirSync(installed, { recursive: true }); + cpSync(join(root, "dist"), join(installed, "dist"), { recursive: true }); + copyFileSync(join(root, "package.json"), join(installed, "package.json")); + writeFileSync(join(dir, "consumer.ts"), [ + `import { AgilityApiClient, type Outcome } from "@versionone/agility-sdk";`, + `import { rest1 } from "@versionone/agility-sdk/wire";`, + `import { search } from "@versionone/agility-sdk/services";`, + `import { FakeAgilityClient, transportConformance } from "@versionone/agility-sdk/testing";`, + `export const fake: AgilityApiClient = new FakeAgilityClient();`, + `export const used = [rest1.list, search.search, transportConformance];`, + `export type O = Outcome;`, + `` + ].join("\n")); +}); +afterAll(() => { if (dir) rmSync(dir, { recursive: true, force: true }); }); + +const RESOLUTIONS: [string, ts.CompilerOptions][] = [ + ["node (node10)", { module: ts.ModuleKind.CommonJS, moduleResolution: ts.ModuleResolutionKind.Node10 }], + ["node16", { module: ts.ModuleKind.Node16, moduleResolution: ts.ModuleResolutionKind.Node16 }], + ["bundler", { module: ts.ModuleKind.ESNext, moduleResolution: ts.ModuleResolutionKind.Bundler }] +]; + +describe("the package's types, as a consumer's compiler resolves them", () => { + for (const [name, options] of RESOLUTIONS) { + it.skipIf(!built)(`all four import paths compile under moduleResolution ${name}${built ? "" : " [skipped: run `npm run build` first]"}`, () => { + const program = ts.createProgram([join(dir, "consumer.ts")], { ...options, target: ts.ScriptTarget.ES2022, strict: true, noEmit: true, skipLibCheck: true, types: [] }); + const problems = ts.getPreEmitDiagnostics(program).map((d) => ts.flattenDiagnosticMessageText(d.messageText, "\n")); + expect(problems).toEqual([]); + }, 60_000); + } +}); From 13da3b63bb756c1e0e8c140993711308e30b705b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 15:05:56 +0000 Subject: [PATCH 09/11] The fake resolves a number of any scripted type; doc lines on search filters and the fake's metamodel A number lookup on the fake went to real per-root queries as soon as one number root (a Request) had scripted rows, and threw on the first root without a script. It now answers from the scripted rows whichever types have them. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- README.md | 2 +- src/services/search.ts | 3 +++ src/testing/index.ts | 17 +++++++++++++---- test/unit/testing.test.ts | 3 +++ 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index da128d1..e82cba8 100644 --- a/README.md +++ b/README.md @@ -115,7 +115,7 @@ const { rows, total, more } = await client.search("warehouse ship*", { - **You name an attribute once, plainly, and each row has that key**: its value if the row's type defines it, `null` if not (`Owners` is null on a Request, `Owner` null on a Story; the SDK does not merge differently named attributes). That holds when none of the searched types has it too: every row has `null`, so one list of columns serves whatever types a user picks. Only a name that is no attribute of any asset type is a usage error (a misspelling). A `findin` name none of the searched types has is left out; if none is left, the search is refused. - `select` defaults to `Name`, `Number`, `AssetType`, `AssetState`; `findin` defaults to `Name` and `Number`. - A relation is a bare `{ _oid }`; ask for a display value as a path (`"Scope.Name"`, `"Owners.Name"`). -- **Selects are plain; filters are sent as written and may be type-qualified.** A select names a value, and the SDK can ask each type for it. A filter is an expression: a condition across types, such as "owned by me" when work items have `Owners` and requests have `Owner`, has no plain spelling, so you write it: `"(Workitem.Owners.IsSelf='true'|Request.Owner.IsSelf='true')"`. A term on an attribute every searched type shares (`AssetState`, `Scope.Name`) needs no qualifying. `sort` is sent as written too. +- **Selects are plain; filters are sent as written and may be type-qualified.** A select names a value, and the SDK can ask each type for it. A filter is an expression: a condition across types, such as "owned by me" when work items have `Owners` and requests have `Owner`, has no plain spelling, so you write it: `"(Workitem.Owners.IsSelf='true'|Request.Owner.IsSelf='true')"`. A term on an attribute every searched type shares (`AssetState`, `Scope.Name`) needs no qualifying. Qualify a term on any other attribute whatever `types` is: unqualified, it happens to be accepted when one type is searched and is refused when several are. `sort` is sent as written too. - Deleted assets are never found; `client.deleted(type, params)` reads those. - The first search loads the schema of each type searched (one request per type, then cached for the client, or shared through a `TypeCache`). A short-lived process that searches once pays that every time: seed the cache (`TypeCache.fromMetamodel`) or keep the client. - To find one asset by its exact number, do not search: `client.resolve.numbers(["S-01042"])` is exact and does not wait for the text index. diff --git a/src/services/search.ts b/src/services/search.ts index 8ffea4f..1323081 100644 --- a/src/services/search.ts +++ b/src/services/search.ts @@ -57,6 +57,9 @@ export interface SearchOptions { * expression, and a condition across types has no plain spelling: a term * on an attribute only some types have is type-qualified by the caller * (`"(Workitem.Owners.IsSelf='true'|Request.Owner.IsSelf='true')"`). + * Qualify such a term whatever `types` is: an unqualified + * `"Owners.Name='x'"` happens to be accepted when one type is searched + * and is refused when several are. */ filter?: readonly string[]; /** Equality terms: attribute → value, the value carried as a variable. */ diff --git a/src/testing/index.ts b/src/testing/index.ts index 25ca77c..764eede 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -273,13 +273,19 @@ function respond(script: Script, request: RequestOptions): unknown { }; const asked = bodies.filter(({ body }) => isQuery(body)).map(({ body }) => body as QueryBody); let answers: { rows: Asset[]; total: number | null }[]; - if (asked.length && asked.every(isNumberLookup) && !asked.some((q) => hitFor(script, q, q.from))) { + if (asked.length && asked.every(isNumberLookup)) { // resolve.numbers asks every number root at once; which roots is the SDK's business, so the fake answers - // from every row a test scripted, by Number, whatever its type. A number no row has is simply not found. + // from every row a test scripted as a list, by Number, whatever its type and whichever types have rows. + // A number no row has is simply not found. A root a test scripted a function or an Error for answers that. + const own = (q: QueryBody) => { const hit = hitFor(script, q, q.from); return typeof hit?.answer === "function" || hit?.answer instanceof Error; }; const wanted = new Set((asked[0]!.with!.$numbers as string[]).map((n) => n.toUpperCase())); const found = scriptedRows(script).filter((row) => typeof row.Number === "string" && wanted.has(row.Number.toUpperCase())); - script.seen.asked.push(...asked); - answers = asked.map((_, i) => ({ rows: i === 0 ? found : [], total: i === 0 ? found.length : 0 })); + const first = asked.findIndex((q) => !own(q)); + answers = asked.map((q, i) => { + if (own(q)) return answerQuery(script, q); + script.seen.asked.push(q); + return { rows: i === first ? found : [], total: i === first ? found.length : 0 }; + }); } else answers = asked.map((q) => answerQuery(script, q, q.from.startsWith("@") ? createdBy(q.from) : undefined)); const tokens = (oidTokens: Oid[]) => ({ oidTokens, count: oidTokens.length }); return { @@ -470,6 +476,9 @@ export class FakeAgilityClient extends AgilityApiClient { * none, and it works the same for a client your code builds on * `fake.transport`. Without a `metamodel` the fake's instance has any * type a search names; script the search before the first one is made. + * With a `metamodel` it has that metamodel's types only, as a server + * has its own: a search naming a type the document leaves out is + * refused, so give a search test the whole document or none. */ onSearch(answer: SearchAnswer): this { this.script.searches.push(answer); diff --git a/test/unit/testing.test.ts b/test/unit/testing.test.ts index 08cbefe..245491f 100644 --- a/test/unit/testing.test.ts +++ b/test/unit/testing.test.ts @@ -120,6 +120,9 @@ describe("FakeAgilityClient", () => { missing: ["S-99999"] }); expect(await fake.resolve.ref("S-01001")).toMatchObject({ _oid: "Story:1" }); + // A number of a type that is itself a number root (a Request), scripted like any other: found, and no other root needs a script (a CLI consumer's test). + fake.onQuery("Request", [{ _oid: "Request:3", Number: "R-3", Name: "Faster export", AssetState: "Active" }]); + expect(await fake.resolve.numbers(["R-3", "S-01001"])).toMatchObject({ found: [{ _oid: "Request:3", AssetType: "Request", Number: "R-3" }, { _oid: "Story:1" }], missing: [] }); expect(await new FakeAgilityClient().resolve.ref("S-1")).toBeNull(); }); From c7c619df759a37cac2bc2847234c15e3937d7c65 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 15:12:38 +0000 Subject: [PATCH 10/11] Dates are spelled with three decimals on every read; toDate removed The standard's date-time format, which any engine's Date parses, where the model spelled seven decimals. This changes the default read path too (client.query and get answered seven). The SDK cuts to the millisecond by design: the server stores about three milliseconds, and in a live sample of 400 timestamps every digit past the third was zero. toDate goes: with three decimals it is new Date. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 36 ++++++++++++++++------------- README.md | 2 +- specs/000-layers.md | 9 +++++--- src/index.ts | 2 +- src/types/asset.ts | 40 ++++++++++++++------------------- test/integration/client.test.ts | 9 ++++---- test/integration/search.test.ts | 4 ++-- test/unit/client.test.ts | 2 +- test/unit/search.test.ts | 2 +- test/unit/translate.test.ts | 26 ++++++++++----------- 10 files changed, 67 insertions(+), 65 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc37639..1a1091e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,19 +28,26 @@ code for a name read off a relation. A read with no select at all (a template) keeps every column the server sent, each under its own key (`template["Scope.Name"]`), and its Refs are bare too. (a CLI consumer.) -- **A date has one spelling on every read**: `"2026-09-06T13:52:51.9030000"` - (seven decimals; a `Z` on a UTC attribute). The endpoints differ, and - rows used to carry whichever spelling the endpoint behind the call - used: `query` / `get` answered seven decimals (unchanged), `queryPage` - answered `"…51.903"` with trailing zeros dropped, and `history`, - `template` and the rest-1 reads answered three decimals and a midnight - as the date alone (`"2011-09-20"`). Nothing is cut: seven decimals is - the server's precision. Migration: code that compares date strings from - `queryPage`, `history` or `template` against stored ones, or slices - them by position, should parse them (`toDate(value)`), take the day - with `value.slice(0, 10)`, or expect the one spelling. `rest1.list` / `get` / `history` / `template` from - `/wire` spell dates this way when given `{ lookup: client.schema }`, - and as rest-1 sent them without. (a CLI consumer.) +- **A date has one spelling on every read**: `"2026-09-06T13:52:51.903"`, + three decimals, with a `Z` on a UTC attribute: the standard's date-time + format, which `new Date(value)` reads in any engine. The endpoints + differ, and rows used to carry whichever spelling the endpoint behind + the call used: `query` and `get` answered seven decimals + (`"…51.9030000"`), `queryPage` dropped trailing zeros (`"…51.903"`, + `"…14.6"`), and `history`, `template` and the rest-1 reads answered + three decimals and a midnight as the date alone (`"2011-09-20"`). So + this changes the default read path too. The SDK cuts to the + millisecond, by design: the server's stored resolution is about three + milliseconds (in a live sample of 400 timestamps, every digit past the + third was zero and the third was only ever 0, 3 or 7), so nothing + observed is lost; if an instance ever carries finer digits they are + dropped. Migration: code that compares date strings against stored + ones, or slices them by position, should parse them (`new Date(value)`, + now portable), take the day with `value.slice(0, 10)`, or expect the + one spelling; a consumer's own normalising of fractions can go. + `rest1.list` / `get` / `history` / `template` from `/wire` spell dates + this way when given `{ lookup: client.schema }`, and as rest-1 sent + them without. (a CLI consumer and a browser-app consumer.) - **A read with an empty `find` throws a `UsageError`** (`kind: "usage"`, nothing is sent), on `query`, `queries`, `queryPage`, `pages`, `all` and `deleted`. It used to answer no rows, because that is what the server @@ -70,9 +77,6 @@ - `FakeAgilityClient.onSearch(rows)` and `fake.searched`, to test code that searches, through the fake or through a client built on `fake.transport`. -- `toDate(value)` on the root: a `DateString` as a `Date`. The model's - seven decimals are more than the standard promises `new Date` will - parse, so parse with this. (a browser-app consumer.) - The subpaths' types resolve under TypeScript's `moduleResolution: "node"` (node10), which ignores `exports`: `package.json` has a `typesVersions` entry for `/wire`, `/services` and `/testing`. A diff --git a/README.md b/README.md index e82cba8..30a81f4 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ const { rows, total, more } = await client.search("warehouse ship*", { - The first search loads the schema of each type searched (one request per type, then cached for the client, or shared through a `TypeCache`). A short-lived process that searches once pays that every time: seed the cache (`TypeCache.fromMetamodel`) or keep the client. - To find one asset by its exact number, do not search: `client.resolve.numbers(["S-01042"])` is exact and does not wait for the text index. -A date is spelled one way on every read: `"2026-09-06T13:52:51.9030000"`, seven decimals, with a `Z` on a UTC attribute (`ChangeDateUTC`). The endpoints each write dates differently, and the SDK answers this one spelling whichever of them was asked. To get a `Date`, use `toDate(value)` from the root rather than `new Date(value)`: the standard promises a parser three decimals, not seven. A value without a `Z` is the server's wall-clock time with no zone; for a day (a sprint's `BeginDate`) take `value.slice(0, 10)`. +A date is spelled one way on every read: `"2026-09-06T13:52:51.903"`, three decimals, with a `Z` on a UTC attribute (`ChangeDateUTC`). That is the standard's date-time format, so `new Date(value)` reads it in any engine. The endpoints each write dates differently, and the SDK answers this one spelling whichever of them was asked; it cuts to the millisecond, which is finer than the server stores. A value without a `Z` is the server's wall-clock time with no zone; for a day (a sprint's `BeginDate`) take `value.slice(0, 10)`. 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`. diff --git a/specs/000-layers.md b/specs/000-layers.md index e611c29..21ce003 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -49,9 +49,12 @@ that endpoint's wire module, once, on the way in and on the way out. A date is one of those spellings. query.v1 writes seven decimals, api/asset drops trailing zeros, rest-1 writes three and a midnight as the -date alone; the model's `DateString` is `2026-09-06T13:52:51.9030000` -(with `Z` on a UTC attribute), and every read answers it. The schema says -which attribute is a date: text that looks like one is never touched. +date alone; the model's `DateString` is `2026-09-06T13:52:51.903` (with +`Z` on a UTC attribute), the standard's date-time format, and every read +answers it. That cuts to the millisecond, by design: finer than the +server stores (about three milliseconds), so nothing observed is lost. +The schema says which attribute is a date: text that looks like one is +never touched. A row's identity is `_oid`: the key the server sends for it, underscored so that it can never collide with an attribute (an asset's own identity diff --git a/src/index.ts b/src/index.ts index 2bac67a..5de2f39 100644 --- a/src/index.ts +++ b/src/index.ts @@ -10,7 +10,7 @@ export type { RequestBody, RequestOptions, ResponseType, Transport } from "./cor // The model: what things are. export type { Asset, AttributeValue, CustomAttributes, DateString, Oid, Ref, AssetStateValue } from "./types/asset"; -export { ASSET_STATE_CODES, assetStateKind, toDate, assetStateOf } from "./types/asset"; +export { ASSET_STATE_CODES, assetStateKind, assetStateOf } from "./types/asset"; export { isOidToken, momentless, parseOid, toOid, typeOfOid } from "./types/oid"; export type { OidParts } from "./types/oid"; export type { AssetType, AttributeDefinition, AttributeLookup, AttributeType, AttributeTokenRef, AssetTypeToken, Metamodel } from "./types/metamodel"; diff --git a/src/types/asset.ts b/src/types/asset.ts index 4fee1b2..395e5b1 100644 --- a/src/types/asset.ts +++ b/src/types/asset.ts @@ -11,36 +11,30 @@ export type Oid = string; /** - * A date-time as the model carries it: `"2026-09-06T13:52:51.9030000"`, - * with a `Z` when the attribute is a UTC one (`ChangeDateUTC`). One - * spelling on every read: the endpoints differ (query.v1 sends seven - * decimals, api/asset drops trailing zeros, rest-1 sends three and writes a - * midnight as the date alone), so each read spells the value this way. - * Seven decimals is the server's own precision; nothing is cut. + * A date-time as the model carries it: `"2026-09-06T13:52:51.903"`, with a + * `Z` when the attribute is a UTC one (`ChangeDateUTC`). This is the + * standard's date-time format, three decimals of a second, so + * `new Date(value)` reads it in any engine. One spelling on every read: the + * endpoints differ (query.v1 sends seven decimals, api/asset drops trailing + * zeros, rest-1 sends three and writes a midnight as the date alone), so + * each read spells the value this way. + * + * The SDK cuts to the millisecond, by design. The server's stored + * resolution is about three milliseconds (in a live sample of 400 + * timestamps every digit past the third was zero), so nothing observed is + * lost; were an instance ever to carry finer digits, they are dropped. + * + * A value without a `Z` is the server's wall-clock time with no zone; a + * parser reads it as local time. For a day, take `value.slice(0, 10)`. */ export type DateString = string; -const DATE = /^(\d{4}-\d\d-\d\d)(?:T(\d\d:\d\d:\d\d)(?:\.(\d{1,7}))?)?(Z)?$/; - -/** - * A DateString as a `Date`, or null when the value is null or no date. - * Use this rather than `new Date(value)`: the standard promises a parser - * only three decimals of a second, and what an engine does with seven is - * its own business. A UTC attribute's value (it ends in `Z`) is that - * instant; any other is the server's wall-clock time with no zone, read - * here, as the standard reads a date-time without one, as local time. - */ -export function toDate(value: DateString | null | undefined): Date | null { - const m = typeof value === "string" ? DATE.exec(value) : null; - if (!m) return null; - const date = new Date(`${m[1]}T${m[2] ?? "00:00:00"}.${(m[3] ?? "").padEnd(3, "0").slice(0, 3)}${m[4] ?? ""}`); - return Number.isNaN(date.getTime()) ? null : date; -} +const DATE = /^(\d{4}-\d\d-\d\d)(?:T(\d\d:\d\d:\d\d)(?:\.(\d+))?)?(Z)?$/; /** A date as any endpoint spells it, in the model's one spelling (see DateString). Anything else is answered as given. */ export function dateString(value: T): T | DateString { const m = typeof value === "string" ? DATE.exec(value) : null; - return m ? `${m[1]}T${m[2] ?? "00:00:00"}.${(m[3] ?? "").padEnd(7, "0")}${m[4] ?? ""}` : value; + return m ? `${m[1]}T${m[2] ?? "00:00:00"}.${(m[3] ?? "").padEnd(3, "0").slice(0, 3)}${m[4] ?? ""}` : value; } /** diff --git a/test/integration/client.test.ts b/test/integration/client.test.ts index a23bdcf..532b5ac 100644 --- a/test/integration/client.test.ts +++ b/test/integration/client.test.ts @@ -56,7 +56,7 @@ describeInstance("client reads (live)", () => { if (byQuery) { const byPage = (await client.queryPage<{ _oid: string; BeginDate: string }>(sprint)).rows[0]!; const byRest = (await rest1.list<{ _oid: string; BeginDate: string }>(client.transport, "Timebox", { select: ["BeginDate"], sort: ["ID"], page: { size: 1, start: 0 } }, { lookup: client.schema })).rows[0]!; - expect(byQuery.BeginDate).toMatch(/^\d{4}-\d\d-\d\dT00:00:00\.0000000$/); + expect(byQuery.BeginDate).toMatch(/^\d{4}-\d\d-\d\dT00:00:00\.000$/); expect([byPage, byRest]).toEqual([byQuery, byQuery]); } for (const row of [viaQuery, viaPage, viaRest]) { @@ -64,9 +64,10 @@ describeInstance("client reads (live)", () => { expect(row["Owners.Name"]).toEqual([me.Name]); // a parallel array beside the Refs expect(typeof row["Scope.Name"]).toBe("string"); // its relation was not selected: the path is still there expect((row.Owners as { _oid: string }[]).map((o) => o._oid)).toEqual([me._oid]); - // The three endpoints write a date three ways (seven decimals, trailing zeros dropped, three decimals): the model has one. - expect(row.ChangeDateUTC).toMatch(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{7}Z$/); - expect(row.CreateDate).toMatch(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{7}$/); + // The three endpoints write a date three ways (seven decimals, trailing zeros dropped, three decimals): the model has one, the standard's, which any engine's Date reads. + expect(row.ChangeDateUTC).toMatch(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/); + expect(new Date(row.ChangeDateUTC as string).toISOString()).toBe(row.ChangeDateUTC); + expect(row.CreateDate).toMatch(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}$/); } // A Ref is bare on all three: the three rows are the same row. expect(viaPage).toEqual(viaQuery); diff --git a/test/integration/search.test.ts b/test/integration/search.test.ts index f3c48a1..31d5ede 100644 --- a/test/integration/search.test.ts +++ b/test/integration/search.test.ts @@ -183,10 +183,10 @@ describeInstance("search (live)", () => { const columns = ["Name", "Number", "Status.Name", "Owners.Name", "Owner.Name", "Scope.Name", "ChangeDateUTC"]; // Only stories: a Story has no Owner. const stories = await client.search(word, { types: ["Story"], select: columns, findin: ["Name", "Description"], page }); - expect(stories.rows).toEqual([{ _oid: story, Name: expect.stringContaining(word), Number: storyNumber, "Status.Name": null, "Owners.Name": [], "Owner.Name": null, "Scope.Name": expect.any(String), ChangeDateUTC: expect.stringMatching(/\.\d{7}Z$/) }]); + expect(stories.rows).toEqual([{ _oid: story, Name: expect.stringContaining(word), Number: storyNumber, "Status.Name": null, "Owners.Name": [], "Owner.Name": null, "Scope.Name": expect.any(String), ChangeDateUTC: expect.stringMatching(/T\d\d:\d\d:\d\d\.\d{3}Z$/) }]); // Only issues: no Status, no Owners. const issues = await client.search(word, { types: ["Issue"], select: columns, page }); - expect(issues.rows).toEqual([{ _oid: issue, Name: expect.stringContaining(word), Number: issueNumber, "Status.Name": null, "Owners.Name": null, "Owner.Name": null, "Scope.Name": expect.any(String), ChangeDateUTC: expect.stringMatching(/\.\d{7}Z$/) }]); + expect(issues.rows).toEqual([{ _oid: issue, Name: expect.stringContaining(word), Number: issueNumber, "Status.Name": null, "Owners.Name": null, "Owner.Name": null, "Scope.Name": expect.any(String), ChangeDateUTC: expect.stringMatching(/T\d\d:\d\d:\d\d\.\d{3}Z$/) }]); // Goals and topics have neither a Status nor an owner: the search is made (and finds none of the fixtures), where it used to be refused. expect(await client.search(word, { types: ["Goal", "Topic"], select: columns, findin: ["Name", "Estimate"], page })).toEqual({ rows: [], total: 0, more: false }); }); diff --git a/test/unit/client.test.ts b/test/unit/client.test.ts index 0e63b24..f487413 100644 --- a/test/unit/client.test.ts +++ b/test/unit/client.test.ts @@ -148,7 +148,7 @@ describe("client: reads", () => { const client = new AgilityApiClient({ baseUrl: "https://x" }, { transport: t, types: schema().cache }); expect(await client.deleted("Story", { select: ["Name", "ChangeDate", "CreateDate"], filter: ["Scope='Scope:0'"], page: { size: 2, start: 0 } })).toEqual({ // The Name is text that happens to look like a date: it is left alone, because the schema says what is a date. - rows: [{ _oid: "Story:7", Name: "2011-09-20", ChangeDate: "2026-07-13T18:06:14.6000000", CreateDate: "2011-09-20T00:00:00.0000000" }], total: null, more: false + rows: [{ _oid: "Story:7", Name: "2011-09-20", ChangeDate: "2026-07-13T18:06:14.600", CreateDate: "2011-09-20T00:00:00.000" }], total: null, more: false }); expect(t.calls).toHaveLength(1); expect(t.calls[0]).toMatchObject({ method: "GET", path: "/rest-1.v1/Data/Story", query: expect.objectContaining({ sel: "Name,ChangeDate,CreateDate", where: "Scope='Scope:0';IsDeleted='true'", page: "2,0", deleted: "true", needTotal: "true" }) }); diff --git a/test/unit/search.test.ts b/test/unit/search.test.ts index d9be7ac..fbb7755 100644 --- a/test/unit/search.test.ts +++ b/test/unit/search.test.ts @@ -128,7 +128,7 @@ describe("search", () => { it("a date is in the model's one spelling, by the row's own type; text that looks like a date is left alone", async () => { const dated = recording({ ...live, Assets: [{ _type: "Asset", href: "", id: "Story:1", Attributes: { Name: attribute("Name", "2011-09-20"), ChangeDateUTC: attribute("ChangeDateUTC", "2026-07-13T22:06:14.600Z"), CreateDate: attribute("CreateDate", "2011-09-20") } }] }); - expect((await search(dated, schema(), "printer", { types: ["Story", "Issue"], select: ["Name", "ChangeDateUTC", "CreateDate"], page })).rows).toEqual([{ _oid: "Story:1", Name: "2011-09-20", ChangeDateUTC: "2026-07-13T22:06:14.6000000Z", CreateDate: "2011-09-20T00:00:00.0000000" }]); + expect((await search(dated, schema(), "printer", { types: ["Story", "Issue"], select: ["Name", "ChangeDateUTC", "CreateDate"], page })).rows).toEqual([{ _oid: "Story:1", Name: "2011-09-20", ChangeDateUTC: "2026-07-13T22:06:14.600Z", CreateDate: "2011-09-20T00:00:00.000" }]); }); }); diff --git a/test/unit/translate.test.ts b/test/unit/translate.test.ts index 78d61fb..1030f89 100644 --- a/test/unit/translate.test.ts +++ b/test/unit/translate.test.ts @@ -4,7 +4,7 @@ import { join } from "node:path"; import { AgilityApiClient } from "../../src/client"; import type { RequestOptions, Transport } from "../../src/core/transport"; import { Schema, TypeCache } from "../../src/services/schema"; -import { dateString, toDate } from "../../src/types/asset"; +import { dateString } from "../../src/types/asset"; import type { Story } from "../../src/types/assets/Story"; import { fromWireRow, send, type AssetApiResponse } from "../../src/wire/assetApi"; import { toMetamodel, type MetamodelDocument } from "../../src/wire/meta"; @@ -62,7 +62,7 @@ describe("translate: a row into the model, by schema", () => { expect(row.IsDeleted).toBe(false); expect(row.IsClosed).toBe(true); expect(row.AssetState).toBe("Closed"); - expect(row.CreateDate).toBe("2026-06-27T12:28:29.1370000"); // sent as "…29.137" by api/asset; every read spells seven decimals + expect(row.CreateDate).toBe("2026-06-27T12:28:29.137"); // three decimals on every read, whatever the endpoint sent expect(row.Order).toBe(-1989738965); // Rank: a 32-bit integer sent as a string, a number in the model expect(row.Status).toEqual({ _oid: "StoryStatus:2191", Name: "Accepted", Order: 3 }); // [x] -> x; the nested row is translated by StoryStatus (Order is Rank there too) expect(row.Super).toEqual({ _oid: "Epic:1185", Name: "Order Entry" }); @@ -142,18 +142,18 @@ describe("translate: through send and the client", () => { expect(again!.IsClosed).toBe(true); }); - it("dateString is the model's one spelling of what each endpoint writes; toDate reads it without relying on a parser's tolerance for seven decimals", () => { - // query.v1, api/asset, rest-1, and rest-1's midnight: one value each way. - for (const sent of ["2026-07-13T22:06:14.6000000Z", "2026-07-13T22:06:14.6Z", "2026-07-13T22:06:14.600Z"]) expect(dateString(sent)).toBe("2026-07-13T22:06:14.6000000Z"); - expect(dateString("2011-09-20T00:00:00")).toBe("2011-09-20T00:00:00.0000000"); - expect(dateString("2011-09-20")).toBe("2011-09-20T00:00:00.0000000"); + it("dateString is the model's one spelling of what each endpoint writes: the standard's three decimals, which any Date parser reads", () => { + // query.v1, api/asset, rest-1: one value each way. + for (const sent of ["2026-07-13T22:06:14.6000000Z", "2026-07-13T22:06:14.6Z", "2026-07-13T22:06:14.600Z"]) { + expect(dateString(sent)).toBe("2026-07-13T22:06:14.600Z"); + expect(new Date(dateString(sent)).toISOString()).toBe("2026-07-13T22:06:14.600Z"); + } + // No fraction, and rest-1's midnight written as the date alone. + expect(dateString("2011-09-20T00:00:00")).toBe("2011-09-20T00:00:00.000"); + expect(dateString("2011-09-20")).toBe("2011-09-20T00:00:00.000"); + // Cut to the millisecond, by design: finer digits, were a server to send them, are dropped. + expect(dateString("2026-07-13T22:06:14.6001234Z")).toBe("2026-07-13T22:06:14.600Z"); // Not a date: answered as given. expect([dateString("soon"), dateString(null), dateString(7), dateString("2011-09-20 or so")]).toEqual(["soon", null, 7, "2011-09-20 or so"]); - // A UTC value is that instant; nothing beyond the millisecond is given to the parser. - expect(toDate("2026-07-13T22:06:14.6001234Z")?.toISOString()).toBe("2026-07-13T22:06:14.600Z"); - // No zone: local wall-clock time, as the standard reads it. - const local = toDate("2011-09-20T08:30:00.0000000")!; - expect([local.getFullYear(), local.getMonth(), local.getDate(), local.getHours(), local.getMinutes()]).toEqual([2011, 8, 20, 8, 30]); - expect([toDate(null), toDate(undefined), toDate("soon"), toDate("2011-13-45T00:00:00.0000000")]).toEqual([null, null, null, null]); }); }); From 5cab0b9023811b41164eb340c4e66319f8226150 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 15:16:52 +0000 Subject: [PATCH 11/11] explain: a rule spelled out in words is for a developer, not a user A rule the instance has no sentence for is answered as its name in words. That is a name, not a sentence written for a person, and it can read as the opposite of what happened ("message must not be sent", of one that was). audience is "developer" for these; the doc comment says exactly when it is "user". Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Rgicmffzzwb2CzyeDSEhBm --- CHANGELOG.md | 12 ++++++++++++ src/services/explain.ts | 24 +++++++++++++++--------- test/unit/explain.test.ts | 6 ++++-- 3 files changed, 31 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a1091e..0819635 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,18 @@ Migration: when the search box is empty, leave `find` out of the query (or do not send the read). +### Changed + +- **`client.explain`: a rule the instance has no sentence for is for a + developer, not a user.** Its explanation is the rule's name spelled out + ("Refused (asset cannot inactivate closed)."), which is a name and not a + sentence written for a person, and can read as the opposite of what + happened ("Refused (message must not be sent)." is said of a message + that was). `audience` is now `"developer"` for these; the sentence, + `rule` and `echoed: false` are unchanged. Migration: none if you show + only `audience: "user"` sentences; such a failure now gets your own + wording. + ### Added - **`client.search(text, { types, select?, findin?, filter?, where?, diff --git a/src/services/explain.ts b/src/services/explain.ts index 9e0c8d6..2908bf3 100644 --- a/src/services/explain.ts +++ b/src/services/explain.ts @@ -39,12 +39,17 @@ export interface Explanation { */ sentence: string; /** - * Who the sentence is for. "user": it was made for a person using the - * consumer's product — from a rule and the instance's labels, from the - * server's own localized sentence, or from the kind of error — and can - * be shown as it is. "developer": it is a message about the call itself - * (a usage error, a rejected query, a protocol error) or the server's - * raw text; log it, and show the user something of your own. + * Who the sentence is for. "user", in exactly three cases: a rule the + * SDK knows, on an attribute, said with the instance's label for it + * ("Project is required."); the server's own localized sentence; or a + * sentence for the kind of error (not signed in, not found). It can be + * shown as it is. "developer" for everything else: a message about the + * call itself (a usage error, a rejected query, a protocol error), the + * server's raw text, and a rule the instance has no sentence for, whose + * name is spelled out in words ("Refused (message must not be sent)."). + * A spelled-out rule is never for a user: it is a name, and can read as + * the opposite of what happened. Log these, and show the user + * something of your own. */ audience: "user" | "developer"; /** True when `sentence` is nothing more than the message as the server (or the SDK) sent it: nothing was explained. */ @@ -99,9 +104,10 @@ function sentenceOf(problem: Problem, label: string | null, related: string | nu } // The server's own sentence where it has one. if (localized) return forUser(localized); - // A rule the instance has no words for (seen live: Violation'AssetCannotInactivateClosed): never the bare token. - // What it means is in the rule's name, which a person can read; the token stays in `message` and `rule`. - if (problem.rule) return forUser(`${label ? `${label}: refused` : "Refused"} (${words(problem.rule)}).`); + // A rule the instance has no words for (seen live: Violation'AssetCannotInactivateClosed, Violation'MessageMustNotBeSent): + // never the bare token, but the rule's name spelled out is still a token and not a sentence written for a person. It can + // read as the opposite of what happened ("message must not be sent" is said of a message that was). So it is for a developer. + if (problem.rule) return { sentence: `${label ? `${label}: refused` : "Refused"} (${words(problem.rule)}).`, audience: "developer", echoed: false }; // Anything else is the server's own text, as it came. return { sentence: message, audience: "developer", echoed: true }; } diff --git a/test/unit/explain.test.ts b/test/unit/explain.test.ts index 3aae557..ff76d80 100644 --- a/test/unit/explain.test.ts +++ b/test/unit/explain.test.ts @@ -52,8 +52,10 @@ describe("explain", () => { expect(explained[4]).toMatchObject({ rule: "AssetCannotDeleteClosed", attribute: null }); // Who each sentence is for: the ones made for a person, and the server's raw text, which is echoed for a developer. expect(explained.map((e) => [e.audience, e.echoed])).toEqual([["user", false], ["user", false], ["developer", true], ["user", false], ["user", false]]); - // A rule the instance has no words for (seen live: closing a closed story) is never answered as its bare token. - expect((await explain(loc2(), [failure(0, "Violation'AssetCannotInactivateClosed")]))[0]).toMatchObject({ sentence: "Refused (asset cannot inactivate closed).", audience: "user", echoed: false, rule: "AssetCannotInactivateClosed", localized: null, message: "Violation'AssetCannotInactivateClosed" }); + // A rule the instance has no words for (seen live: closing a closed story; deleting a sent message) is never answered as its + // bare token, and never as a sentence for a user either: its name in words can read as the opposite of what happened. + expect((await explain(loc2(), [failure(0, "Violation'MessageMustNotBeSent")]))[0]).toMatchObject({ sentence: "Refused (message must not be sent).", audience: "developer", echoed: false, rule: "MessageMustNotBeSent", attribute: null, localized: null, message: "Violation'MessageMustNotBeSent" }); + expect((await explain(loc2(), [failure(0, "Violation'AssetCannotInactivateClosed")]))[0]).toMatchObject({ sentence: "Refused (asset cannot inactivate closed).", audience: "developer", echoed: false, rule: "AssetCannotInactivateClosed", localized: null, message: "Violation'AssetCannotInactivateClosed" }); // A Resolution failure names the related type, labelled when the instance has a label for it. const labelled = loc2(); LOC2["AssetType'Member"] = "Member";