@yolk-sdk/emulators 0.1.0-canary.100 → 0.1.0-canary.102

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1599,10 +1599,10 @@ GitHub case, only to prove that case catches it.
1599
1599
 
1600
1600
  `await makeGoogleEmulator(options?)` returns
1601
1601
  `{ fetch, fetchOn, ledger, faults, reset, seed, snapshot, coverage, close }`. Each call has its own
1602
- state; `await close()` when done. It emulates only the Gmail, Calendar, and Drive routes the
1603
- thirteen Google conformance cases (with their cleanup) send, so the Google connector actions and the
1604
- cases run unchanged against it, the irreversible practice send included. Each route answers only on
1605
- the origin its fixtures record: Gmail (the API and the multipart send upload) on
1602
+ state; `await close()` when done. It emulates only the Gmail, Calendar, and Drive routes the fifteen
1603
+ Google conformance cases (with their cleanup) send, so the Google connector actions and the cases
1604
+ run unchanged against it, the irreversible practice send included. Each route answers only on the
1605
+ origin its fixtures record: Gmail (the API and the multipart send upload) on
1606
1606
  `https://gmail.googleapis.com` (`googleEmulatorGmailOrigin`), Calendar and Drive on
1607
1607
  `https://www.googleapis.com` (`googleEmulatorApisOrigin`). `fetch` takes the origin from the request
1608
1608
  URL (in-process routing keeps it); behind a loopback rewrite, which loses it, serve
@@ -1636,23 +1636,24 @@ the live runner turns that into its lookup-failed `WARN`.
1636
1636
  Routes (every request needs `Authorization: Bearer <token>`, a recognisable bearer; bodies are
1637
1637
  JSON unless noted; Drive requests also send `accept: application/json`, as recorded):
1638
1638
 
1639
- | Route | Behavior |
1640
- | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
1641
- | `GET /gmail/v1/users/me/messages` | `labelIds`, `maxResults`, `pageToken`: `{ messages: [{ id, threadId }], nextPageToken? }` |
1642
- | `GET /gmail/v1/users/me/messages/{messageId}` | `format=minimal`, `metadata`, or `full`, as recorded for that message; the recorded 404 |
1643
- | `GET /gmail/v1/users/me/messages/{messageId}/attachments/{id}` | `{ size, data }` (base64url) of a seeded attachment |
1644
- | `POST /gmail/v1/users/me/messages/{messageId}/modify` | `{ addLabelIds: [<created label>] }`: `{ id, threadId, labelIds }` |
1645
- | `POST /gmail/v1/users/me/messages/{messageId}/trash`, `/untrash` | No body: adds or removes `TRASH`, answering `{ id, threadId, labelIds }` |
1646
- | `POST /gmail/v1/users/me/labels` | `{ name: "yolk-conformance <runId> label" }`: the created user label (`Label_9101` first) |
1647
- | `GET`, `DELETE /gmail/v1/users/me/labels/{labelId}` | Delete a created label (204; it leaves every message); a read of an absent label answers 404 |
1648
- | `POST /gmail/v1/users/me/drafts`, `PUT .../drafts/{draftId}` | The recorded run draft without recipients: `{ id, message: { id, threadId, labelIds } }` |
1649
- | `DELETE /gmail/v1/users/me/drafts/{draftId}` | 204 (the draft and its message go); an absent draft answers the recorded 404 |
1650
- | `GET /gmail/v1/users/me/threads/{threadId}` | `format=full`: a draft thread created here |
1651
- | `POST /upload/gmail/v1/users/me/messages/send` | `uploadType=multipart`, `multipart/related`: the practice message only (see below) |
1652
- | `GET`, `POST /calendar/v3/calendars/{calendarId}/events` | Range listing (`singleEvents=true`, `orderBy=startTime`) with page tokens; the run event |
1653
- | `GET`, `PATCH`, `DELETE .../events/{eventId}` | Read (cancelled too), the recorded rename, delete to `cancelled` (204), then the recorded 410 |
1654
- | `GET`, `POST /drive/v3/files` | Folder listing (`'<folder>' in parents and trashed = false`) with page tokens; the run folder |
1655
- | `GET`, `PATCH`, `DELETE /drive/v3/files/{fileId}` | Read with the connector `fields` (absent: the recorded 404), `{ trashed: true }`, delete 204 |
1639
+ | Route | Behavior |
1640
+ | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
1641
+ | `GET /gmail/v1/users/me/messages` | `labelIds`, `maxResults`, `pageToken`: `{ messages: [{ id, threadId }], nextPageToken? }` |
1642
+ | `GET /gmail/v1/users/me/threads` | `labelIds`, `maxResults`, `pageToken`: `{ threads: [{ id, snippet, historyId }], nextPageToken? }` |
1643
+ | `GET /gmail/v1/users/me/messages/{messageId}` | `format=minimal`, `metadata` (optional `metadataHeaders`), or `full`, as recorded; the recorded 404 |
1644
+ | `GET /gmail/v1/users/me/messages/{messageId}/attachments/{id}` | `{ size, data }` (base64url) of a seeded attachment |
1645
+ | `POST /gmail/v1/users/me/messages/{messageId}/modify` | `{ addLabelIds: [<created label>] }`: `{ id, threadId, labelIds }` |
1646
+ | `POST /gmail/v1/users/me/messages/{messageId}/trash`, `/untrash` | No body: adds or removes `TRASH`, answering `{ id, threadId, labelIds }` |
1647
+ | `POST /gmail/v1/users/me/labels` | `{ name: "yolk-conformance <runId> label" }`: the created user label (`Label_9101` first) |
1648
+ | `GET`, `DELETE /gmail/v1/users/me/labels/{labelId}` | Delete a created label (204; it leaves every message); a read of an absent label answers 404 |
1649
+ | `POST /gmail/v1/users/me/drafts`, `PUT .../drafts/{draftId}` | The recorded run draft without recipients: `{ id, message: { id, threadId, labelIds } }` |
1650
+ | `DELETE /gmail/v1/users/me/drafts/{draftId}` | 204 (the draft and its message go); an absent draft answers the recorded 404 |
1651
+ | `GET /gmail/v1/users/me/threads/{threadId}` | `format=full`: a draft thread created here; `format=metadata` with `metadataHeaders`: a stored thread |
1652
+ | `POST /upload/gmail/v1/users/me/messages/send` | `uploadType=multipart`, `multipart/related`: the practice message only (see below) |
1653
+ | `GET`, `POST /calendar/v3/calendars/{calendarId}/events` | Range listing (`singleEvents=true`, `orderBy=startTime`) with page tokens; the run event |
1654
+ | `GET`, `PATCH`, `DELETE .../events/{eventId}` | Read (cancelled too), the recorded rename, delete to `cancelled` (204), then the recorded 410 |
1655
+ | `GET`, `POST /drive/v3/files` | Folder listing (`'<folder>' in parents and trashed = false`) with page tokens; the run folder |
1656
+ | `GET`, `PATCH`, `DELETE /drive/v3/files/{fileId}` | Read with the connector `fields` (absent: the recorded 404), `{ trashed: true }`, delete 204 |
1656
1657
 
1657
1658
  **The practice send is recorded, never delivered.** `google.gmail.send-practice-address` is
1658
1659
  irreversible on Gmail. The emulator accepts only the recorded 7-bit message whose sole recipient
@@ -1663,8 +1664,9 @@ a minted `Message-ID`), and delivers nothing anywhere; only `reset` or `seed` dr
1663
1664
  set another `practiceAddress`, but then every send answers 400 not-emulated (the reason names the
1664
1665
  recorded `practice@example.test`): the recorded `sizeEstimate` of the sent message covers its
1665
1666
  address, as it covers its subject, so draft and send subjects need a run id of the fixtures' length
1666
- (13 characters; see the latitude below). The draft metadata `body.size` (64) and the sent message
1667
- `body.size` (88) are the fixtures' recorded values, answered as recorded.
1667
+ (13 characters; see the latitude below). The draft payload `body.size` (0, the draft is
1668
+ `multipart/alternative`) and the sent message `body.size` (88) are the fixtures' recorded values,
1669
+ answered as recorded.
1668
1670
 
1669
1671
  **Fail closed: the shared rule.** Google follows the shared fail-closed rule of the stateful
1670
1672
  wrapper, exactly as the GitHub emulator states it above: every route parameter has a raw pattern
@@ -1702,23 +1704,27 @@ emulator mints (it never mints anything else):
1702
1704
  forms no seeded id or thread id may use. All come from counters in the state that only advance.
1703
1705
  Event `created` / `updated`, folder `createdTime` / `modifiedTime` / `trashedTime`, and the sent
1704
1706
  `Date` header come from the injectable `now` clock. Page tokens are the fixtures' values
1705
- (`synthetic-gmail-page-2`, ...) in the generation that first issued them, and
1706
- `<token>.g<generation>` after a reset or seed (each starts a generation); a token is never
1707
- rebound: token values are globally unique, so another list or page size, or a changed list, gets a
1708
- distinct `<token>.v<k>`.
1707
+ (`synthetic-gmail-page-2`, `synthetic-gmail-threads-page-2`, ...) in the generation that first
1708
+ issued them, and `<token>.g<generation>` after a reset or seed (each starts a generation); a token
1709
+ is never rebound: token values are globally unique, so another list or page size, or a changed
1710
+ list, gets a distinct `<token>.v<k>`.
1709
1711
  - **Implied entities.** The paging label (`impliedLabelIds`), the five messages its listing names
1710
- (`impliedMessages`, rendered only as `{ id, threadId }` list entries), and the practice Drive
1711
- folder (`impliedFolderIds`) are only named by the fixtures: references resolve through them (a
1712
- label listing, a folder parent), but an answer that would render one is not emulated.
1712
+ (`impliedMessages`, rendered only as `{ id, threadId }` list entries), their five threads
1713
+ (`impliedThreads`, rendered only as `{ id, snippet, historyId }` thread listing entries), and the
1714
+ practice Drive folder (`impliedFolderIds`) are only named by the fixtures: references resolve
1715
+ through them (a label listing, a folder parent), but an answer that would render one is not
1716
+ emulated.
1713
1717
  - **Recorded renderings.** A Gmail message answers only the formats a fixture records for it (the
1714
- work message `minimal`, the attachment message `full`, a composed draft `metadata` and `full`, an
1715
- updated draft `full`, a sent message `metadata`); another format is not emulated.
1718
+ work message `minimal`, the attachment message `metadata` and `full`, a composed draft `metadata`
1719
+ and `full`, an updated draft `full`, a sent message `metadata`); another format is not emulated. A
1720
+ `metadataHeaders` selection (only with `format=metadata`) answers the recorded metadata rendering
1721
+ with only the selected headers, in recorded order.
1716
1722
  - **What writes leave.** A reversible case ends at the seed except the counters, plus each event
1717
1723
  case's own event, which Calendar keeps readable as `cancelled` (the fixtures read it back); the
1718
1724
  send leaves its sent message. Deleting a label removes it from every message.
1719
1725
  - **Page tokens.** A token is accepted only when this emulator issued it for the same list (label
1720
- and `maxResults`; calendar, range, and `maxResults`; folder and `pageSize`) since the last reset
1721
- or seed, and the list renders exactly as when it was issued.
1726
+ and `maxResults` for messages and for threads; calendar, range, and `maxResults`; folder and
1727
+ `pageSize`) since the last reset or seed, and the list renders exactly as when it was issued.
1722
1728
  - **Request-shape latitude (`/google`, the only accepted deviations).** Any bearer value in the RFC
1723
1729
  6750 `b64token` syntax (`[A-Za-z0-9\-._~+/]+=*`) of at least 8 characters, starting with a
1724
1730
  character in `[G-Zg-z\-._~+/]` other than `n`, `r`, `t`, `u`, with at least one outside
@@ -1731,22 +1737,27 @@ emulator mints (it never mints anything else):
1731
1737
  fixtures' `run-synthetic`, because the recorded `sizeEstimate` of the draft and sent messages
1732
1738
  (answered by their message reads and the draft thread) covers the subject; on the practice send, a
1733
1739
  `content-type` of exactly `multipart/related; boundary=<b>` with any one unquoted boundary of 1 to
1734
- 70 `[A-Za-z0-9_]` characters and no other parameter; a `gmail.list` `maxResults` from 1 to 500, a
1735
- `calendar.list_events` `maxResults` from 1 to 2500, and a `drive.list_files` `pageSize` from 1 to
1736
- 1000; any `timeMin` before `timeMax` (RFC 3339 instants with a real calendar date, hour 0 to 23,
1737
- minute and second 0 to 59, and a `Z` or in-range numeric offset); any id of an item the state
1738
- holds where a fixture has an id (writes: only items created here, plus label changes, trash, and
1739
- untrash of a stored non-draft message); and, for an id the state does not hold, only the recorded
1740
- not-found answers (a `format=minimal` read of a 16-hex-digit message id, a read of a
1741
- `Label_<1 to 999999999>` label, a delete of an `r-<digits>` draft, and a Drive file read). A seed
1742
- may set another `practiceAddress`, but then every send is refused, since the recorded
1743
- `sizeEstimate` of the sent message also covers the address: the send answers only while the seeded
1744
- address is the recorded `practice@example.test`. On the draft compose and update routes,
1745
- `message.raw` must be canonical unpadded base64url of exactly the recorded draft MIME of that
1746
- route, the run id aside; any other `message.raw` (line-wrapped, the standard alphabet, padded,
1747
- with a stray character, or with MIME-level encodings such as RFC 2047 encoded-words,
1748
- quoted-printable, or UTF-16) is refused before anything is recorded or a fault is decided, as a
1749
- constant entry with the route's own declared reason
1740
+ 70 `[A-Za-z0-9_]` characters and no other parameter; a `gmail.list` or `gmail.list_threads`
1741
+ `maxResults` from 1 to 500, a `calendar.list_events` `maxResults` from 1 to 2500, and a
1742
+ `drive.list_files` `pageSize` from 1 to 1000; any `timeMin` before `timeMax` (RFC 3339 instants
1743
+ with a real calendar date, hour 0 to 23, minute and second 0 to 59, and a `Z` or in-range numeric
1744
+ offset); any id of an item the state holds where a fixture has an id (writes: only items created
1745
+ here, plus label changes, trash, and untrash of a stored non-draft message); and, for an id the
1746
+ state does not hold, only the recorded not-found answers (a `format=minimal` read of a
1747
+ 16-hex-digit message id, a read of a `Label_<1 to 999999999>` label, a delete of an `r-<digits>`
1748
+ draft, and a Drive file read); on a `format=metadata` message read, and on a `format=metadata`
1749
+ read of a thread of stored non-draft messages (a thread read in that format takes a selection), a
1750
+ `metadataHeaders` selection, repeated in any order, of 1 to 50 distinct header names each spelled
1751
+ exactly as a header of the recorded metadata rendering, answered as that rendering with only the
1752
+ selected headers, in recorded order. A seed may set another `practiceAddress`, but then every send
1753
+ is refused, since the recorded `sizeEstimate` of the sent message also covers the address: the
1754
+ send answers only while the seeded address is the recorded `practice@example.test`. On the draft
1755
+ compose and update routes, `message.raw` must be canonical unpadded base64url of exactly the
1756
+ recorded draft MIME of that route, the run id aside; any other `message.raw` (line-wrapped, the
1757
+ standard alphabet, padded, with a stray character, or with MIME-level encodings such as RFC 2047
1758
+ encoded-words, quoted-printable other than the recorded parts, or UTF-16) is refused before
1759
+ anything is recorded or a fault is decided, as a constant entry with the route's own declared
1760
+ reason
1750
1761
  (`message.raw must be canonical base64url UTF-8 MIME`,
1751
1762
  `a draft compose other than the recorded run draft is not emulated` or its `update` form, the
1752
1763
  13-character run-id reason, or `message has a key this route does not take`), or
@@ -1773,22 +1784,21 @@ answers an evidence-tagged 500 `{ error: { type: 'emulator_error', message } }`
1773
1784
  reads the clock.
1774
1785
 
1775
1786
  State and seeds: `practiceAddress`, Gmail `messages` (with their recorded renderings),
1776
- `impliedMessages`, `impliedLabelIds`, created `labels`, `attachments`, `drafts`, Calendar
1777
- `calendars` and `events`, Drive `files` and `impliedFolderIds`, and the counters. The default seed
1778
- is the synthetic fixture entities with the ids of `googleConformanceFixtureSeeds`. Pass
1779
- `seed: { profile?, practiceAddress?, messages?, impliedMessages?, impliedLabelIds?, attachments?,
1780
- calendars?, events?, files?, impliedFolderIds? }` (lists replace the profile's; labels and drafts
1781
- are never seeded) with profiles `'default'` or `'empty'`. `reset()`, `seed(next)`, and
1782
- `snapshot()` behave as in the Dropbox emulator; reset and seed also clear issued page tokens.
1787
+ `impliedMessages`, `impliedThreads`, `impliedLabelIds`, created `labels`, `attachments`, `drafts`,
1788
+ Calendar `calendars` and `events`, Drive `files` and `impliedFolderIds`, and the counters. The
1789
+ default seed is the synthetic fixture entities with the ids of `googleConformanceFixtureSeeds`.
1790
+ Pass `seed: { profile?, practiceAddress?, messages?, impliedMessages?, impliedThreads?,
1791
+ impliedLabelIds?, attachments?, calendars?, events?, files?, impliedFolderIds? }` (lists replace
1792
+ the profile's; labels and drafts are never seeded) with profiles `'default'` or `'empty'`.
1793
+ `reset()`, `seed(next)`, and `snapshot()` behave as in the Dropbox emulator; reset and seed also
1794
+ clear issued page tokens.
1783
1795
 
1784
1796
  Faults and the control plane behave as in the Dropbox emulator (the ledger records only the
1785
1797
  `content-type` request header); a 429 fault with `retry-after` reaches the connector as
1786
1798
  `google_rate_limited` with `retryAfterMs`.
1787
1799
 
1788
- **Drill knobs (tests only).** `drills: { gmailPageRepeats, attachmentStandardBase64,
1789
- notFoundWithoutMessage, labelDeleteKeepsOnMessages, draftUpdateKeepsContent,
1790
- trashAnswerOmitsTrash, sentMessageWithoutTo, calendarPageRepeats, eventPatchKeepsSummary,
1791
- repeatedEventDeleteConflict, drivePageRepeats, getFileWithoutParents, listIncludesTrashed }`
1800
+ **Drill knobs (tests only).**
1801
+ `drills: { gmailPageRepeats, attachmentStandardBase64, notFoundWithoutMessage, gmailThreadPageRepeats, metadataHeadersIgnored, labelDeleteKeepsOnMessages, draftUpdateKeepsContent, trashAnswerOmitsTrash, sentMessageWithoutTo, calendarPageRepeats, eventPatchKeepsSummary, repeatedEventDeleteConflict, drivePageRepeats, getFileWithoutParents, listIncludesTrashed }`
1792
1802
  (booleans) each make the emulator disagree with exactly one Google case, only to prove that case
1793
1803
  catches it.
1794
1804
 
@@ -1 +1 @@
1
- {"version":3,"file":"gmail.d.mts","names":[],"sources":["../../src/google/gmail.ts"],"mappings":";;;;cA4Da,YAAA;AAAb;AAAA,cAu6Ba,WAAA,EAAa,aAAa,CAAC,WAAA"}
1
+ {"version":3,"file":"gmail.d.mts","names":[],"sources":["../../src/google/gmail.ts"],"mappings":";;;;cA8Da,YAAA;AAAb;AAAA,cA2sCa,WAAA,EAAa,aAAa,CAAC,WAAA"}
@@ -4,8 +4,9 @@ import { base64UrlOfText, mintedDraftId, mintedLabelIdPattern, mintedMessageId,
4
4
  import { Predicate } from "effect";
5
5
  //#region src/google/gmail.ts
6
6
  /**
7
- * Gmail routes of the Google emulator (internal): message listing by label with page tokens,
8
- * message reads in the recorded formats, attachments, the label lifecycle, label changes, trash and
7
+ * Gmail routes of the Google emulator (internal): message and thread listing by label with page
8
+ * tokens, message and thread reads in the recorded formats (a `metadataHeaders` selection keeps
9
+ * only the selected recorded headers), attachments, the label lifecycle, label changes, trash and
9
10
  * untrash, the draft lifecycle with its thread, and the multipart practice send.
10
11
  *
11
12
  * Every answer comes from the Gmail fixtures, through the seed or the request, or is minted. The
@@ -20,6 +21,8 @@ const gmailApiPath = "/gmail/v1/users/me";
20
21
  const listCase = "google.gmail.list-page-token";
21
22
  const attachmentCase = "google.gmail.attachment-base64url";
22
23
  const notFoundCase = "google.gmail.not-found-envelope";
24
+ const listThreadsCase = "google.gmail.list-threads-page-token";
25
+ const metadataHeadersCase = "google.gmail.metadata-headers";
23
26
  const labelCase = "google.gmail.label-create-apply-delete";
24
27
  const draftCase = "google.gmail.draft-compose-update-delete";
25
28
  const trashCase = "google.gmail.trash-untrash";
@@ -97,7 +100,7 @@ const findMessage = (state, id) => state.messages.find((message) => message.id =
97
100
  const isImpliedMessage = (state, id) => state.impliedMessages.some((message) => message.id === id);
98
101
  const isDraftMessage = (message) => message.labelIds.includes("DRAFT");
99
102
  const replaceMessage = (state, next) => state.messages.map((message) => message.id === next.id ? next : message);
100
- const listMessages = statefulRoute(gmail("GET", "/messages", false, [listCase]), "none", (request) => {
103
+ const listMessages = statefulRoute(gmail("GET", "/messages", false, [listCase, listThreadsCase]), "none", (request) => {
101
104
  const query = exactQuery(request, ["labelIds", "maxResults"], ["pageToken"]);
102
105
  if (isNotEmulated(query)) return query;
103
106
  const labelId = query["labelIds"] ?? "";
@@ -127,35 +130,117 @@ const listMessages = statefulRoute(gmail("GET", "/messages", false, [listCase]),
127
130
  });
128
131
  });
129
132
  });
133
+ const listThreads = statefulRoute(gmail("GET", "/threads", false, [listThreadsCase]), "none", (request) => {
134
+ const query = exactQuery(request, ["labelIds", "maxResults"], ["pageToken"]);
135
+ if (isNotEmulated(query)) return query;
136
+ const labelId = query["labelIds"] ?? "";
137
+ if (!gmailIdSegment.test(labelId)) return notEmulated("labelIds must be one label id");
138
+ const maxResults = pageSize(query["maxResults"], "maxResults", 1, 500);
139
+ if (isNotEmulated(maxResults)) return maxResults;
140
+ const pageToken = query["pageToken"];
141
+ return pageToken === "" ? notEmulated("an empty pageToken is not emulated") : {
142
+ labelId,
143
+ maxResults,
144
+ pageToken
145
+ };
146
+ }, (state, input, { env }) => {
147
+ if (!(state.impliedLabelIds.includes(input.labelId) || state.labels.some((label) => label.id === input.labelId))) return notEmulated("listing a label the state does not hold is not emulated");
148
+ const messages = [...state.messages, ...state.impliedMessages];
149
+ const matches = messages.filter((message) => message.labelIds.includes(input.labelId));
150
+ if (matches.length === 0) return notEmulated("a listing without threads is not emulated (no fixture records one)");
151
+ const threadIds = [...new Set(matches.map((message) => message.threadId))];
152
+ if (messages.some((message) => threadIds.includes(message.threadId) && message.labelIds.some((id) => id === "TRASH" || id === "SPAM"))) return notEmulated("a listing that would leave out threads in Trash or Spam is not emulated");
153
+ const threads = threadIds.map((id) => state.impliedThreads.find((thread) => thread.id === id));
154
+ if (threads.some((thread) => thread === void 0)) return notEmulated("listing a thread no thread listing fixture names is not emulated");
155
+ return listPage(env, "gmail-threads", `gmail-threads\u0000${input.labelId}\u0000${input.maxResults}`, threads.flatMap((thread) => thread === void 0 ? [] : [{
156
+ id: thread.id,
157
+ snippet: thread.snippet,
158
+ historyId: thread.historyId
159
+ }]), input.maxResults, input.pageToken, env.drills.gmailThreadPageRepeats, (page, nextPageToken) => {
160
+ const head = { threads: [...page] };
161
+ if (nextPageToken !== void 0) head.nextPageToken = nextPageToken;
162
+ return googleJson(200, {
163
+ ...head,
164
+ resultSizeEstimate: threads.length
165
+ });
166
+ });
167
+ });
130
168
  const formats = [
131
169
  "minimal",
132
170
  "metadata",
133
171
  "full"
134
172
  ];
135
173
  const isFormat = (value) => value !== void 0 && formats.includes(value);
174
+ /** The connector's bound on one selection (`gmailMetadataHeadersMaxItems`), copied as data. */
175
+ const metadataHeadersMaxItems = 50;
176
+ /** One RFC 5322 header field name, as the connector sends it. */
177
+ const headerNamePattern = /^[!-9;-~]{1,128}$/;
178
+ /**
179
+ * The `format` and the `metadataHeaders` selection of a read: the selection only with
180
+ * `format=metadata`, 1 to 50 distinct header names; not emulated otherwise.
181
+ */
182
+ const readFormat = (request) => {
183
+ const query = exactQuery(request, ["format"], ["metadataHeaders"], { repeatable: ["metadataHeaders"] });
184
+ if (isNotEmulated(query)) return query;
185
+ const format = query["format"];
186
+ if (!isFormat(format)) return notEmulated("format must be minimal, metadata, or full");
187
+ const names = request.query.getAll("metadataHeaders");
188
+ if (names.length === 0) return {
189
+ format,
190
+ metadataHeaders: void 0
191
+ };
192
+ if (format !== "metadata") return notEmulated("metadataHeaders with a format other than metadata is not emulated");
193
+ return names.length <= metadataHeadersMaxItems && new Set(names).size === names.length && names.every((name) => headerNamePattern.test(name)) ? {
194
+ format,
195
+ metadataHeaders: names
196
+ } : notEmulated("metadataHeaders must be 1 to 50 distinct header names");
197
+ };
198
+ const isHeader = (value) => isJsonObject(value) && Predicate.isString(value.name);
199
+ /**
200
+ * `rendered` (a metadata rendering) keeping only the recorded top-level headers the selection
201
+ * names, in recorded order; not emulated when a selected name is not exactly the name of one of its
202
+ * recorded headers (no fixture records a selection of an absent header or in another case).
203
+ * `ignore` (a drill) answers the rendering unchanged.
204
+ */
205
+ const selectHeaders = (rendered, selection, ignore) => {
206
+ if (selection === void 0) return rendered;
207
+ const payload = rendered.payload;
208
+ const headers = isJsonObject(payload) && Array.isArray(payload.headers) ? payload.headers : [];
209
+ const recorded = headers.filter(isHeader);
210
+ if (!isJsonObject(payload) || recorded.length !== headers.length || !selection.every((name) => recorded.some((header) => header.name === name))) return notEmulated("a metadataHeaders selection naming a header the recorded rendering lacks is not emulated");
211
+ if (ignore) return rendered;
212
+ return {
213
+ ...rendered,
214
+ payload: {
215
+ ...payload,
216
+ headers: recorded.filter((header) => selection.includes(header.name))
217
+ }
218
+ };
219
+ };
136
220
  const getMessage = statefulRoute(gmail("GET", "/messages/{messageId}", false, [
137
221
  attachmentCase,
138
222
  notFoundCase,
223
+ metadataHeadersCase,
139
224
  labelCase,
140
225
  draftCase,
141
226
  trashCase,
142
227
  sendCase
143
228
  ], ["messageId"]), "none", (request) => {
144
- const query = exactQuery(request, ["format"]);
145
- if (isNotEmulated(query)) return query;
146
- const format = query["format"];
147
- return isFormat(format) ? {
229
+ const read = readFormat(request);
230
+ return isNotEmulated(read) ? read : {
148
231
  id: param(request, "messageId"),
149
- format
150
- } : notEmulated("format must be minimal, metadata, or full");
232
+ ...read
233
+ };
151
234
  }, (state, input, { env }) => {
152
235
  const message = findMessage(state, input.id);
153
236
  if (message !== void 0) {
154
237
  const rendered = renderMessage(message, input.format);
155
- return rendered === void 0 ? notEmulated(`no fixture records this message with format=${input.format}`) : answer(() => googleJson(200, rendered));
238
+ if (rendered === void 0) return notEmulated(`no fixture records this message with format=${input.format}`);
239
+ const selected = selectHeaders(rendered, input.metadataHeaders, env.drills.metadataHeadersIgnored);
240
+ return isNotEmulated(selected) ? selected : answer(() => googleJson(200, selected));
156
241
  }
157
242
  if (isImpliedMessage(state, input.id)) return notEmulated("reading a message a fixture only names in a listing is not emulated");
158
- return input.format === "minimal" && absentMessageIdPattern.test(input.id) ? answer(() => notFound(env)) : notEmulated("only a format=minimal read of an absent 16-hex-digit id is recorded");
243
+ return input.format === "minimal" && input.metadataHeaders === void 0 && absentMessageIdPattern.test(input.id) ? answer(() => notFound(env)) : notEmulated("only a format=minimal read of an absent 16-hex-digit id is recorded");
159
244
  });
160
245
  const getAttachment = statefulRoute(gmail("GET", "/messages/{messageId}/attachments/{attachmentId}", false, [attachmentCase], ["messageId", "attachmentId"]), "none", (request) => withoutQuery(request) ?? {
161
246
  messageId: param(request, "messageId"),
@@ -263,7 +348,32 @@ const decodeBase64UrlText = (raw) => {
263
348
  return;
264
349
  }
265
350
  };
266
- const draftMimePattern = /^Subject: ([^\r\n]*)\r\nContent-Type: text\/plain; charset=utf-8\r\n\r\n([\s\S]*)$/;
351
+ const draftBoundary = "=_yolk-draft-alternative";
352
+ const draftContentType = `multipart/alternative; boundary="${draftBoundary}"`;
353
+ /** The quoted-printable part of the recorded draft MIME. */
354
+ const recordedDraftPart = (type, encoded) => `Content-Type: text/${type}; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n${encoded}`;
355
+ /** The draft MIME the draft fixture records after the `Subject` line, for each draft kind. */
356
+ const recordedDraftMime = (plain, html) => [
357
+ "MIME-Version: 1.0",
358
+ `Content-Type: ${draftContentType}`,
359
+ "",
360
+ `--${draftBoundary}`,
361
+ recordedDraftPart("plain", plain),
362
+ `--${draftBoundary}`,
363
+ recordedDraftPart("html", html),
364
+ `--${draftBoundary}--`
365
+ ].join("\r\n");
366
+ const recordedDrafts = {
367
+ compose: {
368
+ text: draftText,
369
+ mime: recordedDraftMime("Synthetic conformance draft, safe to delete: gr=C3=BC=C3=9Fe =E2=9C=93", "<div dir=3D\"ltr\">Synthetic conformance draft, safe to delete: gr=C3=BC=\r\n=C3=9Fe =E2=9C=93</div>")
370
+ },
371
+ update: {
372
+ text: updatedDraftText,
373
+ mime: recordedDraftMime("Updated synthetic conformance draft: =C2=A1hola! =E2=9C=93", "<div dir=3D\"ltr\">Updated synthetic conformance draft: =C2=A1hola! =E2=9C=93=\r\n</div>")
374
+ }
375
+ };
376
+ const draftMimePattern = /^Subject: ([^\r\n]*)\r\n([\s\S]*)$/;
267
377
  /** The reasons a draft `message.raw` is refused with (constants; never derived from a request). */
268
378
  const draftKeysReason = "message has a key this route does not take";
269
379
  const canonicalRawReason = "message.raw must be canonical base64url UTF-8 MIME";
@@ -293,9 +403,10 @@ const readDraftRaw = (message, kind) => {
293
403
  };
294
404
  const parts = draftMimePattern.exec(decoded);
295
405
  const subject = parts?.[1] ?? "";
296
- const body = parts?.[2] ?? "";
406
+ const rest = parts?.[2] ?? "";
297
407
  const runId = kind === "compose" ? runIdOf(subject, "draft", draftSubjectRest) : runIdOf(subject, "draft updated", draftSubjectRest);
298
- if (parts === null || runId === void 0 || body !== (kind === "compose" ? draftText : updatedDraftText)) return {
408
+ const recorded = recordedDrafts[kind];
409
+ if (parts === null || runId === void 0 || rest !== recorded.mime) return {
299
410
  decoded,
300
411
  content: notEmulated(otherDraftReason(kind))
301
412
  };
@@ -303,7 +414,7 @@ const readDraftRaw = (message, kind) => {
303
414
  decoded,
304
415
  content: runId.length === 13 ? {
305
416
  subject,
306
- body
417
+ body: recorded.text
307
418
  } : notEmulated(sizedRunIdReason("draft"))
308
419
  };
309
420
  };
@@ -330,18 +441,36 @@ const draftRawViews = (kind) => (body) => {
330
441
  });
331
442
  return decoded === void 0 ? [] : [decoded];
332
443
  };
333
- const textPayload = (subject, body) => ({
444
+ /** A draft's `multipart/alternative` payload as the draft fixture's metadata read records it. */
445
+ const draftPayload = (subject) => ({
334
446
  partId: "",
335
- mimeType: "text/plain",
447
+ mimeType: "multipart/alternative",
336
448
  filename: "",
337
449
  headers: [{
338
450
  name: "Subject",
339
451
  value: subject
340
452
  }, {
341
453
  name: "Content-Type",
342
- value: "text/plain; charset=utf-8"
454
+ value: draftContentType
343
455
  }],
344
- body
456
+ body: { size: 0 }
457
+ });
458
+ /** A `format=full` text part, its `body.data` transfer-decoded as the draft fixture records it. */
459
+ const draftTextPart = (partId, type, content) => ({
460
+ partId,
461
+ mimeType: `text/${type}`,
462
+ filename: "",
463
+ headers: [{
464
+ name: "Content-Type",
465
+ value: `text/${type}; charset=UTF-8`
466
+ }, {
467
+ name: "Content-Transfer-Encoding",
468
+ value: "quoted-printable"
469
+ }],
470
+ body: {
471
+ size: new TextEncoder().encode(content).byteLength,
472
+ data: base64UrlOfText(content)
473
+ }
345
474
  });
346
475
  /** A draft message as the draft fixture records it (the metadata rendering only on compose). */
347
476
  const draftMessage = (id, threadId, content, withMetadata) => ({
@@ -353,11 +482,11 @@ const draftMessage = (id, threadId, content, withMetadata) => ({
353
482
  historyId: "900020",
354
483
  internalDate: recordedInternalDate,
355
484
  minimal: false,
356
- metadataPayload: withMetadata ? textPayload(content.subject, { size: 64 }) : null,
357
- fullPayload: textPayload(content.subject, {
358
- size: new TextEncoder().encode(content.body).byteLength,
359
- data: base64UrlOfText(content.body)
360
- })
485
+ metadataPayload: withMetadata ? draftPayload(content.subject) : null,
486
+ fullPayload: {
487
+ ...draftPayload(content.subject),
488
+ parts: [draftTextPart("0", "plain", content.body), draftTextPart("1", "html", `<div dir="ltr">${content.body}</div>`)]
489
+ }
361
490
  });
362
491
  const draftAnswer = (draftId, message) => googleJson(200, {
363
492
  id: draftId,
@@ -439,20 +568,31 @@ const deleteDraft = statefulRoute(gmail("DELETE", "/drafts/{draftId}", true, [dr
439
568
  return googleNoContent();
440
569
  };
441
570
  });
442
- const getThread = statefulRoute(gmail("GET", "/threads/{threadId}", false, [draftCase], ["threadId"]), "none", (request) => {
443
- const query = exactQuery(request, ["format"]);
444
- if (isNotEmulated(query)) return query;
445
- return recordedValue(query, "format", "full") ?? param(request, "threadId");
446
- }, (state, threadId) => {
447
- const messages = state.messages.filter((message) => message.threadId === threadId);
571
+ const getThread = statefulRoute(gmail("GET", "/threads/{threadId}", false, [draftCase, metadataHeadersCase], ["threadId"]), "none", (request) => {
572
+ const read = readFormat(request);
573
+ if (isNotEmulated(read)) return read;
574
+ if (read.format === "minimal" || read.format === "metadata" !== (read.metadataHeaders !== void 0)) return notEmulated("a thread read other than format=full, or format=metadata with metadataHeaders, is not emulated");
575
+ return {
576
+ threadId: param(request, "threadId"),
577
+ ...read
578
+ };
579
+ }, (state, input, { env }) => {
580
+ const messages = state.messages.filter((message) => message.threadId === input.threadId);
581
+ if (state.impliedMessages.some((message) => message.threadId === input.threadId)) return notEmulated("a thread holding a message a fixture only names is not emulated");
448
582
  const createdDrafts = messages.every((message) => isDraftMessage(message) && mintedMessageIdPattern.test(message.id));
449
- if (messages.length === 0 || !createdDrafts) return notEmulated("a thread other than a draft thread created here is not emulated");
450
- const rendered = messages.map((message) => renderMessage(message, "full"));
451
- if (rendered.some((item) => item === void 0)) return notEmulated("a thread with a message without a full rendering is not emulated");
583
+ if (!(messages.length > 0 && (input.format === "full" ? createdDrafts : !messages.some(isDraftMessage)))) return notEmulated(input.format === "full" ? "a thread other than a draft thread created here is not emulated" : "a metadata read of a thread holding a draft is not emulated");
584
+ const rendered = [];
585
+ for (const message of messages) {
586
+ const rendering = renderMessage(message, input.format);
587
+ if (rendering === void 0) return notEmulated(`a thread with a message without a ${input.format} rendering is not emulated`);
588
+ const selected = selectHeaders(rendering, input.metadataHeaders, env.drills.metadataHeadersIgnored);
589
+ if (isNotEmulated(selected)) return selected;
590
+ rendered.push(selected);
591
+ }
452
592
  return answer(() => googleJson(200, {
453
- id: threadId,
593
+ id: input.threadId,
454
594
  historyId: messages.at(-1)?.historyId ?? "",
455
- messages: rendered.flatMap((item) => item === void 0 ? [] : [item])
595
+ messages: rendered
456
596
  }));
457
597
  });
458
598
  const boundaryPattern = /^[A-Za-z0-9_]{1,70}$/;
@@ -571,6 +711,7 @@ const sendMessage = statefulRoute(evidence(googleEmulatorGmailOrigin, "POST", "/
571
711
  /** The Gmail routes, in manifest order. */
572
712
  const gmailRoutes = [
573
713
  listMessages,
714
+ listThreads,
574
715
  getMessage,
575
716
  getAttachment,
576
717
  modifyMessage,